Search is not available for this dataset
text string | meta dict |
|---|---|
/* multimin/gsl_multimin.h
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000 Fabrice Rossi
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
/* Modified by Tuomo Keskitalo to include fminimizer and
Nelder Mead related lines */
#ifndef __GSL_MULTIMIN_H__
#define __GSL_MULTIMIN_H__
#if !defined( GSL_FUN )
# if !defined( GSL_DLL )
# define GSL_FUN extern
# elif defined( BUILD_GSL_DLL )
# define GSL_FUN extern __declspec(dllexport)
# else
# define GSL_FUN extern __declspec(dllimport)
# endif
#endif
#include <stdlib.h>
#include <gsl/gsl_types.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_min.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
/* Definition of an arbitrary real-valued function with gsl_vector input and */
/* parameters */
struct gsl_multimin_function_struct
{
double (* f) (const gsl_vector * x, void * params);
size_t n;
void * params;
};
typedef struct gsl_multimin_function_struct gsl_multimin_function;
#define GSL_MULTIMIN_FN_EVAL(F,x) (*((F)->f))(x,(F)->params)
/* Definition of an arbitrary differentiable real-valued function */
/* with gsl_vector input and parameters */
struct gsl_multimin_function_fdf_struct
{
double (* f) (const gsl_vector * x, void * params);
void (* df) (const gsl_vector * x, void * params,gsl_vector * df);
void (* fdf) (const gsl_vector * x, void * params,double *f,gsl_vector * df);
size_t n;
void * params;
};
typedef struct gsl_multimin_function_fdf_struct gsl_multimin_function_fdf;
#define GSL_MULTIMIN_FN_EVAL_F(F,x) (*((F)->f))(x,(F)->params)
#define GSL_MULTIMIN_FN_EVAL_DF(F,x,g) (*((F)->df))(x,(F)->params,(g))
#define GSL_MULTIMIN_FN_EVAL_F_DF(F,x,y,g) (*((F)->fdf))(x,(F)->params,(y),(g))
GSL_FUN int gsl_multimin_diff (const gsl_multimin_function * f,
const gsl_vector * x, gsl_vector * g);
/* minimization of non-differentiable functions */
typedef struct
{
const char *name;
size_t size;
int (*alloc) (void *state, size_t n);
int (*set) (void *state, gsl_multimin_function * f,
const gsl_vector * x,
double * size,
const gsl_vector * step_size);
int (*iterate) (void *state, gsl_multimin_function * f,
gsl_vector * x,
double * size,
double * fval);
void (*free) (void *state);
}
gsl_multimin_fminimizer_type;
typedef struct
{
/* multi dimensional part */
const gsl_multimin_fminimizer_type *type;
gsl_multimin_function *f;
double fval;
gsl_vector * x;
double size;
void *state;
}
gsl_multimin_fminimizer;
GSL_FUN gsl_multimin_fminimizer *
gsl_multimin_fminimizer_alloc(const gsl_multimin_fminimizer_type *T,
size_t n);
GSL_FUN int
gsl_multimin_fminimizer_set (gsl_multimin_fminimizer * s,
gsl_multimin_function * f,
const gsl_vector * x,
const gsl_vector * step_size);
GSL_FUN void
gsl_multimin_fminimizer_free(gsl_multimin_fminimizer *s);
GSL_FUN const char *
gsl_multimin_fminimizer_name (const gsl_multimin_fminimizer * s);
GSL_FUN int
gsl_multimin_fminimizer_iterate(gsl_multimin_fminimizer *s);
GSL_FUN gsl_vector *
gsl_multimin_fminimizer_x (const gsl_multimin_fminimizer * s);
GSL_FUN double
gsl_multimin_fminimizer_minimum (const gsl_multimin_fminimizer * s);
GSL_FUN double
gsl_multimin_fminimizer_size (const gsl_multimin_fminimizer * s);
/* Convergence test functions */
GSL_FUN int
gsl_multimin_test_gradient(const gsl_vector * g,double epsabs);
GSL_FUN int
gsl_multimin_test_size(const double size ,double epsabs);
/* minimisation of differentiable functions */
typedef struct
{
const char *name;
size_t size;
int (*alloc) (void *state, size_t n);
int (*set) (void *state, gsl_multimin_function_fdf * fdf,
const gsl_vector * x, double * f,
gsl_vector * gradient, double step_size, double tol);
int (*iterate) (void *state,gsl_multimin_function_fdf * fdf,
gsl_vector * x, double * f,
gsl_vector * gradient, gsl_vector * dx);
int (*restart) (void *state);
void (*free) (void *state);
}
gsl_multimin_fdfminimizer_type;
typedef struct
{
/* multi dimensional part */
const gsl_multimin_fdfminimizer_type *type;
gsl_multimin_function_fdf *fdf;
double f;
gsl_vector * x;
gsl_vector * gradient;
gsl_vector * dx;
void *state;
}
gsl_multimin_fdfminimizer;
GSL_FUN gsl_multimin_fdfminimizer *
gsl_multimin_fdfminimizer_alloc(const gsl_multimin_fdfminimizer_type *T,
size_t n);
GSL_FUN int
gsl_multimin_fdfminimizer_set (gsl_multimin_fdfminimizer * s,
gsl_multimin_function_fdf *fdf,
const gsl_vector * x,
double step_size, double tol);
GSL_FUN void
gsl_multimin_fdfminimizer_free(gsl_multimin_fdfminimizer *s);
GSL_FUN const char *
gsl_multimin_fdfminimizer_name (const gsl_multimin_fdfminimizer * s);
GSL_FUN int
gsl_multimin_fdfminimizer_iterate(gsl_multimin_fdfminimizer *s);
GSL_FUN int
gsl_multimin_fdfminimizer_restart(gsl_multimin_fdfminimizer *s);
GSL_FUN gsl_vector *
gsl_multimin_fdfminimizer_x (const gsl_multimin_fdfminimizer * s);
GSL_FUN gsl_vector *
gsl_multimin_fdfminimizer_dx (const gsl_multimin_fdfminimizer * s);
GSL_FUN gsl_vector *
gsl_multimin_fdfminimizer_gradient (const gsl_multimin_fdfminimizer * s);
GSL_FUN double
gsl_multimin_fdfminimizer_minimum (const gsl_multimin_fdfminimizer * s);
GSL_VAR const gsl_multimin_fdfminimizer_type *gsl_multimin_fdfminimizer_steepest_descent;
GSL_VAR const gsl_multimin_fdfminimizer_type *gsl_multimin_fdfminimizer_conjugate_pr;
GSL_VAR const gsl_multimin_fdfminimizer_type *gsl_multimin_fdfminimizer_conjugate_fr;
GSL_VAR const gsl_multimin_fdfminimizer_type *gsl_multimin_fdfminimizer_vector_bfgs;
GSL_VAR const gsl_multimin_fdfminimizer_type *gsl_multimin_fdfminimizer_vector_bfgs2;
GSL_VAR const gsl_multimin_fminimizer_type *gsl_multimin_fminimizer_nmsimplex;
GSL_VAR const gsl_multimin_fminimizer_type *gsl_multimin_fminimizer_nmsimplex2;
__END_DECLS
#endif /* __GSL_MULTIMIN_H__ */
| {
"alphanum_fraction": 0.7051456575,
"avg_line_length": 31.1271186441,
"ext": "h",
"hexsha": "2cb4bf3a31e465faaf50922854f22cb236916288",
"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_multimin.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_multimin.h",
"max_line_length": 90,
"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_multimin.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1919,
"size": 7346
} |
/*
* File: BlshIndex.h
* Author: chteflio
*
* Created on March 4, 2016, 3:19 PM
*/
#ifndef BLSHINDEX_H
#define BLSHINDEX_H
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
#include <gsl/gsl_sf_gamma.h>
#include <gsl/gsl_sf_result.h>
#include <gsl/gsl_errno.h>
namespace mips {
class BlshIndex : public LshIndex {
int computeMinMatches(int nTrials) {
double p;
double epsilon = 1 - R;
int guess = nTrials / 2;
int start = 0;
int end = nTrials;
// std::cout<<"threshold: "<<threshold<<" epsilon: "<<epsilon<<std::endl;
int retValue = -1;
do {
p = 1.0 - posteriorCdf(guess, nTrials, minMathesT);
if (p > epsilon) {
if (start == end) {
retValue = start - 1;
break;
}
end = guess - 1;
if (end < start) {
retValue = guess - 1;
break;
}
} else if (p < epsilon) {
if (start == end) {
retValue = start;
break;
}
start = guess + 1;
if (start > end) {
retValue = guess;
break;
}
} else {
retValue = guess;
break;
}
guess = (start + end) / 2;
if (end < 0 || start > nTrials) {
std::cout << "Problem in computeMinMatches start " << start << " end " << end << std::endl;
exit(1);
}
} while (1);
if (retValue < 0)
retValue = 0;
else if (retValue > nTrials)
retValue = nTrials;
return retValue;
}
inline double posteriorCdf(double s, double n, double x) {
if (x >= 1.0)
return 1.0;
if (x <= 0.5)
return 0;
double b1 = 1.0;
double bHalf = boost::math::ibeta(s + 1, n - s + 1, 0.5);
double bx = boost::math::ibeta(s + 1, n - s + 1, x);
double den = b1 - bHalf;
if (den < 1.0e-15)
return exp(log(bx - bHalf) - log(den));
else
return (bx - bHalf) / den;
}
public:
double minMathesT; // threshold for matching, r = c2r(simT)
long long hashGroups = 0;
int32_t *minMatches; // minimum number of hashes that should be observed to meet simT
double R;
double worst;
BlshIndex() : LshIndex(), minMathesT(0), minMatches(nullptr) {
}
inline ~BlshIndex() {
if (minMatches != nullptr)
delete[] minMatches;
}
inline void allocateBayesLSHMemory(double worstCaseTheta) {
if (minMatches == nullptr) {
// set up cache space and pre-compute all minimum matches
minMatches = da_i32malloc(hashGroups, NULL); //"allocateBayesLSHMemory: minMatches"
// std::cout << "worstCaseTheta: " << worstCaseTheta << std::endl;
minMathesT = (1.0 - acos(worstCaseTheta) * INVPI); // min matches threshold
for (int i = 0; i < hashGroups; i++) {
minMatches[i] = computeMinMatches((i + 1) * 32);
// std::cout<<minMatches[i]<<" ";
}
// std::cout << std::endl;
}
}
inline void initializeLists(const VectorMatrix& matrix, double worstCaseTheta, bool forProbeVectors, double recall,
ta_size_type start = 0, ta_size_type end = 0) {
omp_set_lock(&writelock);
if (!initialized) {
R = recall;
end = (end == 0 ? matrix.rowNum : end);
row_type nVectors = end - start;
cosSketches = new CosineSketches(nVectors, LSH_CODE_LENGTH, LSH_SIGNATURES);
hashGroups = LSH_CODE_LENGTH * LSH_SIGNATURES / 32;
initializedSketches.resize(nVectors, 0);
cosSketches->alloc();
if (forProbeVectors) {
switch (LSH_CODE_LENGTH) {
case 8:
lshBins = new LshBinsDense();
break;
case 16:
lshBins = new LshBinsSparse<uint16_t>();
break;
case 24:
case 32:
lshBins = new LshBinsSparse<uint32_t>();
break;
default:
lshBins = new LshBinsSparse<uint64_t>();
break;
}
lshBins->init(cosSketches->bytesPerCode, cosSketches->numHashTables, cosSketches->nVectors);
}
if (worstCaseTheta < std::numeric_limits<double>::max()) {
if (worstCaseTheta > 0) {
worstCaseTheta /= matrix.getVectorLength(start);
worstCaseTheta = (worstCaseTheta > 1 ? 1 : worstCaseTheta); // it will break in the loop afterwards
} else {
worstCaseTheta /= matrix.getVectorLength(end - 1);
worstCaseTheta = (worstCaseTheta < -1 ? -1 : worstCaseTheta); // it will have to check everything
}
worst = worstCaseTheta;
allocateBayesLSHMemory(worstCaseTheta);
}
initialized = true;
}
omp_unset_lock(&writelock);
}
};
}
#endif /* BLSHINDEX_H */
| {
"alphanum_fraction": 0.4289418247,
"avg_line_length": 33.1774193548,
"ext": "h",
"hexsha": "9c8201dd2bb4f888075d84981bba49d3b7aa877a",
"lang": "C",
"max_forks_count": 9,
"max_forks_repo_forks_event_max_datetime": "2019-12-04T06:37:41.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-09-16T08:21:24.000Z",
"max_forks_repo_head_hexsha": "0279528b427aa4fae59e4d3598b1f098fcb4cf4b",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "d3v3l0/LEMP-benchmarking",
"max_forks_repo_path": "mips/structs/BlshIndex.h",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "0279528b427aa4fae59e4d3598b1f098fcb4cf4b",
"max_issues_repo_issues_event_max_datetime": "2021-12-16T03:30:55.000Z",
"max_issues_repo_issues_event_min_datetime": "2021-12-16T03:30:55.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "d3v3l0/LEMP-benchmarking",
"max_issues_repo_path": "mips/structs/BlshIndex.h",
"max_line_length": 130,
"max_stars_count": 7,
"max_stars_repo_head_hexsha": "e24ce821692aba8403ca8733382f53641f7f96d5",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "uma-pi1/LEMP",
"max_stars_repo_path": "mips/structs/BlshIndex.h",
"max_stars_repo_stars_event_max_datetime": "2020-11-16T17:34:42.000Z",
"max_stars_repo_stars_event_min_datetime": "2018-07-28T07:05:37.000Z",
"num_tokens": 1366,
"size": 6171
} |
#pragma once
#include "SimpleEvaluator.h"
#include "BooleanDAG.h"
#include "Interface.h"
#include "SuggestionGenerator.h"
#include "OptimizationWrapper.h"
#include "MaxOptimizationWrapper.h"
#include "BoolNodeSimplifier.h"
#include "NumDebugger.h"
#include <map>
#include <set>
#ifndef _NOGSL
#include <gsl/gsl_vector.h>
#else
#include "FakeGSL.h"
#endif
#include "BoolBasedSampler.h"
class SuggestionGeneratorUsingMax: public SuggestionGenerator {
Interface* interf;
BooleanDAG* dag;
map<string, int>& ctrls;
FloatManager& fm;
ActualEvaluators* actualEval;
SmoothEvaluators* smoothEval;
OptimizationWrapper* opt;
MaxOptimizationWrapper* maxOpt;
int minimizeNode;
set<int> assertConstraints;
vector<gsl_vector*> maxes;
gsl_vector* tmp;
int NUM_MAXES = 5;
NumDebugger* debugger;
const vector<vector<int>>& dependentInputs;
public:
vector<gsl_vector*> dirGrads;
SuggestionGeneratorUsingMax(BooleanDAG* _dag, FloatManager& _fm, Interface* _interface, map<string, int>& _ctrls, OptimizationWrapper* _opt, MaxOptimizationWrapper* _maxOpt, ActualEvaluators* _actualEval, SmoothEvaluators* _smoothEval, int ncontrols, const vector<vector<int>>& _dependentInputs, NumDebugger* _debugger): dag(_dag), fm(_fm), interf(_interface), ctrls(_ctrls), opt(_opt), maxOpt(_maxOpt), actualEval(_actualEval), smoothEval(_smoothEval), dependentInputs(_dependentInputs), debugger(_debugger) {
minimizeNode = -1;
for (int i = 0; i < dag->size(); i++) { // TODO: this should also be set by caller class
bool_node* n = (*dag)[i];
if (n->type == bool_node::ASSERT && ((ASSERT_node*)n)->isHard()) {
minimizeNode = i;
} else if (n->type == bool_node::ASSERT || Util::isSqrt(n)) {
assertConstraints.insert(i);
} else if (n->type == bool_node::CTRL && n->getOtype() == OutType::BOOL) {
assertConstraints.insert(i);
}
}
for (int i = 0; i < 20; i++) {
dirGrads.push_back(gsl_vector_alloc(ncontrols));
}
for (int i = 0; i < NUM_MAXES; i++) {
maxes.push_back(gsl_vector_alloc(ncontrols));
}
tmp = gsl_vector_alloc(ncontrols);
}
~SuggestionGeneratorUsingMax() {
for (int i = 0; i < dirGrads.size(); i++) {
gsl_vector_free(dirGrads[i]);
}
for (int i = 0; i < maxes.size(); i++) {
gsl_vector_free(maxes[i]);
}
gsl_vector_free(tmp);
}
pair<int, int> getSuggestion(const gsl_vector* state) {
actualEval->run(state);
vector<tuple<double, int, int>> s;
for (auto it = interf->varsMapping.begin(); it != interf->varsMapping.end(); it++) {
int nodeid = it->first;
if (interf->hasValue(nodeid)) continue;
bool_node* n = (*dag)[nodeid];
bool hasArraccChild = Util::hasArraccChild(n);
double dist = actualEval->dist(n->id);
double cost = abs(dist);
if (hasArraccChild && cost < 0.1) {
return make_pair(nodeid, dist >= 0.0);
}
if (hasArraccChild) {
cost = cost / 1000.0;
}
s.push_back(make_tuple(cost, nodeid, dist > 0));
}
cout << endl;
sort(s.begin(), s.end());
if (s.size() > 0) {
return make_pair(get<1>(s[0]), get<2>(s[1]));
} else {
Assert(false, "weqhqp");
return make_pair(-1, 0);
}
}
pair<int, int> getUnsatSuggestion(const gsl_vector* state) {
actualEval->run(state);
double dassert;
double d;
vector<tuple<int, int>> conflict;
for (auto it = assertConstraints.begin(); it != assertConstraints.end(); it++) {
//dassert = actualEval->getErrorOnConstraint(*it);
if (true) {
// TODO: this is currently hacky
const vector<int>& inputs = dependentInputs[*it];
int minid = -1;
double minerror = 1e30;
for (auto it1 = inputs.begin(); it1 != inputs.end(); it1++) {
if (interf->hasValue(*it1)) continue;
d = actualEval->dist(*it1);
//if (dassert < 0.0) {
cout << *it << " " << *it1 << " " << d << " " << Util::print(actualEval->grad(*it1)) << endl;
//}
if (d < minerror) {
minerror = d;
minid = *it1;
}
}
//Assert(minerror > 0.0, "something is wrong");
if (minid != -1) {
cout << "Min " << *it << " " << minid << " " << minerror << endl;
conflict.push_back(make_tuple(*it, minid));
}
if ((*dag)[*it]->mother()->type == bool_node::NOT && minerror >= 0.2) {
break;
}
}
}
sort(conflict.begin(), conflict.end());
reverse(conflict.begin(), conflict.end());
Assert(conflict.size() > 0, "No failed asserts???");
return make_pair(get<1>(conflict[0]), 1);
}
SClause* getUnsatClause(const gsl_vector* state, const gsl_vector* initState) {
actualEval->run(state);
double dassert;
double d;
vector<int> conflictingAsserts;
for (auto it = assertConstraints.begin(); it != assertConstraints.end(); it++) {
dassert = actualEval->getErrorOnConstraint(*it);
if ( (*dag)[*it]->mother()->type != bool_node::NOT) {
continue;
}
if (true) {
if (dassert < 0.01) {
conflictingAsserts.push_back(*it);
}
if (dassert < -0.2) {
break;
}
}
}
SClause* clause = new SClause();
actualEval->run(initState);
for (auto it = conflictingAsserts.begin(); it != conflictingAsserts.end(); it++) {
// TODO: this is currently hacky
const vector<int>& inputs = dependentInputs[*it];
int minid = -1;
double minerror = 1e30;
for (auto it1 = inputs.begin(); it1 != inputs.end(); it1++) {
d = actualEval->dist(*it1);
cout << *it << " " << *it1 << " " << d << " " << Util::print(actualEval->grad(*it1)) << endl;
if (d < minerror) {
minerror = d;
minid = *it1;
}
}
//Assert(minerror > 0.0, "something is wrong");
if (minid != -1 ) {
clause->add(*it, minid);
}
}
return clause;
}
SClause* getUnsatClause(const gsl_vector* state) {
actualEval->run(state);
double dassert;
double d;
SClause* clause = new SClause();
for (auto it = assertConstraints.begin(); it != assertConstraints.end(); it++) {
dassert = actualEval->getErrorOnConstraint(*it);
if (true) {
// TODO: this is currently hacky
const vector<int>& inputs = dependentInputs[*it];
int minid = -1;
double minerror = 1e30;
for (auto it1 = inputs.begin(); it1 != inputs.end(); it1++) {
d = actualEval->dist(*it1);
if (dassert < 0.0) {
cout << *it << " " << *it1 << " " << d << " " << Util::print(actualEval->grad(*it1)) << endl;
}
if (d < minerror) {
minerror = d;
minid = *it1;
}
}
//Assert(minerror > 0.0, "something is wrong");
if (minid != -1 && (*dag)[*it]->mother()->type == bool_node::NOT && minerror >= -0.01) {
clause->add(*it, minid);
}
if ((*dag)[*it]->mother()->type == bool_node::NOT && minerror >= 0.2) {
break;
}
}
}
return clause;
}
BooleanDAG* getNewDag(BooleanDAG* origDag, int origNid, const gsl_vector* s) {
BooleanDAG* newDag = origDag->clone();
SimpleGradEvaluator* seval = actualEval->getEvaluator(origDag);
seval->run(s);
BoolNodeSimplifier simplifier(*newDag, fm);
simplifier.process(*newDag, origNid, seval);
DagOptim cse(*newDag, fm);
cse.process(*newDag);
newDag->cleanup();
//newDag->lprint(cout);
return newDag;
}
Predicate* make_pure(Predicate* p, const gsl_vector* s) {
cout << "Making pure: " << p->print() << " at " << Util::print(s) << endl;
if (p->isBasic()) {
BasicPredicate* bp = (BasicPredicate*) p;
BooleanDAG* newDag = getNewDag(bp->dag, bp->nid, s);
// register newDag
actualEval->addEvaluator(newDag);
smoothEval->addEvaluator(newDag);
int cid = -1;
for (int i = newDag->size() - 1; i >= 0; i--) {
bool_node* n = (*newDag)[i];
if (n->type == bool_node::ASSERT) {
cid = n->mother()->id;
break;
}
}
Assert(cid != -1, "No assert in new dag");
return new BasicPredicate(newDag, cid, bp);
} else {
DiffPredicate* dp = (DiffPredicate*)p;
Predicate* new_p1;
Predicate* new_p2;
if (dp->p1->isPure()) {
new_p1 = dp->p1;
} else {
new_p1 = make_pure(dp->p1, s);
}
if (dp->p2->isPure()) {
new_p2 = dp->p2;
} else {
new_p2 = make_pure(dp->p2, s);
}
int ncontrols = ctrls.size();
if (ncontrols == 0) {
ncontrols = 1;
}
return new DiffPredicate(new_p1, new_p2, ncontrols);
}
}
int getDirectionsLevel0(const gsl_vector* state, double beta) {
GradUtil::BETA = beta;
GradUtil::ALPHA = -beta;
smoothEval->run(state);
vector<tuple<double, Predicate*, int>> s;
for (auto it = interf->levelPredicates[0].begin(); it != interf->levelPredicates[0].end(); it++) {
Predicate* p = *it;
double dist = smoothEval->dist(p);
double cost = abs(dist);
if (cost >= 0.1) {
s.push_back(make_tuple(cost, p, dist > 0));
}
}
sort(s.begin(), s.end());
cout << "Distances: " << endl;
int end = 5;
if (end > s.size()) {
end = s.size();
}
for (int i = 0; i < end; i++) {
cout << get<1>(s[i])->print() << " " << get<0>(s[i]) << " " << get<2>(s[i]) << endl;
}
int numDirs = 0;
for (int i = 0; i < end; i++) {
if (numDirs == 5) break;
double dist = get<0>(s[i]);
Predicate* p = get<1>(s[i]);
int val = !get<2>(s[i]);
if (dist < 0.1) continue;
smoothEval->getErrorOnPredicate(p, val, dirGrads[numDirs]);
cout << "G: " << Util::print(dirGrads[numDirs]) << endl;
bool newDir = true;
for (int j = 0; j < numDirs; j++) {
if (Util::sameDir(dirGrads[j], dirGrads[numDirs])) {
newDir = false;
cout << "Not a new dir" << endl;
break;
}
}
if (newDir) {
numDirs++;
}
}
Assert(numDirs > 0, "No dirs?");
return numDirs;
}
void updateState(gsl_vector* state, int idx, double dx) {
gsl_vector_set(state, idx, gsl_vector_get(state, idx) + dx);
}
void randomize(gsl_vector* tmp) {
for (int i = 0; i < tmp->size; i++) {
double r = -1.0 + (rand() % 20)/10.0;
gsl_vector_set(tmp, i, r);
}
}
int getMaxes(gsl_vector* state, double beta) {
int numMaxes = 0;
for (int i = 0; i < NUM_MAXES; i++) {
randomize(tmp);
gsl_vector_scale(tmp, 1.0/gsl_blas_dnrm2(tmp));
gsl_vector_add(state, tmp);
cout << Util::print(state) << endl;
maxOpt->maximize(interf, state, tmp, assertConstraints, minimizeNode, beta, -1, i);
gsl_vector_memcpy(maxes[i], maxOpt->getMinState());
gsl_vector_sub(state, tmp);
cout << Util::print(state) << endl;
numMaxes++;
}
return numMaxes;
}
vector<tuple<double, Predicate*, int>> getDistancesLevel0(const gsl_vector* state) {
actualEval->run(state);
vector<tuple<double, Predicate*, int>> s;
for (auto it = interf->levelPredicates[0].begin(); it != interf->levelPredicates[0].end(); it++) {
Predicate* p = *it;
double dist = actualEval->dist(p);
double cost = abs(dist);
s.push_back(make_tuple(cost, p, dist > 0));
}
sort(s.begin(), s.end());
cout << "Distances: " << endl;
int end = 5;
if (end > s.size()) {
end = s.size();
}
for (int i = 0; i < end; i++) {
cout << get<1>(s[i])->print() << " " << get<0>(s[i]) << " " << get<2>(s[i]) << endl;
}
return s;
}
int chooseBeta(LocalState* ls) {
double error1 = ls->errors[0];
double error2 = ls->errors[1];
double error3 = ls->errors[2];
cout << "Errors: " << error1 << " " << error2 << " " << error3 << endl;
if (error3 <= 0.0) {
Assert(false, "Zero error?");
}
if (error3 < 1.0 || error2 <= 0.01) {
return 2;
}
if (error2 < 5.0 || error1 <= 0.01) {
return 1;
} else {
return 0;
}
}
/*virtual IClause* getConflictClause(int level, LocalState* ls) {
Assert(level == -1, "Other levels is not yet supported");
int betaIdx = chooseBeta(ls);
double beta;
gsl_vector* state;
if (betaIdx == 0) {
beta = -1;
state = ls->localSols[0];
} else if (betaIdx == 1) {
beta = -10;
state = ls->localSols[1];
} else if (betaIdx == 2) {
beta = -50;
state = ls->localSols[2];
}
cout << "Choosing beta = " << beta << endl;
vector<tuple<double, Predicate*, int>> preds;
actualEval->run(state);
for (auto it = interf->levelPredicates[0].begin(); it != interf->levelPredicates[0].end(); it++) {
Predicate* p = *it;
cout << p->print() << " ";
double dist = actualEval->dist(p);
cout << dist << " ";
cout << Util::print(actualEval->grad(p)) << endl;
double cost = abs(dist);
double norm = actualEval->grad_norm(p);
if (norm < 0.01) continue;
if (cost/norm < 0.01) continue;
preds.push_back(make_tuple(cost/norm, p, dist >= 0));
}
sort(preds.begin(), preds.end());
int numPreds = min(20, preds.size());
IClause* c = new IClause(GradUtil::counter);
for (int i = 0; i < numPreds; i++) {
Predicate* p = get<1>(preds[i]);
cout << p->print() << " ";
if (!p->isPure()) {
p = make_pure(p, state);
}
c->add(p, !get<2>(preds[i]));
}
cout << endl;
if (c->size() == 0) {
Assert(false, "Empty clause?");
}
return c;
}*/
virtual IClause* getConflictClause(int level, LocalState* ls) {
int betaIdx = chooseBeta(ls);
double beta;
gsl_vector* state;
if (betaIdx == 0) {
beta = -1;
state = ls->localSols[0];
} else if (betaIdx == 1) {
beta = -10;
state = ls->localSols[1];
} else if (betaIdx == 2) {
beta = -50;
state = ls->localSols[2];
}
cout << "Choosing beta = " << beta << endl;
int numMaxes = getMaxes(state, beta);
cout << "Num maxes: " << numMaxes << endl;
map<int, vector<tuple<double, Predicate*, int>>> maxesToPredicates;
map<Predicate*, vector<tuple<double, int, int>>> predicatesToMaxes;
map<Predicate*, tuple<double, int>> lsPreds;
actualEval->run(state);
for (auto it = interf->levelPredicates[0].begin(); it != interf->levelPredicates[0].end(); it++) {
Predicate* p = *it;
double dist = actualEval->dist(p);
double cost = abs(dist);
double norm = actualEval->grad_norm(p);
if (norm < 0.01) {
cost = 1000.0;
} else {
cost = cost/norm;
}
lsPreds[p] = make_tuple(cost, dist >= 0);
}
for (int i = 0; i < numMaxes; i++) {
actualEval->run(maxes[i]);
vector<tuple<double, Predicate*, int>> preds;
for (auto it = interf->levelPredicates[0].begin(); it != interf->levelPredicates[0].end(); it++) {
Predicate* p = *it;
double dist = actualEval->dist(p);
double cost = abs(dist);
double norm = actualEval->grad_norm(p);
if (norm < 0.01) {
cost = 1000.0;
} else {
cost = cost/norm;
}
auto& lsTup = lsPreds[p];
bool same = false;
if (get<1>(lsTup) == (dist > 0)) {
same = true;
}
if (get<0>(lsTup) <= 0.1) {
same = true;
}
if (cost <= 0.1) {
same = true;
}
if (!same) {
preds.push_back(make_tuple(cost, p, dist >= 0));
if (predicatesToMaxes.find(p) == predicatesToMaxes.end()) {
vector<tuple<double, int, int>> maxstates;
predicatesToMaxes[p] = maxstates;
}
predicatesToMaxes[p].push_back(make_tuple(cost, i, dist>=0));
}
}
sort(preds.begin(), preds.end());
maxesToPredicates[i] = (preds);
}
set<int> selected;
IClause* c = new IClause(GradUtil::counter);
for (int i = 0; i < numMaxes; i++) {
if (selected.find(i) != selected.end()) continue;
auto& l = maxesToPredicates[i];
if (l.size() == 0) continue;
//Assert(l.size() != 0, "No preds to eliminate max");
auto& tup = l[0];
Predicate* p = get<1>(tup);
auto& m = predicatesToMaxes[p];
selected.insert(i);
for (int k = 0; k < m.size(); k++) {
selected.insert(get<1>(m[k]));
}
if (!p->isPure()) {
p = make_pure(p, state);
}
c->add(p, get<2>(tup));
}
if (c->size() == 0) {
Assert(false, "Empty clause?");
}
// add predicates that satisfy all maxes and the current local state
vector<tuple<double, Predicate*>> preds;
actualEval->run(state);
for (auto it = interf->levelPredicates[0].begin(); it != interf->levelPredicates[0].end(); it++) {
Predicate* p = *it;
auto& m = predicatesToMaxes[p];
if (m.size() != 0) {
continue;
}
double dist = actualEval->dist(p);
double cost = abs(dist);
double norm = actualEval->grad_norm(p);
if (norm < 0.01) continue;
preds.push_back(make_tuple(cost/norm, p));
}
sort(preds.begin(), preds.end());
int numDirs = 0;
vector<double> dists;
dists.resize(dirGrads.size());
for (int i = 0; i < preds.size(); i++) {
if (numDirs >= dirGrads.size()) break;
Predicate* p = get<1>(preds[i]);
dists[numDirs] = actualEval->dist(p);
gsl_vector_memcpy(dirGrads[numDirs], actualEval->grad(p));
bool newDir = true;
for (int j = 0; j < numDirs; j++) {
if (Util::sameDir(dirGrads[j], dirGrads[numDirs])) {
if (dists[j] * dists[numDirs] >= 0.0) {
newDir = false;
//cout << "Not a new dir" << endl;
break;
}
}
}
if (newDir) {
cout << "New dir from ls: " << p->print() << " " << actualEval->dist(p) << " " << Util::print(actualEval->grad(p)) << endl;
if (!p->isPure()) {
p = make_pure(p, state);
}
c->add(p, dists[numDirs] < 0);
numDirs++;
}
}
return c;
}
/*virtual IClause* getConflictClause(int level, LocalState* ls) {
gsl_vector* state = ls->localSols[2];
vector<tuple<double, Predicate*, int>> preds;
actualEval->run(state);
for (auto it = interf->levelPredicates[0].begin(); it != interf->levelPredicates[0].end(); it++) {
Predicate* p = *it;
double dist = actualEval->dist(p);
double cost = abs(dist);
double norm = actualEval->grad_norm(p);
if (norm < 0.01) continue;
if (cost/norm < 0.1) continue;
preds.push_back(make_tuple(cost/norm, p, dist >= 0));
}
int numPreds = min(5, preds.size());
IClause* c = new IClause(GradUtil::counter);
for (int i = 0; i < numPreds; i++) {
int ridx = rand() % preds.size();
Predicate* p = get<1>(preds[ridx]);
cout << p->print() << " " << actualEval->dist(p) << " " << Util::print(actualEval->grad(p)) << endl;
if (!p->isPure()) {
p = make_pure(p, state);
}
c->add(p, !get<2>(preds[ridx]));
}
if (c->size() == 0) {
Assert(false, "Empty clause?");
}
return c;
}*/
/*virtual IClause* getConflictClause(int level, LocalState * ls) {
Assert(level == -1, "Other levels is not yet supported");
int betaIdx = chooseBeta(ls);
double beta;
gsl_vector* state;
if (betaIdx == 0) {
beta = -1;
state = ls->localSols[0];
} else if (betaIdx == 1) {
beta = -10;
state = ls->localSols[1];
} else if (betaIdx == 2) {
beta = -50;
state = ls->localSols[2];
}
cout << "Choosing beta = " << beta << endl;
int numMaxes = getMaxes(state, beta);
cout << "Num maxes: " << numMaxes << endl;
// collect close preds
set<Predicate*> close_preds;
vector<tuple<double, Predicate*>> preds;
actualEval->run(state);
for (auto it = interf->levelPredicates[0].begin(); it != interf->levelPredicates[0].end(); it++) {
Predicate* p = *it;
double dist = actualEval->dist(p);
double cost = abs(dist);
double norm = actualEval->grad_norm(p);
if (norm < 0.01) continue;
preds.push_back(make_tuple(cost/norm, p));
}
sort(preds.begin(), preds.end());
int numDirs = 0;
vector<double> dists;
dists.resize(dirGrads.size());
for (int i = 0; i < preds.size(); i++) {
if (numDirs >= dirGrads.size()) break;
Predicate* p = get<1>(preds[i]);
dists[numDirs] = actualEval->dist(p);
gsl_vector_memcpy(dirGrads[numDirs], actualEval->grad(p));
bool newDir = true;
for (int j = 0; j < numDirs; j++) {
if (Util::sameDir(dirGrads[j], dirGrads[numDirs])) {
if (dists[j] * dists[numDirs] >= 0.0) {
newDir = false;
//cout << "Not a new dir" << endl;
break;
}
}
}
if (newDir) {
cout << "New dir from ls: " << p->print() << " " << actualEval->dist(p) << " " << Util::print(actualEval->grad(p)) << endl;
numDirs++;
if (p->isPure()) {
close_preds.insert(p);
} else {
p = make_pure(p, state);
close_preds.insert(p);
}
}
}
for (int k = 0; k < numMaxes; k++) {
preds.clear();
actualEval->run(maxes[k]);
for (auto it = interf->levelPredicates[0].begin(); it != interf->levelPredicates[0].end(); it++) {
Predicate* p = *it;
double dist = actualEval->dist(p);
double cost = abs(dist);
double norm = actualEval->grad_norm(p);
if (norm < 0.01) continue;
preds.push_back(make_tuple(cost/norm, p));
}
sort(preds.begin(), preds.end());
int numDirs = 0;
for (int i = 0; i < preds.size(); i++) {
if (numDirs >= 20) break;
Predicate* p = get<1>(preds[i]);
dists[numDirs] = actualEval->dist(p);
gsl_vector_memcpy(dirGrads[numDirs], actualEval->grad(p));
bool newDir = true;
for (int j = 0; j < numDirs; j++) {
if (Util::sameDir(dirGrads[j], dirGrads[numDirs])) {
if (dists[j] * dists[numDirs] >= 0.0) {
newDir = false;
//cout << "Not a new dir" << endl;
break;
}
}
}
if (newDir) {
cout << "New dir from max: " << p->print() << " " << actualEval->dist(p) << " " << Util::print(actualEval->grad(p)) << endl;
numDirs++;
if (p->isPure()) {
close_preds.insert(p);
} else {
p = make_pure(p, maxes[k]);
close_preds.insert(p);
}
}
}
}
// collect common conditions satisfied by state, maxes
map<Predicate*, vector<tuple<double, int>>> common_preds;
actualEval->run(state);
for (auto it = close_preds.begin(); it != close_preds.end(); it++) {
Predicate* p = *it;
cout << "P: " << p->print() << " ";
double dist = actualEval->dist(p);
cout << dist << " ";
cout << Util::print(actualEval->grad(p)) << endl;
double cost = abs(dist);
int val = dist >= 0;
vector<tuple<double, int>> costValPairs;
costValPairs.push_back(make_tuple(cost, val));
common_preds[p] = costValPairs;
}
for (int i = 0; i < numMaxes; i++) {
actualEval->run(maxes[i]);
for (auto it = close_preds.begin(); it != close_preds.end(); it++) {
Predicate* p = *it;
double dist = actualEval->dist(p);
double cost = abs(dist);
int val = dist >= 0;
common_preds[p].push_back(make_tuple(cost, val));
}
}
vector<tuple<double, Predicate*, int>> ss;
for (auto it = common_preds.begin(); it != common_preds.end(); it++) {
Predicate* p = it->first;
vector<tuple<double, int>>& pairs = common_preds[p];
int val = -1;
double cost = 1e10;
cout << "Predicate " << p->print() << " " ;
for (int i = 0; i < pairs.size(); i++) {
auto& tup = pairs[i];
double tcost = get<0>(tup);
double tval = get<1>(tup);
cout << "(" << tval << "," << tcost << ")" << " ";
if (tcost < cost) {
cost = tcost;
}
if (tcost > 0.01) {
if (val == -1) {
val = tval;
} else if (val != tval) {
val = -2;
break;
}
}
}
cout << "Final: " << val << "," << cost << endl;
if (val == 0 || val == 1) {
ss.push_back(make_tuple(cost, p, val));
}
}
sort(ss.begin(), ss.end());
cout << "Num common preds: " << ss.size() << endl;
int numPreds = min(20, ss.size());
IClause* c = new IClause(GradUtil::counter);
for (int i = 0; i < numPreds; i++) {
c->add(get<1>(ss[i]), !get<2>(ss[i]));
}
if (c->size() == 0) {
Assert(false, "Empty clause?");
}
return c;
}*/
};
| {
"alphanum_fraction": 0.4512815365,
"avg_line_length": 35.0363423212,
"ext": "h",
"hexsha": "46803609ae8bb34856a60f1a8ec9e16cc0cbd5a0",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2020-12-06T01:45:04.000Z",
"max_forks_repo_forks_event_min_datetime": "2020-12-04T20:47:51.000Z",
"max_forks_repo_head_hexsha": "6ecbb6f724149d50d290997fef5e2e1e92ab3d9e",
"max_forks_repo_licenses": [
"X11"
],
"max_forks_repo_name": "natebragg/sketch-backend",
"max_forks_repo_path": "src/SketchSolver/NumericalSynthesis/SuggestionGenerators/SuggestionGeneratorUsingMax.h",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "6ecbb6f724149d50d290997fef5e2e1e92ab3d9e",
"max_issues_repo_issues_event_max_datetime": "2022-03-04T04:02:09.000Z",
"max_issues_repo_issues_event_min_datetime": "2022-03-01T16:53:05.000Z",
"max_issues_repo_licenses": [
"X11"
],
"max_issues_repo_name": "natebragg/sketch-backend",
"max_issues_repo_path": "src/SketchSolver/NumericalSynthesis/SuggestionGenerators/SuggestionGeneratorUsingMax.h",
"max_line_length": 514,
"max_stars_count": 17,
"max_stars_repo_head_hexsha": "6ecbb6f724149d50d290997fef5e2e1e92ab3d9e",
"max_stars_repo_licenses": [
"X11"
],
"max_stars_repo_name": "natebragg/sketch-backend",
"max_stars_repo_path": "src/SketchSolver/NumericalSynthesis/SuggestionGenerators/SuggestionGeneratorUsingMax.h",
"max_stars_repo_stars_event_max_datetime": "2022-03-31T00:28:40.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-08-20T14:54:11.000Z",
"num_tokens": 7475,
"size": 29886
} |
#include <math.h>
#include <string.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
extern void getSeries(int dataPoints, double dt, int nComps, int nTypes, int* epsilon, int capacity, int* curState, int rng_seed, int* output);
| {
"alphanum_fraction": 0.7426160338,
"avg_line_length": 33.8571428571,
"ext": "h",
"hexsha": "cf2730c4a1f97f6b86cf99a5acf124e2bb193ae5",
"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": "f436424036c84e28ca6cb871517e2da5de923b88",
"max_forks_repo_licenses": [
"Unlicense"
],
"max_forks_repo_name": "akononovicius/compartmental-voter-model",
"max_forks_repo_path": "model/model.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "f436424036c84e28ca6cb871517e2da5de923b88",
"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": "akononovicius/compartmental-voter-model",
"max_issues_repo_path": "model/model.h",
"max_line_length": 143,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "f436424036c84e28ca6cb871517e2da5de923b88",
"max_stars_repo_licenses": [
"Unlicense"
],
"max_stars_repo_name": "akononovicius/compartmental-voter-model",
"max_stars_repo_path": "model/model.h",
"max_stars_repo_stars_event_max_datetime": "2021-05-15T06:50:50.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-05-15T06:50:50.000Z",
"num_tokens": 69,
"size": 237
} |
/* linalg/sytd.c
*
* Copyright (C) 2001, 2007 Brian Gough
* Copyright (C) 2019 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.
*/
/* Factorise a symmetric matrix A into
*
* A = Q T Q'
*
* where Q is orthogonal and T is symmetric tridiagonal. Only the
* diagonal and lower triangular part of A is referenced and modified.
*
* On exit, T is stored in the diagonal and first subdiagonal of
* A. Since T is symmetric the upper diagonal is not stored.
*
* Q is stored as a packed set of Householder transformations in the
* lower triangular part of the input matrix below the first subdiagonal.
*
* The full matrix for Q can be obtained as the product
*
* Q = Q_1 Q_2 ... Q_(N-2)
*
* where
*
* Q_i = (I - tau_i * v_i * v_i')
*
* and where v_i is a Householder vector
*
* v_i = [0, ... , 0, 1, A(i+1,i), A(i+2,i), ... , A(N,i)]
*
* This storage scheme is the same as in LAPACK. See LAPACK's
* ssytd2.f for details.
*
* See Golub & Van Loan, "Matrix Computations" (3rd ed), Section 8.3
*
* Note: this description uses 1-based indices. The code below uses
* 0-based indices
*/
#include <config.h>
#include <stdlib.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>
int
gsl_linalg_symmtd_decomp (gsl_matrix * A, gsl_vector * tau)
{
if (A->size1 != A->size2)
{
GSL_ERROR ("symmetric tridiagonal decomposition requires square matrix",
GSL_ENOTSQR);
}
else if (tau->size + 1 != A->size1)
{
GSL_ERROR ("size of tau must be N-1", GSL_EBADLEN);
}
else
{
const size_t N = A->size1;
size_t i;
for (i = 0 ; i < N - 2; i++)
{
gsl_vector_view v = gsl_matrix_subcolumn (A, i, i + 1, N - i - 1);
double tau_i = gsl_linalg_householder_transform (&v.vector);
/* Apply the transformation H^T A H to the remaining columns */
if (tau_i != 0.0)
{
gsl_matrix_view m = gsl_matrix_submatrix (A, i + 1, i + 1, N - i - 1, N - i - 1);
double ei = gsl_vector_get(&v.vector, 0);
gsl_vector_view x = gsl_vector_subvector (tau, i, N - i - 1);
gsl_vector_set (&v.vector, 0, 1.0);
/* x = tau * A * v */
gsl_blas_dsymv (CblasLower, tau_i, &m.matrix, &v.vector, 0.0, &x.vector);
/* w = x - (1/2) tau * (x' * v) * v */
{
double xv, alpha;
gsl_blas_ddot(&x.vector, &v.vector, &xv);
alpha = -0.5 * tau_i * xv;
gsl_blas_daxpy(alpha, &v.vector, &x.vector);
}
/* apply the transformation A = A - v w' - w v' */
gsl_blas_dsyr2(CblasLower, -1.0, &v.vector, &x.vector, &m.matrix);
gsl_vector_set (&v.vector, 0, ei);
}
gsl_vector_set (tau, i, tau_i);
}
return GSL_SUCCESS;
}
}
/* Form the orthogonal matrix Q from the packed QR matrix */
int
gsl_linalg_symmtd_unpack (const gsl_matrix * A,
const gsl_vector * tau,
gsl_matrix * Q,
gsl_vector * diag,
gsl_vector * sdiag)
{
if (A->size1 != A->size2)
{
GSL_ERROR ("matrix A must be square", GSL_ENOTSQR);
}
else if (tau->size + 1 != A->size1)
{
GSL_ERROR ("size of tau must be (matrix size - 1)", GSL_EBADLEN);
}
else if (Q->size1 != A->size1 || Q->size2 != A->size1)
{
GSL_ERROR ("size of Q must match size of A", GSL_EBADLEN);
}
else if (diag->size != A->size1)
{
GSL_ERROR ("size of diagonal must match size of A", GSL_EBADLEN);
}
else if (sdiag->size + 1 != A->size1)
{
GSL_ERROR ("size of subdiagonal must be (matrix size - 1)", GSL_EBADLEN);
}
else
{
const size_t N = A->size1;
gsl_vector_const_view d = gsl_matrix_const_diagonal(A);;
gsl_vector_const_view sd = gsl_matrix_const_subdiagonal(A, 1);;
size_t i;
/* Initialize Q to the identity */
gsl_matrix_set_identity (Q);
for (i = N - 2; i-- > 0;)
{
gsl_vector_const_view h = gsl_matrix_const_subcolumn (A, i, i + 1, N - i - 1);
double ti = gsl_vector_get (tau, i);
gsl_matrix_view m = gsl_matrix_submatrix (Q, i + 1, i + 1, N - i - 1, N - i - 1);
gsl_vector_view work = gsl_vector_subvector(diag, 0, N - i - 1);
gsl_linalg_householder_left (ti, &h.vector, &m.matrix, &work.vector);
}
/* copy diagonal into diag */
gsl_vector_memcpy(diag, &d.vector);
/* copy subdiagonal into sd */
gsl_vector_memcpy(sdiag, &sd.vector);
return GSL_SUCCESS;
}
}
int
gsl_linalg_symmtd_unpack_T (const gsl_matrix * A,
gsl_vector * diag,
gsl_vector * sdiag)
{
if (A->size1 != A->size2)
{
GSL_ERROR ("matrix A must be square", GSL_ENOTSQR);
}
else if (diag->size != A->size1)
{
GSL_ERROR ("size of diagonal must match size of A", GSL_EBADLEN);
}
else if (sdiag->size + 1 != A->size1)
{
GSL_ERROR ("size of subdiagonal must be (matrix size - 1)", GSL_EBADLEN);
}
else
{
const size_t N = A->size1;
gsl_vector_const_view d = gsl_matrix_const_diagonal(A);;
gsl_vector_const_view sd = gsl_matrix_const_subdiagonal(A, 1);;
/* copy diagonal into diag */
gsl_vector_memcpy(diag, &d.vector);
/* copy subdiagonal into sd */
gsl_vector_memcpy(sdiag, &sd.vector);
return GSL_SUCCESS;
}
}
| {
"alphanum_fraction": 0.5789473684,
"avg_line_length": 30.2394366197,
"ext": "c",
"hexsha": "b10d4db57d505bdb83c788e5225c53de6f407272",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "83fd1fc4cbd053a4f9b673d5cd5841823ddd4d8b",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "karanbirsandhu/nu-sense",
"max_forks_repo_path": "test/lib/gsl-2.6/linalg/symmtd.c",
"max_issues_count": 6,
"max_issues_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a",
"max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z",
"max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "ielomariala/Hex-Game",
"max_issues_repo_path": "gsl-2.6/linalg/symmtd.c",
"max_line_length": 95,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "ielomariala/Hex-Game",
"max_stars_repo_path": "gsl-2.6/linalg/symmtd.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1822,
"size": 6441
} |
/**
* This file is part of the "libterminal" project
* Copyright (c) 2019-2020 Christian Parpart <christian@parpart.family>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <terminal/Color.h>
#include <terminal/RenderBuffer.h>
#include <terminal/Screen.h>
#include <terminal_renderer/BoxDrawingRenderer.h>
#include <terminal_renderer/FontDescriptions.h>
#include <terminal_renderer/RenderTarget.h>
#include <terminal_renderer/TextureAtlas.h>
#include <text_shaper/font.h>
#include <text_shaper/shaper.h>
#include <crispy/FNV.h>
#include <crispy/LRUCache.h>
#include <crispy/point.h>
#include <crispy/size.h>
#include <unicode/convert.h>
#include <unicode/run_segmenter.h>
#include <gsl/span>
#include <gsl/span_ext>
#include <functional>
#include <list>
#include <memory>
#include <unordered_map>
#include <vector>
namespace terminal::renderer
{
std::unique_ptr<text::font_locator> createFontLocator(FontLocatorEngine _engine);
struct FontKeys
{
text::font_key regular;
text::font_key bold;
text::font_key italic;
text::font_key boldItalic;
text::font_key emoji;
};
/// Text Rendering Pipeline
class TextRenderer: public Renderable
{
public:
TextRenderer(GridMetrics const& gridMetrics,
text::shaper& textShaper,
FontDescriptions& fontDescriptions,
FontKeys const& fontKeys);
void setRenderTarget(RenderTarget& renderTarget, DirectMappingAllocator& directMappingAllocator) override;
void setTextureAtlas(TextureAtlas& atlas) override;
void inspect(std::ostream& _textOutput) const override;
void clearCache() override;
void updateFontMetrics();
void setPressure(bool _pressure) noexcept { pressure_ = _pressure; }
/// Must be invoked before a new terminal frame is rendered.
void beginFrame();
/// Renders a given terminal's grid cell that has been
/// transformed into a RenderCell.
void renderCell(RenderCell const& _cell);
/// Must be invoked when rendering the terminal's text has finished for this frame.
void endFrame();
private:
void initializeDirectMapping();
/// Puts a sequence of codepoints that belong to the same grid cell at @p _pos
/// at the end of the currently filled line.
void appendCellTextToClusterGroup(std::u32string const& _codepoints, TextStyle _style, RGBColor _color);
/// Gets the text shaping result of the current text cluster group
text::shape_result const& getOrCreateCachedGlyphPositions(crispy::StrongHash hash);
text::shape_result createTextShapedGlyphPositions();
text::shape_result shapeTextRun(unicode::run_segmenter::range const& _run);
void flushTextClusterGroup();
AtlasTileAttributes const* getOrCreateRasterizedMetadata(crispy::StrongHash const& hash,
text::glyph_key const& glyphKey,
unicode::PresentationStyle presentationStyle);
/**
* Creates (and rasterizes) a single glyph and returns its
* render tile attributes required for the render step.
*/
std::optional<TextureAtlas::TileCreateData> createSlicedRasterizedGlyph(
atlas::TileLocation tileLocation,
text::glyph_key const& id,
unicode::PresentationStyle presentation,
crispy::StrongHash const& hash);
std::optional<TextureAtlas::TileCreateData> createRasterizedGlyph(
atlas::TileLocation tileLocation, text::glyph_key const& id, unicode::PresentationStyle presentation);
crispy::Point applyGlyphPositionToPen(crispy::Point pen,
AtlasTileAttributes const& tileAttributes,
text::glyph_position const& gpos) const noexcept;
void renderRasterizedGlyph(crispy::Point targetSurfacePosition,
RGBAColor glyphColor,
AtlasTileAttributes const& attributes);
// general properties
//
FontDescriptions& fontDescriptions_;
FontKeys const& fonts_;
// performance optimizations
//
bool pressure_ = false;
using ShapingResultCache = crispy::StrongLRUHashtable<text::shape_result>;
using ShapingResultCachePtr = ShapingResultCache::Ptr;
ShapingResultCachePtr textShapingCache_;
// TODO: make unique_ptr, get owned, export cref for other users in Renderer impl.
text::shaper& textShaper_;
DirectMapping _directMapping {};
// Maps from glyph index to tile index.
std::vector<uint32_t> _directMappedGlyphKeyToTileIndex {};
bool isGlyphDirectMapped(text::glyph_key const& glyph) const noexcept
{
return _directMapping // Is direct mapping enabled?
&& glyph.font == fonts_.regular // Only regular font is direct-mapped for now.
&& glyph.index.value < _directMappedGlyphKeyToTileIndex.size()
&& _directMappedGlyphKeyToTileIndex[glyph.index.value] != 0;
}
// sub-renderer
//
BoxDrawingRenderer boxDrawingRenderer_;
// work-data for the current text cluster group
struct TextClusterGroup
{
// pen-start position of this text group
crispy::Point initialPenPosition {};
// uniform text style for this text group
TextStyle style = TextStyle::Invalid;
// uniform text color for this text group
RGBColor color {};
// codepoints within this text group with
// uniform unicode properties (script, language, direction).
std::vector<char32_t> codepoints;
// cluster indices for each codepoint
std::vector<unsigned> clusters;
// number of grid cells processed
int cellCount = 0; // FIXME: EA width vs actual cells
void resetAndMovePenForward(int penIncrementInX)
{
codepoints.clear();
clusters.clear();
cellCount = 0;
initialPenPosition.x += penIncrementInX;
}
};
TextClusterGroup textClusterGroup_ {};
bool textStartFound_ = false;
bool forceCellGroupSplit_ = false;
};
} // namespace terminal::renderer
| {
"alphanum_fraction": 0.6855677877,
"avg_line_length": 33.6598984772,
"ext": "h",
"hexsha": "53803f6217897780a7906e41ba5113de7b3be934",
"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": "1364ec488def8a0494503b9879b370b3669e81f9",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "dandycheung/contour",
"max_forks_repo_path": "src/terminal_renderer/TextRenderer.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "1364ec488def8a0494503b9879b370b3669e81f9",
"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": "dandycheung/contour",
"max_issues_repo_path": "src/terminal_renderer/TextRenderer.h",
"max_line_length": 110,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "1364ec488def8a0494503b9879b370b3669e81f9",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "dandycheung/contour",
"max_stars_repo_path": "src/terminal_renderer/TextRenderer.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1407,
"size": 6631
} |
/* randist/gamma.c
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000 James Theiler, Brian Gough
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include <config.h>
#include <math.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_sf_gamma.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
static double gamma_large (const gsl_rng * r, const double a);
static double gamma_frac (const gsl_rng * r, const double a);
/* The Gamma distribution of order a>0 is defined by:
p(x) dx = {1 / \Gamma(a) b^a } x^{a-1} e^{-x/b} dx
for x>0. If X and Y are independent gamma-distributed random
variables of order a1 and a2 with the same scale parameter b, then
X+Y has gamma distribution of order a1+a2.
The algorithms below are from Knuth, vol 2, 2nd ed, p. 129. */
double
gsl_ran_gamma_knuth (const gsl_rng * r, const double a, const double b)
{
/* assume a > 0 */
unsigned int na = floor (a);
if (a == na)
{
return b * gsl_ran_gamma_int (r, na);
}
else if (na == 0)
{
return b * gamma_frac (r, a);
}
else
{
return b * (gsl_ran_gamma_int (r, na) + gamma_frac (r, a - na)) ;
}
}
double
gsl_ran_gamma_int (const gsl_rng * r, const unsigned int a)
{
if (a < 12)
{
unsigned int i;
double prod = 1;
for (i = 0; i < a; i++)
{
prod *= gsl_rng_uniform_pos (r);
}
/* Note: for 12 iterations we are safe against underflow, since
the smallest positive random number is O(2^-32). This means
the smallest possible product is 2^(-12*32) = 10^-116 which
is within the range of double precision. */
return -log (prod);
}
else
{
return gamma_large (r, (double) a);
}
}
static double
gamma_large (const gsl_rng * r, const double a)
{
/* Works only if a > 1, and is most efficient if a is large
This algorithm, reported in Knuth, is attributed to Ahrens. A
faster one, we are told, can be found in: J. H. Ahrens and
U. Dieter, Computing 12 (1974) 223-246. */
double sqa, x, y, v;
sqa = sqrt (2 * a - 1);
do
{
do
{
y = tan (M_PI * gsl_rng_uniform (r));
x = sqa * y + a - 1;
}
while (x <= 0);
v = gsl_rng_uniform (r);
}
while (v > (1 + y * y) * exp ((a - 1) * log (x / (a - 1)) - sqa * y));
return x;
}
static double
gamma_frac (const gsl_rng * r, const double a)
{
/* This is exercise 16 from Knuth; see page 135, and the solution is
on page 551. */
double p, q, x, u, v;
p = M_E / (a + M_E);
do
{
u = gsl_rng_uniform (r);
v = gsl_rng_uniform_pos (r);
if (u < p)
{
x = exp ((1 / a) * log (v));
q = exp (-x);
}
else
{
x = 1 - log (v);
q = exp ((a - 1) * log (x));
}
}
while (gsl_rng_uniform (r) >= q);
return x;
}
double
gsl_ran_gamma_pdf (const double x, const double a, const double b)
{
if (x < 0)
{
return 0 ;
}
else if (x == 0)
{
if (a == 1)
return 1/b ;
else
return 0 ;
}
else if (a == 1)
{
return exp(-x/b)/b ;
}
else
{
double p;
double lngamma = gsl_sf_lngamma (a);
p = exp ((a - 1) * log (x/b) - x/b - lngamma)/b;
return p;
}
}
/* New version based on Marsaglia and Tsang, "A Simple Method for
* generating gamma variables", ACM Transactions on Mathematical
* Software, Vol 26, No 3 (2000), p363-372.
*
* Implemented by J.D.Lamb@btinternet.com, minor modifications for GSL
* by Brian Gough
*/
double
gsl_ran_gamma_mt (const gsl_rng * r, const double a, const double b)
{
return gsl_ran_gamma (r, a, b);
}
double
gsl_ran_gamma (const gsl_rng * r, const double a, const double b)
{
/* assume a > 0 */
if (a < 1)
{
double u = gsl_rng_uniform_pos (r);
return gsl_ran_gamma (r, 1.0 + a, b) * pow (u, 1.0 / a);
}
{
double x, v, u;
double d = a - 1.0 / 3.0;
double c = (1.0 / 3.0) / sqrt (d);
while (1)
{
do
{
x = gsl_ran_gaussian_ziggurat (r, 1.0);
v = 1.0 + c * x;
}
while (v <= 0);
v = v * v * v;
u = gsl_rng_uniform_pos (r);
if (u < 1 - 0.0331 * x * x * x * x)
break;
if (log (u) < 0.5 * x * x + d * (1 - v + log (v)))
break;
}
return b * d * v;
}
}
| {
"alphanum_fraction": 0.5617428683,
"avg_line_length": 23.1583710407,
"ext": "c",
"hexsha": "37d167cd945f17b14998d8787d539fb156afd5ff",
"lang": "C",
"max_forks_count": 40,
"max_forks_repo_forks_event_max_datetime": "2022-03-03T23:23:37.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-02-26T15:31:16.000Z",
"max_forks_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "manggoguy/parsec-modified",
"max_forks_repo_path": "pkgs/libs/gsl/src/randist/gamma.c",
"max_issues_count": 12,
"max_issues_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af",
"max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "manggoguy/parsec-modified",
"max_issues_repo_path": "pkgs/libs/gsl/src/randist/gamma.c",
"max_line_length": 81,
"max_stars_count": 64,
"max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "manggoguy/parsec-modified",
"max_stars_repo_path": "pkgs/libs/gsl/src/randist/gamma.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": 1622,
"size": 5118
} |
/* multiset/multiset.c
* based on combination/combination.c by Szymon Jaroszewicz
* based on permutation/permutation.c by Brian Gough
*
* Copyright (C) 2001 Szymon Jaroszewicz
* 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.
*/
#include <config.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_multiset.h>
size_t
gsl_multiset_n (const gsl_multiset * c)
{
return c->n ;
}
size_t
gsl_multiset_k (const gsl_multiset * c)
{
return c->k ;
}
size_t *
gsl_multiset_data (const gsl_multiset * c)
{
return c->data ;
}
int
gsl_multiset_valid (gsl_multiset * c)
{
const size_t n = c->n ;
const size_t k = c->k ;
size_t i, j ;
for (i = 0; i < k; i++)
{
const size_t ci = c->data[i];
if (ci >= n)
{
GSL_ERROR("multiset index outside range", GSL_FAILURE) ;
}
for (j = 0; j < i; j++)
{
if (c->data[j] > ci)
{
GSL_ERROR("multiset indices not in increasing order",
GSL_FAILURE) ;
}
}
}
return GSL_SUCCESS;
}
int
gsl_multiset_next (gsl_multiset * c)
{
/* Replaces c with the next multiset (in the standard lexicographical
* ordering). Returns GSL_FAILURE if there is no next multiset.
*/
const size_t n = c->n;
const size_t k = c->k;
size_t *data = c->data;
size_t i;
if(k == 0)
{
return GSL_FAILURE;
}
i = k - 1;
while(i > 0 && data[i] == n-1)
{
--i;
}
if (i == 0 && data[0] == n-1)
{
return GSL_FAILURE;
}
++data[i];
while(i < k-1)
{
data[i+1] = data[i];
++i;
}
return GSL_SUCCESS;
}
int
gsl_multiset_prev (gsl_multiset * c)
{
/* Replaces c with the previous multiset (in the standard
* lexicographical ordering). Returns GSL_FAILURE if there is no
* previous multiset.
*/
const size_t n = c->n;
const size_t k = c->k;
size_t *data = c->data;
size_t i;
if(k == 0)
{
return GSL_FAILURE;
}
i = k - 1;
while(i > 0 && data[i-1] == data[i])
{
--i;
}
if(i == 0 && data[i] == 0)
{
return GSL_FAILURE;
}
data[i]--;
if (data[i] < n-1)
{
while (i < k-1) {
data[++i] = n - 1;
}
}
return GSL_SUCCESS;
}
int
gsl_multiset_memcpy (gsl_multiset * dest, const gsl_multiset * src)
{
const size_t src_n = src->n;
const size_t src_k = src->k;
const size_t dest_n = dest->n;
const size_t dest_k = dest->k;
if (src_n != dest_n || src_k != dest_k)
{
GSL_ERROR ("multiset lengths are not equal", GSL_EBADLEN);
}
{
size_t j;
for (j = 0; j < src_k; j++)
{
dest->data[j] = src->data[j];
}
}
return GSL_SUCCESS;
}
| {
"alphanum_fraction": 0.5872600349,
"avg_line_length": 19.3146067416,
"ext": "c",
"hexsha": "c1a0f80b4cb0e20bfa2b787fc0ded3d4444269a2",
"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/multiset/multiset.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/multiset/multiset.c",
"max_line_length": 81,
"max_stars_count": 14,
"max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "ielomariala/Hex-Game",
"max_stars_repo_path": "gsl-2.6/multiset/multiset.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": 1035,
"size": 3438
} |
/* Siconos is a program dedicated to modeling, simulation and control
* of non smooth dynamical systems.
*
* Copyright 2021 INRIA.
*
* 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 SiconosLAPACKE_H
#define SiconosLAPACKE_H
// IWYU pragma: private, include "SiconosLapack.h"
//#include "SiconosBlas.h"
#include <stdlib.h>
#include <assert.h>
#include <stdio.h>
// -------- Headers and routines naming conventions for the different Lapack implementations --------
// --- Intel MKL Header ---
#if defined(HAS_MKL_LAPACKE)
#include <mkl_lapacke.h>
#else
// Standard lapacke header
#include <lapacke.h>
#endif
// Name of the routines
#define LAPACK_NAME(N) LAPACKE_##N
#define LA_TRANS 'T'
#define LA_NOTRANS 'N'
#define LA_UP 'U'
#define LA_LO 'L'
#define LA_NONUNIT 'N'
#define LA_UNIT 'U'
#define INTEGER(X) X
#define INTEGERP(X) X
#define CHAR(X) X
#ifndef lapack_int
#define lapack_int int
#endif
// --- DGESVD ---
#if defined(HAS_LAPACK_dgesvd)
#define WRAP_DGESVD(F,A1,A2,A3,A4,A5,A6,A7,A8,A9,A10,A11,A12,INFO) \
INFO = F(CblasColMajor,A1,A2,A3,A4,A5,A6,A7,A8,A9,A10,A11,A12)
#else
#define WRAP_DGESVD(F,A1,A2,A3,A4,A5,A6,A7,A8,A9,A10,A11,A12,INFO) \
fprintf(stderr, "Your lapack version misses dgesvd function.\n");
#endif
// --- DGETRS ---
#define WRAP_DGETRS(F,A1,A2,A3,A4,A5,A6,A7,A8,INFO) \
INFO = F(CblasColMajor,A1,A2,A3,A4,A5,A6,A7,A8)
// --- DPOTRS ---
#define WRAP_DPOTRS(F,A1,A2,A3,A4,A5,A6,A7,INFO) \
INFO = F(CblasColMajor,A1,A2,A3,A4,A5,A6,A7)
// --- DSYTRS ---
#define WRAP_DSYTRS(F,A1,A2,A3,A4,A5,A6,A7,A8,INFO) \
INFO = F(CblasColMajor,A1,A2,A3,A4,A5,A6,A7,A8)
// --- DGESV ---
#define WRAP_DGESV(F,A1,A2,A3,A4,A5,A6,A7,INFO) \
INFO = F(CblasColMajor,A1,A2,A3,A4,A5,A6,A7)
// --- DPOSV ---
#define WRAP_DPOSV(F,A1,A2,A3,A4,A5,A6,A7,INFO) \
INFO = F(CblasColMajor,A1,A2,A3,A4,A5,A6,A7)
// --- DGELS ---
#if defined(HAS_LAPACK_dgels)
#define WRAP_DGELS(F,A1,A2,A3,A4,A5,A6,A7,A8,INFO) \
INFO = F(CblasColMajor,A1,A2,A3,A4,A5,A6,A7,A8)
#else
#define WRAP_DGELS(F,A1,A2,A3,A4,A5,A6,A7,A8,INFO) \
fprintf(stderr, "Your lapack version misses dgels function.\n");
#endif
// --- DGETRI ---
#define WRAP_DGETRI(F,A1,A2,A3,A4,INFO) \
INFO = F(CblasColMajor,A1,A2,A3,A4)
// --- DGETRF ---
#define WRAP_DGETRF(F,A1,A2,A3,A4,A5,INFO) \
INFO = F(CblasColMajor,A1,A2,A3,A4,A5)
// --- DPOTRF ---
#define WRAP_DPOTRF(F,A1,A2,A3,A4,INFO) \
INFO = F(CblasColMajor,A1,A2,A3,A4)
// --- DSYTRF ---
#define WRAP_DSYTRF(F,A1,A2,A3,A4,A5,INFO) \
INFO = F(CblasColMajor,A1,A2,A3,A4,A5)
// --- DTRTRS ---
#if defined(HAS_LAPACK_dtrtrs)
#define WRAP_DTRTRS(F,A1,A2,A3,A4,A5,A6,A7,A8,A9,INFO) \
INFO = F(CblasColMajor,A1,A2,A3,A4,A5,A6,A7,A8,A9)
#else
#define WRAP_DTRTRS(F,A1,A2,A3,A4,A5,A6,A7,A8,A9,INFO) \
fprintf(stderr, "Your lapack version misses dtrtrs function.\n");
#endif
#endif // SICONOSLAPACKE_H
| {
"alphanum_fraction": 0.679558011,
"avg_line_length": 28.1885245902,
"ext": "h",
"hexsha": "c9ba4945071b904f4c81d2718fa898331637da37",
"lang": "C",
"max_forks_count": 30,
"max_forks_repo_forks_event_max_datetime": "2022-03-02T20:30:20.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-08-06T22:57:51.000Z",
"max_forks_repo_head_hexsha": "5e9c95806f0a01d62ab564ffb1d9d50c2dc32ef0",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "BuildJet/siconos",
"max_forks_repo_path": "externals/blas_lapack/SiconosLapacke.h",
"max_issues_count": 381,
"max_issues_repo_head_hexsha": "5e9c95806f0a01d62ab564ffb1d9d50c2dc32ef0",
"max_issues_repo_issues_event_max_datetime": "2022-02-14T09:05:23.000Z",
"max_issues_repo_issues_event_min_datetime": "2015-09-22T15:31:08.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "BuildJet/siconos",
"max_issues_repo_path": "externals/blas_lapack/SiconosLapacke.h",
"max_line_length": 101,
"max_stars_count": 137,
"max_stars_repo_head_hexsha": "5e9c95806f0a01d62ab564ffb1d9d50c2dc32ef0",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "BuildJet/siconos",
"max_stars_repo_path": "externals/blas_lapack/SiconosLapacke.h",
"max_stars_repo_stars_event_max_datetime": "2022-03-26T06:01:59.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-06-16T15:55:28.000Z",
"num_tokens": 1223,
"size": 3439
} |
/*
* Copyright (c) 2006 Rudi Cilibrasi, Rulers of the RHouse
* All rights reserved. cilibrar@cilibrar.com
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the RHouse 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 RULERS 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 RULERS AND 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 __CLOUTPUT_H
#define __CLOUTPUT_H
#include <math.h>
#include <gsl/gsl_blas.h>
/*! \file cloutput.h */
gsl_matrix *complearn_svd_project(gsl_matrix *a);
GString *complearn_matrix_prettyprint_text(LabeledMatrix *inp);
GString *complearn_matrix_prettyprint_nex(LabeledMatrix *inp, GString *treeblock);
struct CLDistMatrix {
char *fileverstr;
char *cllibver;
char *username;
char *hostname;
char *title;
char *compressor;
char *creationTime; // Seconds since the epoch
char * *cmds;
char * *cmdtimes; // Seconds since the epoch
LabeledMatrix *m;
GArray *cmdsa;
GArray *cmdtimesa;
GArray *numa;
GArray *labels1a;
GArray *labels2a;
};
struct CLDistMatrix *complearn_read_clb_dist_matrix(const GString *db);
GArray *complearn_get_nexus_labels(const GString *db);
gsl_matrix *complearn_get_nexus_distance_matrix(const GString *db);
GString *complearn_matrix_prettyprint_clb(LabeledMatrix *result);
LabeledMatrix *complearn_load_nexus_matrix(const GString *inp);
LabeledMatrix *complearn_load_any_matrix(const GString *inp);
gboolean complearn_is_nexus_file(const GString *db);
GString *complearn_get_nexus_tree_block(const GString *db);
gboolean complearn_is_text_matrix(const GString *db);
LabeledMatrix *complearn_load_text_matrix(const GString *inp);
#endif
| {
"alphanum_fraction": 0.7778546713,
"avg_line_length": 40.1388888889,
"ext": "h",
"hexsha": "ea8ec45cfc490faaeb0fa480d425cba2064d0316",
"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": "c70ac5ad7bcfe3af80a2a8f087ee6f5904820a66",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "rudi-cilibrasi/classic-complearn",
"max_forks_repo_path": "src/complearn/cloutput.h",
"max_issues_count": 2,
"max_issues_repo_head_hexsha": "c70ac5ad7bcfe3af80a2a8f087ee6f5904820a66",
"max_issues_repo_issues_event_max_datetime": "2017-03-15T18:30:04.000Z",
"max_issues_repo_issues_event_min_datetime": "2016-05-10T12:56:52.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "rudi-cilibrasi/classic-complearn",
"max_issues_repo_path": "src/complearn/cloutput.h",
"max_line_length": 82,
"max_stars_count": 2,
"max_stars_repo_head_hexsha": "c70ac5ad7bcfe3af80a2a8f087ee6f5904820a66",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "rudi-cilibrasi/classic-complearn",
"max_stars_repo_path": "src/complearn/cloutput.h",
"max_stars_repo_stars_event_max_datetime": "2018-06-08T11:13:03.000Z",
"max_stars_repo_stars_event_min_datetime": "2018-03-14T13:52:31.000Z",
"num_tokens": 712,
"size": 2890
} |
/* specfunc/gamma_inc.c
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
/* Author: G. Jungman */
#include <config.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_sf_erf.h>
#include <gsl/gsl_sf_exp.h>
#include <gsl/gsl_sf_log.h>
#include <gsl/gsl_sf_gamma.h>
#include <gsl/gsl_sf_expint.h>
#include "error.h"
/* The dominant part,
* D(a,x) := x^a e^(-x) / Gamma(a+1)
*/
static
int
gamma_inc_D(const double a, const double x, gsl_sf_result * result)
{
if(a < 10.0) {
double lnr;
gsl_sf_result lg;
gsl_sf_lngamma_e(a+1.0, &lg);
lnr = a * log(x) - x - lg.val;
result->val = exp(lnr);
result->err = 2.0 * GSL_DBL_EPSILON * (fabs(lnr) + 1.0) * fabs(result->val);
return GSL_SUCCESS;
}
else {
gsl_sf_result gstar;
gsl_sf_result ln_term;
double term1;
if (x < 0.5*a) {
double u = x/a;
double ln_u = log(u);
ln_term.val = ln_u - u + 1.0;
ln_term.err = (fabs(ln_u) + fabs(u) + 1.0) * GSL_DBL_EPSILON;
} else {
double mu = (x-a)/a;
gsl_sf_log_1plusx_mx_e(mu, &ln_term); /* log(1+mu) - mu */
};
gsl_sf_gammastar_e(a, &gstar);
term1 = exp(a*ln_term.val)/sqrt(2.0*M_PI*a);
result->val = term1/gstar.val;
result->err = 2.0 * GSL_DBL_EPSILON * (fabs(a*ln_term.val) + 1.0) * fabs(result->val);
result->err += gstar.err/fabs(gstar.val) * fabs(result->val);
return GSL_SUCCESS;
}
}
/* P series representation.
*/
static
int
gamma_inc_P_series(const double a, const double x, gsl_sf_result * result)
{
const int nmax = 5000;
gsl_sf_result D;
int stat_D = gamma_inc_D(a, x, &D);
double sum = 1.0;
double term = 1.0;
int n;
for(n=1; n<nmax; n++) {
term *= x/(a+n);
sum += term;
if(fabs(term/sum) < GSL_DBL_EPSILON) break;
}
result->val = D.val * sum;
result->err = D.err * fabs(sum);
result->err += (1.0 + n) * GSL_DBL_EPSILON * fabs(result->val);
if(n == nmax)
GSL_ERROR ("error", GSL_EMAXITER);
else
return stat_D;
}
/* Q large x asymptotic
*/
static
int
gamma_inc_Q_large_x(const double a, const double x, gsl_sf_result * result)
{
const int nmax = 5000;
gsl_sf_result D;
const int stat_D = gamma_inc_D(a, x, &D);
double sum = 1.0;
double term = 1.0;
double last = 1.0;
int n;
for(n=1; n<nmax; n++) {
term *= (a-n)/x;
if(fabs(term/last) > 1.0) break;
if(fabs(term/sum) < GSL_DBL_EPSILON) break;
sum += term;
last = term;
}
result->val = D.val * (a/x) * sum;
result->err = D.err * fabs((a/x) * sum);
result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val);
if(n == nmax)
GSL_ERROR ("error in large x asymptotic", GSL_EMAXITER);
else
return stat_D;
}
/* Uniform asymptotic for x near a, a and x large.
* See [Temme, p. 285]
*/
static
int
gamma_inc_Q_asymp_unif(const double a, const double x, gsl_sf_result * result)
{
const double rta = sqrt(a);
const double eps = (x-a)/a;
gsl_sf_result ln_term;
const int stat_ln = gsl_sf_log_1plusx_mx_e(eps, &ln_term); /* log(1+eps) - eps */
const double eta = GSL_SIGN(eps) * sqrt(-2.0*ln_term.val);
gsl_sf_result erfc;
double R;
double c0, c1;
/* This used to say erfc(eta*M_SQRT2*rta), which is wrong.
* The sqrt(2) is in the denominator. Oops.
* Fixed: [GJ] Mon Nov 15 13:25:32 MST 2004
*/
gsl_sf_erfc_e(eta*rta/M_SQRT2, &erfc);
if(fabs(eps) < GSL_ROOT5_DBL_EPSILON) {
c0 = -1.0/3.0 + eps*(1.0/12.0 - eps*(23.0/540.0 - eps*(353.0/12960.0 - eps*589.0/30240.0)));
c1 = -1.0/540.0 - eps/288.0;
}
else {
const double rt_term = sqrt(-2.0 * ln_term.val/(eps*eps));
const double lam = x/a;
c0 = (1.0 - 1.0/rt_term)/eps;
c1 = -(eta*eta*eta * (lam*lam + 10.0*lam + 1.0) - 12.0 * eps*eps*eps) / (12.0 * eta*eta*eta*eps*eps*eps);
}
R = exp(-0.5*a*eta*eta)/(M_SQRT2*M_SQRTPI*rta) * (c0 + c1/a);
result->val = 0.5 * erfc.val + R;
result->err = GSL_DBL_EPSILON * fabs(R * 0.5 * a*eta*eta) + 0.5 * erfc.err;
result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val);
return stat_ln;
}
/* Continued fraction which occurs in evaluation
* of Q(a,x) or Gamma(a,x).
*
* 1 (1-a)/x 1/x (2-a)/x 2/x (3-a)/x
* F(a,x) = ---- ------- ----- -------- ----- -------- ...
* 1 + 1 + 1 + 1 + 1 + 1 +
*
* Hans E. Plesser, 2002-01-22 (hans dot plesser at itf dot nlh dot no).
*
* Split out from gamma_inc_Q_CF() by GJ [Tue Apr 1 13:16:41 MST 2003].
* See gamma_inc_Q_CF() below.
*
*/
static int
gamma_inc_F_CF(const double a, const double x, gsl_sf_result * result)
{
const int nmax = 5000;
const double small = gsl_pow_3 (GSL_DBL_EPSILON);
double hn = 1.0; /* convergent */
double Cn = 1.0 / small;
double Dn = 1.0;
int n;
/* n == 1 has a_1, b_1, b_0 independent of a,x,
so that has been done by hand */
for ( n = 2 ; n < nmax ; n++ )
{
double an;
double delta;
if(GSL_IS_ODD(n))
an = 0.5*(n-1)/x;
else
an = (0.5*n-a)/x;
Dn = 1.0 + an * Dn;
if ( fabs(Dn) < small )
Dn = small;
Cn = 1.0 + an/Cn;
if ( fabs(Cn) < small )
Cn = small;
Dn = 1.0 / Dn;
delta = Cn * Dn;
hn *= delta;
if(fabs(delta-1.0) < GSL_DBL_EPSILON) break;
}
result->val = hn;
result->err = 2.0*GSL_DBL_EPSILON * fabs(hn);
result->err += GSL_DBL_EPSILON * (2.0 + 0.5*n) * fabs(result->val);
if(n == nmax)
GSL_ERROR ("error in CF for F(a,x)", GSL_EMAXITER);
else
return GSL_SUCCESS;
}
/* Continued fraction for Q.
*
* Q(a,x) = D(a,x) a/x F(a,x)
*
* Hans E. Plesser, 2002-01-22 (hans dot plesser at itf dot nlh dot no):
*
* Since the Gautschi equivalent series method for CF evaluation may lead
* to singularities, I have replaced it with the modified Lentz algorithm
* given in
*
* I J Thompson and A R Barnett
* Coulomb and Bessel Functions of Complex Arguments and Order
* J Computational Physics 64:490-509 (1986)
*
* In consequence, gamma_inc_Q_CF_protected() is now obsolete and has been
* removed.
*
* Identification of terms between the above equation for F(a, x) and
* the first equation in the appendix of Thompson&Barnett is as follows:
*
* b_0 = 0, b_n = 1 for all n > 0
*
* a_1 = 1
* a_n = (n/2-a)/x for n even
* a_n = (n-1)/(2x) for n odd
*
*/
static
int
gamma_inc_Q_CF(const double a, const double x, gsl_sf_result * result)
{
gsl_sf_result D;
gsl_sf_result F;
const int stat_D = gamma_inc_D(a, x, &D);
const int stat_F = gamma_inc_F_CF(a, x, &F);
result->val = D.val * (a/x) * F.val;
result->err = D.err * fabs((a/x) * F.val) + fabs(D.val * a/x * F.err);
return GSL_ERROR_SELECT_2(stat_F, stat_D);
}
/* Useful for small a and x. Handles the subtraction analytically.
*/
static
int
gamma_inc_Q_series(const double a, const double x, gsl_sf_result * result)
{
double term1; /* 1 - x^a/Gamma(a+1) */
double sum; /* 1 + (a+1)/(a+2)(-x)/2! + (a+1)/(a+3)(-x)^2/3! + ... */
int stat_sum;
double term2; /* a temporary variable used at the end */
{
/* Evaluate series for 1 - x^a/Gamma(a+1), small a
*/
const double pg21 = -2.404113806319188570799476; /* PolyGamma[2,1] */
const double lnx = log(x);
const double el = M_EULER+lnx;
const double c1 = -el;
const double c2 = M_PI*M_PI/12.0 - 0.5*el*el;
const double c3 = el*(M_PI*M_PI/12.0 - el*el/6.0) + pg21/6.0;
const double c4 = -0.04166666666666666667
* (-1.758243446661483480 + lnx)
* (-0.764428657272716373 + lnx)
* ( 0.723980571623507657 + lnx)
* ( 4.107554191916823640 + lnx);
const double c5 = -0.0083333333333333333
* (-2.06563396085715900 + lnx)
* (-1.28459889470864700 + lnx)
* (-0.27583535756454143 + lnx)
* ( 1.33677371336239618 + lnx)
* ( 5.17537282427561550 + lnx);
const double c6 = -0.0013888888888888889
* (-2.30814336454783200 + lnx)
* (-1.65846557706987300 + lnx)
* (-0.88768082560020400 + lnx)
* ( 0.17043847751371778 + lnx)
* ( 1.92135970115863890 + lnx)
* ( 6.22578557795474900 + lnx);
const double c7 = -0.00019841269841269841
* (-2.5078657901291800 + lnx)
* (-1.9478900888958200 + lnx)
* (-1.3194837322612730 + lnx)
* (-0.5281322700249279 + lnx)
* ( 0.5913834939078759 + lnx)
* ( 2.4876819633378140 + lnx)
* ( 7.2648160783762400 + lnx);
const double c8 = -0.00002480158730158730
* (-2.677341544966400 + lnx)
* (-2.182810448271700 + lnx)
* (-1.649350342277400 + lnx)
* (-1.014099048290790 + lnx)
* (-0.191366955370652 + lnx)
* ( 0.995403817918724 + lnx)
* ( 3.041323283529310 + lnx)
* ( 8.295966556941250 + lnx);
const double c9 = -2.75573192239859e-6
* (-2.8243487670469080 + lnx)
* (-2.3798494322701120 + lnx)
* (-1.9143674728689960 + lnx)
* (-1.3814529102920370 + lnx)
* (-0.7294312810261694 + lnx)
* ( 0.1299079285269565 + lnx)
* ( 1.3873333251885240 + lnx)
* ( 3.5857258865210760 + lnx)
* ( 9.3214237073814600 + lnx);
const double c10 = -2.75573192239859e-7
* (-2.9540329644556910 + lnx)
* (-2.5491366926991850 + lnx)
* (-2.1348279229279880 + lnx)
* (-1.6741881076349450 + lnx)
* (-1.1325949616098420 + lnx)
* (-0.4590034650618494 + lnx)
* ( 0.4399352987435699 + lnx)
* ( 1.7702236517651670 + lnx)
* ( 4.1231539047474080 + lnx)
* ( 10.342627908148680 + lnx);
term1 = a*(c1+a*(c2+a*(c3+a*(c4+a*(c5+a*(c6+a*(c7+a*(c8+a*(c9+a*c10)))))))));
}
{
/* Evaluate the sum.
*/
const int nmax = 5000;
double t = 1.0;
int n;
sum = 1.0;
for(n=1; n<nmax; n++) {
t *= -x/(n+1.0);
sum += (a+1.0)/(a+n+1.0)*t;
if(fabs(t/sum) < GSL_DBL_EPSILON) break;
}
if(n == nmax)
stat_sum = GSL_EMAXITER;
else
stat_sum = GSL_SUCCESS;
}
term2 = (1.0 - term1) * a/(a+1.0) * x * sum;
result->val = term1 + term2;
result->err = GSL_DBL_EPSILON * (fabs(term1) + 2.0*fabs(term2));
result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val);
return stat_sum;
}
/* series for small a and x, but not defined for a == 0 */
static int
gamma_inc_series(double a, double x, gsl_sf_result * result)
{
gsl_sf_result Q;
gsl_sf_result G;
const int stat_Q = gamma_inc_Q_series(a, x, &Q);
const int stat_G = gsl_sf_gamma_e(a, &G);
result->val = Q.val * G.val;
result->err = fabs(Q.val * G.err) + fabs(Q.err * G.val);
result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val);
return GSL_ERROR_SELECT_2(stat_Q, stat_G);
}
static int
gamma_inc_a_gt_0(double a, double x, gsl_sf_result * result)
{
/* x > 0 and a > 0; use result for Q */
gsl_sf_result Q;
gsl_sf_result G;
const int stat_Q = gsl_sf_gamma_inc_Q_e(a, x, &Q);
const int stat_G = gsl_sf_gamma_e(a, &G);
result->val = G.val * Q.val;
result->err = fabs(G.val * Q.err) + fabs(G.err * Q.val);
result->err += 2.0*GSL_DBL_EPSILON * fabs(result->val);
return GSL_ERROR_SELECT_2(stat_G, stat_Q);
}
static int
gamma_inc_CF(double a, double x, gsl_sf_result * result)
{
gsl_sf_result F;
gsl_sf_result pre;
const int stat_F = gamma_inc_F_CF(a, x, &F);
const int stat_E = gsl_sf_exp_e((a-1.0)*log(x) - x, &pre);
result->val = F.val * pre.val;
result->err = fabs(F.err * pre.val) + fabs(F.val * pre.err);
result->err += (2.0 + fabs(a)) * GSL_DBL_EPSILON * fabs(result->val);
return GSL_ERROR_SELECT_2(stat_F, stat_E);
}
/* evaluate Gamma(0,x), x > 0 */
#define GAMMA_INC_A_0(x, result) gsl_sf_expint_E1_e(x, result)
/*-*-*-*-*-*-*-*-*-*-*-* Functions with Error Codes *-*-*-*-*-*-*-*-*-*-*-*/
int
gsl_sf_gamma_inc_Q_e(const double a, const double x, gsl_sf_result * result)
{
if(a < 0.0 || x < 0.0) {
DOMAIN_ERROR(result);
}
else if(x == 0.0) {
result->val = 1.0;
result->err = 0.0;
return GSL_SUCCESS;
}
else if(a == 0.0)
{
result->val = 0.0;
result->err = 0.0;
return GSL_SUCCESS;
}
else if(x <= 0.5*a) {
/* If the series is quick, do that. It is
* robust and simple.
*/
gsl_sf_result P;
int stat_P = gamma_inc_P_series(a, x, &P);
result->val = 1.0 - P.val;
result->err = P.err;
result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val);
return stat_P;
}
else if(a >= 1.0e+06 && (x-a)*(x-a) < a) {
/* Then try the difficult asymptotic regime.
* This is the only way to do this region.
*/
return gamma_inc_Q_asymp_unif(a, x, result);
}
else if(a < 0.2 && x < 5.0) {
/* Cancellations at small a must be handled
* analytically; x should not be too big
* either since the series terms grow
* with x and log(x).
*/
return gamma_inc_Q_series(a, x, result);
}
else if(a <= x) {
if(x <= 1.0e+06) {
/* Continued fraction is excellent for x >~ a.
* We do not let x be too large when x > a since
* it is somewhat pointless to try this there;
* the function is rapidly decreasing for
* x large and x > a, and it will just
* underflow in that region anyway. We
* catch that case in the standard
* large-x method.
*/
return gamma_inc_Q_CF(a, x, result);
}
else {
return gamma_inc_Q_large_x(a, x, result);
}
}
else {
if(x > a - sqrt(a)) {
/* Continued fraction again. The convergence
* is a little slower here, but that is fine.
* We have to trade that off against the slow
* convergence of the series, which is the
* only other option.
*/
return gamma_inc_Q_CF(a, x, result);
}
else {
gsl_sf_result P;
int stat_P = gamma_inc_P_series(a, x, &P);
result->val = 1.0 - P.val;
result->err = P.err;
result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val);
return stat_P;
}
}
}
int
gsl_sf_gamma_inc_P_e(const double a, const double x, gsl_sf_result * result)
{
if(a <= 0.0 || x < 0.0) {
DOMAIN_ERROR(result);
}
else if(x == 0.0) {
result->val = 0.0;
result->err = 0.0;
return GSL_SUCCESS;
}
else if(x < 20.0 || x < 0.5*a) {
/* Do the easy series cases. Robust and quick.
*/
return gamma_inc_P_series(a, x, result);
}
else if(a > 1.0e+06 && (x-a)*(x-a) < a) {
/* Crossover region. Note that Q and P are
* roughly the same order of magnitude here,
* so the subtraction is stable.
*/
gsl_sf_result Q;
int stat_Q = gamma_inc_Q_asymp_unif(a, x, &Q);
result->val = 1.0 - Q.val;
result->err = Q.err;
result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val);
return stat_Q;
}
else if(a <= x) {
/* Q <~ P in this area, so the
* subtractions are stable.
*/
gsl_sf_result Q;
int stat_Q;
if(a > 0.2*x) {
stat_Q = gamma_inc_Q_CF(a, x, &Q);
}
else {
stat_Q = gamma_inc_Q_large_x(a, x, &Q);
}
result->val = 1.0 - Q.val;
result->err = Q.err;
result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val);
return stat_Q;
}
else {
if((x-a)*(x-a) < a) {
/* This condition is meant to insure
* that Q is not very close to 1,
* so the subtraction is stable.
*/
gsl_sf_result Q;
int stat_Q = gamma_inc_Q_CF(a, x, &Q);
result->val = 1.0 - Q.val;
result->err = Q.err;
result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val);
return stat_Q;
}
else {
return gamma_inc_P_series(a, x, result);
}
}
}
int
gsl_sf_gamma_inc_e(const double a, const double x, gsl_sf_result * result)
{
if(x < 0.0) {
DOMAIN_ERROR(result);
}
else if(x == 0.0) {
return gsl_sf_gamma_e(a, result);
}
else if(a == 0.0)
{
return GAMMA_INC_A_0(x, result);
}
else if(a > 0.0)
{
return gamma_inc_a_gt_0(a, x, result);
}
else if(x > 0.25)
{
/* continued fraction seems to fail for x too small; otherwise
it is ok, independent of the value of |x/a|, because of the
non-oscillation in the expansion, i.e. the CF is
un-conditionally convergent for a < 0 and x > 0
*/
return gamma_inc_CF(a, x, result);
}
else if(fabs(a) < 0.5)
{
return gamma_inc_series(a, x, result);
}
else
{
/* a = fa + da; da >= 0 */
const double fa = floor(a);
const double da = a - fa;
gsl_sf_result g_da;
const int stat_g_da = ( da > 0.0 ? gamma_inc_a_gt_0(da, x, &g_da)
: GAMMA_INC_A_0(x, &g_da));
double alpha = da;
double gax = g_da.val;
/* Gamma(alpha-1,x) = 1/(alpha-1) (Gamma(a,x) - x^(alpha-1) e^-x) */
do
{
const double shift = exp(-x + (alpha-1.0)*log(x));
gax = (gax - shift) / (alpha - 1.0);
alpha -= 1.0;
} while(alpha > a);
result->val = gax;
result->err = 2.0*(1.0 + fabs(a))*GSL_DBL_EPSILON*fabs(gax);
return stat_g_da;
}
}
/*-*-*-*-*-*-*-*-*-* Functions w/ Natural Prototypes *-*-*-*-*-*-*-*-*-*-*/
#include "eval.h"
double gsl_sf_gamma_inc_P(const double a, const double x)
{
EVAL_RESULT(gsl_sf_gamma_inc_P_e(a, x, &result));
}
double gsl_sf_gamma_inc_Q(const double a, const double x)
{
EVAL_RESULT(gsl_sf_gamma_inc_Q_e(a, x, &result));
}
double gsl_sf_gamma_inc(const double a, const double x)
{
EVAL_RESULT(gsl_sf_gamma_inc_e(a, x, &result));
}
| {
"alphanum_fraction": 0.5651165243,
"avg_line_length": 28.2232142857,
"ext": "c",
"hexsha": "5ca728a56e5dad6771ac6f5bad67eb5ca5abdf46",
"lang": "C",
"max_forks_count": 40,
"max_forks_repo_forks_event_max_datetime": "2022-03-03T23:23:37.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-02-26T15:31:16.000Z",
"max_forks_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "manggoguy/parsec-modified",
"max_forks_repo_path": "pkgs/libs/gsl/src/specfunc/gamma_inc.c",
"max_issues_count": 12,
"max_issues_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af",
"max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "manggoguy/parsec-modified",
"max_issues_repo_path": "pkgs/libs/gsl/src/specfunc/gamma_inc.c",
"max_line_length": 109,
"max_stars_count": 64,
"max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "manggoguy/parsec-modified",
"max_stars_repo_path": "pkgs/libs/gsl/src/specfunc/gamma_inc.c",
"max_stars_repo_stars_event_max_datetime": "2022-03-24T13:26:53.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-03-06T00:30:56.000Z",
"num_tokens": 6352,
"size": 18966
} |
/*
ODE: a program to get optime Runge-Kutta and multi-steps methods.
Copyright 2011-2019, Javier Burguete Tolosa.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY Javier Burguete Tolosa ``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 Javier Burguete Tolosa 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.
*/
/**
* \file optimize.c
* \brief Source file with optimize functions.
* \author Javier Burguete Tolosa.
* \copyright Copyright 2011-2019.
*/
#define _GNU_SOURCE
#include <stdio.h>
#include <string.h>
#include <float.h>
#include <math.h>
#include <libxml/parser.h>
#include <glib.h>
#include <libintl.h>
#include <gsl/gsl_rng.h>
#if HAVE_MPI
#include <mpi.h>
#endif
#include "config.h"
#include "utils.h"
#include "optimize.h"
#define DEBUG_OPTIMIZE 0 ///< macro to debug.
GMutex mutex[1]; ///< GMutex struct.
FILE *file_variables = NULL; ///< random variables file.
int rank; ///< MPI rank.
int nnodes; ///< MPI nodes number.
unsigned nthreads; ///< threads number.
/**
* Function to print the random variables on a file.
*/
void
optimize_print_random (Optimize * optimize, ///< Optimize struct.
FILE * file) ///< file.
{
unsigned int i, n;
n = optimize->nfree;
for (i = 0; i < n; ++i)
fprintf (file, "o%d:%.19Le;\n", i, optimize->value_optimal[i]);
for (i = 0; i < n; ++i)
fprintf (file, "m%d:%.19Le;\n", i, optimize->minimum[i]);
for (i = 0; i < n; ++i)
fprintf (file, "i%d:%.19Le;\n", i, optimize->interval[i]);
}
/**
* Function to perform every optimization step.
*/
void
optimize_step (Optimize * optimize) ///< Optimize struct.
{
long double *is, *vo, *vo2, *random;
long double o, o2, v, f;
unsigned long long int ii, nrandom;
unsigned int i, j, k, n, nfree;
#if DEBUG_OPTIMIZE
fprintf (stderr, "optimize_step: start\n");
#endif
// save optimal values
#if DEBUG_OPTIMIZE
fprintf (stderr, "optimize_step: save optimal values\n");
#endif
nfree = optimize->nfree;
o2 = *optimize->optimal;
vo = (long double *) alloca (nfree * sizeof (long double));
vo2 = (long double *) alloca (nfree * sizeof (long double));
memcpy (vo, optimize->value_optimal, nfree * sizeof (long double));
// optimization algorithm sampling
#if DEBUG_OPTIMIZE
fprintf (stderr, "optimize_step: optimization algorithm sampling\n");
fprintf (stderr, "optimize_step: nsimulations=%Lu\n", optimize->nsimulations);
#endif
random = optimize->random_data;
ii = optimize->nsimulations * (rank * nthreads + optimize->thread)
/ (nnodes * nthreads);
nrandom = optimize->nsimulations * (rank * nthreads + optimize->thread + 1)
/ (nnodes * nthreads);
for (; ii < nrandom; ++ii)
{
// random freedom degrees
#if DEBUG_OPTIMIZE
fprintf (stderr, "optimize_step: random freedom degrees\n");
fprintf (stderr, "optimize_step: simulation=%Lu\n", ii);
#endif
optimize_generate_freedom (optimize, ii);
// method coefficients
#if DEBUG_OPTIMIZE
fprintf (stderr, "optimize_step: method coefficients\n");
#endif
if (!optimize->method (optimize))
o = INFINITY;
else
o = optimize->objective (optimize);
if (o < o2)
{
o2 = o;
memcpy (vo, random, nfree * sizeof (long double));
}
if (file_variables)
{
g_mutex_lock (mutex);
print_variables (random, nfree, file_variables);
fprintf (file_variables, "%.19Le\n", o);
g_mutex_unlock (mutex);
}
}
// array of intervals to climb around the optimal
#if DEBUG_OPTIMIZE
fprintf (stderr,
"optimize_step: array of intervals to climb around the optimal\n");
#endif
is = (long double *) alloca (nfree * sizeof (long double));
for (j = 0; j < nfree; ++j)
is[j] = optimize->interval0[j] * optimize->climbing_factor;
// hill climbing algorithm bucle
#if DEBUG_OPTIMIZE
fprintf (stderr, "optimize_step: hill climbing algorithm bucle\n");
#endif
memcpy (vo2, vo, nfree * sizeof (long double));
n = optimize->nclimbings;
for (i = 0; i < n; ++i)
{
memcpy (random, vo, nfree * sizeof (long double));
for (j = k = 0; j < nfree; ++j)
{
v = vo[j];
random[j] = v + is[j];
if (!optimize->method (optimize))
o = INFINITY;
else
o = optimize->objective (optimize);
if (o < o2)
{
k = 1;
o2 = o;
memcpy (vo2, random, nfree * sizeof (long double));
}
if (file_variables)
{
g_mutex_lock (mutex);
print_variables (random, nfree, file_variables);
fprintf (file_variables, "%.19Le\n", o);
g_mutex_unlock (mutex);
}
random[j] = fmaxl (0.L, v - is[j]);
if (!optimize->method (optimize))
o = INFINITY;
else
o = optimize->objective (optimize);
if (o < o2)
{
k = 1;
o2 = o;
memcpy (vo2, random, nfree * sizeof (long double));
}
if (file_variables)
{
g_mutex_lock (mutex);
print_variables (random, nfree, file_variables);
fprintf (file_variables, "%.19Le\n", o);
g_mutex_unlock (mutex);
}
random[j] = v;
}
// update optimal values and increase or reduce intervals if converging or
// not
if (!k)
f = 0.5L;
else
{
f = 1.2L;
memcpy (vo, vo2, nfree * sizeof (long double));
}
for (j = 0; j < nfree; ++j)
is[j] *= f;
}
// update optimal values
#if DEBUG_OPTIMIZE
fprintf (stderr, "optimize_step: update optimal values\n");
#endif
if (o2 < *optimize->optimal)
{
g_mutex_lock (mutex);
*optimize->optimal = o2;
memcpy (optimize->value_optimal, vo2, nfree * sizeof (long double));
g_mutex_unlock (mutex);
}
#if DEBUG_OPTIMIZE
fprintf (stderr, "optimize_step: end\n");
#endif
}
/**
* Function to init required variables on an Optimize struct data.
*/
void
optimize_init (Optimize * optimize, ///< Optimize struct.
gsl_rng * rng, ///< GSL pseudo-random number generator struct.
unsigned int thread) ///< thread number.
{
#if DEBUG_OPTIMIZE
fprintf (stderr, "optimize_init: start\n");
#endif
#if DEBUG_OPTIMIZE
fprintf (stderr, "optimize_init: nsimulations=%Lu nfree=%u size=%u\n",
optimize->nsimulations, optimize->nfree, optimize->size);
#endif
optimize->random_data
= (long double *) g_slice_alloc (optimize->nfree * sizeof (long double));
optimize->coefficient
= (long double *) g_slice_alloc (optimize->size * sizeof (long double));
optimize->minimum
= (long double *) g_slice_alloc (optimize->nfree * sizeof (long double));
optimize->interval
= (long double *) g_slice_alloc (optimize->nfree * sizeof (long double));
memcpy (optimize->minimum, optimize->minimum0,
optimize->nfree * sizeof (long double));
memcpy (optimize->interval, optimize->interval0,
optimize->nfree * sizeof (long double));
optimize->rng = rng;
optimize->thread = thread;
#if DEBUG_OPTIMIZE
fprintf (stderr, "optimize_init: end\n");
#endif
}
/**
* Function to free the memory allocated by an Optimize struct.
*/
void
optimize_delete (Optimize * optimize) ///< Optimize struct.
{
g_slice_free1 (optimize->nfree * sizeof (long double), optimize->interval);
g_slice_free1 (optimize->nfree * sizeof (long double), optimize->minimum);
g_slice_free1 (optimize->size * sizeof (long double), optimize->coefficient);
g_slice_free1 (optimize->nfree * sizeof (long double), optimize->random_data);
}
/**
* Function to do the optimization bucle.
*/
void
optimize_bucle (Optimize * optimize) ///< Optimize struct.
{
GThread *thread[nthreads];
#if HAVE_MPI
long double *vo;
MPI_Status status;
#endif
unsigned int i, j, nfree;
#if DEBUG_OPTIMIZE
fprintf (stderr, "optimize_bucle: start\n");
fprintf (stderr, "optimize_bucle: nfree=%u\n", optimize->nfree);
#endif
// Allocate local array of optimal values
#if DEBUG_OPTIMIZE
fprintf (stderr, "optimize_bucle: allocate local array of optimal values\n");
#endif
nfree = optimize->nfree;
#if HAVE_MPI
vo = (long double *) alloca ((1 + nfree) * sizeof (long double));
printf ("Rank=%d NNodes=%d\n", rank, nnodes);
#endif
// Init some parameters
#if DEBUG_OPTIMIZE
fprintf (stderr, "optimize_bucle: init some parameters\n");
#endif
*optimize->optimal = INFINITY;
for (i = 0; i < nfree; ++i)
optimize->value_optimal[i]
= optimize->minimum[i] + 0.5L * optimize->interval[i];
// Iterate
#if DEBUG_OPTIMIZE
fprintf (stderr, "optimize_bucle: iterate\n");
#endif
for (i = 0; i < optimize->niterations; ++i)
{
// Optimization step parallelized for every node by GThreads
if (nthreads > 1)
{
for (j = 0; j < nthreads; ++j)
thread[j]
= g_thread_new (NULL,
(GThreadFunc) (void (*)(void)) optimize_step,
(void *) (optimize + j));
for (j = 0; j < nthreads; ++j)
g_thread_join (thread[j]);
}
else
optimize_step (optimize);
#if HAVE_MPI
if (rank > 0)
{
// Secondary nodes send the optimal coefficients to the master node
vo[0] = *optimize->optimal;
memcpy (vo + 1, optimize->value_optimal,
nfree * sizeof (long double));
MPI_Send (vo, 1 + nfree, MPI_LONG_DOUBLE, 0, 1, MPI_COMM_WORLD);
// Secondary nodes receive the optimal coefficients
MPI_Recv (vo, 1 + nfree, MPI_LONG_DOUBLE, 0, 1, MPI_COMM_WORLD,
&status);
*optimize->optimal = vo[0];
memcpy (optimize->value_optimal, vo + 1,
nfree * sizeof (long double));
}
else
{
printf ("rank=%d optimal=%.19Le\n", rank, *optimize->optimal);
for (j = 1; j < nnodes; ++j)
{
// Master node receives the optimal coefficients obtained by
// secondary nodes
MPI_Recv (vo, 1 + nfree, MPI_LONG_DOUBLE, j, 1, MPI_COMM_WORLD,
&status);
// Master node selects the optimal coefficients
if (vo[0] < *optimize->optimal)
{
*optimize->optimal = vo[0];
memcpy (optimize->value_optimal, vo + 1,
nfree * sizeof (long double));
}
}
// Master node sends the optimal coefficients to secondary nodes
vo[0] = *optimize->optimal;
memcpy (vo + 1, optimize->value_optimal,
nfree * sizeof (long double));
for (j = 1; j < nnodes; ++j)
MPI_Send (vo, 1 + nfree, MPI_LONG_DOUBLE, j, 1, MPI_COMM_WORLD);
}
#endif
// Print the optimal coefficients
#if DEBUG_OPTIMIZE
optimize_print_random (optimize, stderr);
fprintf (stderr, "optimal=%.19Le\n", *optimize->optimal);
#endif
// Updating coefficient intervals to converge
optimize_converge (optimize);
// Iterate
#if HAVE_MPI
printf ("Rank %u\n", rank);
#endif
printf ("Iteration %u Optimal %.19Le\n", i + 1, *optimize->optimal);
}
#if DEBUG_OPTIMIZE
fprintf (stderr, "optimize_bucle: end\n");
#endif
}
/**
* Function to create an Optimize struct data.
*/
void
optimize_create (Optimize * optimize, ///< Optimize struct.
long double *optimal,
///< pointer to the optimal objective function value.
long double *value_optimal)
///< array of optimal freedom degree values.
{
unsigned long long int nsimulations;
unsigned int i, nfree;
#if DEBUG_OPTIMIZE
fprintf (stderr, "optimize_create: start\n");
#endif
optimize->optimal = optimal;
optimize->value_optimal = value_optimal;
nfree = optimize->nfree;
optimize->nsimulations = nsimulations = optimize->nvariable;
for (i = 1; i < nfree; ++i)
optimize->nsimulations *= nsimulations;
optimize->nclimbings *= nfree;
#if DEBUG_OPTIMIZE
fprintf (stderr, "optimize_create nsimulations=%Lu nclimbings=%u nfree=%u\n",
optimize->nsimulations, optimize->nclimbings, nfree);
fprintf (stderr, "optimize_create: end\n");
#endif
}
/**
* Function to read the Optimize struct data on a XML node.
*
* \return 1 on success, 0 on error.
*/
int
optimize_read (Optimize * optimize, ///< Optimize struct.
xmlNode * node) ///< XML node.
{
int code;
#if DEBUG_OPTIMIZE
fprintf (stderr, "optimize_read: start\n");
#endif
optimize->nvariable = xml_node_get_uint (node, XML_NSIMULATIONS, &code);
if (code || !optimize->nvariable)
{
error_message = g_strdup (_("Bad simulations number"));
goto exit_on_error;
}
optimize->nclimbings
= xml_node_get_uint_with_default (node, XML_NCLIMBINGS, 0, &code);
if (code)
{
error_message = g_strdup (_("Bad hill climbings number"));
goto exit_on_error;
}
optimize->niterations = xml_node_get_uint (node, XML_NITERATIONS, &code);
if (code || !optimize->niterations)
{
error_message = g_strdup (_("Bad iterations number"));
goto exit_on_error;
}
optimize->convergence_factor
= xml_node_get_float (node, XML_CONVERGENCE_FACTOR, &code);
if (code || optimize->convergence_factor < LDBL_EPSILON)
{
error_message = g_strdup (_("Bad convergence factor"));
goto exit_on_error;
}
optimize->climbing_factor
= xml_node_get_float (node, XML_CLIMBING_FACTOR, &code);
if (code || optimize->climbing_factor < LDBL_EPSILON)
{
error_message = g_strdup (_("Bad climging factor"));
goto exit_on_error;
}
#if DEBUG_OPTIMIZE
fprintf (stderr, "optimize_read: end\n");
#endif
return 1;
exit_on_error:
#if DEBUG_OPTIMIZE
fprintf (stderr, "optimize_read: end\n");
#endif
return 0;
}
| {
"alphanum_fraction": 0.618660726,
"avg_line_length": 31.0203252033,
"ext": "c",
"hexsha": "ecb8e16bf079c97e6b6daeeba64443aefd7af303",
"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": "463b8402ed4aac140a4c4ca2295a69dcce98b061",
"max_forks_repo_licenses": [
"BSD-2-Clause"
],
"max_forks_repo_name": "jburguete/ode",
"max_forks_repo_path": "optimize.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "463b8402ed4aac140a4c4ca2295a69dcce98b061",
"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": "jburguete/ode",
"max_issues_repo_path": "optimize.c",
"max_line_length": 80,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "463b8402ed4aac140a4c4ca2295a69dcce98b061",
"max_stars_repo_licenses": [
"BSD-2-Clause"
],
"max_stars_repo_name": "jburguete/ode",
"max_stars_repo_path": "optimize.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 3882,
"size": 15262
} |
/* movstat/test_qqr.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>
/* compute moving QQR by explicitely constructing window and computing QQR */
int
slow_movqqr(const gsl_movstat_end_t etype, const double q, 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 quant1, quant2;
gsl_sort(window, 1, wsize);
quant1 = gsl_stats_quantile_from_sorted_data(window, 1, wsize, q);
quant2 = gsl_stats_quantile_from_sorted_data(window, 1, wsize, 1.0 - q);
gsl_vector_set(y, i, quant2 - quant1);
}
free(window);
return GSL_SUCCESS;
}
static double
func_qqr(const size_t n, double x[], void * params)
{
double q = *(double *) params;
double quant1, quant2;
(void) params;
gsl_sort(x, 1, n);
quant1 = gsl_stats_quantile_from_sorted_data(x, 1, n, q);
quant2 = gsl_stats_quantile_from_sorted_data(x, 1, n, 1.0 - q);
return (quant2 - quant1);
}
static void
test_qqr_proc(const double tol, const double q, 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_movstat_alloc2(H, J);
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_qqr;
F.params = (void *) &q;
random_vector(x, rng_p);
/* y = QQR(x) with slow brute force method */
slow_movqqr(etype, q, x, y, H, J);
/* y = QQR(x) with fast method */
gsl_movstat_qqr(etype, x, q, z, w);
/* test y = z */
sprintf(buf, "n=%zu H=%zu J=%zu endtype=%u QQR random", n, H, J, etype);
compare_vectors(tol, z, y, buf);
/* z = QQR(x) in-place */
gsl_vector_memcpy(z, x);
gsl_movstat_qqr(etype, z, q, z, w);
sprintf(buf, "n=%zu H=%zu J=%zu endtype=%u QQR random in-place", n, H, J, etype);
compare_vectors(tol, z, y, buf);
/* z = QQR(x) with user-defined function */
gsl_movstat_apply(etype, &F, x, z, w);
sprintf(buf, "n=%zu H=%zu J=%zu endtype=%u QQR user", n, H, J, etype);
compare_vectors(tol, z, y, buf);
gsl_movstat_free(w);
gsl_vector_free(x);
gsl_vector_free(y);
gsl_vector_free(z);
}
static void
test_qqr(gsl_rng * rng_p)
{
const double eps = 1.0e-10;
test_qqr_proc(eps, 0.1, 100, 0, 0, GSL_MOVSTAT_END_PADZERO, rng_p);
test_qqr_proc(eps, 0.1, 1000, 3, 3, GSL_MOVSTAT_END_PADZERO, rng_p);
test_qqr_proc(eps, 0.2, 1000, 0, 5, GSL_MOVSTAT_END_PADZERO, rng_p);
test_qqr_proc(eps, 0.3, 1000, 5, 0, GSL_MOVSTAT_END_PADZERO, rng_p);
test_qqr_proc(eps, 0.25, 2000, 10, 5, GSL_MOVSTAT_END_PADZERO, rng_p);
test_qqr_proc(eps, 0.4, 2000, 5, 10, GSL_MOVSTAT_END_PADZERO, rng_p);
test_qqr_proc(eps, 0.25, 20, 50, 50, GSL_MOVSTAT_END_PADZERO, rng_p);
test_qqr_proc(eps, 0.25, 20, 10, 50, GSL_MOVSTAT_END_PADZERO, rng_p);
test_qqr_proc(eps, 0.25, 20, 50, 10, GSL_MOVSTAT_END_PADZERO, rng_p);
test_qqr_proc(eps, 0.1, 100, 0, 0, GSL_MOVSTAT_END_PADVALUE, rng_p);
test_qqr_proc(eps, 0.1, 1000, 3, 3, GSL_MOVSTAT_END_PADVALUE, rng_p);
test_qqr_proc(eps, 0.2, 1000, 0, 5, GSL_MOVSTAT_END_PADVALUE, rng_p);
test_qqr_proc(eps, 0.3, 1000, 5, 0, GSL_MOVSTAT_END_PADVALUE, rng_p);
test_qqr_proc(eps, 0.25, 2000, 10, 5, GSL_MOVSTAT_END_PADVALUE, rng_p);
test_qqr_proc(eps, 0.4, 2000, 5, 10, GSL_MOVSTAT_END_PADVALUE, rng_p);
test_qqr_proc(eps, 0.25, 20, 50, 50, GSL_MOVSTAT_END_PADVALUE, rng_p);
test_qqr_proc(eps, 0.25, 20, 10, 50, GSL_MOVSTAT_END_PADVALUE, rng_p);
test_qqr_proc(eps, 0.25, 20, 50, 10, GSL_MOVSTAT_END_PADVALUE, rng_p);
test_qqr_proc(eps, 0.1, 100, 0, 0, GSL_MOVSTAT_END_TRUNCATE, rng_p);
test_qqr_proc(eps, 0.1, 1000, 3, 3, GSL_MOVSTAT_END_TRUNCATE, rng_p);
test_qqr_proc(eps, 0.2, 1000, 0, 5, GSL_MOVSTAT_END_TRUNCATE, rng_p);
test_qqr_proc(eps, 0.3, 1000, 5, 0, GSL_MOVSTAT_END_TRUNCATE, rng_p);
test_qqr_proc(eps, 0.25, 2000, 10, 5, GSL_MOVSTAT_END_TRUNCATE, rng_p);
test_qqr_proc(eps, 0.4, 2000, 5, 10, GSL_MOVSTAT_END_TRUNCATE, rng_p);
test_qqr_proc(eps, 0.25, 20, 50, 50, GSL_MOVSTAT_END_TRUNCATE, rng_p);
test_qqr_proc(eps, 0.25, 20, 10, 50, GSL_MOVSTAT_END_TRUNCATE, rng_p);
test_qqr_proc(eps, 0.25, 20, 50, 10, GSL_MOVSTAT_END_TRUNCATE, rng_p);
}
| {
"alphanum_fraction": 0.6955534532,
"avg_line_length": 35.7094594595,
"ext": "c",
"hexsha": "b823653cdca95d3ca660ef28fb52cda0915c968b",
"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_qqr.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_qqr.c",
"max_line_length": 95,
"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_qqr.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": 1899,
"size": 5285
} |
#pragma once
#include <gsl/gsl>
#include <typeindex>
#include "halley/utils/utils.h"
#include "halley/data_structures/maybe.h"
#include "halley/file/byte_serializer.h"
namespace Halley
{
class IMessageStream;
class MessageQueue;
class MessageQueueUDP;
class MessageQueueTCP;
class NetworkMessage
{
friend class MessageQueue;
friend class MessageQueueUDP;
friend class MessageQueueTCP;
public:
virtual ~NetworkMessage() = default;
size_t getSerializedSize() const
{
if (!serialized) {
serialized = Serializer::toBytes(*this);
}
return serialized.get().size();
}
void serializeTo(gsl::span<gsl::byte> dst) const
{
if (!serialized) {
serialized = Serializer::toBytes(*this);
}
memcpy(dst.data(), serialized.get().data(), serialized.get().size());
}
virtual void serialize(Serializer& s) const = 0;
private:
unsigned short seq = 0;
char channel = -1;
mutable Maybe<Bytes> serialized;
};
class NetworkMessageFactoryBase
{
public:
virtual ~NetworkMessageFactoryBase() {}
virtual std::unique_ptr<NetworkMessage> create(gsl::span<const gsl::byte> src) const = 0;
virtual std::type_index getTypeIndex() const = 0;
};
template <typename T>
class NetworkMessageFactory : public NetworkMessageFactoryBase
{
public:
std::unique_ptr<NetworkMessage> create(gsl::span<const gsl::byte> src) const override
{
return std::make_unique<T>(src);
}
std::type_index getTypeIndex() const override
{
return std::type_index(typeid(T));
}
};
}
| {
"alphanum_fraction": 0.7086614173,
"avg_line_length": 20.8767123288,
"ext": "h",
"hexsha": "9aa10fcde0463d06f8c45b1ee09185e219160c17",
"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/net/include/halley/net/connection/network_message.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/net/include/halley/net/connection/network_message.h",
"max_line_length": 91,
"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/net/include/halley/net/connection/network_message.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 398,
"size": 1524
} |
/* $Id$ */
/*
* Copyright (c) 2014, 2015 Kristaps Dzonsons <kristaps@kcons.eu>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <assert.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#ifdef MAC_INTEGRATION
#include <gtkosxapplication.h>
#endif
#include <gtk/gtk.h>
#include <gdk/gdk.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_multifit.h>
#include <gsl/gsl_histogram.h>
#include <kplot.h>
#include "extern.h"
/*
* Brute-force scan all possible pi values (and Poisson means) by
* scanning through the strategy space.
*/
int
rangefind(struct bmigrate *b)
{
size_t mutants;
double mstrat, istrat, v;
gchar buf[22];
g_assert(b->rangeid);
/*
* Set the number of mutants on a given island, then see what
* the utility function would yield given that number of mutants
* and incumbents, setting the current player to be one or the
* other..
*/
mstrat = istrat = 0.0;
for (mutants = 0; mutants <= b->range.n; mutants++) {
mstrat = b->range.ymin +
(b->range.slicey / (double)b->range.slices) *
(b->range.ymax - b->range.ymin);
istrat = b->range.xmin +
(b->range.slicex / (double)b->range.slices) *
(b->range.xmax - b->range.xmin);
/*
* Only check for a given mutant/incumbent individual's
* strategy if the population is going to support the
* existence of that individual.
*/
if (mutants > 0) {
v = hnode_exec
((const struct hnode *const *)
b->range.exp,
istrat, mstrat * mutants + istrat *
(b->range.n - mutants), b->range.n);
if (0.0 != v && ! isnormal(v))
break;
if (v < b->range.pimin)
b->range.pimin = v;
if (v > b->range.pimax)
b->range.pimax = v;
b->range.piaggr += v;
b->range.picount++;
}
if (mutants != b->range.n) {
v = hnode_exec
((const struct hnode *const *)
b->range.exp,
mstrat, mstrat * mutants + istrat *
(b->range.n - mutants), b->range.n);
if (0.0 != v && ! isnormal(v))
break;
if (v < b->range.pimin)
b->range.pimin = v;
if (v > b->range.pimax)
b->range.pimax = v;
b->range.piaggr += v;
b->range.picount++;
}
}
/*
* We might have hit a discontinuous number.
* If we did, then print out an error and don't continue.
* If not, update to the next mutant and incumbent.
*/
if (mutants <= b->range.n) {
g_snprintf(buf, sizeof(buf),
"%zu mutants, mutant=%g, incumbent=%g",
mutants, mstrat, istrat);
gtk_label_set_text(b->wins.rangeerror, buf);
gtk_widget_show_all(GTK_WIDGET(b->wins.rangeerrorbox));
g_debug("Range-finder idle event complete (error)");
b->rangeid = 0;
} else {
if (++b->range.slicey == b->range.slices) {
b->range.slicey = 0;
b->range.slicex++;
}
if (b->range.slicex == b->range.slices) {
g_debug("Range-finder idle event complete");
b->rangeid = 0;
}
}
/*
* Set our current extrema.
*/
g_snprintf(buf, sizeof(buf), "%g", b->range.pimin);
gtk_label_set_text(b->wins.rangemin, buf);
g_snprintf(buf, sizeof(buf), "%g", b->range.alpha *
(1.0 + b->range.delta * b->range.pimin));
gtk_label_set_text(b->wins.rangeminlambda, buf);
g_snprintf(buf, sizeof(buf), "%g", b->range.pimax);
gtk_label_set_text(b->wins.rangemax, buf);
g_snprintf(buf, sizeof(buf), "%g", b->range.alpha *
(1.0 + b->range.delta * b->range.pimax));
gtk_label_set_text(b->wins.rangemaxlambda, buf);
v = b->range.piaggr / (double)b->range.picount;
g_snprintf(buf, sizeof(buf), "%g", v);
gtk_label_set_text(b->wins.rangemean, buf);
g_snprintf(buf, sizeof(buf), "%g", b->range.alpha *
(1.0 + b->range.delta * v));
gtk_label_set_text(b->wins.rangemeanlambda, buf);
v = (b->range.slicex * b->range.slices + b->range.slicey) /
(double)(b->range.slices * b->range.slices);
g_snprintf(buf, sizeof(buf), "%.1f%%", v * 100.0);
gtk_label_set_text(b->wins.rangestatus, buf);
return(0 != b->rangeid);
}
| {
"alphanum_fraction": 0.6530612245,
"avg_line_length": 29.9802631579,
"ext": "c",
"hexsha": "216d845ef5261b6bdfb7f969287419991d72ff8e",
"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": "0280a899564031a5a14af87d9264cd239a89851f",
"max_forks_repo_licenses": [
"0BSD"
],
"max_forks_repo_name": "kristapsdz/bmigrate",
"max_forks_repo_path": "rangefind.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "0280a899564031a5a14af87d9264cd239a89851f",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"0BSD"
],
"max_issues_repo_name": "kristapsdz/bmigrate",
"max_issues_repo_path": "rangefind.c",
"max_line_length": 75,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "0280a899564031a5a14af87d9264cd239a89851f",
"max_stars_repo_licenses": [
"0BSD"
],
"max_stars_repo_name": "kristapsdz/bmigrate",
"max_stars_repo_path": "rangefind.c",
"max_stars_repo_stars_event_max_datetime": "2018-03-03T17:13:19.000Z",
"max_stars_repo_stars_event_min_datetime": "2018-03-03T17:13:19.000Z",
"num_tokens": 1410,
"size": 4557
} |
#ifndef ABLATE_FLUXDIFFERENCER_H
#define ABLATE_FLUXDIFFERENCER_H
#include <petsc.h>
typedef void (*FluxDifferencerFunction)(PetscReal Mm, PetscReal* sPm, PetscReal* sMm,
PetscReal Mp, PetscReal* sPp, PetscReal *sMp);
#endif | {
"alphanum_fraction": 0.6740740741,
"avg_line_length": 33.75,
"ext": "h",
"hexsha": "4971097bea2252efc0afef2149b109ced10cde10",
"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": "8c8443de8a252b03b3535f7c48b7a50aac1e56e4",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "pakserep/ablate",
"max_forks_repo_path": "ablateCore/flow/fluxDifferencer.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "8c8443de8a252b03b3535f7c48b7a50aac1e56e4",
"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": "pakserep/ablate",
"max_issues_repo_path": "ablateCore/flow/fluxDifferencer.h",
"max_line_length": 90,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "8c8443de8a252b03b3535f7c48b7a50aac1e56e4",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "pakserep/ablate",
"max_stars_repo_path": "ablateCore/flow/fluxDifferencer.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 79,
"size": 270
} |
/* rstat/rstat.c
*
* Copyright (C) 2015 Patrick Alken
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include <config.h>
#include <stdlib.h>
#include <math.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_rstat.h>
gsl_rstat_workspace *
gsl_rstat_alloc(void)
{
gsl_rstat_workspace *w;
w = calloc(1, sizeof(gsl_rstat_workspace));
if (w == 0)
{
GSL_ERROR_NULL ("failed to allocate space for workspace", GSL_ENOMEM);
}
w->median_workspace_p = gsl_rstat_quantile_alloc(0.5);
if (w->median_workspace_p == 0)
{
GSL_ERROR_NULL ("failed to allocate space for median workspace",
GSL_ENOMEM);
}
gsl_rstat_reset(w);
return w;
} /* gsl_rstat_alloc() */
void
gsl_rstat_free(gsl_rstat_workspace *w)
{
if (w->median_workspace_p)
gsl_rstat_quantile_free(w->median_workspace_p);
free(w);
} /* gsl_rstat_free() */
size_t
gsl_rstat_n(const gsl_rstat_workspace *w)
{
return w->n;
} /* gsl_rstat_n() */
/* add a data point to the running totals */
int
gsl_rstat_add(const double x, gsl_rstat_workspace *w)
{
double delta = x - w->mean;
double delta_n, delta_nsq, term1, n;
/* update min and max */
if (w->n == 0)
{
w->min = x;
w->max = x;
}
else
{
if (x < w->min)
w->min = x;
if (x > w->max)
w->max = x;
}
/* update mean and variance */
n = (double) ++(w->n);
delta_n = delta / n;
delta_nsq = delta_n * delta_n;
term1 = delta * delta_n * (n - 1.0);
w->mean += delta_n;
w->M4 += term1 * delta_nsq * (n * n - 3.0 * n + 3.0) +
6.0 * delta_nsq * w->M2 - 4.0 * delta_n * w->M3;
w->M3 += term1 * delta_n * (n - 2.0) - 3.0 * delta_n * w->M2;
w->M2 += term1;
/* update median */
gsl_rstat_quantile_add(x, w->median_workspace_p);
return GSL_SUCCESS;
} /* gsl_rstat_add() */
double
gsl_rstat_min(const gsl_rstat_workspace *w)
{
return w->min;
} /* gsl_rstat_min() */
double
gsl_rstat_max(const gsl_rstat_workspace *w)
{
return w->max;
} /* gsl_rstat_max() */
double
gsl_rstat_mean(const gsl_rstat_workspace *w)
{
return w->mean;
} /* gsl_rstat_mean() */
double
gsl_rstat_variance(const gsl_rstat_workspace *w)
{
if (w->n > 1)
{
double n = (double) w->n;
return (w->M2 / (n - 1.0));
}
else
return 0.0;
} /* gsl_rstat_variance() */
double
gsl_rstat_sd(const gsl_rstat_workspace *w)
{
double var = gsl_rstat_variance(w);
return (sqrt(var));
} /* gsl_rstat_sd() */
double
gsl_rstat_rms(const gsl_rstat_workspace *w)
{
double rms = 0.0;
if (w->n > 0)
{
double mean = gsl_rstat_mean(w);
double sigma = gsl_rstat_sd(w);
double n = (double) w->n;
double a = sqrt((n - 1.0) / n);
rms = gsl_hypot(mean, a * sigma);
}
return rms;
}
/* standard deviation of the mean: sigma / sqrt(n) */
double
gsl_rstat_sd_mean(const gsl_rstat_workspace *w)
{
if (w->n > 0)
{
double sd = gsl_rstat_sd(w);
return (sd / sqrt((double) w->n));
}
else
return 0.0;
} /* gsl_rstat_sd_mean() */
double
gsl_rstat_median(gsl_rstat_workspace *w)
{
return gsl_rstat_quantile_get(w->median_workspace_p);
}
double
gsl_rstat_skew(const gsl_rstat_workspace *w)
{
if (w->n > 0)
{
double n = (double) w->n;
double fac = pow(n - 1.0, 1.5) / n;
return ((fac * w->M3) / pow(w->M2, 1.5));
}
else
return 0.0;
} /* gsl_rstat_skew() */
double
gsl_rstat_kurtosis(const gsl_rstat_workspace *w)
{
if (w->n > 0)
{
double n = (double) w->n;
double fac = ((n - 1.0) / n) * (n - 1.0);
return ((fac * w->M4) / (w->M2 * w->M2) - 3.0);
}
else
return 0.0;
} /* gsl_rstat_kurtosis() */
int
gsl_rstat_reset(gsl_rstat_workspace *w)
{
int status;
w->min = 0.0;
w->max = 0.0;
w->mean = 0.0;
w->M2 = 0.0;
w->M3 = 0.0;
w->M4 = 0.0;
w->n = 0;
status = gsl_rstat_quantile_reset(w->median_workspace_p);
return status;
} /* gsl_rstat_reset() */
| {
"alphanum_fraction": 0.619763695,
"avg_line_length": 20.9684684685,
"ext": "c",
"hexsha": "0808622876e1a4cc955857022f6d080826e61666",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z",
"max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "Brian-ning/HMNE",
"max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/rstat/rstat.c",
"max_issues_count": 6,
"max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e",
"max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z",
"max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "Brian-ning/HMNE",
"max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/rstat/rstat.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/rstat/rstat.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": 1535,
"size": 4655
} |
/* sort/test.c
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000 Thomas Walter, Brian Gough
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <config.h>
#include <stdio.h>
#include <stdlib.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_test.h>
#include <gsl/gsl_heapsort.h>
#include <gsl/gsl_sort.h>
#include <gsl/gsl_sort_vector.h>
#include <gsl/gsl_ieee_utils.h>
size_t urand (size_t);
#include "test_heapsort.c"
#define BASE_LONG_DOUBLE
#include "templates_on.h"
#include "test_source.c"
#include "templates_off.h"
#undef BASE_LONG_DOUBLE
#define BASE_DOUBLE
#include "templates_on.h"
#include "test_source.c"
#include "templates_off.h"
#undef BASE_DOUBLE
#define BASE_FLOAT
#include "templates_on.h"
#include "test_source.c"
#include "templates_off.h"
#undef BASE_FLOAT
#define BASE_ULONG
#include "templates_on.h"
#include "test_source.c"
#include "templates_off.h"
#undef BASE_ULONG
#define BASE_LONG
#include "templates_on.h"
#include "test_source.c"
#include "templates_off.h"
#undef BASE_LONG
#define BASE_UINT
#include "templates_on.h"
#include "test_source.c"
#include "templates_off.h"
#undef BASE_UINT
#define BASE_INT
#include "templates_on.h"
#include "test_source.c"
#include "templates_off.h"
#undef BASE_INT
#define BASE_USHORT
#include "templates_on.h"
#include "test_source.c"
#include "templates_off.h"
#undef BASE_USHORT
#define BASE_SHORT
#include "templates_on.h"
#include "test_source.c"
#include "templates_off.h"
#undef BASE_SHORT
#define BASE_UCHAR
#include "templates_on.h"
#include "test_source.c"
#include "templates_off.h"
#undef BASE_UCHAR
#define BASE_CHAR
#include "templates_on.h"
#include "test_source.c"
#include "templates_off.h"
#undef BASE_CHAR
int
main (void)
{
size_t i, s;
gsl_ieee_env_setup ();
/* Test for lengths of 1 ... 31, then 32, 64, 128, 256, ... */
for (i = 1; i < 1024; i = (i < 32) ? i + 1 : 2 * i)
test_heapsort (i);
for (i = 1; i < 1024; i = (i < 32) ? i + 1 : 2 * i)
{
for (s = 1; s < 4; s++)
{
test_sort_vector (i, s);
test_sort_vector_float (i, s);
test_sort_vector_long_double (i, s);
test_sort_vector_ulong (i, s);
test_sort_vector_long (i, s);
test_sort_vector_uint (i, s);
test_sort_vector_int (i, s);
test_sort_vector_ushort (i, s);
test_sort_vector_short (i, s);
test_sort_vector_uchar (i, s);
test_sort_vector_char (i, s);
}
}
exit (gsl_test_summary ());
}
size_t
urand (size_t N)
{
static unsigned long int x = 1;
x = (1103515245 * x + 12345) & 0x7fffffffUL;
return (size_t) ((x / 2147483648.0) * N);
}
| {
"alphanum_fraction": 0.7118384827,
"avg_line_length": 23.1843971631,
"ext": "c",
"hexsha": "69a568535fd0f0bf729479590a8d340e32eaf81b",
"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/sort/test.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "ICML14MoMCompare/spectral-learn",
"max_issues_repo_path": "code/em/treba/gsl-1.0/sort/test.c",
"max_line_length": 72,
"max_stars_count": 14,
"max_stars_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "ICML14MoMCompare/spectral-learn",
"max_stars_repo_path": "code/em/treba/gsl-1.0/sort/test.c",
"max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z",
"num_tokens": 934,
"size": 3269
} |
#include <gsl/gsl_matrix.h>
#include "kexpr.h"
#include "matrix.h"
#include "api.h"
static void ke_matrix_alloc(sml_t* sml) {
int n1 = sml_pop_int(sml);
int n2 = sml_pop_int(sml);
gsl_matrix * m = gsl_matrix_alloc(n1,n2);
sml_mem_inc(sml);
sml_push_matrix(sml, m)
}
void ke_matrix_prop_get(sml_t* sml) {
gsl_matrix * m = sml_pop_matrix(sml);
int j = sml_pop_int(sml);
int i = sml_pop_int(sml);
double r = gsl_matrix_get(m, i, j);
sml_push_real(sml, r);
}
void ke_matrix_get(sml_t* sml) {
int j = sml_pop_int(sml);
int i = sml_pop_int(sml);
gsl_matrix * m = sml_pop_matrix(sml);
double r = gsl_matrix_get(m,i,j);
sml_push_real(sml, r);
}
void ke_matrix_prop_set(sml_t* sml) {
double x = sml_pop_real(sml);
gsl_matrix * m = sml_pop_matrix(sml);
int j = sml_pop_int(sml);
int i = sml_pop_int(sml);
gsl_matrix_set(m, i, j, x);
}
static void ke_matrix_set(sml_t* sml) {
double x = sml_pop_real(sml);
int j = sml_pop_int(sml);
int i = sml_pop_int(sml);
gsl_matrix * m = sml_pop_matrix(sml);
gsl_matrix_set(m,i, j, x);
}
static void ke_matrix_put_row(sml_t* sml) {
int top = sml_get_top(sml);
int n = sml_get_args(sml);
gsl_matrix * m = sml_peek_matrix(sml,(top-n));
int i = sml_peek_int(sml,(top-n+1));
for (size_t j = 0; j < n - 2; ++j) {
if (j == m->size2) break;
double x = sml_peek_real(sml, (top - n + j + 2));
gsl_matrix_set(m, i, j, x);
}
top = top - n;
sml_set_top(sml, top);
}
static void ke_matrix_put_col(sml_t* sml) {
int top = sml_get_top(sml);
int n = sml_get_args(sml);
gsl_matrix * m = sml_peek_matrix(sml, (top - n));
int j = sml_peek_int(sml, (top - n + 1));
for (size_t i = 0; i < n - 2; ++i) {
if (i == m->size2) break;
double x = sml_peek_real(sml, (top - n + i + 2));
gsl_matrix_set(m, i, j, x);
}
top = top - n;
sml_set_top(sml, top);
}
static void ke_matrix_free(sml_t* sml) {
token_t * tokp = sml_pop_token(sml);
void * m = sml_get_ptr(tokp);
sml_free_ptr(sml, m);
sml_set_ptr_null(sml,tokp);
}
static void ke_matrix_set_all(sml_t* sml) {
double x = sml_pop_real(sml);
gsl_matrix * m = sml_pop_matrix(sml);
gsl_matrix_set_all(m,x);
}
static void ke_matrix_set_zero(sml_t* sml) {
gsl_matrix * m = sml_pop_matrix(sml);
gsl_matrix_set_zero(m);
}
static void ke_matrix_set_identity(sml_t* sml) {
gsl_matrix * m = sml_pop_matrix(sml);
gsl_matrix_set_identity(m);
}
static void ke_matrix_swap_rows(sml_t* sml) {
int j = sml_pop_int(sml);
int i = sml_pop_int(sml);
gsl_matrix * m = sml_pop_matrix(sml);
gsl_matrix_swap_rows(m, i, j);
}
static void ke_matrix_swap_columns(sml_t* sml) {
int j = sml_pop_int(sml);
int i = sml_pop_int(sml);
gsl_matrix * m = sml_pop_matrix(sml);
gsl_matrix_swap_columns(m,i,j);
}
static void ke_matrix_rowcol(sml_t* sml) {
int j = sml_pop_int(sml);
int i = sml_pop_int(sml);
gsl_matrix * m = sml_pop_matrix(sml);
gsl_matrix_swap_rowcol(m,i,j);
}
static void ke_matrix_transpose_memcpy(sml_t* sml) {
gsl_matrix * src = sml_pop_matrix(sml);
gsl_matrix * dest = sml_pop_matrix(sml);
gsl_matrix_transpose_memcpy(dest, src);
}
static void ke_matrix_transpose(sml_t* sml) {
gsl_matrix * m = sml_pop_matrix(sml);
gsl_matrix_transpose(m);
}
static void ke_matrix_add(sml_t* sml) {
gsl_matrix * b = sml_pop_matrix(sml);
gsl_matrix * a = sml_pop_matrix(sml);
gsl_matrix_add(a,b);
}
static void ke_matrix_sub(sml_t* sml) {
gsl_matrix * b = sml_pop_matrix(sml);
gsl_matrix * a = sml_pop_matrix(sml);
gsl_matrix_sub(a,b);
}
static void ke_matrix_mul_elements(sml_t* sml) {
gsl_matrix * b = sml_pop_matrix(sml);
gsl_matrix * a = sml_pop_matrix(sml);
gsl_matrix_mul_elements(a,b);
}
static void ke_matrix_div_elements(sml_t* sml) {
gsl_matrix * b = sml_pop_matrix(sml);
gsl_matrix * a = sml_pop_matrix(sml);
gsl_matrix_div_elements(a,b);
}
static void ke_matrix_scale(sml_t* sml) {
double x = sml_pop_real(sml);
gsl_matrix * m = sml_pop_matrix(sml);
gsl_matrix_scale(m,x);
}
static void ke_matrix_add_constant(sml_t* sml) {
double x = sml_pop_real(sml);
gsl_matrix * m = sml_pop_matrix(sml);
gsl_matrix_add_constant(m, x);
}
static void ke_matrix_memcpy(sml_t* sml) {
gsl_matrix * src = sml_pop_matrix(sml);
gsl_matrix * dest = sml_pop_matrix(sml);
gsl_matrix_memcpy(dest,src);
}
static void ke_matrix_swap(sml_t* sml) {
gsl_matrix * m2 = sml_pop_matrix(sml);
gsl_matrix * m1 = sml_pop_matrix(sml);
gsl_matrix_swap(m1,m2);
}
static void ke_matrix_min(sml_t* sml) {
gsl_matrix * m = sml_pop_matrix(sml);
double r = gsl_matrix_min(m);
sml_push_real(sml, r);
}
static void ke_matrix_max(sml_t* sml) {
gsl_matrix * m = sml_pop_matrix(sml);
double r = gsl_matrix_max(m);
sml_push_real(sml, r);
}
static void ke_matrix_isnull(sml_t* sml) {
gsl_matrix * m = sml_pop_matrix(sml);
int i = gsl_matrix_isnull(m);
sml_push_int(sml, i);
}
static void ke_matrix_ispos(sml_t* sml) {
gsl_matrix * m = sml_pop_matrix(sml);
int i = gsl_matrix_ispos(m);
sml_push_int(sml, i);
}
static void ke_matrix_isneg(sml_t* sml) {
gsl_matrix * m = sml_pop_matrix(sml);
int i = gsl_matrix_isneg(m);
sml_push_int(sml, i);
}
static void ke_matrix_isnonneg(sml_t* sml) {
gsl_matrix * m = sml_pop_matrix(sml);
int i = gsl_matrix_isnonneg(m);
sml_push_int(sml, i);
}
static void ke_matrix_equal(sml_t* sml) {
gsl_matrix * b = sml_pop_matrix(sml);
gsl_matrix * a = sml_pop_matrix(sml);
int i = gsl_matrix_equal(a,b);
sml_push_int(sml, i);
}
static void ke_matrix_fscanf(sml_t* sml) {
char * filename = sml_pop_str(sml);
gsl_matrix * m = sml_pop_matrix(sml);
FILE * f = fopen(filename, "r");
gsl_matrix_fscanf(f, m);
fclose(f);
}
static void ke_matrix_fprintf(sml_t* sml) {
gsl_matrix * m = sml_pop_matrix(sml);
char * filename = sml_pop_str(sml);
FILE * f = fopen(filename, "w");
gsl_matrix_fprintf(f, m,"%5g");
fclose(f);
}
static void ke_matrix_fread(sml_t* sml) {
gsl_matrix * m = sml_pop_matrix(sml);
char * filename = sml_pop_str(sml);
FILE * f = fopen(filename, "r");
gsl_matrix_fread(f, m);
fclose(f);
}
static void ke_matrix_fwrite(sml_t* sml) {
token_t **stack = sml->stack;
gsl_matrix * m = sml_pop_matrix(sml);
char * filename = sml_pop_str(sml);
FILE * f = fopen(filename, "w");
gsl_matrix_fwrite(f, m);
fclose(f);
}
void ke_matrix_hash(sml_t * sml) {
ke_hash_add(sml, (fncp)&ke_matrix_alloc, MATRIX);
ke_hash_add(sml, (fncp)&ke_matrix_alloc, MATRIX_ALLOC);
ke_hash_add(sml, (fncp)&ke_matrix_get, MATRIX_GET);
ke_hash_add(sml, (fncp)&ke_matrix_set, MATRIX_SET);
ke_hash_add(sml, (fncp)&ke_matrix_put_row, MATRIX_PUT_ROW);
ke_hash_add(sml, (fncp)&ke_matrix_put_col, MATRIX_PUT_COL);
ke_hash_add(sml, (fncp)&ke_matrix_free, MATRIX_FREE);
ke_hash_add(sml, (fncp)&ke_matrix_set_all, MATRIX_SET_ALL);
ke_hash_add(sml, (fncp)&ke_matrix_set_zero,MATRIX_SET_ZERO);
ke_hash_add(sml, (fncp)&ke_matrix_set_identity,MATRIX_SET_IDENTITY);
ke_hash_add(sml, (fncp)&ke_matrix_swap_rows,MATRIX_SWAP_ROWS);
ke_hash_add(sml, (fncp)&ke_matrix_swap_columns,MATRIX_SWAP_COLUMNS);
ke_hash_add(sml, (fncp)&ke_matrix_rowcol,MATRIX_SWAP_ROWCOL);
ke_hash_add(sml, (fncp)&ke_matrix_transpose_memcpy,MATRIX_TRANSPOSE_MEMCPY);
ke_hash_add(sml, (fncp)&ke_matrix_transpose,MATRIX_TRANSPOSE);
ke_hash_add(sml, (fncp)&ke_matrix_add,MATRIX_ADD);
ke_hash_add(sml, (fncp)&ke_matrix_sub,MATRIX_SUB);
ke_hash_add(sml, (fncp)&ke_matrix_mul_elements,MATRIX_MUL);
ke_hash_add(sml, (fncp)&ke_matrix_mul_elements,MATRIX_MUL_ELEMENTS);
ke_hash_add(sml, (fncp)&ke_matrix_div_elements,MATRIX_DIV);
ke_hash_add(sml, (fncp)&ke_matrix_div_elements,MATRIX_DIV_ELEMENTS);
ke_hash_add(sml, (fncp)&ke_matrix_scale,MATRIX_SCALE);
ke_hash_add(sml, (fncp)&ke_matrix_add_constant,MATRIX_ADD_CONSTANT);
ke_hash_add(sml, (fncp)&ke_matrix_memcpy,MATRIX_MEMCPY);
ke_hash_add(sml, (fncp)&ke_matrix_swap,MATRIX_SWAP);
ke_hash_add(sml, (fncp)&ke_matrix_min,MATRIX_MIN);
ke_hash_add(sml, (fncp)&ke_matrix_max,MATRIX_MAX);
ke_hash_add(sml, (fncp)&ke_matrix_isnull,MATRIX_ISNULL);
ke_hash_add(sml, (fncp)&ke_matrix_ispos,MATRIX_ISPOS);
ke_hash_add(sml, (fncp)&ke_matrix_isneg,MATRIX_ISNEG);
ke_hash_add(sml, (fncp)&ke_matrix_isnonneg,MATRIX_ISNONNEG);
ke_hash_add(sml, (fncp)&ke_matrix_equal,MATRIX_EQUAL);
ke_hash_add(sml, (fncp)&ke_matrix_fscanf,MATRIX_FSCANF);
ke_hash_add(sml, (fncp)&ke_matrix_fscanf,MATRIX_SCAN);
ke_hash_add(sml, (fncp)&ke_matrix_fprintf,MATRIX_FPRINTF);
ke_hash_add(sml, (fncp)&ke_matrix_fprintf,MATRIX_PRINT);
ke_hash_add(sml, (fncp)&ke_matrix_fread,MATRIX_FREAD);
ke_hash_add(sml, (fncp)&ke_matrix_fread,MATRIX_READ);
ke_hash_add(sml, (fncp)&ke_matrix_fwrite,MATRIX_FWRITE);
ke_hash_add(sml, (fncp)&ke_matrix_fwrite,MATRIX_WRITE);
}
void ke_matrix_print(sml_t* sml, token_t *k) {
printf("Matrix: %s\n", k->name);
for(size_t i = 0; i < k->obj.matrix->size1; i++)
for(size_t j = 0; j < k->obj.matrix->size2; j++)
printf("%d,%d : v:%g\n", (int)i, (int)j, gsl_matrix_get(k->obj.matrix, i,j));
}
void ke_matrix_freemem(sml_t* sml, token_t *e) {
if (e->obj.matrix && e->vtype == KEV_MAT) {
gsl_matrix_free(e->obj.matrix); ke_dec_memory(sml);
e->obj.matrix = NULL;
}
}
| {
"alphanum_fraction": 0.7093474047,
"avg_line_length": 29.9548387097,
"ext": "c",
"hexsha": "bdcd215fc270b0173dc82dda44fce2f1406d5d8d",
"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": "115c007926ca80d51a37cdf887b5252338d8bc8d",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "vinej/sml",
"max_forks_repo_path": "matrix.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "115c007926ca80d51a37cdf887b5252338d8bc8d",
"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": "vinej/sml",
"max_issues_repo_path": "matrix.c",
"max_line_length": 89,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "115c007926ca80d51a37cdf887b5252338d8bc8d",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "vinej/sml",
"max_stars_repo_path": "matrix.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 3107,
"size": 9286
} |
/* movstat/test_Qn.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_statistics.h>
#include <gsl/gsl_sort.h>
#include <gsl/gsl_test.h>
#include <gsl/gsl_movstat.h>
/* calculate Q_n statistic for input vector using slow/naive algorithm */
static int
slow_movQn(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));
double *work = malloc(3 * K * sizeof(double));
int *work_int = malloc(5 * K * sizeof(int));
size_t i;
for (i = 0; i < n; ++i)
{
size_t wsize = gsl_movstat_fill(etype, x, i, H, J, window);
double Qn;
gsl_sort(window, 1, wsize);
Qn = gsl_stats_Qn_from_sorted_data(window, 1, wsize, work, work_int);
gsl_vector_set(y, i, Qn);
}
free(window);
free(work);
free(work_int);
return GSL_SUCCESS;
}
static double
func_Qn(const size_t n, double x[], void * params)
{
double *work = malloc(3 * n * sizeof(double));
int *work_int = malloc(5 * n * sizeof(int));
double Qn;
(void) params;
gsl_sort(x, 1, n);
Qn = gsl_stats_Qn_from_sorted_data(x, 1, n, work, work_int);
free(work);
free(work_int);
return Qn;
}
static void
test_Qn_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_Qn;
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 = Q_n(x) with slow brute force algorithm */
slow_movQn(etype, x, y, H, J);
/* z = Q_n(x) */
gsl_movstat_Qn(etype, x, z, w);
/* test y = z */
sprintf(buf, "n=%zu H=%zu J=%zu endtype=%u Qn random", n, H, J, etype);
compare_vectors(tol, z, y, buf);
/* z = Q_n(x) in-place */
gsl_vector_memcpy(z, x);
gsl_movstat_Qn(etype, z, z, w);
sprintf(buf, "n=%zu H=%zu J=%zu endtype=%u Qn random in-place", n, H, J, etype);
compare_vectors(tol, z, y, buf);
/* z = Q_n(x) with user-defined function */
gsl_movstat_apply(etype, &F, x, z, w);
sprintf(buf, "n=%zu H=%zu J=%zu endtype=%u Qn 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_Qn(gsl_rng * rng_p)
{
test_Qn_proc(GSL_DBL_EPSILON, 1000, 0, 0, GSL_MOVSTAT_END_PADZERO, rng_p);
test_Qn_proc(GSL_DBL_EPSILON, 1000, 5, 5, GSL_MOVSTAT_END_PADZERO, rng_p);
test_Qn_proc(GSL_DBL_EPSILON, 1000, 5, 2, GSL_MOVSTAT_END_PADZERO, rng_p);
test_Qn_proc(GSL_DBL_EPSILON, 1000, 2, 5, GSL_MOVSTAT_END_PADZERO, rng_p);
test_Qn_proc(GSL_DBL_EPSILON, 2000, 50, 0, GSL_MOVSTAT_END_PADZERO, rng_p);
test_Qn_proc(GSL_DBL_EPSILON, 2000, 0, 50, GSL_MOVSTAT_END_PADZERO, rng_p);
test_Qn_proc(GSL_DBL_EPSILON, 20, 50, 50, GSL_MOVSTAT_END_PADZERO, rng_p);
test_Qn_proc(GSL_DBL_EPSILON, 20, 1, 50, GSL_MOVSTAT_END_PADZERO, rng_p);
test_Qn_proc(GSL_DBL_EPSILON, 20, 50, 1, GSL_MOVSTAT_END_PADZERO, rng_p);
test_Qn_proc(GSL_DBL_EPSILON, 1000, 0, 0, GSL_MOVSTAT_END_PADVALUE, rng_p);
test_Qn_proc(GSL_DBL_EPSILON, 1000, 5, 5, GSL_MOVSTAT_END_PADVALUE, rng_p);
test_Qn_proc(GSL_DBL_EPSILON, 1000, 5, 2, GSL_MOVSTAT_END_PADVALUE, rng_p);
test_Qn_proc(GSL_DBL_EPSILON, 1000, 2, 5, GSL_MOVSTAT_END_PADVALUE, rng_p);
test_Qn_proc(GSL_DBL_EPSILON, 2000, 50, 0, GSL_MOVSTAT_END_PADVALUE, rng_p);
test_Qn_proc(GSL_DBL_EPSILON, 2000, 0, 50, GSL_MOVSTAT_END_PADVALUE, rng_p);
test_Qn_proc(GSL_DBL_EPSILON, 20, 50, 50, GSL_MOVSTAT_END_PADVALUE, rng_p);
test_Qn_proc(GSL_DBL_EPSILON, 20, 1, 50, GSL_MOVSTAT_END_PADVALUE, rng_p);
test_Qn_proc(GSL_DBL_EPSILON, 20, 50, 1, GSL_MOVSTAT_END_PADVALUE, rng_p);
test_Qn_proc(GSL_DBL_EPSILON, 1000, 0, 0, GSL_MOVSTAT_END_TRUNCATE, rng_p);
test_Qn_proc(GSL_DBL_EPSILON, 1000, 5, 5, GSL_MOVSTAT_END_TRUNCATE, rng_p);
test_Qn_proc(GSL_DBL_EPSILON, 1000, 5, 2, GSL_MOVSTAT_END_TRUNCATE, rng_p);
test_Qn_proc(GSL_DBL_EPSILON, 1000, 2, 5, GSL_MOVSTAT_END_TRUNCATE, rng_p);
test_Qn_proc(GSL_DBL_EPSILON, 2000, 50, 0, GSL_MOVSTAT_END_TRUNCATE, rng_p);
test_Qn_proc(GSL_DBL_EPSILON, 2000, 0, 50, GSL_MOVSTAT_END_TRUNCATE, rng_p);
test_Qn_proc(GSL_DBL_EPSILON, 20, 50, 50, GSL_MOVSTAT_END_TRUNCATE, rng_p);
test_Qn_proc(GSL_DBL_EPSILON, 20, 1, 50, GSL_MOVSTAT_END_TRUNCATE, rng_p);
test_Qn_proc(GSL_DBL_EPSILON, 20, 50, 1, GSL_MOVSTAT_END_TRUNCATE, rng_p);
}
| {
"alphanum_fraction": 0.7128046562,
"avg_line_length": 34.7974683544,
"ext": "c",
"hexsha": "dea406525439c2dde1241bf2ce40a5f88adafaac",
"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_Qn.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_Qn.c",
"max_line_length": 82,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "ielomariala/Hex-Game",
"max_stars_repo_path": "gsl-2.6/movstat/test_Qn.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": 1897,
"size": 5498
} |
#include <stdio.h>
#include <stdlib.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_filter.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
#include <gsl/gsl_vector.h>
int
main(void)
{
const size_t N = 1000; /* length of time series */
const size_t K = 7; /* window size */
const double f = 5.0; /* frequency of square wave in Hz */
gsl_filter_median_workspace *median_p = gsl_filter_median_alloc(K);
gsl_filter_rmedian_workspace *rmedian_p = gsl_filter_rmedian_alloc(K);
gsl_vector *t = gsl_vector_alloc(N); /* time */
gsl_vector *x = gsl_vector_alloc(N); /* input vector */
gsl_vector *y_median = gsl_vector_alloc(N); /* median filtered output */
gsl_vector *y_rmedian = gsl_vector_alloc(N); /* recursive median filtered output */
gsl_rng *r = gsl_rng_alloc(gsl_rng_default);
size_t i;
/* generate input signal */
for (i = 0; i < N; ++i)
{
double ti = (double) i / (N - 1.0);
double tmp = sin(2.0 * M_PI * f * ti);
double xi = (tmp >= 0.0) ? 1.0 : -1.0;
double ei = gsl_ran_gaussian(r, 0.1);
gsl_vector_set(t, i, ti);
gsl_vector_set(x, i, xi + ei);
}
gsl_filter_median(GSL_FILTER_END_PADVALUE, x, y_median, median_p);
gsl_filter_rmedian(GSL_FILTER_END_PADVALUE, x, y_rmedian, rmedian_p);
/* print results */
for (i = 0; i < N; ++i)
{
double ti = gsl_vector_get(t, i);
double xi = gsl_vector_get(x, i);
double medi = gsl_vector_get(y_median, i);
double rmedi = gsl_vector_get(y_rmedian, i);
printf("%f %f %f %f\n",
ti,
xi,
medi,
rmedi);
}
gsl_vector_free(t);
gsl_vector_free(x);
gsl_vector_free(y_median);
gsl_vector_free(y_rmedian);
gsl_rng_free(r);
gsl_filter_median_free(median_p);
return 0;
}
| {
"alphanum_fraction": 0.5899948427,
"avg_line_length": 30.296875,
"ext": "c",
"hexsha": "a1dddaa2c9634aacae88419b9ea86c011340add2",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z",
"max_forks_repo_head_hexsha": "83fd1fc4cbd053a4f9b673d5cd5841823ddd4d8b",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "karanbirsandhu/nu-sense",
"max_forks_repo_path": "test/lib/gsl-2.6/doc/examples/filt_edge.c",
"max_issues_count": 6,
"max_issues_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a",
"max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z",
"max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "ielomariala/Hex-Game",
"max_issues_repo_path": "gsl-2.6/doc/examples/filt_edge.c",
"max_line_length": 93,
"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/filt_edge.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": 539,
"size": 1939
} |
/* ****************************************************************** **
** OpenSees - Open System for Earthquake Engineering Simulation **
** Pacific Earthquake Engineering Research Center **
** **
** **
** (C) Copyright 1999, The Regents of the University of California **
** All Rights Reserved. **
** **
** Commercial use of this program without express permission of the **
** University of California, Berkeley, is strictly prohibited. See **
** file 'COPYRIGHT' in main directory for information on usage and **
** redistribution, and for a DISCLAIMER OF ALL WARRANTIES. **
** **
** Developed by: **
** Frank McKenna (fmckenna@ce.berkeley.edu) **
** Gregory L. Fenves (fenves@ce.berkeley.edu) **
** Filip C. Filippou (filippou@ce.berkeley.edu) **
** **
** ****************************************************************** */
// $Revision: 1.1.1.1 $
// $Date: 2000-09-15 08:23:29 $
// $Source: /usr/local/cvs/OpenSees/SRC/system_of_eqn/linearSOE/petsc/ActorPetscSOE.h,v $
// File: ~/system_of_eqn/linearSOE/petsc/ActorPetscSOE.h
//
// Written: fmk & om
// Created: 7/98
// Revision: A
//
// Description: This file contains the class definition for ActorPetscSOE
// ActorPetscSOE is a subclass of LinearSOE. It uses the LAPACK storage
// scheme to store the components of the A matrix, which is a full matrix.
// What: "@(#) ActorPetscSOE.h, revA"
#ifndef ActorPetscSOE_h
#define ActorPetscSOE_h
#include <LinearSOE.h>
#include <Vector.h>
// extern "C" {
#include <petsc.h>
// }
class PetscSolver;
class PetscSOE;
class ActorPetscSOE
{
public:
ActorPetscSOE(PetscSolver &theSolver, int blockSize);
~ActorPetscSOE();
int run(void);
protected:
private:
MPI_Comm theComm;
PetscSOE *theSOE; // the local portion of the SOE
PetscSolver *theSolver; // created locally via data from process 0
int myRank;
int recvData[3];
void *recvBuffer;
int numProcessors;
};
#endif
| {
"alphanum_fraction": 0.4553113553,
"avg_line_length": 35.4545454545,
"ext": "h",
"hexsha": "afd80353db3d4510747670edec49ed1f5729e082",
"lang": "C",
"max_forks_count": 3,
"max_forks_repo_forks_event_max_datetime": "2020-01-19T07:29:37.000Z",
"max_forks_repo_forks_event_min_datetime": "2019-09-21T03:11:11.000Z",
"max_forks_repo_head_hexsha": "417c3be117992a108c6bbbcf5c9b63806b9362ab",
"max_forks_repo_licenses": [
"TCL"
],
"max_forks_repo_name": "steva44/OpenSees",
"max_forks_repo_path": "SRC/system_of_eqn/linearSOE/petsc/ActorPetscSOE.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "417c3be117992a108c6bbbcf5c9b63806b9362ab",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"TCL"
],
"max_issues_repo_name": "steva44/OpenSees",
"max_issues_repo_path": "SRC/system_of_eqn/linearSOE/petsc/ActorPetscSOE.h",
"max_line_length": 89,
"max_stars_count": 8,
"max_stars_repo_head_hexsha": "ccb350564df54f5c5ec3a079100effe261b46650",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "kuanshi/ductile-fracture",
"max_stars_repo_path": "OpenSees/SRC/system_of_eqn/linearSOE/petsc/ActorPetscSOE.h",
"max_stars_repo_stars_event_max_datetime": "2020-04-17T14:12:03.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-03-05T16:25:10.000Z",
"num_tokens": 557,
"size": 2730
} |
#pragma once
#include <gsl\gsl>
#include <winrt\Windows.Foundation.h>
#include <d3d11.h>
#include "DrawableGameComponent.h"
#include "MatrixHelper.h"
#include "PointLight.h"
#include "DepthMap.h"
#include "Rectangle.h"
#include "ShadowMappingMaterial.h"
#include "RenderStateHelper.h"
namespace DirectX
{
class SpriteBatch;
}
namespace Library
{
class ProxyModel;
class RenderableFrustum;
class DepthMapMaterial;
}
namespace Rendering
{
class ShadowMappingDemo final : public Library::DrawableGameComponent
{
public:
ShadowMappingDemo(Library::Game& game, const std::shared_ptr<Library::Camera>& camera);
ShadowMappingDemo(const ShadowMappingDemo&) = delete;
ShadowMappingDemo(ShadowMappingDemo&&) = default;
ShadowMappingDemo& operator=(const ShadowMappingDemo&) = default;
ShadowMappingDemo& operator=(ShadowMappingDemo&&) = default;
~ShadowMappingDemo();
ShadowMappingDrawModes DrawMode() const;
const std::string& DrawModeString() const;
void SetDrawMode(ShadowMappingDrawModes drawMode);
float DepthBias() const;
void SetDepthBias(float bias);
float SlopeScaledDepthBias() const;
void SetSlopeScaledDepthBias(float bias);
float AmbientLightIntensity() const;
void SetAmbientLightIntensity(float intensity);
float PointLightIntensity() const;
void SetPointLightIntensity(float intensity);
float PointLightRadius() const;
void SetPointLightRadius(float radius);
const Library::Camera& Projector() const;
const DirectX::XMFLOAT3& ProjectorPosition() const;
const DirectX::XMVECTOR ProjectorPositionVector() const;
void SetProjectorPosition(const DirectX::XMFLOAT3& position);
void SetProjectorPosition(DirectX::FXMVECTOR position);
const DirectX::XMFLOAT3& ProjectorDirection() const;
void RotateProjector(const DirectX::XMFLOAT2& amount);
virtual void Initialize() override;
virtual void Update(const Library::GameTime& gameTime) override;
virtual void Draw(const Library::GameTime& gameTime) override;
private:
inline static const std::uint32_t ShadowMapWidth{ 1024 };
inline static const std::uint32_t ShadowMapHeight{ 1024 };
static inline const RECT ShadowMapDestinationRectangle{ 0, 512, 256, 768 };
inline static DirectX::XMFLOAT4X4 mProjectedTextureScalingMatrix
{
0.5f, 0.0f, 0.0f, 0.0f,
0.0f, -0.5f, 0.0f, 0.0f,
0.0f, 0.0f, 1.0f, 0.0f,
0.5f, 0.5f, 0.0f, 1.0f
};
void UpdateTransforms(ShadowMappingMaterial::VertexCBufferPerObject& transforms, DirectX::FXMMATRIX worldViewProjectionMatrix, DirectX::CXMMATRIX worldMatrix, DirectX::CXMMATRIX projectiveTextureMatrix);
void UpdateDepthBiasRasterizerState();
ShadowMappingMaterial::VertexCBufferPerObject mPlaneTransforms;
ShadowMappingMaterial::VertexCBufferPerObject mTeapotTransforms;
DirectX::XMFLOAT4X4 mPlaneWorldMatrix{ Library::MatrixHelper::Identity };
DirectX::XMFLOAT4X4 mTeapotWorldMatrix{ Library::MatrixHelper::Identity };
Library::PointLight mPointLight;
Library::DepthMap mShadowMap;
Library::RenderStateHelper mRenderStateHelper;
std::shared_ptr<ShadowMappingMaterial> mMaterial;
std::shared_ptr<Library::DepthMapMaterial> mDepthMapMaterial;
winrt::com_ptr<ID3D11Buffer> mPlaneVertexBuffer;
winrt::com_ptr<ID3D11Buffer> mTeapotVertexBuffer;
winrt::com_ptr<ID3D11Buffer> mTeapotPositionOnlyVertexBuffer;
winrt::com_ptr<ID3D11Buffer> mTeapotIndexBuffer;
std::uint32_t mPlaneVertexCount{ 0 };
std::uint32_t mTeapotIndexCount{ 0 };
std::unique_ptr<Library::ProxyModel> mProxyModel;
std::unique_ptr<Library::Camera> mProjector;
std::unique_ptr<Library::RenderableFrustum> mRenderableProjectorFrustum;
std::unique_ptr<DirectX::SpriteBatch> mSpriteBatch;
bool mUpdateMaterial{ true };
float mDepthBias{ 0.0f };
float mSlopeScaledDepthBias{ 2.0f };
winrt::com_ptr<ID3D11RasterizerState> mDepthBiasState;
};
} | {
"alphanum_fraction": 0.7828348505,
"avg_line_length": 34.9545454545,
"ext": "h",
"hexsha": "63f474909faa0fbfa632cf7402793951a8a8ab73",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl",
"max_forks_repo_path": "source/8.2_Shadow_Mapping/ShadowMappingDemo.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl",
"max_issues_repo_path": "source/8.2_Shadow_Mapping/ShadowMappingDemo.h",
"max_line_length": 205,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl",
"max_stars_repo_path": "source/8.2_Shadow_Mapping/ShadowMappingDemo.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1072,
"size": 3845
} |
// align.h
//
// prototypes for align.cc
//
// dw, 12/12/3
#include <gsl/gsl_matrix.h>
#include "pdb.h"
#include "point_transformation.h"
#include <map>
// find rigid body transformation z=Rx+t minimizing
// least squares error ||y-z||**2
// find rigid body transformation z=Rx+t minimizing
// least squares error ||y-z||**2
void align(gsl_matrix_const_view , gsl_matrix_const_view, gsl_matrix *, gsl_vector *, double *);
double align(vector<atom>&, vector<atom>&, map<int, int>&, int, vector<atom>&,
vector<atom>&, map<int, int>&, int);
double align(vector<vector<atom> >& P, vector<vector<atom> >& Q,
map<pair<int,int>, vector<int> >& M, int sz, gsl_matrix *R, gsl_vector *t);
// Not only return the RMSD value of the alignment but it also returns a new
// vector with the modified x,y,z coordinates that make input align on target.
// As the method name states ALL atoms are aligned. It's expected that both
// collections are the same size.
// optimal_transformation is an optional output parameter that will copy
// the rotation matrix and translation used to obtain the alignment
// Note: The reason why there are 2 inputs is because the first one can be
// just c-alphas, for instance, and the latter one can be an all atom
// representation that needs to be transformed.
double align_all_and_transform(vector<atom>* input, vector<atom>* target,
vector<atom>* input_to_transform, vector<atom>* transformed_output,
point_transformation* optimal_transformation);
| {
"alphanum_fraction": 0.7283621838,
"avg_line_length": 42.9142857143,
"ext": "h",
"hexsha": "35cba113b0465def54a163ec01ca9b76941f666b",
"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": "9b5286d3375fff691a80ceb44172549e9a6bdee5",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "tecdatalab/legacy",
"max_forks_repo_path": "core/proteinstructure/align.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "9b5286d3375fff691a80ceb44172549e9a6bdee5",
"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": "tecdatalab/legacy",
"max_issues_repo_path": "core/proteinstructure/align.h",
"max_line_length": 96,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "9b5286d3375fff691a80ceb44172549e9a6bdee5",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "tecdatalab/legacy",
"max_stars_repo_path": "core/proteinstructure/align.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 365,
"size": 1502
} |
// Author: David Blei (blei@cs.princeton.edu)
//
// Copyright 2006 David Blei
// All Rights Reserved.
//
// See the README for this package for details about modifying or
// distributing this software.
#ifndef PARAMSH
#define PARAMSH
#define MAX_LINE_LENGTH 100000;
#include "gsl-wrappers.h"
#include <stdlib.h>
#include <stdio.h>
#include <gsl/gsl_vector.h>
#include <string.h>
void params_read_string(FILE* f, char* name, char* x);
void params_read_int(FILE* f, char* name, int* x);
void params_write_int(FILE *, char *, int);
void params_read_double(FILE* f, char* name, double* x);
void params_write_double(FILE *, char *, double);
void params_read_gsl_vector(FILE* f, char* name, gsl_vector** x);
void params_write_gsl_vector(FILE *, char* , gsl_vector *);
void params_write_gsl_vector_multiline(FILE *, char* , gsl_vector *);
void params_write_gsl_matrix(FILE *, char* , gsl_matrix *);
void params_write_sparse_gsl_matrix(FILE *, char* , gsl_matrix *);
#endif
| {
"alphanum_fraction": 0.7346938776,
"avg_line_length": 23.9024390244,
"ext": "h",
"hexsha": "c78d8fef156a6526663948cfeab7d6477520c48d",
"lang": "C",
"max_forks_count": 7,
"max_forks_repo_forks_event_max_datetime": "2020-07-10T09:29:17.000Z",
"max_forks_repo_forks_event_min_datetime": "2019-03-15T04:11:00.000Z",
"max_forks_repo_head_hexsha": "07c936c07d268208dcc2f19e07fb8d2a18e39ba8",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "iwangjian/topic-extractor",
"max_forks_repo_path": "scripts/lib/DTM/dtm/params.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "07c936c07d268208dcc2f19e07fb8d2a18e39ba8",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "iwangjian/topic-extractor",
"max_issues_repo_path": "scripts/lib/DTM/dtm/params.h",
"max_line_length": 69,
"max_stars_count": 11,
"max_stars_repo_head_hexsha": "07c936c07d268208dcc2f19e07fb8d2a18e39ba8",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "iwangjian/dtm-lab",
"max_stars_repo_path": "scripts/lib/DTM/dtm/params.h",
"max_stars_repo_stars_event_max_datetime": "2020-04-22T08:34:34.000Z",
"max_stars_repo_stars_event_min_datetime": "2018-07-12T11:05:51.000Z",
"num_tokens": 246,
"size": 980
} |
#include <cerrno>
#include <cstdio>
#include <cstdlib>
#include <sys/stat.h>
#include <cmath>
#include <vector>
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <time.h>
#include <gsl/gsl_odeiv2.h>
#include <gsl/gsl_math.h>
#include <math.h> /* pow */
#include <gsl/gsl_sf.h>
#include <gsl/gsl_integration.h>
#include <gsl/gsl_spline.h>
/* Conversion constants */
// megaparsec to km
const double mptkm = 3.086e19;
// kg to Gev
const double kgtgev = 5.62e26;
// Gev to kg
const double gevtkg = 1.78e-27;
//// 1/seconds to GeV
const double dstgev = 6.58e-25;
// Gev to 1/seconds
const double gevtds = 1.52e24;
// Kelvin to 1/s
const double keltds = 8.62e-14;
// Solar mass in kg
const double msol = 1.989e30;
// 1/m to GeV
const double dmtgev = 1.98e-16;
// Kelvin to Gev
const double keltgev = 8.62e-14;
/* LCDM constants and yield from Planck 2018 1807.06209 */
// Hubble constant in inverse seconds
const double h0 = 67.32/mptkm;
// Cold dark matter fraction from Planck 2018
const double oc = 0.265;
// Baryonic matter fraction from Planck 2018
const double ob = 0.0494;
// Total matter fraction from Planck 2018
const double om = oc+ob;
// Radiation fraction from Planck 2018 + massless neutrinos
const double orad = 9.2367e-5;//0.00006;
// Yield of B-L = n_B-L/ entropy density
const double yield = 1e-10;
// Hooks value for yield 1404.0113
const double yieldhook = 9e-11;
/* Scale factors */
const double ai = 1e-30; // starting factor ~ end of inflation
const double arad = 0.000264; // dm-rad equality
const double acmb = 9e-4; // CMB
const double alam = 0.5; // DM - Lambda equality
/* Mass constants */
// Planck mass in kg
const double mplanck = 2.176e-8;
// log10 of planck mass (in kg)
const double lgmp = -7.66234;
// log10 of maximum mass used in integrations in kg
const double lgmax =36.;
// horizon mass in kg at time of radiation-matter equality --- 2001.04371
const double meq = 2.8e17;
// Horizon mass when shortest wavelength reenters horizon - choice
const double ms = 1e-7;
// log of 5 times ms
const double lgmf = -6.301;
// proton mass in kg
const double protonm = 1.672621e-27;
/* Decay constants */
// Sum of degrees of freedom of standard model -- see 1404.0113 or our draft
const double gstar = 106.75;
// sum of qi^2 gi
const double sumq2g = 13.;
// 3 x gstar / (30720 pi) * Mplanck^4 in kg^4
const double cc = 7.4397e-34;
// 3 x gstar / (30720 pi) * Mplanck^4 in kg^3/s
const double decfac = 6.35e17; // = cc*gevtds/gevtkg
/* Newton's G in m^3 /kg / s^2 */
const double gnewton = 6.67e-11;
/* Speeed of light in m/s */
const double sofl = 2.99792e8;
// conversion factor from dM to dlog10[M]
const double intf = 2.30259;
/* All parameters should be given in SI base units - conversions are handled in the functions*/
// structure to hold relevant parameters
struct myparam_type2{
double lambda; // coupling constant
double lgn0; // log10 of final total number density of bh in 1/m^3
double peakm; // log10 of mass spectrum peak in kg
double Trh; // reheating Temperature in Kelvin
double trh; // time of reheatting in s
double aval; // scale factor
bool rem; // remnants or not
gsl_spline *spline;
gsl_interp_accel *acc;
bool mono; // monochromatic spectrum (true) or broad (false)
} ;
// Reduced structure for epoch/approximate calculations
struct myparam_type{
double peakm; // mass spectrum peak
double trh; // time of reheating
double aval; // scale factor
bool rem; // remnants or not
};
// structure for creating a(t) object
typedef struct arrays{
int count;
double xx[1002];
double yy[1002]; } *arrays_T;
| {
"alphanum_fraction": 0.7066923712,
"avg_line_length": 27.5075757576,
"ext": "h",
"hexsha": "89c5bdef39a7be49c4896a162278c1581054aeec",
"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": "b896bb65d0f204603e26b3579265d4cd613c48e7",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "nebblu/PBH",
"max_forks_repo_path": "constants.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "b896bb65d0f204603e26b3579265d4cd613c48e7",
"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": "nebblu/PBH",
"max_issues_repo_path": "constants.h",
"max_line_length": 95,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "b896bb65d0f204603e26b3579265d4cd613c48e7",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "nebblu/PBH",
"max_stars_repo_path": "constants.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1158,
"size": 3631
} |
/**
* \file Utilities.h
*/
#ifndef ATK_CORE_UTILITIES_H
#define ATK_CORE_UTILITIES_H
#include <ATK/Core/config.h>
#include <gsl/gsl>
#include <cstddef>
namespace ATK
{
/// Class to convert arrays from different type to another type
template<typename DataType1, typename DataType2>
class ATK_CORE_EXPORT ConversionUtilities
{
public:
/*!
* @brief Method to convert an array to another, using double as the intermediate type
* @param input_array
* @param output_array
* @param size
* @param offset
* @param ports
*/
static void convert_array(const DataType1* input_array, DataType2* output_array, gsl::index size, gsl::index offset = 0, gsl::index ports = 1);
};
class ATK_CORE_EXPORT RuntimeError: public std::runtime_error
{
public:
explicit RuntimeError(const std::string& what_arg);
explicit RuntimeError(const char* what_arg);
};
}
#endif
| {
"alphanum_fraction": 0.7012987013,
"avg_line_length": 22.5365853659,
"ext": "h",
"hexsha": "4b2ae7d67052cf59a59f84ecbb25b76cc778a29a",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2021-12-17T00:47:11.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-04-12T03:28:12.000Z",
"max_forks_repo_head_hexsha": "dba42eea68534501efe74692b74edf4792cca231",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "AudioTK/AudioTK",
"max_forks_repo_path": "ATK/Core/Utilities.h",
"max_issues_count": 2,
"max_issues_repo_head_hexsha": "dba42eea68534501efe74692b74edf4792cca231",
"max_issues_repo_issues_event_max_datetime": "2021-09-13T19:39:05.000Z",
"max_issues_repo_issues_event_min_datetime": "2021-02-01T15:45:06.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "AudioTK/AudioTK",
"max_issues_repo_path": "ATK/Core/Utilities.h",
"max_line_length": 147,
"max_stars_count": 23,
"max_stars_repo_head_hexsha": "dba42eea68534501efe74692b74edf4792cca231",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "AudioTK/AudioTK",
"max_stars_repo_path": "ATK/Core/Utilities.h",
"max_stars_repo_stars_event_max_datetime": "2022-03-25T03:45:00.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-02-04T10:47:46.000Z",
"num_tokens": 222,
"size": 924
} |
/*
* 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 gsm_129e9ac0_6a88_49a3_8bf1_a95a8edf7da8_h
#define gsm_129e9ac0_6a88_49a3_8bf1_a95a8edf7da8_h
#include <gslib/xml.h>
#include <gslib/json.h>
#include <gslib/uuid.h>
#include <gslib/vdir.h>
/*
* Make tool introductions.
* see gsm_help();
*/
__gslib_begin__
enum gsm_project_type
{
gpt_executable,
gpt_static_library,
gpt_dynamic_library,
};
struct gsm_project;
typedef list<string> gsm_str_list;
typedef list<gsm_project> gsm_proj_list;
struct gsm_config
{
string source_dir;
string target_dir;
string spec_compiler;
bool is_debug;
};
struct gsm_globals
{
string compiler; /* $compiler */
string os_name; /* $os */
string os_version; /* $os_ver */
string source_dir; /* $src_dir */
string target_dir; /* $tar_dir */
string target_name; /* $tar_name */
bool is_debug; /* $debug */
};
struct gsm_project
{
string name;
uuid project_id;
string output_name;
gsm_project_type project_type;
gsm_str_list definitions;
gsm_str_list libraries;
string project_dir;
string intermediate_dir;
string output_dir;
gsm_str_list include_dirs;
gsm_str_list library_dirs;
gsm_str_list sources;
json_node_table ext_sheet;
};
extern void gsm_help(string& str);
extern void gsm_syntax_help(string& str);
extern bool gsm_setup_globals(gsm_globals& globals, const gsm_config& cfgs);
extern bool gsm_prepare_projects(gsm_proj_list& proj_list, vdir& vd, const gsm_globals& globals);
extern bool gsm_generate_projects(vdir& vd, const gsm_globals& globals);
extern bool gsm_finalize_projects(vdir& vd, const gsm_proj_list& projects, const gsm_globals& globals);
__gslib_end__
#endif
| {
"alphanum_fraction": 0.6523425843,
"avg_line_length": 33.51,
"ext": "h",
"hexsha": "c329f28a6bd5492e8a4a8bc27e52582214997d03",
"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/gsm.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/gsm.h",
"max_line_length": 104,
"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/gsm.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": 771,
"size": 3351
} |
/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
* Copyright 2017-Present Couchbase, Inc.
*
* Use of this software is governed by the Business Source License included
* in the file licenses/BSL-Couchbase.txt. As of the Change Date specified
* in that file, in accordance with the Business Source License, use of this
* software will be governed by the Apache License, Version 2.0, included in
* the file licenses/APL2.txt.
*/
#pragma once
#include <gsl/gsl-lite.hpp>
#include <mcbp/protocol/dcp_stream_end_status.h>
#include <mcbp/protocol/status.h>
#include <memcached/dcp_stream_id.h>
#include <memcached/engine_error.h>
#include <memcached/types.h>
#include <memcached/vbucket.h>
#include <memcached/visibility.h>
class CookieIface;
struct DocKey;
namespace cb::durability {
class Requirements;
enum class Level : uint8_t;
} // namespace cb::durability
namespace cb::mcbp {
class Response;
}
namespace mcbp::systemevent {
enum class id : uint32_t;
enum class version : uint8_t;
} // namespace mcbp::systemevent
class DcpConnHandlerIface {
public:
virtual ~DcpConnHandlerIface() = default;
};
/**
* The message producers are used by the engine's DCP producer
* to add messages into the DCP stream. Please look at the full
* DCP documentation to figure out the real meaning for all of the
* messages.
*/
struct DcpMessageProducersIface {
virtual ~DcpMessageProducersIface() = default;
virtual cb::engine_errc get_failover_log(uint32_t opaque, Vbid vbucket) = 0;
virtual cb::engine_errc stream_req(uint32_t opaque,
Vbid vbucket,
uint32_t flags,
uint64_t start_seqno,
uint64_t end_seqno,
uint64_t vbucket_uuid,
uint64_t snap_start_seqno,
uint64_t snap_end_seqno,
const std::string& request_value) = 0;
virtual cb::engine_errc add_stream_rsp(uint32_t opaque,
uint32_t stream_opaque,
cb::mcbp::Status status) = 0;
virtual cb::engine_errc marker_rsp(uint32_t opaque,
cb::mcbp::Status status) = 0;
virtual cb::engine_errc set_vbucket_state_rsp(uint32_t opaque,
cb::mcbp::Status status) = 0;
/**
* Send a Stream End message
*
* @param opaque this is the opaque requested by the consumer
* in the Stream Request message
* @param vbucket the vbucket id the message belong to
* @param status the reason for the stream end.
* 0 = success
* 1+ = Something happened on the vbucket causing
* us to abort it.
* @param sid The stream-ID the end applies to (can be 0 for none)
*
* @return cb::engine_errc::success upon success
* cb::engine_errc::would_block if no data is available
* ENGINE_* for errors
*/
virtual cb::engine_errc stream_end(uint32_t opaque,
Vbid vbucket,
cb::mcbp::DcpStreamEndStatus status,
cb::mcbp::DcpStreamId sid) = 0;
/**
* Send a marker
*
* @param opaque this is the opaque requested by the consumer
* in the Stream Request message
* @param vbucket the vbucket id the message belong to
* @param start_seqno start of the snapshot range
* @param end_seqno end of the snapshot range
* @param flags snapshot marker flags (DISK/MEMORY/CHK/ACK).
* @param highCompletedSeqno the SyncRepl high completed seqno
* @param maxVisibleSeqno highest committed seqno (ignores prepare/abort)
* @param timestamp for the data in the snapshot marker (only valid for
* disk type and represents the disk commit time)
* @param sid The stream-ID the marker applies to (can be 0 for none)
*
* @return cb::engine_errc::success upon success
*/
virtual cb::engine_errc marker(uint32_t opaque,
Vbid vbucket,
uint64_t start_seqno,
uint64_t end_seqno,
uint32_t flags,
std::optional<uint64_t> highCompletedSeqno,
std::optional<uint64_t> maxVisibleSeqno,
std::optional<uint64_t> timestamp,
cb::mcbp::DcpStreamId sid) = 0;
/**
* Send a Mutation
*
* @param opaque this is the opaque requested by the consumer
* in the Stream Request message
* @param itm the item to send.
* @param vbucket the vbucket id the message belong to
* @param by_seqno
* @param rev_seqno
* @param lock_time
* @param nru the nru field used by ep-engine (may safely be ignored)
* @param sid The stream-ID the mutation applies to (can be 0 for none)
*
* @return cb::engine_errc::success upon success
*/
virtual cb::engine_errc mutation(uint32_t opaque,
cb::unique_item_ptr itm,
Vbid vbucket,
uint64_t by_seqno,
uint64_t rev_seqno,
uint32_t lock_time,
uint8_t nru,
cb::mcbp::DcpStreamId sid) = 0;
/**
* Send a deletion
*
* @param opaque this is the opaque requested by the consumer
* in the Stream Request message
* @param itm the item to send.
* @param by_seqno
* @param rev_seqno
* @param sid The stream-ID the deletion applies to (can be 0 for none)
*
* @return cb::engine_errc::success upon success
*/
virtual cb::engine_errc deletion(uint32_t opaque,
cb::unique_item_ptr itm,
Vbid vbucket,
uint64_t by_seqno,
uint64_t rev_seqno,
cb::mcbp::DcpStreamId sid) = 0;
/**
* Send a deletion with delete_time or collections (or both)
*
* @param opaque this is the opaque requested by the consumer
* in the Stream Request message
* @param itm the item to send.
* @param vbucket the vbucket id the message belong to
* @param by_seqno
* @param rev_seqno
* @param delete_time the time of the deletion (tombstone creation time)
* @param sid The stream-ID the deletion applies to (can be 0 for none)
*
* @return cb::engine_errc::success upon success
*/
virtual cb::engine_errc deletion_v2(uint32_t opaque,
cb::unique_item_ptr itm,
Vbid vbucket,
uint64_t by_seqno,
uint64_t rev_seqno,
uint32_t delete_time,
cb::mcbp::DcpStreamId sid) = 0;
/**
* Send an expiration
*
* @param opaque this is the opaque requested by the consumer
* in the Stream Request message
* @param itm the item to send.
* @param by_seqno
* @param rev_seqno
* @param delete_time the time of the deletion (tombstone creation time)
* @param sid The stream-ID the expiration applies to (can be 0 for none)
*
* @return cb::engine_errc::success upon success
*/
virtual cb::engine_errc expiration(uint32_t opaque,
cb::unique_item_ptr itm,
Vbid vbucket,
uint64_t by_seqno,
uint64_t rev_seqno,
uint32_t delete_time,
cb::mcbp::DcpStreamId sid) = 0;
/**
* Send a state transition for a vbucket
*
* @param opaque this is the opaque requested by the consumer
* in the Stream Request message
* @param vbucket the vbucket id the message belong to
* @param state the new state
*
* @return cb::engine_errc::success upon success
*/
virtual cb::engine_errc set_vbucket_state(uint32_t opaque,
Vbid vbucket,
vbucket_state_t state) = 0;
/**
* Send a noop
*
* @param opaque what to use as the opaque in the buffer
*
* @return cb::engine_errc::success upon success
*/
virtual cb::engine_errc noop(uint32_t opaque) = 0;
/**
* Send a buffer acknowledgment
*
* @param opaque this is the opaque requested by the consumer
* in the Stream Request message
* @param vbucket the vbucket id the message belong to
* @param buffer_bytes the amount of bytes processed
*
* @return cb::engine_errc::success upon success
*/
virtual cb::engine_errc buffer_acknowledgement(uint32_t opaque,
Vbid vbucket,
uint32_t buffer_bytes) = 0;
/**
* Send a control message to the other end
*
* @param opaque what to use as the opaque in the buffer
* @param key the identifier for the property to set
* @param value The value for the property (the layout of the
* value is defined for the key)
*
* @return cb::engine_errc::success upon success
*/
virtual cb::engine_errc control(uint32_t opaque,
std::string_view key,
std::string_view value) = 0;
/**
* Send a system event message to the other end
*
* @param cookie passed on the cookie provided by step
* @param opaque what to use as the opaque in the buffer
* @param vbucket the vbucket the event applies to
* @param bySeqno the sequence number of the event
* @param version A version value defining the eventData format
* @param key the system event's key data
* @param eventData the system event's specific data
* @param sid The stream-ID the event applies to (can be 0 for none)
*
* @return cb::engine_errc::success upon success
*/
virtual cb::engine_errc system_event(uint32_t opaque,
Vbid vbucket,
mcbp::systemevent::id event,
uint64_t bySeqno,
mcbp::systemevent::version version,
cb::const_byte_buffer key,
cb::const_byte_buffer eventData,
cb::mcbp::DcpStreamId sid) = 0;
/*
* Send a GetErrorMap message to the other end
*
* @param opaque The opaque to send over
* @param version The version of the error map
*
* @return cb::engine_errc::success upon success
*/
virtual cb::engine_errc get_error_map(uint32_t opaque,
uint16_t version) = 0;
/**
* See mutation for a description of the parameters except for:
*
* @param deleted Are we storing a deletion operation?
* @param durability the durability specification for this item
*/
virtual cb::engine_errc prepare(uint32_t opaque,
cb::unique_item_ptr itm,
Vbid vbucket,
uint64_t by_seqno,
uint64_t rev_seqno,
uint32_t lock_time,
uint8_t nru,
DocumentState document_state,
cb::durability::Level level) = 0;
/**
* Send a seqno ack message
*
* It serves to inform KV-Engine active nodes that the replica has
* successfully received and prepared to memory/disk all DCP_PREPARE
* messages up to the specified seqno.
*
* @param opaque identifying stream
* @param vbucket the vbucket the seqno ack is for
* @param prepared_seqno The seqno the replica has prepared up to.
*/
virtual cb::engine_errc seqno_acknowledged(uint32_t opaque,
Vbid vbucket,
uint64_t prepared_seqno) = 0;
/**
* Send a commit message:
*
* This is sent from the DCP Producer to the DCP Consumer.
* It is only sent to DCP replicas, not GSI, FTS etc. It serves to inform
* KV-Engine replicas of a committed Sync Write
*
* @param opaque
* @param vbucket the vbucket the event applies to
* @param key The key of the committed mutation.
* @param prepare_seqno The seqno of the prepare that we are committing.
* @param commit_seqno The sequence number to commit this mutation at.
* @return
*/
virtual cb::engine_errc commit(uint32_t opaque,
Vbid vbucket,
const DocKey& key,
uint64_t prepare_seqno,
uint64_t commit_seqno) = 0;
/**
* Send an abort message:
*
* This is sent from the DCP Producer to the DCP Consumer.
*/
virtual cb::engine_errc abort(uint32_t opaque,
Vbid vbucket,
const DocKey& key,
uint64_t prepared_seqno,
uint64_t abort_seqno) = 0;
/**
* Send an OSO snapshot marker to from server to client
*/
virtual cb::engine_errc oso_snapshot(uint32_t opaque,
Vbid vbucket,
uint32_t flags,
cb::mcbp::DcpStreamId sid) = 0;
virtual cb::engine_errc seqno_advanced(uint32_t opaque,
Vbid vbucket,
uint64_t seqno,
cb::mcbp::DcpStreamId sid) = 0;
};
using dcp_add_failover_log =
std::function<cb::engine_errc(const std::vector<vbucket_failover_t>&)>;
struct MEMCACHED_PUBLIC_CLASS DcpIface {
/**
* Called from the memcached core for a DCP connection to allow it to
* inject new messages on the stream.
*
* @param cookie a unique handle the engine should pass on to the
* message producers
* @param producers functions the client may use to add messages to
* the DCP stream
*
* @return The appropriate error code returned from the message
* producerif it failed, or:
* cb::engine_errc::success if the engine don't have more messages
* to send at this moment
*/
virtual cb::engine_errc step(const CookieIface& cookie,
DcpMessageProducersIface& producers) = 0;
/**
* Called from the memcached core to open a new DCP connection.
*
* @param cookie a unique handle the engine should pass on to the
* message producers (typically representing the memcached
* connection).
* @param opaque what to use as the opaque for this DCP connection.
* @param seqno Unused
* @param flags bitfield of flags to specify what to open. See DCP_OPEN_XXX
* @param name Identifier for this connection. Note that the name must be
* unique; attempting to (re)connect with a name already in use
* will disconnect the existing connection.
* @param value An optional JSON value specifying extra information about
* the connection to be opened.
* @return cb::engine_errc::success if the DCP connection was successfully
* opened, otherwise error code indicating reason for the failure.
*/
virtual cb::engine_errc open(const CookieIface& cookie,
uint32_t opaque,
uint32_t seqno,
uint32_t flags,
std::string_view name,
std::string_view value = {}) = 0;
/**
* Called from the memcached core to add a vBucket stream to the set of
* connected streams.
*
* @param cookie a unique handle the engine should pass on to the
* message producers (typically representing the memcached
* connection).
* @param opaque what to use as the opaque for this DCP connection.
* @param vbucket The vBucket to stream.
* @param flags bitfield of flags to specify what to open. See
* DCP_ADD_STREAM_FLAG_XXX
* @return cb::engine_errc::success if the DCP stream was successfully
* opened, otherwise error code indicating reason for the failure.
*/
virtual cb::engine_errc add_stream(const CookieIface& cookie,
uint32_t opaque,
Vbid vbucket,
uint32_t flags) = 0;
/**
* Called from the memcached core to close a vBucket stream to the set of
* connected streams.
*
* @param cookie a unique handle the engine should pass on to the
* message producers (typically representing the memcached
* connection).
* @param opaque what to use as the opaque for this DCP connection.
* @param vbucket The vBucket to close.
* @param sid The id of the stream to close (can be 0/none)
* @return
*/
virtual cb::engine_errc close_stream(const CookieIface& cookie,
uint32_t opaque,
Vbid vbucket,
cb::mcbp::DcpStreamId sid) = 0;
/**
* Callback to the engine that a Stream Request message was received
*/
virtual cb::engine_errc stream_req(
const CookieIface& cookie,
uint32_t flags,
uint32_t opaque,
Vbid vbucket,
uint64_t start_seqno,
uint64_t end_seqno,
uint64_t vbucket_uuid,
uint64_t snap_start_seqno,
uint64_t snap_end_seqno,
uint64_t* rollback_seqno,
dcp_add_failover_log callback,
std::optional<std::string_view> json) = 0;
/**
* Callback to the engine that a get failover log message was received
*/
virtual cb::engine_errc get_failover_log(const CookieIface& cookie,
uint32_t opaque,
Vbid vbucket,
dcp_add_failover_log callback) = 0;
/**
* Callback to the engine that a stream end message was received
*/
virtual cb::engine_errc stream_end(const CookieIface& cookie,
uint32_t opaque,
Vbid vbucket,
cb::mcbp::DcpStreamEndStatus status) = 0;
/**
* Callback to the engine that a snapshot marker message was received
*/
virtual cb::engine_errc snapshot_marker(
const CookieIface& cookie,
uint32_t opaque,
Vbid vbucket,
uint64_t start_seqno,
uint64_t end_seqno,
uint32_t flags,
std::optional<uint64_t> high_completed_seqno,
std::optional<uint64_t> max_visible_seqno) = 0;
/**
* Callback to the engine that a mutation message was received
*
* @param cookie The cookie representing the connection
* @param opaque The opaque field in the message (identifying the stream)
* @param key The documents key
* @param value The value to store
* @param priv_bytes The number of bytes in the value which should be
* allocated from the privileged pool
* @param datatype The datatype for the incomming item
* @param cas The documents CAS value
* @param vbucket The vbucket identifier for the document
* @param flags The user specified flags
* @param by_seqno The sequence number in the vbucket
* @param rev_seqno The revision number for the item
* @param expiration When the document expire
* @param lock_time The lock time for the document
* @param meta The documents meta
* @param nru The engine's NRU value
* @return Standard engine error code.
*/
virtual cb::engine_errc mutation(const CookieIface& cookie,
uint32_t opaque,
const DocKey& key,
cb::const_byte_buffer value,
size_t priv_bytes,
uint8_t datatype,
uint64_t cas,
Vbid vbucket,
uint32_t flags,
uint64_t by_seqno,
uint64_t rev_seqno,
uint32_t expiration,
uint32_t lock_time,
cb::const_byte_buffer meta,
uint8_t nru) = 0;
/**
* Callback to the engine that a deletion message was received
*
* @param cookie The cookie representing the connection
* @param opaque The opaque field in the message (identifying the stream)
* @param key The documents key
* @param value The value to store
* @param priv_bytes The number of bytes in the value which should be
* allocated from the privileged pool
* @param datatype The datatype for the incomming item
* @param cas The documents CAS value
* @param vbucket The vbucket identifier for the document
* @param by_seqno The sequence number in the vbucket
* @param rev_seqno The revision number for the item
* @param meta The documents meta
* @return Standard engine error code.
*/
virtual cb::engine_errc deletion(const CookieIface& cookie,
uint32_t opaque,
const DocKey& key,
cb::const_byte_buffer value,
size_t priv_bytes,
uint8_t datatype,
uint64_t cas,
Vbid vbucket,
uint64_t by_seqno,
uint64_t rev_seqno,
cb::const_byte_buffer meta) = 0;
/**
* Callback to the engine that a deletion_v2 message was received
*
* @param cookie The cookie representing the connection
* @param opaque The opaque field in the message (identifying the stream)
* @param key The documents key
* @param value The value to store
* @param priv_bytes The number of bytes in the value which should be
* allocated from the privileged pool
* @param datatype The datatype for the incomming item
* @param cas The documents CAS value
* @param vbucket The vbucket identifier for the document
* @param by_seqno The sequence number in the vbucket
* @param rev_seqno The revision number for the item
* @param delete_time The time of the delete
* @return Standard engine error code.
*/
virtual cb::engine_errc deletion_v2(const CookieIface& cookie,
uint32_t opaque,
const DocKey& key,
cb::const_byte_buffer value,
size_t priv_bytes,
uint8_t datatype,
uint64_t cas,
Vbid vbucket,
uint64_t by_seqno,
uint64_t rev_seqno,
uint32_t delete_time) {
return cb::engine_errc::not_supported;
}
/**
* Callback to the engine that an expiration message was received
*
* @param cookie The cookie representing the connection
* @param opaque The opaque field in the message (identifying the stream)
* @param key The documents key
* @param value The value to store
* @param priv_bytes The number of bytes in the value which should be
* allocated from the privileged pool
* @param datatype The datatype for the incomming item
* @param cas The documents CAS value
* @param vbucket The vbucket identifier for the document
* @param by_seqno The sequence number in the vbucket
* @param rev_seqno The revision number for the item
* @param meta The documents meta
* @return Standard engine error code.
*/
virtual cb::engine_errc expiration(const CookieIface& cookie,
uint32_t opaque,
const DocKey& key,
cb::const_byte_buffer value,
size_t priv_bytes,
uint8_t datatype,
uint64_t cas,
Vbid vbucket,
uint64_t by_seqno,
uint64_t rev_seqno,
uint32_t deleteTime) = 0;
/**
* Callback to the engine that a set vbucket state message was received
*/
virtual cb::engine_errc set_vbucket_state(const CookieIface& cookie,
uint32_t opaque,
Vbid vbucket,
vbucket_state_t state) = 0;
/**
* Callback to the engine that a NOOP message was received
*/
virtual cb::engine_errc noop(const CookieIface& cookie,
uint32_t opaque) = 0;
/**
* Callback to the engine that a buffer_ack message was received
*/
virtual cb::engine_errc buffer_acknowledgement(const CookieIface& cookie,
uint32_t opaque,
Vbid vbucket,
uint32_t buffer_bytes) = 0;
/**
* Callback to the engine that a Control message was received.
*
* @param cookie The cookie representing the connection
* @param opaque The opaque field in the message (identifying the stream)
* @param key The control message name
* @param value The control message value
* @return Standard engine error code.
*/
virtual cb::engine_errc control(const CookieIface& cookie,
uint32_t opaque,
std::string_view key,
std::string_view value) = 0;
/**
* Callback to the engine that a response message has been received.
* @param cookie The cookie representing the connection
* @param response The response which the server received.
* @return Standard engine error code.
*/
virtual cb::engine_errc response_handler(
const CookieIface& cookie, const cb::mcbp::Response& response) = 0;
/**
* Callback to the engine that a system event message was received.
*
* @param cookie The cookie representing the connection
* @param opaque The opaque field in the message (identifying the stream)
* @param vbucket The vbucket identifier for this event.
* @param event The type of system event.
* @param bySeqno Sequence number of event.
* @param version The version of system event (defines the eventData format)
* @param key The event name .
* @param eventData The event value.
* @return Standard engine error code.
*/
virtual cb::engine_errc system_event(const CookieIface& cookie,
uint32_t opaque,
Vbid vbucket,
mcbp::systemevent::id event,
uint64_t bySeqno,
mcbp::systemevent::version version,
cb::const_byte_buffer key,
cb::const_byte_buffer eventData) = 0;
/**
* Called by the core when it receives a DCP PREPARE message over the
* wire.
*
* See mutation for a description of the parameters except for:
*
* @param deleted Are we storing a deletion operation?
* @param durability the durability specification for this item
*/
virtual cb::engine_errc prepare(const CookieIface& cookie,
uint32_t opaque,
const DocKey& key,
cb::const_byte_buffer value,
size_t priv_bytes,
uint8_t datatype,
uint64_t cas,
Vbid vbucket,
uint32_t flags,
uint64_t by_seqno,
uint64_t rev_seqno,
uint32_t expiration,
uint32_t lock_time,
uint8_t nru,
DocumentState document_state,
cb::durability::Level level) = 0;
/**
* Called by the core when it receives a DCP SEQNO ACK message over the
* wire.
*
* It serves to inform KV-Engine active nodes that the replica has
* successfully received and prepared all DCP_PREPARE messages up to the
* specified seqno.
*
* @param cookie connection to send it over
* @param opaque identifying stream
* @param vbucket The vbucket which is being acknowledged.
* @param prepared_seqno The seqno the replica has prepared up to.
*/
virtual cb::engine_errc seqno_acknowledged(const CookieIface& cookie,
uint32_t opaque,
Vbid vbucket,
uint64_t prepared_seqno) = 0;
/**
* Called by the core when it receives a DCP COMMIT message over the
* wire.
*
* This is sent from the DCP Producer to the DCP Consumer.
* It is only sent to DCP replicas, not GSI, FTS etc. It serves to inform
* KV-Engine replicas of a committed Sync Write
*/
virtual cb::engine_errc commit(const CookieIface& cookie,
uint32_t opaque,
Vbid vbucket,
const DocKey& key,
uint64_t prepared_seqno,
uint64_t commit_seqno) = 0;
/**
* Called by the core when it receives a DCP ABORT message over the
* wire.
*
* This is sent from the DCP Producer to the DCP Consumer.
*/
virtual cb::engine_errc abort(const CookieIface& cookie,
uint32_t opaque,
Vbid vbucket,
const DocKey& key,
uint64_t prepared_seqno,
uint64_t abort_seqno) = 0;
};
| {
"alphanum_fraction": 0.5288374068,
"avg_line_length": 43.4492753623,
"ext": "h",
"hexsha": "5ee52e3a61b763a63a297b8fb672679824db5440",
"lang": "C",
"max_forks_count": 71,
"max_forks_repo_forks_event_max_datetime": "2022-03-29T10:34:32.000Z",
"max_forks_repo_forks_event_min_datetime": "2017-05-22T20:41:59.000Z",
"max_forks_repo_head_hexsha": "132f1bb04c9212bcac9e401d069aeee5f63ff1cd",
"max_forks_repo_licenses": [
"MIT",
"BSD-3-Clause"
],
"max_forks_repo_name": "nawazish-couchbase/kv_engine",
"max_forks_repo_path": "include/memcached/dcp.h",
"max_issues_count": 3,
"max_issues_repo_head_hexsha": "132f1bb04c9212bcac9e401d069aeee5f63ff1cd",
"max_issues_repo_issues_event_max_datetime": "2022-03-03T11:14:17.000Z",
"max_issues_repo_issues_event_min_datetime": "2017-11-14T08:12:46.000Z",
"max_issues_repo_licenses": [
"MIT",
"BSD-3-Clause"
],
"max_issues_repo_name": "nawazish-couchbase/kv_engine",
"max_issues_repo_path": "include/memcached/dcp.h",
"max_line_length": 80,
"max_stars_count": 104,
"max_stars_repo_head_hexsha": "132f1bb04c9212bcac9e401d069aeee5f63ff1cd",
"max_stars_repo_licenses": [
"MIT",
"BSD-3-Clause"
],
"max_stars_repo_name": "nawazish-couchbase/kv_engine",
"max_stars_repo_path": "include/memcached/dcp.h",
"max_stars_repo_stars_event_max_datetime": "2022-03-24T00:18:34.000Z",
"max_stars_repo_stars_event_min_datetime": "2017-05-22T20:41:57.000Z",
"num_tokens": 6639,
"size": 32978
} |
/**
* header file for data mining sharpening (DMS)
* written by Feng Gao on June 2012
* v1.0_HDF: uses LEDAPS SR in HDF format (in-house LEDAPS product)
* v1.1_ENVI: accepts GeoTIFF, ENVI and HDF format (USGS Landsat SR product)
* v1.2_ENVI: uses Landsat cloud mask (USGS Landsat fmask product)
*/
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include <strings.h>
/* header files for GeoTIFF */
#include "geotiffio.h"
#include "xtiffio.h"
#include "tiffio.h"
/* header file for GNU Scientific Libraries */
//#include <gsl/gsl_multifit.h>
#define MIN_NSAMPLES 20
#define MAX_STRLEN 1000
#define MAX_NBANDS 10
#define EC_VALID_TH 0.5
#define SUCCESS 0
#define FAILURE -1
#define FILLV -9999
/* define structure to hold all variables from input */
typedef struct {
/* for original shortwave spectral bands */
int nbands;
char inFile[MAX_NBANDS][MAX_STRLEN];
char cloudFile[MAX_STRLEN];
char fileType[MAX_STRLEN];
int nrows;
int ncols;
int fillv;
int range[2];
float res;
/* geolocation information (same for shortwave spectral bands and thermal band */
float ulx, uly;
long insys;
long inzone;
double inparm[15];
long inunit;
long indatum;
/* original temperature (float for binary file or byte for GeoTIFF) */
char org_th_File[MAX_STRLEN];
char org_th_fileType[MAX_STRLEN];
int org_th_nrows;
int org_th_ncols;
float org_th_res;
float org_th_range[2];
/* reduced and rescaled T in coarse resolution */
int res_th_nrows;
int res_th_ncols;
float res_th_res;
char cubistFile[MAX_STRLEN]; /* filestem for cubist */
char outFile[MAX_STRLEN]; /* sharpened T (output) */
float CV_TH; /* coeficient of variation threshold */
int SMOOTH_FLAG; /* 1=apply smooth operation to difference map in EC application; 0=do not apply */
/* processing window */
int s_row; /* start row */
int s_col; /* start column */
int e_row; /* end row */
int e_col; /* end column */
} INPUT_PARS;
/* define structure to store data (shortwave bands or thermal band ) */
typedef struct {
int nbands;
char fileName[MAX_NBANDS][MAX_STRLEN];
char fileType[MAX_STRLEN];
int nrows;
int ncols;
int fillValue;
float range[2];
long total_valid_data;
double ulx; /* x value of up-left corner */
double uly; /* y value of up-left corner */
double res; /* spatial resolution */
long insys;
long inzone;
double inparm[15];
long inunit;
long indatum;
float homoTest[MAX_NBANDS]; /* homogeneous test (stdev/mean) */
FILE *fp[MAX_NBANDS]; /* input file pointer for binary file */
TIFF *fp_tiff[MAX_NBANDS]; /* input file pointer for GeoTIFF file */
int16 **data; /* one row in [iband][icol] for shortwave spectral bands */
float **fdata; /* whole image in [irow][icol] for thermal band in float point */
int8 **qa; /* qa data for output (not used) */
FILE *fp_cloud; /* for cloud mask (added on 10/2015) */
TIFF *fp_tiff_cloud;
uint8 **cloud;
int CMASK_FLAG;
float min[MAX_NBANDS], max[MAX_NBANDS];
int scale; /* zoom in scale to the coarse resolution temperature (shortwave and thermal band may different) */
} SENSOR;
/* structure to store samples */
typedef struct {
float ref[MAX_NBANDS]; /* shortwave bands reflectance */
float st; /* skin/surface temperature */
float w; /* weight */
} SAMPLES;
void parseParameters(char *ifile, INPUT_PARS *ipar);
void printoutParameters(INPUT_PARS *ipars);
int getSensorMetaInfo(SENSOR *sensor, SENSOR *st, SENSOR *th, SENSOR *sth, INPUT_PARS *pars);
int getMetaDataFromGeoTIFF(SENSOR *sensor, int iband);
int openForWrite(SENSOR *sth);
int loadThermal(SENSOR *th);
int applyEC(SENSOR *spec, SENSOR *st, SENSOR *th, SENSOR *sth, INPUT_PARS *ipar);
int savePureSamples(SENSOR *spec, SENSOR *th, INPUT_PARS *ipar);
int extractSamples(SENSOR *spec, SENSOR *th, INPUT_PARS *ipar, SAMPLES *sam);
int resize(SENSOR *st, SENSOR *th);
int loadSensorRow(SENSOR *sensor, int irow);
int cleanUpSensor(SENSOR *sensor, SENSOR *st, SENSOR *th, SENSOR *sth);
void dec2bin(unsigned short int num, int *bitpattern, int limit);
void gslRegression(SENSOR *spec, SAMPLES *sam, int NPT, double *coeff);
void localPrediction(SENSOR *spec, SENSOR *sth, INPUT_PARS *pars, double *coeff);
int openOutput(SENSOR *sth);
void alloc_1dim_contig (void **, int, int);
void alloc_2dim_contig (void ***, int, int, int);
void alloc_3dim_contig (void ****, int, int, int, int);
void alloc_4dim_contig (void *****, int, int, int, int, int);
void free_2dim_contig (void **);
void free_3dim_contig (void ***);
void free_4dim_contig (void ****);
void writeENVIHeader(SENSOR *sensor, char *fname, int nbands, int dtype);
/*#define DEBUG*/
#ifdef DEBUG
#define DEBUG_icol 450
#define DEBUG_irow 450
#endif
/*#define SAVE_COARSE_T*/
| {
"alphanum_fraction": 0.6691508139,
"avg_line_length": 31.6708074534,
"ext": "h",
"hexsha": "8861cfb3d73e2e2861729d885040447422cabff9",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2021-04-16T08:05:44.000Z",
"max_forks_repo_forks_event_min_datetime": "2017-04-20T21:04:41.000Z",
"max_forks_repo_head_hexsha": "608495d7cd6890ecca6ad2a8be0d15b5ea80f7c1",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "bucricket/projectMASpreprocess",
"max_forks_repo_path": "source/Landsat_DMS/landsat.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "608495d7cd6890ecca6ad2a8be0d15b5ea80f7c1",
"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": "bucricket/projectMASpreprocess",
"max_issues_repo_path": "source/Landsat_DMS/landsat.h",
"max_line_length": 116,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "9976ce0958e9dff7d5d8475a9242f743edc8a6b3",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "bucricket/projectMASlst2",
"max_stars_repo_path": "source/Landsat_DMS/landsat.h",
"max_stars_repo_stars_event_max_datetime": "2022-02-28T20:26:59.000Z",
"max_stars_repo_stars_event_min_datetime": "2022-02-28T20:26:59.000Z",
"num_tokens": 1472,
"size": 5099
} |
/*
* Copyright 2008-2009 NVIDIA Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*! \file defs.h
* \brief Lapack utility definitions for interface routines
*/
#pragma once
#include <lapacke.h>
namespace cusp
{
namespace lapack
{
struct lapack_format {};
struct upper : public lapack_format {};
struct lower : public lapack_format {};
struct unit : public lapack_format {};
struct nonunit : public lapack_format {};
struct evals : public lapack_format {};
struct evecs : public lapack_format {};
struct gen_op1 : public lapack_format {};
struct gen_op2 : public lapack_format {};
struct gen_op3 : public lapack_format {};
template< typename LayoutFormat >
struct Orientation {static const lapack_int type;};
template<>
const lapack_int Orientation<cusp::row_major>::type = LAPACK_ROW_MAJOR;
template<>
const lapack_int Orientation<cusp::column_major>::type = LAPACK_COL_MAJOR;
template< typename TriangularFormat >
struct UpperOrLower {static const char type;};
template<>
const char UpperOrLower<upper>::type = 'U';
template<>
const char UpperOrLower<lower>::type = 'L';
template< typename DiagonalFormat >
struct UnitOrNonunit {static const char type;};
template<>
const char UnitOrNonunit<unit>::type = 'U';
template<>
const char UnitOrNonunit<nonunit>::type = 'N';
template< typename JobType >
struct EvalsOrEvecs {static const char type;};
template<>
const char EvalsOrEvecs<evals>::type = 'N';
template<>
const char EvalsOrEvecs<evecs>::type = 'V';
template< typename OpType >
struct GenEigOp {static const char type;};
template<>
const char GenEigOp<gen_op1>::type = 1;
template<>
const char GenEigOp<gen_op2>::type = 2;
template<>
const char GenEigOp<gen_op3>::type = 3;
} // end namespace lapack
} // end namespace cusp
| {
"alphanum_fraction": 0.7389033943,
"avg_line_length": 28.0243902439,
"ext": "h",
"hexsha": "e9d5ecaecd35b82cf7fc18a7097c04c797fbf4bf",
"lang": "C",
"max_forks_count": 106,
"max_forks_repo_forks_event_max_datetime": "2022-03-29T13:55:53.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-02-27T19:30:58.000Z",
"max_forks_repo_head_hexsha": "4f72f152804dee592fec86719049af2b5469295a",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "njh19/cusplibrary",
"max_forks_repo_path": "cusp/lapack/detail/defs.h",
"max_issues_count": 41,
"max_issues_repo_head_hexsha": "4f72f152804dee592fec86719049af2b5469295a",
"max_issues_repo_issues_event_max_datetime": "2022-02-27T02:37:38.000Z",
"max_issues_repo_issues_event_min_datetime": "2015-01-08T18:07:42.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "njh19/cusplibrary",
"max_issues_repo_path": "cusp/lapack/detail/defs.h",
"max_line_length": 76,
"max_stars_count": 270,
"max_stars_repo_head_hexsha": "99dcde05991ef59cbc4546aeced6eb3bd49c90c9",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "Raman-sh/cusplibrary",
"max_stars_repo_path": "cusp/lapack/detail/defs.h",
"max_stars_repo_stars_event_max_datetime": "2022-03-28T00:58:21.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-01-12T19:40:50.000Z",
"num_tokens": 567,
"size": 2298
} |
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/**
@file gft.c
@brief Generic frontend for chisquare minimisation
This is planned to comprise all external fitting functions for the
use wherever
$Source: /Volumes/DATA_J_II/data/CVS/gft/gft.c,v $
$Date: 2011/05/04 01:13:59 $
$Revision: 1.5 $
$Author: jozsa $
$Log: gft.c,v $
Revision 1.5 2011/05/04 01:13:59 jozsa
did a lot
Revision 1.4 2007/12/12 17:19:21 gjozsa
checked something
Revision 1.3 2007/08/14 17:10:51 gjozsa
Added some counters
Revision 1.2 2007/07/02 12:55:12 gjozsa
Made ANSI compliant
Revision 1.1 2007/06/22 12:43:28 gjozsa
Added to CVS control
*/
/* ------------------------------------------------------------ */
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/* EXTERNAL INCLUDES */
/* ------------------------------------------------------------ */
/* #include <stdio.h> */
#include <errno.h>
#include <stdlib.h>
#include <float.h>
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/* INTERNAL INCLUDES */
/* ------------------------------------------------------------ */
#include <gft.h>
#include <golden.h>
#include <pswarm.h>
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/* PRIVATE SYMBOLIC CONSTANTS */
/* ------------------------------------------------------------ */
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/**
@def LARGE_INTEGER
@brief a large integer
*/
/* ------------------------------------------------------------ */
#define LARGE_INTEGER 100000000UL
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/**
@def GFT_INPUT_MAX
@brief Maximum input identifyer number
*/
/* ------------------------------------------------------------ */
#define GFT_INPUT_MAX 20
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/**
@def GFT_OUTPUT_MAX
@brief Maximum output identifyer number
*/
/* ------------------------------------------------------------ */
#define GFT_OUTPUT_MAX 51
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/**
@def GFT_STOP_CHAR_DO
@brief Character of stop flag
GFT_STOP_CHAR_ID: Stop is not set
GFT_STOP_CHAR_DO: stop set but do not leave loop
GFT_STOP_CHAR_STOP: leave loop
*/
/* ------------------------------------------------------------ */
#define GFT_STOP_CHAR_DO 1
#define GFT_STOP_CHAR_STOP 2
#define GFT_STOP_CHAR_ID 0
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/**
@def GFT_BUSY_CHAR_YES
@brief Character of busy flag
GFT_BUSY_CHAR_NO: Not busy
GFT_BUSY_CHAR_YES: busy
*/
/* ------------------------------------------------------------ */
#define GFT_BUSY_CHAR_NO 0
#define GFT_BUSY_CHAR_YES 1
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/**
@def GFT_ACT_MAX
@brief Maximum output identifyer number
*/
/* ------------------------------------------------------------ */
#define GFT_ACT_MAX 5
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/**
@def MET_NONE
@brief no algorithm present alias
Alias for undefined fitting algorithm
*/
/* ------------------------------------------------------------ */
#define MET_NONE 0
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/**
@def MET_GOLDEN
@brief golden section algorithm
Alias for golden section fitting algorithm
*/
/* ------------------------------------------------------------ */
#define MET_GOLDEN 1
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/**
@def MET_SIMPLEX
@brief simplex algorithm
Alias for simplex fitting algorithm
*/
/* ------------------------------------------------------------ */
#ifdef GFT_GSL_PRESENT
/* gsl is linked like: -lgsl -lgslcblas */
#include <gsl/gsl_multimin.h>
#define MET_SIMPLEX 2
#else
#define MET_SIMPLEX -2
#endif
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/**
@def MET_PSWARM
@brief pswarm algorithm
Alias for pswarm fitting algorithm
*/
/* ------------------------------------------------------------ */
#define MET_PSWARM 3
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/**
@def MET_SIMPLEX_MAXEQ
@brief A specific stopping condition for simplex
If the chisquare requsted is (number of
parameters+MET_SIMPLEX_MAXEQ) times the same number in a row, the
algorithm is stopped.
*/
/* ------------------------------------------------------------ */
#define MET_SIMPLEX_MAXEQ 2
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/* PRIVATE MACROS */
/* ------------------------------------------------------------ */
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/**
@def FREE_COND
@brief free but check before if pointer is NULL
Note: It has to be checked if this is compliant with memory_here
*/
/* ------------------------------------------------------------ */
#define FREE_COND(x) if ((x)) free(x)
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/**
@def FLUSH_COND
@brief flush but check before if pointer is NULL
Note: It has to be checked if this is compliant with memory_here
*/
/* ------------------------------------------------------------ */
#define FLUSH_COND(x) if ((x)) free(x);x = 0
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/**
@def NORM_HUGE
@brief This will turn a huge value, which is not a real double into a double
*/
/* ------------------------------------------------------------ */
#define NORM_HUGE(x) ((x) == HUGE_VAL?DBL_MAX:((x) == -HUGE_VAL?(-DBL_MAX):()))
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/* (PRIVATE) GLOBAL VARIABLES */
/* ------------------------------------------------------------ */
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/* PRIVATE TYPEDEFS */
/* ------------------------------------------------------------ */
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/**
@typedef mst_spe
@brief generic special struct with fitting info
*/
/* ------------------------------------------------------------ */
typedef void mst_spe;
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/* PRIVATE STRUCTS */
/* ------------------------------------------------------------ */
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/**
@struct mst_gen
@brief generic part of every mstr.in struct
The stop and idle coding goes as follows:
busy 0 0 1 1
stop 0 1 0 1
idle process process process
has been is is
broken running stopped
*/
/* ------------------------------------------------------------ */
typedef struct mst_gen
{
/** brief indicates if a fitting can be started */
int misinf;
/** brief indicates a running fit process, forbidding some actions */
int busy;
/** brief indicates a stop of the running process */
int stopped;
/** brief indicates a kill of the running process */
int broken;
/** brief indicates an overflow or underflow error */
int error;
/** brief Number of calls of chisquare function since the function is there (reset if function or parameter number is changed) */
size_t allcalls;
/** brief Total number of iterations (reset if function or parameter number is changed) */
size_t alliter;
/** brief Total number of iterations (reset if function or parameter number is changed) */
size_t alloops;
/** brief Number of finished minimisation runs */
size_t minruns;
/** @brief Number of parameters */
size_t npar;
/** @brief Currently addressed parameter */
int npar_cur;
/** @brief Number of independent data points of problem */
double indpoints;
/** @brief Chisquare of actual parameters */
double actchisq;
/** @brief reduced chisquare of actual parameters */
double actchisqred;
/** @brief Minimal chisquare reached */
double bestchisq;
/** @brief Reduced minimal chisquare reached */
double bestchisqred;
/** @brief actual parameters */
double *par;
/** @brief dummy needed by gchsq_n and gchsq_ndummy */
double *dummypar;
/** @brief another dummy needed by gchsq_n and gchsq_ndummy */
double *dummypar2;
/** @brief best parameters reached */
double *bestpar;
/** @brief the actual solution */
double *solpar;
/** @brief errors to the solution */
double *solerr;
/** @brief Chisquare of solution */
double solchsq;
/** @brief reduced chisquare of solution */
double solchsqred;
/** @brief start parameters */
double *spar;
/** @brief upper bounds */
double *ubounds;
/** @brief lower bounds */
double *lbounds;
/** @brief Normalisation, origin */
double *opar;
/** @brief starting step widths */
double *dpar;
/** @brief normalisation, grid */
double *ndpar;
/** @brief the external function */
double (*gchsq)(double *par, void *adar);
/** @brief the additional arguments to chisquare function */
void *adar;
/** @brief maximal number of total function calls */
size_t ncalls;
/** @brief Number of calls of chisquare function since start of minimising */
size_t calls;
/** @brief maximal number of iteration steps */
size_t niters;
/** @brief Number of iteration steps */
size_t iters;
/** @brief maximal number of function calls within a step */
size_t ncalls_st;
/** @brief number of function calls within the actual step */
size_t calls_st;
/** @brief characteristic vector size, stopping condition, start */
double stopsize;
/** @brief characteristic vector size, stopping condition, actual */
double stopsize_act;
/** @brief actual characteristic vector size */
double size;
/** @brief golden section only: size of the normalised current step width in an iteration process for a single parameter; if not golden section, same as size */
double dsize;
/** @brief repetitional loops */
size_t loops;
/** @brief actual loop number */
size_t loop;
/** @brief factor to multiply ncalls_st from loop to loop */
double ncalls_st_fac;
/** @brief factor to multiply starting step
widths by from loop to loop */
double dpar_fac;
/** @brief factor to multiply stopsize from loop to loop */
double stopsize_fac;
/** @brief rng seed */
int seed;
/** @brief Number of particles for any minimum finder that works with separate group solutions (psw) */
int psnpart;
/** @brief pswarm cognitional parameter */
double pscogni;
/** @brief pswarm social parameter */
double pssocia;
/** @brief pswarm maximum velocity factor */
double psmaxvf;
/** @brief pswarm number of iterations to final weight */
int psnitfi;
/** @brief pswarm initial weight */
double psiniin;
/** @brief pswarm final weight */
double psfinin;
/** @brief pswarm increase mesh delta by this factor */
double psincde;
/** @brief pswarm decrease mesh delta by this factor */
double psdecde;
/** @brief the normalised external function */
double (*gchsq_n)(double *npar, struct mst_gen *mst_genv);
/** @brief vector containing normalised parameter vector */
double *nopar;
/** @brief vector containing normalised start parameter vector */
double *nospar;
/** @brief vector containing normalised upper bounds */
double *noubounds;
/** @brief vector containing normalised lower bounds */
double *nolbounds;
/** @brief vector containing normalised step sizes */
double *nodpar;
} mst_gen;
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/**
@struct mst
@brief top layer splitting in generic and minimiser psecific struct
Contains arrays, variables, functions for the simplex algorithm
Note: all allocation is done here. pointers in objects will be
deallocated in this struct.
*/
/* ------------------------------------------------------------ */
typedef struct mst
{
/** brief fit method as defined by GFT_MET_* */
int method;
/** @brief generic content of all minimisers */
mst_gen *gen;
/** @brief content for running the specific minimiser */
void *spe;
} mst;
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/**
@struct mst_sim
@brief internal control struct for the simplex algorithm
Contains arrays, variables, functions for the simplex algorithm
Note: all allocation is done here. pointers in objects will be
deallocated in this struct.
*/
/* ------------------------------------------------------------ */
/* Block this if the GSL is not available */
#if MET_SIMPLEX == -2
typedef void mst_sim;
#else
typedef struct mst_sim
{
/** @brief Probably a pointer to a function */
const gsl_multimin_fminimizer_type \
*multimin_fminimizer_type_gsl;
/** @brief struct containing the info needed by the gsl minimiser */
gsl_multimin_fminimizer *multimin_fminimizer_gsl;
/** @brief gsl vector containing the step size */
gsl_vector *stp_gsl_vec;
/** @brief block inside the vector (nevermind) */
/* gsl_block stp_gsl_block; */
/** @brief gsl vector containing the variables */
gsl_vector *var_gsl_vec;
/** @brief block inside the vector (nevermind) */
/* gsl_block var_gsl_block; */
/** @brief the vector itself, a local copy of nopar in mst_gen */
/* double *var_vec; */
/** @brief the vector itself, a local copy of nopar in mst_gen */
/* double *stp_vec; */
/** @brief counts the number of equal chisquares */
size_t eqchisq;
/** @brief counts the number of equal chisquares */
size_t eqchisq2;
/** @brief counts the number of equal chisquares */
double chisqbef;
/** @brief counts the number of alternating equal chisquares */
double chisqbef2;
/** @brief normalisation of length */
double vlnorm;
/** @brief struct containing the function to minimise and stuff */
gsl_multimin_function *multimin_function_gsl;
} mst_sim;
#endif
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/**
@struct mst_gol
@brief internal control struct for the golden section algorithm
Contains arrays, variables, functions for the golden section
algorithm Note: all allocation is done here. pointers in objects
will be deallocated in this struct.
*/
/* ------------------------------------------------------------ */
/* Block this if golden section is not available */
typedef struct mst_gol
{
golden_container *gc;
} mst_gol;
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/**
@struct mst_psw
@brief internal control struct for the golden section algorithm
Contains arrays, variables, functions for the golden section
algorithm Note: all allocation is done here. pointers in objects
will be deallocated in this struct.
*/
/* ------------------------------------------------------------ */
/* Block this if golden section is not available */
typedef struct mst_psw
{
/** @brief struct containing the function to minimise and stuff */
pswarm_options *optv;
/** @brief output and control struct */
pswarm_swarm *swav;
/** @brief current normalised start parameters */
double *curnospar;
} mst_psw;
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/* PRIVATE FUNCTION DECLARATIONS */
/* ------------------------------------------------------------ */
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/**
@fn static mst *mst_const()
@brief Consts a mst struct
The function consts a mst-struct and
initialises the generic part. Pointers are set to NULL.
@param void
@return (success) mst *mst_const(): pointer to struct
(error) NULL
*/
/* ------------------------------------------------------------ */
static mst *mst_const();
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/**
@fn static int mst_destr(mst *mstv)
@brief Destroys mst struct
Will deallocate mstv. Will deallocate everything connected to
mstv if possible. Will report on untidy deallocation (memory
leak).
@param mstv (mst *) Pointer to struct to deallocate
@return (success) int mst_destr: GFT_ERROR_NONE
(error) standard
*/
/* ------------------------------------------------------------ */
static int mst_destr(mst *mstv);
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/**
@fn static int mst_flush(mst *mstv)
@brief Flush of mst struct
Will destroy allocated structs in an mst structs
@param mstv (mst *) Pointer to struct to deallocate
@return (success) int mst_flush: GFT_ERROR_NONE
(error) standard
*/
/* ------------------------------------------------------------ */
static int mst_flush(mst *mstv);
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/**
@fn static int mst_act(mst *mstv, int spec)
@brief Action!
Internal alias, see gft_mst_act
@param gft_mstv (gft_mst *) Pointer to main struct
@param spec (int) specifyer of the type of input
@return (success) int mst_act: GFT_ERROR_NONE
(error) standard
*/
/* ------------------------------------------------------------ */
static int mst_act(mst *mstv, int spec);
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/**
@fn static int mst_stop(mst *mst_genv)
@brief Stop the fitting process, keeping it active
Some fitting methods will have the possibility to stop the fitting,
and to continue with a further call of mst_start. Stopping is done
with this function, starting with mst_start. Basically, this
function sets the stop parameter in the gen struct to 1, which
should cause the fitting to stop.
@param mst_stop (mst_gen *) Pointer to global fit struct
@return (success) int mst_stop: GFT_ERROR_NONE successful in this part
(error) standard
*/
/* ------------------------------------------------------------ */
static int mst_stop(mst *mstv);
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/**
@fn static int mst_start(mst *mstv)
@brief (Re-)start the fitting process
Start or restart (in case it has been stopped) the fitting.
@param mstv (mst *) Pointer to global fit struct
@return (success) int mst_start: GFT_ERROR_NONE
(error) standard
*/
/* ------------------------------------------------------------ */
static int mst_start(mst *mstv);
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/**
@fn static int mst_break(mst *mstv)
@brief Abort the fitting process
After calling this function, the next call of mst_start will start
a new fitting process.
@param mstv (mst *) Pointer to global fit struct
@return (success) int mst_start: GFT_ERROR_NONE
(error) standard
*/
/* ------------------------------------------------------------ */
static int mst_break(mst *mstv);
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/**
@fn static int mst_get(mst *mstv, void *output, int spec)
@brief Generically get information from a minimiser struct, intern
Internal alias, see gft_mst_put
@param gft_mstv (gft_mst *) Pointer to main struct
@param output (void *) array
@param spec (int) specifyer of the type of input
@return (success) int mst_put: GFT_ERROR_NONE
(error) standard
*/
/* ------------------------------------------------------------ */
static int mst_get(mst *mstv, void *output, int spec);
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/**
@fn static int mst_put(mst *mstv, void *input, int spec)
@brief Generically supply information to a minimiser struct, intern
constant expression input type description
GFT_INPUT_FIT_MET int * Specify fit method as defined by GFT_MET_*
@param gft_mstv (gft_mst *) Pointer to main struct
@param input (void *) array containing info
@param spec (int) specifyer of the type of input
@return (success) int mst_put: GFT_ERROR_NONE
(error) standard
*/
/* ------------------------------------------------------------ */
static int mst_put(mst *mstv, void *input, int spec);
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/**
@fn static int mst_putf(mst *mstv, double (*input)(double *, void *), int spec)
@brief Generically supply functions to a minimiser struct, intern
@param gft_mstv (gft_mst *) Pointer to main struct
@param input (double (*input)(double *, void *)) pointer to function
@param spec (int) specifyer of the type of input
@return (success) int mst_putf: GFT_ERROR_NONE
(error) standard
*/
/* ------------------------------------------------------------ */
static int mst_putf(mst *mstv, double (*input)(double *, void *), int spec);
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/**
@fn static int mst_ckme(int method)
@brief Check if a minimisation method is valid and existent
@param method (int) method suggested
@return (success) int mst_ckme: GFT_ERROR_NONE
(error) standard
*/
/* ------------------------------------------------------------ */
static int mst_ckme(int method);
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/**
@fn static int mst_initspe(mst *mstv)
@brief Do initialisations of specific minimiser that needs
a call of the minimising function
This function is called from mst_start, and a check whether the
minimiser is existent has been made before. If no minimiser is
present, the misinf status is set != 0. No check of the proper
allocation status of the minimiser struct is made.
@param mstv (mst *) minimiser struct
@return (success) int mst_initspe: GFT_ERROR_NONE
(error) standard
*/
/* ------------------------------------------------------------ */
static int mst_initspe(mst *mstv);
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/**
@fn static int mst_refresh(mst *mstv)
@brief Refresh of links and allocations in an mst struct
Refreshes all links and allocations in mstv, sets the misinf status
accordingly. Returns GFT_ERROR_NONE if misinf is GFT_ERROR_NONE, an error otherways
@param mstv (mst *) Pointer to struct
@return (success) int mst_refresh: GFT_ERROR_NONE a fit can start
(error) standard
*/
/* ------------------------------------------------------------ */
static int mst_refresh(mst *mstv);
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/**
@fn static int mst_refreshspe(mst *mstv)
@brief Refresh specific part of fit control struct
The function will also change the generic part of the control struct
@param mst (mst *) Pointer to fit control struct
@return (success) int mst_gen_refresh: GFT_ERROR_NONE successful
(error) standard
*/
/* ------------------------------------------------------------ */
static int mst_refreshspe(mst *mstv);
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/**
@fn static int mst_refreshsim(mst *mstv)
@brief Refresh part of control struct connected to simplex
The function will also change the generic part of the control struct
@param mstv (mst *) Pointer to fit control struct
@return (success) int mst_gen_refresh: GFT_ERROR_NONE successful
(error) standard
*/
/* ------------------------------------------------------------ */
static int mst_refreshsim(mst *mstv);
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/**
@fn static int mst_refreshgol(mst *mstv)
@brief Refresh part of control struct connected to golden section
The function will also change the generic part of the control struct
@param mstv (mst *) Pointer to fit control struct
@return (success) int mst_refreshgol: GFT_ERROR_NONE successful
(error) standard
*/
/* ------------------------------------------------------------ */
static int mst_refreshgol(mst *mstv);
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/**
@fn static int mst_refreshpsw(mst *mstv)
@brief Refresh part of control struct connected to golden section
The function will also change the generic part of the control struct
@param mstv (mst *) Pointer to fit control struct
@return (success) int mst_refreshpswarm: GFT_ERROR_NONE successful
(error) standard
*/
/* ------------------------------------------------------------ */
static int mst_refreshpsw(mst *mstv);
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/**
@fn static int mst_ckop(mst *mstv, int spec)
@brief Check if output request makes sense
Helper to mst_get. The function will return an appropriate error,
if at the current stage the request for a quantity makes or better,
made no sense.
@param mstv (mst *) Pointer to fit control struct
@param spec (int) Specification of the quantity requested
@return (success) int mst_ckop: GFT_ERROR_NONE successful
(error) standard
*/
/* ------------------------------------------------------------ */
static int mst_ckop(mst *mstv, int spec);
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/**
@fn static int mst_iterspe(mst *mstv)
@brief Make an iteration with the specific minimiser
This is a switch to invoke the specific minimiser functions that do
one iteration. This function contians no check of proper
initialisation of all necessary structs.
@param mstv (mst *) Pointer to fit control struct
@return (success) int mst_iterspe: GFT_ERROR_NONE successful
(error) standard
*/
/* ------------------------------------------------------------ */
static int mst_iterspe(mst *mstv);
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/**
@fn static mst_gen *mst_gen_const()
@brief Consts a mst_gen struct
The function consts the generic part of the mst-struct and
initialises everything. Pointers are set to NULL. Concerning the rest:
misinf = GFT_ERROR_STANDARD;
busy = GFT_ERROR_NONE;
stopped = GFT_ERROR_NONE;
error = GFT_ERROR_NONE;
allcalls = 0;
alliter = 0;
alloops = 0;
minruns = 0;
method = MET_NONE;
npar = 0;
npar_cur = -1;
indpoints = 0.0
onecall = 0
actchisq = DBL_MAX
bestchisq = DBL_MAX
bestchisqred = DBL_MAX
solchsq = DBL_MAX
solchsqred = DBL_MAX
ncalls = LARGE_INTEGER;
calls = 0
niters = LARGE_INTEGER;
iters = 0
ncalls_st = LARGE_INTEGER;
calls_st = 0
stopsize = 0.0;
stopsize_act = 0.0;
size = 1.0;
dsize = 1.0;
loops = 1;
loop = 0
ncalls_st_fac = 1.0;
dpar_fac = 1.0;
stopsize_fac 1.0;
@param void
@return (success) mst_gen *mst_gen_const(): pointer to struct
(error) NULL
*/
/* ------------------------------------------------------------ */
static mst_gen *mst_gen_const();
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/**
@fn static int mst_gen_destr(mst_gen *mst_genv)
@brief Destroys mst_genv
Will deallocate mst_genv. Will deallocate everything connected to mst_genv.
Will report on untidy deallocation (memory leak).
@param mst_genv (mst_gen *) Pointer to struct to deallocate
@return (success) int mst_gen_destr: GFT_ERROR_NONE
(error) standard
*/
/* ------------------------------------------------------------ */
static int mst_gen_destr(mst_gen *mst_genv);
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/**
@fn static int mst_gen_flush(mst_gen *mst_genv)
@brief Flushes mst_gen struct
Will deallocate all allocations in mst_genv and set pointers to
NULL.
@param mst_genv (mst_gen *) Pointer to struct to deallocate
@return (success) int mst_gen_flush: GFT_ERROR_NONE
(error) standard
*/
/* ------------------------------------------------------------ */
static int mst_gen_flush(mst_gen *mst_genv);
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/**
@fn static int mst_gen_ckbu(mst_gen *mst_genv)
@brief check busy status of mst_gen struct
Checks if the member busy is set to GFT_ERROR_NONE, indicative for no
minimisation being active.
@param mst_genv (mst_gen *) Pointer to generic fit struct
@return (success) int mst_gen_ckbu: GFT_ERROR_NONE idle
(error) standard active
*/
/* ------------------------------------------------------------ */
static int mst_gen_ckbu(mst_gen *mst_genv);
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/**
@fn static int mst_gen_ckmi(mst_gen *mst_genv)
@brief check misinf status of mst_gen struct
Checks if the member misinf is set to GFT_ERROR_NONE, meaning that a minimisation
can be started.
@param mst_genv (mst_gen *) Pointer to generic fit struct
@return (success) int mst_gen_ckmi: GFT_ERROR_NONE if fit can start
(error) standard
*/
/* ------------------------------------------------------------ */
/* static int mst_gen_ckmi(mst_gen *mst_genv); */
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/**
@fn static int mst_gen_ckch(mst_gen *mst_genv, double *array, double chisq)
@brief Check out (best) chisquares and parameter arrays
Helper to gchsq_n or gchsq_ndummy. Takes the array, puts it into
mst_genv -> nopar, copies mstv_genv -> dummypar in mstv_genv ->
par. Then checks whether the chisq(uare) is better than the current
minimal chisquare. If yes, the current best chisquare and the best
fit parameters are changed accordingly.
@param mst_genv (mst_gen *) Pointer to generic fit struct
@param array (double *) Array of the correct length
@param chisq (double) actual chisquare
@return (success) int mst_gen_ckch: GFT_ERROR_NONE if fit can start
(error) standard
*/
/* ------------------------------------------------------------ */
static int mst_gen_ckch(mst_gen *mst_genv, double *array, double chisq);
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/**
@fn static int mst_gen_ckop(mst_gen *mst_genv, int spec)
@brief Check if output request makes sense
Helper to mst_ckop. The function will return an appropriate error,
if at the current stage the request for a quantity makes or better,
made no sense.
@param mstv_genv (mst_gen *) Pointer to fit control struct
@param spec (int) Specification of the quantity requested
@return (success) int mst_ckop: GFT_ERROR_NONE successful
(error) standard
*/
/* ------------------------------------------------------------ */
static int mst_gen_ckop(mst_gen *mst_genv, int spec);
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/**
@fn static int mst_gen_refresh(mst_gen *mst_genv)
@brief Refresh generic part of fit control struct
@param mst_genv (mst_gen *) Pointer to generic fit struct
@return (success) int mst_gen_refresh: GFT_ERROR_NONE successful in this part
(error) standard
*/
/* ------------------------------------------------------------ */
static int mst_gen_refresh(mst_gen *mst_genv);
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/**
@fn static int mst_gen_init(mst_gen *mst_genv)
@brief Calculate the chisquare ONCE
If possible (if both the function to minimise and the actual
parameters are present), calculate the chisquare and change the
informations about the chisquares and best-fit parameters.
@param mst_genv (mst_gen *) Pointer to generic fit struct
@return (success) int mst_gen_init: GFT_ERROR_NONE successful in this part
(error) standard
*/
/* ------------------------------------------------------------ */
static int mst_gen_init(mst_gen *mst_genv);
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/**
@fn static mst_spe *mst_spe_const(int method);
@brief Generic constructor of the mst_spe struct
Calls the specific constructors of the specific fit structs
@param method (int) fit method as defined by GFT_MET_*
@return (success) mst_spe *mst_spe_const pointer to struct
(error) NULL memory allocation problems
*/
/* ------------------------------------------------------------ */
static mst_spe *mst_spe_const(int method);
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/**
@fn static int mst_spe_destr(mst_spe *spev, int method)
@brief Generic destructor of the specific minimiser struct
Will deallocate spev. Will deallocate everything connected to spe.
Will report on untidy deallocation (memory leak).
@param spe (mst_sim *) pointer to the struct to deallocate
@param method (int) fit method
@return (success) int mst_spe_destr: GFT_ERROR_NONE
(error) standard
*/
/* ------------------------------------------------------------ */
static int mst_spe_destr(mst_spe *spev, int method);
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/**
@fn static int mst_spe_ckop(mst_spe *mst_spev, int spec, int method)
@brief Check if output request makes sense
Helper to mst_ckop. The function will return an appropriate error,
if the request for a quantity makes or better, made no sense for a
specific fitting method. A non-valid fit method is allowed as
input.
@param mstv (mst *) Pointer to fit control struct
@param spec (int) Specification of the quantity requested
@param method (int) Specification of fit method
@return (success) int mst_ckop: GFT_ERROR_NONE successful
(error) standard
*/
/* ------------------------------------------------------------ */
static int mst_spe_ckop(mst_spe *mst_spev, int spec, int method);
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/**
@fn static int ckmetinp(int method, int spec)
@brief Check if a value passed makes sense
The function checks if an input identifyer makes sense in the
context of the specified fitting algorithm. This case must be checked
independently.
@param method (int) fit method
@param spec (int) quantity specifyer to check for
@return (success) int mst_ckmeaning: GFT_ERROR_NONE
(error) standard
*/
/* ------------------------------------------------------------ */
static int ckmetinp(int method, int spec);
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/**
@fn static int ckmetinp_undef(int spec)
@brief Helper to ckmetinp
The function checks if for an undefined method the input specifyer
makes sense.
@param spec (int) quantity specifyer to check for
@return (success) int mst_ckmetinp_undef: GFT_ERROR_NONE
(error) standard
*/
/* ------------------------------------------------------------ */
static int ckmetinp_undef(int spec);
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/**
@fn static mst_sim *mst_sim_const();
@brief Consts
The function constructs the simplex part of the in-struct and
initialises everything. Pointers are set to NULL.
@param void
@return (success) mst_sim *mst_sim_const pointer to struct
(error) NULL memory allocation problems
*/
/* ------------------------------------------------------------ */
static mst_sim *mst_sim_const();
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/**
@fn static mst_sim *mst_psw_const();
@brief Consts
The function constructs the simplex part of the in-struct and
initialises everything. Pointers are set to NULL.
@param void
@return (success) mst_psw *mst_psw_const pointer to struct
(error) NULL memory allocation problems
*/
/* ------------------------------------------------------------ */
static mst_psw *mst_psw_const();
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/**
@fn static int mst_sim_destr(mst_sim *spe)
@brief Destrs a specific minimiser struct: simplex
Will deallocate spe. Will deallocate everything connected to spe.
Will report on untidy deallocation (memory leak).
@param spe (mst_sim *) pointer to the struct to deallocate
@return (success) int mst_sim_destr: GFT_ERROR_NONE
(error) standard
*/
/* ------------------------------------------------------------ */
static int mst_sim_destr(mst_sim *spe);
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/**
@fn static int mst_psw_destr(mst_psw *spe)
@brief Destrs a specific minimiser struct: simplex
Will deallocate spe. Will deallocate everything connected to spe.
Will report on untidy deallocation (memory leak).
@param spe (mst_psw *) pointer to the struct to deallocate
@return (success) int mst_psw_destr: GFT_ERROR_NONE
(error) standard
*/
/* ------------------------------------------------------------ */
static int mst_psw_destr(mst_psw *spe);
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/**
@fn static int mst_sim_init(mst_sim *mst_simv, mst_gen *mst_genv)
@brief Do initialisations of the minimiser: simplex
Does initialisations of the minimiser that need calls of the
minimising function.
@param mst_simv (mst_sim *) pointer to the simplex specific struct
@param mst_genv (mst_gen *) pointer to the generic struct
@return (success) int mst_sim_init: GFT_ERROR_NONE
(error) standard
*/
/* ------------------------------------------------------------ */
static int mst_sim_init(mst_sim *mst_simv, mst_gen *mst_genv);
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/**
@fn static int mst_psw_init(mst_psw *mst_pswv, mst_gen *mst_genv)
@brief Do initialisations of the minimiser: pswarm
Does initialisations of the minimiser that need calls of the
minimising function.
@param mst_pswv (mst_psw *) pointer to the pswarm specific struct
@param mst_genv (mst_gen *) pointer to the generic struct
@return (success) int mst_psw_init: GFT_ERROR_NONE
(error) standard
*/
/* ------------------------------------------------------------ */
static int mst_psw_init(mst_psw *mst_pswv, mst_gen *mst_genv);
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/**
@fn static int mst_sim_iter(mst_sim *mst_simv, mst_gen *mst_genv)
@brief Do one iteration step: simplex
Does one iteration step and refreshes, if possible, best-fit
parameters and solution.
@param mst_simv (mst_sim *) pointer to the simplex specific struct
@param mst_genv (mst_gen *) pointer to the generic struct
@return (success) int mst_sim_iter: GFT_ERROR_NONE
(error) standard
*/
/* ------------------------------------------------------------ */
static int mst_sim_iter(mst_sim *mst_simv, mst_gen *mst_genv);
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/**
@fn static int mst_psw_iter(mst_psw *mst_pswv, mst_gen *mst_genv)
@brief Do one iteration step: pswarm
Does one iteration step and refreshes, if possible, best-fit
parameters and solution.
@param mst_simv (mst_psw *) pointer to the simplex specific struct
@param mst_genv (mst_gen *) pointer to the generic struct
@return (success) int mst_psw_iter: GFT_ERROR_NONE
(error) standard
*/
/* ------------------------------------------------------------ */
static int mst_psw_iter(mst_psw *mst_pswv, mst_gen *mst_genv);
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/**
@fn static int cksiminp(int spec)
@brief Check if a value passed makes sense
The function checks if an input identifyer makes sense in the
context of the specified fitting algorithm. The identifyer must be
valid, otherways GFT_ERROR_NONE is returned.
@param spec (int) quantity specifyer to check for
@return (success) int mst_ckmeaning: GFT_ERROR_NONE
(error) standard
*/
/* ------------------------------------------------------------ */
static int cksiminp(int spec);
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/**
@fn static int ckpswinp(int spec)
@brief Check if a value passed makes sense
The function checks if an input identifyer makes sense in the
context of the specified fitting algorithm. The identifyer must be
valid, otherways GFT_ERROR_NONE is returned.
@param spec (int) quantity specifyer to check for
@return (success) int mst_ckmeaning: GFT_ERROR_NONE
(error) standard
*/
/* ------------------------------------------------------------ */
static int ckpswinp(int spec);
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/**
@fn static int cksimop(int spec)
@brief Check if a value requested makes sense
The function checks if an input identifyer makes sense in the
context of the specified fitting algorithm. The identifyer must be
valid, otherways GFT_ERROR_NONE is returned.
@param spec (int) quantity specifyer to check for
@return (success) int mst_ckmeaning: GFT_ERROR_NONE
(error) standard
*/
/* ------------------------------------------------------------ */
/* static int cksimop(int spec); */
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/**
@fn static gsl_vector *empty_gsl_dbl_vector(void);
@brief Allocate and initialise an empty gsl vector with double elements
The vector is allocated and initialised as such:
size = 0
stride = sizeof(double)
data = NULL
block = NULL
owner = 0
@param void
@return (success) gsl_vector *empty_gsl_dbl_vector the vector
(error) NULL
*/
/* ------------------------------------------------------------ */
#ifdef GFT_GSL_PRESENT
/* static gsl_vector *empty_gsl_dbl_vector(void); */
#endif
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/**
@fn static int fill_gsl_dbl_vector(gsl_vector **gsl_vectorv, double *array, size_t length)
@brief Fill (and allocate) gsl vector
If gsl_vectorv = NULL, nothing can be done. If *gsl_vectorv = NULL,
a gsl double vector of length is allocated (by gsl), otherways it is
assumed that the gsl vector passed is of size length. Then, the
vector is filled with the length first elements of array, which
should of course be large enough. If array is empty,
GFT_ERROR_NULL_PASSED is returned. If length is 0,
GFT_ERROR_WRONG_PARAM is returned.
@param empty_gsl_vector (gsl_vector **) pointer to gsl vector
@param array (double *) array of length length
@param length (size_t) length of array (vector)
@return (success) int fill_gsl_dbl_vector: GFT_ERROR_NONE
(error) standard
*/
/* ------------------------------------------------------------ */
#ifdef GFT_GSL_PRESENT
static int fill_gsl_dbl_vector(gsl_vector **gsl_vectorv, double *array, size_t length);
#endif
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/**
@fn static mst_gol *mst_gol_const();
@brief Consts
The function constructs the golplex part of the in-struct and
initialises everything. Pointers are set to NULL.
@param void
@return (success) mst_gol *mst_gol_const pointer to struct
(error) NULL memory allocation problems
*/
/* ------------------------------------------------------------ */
static mst_gol *mst_gol_const();
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/**
@fn static int mst_gol_destr(mst_gol *spe)
@brief Destrs a specific minimiser struct: golplex
Will deallocate spe. Will deallocate everything connected to spe.
Will report on untidy deallocation (memory leak).
@param spe (mst_gol *) pointer to the struct to deallocate
@return (success) int mst_gol_destr: GFT_ERROR_NONE
(error) standard
*/
/* ------------------------------------------------------------ */
static int mst_gol_destr(mst_gol *spe);
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/**
@fn static int mst_gol_init(mst_gol *mst_golv, mst_gen *mst_genv)
@brief Do initialisations of the minimiser: golplex
Does initialisations of the minimiser that need calls of the
minimising function.
@param mst_golv (mst_gol *) pointer to the golplex specific struct
@param mst_genv (mst_gen *) pointer to the generic struct
@return (success) int mst_gol_init: GFT_ERROR_NONE
(error) standard
*/
/* ------------------------------------------------------------ */
static int mst_gol_init(mst_gol *mst_golv, mst_gen *mst_genv);
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/**
@fn static int mst_gol_iter(mst_gol *mst_golv, mst_gen *mst_genv)
@brief Do one iteration step: golden section
Does one iteration step and refreshes, if possible, best-fit
parameters and solution.
@param mst_simv (mst_gol *) pointer to the golden section specific struct
@param mst_genv (mst_gen *) pointer to the generic struct
@return (success) int mst_gol_iter: GFT_ERROR_NONE
(error) standard
*/
/* ------------------------------------------------------------ */
static int mst_gol_iter(mst_gol *mst_golv, mst_gen *mst_genv);
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/**
@fn static int ckgolinp(int spec)
@brief Check if a value passed makes sense
The function checks if an input identifyer makes sense in the
context of the specified fitting algorithm. The identifyer must be
valid, otherways GFT_ERROR_NONE is returned. For the golden section
algorithm, this function is a dummy.
@param spec (int) quantity specifyer to check for
@return (success) int mst_ckmeaning: GFT_ERROR_NONE
(error) standard
*/
/* ------------------------------------------------------------ */
static int ckgolinp(int spec);
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/**
@fn static double gchsq_gol(gsl_vector *par, void *npa)
@brief Function for gsl_minimiser
This is the function passed to the golden section minimiser. npa is interpreted as a struct that is
passed as it is to gchsq_n, passing as parameter array the data
array in the gsl vector.
@param par (double *) An array
@param void *npa A mst_gen_nad struct
@return double gchsq_gol: gchsq_n(par -> data, npa)
*/
/* ------------------------------------------------------------ */
static double gchsq_gol(double *nopar, void *npa);
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/**
@fn static double gchsq_psw(gsl_vector *par, void *npa)
@brief Function for gsl_minimiser
This is the function passed to the pswarm minimiser. npa is interpreted as a struct that is
passed as it is to gchsq_n.
@param par (double *) An array
@param void *npa A mst_gen_nad struct
@return double gchsq_psw
*/
/* ------------------------------------------------------------ */
static double gchsq_psw(double *nopar, void *npa);
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/**
@fn static double gchsq_n(double *nopar, mst_gen *mst_genv)
@brief Calls the external chisquare function contained in npa
renormalising the arguments before
Will set mst_gen_nadv -> par to the renormalised input nopar.
par[i] = nopar[i]*ndpar[i]+opar[i]
@param nopar (double *) parameters to minimise, normalised
@param mst_genv (mst_gen *) struct containing additional external
arguments and original fitting function
and normalisation
@return double gchsq_n: function value of external function after
renormalising the nopar arry
*/
/* ------------------------------------------------------------ */
static double gchsq_n(double *nopar, mst_gen *mst_genv);
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/**
@fn static double gchsq_ndummy(double *nopar, mst_gen *mst_genv)
@brief Calls the external chisquare function contained in npa without
renormalising the arguments before
If normalisation is not desired this takes the place of the
normalised function. Will set mst_genv -> par to the input nopar. For later use, commented out in this version.
@param nopar (double *) parameters to minimise, not normalised
@param mst_genv (mst_gen_nad) struct containing additional external
arguments and original fitting function
and normalisation
@return double gchsq_ndummy: function value of external function after
not renormalising the nopar arry
*/
/* ------------------------------------------------------------ */
/* static double gchsq_ndummy(double *nopar, mst_gen *mst_genv); */
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/**
@fn static double gchsq_sim(gsl_vector *par, void *npa)
@brief Function for gsl_minimiser
This is the function passed to any gsl minimiser, which at the
current state is only one. npa is interpreted as a struct that is
passed as it is to gchsq_n, passing as parameter array the data
array in the gsl vector.
@param par (gsl_vector *) A gsl vector
@param void *npa A mst_gen_nad struct
@return double gchsq_sim: gchsq_n(par -> data, npa)
*/
/* ------------------------------------------------------------ */
#ifdef GFT_GSL_PRESENT
static double gchsq_sim(const gsl_vector *nopar, void *npa);
#endif
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/**
@fn static int copyvec(void *from, void *to, size_t size, size_t length)
@brief Copy an array
Copies the content of from to to. size_t is the size of a member
(can be accessed by the sizeof operator), length is the number of
elements. If from is NULL, the error returned is GFT_ERROR_OBSOLETE_OP,
if to is NULL, the error is GFT_ERROR_NULL_PASSED.
@param from (void *) array to copy
@param to (void *) goal of copy process
@param size (size_t) size of array element
@param length (size_t) length of array (part) to copy
@return (success) int copyvec: GFT_ERROR_NONE
(error) standard
*/
/* ------------------------------------------------------------ */
static int copyvec(void *from, void *to, size_t size, size_t length);
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/**
@fn static int copydblvec(double *from, double **to, size_t length)
@brief Copy an array
If the content of to is NULL, this function allocates a double array
of size length and sets to to this array. In any case it copies the
length first elements of from to *to. If from is NULL, or length is
< 1, *to is deallocated (if it exists) and set to NULL. So, *to
should be dynamically allocated. Action takes place even if an error
is returned.
@param from (double *) array to copy
@param to (double **) goal of copy process
@param length (size_t) length of array (part) to copy
@return (success) int copydblvec: GFT_ERROR_NONE
(error) standard
*/
/* ------------------------------------------------------------ */
static int copydblvec(double *from, double **to, size_t length);
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/**
@fn static int cklimits(size_t length, double *array)
@brief Check if the array is within the numberical limits
Will check every number in the array of length n if the numerical
limits are reached. This will return GFT_ERROR_OVERFLOW if the
absolute number of one of the numbers is greater than DBL_MAX.
@param length (size_t) length of array
@param array (double *) array to check
@return (success) int cklimits: GFT_ERROR_NONE
(error) standard
*/
/* ------------------------------------------------------------ */
static int cklimits(size_t length, double *array);
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/**
@fn static double makenormalnumber(double number)
@brief Check for overflow, in case of overflow, replace by largest double
This is the most primitive way to do that and I hope it's standard.
@param number (double) the number
@return double makenormalnumber
*/
/* ------------------------------------------------------------ */
static double makenormalnumber(double number);
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/**
@fn static int gft_pswarm_standardprint(pswarm_swarm *pswarm_swarmv)
@brief The output function for pswarm
This suppresses any success messages to be printed to stdout, but reports only on errors.
@param pswarm_swarmv (pswarm_swarm) Properly allocated pswarm_swarm struct (see pswarm description).
@return int gft_pswarm_standardprint() success: 0
error: 1
*/
/* ------------------------------------------------------------ */
static int gft_pswarm_standardprint(pswarm_swarm *pswarm_swarmv);
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/**
@fn static double gft_psw_startsize(int n, double *lb, double *ub, double tol, double fdelta)
@brief Calculates the initial size of the problem without using the pswarm library
@param n (int) Dimension
@param lb (double *) Lower bounds (array size is dimension)
@param ub (double *) Upper bounds (array size is dimension)
@param tol (double) Tolerance (the same as stopsize)
@param fdelta (double) Some factor, see pswarm library, use 5.0 as a default.
@return double gft_psw_startsize() size of the problem, DBL_MAX on error.
*/
/* ------------------------------------------------------------ */
static double gft_psw_startsize(int n, double *lb, double *ub, double tol, double fdelta);
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/**
@fn static int outfcn(pswarm_options *opt, pswarm_swarm *pop)
@brief Output for testing pswarm implementation
Prints some information.
@param opt (pswarm_options *) Properly allocated pswarm_options struct
@param pop (pswarm_swarm *) Properly allocated pswarm_swarm struct
@return int outfcn() 0: success, != 0 on error
*/
/* ------------------------------------------------------------ */
/* static int outfcn(pswarm_options *opt, pswarm_swarm *pop); */
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/* FUNCTION CODE */
/* ------------------------------------------------------------ */
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/* Get top layer to fitting control object */
gft_mst *gft_mst_const()
{
return (gft_mst *) mst_const();
}
/* ------------------------------------------------------------ */
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/* destroys gft_mst * struct */
int gft_mst_destr(gft_mst *gft_mstv)
{
return mst_destr((mst *) gft_mstv);
}
/* ------------------------------------------------------------ */
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/* Input of info */
int gft_mst_put (gft_mst *gft_mstv, void *input, int spec)
{
return mst_put((mst *) gft_mstv, input, spec);
}
/* ------------------------------------------------------------ */
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/* Input of info */
int gft_mst_putf (gft_mst *gft_mstv, double (*input)(double *, void *), int spec)
{
return mst_putf((mst *) gft_mstv, input, spec);
}
/* ------------------------------------------------------------ */
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/* Output of info */
int gft_mst_get(gft_mst *gft_mstv, void *output, int spec)
{
return mst_get((mst *) gft_mstv, output, spec);
}
/* ------------------------------------------------------------ */
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/* Action! */
int gft_mst_act(gft_mst *gft_mstv, int spec)
{
return mst_act((mst *) gft_mstv, spec);
}
/* ------------------------------------------------------------ */
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/* Constructs a mst struct */
static mst *mst_const()
{
mst *mst_const = NULL;
if (!(mst_const = (mst *) malloc(sizeof(mst))))
return NULL;
mst_const -> method = MET_NONE;
mst_const -> gen = NULL;
mst_const -> spe = NULL;
if (!(mst_const -> gen = mst_gen_const())) {
mst_destr(mst_const);
return NULL;
}
return mst_const;
}
/* ------------------------------------------------------------ */
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/* Destroys mst * struct */
static int mst_destr(mst *mstv)
{
int mst_destr = GFT_ERROR_NONE;
if (!mstv)
return GFT_ERROR_NULL_PASSED;
if ((mstv -> gen))
mst_destr = mst_gen_destr(mstv -> gen) | GFT_ERROR_MEMORY_LEAK;
if ((mstv -> spe))
mst_destr = mst_spe_destr(mstv -> spe, mstv -> method) | GFT_ERROR_MEMORY_LEAK;
free(mstv);
return mst_destr;
}
/* ------------------------------------------------------------ */
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/* Flush mst * struct */
static int mst_flush(mst *mstv)
{
int mst_flush = GFT_ERROR_NONE;
if (!mstv)
return GFT_ERROR_NULL_PASSED;
if ((mstv -> gen))
mst_flush = mst_gen_destr(mstv -> gen) | GFT_ERROR_MEMORY_LEAK;
if ((mstv -> spe))
mst_flush = mst_spe_destr(mstv -> spe, mstv -> method) | GFT_ERROR_MEMORY_LEAK;
mstv -> gen = NULL;
mstv -> spe = NULL;
return mst_flush;
}
/* ------------------------------------------------------------ */
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/* Stop fitting */
static int mst_stop(mst *mstv)
{
if (!mstv)
return GFT_ERROR_NULL_PASSED;
if (!(mstv -> gen -> busy || mstv -> gen -> stopped))
return GFT_ERROR_NONE;
if (!mst_gen_ckbu(mstv -> gen))
mstv -> gen -> busy = GFT_BUSY_CHAR_YES;
mstv -> gen -> stopped = GFT_STOP_CHAR_STOP;
return GFT_ERROR_NONE;
}
/* ------------------------------------------------------------ */
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/* Action!!! Somewhere here a completeness check, please */
static int mst_start(mst *mstv)
{
int mst_start_ret = GFT_ERROR_NONE;
/* This is an endless loop replacing a recursive definition of this
function that caused a segfault */
while (1) {
/* Check if action is allowed */
if (!mstv || !mstv -> gen)
return GFT_ERROR_NULL_PASSED;
/* Check if this can be started at all */
if (mstv -> gen -> misinf)
return GFT_ERROR_MISSING_INFO;
/* Check if we do anything, if there's an error or the process has
been stopped within execution of one loop, we do this */
if ((mstv -> gen -> error) || (mstv -> gen -> stopped & GFT_STOP_CHAR_STOP)) {
mstv -> gen -> stopped = GFT_STOP_CHAR_DO;
mstv -> gen -> busy = GFT_BUSY_CHAR_YES;
return mstv -> gen -> error;
}
/* A break */
if (mstv -> gen -> stopped == GFT_STOP_CHAR_DO && mstv -> gen -> busy == GFT_BUSY_CHAR_NO) {
mstv -> gen -> stopped = GFT_STOP_CHAR_ID;
return mstv -> gen -> error;
}
/* A continued stop */
if (mstv -> gen -> stopped & GFT_STOP_CHAR_DO && mstv -> gen -> busy)
mstv -> gen -> stopped = GFT_STOP_CHAR_ID;
/* This indicates a new start, one has to initialise */
if (!mstv -> gen -> busy) {
/* If there are no loops or similar, we just initiate and return */
if ( !mstv -> gen -> ncalls \
|| !mstv -> gen -> niters \
|| !mstv -> gen -> loops) {
mstv -> gen -> busy = GFT_BUSY_CHAR_NO;
mstv -> gen -> error = mst_gen_init(mstv -> gen);
mstv -> gen -> stopped = GFT_STOP_CHAR_DO;
return mstv -> gen -> error;
}
if ((mstv -> gen -> error = (mst_initspe(mstv))))
return mstv -> gen -> error;
/* We're at it, we ignore the initialisation */
mstv -> gen -> busy = GFT_BUSY_CHAR_YES;
mstv -> gen -> calls = 0;
mstv -> gen -> iters = 0;
mstv -> gen -> calls_st = 0;
mstv -> gen -> loop = 0;
}
/* Do an iteration */
mst_start_ret = mst_iterspe(mstv);
/* Now check if we're finished already because of parameters */
if (mstv -> gen -> calls >= mstv -> gen -> ncalls \
|| mstv -> gen -> iters >= mstv -> gen -> niters \
|| mstv -> gen -> loop >= mstv -> gen -> loops) {
mstv -> gen -> stopped = GFT_STOP_CHAR_DO;
mstv -> gen -> busy = GFT_BUSY_CHAR_NO;
++mstv -> gen -> minruns;
}
}
/* DEBUG: Before the endless loop above was reached with the
following recursive call, which resulted in a
segfault. Obviously, the stack filled up for no obvious
reason. Therefore, this was changed into an endless loop */
/* mst_start(mstv); */
/* Dummy */
return mst_start_ret;
}
/* ------------------------------------------------------------ */
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/* Break fitting */
static int mst_iterspe(mst *mstv)
{
int mst_iterspe = GFT_ERROR_NONE;
/**********/
/**********/
/* fprintf(stderr,"mst_iterspe mst_iterspe_ret/error: %i %i\n", mst_iterspe, mstv -> gen -> error); */
/**********/
switch (mstv -> method) {
case GFT_MET_SIMPLEX:
mst_iterspe = mst_sim_iter((mst_sim *) mstv -> spe, mstv -> gen);
break;
case GFT_MET_PSWARM:
mst_iterspe = mst_psw_iter((mst_psw *) mstv -> spe, mstv -> gen);
break;
case GFT_MET_GOLDEN:
mst_iterspe = mst_gol_iter((mst_gol *) mstv -> spe, mstv -> gen);
break;
}
/* This should work without checking of anything, all checks are
done in the calling functions */
return mst_iterspe;
}
/* ------------------------------------------------------------ */
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/* Break fitting */
static int mst_break(mst *mstv)
{
if (!mstv)
return GFT_ERROR_NULL_PASSED;
/* This sets the break status to 1, the fitting loop will be broken
instantly */
if ((mstv -> gen -> busy)) {
if ((mstv -> gen -> stopped)) {
mstv -> gen -> stopped = mstv -> gen -> busy = 0;
}
else {
mstv -> gen -> busy = 0;
mstv -> gen -> stopped = 1;
}
}
return GFT_ERROR_NONE;
}
/* ------------------------------------------------------------ */
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/* specify method for fitting */
static int mst_put(mst *mstv, void *input, int spec)
{
int mst_put = GFT_ERROR_NONE;
double *input_dbl;
int *input_int;
size_t *input_size_t;
size_t i;
if (!(mstv && mstv -> gen))
return GFT_ERROR_NULL_PASSED;
if (mstv -> gen -> error)
return GFT_ERROR_ERROR_PRESENT;
if (!input)
mst_put |= GFT_ERROR_NULL_PASSED;
/* These are allowed during fitting */
switch (spec) {
/* external arguments */
case GFT_INPUT_ADAR:
mstv -> gen -> adar = input;
break;
/* These are allowed only when idle */
default:
if (mst_gen_ckbu(mstv -> gen)) {
/* fprintf(stderr,"heyho "); */
return GFT_ERROR_BUSY;
}
switch (spec) {
/* fit method */
case GFT_INPUT_METHOD:
/* This is an int */
input_int = (int *) input;
if (mst_ckme(*input_int)) {
mst_put |= GFT_ERROR_WRONG_IDENT;
break;
}
/* Now destroy the current spe struct */
mst_put |= mst_spe_destr(mstv -> spe, mstv -> method);
/* Reset the spe struct */
mstv -> spe = NULL;
/* These are not valid anymore */
FLUSH_COND(mstv -> gen -> solpar);
FLUSH_COND(mstv -> gen -> solerr);
/* specify method */
mstv -> method = *input_int;
break;
/* Number of parameters, heaviest thing to do */
case GFT_INPUT_NPAR:
input_size_t = (size_t *) input;
if (!input_size_t) {
mst_put |= GFT_ERROR_NULL_PASSED;
break;
}
/* less than 0 counts as 0 */
mstv -> gen -> npar = *input_size_t;
/* Now flush the generic part and destroy the specific part */
mst_put |= mst_gen_flush(mstv -> gen);
mst_put |= mst_spe_destr(mstv -> spe, mstv -> method);
mstv -> spe = NULL;
break;
/* Actual parameters */
case GFT_INPUT_PAR:
input_dbl = (double *) input;
mst_put |= copydblvec(input_dbl, &mstv -> gen -> par, mstv -> gen -> npar);
break;
/* Start parameters */
case GFT_INPUT_SPAR:
input_dbl = (double *) input;
mst_put |= copydblvec(input_dbl, &mstv -> gen -> spar, mstv -> gen -> npar);
break;
/* Upper bounds */
case GFT_INPUT_UBOUNDS:
input_dbl = (double *) input;
mst_put |= copydblvec(input_dbl, &mstv -> gen -> ubounds, mstv -> gen -> npar);
break;
/* Start parameters */
case GFT_INPUT_LBOUNDS:
input_dbl = (double *) input;
mst_put |= copydblvec(input_dbl, &mstv -> gen -> lbounds, mstv -> gen -> npar);
break;
/* Grid origin */
case GFT_INPUT_OPAR:
input_dbl = (double *) input;
mst_put |= copydblvec(input_dbl, &mstv -> gen -> opar, mstv -> gen -> npar);
break;
/* Start step width */
case GFT_INPUT_DPAR:
input_dbl = (double *) input;
mst_put |= copydblvec(input_dbl, &mstv -> gen -> dpar, mstv -> gen -> npar);
break;
/* Grid normalisation */
case GFT_INPUT_NDPAR:
input_dbl = (double *) input;
if (mstv -> gen -> npar && input_dbl)
for (i = 0; i < mstv -> gen -> npar; ++i) {
if (!input_dbl[i])
mst_put |= GFT_ERROR_WRONG_PARAM;
}
if (mst_put & GFT_ERROR_WRONG_PARAM)
break;
mst_put |= copydblvec(input_dbl, &mstv -> gen -> ndpar, mstv -> gen -> npar);
break;
/* Total allowed function calls */
case GFT_INPUT_NCALLS:
input_size_t = (size_t *) input;
if (!input_size_t) {
mst_put |= GFT_ERROR_NULL_PASSED;
break;
}
mstv -> gen -> ncalls = *input_size_t;
break;
/* Maximum number of iteration steps */
case GFT_INPUT_NITERS:
input_size_t = (size_t *) input;
if (!input_size_t) {
mst_put |= GFT_ERROR_NULL_PASSED;
break;
}
mstv -> gen -> niters = *input_size_t;
break;
/* Function calls within a step, must be positive */
case GFT_INPUT_NCALLS_ST:
input_size_t = (size_t *) input;
if (!input_size_t) {
mst_put |= GFT_ERROR_NULL_PASSED;
break;
}
mstv -> gen -> ncalls_st = *input_size_t;
break;
/* Stopping condition, size of vector, must be positive */
case GFT_INPUT_STOPSIZE:
input_dbl = (double *) input;
if (!input_dbl) {
mst_put |= GFT_ERROR_NULL_PASSED;
break;
}
if (*input_dbl < 0)
mstv -> gen -> stopsize = 0.0;
else
mstv -> gen -> stopsize = *input_dbl;
break;
/* loops */
case GFT_INPUT_LOOPS:
input_size_t = (size_t *) input;
if (!input_size_t) {
mst_put |= GFT_ERROR_NULL_PASSED;
break;
}
mstv -> gen -> loops = *input_size_t;
break;
/* factor to multiply ncalls_st from loop to loop, must be positive */
case GFT_INPUT_NCALLS_ST_FAC:
input_dbl = (double *) input;
if (!input_dbl) {
mst_put |= GFT_ERROR_NULL_PASSED;
break;
}
if (*input_dbl < 0)
mstv -> gen -> ncalls_st_fac = 0.0;
else
mstv -> gen -> ncalls_st_fac = *input_dbl;
break;
/* factor to multiply step widths with from loop to loop, everything but zero */
case GFT_INPUT_DPAR_FAC:
input_dbl = (double *) input;
if (!input_dbl) {
mst_put |= GFT_ERROR_NULL_PASSED;
break;
}
if (*input_dbl == 0)
mstv -> gen -> dpar_fac = 1.0;
else
mstv -> gen -> dpar_fac = *input_dbl;
break;
/* factor to multiply stopping condition with from loop to loop */
case GFT_INPUT_STOPSIZE_FAC:
input_dbl = (double *) input;
if (!input_dbl) {
mst_put |= GFT_ERROR_NULL_PASSED;
break;
}
if (*input_dbl < 0)
mstv -> gen -> stopsize_fac = 0.0;
else
mstv -> gen -> stopsize_fac = *input_dbl;
break;
case GFT_INPUT_INDPOINTS:
input_dbl = (double *) input;
if (!input_dbl) {
mst_put |= GFT_ERROR_NULL_PASSED;
break;
}
mstv -> gen -> indpoints = *input_dbl;
/* Report here if the parameter was bad */
if (mstv -> gen -> indpoints - (double) mstv -> gen -> npar < 1.0)
mst_put |= GFT_ERROR_WRONG_PARAM;
break;
case GFT_INPUT_SEED:
input_int = (int *) input;
if (!input_int) {
mst_put |= GFT_ERROR_NULL_PASSED;
break;
}
mstv -> gen -> seed = *input_int;
break;
case GFT_INPUT_PSNPART:
input_int = (int *) input;
if (!input_int) {
mst_put |= GFT_ERROR_NULL_PASSED;
break;
}
mstv -> gen -> psnpart = *input_int;
break;
/* pswarm cognitional parameter */
case GFT_INPUT_PSCOGNI:
input_dbl = (double *) input;
if (!input_dbl) {
mst_put |= GFT_ERROR_NULL_PASSED;
break;
}
mstv -> gen -> pscogni = *input_dbl;
break;
/* pswarm cognitional parameter */
case GFT_INPUT_PSSOCIA:
input_dbl = (double *) input;
if (!input_dbl) {
mst_put |= GFT_ERROR_NULL_PASSED;
break;
}
mstv -> gen -> pssocia = *input_dbl;
break;
case GFT_INPUT_PSMAXVF:
input_dbl = (double *) input;
if (!input_dbl) {
mst_put |= GFT_ERROR_NULL_PASSED;
break;
}
mstv -> gen -> psmaxvf = *input_dbl;
break;
case GFT_INPUT_PSNITFI:
input_int = (int *) input;
if (!input_int) {
mst_put |= GFT_ERROR_NULL_PASSED;
break;
}
mstv -> gen -> psnitfi = *input_int;
break;
case GFT_INPUT_PSINIIN:
input_dbl = (double *) input;
if (!input_dbl) {
mst_put |= GFT_ERROR_NULL_PASSED;
break;
}
mstv -> gen -> psiniin = *input_dbl;
break;
case GFT_INPUT_PSFININ:
input_dbl = (double *) input;
if (!input_dbl) {
mst_put |= GFT_ERROR_NULL_PASSED;
break;
}
mstv -> gen -> psfinin = *input_dbl;
break;
case GFT_INPUT_PSINCDE:
input_dbl = (double *) input;
if (!input_dbl) {
mst_put |= GFT_ERROR_NULL_PASSED;
break;
}
mstv -> gen -> psincde = *input_dbl;
break;
case GFT_INPUT_PSDECDE:
input_dbl = (double *) input;
if (!input_dbl) {
mst_put |= GFT_ERROR_NULL_PASSED;
break;
}
mstv -> gen -> psdecde = *input_dbl;
break;
default:
return GFT_ERROR_WRONG_IDENT;
}
}
return mst_refresh(mstv) | mst_put | ckmetinp(mstv -> method, spec);
}
/* ------------------------------------------------------------ */
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/* specify fitting function */
static int mst_putf(mst *mstv, double (*input)(double *, void *), int spec)
{
int mst_putf = GFT_ERROR_NONE;
if (!(mstv && mstv -> gen))
return GFT_ERROR_NULL_PASSED;
if (mstv -> gen -> error)
return GFT_ERROR_ERROR_PRESENT;
if (!input)
mst_putf |= GFT_ERROR_NULL_PASSED;
/* These are allowed during fitting */
switch (spec) {
/* external function without flushing best fit parameters */
case GFT_INPUT_GCHSQ_REP:
mstv -> gen -> gchsq = input;
return mst_putf;
break;
/* These are allowed only when idle */
default:
if (mst_gen_ckbu(mstv -> gen))
return GFT_ERROR_BUSY;
switch (spec) {
/* external function */
case GFT_INPUT_GCHSQ:
if (!input)
mst_putf |= GFT_ERROR_NULL_PASSED;
/* the chisquares are not valid anymore */
FLUSH_COND(mstv -> gen -> bestpar);
FLUSH_COND(mstv -> gen -> solpar);
FLUSH_COND(mstv -> gen -> solerr);
/* This is a new function that has never been called */
mstv -> gen -> allcalls = 0;
mstv -> gen -> alliter = 0;
mstv -> gen -> alloops = 0;
mstv -> gen -> gchsq = input;
break;
default:
return GFT_ERROR_WRONG_IDENT;
}
}
return mst_refresh(mstv) | mst_putf;
}
/* ------------------------------------------------------------ */
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/* Generically get information from a minimiser struct, intern */
static int mst_get(mst *mstv, void *output, int spec)
{
int mst_get = GFT_ERROR_NONE;
if (!mstv)
return GFT_ERROR_NULL_PASSED;
/* Note that if the mst struct is there, the gen component will be
allocated, too. This is silly, why a gen struct at all? This is
an error of history that is hard to remove, and I'm too lazy */
switch (spec) {
case GFT_OUTPUT_MISINF:
mst_get |= copyvec(&mstv -> gen -> misinf, output, sizeof(int), 1);
break;
case GFT_OUTPUT_BUSY:
mst_get |= copyvec(&mstv -> gen -> busy, output, sizeof(int), 1);
break;
case GFT_OUTPUT_STOPPED:
mst_get |= copyvec(&mstv -> gen -> stopped, output, sizeof(int), 1);
break;
case GFT_OUTPUT_ERROR:
mst_get |= copyvec(&mstv -> gen -> error, output, sizeof(int), 1);
break;
case GFT_OUTPUT_ALLCALLS:
mst_get |= copyvec(&mstv -> gen -> allcalls, output, sizeof(size_t), 1);
break;
case GFT_OUTPUT_ALLITER:
mst_get |= copyvec(&mstv -> gen -> alliter, output, sizeof(size_t), 1);
break;
case GFT_OUTPUT_ALLOOPS:
mst_get |= copyvec(&mstv -> gen -> alloops, output, sizeof(size_t), 1);
break;
case GFT_OUTPUT_MINRUNS:
mst_get |= copyvec(&mstv -> gen -> minruns, output, sizeof(size_t), 1);
break;
case GFT_OUTPUT_METHOD:
mst_get |= copyvec(&mstv -> method, output, sizeof(int), 1);
break;
case GFT_OUTPUT_NPAR:
mst_get |= copyvec(&mstv -> gen -> npar, output, sizeof(size_t), 1);
break;
case GFT_OUTPUT_NPAR_CUR:
mst_get |= copyvec(&mstv -> gen -> npar_cur, output, sizeof(int), 1);
break;
case GFT_OUTPUT_INDPOINTS:
mst_get |= copyvec(&mstv -> gen -> indpoints, output, sizeof(double), 1);
break;
case GFT_OUTPUT_ACTCHISQ:
mst_get |= copyvec(&mstv -> gen -> actchisq, output, sizeof(double), 1);
break;
case GFT_OUTPUT_ACTCHISQRED:
mst_get |= copyvec(&mstv -> gen -> actchisqred, output, sizeof(double), 1);
break;
case GFT_OUTPUT_BESTCHISQ:
mst_get |= copyvec(&mstv -> gen -> bestchisq, output, sizeof(double), 1);
break;
case GFT_OUTPUT_BESTCHISQRED:
mst_get |= copyvec(&mstv -> gen -> bestchisqred, output, sizeof(double), 1);
break;
case GFT_OUTPUT_PAR:
mst_get |= copyvec(mstv -> gen -> par, output, sizeof(double), mstv -> gen -> npar);
break;
case GFT_OUTPUT_BESTPAR:
mst_get |= copyvec(mstv -> gen -> bestpar, output, sizeof(double), mstv -> gen -> npar);
break;
case GFT_OUTPUT_SOLPAR:
mst_get |= copyvec(mstv -> gen -> solpar, output, sizeof(double), mstv -> gen -> npar);
break;
case GFT_OUTPUT_SOLERR:
mst_get |= copyvec(mstv -> gen -> solerr, output, sizeof(double), mstv -> gen -> npar);
break;
case GFT_OUTPUT_SOLCHSQ:
mst_get |= copyvec(&mstv -> gen -> solchsq, output, sizeof(double), 1);
break;
case GFT_OUTPUT_SOLCHSQRED:
mst_get |= copyvec(&mstv -> gen -> solchsqred, output, sizeof(double), 1);
break;
case GFT_OUTPUT_SPAR:
mst_get |= copyvec(mstv -> gen -> spar, output, sizeof(double), mstv -> gen -> npar);
break;
case GFT_OUTPUT_OPAR:
mst_get |= copyvec(mstv -> gen -> opar, output, sizeof(double), mstv -> gen -> npar);
break;
case GFT_OUTPUT_UBOUNDS:
mst_get |= copyvec(mstv -> gen -> ubounds, output, sizeof(double), mstv -> gen -> npar);
break;
case GFT_OUTPUT_LBOUNDS:
mst_get |= copyvec(mstv -> gen -> lbounds, output, sizeof(double), mstv -> gen -> npar);
break;
case GFT_OUTPUT_DPAR:
mst_get |= copyvec(mstv -> gen -> dpar, output, sizeof(double), mstv -> gen -> npar);
break;
case GFT_OUTPUT_NDPAR:
mst_get |= copyvec(mstv -> gen -> ndpar, output, sizeof(double), mstv -> gen -> npar);
break;
case GFT_OUTPUT_ADAR:
output = mstv -> gen -> adar;
break;
case GFT_OUTPUT_NCALLS:
mst_get |= copyvec(&mstv -> gen -> ncalls, output, sizeof(size_t), 1);
break;
case GFT_OUTPUT_CALLS:
mst_get |= copyvec(&mstv -> gen -> calls, output, sizeof(size_t), 1);
break;
case GFT_OUTPUT_NITERS:
mst_get |= copyvec(&mstv -> gen -> niters, output, sizeof(size_t), 1);
break;
case GFT_OUTPUT_ITERS:
mst_get |= copyvec(&mstv -> gen -> iters, output, sizeof(size_t), 1);
break;
case GFT_OUTPUT_NCALLS_ST:
mst_get |= copyvec(&mstv -> gen -> ncalls_st, output, sizeof(size_t), 1);
break;
case GFT_OUTPUT_CALLS_ST:
mst_get |= copyvec(&mstv -> gen -> calls_st, output, sizeof(size_t), 1);
break;
case GFT_OUTPUT_STOPSIZE:
mst_get |= copyvec(&mstv -> gen -> stopsize, output, sizeof(double), 1);
break;
case GFT_OUTPUT_STOPSIZE_ACT:
mst_get |= copyvec(&mstv -> gen -> stopsize_act, output, sizeof(double), 1);
break;
case GFT_OUTPUT_SIZE:
mst_get |= copyvec(&mstv -> gen -> size, output, sizeof(double), 1);
break;
case GFT_OUTPUT_DSIZE:
mst_get |= copyvec(&mstv -> gen -> dsize, output, sizeof(double), 1);
break;
case GFT_OUTPUT_LOOPS:
mst_get |= copyvec(&mstv -> gen -> loops, output, sizeof(size_t), 1);
break;
case GFT_OUTPUT_LOOP:
mst_get |= copyvec(&mstv -> gen -> loop, output, sizeof(size_t), 1);
break;
case GFT_OUTPUT_NCALLS_ST_FAC:
mst_get |= copyvec(&mstv -> gen -> ncalls_st_fac, output, sizeof(double), 1);
break;
case GFT_OUTPUT_DPAR_FAC:
mst_get |= copyvec(&mstv -> gen -> dpar_fac, output, sizeof(double), 1);
break;
case GFT_OUTPUT_STOPSIZE_FAC:
mst_get |= copyvec(&mstv -> gen -> stopsize_fac, output, sizeof(double), 1);
break;
case GFT_OUTPUT_NOPAR:
mst_get |= copyvec(mstv -> gen -> nopar, output, sizeof(double), mstv -> gen -> npar);
break;
case GFT_OUTPUT_NOUBOUNDS:
mst_get |= copyvec(mstv -> gen -> noubounds, output, sizeof(double), mstv -> gen -> npar);
break;
case GFT_OUTPUT_NOLBOUNDS:
mst_get |= copyvec(mstv -> gen -> nolbounds, output, sizeof(double), mstv -> gen -> npar);
break;
case GFT_OUTPUT_SEED:
mst_get |= copyvec(&mstv -> gen -> seed, output, sizeof(int), 1);
break;
case GFT_OUTPUT_PSNPART:
mst_get |= copyvec(&mstv -> gen -> psnpart, output, sizeof(int), 1);
break;
case GFT_OUTPUT_PSCOGNI:
mst_get |= copyvec(&mstv -> gen -> pscogni, output, sizeof(double), 1);
break;
case GFT_OUTPUT_PSSOCIA:
mst_get |= copyvec(&mstv -> gen -> pssocia, output, sizeof(double), 1);
break;
case GFT_OUTPUT_PSMAXVF:
mst_get |= copyvec(&mstv -> gen -> psmaxvf, output, sizeof(double), 1);
break;
case GFT_OUTPUT_PSNITFI:
mst_get |= copyvec(&mstv -> gen -> psnitfi, output, sizeof(int), 1);
break;
case GFT_OUTPUT_PSINIIN:
mst_get |= copyvec(&mstv -> gen -> psiniin, output, sizeof(double), 1);
break;
case GFT_OUTPUT_PSFININ:
mst_get |= copyvec(&mstv -> gen -> psfinin, output, sizeof(double), 1);
break;
case GFT_OUTPUT_PSINCDE:
mst_get |= copyvec(&mstv -> gen -> psincde, output, sizeof(double), 1);
break;
case GFT_OUTPUT_PSDECDE:
mst_get |= copyvec(&mstv -> gen -> psdecde, output, sizeof(double), 1);
break;
default:
mst_get |= GFT_ERROR_WRONG_PARAM;
}
return mst_get | mst_ckop(mstv, spec);
}
/* ------------------------------------------------------------ */
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/* check if an output makes sense */
static int mst_ckop(mst *mstv, int spec)
{
int mst_ckop = GFT_ERROR_NONE;
/***********/
/***********/
/* fprintf(stderr,"mst_ckop %i\n", mst_ckop); */
/***********/
mst_ckop |= mst_gen_ckop(mstv -> gen, spec);
mst_ckop |= mst_spe_ckop(mstv -> spe, spec, mstv -> method);
return mst_ckop;
}
/* ------------------------------------------------------------ */
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/* Action! */
static int mst_act(mst *mstv, int spec)
{
int mst_act = GFT_ERROR_NONE;
/* The called functions will check a NULL pointer passed */
switch (spec) {
case GFT_ACT_FLUSH:
mst_act |= mst_flush(mstv);
if ((mstv))
mst_act |= (mstv -> gen = mst_gen_const())?0:GFT_ERROR_MEMORY_ALLOC;
break;
case GFT_ACT_INIT:
return mst_gen_init(mstv -> gen);
break;
case GFT_ACT_STOP:
return mst_stop(mstv);
break;
case GFT_ACT_START:
return mst_start(mstv);
break;
case GFT_ACT_BREAK:
return mst_break(mstv);
break;
default:
mst_act |= GFT_ERROR_WRONG_IDENT;
}
return mst_act;
}
/* ------------------------------------------------------------ */
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/* check existence of fit method */
static int mst_ckme(int method)
{
switch (method) {
case GFT_MET_SIMPLEX:
return MET_SIMPLEX>0?GFT_ERROR_NONE:GFT_ERROR_WRONG_IDENT;
case GFT_MET_GOLDEN:
return GFT_ERROR_NONE;
case GFT_MET_PSWARM:
return GFT_ERROR_NONE;
default:
;
}
return GFT_ERROR_WRONG_IDENT;
}
/* ------------------------------------------------------------ */
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/* Do initialisations of specific minimiser that needs
a call of the minimising function */
static int mst_initspe(mst *mstv)
{
int mst_initspe = GFT_ERROR_NONE;
switch (mstv -> method) {
case GFT_MET_SIMPLEX:
mst_initspe = mst_sim_init((mst_sim *) mstv -> spe, mstv -> gen);
break;
case GFT_MET_GOLDEN:
mst_initspe = mst_gol_init((mst_gol *) mstv -> spe, mstv -> gen);
break;
case GFT_MET_PSWARM:
mst_initspe = mst_psw_init((mst_psw *) mstv -> spe, mstv -> gen);
break;
}
/* This should work without checking of anything, all checks are
done in the calling functions */
return mst_initspe;
}
/* ------------------------------------------------------------ */
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/* static int mst_refresh(mst *mstv) */
static int mst_refresh(mst *mstv)
{
int mst_refresh = GFT_ERROR_NONE;
mstv -> gen -> misinf = GFT_ERROR_NONE;
/* set misinf refreshing the generic part */
mst_refresh |= mst_gen_refresh(mstv -> gen);
mstv -> gen -> misinf |= mst_refresh;
/* refresh the specific part if there are no memory problems */
if (!(mstv -> gen -> misinf & GFT_ERROR_MEMORY_ALLOC)) {
mst_refresh |= mst_refreshspe(mstv);
mstv -> gen -> misinf |= mst_refresh;
}
/* We got here, so we were successful */
return mst_refresh;
}
/* ------------------------------------------------------------ */
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/* Refresh specific part of fit control struct */
static int mst_refreshspe(mst *mstv)
{
int mst_refreshspe = GFT_ERROR_NONE;
if (!mstv)
return 1;
/* Check existence of fit method */
if (mst_ckme(mstv -> method)) {
mstv -> gen -> misinf |= GFT_ERROR_WRONG_IDENT;
return GFT_ERROR_NONE;
}
/* If the spe part is not allocated, do so */
if (!(mstv -> spe)) {
if (!(mstv -> spe = mst_spe_const(mstv -> method)))
return GFT_ERROR_MEMORY_ALLOC;
}
/* refresh the specific part */
switch(mstv -> method) {
case GFT_MET_SIMPLEX:
mst_refreshspe = mst_refreshsim(mstv);
break;
case GFT_MET_GOLDEN:
mst_refreshspe = mst_refreshgol(mstv);
break;
case GFT_MET_PSWARM:
mst_refreshspe = mst_refreshpsw(mstv);
break;
}
/* finis */
return mst_refreshspe;
}
/* ------------------------------------------------------------ */
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/* Refresh specific part of fit control struct */
static int mst_refreshsim(mst *mstv)
#if MET_SIMPLEX == -2
{
return GFT_ERROR_WRONG_IDENT;
}
#else
{
size_t i;
double cl, srt;
int mst_refreshsim = GFT_ERROR_NONE;
mst_sim *mst_simv;
mst_simv = (mst_sim *) mstv -> spe;
/* The specific function is in any case this one */
mst_simv -> multimin_function_gsl -> f = &gchsq_sim;
/* The additional parameters are allocated */
mst_simv -> multimin_function_gsl -> params = (void *) mstv -> gen;
/* Also we know that we will use the normalised function */
mstv -> gen -> gchsq_n = &gchsq_n;
/* Check if the number of parameters is clear and basic allocations are made */
if (mstv -> gen -> npar && mstv -> gen -> spar && mstv -> gen -> dpar) {
/* Slot in the start grid vectors, they exist if this is called */
for (i = 0; i < mstv -> gen -> npar; ++i) {
mstv -> gen -> nospar[i] = (mstv -> gen -> spar[i]-mstv -> gen -> opar[i])/mstv -> gen -> ndpar[i];
mstv -> gen -> nodpar[i] = mstv -> gen -> dpar[i]/mstv -> gen -> ndpar[i];
mstv -> gen -> nopar[i] = (mstv -> gen -> par[i]-mstv -> gen -> opar[i])/mstv -> gen -> ndpar[i];
}
/* The normalisation for the characteristic length is given by */
mst_simv -> vlnorm = 1.0/(((double) mstv -> gen -> npar*sqrt((double) mstv -> gen -> npar*(double) mstv -> gen -> npar+(double) mstv -> gen -> npar-1)+sqrt((double) mstv -> gen -> npar))/(((double) mstv -> gen -> npar+1)*((double) mstv -> gen -> npar+1)));
/* calculate the inverse of the characteristic length given by the gsl without initialising */
cl = 0.0;
srt = 0.0;
for (i = 0; i < mstv -> gen -> npar; ++i) {
srt += mstv -> gen -> nodpar[i]*mstv -> gen -> nodpar[i];
}
for (i = 0; i < mstv -> gen -> npar; ++i) {
cl += sqrt(((double) mstv -> gen -> npar* (double) mstv -> gen -> npar-1)*mstv -> gen -> nodpar[i]*mstv -> gen -> nodpar[i]+srt);
}
cl += sqrt(srt);
/* Now this is the characteristic length that we can give */
mstv -> gen -> size = mst_simv -> vlnorm*cl/(((double) mstv -> gen -> npar+1)*((double) mstv -> gen -> npar+1));
/* If already done, this causes no memory leak, since the
minimiser won't touch nodpar, we do not make a local copy */
/* if (!(mst_refreshsim = copydblvec(mstv -> gen -> nodpar, &mst_simv -> stp_vec, mstv -> gen -> npar))) { */
/* fill_gsl_dbl_vector(mst_simv -> stp_gsl_vec, mst_simv -> stp_vec, &mst_simv -> stp_gsl_block, mstv -> gen -> npar); */
/* } */
mstv -> gen -> misinf |= mst_refreshsim |= fill_gsl_dbl_vector(&mst_simv -> stp_gsl_vec, mstv -> gen -> nodpar, mstv -> gen -> npar);
mstv -> gen -> misinf |= mst_refreshsim |= fill_gsl_dbl_vector(&mst_simv -> var_gsl_vec, mstv -> gen -> nospar, mstv -> gen -> npar);
/*************/
/*************/
/* fprintf(stderr,"gsl step vector: "); */
/* for (i = 0; i < mstv -> gen -> npar; ++i) { */
/* fprintf(stderr,"%.1e ", gsl_vector_get (mst_simv -> stp_gsl_vec, i)); */
/* } */
/* fprintf(stderr,"\n"); */
/* fprintf(stderr,"input tried: "); */
/* for (i = 0; i < mstv -> gen -> npar; ++i) { */
/* fprintf(stderr,"%.1e ", mstv -> gen -> nodpar[i]); */
/* } */
/* fprintf(stderr,"\n"); */
/*************/
/* Copy the content of nopar to the local copy */
/* ERROR SOURCE??? Here, we copy the start parameters, not the actual parameters */
/* if (!(mst_refreshsim = copydblvec(mstv -> gen -> nospar, &mst_simv -> var_vec, mstv -> gen -> npar))) */
/* fill_gsl_dbl_vector(mst_simv -> var_gsl_vec, mst_simv -> var_vec, &mst_simv -> var_gsl_block, mstv -> gen -> npar); */
/* We can tell more about the function */
mst_simv -> multimin_function_gsl -> n = mstv -> gen -> npar;
/* Now we can allocate the minimiser */
if (!mst_simv -> multimin_fminimizer_gsl) {
if (!(mst_simv -> multimin_fminimizer_gsl = gsl_multimin_fminimizer_alloc (mst_simv -> multimin_fminimizer_type_gsl, mstv -> gen -> npar)))
mst_refreshsim |= GFT_ERROR_MEMORY_ALLOC;
}
/* What is missing is the initialisation of the minimiser calling
gsl_multimin_fminimizer_set (mst_simv -> multimin_fminimizer_gsl,
mst_simv -> multimin_function_gsl, mst_simv -> var_gsl_vec, mst_simv
-> stp_gsl_vec); . Since this will call the chisquare function, we do
this when starting the minimising process */
}
else
mstv -> gen -> misinf |= GFT_ERROR_MISSING_INFO;
mst_simv -> eqchisq = 0;
mst_simv -> eqchisq2 = 0;
mst_simv -> chisqbef = -1.0;
mst_simv -> chisqbef2 = -1.0;
/* finis */
return mst_refreshsim;
}
#endif
/* ------------------------------------------------------------ */
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/* Refresh specific part of fit control struct */
static int mst_refreshpsw(mst *mstv)
{
size_t i;
int mst_refreshpsw = GFT_ERROR_NONE;
mst_psw *mst_pswv;
mst_pswv = (mst_psw *) mstv -> spe;
/* The specific function is in any case this one */
/* mst_pswv -> multimin_function_gsl -> f = &gchsq_psw; */
/* The additional parameters are allocated */
/* mst_simv -> multimin_function_gsl -> params = (void *) mstv -> gen; */
/* Also we know that we will use the normalised function */
mstv -> gen -> gchsq_n = &gchsq_n;
/* Check if the number of parameters is clear and basic allocations are made */
if (mstv -> gen -> npar && mstv -> gen -> spar && mstv -> gen -> dpar && mstv -> gen -> ubounds && mstv -> gen -> lbounds) {
/* Slot in the start grid vectors, they exist if this is called */
for (i = 0; i < mstv -> gen -> npar; ++i) {
mstv -> gen -> nospar[i] = (mstv -> gen -> spar[i]-mstv -> gen -> opar[i])/mstv -> gen -> ndpar[i];
mstv -> gen -> noubounds[i] = (mstv -> gen -> ubounds[i]-mstv -> gen -> opar[i])/mstv -> gen -> ndpar[i];
mstv -> gen -> nolbounds[i] = (mstv -> gen -> lbounds[i]-mstv -> gen -> opar[i])/mstv -> gen -> ndpar[i];
mstv -> gen -> nodpar[i] = mstv -> gen -> dpar[i]/mstv -> gen -> ndpar[i];
mstv -> gen -> nopar[i] = (mstv -> gen -> par[i]-mstv -> gen -> opar[i])/mstv -> gen -> ndpar[i];
}
/* If the vector does not yet exist, it will be created and be filled with the defaults */
/* if (!(mst_pswv -> curnospar)) */
copydblvec(mstv -> gen -> nospar, &mst_pswv -> curnospar, mstv -> gen -> npar);
/* calculate the size without calling the function */
if (mstv -> gen -> stopsize > 0.0)
mstv -> gen -> size = gft_psw_startsize(mstv -> gen -> npar, mstv -> gen -> nolbounds, mstv -> gen -> noubounds, mstv -> gen -> stopsize, 5.0);
else
mstv -> gen -> size = DBL_MAX;
/* Transfer nospar and nodpar ? No. */
/* mstv -> gen -> misinf |= mst_refreshpsw |= fill_gsl_dbl_vector(&mst_pswv -> stp_gsl_vec, mstv -> gen -> nodpar, mstv -> gen -> npar); */
/* mstv -> gen -> misinf |= mst_refreshpsw |= fill_gsl_dbl_vector(&mst_pswv -> var_gsl_vec, mstv -> gen -> nospar, mstv -> gen -> npar); */
/* We can tell more about the function: mstv -> gen -> npar is known */
/* mst_pswv -> multimin_function_gsl -> n = mstv -> gen -> npar; */
/* Now we can allocate the minimiser */
/* if (!mst_simv -> multimin_fminimizer_gsl) { */
/* if (!(mst_simv -> multimin_fminimizer_gsl = gsl_multimin_fminimizer_alloc (mst_simv -> multimin_fminimizer_type_gsl, mstv -> gen -> npar))) */
/* mst_refreshsim |= GFT_ERROR_MEMORY_ALLOC; */
/* } */
/* What is missing is the initialisation of the minimiser calling
gsl_multimin_fminimizer_set (mst_simv -> multimin_fminimizer_gsl,
mst_simv -> multimin_function_gsl, mst_simv -> var_gsl_vec, mst_simv
-> stp_gsl_vec); . Since this will call the chisquare function, we do
this when starting the minimising process */
}
else
mstv -> gen -> misinf |= GFT_ERROR_MISSING_INFO;
/* finis */
return mst_refreshpsw;
}
/* ------------------------------------------------------------ */
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/* Refresh specific part of fit control struct */
static int mst_refreshgol(mst *mstv)
{
size_t i;
int mst_refreshgol = GFT_ERROR_NONE;
mst_gol *mst_golv;
mst_golv = (mst_gol *) mstv -> spe;
/* The specific function is in any case this one */
/* mst_golv -> gc -> gchsq = &gchsq_gol; */
golden_i_gchsq(&gchsq_gol, mst_golv -> gc);
/* The additional parameters are allocated */
/* mst_golv -> gc -> adar = (void *) mstv -> gen; */
golden_i_adar((void *) mstv -> gen, mst_golv -> gc);
/* Also we know that we will use the normalised function */
mstv -> gen -> gchsq_n = &gchsq_n;
/* Check if the number of parameters is clear and basic allocations are made */
if (mstv -> gen -> npar && mstv -> gen -> spar && mstv -> gen -> dpar && mstv -> gen -> ncalls_st) {
/* This (de-) allocates all arrays and resets parameters to a generic value */
golden_refresh(mst_golv -> gc, mstv -> gen -> npar);
/* Slot in the start grid vectors, they exist if this is called */
for (i = 0; i < mstv -> gen -> npar; ++i) {
mstv -> gen -> nospar[i] = (mstv -> gen -> spar[i]-mstv -> gen -> opar[i])/mstv -> gen -> ndpar[i];
mstv -> gen -> nodpar[i] = mstv -> gen -> dpar[i]/mstv -> gen -> ndpar[i];
mstv -> gen -> nopar[i] = (mstv -> gen -> spar[i]-mstv -> gen -> opar[i])/mstv -> gen -> ndpar[i];
}
/* The normalisation for the characteristic length is given by */
/* calculate the inverse of the characteristic length given by the gsl without initialising */
/* Now this is the characteristic length that we can give */
/* mstv -> gen -> size = mst_golv -> gc -> solsize; */
golden_o_solsize(&(mstv -> gen -> size), mst_golv -> gc);
/* Indirect use of gc, hopefully working */
/* if (!(ndpar_here = (double *) malloc(mstv -> gen -> npar*sizeof(double)))) { */
/* mst_refreshgol |= GFT_ERROR_MEMORY_ALLOC; */
/* goto error; */
/* } */
/* This is not initialised at this stage */
/* golden_o_ncurstep(&ncurstep_here, mst_golv -> gc); */
/* golden_o_ndpar(ndpar_here, mst_golv -> gc); */
/* This is not initialised at this stage */
/* golden_o_npar_cur(&npar_cur_here, mst_golv -> gc); */
/* the current npar after a refresh is -1 */
mstv -> gen -> npar_cur = -1;
/* This is not initialised at this stage */
mstv -> gen -> dsize = mstv -> gen -> dpar[0];
/* We can tell more about the function */
/* mst_golv -> gc -> npar = mstv -> gen -> npar; */
/* and fill in the vectors */
/* mstv -> gen -> misinf |= mst_refreshgol |= copydblvec(mstv -> gen -> nodpar, &mst_golv -> gc -> nodpar, mstv -> gen -> npar); */
/* mstv -> gen -> misinf |= mst_refreshgol |= copydblvec(mstv -> gen -> nospar, &mst_golv -> gc -> nospar, mstv -> gen -> npar); */
/* mst_golv -> gc -> ncalls_st = mstv -> gen -> ncalls_st; */
/* mst_golv -> gc -> minstep = 1.0; */
mstv -> gen -> misinf |= mst_refreshgol |= golden_i_nodpar(mstv -> gen -> nodpar, mst_golv -> gc);
mstv -> gen -> misinf |= mst_refreshgol |= golden_i_nospar(mstv -> gen -> nospar, mst_golv -> gc);
/* Check if ncalls_st and minstep are initialised in gen */
golden_i_ncalls_st(mstv -> gen -> ncalls_st, mst_golv -> gc);
golden_i_minstep(1.0, mst_golv -> gc);
/* for (i = 0; i < mst_golv -> gc -> npar; ++i) */
/* fprintf(stderr,"%.3f ", mstv -> gen -> spar[i]); */
/* What is missing is the initialisation of the minimiser calling
gsl_multimin_fminimizer_set (mst_simv -> multimin_fminimizer_gsl,
mst_simv -> multimin_function_gsl, mst_simv -> var_gsl_vec, mst_simv
-> stp_gsl_vec); . Since this will call the chisquare function, we do
this when starting the minimising process */
}
else
mstv -> gen -> misinf |= GFT_ERROR_MISSING_INFO;
/* finis */
return mst_refreshgol;
}
/* ------------------------------------------------------------ */
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/* allocate and initialise internal generic struct to mstr_in */
static mst_gen *mst_gen_const()
{
mst_gen *mst_gen_const;
if (!(mst_gen_const = (mst_gen *) malloc (sizeof(mst_gen))))
return NULL;
/* if (!(mst_gen_const -> nad = mst_gen_nad_const())) */
/* return NULL; */
/* Now initialise */
mst_gen_const -> misinf = GFT_ERROR_STANDARD;
mst_gen_const -> busy = GFT_ERROR_NONE;
mst_gen_const -> error = GFT_ERROR_NONE;
mst_gen_const -> stopped = GFT_ERROR_NONE;
mst_gen_const -> broken = GFT_ERROR_NONE;
mst_gen_const -> allcalls = 0;
mst_gen_const -> alliter = 0;
mst_gen_const -> alloops = 0;
mst_gen_const -> minruns = 0;
mst_gen_const -> npar = 0;
mst_gen_const -> npar_cur = -1;
mst_gen_const -> indpoints = 0.0;
mst_gen_const -> actchisq = DBL_MAX;
mst_gen_const -> actchisqred = DBL_MAX;
mst_gen_const -> bestchisq = DBL_MAX;
mst_gen_const -> bestchisqred = DBL_MAX;
mst_gen_const -> solchsq = DBL_MAX;
mst_gen_const -> solchsqred = DBL_MAX;
mst_gen_const -> par = NULL;
mst_gen_const -> dummypar = NULL;
mst_gen_const -> dummypar2 = NULL;
mst_gen_const -> bestpar = NULL;
mst_gen_const -> solpar = NULL;
mst_gen_const -> solerr = NULL;
mst_gen_const -> spar = NULL;
mst_gen_const -> ubounds = NULL;
mst_gen_const -> lbounds = NULL;
mst_gen_const -> noubounds = NULL;
mst_gen_const -> nolbounds = NULL;
mst_gen_const -> opar = NULL;
mst_gen_const -> dpar = NULL;
mst_gen_const -> ndpar = NULL;
mst_gen_const -> gchsq = NULL;
mst_gen_const -> adar = NULL;
mst_gen_const -> ncalls = LARGE_INTEGER;
mst_gen_const -> calls = 0;
mst_gen_const -> niters = LARGE_INTEGER;
mst_gen_const -> iters = 0;
mst_gen_const -> ncalls_st = LARGE_INTEGER;
mst_gen_const -> calls_st = 0;
mst_gen_const -> stopsize = 0.0;
mst_gen_const -> stopsize_act = 0.0;
mst_gen_const -> size = 1.0;
mst_gen_const -> dsize = 0.0;
mst_gen_const -> loops = 1;
mst_gen_const -> loop = 0;
mst_gen_const -> ncalls_st_fac = 1.0;
mst_gen_const -> dpar_fac = 1.0;
mst_gen_const -> stopsize_fac = 1.0;
mst_gen_const -> gchsq_n = NULL;
mst_gen_const -> nopar = NULL;
mst_gen_const -> nospar = NULL;
mst_gen_const -> nodpar = NULL;
/* Just copy-paste from gft defaults */
mst_gen_const -> psnpart = 42; /* Of course 42 */
mst_gen_const -> seed = 42; /* Why not? */
mst_gen_const -> pscogni = 0.5; /* cognitial parameter */
mst_gen_const -> pssocia = 0.5; /* social parameter */
mst_gen_const -> psmaxvf = 0.5; /* maximum velocity factor */
mst_gen_const -> psnitfi = 8000; /* iterations until final weight is reached */
mst_gen_const -> psiniin = 0.9; /* initial weight (initial inertia) */
mst_gen_const -> psfinin = 0.4; /* final weight (final inertia) */
mst_gen_const -> psincde = 2; /* increase delta by a factor of */
mst_gen_const -> psdecde = 0.5; /* decrease delta by a factor of */
return mst_gen_const;
}
/* ------------------------------------------------------------ */
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/* Destroys mst_genv */
static int mst_gen_destr(mst_gen *mst_genv)
{
if (!mst_genv)
return GFT_ERROR_NULL_PASSED;
/* All allocations for sub-objects in this struct have pointers in
this struct, therefore we can simply de-allocate */
FREE_COND(mst_genv -> par);
FREE_COND(mst_genv -> dummypar);
FREE_COND(mst_genv -> dummypar2);
FREE_COND(mst_genv -> spar);
FREE_COND(mst_genv -> opar);
FREE_COND(mst_genv -> dpar);
FREE_COND(mst_genv -> ndpar);
FREE_COND(mst_genv -> bestpar);
FREE_COND(mst_genv -> solpar);
FREE_COND(mst_genv -> solerr);
/* mst_gen_nad_destr(mst_genv -> nad); */
FREE_COND(mst_genv -> nopar);
FREE_COND(mst_genv -> nospar);
FREE_COND(mst_genv -> nodpar);
FREE_COND(mst_genv -> nolbounds);
FREE_COND(mst_genv -> noubounds);
FREE_COND(mst_genv -> lbounds);
FREE_COND(mst_genv -> ubounds);
free(mst_genv);
return GFT_ERROR_NONE;
}
/* ------------------------------------------------------------ */
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/* Flushes mst_genv */
static int mst_gen_flush(mst_gen *mst_genv)
{
if (!mst_genv)
return GFT_ERROR_NULL_PASSED;
/* All allocations for sub-objects in this struct have pointers in
this struct, therefore we can simply de-allocate */
FLUSH_COND(mst_genv -> par);
FLUSH_COND(mst_genv -> dummypar);
FLUSH_COND(mst_genv -> dummypar2);
FLUSH_COND(mst_genv -> spar);
FLUSH_COND(mst_genv -> opar);
FLUSH_COND(mst_genv -> dpar);
FLUSH_COND(mst_genv -> ndpar);
FLUSH_COND(mst_genv -> nopar);
FLUSH_COND(mst_genv -> nospar);
FLUSH_COND(mst_genv -> nodpar);
FLUSH_COND(mst_genv -> bestpar);
FLUSH_COND(mst_genv -> solpar);
FLUSH_COND(mst_genv -> solerr);
/* We change the error statuses to none */
mst_genv -> misinf = GFT_ERROR_MISSING_INFO;
mst_genv -> busy = GFT_ERROR_NONE;
mst_genv -> stopped = GFT_ERROR_NONE;
mst_genv -> error = GFT_ERROR_NONE;
mst_genv -> broken = GFT_ERROR_NONE;
return GFT_ERROR_NONE;
}
/* ------------------------------------------------------------ */
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/* check busy status of mst_gen struct */
static int mst_gen_ckbu(mst_gen *mst_genv)
{
return mst_genv -> busy;
}
/* ------------------------------------------------------------ */
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/* check misinf status of mst_gen struct */
/* static int mst_gen_ckmi(mst_gen *mst_genv) */
/* { */
/* return mst_genv -> misinf; */
/* } */
/* ------------------------------------------------------------ */
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/* Execute the fitting function once */
static int mst_gen_init(mst_gen *mst_genv)
{
double chisquare;
size_t i;
int mst_gen_init = GFT_ERROR_NONE;
if (!mst_genv)
return GFT_ERROR_NULL_PASSED;
/* This can only be done if the process is idle and an error is not present */
if ((mst_genv -> busy || mst_genv -> stopped))
return GFT_ERROR_BUSY;
if ((mst_genv -> error))
return GFT_ERROR_ERROR_PRESENT;
/* We need: a valid number of parameters, a present minimiser
function, a vector to calculate the chisquare with. If I remember
well, the last element of the following test is obsolete, but... */
if ((mst_genv -> par) && (mst_genv -> gchsq) && (mst_genv -> npar)) {
/* Check for overflow */
if (mst_genv -> error |= cklimits(mst_genv -> npar, mst_genv -> par))
goto error;
/* Copy to dummypar */
mst_gen_init |= copydblvec(mst_genv -> par, &mst_genv -> dummypar, mst_genv -> npar);for (i = 0; i < mst_genv -> npar; ++i);
mst_gen_init |= copydblvec(mst_genv -> par, &mst_genv -> dummypar2, mst_genv -> npar);for (i = 0; i < mst_genv -> npar; ++i);
/* at initialisation, in this part the parameter is not determined */
mst_genv -> npar_cur = -1;
/* get chisquare */
chisquare = makenormalnumber((mst_genv -> gchsq)(mst_genv -> par, mst_genv -> adar));
/* If this is the first call ever of the chisquare function, do this */
if (!mst_genv -> allcalls) {
mst_genv -> actchisq = chisquare;
mst_genv -> actchisqred = mst_genv -> actchisq/(mst_genv -> indpoints - (double) mst_genv -> npar);
mst_genv -> bestchisq = mst_genv -> actchisq;
mst_genv -> bestchisqred = mst_genv -> actchisq/(mst_genv -> indpoints - (double) mst_genv -> npar);
mst_gen_init |= copydblvec(mst_genv -> par, &mst_genv -> bestpar, mst_genv -> npar);
mst_genv -> solchsq = mst_genv -> actchisq;
mst_genv -> solchsqred = mst_genv -> actchisq/(mst_genv -> indpoints - (double) mst_genv -> npar);
mst_gen_init |= copydblvec(mst_genv -> par, &mst_genv -> solpar, mst_genv -> npar);
++mst_genv -> allcalls;
}
/* Check for the existence of opar and ndpar, if they exist this has to go all the way */
if ((mst_genv -> opar) && (mst_genv -> ndpar)) {
/* if they exist, ndpar elements may not be 0, otherways this counts as wrong parameter */
for (i = 0; i < mst_genv -> npar; ++i)
mst_gen_init |= mst_genv -> ndpar[i] == 0?GFT_ERROR_WRONG_PARAM:GFT_ERROR_NONE;
if (mst_gen_init & GFT_ERROR_WRONG_PARAM)
;
else {
/* nopar has to be filled and thus to be created, this is a lazy variant of checking an allocation */
if (!mst_genv -> nopar)
mst_gen_init |= copydblvec(mst_genv -> par, &mst_genv -> nopar, mst_genv -> npar);
/* We got this far, so we can fill it */
if ((mst_genv -> nopar)) {
for (i = 0; i < mst_genv -> npar; ++i)
mst_genv -> nopar[i] = (mst_genv -> par[i]-mst_genv -> opar[i])/mst_genv -> ndpar[i];
}
}
}
/* Now do the other things */
mst_genv -> actchisq = chisquare;
mst_genv -> actchisqred = mst_genv -> actchisq/(mst_genv -> indpoints - (double) mst_genv -> npar);
if (mst_genv -> actchisq < mst_genv -> bestchisq) {
mst_genv -> bestchisq = mst_genv -> actchisq;
mst_genv -> bestchisqred = mst_genv -> actchisq/(mst_genv -> indpoints - (double) mst_genv -> npar);
mst_gen_init |= copydblvec(mst_genv -> par, &mst_genv -> bestpar, mst_genv -> npar);
if (mst_genv -> allcalls > 1)
++mst_genv -> allcalls;
}
}
else
mst_gen_init |= GFT_ERROR_MISSING_INFO;
return mst_gen_init;
error:
return GFT_ERROR_OVERFLOW;
}
/* ------------------------------------------------------------ */
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/* check whether output makes sense */
static int mst_gen_ckop(mst_gen *mst_genv, int spec)
{
int mst_gen_ckop = GFT_ERROR_NONE;
/***********/
/***********/
/* fprintf(stderr,"mst_gen_ckop %i %i\n", mst_gen_ckop, mst_genv -> error); */
/***********/
/* I think this is not necessary, but it might become */
if (!mst_genv)
return GFT_ERROR_NULL_PASSED;
/* Check validity */
if (spec < 0 || spec > GFT_OUTPUT_MAX)
mst_gen_ckop |= GFT_ERROR_WRONG_IDENT;
/* if there has been no iteration, this is not defined */
if (!mst_genv -> allcalls) {
switch (spec) {
case GFT_OUTPUT_ACTCHISQ:
case GFT_OUTPUT_ACTCHISQRED:
case GFT_OUTPUT_BESTCHISQ:
case GFT_OUTPUT_BESTCHISQRED:
case GFT_OUTPUT_SOLPAR:
case GFT_OUTPUT_SOLERR:
case GFT_OUTPUT_SOLCHSQ:
case GFT_OUTPUT_SOLCHSQRED:
mst_gen_ckop |= GFT_ERROR_OBSOLETE_OP;
default:
;
}
}
/* if there has been one call, this is not defined */
if (mst_genv -> allcalls == 1) {
switch (spec) {
case GFT_OUTPUT_SOLPAR:
case GFT_OUTPUT_SOLERR:
case GFT_OUTPUT_SOLCHSQ:
case GFT_OUTPUT_SOLCHSQRED:
mst_gen_ckop |= GFT_ERROR_OBSOLETE_OP;
default:
;
}
}
/* if there has been no finished minimisation run, this is not defined */
if (!mst_genv -> minruns) {
switch (spec) {
case GFT_OUTPUT_SOLPAR:
case GFT_OUTPUT_SOLERR:
case GFT_OUTPUT_SOLCHSQ:
case GFT_OUTPUT_SOLCHSQRED:
mst_gen_ckop |= GFT_ERROR_OBSOLETE_OP;
default:
;
}
}
return mst_gen_ckop;
}
/* ------------------------------------------------------------ */
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/* Refresh generic part of fit control struct */
static int mst_gen_refresh(mst_gen *mst_genv)
{
size_t i;
int mst_gen_refresh = GFT_ERROR_NONE;
if (!mst_genv)
return GFT_ERROR_NULL_PASSED;
/* Check whether the number of parameters is > 0 */
if (mst_genv -> npar > 0) {
/* Check the number of independent data points and change */
if (mst_genv -> indpoints - (double) mst_genv -> npar < 1.0)
mst_genv -> indpoints = (double) mst_genv -> npar + 1.0;
/* Create dummypar */
if (!mst_genv -> dummypar) {
if (!(mst_genv -> dummypar = (double *) malloc(mst_genv -> npar*sizeof(double)))) {
mst_gen_refresh = mst_gen_refresh | GFT_ERROR_MEMORY_ALLOC;
}
}
/* Create dummypar2 */
if (!mst_genv -> dummypar2) {
if (!(mst_genv -> dummypar2 = (double *) malloc(mst_genv -> npar*sizeof(double)))) {
mst_gen_refresh = mst_gen_refresh | GFT_ERROR_MEMORY_ALLOC;
}
}
/* Mutually check upon the existence of first guess, working
vector, and normalisations, create and fill */
/* spar, opar, and par */
if ((mst_genv -> spar)) {
if (!mst_genv -> opar) {
if (!(mst_genv -> opar = (double *) malloc(mst_genv -> npar*sizeof(double)))) {
mst_gen_refresh = mst_gen_refresh | GFT_ERROR_MEMORY_ALLOC;
}
else {
for (i = 0; i < mst_genv -> npar; ++i)
mst_genv -> opar[i] = mst_genv -> spar[i];
}
}
if (!mst_genv -> par) {
if (!(mst_genv -> par = (double *) malloc(mst_genv -> npar*sizeof(double)))) {
mst_gen_refresh = mst_gen_refresh | GFT_ERROR_MEMORY_ALLOC;
}
else {
for (i = 0; i < mst_genv -> npar; ++i)
mst_genv -> par[i] = mst_genv -> spar[i];
}
}
}
if ((mst_genv -> opar)) {
if (!mst_genv -> spar) {
if (!(mst_genv -> spar = (double *) malloc(mst_genv -> npar*sizeof(double)))) {
mst_gen_refresh = mst_gen_refresh | GFT_ERROR_MEMORY_ALLOC;
}
else {
for (i = 0; i < mst_genv -> npar; ++i)
mst_genv -> spar[i] = mst_genv -> opar[i];
}
}
if (!mst_genv -> par) {
if (!(mst_genv -> par = (double *) malloc(mst_genv -> npar*sizeof(double)))) {
mst_gen_refresh = mst_gen_refresh | GFT_ERROR_MEMORY_ALLOC;
}
else {
for (i = 0; i < mst_genv -> npar; ++i)
mst_genv -> par[i] = mst_genv -> opar[i];
}
}
}
if ((mst_genv -> par)) {
if (!mst_genv -> spar) {
if (!(mst_genv -> spar = (double *) malloc(mst_genv -> npar*sizeof(double)))) {
mst_gen_refresh = mst_gen_refresh | GFT_ERROR_MEMORY_ALLOC;
}
else {
for (i = 0; i < mst_genv -> npar; ++i)
mst_genv -> spar[i] = mst_genv -> par[i];
}
}
if (!mst_genv -> opar) {
if (!(mst_genv -> opar = (double *) malloc(mst_genv -> npar*sizeof(double)))) {
mst_gen_refresh = mst_gen_refresh | GFT_ERROR_MEMORY_ALLOC;
}
else {
for (i = 0; i < mst_genv -> npar; ++i)
mst_genv -> opar[i] = mst_genv -> par[i];
}
}
}
/* Now check the existence of one of these, they should all be there, or none */
if (!mst_genv -> opar) {
mst_genv -> misinf |= GFT_ERROR_MISSING_INFO;
}
/* dpar and ndpar */
if ((mst_genv -> dpar)) {
if (!mst_genv -> ndpar) {
if (!(mst_genv -> ndpar = (double *) malloc(mst_genv -> npar*sizeof(double)))) {
mst_gen_refresh = mst_gen_refresh | GFT_ERROR_MEMORY_ALLOC;
}
else {
for (i = 0; i < mst_genv -> npar; ++i)
mst_genv -> ndpar[i] = mst_genv -> dpar[i];
}
}
}
if ((mst_genv -> ndpar)) {
if (!mst_genv -> dpar) {
if (!(mst_genv -> dpar = (double *) malloc(mst_genv -> npar*sizeof(double)))) {
mst_gen_refresh |= GFT_ERROR_MEMORY_ALLOC;
}
else {
for (i = 0; i < mst_genv -> npar; ++i)
mst_genv -> dpar[i] = mst_genv -> ndpar[i];
}
}
}
/* Now check the existence of one of these, they should all be there, or none */
if (!mst_genv -> dpar) {
mst_gen_refresh |= mst_gen_refresh;
}
else {
/* Check also if none of these is 0 */
for (i = 0; i < mst_genv -> npar; ++i) {
if (!mst_genv -> ndpar[i])
mst_genv -> misinf |= GFT_ERROR_WRONG_PARAM;
}
}
/* At the beginning, allocate bestpar */
if (!(mst_genv -> bestpar)) {
if (!(mst_genv -> bestpar = (double *) malloc(mst_genv -> npar*sizeof(double)))) {
mst_gen_refresh = mst_gen_refresh | GFT_ERROR_MEMORY_ALLOC;
}
}
/* If the chisquare has been calculated once, we don't do this */
if (!mst_genv -> allcalls) {
if ((mst_genv -> spar)) {
if (mst_genv -> bestpar) {
for (i = 0; i < mst_genv -> npar; ++i)
mst_genv -> bestpar[i] = mst_genv -> spar[i];
}
}
}
/* At the beginning, allocate solpar */
if (!(mst_genv -> solpar)) {
if (!(mst_genv -> solpar = (double *) malloc(mst_genv -> npar*sizeof(double)))) {
mst_gen_refresh = mst_gen_refresh | GFT_ERROR_MEMORY_ALLOC;
}
}
/* If a solution has been found once, we don't do this */
if (!mst_genv -> minruns) {
if ((mst_genv -> spar)) {
if (mst_genv -> solpar) {
for (i = 0; i < mst_genv -> npar; ++i)
mst_genv -> solpar[i] = mst_genv -> spar[i];
}
}
}
/* At the beginning, allocate solerr */
if (!(mst_genv -> solerr)) {
if (!(mst_genv -> solerr = (double *) malloc(mst_genv -> npar*sizeof(double)))) {
mst_gen_refresh = mst_gen_refresh | GFT_ERROR_MEMORY_ALLOC;
}
}
/* If a solution has been found once, we don't do this */
if (!mst_genv -> minruns) {
if ((mst_genv -> spar)) {
if (mst_genv -> solerr) {
for (i = 0; i < mst_genv -> npar; ++i)
mst_genv -> solerr[i] = 0.0;
}
}
}
/* If not allocated, the normalised vector is 0 */
if (!mst_genv -> nospar) {
if (!(mst_genv -> nospar = (double *) malloc(mst_genv -> npar*sizeof(double)))) {
mst_gen_refresh = mst_gen_refresh | GFT_ERROR_MEMORY_ALLOC;
}
else {
for (i = 0; i < mst_genv -> npar; ++i)
mst_genv -> nospar[i] = 0.;
}
}
/* If not allocated, allocate the normalised vector */
if (!mst_genv -> nopar) {
if (!(mst_genv -> nopar = (double *) malloc(mst_genv -> npar*sizeof(double)))) {
mst_gen_refresh = mst_gen_refresh | GFT_ERROR_MEMORY_ALLOC;
}
else {
for (i = 0; i < mst_genv -> npar; ++i)
mst_genv -> nopar[i] = mst_genv -> nospar[i];
}
}
/* If not allocated, the normalised step width is 1 */
if (!mst_genv -> nodpar) {
if (!(mst_genv -> nodpar = (double *) malloc(mst_genv -> npar*sizeof(double)))) {
mst_gen_refresh = mst_gen_refresh | GFT_ERROR_MEMORY_ALLOC;
}
else {
/* This will in any case be redone by the specific refresher */
for (i = 0; i < mst_genv -> npar; ++i)
mst_genv -> nodpar[i] = 1.0;
}
}
/* Upper and lower bounds are easy if not yet fixed */
/* Upper bounds to be allocated */
if (!mst_genv -> ubounds) {
if (!(mst_genv -> ubounds = (double *) malloc(mst_genv -> npar*sizeof(double)))) {
mst_gen_refresh = mst_gen_refresh | GFT_ERROR_MEMORY_ALLOC;
}
else {
for (i = 0; i < mst_genv -> npar; ++i)
mst_genv -> ubounds[i] = DBL_MAX;
}
}
/* Lower bounds to be allocated */
if (!mst_genv -> lbounds) {
if (!(mst_genv -> lbounds = (double *) malloc(mst_genv -> npar*sizeof(double)))) {
mst_gen_refresh = mst_gen_refresh | GFT_ERROR_MEMORY_ALLOC;
}
else {
for (i = 0; i < mst_genv -> npar; ++i)
mst_genv -> lbounds[i] = -DBL_MAX;
}
}
/* Normalised upper bounds to be allocated */
if (!mst_genv -> noubounds) {
if (!(mst_genv -> noubounds = (double *) malloc(mst_genv -> npar*sizeof(double)))) {
mst_gen_refresh = mst_gen_refresh | GFT_ERROR_MEMORY_ALLOC;
}
else {
/* This will in any case be redone by the specific refresher (or not) */
for (i = 0; i < mst_genv -> npar; ++i)
mst_genv -> noubounds[i] = DBL_MAX;
}
}
/* Normalised lower bounds to be allocated */
if (!mst_genv -> nolbounds) {
if (!(mst_genv -> nolbounds = (double *) malloc(mst_genv -> npar*sizeof(double)))) {
mst_gen_refresh = mst_gen_refresh | GFT_ERROR_MEMORY_ALLOC;
}
else {
/* This will in any case be redone by the specific refresher (or not) */
for (i = 0; i < mst_genv -> npar; ++i)
mst_genv -> noubounds[i] = -DBL_MAX;
}
}
}
else
mst_genv -> misinf |= GFT_ERROR_MISSING_INFO;
/* Check the chisquare function */
if (!mst_genv -> gchsq) {
mst_genv -> misinf |= GFT_ERROR_MISSING_INFO;
}
return mst_gen_refresh;
}
/* ------------------------------------------------------------ */
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/* Check out (best) chisquares and parameter arrays */
static int mst_gen_ckch(mst_gen *mst_genv, double *array, double chisq)
{
int mst_gen_ckch = GFT_ERROR_NONE;
/************/
/************/
/* fprintf(stderr," mst_gen_ckch/error: %i %i\n", mst_gen_ckch, mst_genv -> error); */
/************/
/* Copy vectors */
mst_gen_ckch |= copydblvec(array, &mst_genv -> nopar, mst_genv -> npar);
mst_gen_ckch |= copydblvec(mst_genv -> dummypar, &mst_genv -> par, mst_genv -> npar);
/* Copy chisquare */
mst_genv -> actchisq = chisq;
mst_genv -> actchisqred = mst_genv -> actchisq/(mst_genv -> indpoints - (double) mst_genv -> npar);
/* compare with best chisquare */
if (mst_genv -> actchisq < mst_genv -> bestchisq) {
/* was better */
mst_genv -> bestchisq = mst_genv -> actchisq;
mst_genv -> bestchisqred = mst_genv -> actchisq/(mst_genv -> indpoints - (double) mst_genv -> npar);
/* Change best chisquare parameters */
mst_gen_ckch |= copydblvec(mst_genv -> par, &mst_genv -> bestpar, mst_genv -> npar);
}
/* This was an icrease in the fitting routines */
++mst_genv -> allcalls;
++mst_genv -> calls;
++mst_genv -> calls_st;
/* That's it */
return mst_gen_ckch;
}
/* ------------------------------------------------------------ */
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/* Generic constructor of the mst_spe struct */
static mst_spe *mst_spe_const(int method)
{
mst_spe *mst_spe_const;
switch (method) {
case MET_NONE:
mst_spe_const = NULL;
break;
case MET_SIMPLEX:
mst_spe_const = (mst_spe *) mst_sim_const();
break;
case MET_GOLDEN:
mst_spe_const = (mst_spe *) mst_gol_const();
break;
case MET_PSWARM:
mst_spe_const = (mst_spe *) mst_psw_const();
break;
default:
mst_spe_const = NULL;
}
return mst_spe_const;
}
/* ------------------------------------------------------------ */
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/* destroys a mst_spe * struct */
static int mst_spe_destr(mst_spe *spev, int method)
{
switch(method) {
case MET_NONE:
if ((spev))
return GFT_ERROR_MEMORY_LEAK;
else
break;
case MET_SIMPLEX:
return mst_sim_destr((mst_sim *) spev);
case MET_GOLDEN:
return mst_gol_destr((mst_gol *) spev);
case MET_PSWARM:
return mst_psw_destr((mst_psw *) spev);
default:
if ((spev))
return GFT_ERROR_MEMORY_LEAK;
}
/* obsolete but for the compiler */
return GFT_ERROR_NONE;
}
/* ------------------------------------------------------------ */
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/* check whether output makes sense */
static int mst_spe_ckop(mst_spe *mst_spev, int spec, int method)
{
int mst_spe_ckop = GFT_ERROR_NONE;
/* I think this is not necessary, but it might become */
if ((method)) {
if (!mst_spev) {
return GFT_ERROR_NULL_PASSED;
}
}
/* Check validity */
if (spec < 0 || spec > GFT_OUTPUT_MAX)
mst_spe_ckop |= GFT_ERROR_WRONG_IDENT;
switch (method) {
case GFT_MET_SIMPLEX:
switch(spec){
/* Only needed for GOLDEN */
case GFT_OUTPUT_NCALLS_ST:
case GFT_OUTPUT_NCALLS_ST_FAC:
/* Only needed for PSWARM */
case GFT_OUTPUT_UBOUNDS:
case GFT_OUTPUT_LBOUNDS:
case GFT_OUTPUT_SEED:
case GFT_OUTPUT_PSNPART:
case GFT_OUTPUT_PSCOGNI:
case GFT_OUTPUT_PSSOCIA:
case GFT_OUTPUT_PSMAXVF:
case GFT_OUTPUT_PSNITFI:
case GFT_OUTPUT_PSINIIN:
case GFT_OUTPUT_PSFININ:
case GFT_OUTPUT_PSINCDE:
case GFT_OUTPUT_PSDECDE:
mst_spe_ckop |= GFT_ERROR_NO_MEANING;
default:
;
}
break;
case GFT_MET_PSWARM:
switch(spec){
/* Only needed for GOLDEN */
case GFT_OUTPUT_NCALLS_ST:
case GFT_OUTPUT_NCALLS_ST_FAC:
mst_spe_ckop |= GFT_ERROR_NO_MEANING;
default:
;
}
break;
case GFT_MET_GOLDEN:
switch(spec){
/* Only needed for PSWARM */
case GFT_OUTPUT_UBOUNDS:
case GFT_OUTPUT_LBOUNDS:
case GFT_OUTPUT_SEED:
case GFT_OUTPUT_PSNPART:
case GFT_OUTPUT_PSCOGNI:
case GFT_OUTPUT_PSSOCIA:
case GFT_OUTPUT_PSMAXVF:
case GFT_OUTPUT_PSNITFI:
case GFT_OUTPUT_PSINIIN:
case GFT_OUTPUT_PSFININ:
case GFT_OUTPUT_PSINCDE:
case GFT_OUTPUT_PSDECDE:
mst_spe_ckop |= GFT_ERROR_NO_MEANING;
default:
;
}
break;
default:
/* If the fit method is unknown, these are not clear */
switch (spec) {
case GFT_OUTPUT_NCALLS_ST:
case GFT_OUTPUT_NITERS:
case GFT_OUTPUT_NOPAR:
case GFT_OUTPUT_NOSPAR:
case GFT_OUTPUT_NODPAR:
case GFT_OUTPUT_LOOPS:
mst_spe_ckop |= GFT_ERROR_UNDEF_MEANING;
default:
;
}
}
return mst_spe_ckop;
}
/* ------------------------------------------------------------ */
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/* Check if a value passed makes sense */
static int ckmetinp(int method, int spec)
{
int ckmetinp = GFT_ERROR_NONE;
/* Check validity */
if (spec < 0 || spec > GFT_INPUT_MAX)
ckmetinp |= GFT_ERROR_WRONG_IDENT;
if (mst_ckme(method))
ckmetinp |= ckmetinp_undef(spec);
switch(method) {
case MET_SIMPLEX:
ckmetinp |= cksiminp(spec);
break;
case MET_PSWARM:
ckmetinp |= ckpswinp(spec);
break;
case MET_GOLDEN:
ckmetinp |= ckgolinp(spec);
break;
default:
ckmetinp |= ckmetinp_undef(spec);
}
return ckmetinp;
}
/* ------------------------------------------------------------ */
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/* Check if a value passed makes sense */
static int ckmetinp_undef(int spec)
{
int ckmetinp_undef = GFT_ERROR_NONE;
/* Check validity, probably redundant */
if (spec < 0 || spec > GFT_INPUT_MAX)
ckmetinp_undef |= GFT_ERROR_WRONG_IDENT;
switch(spec) {
case GFT_INPUT_METHOD:
case GFT_INPUT_NPAR:
case GFT_INPUT_SPAR:
case GFT_INPUT_PAR:
case GFT_INPUT_ADAR:
case GFT_INPUT_NCALLS:
case GFT_INPUT_NITERS:
case GFT_INPUT_LOOPS:
case GFT_INPUT_INDPOINTS:
break;
default:
ckmetinp_undef |= GFT_ERROR_UNDEF_MEANING;
}
return ckmetinp_undef;
}
/* ------------------------------------------------------------ */
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/* allocate and initialise internal specific struct to mstr_in: simplex */
static mst_sim *mst_sim_const()
/* if the GSL is not there, this is a dummy function */
#if MET_SIMPLEX == -2
{
return NULL;
}
#else
{
mst_sim *mst_sim_const = NULL;
if (!(mst_sim_const = (mst_sim *) malloc (sizeof(mst_sim))))
goto error;
/* Now initialise */
mst_sim_const -> multimin_fminimizer_type_gsl = gsl_multimin_fminimizer_nmsimplex;
mst_sim_const -> multimin_fminimizer_gsl = NULL;
mst_sim_const -> stp_gsl_vec = NULL;
mst_sim_const -> var_gsl_vec = NULL;
mst_sim_const -> multimin_function_gsl = NULL;
/* mst_sim_const -> var_vec = NULL; */
/* mst_sim_const -> stp_vec = NULL; */
/* Make empty gsl vectors */
/* if (!(mst_sim_const -> stp_gsl_vec = empty_gsl_dbl_vector())) */
/* goto error; */
/* if (!(mst_sim_const -> var_gsl_vec = empty_gsl_dbl_vector())) */
/* goto error; */
/* Make empty function */
if (!(mst_sim_const -> multimin_function_gsl = (gsl_multimin_function *) malloc(sizeof(gsl_multimin_function))))
goto error;
/* This is only used once, so no explicit function */
mst_sim_const -> multimin_function_gsl -> f = NULL;
mst_sim_const -> multimin_function_gsl -> n = 0;
mst_sim_const -> multimin_function_gsl -> params = NULL;
return mst_sim_const;
error:
mst_sim_destr(mst_sim_const);
return NULL;
}
#endif
/* ------------------------------------------------------------ */
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/* allocate and initialise internal specific struct to mstr_in: simplex */
static mst_psw *mst_psw_const()
{
mst_psw *mst_psw_const = NULL;
if (!(mst_psw_const = (mst_psw *) malloc (sizeof(mst_psw))))
goto error;
/* Now initialise */
mst_psw_const -> optv = NULL;
mst_psw_const -> swav = NULL;
mst_psw_const -> curnospar = NULL;
if (!(mst_psw_const -> optv = pswarm_options_const()))
goto error;
if (!(mst_psw_const -> swav = pswarm_swarm_const()))
goto error;
return mst_psw_const;
error:
mst_psw_destr(mst_psw_const);
return NULL;
}
/* ------------------------------------------------------------ */
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/* destroy a mst_sim * struct */
/* if the GSL is not there, this is a dummy function */
#if MET_SIMPLEX == -2
static int mst_sim_destr(mst_sim *mst_simv)
{
return GFT_ERROR_NONE;
}
#else
static int mst_sim_destr(mst_sim *mst_simv)
{
/* Check pointer */
if (!(mst_simv))
return GFT_ERROR_NULL_PASSED;
/* Destroy allocations */
if ((mst_simv -> stp_gsl_vec))
gsl_vector_free (mst_simv -> stp_gsl_vec);
if ((mst_simv -> var_gsl_vec))
gsl_vector_free (mst_simv -> var_gsl_vec);
FREE_COND(mst_simv -> multimin_function_gsl);
/* FREE_COND(mst_simv -> var_vec); */
/* FREE_COND(mst_simv -> stp_vec); */
if ((mst_simv -> multimin_fminimizer_gsl))
gsl_multimin_fminimizer_free(mst_simv -> multimin_fminimizer_gsl);
/* Destroy the struct */
free(mst_simv);
return GFT_ERROR_NONE;
}
#endif
/* ------------------------------------------------------------ */
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/* destroy a mst_psw * struct */
static int mst_psw_destr(mst_psw *mst_pswv)
{
/* Check pointer */
if (!(mst_pswv))
return GFT_ERROR_NULL_PASSED;
/* Destroy allocations */
if ((mst_pswv -> optv))
pswarm_options_destr(mst_pswv -> optv);
if ((mst_pswv -> swav))
pswarm_swarm_destr(mst_pswv -> swav);
FREE_COND(mst_pswv -> curnospar);
/* Destroy the struct */
free(mst_pswv);
return GFT_ERROR_NONE;
}
/* ------------------------------------------------------------ */
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/* Do initialisations of specific minimiser that needs a call of the
minimising function: simplex */
static int mst_sim_init(mst_sim *mst_simv, mst_gen *mst_genv)
/* if the method is not there, this is a dummy function */
#if MET_SIMPLEX == -2
{
return GFT_ERROR_UNDEF_MEANING;
}
/* method is there */
#else
{
int mst_sim_init = GFT_ERROR_NONE;
if (gsl_multimin_fminimizer_set(mst_simv -> multimin_fminimizer_gsl, mst_simv -> multimin_function_gsl, mst_simv -> var_gsl_vec, mst_simv -> stp_gsl_vec)) {
mst_sim_init |= GFT_ERROR_INTRINSIC;
mst_genv -> error |= GFT_ERROR_INTRINSIC;
}
mst_genv -> size = gsl_multimin_fminimizer_size(mst_simv -> multimin_fminimizer_gsl)*mst_simv -> vlnorm;
mst_simv -> eqchisq = 0;
mst_simv -> eqchisq2 = 0;
mst_simv -> chisqbef = -1.0;
mst_simv -> chisqbef2 = -1.0;
/**********/
/**********/
/* fprintf(stderr,"size intern at init: %.2e\n", mst_genv -> size); */
/**********/
return mst_sim_init;
}
#endif
/* ------------------------------------------------------------ */
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/* Do initialisations of specific minimiser that does not need a call of the
minimising function: pswarm (maybe call the function once) */
static int mst_psw_init(mst_psw *mst_pswv, mst_gen *mst_genv)
{
/* int i; */
int mst_psw_init = GFT_ERROR_NONE;
mst_genv -> stopsize_act = mst_genv -> stopsize * pow(mst_genv -> stopsize_fac,mst_genv -> loop);
/* mst_genv -> stopsize_act is tol */
if (pswarm_options_init(mst_pswv -> optv, mst_genv -> npar, &gchsq_psw, (void *) mst_genv, mst_genv -> nolbounds, mst_genv -> noubounds, mst_pswv -> curnospar, mst_genv -> stopsize_act)) {
/* npar is, I think > 0, if this function is called, so the only possibility is that there is a memory problem */
mst_psw_init |= GFT_ERROR_MEMORY_ALLOC;
mst_genv -> error |= GFT_ERROR_MEMORY_ALLOC;
}
pswarm_i_printfun(mst_pswv -> optv, &gft_pswarm_standardprint);
/* Change the input to options */
mst_pswv -> optv -> inputseed = mst_genv -> seed;
mst_pswv -> optv -> s = mst_genv -> psnpart;
mst_pswv -> optv -> mu = mst_genv -> pscogni;
mst_pswv -> optv -> nu = mst_genv -> pssocia;
mst_pswv -> optv -> maxvfactor = mst_genv -> psmaxvf;
mst_pswv -> optv -> iterfweight = mst_genv -> psnitfi;
mst_pswv -> optv -> iweight = mst_genv -> psiniin;
mst_pswv -> optv -> fweight = mst_genv -> psfinin;
mst_pswv -> optv -> idelta = mst_genv -> psincde;
mst_pswv -> optv -> ddelta = mst_genv -> psdecde;
if (pswarm_swarm_init(mst_pswv -> optv, mst_pswv -> swav)) {
/* npar is, I think > 0, if this function is called, so the only possibility is that there is a memory problem */
mst_psw_init |= GFT_ERROR_MEMORY_ALLOC;
mst_genv -> error |= GFT_ERROR_MEMORY_ALLOC;
}
if (pswarm_init(mst_pswv -> optv, mst_pswv -> swav)) {
/* npar is, I think > 0, if this function is called, so the only possibility is that there is a memory problem */
mst_psw_init |= GFT_ERROR_MEMORY_ALLOC;
mst_genv -> error |= GFT_ERROR_MEMORY_ALLOC;
}
/* some normalisation here? No. */
mst_genv -> size = mst_pswv -> swav -> delta;
/* What have we done? */
/* printf("dim: %i\n", mst_pswv -> optv -> n); */
/* printf("tol: %.1E\n", mst_pswv -> optv -> tol); */
/* printf("ub: "); */
/* for (i = 0; i < 6; ++i) */
/* printf("%.1f ", mst_pswv -> optv -> ub[i]); */
/* printf("\n"); */
/* printf("lb: "); */
/* for (i = 0; i < 6; ++i) */
/* printf("%.1f ", mst_pswv -> optv -> lb[i]); */
/* printf("\n"); */
/* printf("fg: "); */
/* for (i = 0; i < 6; ++i) */
/* printf("%.1f ", mst_pswv -> optv -> fg[i]); */
/* printf("\n"); */
return mst_psw_init;
}
/* ------------------------------------------------------------ */
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/* Do iteration step: simplex */
static int mst_sim_iter(mst_sim *mst_simv, mst_gen *mst_genv)
/* if the method is not there, this is a dummy function */
#if MET_SIMPLEX == -2
{
return GFT_ERROR_UNDEF_MEANING;
}
/* method is there */
#else
{
int mst_sim_iter = GFT_ERROR_NONE;
int status;
gsl_vector *agsl_vector;
size_t i;
/* Call the minimiser */
status = gsl_multimin_fminimizer_iterate(mst_simv -> multimin_fminimizer_gsl);
if (mst_simv -> chisqbef == mst_genv -> actchisq)
++mst_simv -> eqchisq;
else
mst_simv -> eqchisq = 0;
if (mst_simv -> chisqbef2 == mst_genv -> actchisq)
++mst_simv -> eqchisq2;
else
mst_simv -> eqchisq2 = 0;
mst_simv -> chisqbef2 = mst_simv -> chisqbef;
mst_simv -> chisqbef = mst_genv -> actchisq;
if ((status)) {
/* Is it a consequence of a domain error that occured before? */
if ((mst_sim_iter |= mst_genv -> error) & GFT_ERROR_OVERFLOW)
errno = 0;
else
mst_sim_iter |= mst_genv -> error |= GFT_ERROR_INTRINSIC;
}
/* If that occurred, we return, otherways we update and check */
else {
++mst_genv -> iters;
++mst_genv -> alliter;
mst_genv -> calls_st = 0;
/* Get current solution and chisquare */
/* This is a pointer to an intrinsic vector, not a copy, but we check ... */
if (!(agsl_vector = gsl_multimin_fminimizer_x (mst_simv -> multimin_fminimizer_gsl))) {
mst_genv -> error |= mst_sim_iter |= GFT_ERROR_MEMORY_ALLOC | GFT_ERROR_INTRINSIC;
}
else {
for (i = 0; i < mst_genv -> npar; ++i) {
mst_genv -> solpar[i] = gsl_vector_get(agsl_vector, i);
mst_genv -> solpar[i] = mst_genv -> solpar[i] *mst_genv -> ndpar[i]+mst_genv -> opar[i];
/* before: ((double *) (agsl_vector -> data))[i]*mst_genv -> ndpar[i]+mst_genv -> opar[i]; */
}
/* Do not deallocate!!! */
/* gsl_vector_free(agsl_vector); */
/* Get chisquare and reduced chisquare */
mst_genv -> solchsq = gsl_multimin_fminimizer_minimum(mst_simv -> multimin_fminimizer_gsl);
mst_genv -> solchsqred = mst_genv -> solchsq/(mst_genv -> indpoints - (double) mst_genv -> npar);
/* OK, now we check for the actual size and copy it, first calculate the actual stop size */
mst_genv -> stopsize_act = mst_genv -> stopsize * pow(mst_genv -> stopsize_fac,mst_genv -> loop);
mst_genv -> dsize = mst_genv -> size = gsl_multimin_fminimizer_size(mst_simv -> multimin_fminimizer_gsl)*mst_simv -> vlnorm;
/**********/
/**********/
/* fprintf(stderr,"size intern: %.2e\n", mst_genv -> size); */
/**********/
/* Now check if we haven't reached the maximum number of iterations or calls */
if (!(mst_genv -> iters >= mst_genv -> niters || mst_genv -> calls >= mst_genv -> ncalls)) {
/* Then ceck size */
if (mst_genv -> size <= mst_genv -> stopsize_act) {
++mst_genv -> loop;
++mst_genv -> alloops;
mst_simv -> eqchisq = 0;
mst_simv -> eqchisq2 = 0;
/* If we're finished we don't change a thing. If we're not finished yet, we actualise things */
if (mst_genv -> loop < mst_genv -> loops){
for (i = 0; i < mst_genv -> npar; ++i) {
mst_simv -> var_gsl_vec -> data[i] = (mst_genv -> solpar[i]-mst_genv -> opar[i])/mst_genv -> ndpar[i];
mst_simv -> stp_gsl_vec -> data[i] = pow(mst_genv -> dpar_fac,mst_genv -> loop)*mst_genv -> dpar[i]/mst_genv -> ndpar[i];
}
/* ERROR SOURCE??? This is a nasty thing, but it seems to be all we can do. I don't know if this is not a cause of memory leakage */
mst_sim_init(mst_simv, mst_genv);
}
}
/* Then check if we've run rigid */
if (mst_simv -> eqchisq > (mst_genv -> npar+MET_SIMPLEX_MAXEQ) || mst_simv -> eqchisq2 > (mst_genv -> npar+MET_SIMPLEX_MAXEQ)) {
++mst_genv -> loop;
++mst_genv -> alloops;
mst_simv -> eqchisq = 0;
mst_simv -> eqchisq2 = 0;
/* If we're finished we don't change a thing. If we're not finished yet, we actualise things */
if (mst_genv -> loop < mst_genv -> loops){
for (i = 0; i < mst_genv -> npar; ++i) {
mst_simv -> var_gsl_vec -> data[i] = (mst_genv -> solpar[i]-mst_genv -> opar[i])/mst_genv -> ndpar[i];
mst_simv -> stp_gsl_vec -> data[i] = pow(mst_genv -> dpar_fac,mst_genv -> loop)*mst_genv -> dpar[i]/mst_genv -> ndpar[i];
}
/* ERROR SOURCE??? This is a nasty thing, but it seems to be all we can do. I don't know if this is not a cause of memory leakage */
mst_sim_init(mst_simv, mst_genv);
}
}
}
}
}
return mst_sim_iter;
}
#endif
/* ------------------------------------------------------------ */
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/* Do iteration step: simplex */
static int mst_psw_iter(mst_psw *mst_pswv, mst_gen *mst_genv)
{
int mst_psw_iter = GFT_ERROR_NONE;
int status;
/* gsl_vector *agsl_vector; */
size_t i;
/* Some testing */
/* if(!(mst_pswv -> swav -> iter % 10)) */
/* outfcn(mst_pswv -> optv, mst_pswv -> swav); */
/* Call the minimiser */
status = pswarm_iter(mst_pswv -> optv, mst_pswv -> swav);
/* Check on error, this is assumed to be a real domain or range
error that occurred */
if ((status)) {
/* Is it a consequence of a domain error that occured before? */
if ((mst_psw_iter |= mst_genv -> error) & GFT_ERROR_OVERFLOW)
errno = 0;
else
mst_psw_iter |= mst_genv -> error |= GFT_ERROR_INTRINSIC;
}
/* If that occurred, we return, otherways we update and check */
else {
++mst_genv -> iters; /* this is redundant with respect to mst_pswv -> swav -> iter */
++mst_genv -> alliter;
mst_genv -> calls_st = 0;
/* Get current solution and chisquare */
for (i = 0; i < mst_genv -> npar; ++i) {
mst_genv -> solpar[i] = mst_pswv -> swav -> sol[i];
mst_genv -> solpar[i] = mst_genv -> solpar[i] *mst_genv -> ndpar[i]+mst_genv -> opar[i];
}
/* Get chisquare and reduced chisquare */
mst_genv -> solchsq = mst_pswv -> swav -> fy[mst_pswv -> swav -> gbest];
mst_genv -> solchsqred = mst_genv -> solchsq/(mst_genv -> indpoints - (double) mst_genv -> npar);
/* OK, now we check for the actual size and copy it, first calculate the actual stop size */
mst_genv -> stopsize_act = mst_genv -> stopsize * pow(mst_genv -> stopsize_fac,mst_genv -> loop);
mst_genv -> dsize = mst_genv -> size = mst_pswv -> swav -> delta;
/**********/
/**********/
/* fprintf(stderr,"size intern: %.2e\n", mst_genv -> size); */
/**********/
/* Now check if we haven't reached the maximum number of iterations or calls */
if (!(mst_genv -> iters >= mst_genv -> niters || mst_genv -> calls >= mst_genv -> ncalls)) {
/* Then ceck stopping conditions */
if (pswarm_check_exit(mst_genv -> niters, mst_genv -> ncalls, mst_pswv -> optv, mst_pswv -> swav) != PSWARM_STATUS_OK) {
/* Some more testing */
/* printf("Some more testing blabla tolerance\n"); */
/* outfcn(mst_pswv -> optv, mst_pswv -> swav); */
++mst_genv -> loop;
++mst_genv -> alloops;
/* If we're finished we don't change a thing. If we're not finished yet, we actualise things */
if (mst_genv -> loop < mst_genv -> loops){
for (i = 0; i < mst_genv -> npar; ++i) {
mst_pswv -> curnospar[i] = (mst_genv -> solpar[i]-mst_genv -> opar[i])/mst_genv -> ndpar[i];
/* mst_simv -> stp_gsl_vec -> data[i] = pow(mst_genv -> dpar_fac,mst_genv -> loop)*mst_genv -> dpar[i]/mst_genv -> ndpar[i]; */
}
mst_psw_init(mst_pswv, mst_genv);
}
}
}
}
return mst_psw_iter;
}
/* ------------------------------------------------------------ */
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/* Check if a value passed makes sense */
/* if the method is not there, this is a dummy function */
#if MET_SIMPLEX == -2
static int cksiminp(int spec)
{
return GFT_ERROR_UNDEF_MEANING;
}
#else
static int cksiminp(int spec)
{
switch (spec) {
case GFT_INPUT_NCALLS_ST:
return GFT_ERROR_NO_MEANING;
case GFT_INPUT_NCALLS_ST_FAC:
return GFT_ERROR_NO_MEANING;
default:
;
}
return GFT_ERROR_NONE;
}
#endif
/* ------------------------------------------------------------ */
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/* Check if a value passed makes sense */
static int ckpswinp(int spec)
{
switch (spec) {
case GFT_INPUT_NCALLS_ST:
return GFT_ERROR_NO_MEANING;
case GFT_INPUT_NCALLS_ST_FAC:
return GFT_ERROR_NO_MEANING;
default:
;
}
return GFT_ERROR_NONE;
}
/* ------------------------------------------------------------ */
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/* Check if a value passed makes sense */
static int ckgolinp(int spec)
{
switch (spec) {
default:
;
}
return GFT_ERROR_NONE;
}
/* ------------------------------------------------------------ */
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/* Allocate and initialise an empty gsl vector with double elements */
#ifdef GFT_GSL_PRESENT
/* static gsl_vector *empty_gsl_dbl_vector(void) */
/* { */
/* gsl_vector *empty_gsl_dbl_vector; */
/* if (!(empty_gsl_dbl_vector = (gsl_vector *) malloc(sizeof(gsl_vector)))) { */
/* return NULL; */
/* } */
/* empty_gsl_dbl_vector -> size = 0; */
/* empty_gsl_dbl_vector -> stride = sizeof(double); */
/* empty_gsl_dbl_vector -> data = NULL; */
/* empty_gsl_dbl_vector -> block = NULL; */
/* empty_gsl_dbl_vector -> owner = 0; */
/* return empty_gsl_dbl_vector; */
/* } */
#endif
/* ------------------------------------------------------------ */
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/* Fill empty gsl vector */
#ifdef GFT_GSL_PRESENT
static int fill_gsl_dbl_vector(gsl_vector **gsl_vectorv, double *array, size_t length)
{
int fill_gsl_dbl_vector = GFT_ERROR_NONE;
if (!gsl_vectorv)
return GFT_ERROR_NULL_PASSED;
if (length == 0) {
if ((array))
return GFT_ERROR_WRONG_PARAM;
}
if (!array) {
fill_gsl_dbl_vector |= GFT_ERROR_NULL_PASSED;
}
if (!*gsl_vectorv) {
if (!(*gsl_vectorv = gsl_vector_alloc(length)))
return GFT_ERROR_MEMORY_ALLOC;
}
while(length--)
gsl_vector_set(*gsl_vectorv, length, array[length]);
return fill_gsl_dbl_vector;
}
#endif
/* ------------------------------------------------------------ */
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/* Function for gsl_minimiser */
#ifdef GFT_GSL_PRESENT
static double gchsq_sim(const gsl_vector *nopar, void *mst_genv)
{
size_t i;
for (i = 0; i < ((mst_gen *) mst_genv) -> npar; ++i)
((mst_gen *) mst_genv) -> dummypar2[i] = gsl_vector_get(nopar, i);
/* This is not dangerous, dummypar will be changed immediately after
this call, but we avoid a direct access of the array from the
gsl */
return (((mst_gen *) mst_genv) -> gchsq_n)(((mst_gen *) mst_genv) -> dummypar2, (mst_gen *) mst_genv);
}
#endif
/* ------------------------------------------------------------ */
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/* Function for golden section minimiser */
static double gchsq_gol(double *nopar, void *mst_genv)
{
size_t i;
for (i = 0; i < ((mst_gen *) mst_genv) -> npar; ++i)
((mst_gen *) mst_genv) -> dummypar2[i] = nopar[i];
/* This is not dangerous, dummypar will be changed immediately after
this call, but we avoid a direct access of the array from the
gsl */
/* return (((mst_gen *) mst_genv) -> gchsq_n)(((mst_gen *) mst_genv) -> dummypar, (mst_gen *) mst_genv); */
return (((mst_gen *) mst_genv) -> gchsq_n)(((mst_gen *) mst_genv) -> dummypar2, (mst_gen *) mst_genv);
}
/* ------------------------------------------------------------ */
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/* Function for pswarm minimiser */
static double gchsq_psw(double *nopar, void *mst_genv)
{
size_t i;
for (i = 0; i < ((mst_gen *) mst_genv) -> npar; ++i)
((mst_gen *) mst_genv) -> dummypar2[i] = nopar[i];
/* This is not dangerous, dummypar will be changed immediately after
this call, but we avoid a direct access of the array from the
gsl */
/* return (((mst_gen *) mst_genv) -> gchsq_n)(((mst_gen *) mst_genv) -> dummypar, (mst_gen *) mst_genv); */
return (((mst_gen *) mst_genv) -> gchsq_n)(((mst_gen *) mst_genv) -> dummypar2, (mst_gen *) mst_genv);
}
/* ------------------------------------------------------------ */
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/* Normalised function */
static double gchsq_n(double *nopar, mst_gen *mst_genv)
{
size_t i;
double gchsq_n;
/************/
/************/
/* fprintf(stderr,"gchsq_n value %.1e error: %i\n", gchsq_n, mst_genv -> error); */
/************/
/* check here the validity of all components and place a flag */
if (mst_genv -> error |= cklimits(mst_genv -> npar, nopar))
goto error;
/************/
/* First place the stuff in the dummy part */
for (i = 0; i < mst_genv -> npar; ++i) {
/************/
/************/
/* fprintf(stderr,"gchsq_n nopar %.1e \n", nopar[i]); */
/************/
/* this is copying dummypar to itself, hence the realmst_genv -> nopar will be changed in ckch and not be identical to the input nopar */
mst_genv -> dummypar[i] = nopar[i]*mst_genv -> ndpar[i]+mst_genv -> opar[i];
}
/************/
/************/
/* fprintf(stderr,"\n"); */
/************/
/************/
/************/
/* for (i = 0; i < mst_genv -> npar; ++i) { */
/* fprintf(stderr,"gchsq_n nopar0 par %i %.1e %.1e dummy %.1e\n", (int) i, nopar[i], mst_genv -> nopar[i], mst_genv -> dummypar[i]); */
/* } */
/************/
/* check here the validity of all components and place a flag */
if (mst_genv -> error |= cklimits(mst_genv -> npar, mst_genv -> dummypar))
goto error;
/************/
/************/
/* for (i = 0; i < mst_genv -> npar; ++i) { */
/* fprintf(stderr,"gchsq_n nopar1 par %i %.1e %.1e dummy %.1e\n", (int) i, nopar[i], mst_genv -> nopar[i], mst_genv -> dummypar[i]); */
/* } */
/************/
/* Check out the chisquare */
gchsq_n = makenormalnumber((*mst_genv -> gchsq)(mst_genv -> dummypar, mst_genv -> adar));
/************/
/************/
/* for (i = 0; i < mst_genv -> npar; ++i) { */
/* fprintf(stderr,"gchsq_n nopar2 par %i %.1e %.1e dummy %.1e\n", (int) i, nopar[i], mst_genv -> nopar[i], mst_genv -> dummypar[i]); */
/* } */
/************/
/* Fill the array and the struct */
mst_gen_ckch(mst_genv, nopar, gchsq_n);
/************/
/************/
/* for (i = 0; i < mst_genv -> npar; ++i) { */
/* fprintf(stderr,"gchsq_n nopar3 %.1e %1e\n", nopar[i], mst_genv -> nopar[i]); */
/* } */
/************/
return gchsq_n;
error:
errno = EDOM;
return HUGE_VAL;
}
/* ------------------------------------------------------------ */
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/* allocate and initialise internal specific struct to mstr_in: golden */
static mst_gol *mst_gol_const()
{
mst_gol *mst_gol_const = NULL;
if (!(mst_gol_const = (mst_gol *) malloc (sizeof(mst_gol))))
goto error;
mst_gol_const -> gc = NULL;
if (!(mst_gol_const -> gc = golden_container_const()))
goto error;
return mst_gol_const;
error:
mst_gol_destr(mst_gol_const);
return NULL;
}
/* ------------------------------------------------------------ */
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/* destroy a mst_gol * struct */
static int mst_gol_destr(mst_gol *mst_golv)
{
/* Check pointer */
if (!(mst_golv))
return GFT_ERROR_NULL_PASSED;
golden_container_destr(mst_golv -> gc);
/* Destroy the struct */
free(mst_golv);
return GFT_ERROR_NONE;
}
/* ------------------------------------------------------------ */
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/* Do initialisations of specific minimiser that needs a call of the
minimising function: golden */
static int mst_gol_init(mst_gol *mst_golv, mst_gen *mst_genv)
{
int mst_gol_init = GFT_ERROR_NONE;
double ncurstep_here;
int npar_cur_here;
if (!(mst_golv -> gc)) {
mst_gol_init |= GFT_ERROR_INTRINSIC;
goto error;
}
/* Just to be sure, we do the following again */
mst_gol_init |= golden_i_gchsq(&gchsq_gol, mst_golv -> gc);
mst_gol_init |= golden_i_adar((void *) mst_genv, mst_golv -> gc);
mst_gol_init |= golden_i_nodpar(mst_genv -> nodpar, mst_golv -> gc);
mst_gol_init |= golden_i_nospar(mst_genv -> nospar, mst_golv -> gc);
mst_gol_init |= golden_i_ncalls_st(mst_genv -> ncalls_st, mst_golv -> gc);
mst_gol_init |= golden_i_minstep(1.0, mst_golv -> gc);
/* At initialisation, the current parameter is -1 */
mst_genv -> npar_cur = -1;
if (golden_init(mst_golv -> gc)) {
mst_gol_init |= GFT_ERROR_INTRINSIC;
mst_genv -> error |= GFT_ERROR_INTRINSIC;
goto error;
}
/* Size defined here, perhaps normalisation necessary */
golden_o_solsize(&(mst_genv -> size), mst_golv -> gc);
golden_o_ncurstep(&ncurstep_here, mst_golv -> gc);
golden_o_npar_cur(&npar_cur_here, mst_golv -> gc);
/* mst_genv -> npar_cur = npar_cur_here; */
/* npar_cur_here should be 0; ncurstep_here IS 0., so dsize becomes 0. It is a dummy that otherwise is kept synchronized with size */
mst_genv -> dsize = ncurstep_here*mst_genv -> ndpar[npar_cur_here];
/* mst_genv -> dsize = 0.0; */
return mst_gol_init;
error:
return mst_gol_init;
}
/* ------------------------------------------------------------ */
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/* Do iteration step: simplex */
static int mst_gol_iter(mst_gol *mst_golv, mst_gen *mst_genv)
{
int mst_gol_iter = GFT_ERROR_NONE;
int status;
size_t i, iters_here, loop_here;
int npar_cur_here;
double nastep_here;
golden_o_nastep(&nastep_here, mst_golv -> gc);
golden_o_npar_cur(&npar_cur_here, mst_golv -> gc);
mst_genv -> npar_cur = npar_cur_here;
/* Get the step width */
mst_genv -> dsize = nastep_here*mst_genv -> ndpar[npar_cur_here];
/* Call the minimiser */
status = golden_iterate(mst_golv -> gc);
/* Check out if the chisquare changed */
/* Check on error, this is assumed to be a real domain or range
error that occurred. Currently golden_iter does not return any
information on that, so this is basically an empty peace of
code */
if ((status)) {
/* Is it a consequence of a domain error that occured before? */
if ((mst_gol_iter |= mst_genv -> error) & GFT_ERROR_OVERFLOW)
errno = 0;
else
mst_gol_iter |= mst_genv -> error |= GFT_ERROR_INTRINSIC;
}
/* If that occurred, we return, otherways we update and check */
else {
/* simply synchronise this */
golden_o_calls_st(&(mst_genv -> calls_st), mst_golv -> gc);
golden_o_iters(&iters_here, mst_golv -> gc);
if (mst_genv -> iters != iters_here) {
++mst_genv -> alliter;
++mst_genv -> iters;
}
/* already done in gchsq_n:
calls
allcalls
not yet done:
npar_cur XXX
gc -> actchisq (is identical with mst_genv -> bestchisq, but not with mst_genv -> actchisq
gc -> par (is identical with mst_genv -> bestpar-mst_genv -> opar[i])/mst_genv -> ndpar[i];, but not with mst_genv -> nopar
gc -> nastep
gc -> ncurstep XXX
gc -> iterstat XXX
*/
/* Get current solution and chisquare */
golden_o_solpar(mst_genv -> solpar, mst_golv -> gc);
/* copydblvec(mst_golv -> gc -> solpar, &mst_genv -> solpar, mst_genv -> npar); */
for (i = 0; i < mst_genv -> npar; ++i) {
mst_genv -> solpar[i] = mst_genv -> solpar[i] *mst_genv -> ndpar[i]+mst_genv -> opar[i];
}
/* Get chisquare and reduced chisquare */
golden_o_solchisq(&(mst_genv -> solchsq), mst_golv -> gc);
mst_genv -> solchsqred = mst_genv -> solchsq/(mst_genv -> indpoints - (double) mst_genv -> npar);
/* OK, now we check for the actual size and copy it, first calculate the actual stop size */
mst_genv -> stopsize_act = mst_genv -> stopsize * pow(mst_genv -> stopsize_fac,mst_genv -> loop);
golden_o_solsize(&(mst_genv -> size), mst_golv -> gc);
/**********/
/**********/
/* fprintf(stderr,"size intern: %.2e\n", mst_genv -> size); */
/**********/
/* synchronise */
golden_o_loop(&loop_here, mst_golv -> gc);
golden_o_nastep(&nastep_here, mst_golv -> gc);
if (mst_genv -> loop != loop_here) {
++mst_genv -> alloops;
mst_genv -> loop = loop_here;
if (mst_genv -> loop < mst_genv -> loops){
for (i = 0; i < mst_genv -> npar; ++i) {
mst_genv -> dummypar2[i] = pow(mst_genv -> dpar_fac,mst_genv -> loop)*mst_genv -> dpar[i]/mst_genv -> ndpar[i];
}
golden_i_nodpar(mst_genv -> dummypar2, mst_golv -> gc);
golden_i_nastep(mst_genv -> dummypar2[0], mst_golv -> gc);
/* the last command is equivalent with this */
/* mst_golv -> gc -> nastep = mst_golv -> gc -> nodpar[0]; */
}
}
/* Now check if we haven't reached the maximum number of iterations or calls or loops */
if (!(mst_genv -> iters >= mst_genv -> niters || mst_genv -> calls >= mst_genv -> ncalls || mst_genv -> loop >= mst_genv -> loops)) {
/* Then check size */
if (mst_genv -> size <= mst_genv -> stopsize_act) {
mst_genv -> loops = mst_genv -> loop;
}
}
}
return mst_gol_iter;
}
/* ------------------------------------------------------------ */
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/* Normalised function, dummy, intended for later use */
/* static double gchsq_ndummy(double *nopar, mst_gen *mst_genv) */
/* { */
/* size_t i; */
/* double gchsq_ndummy; */
/* /\* check here the validity of all components and place a flag *\/ */
/* if (mst_genv -> error |= cklimits(mst_genv -> npar, nopar)) */
/* goto error; */
/* /\* First place the stuff in the dummy part *\/ */
/* for (i = 0; i < mst_genv -> npar; ++i) */
/* mst_genv -> dummypar[i] = nopar[i]; */
/* /\* Check out the chisquare *\/ */
/* gchsq_ndummy = makenormalnumber((*mst_genv -> gchsq)(mst_genv -> dummypar, mst_genv -> adar)); */
/* /\* Fill the array and the struct *\/ */
/* mst_gen_ckch(mst_genv, nopar, gchsq_ndummy); */
/* return gchsq_ndummy; */
/* error: */
/* errno = EDOM; */
/* return HUGE_VAL; */
/* } */
/* ------------------------------------------------------------ */
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/* Copy a vector */
static int copydblvec(double *from, double **to, size_t length)
{
int copydblvec;
copydblvec = GFT_ERROR_NONE;
if (!to)
return GFT_ERROR_NULL_PASSED;
if (!from) {
copydblvec |= GFT_ERROR_NULL_PASSED;
length = 0;
}
if ((*to)) {
if (!length) {
FLUSH_COND(*to);
}
}
else {
if ((length)){
if (!(*to = (double *) malloc(length*sizeof(double))))
return GFT_ERROR_MEMORY_ALLOC;
}
}
while (length--) {
(*to)[length] = from[length];
}
return copydblvec;
}
/* ------------------------------------------------------------ */
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/* Copy a vector */
static int copyvec(void *from, void *to, size_t size, size_t length)
{
char *internto;
char *internfrom;
if (!from)
return GFT_ERROR_NO_MEANING;
if (!to)
return GFT_ERROR_NULL_PASSED;
/* ERROR SOURCE??? Here, expressively a char is the smallest
element, this is standard */
length = length*size;
internto = (char *) to;
internfrom = (char *) from;
while (length--)
internto[length] = internfrom[length];
return GFT_ERROR_NONE;
}
/* ------------------------------------------------------------ */
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/* Check numerical limits */
static int cklimits(size_t length, double *array)
{
int cklimits = GFT_ERROR_NONE;
if (length < 1)
return GFT_ERROR_NONE;
if (!array)
return GFT_ERROR_NULL_PASSED;
/* -DBL_MAX is defined at least in C99, if it's in C90, I couldn't find out */
while (length--)
cklimits |= array[length] < -DBL_MAX?GFT_ERROR_OVERFLOW:(array[length] > DBL_MAX?GFT_ERROR_OVERFLOW:GFT_ERROR_NONE);
return cklimits;
}
/* ------------------------------------------------------------ */
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/* Check for overflow, in case of overflow, replace by largest double */
static double makenormalnumber(double number)
{
/* If it is possible to somehow find out if it is a big number, we
delete the error status */
if (number < -DBL_MAX || number > DBL_MAX)
errno = 0;
return number < -DBL_MAX?-DBL_MAX:(number > DBL_MAX?DBL_MAX:number);
}
/* ------------------------------------------------------------ */
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/* input to pswarm: function to print only if the status is an error, but then to stderr */
static int gft_pswarm_standardprint(pswarm_swarm *pswarm_swarmv)
{
if (!(pswarm_swarmv))
return 1;
if ((pswarm_swarmv -> status)) {
if (pswarm_swarmv -> status & PSWARM_STATUS_ERROR)
fprintf(stderr, "%s\n", pswarm_swarmv -> statusm);
}
return 0;
}
/* ------------------------------------------------------------ */
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/* input to pswarm: function to print only if the status is an error, but then to stderr */
double gft_psw_startsize(int n, double *lb, double *ub, double tol, double fdelta) {
int j;
double delta, mindelta;
if ((n <= 0) || !(lb) || !(ub) || tol <= 0.0 || fdelta <= 0.0)
return DBL_MAX;
mindelta = DBL_MAX;
for(j = 0; j < n ; j++){
if(lb[j] > -DBL_MAX && ub[j] < DBL_MAX) {
if(mindelta > (ub[j]-lb[j]))
mindelta = (ub[j]-lb[j]);
}
}
if(mindelta >= DBL_MAX || mindelta<2*sqrt(tol))
delta=2*sqrt(sqrt(tol));
else delta=mindelta/fdelta;
return delta;
}
/* ------------------------------------------------------------ */
/* Output function, only for testing */
/* static int outfcn(pswarm_options *opt, pswarm_swarm *pop) */
/* { */
/* if(pop -> iter==0){ */
/* printf("\n Iter Leader Objective " */
/* "\n -------------------------------\n" */
/* " %4d %4d %4.6e %4.6e\n", pop -> iter, pop -> gbest, pop -> fy[pop -> gbest], pop -> delta); */
/* } */
/* else */
/* printf(" %4d %4d %4.6e %4.6e\n", pop -> iter, pop -> gbest, pop -> fy[pop -> gbest], pop -> delta); */
/* return 0; */
/* } */
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
$Log: gft.c,v $
Revision 1.5 2011/05/04 01:13:59 jozsa
did a lot
Revision 1.4 2007/12/12 17:19:21 gjozsa
checked something
Revision 1.3 2007/08/14 17:10:51 gjozsa
Added some counters
Revision 1.2 2007/07/02 12:55:12 gjozsa
Made ANSI compliant
Revision 1.1 2007/06/22 12:43:28 gjozsa
Added to CVS control
------------------------------------------------------------ */
| {
"alphanum_fraction": 0.5516885231,
"avg_line_length": 29.4968611521,
"ext": "c",
"hexsha": "5a34590188cd135a25b7a852185966642be615e4",
"lang": "C",
"max_forks_count": 3,
"max_forks_repo_forks_event_max_datetime": "2022-01-03T15:02:35.000Z",
"max_forks_repo_forks_event_min_datetime": "2017-08-28T03:17:38.000Z",
"max_forks_repo_head_hexsha": "05fddee80e715dfee5d0f4e2f994b2f17c5d2ca9",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "kernsuite-debian/tirific",
"max_forks_repo_path": "gft/gft.c",
"max_issues_count": 2,
"max_issues_repo_head_hexsha": "462a58a8312ce437ac5e2c87060cde751774f1de",
"max_issues_repo_issues_event_max_datetime": "2019-08-20T06:37:26.000Z",
"max_issues_repo_issues_event_min_datetime": "2017-02-24T12:40:08.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "gigjozsa/tirific",
"max_issues_repo_path": "gft/gft.c",
"max_line_length": 260,
"max_stars_count": 4,
"max_stars_repo_head_hexsha": "05fddee80e715dfee5d0f4e2f994b2f17c5d2ca9",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "kernsuite-debian/tirific",
"max_stars_repo_path": "gft/gft.c",
"max_stars_repo_stars_event_max_datetime": "2018-01-04T08:22:01.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-07-01T12:07:09.000Z",
"num_tokens": 43769,
"size": 159755
} |
#include <stdio.h>
#include "sweeny_bfs.h"
#include "../src/queue_2.h"
#include <ctype.h>
#include <strings.h>
#include <unistd.h>
#include <math.h>
#include <gsl/gsl_rng.h>
// Define Macro SEQUENTIAL to use sequential BFS; Default is interleaved BFS
#define MIN(a,b) a<=b ? a: b
#define MAX(a,b) a>=b? a:b
static char setup=0; // 0 not setup; 1 ibfs; 2 sbfs
static char verbose=0;
static double rcWeights[4]; // array with precalculated mc weights
static double p_min_del,p_max_del, p_min_ins,p_max_ins;
static __s8 dN,dB;
static char equilibration=1;
static __u32 DX;
static __u32 N;
static __u32 seed;
static double q;
static double coupling;
static double beta;
static double v;
static double K;
static __u32 steps;
static __s8 *bonds;
static gsl_rng * r;
static __u32 edge[2];
static __s32 adj1[4];
static __s32 adj2[4];
static __u32 offset_1;
static __u32 offset_2;
static __u32 cs2;
static struct queue_2_node *todo_pool;
static __u32 *visited;
static __u32 cs1;
static __u32 activeEdges=0;
static __u32 cutoff;
static __u32 *num_bonds , *num_cluster, *size_giant;
static __u64 *sec_cs_moment, *four_cs_moment;
/******************************************************************************
*****************************************************************************/
static char init(void)
{
K=coupling*beta;
v = exp(K) - 1.0;
N = DX*DX;
// Deletion accept. ratios
rcWeights[0] = pow(v,-1); //db==-1,dN==0
rcWeights[1] = rcWeights[0]*q; //db==-1,dN=1
// Insertion accept. ratios
rcWeights[2] = v; //db==1,dN==0
rcWeights[3] = v*pow(q,-1); //db==1,dN==-1
p_min_del = MIN(rcWeights[0],rcWeights[1]);
p_max_del = MAX(rcWeights[0],rcWeights[1]);
p_min_ins = MIN(rcWeights[2],rcWeights[3]);
p_max_ins = MAX(rcWeights[2],rcWeights[3]);
r = gsl_rng_alloc (gsl_rng_mt19937);
if(!r)
return 0;
gsl_rng_set(r,seed);
__u32 i;
bonds = malloc(sizeof(*bonds)*2*N);
if(!bonds) {
return 0;
}
for(i=0;i<2*N;i++) bonds[i] = -1;
visited = calloc(N,sizeof(*visited));
if(!visited) {
return 0;
}
todo_pool = malloc(N*sizeof(struct queue_2_node));
if(!todo_pool) {
return 0;
}
return 1;
}
/******************************************************************************
*****************************************************************************/
static void destroy(void)
{
if(!setup)return;
free(todo_pool);
free(bonds);
gsl_rng_free(r);
free(visited);
}
/******************************************************************************
*****************************************************************************/
static inline __u32 ltcXnext(__u32 idx)
{
if((idx+1) % DX)
return idx+1;
else
return idx +1- DX ;
}
/******************************************************************************
*****************************************************************************/
static inline __u32 ltcXprev(__u32 idx)
{
if((idx%DX))
return idx-1;
else
return idx + DX -1;
}
/******************************************************************************
*****************************************************************************/
static inline __u32 ltcYnext(__u32 idx)
{
if(idx <= N -1 && idx >= N - DX)
return idx +DX- N ;
else
return idx+DX;
}
/******************************************************************************
*****************************************************************************/
static inline __u32 ltcYprev(__u32 idx)
{
if(idx <= DX - 1)
return idx + N - DX;
else
return idx - DX;
}
/******************************************************************************
*****************************************************************************/
static void Adjacent(__u32 bidx)
{
if(bidx%2) {
bidx = (bidx -1)/2;
edge[0] = bidx;
edge[1] = ltcXnext(bidx);
}
else {
bidx = bidx/2;
edge[0] = bidx;
edge[1] = ltcYprev(bidx);
}
}
/******************************************************************************
*****************************************************************************/
static void neighbours(__u32 idx,__u8 a) {
if(a == 1)
{
if(bonds[2*idx] == 1) adj1[0] = ltcYprev(idx);
else adj1[0] = -1;
if(bonds[(2*idx)+1] == 1) adj1[1] = ltcXnext(idx);
else adj1[1] = -1;
if(bonds[2*ltcYnext(idx)] == 1) adj1[2] = ltcYnext(idx);
else adj1[2] = -1;
if(bonds[(2*ltcXprev(idx))+1] ==1)adj1[3] = ltcXprev(idx);
else adj1[3] = -1;
}
else {
if(bonds[2*idx] == 1)adj2[0] = ltcYprev(idx);
else adj2[0] = -1;
if(bonds[(2*idx)+1] == 1)adj2[1] = ltcXnext(idx);
else adj2[1] = -1;
if(bonds[2*ltcYnext(idx)] == 1) adj2[2] = ltcYnext(idx);
else adj2[2] = -1;
if(bonds[(2*ltcXprev(idx))+1] == 1)adj2[3] = ltcXprev(idx);
else adj2[3] = -1;
}
}
/******************************************************************************
*****************************************************************************/
static __u8 breadthFirstSearch_s(__u32 start, __u32 goal)
{
static struct queue_2 todo1;
__u32 i=0,activeP1=0;
init_queue_2(&todo1); //todo_pool);
cs1=0;
enqueue_2(&todo1,start);
cs1++; // Increase cluster size of bfs 1
visited[start] = offset_1; // mark starting point as visited
while(!queue_2_empty_p(&todo1)) {
dequeue_2(&todo1,&activeP1);
neighbours(activeP1,1);
for(i=0;i<4;i++) {
if(adj1[i] != -1) {
if(visited[adj1[i]] == offset_1) continue;
if((__u32)adj1[i] == goal) {
while(!queue_2_empty_p(&todo1)){ dequeue_2(&todo1,&activeP1);}
return 1;
}
enqueue_2(&todo1,adj1[i]);
visited[adj1[i]] = offset_1;
cs1++;
}
}
}
return 0;
}
/******************************************************************************
*****************************************************************************/
static __u8 breadthFirstSearch(__u32 start, __u32 goal)
{
static struct queue_2 todo1,todo2;
__u32 i=0,activeP1=0,activeP2=0;
init_queue_2(&todo1);
init_queue_2(&todo2);
cs1=0;
cs2=0;
enqueue_2(&todo1,start); // Put starting point onto queue_2 1
cs1++; // Increase cluster size of bfs 1
visited[start] = offset_1; // mark starting point as visited
enqueue_2(&todo2,goal); // Put goal point onto queue_2 2
visited[goal] = offset_2; // mark goal point as visited
cs2++; // increase cluster size of bfs 2
while(!queue_2_empty_p(&todo1) && !queue_2_empty_p(&todo2)) {
dequeue_2(&todo2,&activeP2); // get next vertex of bfs 2
neighbours(activeP2,2); // get all adjacent vertices of current vertex
for(i=0;i<4;i++) {
if(adj2[i] != -1) { // if accessable (edge exists)
if(visited[adj2[i]] == offset_2) continue; // already visited
if((__u32)adj2[i] == start || visited[adj2[i]] == offset_1) { // reconnected
while(!queue_2_empty_p(&todo1)){ dequeue_2(&todo1,&activeP1);}
while(!queue_2_empty_p(&todo2)){ dequeue_2(&todo2,&activeP2);}
return 1; // 1 indicates success
}
enqueue_2(&todo2,adj2[i]);
visited[adj2[i]] = offset_2; // mark as visited
cs2++; // increase cluster size
}
}
dequeue_2(&todo1,&activeP1);
neighbours(activeP1,1);
for(i=0;i<4;i++) {
if(adj1[i] != -1) {
if(visited[adj1[i]] == offset_1) continue;
if((__u32)adj1[i] == goal || visited[adj1[i]] == offset_2) {
while(!queue_2_empty_p(&todo1)){ dequeue_2(&todo1,&activeP1);}
while(!queue_2_empty_p(&todo2)){ dequeue_2(&todo2,&activeP2);}
return 1;
}
enqueue_2(&todo1,adj1[i]);
visited[adj1[i]] = offset_1;
cs1++;
}
}
}
while(!queue_2_empty_p(&todo1)){dequeue_2(&todo1,&activeP1);}
while(!queue_2_empty_p(&todo2)){dequeue_2(&todo2,&activeP2);}
return 0;
}
/******************************************************************************
*****************************************************************************/
static inline __u8 connected(__u32 start, __u32 goal) {
offset_1+=2;
offset_2+=2;
return breadthFirstSearch(start,goal);
}
/******************************************************************************
*****************************************************************************/
__u8 static inline connected_s(__u32 start, __u32 goal) {
++offset_1;
return breadthFirstSearch_s(start,goal);
}
/******************************************************************************
*****************************************************************************/
static inline void sweep_ibfs(void)
{
static __u32 bidx;
static double rnd_num;
__u32 i=0;
for(;i<2*N ;++i) {
bidx = gsl_rng_uniform_int(r,2*N);
rnd_num = gsl_rng_uniform(r);
Adjacent(bidx);
if(bonds[bidx] == 1) { //edge is active hence delete it
dB = -1;
if(rnd_num < p_min_del) { // accept bond deletion
bonds[bidx]*=-1;
activeEdges--;
}
else {
if(rnd_num < p_max_del) {
bonds[bidx]*=-1;
dN = (connected(edge[0],edge[1])? 0 : 1);
if(rnd_num >= rcWeights[dB == -1? dN : 2-dN]) bonds[bidx]*=-1; // undo bond deletion
else activeEdges--; // accept bond deletion
}
}
}
else {
// Insert cedge. If adjacent vertices are already connected, the new
// edge will be a non-tree edge, i.e. dN = 0
dB = 1;
if(rnd_num < p_min_ins) { // accept bond insertion
bonds[bidx] *=-1;
activeEdges++;
}
else {
if(rnd_num < p_max_ins) {
dN = ( connected(edge[0],edge[1]) ?0 : -1);
if(rnd_num < rcWeights[dB == -1? dN : 2-dN]) {
bonds[bidx]*=-1;
activeEdges++;
}
}
}
}
}
}
/******************************************************************************
*****************************************************************************/
static inline void sweep_sbfs(void)
{
static __u32 bidx;
static double rnd_num;
__u32 i=0;
for(;i<2*N ;++i) {
bidx = gsl_rng_uniform_int(r,2*N);
rnd_num = gsl_rng_uniform(r);
Adjacent(bidx);
if(bonds[bidx] == 1) { //edge is active hence delete it
dB = -1;
if(rnd_num < p_min_del) { // accept bond deletion
bonds[bidx]*=-1;
activeEdges--;
}
else {
if(rnd_num < p_max_del) {
bonds[bidx]*=-1;
dN = (connected_s(edge[0],edge[1])? 0 : 1);
if(rnd_num >= rcWeights[dB == -1? dN : 2-dN]) bonds[bidx]*=-1; // undo bond deletion
else activeEdges--; // accept bond deletion
}
}
}
else {
// Insert cedge. If adjacent vertices are already connected, the new
// edge will be a non-tree edge, i.e. dN = 0
dB = 1;
if(rnd_num < p_min_ins) { // accept bond insertion
bonds[bidx] *=-1;
activeEdges++;
}
else {
if(rnd_num < p_max_ins) {
dN = ( connected_s(edge[0],edge[1]) ?0 : -1);
if(rnd_num < rcWeights[dB == -1? dN : 2-dN]) {
bonds[bidx]*=-1;
activeEdges++;
}
}
}
}
}
}
/******************************************************************************
*****************************************************************************/
static void extract_observables(__u32 i) {
static __u32 j=0;
static __u32 clust_cnt=0;
static __u64 sum=0,sum_2;
static __u32 maxc=0,chksum=0;
num_bonds[i] = activeEdges;
offset_1=0;
for(j=0;j<N;++j) visited[j] = offset_1;
offset_1=1;
for(j=0;j<N&&chksum<=N;++j) {
if(!visited[j]){
breadthFirstSearch_s(j,N);
clust_cnt++;
if(cs1 > maxc) maxc = cs1;
sum+=cs1*cs1;
sum_2+=pow(cs1,4);
chksum+=cs1;
}
}
num_cluster[i] = clust_cnt;
size_giant[i] = maxc;
sec_cs_moment[i] = sum;
four_cs_moment[i] = sum_2;
maxc=clust_cnt=sum=sum_2=chksum=0;
offset_1=3;
offset_2=2;
}
/******************************************************************************
*****************************************************************************/
static void generateTimeSeries(void)
{
__u32 i;
if(setup==1) {
for(i=0;i<cutoff;++i)sweep_ibfs();
equilibration=0;
if(verbose)
printf("Equilibration done!\n");
for(i=0;i<steps;++i) {
sweep_ibfs();
extract_observables(i);
}
}
if(setup==2) {
for(i=0;i<cutoff;++i)sweep_sbfs();
equilibration=0;
if(verbose)
printf("Equilibration done!\n");
for(i=0;i<steps;++i) {
sweep_sbfs();
extract_observables(i);
}
}
}
/******************************************************************************
*****************************************************************************/
char init_sweeny_ibfs(double _q,unsigned int _l,double _beta,double _coupl,
unsigned int _cutoff,unsigned _tslength,unsigned int rng_seed,
void *ts_0,void *ts_1,void * ts_2,void *ts_3,void *ts_4) {
setup=1;
offset_1 =1;
offset_2 = 2;
activeEdges =0;
q = _q;
DX = _l;
beta = _beta;
coupling = _coupl;
cutoff = _cutoff;
steps = _tslength;
seed = rng_seed;
num_bonds = (__u32 *)ts_0;
num_cluster = (__u32 *)ts_1;
size_giant = (__u32 *)ts_2;
sec_cs_moment = (__u64 *)ts_3;
four_cs_moment = (__u64 *)ts_4;
if(!init())
setup=0;
return setup;
}
/******************************************************************************
*****************************************************************************/
char init_sweeny_sbfs(double _q,unsigned int _l,double _beta,double _coupl,
unsigned int _cutoff,unsigned _tslength,unsigned int rng_seed,
void *ts_0,void *ts_1,void * ts_2,void *ts_3, void *ts_4) {
setup=init_sweeny_ibfs(_q,_l,_beta,_coupl,_cutoff,_tslength,rng_seed,
ts_0,ts_1,ts_2,ts_3,ts_4);
if(setup)
return setup=2;
else
return setup;
}
/******************************************************************************
*****************************************************************************/
void destroy_sweeny_ibfs(void) {
if(setup) {
destroy();
}
setup=0;
}
/******************************************************************************
*****************************************************************************/
void destroy_sweeny_sbfs(void) {
destroy_sweeny_ibfs();
}
/******************************************************************************
*****************************************************************************/
char simulate_sweeny_ibfs(void) {
if(setup!=1)
return 0;
else
generateTimeSeries();
return 1;
}
/******************************************************************************
*****************************************************************************/
char simulate_sweeny_sbfs(void) {
if(setup!=2)
return 0;
else
generateTimeSeries();
return 1;
}
| {
"alphanum_fraction": 0.4324034335,
"avg_line_length": 31.3742574257,
"ext": "c",
"hexsha": "76623e5e3060b8794f1fce1377f219bd958421b3",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2017-04-10T14:18:57.000Z",
"max_forks_repo_forks_event_min_datetime": "2017-04-10T14:18:57.000Z",
"max_forks_repo_head_hexsha": "ae6dc73d9a6c793c797453f4d05724b1210bb1be",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "ermeel86/sweeny",
"max_forks_repo_path": "src/sweeny_bfs.c",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "ae6dc73d9a6c793c797453f4d05724b1210bb1be",
"max_issues_repo_issues_event_max_datetime": "2018-08-20T09:32:03.000Z",
"max_issues_repo_issues_event_min_datetime": "2018-08-19T09:29:25.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "ernmeel/sweeny",
"max_issues_repo_path": "src/sweeny_bfs.c",
"max_line_length": 104,
"max_stars_count": 2,
"max_stars_repo_head_hexsha": "ae6dc73d9a6c793c797453f4d05724b1210bb1be",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "ernmeel/sweeny",
"max_stars_repo_path": "src/sweeny_bfs.c",
"max_stars_repo_stars_event_max_datetime": "2017-04-10T14:18:40.000Z",
"max_stars_repo_stars_event_min_datetime": "2017-03-03T10:57:43.000Z",
"num_tokens": 4031,
"size": 15844
} |
#include <math.h>
#include <string.h>
#include <gsl/gsl_matrix.h>
#include <gpc/gpc.h>
#include <egsl/egsl_macros.h>
#include "../csm_all.h"
#include "icp.h"
void sm_journal_open(const char* file) {
file = 0;
/* journal_open(file);*/
}
void ld_invalid_if_outside(LDP ld, double min_reading, double max_reading) {
int i;
for(i=0;i<ld->nrays;i++) {
if(!ld_valid_ray(ld, i)) continue;
double r = ld->readings[i];
if( r <= min_reading || r > max_reading)
ld->valid[i] = 0;
}
}
void sm_icp(struct sm_params*params, struct sm_result*res) {
res->valid = 0;
LDP laser_ref = params->laser_ref;
LDP laser_sens = params->laser_sens;
if(!ld_valid_fields(laser_ref) ||
!ld_valid_fields(laser_sens)) {
return;
}
sm_debug("sm_icp: laser_sens has %d/%d; laser_ref has %d/%d rays valid\n",
count_equal(laser_sens->valid, laser_sens->nrays, 1), laser_sens->nrays,
count_equal(laser_ref->valid, laser_ref->nrays, 1), laser_ref->nrays);
/** Mark as invalid the rays outside of (min_reading, max_reading] */
ld_invalid_if_outside(laser_ref, params->min_reading, params->max_reading);
ld_invalid_if_outside(laser_sens, params->min_reading, params->max_reading);
sm_debug("sm_icp: laser_sens has %d/%d; laser_ref has %d/%d rays valid (after removing outside interval [%f, %f])\n",
count_equal(laser_sens->valid, laser_sens->nrays, 1), laser_sens->nrays,
count_equal(laser_ref->valid, laser_ref->nrays, 1), laser_ref->nrays,
params->min_reading, params->max_reading);
if(JJ) jj_context_enter("sm_icp");
egsl_push_named("sm_icp");
if(params->use_corr_tricks || params->debug_verify_tricks)
ld_create_jump_tables(laser_ref);
ld_compute_cartesian(laser_ref);
ld_compute_cartesian(laser_sens);
if(params->do_alpha_test) {
ld_simple_clustering(laser_ref, params->clustering_threshold);
ld_compute_orientation(laser_ref, params->orientation_neighbourhood, params->sigma);
ld_simple_clustering(laser_sens, params->clustering_threshold);
ld_compute_orientation(laser_sens, params->orientation_neighbourhood, params->sigma);
}
if(JJ) jj_add("laser_ref", ld_to_json(laser_ref));
if(JJ) jj_add("laser_sens", ld_to_json(laser_sens));
gsl_vector * x_new = gsl_vector_alloc(3);
gsl_vector * x_old = vector_from_array(3, params->first_guess);
if(params->do_visibility_test) {
sm_debug("laser_ref:\n");
visibilityTest(laser_ref, x_old);
sm_debug("laser_sens:\n");
gsl_vector * minus_x_old = gsl_vector_alloc(3);
ominus(x_old,minus_x_old);
visibilityTest(laser_sens, minus_x_old);
gsl_vector_free(minus_x_old);
}
double error;
int iterations;
int nvalid;
if(!icp_loop(params, x_old->data, x_new->data, &error, &nvalid, &iterations)) {
sm_error("icp: ICP failed for some reason. \n");
res->valid = 0;
res->iterations = iterations;
res->nvalid = 0;
} else {
/* It was succesfull */
int restarted = 0;
double best_error = error;
gsl_vector * best_x = gsl_vector_alloc(3);
gsl_vector_memcpy(best_x, x_new);
if(params->restart &&
(error/nvalid)>(params->restart_threshold_mean_error) ) {
sm_debug("Restarting: %f > %f \n",(error/nvalid),(params->restart_threshold_mean_error));
restarted = 1;
double dt = params->restart_dt;
double dth = params->restart_dtheta;
sm_debug("icp_loop: dt = %f dtheta= %f deg\n",dt,rad2deg(dth));
double perturb[6][3] = {
{dt,0,0}, {-dt,0,0},
{0,dt,0}, {0,-dt,0},
{0,0,dth}, {0,0,-dth}
};
int a; for(a=0;a<6;a++){
sm_debug("-- Restarting with perturbation #%d\n", a);
struct sm_params my_params = *params;
gsl_vector * start = gsl_vector_alloc(3);
gvs(start, 0, gvg(x_new,0)+perturb[a][0]);
gvs(start, 1, gvg(x_new,1)+perturb[a][1]);
gvs(start, 2, gvg(x_new,2)+perturb[a][2]);
gsl_vector * x_a = gsl_vector_alloc(3);
double my_error; int my_valid; int my_iterations;
if(!icp_loop(&my_params, start->data, x_a->data, &my_error, &my_valid, &my_iterations)){
sm_error("Error during restart #%d/%d. \n", a, 6);
break;
}
iterations+=my_iterations;
if(my_error < best_error) {
sm_debug("--Perturbation #%d resulted in error %f < %f\n", a,my_error,best_error);
gsl_vector_memcpy(best_x, x_a);
best_error = my_error;
}
gsl_vector_free(x_a); gsl_vector_free(start);
}
}
/* At last, we did it. */
res->valid = 1;
vector_to_array(best_x, res->x);
sm_debug("icp: final x = %s \n", gsl_friendly_pose(best_x));
if (restarted) { // recompute correspondences in case of restarts
ld_compute_world_coords(laser_sens, res->x);
if(params->use_corr_tricks)
find_correspondences_tricks(params);
else
find_correspondences(params);
}
if(params->do_compute_covariance) {
val cov0_x, dx_dy1, dx_dy2;
compute_covariance_exact(
laser_ref, laser_sens, best_x,
&cov0_x, &dx_dy1, &dx_dy2);
val cov_x = sc(square(params->sigma), cov0_x);
/* egsl_v2da(cov_x, res->cov_x); */
res->cov_x_m = egsl_v2gslm(cov_x);
res->dx_dy1_m = egsl_v2gslm(dx_dy1);
res->dx_dy2_m = egsl_v2gslm(dx_dy2);
if(0) {
egsl_print("cov0_x", cov0_x);
egsl_print_spectrum("cov0_x", cov0_x);
val fim = ld_fisher0(laser_ref);
val ifim = inv(fim);
egsl_print("fim", fim);
egsl_print_spectrum("ifim", ifim);
}
}
res->error = best_error;
res->iterations = iterations;
res->nvalid = nvalid;
gsl_vector_free(best_x);
}
gsl_vector_free(x_new);
gsl_vector_free(x_old);
egsl_pop_named("sm_icp");
if(JJ) jj_context_exit();
}
void sm_icp_xy(struct sm_params*params, struct sm_result*res)
{
res->valid = 0;
LDP laser_ref = params->laser_ref;
LDP laser_sens = params->laser_sens;
if(!ld_valid_fields(laser_ref) ||
!ld_valid_fields(laser_sens)) {
return;
}
/*
sm_debug("sm_icp: laser_sens has %d/%d; laser_ref has %d/%d rays valid\n",
count_equal(laser_sens->valid, laser_sens->nrays, 1), laser_sens->nrays,
count_equal(laser_ref->valid, laser_ref->nrays, 1), laser_ref->nrays);
*/
/** Mark as invalid the rays outside of (min_reading, max_reading] */
ld_invalid_if_outside(laser_ref, params->min_reading, params->max_reading);
ld_invalid_if_outside(laser_sens, params->min_reading, params->max_reading);
/*
sm_debug("sm_icp: laser_sens has %d/%d; laser_ref has %d/%d rays valid (after removing outside interval [%f, %f])\n",
count_equal(laser_sens->valid, laser_sens->nrays, 1), laser_sens->nrays,
count_equal(laser_ref->valid, laser_ref->nrays, 1), laser_ref->nrays,
params->min_reading, params->max_reading);
if(JJ) jj_context_enter("sm_icp");
egsl_push_named("sm_icp");
*/
if(params->use_corr_tricks || params->debug_verify_tricks)
ld_create_jump_tables(laser_ref);
/*
ld_compute_cartesian(laser_ref);
ld_compute_cartesian(laser_sens);
*/
if(params->do_alpha_test) {
ld_simple_clustering(laser_ref, params->clustering_threshold);
ld_compute_orientation(laser_ref, params->orientation_neighbourhood, params->sigma);
ld_simple_clustering(laser_sens, params->clustering_threshold);
ld_compute_orientation(laser_sens, params->orientation_neighbourhood, params->sigma);
}
if(JJ) jj_add("laser_ref", ld_to_json(laser_ref));
if(JJ) jj_add("laser_sens", ld_to_json(laser_sens));
gsl_vector * x_new = gsl_vector_alloc(3);
gsl_vector * x_old = vector_from_array(3, params->first_guess);
if(params->do_visibility_test) {
sm_debug("laser_ref:\n");
visibilityTest(laser_ref, x_old);
sm_debug("laser_sens:\n");
gsl_vector * minus_x_old = gsl_vector_alloc(3);
ominus(x_old,minus_x_old);
visibilityTest(laser_sens, minus_x_old);
gsl_vector_free(minus_x_old);
}
double error;
int iterations;
int nvalid;
if(!icp_loop(params, x_old->data, x_new->data, &error, &nvalid, &iterations)) {
sm_error("icp: ICP failed for some reason. \n");
res->valid = 0;
res->iterations = iterations;
res->nvalid = 0;
} else {
/* It was succesfull */
double best_error = error;
gsl_vector * best_x = gsl_vector_alloc(3);
gsl_vector_memcpy(best_x, x_new);
if(params->restart &&
(error/nvalid)>(params->restart_threshold_mean_error) ) {
sm_debug("Restarting: %f > %f \n",(error/nvalid),(params->restart_threshold_mean_error));
double dt = params->restart_dt;
double dth = params->restart_dtheta;
sm_debug("icp_loop: dt = %f dtheta= %f deg\n",dt,rad2deg(dth));
double perturb[6][3] = {
{dt,0,0}, {-dt,0,0},
{0,dt,0}, {0,-dt,0},
{0,0,dth}, {0,0,-dth}
};
int a; for(a=0;a<6;a++){
sm_debug("-- Restarting with perturbation #%d\n", a);
struct sm_params my_params = *params;
gsl_vector * start = gsl_vector_alloc(3);
gvs(start, 0, gvg(x_new,0)+perturb[a][0]);
gvs(start, 1, gvg(x_new,1)+perturb[a][1]);
gvs(start, 2, gvg(x_new,2)+perturb[a][2]);
gsl_vector * x_a = gsl_vector_alloc(3);
double my_error; int my_valid; int my_iterations;
if(!icp_loop(&my_params, start->data, x_a->data, &my_error, &my_valid, &my_iterations)){
sm_error("Error during restart #%d/%d. \n", a, 6);
break;
}
iterations+=my_iterations;
if(my_error < best_error) {
sm_debug("--Perturbation #%d resulted in error %f < %f\n", a,my_error,best_error);
gsl_vector_memcpy(best_x, x_a);
best_error = my_error;
}
gsl_vector_free(x_a); gsl_vector_free(start);
}
}
/* At last, we did it. */
res->valid = 1;
vector_to_array(best_x, res->x);
sm_debug("icp: final x = %s \n", gsl_friendly_pose(best_x));
if(params->do_compute_covariance) {
val cov0_x, dx_dy1, dx_dy2;
compute_covariance_exact(
laser_ref, laser_sens, best_x,
&cov0_x, &dx_dy1, &dx_dy2);
val cov_x = sc(square(params->sigma), cov0_x);
// egsl_v2da(cov_x, res->cov_x);
res->cov_x_m = egsl_v2gslm(cov_x);
res->dx_dy1_m = egsl_v2gslm(dx_dy1);
res->dx_dy2_m = egsl_v2gslm(dx_dy2);
if(0) {
egsl_print("cov0_x", cov0_x);
egsl_print_spectrum("cov0_x", cov0_x);
val fim = ld_fisher0(laser_ref);
val ifim = inv(fim);
egsl_print("fim", fim);
egsl_print_spectrum("ifim", ifim);
}
}
res->error = best_error;
res->iterations = iterations;
res->nvalid = nvalid;
gsl_vector_free(x_new);
gsl_vector_free(x_old);
gsl_vector_free(best_x);
}
/*
egsl_pop_named("sm_icp");
if(JJ) jj_context_exit();
*/
}
| {
"alphanum_fraction": 0.6834553159,
"avg_line_length": 28.7645429363,
"ext": "c",
"hexsha": "ec9362ca5166d5eef4eb55b08903af59e00d1cd0",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "f058fb0bc5c4c9b1a590b7536f75b83af35b7785",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "alecone/ROS_project",
"max_forks_repo_path": "src/csm/sm/csm/icp/icp.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "f058fb0bc5c4c9b1a590b7536f75b83af35b7785",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "alecone/ROS_project",
"max_issues_repo_path": "src/csm/sm/csm/icp/icp.c",
"max_line_length": 119,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "f058fb0bc5c4c9b1a590b7536f75b83af35b7785",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "alecone/ROS_project",
"max_stars_repo_path": "src/csm/sm/csm/icp/icp.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 3390,
"size": 10384
} |
#include <gsl/gsl_matrix.h>
#include "BandEnergy.h"
int main(int argc, char *argv[]) {
HTightBinding *Hrs = ExtractHTightBinding("test_data/Fe_soc/Fe_soc_hr.dat");
gsl_matrix *R = gsl_matrix_calloc(3, 3); // R -> all zeros
// Overall scale for R doesn't matter.
gsl_matrix_set(R, 0, 1, 1.0);
gsl_matrix_set(R, 0, 2, 1.0);
gsl_matrix_set(R, 1, 0, 1.0);
gsl_matrix_set(R, 1, 2, 1.0);
gsl_matrix_set(R, 2, 0, 1.0);
gsl_matrix_set(R, 2, 1, 1.0);
double num_electrons = 8.0;
int na = 8;
int nb = 8;
int nc = 8;
bool use_cache = true;
double E_Fermi = 0.0;
double energy = BandEnergy(&E_Fermi, Hrs, R, num_electrons, na, nb, nc, use_cache);
printf("energy = %f\n", energy);
printf("E_Fermi = %f\n", E_Fermi);
return 0;
}
| {
"alphanum_fraction": 0.6105527638,
"avg_line_length": 27.4482758621,
"ext": "c",
"hexsha": "98cb9cb77d045a9bf3dd3b0c49149061ab84287e",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "96b9719b098d3e2e7d6f4fa5b2c938aa460c5fb8",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "tflovorn/cwannier",
"max_forks_repo_path": "BandEnergy_test.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "96b9719b098d3e2e7d6f4fa5b2c938aa460c5fb8",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "tflovorn/cwannier",
"max_issues_repo_path": "BandEnergy_test.c",
"max_line_length": 87,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "96b9719b098d3e2e7d6f4fa5b2c938aa460c5fb8",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "tflovorn/cwannier",
"max_stars_repo_path": "BandEnergy_test.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 300,
"size": 796
} |
#include <math.h>
#include <stdlib.h>
#include <malloc.h>
#include <stdio.h>
#include <assert.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_integration.h>
#include <gsl/gsl_spline.h>
#include <gsl/gsl_sf_gamma.h>
#include <gsl/gsl_sf_legendre.h>
#include <gsl/gsl_sf_bessel.h>
#include <gsl/gsl_linalg.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_eigen.h>
#include <gsl/gsl_sf_expint.h>
#include <stdio.h>
#include <stdlib.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_interp2d.h>
#include <gsl/gsl_spline2d.h>
#include "../../theory/basics.c"
#include "../../emu13/emu.c"
#include "../../theory/parameters.c"
#include "../../theory/cosmo3D.c"
#include "../../theory/redshift.c"
typedef struct {
const gsl_interp2d_type *T = gsl_interp2d_bilinear;
gsl_spline2d *spline;
gsl_interp_accel *xacc;
gsl_interp_accel *yacc;
double *grid_values;
} spline_interpolator;
spline_interpolator global_baryon_spline;
void init_baryon_spline_interpolation_to_TNG100(){
const size_t N = 100; /* number of points to interpolate */
const double lnk_values[] = { 0.0, 1.0 };
const double z_values[] = { 3.71, 3.49, 3.28, 2.90, 2.44, 2.10, 1.74, 1.41, 1.04, 0.7, 0.35, 0.18, 0.0 }; /* define unit square */
const size_t nk = sizeof(lnk_values) / sizeof(double); /* y grid points */
const size_t nz = sizeof(z_values) / sizeof(double); /* x grid points */
global_baryon_spline.grid_values = malloc(nk * nz * sizeof(double));
global_baryon_spline.spline = gsl_spline2d_alloc(global_baryon_spline.T, nk, nz);
global_baryon_spline.xacc = gsl_interp_accel_alloc();
global_baryon_spline.yacc = gsl_interp_accel_alloc();
size_t i, j;
for(int i = 0; i < nk; i++){
for(int j = 0; j < nz; j++){
gsl_spline2d_set(spline, global_baryon_spline.grid_values, i, j, TNG100[i][j]);
}
}
/* initialize interpolation */
gsl_spline2d_init(global_baryon_spline.spline, lnk_values, z_values, Pk_ratio, nk, nz);
}
void free_baryon_spline_interpolation_to_TNG100(){
gsl_spline2d_free(global_baryon_spline.spline);
gsl_interp_accel_free(global_baryon_spline.xacc);
gsl_interp_accel_free(global_baryon_spline.yacc);
free(global_baryon_spline.grid_values);
}
double fraction_Pdelta_baryon_from_sims_DES(double k,double z)
{
return gsl_spline2d_eval(global_baryon_spline.spline, k, z, global_baryon_spline.xacc, global_baryon_spline.yacc);
}
double fraction_Pdelta_baryon_from_spline_DES(double k,double z)
{
int i;
double val;
static int READ_TABLE=0;
static double **table;
FILE *F;
int baryon_zbin=13;
int baryon_kbin=325;
double logk_min = -3.3010299956639813;
double logk_max = 3.1760912590556813;
double dz=(redshift.shear_zdistrpar_zmax)/(10.0);
static double dlogk=(logk_max-logk_min)/(double(baryon_kbin-1));
val = interpol2d(AGN_DESdepth, baryon_kbin, logk_min, logk_max, dk, log(k), baryon_zbin, 0.0, 2.0, dz, z, 0.0, 0.0);
return val;
}
// if (READ_TABLE==0){
// if (strcmp(pdeltaparams.baryons,"AGN_DESdepth")==0) P_type = 0;
// if (strcmp(pdeltaparams.baryons,"NOSN_DESdepth")==0) P_type = 1;
// if (strcmp(pdeltaparams.baryons,"NOSN_NOZCOOL_DESdepth")==0) P_type = 2;
// if (strcmp(pdeltaparams.baryons,"NOZCOOL_DESdepth")==0) P_type = 3;
// if (strcmp(pdeltaparams.baryons,"REF_DESdepth")==0) P_type = 4;
// if (strcmp(pdeltaparams.baryons,"WDENS_DESdepth") ==0) P_type = 5;
// if (strcmp(pdeltaparams.baryons,"DBLIMFV1618_DESdepth") ==0) P_type = 6;
// if (strcmp(pdeltaparams.baryons,"WML4_DESdepth")==0) P_type = 7;
// if (strcmp(pdeltaparams.baryons,"WML1V848_DESdepth")==0) P_type = 8;
// if (strcmp(pdeltaparams.baryons,"AD_DESdepth")==0) P_type = 9;
// if (strcmp(pdeltaparams.baryons,"CX_DESdepth")==0) P_type = 10;
// if (strcmp(pdeltaparams.baryons,"CW_DESdepth")==0) P_type = 11;
// if (strcmp(pdeltaparams.baryons,"A_DESdepth")==0) P_type = 12;
// if (strcmp(pdeltaparams.baryons,"CSF_DESdepth")==0) P_type = 13;
// }
// switch (P_type){
// case 0: val = interpol2d(AGN_DESdepth, baryon_kbin, 0.3, 10.0, dk, kintern, baryon_zbin, 0.0, 2.0, dz, z, 0.0, 0.0); break;
// case 1: val = interpol2d(NOSN_DESdepth, baryon_kbin, 0.3, 10.0, dk, kintern, baryon_zbin, 0.0, 2.0, dz, z, 0.0, 0.0); break;
// case 2: val = interpol2d(NOSN_NOZCOOL_DESdepth, baryon_kbin, 0.3, 10.0, dk, kintern, baryon_zbin, 0.0, 2.0, dz, z, 0.0, 0.0); break;
// case 3: val = interpol2d(NOZCOOL_DESdepth, baryon_kbin, 0.3, 10.0, dk, kintern, baryon_zbin, 0.0, 2.0, dz, z, 0.0, 0.0); break;
// case 4: val = interpol2d(REF_DESdepth, baryon_kbin, 0.3, 10.0, dk, kintern, baryon_zbin, 0.0, 2.0, dz, z, 0.0, 0.0); break;
// case 5: val = interpol2d(WDENS_DESdepth, baryon_kbin, 0.3, 10.0, dk, kintern, baryon_zbin, 0.0, 2.0, dz, z, 0.0, 0.0); break;
// case 6: val = interpol2d(DBLIMFV1618_DESdepth, baryon_kbin, 0.3, 10.0, dk, kintern, baryon_zbin, 0.0, 2.0, dz, z, 0.0, 0.0); break;
// case 7: val = interpol2d(WML4_DESdepth, baryon_kbin, 0.3, 10.0, dk, kintern, baryon_zbin, 0.0, 2.0, dz, z, 0.0, 0.0); break;
// case 8: val = interpol2d(WML1V848_DESdepth, baryon_kbin, 0.3, 10.0, dk, kintern, baryon_zbin, 0.0, 2.0, dz, z, 0.0, 0.0); break;
// case 9: val = interpol2d(AD_DESdepth, baryon_kbin, 0.3, 10.0, dk, kintern, baryon_zbin, 0.0, 2.0, dz, z, 0.0, 0.0); break;
// case 10: val = interpol2d(CX_DESdepth, baryon_kbin, 0.3, 10.0, dk, kintern, baryon_zbin, 0.0, 2.0, dz, z, 0.0, 0.0); break;
// case 11: val = interpol2d(CW_DESdepth, baryon_kbin, 0.3, 10.0, dk, kintern, baryon_zbin, 0.0, 2.0, dz, z, 0.0, 0.0); break;
// case 12: val = interpol2d(A_DESdepth, baryon_kbin, 0.3, 10.0, dk, kintern, baryon_zbin, 0.0, 2.0, dz, z, 0.0, 0.0); break;
// case 13: val = interpol2d(CSF_DESdepth, baryon_kbin, 0.3, 10.0, dk, kintern, baryon_zbin, 0.0, 2.0, dz, z, 0.0, 0.0); break;
// default:
// printf("baryons.c: %s baryonic scenario not defined\n",pdeltaparams.baryons);
// break;
// }
// kintern=k/cosmology.coverH0;
// return val;
// }
// if (strcmp(pdeltaparams.baryons,"AGN_LSSTdepth")==0) P_type = 14;
// if (strcmp(pdeltaparams.baryons,"NOSN_LSSTdepth")==0) P_type = 15;
// if (strcmp(pdeltaparams.baryons,"NOSN_NOZCOOL_LSSTdepth")==0) P_type = 16;
// if (strcmp(pdeltaparams.baryons,"NOZCOOL_LSSTdepth")==0) P_type = 17;
// if (strcmp(pdeltaparams.baryons,"REF_LSSTdepth")==0) P_type = 18;
// if (strcmp(pdeltaparams.baryons,"WDENS_LSSTdepth") ==0) P_type = 19;
// if (strcmp(pdeltaparams.baryons,"DBLIMFV1618_LSSTdepth") ==0) P_type = 20;
// if (strcmp(pdeltaparams.baryons,"WML4_LSSTdepth")==0) P_type = 21;
// if (strcmp(pdeltaparams.baryons,"WML1V848_LSSTdepth")==0) P_type = 22;
// if (strcmp(pdeltaparams.baryons,"AD_LSSTdepth")==0) P_type = 23;
// if (strcmp(pdeltaparams.baryons,"CX_LSSTdepth")==0) P_type = 24;
// if (strcmp(pdeltaparams.baryons,"CW_LSSTdepth")==0) P_type = 25;
// if (table!=0) free_double_matrix(table, 0, OWLS_kbin-1, 0, OWLS_zbin-1);
// table = create_double_matrix(0, OWLS_kbin-1, 0, OWLS_zbin-1);
// printf("%s\n",file.DATA_FILE);
// F=fopen(file.DATA_FILE,"r");
// for(i=0;i<OWLS_kbin;i++){
// fscanf(F,"%le %le %le %le %le %le %le %le %le %le %le\n",&a1,&a2,&a3,&a4,&a5,&a6,&a7,&a8,&a9,&a10,&a11);
// // printf("%le %le %le %le %le %le %le %le %le %le %le\n",a1,a2,a3,a4,a5,a6,a7,a8,a9,a10,a11);
// table[i][0]=a1;
// table[i][1]=a2;
// table[i][2]=a3;
// table[i][3]=a4;
// table[i][4]=a5;
// table[i][5]=a6;
// table[i][6]=a7;
// table[i][7]=a8;
// table[i][8]=a9;
// table[i][9]=a10;
// table[i][10]=a11;
// }
// READ_TABLE=1;
// }
// kintern=k/cosmology.coverH0;
// val = interpol2d(table, OWLS_kbin, 0.3, 10.0, dk, kintern,OWLS_zbin, 0.0, 2.0, dz, z, 0.0, 0.0);
// return val;
// }
| {
"alphanum_fraction": 0.6593643156,
"avg_line_length": 42.2299465241,
"ext": "c",
"hexsha": "4bbeceb07924fcb66daa0329a2d4bfa08132199b",
"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": "1771d9b3382a977bb97e6e37b987beea73152bdd",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "CosmoLike/LSST_emu_nersc",
"max_forks_repo_path": "CosmoLike/cosmolike_core/theory/baryons.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "1771d9b3382a977bb97e6e37b987beea73152bdd",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "CosmoLike/LSST_emu_nersc",
"max_issues_repo_path": "CosmoLike/cosmolike_core/theory/baryons.c",
"max_line_length": 140,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "1771d9b3382a977bb97e6e37b987beea73152bdd",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "CosmoLike/LSST_emu_nersc",
"max_stars_repo_path": "CosmoLike/cosmolike_core/theory/baryons.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 3226,
"size": 7897
} |
//IN method.
//Affine transformation (weights and biases) of Ni inputs to No outputs.
//This version uses CBLAS.
//Input X has Ni neurons and output Y has No neurons.
//Each output neuron has a bias term, so B is a vector of length No.
//The vecs of length Ni are always contiguous in memory, such that:
//If col-major: Y[:,l] = W' * X[:,l] + B
//where:
//X has size Ni x L
//Y has size No x L
//W has size Ni x No
//B has size No x 1
//If row-major: Y[l,:] = X[l,:] * W' + B
//X has size L x Ni
//Y has size L x No
//W has size No x Ni
//B has size 1 x No
//For a different set-up that allows affine transformation of vecs in
//any orientation, use the affine function from math.
#include <cblas.h>
#ifdef __cplusplus
namespace codee {
extern "C" {
#endif
int affine_cblas_s (float *Y, const float *X, const float *W, const float *B, const size_t Ni, const size_t No, const size_t L);
int affine_cblas_d (double *Y, const double *X, const double *W, const double *B, const size_t Ni, const size_t No, const size_t L);
int affine_cblas_c (float *Y, const float *X, const float *W, const float *B, const size_t Ni, const size_t No, const size_t L);
int affine_cblas_z (double *Y, const double *X, const double *W, const double *B, const size_t Ni, const size_t No, const size_t L);
int affine_cblas_s (float *Y, const float *X, const float *W, const float *B, const size_t Ni, const size_t No, const size_t L)
{
for (size_t l=L; l>0u; --l, X+=Ni, Y+=No)
{
cblas_scopy((int)No,B,1,Y,1);
cblas_sgemv(CblasRowMajor,CblasNoTrans,(int)No,(int)Ni,1.0f,W,(int)Ni,X,1,1.0f,Y,1);
}
return 0;
}
int affine_cblas_d (double *Y, const double *X, const double *W, const double *B, const size_t Ni, const size_t No, const size_t L)
{
for (size_t l=L; l>0u; --l, X+=Ni, Y+=No)
{
cblas_dcopy((int)No,B,1,Y,1);
cblas_dgemv(CblasRowMajor,CblasNoTrans,(int)No,(int)Ni,1.0,W,(int)Ni,X,1,1.0,Y,1);
}
return 0;
}
int affine_cblas_c (float *Y, const float *X, const float *W, const float *B, const size_t Ni, const size_t No, const size_t L)
{
const float o[2] = {1.0f,0.0f};
for (size_t l=L; l>0u; --l, X+=2u*Ni, Y+=2u*No)
{
cblas_ccopy((int)No,B,1,Y,1);
cblas_cgemv(CblasRowMajor,CblasNoTrans,(int)No,(int)Ni,o,W,(int)Ni,X,1,o,Y,1);
}
return 0;
}
int affine_cblas_z (double *Y, const double *X, const double *W, const double *B, const size_t Ni, const size_t No, const size_t L)
{
const double o[2] = {1.0,0.0};
for (size_t l=L; l>0u; --l, X+=2u*Ni, Y+=2u*No)
{
cblas_zcopy((int)No,B,1,Y,1);
cblas_zgemv(CblasRowMajor,CblasNoTrans,(int)No,(int)Ni,o,W,(int)Ni,X,1,o,Y,1);
}
return 0;
}
#ifdef __cplusplus
}
}
#endif
| {
"alphanum_fraction": 0.6457122093,
"avg_line_length": 28.9684210526,
"ext": "c",
"hexsha": "28fc7e916d6ff70ebb04e0ff9a8596d8f07f6b7b",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "c4b8317a38a72a16fd0bf905791b6c19e49c0aa7",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "erikedwards4/nn",
"max_forks_repo_path": "c/affine.cblas.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "c4b8317a38a72a16fd0bf905791b6c19e49c0aa7",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "erikedwards4/nn",
"max_issues_repo_path": "c/affine.cblas.c",
"max_line_length": 132,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "c4b8317a38a72a16fd0bf905791b6c19e49c0aa7",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "erikedwards4/nn",
"max_stars_repo_path": "c/affine.cblas.c",
"max_stars_repo_stars_event_max_datetime": "2020-08-26T09:28:40.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-08-26T09:28:40.000Z",
"num_tokens": 967,
"size": 2752
} |
#ifndef __MATH_GSL_VECTOR__
#define __MATH_GSL_VECTOR__
#include <assert.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_cblas.h>
#include <gsl/gsl_matrix.h>
#include "math/vectorops.h"
class GslVectorItem {
public:
GslVectorItem(gsl_vector* ptr, size_t index) :
ptr_(ptr),
index_(index) { }
operator const double() {
return gsl_vector_get(ptr_, index_);
}
double operator =(const double v) {
gsl_vector_set(ptr_, index_, v);
return v;
}
double operator +=(const double v) {
double oldv = gsl_vector_get(ptr_, index_);
gsl_vector_set(ptr_, index_, oldv + v);
return oldv + v;
}
double operator -=(const double v) {
double oldv = gsl_vector_get(ptr_, index_);
gsl_vector_set(ptr_, index_, oldv - v);
return oldv - v;
}
private:
gsl_vector* ptr_;
size_t index_;
};
class GslVectorBase {
public:
/*
double operator[](const size_t index) const {
assert(ptr_ != NULL);
return gsl_vector_get(ptr_, index);
}
*/
GslVectorItem operator[](const size_t index) const {
assert(ptr_ != NULL);
return GslVectorItem(ptr_, index);
}
GslVectorBase& operator+=(const gsl_vector* x) {
assert(ptr_ != NULL);
gsl_vector_add(ptr_, x);
return *this;
}
GslVectorBase& operator-=(const gsl_vector* x) {
assert(ptr_ != NULL);
gsl_vector_sub(ptr_, x);
return *this;
}
GslVectorBase& operator+=(const GslVectorBase& x) {
assert(ptr_ != NULL);
gsl_vector_add(ptr_, x.ptr());
return *this;
}
GslVectorBase& operator-=(const GslVectorBase& x) {
assert(ptr_ != NULL);
gsl_vector_sub(ptr_, x.ptr());
return *this;
}
GslVectorBase& operator*=(const gsl_vector* x) {
assert(ptr_ != NULL);
gsl_vector_mul(ptr_, x);
return *this;
}
GslVectorBase& operator*=(const GslVectorBase& x) {
assert(ptr_ != NULL);
gsl_vector_mul(ptr_, x.ptr());
return *this;
}
GslVectorBase& operator/=(const GslVectorBase& x) {
assert(ptr_ != NULL);
gsl_vector_div(ptr_, x.ptr());
return *this;
}
double Sum() const {
return gsl_blas_dsum(ptr_);
}
double L2Norm() const {
return gsl_blas_dnrm2(ptr_);
}
void Normalize() const {
assert(ptr_ != NULL);
double s = Sum();
gsl_vector_scale(ptr_, 1. / s);
}
size_t size() const {
return ptr_->size;
}
GslVectorBase& operator*=(double v) {
assert(ptr_ != NULL);
gsl_vector_scale(ptr_, v);
return *this;
}
GslVectorBase& operator/=(double v) {
assert(ptr_ != NULL);
gsl_vector_scale(ptr_, 1. / v);
return *this;
}
// Note that the standalone product is a dot product!
const double operator*(const gsl_vector* x) const {
double result;
assert(ptr_ != NULL);
gsl_blas_ddot(ptr_, x, &result);
return result;
}
const double operator*(const GslVectorBase& x) const {
double result;
assert(ptr_ != NULL);
gsl_blas_ddot(ptr_, x.ptr(), &result);
return result;
}
GslVectorBase& operator+=(const double x) {
for (size_t ii = 0; ii < ptr_->size; ++ii) {
gsl_vector_set(ptr_, ii, gsl_vector_get(ptr_, ii) + x);
}
return *this;
}
GslVectorBase& operator-=(const double x) {
for (size_t ii = 0; ii < ptr_->size; ++ii) {
gsl_vector_set(ptr_, ii, gsl_vector_get(ptr_, ii) - x);
}
return *this;
}
GslVectorBase& operator=(const gsl_vector* x) {
assert(ptr_ != NULL);
gsl_vector_memcpy(ptr_, x);
return *this;
}
GslVectorBase& operator=(const GslVectorBase& x) {
assert(ptr_ != NULL);
return *this = x.ptr();
}
GslVectorBase& operator=(const double v) {
if (v == 0.0) {
SetZero();
} else {
SetAll(v);
}
return *this;
}
void SetZero() {
assert(ptr_ != NULL);
gsl_vector_set_zero(ptr_);
}
void SetAll(const double v) {
assert(ptr_ != NULL);
gsl_vector_set_all(ptr_, v);
}
int Fprintf(FILE* stream, const char* format) const {
assert(ptr_ != NULL);
return gsl_vector_fprintf(stream, ptr_, format);
}
int Fscanf(FILE* stream) {
assert(ptr_ != NULL);
return gsl_vector_fscanf(stream, ptr_);
}
const gsl_vector* ptr() const { return ptr_; }
gsl_vector* mutable_ptr() { return ptr_; }
protected:
GslVectorBase() : ptr_(NULL) { }
gsl_vector* ptr_;
private:
GslVectorBase(const GslVectorBase&) { }
};
class GslVector : public GslVectorBase {
public:
GslVector(const size_t size) : GslVectorBase() {
Allocate(size);
}
GslVector() : GslVectorBase() {
}
~GslVector() {
if (ptr_ != NULL) {
gsl_vector_free(ptr_);
}
}
void Reset(gsl_vector* val) {
if (ptr_ != NULL) {
gsl_vector_free(ptr_);
}
ptr_ = val;
}
void Allocate(const size_t size) {
assert(ptr_ == NULL);
ptr_ = gsl_vector_alloc(size);
}
GslVectorBase& operator=(const gsl_vector* x) {
GslVectorBase::operator=(x);
return *this;
}
GslVectorBase& operator=(const GslVectorBase& x) {
GslVectorBase::operator=(x);
return *this;
}
GslVectorBase& operator=(const double v) {
GslVectorBase::operator=(v);
return *this;
}
private:
GslVector(const GslVector&) { }
};
class GslMatrixRow : public GslVectorBase {
public:
GslMatrixRow(GslMatrix& matrix, const size_t row) :
view_(gsl_matrix_row(matrix.mutable_ptr(), row)) {
ptr_ = &view_.vector;
}
GslMatrixRow(gsl_matrix* matrix, const size_t row) :
view_(gsl_matrix_row(matrix, row)) {
ptr_ = &view_.vector;
}
GslVectorBase& operator=(const gsl_vector* x) {
GslVectorBase::operator=(x);
return *this;
}
GslVectorBase& operator=(const GslVectorBase& x) {
GslVectorBase::operator=(x);
return *this;
}
GslVectorBase& operator=(const double v) {
GslVectorBase::operator=(v);
return *this;
}
private:
gsl_vector_view view_;
GslMatrixRow(const GslMatrixRow&) { }
};
class GslMatrixColumn : public GslVectorBase {
public:
GslMatrixColumn(GslMatrix& matrix, const size_t col) :
view_(gsl_matrix_column(matrix.mutable_ptr(), col)) {
ptr_ = &view_.vector;
}
GslMatrixColumn(gsl_matrix* matrix, const size_t col) :
view_(gsl_matrix_column(matrix, col)) {
ptr_ = &view_.vector;
}
GslVectorBase& operator=(const gsl_vector* x) {
GslVectorBase::operator=(x);
return *this;
}
GslVectorBase& operator=(const GslVectorBase& x) {
GslVectorBase::operator=(x);
return *this;
}
GslVectorBase& operator=(const double v) {
GslVectorBase::operator=(v);
return *this;
}
private:
gsl_vector_view view_;
GslMatrixColumn(const GslMatrixColumn&) { }
};
class GslMatrixDiagonal : public GslVectorBase {
public:
GslMatrixDiagonal(GslMatrix& matrix) :
view_(gsl_matrix_diagonal(matrix.mutable_ptr())) {
ptr_ = &view_.vector;
}
GslMatrixDiagonal(gsl_matrix* matrix) :
view_(gsl_matrix_diagonal(matrix)) {
ptr_ = &view_.vector;
}
GslVectorBase& operator=(const gsl_vector* x) {
GslVectorBase::operator=(x);
return *this;
}
GslVectorBase& operator=(const GslVectorBase& x) {
GslVectorBase::operator=(x);
return *this;
}
GslVectorBase& operator=(const double v) {
GslVectorBase::operator=(v);
return *this;
}
private:
gsl_vector_view view_;
GslMatrixDiagonal(const GslMatrixDiagonal&) { }
};
class GslSubvector : public GslVectorBase {
public:
GslSubvector(GslVectorBase& vector, size_t i, size_t n) :
view_(gsl_vector_subvector(vector.mutable_ptr(), i, n)) {
ptr_ = &view_.vector;
}
GslVectorBase& operator=(const gsl_vector* x) {
GslVectorBase::operator=(x);
return *this;
}
GslVectorBase& operator=(const GslVectorBase& x) {
GslVectorBase::operator=(x);
return *this;
}
GslVectorBase& operator=(const double v) {
GslVectorBase::operator=(v);
return *this;
}
private:
gsl_vector_view view_;
GslSubvector(const GslSubvector&) { }
};
#endif // __MATH_GSL_VECTOR__
| {
"alphanum_fraction": 0.6440508855,
"avg_line_length": 21.3244680851,
"ext": "h",
"hexsha": "402343cde49f770c6e440778eea1b317bca4a4d7",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2018-11-27T01:35:33.000Z",
"max_forks_repo_forks_event_min_datetime": "2018-11-27T01:35:33.000Z",
"max_forks_repo_head_hexsha": "159aab87f04b745d874b53f64fd30703b4d5a70c",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "boomsbloom/dtm-fmri",
"max_forks_repo_path": "DTM/dtm-master/lib/math/gsl_vector.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "159aab87f04b745d874b53f64fd30703b4d5a70c",
"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": "boomsbloom/dtm-fmri",
"max_issues_repo_path": "DTM/dtm-master/lib/math/gsl_vector.h",
"max_line_length": 63,
"max_stars_count": 4,
"max_stars_repo_head_hexsha": "159aab87f04b745d874b53f64fd30703b4d5a70c",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "boomsbloom/dtm-fmri",
"max_stars_repo_path": "DTM/dtm-master/lib/math/gsl_vector.h",
"max_stars_repo_stars_event_max_datetime": "2022-01-27T01:17:11.000Z",
"max_stars_repo_stars_event_min_datetime": "2018-11-27T01:35:30.000Z",
"num_tokens": 2338,
"size": 8018
} |
/* ******************************************************************************
*
*
* This program and the accompanying materials are made available under the
* terms of the Apache License, Version 2.0 which is available at
* https://www.apache.org/licenses/LICENSE-2.0.
*
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
* 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.
*
* SPDX-License-Identifier: Apache-2.0
******************************************************************************/
//
// @author raver119@gmail.com
//
#ifndef LIBND4J_GEMM_H
#define LIBND4J_GEMM_H
#include <cblas.h>
#include <math/templatemath.h>
#include <system/op_boilerplate.h>
namespace sd {
namespace blas {
template <typename T>
static void * transpose(int orderSource, int orderTarget, int rows, int cols, void *source);
static inline int linearIndexC(int rows, int cols, int r, int c);
static inline int linearIndexF(int rows, int cols, int r, int c);
template <typename X, typename Y, typename Z>
class GEMM {
protected:
public:
static void op(int Order, int TransA, int TransB, int M, int N, int K, double alpha, void *A, int lda, void *B, int ldb, double beta, void *C, int ldc);
};
template <typename X, typename Y, typename Z>
class GEMV : public sd::blas::GEMM<X, Y, Z>{
public:
static void op(int TRANS, int M, int N, double alpha, void* vA, int lda, void* vX, int incx, double beta, void* vY, int incy );
};
int FORCEINLINE linearIndexC(int rows, int cols, int r, int c) {
return (r * cols + c);
}
int FORCEINLINE linearIndexF(int rows, int cols, int r, int c) {
return (c * rows + r);
}
}
}
#endif //LIBND4J_GEMM_H
| {
"alphanum_fraction": 0.6010077874,
"avg_line_length": 33.5846153846,
"ext": "h",
"hexsha": "8026fa21e68363921f55c30f651e420e8f445b74",
"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": "d93976922a9af838457a15e69ef1218c3d9adc45",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "Celebrate-future/deeplearning4j",
"max_forks_repo_path": "libnd4j/include/ops/gemm.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "d93976922a9af838457a15e69ef1218c3d9adc45",
"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": "Celebrate-future/deeplearning4j",
"max_issues_repo_path": "libnd4j/include/ops/gemm.h",
"max_line_length": 165,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "d93976922a9af838457a15e69ef1218c3d9adc45",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "Celebrate-future/deeplearning4j",
"max_stars_repo_path": "libnd4j/include/ops/gemm.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 507,
"size": 2183
} |
/* blas/gsl_blas.h
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
/*
* Author: G. Jungman
*/
#ifndef __GSL_BLAS_H__
#define __GSL_BLAS_H__
#include <gsl/gsl_vector.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_blas_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
/* ========================================================================
* Level 1
* ========================================================================
*/
int gsl_blas_sdsdot (float alpha,
const gsl_vector_float * X,
const gsl_vector_float * Y,
float * result
);
int gsl_blas_dsdot (const gsl_vector_float * X,
const gsl_vector_float * Y,
double * result
);
int gsl_blas_sdot (const gsl_vector_float * X,
const gsl_vector_float * Y,
float * result
);
int gsl_blas_ddot (const gsl_vector * X,
const gsl_vector * Y,
double * result
);
int gsl_blas_cdotu (const gsl_vector_complex_float * X,
const gsl_vector_complex_float * Y,
gsl_complex_float * dotu);
int gsl_blas_cdotc (const gsl_vector_complex_float * X,
const gsl_vector_complex_float * Y,
gsl_complex_float * dotc);
int gsl_blas_zdotu (const gsl_vector_complex * X,
const gsl_vector_complex * Y,
gsl_complex * dotu);
int gsl_blas_zdotc (const gsl_vector_complex * X,
const gsl_vector_complex * Y,
gsl_complex * dotc);
float gsl_blas_snrm2 (const gsl_vector_float * X);
float gsl_blas_sasum (const gsl_vector_float * X);
double gsl_blas_dnrm2 (const gsl_vector * X);
double gsl_blas_dasum (const gsl_vector * X);
float gsl_blas_scnrm2 (const gsl_vector_complex_float * X);
float gsl_blas_scasum (const gsl_vector_complex_float * X);
double gsl_blas_dznrm2 (const gsl_vector_complex * X);
double gsl_blas_dzasum (const gsl_vector_complex * X);
CBLAS_INDEX_t gsl_blas_isamax (const gsl_vector_float * X);
CBLAS_INDEX_t gsl_blas_idamax (const gsl_vector * X);
CBLAS_INDEX_t gsl_blas_icamax (const gsl_vector_complex_float * X);
CBLAS_INDEX_t gsl_blas_izamax (const gsl_vector_complex * X);
int gsl_blas_sswap (gsl_vector_float * X,
gsl_vector_float * Y);
int gsl_blas_scopy (const gsl_vector_float * X,
gsl_vector_float * Y);
int gsl_blas_saxpy (float alpha,
const gsl_vector_float * X,
gsl_vector_float * Y);
int gsl_blas_dswap (gsl_vector * X,
gsl_vector * Y);
int gsl_blas_dcopy (const gsl_vector * X,
gsl_vector * Y);
int gsl_blas_daxpy (double alpha,
const gsl_vector * X,
gsl_vector * Y);
int gsl_blas_cswap (gsl_vector_complex_float * X,
gsl_vector_complex_float * Y);
int gsl_blas_ccopy (const gsl_vector_complex_float * X,
gsl_vector_complex_float * Y);
int gsl_blas_caxpy (const gsl_complex_float alpha,
const gsl_vector_complex_float * X,
gsl_vector_complex_float * Y);
int gsl_blas_zswap (gsl_vector_complex * X,
gsl_vector_complex * Y);
int gsl_blas_zcopy (const gsl_vector_complex * X,
gsl_vector_complex * Y);
int gsl_blas_zaxpy (const gsl_complex alpha,
const gsl_vector_complex * X,
gsl_vector_complex * Y);
int gsl_blas_srotg (float a[], float b[], float c[], float s[]);
int gsl_blas_srotmg (float d1[], float d2[], float b1[], float b2, float P[]);
int gsl_blas_srot (gsl_vector_float * X,
gsl_vector_float * Y,
float c, float s);
int gsl_blas_srotm (gsl_vector_float * X,
gsl_vector_float * Y,
const float P[]);
int gsl_blas_drotg (double a[], double b[], double c[], double s[]);
int gsl_blas_drotmg (double d1[], double d2[], double b1[],
double b2, double P[]);
int gsl_blas_drot (gsl_vector * X,
gsl_vector * Y,
const double c, const double s);
int gsl_blas_drotm (gsl_vector * X,
gsl_vector * Y,
const double P[]);
void gsl_blas_sscal (float alpha, gsl_vector_float * X);
void gsl_blas_dscal (double alpha, gsl_vector * X);
void gsl_blas_cscal (const gsl_complex_float alpha, gsl_vector_complex_float * X);
void gsl_blas_zscal (const gsl_complex alpha, gsl_vector_complex * X);
void gsl_blas_csscal (float alpha, gsl_vector_complex_float * X);
void gsl_blas_zdscal (double alpha, gsl_vector_complex * X);
/* ===========================================================================
* Level 2
* ===========================================================================
*/
/*
* Routines with standard 4 prefixes (S, D, C, Z)
*/
int gsl_blas_sgemv (CBLAS_TRANSPOSE_t TransA,
float alpha,
const gsl_matrix_float * A,
const gsl_vector_float * X,
float beta,
gsl_vector_float * Y);
int gsl_blas_strmv (CBLAS_UPLO_t Uplo,
CBLAS_TRANSPOSE_t TransA, CBLAS_DIAG_t Diag,
const gsl_matrix_float * A,
gsl_vector_float * X);
int gsl_blas_strsv (CBLAS_UPLO_t Uplo,
CBLAS_TRANSPOSE_t TransA, CBLAS_DIAG_t Diag,
const gsl_matrix_float * A,
gsl_vector_float * X);
int gsl_blas_dgemv (CBLAS_TRANSPOSE_t TransA,
double alpha,
const gsl_matrix * A,
const gsl_vector * X,
double beta,
gsl_vector * Y);
int gsl_blas_dtrmv (CBLAS_UPLO_t Uplo,
CBLAS_TRANSPOSE_t TransA, CBLAS_DIAG_t Diag,
const gsl_matrix * A,
gsl_vector * X);
int gsl_blas_dtrsv (CBLAS_UPLO_t Uplo,
CBLAS_TRANSPOSE_t TransA, CBLAS_DIAG_t Diag,
const gsl_matrix * A,
gsl_vector * X);
int gsl_blas_cgemv (CBLAS_TRANSPOSE_t TransA,
const gsl_complex_float alpha,
const gsl_matrix_complex_float * A,
const gsl_vector_complex_float * X,
const gsl_complex_float beta,
gsl_vector_complex_float * Y);
int gsl_blas_ctrmv (CBLAS_UPLO_t Uplo,
CBLAS_TRANSPOSE_t TransA, CBLAS_DIAG_t Diag,
const gsl_matrix_complex_float * A,
gsl_vector_complex_float * X);
int gsl_blas_ctrsv (CBLAS_UPLO_t Uplo,
CBLAS_TRANSPOSE_t TransA, CBLAS_DIAG_t Diag,
const gsl_matrix_complex_float * A,
gsl_vector_complex_float * X);
int gsl_blas_zgemv (CBLAS_TRANSPOSE_t TransA,
const gsl_complex alpha,
const gsl_matrix_complex * A,
const gsl_vector_complex * X,
const gsl_complex beta,
gsl_vector_complex * Y);
int gsl_blas_ztrmv (CBLAS_UPLO_t Uplo,
CBLAS_TRANSPOSE_t TransA, CBLAS_DIAG_t Diag,
const gsl_matrix_complex * A,
gsl_vector_complex * X);
int gsl_blas_ztrsv (CBLAS_UPLO_t Uplo,
CBLAS_TRANSPOSE_t TransA, CBLAS_DIAG_t Diag,
const gsl_matrix_complex * A,
gsl_vector_complex *X);
/*
* Routines with S and D prefixes only
*/
int gsl_blas_ssymv (CBLAS_UPLO_t Uplo,
float alpha,
const gsl_matrix_float * A,
const gsl_vector_float * X,
float beta,
gsl_vector_float * Y);
int gsl_blas_sger (float alpha,
const gsl_vector_float * X,
const gsl_vector_float * Y,
gsl_matrix_float * A);
int gsl_blas_ssyr (CBLAS_UPLO_t Uplo,
float alpha,
const gsl_vector_float * X,
gsl_matrix_float * A);
int gsl_blas_ssyr2 (CBLAS_UPLO_t Uplo,
float alpha,
const gsl_vector_float * X,
const gsl_vector_float * Y,
gsl_matrix_float * A);
int gsl_blas_dsymv (CBLAS_UPLO_t Uplo,
double alpha,
const gsl_matrix * A,
const gsl_vector * X,
double beta,
gsl_vector * Y);
int gsl_blas_dger (double alpha,
const gsl_vector * X,
const gsl_vector * Y,
gsl_matrix * A);
int gsl_blas_dsyr (CBLAS_UPLO_t Uplo,
double alpha,
const gsl_vector * X,
gsl_matrix * A);
int gsl_blas_dsyr2 (CBLAS_UPLO_t Uplo,
double alpha,
const gsl_vector * X,
const gsl_vector * Y,
gsl_matrix * A);
/*
* Routines with C and Z prefixes only
*/
int gsl_blas_chemv (CBLAS_UPLO_t Uplo,
const gsl_complex_float alpha,
const gsl_matrix_complex_float * A,
const gsl_vector_complex_float * X,
const gsl_complex_float beta,
gsl_vector_complex_float * Y);
int gsl_blas_cgeru (const gsl_complex_float alpha,
const gsl_vector_complex_float * X,
const gsl_vector_complex_float * Y,
gsl_matrix_complex_float * A);
int gsl_blas_cgerc (const gsl_complex_float alpha,
const gsl_vector_complex_float * X,
const gsl_vector_complex_float * Y,
gsl_matrix_complex_float * A);
int gsl_blas_cher (CBLAS_UPLO_t Uplo,
float alpha,
const gsl_vector_complex_float * X,
gsl_matrix_complex_float * A);
int gsl_blas_cher2 (CBLAS_UPLO_t Uplo,
const gsl_complex_float alpha,
const gsl_vector_complex_float * X,
const gsl_vector_complex_float * Y,
gsl_matrix_complex_float * A);
int gsl_blas_zhemv (CBLAS_UPLO_t Uplo,
const gsl_complex alpha,
const gsl_matrix_complex * A,
const gsl_vector_complex * X,
const gsl_complex beta,
gsl_vector_complex * Y);
int gsl_blas_zgeru (const gsl_complex alpha,
const gsl_vector_complex * X,
const gsl_vector_complex * Y,
gsl_matrix_complex * A);
int gsl_blas_zgerc (const gsl_complex alpha,
const gsl_vector_complex * X,
const gsl_vector_complex * Y,
gsl_matrix_complex * A);
int gsl_blas_zher (CBLAS_UPLO_t Uplo,
double alpha,
const gsl_vector_complex * X,
gsl_matrix_complex * A);
int gsl_blas_zher2 (CBLAS_UPLO_t Uplo,
const gsl_complex alpha,
const gsl_vector_complex * X,
const gsl_vector_complex * Y,
gsl_matrix_complex * A);
/*
* ===========================================================================
* Prototypes for level 3 BLAS
* ===========================================================================
*/
/*
* Routines with standard 4 prefixes (S, D, C, Z)
*/
int gsl_blas_sgemm (CBLAS_TRANSPOSE_t TransA,
CBLAS_TRANSPOSE_t TransB,
float alpha,
const gsl_matrix_float * A,
const gsl_matrix_float * B,
float beta,
gsl_matrix_float * C);
int gsl_blas_ssymm (CBLAS_SIDE_t Side, CBLAS_UPLO_t Uplo,
float alpha,
const gsl_matrix_float * A,
const gsl_matrix_float * B,
float beta,
gsl_matrix_float * C);
int gsl_blas_ssyrk (CBLAS_UPLO_t Uplo, CBLAS_TRANSPOSE_t Trans,
float alpha,
const gsl_matrix_float * A,
float beta,
gsl_matrix_float * C);
int gsl_blas_ssyr2k (CBLAS_UPLO_t Uplo, CBLAS_TRANSPOSE_t Trans,
float alpha,
const gsl_matrix_float * A,
const gsl_matrix_float * B,
float beta,
gsl_matrix_float * C);
int gsl_blas_strmm (CBLAS_SIDE_t Side,
CBLAS_UPLO_t Uplo, CBLAS_TRANSPOSE_t TransA,
CBLAS_DIAG_t Diag,
float alpha,
const gsl_matrix_float * A,
gsl_matrix_float * B);
int gsl_blas_strsm (CBLAS_SIDE_t Side,
CBLAS_UPLO_t Uplo, CBLAS_TRANSPOSE_t TransA,
CBLAS_DIAG_t Diag,
float alpha,
const gsl_matrix_float * A,
gsl_matrix_float * B);
int gsl_blas_dgemm (CBLAS_TRANSPOSE_t TransA,
CBLAS_TRANSPOSE_t TransB,
double alpha,
const gsl_matrix * A,
const gsl_matrix * B,
double beta,
gsl_matrix * C);
int gsl_blas_dsymm (CBLAS_SIDE_t Side,
CBLAS_UPLO_t Uplo,
double alpha,
const gsl_matrix * A,
const gsl_matrix * B,
double beta,
gsl_matrix * C);
int gsl_blas_dsyrk (CBLAS_UPLO_t Uplo,
CBLAS_TRANSPOSE_t Trans,
double alpha,
const gsl_matrix * A,
double beta,
gsl_matrix * C);
int gsl_blas_dsyr2k (CBLAS_UPLO_t Uplo,
CBLAS_TRANSPOSE_t Trans,
double alpha,
const gsl_matrix * A,
const gsl_matrix * B,
double beta,
gsl_matrix * C);
int gsl_blas_dtrmm (CBLAS_SIDE_t Side,
CBLAS_UPLO_t Uplo, CBLAS_TRANSPOSE_t TransA,
CBLAS_DIAG_t Diag,
double alpha,
const gsl_matrix * A,
gsl_matrix * B);
int gsl_blas_dtrsm (CBLAS_SIDE_t Side,
CBLAS_UPLO_t Uplo, CBLAS_TRANSPOSE_t TransA,
CBLAS_DIAG_t Diag,
double alpha,
const gsl_matrix * A,
gsl_matrix * B);
int gsl_blas_cgemm (CBLAS_TRANSPOSE_t TransA,
CBLAS_TRANSPOSE_t TransB,
const gsl_complex_float alpha,
const gsl_matrix_complex_float * A,
const gsl_matrix_complex_float * B,
const gsl_complex_float beta,
gsl_matrix_complex_float * C);
int gsl_blas_csymm (CBLAS_SIDE_t Side,
CBLAS_UPLO_t Uplo,
const gsl_complex_float alpha,
const gsl_matrix_complex_float * A,
const gsl_matrix_complex_float * B,
const gsl_complex_float beta,
gsl_matrix_complex_float * C);
int gsl_blas_csyrk (CBLAS_UPLO_t Uplo,
CBLAS_TRANSPOSE_t Trans,
const gsl_complex_float alpha,
const gsl_matrix_complex_float * A,
const gsl_complex_float beta,
gsl_matrix_complex_float * C);
int gsl_blas_csyr2k (CBLAS_UPLO_t Uplo,
CBLAS_TRANSPOSE_t Trans,
const gsl_complex_float alpha,
const gsl_matrix_complex_float * A,
const gsl_matrix_complex_float * B,
const gsl_complex_float beta,
gsl_matrix_complex_float * C);
int gsl_blas_ctrmm (CBLAS_SIDE_t Side,
CBLAS_UPLO_t Uplo, CBLAS_TRANSPOSE_t TransA,
CBLAS_DIAG_t Diag,
const gsl_complex_float alpha,
const gsl_matrix_complex_float * A,
gsl_matrix_complex_float * B);
int gsl_blas_ctrsm (CBLAS_SIDE_t Side,
CBLAS_UPLO_t Uplo, CBLAS_TRANSPOSE_t TransA,
CBLAS_DIAG_t Diag,
const gsl_complex_float alpha,
const gsl_matrix_complex_float * A,
gsl_matrix_complex_float * B);
int gsl_blas_zgemm (CBLAS_TRANSPOSE_t TransA,
CBLAS_TRANSPOSE_t TransB,
const gsl_complex alpha,
const gsl_matrix_complex * A,
const gsl_matrix_complex * B,
const gsl_complex beta,
gsl_matrix_complex * C);
int gsl_blas_zsymm (CBLAS_SIDE_t Side,
CBLAS_UPLO_t Uplo,
const gsl_complex alpha,
const gsl_matrix_complex * A,
const gsl_matrix_complex * B,
const gsl_complex beta,
gsl_matrix_complex * C);
int gsl_blas_zsyrk (CBLAS_UPLO_t Uplo,
CBLAS_TRANSPOSE_t Trans,
const gsl_complex alpha,
const gsl_matrix_complex * A,
const gsl_complex beta,
gsl_matrix_complex * C);
int gsl_blas_zsyr2k (CBLAS_UPLO_t Uplo,
CBLAS_TRANSPOSE_t Trans,
const gsl_complex alpha,
const gsl_matrix_complex * A,
const gsl_matrix_complex * B,
const gsl_complex beta,
gsl_matrix_complex *C);
int gsl_blas_ztrmm (CBLAS_SIDE_t Side,
CBLAS_UPLO_t Uplo, CBLAS_TRANSPOSE_t TransA,
CBLAS_DIAG_t Diag,
const gsl_complex alpha,
const gsl_matrix_complex * A,
gsl_matrix_complex * B);
int gsl_blas_ztrsm (CBLAS_SIDE_t Side,
CBLAS_UPLO_t Uplo, CBLAS_TRANSPOSE_t TransA,
CBLAS_DIAG_t Diag,
const gsl_complex alpha,
const gsl_matrix_complex * A,
gsl_matrix_complex * B);
/*
* Routines with prefixes C and Z only
*/
int gsl_blas_chemm (CBLAS_SIDE_t Side,
CBLAS_UPLO_t Uplo,
const gsl_complex_float alpha,
const gsl_matrix_complex_float * A,
const gsl_matrix_complex_float * B,
const gsl_complex_float beta,
gsl_matrix_complex_float * C);
int gsl_blas_cherk (CBLAS_UPLO_t Uplo,
CBLAS_TRANSPOSE_t Trans,
float alpha,
const gsl_matrix_complex_float * A,
float beta,
gsl_matrix_complex_float * C);
int gsl_blas_cher2k (CBLAS_UPLO_t Uplo,
CBLAS_TRANSPOSE_t Trans,
const gsl_complex_float alpha,
const gsl_matrix_complex_float * A,
const gsl_matrix_complex_float * B,
float beta,
gsl_matrix_complex_float * C);
int gsl_blas_zhemm (CBLAS_SIDE_t Side,
CBLAS_UPLO_t Uplo,
const gsl_complex alpha,
const gsl_matrix_complex * A,
const gsl_matrix_complex * B,
const gsl_complex beta,
gsl_matrix_complex * C);
int gsl_blas_zherk (CBLAS_UPLO_t Uplo,
CBLAS_TRANSPOSE_t Trans,
double alpha,
const gsl_matrix_complex * A,
double beta,
gsl_matrix_complex * C);
int gsl_blas_zher2k (CBLAS_UPLO_t Uplo,
CBLAS_TRANSPOSE_t Trans,
const gsl_complex alpha,
const gsl_matrix_complex * A,
const gsl_matrix_complex * B,
double beta,
gsl_matrix_complex * C);
__END_DECLS
#endif /* __GSL_BLAS_H__ */
| {
"alphanum_fraction": 0.5298681148,
"avg_line_length": 36.3399668325,
"ext": "h",
"hexsha": "82ecd674edf26adf4fa7abe7374e155d5dc224a3",
"lang": "C",
"max_forks_count": 14,
"max_forks_repo_forks_event_max_datetime": "2021-06-10T03:09:53.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-04-29T20:31:00.000Z",
"max_forks_repo_head_hexsha": "c0d957265608b15f216ece67363c827d01122102",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "pvnuffel/test_repos",
"max_forks_repo_path": "gsl_subset/blas/gsl_blas.h",
"max_issues_count": 2,
"max_issues_repo_head_hexsha": "c0d957265608b15f216ece67363c827d01122102",
"max_issues_repo_issues_event_max_datetime": "2020-07-20T16:32:02.000Z",
"max_issues_repo_issues_event_min_datetime": "2017-11-07T05:42:56.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "pvnuffel/test_repos",
"max_issues_repo_path": "gsl_subset/blas/gsl_blas.h",
"max_line_length": 83,
"max_stars_count": 30,
"max_stars_repo_head_hexsha": "c0d957265608b15f216ece67363c827d01122102",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "pvnuffel/test_repos",
"max_stars_repo_path": "gsl_subset/blas/gsl_blas.h",
"max_stars_repo_stars_event_max_datetime": "2022-03-21T02:07:41.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-04-29T05:13:02.000Z",
"num_tokens": 4679,
"size": 21913
} |
/*
*/
#include "kern.h"
#include <cblas.h>
#include <err.h>
#include <fcntl.h>
#include <float.h>
#include <math.h>
#include <stdbool.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <time.h>
#include <unistd.h>
#ifdef WITH_THREADS
#include <omp.h>
#define MP_LOOP() PRAGMA(omp for simd)
#else
#define MP_LOOP()
#endif
#define PRAGMA(X) _Pragma(#X)
/*
* Transform the input vector to the output stream.
* The m x n matrix is stored with column arrays.
*
* y[k * n + j] = x[k * m + i] * w[m * j + i]
* y(l, n) = x(l,m) * w(m, n)
*
*/
void trans(uint32_t batch_len, uint32_t m, uint32_t n, const float *w,
const float *x, float *y) {
cblas_sgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, batch_len, n, m,
1.0f, x, batch_len, w, m, 0.0f, y, batch_len);
}
/*
* Original:
* w(m,n) -= N * x(l,m)^T * dy(l,n)
* w[m * $j + i] -= N * x[m * $k + i] * dy[n * k + $j]
*
* Optimized:
* w(m,n)^T -= N * dy(l,n)^T * x(l,m)
* w[m * j + $i] -= N * dy[n * $k + j] * x[m * k + $i]
*/
void train_sgd(uint32_t batch_len, uint32_t m, uint32_t n,
const float x[m * batch_len], const float y[n * batch_len],
float rate, float w[m * n]) {
cblas_sgemm(CblasRowMajor, CblasTrans, CblasNoTrans, n, m, batch_len, -rate,
y, n, x, m, 1.0f, w, m);
}
/*
* adam optimizer for the weight matrix
*/
float train_adam(uint32_t batch_len, uint32_t m, uint32_t n,
const float x[restrict m * batch_len],
const float dy[restrict const n * batch_len], float counter,
float N, float beta1, float beta2, float epsilon,
float w[m * n], float mom[n * m], float veloc[n * m]) {
float *restrict wr;
float *restrict mr;
float *restrict vr;
const float *restrict xr;
float dr;
uint32_t k, i;
for (uint32_t j = 0; j < n; j++) {
for (k = 0, wr = &w[m * j], vr = &veloc[j * m], mr = &mom[j * m];
k < batch_len; k++) {
for (i = 0, xr = &x[k * m], dr = dy[k * n + j]; i < m; i++) {
const float g = dr * xr[i];
mr[i] = beta1 * mr[i] + ((1 - beta1) * g);
const float mr_hat = mr[i] / (1 - powf(beta1, counter));
vr[i] = beta2 * vr[i] + ((1 - beta2) * (powf(g, 2)));
const float vr_hat = vr[i] / (1 - powf(beta2, counter));
wr[i] -= N * mr_hat / (sqrtf(vr_hat + epsilon));
}
}
}
return counter + 1.0f;
}
/*
* Original:
* dx(l,m) = dy(l,n) * w(m,n)^T
* dx[m * k + $i] = dy[n * k + $j] * w[m * $j + i]
*/
void loss(uint32_t batch_len, uint32_t m, uint32_t n, const float *w,
const float *dy, float *dx) {
cblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, batch_len, m, n, 1.0f,
dy, n, w, m, .0f, dx, m);
}
/*
* Calculate the difference between two vectors of size 'size'.
*
* size: The size of the vectors.
* vec1: The first vector
* vec2: The second vector
*
* Return the mean difference
*/
double vec_delta(uint32_t size, const float *vec1, const float *vec2,
float *deltas) {
double error = 0.0;
for (size_t i = 0; i < size; i++) {
deltas[i] = vec1[i] - vec2[i];
error += pow(deltas[i], 2.0);
}
return error / (float)size;
}
bool vec_is_equal_f32(uint32_t n, const float a[n], const float b[n],
float epsilon) {
for (uint32_t i = 0; i < n; i++) {
if (fabsf(a[i] - b[i]) >= epsilon) return false;
// better:
// if(fabs(a[ii]-b[ii]) < 1e-10 * (fabs(a[ii]) + fabs(b[ii]))) {
// with the appropriate tolerance
}
return true;
}
/*
* In each iteration of the while loop two normal random variables are
* generated. On the first call of the function, two normal random variables are
* generated.
* On the after call, the second generated number will be returned.
*/
float rand_normal(float mu, float sigma) {
float U1, U2, W, mult;
static float X1, X2;
static bool call = false;
if (call == true) {
call = !call;
return mu + sigma * X2;
}
do {
U1 = -1 + ((float)random() / (float)(RAND_MAX)) * 2;
U2 = -1 + ((float)random() / (float)(RAND_MAX)) * 2;
W = powf(U1, 2) + powf(U2, 2);
} while (W >= 1 || W == 0);
mult = sqrtf((-2 * logf(W)) / W);
X1 = U1 * mult;
X2 = U2 * mult;
call = !call;
return (mu + sigma * X1);
}
void weights_norm_init(uint32_t in_size, uint32_t out_size, float *weights) {
srandom(time(NULL));
for (unsigned long long i = 0; i < (in_size * out_size); i++) {
weights[i] = rand_normal(0.0f, sqrtf(2.0f / in_size));
}
}
uint32_t argmax(uint32_t len, const float x[len], float *max) {
*max = x[0];
uint32_t max_pos = 0;
for (uint32_t i = 0; i < len; i++) {
if (x[i] > *max) {
*max = x[i];
max_pos = i;
}
}
return max_pos;
}
void softmax(uint32_t len, const float x[len], float xs[len]) {
float max;
argmax(len, x, &max);
float sum = .0f;
for (uint32_t i = 0; i < len; i++) {
xs[i] = expf(x[i] - max);
sum += xs[i];
}
for (uint32_t i = 0; i < len; i++) {
xs[i] = xs[i] / sum;
}
}
// List of activation functions
// Convention: derived activation functions are prefixed with label 'derived'
/*
* The sigmoid function
*/
float fsigmoid(float x) { return 1.0f / (1.0f + expf(-x)); }
/*
* The derived of the sigmoid function
*/
float derived_fsigmoid(float y) { return (y * (1.0f - y)); }
float frelu(float x) { return (float)(x > .0) * x; }
float derived_frelu(float x) { return (float)(x > .0); }
float ftanh(float x) { return tanhf(x); }
float derived_ftanh(float x) { return 1.0f - powf(ftanh(x), 2.0f); }
static void vec_func_f32(uint32_t len, float result[len], float (*f)(float)) {
for (uint32_t d = 0; d < len; d++) {
result[d] = f(result[d]);
}
}
void sigmoid(uint32_t len, float *result) {
vec_func_f32(len, result, fsigmoid);
}
void relu(uint32_t len, float *result) { vec_func_f32(len, result, frelu); }
void tanhg(uint32_t len, float *result) { vec_func_f32(len, result, ftanh); }
static void vec_derived_f32(uint32_t len, const float result[len],
float delta[len], float (*f)(float)) {
for (uint32_t d = 0; d < len; d++) {
delta[d] = f(result[d]) * delta[d];
}
}
void relu_derived(uint32_t len, const float *result, float *delta) {
vec_derived_f32(len, result, delta, derived_frelu);
}
void tanhg_derived(uint32_t len, const float *result, float *delta) {
vec_derived_f32(len, result, delta, derived_ftanh);
}
void sigmoid_derived(uint32_t len, const float *result, float *delta) {
vec_derived_f32(len, result, delta, derived_fsigmoid);
}
/*
* Allocate memory for a float matrix.
*/
float *matrix_alloc(uint32_t m, uint32_t n) {
return reallocarray(NULL, m * n, sizeof(float));
}
void matrix_init(uint32_t m, uint32_t n, float matrix[m * n]) {
for (uint32_t i = 0; i < m * n; i++) {
matrix[i] = 0.0f;
}
}
float *weights_create_or_load(const char *filename, uint32_t input_len,
uint32_t output_len) {
float *weight;
if (filename == NULL) {
weight = matrix_alloc(input_len, output_len);
weights_norm_init(input_len, output_len, weight);
} else {
struct stat statbuf;
size_t size_expected = input_len * output_len * sizeof(float);
int fd = open(filename, O_CREAT | O_RDWR, S_IRUSR | S_IWUSR);
if (fd < 0) {
/* failure */
err(EXIT_FAILURE, "open file '%s'", filename);
}
/* find size of input file */
if (fstat(fd, &statbuf) < 0) {
err(EXIT_FAILURE, "fstat error");
} else if (statbuf.st_size == 0) {
// file does not exist before - create it with the required size
if (ftruncate(fd, size_expected)) {
err(EXIT_FAILURE, "file truncate");
}
weight = mmap(0, size_expected, PROT_WRITE, MAP_SHARED, fd, 0);
close(fd);
weights_norm_init(input_len, output_len, weight);
return weight;
} else if (statbuf.st_size > 0 &&
(unsigned long)statbuf.st_size < size_expected) {
errx(EXIT_FAILURE, "invalid data size. Expected: %lu; given: %ld",
size_expected, statbuf.st_size);
}
weight = mmap(0, size_expected, PROT_WRITE, MAP_SHARED, fd, 0);
close(fd);
}
return weight;
}
static inline float fbernoulli(float p /* must between [0,1] */) {
return (float)(p < (((float)random() / (float)(RAND_MAX))));
}
void dropout(uint32_t len, const float vec[len], float p, float result[len]) {
for (uint32_t i = 0; i < len; i++) {
result[i] = vec[i] * fbernoulli(p);
}
}
| {
"alphanum_fraction": 0.5558634449,
"avg_line_length": 29.6776315789,
"ext": "c",
"hexsha": "78e08ebffbfab164893f12055a5b61833ab3e916",
"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": "520f674d2eb780e45dd1cd7beddf0407625afa0c",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "geisten/gstnn",
"max_forks_repo_path": "kern.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "520f674d2eb780e45dd1cd7beddf0407625afa0c",
"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": "geisten/gstnn",
"max_issues_repo_path": "kern.c",
"max_line_length": 81,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "520f674d2eb780e45dd1cd7beddf0407625afa0c",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "geisten/gstnn",
"max_stars_repo_path": "kern.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 2733,
"size": 9022
} |
#ifndef DART_CPP14_SHIM_H
#define DART_CPP14_SHIM_H
// Figure out what compiler we have.
#if defined(__clang__)
#define DART_USING_CLANG 1
#elif defined(__GNUC__) || defined(__GNUG__)
#define DART_USING_GCC 1
#elif defined(_MSC_VER)
#define DART_USING_MSVC 1
#endif
#ifdef DART_USING_MSVC
#define _CRT_SECURE_NO_WARNINGS 1
#endif
#include <ctime>
#include <cstring>
#if DART_USING_CLANG && __clang_major__ >= 5 && __clang_major__ <= 7
// Side-step a disagreement between clang (5/6) and GNU std::variant.
#define DART_USE_MPARK_VARIANT 1
#elif defined(__APPLE__)
// Side-step AppleClang misreporting compiler capabilities on macos 10.13 and below.
#include <availability.h>
#ifndef __MAC_10_14
#define DART_USE_MPARK_VARIANT 1
#endif
#endif
// MSVC doesn't have a signed size type, obviously
#if DART_USING_MSVC
#include <BaseTsd.h>
using ssize_t = SSIZE_T;
#endif
// Make sure we have a fallback for compilers that don't support attributes at all.
#ifndef __has_cpp_attribute
#define __has_cpp_attribute(name) 0
#endif
// Figure out how to declare things [[nodiscard]]
#if __has_cpp_attribute(gnu::warn_unused_result)
#define DART_NODISCARD [[gnu::warn_unused_result]]
#elif __has_cpp_attribute(nodiscard)
#define DART_NODISCARD [[nodiscard]]
#else
#define DART_NODISCARD
#endif
#define DART_STRINGIFY_IMPL(x) #x
#define DART_STRINGIFY(x) DART_STRINGIFY_IMPL(x)
#if DART_USING_MSVC
#define DART_UNLIKELY(x) !!(x)
#else
#define DART_UNLIKELY(x) __builtin_expect(!!(x), 0)
#endif
#ifndef NDEBUG
#if DART_USING_MSVC
#include <io.h>
#define DART_WRITE(fd, ptr, bytes) _write(fd, ptr, static_cast<unsigned int>(bytes))
#define DART_STDERR_FILENO _fileno(stderr)
#else
#include <unistd.h>
#define DART_WRITE(fd, ptr, bytes) write(fd, ptr, bytes)
#define DART_STDERR_FILENO STDERR_FILENO
#endif
/**
* @brief
* Macro customizes functionality usually provided by assert().
*
* @details
* Not strictly necessary, but tries to provide a bit more context and
* information as to why I just murdered the user's program (in production, no doubt).
*
* @remarks
* Don't actually know if Doxygen lets you document macros, guess we'll see.
*/
#define DART_ASSERT(cond) \
if (DART_UNLIKELY(!(cond))) { \
auto& msg = "dart::packet has detected fatal memory corruption and cannot continue execution.\n" \
"\"" DART_STRINGIFY(cond) "\" violated.\nSee " __FILE__ ":" DART_STRINGIFY(__LINE__) "\n"; \
int errfd = DART_STDERR_FILENO; \
ssize_t spins {0}, written {0}, total {sizeof(msg)}; \
do { \
ssize_t ret = DART_WRITE(errfd, msg + written, total - written); \
if (ret >= 0) written += ret; \
} while (written != total && spins++ < 16); \
std::abort(); \
}
#else
#define DART_ASSERT(cond)
#endif
// Conditionally include different implementations of different data structures
// depending on what standard we have access to.
#if __cplusplus >= 201703L && !DART_USE_MPARK_VARIANT
#define DART_HAS_CPP17 1
#include <variant>
#include <optional>
#include <string_view>
#else
#define DART_HAS_CPP14 1
#include "support/variant.h"
#include "support/optional.h"
#include "support/string_view.h"
#endif
// We support two versions of GSL, but unfortunately they don't agree about
// the template signature of gsl::span (why would we expect two production-ready
// implementations of the same exact specification to agree about something like
// that), so we have to declare some of our partial specializations differently
// depending on what we included.
#include <gsl/gsl>
#ifndef gsl_lite_VERSION
#define DART_USING_GSL
#else
#define DART_USING_GSL_LITE
#endif
// Conditionally pull each of those types into our namespace.
namespace dart {
namespace shim {
#if DART_USING_MSVC
inline int aligned_alloc(void** memptr, size_t alignment, size_t size) {
void* ret = _aligned_malloc(size, alignment);
if (ret) {
*memptr = ret;
return 0;
} else {
return -1;
}
}
inline void aligned_free(void* ptr) {
_aligned_free(ptr);
}
inline void gmtime(time_t const* src, std::tm* out) {
gmtime_s(out, src);
}
inline time_t timegm(std::tm* src) {
return _mkgmtime(src);
}
#else
inline int aligned_alloc(void** memptr, size_t alignment, size_t size) {
return posix_memalign(memptr, alignment, size);
}
inline void aligned_free(void* ptr) {
free(ptr);
}
inline void gmtime(time_t const* src, std::tm* out) {
gmtime_r(src, out);
}
inline time_t timegm(std::tm* src) {
return ::timegm(src);
}
#endif
#ifdef DART_HAS_CPP17
// Pull in names of types.
using std::optional;
using std::nullopt_t;
using std::variant;
using std::monostate;
using std::string_view;
using std::basic_string_view;
// Pull in constants.
static inline constexpr auto nullopt = std::nullopt;
// Pull in non-member helpers.
using std::get;
using std::visit;
using std::get_if;
using std::launder;
using std::holds_alternative;
using std::variant_alternative;
using std::variant_alternative_t;
// Define a way to compose lambdas.
template <class... Ls>
struct compose : Ls... {
using Ls::operator ()...;
};
template <class... Ls>
compose(Ls...) -> compose<Ls...>;
template <class... Ls>
auto compose_together(Ls&&... lambdas) {
return compose {std::forward<Ls>(lambdas)...};
}
#else
// Pull in names of types.
using dart::optional;
using dart::nullopt_t;
using dart::string_view;
using dart::basic_string_view;
using mpark::variant;
using mpark::monostate;
// Pull in non-member helpers.
using mpark::get;
using mpark::visit;
using mpark::get_if;
using mpark::holds_alternative;
using mpark::variant_alternative;
using mpark::variant_alternative_t;
// Pull in constants.
static constexpr auto nullopt = dart::nullopt;
// Define a way to compose lambdas.
template <class... Ls>
struct compose;
template <class L, class... Ls>
struct compose<L, Ls...> : L, compose<Ls...> {
compose(L l, Ls... the_rest) : L(std::move(l)), compose<Ls...>(std::move(the_rest)...) {}
using L::operator ();
using compose<Ls...>::operator ();
};
template <class L>
struct compose<L> : L {
compose(L l) : L(std::move(l)) {}
using L::operator ();
};
template <class... Ls>
auto compose_together(Ls&&... lambdas) {
return compose<std::decay_t<Ls>...> {std::forward<Ls>(lambdas)...};
}
#endif
}
}
#endif
| {
"alphanum_fraction": 0.6208550288,
"avg_line_length": 29.3092369478,
"ext": "h",
"hexsha": "74236f85a8436bd02b1ec963bf21586dfe81907b",
"lang": "C",
"max_forks_count": 10,
"max_forks_repo_forks_event_max_datetime": "2020-06-11T11:05:17.000Z",
"max_forks_repo_forks_event_min_datetime": "2019-05-11T08:05:10.000Z",
"max_forks_repo_head_hexsha": "987b01aa1f11455ac6aaf89f8e60825e92e6ec25",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "Cfretz244/libdart",
"max_forks_repo_path": "include/dart/shim.h",
"max_issues_count": 10,
"max_issues_repo_head_hexsha": "987b01aa1f11455ac6aaf89f8e60825e92e6ec25",
"max_issues_repo_issues_event_max_datetime": "2020-03-29T03:25:16.000Z",
"max_issues_repo_issues_event_min_datetime": "2019-05-09T22:37:27.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "Cfretz244/libdart",
"max_issues_repo_path": "include/dart/shim.h",
"max_line_length": 111,
"max_stars_count": 85,
"max_stars_repo_head_hexsha": "987b01aa1f11455ac6aaf89f8e60825e92e6ec25",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "Cfretz244/libdart",
"max_stars_repo_path": "include/dart/shim.h",
"max_stars_repo_stars_event_max_datetime": "2021-02-07T16:31:55.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-05-09T19:12:25.000Z",
"num_tokens": 1792,
"size": 7298
} |
/* combination/test.c
* based on permutation/test.c by Brian Gough
*
* Copyright (C) 2001 Szymon Jaroszewicz
*
* 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 <stdio.h>
#include <math.h>
#include <gsl/gsl_combination.h>
#include <gsl/gsl_test.h>
#include <gsl/gsl_ieee_utils.h>
size_t c63[20][3] = {
{ 0, 1, 2 }, { 0, 1, 3 }, { 0, 1, 4 }, { 0, 1, 5 },
{ 0, 2, 3 }, { 0, 2, 4 }, { 0, 2, 5 }, { 0, 3, 4 },
{ 0, 3, 5 }, { 0, 4, 5 }, { 1, 2, 3 }, { 1, 2, 4 },
{ 1, 2, 5 }, { 1, 3, 4 }, { 1, 3, 5 }, { 1, 4, 5 },
{ 2, 3, 4 }, { 2, 3, 5 }, { 2, 4, 5 }, { 3, 4, 5 }
} ;
void my_error_handler (const char *reason, const char *file, int line, int err);
int
main (void)
{
size_t i, j;
int status = 0, s;
gsl_combination * c ;
gsl_ieee_env_setup ();
c = gsl_combination_alloc (6,3);
/* Test combinations in forward order */
gsl_combination_init_first (c);
i = 0;
do
{
if ( i >= 20 )
{
status = 1;
break;
}
for (j = 0; j < 3; j++)
{
status |= (c->data[j] != c63[i][j]);
}
{
int s1 = gsl_combination_valid (c);
gsl_test (s1, "gsl_combination_valid (%u)", i);
}
i++;
}
while (gsl_combination_next(c) == GSL_SUCCESS);
gsl_test(status, "gsl_combination_next, 6 choose 3 combination, 20 steps");
gsl_combination_next(c);
gsl_combination_next(c);
gsl_combination_next(c);
for (j = 0; j < 3; j++)
{
status |= (c->data[j] != c63[19][j]);
}
gsl_test(status, "gsl_combination_next on the last combination");
{
int s1 = gsl_combination_valid (c);
gsl_test (s1, "gsl_combination_valid on the last combination");
}
{
gsl_combination * d = gsl_combination_alloc (6,3);
gsl_combination_memcpy (d, c);
status = 0;
for (j = 0; j < 3; j++)
{
status |= (d->data[j] != c->data[j]);
}
gsl_test (status, "gsl_combination_memcpy, 6 choose 3 combination");
gsl_combination_free(d);
}
/* Now test combinations in reverse order */
gsl_combination_init_last (c);
i = 20;
do
{
if ( i == 0 )
{
status = 1;
break;
}
i--;
for (j = 0; j < 3; j++)
{
status |= (c->data[j] != c63[i][j]);
}
{
int s1 = gsl_combination_valid (c);
gsl_test (s1, "gsl_combination_valid (%u)", i);
}
}
while (gsl_combination_prev(c) == GSL_SUCCESS);
gsl_test(status, "gsl_combination_prev, 6 choose 3 combination, 20 steps");
gsl_combination_prev(c);
gsl_combination_prev(c);
gsl_combination_prev(c);
for (j = 0; j < 3; j++)
{
status |= (c->data[j] != c63[0][j]);
}
gsl_test(status, "gsl_combination_prev on the first combination");
{
int s1 = gsl_combination_valid (c);
gsl_test (s1, "gsl_combination_valid on the first combination");
}
{
gsl_combination * d = gsl_combination_alloc (6,3);
gsl_combination_memcpy (d, c);
status = 0;
for (j = 0; j < 3; j++)
{
status |= (d->data[j] != c->data[j]);
}
gsl_test (status, "gsl_combination_memcpy, 6 choose 3 combination");
gsl_combination_free(d);
}
gsl_combination_free (c);
c = gsl_combination_calloc(7, 0);
/* should return GSL_FAILURE every time */
status |= (gsl_combination_next(c) != GSL_FAILURE);
status |= (gsl_combination_next(c) != GSL_FAILURE);
status |= (gsl_combination_prev(c) != GSL_FAILURE);
status |= (gsl_combination_prev(c) != GSL_FAILURE);
gsl_test(status, "gsl_combination 7 choose 0");
gsl_combination_free (c);
c = gsl_combination_calloc(7, 7);
/* should return GSL_FAILURE every time */
for(j = 0; j < 7; j++)
{
status |= (gsl_combination_get(c, j) != j);
}
status |= (gsl_combination_next(c) != GSL_FAILURE);
for(j = 0; j < 7; j++)
{
status |= (gsl_combination_get(c, j) != j);
}
status |= (gsl_combination_next(c) != GSL_FAILURE);
for(j = 0; j < 7; j++)
{
status |= (gsl_combination_get(c, j) != j);
}
status |= (gsl_combination_prev(c) != GSL_FAILURE);
for(j = 0; j < 7; j++)
{
status |= (gsl_combination_get(c, j) != j);
}
status |= (gsl_combination_prev(c) != GSL_FAILURE);
for(j = 0; j < 7; j++)
{
status |= (gsl_combination_get(c, j) != j);
}
gsl_test(status, "gsl_combination 7 choose 7");
gsl_combination_free (c);
c = gsl_combination_calloc(6, 3);
gsl_set_error_handler (&my_error_handler);
c->data[0] = 1;
c->data[1] = 1;
c->data[2] = 2;
s = gsl_combination_valid (c);
gsl_test (!s, "gsl_combination_valid on an invalid combination (1,1,2)");
c->data[0] = 2;
c->data[1] = 1;
c->data[2] = 0;
s = gsl_combination_valid (c);
gsl_test (!s, "gsl_combination_valid on an invalid combination (2,1,0)");
c->data[0] = 1;
c->data[1] = 2;
c->data[2] = 0;
s = gsl_combination_valid (c);
gsl_test (!s, "gsl_combination_valid on an invalid combination (1,2,0)");
{
gsl_combination * d = gsl_combination_alloc (6,4);
int s = gsl_combination_memcpy (d, c);
gsl_test (!s, "gsl_combination_memcpy, (6,4) vs (6,3)");
gsl_combination_free(d);
}
{
gsl_combination * d = gsl_combination_alloc (7,3);
int s = gsl_combination_memcpy (d, c);
gsl_test (!s, "gsl_combination_memcpy, (7,3) vs (6,3)");
gsl_combination_free(d);
}
{
gsl_combination * d = gsl_combination_alloc (7,2);
int s = gsl_combination_memcpy (d, c);
gsl_test (!s, "gsl_combination_memcpy, (7,2) vs (6,3)");
gsl_combination_free(d);
}
gsl_combination_free (c);
exit (gsl_test_summary());
}
void
my_error_handler (const char *reason, const char *file, int line, int err)
{
if (0) printf ("(caught [%s:%d: %s (%d)])\n", file, line, reason, err) ;
}
| {
"alphanum_fraction": 0.5953146532,
"avg_line_length": 24.927480916,
"ext": "c",
"hexsha": "0e0a795d8a69289532ac370573f69feecc1cca23",
"lang": "C",
"max_forks_count": 224,
"max_forks_repo_forks_event_max_datetime": "2022-03-30T00:57:48.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-11-12T21:17:03.000Z",
"max_forks_repo_head_hexsha": "70dc728926a835ba049ddd3f4627ef08db7c95a0",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "utdsimmons/ohpc",
"max_forks_repo_path": "tests/libs/gsl/tests/combination/test.c",
"max_issues_count": 1096,
"max_issues_repo_head_hexsha": "70dc728926a835ba049ddd3f4627ef08db7c95a0",
"max_issues_repo_issues_event_max_datetime": "2022-03-31T21:48:41.000Z",
"max_issues_repo_issues_event_min_datetime": "2015-11-12T09:08:22.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "utdsimmons/ohpc",
"max_issues_repo_path": "tests/libs/gsl/tests/combination/test.c",
"max_line_length": 81,
"max_stars_count": 692,
"max_stars_repo_head_hexsha": "70dc728926a835ba049ddd3f4627ef08db7c95a0",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "utdsimmons/ohpc",
"max_stars_repo_path": "tests/libs/gsl/tests/combination/test.c",
"max_stars_repo_stars_event_max_datetime": "2022-03-30T03:45:59.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-11-12T13:56:43.000Z",
"num_tokens": 2162,
"size": 6531
} |
/* matrix/gsl_matrix_ulong.h
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Gerard Jungman, Brian Gough
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#ifndef __GSL_MATRIX_ULONG_H__
#define __GSL_MATRIX_ULONG_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_vector_ulong.h>
#include <gsl/gsl_blas_types.h>
#undef __BEGIN_DECLS
#undef __END_DECLS
#ifdef __cplusplus
# define __BEGIN_DECLS extern "C" {
# define __END_DECLS }
#else
# define __BEGIN_DECLS /* empty */
# define __END_DECLS /* empty */
#endif
__BEGIN_DECLS
typedef struct
{
size_t size1;
size_t size2;
size_t tda;
unsigned long * data;
gsl_block_ulong * block;
int owner;
} gsl_matrix_ulong;
typedef struct
{
gsl_matrix_ulong matrix;
} _gsl_matrix_ulong_view;
typedef _gsl_matrix_ulong_view gsl_matrix_ulong_view;
typedef struct
{
gsl_matrix_ulong matrix;
} _gsl_matrix_ulong_const_view;
typedef const _gsl_matrix_ulong_const_view gsl_matrix_ulong_const_view;
/* Allocation */
GSL_FUN gsl_matrix_ulong *
gsl_matrix_ulong_alloc (const size_t n1, const size_t n2);
GSL_FUN gsl_matrix_ulong *
gsl_matrix_ulong_calloc (const size_t n1, const size_t n2);
GSL_FUN gsl_matrix_ulong *
gsl_matrix_ulong_alloc_from_block (gsl_block_ulong * b,
const size_t offset,
const size_t n1,
const size_t n2,
const size_t d2);
GSL_FUN gsl_matrix_ulong *
gsl_matrix_ulong_alloc_from_matrix (gsl_matrix_ulong * m,
const size_t k1,
const size_t k2,
const size_t n1,
const size_t n2);
GSL_FUN gsl_vector_ulong *
gsl_vector_ulong_alloc_row_from_matrix (gsl_matrix_ulong * m,
const size_t i);
GSL_FUN gsl_vector_ulong *
gsl_vector_ulong_alloc_col_from_matrix (gsl_matrix_ulong * m,
const size_t j);
GSL_FUN void gsl_matrix_ulong_free (gsl_matrix_ulong * m);
/* Views */
GSL_FUN _gsl_matrix_ulong_view
gsl_matrix_ulong_submatrix (gsl_matrix_ulong * m,
const size_t i, const size_t j,
const size_t n1, const size_t n2);
GSL_FUN _gsl_vector_ulong_view
gsl_matrix_ulong_row (gsl_matrix_ulong * m, const size_t i);
GSL_FUN _gsl_vector_ulong_view
gsl_matrix_ulong_column (gsl_matrix_ulong * m, const size_t j);
GSL_FUN _gsl_vector_ulong_view
gsl_matrix_ulong_diagonal (gsl_matrix_ulong * m);
GSL_FUN _gsl_vector_ulong_view
gsl_matrix_ulong_subdiagonal (gsl_matrix_ulong * m, const size_t k);
GSL_FUN _gsl_vector_ulong_view
gsl_matrix_ulong_superdiagonal (gsl_matrix_ulong * m, const size_t k);
GSL_FUN _gsl_vector_ulong_view
gsl_matrix_ulong_subrow (gsl_matrix_ulong * m, const size_t i,
const size_t offset, const size_t n);
GSL_FUN _gsl_vector_ulong_view
gsl_matrix_ulong_subcolumn (gsl_matrix_ulong * m, const size_t j,
const size_t offset, const size_t n);
GSL_FUN _gsl_matrix_ulong_view
gsl_matrix_ulong_view_array (unsigned long * base,
const size_t n1,
const size_t n2);
GSL_FUN _gsl_matrix_ulong_view
gsl_matrix_ulong_view_array_with_tda (unsigned long * base,
const size_t n1,
const size_t n2,
const size_t tda);
GSL_FUN _gsl_matrix_ulong_view
gsl_matrix_ulong_view_vector (gsl_vector_ulong * v,
const size_t n1,
const size_t n2);
GSL_FUN _gsl_matrix_ulong_view
gsl_matrix_ulong_view_vector_with_tda (gsl_vector_ulong * v,
const size_t n1,
const size_t n2,
const size_t tda);
GSL_FUN _gsl_matrix_ulong_const_view
gsl_matrix_ulong_const_submatrix (const gsl_matrix_ulong * m,
const size_t i, const size_t j,
const size_t n1, const size_t n2);
GSL_FUN _gsl_vector_ulong_const_view
gsl_matrix_ulong_const_row (const gsl_matrix_ulong * m,
const size_t i);
GSL_FUN _gsl_vector_ulong_const_view
gsl_matrix_ulong_const_column (const gsl_matrix_ulong * m,
const size_t j);
GSL_FUN _gsl_vector_ulong_const_view
gsl_matrix_ulong_const_diagonal (const gsl_matrix_ulong * m);
GSL_FUN _gsl_vector_ulong_const_view
gsl_matrix_ulong_const_subdiagonal (const gsl_matrix_ulong * m,
const size_t k);
GSL_FUN _gsl_vector_ulong_const_view
gsl_matrix_ulong_const_superdiagonal (const gsl_matrix_ulong * m,
const size_t k);
GSL_FUN _gsl_vector_ulong_const_view
gsl_matrix_ulong_const_subrow (const gsl_matrix_ulong * m, const size_t i,
const size_t offset, const size_t n);
GSL_FUN _gsl_vector_ulong_const_view
gsl_matrix_ulong_const_subcolumn (const gsl_matrix_ulong * m, const size_t j,
const size_t offset, const size_t n);
GSL_FUN _gsl_matrix_ulong_const_view
gsl_matrix_ulong_const_view_array (const unsigned long * base,
const size_t n1,
const size_t n2);
GSL_FUN _gsl_matrix_ulong_const_view
gsl_matrix_ulong_const_view_array_with_tda (const unsigned long * base,
const size_t n1,
const size_t n2,
const size_t tda);
GSL_FUN _gsl_matrix_ulong_const_view
gsl_matrix_ulong_const_view_vector (const gsl_vector_ulong * v,
const size_t n1,
const size_t n2);
GSL_FUN _gsl_matrix_ulong_const_view
gsl_matrix_ulong_const_view_vector_with_tda (const gsl_vector_ulong * v,
const size_t n1,
const size_t n2,
const size_t tda);
/* Operations */
GSL_FUN void gsl_matrix_ulong_set_zero (gsl_matrix_ulong * m);
GSL_FUN void gsl_matrix_ulong_set_identity (gsl_matrix_ulong * m);
GSL_FUN void gsl_matrix_ulong_set_all (gsl_matrix_ulong * m, unsigned long x);
GSL_FUN int gsl_matrix_ulong_fread (FILE * stream, gsl_matrix_ulong * m) ;
GSL_FUN int gsl_matrix_ulong_fwrite (FILE * stream, const gsl_matrix_ulong * m) ;
GSL_FUN int gsl_matrix_ulong_fscanf (FILE * stream, gsl_matrix_ulong * m);
GSL_FUN int gsl_matrix_ulong_fprintf (FILE * stream, const gsl_matrix_ulong * m, const char * format);
GSL_FUN int gsl_matrix_ulong_memcpy(gsl_matrix_ulong * dest, const gsl_matrix_ulong * src);
GSL_FUN int gsl_matrix_ulong_swap(gsl_matrix_ulong * m1, gsl_matrix_ulong * m2);
GSL_FUN int gsl_matrix_ulong_tricpy(CBLAS_UPLO_t Uplo, CBLAS_DIAG_t Diag, gsl_matrix_ulong * dest, const gsl_matrix_ulong * src);
GSL_FUN int gsl_matrix_ulong_swap_rows(gsl_matrix_ulong * m, const size_t i, const size_t j);
GSL_FUN int gsl_matrix_ulong_swap_columns(gsl_matrix_ulong * m, const size_t i, const size_t j);
GSL_FUN int gsl_matrix_ulong_swap_rowcol(gsl_matrix_ulong * m, const size_t i, const size_t j);
GSL_FUN int gsl_matrix_ulong_transpose (gsl_matrix_ulong * m);
GSL_FUN int gsl_matrix_ulong_transpose_memcpy (gsl_matrix_ulong * dest, const gsl_matrix_ulong * src);
GSL_FUN int gsl_matrix_ulong_transpose_tricpy (CBLAS_UPLO_t Uplo_src, CBLAS_DIAG_t Diag, gsl_matrix_ulong * dest, const gsl_matrix_ulong * src);
GSL_FUN unsigned long gsl_matrix_ulong_max (const gsl_matrix_ulong * m);
GSL_FUN unsigned long gsl_matrix_ulong_min (const gsl_matrix_ulong * m);
GSL_FUN void gsl_matrix_ulong_minmax (const gsl_matrix_ulong * m, unsigned long * min_out, unsigned long * max_out);
GSL_FUN void gsl_matrix_ulong_max_index (const gsl_matrix_ulong * m, size_t * imax, size_t *jmax);
GSL_FUN void gsl_matrix_ulong_min_index (const gsl_matrix_ulong * m, size_t * imin, size_t *jmin);
GSL_FUN void gsl_matrix_ulong_minmax_index (const gsl_matrix_ulong * m, size_t * imin, size_t * jmin, size_t * imax, size_t * jmax);
GSL_FUN int gsl_matrix_ulong_equal (const gsl_matrix_ulong * a, const gsl_matrix_ulong * b);
GSL_FUN int gsl_matrix_ulong_isnull (const gsl_matrix_ulong * m);
GSL_FUN int gsl_matrix_ulong_ispos (const gsl_matrix_ulong * m);
GSL_FUN int gsl_matrix_ulong_isneg (const gsl_matrix_ulong * m);
GSL_FUN int gsl_matrix_ulong_isnonneg (const gsl_matrix_ulong * m);
GSL_FUN unsigned long gsl_matrix_ulong_norm1 (const gsl_matrix_ulong * m);
GSL_FUN int gsl_matrix_ulong_add (gsl_matrix_ulong * a, const gsl_matrix_ulong * b);
GSL_FUN int gsl_matrix_ulong_sub (gsl_matrix_ulong * a, const gsl_matrix_ulong * b);
GSL_FUN int gsl_matrix_ulong_mul_elements (gsl_matrix_ulong * a, const gsl_matrix_ulong * b);
GSL_FUN int gsl_matrix_ulong_div_elements (gsl_matrix_ulong * a, const gsl_matrix_ulong * b);
GSL_FUN int gsl_matrix_ulong_scale (gsl_matrix_ulong * a, const double x);
GSL_FUN int gsl_matrix_ulong_scale_rows (gsl_matrix_ulong * a, const gsl_vector_ulong * x);
GSL_FUN int gsl_matrix_ulong_scale_columns (gsl_matrix_ulong * a, const gsl_vector_ulong * x);
GSL_FUN int gsl_matrix_ulong_add_constant (gsl_matrix_ulong * a, const double x);
GSL_FUN int gsl_matrix_ulong_add_diagonal (gsl_matrix_ulong * a, const double x);
/***********************************************************************/
/* The functions below are obsolete */
/***********************************************************************/
GSL_FUN int gsl_matrix_ulong_get_row(gsl_vector_ulong * v, const gsl_matrix_ulong * m, const size_t i);
GSL_FUN int gsl_matrix_ulong_get_col(gsl_vector_ulong * v, const gsl_matrix_ulong * m, const size_t j);
GSL_FUN int gsl_matrix_ulong_set_row(gsl_matrix_ulong * m, const size_t i, const gsl_vector_ulong * v);
GSL_FUN int gsl_matrix_ulong_set_col(gsl_matrix_ulong * m, const size_t j, const gsl_vector_ulong * v);
/***********************************************************************/
/* inline functions if you are using GCC */
GSL_FUN INLINE_DECL unsigned long gsl_matrix_ulong_get(const gsl_matrix_ulong * m, const size_t i, const size_t j);
GSL_FUN INLINE_DECL void gsl_matrix_ulong_set(gsl_matrix_ulong * m, const size_t i, const size_t j, const unsigned long x);
GSL_FUN INLINE_DECL unsigned long * gsl_matrix_ulong_ptr(gsl_matrix_ulong * m, const size_t i, const size_t j);
GSL_FUN INLINE_DECL const unsigned long * gsl_matrix_ulong_const_ptr(const gsl_matrix_ulong * m, const size_t i, const size_t j);
#ifdef HAVE_INLINE
INLINE_FUN
unsigned long
gsl_matrix_ulong_get(const gsl_matrix_ulong * m, const size_t i, const size_t j)
{
#if GSL_RANGE_CHECK
if (GSL_RANGE_COND(1))
{
if (i >= m->size1)
{
GSL_ERROR_VAL("first index out of range", GSL_EINVAL, 0) ;
}
else if (j >= m->size2)
{
GSL_ERROR_VAL("second index out of range", GSL_EINVAL, 0) ;
}
}
#endif
return m->data[i * m->tda + j] ;
}
INLINE_FUN
void
gsl_matrix_ulong_set(gsl_matrix_ulong * m, const size_t i, const size_t j, const unsigned long x)
{
#if GSL_RANGE_CHECK
if (GSL_RANGE_COND(1))
{
if (i >= m->size1)
{
GSL_ERROR_VOID("first index out of range", GSL_EINVAL) ;
}
else if (j >= m->size2)
{
GSL_ERROR_VOID("second index out of range", GSL_EINVAL) ;
}
}
#endif
m->data[i * m->tda + j] = x ;
}
INLINE_FUN
unsigned long *
gsl_matrix_ulong_ptr(gsl_matrix_ulong * m, const size_t i, const size_t j)
{
#if GSL_RANGE_CHECK
if (GSL_RANGE_COND(1))
{
if (i >= m->size1)
{
GSL_ERROR_NULL("first index out of range", GSL_EINVAL) ;
}
else if (j >= m->size2)
{
GSL_ERROR_NULL("second index out of range", GSL_EINVAL) ;
}
}
#endif
return (unsigned long *) (m->data + (i * m->tda + j)) ;
}
INLINE_FUN
const unsigned long *
gsl_matrix_ulong_const_ptr(const gsl_matrix_ulong * m, const size_t i, const size_t j)
{
#if GSL_RANGE_CHECK
if (GSL_RANGE_COND(1))
{
if (i >= m->size1)
{
GSL_ERROR_NULL("first index out of range", GSL_EINVAL) ;
}
else if (j >= m->size2)
{
GSL_ERROR_NULL("second index out of range", GSL_EINVAL) ;
}
}
#endif
return (const unsigned long *) (m->data + (i * m->tda + j)) ;
}
#endif
__END_DECLS
#endif /* __GSL_MATRIX_ULONG_H__ */
| {
"alphanum_fraction": 0.6568205851,
"avg_line_length": 38.5461956522,
"ext": "h",
"hexsha": "7fd554430ac80a85d5c6a016061357f1e4c51c0c",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z",
"max_forks_repo_head_hexsha": "3baed1b5313e6c198d54a33c2c84357035d5146a",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "zzpwahaha/VimbaCamJILA",
"max_forks_repo_path": "VimbaCam/ExternLib/GSL_MSVC/gsl/gsl_matrix_ulong.h",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "3baed1b5313e6c198d54a33c2c84357035d5146a",
"max_issues_repo_issues_event_max_datetime": "2021-01-13T16:28:48.000Z",
"max_issues_repo_issues_event_min_datetime": "2021-01-11T01:08:01.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "zzpwahaha/VimbaCamJILA",
"max_issues_repo_path": "VimbaCam/ExternLib/GSL_MSVC/gsl/gsl_matrix_ulong.h",
"max_line_length": 145,
"max_stars_count": 2,
"max_stars_repo_head_hexsha": "ef4d4539a537ab49329b77648aac893d2b4ad318",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "mgreter/astrometrylib",
"max_stars_repo_path": "vendor/gsl/gsl/gsl_matrix_ulong.h",
"max_stars_repo_stars_event_max_datetime": "2021-01-09T16:18:47.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-01-09T05:48:44.000Z",
"num_tokens": 3384,
"size": 14185
} |
// @(#)root/matrix:$Id$
// Authors: Fons Rademakers, Eddy Offermann Feb 2004
/*************************************************************************
* Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
#ifndef ROOT_TMatrixTSparse
#define ROOT_TMatrixTSparse
#include "TMatrixTBase.h"
#include "TMatrixTUtils.h"
#ifdef CBLAS
#include <vecLib/vBLAS.h>
//#include <cblas.h>
#endif
//////////////////////////////////////////////////////////////////////////
// //
// TMatrixTSparse //
// //
// Template class of a general sparse matrix in the Harwell-Boeing //
// format //
// //
//////////////////////////////////////////////////////////////////////////
template<class Element> class TMatrixT;
template<class Element> class TMatrixTSparse : public TMatrixTBase<Element> {
protected:
Int_t *fRowIndex; //[fNrowIndex] row index
Int_t *fColIndex; //[fNelems] column index
Element *fElements; //[fNelems]
void Allocate(Int_t nrows,Int_t ncols,Int_t row_lwb = 0,Int_t col_lwb = 0,
Int_t init = 0,Int_t nr_nonzeros = 0);
// Elementary constructors
void AMultB (const TMatrixTSparse<Element> &a,const TMatrixTSparse<Element> &b,Int_t constr=0) {
const TMatrixTSparse<Element> bt(TMatrixTSparse::kTransposed,b); AMultBt(a,bt,constr); }
void AMultB (const TMatrixTSparse<Element> &a,const TMatrixT<Element> &b,Int_t constr=0) {
const TMatrixTSparse<Element> bsp = b;
const TMatrixTSparse<Element> bt(TMatrixTSparse::kTransposed,bsp); AMultBt(a,bt,constr); }
void AMultB (const TMatrixT<Element> &a,const TMatrixTSparse<Element> &b,Int_t constr=0) {
const TMatrixTSparse<Element> bt(TMatrixTSparse::kTransposed,b); AMultBt(a,bt,constr); }
void AMultBt(const TMatrixTSparse<Element> &a,const TMatrixTSparse<Element> &b,Int_t constr=0);
void AMultBt(const TMatrixTSparse<Element> &a,const TMatrixT<Element> &b,Int_t constr=0);
void AMultBt(const TMatrixT<Element> &a,const TMatrixTSparse<Element> &b,Int_t constr=0);
void APlusB (const TMatrixTSparse<Element> &a,const TMatrixTSparse<Element> &b,Int_t constr=0);
void APlusB (const TMatrixTSparse<Element> &a,const TMatrixT<Element> &b,Int_t constr=0);
void APlusB (const TMatrixT<Element> &a,const TMatrixTSparse<Element> &b,Int_t constr=0) { APlusB(b,a,constr); }
void AMinusB(const TMatrixTSparse<Element> &a,const TMatrixTSparse<Element> &b,Int_t constr=0);
void AMinusB(const TMatrixTSparse<Element> &a,const TMatrixT<Element> &b,Int_t constr=0);
void AMinusB(const TMatrixT<Element> &a,const TMatrixTSparse<Element> &b,Int_t constr=0);
public:
enum EMatrixCreatorsOp1 { kZero,kUnit,kTransposed,kAtA };
enum EMatrixCreatorsOp2 { kMult,kMultTranspose,kPlus,kMinus };
TMatrixTSparse() { fElements = 0; fRowIndex = 0; fColIndex = 0; }
TMatrixTSparse(Int_t nrows,Int_t ncols);
TMatrixTSparse(Int_t row_lwb,Int_t row_upb,Int_t col_lwb,Int_t col_upb);
TMatrixTSparse(Int_t row_lwb,Int_t row_upb,Int_t col_lwb,Int_t col_upb,Int_t nr_nonzeros,
Int_t *row, Int_t *col,Element *data);
TMatrixTSparse(const TMatrixTSparse<Element> &another);
TMatrixTSparse(const TMatrixT<Element> &another);
TMatrixTSparse(EMatrixCreatorsOp1 op,const TMatrixTSparse<Element> &prototype);
TMatrixTSparse(const TMatrixTSparse<Element> &a,EMatrixCreatorsOp2 op,const TMatrixTSparse<Element> &b);
TMatrixTSparse(const TMatrixTSparse<Element> &a,EMatrixCreatorsOp2 op,const TMatrixT <Element> &b);
TMatrixTSparse(const TMatrixT <Element> &a,EMatrixCreatorsOp2 op,const TMatrixTSparse<Element> &b);
virtual ~TMatrixTSparse() { Clear(); }
virtual const Element *GetMatrixArray () const;
virtual Element *GetMatrixArray ();
virtual const Int_t *GetRowIndexArray() const;
virtual Int_t *GetRowIndexArray();
virtual const Int_t *GetColIndexArray() const;
virtual Int_t *GetColIndexArray();
virtual TMatrixTBase<Element> &SetRowIndexArray(Int_t *data) { memmove(fRowIndex,data,(this->fNrows+1)*sizeof(Int_t)); return *this; }
virtual TMatrixTBase<Element> &SetColIndexArray(Int_t *data) { memmove(fColIndex,data,this->fNelems*sizeof(Int_t)); return *this; }
TMatrixTSparse<Element> &SetSparseIndex (Int_t nelem_new);
TMatrixTSparse<Element> &SetSparseIndex (const TMatrixTBase<Element> &another);
TMatrixTSparse<Element> &SetSparseIndexAB(const TMatrixTSparse<Element> &a,const TMatrixTSparse<Element> &b);
TMatrixTSparse<Element> &SetSparseIndexAB(const TMatrixT <Element> &a,const TMatrixTSparse<Element> &b);
TMatrixTSparse<Element> &SetSparseIndexAB(const TMatrixTSparse<Element> &a,const TMatrixT <Element> &b)
{ return SetSparseIndexAB(b,a); }
virtual void GetMatrix2Array (Element *data,Option_t * /*option*/ ="") const;
virtual TMatrixTBase<Element> &SetMatrixArray (const Element *data,Option_t * /*option*/="")
{ memcpy(fElements,data,this->fNelems*sizeof(Element)); return *this; }
virtual TMatrixTBase<Element> &SetMatrixArray (Int_t nr_nonzeros,Int_t *irow,Int_t *icol,Element *data);
virtual TMatrixTBase<Element> &InsertRow (Int_t row,Int_t col,const Element *v,Int_t n=-1);
virtual void ExtractRow (Int_t row,Int_t col, Element *v,Int_t n=-1) const;
virtual TMatrixTBase<Element> &ResizeTo(Int_t nrows,Int_t ncols,Int_t nr_nonzeros=-1);
virtual TMatrixTBase<Element> &ResizeTo(Int_t row_lwb,Int_t row_upb,Int_t col_lwb,Int_t col_upb,Int_t nr_nonzeros=-1);
inline TMatrixTBase<Element> &ResizeTo(const TMatrixTSparse<Element> &m) {return ResizeTo(m.GetRowLwb(),m.GetRowUpb(),m.GetColLwb(),
m.GetColUpb(),m.GetNoElements()); }
virtual void Clear(Option_t * /*option*/ ="") { if (this->fIsOwner) {
if (fElements) { delete [] fElements; fElements = 0; }
if (fRowIndex) { delete [] fRowIndex; fRowIndex = 0; }
if (fColIndex) { delete [] fColIndex; fColIndex = 0; }
}
this->fNelems = 0;
this->fNrowIndex = 0;
}
TMatrixTSparse<Element> &Use (Int_t row_lwb,Int_t row_upb,Int_t col_lwb,Int_t col_upb,Int_t nr_nonzeros,
Int_t *pRowIndex,Int_t *pColIndex,Element *pData);
const TMatrixTSparse<Element> &Use (Int_t row_lwb,Int_t row_upb,Int_t col_lwb,Int_t col_upb,Int_t nr_nonzeros,
const Int_t *pRowIndex,const Int_t *pColIndex,const Element *pData) const
{ return (const TMatrixTSparse<Element>&)
((const_cast<TMatrixTSparse<Element> *>(this))->Use(row_lwb,row_upb,col_lwb,col_upb,nr_nonzeros,
const_cast<Int_t *>(pRowIndex),
const_cast<Int_t *>(pColIndex),
const_cast<Element *>(pData))); }
TMatrixTSparse<Element> &Use (Int_t nrows,Int_t ncols,Int_t nr_nonzeros,
Int_t *pRowIndex,Int_t *pColIndex,Element *pData);
const TMatrixTSparse<Element> &Use (Int_t nrows,Int_t ncols,Int_t nr_nonzeros,
const Int_t *pRowIndex,const Int_t *pColIndex,const Element *pData) const;
TMatrixTSparse<Element> &Use (TMatrixTSparse<Element> &a);
const TMatrixTSparse<Element> &Use (const TMatrixTSparse<Element> &a) const;
virtual TMatrixTBase<Element> &GetSub(Int_t row_lwb,Int_t row_upb,Int_t col_lwb,Int_t col_upb,
TMatrixTBase<Element> &target,Option_t *option="S") const;
TMatrixTSparse<Element> GetSub(Int_t row_lwb,Int_t row_upb,Int_t col_lwb,Int_t col_upb,Option_t *option="S") const;
virtual TMatrixTBase<Element> &SetSub(Int_t row_lwb,Int_t col_lwb,const TMatrixTBase<Element> &source);
virtual Bool_t IsSymmetric() const { return (*this == TMatrixTSparse<Element>(kTransposed,*this)); }
TMatrixTSparse<Element> &Transpose (const TMatrixTSparse<Element> &source);
inline TMatrixTSparse<Element> &T () { return this->Transpose(*this); }
inline void Mult(const TMatrixTSparse<Element> &a,const TMatrixTSparse<Element> &b) { AMultB(a,b,0); }
virtual TMatrixTBase<Element> &Zero ();
virtual TMatrixTBase<Element> &UnitMatrix ();
virtual Element RowNorm () const;
virtual Element ColNorm () const;
virtual Int_t NonZeros() const { return this->fNelems; }
virtual TMatrixTBase<Element> &NormByDiag(const TVectorT<Element> &/*v*/,Option_t * /*option*/)
{ MayNotUse("NormByDiag"); return *this; }
// Either access a_ij as a(i,j)
Element operator()(Int_t rown,Int_t coln) const;
Element &operator()(Int_t rown,Int_t coln);
// or as a[i][j]
inline const TMatrixTSparseRow_const<Element> operator[](Int_t rown) const { return TMatrixTSparseRow_const<Element>(*this,rown); }
inline TMatrixTSparseRow <Element> operator[](Int_t rown) { return TMatrixTSparseRow <Element>(*this,rown); }
TMatrixTSparse<Element> &operator=(const TMatrixT<Element> &source);
TMatrixTSparse<Element> &operator=(const TMatrixTSparse<Element> &source);
TMatrixTSparse<Element> &operator= (Element val);
TMatrixTSparse<Element> &operator-=(Element val);
TMatrixTSparse<Element> &operator+=(Element val);
TMatrixTSparse<Element> &operator*=(Element val);
TMatrixTSparse<Element> &operator+=(const TMatrixTSparse<Element> &source) { TMatrixTSparse<Element> tmp(*this); Clear();
if (this == &source) APlusB (tmp,tmp,1);
else APlusB (tmp,source,1);
return *this; }
TMatrixTSparse<Element> &operator+=(const TMatrixT<Element> &source) { TMatrixTSparse<Element> tmp(*this); Clear();
APlusB(tmp,source,1); return *this; }
TMatrixTSparse<Element> &operator-=(const TMatrixTSparse<Element> &source) { TMatrixTSparse<Element> tmp(*this); Clear();
if (this == &source) AMinusB (tmp,tmp,1);
else AMinusB(tmp,source,1);
return *this; }
TMatrixTSparse<Element> &operator-=(const TMatrixT<Element> &source) { TMatrixTSparse<Element> tmp(*this); Clear();
AMinusB(tmp,source,1); return *this; }
TMatrixTSparse<Element> &operator*=(const TMatrixTSparse<Element> &source) { TMatrixTSparse<Element> tmp(*this); Clear();
if (this == &source) AMultB (tmp,tmp,1);
else AMultB (tmp,source,1);
return *this; }
TMatrixTSparse<Element> &operator*=(const TMatrixT<Element> &source) { TMatrixTSparse<Element> tmp(*this); Clear();
AMultB(tmp,source,1);
return *this; }
virtual TMatrixTBase <Element> &Randomize (Element alpha,Element beta,Double_t &seed);
virtual TMatrixTSparse<Element> &RandomizePD(Element alpha,Element beta,Double_t &seed);
ClassDef(TMatrixTSparse,3) // Template of Sparse Matrix class
};
#ifndef __CINT__
// When building with -fmodules, it instantiates all pending instantiations,
// instead of delaying them until the end of the translation unit.
// We 'got away with' probably because the use and the definition of the
// explicit specialization do not occur in the same TU.
//
// In case we are building with -fmodules, we need to forward declare the
// specialization in order to compile the dictionary G__Matrix.cxx.
template <> TClass *TMatrixTSparse<double>::Class();
#endif // __CINT__
template <class Element> inline const Element *TMatrixTSparse<Element>::GetMatrixArray () const { return fElements; }
template <class Element> inline Element *TMatrixTSparse<Element>::GetMatrixArray () { return fElements; }
template <class Element> inline const Int_t *TMatrixTSparse<Element>::GetRowIndexArray() const { return fRowIndex; }
template <class Element> inline Int_t *TMatrixTSparse<Element>::GetRowIndexArray() { return fRowIndex; }
template <class Element> inline const Int_t *TMatrixTSparse<Element>::GetColIndexArray() const { return fColIndex; }
template <class Element> inline Int_t *TMatrixTSparse<Element>::GetColIndexArray() { return fColIndex; }
template <class Element>
inline TMatrixTSparse<Element> &TMatrixTSparse<Element>::Use (Int_t nrows,Int_t ncols,Int_t nr_nonzeros,
Int_t *pRowIndex,Int_t *pColIndex,Element *pData)
{ return Use(0,nrows-1,0,ncols-1,nr_nonzeros,pRowIndex,pColIndex,pData); }
template <class Element>
inline const TMatrixTSparse<Element> &TMatrixTSparse<Element>::Use (Int_t nrows,Int_t ncols,Int_t nr_nonzeros,
const Int_t *pRowIndex,const Int_t *pColIndex,const Element *pData) const
{ return Use(0,nrows-1,0,ncols-1,nr_nonzeros,pRowIndex,pColIndex,pData); }
template <class Element>
inline TMatrixTSparse<Element> &TMatrixTSparse<Element>::Use (TMatrixTSparse<Element> &a)
{ R__ASSERT(a.IsValid());
return Use(a.GetRowLwb(),a.GetRowUpb(),a.GetColLwb(),a.GetColUpb(),
a.GetNoElements(),a.GetRowIndexArray(),
a.GetColIndexArray(),a.GetMatrixArray()); }
template <class Element>
inline const TMatrixTSparse<Element> &TMatrixTSparse<Element>::Use (const TMatrixTSparse<Element> &a) const
{ R__ASSERT(a.IsValid());
return Use(a.GetRowLwb(),a.GetRowUpb(),a.GetColLwb(),a.GetColUpb(),
a.GetNoElements(),a.GetRowIndexArray(),
a.GetColIndexArray(),a.GetMatrixArray()); }
template <class Element>
inline TMatrixTSparse<Element> TMatrixTSparse<Element>::GetSub(Int_t row_lwb,Int_t row_upb,Int_t col_lwb,Int_t col_upb,
Option_t *option) const
{
TMatrixTSparse<Element> tmp;
this->GetSub(row_lwb,row_upb,col_lwb,col_upb,tmp,option);
return tmp;
}
template <class Element> TMatrixTSparse<Element> operator+ (const TMatrixTSparse<Element> &source1,const TMatrixTSparse<Element> &source2);
template <class Element> TMatrixTSparse<Element> operator+ (const TMatrixTSparse<Element> &source1,const TMatrixT<Element> &source2);
template <class Element> TMatrixTSparse<Element> operator+ (const TMatrixT<Element> &source1,const TMatrixTSparse<Element> &source2);
template <class Element> TMatrixTSparse<Element> operator+ (const TMatrixTSparse<Element> &source , Element val );
template <class Element> TMatrixTSparse<Element> operator+ ( Element val ,const TMatrixTSparse<Element> &source );
template <class Element> TMatrixTSparse<Element> operator- (const TMatrixTSparse<Element> &source1,const TMatrixTSparse<Element> &source2);
template <class Element> TMatrixTSparse<Element> operator- (const TMatrixTSparse<Element> &source1,const TMatrixT<Element> &source2);
template <class Element> TMatrixTSparse<Element> operator- (const TMatrixT<Element> &source1,const TMatrixTSparse<Element> &source2);
template <class Element> TMatrixTSparse<Element> operator- (const TMatrixTSparse<Element> &source , Element val );
template <class Element> TMatrixTSparse<Element> operator- ( Element val ,const TMatrixTSparse<Element> &source );
template <class Element> TMatrixTSparse<Element> operator* (const TMatrixTSparse<Element> &source1,const TMatrixTSparse<Element> &source2);
template <class Element> TMatrixTSparse<Element> operator* (const TMatrixTSparse<Element> &source1,const TMatrixT<Element> &source2);
template <class Element> TMatrixTSparse<Element> operator* (const TMatrixT<Element> &source1,const TMatrixTSparse<Element> &source2);
template <class Element> TMatrixTSparse<Element> operator* ( Element val ,const TMatrixTSparse<Element> &source );
template <class Element> TMatrixTSparse<Element> operator* (const TMatrixTSparse<Element> &source, Element val );
template <class Element> TMatrixTSparse<Element> &Add (TMatrixTSparse<Element> &target, Element scalar,
const TMatrixTSparse<Element> &source);
template <class Element> TMatrixTSparse<Element> &ElementMult(TMatrixTSparse<Element> &target,const TMatrixTSparse<Element> &source);
template <class Element> TMatrixTSparse<Element> &ElementDiv (TMatrixTSparse<Element> &target,const TMatrixTSparse<Element> &source);
template <class Element> Bool_t AreCompatible(const TMatrixTSparse<Element> &m1,const TMatrixTSparse<Element> &m2,Int_t verbose=0);
#endif
| {
"alphanum_fraction": 0.5656540791,
"avg_line_length": 73.5905797101,
"ext": "h",
"hexsha": "96dab7ddc611f497094f268ce56cd4a66aaac765",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2020-05-28T23:01:44.000Z",
"max_forks_repo_forks_event_min_datetime": "2020-05-28T23:01:44.000Z",
"max_forks_repo_head_hexsha": "2632aa3484ef64c9539c4885026b705b737f6d1e",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "edawson/parliament2",
"max_forks_repo_path": "resources/home/dnanexus/root/include/TMatrixTSparse.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "2632aa3484ef64c9539c4885026b705b737f6d1e",
"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": "edawson/parliament2",
"max_issues_repo_path": "resources/home/dnanexus/root/include/TMatrixTSparse.h",
"max_line_length": 149,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "2632aa3484ef64c9539c4885026b705b737f6d1e",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "edawson/parliament2",
"max_stars_repo_path": "resources/home/dnanexus/root/include/TMatrixTSparse.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 4531,
"size": 20311
} |
/**
* \file FIRFilter.h
*/
#ifndef ATK_EQ_FIRFILTER_H
#define ATK_EQ_FIRFILTER_H
#include <ATK/config.h>
#include <ATK/EQ/config.h>
#include <gsl/gsl>
#include <cassert>
#include <cstdint>
#include <vector>
namespace ATK
{
/**
* FIR filter template class
*/
template<class Coefficients >
class ATK_EQ_EXPORT FIRFilter final : public Coefficients
{
protected:
using Parent = Coefficients;
using typename Parent::DataType;
using typename Parent::AlignedScalarVector;
using Parent::converted_inputs;
using Parent::outputs;
using Parent::coefficients_in;
using Parent::input_sampling_rate;
using Parent::output_sampling_rate;
using Parent::nb_input_ports;
using Parent::nb_output_ports;
using Parent::in_order;
using Parent::input_delay;
using Parent::setup;
public:
/*!
* @brief Constructor
* @param nb_channels is the number of input and output channels
*/
explicit FIRFilter(gsl::index nb_channels = 1)
:Parent(nb_channels)
{
}
/// Move constructor
FIRFilter(FIRFilter&& other)
:Parent(std::move(other))
{
}
void setup() override
{
Parent::setup();
input_delay = in_order;
}
void process_impl(gsl::index size) const final
{
assert(input_sampling_rate == output_sampling_rate);
assert(nb_input_ports == nb_output_ports);
assert(coefficients_in.data());
const auto* ATK_RESTRICT coefficients_in_ptr = coefficients_in.data();
for (gsl::index channel = 0; channel < nb_input_ports; ++channel)
{
const DataType* ATK_RESTRICT input = converted_inputs[channel] - static_cast<int64_t>(in_order);
DataType* ATK_RESTRICT output = outputs[channel];
for (gsl::index i = 0; i < size; ++i)
{
output[i] = 0;
}
for (gsl::index j = 0; j < in_order + 1; ++j)
{
for (gsl::index i = 0; i < size; ++i)
{
output[i] += coefficients_in_ptr[j] * input[i + j];
}
}
}
}
/// Returns the vector of internal coefficients for the MA section
const AlignedScalarVector& get_coefficients_in() const
{
return coefficients_in;
}
};
}
#endif
| {
"alphanum_fraction": 0.6245076586,
"avg_line_length": 22.1844660194,
"ext": "h",
"hexsha": "e33a35a2bcde984bceb5869f246e80dae3c87849",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2021-12-17T00:47:11.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-04-12T03:28:12.000Z",
"max_forks_repo_head_hexsha": "dba42eea68534501efe74692b74edf4792cca231",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "AudioTK/AudioTK",
"max_forks_repo_path": "ATK/EQ/FIRFilter.h",
"max_issues_count": 2,
"max_issues_repo_head_hexsha": "dba42eea68534501efe74692b74edf4792cca231",
"max_issues_repo_issues_event_max_datetime": "2021-09-13T19:39:05.000Z",
"max_issues_repo_issues_event_min_datetime": "2021-02-01T15:45:06.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "AudioTK/AudioTK",
"max_issues_repo_path": "ATK/EQ/FIRFilter.h",
"max_line_length": 104,
"max_stars_count": 23,
"max_stars_repo_head_hexsha": "dba42eea68534501efe74692b74edf4792cca231",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "AudioTK/AudioTK",
"max_stars_repo_path": "ATK/EQ/FIRFilter.h",
"max_stars_repo_stars_event_max_datetime": "2022-03-25T03:45:00.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-02-04T10:47:46.000Z",
"num_tokens": 558,
"size": 2285
} |
#ifndef __MATH_GSL_MATRIX__
#define __MATH_GSL_MATRIX__
#include <gsl/gsl_vector.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_cblas.h>
class GslMatrixItem {
public:
GslMatrixItem(gsl_matrix* ptr, size_t index1, size_t index2) :
ptr_(ptr),
index1_(index1),
index2_(index2) { }
operator const double() {
return gsl_matrix_get(ptr_, index1_, index2_);
}
double operator =(const double v) {
gsl_matrix_set(ptr_, index1_, index2_, v);
return v;
}
double operator +=(const double v) {
double old_v = gsl_matrix_get(ptr_, index1_, index2_);
gsl_matrix_set(ptr_, index1_, index2_, v + old_v);
return v + old_v;
}
private:
gsl_matrix* ptr_;
size_t index1_;
size_t index2_;
};
class GslMatrixBase {
public:
GslMatrixBase& operator=(const double v) {
if (v == 0.0) {
SetZero();
} else {
SetAll(v);
}
return *this;
}
GslMatrixItem operator()(const size_t index1, const size_t index2) const {
assert(ptr_ != NULL);
return GslMatrixItem(ptr_, index1, index2);
}
void SetZero() {
assert(ptr_ != NULL);
gsl_matrix_set_zero(ptr_);
}
void SetAll(const double v) {
assert(ptr_ != NULL);
gsl_matrix_set_all(ptr_, v);
}
void Reset(gsl_matrix* val) {
if(ptr_ != NULL) {
gsl_matrix_free(ptr_);
}
ptr_ = val;
}
int Fprintf(FILE* stream, const char* format) const {
assert(ptr_ != NULL);
return gsl_matrix_fprintf(stream, ptr_, format);
}
int Fscanf(FILE* stream) {
assert(ptr_ != NULL);
return gsl_matrix_fscanf(stream, ptr_);
}
void Set(const int i, const int j, double val) {
gsl_matrix_set(ptr_, i, j, val);
}
/*
double operator()(const int nCol, const int nRow) {
return gsl_matrix_get(ptr_, nCol, nRow);
}
*/
int size1() const {
return ptr_->size1;
}
int size2() const {
return ptr_->size2;
}
double Trace() const {
double val = 0;
assert(ptr_ != NULL);
assert(ptr_->size1 == ptr_->size2);
for (size_t ii = 0; ii < ptr_->size1; ++ii) {
val += gsl_matrix_get(ptr_, ii, ii);
}
return val;
}
double Sum() const {
double val = 0;
assert(ptr_ != NULL);
for (size_t ii = 0; ii < ptr_->size1; ++ii) {
for (size_t jj = 0; jj < ptr_->size2; ++jj) {
val += gsl_matrix_get(ptr_, ii, jj);
}
}
return val;
}
/*
* Apply the transpose of this matrix to a vector x and store the result.
int TransMul(const GslVector& x, GslVector& res, double scale = 0.0) {
return gsl_blas_dgemv(CblasTrans, 1.0, ptr_, x.ptr(), scale, res.ptr());
}
int Mul(const GslVector& x, GslVector& res, double scale = 0.0) {
return gsl_blas_dgemv(CblasNoTrans, 1.0, ptr_, x.ptr(), scale, res.ptr());
}
*/
const gsl_matrix* ptr() const { return ptr_; }
gsl_matrix* mutable_ptr() { return ptr_; }
protected:
GslMatrixBase() : ptr_(NULL) {
}
gsl_matrix* ptr_;
private:
GslMatrixBase(const GslMatrixBase&) { }
};
class GslMatrix : public GslMatrixBase {
public:
GslMatrix(const size_t size1, const size_t size2) : GslMatrixBase() {
Allocate(size1, size2);
}
void Allocate(const size_t size1, const size_t size2) {
assert(ptr_ == NULL);
ptr_ = gsl_matrix_alloc(size1, size2);
}
GslMatrix() : GslMatrixBase() {
}
GslMatrix(gsl_matrix* val) : GslMatrixBase() {
ptr_ = val;
}
~GslMatrix() {
if(ptr_ != NULL) {
gsl_matrix_free(ptr_);
}
}
GslMatrixBase& operator=(const double v) {
GslMatrixBase::operator=(v);
return *this;
}
private:
GslMatrix(const GslMatrix&) { }
};
class GslSubmatrix : public GslMatrixBase {
public:
GslSubmatrix(GslMatrixBase& matrix, size_t k1, size_t k2, size_t n1, size_t n2) :
view_(gsl_matrix_submatrix(matrix.mutable_ptr(), k1, k2, n1, n2)) {
ptr_ = &view_.matrix;
}
GslSubmatrix(gsl_matrix* matrix, size_t k1, size_t k2, size_t n1, size_t n2) :
view_(gsl_matrix_submatrix(matrix, k1, k2, n1, n2)) {
ptr_ = &view_.matrix;
}
GslMatrixBase& operator=(const double v) {
GslMatrixBase::operator=(v);
return *this;
}
private:
gsl_matrix_view view_;
GslSubmatrix(const GslSubmatrix&) { }
};
#endif // __MATH_GSL_MATRIX__
| {
"alphanum_fraction": 0.6315789474,
"avg_line_length": 21.7142857143,
"ext": "h",
"hexsha": "2563f949559df5dadaf678b171a9dd38ef0f485d",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2018-11-27T01:35:33.000Z",
"max_forks_repo_forks_event_min_datetime": "2018-11-27T01:35:33.000Z",
"max_forks_repo_head_hexsha": "159aab87f04b745d874b53f64fd30703b4d5a70c",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "boomsbloom/dtm-fmri",
"max_forks_repo_path": "DTM/dtm-master/lib/math/gsl_matrix.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "159aab87f04b745d874b53f64fd30703b4d5a70c",
"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": "boomsbloom/dtm-fmri",
"max_issues_repo_path": "DTM/dtm-master/lib/math/gsl_matrix.h",
"max_line_length": 82,
"max_stars_count": 4,
"max_stars_repo_head_hexsha": "159aab87f04b745d874b53f64fd30703b4d5a70c",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "boomsbloom/dtm-fmri",
"max_stars_repo_path": "DTM/dtm-master/lib/math/gsl_matrix.h",
"max_stars_repo_stars_event_max_datetime": "2022-01-27T01:17:11.000Z",
"max_stars_repo_stars_event_min_datetime": "2018-11-27T01:35:30.000Z",
"num_tokens": 1314,
"size": 4256
} |
///
/// @file This file contains the Schur reduction experiment.
///
/// @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_test_config.h>
#include <starneig/configuration.h>
#include "experiment.h"
#include "solvers.h"
#include "../common/common.h"
#include "../common/threads.h"
#include "../common/parse.h"
#include "../common/init.h"
#include "../common/checks.h"
#include "../common/hooks.h"
#include "../common/local_pencil.h"
#ifdef STARNEIG_ENABLE_MPI
#include "../common/starneig_pencil.h"
#endif
#include "../common/io.h"
#include "../common/crawler.h"
#include "../common/complex_distr.h"
#include "../hessenberg/solvers.h"
#include <starneig/starneig.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#ifdef GSL_FOUND
#include <gsl/gsl_randist.h>
#endif
#define DEFLATE 0x1
#define SET_TO_INF 0x2
static int deflate_and_place_infinities_crawler(
int offset, int size, int m, int n, int count, size_t *lds,
void **ptrs, void *arg)
{
int const *sub = arg;
double *A = ptrs[0];
size_t ldA = lds[0];
double *B = NULL; size_t ldB = 0;
if (ptrs[1] != NULL) {
B = ptrs[1];
ldB = lds[1];
}
for (int i = 1; i < size; i++) {
if (sub[offset+i] & DEFLATE)
A[(i-1)*ldA+i] = 0.0;
if (B != NULL && sub[offset+i] & SET_TO_INF)
B[i*ldB+i] = 0.0;
}
return size;
}
///
/// @brief Modifies a matrix pencil such that it is decoupled to multiple
/// independent subproblems and adds
///
/// @param[in] cuts
/// The desired number of deflations.
///
/// @param[in] infinities
/// The desired number of infinities.
///
/// @param[in,out] pencil
/// The matrix pencil.
///
static void deflate_and_place_infinities(
int cuts, int infinities, pencil_t pencil)
{
int n = GENERIC_MATRIX_N(pencil->mat_a);
int *sub = malloc(n*sizeof(int));
memset(sub, 0, n*sizeof(int));
cuts = MIN(cuts, n-1);
for (int i = 0; i < cuts; i++) {
int p = prand() % (n-1) + 1;
while (sub[p] & DEFLATE)
p = prand() % (n-1) + 1;
sub[p] |= DEFLATE;
}
for (int i = 0; i < infinities; i++) {
int p = prand() % (n-1) + 1;
while (sub[p] & SET_TO_INF)
p = prand() % (n-1) + 1;
sub[p] |= SET_TO_INF;
}
crawl_matrices(CRAWLER_RW, CRAWLER_DIAG_WINDOW,
&deflate_and_place_infinities_crawler, sub, 0,
pencil->mat_a, pencil->mat_b, NULL);
free(sub);
free_matrix_descr(pencil->mat_ca);
pencil->mat_ca = NULL;
free_matrix_descr(pencil->mat_cb);
pencil->mat_cb = NULL;
fill_pencil(pencil);
}
////////////////////////////////////////////////////////////////////////////////
static void random_initializer_print_usage(int argc, char * const *argv)
{
printf(
" --n (num) -- Problem dimension\n"
" --generalized -- Generalized problem\n"
" --decouple (num) -- Decouple the problem\n"
" --set-to-inf (num) -- Place infinities\n"
);
init_helper_print_usage("", INIT_HELPER_ALL, argc, argv);
}
static void random_initializer_print_args(int argc, char * const *argv)
{
printf(" --n %d", read_int("--n", argc, argv, NULL, -1));
if (read_opt("--generalized", argc, argv, NULL))
printf(" --generalized");
printf(" --decouple %d", read_int("--decouple", argc, argv, NULL, 0));
printf(" --set-to-inf %d", read_int("--set-to-inf", argc, argv, NULL, 0));
init_helper_print_args("", INIT_HELPER_ALL, argc, argv);
}
static int random_initializer_check_args(
int argc, char * const *argv, int *argr)
{
if (read_int("--n", argc, argv, argr, -1) < 1)
return 1;
read_opt("--generalized", argc, argv, argr);
if (read_int("--decouple", argc, argv, argr, 0) < 0)
return 1;
if (read_int("--set-to-inf", argc, argv, argr, 0) < 0)
return 1;
return init_helper_check_args("", INIT_HELPER_ALL, argc, argv, argr);
}
static struct hook_data_env* random_initializer_init(
hook_data_format_t format, int argc, char * const *argv)
{
printf("INIT...\n");
int n = read_int("--n", argc, argv, NULL, -1);
int generalized = read_opt("--generalized", argc, argv, NULL);
int decouple = read_int("--decouple", argc, argv, NULL, 0);
int set_to_inf = read_int("--set-to-inf", argc, argv, NULL, 0);
init_helper_t helper = init_helper_init_hook(
"", format, n, n, PREC_DOUBLE | NUM_REAL, argc, argv);
struct hook_data_env *env = malloc(sizeof(struct hook_data_env));
env->format = format;
env->copy_data = (hook_data_env_copy_t) copy_pencil;
env->free_data = (hook_data_env_free_t) free_pencil;
pencil_t data = env->data = init_pencil();
data->mat_a = generate_random_hessenberg(n, n, helper);
data->mat_q = generate_random_householder(n, helper);
if (generalized) {
data->mat_b = generate_random_uptriag(n, n, helper);
data->mat_z = generate_random_householder(n, helper);
}
if (0 < decouple || 0 < set_to_inf)
deflate_and_place_infinities(decouple, set_to_inf, data);
init_helper_free(helper);
return env;
}
static const struct hook_initializer_t random_initializer = {
.name = "random",
.desc = "Generates a random upper Hessenberg matrix",
.formats = (hook_data_format_t[]) {
HOOK_DATA_FORMAT_PENCIL_LOCAL,
#ifdef STARNEIG_ENABLE_MPI
HOOK_DATA_FORMAT_PENCIL_STARNEIG,
#endif
#ifdef STARNEIG_ENABLE_BLACS
HOOK_DATA_FORMAT_PENCIL_BLACS,
#endif
0 },
.print_usage = &random_initializer_print_usage,
.print_args = &random_initializer_print_args,
.check_args = &random_initializer_check_args,
.init = &random_initializer_init
};
////////////////////////////////////////////////////////////////////////////////
static void known_initializer_print_usage(int argc, char * const *argv)
{
printf(
" --n (num) -- Problem dimension\n"
" --generalized -- Generalized problem\n"
" --complex-distr (complex distribution) -- 2-by-2 block "
"distribution module\n"
);
init_helper_print_usage("", INIT_HELPER_ALL, argc, argv);
}
static void known_initializer_print_args(int argc, char * const *argv)
{
printf(" --n %d", read_int("--n", argc, argv, NULL, -1));
int generalized = read_opt("--generalized", argc, argv, NULL);
if (generalized)
printf(" --generalized");
struct complex_distr const *complex_distr =
read_complex_distr("--complex-distr", argc, argv, NULL);
printf(" --complex-distr %s", complex_distr->name);
if (complex_distr->print_args != NULL)
complex_distr->print_args(argc, argv);
init_helper_print_args("", INIT_HELPER_ALL, argc, argv);
}
static int known_initializer_check_args(
int argc, char * const *argv, int *argr)
{
if (read_int("--n", argc, argv, argr, -1) < 1)
return 1;
read_opt("--generalized", argc, argv, argr);
struct complex_distr const *complex_distr =
read_complex_distr("--complex-distr", argc, argv, argr);
if (complex_distr == NULL) {
fprintf(stderr, "Invalid 2-by-2 block distribution module.\n");
return -1;
}
if (complex_distr->check_args != NULL) {
int ret = complex_distr->check_args(argc, argv, argr);
if (ret)
return ret;
}
return init_helper_check_args("", INIT_HELPER_ALL, argc, argv, argr);
}
static struct hook_data_env* known_initializer_init(
hook_data_format_t format, int argc, char * const *argv)
{
printf("INIT...\n");
int n = read_int("--n", argc, argv, NULL, -1);
int generalized = read_opt("--generalized", argc, argv, NULL);
struct complex_distr const *complex_distr =
read_complex_distr("--complex-distr", argc, argv, NULL);
init_helper_t helper = init_helper_init_hook(
"", format, n, n, PREC_DOUBLE | NUM_REAL, argc, argv);
struct hook_data_env *env = malloc(sizeof(struct hook_data_env));
env->format = format;
env->copy_data = (hook_data_env_copy_t) copy_pencil;
env->free_data = (hook_data_env_free_t) free_pencil;
pencil_t pencil = env->data = init_pencil();
double *real, *imag, *beta;
init_supplementary_known_eigenvalues(n, &real, &imag, &beta, &pencil->supp);
// generate (generalized) Schur form and multiply with Householder
// reflectors from both sides
if (generalized) {
matrix_t mat_s = generate_random_uptriag(n, n, helper);
matrix_t mat_t = generate_identity(n, n, helper);
complex_distr->init(argc, argv, mat_s, mat_t);
extract_eigenvalues(mat_s, mat_t, real, imag, beta);
matrix_t mat_q = generate_random_householder(n, helper);
matrix_t mat_z = generate_random_householder(n, helper);
mul_QAZT(mat_q, mat_s, mat_z, &pencil->mat_a);
mul_QAZT(mat_q, mat_t, mat_z, &pencil->mat_b);
free_matrix_descr(mat_s);
free_matrix_descr(mat_t);
free_matrix_descr(mat_q);
free_matrix_descr(mat_z);
}
else {
matrix_t mat_s = generate_random_uptriag(n, n, helper);
complex_distr->init(argc, argv, mat_s, NULL);
extract_eigenvalues(mat_s, NULL, real, imag, beta);
matrix_t mat_q = generate_random_householder(n, helper);
mul_QAZT(mat_q, mat_s, mat_q, &pencil->mat_a);
free_matrix_descr(mat_s);
free_matrix_descr(mat_q);
}
// reduce the dense matrix (pencil) to Hessenberg(-triangular) form
pencil->mat_q = generate_identity(n, n, helper);
pencil->mat_ca = copy_matrix_descr(pencil->mat_a);
if (generalized) {
pencil->mat_z = generate_identity(n, n, helper);
pencil->mat_cb = copy_matrix_descr(pencil->mat_b);
}
#ifdef STARNEIG_ENABLE_BLACS
if (format == HOOK_DATA_FORMAT_PENCIL_BLACS) {
starneig_node_init(threads_get_workers(), STARNEIG_USE_ALL,
STARNEIG_HINT_DM | STARNEIG_FXT_DISABLE);
if (generalized) {
starneig_GEP_DM_HessenbergTriangular(
STARNEIG_MATRIX_HANDLE(pencil->mat_a),
STARNEIG_MATRIX_HANDLE(pencil->mat_b),
STARNEIG_MATRIX_HANDLE(pencil->mat_q),
STARNEIG_MATRIX_HANDLE(pencil->mat_z));
}
else {
starneig_SEP_DM_Hessenberg(
STARNEIG_MATRIX_HANDLE(pencil->mat_a),
STARNEIG_MATRIX_HANDLE(pencil->mat_q));
}
starneig_node_finalize();
}
#endif
if (format == HOOK_DATA_FORMAT_PENCIL_LOCAL) {
starneig_node_init(threads_get_workers(), STARNEIG_USE_ALL,
STARNEIG_HINT_SM | STARNEIG_FXT_DISABLE);
if (generalized) {
starneig_GEP_SM_HessenbergTriangular(LOCAL_MATRIX_N(pencil->mat_a),
LOCAL_MATRIX_PTR(pencil->mat_a), LOCAL_MATRIX_LD(pencil->mat_a),
LOCAL_MATRIX_PTR(pencil->mat_b), LOCAL_MATRIX_LD(pencil->mat_b),
LOCAL_MATRIX_PTR(pencil->mat_q), LOCAL_MATRIX_LD(pencil->mat_q),
LOCAL_MATRIX_PTR(pencil->mat_z), LOCAL_MATRIX_LD(pencil->mat_z)
);
}
else {
starneig_SEP_SM_Hessenberg(LOCAL_MATRIX_N(pencil->mat_a),
LOCAL_MATRIX_PTR(pencil->mat_a), LOCAL_MATRIX_LD(pencil->mat_a),
LOCAL_MATRIX_PTR(pencil->mat_q), LOCAL_MATRIX_LD(pencil->mat_q));
}
starneig_node_finalize();
}
init_helper_free(helper);
return env;
}
static const struct hook_initializer_t known_initializer = {
.name = "known",
.desc = "Generates an upper Hessenberg matrix with known eigenvalues",
.formats = (hook_data_format_t[]) {
HOOK_DATA_FORMAT_PENCIL_LOCAL,
#ifdef STARNEIG_ENABLE_MPI
HOOK_DATA_FORMAT_PENCIL_STARNEIG,
#endif
#ifdef STARNEIG_ENABLE_BLACS
HOOK_DATA_FORMAT_PENCIL_BLACS,
#endif
0 },
.print_usage = &known_initializer_print_usage,
.print_args = &known_initializer_print_args,
.check_args = &known_initializer_check_args,
.init = &known_initializer_init
};
////////////////////////////////////////////////////////////////////////////////
#ifdef GSL_FOUND
static void hessrand_initializer_print_usage(int argc, char * const *argv)
{
printf(
" --n (num) -- Problem dimension\n"
" --generalized -- Generalized problem\n"
" --decouple (num) -- Decouple the problem\n"
" --set-to-inf (num) -- Place infinities\n"
);
init_helper_print_usage("", INIT_HELPER_ALL, argc, argv);
}
static void hessrand_initializer_print_args(int argc, char * const *argv)
{
printf(" --n %d", read_int("--n", argc, argv, NULL, -1));
if (read_opt("--generalized", argc, argv, NULL))
printf(" --generalized");
printf(" --decouple %d", read_int("--decouple", argc, argv, NULL, 0));
printf(" --set-to-inf %d", read_int("--set-to-inf", argc, argv, NULL, 0));
init_helper_print_args("", INIT_HELPER_ALL, argc, argv);
}
static int hessrand_initializer_check_args(
int argc, char * const *argv, int *argr)
{
if (read_int("--n", argc, argv, argr, -1) < 1)
return 1;
read_opt("--generalized", argc, argv, argr);
if (read_int("--decouple", argc, argv, argr, 0) < 0)
return 1;
if (read_int("--set-to-inf", argc, argv, argr, 0) < 0)
return 1;
return init_helper_check_args("", INIT_HELPER_ALL, argc, argv, argr);
}
static int hessrand_crawler(
int offset, int width, int m, int n, int count, size_t *lds,
void **ptrs, void *arg)
{
gsl_rng *r = arg;
{
double *A = ptrs[0];
size_t ldA = lds[0];
for (int i = 0; i < width; i++) {
for (int j = 0; j < offset+i+1; j++)
A[i*ldA+j] = gsl_ran_gaussian(r, 1.0);
if (offset+i+1 < m)
A[i*ldA+offset+i+1] = sqrt(gsl_ran_chisq(r, n-offset-i-1));
for (int j = offset+i+2; j < m; j++)
A[i*ldA+j] = 0.0;
}
}
if (1 < count) {
double *B = ptrs[1];
size_t ldB = lds[1];
for (int i = 0; i < width; i++) {
for (int j = 0; j < offset+i; j++)
B[i*ldB+j] = gsl_ran_gaussian(r, 1.0);
B[i*ldB+offset+i] = sqrt(gsl_ran_chisq(r, offset+i));
for (int j = offset+i+1; j < m; j++)
B[i*ldB+j] = 0.0;
}
if (offset == 0)
B[0] = sqrt(gsl_ran_chisq(r, n));
}
return width;
}
static struct hook_data_env* hessrand_initializer_init(
hook_data_format_t format, int argc, char * const *argv)
{
printf("INIT...\n");
int n = read_int("--n", argc, argv, NULL, -1);
int generalized = read_opt("--generalized", argc, argv, NULL);
int decouple = read_int("--decouple", argc, argv, NULL, 0);
int set_to_inf = read_int("--set-to-inf", argc, argv, NULL, 0);
init_helper_t helper = init_helper_init_hook(
"", format, n, n, PREC_DOUBLE | NUM_REAL, argc, argv);
struct hook_data_env *env = malloc(sizeof(struct hook_data_env));
env->format = format;
env->copy_data = (hook_data_env_copy_t) copy_pencil;
env->free_data = (hook_data_env_free_t) free_pencil;
pencil_t data = env->data = init_pencil();
data->mat_a = init_matrix(n, n, helper);
if (generalized)
data->mat_b = init_matrix(n, n, helper);
gsl_rng_env_setup();
const gsl_rng_type *T = gsl_rng_default;
gsl_rng *r = gsl_rng_alloc(T);
gsl_rng_set(r, prand());
crawl_matrices(
CRAWLER_W, CRAWLER_PANEL, &hessrand_crawler, r, 0,
data->mat_a, data->mat_b, NULL);
gsl_rng_free(r);
data->mat_q = generate_random_householder(n, helper);
if (generalized)
data->mat_z = generate_random_householder(n, helper);
if (0 < decouple || 0 < set_to_inf)
deflate_and_place_infinities(decouple, set_to_inf, data);
init_helper_free(helper);
return env;
}
static const struct hook_initializer_t hessrand_initializer = {
.name = "hessrand",
.desc = "Generates a hessrand upper Hessenberg matrix",
.formats = (hook_data_format_t[]) {
HOOK_DATA_FORMAT_PENCIL_LOCAL,
#ifdef STARNEIG_ENABLE_MPI
HOOK_DATA_FORMAT_PENCIL_STARNEIG,
#endif
#ifdef STARNEIG_ENABLE_BLACS
HOOK_DATA_FORMAT_PENCIL_BLACS,
#endif
0 },
.print_usage = &hessrand_initializer_print_usage,
.print_args = &hessrand_initializer_print_args,
.check_args = &hessrand_initializer_check_args,
.init = &hessrand_initializer_init
};
#endif
////////////////////////////////////////////////////////////////////////////////
static void generic_initializer_print_usage(int argc, char * const *argv)
{
printf(
" --left-input (mtx filename) -- Left-hand side matrix input "
"file name\n"
" --right-input (mtx filename) -- Right-hand side matrix input "
"file name\n"
" --input-begin (num) -- First matrix row/column to be read\n"
" --input-end (num) -- Last matrix row/column to be read + 1\n"
" --n (num) -- Problem dimension\n"
" --generalized -- Generate a generalized problem\n"
" --decouple (num) -- Decouple the problem\n"
" --set-to-inf (num) -- Place infinities\n"
);
init_helper_print_usage("", INIT_HELPER_BLACS_PENCIL, argc, argv);
}
static void generic_initializer_print_args(int argc, char * const *argv)
{
char const *left_input = read_str("--left-input", argc, argv, NULL, NULL);
char const *right_input = read_str("--right-input", argc, argv, NULL, NULL);
if (left_input != NULL) {
printf(" --left-input %s", left_input);
if (right_input)
printf(" --right-input %s", right_input);
int input_begin = read_int("--input-begin", argc, argv, NULL, -1);
int input_end = read_int("--input-end", argc, argv, NULL, -1);
if (0 <= input_begin && 0 <= input_end)
printf(" --input-begin %d --input-end %d", input_begin, input_end);
}
else {
printf(" --n %d", read_int("--n", argc, argv, NULL, -1));
if (read_opt("--generalized", argc, argv, NULL))
printf(" --generalized");
}
printf(" --decouple %d", read_int("--decouple", argc, argv, NULL, 0));
printf(" --set-to-inf %d", read_int("--set-to-inf", argc, argv, NULL, 0));
init_helper_print_args("", INIT_HELPER_BLACS_PENCIL, argc, argv);
}
static int generic_initializer_check_args(
int argc, char * const *argv, int *argr)
{
char const *left_input = read_str("--left-input", argc, argv, argr, NULL);
char const *right_input = read_str("--right-input", argc, argv, argr, NULL);
if (left_input != NULL) {
if (access(left_input, R_OK) != 0) {
fprintf(stderr, "Left-hand side input file does not exists.\n");
return 1;
}
int input_begin = read_int("--input-begin", argc, argv, argr, -1);
int input_end = read_int("--input-end", argc, argv, argr, -1);
if (input_begin < 0 && input_end < input_begin)
return 1;
}
else if (right_input != NULL) {
fprintf(stderr, "Left-hand side input filename is missing.\n");
return 1;
}
else {
if (read_int("--n", argc, argv, argr, -1) < 1)
return 1;
read_opt("--generalized", argc, argv, argr);
}
if (read_int("--decouple", argc, argv, argr, 0) < 0)
return 1;
if (read_int("--set-to-inf", argc, argv, argr, 0) < 0)
return 1;
return init_helper_check_args(
"", INIT_HELPER_BLACS_PENCIL, argc, argv, argr);
}
static struct hook_data_env* lapack_initializer_init(
hook_data_format_t format, int argc, char * const *argv)
{
printf("INIT...\n");
int n = read_int("--n", argc, argv, NULL, -1);
char const *left_input = read_str("--left-input", argc, argv, NULL, NULL);
char const *right_input = read_str("--right-input", argc, argv, NULL, NULL);
int input_begin = read_int("--input-begin", argc, argv, NULL, -1);
int input_end = read_int("--input-end", argc, argv, NULL, -1);
int generalized = read_opt("--generalized", argc, argv, NULL);
int decouple = read_int("--decouple", argc, argv, NULL, 0);
int set_to_inf = read_int("--set-to-inf", argc, argv, NULL, 0);
if (left_input != NULL) {
int m;
read_mtx_dimensions_from_file(left_input, &m, &n);
}
if (input_begin == -1)
input_begin = 0;
if (input_end == -1)
input_end = n;
init_helper_t helper = init_helper_init_hook(
"", format, n, n, PREC_DOUBLE | NUM_REAL, argc, argv);
struct hook_data_env *env = malloc(sizeof(struct hook_data_env));
env->format = HOOK_DATA_FORMAT_PENCIL_LOCAL;
env->copy_data = (hook_data_env_copy_t) copy_pencil;
env->free_data = (hook_data_env_free_t) free_pencil;
pencil_t data = env->data = data = init_pencil();
// initialize A
if (left_input != NULL)
data->mat_a = read_mtx_sub_matrix_from_file(
input_begin, input_end, left_input, helper);
else
data->mat_a = generate_random_fullpos(n, n, helper);
// initialize B
if (right_input != NULL) {
generalized = 1;
data->mat_b = read_mtx_sub_matrix_from_file(
input_begin, input_end, right_input, helper);
}
else if (generalized) {
data->mat_b = generate_random_fullpos(n, n, helper);
}
// initialize Q and Z
data->mat_q = generate_identity(n, n, helper);
if (generalized)
data->mat_z = generate_identity(n, n, helper);
// prepare for decoupling
if (decouple < 1) {
data->mat_ca = copy_matrix_descr(data->mat_a);
data->mat_cb = copy_matrix_descr(data->mat_b);
}
// reduce
hook_solver_state_t state =
hessenberg_lapack_solver.prepare(argc, argv, env);
hessenberg_lapack_solver.run(state);
hessenberg_lapack_solver.finalize(state, env);
if (0 < decouple || 0 < set_to_inf)
deflate_and_place_infinities(decouple, set_to_inf, data);
init_helper_free(helper);
printf("INIT FINISHED.\n");
return env;
}
static struct hook_data_env* starpu_initializer_init(
hook_data_format_t format, int argc, char * const *argv)
{
printf("INIT...\n");
int n = read_int("--n", argc, argv, NULL, -1);
char const *left_input = read_str("--left-input", argc, argv, NULL, NULL);
char const *right_input = read_str("--right-input", argc, argv, NULL, NULL);
int input_begin = read_int("--input-begin", argc, argv, NULL, -1);
int input_end = read_int("--input-end", argc, argv, NULL, -1);
int generalized = read_opt("--generalized", argc, argv, NULL);
int decouple = read_int("--decouple", argc, argv, NULL, 0);
int set_to_inf = read_int("--set-to-inf", argc, argv, NULL, 0);
if (left_input != NULL) {
int m;
read_mtx_dimensions_from_file(left_input, &m, &n);
}
init_helper_t helper =
init_helper_init_hook("", format, n, n, PREC_DOUBLE | NUM_REAL, argc, argv);
struct hook_data_env *env = malloc(sizeof(struct hook_data_env));
env->format = format;
env->copy_data = (hook_data_env_copy_t) copy_pencil;
env->free_data = (hook_data_env_free_t) free_pencil;
pencil_t data = env->data = data = init_pencil();
// initialize A
if (left_input != NULL) {
if (0 <= input_begin)
data->mat_a = read_mtx_sub_matrix_from_file(
input_begin, input_end, left_input, helper);
else
data->mat_a = read_mtx_matrix_from_file(left_input, helper);
}
else {
data->mat_a = generate_random_fullpos(n, n, helper);
}
// initialize B
if (right_input != NULL) {
generalized = 1;
if (0 <= input_begin)
data->mat_b = read_mtx_sub_matrix_from_file(
input_begin, input_end, right_input, helper);
else
data->mat_b = read_mtx_matrix_from_file(right_input, helper);
}
else if (generalized) {
data->mat_b = generate_random_fullpos(n, n, helper);
}
// initialize Q and Z
data->mat_q = generate_identity(n, n, helper);
if (generalized)
data->mat_z = generate_identity(n, n, helper);
// prepare for decoupling
if (decouple < 1 && set_to_inf < 1) {
data->mat_ca = copy_matrix_descr(data->mat_a);
data->mat_cb = copy_matrix_descr(data->mat_b);
}
// reduce
if (format == HOOK_DATA_FORMAT_PENCIL_LOCAL) {
starneig_node_init(threads_get_workers(), STARNEIG_USE_ALL,
STARNEIG_HINT_SM | STARNEIG_FXT_DISABLE);
if (generalized)
starneig_GEP_SM_HessenbergTriangular(LOCAL_MATRIX_N(data->mat_a),
LOCAL_MATRIX_PTR(data->mat_a), LOCAL_MATRIX_LD(data->mat_a),
LOCAL_MATRIX_PTR(data->mat_b), LOCAL_MATRIX_LD(data->mat_b),
LOCAL_MATRIX_PTR(data->mat_q), LOCAL_MATRIX_LD(data->mat_q),
LOCAL_MATRIX_PTR(data->mat_z), LOCAL_MATRIX_LD(data->mat_z));
else
starneig_SEP_SM_Hessenberg(LOCAL_MATRIX_N(data->mat_a),
LOCAL_MATRIX_PTR(data->mat_a), LOCAL_MATRIX_LD(data->mat_a),
LOCAL_MATRIX_PTR(data->mat_q), LOCAL_MATRIX_LD(data->mat_q));
starneig_node_finalize();
}
#ifdef STARNEIG_ENABLE_BLACS
if (format == HOOK_DATA_FORMAT_PENCIL_BLACS) {
starneig_node_init(threads_get_workers(), STARNEIG_USE_ALL,
STARNEIG_HINT_DM | STARNEIG_FXT_DISABLE);
if (generalized)
starneig_GEP_DM_HessenbergTriangular(
STARNEIG_MATRIX_HANDLE(data->mat_a),
STARNEIG_MATRIX_HANDLE(data->mat_b),
STARNEIG_MATRIX_HANDLE(data->mat_q),
STARNEIG_MATRIX_HANDLE(data->mat_z));
else
starneig_SEP_DM_Hessenberg(
STARNEIG_MATRIX_HANDLE(data->mat_a),
STARNEIG_MATRIX_HANDLE(data->mat_q));
starneig_node_finalize();
}
#endif
if (0 < decouple || 0 < set_to_inf)
deflate_and_place_infinities(decouple, set_to_inf, data);
init_helper_free(helper);
printf("INIT FINISHED.\n");
return env;
}
static const struct hook_initializer_t lapack_initializer = {
.name = "lapack",
.desc =
"Reduces a matrix pencil to upper Hessenberg / Hessenberg-triangular "
"form using a LAPACK algorithm",
.formats = (hook_data_format_t[]) { HOOK_DATA_FORMAT_PENCIL_LOCAL, 0 },
.print_usage = &generic_initializer_print_usage,
.print_args = &generic_initializer_print_args,
.check_args = &generic_initializer_check_args,
.init = &lapack_initializer_init
};
static const struct hook_initializer_t starpu_initializer = {
.name = "starneig",
.desc =
"Reduces a matrix pencil to upper Hessenberg / Hessenberg-triangular "
"form using a StarPU based parallel algorithm",
.formats = (hook_data_format_t[]) {
HOOK_DATA_FORMAT_PENCIL_LOCAL,
#ifdef STARNEIG_ENABLE_BLACS
HOOK_DATA_FORMAT_PENCIL_BLACS,
#endif
0 },
.print_usage = &generic_initializer_print_usage,
.print_args = &generic_initializer_print_args,
.check_args = &generic_initializer_check_args,
.init = &starpu_initializer_init
};
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
static void print_usage(int argc, char * const *argv)
{
print_avail_complex_distr();
print_opt_complex_distr();
}
const struct hook_experiment_descr schur_experiment = {
.print_usage = &print_usage,
.initializers = (struct hook_initializer_t const *[])
{
#ifdef GSL_FOUND
&hessrand_initializer,
#endif
&starpu_initializer,
&lapack_initializer,
&random_initializer,
&known_initializer,
&mtx_initializer,
&raw_initializer,
0
},
.supplementers = (struct hook_supplementer_t const *[])
{
0
},
.solvers = (struct hook_solver const *[])
{
&schur_starpu_solver,
&schur_starpu_simple_solver,
&schur_lapack_solver,
#ifdef PDLAHQR_FOUND
&schur_pdlahqr_solver,
#endif
#ifdef PDHSEQR_FOUND
&schur_pdhseqr_solver,
#endif
#ifdef CUSTOM_PDHSEQR
&schur_custom_pdhseqr_solver,
#endif
#ifdef PDHGEQZ_FOUND
&schur_pdhgeqz_solver,
#endif
0
},
.hook_descrs = (struct hook_descr_t const *[])
{
&default_schur_test_descr,
&default_eigenvalues_descr,
&default_known_eigenvalues_descr,
&default_analysis_descr,
&default_residual_test_descr,
&default_print_pencil_descr,
&default_print_input_pencil_descr,
&default_store_raw_pencil_descr,
&default_store_raw_input_pencil_descr,
0
}
};
| {
"alphanum_fraction": 0.6254889179,
"avg_line_length": 32.0920502092,
"ext": "c",
"hexsha": "5e3f70598091e5d3f3e47dc8c51a207524c7723e",
"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": "test/schur/experiment.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": "test/schur/experiment.c",
"max_line_length": 84,
"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": "test/schur/experiment.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": 7993,
"size": 30680
} |
/* specfunc/test_sf.h
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 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 */
#ifndef TEST_SF_H
#define TEST_SF_H
#include <gsl/gsl_math.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_machine.h>
#include <gsl/gsl_sf_result.h>
double test_sf_frac_diff(double x1, double x2);
int test_sf_check_result(char * message_buff, gsl_sf_result r, double val, double tol);
int test_sf_check_val(char * message_buff, double rval, double val, double tol);
int test_sf_check_return(char * message_buff, int val_return, int expected_return);
int test_sf_check_result_relax(char * message_buff, gsl_sf_result r, double val, double tol);
/* Include an overall test factor to allow for differences between
compilers, otherwise there are too many bug reports on the released
versions. Turn this value down to 1.0 for development purposes */
#ifndef TEST_FACTOR
#ifdef RELEASED
#define TEST_FACTOR 100.0
#else
#define TEST_FACTOR 1.0
#endif
#endif
#ifndef TEST_SIGMA
#ifdef RELEASED
#define TEST_SIGMA 1.5
#else
#define TEST_SIGMA 1.0
#endif
#endif
#define TEST_TOL0 (2.0*GSL_DBL_EPSILON)
#define TEST_TOL1 (16.0*GSL_DBL_EPSILON)
#define TEST_TOL2 (256.0*GSL_DBL_EPSILON)
#define TEST_TOL3 (2048.0*GSL_DBL_EPSILON)
#define TEST_TOL4 (16384.0*GSL_DBL_EPSILON)
#define TEST_TOL5 (131072.0*GSL_DBL_EPSILON)
#define TEST_TOL6 (1048576.0*GSL_DBL_EPSILON)
#define TEST_SQRT_TOL0 (2.0*GSL_SQRT_DBL_EPSILON)
#define TEST_SNGL (1.0e-06)
#define TEST_SF_INCONS 1
#define TEST_SF_ERRNEG 2
#define TEST_SF_TOLBAD 4
#define TEST_SF_RETBAD 8
#define TEST_SF_ERRBAD 16
#define TEST_SF_ERRBIG 32
#define TEST_SF_EXPBAD 64
int test_sf (gsl_sf_result r, double val_in, double tol, int status, int expect_return, const char * desc);
int test_sf_e10 (gsl_sf_result_e10 r, double val_in, int e10_in, double tol, int status, int expect_return, const char * desc);
int test_sf_val (double val, double val_in, double tol, const char * desc);
int test_sf_rlx (gsl_sf_result r, double val_in, double tol, int status, int expect_return, const char * desc);
int test_sf_2 (gsl_sf_result r1, double val1, double tol1, gsl_sf_result r2, double val2, double tol2, int status, int expect_return, const char * desc);
int test_sf_sgn (gsl_sf_result r, double sgn, double val_in, double tol, double expect_sgn, int status, int expect_return, const char * desc);
int test_sf_return (int status, int expect_return, const char * desc);
#define TEST_SF(stat, func, args, val_in, tol, expect_return) { int status = func args; stat += test_sf(r, val_in, tol, status, expect_return, #func #args); }
#define TEST_SF_E10(stat, func, args, val_in, e10_in, tol, expect_return) { int status = func args; stat += test_sf_e10(re, val_in, e10_in, tol, status, expect_return, #func #args); }
#define TEST_SF_VAL(stat, func, args, val_in, tol) { double val = func args; stat += test_sf_val(val, val_in, tol, #func #args); }
#define TEST_SF_RLX(stat, func, args, val_in, tol, expect_return) { int status = func args; stat += test_sf_rlx(r, val_in, tol, status, expect_return, #func #args); }
#define TEST_SF_2(stat, func, args, val1, tol1, val2, tol2, expect_return) { int status = func args; stat += test_sf_2(r1, val1, tol1, r2, val2, tol2, status, expect_return, #func #args); }
#define TEST_SF_SGN(stat, func, args, val_in, tol, expect_sgn, expect_return) { int status = func args; stat += test_sf_sgn(r, sgn, val_in, tol, expect_sgn, status, expect_return, #func #args); }
#define TEST_SF_THETA(stat, func, args, val_in, tol) { int status; theta=args; status = func (&theta); stat += test_sf_val(theta, val_in, tol, #func #args); }
#define TEST_SF_RETURN(stat, func, args, expect_return) { int status = func args; stat += test_sf_return(status, expect_return, #func #args); }
int test_airy(void);
int test_bessel(void);
int test_coulomb(void);
int test_dilog(void);
int test_gamma(void);
int test_mathieu(void);
int test_hermite(void);
int test_hyperg(void);
int test_legendre(void);
int test_sincos_pi(void);
#endif /* !TEST_SF_H */
| {
"alphanum_fraction": 0.751830927,
"avg_line_length": 42.6696428571,
"ext": "h",
"hexsha": "45c73d092b3819540e9129d32f963bf8fde7909a",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z",
"max_forks_repo_head_hexsha": "83fd1fc4cbd053a4f9b673d5cd5841823ddd4d8b",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "karanbirsandhu/nu-sense",
"max_forks_repo_path": "test/lib/gsl-2.6/specfunc/test_sf.h",
"max_issues_count": 6,
"max_issues_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a",
"max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z",
"max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "ielomariala/Hex-Game",
"max_issues_repo_path": "gsl-2.6/specfunc/test_sf.h",
"max_line_length": 195,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "ielomariala/Hex-Game",
"max_stars_repo_path": "gsl-2.6/specfunc/test_sf.h",
"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": 1392,
"size": 4779
} |
#include <gsl/gsl_ntuple.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
struct data
{
double x;
double y;
double z;
};
int
main (void)
{
const gsl_rng_type * T;
gsl_rng * r;
struct data ntuple_row;
int i;
gsl_ntuple *ntuple
= gsl_ntuple_create ("test.dat", &ntuple_row,
sizeof (ntuple_row));
gsl_rng_env_setup ();
T = gsl_rng_default;
r = gsl_rng_alloc (T);
for (i = 0; i < 10000; i++)
{
ntuple_row.x = gsl_ran_ugaussian (r);
ntuple_row.y = gsl_ran_ugaussian (r);
ntuple_row.z = gsl_ran_ugaussian (r);
gsl_ntuple_write (ntuple);
}
gsl_ntuple_close (ntuple);
gsl_rng_free (r);
return 0;
}
| {
"alphanum_fraction": 0.6056338028,
"avg_line_length": 16.1363636364,
"ext": "c",
"hexsha": "82f6fa483b3a5769aab377a16672a009296ca4ec",
"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/ntuplew.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/ntuplew.c",
"max_line_length": 50,
"max_stars_count": 64,
"max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "manggoguy/parsec-modified",
"max_stars_repo_path": "pkgs/libs/gsl/src/doc/examples/ntuplew.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": 230,
"size": 710
} |
/* rng/ranlxd.c
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000 James Theiler, Brian Gough
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <config.h>
#include <stdlib.h>
#include <gsl/gsl_rng.h>
/* This is an implementation of Martin Luescher's second generation
double-precision (48-bit) version of the RANLUX generator.
Thanks to Martin Luescher for providing information on this
generator.
*/
static inline unsigned long int ranlxd_get (void *vstate);
static double ranlxd_get_double (void *vstate);
static void ranlxd_set_lux (void *state, unsigned long int s, unsigned int luxury);
static void ranlxd1_set (void *state, unsigned long int s);
static void ranlxd2_set (void *state, unsigned long int s);
static const int next[12] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 0};
static const double one_bit = 1.0 / 281474976710656.0; /* 1/2^48 */
#define RANLUX_STEP(x1,x2,i1,i2,i3) \
x1=xdbl[i1] - xdbl[i2]; \
if (x2 < 0) \
{ \
x1-=one_bit; \
x2+=1; \
} \
xdbl[i3]=x2
typedef struct
{
double xdbl[12];
double carry;
unsigned int ir;
unsigned int jr;
unsigned int ir_old;
unsigned int pr;
}
ranlxd_state_t;
static inline void increment_state (ranlxd_state_t * state);
static inline void
increment_state (ranlxd_state_t * state)
{
int k, kmax;
double y1, y2, y3;
double *xdbl = state->xdbl;
double carry = state->carry;
unsigned int ir = state->ir;
unsigned int jr = state->jr;
for (k = 0; ir > 0; ++k)
{
y1 = xdbl[jr] - xdbl[ir];
y2 = y1 - carry;
if (y2 < 0)
{
carry = one_bit;
y2 += 1;
}
else
{
carry = 0;
}
xdbl[ir] = y2;
ir = next[ir];
jr = next[jr];
}
kmax = state->pr - 12;
for (; k <= kmax; k += 12)
{
y1 = xdbl[7] - xdbl[0];
y1 -= carry;
RANLUX_STEP (y2, y1, 8, 1, 0);
RANLUX_STEP (y3, y2, 9, 2, 1);
RANLUX_STEP (y1, y3, 10, 3, 2);
RANLUX_STEP (y2, y1, 11, 4, 3);
RANLUX_STEP (y3, y2, 0, 5, 4);
RANLUX_STEP (y1, y3, 1, 6, 5);
RANLUX_STEP (y2, y1, 2, 7, 6);
RANLUX_STEP (y3, y2, 3, 8, 7);
RANLUX_STEP (y1, y3, 4, 9, 8);
RANLUX_STEP (y2, y1, 5, 10, 9);
RANLUX_STEP (y3, y2, 6, 11, 10);
if (y3 < 0)
{
carry = one_bit;
y3 += 1;
}
else
{
carry = 0;
}
xdbl[11] = y3;
}
kmax = state->pr;
for (; k < kmax; ++k)
{
y1 = xdbl[jr] - xdbl[ir];
y2 = y1 - carry;
if (y2 < 0)
{
carry = one_bit;
y2 += 1;
}
else
{
carry = 0;
}
xdbl[ir] = y2;
ir = next[ir];
jr = next[jr];
}
state->ir = ir;
state->ir_old = ir;
state->jr = jr;
state->carry = carry;
}
static inline unsigned long int
ranlxd_get (void *vstate)
{
return ranlxd_get_double (vstate) * 4294967296.0; /* 2^32 */
}
static double
ranlxd_get_double (void *vstate)
{
ranlxd_state_t *state = (ranlxd_state_t *) vstate;
int ir = state->ir;
state->ir = next[ir];
if (state->ir == state->ir_old)
increment_state (state);
return state->xdbl[state->ir];
}
static void
ranlxd_set_lux (void *vstate, unsigned long int s, unsigned int luxury)
{
ranlxd_state_t *state = (ranlxd_state_t *) vstate;
int ibit, jbit, i, k, l, xbit[31];
double x, y;
long int seed;
if (s == 0)
s = 1; /* default seed is 1 */
seed = s;
i = seed & 0xFFFFFFFFUL;
for (k = 0; k < 31; ++k)
{
xbit[k] = i % 2;
i /= 2;
}
ibit = 0;
jbit = 18;
for (k = 0; k < 12; ++k)
{
x = 0;
for (l = 1; l <= 48; ++l)
{
y = (double) ((xbit[ibit] + 1) % 2);
x += x + y;
xbit[ibit] = (xbit[ibit] + xbit[jbit]) % 2;
ibit = (ibit + 1) % 31;
jbit = (jbit + 1) % 31;
}
state->xdbl[k] = one_bit * x;
}
state->carry = 0;
state->ir = 11;
state->jr = 7;
state->ir_old = 0;
state->pr = luxury;
}
static void
ranlxd1_set (void *vstate, unsigned long int s)
{
ranlxd_set_lux (vstate, s, 202);
}
static void
ranlxd2_set (void *vstate, unsigned long int s)
{
ranlxd_set_lux (vstate, s, 397);
}
static const gsl_rng_type ranlxd1_type =
{"ranlxd1", /* name */
0xffffffffUL, /* RAND_MAX */
0, /* RAND_MIN */
sizeof (ranlxd_state_t),
&ranlxd1_set,
&ranlxd_get,
&ranlxd_get_double};
static const gsl_rng_type ranlxd2_type =
{"ranlxd2", /* name */
0xffffffffUL, /* RAND_MAX */
0, /* RAND_MIN */
sizeof (ranlxd_state_t),
&ranlxd2_set,
&ranlxd_get,
&ranlxd_get_double};
const gsl_rng_type *gsl_rng_ranlxd1 = &ranlxd1_type;
const gsl_rng_type *gsl_rng_ranlxd2 = &ranlxd2_type;
| {
"alphanum_fraction": 0.5786651877,
"avg_line_length": 21.636,
"ext": "c",
"hexsha": "233ca31a4d9b757ef62d5237b4881da8dbb9c208",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2015-10-02T01:32:59.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-10-02T01:32:59.000Z",
"max_forks_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "ICML14MoMCompare/spectral-learn",
"max_forks_repo_path": "code/em/treba/gsl-1.0/rng/ranlxd.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "ICML14MoMCompare/spectral-learn",
"max_issues_repo_path": "code/em/treba/gsl-1.0/rng/ranlxd.c",
"max_line_length": 83,
"max_stars_count": 14,
"max_stars_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "ICML14MoMCompare/spectral-learn",
"max_stars_repo_path": "code/em/treba/gsl-1.0/rng/ranlxd.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": 1953,
"size": 5409
} |
/* integration/qaws.c
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Brian Gough
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include <config.h>
#include <math.h>
#include <float.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_integration.h>
#include "initialise.c"
#include "append.c"
#include "qpsrt.c"
#include "util.c"
#include "qc25s.c"
int
gsl_integration_qaws (gsl_function * f,
const double a, const double b,
gsl_integration_qaws_table * t,
const double epsabs, const double epsrel,
const size_t limit,
gsl_integration_workspace * workspace,
double *result, double *abserr)
{
double area, errsum;
double result0, abserr0;
double tolerance;
size_t iteration = 0;
int roundoff_type1 = 0, roundoff_type2 = 0, error_type = 0;
/* Initialize results */
initialise (workspace, a, b);
*result = 0;
*abserr = 0;
if (limit > workspace->limit)
{
GSL_ERROR ("iteration limit exceeds available workspace", GSL_EINVAL) ;
}
if (b <= a)
{
GSL_ERROR ("limits must form an ascending sequence, a < b", GSL_EINVAL) ;
}
if (epsabs <= 0 && (epsrel < 50 * GSL_DBL_EPSILON || epsrel < 0.5e-28))
{
GSL_ERROR ("tolerance cannot be acheived with given epsabs and epsrel",
GSL_EBADTOL);
}
/* perform the first integration */
{
double area1, area2;
double error1, error2;
int err_reliable1, err_reliable2;
double a1 = a;
double b1 = 0.5 * (a + b);
double a2 = b1;
double b2 = b;
qc25s (f, a, b, a1, b1, t, &area1, &error1, &err_reliable1);
qc25s (f, a, b, a2, b2, t, &area2, &error2, &err_reliable2);
if (error1 > error2)
{
append_interval (workspace, a1, b1, area1, error1);
append_interval (workspace, a2, b2, area2, error2);
}
else
{
append_interval (workspace, a2, b2, area2, error2);
append_interval (workspace, a1, b1, area1, error1);
}
result0 = area1 + area2;
abserr0 = error1 + error2;
}
/* Test on accuracy */
tolerance = GSL_MAX_DBL (epsabs, epsrel * fabs (result0));
/* Test on accuracy, use 0.01 relative error as an extra safety
margin on the first iteration (ignored for subsequent iterations) */
if (abserr0 < tolerance && abserr0 < 0.01 * fabs(result0))
{
*result = result0;
*abserr = abserr0;
return GSL_SUCCESS;
}
else if (limit == 1)
{
*result = result0;
*abserr = abserr0;
GSL_ERROR ("a maximum of one iteration was insufficient", GSL_EMAXITER);
}
area = result0;
errsum = abserr0;
iteration = 2;
do
{
double a1, b1, a2, b2;
double a_i, b_i, r_i, e_i;
double area1 = 0, area2 = 0, area12 = 0;
double error1 = 0, error2 = 0, error12 = 0;
int err_reliable1, err_reliable2;
/* Bisect the subinterval with the largest error estimate */
retrieve (workspace, &a_i, &b_i, &r_i, &e_i);
a1 = a_i;
b1 = 0.5 * (a_i + b_i);
a2 = b1;
b2 = b_i;
qc25s (f, a, b, a1, b1, t, &area1, &error1, &err_reliable1);
qc25s (f, a, b, a2, b2, t, &area2, &error2, &err_reliable2);
area12 = area1 + area2;
error12 = error1 + error2;
errsum += (error12 - e_i);
area += area12 - r_i;
if (err_reliable1 && err_reliable2)
{
double delta = r_i - area12;
if (fabs (delta) <= 1.0e-5 * fabs (area12) && error12 >= 0.99 * e_i)
{
roundoff_type1++;
}
if (iteration >= 10 && error12 > e_i)
{
roundoff_type2++;
}
}
tolerance = GSL_MAX_DBL (epsabs, epsrel * fabs (area));
if (errsum > tolerance)
{
if (roundoff_type1 >= 6 || roundoff_type2 >= 20)
{
error_type = 2; /* round off error */
}
/* set error flag in the case of bad integrand behaviour at
a point of the integration range */
if (subinterval_too_small (a1, a2, b2))
{
error_type = 3;
}
}
update (workspace, a1, b1, area1, error1, a2, b2, area2, error2);
retrieve (workspace, &a_i, &b_i, &r_i, &e_i);
iteration++;
}
while (iteration < limit && !error_type && errsum > tolerance);
*result = sum_results (workspace);
*abserr = errsum;
if (errsum <= tolerance)
{
return GSL_SUCCESS;
}
else if (error_type == 2)
{
GSL_ERROR ("roundoff error prevents tolerance from being achieved",
GSL_EROUND);
}
else if (error_type == 3)
{
GSL_ERROR ("bad integrand behavior found in the integration interval",
GSL_ESING);
}
else if (iteration == limit)
{
GSL_ERROR ("maximum number of subdivisions reached", GSL_EMAXITER);
}
else
{
GSL_ERROR ("could not integrate function", GSL_EFAILED);
}
}
| {
"alphanum_fraction": 0.5831462614,
"avg_line_length": 26.2036199095,
"ext": "c",
"hexsha": "a358a580c1e388da5b15cad7068992e595fdfd0e",
"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/integration/qaws.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/integration/qaws.c",
"max_line_length": 81,
"max_stars_count": 14,
"max_stars_repo_head_hexsha": "2ad5bfb9c9684b1c800e96732a9e2f1e844b856f",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "ruslankuzmin/julia",
"max_stars_repo_path": "oldjuila/juliakernel/ext_libraries/gsl/integration/qaws.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": 1669,
"size": 5791
} |
/*
Copyright (C) 2008 Wei Dong <wdong@princeton.edu>. All Rights Reserved.
This file is part of LSHKIT.
LSHKIT 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.
LSHKIT 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 LSHKIT. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* \file fitdata.cpp
* \brief Gather statistics from dataset for MPLSH tuning.
*
* This program gahters statistical data from a small sample dataset
* for automatic MPLSH parameter tuning. It carries out the following
* steps:
* -# Sample N points from the dataset. Only those N points will be used for future computation.
* -# Sample P pairs of points from the sample, calculate the distance for each pair.
* -# Sample Q points from the sample as queries points.
* -# Divide the sample into F folds.
* -# For i = 1 to F, take i folds and run K-NN search, so the query points
* will be searched against sample datasets of N/F, 2N/F, ..., N/F points.
*
* The statistical data is printed to standard output after the progress display.
*
\verbatim
Allowed options:
-h [ --help ] produce help message.
-N [ -- ] arg (=0) number of points to use
-P [ -- ] arg (=50000) number of pairs to sample
-Q [ -- ] arg (=1000) number of queries to sample
-K [ -- ] arg (=100) search for K nearest neighbors
-F [ -- ] arg (=10) divide the sample to F folds
-D [ --data ] arg data file
\endverbatim
*/
#ifndef _MPLSH_FITDATA_H_
#define _MPLSH_FITDATA_H_
#include "logging.h"
#include <cstdlib>
#include <sstream>
#include <gsl/gsl_multifit.h>
namespace lshkit {
inline
bool is_good_value (double v) {
return ((v > -std::numeric_limits<double>::max()) &&
(v < std::numeric_limits<double>::max()));
}
inline
std::string FitData(const FloatMatrix& data,
unsigned N, // number of points to use
unsigned P, // number of pairs to sample
unsigned Q, // number of queries to sample
unsigned K, // search for K neighbors neighbors
unsigned F // divide the sample to F folds
)
{
LOG(LIB_INFO) << "started running FitData" << std::endl;
std::vector<unsigned> idx(data.getSize());
for (size_t i = 0; i < idx.size(); ++i) idx[i] = i;
std::random_shuffle(idx.begin(), idx.end());
if (N > 0 && N < static_cast<unsigned>(data.getSize())) idx.resize(N);
metric::l2sqr<float> l2sqr(data.getDim());
DefaultRng rng;
boost::variate_generator<DefaultRng &, UniformUnsigned> gen(rng,
UniformUnsigned(0, idx.size()-1));
double gM = 0.0;
double gG = 0.0;
{
// sample P pairs of points
for (unsigned k = 0; k < P; ++k)
{
double dist, logdist;
for (;;)
{
unsigned i = gen();
unsigned j = gen();
if (i == j) continue;
dist = l2sqr(data[idx[i]], data[idx[j]]);
logdist = log(dist);
if (is_good_value(logdist)) break;
}
gM += dist;
gG += logdist;
}
gM /= P;
gG /= P;
gG = exp(gG);
}
if (Q > idx.size()) Q = idx.size();
if (K > idx.size() - Q) K = idx.size() - Q;
/* sample query */
std::vector<unsigned> qry(Q);
SampleQueries(&qry, idx.size(), rng);
/* do the queries */
std::vector<Topk<unsigned> > topks(Q);
for (unsigned i = 0; i < Q; ++i) topks[i].reset(K);
/* ... */
gsl_matrix *X = gsl_matrix_alloc(F * K, 3);
gsl_vector *yM = gsl_vector_alloc(F * K);
gsl_vector *yG = gsl_vector_alloc(F * K);
gsl_vector *pM = gsl_vector_alloc(3);
gsl_vector *pG = gsl_vector_alloc(3);
gsl_matrix *cov = gsl_matrix_alloc(3,3);
std::vector<double> M(K);
std::vector<double> G(K);
unsigned m = 0;
for (unsigned l = 0; l < F; l++)
{
// Scan
for (unsigned i = l; i< idx.size(); i += F)
{
for (unsigned j = 0; j < Q; j++)
{
unsigned id = qry[j];
if (i != id)
{
float d = l2sqr(data[idx[id]], data[idx[i]]);
if (is_good_value(log(double(d))))
topks[j] << Topk<unsigned>::Element(i, d);
}
}
}
fill(M.begin(), M.end(), 0.0);
fill(G.begin(), G.end(), 0.0);
for (unsigned i = 0; i < Q; i++)
{
for (unsigned k = 0; k < K; k++)
{
M[k] += topks[i][k].dist;
G[k] += log(topks[i][k].dist);
}
}
for (unsigned k = 0; k < K; k++)
{
M[k] = log(M[k]/Q);
G[k] /= Q;
gsl_matrix_set(X, m, 0, 1.0);
gsl_matrix_set(X, m, 1, log(double(data.getSize() * (l + 1)) / double(F)));
gsl_matrix_set(X, m, 2, log(double(k + 1)));
gsl_vector_set(yM, m, M[k]);
gsl_vector_set(yG, m, G[k]);
++m;
}
//++progress;
}
gsl_multifit_linear_workspace *work = gsl_multifit_linear_alloc(F * K, 3);
double chisq;
gsl_multifit_linear(X, yM, pM, cov, &chisq, work);
gsl_multifit_linear(X, yG, pG, cov, &chisq, work);
std::stringstream ss;
ss << gM << " " << gG << std::endl;
ss << gsl_vector_get(pM, 0) << " "
<< gsl_vector_get(pM, 1) << " "
<< gsl_vector_get(pM, 2) << std::endl;
ss << gsl_vector_get(pG, 0) << " "
<< gsl_vector_get(pG, 1) << " "
<< gsl_vector_get(pG, 2) << std::endl;
gsl_matrix_free(X);
gsl_matrix_free(cov);
gsl_vector_free(pM);
gsl_vector_free(pG);
gsl_vector_free(yM);
gsl_vector_free(yG);
LOG(LIB_INFO) << ss.str();
LOG(LIB_INFO) << "finished FitData";
return ss.str();
}
} // namespace lshkit
#endif
| {
"alphanum_fraction": 0.5415313225,
"avg_line_length": 30.6398104265,
"ext": "h",
"hexsha": "c4db8a575d054e5d400daf0d9c8b6fb317973e66",
"lang": "C",
"max_forks_count": 42,
"max_forks_repo_forks_event_max_datetime": "2021-05-27T19:57:52.000Z",
"max_forks_repo_forks_event_min_datetime": "2016-05-18T05:53:00.000Z",
"max_forks_repo_head_hexsha": "44cdd81ab984c87c2246a0464a7ac93321c58815",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "sourabhpoddar404/nns_benchmark",
"max_forks_repo_path": "algorithms/NMSLIB/code/lshkit/include/lshkit/multiprobelsh-fitdata.h",
"max_issues_count": 7,
"max_issues_repo_head_hexsha": "44cdd81ab984c87c2246a0464a7ac93321c58815",
"max_issues_repo_issues_event_max_datetime": "2019-12-28T07:42:02.000Z",
"max_issues_repo_issues_event_min_datetime": "2016-06-03T13:43:21.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "sourabhpoddar404/nns_benchmark",
"max_issues_repo_path": "algorithms/NMSLIB/code/lshkit/include/lshkit/multiprobelsh-fitdata.h",
"max_line_length": 97,
"max_stars_count": 150,
"max_stars_repo_head_hexsha": "44cdd81ab984c87c2246a0464a7ac93321c58815",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "sourabhpoddar404/nns_benchmark",
"max_stars_repo_path": "algorithms/NMSLIB/code/lshkit/include/lshkit/multiprobelsh-fitdata.h",
"max_stars_repo_stars_event_max_datetime": "2021-05-24T05:32:56.000Z",
"max_stars_repo_stars_event_min_datetime": "2016-06-03T16:39:13.000Z",
"num_tokens": 1765,
"size": 6465
} |
/* ieee-utils/fp-tru64.c
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000 Tim Mooney
*
* 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.
*/
/*
* Under Compaq's Unix with the silly name, read the man pages for read_rnd,
* write_rnd, and ieee(3) for more information on the functions used here.
*
* Note that enabling control of dynamic rounding mode (via write_rnd) requires
* that you pass a special flag to your C compiler. For Compaq's C compiler
* the flag is `-fprm d', for gcc it's `-mfp-rounding-mode=d'.
*
* Enabling the trap control (via ieee_set_fp_control) also requires a
* flag be passed to the C compiler. The flag for Compaq's C compiler
* is `-ieee' and for gcc it's `-mieee'.
* We have not implemented the `inexact' case, since it is rarely used
* and requires the library being built with an additional compiler
* flag that can degrade performance for everything else. If you need
* to add support for `inexact' the relevant flag for Compaq's
* compiler is `-ieee_with_inexact', and the flag for gcc is
* `-mieee-with-inexact'.
*
* Problem have been reported with the "fixed" float.h installed with
* gcc-2.95 lacking some of the definitions in the system float.h (the
* symptoms are errors like: `FP_RND_RN' undeclared). To work around
* this we can include the system float.h before the gcc version, e.g.
*
* #include "/usr/include/float.h"
* #include <float.h>
*/
#include <float.h>
#ifndef FP_RND_RN
# undef _FLOAT_H_
# include "/usr/include/float.h"
# undef _FLOAT_H_
# include <float.h>
#endif
#include <machine/fpu.h>
#include <stdio.h>
#include <gsl/gsl_ieee_utils.h>
#include <gsl/gsl_errno.h>
int
gsl_ieee_set_mode (int precision, int rounding, int exception_mask)
{
unsigned long int mode = 0 ;
unsigned int rnd = 0 ;
/* I'm actually not completely sure that the alpha only supports default
* precisions rounding, but I couldn't find any information regarding this, so
* it seems safe to assume this for now until it's proven otherwise.
*/
switch (precision)
{
case GSL_IEEE_SINGLE_PRECISION:
GSL_ERROR ("Tru64 Unix on the alpha only supports default precision rounding",
GSL_EUNSUP) ;
break ;
case GSL_IEEE_DOUBLE_PRECISION:
GSL_ERROR ("Tru64 Unix on the alpha only supports default precision rounding",
GSL_EUNSUP) ;
break ;
case GSL_IEEE_EXTENDED_PRECISION:
GSL_ERROR ("Tru64 Unix on the alpha only supports default precision rounding",
GSL_EUNSUP) ;
break ;
}
switch (rounding)
{
case GSL_IEEE_ROUND_TO_NEAREST:
rnd = FP_RND_RN ;
write_rnd (rnd) ;
break ;
case GSL_IEEE_ROUND_DOWN:
rnd = FP_RND_RM ;
write_rnd (rnd) ;
break ;
case GSL_IEEE_ROUND_UP:
rnd = FP_RND_RP ;
write_rnd (rnd) ;
break ;
case GSL_IEEE_ROUND_TO_ZERO:
rnd = FP_RND_RZ ;
write_rnd (rnd) ;
break ;
default:
rnd = FP_RND_RN ;
write_rnd (rnd) ;
}
/* Turn on all the exceptions apart from 'inexact' */
/* from the ieee(3) man page:
* IEEE_TRAP_ENABLE_INV -> Invalid operation
* IEEE_TRAP_ENABLE_DZE -> Divide by 0
* IEEE_TRAP_ENABLE_OVF -> Overflow
* IEEE_TRAP_ENABLE_UNF -> Underflow
* IEEE_TRAP_ENABLE_INE -> Inexact (requires special option to C compiler)
* IEEE_TRAP_ENABLE_DNO -> denormal operand
* Note: IEEE_TRAP_ENABLE_DNO is not supported on OSF 3.x or Digital Unix
* 4.0 - 4.0d(?).
* IEEE_TRAP_ENABLE_MASK -> mask of all the trap enables
* IEEE_MAP_DMZ -> map denormal inputs to zero
* IEEE_MAP_UMZ -> map underflow results to zero
*/
mode = IEEE_TRAP_ENABLE_INV | IEEE_TRAP_ENABLE_DZE | IEEE_TRAP_ENABLE_OVF
| IEEE_TRAP_ENABLE_UNF ;
if (exception_mask & GSL_IEEE_MASK_INVALID)
mode &= ~ IEEE_TRAP_ENABLE_INV ;
if (exception_mask & GSL_IEEE_MASK_DENORMALIZED)
{
#ifdef IEEE_TRAP_ENABLE_DNO
mode &= ~ IEEE_TRAP_ENABLE_DNO ;
#else
GSL_ERROR ("Sorry, this version of Digital Unix does not support denormalized operands", GSL_EUNSUP) ;
#endif
}
if (exception_mask & GSL_IEEE_MASK_DIVISION_BY_ZERO)
mode &= ~ IEEE_TRAP_ENABLE_DZE ;
if (exception_mask & GSL_IEEE_MASK_OVERFLOW)
mode &= ~ IEEE_TRAP_ENABLE_OVF ;
if (exception_mask & GSL_IEEE_MASK_UNDERFLOW)
mode &= ~ IEEE_TRAP_ENABLE_UNF ;
if (exception_mask & GSL_IEEE_TRAP_INEXACT)
{
/* To implement this would require a special flag to the C
compiler which can cause degraded performance */
GSL_ERROR ("Sorry, GSL does not implement trap-inexact for Tru64 Unix on the alpha - see fp-tru64.c for details", GSL_EUNSUP) ;
/* In case you need to add it, the appropriate line would be
*
* mode |= IEEE_TRAP_ENABLE_INE ;
*
*/
}
else
{
mode &= ~ IEEE_TRAP_ENABLE_INE ;
}
ieee_set_fp_control (mode) ;
return GSL_SUCCESS ;
}
| {
"alphanum_fraction": 0.6763326966,
"avg_line_length": 32.5367231638,
"ext": "c",
"hexsha": "7feccd9ae38408026ff397fa3fd996a0d4c6aa81",
"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/ieee-utils/fp-tru64.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/ieee-utils/fp-tru64.c",
"max_line_length": 133,
"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/ieee-utils/fp-tru64.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": 1510,
"size": 5759
} |
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <math.h>
#include <gsl/gsl_integration.h>
double f1(double x, void *params) {
(void) (params); /* avoid unused parameter warning */
return pow(x, 2);
}
double fi1(double x) {
return pow(x, 3) / 3;
}
double f2(double x, void *params) {
(void) (params); /* avoid unused parameter warning */
if (0 == x) {
return 0;
}
return 1 / sqrt(x);
}
double fi2(double x) {
return 2 * sqrt(x);
}
double pi(double (*fi)(double), double x1, double x2) {
return fi(x2) - fi(x1);
}
double e(double p1, double p2) {
return fabs(p1 - p2);
}
int main(int argc, char *argv[]) {
double a, b, pg1, e1, pi1, pg2, e2, pi2;
if (argc < 2) {
errno = EINVAL;
perror("");
return errno;
}
a = strtod(argv[1], NULL);
b = strtod(argv[2], NULL);
if (0 != errno) {
perror("");
return errno;
}
gsl_integration_workspace *w1
= gsl_integration_workspace_alloc(1000);
gsl_function F1;
F1.function = &f1;
gsl_integration_qags(&F1, a, b, 0, 1e-7, 1000,
w1, &pg1, &e1);
pi1 = pi(fi1, a, b);
gsl_integration_workspace *w2
= gsl_integration_workspace_alloc(1000);
gsl_function F2;
F2.function = &f2;
gsl_integration_qags(&F2, a, b, 0, 1e-7, 1000,
w2, &pg2, &e2);
pi2 = pi(fi2, a, b);
printf("%f\t%f\n", pg1, pg2);
printf("%f\t%f\n", pi1, pi2);
printf("%e\t%e\n", e(pg1, pi1), e(pg2, pi2));
printf("%zu\t%zu\n", w1->size, w2->size);
gsl_integration_workspace_free(w1);
gsl_integration_workspace_free(w2);
return EXIT_SUCCESS;
}
| {
"alphanum_fraction": 0.557176196,
"avg_line_length": 24.1408450704,
"ext": "c",
"hexsha": "34b658de8ad7a7103fa47acc2e6d8d3bdcbeed08",
"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": "lab4/zad4.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": "lab4/zad4.c",
"max_line_length": 57,
"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": "lab4/zad4.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 550,
"size": 1714
} |
#include <gsl/gsl_math.h>
#include <gsl/gsl_cblas.h>
#include "cblas.h"
void
cblas_sger (const enum CBLAS_ORDER order, const int M, const int N,
const float alpha, const float *X, const int incX, const float *Y,
const int incY, float *A, const int lda)
{
#define BASE float
#include "source_ger.h"
#undef BASE
}
| {
"alphanum_fraction": 0.6795252226,
"avg_line_length": 24.0714285714,
"ext": "c",
"hexsha": "72c366d6777586e9aa83dd801e0834c47e258ad3",
"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/cblas/sger.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/cblas/sger.c",
"max_line_length": 78,
"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/cblas/sger.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": 98,
"size": 337
} |
/* ============================================================ *
* lensing.h *
* *
* Martin Kilbinger, Karim Benabed 2006-2012 *
* ============================================================ */
#ifndef __LENSING_H
#define __LENSING_H
#include <math.h>
#include <stdlib.h>
#include <stdio.h>
#include <assert.h>
#include <string.h>
#include <gsl/gsl_linalg.h>
#include <gsl/gsl_monte_plain.h>
#include <gsl/gsl_monte_miser.h>
#include <gsl/gsl_monte_vegas.h>
#include <gsl/gsl_rng.h>
#include "errorlist.h"
#include "maths.h"
#include "io.h"
#include "mvdens.h"
#include "par.h"
#include "hod.h"
#include "halomodel.h"
#include "cosmo.h"
#include "nofz.h"
#include "decomp_eb.h"
#include "reduced_fit.h"
/* Dimensions of interpolation tables */
/* N_s was increased from 200 to 400, for linear tabulation of P_kappa */
#define N_s 400
#define N_theta 100
/* Ranges of interpolation table for convergence power spectrum. *
* Power-law extrapolation outside these ranges. */
#define s_min 1.0e-2
#define s_max 1.0e6
/* Ranges of interpolation table for reduced-shear correction *
* power spectrum. No extrapolation outside these ranges. */
#define ELL_MIN_REDUCED 0.1
#define ELL_MAX_REDUCED 2.0e5
#define THETA_P_MIN_REDUCED (0.1*arcmin)
#define THETA_M_MIN_REDUCED (0.5*arcmin)
#define THETA_MAP_MIN_REDUCED (0.2*arcmin)
#define THETA_GSQR_MIN_REDUCED (0.1*arcmin)
#define THETA_MAPGAUSS_MIN_REDUCED (0.1*arcmin)
#define THETA_MAX_REDUCED (1000.0*arcmin)
#define NELL_REDUCED 50
#define lensing_base -1400
#define lensing_inconsistent -1 + lensing_base
#define lensing_baryon_fraction -2 + lensing_base
#define lensing_tomoij -3 + lensing_base
#define lensing_initialised -4 + lensing_base
#define lensing_unknown -5 + lensing_base
#define lensing_pm -6 + lensing_base
#define lensing_type -7 + lensing_base
#define lensing_fastxi -8 + lensing_base
#define lensing_nperm -9 + lensing_base
#define lensing_range -10 + lensing_base
#define lensing_cosebi_n_max -11 + lensing_base
#define lensing_ia -12 + lensing_base
#define lensing_angle_format -13 + lensing_base
#define lensing_nzbin -14 + lensing_base
/* If Ob/Oc > BARYON_FRAC, chi2 produces an error */
#define BARYON_FRAC 0.75
/* Intrinsic alignment, constant amplitude C_1 * rho_crit, *
* with C_1 = 5e-14 h^2 Mpc^3/M_sol. */
#define ia_c1_rho_crit 0.0134
typedef enum {xipm, xip, xim, map2poly, map2gauss, gsqr, decomp_eb, nofz, pkappa, map3gauss,
map3gauss_diag, map2gauss_map3gauss_diag, map2gauss_map3gauss,
decomp_eb_map3gauss_diag, decomp_eb_map3gauss}
lensdata_t;
#define slensdata_t(i) ( \
i==xipm ? "xipm" : \
i==xip ? "xip" : \
i==xim ? "xim" : \
i==map2poly ? "map2poly" : \
i==map2gauss ? "map2gauss" : \
i==gsqr ? "gsqr" : \
i==decomp_eb ? "decomp_eb" : \
i==nofz ? "nofz" : \
i==pkappa ? "pkappa" : \
i==map3gauss ? "map3gauss" : \
i==map3gauss_diag ? "map3gauss_diag" : \
i==map2gauss_map3gauss_diag ? "map2gauss_map3gauss_diag" : \
i==map2gauss_map3gauss ? "map2gauss_map3gauss" : \
i==decomp_eb_map3gauss_diag ? "decomp_eb_map3gauss_diag" : \
i==decomp_eb_map3gauss ? "decomp_eb_map3gauss" : \
"")
#define Nlensdata_t 15
typedef enum {decomp_eb_none, FK10_SN, FK10_FoM_eta10, FK10_FoM_eta50, COSEBIs_log} decomp_eb_filter_t;
#define sdecomp_eb_filter_t(i) ( \
i==decomp_eb_none ? "none" : \
i==FK10_SN ? "FK10_SN" : \
i==FK10_FoM_eta10 ? "FK10_FoM_eta10" : \
i==FK10_FoM_eta50 ? "FK10_FoM_eta50" : \
i==COSEBIs_log ? "COSEBIs_log" : \
"")
#define Ndecomp_eb_filter_t 5
/* The following arrays are defined in decomp_eb.c */
extern const double a_FK10_SN[], a_FK10_FoM_eta10[], a_FK10_FoM_eta50[];
// r_COSEB[];
typedef enum {angle_center, angle_mean, angle_wlinear, angle_wquadr} lensformat_t;
#define slensformat_t(i) ( \
i==angle_center ? "angle_center" : \
i==angle_mean ? "angle_mean" : \
i==angle_wlinear ? "angle_wlinear" : \
i==angle_wquadr ? "angle_wquadr" : \
"")
#define Nlensformat_t 4
typedef enum {cov_const, cov_ESH09} cov_scaling_t;
#define scov_scaling_t(i) ( \
i==cov_const ? "cov_const" : \
i==cov_ESH09 ? "cov_ESH09" : \
"__undef__")
#define Ncov_scaling_t 2
typedef enum {reduced_none, reduced_K10} reduced_t;
#define sreduced_t(i) ( \
i==reduced_none ? "none" : \
i==reduced_K10 ? "K10" : \
"")
#define Nreduced_t 2
/* Intrinsic alignment model */
typedef enum {ia_none, ia_HS04} ia_t;
#define sia_t(i) ( \
i==ia_none ? "none" : \
i==ia_HS04 ? "HS04" : \
"")
#define Nia_t 2
/* Bit-coded IA terms */
typedef enum {ia_undef, ia_GI_II, ia_only_GI, ia_only_II} ia_terms_t;
#define sia_terms_t(i) ( \
i==ia_undef ? "undef" : \
i==ia_GI_II ? "GI_II" : \
i==ia_only_GI ? "only_GI" : \
i==ia_only_II ? "only_II" : \
"")
#define Nia_terms_t 4
typedef enum {second_order=2, third_order=3} order_t;
typedef enum {tomo_all, tomo_auto_only, tomo_cross_only} tomo_t;
#define stomo_t(i) ( \
i==tomo_all ? "tomo_all" : \
i==tomo_auto_only ? "tomo_auto_only" : \
i==tomo_cross_only ? "tomo_cross_only" : \
"")
#define Ntomo_t 3
typedef struct {
int n_max;
double th_min, th_max;
char path[1024];
} cosebi_info_t;
typedef struct {
/* Basic cosmology */
cosmo *cosmo;
/* Redshift distribution(s) */
redshift_t *redshift;
/* Tomography type */
tomo_t tomo;
/* Reduced-shear correction */
reduced_t reduced;
double q_mag_size; /* q_mag_size = 2(alpha+beta-1), *
* alpha, beta: slopes of number density *
* with flux (alpha), size (beta) */
/* Intrinsic aligmnent */
ia_t ia;
double A_ia; /* IA amplitude */
ia_terms_t ia_terms; /* Bit-coded terms, GG=1, GI=2, II=4 */
/* Halomodel stuff (only initialised if cosmo->nonlinear=halodm) */
cosmo_hm *hm;
/* ============================================================ *
* Precomputed stuff. *
* ============================================================ */
interTable **g_source;
interTable **Pshear, **Pg1;
/* Shear second-order functions */
interTable **xiP, **xiM, **gamma, **map_gauss, **map_poly;
double *c_cosebi, psimin_cosebi, psimax_cosebi;
int N_cosebi;
} cosmo_lens;
typedef struct {
double r;
cosmo_lens* self;
} cosmo_lensANDdouble;
typedef struct {
int i;
double r;
cosmo_lens *self;
} cosmo_lensANDintANDdouble;
typedef struct {
int i, j;
double r;
cosmo_lens *self;
} cosmo_lensANDiid;
typedef struct {
int i, j, t;
double r;
cosmo_lens *self;
} cosmo_lensANDiiid;
typedef struct {
int i_bin, j_bin, pm, n;
const double *c;
double thmin;
cosmo_lens *self;
error **err;
} cosmo_lensANDextra;
typedef struct {
int Ntheta, Nzbin; /* Number of angular and redshift bins */
int Ntheta2; /* For combined 2nd and 3rd-order */
int Nzcorr; /* Number of z-correlations, Nzcorr=Nzbin*(Nzbin+1)/2 */
int n; /* Number of total entries in data vector, n=Ntheta*Nzcorr */
double *theta; /* n-dimensional vector of angular scales */
double *theta2; /* For angle_range lensformats: (theta,theta2) = (lower,upper) bin limits */
double *data; /* n-dimensional data vector */
double *var; /* n-dimensional vector with variance */
double *cov[3]; /* Maximum three nxn-dimensional covariance matrix */
double a1, a2; /* Coefficients for 'angle_wquadr' */
double lndetC;
int usecov;
lensdata_t type;
lensformat_t format;
order_t order;
decomp_eb_filter_t decomp_eb_filter;
cov_scaling_t cov_scaling;
cosmo_lens *fiducial; /* Needed for ESH09 cov scaling */
} datcov;
/* ============================================================ *
* Initialisation. *
* ============================================================ */
cosmo_lens *init_parameters_lens(double OMEGAM, double OMEGAV, double W0_DE, double W1_DE,
double *W_POLY_DE, int N_POLY_DE,
double H100, double OMEGAB, double OMEGANUMASS,
double NEFFNUMASS, double NORM, double NSPEC,
int Nzbin, const int *Nnz, const nofz_t *nofz, double *par_nz,
nonlinear_t NONLINEAR, transfer_t TRANSFER,
growth_t GROWTH, de_param_t DEPARAM,
norm_t normmode, tomo_t TOMO, reduced_t REDUCED, double Q_MAG_SIZE,
ia_t IA, ia_terms_t ia_terms, double A_IA, error **err);
void consistency_parameters_lens(const cosmo_lens *self, error **err);
cosmo_lens* copy_parameters_lens_only(cosmo_lens* source, error **err);
cosmo_lens* copy_parameters_lens(cosmo_lens* source, sm2_error **err);
void updateFrom_lens(cosmo_lens* avant, cosmo_lens* apres, error **err);
void copy_parameters_lenshm_cosmo(cosmo_lens *model, error **err);
void read_cosmological_parameters_lens(cosmo_lens **self, FILE *F, error **err);
cosmo_lens* set_cosmological_parameters_to_default_lens(error **err);
void free_parameters_lens(cosmo_lens** self);
void dump_param_lens(cosmo_lens* self, FILE *F, int wnofz, error **err);
/* ============================================================ *
* Lensing functions. *
* ============================================================ */
/* Projection */
double int_for_g(double aprime, void *intpar, error **err);
double g_source(cosmo_lens*, double a, int n_bin, error **err);
double G(cosmo_lens* self, double a, int n_bin, error **err);
double int_for_p_2(double a, void *intpar,error **err);
double P_NL_tot(cosmo_lens *self, double a, double k, error **err);
double Pshear(cosmo_lens *self, double a, int i_bin, int j_bin, error **err);
double P_projected_kappa(void *self, double l, int i_bin, int j_bin, error **err);
double int_over_P_kappa(cosmo_lens *self, funcwithpars int_for_p, void *intpar, error **err);
double int_for_p_GI(double a, void *intpar, error **err);
double int_for_p_II(double a, void *intpar, error **err);
/* Reduced-shear correction (K10) */
extern const int parameter[M_PAR];
cosmo *set_cosmological_parameters_to_WMAP7(const redshift_t *nofz, tomo_t tomo, error **err);
double *par_to_pointer(cosmo *self, par_t par, error **err);
void fill_dpar(cosmo *model, cosmo *wmap7, double *dpar, error **err);
double Fbar(cosmo_lens *self, double a, int m_bin, int n_bin, error **err);
void fill_Fbar_array(cosmo_lens *self, double *fbar, int m_bin, int n_bin, double amin, int N_a,
double da, error **err);
void fill_dFbar_dp_array(cosmo_lens *self, par_t par, double *dfbar_dp, int m_bin, int n_bin, double amin,
int N_a, double da, error **err);
double Pg1(cosmo_lens *self, double s, int i_bin, int j_bin, error **err);
/* Second-order shear functions */
double xi(cosmo_lens*, int pm, double theta, int i_bin, int j_bin, error **err);
double gamma2(cosmo_lens*, double theta, int i_bin, int j_bin, error **err);
double map2_poly(cosmo_lens*, double theta, int i_bin, int j_bin, error **err);
double map2_gauss(cosmo_lens*, double theta, int i_bin, int j_bin, error **err);
double RR(cosmo_lens *lens, double THETA_MIN, double THETA_MAX, const double *a, int N,
poly_t poly, int pm, error **err);
double E_cosebi(cosmo_lens *lens, int n, double Psimin, double Psimax, int i_bin, int j_bin,
const char *path, double *B_cosebi, error **err);
double RR_cosebi(cosmo_lens *lens, double THETA_MIN, double THETA_MAX, int i_bin, int j_bin,
int n, int pm, error **err);
double dRR_cosebi_dz_MC(double *z, int ndim, void *intpar);
double dRR_cosebi_dz(double z, void *intpar, error **err);
double int_for_map2_slow(double ell, void *intpar, error **err);
double map2_slow(cosmo_lens *self, double theta, tpstat_t tpstat, int i_bin, int j_bin, error **err);
/* Reading data files */
datcov *init_data_cov_tomo(char* dataname, char *dataname2, char** covname_ptr, lensdata_t type,
decomp_eb_filter_t decomp_eb_filter,
lensformat_t format, double corr_invcov,
double a1, double a2, order_t order,
cov_scaling_t cov_scaling, error **err);
datcov *init_datcov_for_cov_only(int Nzbin, int Ntheta, error **err);
void del_data_cov(datcov** dc);
void read_data_tomo(datcov *dc, char data_name[], int Nzbin, order_t order, error **err);
void read_cov_tomo(datcov* dc, char cov_name[], int icov, error **err);
void datcov2xipm(const datcov *dc, int i_bin, int j_bin, double **xip, double **xim, double **theta,
double **theta2, int *N, error **err);
//void read_cov(datcov* dc, char cov_name[], error **err);
void read_cov_col(datcov *dc, char cov_name[], error **err);
int get_pm(lensdata_t type, int i, int Ntheta, error **err);
int find_bin(double x, const double *list, int N, int prev, error **err);
void scale_cosmic_variance_ESH09(cosmo_lens *model, gsl_matrix *cov, const datcov *dc, error **err);
void scale_mixed_ESH09(const cosmo_lens *model, gsl_matrix *cov, const datcov *dc, error **err);
double lensing_signal(cosmo_lens *model, double theta, int i_bin, int j_bin, lensdata_t type,
decomp_eb_filter_t decomp_eb_filter, const cosebi_info_t *cosebi_info, error **err);
double chi2_lensing(cosmo_lens* csm, datcov* dc, int return_model, double **model_array, int *Nmodel,
const cosebi_info_t *cosebi_info, error **err);
/* Some third-order stuff which is called from lensing.c */
int Nperm_to_Ntheta(int Nperm, error **err);
void read_data_3rd(datcov *dc, char data_name[], int Nzbin, error **err);
void read_data_2nd_3rd(datcov *res, char *dataname, char *dataname2, error **err);
#define CHANGE(fct) int change_##fct(cosmo_lens*, cosmo_lens*)
CHANGE(g_source);
CHANGE(Pshear);
CHANGE(xi);
CHANGE(gamma2);
CHANGE(map2);
#undef CHANGE
#endif /* __LENSING_H */
| {
"alphanum_fraction": 0.6680115274,
"avg_line_length": 36.1458333333,
"ext": "h",
"hexsha": "704e979386ad38d8aa9a9bf11194a7e786e19faa",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "722db5bab850bccba3c7c003e0416cefa6d94c62",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "danielgruen/ccv",
"max_forks_repo_path": "src/nicaea_2.5/Cosmo/include/lensing.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "722db5bab850bccba3c7c003e0416cefa6d94c62",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "danielgruen/ccv",
"max_issues_repo_path": "src/nicaea_2.5/Cosmo/include/lensing.h",
"max_line_length": 106,
"max_stars_count": 2,
"max_stars_repo_head_hexsha": "722db5bab850bccba3c7c003e0416cefa6d94c62",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "danielgruen/ccv",
"max_stars_repo_path": "src/nicaea_2.5/Cosmo/include/lensing.h",
"max_stars_repo_stars_event_max_datetime": "2021-01-08T03:19:03.000Z",
"max_stars_repo_stars_event_min_datetime": "2017-08-11T20:38:17.000Z",
"num_tokens": 4198,
"size": 13880
} |
/* linalg/test_lu_band.c
*
* Copyright (C) 2020 Patrick Alken
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include <config.h>
#include <stdlib.h>
#include <gsl/gsl_test.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_ieee_utils.h>
#include <gsl/gsl_permute_vector.h>
#include <gsl/gsl_blas.h>
#include <gsl/gsl_linalg.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_permutation.h>
static int
test_LU_band_decomp_eps(const size_t p, const size_t q, const gsl_matrix * A, const double eps, const char * desc)
{
int s = 0;
const size_t M = A->size1;
const size_t N = A->size2;
const size_t minMN = GSL_MIN(M, N);
size_t i, j;
gsl_matrix * AB = gsl_matrix_alloc(N, 2*p + q + 1);
gsl_vector_uint * piv = gsl_vector_uint_alloc(minMN);
gsl_matrix * L = gsl_matrix_alloc(M, minMN);
gsl_matrix * U = gsl_matrix_alloc(minMN, N);
gsl_matrix * B = gsl_matrix_alloc(M, N);
/* convert A to packed banded format */
gen2band_matrix(p, q, A, AB);
s += gsl_linalg_LU_band_decomp(M, p, q, AB, piv);
s += gsl_linalg_LU_band_unpack(M, p, q, AB, piv, L, U);
/* compute B = L U */
gsl_blas_dgemm (CblasNoTrans, CblasNoTrans, 1.0, L, U, 0.0, B);
for (i = 0; i < M; ++i)
{
for (j = 0; j < N; ++j)
{
double aij = gsl_matrix_get(A, i, j);
double bij = gsl_matrix_get(B, i, j);
gsl_test_rel(bij, aij, eps, "%s (M=%lu,N=%lu)(p=%lu,q=%lu)[%lu,%lu]: %22.18g %22.18g\n",
desc, M, N, p, q, i, j, aij, bij);
}
}
gsl_matrix_free(AB);
gsl_vector_uint_free(piv);
gsl_matrix_free(L);
gsl_matrix_free(U);
gsl_matrix_free(B);
return s;
}
static int
test_LU_band_decomp(gsl_rng * r)
{
int s = 0;
const size_t N_max = 20;
gsl_matrix * A = gsl_matrix_alloc(N_max, N_max);
size_t M, N, p, q;
for (M = 1; M <= N_max; ++M)
{
for (N = 1; N <= N_max; ++N)
{
gsl_matrix_view m = gsl_matrix_submatrix(A, 0, 0, M, N);
for (p = 0; p < GSL_MIN(M, 10); ++p)
{
for (q = 0; q < GSL_MIN(N, 10); ++q)
{
create_band_matrix(p, q, &m.matrix, r);
s += test_LU_band_decomp_eps(p, q, &m.matrix, 1.0e5 * GSL_MAX(M,N) * GSL_DBL_EPSILON, "LU_band_decomp random");
}
}
}
}
gsl_matrix_free(A);
return s;
}
static int
test_LU_band_solve_eps(const size_t p, const size_t q, const gsl_matrix * A,
const gsl_vector * rhs, const gsl_vector * sol,
const double eps, const char * desc)
{
int s = 0;
const size_t N = A->size2;
size_t i;
gsl_matrix * AB = gsl_matrix_alloc(N, 2*p + q + 1);
gsl_vector_uint * piv = gsl_vector_uint_alloc(N);
gsl_matrix * L = gsl_matrix_alloc(N, N);
gsl_matrix * U = gsl_matrix_alloc(N, N);
gsl_vector * x = gsl_vector_alloc(N);
/* convert A to packed banded format */
gen2band_matrix(p, q, A, AB);
s += gsl_linalg_LU_band_decomp(N, p, q, AB, piv);
s += gsl_linalg_LU_band_solve(p, q, AB, piv, rhs, x);
for (i = 0; i < N; i++)
{
double xi = gsl_vector_get(x, i);
double yi = gsl_vector_get(sol, i);
gsl_test_rel(xi, yi, eps, "%s: %3lu[%lu]: %22.18g %22.18g\n",
desc, N, i, xi, yi);
}
gsl_matrix_free(AB);
gsl_vector_uint_free(piv);
gsl_matrix_free(L);
gsl_matrix_free(U);
gsl_vector_free(x);
return s;
}
static int
test_LU_band_solve(gsl_rng * r)
{
int s = 0;
const size_t N_max = 20;
gsl_matrix * A = gsl_matrix_alloc(N_max, N_max);
gsl_vector * b = gsl_vector_alloc(N_max);
gsl_vector * x = gsl_vector_alloc(N_max);
size_t N, p, q;
for (N = 1; N <= N_max; ++N)
{
gsl_matrix_view m = gsl_matrix_submatrix(A, 0, 0, N, N);
gsl_vector_view sol = gsl_vector_subvector(x, 0, N);
gsl_vector_view rhs = gsl_vector_subvector(b, 0, N);
for (p = 0; p < GSL_MIN(N, 10); ++p)
{
for (q = 0; q < GSL_MIN(N, 10); ++q)
{
create_band_matrix(p, q, &m.matrix, r);
create_random_vector(&sol.vector, r);
gsl_blas_dgemv(CblasNoTrans, 1.0, &m.matrix, &sol.vector, 0.0, &rhs.vector);
s += test_LU_band_solve_eps(p, q, &m.matrix, &rhs.vector, &sol.vector,
1.0e8 * N * GSL_DBL_EPSILON, "LU_band_solve random");
}
}
}
gsl_matrix_free(A);
gsl_vector_free(b);
gsl_vector_free(x);
return s;
}
| {
"alphanum_fraction": 0.6020526723,
"avg_line_length": 28.5303867403,
"ext": "c",
"hexsha": "f6b7c4c3cee4ec31a1551a4d936cec2439750305",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z",
"max_forks_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "zzpwahaha/Chimera-Control-Trim",
"max_forks_repo_path": "Chimera/3rd_Party/GSL_MSVC/linalg/test_lu_band.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "zzpwahaha/Chimera-Control-Trim",
"max_issues_repo_path": "Chimera/3rd_Party/GSL_MSVC/linalg/test_lu_band.c",
"max_line_length": 129,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "zzpwahaha/Chimera-Control-Trim",
"max_stars_repo_path": "Chimera/3rd_Party/GSL_MSVC/linalg/test_lu_band.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": 1617,
"size": 5164
} |
/*
* ht_neuron.h
*
* This file is part of NEST.
*
* Copyright (C) 2004 The NEST Initiative
*
* NEST is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version.
*
* NEST is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with NEST. If not, see <http://www.gnu.org/licenses/>.
*
*/
#ifndef HT_NEURON_H
#define HT_NEURON_H
// Generated includes:
#include "config.h"
#ifdef HAVE_GSL
// C++ includes:
#include <string>
#include <vector>
// C includes:
#include <gsl/gsl_errno.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_odeiv.h>
// Includes from nestkernel:
#include "archiving_node.h"
#include "connection.h"
#include "recordables_map.h"
#include "ring_buffer.h"
#include "universal_data_logger.h"
// Includes from sli:
#include "stringdatum.h"
/* BeginDocumentation
Name: ht_neuron - Neuron model after Hill & Tononi (2005).
Description:
This model neuron implements a slightly modified version of the
neuron model described in [1]. The most important properties are:
- Integrate-and-fire with threshold adaptive threshold.
- Repolarizing potassium current instead of hard reset.
- AMPA, NMDA, GABA_A, and GABA_B conductance-based synapses with
beta-function (difference of exponentials) time course.
- Voltage-dependent NMDA with instantaneous or two-stage unblocking [1, 2].
- Intrinsic currents I_h, I_T, I_Na(p), and I_KNa.
- Synaptic "minis" are not implemented.
Documentation and Examples:
- docs/model_details/HillTononiModels.ipynb
- pynest/examples/intrinsic_currents_spiking.py
- pynest/examples/intrinsic_currents_subthreshold.py
Parameters:
V_m - membrane potential
tau_m - membrane time constant applying to all currents except
repolarizing K-current (see [1], p 1677)
t_ref - refractory time and duration of post-spike repolarizing
potassium current (t_spike in [1])
tau_spike - membrane time constant for post-spike repolarizing
potassium current
voltage_clamp - if true, clamp voltage to value at beginning of simulation
(default: false, mainly for testing)
theta, theta_eq, tau_theta - threshold, equilibrium value, time constant
g_KL, E_K, g_NaL, E_Na - conductances and reversal potentials for K and
Na leak currents
{E_rev,g_peak,tau_rise,tau_decay}_{AMPA,NMDA,GABA_A,GABA_B}
- reversal potentials, peak conductances and
time constants for synapses (tau_rise/
tau_decay correspond to tau_1/tau_2 in the
paper)
V_act_NMDA, S_act_NMDA, tau_Mg_{fast, slow}_NMDA
- parameters for voltage dependence of NMDA-
conductance, see above
instant_unblock_NMDA - instantaneous NMDA unblocking (default: false)
{E_rev,g_peak}_{h,T,NaP,KNa} - reversal potential and peak conductance for
intrinsic currents
tau_D_KNa - relaxation time constant for I_KNa
receptor_types - dictionary mapping synapse names to ports on
neuron model
recordables - list of recordable quantities
equilibrate - if given and true, time-dependent activation
and inactivation state variables (h, m) of
intrinsic currents and NMDA channels are set
to their equilibrium values during this
SetStatus call; otherwise they retain their
present values.
Note: Conductances are unitless in this model and currents are in mV.
Author: Hans Ekkehard Plesser
Sends: SpikeEvent
Receives: SpikeEvent, CurrentEvent, DataLoggingRequest
FirstVersion: October 2009; full revision November 2016
References:
[1] S Hill and G Tononi (2005). J Neurophysiol 93:1671-1698.
[2] M Vargas-Caballero HPC Robinson (2003). J Neurophysiol 89:2778-2783.
SeeAlso: ht_synapse
*/
namespace nest
{
/**
* Function computing right-hand side of ODE for GSL solver.
* @note Must be declared here so we can befriend it in class.
* @note Must have C-linkage for passing to GSL. Internally, it is
* a first-class C++ function, but cannot be a member function
* because of the C-linkage.
* @note No point in declaring it inline, since it is called
* through a function pointer.
* @param void* Pointer to model neuron instance.
*/
extern "C" int ht_neuron_dynamics( double, const double*, double*, void* );
class ht_neuron : public Archiving_Node
{
public:
ht_neuron();
ht_neuron( const ht_neuron& );
~ht_neuron();
/**
* Import sets of overloaded virtual functions.
* @see Technical Issues / Virtual Functions: Overriding, Overloading, and
* Hiding
*/
using Node::handle;
using Node::handles_test_event;
port send_test_event( Node&, rport, synindex, bool );
void handle( SpikeEvent& e );
void handle( CurrentEvent& e );
void handle( DataLoggingRequest& );
port handles_test_event( SpikeEvent&, rport );
port handles_test_event( CurrentEvent&, rport );
port handles_test_event( DataLoggingRequest&, rport );
void get_status( DictionaryDatum& ) const;
void set_status( const DictionaryDatum& );
private:
/**
* Synapse types to connect to
* @note Excluded upper and lower bounds are defined as INF_, SUP_.
* Excluding port 0 avoids accidental connections.
*/
enum SynapseTypes
{
INF_SPIKE_RECEPTOR = 0,
AMPA,
NMDA,
GABA_A,
GABA_B,
SUP_SPIKE_RECEPTOR
};
void init_state_( const Node& proto );
void init_buffers_();
void calibrate();
void update( Time const&, const long, const long );
double get_synapse_constant( double, double, double );
// END Boilerplate function declarations ----------------------------
// Friends --------------------------------------------------------
// make dynamics function quasi-member
friend int ht_neuron_dynamics( double, const double*, double*, void* );
// ----------------------------------------------------------------
/**
* Independent parameters of the model.
*/
struct Parameters_
{
Parameters_();
void get( DictionaryDatum& ) const; //!< Store current values in dictionary
void set( const DictionaryDatum& ); //!< Set values from dicitonary
// Note: Conductances are unitless
// Leaks
double E_Na; // mV
double E_K; // mV
double g_NaL;
double g_KL;
double tau_m; // ms
// Dynamic threshold
double theta_eq; // mV
double tau_theta; // ms
// Post-spike potassium current
double tau_spike; // ms, membrane time constant for this current
double t_ref; // ms, refractory time
// Parameters for synapse of type AMPA, GABA_A, GABA_B and NMDA
double g_peak_AMPA;
double tau_rise_AMPA; // ms
double tau_decay_AMPA; // ms
double E_rev_AMPA; // mV
double g_peak_NMDA;
double tau_rise_NMDA; // ms
double tau_decay_NMDA; // ms
double E_rev_NMDA; // mV
double V_act_NMDA; // mV, inactive for V << Vact, inflection of sigmoid
double S_act_NMDA; // mV, scale of inactivation
double tau_Mg_slow_NMDA; // ms
double tau_Mg_fast_NMDA; // ms
bool instant_unblock_NMDA;
double g_peak_GABA_A;
double tau_rise_GABA_A; // ms
double tau_decay_GABA_A; // ms
double E_rev_GABA_A; // mV
double g_peak_GABA_B;
double tau_rise_GABA_B; // ms
double tau_decay_GABA_B; // ms
double E_rev_GABA_B; // mV
// parameters for intrinsic currents
double g_peak_NaP;
double E_rev_NaP; // mV
double g_peak_KNa;
double E_rev_KNa; // mV
double tau_D_KNa; // ms
double g_peak_T;
double E_rev_T; // mV
double g_peak_h;
double E_rev_h; // mV
bool voltage_clamp;
};
// ----------------------------------------------------------------
/**
* State variables of the model.
*/
public:
struct State_
{
// y_ = [V, theta, Synapses]
enum StateVecElems_
{
V_M = 0,
THETA,
DG_AMPA,
G_AMPA,
DG_NMDA_TIMECOURSE,
G_NMDA_TIMECOURSE,
DG_GABA_A,
G_GABA_A,
DG_GABA_B,
G_GABA_B, // DO NOT INSERT ANYTHING UP TO HERE, WILL MIX UP
// SPIKE DELIVERY
m_fast_NMDA,
m_slow_NMDA,
m_Ih,
D_IKNa,
m_IT,
h_IT,
STATE_VEC_SIZE
};
//! neuron state, must be C-array for GSL solver
double y_[ STATE_VEC_SIZE ];
/** Timer (counter) for spike-activated repolarizing potassium current.
* Neuron is absolutely refractory during this period.
*/
long ref_steps_;
double I_NaP_; //!< Persistent Na current; member only to allow recording
double I_KNa_; //!< Depol act. K current; member only to allow recording
double I_T_; //!< Low-thresh Ca current; member only to allow recording
double I_h_; //!< Pacemaker current; member only to allow recording
State_( const ht_neuron&, const Parameters_& p );
State_( const State_& s );
~State_();
State_& operator=( const State_& s );
void get( DictionaryDatum& ) const;
void set( const DictionaryDatum&, const ht_neuron& );
};
private:
// These friend declarations must be precisely here.
friend class RecordablesMap< ht_neuron >;
friend class UniversalDataLogger< ht_neuron >;
// ----------------------------------------------------------------
/**
* Buffers of the model.
*/
struct Buffers_
{
Buffers_( ht_neuron& );
Buffers_( const Buffers_&, ht_neuron& );
UniversalDataLogger< ht_neuron > logger_;
/** buffers and sums up incoming spikes/currents */
std::vector< RingBuffer > spike_inputs_;
RingBuffer currents_;
/** GSL ODE stuff */
gsl_odeiv_step* s_; //!< stepping function
gsl_odeiv_control* c_; //!< adaptive stepsize control function
gsl_odeiv_evolve* e_; //!< evolution function
gsl_odeiv_system sys_; //!< struct describing system
// IntergrationStep_ should be reset with the neuron on ResetNetwork,
// but remain unchanged during calibration. Since it is initialized with
// step_, and the resolution cannot change after nodes have been created,
// it is safe to place both here.
double step_; //!< step size in ms
double integration_step_; //!< current integration time step, updated by GSL
/**
* Input current injected by CurrentEvent.
* This variable is used to transport the current applied into the
* _dynamics function computing the derivative of the state vector.
* It must be a part of Buffers_, since it is initialized once before
* the first simulation, but not modified before later Simulate calls.
*/
double I_stim_;
};
// ----------------------------------------------------------------
/**
* Internal variables of the model.
*/
struct Variables_
{
//! size of conductance steps for arriving spikes
std::vector< double > cond_steps_;
//! Duration of potassium current.
int PotassiumRefractoryCounts_;
//! Voltage at beginning of simulation, for clamping
double V_clamp_;
};
// readout functions, can use template for vector elements
template < State_::StateVecElems_ elem >
double
get_y_elem_() const
{
return S_.y_[ elem ];
}
double
get_I_NaP_() const
{
return S_.I_NaP_;
}
double
get_I_KNa_() const
{
return S_.I_KNa_;
}
double
get_I_T_() const
{
return S_.I_T_;
}
double
get_I_h_() const
{
return S_.I_h_;
}
double get_g_NMDA_() const;
/**
* NMDA activation for given parameters
* Needs to take parameter values explicitly since it is called from
* _dynamics.
*/
double m_NMDA_( double V, double m_eq, double m_fast, double m_slow ) const;
/**
* Return equilibrium value of I_h activation
*
* @param V Membrane potential for which to evaluate
* (may differ from y_[V_M] when clamping)
*/
double m_eq_h_( double V ) const;
/**
* Return equilibrium value of I_T activation
*
* @param V Membrane potential for which to evaluate
* (may differ from y_[V_M] when clamping)
*/
double m_eq_T_( double V ) const;
/**
* Return equilibrium value of I_T inactivation
*
* @param V Membrane potential for which to evaluate
* (may differ from y_[V_M] when clamping)
*/
double h_eq_T_( double V ) const;
/**
* Return steady-state magnesium unblock ratio.
*
* Receives V_m as argument since it is called from ht_neuron_dyamics
* with temporary state values.
*/
double m_eq_NMDA_( double V ) const;
/**
* Steady-state "D" value for given voltage.
*/
double D_eq_KNa_( double V ) const;
static RecordablesMap< ht_neuron > recordablesMap_;
Parameters_ P_;
State_ S_;
Variables_ V_;
Buffers_ B_;
};
inline port
ht_neuron::send_test_event( Node& target, rport receptor_type, synindex, bool )
{
SpikeEvent e;
e.set_sender( *this );
return target.handles_test_event( e, receptor_type );
}
inline port
ht_neuron::handles_test_event( SpikeEvent&, rport receptor_type )
{
assert( B_.spike_inputs_.size() == 4 );
if ( not( INF_SPIKE_RECEPTOR < receptor_type
&& receptor_type < SUP_SPIKE_RECEPTOR ) )
{
throw UnknownReceptorType( receptor_type, get_name() );
return 0;
}
else
{
return receptor_type - 1;
}
/*
if (receptor_type != 0)
{
throw UnknownReceptorType(receptor_type, get_name());
}
return 0;*/
}
inline port
ht_neuron::handles_test_event( CurrentEvent&, rport receptor_type )
{
if ( receptor_type != 0 )
{
throw UnknownReceptorType( receptor_type, get_name() );
}
return 0;
}
inline port
ht_neuron::handles_test_event( DataLoggingRequest& dlr, rport receptor_type )
{
if ( receptor_type != 0 )
{
throw UnknownReceptorType( receptor_type, get_name() );
}
return B_.logger_.connect_logging_device( dlr, recordablesMap_ );
}
}
#endif // HAVE_GSL
#endif // HT_NEURON_H
| {
"alphanum_fraction": 0.644561617,
"avg_line_length": 28.2309160305,
"ext": "h",
"hexsha": "af97fde2349a358e0dc12e7e161fdcdc203c8568",
"lang": "C",
"max_forks_count": 10,
"max_forks_repo_forks_event_max_datetime": "2021-03-25T09:32:56.000Z",
"max_forks_repo_forks_event_min_datetime": "2019-12-09T06:45:59.000Z",
"max_forks_repo_head_hexsha": "14f86a76edf4e8763b58f84960876e95d4efc43a",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "OpenHEC/SNN-simulator-on-PYNQcluster",
"max_forks_repo_path": "NEST-14.0-FPGA/models/ht_neuron.h",
"max_issues_count": 2,
"max_issues_repo_head_hexsha": "14f86a76edf4e8763b58f84960876e95d4efc43a",
"max_issues_repo_issues_event_max_datetime": "2021-09-08T02:33:46.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-05-23T05:34:21.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "zlchai/SNN-simulator-on-PYNQcluster",
"max_issues_repo_path": "NEST-14.0-FPGA/models/ht_neuron.h",
"max_line_length": 80,
"max_stars_count": 45,
"max_stars_repo_head_hexsha": "14f86a76edf4e8763b58f84960876e95d4efc43a",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "OpenHEC/SNN-simulator-on-PYNQcluster",
"max_stars_repo_path": "NEST-14.0-FPGA/models/ht_neuron.h",
"max_stars_repo_stars_event_max_datetime": "2022-01-29T12:16:41.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-12-09T06:45:53.000Z",
"num_tokens": 3753,
"size": 14793
} |
// @(#)root/matrix:$Id$
// Authors: Fons Rademakers, Eddy Offermann Nov 2003
/*************************************************************************
* Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
#ifndef ROOT_TMatrixT
#define ROOT_TMatrixT
//////////////////////////////////////////////////////////////////////////
// //
// TMatrixT //
// //
// Template class of a general matrix in the linear algebra package //
// //
//////////////////////////////////////////////////////////////////////////
#include "TMatrixTBase.h"
#include "TMatrixTUtils.h"
#ifdef CBLAS
#include <vecLib/vBLAS.h>
//#include <cblas.h>
#endif
#include "Rtypes.h"
#include "TError.h"
template<class Element> class TMatrixTSym;
template<class Element> class TMatrixTSparse;
template<class Element> class TMatrixTLazy;
template<class Element> class TMatrixT : public TMatrixTBase<Element> {
protected:
Element fDataStack[TMatrixTBase<Element>::kSizeMax]; //! data container
Element *fElements; //[fNelems] elements themselves
Element *New_m (Int_t size);
void Delete_m(Int_t size,Element*&);
Int_t Memcpy_m(Element *newp,const Element *oldp,Int_t copySize,
Int_t newSize,Int_t oldSize);
void Allocate(Int_t nrows,Int_t ncols,Int_t row_lwb = 0,Int_t col_lwb = 0,Int_t init = 0,
Int_t /*nr_nonzeros*/ = -1);
public:
enum {kWorkMax = 100};
enum EMatrixCreatorsOp1 { kZero,kUnit,kTransposed,kInverted,kAtA };
enum EMatrixCreatorsOp2 { kMult,kTransposeMult,kInvMult,kMultTranspose,kPlus,kMinus };
TMatrixT(): fDataStack(), fElements(0) { }
TMatrixT(Int_t nrows,Int_t ncols);
TMatrixT(Int_t row_lwb,Int_t row_upb,Int_t col_lwb,Int_t col_upb);
TMatrixT(Int_t nrows,Int_t ncols,const Element *data,Option_t *option="");
TMatrixT(Int_t row_lwb,Int_t row_upb,Int_t col_lwb,Int_t col_upb,const Element *data,Option_t *option="");
TMatrixT(const TMatrixT <Element> &another);
TMatrixT(const TMatrixTSym <Element> &another);
TMatrixT(const TMatrixTSparse<Element> &another);
template <class Element2> TMatrixT(const TMatrixT<Element2> &another): fElements(0)
{
R__ASSERT(another.IsValid());
Allocate(another.GetNrows(),another.GetNcols(),another.GetRowLwb(),another.GetColLwb());
*this = another;
}
TMatrixT(EMatrixCreatorsOp1 op,const TMatrixT<Element> &prototype);
TMatrixT(const TMatrixT <Element> &a,EMatrixCreatorsOp2 op,const TMatrixT <Element> &b);
TMatrixT(const TMatrixT <Element> &a,EMatrixCreatorsOp2 op,const TMatrixTSym<Element> &b);
TMatrixT(const TMatrixTSym <Element> &a,EMatrixCreatorsOp2 op,const TMatrixT <Element> &b);
TMatrixT(const TMatrixTSym <Element> &a,EMatrixCreatorsOp2 op,const TMatrixTSym<Element> &b);
TMatrixT(const TMatrixTLazy<Element> &lazy_constructor);
virtual ~TMatrixT() { Clear(); }
// Elementary constructors
void Plus (const TMatrixT <Element> &a,const TMatrixT <Element> &b);
void Plus (const TMatrixT <Element> &a,const TMatrixTSym<Element> &b);
void Plus (const TMatrixTSym<Element> &a,const TMatrixT <Element> &b) { Plus(b,a); }
void Minus(const TMatrixT <Element> &a,const TMatrixT <Element> &b);
void Minus(const TMatrixT <Element> &a,const TMatrixTSym<Element> &b);
void Minus(const TMatrixTSym<Element> &a,const TMatrixT <Element> &b) { Minus(b,a); }
void Mult (const TMatrixT <Element> &a,const TMatrixT <Element> &b);
void Mult (const TMatrixT <Element> &a,const TMatrixTSym<Element> &b);
void Mult (const TMatrixTSym<Element> &a,const TMatrixT <Element> &b);
void Mult (const TMatrixTSym<Element> &a,const TMatrixTSym<Element> &b);
void TMult(const TMatrixT <Element> &a,const TMatrixT <Element> &b);
void TMult(const TMatrixT <Element> &a,const TMatrixTSym<Element> &b);
void TMult(const TMatrixTSym<Element> &a,const TMatrixT <Element> &b) { Mult(a,b); }
void TMult(const TMatrixTSym<Element> &a,const TMatrixTSym<Element> &b) { Mult(a,b); }
void MultT(const TMatrixT <Element> &a,const TMatrixT <Element> &b);
void MultT(const TMatrixT <Element> &a,const TMatrixTSym<Element> &b) { Mult(a,b); }
void MultT(const TMatrixTSym<Element> &a,const TMatrixT <Element> &b);
void MultT(const TMatrixTSym<Element> &a,const TMatrixTSym<Element> &b) { Mult(a,b); }
virtual const Element *GetMatrixArray () const;
virtual Element *GetMatrixArray ();
virtual const Int_t *GetRowIndexArray() const { return 0; }
virtual Int_t *GetRowIndexArray() { return 0; }
virtual const Int_t *GetColIndexArray() const { return 0; }
virtual Int_t *GetColIndexArray() { return 0; }
virtual TMatrixTBase<Element> &SetRowIndexArray(Int_t * /*data*/) { MayNotUse("SetRowIndexArray(Int_t *)"); return *this; }
virtual TMatrixTBase<Element> &SetColIndexArray(Int_t * /*data*/) { MayNotUse("SetColIndexArray(Int_t *)"); return *this; }
virtual void Clear(Option_t * /*option*/ ="") { if (this->fIsOwner) Delete_m(this->fNelems,fElements);
else fElements = 0;
this->fNelems = 0; }
TMatrixT <Element> &Use (Int_t row_lwb,Int_t row_upb,Int_t col_lwb,Int_t col_upb,Element *data);
const TMatrixT <Element> &Use (Int_t row_lwb,Int_t row_upb,Int_t col_lwb,Int_t col_upb,const Element *data) const
{ return (const TMatrixT<Element>&)
((const_cast<TMatrixT<Element> *>(this))->Use(row_lwb,row_upb,col_lwb,col_upb, const_cast<Element *>(data))); }
TMatrixT <Element> &Use (Int_t nrows,Int_t ncols,Element *data);
const TMatrixT <Element> &Use (Int_t nrows,Int_t ncols,const Element *data) const;
TMatrixT <Element> &Use (TMatrixT<Element> &a);
const TMatrixT <Element> &Use (const TMatrixT<Element> &a) const;
virtual TMatrixTBase<Element> &GetSub (Int_t row_lwb,Int_t row_upb,Int_t col_lwb,Int_t col_upb,
TMatrixTBase<Element> &target,Option_t *option="S") const;
TMatrixT <Element> GetSub (Int_t row_lwb,Int_t row_upb,Int_t col_lwb,Int_t col_upb,Option_t *option="S") const;
virtual TMatrixTBase<Element> &SetSub (Int_t row_lwb,Int_t col_lwb,const TMatrixTBase<Element> &source);
virtual TMatrixTBase<Element> &ResizeTo(Int_t nrows,Int_t ncols,Int_t /*nr_nonzeros*/ =-1);
virtual TMatrixTBase<Element> &ResizeTo(Int_t row_lwb,Int_t row_upb,Int_t col_lwb,Int_t col_upb,Int_t /*nr_nonzeros*/ =-1);
inline TMatrixTBase<Element> &ResizeTo(const TMatrixT<Element> &m) {
return ResizeTo(m.GetRowLwb(),m.GetRowUpb(),m.GetColLwb(),m.GetColUpb());
}
virtual Double_t Determinant () const;
virtual void Determinant (Double_t &d1,Double_t &d2) const;
TMatrixT<Element> &Invert (Double_t *det=0);
TMatrixT<Element> &InvertFast (Double_t *det=0);
TMatrixT<Element> &Transpose (const TMatrixT<Element> &source);
inline TMatrixT<Element> &T () { return this->Transpose(*this); }
TMatrixT<Element> &Rank1Update (const TVectorT<Element> &v,Element alpha=1.0);
TMatrixT<Element> &Rank1Update (const TVectorT<Element> &v1,const TVectorT<Element> &v2,Element alpha=1.0);
Element Similarity (const TVectorT<Element> &v) const;
TMatrixT<Element> &NormByColumn(const TVectorT<Element> &v,Option_t *option="D");
TMatrixT<Element> &NormByRow (const TVectorT<Element> &v,Option_t *option="D");
// Either access a_ij as a(i,j)
inline Element operator()(Int_t rown,Int_t coln) const;
inline Element &operator()(Int_t rown,Int_t coln);
// or as a[i][j]
inline const TMatrixTRow_const<Element> operator[](Int_t rown) const { return TMatrixTRow_const<Element>(*this,rown); }
inline TMatrixTRow <Element> operator[](Int_t rown) { return TMatrixTRow <Element>(*this,rown); }
TMatrixT<Element> &operator= (const TMatrixT <Element> &source);
TMatrixT<Element> &operator= (const TMatrixTSym <Element> &source);
TMatrixT<Element> &operator= (const TMatrixTSparse<Element> &source);
TMatrixT<Element> &operator= (const TMatrixTLazy <Element> &source);
template <class Element2> TMatrixT<Element> &operator= (const TMatrixT<Element2> &source)
{
if (!AreCompatible(*this,source)) {
Error("operator=(const TMatrixT2 &)","matrices not compatible");
return *this;
}
TObject::operator=(source);
const Element2 * const ps = source.GetMatrixArray();
Element * const pt = this->GetMatrixArray();
for (Int_t i = 0; i < this->fNelems; i++)
pt[i] = ps[i];
this->fTol = source.GetTol();
return *this;
}
TMatrixT<Element> &operator= (Element val);
TMatrixT<Element> &operator-=(Element val);
TMatrixT<Element> &operator+=(Element val);
TMatrixT<Element> &operator*=(Element val);
TMatrixT<Element> &operator+=(const TMatrixT <Element> &source);
TMatrixT<Element> &operator+=(const TMatrixTSym<Element> &source);
TMatrixT<Element> &operator-=(const TMatrixT <Element> &source);
TMatrixT<Element> &operator-=(const TMatrixTSym<Element> &source);
TMatrixT<Element> &operator*=(const TMatrixT <Element> &source);
TMatrixT<Element> &operator*=(const TMatrixTSym <Element> &source);
TMatrixT<Element> &operator*=(const TMatrixTDiag_const <Element> &diag);
TMatrixT<Element> &operator/=(const TMatrixTDiag_const <Element> &diag);
TMatrixT<Element> &operator*=(const TMatrixTRow_const <Element> &row);
TMatrixT<Element> &operator/=(const TMatrixTRow_const <Element> &row);
TMatrixT<Element> &operator*=(const TMatrixTColumn_const<Element> &col);
TMatrixT<Element> &operator/=(const TMatrixTColumn_const<Element> &col);
const TMatrixT<Element> EigenVectors(TVectorT<Element> &eigenValues) const;
ClassDef(TMatrixT,4) // Template of General Matrix class
};
#ifndef __CINT__
// When building with -fmodules, it instantiates all pending instantiations,
// instead of delaying them until the end of the translation unit.
// We 'got away with' probably because the use and the definition of the
// explicit specialization do not occur in the same TU.
//
// In case we are building with -fmodules, we need to forward declare the
// specialization in order to compile the dictionary G__Matrix.cxx.
template <> TClass *TMatrixT<double>::Class();
#endif // __CINT__
template <class Element> inline const Element *TMatrixT<Element>::GetMatrixArray() const { return fElements; }
template <class Element> inline Element *TMatrixT<Element>::GetMatrixArray() { return fElements; }
template <class Element> inline TMatrixT<Element> &TMatrixT<Element>::Use (Int_t nrows,Int_t ncols,Element *data)
{ return Use(0,nrows-1,0,ncols-1,data); }
template <class Element> inline const TMatrixT<Element> &TMatrixT<Element>::Use (Int_t nrows,Int_t ncols,const Element *data) const
{ return Use(0,nrows-1,0,ncols-1,data); }
template <class Element> inline TMatrixT<Element> &TMatrixT<Element>::Use (TMatrixT &a)
{
R__ASSERT(a.IsValid());
return Use(a.GetRowLwb(),a.GetRowUpb(),
a.GetColLwb(),a.GetColUpb(),a.GetMatrixArray());
}
template <class Element> inline const TMatrixT<Element> &TMatrixT<Element>::Use (const TMatrixT &a) const
{
R__ASSERT(a.IsValid());
return Use(a.GetRowLwb(),a.GetRowUpb(),
a.GetColLwb(),a.GetColUpb(),a.GetMatrixArray());
}
template <class Element> inline TMatrixT<Element> TMatrixT<Element>::GetSub (Int_t row_lwb,Int_t row_upb,Int_t col_lwb,Int_t col_upb,
Option_t *option) const
{
TMatrixT tmp;
this->GetSub(row_lwb,row_upb,col_lwb,col_upb,tmp,option);
return tmp;
}
template <class Element> inline Element TMatrixT<Element>::operator()(Int_t rown,Int_t coln) const
{
R__ASSERT(this->IsValid());
const Int_t arown = rown-this->fRowLwb;
const Int_t acoln = coln-this->fColLwb;
if (arown >= this->fNrows || arown < 0) {
Error("operator()","Request row(%d) outside matrix range of %d - %d",rown,this->fRowLwb,this->fRowLwb+this->fNrows);
return TMatrixTBase<Element>::NaNValue();
}
if (acoln >= this->fNcols || acoln < 0) {
Error("operator()","Request column(%d) outside matrix range of %d - %d",coln,this->fColLwb,this->fColLwb+this->fNcols);
return TMatrixTBase<Element>::NaNValue();
}
return (fElements[arown*this->fNcols+acoln]);
}
template <class Element> inline Element &TMatrixT<Element>::operator()(Int_t rown,Int_t coln)
{
R__ASSERT(this->IsValid());
const Int_t arown = rown-this->fRowLwb;
const Int_t acoln = coln-this->fColLwb;
if (arown >= this->fNrows || arown < 0) {
Error("operator()","Request row(%d) outside matrix range of %d - %d",rown,this->fRowLwb,this->fRowLwb+this->fNrows);
return TMatrixTBase<Element>::NaNValue();
}
if (acoln >= this->fNcols || acoln < 0) {
Error("operator()","Request column(%d) outside matrix range of %d - %d",coln,this->fColLwb,this->fColLwb+this->fNcols);
return TMatrixTBase<Element>::NaNValue();
}
return (fElements[arown*this->fNcols+acoln]);
}
template <class Element> TMatrixT<Element> operator+ (const TMatrixT <Element> &source1,const TMatrixT <Element> &source2);
template <class Element> TMatrixT<Element> operator+ (const TMatrixT <Element> &source1,const TMatrixTSym<Element> &source2);
template <class Element> TMatrixT<Element> operator+ (const TMatrixTSym<Element> &source1,const TMatrixT <Element> &source2);
template <class Element> TMatrixT<Element> operator+ (const TMatrixT <Element> &source , Element val );
template <class Element> TMatrixT<Element> operator+ ( Element val ,const TMatrixT <Element> &source );
template <class Element> TMatrixT<Element> operator- (const TMatrixT <Element> &source1,const TMatrixT <Element> &source2);
template <class Element> TMatrixT<Element> operator- (const TMatrixT <Element> &source1,const TMatrixTSym<Element> &source2);
template <class Element> TMatrixT<Element> operator- (const TMatrixTSym<Element> &source1,const TMatrixT <Element> &source2);
template <class Element> TMatrixT<Element> operator- (const TMatrixT <Element> &source , Element val );
template <class Element> TMatrixT<Element> operator- ( Element val ,const TMatrixT <Element> &source );
template <class Element> TMatrixT<Element> operator* ( Element val ,const TMatrixT <Element> &source );
template <class Element> TMatrixT<Element> operator* (const TMatrixT <Element> &source , Element val );
template <class Element> TMatrixT<Element> operator* (const TMatrixT <Element> &source1,const TMatrixT <Element> &source2);
template <class Element> TMatrixT<Element> operator* (const TMatrixT <Element> &source1,const TMatrixTSym<Element> &source2);
template <class Element> TMatrixT<Element> operator* (const TMatrixTSym<Element> &source1,const TMatrixT <Element> &source2);
template <class Element> TMatrixT<Element> operator* (const TMatrixTSym<Element> &source1,const TMatrixTSym<Element> &source2);
// Preventing warnings with -Weffc++ in GCC since overloading the || and && operators was a design choice.
#if (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__) >= 40600
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Weffc++"
#endif
template <class Element> TMatrixT<Element> operator&& (const TMatrixT <Element> &source1,const TMatrixT <Element> &source2);
template <class Element> TMatrixT<Element> operator&& (const TMatrixT <Element> &source1,const TMatrixTSym<Element> &source2);
template <class Element> TMatrixT<Element> operator&& (const TMatrixTSym<Element> &source1,const TMatrixT <Element> &source2);
template <class Element> TMatrixT<Element> operator|| (const TMatrixT <Element> &source1,const TMatrixT <Element> &source2);
template <class Element> TMatrixT<Element> operator|| (const TMatrixT <Element> &source1,const TMatrixTSym<Element> &source2);
template <class Element> TMatrixT<Element> operator|| (const TMatrixTSym<Element> &source1,const TMatrixT <Element> &source2);
#if (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__) >= 40600
#pragma GCC diagnostic pop
#endif
template <class Element> TMatrixT<Element> operator> (const TMatrixT <Element> &source1,const TMatrixT <Element> &source2);
template <class Element> TMatrixT<Element> operator> (const TMatrixT <Element> &source1,const TMatrixTSym<Element> &source2);
template <class Element> TMatrixT<Element> operator> (const TMatrixTSym<Element> &source1,const TMatrixT <Element> &source2);
template <class Element> TMatrixT<Element> operator>= (const TMatrixT <Element> &source1,const TMatrixT <Element> &source2);
template <class Element> TMatrixT<Element> operator>= (const TMatrixT <Element> &source1,const TMatrixTSym<Element> &source2);
template <class Element> TMatrixT<Element> operator>= (const TMatrixTSym<Element> &source1,const TMatrixT <Element> &source2);
template <class Element> TMatrixT<Element> operator<= (const TMatrixT <Element> &source1,const TMatrixT <Element> &source2);
template <class Element> TMatrixT<Element> operator<= (const TMatrixT <Element> &source1,const TMatrixTSym<Element> &source2);
template <class Element> TMatrixT<Element> operator<= (const TMatrixTSym<Element> &source1,const TMatrixT <Element> &source2);
template <class Element> TMatrixT<Element> operator< (const TMatrixT <Element> &source1,const TMatrixT <Element> &source2);
template <class Element> TMatrixT<Element> operator< (const TMatrixT <Element> &source1,const TMatrixTSym<Element> &source2);
template <class Element> TMatrixT<Element> operator< (const TMatrixTSym<Element> &source1,const TMatrixT <Element> &source2);
template <class Element> TMatrixT<Element> operator!= (const TMatrixT <Element> &source1,const TMatrixT <Element> &source2);
template <class Element> TMatrixT<Element> operator!= (const TMatrixT <Element> &source1,const TMatrixTSym<Element> &source2);
template <class Element> TMatrixT<Element> operator!= (const TMatrixTSym<Element> &source1,const TMatrixT <Element> &source2);
template <class Element> TMatrixT<Element> &Add (TMatrixT<Element> &target, Element scalar,const TMatrixT <Element> &source);
template <class Element> TMatrixT<Element> &Add (TMatrixT<Element> &target, Element scalar,const TMatrixTSym<Element> &source);
template <class Element> TMatrixT<Element> &ElementMult(TMatrixT<Element> &target,const TMatrixT <Element> &source);
template <class Element> TMatrixT<Element> &ElementMult(TMatrixT<Element> &target,const TMatrixTSym<Element> &source);
template <class Element> TMatrixT<Element> &ElementDiv (TMatrixT<Element> &target,const TMatrixT <Element> &source);
template <class Element> TMatrixT<Element> &ElementDiv (TMatrixT<Element> &target,const TMatrixTSym<Element> &source);
template <class Element> void AMultB (const Element * const ap,Int_t na,Int_t ncolsa,
const Element * const bp,Int_t nb,Int_t ncolsb,Element *cp);
template <class Element> void AtMultB(const Element * const ap,Int_t ncolsa,
const Element * const bp,Int_t nb,Int_t ncolsb,Element *cp);
template <class Element> void AMultBt(const Element * const ap,Int_t na,Int_t ncolsa,
const Element * const bp,Int_t nb,Int_t ncolsb,Element *cp);
#endif
| {
"alphanum_fraction": 0.6149012967,
"avg_line_length": 65.2354651163,
"ext": "h",
"hexsha": "ead09f67e609f9b898f3aa7cecc76be0be10024b",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2020-05-28T23:01:44.000Z",
"max_forks_repo_forks_event_min_datetime": "2020-05-28T23:01:44.000Z",
"max_forks_repo_head_hexsha": "2632aa3484ef64c9539c4885026b705b737f6d1e",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "edawson/parliament2",
"max_forks_repo_path": "resources/home/dnanexus/root/include/TMatrixT.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "2632aa3484ef64c9539c4885026b705b737f6d1e",
"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": "edawson/parliament2",
"max_issues_repo_path": "resources/home/dnanexus/root/include/TMatrixT.h",
"max_line_length": 164,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "2632aa3484ef64c9539c4885026b705b737f6d1e",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "edawson/parliament2",
"max_stars_repo_path": "resources/home/dnanexus/root/include/TMatrixT.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 5727,
"size": 22441
} |
/**
* \author Sylvain Marsat, University of Maryland - NASA GSFC
*
* \brief C code for structures EOBNRv2HM reduced order model (non-spinning version).
* See CQG 31 195010, 2014, arXiv:1402.4146 for details on the reduced order method.
* See arXiv:1106.1021 for the EOBNRv2HM model.
*
* Borrows from the SEOBNR ROM LAL code written by Michael Puerrer and John Veitch.
*
* Put the untared data in the directory designated by the environment variable ROM_DATA_PATH.
*
* Parameter range:
* q = 1-12 (almost)
* No spin
* Mtot >= 10Msun for fstart=8Hz
*
*/
#define _XOPEN_SOURCE 500
#ifdef __GNUC__
#define UNUSED __attribute__ ((unused))
#else
#define UNUSED
#endif
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <complex.h>
#include <time.h>
#include <unistd.h>
#include <getopt.h>
#include <stdbool.h>
#include <string.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_bspline.h>
#include <gsl/gsl_blas.h>
#include <gsl/gsl_min.h>
#include <gsl/gsl_spline.h>
#include <gsl/gsl_complex.h>
#include "constants.h"
#include "EOBNRv2HMROMstruct.h"
#include "EOBNRv2HMROM.h"
/************************************************************************/
/********************* Functions for list structures ********************/
/***************** Functions for the SplineList structure ****************/
/* Prepend a node to a linked list of splines, or create a new head */
SplineList* SplineList_AddElementNoCopy(
SplineList* appended, /* List structure to prepend to */
gsl_spline* spline, /* spline to contain */
gsl_interp_accel* accel, /* accelerator to contain */
int i /* index in the list */)
{
SplineList* splinelist;
/* Check if the node with this index already exists */
splinelist = appended;
while( splinelist ){
if( i == splinelist->i ){
break;
}
splinelist = splinelist->next;
}
if( splinelist ){ /* We don't allow for the case where the index already exists*/
printf("Error: Tried to add an already existing index to a SplineList");
return(NULL);
} else { /* In that case, we do NOT COPY the input spline, which therefore can't be
used anywhere else; this will be acceptable as these operations will only be done
when initializing the data */
splinelist = malloc( sizeof(SplineList) );
}
splinelist->i = i;
if( spline ){
splinelist->spline = spline;
} else {
splinelist->spline = NULL;
}
if( accel ){
splinelist->accel = accel;
} else {
splinelist->accel = NULL;
}
if( appended ){
splinelist->next = appended;
} else {
splinelist->next = NULL;
}
return splinelist;
}
/* Get the element of a SplineList with a given index */
SplineList* SplineList_GetElement(
SplineList* const splinelist, /* List structure to get element from */
const int i ) /* Index looked for */
{
if( !splinelist ) return NULL;
SplineList* itr = splinelist;
while( itr->i != i ){
itr = itr->next;
if( !itr ) return NULL;
}
return itr; /* The element returned is itself a pointer to a SplineList */
}
/* Delete list from given pointer to the end of the list */
void SplineList_Destroy( SplineList* splinelist ) /* Head of linked list to destroy */
{
SplineList* pop;
while( (pop = splinelist) ){
if( pop->spline ){ /* Internal spline and accelerator are freed */
gsl_spline_free( pop->spline );
}
if( pop->accel ){
gsl_interp_accel_free( pop->accel );
}
/* Notice that the index i is not freed, like in SphHarmTimeSeries struct indices l and m */
splinelist = pop->next;
free( pop );
}
}
/***************** Functions for the EOBNRHMROMdata structure ****************/
ListmodesEOBNRHMROMdata* ListmodesEOBNRHMROMdata_AddModeNoCopy(
ListmodesEOBNRHMROMdata* appended, /* List structure to prepend to */
EOBNRHMROMdata* data, /* data to contain */
const int l, /* major mode number */
const int m /* minor mode number */)
{
ListmodesEOBNRHMROMdata* list;
/* Check if the node with this mode already exists */
list = appended;
while( list ){
if( l == list->l && m == list->m ){
break;
}
list = list->next;
}
if( list ){ /* We don't allow for the case where the mode already exists in the list*/
printf("Error: Tried to add an already existing mode to a ListmodesEOBNRHMROMdata ");
return(NULL);
} else { /* In that case, we do NOT COPY the input interpolated data, which therefore can't be
used anywhere else; this will be acceptable as these operations will only be done
when interpolating the initialization data */
list = malloc( sizeof(ListmodesEOBNRHMROMdata) );
}
list->l = l;
list->m = m;
if( data ){
list->data = data;
} else {
list->data = NULL;
}
if( appended ){
list->next = appended;
} else {
list->next = NULL;
}
return list;
}
/* Get the element of a ListmodesEOBNRHMROMdata with a given index */
ListmodesEOBNRHMROMdata* ListmodesEOBNRHMROMdata_GetMode(
ListmodesEOBNRHMROMdata* const list, /* List structure to get a particular mode from */
int l, /*< major mode number */
int m /*< minor mode number */ )
{
if( !list ) return NULL;
ListmodesEOBNRHMROMdata *itr = list;
while( itr->l != l || itr->m != m ){
itr = itr->next;
if( !itr ) return NULL;
}
return itr; /* The element returned is itself a pointer to a ListmodesEOBNRHMROMdata */
}
void ListmodesEOBNRHMROMdata_Destroy(
ListmodesEOBNRHMROMdata* list /* List structure to destroy; notice that the data is destroyed too */
)
{
ListmodesEOBNRHMROMdata* pop;
while( (pop = list) ){
if( pop->data ){ /* Destroying the EOBNRHMROMdata data */
EOBNRHMROMdata_Cleanup( pop->data );
}
/* Notice that the mode indices l and m are not freed, like in SphHarmTimeSeries struct indices l and m */
list = pop->next;
free( pop );
}
}
/***************** Functions for the EOBNRHMROMdata_interp structure ****************/
ListmodesEOBNRHMROMdata_interp* ListmodesEOBNRHMROMdata_interp_AddModeNoCopy(
ListmodesEOBNRHMROMdata_interp* appended, /* List structure to prepend to */
EOBNRHMROMdata_interp* data_interp, /* data to contain */
int l, /* major mode number */
int m /* minor mode number */)
{
ListmodesEOBNRHMROMdata_interp* list;
/* Check if the node with this mode already exists */
list = appended;
while( list ){
if( l == list->l && m == list->m ){
break;
}
list = list->next;
}
if( list ){ /* We don't allow for the case where the mode already exists in the list*/
printf("Error: Tried to add an already existing mode to a ListmodesEOBNRHMROMdata_interp ");
return(NULL);
} else { /* In that case, we do NOT COPY the input interpolated data, which therefore can't be
used anywhere else; this will be acceptable as these operations will only be done
when interpolating the initialization data */
list = malloc( sizeof(ListmodesEOBNRHMROMdata_interp) );
}
list->l = l;
list->m = m;
if( data_interp ){
list->data_interp = data_interp;
} else {
list->data_interp = NULL;
}
if( appended ){
list->next = appended;
} else {
list->next = NULL;
}
return list;
}
/* Get the element of a ListmodesEOBNRHMROMdata with a given index */
ListmodesEOBNRHMROMdata_interp* ListmodesEOBNRHMROMdata_interp_GetMode(
ListmodesEOBNRHMROMdata_interp* const list, /* List structure to get a particular mode from */
int l, /*< major mode number */
int m /*< minor mode number */ )
{
if( !list ) return NULL;
ListmodesEOBNRHMROMdata_interp *itr = list;
while( itr->l != l || itr->m != m ){
itr = itr->next;
if( !itr ) return NULL;
}
return itr; /* The element returned is itself a pointer to a ListmodesEOBNRHMROMdata_interp */
}
void ListmodesEOBNRHMROMdata_interp_Destroy(
ListmodesEOBNRHMROMdata_interp* list /* List structure to destroy; notice that the data is destroyed too */
)
{
ListmodesEOBNRHMROMdata_interp* pop;
while( (pop = list) ){
if( pop->data_interp ){ /* Destroying the EOBNRHMROMdata_interp data */
EOBNRHMROMdata_interp_Cleanup( pop->data_interp );
}
/* Notice that the mode indices l and m are not freed, like in SphHarmTimeSeries struct indices l and m */
list = pop->next;
free( pop );
}
}
/***************** Functions for the EOBNRHMROMdata_coeff structure ****************/
ListmodesEOBNRHMROMdata_coeff* ListmodesEOBNRHMROMdata_coeff_AddModeNoCopy(
ListmodesEOBNRHMROMdata_coeff* appended, /* List structure to prepend to */
EOBNRHMROMdata_coeff* data_coeff, /* data to contain */
int l, /* major mode number */
int m /* minor mode number */)
{
ListmodesEOBNRHMROMdata_coeff* list;
/* Check if the node with this mode already exists */
list = appended;
while( list ){
if( l == list->l && m == list->m ){
break;
}
list = list->next;
}
if( list ){ /* We don't allow for the case where the mode already exists in the list*/
printf("Error: Tried to add an already existing mode to a ListmodesEOBNRHMROMdata_coeff ");
return(NULL);
} else { /* In that case, we do NOT COPY the input interpolated data, which therefore can't be
used anywhere else; this will be acceptable as these operations will only be done
when interpolating the initialization data */
list = malloc( sizeof(ListmodesEOBNRHMROMdata_coeff) );
}
list->l = l;
list->m = m;
if( data_coeff ){
list->data_coeff = data_coeff;
} else {
list->data_coeff = NULL;
}
if( appended ){
list->next = appended;
} else {
list->next = NULL;
}
return list;
}
/* Get the element of a ListmodesEOBNRHMROMdata_coeff with a given index */
ListmodesEOBNRHMROMdata_coeff* ListmodesEOBNRHMROMdata_coeff_GetMode(
ListmodesEOBNRHMROMdata_coeff* const list, /* List structure to get a particular mode from */
int l, /*< major mode number */
int m /*< minor mode number */ )
{
if( !list ) return NULL;
ListmodesEOBNRHMROMdata_coeff *itr = list;
while( itr->l != l || itr->m != m ){
itr = itr->next;
if( !itr ) return NULL;
}
return itr; /* The element returned is itself a pointer to a ListmodesEOBNRHMROMdata_coeff */
}
void ListmodesEOBNRHMROMdata_coeff_Destroy(
ListmodesEOBNRHMROMdata_coeff* list /* List structure to destroy; notice that the data is destroyed too */
)
{
ListmodesEOBNRHMROMdata_coeff* pop;
while( (pop = list) ){
if( pop->data_coeff ){ /* Destroying the EOBNRHMROMdata_coeff data */
EOBNRHMROMdata_coeff_Cleanup( pop->data_coeff );
}
/* Notice that the mode indices l and m are not freed, like in SphHarmTimeSeries struct indices l and m */
list = pop->next;
free( pop );
}
}
| {
"alphanum_fraction": 0.6434892541,
"avg_line_length": 33.4561933535,
"ext": "c",
"hexsha": "1f23179fac5a90cc6827d975df02f6400bfeaf80",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2020-07-20T02:56:30.000Z",
"max_forks_repo_forks_event_min_datetime": "2018-09-20T14:19:13.000Z",
"max_forks_repo_head_hexsha": "4ffb02977d19786ab8c1a767cc495a799d9575ae",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "titodalcanton/flare",
"max_forks_repo_path": "EOBNRv2HMROM/EOBNRv2HMROMstruct.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "4ffb02977d19786ab8c1a767cc495a799d9575ae",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "titodalcanton/flare",
"max_issues_repo_path": "EOBNRv2HMROM/EOBNRv2HMROMstruct.c",
"max_line_length": 112,
"max_stars_count": 3,
"max_stars_repo_head_hexsha": "4ffb02977d19786ab8c1a767cc495a799d9575ae",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "titodalcanton/flare",
"max_stars_repo_path": "EOBNRv2HMROM/EOBNRv2HMROMstruct.c",
"max_stars_repo_stars_event_max_datetime": "2020-07-20T02:56:25.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-05-26T15:21:13.000Z",
"num_tokens": 2964,
"size": 11074
} |
#include <stdio.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
int main(int argc, char *argv[])
{
gsl_rng *r = gsl_rng_alloc(gsl_rng_mt19937);
int i, n;
double gauss, gamma;
n = atoi(argv[1]);
for (i=0; i<n; i++){
gauss = gsl_ran_gaussian(r, 2.0);
gamma = gsl_ran_gamma(r, 2.0, 3.0);
printf("%2.4f %2.4f\n", gauss, gamma);
}
return 0;
}
| {
"alphanum_fraction": 0.5942408377,
"avg_line_length": 17.3636363636,
"ext": "c",
"hexsha": "81cb3c469fbed468c3af7e2fc2b6e6ee5cc27e10",
"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": "69727d76fd652390d9660e9ea4354ba5cc76dd5c",
"max_forks_repo_licenses": [
"BSD-2-Clause"
],
"max_forks_repo_name": "Bingwen-Hu/hackaway",
"max_forks_repo_path": "books/21centuryC/cp1/gsl_test.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "69727d76fd652390d9660e9ea4354ba5cc76dd5c",
"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": "Bingwen-Hu/hackaway",
"max_issues_repo_path": "books/21centuryC/cp1/gsl_test.c",
"max_line_length": 46,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "69727d76fd652390d9660e9ea4354ba5cc76dd5c",
"max_stars_repo_licenses": [
"BSD-2-Clause"
],
"max_stars_repo_name": "Bingwen-Hu/hackaway",
"max_stars_repo_path": "books/21centuryC/cp1/gsl_test.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 144,
"size": 382
} |
/* histogram/stat2d.c
* Copyright (C) 2002 Achim Gaedke
*
* This library 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 library; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
/***************************************************************
*
* File histogram/stat2d.c:
* Routine to return statistical values of the content of a 2D hisogram.
*
* Contains the routines:
* gsl_histogram2d_sum sum up all bin values
* gsl_histogram2d_xmean determine mean of x values
* gsl_histogram2d_ymean determine mean of y values
*
* Author: Achim Gaedke Achim.Gaedke@zpr.uni-koeln.de
* Jan. 2002
*
***************************************************************/
#include <config.h>
#include <math.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_histogram2d.h>
/*
sum up all bins of histogram2d
*/
double
gsl_histogram2d_sum (const gsl_histogram2d * h)
{
const size_t n = h->nx * h->ny;
double sum = 0;
size_t i = 0;
while (i < n)
sum += h->bin[i++];
return sum;
}
double
gsl_histogram2d_xmean (const gsl_histogram2d * h)
{
const size_t nx = h->nx;
const size_t ny = h->ny;
size_t i;
size_t j;
/* Compute the bin-weighted arithmetic mean M of a histogram using the
recurrence relation
M(n) = M(n-1) + (x[n] - M(n-1)) (w(n)/(W(n-1) + w(n)))
W(n) = W(n-1) + w(n)
*/
long double wmean = 0;
long double W = 0;
for (i = 0; i < nx; i++)
{
double xi = (h->xrange[i + 1] + h->xrange[i]) / 2.0;
double wi = 0;
for (j = 0; j < ny; j++)
{
double wij = h->bin[i * ny + j];
if (wij > 0)
wi += wij;
}
if (wi > 0)
{
W += wi;
wmean += (xi - wmean) * (wi / W);
}
}
return wmean;
}
double
gsl_histogram2d_ymean (const gsl_histogram2d * h)
{
const size_t nx = h->nx;
const size_t ny = h->ny;
size_t i;
size_t j;
/* Compute the bin-weighted arithmetic mean M of a histogram using the
recurrence relation
M(n) = M(n-1) + (x[n] - M(n-1)) (w(n)/(W(n-1) + w(n)))
W(n) = W(n-1) + w(n)
*/
long double wmean = 0;
long double W = 0;
for (j = 0; j < ny; j++)
{
double yj = (h->yrange[j + 1] + h->yrange[j]) / 2.0;
double wj = 0;
for (i = 0; i < nx; i++)
{
double wij = h->bin[i * ny + j];
if (wij > 0)
wj += wij;
}
if (wj > 0)
{
W += wj;
wmean += (yj - wmean) * (wj / W);
}
}
return wmean;
}
double
gsl_histogram2d_xsigma (const gsl_histogram2d * h)
{
const double xmean = gsl_histogram2d_xmean (h);
const size_t nx = h->nx;
const size_t ny = h->ny;
size_t i;
size_t j;
/* Compute the bin-weighted arithmetic mean M of a histogram using the
recurrence relation
M(n) = M(n-1) + (x[n] - M(n-1)) (w(n)/(W(n-1) + w(n)))
W(n) = W(n-1) + w(n)
*/
long double wvariance = 0;
long double W = 0;
for (i = 0; i < nx; i++)
{
double xi = (h->xrange[i + 1] + h->xrange[i]) / 2 - xmean;
double wi = 0;
for (j = 0; j < ny; j++)
{
double wij = h->bin[i * ny + j];
if (wij > 0)
wi += wij;
}
if (wi > 0)
{
W += wi;
wvariance += ((xi * xi) - wvariance) * (wi / W);
}
}
{
double xsigma = sqrt (wvariance);
return xsigma;
}
}
double
gsl_histogram2d_ysigma (const gsl_histogram2d * h)
{
const double ymean = gsl_histogram2d_ymean (h);
const size_t nx = h->nx;
const size_t ny = h->ny;
size_t i;
size_t j;
/* Compute the bin-weighted arithmetic mean M of a histogram using the
recurrence relation
M(n) = M(n-1) + (x[n] - M(n-1)) (w(n)/(W(n-1) + w(n)))
W(n) = W(n-1) + w(n)
*/
long double wvariance = 0;
long double W = 0;
for (j = 0; j < ny; j++)
{
double yj = (h->yrange[j + 1] + h->yrange[j]) / 2.0 - ymean;
double wj = 0;
for (i = 0; i < nx; i++)
{
double wij = h->bin[i * ny + j];
if (wij > 0)
wj += wij;
}
if (wj > 0)
{
W += wj;
wvariance += ((yj * yj) - wvariance) * (wj / W);
}
}
{
double ysigma = sqrt (wvariance);
return ysigma;
}
}
double
gsl_histogram2d_cov (const gsl_histogram2d * h)
{
const double xmean = gsl_histogram2d_xmean (h);
const double ymean = gsl_histogram2d_ymean (h);
const size_t nx = h->nx;
const size_t ny = h->ny;
size_t i;
size_t j;
/* Compute the bin-weighted arithmetic mean M of a histogram using the
recurrence relation
M(n) = M(n-1) + (x[n] - M(n-1)) (w(n)/(W(n-1) + w(n)))
W(n) = W(n-1) + w(n)
*/
long double wcovariance = 0;
long double W = 0;
for (j = 0; j < ny; j++)
{
for (i = 0; i < nx; i++)
{
double xi = (h->xrange[i + 1] + h->xrange[i]) / 2.0 - xmean;
double yj = (h->yrange[j + 1] + h->yrange[j]) / 2.0 - ymean;
double wij = h->bin[i * ny + j];
if (wij > 0)
{
W += wij;
wcovariance += ((xi * yj) - wcovariance) * (wij / W);
}
}
}
return wcovariance;
}
| {
"alphanum_fraction": 0.5190787212,
"avg_line_length": 21.8721804511,
"ext": "c",
"hexsha": "5982817838e0d37929b32855be6b10ddb8c4687b",
"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/histogram/stat2d.c",
"max_issues_count": 6,
"max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e",
"max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z",
"max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "Brian-ning/HMNE",
"max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/histogram/stat2d.c",
"max_line_length": 74,
"max_stars_count": 14,
"max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "ielomariala/Hex-Game",
"max_stars_repo_path": "gsl-2.6/histogram/stat2d.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": 1903,
"size": 5818
} |
/*
/
/ adkGSL.h
/
/ homebrewed addons to gsl */
#include <gsl/gsl_vector.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_sort.h>
#include <gsl/gsl_sort_vector.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
#include <math.h>
#include <assert.h>
int gsl_vector_includes(gsl_vector *aVec, double aValue);
double gsl_vector_sum(gsl_vector *aVec, int aVecSize);
double gsl_matrix_row_sum(gsl_matrix *mat, int row, int rowSize);
double gsl_matrix_row_max(gsl_matrix *mat, int iRow);
double log_sum(gsl_vector *vec);
double *gsl_matrix_2_lapack(gsl_matrix *m);
double gsl_vector_dot_product(gsl_vector *vec1, gsl_vector *vec2);
void gsl_vector_outer_product(gsl_vector *vec1, gsl_vector *vec2, gsl_matrix *result);
gsl_matrix *gsl_matrix_power(gsl_matrix *A, int k);
gsl_matrix *gsl_matrix_power_logs(gsl_matrix *A, int k);
void gsl_matrix_lower_tri_copy(gsl_matrix *src, gsl_matrix *dest);
void gsl_matrix_upper_tri_copy(gsl_matrix *src, gsl_matrix *dest);
void gsl_matrix_lower_tri(gsl_matrix *x);
void gsl_matrix_upper_tri(gsl_matrix *x);
double gsl_matrix_trace(gsl_matrix *x);
void gsl_matrix_covariance(gsl_matrix *data, gsl_matrix *cov);
void gsl_matrix_bootstrap(gsl_matrix *orig, gsl_matrix *boot, gsl_rng *rng);
void gsl_matrix_prettyPrint(gsl_matrix *m);
void fillMatrixFromArray(double *numbers, gsl_matrix *dest, int nrow, int ncol);
void fillMatrixFromVector(gsl_vector *numbers, gsl_matrix *dest, int nrow, int ncol);
void fillArrayFromMatrix(gsl_matrix *src, gsl_vector *dest);
void fillCholArrayFromMatrix(gsl_matrix *src, gsl_vector *dest);
void fillMatrixFromCholArray(double *numbers, gsl_matrix *dest, int nrow, int ncol);
int gsl_matrix_invert_lapack(gsl_matrix *m);
void gsl_matrix_prettyPrint(gsl_matrix *m);
double gsl_matrix_sum(gsl_matrix *mat);
//lapack wrappers
//int dgeev(char jobvl, char jobvr, int n, double *a, int lda, double *wr, double *wi, double *vl,
// int ldvl,double *vr, int ldvr, double *work, int lwork);
//int dhseqr(char job, char compz, int n, int ilo, int ihi,double *h, int ldh, double *wr, double *wi, double *z, int ldz, double *work, int lwork);
| {
"alphanum_fraction": 0.7781972629,
"avg_line_length": 38.5272727273,
"ext": "h",
"hexsha": "acd97d9074b135fa3873a4ebbf6924d90b240f09",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "e1643d7489106d5e040329bd0b7db75d80ce21d6",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "kern-lab/im_clam",
"max_forks_repo_path": "adkGSL.h",
"max_issues_count": 3,
"max_issues_repo_head_hexsha": "e55ad3d0114f2e1491989fb6a00a37f8e2e4cfec",
"max_issues_repo_issues_event_max_datetime": "2018-04-08T17:04:32.000Z",
"max_issues_repo_issues_event_min_datetime": "2018-01-17T09:15:17.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "dortegadelv/IMaDNA",
"max_issues_repo_path": "adkGSL.h",
"max_line_length": 148,
"max_stars_count": 2,
"max_stars_repo_head_hexsha": "e55ad3d0114f2e1491989fb6a00a37f8e2e4cfec",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "dortegadelv/IMaDNA",
"max_stars_repo_path": "adkGSL.h",
"max_stars_repo_stars_event_max_datetime": "2020-04-17T17:22:14.000Z",
"max_stars_repo_stars_event_min_datetime": "2016-07-22T13:06:07.000Z",
"num_tokens": 620,
"size": 2119
} |
/* specfunc/bessel_amp_phase.c
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
/* Author: G. Jungman */
#include <config.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_sf_bessel.h>
#include "bessel_amp_phase.h"
/* chebyshev expansions for amplitude and phase
functions used in bessel evaluations
These are the same for J0,Y0 and for J1,Y1, so
they sit outside those functions.
*/
static double bm0_data[21] = {
0.09284961637381644,
-0.00142987707403484,
0.00002830579271257,
-0.00000143300611424,
0.00000012028628046,
-0.00000001397113013,
0.00000000204076188,
-0.00000000035399669,
0.00000000007024759,
-0.00000000001554107,
0.00000000000376226,
-0.00000000000098282,
0.00000000000027408,
-0.00000000000008091,
0.00000000000002511,
-0.00000000000000814,
0.00000000000000275,
-0.00000000000000096,
0.00000000000000034,
-0.00000000000000012,
0.00000000000000004
};
const cheb_series _gsl_sf_bessel_amp_phase_bm0_cs = {
bm0_data,
20,
-1, 1,
10
};
static double bth0_data[24] = {
-0.24639163774300119,
0.001737098307508963,
-0.000062183633402968,
0.000004368050165742,
-0.000000456093019869,
0.000000062197400101,
-0.000000010300442889,
0.000000001979526776,
-0.000000000428198396,
0.000000000102035840,
-0.000000000026363898,
0.000000000007297935,
-0.000000000002144188,
0.000000000000663693,
-0.000000000000215126,
0.000000000000072659,
-0.000000000000025465,
0.000000000000009229,
-0.000000000000003448,
0.000000000000001325,
-0.000000000000000522,
0.000000000000000210,
-0.000000000000000087,
0.000000000000000036
};
const cheb_series _gsl_sf_bessel_amp_phase_bth0_cs = {
bth0_data,
23,
-1, 1,
12
};
static double bm1_data[21] = {
0.1047362510931285,
0.00442443893702345,
-0.00005661639504035,
0.00000231349417339,
-0.00000017377182007,
0.00000001893209930,
-0.00000000265416023,
0.00000000044740209,
-0.00000000008691795,
0.00000000001891492,
-0.00000000000451884,
0.00000000000116765,
-0.00000000000032265,
0.00000000000009450,
-0.00000000000002913,
0.00000000000000939,
-0.00000000000000315,
0.00000000000000109,
-0.00000000000000039,
0.00000000000000014,
-0.00000000000000005,
};
const cheb_series _gsl_sf_bessel_amp_phase_bm1_cs = {
bm1_data,
20,
-1, 1,
10
};
static double bth1_data[24] = {
0.74060141026313850,
-0.004571755659637690,
0.000119818510964326,
-0.000006964561891648,
0.000000655495621447,
-0.000000084066228945,
0.000000013376886564,
-0.000000002499565654,
0.000000000529495100,
-0.000000000124135944,
0.000000000031656485,
-0.000000000008668640,
0.000000000002523758,
-0.000000000000775085,
0.000000000000249527,
-0.000000000000083773,
0.000000000000029205,
-0.000000000000010534,
0.000000000000003919,
-0.000000000000001500,
0.000000000000000589,
-0.000000000000000237,
0.000000000000000097,
-0.000000000000000040,
};
const cheb_series _gsl_sf_bessel_amp_phase_bth1_cs = {
bth1_data,
23,
-1, 1,
12
};
int
gsl_sf_bessel_asymp_Mnu_e(const double nu, const double x, double * result)
{
const double r = 2.0*nu/x;
const double r2 = r*r;
const double x2 = x*x;
const double term1 = (r2-1.0/x2)/8.0;
const double term2 = (r2-1.0/x2)*(r2-9.0/x2)*3.0/128.0;
const double Mnu2_c = 2.0/(M_PI) * (1.0 + term1 + term2);
*result = sqrt(Mnu2_c)/sqrt(x); /* will never underflow this way */
return GSL_SUCCESS;
}
int
gsl_sf_bessel_asymp_thetanu_corr_e(const double nu, const double x, double * result)
{
const double r = 2.0*nu/x;
const double r2 = r*r;
const double x2 = x*x;
const double term1 = x*(r2 - 1.0/x2)/8.0;
const double term2 = x*(r2 - 1.0/x2)*(r2 - 25.0/x2)/384.0;
*result = (-0.25*M_PI + term1 + term2);
return GSL_SUCCESS;
}
| {
"alphanum_fraction": 0.7202752096,
"avg_line_length": 24.6084656085,
"ext": "c",
"hexsha": "b1099b559ef42a751ae041c4abff0c6640e4e74c",
"lang": "C",
"max_forks_count": 40,
"max_forks_repo_forks_event_max_datetime": "2022-03-03T23:23:37.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-02-26T15:31:16.000Z",
"max_forks_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "manggoguy/parsec-modified",
"max_forks_repo_path": "pkgs/libs/gsl/src/specfunc/bessel_amp_phase.c",
"max_issues_count": 12,
"max_issues_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af",
"max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "manggoguy/parsec-modified",
"max_issues_repo_path": "pkgs/libs/gsl/src/specfunc/bessel_amp_phase.c",
"max_line_length": 84,
"max_stars_count": 64,
"max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "manggoguy/parsec-modified",
"max_stars_repo_path": "pkgs/libs/gsl/src/specfunc/bessel_amp_phase.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": 1805,
"size": 4651
} |
#pragma once
// Standard
#include <exception>
#include <cassert>
#include <string>
#include <iostream>
#include <sstream>
#include <fstream>
#include <memory>
#include <vector>
#include <map>
#include <stack>
#include <cstdint>
#include <iomanip>
#include <codecvt>
#include <algorithm>
#include <functional>
#include <limits>
#include <filesystem>
#include <tuple>
#include <iterator>
#include <random>
#include <cmath>
#if defined(DEBUG) || defined(_DEBUG)
#define _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>
#endif
// Guidelines Support Library
#include <gsl\gsl>
// Windows
#include <windows.h>
#include <winrt\Windows.Foundation.h>
// DirectX
#include <d3d11_3.h>
#include <dxgi1_2.h>
#include <DirectXMath.h>
#include <DirectXPackedVector.h>
#include <DirectXColors.h>
#include <DirectXTK\DDSTextureLoader.h>
#include <DirectXTK\WICTextureLoader.h>
#include <DirectXTK\SpriteBatch.h>
#include <DirectXTK\SpriteFont.h>
#include <DirectXTK\GamePad.h>
#include <DirectXTK\Keyboard.h>
#include <DirectXTK\Mouse.h> | {
"alphanum_fraction": 0.751450677,
"avg_line_length": 20.2745098039,
"ext": "h",
"hexsha": "5ccc7ea757f858affad947ddc1b6345e3995640e",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl",
"max_forks_repo_path": "source/Library.Shared/pch.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl",
"max_issues_repo_path": "source/Library.Shared/pch.h",
"max_line_length": 39,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl",
"max_stars_repo_path": "source/Library.Shared/pch.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 269,
"size": 1034
} |
// @file kn2row_conv.c
//
// \date Created on: Sep 23, 2017
// \author Gopalakrishna Hegde
//
// Description:
//
//
//
#include <assert.h>
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>
#include <cblas.h>
#include "common_types.h"
#include "data_reshape.h"
#include "utils.h"
//
// col_shift : +ve --> shift left overlap mat , -ve --> shift right overlap mat
// or shift left base mat and keep overlap mat as it is.
//
//
// row_shift : +ve (coeff is down the center coeff) --> shift up overlap mat ,
// -ve --> shift down overlap mat or shift up the base mat.
void MatrixShiftAdd(float *base_mat,
int base_no_rows, int base_no_cols,
float *overlap_mat,
int ov_no_rows, int ov_no_cols,
int row_shift, int col_shift) {
if (row_shift == 0 && col_shift == 0 && (base_no_rows == ov_no_rows) &&
(base_no_cols == ov_no_cols)) {
// normal matrix add
cblas_saxpy(base_no_rows * base_no_cols, 1.0, overlap_mat, 1, base_mat, 1);
return;
}
int rows_to_add, cols_to_add;
int base_row_start, base_col_start;
int ov_row_start, ov_col_start;
// without padding case
if (ov_no_rows > base_no_rows) {
rows_to_add = base_no_rows;
cols_to_add = base_no_cols;
base_row_start = 0;
base_col_start = 0;
ov_row_start = row_shift < 0? -row_shift : 0;
ov_col_start = col_shift < 0? -col_shift : 0;
} else {
rows_to_add = ov_no_rows - abs(row_shift);
cols_to_add = ov_no_cols - abs(col_shift);
ov_col_start = col_shift > 0? col_shift : 0;
ov_row_start = row_shift > 0? row_shift : 0;
base_row_start = row_shift < 0? -row_shift : 0;
base_col_start = col_shift < 0? -col_shift : 0;
}
for (int r = 0; r < rows_to_add; ++r) {
int base_mat_offset = (r + base_row_start) * base_no_cols + base_col_start;
int overlap_mat_offset = (r + ov_row_start) * ov_no_cols + ov_col_start;
cblas_saxpy(cols_to_add, 1.0, overlap_mat + overlap_mat_offset, 1,
base_mat + base_mat_offset, 1);
}
}
/* Ker2Row convolution implementations.
*
* Assumptions:
* 1. in_data is in NCHW format.
* 2. filters are in MCKK format where M is the no of output maps.
* 3. Stride will always be 1.
* 4. pad will be zero or kernel_size / 2
*
* Output will be in NCHW format.
*/
bool Kn2RowConvLayer(const float *in_data, const float *filters,
const float *bias, TensorDim in_dim,
TensorDim filt_dim, int stride, int pad, int group,
float *output) {
// Currently we have limited support.
assert(group == 1);
assert((pad == 0) || (pad == filt_dim.w / 2));
assert(in_dim.n == 1);
assert(filt_dim.h == filt_dim.w);
assert(stride == 1);
// Output dimensions.
TensorDim out_dim;
out_dim.w = (in_dim.w + (pad + pad) - filt_dim.w) / stride + 1;
out_dim.h = (in_dim.h + (pad + pad) - filt_dim.h) / stride + 1;
out_dim.c = filt_dim.n;
out_dim.n = in_dim.n;
// Re-arrange filters in the k x k x no_out_maps x no_in_maps.
// We can avoid this if the filters are already reshaped in this format.
float *kkmc_filters = malloc(filt_dim.n * filt_dim.c * filt_dim.h *
filt_dim.w * sizeof(float));
NCHW2HWNC(filters, filt_dim.n, filt_dim.c, filt_dim.h, filt_dim.w,
kkmc_filters);
// Just for convenience
int H = in_dim.h;
int W = in_dim.w;
float alpha = 1.0;
float beta = 0.0;
// We need separate buffer because GEMM output will have width = H*W even
// if there is no padding (pad = 0).
float *gemm_output = malloc(out_dim.c * H * W * sizeof(float));
// Prefill output buffer with bias if present else set to zero.
if (bias) {
for (int m = 0; m < out_dim.c; ++m) {
for (int a = 0; a < out_dim.h * out_dim.w; ++a) {
output[m * out_dim.h * out_dim.w + a] = bias[m];
}
// For batch size > 1
for (int b = 1; b < out_dim.n; ++b) {
memcpy(output + b * out_dim.c * out_dim.h * out_dim.w,
output, out_dim.c * out_dim.h * out_dim.w * sizeof(float));
}
}
} else {
memset(output, 0, out_dim.n * out_dim.c * out_dim.h * out_dim.w *
sizeof(float));
}
for (int kr = 0; kr < filt_dim.h; kr++) {
int row_shift = kr - filt_dim.h / 2;
for (int kc = 0; kc < filt_dim.w; kc++) {
int group_no = kr * filt_dim.w + kc;
int col_shift = kc - filt_dim.w / 2;
// Matrix dimensions - A -> mxk B -> kxn C --> mxn
int m = filt_dim.n;
int k = filt_dim.c;
int n = in_dim.h * in_dim.w;
// This is just 1x1 convolution
cblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans,
m, n, k, alpha, kkmc_filters + group_no * m * k,
k, in_data, n, beta, gemm_output, n);
// Slide the resulting matrix which has contribution from one of the
// KxK kernel coefficients and add to the output.
for (int omap = 0; omap < filt_dim.n; omap++) {
MatrixShiftAdd(output + omap * out_dim.h * out_dim.w,
out_dim.h, out_dim.w,
gemm_output + omap * H * W,
H, W, row_shift, col_shift);
}
}
}
free(kkmc_filters);
free(gemm_output);
return true;
}
| {
"alphanum_fraction": 0.601581623,
"avg_line_length": 34.0448717949,
"ext": "c",
"hexsha": "20ff16aab7b061f00cfa0f70a161778822c7558a",
"lang": "C",
"max_forks_count": 23,
"max_forks_repo_forks_event_max_datetime": "2021-12-21T14:16:14.000Z",
"max_forks_repo_forks_event_min_datetime": "2017-10-24T05:17:21.000Z",
"max_forks_repo_head_hexsha": "c5f612d35888e224aa610408a7fc9f08f232147c",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "chayitw/convolution-flavors",
"max_forks_repo_path": "src/kn2row_conv.c",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "c5f612d35888e224aa610408a7fc9f08f232147c",
"max_issues_repo_issues_event_max_datetime": "2021-10-16T02:49:23.000Z",
"max_issues_repo_issues_event_min_datetime": "2021-10-16T02:49:23.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "chayitw/convolution-flavors",
"max_issues_repo_path": "src/kn2row_conv.c",
"max_line_length": 79,
"max_stars_count": 54,
"max_stars_repo_head_hexsha": "c5f612d35888e224aa610408a7fc9f08f232147c",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "gplhegde/convolution-flavors",
"max_stars_repo_path": "src/kn2row_conv.c",
"max_stars_repo_stars_event_max_datetime": "2022-01-12T06:38:50.000Z",
"max_stars_repo_stars_event_min_datetime": "2017-10-03T18:10:24.000Z",
"num_tokens": 1567,
"size": 5311
} |
/***************************************************************************
* Copyright (C) 2008 by Mikhail Zaslavskiy *
* mikhail.zaslavskiy@ensmp.fr *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
#ifndef ALGORITHM_H
#define ALGORITHM_H
#define EPSILON 1e-100
#include "rpc.h"
#include "graph.h"
#include <math.h>
#include "hungarian.h"
#include <gsl/gsl_blas.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_permutation.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
#include <gsl/gsl_linalg.h>
#include <gsl/gsl_eigen.h>
#include <vector>
#include <iostream>
/**
Class of graph matching results
*/
class match_result
{
public:
match_result(){gm_P=NULL;gm_P_exact=NULL;salgo="";}
std::vector<double> vd_trace;
int inum_iteration;
double dres;
gsl_matrix* gm_P;
gsl_matrix* gm_P_exact;
double dtime;
double dfvalue;
double dfvalue_exact;
std::string salgo;
~match_result(){};
};
/**
Parent class for all graph matching algorithms
@author Mikhail Zaslavskiy <mikhail.zaslavskiy@ensmp.fr>
*/
class algorithm : public rpc
{
public:
algorithm(std::string );
algorithm();
match_result gmatch(graph& g, graph& h,gsl_matrix* gm_P_i=NULL, gsl_matrix* gm_ldh=NULL,double dalpha_ldh=-1);//common stuff,
virtual match_result match(graph& g, graph& h, gsl_matrix* gm_P_i=NULL, gsl_matrix* gm_ldh=NULL,double dalpha_ldh=-1)=0;//particular method implementation
double graph_dist(graph &g,graph &h,gsl_matrix* gm_P,char cscore_matrix);
double graph_dist(graph &g, graph &h,char cscore_matrix);
~algorithm();
const gsl_matrix* get_ldhmatrix(){return gm_ldh;};
void set_ldhmatrix(const gsl_matrix* _gm_A);
protected:
gsl_matrix *gm_ldh;
double dalpha_ldh;
void update_C_hungarian(gsl_matrix* gm_C,int isign=1, bool bback=false);
double f_qcv(gsl_matrix *gm_Ag_d,gsl_matrix *gm_Ah_d,gsl_matrix* gm_P,gsl_matrix * gm_temp,bool bqcv=false);
char cdesc_matrix,cscore_matrix;
parameter pdebug,pdebug_f;
bool bverbose;
std::string sverbfile;
std::ofstream fverbose;
long long N;
double df_norm;
bool bnosymm;
};
#endif
| {
"alphanum_fraction": 0.6013229104,
"avg_line_length": 34.2886597938,
"ext": "h",
"hexsha": "e866f1779ad99a76531b02b271358ff9d3266df7",
"lang": "C",
"max_forks_count": 7,
"max_forks_repo_forks_event_max_datetime": "2021-08-06T01:41:25.000Z",
"max_forks_repo_forks_event_min_datetime": "2016-08-23T11:44:05.000Z",
"max_forks_repo_head_hexsha": "52f579a07d106cb241d21dbc29a2ec9e9c77b254",
"max_forks_repo_licenses": [
"Unlicense"
],
"max_forks_repo_name": "mk2510/jointGraphMatchingAndClustering",
"max_forks_repo_path": "code/clustered_setup/fgm-master/LSGMcode-master/algorithms/graphm-0.52/algorithm.h",
"max_issues_count": 2,
"max_issues_repo_head_hexsha": "52f579a07d106cb241d21dbc29a2ec9e9c77b254",
"max_issues_repo_issues_event_max_datetime": "2016-08-24T11:14:00.000Z",
"max_issues_repo_issues_event_min_datetime": "2015-02-20T01:53:58.000Z",
"max_issues_repo_licenses": [
"Unlicense"
],
"max_issues_repo_name": "mk2510/jointGraphMatchingAndClustering",
"max_issues_repo_path": "code/clustered_setup/fgm-master/LSGMcode-master/algorithms/graphm-0.52/algorithm.h",
"max_line_length": 159,
"max_stars_count": 10,
"max_stars_repo_head_hexsha": "52f579a07d106cb241d21dbc29a2ec9e9c77b254",
"max_stars_repo_licenses": [
"Unlicense"
],
"max_stars_repo_name": "mk2510/jointGraphMatchingAndClustering",
"max_stars_repo_path": "code/clustered_setup/fgm-master/LSGMcode-master/algorithms/graphm-0.52/algorithm.h",
"max_stars_repo_stars_event_max_datetime": "2021-02-08T21:38:55.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-08-27T14:10:38.000Z",
"num_tokens": 780,
"size": 3326
} |
#pragma once
#include <utility>
#include <initializer_list>
#include <exception>
#include <iostream>
#include <cmath>
#include <gsl/gsl_math.h>
#include <gsl/gsl_linalg.h>
#include "bits/matrix-view.h"
#include "utils/fcmp.h"
#include "vector.h"
namespace gsl_wrapper
{
class Matrix
{
public:
// Constructors and destructor
Matrix(size_t i, size_t j);
Matrix(size_t matrix_size);
Matrix(std::initializer_list<std::initializer_list<double>> args);
Matrix(const Vector &vec);
Matrix(const Matrix ©_from);
Matrix(Matrix &&move_from);
~Matrix();
// Member functions
auto get_gsl_matrix() const -> gsl_matrix *;
auto get_dimensions() const -> std::pair<size_t, size_t>;
auto num_rows() const -> size_t;
auto num_collumns() const -> size_t;
// Operators
auto operator=(const Matrix ©_from) -> Matrix &;
auto operator=(Matrix &&move_from) -> Matrix &;
auto operator==(const Matrix &comparasion_matrix) const -> bool;
auto operator!=(const Matrix &comparasion_matrix) const -> bool;
auto operator[](const size_t index) const -> gsl_wrapper::bits::MatrixRow;
auto operator*(const Matrix &mul) const -> Matrix;
auto operator*(const double number) const -> Matrix;
auto operator+(const Matrix &matrix) const -> Matrix;
auto operator+(const double numer) const -> Matrix;
// Friend declarations
friend auto operator<<(std::ostream &stream, const Matrix &matrix) -> std::ostream &;
friend auto operator*(const double number, const Matrix &matrix) -> Matrix;
friend auto operator+(const double number, const Matrix &matrix) -> Matrix;
private:
gsl_matrix *m_matrixPtr;
size_t m_numRows;
size_t m_numCollumns;
};
inline Matrix::Matrix(size_t i, size_t j)
: m_matrixPtr{gsl_matrix_calloc(i, j)}, m_numRows{i}, m_numCollumns{j}
{
}
inline Matrix::Matrix(size_t matrix_size)
: Matrix(matrix_size, matrix_size)
{
}
inline Matrix::Matrix(std::initializer_list<std::initializer_list<double>> args)
: m_matrixPtr{nullptr}, m_numCollumns{0}, m_numRows{0}
{
if (args.size() == 0)
return;
size_t num_rows = args.size();
size_t num_collumns = (*args.begin()).size();
// Setting object properties
m_numCollumns = num_collumns;
m_numRows = num_rows;
m_matrixPtr = gsl_matrix_calloc(m_numRows, m_numCollumns);
size_t row_iterator = 0;
size_t collumn_iterator = 0;
for (auto &&row : args)
{
if (row.size() != num_collumns)
throw std::range_error{"Diffrent number of items in diffrent rows when creating matrix"};
for (auto &&el : row)
{
(*this)[row_iterator][collumn_iterator++] = el;
}
collumn_iterator = 0;
++row_iterator;
}
}
inline Matrix::Matrix(const Vector &vec)
: m_matrixPtr{gsl_matrix_calloc(vec.size(), 1)},
m_numCollumns{1},
m_numRows{vec.size()}
{
for (size_t i = 0; i < m_numRows; i++)
{
(*this)[i][0] = vec[i];
}
}
inline Matrix::Matrix(const Matrix ©_from)
: m_matrixPtr{gsl_matrix_calloc(copy_from.m_numRows, copy_from.m_numCollumns)},
m_numRows{copy_from.m_numRows},
m_numCollumns{copy_from.m_numCollumns}
{
gsl_matrix_memcpy(m_matrixPtr, copy_from.m_matrixPtr);
}
inline Matrix::Matrix(Matrix &&move_from)
: m_matrixPtr{std::exchange(move_from.m_matrixPtr, nullptr)},
m_numRows{std::exchange(move_from.m_numRows, 0)},
m_numCollumns{std::exchange(move_from.m_numCollumns, 0)}
{
}
inline Matrix::~Matrix()
{
gsl_matrix_free(m_matrixPtr);
}
inline auto Matrix::get_gsl_matrix() const -> gsl_matrix *
{
return m_matrixPtr;
}
inline auto Matrix::get_dimensions() const -> std::pair<size_t, size_t>
{
return {m_numRows, m_numCollumns};
}
inline auto Matrix::num_rows() const -> size_t
{
return m_numRows;
}
inline auto Matrix::num_collumns() const -> size_t
{
return m_numCollumns;
}
inline auto Matrix::operator=(const Matrix ©_from) -> Matrix &
{
// Prevent self copy
if (m_matrixPtr == copy_from.m_matrixPtr)
return *this;
gsl_matrix_free(m_matrixPtr);
m_matrixPtr = gsl_matrix_calloc(copy_from.m_numRows, copy_from.m_numCollumns);
gsl_matrix_memcpy(m_matrixPtr, copy_from.m_matrixPtr);
m_numCollumns = copy_from.m_numCollumns;
m_numRows = copy_from.m_numRows;
return *this;
}
inline auto Matrix::operator=(Matrix &&move_from) -> Matrix &
{
// Prevent self move
if (m_matrixPtr == move_from.m_matrixPtr)
return *this;
gsl_matrix_free(m_matrixPtr);
m_matrixPtr = std::exchange(move_from.m_matrixPtr, nullptr);
m_numRows = std::exchange(move_from.m_numRows, 0);
m_numCollumns = std::exchange(move_from.m_numCollumns, 0);
return *this;
}
inline auto Matrix::operator==(const Matrix &comparasion_matrix) const -> bool
{
if ((m_numCollumns != comparasion_matrix.m_numCollumns) || (m_numRows != comparasion_matrix.m_numRows))
return false;
for (size_t i = 0; i < m_numRows; i++)
{
for (size_t j = 0; j < m_numCollumns; j++)
{
bool test = ::gsl_wrapper::utils::equal((*this)[i][j], comparasion_matrix[i][j]);
if (!test)
return false;
}
}
return true;
}
inline auto Matrix::operator!=(const Matrix &comparasion_matrix) const -> bool
{
return !(*this == comparasion_matrix);
}
inline auto Matrix::operator[](const size_t index) const -> gsl_wrapper::bits::MatrixRow
{
using bits::MatrixRow;
gsl_vector_view view = gsl_matrix_row(m_matrixPtr, index);
return MatrixRow(view);
}
inline auto Matrix::operator*(const Matrix &mul) const -> Matrix
{
// Check sizes
if (m_numCollumns != mul.m_numRows)
throw std::runtime_error{"Wrong matrix sizes!"};
Matrix result(m_numRows, mul.m_numCollumns);
gsl_blas_dgemm(CblasNoTrans, CblasNoTrans, 1.0, m_matrixPtr, mul.m_matrixPtr, 0.0, result.get_gsl_matrix());
return result;
}
inline auto Matrix::operator*(const double number) const -> Matrix
{
Matrix result = *this;
for (size_t i = 0; i < m_numRows; i++)
{
for (size_t j = 0; j < m_numCollumns; j++)
{
result[i][j] *= number;
}
}
return result;
}
inline auto Matrix::operator+(const Matrix &matrix) const -> Matrix
{
if ((m_numCollumns != matrix.m_numCollumns) || (m_numRows != matrix.m_numRows))
throw std::range_error{"Wrong matrix sizes when adding"};
Matrix result = *this;
gsl_matrix_add(result.m_matrixPtr, matrix.m_matrixPtr);
return result;
}
inline auto Matrix::operator+(const double number) const -> Matrix
{
Matrix result = *this;
for (size_t i = 0; i < m_numRows; i++)
{
for (size_t j = 0; j < m_numCollumns; j++)
{
result[i][j] += number;
}
}
return result;
}
inline auto operator<<(std::ostream &stream, const Matrix &matrix) -> std::ostream &
{
for (size_t i = 0; i < matrix.m_numRows; i++)
{
for (size_t j = 0; j < matrix.m_numCollumns; j++)
{
stream << matrix[i][j] << " ";
}
stream << std::endl;
}
return stream;
}
inline auto operator*(const double number, const Matrix &matrix) -> Matrix
{
Matrix result = matrix;
for (size_t i = 0; i < matrix.m_numRows; i++)
{
for (size_t j = 0; j < matrix.m_numCollumns; j++)
{
result[i][j] *= number;
}
}
return result;
}
inline auto operator+(const double number, const Matrix &matrix) -> Matrix
{
Matrix result = matrix;
for (size_t i = 0; i < matrix.m_numRows; i++)
{
for (size_t j = 0; j < matrix.m_numCollumns; j++)
{
result[i][j] += number;
}
}
return result;
}
}
| {
"alphanum_fraction": 0.6409769679,
"avg_line_length": 25.9934210526,
"ext": "h",
"hexsha": "d786246debb611da3f8a57345e023e86ee4894c6",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2022-03-10T09:06:07.000Z",
"max_forks_repo_forks_event_min_datetime": "2022-03-10T09:06:07.000Z",
"max_forks_repo_head_hexsha": "0c9c4edfe751474edbf1a9a23075762cc3362cc1",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "Szynkaa/gsl_cpp_wrapper",
"max_forks_repo_path": "include/gsl_wrapper/matrix.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "0c9c4edfe751474edbf1a9a23075762cc3362cc1",
"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": "Szynkaa/gsl_cpp_wrapper",
"max_issues_repo_path": "include/gsl_wrapper/matrix.h",
"max_line_length": 112,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "0c9c4edfe751474edbf1a9a23075762cc3362cc1",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "Szynkaa/gsl_cpp_wrapper",
"max_stars_repo_path": "include/gsl_wrapper/matrix.h",
"max_stars_repo_stars_event_max_datetime": "2022-03-09T14:35:36.000Z",
"max_stars_repo_stars_event_min_datetime": "2022-03-09T14:35:36.000Z",
"num_tokens": 2171,
"size": 7902
} |
/* block/test.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.
*/
#include <config.h>
#include <fcntl.h>
#include <stdlib.h>
#include <stdio.h>
#include <gsl/gsl_block.h>
#include <gsl/gsl_ieee_utils.h>
#include <gsl/gsl_test.h>
int status = 0;
#ifndef DESC
#define DESC ""
#endif
#define N 1027
#define BASE_GSL_COMPLEX_LONG
#include "templates_on.h"
#include "test_complex_source.c"
#if HAVE_PRINTF_LONGDOUBLE
#include "test_complex_io.c"
#endif
#include "templates_off.h"
#undef BASE_GSL_COMPLEX_LONG
#define BASE_GSL_COMPLEX
#include "templates_on.h"
#include "test_complex_source.c"
#include "test_complex_io.c"
#include "templates_off.h"
#undef BASE_GSL_COMPLEX
#define BASE_GSL_COMPLEX_FLOAT
#include "templates_on.h"
#include "test_complex_source.c"
#include "test_complex_io.c"
#include "templates_off.h"
#undef BASE_GSL_COMPLEX_FLOAT
#define BASE_LONG_DOUBLE
#include "templates_on.h"
#include "test_source.c"
#if HAVE_PRINTF_LONGDOUBLE
#include "test_io.c"
#endif
#include "templates_off.h"
#undef BASE_LONG_DOUBLE
#define BASE_DOUBLE
#include "templates_on.h"
#include "test_source.c"
#include "test_io.c"
#include "templates_off.h"
#undef BASE_DOUBLE
#define BASE_FLOAT
#include "templates_on.h"
#include "test_source.c"
#include "test_io.c"
#include "templates_off.h"
#undef BASE_FLOAT
#define BASE_ULONG
#include "templates_on.h"
#include "test_source.c"
#include "test_io.c"
#include "templates_off.h"
#undef BASE_ULONG
#define BASE_LONG
#include "templates_on.h"
#include "test_source.c"
#include "test_io.c"
#include "templates_off.h"
#undef BASE_LONG
#define BASE_UINT
#include "templates_on.h"
#include "test_source.c"
#include "test_io.c"
#include "templates_off.h"
#undef BASE_UINT
#define BASE_INT
#include "templates_on.h"
#include "test_source.c"
#include "test_io.c"
#include "templates_off.h"
#undef BASE_INT
#define BASE_USHORT
#include "templates_on.h"
#include "test_source.c"
#include "test_io.c"
#include "templates_off.h"
#undef BASE_USHORT
#define BASE_SHORT
#include "templates_on.h"
#include "test_source.c"
#include "test_io.c"
#include "templates_off.h"
#undef BASE_SHORT
#define BASE_UCHAR
#include "templates_on.h"
#include "test_source.c"
#include "test_io.c"
#include "templates_off.h"
#undef BASE_UCHAR
#define BASE_CHAR
#include "templates_on.h"
#include "test_source.c"
#include "test_io.c"
#include "templates_off.h"
#undef BASE_CHAR
void my_error_handler (const char *reason, const char *file,
int line, int err);
int
main (void)
{
gsl_ieee_env_setup ();
test_func ();
test_float_func ();
test_long_double_func ();
test_ulong_func ();
test_long_func ();
test_uint_func ();
test_int_func ();
test_ushort_func ();
test_short_func ();
test_uchar_func ();
test_char_func ();
test_complex_func ();
test_complex_float_func ();
test_complex_long_double_func ();
test_text ();
test_float_text ();
#if HAVE_PRINTF_LONGDOUBLE
test_long_double_text ();
#endif
test_ulong_text ();
test_long_text ();
test_uint_text ();
test_int_text ();
test_ushort_text ();
test_short_text ();
test_uchar_text ();
test_char_text ();
test_complex_text ();
test_complex_float_text ();
#if HAVE_PRINTF_LONGDOUBLE
test_complex_long_double_text ();
#endif
test_binary ();
test_float_binary ();
test_long_double_binary ();
test_ulong_binary ();
test_long_binary ();
test_uint_binary ();
test_int_binary ();
test_ushort_binary ();
test_short_binary ();
test_uchar_binary ();
test_char_binary ();
test_complex_binary ();
test_complex_float_binary ();
test_complex_long_double_binary ();
gsl_set_error_handler (&my_error_handler);
test_alloc_zero_length ();
test_float_alloc_zero_length ();
test_long_double_alloc_zero_length ();
test_ulong_alloc_zero_length ();
test_long_alloc_zero_length ();
test_uint_alloc_zero_length ();
test_int_alloc_zero_length ();
test_ushort_alloc_zero_length ();
test_short_alloc_zero_length ();
test_uchar_alloc_zero_length ();
test_char_alloc_zero_length ();
test_complex_alloc_zero_length ();
test_complex_float_alloc_zero_length ();
test_complex_long_double_alloc_zero_length ();
test_calloc_zero_length ();
test_float_calloc_zero_length ();
test_long_double_calloc_zero_length ();
test_ulong_calloc_zero_length ();
test_long_calloc_zero_length ();
test_uint_calloc_zero_length ();
test_int_calloc_zero_length ();
test_ushort_calloc_zero_length ();
test_short_calloc_zero_length ();
test_uchar_calloc_zero_length ();
test_char_calloc_zero_length ();
test_complex_calloc_zero_length ();
test_complex_float_calloc_zero_length ();
test_complex_long_double_calloc_zero_length ();
exit (gsl_test_summary ());
}
void
my_error_handler (const char *reason, const char *file, int line, int err)
{
if (0)
printf ("(caught [%s:%d: %s (%d)])\n", file, line, reason, err);
status = 1;
}
| {
"alphanum_fraction": 0.7533333333,
"avg_line_length": 23.8493723849,
"ext": "c",
"hexsha": "fc104175e41f676f3d678e99112151b656320081",
"lang": "C",
"max_forks_count": 224,
"max_forks_repo_forks_event_max_datetime": "2022-03-30T00:57:48.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-11-12T21:17:03.000Z",
"max_forks_repo_head_hexsha": "70dc728926a835ba049ddd3f4627ef08db7c95a0",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "utdsimmons/ohpc",
"max_forks_repo_path": "tests/libs/gsl/tests/block/test.c",
"max_issues_count": 1096,
"max_issues_repo_head_hexsha": "70dc728926a835ba049ddd3f4627ef08db7c95a0",
"max_issues_repo_issues_event_max_datetime": "2022-03-31T21:48:41.000Z",
"max_issues_repo_issues_event_min_datetime": "2015-11-12T09:08:22.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "utdsimmons/ohpc",
"max_issues_repo_path": "tests/libs/gsl/tests/block/test.c",
"max_line_length": 81,
"max_stars_count": 692,
"max_stars_repo_head_hexsha": "70dc728926a835ba049ddd3f4627ef08db7c95a0",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "utdsimmons/ohpc",
"max_stars_repo_path": "tests/libs/gsl/tests/block/test.c",
"max_stars_repo_stars_event_max_datetime": "2022-03-30T03:45:59.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-11-12T13:56:43.000Z",
"num_tokens": 1364,
"size": 5700
} |
#include <gsl/gsl_spline.h>
#include <galpy_potentials.h>
// interpSphericalPotential: 6 arguments: amp (not used here), rmin, rmax,
// M(<rmax), Phi0, Phimax
double interpSphericalPotentialrevaluate(double r,double t,
struct potentialArg * potentialArgs){
double * args= potentialArgs->args;
//Get args
double rmin= *(args+1);
double rmax= *(args+2);
double Mmax= *(args+3);
double Phi0= *(args+4);
double Phimax= *(args+5);
if ( r >= rmax ) {
return -Mmax/r+Phimax;
}
else {
return r < rmin ? 0. : \
-gsl_spline_eval_integ(*potentialArgs->spline1d,
rmin,r,*potentialArgs->acc1d) + Phi0;
}
}
double interpSphericalPotentialrforce(double r,double t,
struct potentialArg * potentialArgs){
double * args= potentialArgs->args;
//Get args
double rmin= *(args+1);
double rmax= *(args+2);
double Mmax= *(args+3);
if ( r >= rmax ) {
return -Mmax/r/r;
}
else {
return r < rmin ? 0. : gsl_spline_eval(*potentialArgs->spline1d,
r,*potentialArgs->acc1d);
}
}
double interpSphericalPotentialr2deriv(double r,double t,
struct potentialArg * potentialArgs){
double * args= potentialArgs->args;
//Get args
double rmin= *(args+1);
double rmax= *(args+2);
double Mmax= *(args+3);
if ( r >= rmax ) {
return -2. * Mmax / r / r / r;
}
else {
return r < rmin ? 0. : -gsl_spline_eval_deriv(*potentialArgs->spline1d,
r,*potentialArgs->acc1d);
}
}
double interpSphericalPotentialrdens(double r,double t,
struct potentialArg * potentialArgs){
double * args= potentialArgs->args;
//Get args
double rmin= *(args+1);
double rmax= *(args+2);
if ( r >= rmax ) {
return 0.;
}
else {
return r < rmin ? 0. : M_1_PI / 4. \
* ( interpSphericalPotentialr2deriv(r,t,potentialArgs)
- 2. * interpSphericalPotentialrforce(r,t,potentialArgs)/r);
}
}
| {
"alphanum_fraction": 0.6365079365,
"avg_line_length": 27.7941176471,
"ext": "c",
"hexsha": "3f0994ec913e4304222daaf011ae0fd72eed95e0",
"lang": "C",
"max_forks_count": 110,
"max_forks_repo_forks_event_max_datetime": "2021-12-28T07:56:49.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-02-08T10:57:24.000Z",
"max_forks_repo_head_hexsha": "d6db971285f163456c81775fc2fdc7d75189762c",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "gusbeane/galpy",
"max_forks_repo_path": "galpy/potential/potential_c_ext/interpSphericalPotential.c",
"max_issues_count": 269,
"max_issues_repo_head_hexsha": "d6db971285f163456c81775fc2fdc7d75189762c",
"max_issues_repo_issues_event_max_datetime": "2022-03-30T18:42:08.000Z",
"max_issues_repo_issues_event_min_datetime": "2015-01-07T15:58:31.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "gusbeane/galpy",
"max_issues_repo_path": "galpy/potential/potential_c_ext/interpSphericalPotential.c",
"max_line_length": 75,
"max_stars_count": 147,
"max_stars_repo_head_hexsha": "d6db971285f163456c81775fc2fdc7d75189762c",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "gusbeane/galpy",
"max_stars_repo_path": "galpy/potential/potential_c_ext/interpSphericalPotential.c",
"max_stars_repo_stars_event_max_datetime": "2022-03-24T14:47:41.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-01-01T14:06:17.000Z",
"num_tokens": 604,
"size": 1890
} |
#include "solver_intern.h"
#include <pygsl/general_helpers.h>
#include <pygsl/block_helpers.h>
#if 0
#include <pygsl/function_helpers.h>
#endif
#include <setjmp.h>
#include <gsl/gsl_math.h>
#include <pygsl/error_helpers.h>
#include <strings.h>
#include "solver_doc.ic"
PyObject * module = NULL;
const char *filename = __FILE__;
static int
PyGSL_solver_set_called(PyGSL_solver *self)
{
FUNC_MESS_BEGIN();
if(self->set_called == 1)
return GSL_SUCCESS;
DEBUG_MESS(2, "self->set_called was %d", self->set_called);
pygsl_error("The set() method must be called before using the other methods!",
filename, __LINE__, GSL_EINVAL);
FUNC_MESS_END();
return GSL_EINVAL;
}
static PyObject*
PyGSL_solver_restart(PyGSL_solver *self, PyObject *args)
{
FUNC_MESS_BEGIN();
if (PyGSL_SOLVER_SET_CALLED(self) != GSL_SUCCESS)
return NULL;
if(self->mstatic->cmethods.restart == NULL)
PyGSL_ERROR_NULL("Can not restart a solver of this type!", GSL_ESANITY);
self->mstatic->cmethods.restart(self->solver);
Py_INCREF(Py_None);
FUNC_MESS_END();
return Py_None;
}
static PyObject*
PyGSL_solver_name(PyGSL_solver *self, PyObject *args)
{
PyObject * tmp;
const char * ctmp;
FUNC_MESS_BEGIN();
if(self->mstatic->cmethods.name == NULL)
PyGSL_ERROR_NULL("Can not restart a solver of this type!", GSL_ESANITY);
ctmp = self->mstatic->cmethods.name(self->solver);
tmp = PyString_FromString(ctmp);
FUNC_MESS_END();
return tmp;
}
static PyObject*
PyGSL_solver_iterate(PyGSL_solver *self, PyObject *args)
{
int tmp;
FUNC_MESS_BEGIN();
if (PyGSL_SOLVER_SET_CALLED(self) != GSL_SUCCESS)
return NULL;
if(self->mstatic->cmethods.iterate == NULL)
PyGSL_ERROR_NULL("Can not restart a solver of this type!", GSL_ESANITY);
assert(self->mstatic->cmethods.iterate);
assert(self->solver);
tmp = (self->mstatic->cmethods.iterate(self->solver));
if(PyGSL_ERROR_FLAG(tmp) != GSL_SUCCESS)
return NULL;
return PyInt_FromLong((long) tmp);
}
static void
PyGSL_solver_dealloc(PyGSL_solver * self)
{
/* struct pygsl_array_cache * cache_ptr;
int i, count;
PyObject * ob;
PyArrayObject *tmp;
*/
FUNC_MESS_BEGIN();
assert(self);
assert(self->mstatic);
if(self->mstatic->cmethods.free == NULL){
DEBUG_MESS(3, "Could not free solver @ %p. No free method specified!", self->solver);
}else{
DEBUG_MESS(3, "Freeing a solver of type %s", self->mstatic->type_name);
if(self->solver != NULL){
self->mstatic->cmethods.free(self->solver);
self->solver = NULL;
}
}
Py_XDECREF(self->args);
self->args = NULL;
if(self->c_sys){
DEBUG_MESS(3, "Freeing c_sys @ %p", self->c_sys);
free(self->c_sys);
self->c_sys = NULL;
}
/*
* remove the cached arrays
*/
if(self->cache == NULL){
DEBUG_MESS(2, "No cache was used cache = %p", self->cache);
}else{
#if 0
cache_ptr = self->cache;
for(i = 0; i< PyGSL_SOLVER_N_ARRAYS; ++i){
tmp = cache_ptr[i].ref;
ob = (PyObject *) tmp;
if(ob == NULL){
break;
}
count = ob->ob_refcnt;
if(count == 0){
DEBUG_MESS(3, "object[%d] @ %p has a zero reference count!"
" array should be deposed already and ptr set to zero!", i, ob);
}else if(count == 1){
/* no one referencing the array; good */
DEBUG_MESS(3, "Dereferencing object[%d] @ %p", i, ob);
Py_DECREF(ob);
cache_ptr[i].ref = NULL;
}else if(count < 0){
DEBUG_MESS(2, "I found an array (object) at %p which had "
"a count [%d] smaller than zero", ob, count);
}else{
/* count > 1 */
fprintf(stderr, "In %s at %d array %d had %d refcouts.\n"
"This means you reference an array which was\n"
"passed to you while evaluating your callback.\n"
"This produces a memory leak!\n",
__FILE__, __LINE__, i, count);
}
} /* handeled cached objects */
fprintf(stderr, "Freed %d cached objects\n", i);
/* free the cache */
free(self->cache);
self->cache = NULL;
#endif
} /* freeing cached objects */
PyObject_Del(self);
self = NULL;
FUNC_MESS_END();
}
static PyObject *
PyGSL_solver_type(PyGSL_solver * self, PyObject *unused)
{
assert(self->mstatic->type_name);
return PyString_FromString(self->mstatic->type_name);
}
static PyMethodDef solver_methods[] = {
{"name", (PyCFunction) PyGSL_solver_name, METH_NOARGS, NULL},
{"restart", (PyCFunction) PyGSL_solver_restart, METH_NOARGS, NULL},
{"iterate", (PyCFunction) PyGSL_solver_iterate, METH_NOARGS, NULL},
{"type", (PyCFunction) PyGSL_solver_type, METH_NOARGS, NULL},
{NULL, NULL, 0, NULL}
};
static PyObject *
PyGSL_solver_getattr(PyGSL_solver * self, char * name)
{
PyObject *tmp = NULL;
FUNC_MESS_BEGIN();
if(self->mstatic->pymethods)
tmp = Py_FindMethod(self->mstatic->pymethods, (PyObject *) self, name);
if(tmp == NULL){
PyErr_Clear();
tmp = Py_FindMethod(solver_methods, (PyObject *) self, name);
}
FUNC_MESS_END();
return tmp;
}
static PyTypeObject PyGSL_solver_pytype = {
PyObject_HEAD_INIT(NULL) /* fix up the type slot in initcrng */
0, /* ob_size */
"PyGSL_solver", /* tp_name */
sizeof(PyGSL_solver), /* tp_basicsize */
0, /* tp_itemsize */
/* standard methods */
(destructor) PyGSL_solver_dealloc, /* tp_dealloc ref-count==0 */
(printfunc) 0, /* tp_print "print x" */
(getattrfunc) PyGSL_solver_getattr,/* tp_getattr "x.attr" */
(setattrfunc) 0, /* tp_setattr "x.attr=v" */
(cmpfunc) 0, /* tp_compare "x > y" */
(reprfunc) 0, /* tp_repr `x`, print x */
/* type categories */
0, /* tp_as_number +,-,*,/,%,&,>>,pow...*/
0, /* tp_as_sequence +,[i],[i:j],len, ...*/
0, /* tp_as_mapping [key], len, ...*/
/* more methods */
(hashfunc) 0, /* tp_hash "dict[x]" */
(ternaryfunc) 0, /* tp_call "x()" */
(reprfunc) 0, /* tp_str "str(x)" */
(getattrofunc) 0, /* tp_getattro */
(setattrofunc) 0, /* tp_setattro */
0, /* tp_as_buffer */
0L, /* tp_flags */
(char *) PyGSL_solver_type_doc /* tp_doc */
};
PyGSL_solver*
_PyGSL_solver_init(const struct _SolverStatic *mstatic)
{
PyGSL_solver *solver_o=NULL;
int line = -1;
int i;
FUNC_MESS_BEGIN();
if(mstatic->n_cbs > PyGSL_SOLVER_NCBS_MAX){
line = __LINE__ - 1;
pygsl_error("More callbacks requested than possible!", __FILE__,
line, GSL_ESANITY);
goto fail;
}
solver_o = (PyGSL_solver *) PyObject_NEW(PyGSL_solver, &PyGSL_solver_pytype);
if(solver_o == NULL){
line = __LINE__ -1;
goto fail;
}
solver_o->args = NULL;
solver_o->cache = NULL;
solver_o->mstatic = NULL;
solver_o->mstatic = mstatic;
solver_o->solver = NULL;
solver_o->c_sys = NULL;
solver_o->set_called = 0;
solver_o->isset = 0;
for(i = 0; i < PyGSL_SOLVER_NCBS_MAX; ++i){
solver_o->cbs[i] = NULL;
}
for(i = 0; i < PyGSL_SOLVER_PB_ND_MAX; ++i){
solver_o->problem_dimensions[i] = -1;
}
DEBUG_MESS(3, "refcount = %d", solver_o->ob_refcnt);
FUNC_MESS_END();
return solver_o;
fail:
FUNC_MESS("Fail");
PyGSL_add_traceback(module, __FILE__, __FUNCTION__, line);
return NULL;
}
static PyObject *
PyGSL_solver_dn_init(PyObject *self, PyObject *args, const solver_alloc_struct * alloc, int nd)
{
PyGSL_solver *solver_o=NULL;
int n1=1, n2=1;
int line = -1;
int flag=0;
FUNC_MESS_BEGIN();
assert(alloc);
solver_o = _PyGSL_solver_init(alloc->mstatic);
if(solver_o == NULL){
line = __LINE__ - 2;
goto fail;
}
switch(nd){
case 0: flag = 1; break;
case 1: flag = PyArg_ParseTuple(args,"i", &n1); break;
case 2: flag = PyArg_ParseTuple(args,"ii", &n1, &n2); break;
case 3:
/* odeiv */
flag = 1; break;
default:
line = __LINE__;
pygsl_error("Only 1 or two for number of problem_dimensions implemented!",
__FILE__, line, GSL_ESANITY);
goto fail;
}
if (0==flag){
/* Successful parsing of the arguments ?*/
line = __LINE__ - 1;
goto fail;
}
if (n1<=0) {
PyErr_SetString(PyExc_RuntimeError, "dimension 1 must be >0");
line = __LINE__ - 2;
goto fail;
}
if (n2<=0) {
PyErr_SetString(PyExc_RuntimeError, "dimension 2 must be >0");
line = __LINE__ - 2;
goto fail;
}
{
void *tmp = alloc->alloc;
switch(nd){
case 0:
solver_o->solver = ((void_a_t)(tmp))(alloc->type);
break;
case 1:
solver_o->solver = (void *) ((void_an_t) tmp)(alloc->type, n1);
break;
case 2:
DEBUG_MESS(3, "Allocating solver with N=%d, p=%d", n1, n2);
solver_o->solver = (void *) ((void_anp_t) tmp)(alloc->type, n1, n2);
break;
case 3:
/* odeiv handles that itself */
break;
default:
pygsl_error("Only 0,1 or 2 for number of problem_dimensions implemented!",
__FILE__, __LINE__, GSL_ESANITY);
goto fail;
}
}
switch(nd){
case 1:
case 2:
if(solver_o->solver == NULL){
line = __LINE__ - 1;
goto fail;
}
break;
default:
;
}
switch(nd){
case 1:
solver_o->problem_dimensions[0] = n1;
break;
case 2:
solver_o->problem_dimensions[0] = n2;
solver_o->problem_dimensions[1] = n1;
break;
default:
;
}
solver_o->cache = (struct pygsl_array_cache *) calloc(PyGSL_SOLVER_N_ARRAYS, sizeof(struct pygsl_array_cache));
if(solver_o->cache == NULL){
PyErr_NoMemory();
line = __LINE__ - 1;
goto fail;
}
FUNC_MESS_END();
return (PyObject *) solver_o;
fail:
FUNC_MESS("Fail");
DEBUG_MESS(3, "line was %d", line);
PyGSL_add_traceback(module, __FILE__, __FUNCTION__, line);
Py_XDECREF(solver_o);
return NULL;
}
#if 0
static PyObject *
_PyGSL_solver_np_init(PyObject *self, PyObject *args, const solver_alloc_struct * alloc)
{
FUNC_MESS_BEGIN();
return PyGSL_solver_dn_init(self, args, alloc, 2);
FUNC_MESS_END();
}
static PyObject *
PyGSL_solver_n_init(PyObject *self, PyObject *args, const solver_alloc_struct * alloc)
{
FUNC_MESS_BEGIN();
return PyGSL_solver_dn_init(self, args, alloc, 1);
FUNC_MESS_END();
}
static PyObject *
_PyGSL_solver_1_init(PyObject *self, PyObject *args, const solver_alloc_struct * alloc)
{
FUNC_MESS_BEGIN();
return PyGSL_solver_dn_init(self, args, alloc, 0);
FUNC_MESS_END();
}
#endif
static double
PyGSL_gsl_function(double x, void * params)
{
PyGSL_solver *s;
double result = GSL_NAN;
int flag = GSL_EFAILED;
FUNC_MESS_BEGIN();
assert(params);
assert(PyGSL_solver_check((PyObject *) params));
s = (PyGSL_solver *) params;
flag = PyGSL_function_wrap_helper(x, &result, NULL, s->cbs[0], s->args, __FUNCTION__);
if(flag == GSL_SUCCESS){
FUNC_MESS_END();
return result;
}
FUNC_MESS("Fail");
if(s->isset)
longjmp(s->buffer, flag);
DEBUG_MESS(2, "Found an error of %d but could not jump!", flag);
return GSL_NAN;
}
static double
PyGSL_gsl_function_df(double x, void * params)
{
PyGSL_solver *s;
double result = GSL_NAN;
int flag = GSL_EFAILED;
FUNC_MESS_BEGIN();
assert(params);
assert(PyGSL_solver_check((PyObject *) params));
s = (PyGSL_solver *) params;
flag = PyGSL_function_wrap_helper(x, &result, NULL, s->cbs[1], s->args, __FUNCTION__);
if(flag == GSL_SUCCESS){
FUNC_MESS_END();
return result;
}
FUNC_MESS("Fail");
if(s->isset)
longjmp(s->buffer, flag);
DEBUG_MESS(2, "Found an error of %d but could not jump!", flag);
return GSL_NAN;
}
static void
PyGSL_gsl_function_fdf(double x, void * params, double *f, double *df)
{
PyGSL_solver *s;
int flag = GSL_EFAILED;
FUNC_MESS_BEGIN();
assert(params);
assert(PyGSL_solver_check((PyObject *) params));
s = (PyGSL_solver *) params;
assert(s->cbs[2]);
assert(PyCallable_Check(s->cbs[2]));
flag = PyGSL_function_wrap_helper(x, f, df, s->cbs[2], s->args, __FUNCTION__);
if(flag == GSL_SUCCESS){
FUNC_MESS_END();
return;
}
FUNC_MESS("Fail");
if(s->isset)
longjmp(s->buffer, flag);
DEBUG_MESS(2, "Found an error of %d but could not jump!", flag);
*f = GSL_NAN;
*df = GSL_NAN;
}
static PyObject*
PyGSL_solver_set_f(PyGSL_solver *self, PyObject *pyargs, PyObject *kw,
void *fptr, int isfdf)
{
PyObject *f = NULL, *df = NULL, *fdf = NULL, *args = Py_None;
int flag=GSL_EFAILED;
void *c_sys = NULL;
gsl_function * f_sys = NULL;
gsl_function_fdf * fdf_sys = NULL;
double x0, lower=0, upper=0;
static const char *f_kwlist[] = {"f", "x0", "upper", "lower", "args", NULL};
static const char *fdf_kwlist[] = {"f", "df", "fdf", "x0", "args", NULL};
FUNC_MESS_BEGIN();
assert(PyGSL_solver_check(self));
if (self->solver == NULL) {
pygsl_error("Got a NULL Pointer of min.f", filename, __LINE__ - 3, GSL_EFAULT);
return NULL;
}
assert(pyargs);
/* arguments PyFunction, Parameters, start Vector, step Vector */
if(isfdf == 0){
if (0==PyArg_ParseTupleAndKeywords(pyargs,kw,"OdddO", (char **)f_kwlist, &f,
&x0,&lower,&upper,&args))
return NULL;
}else{
if (0==PyArg_ParseTupleAndKeywords(pyargs,kw,"OOOdO", (char **)fdf_kwlist, &f,&df,&fdf,
&x0,&args))
return NULL;
}
if(!PyCallable_Check(f)){
pygsl_error("First argument must be callable", filename, __LINE__ - 3, GSL_EBADFUNC);
return NULL;
}
if(isfdf == 1){
if(!PyCallable_Check(df)){
pygsl_error("Second argument must be callable", filename, __LINE__ - 3, GSL_EBADFUNC);
return NULL;
}
if(!PyCallable_Check(fdf)){
pygsl_error("Third argument must be callable", filename, __LINE__ - 3, GSL_EBADFUNC);
return NULL;
}
}
if (self->c_sys != NULL) {
/* free the previous function and args */
c_sys = self->c_sys;
} else {
/* allocate function space */
if(isfdf == 0)
c_sys=calloc(1, sizeof(gsl_function));
else
c_sys=calloc(1, sizeof(gsl_function_fdf));
if (c_sys == NULL) {
pygsl_error("Could not allocate the object for the minimizer function",
filename, __LINE__ - 3, GSL_ENOMEM);
goto fail;
}
}
DEBUG_MESS(3, "Everything allocated args = %p", args);
/* add new function and parameters */
if(PyGSL_solver_func_set(self, args, f, df, fdf) != GSL_SUCCESS)
goto fail;
/* initialize the function struct */
if(isfdf == 0){
f_sys = c_sys;
f_sys->function=PyGSL_gsl_function;
f_sys->params=(void*)self;
}else{
fdf_sys = c_sys;
fdf_sys->f=PyGSL_gsl_function;
fdf_sys->df=PyGSL_gsl_function_df;
fdf_sys->fdf=PyGSL_gsl_function_fdf;
fdf_sys->params=(void*)self;
}
DEBUG_MESS(3, "Setting jmp buffer isset = % d", self->isset);
if((flag = setjmp(self->buffer)) == 0){
self->isset = 1;
if(isfdf == 0){
DEBUG_MESS(3, "Calling f isfdf = %d", isfdf);
flag = ((set_m_ddd_t) fptr)(self->solver, c_sys, x0, lower, upper);
}else{
DEBUG_MESS(3, "Calling fdf isfdf = %d", isfdf);
flag = ((set_m_d_t) fptr)(self->solver, c_sys, x0);
}
if(PyGSL_ERROR_FLAG(flag) != GSL_SUCCESS){
goto fail;
}
} else {
goto fail;
}
DEBUG_MESS(4, "Set evaluated. flag = %d", flag);
self->c_sys = c_sys;
self->set_called = 1;
self->isset = 0;
Py_INCREF(Py_None);
FUNC_MESS_END();
return Py_None;
fail:
FUNC_MESS("Fail");
PyGSL_ERROR_FLAG(flag);
self->isset = 0;
return NULL;
}
/*
* Set the solver
*/
PyGSL_API_EXTERN PyObject *
PyGSL_solver_n_set(PyGSL_solver *self, PyObject *pyargs, PyObject *kw,
const struct pygsl_solver_n_set * info)
{
int n, flag=GSL_EFAILED;
PyGSL_array_index_t stride;
PyObject *args=Py_None, *f=NULL, *df=NULL, *fdf=NULL, *x;
PyArrayObject * xa = NULL;
gsl_vector_view gsl_x;
void *c_sys;
int line = -1;
static const char *f_kwlist[] = {"f", "x0", "args", NULL};
static const char *fdf_kwlist[] = {"f", "df", "fdf", "x0", "args", NULL};
FUNC_MESS_BEGIN();
assert(PyGSL_solver_check(self));
if (self->solver == NULL) {
pygsl_error("solver == NULL at solver_n_set", filename, __LINE__ - 3, GSL_EFAULT);
return NULL;
}
/* arguments PyFunction, Parameters, start Vector, step Vector */
if(info->is_fdf == 0){
if (0==PyArg_ParseTupleAndKeywords(pyargs, kw, "OO|O", (char **)f_kwlist,
&f, &x, &args))
return NULL;
} else {
if (0==PyArg_ParseTupleAndKeywords(pyargs, kw, "OOOO|O", (char **)fdf_kwlist,
&f, &df, &fdf, &x, &args))
return NULL;
}
n=self->problem_dimensions[0];
DEBUG_MESS(3, "len(x) should be %d", n);
xa = PyGSL_vector_check(x, n, PyGSL_DARRAY_INPUT(2), &stride, NULL);
if (xa == NULL){
line = __LINE__ - 2;
goto fail;
}
gsl_x = gsl_vector_view_array_with_stride((double *)(xa->data), stride,
xa->dimensions[0]);
if (self->c_sys != NULL) {
c_sys = self->c_sys;
} else {
c_sys=info->c_sys;
}
if(PyGSL_solver_func_set(self, args, f, df, fdf) != GSL_SUCCESS){
line = __LINE__ - 1;
goto fail;
}
if((flag = setjmp(self->buffer)) == 0){
self->isset = 1;
flag = info->set(self->solver, c_sys, &gsl_x.vector);
if((PyGSL_ERROR_FLAG(flag)) != GSL_SUCCESS){
line = __LINE__ - 2;
goto fail;
}
}else{
line = __LINE__ - 9;
goto fail;
}
self->c_sys = c_sys;
self->isset = 0;
Py_DECREF(xa);
self->set_called = 1;
Py_INCREF(Py_None);
FUNC_MESS_END();
return Py_None;
fail:
PyGSL_add_traceback(module, __FILE__, __FUNCTION__, line);
self->isset = 0;
self->set_called = 0;
Py_XDECREF(xa);
return NULL;
}
static PyObject*
PyGSL_solver_ret_size_t(PyGSL_solver *self, PyObject *args,
size_t_m_t func)
{
size_t result;
FUNC_MESS_BEGIN();
assert(PyGSL_solver_check(self));
result=func(self->solver);
FUNC_MESS_END();
return (PyObject *) PyLong_FromLong((long)result);
}
static PyObject*
PyGSL_solver_ret_int(PyGSL_solver *self, PyObject *args,
int_m_t func)
{
int result;
FUNC_MESS_BEGIN();
assert(PyGSL_solver_check(self));
result=func(self->solver);
FUNC_MESS_END();
return (PyObject *) PyLong_FromLong((long)result);
}
static PyObject*
PyGSL_solver_ret_double(PyGSL_solver *self, PyObject *args,
double_m_t func)
{
double result;
FUNC_MESS_BEGIN();
assert(PyGSL_solver_check(self));
result=func(self->solver);
FUNC_MESS_END();
return (PyObject *) PyFloat_FromDouble(result);
}
static PyObject*
PyGSL_solver_ret_vec(PyGSL_solver *self, PyObject *args,
ret_vec func)
{
gsl_vector *result;
FUNC_MESS_BEGIN();
assert(PyGSL_solver_check(self));
result=func(self->solver);
if(result == NULL)
PyGSL_ERROR_NULL("Could not retrive vector ...", GSL_ESANITY);
FUNC_MESS_END();
return (PyObject *) PyGSL_copy_gslvector_to_pyarray(result);
}
/*
* evaluates a C function taking an vector and a double as input and returning a status.
*/
static PyObject*
PyGSL_solver_vd_i(PyObject * self, PyObject *args, int_f_vd_t func)
{
PyObject *g=NULL;
PyArrayObject *ga=NULL;
gsl_vector_view gradient;
double epsabs;
int flag = GSL_EFAILED;
PyGSL_array_index_t stride_recalc=-1;
FUNC_MESS_BEGIN();
if (0==PyArg_ParseTuple(args,"Od", &g, &epsabs))
return NULL;
ga = PyGSL_vector_check(g, -1, PyGSL_DARRAY_INPUT(1), &stride_recalc, NULL);
if (ga == NULL){
PyGSL_add_traceback(module, filename, __FUNCTION__, __LINE__ - 1);
return NULL;
}
gradient = gsl_vector_view_array_with_stride((double *)(ga->data), stride_recalc,
ga->dimensions[0]);
flag = func(&gradient.vector, epsabs);
FUNC_MESS_END();
return PyGSL_ERROR_FLAG_TO_PYINT(flag);
}
static PyObject *
PyGSL_solver_vvdd_i(PyObject * self, PyObject * args, int_f_vvdd_t func)
{
int flag;
int line = -1;
double epsabs, epsrel;
PyObject *dx_o, *x_o;
PyArrayObject *dx_a = NULL, *x_a = NULL;
gsl_vector_view x, dx;
PyGSL_array_index_t dimension, stride;
FUNC_MESS_BEGIN();
if(!PyArg_ParseTuple(args, "OOdd", &dx_o, &x_o, &epsabs, &epsrel))
return NULL;
dx_a = PyGSL_vector_check(dx_o, -1, PyGSL_DARRAY_INPUT(1), &stride, NULL);
if(dx_a == NULL){
line = __LINE__ - 4;
goto fail;
}
dx = gsl_vector_view_array_with_stride((double *)(dx_a->data), stride, dx_a->dimensions[0]);
dimension = dx_a->dimensions[0];
x_a = PyGSL_vector_check(x_o, dimension, PyGSL_DARRAY_CINPUT(2), &stride, NULL);
if(x_a == NULL){
line = __LINE__ - 4;
goto fail;
}
x = gsl_vector_view_array_with_stride((double *)(x_a->data), stride, x_a->dimensions[0]);
flag = func(&(dx.vector), &(x.vector), epsabs, epsrel);
Py_DECREF(x_a);
Py_DECREF(dx_a);
FUNC_MESS_END();
return PyGSL_ERROR_FLAG_TO_PYINT(flag);
fail:
PyGSL_add_traceback(module, __FILE__, __FUNCTION__, line);
Py_XDECREF(dx_a);
Py_XDECREF(x_a);
return NULL;
}
PyGSL_API_EXTERN int
PyGSL_Callable_Check(PyObject *f, const char * myname)
{
FUNC_MESS_BEGIN();
if(!PyCallable_Check(f)){
char str[256];
snprintf(str, 254, "Callback named %s is not callable!", myname);
PyGSL_ERROR(str, GSL_EINVAL);
}
FUNC_MESS_END();
return GSL_SUCCESS;
}
PyGSL_API_EXTERN int
PyGSL_solver_func_set(PyGSL_solver *self, PyObject *args, PyObject *f,
PyObject *df, PyObject *fdf)
{
int flag = GSL_EFAILED;
if(df){
if(!fdf)
PyGSL_ERROR("If df is given, fdf must be given as well!", GSL_ESANITY);
Py_XDECREF(self->cbs[1]);
Py_XDECREF(self->cbs[2]);
self->cbs[1] = NULL;
self->cbs[2] = NULL;
}
Py_XDECREF(self->args);
Py_XDECREF(self->cbs[0]);
self->args = NULL;
self->cbs[0] = NULL;
DEBUG_MESS(3, "args = %p", (void *) args);
self->args=args; Py_XINCREF(args);
assert(f);
if((flag = PyGSL_CALLABLE_CHECK(f, "f")) != GSL_SUCCESS)
return flag;
self->cbs[0] = f; Py_INCREF(f);
if(df){
assert(fdf);
if((flag = PyGSL_CALLABLE_CHECK(df, "df")) != GSL_SUCCESS)
return flag;
if((flag = PyGSL_CALLABLE_CHECK(fdf, "fdf")) != GSL_SUCCESS)
return flag;
self->cbs[1]=df; Py_INCREF(df);
self->cbs[2]=fdf; Py_INCREF(fdf);
}
return GSL_SUCCESS;
}
static PyObject *
PyGSL_solver_GetSet(PyObject *self, PyObject *args, void * address, enum PyGSL_GETSET_typemode mode)
{
PyObject *ret=NULL, *input=NULL;
unsigned long ultmp;
int flag;
if (!PyArg_ParseTuple(args, "|O", &input))
return NULL;
if(input){
switch(mode){
case PyGSL_MODE_DOUBLE:
flag = PyGSL_PYFLOAT_TO_DOUBLE(input, (double *) address, NULL);
break;
case PyGSL_MODE_INT:
flag = PyGSL_PYINT_TO_INT(input, (int *) address, NULL);
break;
case PyGSL_MODE_SIZE_T:
flag = PyGSL_PYLONG_TO_ULONG(input, &ultmp, NULL);
*((size_t *) address) = ultmp;
break;
default:
PyGSL_ERROR_NULL("Unknown mode",GSL_ESANITY);
}
if(PyGSL_ERROR_FLAG(flag) != GSL_SUCCESS)
return NULL;
Py_INCREF(Py_None);
ret = Py_None;
return ret;
}
switch(mode){
case PyGSL_MODE_DOUBLE:
ret = PyFloat_FromDouble(*((double *) address));
break;
case PyGSL_MODE_INT:
ret = PyInt_FromLong(((long) *((int *) address)));
break;
case PyGSL_MODE_SIZE_T:
ret = PyLong_FromUnsignedLong(((unsigned long) *((size_t *) address)));
break;
default:
PyGSL_ERROR_NULL("Unknown mode",GSL_ESANITY);
}
return ret;
}
#ifdef ONEFILE
#include "chars.c"
#include "function_helpers2.c"
/*
#include "function_helpers.c"
#include "integrate.c"
#include "odeiv.c"
#include "roots.c"
#include "minimize.c"
#include "multifit_nlin.c"
#include "multimin.c"
#include "multiroot.c"
*/
#endif /* ONEFILE */
static PyMethodDef solverMethods[] = {
{NULL, NULL, 0, NULL}
};
void
init_api(void)
{
FUNC_MESS_BEGIN();
PyGSL_API[PyGSL_solver_type_NUM ] = (void *) &PyGSL_solver_pytype ;
PyGSL_API[PyGSL_solver_ret_int_NUM ] = (void *) &PyGSL_solver_ret_int ;
PyGSL_API[PyGSL_solver_ret_double_NUM ] = (void *) &PyGSL_solver_ret_double ;
PyGSL_API[PyGSL_solver_ret_size_t_NUM ] = (void *) &PyGSL_solver_ret_size_t ;
PyGSL_API[PyGSL_solver_ret_vec_NUM ] = (void *) &PyGSL_solver_ret_vec ;
PyGSL_API[PyGSL_solver_dn_init_NUM ] = (void *) &PyGSL_solver_dn_init ;
PyGSL_API[PyGSL_solver_vd_i_NUM ] = (void *) &PyGSL_solver_vd_i ;
PyGSL_API[PyGSL_solver_vvdd_i_NUM ] = (void *) &PyGSL_solver_vvdd_i ;
PyGSL_API[PyGSL_Callable_Check_NUM ] = (void *) &PyGSL_Callable_Check ;
PyGSL_API[PyGSL_solver_func_set_NUM ] = (void *) &PyGSL_solver_func_set ;
PyGSL_API[PyGSL_function_wrap_OnOn_On_NUM ] = (void *) &PyGSL_function_wrap_OnOn_On;
PyGSL_API[PyGSL_function_wrap_On_O_NUM ] = (void *) &PyGSL_function_wrap_On_O;
PyGSL_API[PyGSL_function_wrap_Op_On_NUM ] = (void *) &PyGSL_function_wrap_Op_On;
PyGSL_API[PyGSL_function_wrap_Op_Opn_NUM ] = (void *) &PyGSL_function_wrap_Op_Opn;
PyGSL_API[PyGSL_function_wrap_Op_On_Opn_NUM] = (void *) &PyGSL_function_wrap_Op_On_Opn;
PyGSL_API[PyGSL_solver_n_set_NUM ] = (void *) &PyGSL_solver_n_set ;
PyGSL_API[PyGSL_solver_set_f_NUM ] = (void *) &PyGSL_solver_set_f ;
PyGSL_API[PyGSL_solver_getset_NUM ] = (void *) &PyGSL_solver_GetSet ;
FUNC_MESS_END();
}
void
initsolver(void)
{
PyObject* m, *dict, *item;
FUNC_MESS_BEGIN();
m=Py_InitModule("solver", solverMethods);
init_pygsl();
/* init multimin type */
PyGSL_solver_pytype.ob_type = &PyType_Type;
init_api();
module = m;
Py_INCREF((PyObject*)&PyGSL_solver_pytype);
dict = PyModule_GetDict(m);
if(!dict)
goto fail;
if (!(item = PyString_FromString((char*)PyGSL_solver_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;
}
FUNC_MESS_END();
fail:
FUNC_MESS("FAIL");
return;
}
| {
"alphanum_fraction": 0.6192860014,
"avg_line_length": 27.7555780933,
"ext": "c",
"hexsha": "d7ba52dcf4909ce8fa2433ad8431d021c2b2a30f",
"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/solvermodule.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/solvermodule.c",
"max_line_length": 116,
"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/solvermodule.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 8172,
"size": 27367
} |
#include "cimple_c_from_py.h"
#include "setoper.h"
#include "cimple_safe_mode.h"
#include <cdd.h>
#include <gsl/gsl_matrix.h>
int main(){
dd_set_global_constants();
// Initialize state:
system_dynamics *s_dyn;
cost_function *f_cost;
discrete_dynamics *d_dyn;
current_state *now;
system_alloc(&now, &s_dyn, &f_cost, &d_dyn);
system_init(now, s_dyn, f_cost, d_dyn);
double sec = 2;
ACT(4, now, d_dyn, s_dyn, f_cost, sec);
system_dynamics_free(s_dyn);
discrete_dynamics_free(d_dyn);
cost_function_free(f_cost);
state_free(now);
dd_free_global_constants();
return 0;
}
| {
"alphanum_fraction": 0.6813186813,
"avg_line_length": 19.90625,
"ext": "c",
"hexsha": "a36ee23d21f24624ad69b645c097855057c4836c",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2018-10-06T12:58:52.000Z",
"max_forks_repo_forks_event_min_datetime": "2018-10-06T12:58:52.000Z",
"max_forks_repo_head_hexsha": "56cf4d58a9d7e17b6f6aebe6de8d5a1231035671",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "shaesaert/TuLiPXML",
"max_forks_repo_path": "Interface/Cimple/main.c",
"max_issues_count": 2,
"max_issues_repo_head_hexsha": "56cf4d58a9d7e17b6f6aebe6de8d5a1231035671",
"max_issues_repo_issues_event_max_datetime": "2018-08-21T09:50:09.000Z",
"max_issues_repo_issues_event_min_datetime": "2017-10-03T18:54:08.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "shaesaert/TuLiPXML",
"max_issues_repo_path": "Interface/Cimple/main.c",
"max_line_length": 48,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "56cf4d58a9d7e17b6f6aebe6de8d5a1231035671",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "shaesaert/TuLiPXML",
"max_stars_repo_path": "Interface/Cimple/main.c",
"max_stars_repo_stars_event_max_datetime": "2021-05-28T23:44:28.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-05-28T23:44:28.000Z",
"num_tokens": 178,
"size": 637
} |
/* ******************************************************************************
*
*
* This program and the accompanying materials are made available under the
* terms of the Apache License, Version 2.0 which is available at
* https://www.apache.org/licenses/LICENSE-2.0.
*
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
* 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.
*
* SPDX-License-Identifier: Apache-2.0
******************************************************************************/
//
// Created by agibsonccc on 1/26/16.
//
#ifndef NATIVEOPERATIONS_CBLAS_H
#define NATIVEOPERATIONS_CBLAS_H
#ifndef __STANDALONE_BUILD__
#include "config.h"
#endif
#ifdef __MKL_CBLAS_H__
// CBLAS from MKL is already included
#define CBLAS_H
#endif
#ifdef HAVE_OPENBLAS
// include CBLAS from OpenBLAS
#ifdef __GNUC__
#include_next <cblas.h>
#else
#include <cblas.h>
#endif
#define CBLAS_H
#endif
#ifndef CBLAS_H
#ifdef __cplusplus
extern "C" {
#endif
#ifndef CBLAS_ENUM_DEFINED_H
#define CBLAS_ENUM_DEFINED_H
enum CBLAS_ORDER { CblasRowMajor = 101, CblasColMajor = 102 };
enum CBLAS_TRANSPOSE { CblasNoTrans = 111, CblasTrans = 112, CblasConjTrans = 113, AtlasConj = 114 };
enum CBLAS_UPLO { CblasUpper = 121, CblasLower = 122 };
enum CBLAS_DIAG { CblasNonUnit = 131, CblasUnit = 132 };
enum CBLAS_SIDE { CblasLeft = 141, CblasRight = 142 };
#endif
#ifndef CBLAS_ENUM_ONLY
#define CBLAS_H
#define CBLAS_INDEX int
int cblas_errprn(int ierr, int info, char *form, ...);
void cblas_xerbla(int p, char *rout, char *form, ...);
#ifdef __MKL
void MKL_Set_Num_Threads(int num);
int MKL_Domain_Set_Num_Threads(int num, int domain);
int MKL_Set_Num_Threads_Local(int num);
#elif __OPENBLAS
void openblas_set_num_threads(int num);
#else
// do nothing
#endif
/*
* ===========================================================================
* Prototypes for level 1 BLAS functions (complex are recast as routines)
* ===========================================================================
*/
float cblas_sdsdot(int N, float alpha, float *X, int incX, float *Y, int incY);
double cblas_dsdot(int N, float *X, int incX, float *Y, int incY);
float cblas_sdot(int N, float *X, int incX, float *Y, int incY);
double cblas_ddot(int N, double *X, int incX, double *Y, int incY);
/*
* Functions having prefixes Z and C only
*/
void cblas_cdotu_sub(int N, void *X, int incX, void *Y, int incY, void *dotu);
void cblas_cdotc_sub(int N, void *X, int incX, void *Y, int incY, void *dotc);
void cblas_zdotu_sub(int N, void *X, int incX, void *Y, int incY, void *dotu);
void cblas_zdotc_sub(int N, void *X, int incX, void *Y, int incY, void *dotc);
/*
* Functions having prefixes S D SC DZ
*/
float cblas_snrm2(int N, float *X, int incX);
float cblas_sasum(int N, float *X, int incX);
double cblas_dnrm2(int N, double *X, int incX);
double cblas_dasum(int N, double *X, int incX);
float cblas_scnrm2(int N, void *X, int incX);
float cblas_scasum(int N, void *X, int incX);
double cblas_dznrm2(int N, void *X, int incX);
double cblas_dzasum(int N, void *X, int incX);
/*
* Functions having standard 4 prefixes (S D C Z)
*/
CBLAS_INDEX cblas_isamax(int N, float *X, int incX);
CBLAS_INDEX cblas_idamax(int N, double *X, int incX);
CBLAS_INDEX cblas_icamax(int N, void *X, int incX);
CBLAS_INDEX cblas_izamax(int N, void *X, int incX);
/*
* ===========================================================================
* Prototypes for level 1 BLAS routines
* ===========================================================================
*/
/*
* Routines with standard 4 prefixes (s, d, c, z)
*/
void cblas_sswap(int N, float *X, int incX, float *Y, int incY);
void cblas_scopy(int N, float *X, int incX, float *Y, int incY);
void cblas_saxpy(int N, float alpha, float *X, int incX, float *Y, int incY);
void catlas_saxpby(int N, float alpha, float *X, int incX, float beta, float *Y, int incY);
void catlas_sset(int N, float alpha, float *X, int incX);
void cblas_dswap(int N, double *X, int incX, double *Y, int incY);
void cblas_dcopy(int N, double *X, int incX, double *Y, int incY);
void cblas_daxpy(int N, double alpha, double *X, int incX, double *Y, int incY);
void catlas_daxpby(int N, double alpha, double *X, int incX, double beta, double *Y, int incY);
void catlas_dset(int N, double alpha, double *X, int incX);
void cblas_cswap(int N, void *X, int incX, void *Y, int incY);
void cblas_ccopy(int N, void *X, int incX, void *Y, int incY);
void cblas_caxpy(int N, void *alpha, void *X, int incX, void *Y, int incY);
void catlas_caxpby(int N, void *alpha, void *X, int incX, void *beta, void *Y, int incY);
void catlas_cset(int N, void *alpha, void *X, int incX);
void cblas_zswap(int N, void *X, int incX, void *Y, int incY);
void cblas_zcopy(int N, void *X, int incX, void *Y, int incY);
void cblas_zaxpy(int N, void *alpha, void *X, int incX, void *Y, int incY);
void catlas_zaxpby(int N, void *alpha, void *X, int incX, void *beta, void *Y, int incY);
void catlas_zset(int N, void *alpha, void *X, int incX);
/*
* Routines with S and D prefix only
*/
void cblas_srotg(float *a, float *b, float *c, float *s);
void cblas_srotmg(float *d1, float *d2, float *b1, float b2, float *P);
void cblas_srot(int N, float *X, int incX, float *Y, int incY, float c, float s);
void cblas_srotm(int N, float *X, int incX, float *Y, int incY, float *P);
void cblas_drotg(double *a, double *b, double *c, double *s);
void cblas_drotmg(double *d1, double *d2, double *b1, double b2, double *P);
void cblas_drot(int N, double *X, int incX, double *Y, int incY, double c, double s);
void cblas_drotm(int N, double *X, int incX, double *Y, int incY, double *P);
/*
* Routines with S D C Z CS and ZD prefixes
*/
void cblas_sscal(int N, float alpha, float *X, int incX);
void cblas_dscal(int N, double alpha, double *X, int incX);
void cblas_cscal(int N, void *alpha, void *X, int incX);
void cblas_zscal(int N, void *alpha, void *X, int incX);
void cblas_csscal(int N, float alpha, void *X, int incX);
void cblas_zdscal(int N, double alpha, void *X, int incX);
/*
* Extra reference routines provided by ATLAS, but not mandated by the standard
*/
void cblas_crotg(void *a, void *b, void *c, void *s);
void cblas_zrotg(void *a, void *b, void *c, void *s);
void cblas_csrot(int N, void *X, int incX, void *Y, int incY, float c, float s);
void cblas_zdrot(int N, void *X, int incX, void *Y, int incY, double c, double s);
/*
* ===========================================================================
* Prototypes for level 2 BLAS
* ===========================================================================
*/
/*
* Routines with standard 4 prefixes (S, D, C, Z)
*/
void cblas_sgemv(enum CBLAS_ORDER Order, enum CBLAS_TRANSPOSE TransA, int M, int N, float alpha, float *A, int lda,
float *X, int incX, float beta, float *Y, int incY);
void cblas_sgbmv(enum CBLAS_ORDER Order, enum CBLAS_TRANSPOSE TransA, int M, int N, int KL, int KU, float alpha,
float *A, int lda, float *X, int incX, float beta, float *Y, int incY);
void cblas_strmv(enum CBLAS_ORDER Order, enum CBLAS_UPLO Uplo, enum CBLAS_TRANSPOSE TransA, enum CBLAS_DIAG Diag, int N,
float *A, int lda, float *X, int incX);
void cblas_stbmv(enum CBLAS_ORDER Order, enum CBLAS_UPLO Uplo, enum CBLAS_TRANSPOSE TransA, enum CBLAS_DIAG Diag, int N,
int K, float *A, int lda, float *X, int incX);
void cblas_stpmv(enum CBLAS_ORDER Order, enum CBLAS_UPLO Uplo, enum CBLAS_TRANSPOSE TransA, enum CBLAS_DIAG Diag, int N,
float *Ap, float *X, int incX);
void cblas_strsv(enum CBLAS_ORDER Order, enum CBLAS_UPLO Uplo, enum CBLAS_TRANSPOSE TransA, enum CBLAS_DIAG Diag, int N,
float *A, int lda, float *X, int incX);
void cblas_stbsv(enum CBLAS_ORDER Order, enum CBLAS_UPLO Uplo, enum CBLAS_TRANSPOSE TransA, enum CBLAS_DIAG Diag, int N,
int K, float *A, int lda, float *X, int incX);
void cblas_stpsv(enum CBLAS_ORDER Order, enum CBLAS_UPLO Uplo, enum CBLAS_TRANSPOSE TransA, enum CBLAS_DIAG Diag, int N,
float *Ap, float *X, int incX);
void cblas_dgemv(enum CBLAS_ORDER Order, enum CBLAS_TRANSPOSE TransA, int M, int N, double alpha, double *A, int lda,
double *X, int incX, double beta, double *Y, int incY);
void cblas_dgbmv(enum CBLAS_ORDER Order, enum CBLAS_TRANSPOSE TransA, int M, int N, int KL, int KU, double alpha,
double *A, int lda, double *X, int incX, double beta, double *Y, int incY);
void cblas_dtrmv(enum CBLAS_ORDER Order, enum CBLAS_UPLO Uplo, enum CBLAS_TRANSPOSE TransA, enum CBLAS_DIAG Diag, int N,
double *A, int lda, double *X, int incX);
void cblas_dtbmv(enum CBLAS_ORDER Order, enum CBLAS_UPLO Uplo, enum CBLAS_TRANSPOSE TransA, enum CBLAS_DIAG Diag, int N,
int K, double *A, int lda, double *X, int incX);
void cblas_dtpmv(enum CBLAS_ORDER Order, enum CBLAS_UPLO Uplo, enum CBLAS_TRANSPOSE TransA, enum CBLAS_DIAG Diag, int N,
double *Ap, double *X, int incX);
void cblas_dtrsv(enum CBLAS_ORDER Order, enum CBLAS_UPLO Uplo, enum CBLAS_TRANSPOSE TransA, enum CBLAS_DIAG Diag, int N,
double *A, int lda, double *X, int incX);
void cblas_dtbsv(enum CBLAS_ORDER Order, enum CBLAS_UPLO Uplo, enum CBLAS_TRANSPOSE TransA, enum CBLAS_DIAG Diag, int N,
int K, double *A, int lda, double *X, int incX);
void cblas_dtpsv(enum CBLAS_ORDER Order, enum CBLAS_UPLO Uplo, enum CBLAS_TRANSPOSE TransA, enum CBLAS_DIAG Diag, int N,
double *Ap, double *X, int incX);
void cblas_cgemv(enum CBLAS_ORDER Order, enum CBLAS_TRANSPOSE TransA, int M, int N, void *alpha, void *A, int lda,
void *X, int incX, void *beta, void *Y, int incY);
void cblas_cgbmv(enum CBLAS_ORDER Order, enum CBLAS_TRANSPOSE TransA, int M, int N, int KL, int KU, void *alpha,
void *A, int lda, void *X, int incX, void *beta, void *Y, int incY);
void cblas_ctrmv(enum CBLAS_ORDER Order, enum CBLAS_UPLO Uplo, enum CBLAS_TRANSPOSE TransA, enum CBLAS_DIAG Diag, int N,
void *A, int lda, void *X, int incX);
void cblas_ctbmv(enum CBLAS_ORDER Order, enum CBLAS_UPLO Uplo, enum CBLAS_TRANSPOSE TransA, enum CBLAS_DIAG Diag, int N,
int K, void *A, int lda, void *X, int incX);
void cblas_ctpmv(enum CBLAS_ORDER Order, enum CBLAS_UPLO Uplo, enum CBLAS_TRANSPOSE TransA, enum CBLAS_DIAG Diag, int N,
void *Ap, void *X, int incX);
void cblas_ctrsv(enum CBLAS_ORDER Order, enum CBLAS_UPLO Uplo, enum CBLAS_TRANSPOSE TransA, enum CBLAS_DIAG Diag, int N,
void *A, int lda, void *X, int incX);
void cblas_ctbsv(enum CBLAS_ORDER Order, enum CBLAS_UPLO Uplo, enum CBLAS_TRANSPOSE TransA, enum CBLAS_DIAG Diag, int N,
int K, void *A, int lda, void *X, int incX);
void cblas_ctpsv(enum CBLAS_ORDER Order, enum CBLAS_UPLO Uplo, enum CBLAS_TRANSPOSE TransA, enum CBLAS_DIAG Diag, int N,
void *Ap, void *X, int incX);
void cblas_zgemv(enum CBLAS_ORDER Order, enum CBLAS_TRANSPOSE TransA, int M, int N, void *alpha, void *A, int lda,
void *X, int incX, void *beta, void *Y, int incY);
void cblas_zgbmv(enum CBLAS_ORDER Order, enum CBLAS_TRANSPOSE TransA, int M, int N, int KL, int KU, void *alpha,
void *A, int lda, void *X, int incX, void *beta, void *Y, int incY);
void cblas_ztrmv(enum CBLAS_ORDER Order, enum CBLAS_UPLO Uplo, enum CBLAS_TRANSPOSE TransA, enum CBLAS_DIAG Diag, int N,
void *A, int lda, void *X, int incX);
void cblas_ztbmv(enum CBLAS_ORDER Order, enum CBLAS_UPLO Uplo, enum CBLAS_TRANSPOSE TransA, enum CBLAS_DIAG Diag, int N,
int K, void *A, int lda, void *X, int incX);
void cblas_ztpmv(enum CBLAS_ORDER Order, enum CBLAS_UPLO Uplo, enum CBLAS_TRANSPOSE TransA, enum CBLAS_DIAG Diag, int N,
void *Ap, void *X, int incX);
void cblas_ztrsv(enum CBLAS_ORDER Order, enum CBLAS_UPLO Uplo, enum CBLAS_TRANSPOSE TransA, enum CBLAS_DIAG Diag, int N,
void *A, int lda, void *X, int incX);
void cblas_ztbsv(enum CBLAS_ORDER Order, enum CBLAS_UPLO Uplo, enum CBLAS_TRANSPOSE TransA, enum CBLAS_DIAG Diag, int N,
int K, void *A, int lda, void *X, int incX);
void cblas_ztpsv(enum CBLAS_ORDER Order, enum CBLAS_UPLO Uplo, enum CBLAS_TRANSPOSE TransA, enum CBLAS_DIAG Diag, int N,
void *Ap, void *X, int incX);
/*
* Routines with S and D prefixes only
*/
void cblas_ssymv(enum CBLAS_ORDER Order, enum CBLAS_UPLO Uplo, int N, float alpha, float *A, int lda, float *X,
int incX, float beta, float *Y, int incY);
void cblas_ssbmv(enum CBLAS_ORDER Order, enum CBLAS_UPLO Uplo, int N, int K, float alpha, float *A, int lda, float *X,
int incX, float beta, float *Y, int incY);
void cblas_sspmv(enum CBLAS_ORDER Order, enum CBLAS_UPLO Uplo, int N, float alpha, float *Ap, float *X, int incX,
float beta, float *Y, int incY);
void cblas_sger(enum CBLAS_ORDER Order, int M, int N, float alpha, float *X, int incX, float *Y, int incY, float *A,
int lda);
void cblas_ssyr(enum CBLAS_ORDER Order, enum CBLAS_UPLO Uplo, int N, float alpha, float *X, int incX, float *A,
int lda);
void cblas_sspr(enum CBLAS_ORDER Order, enum CBLAS_UPLO Uplo, int N, float alpha, float *X, int incX, float *Ap);
void cblas_ssyr2(enum CBLAS_ORDER Order, enum CBLAS_UPLO Uplo, int N, float alpha, float *X, int incX, float *Y,
int incY, float *A, int lda);
void cblas_sspr2(enum CBLAS_ORDER Order, enum CBLAS_UPLO Uplo, int N, float alpha, float *X, int incX, float *Y,
int incY, float *A);
void cblas_dsymv(enum CBLAS_ORDER Order, enum CBLAS_UPLO Uplo, int N, double alpha, double *A, int lda, double *X,
int incX, double beta, double *Y, int incY);
void cblas_dsbmv(enum CBLAS_ORDER Order, enum CBLAS_UPLO Uplo, int N, int K, double alpha, double *A, int lda,
double *X, int incX, double beta, double *Y, int incY);
void cblas_dspmv(enum CBLAS_ORDER Order, enum CBLAS_UPLO Uplo, int N, double alpha, double *Ap, double *X, int incX,
double beta, double *Y, int incY);
void cblas_dger(enum CBLAS_ORDER Order, int M, int N, double alpha, double *X, int incX, double *Y, int incY, double *A,
int lda);
void cblas_dsyr(enum CBLAS_ORDER Order, enum CBLAS_UPLO Uplo, int N, double alpha, double *X, int incX, double *A,
int lda);
void cblas_dspr(enum CBLAS_ORDER Order, enum CBLAS_UPLO Uplo, int N, double alpha, double *X, int incX, double *Ap);
void cblas_dsyr2(enum CBLAS_ORDER Order, enum CBLAS_UPLO Uplo, int N, double alpha, double *X, int incX, double *Y,
int incY, double *A, int lda);
void cblas_dspr2(enum CBLAS_ORDER Order, enum CBLAS_UPLO Uplo, int N, double alpha, double *X, int incX, double *Y,
int incY, double *A);
/*
* Routines with C and Z prefixes only
*/
void cblas_chemv(enum CBLAS_ORDER Order, enum CBLAS_UPLO Uplo, int N, void *alpha, void *A, int lda, void *X, int incX,
void *beta, void *Y, int incY);
void cblas_chbmv(enum CBLAS_ORDER Order, enum CBLAS_UPLO Uplo, int N, int K, void *alpha, void *A, int lda, void *X,
int incX, void *beta, void *Y, int incY);
void cblas_chpmv(enum CBLAS_ORDER Order, enum CBLAS_UPLO Uplo, int N, void *alpha, void *Ap, void *X, int incX,
void *beta, void *Y, int incY);
void cblas_cgeru(enum CBLAS_ORDER Order, int M, int N, void *alpha, void *X, int incX, void *Y, int incY, void *A,
int lda);
void cblas_cgerc(enum CBLAS_ORDER Order, int M, int N, void *alpha, void *X, int incX, void *Y, int incY, void *A,
int lda);
void cblas_cher(enum CBLAS_ORDER Order, enum CBLAS_UPLO Uplo, int N, float alpha, void *X, int incX, void *A, int lda);
void cblas_chpr(enum CBLAS_ORDER Order, enum CBLAS_UPLO Uplo, int N, float alpha, void *X, int incX, void *A);
void cblas_cher2(enum CBLAS_ORDER Order, enum CBLAS_UPLO Uplo, int N, void *alpha, void *X, int incX, void *Y, int incY,
void *A, int lda);
void cblas_chpr2(enum CBLAS_ORDER Order, enum CBLAS_UPLO Uplo, int N, void *alpha, void *X, int incX, void *Y, int incY,
void *Ap);
void cblas_zhemv(enum CBLAS_ORDER Order, enum CBLAS_UPLO Uplo, int N, void *alpha, void *A, int lda, void *X, int incX,
void *beta, void *Y, int incY);
void cblas_zhbmv(enum CBLAS_ORDER Order, enum CBLAS_UPLO Uplo, int N, int K, void *alpha, void *A, int lda, void *X,
int incX, void *beta, void *Y, int incY);
void cblas_zhpmv(enum CBLAS_ORDER Order, enum CBLAS_UPLO Uplo, int N, void *alpha, void *Ap, void *X, int incX,
void *beta, void *Y, int incY);
void cblas_zgeru(enum CBLAS_ORDER Order, int M, int N, void *alpha, void *X, int incX, void *Y, int incY, void *A,
int lda);
void cblas_zgerc(enum CBLAS_ORDER Order, int M, int N, void *alpha, void *X, int incX, void *Y, int incY, void *A,
int lda);
void cblas_zher(enum CBLAS_ORDER Order, enum CBLAS_UPLO Uplo, int N, double alpha, void *X, int incX, void *A, int lda);
void cblas_zhpr(enum CBLAS_ORDER Order, enum CBLAS_UPLO Uplo, int N, double alpha, void *X, int incX, void *A);
void cblas_zher2(enum CBLAS_ORDER Order, enum CBLAS_UPLO Uplo, int N, void *alpha, void *X, int incX, void *Y, int incY,
void *A, int lda);
void cblas_zhpr2(enum CBLAS_ORDER Order, enum CBLAS_UPLO Uplo, int N, void *alpha, void *X, int incX, void *Y, int incY,
void *Ap);
/*
* ===========================================================================
* Prototypes for level 3 BLAS
* ===========================================================================
*/
/*
* Routines with standard 4 prefixes (S, D, C, Z)
*/
void cblas_sgemm(enum CBLAS_ORDER Order, enum CBLAS_TRANSPOSE TransA, enum CBLAS_TRANSPOSE TransB, int M, int N, int K,
float alpha, float *A, int lda, float *B, int ldb, float beta, float *C, int ldc);
void cblas_ssymm(enum CBLAS_ORDER Order, enum CBLAS_SIDE Side, enum CBLAS_UPLO Uplo, int M, int N, float alpha,
float *A, int lda, float *B, int ldb, float beta, float *C, int ldc);
void cblas_ssyrk(enum CBLAS_ORDER Order, enum CBLAS_UPLO Uplo, enum CBLAS_TRANSPOSE Trans, int N, int K, float alpha,
float *A, int lda, float beta, float *C, int ldc);
void cblas_ssyr2k(enum CBLAS_ORDER Order, enum CBLAS_UPLO Uplo, enum CBLAS_TRANSPOSE Trans, int N, int K, float alpha,
float *A, int lda, float *B, int ldb, float beta, float *C, int ldc);
void cblas_strmm(enum CBLAS_ORDER Order, enum CBLAS_SIDE Side, enum CBLAS_UPLO Uplo, enum CBLAS_TRANSPOSE TransA,
enum CBLAS_DIAG Diag, int M, int N, float alpha, float *A, int lda, float *B, int ldb);
void cblas_strsm(enum CBLAS_ORDER Order, enum CBLAS_SIDE Side, enum CBLAS_UPLO Uplo, enum CBLAS_TRANSPOSE TransA,
enum CBLAS_DIAG Diag, int M, int N, float alpha, float *A, int lda, float *B, int ldb);
void cblas_dgemm(enum CBLAS_ORDER Order, enum CBLAS_TRANSPOSE TransA, enum CBLAS_TRANSPOSE TransB, int M, int N, int K,
double alpha, double *A, int lda, double *B, int ldb, double beta, double *C, int ldc);
void cblas_dsymm(enum CBLAS_ORDER Order, enum CBLAS_SIDE Side, enum CBLAS_UPLO Uplo, int M, int N, double alpha,
double *A, int lda, double *B, int ldb, double beta, double *C, int ldc);
void cblas_dsyrk(enum CBLAS_ORDER Order, enum CBLAS_UPLO Uplo, enum CBLAS_TRANSPOSE Trans, int N, int K, double alpha,
double *A, int lda, double beta, double *C, int ldc);
void cblas_dsyr2k(enum CBLAS_ORDER Order, enum CBLAS_UPLO Uplo, enum CBLAS_TRANSPOSE Trans, int N, int K, double alpha,
double *A, int lda, double *B, int ldb, double beta, double *C, int ldc);
void cblas_dtrmm(enum CBLAS_ORDER Order, enum CBLAS_SIDE Side, enum CBLAS_UPLO Uplo, enum CBLAS_TRANSPOSE TransA,
enum CBLAS_DIAG Diag, int M, int N, double alpha, double *A, int lda, double *B, int ldb);
void cblas_dtrsm(enum CBLAS_ORDER Order, enum CBLAS_SIDE Side, enum CBLAS_UPLO Uplo, enum CBLAS_TRANSPOSE TransA,
enum CBLAS_DIAG Diag, int M, int N, double alpha, double *A, int lda, double *B, int ldb);
void cblas_cgemm(enum CBLAS_ORDER Order, enum CBLAS_TRANSPOSE TransA, enum CBLAS_TRANSPOSE TransB, int M, int N, int K,
void *alpha, void *A, int lda, void *B, int ldb, void *beta, void *C, int ldc);
void cblas_csymm(enum CBLAS_ORDER Order, enum CBLAS_SIDE Side, enum CBLAS_UPLO Uplo, int M, int N, void *alpha, void *A,
int lda, void *B, int ldb, void *beta, void *C, int ldc);
void cblas_csyrk(enum CBLAS_ORDER Order, enum CBLAS_UPLO Uplo, enum CBLAS_TRANSPOSE Trans, int N, int K, void *alpha,
void *A, int lda, void *beta, void *C, int ldc);
void cblas_csyr2k(enum CBLAS_ORDER Order, enum CBLAS_UPLO Uplo, enum CBLAS_TRANSPOSE Trans, int N, int K, void *alpha,
void *A, int lda, void *B, int ldb, void *beta, void *C, int ldc);
void cblas_ctrmm(enum CBLAS_ORDER Order, enum CBLAS_SIDE Side, enum CBLAS_UPLO Uplo, enum CBLAS_TRANSPOSE TransA,
enum CBLAS_DIAG Diag, int M, int N, void *alpha, void *A, int lda, void *B, int ldb);
void cblas_ctrsm(enum CBLAS_ORDER Order, enum CBLAS_SIDE Side, enum CBLAS_UPLO Uplo, enum CBLAS_TRANSPOSE TransA,
enum CBLAS_DIAG Diag, int M, int N, void *alpha, void *A, int lda, void *B, int ldb);
void cblas_zgemm(enum CBLAS_ORDER Order, enum CBLAS_TRANSPOSE TransA, enum CBLAS_TRANSPOSE TransB, int M, int N, int K,
void *alpha, void *A, int lda, void *B, int ldb, void *beta, void *C, int ldc);
void cblas_zsymm(enum CBLAS_ORDER Order, enum CBLAS_SIDE Side, enum CBLAS_UPLO Uplo, int M, int N, void *alpha, void *A,
int lda, void *B, int ldb, void *beta, void *C, int ldc);
void cblas_zsyrk(enum CBLAS_ORDER Order, enum CBLAS_UPLO Uplo, enum CBLAS_TRANSPOSE Trans, int N, int K, void *alpha,
void *A, int lda, void *beta, void *C, int ldc);
void cblas_zsyr2k(enum CBLAS_ORDER Order, enum CBLAS_UPLO Uplo, enum CBLAS_TRANSPOSE Trans, int N, int K, void *alpha,
void *A, int lda, void *B, int ldb, void *beta, void *C, int ldc);
void cblas_ztrmm(enum CBLAS_ORDER Order, enum CBLAS_SIDE Side, enum CBLAS_UPLO Uplo, enum CBLAS_TRANSPOSE TransA,
enum CBLAS_DIAG Diag, int M, int N, void *alpha, void *A, int lda, void *B, int ldb);
void cblas_ztrsm(enum CBLAS_ORDER Order, enum CBLAS_SIDE Side, enum CBLAS_UPLO Uplo, enum CBLAS_TRANSPOSE TransA,
enum CBLAS_DIAG Diag, int M, int N, void *alpha, void *A, int lda, void *B, int ldb);
/*
* Routines with prefixes C and Z only
*/
void cblas_chemm(enum CBLAS_ORDER Order, enum CBLAS_SIDE Side, enum CBLAS_UPLO Uplo, int M, int N, void *alpha, void *A,
int lda, void *B, int ldb, void *beta, void *C, int ldc);
void cblas_cherk(enum CBLAS_ORDER Order, enum CBLAS_UPLO Uplo, enum CBLAS_TRANSPOSE Trans, int N, int K, float alpha,
void *A, int lda, float beta, void *C, int ldc);
void cblas_cher2k(enum CBLAS_ORDER Order, enum CBLAS_UPLO Uplo, enum CBLAS_TRANSPOSE Trans, int N, int K, void *alpha,
void *A, int lda, void *B, int ldb, float beta, void *C, int ldc);
void cblas_zhemm(enum CBLAS_ORDER Order, enum CBLAS_SIDE Side, enum CBLAS_UPLO Uplo, int M, int N, void *alpha, void *A,
int lda, void *B, int ldb, void *beta, void *C, int ldc);
void cblas_zherk(enum CBLAS_ORDER Order, enum CBLAS_UPLO Uplo, enum CBLAS_TRANSPOSE Trans, int N, int K, double alpha,
void *A, int lda, double beta, void *C, int ldc);
void cblas_zher2k(enum CBLAS_ORDER Order, enum CBLAS_UPLO Uplo, enum CBLAS_TRANSPOSE Trans, int N, int K, void *alpha,
void *A, int lda, void *B, int ldb, double beta, void *C, int ldc);
int cblas_errprn(int ierr, int info, char *form, ...);
#ifdef __cplusplus
}
#endif
#endif /* end #ifdef CBLAS_ENUM_ONLY */
#endif
#endif // NATIVEOPERATIONS_CBLAS_H
| {
"alphanum_fraction": 0.6667206674,
"avg_line_length": 59.6400966184,
"ext": "h",
"hexsha": "a98027c5fc5a25ed00e3f750fa685ef5bf79c778",
"lang": "C",
"max_forks_count": 572,
"max_forks_repo_forks_event_max_datetime": "2022-03-31T16:46:46.000Z",
"max_forks_repo_forks_event_min_datetime": "2019-06-12T22:13:57.000Z",
"max_forks_repo_head_hexsha": "4653c97a713cc59e41d4313ddbafc5ff527f8714",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "steljord2/deeplearning4j",
"max_forks_repo_path": "libnd4j/include/cblas.h",
"max_issues_count": 1685,
"max_issues_repo_head_hexsha": "4653c97a713cc59e41d4313ddbafc5ff527f8714",
"max_issues_repo_issues_event_max_datetime": "2022-03-29T21:45:15.000Z",
"max_issues_repo_issues_event_min_datetime": "2019-06-12T17:41:33.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "steljord2/deeplearning4j",
"max_issues_repo_path": "libnd4j/include/cblas.h",
"max_line_length": 120,
"max_stars_count": 2206,
"max_stars_repo_head_hexsha": "4653c97a713cc59e41d4313ddbafc5ff527f8714",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "steljord2/deeplearning4j",
"max_stars_repo_path": "libnd4j/include/cblas.h",
"max_stars_repo_stars_event_max_datetime": "2022-03-29T08:14:27.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-06-12T18:57:14.000Z",
"num_tokens": 7796,
"size": 24691
} |
/*
* HelloWorld.cpp
*
* Created on: 22 August 2016
* Author: Dr. Corneliu Arsene
*
* This software implements the Canonical Variates Analysis method (libhelloworld.jnilib file) for image
* processing: it reads the multispectral images from the same directory as where the libhelloworld.jnilib
* file is located and then produces a number of improved colour images in comparison to the original
* multispectral images.
*
*
*
*
*
*/
#include "jni.h"
#include <stdio.h>
#include "HelloWorld.h"
#include <math.h>
#include <assert.h>
#include <dirent.h>
#include </usr/local/Cellar/libiomp/20150701/include/libiomp/omp.h>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui.hpp>
#include <opencv/cv.h>
#include <opencv/highgui.h>
#include <time.h>
#include <string.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <iostream>
#include "gsl/matrix/gsl_matrix.h"
#include "gsl/specfunc/gsl_sf_bessel.h"
#include "gsl_math.h"
#include "gsl/gsl_blas.h"
#include <gsl/gsl_vector.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_eigen.h>
#include <gsl/gsl_sort_vector.h>
#include <gsl/eigen/gsl_eigen.h>
using namespace cv;
using namespace std;
// * THIS FILE IS COMPILED TO A LIBRARY WHICH IS CALLED BY A JAVA LIBRARY
JNIEXPORT void JNICALL
Java_HelloWorld_print(JNIEnv *env, jobject thisObj){
int i,j,k;
int grp1[9];//,grouping_vector[200] ;
char *dir;
int depth;
dir ="/home";
depth=0;
DIR * dp1,*dp3;
struct dirent* ep,*ep3;
char* text;
char pattern[6];
char* text2;
pattern[0]='\0';
pattern[1]='\0';
pattern[2]='\0';
pattern[3]='\0';
pattern[4]='\0';
pattern[5]='\0';
clock_t start, end;
double cpu_time_used;
start = clock();
// * DETECT HOW MANY CLASS TEXT FILES EXIST (E.G. CLASS MANUSCRIPT, CLASS UNDERWRITING, ETC)
text="Class";
dp1 = opendir ("./");
int acindex,newacindex;
acindex = 0;
newacindex =0;
while (ep = readdir (dp1))
{
text2 = ep->d_name;
pattern[0] = text2[0];//ep->d_name[0];
pattern[1] = text2[1];//ep->d_name[1];
pattern[2] = text2[2];//ep->d_name[2];
pattern[3] = text2[3];//ep->d_name[3];
pattern[4] = text2[4];//ep->d_name[4];
pattern[5] ='\0';
if( strcmp(text, pattern) == 0 )
{
acindex = acindex +1;
}
}
(void) closedir (dp1);
// * ONCE I KNOW HOW MANY CLASSES THERE ARE THEN I MEMORIZE THE PATH TO THE RESPECTIVE CLASS FILES
char arrayclass[acindex][2024];
dp3 = opendir ("./");
while (ep3 = readdir (dp3))
{
text2 = ep3->d_name;
pattern[0] = text2[0];//ep->d_name[0];
pattern[1] = text2[1];//ep->d_name[1];
pattern[2] = text2[2];//ep->d_name[2];
pattern[3] = text2[3];//ep->d_name[3];
pattern[4] = text2[4];//ep->d_name[4];
pattern[5] ='\0';
if( strcmp(text, pattern) == 0 )
{
strcpy(arrayclass[newacindex],ep3->d_name);
newacindex = newacindex +1;
}
}
// * I AM PREPARING TO READ THE CLASS TEXT FILES WHICH I DETECTED ABOVE
(void) closedir (dp3);
char cwd[1024],cwdtemp[1024];
getcwd(cwd, sizeof(cwd));
strcat(cwd,"/");
FILE *file[acindex];
for (int j=0; j < acindex; j=j+1)
{
strcpy(cwdtemp,cwd);
strcat(cwdtemp,arrayclass[j]);
if((file[j] = fopen(cwdtemp, "r"))==NULL) /* open a text file for reading */
exit(1);
printf("%s\n",cwdtemp);
}
int over,over1,over2,over3,over4,over5,over6;
int xx=0;
double dd=0;
char str[256],str1[256],str2[256],str3[256],str4[256],str5[256],str6[256],str7[256],str8[256];
int classoverwriting[50][7];
double classoverwriting1[1][7];
int classunderwriting[50][7];
int classmanuscript[50][7];
int classbothuo[50][7];
int i1;
int nrclass[acindex];
// * I AM DETECTING HOW MANY POINTS HAS EACH CLASS, FOR EXAMPLE CLASS MANUSCRIPT MIGHT HAVE 100 POINTS WHILE CLASS OVERWRITING MIGHT HAVE 120 POINTS, ETC
for (int j=0; j < acindex; j=j+1)
{
fscanf(file[j], " %s %s %s %s %s %s \n", &str,&str1, &str2,&str3,&str4,&str5);
i1=0;
while (!feof(file[j]))
{
fscanf(file[j], " %lf %lf %lf %lf %lf %lf %lf\n", &classoverwriting1[1][1], &classoverwriting1[1][2], &classoverwriting1[1][3], &classoverwriting1[1][4], &classoverwriting1[1][5], &classoverwriting1[1][6], &classoverwriting1[1][7]);
i1 =i1+1;
}
nrclass[j]=i1;
}
int sumtotalnrclass;
sumtotalnrclass = 0;
//exit(1);
for (int j=0; j < acindex; j=j+1)
{
sumtotalnrclass = sumtotalnrclass + nrclass[j];
}
int dummyvar;
int **classtotal = new int*[sumtotalnrclass];
for (int i = 0; i < sumtotalnrclass; i++)
{
classtotal[i] = new int[7];
}
printf(" \n");
double testclass1,testclass2;
// * I AM READING THE POINTS FROM EACH CLASS FILES
i1=0;
for (int j=0; j < acindex; j=j+1)
{
fseek( file[j], 0, SEEK_SET );
fscanf(file[j], " %s %s %s %s %s %s \n", &str,&str1, &str2,&str3,&str4,&str5);
//printf ("%s\n", str);
while (!feof(file[j]))
{
fscanf(file[j], " %s %s %s %s %s %s %s\n", &str,&str1, &str2,&str3,&str4,&str5,&str6);
testclass1 = atof(str5);
testclass2 = atof(str6);
classtotal[i1][6] = round(testclass1);
classtotal[i1][7] = round(testclass2);
i1 =i1+1;
}
fclose(file[j]);
}
char arraytiff[50][2024];//maximum number of images is 50
// * I AM DETECTING THE NUMBER OF MULTISPECTRAL IMAGES AS THERE COULD BE 10 , 16, 23 , ETC MULTISPECTRAL IMAGES
DIR * dp2;
struct dirent* ep2;
char* text1;
char pattern1[6];
char* text22;
pattern1[0]='\0';
pattern1[1]='\0';
pattern1[2]='\0';
pattern1[3]='\0';
pattern1[4]='\0';
pattern1[5]='\0';
text1=".tif";
dp2 = opendir ("./");
int acindex1, sn1;
acindex1 = 0;
while (ep2 = readdir (dp2))
{
text22 = ep2->d_name;
sn1 = strlen(text22);;//sizeof(text22);
pattern1[0] = text22[sn1-4];//ep->d_name[0];
pattern1[1] = text22[sn1-3];//ep->d_name[1];
pattern1[2] = text22[sn1-2];//ep->d_name[2];
pattern1[3] = text22[sn1-1];//ep->d_name[3];
pattern1[4] ='\0';
if( strcmp(text1, pattern1) == 0 )
{
strcpy(arraytiff[acindex1],ep2->d_name);
printf("%s\n",arraytiff[acindex1]);
acindex1 = acindex1 +1;
}
}
char tiffext[4];
char namefile[40];
strncpy(namefile,arraytiff[0],strlen(arraytiff[0])-4);
printf(" TEST 3333333 \n ");
// * I AM COPYING THE PATH TO THE MULTISPECTRAL IMAGES
(void) closedir (dp2);
char cwd1[1024],cwdtemp1[1024],*dfg;
getcwd(cwd1, sizeof(cwd1));
strcat(cwd1,"/");
char arrayimage[acindex1][2024];
char *arrayimage2[acindex1];
printf("%s\n",cwd);
printf("%s\n",cwd1);
for (int j=0; j < acindex1; j=j+1)
{
strcpy(cwdtemp1,cwd1);
strcat(cwdtemp1,arraytiff[j]);
strcpy(arrayimage[j],cwdtemp1);
printf("%s \n",arrayimage[j]);
}
double data_matrix[sumtotalnrclass][acindex1];
//#pragma omp parallel for private(j,i)
for (int i=0; i < sumtotalnrclass; i=i+1)
{
for (int j=0; j < acindex1; j=j+1)
{
data_matrix[i][j] = 0;
}
}
std::vector<Mat> image(acindex1);
std::vector<Mat> various_images;
// * I AM READING THE IMAGES AND I PUT THEM IN THE VECTOR OF IMAGES CALLED VARIOUS_IMAGES
for (int i=0; i < acindex1; i=i+1)
{
image[i] = imread(arrayimage[i], 0);
various_images.push_back(image[i]);
}
s1 = image[0].rows;
s2 = image[0].cols;
//int s1s2;
s1s2 = s1*s2;
if(! image[0].data ) // Check for invalid input
{
cout << "Could not open or find the image" << std::endl ;
// return -1;
}
// p o u b
int *grouping_vector = new int[sumtotalnrclass] ;
for (int k = 0; k < sumtotalnrclass; k++) {
grouping_vector[k] = 0;
}
int *grp = new int[sumtotalnrclass] ;
for (int k = 0; k < sumtotalnrclass; k++) {
grp[k] = 0;
}
// * FROM THE MULTISPECTRAL IMAGES I AM SELECTING THE POINTS BASED ON THE CLASS FILES
int indexonc;
for (int j = 0; j < acindex1; j++) {
indexonc = 0;
for (int k = 0; k < acindex; k++) {
for (int ss = 0; ss < nrclass[k]; ss++)
{
data_matrix[indexonc][j] = (double) various_images[j].at<uchar>(classtotal[indexonc][7]-1,classtotal[indexonc][6]-1);
indexonc = indexonc +1 ;
}
}
}
// * I AM COUNTING THE POINTS FROM EACH CLASS
indexonc = 0;
for (int k = 0; k < acindex; k=k+1) {
for (int ss = 0; ss < nrclass[k]; ss=ss+1)
{
grouping_vector[indexonc] = 1+k;
grp[indexonc]=1+k;
indexonc = indexonc +1 ;
}
}
printf(" \n ");
double X[sumtotalnrclass][acindex1];
for (int i = 0; i < sumtotalnrclass; i++) {
for (int j = 0; j < acindex1; j++) {
X[i][j] = data_matrix[i][j];
}
}
int N,D,K;
float nk[acindex1];
float alpha,xmg[acindex1],xmk[acindex][acindex1];
int index;
float xdiff[sumtotalnrclass], transxdiff[sumtotalnrclass][1];
float sum[acindex1][acindex1], sumare;
// * I AM IMPLEMENTING THE CANONICAL VARIATES ANALYSIS METHOD BASED ON THE MATLAB VERSION OF THIS METHOD
N = sumtotalnrclass;//sizeof(X);
D = acindex1;//sizeof(X[0][0])-1;
for (j=0; j < acindex1; j=j+1)
{
xmg[j] = 0;
}
K = grp[0];
for (int j=1;j<sumtotalnrclass;j++)
{
if (K < grp[j])
{
K = grp[j];
}
}
index=0;
for (j=0;j<acindex1;j++)
{
alpha =0;
for (i=0;i<sumtotalnrclass;i++)
{
alpha = alpha + X[i][j];
}
xmg[j] = alpha/sumtotalnrclass;
}
for (i=0; i < K; i=i+1)
{
for (j=0; j < acindex1; j=j+1)
{
xmk[i][j] = 0;
}
}
float **difference = new float*[acindex1];
for (int i = 0; i < acindex1; i++)
{
difference[i] = new float[acindex1];
}
float **difference1 = new float*[acindex1];
for (int i = 0; i < acindex1; i++)
{
difference1[i] = new float[acindex1];
}
float suma = 0;
double Xinter[sumtotalnrclass][acindex1];
//printf("Hello from thread %d, nthreads %d\n", omp_get_thread_num(), omp_get_num_threads());
//#pragma omp parallel for
/*#pragma omp parallel for
for(int n=0; n<10; n++)
{
printf(" %d", n);
}
printf(".\n");*/
//#pragma omp parallel num_threads(5)
//{
//#pragma omp parallel for
//#pragma omp parallel for private(k,i,c)
for (k=1;k < acindex+1; k++)
{
index = 0;
for (i=0;i<sumtotalnrclass;i++)
{
if (grp[i] == k)
{
for (int c=0;c<acindex1;c++)
{
Xinter[index][c] = X[i][c];
}
index = index +1;
}
}
//printf("Hello from thread %d, nthreads %d\n", omp_get_thread_num(), omp_get_num_threads());
for (int c=0;c<acindex1;c++)
{
suma = 0;
for (int d=0;d<nrclass[k-1];d++)
suma = suma + Xinter[d][c];
xmk[k-1][c] = suma/nrclass[k-1];
}
}
//}
float **S = new float*[D];
for (int i = 0; i < D; i++)
{
S[i] = new float[D];
}
float **B = new float*[D];
for (int i = 0; i < D; i++)
{
B[i] = new float[D];
}
float **xsumdiff = new float*[D];
for (int i = 0; i < D; i++)
{
xsumdiff[i] = new float[D];
}
for (i=0; i < D; i=i+1)
{
for (j=0; j < D; j=j+1)
{
S[i][j] = 0;
}
}
for (i=0; i < D; i=i+1)
{
for (j=0; j < D; j=j+1)
{
xsumdiff[i][j] = 0;
}
}
//#pragma omp parallel for private(i,j,c)
for (int i=0;i<sumtotalnrclass;i++)
{
for (int j=0;j<acindex1;j++)
{
index = grp[i];
xdiff[j] = X[i][j] - xmk[index-1][j] ;
}
for (int c = 0; c < acindex1; c++)
{
transxdiff[c][1] = xdiff[c];
}
//multiply xdiff'*xdiff
for (int c=0;c<acindex1;c++)
{
for (int d = 0; d < acindex1; d++)
{
xsumdiff[c][d] = transxdiff[c][1]*xdiff[d];
//printf ("%f \n", xsumdiff[c][d]);
}
}
for (int c = 0; c < acindex1; c++)
{
for (int d = 0; d < acindex1; d++)
{
//printf ("%f \n", S[c][d]);
S[c][d] = S[c][d] + xsumdiff[c][d];
}
}
}
//#pragma omp parallel for private(i,j)
for (i=0; i < acindex1; i=i+1)
{
for (j=0; j < acindex1; j=j+1)
{
S[i][j] = S[i][j]/(sumtotalnrclass-acindex);
}
}
printf("\n");
//#pragma omp parallel for private(i,j)
for (int i=0; i < D; i=i+1)
{
for (int j=0; j < D; j=j+1)
{
B[i][j] = 0;
//printf("%f \n",B[i][j]);
}
}
double Xtemp[sumtotalnrclass][acindex1];
//#pragma omp parallel for private(i)
for(i = 0; i < sumtotalnrclass; i++)
{
// //printf("%3d: ", i);
for(j = 0; j < acindex1; j++)
Xtemp[i][j] = X[i][j];
}
//nrclass acindex
//#pragma omp parallel for private(k,i,d,c)
for (k =0;k<acindex;k++)
{
for (i=0;i<acindex1;i++)
{
difference[1][i] = nrclass[k]*(xmk[k][i] - xmg[i]);
difference1[1][i] = xmk[k][i] - xmg[i];
}
for(int d = 0 ; d < acindex1 ; d++ )
transxdiff[d][1] = difference[1][d];
for (int d = 0; d < acindex1; d++)
{
for (int c = 0; c < acindex1; c++)
{
sum[c][d] = transxdiff[c][1]*difference1[1][d];
//printf("%f \n",sum[c][d]);
}
}
for (int c=0; c < acindex1; c=c+1)
{
for (int d=0; d < acindex1; d=d+1)
{
B[c][d] = B[c][d]+sum[c][d];
//
printf("%f ",B[c][d]);
}
printf(" \n");
}
printf(" \n");
}
double coefficient;
double coefficient1;
coefficient1 = acindex-1;
coefficient = acindex/coefficient1;
//printf(" %d \n",acindex);
//printf(" %lf \n",coefficient);
//printf(" %d \n",sumtotalnrclass);
//#pragma omp parallel for private(d,c)
for (int c=0; c < acindex1; c=c+1)
{
for (int d=0; d < acindex1; d=d+1)
{
B[c][d] = coefficient*B[c][d]/sumtotalnrclass;
//printf("%f ",B[c][d]);
}
//printf(" \n");
}
float vectork[acindex1];
float finalk =0;
gsl_matrix * AA , *SS;
gsl_vector * eval;
gsl_matrix * evec;
gsl_eigen_gensymmv_workspace * w;
//, gsl_vector_complex * eval, gsl_matrix_complex * evec, gsl_eigen_nonsymmv_workspace * w
int err;
err = 1;
// * I AM USING THE GSL GNU FUNCTIONS GSL_MATRIX_ALLOC , GSL_EIGEN_GENSYMMV_ALLOC , ETC TO CALCULATE THE EIGEN VECTORS
AA = gsl_matrix_alloc(acindex1, acindex1);
SS = gsl_matrix_alloc(acindex1, acindex1);
eval = gsl_vector_alloc(acindex1);
evec = gsl_matrix_alloc(acindex1, acindex1);
w = gsl_eigen_gensymmv_alloc(acindex1);
//#pragma omp parallel for private(i,j)
for (int i = 0; i < acindex1; i++)
for (int j = 0; j < acindex1; j++)
gsl_matrix_set (AA, i, j, B[i][j]);// B[i][j]);
for (int i = 0; i < acindex1; i++)
for (int j = 0; j < acindex1; j++)
gsl_matrix_set (SS, i, j, S[i][j]);// B[i][j]);
int status;
gsl_set_error_handler_off();
status = gsl_eigen_gensymmv( AA, SS, eval, evec, w) ;
double a;
int indexa[acindex1];
for (i = 0; i < acindex1; i++)
{
indexa[i] = i;
}
for (i = 0; i < acindex1; i++)
{
indexa[i]= i;
}
/*for(i = 0; i < 23; i++)
{
printf("%3d %f %i \n", i, gsl_vector_get(eval, i) ,indexa[i]);
}*/
int prst;
//#pragma omp parallel for private(i,j)
for (i = 0; i < acindex1; i++)
{
//indexa[i]= i;
for (j = i ; j < acindex1; j++)
{
if (gsl_vector_get(eval, i) < gsl_vector_get(eval, j))
{
a = gsl_vector_get(eval, i);
gsl_vector_set(eval, i, gsl_vector_get(eval, j) );
prst = indexa[i];
indexa[i]= indexa[j];
indexa[j]= prst;
gsl_vector_set(eval, j, a);
}
else
{
//gsl_vector_set(eval, i, (-1)*gsl_vector_get(eval, i) );
}
}
}
printf(" \n" );
printf(" EIGENVALUES \n ");
for(i = 0; i < acindex1; i++)
{
printf("%3d %f %i \n", i, gsl_vector_get(eval, i) ,indexa[i]);
}
double summ = 0;
double Xresult[sumtotalnrclass][acindex1];
double tempcoef[acindex1][acindex1];
for (i = 0; i < acindex1; i++)
{
for (j = 0; j < acindex1; j++)
{
tempcoef[i][j] = gsl_matrix_get(evec,i,j) ;
}
}
printf(" \n" );
printf(" EIGEN VECTORS \n ");
for(i = 0; i < acindex1; i++)
{
//printf("%3d: ", i);
for(j = 0; j < acindex1; j++)
printf("%lf ", gsl_matrix_get(evec,i,j) );
printf("\n");
}
double coef[acindex1][acindex1];
for(i = 0; i < acindex1; i++)
{
//printf("%3d: ", i);
for(j = 0; j < acindex1; j++)
coef[i][j] = gsl_matrix_get(evec,i,j) ;
}
// * I AM CALCULATING THE NEW IMAGE POINTS BASED ON THE PARAMETERS CALCULATED BY THE GSL GNU FUNCTIONS
//#pragma omp parallel for
//#pragma omp parallel for private(k,i,j)
for(i=0;i<sumtotalnrclass;i++)
{
for(j=0;j<acindex1;j++)
{
summ=0;
for(k=0;k<acindex1;k++)
{
summ=summ+Xtemp[i][k]*gsl_matrix_get(evec, k, j);
}
Xresult[i][j]=summ;
}
}
double** newmatrix1= new double*[s1];
for (int i = 0; i < s1; i++)
{
newmatrix1[i] = new double[s2];
}
//static double newmatrix2[5412][7216];
double** newmatrix2= new double*[s1];
for (int i = 0; i < s1; i++)
{
newmatrix2[i] = new double[s2];
}
//static double newmatrix3[5412][7216];
double** newmatrix3= new double*[s1];
for (int i = 0; i < s1; i++)
{
newmatrix3[i] = new double[s2];
}
for(i = 0; i < s1; i++)
{
for(j = 0; j < s2; j++)
{
newmatrix1[i][j] = 0;
}
}
for(i = 0; i < s1; i++)
{
for(j = 0; j < s2; j++)
{
newmatrix2[i][j] = 0;
}
}
for(i = 0; i < s1; i++)
{
for(j = 0; j < s2; j++)
{
newmatrix3[i][j] = 0;
}
}
double coef1[acindex1][acindex1];
double score1[sumtotalnrclass][acindex1];
//#pragma omp parallel for private(i,j)
for (int i=0; i < sumtotalnrclass; i=i+1)
{
for (int j=0; j < acindex1; j=j+1)
{
score1[i][j] = 0;
}
}
for (int i=0; i < acindex1; i=i+1)
{
for (int j=0; j < acindex1; j=j+1)
{
coef1[i][j] = 0;
}
}
for (int i=0; i < sumtotalnrclass; i=i+1)
{
for (int j=0; j < acindex1; j=j+1)
{
score1[i][j] = Xresult[i][j];
}
}
for (int i=0; i < acindex1; i=i+1)
{
for (int j=0; j < acindex1; j=j+1)
{
coef1[i][j] = coef[i][j];
}
}
// * I AM IMPLEMENTING THE POST-PROCESSING WHICH EXIST IN THE ORIGINAL CANONICAL VARIATES ANALYSIS METHOD IMPLEMENTED INITIALLY IN MATLAB
//#pragma omp parallel for private(j,i,k)
for(i = 0; i < s1; i++)
{
for(j = 0; j < s2; j++)
{
for(k = 0; k < acindex1; k++)
{
newmatrix1[i][j] = newmatrix1[i][j] + ( (double)various_images[k].at<uchar>(i,j) )*coef1[k][0];
newmatrix2[i][j] = newmatrix2[i][j] + ( (double)various_images[k].at<uchar>(i,j) )*coef1[k][1];
newmatrix3[i][j] = newmatrix3[i][j] + ( (double)various_images[k].at<uchar>(i,j) )*coef1[k][2];
}
}
}
double minimum1,minimum2,minimum3;
double maximum1,maximum2,maximum3;
double **range_cv1 = new double*[s1];
for (int i = 0; i < s1; i++)
{
range_cv1[i] = new double[s2];
}
double **range_cv2 = new double*[s1];
for (int i = 0; i < s1; i++)
{
range_cv2[i] = new double[s2];
}
double **range_cv3 = new double*[s1];
for (int i = 0; i < s1; i++)
{
range_cv3[i] = new double[s2];
}
minimum1= newmatrix1[0][0];
for(int i=0; i<s1; i++)
{
for(int j=0; j<s2; j++)
{
if( newmatrix1[i][j]< minimum1)
{
minimum1=newmatrix1[i][j];
}
}
}
minimum2= newmatrix2[0][0];
for(int i=0; i<s1; i++)
{
for(int j=0; j<s2; j++)
{
if( newmatrix2[i][j]< minimum2)
{
minimum2=newmatrix2[i][j];
}
}
}
minimum3= newmatrix3[0][0];
for(int i=0; i<s1; i++)
{
for(int j=0; j<s2; j++)
{
if( newmatrix3[i][j]< minimum3)
{
minimum3=newmatrix3[i][j];
}
}
}
maximum1= newmatrix1[0][0];
for(int i=0; i<s1; i++)
{
for(int j=0; j<s2; j++)
{
if( newmatrix1[i][j]> maximum1)
{
maximum1=newmatrix1[i][j];
}
}
}
maximum2= newmatrix2[0][0];
for(int i=0; i<s1; i++)
{
for(int j=0; j<s2; j++)
{
if( newmatrix2[i][j]> maximum2)
{
maximum2=newmatrix2[i][j];
}
}
}
maximum3= newmatrix3[0][0];
for(int i=0; i<s1; i++)
{
for(int j=0; j<s2; j++)
{
if( newmatrix3[i][j]> maximum3)
{
maximum3=newmatrix3[i][j];
}
}
}
range_cv1 = range_map(newmatrix1, minimum1, maximum1);
range_cv2 = range_map(newmatrix2, minimum2, maximum2);
range_cv3 = range_map(newmatrix3, minimum3, maximum3);
int aa,bb,cc;
printf(" \n" );
printf(" A SET OF 8 PICTURES ARE PRODUCED ");
cv::Mat img16(s1, s2, CV_8UC3);
vector<int> compression_params;
compression_params.push_back(CV_IMWRITE_PNG_COMPRESSION);
compression_params.push_back(9);
for (int i = 0; i < s1; i++) {
for (int j = 0; j < s2; j++) {
img16.at<cv::Vec3b>(i,j)[1] = (255-range_cv2[i][j]);
img16.at<cv::Vec3b>(i,j)[2] = (255-range_cv1[i][j]);
img16.at<cv::Vec3b>(i,j)[3] = (255-range_cv3[i][j]);
}
}
char fileword[100];
strcpy(fileword,namefile);
strcat(fileword,"_image_rangecvasecond.tiff");
//end = clock();
//cpu_time_used = ((double) (end - start)) / CLOCKS_PER_SEC;
//printf(" \n" );
//printf(" %lf ", cpu_time_used );
//exit(1);
cv::imwrite(fileword, img16);
cv::Mat img162(s1, s2, CV_8UC3);
for (int i = 0; i < s1; i++) {
for (int j = 0; j < s2; j++) {
img162.at<cv::Vec3b>(i,j)[1] = range_cv2[i][j];
img162.at<cv::Vec3b>(i,j)[2] = range_cv1[i][j];
img162.at<cv::Vec3b>(i,j)[3] = range_cv3[i][j];
}
}
char fileword1[100];
strcpy(fileword1,namefile);
strcat(fileword1,"_image_rangecva.tiff");
cv::imwrite(fileword1, img162);
double minscore1,minscore2,minscore3;
double maxscore1,maxscore2,maxscore3;
minscore1=0;
minscore1= score1[0][0];
for(int i=0; i<sumtotalnrclass; i++)
{
if( score1[i][0]< minscore1)
{
minscore1=score1[i][0];
}
}
minscore2==0;
minscore2= score1[0][1];
for(int i=0; i<sumtotalnrclass; i++)
{
if( score1[i][1]< minscore2)
{
minscore2=score1[i][1];
}
}
minscore3==0;
minscore3= score1[0][2];
for(int i=0; i<sumtotalnrclass; i++)
{
if( score1[i][2]< minscore3)
{
minscore3=score1[i][2];
}
}
maxscore1=0;
maxscore1= score1[0][0];
for(int i=0; i<sumtotalnrclass; i++)
{
if( score1[i][0]> maxscore1)
{
maxscore1=score1[i][0];
}
}
maxscore2=0;
maxscore2= score1[0][1];
for(int i=0; i<sumtotalnrclass; i++)
{
if( score1[i][1]> maxscore2)
{
maxscore2=score1[i][1];
}
}
maxscore3=0;
maxscore3= score1[0][2];
for(int i=0; i<sumtotalnrclass; i++)
{
if( newmatrix3[i][2]> maxscore3)
{
maxscore3=score1[i][2];
}
}
double **score_cv1 = new double*[s1];
for (int i = 0; i < s1; i++)
{
score_cv1[i] = new double[s2];
}
double **score_cv2 = new double*[s1];
for (int i = 0; i < s1; i++)
{
score_cv2[i] = new double[s2];
}
double **score_cv3 = new double*[s1];
for (int i = 0; i < s1; i++)
{
score_cv3[i] = new double[s2];
}
score_cv1 = range_map(newmatrix1, minscore1, maxscore1);
score_cv2 = range_map(newmatrix2, minscore2, maxscore2);
score_cv3 = range_map(newmatrix3, minscore3, maxscore3);
cv::Mat img163(s1, s2, CV_8UC3);
for (int i = 0; i < s1; i++) {
for (int j = 0; j < s2; j++) {
img163.at<cv::Vec3b>(i,j)[1] = score_cv2[i][j];
img163.at<cv::Vec3b>(i,j)[2] = score_cv1[i][j];
img163.at<cv::Vec3b>(i,j)[3] = score_cv3[i][j];
}
}
char fileword2[100];
strcpy(fileword2,namefile);
strcat(fileword2,"_image_score_rangecva.tiff");
cv::imwrite(fileword2, img163);
cv::Mat img164(s1, s2, CV_8UC3);
for (int i = 0; i < s1; i++) {
for (int j = 0; j < s2; j++) {
img164.at<cv::Vec3b>(i,j)[1] = (255-score_cv2[i][j]);
img164.at<cv::Vec3b>(i,j)[2] = (255-score_cv1[i][j]);
img164.at<cv::Vec3b>(i,j)[3] = (255-score_cv3[i][j]);
}
}
char fileword3[100];
strcpy(fileword3,namefile);
strcat(fileword3,"_image_score_rangecvasecond.tiff");
cv::imwrite(fileword3, img164);
// * I AM PRODUCING THE 8 BIT IMAGES OF THE PERCENTILE
double required_percentiles[8];
required_percentiles[0] = 0.01;
required_percentiles[1] = 0.1;
required_percentiles[2] = 1;
required_percentiles[3] = 5;
required_percentiles[4] = 99.99;
required_percentiles[5] = 99.9;
required_percentiles[6] = 99;
required_percentiles[7] = 95;
int sizerows,sizecolumns;
int n_percentiles;
n_percentiles = (int) 8 / 2;
double *percentiles_cv1 = new double[5];
double *percentiles_cv2 = new double[5];
double *percentiles_cv3 = new double[5];
double *percentiles_cv4 = new double[5];
double *percentiles_cv5 = new double[5];
for (int i = 0; i < 5; i++)
{
percentiles_cv1[i] = 0;
percentiles_cv2[i] = 0;
percentiles_cv3[i] = 0;
percentiles_cv4[i] = 0;
percentiles_cv5[i] = 0;
}
percentiles_cv1 = Percentile(newmatrix1, required_percentiles);
percentiles_cv2 = Percentile(newmatrix2, required_percentiles);
percentiles_cv3 = Percentile(newmatrix3, required_percentiles);
double **per_cv1 = new double*[s1];
for (int i = 0; i < s1; i++)
{
per_cv1[i] = new double[s2];
}
double **per_cv2 = new double*[s1];
for (int i = 0; i < s1; i++)
{
per_cv2[i] = new double[s2];
}
double **per_cv3 = new double*[s1];
for (int i = 0; i < s1; i++)
{
per_cv3[i] = new double[s2];
}
cv::Mat img165(s1, s2, CV_8UC3);
char str22[35];
for (int i = 0; i < n_percentiles ; i++)
{
per_cv1 = range_map(newmatrix1,percentiles_cv1[i] , percentiles_cv1[i+n_percentiles]);
per_cv2 = range_map(newmatrix2, percentiles_cv2[i], percentiles_cv2[i+n_percentiles]);
per_cv3 = range_map(newmatrix3, percentiles_cv3[i], percentiles_cv3[i+n_percentiles]);
for (int i = 0; i < s1; i++) {
for (int j = 0; j < s2; j++) {
img165.at<cv::Vec3b>(i,j)[1] = per_cv2[i][j];
img165.at<cv::Vec3b>(i,j)[2] = per_cv1[i][j];
img165.at<cv::Vec3b>(i,j)[3] = per_cv3[i][j];
}
}
sprintf(str22,"_image_percentile_%lfcva.tiff", required_percentiles[i]);
strcpy(fileword3,namefile);
strcat(fileword3,str22);
cv::imwrite(fileword3, img165);
}
end = clock();
cpu_time_used = ((double) (end - start)) / CLOCKS_PER_SEC;
printf(" %lf ", cpu_time_used );
return;
}
//double* Percentile(double arr[5412][7216], double percentile[8])
double* Percentile(double** arr, double percentile[8])
{
int index,size1;
index =0;
double *resultingvector = new double[s1s2];
size1 = sizeof(percentile);
for(int i = 0; i < s1; i++)
{
for(int j = 0; j < s2; j++)
{
resultingvector[index] = arr[i][j];
index = index +1;
}
}
double aa;
gsl_vector * v = gsl_vector_alloc (s1s2);
for (int i = 0; i < s1s2; i++)
{
gsl_vector_set (v, i,resultingvector[i] );
}
gsl_sort_vector(v);
for (int i = 0; i < s1s2; i++)
{
resultingvector[i] = gsl_vector_get (v, i);
}
int index2;
double *percentile_values = new double[size1];
for(int i = 0; i < size1; i++)
{
index2 = round(1 + (percentile[i]/100)*(s1s2-1));
percentile_values[i] = resultingvector[index2];
}
return percentile_values;
}
int compare_doubles (const double * a,
const double * b)
{
if (*a > *b)
return 1;
else if (*a < *b)
return -1;
else
return 0;
}
double* quickSort( double a[], long l, long r)
{
long j;
//r = 39052992;
if( l < r )
{
// divide and conquer
j = partition( a, l, r);
a = quickSort( a, l, j-1);
a = quickSort( a, j+1, r);
}
//for(int i = 0; i < 39052992; i++)
//{
printf(" %d \n", j );
//}
return a;
}
long partition(double a[], long l, long r) {
long i, j;
double pivot,t;
pivot = a[l];
i = l; j = r+1;
while( 1)
{
do ++i; while( a[i] <= pivot && i <= r );
do --j; while( a[j] > pivot );
if( i >= j ) break;
t = a[i]; a[i] = a[j]; a[j] = t;
}
t = a[l]; a[l] = a[j]; a[j] = t;
return j;
}
//double** range_map(double newmatrix[5412][7216], double minimum, double maximum)
double** range_map(double** newmatrix, double minimum, double maximum)
{
//static double newimage[5412][7216];
double **newimage = new double*[s1];
for (int i = 0; i < s1; i++)
{
newimage[i] = new double[s2];
}
double out_low, out_high, out_range_low, out_range_high,v,v2;
out_low = 0;
out_high =255;
out_range_low = 0;
out_range_high = 255;
double in_low,in_high;
in_low = minimum;
in_high = maximum;
for(int i = 0; i < s1; i++)
{
for(int j = 0; j < s2; j++)
{
v = newmatrix[i][j];
if (v < in_low)
v2 = out_range_low;
else if (v > in_high)
v2 = out_range_high;
else
v2 = ((v - in_low) / (in_high - in_low)) * (out_high - out_low) + out_low;
//newimage[i][j] = uint8(floor(v2 + 0.5));
newimage[i][j] = uint8_t(floor(v2+0.5));
}
}
return newimage;
}
| {
"alphanum_fraction": 0.4462886626,
"avg_line_length": 20.8723646724,
"ext": "c",
"hexsha": "61d271f830acd04387ba5f8f139a1a4783e773e1",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2019-05-12T00:30:12.000Z",
"max_forks_repo_forks_event_min_datetime": "2019-05-12T00:30:12.000Z",
"max_forks_repo_head_hexsha": "8d0ad9b36eb3e0830814a18243c8ac57ddcaf6a6",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "corneliu37/GalenProject",
"max_forks_repo_path": "HelloWorld.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "8d0ad9b36eb3e0830814a18243c8ac57ddcaf6a6",
"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": "corneliu37/GalenProject",
"max_issues_repo_path": "HelloWorld.c",
"max_line_length": 245,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "8d0ad9b36eb3e0830814a18243c8ac57ddcaf6a6",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "corneliu25/GalenProject",
"max_stars_repo_path": "HelloWorld.c",
"max_stars_repo_stars_event_max_datetime": "2019-08-09T10:10:24.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-08-09T10:10:24.000Z",
"num_tokens": 11081,
"size": 36631
} |
/*
* Copyright 2008-2016 Jan Gasthaus
*
* 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 UTILS_H_
#define UTILS_H_
#include <string>
#include <cmath>
#include <map>
#include <iostream>
#include <fstream>
#include <sstream>
#include <cassert>
#include <algorithm>
#include <gsl/gsl_sf_gamma.h>
////////////////////////////////////////////////////////////////////////////////
///////////////// SOME USEFUL MACROS ///////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
#ifdef DEBUG
#define tracer if (0) ; else std::cerr
#define DBG if (1)
#else
#define tracer if (1) ; else std::cerr
#define DBG if (1) ; else
#endif
// some syntactic sugar for implementing interfaces using (multiple) inheritance
#define interface class
#define implements public
// A macro to disallow the copy constructor and operator= functions
// This should be used in the private: declarations for a class
#define DISALLOW_COPY_AND_ASSIGN(TypeName) \
TypeName(const TypeName&); \
void operator=(const TypeName&)
namespace gatsby { namespace libplump {
/**
* Alias: std::vector<double>
*/
typedef std::vector<double> d_vec;
/**
* Alias: std::vector<std::vector<double> >
*/
typedef std::vector<d_vec> d_vec_vec;
/**
* Alias: std::vector<unsigned int>
*/
typedef std::vector<unsigned int> ui_vec;
/**
* Alias: std::vector<std::vector<unsigned int> >
*/
typedef std::vector<ui_vec> ui_vec_vec;
/**
* Compute log2(x) -- the log2 provided by GCC is somewhat weird.
*/
inline double log2(double x){
static const double LOG2 = std::log(2.);
return std::log(x)/LOG2;
}
/**
* Read items of type E from a file and push them into a sequence of type
* S (that has to support push_back(E item).
*
* Items are read from the file sizeof(E) bytes at a time. No error checking
* is performed.
*
* @tparam E Type of element to read from file, elements will be read sizeof(E)
* bytes at a time.
* @tparam S Type of sequence to push items into;
* must support push_back(E item)
* @param fileName Name of the file to read from
* @param seq Sequence to push items into
* @param limit Maximum number of items to push (default: 0, no limit)
*/
template<typename E, class S>
inline void pushFileToVec(const std::string& fileName, S& seq, int limit = 0){
std::ifstream in;
in.open(fileName.c_str(),std::ios::binary | std::ios_base::in);
char buffer[sizeof(E)];
in.read(buffer,sizeof(E));
int j = 0;
if (limit==0)
limit = -1;
while (!in.eof() && j!=limit){
seq.push_back(*((E*)buffer));
in.read(buffer,sizeof(E));
j++;
}
in.close();
}
/**
* Push each character of string s individually into container seq of type S,
* which has to support push_back(char c);
*
* @tparam S type of container to push into
* @param s input string to push
* @param seq output container to push into
*/
template<class S>
inline void pushStringToVec(const std::string& s, S& seq){
for (size_t i=0;i<s.length();i++) {
seq.push_back(s[i]);
}
}
/**
* Convert a map<T,T> where T is an integer type with
* range 0...MAX to a vector v of length MAX+1 so that
* v[x] = m[x] for x=1,...,MAX. v[x] = 0 if m.count(x) = 0.
*
* @tparam T integer type
* @param m input map
* @param v output vector
* @returns pointer to histogram vector on the heap
*/
template<typename T>
inline void mapHistogramToVectorHistogram(const std::map<T,T>& m, std::vector<T>& v) {
T max = (*max_element(m.begin(), m.end())).first;
v.clear();
v.assign(max + 1,0);
for (typename std::map<T,T>::iterator i = m.begin(); i != m.end(); ++i) {
v[(*i).first] = (*i).second;
}
return v;
}
/**
* Count the number of times the elements k=0...max-1 occur in vec and
* return the result in ret[k].
*/
template<typename T>
inline std::vector<T> vec2hist(std::vector<T>& vec, T max) {
std::vector<T> ret(max,0);
for (unsigned int i = 0; i < vec.size(); ++i) {
++ret[vec[i]];
}
return ret;
}
/**
* Compute the mean of the elements in a sequence.
*
* @tparam T iteratable sequence type; must have a const_iterator member
* as well as begin() and end() methods.
* @param in sequence to compute the mean of
* @returns the mean of the elements in the sequence
*/
template<typename T>
inline double mean(const T& in) {
double mean = 0.0;
size_t j = 0;
for (typename T::const_iterator i = in.begin(); i != in.end(); ++i) {
mean += (((double)*i)-mean)/(++j);
}
return mean;
}
/**
* Sum the elements in a sequence.
*
* @tparam T iteratable sequence type; must have a const_iterator member
* as well as begin() and end() methods.
* @param in sequence to compute the sum of
* @returns the sum of the elements in the sequence
*/
template<typename T>
inline typename T::value_type sum(const T& in) {
typename T::value_type sum = 0;
for (typename T::const_iterator i = in.begin(); i != in.end(); ++i) {
sum += *i;
}
return sum;
}
inline void log2_vec(d_vec& in) {
for (size_t i=0;i<in.size();i++){
in[i] = log2(in[i]);
}
}
inline void exp_vec(d_vec& in) {
for (size_t i=0;i<in.size();i++){
in[i] = exp(in[i]);
}
}
/**
* Multiply all elements of a vector by a constant.
*/
template<typename elem_t>
inline void mult_vec(std::vector<elem_t>& in, elem_t mult) {
for (size_t i=0;i<in.size();i++){
in[i] = in[i] * mult;
}
}
/**
* Add a constant to all elements of a vector.
*/
template<typename elem_t>
inline void add_vec(std::vector<elem_t>& in, elem_t add) {
for (size_t i=0;i<in.size();i++){
in[i] = in[i] + add;
}
}
/**
* Subtract max element fromall elements of a vector.
*/
template<typename elem_t>
inline void subMax_vec(std::vector<elem_t>& in) {
elem_t max = *std::max_element(in.begin(), in.end());
// if (max == -INFINITY) {
// for (size_t i=0;i<in.size();i++){
// in[i] = 0;
// }
// }
for (size_t i=0;i<in.size();i++){
in[i] = in[i] - max;
}
}
/**
* Add two vectors elementwise.
*/
template<typename elem_t>
inline void add_vec(std::vector<elem_t>& inout, const std::vector<elem_t>& add) {
std::transform(inout.begin(), inout.end(), add.begin(), inout.begin(),
std::plus<elem_t>());
}
/**
* Elementwise multiplication. Results is returned in the first argument.
*/
template<typename elem_t>
inline void mult_vec(std::vector<elem_t>& inout, std::vector<elem_t> in) {
assert(inout.size() == in.size());
for (size_t i=0;i<inout.size();i++){
inout[i] *= in[i];
}
}
/**
* Average the values in multiple vectors of the same length.
**/
inline d_vec average(const d_vec_vec& ins) {
d_vec out(ins[0].size(), 0);
for (int j = 0; j < ins.size(); j++) {
add_vec(out, ins[j]);
}
mult_vec(out, 1./ins.size());
return out;
}
template<typename elem_t>
inline double prob2loss(std::vector<elem_t> in) {
double out = 0.0;
for (size_t i=0;i<in.size();i++){
out -= log2(in[i]);
}
return out/in.size();
}
inline bool closeTo(double value, double target, double tol=10e-4) {
return std::abs(value-target) < tol;
}
template<typename Iterable>
inline std::string iterableToString(const Iterable input) {
std::ostringstream output;
for(typename Iterable::const_iterator it = input.begin(); it!=input.end();it++) {
output << *it << ", ";
}
return output.str();
}
template<typename Iterable>
void iterableToCSVFile(const Iterable input, std::string fn) {
std::ofstream output(fn.c_str());
output.precision(10);
for(typename Iterable::const_iterator it = input.begin(); it!=input.end();it++) {
output << *it << ", ";
}
}
/**
* computes log(exp(a) + exp(b)) while avoiding numerical
* instabilities.
*/
inline double logsumexp(double a, double b) {
// choose c to be the one that is largest in abs value
double c = (a>b)?a:b;
return (log(exp(a-c) + exp(b-c))) + c;
}
inline double sigmoid(double x) {
return 1.0/(1.0 + exp(-x));
}
// logit = inverse sigmoid
inline double logit(double x) {
return log(x) - log(1-x);
}
inline double logKramp(double base, double inc, double lim) {
if (inc == 0)
return lim*log(base);
if (lim <= 0) {
return 0;
} else {
return lim*log(inc) + gsl_sf_lnpoch(base/inc, lim);
}
}
inline double kramp(double base, double inc, double lim) {
return exp(logKramp(base, inc, lim));
}
static clock_t global_clock;
/*
* Start timing
*/
inline void tic() {
global_clock = clock();
}
/**
* Return number of seconds since last tic()
*/
inline double toc() {
return (clock() - global_clock)/(double)CLOCKS_PER_SEC;
}
inline std::string makeProgressBarString(double percentDone, int total=10) {
std::ostringstream out;
int numDone = (int)floor(total * percentDone);
out << "[";
for (int i=0; i<numDone; i++) {
out << "=";
}
out << ">";
for (int i=numDone; i<total; i++) {
out << " ";
}
out << "]";
return out.str();
}
}} // namespace gatsby::libplump
#endif /* UTILS_H_ */
| {
"alphanum_fraction": 0.6144368005,
"avg_line_length": 24.7811704835,
"ext": "h",
"hexsha": "b0f6717b5546c8e258596fb070b78a6eba5f95df",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2016-11-20T00:56:17.000Z",
"max_forks_repo_forks_event_min_datetime": "2016-11-17T19:19:37.000Z",
"max_forks_repo_head_hexsha": "18e5911575e3c9a054482b08d637dc91b0cd05b9",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "jgasthaus/libPLUMP",
"max_forks_repo_path": "src/libplump/utils.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "18e5911575e3c9a054482b08d637dc91b0cd05b9",
"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": "jgasthaus/libPLUMP",
"max_issues_repo_path": "src/libplump/utils.h",
"max_line_length": 88,
"max_stars_count": 13,
"max_stars_repo_head_hexsha": "18e5911575e3c9a054482b08d637dc91b0cd05b9",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "jgasthaus/libPLUMP",
"max_stars_repo_path": "src/libplump/utils.h",
"max_stars_repo_stars_event_max_datetime": "2021-02-16T03:50:37.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-02-02T21:46:58.000Z",
"num_tokens": 2614,
"size": 9739
} |
/**
* @file zheevd.c
*
* PLASMA computational routines
* Release Date: November, 15th 2009
* PLASMA is a software package provided by Univ. of Tennessee,
* Univ. of California Berkeley and Univ. of Colorado Denver
*
* @version 2.6.0
* @author Azzam Haidar
* @author Hatem Ltaief
* @date 2010-11-15
* @precisions normal z -> s d c
*
**/
#include <lapacke.h>
#include "common.h"
/***************************************************************************//**
*
* @ingroup PLASMA_Complex64_t
*
* PLASMA_zheevd - Computes all eigenvalues and, optionally,
* eigenvectors of a complex Hermitian matrix A. The matrix A is
* preliminary reduced to tridiagonal form using a two-stage
* approach:
* First stage: reduction to band tridiagonal form;
* Second stage: reduction from band to tridiagonal form.
*
*******************************************************************************
*
* @param[in] jobz
* Intended usage:
* = PlasmaNoVec: computes eigenvalues only;
* = PlasmaVec: computes eigenvalues and eigenvectors.
*
* @param[in] uplo
* Specifies whether the matrix A is upper triangular or
* lower triangular:
* = PlasmaUpper: Upper triangle of A is stored;
* = PlasmaLower: Lower triangle of A is stored.
*
* @param[in] N
* The order of the matrix A. N >= 0.
*
* @param[in,out] A
* On entry, the symmetric (or Hermitian) matrix A.
* If uplo = PlasmaUpper, the leading N-by-N upper triangular
* part of A contains the upper triangular part of the matrix
* A, and the strictly lower triangular part of A is not
* referenced.
* If uplo = PlasmaLower, the leading N-by-N lower triangular
* part of A contains the lower triangular part of the matrix
* A, and the strictly upper triangular part of A is not
* referenced.
* On exit, the lower triangle (if uplo = PlasmaLower) or the
* upper triangle (if uplo = PlasmaUpper) of A, including the
* diagonal, is destroyed.
*
* @param[in] LDA
* The leading dimension of the array A. LDA >= max(1,N).
*
* @param[out] W
* On exit, if info = 0, the eigenvalues.
*
* @param[in, out] descT
* On entry, descriptor as return by PLASMA_Alloc_Workspace_zheevd
* On exit, contains auxiliary factorization data.
*
* @param[out] Q
* On exit, if jobz = PlasmaVec and info = 0, the eigenvectors.
*
* @param[in] LDQ
* The leading dimension of the array Q. LDQ >= max(1,N).
*
*******************************************************************************
*
* @return
* \retval PLASMA_SUCCESS successful exit
* \retval <0 if -i, the i-th argument had an illegal value
* \retval >0 if INFO = i, the algorithm failed to converge; i
* off-diagonal elements of an intermediate tridiagonal
* form did not converge to zero.
*
*******************************************************************************
*
* @sa PLASMA_zheevd_Tile
* @sa PLASMA_zheevd_Tile_Async
* @sa PLASMA_cheevd
* @sa PLASMA_dsyev
* @sa PLASMA_ssyev
*
******************************************************************************/
int PLASMA_zheevd(PLASMA_enum jobz, PLASMA_enum uplo, int N,
PLASMA_Complex64_t *A, int LDA,
double *W,
PLASMA_desc *descT,
PLASMA_Complex64_t *Q, int LDQ)
{
int NB;
int status;
plasma_context_t *plasma;
PLASMA_sequence *sequence = NULL;
PLASMA_request request = PLASMA_REQUEST_INITIALIZER;
PLASMA_desc descA;
plasma = plasma_context_self();
if (plasma == NULL) {
plasma_error("PLASMA_zheevd", "PLASMA not initialized");
return PLASMA_ERR_NOT_INITIALIZED;
}
/* Check input arguments */
if (jobz != PlasmaNoVec && jobz != PlasmaVec) {
plasma_error("PLASMA_zheevd", "illegal value of jobz");
return -1;
}
if (uplo != PlasmaLower && uplo != PlasmaUpper) {
plasma_error("PLASMA_zheevd", "illegal value of uplo");
return -2;
}
if (N < 0) {
plasma_error("PLASMA_zheevd", "illegal value of N");
return -3;
}
if (LDA < max(1, N)) {
plasma_error("PLASMA_zheevd", "illegal value of LDA");
return -5;
}
if (LDQ < max(1, N)) {
plasma_error("PLASMA_zheevd", "illegal value of LDQ");
return -9;
}
/* Quick return */
if (N == 0)
return PLASMA_SUCCESS;
/* Tune NB & IB depending on N; Set NBNB */
status = plasma_tune(PLASMA_FUNC_ZHEEVD, N, N, 0);
if (status != PLASMA_SUCCESS) {
plasma_error("PLASMA_zheevd", "plasma_tune() failed");
return status;
}
/* Set NT */
NB = PLASMA_NB;
plasma_sequence_create(plasma, &sequence);
if ( PLASMA_TRANSLATION == PLASMA_OUTOFPLACE ) {
plasma_zooplap2tile( descA, A, NB, NB, LDA, N, 0, 0, N, N, sequence, &request,
plasma_desc_mat_free(&(descA)) );
} else {
plasma_ziplap2tile( descA, A, NB, NB, LDA, N, 0, 0, N, N,
sequence, &request);
}
/* Call the tile interface */
PLASMA_zheevd_Tile_Async(jobz, uplo, &descA, W, descT, Q, LDQ, sequence, &request);
if ( PLASMA_TRANSLATION == PLASMA_OUTOFPLACE ) {
plasma_zooptile2lap( descA, A, NB, NB, LDA, N, sequence, &request);
plasma_dynamic_sync();
plasma_desc_mat_free(&descA);
} else {
plasma_ziptile2lap( descA, A, NB, NB, LDA, N, sequence, &request);
plasma_dynamic_sync();
}
status = sequence->status;
plasma_sequence_destroy(plasma, sequence);
return status;
}
/***************************************************************************//**
*
* @ingroup PLASMA_Complex64_t_Tile
*
* PLASMA_zheevd_Tile - Computes all eigenvalues and, optionally, eigenvectors of a
* complex Hermitian matrix A using a two-stage approach:
* First stage: reduction to band tridiagonal form;
* Second stage: reduction from band to tridiagonal form.
*
* Operates on matrices stored by tiles.
* All matrices are passed through descriptors.
* All dimensions are taken from the descriptors.
*
*******************************************************************************
*
* @param[in] jobz
* Intended usage:
* = PlasmaNoVec: computes eigenvalues only;
* = PlasmaVec: computes eigenvalues and eigenvectors.
*
* @param[in] uplo
* Specifies whether the matrix A is upper triangular or
* lower triangular:
* = PlasmaUpper: Upper triangle of A is stored;
* = PlasmaLower: Lower triangle of A is stored.
*
* @param[in,out] A
* On entry, the symmetric (or Hermitian) matrix A.
* If uplo = PlasmaUpper, the leading N-by-N upper triangular
* part of A contains the upper triangular part of the matrix
* A, and the strictly lower triangular part of A is not
* referenced.
* If UPLO = 'L', the leading N-by-N lower triangular part of
* A contains the lower triangular part of the matrix A, and
* the strictly upper triangular part of A is not referenced.
* On exit, if jobz = PlasmaVec, then if return value = 0, A
* contains the orthonormal eigenvectors of the matrix A.
* If jobz = PlasmaNoVec, then on exit the lower triangle (if
* uplo = PlasmaLower) or the upper triangle (if uplo =
* PlasmaUpper) of A, including the diagonal, is destroyed.*
*
* @param[out] W
* On exit, if info = 0, the eigenvalues.
*
* @param[in,out] T
* On entry, descriptor as return by
* PLASMA_Alloc_Workspace_zheevd
* On exit, contains auxiliary factorization data.
*
* @param[out] Q
* On exit, if jobz = PlasmaVec and info = 0, the eigenvectors.
*
* @param[in] LDQ
* The leading dimention of the eigenvectors matrix Q. LDQ >= max(1,N).
*
*******************************************************************************
*
* @return
* \retval PLASMA_SUCCESS successful exit
* \retval <0 if -i, the i-th argument had an illegal value
* \retval >0 if INFO = i, the algorithm failed to converge; i
* off-diagonal elements of an intermediate tridiagonal
* form did not converge to zero.
*
*******************************************************************************
*
* @sa PLASMA_zheevd_Tile
* @sa PLASMA_zheevd_Tile_Async
* @sa PLASMA_cheevd
* @sa PLASMA_dsyev
* @sa PLASMA_ssyev
*
******************************************************************************/
int PLASMA_zheevd_Tile(PLASMA_enum jobz, PLASMA_enum uplo,
PLASMA_desc *A, double *W,
PLASMA_desc *T, PLASMA_Complex64_t *Q, int LDQ)
{
plasma_context_t *plasma;
PLASMA_sequence *sequence = NULL;
PLASMA_request request = PLASMA_REQUEST_INITIALIZER;
int status;
plasma = plasma_context_self();
if (plasma == NULL) {
plasma_fatal_error("PLASMA_zheevd_Tile", "PLASMA not initialized");
return PLASMA_ERR_NOT_INITIALIZED;
}
plasma_sequence_create(plasma, &sequence);
PLASMA_zheevd_Tile_Async(jobz, uplo, A, W, T, Q, LDQ, sequence, &request);
plasma_dynamic_sync();
status = sequence->status;
plasma_sequence_destroy(plasma, sequence);
return status;
}
/***************************************************************************//**
*
* @ingroup PLASMA_Complex64_t_Tile_Async
*
* PLASMA_zheevd_Tile_Async - Computes all eigenvalues and,
* optionally, eigenvectors of a complex Hermitian matrix A using a
* two-stage approach:
* First stage: reduction to band tridiagonal form;
* Second stage: reduction from band to tridiagonal form.
*
* May return before the computation is finished.
* Allows for pipelining of operations at runtime.
*
*******************************************************************************
*
* @param[in] jobz
* Intended usage:
* = PlasmaNoVec: computes eigenvalues only;
* = PlasmaVec: computes eigenvalues and eigenvectors.
*
* @param[in] uplo
* Specifies whether the matrix A is upper triangular or
* lower triangular:
* = PlasmaUpper: Upper triangle of A is stored;
* = PlasmaLower: Lower triangle of A is stored.
*
* @param[in,out] A
* On entry, the symmetric (or Hermitian) matrix A.
* If uplo = PlasmaUpper, the leading N-by-N upper triangular
* part of A contains the upper triangular part of the matrix
* A, and the strictly lower triangular part of A is not
* referenced.
* If UPLO = 'L', the leading N-by-N lower triangular part of
* A contains the lower triangular part of the matrix A, and
* the strictly upper triangular part of A is not referenced.
* On exit, if jobz = PlasmaVec, then if return value = 0, A
* contains the orthonormal eigenvectors of the matrix A.
* If jobz = PlasmaNoVec, then on exit the lower triangle (if
* uplo = PlasmaLower) or the upper triangle (if uplo =
* PlasmaUpper) of A, including the diagonal, is destroyed.*
*
* @param[out] W
* On exit, if info = 0, the eigenvalues.
*
* @param[in,out] T
* On entry, descriptor as return by
* PLASMA_Alloc_Workspace_zheevd
* On exit, contains auxiliary factorization data.
*
* @param[out] Q
* On exit, if jobz = PlasmaVec and info = 0, the eigenvectors.
*
* @param[in] LDQ
* The leading dimention of the eigenvectors matrix Q. LDQ >= max(1,N).
*
* @param[in] sequence
* Identifies the sequence of function calls that this call belongs to
* (for completion checks and exception handling purposes).
*
* @param[out] request
* Identifies this function call (for exception handling purposes).
*
*******************************************************************************
*
* @sa PLASMA_zheevd
* @sa PLASMA_zheevd_Tile
* @sa PLASMA_cheevd_Tile_Async
* @sa PLASMA_dsyev_Tile_Async
* @sa PLASMA_ssyev_Tile_Async
*
******************************************************************************/
int PLASMA_zheevd_Tile_Async(PLASMA_enum jobz, PLASMA_enum uplo,
PLASMA_desc *A,
double *W,
PLASMA_desc *T,
PLASMA_Complex64_t *Q, int LDQ,
PLASMA_sequence *sequence, PLASMA_request *request)
{
plasma_context_t *plasma;
PLASMA_desc descA;
PLASMA_desc descT;
PLASMA_desc descQ;
PLASMA_Complex64_t *AB;
double *E;
int N;
int NB;
int LDAB;
int status;
plasma = plasma_context_self();
if (plasma == NULL) {
plasma_fatal_error("PLASMA_zheevd_Tile_Async", "PLASMA not initialized");
return PLASMA_ERR_NOT_INITIALIZED;
}
if (sequence == NULL) {
plasma_fatal_error("PLASMA_zheevd_Tile_Async", "NULL sequence");
return PLASMA_ERR_UNALLOCATED;
}
if (request == NULL) {
plasma_fatal_error("PLASMA_zheevd_Tile_Async", "NULL request");
return PLASMA_ERR_UNALLOCATED;
}
/* Check sequence status */
if (sequence->status == PLASMA_SUCCESS)
request->status = PLASMA_SUCCESS;
else
return plasma_request_fail(sequence, request, PLASMA_ERR_SEQUENCE_FLUSHED);
/* Check descriptors for correctness */
if (plasma_desc_check(A) != PLASMA_SUCCESS) {
plasma_error("PLASMA_zheevd_Tile_Async", "invalid descriptor");
return plasma_request_fail(sequence, request, PLASMA_ERR_ILLEGAL_VALUE);
} else {
descA = *A;
}
if (plasma_desc_check(T) != PLASMA_SUCCESS) {
plasma_error("PLASMA_zheevd_Tile_Async", "invalid descriptor");
return plasma_request_fail(sequence, request, PLASMA_ERR_ILLEGAL_VALUE);
} else {
descT = *T;
}
/* Check input arguments */
if (jobz != PlasmaNoVec && jobz != PlasmaVec) {
plasma_error("PLASMA_zheevd_Tile_Async", "illegal value of jobz");
return plasma_request_fail(sequence, request, PLASMA_ERR_ILLEGAL_VALUE);
}
if (uplo != PlasmaLower && uplo != PlasmaUpper) {
plasma_error("PLASMA_zheevd_Tile_Async", "illegal value of uplo");
return plasma_request_fail(sequence, request, PLASMA_ERR_ILLEGAL_VALUE);
}
if (descA.m != descA.n) {
plasma_error("PLASMA_zheevd_Tile_Async", "matrix need to be square");
return plasma_request_fail(sequence, request, PLASMA_ERR_ILLEGAL_VALUE);
}
if (descA.nb != descA.mb) {
plasma_error("PLASMA_zheevd_Tile_Async", "only square tiles supported");
return plasma_request_fail(sequence, request, PLASMA_ERR_ILLEGAL_VALUE);
}
N = descA.m;
NB = min(descA.mb,descA.m);
LDAB = 2*NB+1;
/* Allocate workspace for band storage of the band matrix A and for the off diagonal after tridiagonalisation */
AB = (PLASMA_Complex64_t *)plasma_shared_alloc(plasma, LDAB*N, PlasmaComplexDouble);
memset( AB, 0, LDAB * N * sizeof(PLASMA_Complex64_t) );
if (AB == NULL) {
plasma_error("PLASMA_zheevd_Tile_Async", "plasma_shared_alloc(AB) failed");
plasma_shared_free(plasma, AB);
return PLASMA_ERR_OUT_OF_RESOURCES;
}
E = (double *)plasma_shared_alloc(plasma, N, PlasmaRealDouble);
if (E == NULL) {
plasma_error("PLASMA_zheevd_Tile_Async", "plasma_shared_alloc(E) failed");
plasma_shared_free(plasma, E);
return PLASMA_ERR_OUT_OF_RESOURCES;
}
#if defined(ENABLE_TIMER)
PLASMA_Double_t timelpk=0.0,timeaplQ2=0.0, timeT=0.0;
PLASMA_Double_t timeB=0.0,timeblg=0.0,timeaplQ1=0.0,timeconv1=0.0,timeconv2=0.0,timeall=0.0;
timeall = PLASMA_Wtime();
timeB = PLASMA_Wtime();
#endif
/* Reduction to tridiagonal form
* with a two-stage approach.
*/
/*=======================================
* calling Reduction to BAND
* then convert matrix to band form
*=======================================*/
plasma_dynamic_call_5(plasma_pzhetrd_he2hb,
PLASMA_enum, uplo,
PLASMA_desc, descA,
PLASMA_desc, descT,
PLASMA_sequence*, sequence,
PLASMA_request*, request);
plasma_dynamic_call_6( plasma_pzhbcpy_t2bl,
PLASMA_enum, uplo,
PLASMA_desc, descA,
PLASMA_Complex64_t*, AB,
int, LDAB,
PLASMA_sequence*, sequence,
PLASMA_request*, request);
plasma_dynamic_sync();
status = sequence->status;
if (status != PLASMA_SUCCESS) {
plasma_error("PLASMA_zheevd","pzhetrd_he2hb+pzcopy");
return status;
}
/*=======================================
* END of calling Reduction to BAND
*=======================================*/
#if defined(ENABLE_TIMER)
timeB = PLASMA_Wtime()-timeB;
printf("\n Finish Band red timing= %lf \n",timeB);
#endif
/*=======================================
* calling bulge chasing
*=======================================*/
PLASMA_Complex64_t *TAU2 = NULL;
PLASMA_Complex64_t *V2 = NULL;
PLASMA_Complex64_t *T2 = NULL;
int Vblksiz, blkcnt, LDT, LDV;
int WANTZ = 0;
int blguplo = PlasmaLower;
/* int NE = N; // for later use when a portion of the eigenvectors are requested*/
if( jobz == PlasmaNoVec )
WANTZ=0;
else
WANTZ=2;
/* Vblksiz correspond to the blocking used when applying V2 to the matrix Q
* it is similar to IB in LAPACK ZUNMQR.
* blkcnt is the number of losange or tile of Vs */
/* Note that in case PlamaVec requested, the V2 and T2 are stored by the
* bulgechasing function in a special format:
* for V2s: it store the V2(LDV,Vblksiz) of each losange in a tile storage meaning
* that V2_1 is stored then V2_2,..., V2_blkcnt.
* blkcnt is the number of losange.
* */
Vblksiz = min(NB,48);
LDT = Vblksiz;
if( jobz == PlasmaVec ) {
findVTsiz(N, NB, Vblksiz, &blkcnt, &LDV);
TAU2 = (PLASMA_Complex64_t *) plasma_shared_alloc(plasma, blkcnt*Vblksiz, PlasmaComplexDouble);
V2 = (PLASMA_Complex64_t *) plasma_shared_alloc(plasma, LDV*blkcnt*Vblksiz, PlasmaComplexDouble);
T2 = (PLASMA_Complex64_t *) plasma_shared_alloc(plasma, LDT*blkcnt*Vblksiz, PlasmaComplexDouble);
if ( (TAU2 == NULL) || (V2 == NULL) || (T2 == NULL) ) {
plasma_error("PLASMA_zheevd", "plasma_shared_alloc() failed");
plasma_shared_free(plasma, TAU2);
plasma_shared_free(plasma, V2);
plasma_shared_free(plasma, T2);
return PLASMA_ERR_OUT_OF_RESOURCES;
}
memset(TAU2, 0, blkcnt*Vblksiz*sizeof(PLASMA_Complex64_t));
memset(V2, 0, LDV*blkcnt*Vblksiz*sizeof(PLASMA_Complex64_t));
memset(T2, 0, LDT*blkcnt*Vblksiz*sizeof(PLASMA_Complex64_t));
}
else {
TAU2 = (PLASMA_Complex64_t *) plasma_shared_alloc(plasma, 2*N, PlasmaComplexDouble);
V2 = (PLASMA_Complex64_t *) plasma_shared_alloc(plasma, 2*N, PlasmaComplexDouble);
if ( (TAU2 == NULL) || (V2 == NULL) ) {
plasma_error("PLASMA_zheevd", "plasma_shared_alloc() failed");
plasma_shared_free(plasma, TAU2);
plasma_shared_free(plasma, V2);
return PLASMA_ERR_OUT_OF_RESOURCES;
}
memset(TAU2, 0, 2*N*sizeof(PLASMA_Complex64_t));
memset(V2, 0, 2*N*sizeof(PLASMA_Complex64_t));
}
#if defined(ENABLE_TIMER)
timeblg = PLASMA_Wtime();
#endif
plasma_static_call_13(plasma_pzhetrd_hb2st_v1,
PLASMA_enum, blguplo,
int, N,
int, NB,
int, Vblksiz,
PLASMA_Complex64_t*, AB,
int, LDAB,
PLASMA_Complex64_t*, V2,
PLASMA_Complex64_t*, TAU2,
double*, W,
double*, E,
int, WANTZ,
PLASMA_sequence*, sequence,
PLASMA_request*, request);
/* WARNING: If plasma_pzhetrd_hb2st is implemented through a dynamic call, don't
* forget to synchronize */
plasma_dynamic_sync();
/*=======================================
* END of calling bulge chasing
*=======================================*/
#if defined(ENABLE_TIMER)
timeblg = PLASMA_Wtime()-timeblg;
printf(" Finish Bulge timing= %lf \n" ,timeblg);
timelpk = PLASMA_Wtime();
#endif
/*=======================================
* calling eigensolver
*=======================================*/
/* call eigensolver using lapack routine for our resulting tridiag [D E] */
plasma_setlapack_multithreads(plasma->world_size);
/*
status = LAPACKE_zstevd( LAPACK_COL_MAJOR, lapack_const(jobz), N, W, E, Q, LDQ );
*/
if(jobz == PlasmaNoVec){
status = LAPACKE_zstedc( LAPACK_COL_MAJOR, lapack_const(PlasmaNoVec),
N, W, E, Q, LDQ );
} else {
status = LAPACKE_zstedc( LAPACK_COL_MAJOR, lapack_const(PlasmaIvec),
N, W, E, Q, LDQ );
}
if(status != 0){
plasma_error("PLASMA_zstedc","ZSTEDC");
return status;
}
sequence->status = status;
plasma_setlapack_sequential(plasma);
/*=======================================
* END of calling eigensolver
*=======================================*/
#if defined(ENABLE_TIMER)
timelpk = PLASMA_Wtime()-timelpk;
printf(" Finish Eigensolver timing= %lf WANTZ %d threads %d\n" ,timelpk, WANTZ, plasma->world_size);
#endif
if (jobz == PlasmaVec){
/*=======================================
* apply Q2 from the bulge
*=======================================*/
/* compute T2 */
#if defined(ENABLE_TIMER)
timeT = PLASMA_Wtime();
#endif
plasma_static_call_8(plasma_pzlarft_blgtrd,
int, N,
int, NB,
int, Vblksiz,
PLASMA_Complex64_t*, V2,
PLASMA_Complex64_t*, T2,
PLASMA_Complex64_t*, TAU2,
PLASMA_sequence*, sequence,
PLASMA_request*, request);
#if defined(ENABLE_TIMER)
plasma_dynamic_sync();
timeT = PLASMA_Wtime()-timeT;
printf(" Finish compute T2 timing= %lf \n" ,timeT);
timeaplQ2 = PLASMA_Wtime();
#endif
/* apply Q2 from Left */
plasma_static_call_14(plasma_pzunmqr_blgtrd,
PLASMA_enum, PlasmaLeft,
PLASMA_enum, PlasmaNoTrans,
int, N,
int, NB,
int, N,
int, Vblksiz,
int, WANTZ,
PLASMA_Complex64_t*, V2,
PLASMA_Complex64_t*, T2,
PLASMA_Complex64_t*, TAU2,
PLASMA_Complex64_t*, Q,
int, LDQ,
PLASMA_sequence*, sequence,
PLASMA_request*, request);
#if defined(ENABLE_TIMER)
plasma_dynamic_sync();
timeaplQ2 = PLASMA_Wtime()-timeaplQ2;
printf(" Finish compute Q2 timing= %lf \n" ,timeaplQ2);
#endif
/*=======================================
* apply Q1 from the reduction to band
*=======================================*/
/* CASE NB>N, Q1 doesn't need to be applied, only bulge chasing has been done */
if( NB < N ){
#if defined(ENABLE_TIMER)
plasma_dynamic_sync();
timeconv1 = PLASMA_Wtime();
#endif
if ( PLASMA_TRANSLATION == PLASMA_OUTOFPLACE ) {
plasma_zooplap2tile( descQ, Q, NB, NB, LDQ, N, 0, 0, N, N, sequence, request, plasma_desc_mat_free(&(descQ)) );
}else {
plasma_ziplap2tile( descQ, Q, NB, NB, LDQ, N, 0, 0, N, N, sequence, request );
}
#if defined(ENABLE_TIMER)
timeconv1 = PLASMA_Wtime()-timeconv1;
timeaplQ1 = PLASMA_Wtime();
#endif
/* Accumulate the transformations from the first stage */
if(uplo==PlasmaLower){
plasma_dynamic_call_7(plasma_pzunmqr,
PLASMA_enum, PlasmaLeft,
PLASMA_enum, PlasmaNoTrans,
PLASMA_desc, plasma_desc_submatrix(descA, descA.mb, 0, descA.m-descA.mb, descA.n-descA.nb),
PLASMA_desc, plasma_desc_submatrix(descQ, descQ.mb, 0, descQ.m-descQ.mb, descQ.n),
PLASMA_desc, plasma_desc_submatrix(descT, descT.mb, 0, descT.m-descT.mb, descT.n-descT.nb),
PLASMA_sequence*, sequence,
PLASMA_request*, request);
}
else {
plasma_dynamic_call_7(plasma_pzunmlq,
PLASMA_enum, PlasmaLeft,
PLASMA_enum, PlasmaConjTrans,
PLASMA_desc, plasma_desc_submatrix(descA, 0, descA.nb, descA.m-descA.mb, descA.n-descA.nb),
PLASMA_desc, plasma_desc_submatrix(descQ, descQ.mb, 0, descQ.m-descQ.mb, descQ.n ),
PLASMA_desc, plasma_desc_submatrix(descT, 0, descT.nb, descT.m-descT.mb, descT.n-descT.nb),
PLASMA_sequence*, sequence,
PLASMA_request*, request);
}
#if defined(ENABLE_TIMER)
plasma_dynamic_sync();
timeaplQ1 = PLASMA_Wtime()-timeaplQ1;
printf(" Finish compute Q1 timing= %lf \n" ,timeaplQ1);
timeconv2 = PLASMA_Wtime();
#endif
if ( PLASMA_TRANSLATION == PLASMA_OUTOFPLACE ) {
plasma_zooptile2lap( descQ, Q, NB, NB, LDQ, N, sequence, request );
plasma_dynamic_sync();
plasma_desc_mat_free(&descQ);
} else {
plasma_ziptile2lap( descQ, Q, NB, NB, LDQ, N, sequence, request );
plasma_dynamic_sync();
}
#if defined(ENABLE_TIMER)
plasma_dynamic_sync();
timeconv2 = PLASMA_Wtime()-timeconv2;
printf(" Finish convert timing= %lf \n" ,timeconv1+timeconv2);
#endif
} /* END of ( NB < N ) */
}
#if defined(ENABLE_TIMER)
timeall = PLASMA_Wtime()-timeall;
printf(" Finish full eigenproblem threads %d N %d timeall= %lf \n", plasma->world_size, N, timeall);
#endif
if( jobz == PlasmaVec )
plasma_shared_free(plasma, T2);
plasma_shared_free(plasma, V2);
plasma_shared_free(plasma, TAU2);
plasma_shared_free(plasma, E);
plasma_shared_free(plasma, AB);
return PLASMA_SUCCESS;
}
| {
"alphanum_fraction": 0.5664106992,
"avg_line_length": 39.1048850575,
"ext": "c",
"hexsha": "fd9cacd5b0a8e0b795b1c05539eba3d989074546",
"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": "compute/zheevd.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": "compute/zheevd.c",
"max_line_length": 127,
"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": "compute/zheevd.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 7185,
"size": 27217
} |
/* See compilation notes in simple_cplx.c*/
#include "cplx.h" //gsl_cplx_from_c99; see below.
#include <gsl/gsl_blas.h> //gsl_blas_ddot
#include <gsl/gsl_complex_math.h> //gsl_complex_mul(_real)
gsl_vector_complex *cvec_dot_gslcplx(gsl_vector_complex *v, gsl_complex x){
gsl_vector_complex *out = gsl_vector_complex_alloc(v->size);
for (int i=0; i< v->size; i++)
gsl_vector_complex_set(out, i,
gsl_complex_mul(x, gsl_vector_complex_get(v, i)));
return out;
}
gsl_vector_complex *vec_dot_gslcplx(gsl_vector *v, gsl_complex x){
gsl_vector_complex *out = gsl_vector_complex_alloc(v->size);
for (int i=0; i< v->size; i++)
gsl_vector_complex_set(out, i,
gsl_complex_mul_real(x, gsl_vector_get(v, i)));
return out;
}
gsl_vector_complex *cvec_dot_c(gsl_vector_complex *v, complex double x){
return cvec_dot_gslcplx(v, gsl_cplx_from_c99(x));
}
gsl_vector_complex *vec_dot_c(gsl_vector *v, complex double x){
return vec_dot_gslcplx(v, gsl_cplx_from_c99(x));
}
complex double ddot (complex double x, complex double y){return x*y;}
void gsl_vector_complex_print(gsl_vector_complex *v){
for (int i=0; i< v->size; i++) {
gsl_complex x = gsl_vector_complex_get(v, i);
printf("%4g+%4gi%c", GSL_REAL(x), GSL_IMAG(x), i < v->size-1 ? '\t' : '\n');
}
}
| {
"alphanum_fraction": 0.6683417085,
"avg_line_length": 36.6578947368,
"ext": "c",
"hexsha": "7b183c39a38edec6dfff8511146603fa195a6548",
"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": "8ca2eefc7e8ea3170506a5698c3e5a3bff333de2",
"max_forks_repo_licenses": [
"Unlicense"
],
"max_forks_repo_name": "catalingheorghe/learning-activities",
"max_forks_repo_path": "progr/c/21st-century-c/21st-Century-Examples/complex.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "8ca2eefc7e8ea3170506a5698c3e5a3bff333de2",
"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": "catalingheorghe/learning-activities",
"max_issues_repo_path": "progr/c/21st-century-c/21st-Century-Examples/complex.c",
"max_line_length": 84,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "8ca2eefc7e8ea3170506a5698c3e5a3bff333de2",
"max_stars_repo_licenses": [
"Unlicense"
],
"max_stars_repo_name": "catalingheorghe/learning-activities",
"max_stars_repo_path": "progr/c/21st-century-c/21st-Century-Examples/complex.c",
"max_stars_repo_stars_event_max_datetime": "2022-03-10T11:24:07.000Z",
"max_stars_repo_stars_event_min_datetime": "2022-03-10T11:24:07.000Z",
"num_tokens": 401,
"size": 1393
} |
/**
* The interface to the binning and weight routines
*/
#ifndef _SPCE_BINNING_H
#define _SPCE_BINNING_H 1
#include <math.h>
#include <gsl/gsl_vector.h>
#include "spce_output.h"
#include "spc_trace_functions.h"
#include "aXe_grism.h"
#include "spc_spc.h"
/**
defines a pixel for weighting purposes. Here, p0, p1, p2, p3 are
the coordinates of the points where the square first contribute,
where its contribution becomes constant, where it slopes down again,
and where it doesn't contribute any more. For example, a pixel at (0,0)
viewed at from a side has p0=p1=0, p2=p3=1, whereas the same pixel
viewed from a corner has p0=-1, p1=p2=0, p3=1; slope is the
ascent on the non-constant parts, fmax the maximum contribution.
angle is the angle viewing. Its tangent tana or its cotangent
cota may be undefined for certain viewing angles. The function
weight_function is selected such that this is unimportatnt.
x0, y0, and size are the coordinates of the lower left corner and
the size of the square.
*/
typedef struct w_pixel_s
{
double p0, p1, p2, p3;
double angle;
double tana, cota;
double x0, y0, size;
double fmax, slope;
double (*weight_function) (const double x1, const double y1,
const double x2, const double y2,
const struct w_pixel_s * const pix);
}
w_pixel;
extern spectrum *
bin_naive (const ap_pixel * const ap_p, const double ob_width,
const double ob_orient, const int quant_cont);
extern spectrum *
bin_weighted (const ap_pixel * const ap_p, const double ob_orient,
const trace_func * const trace, const int n_sub,
const int flags);
extern spectrum *
bin_optimal (const ap_pixel * const ap_p, const beam curbeam,
const int quant_cont, const gsl_matrix *weights,
const drzstamp_dim dimension, gsl_matrix *coverage);
#endif
| {
"alphanum_fraction": 0.728308026,
"avg_line_length": 31.7931034483,
"ext": "h",
"hexsha": "12f4ed9222ffcf83e216e19cfa450dca4eb03548",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "sosey/pyaxe",
"max_forks_repo_path": "cextern/src/spce_binning.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "sosey/pyaxe",
"max_issues_repo_path": "cextern/src/spce_binning.h",
"max_line_length": 74,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "sosey/pyaxe",
"max_stars_repo_path": "cextern/src/spce_binning.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 499,
"size": 1844
} |
#include "simple_blas.h"
#ifdef ACCELERATE
#include <Accelerate/Accelerate.h>
#else
#include <cblas.h>
#include "lapack.h"
#endif
int to_cblas_transpose(const morpheus_transpose_e trans) {
switch (trans) {
case morpheus_no_trans:
return CblasNoTrans;
case morpheus_trans:
return CblasTrans;
}
return 0;
}
int to_cblas_layout(const morpheus_layout_e layout) {
switch (layout) {
case morpheus_row_major:
return CblasRowMajor;
case morpheus_col_major:
return CblasColMajor;
}
return 0;
}
void morpheus_dscal(const int n, const double alpha, double *x) {
const int inc = 1;
cblas_dscal(n, alpha, x, inc);
}
void morpheus_dcopy(const int n, const double *x, double *y) {
const int inc = 1;
cblas_dcopy(n, x, inc, y, inc);
}
void morpheus_dcopy_scalar(const int n, const double alpha, double *x) {
cblas_dcopy(n, &alpha, 0, x, 1);
}
void morpheus_dgemv(const morpheus_layout_e layout,
const morpheus_transpose_e trans,
const int nrows, const int ncols,
const double alpha, const double *A, const double *x,
const double beta, double *y) {
const int inc = 1;
const int lda = layout == morpheus_row_major ? ncols : nrows;
cblas_dgemv(to_cblas_layout(layout), to_cblas_transpose(trans), nrows, ncols,
alpha, A, lda, x, inc, beta, y, inc);
}
void morpheus_daxpy(const int n, const double alpha,
const double *x, double *y) {
const int inc = 1;
cblas_daxpy(n, alpha, x, inc, y, inc);
}
double morpheus_dnrm2(const int n, const double *x) {
const int inc = 1;
return cblas_dnrm2(n, x, inc);
}
double morpheus_ddot(const int n, const double *x, const double *y) {
const int inc = 1;
return cblas_ddot(n, x, inc, y, inc);
}
int morpheus_inverse(int n, double *x, int *pivot, double *workspace) {
workspace = workspace+n;
int lwork = n*n;
int rc;
dgetrf_(&n, &n, x, &n, pivot, &rc);
if (rc != 0) {
return rc;
}
dgetri_(&n, x, &n, pivot, workspace, &lwork, &rc);
return rc;
}
void morpheus_dger(const morpheus_layout_e layout,
const int nrows,
const int ncols,
const double alpha,
const double *x,
const double *y,
double *a) {
const int inc = 1;
const int lda = layout == morpheus_row_major ? ncols : nrows;
cblas_dger(to_cblas_layout(layout), nrows, ncols,
alpha, x, inc, y, inc, a, lda);
}
void morpheus_dgemm(const morpheus_layout_e layout,
const morpheus_transpose_e trans_a,
const morpheus_transpose_e trans_b,
const int m,
const int n,
const int k,
const double alpha,
const double *a,
const double *b,
const double beta,
double *c) {
int lda, ldb, ldc;
if (layout == morpheus_row_major) {
lda = trans_a == morpheus_no_trans ? k : m;
ldb = trans_b == morpheus_no_trans ? n : k;
ldc = n;
} else {
lda = trans_a == morpheus_no_trans ? m : k;
ldb = trans_b == morpheus_no_trans ? k : n;
ldc = m;
}
cblas_dgemm(to_cblas_layout(layout),
to_cblas_transpose(trans_a), to_cblas_transpose(trans_b),
m, n, k, alpha, a, lda, b, ldb, beta, c, ldc);
}
void morpheus_identity(const int n, double *a) {
const int m = n*n;
const double zero = 0;
const double one = 1;
cblas_dcopy(m, &zero, 0, a, 1);
cblas_dcopy(n, &one, 0, a, n+1);
}
| {
"alphanum_fraction": 0.5963227223,
"avg_line_length": 28.0307692308,
"ext": "c",
"hexsha": "5b443cc09062b265a1e5eeb9ad91483fd2f6aae9",
"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": "ee01b67441cb2e27abff4a025bd0be4a44762108",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "aligusnet/morpheus",
"max_forks_repo_path": "src/simple_blas.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "ee01b67441cb2e27abff4a025bd0be4a44762108",
"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": "aligusnet/morpheus",
"max_issues_repo_path": "src/simple_blas.c",
"max_line_length": 79,
"max_stars_count": 2,
"max_stars_repo_head_hexsha": "ee01b67441cb2e27abff4a025bd0be4a44762108",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "Alexander-Ignatyev/morpheus",
"max_stars_repo_path": "src/simple_blas.c",
"max_stars_repo_stars_event_max_datetime": "2019-01-14T11:30:47.000Z",
"max_stars_repo_stars_event_min_datetime": "2018-08-04T19:44:16.000Z",
"num_tokens": 1057,
"size": 3644
} |
#if !defined(fvSupport_h)
#define fvSupport_h
#include <petsc.h>
/**
* reproduces the petsc call with grad fixes for multiple fields
* @param dm
* @param fvm
* @param locX
* @param grad
* @return
*/
PETSC_EXTERN PetscErrorCode DMPlexGetDataFVM_MulfiField(DM dm, PetscFV fv, Vec *cellgeom, Vec *facegeom, DM *gradDM);
/**
* Check to make sure local ghost boundary have valid gradient values
*/
PETSC_EXTERN PetscErrorCode ABLATE_FillGradientBoundary(DM dm, PetscFV auxFvm, Vec localXVec, Vec gradLocalVec);
#endif | {
"alphanum_fraction": 0.7523809524,
"avg_line_length": 25,
"ext": "h",
"hexsha": "c63af99fc08c753a53641fadd4c25c49cbcd9c4a",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2020-12-22T14:16:59.000Z",
"max_forks_repo_forks_event_min_datetime": "2020-12-22T14:16:59.000Z",
"max_forks_repo_head_hexsha": "35ee9a30277908775a61d78462ea9724ee631a9b",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "mtmcgurn-buffalo/ablate",
"max_forks_repo_path": "ablateCore/flow/fvSupport.h",
"max_issues_count": 8,
"max_issues_repo_head_hexsha": "35ee9a30277908775a61d78462ea9724ee631a9b",
"max_issues_repo_issues_event_max_datetime": "2021-01-12T14:36:22.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-12-28T16:05:56.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "mtmcgurn-buffalo/ablate",
"max_issues_repo_path": "ablateCore/flow/fvSupport.h",
"max_line_length": 117,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "35ee9a30277908775a61d78462ea9724ee631a9b",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "mtmcgurn-buffalo/ablate",
"max_stars_repo_path": "ablateCore/flow/fvSupport.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 149,
"size": 525
} |
/* interpolation/bilinear.c
*
* Copyright 2012 David Zaslavsky
*
* 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_errno.h>
#include <gsl/gsl_interp.h>
#include <gsl/gsl_interp2d.h>
#define IDX2D(i, j, xsize, ysize) ((j) * (xsize) + (i))
static int
bilinear_init(void * state, const double xa[], const double ya[],
const double za[], size_t xsize, size_t ysize)
{
return GSL_SUCCESS;
}
static int
bilinear_eval(const void * state, const double xarr[], const double yarr[],
const double zarr[], size_t xsize, size_t ysize,
double x, double y, gsl_interp_accel * xa,
gsl_interp_accel * ya, double * z)
{
double xmin, xmax, ymin, ymax, zminmin, zminmax, zmaxmin, zmaxmax;
double dx, dy;
double t, u;
size_t xi, yi;
if (xa != NULL)
xi = gsl_interp_accel_find(xa, xarr, xsize, x);
else
xi = gsl_interp_bsearch(xarr, x, 0, xsize - 1);
if (ya != NULL)
yi = gsl_interp_accel_find(ya, yarr, ysize, y);
else
yi = gsl_interp_bsearch(yarr, y, 0, ysize - 1);
xmin = xarr[xi];
xmax = xarr[xi + 1];
ymin = yarr[yi];
ymax = yarr[yi + 1];
zminmin = zarr[IDX2D(xi, yi, xsize, ysize)];
zminmax = zarr[IDX2D(xi, yi + 1, xsize, ysize)];
zmaxmin = zarr[IDX2D(xi + 1, yi, xsize, ysize)];
zmaxmax = zarr[IDX2D(xi + 1, yi + 1, xsize, ysize)];
dx = xmax - xmin;
dy = ymax - ymin;
t = (x - xmin)/dx;
u = (y - ymin)/dy;
*z = (1.-t)*(1.-u)*zminmin + t*(1.-u)*zmaxmin + (1.-t)*u*zminmax + t*u*zmaxmax;
return GSL_SUCCESS;
}
static int
bilinear_deriv_x(const void * state, const double xarr[],
const double yarr[], const double zarr[],
size_t xsize, size_t ysize, double x, double y,
gsl_interp_accel * xa, gsl_interp_accel * ya, double * z_p)
{
double xmin, xmax, ymin, ymax, zminmin, zminmax, zmaxmin, zmaxmax;
double dx, dy;
double dt, u;
size_t xi, yi;
if (xa != NULL)
xi = gsl_interp_accel_find(xa, xarr, xsize, x);
else
xi = gsl_interp_bsearch(xarr, x, 0, xsize - 1);
if (ya != NULL)
yi = gsl_interp_accel_find(ya, yarr, ysize, y);
else
yi = gsl_interp_bsearch(yarr, y, 0, ysize - 1);
xmin = xarr[xi];
xmax = xarr[xi + 1];
ymin = yarr[yi];
ymax = yarr[yi + 1];
zminmin = zarr[IDX2D(xi, yi, xsize, ysize)];
zminmax = zarr[IDX2D(xi, yi + 1, xsize, ysize)];
zmaxmin = zarr[IDX2D(xi + 1, yi, xsize, ysize)];
zmaxmax = zarr[IDX2D(xi + 1, yi + 1, xsize, ysize)];
dx = xmax - xmin;
dy = ymax - ymin;
dt = 1./dx; /* partial t / partial x */
u = (y - ymin)/dy;
*z_p = dt*(-(1.-u)*zminmin + (1.-u)*zmaxmin - u*zminmax + u*zmaxmax);
return GSL_SUCCESS;
}
static int
bilinear_deriv_y(const void * state, const double xarr[],
const double yarr[], const double zarr[],
size_t xsize, size_t ysize, double x, double y,
gsl_interp_accel * xa, gsl_interp_accel * ya, double * z_p)
{
double xmin, xmax, ymin, ymax, zminmin, zminmax, zmaxmin, zmaxmax;
double dx, dy;
double t, du;
size_t xi, yi;
if (xa != NULL)
xi = gsl_interp_accel_find(xa, xarr, xsize, x);
else
xi = gsl_interp_bsearch(xarr, x, 0, xsize - 1);
if (ya != NULL)
yi = gsl_interp_accel_find(ya, yarr, ysize, y);
else
yi = gsl_interp_bsearch(yarr, y, 0, ysize - 1);
xmin = xarr[xi];
xmax = xarr[xi + 1];
ymin = yarr[yi];
ymax = yarr[yi + 1];
zminmin = zarr[IDX2D(xi, yi, xsize, ysize)];
zminmax = zarr[IDX2D(xi, yi + 1, xsize, ysize)];
zmaxmin = zarr[IDX2D(xi + 1, yi, xsize, ysize)];
zmaxmax = zarr[IDX2D(xi + 1, yi + 1, xsize, ysize)];
dx = xmax - xmin;
dy = ymax - ymin;
t = (x - xmin)/dx;
du = 1./dy; /* partial u / partial y */
*z_p = du*(-(1.-t)*zminmin - t*zmaxmin + (1.-t)*zminmax + t*zmaxmax);
return GSL_SUCCESS;
}
static int
bilinear_deriv2(const void * state, const double xarr[],
const double yarr[], const double zarr[],
size_t xsize, size_t ysize, double x, double y,
gsl_interp_accel * xa, gsl_interp_accel * ya, double * z_pp)
{
*z_pp = 0.0;
return GSL_SUCCESS;
}
static int
bilinear_derivxy(const void * state, const double xarr[],
const double yarr[], const double zarr[],
size_t xsize, size_t ysize, double x, double y,
gsl_interp_accel * xa, gsl_interp_accel * ya, double * z_pp)
{
double xmin, xmax, ymin, ymax, zminmin, zminmax, zmaxmin, zmaxmax;
double dx, dy;
double dt, du;
size_t xi, yi;
if (xa != NULL)
xi = gsl_interp_accel_find(xa, xarr, xsize, x);
else
xi = gsl_interp_bsearch(xarr, x, 0, xsize - 1);
if (ya != NULL)
yi = gsl_interp_accel_find(ya, yarr, ysize, y);
else
yi = gsl_interp_bsearch(yarr, y, 0, ysize - 1);
xmin = xarr[xi];
xmax = xarr[xi + 1];
ymin = yarr[yi];
ymax = yarr[yi + 1];
zminmin = zarr[IDX2D(xi, yi, xsize, ysize)];
zminmax = zarr[IDX2D(xi, yi + 1, xsize, ysize)];
zmaxmin = zarr[IDX2D(xi + 1, yi, xsize, ysize)];
zmaxmax = zarr[IDX2D(xi + 1, yi + 1, xsize, ysize)];
dx = xmax - xmin;
dy = ymax - ymin;
dt = 1./dx; /* partial t / partial x */
du = 1./dy; /* partial u / partial y */
*z_pp = dt*du*(zminmin-zmaxmin-zminmax+zmaxmax);
return GSL_SUCCESS;
}
static const gsl_interp2d_type bilinear_type = {
"bilinear",
2,
NULL,
&bilinear_init,
&bilinear_eval,
&bilinear_deriv_x,
&bilinear_deriv_y,
&bilinear_deriv2,
&bilinear_derivxy,
&bilinear_deriv2,
NULL
};
const gsl_interp2d_type * gsl_interp2d_bilinear = &bilinear_type;
#undef IDX2D
| {
"alphanum_fraction": 0.6231283848,
"avg_line_length": 29.4741784038,
"ext": "c",
"hexsha": "d6206cd8ae006181b81f486dc4e0ce6ea56e4173",
"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/interpolation/bilinear.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/interpolation/bilinear.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/interpolation/bilinear.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": 2142,
"size": 6278
} |
#ifndef PETSC4PY_COMPAT_H
#define PETSC4PY_COMPAT_H
#include <petsc.h>
#include "compat/mpi.h"
#include "compat/hdf5.h"
#include "compat/mumps.h"
#include "compat/hypre.h"
#include "compat/tao.h"
#endif/*PETSC4PY_COMPAT_H*/
| {
"alphanum_fraction": 0.7566371681,
"avg_line_length": 18.8333333333,
"ext": "h",
"hexsha": "d2113763e06f83b7c85386b2b79eca4ec08c07db",
"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": "fdfdd79be39b8cbe95cf57010f29a6cb2ef463a6",
"max_forks_repo_licenses": [
"BSD-2-Clause"
],
"max_forks_repo_name": "underworldcode/petsc4py",
"max_forks_repo_path": "src/include/compat.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "fdfdd79be39b8cbe95cf57010f29a6cb2ef463a6",
"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": "underworldcode/petsc4py",
"max_issues_repo_path": "src/include/compat.h",
"max_line_length": 27,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "fdfdd79be39b8cbe95cf57010f29a6cb2ef463a6",
"max_stars_repo_licenses": [
"BSD-2-Clause"
],
"max_stars_repo_name": "underworldcode/petsc4py",
"max_stars_repo_path": "src/include/compat.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 69,
"size": 226
} |
#include <pygsl/solver.h>
#include <pygsl/utils.h>
#include <gsl/gsl_odeiv.h>
static const char odeiv_step_type_name [] = "Odeiv-Step";
static const char odeiv_control_type_name[] = "Odeiv-Control";
static const char odeiv_evolve_type_name [] = "Odeiv-Evolve";
const char * filename = __FILE__;
PyObject *module = NULL;
struct _mycontrol{
gsl_odeiv_control *control;
gsl_odeiv_step *step;
PyGSL_solver *step_ob;
};
typedef struct _mycontrol mycontrol;
struct _myevolve{
gsl_odeiv_evolve *evolve;
gsl_odeiv_control *control;
gsl_odeiv_step *step;
PyGSL_solver *control_ob;
PyGSL_solver *step_ob;
};
typedef struct _myevolve myevolve;
void
_mycontrol_free(mycontrol *c)
{
FUNC_MESS_BEGIN();
gsl_odeiv_control_free(c->control);
if(c->step_ob){
DEBUG_MESS(3, "Decreasing step @ %p refcont %d", c->step_ob,
c->step_ob->ob_refcnt);
Py_DECREF(c->step_ob);
}else{
DEBUG_MESS(3, "Freeing GSL Step @ %p", c->step);
gsl_odeiv_step_free(c->step);
}
memset(c, 0, sizeof(mycontrol));
free(c);
c = NULL;
FUNC_MESS_END();
}
void
_myevolve_free(myevolve *c)
{
FUNC_MESS_BEGIN();
gsl_odeiv_evolve_free(c->evolve);
if(c->control_ob){
DEBUG_MESS(3, "Decreasing control @ %p refcont %d", c->control_ob,
c->control_ob->ob_refcnt);
Py_DECREF(c->control_ob);
}else{
DEBUG_MESS(3, "Freeing GSL Control @ %p", c->control);
gsl_odeiv_control_free(c->control);
}
if(c->step_ob){
DEBUG_MESS(3, "Decreasing step @ %p refcont %d", c->step_ob,
c->step_ob->ob_refcnt);
Py_DECREF(c->step_ob);
}else{
DEBUG_MESS(3, "Freeing GSL Step @ %p", c->step);
gsl_odeiv_step_free(c->step);
}
memset(c, 0, sizeof(myevolve));
free(c);
c = NULL;
FUNC_MESS_END();
}
const char *
PyGSL_mycontrol_getname(void *v)
{
mycontrol *c = (mycontrol *) v;
return gsl_odeiv_control_name(c->control);
}
#define _PyGSL_ODEIV_GENERIC_CHECK(ob, type_desc) \
((PyGSL_solver_check((ob))) && (((PyGSL_solver *)ob)->mstatic->type_name == (type_desc)))
#define PyGSL_ODEIV_STEP_Check(ob) _PyGSL_ODEIV_GENERIC_CHECK((ob), odeiv_step_type_name)
#define PyGSL_ODEIV_CONTROL_Check(ob) _PyGSL_ODEIV_GENERIC_CHECK((ob), odeiv_control_type_name)
#define PyGSL_ODEIV_EVOLVE_Check(ob) _PyGSL_ODEIV_GENERIC_CHECK((ob), odeiv_evolve_type_name)
static const char *this_file = __FILE__;
static char odeiv_step_init_err_msg[] = "odeiv_step.__init__";
static char odeiv_step_apply_doc[] = "XXX Documentation missing\n";
static char odeiv_step_order_doc[] = "XXX Documentation missing\n";
static char odeiv_control_hadjust_doc[] = "XXX Documentation missing\n";
static char odeiv_evolve_apply_doc[] = "XXX Documentation missing\n";
static char PyGSL_odeiv_step_doc[] = "XXX Documentation missing\n";
static char PyGSL_odeiv_control_doc[] = "XXX Documentation missing\n";
static char PyGSL_odeiv_evolve_doc[] = "XXX Documentation missing\n";
/*---------------------------------------------------------------------------
Wrapper functions to push call the approbriate Python Objects
---------------------------------------------------------------------------*/
static int
PyGSL_odeiv_func(double t, const double y[], double f[], void *params)
{
int dimension, flag = GSL_FAILURE;
PyObject *arglist = NULL, *result = NULL;
PyArrayObject *yo = NULL;
PyGSL_solver * step;
gsl_vector_view yv, fv;
PyGSL_error_info info;
FUNC_MESS_BEGIN();
step = (PyGSL_solver *) params;
if(!PyGSL_ODEIV_STEP_Check(step)){
PyGSL_add_traceback(module, this_file, __FUNCTION__,
__LINE__ - 2);
pygsl_error("Param not a step type!",
this_file, __LINE__ -2, GSL_EFAULT);
goto fail;
}
dimension = step->problem_dimensions[0];
/* Do I need to copy the array ??? */
yv = gsl_vector_view_array((double *) y, dimension);
yo = PyGSL_copy_gslvector_to_pyarray(&yv.vector);
if (yo == NULL) goto fail;
FUNC_MESS("\t\tBuild args");
arglist = Py_BuildValue("(dOO)", t, yo, step->args);
FUNC_MESS("\t\tEnd Build args");
info.callback = step->cbs[0];
info.message = "odeiv_func";
result = PyEval_CallObject(step->cbs[0], arglist);
if((flag = PyGSL_CHECK_PYTHON_RETURN(result, 1, &info)) != GSL_SUCCESS){
goto fail;
}
info.argnum = 1;
fv = gsl_vector_view_array(f, dimension);
if((flag = PyGSL_copy_pyarray_to_gslvector(&fv.vector, result, dimension,
&info)) != GSL_SUCCESS){
goto fail;
}
Py_DECREF(arglist); arglist = NULL;
Py_DECREF(yo); yo = NULL;
Py_DECREF(result); result = NULL;
FUNC_MESS_END();
return GSL_SUCCESS;
fail:
FUNC_MESS(" IN Fail BEGIN");
Py_XDECREF(yo);
Py_XDECREF(result);
Py_XDECREF(arglist);
assert(flag != GSL_SUCCESS);
FUNC_MESS(" IN Fail END");
if(step->isset)
longjmp(step->buffer, flag);
return flag;
}
static int
PyGSL_odeiv_jac(double t, const double y[], double *dfdy, double dfdt[],
void *params)
{
int dimension, flag = GSL_FAILURE;
PyGSL_solver *step;
PyGSL_error_info info;
PyObject *arglist = NULL, *result = NULL, *tmp=NULL;
PyArrayObject *yo = NULL;
gsl_vector_view yv, dfdtv;
gsl_matrix_view dfdyv;
FUNC_MESS_BEGIN();
step = (PyGSL_solver *) params;
if(!PyGSL_ODEIV_STEP_Check(step)){
PyGSL_add_traceback(module, this_file, __FUNCTION__,
__LINE__ - 2);
pygsl_error("Param not a step type!",
this_file, __LINE__ -2, GSL_EFAULT);
goto fail;
}
dimension = step->problem_dimensions[0];
yv = gsl_vector_view_array((double *) y, dimension);
yo = PyGSL_copy_gslvector_to_pyarray(&yv.vector);
if (yo == NULL) goto fail;
arglist = Py_BuildValue("(dOO)", t, yo, step->args);
result = PyEval_CallObject(step->cbs[1], arglist);
info.callback = step->cbs[1];
info.message = "odeiv_jac";
if((flag = PyGSL_CHECK_PYTHON_RETURN(result, 2, &info)) != GSL_SUCCESS){
goto fail;
}
info.argnum = 1;
tmp = PyTuple_GET_ITEM(result, 0);
dfdyv = gsl_matrix_view_array((double *) dfdy, dimension, dimension);
if((flag = PyGSL_copy_pyarray_to_gslmatrix(&dfdyv.matrix, tmp, dimension, dimension, &info)) != GSL_SUCCESS){
goto fail;
}
info.argnum = 2;
tmp = PyTuple_GET_ITEM(result, 1);
dfdtv = gsl_vector_view_array((double *) dfdt, dimension);
if((flag = PyGSL_copy_pyarray_to_gslvector(&dfdtv.vector, tmp, dimension, &info)) != GSL_SUCCESS){
goto fail;
}
Py_DECREF(arglist); arglist = NULL;
Py_DECREF(result); result = NULL;
Py_DECREF(yo); yo = NULL;
FUNC_MESS_END();
return GSL_SUCCESS;
fail:
FUNC_MESS("IN Fail");
assert(flag != GSL_SUCCESS);
longjmp(step->buffer, flag);
return flag;
}
/* Wrappers for the evaluation of the system */
static PyObject *
PyGSL_odeiv_step_apply(PyGSL_solver *self, PyObject *args)
{
PyObject *result = NULL;
PyObject *y0_o = NULL, *dydt_in_o = NULL;
PyArrayObject *volatile y0 = NULL, * volatile yerr = NULL,
*volatile dydt_in = NULL, *volatile dydt_out = NULL,
*volatile yout = NULL;
double t=0, h=0, *volatile dydt_in_d;
int r, flag;
PyGSL_array_index_t dimension;
FUNC_MESS_BEGIN();
assert(PyGSL_ODEIV_STEP_Check(self));
if(! PyArg_ParseTuple(args, "ddOOO", &t, &h, &y0_o, &dydt_in_o)){
return NULL;
}
dimension = self->problem_dimensions[0];
y0 = PyGSL_vector_check(y0_o, dimension, PyGSL_DARRAY_CINPUT(1), NULL, NULL);
if(y0 == NULL) goto fail;
if (Py_None == dydt_in_o){
dydt_in_d = NULL;
}else{
dydt_in = PyGSL_vector_check(dydt_in_o, dimension, PyGSL_DARRAY_CINPUT(2), NULL, NULL);
if(dydt_in == NULL) goto fail;
dydt_in_d = (double *) dydt_in->data;
}
dydt_out = PyGSL_New_Array(1, &dimension, PyArray_DOUBLE);
if (dydt_out == NULL) goto fail;
yerr = PyGSL_New_Array(1, &dimension, PyArray_DOUBLE);
if(yerr == NULL) goto fail;
yout = (PyArrayObject *) PyGSL_Copy_Array(y0);
if(yout == NULL) goto fail;
self->isset = 0;
if((flag=setjmp(self->buffer)) == 0){
FUNC_MESS("\t\t Setting Jmp Buffer");
self->isset = 1;
} else {
FUNC_MESS("\t\t Returning from Jmp Buffer");
self->isset = 0;
goto fail;
}
r = gsl_odeiv_step_apply(self->solver, t, h,
(double *) yout->data,
(double *) yerr->data,
dydt_in_d,
(double *) dydt_out->data,
((gsl_odeiv_system *)self->c_sys));
self->isset = 0;
if (GSL_SUCCESS != r){
PyErr_SetString(PyExc_TypeError, "Error While evaluating gsl_odeiv");
goto fail;
}
FUNC_MESS(" Returnlist create ");
assert(yout != NULL);
assert(yerr != NULL);
assert(dydt_out != NULL);
result = Py_BuildValue("(OOO)", yout, yerr, dydt_out);
FUNC_MESS(" Memory free ");
/* Deleting the arrays */
Py_DECREF(y0); y0 = NULL;
Py_DECREF(yout); yout = NULL;
Py_DECREF(yerr); yerr = NULL;
Py_DECREF(dydt_out); dydt_out = NULL;
/* This array does not need to exist ... */
Py_XDECREF(dydt_in); dydt_in=NULL;
FUNC_MESS_END();
return result;
fail:
FUNC_MESS("IN Fail");
self->isset = 0;
Py_XDECREF(y0);
Py_XDECREF(yout);
Py_XDECREF(yerr);
Py_XDECREF(dydt_in);
Py_XDECREF(dydt_out);
FUNC_MESS("IN Fail End");
return NULL;
}
static PyObject *
PyGSL_odeiv_control_hadjust(PyGSL_solver *self, PyObject *args)
{
PyObject *result = NULL;
PyObject *y0_o = NULL, *yerr_o = NULL, *dydt_o = NULL;
PyArrayObject *y0 = NULL, *yerr = NULL, *dydt = NULL;
double h = 0;
int r = 0;
mycontrol *c;
PyGSL_array_index_t dimension = 0;
FUNC_MESS_BEGIN();
assert(PyGSL_ODEIV_CONTROL_Check(self));
if(!PyArg_ParseTuple(args, "OOOd", &y0_o, &yerr_o, &dydt_o, &h)){
return NULL;
}
dimension = self->problem_dimensions[0];
y0 = PyGSL_vector_check(y0_o, dimension, PyGSL_DARRAY_CINPUT(1), NULL, NULL);
if(y0 == NULL) goto fail;
yerr = PyGSL_vector_check(yerr_o, dimension, PyGSL_DARRAY_CINPUT(2), NULL, NULL);
if(yerr == NULL) goto fail;
dydt = PyGSL_vector_check(dydt_o, dimension, PyGSL_DARRAY_CINPUT(3), NULL, NULL);
if(dydt == NULL) goto fail;
FUNC_MESS(" Array Pointers End");
c = (mycontrol *) self->solver;
r = gsl_odeiv_control_hadjust(c->control, c->step,
(double *) y0->data,
(double *) yerr->data,
(double *) dydt->data, &h);
FUNC_MESS(" Function End");
Py_DECREF(y0); y0 = NULL;
Py_DECREF(yerr); yerr = NULL;
Py_DECREF(dydt); dydt = NULL;
result = Py_BuildValue("di",h,r);
FUNC_MESS_END();
return result;
fail:
FUNC_MESS("IN Fail");
Py_XDECREF(y0);
Py_XDECREF(yerr);
Py_XDECREF(dydt);
FUNC_MESS("IN Fail END");
return NULL;
}
static PyObject *
PyGSL_odeiv_evolve_apply(PyGSL_solver *self, PyObject *args)
{
PyObject *result = NULL;
PyObject *y0_o = NULL, *myargs = NULL;
PyArrayObject *volatile y0 = NULL, *volatile yout = NULL;
myevolve *e = NULL;
double t=0, h=0, t1 = 0, flag;
int dimension = self->problem_dimensions[0], r;
assert(PyGSL_ODEIV_EVOLVE_Check(self));
FUNC_MESS_BEGIN();
if(!PyArg_ParseTuple(args, "dddOO", &t, &t1, &h, &y0_o, &myargs)){
return NULL;
}
DEBUG_MESS(3, "y0_o @ %p", y0_o);
y0 = PyGSL_vector_check(y0_o, dimension, PyGSL_DARRAY_CINPUT(1), NULL, NULL);
if(y0 == NULL) goto fail;
yout = (PyArrayObject *) PyGSL_Copy_Array(y0);
if(yout == NULL) goto fail;
e = (myevolve *) self->solver;
if((flag=setjmp(e->step_ob->buffer)) == 0){
e->step_ob->isset = 1;
FUNC_MESS("\t\t Setting Jmp Buffer");
} else {
FUNC_MESS("\t\t Returning from Jmp Buffer");
e->step_ob->isset = 0;
goto fail;
}
DEBUG_MESS(3, "evolve @ %p\t control @ %p\t step @ %p", e, e->control, e->step);
r = gsl_odeiv_evolve_apply(e->evolve,
e->control,
e->step,
e->step_ob->c_sys, &t, t1, &h,
(double * )yout->data);
e->step_ob->isset = 0;
if (GSL_SUCCESS != r){
goto fail;
}
assert(yout != NULL);
result = Py_BuildValue("(ddO)", t, h, yout);
/* Deleting the arrays */
Py_DECREF(yout); yout = NULL;
Py_DECREF(y0); y0=NULL;
FUNC_MESS_END();
return result;
fail:
FUNC_MESS("IN Fail");
e->step_ob->isset = 0;
PyGSL_add_traceback(module, this_file, odeiv_step_init_err_msg, __LINE__);
Py_XDECREF(y0);
Py_XDECREF(yout);
FUNC_MESS("IN Fail End");
return NULL;
}
GETINT(odeiv_step_order)
static struct PyMethodDef PyGSL_odeiv_step_methods[] = {
{"apply", (PyCFunction) PyGSL_odeiv_step_apply, METH_VARARGS, odeiv_step_apply_doc},
{"order", (PyCFunction) PyGSL_odeiv_step_order, METH_VARARGS, odeiv_step_order_doc},
{NULL, NULL}
};
static struct PyMethodDef PyGSL_odeiv_control_methods[] = {
{"hadjust", (PyCFunction) PyGSL_odeiv_control_hadjust, METH_VARARGS, odeiv_control_hadjust_doc},
{NULL, NULL}
};
static struct PyMethodDef PyGSL_odeiv_evolve_methods[] = {
{"apply", (PyCFunction) PyGSL_odeiv_evolve_apply, METH_VARARGS, odeiv_evolve_apply_doc},
{NULL, NULL}
};
static const struct _SolverStatic
_StepMethods = {{(void_m_t) gsl_odeiv_step_free,
(void_m_t) gsl_odeiv_step_reset,
(name_m_t) gsl_odeiv_step_name,
(int_m_t) NULL},
3, PyGSL_odeiv_step_methods, odeiv_step_type_name},
_ControlMethods = {{(void_m_t) _mycontrol_free,
(void_m_t) NULL,
(name_m_t) PyGSL_mycontrol_getname,
(int_m_t) NULL},
3, PyGSL_odeiv_control_methods, odeiv_control_type_name},
_EvolveMethods = {{(void_m_t) _myevolve_free,
(void_m_t) gsl_odeiv_evolve_reset,
(name_m_t) NULL,
(int_m_t) NULL,},
3, PyGSL_odeiv_evolve_methods, odeiv_evolve_type_name};
static PyObject *
PyGSL_odeiv_step_init(PyObject *self, PyObject *args, PyObject *kwdict, const gsl_odeiv_step_type * odeiv_type)
{
PyObject *func=NULL, *jac=NULL, *o_params=NULL;
PyGSL_solver *solver = NULL;
static char * kwlist[] = {"dimension", "func", "jac", "args", NULL};
int dim, has_jacobian = 0;
gsl_odeiv_system * c_sys;
solver_alloc_struct s = {odeiv_type, (void_an_t) gsl_odeiv_step_alloc,
&_StepMethods};
FUNC_MESS_BEGIN();
assert(args);
if (0 == PyArg_ParseTupleAndKeywords(args, kwdict, "iOOO:odeiv_step.__init__", kwlist,
&dim, &func, &jac, &o_params)){
PyGSL_add_traceback(module, this_file, odeiv_step_init_err_msg, __LINE__ - 2);
return NULL;
}
if (dim <= 0){
PyGSL_add_traceback(module, this_file, odeiv_step_init_err_msg, __LINE__ - 1);
pygsl_error("The dimension of the problem must be at least 1",
this_file, __LINE__ -2, GSL_EDOM);
return NULL;
}
if(!PyCallable_Check(func)){
PyGSL_add_traceback(module, this_file, odeiv_step_init_err_msg, __LINE__ - 1);
pygsl_error("The function object is not callable!",
this_file, __LINE__ -2, GSL_EBADFUNC);
goto fail;
}
if(jac == Py_None){
if(odeiv_type == gsl_odeiv_step_bsimp){
PyGSL_add_traceback(module, this_file, odeiv_step_init_err_msg, __LINE__ - 1);
pygsl_error("The bsimp method needs a jacobian! You supplied None.",
this_file, __LINE__ -2, GSL_EBADFUNC);
goto fail;
}
}else{
if(!PyCallable_Check(jac)){
PyGSL_add_traceback(module, this_file, odeiv_step_init_err_msg, __LINE__ - 1);
pygsl_error("The jacobian object must be None or callable!",
this_file, __LINE__ -2, GSL_EBADFUNC);
goto fail;
}
has_jacobian = 1;
}
solver = (PyGSL_solver *) PyGSL_solver_dn_init(self, args, &s, 3);
if(solver == NULL){
goto fail;
}
DEBUG_MESS(3, "solver @ %p", solver);
solver->solver = gsl_odeiv_step_alloc(odeiv_type, dim);
if(solver->solver == NULL){
goto fail;
}
DEBUG_MESS(3, "step @ %p", solver->solver);
c_sys = (gsl_odeiv_system *)calloc(1, sizeof(gsl_odeiv_system));
if(c_sys == NULL){
PyErr_NoMemory();
goto fail;
}
/* Need for cleanup in fail : */
solver->c_sys = c_sys;
DEBUG_MESS(3, "c_sys @ %p", solver->c_sys);
solver->problem_dimensions[0] = dim;
if(has_jacobian){
c_sys->jacobian = PyGSL_odeiv_jac;
if(!PyCallable_Check(jac))
goto fail;
solver->cbs[1] = jac;
}else{
c_sys->jacobian = NULL;
solver->cbs[1] = NULL;
}
c_sys->function = PyGSL_odeiv_func;
if(!PyCallable_Check(func))
goto fail;
solver->cbs[0] = func;
c_sys->params = (void *) solver;
DEBUG_MESS(3, "params @ %p", c_sys->params);
Py_INCREF(solver->cbs[0]);
Py_XINCREF(solver->cbs[1]);
Py_XINCREF(solver->args);
solver->args = o_params;
Py_INCREF(solver->args);
FUNC_MESS_END();
return (PyObject *) solver;
fail:
FUNC_MESS("FAIL");
Py_XDECREF(solver);
return NULL;
}
#define ADD_ODESTEPPER(mytype) \
static PyObject * \
PyGSL_odeiv_step_init_ ## mytype (PyObject * self, PyObject * args, PyObject *kwdic) \
{ \
return PyGSL_odeiv_step_init(self, args, kwdic, gsl_odeiv_step_ ## mytype); \
}
ADD_ODESTEPPER(rk2)
ADD_ODESTEPPER(rk4)
ADD_ODESTEPPER(rkf45)
ADD_ODESTEPPER(rkck)
ADD_ODESTEPPER(rk8pd)
ADD_ODESTEPPER(rk2imp)
ADD_ODESTEPPER(rk4imp)
ADD_ODESTEPPER(bsimp)
ADD_ODESTEPPER(gear1)
ADD_ODESTEPPER(gear2)
static PyObject *
PyGSL_odeiv_control_init(PyObject *self, PyObject *args, void * type)
{
int nargs = -1, tmp=0;
double eps_abs, eps_rel, a_y, a_dydt;
PyGSL_solver *step=NULL, *solver=NULL;
mycontrol * c;
gsl_odeiv_control *(*evaluator_5)(double , double , double , double ) = NULL;
gsl_odeiv_control *(*evaluator_3)(double , double ) = NULL;
solver_alloc_struct s = {type, (void_an_t) gsl_odeiv_control_alloc,
&_ControlMethods};
FUNC_MESS_BEGIN();
/* The arguments depend on the type of control */
if(type == (void *) gsl_odeiv_control_standard_new){
/* step, eps_abs, eps_rel, a_y, a_dydt */
nargs = 5;
}else if(type == (void *) gsl_odeiv_control_y_new ||
type == (void *) gsl_odeiv_control_yp_new){
nargs = 3;
}else{
PyGSL_add_traceback(module, this_file, odeiv_step_init_err_msg,
__LINE__ - 2);
pygsl_error("Unknown control type",
this_file, __LINE__ -2, GSL_EFAULT);
goto fail;
}
assert(nargs > -1);
switch(nargs){
case 5:
tmp == PyArg_ParseTuple(args, "Odddd:odeiv_control.__init__",
&step, &eps_abs, &eps_rel, &a_y, &a_dydt);
break;
case 3:
tmp == PyArg_ParseTuple(args, "Odd:odeiv_control.__init__",
&step, &eps_abs, &eps_rel);
break;
default:
fprintf(stderr, "nargs = %d\n", nargs);
pygsl_error("Unknown number of arguments",
this_file, __LINE__ -2, GSL_EFAULT);
goto fail; break;
}
if(!PyGSL_ODEIV_STEP_Check(step)){
int flag;
flag = PyGSL_solver_check(step);
DEBUG_MESS(3, "is solver? %d, %p %p ", flag, PyGSL_API[PyGSL_solver_type_NUM], step->ob_type);
if(flag){
DEBUG_MESS(3, "solver = %s, %p != %p", step->mstatic->type_name, step->mstatic->type_name,
odeiv_step_type_name);
pygsl_error("First argument must be a step solver!", __FILE__, __LINE__, GSL_EINVAL);
}
goto fail;
}
if(tmp){
PyGSL_add_traceback(module, this_file, odeiv_step_init_err_msg,
__LINE__ - 2);
return NULL;
}
solver = (PyGSL_solver *) PyGSL_solver_dn_init(self, args, &s, 3);
if (NULL == solver){
PyErr_NoMemory();
goto fail;
}
c = calloc(1, sizeof(mycontrol));
if(c == NULL){
PyErr_NoMemory();
goto fail;
}
solver->solver = c;
switch(nargs){
case 5:
evaluator_5 = type;
c->control = evaluator_5(eps_abs, eps_rel, a_y, a_dydt);
break;
case 3:
evaluator_3 = type;
c->control = evaluator_3(eps_abs, eps_rel);
break;
default:
goto fail;
}
if (NULL == c->control){
PyErr_NoMemory();
goto fail;
}
DEBUG_MESS(3, "c->control @ %p", c->control);
c->step = step->solver;
c->step_ob = step;
Py_INCREF(step);
FUNC_MESS_END();
return (PyObject *) solver;
fail:
FUNC_MESS("FAIL");
Py_XDECREF(solver);
return NULL;
}
#define ADD_ODECONTROL(name) \
static PyObject * \
PyGSL_odeiv_control_init_ ## name (PyObject * self, PyObject * args) \
{ \
return PyGSL_odeiv_control_init(self, args, (void *) gsl_odeiv_control_ ## name); \
}
ADD_ODECONTROL(standard_new)
ADD_ODECONTROL(y_new)
ADD_ODECONTROL(yp_new)
static PyObject *
PyGSL_odeiv_evolve_init(PyObject *self, PyObject *args)
{
PyGSL_solver *step, *control, *a_ev = NULL;
myevolve *e;
solver_alloc_struct s = {NULL, (void_an_t) gsl_odeiv_evolve_alloc,
&_EvolveMethods};
/* step, control */
FUNC_MESS_BEGIN();
if(0== PyArg_ParseTuple(args, "OO:odeiv_evolve.__init__",
&step, &control)){
return NULL;
}
if(!PyGSL_ODEIV_STEP_Check(step)){
pygsl_error("First argument must be a step solver!", __FILE__, __LINE__, GSL_EINVAL);
goto fail;
}
if(!PyGSL_ODEIV_CONTROL_Check(control)){
pygsl_error("Second argument must be a control solver!", __FILE__, __LINE__, GSL_EINVAL);
goto fail;
}
a_ev = (PyGSL_solver *) PyGSL_solver_dn_init(self, args, &s, 3);
if(NULL == a_ev){
PyErr_NoMemory();
return NULL;
}
a_ev->problem_dimensions[0] = step->problem_dimensions[0];
e = (myevolve *) calloc(1, sizeof(myevolve));
if(e == NULL){
PyErr_NoMemory();
goto fail;
}
a_ev->solver = e;
e->step_ob = step;
e->control_ob = control;
Py_INCREF(step);
Py_INCREF(control);
e->step = step->solver;
e->control = ((mycontrol *)control->solver)->control;
e->evolve = gsl_odeiv_evolve_alloc(step->problem_dimensions[0]);
if(NULL == e->evolve){
PyErr_NoMemory();
goto fail;
}
FUNC_MESS_END();
return (PyObject *) a_ev;
fail:
FUNC_MESS("FAIL");
Py_XDECREF(a_ev);
return NULL;
}
static const char PyGSL_odeiv_module_doc [] = "XXX Missing ";
static PyMethodDef mMethods[] = {
{"step_rk2", (PyCFunction)PyGSL_odeiv_step_init_rk2, METH_VARARGS|METH_KEYWORDS, PyGSL_odeiv_step_doc},
{"step_rk4", (PyCFunction)PyGSL_odeiv_step_init_rk4, METH_VARARGS|METH_KEYWORDS, PyGSL_odeiv_step_doc},
{"step_rkf45", (PyCFunction)PyGSL_odeiv_step_init_rkf45, METH_VARARGS|METH_KEYWORDS, PyGSL_odeiv_step_doc},
{"step_rkck", (PyCFunction)PyGSL_odeiv_step_init_rkck, METH_VARARGS|METH_KEYWORDS, PyGSL_odeiv_step_doc},
{"step_rk8pd", (PyCFunction)PyGSL_odeiv_step_init_rk8pd, METH_VARARGS|METH_KEYWORDS, PyGSL_odeiv_step_doc},
{"step_rk2imp", (PyCFunction)PyGSL_odeiv_step_init_rk2imp, METH_VARARGS|METH_KEYWORDS, PyGSL_odeiv_step_doc},
{"step_rk4imp", (PyCFunction)PyGSL_odeiv_step_init_rk4imp, METH_VARARGS|METH_KEYWORDS, PyGSL_odeiv_step_doc},
{"step_bsimp", (PyCFunction)PyGSL_odeiv_step_init_bsimp, METH_VARARGS|METH_KEYWORDS, PyGSL_odeiv_step_doc},
{"step_gear1", (PyCFunction)PyGSL_odeiv_step_init_gear1, METH_VARARGS|METH_KEYWORDS, PyGSL_odeiv_step_doc},
{"step_gear2", (PyCFunction)PyGSL_odeiv_step_init_gear2, METH_VARARGS|METH_KEYWORDS, PyGSL_odeiv_step_doc},
{"control_standard_new", PyGSL_odeiv_control_init_standard_new, METH_VARARGS, PyGSL_odeiv_control_doc},
{"control_y_new", PyGSL_odeiv_control_init_y_new, METH_VARARGS, PyGSL_odeiv_control_doc},
{"control_yp_new", PyGSL_odeiv_control_init_yp_new, METH_VARARGS, PyGSL_odeiv_control_doc},
{"evolve", PyGSL_odeiv_evolve_init, METH_VARARGS, PyGSL_odeiv_evolve_doc},
{NULL, NULL, 0, NULL}
};
void
initodeiv(void)
{
PyObject* m, *dict, *item;
FUNC_MESS_BEGIN();
m=Py_InitModule("odeiv", 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*)PyGSL_odeiv_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;
}
FUNC_MESS_END();
fail:
FUNC_MESS("FAIL");
return;
}
| {
"alphanum_fraction": 0.6365717895,
"avg_line_length": 29.1831797235,
"ext": "c",
"hexsha": "e715ed590649947cb660df5c62c6f1c53c550c45",
"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/odeiv.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/odeiv.c",
"max_line_length": 114,
"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/odeiv.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 7658,
"size": 25331
} |
#include <stdio.h>
#include <gsl_rng.h>
#include <gsl_randist.h>
int main(int argv, char* argc[])
{
// Regression test for https://github.com/conda-forge/ipopt-feedstock/issues/57
gsl_rng *r = gsl_rng_alloc(gsl_rng_mt19937);
if (r == NULL)
{
return 1;
}
gsl_rng_free(r);
return 0;
}
| {
"alphanum_fraction": 0.6516129032,
"avg_line_length": 16.3157894737,
"ext": "c",
"hexsha": "a1ca035d596f65e4cda83659bb0fbd9937309588",
"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": "7ecbeb17ea5b98c7483c349c01eab5c6bdf1a25f",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "hmaarrfk/gsl-feedstock",
"max_forks_repo_path": "recipe/test/regression_test.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "7ecbeb17ea5b98c7483c349c01eab5c6bdf1a25f",
"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": "hmaarrfk/gsl-feedstock",
"max_issues_repo_path": "recipe/test/regression_test.c",
"max_line_length": 81,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "7ecbeb17ea5b98c7483c349c01eab5c6bdf1a25f",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "hmaarrfk/gsl-feedstock",
"max_stars_repo_path": "recipe/test/regression_test.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 98,
"size": 310
} |
#pragma once
#include <memory>
#include <gsl/span>
#include "D3DManager.h"
namespace vrutil
{
class OverlayItem
{
class OverlayItemImpl *m_impl;
OverlayItem(class OverlayItemImpl *impl);
public:
~OverlayItem();
static std::shared_ptr<OverlayItem> Create(uint64_t handle);
void ProcessEvents();
void SetTexture(const ComPtr<ID3D11Texture2D> &texture);
void SetSharedHandle(void *handle);
void SetOverlayWidthInMeters(float meter);
void Show();
void SetMatrix34(const float *matrix34);
};
using OverlayItemPtr = std::shared_ptr<OverlayItem>;
} // namespace vrutil
| {
"alphanum_fraction": 0.7009493671,
"avg_line_length": 23.4074074074,
"ext": "h",
"hexsha": "3aab4be071c3fd1f1f0b0137df46213c5576e0da",
"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": "6116b91403393f2f7747c3da902b29612b0ce20a",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "ousttrue/VROverlaySample",
"max_forks_repo_path": "vrutil/OverlayItem.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "6116b91403393f2f7747c3da902b29612b0ce20a",
"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": "ousttrue/VROverlaySample",
"max_issues_repo_path": "vrutil/OverlayItem.h",
"max_line_length": 65,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "6116b91403393f2f7747c3da902b29612b0ce20a",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "ousttrue/VROverlaySample",
"max_stars_repo_path": "vrutil/OverlayItem.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 152,
"size": 632
} |
/* cdf/cdf_beta.c
*
* Copyright (C) 2003 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
*/
#include <config.h>
#include <math.h>
#include <gsl/gsl_cdf.h>
#include <gsl/gsl_sf_gamma.h>
#include <gsl/gsl_math.h>
#include "beta_inc.c"
double
gsl_cdf_beta_P (const double x, const double a, const double b)
{
double P;
if (x <= 0.0 )
{
return 0.0;
}
if ( x >= 1.0 )
{
return 1.0;
}
P = beta_inc_AXPY (1.0, 0.0, a, b, x);
return P;
}
double
gsl_cdf_beta_Q (const double x, const double a, const double b)
{
double Q;
if ( x >= 1.0)
{
return 0.0;
}
if ( x <= 0.0 )
{
return 1.0;
}
Q = beta_inc_AXPY (-1.0, 1.0, a, b, x);
return Q;
}
| {
"alphanum_fraction": 0.6476868327,
"avg_line_length": 20.9701492537,
"ext": "c",
"hexsha": "524391da14e0bffcc75c8bf49943acafc1f22e69",
"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/cdf/beta.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/cdf/beta.c",
"max_line_length": 77,
"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/cdf/beta.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": 430,
"size": 1405
} |
#include <unistd.h>
#include <stdio.h>
#include <gsl/gsl_math.h>
int main (void) {
for ( ; ; ) {
double x = 5.0;
double y = gsl_expm1(100.0);
printf ("J0(%g) = %.18e\n", x, y);
sleep(2);
}
return 0;
} | {
"alphanum_fraction": 0.5109170306,
"avg_line_length": 17.6153846154,
"ext": "c",
"hexsha": "72ae3c469244727eb15fc374ec840ced3ab125b7",
"lang": "C",
"max_forks_count": 25,
"max_forks_repo_forks_event_max_datetime": "2021-09-26T16:19:29.000Z",
"max_forks_repo_forks_event_min_datetime": "2018-01-26T23:31:18.000Z",
"max_forks_repo_head_hexsha": "60933a2fc8ddd62df813f5f928142ec949619ac1",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "gbudigiri/k8-scalar",
"max_forks_repo_path": "studies/WOC2020/experiments/0-experiment-sharedlibraries/reproductie/test.c",
"max_issues_count": 4,
"max_issues_repo_head_hexsha": "60933a2fc8ddd62df813f5f928142ec949619ac1",
"max_issues_repo_issues_event_max_datetime": "2022-03-08T21:11:14.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-04-23T20:46:51.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "gbudigiri/k8-scalar",
"max_issues_repo_path": "studies/WOC2020/experiments/0-experiment-sharedlibraries/reproductie/test.c",
"max_line_length": 38,
"max_stars_count": 10,
"max_stars_repo_head_hexsha": "60933a2fc8ddd62df813f5f928142ec949619ac1",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "gbudigiri/k8-scalar",
"max_stars_repo_path": "studies/WOC2020/experiments/0-experiment-sharedlibraries/reproductie/test.c",
"max_stars_repo_stars_event_max_datetime": "2021-01-13T10:00:04.000Z",
"max_stars_repo_stars_event_min_datetime": "2018-09-02T14:59:52.000Z",
"num_tokens": 85,
"size": 229
} |
#ifndef SCALING_H_SAL4XICS
#define SCALING_H_SAL4XICS
#include <algorithm>
#include <gsl/gsl>
#include <type_traits>
#include <utility>
namespace sens_loc::math {
/// This class is a small wrapper to clarify the mathematical notation
/// of ranges. It does NOT distinguish between \f$[min, max)\f$,
/// \f$[min, max]\f$, \f$(min, max)\f$.
/// \tparam Real underlying type of the range, integer type for example
/// \warning this struct does not ensure that \p min is always smaller \p max.
template <typename Real>
struct numeric_range {
static_assert(std::is_arithmetic_v<Real>);
Real min; ///< lower bound of the range
Real max; ///< uppoer bound of the range
};
/// This function scales \p value from the range \p source_range to the
/// new range \p target_range.
/// \note \p value is clamped to \p source_range
/// \pre the ranges are well formed (\p min is smaller \p max)
/// \returns the scaled value that is clamped to \p target_range.
template <typename Real>
inline constexpr Real scale(const numeric_range<Real>& source_range,
const numeric_range<Real>& target_range,
Real value) noexcept {
static_assert(std::is_arithmetic_v<Real>);
Expects(source_range.min < source_range.max);
Expects(target_range.min < target_range.max);
const Real clamped = std::clamp(value, source_range.min, source_range.max);
Ensures(clamped <= source_range.max);
Ensures(clamped >= source_range.min);
const Real scaled =
((target_range.max - target_range.min) * (value - source_range.min)) /
(source_range.max - source_range.min) +
target_range.min;
const Real target_clamped =
std::clamp(scaled, target_range.min, target_range.max);
Ensures(target_clamped <= target_range.max);
Ensures(target_clamped >= target_range.min);
return target_clamped;
}
} // namespace sens_loc::math
#endif /* end of include guard: SCALING_H_SAL4XICS */
| {
"alphanum_fraction": 0.6824290692,
"avg_line_length": 34.0508474576,
"ext": "h",
"hexsha": "46acabd53ffa1abf917485df0420cbe23c99183a",
"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/scaling.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/scaling.h",
"max_line_length": 79,
"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/scaling.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": 480,
"size": 2009
} |
#pragma once
#include <halley/maths/vector2.h>
#include <halley/maths/rect.h>
#include <memory>
#include <halley/resources/resource.h>
#include <halley/text/halleystring.h>
#include <halley/data_structures/hash_map.h>
#include <gsl/span>
#include "halley/maths/vector4.h"
namespace Halley
{
class Resources;
class Serializer;
class Deserializer;
class ResourceDataStatic;
class Texture;
class ResourceLoader;
class SpriteSheetEntry
{
public:
Vector2f pivot;
Vector2i origPivot;
Vector2f size;
Rect4f coords;
Vector4s trimBorder;
Vector4s slices;
int duration = 0;
bool rotated = false;
bool sliced = false;
void serialize(Serializer& s) const;
void deserialize(Deserializer& s);
};
class SpriteSheetFrameTag
{
public:
String name;
int from = 0;
int to = 0;
void serialize(Serializer& s) const;
void deserialize(Deserializer& s);
};
class SpriteSheet : public Resource
{
public:
const std::shared_ptr<const Texture>& getTexture() const;
const SpriteSheetEntry& getSprite(const String& name) const;
const SpriteSheetEntry& getSprite(size_t idx) const;
const std::vector<SpriteSheetFrameTag>& getFrameTags() const;
std::vector<String> getSpriteNames() const;
size_t getSpriteCount() const;
size_t getIndex(const String& name) const;
bool hasSprite(const String& name) const;
void loadJson(gsl::span<const gsl::byte> data);
void addSprite(String name, const SpriteSheetEntry& sprite);
void setTextureName(String name);
static std::unique_ptr<SpriteSheet> loadResource(ResourceLoader& loader);
constexpr static AssetType getAssetType() { return AssetType::SpriteSheet; }
void reload(Resource&& resource) override;
void serialize(Serializer& s) const;
void deserialize(Deserializer& s);
private:
Resources* resources = nullptr;
mutable std::shared_ptr<const Texture> texture;
std::vector<SpriteSheetEntry> sprites;
HashMap<String, uint32_t> spriteIdx;
std::vector<SpriteSheetFrameTag> frameTags;
String textureName;
void loadTexture(Resources& resources) const;
};
class SpriteResource : public Resource
{
public:
SpriteResource(std::shared_ptr<const SpriteSheet> spriteSheet, size_t idx);
const SpriteSheetEntry& getSprite() const;
size_t getIdx() const;
std::shared_ptr<const SpriteSheet> getSpriteSheet() const;
constexpr static AssetType getAssetType() { return AssetType::Sprite; }
static std::unique_ptr<SpriteResource> loadResource(ResourceLoader& loader);
void reload(Resource&& resource) override;
private:
std::weak_ptr<const SpriteSheet> spriteSheet;
size_t idx = -1;
};
}
| {
"alphanum_fraction": 0.750668194,
"avg_line_length": 24.9428571429,
"ext": "h",
"hexsha": "e429f20d36398a085be99c78e3c9570bb958c084",
"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": "fc4f153956cc34d7fa02b76850e22183b8e30e25",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "sunhay/halley",
"max_forks_repo_path": "src/engine/core/include/halley/core/graphics/sprite/sprite_sheet.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "fc4f153956cc34d7fa02b76850e22183b8e30e25",
"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": "sunhay/halley",
"max_issues_repo_path": "src/engine/core/include/halley/core/graphics/sprite/sprite_sheet.h",
"max_line_length": 78,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "fc4f153956cc34d7fa02b76850e22183b8e30e25",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "sunhay/halley",
"max_stars_repo_path": "src/engine/core/include/halley/core/graphics/sprite/sprite_sheet.h",
"max_stars_repo_stars_event_max_datetime": "2019-11-27T20:23:45.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-11-27T20:23:45.000Z",
"num_tokens": 649,
"size": 2619
} |
/**
* \file matrix.h
* \brief a template class to describe the Matrix
* \author wbd
*
* This class implements the template matrix. It contains the array "data" to
* hold the matrix elements.
* The matrix can be initialize with the matrix_initializer_list
* (a.k, recursive initializer_list).
* For example:
* Matrix<float, 2> amat {{1,2}, {2, 4}};
* The matrix can also initialize with the MatrixShape and the initialize value.
* For example:
* Matrix<float 2> bmat({2,2}, 0);
*
*/
#ifndef MATRIX_H_
#define MATRIX_H_
#include <iostream>
#include <fstream>
#include <cblas.h>
#include <cstring>
#include <iomanip>
#include <memory>
#include <initializer_list>
#include <type_traits>
#include <array>
#include "expr.h"
#include "matrix_shape.h"
#include "sub_matrix.h"
//#define DEBUG
namespace matrix {
// ============================================================================
// recursive initializer_list for Matrix Class
template<typename DataType, size_t N>
struct MatrixInit {
using type = std::initializer_list<typename MatrixInit<DataType, N-1>::type>;
};
template<typename DataType>
struct MatrixInit<DataType, 1> {
using type = std::initializer_list<DataType>;
};
template<typename DataType>
struct MatrixInit<DataType, 0> ;
template<typename DataType, size_t N>
using matrix_initializer_list = typename MatrixInit<DataType, N>::type;
template<typename DataType, size_t N>
class Matrix : public ExprBase<Matrix<DataType, N>, DataType> {
public:
/**
* default constructor
*/
Matrix()
: data(nullptr),
stride(size_t(0)),
capicity(size_t(0)),
row(size_t(0)),
column(size_t(0)) {
}
;
/**
* constructor with matrix shape and initial value
* @param s is shape of matrix
* @param n is initial value for the elements in the matrix
*/
inline Matrix(const MatrixShape<N> &s, const DataType n);
/**
* constructor with matrix shape, stride and initial value
* @param s is shape of the matrix
* @param st is stride for each row of the multi-array(Note that: change the shape[N-1] memeory )
* @param n is initial value for the elements in the matrix
*/
inline Matrix(const MatrixShape<N> &s, const size_t st, const DataType n);
/**
* copy constructor
* @param m is another matrix to be cloned to this matrix
*/
inline Matrix(const Matrix<DataType, N> &m);
/**
* copy assignment
* @param m is another matrix to be cloned to this matrix
* @return the matrix that has copied data from another matrix
*/
inline Matrix<DataType, N> & operator =(const Matrix<DataType, N> &m);
/**
* copy constructor from SubMatrix
* @param m is the submatrix to be cloned to this matrix
*/
inline Matrix(const SubMatrix<DataType, N> &m);
/**
* copy assignment from SubMatrix
* @param m is another submatrix to be cloned to this matrix
* @return the matrix that has copied data from another matrix
*/
inline Matrix<DataType, N> & operator =(const SubMatrix<DataType, N> &m);
/**
* move constructor
* @param m is another matrix to be moved to this matrix
*/
inline Matrix(Matrix<DataType, N> &&m);
/**
* move assignment operator
* @param m is matrix to be moved to this matrix
* @return the matrix that has gotten data from another matrix
*/
inline Matrix<DataType, N> & operator =(Matrix<DataType, N> &&m);
/**
* constructor with matrix_initializer_list
* @param t is initializer_list for the matrix
*/
inline Matrix(matrix_initializer_list<DataType, N> t);
/**
* assignment operator with matrix_initializer_list
* @param t is initializer_list for the matrix
* @return the matrix that has filled the data with the initializer_list
*/
inline Matrix & operator =(matrix_initializer_list<DataType, N> t);
template<typename T>
inline Matrix(std::initializer_list<T> t) = delete;
template<typename T>
inline Matrix & operator =(std::initializer_list<T> t) = delete;
/**
* de-constructor: delete the array
*/
~Matrix() {
#ifdef DEBUG
std::cout<<"decons!!!!!!!!!!!!!!!!!!!!" << this << std::endl;
#endif
delete[] data;
}
/**
* index operation for the matrix
* @param i is the index
* @return a SubMatrix Object which is refer to some elements in the Matrix Object
*/
inline SubMatrix<DataType, N - 1> operator[](size_t i) const;
inline SubMatrix<DataType, N - 1> operator[](size_t i);
/**
* slice function for the matrix
* @param i is the start index
* @param j is the end index
* @return a SubMatrix Object which is refer to some elements in the Matrix Object
*/
inline SubMatrix<DataType, N> slice(size_t i, size_t j) const;
inline SubMatrix<DataType, N> slice(size_t i, size_t j);
/**
* Scalar add Operator
* @param n is the scalar added to matrix
* @return the matrix in which the elements are all added the scalar value
*/
inline Matrix<DataType, N> & operator +=(const DataType & n);
/**
* Scalar sub Operator
* @param n is the scalar subscribed to matrix
* @return the matrix in which the elements are all subscribed the scalar value
*/
inline Matrix<DataType, N> & operator -=(const DataType & n);
/**
* Scalar multiply Operator
* @param n is the scalar multiplied to matrix
* @return the matrix in which the elements are all multiplied the scalar value
*/
inline Matrix<DataType, N> & operator *=(const DataType & n);
/**
* Scalar devision Operator
* @param n is the scalar divided to matrix
* @return the matrix in which the elements are all devided the scalar value
*/
inline Matrix<DataType, N> & operator /=(const DataType & n);
/**
* add Operator
* @param t is the matrix added to this matrix
* @return the matrix in which the elements: m1(i,j) += m2(i,j)
*/
inline Matrix<DataType, N> & operator +=(const Matrix<DataType, N> & t);
/**
* sub Operator
* @param t is the matrix subscribed to this matrix
* @return the matrix in which the elements: m1(i,j) -= m2(i,j)
*/
inline Matrix<DataType, N> & operator -=(const Matrix<DataType, N> & t);
/**
* multiply Operator
* @param t is the matrix multiplied to this matrix
* @return the matrix in which the elements: m1(i,j) *= m2(i,j)
*/
inline Matrix<DataType, N> & operator *=(const Matrix<DataType, N> & t);
/**
* division opertor
* @param t is the matrix divided to this matrix
* @return the matrix in which the elements: m1(i,j) /= m2(i,j)
*/
inline Matrix<DataType, N>& operator /=(const Matrix<DataType, N> & t);
/**
* Assign Operator
* @param e is the right matrix object or a scalar
* @return the result matrix
*/
template<typename SubType>
inline Matrix<DataType, N>& operator=(const ExprBase<SubType, DataType> &e);
/**
* get the basic element in index (i,j)
* @param i is the row index
* @param j is the column index
* @return the element in the index(i,j)
*/
inline DataType eval(size_t i, size_t j) const;
inline void set_row_ele(int i, const Matrix<DataType, N> & s);
/**
* get the column size
* @return the column size
*/
inline size_t getColumn() const {
return column;
}
/**
* get the row size
* @return the row size
*/
inline size_t getRow() const {
return row;
}
/**
* get the capicity of the matrix
* @return the capicity of the matrix
*/
inline size_t getCapicity() const {
return capicity;
}
/**
* get the memory length for the matrix
* @return the capicity of the matrix
*/
inline int get_capicity() const;
/**
* get the number of the elemments in the matrix
* @return the matrix elements number
*/
inline int get_size() const;
/**
* get the length of the shape
* @param s is the shape object
* @param stride is the row length
* @return the length of the shape with the stride
*/
inline size_t get_length(const MatrixShape<N> &s, size_t stride) const;
/**
* @return the pointer to the data of the matrix
*/
inline DataType * get_data() {
return data;
}
/**
* @return the pointer to the data of the matrix
*/
inline DataType * get_data() const {
return data;
}
//private:
MatrixShape<N> shape;
size_t stride;
size_t capicity;
DataType * data;
size_t row;
size_t column;
};
//=============================================================================
/**
* One-dimension Matrix Class
* For example:
* Matrix<float, 1> m {1,2,3,4}
* support operator [], such as m[0].
*/
template<typename DataType>
class Matrix<DataType, 1> : public ExprBase<Matrix<DataType, 1>, DataType> {
public:
Matrix()
: data(nullptr),
stride(size_t(0)) {
}
;
inline Matrix(const MatrixShape<1> &s, const DataType n);
inline Matrix(const MatrixShape<1> &s, const size_t st, const DataType n);
inline Matrix(const Matrix<DataType, 1> &m);
inline Matrix<DataType, 1> & operator =(const Matrix<DataType, 1> &m);
inline Matrix(const SubMatrix<DataType, 1> &m);
inline Matrix<DataType, 1> & operator =(const SubMatrix<DataType, 1> &m);
inline Matrix(Matrix<DataType, 1> &&m);
inline Matrix<DataType, 1> & operator =(Matrix<DataType, 1> &&m);
inline Matrix(matrix_initializer_list<DataType, 1> t);
inline Matrix & operator =(matrix_initializer_list<DataType, 1> t);
~Matrix() {
delete[] data;
}
inline int get_capicity() const;
inline int get_size() const;
inline size_t get_length(const MatrixShape<1> &s, size_t stride) const;
inline DataType * get_data() {
return data;
}
inline DataType * get_data() const {
return data;
}
inline const DataType & operator[](size_t i) const;
inline DataType & operator[](size_t i);
inline SubMatrix<DataType, 1> slice(size_t i, size_t j) const;
inline SubMatrix<DataType, 1> slice(size_t i, size_t j);
inline Matrix<DataType, 1> & operator +=(const DataType & n);
inline Matrix<DataType, 1> & operator -=(const DataType & n);
inline Matrix<DataType, 1> & operator *=(const DataType & n);
inline Matrix<DataType, 1> & operator /=(const DataType & n);
inline Matrix<DataType, 1> & operator +=(const Matrix<DataType, 1> & t);
inline Matrix<DataType, 1> & operator -=(const Matrix<DataType, 1> & t);
inline Matrix<DataType, 1> & operator *=(const Matrix<DataType, 1> & t);
inline Matrix<DataType, 1>& operator /=(const Matrix<DataType, 1> & t);
template<typename SubType>
inline Matrix<DataType, 1>& operator=(const ExprBase<SubType, DataType> &e);
inline DataType eval(size_t i, size_t j) const;
inline void set_row_ele(int i, const Matrix<DataType, 1> & s);
inline size_t getColumn() const {
return column;
}
inline size_t getRow() const {
return row;
}
inline size_t getCapicity() const {
return capicity;
}
//private:
MatrixShape<1> shape;
size_t stride;
size_t capicity;
DataType * data;
size_t row;
size_t column;
};
//=============================================================================
//matrix operation for two dimensional Matrix and SubMatrix
// matrix multiplication operator
// overload equal Operator
// Ruturn true if all elements in the matrix is equal and stride is equal
template<typename DataType, size_t N>
inline bool operator==(const Matrix<DataType, N>& m1,
const Matrix<DataType, N>& m2) {
DataType * d1 = m1.data;
DataType * d2 = m2.data;
if (m1.get_size() != m2.get_size())
return false;
for (int i = 0; i < m1.get_size(); ++i) {
if (d1[i] != d2[i])
return false;
}
return true;
}
template<typename DataType, size_t N>
inline bool operator==(const SubMatrix<DataType, N>& m1,
const Matrix<DataType, N>& m2) {
DataType * d1 = m1.data;
DataType * d2 = m2.data;
if (m1.get_size() != m2.get_size())
return false;
for (int i = 0; i < m1.get_size(); ++i) {
if (d1[i] != d2[i])
return false;
}
return true;
}
template<typename DataType, size_t N>
inline bool operator==(const Matrix<DataType, N>& m1,
const SubMatrix<DataType, N>& m2) {
DataType * d1 = m1.data;
DataType * d2 = m2.data;
if (m1.get_size() != m2.get_size())
return false;
for (int i = 0; i < m1.get_size(); ++i) {
if (d1[i] != d2[i])
return false;
}
return true;
}
template<typename DataType, size_t N>
inline bool operator==(const SubMatrix<DataType, N>& m1,
const SubMatrix<DataType, N>& m2) {
DataType * d1 = m1.data;
DataType * d2 = m2.data;
if (m1.get_size() != m2.get_size())
return false;
for (int i = 0; i < m1.get_size(); ++i) {
if (d1[i] != d2[i])
return false;
}
return true;
}
} //namespace matrix
#ifdef MATRIX_SCALAR_TYPE_
#error "MATRIX_SCALAR_TYPE_ Should not be defined!"
#endif
#define MATRIX_SCALAR_TYPE_ float
#include "expr-inl.h"
#undef MATRIX_SCALAR_TYPE_
#define MATRIX_SCALAR_TYPE_ double
#include "expr-inl.h"
#undef MATRIX_SCALAR_TYPE_
#define MATRIX_SCALAR_TYPE_ int
#include "expr-inl.h"
#undef MATRIX_SCALAR_TYPE_
#include "matrix-inl.h"
#include "sub_matrix-inl.h"
#include "matrix_math.h"
#include "random.h"
#endif // MATRIX_MATRIX_H
| {
"alphanum_fraction": 0.6514212277,
"avg_line_length": 29.0725274725,
"ext": "h",
"hexsha": "ce633147b928863ba46c2946a8d67150241f295c",
"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": "35655f925f687382f9d141c5f43dc392170507df",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "seaslee/snoopy",
"max_forks_repo_path": "snoopy/matrix/matrix.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "35655f925f687382f9d141c5f43dc392170507df",
"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": "seaslee/snoopy",
"max_issues_repo_path": "snoopy/matrix/matrix.h",
"max_line_length": 99,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "35655f925f687382f9d141c5f43dc392170507df",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "seaslee/snoopy",
"max_stars_repo_path": "snoopy/matrix/matrix.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 3520,
"size": 13228
} |
#include <stdio.h>
#include "sweeny_uf.h"
#include <ctype.h>
#include <strings.h>
#include <stdio.h>
#include "../src/uf.h"
#include "../src/queue.h"
#include <math.h>
#include <gsl/gsl_rng.h> //Verwendung von Mersenne-Twister Pseudozufallszahlengenerator
static __s8 dN;
#define MIN(a,b) a <= b ? a: b
#define MAX(a,b) a >= b? a: b
static char setup=0;
static char verbose=0;
static double rcWeights[4]; // array with precalculated mc weights
static double p_min_del,p_max_del, p_min_ins,p_max_ins;
static struct queue collect1,collect2;
static struct queue_node *todo_pool, *collect_pool;
static __u32 offset_1=1,offset_2=2;
static __u64 *sec_cs_moment,*four_cs_moment;
static __u32 *size_giant;
static __u32 *num_bonds;
static __u32 *num_cluster;
static __u32 DX;
static __u32 N;
static __u32 seed;
static double q;
static double coupling;
static double beta;
static double v;
static double K;
static __u32 steps;
static __s8 *bonds;
static gsl_rng * r;
static __u32 edge[2];
static __s32 adj1[4];
static __s32 adj2[4];
static __s32 *uf1;
static __u32 cs1,cs2;
static __u32 activeEdges=0;
static __u32 cutoff;
/******************************************************************************
*****************************************************************************/
static char init(void)
{
K=coupling*beta;
v = exp(K) - 1.0;
N = DX*DX;
rcWeights[0] = MIN(pow(v,-1),1); //db==-1,dN==0
rcWeights[1] = MIN(pow(v,-1)*q,1); //db==-1,dN=1
rcWeights[2] = MIN(v,1); //db==1,dN==0
rcWeights[3] = MIN(v*pow(q,-1),1); //db==1,dN==-1
p_min_del = MIN(rcWeights[0],rcWeights[1]);
p_max_del = MAX(rcWeights[0],rcWeights[1]);
p_min_ins = MIN(rcWeights[2],rcWeights[3]);
p_max_ins = MAX(rcWeights[2],rcWeights[3]);
if(verbose) {
printf("p_min_del = %f\n",p_min_del);
printf("p_max_del = %f\n",p_max_del);
printf("p_min_ins = %f\n",p_min_ins);
printf("p_max_ins = %f\n",p_max_ins);
}
r = gsl_rng_alloc(gsl_rng_mt19937);
if(!r)
return 0;
gsl_rng_set(r,seed);
__u32 i;
uf1 = initUF(N);
todo_pool = malloc(N*sizeof(struct queue_node));
if(!todo_pool) {
return 0;
}
collect_pool = malloc(N*sizeof(struct queue_node));
if(!collect_pool) {
return 0;
}
for(i=0;i<N;++i) {
collect_pool[i].next = todo_pool[i].next = NULL;
collect_pool[i].data = todo_pool[i].data= i;
collect_pool[i].visited = todo_pool[i].visited = 0;
}
bonds = malloc(sizeof(*bonds)*2*N);
if(!bonds) {
return 0;
}
for(i=0;i<2*N;i++) bonds[i] = -1;
return 1;
}
/******************************************************************************
*****************************************************************************/
static void destroy(void)
{
destroyUF(uf1);
free(bonds);
gsl_rng_free(r);
free(collect_pool);
free(todo_pool);
}
/******************************************************************************
*****************************************************************************/
static inline __u32 ltcXnext(__u32 idx)
{
if((idx+1) % DX)
return idx+1;
else
return idx +1- DX ;
}
/******************************************************************************
*****************************************************************************/
static inline __u32 ltcXprev(__u32 idx)
{
if((idx%DX))
return idx-1;
else
return idx + DX -1;
}
/******************************************************************************
*****************************************************************************/
static inline __u32 ltcYnext(__u32 idx)
{
if(idx <= N -1 && idx >= N - DX)
return idx +DX- N ;
else
return idx+DX;
}
/******************************************************************************
*****************************************************************************/
static inline __u32 ltcYprev(__u32 idx)
{
if(idx <= DX - 1)
return idx + N - DX;
else
return idx - DX;
}
/******************************************************************************
*****************************************************************************/
static void Adjacent(__u32 bidx)
{
if(bidx%2) {
bidx = (bidx -1)/2;
edge[0] = bidx;
edge[1] = ltcXnext(bidx);
}
else {
bidx = bidx/2;
edge[0] = bidx;
edge[1] = ltcYprev(bidx);
}
}
/******************************************************************************
*****************************************************************************/
static void Adjacent2(__u32 idx, __u8 a) {
if(a == 1)
{
if(bonds[2*idx] == 1) adj1[0] = ltcYprev(idx);
else adj1[0] = -1;
if(bonds[(2*idx)+1] == 1) adj1[1] = ltcXnext(idx);
else adj1[1] = -1;
if(bonds[2*ltcYnext(idx)] == 1) adj1[2] = ltcYnext(idx);
else adj1[2] = -1;
if(bonds[(2*ltcXprev(idx))+1] ==1)adj1[3] = ltcXprev(idx);
else adj1[3] = -1;
}
else {
if(bonds[2*idx] == 1)adj2[0] = ltcYprev(idx);
else adj2[0] = -1;
if(bonds[(2*idx)+1] == 1)adj2[1] = ltcXnext(idx);
else adj2[1] = -1;
if(bonds[2*ltcYnext(idx)] == 1) adj2[2] = ltcYnext(idx);
else adj2[2] = -1;
if(bonds[(2*ltcXprev(idx))+1] == 1)adj2[3] = ltcXprev(idx);
else adj2[3] = -1;
}
}
/******************************************************************************
*****************************************************************************/
static __u8 breadthFirstSearch(__u32 start, __u32 goal,__u8 accept_split)
{
static struct queue todo1,todo2;
__u32 i=0,activeP1=0,activeP2=0;
init_queue(&todo1,todo_pool);
init_queue(&todo2,todo_pool);
init_queue(&collect1,collect_pool);
init_queue(&collect2,collect_pool);
cs1=0;
cs2=0;
enqueue(&todo1,start); // Put starting point onto queue 1
enqueue(&collect1,start);
cs1++; // Increase cluster size of bfs 1
collect_pool[start].visited = offset_1;
enqueue(&todo2,goal); // Put goal point onto queue 2
enqueue(&collect2,goal);
collect_pool[goal].visited = offset_2;
cs2++; // increase cluster size of bfs 2
while(!queue_empty_p(&todo1) && !queue_empty_p(&todo2)) {
dequeue(&todo2,&activeP2); // get next vertex of bfs 2
Adjacent2(activeP2,2); // get all adjacent vertices of current vertex
for(i=0;i<4;i++) {
if(adj2[i] != -1) { // if accessable (edge exists)
if(collect_pool[adj2[i]].visited == offset_2) continue; // already visited
if((__u32)adj2[i] == start || collect_pool[adj2[i]].visited == offset_1) { // reconnected
while(!queue_empty_p(&todo1)) dequeue(&todo1,&activeP1); // empty queue 1
while(!queue_empty_p(&todo2)) dequeue(&todo2,&activeP2); // empty queue 2
while(!queue_empty_p(&collect1)) dequeue(&collect1,&activeP1);
while(!queue_empty_p(&collect2)) dequeue(&collect2,&activeP2);
offset_1+=2;
offset_2+=2;
return 1; // 1 indicates success
}
enqueue(&todo2,adj2[i]);
enqueue(&collect2,adj2[i]);
collect_pool[adj2[i]].visited = offset_2; // mark as visited
cs2++; // increase cluster size
}
}
dequeue(&todo1,&activeP1);
Adjacent2(activeP1,1);
for(i=0;i<4;i++) {
if(adj1[i] != -1) {
if(collect_pool[adj1[i]].visited == offset_1) continue;
if((__u32)adj1[i] == goal || collect_pool[adj1[i]].visited == offset_2) {
while(!queue_empty_p(&todo1)) dequeue(&todo1,&activeP1);
while(!queue_empty_p(&todo2)) dequeue(&todo2,&activeP2);
while(!queue_empty_p(&collect1)) dequeue(&collect1,&activeP1);
while(!queue_empty_p(&collect2)) dequeue(&collect2,&activeP2);
offset_1+=2;
offset_2+=2;
return 1;
}
enqueue(&todo1,adj1[i]);
enqueue(&collect1,adj1[i]);
collect_pool[adj1[i]].visited = offset_1;
cs1++;
}
}
}
/* Only if a deletion of a cutting edge has to be accepted,
* completely traverse the unfinished cluster to
* be able to update the UF datastructure afterwards based on
* the collect1 and collect2 queues.
*/
if(accept_split) {
while(!queue_empty_p(&todo1)) {
dequeue(&todo1,&activeP1);
Adjacent2(activeP1,1);
for(i=0;i<4;i++) {
if(adj1[i] != -1) {
if(collect_pool[adj1[i]].visited == offset_1) continue;
enqueue(&todo1,adj1[i]);
enqueue(&collect1,adj1[i]);
collect_pool[adj1[i]].visited = offset_1;
cs1++;
}
}
}
while(!queue_empty_p(&todo2)) {
dequeue(&todo2,&activeP2);
Adjacent2(activeP2,2);
for(i=0;i<4;i++) {
if(adj2[i] != -1) {
if(collect_pool[adj2[i]].visited == offset_2) continue;
enqueue(&todo2,adj2[i]);
enqueue(&collect2,adj2[i]);
collect_pool[adj2[i]].visited = offset_2;
cs2++;
}
}
}
}
else {
while(!queue_empty_p(&todo1)) dequeue(&todo1,&activeP1);
while(!queue_empty_p(&todo2)) dequeue(&todo2,&activeP2);
while(!queue_empty_p(&collect1)) dequeue(&collect1,&activeP1);
while(!queue_empty_p(&collect2)) dequeue(&collect2,&activeP2);
}
offset_1+=2;
offset_2+=2;
return 0;
}
/******************************************************************************
*****************************************************************************/
static __u8 removeBond(__u32 a, __u32 b,__u8 accept_split,__u8 accept_non_split) {
__u32 vertex;
if(breadthFirstSearch(a,b,accept_split)) //replacement edge found
return accept_non_split;
else { // no replacement edge available and hence cluster will be splitted if move accepted
if(accept_split) { // accept cluster splitting case? if yes rebuild uf
while(!queue_empty_p(&collect1)) {
dequeue(&collect1,&vertex);
uf1[vertex] = a;
}
uf1[a] = -1*cs1;
while(!queue_empty_p(&collect2)) {
dequeue(&collect2,&vertex);
uf1[vertex] = b;
}
uf1[b] = -1*cs2;
return 1;
} // not accepted
else {
return 0;
}
}
}
/******************************************************************************
*****************************************************************************/
static inline __u8 acceptChange(__s8 d_numCl, __s8 d_numAB, double randV)
{
return d_numAB == -1 ? (randV < rcWeights[d_numCl]) : (randV < rcWeights[2 - d_numCl]);
}
/******************************************************************************
*****************************************************************************/
static inline void mcStep(void)
{
static __u32 bidx;
static double rnd_num;
bidx = gsl_rng_uniform_int(r,2*N);
rnd_num = gsl_rng_uniform(r);
Adjacent(bidx);
if(bonds[bidx] == 1) { //edge is active hence delete it
if(rnd_num < p_min_del) {
bonds[bidx] = -1;
if(removeBond(edge[0],edge[1],1,1))
activeEdges--;
else {
if(verbose)fprintf(stderr,"ERROR!\n");
exit(-1);
}
}
else {
if(rnd_num < p_max_del) {
bonds[bidx] = -1;
if(removeBond(edge[0],edge[1], acceptChange(1,-1,rnd_num),acceptChange(0,-1,rnd_num)))
activeEdges--;
else
bonds[bidx] = 1;
}
}
}
else {
if(rnd_num < p_min_ins) {
bonds[bidx] = 1;
activeEdges++;
unite(edge[0],edge[1],uf1);
}
else {
if(rnd_num < p_max_ins) {
dN = connected(edge[0],edge[1],uf1) ? 0: -1;
if(acceptChange(dN,1,rnd_num)) {
bonds[bidx]=1;
activeEdges++;
if(dN == -1)
unite(edge[0],edge[1],uf1);
}
}
}
}
}
/******************************************************************************
*****************************************************************************/
static void extract_observables(__u32 cnt)
{
__u32 i=0,tn=0,nclust=0;
size_giant[cnt] = 0;
sec_cs_moment[cnt] = 0;
four_cs_moment[cnt] = 0;
for(i=0;i<N && tn <= N;i++) {
if(uf1[i] < 0) {
tn -= uf1[i];
nclust+=1;
sec_cs_moment[cnt]+= (__u64)pow(uf1[i],2);
four_cs_moment[cnt]+= (__u64)pow(uf1[i],4);
if((__u32)(-uf1[i]) > size_giant[cnt]) size_giant[cnt] = (__u32)(-uf1[i]);
}
}
num_bonds[cnt] = activeEdges;
num_cluster[cnt] = nclust;
}
/******************************************************************************
*****************************************************************************/
static void generateTimeSeries(void)
{
__u32 i=0,j=0;
for(i=0;i<cutoff;i++){
for(j=0;j<2*N;j++)mcStep();
// reset visited array
// otherwise it will overflow at some point
// could also be done less frequent
for(j=0;j<N;j++)collect_pool[j].visited=0;
}
for(i=0;i<steps;i++) {
for(j=0;j<2*N;j++)
mcStep();
extract_observables(i);
for(j=0;j<N;j++)collect_pool[j].visited=0;
}
}
/******************************************************************************
*****************************************************************************/
char init_sweeny_uf(double _q,unsigned int _l,double _beta,double _coupl,
unsigned int _cutoff,unsigned _tslength,unsigned int rng_seed,
void *ts_0,void *ts_1,void * ts_2,void *ts_3, void *ts_4) {
q = _q;
DX = _l;
beta = _beta;
coupling = _coupl;
cutoff = _cutoff;
steps = _tslength;
seed = rng_seed;
num_bonds = (__u32 *)ts_0;
num_cluster = (__u32 *)ts_1;
size_giant = (__u32 *)ts_2;
sec_cs_moment = (__u64 *)ts_3;
four_cs_moment = (__u64 *)ts_4;
return setup=init();
}
/******************************************************************************
*****************************************************************************/
void destroy_sweeny_uf(void) {
if(setup)
destroy();
setup=0;
}
/******************************************************************************
*****************************************************************************/
char simulate_sweeny_uf(void) {
if(!setup)return 0;
generateTimeSeries();
return 1;
}
/******************************************************************************
*****************************************************************************/
| {
"alphanum_fraction": 0.4470780281,
"avg_line_length": 33.6593406593,
"ext": "c",
"hexsha": "39e12d46a659c9faed7831bf15cf4463ccaf4d89",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2017-04-10T14:18:57.000Z",
"max_forks_repo_forks_event_min_datetime": "2017-04-10T14:18:57.000Z",
"max_forks_repo_head_hexsha": "ae6dc73d9a6c793c797453f4d05724b1210bb1be",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "ermeel86/sweeny",
"max_forks_repo_path": "src/sweeny_uf.c",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "ae6dc73d9a6c793c797453f4d05724b1210bb1be",
"max_issues_repo_issues_event_max_datetime": "2018-08-20T09:32:03.000Z",
"max_issues_repo_issues_event_min_datetime": "2018-08-19T09:29:25.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "ernmeel/sweeny",
"max_issues_repo_path": "src/sweeny_uf.c",
"max_line_length": 106,
"max_stars_count": 2,
"max_stars_repo_head_hexsha": "ae6dc73d9a6c793c797453f4d05724b1210bb1be",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "ermeel86/sweeny",
"max_stars_repo_path": "src/sweeny_uf.c",
"max_stars_repo_stars_event_max_datetime": "2018-08-14T15:05:04.000Z",
"max_stars_repo_stars_event_min_datetime": "2018-06-24T09:04:04.000Z",
"num_tokens": 3858,
"size": 15315
} |
#pragma once
#include <array>
#include <gsl/span>
#include "Quiver/Animation/Rect.h"
namespace qvr {
struct ViewBuffer {
int viewCount = 0;
std::array<Animation::Rect, 8> views;
// TODO: Consider making initial value of viewCount == 1.
// TODO: Consider making viewCount < 1 illegal.
};
// TODO: Consider making these public member functions of ViewBuffer and
// making the data members private.
inline void SetView(
ViewBuffer& vb,
const Animation::Rect& singleView)
{
vb.viewCount = 1;
vb.views[0] = singleView;
}
inline void SetViews(
ViewBuffer& target,
const gsl::span<const Animation::Rect> newViews)
{
target.viewCount =
std::min(
(int)newViews.length(),
(int)target.views.max_size());
std::copy(
std::begin(newViews),
std::begin(newViews) + target.viewCount,
std::begin(target.views));
}
inline auto GetViews(const ViewBuffer& vb) -> gsl::span<const Animation::Rect> {
return gsl::make_span(&vb.views[0], vb.viewCount);
}
inline const Animation::Rect& CalculateView(
const ViewBuffer& vb,
const float objectAngle,
const float viewAngle)
{
assert(vb.viewCount > 0);
const float Tau = 6.28318530718f;
const int viewIndex =
(int)((fmodf((objectAngle - viewAngle + Tau), Tau) / Tau) * (vb.viewCount));
// Make sure my maths is right.
assert(viewIndex >= 0);
assert(viewIndex < vb.viewCount);
return vb.views[viewIndex];
}
} | {
"alphanum_fraction": 0.7023121387,
"avg_line_length": 20.3529411765,
"ext": "h",
"hexsha": "19adc777f38914ff87913c0b222aeee43a5dac6c",
"lang": "C",
"max_forks_count": 8,
"max_forks_repo_forks_event_max_datetime": "2020-03-19T10:08:45.000Z",
"max_forks_repo_forks_event_min_datetime": "2017-10-22T14:47:57.000Z",
"max_forks_repo_head_hexsha": "c8ef9591117bdfc8d6fa509ae53451e0807f5686",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "rachelnertia/Quiver",
"max_forks_repo_path": "Source/Quiver/Quiver/Graphics/ViewBuffer.h",
"max_issues_count": 46,
"max_issues_repo_head_hexsha": "69616179fc71305757549c7fcaccc22707a91ba4",
"max_issues_repo_issues_event_max_datetime": "2018-10-13T14:46:17.000Z",
"max_issues_repo_issues_event_min_datetime": "2017-10-26T21:21:51.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "rachelnertia/Quarrel",
"max_issues_repo_path": "External/Quiver/Source/Quiver/Quiver/Graphics/ViewBuffer.h",
"max_line_length": 80,
"max_stars_count": 39,
"max_stars_repo_head_hexsha": "69616179fc71305757549c7fcaccc22707a91ba4",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "rachelnertia/Quarrel",
"max_stars_repo_path": "External/Quiver/Source/Quiver/Quiver/Graphics/ViewBuffer.h",
"max_stars_repo_stars_event_max_datetime": "2020-03-31T22:19:55.000Z",
"max_stars_repo_stars_event_min_datetime": "2017-10-22T15:47:39.000Z",
"num_tokens": 369,
"size": 1384
} |
/* ///////////////////////////////////////////////////////////////////// */
/*!
\file
\brief Contains basic functions for problem initialization.
The init.c file collects most of the user-supplied functions useful
for problem configuration.
It is automatically searched for by the makefile.
\author A. Mignone (mignone@ph.unito.it)
\date March 5, 2017
*/
/* ///////////////////////////////////////////////////////////////////// */
#include "pluto.h"
#include "local_pluto.h"
#include <math.h>
#include "coolit.h"
#include "init_interp.h"
#include <stdbool.h>
//#include <gsl.h>
double mu, mue, mui, Rcl;
double rho0, P0, cs0, v0, s0, cool_0, tcool0, r_crit;
double rhobnd[2], pbnd[2], vbnd[2]; //boundary conditions at inner and outer radius
int q = 1, counter = 0;
double T0 , Mach0, n0, chi, singular;
/* ********************************************************************* */
void Init (double *v, double x1, double x2, double x3)
/*!
* The Init() function can be used to assign initial conditions as
* as a function of spatial position.
*
* \param [out] v a pointer to a vector of primitive variables
* \param [in] x1 coordinate point in the 1st dimension
* \param [in] x2 coordinate point in the 2nd dimension
* \param [in] x3 coordinate point in the 3rdt dimension
*
* The meaning of x1, x2 and x3 depends on the geometry:
* \f[ \begin{array}{cccl}
* x_1 & x_2 & x_3 & \mathrm{Geometry} \\ \noalign{\medskip}
* \hline
* x & y & z & \mathrm{Cartesian} \\ \noalign{\medskip}
* R & z & - & \mathrm{cylindrical} \\ \noalign{\medskip}
* R & \phi & z & \mathrm{polar} \\ \noalign{\medskip}
* r & \theta & \phi & \mathrm{spherical}
* \end{array}
* \f]
*
* Variable names are accessed by means of an index v[nv], where
* nv = RHO is density, nv = PRS is pressure, nv = (iVR, VX2, VX3) are
* the three components of velocity, and so forth.
*
*********************************************************************** */
{
#if PHYSICS == MHD || PHYSICS == RMHD
v[BX1] = 0.0;
v[BX2] = 0.0;
v[BX3] = 0.0;
v[AX1] = 0.0;
v[AX2] = 0.0;
v[AX3] = 0.0;
#endif
}
/* ********************************************************************* */
void InitDomain (Data *d, Grid *grid)
/*!
* Assign initial condition by looping over the computational domain.
* Called after the usual Init() function to assign initial conditions
* on primitive variables.
* Value assigned here will overwrite those prescribed during Init().
*
*
*********************************************************************** */
{
int i, j, k;
int id;
double *x1 = grid->x[IDIR];
double *x2 = grid->x[JDIR];
double *x3 = grid->x[KDIR];
double ne0, ni0;
double* muemui = MeanElIonWeight((double*)d->Vc);
mue = muemui[0];
mui = muemui[1];
mu = MeanMolecularWeight((double*)d->Vc);
T0 = g_inputParam[T_CRIT]; //K
Mach0 = g_inputParam[MACH_CRIT];
n0 = g_inputParam[N_CRIT]; //cm^-3
chi = g_inputParam[CHI];
singular = g_inputParam[SINGULAR];
rho0 = n0*mu*CONST_mp; //g cm^-3
ne0 = n0*mu/mue;
ni0 = n0*mu/mui;
P0 = n0*CONST_kB*T0; //dyne cm^-2
cs0 = sqrt(g_gamma*P0/rho0); //cm s^-1
v0 = -Mach0*cs0; //cm s^-1
s0 = P0/pow(rho0,g_gamma); //CGS
cool_0 = lambda(T0); //CGS
tcool0 = (1./(g_gamma-1))*n0*CONST_kB*T0/(ne0*ni0*cool_0); //s
r_crit = -q*v0*g_gamma*tcool0; //cm
Rcl = singular*r_crit*pow(UNIT_LENGTH,-1); // code units (pc usually)
//print("Test: %.3e\t%.3e\t%.3e\n",r_crit,UNIT_LENGTH,r_crit*pow(UNIT_LENGTH,-1));
print("T0=%.1e\tM0=%.1f\tn0=%.2e\t\tchi=%d\tsingular=%.2f\n",T0,Mach0, n0, (int)chi, singular);
print("rho0=%.1e\t\tP0=%.1e\t\tv0=%.2e\t\tr_crit=%.2e kpc\tRcl=%.2e kpc\t\ttcool0=%.2e Myr\n",rho0/UNIT_DENSITY,P0/(UNIT_DENSITY*pow(UNIT_VELOCITY,2)), v0/UNIT_VELOCITY, r_crit*pow(UNIT_LENGTH,-1), Rcl, tcool0*pow(CONST_PI*1e13,-1.));
print("Starting from %.2f kpc (r/ro=%.2e) to %.2f kpc (r/r0=%.2e)\n",g_domBeg[IDIR],g_domBeg[IDIR]/r_crit*UNIT_LENGTH,g_domEnd[IDIR],g_domEnd[IDIR]/r_crit*UNIT_LENGTH);
print("Using Solar metallicity\n");
print("Useful info: mu=%.2f mu_e=%.2f mu_i=%.2f\n",mu,mue,mui);
print("Mass flux: %.2e Msun/yr\n",-4*CONST_PI*r_crit*r_crit*rho0*v0/(CONST_Msun/(365*24*60*60)));
#if SUBSONIC_INI != NO
readICfile("subsonic_rdpv.txt");
#else
readICfile("transonic_rdpv.txt");
#endif
TOT_LOOP(k,j,i){
//if (prank==0 && (x1[i]<g_domBeg[IDIR] || x1[i]>g_domEnd[IDIR])) printf("%.2f pc\n",x1[i]);
double* dpv = initdpv(x1[i]*UNIT_LENGTH/r_crit);
if (i==0){
rhobnd[0] = dpv[0]; pbnd[0] = dpv[1]; vbnd[0] = dpv[2];
}
else if(i==NX1-10){
rhobnd[1] = dpv[0]; pbnd[1] = dpv[1]; vbnd[1] = dpv[2];
}
//print("%.2e\t\t%.2e\t\t%.2e\t\t%.2e\n",x1[i]*UNIT_LENGTH/r_crit,dpv[0],dpv[1],dpv[2]);
d->Vc[RHO][k][j][i] = dpv[0]*rho0/UNIT_DENSITY; //(x1[i]/Rcl<=1.)?chi*n0*mu*CONST_mp/UNIT_DENSITY:n0*mu*CONST_mp/UNIT_DENSITY;
d->Vc[PRS][k][j][i] = dpv[1]*P0/(UNIT_DENSITY*pow(UNIT_VELOCITY,2));
EXPAND(d->Vc[iVR][k][j][i] = dpv[2]*abs(v0)/UNIT_VELOCITY; ,d->Vc[iVZ][k][j][i] = 0.;, d->Vc[VX3][k][j][i] = 0.;)
d->Vc[TRC][k][j][i] = 1.0;
}
print("Done reading IC from file!\n");
print("Left fixed boundary: rho/rho0=%.2e\t\tp/p0=%.2e\t\tv/v0=%.2e\n",rhobnd[0],pbnd[0],vbnd[0]);
print("Right fixed boundary: rho/rho0=%.2e\t\tp/p0=%.2e\t\tv/v0=%.2e\n",rhobnd[1],pbnd[1],vbnd[1]);
#if VX1RHO_OUTFLOW ==YES
print("iVR and Density are outflowing.\n");
#endif
}
/* ********************************************************************* */
void Analysis (const Data *d, Grid *grid)
/*!
* Perform runtime data analysis.
*
* \param [in] d the PLUTO Data structure
* \param [in] grid pointer to array of Grid structures
*
*********************************************************************** */
{
/*
int i, j, k;
double *dx, *dy, *dz;*/
/* ---- Parallel data reduction ---- */
/*
#ifdef PARALLEL
int transfer_size = 3;
int transfer = 0;
double sendArray [transfer_size], recvArray[transfer_size];*/
/* ---- Set pointer shortcuts ---- */
/*
dx = grid->dx[IDIR];
dy = grid->dx[JDIR];
dz = grid->dx[KDIR];*/
}
#if PHYSICS == MHD
/* ********************************************************************* */
void BackgroundField (double x1, double x2, double x3, double *B0)
/*!
* Define the component of a static, curl-free background
* magnetic field.
*
* \param [in] x1 position in the 1st coordinate direction \f$x_1\f$
* \param [in] x2 position in the 2nd coordinate direction \f$x_2\f$
* \param [in] x3 position in the 3rd coordinate direction \f$x_3\f$
* \param [out] B0 array containing the vector componens of the background
* magnetic field
*********************************************************************** */
{
B0[0] = 0.0;
B0[1] = 0.0;
B0[2] = 0.0;
}
#endif
/* ********************************************************************* */
void UserDefBoundary (const Data *d, RBox *box, int side, Grid *grid)
/*!
* Assign user-defined boundary conditions.
*
* \param [in,out] d pointer to the PLUTO data structure containing
* cell-centered primitive quantities (d->Vc) and
* staggered magnetic fields (d->Vs, when used) to
* be filled.
* \param [in] box pointer to a RBox structure containing the lower
* and upper indices of the ghost zone-centers/nodes
* or edges at which data values should be assigned.
* \param [in] side specifies the boundary side where ghost zones need
* to be filled. It can assume the following
* pre-definite values: X1_BEG, X1_END,
* X2_BEG, X2_END,
* X3_BEG, X3_END.
* The special value side == 0 is used to control
* a region inside the computational domain.
* \param [in] grid pointer to an array of Grid structures.
*
*********************************************************************** */
{
int i, j, k, nv;
double *x1, *x2, *x3;
x1 = grid->x[IDIR];
x2 = grid->x[JDIR];
x3 = grid->x[KDIR];
if (side == X1_BEG) {
BOX_LOOP(box,k,j,i) {
d->Vc[PRS][k][j][i] = pbnd[0]*P0/(UNIT_DENSITY*pow(UNIT_VELOCITY,2)); //only fix the pressure
#if VX1RHO_OUTFLOW ==YES
d->Vc[RHO][k][j][i] = d->Vc[RHO][k][j][IBEG]; //outflow density
d->Vc[iVR][k][j][i] = d->Vc[iVR][k][j][IBEG]; //outflow velocity
#else
d->Vc[RHO][k][j][i] = rhobnd[0]*rho0/UNIT_DENSITY;
d->Vc[iVR][k][j][i] = vbnd[0]*abs(v0)/UNIT_VELOCITY;
#endif
}
}else if (side == X1_END){
BOX_LOOP(box,k,j,i) {
d->Vc[PRS][k][j][i] = pbnd[1]*P0/(UNIT_DENSITY*pow(UNIT_VELOCITY,2));
#if VX1RHO_OUTFLOW ==YES
d->Vc[RHO][k][j][i] = d->Vc[RHO][k][j][IEND]; //outflow density
d->Vc[iVR][k][j][i] = d->Vc[iVR][k][j][IEND]; //outflow velocity
#else
d->Vc[RHO][k][j][i] = rhobnd[1]*rho0/UNIT_DENSITY;
d->Vc[iVR][k][j][i] = vbnd[1]*abs(v0)/UNIT_VELOCITY;
#endif
}
}
/*
if (side == 0) { */ /* -- check solution inside domain -- */
/* TOT_LOOP(k,j,i){
if ((x1[i]*UNIT_LENGTH/r_crit>=(1.-1e-1)) && (x1[i]*UNIT_LENGTH/r_crit<=(1.+1e-1))) {
d->Vc[RHO][k][j][i] = rho0/UNIT_DENSITY;
d->Vc[iVR][k][j][i] = v0/UNIT_VELOCITY;
d->Vc[PRS][k][j][i] = P0/(UNIT_DENSITY*pow(UNIT_VELOCITY,2));
}/*
if (x1[i]/Rcl<1.)
d->Vc[iVR][k][j][i] = 0.; *//*
}
}*/
}
#if BODY_FORCE != NO
/* ********************************************************************* */
void BodyForceVector(double *v, double *g, double x1, double x2, double x3)
/*!
* Prescribe the acceleration vector as a function of the coordinates
* and the vector of primitive variables *v.
*
* \param [in] v pointer to a cell-centered vector of primitive
* variables
* \param [out] g acceleration vector
* \param [in] x1 position in the 1st coordinate direction \f$x_1\f$
* \param [in] x2 position in the 2nd coordinate direction \f$x_2\f$
* \param [in] x3 position in the 3rd coordinate direction \f$x_3\f$
*
*********************************************************************** */
{
g[IDIR] = 0.0;
g[JDIR] = 0.0;
g[KDIR] = 0.0;
}
/* ********************************************************************* */
double BodyForcePotential(double x1, double x2, double x3)
/*!
* Return the gravitational potential as function of the coordinates.
*
* \param [in] x1 position in the 1st coordinate direction \f$x_1\f$
* \param [in] x2 position in the 2nd coordinate direction \f$x_2\f$
* \param [in] x3 position in the 3rd coordinate direction \f$x_3\f$
*
* \return The body force potential \f$ \Phi(x_1,x_2,x_3) \f$.
*
*********************************************************************** */
{
return 0.0;
}
#endif
| {
"alphanum_fraction": 0.5450188923,
"avg_line_length": 35.8118811881,
"ext": "c",
"hexsha": "c27c0d946cece669ce6c04a3eeddb3d100720f78",
"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": "d3aed3c0ab9d976f7552b658e08e4f01046dff32",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "dutta-alankar/cooling-flow-model",
"max_forks_repo_path": "PLUTO-simulations/Cylindrical_CF/transonic/init.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "d3aed3c0ab9d976f7552b658e08e4f01046dff32",
"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": "dutta-alankar/cooling-flow-model",
"max_issues_repo_path": "PLUTO-simulations/Cylindrical_CF/transonic/init.c",
"max_line_length": 236,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "d3aed3c0ab9d976f7552b658e08e4f01046dff32",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "dutta-alankar/cooling-flow-model",
"max_stars_repo_path": "PLUTO-simulations/Cylindrical_CF/transonic/init.c",
"max_stars_repo_stars_event_max_datetime": "2021-07-02T15:03:49.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-07-02T15:03:49.000Z",
"num_tokens": 3609,
"size": 10851
} |
//! \file neutronics_driver.h
//! Base class for single-physics neutronics solver
#ifndef NEUTRONICS_DRIVER_H
#define NEUTRONICS_DRIVER_H
#include "enrico/driver.h"
#include "enrico/geom.h"
#include "enrico/mpi_types.h"
#include <gsl/gsl>
#include <xtensor/xtensor.hpp>
#include <vector>
namespace enrico {
using CellHandle = gsl::index;
//! Base class for driver that controls a neutronics solve
class NeutronicsDriver : public Driver {
public:
explicit NeutronicsDriver(MPI_Comm comm)
: Driver(comm)
{}
virtual ~NeutronicsDriver() = default;
//! Get energy deposition in each material normalized to a given power
//! \param power User-specified power in [W]
//! \return Heat source in each material as [W/cm3]
virtual xt::xtensor<double, 1> heat_source(double power) const = 0;
//! Find cells corresponding to a vector of positions
//! \param positions (x,y,z) coordinates to search for
//! \return Handles to cells
virtual std::vector<CellHandle> find(const std::vector<Position>& positions) = 0;
//! Set the density of the material in a cell
//! \param cell Handle to a cell
//! \param rho Density in [g/cm^3]
virtual void set_density(CellHandle cell, double rho) const = 0;
//! Set the temperature of a cell
//! \param cell Handle to a cell
//! \param T Temperature in [K]
virtual void set_temperature(CellHandle cell, double T) const = 0;
//! Get the density of a cell
//! \param cell Handle to a cell
//! \return Cell density in [g/cm^3]
virtual double get_density(CellHandle cell) const = 0;
//! Get the temperature of a cell
//! \param cell Handle to a cell
//! \return Temperature in [K]
virtual double get_temperature(CellHandle cell) const = 0;
//! Get the volume of a cell
//! \param cell Handle to a cell
//! \return Volume in [cm^3]
virtual double get_volume(CellHandle cell) const = 0;
//! Detemrine whether a cell contains fissionable nuclides
//! \param cell Handle to a cell
//! \return Whether the cell contains fissionable nuclides
virtual bool is_fissionable(CellHandle cell) const = 0;
//! Determine number of cells participating in coupling
//! \return Number of cells
virtual std::size_t n_cells() const = 0;
//! Create energy production tallies
virtual void create_tallies() = 0;
//! Get a label for a cell
//! \param cell Handle to a clel
//! \return Label for the cell
virtual std::string cell_label(CellHandle cell) const = 0;
};
} // namespace enrico
#endif // NEUTRONICS_DRIVER_H
| {
"alphanum_fraction": 0.707491082,
"avg_line_length": 30.0357142857,
"ext": "h",
"hexsha": "7f8c8dce23b2d3cfa5493a6283e9169763da491a",
"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": "edd04f1e02caf1c3fae2992e55d9a47e4429655c",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "lebuller/enrico",
"max_forks_repo_path": "include/enrico/neutronics_driver.h",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "72b95ca947804f672e5f1726e169ef6f4889e78e",
"max_issues_repo_issues_event_max_datetime": "2020-03-17T20:56:35.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-03-17T15:52:45.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "pshriwise/enrico",
"max_issues_repo_path": "include/enrico/neutronics_driver.h",
"max_line_length": 83,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "72b95ca947804f672e5f1726e169ef6f4889e78e",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "pshriwise/enrico",
"max_stars_repo_path": "include/enrico/neutronics_driver.h",
"max_stars_repo_stars_event_max_datetime": "2021-04-02T16:21:59.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-04-02T16:21:59.000Z",
"num_tokens": 662,
"size": 2523
} |
#include <stdio.h>
#include <stdlib.h>
#include <gsl/gsl_randist.h>
#include <errno.h>
#include <string.h>
#include <time.h>
const int SAMPLENUM = 1000;
int obsnum;
gsl_rng * r;
typedef struct {
int prey;
int predator;
} lvstate;
typedef struct {
double time;
double rawdata;
} obsdata;
void simPrior(lvstate *simData);
void rowsample(int *rows, double *w);
void stepLV(lvstate *state, double *t0p, double *dtp, double *lvParam);
void peturb(double *lvParam);
double obsLik(lvstate *mystate, double obs) {
const double SIGMA = 10.0;
return log(gsl_ran_gaussian_pdf((obs - mystate->prey), SIGMA));
}
void callStepLV(lvstate *simData, double *t0p, double *dtp, double *lvParam) {
int j;
for (j=0;j<SAMPLENUM;j++) {
stepLV(simData + j, t0p, dtp, lvParam);
}
}
//particle filter: output new estimated lvstate and its likehood
void pfPropPar(lvstate ppstate[16], obsdata *myobsdata, double *lvParam,
double *ll) {
//printf("Starting pfPropPar...\n");
typedef struct {
lvstate *vpptuple;
} stateVec;
int i, j, k, l;
double timeUnit = 2.0;
int deltaTimeUnit = 1;
double delTime = timeUnit * deltaTimeUnit;
double curTime = 0.0;
double lw[SAMPLENUM];
double w[SAMPLENUM];
double wSum;
double maxLw;
double likehood = 0.0;
unsigned int rows[SAMPLENUM];
//printf("Starting pfPropPar 1 ...\n");
stateVec *myStateVec = malloc(obsnum * sizeof(stateVec));
if (myStateVec == NULL) {
printf("Fail to initiate myStateVec...Exit");
goto freeMem;
}
memset(myStateVec, 0, obsnum * sizeof(stateVec));
stateVec *tempStateVec = malloc(obsnum * sizeof(stateVec));
if (tempStateVec == NULL) {
printf("Fail to initiate tempStateVec...Exit");
goto freeMem;
}
memset(tempStateVec, 0, obsnum * sizeof(stateVec));
lvstate *simData = malloc(SAMPLENUM * sizeof(lvstate));
if (simData == NULL) {
printf("Fail to initiate simData...EXIT!");
goto freeMem;
}
memset(simData, 0, SAMPLENUM * sizeof(lvstate));
//initiate state: get simulated prey-predator tuple
simPrior(simData);
*ll = 0.0;
if ((tempStateVec + 0)->vpptuple == NULL) {
(tempStateVec + 0)->vpptuple = (lvstate*) malloc(
SAMPLENUM * sizeof(lvstate));
if ((tempStateVec + 0)->vpptuple == NULL) {
printf("Fail to initiate myStateVec->vpptuple...Exit");
goto freeMem;
//free(tempStateVec);
//goto error;
}
}
memset(tempStateVec[0].vpptuple, 0, SAMPLENUM * sizeof(lvstate));
for (j = 0; j < SAMPLENUM; j++) {
((tempStateVec + 0)->vpptuple + j)->predator = (simData + j)->predator;
((tempStateVec + 0)->vpptuple + j)->prey = (simData + j)->prey;
}
for (i = 1; i < obsnum; i++) {
curTime = myobsdata[i - 1].time;
wSum = 0.0;
if ((tempStateVec + i)->vpptuple == NULL) {
//printf("init temp \n");
(tempStateVec + i)->vpptuple = (lvstate*) malloc(
SAMPLENUM * sizeof(lvstate));
if ((tempStateVec + i)->vpptuple == NULL) {
printf("Fail to initiate myStateVec->vpptuple...Exit");
goto freeMem;
}
memset((tempStateVec + i)->vpptuple, 0,
SAMPLENUM * sizeof(lvstate));
}
//printf("tempvec 1 %i\n", ((tempStateVec+0)->vpptuple+1)->prey);
callStepLV(simData, &curTime, &delTime, lvParam);
for (j = 0; j < SAMPLENUM; j++) {
//stepLV(simData + j, &curTime, &delTime, lvParam);
((tempStateVec + i)->vpptuple + j)->predator =
(simData + j)->predator;
((tempStateVec + i)->vpptuple + j)->prey = (simData + j)->prey;
//printf("tempState %i vpptuple %i , %p\n", i,j,(tempStateVec+i)->vpptuple+j);
lw[j] = obsLik(((tempStateVec + i)->vpptuple + j),
myobsdata[i].rawdata);
if (j == 0) {
maxLw = lw[0];
} else {
if (lw[j] > maxLw) {
maxLw = lw[j];
}
}
}
for (l = 0; l < SAMPLENUM; l++) {
w[l] = exp(lw[l] - maxLw);
wSum = wSum + w[l];
}
rowsample(rows, w);
//reorganize the vector with only keeping the rows in 'rows'
for (k = 0; k <= i; k++) {
if ((myStateVec + k)->vpptuple == NULL) {
//printf("init mystatevec \n");
(myStateVec + k)->vpptuple = (lvstate*) malloc(
SAMPLENUM * sizeof(lvstate));
if ((myStateVec + k)->vpptuple == NULL) {
printf("Fail to initiate myStateVec->vpptuple...Exit");
goto freeMem;
}
}
// memset(myStateVec[k].vpptuple,0,SAMPLENUM * sizeof(lvstate));
for (j = 0; j < SAMPLENUM; j++) {
((myStateVec + k)->vpptuple + j)->predator =
((tempStateVec + k)->vpptuple + rows[j])->predator;
((myStateVec + k)->vpptuple + j)->prey =
((tempStateVec + k)->vpptuple + rows[j])->prey;
//printf("row %i %i,%i,%i,%i,%i\n", i,k,j,rows[j],((myStateVec+k)->vpptuple+j)->prey,((tempStateVec+k)->vpptuple+rows[j])->prey);
}
for (j = 0; j < SAMPLENUM; j++) {
((tempStateVec + k)->vpptuple + j)->predator =
((myStateVec + k)->vpptuple + j)->predator;
((tempStateVec + k)->vpptuple + j)->prey =
((myStateVec + k)->vpptuple + j)->prey;
}
}
for (j = 0; j < SAMPLENUM; j++) {
simData[j].predator = ((myStateVec + i)->vpptuple + j)->predator;
simData[j].prey = ((myStateVec + i)->vpptuple + j)->prey;
}
likehood = likehood + maxLw + log(wSum / SAMPLENUM);
*ll = likehood;
rows[SAMPLENUM] = NULL;
}
for (i = 0; i < obsnum; i++) {
ppstate[i].prey = ((myStateVec + i)->vpptuple + 0)->prey;
ppstate[i].predator = ((myStateVec + i)->vpptuple + 0)->predator;
}
freeMem:
//printf("free mem...");
if (myStateVec != NULL) {
//printf("free mem 2...");
for (i = 0; ((myStateVec + i)->vpptuple != NULL) && i < obsnum; i++) {
//printf("free myStateVec...i %i\n", i);
free((myStateVec + i)->vpptuple);
(myStateVec + i)->vpptuple = NULL;
}
free(myStateVec);
myStateVec = NULL;
}
if (tempStateVec != NULL) {
for (i = 0; NULL != (tempStateVec + i)->vpptuple && i < obsnum; i++) {
//printf("free tempStateVec...i %i\n", i);
free((tempStateVec + i)->vpptuple);
(tempStateVec + i)->vpptuple = NULL;
}
free(tempStateVec);
tempStateVec = NULL;
}
if (simData != NULL) {
free(simData);
simData = NULL;
}
}
void stepLV(lvstate *state, double *t0p, double *dtp, double *lvParam) {
//printf("Starting stepLV...\n");
register double t0 = *t0p, dt = *dtp, t;
register double h0, h1, h2, h3, u, l0, l1, l2;
register int prey, predator;
prey = state->prey;
predator = state->predator;
l0 = lvParam[0];
l1 = lvParam[1];
l2 = lvParam[2];
while (dt > 0) {
h1 = l0 * prey;
h2 = l1 * prey * predator;
h3 = l2 * predator;
h0 = h1 + h2 + h3;
if ((h0 < (1e-10)) || (prey >= 1000000))
t = 1e99;
else {
t = gsl_ran_exponential(r, 1/h0);
}
if (t > dt) {
state->prey = prey;
state->predator = predator;
return;
} else {
u = gsl_rng_uniform(r);
if (u < (h1 / h0)) {
prey = prey + 1;
t0 = t0 + t;
dt = dt - t;
} else if (u < ((h1 + h2) / h0)) {
prey = prey - 1;
predator = predator + 1;
t0 = t0 + t;
dt = dt - t;
} else {
predator = predator - 1;
t0 = t0 + t;
dt = dt - t;
}
}
}
return;
}
//mcmc process
void runPmmhPath(int its, double *lvParam, double *obslik, lvstate ppstate[16],
obsdata *myobsdata) {
//printf("Starting runPmmhPath...\n");
int i, j;
double propParam[3];
double curParam[3];
double ll;
double propMll, curMll = -1e99;
lvstate curPath[obsnum];
lvstate propPath[obsnum];
FILE *fp = fopen("mcmc-out.txt", "wab+");
if (fp == NULL) {
printf("file is null.\n");
return;
}
fprintf(fp, "th1,th2,th3,");
for (i = 0; i <= 30; i++) {
if ((i % 2) == 0) {
if (i == 30) {
fprintf(fp, "x%i,y%i", i, i);
} else {
fprintf(fp, "x%i,y%i,", i, i);
}
}
}
fprintf(fp, "\n");
memcpy(curPath, ppstate, sizeof(lvstate) * obsnum);
memcpy(curParam, lvParam, sizeof(double) * 3);
for (i = its; i > 0; i--) {
//calculate measurements and decide moving to next state or not
memcpy(propParam, curParam, sizeof(double) * 3);
peturb(propParam);
pfPropPar(propPath, myobsdata, propParam, &ll);
propMll = ll;
if (log(gsl_ran_flat(r, 0.0, 1.0)) < (propMll - curMll)) {
curMll = propMll;
memcpy(curParam, propParam, sizeof(double) * 3);
memcpy(curPath, propPath, sizeof(lvstate) * obsnum);
}
//write current parameters and state sequence into output
fprintf(fp, "%f,%f,%f,", curParam[0], curParam[1], curParam[2]);
for (j = 0; j < obsnum; j++) {
if (j == (obsnum - 1)) {
fprintf(fp, "%i,%i", (int)curPath[j].prey, (int)curPath[j].predator);
} else {
fprintf(fp, "%i,%i,", (int)curPath[j].prey, (int)curPath[j].predator);
}
}
fprintf(fp, "\n");
}
fclose(fp);
}
void rowsample(int *rows, double *w) {
//printf("Starting rowsample...\n");
gsl_ran_discrete_t * grdp;
int row;
int i;
grdp = gsl_ran_discrete_preproc(SAMPLENUM, w);
for (i = 0; i < SAMPLENUM; i++) {
row = (int) gsl_ran_discrete(r, grdp);
rows[i] = row;
}
gsl_ran_discrete_free(grdp);
return;
}
void peturb(double *lvParam) {
//printf("Starting peturb...\n");
const double SIGMA = 0.01;
//printf("lvParam_before %f, %f, %f\n", lvParam[0], lvParam[1], lvParam[2]);
lvParam[0] = lvParam[0] * exp(gsl_ran_gaussian(r, SIGMA));
lvParam[1] = lvParam[1] * exp(gsl_ran_gaussian(r, SIGMA));
lvParam[2] = lvParam[2] * exp(gsl_ran_gaussian(r, SIGMA));
//printf("lvParam_after %f, %f, %f\n", lvParam[0], lvParam[1], lvParam[2]);
}
//to get the prior simulate value of prey and predator
void simPrior(lvstate *simData) {
//printf("Starting simPrior...\n");
int i;
const double PREY_MEAN = 50.0;
const double PRED_MEAN = 100.0;
for (i = 0; i < SAMPLENUM; i++) {
simData[i].prey = gsl_ran_poisson(r, PREY_MEAN);
simData[i].predator = gsl_ran_poisson(r, PRED_MEAN);
//printf("simPrior %i\n", simData[i].prey);
}
//printf("End simPrior...\n");
}
void runModel(int its) {
obsnum = 16;
obsdata myobsdata[obsnum];
lvstate mylvstate[obsnum];
double ll = 0.0;
double lvParam[3] = { 1.0, 0.005, 0.6 };
//produce time list(with even number in)
int i;
int j = 0;
for (i = 0; i <= 30; i++) {
if ((i % 2) == 0) {
myobsdata[j].time = (double) i;
j++;
}
}
//read external txt file
FILE *file = fopen("LVpreyNoise10.txt", "r");
char line[1024];
if (file == NULL) {
printf("file is null.\n");
exit(EXIT_FAILURE);
}
if (file != NULL) {
i = 0;
while (fgets(line, 1024, file)) {
myobsdata[i].rawdata = atof(line);
i++;
}
fclose(file);
}
runPmmhPath(its, lvParam, &ll, mylvstate, myobsdata);
return;
}
int main(int argc, char *argv[]) {
const gsl_rng_type * T;
long seed;
gsl_rng_env_setup();
T = gsl_rng_default;
r = gsl_rng_alloc(T);
seed = time(NULL) * getpid(); // set seed
gsl_rng_set(r, seed);
clock_t begin, end;
double time_spent;
begin = clock();
int its;
printf("Starting main...\n");
if (argc == 1) {
its = 5;
} else {
its = atoi(argv[1]);
}
runModel(its);
gsl_rng_free(r);
end = clock();
time_spent = (double)(end - begin) / CLOCKS_PER_SEC;
printf("Time consuming in total is %f\n", time_spent);
printf("Running for %i", its);
printf(" iterations, Done.");
return 0;
}
| {
"alphanum_fraction": 0.6063887878,
"avg_line_length": 25.0867579909,
"ext": "c",
"hexsha": "fc0a92ef6cd26feaa8c872f843b1d960bf8f2e90",
"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": "e1d0a15de73136355afb0e89baa5dcd8d08bad30",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "scania/scania-pmcmc",
"max_forks_repo_path": "MPI/main/bayeskit.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "e1d0a15de73136355afb0e89baa5dcd8d08bad30",
"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": "scania/scania-pmcmc",
"max_issues_repo_path": "MPI/main/bayeskit.c",
"max_line_length": 133,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "e1d0a15de73136355afb0e89baa5dcd8d08bad30",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "scania/scania-pmcmc",
"max_stars_repo_path": "MPI/main/bayeskit.c",
"max_stars_repo_stars_event_max_datetime": "2018-01-31T04:07:03.000Z",
"max_stars_repo_stars_event_min_datetime": "2018-01-31T04:07:03.000Z",
"num_tokens": 3934,
"size": 10988
} |
/* bst.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 <config.h>
#include <stdlib.h>
#include <math.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_bst.h>
#include <gsl/gsl_errno.h>
static void * bst_malloc(size_t size, void * params);
static void bst_free(void * block, void * params);
static const gsl_bst_allocator bst_default_allocator =
{
bst_malloc,
bst_free
};
/*
gsl_bst_alloc()
Allocate binary search tree
Inputs: T - tree type
allocator - memory allocator
compare - comparison function
params - parameters to pass to allocator and compare
*/
gsl_bst_workspace *
gsl_bst_alloc(const gsl_bst_type * T, const gsl_bst_allocator * allocator,
gsl_bst_cmp_function * compare, void * params)
{
int status;
gsl_bst_workspace *w;
w = calloc(1, sizeof(gsl_bst_workspace));
if (w == NULL)
{
GSL_ERROR_NULL("failed to allocate bst workspace", GSL_ENOMEM);
}
w->type = T;
status = (w->type->init)(allocator != NULL ? allocator : &bst_default_allocator, compare, params, (void *) &w->table);
if (status)
{
gsl_bst_free(w);
GSL_ERROR_NULL("failed to initialize bst", GSL_EFAILED);
}
return w;
}
void
gsl_bst_free(gsl_bst_workspace * w)
{
/* free tree nodes */
gsl_bst_empty(w);
free(w);
}
/* delete all nodes from tree */
int
gsl_bst_empty(gsl_bst_workspace * w)
{
return (w->type->empty)((void *) &w->table);
}
/*
gsl_bst_insert()
Inserts |item| into tree
AVL: if duplicate found, returns pointer to item without inserting
AVLmult: if duplicate found, increase multiplicity for that node
If no duplicate found, insert item and return pointer to item.
Returns NULL if a memory allocation error occurred.
*/
void *
gsl_bst_insert(void * item, gsl_bst_workspace * w)
{
return (w->type->insert)(item, (void *) &w->table);
}
void *
gsl_bst_find(const void * item, const gsl_bst_workspace * w)
{
return (w->type->find)(item, (const void *) &w->table);
}
void *
gsl_bst_remove(const void * item, gsl_bst_workspace * w)
{
return (w->type->remove)(item, (void *) &w->table);
}
/* return number of nodes in tree */
size_t
gsl_bst_nodes(const gsl_bst_workspace * w)
{
return (w->type->nodes)((const void *) &w->table);
}
/* return size (in bytes) of each node in tree */
size_t
gsl_bst_node_size(const gsl_bst_workspace * w)
{
return w->type->node_size;
}
const char *
gsl_bst_name(const gsl_bst_workspace * w)
{
return w->type->name;
}
/**********************************************
* INTERNAL ROUTINES *
**********************************************/
static void *
bst_malloc(size_t size, void * params)
{
(void) params; /* avoid unused parameter warning */
return malloc(size);
}
static void
bst_free(void * block, void * params)
{
(void) params; /* avoid unused parameter warning */
free(block);
}
| {
"alphanum_fraction": 0.6712821933,
"avg_line_length": 23.4480519481,
"ext": "c",
"hexsha": "b8802454fd41536e9a88d1170ddfcd364ed212d6",
"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/bst.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/bst.c",
"max_line_length": 120,
"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/bst.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": 933,
"size": 3611
} |
/*
** gsl routines for float data type
**
** G.Lohmann, July 2004
*/
#include <viaio/Vlib.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <gsl/gsl_cblas.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_blas.h>
#include <gsl/gsl_linalg.h>
#include <gsl/gsl_sort_vector.h>
#include "gsl_utils.h"
/*
** y = Ax
*/
gsl_vector_float *fmat_x_vector(gsl_matrix_float *A, gsl_vector_float *x, gsl_vector_float *y)
{
if (y == NULL) {
y = gsl_vector_float_alloc (A->size1);
}
gsl_blas_sgemv(CblasNoTrans, 1.0, A, x, 0.0, y);
return y;
}
/*
** C = A x B^T
*/
gsl_matrix_float *fmat_x_matT(gsl_matrix_float *A,gsl_matrix_float *B,gsl_matrix_float *C)
{
if (C == NULL) {
C = gsl_matrix_float_alloc( A->size1, B->size1 );
}
gsl_blas_sgemm( CblasNoTrans, CblasTrans, 1.0, A, B, 0.0, C );
return C;
}
/*
** C = A^T x B
*/
gsl_matrix_float *fmatT_x_mat(gsl_matrix_float *A,gsl_matrix_float *B,gsl_matrix_float *C)
{
if (C == NULL) {
C = gsl_matrix_float_alloc( A->size2, B->size2 );
}
gsl_blas_sgemm( CblasTrans, CblasNoTrans, 1.0, A, B, 0.0, C );
return C;
}
/*
** C = A x B
*/
gsl_matrix_float *fmat_x_mat(gsl_matrix_float *A,gsl_matrix_float *B,gsl_matrix_float *C)
{
if (C == NULL) {
C = gsl_matrix_float_alloc( A->size1, B->size2 );
}
gsl_blas_sgemm( CblasNoTrans, CblasNoTrans, 1.0, A, B, 0.0, C );
return C;
}
/*
** y = Ax, A double, x float
*/
gsl_vector_float *dmat_x_fvector(gsl_matrix *A, gsl_vector_float *x, gsl_vector_float *y)
{
int i,j,nrows,ncols;
float *ptr2,*ptr3,sum;
double *ptr1;
nrows = A->size1;
ncols = A->size2;
if (y == NULL) {
y = gsl_vector_float_alloc (nrows);
}
if (x->size != ncols || y->size != nrows) {
fprintf(stderr," fmat_x_vect: incongruent dimensions\n");
exit(0);
}
ptr1 = A->data;
ptr3 = y->data;
for (i=0; i<nrows; i++) {
sum = 0;
ptr2 = x->data;
for (j=0; j<ncols; j++) {
sum += (*ptr1++) * (*ptr2++);
}
*ptr3++ = sum;
}
return y;
}
/*
** z = x^T y
*/
float fskalarproduct(gsl_vector_float *x,gsl_vector_float *y)
{
int i,n;
float *ptr1,*ptr2,sum;
n = x->size;
if (y->size != n) {
fprintf(stderr," fskalarproduct: incongruent vector sizes: %d %ld",n,y->size);
exit(0);
}
ptr1 = x->data;
ptr2 = y->data;
sum = 0;
for (i=0; i<n; i++) {
sum += (*ptr1) * (*ptr2);
ptr1++;
ptr2++;
}
return sum;
}
/*
** printout
*/
void fmatprint(FILE *fp,gsl_matrix_float *A,const char *format)
{
int i,j;
for (i=0; i<A->size1; i++) {
for (j=0; j<A->size2; j++) {
fprintf(fp,format,fmget(A,i,j));
}
fprintf(fp,"\n");
}
fprintf(fp,"\n");
}
/*
** B = A^T
*/
gsl_matrix_float *ftranspose(gsl_matrix_float *A,gsl_matrix_float *B)
{
int i,j,n,m;
n = A->size1;
m = A->size2;
if (B == NULL) {
B = gsl_matrix_float_alloc(m,n);
}
else if (B->size1 != m || B->size2 != n) {
gsl_matrix_float_free(B);
B = gsl_matrix_float_alloc(m,n);
}
for (i=0; i<n; i++) {
for (j=0; j<m; j++) {
fmset(B,j,i,fmget(A,i,j));
}
}
return B;
}
/*
** B = A^-1 = A^+
*/
gsl_matrix_float *fmat_PseudoInv(gsl_matrix_float *A,gsl_matrix_float *B)
{
int i,j,k,l,n,m;
double u,x;
double *dbl_pp;
float *flt_pp;
m = A->size1;
n = A->size2;
if (B == NULL) {
B = gsl_matrix_float_alloc (n,m);
}
else if (B->size1 != n || B->size2 != m) {
gsl_matrix_float_free(B);
B = gsl_matrix_float_alloc (n, m);
}
gsl_matrix *U = gsl_matrix_alloc (m, n);
gsl_matrix *V = gsl_matrix_alloc (n, n);
gsl_matrix *X = gsl_matrix_alloc (n, n);
gsl_vector *w = gsl_vector_alloc (n);
gsl_vector *work = gsl_vector_alloc (n);
/* singular value decomposition */
flt_pp = A->data;
dbl_pp = U->data;
for (i=0; i<A->size1 * A->size2; i++)
*dbl_pp++ = *flt_pp++;
/* gsl_linalg_SV_decomp_jacobi(U,V,w); */
gsl_linalg_SV_decomp_mod (U,X,V,w,work);
/* check if singular */
k=0;
for (j=0; j<n; j++) {
if (fabs(w->data[j]) > 1.0e-6) k++;
}
if (k < 2) VError(" Design matrix is singular");
/* exception from Gaby */
int j0 = 0;
double xmin, xmax, tiny=10.0e-6;
xmax = gsl_vector_get(w,0);
xmin = tiny;
for (j=n-1; j >= 0; j--) {
u = gsl_vector_get(w,j);
if (u > 0 && u/xmax > tiny) {
j0 = j;
goto skip;
}
}
skip: ;
if (j0 < n-1) {
fprintf(stderr," Warning: Matrix almost singular\n");
xmin = gsl_vector_get(w,j0) - tiny;
if (xmin < 0) xmin = 0;
}
/* Fill the result matrix */
gsl_matrix_float_set_zero(B);
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) > xmin) {
x = gsl_matrix_float_get(B,k,l);
x += gsl_matrix_get(V,k,j)*gsl_matrix_get(U,l,j)/u;
gsl_matrix_float_set(B,k,l,x);
}
}
}
}
gsl_matrix_free(U);
gsl_matrix_free(V);
gsl_matrix_free(X);
gsl_vector_free(w);
gsl_vector_free(work);
return B;
}
/*
** returns the trace of a matrix M
*/
float trace(gsl_matrix_float *M)
{
gsl_vector_float_view diag = gsl_matrix_float_diagonal(M);
float sum = 0;
int i = 0;
for(i = 0; i<diag.vector.size; i++) {
sum += gsl_vector_float_get(&diag.vector,i);
}
return sum;
}
/*
** rank(A)
*/
int rank(gsl_matrix_float* mat)
{
int m = mat->size1;
int n = mat->size2;
int i;
/* Create matrix buffer from source matrix. This prevents the overwriting of
* matrix mat by gsl_linalg_SV_decomp().*/
gsl_matrix* U = gsl_matrix_alloc(m,n);
double* dpU = U->data;
float* fpMat = mat->data;
for(i=0;i<mat->size1* mat->size2;i++) {
*dpU++ = *fpMat++;
}
/* create additional matrix buffers */
gsl_matrix *V;
gsl_matrix *X;
gsl_vector *S;
gsl_vector *work;
S = gsl_vector_alloc(n);
V = gsl_matrix_alloc(n,n);
X = gsl_matrix_alloc (n, n);
work = gsl_vector_alloc (n);
/* SVD */
/* gsl_linalg_SV_decomp_jacobi(U,V,S); */
gsl_linalg_SV_decomp_mod (U,X,V,S,work);
int rank = 0;
/* counting the nonzero singular values with a tolerance of EPSILON*/
for(i=0;i<S->size;i++){
if(S->data[i] > EPSILON) {
rank++;
}
}
gsl_matrix_free(U);
gsl_matrix_free(V);
gsl_matrix_free(X);
gsl_vector_free(S);
gsl_vector_free(work);
return rank;
}
/*
** fsum
*/
gsl_vector_float *fsum(gsl_matrix_float *matrix, int dim,gsl_vector_float *v)
{
int row,col;
float sum=0;
/* build sum over all columns */
if (dim == 1) {
if (v == NULL) {
v = gsl_vector_float_alloc(matrix->size2);
}
if(v->size != matrix->size2) {
fprintf(stderr, "Warning in fsum: vector size doesn't match related matrix dimension. Resizing ..");
gsl_vector_float_free(v);
v = gsl_vector_float_alloc(matrix->size2);
}
for (col=0;col<matrix->size2;col++){
sum=0;
for(row=0;row<matrix->size1;row++) {
sum+=matrix->data[col+row*matrix->size2];
}
v->data[col] = sum;
}
}
/* build sum over all rows */
else {
if (v == NULL) {
v = gsl_vector_float_alloc(matrix->size1);
}
if (v->size != matrix->size1) {
fprintf(stderr, "Warning in fsum: vector size doesn't match related matrix dimension. Resizing ..");
gsl_vector_float_free(v);
v = gsl_vector_float_alloc(matrix->size1);
}
for (row = 0;row<matrix->size1;row++) {
sum = 0;
for(col=0;col<matrix->size2;col++) {
sum += matrix->data[col+row*matrix->size2];
}
v->data[row] = sum;
}
}
return v;
}
/*
** funique
*/
gsl_vector_float *funique(gsl_vector_float* V)
{
/* working copy */
gsl_vector_float* v = gsl_vector_float_alloc(V->size);
/* pointer to result */
gsl_vector_float* res;
/* holds value of last saved element */
float max=0;
/* counter */
int i;
gsl_vector_float_memcpy(v,V);
/* sort elements from V. */
gsl_sort_vector_float(v);
/* count number of different elements */
int nelements = 0;
/* first run: count different values */
float* p = v->data;
for(i=0;i<v->size;i++) {
/* the first element in the list is special */
if(i==0) {
max = *p;
nelements++;
}
else {
if(*p > max) {
max = *p;
nelements++;
}
}
p++;
}
/* second run: allocate mem & copy every value exactly once. */
res = gsl_vector_float_alloc(nelements);
p = v->data;
float *s = res->data;
for(i=0;i<v->size;i++) {
if(i==0) {
max = *p;
*s++ = *p;
}
else {
if(*p > max) {
max = *p;
*s++ = *p;
}
}
p++;
}
gsl_vector_float_free(v);
return res;
}
/*
** subcols
*/
gsl_matrix_float *fmat_subcols(gsl_matrix_float* mat,gsl_vector_float* cols)
{
/* some tests */
if((cols->size < 0) || (cols->size > mat->size2)) {
fprintf(stderr,"column vector: invalid dimensions");
exit(-1);
}
float min, max;
gsl_vector_float_minmax(cols, &min, &max);
if((min < 0) || (max > mat->size2)) {
fprintf(stderr,"column vector values exceed matrix dimensions!");
exit(-1);
}
/* TODO reduce column vector to unique values with funique. We will omit
* this due to performance reasons. */
/* the return value */
gsl_matrix_float* ret = gsl_matrix_float_alloc(mat->size1, cols->size);
/* the copy buffer */
gsl_vector_float* buff = gsl_vector_float_alloc(mat->size1);
/* counter */
int i;
/* copy columns from matrix to return buffer */
for (i = 0; i < cols->size; ++i) {
gsl_matrix_float_get_col(buff, mat, (int)cols->data[i]);
gsl_matrix_float_set_col(ret, i, buff);
}
gsl_vector_float_free(buff);
return ret;
}
/*
** toeplitz
*/
gsl_matrix_float *fmat_toeplitz(gsl_vector_float* v, gsl_matrix_float* A)
{
int i,j;
if(A == NULL)
A = gsl_matrix_float_alloc(v->size, v->size);
else {
if((A->size1 != v->size) || (A->size2 != v->size)) {
fprintf(stderr, "Warning fmat_toeplitz: incongruent matrix dimensions. Trying to\
correct it.");
gsl_matrix_float_free(A);
A = gsl_matrix_float_alloc(v->size, v->size);
}
}
for(i=0;i<A->size1;i++){
for(j=0;j<A->size2;j++) {
gsl_matrix_float_set(A,i,j,gsl_vector_float_get(v, fabs(i-j)));
}
}
return A;
}
/*
** A^-1
*/
gsl_matrix_float *fInv(gsl_matrix_float *M, gsl_matrix_float *result)
{
int s; /*permutation signum for LU-Decomposition*/
int i;
int m = M->size1;
int n = M->size2;
if(m != n) {
fprintf(stderr, "dInv: not a square matrix\n");
exit(0);
}
if(result == NULL) {
result = gsl_matrix_float_alloc(m,m);
}
if((result->size1 != m) || (result->size2 != n)) {
fprintf(stderr,"dInv: incongruent matrix dimensions.\n");
exit(0);
}
gsl_matrix *ludecomp = gsl_matrix_alloc(m,m);
gsl_permutation *perm = gsl_permutation_alloc(m);
gsl_matrix *res = gsl_matrix_alloc(m,m);
/* convert from float to double */
double *d_ptr = ludecomp->data;
float *f_ptr = M->data;
for(i=0;i<M->size1*M->size2;i++) {
*d_ptr = (double)*f_ptr;
d_ptr++;f_ptr++;
}
/* LU decomposition */
gsl_linalg_LU_decomp(ludecomp,perm,&s);
/* inverting matrix */
gsl_linalg_LU_invert(ludecomp,perm,res);
/* convert from double to float */
d_ptr = res->data;
f_ptr = result->data;
for(i=0;i<res->size1*res->size2;i++) {
*f_ptr = (float)*d_ptr;
d_ptr++;f_ptr++;
}
gsl_matrix_free(ludecomp);
gsl_matrix_free(res);
gsl_permutation_free(perm);
return result;
}
| {
"alphanum_fraction": 0.5812547885,
"avg_line_length": 20.2534482759,
"ext": "c",
"hexsha": "c5d5ca023b08f041ffb10c6cbf048a3d2728b350",
"lang": "C",
"max_forks_count": 8,
"max_forks_repo_forks_event_max_datetime": "2022-03-22T08:05:46.000Z",
"max_forks_repo_forks_event_min_datetime": "2017-09-29T10:33:53.000Z",
"max_forks_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "zrajna/lipsia",
"max_forks_repo_path": "src/stats/vlisa_prewhitening/gsl_futils.c",
"max_issues_count": 7,
"max_issues_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014",
"max_issues_repo_issues_event_max_datetime": "2022-02-16T13:42:05.000Z",
"max_issues_repo_issues_event_min_datetime": "2019-11-12T15:47:56.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "zrajna/lipsia",
"max_issues_repo_path": "src/stats/vlisa_prewhitening/gsl_futils.c",
"max_line_length": 106,
"max_stars_count": 17,
"max_stars_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "zrajna/lipsia",
"max_stars_repo_path": "src/stats/vlisa_prewhitening/gsl_futils.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": 3847,
"size": 11747
} |
// Copyright The Authors 2018.
// Distributed under the 3-Clause BSD License.
// (See accompanying file LICENSE or copy at
// https://opensource.org/licenses/BSD-3-Clause)
#pragma once
#include <cstdint> // for uint8_t
#include <gsl/gsl> // for gsl::span
#include <string> // for std::string
namespace blocxxi {
namespace codec {
namespace hex {
std::string Encode(gsl::span<const uint8_t> src, bool reverse = false,
bool lower_case = false);
void Decode(gsl::span<const char> src, gsl::span<uint8_t> dest,
bool reverse = false);
} // namespace hex
} // namespace codec
} // namespace blocxxi
| {
"alphanum_fraction": 0.6574923547,
"avg_line_length": 26.16,
"ext": "h",
"hexsha": "5d53872b0f1059b315917894b50c58ff3ec860c4",
"lang": "C",
"max_forks_count": 6,
"max_forks_repo_forks_event_max_datetime": "2021-11-27T19:37:05.000Z",
"max_forks_repo_forks_event_min_datetime": "2018-07-13T17:55:31.000Z",
"max_forks_repo_head_hexsha": "e0e1e629334a7959c3fb9c38567f9cf28e2cf44a",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "canhld94/blocxxi",
"max_forks_repo_path": "codec/include/codec/base16.h",
"max_issues_count": 3,
"max_issues_repo_head_hexsha": "e0e1e629334a7959c3fb9c38567f9cf28e2cf44a",
"max_issues_repo_issues_event_max_datetime": "2020-09-03T09:50:56.000Z",
"max_issues_repo_issues_event_min_datetime": "2018-06-20T08:39:12.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "canhld94/blocxxi",
"max_issues_repo_path": "codec/include/codec/base16.h",
"max_line_length": 70,
"max_stars_count": 24,
"max_stars_repo_head_hexsha": "e0e1e629334a7959c3fb9c38567f9cf28e2cf44a",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "canhld94/blocxxi",
"max_stars_repo_path": "codec/include/codec/base16.h",
"max_stars_repo_stars_event_max_datetime": "2021-01-12T07:08:26.000Z",
"max_stars_repo_stars_event_min_datetime": "2018-06-17T22:10:41.000Z",
"num_tokens": 167,
"size": 654
} |
/* -----------------------------------------------------------------------------
* Copyright 2021 Jonathan Haigh
* SPDX-License-Identifier: MIT
* ---------------------------------------------------------------------------*/
#ifndef SQ_INCLUDE_GUARD_core_errors_h_
#define SQ_INCLUDE_GUARD_core_errors_h_
#include "core/Primitive.fwd.h"
#include "core/Token.fwd.h"
#include "core/typeutil.h"
#include <cstddef>
#include <filesystem>
#include <fmt/format.h>
#include <fmt/ostream.h>
#include <gsl/gsl>
#include <stdexcept>
#include <string_view>
#include <system_error>
namespace sq {
/**
* Base class for errors thrown by the SQ code.
*/
class Exception : public std::runtime_error {
public:
using std::runtime_error::runtime_error;
};
/**
* Indicates that a required parameter of a field is missing.
*/
class ArgumentMissingError : public Exception {
public:
/**
* @param arg_name the name of the missing argument.
* @param arg_type the type of the missing argument.
*/
ArgumentMissingError(std::string_view arg_name, std::string_view arg_type);
};
/**
* Indicates that a given parameter is of incorrect type.
*/
class ArgumentTypeError : public Exception {
public:
/**
* @param received the value of the given parameter.
* @param type_expected the name of the type expected for the parameter.
*/
ArgumentTypeError(const Primitive &received, std::string_view type_expected);
};
/**
* Indicates a programming error in SQ.
*
* InternalError should never actually be thrown - they are used in places that
* the programmer believes are dead code, but where the C++ language still
* requires e.g. a return statement.
*/
class InternalError : public Exception {
public:
using Exception::Exception;
};
class InvalidConversionError : public Exception {
public:
using Exception::Exception;
InvalidConversionError(std::string_view from, std::string_view to);
};
/**
* Indicates attempted access of a non-existent field.
*/
class InvalidFieldError : public Exception {
public:
/**
* @param sq_type the SQ type of the parent of the missing field.
* @param field the name of the field that was requested.
*
* E.g. if the query is "a.b" and "b" is not a field of "a" then sq_type
* should be the type of "a" and field should be "b".
*/
InvalidFieldError(std::string_view sq_type, std::string_view field);
};
/**
* Indicates incorrect grammar in a query.
*/
class ParseError : public Exception {
public:
using Exception::Exception;
/**
* Create a ParseError for when an unexpected token is found.
*
* @param token the unexpected token.
* @param expecting the set of tokens that would have been valid in place
* of the unexpected token.
*/
ParseError(const Token &token, const TokenKindSet &expecting);
};
/**
* Indicates a failure to interpret part of the input query as a token.
*/
class LexError : public ParseError {
public:
/**
* @param pos position in the input query (in characters) at which the lex
* error occured.
* @param query the full input query.
*/
LexError(gsl::index pos, std::string_view query);
};
/**
* Indicates that an array operation has been requested on a non-array type.
*/
class NotAScalarError : public Exception {
public:
using Exception::Exception;
};
/**
* Indicates that an array operation has been requested on a non-array type.
*/
class NotAnArrayError : public Exception {
public:
using Exception::Exception;
};
/**
* Indicates that a requested feature has not been implemented.
*/
class NotImplementedError : public Exception {
public:
using Exception::Exception;
};
/**
* Indicates that a request to access an element outside of an allowed range.
*/
class OutOfRangeError : public Exception {
public:
using Exception::Exception;
/**
* @param token the token in the query where the access was requested.
* @param message details about the requested access.
*/
OutOfRangeError(const Token &token, std::string_view message);
};
/**
* Indicates that a pullup type field access has been requested for a field
* access with siblings.
*/
class PullupWithSiblingsError : public Exception {
using Exception::Exception;
};
/**
* Indicates an error was received from a system library.
*/
class SystemError : public Exception {
public:
using Exception::Exception;
/**
* Create a SystemError object.
*
* @param operation the operation that failed.
* @param code the system error code associated with the error.
*/
SystemError(std::string_view operation, std::error_code code);
/**
* Get the system error code associated with this error.
*/
SQ_ND std::error_code code() const;
private:
std::error_code code_;
};
/**
* Indicates that the udev library returned an error.
*/
class UdevError : public SystemError {
using SystemError::SystemError;
};
/**
* Indicates that a filesystem error occurred.
*/
class FilesystemError : public SystemError {
public:
using SystemError::SystemError;
/**
* Create a FilesystemError object.
*
* @param operation the operation that failed.
* @param path the path for which the operation failed.
* @param code the system error code associated with the error.
*/
FilesystemError(std::string_view operation, const std::filesystem::path &path,
std::error_code code);
};
class NarrowingError : public OutOfRangeError {
public:
using OutOfRangeError::OutOfRangeError;
NarrowingError(auto &&target, auto &&value, auto &&kind_of_value_format,
auto &&...format_args);
NarrowingError(auto &&target, auto &&value);
};
} // namespace sq
#include "core/errors.inl.h"
#endif // SQ_INCLUDE_GUARD_core_errors_h_
| {
"alphanum_fraction": 0.6935033182,
"avg_line_length": 25.2246696035,
"ext": "h",
"hexsha": "17f055743db57ed4b537f8a8ca201f724b4ad7f4",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "6ca366b86ff6436620c36eabb1f0103cab88722b",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "jonathanhaigh/sq",
"max_forks_repo_path": "src/core/include/core/errors.h",
"max_issues_count": 44,
"max_issues_repo_head_hexsha": "6ca366b86ff6436620c36eabb1f0103cab88722b",
"max_issues_repo_issues_event_max_datetime": "2021-04-05T18:51:38.000Z",
"max_issues_repo_issues_event_min_datetime": "2021-02-08T19:17:57.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "jonathanhaigh/sq",
"max_issues_repo_path": "src/core/include/core/errors.h",
"max_line_length": 80,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "6ca366b86ff6436620c36eabb1f0103cab88722b",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "jonathanhaigh/sq",
"max_stars_repo_path": "src/core/include/core/errors.h",
"max_stars_repo_stars_event_max_datetime": "2020-11-12T16:21:41.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-11-12T16:21:41.000Z",
"num_tokens": 1254,
"size": 5726
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.