Search is not available for this dataset
text string | meta dict |
|---|---|
/*
* 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 xsd_284c8467_1f5e_4ae4_b645_077382bf6ab4_h
#define xsd_284c8467_1f5e_4ae4_b645_077382bf6ab4_h
#include <gslib/config.h>
#include <gslib/xml.h>
#include <gslib/std.h>
#include <gslib/xsdtypes.h>
__gslib_begin__
//#define xsd_def_
class xsd_schema;
struct xsd_extern_schema;
class xsd_node;
class xsd_element;
class xsd_attribute;
class xsd_group;
class xsd_attribute_group;
class xsd_simple_type;
class xsd_complex_type;
typedef xml_wrapper xsd_wrapper;
typedef vector<xsd_wrapper*> xsd_wrappers;
typedef xmltree::iterator xsd_iterator;
typedef xmltree::const_iterator xsd_const_iterator;
template<class _ty>
struct xsd_schema_ns_hash:
public std::unary_function<_ty, size_t>
{
size_t operator()(_ty t) const
{
assert(t);
return string_hash(t->get_namespace());
}
};
template<class _ty>
struct xsd_schema_ns_equalto:
public std::binary_function<_ty, _ty, bool>
{
bool operator()(_ty t1, _ty t2) const
{
assert(t1 && t2);
return t1->get_namespace() == t2->get_namespace();
}
};
template<class _ty>
struct xsd_schema_loc_hash:
public std::unary_function<_ty, size_t>
{
size_t operator()(_ty t) const
{
assert(t);
return string_hash(t->get_location());
}
};
template<class _ty>
struct xsd_schema_loc_equalto:
public std::binary_function<_ty, _ty, bool>
{
bool operator()(_ty t1, _ty t2) const
{
assert(t1 && t2);
return t1->get_location() == t2->get_location();
}
};
template<class _ty>
struct xsd_name_hash:
public std::unary_function<_ty, size_t>
{
size_t operator()(_ty t) const
{
assert(t);
return string_hash(t->get_name());
}
};
template<class _ty>
struct xsd_name_equalto:
public std::binary_function<_ty, _ty, bool>
{
bool operator()(_ty t1, _ty t2) const
{
assert(t1 && t2);
return t1->get_name() == t2->get_name();
}
};
typedef vector<xsd_schema*> xsd_schemas;
typedef unordered_multiset<xsd_schema*, xsd_schema_ns_hash<xsd_schema*>, xsd_schema_ns_equalto<xsd_schema*> > xsd_schema_ns_map;
typedef unordered_set<xsd_schema*, xsd_schema_loc_hash<xsd_schema*>, xsd_schema_loc_equalto<xsd_schema*> > xsd_schema_loc_map;
typedef list<xsd_extern_schema> xsd_extern_schemas;
typedef unordered_set<xsd_node*, xsd_name_hash<xsd_node*>, xsd_name_equalto<xsd_node*> > xsd_node_map;
typedef unordered_multiset<xsd_node*, xsd_name_hash<xsd_node*>, xsd_name_equalto<xsd_node*> > xsd_node_multimap;
struct xsd_global
{
xsd_schemas packs;
xsd_schema_ns_map ns_map;
xsd_schema_loc_map loc_map;
public:
~xsd_global();
};
struct xsd_cg_config {};
extern xsd_schema* xsd_parse_schema(xsd_global& global, xmltree& dom, const gchar* location);
extern xsd_schema* xsd_parse_schema(xsd_global& global, const gchar* location);
extern void xsd_make_file_name(string& name, const string& str);
extern bool xsd_prepare_name_mangling(xsd_global& global);
extern bool xsd_prepare_translation(xsd_schema* schema, xsd_global& global);
extern bool xsd_translate_declarations(string& output, xsd_schema* schema, xsd_global& global);
extern bool xsd_translate_implementations(string& output, xsd_schema* schema, xsd_global& global);
enum xsd_extern_schema_type
{
xest_include,
xest_import,
};
enum xsd_node_type
{
xnt_key,
xnt_element,
xnt_attribute,
xnt_attribute_group,
xnt_group,
xnt_simple_type,
xnt_complex_type,
};
struct xsd_extern_schema
{
xsd_extern_schema_type type;
string ns;
xsd_schema* schema;
public:
xsd_schema* operator->() { return schema; }
const xsd_schema* operator->() const { return schema; }
};
class xsd_schema
{
protected:
xsd_wrapper* _source;
string _namespace;
string _location;
xsd_extern_schemas _external; // include & import
string _xsd_namespace;
xsd_node_map _element_map;
xsd_node_map _attribute_map;
xsd_node_map _attribute_group_map;
xsd_node_map _group_map;
xsd_node_map _simple_type_map;
xsd_node_map _complex_type_map;
public:
xsd_schema();
~xsd_schema();
const string& get_namespace() const { return _namespace; }
const string& get_location() const { return _location; }
const string& get_xsd_namespace() const { return _xsd_namespace; }
void set_namespace(const string& str) { _namespace = str; }
void set_location(const string& str) { _location = str; }
void set_xsd_namespace(const string& str) { _xsd_namespace = str; }
void set_source(xsd_wrapper* s) { _source = s; }
xsd_extern_schemas& get_extern_schemas() { return _external; }
xsd_node_map& get_element_map() { return _element_map; }
xsd_node_map& get_attribute_map() { return _attribute_map; }
xsd_node_map& get_attribute_group_map() { return _attribute_group_map; }
xsd_node_map& get_group_map() { return _group_map; }
xsd_node_map& get_simple_type_map() { return _simple_type_map; }
xsd_node_map& get_complex_type_map() { return _complex_type_map; }
protected:
static xsd_node* find_node(const xsd_node_map& m, const string& name);
template<class _node>
static _node* find_and_verify(const xsd_node_map& m, const string& n, xsd_node_type t)
{
xsd_node* r = find_node(m, n);
if(!r) return 0;
assert(r->get_type() == t);
return static_cast<_node*>(r);
}
public:
xsd_element* find_element_node(const string& name) const { return find_and_verify<xsd_element>(_element_map, name, xnt_element); }
xsd_attribute* find_attribute_node(const string& name) const { return find_and_verify<xsd_attribute>(_attribute_map, name, xnt_attribute); }
xsd_group* find_group_node(const string& name) const { return find_and_verify<xsd_group>(_group_map, name, xnt_group); }
xsd_attribute_group* find_attribute_group_node(const string& name) const { return find_and_verify<xsd_attribute_group>(_attribute_group_map, name, xnt_attribute_group); }
xsd_simple_type* find_simple_type_node(const string& name) const { return find_and_verify<xsd_simple_type>(_simple_type_map, name, xnt_simple_type); }
xsd_complex_type* find_complex_type_node(const string& name) const { return find_and_verify<xsd_complex_type>(_complex_type_map, name, xnt_complex_type); }
};
struct xsd_ns_key:
public xsd_schema
{
xsd_ns_key(const string& str) { _namespace.assign(str); }
xsd_ns_key(const gchar* str) { _namespace.assign(str); }
xsd_ns_key(const gchar* str, int len) { _namespace.assign(str, len); }
};
struct xsd_loc_key:
public xsd_schema
{
xsd_loc_key(const string& str) { _location.assign(str); }
xsd_loc_key(const gchar* str) { _location.assign(str); }
xsd_loc_key(const gchar* str, int len) { _location.assign(str, len); }
};
class __gs_novtable xsd_node abstract
{
public:
xsd_node();
virtual ~xsd_node() {}
virtual xsd_node_type get_type() const = 0;
public:
void set_name(const string& str) { _name = str; }
void set_mangling(const string& str) { _mangling = str; }
const string& get_name() const { return _name; }
const string& get_mangling() const { return _mangling; }
xsd_wrapper* get_source() const { return _source; }
void set_source(xsd_wrapper* s) { _source = s; }
void set_translated(bool b) { _translated = b; }
bool is_translated() const { return _translated; }
protected:
string _name;
string _mangling;
xsd_wrapper* _source;
bool _translated;
};
struct xsd_node_key:
public xsd_node
{
xsd_node_key(const string& str) { _name.assign(str); }
xsd_node_key(const gchar* str) { _name.assign(str); }
xsd_node_key(const gchar* str, int len) { _name.assign(str, len); }
xsd_node_type get_type() const override { return xnt_key; }
};
class xsd_element:
public xsd_node
{
public:
xsd_element();
~xsd_element();
xsd_node_type get_type() const override { return xnt_element; }
void set_ref(xsd_element* r) { _ref = r; }
xsd_element* get_ref() const { return _ref; }
void set_local_type(xsd_node* n) { _local_type = n; }
xsd_node* get_local_type() const { return _local_type; }
string& get_type_name() { return _elem_type_name; }
string& get_entity_name() { return _elem_entity_name; }
string& get_verificator() { return _elem_verificator; }
string& get_assigner() { return _elem_assigner; }
const string& const_type_name() const { return _elem_type_name; }
const string& const_entity_name() const { return _elem_entity_name; }
const string& const_verificator() const { return _elem_verificator; }
const string& const_assigner() const { return _elem_assigner; }
protected:
xsd_element* _ref;
xsd_node* _local_type;
string _elem_type_name;
string _elem_entity_name;
string _elem_verificator;
string _elem_assigner;
};
class xsd_attribute:
public xsd_node
{
public:
xsd_attribute();
~xsd_attribute();
xsd_node_type get_type() const override { return xnt_attribute; }
void set_ref(xsd_attribute* r) { _ref = 0; }
xsd_attribute* get_ref() const { return _ref; }
void set_local_type(xsd_node* n) { _local_type = 0; }
xsd_node* get_local_type() const { return _local_type; }
string& get_type_name() { return _attr_type_name; }
string& get_entity_name() { return _attr_entity_name; }
string& get_verificator() { return _attr_verificator; }
string& get_assigner() { return _attr_assigner; }
const string& const_type_name() const { return _attr_type_name; }
const string& const_entity_name() const { return _attr_entity_name; }
const string& const_verificator() const { return _attr_verificator; }
const string& const_assigner() const { return _attr_assigner; }
protected:
xsd_attribute* _ref;
xsd_node* _local_type;
string _attr_type_name;
string _attr_entity_name;
string _attr_verificator;
string _attr_assigner;
};
class xsd_group:
public xsd_node
{
public:
xsd_node_type get_type() const override { return xnt_group; }
protected:
};
class xsd_attribute_group:
public xsd_node
{
public:
xsd_node_type get_type() const override { return xnt_attribute_group; }
};
enum xsd_sts_type
{
xst_restriction,
xst_union,
xst_list,
};
class __gs_novtable xsd_st_substitution abstract
{
public:
virtual ~xsd_st_substitution() {}
virtual xsd_sts_type get_type() const = 0;
};
class xsd_st_restriction:
public xsd_st_substitution
{
public:
xsd_sts_type get_type() const override { return xst_restriction; }
protected:
};
class xsd_st_union:
public xsd_st_substitution
{
public:
xsd_sts_type get_type() const override { return xst_union; }
};
class xsd_st_list:
public xsd_st_substitution
{
public:
xsd_sts_type get_type() const override { return xst_list; }
};
class xsd_simple_type:
public xsd_node
{
public:
xsd_simple_type();
~xsd_simple_type();
xsd_node_type get_type() const override { return xnt_simple_type; }
void set_ref(xsd_simple_type* r) { _ref = r; }
xsd_simple_type* get_ref() const { return _ref; }
void set_substitution(xsd_st_substitution* sub);
bool build_assigner(string& code, const string& arg, const string& indent);
protected:
xsd_simple_type* _ref;
xsd_st_substitution* _substitution;
};
class xsd_complex_type:
public xsd_node
{
public:
xsd_node_type get_type() const override { return xnt_complex_type; }
bool build_assigner(string& code, const string& arg, const string& indent) { return false; }
};
__gslib_end__
#endif
| {
"alphanum_fraction": 0.6822832919,
"avg_line_length": 32.6539379475,
"ext": "h",
"hexsha": "3062295ae545cd86b8d0ba4ed24f68cc1eb63d1d",
"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/xsd.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/xsd.h",
"max_line_length": 175,
"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/xsd.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": 3464,
"size": 13682
} |
/* -*- linux-c -*- */
/* sigma_binsingle.c
Copyright (C) 2002-2004 John M. Fregeau
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <stdio.h>
#include <stddef.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <time.h>
#include <getopt.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_rng.h>
#include "fewbody.h"
#include "sigma_binsingle.h"
/* print the usage */
void print_usage(FILE *stream)
{
fprintf(stream, "USAGE:\n");
fprintf(stream, " sigma_binsingle [options...]\n");
fprintf(stream, "\n");
fprintf(stream, "OPTIONS:\n");
fprintf(stream, " -m --m0 <m0/MSUN> : set mass of single star [%.6g]\n", FB_M0/FB_CONST_MSUN);
fprintf(stream, " -n --m10 <m10/MSUN> : set mass of star 0 of binary [%.6g]\n", FB_M10/FB_CONST_MSUN);
fprintf(stream, " -o --m11 <m11/MSUN> : set mass of star 1 of binary [%.6g]\n", FB_M11/FB_CONST_MSUN);
fprintf(stream, " -r --r0 <r0/RSUN> : set radius of single star [%.6g]\n", FB_R0/FB_CONST_RSUN);
fprintf(stream, " -g --r10 <r10/RSUN> : set radius of star 0 of binary [%.6g]\n", FB_R10/FB_CONST_RSUN);
fprintf(stream, " -i --r11 <r11/RSUN> : set radius of star 1 of binary [%.6g]\n", FB_R11/FB_CONST_RSUN);
fprintf(stream, " -a --a1 <a1/AU> : set semimajor axis of binary [%.6g]\n", FB_A1/FB_CONST_AU);
fprintf(stream, " -e --e1 <e1> : set eccentricity of binary 0 [%.6g]\n", FB_E1);
fprintf(stream, " -v --vinf <vinf/v_crit> : set velocity at infinity [%.6g]\n", FB_VINF);
fprintf(stream, " -P --precision <dsigma/sigma> : set fractional precision on cross\n");
fprintf(stream, " section [%.6g]\n", FB_PRECISION);
fprintf(stream, " -t --tstop <tstop/t_dyn> : set stopping time [%.6g]\n", FB_TSTOP);
fprintf(stream, " -D --dt <dt/t_dyn> : set approximate output dt [%.6g]\n", FB_DT);
fprintf(stream, " -c --tcpustop <tcpustop/sec> : set cpu stopping time [%.6g]\n", FB_TCPUSTOP);
fprintf(stream, " -A --absacc <absacc> : set integrator's absolute accuracy [%.6g]\n", FB_ABSACC);
fprintf(stream, " -R --relacc <relacc> : set integrator's relative accuracy [%.6g]\n", FB_RELACC);
fprintf(stream, " -N --ncount <ncount> : set number of integration steps between calls\n");
fprintf(stream, " to fb_classify() [%d]\n", FB_NCOUNT);
fprintf(stream, " -z --tidaltol <tidaltol> : set tidal tolerance [%.6g]\n", FB_TIDALTOL);
fprintf(stream, " -x --fexp <f_exp> : set expansion factor of merger product [%.6g]\n", FB_FEXP);
fprintf(stream, " -k --ks : turn K-S regularization on or off [%d]\n", FB_KS);
fprintf(stream, " -s --seed : set random seed [%ld]\n", FB_SEED);
fprintf(stream, " -d --debug : turn on debugging\n");
fprintf(stream, " -V --version : print version info\n");
fprintf(stream, " -h --help : display this help text\n");
}
/* calculate the units used */
int calc_units(fb_obj_t *obj[2], fb_units_t *units)
{
units->v = sqrt(FB_CONST_G*(obj[0]->m + obj[1]->m)/(obj[0]->m * obj[1]->m) * \
(obj[1]->obj[0]->m * obj[1]->obj[1]->m / obj[1]->a));
units->l = obj[1]->a;
units->t = units->l / units->v;
units->m = units->l * fb_sqr(units->v) / FB_CONST_G;
units->E = units->m * fb_sqr(units->v);
return(0);
}
/* the main attraction */
int main(int argc, char *argv[])
{
int i, j, k, res, err, sid, bid, precisionmet=0;
long l, nb;
unsigned long int seed;
double m0, m10, m11, r0, r10, r11, a1, e1, precision;
double rtid, vinf, rperi, b, b0, bmin, bmax, db, bxlast, t, vc;
fb_sigma_t sigmacurr[11], sigmaprev[11];
char outcome[11][FB_MAX_STRING_LENGTH];
/* char string1[FB_MAX_STRING_LENGTH], string2[FB_MAX_STRING_LENGTH]; */
fb_hier_t hier;
fb_input_t input;
fb_ret_t retval;
fb_units_t units;
gsl_rng *rng;
const gsl_rng_type *rng_type=gsl_rng_mt19937;
const char *short_opts = "m:n:o:r:g:i:a:e:v:P:t:D:c:A:R:N:z:x:k:s:dVh";
const struct option long_opts[] = {
{"m0", required_argument, NULL, 'm'},
{"m10", required_argument, NULL, 'n'},
{"m11", required_argument, NULL, 'o'},
{"r0", required_argument, NULL, 'r'},
{"r10", required_argument, NULL, 'g'},
{"r11", required_argument, NULL, 'i'},
{"a1", required_argument, NULL, 'a'},
{"e1", required_argument, NULL, 'e'},
{"vinf", required_argument, NULL, 'v'},
{"precision", required_argument, NULL, 'P'},
{"tstop", required_argument, NULL, 't'},
{"dt", required_argument, NULL, 'D'},
{"tcpustop", required_argument, NULL, 'c'},
{"absacc", required_argument, NULL, 'A'},
{"relacc", required_argument, NULL, 'R'},
{"ncount", required_argument, NULL, 'N'},
{"tidaltol", required_argument, NULL, 'z'},
{"fexp", required_argument, NULL, 'x'},
{"ks", required_argument, NULL, 'k'},
{"seed", required_argument, NULL, 's'},
{"debug", no_argument, NULL, 'd'},
{"version", no_argument, NULL, 'V'},
{"help", no_argument, NULL, 'h'},
{NULL, 0, NULL, 0}
};
/* set parameters to default values */
m0 = FB_M0;
m10 = FB_M10;
m11 = FB_M11;
r0 = FB_R0;
r10 = FB_R10;
r11 = FB_R11;
a1 = FB_A1;
e1 = FB_E1;
vinf = FB_VINF;
precision = 1.0e-2;
input.ks = FB_KS;
input.tstop = FB_TSTOP;
input.Dflag = 0;
input.dt = FB_DT;
input.tcpustop = FB_TCPUSTOP;
input.absacc = FB_ABSACC;
input.relacc = FB_RELACC;
input.ncount = FB_NCOUNT;
input.tidaltol = FB_TIDALTOL;
input.fexp = FB_FEXP;
seed = FB_SEED;
fb_debug = FB_DEBUG;
while ((i = getopt_long(argc, argv, short_opts, long_opts, NULL)) != -1) {
switch (i) {
case 'm':
m0 = atof(optarg) * FB_CONST_MSUN;
break;
case 'n':
m10 = atof(optarg) * FB_CONST_MSUN;
break;
case 'o':
m11 = atof(optarg) * FB_CONST_MSUN;
break;
case 'r':
r0 = atof(optarg) * FB_CONST_RSUN;
break;
case 'g':
r10 = atof(optarg) * FB_CONST_RSUN;
break;
case 'i':
r11 = atof(optarg) * FB_CONST_RSUN;
break;
case 'a':
a1 = atof(optarg) * FB_CONST_AU;
break;
case 'e':
e1 = atof(optarg);
if (e1 >= 1.0) {
fprintf(stderr, "e0 must be less than 1\n");
return(1);
}
break;
case 'v':
vinf = atof(optarg);
if (vinf < 0.0) {
fprintf(stderr, "vinf must be non-negative\n");
return(1);
}
break;
case 'P':
precision = atof(optarg);
if (precision <= 0.0) {
fprintf(stderr, "precision must be > 0\n");
return(1);
} else if (precision > 1.0) {
fprintf(stderr, "precision must be < 1\n");
return(1);
}
break;
case 't':
input.tstop = atof(optarg);
break;
case 'D':
input.Dflag = 1;
input.dt = atof(optarg);
break;
case 'c':
input.tcpustop = atof(optarg);
break;
case 'A':
input.absacc = atof(optarg);
break;
case 'R':
input.relacc = atof(optarg);
break;
case 'N':
input.ncount = atoi(optarg);
break;
case 'z':
input.tidaltol = atof(optarg);
break;
case 'x':
input.fexp = atof(optarg);
break;
case 'k':
input.ks = atoi(optarg);
break;
case 's':
seed = atol(optarg);
break;
case 'd':
fb_debug = 1;
break;
case 'V':
fb_print_version(stdout);
return(0);
case 'h':
fb_print_version(stdout);
fprintf(stdout, "\n");
print_usage(stdout);
return(0);
default:
break;
}
}
/* check to make sure there was nothing crazy on the command line */
if (optind < argc) {
print_usage(stdout);
return(1);
}
/* initialize a few things for integrator */
hier.nstarinit = 3;
fb_malloc_hier(&hier);
/* initialize GSL rng */
gsl_rng_env_setup();
rng = gsl_rng_alloc(rng_type);
gsl_rng_set(rng, seed);
/* zero everything out before summing */
for (i=0; i<11; i++) {
sigmacurr[i].sigma_r = 0.0;
sigmacurr[i].dsigma2_r_minus = 0.0;
sigmacurr[i].dsigma2_r_plus = 0.0;
sigmacurr[i].sigma_nr = 0.0;
sigmacurr[i].dsigma2_nr_minus = 0.0;
sigmacurr[i].dsigma2_nr_plus = 0.0;
sigmaprev[i].sigma_r = 0.0;
sigmaprev[i].dsigma2_r_minus = 0.0;
sigmaprev[i].dsigma2_r_plus = 0.0;
sigmaprev[i].sigma_nr = 0.0;
sigmaprev[i].dsigma2_nr_minus = 0.0;
sigmaprev[i].dsigma2_nr_plus = 0.0;
}
/* loop through and calcluate cross sections */
nb = (long) (1.0/precision);
while (!precisionmet) {
/* select b0 that gives r_p=2a */
vc = sqrt(FB_CONST_G * (m0+m10+m11) / (m0*(m10+m11)) * (m10*m11/a1));
rperi = 2.0 * a1;
/* b0 is in code units here (vinf is in units of vc) */
b0 = sqrt(fb_sqr(rperi) + 2.0 * FB_CONST_G * (m0+m10+m11) * rperi / fb_sqr(vinf*vc)) / a1;
db = b0/((double) nb);
bxlast = GSL_POSINF;
l = 0;
bmin = ((double) l) * db;
bmax = bmin + db;
while (bmax <= b0 || bmax <= 2.0*bxlast) {
bmin = ((double) l) * db;
bmax = bmin + db;
/* choose b uniformly in area from bmin to bmax */
b = sqrt(gsl_rng_uniform(rng) * (fb_sqr(bmax)-fb_sqr(bmin)) + fb_sqr(bmin));
/* do scattering experiment */
/* initialize a few things for integrator */
t = 0.0;
hier.nstar = 3;
fb_init_hier(&hier);
/* create binary */
hier.hier[hier.hi[2]+0].obj[0] = &(hier.hier[hier.hi[1]+1]);
hier.hier[hier.hi[2]+0].obj[1] = &(hier.hier[hier.hi[1]+2]);
hier.hier[hier.hi[2]+0].t = t;
/* give the objects some properties */
for (j=0; j<hier.nstar; j++) {
hier.hier[hier.hi[1]+j].ncoll = 1;
hier.hier[hier.hi[1]+j].id[0] = j;
snprintf(hier.hier[hier.hi[1]+j].idstring, FB_MAX_STRING_LENGTH, "%d", j);
hier.hier[hier.hi[1]+j].n = 1;
hier.hier[hier.hi[1]+j].obj[0] = NULL;
hier.hier[hier.hi[1]+j].obj[1] = NULL;
hier.hier[hier.hi[1]+j].Eint = 0.0;
hier.hier[hier.hi[1]+j].Lint[0] = 0.0;
hier.hier[hier.hi[1]+j].Lint[1] = 0.0;
hier.hier[hier.hi[1]+j].Lint[2] = 0.0;
}
hier.hier[hier.hi[1]+0].R = r0;
hier.hier[hier.hi[1]+1].R = r10;
hier.hier[hier.hi[1]+2].R = r11;
hier.hier[hier.hi[1]+0].m = m0;
hier.hier[hier.hi[1]+1].m = m10;
hier.hier[hier.hi[1]+2].m = m11;
hier.hier[hier.hi[2]+0].m = m10 + m11;
hier.hier[hier.hi[2]+0].a = a1;
hier.hier[hier.hi[2]+0].e = e1;
hier.obj[0] = &(hier.hier[hier.hi[1]+0]);
hier.obj[1] = &(hier.hier[hier.hi[2]+0]);
hier.obj[2] = NULL;
/* get the units and normalize */
calc_units(hier.obj, &units);
fb_normalize(&hier, units);
/* move hierarchies analytically in from infinity along hyperbolic orbit */
rtid = pow(2.0*(hier.obj[0]->m + hier.obj[1]->m) / (hier.obj[1]->m * input.tidaltol), 1.0/3.0) *
hier.obj[1]->a * (1.0 + hier.obj[1]->e);
fb_init_scattering(hier.obj[0], hier.obj[1], vinf, b, rtid);
/* trickle down the binary properties, then back up */
fb_randorient(&(hier.hier[hier.hi[2]+0]), rng);
fb_downsync(&(hier.hier[hier.hi[2]+0]), t);
/* fb_upsync(&(hier.hier[hier.hi[2]+0]), t); */
/* call fewbody! */
retval = fewbody(input, &hier, &t);
k = -1;
res = 0;
err = 0;
/* analyze outcome */
if (retval.retval == 1 &&
FB_MIN(fabs(retval.DeltaEfrac), fabs(retval.DeltaE)) <= 1.0e-4 &&
FB_MIN(fabs(retval.DeltaLfrac), fabs(retval.DeltaL)) <= 1.0e-4) {
/* check for resonance */
if (retval.Nosc >= 1) {
res = 1;
} else {
res = 0;
}
/* classify outcome */
if (hier.nstar == 3) {
if (hier.nobj == 1) {
/* triples physically forbidden */
err = 1;
} else if (hier.nobj == 2) {
if (fb_n_hier(hier.obj[0])==2) {
bid = 0;
sid = 1;
} else {
bid = 1;
sid = 0;
}
if (hier.obj[sid]->id[0] == 0) {
k = 0;
} else if (hier.obj[sid]->id[0] == 1) {
k = 1;
} else {
k = 2;
}
} else { /* hier.nobj == 3 */
k = 3;
}
} else if (hier.nstar == 2) {
if (hier.nobj == 1) {
if ((hier.obj[0]->obj[0]->ncoll==1 && hier.obj[0]->obj[0]->id[0]==0) ||
(hier.obj[0]->obj[1]->ncoll==1 && hier.obj[0]->obj[1]->id[0]==0)) {
k = 4;
} else if ((hier.obj[0]->obj[0]->ncoll==1 && hier.obj[0]->obj[0]->id[0]==1) ||
(hier.obj[0]->obj[1]->ncoll==1 && hier.obj[0]->obj[1]->id[0]==1)) {
k = 5;
} else {
k = 6;
}
} else { /* hier.nobj == 2 */
if ((hier.obj[0]->ncoll==1 && hier.obj[0]->id[0]==0) ||
(hier.obj[1]->ncoll==1 && hier.obj[1]->id[0]==0)) {
k = 7;
} else if ((hier.obj[0]->ncoll==1 && hier.obj[0]->id[0]==1) ||
(hier.obj[1]->ncoll==1 && hier.obj[1]->id[0]==1)) {
k = 8;
} else {
k = 9;
}
}
} else if (hier.nstar == 1) {
k = 10;
} else {
fprintf(stderr, "ERROR: hier.nstar!=1,2,3!\n");
exit(1);
}
} else { /* bad outcome */
err = 1;
}
/* tally up cross sections */
if (!err) {
for (i=0; i<11; i++) {
if (i==k) {
if (res) {
sigmacurr[i].sigma_r += FB_CONST_PI * (fb_sqr(bmax)-fb_sqr(bmin));
sigmacurr[i].dsigma2_r_minus += fb_sqr(0.1587 * FB_CONST_PI * (fb_sqr(bmax)-fb_sqr(bmin)));
sigmacurr[i].dsigma2_nr_plus += fb_sqr(0.8413/21.0 * FB_CONST_PI * (fb_sqr(bmax)-fb_sqr(bmin)));
} else {
sigmacurr[i].sigma_nr += FB_CONST_PI * (fb_sqr(bmax)-fb_sqr(bmin));
sigmacurr[i].dsigma2_nr_minus += fb_sqr(0.1587 * FB_CONST_PI * (fb_sqr(bmax)-fb_sqr(bmin)));
sigmacurr[i].dsigma2_r_plus += fb_sqr(0.8413/21.0 * FB_CONST_PI * (fb_sqr(bmax)-fb_sqr(bmin)));
}
} else {
sigmacurr[i].dsigma2_r_plus += fb_sqr(0.8413/21.0 * FB_CONST_PI * (fb_sqr(bmax)-fb_sqr(bmin)));
sigmacurr[i].dsigma2_nr_plus += fb_sqr(0.8413/21.0 * FB_CONST_PI * (fb_sqr(bmax)-fb_sqr(bmin)));
}
}
} else {
for (i=0; i<11; i++) {
sigmacurr[i].dsigma2_r_plus += fb_sqr(0.8413/22.0 * FB_CONST_PI * (fb_sqr(bmax)-fb_sqr(bmin)));
sigmacurr[i].dsigma2_nr_plus += fb_sqr(0.8413/22.0 * FB_CONST_PI * (fb_sqr(bmax)-fb_sqr(bmin)));
}
}
/* if the outcome was not a weak flyby, then record last impact parameter */
if (!err && (k!=0 || (k==0 && res))) {
bxlast = bmax;
}
/*
fprintf(stderr, "outcome: retval=%d %s (%s)\n", retval.retval,
fb_sprint_hier(hier, string1), fb_sprint_hier_hr(hier, string2));
fprintf(stderr, " DeltaL/L0=%.6g DeltaL=%.6g\n", retval.DeltaLfrac, retval.DeltaL);
fprintf(stderr, " DeltaE/E0=%.6g DeltaE=%.6g\n", retval.DeltaEfrac, retval.DeltaE);
fprintf(stderr, " l=%ld b0=%g bmin=%g bmax=%g bxlast=%g k=%d res=%d err=%d\n", l, b0, bmin, bmax, bxlast, k, res, err);
*/
l++;
}
/* add current and previous sigmas, and transfer current to previous */
/* increase resolution geometrically */
nb *= 2;
precisionmet = 1;
}
snprintf(outcome[0], FB_MAX_STRING_LENGTH, "[1 2] 0 (preservation)");
snprintf(outcome[1], FB_MAX_STRING_LENGTH, "[0 2] 1 (exchange_1)");
snprintf(outcome[2], FB_MAX_STRING_LENGTH, "[0 1] 2 (exchange_2)");
snprintf(outcome[3], FB_MAX_STRING_LENGTH, "0 1 2 (ionization)");
snprintf(outcome[4], FB_MAX_STRING_LENGTH, "[1:2 0] (merger_binary_12)");
snprintf(outcome[5], FB_MAX_STRING_LENGTH, "[0:2 1] (merger_binary_02)");
snprintf(outcome[6], FB_MAX_STRING_LENGTH, "[0:1 2] (merger_binary_01)");
snprintf(outcome[7], FB_MAX_STRING_LENGTH, "1:2 0 (merger_12)");
snprintf(outcome[8], FB_MAX_STRING_LENGTH, "0:2 1 (merger_02)");
snprintf(outcome[9], FB_MAX_STRING_LENGTH, "0:1 2 (merger_01)");
snprintf(outcome[10], FB_MAX_STRING_LENGTH, "0:1:2 (triple_merger)");
/* precision has now been met, so print out results */
fprintf(stdout, "outcome sigma_r dsigma_r_minus dsigma_r_plus sigma_nr dsigma_nr_minus dsigma_nr_plus\n");
for (i=0; i<11; i++) {
fprintf(stdout, "%27s %6.6g %6.6g %6.6g %6.6g %6.6g %6.6g\n", outcome[i],
sigmacurr[i].sigma_r/FB_CONST_PI,
sqrt(sigmacurr[i].dsigma2_r_minus)/FB_CONST_PI,
sqrt(sigmacurr[i].dsigma2_r_plus)/FB_CONST_PI,
sigmacurr[i].sigma_nr/FB_CONST_PI,
sqrt(sigmacurr[i].dsigma2_nr_minus)/FB_CONST_PI,
sqrt(sigmacurr[i].dsigma2_nr_plus)/FB_CONST_PI);
}
/* free GSL stuff */
gsl_rng_free(rng);
/* free our own stuff */
fb_free_hier(hier);
/* done! */
return(0);
}
| {
"alphanum_fraction": 0.5908176547,
"avg_line_length": 33.6023856859,
"ext": "c",
"hexsha": "87d3c1d3a3c92e8c97f9e4383ed1967c7bf954ac",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "3612456fc2042519f96a49e4d4cc6d3c1f41de7c",
"max_forks_repo_licenses": [
"PSF-2.0"
],
"max_forks_repo_name": "gnodvi/cosmos",
"max_forks_repo_path": "ext/fewbod/fewbody-0.26/sigma_binsingle.c",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "3612456fc2042519f96a49e4d4cc6d3c1f41de7c",
"max_issues_repo_issues_event_max_datetime": "2021-12-13T20:35:46.000Z",
"max_issues_repo_issues_event_min_datetime": "2021-12-13T20:35:46.000Z",
"max_issues_repo_licenses": [
"PSF-2.0"
],
"max_issues_repo_name": "gnodvi/cosmos",
"max_issues_repo_path": "ext/fewbod/fewbody-0.26/sigma_binsingle.c",
"max_line_length": 123,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "3612456fc2042519f96a49e4d4cc6d3c1f41de7c",
"max_stars_repo_licenses": [
"PSF-2.0"
],
"max_stars_repo_name": "gnodvi/cosmos",
"max_stars_repo_path": "ext/fewbod/fewbody-0.26/sigma_binsingle.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 6034,
"size": 16902
} |
/* vector/gsl_vector_uchar.h
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Gerard Jungman, Brian Gough
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#ifndef __GSL_VECTOR_UCHAR_H__
#define __GSL_VECTOR_UCHAR_H__
#if !defined( GSL_FUN )
# if !defined( GSL_DLL )
# define GSL_FUN extern
# elif defined( BUILD_GSL_DLL )
# define GSL_FUN extern __declspec(dllexport)
# else
# define GSL_FUN extern __declspec(dllimport)
# endif
#endif
#include <stdlib.h>
#include <gsl/gsl_types.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_inline.h>
#include <gsl/gsl_check_range.h>
#include <gsl/gsl_block_uchar.h>
#undef __BEGIN_DECLS
#undef __END_DECLS
#ifdef __cplusplus
# define __BEGIN_DECLS extern "C" {
# define __END_DECLS }
#else
# define __BEGIN_DECLS /* empty */
# define __END_DECLS /* empty */
#endif
__BEGIN_DECLS
typedef struct
{
size_t size;
size_t stride;
unsigned char *data;
gsl_block_uchar *block;
int owner;
}
gsl_vector_uchar;
typedef struct
{
gsl_vector_uchar vector;
} _gsl_vector_uchar_view;
typedef _gsl_vector_uchar_view gsl_vector_uchar_view;
typedef struct
{
gsl_vector_uchar vector;
} _gsl_vector_uchar_const_view;
typedef const _gsl_vector_uchar_const_view gsl_vector_uchar_const_view;
/* Allocation */
GSL_FUN gsl_vector_uchar *gsl_vector_uchar_alloc (const size_t n);
GSL_FUN gsl_vector_uchar *gsl_vector_uchar_calloc (const size_t n);
GSL_FUN gsl_vector_uchar *gsl_vector_uchar_alloc_from_block (gsl_block_uchar * b,
const size_t offset,
const size_t n,
const size_t stride);
GSL_FUN gsl_vector_uchar *gsl_vector_uchar_alloc_from_vector (gsl_vector_uchar * v,
const size_t offset,
const size_t n,
const size_t stride);
GSL_FUN void gsl_vector_uchar_free (gsl_vector_uchar * v);
/* Views */
GSL_FUN _gsl_vector_uchar_view
gsl_vector_uchar_view_array (unsigned char *v, size_t n);
GSL_FUN _gsl_vector_uchar_view
gsl_vector_uchar_view_array_with_stride (unsigned char *base,
size_t stride,
size_t n);
GSL_FUN _gsl_vector_uchar_const_view
gsl_vector_uchar_const_view_array (const unsigned char *v, size_t n);
GSL_FUN _gsl_vector_uchar_const_view
gsl_vector_uchar_const_view_array_with_stride (const unsigned char *base,
size_t stride,
size_t n);
GSL_FUN _gsl_vector_uchar_view
gsl_vector_uchar_subvector (gsl_vector_uchar *v,
size_t i,
size_t n);
GSL_FUN _gsl_vector_uchar_view
gsl_vector_uchar_subvector_with_stride (gsl_vector_uchar *v,
size_t i,
size_t stride,
size_t n);
GSL_FUN _gsl_vector_uchar_const_view
gsl_vector_uchar_const_subvector (const gsl_vector_uchar *v,
size_t i,
size_t n);
GSL_FUN _gsl_vector_uchar_const_view
gsl_vector_uchar_const_subvector_with_stride (const gsl_vector_uchar *v,
size_t i,
size_t stride,
size_t n);
/* Operations */
GSL_FUN void gsl_vector_uchar_set_zero (gsl_vector_uchar * v);
GSL_FUN void gsl_vector_uchar_set_all (gsl_vector_uchar * v, unsigned char x);
GSL_FUN int gsl_vector_uchar_set_basis (gsl_vector_uchar * v, size_t i);
GSL_FUN int gsl_vector_uchar_fread (FILE * stream, gsl_vector_uchar * v);
GSL_FUN int gsl_vector_uchar_fwrite (FILE * stream, const gsl_vector_uchar * v);
GSL_FUN int gsl_vector_uchar_fscanf (FILE * stream, gsl_vector_uchar * v);
GSL_FUN int gsl_vector_uchar_fprintf (FILE * stream, const gsl_vector_uchar * v,
const char *format);
GSL_FUN int gsl_vector_uchar_memcpy (gsl_vector_uchar * dest, const gsl_vector_uchar * src);
GSL_FUN int gsl_vector_uchar_reverse (gsl_vector_uchar * v);
GSL_FUN int gsl_vector_uchar_swap (gsl_vector_uchar * v, gsl_vector_uchar * w);
GSL_FUN int gsl_vector_uchar_swap_elements (gsl_vector_uchar * v, const size_t i, const size_t j);
GSL_FUN unsigned char gsl_vector_uchar_max (const gsl_vector_uchar * v);
GSL_FUN unsigned char gsl_vector_uchar_min (const gsl_vector_uchar * v);
GSL_FUN void gsl_vector_uchar_minmax (const gsl_vector_uchar * v, unsigned char * min_out, unsigned char * max_out);
GSL_FUN size_t gsl_vector_uchar_max_index (const gsl_vector_uchar * v);
GSL_FUN size_t gsl_vector_uchar_min_index (const gsl_vector_uchar * v);
GSL_FUN void gsl_vector_uchar_minmax_index (const gsl_vector_uchar * v, size_t * imin, size_t * imax);
GSL_FUN int gsl_vector_uchar_add (gsl_vector_uchar * a, const gsl_vector_uchar * b);
GSL_FUN int gsl_vector_uchar_sub (gsl_vector_uchar * a, const gsl_vector_uchar * b);
GSL_FUN int gsl_vector_uchar_mul (gsl_vector_uchar * a, const gsl_vector_uchar * b);
GSL_FUN int gsl_vector_uchar_div (gsl_vector_uchar * a, const gsl_vector_uchar * b);
GSL_FUN int gsl_vector_uchar_scale (gsl_vector_uchar * a, const unsigned char x);
GSL_FUN int gsl_vector_uchar_add_constant (gsl_vector_uchar * a, const double x);
GSL_FUN int gsl_vector_uchar_axpby (const unsigned char alpha, const gsl_vector_uchar * x, const unsigned char beta, gsl_vector_uchar * y);
GSL_FUN unsigned char gsl_vector_uchar_sum (const gsl_vector_uchar * a);
GSL_FUN int gsl_vector_uchar_equal (const gsl_vector_uchar * u,
const gsl_vector_uchar * v);
GSL_FUN int gsl_vector_uchar_isnull (const gsl_vector_uchar * v);
GSL_FUN int gsl_vector_uchar_ispos (const gsl_vector_uchar * v);
GSL_FUN int gsl_vector_uchar_isneg (const gsl_vector_uchar * v);
GSL_FUN int gsl_vector_uchar_isnonneg (const gsl_vector_uchar * v);
GSL_FUN INLINE_DECL unsigned char gsl_vector_uchar_get (const gsl_vector_uchar * v, const size_t i);
GSL_FUN INLINE_DECL void gsl_vector_uchar_set (gsl_vector_uchar * v, const size_t i, unsigned char x);
GSL_FUN INLINE_DECL unsigned char * gsl_vector_uchar_ptr (gsl_vector_uchar * v, const size_t i);
GSL_FUN INLINE_DECL const unsigned char * gsl_vector_uchar_const_ptr (const gsl_vector_uchar * v, const size_t i);
#ifdef HAVE_INLINE
INLINE_FUN
unsigned char
gsl_vector_uchar_get (const gsl_vector_uchar * v, const size_t i)
{
#if GSL_RANGE_CHECK
if (GSL_RANGE_COND(i >= v->size))
{
GSL_ERROR_VAL ("index out of range", GSL_EINVAL, 0);
}
#endif
return v->data[i * v->stride];
}
INLINE_FUN
void
gsl_vector_uchar_set (gsl_vector_uchar * v, const size_t i, unsigned char x)
{
#if GSL_RANGE_CHECK
if (GSL_RANGE_COND(i >= v->size))
{
GSL_ERROR_VOID ("index out of range", GSL_EINVAL);
}
#endif
v->data[i * v->stride] = x;
}
INLINE_FUN
unsigned char *
gsl_vector_uchar_ptr (gsl_vector_uchar * v, const size_t i)
{
#if GSL_RANGE_CHECK
if (GSL_RANGE_COND(i >= v->size))
{
GSL_ERROR_NULL ("index out of range", GSL_EINVAL);
}
#endif
return (unsigned char *) (v->data + i * v->stride);
}
INLINE_FUN
const unsigned char *
gsl_vector_uchar_const_ptr (const gsl_vector_uchar * v, const size_t i)
{
#if GSL_RANGE_CHECK
if (GSL_RANGE_COND(i >= v->size))
{
GSL_ERROR_NULL ("index out of range", GSL_EINVAL);
}
#endif
return (const unsigned char *) (v->data + i * v->stride);
}
#endif /* HAVE_INLINE */
__END_DECLS
#endif /* __GSL_VECTOR_UCHAR_H__ */
| {
"alphanum_fraction": 0.6755484093,
"avg_line_length": 35.8312757202,
"ext": "h",
"hexsha": "2a0d6135ea6db008f45fa78895646856f3353fab",
"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_vector_uchar.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_vector_uchar.h",
"max_line_length": 140,
"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_vector_uchar.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": 2159,
"size": 8707
} |
/* ieee-utils/fp-aix.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 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 <math.h>
#include <fptrap.h>
#include <float.h>
#include <gsl/gsl_ieee_utils.h>
#include <gsl/gsl_errno.h>
int
gsl_ieee_set_mode (int precision, int rounding, int exception_mask)
{
fptrap_t mode = 0 ;
fprnd_t rnd = 0 ;
switch (precision)
{
/* I'm not positive about AIX only supporting default precision rounding,
* but this is the best assumption until it's proven otherwise. */
case GSL_IEEE_SINGLE_PRECISION:
GSL_ERROR ("AIX only supports default precision rounding",
GSL_EUNSUP) ;
break ;
case GSL_IEEE_DOUBLE_PRECISION:
GSL_ERROR ("AIX only supports default precision rounding",
GSL_EUNSUP) ;
break ;
case GSL_IEEE_EXTENDED_PRECISION:
GSL_ERROR ("AIX only supports default precision rounding",
GSL_EUNSUP) ;
break ;
}
switch (rounding)
{
case GSL_IEEE_ROUND_TO_NEAREST:
rnd = FP_RND_RN ;
fp_swap_rnd (rnd) ;
break ;
case GSL_IEEE_ROUND_DOWN:
rnd = FP_RND_RM ;
fp_swap_rnd (rnd) ;
break ;
case GSL_IEEE_ROUND_UP:
rnd = FP_RND_RP ;
fp_swap_rnd (rnd) ;
break ;
case GSL_IEEE_ROUND_TO_ZERO:
rnd = FP_RND_RZ ;
fp_swap_rnd (rnd) ;
break ;
default:
rnd = FP_RND_RN ;
fp_swap_rnd (rnd) ;
}
/* Turn on all the exceptions apart from 'inexact' */
mode = TRP_INVALID | TRP_DIV_BY_ZERO | TRP_OVERFLOW | TRP_UNDERFLOW ;
if (exception_mask & GSL_IEEE_MASK_INVALID)
mode &= ~ TRP_INVALID ;
if (exception_mask & GSL_IEEE_MASK_DENORMALIZED)
{
/* do nothing */
}
else
{
GSL_ERROR ("AIX does not support the denormalized operand exception. "
"Use 'mask-denormalized' to work around this.",
GSL_EUNSUP) ;
}
if (exception_mask & GSL_IEEE_MASK_DIVISION_BY_ZERO)
mode &= ~ TRP_DIV_BY_ZERO ;
if (exception_mask & GSL_IEEE_MASK_OVERFLOW)
mode &= ~ TRP_OVERFLOW ;
if (exception_mask & GSL_IEEE_MASK_UNDERFLOW)
mode &= ~ TRP_UNDERFLOW ;
if (exception_mask & GSL_IEEE_TRAP_INEXACT)
{
mode |= TRP_INEXACT ;
}
else
{
mode &= ~ TRP_INEXACT ;
}
/* AIX appears to require two steps -- first enable floating point traps
* in general... */
fp_trap(FP_TRAP_SYNC);
/* next, enable the traps we're interested in */
fp_enable(mode);
return GSL_SUCCESS ;
}
| {
"alphanum_fraction": 0.6574159729,
"avg_line_length": 26.8016528926,
"ext": "c",
"hexsha": "9933f8faf94aaa8843105f2e5dc37fd62af99881",
"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/ieee-utils/fp-aix.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/ieee-utils/fp-aix.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/ieee-utils/fp-aix.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": 857,
"size": 3243
} |
/* Original simple matrix class taken from http://www.algarcia.org/nummeth/Cpp/Matrix.h */
#ifndef MATRIX_H
#define MATRIX_H
#include <assert.h> // Defines the assert function.
//#define assert(x) {} //to avoid bound checking
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_blas.h>
#include <gsl/gsl_linalg.h>
#include <gsl/gsl_errno.h>
#include <string.h>
#include <stdio.h>
#define BUFF_SIZE 4096
class Matrix {
public:
// Default Constructor. Creates a 1 by 1 matrix; sets value to zero.
Matrix () {
ma = gsl_matrix_alloc( 1, 1);// Allocate memory
ve.owner = 0;
ve.block = ma->block;
set(0.0); // Set value of data_[0] to 0.0
header = NULL;
}
// Regular Constructor. Creates an nR by nC matrix; sets values to zero.
// If number of columns is not specified, it is set to 1.
Matrix(int nR, int nC = 1, char *head=NULL) {
assert(nR > 0 && nC > 0); // Check that nC and nR both > 0.
ma = gsl_matrix_alloc( nR, nC);// Allocate memory
ve.owner = 0;
ve.block = ma->block;
set(0.0); // Set values of data_[] to 0.0
if (head != NULL)
header = strdup(head);
else
header = NULL;
}
//copy constructor
Matrix(Matrix &mat) {
printf("Matrix::Matrix 2 ...\n");
ma = gsl_matrix_alloc( mat.nRow(), mat.nCol());// Allocate memory
ve.owner = 0;
ve.block = ma->block;
copy(mat);
if (mat.Header() != NULL)
header = strdup(mat.Header());
else
header = NULL;
}
//Identity (preferably square) matrix
void Iden() {
//assert(nRow() == nCol()); // Check that square matrix.
set(0.0); // Set values of data_[] to 0.0
for (int i=0; i<nRow(); i++)
ma->data[ (ma->tda)*i + i] = 1.0;
}
// Destructor. Called when a Matrix object goes out of scope or deleted.
~Matrix() {
//printf("Matrix::~Matrix\n");
if (ma != NULL)
gsl_matrix_free(ma); // Release allocated memory
if (header != NULL) {
free(header);
}
}
// Assignment operator function.
// Overloads the equal sign operator to work with
// Matrix objects.
Matrix& operator=(const Matrix& mat) {
if( this == &mat ) return *this; // If two sides equal, do nothing.
this->copy(mat); // Copy right hand side to l.h.s.
return *this;
}
// += operator function.
// Overloads the += sign operator to work with
// Matrix objects.
Matrix& operator+=(const Matrix& mat) {
gsl_matrix_add( this->ma, mat.ma);
return *this;
}
// -= operator function.
// Overloads the -= sign operator to work with
// Matrix objects.
Matrix& operator-=(const Matrix& mat) {
gsl_matrix_sub( this->ma, mat.ma);
return *this;
}
// *= operator function.
// Overloads the *= sign operator to work with
// Matrix objects.
Matrix& operator*=(const double a) {
gsl_matrix_scale( this->ma, a);
return *this;
}
// Set function. Sets all elements of a matrix to a given value.
void set(double value) {
gsl_matrix_set_all( ma, value);
}
/*// Set function. Sets all elements of a matrix to a given value.
void eval(double value, double (*fct)(double x)) {
to be done
}*/
//info
// Simple "get" functions. Return number of rows or columns.
int nRow() const { return ma->size1; }
int nCol() const { return ma->size2; }
//min and max
double Max() { gsl_matrix_max(ma); }
double Min() { gsl_matrix_min(ma); }
// Parenthesis operator function.
// Allows access to values of Matrix via (i,j) pair.
// Example: a(1,1) = 2*b(2,3);
// If column is unspecified, take as 1.
double& operator() (int i, int j = 0) {
assert(i >= 0 && i < ma->size1); // Bounds checking for rows
assert(j >= 0 && j < ma->size2); // Bounds checking for columns
return ma->data[ (ma->tda)*i + j]; // Access appropriate value
}
// Parenthesis operator function (const version).
const double& operator() (int i, int j = 0) const{
assert(i >= 0 && i < ma->size1); // Bounds checking for rows
assert(j >= 0 && j < ma->size2); // Bounds checking for columns
return ma->data[(ma->tda)*i + j]; // Access appropriate value
}
// Allows access to values of Matrix via ele(i,j) pair.
// If column is unspecified, take as 1.
double ele(int i, int j = 0) {
assert(i >= 0 && i < ma->size1); // Bounds checking for rows
assert(j >= 0 && j < ma->size2); // Bounds checking for columns
return ma->data[ (ma->tda)*i + j]; // Access appropriate value
}
//i/o
//Print function
void print( FILE *F, char *name=NULL, int fw=11, int pres=4, char *sep=" ", int rownums=0, int colnums=0)
{
if (name == NULL)
if (header == NULL)
fprintf( F, "\n");
else
fprintf( F, "%s\n", header);
else
fprintf( F, "%s", name);
for (int i=0; i<ma->size1; i++)
{
if ((i == 0) && (colnums)) {
fprintf( F, "%*s%s", fw, "", sep);
for (int j=0; j<ma->size2; j++)
fprintf( F, "%*d%s", fw, j, sep);
fprintf(F, "\n");
}
for (int j=0; j<ma->size2; j++) {
if ((j == 0) && (rownums))
fprintf( F, "%3d%s", i, sep);
fprintf( F, "%*.*g%s", fw, pres, ele(i,j), sep);
}
fprintf( F, "\n");
}
}
void print(char *name=NULL) { print( stdout, name, 11, 4, " ", 0, 0); }
void printnums(char *name=NULL) { print( stdout, name, 11, 4, " ", 1, 1); }
void fileprint(char *fnam) {
FILE *F;
if ((F = fopen( fnam, "w+")) == NULL)
{
printf( "Could not open file %s for writing\n", fnam);
assert(F == NULL);
}
else
{
print( F, NULL, 11, 4, " ");
fclose(F);
}
}
void printrow(int i) {
assert(i < nRow());
for (int j=0; j<ma->size2; j++) {
printf( "%*.*g%s", 11, 4, ele(i,j), " ");
}
printf( "\n");
}
int filescan(char *fnam, int file_header=0) {
FILE *F;
if ((F = fopen( fnam, "r")) == NULL)
{
printf( "File %s not found\n", fnam);
return 0;
}
else
{
if (file_header == 1) {
header = (char *) malloc((size_t) BUFF_SIZE);
header = fgets( header, (size_t) BUFF_SIZE, F);
header[strlen(header)-1] = '\0'; //remove the \n
}
gsl_matrix_fscanf( F, ma);
fclose(F);
return 1;
}
}
/*********************** Views *********************/
//Get the gsl matrix
gsl_matrix *Ma() { return ma; }
//Column gsl Vector
gsl_vector *AsColVec(int Col) {
assert(Col >= 0 && Col < ma->size2); // Bounds checking for columns
ve.size = ma->size1;
ve.stride = ma->tda;
ve.data = ma->data + Col;
return &ve;
}
//First column is the defalut
gsl_vector *Ve() {
ve.size = ma->size1;
ve.stride = ma->tda;
ve.data = ma->data;
return &ve;
}
//Row Vector
gsl_vector *AsRowVec(int Row, int ChopOff=0) {
assert(Row >= 0 && Row < ma->size1); // Bounds checking for rows
ve.size = ma->size2-ChopOff;
ve.stride = 1;
ve.data = ma->data + (ma->tda)*Row;
return &ve;
}
// Copy function.
// Copies values from one Matrix object to another.
void Copy(const Matrix *mat) {
assert((nRow() == mat->nRow()) && (nCol() == mat->nCol()));
gsl_matrix_memcpy( ma, mat->ma);
}
// Copy function.
// Copies values from one Matrix object to another.
void copy(const Matrix& mat) {
gsl_matrix_memcpy( ma, mat.ma);
}
const char *Header() { return header; }
//*********************************************************************
protected:
// Matrix data.
gsl_matrix *ma;
gsl_vector ve;
char *header;
}; // Class Matrix
class SubMatrix : public Matrix {
private:
gsl_matrix_view view;
Matrix *Parent;
public:
SubMatrix(Matrix &mat, size_t k1, size_t k2, size_t n1, size_t n2) {
view = gsl_matrix_submatrix ( mat.Ma(), k1, k2, n1, n2);
ma = &view.matrix;
Parent = &mat;
if (mat.Header() != NULL)
header = strdup(mat.Header());
else
header = NULL;
}
SubMatrix( Matrix& mat, size_t n1, size_t n2) {
view = gsl_matrix_submatrix ( mat.Ma(), (size_t) 0, (size_t) 0, n1, n2);
ma = &view.matrix;
Parent = &mat;
if (mat.Header() != NULL)
header = strdup(mat.Header());
else
header = NULL;
}
SubMatrix() {
//delay the opening of this submatrix
ma = NULL;
Parent = NULL;
header = NULL;
}
~SubMatrix() {
ma = NULL; //we avoid the base class call to free with this
if (header != NULL) {
free(header);
header=NULL;
}
}
void Set(Matrix *mat, size_t k1, size_t k2, size_t n1, size_t n2) {
view = gsl_matrix_submatrix ( mat->Ma(), k1, k2, n1, n2);
ma = &view.matrix;
Parent = mat;
if (mat->Header() == NULL)
header = NULL;
else
header = strdup(mat->Header());
}
const char *SetHeader(char *head) {
if (header != NULL)
free(header);
header == NULL;
if (head != NULL)
header = strdup(head);
return header;
}
// Assignment operator function.
// Overloads the equal sign operator to work with
// Matrix objects.
SubMatrix& operator=(const SubMatrix& mat) {
if( this == &mat ) return *this; // If two sides equal, do nothing.
this->copy(mat); // Copy right hand side to l.h.s.
return *this;
}
// += operator function.
// Overloads the += sign operator to work with
// Matrix objects.
SubMatrix& operator+=(const SubMatrix& mat) {
gsl_matrix_add( this->ma, mat.ma);
return *this;
}
// -= operator function.
// Overloads the -= sign operator to work with
// Matrix objects.
SubMatrix& operator-=(const SubMatrix& mat) {
gsl_matrix_sub( this->ma, mat.ma);
return *this;
}
// *= operator function.
// Overloads the *= sign operator to work with
// Matrix objects.
SubMatrix& operator*=(const double a) {
gsl_matrix_scale( this->ma, a);
return *this;
}
void Set( Matrix *mat, size_t n1, size_t n2) {
view = gsl_matrix_submatrix ( mat->Ma(), (size_t) 0, (size_t) 0, n1, n2);
ma = &view.matrix;
Parent = mat;
}
void ReSize(size_t k1, size_t k2, size_t n1, size_t n2) {
view = gsl_matrix_submatrix( Parent->Ma(), k1, k2, n1, n2);
ma = &view.matrix;
}
void ReSize(size_t n1, size_t n2) {
view = gsl_matrix_submatrix ( Parent->Ma(), (size_t) 0, (size_t) 0, n1, n2);
ma = &view.matrix;
}
};
/*Auxiliary functions*/
//C = A^trA B^trB
int MatMul(Matrix &C, int trA, Matrix &A, int trB, Matrix &B);
int MatMul(Matrix &C, Matrix &A, Matrix &B);
double CuadForm(Matrix &A, Matrix &b);
int MatMulSym(Matrix &C, Matrix &A, Matrix &B);
//inverse of real (symetric) positive defined matrix
//as a by product we may obtain the square root of the determinat of A
int InvRPD(Matrix &R, Matrix &A, double *LogDetSqrt=NULL, Matrix *ExternChol=NULL);
//I have seen problems with this when dest and src are rows or cls of the same matrix
int VecCopy(gsl_vector * dest, const gsl_vector * src);
#endif
| {
"alphanum_fraction": 0.6054940862,
"avg_line_length": 22.8409586057,
"ext": "h",
"hexsha": "5b9ec14354316c3555dace23d84c7a00d16f43b6",
"lang": "C",
"max_forks_count": 5,
"max_forks_repo_forks_event_max_datetime": "2019-06-14T13:27:02.000Z",
"max_forks_repo_forks_event_min_datetime": "2016-10-07T03:10:31.000Z",
"max_forks_repo_head_hexsha": "ef2857caddb1be9faac0173ad15d030684780ade",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "SFlantua/Workshops",
"max_forks_repo_path": "UW_ACES2016/cpp/Matrix.h",
"max_issues_count": 9,
"max_issues_repo_head_hexsha": "ef2857caddb1be9faac0173ad15d030684780ade",
"max_issues_repo_issues_event_max_datetime": "2016-12-14T18:14:40.000Z",
"max_issues_repo_issues_event_min_datetime": "2016-07-25T19:44:00.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "SFlantua/Workshops",
"max_issues_repo_path": "UW_ACES2016/cpp/Matrix.h",
"max_line_length": 105,
"max_stars_count": 3,
"max_stars_repo_head_hexsha": "ef2857caddb1be9faac0173ad15d030684780ade",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "SFlantua/Workshops",
"max_stars_repo_path": "UW_ACES2016/cpp/Matrix.h",
"max_stars_repo_stars_event_max_datetime": "2021-01-14T22:49:11.000Z",
"max_stars_repo_stars_event_min_datetime": "2016-10-25T16:00:10.000Z",
"num_tokens": 3254,
"size": 10484
} |
/* specfunc/bessel_zero.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_airy.h>
#include <gsl/gsl_sf_pow_int.h>
#include <gsl/gsl_sf_bessel.h>
#include "error.h"
#include "bessel_olver.h"
/* For Chebyshev expansions of the roots as functions of nu,
* see [G. Nemeth, Mathematical Approximation of Special Functions].
* This gives the fits for all nu and s <= 10.
* I made the fits for other values of s myself [GJ].
*/
/* Chebyshev expansion: j_{nu,1} = c_k T_k*(nu/2), nu <= 2 */
static const double coef_jnu1_a[] = {
3.801775243633476,
1.360704737511120,
-0.030707710261106,
0.004526823746202,
-0.000808682832134,
0.000159218792489,
-0.000033225189761,
0.000007205599763,
-0.000001606110397,
0.000000365439424,
-0.000000084498039,
0.000000019793815,
-0.000000004687054,
0.000000001120052,
-0.000000000269767,
0.000000000065420,
-0.000000000015961,
0.000000000003914,
-0.000000000000965,
0.000000000000239,
-0.000000000000059,
0.000000000000015,
-0.000000000000004,
0.000000000000001
};
/* Chebyshev expansion: j_{nu,1} = nu c_k T_k*((2/nu)^(2/3)), nu >= 2 */
static const double coef_jnu1_b[] = {
1.735063412537096,
0.784478100951978,
0.048881473180370,
-0.000578279783021,
-0.000038984957864,
0.000005758297879,
-0.000000327583229,
-0.000000003853878,
0.000000002284653,
-0.000000000153079,
-0.000000000000895,
0.000000000000283,
0.000000000000043,
0.000000000000010,
-0.000000000000003
};
/* Chebyshev expansion: j_{nu,2} = c_k T_k*(nu/2), nu <= 2 */
static const double coef_jnu2_a[] = {
6.992370244046161,
1.446379282056534,
-0.023458616207293,
0.002172149448700,
-0.000246262775620,
0.000030990180959,
-0.000004154183047,
0.000000580766328,
-0.000000083648175,
0.000000012317355,
-0.000000001844887,
0.000000000280076,
-0.000000000042986,
0.000000000006658,
-0.000000000001039,
0.000000000000163,
-0.000000000000026,
0.000000000000004,
-0.000000000000001
};
/* Chebyshev expansion: j_{nu,2} = nu c_k T_k*((2/nu)^(2/3)), nu >= 2 */
static const double coef_jnu2_b[] = {
2.465611864263400,
1.607952988471069,
0.138758034431497,
-0.003687791182054,
-0.000051276007868,
0.000045113570749,
-0.000007579172152,
0.000000736469208,
-0.000000011118527,
-0.000000011919884,
0.000000002696788,
-0.000000000314488,
0.000000000008124,
0.000000000005211,
-0.000000000001292,
0.000000000000158,
-0.000000000000004,
-0.000000000000003,
0.000000000000001
};
/* Chebyshev expansion: j_{nu,3} = c_k T_k*(nu/3), nu <= 3 */
static const double coef_jnu3_a[] = {
10.869647065239236,
2.177524286141710,
-0.034822817125293,
0.003167249102413,
-0.000353960349344,
0.000044039086085,
-0.000005851380981,
0.000000812575483,
-0.000000116463617,
0.000000017091246,
-0.000000002554376,
0.000000000387335,
-0.000000000059428,
0.000000000009207,
-0.000000000001438,
0.000000000000226,
-0.000000000000036,
0.000000000000006,
-0.000000000000001
};
/* Chebyshev expansion: j_{nu,3} = nu c_k T_k*((3/nu)^(2/3)), nu >= 3 */
static const double coef_jnu3_b[] = {
2.522816775173244,
1.673199424973720,
0.146431617506314,
-0.004049001763912,
-0.000039517767244,
0.000048781729288,
-0.000008729705695,
0.000000928737310,
-0.000000028388244,
-0.000000012927432,
0.000000003441008,
-0.000000000471695,
0.000000000025590,
0.000000000005502,
-0.000000000001881,
0.000000000000295,
-0.000000000000020,
-0.000000000000003,
0.000000000000001
};
/* Chebyshev expansion: j_{nu,4} = c_k T_k*(nu/4), nu <= 4 */
static const double coef_jnu4_a[] = {
14.750310252773009,
2.908010932941708,
-0.046093293420315,
0.004147172321412,
-0.000459092310473,
0.000056646951906,
-0.000007472351546,
0.000001031210065,
-0.000000147008137,
0.000000021475218,
-0.000000003197208,
0.000000000483249,
-0.000000000073946,
0.000000000011431,
-0.000000000001782,
0.000000000000280,
-0.000000000000044,
0.000000000000007,
-0.000000000000001
};
/* Chebyshev expansion: j_{nu,4} = nu c_k T_k*((4/nu)^(2/3)), nu >= 4 */
static const double coef_jnu4_b[] = {
2.551681323117914,
1.706177978336572,
0.150357658406131,
-0.004234001378590,
-0.000033854229898,
0.000050763551485,
-0.000009337464057,
0.000001029717834,
-0.000000037474196,
-0.000000013450153,
0.000000003836180,
-0.000000000557404,
0.000000000035748,
0.000000000005487,
-0.000000000002187,
0.000000000000374,
-0.000000000000031,
-0.000000000000003,
0.000000000000001
};
/* Chebyshev expansion: j_{nu,5} = c_k T_k*(nu/5), nu <= 5 */
static const double coef_jnu5_a[] = {
18.632261081028211,
3.638249012596966,
-0.057329705998828,
0.005121709126820,
-0.000563325259487,
0.000069100826174,
-0.000009066603030,
0.000001245181383,
-0.000000176737282,
0.000000025716695,
-0.000000003815184,
0.000000000574839,
-0.000000000087715,
0.000000000013526,
-0.000000000002104,
0.000000000000330,
-0.000000000000052,
0.000000000000008,
-0.000000000000001
};
/* Chebyshev expansion: j_{nu,5} = nu c_k T_k*((5/nu)^(2/3)), nu >= 5 */
/* FIXME: There is something wrong with this fit, in about the
* 9th or 10th decimal place.
*/
static const double coef_jnu5_b[] = {
2.569079487591442,
1.726073360882134,
0.152740776809531,
-0.004346449660148,
-0.000030512461856,
0.000052000821080,
-0.000009713343981,
0.000001091997863,
-0.000000043061707,
-0.000000013779413,
0.000000004082870,
-0.000000000611259,
0.000000000042242,
0.000000000005448,
-0.000000000002377,
0.000000000000424,
-0.000000000000038,
-0.000000000000002,
0.000000000000002
};
/* Chebyshev expansion: j_{nu,6} = c_k T_k*(nu/6), nu <= 6 */
static const double coef_jnu6_a[] = {
22.514836143374042,
4.368367257557198,
-0.068550155285562,
0.006093776505822,
-0.000667152784957,
0.000081486022398,
-0.000010649011647,
0.000001457089679,
-0.000000206105082,
0.000000029894724,
-0.000000004422012,
0.000000000664471,
-0.000000000101140,
0.000000000015561,
-0.000000000002416,
0.000000000000378,
-0.000000000000060,
0.000000000000009,
-0.000000000000002
};
/* Chebyshev expansion: j_{nu,6} = nu c_k T_k*((6/nu)^(2/3)), nu >= 6 */
static const double coef_jnu6_b[] = {
2.580710285494837,
1.739380728566154,
0.154340696401691,
-0.004422028860168,
-0.000028305272624,
0.000052845975269,
-0.000009968794373,
0.000001134252926,
-0.000000046841241,
-0.000000014007555,
0.000000004251816,
-0.000000000648213,
0.000000000046728,
0.000000000005414,
-0.000000000002508,
0.000000000000459,
-0.000000000000043,
-0.000000000000002,
0.000000000000002
};
/* Chebyshev expansion: j_{nu,7} = c_k T_k*(nu/7), nu <= 7 */
static const double coef_jnu7_a[] = {
26.397760539730869,
5.098418721711790,
-0.079761896398948,
0.007064521280487,
-0.000770766522482,
0.000093835449636,
-0.000012225308542,
0.000001667939800,
-0.000000235288157,
0.000000034040347,
-0.000000005023142,
0.000000000753101,
-0.000000000114389,
0.000000000017564,
-0.000000000002722,
0.000000000000425,
-0.000000000000067,
0.000000000000011,
-0.000000000000002
};
/* Chebyshev expansion: j_{nu,7} = nu c_k T_k*((7/nu)^(2/3)), nu >= 7 */
static const double coef_jnu7_b[] = {
2.589033335856773,
1.748907007612678,
0.155488900387653,
-0.004476317805688,
-0.000026737952924,
0.000053459680946,
-0.000010153699240,
0.000001164804272,
-0.000000049566917,
-0.000000014175403,
0.000000004374840,
-0.000000000675135,
0.000000000050004,
0.000000000005387,
-0.000000000002603,
0.000000000000485,
-0.000000000000047,
-0.000000000000002,
0.000000000000002
};
/* Chebyshev expansion: j_{nu,8} = c_k T_k*(nu/8), nu <= 8 */
static const double coef_jnu8_a[] = {
30.280900001606662,
5.828429205461221,
-0.090968381181069,
0.008034479731033,
-0.000874254899080,
0.000106164151611,
-0.000013798098749,
0.000001878187386,
-0.000000264366627,
0.000000038167685,
-0.000000005621060,
0.000000000841165,
-0.000000000127538,
0.000000000019550,
-0.000000000003025,
0.000000000000472,
-0.000000000000074,
0.000000000000012,
-0.000000000000002
};
/* Chebyshev expansion: j_{nu,8} = nu c_k T_k*((8/nu)^(2/3)), nu >= 8 */
static const double coef_jnu8_b[] = {
2.595283877150078,
1.756063044986928,
0.156352972371030,
-0.004517201896761,
-0.000025567187878,
0.000053925472558,
-0.000010293734486,
0.000001187923085,
-0.000000051625122,
-0.000000014304212,
0.000000004468450,
-0.000000000695620,
0.000000000052500,
0.000000000005367,
-0.000000000002676,
0.000000000000505,
-0.000000000000050,
-0.000000000000002,
0.000000000000002
};
/* Chebyshev expansion: j_{nu,9} = c_k T_k*(nu/9), nu <= 9 */
static const double coef_jnu9_a[] = {
34.164181213238386,
6.558412747925228,
-0.102171455365016,
0.009003934361201,
-0.000977663914535,
0.000118479876579,
-0.000015368714220,
0.000002088064285,
-0.000000293381154,
0.000000042283900,
-0.000000006217033,
0.000000000928887,
-0.000000000140627,
0.000000000021526,
-0.000000000003326,
0.000000000000518,
-0.000000000000081,
0.000000000000013,
-0.000000000000002
};
/* Chebyshev expansion: j_{nu,9} = nu c_k T_k*((9/nu)^(2/3)), nu >= 9 */
static const double coef_jnu9_b[] = {
2.600150240905079,
1.761635491694032,
0.157026743724010,
-0.004549100368716,
-0.000024659248617,
0.000054291035068,
-0.000010403464334,
0.000001206027524,
-0.000000053234089,
-0.000000014406241,
0.000000004542078,
-0.000000000711728,
0.000000000054464,
0.000000000005350,
-0.000000000002733,
0.000000000000521,
-0.000000000000052,
-0.000000000000002,
0.000000000000002
};
/* Chebyshev expansion: j_{nu,10} = c_k T_k*(nu/10), nu <= 10 */
static const double coef_jnu10_a[] = {
38.047560766184647,
7.288377637926008,
-0.113372193277897,
0.009973047509098,
-0.001081019701335,
0.000130786983847,
-0.000016937898538,
0.000002297699179,
-0.000000322354218,
0.000000046392941,
-0.000000006811759,
0.000000001016395,
-0.000000000153677,
0.000000000023486,
-0.000000000003616,
0.000000000000561,
-0.000000000000095,
0.000000000000027,
-0.000000000000013,
0.000000000000005
};
/* Chebyshev expansion: j_{nu,10} = nu c_k T_k*((10/nu)^(2/3)), nu >= 10 */
static const double coef_jnu10_b[] = {
2.604046346867949,
1.766097596481182,
0.157566834446511,
-0.004574682244089,
-0.000023934500688,
0.000054585558231,
-0.000010491765415,
0.000001220589364,
-0.000000054526331,
-0.000000014489078,
0.000000004601510,
-0.000000000724727,
0.000000000056049,
0.000000000005337,
-0.000000000002779,
0.000000000000533,
-0.000000000000054,
-0.000000000000002,
0.000000000000002
};
/* Chebyshev expansion: j_{nu,11} = c_k T_k*(nu/22), nu <= 22 */
static const double coef_jnu11_a[] = {
49.5054081076848637,
15.33692279367165101,
-0.33677234163517130,
0.04623235772920729,
-0.00781084960665093,
0.00147217395434708,
-0.00029695043846867,
0.00006273356860235,
-0.00001370575125628,
3.07171282012e-6,
-7.0235041249e-7,
1.6320559339e-7,
-3.843117306e-8,
9.15083800e-9,
-2.19957642e-9,
5.3301703e-10,
-1.3007541e-10,
3.193827e-11,
-7.88605e-12,
1.95918e-12,
-4.9020e-13,
1.2207e-13,
-2.820e-14,
5.25e-15,
-1.88e-15,
2.80e-15,
-2.45e-15
};
/* Chebyshev expansion: j_{nu,12} = c_k T_k*(nu/24), nu <= 24 */
static const double coef_jnu12_a[] = {
54.0787833216641519,
16.7336367772863598,
-0.36718411124537953,
0.05035523375053820,
-0.00849884978867533,
0.00160027692813434,
-0.00032248114889921,
0.00006806354127199,
-0.00001485665901339,
3.32668783672e-6,
-7.5998952729e-7,
1.7644939709e-7,
-4.151538210e-8,
9.87722772e-9,
-2.37230133e-9,
5.7442875e-10,
-1.4007767e-10,
3.437166e-11,
-8.48215e-12,
2.10554e-12,
-5.2623e-13,
1.3189e-13,
-3.175e-14,
5.73e-15,
5.6e-16,
-8.7e-16,
-6.5e-16
};
/* Chebyshev expansion: j_{nu,13} = c_k T_k*(nu/26), nu <= 26 */
static const double coef_jnu13_a[] = {
58.6521941921708890,
18.1303398137970284,
-0.39759381380126650,
0.05447765240465494,
-0.00918674227679980,
0.00172835361420579,
-0.00034800528297612,
0.00007339183835188,
-0.00001600713368099,
3.58154960392e-6,
-8.1759873497e-7,
1.8968523220e-7,
-4.459745253e-8,
1.060304419e-8,
-2.54487624e-9,
6.1580214e-10,
-1.5006751e-10,
3.679707e-11,
-9.07159e-12,
2.24713e-12,
-5.5943e-13,
1.4069e-13,
-3.679e-14,
1.119e-14,
-4.99e-15,
3.43e-15,
-2.85e-15,
2.3e-15,
-1.7e-15,
8.7e-16
};
/* Chebyshev expansion: j_{nu,14} = c_k T_k*(nu/28), nu <= 28 */
static const double coef_jnu14_a[] = {
63.2256329577315566,
19.5270342832914901,
-0.42800190567884337,
0.05859971627729398,
-0.00987455163523582,
0.00185641011402081,
-0.00037352439419968,
0.00007871886257265,
-0.00001715728110045,
3.83632624437e-6,
-8.7518558668e-7,
2.0291515353e-7,
-4.767795233e-8,
1.132844415e-8,
-2.71734219e-9,
6.5714886e-10,
-1.6005342e-10,
3.922557e-11,
-9.66637e-12,
2.39379e-12,
-5.9541e-13,
1.4868e-13,
-3.726e-14,
9.37e-15,
-2.36e-15,
6.0e-16
};
/* Chebyshev expansion: j_{nu,15} = c_k T_k*(nu/30), nu <= 30 */
static const double coef_jnu15_a[] = {
67.7990939565631635,
20.9237219226859859,
-0.45840871823085836,
0.06272149946755639,
-0.01056229551143042,
0.00198445078693100,
-0.00039903958650729,
0.00008404489865469,
-0.00001830717574922,
4.09103745566e-6,
-9.3275533309e-7,
2.1614056403e-7,
-5.075725222e-8,
1.205352081e-8,
-2.88971837e-9,
6.9846848e-10,
-1.7002946e-10,
4.164941e-11,
-1.025859e-11,
2.53921e-12,
-6.3128e-13,
1.5757e-13,
-3.947e-14,
9.92e-15,
-2.50e-15,
6.3e-16
};
/* Chebyshev expansion: j_{nu,16} = c_k T_k*(nu/32), nu <= 32 */
static const double coef_jnu16_a[] = {
72.3725729616724770,
22.32040402918608585,
-0.48881449782358690,
0.06684305681828766,
-0.01124998690363398,
0.00211247882775445,
-0.00042455166484632,
0.00008937015316346,
-0.00001945687139551,
4.34569739281e-6,
-9.9031173548e-7,
2.2936247195e-7,
-5.383562595e-8,
1.277835103e-8,
-3.06202860e-9,
7.3977037e-10,
-1.8000071e-10,
4.407196e-11,
-1.085046e-11,
2.68453e-12,
-6.6712e-13,
1.6644e-13,
-4.168e-14,
1.047e-14,
-2.64e-15,
6.7e-16
};
/* Chebyshev expansion: j_{nu,17} = c_k T_k*(nu/34), nu <= 34 */
static const double coef_jnu17_a[] = {
76.9460667535209549,
23.71708159112252670,
-0.51921943142405352,
0.07096442978067622,
-0.01193763559341369,
0.00224049662974902,
-0.00045006122941781,
0.00009469477941684,
-0.00002060640777107,
4.60031647195e-6,
-1.04785755046e-6,
2.4258161247e-7,
-5.691327087e-8,
1.350298805e-8,
-3.23428733e-9,
7.8105847e-10,
-1.8996825e-10,
4.649350e-11,
-1.144205e-11,
2.82979e-12,
-7.0294e-13,
1.7531e-13,
-4.388e-14,
1.102e-14,
-2.78e-15,
7.0e-16
};
/* Chebyshev expansion: j_{nu,18} = c_k T_k*(nu/36), nu <= 36 */
static const double coef_jnu18_a[] = {
81.5195728368096659,
25.11375537470259305,
-0.54962366347317668,
0.07508565026117689,
-0.01262524908033818,
0.00236850602019778,
-0.00047556873651929,
0.00010001889347161,
-0.00002175581482429,
4.85490251239e-6,
-1.10539483940e-6,
2.5579853343e-7,
-5.999033352e-8,
1.422747129e-8,
-3.40650521e-9,
8.2233565e-10,
-1.9993286e-10,
4.891426e-11,
-1.203343e-11,
2.97498e-12,
-7.3875e-13,
1.8418e-13,
-4.608e-14,
1.157e-14,
-2.91e-15,
7.4e-16
};
/* Chebyshev expansion: j_{nu,19} = c_k T_k*(nu/38), nu <= 38 */
static const double coef_jnu19_a[] = {
86.0930892477047512,
26.51042598308271729,
-0.58002730731948358,
0.07920674321589394,
-0.01331283320930301,
0.00249650841778073,
-0.00050107453900793,
0.00010534258471335,
-0.00002290511552874,
5.10946148897e-6,
-1.16292517157e-6,
2.6901365037e-7,
-6.306692473e-8,
1.495183048e-8,
-3.57869025e-9,
8.6360410e-10,
-2.0989514e-10,
5.133439e-11,
-1.262465e-11,
3.12013e-12,
-7.7455e-13,
1.9304e-13,
-4.829e-14,
1.212e-14,
-3.05e-15,
7.7e-16
};
/* Chebyshev expansion: j_{nu,20} = c_k T_k*(nu/40), nu <= 40 */
static const double coef_jnu20_a[] = {
90.6666144195163770,
27.9070938975436823,
-0.61043045315390591,
0.08332772844325554,
-0.01400039260208282,
0.00262450494035660,
-0.00052657891389470,
0.00011066592304919,
-0.00002405432778364,
5.36399803946e-6,
-1.22044976064e-6,
2.8222728362e-7,
-6.614312964e-8,
1.567608839e-8,
-3.75084856e-9,
9.0486546e-10,
-2.1985553e-10,
5.375401e-11,
-1.321572e-11,
3.26524e-12,
-8.1033e-13,
2.0190e-13,
-5.049e-14,
1.267e-14,
-3.19e-15,
8.0e-16,
-2.0e-16
};
static const double * coef_jnu_a[] = {
0,
coef_jnu1_a,
coef_jnu2_a,
coef_jnu3_a,
coef_jnu4_a,
coef_jnu5_a,
coef_jnu6_a,
coef_jnu7_a,
coef_jnu8_a,
coef_jnu9_a,
coef_jnu10_a,
coef_jnu11_a,
coef_jnu12_a,
coef_jnu13_a,
coef_jnu14_a,
coef_jnu15_a,
coef_jnu16_a,
coef_jnu17_a,
coef_jnu18_a,
coef_jnu19_a,
coef_jnu20_a
};
static const size_t size_jnu_a[] = {
0,
sizeof(coef_jnu1_a)/sizeof(double),
sizeof(coef_jnu2_a)/sizeof(double),
sizeof(coef_jnu3_a)/sizeof(double),
sizeof(coef_jnu4_a)/sizeof(double),
sizeof(coef_jnu5_a)/sizeof(double),
sizeof(coef_jnu6_a)/sizeof(double),
sizeof(coef_jnu7_a)/sizeof(double),
sizeof(coef_jnu8_a)/sizeof(double),
sizeof(coef_jnu9_a)/sizeof(double),
sizeof(coef_jnu10_a)/sizeof(double),
sizeof(coef_jnu11_a)/sizeof(double),
sizeof(coef_jnu12_a)/sizeof(double),
sizeof(coef_jnu13_a)/sizeof(double),
sizeof(coef_jnu14_a)/sizeof(double),
sizeof(coef_jnu15_a)/sizeof(double),
sizeof(coef_jnu16_a)/sizeof(double),
sizeof(coef_jnu17_a)/sizeof(double),
sizeof(coef_jnu18_a)/sizeof(double),
sizeof(coef_jnu19_a)/sizeof(double),
sizeof(coef_jnu20_a)/sizeof(double)
};
static const double * coef_jnu_b[] = {
0,
coef_jnu1_b,
coef_jnu2_b,
coef_jnu3_b,
coef_jnu4_b,
coef_jnu5_b,
coef_jnu6_b,
coef_jnu7_b,
coef_jnu8_b,
coef_jnu9_b,
coef_jnu10_b
};
static const size_t size_jnu_b[] = {
0,
sizeof(coef_jnu1_b)/sizeof(double),
sizeof(coef_jnu2_b)/sizeof(double),
sizeof(coef_jnu3_b)/sizeof(double),
sizeof(coef_jnu4_b)/sizeof(double),
sizeof(coef_jnu5_b)/sizeof(double),
sizeof(coef_jnu6_b)/sizeof(double),
sizeof(coef_jnu7_b)/sizeof(double),
sizeof(coef_jnu8_b)/sizeof(double),
sizeof(coef_jnu9_b)/sizeof(double),
sizeof(coef_jnu10_b)/sizeof(double)
};
/* Evaluate Clenshaw recurrence for
* a T* Chebyshev series.
* sizeof(c) = N+1
*/
static double
clenshaw(const double * c, int N, double u)
{
double B_np1 = 0.0;
double B_n = c[N];
double B_nm1;
int n;
for(n=N; n>0; n--) {
B_nm1 = 2.0*(2.0*u-1.0) * B_n - B_np1 + c[n-1];
B_np1 = B_n;
B_n = B_nm1;
}
return B_n - (2.0*u-1.0)*B_np1;
}
/* correction terms to leading McMahon expansion
* [Abramowitz+Stegun 9.5.12]
* [Olver, Royal Society Math. Tables, v. 7]
* We factor out a beta, so that this is a multiplicative
* correction:
* j_{nu,s} = beta(s,nu) * mcmahon_correction(nu, beta(s,nu))
* macmahon_correction --> 1 as s --> Inf
*/
static double
mcmahon_correction(const double mu, const double beta)
{
const double eb = 8.0*beta;
const double ebsq = eb*eb;
if(mu < GSL_DBL_EPSILON) {
/* Prevent division by zero below. */
const double term1 = 1.0/ebsq;
const double term2 = -4.0*31.0/(3*ebsq*ebsq);
const double term3 = 32.0*3779.0/(15.0*ebsq*ebsq*ebsq);
const double term4 = -64.0*6277237.0/(105.0*ebsq*ebsq*ebsq*ebsq);
const double term5 = 512.0*2092163573.0/(315.0*ebsq*ebsq*ebsq*ebsq*ebsq);
return 1.0 + 8.0*(term1 + term2 + term3 + term4 + term5);
}
else {
/* Here we do things in terms of 1/mu, which
* is purely to prevent overflow in the very
* unlikely case that mu is really big.
*/
const double mi = 1.0/mu;
const double r = mu/ebsq;
const double n2 = 4.0/3.0 * (7.0 - 31.0*mi);
const double n3 = 32.0/15.0 * (83.0 + (-982.0 + 3779.0*mi)*mi);
const double n4 = 64.0/105.0 * (6949.0 + (-153855.0 + (1585743.0 - 6277237.0*mi)*mi)*mi);
const double n5 = 512.0/315.0 * (70197.0 + (-2479316.0 + (48010494.0 + (-512062548.0 + 2092163573.0*mi)*mi)*mi)*mi);
const double n6 = 2048.0/3465.0 * (5592657.0 + (-287149133.0 + (8903961290.0 + (-179289628602.0 + (1982611456181.0 - 8249725736393.0*mi)*mi)*mi)*mi)*mi);
const double term1 = (1.0 - mi) * r;
const double term2 = term1 * n2 * r;
const double term3 = term1 * n3 * r*r;
const double term4 = term1 * n4 * r*r*r;
const double term5 = term1 * n5 * r*r*r*r;
const double term6 = term1 * n6 * r*r*r*r*r;
return 1.0 - 8.0*(term1 + term2 + term3 + term4 + term5 + term6);
}
}
/* Assumes z >= 1.0 */
static double
olver_b0(double z, double minus_zeta)
{
if(z < 1.02) {
const double a = 1.0-z;
const double c0 = 0.0179988721413553309252458658183;
const double c1 = 0.0111992982212877614645974276203;
const double c2 = 0.0059404069786014304317781160605;
const double c3 = 0.0028676724516390040844556450173;
const double c4 = 0.0012339189052567271708525111185;
const double c5 = 0.0004169250674535178764734660248;
const double c6 = 0.0000330173385085949806952777365;
const double c7 = -0.0001318076238578203009990106425;
const double c8 = -0.0001906870370050847239813945647;
return c0 + a*(c1 + a*(c2 + a*(c3 + a*(c4 + a*(c5 + a*(c6 + a*(c7 + a*c8)))))));
}
else {
const double abs_zeta = minus_zeta;
const double t = 1.0/(z*sqrt(1.0 - 1.0/(z*z)));
return -5.0/(48.0*abs_zeta*abs_zeta) + t*(3.0 + 5.0*t*t)/(24.0*sqrt(abs_zeta));
}
}
inline
static double
olver_f1(double z, double minus_zeta)
{
const double b0 = olver_b0(z, minus_zeta);
const double h2 = sqrt(4.0*minus_zeta/(z*z-1.0)); /* FIXME */
return 0.5 * z * h2 * b0;
}
int
gsl_sf_bessel_zero_J0_e(unsigned int s, gsl_sf_result * result)
{
/* CHECK_POINTER(result) */
if(s == 0){
result->val = 0.0;
result->err = 0.0;
GSL_ERROR ("error", GSL_EINVAL);
}
else {
/* See [F. Lether, J. Comp. Appl .Math. 67, 167 (1996)]. */
static const double P[] = { 1567450796.0/12539606369.0,
8903660.0/2365861.0,
10747040.0/536751.0,
17590991.0/1696654.0
};
static const double Q[] = { 1.0,
29354255.0/954518.0,
76900001.0/431847.0,
67237052.0/442411.0
};
const double beta = (s - 0.25) * M_PI;
const double bi2 = 1.0/(beta*beta);
const double R33num = P[0] + bi2 * (P[1] + bi2 * (P[2] + P[3] * bi2));
const double R33den = Q[0] + bi2 * (Q[1] + bi2 * (Q[2] + Q[3] * bi2));
const double R33 = R33num/R33den;
result->val = beta + R33/beta;
result->err = fabs(3.0e-15 * result->val);
return GSL_SUCCESS;
}
}
int
gsl_sf_bessel_zero_J1_e(unsigned int s, gsl_sf_result * result)
{
/* CHECK_POINTER(result) */
if(s == 0) {
result->val = 0.0;
result->err = 0.0;
return GSL_SUCCESS;
}
else {
/* See [M. Branders et al., J. Comp. Phys. 42, 403 (1981)]. */
static const double a[] = { -0.362804405737084,
0.120341279038597,
0.439454547101171e-01,
0.159340088474713e-02
};
static const double b[] = { 1.0,
-0.325641790801361,
-0.117453445968927,
-0.424906902601794e-02
};
const double beta = (s + 0.25) * M_PI;
const double bi2 = 1.0/(beta*beta);
const double Rnum = a[3] + bi2 * (a[2] + bi2 * (a[1] + bi2 * a[0]));
const double Rden = b[3] + bi2 * (b[2] + bi2 * (b[1] + bi2 * b[0]));
const double R = Rnum/Rden;
result->val = beta * (1.0 + R*bi2);
result->err = fabs(2.0e-14 * result->val);
return GSL_SUCCESS;
}
}
int
gsl_sf_bessel_zero_Jnu_e(double nu, unsigned int s, gsl_sf_result * result)
{
/* CHECK_POINTER(result) */
if(nu <= -1.0) {
DOMAIN_ERROR(result);
}
else if(s == 0) {
result->val = 0.0;
result->err = 0.0;
if (nu == 0.0) {
GSL_ERROR ("no zero-th root for nu = 0.0", GSL_EINVAL);
}
return GSL_SUCCESS;
}
else if(nu < 0.0) {
/* This can be done, I'm just lazy now. */
result->val = 0.0;
result->err = 0.0;
GSL_ERROR("unimplemented", GSL_EUNIMPL);
}
else if(s == 1) {
/* Chebyshev fits for the first positive zero.
* For some reason Nemeth made this different from the others.
*/
if(nu < 2.0) {
const double * c = coef_jnu_a[s];
const size_t L = size_jnu_a[s];
const double arg = nu/2.0;
const double chb = clenshaw(c, L-1, arg);
result->val = chb;
result->err = 2.0e-15 * result->val;
}
else {
const double * c = coef_jnu_b[s];
const size_t L = size_jnu_b[s];
const double arg = pow(2.0/nu, 2.0/3.0);
const double chb = clenshaw(c, L-1, arg);
result->val = nu * chb;
result->err = 2.0e-15 * result->val;
}
return GSL_SUCCESS;
}
else if(s <= 10) {
/* Chebyshev fits for the first 10 positive zeros. */
if(nu < s) {
const double * c = coef_jnu_a[s];
const size_t L = size_jnu_a[s];
const double arg = nu/s;
const double chb = clenshaw(c, L-1, arg);
result->val = chb;
result->err = 2.0e-15 * result->val;
}
else {
const double * c = coef_jnu_b[s];
const size_t L = size_jnu_b[s];
const double arg = pow(s/nu, 2.0/3.0);
const double chb = clenshaw(c, L-1, arg);
result->val = nu * chb;
result->err = 2.0e-15 * result->val;
/* FIXME: truth in advertising for the screwed up
* s = 5 fit. Need to fix that.
*/
if(s == 5) {
result->err *= 5.0e+06;
}
}
return GSL_SUCCESS;
}
else if(s > 0.5*nu && s <= 20) {
/* Chebyshev fits for 10 < s <= 20. */
const double * c = coef_jnu_a[s];
const size_t L = size_jnu_a[s];
const double arg = nu/(2.0*s);
const double chb = clenshaw(c, L-1, arg);
result->val = chb;
result->err = 4.0e-15 * chb;
return GSL_SUCCESS;
}
else if(s > 2.0 * nu) {
/* McMahon expansion if s is large compared to nu. */
const double beta = (s + 0.5*nu - 0.25) * M_PI;
const double mc = mcmahon_correction(4.0*nu*nu, beta);
gsl_sf_result rat12;
gsl_sf_pow_int_e(nu/beta, 14, &rat12);
result->val = beta * mc;
result->err = 4.0 * fabs(beta) * rat12.val;
result->err += 4.0 * fabs(GSL_DBL_EPSILON * result->val);
return GSL_SUCCESS;
}
else {
/* Olver uniform asymptotic. */
gsl_sf_result as;
const int stat_as = gsl_sf_airy_zero_Ai_e(s, &as);
const double minus_zeta = -pow(nu,-2.0/3.0) * as.val;
const double z = gsl_sf_bessel_Olver_zofmzeta(minus_zeta);
const double f1 = olver_f1(z, minus_zeta);
result->val = nu * (z + f1/(nu*nu));
result->err = 0.001/(nu*nu*nu);
result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val);
return stat_as;
}
}
/*-*-*-*-*-*-*-*-*-* Functions w/ Natural Prototypes *-*-*-*-*-*-*-*-*-*-*/
#include "eval.h"
double gsl_sf_bessel_zero_J0(unsigned int s)
{
EVAL_RESULT(gsl_sf_bessel_zero_J0_e(s, &result));
}
double gsl_sf_bessel_zero_J1(unsigned int s)
{
EVAL_RESULT(gsl_sf_bessel_zero_J1_e(s, &result));
}
double gsl_sf_bessel_zero_Jnu(double nu, unsigned int s)
{
EVAL_RESULT(gsl_sf_bessel_zero_Jnu_e(nu, s, &result));
}
| {
"alphanum_fraction": 0.6611816983,
"avg_line_length": 23.6114754098,
"ext": "c",
"hexsha": "7ff8f7ebf0d7c0d044a7bb7a51b189ffea958a75",
"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_zero.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_zero.c",
"max_line_length": 157,
"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_zero.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": 12032,
"size": 28806
} |
#pragma once
#include <gsl\gsl>
#include <winrt\base.h>
#include <d3d11.h>
#include "DrawableGameComponent.h"
#include "BasicTessellationMaterial.h"
#include "RenderStateHelper.h"
namespace Rendering
{
class BasicTessellationDemo final : public Library::DrawableGameComponent
{
public:
BasicTessellationDemo(Library::Game& game, const std::shared_ptr<Library::Camera>& camera);
BasicTessellationDemo(const BasicTessellationDemo&) = delete;
BasicTessellationDemo(BasicTessellationDemo&&) = default;
BasicTessellationDemo& operator=(const BasicTessellationDemo&) = default;
BasicTessellationDemo& operator=(BasicTessellationDemo&&) = default;
~BasicTessellationDemo();
bool UseUniformTessellation() const;
void SetUseUniformTessellation(bool useUniformTessellation);
void ToggleUseUniformTessellation();
bool ShowQuadTopology() const;
void SetShowQuadTopology(bool showQuadTopology);
void ToggleTopology();
gsl::span<const float> EdgeFactors() const;
void SetUniformEdgeFactors(float factor);
void SetEdgeFactor(float factor, std::uint32_t index);
void SetInsideFactor(float factor, std::uint32_t index);
gsl::span<const float> InsideFactors() const;
virtual void Initialize() override;
virtual void Draw(const Library::GameTime& gameTime) override;
private:
/*void UpdateEdgeFactors();
void UpdateInsideEdgeFactors();*/
Library::RenderStateHelper mRenderStateHelper;
BasicTessellationMaterial mMaterial;
winrt::com_ptr<ID3D11Buffer> mTriVertexBuffer;
winrt::com_ptr<ID3D11Buffer> mQuadVertexBuffer;
bool mUpdateMaterial{ true };
bool mUseUniformTessellation{ true };
};
} | {
"alphanum_fraction": 0.7858450275,
"avg_line_length": 32.78,
"ext": "h",
"hexsha": "52c52a26defb45b733c09807e20653634b8b6b4c",
"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/10.2_Basic_Tessellation/BasicTessellationDemo.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/10.2_Basic_Tessellation/BasicTessellationDemo.h",
"max_line_length": 93,
"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/10.2_Basic_Tessellation/BasicTessellationDemo.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 421,
"size": 1639
} |
/* -----------------------------------------------------------------------------
* Copyright 2021 Jonathan Haigh
* SPDX-License-Identifier: MIT
* ---------------------------------------------------------------------------*/
#ifndef SQ_INCLUDE_GUARD_core_narrow_h_
#define SQ_INCLUDE_GUARD_core_narrow_h_
#include "core/typeutil.h"
#include <concepts>
#include <cstddef>
#include <gsl/gsl>
#include <string_view>
namespace sq {
/**
* Wrapper around gsl::narrow that provides better diags on failure.
*
* @param value value to convert
* @param format_args optional arguments, passed to fmt::format that describe
* what kind of thing is being converted.
*
* E.g.
* narrow<int>(0.5, "number of words in file {}", path)
* might throw an exception with a message like:
* number of words in file "/some/file" (0.5) does not fit in type int
*
* If the optional format_args args aren't given then the value's type is used
* as a description instead. E.g.
* narrow<int>(0.5)
* might throw an exception with a message like:
* float (0.5) does not fit in type int
*/
template <typename T, typename U, typename... FormatArgs>
SQ_ND constexpr T narrow(U value, FormatArgs &&...format_args);
/**
* Convert an integral value to a gsl::index.
*
* Throws if the value can't be represented by a gsl::index.
*/
SQ_ND constexpr gsl::index to_index(auto value, auto &&...format_args);
/**
* Convert an integral value to a std::size_t.
*
* Throws if the value can't be represented by a std::size_t.
*/
SQ_ND constexpr std::size_t to_size(auto value, auto &&...format_args);
} // namespace sq
#include "core/narrow.inl.h"
#endif // SQ_INCLUDE_GUARD_core_narrow_h_
| {
"alphanum_fraction": 0.6417206836,
"avg_line_length": 29.2586206897,
"ext": "h",
"hexsha": "cce2a0645b7805a25e66833acce08dcbe58ff498",
"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/narrow.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/narrow.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/narrow.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": 395,
"size": 1697
} |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
#pragma once
#include "arcana/bob/bob_helpers.h"
#include <cstdint>
#include <string>
#include <vector>
#include <cereal/cereal.hpp>
#include <cereal/types/vector.hpp>
#include <gsl/gsl>
namespace mira
{
namespace bob
{
namespace v1
{
namespace
{
constexpr std::uint32_t VERSION = 1;
}
//
// manifest and stream_file_header are both types found in the json
// manifest file. This file describes in a human readable format what the bob
// stream contains and which data it depends on.
//
// entry_instance is the header data of each instance of an entry stream in the
// binary stream file (.bob).
//
//
// Describes what the binary stream file contains
//
class stream_file_header
{
public:
//
// An entry describes the properties of one type of packet found in the stream
//
class entry
{
public:
entry()
: m_name{}
, m_type{}
, m_version{}
{}
entry(std::string name, ::uint32_t version)
: m_name{ std::move(name) }
, m_type{}
, m_version{ version }
{}
entry(std::string name, std::string type, ::uint32_t version)
: m_name{ std::move(name) }
, m_type{ std::move(type) }
, m_version{ version }
{}
const std::string& name() const
{
return m_name;
}
const std::string& type() const
{
return m_type;
}
std::uint32_t version() const
{
return m_version;
}
template<typename Archive>
void serialize(Archive& ar)
{
ar(cereal::make_nvp("Name", m_name), cereal::make_nvp("Type", m_type), cereal::make_nvp("Version", m_version));
}
private:
std::string m_name;
std::string m_type;
std::uint32_t m_version;
};
stream_file_header() = default;
explicit stream_file_header(std::vector<entry> entries)
: m_entries(std::move(entries))
{}
std::uint32_t version() const
{
return VERSION;
}
const std::vector<entry>& entries() const
{
return m_entries;
}
template<typename Archive>
void serialize(Archive& ar, const std::uint32_t version)
{
if (version != VERSION)
throw_invalid_version();
ar(cereal::make_nvp("Entries", m_entries));
}
private:
std::vector<entry> m_entries;
};
class manifest
{
public:
manifest() = default;
manifest(stream_file_header header)
: m_stream{ std::move(header) }
{}
std::uint32_t version() const
{
return VERSION;
}
const stream_file_header& stream() const
{
return m_stream;
}
template<typename Archive>
void serialize(Archive& ar, const std::uint32_t version)
{
if (version != VERSION)
throw_invalid_version();
ar(cereal::make_nvp("Stream", m_stream));
}
private:
stream_file_header m_stream;
};
//
// describes an entry in the binary stream, the data for the entry
// is contained between this block and the next.
//
struct entry_instance
{
std::int64_t Timestamp;
std::int64_t NextBlockOffset;
std::int32_t EntryIdx;
template<typename Archive>
void serialize(Archive& ar, const std::uint32_t version)
{
if (version != VERSION)
throw_invalid_version();
ar(CEREAL_NVP(Timestamp), CEREAL_NVP(NextBlockOffset), CEREAL_NVP(EntryIdx));
}
};
}
using namespace v1;
}
}
CEREAL_CLASS_VERSION(::mira::bob::v1::manifest, ::mira::bob::v1::VERSION);
CEREAL_CLASS_VERSION(::mira::bob::v1::stream_file_header, ::mira::bob::v1::VERSION);
| {
"alphanum_fraction": 0.4292948237,
"avg_line_length": 29.2967032967,
"ext": "h",
"hexsha": "a19f8ff4c4e5df5d8e31334334fdee11258e565a",
"lang": "C",
"max_forks_count": 16,
"max_forks_repo_forks_event_max_datetime": "2022-03-31T15:36:49.000Z",
"max_forks_repo_forks_event_min_datetime": "2020-05-07T03:09:13.000Z",
"max_forks_repo_head_hexsha": "ba79a4e6315689c072c29749de18d70279a4c5e4",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "syntheticmagus/mageslam",
"max_forks_repo_path": "Dependencies/Arcana/Shared/arcana/bob/bob_data.h",
"max_issues_count": 3,
"max_issues_repo_head_hexsha": "ba79a4e6315689c072c29749de18d70279a4c5e4",
"max_issues_repo_issues_event_max_datetime": "2020-10-08T07:43:32.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-06-01T00:34:01.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "syntheticmagus/mageslam",
"max_issues_repo_path": "Dependencies/Arcana/Shared/arcana/bob/bob_data.h",
"max_line_length": 135,
"max_stars_count": 70,
"max_stars_repo_head_hexsha": "ba79a4e6315689c072c29749de18d70279a4c5e4",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "syntheticmagus/mageslam",
"max_stars_repo_path": "Dependencies/Arcana/Shared/arcana/bob/bob_data.h",
"max_stars_repo_stars_event_max_datetime": "2022-02-11T01:04:54.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-05-07T03:09:09.000Z",
"num_tokens": 951,
"size": 5332
} |
#include <cblas.h>
#include <stdlib.h>
#include <string.h>
#include "loss.h"
void expit(const double *x, double *out, int x_len) {
for (int i = 0; i < x_len; i++) {
if (x[i] > 0) {
out[i] = 1. / (1. + exp(-x[i]));
} else {
out[i] = 1. - 1. / (1. + exp(x[i]));
}
}
}
void log_logistic(const double *x, double *out, int x_len) {
for (int i = 0; i < x_len; i++) {
if (x[i] > 0.0) {
out[i] = -log(1.0 + exp(-x[i]));
} else {
out[i] = x[i] - log(1.0 + exp(x[i]));
}
}
}
void logistic(const double *x, double *out, int x_len) {
for (int i = 0; i < x_len; i++) {
if (x[i] > 0) {
out[i] = 1. / (1. + exp(-x[i]));
} else {
out[i] = 1. - 1. / (1. + exp(x[i]));
}
}
}
double log_sum_exp(const double *x, int x_len) {
double max_x = x[0], out = 0.0;
for (int i = 1; i < x_len; i++) {
if (x[i] > max_x) {
max_x = x[i];
}
}
for (int i = 0; i < x_len; i++) {
out += exp(x[i] - max_x);
}
return max_x + log(out);
}
void logistic_loss_grad(const double *w,
const double *x_tr,
const double *y_tr,
double *loss_grad,
double eta,
int n_samples,
int n_features) {
for (int i = 0; i < n_features + 1; i++) {
if (isnan(w[i])) {
printf("%f\n", w[i]);
printf("warning: loss grad error!\n");
break;
}
}
int i, n = n_samples, p = n_features;
double intercept = w[p], sum_z0 = 0.0;
loss_grad[0] = 0.0;
double *yz = malloc(sizeof(double) * n);
double *z0 = malloc(sizeof(double) * n);
double *logistic = malloc(sizeof(double) * n);
for (i = 0; i < n; i++) { /** calculate yz */
yz[i] = intercept;
}
//x_tr^T*w+
cblas_dgemv(CblasRowMajor, CblasNoTrans, n, p, 1., x_tr, p, w, 1, 1., yz, 1);
for (i = 0; i < n; i++) {
yz[i] *= y_tr[i];
}
expit(yz, z0, n); // calculate z0 and final intercept
/** calculate logistic logistic[i] = 1/(1+exp(-y[i]*(xi^T*w+c)))*/
log_logistic(yz, logistic, n);
/** calculate loss of data fitting part*/
for (i = 0; i < n; i++) {
z0[i] = (z0[i] - 1.) * y_tr[i];
sum_z0 += z0[i];
loss_grad[0] -= logistic[i];
}
/**calculate loss of regularization part (it does not have intercept)*/
loss_grad[0] += 0.5 * eta * cblas_ddot(p, w, 1, w, 1);
/** calculate gradient of coefficients*/
memcpy(loss_grad + 1, w, sizeof(double) * p);
/** x^T*z0 + eta*w, where z0[i]=(logistic[i] - 1.)*yi*/
cblas_dgemv(CblasRowMajor, CblasTrans,
n, p, 1., x_tr, p, z0, 1, eta, loss_grad + 1, 1);
/** calculate gradient of intercept part*/
loss_grad[p + 1] = sum_z0; // intercept part
free(logistic);
free(z0);
free(yz);
}
void logistic_loss_grad_sparse(const double *w,
const double *x_tr,
const double *y_tr,
double *loss_grad,
double eta,
int n_samples,
int n_features) {
//sub_p is number of nonzeros in w.
int i, n = n_samples, p = n_features, sub_p = 0;
double intercept = w[p], sum_z0 = 0.0;
loss_grad[0] = 0.0;
double *yz = malloc(sizeof(double) * n);
double *z0 = malloc(sizeof(double) * n);
double *logistic = malloc(sizeof(double) * n);
for (i = 0; i < n; i++) { /** calculate yz */
yz[i] = intercept;
}
double nonzero_w[p];
int nonzero_w_ind[p];
for (i = 0; i < p; i++) {
if (w[i] != 0.0) {
nonzero_w_ind[sub_p] = i;
nonzero_w[sub_p] = w[i];
sub_p++;
}
}
//x_tr^T*w+ to use the sparsity of w
for (i = 0; i < n; i++) {
double tmp_val = 0.0;
for (int j = 0; j < sub_p; j++) {
tmp_val += x_tr[i * p + nonzero_w_ind[j]] * nonzero_w[j];
}
yz[i] = yz[i] + tmp_val;
}
for (i = 0; i < n; i++) {
yz[i] *= y_tr[i];
}
expit(yz, z0, n); // calculate z0 and final intercept
/** calculate logistic logistic[i] = 1/(1+exp(-y[i]*(xi^T*w+c)))*/
log_logistic(yz, logistic, n);
/** calculate loss of data fitting part*/
for (i = 0; i < n; i++) {
z0[i] = (z0[i] - 1.) * y_tr[i];
sum_z0 += z0[i];
loss_grad[0] -= logistic[i];
}
/**calculate loss of regularization part (it does not have intercept)*/
loss_grad[0] += 0.5 * eta * cblas_ddot(p, w, 1, w, 1);
/** calculate gradient of coefficients*/
memcpy(loss_grad + 1, w, sizeof(double) * p);
/** x^T*z0 + eta*w, where z0[i]=(logistic[i] - 1.)*yi*/
cblas_dgemv(CblasRowMajor, CblasTrans,
n, p, 1., x_tr, p, z0, 1, eta, loss_grad + 1, 1);
/** calculate gradient of intercept part*/
loss_grad[p + 1] = sum_z0; // intercept part
free(logistic);
free(z0);
free(yz);
}
void logistic_predict(const double *x_te,
const double *wt,
double *pred_prob,
double *pred_label,
double threshold,
int n,
int p) {
openblas_set_num_threads(1);
int i;
cblas_dgemv(CblasRowMajor, CblasNoTrans,
n, p, 1., x_te, p, wt, 1, 0., pred_prob, 1);
for (i = 0; i < n; i++) {
pred_prob[i] += wt[p]; // intercept
}
expit(pred_prob, pred_prob, n);
for (i = 0; i < n; i++) {
if (pred_prob[i] >= threshold) {
pred_label[i] = 1.;
} else {
pred_label[i] = -1.;
}
}
}
void least_square_loss_grad(const double *w,
const double *x_tr,
const double *y_tr,
double *loss_grad,
double eta,
int n_samples,
int n_features) {
for (int i = 0; i < n_features + 1; i++) {
if (isnan(w[i])) {
printf("%f\n", w[i]);
printf("warning: loss grad error!\n");
break;
}
}
int i, n = n_samples, p = n_features;
double *yz = malloc(sizeof(double) * n);
double *w0 = malloc(sizeof(double) * n);
cblas_dcopy(n, y_tr, 1, yz, 1); // y_tr --> yz
cblas_dscal(p + 2, 0.0, loss_grad, 1);
cblas_daxpy(p, eta, w, 1, loss_grad + 1, 1); // l2_lambda*w --> loss_grad
//Order,TransA, M, N, alpha, A, lda, x, incX, beta, Y, incY
// Y<-alpha*AX + beta*Y, where A=MxN, Y=N
cblas_dgemv(CblasRowMajor, CblasNoTrans,
n, p, 1., x_tr, p, w, 1, -1., yz, 1); //Xw - y
for (i = 0; i < n; i++) { w0[i] = w[p]; }
cblas_daxpy(n, 1., w0, 1, yz, 1);
loss_grad[0] = cblas_ddot(n, yz, 1, yz, 1) / (2. * n);
loss_grad[0] += (.5 * eta) * cblas_ddot(p, w, 1, w, 1); //loss
cblas_dgemv(CblasRowMajor, CblasTrans,
n, p, 1. / n, x_tr, p, yz, 1, 1., loss_grad + 1, 1);
for (i = 0; i < n; i++) {
w0[i] = w[p];
loss_grad[p + 1] = yz[i];
}
loss_grad[p + 1] /= n;
free(w0), free(yz);
}
void least_square_predict(const double *x_te,
const double *wt,
double *pred_prob,
double *pred_label,
double threshold,
int n_samples,
int p_features) {
openblas_set_num_threads(1);
int i, n = n_samples, p = p_features;
cblas_dgemv(CblasRowMajor, CblasNoTrans,
n, p, 1., x_te, p, wt, 1, 0., pred_prob, 1);
for (i = 0; i < n; i++) {
pred_prob[i] += wt[p]; // intercept
}
// this is not useful.
for (i = 0; i < n; i++) {
if (pred_prob[i] >= threshold) {
pred_label[i] = 1.;
} else {
pred_label[i] = -1.;
}
}
} | {
"alphanum_fraction": 0.4607915438,
"avg_line_length": 33.0731707317,
"ext": "c",
"hexsha": "301a032d5bea92309a1f380217799b0ac857abe0",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2021-02-08T11:52:16.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-02-08T11:52:16.000Z",
"max_forks_repo_head_hexsha": "2f338cdd9188dc6464c2efb3770d55fd964d1bd0",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "baojianzhou/sparse-auc",
"max_forks_repo_path": "algo_wrapper/loss.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "2f338cdd9188dc6464c2efb3770d55fd964d1bd0",
"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": "baojianzhou/sparse-auc",
"max_issues_repo_path": "algo_wrapper/loss.c",
"max_line_length": 81,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "2f338cdd9188dc6464c2efb3770d55fd964d1bd0",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "baojianzhou/sparse-auc",
"max_stars_repo_path": "algo_wrapper/loss.c",
"max_stars_repo_stars_event_max_datetime": "2020-11-13T13:45:14.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-11-13T13:45:14.000Z",
"num_tokens": 2583,
"size": 8136
} |
/* matrix/gsl_matrix_float.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_FLOAT_H__
#define __GSL_MATRIX_FLOAT_H__
#include <stdlib.h>
#include <gsl/gsl_types.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_inline.h>
#include <gsl/gsl_check_range.h>
#include <gsl/gsl_vector_float.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;
float * data;
gsl_block_float * block;
int owner;
} gsl_matrix_float;
typedef struct
{
gsl_matrix_float matrix;
} _gsl_matrix_float_view;
typedef _gsl_matrix_float_view gsl_matrix_float_view;
typedef struct
{
gsl_matrix_float matrix;
} _gsl_matrix_float_const_view;
typedef const _gsl_matrix_float_const_view gsl_matrix_float_const_view;
/* Allocation */
gsl_matrix_float *
gsl_matrix_float_alloc (const size_t n1, const size_t n2);
gsl_matrix_float *
gsl_matrix_float_calloc (const size_t n1, const size_t n2);
gsl_matrix_float *
gsl_matrix_float_alloc_from_block (gsl_block_float * b,
const size_t offset,
const size_t n1,
const size_t n2,
const size_t d2);
gsl_matrix_float *
gsl_matrix_float_alloc_from_matrix (gsl_matrix_float * m,
const size_t k1,
const size_t k2,
const size_t n1,
const size_t n2);
gsl_vector_float *
gsl_vector_float_alloc_row_from_matrix (gsl_matrix_float * m,
const size_t i);
gsl_vector_float *
gsl_vector_float_alloc_col_from_matrix (gsl_matrix_float * m,
const size_t j);
void gsl_matrix_float_free (gsl_matrix_float * m);
/* Views */
_gsl_matrix_float_view
gsl_matrix_float_submatrix (gsl_matrix_float * m,
const size_t i, const size_t j,
const size_t n1, const size_t n2);
_gsl_vector_float_view
gsl_matrix_float_row (gsl_matrix_float * m, const size_t i);
_gsl_vector_float_view
gsl_matrix_float_column (gsl_matrix_float * m, const size_t j);
_gsl_vector_float_view
gsl_matrix_float_diagonal (gsl_matrix_float * m);
_gsl_vector_float_view
gsl_matrix_float_subdiagonal (gsl_matrix_float * m, const size_t k);
_gsl_vector_float_view
gsl_matrix_float_superdiagonal (gsl_matrix_float * m, const size_t k);
_gsl_vector_float_view
gsl_matrix_float_subrow (gsl_matrix_float * m, const size_t i,
const size_t offset, const size_t n);
_gsl_vector_float_view
gsl_matrix_float_subcolumn (gsl_matrix_float * m, const size_t j,
const size_t offset, const size_t n);
_gsl_matrix_float_view
gsl_matrix_float_view_array (float * base,
const size_t n1,
const size_t n2);
_gsl_matrix_float_view
gsl_matrix_float_view_array_with_tda (float * base,
const size_t n1,
const size_t n2,
const size_t tda);
_gsl_matrix_float_view
gsl_matrix_float_view_vector (gsl_vector_float * v,
const size_t n1,
const size_t n2);
_gsl_matrix_float_view
gsl_matrix_float_view_vector_with_tda (gsl_vector_float * v,
const size_t n1,
const size_t n2,
const size_t tda);
_gsl_matrix_float_const_view
gsl_matrix_float_const_submatrix (const gsl_matrix_float * m,
const size_t i, const size_t j,
const size_t n1, const size_t n2);
_gsl_vector_float_const_view
gsl_matrix_float_const_row (const gsl_matrix_float * m,
const size_t i);
_gsl_vector_float_const_view
gsl_matrix_float_const_column (const gsl_matrix_float * m,
const size_t j);
_gsl_vector_float_const_view
gsl_matrix_float_const_diagonal (const gsl_matrix_float * m);
_gsl_vector_float_const_view
gsl_matrix_float_const_subdiagonal (const gsl_matrix_float * m,
const size_t k);
_gsl_vector_float_const_view
gsl_matrix_float_const_superdiagonal (const gsl_matrix_float * m,
const size_t k);
_gsl_vector_float_const_view
gsl_matrix_float_const_subrow (const gsl_matrix_float * m, const size_t i,
const size_t offset, const size_t n);
_gsl_vector_float_const_view
gsl_matrix_float_const_subcolumn (const gsl_matrix_float * m, const size_t j,
const size_t offset, const size_t n);
_gsl_matrix_float_const_view
gsl_matrix_float_const_view_array (const float * base,
const size_t n1,
const size_t n2);
_gsl_matrix_float_const_view
gsl_matrix_float_const_view_array_with_tda (const float * base,
const size_t n1,
const size_t n2,
const size_t tda);
_gsl_matrix_float_const_view
gsl_matrix_float_const_view_vector (const gsl_vector_float * v,
const size_t n1,
const size_t n2);
_gsl_matrix_float_const_view
gsl_matrix_float_const_view_vector_with_tda (const gsl_vector_float * v,
const size_t n1,
const size_t n2,
const size_t tda);
/* Operations */
void gsl_matrix_float_set_zero (gsl_matrix_float * m);
void gsl_matrix_float_set_identity (gsl_matrix_float * m);
void gsl_matrix_float_set_all (gsl_matrix_float * m, float x);
int gsl_matrix_float_fread (FILE * stream, gsl_matrix_float * m) ;
int gsl_matrix_float_fwrite (FILE * stream, const gsl_matrix_float * m) ;
int gsl_matrix_float_fscanf (FILE * stream, gsl_matrix_float * m);
int gsl_matrix_float_fprintf (FILE * stream, const gsl_matrix_float * m, const char * format);
int gsl_matrix_float_memcpy(gsl_matrix_float * dest, const gsl_matrix_float * src);
int gsl_matrix_float_swap(gsl_matrix_float * m1, gsl_matrix_float * m2);
int gsl_matrix_float_swap_rows(gsl_matrix_float * m, const size_t i, const size_t j);
int gsl_matrix_float_swap_columns(gsl_matrix_float * m, const size_t i, const size_t j);
int gsl_matrix_float_swap_rowcol(gsl_matrix_float * m, const size_t i, const size_t j);
int gsl_matrix_float_transpose (gsl_matrix_float * m);
int gsl_matrix_float_transpose_memcpy (gsl_matrix_float * dest, const gsl_matrix_float * src);
float gsl_matrix_float_max (const gsl_matrix_float * m);
float gsl_matrix_float_min (const gsl_matrix_float * m);
void gsl_matrix_float_minmax (const gsl_matrix_float * m, float * min_out, float * max_out);
void gsl_matrix_float_max_index (const gsl_matrix_float * m, size_t * imax, size_t *jmax);
void gsl_matrix_float_min_index (const gsl_matrix_float * m, size_t * imin, size_t *jmin);
void gsl_matrix_float_minmax_index (const gsl_matrix_float * m, size_t * imin, size_t * jmin, size_t * imax, size_t * jmax);
int gsl_matrix_float_equal (const gsl_matrix_float * a, const gsl_matrix_float * b);
int gsl_matrix_float_isnull (const gsl_matrix_float * m);
int gsl_matrix_float_ispos (const gsl_matrix_float * m);
int gsl_matrix_float_isneg (const gsl_matrix_float * m);
int gsl_matrix_float_isnonneg (const gsl_matrix_float * m);
int gsl_matrix_float_add (gsl_matrix_float * a, const gsl_matrix_float * b);
int gsl_matrix_float_sub (gsl_matrix_float * a, const gsl_matrix_float * b);
int gsl_matrix_float_mul_elements (gsl_matrix_float * a, const gsl_matrix_float * b);
int gsl_matrix_float_div_elements (gsl_matrix_float * a, const gsl_matrix_float * b);
int gsl_matrix_float_scale (gsl_matrix_float * a, const double x);
int gsl_matrix_float_add_constant (gsl_matrix_float * a, const double x);
int gsl_matrix_float_add_diagonal (gsl_matrix_float * a, const double x);
/***********************************************************************/
/* The functions below are obsolete */
/***********************************************************************/
int gsl_matrix_float_get_row(gsl_vector_float * v, const gsl_matrix_float * m, const size_t i);
int gsl_matrix_float_get_col(gsl_vector_float * v, const gsl_matrix_float * m, const size_t j);
int gsl_matrix_float_set_row(gsl_matrix_float * m, const size_t i, const gsl_vector_float * v);
int gsl_matrix_float_set_col(gsl_matrix_float * m, const size_t j, const gsl_vector_float * v);
/***********************************************************************/
/* inline functions if you are using GCC */
INLINE_DECL float gsl_matrix_float_get(const gsl_matrix_float * m, const size_t i, const size_t j);
INLINE_DECL void gsl_matrix_float_set(gsl_matrix_float * m, const size_t i, const size_t j, const float x);
INLINE_DECL float * gsl_matrix_float_ptr(gsl_matrix_float * m, const size_t i, const size_t j);
INLINE_DECL const float * gsl_matrix_float_const_ptr(const gsl_matrix_float * m, const size_t i, const size_t j);
#ifdef HAVE_INLINE
INLINE_FUN
float
gsl_matrix_float_get(const gsl_matrix_float * 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_float_set(gsl_matrix_float * m, const size_t i, const size_t j, const float 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
float *
gsl_matrix_float_ptr(gsl_matrix_float * 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 (float *) (m->data + (i * m->tda + j)) ;
}
INLINE_FUN
const float *
gsl_matrix_float_const_ptr(const gsl_matrix_float * 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 float *) (m->data + (i * m->tda + j)) ;
}
#endif
__END_DECLS
#endif /* __GSL_MATRIX_FLOAT_H__ */
| {
"alphanum_fraction": 0.6543501261,
"avg_line_length": 35.0056980057,
"ext": "h",
"hexsha": "9af95e0261ea1aa831c27db5e7d30b4ab728be2f",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2020-08-30T20:40:25.000Z",
"max_forks_repo_forks_event_min_datetime": "2020-08-30T20:40:25.000Z",
"max_forks_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "ielomariala/Hex-Game",
"max_forks_repo_path": "gsl-2.6/gsl/gsl_matrix_float.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a",
"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": "ielomariala/Hex-Game",
"max_issues_repo_path": "gsl-2.6/gsl/gsl_matrix_float.h",
"max_line_length": 124,
"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/gsl/gsl_matrix_float.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 2900,
"size": 12287
} |
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include <gsl/gsl_integration.h>
#include <gsl/gsl_interp.h>
#include <gsl/gsl_spline.h>
#include <gsl/gsl_errno.h>
#include "ccl.h"
/*----- ROUTINE: dc_NakamuraSuto -----
INPUT: cosmology, scale factor
TASK: Computes the peak threshold: delta_c(z) assuming LCDM.
Cosmology dependence of the critical linear density according to the spherical-collapse model.
Fitting function from Nakamura & Suto (1997; arXiv:astro-ph/9710107).
*/
double dc_NakamuraSuto(ccl_cosmology *cosmo, double a, int *status){
double Om_mz = ccl_omega_x(cosmo, a, ccl_species_m_label, status);
double dc0 = (3./20.)*pow(12.*M_PI,2./3.);
double dc = dc0*(1.+0.012299*log10(Om_mz));
return dc;
}
/*----- ROUTINE: Dv_BryanNorman -----
INPUT: cosmology, scale factor
TASK: Computes the virial collapse density contrast with respect to the matter density assuming LCDM.
Cosmology dependence of the virial collapse density according to the spherical-collapse model
Fitting function from Bryan & Norman (1998; arXiv:astro-ph/9710107)
*/
double Dv_BryanNorman(ccl_cosmology *cosmo, double a, int *status){
double Om_mz = ccl_omega_x(cosmo, a, ccl_species_m_label, status);
double x = Om_mz-1.;
double Dv0 = 18.*pow(M_PI,2);
double Dv = (Dv0+82.*x-39.*pow(x,2))/Om_mz;
return Dv;
}
/*----- ROUTINE: r_delta -----
INPUT: cosmology, halo mass, scale factor, halo overdensity
TASK: Computes comoving halo radius assuming the overdensity criteria
*/
double r_delta(ccl_cosmology *cosmo, double halomass, double a, double odelta, int *status){
double rho_matter = ccl_rho_x(cosmo, 1., 1, 1, status);
return pow(halomass*3.0/(4.0*M_PI*rho_matter*odelta),1.0/3.0);
}
// This checks to make sure all necessary halo mass function parameters have been set-up,
// as well as associated splines.
void ccl_cosmology_compute_hmfparams(ccl_cosmology *cosmo, int *status) {
if(cosmo->computed_hmfparams)
return;
gsl_spline* alphahmf = NULL;
gsl_spline* betahmf = NULL;
gsl_spline* gammahmf = NULL;
gsl_spline* phihmf = NULL;
gsl_spline* etahmf = NULL;
// declare parameter splines on case-by-case basis
switch(cosmo->config.mass_function_method) {
case ccl_tinker10:{
double delta[9] = {200.0, 300.0, 400.0, 600.0, 800.0, 1200.0, 1600.0, 2400.0, 3200.0};
double lgdelta[9];
double alpha[9] = {0.368, 0.363, 0.385, 0.389, 0.393, 0.365, 0.379, 0.355, 0.327};
double beta[9] = {0.589, 0.585, 0.544, 0.543, 0.564, 0.623, 0.637, 0.673, 0.702};
double gamma[9] ={0.864, 0.922, 0.987, 1.09, 1.20, 1.34, 1.50, 1.68, 1.81};
double phi[9] = {-0.729, -0.789, -0.910, -1.05, -1.20, -1.26, -1.45, -1.50, -1.49};
double eta[9] = {-0.243, -0.261, -0.261, -0.273, -0.278, -0.301, -0.301, -0.319, -0.336};
int nd = 9;
int i;
for(i=0; i<nd; i++) {
lgdelta[i] = log10(delta[i]);
}
if (*status == 0) {
alphahmf = gsl_spline_alloc(cosmo->spline_params.D_SPLINE_TYPE, nd);
if (alphahmf == NULL) {
*status = CCL_ERROR_MEMORY;
ccl_cosmology_set_status_message(
cosmo,
"ccl_massfunc.c: ccl_cosmology_compute_hmfparams(): Error allocating alpha(D) spline\n");
}
}
if (*status == 0) {
*status = gsl_spline_init(alphahmf, lgdelta, alpha, nd);
if (*status) {
*status = CCL_ERROR_SPLINE ;
ccl_cosmology_set_status_message(
cosmo,
"ccl_massfunc.c: ccl_cosmology_compute_hmfparams(): Error creating alpha(D) spline\n");
}
}
if (*status == 0) {
betahmf = gsl_spline_alloc(cosmo->spline_params.D_SPLINE_TYPE, nd);
if (betahmf == NULL) {
*status = CCL_ERROR_MEMORY;
ccl_cosmology_set_status_message(
cosmo,
"ccl_massfunc.c: ccl_cosmology_compute_hmfparams(): Error allocating beta(D) spline\n");
}
}
if (*status == 0) {
*status = gsl_spline_init(betahmf, lgdelta, beta, nd);
if (*status) {
*status = CCL_ERROR_SPLINE;
ccl_cosmology_set_status_message(
cosmo,
"ccl_massfunc.c: ccl_cosmology_compute_hmfparams(): Error creating beta(D) spline\n");
}
}
if (*status == 0) {
gammahmf = gsl_spline_alloc(cosmo->spline_params.D_SPLINE_TYPE, nd);
if (gammahmf == NULL) {
*status = CCL_ERROR_MEMORY;
ccl_cosmology_set_status_message(
cosmo,
"ccl_massfunc.c: ccl_cosmology_compute_hmfparams(): Error allocating gamma(D) spline\n");
}
}
if (*status == 0) {
*status = gsl_spline_init(gammahmf, lgdelta, gamma, nd);
if (*status) {
*status = CCL_ERROR_SPLINE;
ccl_cosmology_set_status_message(
cosmo,
"ccl_massfunc.c: ccl_cosmology_compute_hmfparams(): Error creating gamma(D) spline\n");
}
}
if (*status == 0) {
phihmf = gsl_spline_alloc(cosmo->spline_params.D_SPLINE_TYPE, nd);
if (phihmf == NULL) {
*status = CCL_ERROR_MEMORY;
ccl_cosmology_set_status_message(
cosmo,
"ccl_massfunc.c: ccl_cosmology_compute_hmfparams(): Error allocating phi(D) spline\n");
}
}
if (*status == 0) {
*status = gsl_spline_init(phihmf, lgdelta, phi, nd);
if (*status) {
*status = CCL_ERROR_SPLINE;
ccl_cosmology_set_status_message(
cosmo,
"ccl_massfunc.c: ccl_cosmology_compute_hmfparams(): Error creating phi(D) spline\n");
}
}
if (*status == 0) {
etahmf = gsl_spline_alloc(cosmo->spline_params.D_SPLINE_TYPE, nd);
if (etahmf == NULL) {
*status = CCL_ERROR_MEMORY;
ccl_cosmology_set_status_message(
cosmo,
"ccl_massfunc.c: ccl_cosmology_compute_hmfparams(): Error allocating eta(D) spline\n");
}
}
if (*status == 0) {
*status = gsl_spline_init(etahmf, lgdelta, eta, nd);
if (*status) {
*status = CCL_ERROR_SPLINE;
ccl_cosmology_set_status_message(
cosmo,
"ccl_massfunc.c: ccl_cosmology_compute_hmfparams(): Error creating eta(D) spline\n");
}
}
if (*status == 0) {
cosmo->data.alphahmf = alphahmf;
cosmo->data.betahmf = betahmf;
cosmo->data.gammahmf = gammahmf;
cosmo->data.phihmf = phihmf;
cosmo->data.etahmf = etahmf;
cosmo->computed_hmfparams = true;
}
break;
}
case ccl_tinker:{
double delta[9] = {200.0, 300.0, 400.0, 600.0, 800.0, 1200.0, 1600.0, 2400.0, 3200.0};
double lgdelta[9];
double alpha[9] = {0.186, 0.200, 0.212, 0.218, 0.248, 0.255, 0.260, 0.260, 0.260};
double beta[9] = {1.47, 1.52, 1.56, 1.61, 1.87, 2.13, 2.30, 2.53, 2.66};
double gamma[9] ={2.57, 2.25, 2.05, 1.87, 1.59, 1.51, 1.46, 1.44, 1.41};
double phi[9] = {1.19, 1.27, 1.34, 1.45, 1.58, 1.80, 1.97, 2.24, 2.44};
int nd = 9;
int i;
for(i=0; i<nd; i++) {
lgdelta[i] = log10(delta[i]);
}
if (*status == 0) {
alphahmf = gsl_spline_alloc(cosmo->spline_params.D_SPLINE_TYPE, nd);
if (alphahmf == NULL) {
*status = CCL_ERROR_MEMORY;
ccl_cosmology_set_status_message(
cosmo,
"ccl_massfunc.c: ccl_cosmology_compute_hmfparams(): Error allocating alpha(D) spline\n");
}
}
if (*status == 0) {
*status = gsl_spline_init(alphahmf, lgdelta, alpha, nd);
if (*status) {
*status = CCL_ERROR_SPLINE;
ccl_cosmology_set_status_message(
cosmo,
"ccl_massfunc.c: ccl_cosmology_compute_hmfparams(): Error creating alpha(D) spline\n");
}
}
if (*status == 0) {
betahmf = gsl_spline_alloc(cosmo->spline_params.D_SPLINE_TYPE, nd);
if (betahmf == NULL) {
*status = CCL_ERROR_MEMORY;
ccl_cosmology_set_status_message(
cosmo,
"ccl_massfunc.c: ccl_cosmology_compute_hmfparams(): Error allocating beta(D) spline\n");
}
}
if (*status == 0) {
*status = gsl_spline_init(betahmf, lgdelta, beta, nd);
if (*status) {
*status = CCL_ERROR_SPLINE;
ccl_cosmology_set_status_message(
cosmo,
"ccl_massfunc.c: ccl_cosmology_compute_hmfparams(): Error creating beta(D) spline\n");
}
}
if (*status == 0) {
gammahmf = gsl_spline_alloc(cosmo->spline_params.D_SPLINE_TYPE, nd);
if (gammahmf == NULL) {
*status = CCL_ERROR_MEMORY;
ccl_cosmology_set_status_message(
cosmo,
"ccl_massfunc.c: ccl_cosmology_compute_hmfparams(): Error allocating gamma(D) spline\n");
}
}
if (*status == 0) {
*status = gsl_spline_init(gammahmf, lgdelta, gamma, nd);
if (*status) {
*status = CCL_ERROR_SPLINE;
ccl_cosmology_set_status_message(
cosmo,
"ccl_massfunc.c: ccl_cosmology_compute_hmfparams(): Error creating gamma(D) spline\n");
}
}
if (*status == 0) {
phihmf = gsl_spline_alloc(cosmo->spline_params.D_SPLINE_TYPE, nd);
if (phihmf == NULL) {
*status = CCL_ERROR_MEMORY;
ccl_cosmology_set_status_message(
cosmo,
"ccl_massfunc.c: ccl_cosmology_compute_hmfparams(): Error allocating phi(D) spline\n");
}
}
if (*status == 0) {
*status = gsl_spline_init(phihmf, lgdelta, phi, nd);
if (*status) {
*status = CCL_ERROR_SPLINE;
ccl_cosmology_set_status_message(
cosmo,
"ccl_massfunc.c: ccl_cosmology_compute_hmfparams(): Error creating phi(D) spline\n");
}
}
if (*status == 0) {
cosmo->data.alphahmf = alphahmf;
cosmo->data.betahmf = betahmf;
cosmo->data.gammahmf = gammahmf;
cosmo->data.phihmf = phihmf;
cosmo->computed_hmfparams = true;
}
break;
}
default:
// Error message could go here if we decide to make this public facing.
// Currently not accessible from the API though.
break;
}
if (*status) {
gsl_spline_free(alphahmf);
gsl_spline_free(betahmf);
gsl_spline_free(gammahmf);
gsl_spline_free(phihmf);
gsl_spline_free(etahmf);
}
}
//TODO: some of these are unused, many are included in ccl.h
/*----- ROUTINE: ccl_massfunc_f -----
INPUT: cosmology+parameters, a halo mass, and scale factor
TASK: Outputs fitting function for use in halo mass function calculation;
currently only supports:
ccl_tinker (arxiv 0803.2706 )
ccl_tinker10 (arxiv 1001.3162 )
ccl_angulo (arxiv 1203.3216 )
ccl_watson (arxiv 1212.0095 )
ccl_shethtormen (arxiv 9901122)
-*/
static double massfunc_f(ccl_cosmology *cosmo, double halomass, double a, double odelta, int *status)
{
double fit_A, fit_a, fit_b, fit_c, fit_d, fit_p, overdensity_delta;
double Omega_m_a;
double delta_c_Tinker, nu;
double sigma=ccl_sigmaM(cosmo, log10(halomass), a, status);
int gslstatus;
switch(cosmo->config.mass_function_method) {
// Equation (10) in arxiv: 9901122
// Note that Sheth & Tormen (1999) use nu=(dc/sigma)^2 whereas we use nu=dc/sigma
case ccl_shethtormen:
// Check if odelta is outside the interpolated range
if (odelta != Dv_BryanNorman(cosmo, a, status)) {
*status = CCL_ERROR_HMF_DV;
ccl_cosmology_set_status_message(
cosmo, "ccl_massfunc.c: massfunc_f(): Sheth-Tormen called with not virial Delta_v\n");
return NAN;
}
// ST mass function fitting parameters
fit_A = 0.21616;
fit_p = 0.3;
fit_a = 0.707;
// nu = delta_c(z) / sigma(M)
nu = dc_NakamuraSuto(cosmo, a, status)/ccl_sigmaM(cosmo, log10(halomass), a, status);
return nu*fit_A*(1.+pow(fit_a*pow(nu,2),-fit_p))*exp(-fit_a*pow(nu,2)/2.);
case ccl_tinker:
// Check if odelta is outside the interpolated range
if ((odelta < 200) || (odelta > 3200)) {
*status = CCL_ERROR_HMF_INTERP;
ccl_cosmology_set_status_message(
cosmo,
"ccl_massfunc.c: massfunc_f(): Tinker 2008 only "
"supported in range of Delta = 200 to Delta = 3200.\n");
return NAN;
}
if (!cosmo->computed_hmfparams) {
*status = CCL_ERROR_HMF_INIT;
ccl_cosmology_set_status_message(
cosmo,
"ccl_massfunc.c: massfunc_f(): mass function parameters splines have not been computed!");
return NAN;
}
// Compute HMF parameter (alpha, beta, gamma, phi) splines if they haven't
// been computed already
gslstatus = gsl_spline_eval_e(cosmo->data.alphahmf, log10(odelta), NULL, &fit_A);
gslstatus |= gsl_spline_eval_e(cosmo->data.betahmf, log10(odelta), NULL, &fit_a);
gslstatus |= gsl_spline_eval_e(cosmo->data.gammahmf, log10(odelta), NULL, &fit_b);
gslstatus |= gsl_spline_eval_e(cosmo->data.phihmf, log10(odelta), NULL, &fit_c);
fit_d = pow(10, -1.0*pow(0.75 / log10(odelta / 75.0), 1.2));
fit_A = fit_A*pow(a, 0.14);
fit_a = fit_a*pow(a, 0.06);
fit_b = fit_b*pow(a, fit_d);
if(gslstatus != GSL_SUCCESS) {
ccl_raise_gsl_warning(gslstatus, "ccl_massfunc.c: massfunc_f():");
*status |= gslstatus;
ccl_cosmology_set_status_message(
cosmo, "ccl_massfunc.c: massfunc_f(): interpolation error for Tinker MF\n");
return NAN;
}
return fit_A*(pow(sigma/fit_b,-fit_a)+1.0)*exp(-fit_c/sigma/sigma);
break;
case ccl_tinker10:
// this version uses f(nu) parameterization from Eq. 8 in Tinker et al. 2010
// use this for consistency with Tinker et al. 2010 fitting function for halo bias
// Check if odelta is outside the interpolated range
if ((odelta < 200) || (odelta > 3200)) {
*status = CCL_ERROR_HMF_INTERP;
ccl_cosmology_set_status_message(
cosmo,
"ccl_massfunc.c: massfunc_f(): Tinker 2010 only "
"supported in range of Delta = 200 to Delta = 3200.\n");
return 0;
}
//critical collapse overdensity assumed in this model
delta_c_Tinker = 1.686;
nu = delta_c_Tinker/(sigma);
if (!cosmo->computed_hmfparams) {
*status = CCL_ERROR_HMF_INIT;
ccl_cosmology_set_status_message(
cosmo,
"ccl_massfunc.c: massfunc_f(): mass function parameters splines have not been computed!");
return NAN;
}
gslstatus = gsl_spline_eval_e(cosmo->data.alphahmf, log10(odelta), NULL, &fit_A); //alpha in Eq. 8
gslstatus |= gsl_spline_eval_e(cosmo->data.etahmf, log10(odelta), NULL, &fit_a); //eta in Eq. 8
gslstatus |= gsl_spline_eval_e(cosmo->data.betahmf, log10(odelta), NULL, &fit_b); //beta in Eq. 8
gslstatus |= gsl_spline_eval_e(cosmo->data.gammahmf, log10(odelta), NULL, &fit_c); //gamma in Eq. 8
gslstatus |= gsl_spline_eval_e(cosmo->data.phihmf, log10(odelta), NULL, &fit_d); //phi in Eq. 8;
fit_a *=pow(a, -0.27);
fit_b *=pow(a, -0.20);
fit_c *=pow(a, 0.01);
fit_d *=pow(a, 0.08);
if(gslstatus != GSL_SUCCESS) {
ccl_raise_gsl_warning(gslstatus, "ccl_massfunc.c: massfunc_f():");
*status |= gslstatus;
ccl_cosmology_set_status_message(
cosmo, "ccl_massfunc.c: massfunc_f(): interpolation error for Tinker 2010 MF\n");
return NAN;
}
return nu*fit_A*(1.+pow(fit_b*nu,-2.*fit_d))*pow(nu, 2.*fit_a)*exp(-0.5*fit_c*nu*nu);
break;
case ccl_watson:
if(odelta!=200.) {
*status = CCL_ERROR_HMF_INTERP;
ccl_cosmology_set_status_message(
cosmo, "ccl_massfunc.c: massfunc_f(): Watson HMF only supported for Delta = 200.\n");
return NAN;
}
// these parameters from: Angulo et al 2012 (arxiv 1203.3216 )
Omega_m_a = ccl_omega_x(cosmo, a, ccl_species_m_label,status);
fit_A = Omega_m_a*(0.990*pow(a,3.216)+0.074);
fit_a = Omega_m_a*(5.907*pow(a,3.599)+2.344);
fit_b = Omega_m_a*(3.136*pow(a,3.058)+2.349);
fit_c = 1.318;
return fit_A*(pow(sigma/fit_b,-fit_a)+1.0)*exp(-fit_c/sigma/sigma);
case ccl_angulo:
if(odelta!=200.) {
*status = CCL_ERROR_HMF_INTERP;
ccl_cosmology_set_status_message(
cosmo, "ccl_massfunc.c: massfunc_f(): Angulo HMF only supported for Delta = 200.\n");
return NAN;
}
// these parameters from: Watson et al 2012 (arxiv 1212.0095 )
fit_A = 0.201;
fit_a = 2.08;
fit_b = 1.7;
fit_c = 1.172;
return fit_A*pow( (fit_a/sigma)+1.0, fit_b)*exp(-fit_c/sigma/sigma);
default:
*status = CCL_ERROR_MF;
ccl_cosmology_set_status_message(cosmo ,
"ccl_massfunc.c: massfunc_f(): Unknown or non-implemented mass function method: %d \n",
cosmo->config.mass_function_method);
return NAN;
}
}
static double ccl_halo_b1(ccl_cosmology *cosmo, double halomass, double a, double odelta, int *status)
{
double fit_A, fit_B, fit_C, fit_a, fit_b, fit_c, fit_p, overdensity_delta, y;
double delta_c_Tinker, nu;
double sigma=ccl_sigmaM(cosmo,log10(halomass),a, status);
switch(cosmo->config.mass_function_method) {
// Equation (12) in arXiv: 9901122
// Derived using the peak-background split applied to the mass function in the same paper
// Note that Sheth & Tormen (1999) use nu=(dc/sigma)^2 whereas we use nu=dc/sigma
case ccl_shethtormen:
// Check if Delta_v is the virial Delta_v
if (odelta != Dv_BryanNorman(cosmo, a, status)) {
*status = CCL_ERROR_HMF_DV;
ccl_cosmology_set_status_message(
cosmo, "ccl_massfunc.c: halo_b1(): Sheth-Tormen called with not virial Delta_v\n");
return NAN;
}
// ST bias fitting parameters (which are the same as for the mass function)
fit_p = 0.3;
fit_a = 0.707;
// Cosmology dependent delta_c and nu
double delta_c = dc_NakamuraSuto(cosmo, a, status);
nu = delta_c/ccl_sigmaM(cosmo, log10(halomass), a, status);
return 1.+(fit_a*pow(nu,2)-1.+2.*fit_p/(1.+pow(fit_a*pow(nu,2),fit_p)))/delta_c;
//this version uses b(nu) parameterization, Eq. 6 in Tinker et al. 2010
// use this for consistency with Tinker et al. 2010 fitting function for halo bias
case ccl_tinker10:
y = log10(odelta);
//critical collapse overdensity assumed in this model
delta_c_Tinker = 1.686;
//peak height - note that this factorization is incorrect for e.g. massive neutrino cosmologies
nu = delta_c_Tinker/(sigma);
// Table 2 in https://arxiv.org/pdf/1001.3162.pdf
fit_A = 1.0 + 0.24*y*exp(-pow(4./y,4.));
fit_a = 0.44*y-0.88;
fit_B = 0.183;
fit_b = 1.5;
fit_C = 0.019+0.107*y+0.19*exp(-pow(4./y,4.));
fit_c = 2.4;
return 1.-fit_A*pow(nu,fit_a)/(pow(nu,fit_a)+pow(delta_c_Tinker,fit_a))+fit_B*pow(nu,fit_b)+fit_C*pow(nu,fit_c);
break;
default:
*status = CCL_ERROR_MF;
ccl_cosmology_set_status_message(cosmo ,
"ccl_massfunc.c: ccl_halo_b1(): No b(M) fitting function implemented for mass_function_method: %d \n",
cosmo->config.mass_function_method);
return 0;
}
}
void ccl_cosmology_compute_sigma(ccl_cosmology *cosmo, int *status)
{
if(cosmo->computed_sigma)
return;
// create linearly-spaced values of the mass.
int nm = cosmo->spline_params.LOGM_SPLINE_NM;
double *m = NULL;
double *y = NULL;
double smooth_radius;
double na, nb;
m = ccl_linear_spacing(cosmo->spline_params.LOGM_SPLINE_MIN, cosmo->spline_params.LOGM_SPLINE_MAX, nm);
if (m == NULL ||
(fabs(m[0]-cosmo->spline_params.LOGM_SPLINE_MIN)>1e-5) ||
(fabs(m[nm-1]-cosmo->spline_params.LOGM_SPLINE_MAX)>1e-5) ||
(m[nm-1]>10E17)) {
*status = CCL_ERROR_MEMORY;
ccl_cosmology_set_status_message(cosmo,"ccl_cosmology_compute_sigmas(): Error creating linear spacing in m\n");
}
if (*status == 0) {
// create space for y, to be filled with sigma and dlnsigma_dlogm
y = malloc(sizeof(double)*nm);
if (y == NULL) {
*status = CCL_ERROR_MEMORY;
}
}
// start up of GSL pointers
int gslstatus = 0;
gsl_spline *logsigma = NULL;
gsl_spline *dlnsigma_dlogm = NULL;
// fill in sigma, if no errors have been triggered at this time.
if (*status == 0) {
for (int i=0; i<nm; i++) {
smooth_radius = ccl_massfunc_m2r(cosmo, pow(10,m[i]), status);
y[i] = log(ccl_sigmaR(cosmo, smooth_radius, 1., status));
}
logsigma = gsl_spline_alloc(cosmo->spline_params.M_SPLINE_TYPE, nm);
if (logsigma == NULL) {
*status = CCL_ERROR_MEMORY;
}
}
if (*status == 0) {
gslstatus = gsl_spline_init(logsigma, m, y, nm);
if (gslstatus != GSL_SUCCESS) {
*status = CCL_ERROR_SPLINE ;
ccl_cosmology_set_status_message(
cosmo,
"ccl_massfunc.c: ccl_cosmology_compute_sigma(): Error creating sigma(M) spline\n");
}
}
// again, making splines assuming nothing bad has happened to this point
if (*status == 0 ) {
for (int i=0; i<nm; i++) {
if(i==0) {
gslstatus |= gsl_spline_eval_e(logsigma, m[i], NULL,&na);
gslstatus |= gsl_spline_eval_e(logsigma, m[i]+cosmo->spline_params.LOGM_SPLINE_DELTA/2., NULL,&nb);
y[i] = 2.*(na-nb)*y[i] / cosmo->spline_params.LOGM_SPLINE_DELTA;
}
else if (i==nm-1) {
gslstatus |= gsl_spline_eval_e(logsigma, m[i]-cosmo->spline_params.LOGM_SPLINE_DELTA/2., NULL,&na);
gslstatus |= gsl_spline_eval_e(logsigma, m[i], NULL,&nb);
y[i] = 2.*(na-nb)*y[i] / cosmo->spline_params.LOGM_SPLINE_DELTA;
}
else {
gslstatus |= gsl_spline_eval_e(logsigma, m[i]-cosmo->spline_params.LOGM_SPLINE_DELTA/2., NULL,&na);
gslstatus |= gsl_spline_eval_e(logsigma, m[i]+cosmo->spline_params.LOGM_SPLINE_DELTA/2., NULL,&nb);
y[i] = (na-nb) / cosmo->spline_params.LOGM_SPLINE_DELTA;
}
}
if(gslstatus != GSL_SUCCESS ) {
ccl_raise_gsl_warning(
gslstatus, "ccl_massfunc.c: ccl_cosmology_compute_sigma():");
*status = CCL_ERROR_SPLINE;
ccl_cosmology_set_status_message(
cosmo,
"ccl_massfunc.c: ccl_cosmology_compute_sigma(): "
"Error evaluating grid points for dlnsigma/dlogM spline\n");
}
}
if (*status == 0) {
dlnsigma_dlogm = gsl_spline_alloc(cosmo->spline_params.M_SPLINE_TYPE, nm);
if (dlnsigma_dlogm == NULL) {
*status = CCL_ERROR_MEMORY;
}
}
if (*status == 0) {
gslstatus = gsl_spline_init(dlnsigma_dlogm, m, y, nm);
if (gslstatus != GSL_SUCCESS) {
*status = CCL_ERROR_SPLINE ;
ccl_cosmology_set_status_message(
cosmo,
"ccl_massfunc.c: ccl_cosmology_compute_sigma(): Error creating dlnsigma/dlogM spline\n");
}
}
if (*status == 0) {
cosmo->data.logsigma = logsigma;
cosmo->data.dlnsigma_dlogm = dlnsigma_dlogm;
cosmo->computed_sigma = true;
} else {
gsl_spline_free(logsigma);
gsl_spline_free(dlnsigma_dlogm);
}
free(m);
free(y);
}
/*----- ROUTINE: ccl_massfunc -----
INPUT: ccl_cosmology * cosmo, double halo mass in units of Msun, double scale factor
TASK: returns halo mass function as dn/dlog10(m) in comoving Msun^-1 Mpc^-3 (haloes per mass interval per volume)
*/
double ccl_massfunc(ccl_cosmology *cosmo, double halomass, double a, double odelta, int *status)
{
if (cosmo->params.N_nu_mass>0){
*status = CCL_ERROR_NOT_IMPLEMENTED;
ccl_cosmology_set_status_message(cosmo, "ccl_background.c: ccl_cosmology_compute_growth(): Support for the halo mass function in cosmologies with massive neutrinos is not yet implemented.\n");
return NAN;
}
double logmass;
logmass = log10(halomass);
if (logmass > cosmo->spline_params.LOGM_SPLINE_MAX || logmass < cosmo->spline_params.LOGM_SPLINE_MIN){
*status = CCL_ERROR_HMF_INTERP;
ccl_cosmology_set_status_message(cosmo, "ccl_massfunc(): The specified halo mass is outside of the range.");
return NAN;
}
if (fabs(cosmo->params.mu_0)>1e-14 || fabs(cosmo->params.sigma_0)>1e-14){
*status = CCL_ERROR_NOT_IMPLEMENTED;
strcpy(cosmo->status_message,"ccl_massfunc.c: ccl_massfunc(): The halo mass funcion is not implemented the mu / Sigma modified gravity parameterisation.\n");
return NAN;
}
double f, rho_m;
rho_m = ccl_constants.RHO_CRITICAL*cosmo->params.Omega_m*cosmo->params.h*cosmo->params.h;
f=massfunc_f(cosmo,halomass,a,odelta,status);
return f*rho_m*ccl_dlnsigM_dlogM(cosmo,logmass,status)/halomass;
}
/*----- ROUTINE: ccl_halob1 -----
INPUT: ccl_cosmology * cosmo, double halo mass in units of Msun, double scale factor
TASK: returns dimensionless linear halo bias
*/
double ccl_halo_bias(ccl_cosmology *cosmo, double halomass, double a, double odelta, int *status)
{
if (cosmo->params.N_nu_mass>0){
*status = CCL_ERROR_NOT_IMPLEMENTED;
ccl_cosmology_set_status_message(cosmo, "ccl_background.c: ccl_cosmology_compute_growth(): Support for the halo bias in cosmologies with massive neutrinos is not yet implemented.\n");
return NAN;
}
if (fabs(cosmo->params.mu_0)>1e-14 || fabs(cosmo->params.sigma_0)>1e-14){
*status = CCL_ERROR_NOT_IMPLEMENTED;
strcpy(cosmo->status_message,"ccl_massfunc.c: ccl_halobias(): The halo bias is not implemented the mu / Sigma modified gravity parameterisation.\n");
return NAN;
}
double f;
f = ccl_halo_b1(cosmo,halomass,a,odelta, status);
return f;
}
/*---- ROUTINE: ccl_massfunc_m2r -----
INPUT: ccl_cosmology * cosmo, halomass in units of Msun
TASK: takes halo mass and converts to halo radius
in units of Mpc.
*/
double ccl_massfunc_m2r(ccl_cosmology *cosmo, double halomass, int *status)
{
double rho_m, smooth_radius;
// Comoving matter density
//rho_m = ccl_constants.RHO_CRITICAL*cosmo->params.Omega_m*cosmo->params.h*cosmo->params.h;
rho_m = ccl_rho_x(cosmo, 1., ccl_species_m_label, 1, status);
smooth_radius = pow((3.0*halomass) / (4*M_PI*rho_m), (1.0/3.0));
return smooth_radius;
}
/*----- ROUTINE: ccl_sigma_M -----
INPUT: ccl_cosmology * cosmo, double halo mass in units of Msun, double scale factor
TASK: returns sigma from the sigmaM interpolation. Also computes the sigma interpolation if
necessary.
*/
double ccl_sigmaM(ccl_cosmology *cosmo, double log_halomass, double a, int *status)
{
double sigmaM;
// Check if sigma has already been calculated
if (!cosmo->computed_sigma) {
*status = CCL_ERROR_SIGMA_INIT;
ccl_cosmology_set_status_message(
cosmo,
"ccl_massfunc.c: ccl_sigmaM(): linear power spctrum has not been computed!");
return NAN;
}
double lgsigmaM;
int gslstatus = gsl_spline_eval_e(cosmo->data.logsigma, log_halomass, NULL, &lgsigmaM);
if(gslstatus != GSL_SUCCESS) {
ccl_raise_gsl_warning(gslstatus, "ccl_massfunc.c: ccl_sigmaM():");
*status |= gslstatus;
}
// Interpolate to get sigma
sigmaM = exp(lgsigmaM)*ccl_growth_factor(cosmo, a, status);
return sigmaM;
}
/*----- ROUTINE: ccl_dlnsigM_dlogM -----
INPUT: ccl_cosmology *cosmo, double halo mass in units of Msun
TASK: returns the value of the derivative of ln(sigma^-1) with respect to log10 in halo mass.
*/
double ccl_dlnsigM_dlogM(ccl_cosmology *cosmo, double log_halomass, int *status)
{
// Check if sigma has already been calculated
if (!cosmo->computed_sigma) {
*status = CCL_ERROR_SIGMA_INIT;
ccl_cosmology_set_status_message(
cosmo,
"ccl_massfunc.c: ccl_sigmaM(): linear power spctrum has not been computed!");
return NAN;
}
double dlsdlgm;
int gslstatus = gsl_spline_eval_e(cosmo->data.dlnsigma_dlogm,
log_halomass, NULL, &dlsdlgm);
if(gslstatus) {
ccl_raise_gsl_warning(gslstatus, "ccl_massfunc.c: ccl_dlnsigM_dlogM():");
*status |= gslstatus;
}
return dlsdlgm;
}
| {
"alphanum_fraction": 0.6602641496,
"avg_line_length": 34.952685422,
"ext": "c",
"hexsha": "730879d21ab036f0e1de411056ad0f7299d45f78",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2021-02-10T07:35:07.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-02-10T07:35:07.000Z",
"max_forks_repo_head_hexsha": "3a5f9dec72c6ce602ac8b11ceed0ee6c0460a926",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "benediktdiemer/CCL",
"max_forks_repo_path": "src/ccl_massfunc.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "3a5f9dec72c6ce602ac8b11ceed0ee6c0460a926",
"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": "benediktdiemer/CCL",
"max_issues_repo_path": "src/ccl_massfunc.c",
"max_line_length": 195,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "3a5f9dec72c6ce602ac8b11ceed0ee6c0460a926",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "benediktdiemer/CCL",
"max_stars_repo_path": "src/ccl_massfunc.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 8769,
"size": 27333
} |
/* -*- c++ -*- */
/*
* Copyright 2015 Free Software Foundation, Inc.
*
* This is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published
* by the Free Software Foundation; either version 3, or (at your
* option) any later version.
*
* This software 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 software; see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street,
* Boston, MA 02110-1301, USA.
*/
#ifndef INCLUDED_fec_mtrx_impl_H
#define INCLUDED_fec_mtrx_impl_H
#include <string>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_randist.h>
#include <gsl/gsl_permutation.h>
#include <gsl/gsl_linalg.h>
#include <gsl/gsl_blas.h>
#include <gnuradio/fec/fec_mtrx.h>
namespace gr {
namespace fec {
namespace code {
class fec_mtrx_impl : public fec_mtrx
{
protected:
//! Constructor
fec_mtrx_impl();
//! Codeword length n
unsigned int d_n;
//! Information word length k
unsigned int d_k;
//! Number of rows in the matrix read in from alist file
unsigned int d_num_rows;
//! Number of columns in the matrix read in from alist file
unsigned int d_num_cols;
//! GSL matrix structure for the parity check matrix
matrix_sptr d_H_sptr;
//! Flag for whether or not the parity bits come first or last
bool d_par_bits_last;
public:
//! Returns the parity check matrix H (needed by decoder)
const gsl_matrix *H() const;
//!Get the codeword length n
unsigned int n() const;
//! Get the information word length k
unsigned int k() const;
//! Subtract matrices using mod2 operations
void add_matrices_mod2(gsl_matrix *result,
const gsl_matrix *,
const gsl_matrix *) const;
//! Multiply matrices using mod2 operations
void mult_matrices_mod2(gsl_matrix *result,
const gsl_matrix *,
const gsl_matrix *) const;
//! Invert a square matrix using mod2 operations
gsl_matrix *calc_inverse_mod2(const gsl_matrix *) const;
/*!
* \brief Get Boolean for whether or not parity bits come first or last
* \details
* The decoder will need to know if the parity bits are
* coming first or last
*/
bool parity_bits_come_last() const;
virtual ~fec_mtrx_impl();
};
}
}
}
#endif /* INCLUDED_fec_mtrx_impl_H */
| {
"alphanum_fraction": 0.6346219637,
"avg_line_length": 29.5252525253,
"ext": "h",
"hexsha": "8857b743218d28376f7baa3b7b1623a633220399",
"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": "64c149520ac6a7d44179c3f4a38f38add45dd5dc",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "v1259397/cosmic-gnuradio",
"max_forks_repo_path": "gnuradio-3.7.13.4/gr-fec/lib/fec_mtrx_impl.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "64c149520ac6a7d44179c3f4a38f38add45dd5dc",
"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": "v1259397/cosmic-gnuradio",
"max_issues_repo_path": "gnuradio-3.7.13.4/gr-fec/lib/fec_mtrx_impl.h",
"max_line_length": 79,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "64c149520ac6a7d44179c3f4a38f38add45dd5dc",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "v1259397/cosmic-gnuradio",
"max_stars_repo_path": "gnuradio-3.7.13.4/gr-fec/lib/fec_mtrx_impl.h",
"max_stars_repo_stars_event_max_datetime": "2021-03-09T07:32:37.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-03-09T07:32:37.000Z",
"num_tokens": 646,
"size": 2923
} |
// demo3d.c
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <time.h>
#include <string.h>
#include <assert.h>
#include <stdbool.h>
#include <math.h>
#include <gsl/gsl_math.h>
#define SDL_MAIN_HANDLED
#include <SDL2/SDL.h>
#include "libvecdisp.h"
int main(int argc, char * argv[]) {
VECDISP_T ret;
// Init
ret = vecdisp_init();
assert(ret == VECDISP_SUCCESS);
ret = vecdisp_out_init();
assert(ret == VECDISP_SUCCESS);
SDL_GameController * controller_p0 = NULL, * controller_p1 = NULL;
int controller_cnt = 0;
SDL_Init( SDL_INIT_GAMECONTROLLER );
SDL_GameControllerEventState(SDL_ENABLE);
vecdisp_shape_t * shape_cube3d = vecdisp_shape_create(VECDISP_SHAPE_LINES, NULL, 0 );
// format: {x, y, z}, x = horizontal, y = vertical, z = depth
double cube3d[][3] = {
{ -1, -1, -1 },
{ 1, -1, -1 },
{ 1, -1, -1 },
{ 1, 1, -1 },
{ 1, 1, -1 },
{ -1, 1, -1 },
{ -1, 1, -1 },
{ -1, -1, -1 },
{ -1, -1, -1 },
{ -1, -1, 1 },
{ -1, 1, -1 },
{ -1, 1, 1 },
{ 1, 1, -1 },
{ 1, 1, 1 },
{ 1, -1, -1 },
{ 1, -1, 1 },
{ -1, -1, 1 },
{ 1, -1, 1 },
{ 1, -1, 1 },
{ 1, 1, 1 },
{ 1, 1, 1 },
{ -1, 1, 1 },
{ -1, 1, 1 },
{ -1, -1, 1 },
};
for(int i = 0; i < 24; i++) {
uint16_t data[2] = {0,0};
vecdisp_shape_data_add(shape_cube3d, &data, 1 );
}
printf("%i\n", shape_cube3d->data_len);
double rotx = 0, roty = 0, rotz = 0;
double sqrt_3 = sqrt(3);
double sqrt_6 = sqrt(6);
// main loop
SDL_Event event;
bool quit = false;
while( quit == false ) {
while( SDL_PollEvent(&event) != 0 ) {
switch (event.type) {
case SDL_QUIT:
quit = true;
break;
case SDL_CONTROLLERDEVICEADDED:
if(controller_p0 == NULL) {
controller_p0 = SDL_GameControllerOpen(event.cdevice.which);
printf("adding Controller p0\n");
controller_cnt++;
}
else if(controller_p1 == NULL) {
controller_p1 = SDL_GameControllerOpen(event.cdevice.which);
printf("adding Controller p1\n");
controller_cnt++;
}
else {
printf("Only two controllers allowed.\n");
}
break;
case SDL_CONTROLLERDEVICEREMOVED:
if (event.cdevice.which == SDL_JoystickInstanceID(SDL_GameControllerGetJoystick(controller_p0) ) ) {
SDL_GameControllerClose(controller_p0);
printf("freeing controller_p0\n");
controller_p0 = NULL;
controller_cnt--;
}
else if (event.cdevice.which == SDL_JoystickInstanceID(SDL_GameControllerGetJoystick(controller_p1) ) ) {
SDL_GameControllerClose(controller_p1);
printf("freeing controller_p1\n");
controller_p1 = NULL;
controller_cnt--;
}
break;
case SDL_CONTROLLERBUTTONDOWN:
switch (event.cbutton.button) {
case SDL_CONTROLLER_BUTTON_BACK:
if(event.cbutton.state == 1) {
SDL_Event user_quit_event;
user_quit_event.type = SDL_QUIT;
SDL_PushEvent( &user_quit_event );
}
break;
}
break;
case SDL_KEYDOWN:
switch (event.key.keysym.sym) {
case SDLK_q: {
SDL_Event user_quit_event;
user_quit_event.type = SDL_QUIT;
SDL_PushEvent( &user_quit_event );
break;
}
}
break;
}
}
rotx += 0.00004;
roty += 0.00002;
rotz += 0.00001;
if( rotx >= M_PI ) rotx -= M_PI;
if( roty >= M_PI ) roty -= M_PI;
if( rotz >= M_PI ) rotz -= M_PI;
for(int i = 0; i < 24; i++) {
double c[3];
cube3d[i][0] = cos(rotx) * cube3d[i][0] - sin(rotx) * cube3d[i][1]; // Rotation around X Axis
cube3d[i][1] = sin(rotx) * cube3d[i][0] + cos(rotx) * cube3d[i][1];
cube3d[i][2] = 1 * cube3d[i][2];
cube3d[i][0] = cos(roty) * cube3d[i][0] - sin(roty) * cube3d[i][2]; // Rotation around Y Axis
cube3d[i][1] = 1 * cube3d[i][1];
cube3d[i][2] = cos(roty) * cube3d[i][2] + sin(roty) * cube3d[i][0];
cube3d[i][0] = 1 * cube3d[i][0]; // Rotation around Z Axis
cube3d[i][1] = cos(rotz) * cube3d[i][1] - sin(rotz) * cube3d[i][2]; // Rotation around Z Axis
cube3d[i][2] = cos(rotz) * cube3d[i][2] + sin(rotz) * cube3d[i][1];
c[0] = ( sqrt(3) * cube3d[i][0] + (-1) * sqrt_3 * cube3d[i][2] ) / sqrt_6;
c[1] = ( 1 * cube3d[i][0] + 2 * cube3d[i][1] + 1 * cube3d[i][2] ) / sqrt_6;
shape_cube3d->data[i][0] = lround((DRAW_RES / 4) * c[0] + (DRAW_RES / 2));
shape_cube3d->data[i][1] = lround((DRAW_RES / 4) * c[1] + (DRAW_RES / 2));
}
vecdisp_draw_shape( shape_cube3d, 0, 0, DRAW_RES - 1, DRAW_RES - 1, DRAW_BRTNS_BRIGHT);
vecdisp_dbg_showfps();
vecdisp_draw_update();
}
// cleaning up
vecdisp_shape_destroy(shape_cube3d);
SDL_QuitSubSystem( SDL_INIT_EVERYTHING );
vecdisp_out_end();
vecdisp_end();
return 0;
}
| {
"alphanum_fraction": 0.5938713854,
"avg_line_length": 26.1807909605,
"ext": "c",
"hexsha": "90d1e16049361b3dad6454e9cd25da8ac82a5cb8",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2022-01-24T02:44:40.000Z",
"max_forks_repo_forks_event_min_datetime": "2022-01-24T02:44:40.000Z",
"max_forks_repo_head_hexsha": "a3fdd15b228231c69d608af1eb2ea020529c4f5e",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "fpunktz/vecdisp",
"max_forks_repo_path": "src/demo3d.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "a3fdd15b228231c69d608af1eb2ea020529c4f5e",
"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": "fpunktz/vecdisp",
"max_issues_repo_path": "src/demo3d.c",
"max_line_length": 110,
"max_stars_count": 3,
"max_stars_repo_head_hexsha": "91a8d9968b78b9e6513052490800b40681e8b7db",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "felixzwettler/vecdisp",
"max_stars_repo_path": "src/demo3d.c",
"max_stars_repo_stars_event_max_datetime": "2022-01-24T02:44:30.000Z",
"max_stars_repo_stars_event_min_datetime": "2022-01-15T12:44:05.000Z",
"num_tokens": 1707,
"size": 4634
} |
// Author: Adam J. Robinson
// Summary: This file contains definition for the integral that
// characterizes the interaction between nuclei and electrons,
// as defined in the mathematical documentation.
// Performs the Electron Nuclei integral for the given
// Gaussian wavefunction.
#include <gsl/gsl_math.h>
#include <gsl/gsl_monte.h>
#include <gsl/gsl_monte_vegas.h>
#include <gsl/gsl_errno.h>
// Can't just include "gaussian.h", it will create a circular
// reference.
class GaussianWFN;
#ifndef INTEGRAL_EN
#define INTEGRAL_EN
class ENIntegrator {
public:
gsl_monte_vegas_state * state;
double * lowerBounds;
double * upperBounds;
GaussianWFN * wavefn;
int maxCalls;
double width;
double epsilon;
// Initializes an integral calculator.
// fn = The wavefunction that the computation is being carried
// out for.
// width = The number of half width half maxes to
// limit the integral range to. Monte Carlo
// integration does not work for bounds at infinity.
// typically, 3 < width < 6
//
// ncalls = The maximum number of calls to the integrand function
// that the integrator is permitted to make in order to
// calculate the integral. Higher values are slower and
// more accurate.
ENIntegrator(GaussianWFN * fn, double width, int ncalls);
~ENIntegrator();
// These are set temporarily before an integral is performed.
double A1;
double A2;
double A3;
double s1;
double s2;
double s3;
double R1;
double R2;
double R3;
// Used to set the number of calls to the integrand that can be made.
void setMaxCalls(int ncalls);
// Given the three indices that define the integral being calculated,
// sets the lowerBounds and upperBounds members of the class to
// values appropriate for the given width, nuclei location, gaussian
// center and gaussian width.
void setBounds(int iu, int w, int l);
double Integrate(int iu, int w, int l, double * error);
private:
static double integrand(double * x, size_t dim, void * params);
};
#endif | {
"alphanum_fraction": 0.6912247771,
"avg_line_length": 26.6375,
"ext": "h",
"hexsha": "e2783b6ae63e0d42cb9f18834884567fe8aa107c",
"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": "ce8f0e3f44a98ccbbb437c74c940cb7cdfebfff5",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "derangedhk417/MGSC",
"max_forks_repo_path": "src/integral_en.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "ce8f0e3f44a98ccbbb437c74c940cb7cdfebfff5",
"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": "derangedhk417/MGSC",
"max_issues_repo_path": "src/integral_en.h",
"max_line_length": 71,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "ce8f0e3f44a98ccbbb437c74c940cb7cdfebfff5",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "derangedhk417/MGSC",
"max_stars_repo_path": "src/integral_en.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 512,
"size": 2131
} |
#pragma once
#include <memory>
#include <halley/maths/colour.h>
#include <halley/maths/vector2.h>
#include "halley/maths/rect.h"
#include "halley/data_structures/maybe.h"
#include <gsl/span>
#include <map>
#include "halley/core/graphics/sprite/sprite.h"
#include "halley/core/graphics/text/font.h"
namespace Halley
{
class LocalisedString;
class Painter;
class Material;
using ColourOverride = std::pair<size_t, std::optional<Colour4f>>;
class TextRenderer
{
public:
using SpriteFilter = std::function<void(gsl::span<Sprite>)>;
TextRenderer();
explicit TextRenderer(std::shared_ptr<const Font> font, String text = "", float size = 20, Colour colour = Colour(1, 1, 1, 1), float outline = 0, Colour outlineColour = Colour(0, 0, 0, 1));
TextRenderer& setPosition(Vector2f pos);
TextRenderer& setFont(std::shared_ptr<const Font> font);
TextRenderer& setText(const String& text);
TextRenderer& setText(const StringUTF32& text);
TextRenderer& setText(const LocalisedString& text);
TextRenderer& setSize(float size);
TextRenderer& setColour(Colour colour);
TextRenderer& setOutlineColour(Colour colour);
TextRenderer& setOutline(float width);
TextRenderer& setAlignment(float align);
TextRenderer& setOffset(Vector2f align);
TextRenderer& setClip(Rect4f clip);
TextRenderer& setClip();
TextRenderer& setSmoothness(float smoothness);
TextRenderer& setPixelOffset(Vector2f offset);
TextRenderer& setColourOverride(const std::vector<ColourOverride>& colOverride);
TextRenderer& setLineSpacing(float spacing);
TextRenderer clone() const;
void generateSprites(std::vector<Sprite>& sprites) const;
void draw(Painter& painter, const std::optional<Rect4f>& extClip = {}) const;
void setSpriteFilter(SpriteFilter f);
Vector2f getExtents() const;
Vector2f getExtents(const StringUTF32& str) const;
Vector2f getCharacterPosition(size_t character) const;
Vector2f getCharacterPosition(size_t character, const StringUTF32& str) const;
size_t getCharacterAt(const Vector2f& position) const;
size_t getCharacterAt(const Vector2f& position, const StringUTF32& str) const;
StringUTF32 split(const String& str, float width) const;
StringUTF32 split(const StringUTF32& str, float width, std::function<bool(int32_t)> filter = {}) const;
StringUTF32 split(float width) const;
Vector2f getPosition() const;
String getText() const;
const StringUTF32& getTextUTF32() const;
Colour getColour() const;
float getOutline() const;
Colour getOutlineColour() const;
float getSmoothness() const;
std::optional<Rect4f> getClip() const;
float getLineHeight() const;
float getAlignment() const;
bool empty() const;
private:
std::shared_ptr<const Font> font;
mutable std::map<const Font*, std::shared_ptr<Material>> materials;
StringUTF32 text;
SpriteFilter spriteFilter;
float size = 20;
float outline = 0;
float align = 0;
float smoothness = 1.0f;
float lineSpacing = 0.0f;
Vector2f position;
Vector2f offset;
Vector2f pixelOffset;
Colour colour;
Colour outlineColour;
std::optional<Rect4f> clip;
std::vector<ColourOverride> colourOverrides;
mutable Vector<Sprite> spritesCache;
mutable bool materialDirty = true;
mutable bool glyphsDirty = true;
mutable bool positionDirty = true;
std::shared_ptr<Material> getMaterial(const Font& font) const;
void updateMaterial(Material& material, const Font& font) const;
void updateMaterialForFont(const Font& font) const;
void updateMaterials() const;
float getScale(const Font& font) const;
};
class ColourStringBuilder {
public:
void append(std::string_view text, std::optional<Colour4f> col = {});
std::pair<String, std::vector<ColourOverride>> moveResults();
private:
std::vector<String> strings;
std::vector<ColourOverride> colours;
size_t len = 0;
};
}
| {
"alphanum_fraction": 0.7486338798,
"avg_line_length": 31.243902439,
"ext": "h",
"hexsha": "65b1409b0f1c54934b3957d3eead01371a2dce5d",
"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": "cbc3713017de2e6e4b6d0e4e787b19695c1e6cec",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "akien-mga/halley",
"max_forks_repo_path": "src/engine/core/include/halley/core/graphics/text/text_renderer.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "cbc3713017de2e6e4b6d0e4e787b19695c1e6cec",
"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": "akien-mga/halley",
"max_issues_repo_path": "src/engine/core/include/halley/core/graphics/text/text_renderer.h",
"max_line_length": 191,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "cbc3713017de2e6e4b6d0e4e787b19695c1e6cec",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "akien-mga/halley",
"max_stars_repo_path": "src/engine/core/include/halley/core/graphics/text/text_renderer.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1002,
"size": 3843
} |
/* integration/qawf.c
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000 Brian Gough
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <config.h>
#include <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 "qelg.c"
int
gsl_integration_qawf (gsl_function * f,
const double a,
const double epsabs,
const size_t limit,
gsl_integration_workspace * workspace,
gsl_integration_workspace * cycle_workspace,
gsl_integration_qawo_table * wf,
double *result, double *abserr)
{
double area, errsum;
double res_ext, err_ext;
double correc, total_error = 0.0, truncation_error;
size_t ktmin = 0;
size_t iteration = 0;
struct extrapolation_table table;
double cycle;
double omega = wf->omega;
const double p = 0.9;
double factor = 1;
double initial_eps, eps;
int error_type = 0;
/* Initialize results */
initialise (workspace, a, a);
*result = 0;
*abserr = 0;
if (limit > workspace->limit)
{
GSL_ERROR ("iteration limit exceeds available workspace", GSL_EINVAL) ;
}
/* Test on accuracy */
if (epsabs <= 0)
{
GSL_ERROR ("absolute tolerance epsabs must be positive", GSL_EBADTOL) ;
}
if (omega == 0.0)
{
if (wf->sine == GSL_INTEG_SINE)
{
/* The function sin(w x) f(x) is always zero for w = 0 */
*result = 0;
*abserr = 0;
return GSL_SUCCESS;
}
else
{
/* The function cos(w x) f(x) is always f(x) for w = 0 */
int status = gsl_integration_qagiu (f, a, epsabs, 0.0,
cycle_workspace->limit,
cycle_workspace,
result, abserr);
return status;
}
}
if (epsabs > GSL_DBL_MIN / (1 - p))
{
eps = epsabs * (1 - p);
}
else
{
eps = epsabs;
}
initial_eps = eps;
area = 0;
errsum = 0;
res_ext = 0;
err_ext = GSL_DBL_MAX;
correc = 0;
cycle = (2 * floor (fabs (omega)) + 1) * M_PI / fabs (omega);
gsl_integration_qawo_table_set_length (wf, cycle);
initialise_table (&table);
for (iteration = 0; iteration < limit; iteration++)
{
double area1, error1, reseps, erreps;
double a1 = a + iteration * cycle;
double b1 = a1 + cycle;
double epsabs1 = eps * factor;
int status = gsl_integration_qawo (f, a1, epsabs1, 0.0, limit,
cycle_workspace, wf,
&area1, &error1);
append_interval (workspace, a1, b1, area1, error1);
factor *= p;
area = area + area1;
errsum = errsum + error1;
/* estimate the truncation error as 50 times the final term */
truncation_error = 50 * fabs (area1);
total_error = errsum + truncation_error;
if (total_error < epsabs && iteration > 4)
{
goto compute_result;
}
if (error1 > correc)
{
correc = error1;
}
if (status)
{
eps = GSL_MAX_DBL (initial_eps, correc * (1.0 - p));
}
if (status && total_error < 10 * correc && iteration > 3)
{
goto compute_result;
}
append_table (&table, area);
if (table.n < 2)
{
continue;
}
qelg (&table, &reseps, &erreps);
ktmin++;
if (ktmin >= 15 && err_ext < 0.001 * total_error)
{
error_type = 4;
}
if (erreps < err_ext)
{
ktmin = 0;
err_ext = erreps;
res_ext = reseps;
if (err_ext + 10 * correc <= epsabs)
break;
if (err_ext <= epsabs && 10 * correc >= epsabs)
break;
}
}
if (iteration == limit)
error_type = 1;
if (err_ext == GSL_DBL_MAX)
goto compute_result;
err_ext = err_ext + 10 * correc;
*result = res_ext;
*abserr = err_ext;
if (error_type == 0)
{
return GSL_SUCCESS ;
}
if (res_ext != 0.0 && area != 0.0)
{
if (err_ext / fabs (res_ext) > errsum / fabs (area))
goto compute_result;
}
else if (err_ext > errsum)
{
goto compute_result;
}
else if (area == 0.0)
{
goto return_error;
}
if (error_type == 4)
{
err_ext = err_ext + truncation_error;
}
goto return_error;
compute_result:
*result = area;
*abserr = total_error;
return_error:
if (error_type > 2)
error_type--;
if (error_type == 0)
{
return GSL_SUCCESS;
}
else if (error_type == 1)
{
GSL_ERROR ("number of iterations was insufficient", GSL_EMAXITER);
}
else if (error_type == 2)
{
GSL_ERROR ("cannot reach tolerance because of roundoff error",
GSL_EROUND);
}
else if (error_type == 3)
{
GSL_ERROR ("bad integrand behavior found in the integration interval",
GSL_ESING);
}
else if (error_type == 4)
{
GSL_ERROR ("roundoff error detected in the extrapolation table",
GSL_EROUND);
}
else if (error_type == 5)
{
GSL_ERROR ("integral is divergent, or slowly convergent",
GSL_EDIVERGE);
}
else
{
GSL_ERROR ("could not integrate function", GSL_EFAILED);
}
}
| {
"alphanum_fraction": 0.609738885,
"avg_line_length": 20.0992907801,
"ext": "c",
"hexsha": "134fd8c5f0a9807e8ccf16168566bd5f5645c486",
"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/integration/qawf.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/integration/qawf.c",
"max_line_length": 77,
"max_stars_count": 14,
"max_stars_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "ICML14MoMCompare/spectral-learn",
"max_stars_repo_path": "code/em/treba/gsl-1.0/integration/qawf.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": 1651,
"size": 5668
} |
/*
* Define digamma() and polygamma() here.
*
* We use the GSL special functions, GSL is available
* on most platforms including MAC and Windows.
*
* Another option is the Cephes library with psi() and zeta()
* http://www.netlib.org/cephes/
* which have nice, small self contained functions without all the
* GSL cruft.
*/
#ifndef __DIGAMMA_H
#define __DIGAMMA_H
/*
* Define this to switch off use of polygamma.
* Polygamma (trigamma, etc.) is used in some
* functions to speed things up. So disabling
* it wont stop the functions working:
* gammadiff(), psidiff(), S_approx()
* But it also disables digammaInv() which
* uses a Newton-Raphson step.
*/
#define LS_NOPOLYGAMMA
/*
* Leaving this undefined means we use the library functions grabbed
* from the Mathlib and under GPL. This makes the code self
* contained since no other libraries will be needed.
* Define this if you have GSL available to use instead.
* In which case, you will also need to modify the Makefile
* to include GSL.
*/
// #define GSL_POLYGAMMA
#ifdef LS_NOPOLYGAMMA
/*
* Radford Neal's implementation in digamma.c
*/
double digammaRN(double x);
#define digamma(x) digammaRN(x)
#else
double digammaInv(double x);
#ifndef GSL_POLYGAMMA
/*
* Mathlib implementation
*/
double MLpsigamma(double x, double deriv);
double MLdigamma(double x);
double MLtrigamma(double x);
double MLtetragamma(double x);
double MLpentagamma(double x);
#define digamma(x) MLdigamma(x)
#define trigamma(x) MLtrigamma(x)
#define tetragamma(x) MLtetragamma(x)
#define pentagamma(x) MLpentagamma(x)
#else
/*
* GSL library
*/
#include <gsl/gsl_sf.h>
#define digamma(x) gsl_sf_psi(x)
#define trigamma(x) gsl_sf_psi_n(1,x)
#define tetragamma(x) gsl_sf_psi_n(2,x)
#define pentagamma(x) gsl_sf_psi_n(3,x)
#endif
#endif
#endif
| {
"alphanum_fraction": 0.716828479,
"avg_line_length": 24.3947368421,
"ext": "h",
"hexsha": "5ec13a236208e74b3afcfb25b8235c8f41a69012",
"lang": "C",
"max_forks_count": 5,
"max_forks_repo_forks_event_max_datetime": "2020-11-30T10:27:55.000Z",
"max_forks_repo_forks_event_min_datetime": "2016-08-15T07:57:43.000Z",
"max_forks_repo_head_hexsha": "7338435bce01fec751d360c6f1b54e585acad482",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "awbennett/HCA-WSI",
"max_forks_repo_path": "topicmodelling/HCA-0.61/lib/digamma.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "7338435bce01fec751d360c6f1b54e585acad482",
"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": "awbennett/HCA-WSI",
"max_issues_repo_path": "topicmodelling/HCA-0.61/lib/digamma.h",
"max_line_length": 69,
"max_stars_count": 6,
"max_stars_repo_head_hexsha": "7338435bce01fec751d360c6f1b54e585acad482",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "awbennett/HCA-WSI",
"max_stars_repo_path": "topicmodelling/HCA-0.61/lib/digamma.h",
"max_stars_repo_stars_event_max_datetime": "2021-01-16T06:27:38.000Z",
"max_stars_repo_stars_event_min_datetime": "2016-08-15T07:57:42.000Z",
"num_tokens": 512,
"size": 1854
} |
/*
* resampling.c
*
* Created on: 5.5.2017
* Author: heine
*/
#define _XOPEN_SOURCE 600
#include <math.h>
#include <stdint.h>
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include <mpi.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
//#include "ziggurat.h"
const gsl_rng_type *T; // Generator type
const gsl_rng *rgen; // Generator
void set_resamplingseed( int id ) {
struct timespec spec;
clock_gettime( CLOCK_REALTIME, &spec );
gsl_rng_env_setup();
T = gsl_rng_default;
rgen = gsl_rng_alloc( T );
gsl_rng_set( rgen, ( unsigned long int ) ( round( spec.tv_nsec / 1.0e6 ) + 223 * id ) );
}
double depth_first_sum(double *x, long len) {
long n = len;
double *x_tmp, out;
x_tmp = malloc(sizeof(double) * len);
for (long i = 0; i < len; i++)
x_tmp[i] = x[i];
while (n > 1) {
for (long i = 0; i < n / 2; i++) {
x_tmp[i] = x_tmp[2 * i] + x_tmp[2 * i + 1];
}
if (n % 2 != 0) {
x_tmp[n / 2] = x_tmp[n - 1];
}
n = n / 2 + n % 2;
}
out = x_tmp[0];
free(x_tmp);
return out;
}
double *depth_first_cumsum(double *x, long len) {
double *W;
W = malloc(sizeof(double) * len);
for (long i = 0; i < len; i++) {
W[i] = depth_first_sum(x, i);
}
return W;
}
double *exclusive_prefix_sum(double *w, long len) {
double *W;
W = malloc(sizeof(double) * len);
W[0] = 0;
for (long i = 1; i < len; i++) {
W[i] = W[i - 1] + w[i - 1];
}
return W;
}
double *combining_exclusive_prefix_sum(double *w, double *w_recv, long n) {
double *W;
W = malloc(sizeof(double) * 2 * n);
W[0] = 0;
for (long i = 1; i <= n; i++) {
W[i] = W[i - 1] + w[i - 1];
}
for (long i = 0; i < n-1; i++) {
W[n + i + 1] = W[n + i] + w_recv[i];
}
return W;
}
double serial_multinomial_resample(long n, double *w, double *w_recv, long *inds) {
double *W;
double total_weight, lnmax = 0, u;
long j = 2 * n - 1;
W = combining_exclusive_prefix_sum(w, w_recv, n);
total_weight = log(W[2 * n - 1] + w_recv[n - 1]);
for (long i = n; i >= 1; i--) {
u = gsl_rng_uniform_pos( rgen );
lnmax = lnmax + log(u) / (double) i;
u = exp(total_weight + lnmax);
while (u < W[j])
j--;
inds[i - 1] = j;
}
free(W);
return exp(total_weight);
}
double serial_multinomial_resample_sng(long n, double *w, long *inds) {
double *W;
double total_weight, lnmax = 0, u;
long j = n - 1;
W = exclusive_prefix_sum(w, n);
total_weight = log(W[n - 1] + w[n - 1]);
for (long i = n; i >= 1; i--) {
u = gsl_rng_uniform_pos( rgen );
lnmax = lnmax + log(u) / (double) i;
u = exp(total_weight + lnmax);
while (u < W[j])
j--;
inds[i - 1] = j;
}
free(W);
return exp(total_weight);
}
double serial_multinomial_resample_sng_noutk(long n, double *w, long *inds, long k) {
double *W;
double total_weight, lnmax = 0, u;
long j = k - 1;
W = exclusive_prefix_sum(w, k);
total_weight = log( W[ k - 1 ] + w[ k - 1 ] );
for (long i = n; i >= 1; i--) {
u = gsl_rng_uniform_pos( rgen );
lnmax = lnmax + log(u) / (double) i;
u = exp(total_weight + lnmax);
while (u < W[j])
j--;
inds[i - 1] = j;
}
free(W);
return exp(total_weight);
}
double serial_multinomial_resample_noutk(long n, double *w, double* W, long *inds, long k) {
double total_weight, lnmax = 0, u;
long j = k - 1;
total_weight = log(W[k - 1] + w[k - 1]);
for (long i = n; i >= 1; i--) {
u = gsl_rng_uniform_pos( rgen );
lnmax = lnmax + log(u) / (double) i;
u = exp(total_weight + lnmax);
while (u < W[j])
j--;
inds[i - 1] = j;
}
return -1;
}
void binary_resampler(long n, double w, long *counts) {
counts[0] = 0;
counts[1] = 0;
for ( long i = 0; i < n; i++ )
counts[ gsl_rng_uniform_pos( rgen ) < w ? 0 : 1 ]++;
}
void
simplified_resample(
long n,
long *inds,
long k)
{
for ( long i = 0; i < n; i++ )
inds[ i ] = ( long ) ( gsl_rng_uniform_int( rgen, ( unsigned long int ) k ) );
}
void serial_multinomial_resample_counts(long n, long k, double *w, long *cnts) {
double *W;
double total_weight, lnmax = 0, u;
long j = k - 1;
for( long i = 0; i < k ; i++ )
cnts[ i ] = 0;
W = exclusive_prefix_sum(w, k);
total_weight = log(W[k - 1] + w[k - 1]);
for (long i = n; i >= 1; i--) {
u = gsl_rng_uniform_pos( rgen );
lnmax = lnmax + log(u) / (double) i;
u = exp(total_weight + lnmax);
while (u < W[j])
j--;
cnts[j]++;
}
free(W);
}
| {
"alphanum_fraction": 0.5364067212,
"avg_line_length": 17.7175572519,
"ext": "c",
"hexsha": "d0936bb9e49cf82656e8027f43482c9075a16b20",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "2b7d74519289d2dac684b483a85ec2696e694c27",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "heinekmp/AIRPF",
"max_forks_repo_path": "src/resampling.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "2b7d74519289d2dac684b483a85ec2696e694c27",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "heinekmp/AIRPF",
"max_issues_repo_path": "src/resampling.c",
"max_line_length": 92,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "2b7d74519289d2dac684b483a85ec2696e694c27",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "heinekmp/AIRPF",
"max_stars_repo_path": "src/resampling.c",
"max_stars_repo_stars_event_max_datetime": "2020-05-21T06:38:23.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-05-21T06:38:23.000Z",
"num_tokens": 1672,
"size": 4642
} |
/*
* vbHmmGaussDiffusion.c
* Model-specific core functions for VB-HMM-GAUSS-DIFFUSION.
*
* Created by OKAMOTO Kenji, SAKO Yasushi and RIKEN
* Copyright 2011-2016
* Cellular Informatics Laboratory, Advance Science Institute, RIKEN, Japan.
* All rights reserved.
*
* Ver. 1.0.0
* Last modified on 2016.02.08
*/
#include "vbHmmGaussDiffusion.h"
#include <gsl/gsl_sf_gamma.h>
#include <gsl/gsl_sf_psi.h>
#include <string.h>
#include "rand.h"
#ifdef _OPENMP
#include "omp.h"
#endif
#define MAX(a,b) ((a)>(b)?(a):(b))
#define MIN(a,b) ((a)<(b)?(a):(b))
static int isGlobalAnalysis = 0;
void setFunctions_gaussDiff(){
commonFunctions funcs;
funcs.newModelParameters = newModelParameters_gaussDiff;
funcs.freeModelParameters = freeModelParameters_gaussDiff;
funcs.newModelStats = newModelStats_gaussDiff;
funcs.freeModelStats = freeModelStats_gaussDiff;
funcs.initializeVbHmm = initializeVbHmm_gaussDiff;
funcs.pTilde_z1 = pTilde_z1_gaussDiff;
funcs.pTilde_zn_zn1 = pTilde_zn_zn1_gaussDiff;
funcs.pTilde_xn_zn = pTilde_xn_zn_gaussDiff;
funcs.calcStatsVars = calcStatsVars_gaussDiff;
funcs.maximization = maximization_gaussDiff;
funcs.varLowerBound = varLowerBound_gaussDiff;
funcs.reorderParameters = reorderParameters_gaussDiff;
funcs.outputResults = outputResults_gaussDiff;
setFunctions( funcs );
}
void setGFunctions_gaussDiff(){
gCommonFunctions funcs;
funcs.newModelParameters = newModelParameters_gaussDiff;
funcs.freeModelParameters = freeModelParameters_gaussDiff;
funcs.newModelStats = newModelStats_gaussDiff;
funcs.freeModelStats = freeModelStats_gaussDiff;
funcs.newModelStatsG = newModelStatsG_gaussDiff;
funcs.freeModelStatsG = freeModelStatsG_gaussDiff;
funcs.initializeVbHmmG = initializeVbHmmG_gaussDiff;
funcs.pTilde_z1 = pTilde_z1_gaussDiff;
funcs.pTilde_zn_zn1 = pTilde_zn_zn1_gaussDiff;
funcs.pTilde_xn_zn = pTilde_xn_zn_gaussDiff;
funcs.calcStatsVarsG = calcStatsVarsG_gaussDiff;
funcs.maximizationG = maximizationG_gaussDiff;
funcs.varLowerBoundG = varLowerBoundG_gaussDiff;
funcs.reorderParametersG = reorderParametersG_gaussDiff;
funcs.outputResultsG = outputResultsG_gaussDiff;
setGFunctions( funcs );
isGlobalAnalysis = 1;
}
void outputResults_gaussDiff( xn, gv, iv, logFP )
xnDataSet *xn;
globalVars *gv;
indVars *iv;
FILE *logFP;
{
outputGaussDiffResults( xn, gv, iv, logFP );
}
void outputResultsG_gaussDiff( xns, gv, ivs, logFP )
xnDataBundle *xns;
globalVars *gv;
indVarBundle *ivs;
FILE *logFP;
{
outputGaussDiffResultsG( xns, gv, ivs, logFP );
}
void *newModelParameters_gaussDiff( xn, sNo )
xnDataSet *xn;
int sNo;
{
int i;
gaussDiffParameters *p = (gaussDiffParameters*)malloc( sizeof(gaussDiffParameters) );
p->uPiArr = (double*)malloc( sNo * sizeof(double) );
p->sumUPi = 0.0;
p->uAMat = (double**)malloc( sNo * sizeof(double*) );
for( i = 0 ; i < sNo ; i++ ){
p->uAMat[i] = (double*)malloc( sNo * sizeof(double) );
}
p->sumUAArr = (double*)malloc( sNo * sizeof(double) );
p->avgPi = (double *)malloc( sNo * sizeof(double) );
p->avgLnPi = (double *)malloc( sNo * sizeof(double) );
p->avgA = (double **)malloc( sNo * sizeof(double*) );
p->avgLnA = (double **)malloc( sNo * sizeof(double*) );
for( i = 0 ; i < sNo ; i++ ){
p->avgA[i] = (double *)malloc( sNo * sizeof(double) );
p->avgLnA[i] = (double *)malloc( sNo * sizeof(double) );
}
p->avgDlt = (double *)malloc( sNo * sizeof(double) );
p->avgLnDlt = (double *)malloc( sNo * sizeof(double) );
p->uAArr = (double *)malloc( sNo * sizeof(double) );
p->uBArr = (double *)malloc( sNo * sizeof(double) );
p->aDlt = (double *)malloc( sNo * sizeof(double) );
p->bDlt = (double *)malloc( sNo * sizeof(double) );
return p;
}
void freeModelParameters_gaussDiff( p, xn, sNo )
void **p;
xnDataSet *xn;
int sNo;
{
gaussDiffParameters *gp = *p;
int i;
free( gp->uPiArr );
for( i = 0 ; i < sNo ; i++ ){
free( gp->uAMat[i] );
}
free( gp->uAMat );
free( gp->sumUAArr );
free( gp->avgPi );
free( gp->avgLnPi );
for( i = 0 ; i < sNo ; i++ ){
free( gp->avgA[i] );
free( gp->avgLnA[i] );
}
free( gp->avgA );
free( gp->avgLnA );
free( gp->avgDlt );
free( gp->avgLnDlt );
free( gp->uAArr );
free( gp->uBArr );
free( gp->aDlt );
free( gp->bDlt );
free( *p );
*p = NULL;
}
void *newModelStats_gaussDiff( xn, gv, iv )
xnDataSet *xn;
globalVars *gv;
indVars *iv;
{
if( isGlobalAnalysis == 0 ){
int sNo = gv->sNo;
gaussDiffStats *s = (gaussDiffStats*)malloc( sizeof(gaussDiffStats) );
int i;
s->Ni = (double *)malloc( sNo * sizeof(double) );
s->Ri = (double *)malloc( sNo * sizeof(double) );
s->Nij = (double **)malloc( sNo * sizeof(double*) );
for( i = 0 ; i < sNo ; i++ )
{ s->Nij[i] = (double *)malloc( sNo * sizeof(double) ); }
s->Nii = (double *)malloc( sNo * sizeof(double) );
return s;
} else {
return NULL;
}
}
void freeModelStats_gaussDiff( s, xn, gv, iv )
void **s;
xnDataSet *xn;
globalVars *gv;
indVars *iv;
{
if( isGlobalAnalysis == 0 ){
int sNo = gv->sNo;
gaussDiffStats *gs = *s;
int i;
free( gs->Ni );
free( gs->Ri );
for( i = 0 ; i < sNo ; i++ )
{ free( gs->Nij[i] ); }
free( gs->Nij );
free( gs->Nii );
free( gs );
*s = NULL;
}
}
void *newModelStatsG_gaussDiff( xns, gv, ivs)
xnDataBundle *xns;
globalVars *gv;
indVarBundle *ivs;
{
int sNo = gv->sNo;
gaussDiffGlobalStats *gs = (gaussDiffGlobalStats*)malloc( sizeof(gaussDiffGlobalStats) );
int i;
gs->NiR = (double *)malloc( sNo * sizeof(double) );
gs->RiR = (double *)malloc( sNo * sizeof(double) );
gs->NijR = (double **)malloc( sNo * sizeof(double*) );
for( i = 0 ; i < sNo ; i++ )
{ gs->NijR[i] = (double *)malloc( sNo * sizeof(double) ); }
gs->NiiR = (double *)malloc( sNo * sizeof(double) );
gs->z1iR = (double *)malloc( sNo * sizeof(double) );
return gs;
}
void freeModelStatsG_gaussDiff( gs, xns, gv, ivs )
void **gs;
xnDataBundle *xns;
globalVars *gv;
indVarBundle *ivs;
{
int sNo = gv->sNo;
gaussDiffGlobalStats *ggs = *gs;
int i;
free( ggs->NiR );
for( i = 0 ; i < sNo ; i++ )
{ free( ggs->NijR[i] ); }
free( ggs->NijR );
free( ggs->NiiR );
free( ggs->RiR );
free( ggs->z1iR );
free( *gs );
*gs = NULL;
}
void initializeVbHmm_gaussDiff( xn, gv, iv )
xnDataSet *xn;
globalVars *gv;
indVars *iv;
{
int sNo = gv->sNo;
gaussDiffParameters *p = gv->params;
int i, j;
// hyper parameter for p( pi(i) )
p->sumUPi = 0.0;
for( i = 0 ; i < sNo ; i++ ){
p->uPiArr[i] = 1.0;
p->sumUPi += p->uPiArr[i];
}
// hyper parameter for p( A(i,j) )
for( i = 0 ; i < sNo ; i++ ){
p->sumUAArr[i] = 0.0;
for( j = 0 ; j < sNo ; j++ ){
if( j == i ){
p->uAMat[i][j] = 5.0;
} else {
p->uAMat[i][j] = 1.0;
}
p->sumUAArr[i] += p->uAMat[i][j];
}
}
// hyper parameter for p( delta(k) )
for( i = 0 ; i < sNo ; i++ ){
p->uAArr[i] = 1.0;
p->uBArr[i] = 0.0005;
}
initialize_indVars_gaussDiff( xn, gv, iv );
calcStatsVars_gaussDiff( xn, gv, iv );
maximization_gaussDiff( xn, gv, iv );
}
void initializeVbHmmG_gaussDiff( xns, gv, ivs )
xnDataBundle *xns;
globalVars *gv;
indVarBundle *ivs;
{
int sNo = gv->sNo, rNo = xns->R;
gaussDiffParameters *p = gv->params;
int i, j, r;
p->sumUPi = 0.0;
for( i = 0 ; i < sNo ; i++ ){
p->uPiArr[i] = 1.0;
p->sumUPi += p->uPiArr[i];
}
for( i = 0 ; i < sNo ; i++ ){
p->sumUAArr[i] = 0.0;
for( j = 0 ; j < sNo ; j++ ){
if( j == i ){
p->uAMat[i][j] = 5.0;
} else {
p->uAMat[i][j] = 1.0;
}
p->sumUAArr[i] += p->uAMat[i][j];
}
}
// hyper parameter for p( delta(k) )
for( i = 0 ; i < sNo ; i++ ){
p->uAArr[i] = 1.0;
p->uBArr[i] = 0.0005;
}
for( r = 0 ; r < rNo ; r++ ){
initialize_indVars_gaussDiff( xns->xn[r], gv, ivs->indVars[r] );
}
calcStatsVarsG_gaussDiff( xns, gv, ivs );
maximizationG_gaussDiff( xns, gv, ivs );
}
void initialize_indVars_gaussDiff( xn, gv, iv )
xnDataSet *xn;
globalVars *gv;
indVars *iv;
{
size_t dLen = xn->N;
int sNo = gv->sNo;
double **gmMat = iv->gmMat;
int i;
size_t n;
double sumPar;
for( n = 0 ; n < dLen ; n++ ){
sumPar = 0.0;
for( i = 0 ; i < sNo ; i++ ){
gmMat[n][i] = enoise(1.0) + 1.0;
sumPar += gmMat[n][i];
}
for( i = 0 ; i < sNo ; i++ ){
gmMat[n][i] /= sumPar;
}
}
}
xnDataSet *newXnDataSet_gaussDiff( filename )
const char *filename;
{
xnDataSet *xn = (xnDataSet*)malloc( sizeof(xnDataSet) );
xn->name = (char*)malloc( strlen(filename) + 2 );
strncpy( xn->name, filename, strlen(filename)+1 );
xn->data = (gaussDiffData*)malloc( sizeof(gaussDiffData) );
gaussDiffData *d = (gaussDiffData*)xn->data;
d->v = NULL;
return xn;
}
void freeXnDataSet_gaussDiff( xn )
xnDataSet **xn;
{
gaussDiffData *d = (gaussDiffData*)(*xn)->data;
free( d->v );
free( (*xn)->data );
free( (*xn)->name );
free( *xn );
*xn = NULL;
}
double pTilde_z1_gaussDiff( i, params )
int i;
void *params;
{
gaussDiffParameters *p = (gaussDiffParameters*)params;
return exp( p->avgLnPi[i] );
}
double pTilde_zn_zn1_gaussDiff( i, j, params )
int i, j;
void *params;
{
gaussDiffParameters *p = (gaussDiffParameters*)params;
return exp( p->avgLnA[i][j] );
}
double pTilde_xn_zn_gaussDiff( xnWv, n, i, params )
xnDataSet *xnWv;
size_t n;
int i;
void *params;
{
gaussDiffParameters *p = (gaussDiffParameters*)params;
gaussDiffData *xn = (gaussDiffData*)xnWv->data;
double val;
val = p->avgLnDlt[i] - log(2.0);
val -= log(xn->v[n]) + p->avgDlt[i] * pow( xn->v[n], 2.0) / 4.0;
return exp(val);
}
void calcStatsVars_gaussDiff( xn, gv, iv )
xnDataSet *xn;
globalVars *gv;
indVars *iv;
{
gaussDiffData *d = (gaussDiffData*)xn->data;
gaussDiffStats *s = (gaussDiffStats*)iv->stats;
size_t dLen = xn->N;
int sNo = gv->sNo;
double **gmMat = iv->gmMat, ***xiMat = iv->xiMat;
double *Ni = s->Ni, *Ri = s->Ri, *Nii = s->Nii, **Nij = s->Nij;
size_t n;
int i, j;
for( i = 0 ; i < sNo ; i++ ){
Ni[i] = 1e-10;
Ri[i] = 1e-10;
Nii[i] = 1e-10;
for( j = 0 ; j < sNo ; j++ ){
Nij[i][j] = 1e-10;
}
for( n = 0 ; n < dLen ; n++ ){
Ni[i] += gmMat[n][i];
Ri[i] += gmMat[n][i] * pow( d->v[n], 2.0 );
for( j = 0 ; j < sNo ; j++ ){
Nii[i] += xiMat[n][i][j];
Nij[i][j] += xiMat[n][i][j];
}
}
}
}
void calcStatsVarsG_gaussDiff( xns, gv, ivs )
xnDataBundle *xns;
globalVars *gv;
indVarBundle *ivs;
{
gaussDiffData *d;
gaussDiffGlobalStats *gs = (gaussDiffGlobalStats*)ivs->stats;
int sNo = gv->sNo, rNo = xns->R;
double **gmMat, ***xiMat;
double *NiR = gs->NiR, *RiR = gs->RiR, *NiiR = gs->NiiR;
double **NijR = gs->NijR, *z1iR = gs->z1iR;
size_t dLen, n;
int i, j, r;
for( i = 0 ; i < sNo ; i++ ){
NiR[i] = 1e-10;
RiR[i] = 1e-10;
NiiR[i] = 1e-10;
for( j = 0 ; j < sNo ; j++ ){
NijR[i][j] = 1e-10;
}
z1iR[i] = 1e-10;
}
for( r = 0 ; r < rNo ; r++ ){
d = (gaussDiffData*)xns->xn[r]->data;
dLen = xns->xn[r]->N;
gmMat = ivs->indVars[r]->gmMat;
xiMat = ivs->indVars[r]->xiMat;
for( i = 0 ; i < sNo ; i++ ){
z1iR[i] += gmMat[0][i];
for( n = 0 ; n < dLen ; n++ ){
NiR[i] += gmMat[n][i];
RiR[i] += gmMat[n][i] * pow( d->v[n], 2.0 );
for( j = 0 ; j < sNo ; j++ ){
NiiR[i] += xiMat[n][i][j];
NijR[i][j] += xiMat[n][i][j];
}
}
}
}
}
void maximization_gaussDiff( xn, gv, iv )
xnDataSet *xn;
globalVars *gv;
indVars *iv;
{
gaussDiffParameters *p = (gaussDiffParameters*)gv->params;
gaussDiffStats *s = (gaussDiffStats*)iv->stats;
int sNo = gv->sNo;
double **gmMat = iv->gmMat;
double *uPiArr = p->uPiArr, sumUPi = p->sumUPi;
double **uAMat = p->uAMat, *sumUAArr = p->sumUAArr;
double *uAArr = p->uAArr, *uBArr = p->uBArr, *aDlt = p->aDlt, *bDlt = p->bDlt;
double *avgPi = p->avgPi, *avgLnPi = p->avgLnPi, **avgA = p->avgA, **avgLnA = p->avgLnA;
double *avgDlt = p->avgDlt, *avgLnDlt = p->avgLnDlt;
double *Ni = s->Ni, *Ri = s->Ri, *Nii = s->Nii, **Nij = s->Nij;
int i, j;
for( i = 0 ; i < sNo ; i++ ){
avgPi[i] = ( uPiArr[i] + gmMat[0][i] ) / ( sumUPi + 1.0 );
avgLnPi[i] = gsl_sf_psi( uPiArr[i] + gmMat[0][i] ) - gsl_sf_psi( sumUPi + 1.0 );
for( j = 0 ; j < sNo ; j++ ){
avgA[i][j] = ( uAMat[i][j] + Nij[i][j] ) / ( sumUAArr[i] + Nii[i] );
avgLnA[i][j] = gsl_sf_psi( uAMat[i][j] + Nij[i][j] ) - gsl_sf_psi( sumUAArr[i] + Nii[i] );
}
aDlt[i] = uAArr[i] + Ni[i];
bDlt[i] = uBArr[i] + Ri[i] / 4.0;
avgDlt[i] = aDlt[i] / bDlt[i];
avgLnDlt[i] = gsl_sf_psi( aDlt[i] ) - log( bDlt[i] );
}
}
void maximizationG_gaussDiff( xns, gv, ivs )
xnDataBundle *xns;
globalVars *gv;
indVarBundle *ivs;
{
gaussDiffParameters *p = (gaussDiffParameters*)gv->params;
double *uPiArr = p->uPiArr, sumUPi = p->sumUPi;
double **uAMat = p->uAMat, *sumUAArr = p->sumUAArr;
double *uAArr = p->uAArr, *uBArr = p->uBArr, *aDlt = p->aDlt, *bDlt = p->bDlt;
double *avgPi = p->avgPi, *avgLnPi = p->avgLnPi, **avgA = p->avgA, **avgLnA = p->avgLnA;
double *avgDlt = p->avgDlt, *avgLnDlt = p->avgLnDlt;
gaussDiffGlobalStats *gs = (gaussDiffGlobalStats*)ivs->stats;
double *NiR = gs->NiR, *NiiR = gs->NiiR, **NijR = gs->NijR, *RiR = gs->RiR;
double *z1iR = gs->z1iR, dR = (double)(xns->R);
int sNo = gv->sNo;
int i, j;
for( i = 0 ; i < sNo ; i++ ){
avgPi[i] = ( uPiArr[i] + z1iR[i] ) / ( sumUPi + dR );
avgLnPi[i] = gsl_sf_psi( uPiArr[i] + z1iR[i] ) - gsl_sf_psi( sumUPi + dR );
for( j = 0 ; j < sNo ; j++ ){
avgA[i][j] = ( uAMat[i][j] + NijR[i][j] ) / ( sumUAArr[i] + NiiR[i] );
avgLnA[i][j] = gsl_sf_psi( uAMat[i][j] + NijR[i][j] ) - gsl_sf_psi( sumUAArr[i] + NiiR[i] );
}
aDlt[i] = uAArr[i] + NiR[i];
bDlt[i] = uBArr[i] + RiR[i] / 4.0;
avgDlt[i] = aDlt[i] / bDlt[i];
avgLnDlt[i] = gsl_sf_psi( aDlt[i] ) - log( bDlt[i] );
}
}
double varLowerBound_gaussDiff( xn, gv, iv )
xnDataSet *xn;
globalVars *gv;
indVars *iv;
{
gaussDiffParameters *p = (gaussDiffParameters*)gv->params;
gaussDiffStats *s = (gaussDiffStats*)iv->stats;
size_t dLen = xn->N;
int sNo = gv->sNo;
double **gmMat = iv->gmMat, *cn = iv->cn;
double *uPiArr = p->uPiArr, sumUPi = p->sumUPi;
double **uAMat = p->uAMat, *sumUAArr = p->sumUAArr;
double *uAArr = p->uAArr, *uBArr = p->uBArr;
double *avgLnPi = p->avgLnPi, **avgLnA = p->avgLnA;
double *avgDlt = p->avgDlt, *avgLnDlt = p->avgLnDlt;
double *Nii = s->Nii, **Nij = s->Nij;
double *aDlt = p->aDlt, *bDlt = p->bDlt;
size_t n;
int i, j;
double lnpPi = gsl_sf_lngamma(sumUPi);
double lnpA = 0.0;
double lnpDlt = 0.0;
double lnqPi = gsl_sf_lngamma(sumUPi + 1.0);
double lnqA = 0.0;
double lnqDlt = - sNo / 2.0;
for( i = 0 ; i < sNo ; i++ ){
lnpPi += (uPiArr[i]-1.0) * avgLnPi[i] - gsl_sf_lngamma(uPiArr[i]);
lnpDlt += - gsl_sf_lngamma(uAArr[i]) + uAArr[i] * log(uBArr[i]);
lnpDlt += (uAArr[i] - 1.0) * avgLnDlt[i] - uBArr[i] * avgDlt[i];
lnqPi += (uPiArr[i]+gmMat[0][i]-1.0) * (gsl_sf_psi(uPiArr[i]+gmMat[0][i]) - gsl_sf_psi(sumUPi+1.0));
lnqPi -= gsl_sf_lngamma(uPiArr[i] + gmMat[0][i]);
lnpA += gsl_sf_lngamma(sumUAArr[i]);
lnqA += gsl_sf_lngamma(sumUAArr[i] + Nii[i]);
for( j = 0 ; j < sNo ; j++ ){
lnpA += (uAMat[i][j]-1.0)*avgLnA[i][j] - gsl_sf_lngamma(uAMat[i][j]);
lnqA += (uAMat[i][j] + Nij[i][j] - 1.0) * (gsl_sf_psi(uAMat[i][j]+Nij[i][j]) - gsl_sf_psi(sumUAArr[i]+Nii[i]));
lnqA -= gsl_sf_lngamma( uAMat[i][j] + Nij[i][j] );
}
lnqDlt += - gsl_sf_lngamma(aDlt[i]) + aDlt[i] * log(bDlt[i]);
lnqDlt += (aDlt[i] - 1.0) * avgLnDlt[i] - aDlt[i];
}
double lnpX = 0.0;
for( n = 0 ; n < dLen ; n++ ){
lnpX += log( cn[n] );
}
double val;
val = lnpPi + lnpA + lnpDlt;
val -= lnqPi + lnqA + lnqDlt;
val += lnpX;
val += log(gsl_sf_fact(sNo));
return val;
}
double varLowerBoundG_gaussDiff( xns, gv, ivs )
xnDataBundle *xns;
globalVars *gv;
indVarBundle *ivs;
{
gaussDiffParameters *p = (gaussDiffParameters*)gv->params;
int sNo = gv->sNo, rNo = xns->R;
double *uPiArr = p->uPiArr, sumUPi = p->sumUPi;
double **uAMat = p->uAMat, *sumUAArr = p->sumUAArr;
double *uAArr = p->uAArr, *uBArr = p->uBArr;
double *avgLnPi = p->avgLnPi, **avgLnA = p->avgLnA;
double *avgDlt = p->avgDlt, *avgLnDlt = p->avgLnDlt;
double *aDlt = p->aDlt, *bDlt = p->bDlt;
gaussDiffGlobalStats *gs = (gaussDiffGlobalStats*)ivs->stats;
double *NiiR = gs->NiiR, **NijR = gs->NijR, *z1iR = gs->z1iR, dR = (double)xns->R;
size_t n;
int i, j, r;
double lnpPi = gsl_sf_lngamma(sumUPi);
double lnpA = 0.0;
double lnpDlt = 0.0;
double lnqPi = gsl_sf_lngamma(sumUPi + dR);
double lnqA = 0.0;
double lnqDlt = - sNo / 2.0;
for( i = 0 ; i < sNo ; i++ ){
lnpPi += (uPiArr[i]-1.0) * avgLnPi[i] - gsl_sf_lngamma(uPiArr[i]);
lnpDlt += - gsl_sf_lngamma(uAArr[i]) + uAArr[i] * log(uBArr[i]);
lnpDlt += (uAArr[i] - 1.0) * avgLnDlt[i] - uBArr[i] * avgDlt[i];
lnqPi += (uPiArr[i]+z1iR[i]-1.0) * (gsl_sf_psi(uPiArr[i]+z1iR[i]) - gsl_sf_psi(sumUPi+dR));
lnqPi -= gsl_sf_lngamma(uPiArr[i] + z1iR[i]);
lnpA += gsl_sf_lngamma(sumUAArr[i]);
lnqA += gsl_sf_lngamma(sumUAArr[i] + NiiR[i]);
for( j = 0 ; j < sNo ; j++ ){
lnpA += (uAMat[i][j]-1.0)*avgLnA[i][j] - gsl_sf_lngamma(uAMat[i][j]);
lnqA += (uAMat[i][j] + NijR[i][j] - 1.0) * (gsl_sf_psi(uAMat[i][j]+NijR[i][j]) - gsl_sf_psi(sumUAArr[i]+NiiR[i]));
lnqA -= gsl_sf_lngamma( uAMat[i][j] + NijR[i][j] );
}
lnqDlt += - gsl_sf_lngamma(aDlt[i]) + aDlt[i] * log(bDlt[i]);
lnqDlt += (aDlt[i] - 1.0) * avgLnDlt[i] - aDlt[i];
}
double lnpX = 0.0;
for( r = 0 ; r < rNo ; r++ ){
size_t dLen = xns->xn[r]->N;
for( n = 0 ; n < dLen ; n++ ){
lnpX += log( ivs->indVars[r]->cn[n] );
}
}
double val;
val = lnpPi + lnpA + lnpDlt;
val -= lnqPi + lnqA + lnqDlt;
val += lnpX;
val += log(gsl_sf_fact(sNo));
return val;
}
void reorderParameters_gaussDiff( xn, gv, iv )
xnDataSet *xn;
globalVars *gv;
indVars *iv;
{
gaussDiffParameters *p = (gaussDiffParameters*)gv->params;
gaussDiffStats *s = (gaussDiffStats*)iv->stats;
size_t dLen = xn->N;
int sNo = gv->sNo;
double **gmMat = iv->gmMat, ***xiMat = iv->xiMat;
double *avgPi = p->avgPi, *avgLnPi = p->avgLnPi, **avgA = p->avgA, **avgLnA = p->avgLnA;
double *avgDlt = p->avgDlt, *avgLnDlt = p->avgLnDlt;
double *Ni = s->Ni;
size_t n;
int i, j;
int *index = (int*)malloc( sNo * sizeof(int) );
double *store = (double*)malloc( sNo * sizeof(double) );
double **s2D = (double**)malloc( sNo * sizeof(double*) );
for( i = 0 ; i < sNo ; i++ )
{ s2D[i] = (double*)malloc( MAX(sNo,2) * sizeof(double) ); }
// index indicates order of avgDlt values (0=biggest avgDlt -- sNo=smallest avgDlt).
for( i = 0 ; i < sNo ; i++ ){
index[i] = sNo - 1;
for( j = 0 ; j < sNo ; j++ ){
if( j != i ){
if( avgDlt[i] < avgDlt[j] ){
index[i]--;
} else if( avgDlt[i] == avgDlt[j] ){
if( j > i )
{ index[i]--; }
}
}
}
}
for( i = 0 ; i < sNo ; i++ ){ store[index[i]] = avgPi[i]; }
for( i = 0 ; i < sNo ; i++ ){ avgPi[i] = store[i]; }
for( i = 0 ; i < sNo ; i++ ){ store[index[i]] = avgLnPi[i]; }
for( i = 0 ; i < sNo ; i++ ){ avgLnPi[i] = store[i]; }
for( i = 0 ; i < sNo ; i++ ){ store[index[i]] = avgDlt[i]; }
for( i = 0 ; i < sNo ; i++ ){ avgDlt[i] = store[i]; }
for( i = 0 ; i < sNo ; i++ ){ store[index[i]] = avgLnDlt[i]; }
for( i = 0 ; i < sNo ; i++ ){ avgLnDlt[i] = store[i]; }
for( j = 0 ; j < sNo ; j++ ){
for( i = 0 ; i < sNo ; i++ ){ s2D[index[i]][index[j]] = avgA[i][j]; }
}
for( j = 0 ; j < sNo ; j++ ){
for( i = 0 ; i < sNo ; i++ ){ avgA[i][j] = s2D[i][j]; }
}
for( j = 0 ; j < sNo ; j++ ){
for( i = 0 ; i < sNo ; i++ ){ s2D[index[i]][index[j]] = avgLnA[i][j]; }
}
for( j = 0 ; j < sNo ; j++ ){
for( i = 0 ; i < sNo ; i++ ){ avgLnA[i][j] = s2D[i][j]; }
}
for( i = 0 ; i < sNo ; i++ ){ store[index[i]] = Ni[i]; }
for( i = 0 ; i < sNo ; i++ ){ Ni[i] = store[i]; }
for( n = 0 ; n < dLen ; n++ ){
for( i = 0 ; i < sNo ; i++ ){ store[index[i]] = gmMat[n][i]; }
for( i = 0 ; i < sNo ; i++ ){ gmMat[n][i] = store[i]; }
}
for( n = 0 ; n < dLen ; n++ ){
for( j = 0 ; j < sNo ; j++ ){
for( i = 0 ; i < sNo ; i++ ){ s2D[index[i]][index[j]] = xiMat[n][i][j]; }
}
for( j = 0 ; j < sNo ; j++ ){
for( i = 0 ; i < sNo ; i++ ){ xiMat[n][i][j] = s2D[i][j]; }
}
}
for( i = 0 ; i < sNo ; i++ ){ free( s2D[i] ); }
free( s2D );
free( store );
free( index );
}
void reorderParametersG_gaussDiff( xns, gv, ivs )
xnDataBundle *xns;
globalVars *gv;
indVarBundle *ivs;
{
gaussDiffParameters *p = (gaussDiffParameters*)gv->params;
size_t dLen;
int sNo = gv->sNo, rNo = xns->R;
double *avgPi = p->avgPi, *avgLnPi = p->avgLnPi, **avgA = p->avgA, **avgLnA = p->avgLnA;
double *avgDlt = p->avgDlt, *avgLnDlt = p->avgLnDlt;
size_t n;
int i, j, r;
int *index = (int*)malloc( sNo * sizeof(int) );
double *store = (double*)malloc( sNo * sizeof(double) );
double **s2D = (double**)malloc( sNo * sizeof(double*) );
for( i = 0 ; i < sNo ; i++ )
{ s2D[i] = (double*)malloc( MAX(sNo,2) * sizeof(double) ); }
// index indicates order of avgMu values (0=biggest avgMu -- sNo=smallest avgMu).
for( i = 0 ; i < sNo ; i++ ){
index[i] = sNo - 1;
for( j = 0 ; j < sNo ; j++ ){
if( j != i ){
if( avgDlt[i] < avgDlt[j] ){
index[i]--;
} else if( avgDlt[i] == avgDlt[j] ){
if( j > i )
{ index[i]--; }
}
}
}
}
for( i = 0 ; i < sNo ; i++ ){ store[index[i]] = avgPi[i]; }
for( i = 0 ; i < sNo ; i++ ){ avgPi[i] = store[i]; }
for( i = 0 ; i < sNo ; i++ ){ store[index[i]] = avgLnPi[i]; }
for( i = 0 ; i < sNo ; i++ ){ avgLnPi[i] = store[i]; }
for( i = 0 ; i < sNo ; i++ ){ store[index[i]] = avgDlt[i]; }
for( i = 0 ; i < sNo ; i++ ){ avgDlt[i] = store[i]; }
for( i = 0 ; i < sNo ; i++ ){ store[index[i]] = avgLnDlt[i]; }
for( i = 0 ; i < sNo ; i++ ){ avgLnDlt[i] = store[i]; }
for( j = 0 ; j < sNo ; j++ ){
for( i = 0 ; i < sNo ; i++ ){ s2D[index[i]][index[j]] = avgA[i][j]; }
}
for( j = 0 ; j < sNo ; j++ ){
for( i = 0 ; i < sNo ; i++ ){ avgA[i][j] = s2D[i][j]; }
}
for( j = 0 ; j < sNo ; j++ ){
for( i = 0 ; i < sNo ; i++ ){ s2D[index[i]][index[j]] = avgLnA[i][j]; }
}
for( j = 0 ; j < sNo ; j++ ){
for( i = 0 ; i < sNo ; i++ ){ avgLnA[i][j] = s2D[i][j]; }
}
double *NiR = ((gaussDiffGlobalStats*)ivs->stats)->NiR;
for( i = 0 ; i < sNo ; i++ ){ store[index[i]] = NiR[i]; }
for( i = 0 ; i < sNo ; i++ ){ NiR[i] = store[i]; }
for( r = 0 ; r < rNo ; r++ ){
double **gmMat = ivs->indVars[r]->gmMat;
dLen = xns->xn[r]->N;
for( n = 0 ; n < dLen ; n++ ){
for( i = 0 ; i < sNo ; i++ ){ store[index[i]] = gmMat[n][i]; }
for( i = 0 ; i < sNo ; i++ ){ gmMat[n][i] = store[i]; }
}
}
for( r = 0 ; r < rNo ; r++ ){
double ***xiMat = ivs->indVars[r]->xiMat;
dLen = xns->xn[r]->N;
for( n = 0 ; n < dLen ; n++ ){
for( j = 0 ; j < sNo ; j++ ){
for( i = 0 ; i < sNo ; i++ ){ s2D[index[i]][index[j]] = xiMat[n][i][j]; }
}
for( j = 0 ; j < sNo ; j++ ){
for( i = 0 ; i < sNo ; i++ ){ xiMat[n][i][j] = s2D[i][j]; }
}
}
}
for( i = 0 ; i < sNo ; i++ ){ free( s2D[i] ); }
free( s2D );
free( store );
free( index );
}
void outputGaussDiffResults( xn, gv, iv, logFP )
xnDataSet *xn;
globalVars *gv;
indVars *iv;
FILE *logFP;
{
gaussDiffParameters *p = (gaussDiffParameters*)gv->params;
int sNo = gv->sNo;
int i, j;
fprintf(logFP, " results: K = %d \n", sNo);
fprintf(logFP, " delta: ( %g", p->avgDlt[0]);
for( i = 1 ; i < sNo ; i++ ){
fprintf(logFP, ", %g", p->avgDlt[i]);
}
fprintf(logFP, " ) \n");
fprintf(logFP, " pi: ( %g", p->avgPi[0]);
for( i = 1 ; i < sNo ; i++ ){
fprintf(logFP, ", %g", p->avgPi[i]);
}
fprintf(logFP, " ) \n");
fprintf(logFP, " A_matrix: [");
for( i = 0 ; i < sNo ; i++ ){
fprintf(logFP, " ( %g", p->avgA[i][0]);
for( j = 1 ; j < sNo ; j++ )
{ fprintf(logFP, ", %g", p->avgA[i][j]); }
fprintf(logFP, ")");
}
fprintf(logFP, " ] \n\n");
char fn[256];
FILE *fp;
size_t n;
sprintf( fn, "%s.param%03d", xn->name, sNo );
if( (fp = fopen( fn, "w")) != NULL ){
fprintf(fp, "delta, pi");
for( i = 0 ; i < sNo ; i++ )
{ fprintf(fp, ", A%dx", i); }
fprintf(fp, "\n");
for( i = 0 ; i < sNo ; i++ ){
fprintf(fp, "%g, %g", p->avgDlt[i], p->avgPi[i]);
for( j = 0 ; j < sNo ; j++ )
{ fprintf(fp, ", %g", p->avgA[j][i]); }
fprintf(fp, "\n");
}
fclose(fp);
}
sprintf( fn, "%s.Lq%03d", xn->name, sNo );
if( (fp = fopen( fn, "w")) != NULL ){
for( n = 0 ; n < gv->iteration ; n++ ){
fprintf( fp, "%24.20e\n", gv->LqArr[n] );
}
fclose(fp);
}
sprintf( fn, "%s.maxS%03d", xn->name, sNo );
if( (fp = fopen( fn, "w")) != NULL ){
for( n = 0 ; n < xn->N ; n++ ){
fprintf( fp, "%d\n", iv->stateTraj[n] );
}
fclose(fp);
}
}
void outputGaussDiffResultsG( xns, gv, ivs, logFP )
xnDataBundle *xns;
globalVars *gv;
indVarBundle *ivs;
FILE *logFP;
{
int sNo = gv->sNo, rNo = xns->R;
gaussDiffParameters *p = (gaussDiffParameters*)gv->params;
int i, j, r;
fprintf(logFP, " results: K = %d \n", sNo);
fprintf(logFP, " delta: ( %g", p->avgDlt[0]);
for( i = 1 ; i < sNo ; i++ )
{ fprintf(logFP, ", %g", p->avgDlt[i]); }
fprintf(logFP, " ) \n");
fprintf(logFP, " pi: ( %g", p->avgPi[0]);
for( i = 1 ; i < sNo ; i++ ){
fprintf(logFP, ", %g", p->avgPi[i]);
}
fprintf(logFP, " ) \n");
fprintf(logFP, " A_matrix: [");
for( i = 0 ; i < sNo ; i++ ){
fprintf(logFP, " ( %g", p->avgA[i][0]);
for( j = 1 ; j < sNo ; j++ )
{ fprintf(logFP, ", %g", p->avgA[i][j]); }
fprintf(logFP, ")");
}
fprintf(logFP, " ] \n\n");
char fn[256];
FILE *fp;
size_t n;
sprintf( fn, "%s.param%03d", xns->xn[0]->name, sNo );
if( (fp = fopen( fn, "w")) != NULL ){
fprintf(fp, "delta, pi");
for( i = 0 ; i < sNo ; i++ )
{ fprintf(fp, ", A%dx", i); }
fprintf(fp, "\n");
for( i = 0 ; i < sNo ; i++ ){
fprintf(fp, "%g, %g", p->avgDlt[i], p->avgPi[i]);
for( j = 0 ; j < sNo ; j++ )
{ fprintf(fp, ", %g", p->avgA[j][i]); }
fprintf(fp, "\n");
}
fclose(fp);
}
sprintf( fn, "%s.Lq%03d", xns->xn[0]->name, sNo );
if( (fp = fopen( fn, "w")) != NULL ){
for( n = 0 ; n < gv->iteration ; n++ ){
fprintf( fp, "%24.20e\n", gv->LqArr[n] );
}
fclose(fp);
}
sprintf( fn, "%s.maxS%03d", xns->xn[0]->name, sNo );
int flag = 0;
if( (fp = fopen( fn, "w")) != NULL ){
n = 0;
do{
flag = 1;
for( r = 0 ; r < rNo ; r++ ){
xnDataSet *xn = xns->xn[r];
indVars *iv = ivs->indVars[r];
if( r > 0 ){
fprintf( fp, "," );
}
if( n < xn->N ){
fprintf( fp, "%d", iv->stateTraj[n] );
}
flag &= (n >= (xn->N - 1));
}
fprintf( fp, "\n" );
n++;
}while( !flag );
fclose(fp);
}
}
//
| {
"alphanum_fraction": 0.4883567518,
"avg_line_length": 29.8112094395,
"ext": "c",
"hexsha": "c8a0fa0bcfd0940f04f183db8482dfbb62a79d0d",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "77afe3c336c9e1ebeb115ca4f0b2bc25060556bd",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "okamoto-kenji/varBayes-HMM",
"max_forks_repo_path": "C/vbHmmGaussDiffusion.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "77afe3c336c9e1ebeb115ca4f0b2bc25060556bd",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "okamoto-kenji/varBayes-HMM",
"max_issues_repo_path": "C/vbHmmGaussDiffusion.c",
"max_line_length": 126,
"max_stars_count": 7,
"max_stars_repo_head_hexsha": "77afe3c336c9e1ebeb115ca4f0b2bc25060556bd",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "okamoto-kenji/varBayes-HMM",
"max_stars_repo_path": "C/vbHmmGaussDiffusion.c",
"max_stars_repo_stars_event_max_datetime": "2019-11-01T06:35:57.000Z",
"max_stars_repo_stars_event_min_datetime": "2016-03-31T06:59:00.000Z",
"num_tokens": 11323,
"size": 30318
} |
/* randist/demo.c
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 James Theiler, Brian Gough
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include <stdio.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
int
main ()
{
gsl_rng * r ;
int i, n = 10;
double mu = 3.0;
/* create a generator chosen by the environment variable GSL_RNG_TYPE */
gsl_rng_env_setup();
r = gsl_rng_alloc (gsl_rng_default);
/* print n random variates chosen from the poisson distribution with
mean parameter mu */
for (i = 0; i < n; i++)
{
unsigned int k = gsl_ran_poisson (r, mu);
printf(" %u", k);
}
printf("\n");
}
| {
"alphanum_fraction": 0.6849518162,
"avg_line_length": 26.98,
"ext": "c",
"hexsha": "0e7136833ed46e2a0f8213ab6bbbe88866479297",
"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/randist/demo.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/randist/demo.c",
"max_line_length": 81,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "zzpwahaha/Chimera-Control-Trim",
"max_stars_repo_path": "Chimera/3rd_Party/GSL_MSVC/randist/demo.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": 368,
"size": 1349
} |
#pragma once
#define OEMRESOURCE
#include <atomic>
#include <concepts>
#include <ppl.h>
#include <gsl/gsl>
// Included before windows.h, because pfc.h includes winsock2.h
#include "../pfc/pfc.h"
#include <windows.h>
#include <SHLWAPI.H>
#include "../foobar2000/SDK/foobar2000.h"
#include "../mmh/stdafx.h"
#include "../ui_helpers/stdafx.h"
#include "config_var.h"
#include "config_object.h"
#include "console.h"
#include "fcl.h"
#include "info_box.h"
#include "initquit.h"
#include "library.h"
#include "low_level_hook.h"
#include "main_thread_callback.h"
#include "sort.h"
#include "stream.h"
| {
"alphanum_fraction": 0.7180762852,
"avg_line_length": 17.7352941176,
"ext": "h",
"hexsha": "abffa3466220cecfdbc1f9902e18d72181e42072",
"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": "d065acb4ceaf829292613f8ce9f4aa373b187ad7",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "reupen/fbh",
"max_forks_repo_path": "stdafx.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "d065acb4ceaf829292613f8ce9f4aa373b187ad7",
"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": "reupen/fbh",
"max_issues_repo_path": "stdafx.h",
"max_line_length": 63,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "d065acb4ceaf829292613f8ce9f4aa373b187ad7",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "reupen/fbh",
"max_stars_repo_path": "stdafx.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 159,
"size": 603
} |
/**
*
* @file core_zsyssq.c
*
* PLASMA core_blas kernel
* PLASMA is a software package provided by Univ. of Tennessee,
* Univ. of California Berkeley and Univ. of Colorado Denver
*
* @version 2.8.0
* @author Mathieu Faverge
* @date 2010-11-15
* @precisions normal z -> c d s
*
**/
#include <math.h>
#include <lapacke.h>
#include "common.h"
#define COMPLEX
#define UPDATE( __nb, __value ) \
if (__value != 0. ){ \
if ( *scale < __value ) { \
*sumsq = __nb + (*sumsq) * ( *scale / __value ) * ( *scale / __value ); \
*scale = __value; \
} else { \
*sumsq = *sumsq + __nb * ( __value / *scale ) * ( __value / *scale ); \
} \
}
/*****************************************************************************
*
* @ingroup dplasma_cores_complex64
*
* CORE_zsyssq returns the values scl and ssq such that
*
* ( scl**2 )*ssq = sum( A( i, j )**2 ) + ( scale**2 )*sumsq,
* i,j
*
* with i from 0 to N-1 and j form 0 to N-1. The value of sumsq is
* assumed to be at least unity and the value of ssq will then satisfy
*
* 1.0 .le. ssq .le. ( sumsq + 2*n*n ).
*
* scale is assumed to be non-negative and scl returns the value
*
* scl = max( scale, abs( real( A( i, j ) ) ), abs( aimag( A( i, j ) ) ) ),
* i,j
*
* scale and sumsq must be supplied in SCALE and SUMSQ respectively.
* SCALE and SUMSQ are overwritten by scl and ssq respectively.
*
* The routine makes only one pass through the tile triangular part of the
* symmetric tile A defined by uplo.
* See also LAPACK zlassq.f
*
*******************************************************************************
*
* @param[in] uplo
* Specifies whether the upper or lower triangular part of
* the symmetric matrix A is to be referenced as follows:
* = PlasmaLower: Only the lower triangular part of the
* symmetric matrix A is to be referenced.
* = PlasmaUpper: Only the upper triangular part of the
* symmetric matrix A is to be referenced.
*
* @param[in] N
* The number of columns and rows in the tile A.
*
* @param[in] A
* The N-by-N matrix on which to compute the norm.
*
* @param[in] LDA
* The leading dimension of the tile A. LDA >= max(1,N).
*
* @param[in,out] scale
* On entry, the value scale in the equation above.
* On exit, scale is overwritten with the value scl.
*
* @param[in,out] sumsq
* On entry, the value sumsq in the equation above.
* On exit, SUMSQ is overwritten with the value ssq.
*
*******************************************************************************
*
* @return
* \retval PLASMA_SUCCESS successful exit
* \retval -k, the k-th argument had an illegal value
*
*/
#if defined(PLASMA_HAVE_WEAK)
#pragma weak CORE_zsyssq = PCORE_zsyssq
#define CORE_zsyssq PCORE_zsyssq
#endif
int CORE_zsyssq(PLASMA_enum uplo, int N,
const PLASMA_Complex64_t *A, int LDA,
double *scale, double *sumsq)
{
int i, j;
double tmp;
double *ptr;
if ( uplo == PlasmaUpper ) {
for(j=0; j<N; j++) {
ptr = (double*) ( A + j * LDA );
for(i=0; i<j; i++, ptr++) {
tmp = fabs(*ptr);
UPDATE( 2., tmp );
#ifdef COMPLEX
ptr++;
tmp = fabs(*ptr);
UPDATE( 2., tmp );
#endif
}
/* Diagonal */
tmp = fabs(*ptr);
UPDATE( 1., tmp );
#ifdef COMPLEX
ptr++;
tmp = fabs(*ptr);
UPDATE( 1., tmp );
#endif
}
} else {
for(j=0; j<N; j++) {
ptr = (double*) ( A + j * LDA + j);
/* Diagonal */
tmp = fabs(*ptr);
UPDATE( 1., tmp );
ptr++;
#ifdef COMPLEX
tmp = fabs(*ptr);
UPDATE( 1., tmp );
ptr++;
#endif
for(i=j+1; i<N; i++, ptr++) {
tmp = fabs(*ptr);
UPDATE( 2., tmp );
#ifdef COMPLEX
ptr++;
tmp = fabs(*ptr);
UPDATE( 2., tmp );
#endif
}
}
}
return PLASMA_SUCCESS;
}
| {
"alphanum_fraction": 0.4558601338,
"avg_line_length": 28.95625,
"ext": "c",
"hexsha": "82843a2b6f46b905d5a53047411efd51c12dc275",
"lang": "C",
"max_forks_count": 5,
"max_forks_repo_forks_event_max_datetime": "2022-03-30T01:53:32.000Z",
"max_forks_repo_forks_event_min_datetime": "2022-02-28T21:24:37.000Z",
"max_forks_repo_head_hexsha": "fa687f0ceec07f03249217b93e8a707aa9fd8ef3",
"max_forks_repo_licenses": [
"BSD-3-Clause-Open-MPI"
],
"max_forks_repo_name": "therault/dplasma",
"max_forks_repo_path": "src/cores/core_zsyssq.c",
"max_issues_count": 5,
"max_issues_repo_head_hexsha": "fa687f0ceec07f03249217b93e8a707aa9fd8ef3",
"max_issues_repo_issues_event_max_datetime": "2022-03-21T15:22:21.000Z",
"max_issues_repo_issues_event_min_datetime": "2022-03-02T21:42:26.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause-Open-MPI"
],
"max_issues_repo_name": "therault/dplasma",
"max_issues_repo_path": "src/cores/core_zsyssq.c",
"max_line_length": 85,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "fa687f0ceec07f03249217b93e8a707aa9fd8ef3",
"max_stars_repo_licenses": [
"BSD-3-Clause-Open-MPI"
],
"max_stars_repo_name": "therault/dplasma",
"max_stars_repo_path": "src/cores/core_zsyssq.c",
"max_stars_repo_stars_event_max_datetime": "2022-03-17T19:36:41.000Z",
"max_stars_repo_stars_event_min_datetime": "2022-03-17T19:36:41.000Z",
"num_tokens": 1147,
"size": 4633
} |
/* -*- linux-c -*- */
/* fewbody_nonks.c
Copyright (C) 2002-2004 John M. Fregeau
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <stdio.h>
#include <stddef.h>
#include <stdlib.h>
#include <math.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_odeiv.h>
#include "fewbody.h"
/* the derivatives function for the GSL ODE integrator */
#define FB_FM(i, j, k) fm[nstar*3*i + 3*j + k]
int fb_nonks_func(double t, const double *y, double *f, void *params)
{
int i, j, k, nstar;
double r[3], *m, *fm, val;
nstar = (*(fb_nonks_params_t *) params).nstar;
m = (*(fb_nonks_params_t *) params).m;
fm = fb_malloc_vector(nstar * nstar * 3);
/* calculate the matrix */
for (i=0; i<nstar; i++) {
for (j=0; j<i; j++) {
for (k=0; k<3; k++) {
FB_FM(i, j, k) = -FB_FM(j, i, k);
}
}
for (j=i+1; j<nstar; j++) {
for (k=0; k<3; k++) {
r[k] = y[j*6+k] - y[i*6+k];
}
val = 1.0 / fb_cub(fb_mod(r));
for (k=0; k<3; k++) {
FB_FM(i, j, k) = val * r[k];
}
}
}
/* calculate derivatives */
for (i=0; i<nstar; i++) {
for (k=0; k<3; k++) {
f[i*6+k] = y[i*6+k+3];
f[i*6+k+3] = 0.0;
}
for (j=0; j<i; j++) {
for (k=0; k<3; k++) {
f[i*6+k+3] += m[j] * FB_FM(i, j, k);
}
}
for (j=i+1; j<nstar; j++) {
for (k=0; k<3; k++) {
f[i*6+k+3] += m[j] * FB_FM(i, j, k);
}
}
}
fb_free_vector(fm);
return(GSL_SUCCESS);
}
#undef FB_FM
/* the Jacobian for the GSL ODE integrator */
int fb_nonks_jac(double t, const double *y, double *dfdy, double *dfdt, void *params)
{
unsigned int i, j, k, a, b, kk;
int nstar;
double r[3], *m, val;
gsl_matrix_view dfdy_mat;
gsl_matrix *matrix;
nstar = (*(fb_nonks_params_t *) params).nstar;
m = (*(fb_nonks_params_t *) params).m;
/* allocate matrices */
dfdy_mat = gsl_matrix_view_array(dfdy, nstar*6, nstar*6);
matrix = &dfdy_mat.matrix;
/* set dfdt to zero */
for (j=0; j< (unsigned int) nstar*6; j++) {
dfdt[j] = 0.0;
}
/* set the matrix to zero to begin with */
gsl_matrix_set_zero(matrix);
/* then set the actual values */
for (i=0; i< (unsigned int) nstar; i++) {
for (a=0; a<3; a++) {
gsl_matrix_set(matrix, i+a, i+a+3, 1.0);
for (k=0; k< (unsigned int) nstar; k++) {
for (b=0; b<3; b++) {
val = 0.0;
for (j=0; j< (unsigned int) nstar; j++) {
if (j != i) {
for (kk=0; kk<3; kk++) {
r[kk] = y[i*6+kk] - y[j*6+kk];
}
val -= m[j] * ((double) (FB_DELTA(i, k) - FB_DELTA(j, k))) / fb_cub(fb_mod(r)) * \
(((double) FB_DELTA(a, b)) - 3.0 * (y[i*6+a] - y[j*6+a])*(y[i*6+b] - y[j*6+b])/fb_dot(r, r));
}
}
gsl_matrix_set(matrix, i+a+3, k+b, val);
}
}
}
}
return(GSL_SUCCESS);
}
void fb_euclidean_to_nonks(fb_obj_t **star, double *y, int nstar)
{
int i, j;
for (i=0; i<nstar; i++) {
for (j=0; j<3; j++) {
y[i*6+j] = star[i]->x[j];
y[i*6+j+3] = star[i]->v[j];
}
}
}
void fb_nonks_to_euclidean(double *y, fb_obj_t **star, int nstar)
{
int i, j;
for (i=0; i<nstar; i++) {
for (j=0; j<3; j++) {
star[i]->x[j] = y[i*6+j];
star[i]->v[j] = y[i*6+j+3];
}
}
}
| {
"alphanum_fraction": 0.5667016807,
"avg_line_length": 23.5061728395,
"ext": "c",
"hexsha": "1cf3a33fa4c7bc0c572e88cbe730ff74f8ff6b6b",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "3612456fc2042519f96a49e4d4cc6d3c1f41de7c",
"max_forks_repo_licenses": [
"PSF-2.0"
],
"max_forks_repo_name": "gnodvi/cosmos",
"max_forks_repo_path": "ext/fewbod/fewbody-0.26/fewbody_nonks.c",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "3612456fc2042519f96a49e4d4cc6d3c1f41de7c",
"max_issues_repo_issues_event_max_datetime": "2021-12-13T20:35:46.000Z",
"max_issues_repo_issues_event_min_datetime": "2021-12-13T20:35:46.000Z",
"max_issues_repo_licenses": [
"PSF-2.0"
],
"max_issues_repo_name": "gnodvi/cosmos",
"max_issues_repo_path": "ext/fewbod/fewbody-0.26/fewbody_nonks.c",
"max_line_length": 101,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "3612456fc2042519f96a49e4d4cc6d3c1f41de7c",
"max_stars_repo_licenses": [
"PSF-2.0"
],
"max_stars_repo_name": "gnodvi/cosmos",
"max_stars_repo_path": "ext/fewbod/fewbody-0.26/fewbody_nonks.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1433,
"size": 3808
} |
/*
* 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 uuid_93a5858f_7040_4f67_9767_808d2a4f7ff9_h
#define uuid_93a5858f_7040_4f67_9767_808d2a4f7ff9_h
#include <gslib/type.h>
#include <gslib/string.h>
__gslib_begin__
struct uuid_timestamp
{
byte tm_sec;
byte tm_min;
byte tm_hour;
byte tm_mday; /* day of month */
byte tm_mon;
byte tm_wday; /* day of week */
int16 tm_year;
int16 tm_yday; /* day of year */
int32 tm_fraction;
};
enum uuid_version
{
uuid_v1, /* date-time & MAC address */
uuid_v2, /* DCE security */
uuid_v3, /* MD5 hash & namespace */
uuid_v4, /* random */
uuid_v5, /* SHA-1 hash & namespace */
uuid_ver_default = uuid_v4,
uuid_ver_invalid = uuid_v2,
};
struct uuid_raw
{
uint data1;
uint16 data2;
uint16 data3;
byte data4[8];
};
class uuid:
protected uuid_raw
{
public:
uuid();
uuid(uuid_version ver) { generate(ver); }
uuid(uuid_version ver, const gchar* name, int len) { generate(ver, name, len); }
uuid(const string& str) { from_string(str.c_str(), str.length()); }
uuid(const gchar* str, int len) { from_string(str, len); }
bool operator==(const uuid& that) const;
bool is_valid() const;
void generate(uuid_version ver);
void generate(uuid_version ver, const gchar* name, int len);
void from_string(const gchar* str, int len);
const gchar* to_string(string& str) const;
void get_timestamp(uuid_timestamp& ts) const;
};
__gslib_end__
#endif
| {
"alphanum_fraction": 0.6472184532,
"avg_line_length": 33.1235955056,
"ext": "h",
"hexsha": "3b28627581bbfeb128cafb0ee781c52923dfe40f",
"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/uuid.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/uuid.h",
"max_line_length": 85,
"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/uuid.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": 720,
"size": 2948
} |
/* specfunc/gsl_sf_bessel.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 __GSL_SF_BESSEL_H__
#define __GSL_SF_BESSEL_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_mode.h>
#include <gsl/gsl_precision.h>
#include <gsl/gsl_sf_result.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
/* Regular Bessel Function J_0(x)
*
* exceptions: none
*/
GSL_FUN int gsl_sf_bessel_J0_e(const double x, gsl_sf_result * result);
GSL_FUN double gsl_sf_bessel_J0(const double x);
/* Regular Bessel Function J_1(x)
*
* exceptions: GSL_EUNDRFLW
*/
GSL_FUN int gsl_sf_bessel_J1_e(const double x, gsl_sf_result * result);
GSL_FUN double gsl_sf_bessel_J1(const double x);
/* Regular Bessel Function J_n(x)
*
* exceptions: GSL_EUNDRFLW
*/
GSL_FUN int gsl_sf_bessel_Jn_e(int n, double x, gsl_sf_result * result);
GSL_FUN double gsl_sf_bessel_Jn(const int n, const double x);
/* Regular Bessel Function J_n(x), nmin <= n <= nmax
*
* exceptions: GSL_EDOM, GSL_EUNDRFLW
*/
GSL_FUN int gsl_sf_bessel_Jn_array(int nmin, int nmax, double x, double * result_array);
/* Irregular Bessel function Y_0(x)
*
* x > 0.0
* exceptions: GSL_EDOM, GSL_EUNDRFLW
*/
GSL_FUN int gsl_sf_bessel_Y0_e(const double x, gsl_sf_result * result);
GSL_FUN double gsl_sf_bessel_Y0(const double x);
/* Irregular Bessel function Y_1(x)
*
* x > 0.0
* exceptions: GSL_EDOM, GSL_EOVRFLW, GSL_EUNDRFLW
*/
GSL_FUN int gsl_sf_bessel_Y1_e(const double x, gsl_sf_result * result);
GSL_FUN double gsl_sf_bessel_Y1(const double x);
/* Irregular Bessel function Y_n(x)
*
* x > 0.0
* exceptions: GSL_EDOM, GSL_EOVRFLW, GSL_EUNDRFLW
*/
GSL_FUN int gsl_sf_bessel_Yn_e(int n,const double x, gsl_sf_result * result);
GSL_FUN double gsl_sf_bessel_Yn(const int n,const double x);
/* Irregular Bessel function Y_n(x), nmin <= n <= nmax
*
* x > 0.0
* exceptions: GSL_EDOM, GSL_EOVRFLW, GSL_EUNDRFLW
*/
GSL_FUN int gsl_sf_bessel_Yn_array(const int nmin, const int nmax, const double x, double * result_array);
/* Regular modified Bessel function I_0(x)
*
* exceptions: GSL_EOVRFLW
*/
GSL_FUN int gsl_sf_bessel_I0_e(const double x, gsl_sf_result * result);
GSL_FUN double gsl_sf_bessel_I0(const double x);
/* Regular modified Bessel function I_1(x)
*
* exceptions: GSL_EOVRFLW, GSL_EUNDRFLW
*/
GSL_FUN int gsl_sf_bessel_I1_e(const double x, gsl_sf_result * result);
GSL_FUN double gsl_sf_bessel_I1(const double x);
/* Regular modified Bessel function I_n(x)
*
* exceptions: GSL_EOVRFLW, GSL_EUNDRFLW
*/
GSL_FUN int gsl_sf_bessel_In_e(const int n, const double x, gsl_sf_result * result);
GSL_FUN double gsl_sf_bessel_In(const int n, const double x);
/* Regular modified Bessel function I_n(x) for n=nmin,...,nmax
*
* nmin >=0, nmax >= nmin
* exceptions: GSL_EDOM, GSL_EOVRFLW, GSL_EUNDRFLW
*/
GSL_FUN int gsl_sf_bessel_In_array(const int nmin, const int nmax, const double x, double * result_array);
/* Scaled regular modified Bessel function
* exp(-|x|) I_0(x)
*
* exceptions: none
*/
GSL_FUN int gsl_sf_bessel_I0_scaled_e(const double x, gsl_sf_result * result);
GSL_FUN double gsl_sf_bessel_I0_scaled(const double x);
/* Scaled regular modified Bessel function
* exp(-|x|) I_1(x)
*
* exceptions: GSL_EUNDRFLW
*/
GSL_FUN int gsl_sf_bessel_I1_scaled_e(const double x, gsl_sf_result * result);
GSL_FUN double gsl_sf_bessel_I1_scaled(const double x);
/* Scaled regular modified Bessel function
* exp(-|x|) I_n(x)
*
* exceptions: GSL_EUNDRFLW
*/
GSL_FUN int gsl_sf_bessel_In_scaled_e(int n, const double x, gsl_sf_result * result);
GSL_FUN double gsl_sf_bessel_In_scaled(const int n, const double x);
/* Scaled regular modified Bessel function
* exp(-|x|) I_n(x) for n=nmin,...,nmax
*
* nmin >=0, nmax >= nmin
* exceptions: GSL_EUNDRFLW
*/
GSL_FUN int gsl_sf_bessel_In_scaled_array(const int nmin, const int nmax, const double x, double * result_array);
/* Irregular modified Bessel function K_0(x)
*
* x > 0.0
* exceptions: GSL_EDOM, GSL_EUNDRFLW
*/
GSL_FUN int gsl_sf_bessel_K0_e(const double x, gsl_sf_result * result);
GSL_FUN double gsl_sf_bessel_K0(const double x);
/* Irregular modified Bessel function K_1(x)
*
* x > 0.0
* exceptions: GSL_EDOM, GSL_EOVRFLW, GSL_EUNDRFLW
*/
GSL_FUN int gsl_sf_bessel_K1_e(const double x, gsl_sf_result * result);
GSL_FUN double gsl_sf_bessel_K1(const double x);
/* Irregular modified Bessel function K_n(x)
*
* x > 0.0
* exceptions: GSL_EDOM, GSL_EOVRFLW, GSL_EUNDRFLW
*/
GSL_FUN int gsl_sf_bessel_Kn_e(const int n, const double x, gsl_sf_result * result);
GSL_FUN double gsl_sf_bessel_Kn(const int n, const double x);
/* Irregular modified Bessel function K_n(x) for n=nmin,...,nmax
*
* x > 0.0, nmin >=0, nmax >= nmin
* exceptions: GSL_EDOM, GSL_EOVRFLW, GSL_EUNDRFLW
*/
GSL_FUN int gsl_sf_bessel_Kn_array(const int nmin, const int nmax, const double x, double * result_array);
/* Scaled irregular modified Bessel function
* exp(x) K_0(x)
*
* x > 0.0
* exceptions: GSL_EDOM
*/
GSL_FUN int gsl_sf_bessel_K0_scaled_e(const double x, gsl_sf_result * result);
GSL_FUN double gsl_sf_bessel_K0_scaled(const double x);
/* Scaled irregular modified Bessel function
* exp(x) K_1(x)
*
* x > 0.0
* exceptions: GSL_EDOM, GSL_EUNDRFLW
*/
GSL_FUN int gsl_sf_bessel_K1_scaled_e(const double x, gsl_sf_result * result);
GSL_FUN double gsl_sf_bessel_K1_scaled(const double x);
/* Scaled irregular modified Bessel function
* exp(x) K_n(x)
*
* x > 0.0
* exceptions: GSL_EDOM, GSL_EUNDRFLW
*/
GSL_FUN int gsl_sf_bessel_Kn_scaled_e(int n, const double x, gsl_sf_result * result);
GSL_FUN double gsl_sf_bessel_Kn_scaled(const int n, const double x);
/* Scaled irregular modified Bessel function exp(x) K_n(x) for n=nmin,...,nmax
*
* x > 0.0, nmin >=0, nmax >= nmin
* exceptions: GSL_EDOM, GSL_EUNDRFLW
*/
GSL_FUN int gsl_sf_bessel_Kn_scaled_array(const int nmin, const int nmax, const double x, double * result_array);
/* Regular spherical Bessel function j_0(x) = sin(x)/x
*
* exceptions: none
*/
GSL_FUN int gsl_sf_bessel_j0_e(const double x, gsl_sf_result * result);
GSL_FUN double gsl_sf_bessel_j0(const double x);
/* Regular spherical Bessel function j_1(x) = (sin(x)/x - cos(x))/x
*
* exceptions: GSL_EUNDRFLW
*/
GSL_FUN int gsl_sf_bessel_j1_e(const double x, gsl_sf_result * result);
GSL_FUN double gsl_sf_bessel_j1(const double x);
/* Regular spherical Bessel function j_2(x) = ((3/x^2 - 1)sin(x) - 3cos(x)/x)/x
*
* exceptions: GSL_EUNDRFLW
*/
GSL_FUN int gsl_sf_bessel_j2_e(const double x, gsl_sf_result * result);
GSL_FUN double gsl_sf_bessel_j2(const double x);
/* Regular spherical Bessel function j_l(x)
*
* l >= 0, x >= 0.0
* exceptions: GSL_EDOM, GSL_EUNDRFLW
*/
GSL_FUN int gsl_sf_bessel_jl_e(const int l, const double x, gsl_sf_result * result);
GSL_FUN double gsl_sf_bessel_jl(const int l, const double x);
/* Regular spherical Bessel function j_l(x) for l=0,1,...,lmax
*
* exceptions: GSL_EDOM, GSL_EUNDRFLW
*/
GSL_FUN int gsl_sf_bessel_jl_array(const int lmax, const double x, double * result_array);
/* Regular spherical Bessel function j_l(x) for l=0,1,...,lmax
* Uses Steed's method.
*
* exceptions: GSL_EDOM, GSL_EUNDRFLW
*/
GSL_FUN int gsl_sf_bessel_jl_steed_array(const int lmax, const double x, double * jl_x_array);
/* Irregular spherical Bessel function y_0(x)
*
* exceptions: none
*/
GSL_FUN int gsl_sf_bessel_y0_e(const double x, gsl_sf_result * result);
GSL_FUN double gsl_sf_bessel_y0(const double x);
/* Irregular spherical Bessel function y_1(x)
*
* exceptions: GSL_EUNDRFLW
*/
GSL_FUN int gsl_sf_bessel_y1_e(const double x, gsl_sf_result * result);
GSL_FUN double gsl_sf_bessel_y1(const double x);
/* Irregular spherical Bessel function y_2(x)
*
* exceptions: GSL_EUNDRFLW
*/
GSL_FUN int gsl_sf_bessel_y2_e(const double x, gsl_sf_result * result);
GSL_FUN double gsl_sf_bessel_y2(const double x);
/* Irregular spherical Bessel function y_l(x)
*
* exceptions: GSL_EUNDRFLW
*/
GSL_FUN int gsl_sf_bessel_yl_e(int l, const double x, gsl_sf_result * result);
GSL_FUN double gsl_sf_bessel_yl(const int l, const double x);
/* Irregular spherical Bessel function y_l(x) for l=0,1,...,lmax
*
* exceptions: GSL_EUNDRFLW
*/
GSL_FUN int gsl_sf_bessel_yl_array(const int lmax, const double x, double * result_array);
/* Regular scaled modified spherical Bessel function
*
* Exp[-|x|] i_0(x)
*
* exceptions: none
*/
GSL_FUN int gsl_sf_bessel_i0_scaled_e(const double x, gsl_sf_result * result);
GSL_FUN double gsl_sf_bessel_i0_scaled(const double x);
/* Regular scaled modified spherical Bessel function
*
* Exp[-|x|] i_1(x)
*
* exceptions: GSL_EUNDRFLW
*/
GSL_FUN int gsl_sf_bessel_i1_scaled_e(const double x, gsl_sf_result * result);
GSL_FUN double gsl_sf_bessel_i1_scaled(const double x);
/* Regular scaled modified spherical Bessel function
*
* Exp[-|x|] i_2(x)
*
* exceptions: GSL_EUNDRFLW
*/
GSL_FUN int gsl_sf_bessel_i2_scaled_e(const double x, gsl_sf_result * result);
GSL_FUN double gsl_sf_bessel_i2_scaled(const double x);
/* Regular scaled modified spherical Bessel functions
*
* Exp[-|x|] i_l(x)
*
* i_l(x) = Sqrt[Pi/(2x)] BesselI[l+1/2,x]
*
* l >= 0
* exceptions: GSL_EDOM, GSL_EUNDRFLW
*/
GSL_FUN int gsl_sf_bessel_il_scaled_e(const int l, double x, gsl_sf_result * result);
GSL_FUN double gsl_sf_bessel_il_scaled(const int l, const double x);
/* Regular scaled modified spherical Bessel functions
*
* Exp[-|x|] i_l(x)
* for l=0,1,...,lmax
*
* exceptions: GSL_EUNDRFLW
*/
GSL_FUN int gsl_sf_bessel_il_scaled_array(const int lmax, const double x, double * result_array);
/* Irregular scaled modified spherical Bessel function
* Exp[x] k_0(x)
*
* x > 0.0
* exceptions: GSL_EDOM, GSL_EUNDRFLW
*/
GSL_FUN int gsl_sf_bessel_k0_scaled_e(const double x, gsl_sf_result * result);
GSL_FUN double gsl_sf_bessel_k0_scaled(const double x);
/* Irregular modified spherical Bessel function
* Exp[x] k_1(x)
*
* x > 0.0
* exceptions: GSL_EDOM, GSL_EUNDRFLW, GSL_EOVRFLW
*/
GSL_FUN int gsl_sf_bessel_k1_scaled_e(const double x, gsl_sf_result * result);
GSL_FUN double gsl_sf_bessel_k1_scaled(const double x);
/* Irregular modified spherical Bessel function
* Exp[x] k_2(x)
*
* x > 0.0
* exceptions: GSL_EDOM, GSL_EUNDRFLW, GSL_EOVRFLW
*/
GSL_FUN int gsl_sf_bessel_k2_scaled_e(const double x, gsl_sf_result * result);
GSL_FUN double gsl_sf_bessel_k2_scaled(const double x);
/* Irregular modified spherical Bessel function
* Exp[x] k_l[x]
*
* k_l(x) = Sqrt[Pi/(2x)] BesselK[l+1/2,x]
*
* exceptions: GSL_EDOM, GSL_EUNDRFLW
*/
GSL_FUN int gsl_sf_bessel_kl_scaled_e(int l, const double x, gsl_sf_result * result);
GSL_FUN double gsl_sf_bessel_kl_scaled(const int l, const double x);
/* Irregular scaled modified spherical Bessel function
* Exp[x] k_l(x)
*
* for l=0,1,...,lmax
* exceptions: GSL_EDOM, GSL_EUNDRFLW
*/
GSL_FUN int gsl_sf_bessel_kl_scaled_array(const int lmax, const double x, double * result_array);
/* Regular cylindrical Bessel function J_nu(x)
*
* exceptions: GSL_EDOM, GSL_EUNDRFLW
*/
GSL_FUN int gsl_sf_bessel_Jnu_e(const double nu, const double x, gsl_sf_result * result);
GSL_FUN double gsl_sf_bessel_Jnu(const double nu, const double x);
/* Irregular cylindrical Bessel function Y_nu(x)
*
* exceptions:
*/
GSL_FUN int gsl_sf_bessel_Ynu_e(double nu, double x, gsl_sf_result * result);
GSL_FUN double gsl_sf_bessel_Ynu(const double nu, const double x);
/* Regular cylindrical Bessel function J_nu(x)
* evaluated at a series of x values. The array
* contains the x values. They are assumed to be
* strictly ordered and positive. The array is
* over-written with the values of J_nu(x_i).
*
* exceptions: GSL_EDOM, GSL_EINVAL
*/
GSL_FUN int gsl_sf_bessel_sequence_Jnu_e(double nu, gsl_mode_t mode, size_t size, double * v);
/* Scaled modified cylindrical Bessel functions
*
* Exp[-|x|] BesselI[nu, x]
* x >= 0, nu >= 0
*
* exceptions: GSL_EDOM
*/
GSL_FUN int gsl_sf_bessel_Inu_scaled_e(double nu, double x, gsl_sf_result * result);
GSL_FUN double gsl_sf_bessel_Inu_scaled(double nu, double x);
/* Modified cylindrical Bessel functions
*
* BesselI[nu, x]
* x >= 0, nu >= 0
*
* exceptions: GSL_EDOM, GSL_EOVRFLW
*/
GSL_FUN int gsl_sf_bessel_Inu_e(double nu, double x, gsl_sf_result * result);
GSL_FUN double gsl_sf_bessel_Inu(double nu, double x);
/* Scaled modified cylindrical Bessel functions
*
* Exp[+|x|] BesselK[nu, x]
* x > 0, nu >= 0
*
* exceptions: GSL_EDOM
*/
GSL_FUN int gsl_sf_bessel_Knu_scaled_e(const double nu, const double x, gsl_sf_result * result);
GSL_FUN double gsl_sf_bessel_Knu_scaled(const double nu, const double x);
GSL_FUN int gsl_sf_bessel_Knu_scaled_e10_e(const double nu, const double x, gsl_sf_result_e10 * result);
/* Modified cylindrical Bessel functions
*
* BesselK[nu, x]
* x > 0, nu >= 0
*
* exceptions: GSL_EDOM, GSL_EUNDRFLW
*/
GSL_FUN int gsl_sf_bessel_Knu_e(const double nu, const double x, gsl_sf_result * result);
GSL_FUN double gsl_sf_bessel_Knu(const double nu, const double x);
/* Logarithm of modified cylindrical Bessel functions.
*
* Log[BesselK[nu, x]]
* x > 0, nu >= 0
*
* exceptions: GSL_EDOM
*/
GSL_FUN int gsl_sf_bessel_lnKnu_e(const double nu, const double x, gsl_sf_result * result);
GSL_FUN double gsl_sf_bessel_lnKnu(const double nu, const double x);
/* s'th positive zero of the Bessel function J_0(x).
*
* exceptions:
*/
GSL_FUN int gsl_sf_bessel_zero_J0_e(unsigned int s, gsl_sf_result * result);
GSL_FUN double gsl_sf_bessel_zero_J0(unsigned int s);
/* s'th positive zero of the Bessel function J_1(x).
*
* exceptions:
*/
GSL_FUN int gsl_sf_bessel_zero_J1_e(unsigned int s, gsl_sf_result * result);
GSL_FUN double gsl_sf_bessel_zero_J1(unsigned int s);
/* s'th positive zero of the Bessel function J_nu(x).
*
* exceptions:
*/
GSL_FUN int gsl_sf_bessel_zero_Jnu_e(double nu, unsigned int s, gsl_sf_result * result);
GSL_FUN double gsl_sf_bessel_zero_Jnu(double nu, unsigned int s);
__END_DECLS
#endif /* __GSL_SF_BESSEL_H__ */
| {
"alphanum_fraction": 0.7158896289,
"avg_line_length": 28.1517857143,
"ext": "h",
"hexsha": "316b56113e1e9d646905135c56f73801fed9d255",
"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_sf_bessel.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_sf_bessel.h",
"max_line_length": 114,
"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_sf_bessel.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": 4590,
"size": 15765
} |
/*
* Copyright (c) 1997-1999 Massachusetts Institute of Technology
*
* 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
*
*/
/* This file was automatically generated --- DO NOT EDIT */
/* Generated on Sun Nov 7 20:43:56 EST 1999 */
#include <fftw-int.h>
#include <fftw.h>
/* Generated by: ./genfft -magic-alignment-check -magic-twiddle-load-all -magic-variables 4 -magic-loopi -real2hc 13 */
/*
* This function contains 76 FP additions, 34 FP multiplications,
* (or, 57 additions, 15 multiplications, 19 fused multiply/add),
* 34 stack variables, and 26 memory accesses
*/
static const fftw_real K083333333 = FFTW_KONST(+0.083333333333333333333333333333333333333333333);
static const fftw_real K075902986 = FFTW_KONST(+0.075902986037193865983102897245103540356428373);
static const fftw_real K251768516 = FFTW_KONST(+0.251768516431883313623436926934233488546674281);
static const fftw_real K503537032 = FFTW_KONST(+0.503537032863766627246873853868466977093348562);
static const fftw_real K113854479 = FFTW_KONST(+0.113854479055790798974654345867655310534642560);
static const fftw_real K265966249 = FFTW_KONST(+0.265966249214837287587521063842185948798330267);
static const fftw_real K387390585 = FFTW_KONST(+0.387390585467617292130675966426762851778775217);
static const fftw_real K300462606 = FFTW_KONST(+0.300462606288665774426601772289207995520941381);
static const fftw_real K258260390 = FFTW_KONST(+0.258260390311744861420450644284508567852516811);
static const fftw_real K132983124 = FFTW_KONST(+0.132983124607418643793760531921092974399165133);
static const fftw_real K2_000000000 = FFTW_KONST(+2.000000000000000000000000000000000000000000000);
static const fftw_real K1_732050807 = FFTW_KONST(+1.732050807568877293527446341505872366942805254);
static const fftw_real K156891391 = FFTW_KONST(+0.156891391051584611046832726756003269660212636);
static const fftw_real K256247671 = FFTW_KONST(+0.256247671582936600958684654061725059144125175);
static const fftw_real K011599105 = FFTW_KONST(+0.011599105605768290721655456654083252189827041);
static const fftw_real K300238635 = FFTW_KONST(+0.300238635966332641462884626667381504676006424);
static const fftw_real K174138601 = FFTW_KONST(+0.174138601152135905005660794929264742616964676);
static const fftw_real K575140729 = FFTW_KONST(+0.575140729474003121368385547455453388461001608);
static const fftw_real K866025403 = FFTW_KONST(+0.866025403784438646763723170752936183471402627);
static const fftw_real K500000000 = FFTW_KONST(+0.500000000000000000000000000000000000000000000);
/*
* Generator Id's :
* $Id: exprdag.ml,v 1.41 1999/05/26 15:44:14 fftw Exp $
* $Id: fft.ml,v 1.43 1999/05/17 19:44:18 fftw Exp $
* $Id: to_c.ml,v 1.25 1999/10/26 21:41:32 stevenj Exp $
*/
void fftw_real2hc_13(const fftw_real *input, fftw_real *real_output, fftw_real *imag_output, int istride, int real_ostride, int imag_ostride)
{
fftw_real tmp65;
fftw_real tmp11;
fftw_real tmp28;
fftw_real tmp37;
fftw_real tmp51;
fftw_real tmp62;
fftw_real tmp22;
fftw_real tmp58;
fftw_real tmp59;
fftw_real tmp66;
fftw_real tmp56;
fftw_real tmp63;
fftw_real tmp35;
fftw_real tmp38;
ASSERT_ALIGNED_DOUBLE;
tmp65 = input[0];
{
fftw_real tmp3;
fftw_real tmp53;
fftw_real tmp21;
fftw_real tmp30;
fftw_real tmp26;
fftw_real tmp16;
fftw_real tmp29;
fftw_real tmp25;
fftw_real tmp6;
fftw_real tmp32;
fftw_real tmp9;
fftw_real tmp33;
fftw_real tmp10;
fftw_real tmp54;
fftw_real tmp1;
fftw_real tmp2;
ASSERT_ALIGNED_DOUBLE;
tmp1 = input[8 * istride];
tmp2 = input[5 * istride];
tmp3 = tmp1 - tmp2;
tmp53 = tmp1 + tmp2;
{
fftw_real tmp17;
fftw_real tmp18;
fftw_real tmp19;
fftw_real tmp20;
ASSERT_ALIGNED_DOUBLE;
tmp17 = input[12 * istride];
tmp18 = input[4 * istride];
tmp19 = input[10 * istride];
tmp20 = tmp18 + tmp19;
tmp21 = tmp17 + tmp20;
tmp30 = tmp17 - (K500000000 * tmp20);
tmp26 = tmp18 - tmp19;
}
{
fftw_real tmp12;
fftw_real tmp13;
fftw_real tmp14;
fftw_real tmp15;
ASSERT_ALIGNED_DOUBLE;
tmp12 = input[istride];
tmp13 = input[3 * istride];
tmp14 = input[9 * istride];
tmp15 = tmp13 + tmp14;
tmp16 = tmp12 + tmp15;
tmp29 = tmp12 - (K500000000 * tmp15);
tmp25 = tmp13 - tmp14;
}
{
fftw_real tmp4;
fftw_real tmp5;
fftw_real tmp7;
fftw_real tmp8;
ASSERT_ALIGNED_DOUBLE;
tmp4 = input[6 * istride];
tmp5 = input[11 * istride];
tmp6 = tmp4 - tmp5;
tmp32 = tmp4 + tmp5;
tmp7 = input[2 * istride];
tmp8 = input[7 * istride];
tmp9 = tmp7 - tmp8;
tmp33 = tmp7 + tmp8;
}
tmp10 = tmp6 + tmp9;
tmp54 = tmp32 + tmp33;
tmp11 = tmp3 - tmp10;
{
fftw_real tmp24;
fftw_real tmp27;
fftw_real tmp49;
fftw_real tmp50;
ASSERT_ALIGNED_DOUBLE;
tmp24 = tmp3 + (K500000000 * tmp10);
tmp27 = K866025403 * (tmp25 + tmp26);
tmp28 = tmp24 - tmp27;
tmp37 = tmp27 + tmp24;
tmp49 = tmp9 - tmp6;
tmp50 = tmp25 - tmp26;
tmp51 = tmp49 - tmp50;
tmp62 = tmp50 + tmp49;
}
tmp22 = tmp16 - tmp21;
tmp58 = tmp16 + tmp21;
tmp59 = tmp53 + tmp54;
tmp66 = tmp58 + tmp59;
{
fftw_real tmp52;
fftw_real tmp55;
fftw_real tmp31;
fftw_real tmp34;
ASSERT_ALIGNED_DOUBLE;
tmp52 = tmp29 + tmp30;
tmp55 = tmp53 - (K500000000 * tmp54);
tmp56 = tmp52 - tmp55;
tmp63 = tmp52 + tmp55;
tmp31 = tmp29 - tmp30;
tmp34 = K866025403 * (tmp32 - tmp33);
tmp35 = tmp31 + tmp34;
tmp38 = tmp31 - tmp34;
}
}
real_output[0] = tmp65 + tmp66;
{
fftw_real tmp23;
fftw_real tmp45;
fftw_real tmp40;
fftw_real tmp48;
fftw_real tmp44;
fftw_real tmp46;
fftw_real tmp41;
fftw_real tmp47;
ASSERT_ALIGNED_DOUBLE;
tmp23 = (K575140729 * tmp11) - (K174138601 * tmp22);
tmp45 = (K575140729 * tmp22) + (K174138601 * tmp11);
{
fftw_real tmp36;
fftw_real tmp39;
fftw_real tmp42;
fftw_real tmp43;
ASSERT_ALIGNED_DOUBLE;
tmp36 = (K300238635 * tmp28) + (K011599105 * tmp35);
tmp39 = (K256247671 * tmp37) + (K156891391 * tmp38);
tmp40 = tmp36 - tmp39;
tmp48 = K1_732050807 * (tmp39 + tmp36);
tmp42 = (K300238635 * tmp35) - (K011599105 * tmp28);
tmp43 = (K156891391 * tmp37) - (K256247671 * tmp38);
tmp44 = K1_732050807 * (tmp42 - tmp43);
tmp46 = tmp43 + tmp42;
}
imag_output[imag_ostride] = tmp23 + (K2_000000000 * tmp40);
tmp41 = tmp23 - tmp40;
imag_output[3 * imag_ostride] = tmp41 - tmp44;
imag_output[4 * imag_ostride] = -(tmp41 + tmp44);
imag_output[5 * imag_ostride] = -(tmp45 + (K2_000000000 * tmp46));
tmp47 = tmp46 - tmp45;
imag_output[2 * imag_ostride] = tmp47 - tmp48;
imag_output[6 * imag_ostride] = tmp48 + tmp47;
}
{
fftw_real tmp61;
fftw_real tmp70;
fftw_real tmp74;
fftw_real tmp76;
fftw_real tmp68;
fftw_real tmp69;
fftw_real tmp57;
fftw_real tmp60;
fftw_real tmp71;
fftw_real tmp75;
ASSERT_ALIGNED_DOUBLE;
tmp57 = (K132983124 * tmp51) + (K258260390 * tmp56);
tmp60 = K300462606 * (tmp58 - tmp59);
tmp61 = (K2_000000000 * tmp57) + tmp60;
tmp70 = tmp60 - tmp57;
{
fftw_real tmp72;
fftw_real tmp73;
fftw_real tmp64;
fftw_real tmp67;
ASSERT_ALIGNED_DOUBLE;
tmp72 = (K387390585 * tmp51) - (K265966249 * tmp56);
tmp73 = (K113854479 * tmp62) - (K503537032 * tmp63);
tmp74 = tmp72 + tmp73;
tmp76 = tmp73 - tmp72;
tmp64 = (K251768516 * tmp62) + (K075902986 * tmp63);
tmp67 = tmp65 - (K083333333 * tmp66);
tmp68 = (K2_000000000 * tmp64) + tmp67;
tmp69 = tmp67 - tmp64;
}
real_output[real_ostride] = tmp61 + tmp68;
real_output[5 * real_ostride] = tmp68 - tmp61;
tmp71 = tmp69 - tmp70;
real_output[2 * real_ostride] = tmp71 - tmp74;
real_output[6 * real_ostride] = tmp74 + tmp71;
tmp75 = tmp70 + tmp69;
real_output[3 * real_ostride] = tmp75 - tmp76;
real_output[4 * real_ostride] = tmp76 + tmp75;
}
}
fftw_codelet_desc fftw_real2hc_13_desc =
{
"fftw_real2hc_13",
(void (*)()) fftw_real2hc_13,
13,
FFTW_FORWARD,
FFTW_REAL2HC,
288,
0,
(const int *) 0,
};
| {
"alphanum_fraction": 0.6665590704,
"avg_line_length": 34.1691176471,
"ext": "c",
"hexsha": "538e149c6167b5523eae4638563d7cffd2dc311d",
"lang": "C",
"max_forks_count": 8,
"max_forks_repo_forks_event_max_datetime": "2022-03-29T02:59:10.000Z",
"max_forks_repo_forks_event_min_datetime": "2017-11-20T07:52:01.000Z",
"max_forks_repo_head_hexsha": "3361d1f18bf529958b78231fdcf139b1c1c1f232",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "albertsgrc/ftdock-opt",
"max_forks_repo_path": "original/lib/fftw-2.1.3/rfftw/frc_13.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "3361d1f18bf529958b78231fdcf139b1c1c1f232",
"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": "albertsgrc/ftdock-opt",
"max_issues_repo_path": "original/lib/fftw-2.1.3/rfftw/frc_13.c",
"max_line_length": 141,
"max_stars_count": 9,
"max_stars_repo_head_hexsha": "3361d1f18bf529958b78231fdcf139b1c1c1f232",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "albertsgrc/ftdock-opt",
"max_stars_repo_path": "original/lib/fftw-2.1.3/rfftw/frc_13.c",
"max_stars_repo_stars_event_max_datetime": "2022-01-08T14:37:24.000Z",
"max_stars_repo_stars_event_min_datetime": "2018-10-03T19:57:47.000Z",
"num_tokens": 3053,
"size": 9294
} |
// --------------------------------------------------------------------------
// OpenMS -- Open-Source Mass Spectrometry
// --------------------------------------------------------------------------
// Copyright The OpenMS Team -- Eberhard Karls University Tuebingen,
// ETH Zurich, and Freie Universitaet Berlin 2002-2013.
//
// This software is released under a three-clause BSD license:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of any author or any participating institution
// may be used to endorse or promote products derived from this software
// without specific prior written permission.
// For a full list of authors, refer to the file AUTHORS.
// --------------------------------------------------------------------------
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL ANY OF THE AUTHORS OR THE CONTRIBUTING
// INSTITUTIONS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
// OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// --------------------------------------------------------------------------
// $Maintainer: Clemens Groepl $
// $Authors: $
// --------------------------------------------------------------------------
#ifndef OPENMS_MATH_STATISTICS_LINEARREGRESSION_H
#define OPENMS_MATH_STATISTICS_LINEARREGRESSION_H
#include <OpenMS/CONCEPT/Types.h>
#include <OpenMS/CONCEPT/Exception.h>
#include <vector>
#include <gsl/gsl_fit.h>
#include <gsl/gsl_statistics.h>
#include <gsl/gsl_cdf.h>
namespace OpenMS
{
namespace Math
{
/**
@brief This class offers functions to perform least-squares fits to a straight line model, \f$ Y(c,x) = c_0 + c_1 x \f$.
It encapsulates the GSL methods for a weighted and an unweighted linear regression.
Next to the intercept with the y-axis and the slope of the fitted line, this class computes the:
- squared pearson coefficient
- value of the t-distribution
- standard deviation of the residuals
- standard error of the slope
- intercept with the x-axis (useful for additive series experiments)
- lower border of confidence interval
- higher border of confidence interval
- chi squared value
- x mean
@ingroup Math
*/
class OPENMS_DLLAPI LinearRegression
{
public:
/// Constructor
LinearRegression() :
intercept_(0),
slope_(0),
x_intercept_(0),
lower_(0),
upper_(0),
t_star_(0),
r_squared_(0),
stand_dev_residuals_(0),
mean_residuals_(0),
stand_error_slope_(0),
chi_squared_(0),
rsd_(0)
{
}
/// Destructor
virtual ~LinearRegression()
{
}
/**
@brief This function computes the best-fit linear regression coefficients \f$ (c_0,c_1) \f$
of the model \f$ Y = c_0 + c_1 X \f$ for the dataset \f$ (x, y) \f$.
The values in x-dimension of the dataset \f$ (x,y) \f$ are given by the iterator range [x_begin,x_end)
and the corresponding y-values start at position y_begin.
For a "x %" Confidence Interval use confidence_interval_P = x/100.
For example the 95% Confidence Interval is supposed to be an interval that has a 95% chance of
containing the true value of the parameter.
@return If an error occurred during the fit.
@exception Exception::UnableToFit is thrown if fitting cannot be performed
*/
template <typename Iterator>
void computeRegression(double confidence_interval_P, Iterator x_begin, Iterator x_end, Iterator y_begin);
/**
@brief This function computes the best-fit linear regression coefficient \f$ (c_0) \f$
of the model \f$ Y = c_1 X \f$ for the dataset \f$ (x, y) \f$.
The values in x-dimension of the dataset \f$ (x,y) \f$ are given by the iterator range [x_begin,x_end)
and the corresponding y-values start at position y_begin.
For a "x %" Confidence Interval use confidence_interval_P = x/100.
For example the 95% Confidence Interval is supposed to be an interval that has a 95% chance of
containing the true value of the parameter.
@return If an error occurred during the fit.
@exception Exception::UnableToFit is thrown if fitting cannot be performed
*/
template <typename Iterator>
void computeRegressionNoIntercept(double confidence_interval_P, Iterator x_begin, Iterator x_end, Iterator y_begin);
/**
@brief This function computes the best-fit linear regression coefficients \f$ (c_0,c_1) \f$
of the model \f$ Y = c_0 + c_1 X \f$ for the weighted dataset \f$ (x, y) \f$.
The values in x-dimension of the dataset \f$ (x, y) \f$ are given by the iterator range [x_begin,x_end)
and the corresponding y-values start at position y_begin. They will be weighted by the
values starting at w_begin.
For a "x %" Confidence Interval use confidence_interval_P = x/100.
For example the 95% Confidence Interval is supposed to be an interval that has a 95% chance of
containing the true value of the parameter.
@return If an error occurred during the fit.
@exception Exception::UnableToFit is thrown if fitting cannot be performed
*/
template <typename Iterator>
void computeRegressionWeighted(double confidence_interval_P, Iterator x_begin, Iterator x_end, Iterator y_begin, Iterator w_begin);
/// Non-mutable access to the y-intercept of the straight line
DoubleReal getIntercept() const;
/// Non-mutable access to the slope of the straight line
DoubleReal getSlope() const;
/// Non-mutable access to the x-intercept of the straight line
DoubleReal getXIntercept() const;
/// Non-mutable access to the lower border of confidence interval
DoubleReal getLower() const;
/// Non-mutable access to the upper border of confidence interval
DoubleReal getUpper() const;
/// Non-mutable access to the value of the t-distribution
DoubleReal getTValue() const;
/// Non-mutable access to the squared pearson coefficient
DoubleReal getRSquared() const;
/// Non-mutable access to the standard deviation of the residuals
DoubleReal getStandDevRes() const;
/// Non-mutable access to the residual mean
DoubleReal getMeanRes() const;
/// Non-mutable access to the standard error of the slope
DoubleReal getStandErrSlope() const;
/// Non-mutable access to the chi squared value
DoubleReal getChiSquared() const;
/// Non-mutable access to relative standard deviation
DoubleReal getRSD() const;
protected:
/// The intercept of the fitted line with the y-axis
double intercept_;
/// The slope of the fitted line
double slope_;
/// The intercept of the fitted line with the x-axis
double x_intercept_;
/// The lower bound of the confidence interval
double lower_;
/// The upper bound of the confidence interval
double upper_;
/// The value of the t-statistic
double t_star_;
/// The squared correlation coefficient (Pearson)
double r_squared_;
/// The standard deviation of the residuals
double stand_dev_residuals_;
/// Mean of residuals
double mean_residuals_;
/// The standard error of the slope
double stand_error_slope_;
/// The value of the Chi Squared statistic
double chi_squared_;
/// the relative standard deviation
double rsd_;
/// Computes the goodness of the fitted regression line
void computeGoodness_(double * X, double * Y, int N, double confidence_interval_P);
/// Copies the distance(x_begin,x_end) elements starting at x_begin and y_begin into the arrays x_array and y_array
template <typename Iterator>
void iteratorRange2Arrays_(Iterator x_begin, Iterator x_end, Iterator y_begin, double * x_array, double * y_array);
/// Copy the distance(x_begin,x_end) elements starting at x_begin, y_begin and w_begin into the arrays x_array, y_array and w_array
template <typename Iterator>
void iteratorRange3Arrays_(Iterator x_begin, Iterator x_end, Iterator y_begin, Iterator w_begin, double * x_array, double * y_array, double * w_array);
private:
/// Not implemented
LinearRegression(const LinearRegression & arg);
/// Not implemented
LinearRegression & operator=(const LinearRegression & arg);
};
template <typename Iterator>
void LinearRegression::computeRegression(double confidence_interval_P, Iterator x_begin, Iterator x_end, Iterator y_begin)
{
int N = int(distance(x_begin, x_end));
double * X = new double[N];
double * Y = new double[N];
iteratorRange2Arrays_(x_begin, x_end, y_begin, X, Y);
double cov00, cov01, cov11;
// Compute the unweighted linear fit.
// Get the intercept and the slope of the regression Y_hat=intercept_+slope_*X
// and the value of Chi squared, the covariances of the intercept and the slope
int error = gsl_fit_linear(X, 1, Y, 1, N, &intercept_, &slope_, &cov00, &cov01, &cov11, &chi_squared_);
if (!error)
{
computeGoodness_(X, Y, N, confidence_interval_P);
}
delete[] X;
delete[] Y;
if (error)
{
throw Exception::UnableToFit(__FILE__, __LINE__, __PRETTY_FUNCTION__, "UnableToFit-LinearRegression", "Could not fit a linear model to the data");
}
}
template <typename Iterator>
void LinearRegression::computeRegressionNoIntercept(double confidence_interval_P, Iterator x_begin, Iterator x_end, Iterator y_begin)
{
int N = int(distance(x_begin, x_end));
double * X = new double[N];
double * Y = new double[N];
iteratorRange2Arrays_(x_begin, x_end, y_begin, X, Y);
double cov;
// Compute the linear fit.
// Get the intercept and the slope of the regression Y_hat=intercept_+slope_*X
// and the value of Chi squared, the covariances of the intercept and the slope
int error = gsl_fit_mul(X, 1, Y, 1, N, &slope_, &cov, &chi_squared_);
intercept_ = 0.0;
if (!error)
{
computeGoodness_(X, Y, N, confidence_interval_P);
}
delete[] X;
delete[] Y;
if (error)
{
throw Exception::UnableToFit(__FILE__, __LINE__, __PRETTY_FUNCTION__, "UnableToFit-LinearRegression", "Could not fit a linear model to the data");
}
}
template <typename Iterator>
void LinearRegression::computeRegressionWeighted(double confidence_interval_P, Iterator x_begin, Iterator x_end, Iterator y_begin, Iterator w_begin)
{
int N = int(distance(x_begin, x_end));
double * X = new double[N];
double * Y = new double[N];
double * W = new double[N];
iteratorRange3Arrays_(x_begin, x_end, y_begin, w_begin, X, Y, W);
double cov00, cov01, cov11;
// Compute the weighted linear fit.
// Get the intercept and the slope of the regression Y_hat=intercept_+slope_*X
// and the value of Chi squared, the covariances of the intercept and the slope
int error = gsl_fit_wlinear(X, 1, W, 1, Y, 1, N, &intercept_, &slope_, &cov00, &cov01, &cov11, &chi_squared_);
if (!error)
{
computeGoodness_(X, Y, N, confidence_interval_P);
}
delete[] X;
delete[] Y;
delete[] W;
if (error)
{
throw Exception::UnableToFit(__FILE__, __LINE__, __PRETTY_FUNCTION__, "UnableToFit-LinearRegression", "Could not fit a linear model to the data");
}
}
template <typename Iterator>
void LinearRegression::iteratorRange2Arrays_(Iterator x_begin, Iterator x_end, Iterator y_begin, double * x_array, double * y_array)
{
int i = 0;
while (x_begin < x_end)
{
x_array[i] = *x_begin;
y_array[i] = *y_begin;
++x_begin;
++y_begin;
++i;
}
}
template <typename Iterator>
void LinearRegression::iteratorRange3Arrays_(Iterator x_begin, Iterator x_end, Iterator y_begin, Iterator w_begin, double * x_array, double * y_array, double * w_array)
{
int i = 0;
while (x_begin < x_end)
{
x_array[i] = *x_begin;
y_array[i] = *y_begin;
w_array[i] = *w_begin;
++x_begin;
++y_begin;
++w_begin;
++i;
}
}
} // namespace Math
} // namespace OpenMS
#endif
| {
"alphanum_fraction": 0.6504983389,
"avg_line_length": 38.5897435897,
"ext": "h",
"hexsha": "4e267d9de9503ed98e129ed9ec16470ede8d1432",
"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": "45455356482ce5ab35e32e445609b291ec78a6d6",
"max_forks_repo_licenses": [
"Zlib",
"Apache-2.0"
],
"max_forks_repo_name": "kreinert/OpenMS",
"max_forks_repo_path": "src/openms/include/OpenMS/MATH/STATISTICS/LinearRegression.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "45455356482ce5ab35e32e445609b291ec78a6d6",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"Zlib",
"Apache-2.0"
],
"max_issues_repo_name": "kreinert/OpenMS",
"max_issues_repo_path": "src/openms/include/OpenMS/MATH/STATISTICS/LinearRegression.h",
"max_line_length": 172,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "45455356482ce5ab35e32e445609b291ec78a6d6",
"max_stars_repo_licenses": [
"Zlib",
"Apache-2.0"
],
"max_stars_repo_name": "kreinert/OpenMS",
"max_stars_repo_path": "src/openms/include/OpenMS/MATH/STATISTICS/LinearRegression.h",
"max_stars_repo_stars_event_max_datetime": "2016-12-09T01:45:03.000Z",
"max_stars_repo_stars_event_min_datetime": "2016-12-09T01:45:03.000Z",
"num_tokens": 3093,
"size": 13545
} |
/* diff/test.c
*
* Copyright (C) 2000 David Morrison
*
* 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 <stdio.h>
#include <math.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_diff.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_test.h>
double
f1 (double x, void *params)
{
return exp (x);
}
double
df1 (double x, void *params)
{
return exp (x);
}
double
f2 (double x, void *params)
{
if (x >= 0.0)
{
return x * sqrt (x);
}
else
{
return 0.0;
}
}
double
df2 (double x, void *params)
{
if (x >= 0.0)
{
return 1.5 * sqrt (x);
}
else
{
return 0.0;
}
}
double
f3 (double x, void *params)
{
if (x != 0.0)
{
return sin (1 / x);
}
else
{
return 0.0;
}
}
double
df3 (double x, void *params)
{
if (x != 0.0)
{
return -cos (1 / x) / (x * x);
}
else
{
return 0.0;
}
}
double
f4 (double x, void *params)
{
return exp (-x * x);
}
double
df4 (double x, void *params)
{
return -2.0 * x * exp (-x * x);
}
double
f5 (double x, void *params)
{
return x * x;
}
double
df5 (double x, void *params)
{
return 2.0 * x;
}
double
f6 (double x, void *params)
{
return 1.0 / x;
}
double
df6 (double x, void *params)
{
return -1.0 / (x * x);
}
typedef int (diff_fn) (const gsl_function * f, double x, double * res, double *abserr);
void
test (diff_fn * diff, gsl_function * f, gsl_function * df, double x,
const char * desc)
{
double result, abserr;
double expected = GSL_FN_EVAL (df, x);
(*diff) (f, x, &result, &abserr);
gsl_test_abs (result, expected, abserr, desc);
gsl_test (fabs(result-expected) > abserr, "%s, valid error estimate", desc);
}
int
main ()
{
gsl_function F1, DF1, F2, DF2, F3, DF3, F4, DF4, F5, DF5, F6, DF6;
F1.function = &f1;
DF1.function = &df1;
F2.function = &f2;
DF2.function = &df2;
F3.function = &f3;
DF3.function = &df3;
F4.function = &f4;
DF4.function = &df4;
F5.function = &f5;
DF5.function = &df5;
F6.function = &f6;
DF6.function = &df6;
test (&gsl_diff_central, &F1, &DF1, 1.0, "exp(x), x=1, central diff");
test (&gsl_diff_forward, &F1, &DF1, 1.0, "exp(x), x=1, forward diff");
test (&gsl_diff_backward, &F1, &DF1, 1.0, "exp(x), x=1, backward diff");
test (&gsl_diff_central, &F2, &DF2, 0.1, "x^(3/2), x=0.1, central diff");
test (&gsl_diff_forward, &F2, &DF2, 0.1, "x^(3/2), x=0.1, forward diff");
test (&gsl_diff_backward, &F2, &DF2, 0.1, "x^(3/2), x=0.1, backward diff");
test (&gsl_diff_central, &F3, &DF3, 0.45, "sin(1/x), x=0.45, central diff");
test (&gsl_diff_forward, &F3, &DF3, 0.45, "sin(1/x), x=0.45, forward diff");
test (&gsl_diff_backward, &F3, &DF3, 0.45, "sin(1/x), x=0.45, backward diff");
test (&gsl_diff_central, &F4, &DF4, 0.5, "exp(-x^2), x=0.5, central diff");
test (&gsl_diff_forward, &F4, &DF4, 0.5, "exp(-x^2), x=0.5, forward diff");
test (&gsl_diff_backward, &F4, &DF4, 0.5, "exp(-x^2), x=0.5, backward diff");
test (&gsl_diff_central, &F5, &DF5, 0.0, "x^2, x=0, central diff");
test (&gsl_diff_forward, &F5, &DF5, 0.0, "x^2, x=0, forward diff");
test (&gsl_diff_backward, &F5, &DF5, 0.0, "x^2, x=0, backward diff");
test (&gsl_diff_central, &F6, &DF6, 10.0, "1/x, x=10, central diff");
test (&gsl_diff_forward, &F6, &DF6, 10.0, "1/x, x=10, forward diff");
test (&gsl_diff_backward, &F6, &DF6, 10.0, "1/x, x=10, backward diff");
exit (gsl_test_summary ());
}
| {
"alphanum_fraction": 0.6061553258,
"avg_line_length": 21.5492227979,
"ext": "c",
"hexsha": "aecfb93e1dfd9758440ac543b6aecc95b1bce2f4",
"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/diff/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/diff/test.c",
"max_line_length": 87,
"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/diff/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": 1545,
"size": 4159
} |
/*
* $Source: /Users/mariko/lib/source/sde_wa/sde_wa_manual/sde_wa_manual_progra
* $Revision: 1.7 $
* $Author: mariko $
* $Date: 2011/11/29 10:48:07 $
*/
#include <stdlib.h> /* for malloc */
#include <stdio.h>
#include <math.h>
#include <gsl/gsl_qrng.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
#include <gsl/gsl_statistics.h>
#include <sde_wa.h>
#include "european_option_blacksholes.h"
#include "mlmc.h"
#define L_MAX 20
int main(void){
enum ALG alg = E_M;
int m_moment = 7; /* Romberg */
int M = 4;
int n;
double x0=1.0;
double K = 1.00;
struct EBS_params ebs_params;
double mu=0.05;
double sigma=0.2;
double T=1.0;
ebs_params.mu=mu;
ebs_params.sigma=sigma;
ebs_params.T=T;
ebs_params.K=K;
MLMC_L **mlmc_est;
{
SDE_WA_SYSTEM *sde;
SDE_WA_SLTN *sl;
SDE_WA_PRICER *pricer;
double sum;
int dNl;
double hl;
double eps=0.0001;
double epss[] = {0.001, 0.0005, 0.0002, 0.0001, 0.00005};
int l;
int L;
int i;
double con;
int converged_flag=0;
int extraporation_flag=0;
sde=alloc_SDE_WA_SYSTEM(1, 1, &ebs_params);
sde->sde_type=STR;
sde->V[0]=ebs_str_V_0;
sde->V[1]=ebs_V_1;
sde->drift_corrector[0]=NULL;
sde->drift_corrector[1]=diff_ebs_V_1; /* for EM */
sde->exp_sV[0]=exp_ebs_sVy_0; /* for NV */
sde->exp_sV[1]=exp_ebs_sVy_1; /* for NV */
sl=alloc_SDE_WA_SLTN(alg, m_moment, sde);
pricer=alloc_SDE_WA_PRICER(sl);
pricer->payoff_function=european_option_blacksholes_call_payoff;
pricer->init_y[0] = x0;
pricer->T = 1.0;
//gsl_qrng *q;
gsl_rng_type *rng_type = (gsl_rng_type *)gsl_rng_default;
gsl_rng *rng = gsl_rng_alloc(rng_type);
if (pricer->gen_unif_rand == NULL) {
/* sobol seq. => seq.dim.<=40*/
// q=gsl_qrng_alloc(gsl_qrng_sobol, n*sde->dim_BM);
// pricer->gen_unif_rand = q;
// pricer->next_rand = gen_unif_rand_number_gsl_quasi;
pricer->gen_unif_rand = rng;
pricer->next_rand = gen_unif_rand_number_gsl_pseudo;
}
mlmc_est = (MLMC_L **)malloc(sizeof(MLMC_L *)*L_MAX);
for (l=0; l<L_MAX; l++) {
mlmc_est[l] = alloc_level_l_estimator();
}
for (l=0; l<=-4; l++) {
L=l;
mlmc_est[L]->N = 4000000;
mlmc_level_l_estimation(pricer, mlmc_est[L], L, M, mlmc_est[L]->N);
mlmc_est[L]->V = mlmc_est[L]->sumV/mlmc_est[L]->N - (mlmc_est[L]->sumY/mlmc_est[L]->N)*(mlmc_est[L]->sumY/mlmc_est[L]->N);
printf("L:%d M:%d\n", L, M);
printf("N:%d, Y:%12e, V:%12.12lf, sumV:%lf\n", mlmc_est[L]->N, mlmc_est[L]->sumY/mlmc_est[L]->N, mlmc_est[L]->V, mlmc_est[L]->sumV);
}
//exit(-1);
for (i=0; i<5; i++) {
L=-1;
eps = epss[i];
for (l=0; l<L_MAX; l++) {
init_level_l_estimator(mlmc_est[l]);
}
converged_flag=0;
printf("eps:%lf \n", eps);
while (!converged_flag) {
L++;
n = (int)pow(M,L);
mlmc_level_l_estimation(pricer, mlmc_est[L], L, M, mlmc_est[L]->N);
printf("N:%d, Y:%lf, sumV:%lf\n", mlmc_est[L]->N, mlmc_est[L]->sumY/mlmc_est[L]->N, mlmc_est[L]->sumV);
//estimate Vl
sum = 0.0;
for (l=0; l<=L; l++) {
mlmc_est[l]->V = mlmc_est[l]->sumV/mlmc_est[l]->N -
(mlmc_est[l]->sumY/mlmc_est[l]->N)*(mlmc_est[l]->sumY/mlmc_est[l]->N);
hl = 1.0/pow(M,l);
sum += sqrt(mlmc_est[l]->V/hl);
}
//define optimal Nl
for (l=0; l<=L; l++) {
mlmc_est[l]->newN = ceil(2.0 * sqrt(mlmc_est[l]->V * hl) * sum / (eps * eps));
printf("newN[%d]:%d\n", l, mlmc_est[l]->newN);
}
//update sample sum
for (l=0; l<=L; l++) {
dNl = mlmc_est[l]->newN - mlmc_est[l]->N;
printf("dN[%d]:%d\n", l, dNl);
if (dNl > 0) {
mlmc_est[l]->N += dNl;
mlmc_level_l_estimation(pricer, mlmc_est[l], l, M, dNl);
}
}
//test for convergence
if (extraporation_flag) {
if (L > 1) {
con = mlmc_est[L]->sumY/mlmc_est[L]->N - (1.0/(double)n) * mlmc_est[L-1]->sumY/mlmc_est[L-1]->N;
if (fabs(con) < 1.0*(M*M - 1.0)*eps/sqrt(2.0)) {
converged_flag = 1;
}
}
} else {
if (L > 1) {
con = fmax(fabs(mlmc_est[L]->sumY/mlmc_est[L]->N), fabs(mlmc_est[L-1]->sumY/mlmc_est[L-1]->N/M));
if (con < (M-1)*eps/sqrt(2.0)) {
converged_flag = 1;
}
}
}
printf("N:%d, Y:%lf, V:%12.12lf, sumV:%lf\n", mlmc_est[L]->N, mlmc_est[L]->sumY/mlmc_est[L]->N, mlmc_est[L]->V, mlmc_est[L]->sumV);
printf("L:%d, con:%lf, test:%lf \n\n", L, con, (M-1)*eps/sqrt(2.0));
}
sum=0.0;
for (l=0; l<=L; l++) {
sum += mlmc_est[l]->sumY / mlmc_est[l]->N;
}
if (extraporation_flag) {
sum += mlmc_est[L]->sumY/mlmc_est[L]->N/(M-1);
}
printf("P:%.12e\n\n", sum);
}
for (l=0; l<L_MAX; l++) {
free(mlmc_est[l]);
}
free_SDE_WA_PRICER(pricer);
free_SDE_WA_SLTN(sl);
free_SDE_WA_SYSTEM(sde);
}
return SDE_WA_SUCCESS;
}
/**
* MLMC_L allocation
*/
MLMC_L *alloc_level_l_estimator(void) {
MLMC_L *mlmc_l;
mlmc_l = (MLMC_L *)malloc(sizeof(MLMC_L));
mlmc_l->sumY = 0.0;
mlmc_l->sumV = 0.0;
mlmc_l->V = 0.0;
mlmc_l->N = 10000;
mlmc_l->newN = 0;
return mlmc_l;
}
void init_level_l_estimator(MLMC_L *mlmc_l) {
mlmc_l->sumY = 0.0;
mlmc_l->sumV = 0.0;
mlmc_l->V = 0.0;
mlmc_l->N = 10000;
mlmc_l->newN = 0;
}
void gen_unif_rand_number_gsl_pseudo(void *gen, double *rand, int n) {
gsl_rng *rng = gen;
int j=0;
for (j=0; j<n; j++) {
rand[j] = gsl_rng_uniform(rng);
}
}
void gen_unif_rand_number_gsl_quasi(void *gen, double *rand, int n) {
gsl_qrng *q = gen;
gsl_qrng_get(q, rand);
}
/**
* transform uniform random number to normal random number.
* transform uniform random number to normal random number.
* @param unif_rand n dimension uniform random number.
* @param normal_rand n dimension normal random number.
* @param n dimension of randm number. n must be even number.
* @return transformed noraml random number
*/
void trans_rand_unif_to_normal(double *unif_rand, double *normal_rand, int n) {
int i;
double *u_seq1, *u_seq2;
double *n_seq1, *n_seq2;
if ((n % 2) != 0) {
printf("%d error\n", n);
return;
}
u_seq1 = unif_rand;
u_seq2 = u_seq1 + n/2;
n_seq1 = normal_rand;
n_seq2 = n_seq1 + n/2;
for (i=0; i<n/2; i++) {
n_seq1[i] = sqrt(-2.0*log(u_seq1[i]))*cos(2.0*M_PIl*u_seq2[i]);
n_seq2[i] = sqrt(-2.0*log(u_seq1[i]))*sin(2.0*M_PIl*u_seq2[i]);
}
}
/**
* level l estimaton
* level l esitmator for MLMC
* @param sl
* @param sde
* @param l level
* @param M base of number of partitions
* @param N num of samles for level l estimation
* @return estimated expectation
*/
int mlmc_level_l_estimation(SDE_WA_PRICER *pricer, MLMC_L *estimator, int l, int M, int N) {
SDE_WA_SLTN *sl = pricer->sltn;
SDE_WA_SYSTEM *sde = sl->sde;
int i,j,k,m;
double sum=0.0;
int n = pow(M, l);
double dt1, dt2;
double *u_seq;
double *n_seq;
double *sp, *sp2;
double *tmp_pt;
double tmp;
double **xf;
double **xc;
u_seq=(double *)malloc(sizeof(double)*n*sde->dim_BM);
n_seq=(double *)malloc(sizeof(double)*n*sde->dim_BM);
xf=(double **)malloc(sizeof(double *)*2);
for (i=0; i<2; i++) xf[i]=(double *)malloc(sizeof(double)*sde->dim_y);
xc=(double **)malloc(sizeof(double *)*2);
for (i=0; i<2; i++) xc[i]=(double *)malloc(sizeof(double)*sde->dim_y);
if (l == 0) {
sp=(double *)malloc(sizeof(double)*sde->dim_BM*2);
sp2=(double *)malloc(sizeof(double)*sde->dim_BM*2);
for (sum=0.0, i=0; i < N; i++){
for (j=0; j<sde->dim_y; j++) {
xf[0][j] = pricer->init_y[j];
}
pricer->next_rand(pricer->gen_unif_rand, sp2, sde->dim_BM*2);
trans_rand_unif_to_normal(sp2, sp, sde->dim_BM*2);
next_SDE_WA(sl, pricer->T, xf[0], xf[1], sp);
tmp_pt=xf[0];
xf[0]=xf[1];
xf[1]=tmp_pt;
estimator->sumY += pricer->payoff_function(xf[0], sde->params);
estimator->sumV += pricer->payoff_function(xf[0], sde->params) * pricer->payoff_function(xf[0], sde->params);
} /* for i */
} else {
sp=(double *)malloc(sizeof(double)*sde->dim_BM);
sp2=(double *)malloc(sizeof(double)*sde->dim_BM);
dt1=pricer->T/(double)n;
dt2=M/(double)n;
for (sum=0.0, i=0; i < N; i++){
pricer->next_rand(pricer->gen_unif_rand, u_seq, n*sde->dim_BM);
trans_rand_unif_to_normal(u_seq, n_seq, n*sde->dim_BM);
for (j=0; j<sde->dim_y; j++) {
xf[0][j] = pricer->init_y[j];
xc[0][j] = pricer->init_y[j];
}
for (k=0; k<n/M; k++){
for (m=0; m<sde->dim_BM; m++) {
sp2[m] = 0.0;
}
for (j=0; j<M; j++){
for (m=0; m<sde->dim_BM; m++) {
sp[m] = n_seq[k*M + m + sde->dim_BM*j];
sp2[m] += sp[m];
}
next_SDE_WA(sl, dt1, xf[0], xf[1], sp);
tmp_pt=xf[0];
xf[0]=xf[1];
xf[1]=tmp_pt;
}
for (m=0; m<sde->dim_BM; m++) {
sp2[m] = sp2[m]/sqrt(M);
}
next_SDE_WA(sl, dt2, xc[0], xc[1], sp2);
tmp_pt=xc[0];
xc[0]=xc[1];
xc[1]=tmp_pt;
}
tmp = pricer->payoff_function(xf[0], sde->params) - pricer->payoff_function(xc[0], sde->params);
estimator->sumY += tmp;
estimator->sumV += tmp*tmp;
} /* for i */
}
return sum;
}
| {
"alphanum_fraction": 0.6032974428,
"avg_line_length": 26.3008849558,
"ext": "c",
"hexsha": "6fc2f9e764417eaf07f5e4c884fab39889f94f33",
"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": "9b3d348812229b616df451dd46de0c8b928bb791",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "i05nagai/SDEWeakApproximationMLMCSamples",
"max_forks_repo_path": "european_option_blackscholes_mlmc/src/european_option_blacksholes_main_em_mlmc.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "9b3d348812229b616df451dd46de0c8b928bb791",
"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": "i05nagai/SDEWeakApproximationMLMCSamples",
"max_issues_repo_path": "european_option_blackscholes_mlmc/src/european_option_blacksholes_main_em_mlmc.c",
"max_line_length": 135,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "9b3d348812229b616df451dd46de0c8b928bb791",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "i05nagai/SDEWeakApproximationMLMCSamples",
"max_stars_repo_path": "european_option_blackscholes_mlmc/src/european_option_blacksholes_main_em_mlmc.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 3556,
"size": 8916
} |
/**
@file
Copyright John Reid 2007
*/
#ifndef MYRRH_MATH_H_
#define MYRRH_MATH_H_
#ifdef _MSC_VER
# pragma once
#endif //_MSC_VER
#include "myrrh/defs.h"
#include <boost/iterator.hpp>
#include <boost/range.hpp>
#include <boost/tuple/tuple.hpp>
#include <boost/foreach.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/math/special_functions/fpclassify.hpp>
#include <gsl/gsl_sf_log.h>
#include <gsl/gsl_sf_exp.h>
#include <gsl/gsl_sf_gamma.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_machine.h>
#include <numeric>
#include <iostream>
#include <stdexcept>
#include <vector>
#include <math.h>
#include <boost/version.hpp>
#include <boost/test/floating_point_comparison.hpp>
#if BOOST_VERSION < 104400
# define MYRRH_FPC_NS ::boost::test_tools ///< Floating point comparison namespace
#elif BOOST_VERSION < 104500
# define MYRRH_FPC_NS ::boost::math::fpc ///< Floating point comparison namespace
#elif BOOST_VERSION < 104600
# define MYRRH_FPC_NS ::boost::test_tools ///< Floating point comparison namespace
#elif BOOST_VERSION < 104900
# define MYRRH_FPC_NS ::boost::math::fpc ///< Floating point comparison namespace
#elif BOOST_VERSION >= 105900
# include <boost/test/tools/old/impl.hpp>
# include <boost/test/tools/floating_point_comparison.hpp>
# define MYRRH_FPC_NS ::boost::math::fpc ///< Floating point comparison namespace
#else
# define MYRRH_FPC_NS ::boost::test_tools ///< Floating point comparison namespace
#endif
#ifdef _MSC_VER
# define MYRRH_ISNAN( x ) _isnan( x )
# define MYRRH_ISFINITE( x ) _finite( x )
#else
# define MYRRH_ISNAN( x ) ::boost::math::isnan( x )
# define MYRRH_ISFINITE( x ) ::boost::math::isfinite( x )
#endif
#ifdef max
#undef max
#endif //max
#ifdef min
#undef min
#endif //min
namespace myrrh {
template< typename T >
T int_power( T x, unsigned exponent )
{
T result = T( 1.0 );
for( unsigned i = 0; exponent != i; ++i ) result *= x;
return result;
}
inline
int
nearest_integer( double a )
{
return static_cast<int>( a < 0.0 ? a - 0.5 : a + 0.5 );
}
inline bool within_closed_range( double x, double lower, double higher )
{
return MYRRH_ISFINITE( x ) && lower <= x && x <= higher;
}
inline bool is_probability( double x )
{
return within_closed_range( x, 0.0, 1.0 );
}
template< typename T >
bool
is_close( T t1, T t2, T percent_tolerance )
{
return boost::test_tools::check_is_close( t1, t2, MYRRH_FPC_NS::percent_tolerance( percent_tolerance ) );
}
inline
double
safe_exp( double x )
{
return ( x <= GSL_LOG_DBL_MIN ) ? 0.0 : gsl_sf_exp( x );
}
inline
double
safe_log( double x )
{
if( 0.0 == x ) return - std::numeric_limits< double >::max();
if( 0.0 > x ) return std::numeric_limits< double >::quiet_NaN();
return gsl_sf_log( x );
}
/**
Returns the log of the sum of 2 values, when the values are passed as their logarithms.
I.e. we have log(p) and log(q), we want to calculate log(p+q).
*/
inline
double
log_sum_of_logs(
double log_p,
double log_q )
{
//make sure log_p is the larger of the two, so that exp( log(q) - log(p) ) is small
if( log_q > log_p ) std::swap( log_q, log_p );
BOOST_ASSERT( log_p >= log_q );
return log_p + gsl_sf_log_1plusx( safe_exp( log_q - log_p ) );
}
/** Ensures that the sum of the elements in the range adds to the given value. Returns the scale factor used. */
template< typename Range >
double
scale(
Range & range,
typename boost::range_value< Range >::type desired_sum = 1.0 )
{
using boost::begin;
using boost::end;
using boost::range_value;
typedef typename range_value< Range >::type value_type;
const value_type current_sum =
std::accumulate(
begin( range ),
end( range ),
0.0 );
const double scale_factor = desired_sum / current_sum;
BOOST_FOREACH( value_type & v, range ) v *= scale_factor;
return scale_factor;
}
namespace gsl {
namespace impl {
inline
void
error_handler(
const char * reason,
const char * file,
int line,
int gsl_errno)
{
using namespace std;
const string msg = MYRRH_MAKE_STRING( "GSL error(" << gsl_errno << "): " << file << "(" << line << "): " << reason );
//cout << msg << endl;
throw logic_error( msg );
}
} //namespace impl
inline
void init()
{
static bool inited = false;
if( ! inited )
{
gsl_set_error_handler( impl::error_handler );
inited = true;
}
}
inline
gsl_rng *
get_rng()
{
static const gsl_rng_type * T = 0;
static gsl_rng * r = 0;
if( 0 == T || 0 == r )
{
init();
gsl_rng_env_setup();
T = gsl_rng_default;
if( ! T ) throw std::logic_error( "Could not find default GSL random number generator type" );
r = gsl_rng_alloc( T );
if( ! r ) throw std::logic_error( "Could not allocate GSL random number generator" );
}
return r;
}
template< typename Range >
unsigned
one_sample_from_multinomial(
const Range & dist,
double weight = 1.0,
gsl_rng * rng = gsl::get_rng() )
{
double uniform_sample = gsl_rng_uniform( rng ) * weight;
unsigned result = 0;
BOOST_FOREACH( double p, dist )
{
uniform_sample -= p;
if( uniform_sample < 0.0 ) return result;
++result;
}
throw std::logic_error( "Multinomial parameters did not sum to 1 (or the supplied weight)" );
}
template<
typename ParameterRange,
typename OutputRange
>
void
draw_from_dirichlet(
const ParameterRange & alpha,
OutputRange & output,
gsl_rng * rng = gsl::get_rng() )
{
using boost::size;
using boost::begin;
BOOST_ASSERT( size( alpha ) == size( output ) );
gsl_ran_dirichlet(
rng,
size( alpha ),
&*boost::begin( alpha ),
&*boost::begin( output ) );
}
template<
typename ParameterRange,
typename ValueRange
>
double
dirichlet_ln_pdf(
const ParameterRange & alpha,
const ValueRange & values )
{
using namespace boost;
typedef typename range_value< ParameterRange >::type param_t;
typedef typename range_value< ValueRange >::type value_t;
typedef boost::tuple< param_t, value_t > tuple;
BOOST_ASSERT( size( alpha ) == size( values ) );
double result = 0.0;
param_t alpha_sum = 0.0;
BOOST_FOREACH(
const tuple & t,
make_iterator_range(
make_zip_iterator(
make_tuple(
const_begin( alpha ),
const_begin( values ) ) ),
make_zip_iterator(
make_tuple(
const_end( alpha ),
const_end( values )) ) ) )
{
const param_t a = t.get< 0 >();
const value_t v = t.get< 1 >();
alpha_sum += a;
result += ( a - param_t( 1.0 ) ) * gsl_sf_log( v );
std::cout << a << "\n";
result -= gsl_sf_lngamma( a );
}
return result + gsl_sf_lngamma( alpha_sum );
}
/**
Pre-processed sampling from general discrete distributions.
See http://www.gnu.org/software/gsl/manual/html_node/General-Discrete-Distributions.html
*/
struct ran_discrete : boost::noncopyable
{
typedef boost::shared_ptr< ran_discrete > ptr;
gsl_ran_discrete_t * _pre_processed;
inline ran_discrete(size_t K, const double * P)
: _pre_processed( gsl_ran_discrete_preproc( K, P ) )
{
}
template< typename Range >
ran_discrete( const Range & P_range )
{
using namespace boost;
const size_t K = size( P_range );
std::vector< double > P( K );
std::copy( begin( P_range ), end( P_range ), P.begin() );
_pre_processed = gsl_ran_discrete_preproc( K, &(*(P.begin())) );
}
inline ~ran_discrete()
{
gsl_ran_discrete_free( _pre_processed );
}
size_t sample(gsl_rng * rng = get_rng()) const
{
return gsl_ran_discrete( rng, _pre_processed );
}
};
} //namespace gsl
} //namespace myrrh
#endif //MYRRH_MATH_H_
| {
"alphanum_fraction": 0.6405025501,
"avg_line_length": 22.0851648352,
"ext": "h",
"hexsha": "54cd347e3b2db1f2e377299448db8550d2f7ae3a",
"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": "09dc97c739232c03493e2344e64735b30eea5f99",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "JohnReid/myrrh",
"max_forks_repo_path": "myrrh/math.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "09dc97c739232c03493e2344e64735b30eea5f99",
"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": "JohnReid/myrrh",
"max_issues_repo_path": "myrrh/math.h",
"max_line_length": 121,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "09dc97c739232c03493e2344e64735b30eea5f99",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "JohnReid/myrrh",
"max_stars_repo_path": "myrrh/math.h",
"max_stars_repo_stars_event_max_datetime": "2015-06-04T00:39:51.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-06-04T00:39:51.000Z",
"num_tokens": 2139,
"size": 8039
} |
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <float.h>
#include <math.h>
#include <time.h>
#include <sys/time.h>
#include <cblas.h>
/* Your function must have the following signature: */
void sgemm( int m, int n, float *A, float *C );
/* The benchmarking program */
int main( int argc, char **argv )
{
srand(time(NULL));
int n;
double sum= 0;
for(n = 32; n < 101; n+=54)
/* Try different m */
for( int m = 1000; m <10001; m+=511 )
{
/* Allocate and fill 2 random matrices A, C */
float *A = (float*) malloc( m * n * sizeof(float) );
float *C = (float*) malloc( m * m * sizeof(float) );
for( int i = 0; i < m*n; i++ ) A[i] = 2 * drand48() - 1;
for( int i = 0; i < m*m; i++ ) C[i] = 2 * drand48() - 1;
/* measure Gflop/s rate; time a sufficiently long sequence of calls to eliminate noise */
double Gflop_s, seconds = -1.0;
for( int n_iterations = 1; seconds < 0.1; n_iterations *= 2 )
{
/* warm-up */
sgemm( m, n, A, C );
/* measure time */
struct timeval start, end;
gettimeofday( &start, NULL );
for( int i = 0; i < n_iterations; i++ )
sgemm( m,n, A, C );
gettimeofday( &end, NULL );
seconds = (end.tv_sec - start.tv_sec) + 1.0e-6 * (end.tv_usec - start.tv_usec);
/* compute Gflop/s rate */
Gflop_s = 2e-9 * n_iterations * m * m * n / seconds;
}
sum += Gflop_s;
printf( "%d by %d matrix \t %g Gflop/s\n", m, n, Gflop_s );
//printf( "%g\n", Gflop_s );
/* Ensure that error does not exceed the theoretical error bound */
/* Set initial C to 0 and do matrix multiply of A*B */
memset( C, 0, sizeof( float ) * m * m );
sgemm( m,n, A, C );
/* Subtract A*B from C using standard sgemm (note that this should be 0 to within machine roundoff) */
cblas_sgemm( CblasColMajor,CblasNoTrans,CblasTrans, m,m,n, -1, A,m, A,m, 1, C,m );
/* Subtract the maximum allowed roundoff from each element of C */
for( int i = 0; i < m*n; i++ ) A[i] = fabs( A[i] );
for( int i = 0; i < m*m; i++ ) C[i] = fabs( C[i] );
cblas_sgemm( CblasColMajor,CblasNoTrans,CblasTrans, m,m,n, -3.0*FLT_EPSILON*n, A,m, A,m, 1, C,m );
/* After this test if any element in C is still positive something went wrong in square_sgemm */
for( int i = 0; i < m * m; i++ )
if( C[i] > 0 ) {
printf( "FAILURE: error in matrix multiply exceeds an acceptable margin\n" );
return -1;
}
/* release memory */
free( C );
free( A );
}
return 0;
}
| {
"alphanum_fraction": 0.5670588235,
"avg_line_length": 30.3571428571,
"ext": "c",
"hexsha": "70bda94afb01266eb8740a2902c000eab5c13fad",
"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": "4c3e75f48bdafa02fabb551beb6ebf2fea871238",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "jasonaibrahim/AcademicWorks",
"max_forks_repo_path": "MatrixMultiply/benchmark.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "4c3e75f48bdafa02fabb551beb6ebf2fea871238",
"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": "jasonaibrahim/AcademicWorks",
"max_issues_repo_path": "MatrixMultiply/benchmark.c",
"max_line_length": 106,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "4c3e75f48bdafa02fabb551beb6ebf2fea871238",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "jasonaibrahim/AcademicWorks",
"max_stars_repo_path": "MatrixMultiply/benchmark.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 841,
"size": 2550
} |
#pragma once
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_vector.h>
size_t nn_utils_sizeof_gsl_matrix(void);
size_t nn_utils_sizeof_gsl_vector(void);
| {
"alphanum_fraction": 0.8104575163,
"avg_line_length": 19.125,
"ext": "h",
"hexsha": "ae1d3fd390e2f4d0e6f2477ea42bd417aba0320a",
"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": "250995db0e9d555cc51dfda2f0ee6720c15fc4c4",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "mygulamali/neural-net",
"max_forks_repo_path": "include/nn_utils.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "250995db0e9d555cc51dfda2f0ee6720c15fc4c4",
"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": "mygulamali/neural-net",
"max_issues_repo_path": "include/nn_utils.h",
"max_line_length": 40,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "250995db0e9d555cc51dfda2f0ee6720c15fc4c4",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "mygulamali/neural-net",
"max_stars_repo_path": "include/nn_utils.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 43,
"size": 153
} |
#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>
// functions particular to bh_clean.cpp
/* Time as a function of scale factor in seconds */
// integrand
double timeofa_int(double ap, void * params) {
double integrand = 1./(ap*hubble(om,orad,ap));
return integrand;
}
double timeofa(double a){
gsl_integration_workspace * w = gsl_integration_workspace_alloc (1000);
double result, error;
gsl_function F;
F.function = &timeofa_int;
gsl_integration_qags (&F, ai, a, 0, 1e-7, 1000, w, &result, &error);
gsl_integration_workspace_free (w);
return result;
}
/* scale factor as a function of time */
// fill array to then spline
void aoftime(arrays_T xxyy){
for(int i=0; i<1001; i++){
double a = ai*exp(i*log(0.9999/ai)/(1000.));
(*xxyy).xx[i] = timeofa(a);
(*xxyy).yy[i] = a;
}
// set final time
(*xxyy).xx[1001] = 1./hubble(om,orad,1.);
(*xxyy).yy[1001] = 1.;
}
/* Log10[Mass] as a function of scale factor -- not a step function*/
// M = 10^lgm , a is the scale factor , rem= false for no planck mass remnants
double bhmasslg(double lgm, double a, bool rem){
// If M_i^3 <= 3 K M_p^4 t then the black hole should have 0 mass ---> Log10[M_i] <= 1/3 (Log10[ 3 K M_p^4] + Log10[t]) = 1/3 ( 17.803 + Log10[t])
double logdect = 1./3. * (17.803 + log10(timeofa(a)));
if (lgm>logdect) {
return log10(pow(pow(10., lgm*3.) - decfac*timeofa(a), 1.0/3.));
}
else{
if (!rem) {
return -100.;
}
else{
return lgmp;
}
}
}
// Initial mass from final mass. Any bh that has decayed completely earlier than a will be mapped to decfac*timeofa(a)^(1/3)
// (There's no way of knowing with certainty what its initial mass is if its final mass is 0)
double bhmasslgi(double lgm, double a, bool rem){
double logdect = 1./3. * (17.803 + log10(timeofa(a)));
double mymasslg = log10(pow(10., lgm*3.) + decfac*timeofa(a))/3.;
if(lgm<logdect ){
return -100;
}
else if(mymasslg>lgmax){
return -100;
}
else{
return mymasslg;
}
}
/* Calculate normalisation for psibroad */
// normalisation integrand --- see equation 3.4 for example
// Params are peak mass (as proxy for M_s)
// Normalisation = 1/ Integrate[ 10^psilg dM ] = 1/ Integrate[ 10^(psilg + lgm) x Ln[10] dlgm ]
double normlg_int(double lgm, void * params) {
myparam_type pars = *(myparam_type *)(params);
double peakm = pars.peakm;
double expt = lgm + psibroadlg(lgm,peakm);
double integrand =pow(10.,expt);
return integrand;
}
// Normalisation = 10^normlg
double normlg(double peakm){
struct myparam_type pars = {peakm, 1., ai, false};
gsl_integration_workspace * w = gsl_integration_workspace_alloc (1000);
double result, error;
gsl_function F;
F.function = &normlg_int;
F.params = &pars;
gsl_integration_qags (&F, lgmp, lgmax, 0., 1e-5, 1000, w, &result, &error);
gsl_integration_workspace_free (w);
return log10(1./(log(10.)*result));
}
/* Calculate normalisation for psi_mono */
// normalisation integrand --- see equation 3.4 for example
// Params are peak mass
// Normalisation = 1/ Integrate[ 10^psilg dM ] = 1/ Integrate[ 10^(psilg + lgm) x Ln[10] dlgm ]
double normlg_int_mono(double lgm, void * params) {
myparam_type pars = *(myparam_type *)(params);
double peakm = pars.peakm;
double expt = lgm + psilowlg(lgm,peakm);
double integrand =pow(10.,expt);
return integrand;
}
// Normalisation = 10^normlg
double normlg_mono(double peakm){
struct myparam_type pars = {peakm, 1., ai, false};
gsl_integration_workspace * w = gsl_integration_workspace_alloc (1000);
double result, error;
gsl_function F;
F.function = &normlg_int_mono;
F.params = &pars;
gsl_integration_qags (&F, lgmp, lgmax, 0., 1e-5, 1000, w, &result, &error);
gsl_integration_workspace_free (w);
return log10(1./(log(10.)*result));
}
| {
"alphanum_fraction": 0.6756625334,
"avg_line_length": 27.7905405405,
"ext": "h",
"hexsha": "b842c60da4d79307b870ed8c9f8abea54569344a",
"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": "clean.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": "clean.h",
"max_line_length": 149,
"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": "clean.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1349,
"size": 4113
} |
/* The MIT License
Copyright (c) 2013-2015 Genome Research Ltd.
Author: Petr Danecek <pd3@sanger.ac.uk>
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.
*/
#include <stdio.h>
#include <stdlib.h>
#include <getopt.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_multifit_nlin.h>
#include <htslib/vcf.h>
#include <htslib/synced_bcf_reader.h>
#include "bcftools.h"
#include "peakfit.h"
typedef struct
{
int nvals; // all values, including RR,AA peaks
double *xvals; // pointer to args_t.xvals
double *yvals;
int copy_number; // heuristics to skip futile CN1 fits when no het peak is detected
int irr, ira, iaa; // chop off RR and AA peaks
char *chr;
}
dist_t;
typedef struct
{
int ndist, nbins, ra_rr_scaling, smooth;
double *xvals;
dist_t *dist;
char **argv, *output_dir;
double fit_th, peak_symmetry, cn_penalty, min_peak_size, min_fraction;
int argc, plot, verbose, regions_is_file, targets_is_file, include_aa, force_cn;
char *dat_fname, *fname, *regions_list, *targets_list, *sample;
FILE *dat_fp;
}
args_t;
FILE *open_file(char **fname, const char *mode, const char *fmt, ...);
static void init_dist(args_t *args, dist_t *dist, int verbose)
{
// isolate RR and AA peaks and rescale so that they are comparable to hets
int i, irr, iaa, n = dist->nvals;
// smooth the distribution, this is just to find the peaks
double *tmp = (double*) malloc(sizeof(double)*n);
int win = args->smooth ? fabs(args->smooth)*2 + 1 : 7; // must be an odd number
int hwin = win/2;
double avg = tmp[0] = dist->yvals[0];
for (i=1; i<hwin; i++)
{
avg += dist->yvals[2*i-1];
tmp[i] = avg/(2*i+1);
}
avg = 0;
for (i=0; i<n; i++)
{
avg += dist->yvals[i];
if ( i>=win-1 )
{
tmp[i-hwin] = avg/win;
avg -= dist->yvals[i-win+1];
}
}
for (i=n-hwin; i<n; i++)
{
avg -= dist->yvals[i-hwin];
hwin--;
tmp[i] = avg/(2*hwin+1);
avg -= dist->yvals[i-hwin];
}
// find the extremes; first a simple approach: find a gap
for (irr=0,i=0; i<n/2; i++) if ( tmp[i] < tmp[irr] ) irr = i;
for (iaa=n-1,i=n-1; i>=n/2; i--) if ( tmp[i] < tmp[iaa] ) iaa = i;
irr += win*0.5;
iaa += win*0.5;
if ( iaa>=n ) iaa = n-1;
if ( irr>=iaa ) error("FIXME: oops, dist normalization failed for %s: %d vs %d\n", dist->chr,irr,iaa); // we may need to be smarter
if ( args->smooth>0 ) for (i=0; i<n; i++) dist->yvals[i] = tmp[i];
free(tmp);
// clean the data: the AA peak is occasionally not centered at 1.0 but is closer to the center, chop off
int imax_aa = iaa;
for (i=iaa; i<n; i++)
if ( dist->yvals[imax_aa] < dist->yvals[i] ) imax_aa = i;
dist->nvals = imax_aa+1;
if ( iaa>=dist->nvals ) iaa = dist->nvals-1;
// find the maximum and scale the peaks (first draft: no attempt to join the segments smootly)
double max_rr = 0, max_aa = 0, max_ra = 0, srr = 0, saa = 0, sra = 0;
for (i=0; i<irr; i++)
{
srr += dist->yvals[i];
if ( max_rr < dist->yvals[i] ) max_rr = dist->yvals[i];
}
for (i=irr; i<=iaa; i++)
{
sra += dist->yvals[i];
if ( max_ra < dist->yvals[i] ) max_ra = dist->yvals[i];
}
for (i=iaa+1; i<n; i++)
{
saa += dist->yvals[i];
if ( max_aa < dist->yvals[i] ) max_aa = dist->yvals[i];
}
// Does the het peak exist at all? Usually the numbers are as follows:
// 1: cn=0 ra/rr=0.205730 aa/ra=0.674922 nra=7066
// 20: cn=0 ra/rr=0.258019 aa/ra=0.548929 nra=2381
// X: cn=0 ra/rr=0.005976 aa/ra=44.116667 nra=60
// Y: cn=0 ra/rr=0.008316 aa/ra=7.250000 nra=12
// MT: cn=0 ra/rr=0.013699 aa/ra=0.666667 nra=3
if ( !args->ra_rr_scaling ) max_ra = max_aa = max_rr;
if ( !sra || (sra/srr<0.1 && saa/sra>1.0) ) // too few hets, CN1
{
max_ra = max_aa;
dist->copy_number = 1;
}
else if ( sra/srr<0.1 || saa/sra>1.0 )
{
max_ra = max_aa;
dist->copy_number = -1; // unknown copy number
}
if ( max_rr ) for (i=0; i<irr; i++) dist->yvals[i] /= max_rr;
if ( max_ra ) for (i=irr; i<=iaa; i++) dist->yvals[i] /= max_ra;
if ( max_aa ) for (i=iaa+1; i<n; i++) dist->yvals[i] /= max_aa;
dist->irr = irr;
dist->iaa = iaa;
dist->ira = n*0.5;
if ( verbose )
fprintf(stderr,"%s:\t irr,ira,iaa=%.2f,%.2f,%.2f \t cn=%2d \t ra/rr=%f \t aa/ra=%f \t nra=%d\n",
dist->chr, dist->xvals[irr],dist->xvals[dist->ira],dist->xvals[iaa],
dist->copy_number,sra/srr,saa/sra, (int)sra);
}
static void init_data(args_t *args)
{
bcf_srs_t *files = bcf_sr_init();
if ( args->regions_list )
{
if ( bcf_sr_set_regions(files, args->regions_list, args->regions_is_file)<0 )
error("Failed to read the regions: %s\n", args->regions_list);
}
if ( args->targets_list )
{
if ( bcf_sr_set_targets(files, args->targets_list, args->targets_is_file, 0)<0 )
error("Failed to read the targets: %s\n", args->targets_list);
}
if ( !bcf_sr_add_reader(files, args->fname) ) error("Failed to open %s: %s\n", args->fname,bcf_sr_strerror(files->errnum));
bcf_hdr_t *hdr = files->readers[0].header;
if ( !args->sample )
{
if ( bcf_hdr_nsamples(hdr)>1 ) error("Missing the option -s, --sample\n");
args->sample = hdr->samples[0];
}
else if ( bcf_hdr_id2int(hdr,BCF_DT_SAMPLE,args->sample)<0 ) error("No such sample: %s\n", args->sample);
int ret = bcf_hdr_set_samples(hdr, args->sample, 0);
if ( ret<0 ) error("Error setting the sample: %s\n", args->sample);
if ( !bcf_hdr_idinfo_exists(hdr,BCF_HL_FMT,bcf_hdr_id2int(hdr,BCF_DT_ID,"BAF")) )
error("The tag FORMAT/BAF is not present in the VCF: %s\n", args->fname);
int i;
args->xvals = (double*) calloc(args->nbins,sizeof(double));
for (i=0; i<args->nbins; i++) args->xvals[i] = 1.0*i/(args->nbins-1);
// collect BAF distributions for all chromosomes
int idist = -1, nbaf = 0, nprocessed = 0, ntotal = 0, prev_chr = -1;
float *baf = NULL;
while ( bcf_sr_next_line(files) )
{
ntotal++;
bcf1_t *line = bcf_sr_get_line(files,0);
if ( bcf_get_format_float(hdr,line,"BAF",&baf,&nbaf) != 1 ) continue;
if ( bcf_float_is_missing(baf[0]) ) continue;
nprocessed++;
if ( prev_chr==-1 || prev_chr!=line->rid )
{
// new chromosome
idist = args->ndist++;
args->dist = (dist_t*) realloc(args->dist, sizeof(dist_t)*args->ndist);
memset(&args->dist[idist],0,sizeof(dist_t));
args->dist[idist].chr = strdup(bcf_seqname(hdr,line));
args->dist[idist].yvals = (double*) calloc(args->nbins,sizeof(double));
args->dist[idist].xvals = args->xvals;
args->dist[idist].nvals = args->nbins;
prev_chr = line->rid;
}
int bin = baf[0]*(args->nbins-1);
args->dist[idist].yvals[bin]++; // the distribution
}
free(baf);
bcf_sr_destroy(files);
for (idist=0; idist<args->ndist; idist++)
{
#if 0
int j;
for (j=0; j<args->nbins; j++)
{
double x = args->dist[idist].xvals[j];
args->dist[idist].yvals[j] = exp(-(x-0.5)*(x-0.5)/1e-3);
}
#endif
init_dist(args, &args->dist[idist],args->verbose);
}
args->dat_fp = open_file(&args->dat_fname,"w","%s/dist.dat", args->output_dir);
fprintf(args->dat_fp, "# This file was produced by: bcftools polysomy(%s+htslib-%s), the command line was:\n", bcftools_version(),hts_version());
fprintf(args->dat_fp, "# \t bcftools %s ", args->argv[0]);
for (i=1; i<args->argc; i++)
fprintf(args->dat_fp, " %s",args->argv[i]);
fprintf(args->dat_fp,"\n#\n");
fprintf(args->dat_fp,"# DIST\t[2]Chrom\t[3]BAF\t[4]Normalized Count\n");
fprintf(args->dat_fp,"# FIT\t[2]Goodness of Fit\t[3]iFrom\t[4]iTo\t[5]The Fitted Function\n");
fprintf(args->dat_fp,"# CN\t[2]Chrom\t[3]Estimated Copy Number\t[4]Absolute fit deviation\n");
char *fname = NULL;
FILE *fp = open_file(&fname,"w","%s/dist.py", args->output_dir);
//-------- matplotlib script --------------
fprintf(fp,
"#!/usr/bin/env python\n"
"#\n"
"import matplotlib as mpl\n"
"mpl.use('Agg')\n"
"import matplotlib.pyplot as plt\n"
"import csv,sys,argparse\n"
"from math import exp\n"
"\n"
"outdir = '%s'\n"
"\n"
"def read_dat(dat,fit,cn):\n"
" csv.register_dialect('tab', delimiter='\t', quoting=csv.QUOTE_NONE)\n"
" with open(outdir+'/dist.dat', 'rb') as f:\n"
" reader = csv.reader(f, 'tab')\n"
" for row in reader:\n"
" if row[0][0]=='#': continue\n"
" type = row[0]\n"
" chr = row[1]\n"
" if type=='DIST':\n"
" if chr not in dat: dat[chr] = []\n"
" dat[chr].append(row)\n"
" elif type=='FIT':\n"
" if chr not in fit: fit[chr] = []\n"
" fit[chr].append(row)\n"
" elif type=='CN':\n"
" cn[chr] = row[2]\n"
"\n"
"def plot_dist(dat,fit,chr):\n"
" fig, ax = plt.subplots(1, 1, figsize=(7,5))\n"
" ax.plot([x[2] for x in dat[chr]],[x[3] for x in dat[chr]],'k-',label='Distribution')\n"
" if chr in fit:\n"
" for i in range(len(fit[chr])):\n"
" pfit = fit[chr][i]\n"
" exec('def xfit(x): return '+pfit[5])\n"
" istart = int(pfit[3])\n"
" iend = int(pfit[4])+1\n"
" vals = dat[chr][istart:iend]\n"
" args = {}\n"
" if i==0: args = {'label':'Target to Fit'}\n"
" ax.plot([x[2] for x in vals],[x[3] for x in vals],'r-',**args)\n"
" if i==0: args = {'label':'Best Fit'}\n"
" ax.plot([x[2] for x in vals],[xfit(float(x[2])) for x in vals],'g-',**args)\n"
" ax.set_title('BAF distribution, chr'+chr)\n"
" ax.set_xlabel('BAF')\n"
" ax.set_ylabel('Frequency')\n"
" ax.legend(loc='best',prop={'size':7},frameon=False)\n"
" plt.savefig(outdir+'/dist.chr'+chr+'.png')\n"
" plt.close()\n"
"\n"
"def plot_copy_number(cn):\n"
" fig, ax = plt.subplots(1, 1, figsize=(7,5))\n"
" xlabels = sorted(cn.keys())\n"
" xvals = range(len(xlabels))\n"
" yvals = [float(cn[x]) for x in xlabels]\n"
" ax.plot(xvals,yvals,'o',color='red')\n"
" for i in range(len(xvals)):\n"
" if yvals[i]==-1: ax.annotate('?', xy=(xvals[i],0.5),va='center',ha='center',color='red',fontweight='bold')\n"
" ax.tick_params(axis='both', which='major', labelsize=9)\n"
" ax.set_xticks(xvals)\n"
" ax.set_xticklabels(xlabels,rotation=45)\n"
" ax.set_xlim(-1,len(xlabels))\n"
" ax.set_ylim(0,5.0)\n"
" ax.set_yticks([1.0,2.0,3.0,4.0])\n"
" ax.set_xlabel('Chromosome')\n"
" ax.set_ylabel('Copy Number')\n"
" plt.savefig(outdir+'/copy-number.png')\n"
" plt.close()\n"
"\n"
"class myParser(argparse.ArgumentParser):\n"
" def error(self, message):\n"
" self.print_help()\n"
" sys.stderr.write('error: %%s\\n' %% message)\n"
" sys.exit(2)\n"
"\n"
"def main():\n"
" parser = myParser()\n"
" parser.add_argument('-a', '--all', action='store_true', help='Create all plots')\n"
" parser.add_argument('-c', '--copy-number', action='store_true', help='Create copy-number plot')\n"
" parser.add_argument('-d', '--distrib', metavar='CHR', help='Plot BAF distribution of a single chromosome')\n"
" args = parser.parse_args()\n"
" dat = {}; fit = {}; cn = {}\n"
" read_dat(dat,fit,cn)\n"
" if args.distrib!=None:\n"
" plot_dist(dat,fit,args.distrib)\n"
" if args.all:\n"
" for chr in dat: plot_dist(dat,fit,chr)\n"
" plot_copy_number(cn)\n"
" elif args.copy_number:\n"
" plot_copy_number(cn)\n"
" else:\n"
" for chr in dat: plot_dist(dat,fit,chr)\n"
"\n"
"if __name__ == '__main__':\n"
" main()\n",
args->output_dir);
//---------------------------------------
chmod(fname, S_IWUSR|S_IRUSR|S_IRGRP|S_IROTH|S_IXUSR|S_IXGRP|S_IXOTH);
free(fname);
fclose(fp);
}
static void destroy_data(args_t *args)
{
int i;
for (i=0; i<args->ndist; i++)
{
free(args->dist[i].chr);
free(args->dist[i].yvals);
}
free(args->dist);
free(args->xvals);
free(args->dat_fname);
fclose(args->dat_fp);
}
static void save_dist(args_t *args, dist_t *dist)
{
int i;
for (i=0; i<args->nbins; i++)
fprintf(args->dat_fp,"DIST\t%s\t%f\t%f\n",dist->chr,dist->xvals[i],dist->yvals[i]);
}
static void fit_curves(args_t *args)
{
peakfit_t *pkf = peakfit_init();
peakfit_verbose(pkf,args->verbose);
int i, nmc = 50;
for (i=0; i<args->ndist; i++)
{
dist_t *dist = &args->dist[i];
save_dist(args, &args->dist[i]);
if ( dist->copy_number!=0 )
{
fprintf(args->dat_fp,"CN\t%s\t%.2f\n", dist->chr,(float)dist->copy_number);
continue;
}
if ( args->verbose )
fprintf(stderr,"%s:\n", dist->chr);
int nrr_aa = dist->iaa - dist->irr + 1;
int nrr_ra = dist->ira - dist->irr + 1;
int naa_max = dist->nvals - dist->iaa;
double xrr = dist->xvals[dist->irr], *xrr_vals = &dist->xvals[dist->irr], *yrr_vals = &dist->yvals[dist->irr];
double xaa = dist->xvals[dist->iaa], *xaa_vals = &dist->xvals[dist->iaa], *yaa_vals = &dist->yvals[dist->iaa];
double xra = dist->xvals[dist->ira];
double xmax = dist->xvals[dist->nvals-1];
// CN2
double cn2aa_fit = 0, cn2ra_fit, cn2_fit;
char *cn2aa_func = 0, *cn2ra_func;
double cn2aa_params[3] = {1,1,1} ,cn2ra_params[3];
if ( args->include_aa )
{
peakfit_reset(pkf);
peakfit_add_exp(pkf, 1.0,1.0,0.2, 5);
peakfit_set_mc(pkf, 0.01,0.3,2,nmc);
peakfit_set_mc(pkf, 0.05,1.0,0,nmc);
cn2aa_fit = peakfit_run(pkf, naa_max, xaa_vals, yaa_vals);
cn2aa_func = strdup(peakfit_sprint_func(pkf));
peakfit_get_params(pkf,0,cn2aa_params,3);
}
peakfit_reset(pkf);
peakfit_add_bounded_gaussian(pkf, 1.0,0.5,0.03, 0.45,0.55, 7);
peakfit_set_mc(pkf, 0.01,0.3,2,nmc);
peakfit_set_mc(pkf, 0.05,1.0,0,nmc);
cn2ra_fit = peakfit_run(pkf, nrr_aa,xrr_vals,yrr_vals);
cn2ra_func = strdup(peakfit_sprint_func(pkf));
cn2_fit = cn2ra_fit + cn2aa_fit;
peakfit_get_params(pkf,0,cn2ra_params,3);
// CN3: fit two peaks, then enforce the symmetry and fit again
double cn3rra_params[5], cn3raa_params[5], *cn3aa_params = cn2aa_params;
double cn3aa_fit = cn2aa_fit, cn3ra_fit;
char *cn3aa_func = cn2aa_func, *cn3ra_func;
double min_dx3 = 0.5 - 1./(args->min_fraction+2);
peakfit_reset(pkf);
peakfit_add_bounded_gaussian(pkf, 1.0,1/3.,0.03, xrr,xra-min_dx3, 7);
peakfit_set_mc(pkf, xrr,xra-min_dx3, 1,nmc);
peakfit_add_bounded_gaussian(pkf, 1.0,2/3.,0.03, xra+min_dx3,xaa, 7);
peakfit_set_mc(pkf, xra+min_dx3,xaa, 1,nmc);
peakfit_run(pkf, nrr_aa, xrr_vals, yrr_vals);
// force symmetry around x=0.5
peakfit_get_params(pkf,0,cn3rra_params,5);
peakfit_get_params(pkf,1,cn3raa_params,5);
double cn3_dx = (0.5-cn3rra_params[1] + cn3raa_params[1]-0.5)*0.5;
if ( cn3_dx > 0.5/3 ) cn3_dx = 0.5/3; // CN3 peaks should not be separated by more than 1/3
peakfit_reset(pkf);
peakfit_add_gaussian(pkf, cn3rra_params[0],0.5-cn3_dx,cn3rra_params[2], 5);
peakfit_add_gaussian(pkf, cn3raa_params[0],0.5+cn3_dx,cn3raa_params[2], 5);
cn3ra_fit = peakfit_run(pkf, nrr_aa, xrr_vals, yrr_vals);
cn3ra_func = strdup(peakfit_sprint_func(pkf));
// compare peak sizes
peakfit_get_params(pkf,0,cn3rra_params,3);
peakfit_get_params(pkf,1,cn3raa_params,3);
double cn3rra_size = cn3rra_params[0]*cn3rra_params[0];
double cn3raa_size = cn3raa_params[0]*cn3raa_params[0];
double cn3_dy = cn3rra_size > cn3raa_size ? cn3raa_size/cn3rra_size : cn3rra_size/cn3raa_size;
double cn3_frac = (1 - 2*cn3rra_params[1]) / cn3rra_params[1];
double cn3_fit = cn3ra_fit + cn3aa_fit;
// A very reasonable heuristics: check if the peak's width converged, exclude far too broad or far too narrow peaks
if ( cn3rra_params[2]>0.3 || cn3raa_params[2]>0.3 ) cn3_fit = HUGE_VAL;
if ( cn3rra_params[2]<1e-2 || cn3raa_params[2]<1e-2 ) cn3_fit = HUGE_VAL;
// CN4 (contaminations)
// - first fit only the [0,0.5] part of the data, then enforce the symmetry and fit again
// - min_frac=1 (resp. 0.5) is interpreted as 50:50% (rep. 75:25%) contamination
double cn4AAaa_params[3] = {1,1,1} ,cn4AAra_params[3] = {1,1,1}, cn4RAra_params[3], cn4RArr_params[5], cn4RAaa_params[5];
double cn4aa_fit = 0, cn4ra_fit;
char *cn4aa_func = 0, *cn4ra_func;
double min_dx4 = 0.25*args->min_fraction;
if ( args->include_aa )
{
peakfit_reset(pkf);
peakfit_add_exp(pkf, 0.5,1.0,0.2, 5);
peakfit_set_mc(pkf, 0.01,0.3,2,nmc);
peakfit_add_bounded_gaussian(pkf, 0.4,(xaa+xmax)*0.5,2e-2, xaa,xmax, 7);
peakfit_set_mc(pkf, xaa,xmax, 1,nmc);
cn4aa_fit = peakfit_run(pkf, naa_max, xaa_vals,yaa_vals);
cn4aa_func = strdup(peakfit_sprint_func(pkf));
peakfit_get_params(pkf,0,cn4AAaa_params,3);
peakfit_get_params(pkf,1,cn4AAra_params,5);
}
peakfit_reset(pkf);
// first fit only the [0,0.5] part of the data
peakfit_add_gaussian(pkf, 1.0,0.5,0.03, 5);
peakfit_add_bounded_gaussian(pkf, 0.6,0.3,0.03, xrr,xra-min_dx4, 7);
peakfit_set_mc(pkf, xrr,xra-min_dx4,2,nmc);
peakfit_run(pkf, nrr_ra , xrr_vals, yrr_vals);
// now forcet symmetry around x=0.5
peakfit_get_params(pkf,0,cn4RAra_params,3);
peakfit_get_params(pkf,1,cn4RArr_params,5);
double cn4_dx = 0.5-cn4RArr_params[1];
if ( cn4_dx > 0.25 ) cn4_dx = 0.25; // CN4 peaks should not be separated by more than 0.5
peakfit_reset(pkf);
peakfit_add_gaussian(pkf, cn4RAra_params[0],0.5,cn4RAra_params[2], 5);
peakfit_add_gaussian(pkf, cn4RArr_params[0],0.5-cn4_dx,cn4RArr_params[2], 5);
peakfit_add_gaussian(pkf, cn4RArr_params[0],0.5+cn4_dx,cn4RArr_params[2], 5);
peakfit_set_mc(pkf, 0.1,cn4RAra_params[0],0,nmc);
peakfit_set_mc(pkf, 0.01,0.1,2,nmc);
cn4ra_fit = peakfit_run(pkf, nrr_aa , xrr_vals, yrr_vals);
cn4ra_func = strdup(peakfit_sprint_func(pkf));
peakfit_get_params(pkf,0,cn4RAra_params,3);
peakfit_get_params(pkf,1,cn4RArr_params,3);
peakfit_get_params(pkf,2,cn4RAaa_params,3);
double cn4RAra_size = cn4RAra_params[0]==0 ? HUGE_VAL : cn4RAra_params[0]*cn4RAra_params[0];
double cn4RArr_size = cn4RArr_params[0]*cn4RArr_params[0];
double cn4RAaa_size = cn4RAaa_params[0]*cn4RAaa_params[0];
double cn4RArr_dy = cn4RArr_size < cn4RAra_size ? cn4RArr_size/cn4RAra_size : cn4RAra_size/cn4RArr_size;
double cn4RAaa_dy = cn4RAaa_size < cn4RAra_size ? cn4RAaa_size/cn4RAra_size : cn4RAra_size/cn4RAaa_size;
double cn4_dy = cn4RArr_dy < cn4RAaa_dy ? cn4RArr_dy/cn4RAaa_dy : cn4RAaa_dy/cn4RArr_dy;
double cn4_ymin = cn4RArr_size < cn4RAaa_size ? cn4RArr_size/cn4RAra_size : cn4RAaa_size/cn4RAra_size;
cn4_dx = (cn4RAaa_params[1]-0.5) - (0.5-cn4RArr_params[1]);
double cn4_frac = cn4RAaa_params[1] - cn4RArr_params[1];
double cn4_fit = cn4ra_fit + cn4aa_fit;
// A very reasonable heuristics: check if the peak's width converged, exclude far too broad or far too narrow peaks
if ( cn4RAra_params[2]>0.3 || cn4RArr_params[2]>0.3 || cn4RAaa_params[2]>0.3 ) cn4_fit = HUGE_VAL;
if ( cn4RAra_params[2]<1e-2 || cn4RArr_params[2]<1e-2 || cn4RAaa_params[2]<1e-2 ) cn4_fit = HUGE_VAL;
// Choose the best match
char cn2_fail = '*', cn3_fail = '*', cn4_fail = '*';
if ( cn2_fit > args->fit_th ) cn2_fail = 'f';
if ( cn3_fit > args->fit_th ) cn3_fail = 'f';
else if ( cn3_dy < args->peak_symmetry ) cn3_fail = 'y'; // size difference is too big
if ( cn4_fit > args->fit_th ) cn4_fail = 'f';
else if ( cn4_ymin < args->min_peak_size ) cn4_fail = 'y'; // side peak is too small
else if ( cn4_dy < args->peak_symmetry ) cn4_fail = 'Y'; // size difference is too big
else if ( cn4_dx > 0.1 ) cn4_fail = 'x'; // side peaks placed assymetrically
double cn = -1, fit = cn2_fit;
if ( cn2_fail == '*' ) { cn = 2; fit = cn2_fit; }
if ( cn3_fail == '*' )
{
// Use cn_penalty as a tiebreaker. If set to 0.3, cn3_fit must be 30% smaller than cn2_fit.
if ( cn<0 || cn3_fit < (1-args->cn_penalty) * fit )
{
cn = 2 + cn3_frac;
fit = cn3_fit;
if ( cn2_fail=='*' ) cn2_fail = 'p';
}
else cn3_fail = 'p';
}
if ( cn4_fail == '*' )
{
if ( cn<0 || cn4_fit < (1-args->cn_penalty) * fit )
{
cn = 3 + cn4_frac;
fit = cn4_fit;
if ( cn2_fail=='*' ) cn2_fail = 'p';
if ( cn3_fail=='*' ) cn3_fail = 'p';
}
else cn4_fail = 'p';
}
if ( args->verbose )
{
fprintf(stderr,"\tcn2 %c fit=%e\n", cn2_fail, cn2_fit);
fprintf(stderr,"\t .. %e\n", cn2ra_fit);
fprintf(stderr,"\t RA: %f %f %f\n", cn2ra_params[0],cn2ra_params[1],cn2ra_params[2]);
fprintf(stderr,"\t .. %e\n", cn2aa_fit);
fprintf(stderr,"\t AA: %f %f %f\n", cn2aa_params[0],cn2aa_params[1],cn2aa_params[2]);
fprintf(stderr,"\t func:\n");
fprintf(stderr,"\t %s\n", cn2ra_func);
fprintf(stderr,"\t %s\n", cn2aa_func);
fprintf(stderr,"\n");
fprintf(stderr,"\tcn3 %c fit=%e frac=%f symmetry=%f\n", cn3_fail, cn3_fit, cn3_frac, cn3_dy);
fprintf(stderr,"\t .. %e\n", cn3ra_fit);
fprintf(stderr,"\t RRA: %f %f %f\n", cn3rra_params[0],cn3rra_params[1],cn3rra_params[2]);
fprintf(stderr,"\t RAA: %f %f %f\n", cn3raa_params[0],cn3raa_params[1],cn3raa_params[2]);
fprintf(stderr,"\t .. %e\n", cn3aa_fit);
fprintf(stderr,"\t AAA: %f %f %f\n", cn3aa_params[0],cn3aa_params[1],cn3aa_params[2]);
fprintf(stderr,"\t func:\n");
fprintf(stderr,"\t %s\n", cn3ra_func);
fprintf(stderr,"\t %s\n", cn3aa_func);
fprintf(stderr,"\n");
fprintf(stderr,"\tcn4 %c fit=%e frac=%f symmetry=%f ymin=%f\n", cn4_fail, cn4_fit, cn4_frac, cn4_dy, cn4_ymin);
fprintf(stderr,"\t .. %e\n", cn4ra_fit);
fprintf(stderr,"\t RArr: %f %f %f\n", cn4RArr_params[0],cn4RArr_params[1],cn4RArr_params[2]);
fprintf(stderr,"\t RAra: %f %f %f\n", cn4RAra_params[0],cn4RAra_params[1],cn4RAra_params[2]);
fprintf(stderr,"\t RAaa: %f %f %f\n", cn4RAaa_params[0],cn4RAaa_params[1],cn4RAaa_params[2]);
fprintf(stderr,"\t .. %e\n", cn4aa_fit);
fprintf(stderr,"\t AAaa: %f %f %f\n", cn4AAaa_params[0],cn4AAaa_params[1],cn4AAaa_params[2]);
fprintf(stderr,"\t func:\n");
fprintf(stderr,"\t %s\n", cn4ra_func);
fprintf(stderr,"\t %s\n", cn4aa_func);
fprintf(stderr,"\n");
}
if ( args->force_cn==2 || cn2_fail == '*' )
{
fprintf(args->dat_fp,"FIT\t%s\t%e\t%d\t%d\t%s\n", dist->chr,cn2ra_fit,dist->irr,dist->iaa,cn2ra_func);
if ( cn2aa_func ) fprintf(args->dat_fp,"FIT\t%s\t%e\t%d\t%d\t%s\n", dist->chr,cn2aa_fit,dist->iaa,dist->nvals-1,cn2aa_func);
}
if ( args->force_cn==3 || cn3_fail == '*' )
{
fprintf(args->dat_fp,"FIT\t%s\t%e\t%d\t%d\t%s\n", dist->chr,cn3ra_fit,dist->irr,dist->iaa,cn3ra_func);
if ( cn3aa_func ) fprintf(args->dat_fp,"FIT\t%s\t%e\t%d\t%d\t%s\n", dist->chr,cn3aa_fit,dist->iaa,dist->nvals-1,cn3aa_func);
}
if ( args->force_cn==4 || cn4_fail == '*' )
{
fprintf(args->dat_fp,"FIT\t%s\t%e\t%d\t%d\t%s\n", dist->chr,cn4ra_fit,dist->irr,dist->iaa,cn4ra_func);
if ( cn4aa_func ) fprintf(args->dat_fp,"FIT\t%s\t%e\t%d\t%d\t%s\n", dist->chr,cn4aa_fit,dist->iaa,dist->nvals-1,cn4aa_func);
}
fprintf(args->dat_fp,"CN\t%s\t%.2f\t%f\n", dist->chr, cn, fit);
free(cn2aa_func);
free(cn2ra_func);
free(cn3ra_func);
free(cn4ra_func);
free(cn4aa_func);
}
peakfit_destroy(pkf);
}
static void usage(args_t *args)
{
fprintf(stderr, "\n");
fprintf(stderr, "About: Detect number of chromosomal copies from Illumina's B-allele frequency (BAF)\n");
fprintf(stderr, "Usage: bcftools polysomy [OPTIONS] <file.vcf>\n");
fprintf(stderr, "\n");
fprintf(stderr, "General options:\n");
fprintf(stderr, " -o, --output-dir <path> \n");
fprintf(stderr, " -r, --regions <region> restrict to comma-separated list of regions\n");
fprintf(stderr, " -R, --regions-file <file> restrict to regions listed in a file\n");
fprintf(stderr, " -s, --sample <name> sample to analyze\n");
fprintf(stderr, " -t, --targets <region> similar to -r but streams rather than index-jumps\n");
fprintf(stderr, " -T, --targets-file <file> similar to -R but streams rather than index-jumps\n");
fprintf(stderr, " -v, --verbose \n");
fprintf(stderr, "\n");
fprintf(stderr, "Algorithm options:\n");
fprintf(stderr, " -b, --peak-size <float> minimum peak size (0-1, larger is stricter) [0.1]\n");
fprintf(stderr, " -c, --cn-penalty <float> penalty for increasing CN (0-1, larger is stricter) [0.7]\n");
fprintf(stderr, " -f, --fit-th <float> goodness of fit threshold (>0, smaller is stricter) [3.3]\n");
fprintf(stderr, " -i, --include-aa include the AA peak in CN2 and CN3 evaluation\n");
fprintf(stderr, " -m, --min-fraction <float> minimum distinguishable fraction of aberrant cells [0.1]\n");
fprintf(stderr, " -p, --peak-symmetry <float> peak symmetry threshold (0-1, larger is stricter) [0.5]\n");
fprintf(stderr, "\n");
exit(1);
}
int main_polysomy(int argc, char *argv[])
{
args_t *args = (args_t*) calloc(1,sizeof(args_t));
args->argc = argc; args->argv = argv;
args->nbins = 150;
args->fit_th = 3.3;
args->cn_penalty = 0.7;
args->peak_symmetry = 0.5;
args->min_peak_size = 0.1;
args->ra_rr_scaling = 1;
args->min_fraction = 0.1;
args->smooth = -3;
static struct option loptions[] =
{
{"ra-rr-scaling",0,0,1}, // hidden option
{"force-cn",1,0,2}, // hidden option
{"smooth",1,0,'S'}, // hidden option
{"nbins",1,0,'n'}, // hidden option
{"include-aa",0,0,'i'},
{"peak-size",1,0,'b'},
{"min-fraction",1,0,'m'},
{"verbose",0,0,'v'},
{"fit-th",1,0,'f'},
{"cn-penalty",1,0,'c'},
{"peak-symmetry",1,0,'p'},
{"output-dir",1,0,'o'},
{"sample",1,0,'s'},
{"targets",1,0,'t'},
{"targets-file",1,0,'T'},
{"regions",1,0,'r'},
{"regions-file",1,0,'R'},
{0,0,0,0}
};
char c, *tmp;
while ((c = getopt_long(argc, argv, "h?o:vt:T:r:R:s:f:p:c:im:b:n:S:",loptions,NULL)) >= 0)
{
switch (c)
{
case 1 : args->ra_rr_scaling = 0; break;
case 2 : args->force_cn = atoi(optarg); break;
case 'n': args->nbins = atoi(optarg); break;
case 'S': args->smooth = atoi(optarg); break;
case 'i': args->include_aa = 1; break;
case 'b':
args->min_peak_size = strtod(optarg,&tmp);
if ( *tmp ) error("Could not parse: -b %s\n", optarg);
if ( args->min_peak_size<0 || args->min_peak_size>1 ) error("Range error: -b %s\n", optarg);
break;
case 'm':
args->min_fraction = strtod(optarg,&tmp);
if ( *tmp ) error("Could not parse: -n %s\n", optarg);
if ( args->min_fraction<0 || args->min_fraction>1 ) error("Range error: -n %s\n", optarg);
break;
case 'f':
args->fit_th = strtod(optarg,&tmp);
if ( *tmp ) error("Could not parse: -f %s\n", optarg);
break;
case 'p':
args->peak_symmetry = strtod(optarg,&tmp);
if ( *tmp ) error("Could not parse: -p %s\n", optarg);
break;
case 'c':
args->cn_penalty = strtod(optarg,&tmp);
if ( *tmp ) error("Could not parse: -c %s\n", optarg);
break;
case 's': args->sample = optarg; break;
case 't': args->targets_list = optarg; break;
case 'T': args->targets_list = optarg; args->targets_is_file = 1; break;
case 'r': args->regions_list = optarg; break;
case 'R': args->regions_list = optarg; args->regions_is_file = 1; break;
case 'o': args->output_dir = optarg; break;
case 'v': args->verbose++; break;
default: usage(args); break;
}
}
if ( optind>=argc )
{
if ( !isatty(fileno((FILE *)stdin)) ) args->fname = "-";
}
else args->fname = argv[optind];
if ( !args->fname ) usage(args);
if ( !args->output_dir ) error("Missing the -o option\n");
init_data(args);
fit_curves(args);
destroy_data(args);
free(args);
return 0;
}
| {
"alphanum_fraction": 0.5546010753,
"avg_line_length": 43.9104477612,
"ext": "c",
"hexsha": "c5a5394e1119e3eff92972ca4353fd25b4f2808e",
"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": "43948b4ea5db6333633361dd91f7e7b320392fb2",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "SANBI-SA-archive/s_bvc_pipeline",
"max_forks_repo_path": "USAP_H37Rv/Tools/bcftools-1.3/polysomy.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "43948b4ea5db6333633361dd91f7e7b320392fb2",
"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": "SANBI-SA-archive/s_bvc_pipeline",
"max_issues_repo_path": "USAP_H37Rv/Tools/bcftools-1.3/polysomy.c",
"max_line_length": 149,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "43948b4ea5db6333633361dd91f7e7b320392fb2",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "SANBI-SA-archive/s_bvc_pipeline",
"max_stars_repo_path": "USAP_H37Rv/Tools/bcftools-1.3/polysomy.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 10434,
"size": 32362
} |
#ifndef FUSED_LASSO_B_H
#define FUSED_LASSO_B_H
#include "ALM_Katyusha.h"
#include <string>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
#include <stdio.h> /* printf */
#include <time.h>
#include <fstream>
#include <algorithm>
#include <iomanip>
#include <ctime>
#include <math.h>
//This class solves problem: min_{x} sum_i 0.5*(Ax- b)^2+ sum_i |x^i- x^{i+1}|+ P(x) by IPALM_Katyusha
// where P(x)=frac{sig2}{2}|x|_2^2 +sig1|x|_1.
// f^i(x)= 0.5*(x- b_i)^2, h^i(x)= |x|, Mx= (x^1- x^2, ..., x_n- x_1)
template<typename L, typename D>
class Fused_lasso_b: public ALM_Katyusha<L, D>
{
private:
D lambda3;
Matrix<L,D> my_M;
Matrix<L,D> my_A;
D val_lambda_f;
protected:
public:
D sig1;
D sig2;
Fused_lasso_b(const char* Matrix_file, D val_lambda1, D val_lambda2, D val_lambda3)
:ALM_Katyusha<L,D>(),my_A(Matrix_file)
{
my_M.construct_fused_matrix(my_A);
this->matrix_merge(my_M,my_A);
sig1=val_lambda1;
sig2=val_lambda2;
lambda3=val_lambda3;
this->L_h= val_lambda3;
this->mu_g= sig2;
}
L get_n(){return my_A.nfeatures;}
L get_m(){return my_A.nfeatures+ my_A.nsamples;}
inline void set_matrix_A(){
this->data_A= my_A;
}
inline void set_matrix_M(){
this->data_M= my_M;
}
inline D value_of_f_j(D x, L i){
return 0.5*(x- my_A.b[i])*(x- my_A.b[i]);
}
inline D gradient_of_f_j(D x, L i){
return x- my_A.b[i];
}
inline D value_of_f_star_j(D x, L i){
return 0.5*x*x+ my_A.b[i]*x;
}
inline void rescale(){
this->lambda1= sig1;
this->lambda2= sig2+ this->tau_s*this->beta_s;
}
inline D value_of_P_j(D x, L j){
return sig1*fabs(x)+ sig2/2*x*x;
}
inline D prox_of_P_j(D x1, D x2, L j){
if (x1*x2- sig1> 0){
return (x1*x2- sig1)/(sig2+ x2);
}
else if(x1*x2+ sig1< 0){
return (x1*x2+ sig1)/(sig2+ x2);
}
else{
return 0;
}
}
inline D value_of_h_j(D x, L i){
return lambda3*fabs(x);
}
inline D value_of_h_star_j(D x, L j){
if (x<= 2*lambda3 && x>= -2*lambda3){
return 0;
}
else{
cout<< "error in h*(x)"<< endl;
cout<< "lambda3= "<< lambda3<< "; x= "<< x<< endl;
system("pause");
return std::numeric_limits<double>::max();
}
}
inline D compute_one_step(D tau, D u, D x){
D new_x;
if(x>tau*(this->lambda1+u))
new_x=(x-tau*(this->lambda1+u))/(1+this->lambda2*tau);
else if(x<tau*(u-this->lambda1))
new_x=(x-tau*(u-this->lambda1))/(1+this->lambda2*tau);
else
new_x=0;
return new_x;
}
inline D prox_of_h_star_j(D x1, D x2, L j){
if (x1> lambda3){
return lambda3;
}
else if (x1< -lambda3){
return -lambda3;
}
else{
return x1;
}
}
inline D feasible_dual(vector<D> & x){
if(this->lambda2>0)
{
return 1;
}
else
{
D scal=1;
L l=x.size();
for(L i=0;i<l;i++)
if(fabs(x[i])>this->lambda1)
scal=min(this->lambda1/fabs(x[i]),scal);
return scal;
}
}
//We implement Section 6.2 of SPDC paper for 'just-in-time' update
//t0 is t0+1 in the paper SPDC ; x is the z vector in Katyusha
inline void compute_just_in_time_prox_grad_without_x_s(D tau, D u, D &x, L t0,L t1, D w, D &y, L j){
if(t0==t1)
return;
else{
if(this->lambda2>0)
{
D theta=1./(1+this->lambda2*tau);
D hplus=(u+this->lambda1)/this->lambda2;
D hminus=(u-this->lambda1)/this->lambda2;
D p=pow(theta,t1-t0);
if(this->lambda1==0){
y=compute_aid_2(p,theta, hplus, t1-t0, x, y, w);
x=p*(x)-(1-p)*u/this->lambda2;
}else{
if(x==0){
if(this->lambda1+u<0){
y=compute_aid_2(p,theta, hplus, t1-t0, x, y, w);
x=p*x-(1-p)*hplus;
}
else if(u-this->lambda1>0){
y=compute_aid_2(p,theta, hminus, t1-t0, x, y, w);
x=p*x-(1-p)*hminus;
}else{
x=0;
D p2=pow(this->theta3,t1-t0);
D tmp2=(1-p2)/(this->theta1+this->theta2);
y=(this->theta2*w)*tmp2+p2*y;
}
}else if(x>0){
if(this->lambda1+u<=0){
y=compute_aid_2(p,theta, hplus, t1-t0, x, y, w);
x=p*x-(1-p)*hplus;
}else{
D t=t0-log(1+this->lambda2*x/(this->lambda1+u))/log(theta);
if(t<t1){
L t_tmp=floor(t);
p=pow(theta,t_tmp-t0);
y=compute_aid_2(p,theta, hplus, t_tmp-t0, x, y, w);
x=p*x-(1-p)*hplus;
x=compute_one_step(tau,u,x);
y=this->theta1*x+this->theta2*w+this->theta3*y;
compute_just_in_time_prox_grad_without_x_s(tau, u, x, t_tmp+1, t1, w, y, j);
}
else{
y=compute_aid_2(p,theta, hplus, t1-t0, x, y, w);
x=p*x-(1-p)*hplus;
}
}
}else if(x<0){
D minusw=-w;
D minusx=-x;
D minusy=-y;
compute_just_in_time_prox_grad_without_x_s(tau, -u, minusx, t0, t1,minusw, minusy, j);
x=-minusx;
y=-minusy;
}
}
}
else{
if(this->lambda1==0){
y=compute_aid(tau*u, t1-t0, x, y, w);
x=x-(t1-t0)*tau*u;
}
else{
if(x==0){
if(this->lambda1+u<0){
y=compute_aid(tau*(this->lambda1+u), t1-t0, x, y, w);
x=x-(t1-t0)*tau*(this->lambda1+u);
}
else if(u-this->lambda1>0){
y=compute_aid(tau*(-this->lambda1+u), t1-t0, x, y, w);
x=x-(t1-t0)*tau*(u-this->lambda1);
}else{
D p2=pow(this->theta3,t1-t0);
D tmp2=(1-p2)/(this->theta1+this->theta2);
y=(this->theta2*w)*tmp2+p2*y;
x=0;
}
}else if(x>0){
if(this->lambda1+u<=0){
y=compute_aid(tau*(this->lambda1+u), t1-t0, x, y, w);
x=x-(t1-t0)*tau*(this->lambda1+u);
}else{
D t=t0+x/(this->lambda1+u);
if(t<t1){
L t_tmp=floor(t);
y=compute_aid(tau*(this->lambda1+u), t_tmp-t0, x, y, w);
x=x-(t_tmp-t0)*tau*(this->lambda1+u);
x=compute_one_step(tau,u,x);
y=this->theta1*x+this->theta2*w+this->theta3*y;
compute_just_in_time_prox_grad_without_x_s(tau, u, x, t_tmp+1, t1, w, y, j);
}
else{
y=compute_aid(tau*(this->lambda1+u), t1-t0, x, y, w);
x=x-(t1-t0)*tau*(this->lambda1+u);
}
}
}else if(x<0){
D minusw=-w;
D minusx=-x;
D minusy=-y;
compute_just_in_time_prox_grad_without_x_s(tau, -u, minusx, t0, t1,minusw, minusy, j);
x=-minusx;
y=-minusy;
}
}
}
}
};
// compute_aid returns the value of y_{k+s} given by: y_{k+1}=theta1*z_{k+1}+theta2*w+(1-theta1-theta2)*y_k; z_{k+i}=z_k-i*h
D compute_aid(D h, D s, D x, D y, D w){
D p2=pow(this->theta3,s);
D tmp2=(1-p2)/(this->theta1+this->theta2);
D tmp3=(tmp2*this->theta3-p2*s)/(this->theta1+this->theta2);
y=this->theta1*(tmp2*(x-s*h)+h*tmp3)+this->theta2*w*tmp2+p2*y;
return y;
}
// compute_aid_2 returns the value of y_{k+s} given by: y_{k+1}=theta1*z_{k+1}+theta2*w+(1-theta1-theta2)*y_k; z_{k+i}=q^i(z_k+h)-h
//p=q^s;
D compute_aid_2(D p, D q, D h, D s, D x, D y, D w){
D theta3overq=this->theta3/q;
D p2=pow(this->theta3,s);
D p3=pow(theta3overq,s);
D tmp=(1-p3)/(1-theta3overq);
D tmp2=(1-p2)/(this->theta1+this->theta2);
y=this->theta1*p*(x+h)*tmp+(this->theta2*w-this->theta1*h)*tmp2+p2*y;
return y;
}
void Katyusha_solver(D beta_0, D epsilon_0, D eta , D rho, vector<D> & x0,vector<D> & y0,L val_tau, L max_nb_outer, L p_N_1, L p_N_2,string filename1, string filename2, D time){
this->ALM_solve_with_L_Katyusha(beta_0, epsilon_0, eta, rho, x0,y0, val_tau, max_nb_outer, p_N_1, p_N_2, filename1, filename2, time);
}
};
#endif
| {
"alphanum_fraction": 0.5552672548,
"avg_line_length": 24.4698412698,
"ext": "h",
"hexsha": "d3b296ec5f3bf377b38c9aa81cc2bf1e93c5def2",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2021-01-15T04:23:24.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-01-15T04:23:24.000Z",
"max_forks_repo_head_hexsha": "3d5d8c281411fdfd6379480429a1fbb9b21464ff",
"max_forks_repo_licenses": [
"BSD-Source-Code"
],
"max_forks_repo_name": "lifei16/supplementary_code",
"max_forks_repo_path": "IPALM_OPENMP/Fused_Lasso_b.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "3d5d8c281411fdfd6379480429a1fbb9b21464ff",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-Source-Code"
],
"max_issues_repo_name": "lifei16/supplementary_code",
"max_issues_repo_path": "IPALM_OPENMP/Fused_Lasso_b.h",
"max_line_length": 180,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "3d5d8c281411fdfd6379480429a1fbb9b21464ff",
"max_stars_repo_licenses": [
"BSD-Source-Code"
],
"max_stars_repo_name": "lifei16/supplementary_code",
"max_stars_repo_path": "IPALM_OPENMP/Fused_Lasso_b.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 2914,
"size": 7708
} |
/*
* -----------------------------------------------------------------
* In Situ Adaptive Tabulation Library --- isat_lib.h
* Version: 1.6180
* Date: Feb 25, 2010
* -----------------------------------------------------------------
* Programmer: Americo Barbosa da Cunha Junior
* americo.cunhajr@gmail.com
* -----------------------------------------------------------------
* Copyright (c) 2010 by Americo Barbosa da Cunha Junior
*
* 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.
*
* A copy of the GNU General Public License is available in
* LICENSE.txt or http://www.gnu.org/licenses/.
* -----------------------------------------------------------------
* This is the header file for a library
* with the ISAT algorithm.
* -----------------------------------------------------------------
*/
#ifndef __ISAT_LIB_H__
#define __ISAT_LIB_H__
#include <gsl/gsl_blas.h>
#include <gsl/gsl_math.h>
#include "../include/bst_lib.h"
#undef RTOL
#define RTOL 1.0e-6
#undef ATOL
#define ATOL 1.0e-9
/*
*------------------------------------------------------------
* structure of ISAT workspace
*
* last update: Jul 13, 2010
*------------------------------------------------------------
*/
typedef struct isat_struct
{
bst_node *root; /* binary search tree root */
unsigned int lf; /* # of leaves */
unsigned int nd; /* # of nodes */
unsigned int add; /* # of adds */
unsigned int grw; /* # of grows */
unsigned int rtv; /* # of retrieves */
unsigned int dev; /* # of discarted evaluations */
unsigned int hgt; /* tree height */
unsigned int max_lf; /* maximum value of tree leaves */
clock_t time_add; /* cpu clock spent by additions */
clock_t time_grw; /* cpu clock spent by growths */
clock_t time_rtv; /* cpu clock spent by retrieves */
clock_t time_dev; /* cpu clock spent by dev */
} isat_wrk;
/*------------------------------------------------------------*/
/*
*------------------------------------------------------------
* function prototypes
*------------------------------------------------------------
*/
isat_wrk *isat_alloc();
void isat_free(void **isat_bl);
int isat_set(isat_wrk *isat);
void isat_statistics(isat_wrk *isat);
int isat_input(unsigned int *max_lf,
double *etol,
double *n0);
void isat_eoa_mtrx(gsl_matrix *A,
double etol,
double n0,
gsl_matrix *L);
double isat_lerror(gsl_vector *Rphi,
gsl_vector *Rphi0,
gsl_matrix *A,
gsl_vector *phi,
gsl_vector *phi0);
int isat4(isat_wrk *isat,
void *thrm_data,
void *cvode_mem,
double etol,
double n0,
double t0,
double delta_t,
gsl_vector *phi,
gsl_matrix *A,
gsl_matrix *L,
gsl_vector *Rphi);
#endif /* __ISAT_LIB_H__ */
| {
"alphanum_fraction": 0.4844444444,
"avg_line_length": 28.8,
"ext": "h",
"hexsha": "cf7e6fa26a3f5e0cc7a883378100bd1ebbf2c99c",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2021-12-30T01:44:13.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-11-15T03:57:44.000Z",
"max_forks_repo_head_hexsha": "35b67f798c1c33118c028691f42b98ba06220eeb",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "americocunhajr/CRFlowLib",
"max_forks_repo_path": "CRFlowLib-1.0/include/isat_lib.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "35b67f798c1c33118c028691f42b98ba06220eeb",
"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": "americocunhajr/CRFlowLib",
"max_issues_repo_path": "CRFlowLib-1.0/include/isat_lib.h",
"max_line_length": 68,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "35b67f798c1c33118c028691f42b98ba06220eeb",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "americocunhajr/CRFlowLib",
"max_stars_repo_path": "CRFlowLib-1.0/include/isat_lib.h",
"max_stars_repo_stars_event_max_datetime": "2020-12-29T12:56:14.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-12-29T12:56:14.000Z",
"num_tokens": 792,
"size": 3600
} |
/* statistics/gsl_statistics_uint.h
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000 Jim Davies, Brian Gough
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#ifndef __GSL_STATISTICS_UINT_H__
#define __GSL_STATISTICS_UINT_H__
#include <stddef.h>
#include <gsl/gsl_types.h>
#undef __BEGIN_DECLS
#undef __END_DECLS
#ifdef __cplusplus
# define __BEGIN_DECLS extern "C" {
# define __END_DECLS }
#else
# define __BEGIN_DECLS /* empty */
# define __END_DECLS /* empty */
#endif
__BEGIN_DECLS
GSL_EXPORT double gsl_stats_uint_mean (const unsigned int data[], const size_t stride, const size_t n);
GSL_EXPORT double gsl_stats_uint_variance (const unsigned int data[], const size_t stride, const size_t n);
GSL_EXPORT double gsl_stats_uint_sd (const unsigned int data[], const size_t stride, const size_t n);
GSL_EXPORT double gsl_stats_uint_variance_with_fixed_mean (const unsigned int data[], const size_t stride, const size_t n, const double mean);
GSL_EXPORT double gsl_stats_uint_sd_with_fixed_mean (const unsigned int data[], const size_t stride, const size_t n, const double mean);
GSL_EXPORT double gsl_stats_uint_absdev (const unsigned int data[], const size_t stride, const size_t n);
GSL_EXPORT double gsl_stats_uint_skew (const unsigned int data[], const size_t stride, const size_t n);
GSL_EXPORT double gsl_stats_uint_kurtosis (const unsigned int data[], const size_t stride, const size_t n);
GSL_EXPORT double gsl_stats_uint_lag1_autocorrelation (const unsigned int data[], const size_t stride, const size_t n);
GSL_EXPORT double gsl_stats_uint_covariance (const unsigned int data1[], const size_t stride1,const unsigned int data2[], const size_t stride2, const size_t n);
GSL_EXPORT double gsl_stats_uint_variance_m (const unsigned int data[], const size_t stride, const size_t n, const double mean);
GSL_EXPORT double gsl_stats_uint_sd_m (const unsigned int data[], const size_t stride, const size_t n, const double mean);
GSL_EXPORT double gsl_stats_uint_absdev_m (const unsigned int data[], const size_t stride, const size_t n, const double mean);
GSL_EXPORT double gsl_stats_uint_skew_m_sd (const unsigned int data[], const size_t stride, const size_t n, const double mean, const double sd);
GSL_EXPORT double gsl_stats_uint_kurtosis_m_sd (const unsigned int data[], const size_t stride, const size_t n, const double mean, const double sd);
GSL_EXPORT double gsl_stats_uint_lag1_autocorrelation_m (const unsigned int data[], const size_t stride, const size_t n, const double mean);
GSL_EXPORT double gsl_stats_uint_covariance_m (const unsigned int data1[], const size_t stride1,const unsigned int data2[], const size_t stride2, const size_t n, const double mean1, const double mean2);
GSL_EXPORT double gsl_stats_uint_pvariance (const unsigned int data1[], const size_t stride1, const size_t n1, const unsigned int data2[], const size_t stride2, const size_t n2);
GSL_EXPORT double gsl_stats_uint_ttest (const unsigned int data1[], const size_t stride1, const size_t n1, const unsigned int data2[], const size_t stride2, const size_t n2);
GSL_EXPORT unsigned int gsl_stats_uint_max (const unsigned int data[], const size_t stride, const size_t n);
GSL_EXPORT unsigned int gsl_stats_uint_min (const unsigned int data[], const size_t stride, const size_t n);
GSL_EXPORT void gsl_stats_uint_minmax (unsigned int * min, unsigned int * max, const unsigned int data[], const size_t stride, const size_t n);
GSL_EXPORT size_t gsl_stats_uint_max_index (const unsigned int data[], const size_t stride, const size_t n);
GSL_EXPORT size_t gsl_stats_uint_min_index (const unsigned int data[], const size_t stride, const size_t n);
GSL_EXPORT void gsl_stats_uint_minmax_index (size_t * min_index, size_t * max_index, const unsigned int data[], const size_t stride, const size_t n);
GSL_EXPORT double gsl_stats_uint_median_from_sorted_data (const unsigned int sorted_data[], const size_t stride, const size_t n) ;
GSL_EXPORT double gsl_stats_uint_quantile_from_sorted_data (const unsigned int sorted_data[], const size_t stride, const size_t n, const double f) ;
__END_DECLS
#endif /* __GSL_STATISTICS_UINT_H__ */
| {
"alphanum_fraction": 0.7960882231,
"avg_line_length": 62.4155844156,
"ext": "h",
"hexsha": "a5327bc33a95a90a837b9c58d6999b98abd7bb13",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "f6ed9b75408f7ce6100ed59b7754f745e59be152",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "dynaryu/vaws",
"max_forks_repo_path": "src/core/gsl/include/gsl/gsl_statistics_uint.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "f6ed9b75408f7ce6100ed59b7754f745e59be152",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "dynaryu/vaws",
"max_issues_repo_path": "src/core/gsl/include/gsl/gsl_statistics_uint.h",
"max_line_length": 202,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "f6ed9b75408f7ce6100ed59b7754f745e59be152",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "dynaryu/vaws",
"max_stars_repo_path": "src/core/gsl/include/gsl/gsl_statistics_uint.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1161,
"size": 4806
} |
/**
*
* @file qwrapper_cpotrf.c
*
* PLASMA core_blas quark wrapper
* PLASMA is a software package provided by Univ. of Tennessee,
* Univ. of California Berkeley and Univ. of Colorado Denver
*
* @version 2.6.0
* @author Hatem Ltaief
* @author Mathieu Faverge
* @author Jakub Kurzak
* @date 2010-11-15
* @generated c Tue Jan 7 11:44:56 2014
*
**/
#include <lapacke.h>
#include "common.h"
/***************************************************************************//**
*
**/
void QUARK_CORE_cpotrf(Quark *quark, Quark_Task_Flags *task_flags,
PLASMA_enum uplo, int n, int nb,
PLASMA_Complex32_t *A, int lda,
PLASMA_sequence *sequence, PLASMA_request *request,
int iinfo)
{
DAG_CORE_POTRF;
QUARK_Insert_Task(quark, CORE_cpotrf_quark, task_flags,
sizeof(PLASMA_enum), &uplo, VALUE,
sizeof(int), &n, VALUE,
sizeof(PLASMA_Complex32_t)*nb*nb, A, INOUT,
sizeof(int), &lda, VALUE,
sizeof(PLASMA_sequence*), &sequence, VALUE,
sizeof(PLASMA_request*), &request, VALUE,
sizeof(int), &iinfo, VALUE,
0);
}
/***************************************************************************//**
*
**/
#if defined(PLASMA_HAVE_WEAK)
#pragma weak CORE_cpotrf_quark = PCORE_cpotrf_quark
#define CORE_cpotrf_quark PCORE_cpotrf_quark
#endif
void CORE_cpotrf_quark(Quark *quark)
{
PLASMA_enum uplo;
int n;
PLASMA_Complex32_t *A;
int lda;
PLASMA_sequence *sequence;
PLASMA_request *request;
int iinfo;
int info;
quark_unpack_args_7(quark, uplo, n, A, lda, sequence, request, iinfo);
info = LAPACKE_cpotrf_work(
LAPACK_COL_MAJOR,
lapack_const(uplo),
n, A, lda);
if (sequence->status == PLASMA_SUCCESS && info != 0)
plasma_sequence_flush(quark, sequence, request, iinfo+info);
}
| {
"alphanum_fraction": 0.5438681532,
"avg_line_length": 30.3382352941,
"ext": "c",
"hexsha": "57512e7766ece36595b89e2608503924e67cd527",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "zhuangsc/Plasma-ompss1",
"max_forks_repo_path": "core_blas-qwrapper/qwrapper_cpotrf.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "zhuangsc/Plasma-ompss1",
"max_issues_repo_path": "core_blas-qwrapper/qwrapper_cpotrf.c",
"max_line_length": 80,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "zhuangsc/Plasma-ompss1",
"max_stars_repo_path": "core_blas-qwrapper/qwrapper_cpotrf.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 555,
"size": 2063
} |
#include <gsl/gsl_math.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_complex.h>
#include <gsl/gsl_complex_math.h>
#include "oct.h"
void
print_octave(const gsl_matrix *m, const char *str)
{
FILE *fp;
size_t i, j;
const size_t N = m->size1;
const size_t M = m->size2;
if (str == NULL)
fp = stdout;
else
fp = fopen(str, "w");
if (!fp)
return;
fprintf(fp, "%% Created by Octave 2.1.73, Tue Aug 01 15:00:27 2006 MDT <blah@blah>\n");
fprintf(fp, "%% name: %s\n", str);
fprintf(fp, "%% type: matrix\n");
fprintf(fp, "%% rows: %zu\n", N);
fprintf(fp, "%% columns: %zu\n", M);
for (i = 0; i < N; ++i)
{
for (j = 0; j < M; ++j)
{
fprintf(fp,
"%10.12e%s",
gsl_matrix_get(m, i, j),
(j < M - 1) ? " " : "\n");
}
}
if (str != NULL)
fclose(fp);
}
void
printv_octave(const gsl_vector *v, const char *str)
{
FILE *fp;
size_t i;
const size_t N = v->size;
fp = fopen(str, "w");
if (!fp)
return;
fprintf(fp, "%% Created by Octave 2.1.73, Tue Aug 01 15:00:27 2006 MDT <blah@blah>\n");
fprintf(fp, "%% name: %s\n", str);
fprintf(fp, "%% type: matrix\n");
fprintf(fp, "%% rows: %zu\n", N);
fprintf(fp, "%% columns: %u\n", 1);
for (i = 0; i < N; ++i)
{
fprintf(fp, "%10.12e\n", gsl_vector_get(v, i));
}
fclose(fp);
}
void
printc_octave(const gsl_matrix_complex *m, const char *str)
{
FILE *fp;
size_t i, j;
const size_t N = m->size1;
const size_t M = m->size2;
fp = fopen(str, "w");
if (!fp)
return;
fprintf(fp, "%% Created by Octave 2.1.73, Tue Aug 01 15:00:27 2006 MDT <blah@blah>\n");
fprintf(fp, "%% name: %s\n", str);
fprintf(fp, "%% type: complex matrix\n");
fprintf(fp, "%% rows: %zu\n", N);
fprintf(fp, "%% columns: %zu\n", M);
for (i = 0; i < N; ++i)
{
for (j = 0; j < M; ++j)
{
gsl_complex z = gsl_matrix_complex_get(m, i, j);
fprintf(fp,
"(%.12e,%.12e)%s",
GSL_REAL(z),
GSL_IMAG(z),
(j < M - 1) ? " " : "\n");
}
}
fclose(fp);
}
/* print symmetric matrix, using upper triangle */
void
printsym_octave(const gsl_matrix *m, const char *str)
{
FILE *fp;
size_t i, j;
const size_t N = m->size1;
const size_t M = m->size2;
fp = fopen(str, "w");
if (!fp)
return;
fprintf(fp, "%% Created by Octave 2.1.73, Tue Aug 01 15:00:27 2006 MDT <blah@blah>\n");
fprintf(fp, "%% name: %s\n", str);
fprintf(fp, "%% type: matrix\n");
fprintf(fp, "%% rows: %zu\n", N);
fprintf(fp, "%% columns: %zu\n", M);
for (i = 0; i < N; ++i)
{
for (j = 0; j < M; ++j)
{
double z;
if (j >= i)
z = gsl_matrix_get(m, i, j);
else
z = gsl_matrix_get(m, j, i);
fprintf(fp,
"%.12e%s",
z,
(j < M - 1) ? " " : "\n");
}
}
fclose(fp);
}
/* print Hermitian matrix, using upper triangle */
void
printherm_octave(const gsl_matrix_complex *m, const char *str)
{
FILE *fp;
size_t i, j;
const size_t N = m->size1;
const size_t M = m->size2;
fp = fopen(str, "w");
if (!fp)
return;
fprintf(fp, "%% Created by Octave 2.1.73, Tue Aug 01 15:00:27 2006 MDT <blah@blah>\n");
fprintf(fp, "%% name: %s\n", str);
fprintf(fp, "%% type: complex matrix\n");
fprintf(fp, "%% rows: %zu\n", N);
fprintf(fp, "%% columns: %zu\n", M);
for (i = 0; i < N; ++i)
{
for (j = 0; j < M; ++j)
{
gsl_complex z;
if (j >= i)
z = gsl_matrix_complex_get(m, i, j);
else
z = gsl_complex_conjugate(gsl_matrix_complex_get(m, j, i));
fprintf(fp,
"(%.12e,%.12e)%s",
GSL_REAL(z),
GSL_IMAG(z),
(j < M - 1) ? " " : "\n");
}
}
fclose(fp);
}
void
printcv_octave(const gsl_vector_complex *v, const char *str)
{
FILE *fp;
size_t i;
const size_t N = v->size;
fp = fopen(str, "w");
if (!fp)
return;
fprintf(fp, "%% Created by Octave 2.1.73, Tue Aug 01 15:00:27 2006 MDT <blah@blah>\n");
fprintf(fp, "%% name: %s\n", str);
fprintf(fp, "%% type: complex matrix\n");
fprintf(fp, "%% rows: %zu\n", N);
fprintf(fp, "%% columns: %u\n", 1);
for (i = 0; i < N; ++i)
{
gsl_complex z = gsl_vector_complex_get(v, i);
fprintf(fp, "(%.12e,%.12e)\n", GSL_REAL(z), GSL_IMAG(z));
}
fclose(fp);
}
/* print triangular matrix, using upper triangle */
void
printtri_octave(const gsl_matrix *m, const char *str)
{
FILE *fp;
size_t i, j;
const size_t N = m->size1;
const size_t M = m->size2;
if (str == NULL)
fp = stdout;
else
fp = fopen(str, "w");
if (!fp)
return;
fprintf(fp, "%% Created by Octave 2.1.73, Tue Aug 01 15:00:27 2006 MDT <blah@blah>\n");
fprintf(fp, "%% name: %s\n", str);
fprintf(fp, "%% type: matrix\n");
fprintf(fp, "%% rows: %zu\n", N);
fprintf(fp, "%% columns: %zu\n", M);
for (i = 0; i < N; ++i)
{
for (j = 0; j < M; ++j)
{
double mij;
if (j >= i)
mij = gsl_matrix_get(m, i, j);
else
mij = 0.0;
fprintf(fp,
"%10.12e%s",
mij,
(j < M - 1) ? " " : "\n");
}
}
if (str != NULL)
fclose(fp);
}
| {
"alphanum_fraction": 0.4865503453,
"avg_line_length": 21.0804597701,
"ext": "c",
"hexsha": "8ccdc32c283a3d49d7e47154f40e2931b163d8e1",
"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/doc/examples/oct.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/doc/examples/oct.c",
"max_line_length": 89,
"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/doc/examples/oct.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": 1868,
"size": 5502
} |
#include "../include/paralleltt.h"
#include <stdlib.h>
#include <lapacke.h>
#include <mpi.h>
#include <stdio.h>
#include <string.h>
void SSTT_sketch_to_train(sketch* s, tensor_train* tt, int train_ind)
{
int head = 0;
MPI_tensor* ten = s->ten;
MPI_Comm comm = ten->comm;
int iscol = s->iscol;
int flattening = s->flattening;
flattening_info* fi = flattening_info_init(ten, flattening, iscol, 0);
// train stuff
int d = ten->d;
int n = tt->n[train_ind];
int r1 = tt->r[train_ind];
int r2 = tt->r[train_ind + 1];
double* train = tt->trains[train_ind];
matrix_tt* train_mat = matrix_tt_wrap(r1 * n, r2, train);
matrix_tt_fill_zeros(train_mat);
int* op = s->owner_partition;
int rank = ten->rank;
matrix_tt* train_submat = submatrix(train_mat, 0, 0, 0, 0);
for (int ii = op[rank]; ii < op[rank+1]; ++ii){
matrix_tt* X_submat = own_submatrix(s, ii, 0);
matrix_tt* X_subsubmat = submatrix(X_submat, 0, 0, 0, 0);
flattening_info_f_update(fi, ten, ii);
int i0_train = fi->f_t_index[0];
int sz = fi->f_t_sizes[0];
int jj_max = 1;
if (train_ind != 0){
i0_train = i0_train + r1 * fi->f_t_index[1];
jj_max = fi->f_t_sizes[1];
}
for (int jj = 0; jj < jj_max; ++jj){
submatrix_update(train_submat, i0_train + jj*r1, i0_train + sz + jj*r1, 0, r2);
submatrix_update(X_subsubmat, jj*sz, (jj+1)*sz, 0, r2);
matrix_tt_copy_data(train_submat, X_subsubmat);
}
free(X_submat); X_submat = NULL;
free(X_subsubmat); X_subsubmat = NULL;
}
free(train_submat); train_submat = NULL;
matrix_tt_reshape(r1*n*r2, 1, train_mat); // Reshape so MPI_Allreduce is only called once
matrix_tt_allreduce(comm, train_mat);
flattening_info_free(fi);
free(train_mat);
return;
}
MPI_tensor* SSTT_next_ten_init(MPI_tensor* prev_ten, tensor_train* tt, int train_ind)
{
int r2 = tt->r[train_ind + 1];
MPI_Comm comm = prev_ten->comm;
int rank = prev_ten->rank;
int size = prev_ten->comm_size;
int is_first = (train_ind == 0);
int d = (is_first) ? prev_ten->d : prev_ten->d - 1;
int prev_offset = (is_first) ? 0 : 1;
int* n = (int*) calloc(d, sizeof(int));
int* nps = (int*) calloc(d, sizeof(int));
int Nblocks = 1;
n[0] = r2;
nps[0] = 1;
int** partitions = (int**) malloc(d * sizeof(int*));
partitions[0] = (int*) calloc(2, sizeof(int));
partitions[0][1] = r2;
for (int ii = 1; ii < d; ++ii){
n[ii] = prev_ten->n[prev_offset + ii];
nps[ii] = prev_ten->nps[prev_offset + ii];
Nblocks = Nblocks * nps[ii];
partitions[ii] = (int*) calloc(nps[ii]+1, sizeof(int));
int* partition_ii = partitions[ii];
int* prev_partition_ii = prev_ten->partitions[prev_offset + ii];
for (int jj = 0; jj < nps[ii]+1; ++jj){
partition_ii[jj] = prev_partition_ii[jj];
}
}
int** schedule = (int**) calloc(size, sizeof(int*));
int n_schedule = get_schedule(schedule, nps, d, size);
int* inverse_schedule = (int*) calloc(Nblocks, sizeof(int));
for (int ii = 0; ii < size; ++ii){
int* schedule_ii = schedule[ii];
for (int jj = 0; jj < n_schedule; ++jj){
if (schedule_ii[jj] != -1){
inverse_schedule[schedule_ii[jj]] = ii*n_schedule + jj;
}
}
}
long* subtensor_sizes = (long*) malloc(n_schedule * sizeof(long));
int* t_t_block = (int*) malloc(d*sizeof(int));
long X_size = 0;
for (int jj = 0; jj < n_schedule; ++jj){
int t_v_block = schedule[rank][jj];
if (t_v_block != -1){
subtensor_sizes[jj] = 1;
to_tensor_ind(t_t_block, t_v_block, nps, d);
for (int kk = 0; kk < d; ++kk){
subtensor_sizes[jj] = subtensor_sizes[jj] * (partitions[kk][t_t_block[kk]+1] - partitions[kk][t_t_block[kk]]);
}
X_size = X_size + subtensor_sizes[jj];
}
else{
subtensor_sizes[jj] = 0;
}
}
free(t_t_block);
double* X = (double*) calloc(X_size, sizeof(double)); // callocing here, because I will probably need it to start at 0
double* X_subtensor = X;
double** subtensors = (double**) malloc(n_schedule * sizeof(double*));
for (int jj = 0; jj < n_schedule; ++jj){
subtensors[jj] = X_subtensor;
X_subtensor = X_subtensor + subtensor_sizes[jj];
}
int flattening = d;
void* parameters = p_static_init(subtensors);
free(subtensor_sizes);
// Assigning fields
MPI_tensor* next_ten = (MPI_tensor*) malloc(sizeof(MPI_tensor));
next_ten->d = d;
next_ten->n = n;
next_ten->comm = comm;
next_ten->rank = rank;
next_ten->comm_size = size;
next_ten->schedule = schedule;
next_ten->n_schedule = n_schedule;
next_ten->inverse_schedule = inverse_schedule;
next_ten->partitions = partitions;
next_ten->nps = nps;
next_ten->current_part = -1;
next_ten->f_ten = NULL;
next_ten->parameters = parameters;
next_ten->X_size = X_size;
next_ten->X = X;
next_ten->ind1 = (int*) malloc(d * sizeof(int));
next_ten->ind2 = (int*) malloc(d * sizeof(int));
next_ten->tensor_part = (int*) malloc(d * sizeof(int));
next_ten->group_ranks = (int*) malloc(size * sizeof(int));
next_ten->t_kk = (int*) malloc(d * sizeof(int));
return next_ten;
}
MPI_tensor* SSTT_next_ten(MPI_tensor* prev_ten, tensor_train* tt, int train_ind)
{
// Get the train matrix. This is what we multiply prev_ten by!
int n0 = tt->n[train_ind];
int r1 = tt->r[train_ind];
int r2 = tt->r[train_ind + 1];
double* train = tt->trains[train_ind];
matrix_tt* train_mat = matrix_tt_wrap(r1 * n0, r2, train);
// Allocate memory for next_ten
MPI_tensor* next_ten = SSTT_next_ten_init(prev_ten, tt, train_ind);
// Allocate scratch memory
long scratch_size = 1;
for (int ii = 0; ii < next_ten->d; ++ii){
int* partition_ii = next_ten->partitions[ii];
int size_ii = 0;
for (int jj = 0; jj < next_ten->nps[ii]; ++jj){
int tmp = partition_ii[jj+1] - partition_ii[jj];
size_ii = (size_ii > tmp) ? size_ii : tmp;
}
scratch_size = scratch_size * size_ii;
}
double* scratch = (double*) malloc(scratch_size * sizeof(double));
// Get some indexing stuff
int iscol = 1;
int prev_flattening = (train_ind == 0) ? 1 : 2;
flattening_info* prev_fi = flattening_info_init(prev_ten, prev_flattening, iscol, 0);
flattening_info* prev_fi_tmp = flattening_info_init(prev_ten, prev_flattening, iscol, 0);
int next_flattening = 1;
flattening_info* next_fi = flattening_info_init(next_ten, next_flattening, iscol, 0);
flattening_info* next_fi_tmp = flattening_info_init(next_ten, next_flattening, iscol, 0);
// Streaming loop
int rank = prev_ten->rank;
int size = prev_ten->comm_size;
int* prev_schedule_rank = prev_ten->schedule[rank];
int* next_schedule_rank = next_ten->schedule[rank];
MPI_Group world_group;
MPI_Comm_group(next_ten->comm, &world_group);
matrix_tt* prev_mat = (matrix_tt*) calloc(1, sizeof(matrix_tt));
matrix_tt* next_mat = (matrix_tt*) calloc(1, sizeof(matrix_tt));
matrix_tt* share_mat = (matrix_tt*) calloc(1, sizeof(matrix_tt));
long buf_size = 1;
for (int ii = 0; ii < next_ten->d; ++ii){
int sz_ii = 0;
int* partition_ii = next_ten->partitions[ii];
for (int jj = 0; jj < next_ten->nps[ii]; ++jj){
int sz_ii_jj = partition_ii[jj+1] - partition_ii[jj];
sz_ii = (sz_ii > sz_ii_jj) ? sz_ii : sz_ii_jj;
}
buf_size *= sz_ii;
}
matrix_tt* buf = matrix_tt_init(buf_size, 1);
for (int ii = 0; ii < prev_ten->n_schedule; ++ii){
// Some initialization - figuring out who owns and needs what
int prev_block_rank = prev_schedule_rank[ii];
int* next_t_v_blocks = (int*) malloc(size*sizeof(int));
for (int jj = 0; jj < size; ++jj){
int prev_block_jj = prev_ten->schedule[jj][ii];
if (prev_block_jj != -1){
flattening_info_update(prev_fi_tmp, prev_ten, prev_block_jj);
int* next_t_t_block = (prev_fi_tmp->t_t_block) + prev_flattening;
int* next_nps = (next_fi->t_nps) + 1;
next_t_v_blocks[jj] = to_vec_ind(next_t_t_block, next_nps, next_fi->t_d - 1);
}
else{
next_t_v_blocks[jj] = -1;
}
}
if (prev_block_rank != -1){
// Get prev_mat
stream(prev_ten, prev_block_rank);
flattening_info_update(prev_fi, prev_ten, prev_block_rank);
matrix_tt_wrap_update(prev_mat, prev_fi->f_N, prev_fi->s_N, get_X(prev_ten));
// Get next_mat
int next_t_v_block = next_t_v_blocks[rank];
flattening_info_update(next_fi, next_ten, next_t_v_block);
int next_owner;
int next_epoch;
MPI_tensor_get_owner(next_ten, next_t_v_block, &next_owner, &next_epoch);
double beta;
if (next_owner == rank){
beta = 1.0;
stream(next_ten, next_schedule_rank[next_epoch]);
matrix_tt_wrap_update(next_mat, next_fi->f_N, next_fi->s_N, get_X(next_ten));
}
else{
beta = 0.0;
matrix_tt_wrap_update(next_mat, next_fi->f_N, next_fi->s_N, scratch);
}
// Get train submat
int i0 = r1 * prev_fi->f_t_index[prev_flattening - 1];
int i1 = i0 + r1 * prev_fi->f_t_sizes[prev_flattening - 1];
submatrix_update(train_mat, i0, i1, 0, r2);
train_mat->transpose = 1;
// Multiply
matrix_tt_dgemm(train_mat, prev_mat, next_mat, 1.0, beta);
}
// Share
int* already_shared = (int*) calloc(size, sizeof(int));
int* group_ranks = prev_ten->group_ranks;
// printf("Starting share\n");
for (int jj = 0; jj < size; ++jj){
int group_size = 0;
int t_v_block_jj = next_t_v_blocks[jj];
int owner_jj;
int epoch_jj;
MPI_tensor_get_owner(next_ten, t_v_block_jj, &owner_jj, &epoch_jj);
if (owner_jj == jj){
already_shared[jj] = 1;
}
else if (t_v_block_jj == -1){
already_shared[jj] = 1;
}
else if(already_shared[jj] == 0){
int owner_ind;
int rank_ind;
for (int kk = 0; kk < size; ++kk){
if (kk == rank){
rank_ind = group_size;
}
if (kk == owner_jj){
group_ranks[group_size] = kk;
group_size = group_size + 1;
}
else if (next_t_v_blocks[kk] == t_v_block_jj){
already_shared[kk] = 1;
group_ranks[group_size] = kk;
group_size = group_size + 1;
}
}
matrix_tt* reduce_mat = NULL;
if (owner_jj == rank){
flattening_info_update(next_fi_tmp, next_ten, t_v_block_jj);
stream(next_ten, t_v_block_jj);
matrix_tt_wrap_update(share_mat, next_fi_tmp->t_N, 1, get_X(next_ten));
reduce_mat = share_mat;
}
else{
matrix_tt_reshape(next_mat->n * next_mat->m, 1, next_mat);
reduce_mat = next_mat;
}
matrix_tt_reshape(reduce_mat->m, reduce_mat->n, buf);
matrix_tt_group_reduce(next_ten->comm, rank, reduce_mat, buf, owner_jj, group_ranks, group_size);
}
}
free(next_t_v_blocks);
free(already_shared);
}
free(prev_mat);
free(next_mat);
free(share_mat);
matrix_tt_free(buf);
free(train_mat);
free(scratch);
flattening_info_free(prev_fi);
flattening_info_free(prev_fi_tmp);
flattening_info_free(next_fi);
flattening_info_free(next_fi_tmp);
MPI_Group_free(&world_group);
return next_ten;
}
void SSTT_copy_final_train(MPI_tensor* ten, tensor_train* tt)
{
int r1 = tt->r[tt->d - 1];
int n = tt->n[tt->d - 1];
matrix_tt* train_mat = matrix_tt_wrap(r1, n, tt->trains[tt->d - 1]);
int rank = ten->rank;
MPI_Comm comm = ten->comm;
int size = ten->comm_size;
int flattening = 1;
int iscol = 0;
flattening_info* fi = flattening_info_init(ten, flattening, iscol, 0);
int Nblocks = ten->nps[1];
int head = 0;
for (int ii = 0; ii < Nblocks; ++ii){
int rank_ii;
int epoch_ii;
MPI_tensor_get_owner(ten, ii, &rank_ii, &epoch_ii);
flattening_info_update(fi, ten, ii);
matrix_tt* train_submat = submatrix(train_mat, 0, r1, fi->f_t_index[0], fi->f_t_index[0] + fi->f_N);
if (rank_ii == rank){
stream(ten, ii);
matrix_tt* ten_mat = matrix_tt_wrap(train_submat->m, train_submat->n, get_X(ten));
if (rank == head){
matrix_tt_copy_data(train_submat, ten_mat);
}
else{
matrix_tt_send(comm, ten_mat, head);
}
free(ten_mat);
}
else if (rank == head){
matrix_tt_recv(comm, train_submat, rank_ii);
}
free(train_submat);
}
free(train_mat);
flattening_info_free(fi);
}
// This frees ten. So just be careful
void SSTT(tensor_train* tt, MPI_tensor* ten){
int d = ten->d;
int buf = 2;
int iscol = 1;
for (int ii = 0; ii < d-1; ++ii){
int flattening = (ii == 0) ? 1 : 2;
sketch* s = sketch_init(ten, flattening, tt->r[ii+1], buf, iscol); // Initialize sketch
perform_sketch(s); // Sketch
sketch_qr(s); // QR
SSTT_sketch_to_train(s, tt, ii); // Get the train
MPI_tensor* prev_ten = ten;
ten = SSTT_next_ten(prev_ten, tt, ii); // Perform train^T * ten
sketch_free(s);
MPI_tensor_free(prev_ten); prev_ten = NULL;
}
SSTT_copy_final_train(ten, tt); // copy ten into trains[d-1]
MPI_tensor_free(ten);
} | {
"alphanum_fraction": 0.572723527,
"avg_line_length": 32.4320712695,
"ext": "c",
"hexsha": "71bb3e1a1980a30b9d47d8aa5e13a4db9d0c4c6d",
"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": "e2c00c289d75d3ac1df32ed2b95af579a517fcbf",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "SidShi/Parallel_TT_sketching",
"max_forks_repo_path": "src/SSTT.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "e2c00c289d75d3ac1df32ed2b95af579a517fcbf",
"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": "SidShi/Parallel_TT_sketching",
"max_issues_repo_path": "src/SSTT.c",
"max_line_length": 126,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "e2c00c289d75d3ac1df32ed2b95af579a517fcbf",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "SidShi/Parallel_TT_sketching",
"max_stars_repo_path": "src/SSTT.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 4102,
"size": 14562
} |
/*
Copyright (C) 2019-2020 JingWeiZhangHuai <jingweizhanghuai@163.com>
Licensed under the Apache License, Version 2.0; you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
*/
// #include <cblas.h>
#include "morn_tensor.h"
struct TensorConnectPara
{
MLayer *prev;
int height;
int width;
int channel;
int res_valid;
float rate;
float decay;
float momentum;
};
void *mTensorConnectPara(MList *ini,char *name)
{
struct TensorConnectPara *para=(struct TensorConnectPara *)mMalloc(sizeof(struct TensorConnectPara));
para->prev = mNetworkLayer(ini,mINIRead(ini,name,"prev"));
mException((para->prev == NULL),EXIT,"invalid prev");
para->res_valid = (strcmp("Input",mLayerType(para->prev))!=0);
para->height = 1; mINIRead(ini,name,"height" ,"%d",&(para->height ));
para->width = 1; mINIRead(ini,name,"width" ,"%d",&(para->width ));
para->channel= 1; mINIRead(ini,name,"channel","%d",&(para->channel));
para->rate =0.001;if(mINIRead(ini,name,"rate" ,"%f",&(para->rate ))==NULL) mINIRead(ini,"para","rate" ,"%f",&(para->rate ));
para->momentum= 0.9 ;if(mINIRead(ini,name,"momentum","%f",&(para->momentum))==NULL) mINIRead(ini,"para","momentum","%f",&(para->momentum));
para->decay = 0.01;if(mINIRead(ini,name,"decay" ,"%f",&(para->decay ))==NULL) mINIRead(ini,"para","decay" ,"%f",&(para->decay ));
mException((para->decay<0.0f)||(para->decay>=1.0f),EXIT,"invalid para decay");
return para;
}
struct HandleTensorConnect
{
MMemoryBlock *weight;
MMemoryBlock *update;
};
void endTensorConnect(struct HandleTensorConnect *handle)
{
if(handle->weight != NULL) mMemoryBlockRelease(handle->weight);
if(handle->update != NULL) mMemoryBlockRelease(handle->update);
}
#define HASH_TensorConnect 0xb8986c4a
struct HandleTensorConnect *TensorConnectSet(MLayer *layer)
{
struct TensorConnectPara *para = (struct TensorConnectPara *)(layer->para);
MTensor *in = para->prev->tns;
MTensor *res= para->prev->res;
MTensor *out=layer->tns;
int device = out->device;
MHandle *hdl=mHandle(out,TensorConnect);
struct HandleTensorConnect *handle = (struct HandleTensorConnect *)(hdl->handle);
if(layer->state != DFLT) return handle;
int weight_height= para->channel*para->height*para->width;
int weight_width = in->channel* in->height* in->width +1;
int data_size = weight_height*weight_width;
mTensorRedefine(out,in->batch,para->channel,para->height,para->width,NULL);
if(morn_network_flag == MORN_TRAIN)
{
mTensorRedefine(res,in->batch,in->channel,in->height,in->width,NULL);
if(handle->update != NULL) mMemoryBlockRelease(handle->update);
handle->update =mMemoryBlockCreate(data_size*sizeof(float),device);
memset(handle->update->data,0,data_size*sizeof(float));
handle->update->flag = MORN_HOST;
mMemoryBlockWrite(handle->update);
}
if(handle->weight != NULL) mMemoryBlockRelease(handle->weight);
handle->weight =mMemoryBlockCreate(data_size*sizeof(float),device);
float *weight_data = (float *)(handle->weight->data);
if(morn_network_parafile==NULL)
{
float scale = sqrt(2.0f/weight_width);
for(int i=0;i<data_size;i++)
weight_data[i] = scale*mNormalRand(0.0f,1.0f);//((float)mRand(-16384,16383))/16384.0f;
}
else
{
mNetworkParaRead(layer,"weight",weight_data,data_size*sizeof(float));
}
handle->weight->flag = MORN_HOST;
mMemoryBlockWrite(handle->weight);
hdl->valid = 1;
return handle;
}
void mTensorConnectForward(MLayer *layer)
{
mException(INVALID_POINTER(layer),EXIT,"invalid input");
mException(strcmp("Connect",mLayerType(layer)),EXIT,"invalid layer type");
struct TensorConnectPara *para = (struct TensorConnectPara *)(layer->para);
MTensor *in = para->prev->tns;
MTensor *out= layer->tns;
int device = out->device;
struct HandleTensorConnect *handle = TensorConnectSet(layer);
int weight_height= out->height*out->width*out->channel;
int weight_width = in->height* in->width* in->channel +1;
for(int b=0;b<in->batch;b++)
{
mSgemm(device,MORN_NO_TRANS,MORN_NO_TRANS,weight_height,1,weight_width,1.0f,handle->weight,weight_width,mTensorMemory(in,b),1,0.0f,mTensorMemory(out,b),1);
printf("out_data[8]=%f\n",((float *)(out->data[b]))[8]);
}
layer->state = MORN_FORWARD;
}
void mTensorConnectBackward(MLayer *layer)
{
mException(INVALID_POINTER(layer),EXIT,"invalid input");
mException(strcmp("Connect",mLayerType(layer)),EXIT,"invalid layer type");
struct TensorConnectPara *para = (struct TensorConnectPara *)(layer->para);
MTensor *in = para->prev->tns;
MTensor *res = para->prev->res;
MTensor *out = layer->res;
int device = out->device;
MHandle *hdl=mHandle(layer->tns,TensorConnect);
struct HandleTensorConnect *handle = (struct HandleTensorConnect *)(hdl->handle);
mException((hdl->valid==0),EXIT,"no forward operate");
int weight_height= out->height*out->width*out->channel;
int weight_width = in->height* in->width* in->channel +1;
float *update_data = (float*)(handle->update->data);
mNetworkParaWrite(layer,"weight",handle->weight->data,weight_height*weight_width*sizeof(float));
float beta = para->momentum;
for(int b=0;b<in->batch;b++)
{
mSgemm(device,MORN_NO_TRANS,MORN_TRANS,weight_height,weight_width,1,1.0f,mTensorMemory(out,b),1,mTensorMemory(in,b),1,beta,handle->update,weight_width);
printf("update_data[8]=%f\n",((float*)(handle->update->data))[8]);
beta = 1.0;
}
if(para->res_valid) for(int b=0;b<in->batch;b++)
{
mSgemm(device,MORN_TRANS,MORN_NO_TRANS,weight_width,1,weight_height,1.0f,handle->weight,weight_width,mTensorMemory(out,b),1,((para->prev->state==MORN_FORWARD)?0.0f:1.0f),mTensorMemory(res,b),1);
printf("res_data[8]=%f\n",((float *)(res->data[b]))[8]);
}
mSaxpby(device,weight_height*weight_width,(0.0f-(para->rate/(float)(in->batch))),handle->update,1,(1.0f-(para->decay*para->rate)),handle->weight,1);
para->prev->state = MORN_BACKWARD;
}
| {
"alphanum_fraction": 0.6707972529,
"avg_line_length": 41.0920245399,
"ext": "c",
"hexsha": "b18075e6b9fecb44334f0ff31991ce3cc232eecb",
"lang": "C",
"max_forks_count": 35,
"max_forks_repo_forks_event_max_datetime": "2022-03-22T11:34:47.000Z",
"max_forks_repo_forks_event_min_datetime": "2019-09-26T05:09:23.000Z",
"max_forks_repo_head_hexsha": "4aacf6dfff67d0fbed75048dc4f2b571f52185b0",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "ishine/Morn",
"max_forks_repo_path": "src/deep_learning/morn_tensor_connect.c",
"max_issues_count": 4,
"max_issues_repo_head_hexsha": "4aacf6dfff67d0fbed75048dc4f2b571f52185b0",
"max_issues_repo_issues_event_max_datetime": "2020-04-07T15:05:18.000Z",
"max_issues_repo_issues_event_min_datetime": "2019-09-29T02:52:41.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "ishine/Morn",
"max_issues_repo_path": "src/deep_learning/morn_tensor_connect.c",
"max_line_length": 501,
"max_stars_count": 121,
"max_stars_repo_head_hexsha": "4aacf6dfff67d0fbed75048dc4f2b571f52185b0",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "ishine/Morn",
"max_stars_repo_path": "src/deep_learning/morn_tensor_connect.c",
"max_stars_repo_stars_event_max_datetime": "2022-03-30T03:23:49.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-09-24T05:53:42.000Z",
"num_tokens": 1890,
"size": 6698
} |
/*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*
** **
** This file forms part of the Underworld geophysics modelling application. **
** **
** For full license and copyright information, please refer to the LICENSE.md file **
** located at the project root, or contact the authors. **
** **
**~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*/
/*
This provides a couple of routines which allowed the time per iteration
to be stored. This is achieved useing the KSPMonitors. The issue with using
these monitors is the petsc support for these is terrible. We need to be
able to access our user monitor context, but petsc only lets you get the
context from the FIRST monitor, which we cannot guarentee will be the one
defined to store the timing information.
To get around this we store the index into the monitor array which our
monitor gets inersted into. This works, but we have no 'nice' way to
recover the user monitor context except via the monitor_index. Thus when
the monitor is set, we return the value of the monitor index. This number
is required whenever you wish to extract the timing information.
*/
#ifndef _GNU_SOURCE
#define _GNU_SOURCE
#endif /* _GNU_SOURCE needed for asprintf */
#include <stdio.h>
#include <stdlib.h>
#include <petsc.h>
#include <petscvec.h>
#include <petscmat.h>
#include <petscksp.h>
#include <StGermain/StGermain.h>
#include <StgDomain/StgDomain.h>
#include "common-driver-utils.h"
#include <petscversion.h>
#if ( (PETSC_VERSION_MAJOR >= 3) && (PETSC_VERSION_MINOR >=3) )
#if (PETSC_VERSION_MINOR >=6)
#include "petsc/private/kspimpl.h"
#else
#include "petsc-private/kspimpl.h"
#endif
#else
#include "private/kspimpl.h"
#endif
struct timed_cvg_ctx {
PetscInt monitor_index;
PetscInt hist_len, hist_len_max;
PetscLogDouble *time_log;
PetscLogDouble time;
PetscReal *r_log;
};
/* ~~~~~~~~~~~~~~~~ SolverMonitor routines ~~~~~~~~~~~~~~~~~~~~~~ */
/*
I shouldn't need to include the residual log, but the petsc one does strange things, when used
with gmres and fgmres. I know it's related to restarts but I just don't get it. This one will
produce the same data as that which is displayed on the screen when you used -ksp_monitor.
*/
#undef __FUNCT__
#define __FUNCT__ "BSSCR_check_validity_of_timing_monitor"
PetscErrorCode BSSCR_check_validity_of_timing_monitor( KSP ksp, PetscInt monitor_index )
{
if( monitor_index < 0 ) {
Stg_SETERRQ1( PETSC_ERR_ARG_WRONG, "Monitor index cannot be negative. You had %D", monitor_index );
}
if( monitor_index >= ksp->numbermonitors ) {
Stg_SETERRQ2( PETSC_ERR_ARG_WRONG, "Monitor index >= number of monitors set (%D). You had %D", ksp->numbermonitors, monitor_index );
}
PetscFunctionReturn(0);
}
#undef __FUNCT__
#define __FUNCT__ "BSSCR_KSPLogHistory"
PetscErrorCode BSSCR_KSPLogHistory(struct timed_cvg_ctx *ctx,PetscReal norm)
{
PetscLogDouble t, time;
PetscGetTime(&t);
time = t - ctx->time;
if (ctx->hist_len==0) {
/* Get reference time and zero first result */
PetscGetTime(&ctx->time);
time = 0.0;
}
if (ctx->r_log && ctx->time_log && ctx->hist_len_max > ctx->hist_len) {
ctx->r_log[ctx->hist_len] = norm;
ctx->time_log[ctx->hist_len] = time;
ctx->hist_len++;
}
PetscFunctionReturn(0);
}
#undef __FUNCT__
#define __FUNCT__ "BSSCR_timed_cvg_test"
PetscErrorCode BSSCR_timed_cvg_test(KSP ksp, int it, PetscReal rnorm, void *mctx)
{
struct timed_cvg_ctx *ctx = (struct timed_cvg_ctx*)(mctx);
BSSCR_KSPLogHistory(ctx,rnorm);
PetscFunctionReturn(0);
}
#undef __FUNCT__
#define __FUNCT__ "BSSCR_KSPLogDestroyMonitor"
PetscErrorCode BSSCR_KSPLogDestroyMonitor(void *_ctx)
{
struct timed_cvg_ctx *ctx = (struct timed_cvg_ctx*)_ctx;
PetscFree( ctx->r_log );
PetscFree( ctx->time_log );
PetscFree( ctx );
PetscFunctionReturn(0);
}
#undef __FUNCT__
#define __FUNCT__ "BSSCR_KSPLogSetMonitor"
PetscErrorCode BSSCR_KSPLogSetMonitor(KSP ksp,PetscInt len,PetscInt *monitor_index)
{
PetscLogDouble *time_log;
PetscReal *r_log;
struct timed_cvg_ctx *ctx;
PetscMalloc( sizeof(PetscLogDouble)*len, &time_log );
PetscMalloc( sizeof(PetscReal)*len, &r_log );
PetscMalloc( sizeof(struct timed_cvg_ctx), &ctx );
ctx->hist_len_max = len;
ctx->hist_len = 0;
ctx->time_log = time_log;
ctx->r_log = r_log;
ctx->monitor_index = ksp->numbermonitors;
*monitor_index = ksp->numbermonitors;
//KSPSetConvergenceTest(ksp,timed_cvg_test,(void*)ctx );
KSPMonitorSet( ksp, BSSCR_timed_cvg_test, (void*)ctx, BSSCR_KSPLogDestroyMonitor );
PetscFunctionReturn(0);
}
#undef __FUNCT__
#define __FUNCT__ "BSSCR_KSPLogGetTimeHistory"
PetscErrorCode BSSCR_KSPLogGetTimeHistory(KSP ksp,PetscInt monitor_index, PetscInt *na,PetscLogDouble **log)
{
struct timed_cvg_ctx *ctx;
PetscInt its;
ctx = (struct timed_cvg_ctx*)ksp->monitorcontext[ monitor_index ];
KSPGetIterationNumber(ksp,&its);
its = its + 1;
*na = PetscMin( (PetscInt)(its), (PetscInt)(ctx->hist_len_max) );
*log = ctx->time_log;
PetscFunctionReturn(0);
}
#undef __FUNCT__
#define __FUNCT__ "BSSCR_KSPLogGetResidualHistory"
PetscErrorCode BSSCR_KSPLogGetResidualHistory(KSP ksp,PetscInt monitor_index, PetscInt *na,PetscReal **rlog)
{
struct timed_cvg_ctx *ctx;
PetscInt its;
ctx = (struct timed_cvg_ctx*)ksp->monitorcontext[ monitor_index ];
KSPGetIterationNumber(ksp,&its);
its = its + 1;
*na = PetscMin( (PetscInt)(its), (PetscInt)(ctx->hist_len_max) );
*rlog = ctx->r_log;
PetscFunctionReturn(0);
}
#undef __FUNCT__
#define __FUNCT__ "BSSCR_KSPLogGetResidualTimeHistory"
PetscErrorCode BSSCR_KSPLogGetResidualTimeHistory(KSP ksp,PetscInt monitor_index, PetscInt *na,PetscReal **rlog,PetscLogDouble **tlog)
{
struct timed_cvg_ctx *ctx;
PetscInt its;
KSPGetIterationNumber(ksp,&its);
ctx = (struct timed_cvg_ctx*)ksp->monitorcontext[ monitor_index ];
its = its + 1;
*na = PetscMin( (PetscInt)(its), (PetscInt)(ctx->hist_len_max) );
*rlog = ctx->r_log;
*tlog = ctx->time_log;
PetscFunctionReturn(0);
}
KSPNormType BS_NO_PC= KSP_NORM_UNPRECONDITIONED;
KSPNormType BS_W_PC= KSP_NORM_PRECONDITIONED;
#undef __FUNCT__
#define __FUNCT__ "BSSCR_KSPGetNormType"
PetscErrorCode BSSCR_KSPGetNormType(KSP ksp, KSPNormType *normtype) {
*normtype = ksp->normtype;
return(0);
}
#undef __FUNCT__
#define __FUNCT__ "BSSCR_KSPLogSolve"
PetscErrorCode BSSCR_KSPLogSolve(PetscViewer v,PetscInt monitor_index, KSP ksp)
{
Vec b,u;
PetscInt i;
KSPType type;
PetscReal b_nrm, *rlog;
PC pc;
PetscLogDouble *log;
PetscInt nits;
KSPNormType ntype;
PCSide side;
PetscTruth has_unpc_config, ksp_matches;
const char *list[] = { "cg" , "bicg" , "bcgs" , "gmres" , "fgmres", "minres", "lgmres", 0 };
const PCSide pc_side[] = { PC_LEFT, PC_LEFT, PC_LEFT, PC_RIGHT, PC_RIGHT, PC_LEFT , PC_RIGHT, 0 };
const KSPNormType norm_type[] = { BS_NO_PC , BS_NO_PC , BS_NO_PC , BS_W_PC , BS_NO_PC , BS_NO_PC , BS_W_PC , 0 };
KSPGetRhs( ksp, &b );
KSPGetSolution( ksp, &u );
KSPGetType( ksp, &type );
BSSCR_KSPGetNormType( ksp, &ntype );
KSPGetPreconditionerSide( ksp, &side );
has_unpc_config = PETSC_FALSE;
i = 0;
while (list[i]) {
PetscStrcmp( "fgmres", type, &ksp_matches );
if (ksp_matches) {
has_unpc_config = PETSC_TRUE;
break;
}
PetscStrcmp( list[i],type,&ksp_matches );
if (ksp_matches) {
if( pc_side[i] == side && ntype == norm_type[i] ) {
has_unpc_config = PETSC_TRUE;
break;
}
}
i++;
}
if (has_unpc_config) {
PetscViewerASCIIPrintf( v, "[%s] Detected options consistent with unpreconditioned norm: using side=%d, norm_type=%d \n", type, side, ntype );
}
BSSCR_KSPLogGetResidualTimeHistory(ksp,monitor_index, &nits,&rlog,&log);
if (!rlog || !log) {
Stg_SETERRQ( PETSC_ERR_ORDER, "You need to call BSSCR_KSPLogSetMonitor() before BSSCR_KSPLogGetResidualTimeHistory()" );
}
if (!has_unpc_config) {
Vec pc_b;
VecDuplicate( u, &pc_b );
KSPGetPC( ksp, &pc );
PCApply( pc, b, pc_b );
VecNorm( pc_b, NORM_2, &b_nrm );
Stg_VecDestroy(&pc_b );
PetscViewerASCIIPrintf( v, "# it |Qr| |Qr0| |f| |Qr|/|Qr0| log10(Qr/Qr0) |Qr|/|Qf| log10(Qr/Qf) time\n" );
}
else if (has_unpc_config) {
VecNorm( b, NORM_2, &b_nrm );
PetscViewerASCIIPrintf( v, "# it |r| |r0| |f| |r|/|r0| log10(r/r0) |r|/|f| log10(r/f) time\n" );
}
for( i=0; i<nits; i++ ) {
PetscViewerASCIIPrintf( v, "%1.4d %14.12e %14.12e %14.12e %14.12e %14.12e %14.12e %14.12e %14.12e\n",
i, rlog[i],rlog[0],b_nrm, rlog[i]/rlog[0],log10(rlog[i]/rlog[0]), rlog[i]/b_nrm,log10(rlog[i]/b_nrm), log[i] );
}
PetscFunctionReturn(0);
}
#undef __FUNCT__
#define __FUNCT__ "BSSCR_BSSCR_KSPLogSolveSummary"
PetscErrorCode BSSCR_BSSCR_KSPLogSolveSummary(PetscViewer v,PetscInt monitor_index, KSP ksp)
{
KSPConvergedReason reason;
char *reas;
PetscReal *rlog;
PetscLogDouble *log;
PetscInt nits;
KSPGetConvergedReason( ksp, &reason );
if( reason == KSP_CONVERGED_RTOL )
asprintf(&reas, "KSP_CONVERGED_RTOL" );
else if( reason == KSP_CONVERGED_ATOL )
asprintf(&reas, "KSP_CONVERGED_ATOL" );
else if( reason == KSP_CONVERGED_ITS )
asprintf(&reas, "KSP_CONVERGED_ITS" );
else if( reason == KSP_DIVERGED_ITS )
asprintf(&reas, "KSP_DIVERGED_ITS" );
else if( reason == KSP_DIVERGED_DTOL )
asprintf(&reas, "KSP_DIVERGED_DTOL" );
else if( reason == KSP_DIVERGED_INDEFINITE_PC )
asprintf(&reas, "KSP_DIVERGED_INDEFINITE_PC" );
else {
Stg_SETERRQ( PETSC_ERR_SUP, "unknown convergence reason detected");
}
BSSCR_KSPLogGetResidualTimeHistory(ksp,monitor_index, &nits,&rlog,&log);
if (!rlog || !log) {
Stg_SETERRQ( PETSC_ERR_ORDER, "You need to call BSSCR_KSPLogSetMonitor() before BSSCR_KSPLogGetResidualTimeHistory()" );
}
PetscViewerASCIIPrintf( v, "\n");
PetscViewerASCIIPrintf( v, "# ===========================================================\n");
PetscViewerASCIIPrintf( v, "# KSP summary \n" );
PetscViewerASCIIPrintf( v, "# time (its) [rnorm] reason \n" );
PetscViewerASCIIPrintf( v, "# %.2f (%d) %.2e %s \n", log[nits-1], nits-1, rlog[nits-1], reas );
PetscViewerASCIIPrintf( v, "# ===========================================================\n");
PetscFunctionReturn(0);
}
| {
"alphanum_fraction": 0.6675988069,
"avg_line_length": 30.916426513,
"ext": "c",
"hexsha": "b147a53e1d785adc194f138f2616acaeff872b90",
"lang": "C",
"max_forks_count": 68,
"max_forks_repo_forks_event_max_datetime": "2021-08-25T04:54:26.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-12-14T21:57:46.000Z",
"max_forks_repo_head_hexsha": "5c8acc17fa4d97e86a62b13b8bfb2af6e81a8ee4",
"max_forks_repo_licenses": [
"CC-BY-4.0"
],
"max_forks_repo_name": "longgangfan/underworld2",
"max_forks_repo_path": "underworld/libUnderworld/Solvers/KSPSolvers/src/BSSCR/timed_residual_hist.c",
"max_issues_count": 561,
"max_issues_repo_head_hexsha": "5c8acc17fa4d97e86a62b13b8bfb2af6e81a8ee4",
"max_issues_repo_issues_event_max_datetime": "2022-03-22T23:37:29.000Z",
"max_issues_repo_issues_event_min_datetime": "2015-09-29T06:05:50.000Z",
"max_issues_repo_licenses": [
"CC-BY-4.0"
],
"max_issues_repo_name": "longgangfan/underworld2",
"max_issues_repo_path": "underworld/libUnderworld/Solvers/KSPSolvers/src/BSSCR/timed_residual_hist.c",
"max_line_length": 187,
"max_stars_count": 116,
"max_stars_repo_head_hexsha": "5c8acc17fa4d97e86a62b13b8bfb2af6e81a8ee4",
"max_stars_repo_licenses": [
"CC-BY-4.0"
],
"max_stars_repo_name": "longgangfan/underworld2",
"max_stars_repo_path": "underworld/libUnderworld/Solvers/KSPSolvers/src/BSSCR/timed_residual_hist.c",
"max_stars_repo_stars_event_max_datetime": "2022-03-22T04:12:38.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-09-28T10:30:55.000Z",
"num_tokens": 3571,
"size": 10728
} |
/*
* BRAINS
* (B)LR (R)everberation-mapping (A)nalysis (I)n AGNs with (N)ested (S)ampling
* Yan-Rong Li, liyanrong@ihep.ac.cn
* Thu, Aug 4, 2016
*/
/*! \file dnest_sa.c
* \brief run dnest sampling for sa analysis.
*/
#ifdef SA
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <stddef.h>
#include <math.h>
#include <float.h>
#include <string.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
#include <gsl/gsl_interp.h>
#include <mpi.h>
#include "brains.h"
DNestFptrSet *fptrset_sa;
int dnest_sa(int argc, char **argv)
{
int i;
double logz_sa;
set_sa_blr_model();
num_params_blr = 0; /* RM parameter numbers */
num_params_sa_blr = num_params_sa_blr_model + num_params_sa_extpar;
num_params_blr_tot = num_params_sa_blr;
num_params_sa = num_params_sa_blr;
num_params = num_params_sa;
par_fix = (int *) malloc(num_params * sizeof(int));
par_fix_val = (double *) malloc(num_params * sizeof(double));
par_range_model = malloc( num_params * sizeof(double *));
par_prior_gaussian = malloc( num_params * sizeof(double *));
for(i=0; i<num_params; i++)
{
par_range_model[i] = malloc(2*sizeof(double));
par_prior_gaussian[i] = malloc(2*sizeof(double));
}
par_prior_model = malloc( num_params * sizeof(int));
fptrset_sa = dnest_malloc_fptrset();
/* setup functions used for dnest*/
fptrset_sa->from_prior = from_prior_sa;
fptrset_sa->print_particle = print_particle_sa;
fptrset_sa->restart_action = restart_action_sa;
fptrset_sa->accept_action = accept_action_sa;
fptrset_sa->kill_action = kill_action_sa;
fptrset_sa->perturb = perturb_sa;
fptrset_sa->read_particle = read_particle_sa;
fptrset_sa->log_likelihoods_cal_initial = log_likelihoods_cal_initial_sa;
fptrset_sa->log_likelihoods_cal_restart = log_likelihoods_cal_restart_sa;
fptrset_sa->log_likelihoods_cal = log_likelihoods_cal_sa;
set_par_range_sa();
set_par_fix_sa_blrmodel();
for(i=num_params_sa_blr_model; i<num_params; i++)
{
par_fix[i] = 0;
par_fix_val[i] = -DBL_MAX;
}
/* fix DA */
par_fix[num_params_sa_blr_model] = 1;
par_fix_val[num_params_sa_blr_model] = log(550.0);
/* fix FA */
par_fix[num_params_sa_blr_model+2] = 1;
par_fix_val[num_params_sa_blr_model+2] = log(1.0);
print_par_names_sa();
force_update = parset.flag_force_update;
if(parset.flag_para_name != 1)
logz_sa = dnest(argc, argv, fptrset_sa, num_params, dnest_options_file);
dnest_free_fptrset(fptrset_sa);
return 0;
}
void set_par_range_sa()
{
int i;
/* setup parameter range, BLR parameters first */
for(i=0; i<num_params_sa_blr_model; i++)
{
par_range_model[i][0] = sa_blr_range_model[i][0];
par_range_model[i][1] = sa_blr_range_model[i][1];
par_prior_model[i] = UNIFORM;
par_prior_gaussian[i][0] = 0.0;
par_prior_gaussian[i][1] = 0.0;
}
/* sa extra parameters */
for(i=num_params_sa_blr_model; i<num_params_sa; i++)
{
par_range_model[i][0] = sa_extpar_range[i-num_params_sa_blr_model][0];
par_range_model[i][1] = sa_extpar_range[i-num_params_sa_blr_model][1];
par_prior_model[i] = UNIFORM;
par_prior_gaussian[i][0] = 0.0;
par_prior_gaussian[i][1] = 0.0;
}
return;
}
/*!
* print names and prior ranges for parameters
*
*/
void print_par_names_sa()
{
if(thistask != roottask)
return;
int i, j;
FILE *fp;
char fname[BRAINS_MAX_STR_LENGTH], str_fmt[BRAINS_MAX_STR_LENGTH];
sprintf(fname, "%s/%s", parset.file_dir, "data/para_names_sa.txt");
fp = fopen(fname, "w");
if(fp == NULL)
{
fprintf(stderr, "# Error: Cannot open file %s.\n", fname);
exit(0);
}
strcpy(str_fmt, "%4d %-15s %10.6f %10.6f %4d %4d %15.6e\n");
printf("# Print parameter name in %s\n", fname);
fprintf(fp, "#*************************************************\n");
fprint_version(fp);
fprintf(fp, "#*************************************************\n");
fprintf(fp, "%4s %-15s %10s %10s %4s %4s %15s\n", "#", "Par", "Min", "Max", "Prior", "Fix", "Val");
i=-1;
for(j=0; j<num_params_sa_blr_model; j++)
{
i++;
fprintf(fp, str_fmt, i, "SA BLR model", par_range_model[i][0], par_range_model[i][1], par_prior_model[i],
par_fix[i], par_fix_val[i]);
}
for(j=0; j<num_params_sa_extpar; j++)
{
i++;
fprintf(fp, str_fmt, i, "SA ExtPar", par_range_model[i][0], par_range_model[i][1], par_prior_model[i],
par_fix[i], par_fix_val[i]);
}
fclose(fp);
return;
}
/*!
* this function generates a sample from prior.
*/
void from_prior_sa(void *model)
{
int i;
double *pm = (double *)model;
for(i=0; i<num_params; i++)
{
if(par_prior_model[i] == GAUSSIAN)
{
pm[i] = dnest_randn()*par_prior_gaussian[i][1] + par_prior_gaussian[i][0];
dnest_wrap(&pm[i], par_range_model[i][0], par_range_model[i][1]);
}
else
{
pm[i] = par_range_model[i][0] + dnest_rand() * (par_range_model[i][1] - par_range_model[i][0]);
}
}
/* cope with fixed parameters */
for(i=0; i<num_params; i++)
{
if(par_fix[i] == 1)
pm[i] = par_fix_val[i];
}
which_parameter_update = -1;
return;
}
/*!
* this function calculates likelihood at initial step.
*/
double log_likelihoods_cal_initial_sa(const void *model)
{
double logL;
logL = prob_sa(model);
return logL;
}
/*!
* this function calculates likelihood at initial step.
*/
double log_likelihoods_cal_restart_sa(const void *model)
{
double logL;
logL = prob_sa(model);
return logL;
}
/*!
* this function calculates likelihood.
*/
double log_likelihoods_cal_sa(const void *model)
{
double logL;
logL = prob_sa(model);
return logL;
}
/*!
* this function prints out parameters.
*/
void print_particle_sa(FILE *fp, const void *model)
{
int i;
double *pm = (double *)model;
for(i=0; i<num_params; i++)
{
fprintf(fp, "%e ", pm[i] );
}
fprintf(fp, "\n");
return;
}
/*!
* This function read the particle from the file.
*/
void read_particle_sa(FILE *fp, void *model)
{
int j;
double *psample = (double *)model;
for(j=0; j < dnest_num_params; j++)
{
if(fscanf(fp, "%lf", psample+j) < 1)
{
printf("%f\n", *psample);
fprintf(stderr, "#Error: Cannot read file %s.\n", options.sample_file);
exit(0);
}
}
return;
}
/*!
* this function perturbs parameters.
*/
double perturb_sa(void *model)
{
double *pm = (double *)model;
double logH = 0.0, limit1, limit2, width;
int which, which_level, count_saves;
/*
* fixed parameters need not to update
* perturb important parameters more frequently
*/
do
{
which = dnest_rand_int(num_params);
}while(par_fix[which] == 1);
which_parameter_update = which;
/* level-dependent width */
count_saves = dnest_get_count_saves();
which_level_update = dnest_get_which_level_update();
which_level = which_level_update > (size_levels-10)?(size_levels-10):which_level_update;
if( which_level > 0 && count_saves > 1000)
{
limit1 = limits[(which_level-1) * num_params *2 + which *2];
limit2 = limits[(which_level-1) * num_params *2 + which *2 + 1];
width = (limit2 - limit1);
width /= (3*2.35);
}
else
{
limit1 = par_range_model[which][0];
limit2 = par_range_model[which][1];
width = (par_range_model[which][1] - par_range_model[which][0]);
width /= (2.35);
}
if(par_prior_model[which] == GAUSSIAN)
{
logH -= (-0.5*pow((pm[which] - par_prior_gaussian[which][0])/par_prior_gaussian[which][1], 2.0) );
pm[which] += dnest_randh() * width;
dnest_wrap(&pm[which], par_range_model[which][0], par_range_model[which][1]);
//dnest_wrap(&pm[which], limit1, limit2);
logH += (-0.5*pow((pm[which] - par_prior_gaussian[which][0])/par_prior_gaussian[which][1], 2.0) );
}
else
{
pm[which] += dnest_randh() * width;
dnest_wrap(&(pm[which]), par_range_model[which][0], par_range_model[which][1]);
//dnest_wrap(&pm[which], limit1, limit2);
}
return logH;
}
/*!
* this function calculates likelihood.
*/
double log_likelihoods_cal_sa_exam(const void *model)
{
return 0.0;
}
/*
* action when a particle's move is accepted.
* usually store some values with no need to recompute.
*/
void accept_action_sa()
{
return;
}
/*
* action when particle i is killed in cdnest sampling.
* particle i_copy's properties is copyed to particle i.
*/
void kill_action_sa(int i, int i_copy)
{
return;
}
#endif | {
"alphanum_fraction": 0.6508478568,
"avg_line_length": 23.7206703911,
"ext": "c",
"hexsha": "d2c0a469bd3d40f58799a741fa6d55f292212a9e",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "b81cec02a1902df1e544542a970b66d9916a7496",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "yzxamos/BRAINS",
"max_forks_repo_path": "src/dnest_sa.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "b81cec02a1902df1e544542a970b66d9916a7496",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "yzxamos/BRAINS",
"max_issues_repo_path": "src/dnest_sa.c",
"max_line_length": 109,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "b81cec02a1902df1e544542a970b66d9916a7496",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "yzxamos/BRAINS",
"max_stars_repo_path": "src/dnest_sa.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 2559,
"size": 8492
} |
#pragma once
#include "memcached/types.h"
#include "slabs.h"
#include <gsl/gsl-lite.h>
#include <atomic>
#include <cstddef>
#include <cstring>
/*
* You should not try to aquire any of the item locks before calling these
* functions.
*/
typedef struct _hash_item {
struct _hash_item* next;
struct _hash_item* prev;
struct _hash_item* h_next; /* hash chain next */
/**
* The unique identifier for this item (it is guaranteed to be unique
* per key, which means that a two different version of a document
* cannot have the same CAS value (This is not true after a server
* restart given that default_bucket is an in-memory bucket).
*/
uint64_t cas;
/** least recent access */
rel_time_t time;
/** When the item will expire (relative to process startup) */
rel_time_t exptime;
/**
* When the current lock for the object expire. If locktime < "current
* time" the item isn't locked anymore (timed out). If locktime >=
* "current time" the object is locked.
*/
rel_time_t locktime;
/** The total size of the data (in bytes) */
uint32_t nbytes;
/** Flags associated with the item (in network byte order) */
uint32_t flags;
/**
* The number of entities holding a reference to this item object (we
* operate in a copy'n'write context so it is always safe for all of
* our clients to share an existing object, but we need the refcount
* so that we know when we can release the object.
*/
uint16_t refcount;
/** Intermal flags used by the engine.*/
std::atomic<uint8_t> iflag;
/** which slab class we're in */
uint8_t slabs_clsid;
/** to identify the type of the data */
uint8_t datatype;
// There is 3 spare bytes due to alignment
} hash_item;
/*
The structure of the key we hash with.
This is a combination of the bucket index and the client's key.
To respect the memcached protocol we support keys > 250, even
though the current frontend doesn't.
Keys upto 128 bytes long will be carried wholly on the stack,
larger keys go on the heap.
*/
typedef struct _hash_key_sized {
bucket_id_t bucket_index;
uint8_t client_key[128];
} hash_key_sized;
typedef struct _hash_key_data {
bucket_id_t bucket_index;
uint8_t client_key[1];
} hash_key_data;
typedef struct _hash_key_header {
uint16_t len; /* length of the hash key (bucket_index+client) */
hash_key_data* full_key; /* points to hash_key::key_storage or a malloc blob*/
} hash_key_header;
typedef struct _hash_key {
hash_key_header header;
hash_key_sized key_storage;
} hash_key;
static inline uint8_t* hash_key_get_key(const hash_key* key) {
return (uint8_t*)key->header.full_key;
}
static inline bucket_id_t hash_key_get_bucket_index(const hash_key* key) {
return key->header.full_key->bucket_index;
}
static inline void hash_key_set_bucket_index(hash_key* key,
bucket_id_t bucket_index) {
key->header.full_key->bucket_index = bucket_index;
}
static inline uint16_t hash_key_get_key_len(const hash_key* key) {
return key->header.len;
}
static inline void hash_key_set_len(hash_key* key, uint16_t len) {
key->header.len = len;
}
static inline uint8_t* hash_key_get_client_key(const hash_key* key) {
return key->header.full_key->client_key;
}
static inline uint16_t hash_key_get_client_key_len(const hash_key* key) {
return hash_key_get_key_len(key) -
gsl::narrow<uint16_t>(sizeof(key->header.full_key->bucket_index));
}
static inline void hash_key_set_client_key(hash_key* key,
const void* client_key,
const size_t client_key_len) {
memcpy(key->header.full_key->client_key, client_key, client_key_len);
}
/*
* return the bytes needed to store the hash_key structure
* in a single contiguous allocation.
*/
static inline size_t hash_key_get_alloc_size(const hash_key* key) {
return offsetof(hash_key, key_storage) + hash_key_get_key_len(key);
}
typedef struct {
unsigned int evicted;
unsigned int evicted_nonzero;
rel_time_t evicted_time;
unsigned int outofmemory;
unsigned int tailrepairs;
unsigned int reclaimed;
} itemstats_t;
struct items {
hash_item *heads[POWER_LARGEST];
hash_item *tails[POWER_LARGEST];
itemstats_t itemstats[POWER_LARGEST];
unsigned int sizes[POWER_LARGEST];
/*
* serialise access to the items data
*/
std::mutex lock;
};
/**
* Allocate and initialize a new item structure
* @param engine handle to the storage engine
* @param key the key for the new item
* @param nkey the number of bytes in the key
* @param flags the flags in the new item
* @param exptime when the object should expire
* @param nbytes the number of bytes in the body for the item
* @return a pointer to an item on success NULL otherwise
*/
hash_item *item_alloc(struct default_engine *engine,
const void *key, const size_t nkey, int flags,
rel_time_t exptime, int nbytes, const void *cookie,
uint8_t datatype);
/**
* Get an item from the cache
*
* @param engine handle to the storage engine
* @param cookie connection cookie
* @param key the key for the item to get
* @param nkey the number of bytes in the key
* @param state Only return documents in this state
* @return pointer to the item if it exists or NULL otherwise
*/
hash_item* item_get(struct default_engine* engine,
const void* cookie,
const void* key,
const size_t nkey,
const DocStateFilter state);
/**
* Get an item from the cache using a hash_key
*
* @param engine handle to the storage engine
* @param cookie connection cookie
* @param key to lookup
* @param state Only return documents in this state
* @return pointer to the item if it exists or NULL otherwise
*/
hash_item* item_get(struct default_engine* engine,
const void* cookie,
const hash_key& key,
const DocStateFilter state);
/**
* Get an item from the cache and acquire the lock.
*
* @param engine handle to the storage engine
* @param cookie connection cookie
* @param where to return the item (if found)
* @param key the key for the item to get
* @param nkey the number of bytes in the key
* @param locktime when the item expire
* @return ENGINE_SUCCESS for success
*/
ENGINE_ERROR_CODE item_get_locked(struct default_engine* engine,
const void* cookie,
hash_item** it,
const void* key,
const size_t nkey,
rel_time_t locktime);
/**
* Get and touch an item
*
* @param engine handle to the storage engine
* @param cookie connection cookie
* @param where to return the item (if found)
* @param key the key for the item to get
* @param nkey the number of bytes in the key
* @param exptime The new expiry time
* @return ENGINE_SUCCESS for success
*/
ENGINE_ERROR_CODE item_get_and_touch(struct default_engine* engine,
const void* cookie,
hash_item** it,
const void* key,
const size_t nkey,
rel_time_t exptime);
/**
* Unlock an item in the cache
*
* @param engine handle to the storage engine
* @param cookie connection cookie
* @param key the key for the item to unlock
* @param nkey the number of bytes in the key
* @param cas value for the locked value
* @return ENGINE_SUCCESS for success
*/
ENGINE_ERROR_CODE item_unlock(struct default_engine* engine,
const void* cookie,
const void* key,
const size_t nkey,
uint64_t cas);
/**
* Reset the item statistics
* @param engine handle to the storage engine
*/
void item_stats_reset(struct default_engine *engine);
/**
* Get item statitistics
* @param engine handle to the storage engine
* @param add_stat callback provided by the core used to
* push statistics into the response
* @param cookie cookie provided by the core to identify the client
*/
void item_stats(struct default_engine* engine,
const AddStatFn& add_stat,
const void* cookie);
/**
* Get detaild item statitistics
* @param engine handle to the storage engine
* @param add_stat callback provided by the core used to
* push statistics into the response
* @param cookie cookie provided by the core to identify the client
*/
void item_stats_sizes(struct default_engine* engine,
const AddStatFn& add_stat,
const void* cookie);
/**
* Flush expired items from the cache
* @param engine handle to the storage engine
*/
void item_flush_expired(struct default_engine *engine);
/**
* Release our reference to the current item
* @param engine handle to the storage engine
* @param it the item to release
*/
void item_release(struct default_engine *engine, hash_item *it);
/**
* Unlink the item from the hash table (make it inaccessible)
* @param engine handle to the storage engine
* @param it the item to unlink
*/
void item_unlink(struct default_engine *engine, hash_item *it);
/**
* Unlink the item from the hash table (make it inaccessible),
* but only if the CAS value in the item is the same as the
* one in the hash table (two different connections may operate
* on the same objects, so the cas value for the value in the
* hashtable may be different than the items value. We need
* to have exclusive access to the hashtable to do the actual
* unlink)
*
* @param engine handle to the storage engine
* @param it the item to unlink
*/
ENGINE_ERROR_CODE safe_item_unlink(struct default_engine *engine,
hash_item *it);
/**
* Store an item in the cache
* @param engine handle to the storage engine
* @param item the item to store
* @param cas the cas value (OUT)
* @param operation what kind of store operation is this (ADD/SET etc)
* @param document_state the state of the document to store
* @return ENGINE_SUCCESS on success
*
* @todo should we refactor this into hash_item ** and remove the cas
* there so that we can get it from the item instead?
*/
ENGINE_ERROR_CODE store_item(struct default_engine *engine,
hash_item *item,
uint64_t *cas,
ENGINE_STORE_OPERATION operation,
const void *cookie,
const DocumentState document_state);
/**
* Run a single scrub loop for the engine.
* @param engine handle to the storage engine
*/
void item_scrubber_main(struct default_engine *engine);
/**
* Start the item scrubber for the engine
* @param engine handle to the storage engine
* @return true if the scrubber has been invoked
*/
bool item_start_scrub(struct default_engine *engine);
| {
"alphanum_fraction": 0.6599911778,
"avg_line_length": 32.0197740113,
"ext": "h",
"hexsha": "3177d49768358de4ada0d7cd5410612f663b6caf",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2020-01-15T16:52:37.000Z",
"max_forks_repo_forks_event_min_datetime": "2020-01-15T16:52:37.000Z",
"max_forks_repo_head_hexsha": "40256dca6bf77fb4bcc18e8ef7d9b8f991bf4e45",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "paolococchi/kv_engine",
"max_forks_repo_path": "engines/default_engine/items.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "40256dca6bf77fb4bcc18e8ef7d9b8f991bf4e45",
"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": "paolococchi/kv_engine",
"max_issues_repo_path": "engines/default_engine/items.h",
"max_line_length": 82,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "33fb1ab2c9787f55555e5f7edea38807b3dbc371",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "hrajput89/kv_engine",
"max_stars_repo_path": "engines/default_engine/items.h",
"max_stars_repo_stars_event_max_datetime": "2019-06-13T07:33:09.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-06-13T07:33:09.000Z",
"num_tokens": 2487,
"size": 11335
} |
/* ///////////////////////////////////////////////////////////////////// */
/*!
\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 <math.h>
#include "coolit.h"
#include <stdbool.h>
//#include <gsl.h>
double mu, Rcl;
double rho0, P0, cs0, v0, s0, cool_0, tcool0, r_crit;
int q = 2, 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 = (VX1, VX2, VX3) are
* the three components of velocity, and so forth.
*
*********************************************************************** */
{
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];
mu = MeanMolecularWeight(v);
rho0 = n0*mu*CONST_mp; //g cm^-3
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))*CONST_kB*T0/(n0*cool_0); //s
r_crit = -q*v0*g_gamma*tcool0; //cm
Rcl = singular*r_crit/UNIT_LENGTH; // code units (pc usually)
//double steep=20., f=0.007;
//double shift = steep*atanh(2.*f*Tcl/(Tw-Tcl)-1);
if (prank==0 && counter==0) printf("T0=%.1e\tM0=%.1f\tn0=%.2f\tchi=%d\tsingular=%.2f\n",T0,Mach0, n0, (int)chi, singular);
if (prank==0 && counter==0) printf("rho0=%.1e\t\tP0=%.1e\t\tv0=%.2e\t\tr_crit=%.2e pc\tRcl=%.2e pc\t\ttcool0=%.2e\n",rho0/UNIT_DENSITY,P0/(UNIT_DENSITY*pow(UNIT_VELOCITY,2)), v0/UNIT_VELOCITY, r_crit/UNIT_LENGTH, Rcl, tcool0/(CONST_PI*1e12));
if (prank==0 && counter==0) printf("x from %.2f to %.2f\n",g_domBeg[IDIR],g_domEnd[IDIR],x1);
if (prank==0 && (x1<g_domBeg[IDIR] || x1>g_domEnd[IDIR])) printf("%.2f pc\n",x1);
counter++;
double T = (x1/Rcl<1.)?T0/chi:T0; //Tcl + (Tw-Tcl)/2. *(1+ tanh(x1/steep+shift));
//T = Tcl + (chi-1.)*Tcl*(x1-g_domBeg[IDIR])/(g_domEnd[IDIR]-g_domBeg[IDIR]); //a linear temperature going from cooler to hotter
v[RHO] = (x1/Rcl<1.)?chi*n0*mu*CONST_mp/UNIT_DENSITY:n0*mu*CONST_mp/UNIT_DENSITY;
EXPAND(
v[VX1] = 0.0;,
v[VX2] = 0.0;,
v[VX3] = 0.0;);
//#if HAVE_ENERGY
v[PRS] = P0/(UNIT_DENSITY*pow(UNIT_VELOCITY,2));
//#endif
v[TRC] = 1.0;
//Pwind = P/(UNIT_DENSITY*UNIT_VELOCITY*UNIT_VELOCITY);
//Dwind = ncl*mu*mp/chi/UNIT_DENSITY;
#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().
*
*
*********************************************************************** */
{
}
/* ********************************************************************* */
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[VX1][k][j][i] = d->Vc[VX1][k][j][IBEG]; //outflow velocity
d->Vc[RHO][k][j][i] = 3.*rho0/UNIT_DENSITY;
d->Vc[PRS][k][j][i] = 1.52*P0/(UNIT_DENSITY*pow(UNIT_VELOCITY,2));
//d->Vc[VX1][k][j][i] = 0.14*sqrt(g_gamma*d->Vc[PRS][k][j][i]/d->Vc[RHO][k][j][i]);
}
}else if (side == X1_END){
BOX_LOOP(box,k,j,i) {
d->Vc[VX1][k][j][i] = d->Vc[VX1][k][j][IEND]; //outflow velocity
d->Vc[RHO][k][j][i] = 0.02*rho0/UNIT_DENSITY;
d->Vc[PRS][k][j][i] = 1.12*P0/(UNIT_DENSITY*pow(UNIT_VELOCITY,2));
//d->Vc[VX1][k][j][i] = 0.*sqrt(g_gamma*d->Vc[PRS][k][j][i]/d->Vc[RHO][k][j][i]);
}
}
/*
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[VX1][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[VX1][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.5299904792,
"avg_line_length": 35.2723880597,
"ext": "c",
"hexsha": "eaf0308a04f411d9cd46c18ed7a3cfb1153fd4af",
"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/Spherical_CF/init - Copy.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/Spherical_CF/init - Copy.c",
"max_line_length": 244,
"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/Spherical_CF/init - Copy.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": 3008,
"size": 9453
} |
/*
* Copyright (c) 2011-2013 University of Texas at Austin. All rights reserved.
*
* $COPYRIGHT$
*
* Additional copyrights may follow
*
* This file is part of PerfExpert.
*
* PerfExpert is free software: you can redistribute it and/or modify it under
* the terms of the The University of Texas at Austin Research License
*
* PerfExpert 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.
*
* Authors: Leonardo Fialho and Ashay Rane
*
* $HEADER$
*/
#ifndef HISTOGRAM_H_
#define HISTOGRAM_H_
#include <algorithm>
#include <gsl/gsl_histogram.h>
#include "analysis_defs.h"
bool pair_sort(const pair_t& p1, const pair_t& p2);
int flatten_and_sort_histogram(gsl_histogram*& hist, pair_list_t& pair_list);
int create_histogram_if_null(gsl_histogram*& hist, size_t bins);
#endif /* HISTOGRAM_H_ */
| {
"alphanum_fraction": 0.7465388711,
"avg_line_length": 25.3783783784,
"ext": "h",
"hexsha": "019cfa5c7ffb6d0fc74e9461bb97ddf7b1c6fc43",
"lang": "C",
"max_forks_count": 11,
"max_forks_repo_forks_event_max_datetime": "2020-08-18T03:53:19.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-01-23T15:41:40.000Z",
"max_forks_repo_head_hexsha": "a03b13db9ac83e992e1c5cc3b6e45e52c266fe30",
"max_forks_repo_licenses": [
"BSD-4-Clause-UC"
],
"max_forks_repo_name": "roystgnr/perfexpert",
"max_forks_repo_path": "tools/macpo/analyze/include/histogram.h",
"max_issues_count": 15,
"max_issues_repo_head_hexsha": "a03b13db9ac83e992e1c5cc3b6e45e52c266fe30",
"max_issues_repo_issues_event_max_datetime": "2018-04-18T16:08:41.000Z",
"max_issues_repo_issues_event_min_datetime": "2015-10-07T20:52:05.000Z",
"max_issues_repo_licenses": [
"BSD-4-Clause-UC"
],
"max_issues_repo_name": "roystgnr/perfexpert",
"max_issues_repo_path": "tools/macpo/analyze/include/histogram.h",
"max_line_length": 80,
"max_stars_count": 28,
"max_stars_repo_head_hexsha": "a03b13db9ac83e992e1c5cc3b6e45e52c266fe30",
"max_stars_repo_licenses": [
"BSD-4-Clause-UC"
],
"max_stars_repo_name": "roystgnr/perfexpert",
"max_stars_repo_path": "tools/macpo/analyze/include/histogram.h",
"max_stars_repo_stars_event_max_datetime": "2021-09-27T16:23:36.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-05-05T15:54:25.000Z",
"num_tokens": 231,
"size": 939
} |
#include <stdio.h>
#include <gsl/gsl_vector.h>
int
main (void)
{
int i;
gsl_vector * v = gsl_vector_alloc (3);
for (i = 0; i < 3; i++)
{
gsl_vector_set (v, i, 1.23 + i);
}
for (i = 0; i < 100; i++) /* OUT OF RANGE ERROR */
{
printf ("v_%d = %g\n", i, gsl_vector_get (v, i));
}
gsl_vector_free (v);
return 0;
}
| {
"alphanum_fraction": 0.5055865922,
"avg_line_length": 15.5652173913,
"ext": "c",
"hexsha": "27462b00c2212d259699af67ea7b8a0147c57347",
"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/vector.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/vector.c",
"max_line_length": 55,
"max_stars_count": 64,
"max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "manggoguy/parsec-modified",
"max_stars_repo_path": "pkgs/libs/gsl/src/doc/examples/vector.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": 133,
"size": 358
} |
/*
** estimate false discovery rate based on histograms
** input histograms are generated by "vted"
**
** Ref: Lohmann et al (2016) PLoS One, 11(6):e0158185
**
** G.Lohmann, MPI-KYB, Jan 2015
*/
#include <viaio/VImage.h>
#include <viaio/Vlib.h>
#include <viaio/mu.h>
#include <viaio/option.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_histogram.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
#include <gsl/gsl_cdf.h>
#include <gsl/gsl_math.h>
#define SQR(x) ((x)*(x))
#define ABS(x) ((x) > 0 ? (x) : -(x))
#define HMIN 0
#define HMAX 1.001
#define NBINS 10000
size_t CountLines(FILE *fp)
{
char ch;
size_t numlines=0;
while(!feof(fp)) {
ch = fgetc(fp);
if(ch == '\n') {
numlines++;
}
}
rewind(fp);
return numlines;
}
void ReadTxtHist(char *filename,gsl_histogram *hist)
{
FILE *fp=fopen(filename,"r");
if (!fp) VError("err opening %s",filename);
size_t nbins = CountLines(fp);
if (nbins != (size_t)NBINS)
VError(" inconsistent bins: %lu",gsl_histogram_bins (hist));
size_t i=0;
double lower=0,hz=0,mx=0;
for (i=0; i<nbins; i++) {
if (fscanf(fp,"%lf %lf %lf",&lower,&hz,&mx) != 3) VError(" read error");
if (lower < HMIN || lower >= HMAX) VError(" value out of histogram range: %f",lower);
hist->bin[i] = mx;
}
fclose(fp);
}
int main(int argc, char *argv[])
{
static VString realfilename = "";
static VString nullfilename = "";
static VString outfilename = "";
static VFloat alpha = 0.05;
static VOptionDescRec options[] = {
{"real",VStringRepn,1,(VPointer) &realfilename,VRequiredOpt,NULL,"input real histogram file"},
{"null",VStringRepn,1,(VPointer) &nullfilename,VRequiredOpt,NULL,"input null histogram file"},
{"out",VStringRepn,1,(VPointer) &outfilename,VRequiredOpt,NULL,"output txt file"},
{"alpha",VFloatRepn,1,(VPointer) &alpha,VOptionalOpt,NULL,"alpha level"},
};
double lower=0,upper=0,tiny=1.0e-8;
long i;
VParseFilterCmd(VNumber(options),options,argc,argv,NULL,NULL);
gsl_set_error_handler_off();
/* ini histogram structs */
size_t nbins = NBINS;
double hmin = HMIN,hmax = HMAX;
gsl_histogram *realhist = gsl_histogram_alloc (nbins);
gsl_histogram_set_ranges_uniform (realhist,hmin,hmax);
gsl_histogram *nullhist = gsl_histogram_alloc (nbins);
gsl_histogram_set_ranges_uniform (nullhist,hmin,hmax);
/* read input histograms */
ReadTxtHist(realfilename,realhist);
ReadTxtHist(nullfilename,nullhist);
/* cumulative distribution functions */
gsl_histogram_pdf *cdfz = gsl_histogram_pdf_alloc(nbins);
gsl_histogram_pdf *cdf0 = gsl_histogram_pdf_alloc(nbins);
gsl_histogram_pdf_init (cdfz,realhist);
gsl_histogram_pdf_init (cdf0,nullhist);
FILE *fp = fopen(outfilename,"w");
if (!fp) VError(" err opening file %s",outfilename);
fprintf(fp,"# ted F0 Fz FDR \n");
fprintf(fp,"#------------------------------------------------------\n");
/* tail-area FDR */
double cutoff=0;
int flag = 0;
for (i=0; i<nbins; i++) {
gsl_histogram_get_range (realhist,i,&lower,&upper);
double z = lower + 0.5*(upper-lower);
double Fz = 1.0-cdfz->sum[i];
double F0 = 1.0-cdf0->sum[i];
double Fdr = 0.0;
if (Fz > tiny) Fdr = F0/Fz;
if (Fdr > 1.0) Fdr = 1.0;
if (Fdr < 0.0) Fdr = 0.0;
if (Fdr < alpha && flag == 0 && i > 10) {
flag = 1;
cutoff = z;
}
fprintf(fp," %12.8f %12.8f %12.8f %12.8f\n",z,F0,Fz,Fdr);
}
fprintf(fp,"# Fdr < %.3f if ted > %lf\n",alpha,cutoff);
fprintf(stderr," Fdr < %.3f if ted > %lf\n",alpha,cutoff);
fclose(fp);
exit(0);
}
| {
"alphanum_fraction": 0.6346716299,
"avg_line_length": 26.1180555556,
"ext": "c",
"hexsha": "0eaa390ca0a11ce7f257d7479892e0763977cb0f",
"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/ted/vtedfdr/vtedfdr.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/ted/vtedfdr/vtedfdr.c",
"max_line_length": 98,
"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/ted/vtedfdr/vtedfdr.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": 1210,
"size": 3761
} |
/* vector/gsl_vector_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_VECTOR_ULONG_H__
#define __GSL_VECTOR_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_block_ulong.h>
#undef __BEGIN_DECLS
#undef __END_DECLS
#ifdef __cplusplus
# define __BEGIN_DECLS extern "C" {
# define __END_DECLS }
#else
# define __BEGIN_DECLS /* empty */
# define __END_DECLS /* empty */
#endif
__BEGIN_DECLS
typedef struct
{
size_t size;
size_t stride;
unsigned long *data;
gsl_block_ulong *block;
int owner;
}
gsl_vector_ulong;
typedef struct
{
gsl_vector_ulong vector;
} _gsl_vector_ulong_view;
typedef _gsl_vector_ulong_view gsl_vector_ulong_view;
typedef struct
{
gsl_vector_ulong vector;
} _gsl_vector_ulong_const_view;
typedef const _gsl_vector_ulong_const_view gsl_vector_ulong_const_view;
/* Allocation */
GSL_FUN gsl_vector_ulong *gsl_vector_ulong_alloc (const size_t n);
GSL_FUN gsl_vector_ulong *gsl_vector_ulong_calloc (const size_t n);
GSL_FUN gsl_vector_ulong *gsl_vector_ulong_alloc_from_block (gsl_block_ulong * b,
const size_t offset,
const size_t n,
const size_t stride);
GSL_FUN gsl_vector_ulong *gsl_vector_ulong_alloc_from_vector (gsl_vector_ulong * v,
const size_t offset,
const size_t n,
const size_t stride);
GSL_FUN void gsl_vector_ulong_free (gsl_vector_ulong * v);
/* Views */
GSL_FUN _gsl_vector_ulong_view
gsl_vector_ulong_view_array (unsigned long *v, size_t n);
GSL_FUN _gsl_vector_ulong_view
gsl_vector_ulong_view_array_with_stride (unsigned long *base,
size_t stride,
size_t n);
GSL_FUN _gsl_vector_ulong_const_view
gsl_vector_ulong_const_view_array (const unsigned long *v, size_t n);
GSL_FUN _gsl_vector_ulong_const_view
gsl_vector_ulong_const_view_array_with_stride (const unsigned long *base,
size_t stride,
size_t n);
GSL_FUN _gsl_vector_ulong_view
gsl_vector_ulong_subvector (gsl_vector_ulong *v,
size_t i,
size_t n);
GSL_FUN _gsl_vector_ulong_view
gsl_vector_ulong_subvector_with_stride (gsl_vector_ulong *v,
size_t i,
size_t stride,
size_t n);
GSL_FUN _gsl_vector_ulong_const_view
gsl_vector_ulong_const_subvector (const gsl_vector_ulong *v,
size_t i,
size_t n);
GSL_FUN _gsl_vector_ulong_const_view
gsl_vector_ulong_const_subvector_with_stride (const gsl_vector_ulong *v,
size_t i,
size_t stride,
size_t n);
/* Operations */
GSL_FUN void gsl_vector_ulong_set_zero (gsl_vector_ulong * v);
GSL_FUN void gsl_vector_ulong_set_all (gsl_vector_ulong * v, unsigned long x);
GSL_FUN int gsl_vector_ulong_set_basis (gsl_vector_ulong * v, size_t i);
GSL_FUN int gsl_vector_ulong_fread (FILE * stream, gsl_vector_ulong * v);
GSL_FUN int gsl_vector_ulong_fwrite (FILE * stream, const gsl_vector_ulong * v);
GSL_FUN int gsl_vector_ulong_fscanf (FILE * stream, gsl_vector_ulong * v);
GSL_FUN int gsl_vector_ulong_fprintf (FILE * stream, const gsl_vector_ulong * v,
const char *format);
GSL_FUN int gsl_vector_ulong_memcpy (gsl_vector_ulong * dest, const gsl_vector_ulong * src);
GSL_FUN int gsl_vector_ulong_reverse (gsl_vector_ulong * v);
GSL_FUN int gsl_vector_ulong_swap (gsl_vector_ulong * v, gsl_vector_ulong * w);
GSL_FUN int gsl_vector_ulong_swap_elements (gsl_vector_ulong * v, const size_t i, const size_t j);
GSL_FUN unsigned long gsl_vector_ulong_max (const gsl_vector_ulong * v);
GSL_FUN unsigned long gsl_vector_ulong_min (const gsl_vector_ulong * v);
GSL_FUN void gsl_vector_ulong_minmax (const gsl_vector_ulong * v, unsigned long * min_out, unsigned long * max_out);
GSL_FUN size_t gsl_vector_ulong_max_index (const gsl_vector_ulong * v);
GSL_FUN size_t gsl_vector_ulong_min_index (const gsl_vector_ulong * v);
GSL_FUN void gsl_vector_ulong_minmax_index (const gsl_vector_ulong * v, size_t * imin, size_t * imax);
GSL_FUN int gsl_vector_ulong_add (gsl_vector_ulong * a, const gsl_vector_ulong * b);
GSL_FUN int gsl_vector_ulong_sub (gsl_vector_ulong * a, const gsl_vector_ulong * b);
GSL_FUN int gsl_vector_ulong_mul (gsl_vector_ulong * a, const gsl_vector_ulong * b);
GSL_FUN int gsl_vector_ulong_div (gsl_vector_ulong * a, const gsl_vector_ulong * b);
GSL_FUN int gsl_vector_ulong_scale (gsl_vector_ulong * a, const unsigned long x);
GSL_FUN int gsl_vector_ulong_add_constant (gsl_vector_ulong * a, const double x);
GSL_FUN int gsl_vector_ulong_axpby (const unsigned long alpha, const gsl_vector_ulong * x, const unsigned long beta, gsl_vector_ulong * y);
GSL_FUN unsigned long gsl_vector_ulong_sum (const gsl_vector_ulong * a);
GSL_FUN int gsl_vector_ulong_equal (const gsl_vector_ulong * u,
const gsl_vector_ulong * v);
GSL_FUN int gsl_vector_ulong_isnull (const gsl_vector_ulong * v);
GSL_FUN int gsl_vector_ulong_ispos (const gsl_vector_ulong * v);
GSL_FUN int gsl_vector_ulong_isneg (const gsl_vector_ulong * v);
GSL_FUN int gsl_vector_ulong_isnonneg (const gsl_vector_ulong * v);
GSL_FUN INLINE_DECL unsigned long gsl_vector_ulong_get (const gsl_vector_ulong * v, const size_t i);
GSL_FUN INLINE_DECL void gsl_vector_ulong_set (gsl_vector_ulong * v, const size_t i, unsigned long x);
GSL_FUN INLINE_DECL unsigned long * gsl_vector_ulong_ptr (gsl_vector_ulong * v, const size_t i);
GSL_FUN INLINE_DECL const unsigned long * gsl_vector_ulong_const_ptr (const gsl_vector_ulong * v, const size_t i);
#ifdef HAVE_INLINE
INLINE_FUN
unsigned long
gsl_vector_ulong_get (const gsl_vector_ulong * v, const size_t i)
{
#if GSL_RANGE_CHECK
if (GSL_RANGE_COND(i >= v->size))
{
GSL_ERROR_VAL ("index out of range", GSL_EINVAL, 0);
}
#endif
return v->data[i * v->stride];
}
INLINE_FUN
void
gsl_vector_ulong_set (gsl_vector_ulong * v, const size_t i, unsigned long x)
{
#if GSL_RANGE_CHECK
if (GSL_RANGE_COND(i >= v->size))
{
GSL_ERROR_VOID ("index out of range", GSL_EINVAL);
}
#endif
v->data[i * v->stride] = x;
}
INLINE_FUN
unsigned long *
gsl_vector_ulong_ptr (gsl_vector_ulong * v, const size_t i)
{
#if GSL_RANGE_CHECK
if (GSL_RANGE_COND(i >= v->size))
{
GSL_ERROR_NULL ("index out of range", GSL_EINVAL);
}
#endif
return (unsigned long *) (v->data + i * v->stride);
}
INLINE_FUN
const unsigned long *
gsl_vector_ulong_const_ptr (const gsl_vector_ulong * v, const size_t i)
{
#if GSL_RANGE_CHECK
if (GSL_RANGE_COND(i >= v->size))
{
GSL_ERROR_NULL ("index out of range", GSL_EINVAL);
}
#endif
return (const unsigned long *) (v->data + i * v->stride);
}
#endif /* HAVE_INLINE */
__END_DECLS
#endif /* __GSL_VECTOR_ULONG_H__ */
| {
"alphanum_fraction": 0.6755484093,
"avg_line_length": 35.8312757202,
"ext": "h",
"hexsha": "324b049bc57daa3d18aa242e8213624396880067",
"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_vector_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_vector_ulong.h",
"max_line_length": 140,
"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_vector_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": 2031,
"size": 8707
} |
#ifndef _TEST_H_
#define _TEST_H_
#define _GNU_SOURCE
#include <time.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <float.h>
#include <string.h>
#include <omp.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_spline.h>
#include <gsl/gsl_interp2d.h>
#include <gsl/gsl_spline2d.h>
#include <gsl/gsl_sf_bessel.h>
#include <gsl/gsl_sf_legendre.h>
#include <gsl/gsl_integration.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_linalg.h>
#include <gsl/gsl_blas.h>
#include <gsl/gsl_monte.h>
#include <gsl/gsl_monte_vegas.h>
#include <gsl/gsl_odeiv2.h>
#include <gsl/gsl_roots.h>
#include <gsl/gsl_sf_expint.h>
#include <ctype.h>
#include "cuba.h"
#define PSC 101L
#define ST 102L
#define TK 103L
#define CO10 131L
#define CO21 132L
#define CO32 133L
#define CO43 134L
#define CO54 135L
#define CO65 136L
#define CII 137L
#define NPARS 6
extern struct globals gb;
#include "../Class/include/class.h"
#include "global_structs.h"
#include "cosmology.h"
typedef struct initialize_struct{
double Mh_min;
long mode_mf;
size_t ninterp;
int nlines;
int lines[7];
}initialize_struct;
void initialize(char *argv[], struct initialize_struct *init_struct);
void cleanup();
int Cosmology_init(struct Cosmology *Cx, double pk_kmax, double pk_zmax,
int nlines, int * line_types, size_t npoints_interp, double M_min, long mode_mf);
double PS_line_HM(struct Cosmology *Cx, double k, double z, double M_min, long mode_mf, long line_type, int line_id);
double PS_shot_HM(struct Cosmology *Cx, double k, double z, double M_min, double *input, long mode_mf, long line_type, int line_id);
double b22_ls(struct Cosmology *Cx, double z);
double PS_shot(struct Cosmology *Cx, double z, size_t line_id);
double Tbar_line(struct Cosmology *Cx, size_t line_id, double z);
void line_bias(struct Line *Lx, double z, double *result);
double rhoc(struct Cosmology *Cx, double z);
#endif
| {
"alphanum_fraction": 0.6920133907,
"avg_line_length": 26.1375,
"ext": "h",
"hexsha": "3e50ceb0b334708e2cfc4cae38661e26fcc22c99",
"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": "302c139809ffa95a6e154a4268e4d48e4082cdf3",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "amoradinejad/limHaloPT",
"max_forks_repo_path": "Test/test_header.h",
"max_issues_count": 11,
"max_issues_repo_head_hexsha": "302c139809ffa95a6e154a4268e4d48e4082cdf3",
"max_issues_repo_issues_event_max_datetime": "2022-03-24T17:35:55.000Z",
"max_issues_repo_issues_event_min_datetime": "2022-02-17T14:55:17.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "amoradinejad/limHaloPT",
"max_issues_repo_path": "Test/test_header.h",
"max_line_length": 132,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "302c139809ffa95a6e154a4268e4d48e4082cdf3",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "amoradinejad/limHaloPT",
"max_stars_repo_path": "Test/test_header.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 602,
"size": 2091
} |
/** \file
* Analyze CSA output traces responding to pulses for ENC evaluation.
*/
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <math.h>
#include <string.h>
#include <unistd.h>
#include <gsl/gsl_histogram2d.h>
#include "common.h"
#include "filters.h"
#include "hdf5rawWaveformIo.h"
typedef SCOPE_DATA_TYPE IN_WFM_BASE_TYPE;
typedef SCOPE_DATA_TYPE OUT_WFM_BASE_TYPE;
/** Parameters settable from commandline */
typedef struct param
{
size_t diffSep; //!< rise-time in samples for pulse finding
double riseFrac; //!< fraction of max pulse height for pulse edge location
double fltM; //!< exp decay constant for Trapezoidal filter
size_t sPre; //!< samples before rising edge
size_t sLen; //!< total number of samples of a pulse
size_t sHscale; //!< histogram sample scaling factor
} param_t;
param_t param_default = {
.diffSep = 150,
.riseFrac = 0.5,
.fltM = -1.0,
.sPre = 1000,
.sLen = 4000,
.sHscale = 4
};
void print_usage(const param_t *pm)
{
printf("Usage:\n");
printf(" -r rise time in samples[%zd]\n", pm->diffSep);
printf(" -f riseFrac[%g]\n", pm->riseFrac);
printf(" -m fltM[%g]\n", pm->fltM);
printf(" -p sPre[%zd]\n", pm->sPre);
printf(" -l sLen[%zd]\n", pm->sLen);
printf(" -s iStart[0] -e iStop[-1] starting and stopping(+1) eventid\n");
printf(" inFileName(.h5) outFileName\n");
}
/** Find pulses by their rising edges.
*
* @param[out] npulse number of pulses found
* @param[in] fltH input waveform should be loaded into it already
* @param[in] diffSep basically the rise time in samples
* @param[in] riseFrac fraction of max pulse height to set pulse edge location
* @param[in] M exp decay constant for Trapezoidal filter
* @return the list of rising edge positions (times)
*/
size_t *find_pulses(size_t *npulse, filters_t *fltH, size_t diffSep, double riseFrac, double M)
{
size_t n, nc = 1024;
size_t *pulseRiseT = NULL, *pulseRiseT1;
size_t flt_k = 2*diffSep, flt_l = 2*flt_k;
double flt_M = M, max, dV;
ssize_t i, j, sep, prev;
if((pulseRiseT = calloc(nc, sizeof(size_t))) == NULL) {
error_printf("calloc failed for pulseRiseT in %s()\n", __FUNCTION__);
return NULL;
}
filters_trapezoidal(fltH, flt_k, flt_l, flt_M);
max = 0.0;
for(i=0; i<fltH->wavLen; i++)
if(fltH->outWav[i] > max) max = fltH->outWav[i];
sep = flt_k + flt_l;
prev = 0;
n = 0;
for(i=0; i<fltH->wavLen; i++) {
j = ((i+diffSep)>=fltH->wavLen)?(fltH->wavLen-1):(i+diffSep);
dV = fltH->inWav[j] - fltH->inWav[i];
if(dV > max * riseFrac) {
if(i-prev > sep) {
pulseRiseT[n] = j; n++;
if(n >= nc) {
nc *= 2;
if((pulseRiseT1 = realloc(pulseRiseT, nc * sizeof(size_t))) == NULL) {
error_printf("realloc failed for pulseRiseT in %s()\n", __FUNCTION__);
*npulse = n;
return pulseRiseT;
}
pulseRiseT = pulseRiseT1;
}
prev = i;
}
}
}
*npulse = n;
return pulseRiseT;
}
int main(int argc, char **argv)
{
int optC = 0;
param_t pm;
char *inFileName, *outFileName;
struct hdf5rawWaveformIo_waveform_file *inWfmFile;
struct waveform_attribute inWfmAttr;
struct hdf5rawWaveformIo_waveform_event inWfmEvent;
IN_WFM_BASE_TYPE *inWfmBuf;
// OUT_WFM_BASE_TYPE *outWfmBuf;
filters_t *fltHdl;
ssize_t iStart=0, iStop=-1, i, j, k, iCh;
size_t nEventsInFile, chGrpLen, npulse, *pulseRiseT, nSep;
unsigned int v, c;
size_t chGrpIdx[SCOPE_NCH] = {0};
double frameSize, val, sep, sepMu, sepSigma;
gsl_histogram2d *wav2H, *flt2H;
memcpy(&pm, ¶m_default, sizeof(pm));
// parse switches
while((optC = getopt(argc, argv, "e:f:l:m:p:r:s:")) != -1) {
switch(optC) {
case 'e':
iStop = atoll(optarg);
break;
case 'f':
pm.riseFrac = atof(optarg);
break;
case 'l':
pm.sLen = atoll(optarg);
break;
case 'm':
pm.fltM = atof(optarg);
break;
case 'p':
pm.sPre = atoll(optarg);
break;
case 'r':
pm.diffSep = atoll(optarg);
break;
case 's':
iStart = atoll(optarg);
break;
default:
print_usage(&pm);
return EXIT_FAILURE;
break;
}
}
argc -= optind;
argv += optind;
if(argc<2 || argc>=3) {
print_usage(&pm);
return EXIT_FAILURE;
}
inFileName = argv[0];
outFileName = argv[1];
inWfmFile = hdf5rawWaveformIo_open_file_for_read(inFileName);
hdf5rawWaveformIo_read_waveform_attribute_in_file_header(inWfmFile, &inWfmAttr);
fprintf(stderr, "waveform_attribute:\n"
" chMask = 0x%04x\n"
" nPt = %zd\n"
" nFrames = %zd\n"
" dt = %g\n"
" t0 = %g\n"
" ymult = %g %g %g %g\n"
" yoff = %g %g %g %g\n"
" yzero = %g %g %g %g\n",
inWfmAttr.chMask, inWfmAttr.nPt, inWfmAttr.nFrames, inWfmAttr.dt,
inWfmAttr.t0, inWfmAttr.ymult[0], inWfmAttr.ymult[1], inWfmAttr.ymult[2],
inWfmAttr.ymult[3], inWfmAttr.yoff[0], inWfmAttr.yoff[1],
inWfmAttr.yoff[2], inWfmAttr.yoff[3], inWfmAttr.yzero[0],
inWfmAttr.yzero[1], inWfmAttr.yzero[2], inWfmAttr.yzero[3]);
nEventsInFile = hdf5rawWaveformIo_get_number_of_events(inWfmFile);
fprintf(stderr, "Number of events in file: %zd\n", nEventsInFile);
if(iStart < 0) iStart = 0;
if(iStart >= nEventsInFile) iStart = nEventsInFile - 1;
if(iStop < 0) iStop = nEventsInFile;
if(iStop <= iStart) iStop = iStart + 1;
if(inWfmAttr.nFrames > 0) {
frameSize = inWfmAttr.nPt / (double)inWfmAttr.nFrames;
} else {
frameSize = (double)inWfmAttr.nPt;
}
v = inWfmAttr.chMask;
for(c=0; v; c++) v &= v - 1;
/* Brian Kernighan's way of counting bits */
chGrpLen = inWfmFile->nCh / c;
i=0;
for(v=0; v<SCOPE_NCH; v++)
if((inWfmAttr.chMask >> v) & 0x01) {
chGrpIdx[i] = v;
i++;
}
inWfmBuf = (IN_WFM_BASE_TYPE*)malloc(inWfmFile->nPt * inWfmFile->nCh * sizeof(IN_WFM_BASE_TYPE));
inWfmEvent.wavBuf = inWfmBuf;
fltHdl = filters_init(NULL, inWfmFile->nPt);
wav2H = gsl_histogram2d_alloc(pm.sLen/pm.sHscale, 128);
gsl_histogram2d_set_ranges_uniform(wav2H, -0.5 * inWfmAttr.dt, (pm.sLen+0.5) * inWfmAttr.dt,
inWfmAttr.yzero[chGrpIdx[0]] + (-128.5 - inWfmAttr.yoff[chGrpIdx[0]]) * inWfmAttr.ymult[chGrpIdx[0]],
inWfmAttr.yzero[chGrpIdx[0]] + ( 127.5 - inWfmAttr.yoff[chGrpIdx[0]]) * inWfmAttr.ymult[chGrpIdx[0]]);
flt2H = gsl_histogram2d_alloc(pm.sLen/pm.sHscale, 256);
gsl_histogram2d_set_ranges_uniform(flt2H, -0.5 * inWfmAttr.dt, (pm.sLen+0.5) * inWfmAttr.dt, -0.01, -0.01 + 256 * inWfmAttr.ymult[chGrpIdx[0]]);
nSep = 0; sepMu = 0.0; sepSigma = 0.0;
for(inWfmEvent.eventId = iStart; inWfmEvent.eventId < iStop; inWfmEvent.eventId++) {
hdf5rawWaveformIo_read_event(inWfmFile, &inWfmEvent);
for(iCh=0; iCh < 1 /* inWfmFile->nCh */; iCh++) {
for(i=0; i<inWfmFile->nPt; i++) {
val = (inWfmBuf[(size_t)(iCh * inWfmFile->nPt + i)]
- inWfmAttr.yoff[chGrpIdx[iCh]])
* inWfmAttr.ymult[chGrpIdx[iCh]]
+ inWfmAttr.yzero[chGrpIdx[iCh]];
fltHdl->inWav[i] = val;
}
}
pulseRiseT = find_pulses(&npulse, fltHdl,
pm.diffSep, pm.riseFrac, pm.fltM);
fprintf(stderr, "eventId = %zd, npulse = %zd, first at %zd\n",
inWfmEvent.eventId, npulse, pulseRiseT[0]);
for(i=0; i<npulse-1; i++) {
sep = pulseRiseT[i+1] - pulseRiseT[i];
sepMu += sep;
sepSigma += sep * sep;
nSep++;
}
for(i=1; i<npulse-1; i++) {
for(j=0; j<pm.sLen; j++) {
k = pulseRiseT[i]-pm.sPre + j;
gsl_histogram2d_increment(wav2H, j*inWfmAttr.dt, fltHdl->inWav[k]);
gsl_histogram2d_increment(flt2H, j*inWfmAttr.dt, fltHdl->outWav[k]);
}
}
free(pulseRiseT);
}
sepMu /= (double)nSep;
sepSigma = sqrt(1.0/(double)(nSep-1) * (sepSigma - nSep * sepMu * sepMu));
printf("nSep = %zd, sepMu = %g, sepSigma = %g\n", nSep, sepMu, sepSigma);
FILE *ofp;
if((ofp = fopen(outFileName, "w"))==NULL) {
perror(outFileName);
goto Exit;
}
gsl_histogram2d_fprintf(ofp, wav2H, "%24.16e", "%g");
fprintf(ofp, "\n\n");
gsl_histogram2d_fprintf(ofp, flt2H, "%24.16e", "%g");
fprintf(ofp, "\n\n");
fprintf(ofp, "# baseline distribution");
double yl, yu;
for(i=0; i<gsl_histogram2d_ny(wav2H); i++) {
gsl_histogram2d_get_yrange(wav2H, i, &yl, &yu);
fprintf(ofp, "%24.16e, %g\n", yl, gsl_histogram2d_get(wav2H, 0, i));
}
fprintf(ofp, "\n\n");
fprintf(ofp, "# filtered distribution");
for(i=0; i<gsl_histogram2d_ny(flt2H); i++) {
gsl_histogram2d_get_yrange(flt2H, i, &yl, &yu);
fprintf(ofp, "%24.16e, %g\n", yl,
gsl_histogram2d_get(flt2H, (pm.sPre+3*pm.diffSep)/pm.sHscale, i));
}
fclose(ofp);
Exit:
free(inWfmBuf); inWfmBuf = NULL;
gsl_histogram2d_free(wav2H);
gsl_histogram2d_free(flt2H);
filters_close(fltHdl);
hdf5rawWaveformIo_close_file(inWfmFile);
return EXIT_SUCCESS;
}
| {
"alphanum_fraction": 0.5662201632,
"avg_line_length": 33.430976431,
"ext": "c",
"hexsha": "5a7e5db85a3474e8dc56cbcdaa8c454bb50081dd",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2020-12-14T11:30:47.000Z",
"max_forks_repo_forks_event_min_datetime": "2018-01-17T08:46:04.000Z",
"max_forks_repo_head_hexsha": "0a66a7305934f9d9da5c725a04e1e1ddcc4763c1",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "AmberXiong/Mic4Test_KC705",
"max_forks_repo_path": "Software/Analysis/src/pulserENC.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "0a66a7305934f9d9da5c725a04e1e1ddcc4763c1",
"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": "AmberXiong/Mic4Test_KC705",
"max_issues_repo_path": "Software/Analysis/src/pulserENC.c",
"max_line_length": 148,
"max_stars_count": 2,
"max_stars_repo_head_hexsha": "0a66a7305934f9d9da5c725a04e1e1ddcc4763c1",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "AmberXiong/Mic4Test_KC705",
"max_stars_repo_path": "Software/Analysis/src/pulserENC.c",
"max_stars_repo_stars_event_max_datetime": "2020-12-14T11:30:45.000Z",
"max_stars_repo_stars_event_min_datetime": "2018-01-17T08:44:39.000Z",
"num_tokens": 3247,
"size": 9929
} |
/**
* \author Sylvain Marsat, University of Maryland - NASA GSFC
*
* \brief C header for functions computing coeffcients of Not-A-Knot and Quadratic splines in matrix form.
*
*/
#ifndef _FRESNEL_H
#define _FRESNEL_H
#define _XOPEN_SOURCE 500
#ifdef __GNUC__
#define UNUSED __attribute__ ((unused))
#else
#define UNUSED
#endif
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <complex.h>
#include <time.h>
#include <unistd.h>
#include <getopt.h>
#include <stdbool.h>
#include <string.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_bspline.h>
#include <gsl/gsl_blas.h>
#include <gsl/gsl_min.h>
#include <gsl/gsl_spline.h>
#include <gsl/gsl_complex.h>
#include "constants.h"
#include "struct.h"
#if defined(__cplusplus)
#define complex _Complex
extern "C" {
#elif 0
} /* so that editors will match preceding brace */
#endif
double complex ComputeInt(
gsl_matrix* splinecoeffsAreal, /* */
gsl_matrix* splinecoeffsAimag, /* */
gsl_matrix* splinecoeffsphase); /* */
double complex ComputeIntCase1a(
const double complex* coeffsA, /* */
const double p1, /* */
const double p2, /* */
const double scale); /* */
double complex ComputeIntCase1b(
const double complex* coeffsA, /* */
const double p1, /* */
const double p2, /* */
const double scale); /* */
double complex ComputeIntCase2(
const double complex* coeffsA, /* */
const double p1, /* */
const double p2); /* */
double complex ComputeIntCase3(
const double complex* coeffsA, /* */
const double p1, /* */
const double p2); /* */
double complex ComputeIntCase4(
const double complex* coeffsA, /* */
const double p1, /* */
const double p2); /* */
#if 0
{ /* so that editors will match succeeding brace */
#elif defined(__cplusplus)
}
#endif
#endif /* _FRESNEL_H */
| {
"alphanum_fraction": 0.5866160418,
"avg_line_length": 25.3855421687,
"ext": "h",
"hexsha": "af0862b0fe9deb21faebc2fd49603e81ec81f59e",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2020-07-20T02:56:30.000Z",
"max_forks_repo_forks_event_min_datetime": "2018-09-20T14:19:13.000Z",
"max_forks_repo_head_hexsha": "4ffb02977d19786ab8c1a767cc495a799d9575ae",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "titodalcanton/flare",
"max_forks_repo_path": "tools/fresnel.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "4ffb02977d19786ab8c1a767cc495a799d9575ae",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "titodalcanton/flare",
"max_issues_repo_path": "tools/fresnel.h",
"max_line_length": 106,
"max_stars_count": 3,
"max_stars_repo_head_hexsha": "4ffb02977d19786ab8c1a767cc495a799d9575ae",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "titodalcanton/flare",
"max_stars_repo_path": "tools/fresnel.h",
"max_stars_repo_stars_event_max_datetime": "2020-07-20T02:56:25.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-05-26T15:21:13.000Z",
"num_tokens": 504,
"size": 2107
} |
#pragma once
// support functions for TString & c-string handling...
// v1.17
#include <tchar.h>
#include <cstdlib>
#include <codecvt>
#ifdef max
#undef max
#endif
#ifdef min
#undef min
#endif
#include <concepts>
#include <gsl/gsl>
// determine whether _Ty is a Number type (excluding char / wchar)
template<class _Ty>
struct is_Numeric
: std::integral_constant<bool,
(std::is_arithmetic_v<_Ty> || std::is_same_v<_Ty, std::byte> || std::is_enum_v<_Ty>)
&& !std::is_same_v<_Ty, wchar_t>
&& !std::is_same_v<_Ty, char>
&& !std::is_pointer_v<_Ty>
>
{
};
// determine whether T is a Number type (excluding char / wchar), same as is_Numeric<T>::value
template <typename T>
constexpr bool is_Numeric_v = is_Numeric<T>::value;
namespace std
{
inline string to_string(const wstring& wstr)
{
//string str;
//str.assign(wstr.begin(), wstr.end());
//return str;
using convert_type = std::codecvt_utf8<wchar_t>;
std::wstring_convert<convert_type, wchar_t> converter;
//use converter (.to_bytes: wstr->str, .from_bytes: str->wstr)
return converter.to_bytes(wstr);
}
inline wstring to_wstring(const string& str)
{
wstring wstr;
wstr.assign(str.begin(), str.end());
return wstr;
}
inline string to_string(const std::byte& num)
{
return to_string(gsl::narrow_cast<uint8_t>(num));
}
inline wstring to_wstring(const std::byte& num)
{
return to_wstring(gsl::narrow_cast<uint8_t>(num));
}
}
struct ci_char_traits
: public std::char_traits<char>
{
static char to_upper(char ch) noexcept
{
if (ch >= 'a' && ch <= 'z') return _toupper(ch);
return ch;
}
static bool eq(char c1, char c2) noexcept
{
return to_upper(c1) == to_upper(c2);
}
static bool lt(char c1, char c2) noexcept
{
return to_upper(c1) < to_upper(c2);
}
static int compare(const char* s1, const char* s2, size_t n) noexcept
{
while (n-- != 0)
{
if (to_upper(*s1) < to_upper(*s2)) return -1;
if (to_upper(*s1) > to_upper(*s2)) return 1;
++s1; ++s2;
}
return 0;
}
static const char* find(const char* s, int n, char a) noexcept
{
if (s)
for (auto const ua(to_upper(a)); (n != 0); ++s, --n)
{
if (to_upper(*s) == ua)
return s;
}
return nullptr;
}
};
struct ci_wchar_traits
: public std::char_traits<wchar_t>
{
static wchar_t to_upper(wchar_t ch) noexcept
{
if (ch >= L'a' && ch <= L'z') return _toupper(ch);
return ch;
}
static bool eq(wchar_t c1, wchar_t c2) noexcept
{
return to_upper(c1) == to_upper(c2);
}
static bool lt(wchar_t c1, wchar_t c2) noexcept
{
return to_upper(c1) < to_upper(c2);
}
static int compare(const wchar_t* s1, const wchar_t* s2, size_t n) noexcept
{
while (n-- != 0)
{
if (to_upper(*s1) < to_upper(*s2)) return -1;
if (to_upper(*s1) > to_upper(*s2)) return 1;
++s1; ++s2;
}
return 0;
}
static const wchar_t* find(const wchar_t* s, int n, wchar_t a) noexcept
{
if (s)
for (auto const ua(to_upper(a)); (n-- != 0); ++s)
{
if (to_upper(*s) == ua)
return s;
}
return nullptr;
}
};
using ci_stringview = std::basic_string_view<char, ci_char_traits>;
using ci_wstringview = std::basic_string_view<wchar_t, ci_wchar_traits>;
namespace details {
template<class _Ty>
struct is_pod
: std::integral_constant<bool, std::is_standard_layout_v<_Ty>&& std::is_trivial_v<_Ty> >
{
};
template <typename T>
constexpr bool is_pod_v = is_pod<T>::value;
template<typename T>
concept IsPODText = std::is_same_v<std::remove_all_extents_t<std::remove_cv_t<std::remove_pointer_t<T>>>, char> || std::is_same_v<std::remove_all_extents_t<std::remove_cv_t<std::remove_pointer_t<T>>>, wchar_t>;
template <class T>
concept IsNumeric = is_Numeric_v<std::remove_cvref_t<T>>;
template <class T>
concept HasDataFunction = requires(T t)
{
t.data();
};
template <class T>
concept HasChrFunction = requires(T t)
{
t.to_chr();
};
template <class T>
concept HasSizeFunction = requires(T t)
{
static_cast<std::size_t>(t.size());
};
template <class T>
concept HasDataSizeNoChr = HasDataFunction<T> && HasSizeFunction<T> && !HasChrFunction<T>;
template <class T>
concept HasDataSizeChr = HasDataFunction<T> && HasSizeFunction<T> && HasChrFunction<T>;
constexpr WCHAR make_upper(const WCHAR c) noexcept
{
if (c >= L'a' && c <= L'z') return _toupper(c);
return c;
}
constexpr char make_upper(const char c) noexcept
{
if (c >= 'a' && c <= 'z') return _toupper(c);
return c;
}
constexpr bool CompareChar(const WCHAR c, const WCHAR other, const bool bCase) noexcept
{
return (bCase) ? c == other : make_upper(c) == make_upper(other);
}
constexpr bool CompareChar(const char c, const char other, const bool bCase) noexcept
{
return (bCase) ? c == other : make_upper(c) == make_upper(other);
}
template <typename Result, typename Format>
Result& _ts_printf_do(Result& res, const Format& fmt)
{
res += fmt;
return res;
}
template <typename Result, typename Format, typename Value, typename... Arguments>
Result& _ts_printf_do(Result& res, const Format& fmt, const Value& val, Arguments&&... args)
{
auto i = 0U;
auto bSkip = false;
for (auto c = fmt[0]; c != decltype(c){'\0'}; c = fmt[++i])
{
if (!bSkip)
{
if (c == decltype(c){'\\'})
{
bSkip = true;
continue;
}
else if (c == decltype(c){'%'})
{
if constexpr (is_Numeric_v<Value>)
{
if constexpr (std::is_same_v<std::string, std::remove_cv_t<Result>>)
res += std::to_string(val);
else if constexpr (std::is_same_v<std::wstring, std::remove_cv_t<Result>>)
res += std::to_wstring(val);
else
res += val; // assumes this type can handle adding numbers.
}
else
res += val;
if constexpr (std::is_array_v<Format> && details::is_pod_v<Format>)
return _ts_printf_do(res, &fmt[0] + i + 1, args...);
else
return _ts_printf_do(res, fmt + i + 1, args...);
}
}
else
bSkip = false;
res += c;
}
//// Ook: needs checked may need work
//for (const auto &c: fmt)
//{
// if (!bSkip)
// {
// if (c == decltype(c){'\\'})
// {
// bSkip = true;
// continue;
// }
// else if (c == decltype(c){'%'})
// {
// if constexpr (is_Numeric_v<Value>)
// {
// if constexpr (std::is_same_v<std::string, std::remove_cv_t<Result>>)
// res += std::to_string(val);
// else if constexpr (std::is_same_v<std::wstring, std::remove_cv_t<Result>>)
// res += std::to_wstring(val);
// else
// res += val; // assumes this type can handle adding numbers.
// }
// else
// res += val;
// if constexpr (std::is_array_v<Format> && std::is_pod_v<Format>)
// return _ts_printf_do(res, &fmt[0] + i + 1, args...);
// else
// return _ts_printf_do(res, fmt + i + 1, args...);
// }
// }
// else
// bSkip = false;
// res += c;
//}
return res;
}
template<typename T, class TR = std::char_traits<T> >
struct impl_strstr {
using ptype = typename TR::char_type*;
using cptype = typename const ptype;
ptype operator()(ptype input, cptype find)
{
do {
ptype p{}, q{};
for (p = input, q = find; !TR::eq(*q, 0) && TR::eq(*p, *q); p++, q++) {}
if (TR::eq(*q, 0))
return input;
} while (!TR::eq(*(input++), 0));
return nullptr;
}
};
//// Test if a string is empty, works for std::basic_string & TString objects
//template <typename T>
//std::enable_if_t<!std::is_pointer_v<T> && !std::is_pod_v<T> && std::is_member_function_pointer_v<decltype(&T::empty)>, bool> _ts_isEmpty(const T &str) noexcept
//{
// return str.empty();
//}
//
//// Test if a string is empty, works for C String char * or wchar_t *
//template <typename T>
//std::enable_if_t<std::is_pointer_v<T>, bool> _ts_isEmpty(const T &str) noexcept
//{
// using value_type = std::remove_cv_t<std::remove_pointer_t<T> >;
//
// static_assert(std::is_same_v<value_type, char> || std::is_same_v<value_type, wchar_t>, "Invalid Type used");
// return ((str == nullptr) || (str[0] == value_type()));
//}
//
//// Test if a string is empty, works for C char or wchar_t
//template <typename T>
//std::enable_if_t<!std::is_pointer_v<T> && std::is_pod_v<T>, bool> _ts_isEmpty(const T &str) noexcept
//{
// using value_type = std::remove_cv_t<T>;
//
// static_assert(std::is_same_v<value_type, char> || std::is_same_v<value_type, wchar_t>, "Invalid Type used");
// return (str == value_type());
//}
template <typename T>
bool _ts_isEmpty(const T& str) noexcept
{
if constexpr (std::is_pointer_v<T>)
{
// T is a pointer
// Test if a string is empty, works for C String char * or wchar_t *
using value_type = std::remove_cv_t<std::remove_pointer_t<T> >;
static_assert(IsPODText<value_type>, "Invalid Type used");
return ((str == nullptr) || (str[0] == value_type()));
}
else if constexpr (std::is_standard_layout_v<T> && std::is_trivial_v<T>) // same as old std::is_pod_v<T>
{
if constexpr (std::is_array_v<T>)
{
// T is NOT a pointer but IS POD and IS an array (char[3] ...)
// Test if a string is empty, works for C char or wchar_t
using value_type = std::remove_all_extents_t<std::remove_cv_t<T>>;
static_assert(IsPODText<value_type>, "Invalid Type used");
return (str[0] == value_type());
}
else {
// T is NOT a pointer but IS POD and is NOT an array (single char ...)
// Test if a string is empty, works for C char or wchar_t
using value_type = std::remove_cv_t<T>;
static_assert(IsPODText<value_type>, "Invalid Type used");
return (str == value_type());
}
}
else if constexpr (std::is_member_function_pointer_v<decltype(&T::empty)>)
{
// T is NOT a pointer and is NOT POD
// Test if a container is empty, works for std::basic_string & TString objects or any container with an empty() member function.
return str.empty();
}
}
//// Get String length
//template <typename T, typename size_type = std::size_t>
//std::enable_if_t<std::is_pointer_v<T>, size_type> _ts_strlen(const T &str) noexcept
//{
// using value_type = std::remove_cv_t<std::remove_pointer_t<T> >;
//
// static_assert(std::is_same_v<value_type, char> || std::is_same_v<value_type, wchar_t>, "Invalid Type used");
// auto iLen = size_type();
// for (auto p = str; p && *p; ++p)
// ++iLen;
// return iLen;
//}
//
//template <typename T, typename size_type = std::size_t>
//constexpr inline std::enable_if_t<!std::is_pointer_v<T> && std::is_same_v<std::remove_cv_t<T>, wchar_t>, size_type> _ts_strlen(const T &str) noexcept
//{
// return (str == T() ? 0U : 1U);
//}
//
//template <typename T, typename size_type = std::size_t>
//constexpr inline std::enable_if_t<!std::is_pointer_v<T> && std::is_same_v<std::remove_cv_t<T>, char>, size_type> _ts_strlen(const T &str) noexcept
//{
// return (str == T() ? 0U : 1U);
//}
//
//template <typename T, typename size_type = std::size_t, std::size_t N>
//constexpr inline size_type _ts_strlen(T const (&)[N]) noexcept
//{
// return (N == 0U ? 0U : N - 1);
//}
//
//template <typename T, typename size_type = T::size_type>
//inline std::enable_if_t<!std::is_pointer_v<T> && std::is_member_function_pointer_v<decltype(&T::length)>, size_type> _ts_strlen(const T &str)
//{
// return str.length();
//}
// Get String length
template <typename T, IsNumeric size_type = std::size_t>
constexpr size_type _ts_strlen(const T& str) noexcept
{
if constexpr (std::is_pointer_v<T>)
{
// T is a pointer
// return length of string...
static_assert(IsPODText<T>, "Invalid Type used");
auto iLen = size_type();
for (auto p = str; p && *p; ++p)
++iLen;
return iLen;
}
else if constexpr (IsPODText<T>)
{
// T is POD, char or wchar_t
// checks if char is zero or not
return (str == T() ? 0U : 1U);
}
else if constexpr (std::is_member_function_pointer_v<decltype(&T::length)>)
{
// T has a member function length()
return gsl::narrow_cast<size_type>(str.length());
}
}
//template <typename T, typename size_type = std::size_t, std::size_t N>
//constexpr inline size_type _ts_strlen(T const (&)[N]) noexcept
//{
// // T is a fixed array
// return (N == 0U ? 0U : N - 1);
//}
template <IsPODText T, IsNumeric size_type = std::size_t, std::size_t N>
constexpr inline size_type _ts_strlen(T const (&)[N]) noexcept
{
// T is a fixed array
return (N == 0U ? 0U : N - 1);
}
template <typename T>
struct _impl_strnlen {
};
template <>
struct _impl_strnlen<char*> {
size_t operator()(const char* const ptr, size_t length) noexcept
{
return strnlen(ptr, length);
}
};
template <>
struct _impl_strnlen<wchar_t*> {
size_t operator()(const wchar_t* const ptr, size_t length) noexcept
{
return wcsnlen(ptr, length);
}
};
template <>
struct _impl_strnlen<char> {
size_t operator()(const char& ptr, size_t length) noexcept
{
return (ptr == 0 || length == 0 ? 0U : 1U);
}
};
template <>
struct _impl_strnlen<wchar_t> {
size_t operator()(const wchar_t& ptr, size_t length) noexcept
{
return (ptr == 0 || length == 0 ? 0U : 1U);
}
};
template <typename T>
struct _impl_strcpyn {
};
template <>
struct _impl_strcpyn<char> {
char* operator()(char* const pDest, const char* const pSrc, const size_t length) noexcept
{
//auto t = strncpy(pDest, pSrc, length); // doesn't guarantee NULL termination!
//if (t)
// t[length - 1] = 0; // make sure it ends in NULL
//return t;
return lstrcpynA(pDest, pSrc, gsl::narrow_cast<int>(length));
}
};
template <>
struct _impl_strcpyn<wchar_t> {
wchar_t* operator()(wchar_t* const pDest, const wchar_t* const pSrc, const size_t length) noexcept
{
//auto t = wcsncpy(pDest, pSrc, length); // doesn't guarantee NULL termination!
//if (t)
// t[length - 1] = 0; // make sure it ends in NULL
//return t;
return lstrcpynW(pDest, pSrc, gsl::narrow_cast<int>(length));
}
};
template <typename T>
struct _impl_strcpy {
};
template <>
struct _impl_strcpy<char> {
char* operator()(char* const pDest, const char* const pSrc) noexcept
{
return strcpy(pDest, pSrc);
}
};
template <>
struct _impl_strcpy<wchar_t> {
wchar_t* operator()(wchar_t* const pDest, const wchar_t* const pSrc) noexcept
{
return wcscpy(pDest, pSrc);
}
};
template <typename T>
struct _impl_strncat {
};
template <>
struct _impl_strncat<char> {
char* operator()(char* const pDest, const char* const pSrc, const size_t length) noexcept
{
return strncat(pDest, pSrc, length);
}
};
template <>
struct _impl_strncat<wchar_t> {
wchar_t* operator()(wchar_t* const pDest, const wchar_t* const pSrc, const size_t length) noexcept
{
return wcsncat(pDest, pSrc, length);
}
};
template <typename T>
struct _impl_strcat {
};
template <>
struct _impl_strcat<char> {
char* operator()(char* const pDest, const char* const pSrc) noexcept
{
return strcat(pDest, pSrc);
}
};
template <>
struct _impl_strcat<wchar_t> {
wchar_t* operator()(wchar_t* const pDest, const wchar_t* const pSrc) noexcept
{
return wcscat(pDest, pSrc);
}
};
template <typename T>
struct _impl_strchr {
};
template <>
struct _impl_strchr<char> {
char* operator()(char* const pString, const char ch)
{
return strchr(pString, ch);
}
};
template <>
struct _impl_strchr<wchar_t> {
wchar_t* operator()(wchar_t* const pString, const wchar_t ch)
{
return wcschr(pString, ch);
}
};
template <typename T>
struct _impl_strncmp {
};
template <>
struct _impl_strncmp<char> {
int operator()(const char* const pDest, const char* const pSrc, const size_t length) noexcept
{
return strncmp(pDest, pSrc, length);
}
};
template <>
struct _impl_strncmp<wchar_t> {
int operator()(const wchar_t* const pDest, const wchar_t* const pSrc, const size_t length) noexcept
{
return wcsncmp(pDest, pSrc, length);
}
};
template <typename T>
struct _impl_strnicmp {
};
template <>
struct _impl_strnicmp<char> {
int operator()(const char* const pDest, const char* const pSrc, const size_t length) noexcept
{
return _strnicmp(pDest, pSrc, length);
}
};
template <>
struct _impl_strnicmp<wchar_t> {
int operator()(const wchar_t* const pDest, const wchar_t* const pSrc, const size_t length) noexcept
{
return _wcsnicmp(pDest, pSrc, length);
}
};
template <typename T>
struct _impl_strcmp {
};
template <>
struct _impl_strcmp<char> {
int operator()(const char* const pDest, const char* const pSrc) noexcept
{
return strcmp(pDest, pSrc);
}
};
template <>
struct _impl_strcmp<wchar_t> {
int operator()(const wchar_t* const pDest, const wchar_t* const pSrc) noexcept
{
return wcscmp(pDest, pSrc);
}
};
template <typename T>
struct _impl_stricmp {
};
template <>
struct _impl_stricmp<char> {
int operator()(const char* const pDest, const char* const pSrc) noexcept
{
return _stricmp(pDest, pSrc);
}
};
template <>
struct _impl_stricmp<wchar_t> {
int operator()(const wchar_t* const pDest, const wchar_t* const pSrc) noexcept
{
return _wcsicmp(pDest, pSrc);
}
};
template <typename T>
struct _impl_ts_find {
};
template <>
struct _impl_ts_find<char> {
const char* operator()(const char* const str, const char& srch) noexcept
{
return strchr(str, srch);
}
};
template <>
struct _impl_ts_find<const char> {
const char* operator()(const char* const str, const char& srch) noexcept
{
return strchr(str, srch);
}
};
template <>
struct _impl_ts_find<char*> {
const char* operator()(const char* const str, const char* srch) noexcept
{
return strstr(str, srch);
}
};
template <>
struct _impl_ts_find<const char*> {
const char* operator()(const char* const str, const char* srch) noexcept
{
return strstr(str, srch);
}
};
template <>
struct _impl_ts_find<wchar_t> {
const wchar_t* operator()(const wchar_t* const str, const wchar_t& srch) noexcept
{
return wcschr(str, srch);
}
};
template <>
struct _impl_ts_find<const wchar_t> {
const wchar_t* operator()(const wchar_t* const str, const wchar_t& srch) noexcept
{
return wcschr(str, srch);
}
};
template <>
struct _impl_ts_find<wchar_t*> {
const wchar_t* operator()(const wchar_t* const str, const wchar_t* srch) noexcept
{
return wcsstr(str, srch);
}
};
template <>
struct _impl_ts_find<const wchar_t*> {
const wchar_t* operator()(const wchar_t* const str, const wchar_t* srch) noexcept
{
return wcsstr(str, srch);
}
};
template <typename T>
struct _impl_vscprintf {
};
template <>
struct _impl_vscprintf<char> {
const int operator()(const char* const fmt, const va_list args) noexcept
{
return _vscprintf(fmt, args);
}
};
template <>
struct _impl_vscprintf<wchar_t> {
const int operator()(const wchar_t* const fmt, const va_list args) noexcept
{
return _vscwprintf(fmt, args);
}
};
template <typename T>
struct _impl_vsprintf {
};
template <>
struct _impl_vsprintf<char> {
const int operator()(char* const buf, size_t nCount, const char* const fmt, const va_list args) noexcept
{
return vsnprintf(buf, nCount, fmt, args);
}
};
template <>
struct _impl_vsprintf<wchar_t> {
const int operator()(wchar_t* const buf, size_t nCount, const wchar_t* const fmt, const va_list args) noexcept
{
return vswprintf(buf, nCount, fmt, args);
}
};
template <typename T, typename Format, typename... Arguments>
struct _impl_snprintf {
};
template <typename... Arguments>
struct _impl_snprintf<char, char, Arguments...> {
const int operator()(char* const buf, const size_t nCount, const char* const fmt, const Arguments&&... args) noexcept
{
return snprintf(buf, nCount, fmt, args...);
}
};
template <typename... Arguments>
struct _impl_snprintf<wchar_t, wchar_t, Arguments...> {
const int operator()(wchar_t* const buf, const size_t nCount, const wchar_t* const fmt, const Arguments&&... args) noexcept
{
return _snwprintf(buf, nCount, fmt, args...);
}
};
//template <typename T, typename... Arguments>
//struct _impl_snprintf<T, typename T::value_type, Arguments...> {
// const std::enable_if_t<std::is_member_function_pointer_v<decltype(&T::data)> && std::is_member_function_pointer_v<decltype(&T::size)>, int> operator()(T& buf, const typename T::value_type* const fmt, const Arguments&&... args) noexcept
// {
// if constexpr (std::is_same_v<char, T::value_type>)
// return snprintf(buf.data(), buf.size(), fmt, args...);
// else
// return _snwprintf(buf.data(), buf.size(), fmt, args...);
// }
//};
template <HasDataSizeNoChr T, typename... Arguments>
struct _impl_snprintf<T, typename T::value_type, Arguments...> {
const int operator()(T& buf, const typename T::value_type* const fmt, const Arguments&&... args) noexcept
{
if constexpr (std::is_same_v<char, T::value_type>)
return snprintf(buf.data(), buf.size(), fmt, args...);
else
return _snwprintf(buf.data(), buf.size(), fmt, args...);
}
};
template <HasDataSizeChr T, typename... Arguments>
struct _impl_snprintf<T, typename T::value_type, Arguments...> {
const int operator()(T& buf, const typename T::value_type* const fmt, const Arguments&&... args) noexcept
{
if constexpr (std::is_same_v<char, T::value_type>)
return snprintf(buf.to_chr(), buf.size(), fmt, args...);
else
return _snwprintf(buf.to_chr(), buf.size(), fmt, args...);
}
};
template <typename T>
struct _impl_atoi {
};
template <>
struct _impl_atoi<char> {
auto operator()(const char* const buf) noexcept
{
return atoi(buf);
}
};
template <>
struct _impl_atoi<wchar_t> {
auto operator()(const wchar_t* const buf) noexcept
{
return _wtoi(buf);
}
};
template <typename T>
struct _impl_atoi64 {
};
template <>
struct _impl_atoi64<char> {
auto operator()(const char* const buf) noexcept
{
return _atoi64(buf);
}
};
template <>
struct _impl_atoi64<wchar_t> {
auto operator()(const wchar_t* const buf) noexcept
{
return _wtoi64(buf);
}
};
template <typename T>
struct _impl_atof {
};
template <>
struct _impl_atof<char> {
auto operator()(const char* const buf) noexcept
{
return atof(buf);
}
};
template <>
struct _impl_atof<wchar_t> {
auto operator()(const wchar_t* const buf) noexcept
{
return _wtof(buf);
}
};
template <typename T>
struct _impl_itoa {
};
template <>
struct _impl_itoa<char> {
auto operator()(const int val, char* const buf, const int radix) noexcept
{
return _itoa(val, buf, radix);
}
};
template <>
struct _impl_itoa<wchar_t> {
auto operator()(const int val, wchar_t* const buf, const int radix) noexcept
{
return _itow(val, buf, radix);
}
};
template <typename T>
struct _impl_strtoul {
};
template <>
struct _impl_strtoul<char> {
auto operator()(const char* const buf, char** endptr, int radx) noexcept
{
return strtoul(buf, endptr, radx);
}
};
template <>
struct _impl_strtoul<wchar_t> {
auto operator()(const wchar_t* const buf, wchar_t** endptr, int radx) noexcept
{
return wcstoul(buf, endptr, radx);
}
};
/// <summary>
/// Convert a string representation of a binary number to an unsigned long
/// </summary>
/// <typeparam name="T">- char or wchar_t</typeparam>
template <typename T>
struct _impl_bstrtoul {
};
template <>
struct _impl_bstrtoul<char> {
auto operator()(const char* const buf) noexcept
{
return strtoul(buf, nullptr, 2);
}
};
template <>
struct _impl_bstrtoul<wchar_t> {
auto operator()(const wchar_t* const buf) noexcept
{
return wcstoul(buf, nullptr, 2);
}
};
template <typename T>
struct _impl_strtok {
};
template <>
struct _impl_strtok<char> {
auto operator()(char* const buf, const char* delim, char** contex) noexcept
{
return strtok_s(buf, delim, contex);
}
};
template <>
struct _impl_strtok<wchar_t> {
auto operator()(wchar_t* const buf, const wchar_t* delim, wchar_t** contex) noexcept
{
return wcstok_s(buf, delim, contex);
}
};
}
// Check string bounds, make sure dest is not within the source string & vice versa (this could be a possible reason for some strcpyn() fails we see)
template <details::IsPODText T>
constexpr bool isInBounds(const T* const sDest, const T* const sSrc, const std::size_t iLen) noexcept
{
return (sSrc >= sDest && sSrc <= (sDest + iLen)) || (sDest >= sSrc && sDest <= (sSrc + iLen));
}
template <typename Result, typename Format, typename Value, typename... Arguments>
Result& _ts_sprintf(Result& res, const Format& fmt, const Value& val, Arguments&&... args)
{
static_assert(details::IsPODText<Format>, "Format string must be char or wchar_t");
res.clear();
return details::_ts_printf_do(res, fmt, val, args...);
}
template <details::IsPODText T>
T* _ts_strstr(T* input, const std::remove_const_t<T>* find)
{
return details::impl_strstr<T>()(input, find);
}
// Get String length
template <typename T>
inline auto _ts_strlen(const T& str) noexcept
{
return details::_ts_strlen(str);
}
// Get String length (with buffer size limit)
template <details::IsPODText T>
inline size_t _ts_strnlen(const T& str, const size_t& nBufSize) noexcept
{
return details::_impl_strnlen<T>()(str, nBufSize);
}
// Test if a string is empty, works for any object that has an empty() member function as well as C strings.
template <typename T>
inline bool _ts_isEmpty(const T& str) noexcept
{
return details::_ts_isEmpty(str);
}
// Finds a string or character within a string & returns a pointer to it.
template <details::IsPODText HayStack, details::IsPODText Needle>
inline HayStack* _ts_find(HayStack* const str, Needle srch) noexcept
{
return const_cast<HayStack*>(details::_impl_ts_find<Needle>()(str, srch));
}
template <details::IsPODText HayStack, details::IsPODText Needle>
inline const HayStack* _ts_find(const HayStack* const str, Needle srch) noexcept
{
return details::_impl_ts_find<Needle>()(str, srch);
}
// Finds a string literal within a string & returns a pointer to it.
template <typename T, size_t N>
inline T* _ts_find(T* const str, const T(&srch)[N]) noexcept
{
return const_cast<T*>(details::_impl_ts_find<std::add_pointer_t<T>>()(str, &srch[0]));
}
//// Finds a string or character within a string & returns a pointer to it.
//template <typename T, typename TStr>
//inline TStr *_ts_find(TStr *const str, T &srch)
//{
// return const_cast<TStr *>(details::_impl_ts_find<std::remove_cv_t<T>>()(str, srch));
//}
//
//// Finds a string literal within a string & returns a pointer to it.
//template <typename T, typename TStr, size_t N>
//inline TStr *_ts_find(TStr *const str, const T (&srch)[N])
//{
// return const_cast<TStr *>(details::_impl_ts_find<std::add_pointer_t<T>>()(str, &srch[0]));
//}
//template <typename T, typename TStr>
//inline const TStr *_ts_find(const TStr *const str, const T &srch)
//{
// return details::_impl_ts_find<std::remove_cv_t<T>>()(str, srch);
//}
//
//template <typename T, typename TStr>
//inline TStr *_ts_find(TStr *const str, const T &srch)
//{
// return const_cast<TStr *>(details::_impl_ts_find<std::remove_cv_t<T>>()(str, srch));
//}
template <details::IsPODText T>
T* _ts_strcpyn(T* const sDest, const T* const sSrc, const size_t iChars) noexcept
{
static_assert(details::IsPODText<T>, "Only char & wchar_t supported...");
//#if DCX_DEBUG_OUTPUT
// if ((sDest == nullptr) || (sSrc == nullptr) || isInBounds<std::remove_cv_t<T> >(sDest, sSrc, iChars))
// return nullptr;
//#else
if ((!sDest) || (!sSrc))
return nullptr;
//#endif
return details::_impl_strcpyn<T>()(sDest, sSrc, iChars);
}
template <details::IsPODText T>
T* _ts_strcpy(T* const sDest, const T* const sSrc) noexcept
{
static_assert(details::IsPODText<T>, "Only char & wchar_t supported...");
if ((!sDest) || (!sSrc))
return nullptr;
return details::_impl_strcpy<T>()(sDest, sSrc);
}
template <details::IsPODText T>
T* _ts_strncat(T* const sDest, const T* const sSrc, const size_t iChars) noexcept
{
static_assert(details::IsPODText<T>, "Only char & wchar_t supported...");
return details::_impl_strncat<T>()(sDest, sSrc, iChars);
}
template <details::IsPODText T>
T* _ts_strcat(T* const sDest, const T* const sSrc) noexcept
{
static_assert(details::IsPODText<T>, "Only char & wchar_t supported...");
return details::_impl_strcat<T>()(sDest, sSrc);
}
template <details::IsPODText T>
T* _ts_strchr(T* const sDest, const T ch)
{
static_assert(details::IsPODText<T>, "Only char & wchar_t supported...");
return details::_impl_strchr<T>()(sDest, ch);
}
template <details::IsPODText T>
int _ts_strncmp(const T* const sDest, const T* const sSrc, const size_t iChars) noexcept
{
static_assert(details::IsPODText<T>, "Only char & wchar_t supported...");
return details::_impl_strncmp<T>()(sDest, sSrc, iChars);
}
template <details::IsPODText T>
int _ts_strnicmp(const T* const sDest, const T* const sSrc, const size_t iChars) noexcept
{
static_assert(details::IsPODText<T>, "Only char & wchar_t supported...");
return details::_impl_strnicmp<T>()(sDest, sSrc, iChars);
}
template <details::IsPODText T>
int _ts_strcmp(const T* const sDest, const T* const sSrc) noexcept
{
static_assert(details::IsPODText<T>, "Only char & wchar_t supported...");
return details::_impl_strcmp<T>()(sDest, sSrc);
}
template <details::IsPODText T>
int _ts_stricmp(const T* const sDest, const T* const sSrc) noexcept
{
static_assert(details::IsPODText<T>, "Only char & wchar_t supported...");
return details::_impl_stricmp<T>()(sDest, sSrc);
}
template <details::IsPODText T>
int _ts_vscprintf(_Printf_format_string_ const T* const _Format, va_list _ArgList) noexcept
{
static_assert(details::IsPODText<T>, "Only char & wchar_t supported...");
return details::_impl_vscprintf<T>()(_Format, _ArgList);
}
template <details::IsPODText T>
int _ts_vsprintf(T* const buf, size_t nCount, _Printf_format_string_ const T* const fmt, const va_list args) noexcept
{
static_assert(details::IsPODText<T>, "Only char & wchar_t supported...");
return details::_impl_vsprintf<T>()(buf, nCount, fmt, args);
}
template <details::IsPODText T, typename Format, typename... Arguments>
int _ts_snprintf(T* const buf, const size_t nCount, _Printf_format_string_ const Format* const fmt, Arguments&&... args) noexcept
{
static_assert(details::IsPODText<T>, "Only char & wchar_t supported...");
static_assert(std::is_same_v<std::remove_cv_t<T>, std::remove_cv_t<Format>>, "Buffer & format must have same type.");
return details::_impl_snprintf<T, Format, Arguments...>()(buf, nCount, fmt, std::forward<Arguments>(args)...);
}
template <typename T, details::IsPODText Format, typename... Arguments>
int _ts_snprintf(T& buf, _Printf_format_string_ const Format* const fmt, Arguments&&... args) noexcept
{
static_assert(details::IsPODText<Format>, "Only char & wchar_t supported...");
return details::_impl_snprintf<T, Format, Arguments...>()(buf, fmt, std::forward<Arguments>(args)...);
}
template <details::IsPODText T>
auto _ts_atoi(const T* const buf) noexcept
{
static_assert(details::IsPODText<T>, "Only char & wchar_t supported...");
return details::_impl_atoi<T>()(buf);
}
template <details::IsPODText T>
auto _ts_atoi64(const T* const buf) noexcept
{
static_assert(details::IsPODText<T>, "Only char & wchar_t supported...");
return details::_impl_atoi64<T>()(buf);
}
template <details::IsPODText T>
auto _ts_atof(const T* const buf) noexcept
{
static_assert(details::IsPODText<T>, "Only char & wchar_t supported...");
return details::_impl_atof<T>()(buf);
}
template <details::IsPODText T>
auto _ts_itoa(const int val, T* const buf, const int radix) noexcept
{
static_assert(details::IsPODText<T>, "Only char & wchar_t supported...");
return details::_impl_itoa<T>()(val, buf, radix);
}
template <details::IsPODText T>
auto _ts_strtoul(const T* const buf, T** endptr, int base) noexcept
{
static_assert(details::IsPODText<T>, "Only char & wchar_t supported...");
return details::_impl_strtoul<T>()(buf, endptr, base);
}
/// <summary>
/// Convert a string representation of a binary number to an unsigned long
/// </summary>
/// <param name="buf">- String representing a binary number.</param>
/// <returns>Binary number</returns>
template <details::IsPODText T>
auto _ts_bstrtoul(const T* const buf) noexcept
{
static_assert(details::IsPODText<T>, "Only char & wchar_t supported...");
return details::_impl_bstrtoul<T>()(buf);
}
/// <summary>
/// same as strtok_s()
/// </summary>
/// <param name="buf"></param>
/// <param name="delim"></param>
/// <param name="contex"></param>
/// <returns></returns>
template <details::IsPODText T>
auto _ts_strtok(T* const buf, const T* delim, T** contex) noexcept
{
static_assert(details::IsPODText<T>, "Only char & wchar_t supported...");
return details::_impl_strtok<T>()(buf, delim, contex);
}
/// <summary>
/// Converts a number into a binary string representing that number (whole integers only)
/// </summary>
/// <typeparam name="Result">A string type object</typeparam>
/// <param name="a">- The number to convert.</param>
/// <returns>The string representation of the number.</returns>
template <details::IsNumeric T, class Result>
Result DecimalToBinaryString(const T& a)
{
Result binary;
constexpr auto sz = sizeof(a) * 8;
std::remove_const_t<T> mask = 1;
for (std::remove_const_t<decltype(sz)> i = 0; i < sz; ++i)
{
if ((mask & a))
binary = '1' + binary;
else
binary = '0' + binary;
mask <<= 1;
}
return binary;
}
/// <summary>
/// Replace all instances of 'rep' in 'str' with 'with'
/// </summary>
/// <typeparam name="T"></typeparam>
/// <typeparam name="RepThis"></typeparam>
/// <typeparam name="WithThis"></typeparam>
/// <param name="str">- string to search</param>
/// <param name="rep">- string to search for</param>
/// <param name="with">- replacement string</param>
/// <returns>The string it was passed with the changes made.</returns>
template <class T, class RepThis, class WithThis>
T& _ts_replace(T& str, RepThis rep, WithThis with)
{
for (std::size_t wlen = _ts_strlen(with), rlen = _ts_strlen(rep), pos = 0U; ; pos += wlen)
{
pos = str.find(rep, pos);
if (pos == T::npos)
break;
if constexpr (std::is_same_v<char, std::remove_cv_t<WithThis>> || std::is_same_v<wchar_t, std::remove_cv_t<WithThis>>)
{
str.replace(pos, rlen, 1, with);
}
else
{
str.replace(pos, rlen, with);
}
}
return str;
}
//void ReplaceStringInPlace(std::string& subject, const std::string& search, const std::string& replace)
//{
// size_t pos = 0;
// while ((pos = subject.find(search, pos)) != std::string::npos)
// {
// subject.replace(pos, search.length(), replace);
// pos += replace.length();
// }
//}
/// <summary>
/// Replace all instances of each character in 'rep' in 'str' with 'with'
/// </summary>
/// <typeparam name="T"></typeparam>
/// <typeparam name="RepThis"></typeparam>
/// <typeparam name="WithThis"></typeparam>
/// <param name="str">- string to search</param>
/// <param name="rep">- string of characters to search for</param>
/// <param name="with">- replacement string</param>
/// <returns>The string it was passed with the changes made.</returns>
template <class T, class RepThis, class WithThis>
T& _ts_mreplace(T& str, RepThis rep, WithThis with)
{
for (std::ptrdiff_t i = 0; rep[i] != 0; ++i)
_ts_replace(str, rep[i], with);
return str;
}
/// <summary>
/// Remove all instances of 'rep' within 'str'
/// </summary>
/// <typeparam name="T"></typeparam>
/// <typeparam name="RemThis"></typeparam>
/// <param name="str">- string to search.</param>
/// <param name="rep">- string to remove.</param>
/// <returns>The string it was passed with the changes made.</returns>
template <class T, class RemThis>
T& _ts_remove(T& str, RemThis rep)
{
for (auto itEnd = str.end(), itStart = str.begin(); str.erase(std::find(itStart, itEnd, rep)) != itEnd; ) {}
return str;
}
/// <summary>
/// Remove spaces from the front and back of the string.
/// </summary>
/// <typeparam name="T">A string type object</typeparam>
/// <param name="str">- The string to trim.</param>
/// <returns>A reference to the same string object it was passed.</returns>
template <class T>
T& _ts_trim(T& str)
{
if (str.empty())
return str;
while (str.front() == _T(' '))
str.erase(0, 1);
while (str.back() == _T(' '))
str.pop_back();
return str;
}
/// <summary>
/// Copies the string then remove spaces from the front and back of the string.
/// </summary>
/// <typeparam name="T">A string type object</typeparam>
/// <param name="str">- The string to trim.</param>
/// <returns>A copy of the string object it was passed.</returns>
template <class T>
T _ts_trim_and_copy(const T& str)
{
if (str.empty())
return str;
T res(str);
while (res.front() == _T(' '))
res.erase(0, 1);
while (res.back() == _T(' '))
res.pop_back();
return res;
}
/// <summary>
/// Trim the string and remove double spaces.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="str">- string to modify.</param>
/// <returns>The string it was passed with the changes made.</returns>
template <class T>
T& _ts_strip(T& str)
{
//_ts_remove(str, _T('\0x02')); //02
//_ts_remove(str, _T('\0x0F')); //15
//_ts_remove(str, _T('\0x16')); //22
//_ts_remove(str, _T('\0x1D')); //29
_ts_replace(str, _T(" "), _T(' '));
// NB: TODO: add ctrl-k removal for colour codes.
return _ts_trim(str);
}
/// <summary>
/// Change a string to uppercase.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="str">- string to modify.</param>
/// <returns>The string it was passed with the changes made.</returns>
template <class T>
T& _ts_toupper(T& str)
{
for (auto& a : str)
a = details::make_upper(a);
return str;
}
template <details::IsPODText T>
T _ts_toupper_c(const T& c) noexcept
{
return details::make_upper(c);
}
template <details::IsPODText T>
bool _ts_isupper(const T& c) noexcept
{
if constexpr (std::is_same_v<wchar_t, T>)
return (iswupper(c) != 0);
else
return (isupper(c) != 0);
}
/// <summary>
/// Convert a string to a number.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <typeparam name="Input"></typeparam>
/// <param name="str">- string to convert.</param>
/// <returns>The number contained in the string.</returns>
template <class T, class Input>
T _ts_to_(const Input& str)
{
static_assert(is_Numeric_v<T>, "Type T must be (int, long, float, double, ....)");
std::basic_istringstream<TCHAR> ss(str); // makes copy of string :(
T result{};
return ss >> result ? result : T();
}
#define TSTRING_WILDT 0
#define TSTRING_WILDA 0
#define TSTRING_WILDE 0
#define TSTRING_WILDW 0
//template <class T>
//constexpr auto getWildType(T s) noexcept
//{
// if constexpr (details::is_pod_v<T>)
// return typename std::remove_pointer_t<std::remove_cv_t<std::remove_all_extents_t<T>>>;
// else
// return typename std::remove_pointer_t<std::remove_cv_t<std::remove_all_extents_t<T::value_type>>>;
//}
//
//template <typename TameString, typename WildString>
//[[gsl::suppress(bounds)]] bool _ts_WildcardMatch(const TameString& pszString, const WildString& pszMatch, const bool bCase = false)
//{
// //if ((!pszMatch) || (!pszString))
// // return false;
//
// if (_ts_isEmpty(pszMatch) || _ts_isEmpty(pszString))
// return false;
//
// ptrdiff_t MatchPlaceholder = 0;
// ptrdiff_t StringPlaceholder = 0;
// ptrdiff_t iWildOffset = 0;
// ptrdiff_t iTameOffset = 0;
//
// //using _WildString = typename std::remove_pointer_t<std::remove_cv_t<std::remove_all_extents_t<WildString::value_type>>>;
// using _WildString = typename std::remove_pointer_t<std::remove_cv_t<std::remove_all_extents_t<WildString>>>;
// //auto a = getWildType(pszMatch);
//
// constexpr _WildString _zero{};
// constexpr _WildString _star = static_cast<_WildString>('*');
// constexpr _WildString _question = static_cast<_WildString>('?');
// constexpr _WildString _tilda = static_cast<_WildString>('~');
// constexpr _WildString _space = static_cast<_WildString>(' ');
// constexpr _WildString _power = static_cast<_WildString>('^');
// constexpr _WildString _hash = static_cast<_WildString>('#');
// constexpr _WildString _slash = static_cast<_WildString>('\\');
// constexpr _WildString _tab = static_cast<_WildString>('\t');
// constexpr _WildString _n = static_cast<_WildString>('\n');
// constexpr _WildString _r = static_cast<_WildString>('\r');
//
// while (pszString[iTameOffset])
// {
// if (pszMatch[iWildOffset] == _star)
// {
// if (pszMatch[++iWildOffset] == _zero)
// return true;
// MatchPlaceholder = iWildOffset;
// StringPlaceholder = iTameOffset + 1;
// }
//#if TSTRING_WILDT
// else if (pszMatch[iWildOffset] == _tilda && pszString[iTameOffset] == _space)
// {
// ++iWildOffset;
// while (pszString[iTameOffset] == _space)
// ++iTameOffset;
// }
//#endif
//#if TSTRING_WILDA
// else if (pszMatch[iWildOffset] == _power)
// {
// ++iWildOffset;
// if (details::CompareChar(pszMatch[iWildOffset], pszString[iTameOffset], bCase))
// ++iTameOffset;
// ++iWildOffset;
// }
//#endif
//#if TSTRING_WILDE
// else if (pszMatch[iWildOffset] == _slash)
// {
// // any character following a '\' is taken as a literal character.
// ++iWildOffset;
// if (!details::CompareChar(pszMatch[iWildOffset], pszString[iTameOffset], bCase))
// return false;
// ++iTameOffset;
// }
//#endif
//#if TSTRING_WILDW
// else if (pszMatch[iWildOffset] == _hash)
// {
// ++iWildOffset;
// while (pszString[iTameOffset] && (pszString[iTameOffset] != _space || pszString[iTameOffset] != _tab || pszString[iTameOffset] != _n || pszString[iTameOffset] != _r))
// ++iTameOffset;
// }
//#endif
// //else if (pszMatch[iWildOffset] == TEXT('?') || _toupper(pszMatch[iWildOffset]) == _toupper(pszString[iTameOffset]))
// else if (pszMatch[iWildOffset] == _question || details::CompareChar(pszMatch[iWildOffset], pszString[iTameOffset], bCase))
// {
// ++iWildOffset;
// ++iTameOffset;
// }
// else if (StringPlaceholder == 0)
// return false;
// else
// {
// iWildOffset = MatchPlaceholder;
// iTameOffset = StringPlaceholder++;
// }
// }
//
// while (pszMatch[iWildOffset] == _star)
// ++iWildOffset;
//
// return !pszMatch[iWildOffset];
//}
/// <summary>
/// Internal wildcard match function.
/// </summary>
/// <typeparam name="_Wild"></typeparam>
/// <typeparam name="TameString"></typeparam>
/// <typeparam name="WildString"></typeparam>
/// <param name="pszString"></param>
/// <param name="pszMatch"></param>
/// <param name="bCase"></param>
/// <returns></returns>
template <class _Wild, typename TameString, typename WildString>
GSL_SUPPRESS(bounds.4) bool _ts_InnerWildcardMatch(const TameString& pszString, const WildString& pszMatch, const bool bCase) noexcept(std::is_nothrow_move_assignable_v<WildString>)
{
ptrdiff_t MatchPlaceholder = 0;
ptrdiff_t StringPlaceholder = 0;
ptrdiff_t iWildOffset = 0;
ptrdiff_t iTameOffset = 0;
constexpr _Wild _zero{};
constexpr _Wild _star = static_cast<_Wild>('*');
constexpr _Wild _question = static_cast<_Wild>('?');
constexpr _Wild _tilda = static_cast<_Wild>('~');
constexpr _Wild _space = static_cast<_Wild>(' ');
constexpr _Wild _power = static_cast<_Wild>('^');
constexpr _Wild _hash = static_cast<_Wild>('#');
constexpr _Wild _slash = static_cast<_Wild>('\\');
constexpr _Wild _tab = static_cast<_Wild>('\t');
constexpr _Wild _n = static_cast<_Wild>('\n');
constexpr _Wild _r = static_cast<_Wild>('\r');
while (pszString[iTameOffset])
{
if (pszMatch[iWildOffset] == _star)
{
if (pszMatch[++iWildOffset] == _zero)
return true;
MatchPlaceholder = iWildOffset;
StringPlaceholder = iTameOffset + 1;
}
#if TSTRING_WILDT
else if (pszMatch[iWildOffset] == _tilda && pszString[iTameOffset] == _space)
{
++iWildOffset;
while (pszString[iTameOffset] == _space)
++iTameOffset;
}
#endif
#if TSTRING_WILDA
else if (pszMatch[iWildOffset] == _power)
{
++iWildOffset;
if (details::CompareChar(pszMatch[iWildOffset], pszString[iTameOffset], bCase))
++iTameOffset;
++iWildOffset;
}
#endif
#if TSTRING_WILDE
else if (pszMatch[iWildOffset] == _slash)
{
// any character following a '\' is taken as a literal character.
++iWildOffset;
if (!details::CompareChar(pszMatch[iWildOffset], pszString[iTameOffset], bCase))
return false;
++iTameOffset;
}
#endif
#if TSTRING_WILDW
else if (pszMatch[iWildOffset] == _hash)
{
++iWildOffset;
while (pszString[iTameOffset] && (pszString[iTameOffset] != _space || pszString[iTameOffset] != _tab || pszString[iTameOffset] != _n || pszString[iTameOffset] != _r))
++iTameOffset;
}
#endif
//else if (pszMatch[iWildOffset] == _question || _toupper(pszMatch[iWildOffset]) == _toupper(pszString[iTameOffset]))
else if (pszMatch[iWildOffset] == _question || details::CompareChar(pszMatch[iWildOffset], pszString[iTameOffset], bCase))
{
++iWildOffset;
++iTameOffset;
}
else if (StringPlaceholder == 0)
return false;
else
{
iWildOffset = MatchPlaceholder;
iTameOffset = StringPlaceholder++;
}
}
while (pszMatch[iWildOffset] == _star)
++iWildOffset;
return !pszMatch[iWildOffset];
}
/// <summary>
/// Wildcard match
/// </summary>
/// <typeparam name="TameString"></typeparam>
/// <typeparam name="WildString"></typeparam>
/// <param name="pszString">- string to search</param>
/// <param name="pszMatch">- the wildcard string to search for.</param>
/// <param name="bCase">- does case matter</param>
/// <returns>did match succeed true/false</returns>
template <typename TameString, typename WildString>
GSL_SUPPRESS(bounds) bool _ts_WildcardMatch(const TameString& pszString, const WildString& pszMatch, const bool bCase = false) noexcept(std::is_nothrow_move_assignable_v<WildString>)
{
if (_ts_isEmpty(pszMatch) || _ts_isEmpty(pszString))
return false;
if constexpr (details::is_pod_v<std::remove_pointer_t<std::remove_cv_t<std::remove_all_extents_t<WildString>>>>)
return _ts_InnerWildcardMatch<std::remove_pointer_t<std::remove_cv_t<std::remove_all_extents_t<WildString>>>>(pszString, pszMatch, bCase);
else
return _ts_InnerWildcardMatch<std::remove_pointer_t<std::remove_cv_t<std::remove_all_extents_t<WildString::value_type>>>>(pszString, pszMatch, bCase);
}
template <typename T> T* _ts_AddMem(std::vector<std::shared_ptr<std::vector<char>>>& mem, std::size_t sz = sizeof(T))
{
std::shared_ptr<std::vector<char>> x = std::make_shared<std::vector<char>>();
x->resize(sz);
mem.push_back(x);
T* d = (T*)mem[mem.size() - 1].get()->data();
return d;
}
/// <summary>
/// Sort a vector
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="str">- The vector to sort.</param>
/// <returns>A sorted copy of the input.</returns>
template <class T>
std::vector<T> _ts_SortString(const std::vector<T>& str)
{
std::vector<T> out(str);
std::sort(out.begin(), out.end(), std::less<T>);
return out;
}
| {
"alphanum_fraction": 0.6503683582,
"avg_line_length": 29.2911392405,
"ext": "h",
"hexsha": "f214a8321168ab3ef5a3babd767986f99d63f565",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2018-08-04T23:53:29.000Z",
"max_forks_repo_forks_event_min_datetime": "2018-04-01T09:39:33.000Z",
"max_forks_repo_head_hexsha": "cd0cb308b76daf0be614025d71670580007a0d78",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "twig/dcxdll",
"max_forks_repo_path": "Classes/tstring/string_support.h",
"max_issues_count": 68,
"max_issues_repo_head_hexsha": "cd0cb308b76daf0be614025d71670580007a0d78",
"max_issues_repo_issues_event_max_datetime": "2022-03-09T17:33:50.000Z",
"max_issues_repo_issues_event_min_datetime": "2015-04-06T16:23:35.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "twig/dcxdll",
"max_issues_repo_path": "Classes/tstring/string_support.h",
"max_line_length": 240,
"max_stars_count": 18,
"max_stars_repo_head_hexsha": "cd0cb308b76daf0be614025d71670580007a0d78",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "twig/dcxdll",
"max_stars_repo_path": "Classes/tstring/string_support.h",
"max_stars_repo_stars_event_max_datetime": "2022-02-26T00:48:31.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-02-21T05:41:19.000Z",
"num_tokens": 14064,
"size": 48594
} |
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <assert.h>
#include <string.h>
#include <time.h>
#include <sys/time.h>
#include <gsl/gsl_math.h>
#include "cosmocalc.h"
#include "haloprofs.h"
#include "weaklens.h"
void test_cosmo(char *path);
int main(int argc, char **argv)
{
cosmoData.useSmoothTransFunc = 0;
cosmoData.delta = 200.0;
char path[4096];
//init cosmology 2
cosmoData.cosmoNum = 2;
cosmoData.OmegaM = 0.28;
cosmoData.OmegaL = 0.72;
cosmoData.OmegaB = 0.05;
cosmoData.OmegaNu = 0.0;
cosmoData.OmegaK = 0.0;
cosmoData.h = 0.7;
cosmoData.w0 = -1.0;
cosmoData.wa = 0.0;
cosmoData.SpectralIndex = 0.96;
cosmoData.Sigma8 = 0.8;
sprintf(path,"./cosmo2");
test_cosmo(path);
//init cosmology 1
cosmoData.cosmoNum = 1;
cosmoData.OmegaM = 0.3;
cosmoData.OmegaL = 0.68;
cosmoData.OmegaB = 0.05;
cosmoData.OmegaNu = 0.0;
cosmoData.OmegaK = 1.0 - cosmoData.OmegaM - cosmoData.OmegaL - cosmoData.OmegaNu;
cosmoData.h = 0.7;
cosmoData.w0 = -0.8;
cosmoData.wa = 0.2;
cosmoData.SpectralIndex = 0.96;
cosmoData.Sigma8 = 0.8;
sprintf(path,"./cosmo1");
test_cosmo(path);
return 0;
}
void test_cosmo(char *path)
{
char fname[4096];
char fnameo[4096];
char str[4096];
FILE *fp;
FILE *fpout;
double z;
sprintf(fname,"%s/codist.dat",path);
sprintf(fnameo,"%s/codist.dat.matt",path);
fp = fopen(fname,"r");
if( fp != NULL)
{
fpout = fopen(fnameo,"w");
while(fgets(str,4096,fp) != NULL)
{
if(str[0] == '#')
continue;
sscanf(str,"%le %*e\n",&z);
fprintf(fpout,"%e %e\n",z,comvdist(1.0/(1.0+z)));
}
fclose(fp);
fclose(fpout);
}
sprintf(fname,"%s/Evol_z.dat",path);
sprintf(fnameo,"%s/Evol_z.dat.matt",path);
fp = fopen(fname,"r");
if(fp != NULL)
{
fpout = fopen(fnameo,"w");
while(fgets(str,4096,fp) != NULL)
{
if(str[0] == '#')
continue;
sscanf(str,"%le %*e\n",&z);
//fprintf(stderr,"weff(%f) = %f, h(a) = %f\n",1.0/(1.0+z),weff(1.0/(1.0+z)),hubble_noscale(1.0/(1.0+z)));
fprintf(fpout,"%e %e\n",z,hubble_noscale(1.0/(1.0+z)));
}
fclose(fp);
fclose(fpout);
}
}
| {
"alphanum_fraction": 0.6006404392,
"avg_line_length": 21.2233009709,
"ext": "c",
"hexsha": "f68930ec925123d789993523f6f9f2b79204623a",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2017-08-11T17:31:51.000Z",
"max_forks_repo_forks_event_min_datetime": "2017-07-14T12:17:31.000Z",
"max_forks_repo_head_hexsha": "aa7d7cb58f05a36d446e02b45a9117d93eb16556",
"max_forks_repo_licenses": [
"Unlicense"
],
"max_forks_repo_name": "beckermr/cosmocalc",
"max_forks_repo_path": "src/main.c",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "aa7d7cb58f05a36d446e02b45a9117d93eb16556",
"max_issues_repo_issues_event_max_datetime": "2016-04-05T19:36:21.000Z",
"max_issues_repo_issues_event_min_datetime": "2016-04-05T19:10:45.000Z",
"max_issues_repo_licenses": [
"Unlicense"
],
"max_issues_repo_name": "beckermr/cosmocalc",
"max_issues_repo_path": "src/main.c",
"max_line_length": 108,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "aa7d7cb58f05a36d446e02b45a9117d93eb16556",
"max_stars_repo_licenses": [
"Unlicense"
],
"max_stars_repo_name": "beckermr/cosmocalc",
"max_stars_repo_path": "src/main.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 839,
"size": 2186
} |
#include <assert.h>
#include <math.h>
#include <gsl/gsl_randist.h>
#include "nmcalc.h"
void get_ab(struct variant_table *v, struct variant_counts **a, struct variant_counts **b);
// Convenience function to mimic MATLAB function
static inline double binopdf(unsigned int x, unsigned int n, double p) {
return gsl_ran_binomial_pdf(x, p, n);
}
#define NONZERO_OR_NAN(X, NAN_CODE) ((X) == (X) ? (X) : nan(#NAN_CODE))
void nmcalc(struct context *context,
struct variant_table *v,
double prior_map_error,
int ploidy,
struct nm_entry *out)
{
(void) context;
double a_read_depth, b_read_depth;
double a_mean_mq, b_mean_mq;
double prior_hom, prior_het;
double p_data_map_error, p_data_hom, p_data_het, p_data;
double p_map_error;
double per_read_pass, ab_frac;
struct variant_counts *a, *b;
get_ab(v, &a, &b);
// Initialization of useful variables
a_read_depth = (a->count_f + a->count_r) / 2.0;
b_read_depth = (b->count_f + b->count_r) / 2.0;
a_mean_mq = a->total_mq / NONZERO_OR_NAN(a_read_depth, 200);
b_mean_mq = b->total_mq / NONZERO_OR_NAN(b_read_depth, 200);
// Normal metrics calculation starts here
// priors
if (ploidy == 2) {
prior_het = 2 * a->pop_af * b->pop_af;
} else {
prior_het = 0;
}
prior_hom = a->pop_af * a->pop_af;
// likelihoods
p_data_map_error = pow(10, -fmin(a_mean_mq, b_mean_mq)/10);
p_data_hom = binopdf(b_read_depth, v->read_count_pass, pow(10, (-b_mean_mq / 10)));
p_data_het = binopdf(b_read_depth, v->read_count_pass, 0.5);
p_data = prior_map_error * p_data_map_error + prior_het * p_data_het + prior_hom * p_data_hom;
// posteriors
if (v->read_count_pass > 0) {
p_map_error = prior_map_error * p_data_map_error / p_data;
} else {
p_map_error = nan("300");
}
// other metrics
per_read_pass = v->read_count_pass / NONZERO_OR_NAN(v->read_count, 200);
ab_frac = (a_read_depth + b_read_depth) / NONZERO_OR_NAN(v->read_count_pass, 200);
out->pos = v->offset;
if (ploidy == 1 || ploidy == 2) {
out->norm_read_depth = (3-ploidy) * v->read_count_pass; // sneak
out->prob_map_err = p_map_error;
out->read_pass = per_read_pass;
out->a_or_b = ab_frac;
} else {
out->norm_read_depth = nan("101");
out->prob_map_err = nan("102");
out->read_pass = nan("103");
out->a_or_b = nan("104");
}
}
| {
"alphanum_fraction": 0.6853836262,
"avg_line_length": 26.5113636364,
"ext": "c",
"hexsha": "08c456412c2fa0bca8145c2d6580d380dc30f2c2",
"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": "eaa664f584b23864244b33d27797e31d12c4ab07",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "tgen/gvm",
"max_forks_repo_path": "src/nmcalc.c",
"max_issues_count": 2,
"max_issues_repo_head_hexsha": "eaa664f584b23864244b33d27797e31d12c4ab07",
"max_issues_repo_issues_event_max_datetime": "2020-05-22T20:44:42.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-02-24T22:37:00.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "tgen/gvm",
"max_issues_repo_path": "src/nmcalc.c",
"max_line_length": 95,
"max_stars_count": 2,
"max_stars_repo_head_hexsha": "eaa664f584b23864244b33d27797e31d12c4ab07",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "tgen/gvm",
"max_stars_repo_path": "src/nmcalc.c",
"max_stars_repo_stars_event_max_datetime": "2020-01-12T11:40:43.000Z",
"max_stars_repo_stars_event_min_datetime": "2018-07-12T02:18:53.000Z",
"num_tokens": 747,
"size": 2333
} |
#include <petsc.h>
#if PETSC_VERSION_LE(3,3,0)
PETSC_EXTERN PetscErrorCode PetscOptionsGetViewer(MPI_Comm,const char[],const char[],PetscViewer*,PetscViewerFormat*,PetscBool*);
#undef __FUNCT__
#define __FUNCT__ "PetscEListFind"
static PetscErrorCode PetscEListFind(PetscInt n,const char *const *list,const char *str,PetscInt *value,PetscBool *found)
{
PetscInt i;
PetscBool matched;
PetscErrorCode ierr;
PetscFunctionBegin;
if (found) *found = PETSC_FALSE;
for (i=0; i<n; i++) {
ierr = PetscStrcasecmp(str,list[i],&matched);CHKERRQ(ierr);
if (matched || !str[0]) {
if (found) *found = PETSC_TRUE;
*value = i;
break;
}
}
PetscFunctionReturn(0);
}
#undef __FUNCT__
#define __FUNCT__ "PetscEnumFind"
static PetscErrorCode PetscEnumFind(const char *const *enumlist,const char *str,PetscEnum *value,PetscBool *found)
{
PetscInt n,evalue;
PetscBool efound;
PetscErrorCode ierr;
PetscFunctionBegin;
for (n = 0; enumlist[n]; n++) {
if (n > 50) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"List argument appears to be wrong or have more than 50 entries");
}
if (n < 3) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"List argument must have at least two entries: typename and type prefix");
n -= 3; /* drop enum name, prefix, and null termination */
ierr = PetscEListFind(n,enumlist,str,&evalue,&efound);CHKERRQ(ierr);
if (efound) *value = (PetscEnum)evalue;
if (found) *found = efound;
PetscFunctionReturn(0);
}
#undef __FUNCT__
#define __FUNCT__ "PetscOptionsGetViewer"
PetscErrorCode PetscOptionsGetViewer(MPI_Comm comm,const char pre[],const char name[],PetscViewer *viewer,PetscViewerFormat *format,PetscBool *set)
{
char value[2*PETSC_MAX_PATH_LEN];
PetscBool flag;
PetscErrorCode ierr;
PetscFunctionBegin;
PetscValidCharPointer(name,3);
if (format) *format = PETSC_VIEWER_DEFAULT;
if (set) *set = PETSC_FALSE;
ierr = PetscOptionsGetString(pre,name,value,sizeof(value),&flag);CHKERRQ(ierr);
if (flag) {
if (set) *set = PETSC_TRUE;
if (!value[0]) {
ierr = PetscViewerASCIIGetStdout(comm,viewer);CHKERRQ(ierr);
ierr = PetscObjectReference((PetscObject)*viewer);CHKERRQ(ierr);
} else {
char *loc0_vtype,*loc1_fname,*loc2_fmt = NULL,*loc3_fmode = NULL;
PetscInt cnt;
const char *const PetscFileModes[] = {"READ","WRITE","APPEND","UPDATE","APPEND_UPDATE","PetscFileMode","PETSC_FILE_",0};
const char *const viewers[] = {PETSCVIEWERASCII,PETSCVIEWERBINARY,PETSCVIEWERDRAW,PETSCVIEWERSOCKET,PETSCVIEWERMATLAB,PETSCVIEWERAMS,PETSCVIEWERVTK,0};
ierr = PetscStrallocpy(value,&loc0_vtype);CHKERRQ(ierr);
ierr = PetscStrchr(loc0_vtype,':',&loc1_fname);CHKERRQ(ierr);
if (loc1_fname) {
*loc1_fname++ = 0;
ierr = PetscStrchr(loc1_fname,':',&loc2_fmt);CHKERRQ(ierr);
}
if (loc2_fmt) {
*loc2_fmt++ = 0;
ierr = PetscStrchr(loc2_fmt,':',&loc3_fmode);CHKERRQ(ierr);
}
if (loc3_fmode) *loc3_fmode++ = 0;
ierr = PetscStrendswithwhich(*loc0_vtype ? loc0_vtype : "ascii",viewers,&cnt);CHKERRQ(ierr);
if (cnt > (PetscInt)sizeof(viewers)-1) SETERRQ1(comm,PETSC_ERR_ARG_OUTOFRANGE,"Unknown viewer type: %s",loc0_vtype);
if (!loc1_fname) {
switch (cnt) {
case 0:
ierr = PetscViewerASCIIGetStdout(comm,viewer);CHKERRQ(ierr);
break;
case 1:
if (!(*viewer = PETSC_VIEWER_BINARY_(comm))) CHKERRQ(PETSC_ERR_PLIB);
break;
case 2:
if (!(*viewer = PETSC_VIEWER_DRAW_(comm))) CHKERRQ(PETSC_ERR_PLIB);
break;
#if defined(PETSC_USE_SOCKET_VIEWER)
case 3:
if (!(*viewer = PETSC_VIEWER_SOCKET_(comm))) CHKERRQ(PETSC_ERR_PLIB);
break;
#endif
#if defined(PETSC_HAVE_MATLAB_ENGINE)
case 4:
if (!(*viewer = PETSC_VIEWER_MATLAB_(comm))) CHKERRQ(PETSC_ERR_PLIB);
break;
#endif
#if defined(PETSC_HAVE_AMS)
case 5:
if (!(*viewer = PETSC_VIEWER_AMS_(comm))) CHKERRQ(PETSC_ERR_PLIB);
break;
#endif
default: SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Unsupported viewer %s",loc0_vtype);
}
ierr = PetscObjectReference((PetscObject)*viewer);CHKERRQ(ierr);
} else {
if (loc2_fmt && !*loc1_fname && (cnt == 0)) { /* ASCII format without file name */
ierr = PetscViewerASCIIGetStdout(comm,viewer);CHKERRQ(ierr);
ierr = PetscObjectReference((PetscObject)*viewer);CHKERRQ(ierr);
} else {
PetscFileMode fmode;
ierr = PetscViewerCreate(comm,viewer);CHKERRQ(ierr);
ierr = PetscViewerSetType(*viewer,*loc0_vtype ? loc0_vtype : "ascii");CHKERRQ(ierr);
#if defined(PETSC_HAVE_AMS)
ierr = PetscViewerAMSSetCommName(*viewer,loc1_fname);CHKERRQ(ierr);
#endif
fmode = FILE_MODE_WRITE;
if (loc3_fmode && *loc3_fmode) { /* Has non-empty file mode ("write" or "append") */
ierr = PetscEnumFind(PetscFileModes,loc3_fmode,(PetscEnum*)&fmode,&flag);CHKERRQ(ierr);
if (!flag) SETERRQ1(comm,PETSC_ERR_ARG_UNKNOWN_TYPE,"Unknown file mode: %s",loc3_fmode);
}
ierr = PetscViewerFileSetMode(*viewer,flag?fmode:FILE_MODE_WRITE);CHKERRQ(ierr);
ierr = PetscViewerFileSetName(*viewer,loc1_fname);CHKERRQ(ierr);
}
}
if (loc2_fmt && *loc2_fmt) {
ierr = PetscEnumFind(PetscViewerFormats,loc2_fmt,(PetscEnum*)format,&flag);CHKERRQ(ierr);
if (!flag) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Unknown viewer format %s",loc2_fmt);CHKERRQ(ierr);
if (((int)*format) >= 5) *format = (PetscViewerFormat)(((int)*format)-2); /**/
}
ierr = PetscViewerSetUp(*viewer);CHKERRQ(ierr);
ierr = PetscFree(loc0_vtype);CHKERRQ(ierr);
}
}
PetscFunctionReturn(0);
}
#endif
| {
"alphanum_fraction": 0.666212766,
"avg_line_length": 41.3732394366,
"ext": "c",
"hexsha": "1bdc512c56fa7fd50d65922fd33029935cd0cbdb",
"lang": "C",
"max_forks_count": 5,
"max_forks_repo_forks_event_max_datetime": "2021-06-14T10:40:40.000Z",
"max_forks_repo_forks_event_min_datetime": "2016-11-08T12:55:17.000Z",
"max_forks_repo_head_hexsha": "ce8c07de8511000ee6f1cbfd3fb90fda9cb31954",
"max_forks_repo_licenses": [
"BSD-2-Clause"
],
"max_forks_repo_name": "otherlab/petiga",
"max_forks_repo_path": "src/petscvwopt.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "ce8c07de8511000ee6f1cbfd3fb90fda9cb31954",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-2-Clause"
],
"max_issues_repo_name": "otherlab/petiga",
"max_issues_repo_path": "src/petscvwopt.c",
"max_line_length": 157,
"max_stars_count": 4,
"max_stars_repo_head_hexsha": "ce8c07de8511000ee6f1cbfd3fb90fda9cb31954",
"max_stars_repo_licenses": [
"BSD-2-Clause"
],
"max_stars_repo_name": "otherlab/petiga",
"max_stars_repo_path": "src/petscvwopt.c",
"max_stars_repo_stars_event_max_datetime": "2021-06-14T10:40:32.000Z",
"max_stars_repo_stars_event_min_datetime": "2017-08-31T21:20:27.000Z",
"num_tokens": 1679,
"size": 5875
} |
#ifndef GBNET_GRAPHBASE
#define GBNET_GRAPHBASE
#include <iostream>
#include <string>
#include <vector>
#include <utility>
#include <map>
#include <set>
#include <stdio.h>
#include <gsl/gsl_rng.h>
#include "RVNode.h"
#include "XNode.h"
#include "HNodeORNOR.h"
#include "YDataNode.h"
#include "SNode.h"
#include "NodeDictionary.h"
namespace gbn
{
// used accross module. might want to find a better place for these typedefs
typedef std::vector<RVNode *> node_vector_t;
typedef std::pair<std::string, int> trg_de_pair_t;
typedef std::map<std::string, int> evidence_dict_t;
typedef std::set<std::string> prior_active_tf_set_t;
typedef std::pair<std::string, std::string> src_trg_pair_t;
typedef std::pair<src_trg_pair_t, int> network_edge_t;
typedef std::vector<network_edge_t> network_t;
class GraphBase
{
private:
protected:
gsl_rng * rng;
public:
node_vector_t random_nodes;
node_vector_t norand_nodes; /* Used to keep track of node pointers for later destruction */
GraphBase (unsigned int);
virtual ~GraphBase ();
void sample (unsigned int);
void burn_stats();
void print_stats();
};
}
#endif | {
"alphanum_fraction": 0.6570086139,
"avg_line_length": 22.4035087719,
"ext": "h",
"hexsha": "cdbb41a1f49d3a4b9ecb5ee8a41c6d3d4da63545",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2019-06-10T16:19:58.000Z",
"max_forks_repo_forks_event_min_datetime": "2019-06-10T16:19:58.000Z",
"max_forks_repo_head_hexsha": "0e478d764cfa02eaed3e32d11d03c240c78e2ff6",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "umbibio/gbnet",
"max_forks_repo_path": "libgbnet/include/GraphBase.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "0e478d764cfa02eaed3e32d11d03c240c78e2ff6",
"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": "umbibio/gbnet",
"max_issues_repo_path": "libgbnet/include/GraphBase.h",
"max_line_length": 103,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "0e478d764cfa02eaed3e32d11d03c240c78e2ff6",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "umbibio/gbnet",
"max_stars_repo_path": "libgbnet/include/GraphBase.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 305,
"size": 1277
} |
#ifndef EXT_VANILLAGENERATOR_LIB_OBJECTS_BIOMEARRAY_H_
#define EXT_VANILLAGENERATOR_LIB_OBJECTS_BIOMEARRAY_H_
#include <cstddef>
#include <gsl/span>
class BiomeArray {
public:
static const size_t DATA_SIZE = 256;
explicit BiomeArray(const gsl::span<const uint_fast8_t, BiomeArray::DATA_SIZE> &values);
auto Get(uint8_t x, uint8_t z) const -> uint_fast8_t;
auto Set(uint8_t x, uint8_t z, uint_fast8_t value) -> void;
[[nodiscard]] gsl::span<const uint_fast8_t, DATA_SIZE> GetRawData() const;
private:
std::array<uint_fast8_t, 256> mValues;
static inline void Index(uint8_t x, uint8_t z, uint_fast8_t &offset);
};
#endif // EXT_VANILLAGENERATOR_LIB_OBJECTS_BIOMEARRAY_H_
| {
"alphanum_fraction": 0.7763347763,
"avg_line_length": 27.72,
"ext": "h",
"hexsha": "559f76b61131e2a867e3397f7774545979f25781",
"lang": "C",
"max_forks_count": 3,
"max_forks_repo_forks_event_max_datetime": "2021-08-04T01:36:08.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-06-21T02:10:39.000Z",
"max_forks_repo_head_hexsha": "56fc48ea1367e1d08b228dfa580b513fbec8ca31",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "NetherGamesMC/ext-vanillagenerator",
"max_forks_repo_path": "lib/biomes/BiomeArray.h",
"max_issues_count": 2,
"max_issues_repo_head_hexsha": "56fc48ea1367e1d08b228dfa580b513fbec8ca31",
"max_issues_repo_issues_event_max_datetime": "2021-07-19T01:48:00.000Z",
"max_issues_repo_issues_event_min_datetime": "2021-06-21T15:10:01.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "NetherGamesMC/ext-vanillagenerator",
"max_issues_repo_path": "lib/biomes/BiomeArray.h",
"max_line_length": 90,
"max_stars_count": 14,
"max_stars_repo_head_hexsha": "56fc48ea1367e1d08b228dfa580b513fbec8ca31",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "NetherGamesMC/noiselib",
"max_stars_repo_path": "lib/biomes/BiomeArray.h",
"max_stars_repo_stars_event_max_datetime": "2022-02-13T01:12:31.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-08-16T18:58:30.000Z",
"num_tokens": 210,
"size": 693
} |
/**
*
* @file qwrapper_dlag2s.c
*
* PLASMA core_blas quark wrapper
* PLASMA is a software package provided by Univ. of Tennessee,
* Univ. of California Berkeley and Univ. of Colorado Denver
*
* @version 2.6.0
* @author Mathieu Faverge
* @date 2010-11-15
* @generated ds Tue Jan 7 11:44:57 2014
*
**/
#include <lapacke.h>
#include "common.h"
/***************************************************************************//**
*
**/
void QUARK_CORE_dlag2s(Quark *quark, Quark_Task_Flags *task_flags,
int m, int n, int nb,
const double *A, int lda,
float *B, int ldb,
PLASMA_sequence *sequence, PLASMA_request *request)
{
DAG_CORE_LAG2C;
QUARK_Insert_Task(quark, CORE_dlag2s_quark, task_flags,
sizeof(int), &m, VALUE,
sizeof(int), &n, VALUE,
sizeof(double)*nb*nb, A, INPUT,
sizeof(int), &lda, VALUE,
sizeof(float)*nb*nb, B, OUTPUT,
sizeof(int), &ldb, VALUE,
sizeof(PLASMA_sequence*), &sequence, VALUE,
sizeof(PLASMA_request*), &request, VALUE,
0);
}
/***************************************************************************//**
*
**/
#if defined(PLASMA_HAVE_WEAK)
#pragma weak CORE_dlag2s_quark = PCORE_dlag2s_quark
#define CORE_dlag2s_quark PCORE_dlag2s_quark
#endif
void CORE_dlag2s_quark(Quark *quark)
{
int m;
int n;
double *A;
int lda;
float *B;
int ldb;
PLASMA_sequence *sequence;
PLASMA_request *request;
int info;
quark_unpack_args_8(quark, m, n, A, lda, B, ldb, sequence, request);
info = LAPACKE_dlag2s_work(LAPACK_COL_MAJOR, m, n, A, lda, B, ldb);
if (sequence->status == PLASMA_SUCCESS && info != 0)
plasma_sequence_flush(quark, sequence, request, info);
}
/***************************************************************************//**
*
**/
void QUARK_CORE_slag2d(Quark *quark, Quark_Task_Flags *task_flags,
int m, int n, int nb,
const float *A, int lda,
double *B, int ldb)
{
QUARK_Insert_Task(quark, CORE_slag2d_quark, task_flags,
sizeof(int), &m, VALUE,
sizeof(int), &n, VALUE,
sizeof(float)*nb*nb, A, INPUT,
sizeof(int), &lda, VALUE,
sizeof(double)*nb*nb, B, INOUT,
sizeof(int), &ldb, VALUE,
0);
}
/***************************************************************************//**
*
**/
#if defined(PLASMA_HAVE_WEAK)
#pragma weak CORE_slag2d_quark = PCORE_slag2d_quark
#define CORE_slag2d_quark PCORE_slag2d_quark
#endif
void CORE_slag2d_quark(Quark *quark)
{
int m;
int n;
float *A;
int lda;
double *B;
int ldb;
quark_unpack_args_6(quark, m, n, A, lda, B, ldb);
LAPACKE_slag2d_work(LAPACK_COL_MAJOR, m, n, A, lda, B, ldb);
}
| {
"alphanum_fraction": 0.4874134676,
"avg_line_length": 30.5576923077,
"ext": "c",
"hexsha": "0f0b5b08247a14346c0901faf1fcc043ba883254",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "zhuangsc/Plasma-ompss1",
"max_forks_repo_path": "core_blas-qwrapper/qwrapper_dlag2s.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "zhuangsc/Plasma-ompss1",
"max_issues_repo_path": "core_blas-qwrapper/qwrapper_dlag2s.c",
"max_line_length": 80,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "zhuangsc/Plasma-ompss1",
"max_stars_repo_path": "core_blas-qwrapper/qwrapper_dlag2s.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 828,
"size": 3178
} |
//
// CI Hello World
//
// Copyright (C) 2017 Assured Information Security, Inc.
// Author: Rian Quinn <quinnr@ainfosec.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#ifndef CONSUMER_H
#define CONSUMER_H
#include <gsl/gsl>
#include <producer.h>
/// Consumer
///
/// A simple example of a consumer that is capable of accepting the real
/// producer, or a mocked version for unit testing.
///
class consumer
{
public:
/// Default Constructor
///
/// @param p the producer that this consumer will use.
///
explicit consumer(gsl::not_null<producer *> p)
{ p->print_msg(); }
/// Default Destructor
///
~consumer() = default;
public:
// We define the copy and move constructors / operators because Clang Tidy
// (legitimately) complains about the definition of a destructor without
// defining the copy and move semantics for this class. In general a class
// should always be marked non-copyable unless such functionality is
// specifically desired.
consumer(consumer &&) noexcept = default; ///< Default move construction
consumer &operator=(consumer &&) noexcept = default; ///< Default move operator
consumer(const consumer &) = delete; ///< Deleted copy construction
consumer &operator=(const consumer &) = delete; ///< Deleted copy operator
};
#endif | {
"alphanum_fraction": 0.7070748862,
"avg_line_length": 36.6212121212,
"ext": "h",
"hexsha": "a120441f65363c4dfb1258e11bb04fc3a77664a2",
"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": "88291129c30fff188d6fa8137dec8900ac3dd5ae",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "lopezfjose/GPP",
"max_forks_repo_path": "include/consumer.h",
"max_issues_count": 2,
"max_issues_repo_head_hexsha": "88291129c30fff188d6fa8137dec8900ac3dd5ae",
"max_issues_repo_issues_event_max_datetime": "2018-01-31T04:34:58.000Z",
"max_issues_repo_issues_event_min_datetime": "2018-01-31T04:26:44.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "lopezfjose/GPP",
"max_issues_repo_path": "include/consumer.h",
"max_line_length": 90,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "88291129c30fff188d6fa8137dec8900ac3dd5ae",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "lopezfjose/GPP",
"max_stars_repo_path": "include/consumer.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 513,
"size": 2417
} |
/**
*
* @file qwrapper_dgemv.c
*
* PLASMA core_blas quark wrapper
* PLASMA is a software package provided by Univ. of Tennessee,
* Univ. of California Berkeley and Univ. of Colorado Denver
*
* @version 2.6.0
* @author Mark Gates
* @author Mathieu Faverge
* @date 2010-11-15
* @generated d Tue Jan 7 11:44:59 2014
*
**/
#include <cblas.h>
#include "common.h"
/***************************************************************************//**
*
**/
void QUARK_CORE_dgemv(Quark *quark, Quark_Task_Flags *task_flags,
PLASMA_enum trans, int m, int n,
double alpha, const double *A, int lda,
const double *x, int incx,
double beta, double *y, int incy)
{
DAG_CORE_GEMV;
QUARK_Insert_Task(quark, CORE_dgemv_quark, task_flags,
sizeof(PLASMA_enum), &trans, VALUE,
sizeof(int), &m, VALUE,
sizeof(int), &n, VALUE,
sizeof(double), &alpha, VALUE,
sizeof(double)*m*n, A, INPUT,
sizeof(int), &lda, VALUE,
sizeof(double)*n, x, INPUT,
sizeof(int), &incx, VALUE,
sizeof(double), &beta, VALUE,
sizeof(double)*m, y, INOUT,
sizeof(int), &incy, VALUE,
0);
}
/***************************************************************************//**
*
**/
#if defined(PLASMA_HAVE_WEAK)
#pragma weak CORE_dgemv_quark = PCORE_dgemv_quark
#define CORE_dgemv_quark PCORE_dgemv_quark
#endif
void CORE_dgemv_quark(Quark *quark)
{
PLASMA_enum trans;
int m, n, lda, incx, incy;
double alpha, beta;
const double *A, *x;
double *y;
quark_unpack_args_11( quark, trans, m, n, alpha, A, lda, x, incx, beta, y, incy );
cblas_dgemv(
CblasColMajor,
(CBLAS_TRANSPOSE)trans,
m, n,
(alpha), A, lda,
x, incx,
(beta), y, incy);
}
| {
"alphanum_fraction": 0.4784666351,
"avg_line_length": 31.0735294118,
"ext": "c",
"hexsha": "044faf9b49b6f19dcac2b09824aace4e63df7743",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "zhuangsc/Plasma-ompss1",
"max_forks_repo_path": "core_blas-qwrapper/qwrapper_dgemv.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "zhuangsc/Plasma-ompss1",
"max_issues_repo_path": "core_blas-qwrapper/qwrapper_dgemv.c",
"max_line_length": 86,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "zhuangsc/Plasma-ompss1",
"max_stars_repo_path": "core_blas-qwrapper/qwrapper_dgemv.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 555,
"size": 2113
} |
#include "ccv.h"
#ifdef HAVE_CBLAS
#include <cblas.h>
#endif
double ccv_trace(ccv_matrix_t* mat)
{
return 0;
}
double ccv_norm(ccv_matrix_t* mat, int type)
{
return 0;
}
double ccv_normalize(ccv_matrix_t* a, ccv_matrix_t** b, int btype, int l_type)
{
ccv_dense_matrix_t* da = ccv_get_dense_matrix(a);
assert(CCV_GET_CHANNEL(da->type) == CCV_C1);
char identifier[20];
memset(identifier, 0, 20);
snprintf(identifier, 20, "ccv_normalize(%d)", l_type);
uint64_t sig = (da->sig == 0) ? 0 : ccv_matrix_generate_signature(identifier, 20, da->sig, 0);
btype = (btype == 0) ? CCV_GET_DATA_TYPE(da->type) | CCV_C1 : CCV_GET_DATA_TYPE(btype) | CCV_C1;
ccv_dense_matrix_t* db = *b = ccv_dense_matrix_renew(*b, da->rows, da->cols, CCV_ALL_DATA_TYPE | CCV_C1, btype, sig);
ccv_cache_return(db, 0);
double sum = 0;
int i, j;
unsigned char* a_ptr = da->data.ptr;
unsigned char* b_ptr = db->data.ptr;
switch (l_type)
{
case CCV_L2_NORM:
#define for_block(__for_set, __for_get) \
for (i = 0; i < da->rows; i++) \
{ \
for (j = 0; j < da->cols; j++) \
sum += __for_get(a_ptr, j, 0) * __for_get(a_ptr, j, 0); \
a_ptr += da->step; \
} \
sum = sqrt(sum); \
double inv = 1.0 / sqrt(sum); \
a_ptr = da->data.ptr; \
for (i = 0; i < da->rows; i++) \
{ \
for (j = 0; j < da->cols; j++) \
__for_set(b_ptr, j, __for_get(a_ptr, j, 0) * inv, 0); \
a_ptr += da->step; \
b_ptr += db->step; \
}
ccv_matrix_setter(db->type, ccv_matrix_getter, da->type, for_block);
#undef for_block
break;
}
return sum;
}
double ccv_sum(ccv_matrix_t* mat)
{
ccv_dense_matrix_t* dmt = ccv_get_dense_matrix(mat);
double sum = 0;
unsigned char* m_ptr = dmt->data.ptr;
int i, j;
#define for_block(dummy, __for_get) \
for (i = 0; i < dmt->rows; i++) \
{ \
for (j = 0; j < dmt->cols; j++) \
sum += __for_get(m_ptr, j, 0); \
m_ptr += dmt->step; \
}
ccv_matrix_getter(dmt->type, for_block);
#undef for_block
return sum;
}
void ccv_zero(ccv_matrix_t* mat)
{
ccv_dense_matrix_t* dmt = ccv_get_dense_matrix(mat);
memset(dmt->data.ptr, 0, dmt->step * dmt->rows);
}
void ccv_substract(ccv_matrix_t* a, ccv_matrix_t* b, ccv_matrix_t** c, int type)
{
ccv_dense_matrix_t* da = ccv_get_dense_matrix(a);
ccv_dense_matrix_t* db = ccv_get_dense_matrix(b);
assert(da->rows == db->rows && da->cols == db->cols && CCV_GET_DATA_TYPE(da->type) == CCV_GET_DATA_TYPE(db->type) && CCV_GET_CHANNEL(da->type) == CCV_GET_CHANNEL(db->type));
uint64_t sig = ccv_matrix_generate_signature("ccv_substract", 13, da->sig, db->sig, 0);
int no_8u_type = (da->type & CCV_8U) ? CCV_32S : da->type;
type = (type == 0) ? CCV_GET_DATA_TYPE(no_8u_type) | CCV_GET_CHANNEL(da->type) : CCV_GET_DATA_TYPE(type) | CCV_GET_CHANNEL(da->type);
ccv_dense_matrix_t* dc = *c = ccv_dense_matrix_renew(*c, da->rows, da->cols, CCV_ALL_DATA_TYPE | CCV_GET_CHANNEL(da->type), type, sig);
ccv_cache_return(dc, );
int i, j;
unsigned char* aptr = da->data.ptr;
unsigned char* bptr = db->data.ptr;
unsigned char* cptr = dc->data.ptr;
#define for_block(__for_get, __for_set) \
for (i = 0; i < da->rows; i++) \
{ \
for (j = 0; j < da->cols; j++) \
{ \
__for_set(cptr, j, __for_get(aptr, j, 0) - __for_get(bptr, j, 0), 0); \
} \
aptr += da->step; \
bptr += db->step; \
cptr += dc->step; \
}
ccv_matrix_getter(da->type, ccv_matrix_setter, dc->type, for_block);
#undef for_block
}
void ccv_gemm(ccv_matrix_t* a, ccv_matrix_t* b, double alpha, ccv_matrix_t* c, double beta, int transpose, ccv_matrix_t** d, int type)
{
ccv_dense_matrix_t* da = ccv_get_dense_matrix(a);
ccv_dense_matrix_t* db = ccv_get_dense_matrix(b);
ccv_dense_matrix_t* dc = (c == 0) ? 0 : ccv_get_dense_matrix(c);
assert(CCV_GET_DATA_TYPE(da->type) == CCV_GET_DATA_TYPE(db->type) && CCV_GET_CHANNEL_NUM(da->type) == 1 && CCV_GET_CHANNEL_NUM(db->type) == 1 && ((transpose & CCV_A_TRANSPOSE) ? da->rows : da->cols) == ((transpose & CCV_B_TRANSPOSE) ? db->cols : db->rows));
if (dc != 0)
assert(CCV_GET_DATA_TYPE(dc->type) == CCV_GET_DATA_TYPE(da->type) && CCV_GET_CHANNEL_NUM(dc->type) == 1 && ((transpose & CCV_A_TRANSPOSE) ? da->cols : da->rows) == dc->rows && ((transpose & CCV_B_TRANSPOSE) ? db->rows : db->cols) == dc->cols);
char identifier[20];
memset(identifier, 0, 20);
snprintf(identifier, 20, "ccv_gemm(%d)", transpose);
uint64_t sig = (dc == 0) ? ((da->sig == 0 || db->sig == 0) ? 0 : ccv_matrix_generate_signature(identifier, 20, da->sig, db->sig, 0)) : ((da->sig == 0 || db->sig == 0 || dc->sig == 0) ? 0 : ccv_matrix_generate_signature(identifier, 20, da->sig, db->sig, dc->sig, 0));
type = CCV_GET_DATA_TYPE(da->type) | CCV_GET_CHANNEL(da->type);
ccv_dense_matrix_t* dd = *d = ccv_dense_matrix_renew(*d, (transpose & CCV_A_TRANSPOSE) ? da->cols : da->rows, (transpose & CCV_B_TRANSPOSE) ? db->rows : db->cols, type, type, sig);
ccv_cache_return(dd, );
if (dd != dc && dc != 0)
memcpy(dd->data.ptr, dc->data.ptr, dc->step * dc->rows);
#ifdef HAVE_CBLAS
switch (CCV_GET_DATA_TYPE(dd->type))
{
case CCV_32F:
cblas_sgemm(CblasRowMajor, (transpose & CCV_A_TRANSPOSE) ? CblasTrans : CblasNoTrans, (transpose & CCV_B_TRANSPOSE) ? CblasTrans : CblasNoTrans, dd->rows, dd->cols, da->cols, alpha, da->data.fl, da->cols, db->data.fl, db->cols, beta, dd->data.fl, dd->cols);
break;
case CCV_64F:
cblas_dgemm(CblasRowMajor, (transpose & CCV_A_TRANSPOSE) ? CblasTrans : CblasNoTrans, (transpose & CCV_B_TRANSPOSE) ? CblasTrans : CblasNoTrans, dd->rows, dd->cols, (transpose & CCV_A_TRANSPOSE) ? da->rows : da->cols, alpha, da->data.db, da->cols, db->data.db, db->cols, beta, dd->data.db, dd->cols);
break;
}
#endif
}
| {
"alphanum_fraction": 0.66070163,
"avg_line_length": 38.924137931,
"ext": "c",
"hexsha": "89f5e87045ee8d9c72403f331bab28e3e468cdd4",
"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": "a79535b92a7dd55dd338fcb4b3f9b8a63387a5ef",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "deminew/ccv",
"max_forks_repo_path": "lib/ccv_algebra.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "a79535b92a7dd55dd338fcb4b3f9b8a63387a5ef",
"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": "deminew/ccv",
"max_issues_repo_path": "lib/ccv_algebra.c",
"max_line_length": 303,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "a79535b92a7dd55dd338fcb4b3f9b8a63387a5ef",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "deminew/ccv",
"max_stars_repo_path": "lib/ccv_algebra.c",
"max_stars_repo_stars_event_max_datetime": "2015-11-05T05:46:45.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-11-05T05:46:45.000Z",
"num_tokens": 1989,
"size": 5644
} |
/*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*
** **
** This file forms part of the Underworld geophysics modelling application. **
** **
** For full license and copyright information, please refer to the LICENSE.md file **
** located at the project root, or contact the authors. **
** **
**~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*/
#include <petsc.h>
#include <petscvec.h>
#include <petscmat.h>
#include <StGermain/libStGermain/src/StGermain.h>
#include <StgDomain/libStgDomain/src/StgDomain.h>
#include "common-driver-utils.h"
/*
name[] is operator name
*/
PetscErrorCode BSSCR_MatInfoLog(PetscViewer v,Mat A,const char name[])
{
MatInfo i;
PetscReal nrm_1,nrm_f,nrm_inf;
MatType mtype;
PetscInt M,N;
PetscViewerType vtype;
PetscTruth isascii;
PetscViewerGetType( v, &vtype );
Stg_PetscObjectTypeCompare( (PetscObject)v,PETSC_VIEWER_ASCII,&isascii );
if (!isascii) { PetscFunctionReturn(0); }
MatGetSize( A, &M,&N );
MatGetInfo(A,MAT_GLOBAL_SUM,&i);
MatGetType( A, &mtype );
MatNorm( A, NORM_1, &nrm_1 );
MatNorm( A, NORM_FROBENIUS, &nrm_f );
MatNorm( A, NORM_INFINITY, &nrm_inf );
PetscViewerASCIIPrintf( v, "MatInfo: %s \n", name );
PetscViewerASCIIPushTab(v);
PetscViewerASCIIPrintf( v, "type=%s \n", mtype );
PetscViewerASCIIPrintf( v, "dimension=%Dx%D \n", M,N );
PetscViewerASCIIPrintf( v, "nnz=%D (total)\n", (PetscInt)i.nz_used );
PetscViewerASCIIPrintf( v, "nnz=%D (allocated)\n", (PetscInt)i.nz_allocated );
PetscViewerASCIIPrintf( v, "|A|_1 = %1.12e\n", nrm_1 );
PetscViewerASCIIPrintf( v, "|A|_frobenius = %1.12e\n", nrm_f );
PetscViewerASCIIPrintf( v, "|A|_inf = %1.12e\n", nrm_inf );
PetscViewerASCIIPopTab(v);
PetscFunctionReturn(0);
}
/*
name[] is operator name
*/
PetscErrorCode BSSCR_VecInfoLog(PetscViewer v,Vec x,const char name[])
{
PetscReal nrm_1,nrm_f,nrm_inf;
VecType vectype;
PetscInt M;
PetscViewerType vtype;
PetscTruth isascii;
PetscViewerGetType( v, &vtype );
Stg_PetscObjectTypeCompare( (PetscObject)v,PETSC_VIEWER_ASCII,&isascii );
if (!isascii) { PetscFunctionReturn(0); }
VecGetSize( x, &M);
VecGetType( x, &vectype );
VecNorm( x, NORM_1, &nrm_1 );
VecNorm( x, NORM_2, &nrm_f );
VecNorm( x, NORM_INFINITY, &nrm_inf );
PetscViewerASCIIPrintf( v, "VecInfo: %s \n", name );
PetscViewerASCIIPushTab(v);
PetscViewerASCIIPrintf( v, "type=%s \n", vectype );
PetscViewerASCIIPrintf( v, "dimension=%Dx1 \n", M);
PetscViewerASCIIPrintf( v, "|x|_1 = %1.12e\n", nrm_1 );
PetscViewerASCIIPrintf( v, "|x|_2 = %1.12e\n", nrm_f );
PetscViewerASCIIPrintf( v, "|x|_inf = %1.12e\n", nrm_inf );
PetscViewerASCIIPopTab(v);
PetscFunctionReturn(0);
}
PetscErrorCode BSSCR_StokesCreateOperatorSummary( Mat K, Mat G, Mat C, Vec f, Vec h, const char filename[] )
{
MPI_Comm comm;
PetscViewer v;
char op_name[PETSC_MAX_PATH_LEN];
PetscTruth flg;
PetscObjectGetComm( (PetscObject)K, &comm );
PetscViewerASCIIOpen( comm, filename, &v );
BSSCR_GeneratePetscHeader_for_viewer( v );
PetscViewerASCIIPrintf( v, "\nInput matrices:\n");
PetscViewerASCIIPushTab(v);
PetscOptionsGetString( PETSC_NULL,"-stokes_A11",op_name,PETSC_MAX_PATH_LEN-1,&flg );
if (flg) { PetscViewerASCIIPrintf( v, "A11: %s\n", op_name ); }
PetscOptionsGetString( PETSC_NULL,"-stokes_A12",op_name,PETSC_MAX_PATH_LEN-1,&flg );
if (flg) { PetscViewerASCIIPrintf( v, "A12: %s\n", op_name ); }
PetscOptionsGetString( PETSC_NULL,"-stokes_A22",op_name,PETSC_MAX_PATH_LEN-1,&flg );
if (flg) { PetscViewerASCIIPrintf( v, "A22: %s\n", op_name ); }
PetscOptionsGetString( PETSC_NULL,"-stokes_Smat",op_name,PETSC_MAX_PATH_LEN-1,&flg );
if (flg) { PetscViewerASCIIPrintf( v, "Smat: %s\n", op_name ); }
PetscOptionsGetString( PETSC_NULL,"-stokes_b1",op_name,PETSC_MAX_PATH_LEN-1,&flg );
if (flg) { PetscViewerASCIIPrintf( v, "b1: %s\n", op_name ); }
PetscOptionsGetString( PETSC_NULL,"-stokes_b2",op_name,PETSC_MAX_PATH_LEN-1,&flg );
if (flg) { PetscViewerASCIIPrintf( v, "b2: %s\n", op_name ); }
PetscViewerASCIIPopTab(v);
PetscViewerASCIIPrintf( v, "\n");
BSSCR_MatInfoLog(v,K,"stokes_A11"); PetscViewerASCIIPrintf( v, "\n");
BSSCR_MatInfoLog(v,G,"stokes_A12"); PetscViewerASCIIPrintf( v, "\n");
if (C) { BSSCR_MatInfoLog(v,C,"stokes_A22"); PetscViewerASCIIPrintf( v, "\n"); }
BSSCR_VecInfoLog(v,f,"stokes_b1"); PetscViewerASCIIPrintf( v, "\n");
BSSCR_VecInfoLog(v,h,"stokes_b2"); PetscViewerASCIIPrintf( v, "\n");
Stg_PetscViewerDestroy(&v );
PetscFunctionReturn(0);
}
| {
"alphanum_fraction": 0.642358258,
"avg_line_length": 34.041958042,
"ext": "c",
"hexsha": "a6193dc64ebd38cc60b64bf41d4917c2ab45688e",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "76991c475ac565e092e99a364370fbae15bb40ac",
"max_forks_repo_licenses": [
"CC-BY-4.0"
],
"max_forks_repo_name": "rbeucher/underworld2",
"max_forks_repo_path": "underworld/libUnderworld/Solvers/KSPSolvers/src/BSSCR/operator_summary.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "76991c475ac565e092e99a364370fbae15bb40ac",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"CC-BY-4.0"
],
"max_issues_repo_name": "rbeucher/underworld2",
"max_issues_repo_path": "underworld/libUnderworld/Solvers/KSPSolvers/src/BSSCR/operator_summary.c",
"max_line_length": 108,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "76991c475ac565e092e99a364370fbae15bb40ac",
"max_stars_repo_licenses": [
"CC-BY-4.0"
],
"max_stars_repo_name": "rbeucher/underworld2",
"max_stars_repo_path": "underworld/libUnderworld/Solvers/KSPSolvers/src/BSSCR/operator_summary.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1853,
"size": 4868
} |
#pragma once
#include "BufferView.h"
#include "Enum.h"
#include "Error.h"
#include "parsers/Parsing.h"
#include <boost/hana/define_struct.hpp>
#include <gsl/span>
namespace gltfpp {
inline namespace v1 {
BETTER_ENUM(AccessorComponentType,
int,
BYTE = 5120,
UNSIGNED_BYTE = 5121,
SHORT = 5122,
UNSIGNED_SHORT = 5123,
UNSIGNED_INT = 5125,
FLOAT = 5126)
BETTER_ENUM(AccessorType, int, SCALAR, VEC2, VEC3, VEC4, MAT2, MAT3, MAT4)
constexpr auto AccessorTypeComponentCount =
boost::hana::make_map(boost::hana::make_pair(boost::hana::int_c<(int)AccessorType::SCALAR>, 1),
boost::hana::make_pair(boost::hana::int_c<(int)AccessorType::VEC2>, 2),
boost::hana::make_pair(boost::hana::int_c<(int)AccessorType::VEC3>, 3),
boost::hana::make_pair(boost::hana::int_c<(int)AccessorType::VEC4>, 4),
boost::hana::make_pair(boost::hana::int_c<(int)AccessorType::MAT2>, 4),
boost::hana::make_pair(boost::hana::int_c<(int)AccessorType::MAT3>, 9),
boost::hana::make_pair(boost::hana::int_c<(int)AccessorType::MAT4>, 16));
struct Accessor {
BOOST_HANA_DEFINE_STRUCT(Accessor,
(bool, normalized),
(std::vector<double>, min),
(std::vector<double>, max),
(option<std::string>, name),
(option<nlohmann::json>, sparse),
(option<nlohmann::json>, extensions),
(option<nlohmann::json>, extras),
(ptrdiff_t, byteOffset),
(size_t, count),
(AccessorComponentType, componentType));
BufferView const *bufferView;
};
auto parse(Accessor &) noexcept;
} // namespace v1
} // namespace gltfpp
| {
"alphanum_fraction": 0.5279960707,
"avg_line_length": 41.5510204082,
"ext": "h",
"hexsha": "1b2166ea0bf1f460d6a157619d393fbc4b0a11f6",
"lang": "C",
"max_forks_count": 5,
"max_forks_repo_forks_event_max_datetime": "2019-09-18T07:04:15.000Z",
"max_forks_repo_forks_event_min_datetime": "2017-06-01T14:38:11.000Z",
"max_forks_repo_head_hexsha": "9e9e2fe5f8da374838a5b6b03d97963bed87956d",
"max_forks_repo_licenses": [
"BSL-1.0"
],
"max_forks_repo_name": "mmha/gltfpp",
"max_forks_repo_path": "gltfpp/include/Accessor.h",
"max_issues_count": 9,
"max_issues_repo_head_hexsha": "9e9e2fe5f8da374838a5b6b03d97963bed87956d",
"max_issues_repo_issues_event_max_datetime": "2017-06-02T18:05:45.000Z",
"max_issues_repo_issues_event_min_datetime": "2017-06-02T16:53:11.000Z",
"max_issues_repo_licenses": [
"BSL-1.0"
],
"max_issues_repo_name": "mmha/gltfpp",
"max_issues_repo_path": "gltfpp/include/Accessor.h",
"max_line_length": 101,
"max_stars_count": 25,
"max_stars_repo_head_hexsha": "9e9e2fe5f8da374838a5b6b03d97963bed87956d",
"max_stars_repo_licenses": [
"BSL-1.0"
],
"max_stars_repo_name": "mmha/gltfpp",
"max_stars_repo_path": "gltfpp/include/Accessor.h",
"max_stars_repo_stars_event_max_datetime": "2021-06-06T04:23:54.000Z",
"max_stars_repo_stars_event_min_datetime": "2017-05-03T04:09:50.000Z",
"num_tokens": 487,
"size": 2036
} |
/* Copyright 2019-2021 Canaan Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <gsl/gsl-lite.hpp>
#include <type_traits>
#if defined(_MSC_VER)
#ifdef NNCASE_DLL
#define NNCASE_API __declspec(dllexport)
#elif defined(NNCASE_SHARED_LIBS)
#define NNCASE_API __declspec(dllimport)
#else
#define NNCASE_API
#endif
#else
#define NNCASE_API
#endif
#if defined(_MSC_VER)
#define NNCASE_UNREACHABLE() __assume(0)
#else
#define NNCASE_UNREACHABLE() __builtin_unreachable()
#endif
#if gsl_CPP17_OR_GREATER
#define NNCASE_INLINE_VAR inline
#define NNCASE_UNUSED [[maybe_unused]]
namespace nncase
{
template <class Callable, class... Args>
using invoke_result_t = std::invoke_result_t<Callable, Args...>;
}
#else
#define NNCASE_INLINE_VAR
#if defined(_MSC_VER)
#define NNCASE_UNUSED
#else
#define NNCASE_UNUSED __attribute__((unused))
#endif
namespace nncase
{
template <class Callable, class... Args>
using invoke_result_t = std::result_of_t<Callable(Args...)>;
}
#endif
#define NNCASE_LITTLE_ENDIAN 1
#define NNCASE_HAVE_STD_BYTE gsl_CPP17_OR_GREATER
#define NNCASE_NODISCARD gsl_NODISCARD
#define NNCASE_NORETURN gsl_NORETURN
#define BEGIN_NS_NNCASE_RUNTIME \
namespace nncase \
{ \
namespace runtime \
{
#define END_NS_NNCASE_RUNTIME \
} \
}
#define BEGIN_NS_NNCASE_RT_MODULE(MODULE) \
namespace nncase \
{ \
namespace runtime \
{ \
namespace MODULE \
{
#define END_NS_NNCASE_RT_MODULE \
} \
} \
}
#define BEGIN_NS_NNCASE_KERNELS \
namespace nncase \
{ \
namespace kernels \
{
#define END_NS_NNCASE_KERNELS \
} \
}
#ifndef DEFINE_ENUM_BITMASK_OPERATORS
#define DEFINE_ENUM_BITMASK_OPERATORS(ENUMTYPE) gsl_DEFINE_ENUM_BITMASK_OPERATORS(ENUMTYPE)
#endif
namespace nncase
{
struct default_init_t
{
};
NNCASE_INLINE_VAR constexpr default_init_t default_init {};
}
| {
"alphanum_fraction": 0.6573938507,
"avg_line_length": 25.0642201835,
"ext": "h",
"hexsha": "ca9339c54871e17a54cf3c9489ce6850b84512bd",
"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": "898bd4075a0f246bca7b62a912051af3d890aff4",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "annosoo/nncase",
"max_forks_repo_path": "include/nncase/runtime/compiler_defs.h",
"max_issues_count": 3,
"max_issues_repo_head_hexsha": "898bd4075a0f246bca7b62a912051af3d890aff4",
"max_issues_repo_issues_event_max_datetime": "2021-06-02T10:39:35.000Z",
"max_issues_repo_issues_event_min_datetime": "2021-05-27T06:08:30.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "annosoo/nncase",
"max_issues_repo_path": "include/nncase/runtime/compiler_defs.h",
"max_line_length": 91,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "898bd4075a0f246bca7b62a912051af3d890aff4",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "annosoo/nncase",
"max_stars_repo_path": "include/nncase/runtime/compiler_defs.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 622,
"size": 2732
} |
/*
** read nifti-1 or nifti-2 to vista format
**
** G.Lohmann, MPI-KYB, 2016
*/
#include <viaio/Vlib.h>
#include <viaio/VImage.h>
#include <viaio/mu.h>
#include <viaio/option.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <math.h>
#include <ctype.h>
#include <gsl/gsl_math.h>
#include <nifti/nifti2.h>
#include <nifti/nifti1_io.h>
#define MIN_HEADER_SIZE 348
#define NII_HEADER_SIZE 352
#define ABS(x) ((x) > 0 ? (x) : -(x))
/*extern int isinff(float x);
extern int isnanf(float x);
*/
extern char *VReadGzippedData(char *filename,size_t *len);
extern char *VReadUnzippedData(char *filename,VBoolean nofail,size_t *size);
extern char *VReadDataContainer(char *filename,VBoolean nofail,size_t *size);
extern FILE *VReadInputFile (char *filename,VBoolean nofail);
extern int CheckGzip(char *filename);
extern void VByteSwapNiftiHeader(nifti_1_header *hdr);
extern void VByteSwapNifti2Header(nifti_2_header *hdr);
extern void VByteSwapData(char *data,size_t ndata,size_t nsize);
extern float strtof(const char *str, char **endptr);
int NiftiVersion(char *databuffer,int *swap)
{
int *k = (int *)(&databuffer[0]);
int type = *k;
*swap = 0;
if (type == 348) return 1;
else if (type == 540) return 2;
else {
nifti_swap_4bytes(1,k);
type = *k;
*swap = 1;
if (type == 348) return 1;
else if (type == 540) return 2;
else return 0;
}
return 0;
}
/* read repetition time from description field instead of pixdim */
float TRfromString(const char *str)
{
float f_tr = -1; /* return value on failure */
float factor = 1000; /* expect seconds as default */
char* c_tr;
if( ( c_tr = strstr( str, "TR=" ) ) || ( c_tr = strstr( str, "TR =" ) ) ) {
while( *c_tr++ != '=' )
;
while( *c_tr && isspace( *c_tr ) )
c_tr++;
f_tr = strtof( c_tr, &c_tr );
if( f_tr > 0.0 ) {
while( *c_tr && isspace( *c_tr ) )
c_tr++;
if( strncasecmp( c_tr, "ms", 2 ) == 0 )
factor = 1;
}
}
return f_tr * factor;
}
/* set dimension in geo info */
void VUpdateGeoinfo(VAttrList geolist,int dimtype,VLong tr)
{
double *D = VGetGeoDim(geolist,NULL);
D[0] = (double)dimtype;
VSetGeoDim(geolist,D);
double *E = VGetGeoPixdim(geolist,NULL);
if (tr > 0) {
E[4] = (double)tr;
VSetGeoPixdim(geolist,E);
}
}
/*
* VIniImage
*
* Allocate Image structure and fill voxel values with databuffer.
* Returns a pointer to the image if successful, zero otherwise.
* Useful for converting from 4D nifti to list of 3D vista images
*/
VImage VIniImage (int nbands, int nrows, int ncolumns, VRepnKind pixel_repn, char *databuffer)
{
size_t row_size = ncolumns * VRepnSize (pixel_repn);
size_t row_index_size = nbands * nrows * sizeof (char *);
size_t band_index_size = nbands * sizeof (char **);
size_t pixel_size=0;
VImage image;
int band=0, row=0;
char *p = NULL;
/* Check parameters: */
if (nbands < 1) VError("VIniImage: Invalid number of bands: %d", (int) nbands);
if (nrows < 1) VError ("VIniImage: Invalid number of rows: %d", (int) nrows);
if (ncolumns < 1) VError ("VIniImage: Invalid number of columns: %d",(int) ncolumns);
#define AlignUp(v, b) ((((v) + (b) - 1) / (b)) * (b))
/* Initialize VImage data struct */
pixel_size = VRepnSize (pixel_repn);
p = VMalloc(AlignUp (sizeof (VImageRec) + row_index_size + band_index_size, pixel_size));
image = (VImage) p;
image->nbands = nbands;
image->nrows = nrows;
image->ncolumns = ncolumns;
image->flags = VImageSingleAlloc;
image->pixel_repn = pixel_repn;
image->attributes = VCreateAttrList ();
image->band_index = (VPointer **) (p += sizeof (VImageRec));
image->row_index = (VPointer *) (p += band_index_size);
image->data = (VPointer) AlignUp((long) (databuffer+4), pixel_size);
image->nframes = nbands;
image->nviewpoints = image->ncolors = image->ncomponents = 1;
/* Initialize the indices: */
for (band = 0; band < nbands; band++)
image->band_index[band] = image->row_index + band * nrows;
for (row = 0, p = image->data; row < nbands * nrows; row++, p += row_size)
image->row_index[row] = p;
return image;
#undef AlignUp
}
#define xgetval(data,index,Datatype) \
{ \
Datatype *k = (Datatype *)(&data[index]); \
u = (float)(*k); \
}
float VGetValue(char *data,size_t index,int datatype)
{
float u=0;
switch(datatype) {
case DT_BINARY:
xgetval(data,index,VBit);
break;
case DT_UNSIGNED_CHAR:
xgetval(data,index,VUByte);
break;
case DT_SIGNED_SHORT:
xgetval(data,index,short);
break;
case DT_SIGNED_INT:
xgetval(data,index,int);
break;
case DT_FLOAT:
xgetval(data,index,float);
break;
case DT_DOUBLE:
xgetval(data,index,double);
break;
case DT_INT8:
xgetval(data,index,VSByte);
break;
case DT_UINT16:
xgetval(data,index,unsigned short);
break;
case DT_UINT32:
xgetval(data,index,unsigned int);
break;
case DT_INT64:
xgetval(data,index,long);
break;
case DT_UINT64:
xgetval(data,index,unsigned long);
break;
default:
VError(" unknown datatype %d",datatype);
}
if (isinf(u) || isnan(u))
u = 0;
return u;
}
void VCleanData(VImage src)
{
int b,r,c;
double u=0;
for (b=0; b<VImageNBands(src); b++) {
for (r=0; r<VImageNRows(src); r++) {
for (c=0; c<VImageNColumns(src); c++) {
u = VGetPixel(src,b,r,c);
if (isinf(u) || isnan(u)) {
u = 0;
VSetPixel(src,b,r,c,u);
}
}
}
}
}
/* get image statistics for re-scaling parameters */
void VDataStats(char *data,size_t ndata,size_t nsize,int datatype,float *xmin,float *xmax)
{
size_t i,n;
float u=0;
float zmin = VRepnMaxValue(VFloatRepn);
float zmax = VRepnMinValue(VFloatRepn);
n=0;
for (i=0; i<ndata; i+= nsize) {
u = VGetValue(data,i,datatype);
if (fabs(u) < TINY) continue;
if (u < zmin) zmin = u;
if (u > zmax) zmax = u;
n++;
}
if (n < 1) VError(" no non-zero data points found");
*xmin = (zmin+TINY);
*xmax = (zmax-TINY);
}
/* list of 3D images */
void Nii2Vista3DList(char *data,size_t nsize,size_t nslices,size_t nrows,size_t ncols,size_t nt,
VRepnKind dst_repn,int datatype,float scl_slope,float scl_inter,
VString voxelstr,VLong tr,VAttrList out_list)
{
int slice,row,col;
float u=0;
size_t i;
size_t add=0;
size_t nrnc = nrows*ncols;
size_t npix = nrnc*nslices;
size_t ndata = nt * npix * nsize;
if (nsize == 1) add=4;
if (nsize == 2) add=2;
if (nsize == 4) add=1;
VImage *dst = (VImage *) VCalloc(nt,sizeof(VImage));
if (nt > 1) VAppendAttr(out_list,"nimages",NULL,VLongRepn,(VLong) nt);
for (i=0; i<nt; i++) {
/* rescale if needed */
if (fabs(scl_slope) > 0 || fabs(scl_inter) > 0) {
VImage tmp = VCreateImage(nslices,nrows,ncols,dst_repn);
VSetAttr(VImageAttrList(tmp),"voxel",NULL,VStringRepn,voxelstr);
if (tr > 0) VSetAttr(VImageAttrList(tmp),"repetition_time",NULL,VLongRepn,(VLong)tr);
for (slice=0; slice<nslices; slice++) {
for (row=0; row<nrows; row++) {
for (col=0; col<ncols; col++) {
const size_t src_index = (col + row*ncols + slice*nrnc + i*npix)*nsize;
if (src_index >= ndata || src_index < 0) continue;
u = VGetValue(data,src_index,datatype);
u = scl_slope*u + scl_inter;
VSetPixel(tmp,slice,row,col,(double)u);
}
}
}
VAppendAttr(out_list,"image",NULL,VImageRepn,tmp);
}
/* otherwise just copy */
else {
const size_t index = (i*npix-add)*nsize;
dst[i] = VIniImage(nslices,nrows,ncols,dst_repn,&data[index]);
VSetAttr(VImageAttrList(dst[i]),"voxel",NULL,VStringRepn,voxelstr);
if (tr > 0) VSetAttr(VImageAttrList(dst[i]),"repetition_time",NULL,VLongRepn,(VLong)tr);
VAppendAttr(out_list,"image",NULL,VImageRepn,dst[i]);
VCleanData(dst[i]);
}
}
}
/* 4D time series data */
void Nii2Vista4D(char *data,size_t nsize,size_t nslices,size_t nrows,size_t ncols,size_t nt,
VRepnKind dst_repn,int datatype,VBoolean do_scaling,float scl_slope,float scl_inter,
VString voxelstr,double *slicetime,VLong tr,VAttrList out_list)
{
size_t slice,row,col,ti;
size_t nrnc = nrows*ncols;
size_t npix = nrnc*nslices;
size_t ndata = nt * npix * nsize;
size_t add=0;
float u=0;
/* rescale to 16bit integer if needed */
float xmin=0,xmax=0,umin=0,umax=0;
if (do_scaling && dst_repn != VShortRepn) {
dst_repn = VShortRepn;
VDataStats(data,ndata,nsize,datatype,&xmin,&xmax);
fprintf(stderr," data range: [%f, %f]\n",xmin,xmax);
umin = 0;
umax = VRepnMaxValue(VShortRepn);
}
VImage *dst = (VImage *) VCalloc(nslices,sizeof(VImage));
for (slice=0; slice<nslices; slice++) {
dst[slice] = VCreateImage(nt,nrows,ncols,dst_repn);
if (!dst[slice]) VError(" err allocating image");
VFillImage(dst[slice],VAllBands,0);
VSetAttr(VImageAttrList(dst[slice]),"voxel",NULL,VStringRepn,voxelstr);
if (tr > 0) VSetAttr(VImageAttrList(dst[slice]),"repetition_time",NULL,VLongRepn,(VLong)tr);
if (slicetime != NULL)
VSetAttr(VImageAttrList(dst[slice]),"slice_time",NULL,VShortRepn,(VShort)slicetime[slice]);
for (ti=0; ti<nt; ti++) {
for (row=0; row<nrows; row++) {
for (col=0; col<ncols; col++) {
const size_t src_index = (col + row*ncols + slice*nrnc + ti*npix + add)*nsize;
if (src_index >= ndata || src_index < 0) continue;
if (!do_scaling) {
u = VGetValue(data,src_index,datatype);
if (fabs(scl_slope) > 0 || fabs(scl_inter) > 0) {
u = scl_slope*u + scl_inter;
}
if (VPixelRepn(dst[slice]) == VShortRepn) {
VPixel(dst[slice],ti,row,col,VShort) = u;
}
else if (VPixelRepn(dst[slice]) == VFloatRepn) {
VPixel(dst[slice],ti,row,col,VFloat) = u;
}
else {
VSetPixel(dst[slice],ti,row,col,(double)u);
}
}
else {
u = VGetValue(data,src_index,datatype);
u = umax * (u-xmin)/(xmax-xmin);
if (u < umin) u = umin;
if (u > umax) u = umax;
VPixel(dst[slice],ti,row,col,VShort) = (VShort)u;
}
}
}
}
VCleanData(dst[slice]);
VAppendAttr(out_list,"image",NULL,VImageRepn,dst[slice]);
}
}
/* copy nifti header infos to geolist in vista header */
double *VGetNiftiHeader(VAttrList geolist,nifti_2_header hdr,VLong tr)
{
/* units in lipsia: mm and sec */
char xyzt = hdr.xyzt_units;
int spaceunits = XYZT_TO_SPACE(xyzt);
int timeunits = XYZT_TO_TIME(xyzt);
double xscale = 1.0;
double tscale = 1.0;
if (spaceunits == NIFTI_UNITS_MICRON) xscale=1000.0;
if (timeunits == NIFTI_UNITS_SEC) tscale=1000.0;
/* dim info */
VSetAttr(geolist,"dim_info",NULL,VShortRepn,(VShort)hdr.dim_info);
/* dim */
/* hdr.dim[0]==3 means dim=3, hdr.dim[0]==4 means dim=4 (timeseries) */
float *E = VCalloc(8,sizeof(float));
VAttrList elist = VCreateAttrList();
VBundle ebundle = VCreateBundle ("bundle",elist,8*sizeof(float),(VPointer)E);
VSetAttr(geolist,"dim",NULL,VBundleRepn,ebundle);
int i;
for (i=0; i<8; i++) E[i] = hdr.dim[i];
for (i=5; i<8; i++) E[i] = 0;
/* pixdim */
float *D = VCalloc(8,sizeof(float));
for (i=0; i<8; i++) D[i] = hdr.pixdim[i];
for (i=1; i<=3; i++) D[i] *= xscale;
D[4] *= tscale;
if (tr > 0) D[4] = (double)tr;
/* override if TR info is in description field */
float xtr = TRfromString(hdr.descrip);
if (xtr > 0) {
D[4] = (double)(xtr*tscale);
fprintf(stderr," reading TR from description field, TR= %.4f ms\n",D[4]);
}
if (fabs(D[0]) < 0.0001) D[0] = 1.0; /* if not specified, assume pixdim[0] = 1 */
for (i=5; i<8; i++) D[i] = 0;
VAttrList dlist = VCreateAttrList();
VBundle dbundle = VCreateBundle ("bundle",dlist,8*sizeof(float),(VPointer)D);
VSetAttr(geolist,"pixdim",NULL,VBundleRepn,dbundle);
/* sform */
VImage sform = VCreateImage(1,4,4,VFloatRepn);
VFillImage (sform,VAllBands,0);
int j;
for (j=0; j<4; j++) {
VPixel(sform,0,0,j,VFloat) = hdr.srow_x[j];
VPixel(sform,0,1,j,VFloat) = hdr.srow_y[j];
VPixel(sform,0,2,j,VFloat) = hdr.srow_z[j];
}
VSetAttr(geolist,"sform_code",NULL,VShortRepn,(VShort)hdr.sform_code);
VSetAttr(geolist,"sform",NULL,VImageRepn,sform);
/* qform */
size_t dim=6;
float *Q = VCalloc(dim,sizeof(float));
VAttrList qlist = VCreateAttrList();
VBundle qbundle = VCreateBundle ("bundle",qlist,dim*sizeof(float),(VPointer)Q);
Q[0] = hdr.quatern_b;
Q[1] = hdr.quatern_c;
Q[2] = hdr.quatern_d;
Q[3] = hdr.qoffset_x;
Q[4] = hdr.qoffset_y;
Q[5] = hdr.qoffset_z;
VShort qform_code = hdr.qform_code;
if (hdr.sform_code==0 && qform_code==0) qform_code = 1; /* if both codes are unspecified, assume scanner coord */
VSetAttr(geolist,"qform_code",NULL,VShortRepn,(VShort)qform_code);
VSetAttr(geolist,"qform",NULL,VBundleRepn,qbundle);
/* MRI encoding directions */
int freq_dim=0,phase_dim=0,slice_dim=0;
if (hdr.dim_info != 0) {
freq_dim = DIM_INFO_TO_FREQ_DIM (hdr.dim_info );
phase_dim = DIM_INFO_TO_PHASE_DIM(hdr.dim_info );
slice_dim = DIM_INFO_TO_SLICE_DIM(hdr.dim_info );
VSetAttr(geolist,"freq_dim",NULL,VShortRepn,(VShort)freq_dim);
VSetAttr(geolist,"phase_dim",NULL,VShortRepn,(VShort)phase_dim);
VSetAttr(geolist,"slice_dim",NULL,VShortRepn,(VShort)slice_dim);
}
if (slice_dim == 0) return NULL;
/* slicetiming information */
int slice_start = hdr.slice_start;
int slice_end = hdr.slice_end;
int slice_code = hdr.slice_code;
double slice_duration = hdr.slice_duration;
if (slice_code == 0 || slice_duration < 1.0e-10) return NULL;
fprintf(stderr," slice duration: %.2f ms\n", slice_duration);
VSetAttr(geolist,"slice_start",NULL,VShortRepn,(VShort)slice_start);
VSetAttr(geolist,"slice_end",NULL,VShortRepn,(VShort)slice_end);
VSetAttr(geolist,"slice_code",NULL,VShortRepn,(VShort)slice_code);
VSetAttr(geolist,"slice_duration",NULL,VFloatRepn,(VFloat)slice_duration);
int nslices = (int)E[3];
double *slicetimes = (double *) VCalloc(nslices,sizeof(double));
VGetSlicetimes(slice_start,slice_end,slice_code,slice_duration,slicetimes);
return slicetimes;
}
VAttrList Nifti1_to_Vista(char *databuffer,VLong tr,VBoolean attrtype,VBoolean do_scaling,VBoolean *ok)
{
/* read header */
nifti_1_header hdr1;
nifti_2_header hdr;
int i=0,swap=0;
size_t header_size=0;
int nifti_version = NiftiVersion(databuffer,&swap);
if (nifti_version < 1) VError(" unknown nifti version");
/* fprintf(stderr," nifti version: %d\n",nifti_version); */
if (nifti_version == 1) { /* nifti-1 */
header_size = 348;
memcpy(&hdr1,databuffer,header_size);
swap = NIFTI_NEEDS_SWAP(hdr1);
if (swap == 1) VByteSwapNiftiHeader(&hdr1);
hdr.datatype = hdr1.datatype;
for (i=0; i<8; i++) hdr.dim[i]=hdr1.dim[i];
for (i=0; i<8; i++) hdr.pixdim[i]=hdr1.pixdim[i];
hdr.bitpix=hdr1.bitpix;
hdr.vox_offset=hdr1.vox_offset;
hdr.intent_p1 = hdr1.intent_p1;
hdr.intent_p2 = hdr1.intent_p2;
hdr.intent_p3 = hdr1.intent_p3;
hdr.scl_slope = hdr1.scl_slope;
hdr.scl_inter = hdr1.scl_inter;
hdr.slice_duration = hdr1.slice_duration;
hdr.slice_start = hdr1.slice_start;
hdr.slice_end = hdr1.slice_end;
for (i=0; i<80; i++) hdr.descrip[i] = hdr1.descrip[i];
hdr.qform_code = hdr1.qform_code;
hdr.sform_code = hdr1.sform_code;
hdr.quatern_b = hdr1.quatern_b;
hdr.quatern_c = hdr1.quatern_c;
hdr.quatern_d = hdr1.quatern_d;
hdr.qoffset_x = hdr1.qoffset_x;
hdr.qoffset_y = hdr1.qoffset_y;
hdr.qoffset_z = hdr1.qoffset_z;
for (i=0; i<4; i++) hdr.srow_x[i]=hdr1.srow_x[i];
for (i=0; i<4; i++) hdr.srow_y[i]=hdr1.srow_y[i];
for (i=0; i<4; i++) hdr.srow_z[i]=hdr1.srow_z[i];
hdr.xyzt_units = hdr1.xyzt_units;
hdr.dim_info = hdr1.dim_info;
}
else if (nifti_version == 2) { /* nifti-2 */
header_size = 540;
memcpy(&hdr,databuffer,header_size);
if (swap) {
VByteSwapNifti2Header(&hdr);
}
}
else {
VError(" not a nifti file");
}
/* get data type */
VRepnKind dst_repn = DT_UNKNOWN;
int datatype = (int)hdr.datatype;
switch(datatype) {
case DT_UNKNOWN:
VError(" unknown data type");
break;
case DT_BINARY:
dst_repn = VBitRepn;
break;
case DT_UNSIGNED_CHAR:
dst_repn = VUByteRepn;
break;
case DT_SIGNED_SHORT:
dst_repn = VShortRepn;
break;
case DT_SIGNED_INT:
dst_repn = VIntegerRepn;
break;
case DT_FLOAT:
dst_repn = VFloatRepn;
break;
case DT_DOUBLE:
dst_repn = VDoubleRepn;
break;
case DT_INT8:
dst_repn = VSByteRepn;
break;
case DT_UINT16:
dst_repn = VUShortRepn;
break;
case DT_UINT32:
dst_repn = VUIntegerRepn;
break;
case DT_INT64:
dst_repn = VLongRepn;
break;
case DT_UINT64:
dst_repn = VULongRepn;
break;
default:
VError(" unknown data type %d",datatype);
}
/* get scaling parameters */
double scl_slope = (double)hdr.scl_slope;
double scl_inter = (double)hdr.scl_inter;
double tiny=1.0e-6;
if (fabs(scl_slope) < tiny && fabs(scl_inter) < tiny) {
scl_slope = 1.0;
scl_inter = 0;
}
else if (fabs(scl_slope-1.0) < tiny && fabs(scl_inter) < tiny) {
scl_slope = 1.0;
scl_inter = 0;
}
else {
dst_repn = VFloatRepn;
do_scaling = FALSE; /* no automatic scaling */
}
/* number of values stored at each time point */
if (hdr.dim[5] > 1) VError("data type not supported, dim[5]= %d\n",hdr.dim[5]);
/* image size */
/* size_t dimtype = (size_t)hdr.dim[0]; */
size_t ncols = (size_t)hdr.dim[1];
size_t nrows = (size_t)hdr.dim[2];
size_t nslices = (size_t)hdr.dim[3];
size_t nt = (size_t)hdr.dim[4];
/* fill data container */
size_t bytesize = 8;
if (dst_repn == VBitRepn) bytesize = 1;
size_t nsize = hdr.bitpix/bytesize;
size_t npixels = nslices * nrows * ncols;
size_t ndata = nt * npixels * nsize;
size_t vox_offset = (size_t)hdr.vox_offset;
size_t startdata = MIN_HEADER_SIZE;
if (vox_offset > 0) startdata = vox_offset;
char *data = &databuffer[startdata];
/* byte swap image data, if needed */
if (swap == 1) {
VByteSwapData(data,ndata,nsize);
}
/* repetition time (may be wrong in some cases) */
char xyzt = hdr.xyzt_units;
int tcode = XYZT_TO_TIME(xyzt);
float factor = 1.0;
float xtr=0;
if (tcode == NIFTI_UNITS_MSEC) factor = 1.0;
if (tcode == NIFTI_UNITS_SEC) factor = 1000.0;
if (nt > 1) {
if (tr == 0) tr = (short)(factor*hdr.pixdim[4]);
/* override if TR info is in description field */
xtr = TRfromString(hdr.descrip);
if (xtr > 0) {
tr = (short) (xtr*factor);
fprintf(stderr," reading TR from description field, TR= %ld ms\n",tr);
}
/* fprintf(stderr," nt=%ld, TR= %ld milliseconds\n",nt,tr); */
if (tr < 0.1) VWarning(" implausible TR (%d ms), use 'vnifti' for data conversion to specify TR on the command line",tr);
}
/* voxel reso */
int blen=512;
char *voxelstr = (char *) VCalloc(blen,sizeof(char));
memset(voxelstr,0,blen);
sprintf(voxelstr,"%f %f %f",hdr.pixdim[1],hdr.pixdim[2],hdr.pixdim[3]);
/* geometry information */
VAttrList geolist = VCreateAttrList();
double *slicetime = VGetNiftiHeader(geolist,hdr,tr);
/* read nii image into vista attrlist */
VAttrList out_list = VCreateAttrList();
VAppendAttr(out_list,"geoinfo",NULL,VAttrListRepn,geolist);
(*ok) = FALSE;
if (nt <= 1) { /* output one 3D image */
Nii2Vista3DList(data,nsize,nslices,nrows,ncols,nt,dst_repn,datatype,scl_slope,scl_inter,voxelstr,tr,out_list);
VUpdateGeoinfo(geolist,(int)3,tr);
}
else if (attrtype == FALSE) { /* output list of 3D images */
Nii2Vista3DList(data,nsize,nslices,nrows,ncols,nt,dst_repn,datatype,scl_slope,scl_inter,voxelstr,tr,out_list);
VUpdateGeoinfo(geolist,(int)3,tr);
}
else if (attrtype == TRUE && nt > 1) { /* output one 4D image */
Nii2Vista4D(data,nsize,nslices,nrows,ncols,nt,dst_repn,datatype,do_scaling,scl_slope,scl_inter,voxelstr,slicetime,tr,out_list);
VUpdateGeoinfo(geolist,(int)4,tr);
(*ok) = TRUE;
}
return out_list;
}
| {
"alphanum_fraction": 0.6483239395,
"avg_line_length": 28.248603352,
"ext": "c",
"hexsha": "636b384407cb94fd4c66bdd146bc3ec475c750ec",
"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/conv/vnifti/Nii2Vista.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/conv/vnifti/Nii2Vista.c",
"max_line_length": 131,
"max_stars_count": 17,
"max_stars_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "zrajna/lipsia",
"max_stars_repo_path": "src/conv/vnifti/Nii2Vista.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": 6818,
"size": 20226
} |
/* rng/ran1.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 <stdlib.h>
#include <gsl/gsl_rng.h>
/* This is an implementation of the algorithm used in Numerical
Recipe's ran1 generator. It is MINSTD with a 32-element
shuffle-box. */
static inline unsigned long int ran1_get (void *vstate);
static double ran1_get_double (void *vstate);
static void ran1_set (void *state, unsigned long int s);
static const long int m = 2147483647, a = 16807, q = 127773, r = 2836;
#define N_SHUFFLE 32
#define N_DIV (1 + 2147483646/N_SHUFFLE)
typedef struct
{
unsigned long int x;
unsigned long int n;
unsigned long int shuffle[N_SHUFFLE];
}
ran1_state_t;
static inline unsigned long int
ran1_get (void *vstate)
{
ran1_state_t *state = (ran1_state_t *) vstate;
const unsigned long int x = state->x;
const long int h = x / q;
const long int t = a * (x - h * q) - h * r;
if (t < 0)
{
state->x = t + m;
}
else
{
state->x = t;
}
{
unsigned long int j = state->n / N_DIV;
state->n = state->shuffle[j];
state->shuffle[j] = state->x;
}
return state->n;
}
static double
ran1_get_double (void *vstate)
{
float x_max = 1 - 1.2e-7f ; /* Numerical Recipes version of 1-FLT_EPS */
float x = ran1_get (vstate) / 2147483647.0f ;
if (x > x_max)
return x_max ;
return x ;
}
static void
ran1_set (void *vstate, unsigned long int s)
{
ran1_state_t *state = (ran1_state_t *) vstate;
int i;
if (s == 0)
s = 1; /* default seed is 1 */
for (i = 0; i < 8; i++)
{
long int h = s / q;
long int t = a * (s - h * q) - h * r;
if (t < 0)
t += m;
s = t;
}
for (i = N_SHUFFLE - 1; i >= 0; i--)
{
long int h = s / q;
long int t = a * (s - h * q) - h * r;
if (t < 0)
t += m;
s = t;
state->shuffle[i] = s;
}
state->x = s;
state->n = s;
return;
}
static const gsl_rng_type ran1_type =
{"ran1", /* name */
2147483646, /* RAND_MAX */
1, /* RAND_MIN */
sizeof (ran1_state_t),
&ran1_set,
&ran1_get,
&ran1_get_double};
const gsl_rng_type *gsl_rng_ran1 = &ran1_type;
| {
"alphanum_fraction": 0.6081890812,
"avg_line_length": 22.9312977099,
"ext": "c",
"hexsha": "0802ad2cac70ffb191bc9cf15c47c9c206d42bc5",
"lang": "C",
"max_forks_count": 40,
"max_forks_repo_forks_event_max_datetime": "2022-03-03T23:23:37.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-02-26T15:31:16.000Z",
"max_forks_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "manggoguy/parsec-modified",
"max_forks_repo_path": "pkgs/libs/gsl/src/rng/ran1.c",
"max_issues_count": 12,
"max_issues_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af",
"max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "manggoguy/parsec-modified",
"max_issues_repo_path": "pkgs/libs/gsl/src/rng/ran1.c",
"max_line_length": 81,
"max_stars_count": 64,
"max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "manggoguy/parsec-modified",
"max_stars_repo_path": "pkgs/libs/gsl/src/rng/ran1.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": 930,
"size": 3004
} |
/* Header file for ridgeRegressionFunctions.c */
#include "depends.h"
#ifdef HAVE_GSL_HEADER
/* includes */
#if _CUDA_
#include <cuda.h>
#include <cuda_runtime_api.h>
#include <cublas.h>
#include <cula_blas.h>
#include <cula.h>
#include "cudaOnlyFunctions.h"
#endif
#include <gsl/gsl_blas.h>
#include <gsl/gsl_linalg.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_vector.h>
#include <math.h>
#include "computeLinearRidge.h"
#include "ReadInData.h"
/* Compute linear ridge coefficeints */
int computeLinearRidge(GSL_TYPE(vector) * ahat,
GSL_TYPE(vector) * B,
GSL_TYPE(vector) * D2,
GSL_TYPE(matrix) * V,
PREC lambda);
/* linear generalized ridge regression */
GSL_TYPE(vector) * computeLinearGeneralizedRidge(GSL_TYPE(vector) * beta,
GSL_TYPE(matrix) * pred,
GSL_TYPE(vector) * pheno,
GSL_TYPE(vector) * shrinkage,
int intercept_flag);
int computeLogisticRidge(GSL_TYPE(vector) * beta,
GSL_TYPE(matrix) * pred,
GSL_TYPE(vector) * pheno,
GSL_TYPE(vector) * shrinkage,
int intercept_flat,
int Doff_flat,
PREC * DofF);
PREC objectiveFunction(GSL_TYPE(vector) * beta,
GSL_TYPE(matrix) * X,
GSL_TYPE(vector) * pheno,
GSL_TYPE(vector) * shrinkage,
int intercept_flat);
int updateBeta(GSL_TYPE(vector) * beta,
GSL_TYPE(matrix) * X,
GSL_TYPE(vector) * pheno,
GSL_TYPE(matrix) * kI,
int intercept_flag,
int DofF_flag,
GSL_TYPE(matrix) * invtXWX_return,
GSL_TYPE(matrix) * W_return);
int getProb(GSL_TYPE(vector) * p, GSL_TYPE(vector) * XB);
/* NB my_gsl_solve only works for matrices of type double
due to the linalg functions only having been written for this type */
int my_gsl_solve(gsl_matrix * X,
gsl_matrix * solvedX);
int compute_XB_and_p(GSL_TYPE(matrix) * X,
GSL_TYPE(vector) * B,
GSL_TYPE(vector) * XB,
GSL_TYPE(vector) * p);
int chooseHowManyK(GSL_TYPE(vector) * D);
int returnToOriginalScaleLinear(GSL_TYPE(vector) * betaOut,
GSL_TYPE(vector) * Bridge,
GSL_TYPE(vector) * means,
GSL_TYPE(vector) * scales,
PREC y_mean,
int intercept_flag);
/* return to original scale - generalized linear ridge regression */
int returnToOriginalScaleGenLinear(GSL_TYPE(vector) * Bridge,
GSL_TYPE(vector) * betaOut,
GSL_TYPE(matrix) * pred,
GSL_TYPE(vector) * pheno,
GSL_TYPE(vector) * scales,
int intercept_flag);
/* Convert trans */
char setTrans(CBLAS_TRANSPOSE_t Trans);
/* prepare for linear ridge
used when we are going to call linear rr on a range of different shrinkage parameters */
int prepareForLinearRidge(GSL_TYPE(matrix) * X,
GSL_TYPE(vector) * y,
GSL_TYPE(matrix) * U,
GSL_TYPE(matrix) * V,
GSL_TYPE(vector) * D,
GSL_TYPE(vector) * D2,
GSL_TYPE(matrix) * Z,
GSL_TYPE(vector) * ahat);
/* compute DofF for ridge model */
int computeDofF(GSL_TYPE(vector) * D2,
PREC Kr,
PREC * DofF);
/* compute (A + BDC')^(-1) */
int invert_sum_of_matrices(const PREC Ainv,
const GSL_TYPE(matrix) * B,
const GSL_TYPE(vector) * Dinv,
const GSL_TYPE(matrix) * tC,
GSL_TYPE(matrix) * out);
/* ordinary regression */
gsl_vector * my_gsl_linear_fit(gsl_matrix * X,
gsl_vector * y,
int NROW,
int NCOL);
#endif
| {
"alphanum_fraction": 0.6736028537,
"avg_line_length": 25.1044776119,
"ext": "h",
"hexsha": "dc51e7f894838eca9a827057a04a58136cda830e",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "78183d367b6e43aa93b629248450d001b6bb58ef",
"max_forks_repo_licenses": [
"OLDAP-2.4"
],
"max_forks_repo_name": "dfrankow/ridge-cran",
"max_forks_repo_path": "src/ridgeRegressionFunctions.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "78183d367b6e43aa93b629248450d001b6bb58ef",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"OLDAP-2.4"
],
"max_issues_repo_name": "dfrankow/ridge-cran",
"max_issues_repo_path": "src/ridgeRegressionFunctions.h",
"max_line_length": 89,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "78183d367b6e43aa93b629248450d001b6bb58ef",
"max_stars_repo_licenses": [
"OLDAP-2.4"
],
"max_stars_repo_name": "dfrankow/ridge-cran",
"max_stars_repo_path": "src/ridgeRegressionFunctions.h",
"max_stars_repo_stars_event_max_datetime": "2021-01-05T13:56:56.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-01-05T13:56:56.000Z",
"num_tokens": 933,
"size": 3364
} |
#include <stdio.h>
#include <gsl/gsl_errno.h>
#include <gsl/block/gsl_block.h>
#include <gsl/vector/gsl_vector.h>
#define BASE_DOUBLE
#include <gsl/templates_on.h>
#include <gsl/vector/file_source.c>
#include <gsl/templates_off.h>
#undef BASE_DOUBLE
| {
"alphanum_fraction": 0.7628458498,
"avg_line_length": 19.4615384615,
"ext": "c",
"hexsha": "faf6d1574f8be1a82dd328f0dd5a1a28bb8546dd",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "58778f148e65749e1dfc443043e9fc054ca3ff4d",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "MontyThibault/centre-of-mass-awareness",
"max_forks_repo_path": "Cartwheel/cartwheel-3d/gsl/vector/file.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "58778f148e65749e1dfc443043e9fc054ca3ff4d",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "MontyThibault/centre-of-mass-awareness",
"max_issues_repo_path": "Cartwheel/cartwheel-3d/gsl/vector/file.c",
"max_line_length": 35,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "58778f148e65749e1dfc443043e9fc054ca3ff4d",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "MontyThibault/centre-of-mass-awareness",
"max_stars_repo_path": "Cartwheel/cartwheel-3d/gsl/vector/file.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 67,
"size": 253
} |
/**
* Copyright 2016 BitTorrent Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <scraps/config.h>
#include <scraps/Byte.h>
#include <scraps/Temp.h>
#include <scraps/ByteArray.h>
#include <gsl.h>
#include <iterator>
namespace scraps {
constexpr signed char DecToHex(int c) {
if (c >= 0 && c < 16) {
return "0123456789abcdef"[c];
}
return -1;
}
constexpr signed char DecToHex(const Byte& c) {
return DecToHex(c.value());
}
template <typename CharT>
constexpr int8_t HexToDec(CharT c) {
if (c >= '0' && c <= '9') { return c - '0'; }
if (c >= 'a' && c <= 'f') { return c - 'a' + 10; }
if (c >= 'A' && c <= 'F') { return c - 'A' + 10; }
return -1;
}
/**
* Returns a hex string representation of the input span. The output does not
* include an "0x" prefix.
*
* example: ToHex(std::array<uint8_t, 1>{0xAB}) == "AB";
*/
template <typename T, std::ptrdiff_t... BytesDimension>
std::string ToHex(const gsl::span<T, BytesDimension...> range) {
std::string ret;
static_assert(sizeof(T) == 1, "Input span type too large");
ret.reserve(range.size() * 2 + 2);
for (auto& b : range) {
ret += DecToHex(b >> 4);
ret += DecToHex(b & 0x0F);
}
return ret;
}
template <typename T, size_t N>
std::string ToHex(const std::array<T, N>& in) {
return ToHex(gsl::span<const T, N>{in});
}
template <size_t N>
std::string ToHex(const ByteArray<N>& in) {
return ToHex(gsl::span<const unsigned char, N>{in.bytes});
}
/**
* Fills a byte range from a range of hex characters. Returns true if the input
* range is successfully converted to the output range. A prefix of "0x" or "0X"
* is optional.
*/
template <typename HexCharT, std::ptrdiff_t HexExtent, typename ByteType, std::ptrdiff_t... BytesDimension>
constexpr bool ToBytes(const gsl::basic_string_span<const HexCharT, HexExtent> hex, const gsl::span<ByteType, BytesDimension...> bytes) {
auto prefixSize = 0;
if (hex.size() > 2 && hex[0] == '0' && (hex[1] == 'x' || hex[1] == 'X')) {
prefixSize += 2;
}
if (hex.size() - prefixSize != bytes.size() * 2) {
return false;
}
for (decltype(bytes.size()) i = 0; i < bytes.size(); ++i) {
auto hi = HexToDec(hex[i * 2 + prefixSize]);
auto lo = HexToDec(hex[i * 2 + 1 + prefixSize]);
if (hi < 0 || lo < 0) {
return false;
}
bytes[i] = ByteType{static_cast<uint8_t>((hi << 4) | lo)};
}
return true;
}
template <typename CharT, typename T, size_t N>
constexpr bool ToBytes(const std::basic_string<CharT>& in, std::array<T, N>& out) {
return ToBytes(gsl::basic_string_span<const CharT>{in}, gsl::span<T, N>{out});
}
} // namespace scraps
| {
"alphanum_fraction": 0.629081947,
"avg_line_length": 28.9821428571,
"ext": "h",
"hexsha": "8abb838292e3280d2306a5a208db86baf3ff960b",
"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": "6308c4c7bd61bf7822a6eea27c499faf6fe6e263",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "marakew/scraps",
"max_forks_repo_path": "include/scraps/hex.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "6308c4c7bd61bf7822a6eea27c499faf6fe6e263",
"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": "marakew/scraps",
"max_issues_repo_path": "include/scraps/hex.h",
"max_line_length": 137,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "6308c4c7bd61bf7822a6eea27c499faf6fe6e263",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "marakew/scraps",
"max_stars_repo_path": "include/scraps/hex.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 937,
"size": 3246
} |
/**
* @file binauralprocessing.h
* @brief Binaural processing
* @author Kenichi Kumatani
*/
#ifndef BINAURALPROCESSING_H
#define BINAURALPROCESSING_H
#include <stdio.h>
#include <assert.h>
#include <float.h>
#include <gsl/gsl_block.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_complex.h>
#include <gsl/gsl_complex_math.h>
#include <gsl/gsl_fft_complex.h>
#include <common/refcount.h>
#include "common/jexception.h"
#include "stream/stream.h"
#include "postfilter/spectralsubtraction.h"
#include "beamformer/spectralinfoarray.h"
#include "beamformer/beamformer.h"
class BinaryMaskFilter : public VectorComplexFeatureStream {
public:
BinaryMaskFilter( unsigned chanX, VectorComplexFeatureStreamPtr &srcL, VectorComplexFeatureStreamPtr &srcR,
unsigned M, float threshold, float alpha,
float dEta = 0.01, const String& nm = "BinaryMaskFilter" );
~BinaryMaskFilter();
virtual const gsl_vector_complex* next(int frame_no = -5);
virtual void reset();
void set_threshold( float threshold ){ threshold_ = threshold; }
void set_thresholds( const gsl_vector *thresholds );
double threshold(){ return threshold_; }
gsl_vector *thresholds(){ return threshold_per_freq_; }
#ifdef ENABLE_LEGACY_BTK_API
void setThreshold( float threshold ){ set_threshold(threshold); }
void setThresholds( const gsl_vector *thresholds ){ set_thresholds(thresholds); }
double getThreshold(){ return threshold(); }
gsl_vector *getThresholds(){ return thresholds(); }
#endif
protected:
VectorComplexFeatureStreamPtr srcL_; /* left channel */
VectorComplexFeatureStreamPtr srcR_; /* right channel */
unsigned chanX_; /* want to extract the index of a channel */
gsl_vector_float *prevMu_; /* binary mask at a previous frame */
float alpha_; /* forgetting factor */
float dEta_; /* flooring value */
float threshold_; /* threshold for the ITD */
gsl_vector *threshold_per_freq_;
};
typedef Inherit<BinaryMaskFilter, VectorComplexFeatureStreamPtr> BinaryMaskFilterPtr;
/**
@class Implementation of binary masking based on C. Kim's Interspeech2010 paper
@brief binary mask two inputs based of the threshold of the interaural time delay (ITD)
@usage
*/
class KimBinaryMaskFilter : public BinaryMaskFilter {
public:
KimBinaryMaskFilter( unsigned chanX, VectorComplexFeatureStreamPtr &srcL, VectorComplexFeatureStreamPtr &srcR,
unsigned M, float threshold, float alpha,
float dEta = 0.01, float dPowerCoeff = 1/15.0, const String& nm = "KimBinaryMaskFilter" );
~KimBinaryMaskFilter();
virtual const gsl_vector_complex* next(int frame_no = -5);
virtual void reset();
virtual const gsl_vector_complex* masking1( const gsl_vector_complex* ad_X_L, const gsl_vector_complex* ad_X_R, float threshold );
protected:
float dpower_coeff_; /* power law non-linearity */
};
typedef Inherit<KimBinaryMaskFilter, BinaryMaskFilterPtr> KimBinaryMaskFilterPtr;
/**
@class Implementation of estimating the threshold for C. Kim's ITD-based binary masking
@brief binary mask two inputs based of the threshold of the interaural time delay (ITD)
@usage
*/
class KimITDThresholdEstimator : public KimBinaryMaskFilter {
public:
KimITDThresholdEstimator( VectorComplexFeatureStreamPtr &srcL, VectorComplexFeatureStreamPtr &srcR, unsigned M, float minThreshold = 0, float maxThreshold = 0, float width = 0.02, float minFreq= -1, float maxFreq=-1, int sampleRate=-1, float dEta = 0.01, float dPowerCoeff = 1/15.0, const String& nm = "KimITDThresholdEstimator" );
~KimITDThresholdEstimator();
virtual const gsl_vector_complex* next(int frame_no = -5);
virtual void reset();
virtual double calc_threshold();
const gsl_vector* cost_function();
#ifdef ENABLE_LEGACY_BTK_API
virtual double calcThreshold(){ return calc_threshold(); }
const gsl_vector* getCostFunction(){ return cost_function(); }
#endif
protected:
virtual void accumStats1( const gsl_vector_complex* ad_X_L, const gsl_vector_complex* ad_X_R );
/* for restricting the search space */
float min_threshold_;
float max_threshold_;
float width_;
unsigned min_fbinX_;
unsigned max_fbinX_;
/* work space */
double *cost_func_values_;
double *sigma_T_;
double *sigma_I_;
double *mean_T_;
double *mean_I_;
unsigned int nCand_;
unsigned int nSamples_;
gsl_vector *buffer_; /* for returning values from the python */
bool cost_func_computed_;
};
typedef Inherit<KimITDThresholdEstimator, KimBinaryMaskFilterPtr> KimITDThresholdEstimatorPtr;
/**
@class
*/
class IIDBinaryMaskFilter : public BinaryMaskFilter {
public:
IIDBinaryMaskFilter( unsigned chanX, VectorComplexFeatureStreamPtr &srcL, VectorComplexFeatureStreamPtr &srcR,
unsigned M, float threshold, float alpha,
float dEta = 0.01, const String& nm = "IIDBinaryMaskFilter" );
~IIDBinaryMaskFilter();
virtual const gsl_vector_complex* next(int frame_no = -5);
virtual void reset();
virtual const gsl_vector_complex* masking1( const gsl_vector_complex* ad_X_L, const gsl_vector_complex* ad_X_R, float threshold );
};
typedef Inherit<IIDBinaryMaskFilter, BinaryMaskFilterPtr> IIDBinaryMaskFilterPtr;
/**
@class binary masking based on a difference between magnitudes of two beamformers' outputs.
@brief set zero to beamformer's output with the smaller magnitude over frequency bins
*/
class IIDThresholdEstimator : public KimITDThresholdEstimator {
public:
IIDThresholdEstimator( VectorComplexFeatureStreamPtr &srcL, VectorComplexFeatureStreamPtr &srcR, unsigned M,
float minThreshold = 0, float maxThreshold = 0, float width = 0.02,
float minFreq= -1, float maxFreq=-1, int sampleRate=-1, float dEta = 0.01, float dPowerCoeff = 0.5, const String& nm = "IIDThresholdEstimator" );
~IIDThresholdEstimator();
virtual const gsl_vector_complex* next(int frame_no = -5);
virtual void reset();
virtual double calc_threshold();
#ifdef ENABLE_LEGACY_BTK_API
virtual double calcThreshold(){ return calc_threshold(); }
#endif
protected:
virtual void accumStats1( const gsl_vector_complex* ad_X_L, const gsl_vector_complex* ad_X_R );
private:
double *_Y4_T;
double *_Y4_I;
double _beta;
};
typedef Inherit<IIDThresholdEstimator, KimITDThresholdEstimatorPtr> IIDThresholdEstimatorPtr;
/**
@class binary masking based on a difference between magnitudes of two beamformers' outputs at each frequency bin.
@brief set zero to beamformer's output with the smaller magnitude at each frequency bin
*/
class FDIIDThresholdEstimator : public BinaryMaskFilter {
public:
FDIIDThresholdEstimator( VectorComplexFeatureStreamPtr &srcL, VectorComplexFeatureStreamPtr &srcR, unsigned M,
float minThreshold = 0, float maxThreshold = 0, float width = 1000,
float dEta = 0.01, float dPowerCoeff = 1/15.0, const String& nm = "FDIIDThresholdEstimator" );
~FDIIDThresholdEstimator();
virtual const gsl_vector_complex* next(int frame_no = -5);
virtual void reset();
virtual double calc_threshold();
const gsl_vector* cost_function(unsigned freqX);
#ifdef ENABLE_LEGACY_BTK_API
virtual double calcThreshold(){ return calc_threshold(); }
const gsl_vector* getCostFunction( unsigned freqX ){ return cost_function(freqX); }
#endif
protected:
virtual void accumStats1( const gsl_vector_complex* ad_X_L, const gsl_vector_complex* ad_X_R );
/* for restricting the search space */
float min_threshold_;
float max_threshold_;
float width_;
float dpower_coeff_;
/* work space */
double **cost_func_values_;
double **_Y4;
double **_sigma;
double **_mean;
double _beta;
unsigned int nCand_;
unsigned int nSamples_;
gsl_vector *buffer_; /* for returning values from the python */
bool cost_func_computed_;
};
typedef Inherit<FDIIDThresholdEstimator, BinaryMaskFilterPtr> FDIIDThresholdEstimatorPtr;
#endif
| {
"alphanum_fraction": 0.7560146114,
"avg_line_length": 37.0981308411,
"ext": "h",
"hexsha": "ae6150d6f364d86d2c95ef7f31ad0f1bbb7eb1fe",
"lang": "C",
"max_forks_count": 68,
"max_forks_repo_forks_event_max_datetime": "2021-11-17T09:33:10.000Z",
"max_forks_repo_forks_event_min_datetime": "2019-01-08T06:33:30.000Z",
"max_forks_repo_head_hexsha": "60f867383488ac45c2fa3a5433736fdf00dd4f1d",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "musiclvme/distant_speech_recognition",
"max_forks_repo_path": "btk20_src/postfilter/binauralprocessing.h",
"max_issues_count": 25,
"max_issues_repo_head_hexsha": "60f867383488ac45c2fa3a5433736fdf00dd4f1d",
"max_issues_repo_issues_event_max_datetime": "2021-07-28T22:01:37.000Z",
"max_issues_repo_issues_event_min_datetime": "2018-12-03T04:33:24.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "musiclvme/distant_speech_recognition",
"max_issues_repo_path": "btk20_src/postfilter/binauralprocessing.h",
"max_line_length": 333,
"max_stars_count": 136,
"max_stars_repo_head_hexsha": "60f867383488ac45c2fa3a5433736fdf00dd4f1d",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "musiclvme/distant_speech_recognition",
"max_stars_repo_path": "btk20_src/postfilter/binauralprocessing.h",
"max_stars_repo_stars_event_max_datetime": "2022-03-27T15:07:42.000Z",
"max_stars_repo_stars_event_min_datetime": "2018-12-06T06:35:44.000Z",
"num_tokens": 1950,
"size": 7939
} |
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <gsl/gsl_blas.h>
#include "my_timer.h"
#define N 5
int cal_index_offset(int ndim, int *darr, int *position) {
int size = 1;
int offset = 0;
for(int i = ndim-1; i >= 0; i--) {
offset += position[i] * size;
size *= darr[i];
}
return offset;
}
void print_mat_recursive(double *mat, int ndim, int *darr, int pdim, int *position) {
if(pdim >= ndim) {
int index_offset = cal_index_offset(ndim, darr, position);
printf("%lf ", mat[index_offset]);
return;
}
printf("[ ");
for(int i = 0; i < darr[pdim]; i++) {
position[pdim] = i;
print_mat_recursive(mat, ndim, darr, pdim+1, position);
}
printf("]");
}
void print_mat(double *mat, int ndim, ...) {
int position[ndim];
int darr[ndim];
va_list args;
va_start(args, ndim);
for(int i = 0; i < ndim; i++) {
darr[i] = va_arg(args, int);
}
va_end(args);
print_mat_recursive(mat, ndim, darr, 0, position);
printf("\n");
}
void mm_brute_force(double *a, double *b, double *c, int p, int q, int r) {
for(int i = 0; i < p; i++) {
for(int k = 0; k < q; k++) {
for(int j = 0; j < r; j++) {
c[i * r + j] += a[i * q + k] * b[k * r + j];
}
}
}
}
void mm_dgemm(double *a, double *b, double *c, int p, int q, int r) {
int l = p;
int m = q;
int n = r;
int lda = m;
int ldb = n;
int ldc = n;
double alpha = 1.0;
double beta = 0.0;
cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans,
l, n, m, alpha, a, lda, b, ldb, beta, c, ldc);
}
void example_dgemm() {
int l, m, n;
l = m = n = N;
double *mat_a = (double*)malloc(sizeof(double) * l * m);
double *mat_b = (double*)malloc(sizeof(double) * m * n);
double *mat_c = (double*)malloc(sizeof(double) * l * n);
for(int i = 0; i < (l*m); i++) {
mat_a[i] = i + 1;
}
for(int i = 0; i < (m*n); i++) {
mat_b[i] = i + 1;
}
for(int i = 0; i < (l*n); i++) {
mat_c[i] = 0;
}
my_timer_t mt;
my_timer_start(&mt);
mm_dgemm(mat_a, mat_b, mat_c, l, m, n);
my_timer_end(&mt);
my_timer_print(&mt);
printf("\n");
print_mat(mat_a, 2, l, m);
printf("\n");
print_mat(mat_b, 2, m, n);
printf("\n");
print_mat(mat_c, 2, l, n);
printf("\n");
free(mat_a);
free(mat_b);
free(mat_c);
}
int main(void) {
example_dgemm();
return 0;
}
| {
"alphanum_fraction": 0.5082159624,
"avg_line_length": 21.4789915966,
"ext": "c",
"hexsha": "03dd4fc6b041eb33807ec4c4cc528d913ac37650",
"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": "80a0579c890bbb1a4d3ee6ee323f23d1204d0bdf",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "read2r/blas_practice",
"max_forks_repo_path": "main.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "80a0579c890bbb1a4d3ee6ee323f23d1204d0bdf",
"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": "read2r/blas_practice",
"max_issues_repo_path": "main.c",
"max_line_length": 85,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "80a0579c890bbb1a4d3ee6ee323f23d1204d0bdf",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "read2r/blas_practice",
"max_stars_repo_path": "main.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 863,
"size": 2556
} |
#pragma once
#include "type_traits.h"
#include <gsl/gsl>
#include <system_error>
#include <variant>
namespace arcana
{
template<typename Type>
struct is_expected;
template<typename T, typename E>
class basic_expected;
namespace internal
{
template<typename T>
struct expected_error_traits;
template<>
struct expected_error_traits<std::error_code>
{
template<typename ErrorT>
using is_convertible = std::bool_constant<
std::is_error_code_enum<std::decay_t<ErrorT>>::value ||
std::is_error_condition_enum<std::decay_t<ErrorT>>::value
>;
template<typename ErrorT>
using enable_conversion = std::enable_if<
is_convertible<ErrorT>::value
>;
template<typename ErrorT>
static std::error_code convert(ErrorT errorEnum)
{
using std::make_error_code;
return make_error_code(errorEnum);
}
};
template<>
struct expected_error_traits<std::exception_ptr>
{
template<typename ErrorT>
using enable_conversion = std::enable_if<
std::is_same<std::error_code, ErrorT>::value || // support conversion from error_codes
expected_error_traits<std::error_code>::template is_convertible<ErrorT>::value // and also enumerations that are error codes
>;
static std::exception_ptr convert(std::error_code code)
{
return std::make_exception_ptr(std::system_error(code));
}
template<typename ErrorT, typename = typename expected_error_traits<std::error_code>::template enable_conversion<ErrorT>::type>
static std::exception_ptr convert(ErrorT errorEnum)
{
return convert(
expected_error_traits<std::error_code>::convert(errorEnum));
}
};
}
class bad_expected_access : public std::exception
{
public:
const char* what() const override
{
return "tried accessing value()/error() of an expected when it wasn't set";
}
};
template<typename E>
class unexpected
{
public:
unexpected() = delete;
constexpr explicit unexpected(const E& e)
: m_e{ e }
{}
constexpr explicit unexpected(E&& e)
: m_e{ std::move(e) }
{}
constexpr const E& value() const &
{
return m_e;
}
constexpr E& value() &
{
return m_e;
}
constexpr E&& value() &&
{
return std::move(m_e);
}
private:
E m_e;
};
template<typename T>
inline auto make_unexpected(T&& error)
{
return unexpected<std::decay_t<T>>{std::forward<T>(error)};
}
template<typename T, typename E>
class basic_expected
{
using traits = internal::expected_error_traits<E>;
template<typename E2,
typename = typename traits::template enable_conversion<E2>::type>
std::variant<E, T> convert_variant(const basic_expected<T, E2>& exp)
{
if (exp.has_error())
return { traits::convert(exp.error()) };
else
return { exp.value() };
}
public:
using value_type = T;
using error_type = E;
basic_expected(const value_type& value)
: m_data{ value }
{}
basic_expected(value_type&& value)
: m_data{ std::move(value) }
{}
template<typename ErrorT,
typename = typename traits::template enable_conversion<ErrorT>::type>
basic_expected(const unexpected<ErrorT>& errorEnum)
: m_data{ traits::convert(errorEnum.value()) }
{}
basic_expected(const unexpected<error_type>& ec)
: m_data{ ec.value() }
{
GSL_CONTRACT_CHECK("you should never build an basic_expected<T,E> with a non-error", static_cast<bool>(error()));
}
basic_expected(unexpected<error_type>&& ec)
: m_data{ std::move(ec).value() }
{
GSL_CONTRACT_CHECK("you should never build an basic_expected<T,E> with a non-error", static_cast<bool>(error()));
}
template<typename ErrorT,
typename = typename traits::template enable_conversion<ErrorT>::type>
basic_expected(const basic_expected<value_type, ErrorT>& other)
: m_data{ convert_variant(other) }
{}
template<typename ErrorT,
typename = typename traits::template enable_conversion<ErrorT>::type>
basic_expected& operator=(const basic_expected<value_type, ErrorT>& other)
{
m_data = convert_variant(other);
}
//
// Returns the expected value or throws bad_expected_access if it is in an error state.
//
const value_type& value() const
{
return const_cast<basic_expected*>(this)->value();
}
value_type& value()
{
auto val = std::get_if<value_type>(&m_data);
if (val == nullptr)
{
throw bad_expected_access();
}
return *val;
}
//
// Returns the value contained or the default passed in if the expected is in an error state.
//
template<typename U>
value_type value_or(U&& def) const
{
if (!has_value())
{
return std::forward<U>(def);
}
return value();
}
//
// Returns the error or throws bad_expected_access if it is not in an error state.
//
const error_type& error() const
{
auto err = std::get_if<error_type>(&m_data);
if (err == nullptr)
{
throw bad_expected_access();
}
return *err;
}
//
// Returns whether or not the expected contains a value.
//
bool has_value() const noexcept
{
return std::holds_alternative<value_type>(m_data);
}
//
// Returns whether or not the expected is in an error state.
//
bool has_error() const noexcept
{
return std::holds_alternative<error_type>(m_data);
}
//
// Converts to true if the value is valid.
//
explicit operator bool() const noexcept
{
return has_value();
}
//
// Shorthand access operators
//
const value_type& operator*() const
{
return value();
}
value_type& operator*()
{
return value();
}
//
// Shorthand access operators
//
const value_type* operator->() const
{
return &value();
}
value_type* operator->()
{
return &value();
}
private:
std::variant<error_type, value_type> m_data;
};
template<typename E>
class basic_expected<void, E>
{
public:
using value_type = void;
using error_type = E;
using traits = internal::expected_error_traits<error_type>;
template<typename ErrorT,
typename = typename traits::template enable_conversion<ErrorT>::type>
basic_expected(const unexpected<ErrorT>& errorEnum)
: m_error{ traits::convert(errorEnum.value()) }
{}
basic_expected(const unexpected<error_type>& ec)
: m_error{ ec.value() }
{
GSL_CONTRACT_CHECK("you should never build an basic_expected<T,E> with a non-error", static_cast<bool>(error()));
}
basic_expected(unexpected<error_type>&& ec)
: m_error{ std::move(ec).value() }
{
GSL_CONTRACT_CHECK("you should never build an basic_expected<T,E> with a non-error", static_cast<bool>(error()));
}
template<typename ErrorT,
typename = typename traits::template enable_conversion<ErrorT>::type>
basic_expected(const basic_expected<value_type, ErrorT>& other)
: m_error{ other.has_error() ? traits::convert(other.error()) : nullptr }
{}
template<typename ErrorT,
typename = typename traits::template enable_conversion<ErrorT>::type>
basic_expected& operator=(const basic_expected<value_type, ErrorT>& other)
{
m_error = other.has_error() ? traits::convert(other.error()) : nullptr;
}
//
// Returns the error, throws bad_expected_access if it is not in an error state
//
const error_type& error() const
{
if (!has_error())
{
throw bad_expected_access();
}
return m_error;
}
//
// Returns whether or not the expected is in an error state.
//
bool has_error() const noexcept
{
return static_cast<bool>(m_error);
}
//
// Converts to true if the value is valid.
//
explicit operator bool() const noexcept
{
return !has_error();
}
//
// Creates an expected<void> that doesn't have an error
//
static basic_expected make_valid()
{
return basic_expected{};
}
private:
basic_expected() = default;
error_type m_error;
};
template<typename Type>
struct is_expected : public std::false_type
{};
template<typename Type, typename Error>
struct is_expected<basic_expected<Type, Error>> : public std::true_type
{};
template<typename ResultT, typename ErrorT>
struct as_expected
{
using type = basic_expected<ResultT, ErrorT>;
using value_type = typename type::value_type;
using error_type = typename type::error_type;
};
template<typename ResultT, typename ErrorT, typename DesiredErrorT>
struct as_expected<basic_expected<ResultT, ErrorT>, DesiredErrorT>
{
static_assert(std::is_same<ErrorT, DesiredErrorT>::value, "the error type of the expected and the desired error type don't match");
using type = basic_expected<ResultT, ErrorT>;
using value_type = typename type::value_type;
using error_type = typename type::error_type;
};
template<typename ResultT, typename ErrorT>
using expected = basic_expected<ResultT, ErrorT>;
template<typename ErrorT>
struct error_priority;
template<>
struct error_priority<std::error_code> : std::integral_constant<int, 0>
{
using type = std::error_code;
};
template<>
struct error_priority<std::exception_ptr> : std::integral_constant<int, 1>
{
using type = std::exception_ptr;
};
template<typename Left, typename Right>
struct largest_error
{
using type = typename typename largest_integral_constant<error_priority<Left>, error_priority<Right>>::type::type;
};
namespace internal
{
template<typename Expected, typename OrType, bool IsExpected>
struct expected_error_or_impl
{
using type = OrType;
};
template<typename Expected, typename OrType>
struct expected_error_or_impl<Expected, OrType, true>
{
using type = typename Expected::error_type;
};
}
template<typename Expected, typename OrType>
struct expected_error_or : public internal::expected_error_or_impl<Expected, OrType, is_expected<Expected>::value>
{};
}
| {
"alphanum_fraction": 0.5670578374,
"avg_line_length": 28.2033096927,
"ext": "h",
"hexsha": "c94ad68b3208a76b6d584a1261afea75040c69b1",
"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": "1df97dab612caf0d25f9f00bda6d7ca2f27b7e6d",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "ryantrem/arcana.cpp",
"max_forks_repo_path": "Source/Shared/arcana/expected.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "1df97dab612caf0d25f9f00bda6d7ca2f27b7e6d",
"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": "ryantrem/arcana.cpp",
"max_issues_repo_path": "Source/Shared/arcana/expected.h",
"max_line_length": 140,
"max_stars_count": 2,
"max_stars_repo_head_hexsha": "1df97dab612caf0d25f9f00bda6d7ca2f27b7e6d",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "ryantrem/arcana.cpp",
"max_stars_repo_path": "Source/Shared/arcana/expected.h",
"max_stars_repo_stars_event_max_datetime": "2021-07-07T10:25:56.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-11-25T10:03:17.000Z",
"num_tokens": 2422,
"size": 11930
} |
#ifndef GEMMFORGE_REFERENCE_GEMM_H
#define GEMMFORGE_REFERENCE_GEMM_H
#include "typedef.h"
#include <iostream>
#define GEMMFORGE 1
#define OPENBLAS 2
#define CPU_BACKEND CONCRETE_CPU_BACKEND
#if CPU_BACKEND == OPENBLAS
#include <cblas.h>
#endif
namespace gemmforge {
namespace reference {
enum class LayoutType {
Trans, NoTrans
};
void singleGemm(LayoutType TypeA,
LayoutType TypeB,
int M, int N, int K,
real Alpha, real *A, int Lda,
real *B, int Ldb,
real Beta, real *C, int Ldc);
real *findData(real *Data, unsigned Stride, unsigned BlockId);
real *findData(real **Data, unsigned Stride, unsigned BlockId);
template<typename AT, typename BT, typename CT>
void gemm(LayoutType TypeA,
LayoutType TypeB,
int M, int N, int K,
real Alpha, AT A, int Lda,
BT B, int Ldb,
real Beta, CT C, int Ldc,
unsigned OffsetA,
unsigned OffsetB,
unsigned OffsetC,
unsigned NumElements) {
for (unsigned Index = 0; Index < NumElements; ++Index) {
real *MatrixA = findData(A, OffsetA, Index);
real *MatrixB = findData(B, OffsetB, Index);
real *MatrixC = findData(C, OffsetC, Index);
#if CPU_BACKEND == GEMMFORGE
singleGemm(TypeA, TypeB,
M, N, K,
Alpha, MatrixA, Lda,
MatrixB, Ldb,
Beta, MatrixC, Ldc);
#elif CPU_BACKEND == OPENBLAS
CBLAS_LAYOUT Layout = CblasColMajor;
CBLAS_TRANSPOSE TransA = TypeA == LayoutType::Trans ? CblasTrans : CblasNoTrans;
CBLAS_TRANSPOSE TransB = TypeB == LayoutType::Trans ? CblasTrans : CblasNoTrans;
#if REAL_SIZE == 4
cblas_sgemm(Layout, TransA, TransB,
M, N, K,
Alpha, MatrixA, Lda,
MatrixB, Ldb,
Beta, MatrixC, Ldc);
#elif REAL_SIZE == 8
cblas_dgemm(Layout, TransA, TransB,
M, N, K,
Alpha, MatrixA, Lda,
MatrixB, Ldb,
Beta, MatrixC, Ldc);
#endif
#else
#error "Chosen reference CPU-GEMM impl. is not supported"
#endif
}
}
}
}
#endif //GEMMFORGE_REFERENCE_GEMM_H | {
"alphanum_fraction": 0.5761531767,
"avg_line_length": 27.3571428571,
"ext": "h",
"hexsha": "2682c029af6c931f297615467159444e1ce4f19b",
"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": "6381584c2d1ce77eaa938de02bc4f130f19cb2e4",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "ravil-mobile/gemmforge",
"max_forks_repo_path": "common/gemm.h",
"max_issues_count": 2,
"max_issues_repo_head_hexsha": "6381584c2d1ce77eaa938de02bc4f130f19cb2e4",
"max_issues_repo_issues_event_max_datetime": "2021-05-05T13:44:43.000Z",
"max_issues_repo_issues_event_min_datetime": "2021-02-01T16:31:22.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "ravil-mobile/gemmforge",
"max_issues_repo_path": "common/gemm.h",
"max_line_length": 82,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "6381584c2d1ce77eaa938de02bc4f130f19cb2e4",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "ravil-mobile/gemmforge",
"max_stars_repo_path": "common/gemm.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 610,
"size": 2298
} |
//
// SPDX-License-Identifier: MIT
// Copyright (C) 2020 - 2021 by the ryujin authors
//
#pragma once
#ifdef DEAL_II_WITH_GSL
#include <gsl/gsl_spline.h>
namespace ryujin
{
/**
* A cubic spline class implemented as a thin wrapper around the GSL
* spline library functions.
*
* Usage:
* @code
* std::vector<double> xs{0.0, 0.2, 0.4, 0.6, 0.8, 1.0};
* std::vector<double> ys{1.0, 0.2, 5.0, 2.0, 1.0, 10.0};
* CubicSpline spline(xs, ys);
*
* spline.eval(0.5);
* @endcode
*
* @ingroup Mesh
*/
class CubicSpline
{
public:
/**
* Constructor.
*
* @pre The supplied vectors @p x and @p y must have the same size and
* must contain at least two elements. The vector @p x must be sorted
*/
CubicSpline(const std::vector<double> &x,
const std::vector<double> &y) noexcept
: x_(x)
, y_(y)
{
AssertNothrow(x_.size() == y_.size(), dealii::ExcInternalError());
AssertNothrow(x_.size() >= 2, dealii::ExcInternalError());
AssertNothrow(std::is_sorted(x_.begin(), x_.end()),
dealii::ExcInternalError());
spline = gsl_spline_alloc(gsl_interp_cspline, x_.size());
gsl_spline_init(spline, x_.data(), y_.data(), x_.size());
accel = gsl_interp_accel_alloc();
}
/**
* Copy constructor.
*/
CubicSpline(const CubicSpline ©)
: CubicSpline(copy.x_, copy.y_)
{
}
/**
* The copy assignment operator is deleted.
*/
CubicSpline &operator=(const CubicSpline &) = delete;
/**
* Destructor.
*/
~CubicSpline()
{
gsl_interp_accel_free(accel);
gsl_spline_free(spline);
}
/**
* Evaluate the cubic spline at a given point @p x.
*
* @pre The point @p x must lie within the interval described by the
* largest and smallest support point supplied to the constructor.
*/
inline double eval(double x) const
{
return gsl_spline_eval(spline, x, accel);
}
private:
const std::vector<double> x_;
const std::vector<double> y_;
gsl_spline *spline;
mutable gsl_interp_accel *accel;
};
} // namespace ryujin
#endif
| {
"alphanum_fraction": 0.5937641211,
"avg_line_length": 23.2947368421,
"ext": "h",
"hexsha": "dbe31601d32367fe22dcafb6af20afc923ee2d1a",
"lang": "C",
"max_forks_count": 12,
"max_forks_repo_forks_event_max_datetime": "2021-11-23T18:09:54.000Z",
"max_forks_repo_forks_event_min_datetime": "2020-07-11T16:30:39.000Z",
"max_forks_repo_head_hexsha": "8752fff625300d1e7e2ea22bf3e816e2f5725afa",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "Fanxiaotsing/ryujin",
"max_forks_repo_path": "source/cubic_spline.h",
"max_issues_count": 4,
"max_issues_repo_head_hexsha": "8752fff625300d1e7e2ea22bf3e816e2f5725afa",
"max_issues_repo_issues_event_max_datetime": "2021-09-13T19:40:41.000Z",
"max_issues_repo_issues_event_min_datetime": "2021-08-28T17:11:52.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "Fanxiaotsing/ryujin",
"max_issues_repo_path": "source/cubic_spline.h",
"max_line_length": 74,
"max_stars_count": 37,
"max_stars_repo_head_hexsha": "8752fff625300d1e7e2ea22bf3e816e2f5725afa",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "Fanxiaotsing/ryujin",
"max_stars_repo_path": "source/cubic_spline.h",
"max_stars_repo_stars_event_max_datetime": "2022-03-04T00:30:21.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-06-30T20:52:53.000Z",
"num_tokens": 640,
"size": 2213
} |
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <gsl/gsl_linalg.h>
#include <gsl/gsl_eigen.h>
#include "shared/libklp_matrix_header.h"
#include "shared/libtpl_header.h"
#include "population_constants.h"
#include "population_params.h"
#include "population_initializers.h"
#include "population_functions.h"
void population_from_row_ordered_transition_matrix(const KLP_PARAMS klp_params, const POPULATION_PARAMS parameters, TRANSITION_MATRIX row_transition_matrix) {
if (parameters.equilibrium) {
equilibrium_from_row_ordered_transition_matrix(klp_params, parameters, row_transition_matrix);
} else {
population_proportion_from_row_ordered_transition_matrix(klp_params, parameters, row_transition_matrix);
}
}
void equilibrium_from_row_ordered_transition_matrix(const KLP_PARAMS klp_params, const POPULATION_PARAMS parameters, TRANSITION_MATRIX row_transition_matrix) {
EIGENSYSTEM eigensystem;
eigensystem = eigensystem_from_row_ordered_transition_matrix(row_transition_matrix);
print_equilibrium(eigensystem, klp_params, parameters);
}
void population_proportion_from_row_ordered_transition_matrix(const KLP_PARAMS klp_params, const POPULATION_PARAMS parameters, TRANSITION_MATRIX row_transition_matrix) {
EIGENSYSTEM eigensystem;
eigensystem = eigensystem_from_row_ordered_transition_matrix(row_transition_matrix);
print_population_proportion(eigensystem, klp_params, parameters);
}
EIGENSYSTEM eigensystem_from_row_ordered_transition_matrix(TRANSITION_MATRIX row_transition_matrix) {
TRANSITION_MATRIX column_transition_matrix;
EIGENSYSTEM eigensystem;
column_transition_matrix = transpose_matrix(row_transition_matrix);
eigensystem = convert_transition_matrix_to_eigenvectors(column_transition_matrix);
invert_matrix(&eigensystem);
return eigensystem;
}
TRANSITION_MATRIX convert_structures_to_transition_matrix(const SOLUTION* all_structures, int num_structures) {
// This code to convert the list of structures to a transition matrix does not ensure that there are only single b.p. moves.
int i, j;
double col_sum;
TRANSITION_MATRIX transition_matrix = init_transition_matrix(num_structures, 'R');
for (i = 0; i < num_structures; ++i) {
col_sum = 0;
for (j = 0; j < num_structures; ++j) {
if (i != j) {
T_COL_ORDER(transition_matrix, i, j) = \
MIN(1, exp(-((double)all_structures[j].energy - (double)all_structures[i].energy) / VIENNA_RT));
col_sum += T_COL_ORDER(transition_matrix, i, j);
#ifdef INSANE_DEBUG
printf("%d\t%d\t%.4e\n", i, j, T_COL_ORDER(transition_matrix, i, j));
#endif
}
}
#ifdef INSANE_DEBUG
printf("%d col_sum:\t%.4e\n\n", i, col_sum);
#endif
T_COL_ORDER(transition_matrix, i, i) = -col_sum;
}
return transition_matrix;
}
EIGENSYSTEM convert_transition_matrix_to_eigenvectors(TRANSITION_MATRIX transition_matrix) {
// Generates right eigenvectors from a column-ordered transition rate matrix, and saves them in a one-dimensional column-ordered array (eigensystem.vectors).
int i, j;
EIGENSYSTEM eigensystem;
eigensystem = init_eigensystem(transition_matrix.row_length);
gsl_matrix_view matrix_view = gsl_matrix_view_array(transition_matrix.matrix, eigensystem.length, eigensystem.length);
gsl_vector_complex* eigenvalues = gsl_vector_complex_alloc(eigensystem.length);
gsl_matrix_complex* eigenvectors = gsl_matrix_complex_alloc(eigensystem.length, eigensystem.length);
gsl_eigen_nonsymmv_workspace* workspace = gsl_eigen_nonsymmv_alloc(eigensystem.length);
gsl_eigen_nonsymmv_params(1, workspace);
gsl_eigen_nonsymmv(&matrix_view.matrix, eigenvalues, eigenvectors, workspace);
gsl_eigen_nonsymmv_free(workspace);
for (i = 0; i < eigensystem.length; ++i) {
eigensystem.values[i] = GSL_REAL(gsl_vector_complex_get(eigenvalues, i));
gsl_vector_complex_view eigenvector = gsl_matrix_complex_column(eigenvectors, i);
for (j = 0; j < eigensystem.length; ++j) {
E_COL_ORDER(eigensystem.vectors, i, j, eigensystem.length) = GSL_REAL(gsl_vector_complex_get(&eigenvector.vector, j));
}
}
free_transition_matrix(transition_matrix);
gsl_vector_complex_free(eigenvalues);
gsl_matrix_complex_free(eigenvectors);
return eigensystem;
}
void invert_matrix(EIGENSYSTEM* eigensystem) {
int i, j, signum;
gsl_matrix* matrix_to_invert = gsl_matrix_alloc(eigensystem->length, eigensystem->length);
gsl_matrix* inversion_matrix = gsl_matrix_alloc(eigensystem->length, eigensystem->length);
gsl_permutation* permutation = gsl_permutation_alloc(eigensystem->length);
for (i = 0; i < eigensystem->length; ++i) {
for (j = 0; j < eigensystem->length; ++j) {
gsl_matrix_set(matrix_to_invert, i, j, E_ROW_ORDER(eigensystem->vectors, i, j, eigensystem->length));
}
}
gsl_linalg_LU_decomp(matrix_to_invert, permutation, &signum);
gsl_linalg_LU_invert(matrix_to_invert, permutation, inversion_matrix);
for (i = 0; i < eigensystem->length; ++i) {
for (j = 0; j < eigensystem->length; ++j) {
E_ROW_ORDER(eigensystem->inverse_vectors, i, j, eigensystem->length) = gsl_matrix_get(inversion_matrix, i, j);
}
}
gsl_matrix_free(matrix_to_invert);
gsl_matrix_free(inversion_matrix);
gsl_permutation_free(permutation);
}
double probability_at_logtime(const EIGENSYSTEM eigensystem, const KLP_PARAMS klp_params, double timepoint, int start_index, int target_index) {
// This function is hard-wired to only consider the kinetics for folding from a distribution where p_{0}(start_index) == 1.
int i;
double cumulative_probability = 0;
if (klp_params.start_state < 0 || klp_params.end_state < 0) {
if (klp_params.start_state < 0) {
fprintf(stderr, "Error: the starting structure could not be found. Usually this means that you did not specify an explicit starting structure so the empty structure was used, but the energy band was not wide enough for RNAsubopt to sample it.\n");
}
if (klp_params.end_state < 0) {
fprintf(stderr, "Error: the ending structure could not be found. Usually this means that you did explicitly provided a suboptimal ending structure, but the energy band was not wide enough for RNAsubopt to sample it.\n");
}
abort();
}
for (i = 0; i < eigensystem.length; ++i) {
cumulative_probability +=
E_ROW_ORDER(eigensystem.vectors, target_index, i, eigensystem.length) *
E_ROW_ORDER(eigensystem.inverse_vectors, i, start_index, eigensystem.length) *
exp(eigensystem.values[i] * pow(10, timepoint));
}
return cumulative_probability;
}
void find_key_structure_indices_in_structure_list(KLP_PARAMS* klp_params, const POPULATION_PARAMS parameters, const SOLUTION* all_structures, int num_structures) {
int i;
for (i = 0; i < num_structures; ++i) {
if (klp_params->start_state == -1) {
if (!strcmp(parameters.start_structure, all_structures[i].structure)) {
klp_params->start_state = i;
}
}
if (klp_params->end_state == -1) {
if (!strcmp(parameters.end_structure, all_structures[i].structure)) {
klp_params->end_state = i;
}
}
}
}
void serialize_eigensystem(const EIGENSYSTEM eigensystem, const POPULATION_PARAMS parameters) {
tpl_node* tpl;
int i;
double value, vector, inverse_vector;
tpl = tpl_map("iA(f)A(f)A(f)", &eigensystem.length, &value, &vector, &inverse_vector);
tpl_pack(tpl, 0);
for (i = 0; i < eigensystem.length * eigensystem.length; ++i) {
if (i < eigensystem.length) {
value = eigensystem.values[i];
tpl_pack(tpl, 1);
}
vector = eigensystem.vectors[i];
inverse_vector = eigensystem.inverse_vectors[i];
tpl_pack(tpl, 2);
tpl_pack(tpl, 3);
}
tpl_dump(tpl, TPL_FILE, parameters.filename);
tpl_free(tpl);
}
EIGENSYSTEM deserialize_eigensystem(const POPULATION_PARAMS parameters) {
tpl_node* tpl;
int i, length;
double value, vector, inverse_vector;
EIGENSYSTEM eigensystem;
tpl = tpl_map("iA(f)A(f)A(f)", &length, &value, &vector, &inverse_vector);
tpl_load(tpl, TPL_FILE, parameters.filename);
tpl_unpack(tpl, 0);
eigensystem = init_eigensystem(length);
for (i = 0; i < eigensystem.length * eigensystem.length; ++i) {
if (i < eigensystem.length) {
tpl_unpack(tpl, 1);
eigensystem.values[i] = value;
}
tpl_unpack(tpl, 2);
tpl_unpack(tpl, 3);
eigensystem.vectors[i] = vector;
eigensystem.inverse_vectors[i] = inverse_vector;
}
tpl_free(tpl);
return eigensystem;
}
void ensure_key_structures_and_energies_assigned(POPULATION_PARAMS* parameters) {
int i, seq_length = strlen(parameters->sequence);
if (parameters->start_structure == NULL) {
parameters->start_structure = malloc((seq_length + 1) * sizeof(char));
for (i = 0; i < seq_length; ++i) {
parameters->start_structure[i] = '.';
}
parameters->start_structure[i] = '\0';
}
if (parameters->end_structure == NULL) {
set_end_structure(parameters);
}
}
void set_end_structure(POPULATION_PARAMS* parameters) {
paramT* vienna_params;
vienna_params = init_vienna_params(*parameters);
parameters->end_structure = malloc((strlen(parameters->sequence) + 1) * sizeof(char));
fold_par(parameters->sequence, parameters->end_structure, vienna_params, 0, 0);
}
SOLUTION* sample_structures(const POPULATION_PARAMS parameters) {
double energy_cap;
paramT* vienna_params;
vienna_params = init_vienna_params(parameters);
energy_cap = parameters.energy_cap ? (int)round(parameters.energy_cap * 100) : INF;
return subopt_par(parameters.sequence, parameters.start_structure, vienna_params, energy_cap, 0, 0, NULL);
}
double estimate_equilibrium(const EIGENSYSTEM eigensystem, const KLP_PARAMS klp_params, const POPULATION_PARAMS parameters, int eigensystem_index) {
int i, everything_in_equilibrium = 0;
double equilibrium_time;
equilibrium_time = soft_bound_for_population_proportion(eigensystem, klp_params, parameters, eigensystem_index, parameters.end_time, 1);
#ifdef INSANE_DEBUG
printf("equilibrium_time: %f\n", equilibrium_time);
#endif
while (equilibrium_time >= parameters.start_time && index_in_equilibrium_within_window(eigensystem, klp_params, parameters, eigensystem_index, equilibrium_time)) {
equilibrium_time -= parameters.step_size;
}
#ifdef INSANE_DEBUG
printf("equilibrium_time after backtrack: %f\n", equilibrium_time);
#endif
if (equilibrium_time < parameters.start_time) {
return NEG_INF(parameters);
} else {
while (equilibrium_time <= parameters.end_time) {
if (parameters.all_subpop_for_eq) {
everything_in_equilibrium = 1;
for (i = 0; i < eigensystem.length && everything_in_equilibrium; ++i) {
everything_in_equilibrium = index_in_equilibrium_within_window(eigensystem, klp_params, parameters, i, equilibrium_time);
}
} else {
everything_in_equilibrium = index_in_equilibrium_within_window(eigensystem, klp_params, parameters, eigensystem_index, equilibrium_time);
}
if (everything_in_equilibrium) {
return equilibrium_time;
} else {
equilibrium_time += parameters.step_size;
}
}
return POS_INF(parameters);
}
}
double soft_bound_for_population_proportion(const EIGENSYSTEM eigensystem, const KLP_PARAMS klp_params, const POPULATION_PARAMS parameters, int eigensystem_index, double final_time, int sign) {
double current_probability, final_probability, current_time, temp_time, last_time = final_time;
if (parameters.soft_bounds) {
last_time = final_time;
current_time = parameters.start_time + (parameters.end_time - parameters.start_time) / 2.0;
current_probability = probability_at_logtime(eigensystem, klp_params, current_time, klp_params.start_state, eigensystem_index);
final_probability = probability_at_logtime(eigensystem, klp_params, final_time, klp_params.start_state, eigensystem_index);
while (fabs(current_time - last_time) > parameters.step_size) {
current_probability = probability_at_logtime(eigensystem, klp_params, current_time, klp_params.start_state, eigensystem_index);
#ifdef INSANE_DEBUG
printf("current_time: %+.4f\tlast_time: %+.4f\tp(%d, current): %.4f\tp(%d, target): %.4f\n", current_time, last_time, eigensystem_index, current_probability, eigensystem_index, final_probability);
#endif
temp_time = current_time;
if (fabs(current_probability - final_probability) > parameters.delta) {
current_time += sign * fabs(last_time - current_time) / 2.0;
} else {
current_time -= sign * fabs(last_time - current_time) / 2.0;
}
last_time = temp_time;
}
#ifdef INSANE_DEBUG
printf("Bounded at %+f within %f of requested delta, %f\n\n", current_time, fabs(current_probability - final_probability), parameters.delta);
#endif
return round(current_time / parameters.step_size) * parameters.step_size;
} else {
return final_time;
}
}
int index_in_equilibrium_within_window(const EIGENSYSTEM eigensystem, const KLP_PARAMS klp_params, const POPULATION_PARAMS parameters, int eigensystem_index, double logtime) {
int i;
double current_proportion, future_proportion;
current_proportion = probability_at_logtime(
eigensystem,
klp_params,
logtime,
klp_params.start_state,
eigensystem_index
);
for (i = 1; i < parameters.window_size; ++i) {
future_proportion = probability_at_logtime(
eigensystem,
klp_params,
logtime + parameters.step_size * i,
klp_params.start_state,
eigensystem_index
);
#ifdef INSANE_DEBUG
printf(
"current_time: %f, window_time: %f, index: %d, abs(p(window) - p(current)): %e, within epsilon?: %s\n",
logtime,
logtime + parameters.step_size * i,
eigensystem_index,
fabs(current_proportion - future_proportion),
fabs(current_proportion - future_proportion) < parameters.epsilon ? "yes" : "no"
);
#endif
if (fabs(current_proportion - future_proportion) > parameters.epsilon) {
return 0;
}
}
return 1;
}
static int compare_tuple(const void* pa, const void* pb) {
const double* a = *(const double**)pa;
const double* b = *(const double**)pb;
if (a[0] > b[0]) {
return 1;
} else if (a[0] < b[0]) {
return -1;
} else {
return 0;
}
}
int* array_of_indices_to_output(const EIGENSYSTEM eigensystem, const KLP_PARAMS klp_params, const POPULATION_PARAMS parameters, double logtime) {
int i, output_size;
int* id_list;
double** final_proportions;
switch (parameters.num_subpop_to_show) {
case -1:
output_size = 2;
break;
case 0:
output_size = eigensystem.length;
break;
default:
output_size = parameters.num_subpop_to_show;
}
#ifdef INSANE_DEBUG
printf("number of subpopulations to output: %d\n", output_size);
#endif
id_list = malloc((output_size + 1) * sizeof(int));
id_list[0] = output_size;
if (parameters.num_subpop_to_show == -1) {
id_list[1] = klp_params.end_state;
id_list[2] = klp_params.start_state;
} else {
final_proportions = malloc(eigensystem.length * sizeof(double*));
for (i = 0; i < eigensystem.length; ++i) {
final_proportions[i] = malloc(2 * sizeof(double));
}
for (i = 0; i < eigensystem.length; ++i) {
final_proportions[i][0] = probability_at_logtime(eigensystem, klp_params, logtime, klp_params.start_state, i);
final_proportions[i][1] = i;
}
#ifdef INSANE_DEBUG
printf("\nBefore calling qsort:\n\n");
for (i = 0; i < eigensystem.length; ++i) {
printf("final_proportions[%d]\t%.8f\n", (int)final_proportions[i][1], final_proportions[i][0]);
}
#endif
qsort(final_proportions, eigensystem.length, sizeof(final_proportions[0]), compare_tuple);
#ifdef INSANE_DEBUG
printf("\nAfter calling qsort:\n\n");
for (i = 0; i < eigensystem.length; ++i) {
printf("final_proportions[%d]\t%.8f\n", (int)final_proportions[i][1], final_proportions[i][0]);
}
printf("\nIndices to keep:\n\n");
#endif
for (i = 1; i <= id_list[0]; ++i) {
id_list[i] = (int)final_proportions[eigensystem.length - i][1];
#ifdef INSANE_DEBUG
printf("final_proportions[%d]\t%.8f\n", id_list[i], final_proportions[eigensystem.length - i][0]);
#endif
}
}
return id_list;
}
void print_equilibrium(const EIGENSYSTEM eigensystem, const KLP_PARAMS klp_params, const POPULATION_PARAMS parameters) {
double soft_right_bound, equilibrium_time;
int i, list_length;
int* id_list;
soft_right_bound = soft_bound_for_population_proportion(eigensystem, klp_params, parameters, klp_params.end_state, parameters.end_time, 1);
id_list = array_of_indices_to_output(eigensystem, klp_params, parameters, soft_right_bound);
list_length = id_list++[0];
printf("index\tlogtime\n");
for (i = 0; i < list_length; ++i) {
equilibrium_time = estimate_equilibrium(eigensystem, klp_params, parameters, id_list[i]);
printf("%d\t", id_list[i]);
if (equilibrium_time == NEG_INF(parameters)) {
printf("-Infinity\n");
} else if (equilibrium_time == POS_INF(parameters)) {
printf("Infinity\n");
} else {
printf("%+.8f\n", equilibrium_time);
}
}
}
void print_population_proportion(const EIGENSYSTEM eigensystem, const KLP_PARAMS klp_params, const POPULATION_PARAMS parameters) {
double current_time, soft_left_bound, soft_right_bound;
int i, list_length;
int* id_list;
soft_left_bound = soft_bound_for_population_proportion(eigensystem, klp_params, parameters, klp_params.start_state, parameters.start_time, -1);
soft_right_bound = soft_bound_for_population_proportion(eigensystem, klp_params, parameters, klp_params.end_state, parameters.end_time, 1);
id_list = array_of_indices_to_output(eigensystem, klp_params, parameters, soft_right_bound);
list_length = id_list++[0];
printf("logtime\t");
for (i = 0; i < list_length; ++i) {
printf("%d\t", id_list[i]);
}
printf("\n");
for (current_time = soft_left_bound; current_time <= soft_right_bound; current_time += parameters.step_size) {
printf("%+.8f\t", current_time);
for (i = 0; i < list_length - 1; ++i) {
printf("%+.8f\t", probability_at_logtime(eigensystem, klp_params, current_time, klp_params.start_state, id_list[i]));
}
printf("%+.8f", probability_at_logtime(eigensystem, klp_params, current_time, klp_params.start_state, id_list[i]));
printf("\n");
}
}
void print_array(char* title, double* matrix, int length) {
int i;
printf("%s\n", title);
for (i = 0; i < length; ++i) {
printf("%+.4f\n", matrix[i]);
}
printf("\n");
}
void print_square_matrix(char* title, double* matrix, int length) {
int i, j;
printf("%s\n", title);
for (i = 0; i < length; ++i) {
for (j = 0; j < length; ++j) {
printf("%+.2e ", E_ROW_ORDER(matrix, i, j, length));
}
printf("\n");
}
printf("\n");
}
void print_eigenvalues(const EIGENSYSTEM eigensystem) {
int i;
for (i = 0; i < eigensystem.length; ++i) {
printf("%+.8f\n", eigensystem.values[i]);
}
}
| {
"alphanum_fraction": 0.6928353277,
"avg_line_length": 35.4131205674,
"ext": "c",
"hexsha": "72847042d30fc77feeab1b0544b4745cb3beecf8",
"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": "8ad3800f98fcfe7fb2e9f57cdf11b18cf781ac2d",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "evansenter/hermes",
"max_forks_repo_path": "src/population/c/population_functions.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "8ad3800f98fcfe7fb2e9f57cdf11b18cf781ac2d",
"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": "evansenter/hermes",
"max_issues_repo_path": "src/population/c/population_functions.c",
"max_line_length": 253,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "8ad3800f98fcfe7fb2e9f57cdf11b18cf781ac2d",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "evansenter/hermes",
"max_stars_repo_path": "src/population/c/population_functions.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 5194,
"size": 19973
} |
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <assert.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_integration.h>
#include <gsl/gsl_spline.h>
#include <gsl/gsl_sort.h>
#include <gsl/gsl_fit.h>
#include <gsl/gsl_roots.h>
#include "cosmocalc.h"
double fourierTransformTopHat(double y);
double tophatradnorm_linear_powspec_exact_nonorm_lnk_integ_funct_I0(double lnk, void *p);
double tophatradnorm_linear_powspec_exact_nonorm_k_integ_funct_I0(double k, void *p);
double convert_cmbnorm2sigma8_k_integ_funct_I0(double k, void *p)
{
//k is in units of 1/Mpc
//to get to units of h/Mpc
// k -> k/h
double ft = fourierTransformTopHat(k*8.0/cosmoData.h);
double tf = transfer_function(k/cosmoData.h);
/*
fprintf(stderr,"Tf^2 = %g, W(k)^2 = %g (2/5/OmegaM)^2 = %g (k/H0)^4/k = %g, nspow = %g\n",
tf*tf,ft*ft,4.0/25.0/cosmoData.OmegaM/cosmoData.OmegaM,
pow(k/100.0,4.0)/k,pow(k*cosmoData.h/cosmoData.As_pivot,cosmoData.SpectralIndex-1.0)
);
*/
return cosmoData.As*4.0/25.0/cosmoData.OmegaM/cosmoData.OmegaM
*pow(k/cosmoData.h*DH,4.0)/k*pow(k/cosmoData.As_pivot,cosmoData.SpectralIndex-1.0)
*ft*ft*tf*tf;
}
double convert_cmbnorm2sigma8(void)
{
double I0,I1;
double abserr;
double epsrel,epsabs;
gsl_integration_workspace *workspace;
gsl_function F;
#define WORKSPACE_NUM 10000000
#define ABSERR 1e-8
#define RELERR 0.0
workspace = gsl_integration_workspace_alloc((size_t) WORKSPACE_NUM);
epsabs = 1e-20;
epsrel = 1e-6;
F.function = &convert_cmbnorm2sigma8_k_integ_funct_I0;
gsl_integration_qags(&F,0.0,2.0*M_PI/8.0,epsabs,epsrel,(size_t) WORKSPACE_NUM,workspace,&I0,&abserr);
gsl_integration_qagiu(&F,2.0*M_PI/8.0,epsabs,epsrel,(size_t) WORKSPACE_NUM,workspace,&I1,&abserr);
gsl_integration_workspace_free(workspace);
#undef ABSERR
#undef RELERR
#undef WORKSPACE_NUM
//fprintf(stderr,"I0 = %g, I1 = %g, g = %g\n",I0,I1,growth_function_exact_nonorm(1.0));
return sqrt(I0 + I1)*growth_function_exact_nonorm(1.0);
}
double fourierTransformTopHat(double y)
{
if(y < 1e-3)
return 1.0;
else
return 3.0/y/y/y*(sin(y) - y*cos(y));
}
double tophatradnorm_linear_powspec_exact_nonorm_lnk_integ_funct_I0(double lnk, void *p)
{
// topHatRad = (*((double*)p));
double k = exp(lnk);
double ft = fourierTransformTopHat(k*(*((double*)p)));
double tf = transfer_function(k);
return ft*ft*tf*tf*pow(k,cosmoData.SpectralIndex)*k*k/2.0/M_PI/M_PI*k;
}
double tophatradnorm_linear_powspec_exact_nonorm_k_integ_funct_I0(double k, void *p)
{
// topHatRad = (*((double*)p));
double ft = fourierTransformTopHat(k*(*((double*)p)));
double tf = transfer_function(k);
return ft*ft*tf*tf*pow(k,cosmoData.SpectralIndex)*k*k/2.0/M_PI/M_PI;
}
double tophatradnorm_linear_powspec_exact_nonorm(double topHatRad)
{
double I0,I1;
double abserr;
double epsrel,epsabs;
gsl_integration_workspace *workspace;
gsl_function F;
#define WORKSPACE_NUM 10000000
#define ABSERR 1e-8
#define RELERR 0.0
workspace = gsl_integration_workspace_alloc((size_t) WORKSPACE_NUM);
F.params = &(topHatRad);
if(topHatRad > 1e-4)
{
epsabs = 1e-20;
epsrel = 1e-6;
F.function = &tophatradnorm_linear_powspec_exact_nonorm_k_integ_funct_I0;
gsl_integration_qags(&F,0.0,2.0*M_PI/topHatRad,epsabs,epsrel,(size_t) WORKSPACE_NUM,workspace,&I0,&abserr);
gsl_integration_qagiu(&F,2.0*M_PI/topHatRad,epsabs,epsrel,(size_t) WORKSPACE_NUM,workspace,&I1,&abserr);
}
else
{
F.function = &tophatradnorm_linear_powspec_exact_nonorm_lnk_integ_funct_I0;
gsl_integration_qagil(&F,log(2.0*M_PI/topHatRad),ABSERR,RELERR,(size_t) WORKSPACE_NUM,workspace,&I0,&abserr);
gsl_integration_qagiu(&F,log(2.0*M_PI/topHatRad),ABSERR,RELERR,(size_t) WORKSPACE_NUM,workspace,&I1,&abserr);
}
gsl_integration_workspace_free(workspace);
#undef ABSERR
#undef RELERR
#undef WORKSPACE_NUM
return I0 + I1;
}
double linear_powspec_exact(double k, double a)
{
static int initFlag = 1;
static int currCosmoNum;
static double linear_powspec_norm = 1.0;
double gf = growth_function(a);
double tf = transfer_function(k);
if(initFlag == 1 || currCosmoNum != cosmoData.cosmoNum)
{
initFlag = 0;
currCosmoNum = cosmoData.cosmoNum;
linear_powspec_norm = cosmoData.Sigma8*cosmoData.Sigma8/tophatradnorm_linear_powspec_exact_nonorm(8.0);
}
return tf*tf*pow(k,cosmoData.SpectralIndex)*gf*gf*linear_powspec_norm;
}
double linear_powspec(double k, double a)
{
static int initFlag = 1;
static int currCosmoNum;
static double linear_powspec_norm = 1.0;
static gsl_spline *cosmocalc_linear_powspec_spline = NULL;
static gsl_interp_accel *cosmocalc_linear_powspec_acc = NULL;
static double c0,c1;
double linear_powspec_table[COSMOCALC_LINEAR_POWSPEC_TABLE_LENGTH];
double k_table[COSMOCALC_LINEAR_POWSPEC_TABLE_LENGTH];
long i;
double gf,cov00,cov01,cov11,sumsq,tf;
if(initFlag == 1 || currCosmoNum != cosmoData.cosmoNum)
{
initFlag = 0;
currCosmoNum = cosmoData.cosmoNum;
for(i=0;i<COSMOCALC_LINEAR_POWSPEC_TABLE_LENGTH;++i)
{
k_table[i] = log(K_MAX/K_MIN)/(COSMOCALC_LINEAR_POWSPEC_TABLE_LENGTH-1.0)*((double) i) + log(K_MIN);
tf = transfer_function(exp(k_table[i]));
linear_powspec_table[i] = log(tf*tf*pow(exp(k_table[i]),cosmoData.SpectralIndex));
}
//init the spline and accelerators
if(cosmocalc_linear_powspec_spline != NULL)
gsl_spline_free(cosmocalc_linear_powspec_spline);
cosmocalc_linear_powspec_spline = gsl_spline_alloc(GSL_SPLINE_TYPE,(size_t) (COSMOCALC_LINEAR_POWSPEC_TABLE_LENGTH));
gsl_spline_init(cosmocalc_linear_powspec_spline,k_table,linear_powspec_table,(size_t) (COSMOCALC_LINEAR_POWSPEC_TABLE_LENGTH));
if(cosmocalc_linear_powspec_acc != NULL)
gsl_interp_accel_reset(cosmocalc_linear_powspec_acc);
else
cosmocalc_linear_powspec_acc = gsl_interp_accel_alloc();
gsl_fit_linear(k_table+COSMOCALC_LINEAR_POWSPEC_TABLE_LENGTH-COSMOCALC_LINEAR_POWSPEC_FIT_LENGTH,(size_t) 1,
linear_powspec_table+COSMOCALC_LINEAR_POWSPEC_TABLE_LENGTH-COSMOCALC_LINEAR_POWSPEC_FIT_LENGTH,(size_t) 1,
(size_t) COSMOCALC_LINEAR_POWSPEC_FIT_LENGTH,&c0,&c1,&cov00,&cov01,&cov11,&sumsq);
linear_powspec_norm = cosmoData.Sigma8*cosmoData.Sigma8/tophatradnorm_linear_powspec_exact_nonorm(8.0);
}
gf = growth_function(a);
if(k < K_MIN)
{
tf = transfer_function(k);
return tf*tf*pow(k,cosmoData.SpectralIndex)*linear_powspec_norm*gf*gf;
}
else if(k < K_MAX)
return exp(gsl_spline_eval(cosmocalc_linear_powspec_spline,log(k),cosmocalc_linear_powspec_acc))*linear_powspec_norm*gf*gf;
else
return exp(c0+c1*log(k))*linear_powspec_norm*gf*gf;
}
double tophatnorm_linear_powspec(double topHatRad)
{
#define NL_RTOPHAT_MIN 0.0001
#define NL_RTOPHAT_MAX 100.0
#define WORKSPACE_NUM 10000000
#define ABSERR 1e-8
#define RELERR 0.0
static int initFlag = 1;
static int currCosmoNum;
static gsl_spline *spline = NULL;
static gsl_interp_accel *accel = NULL;
static double linear_powspec_norm;
double I0,I1;
double abserr,epsabs,epsrel;
gsl_integration_workspace *workspace;
gsl_function F;
int i;
double xtab[COSMOCALC_LINEAR_POWSPEC_NORM_TABLE_LENGTH];
double ytab[COSMOCALC_LINEAR_POWSPEC_NORM_TABLE_LENGTH];
double dlnr;
double lnrmin;
double lnr;
if(initFlag == 1 || currCosmoNum != cosmoData.cosmoNum)
{
initFlag = 0;
currCosmoNum = cosmoData.cosmoNum;
workspace = gsl_integration_workspace_alloc((size_t) WORKSPACE_NUM);
dlnr = log(NL_RTOPHAT_MAX/NL_RTOPHAT_MIN)/(COSMOCALC_LINEAR_POWSPEC_NORM_TABLE_LENGTH-1.0);
lnrmin = log(NL_RTOPHAT_MIN);
for(i=0;i<COSMOCALC_LINEAR_POWSPEC_NORM_TABLE_LENGTH;++i)
{
lnr = dlnr*i + lnrmin;
xtab[i] = exp(lnr);
F.params = &(xtab[i]);
if(topHatRad > 1e-4)
{
epsabs = 1e-20;
epsrel = 1e-6;
F.function = &tophatradnorm_linear_powspec_exact_nonorm_k_integ_funct_I0;
gsl_integration_qags(&F,0.0,2.0*M_PI/topHatRad,epsabs,epsrel,(size_t) WORKSPACE_NUM,workspace,&I0,&abserr);
gsl_integration_qagiu(&F,2.0*M_PI/topHatRad,epsabs,epsrel,(size_t) WORKSPACE_NUM,workspace,&I1,&abserr);
}
else
{
F.function = &tophatradnorm_linear_powspec_exact_nonorm_lnk_integ_funct_I0;
gsl_integration_qagil(&F,log(2.0*M_PI/topHatRad),ABSERR,RELERR,(size_t) WORKSPACE_NUM,workspace,&I0,&abserr);
gsl_integration_qagiu(&F,log(2.0*M_PI/topHatRad),ABSERR,RELERR,(size_t) WORKSPACE_NUM,workspace,&I1,&abserr);
}
xtab[i] = lnr;
ytab[i] = log(I0+I1);
}
gsl_integration_workspace_free(workspace);
if(spline != NULL)
gsl_spline_free(spline);
spline = gsl_spline_alloc(GSL_SPLINE_TYPE,(size_t) (COSMOCALC_LINEAR_POWSPEC_NORM_TABLE_LENGTH));
gsl_spline_init(spline,xtab,ytab,(size_t) (COSMOCALC_LINEAR_POWSPEC_NORM_TABLE_LENGTH));
if(accel != NULL)
gsl_interp_accel_reset(accel);
else
accel = gsl_interp_accel_alloc();
linear_powspec_norm = cosmoData.Sigma8*cosmoData.Sigma8/exp(gsl_spline_eval(spline,log(8.0),accel));
#undef ABSERR
#undef RELERR
#undef WORKSPACE_NUM
#undef NL_RTOPHAT_MIN
#undef NL_RTOPHAT_MAX
}
return exp(gsl_spline_eval(spline,log(topHatRad),accel))*linear_powspec_norm;
}
double linear_tophatnorm_scale_funct(double rad, void *p)
{
double gf = ((double*)p)[0];
return tophatnorm_linear_powspec(rad)*gf*gf-1.0;
}
double get_linear_tophatnorm_scale(double a)
{
double gf = growth_function(a);
double Rsigma,Rlow=0.001,Rhigh=10.0;
int itr,maxItr=1000,status;
//fprintf(stderr,"sigma2(Rlow) = %f, sigma2(Rhigh) = %f\n",tophatnorm_linear_powspec(Rlow)*gf*gf,tophatnorm_linear_powspec(Rhigh)*gf*gf);
#define ABSERR 1e-6
#define RELERR 1e-6
const gsl_root_fsolver_type *T;
gsl_root_fsolver *s;
gsl_function F;
F.function = &linear_tophatnorm_scale_funct;
F.params = &gf;
T = gsl_root_fsolver_brent;
s = gsl_root_fsolver_alloc(T);
gsl_root_fsolver_set(s,&F,Rlow,Rhigh);
itr = 0;
do
{
itr++;
status = gsl_root_fsolver_iterate(s);
Rsigma = gsl_root_fsolver_root(s);
Rlow = gsl_root_fsolver_x_lower(s);
Rhigh = gsl_root_fsolver_x_upper(s);
status = gsl_root_test_interval(Rlow,Rhigh,ABSERR,RELERR);
}
while(status == GSL_CONTINUE && itr < maxItr);
#undef ABSERR
#undef RELERR
gsl_root_fsolver_free(s);
return Rsigma;
}
| {
"alphanum_fraction": 0.7338026829,
"avg_line_length": 31.5645645646,
"ext": "c",
"hexsha": "fbc0b3aa1b2ef39474d0f79a87bf8ec0576f142b",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2017-08-11T17:31:51.000Z",
"max_forks_repo_forks_event_min_datetime": "2017-07-14T12:17:31.000Z",
"max_forks_repo_head_hexsha": "aa7d7cb58f05a36d446e02b45a9117d93eb16556",
"max_forks_repo_licenses": [
"Unlicense"
],
"max_forks_repo_name": "beckermr/cosmocalc",
"max_forks_repo_path": "src/linear_powspec.c",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "aa7d7cb58f05a36d446e02b45a9117d93eb16556",
"max_issues_repo_issues_event_max_datetime": "2016-04-05T19:36:21.000Z",
"max_issues_repo_issues_event_min_datetime": "2016-04-05T19:10:45.000Z",
"max_issues_repo_licenses": [
"Unlicense"
],
"max_issues_repo_name": "beckermr/cosmocalc",
"max_issues_repo_path": "src/linear_powspec.c",
"max_line_length": 139,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "aa7d7cb58f05a36d446e02b45a9117d93eb16556",
"max_stars_repo_licenses": [
"Unlicense"
],
"max_stars_repo_name": "beckermr/cosmocalc",
"max_stars_repo_path": "src/linear_powspec.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 3462,
"size": 10511
} |
#include <stdio.h>
#include <gsl/gsl_combination.h>
int
main (void)
{
gsl_combination * c;
size_t i;
printf ("All subsets of {0,1,2,3} by size:\n") ;
for (i = 0; i <= 4; i++)
{
c = gsl_combination_calloc (4, i);
do
{
printf ("{");
gsl_combination_fprintf (stdout, c, " %u");
printf (" }\n");
}
while (gsl_combination_next (c) == GSL_SUCCESS);
gsl_combination_free (c);
}
return 0;
}
| {
"alphanum_fraction": 0.5168067227,
"avg_line_length": 18.3076923077,
"ext": "c",
"hexsha": "708174ffa36ad15e9b8248112230dff87171e2ad",
"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/combination.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/combination.c",
"max_line_length": 54,
"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/combination.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": 150,
"size": 476
} |
/*************************************************************
Generalized-ICP Copyright (c) 2009 Aleksandr Segal.
All rights reserved.
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.
* The names of the contributors may not 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 OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
DAMAGE.
*************************************************************/
#ifndef GICP_H_
#define GICP_H_
#include <ANN.h>
#include <vector>
#include <iostream>
//#include <gsl/gsl.h>
#include <semaphore.h>
#include "transform.h"
namespace dgc {
namespace gicp {
typedef double gicp_mat_t[3][3];
struct GICPPoint {
double x, y, z;
float range;
gicp_mat_t C; // covariance matrix
};
class GICPPointSet {
public:
GICPPointSet();
~GICPPointSet();
void BuildKDTree();
void ComputeMatrices();
void SavePoints(const char *filename);
void SaveMatrices(const char *filename);
int NumPoints() { return (int)point_.size(); }
void Clear(void);
int Size() { return point_.size(); }
inline void AppendPoint(GICPPoint const & pt) { point_.push_back(pt); }
void SetMaxIteration(int iter) { max_iteration_ = iter; }
void SetMaxIterationInner(int iter) { max_iteration_inner_ = iter; }
void SetEpsilon(double eps) { epsilon_ = eps; }
void SetSolveRotation(bool s) { solve_rotation_ = s; }
void SetGICPEpsilon(double eps) { gicp_epsilon_ = eps; }
void SetDebug(bool d) { debug_ = d; }
GICPPoint & operator[](int i) { return point_[i]; }
GICPPoint const& operator[](int i) const { return point_[i]; }
// returns number of iterations it took to converge
int AlignScan(GICPPointSet *scan, dgc_transform_t base_t, dgc_transform_t t, double max_match_dist, bool save_error_plot = 0);
private:
std::vector <GICPPoint> point_;
ANNpointArray kdtree_points_;
ANNkd_tree *kdtree_;
int max_iteration_;
int max_iteration_inner_;
double epsilon_;
double epsilon_rot_;
double gicp_epsilon_;
bool debug_;
bool solve_rotation_;
bool matrices_done_;
bool kdtree_done_;
pthread_mutex_t mutex_;
};
}
}
#endif
| {
"alphanum_fraction": 0.7076333628,
"avg_line_length": 31.4166666667,
"ext": "h",
"hexsha": "c68ac123121fdd9d8a47f985ff818e50cc7dc06d",
"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": "48941767c1dddec514c0fe16b222d379d866cc53",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "raandoom/gicp",
"max_forks_repo_path": "gicp.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "48941767c1dddec514c0fe16b222d379d866cc53",
"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": "raandoom/gicp",
"max_issues_repo_path": "gicp.h",
"max_line_length": 130,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "48941767c1dddec514c0fe16b222d379d866cc53",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "raandoom/gicp",
"max_stars_repo_path": "gicp.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 801,
"size": 3393
} |
#include <stdio.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
void mcmc
(
int &mcID,
int &seed,
int &imh,
int &vmh,
int &neighborPast,
int &n_neighbor,
int &ptAccpt,
double &pllh,
double *jump,
struct FXP &fxp,
struct PAR &par_a,
struct PAR &par_c,
struct RND &rnd,
struct VAR &var,
struct DATA &data,
struct DIAG &diag,
struct HIST &hist,
struct INCV &incv,
struct POST &post,
struct PRED &pred,
gsl_rng *rng,
FILE *outp
);
void logQuasiposterior
(
//=======================================================
double &llh,
struct FXP &fxp,
struct PAR &par,
struct RND &rnd,
struct VAR &var,
struct DATA &data,
struct DIAG &diag,
struct INCV &incv,
struct PRED &pred
//=======================================================
);
void logQuasiposterior
(
//=======================================================
double &llh,
double *expDeltaIn,
struct PAR &par,
struct VAR &var
//=======================================================
);
void rollbackTest
(
int &imh,
int &vmh,
int &n_neighbor,
int &neighborPast,
double &pllh,
double &pllhbackup,
struct FXP &fxp,
struct PAR &par,
struct VAR &var,
struct DATA &data,
struct DIAG &diag,
struct HIST &hist,
struct INCV &incv,
struct PRED &pred
);
| {
"alphanum_fraction": 0.5583796664,
"avg_line_length": 17.2465753425,
"ext": "h",
"hexsha": "856facd354ff82bf17e129816e5ed19b498bfc41",
"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": "b3c52e19600faefc8ec853f0d2bd18f2293e2897",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "foolish3/DDCM",
"max_forks_repo_path": "PFP/mcmc.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "b3c52e19600faefc8ec853f0d2bd18f2293e2897",
"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": "foolish3/DDCM",
"max_issues_repo_path": "PFP/mcmc.h",
"max_line_length": 58,
"max_stars_count": 4,
"max_stars_repo_head_hexsha": "b3c52e19600faefc8ec853f0d2bd18f2293e2897",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "foolish3/DDCM",
"max_stars_repo_path": "PFP/mcmc.h",
"max_stars_repo_stars_event_max_datetime": "2020-05-04T03:26:32.000Z",
"max_stars_repo_stars_event_min_datetime": "2018-10-29T04:59:03.000Z",
"num_tokens": 333,
"size": 1259
} |
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <iniparser.h>
#include "prepmt/prepmt_hudson96.h"
#ifdef PARMT_USE_INTEL
#include <mkl_cblas.h>
#else
#include <cblas.h>
#endif
#include "cps.h"
#include "iscl/array/array.h"
#include "iscl/fft/fft.h"
#include "iscl/memory/memory.h"
#include "iscl/os/os.h"
/*!
* @brief Reads the ini file for Computer Programs in Seismology hudson96
* forward modeling variables.
*
* @param[in] iniFile Name of ini file.
* @param[in] section Section of ini file to read.
*
* @param[out] parms The hudson96 parameters.
*
* @result 0 indicates success.
*
* @author Ben Baker, ISTI
*
*/
int prepmt_hudson96_readHudson96Parameters(const char *iniFile,
const char *section,
struct hudson96_parms_struct *parms)
{
const char *s;
char vname[256];
dictionary *ini;
//------------------------------------------------------------------------//
cps_setHudson96Defaults(parms);
if (!os_path_isfile(iniFile))
{
fprintf(stderr, "%s: ini file: %s does not exist\n", __func__, iniFile);
return -1;
}
ini = iniparser_load(iniFile);
if (ini == NULL)
{
fprintf(stderr, "%s: Cannot parse ini file\n", __func__);
return -1;
}
// Teleseismic model
memset(vname, 0, 256*sizeof(char));
sprintf(vname, "%s:modeltel", section);
s = iniparser_getstring(ini, vname, NULL);
if (s != NULL)
{
strcpy(parms->modeltel, s);
}
else
{
strcpy(parms->modeltel, "tak135sph.mod\0");
}
// Receiver model
memset(vname, 0, 256*sizeof(char));
sprintf(vname, "%s:modelrec", section);
s = iniparser_getstring(ini, vname, NULL);
if (s != NULL)
{
strcpy(parms->modelrec, s);
}
else
{
strcpy(parms->modelrec, parms->modelrec);
}
// Source model
memset(vname, 0, 256*sizeof(char));
sprintf(vname, "%s:modelsrc", section);
s = iniparser_getstring(ini, vname, NULL);
if (s != NULL)
{
strcpy(parms->modelsrc, s);
}
else
{
strcpy(parms->modelsrc, parms->modelsrc);
}
memset(vname, 0, 256*sizeof(char));
sprintf(vname, "%s:hs", section);
parms->hs = iniparser_getdouble(ini, vname, 0.0);
memset(vname, 0, 256*sizeof(char));
sprintf(vname, "%s:dt", section);
parms->dt = iniparser_getdouble(ini, vname, 1.0);
memset(vname, 0, 256*sizeof(char));
sprintf(vname, "%s:npts", section);
parms->npts = iniparser_getint(ini, vname, 1024);
memset(vname, 0, 256*sizeof(char));
sprintf(vname, "%s:gcarc", section);
parms->gcarc = iniparser_getdouble(ini, vname, 50.0);
memset(vname, 0, 256*sizeof(char));
sprintf(vname, "%s:offset", section);
parms->offset = iniparser_getdouble(ini, vname, 10.0);
memset(vname, 0, 256*sizeof(char));
sprintf(vname, "%s:dosrc", section);
parms->dosrc = iniparser_getboolean(ini, vname, 1);
memset(vname, 0, 256*sizeof(char));
sprintf(vname, "%s:dorec", section);
parms->dorec = iniparser_getboolean(ini, vname, 1);
memset(vname, 0, 256*sizeof(char));
sprintf(vname, "%s:dotel", section);
parms->dotel = iniparser_getboolean(ini, vname, 1);
memset(vname, 0, 256*sizeof(char));
sprintf(vname, "%s:dop", section);
parms->dop = iniparser_getboolean(ini, vname, 1);
memset(vname, 0, 256*sizeof(char));
sprintf(vname, "%s:dokjar", section);
parms->dokjar = iniparser_getboolean(ini, vname, 1);
memset(vname, 0, 256*sizeof(char));
sprintf(vname, "%s:loffsetdefault", section);
parms->loffsetdefault = iniparser_getboolean(ini, vname, 1);
memset(vname, 0, 256*sizeof(char));
sprintf(vname, "%s:verbose", section);
parms->verbose = iniparser_getboolean(ini, vname, 0);
memset(vname, 0, 256*sizeof(char));
sprintf(vname, "%s:utstar", section);
parms->utstar = iniparser_getdouble(ini, vname, -12345.0);
memset(vname, 0, 256*sizeof(char));
sprintf(vname, "%s:dottonly", section);
parms->dottonly = iniparser_getboolean(ini, vname, 0);
memset(vname, 0, 256*sizeof(char));
sprintf(vname, "%s:zsrc", section);
parms->zsrc = iniparser_getdouble(ini, vname, 100.0);
memset(vname, 0, 256*sizeof(char));
sprintf(vname, "%s:zrec", section);
parms->zrec = iniparser_getdouble(ini, vname, 60.0);
// Free ini dictionary
iniparser_freedict(ini);
return 0;
}
//============================================================================//
/*!
* @brief Computes the fundamental fault Green's functions for the teleseismic
* body waves with hudson96.
*
* @param[in] nobs Number of observations.
* @param[in] obs Observations with source location and
* receiver location. This is an array of length
* nobs.
* @param[in] luseCrust1 If true then use crust1.0 models at source
* and receiver.
* @param[in] crust1Dir If luseCrust1 is true then this is the name
* of the crust1.0 directory. If NULL and
* luseCrust1 is used then it will default to
* libcps configuration.
* @param[in] luseSrcModel If true then use the local source velocity
* at the source. This supersedes the crust1.0
* source velocity if it is defined.
* @param[in] sourceModel If luseSrcModel is true then this is the name
* of the CPS style source model to read.
*
* @param[out] telmod Holds the teleseismic model (ak135).
* @param[out] srcmod Holds the local source model.
* @param[in,out] recmod On input contains sufficient space and should
* be an array of length nobs.
* On output holds the receiver models.
*
* @param[out] ierr 0 indicates success.
*
* @author Ben Baker, ISTI
*
* @bug I need better handling of the offset.
*
*/
int hudson96_getModels(const int nobs, const struct sacData_struct *obs,
const bool luseCrust1, const char *crust1Dir,
const bool luseSrcModel, const char *sourceModel,
struct vmodel_struct *telmod,
struct vmodel_struct *srcmod,
struct vmodel_struct *recmod)
{
double *lats, *lons, evla, evlo;
int ierr, iobs;
ierr = 0;
// Set the teleseismic model
memset(srcmod, 0, sizeof(struct vmodel_struct));
memset(telmod, 0, sizeof(struct vmodel_struct));
cps_globalModel_ak135f(telmod);
if (luseCrust1)
{
fprintf(stdout, "%s: Reading crust1.0...\n", __func__);
lats = memory_calloc64f(nobs);
lons = memory_calloc64f(nobs);
ierr = sacio_getFloatHeader(SAC_FLOAT_EVLA, obs[0].header, &evla);
if (ierr != 0)
{
fprintf(stderr, "%s: Error - evla not set\n", __func__);
return ierr;
}
ierr = sacio_getFloatHeader(SAC_FLOAT_EVLO, obs[0].header, &evlo);
if (ierr != 0)
{
fprintf(stderr, "%s: Error - evlo not set\n", __func__);
return ierr;
}
for (iobs=0; iobs<nobs; iobs++)
{
sacio_getFloatHeader(SAC_FLOAT_STLA, obs[iobs].header,
&lats[iobs]);
sacio_getFloatHeader(SAC_FLOAT_STLO, obs[iobs].header,
&lons[iobs]);
}
ierr = cps_crust1_getCrust1ForHerrmann(crust1Dir, false,
evla, evlo,
lats, lons,
nobs,
srcmod, recmod);
if (ierr != 0)
{
fprintf(stderr, "%s: Failed to load crust1.0 model\n", __func__);
return ierr;
}
memory_free64f(&lats);
memory_free64f(&lons);
}
// Use teleseismic model for receiver model
else
{
fprintf(stdout, "%s: Setting receiver models to teleseismic model\n",
__func__);
for (iobs=0; iobs<nobs; iobs++)
{
cps_utils_copyVmodelStruct(*telmod, &recmod[iobs]);
}
}
// Use source model
if (luseSrcModel)
{
fprintf(stdout, "%s: Using source model: %s\n", __func__, sourceModel);
cps_utils_freeVmodelStruct(srcmod);
ierr = cps_getmod(sourceModel, srcmod);
if (ierr != 0)
{
fprintf(stderr, "%s: Error loading srcmod\n", __func__);
return ierr;
}
}
fprintf(stdout, "%s: Computing Green's functions...\n", __func__);
// Otherwise source to teleseismic model
if (!luseSrcModel && !luseCrust1)
{
fprintf(stdout, "%s: Setting source model to teleseismic model\n",
__func__);
cps_utils_copyVmodelStruct(*telmod, srcmod);
}
return 0;
}
//============================================================================//
/*!
* @brief Computes the fundamental fault Green's functions for the teleseismic
* body waves with hudson96.
*
* @param[in] hudson96Parms hudson96 forward modeling parameters.
* @param[in] hpulse96Parms hpulse96 forward modeling parameters.
* @param[in] telmod Holds the teleseismic model (ak135).
* @param[in] srcmod Holds the local source model.
* @param[in] recmod Holds each receiver model.
* This is an array of dimension [nobs].
* @param[in] ntstar Number of t*'s in grid.
* @param[in] tstars Array of dimension [ntstar] with the attenuation
* factors.
* @param[in] ndepth Number of source depths in grid.
* @param[in] depths Array of dimension [ndepth] with the source
* depths specified in (km).
* @param[in] nobs Number of observations.
* @param[in] obs Observed waveforms which contain the receiver
* locations, components of motion, first
* arrival time, sampling period, and number of
* points in waveform.
*
* @param[out] ierr 0 indicates success.
*
* @author Ben Baker, ISTI
*
* @bug I need better handling of the offset.
*
*/
struct sacData_struct *prepmt_hudson96_computeGreensFF(
const struct hudson96_parms_struct hudson96Parms,
const struct hpulse96_parms_struct hpulse96Parms,
const struct vmodel_struct telmod,
const struct vmodel_struct srcmod,
const struct vmodel_struct *recmod,
const int ntstar, const double *__restrict__ tstars,
const int ndepth, const double *__restrict__ depths,
const int nobs, const struct sacData_struct *obs, int *ierr)
{
struct hudson96_parms_struct hudson96ParmsWork;
struct hpulse96_parms_struct hpulse96ParmsWork;
struct hpulse96_data_struct zresp;
struct sacData_struct *sacFFGrns;
struct hwave_greens_struct *ffGrns;
char sncl[64], phaseName[8];
double *dptr, cmpaz, cmpinc, dt, gcarc, offset0,
pickTime, xnorm;
int i, idep, ierrAll, ierr1, ierr2, indx, iobs, iobs0, ip, it,
factor, kndx, nloop, npts;
bool lzero[10], lfound, lsh;
enum isclError_enum isclError;
const enum sacHeader_enum pickVars[11]
= {SAC_FLOAT_A,
SAC_FLOAT_T0, SAC_FLOAT_T1, SAC_FLOAT_T2, SAC_FLOAT_T3,
SAC_FLOAT_T4, SAC_FLOAT_T5, SAC_FLOAT_T6, SAC_FLOAT_T7,
SAC_FLOAT_T8, SAC_FLOAT_T9};
const enum sacHeader_enum pickTypes[11]
= {SAC_CHAR_KA,
SAC_CHAR_KT0, SAC_CHAR_KT1, SAC_CHAR_KT2, SAC_CHAR_KT3,
SAC_CHAR_KT4, SAC_CHAR_KT5, SAC_CHAR_KT6, SAC_CHAR_KT7,
SAC_CHAR_KT8, SAC_CHAR_KT9};
// Here's the idea: I want to input magnitudes with units of N-m so:
// N-m -> Dyne-dm (1.e+7)
// CPS internally scales from Dyne-cm to cm (1.e+20)
// Finally, I want outputs proprotional to m (1.e-2)
const double xmom = 1.0; // no confusing `relative' magnitudes
const double xcps = 1.e-20; // convert dyne-cm mt to output cm
const double cm2m = 1.e-2; // cm to meters
const double dcm2nm = 1.e+7; // magnitudes intended to be specified in
// Dyne-cm but I work in N-m
// Given a M0 in Newton-meters get a seismogram in meters
const double xscal = xmom*xcps*cm2m*dcm2nm;
const char *cfaults[10] = {"ZDS\0", "ZSS\0", "ZDD", "ZEX\0",
"RDS\0", "RSS\0", "RDD", "REX\0",
"TDS\0", "TSS\0"};
const int npTypes = 11;
const int nrDist = 1;
const int nrDepths = 1;
const int nsDepths = 1;
//------------------------------------------------------------------------//
//
// Quick error checks
*ierr = 0;
sacFFGrns = NULL;
if (nobs < 1 || obs == NULL ||
ntstar < 1 || tstars == NULL ||
ndepth < 1 || depths == NULL)
{
*ierr = 1;
if (nobs < 1){fprintf(stderr, "%s: Error no observations\n", __func__);}
if (obs == NULL){fprintf(stderr, "%s: Error obs is NULL\n", __func__);}
if (ntstar < 1){fprintf(stderr, "%s: Error no t*'s\n", __func__);}
if (tstars == NULL)
{
fprintf(stderr, "%s: Error tstars is NULL\n", __func__);
}
if (ndepth < 1){fprintf(stderr, "%s: Error no depths\n", __func__);}
if (depths == NULL)
{
fprintf(stderr, "%s: Error depths is NULL\n", __func__);
}
return sacFFGrns;
}
// Set the modeling structures
memset(&hudson96ParmsWork, 0, sizeof(struct hudson96_parms_struct));
memset(&hpulse96ParmsWork, 0, sizeof(struct hpulse96_parms_struct));
cps_setHudson96Defaults(&hudson96ParmsWork);
cps_setHpulse96Defaults(&hpulse96ParmsWork);
cps_utils_copyHudson96ParmsStruct(hudson96Parms, &hudson96ParmsWork);
cps_utils_copyHpulse96ParmsStruct(hpulse96Parms, &hpulse96ParmsWork);
offset0 = hudson96Parms.offset;
// Set space for output
nloop = nobs*ndepth*ntstar;
sacFFGrns = (struct sacData_struct *)
calloc((size_t) (10*nloop), sizeof(struct sacData_struct));
// Loop on the distances, depths, t*'s and compute greens functions
iobs0 =-1;
ierrAll = 0;
for (indx=0; indx<nloop; indx++)
{
ffGrns = NULL;
// Convert 3D grid into loop indices (i->n1 is fast; k->n3 is slow)
*ierr = prepmt_hudson96_grd2ijk(indx,
ntstar, ndepth, nobs,
&it, &idep, &iobs);
if (*ierr != 0)
{
fprintf(stderr, "%s: Failed to convert to grid\n", __func__);
break;
}
// New observation (station) -> may need to update velocity model
if (iobs != iobs0)
{
iobs0 = iobs;
}
*ierr = sacio_getFloatHeader(SAC_FLOAT_DELTA,
obs[iobs].header, &dt);
if (*ierr != 0)
{
fprintf(stderr, "%s: Could not get sampling period\n", __func__);
break;
}
*ierr = sacio_getFloatHeader(SAC_FLOAT_GCARC,
obs[iobs].header, &gcarc);
if (*ierr != 0)
{
fprintf(stderr, "%s: Could not get gcarc\n", __func__);
break;
}
*ierr = sacio_getIntegerHeader(SAC_INT_NPTS,
obs[iobs].header, &npts);
if (*ierr != 0)
{
fprintf(stderr, "%s: Could not get npts\n", __func__);
break;
}
// Tie waveform modeling to first pick type
lfound = false;
hudson96ParmsWork.dop = true;
for (ip=0; ip<npTypes; ip++)
{
ierr1 = sacio_getCharacterHeader(pickTypes[ip],
obs[iobs].header, phaseName);
ierr2 = sacio_getFloatHeader(pickVars[ip],
obs[iobs].header, &pickTime);
if (ierr1 == 0 && ierr2 == 0)
{
lfound = true;
if (strncasecmp(phaseName, "P", 1) == 0)
{
hudson96ParmsWork.dop = true;
}
else if (strncasecmp(phaseName, "S", 1) == 0)
{
hudson96ParmsWork.dop = false;
}
else
{
fprintf(stderr, "%s: Can't classify phase: %s\n",
__func__, phaseName);
lfound = false;
}
break;
}
}
if (!lfound)
{
fprintf(stdout, "%s: No pick available - won't be able to align\n",
__func__);
continue;
}
memset(&zresp, 0, sizeof(struct hpulse96_data_struct));
hudson96ParmsWork.hs = depths[idep];
hudson96ParmsWork.dt = dt;
hudson96ParmsWork.gcarc = gcarc;
hudson96ParmsWork.utstar = tstars[it];
factor = 2;
if (hudson96ParmsWork.dt < 0.1){factor = 4;}
hudson96ParmsWork.npts = MAX(256,
MIN(2048,
factor*fft_nextpow2(MAX(1, npts), ierr)));
hudson96ParmsWork.offset = fmin(pickTime, offset0); //TODO: fmin or fmax?
//printf("%s %f\n", phaseName, pickTime);
// Try to pad this out a little
hudson96ParmsWork.offset = fmax(hudson96ParmsWork.offset,
(double) (hudson96ParmsWork.npts - 1)*dt*0.2);
// printf("%e %d\n", hudson96ParmsWork.offset/dt, npts);
/*
if (pickTime < hudson96ParmsWork.offset)
{
hudson96ParmsWork.offset = (double) (int) (pickTime/dt + 0.5)*dt;
}
*/
zresp = hudson96_interface(hudson96ParmsWork,
telmod, recmod[iobs], srcmod, ierr);
if (*ierr != 0)
{
fprintf(stderr, "%s: Error calling hudson96\n", __func__);
ierrAll = ierrAll + 1;
goto NEXT_OBS;
}
ffGrns = hpulse96_interface(nrDist, nrDepths, nsDepths,
hpulse96ParmsWork,
&zresp, ierr);
if (*ierr != 0)
{
fprintf(stderr, "%s: Error calling hpulse96 interface\n", __func__);
ierrAll = ierrAll + 1;
goto NEXT_OBS;
}
// Set the fundamental fault Green's functions
for (i=0; i<10; i++)
{
dptr = NULL;
lsh = false;
lzero[i] = false;
if (i == 0)
{
dptr = ffGrns->zds;
}
else if (i == 1)
{
dptr = ffGrns->zss;
}
else if (i == 2)
{
dptr = ffGrns->zdd;
}
else if (i == 3)
{
dptr = ffGrns->zex;
}
else if (i == 4)
{
dptr = ffGrns->rds;
cmpinc = 90.0;
}
else if (i == 5)
{
dptr = ffGrns->rss;
cmpinc = 90.0;
}
else if (i == 6)
{
dptr = ffGrns->rdd;
cmpinc = 90.0;
}
else if (i == 7)
{
dptr = ffGrns->rex;
cmpinc = 90.0;
}
else if (i == 8)
{
dptr = ffGrns->tds;
lsh = true;
cmpaz = 90.0;
cmpinc = 90.0;
}
else if (i == 9)
{
dptr = ffGrns->tss;
lsh = true;
cmpaz = 90.0;
cmpinc = 90.0;
}
kndx = indx*10 + i;
sacio_setDefaultHeader(&sacFFGrns[kndx].header);
sacFFGrns[kndx].header.lhaveHeader = true;
sacio_setIntegerHeader(SAC_INT_NPTS, ffGrns->npts,
&sacFFGrns[kndx].header);
sacio_setIntegerHeader(SAC_INT_NZYEAR, 1970,
&sacFFGrns[kndx].header);
sacio_setIntegerHeader(SAC_INT_NZJDAY, 1,
&sacFFGrns[kndx].header);
sacio_setIntegerHeader(SAC_INT_NZHOUR, 0,
&sacFFGrns[kndx].header);
sacio_setIntegerHeader(SAC_INT_NZMIN, 0,
&sacFFGrns[kndx].header);
sacio_setIntegerHeader(SAC_INT_NZSEC, 0,
&sacFFGrns[kndx].header);
sacio_setIntegerHeader(SAC_INT_NZMSEC, 0,
&sacFFGrns[kndx].header);
sacio_setBooleanHeader(SAC_BOOL_LCALDA, false,
&sacFFGrns[kndx].header);
sacio_setFloatHeader(SAC_FLOAT_DELTA, ffGrns->dt,
&sacFFGrns[kndx].header);
sacio_setFloatHeader(SAC_FLOAT_GCARC, ffGrns->dist/111.195,
&sacFFGrns[kndx].header);
sacio_setFloatHeader(SAC_FLOAT_DIST, ffGrns->dist,
&sacFFGrns[kndx].header);
sacio_setFloatHeader(SAC_FLOAT_EVDP, depths[idep],
&sacFFGrns[kndx].header);
sacio_setFloatHeader(SAC_FLOAT_STEL, ffGrns->stelel,
&sacFFGrns[kndx].header);
sacio_setFloatHeader(SAC_FLOAT_AZ, 0.0,
&sacFFGrns[kndx].header);
sacio_setFloatHeader(SAC_FLOAT_BAZ, 180.0,
&sacFFGrns[kndx].header);
sacio_setFloatHeader(SAC_FLOAT_O, -ffGrns->t0,
&sacFFGrns[kndx].header);
sacio_setFloatHeader(SAC_FLOAT_B, ffGrns->t0,
&sacFFGrns[kndx].header);
sacio_setFloatHeader(SAC_FLOAT_CMPAZ, cmpaz,
&sacFFGrns[kndx].header);
sacio_setFloatHeader(SAC_FLOAT_CMPINC, cmpinc,
&sacFFGrns[kndx].header);
if (hudson96ParmsWork.dop)
{
sacio_setFloatHeader(SAC_FLOAT_A, ffGrns->timep,
&sacFFGrns[kndx].header);
sacio_setCharacterHeader(SAC_CHAR_KA, "P",
&sacFFGrns[kndx].header);
}
else
{
if (!lsh)
{
sacio_setFloatHeader(SAC_FLOAT_A, ffGrns->timesv,
&sacFFGrns[kndx].header);
}
else
{
sacio_setFloatHeader(SAC_FLOAT_A, ffGrns->timesh,
&sacFFGrns[kndx].header);
}
sacio_setCharacterHeader(SAC_CHAR_KA, "S",
&sacFFGrns[kndx].header);
}
sacio_setCharacterHeader(SAC_CHAR_KO, "O\0",
&sacFFGrns[kndx].header);
sacio_setCharacterHeader(SAC_CHAR_KEVNM, "SYNTHETIC\0",
&sacFFGrns[kndx].header);
sacio_setCharacterHeader(SAC_CHAR_KCMPNM, cfaults[i],
&sacFFGrns[kndx].header);
sacFFGrns[kndx].npts = ffGrns->npts;
sacFFGrns[kndx].data = sacio_malloc64f(ffGrns->npts);
if (dptr != NULL)
{
array_copy64f_work(ffGrns->npts, dptr, sacFFGrns[kndx].data);
}
else
{
array_set64f_work(ffGrns->npts, 0.0, sacFFGrns[kndx].data);
}
xnorm = cblas_dnrm2(sacFFGrns[kndx].npts, sacFFGrns[kndx].data, 1);
if (xnorm == 0.0){lzero[i] = true;}
// Handle scaling
cblas_dscal(sacFFGrns[kndx].npts, xscal, sacFFGrns[kndx].data, 1);
dptr = NULL;
} // Loop on fundamnetal faults
if (array_sum8l(10, lzero, &isclError) == 10)
{
memset(sncl, 0, 64*sizeof(char));
sprintf(sncl, "%s.%s.%s.%s",
obs[iobs].header.knetwk, obs[iobs].header.kstnm,
obs[iobs].header.kcmpnm, obs[iobs].header.khole);
fprintf(stdout,
"%s: Warning Greens fn %s w/ npts %d at gcarc=%e is zero\n",
__func__, sncl, hudson96ParmsWork.npts, gcarc);
}
NEXT_OBS:;
if (ffGrns != NULL)
{
cps_utils_freeHwaveGreensStruct(ffGrns);
free(ffGrns);
}
cps_utils_freeHpulse96DataStruct(&zresp);
}
return sacFFGrns;
}
//============================================================================//
/*!
* @brief Converts a 1D index to 3D grid indices:
*
* Changes:
* for (igrd=0; igrd<n1*n2*n3; igrd++)
* {
*
* }
* To:
* for (k=0; k<n3; k++)
* {
* for (j=0; j<n2; j++)
* {
* for (i=0; i<n1; i++)
* {
* igrd = k*n2*n1 + j*n1 + i;
* }
* }
* }
*
* @param[in] igrd Flattened C numbered grid index: igrd = k*n2*n1 + j*n1 + i.
* @param[in] n1 This is the fastest loop iterator (innermost loop).
* @param[in] n2 This is the middle loop iterator (intermediate loop).
* @param[in] n3 This is the slowest loop iterator (outermost loop).
* @param[out] i C index in inner loop [0,n1).
* @param[out] j C index in intermediate loop [0,n2).
* @param[out] k C index in outermost loop [0,n3).
*
* @result 0 indicates success.
*
*/
int prepmt_hudson96_grd2ijk(const int igrd,
const int n1, const int n2, const int n3,
int *i, int *j, int *k)
{
int ierr, n12;
ierr = 0;
n12 = n1*n2;
*k = (igrd)/n12;
*j = (igrd - *k*n12)/n1;
*i = igrd - *k*n12 - *j*n1;
if (*i < 0 || *i > n1 - 1){ierr = ierr + 1;}
if (*j < 0 || *j > n2 - 1){ierr = ierr + 1;}
if (*k < 0 || *k > n3 - 1){ierr = ierr + 1;}
return ierr;
}
//============================================================================//
/*!
* @brief Maps the observation, depth, and t* to the global index.
*
* @param[in] ndepth Number of depths.
* @param[in] ntstar Number of t*'s.
* @param[in] iobs C indexed observation number [0,nobs-1]
* @param[in] idep C indexed depth number [0,ndepth-1]
* @param[in] it C indexed t* number [0,ntstar-1]
*
* @result If >= 0 then this (iobs, idep, it) index in the Green's functions
* table.
*
* @author Ben Baker, ISTI
*
*/
int prepmt_hudson96_observationDepthTstarToIndex(
const int ndepth, const int ntstar,
const int iobs, const int idep, const int it)
{
int indx;
indx = iobs*ntstar*ndepth + idep*ntstar + it;
return indx;
}
| {
"alphanum_fraction": 0.5168686063,
"avg_line_length": 37.5558583106,
"ext": "c",
"hexsha": "ab7dabd404e7d7606c1c65b466a545bf216b887b",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "2b4097df02ef5e56407d40e821d5c7155c2e4416",
"max_forks_repo_licenses": [
"Intel"
],
"max_forks_repo_name": "bakerb845/parmt",
"max_forks_repo_path": "prepmt/hudson96.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "2b4097df02ef5e56407d40e821d5c7155c2e4416",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"Intel"
],
"max_issues_repo_name": "bakerb845/parmt",
"max_issues_repo_path": "prepmt/hudson96.c",
"max_line_length": 83,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "2b4097df02ef5e56407d40e821d5c7155c2e4416",
"max_stars_repo_licenses": [
"Intel"
],
"max_stars_repo_name": "bakerb845/parmt",
"max_stars_repo_path": "prepmt/hudson96.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 7388,
"size": 27566
} |
#include <stdio.h>
#include <stdlib.h>
#include <gsl/gsl_block.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_errno.h>
/* Block IO */
int mgsl_block_fwrite(const char *filename, const gsl_block *b)
{
FILE *fp;
if((fp = fopen(filename, "w")) == NULL) return GSL_EFAILED;
if(gsl_block_fwrite(fp, b) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
int mgsl_block_fread(const char *filename, gsl_block *b)
{
FILE *fp;
if((fp = fopen(filename, "r")) == NULL) return GSL_EFAILED;
if(gsl_block_fread(fp, b) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
int mgsl_block_fprintf(const char *filename, const gsl_block *b, const char *format)
{
FILE *fp;
if((fp = fopen(filename, "w")) == NULL) return GSL_EFAILED;
if(gsl_block_fprintf(fp, b, format) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
int mgsl_block_fscanf(const char *filename, gsl_block *b)
{
FILE *fp;
if((fp = fopen(filename, "r")) == NULL) return GSL_EFAILED;
if(gsl_block_fscanf(fp, b) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
int mgsl_block_float_fwrite(const char *filename, const gsl_block_float *b)
{
FILE *fp;
if((fp = fopen(filename, "w")) == NULL) return GSL_EFAILED;
if(gsl_block_float_fwrite(fp, b) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
int mgsl_block_float_fread(const char *filename, gsl_block_float *b)
{
FILE *fp;
if((fp = fopen(filename, "r")) == NULL) return GSL_EFAILED;
if(gsl_block_float_fread(fp, b) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
int mgsl_block_float_fprintf(const char *filename, const gsl_block_float *b, const char *format)
{
FILE *fp;
if((fp = fopen(filename, "w")) == NULL) return GSL_EFAILED;
if(gsl_block_float_fprintf(fp, b, format) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
int mgsl_block_float_fscanf(const char *filename, gsl_block_float *b)
{
FILE *fp;
if((fp = fopen(filename, "r")) == NULL) return GSL_EFAILED;
if(gsl_block_float_fscanf(fp, b) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
int mgsl_block_int_fwrite(const char *filename, const gsl_block_int *b)
{
FILE *fp;
if((fp = fopen(filename, "w")) == NULL) return GSL_EFAILED;
if(gsl_block_int_fwrite(fp, b) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
int mgsl_block_int_fread(const char *filename, gsl_block_int *b)
{
FILE *fp;
if((fp = fopen(filename, "r")) == NULL) return GSL_EFAILED;
if(gsl_block_int_fread(fp, b) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
int mgsl_block_int_fprintf(const char *filename, const gsl_block_int *b, const char *format)
{
FILE *fp;
if((fp = fopen(filename, "w")) == NULL) return GSL_EFAILED;
if(gsl_block_int_fprintf(fp, b, format) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
int mgsl_block_int_fscanf(const char *filename, gsl_block_int *b)
{
FILE *fp;
if((fp = fopen(filename, "r")) == NULL) return GSL_EFAILED;
if(gsl_block_int_fscanf(fp, b) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
int mgsl_block_uint_fwrite(const char *filename, const gsl_block_uint *b)
{
FILE *fp;
if((fp = fopen(filename, "w")) == NULL) return GSL_EFAILED;
if(gsl_block_uint_fwrite(fp, b) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
int mgsl_block_uint_fread(const char *filename, gsl_block_uint *b)
{
FILE *fp;
if((fp = fopen(filename, "r")) == NULL) return GSL_EFAILED;
if(gsl_block_uint_fread(fp, b) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
int mgsl_block_uint_fprintf(const char *filename, const gsl_block_uint *b, const char *format)
{
FILE *fp;
if((fp = fopen(filename, "w")) == NULL) return GSL_EFAILED;
if(gsl_block_uint_fprintf(fp, b, format) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
int mgsl_block_uint_fscanf(const char *filename, gsl_block_uint *b)
{
FILE *fp;
if((fp = fopen(filename, "r")) == NULL) return GSL_EFAILED;
if(gsl_block_uint_fscanf(fp, b) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
int mgsl_block_long_fwrite(const char *filename, const gsl_block_long *b)
{
FILE *fp;
if((fp = fopen(filename, "w")) == NULL) return GSL_EFAILED;
if(gsl_block_long_fwrite(fp, b) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
int mgsl_block_long_fread(const char *filename, gsl_block_long *b)
{
FILE *fp;
if((fp = fopen(filename, "r")) == NULL) return GSL_EFAILED;
if(gsl_block_long_fread(fp, b) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
int mgsl_block_long_fprintf(const char *filename, const gsl_block_long *b, const char *format)
{
FILE *fp;
if((fp = fopen(filename, "w")) == NULL) return GSL_EFAILED;
if(gsl_block_long_fprintf(fp, b, format) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
int mgsl_block_long_fscanf(const char *filename, gsl_block_long *b)
{
FILE *fp;
if((fp = fopen(filename, "r")) == NULL) return GSL_EFAILED;
if(gsl_block_long_fscanf(fp, b) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
int mgsl_block_ulong_fwrite(const char *filename, const gsl_block_ulong *b)
{
FILE *fp;
if((fp = fopen(filename, "w")) == NULL) return GSL_EFAILED;
if(gsl_block_ulong_fwrite(fp, b) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
int mgsl_block_ulong_fread(const char *filename, gsl_block_ulong *b)
{
FILE *fp;
if((fp = fopen(filename, "r")) == NULL) return GSL_EFAILED;
if(gsl_block_ulong_fread(fp, b) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
int mgsl_block_ulong_fprintf(const char *filename, const gsl_block_ulong *b, const char *format)
{
FILE *fp;
if((fp = fopen(filename, "w")) == NULL) return GSL_EFAILED;
if(gsl_block_ulong_fprintf(fp, b, format) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
int mgsl_block_ulong_fscanf(const char *filename, gsl_block_ulong *b)
{
FILE *fp;
if((fp = fopen(filename, "r")) == NULL) return GSL_EFAILED;
if(gsl_block_ulong_fscanf(fp, b) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
int mgsl_block_short_fwrite(const char *filename, const gsl_block_short *b)
{
FILE *fp;
if((fp = fopen(filename, "w")) == NULL) return GSL_EFAILED;
if(gsl_block_short_fwrite(fp, b) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
int mgsl_block_short_fread(const char *filename, gsl_block_short *b)
{
FILE *fp;
if((fp = fopen(filename, "r")) == NULL) return GSL_EFAILED;
if(gsl_block_short_fread(fp, b) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
int mgsl_block_short_fprintf(const char *filename, const gsl_block_short *b, const char *format)
{
FILE *fp;
if((fp = fopen(filename, "w")) == NULL) return GSL_EFAILED;
if(gsl_block_short_fprintf(fp, b, format) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
int mgsl_block_short_fscanf(const char *filename, gsl_block_short *b)
{
FILE *fp;
if((fp = fopen(filename, "r")) == NULL) return GSL_EFAILED;
if(gsl_block_short_fscanf(fp, b) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
int mgsl_block_ushort_fwrite(const char *filename, const gsl_block_ushort *b)
{
FILE *fp;
if((fp = fopen(filename, "w")) == NULL) return GSL_EFAILED;
if(gsl_block_ushort_fwrite(fp, b) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
int mgsl_block_ushort_fread(const char *filename, gsl_block_ushort *b)
{
FILE *fp;
if((fp = fopen(filename, "r")) == NULL) return GSL_EFAILED;
if(gsl_block_ushort_fread(fp, b) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
int mgsl_block_ushort_fprintf(const char *filename, const gsl_block_ushort *b, const char *format)
{
FILE *fp;
if((fp = fopen(filename, "w")) == NULL) return GSL_EFAILED;
if(gsl_block_ushort_fprintf(fp, b, format) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
int mgsl_block_ushort_fscanf(const char *filename, gsl_block_ushort *b)
{
FILE *fp;
if((fp = fopen(filename, "r")) == NULL) return GSL_EFAILED;
if(gsl_block_ushort_fscanf(fp, b) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
int mgsl_block_char_fwrite(const char *filename, const gsl_block_char *b)
{
FILE *fp;
if((fp = fopen(filename, "w")) == NULL) return GSL_EFAILED;
if(gsl_block_char_fwrite(fp, b) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
int mgsl_block_char_fread(const char *filename, gsl_block_char *b)
{
FILE *fp;
if((fp = fopen(filename, "r")) == NULL) return GSL_EFAILED;
if(gsl_block_char_fread(fp, b) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
int mgsl_block_char_fprintf(const char *filename, const gsl_block_char *b, const char *format)
{
FILE *fp;
if((fp = fopen(filename, "w")) == NULL) return GSL_EFAILED;
if(gsl_block_char_fprintf(fp, b, format) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
int mgsl_block_char_fscanf(const char *filename, gsl_block_char *b)
{
FILE *fp;
if((fp = fopen(filename, "r")) == NULL) return GSL_EFAILED;
if(gsl_block_char_fscanf(fp, b) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
int mgsl_block_uchar_fwrite(const char *filename, const gsl_block_uchar *b)
{
FILE *fp;
if((fp = fopen(filename, "w")) == NULL) return GSL_EFAILED;
if(gsl_block_uchar_fwrite(fp, b) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
int mgsl_block_uchar_fread(const char *filename, gsl_block_uchar *b)
{
FILE *fp;
if((fp = fopen(filename, "r")) == NULL) return GSL_EFAILED;
if(gsl_block_uchar_fread(fp, b) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
int mgsl_block_uchar_fprintf(const char *filename, const gsl_block_uchar *b, const char *format)
{
FILE *fp;
if((fp = fopen(filename, "w")) == NULL) return GSL_EFAILED;
if(gsl_block_uchar_fprintf(fp, b, format) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
int mgsl_block_uchar_fscanf(const char *filename, gsl_block_uchar *b)
{
FILE *fp;
if((fp = fopen(filename, "r")) == NULL) return GSL_EFAILED;
if(gsl_block_uchar_fscanf(fp, b) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
int mgsl_block_complex_fwrite(const char *filename, const gsl_block_complex *b)
{
FILE *fp;
if((fp = fopen(filename, "w")) == NULL) return GSL_EFAILED;
if(gsl_block_complex_fwrite(fp, b) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
int mgsl_block_complex_fread(const char *filename, gsl_block_complex *b)
{
FILE *fp;
if((fp = fopen(filename, "r")) == NULL) return GSL_EFAILED;
if(gsl_block_complex_fread(fp, b) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
int mgsl_block_complex_fprintf(const char *filename, const gsl_block_complex *b, const char *format)
{
FILE *fp;
if((fp = fopen(filename, "w")) == NULL) return GSL_EFAILED;
if(gsl_block_complex_fprintf(fp, b, format) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
int mgsl_block_complex_fscanf(const char *filename, gsl_block_complex *b)
{
FILE *fp;
if((fp = fopen(filename, "r")) == NULL) return GSL_EFAILED;
if(gsl_block_complex_fscanf(fp, b) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
int mgsl_block_complex_float_fwrite(const char *filename, const gsl_block_complex_float *b)
{
FILE *fp;
if((fp = fopen(filename, "w")) == NULL) return GSL_EFAILED;
if(gsl_block_complex_float_fwrite(fp, b) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
int mgsl_block_complex_float_fread(const char *filename, gsl_block_complex_float *b)
{
FILE *fp;
if((fp = fopen(filename, "r")) == NULL) return GSL_EFAILED;
if(gsl_block_complex_float_fread(fp, b) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
int mgsl_block_complex_float_fprintf(const char *filename, const gsl_block_complex_float *b, const char *format)
{
FILE *fp;
if((fp = fopen(filename, "w")) == NULL) return GSL_EFAILED;
if(gsl_block_complex_float_fprintf(fp, b, format) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
int mgsl_block_complex_float_fscanf(const char *filename, gsl_block_complex_float *b)
{
FILE *fp;
if((fp = fopen(filename, "r")) == NULL) return GSL_EFAILED;
if(gsl_block_complex_float_fscanf(fp, b) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
/* Vector IO */
int mgsl_vector_fwrite(const char *filename, const gsl_vector *v)
{
FILE *fp;
if((fp = fopen(filename, "w")) == NULL) return GSL_EFAILED;
if(gsl_vector_fwrite(fp, v) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
int mgsl_vector_fread(const char *filename, gsl_vector *v)
{
FILE *fp;
if((fp = fopen(filename, "r")) == NULL) return GSL_EFAILED;
if(gsl_vector_fread(fp, v) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
int mgsl_vector_fprintf(const char *filename, const gsl_vector *v, const char *format)
{
FILE *fp;
if((fp = fopen(filename, "w")) == NULL) return GSL_EFAILED;
if(gsl_vector_fprintf(fp, v, format) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
int mgsl_vector_fscanf(const char *filename, gsl_vector *v)
{
FILE *fp;
if((fp = fopen(filename, "r")) == NULL) return GSL_EFAILED;
if(gsl_vector_fscanf(fp, v) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
int mgsl_vector_float_fwrite(const char *filename, const gsl_vector_float *v)
{
FILE *fp;
if((fp = fopen(filename, "w")) == NULL) return GSL_EFAILED;
if(gsl_vector_float_fwrite(fp, v) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
int mgsl_vector_float_fread(const char *filename, gsl_vector_float *v)
{
FILE *fp;
if((fp = fopen(filename, "r")) == NULL) return GSL_EFAILED;
if(gsl_vector_float_fread(fp, v) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
int mgsl_vector_float_fprintf(const char *filename, const gsl_vector_float *v, const char *format)
{
FILE *fp;
if((fp = fopen(filename, "w")) == NULL) return GSL_EFAILED;
if(gsl_vector_float_fprintf(fp, v, format) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
int mgsl_vector_float_fscanf(const char *filename, gsl_vector_float *v)
{
FILE *fp;
if((fp = fopen(filename, "r")) == NULL) return GSL_EFAILED;
if(gsl_vector_float_fscanf(fp, v) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
int mgsl_vector_int_fwrite(const char *filename, const gsl_vector_int *v)
{
FILE *fp;
if((fp = fopen(filename, "w")) == NULL) return GSL_EFAILED;
if(gsl_vector_int_fwrite(fp, v) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
int mgsl_vector_int_fread(const char *filename, gsl_vector_int *v)
{
FILE *fp;
if((fp = fopen(filename, "r")) == NULL) return GSL_EFAILED;
if(gsl_vector_int_fread(fp, v) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
int mgsl_vector_int_fprintf(const char *filename, const gsl_vector_int *v, const char *format)
{
FILE *fp;
if((fp = fopen(filename, "w")) == NULL) return GSL_EFAILED;
if(gsl_vector_int_fprintf(fp, v, format) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
int mgsl_vector_int_fscanf(const char *filename, gsl_vector_int *v)
{
FILE *fp;
if((fp = fopen(filename, "r")) == NULL) return GSL_EFAILED;
if(gsl_vector_int_fscanf(fp, v) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
int mgsl_vector_uint_fwrite(const char *filename, const gsl_vector_uint *v)
{
FILE *fp;
if((fp = fopen(filename, "w")) == NULL) return GSL_EFAILED;
if(gsl_vector_uint_fwrite(fp, v) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
int mgsl_vector_uint_fread(const char *filename, gsl_vector_uint *v)
{
FILE *fp;
if((fp = fopen(filename, "r")) == NULL) return GSL_EFAILED;
if(gsl_vector_uint_fread(fp, v) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
int mgsl_vector_uint_fprintf(const char *filename, const gsl_vector_uint *v, const char *format)
{
FILE *fp;
if((fp = fopen(filename, "w")) == NULL) return GSL_EFAILED;
if(gsl_vector_uint_fprintf(fp, v, format) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
int mgsl_vector_uint_fscanf(const char *filename, gsl_vector_uint *v)
{
FILE *fp;
if((fp = fopen(filename, "r")) == NULL) return GSL_EFAILED;
if(gsl_vector_uint_fscanf(fp, v) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
int mgsl_vector_long_fwrite(const char *filename, const gsl_vector_long *v)
{
FILE *fp;
if((fp = fopen(filename, "w")) == NULL) return GSL_EFAILED;
if(gsl_vector_long_fwrite(fp, v) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
int mgsl_vector_long_fread(const char *filename, gsl_vector_long *v)
{
FILE *fp;
if((fp = fopen(filename, "r")) == NULL) return GSL_EFAILED;
if(gsl_vector_long_fread(fp, v) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
int mgsl_vector_long_fprintf(const char *filename, const gsl_vector_long *v, const char *format)
{
FILE *fp;
if((fp = fopen(filename, "w")) == NULL) return GSL_EFAILED;
if(gsl_vector_long_fprintf(fp, v, format) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
int mgsl_vector_long_fscanf(const char *filename, gsl_vector_long *v)
{
FILE *fp;
if((fp = fopen(filename, "r")) == NULL) return GSL_EFAILED;
if(gsl_vector_long_fscanf(fp, v) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
int mgsl_vector_ulong_fwrite(const char *filename, const gsl_vector_ulong *v)
{
FILE *fp;
if((fp = fopen(filename, "w")) == NULL) return GSL_EFAILED;
if(gsl_vector_ulong_fwrite(fp, v) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
int mgsl_vector_ulong_fread(const char *filename, gsl_vector_ulong *v)
{
FILE *fp;
if((fp = fopen(filename, "r")) == NULL) return GSL_EFAILED;
if(gsl_vector_ulong_fread(fp, v) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
int mgsl_vector_ulong_fprintf(const char *filename, const gsl_vector_ulong *v, const char *format)
{
FILE *fp;
if((fp = fopen(filename, "w")) == NULL) return GSL_EFAILED;
if(gsl_vector_ulong_fprintf(fp, v, format) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
int mgsl_vector_ulong_fscanf(const char *filename, gsl_vector_ulong *v)
{
FILE *fp;
if((fp = fopen(filename, "r")) == NULL) return GSL_EFAILED;
if(gsl_vector_ulong_fscanf(fp, v) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
int mgsl_vector_short_fwrite(const char *filename, const gsl_vector_short *v)
{
FILE *fp;
if((fp = fopen(filename, "w")) == NULL) return GSL_EFAILED;
if(gsl_vector_short_fwrite(fp, v) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
int mgsl_vector_short_fread(const char *filename, gsl_vector_short *v)
{
FILE *fp;
if((fp = fopen(filename, "r")) == NULL) return GSL_EFAILED;
if(gsl_vector_short_fread(fp, v) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
int mgsl_vector_short_fprintf(const char *filename, const gsl_vector_short *v, const char *format)
{
FILE *fp;
if((fp = fopen(filename, "w")) == NULL) return GSL_EFAILED;
if(gsl_vector_short_fprintf(fp, v, format) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
int mgsl_vector_short_fscanf(const char *filename, gsl_vector_short *v)
{
FILE *fp;
if((fp = fopen(filename, "r")) == NULL) return GSL_EFAILED;
if(gsl_vector_short_fscanf(fp, v) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
int mgsl_vector_ushort_fwrite(const char *filename, const gsl_vector_ushort *v)
{
FILE *fp;
if((fp = fopen(filename, "w")) == NULL) return GSL_EFAILED;
if(gsl_vector_ushort_fwrite(fp, v) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
int mgsl_vector_ushort_fread(const char *filename, gsl_vector_ushort *v)
{
FILE *fp;
if((fp = fopen(filename, "r")) == NULL) return GSL_EFAILED;
if(gsl_vector_ushort_fread(fp, v) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
int mgsl_vector_ushort_fprintf(const char *filename, const gsl_vector_ushort *v, const char *format)
{
FILE *fp;
if((fp = fopen(filename, "w")) == NULL) return GSL_EFAILED;
if(gsl_vector_ushort_fprintf(fp, v, format) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
int mgsl_vector_ushort_fscanf(const char *filename, gsl_vector_ushort *v)
{
FILE *fp;
if((fp = fopen(filename, "r")) == NULL) return GSL_EFAILED;
if(gsl_vector_ushort_fscanf(fp, v) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
int mgsl_vector_char_fwrite(const char *filename, const gsl_vector_char *v)
{
FILE *fp;
if((fp = fopen(filename, "w")) == NULL) return GSL_EFAILED;
if(gsl_vector_char_fwrite(fp, v) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
int mgsl_vector_char_fread(const char *filename, gsl_vector_char *v)
{
FILE *fp;
if((fp = fopen(filename, "r")) == NULL) return GSL_EFAILED;
if(gsl_vector_char_fread(fp, v) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
int mgsl_vector_char_fprintf(const char *filename, const gsl_vector_char *v, const char *format)
{
FILE *fp;
if((fp = fopen(filename, "w")) == NULL) return GSL_EFAILED;
if(gsl_vector_char_fprintf(fp, v, format) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
int mgsl_vector_char_fscanf(const char *filename, gsl_vector_char *v)
{
FILE *fp;
if((fp = fopen(filename, "r")) == NULL) return GSL_EFAILED;
if(gsl_vector_char_fscanf(fp, v) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
int mgsl_vector_uchar_fwrite(const char *filename, const gsl_vector_uchar *v)
{
FILE *fp;
if((fp = fopen(filename, "w")) == NULL) return GSL_EFAILED;
if(gsl_vector_uchar_fwrite(fp, v) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
int mgsl_vector_uchar_fread(const char *filename, gsl_vector_uchar *v)
{
FILE *fp;
if((fp = fopen(filename, "r")) == NULL) return GSL_EFAILED;
if(gsl_vector_uchar_fread(fp, v) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
int mgsl_vector_uchar_fprintf(const char *filename, const gsl_vector_uchar *v, const char *format)
{
FILE *fp;
if((fp = fopen(filename, "w")) == NULL) return GSL_EFAILED;
if(gsl_vector_uchar_fprintf(fp, v, format) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
int mgsl_vector_uchar_fscanf(const char *filename, gsl_vector_uchar *v)
{
FILE *fp;
if((fp = fopen(filename, "r")) == NULL) return GSL_EFAILED;
if(gsl_vector_uchar_fscanf(fp, v) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
int mgsl_vector_complex_fwrite(const char *filename, const gsl_vector_complex *v)
{
FILE *fp;
if((fp = fopen(filename, "w")) == NULL) return GSL_EFAILED;
if(gsl_vector_complex_fwrite(fp, v) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
int mgsl_vector_complex_fread(const char *filename, gsl_vector_complex *v)
{
FILE *fp;
if((fp = fopen(filename, "r")) == NULL) return GSL_EFAILED;
if(gsl_vector_complex_fread(fp, v) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
int mgsl_vector_complex_fprintf(const char *filename, const gsl_vector_complex *v, const char *format)
{
FILE *fp;
if((fp = fopen(filename, "w")) == NULL) return GSL_EFAILED;
if(gsl_vector_complex_fprintf(fp, v, format) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
int mgsl_vector_complex_fscanf(const char *filename, gsl_vector_complex *v)
{
FILE *fp;
if((fp = fopen(filename, "r")) == NULL) return GSL_EFAILED;
if(gsl_vector_complex_fscanf(fp, v) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
int mgsl_vector_complex_float_fwrite(const char *filename, const gsl_vector_complex_float *v)
{
FILE *fp;
if((fp = fopen(filename, "w")) == NULL) return GSL_EFAILED;
if(gsl_vector_complex_float_fwrite(fp, v) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
int mgsl_vector_complex_float_fread(const char *filename, gsl_vector_complex_float *v)
{
FILE *fp;
if((fp = fopen(filename, "r")) == NULL) return GSL_EFAILED;
if(gsl_vector_complex_float_fread(fp, v) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
int mgsl_vector_complex_float_fprintf(const char *filename, const gsl_vector_complex_float *v, const char *format)
{
FILE *fp;
if((fp = fopen(filename, "w")) == NULL) return GSL_EFAILED;
if(gsl_vector_complex_float_fprintf(fp, v, format) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
int mgsl_vector_complex_float_fscanf(const char *filename, gsl_vector_complex_float *v)
{
FILE *fp;
if((fp = fopen(filename, "r")) == NULL) return GSL_EFAILED;
if(gsl_vector_complex_float_fscanf(fp, v) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
/* Vector view */
gsl_vector_view *alloc_gsl_vector_view(void)
{
gsl_vector_view *c = calloc(1, sizeof(gsl_vector_view));
return c;
}
void free_gsl_vector_view(gsl_vector_view *c)
{
if(c != NULL){
free(c);
c = NULL;
}
}
gsl_vector *mgsl_vector_subvector(gsl_vector_view *view, gsl_vector *v, size_t offset, size_t n)
{
*view = gsl_vector_subvector(v, offset, n);
return &view->vector;
}
gsl_vector *mgsl_vector_subvector_with_stride(gsl_vector_view *view, gsl_vector *v, size_t offset, size_t stride, size_t n)
{
*view = gsl_vector_subvector_with_stride(v, offset, stride, n);
return &view->vector;
}
gsl_vector *mgsl_vector_complex_real(gsl_vector_view *view, gsl_vector_complex *v)
{
*view = gsl_vector_complex_real(v);
return &view->vector;
}
gsl_vector *mgsl_vector_complex_imag(gsl_vector_view *view, gsl_vector_complex *v)
{
*view = gsl_vector_complex_imag(v);
return &view->vector;
}
gsl_vector_float *mgsl_vector_complex_float_real(gsl_vector_float_view *view, gsl_vector_complex_float *v)
{
*view = gsl_vector_complex_float_real(v);
return &view->vector;
}
gsl_vector_float *mgsl_vector_complex_float_imag(gsl_vector_float_view *view, gsl_vector_complex_float *v)
{
*view = gsl_vector_complex_float_imag(v);
return &view->vector;
}
gsl_vector *mgsl_vector_view_array(gsl_vector_view *view, double *base, size_t n)
{
*view = gsl_vector_view_array(base, n);
return &view->vector;
}
gsl_vector *mgsl_vector_view_array_with_stride(gsl_vector_view *view, double *base, size_t stride, size_t n)
{
*view = gsl_vector_view_array_with_stride(base, stride, n);
return &view->vector;
}
gsl_vector_float_view *alloc_gsl_vector_float_view(void)
{
gsl_vector_float_view *c = calloc(1, sizeof(gsl_vector_float_view));
return c;
}
void free_gsl_vector_float_view(gsl_vector_float_view *c)
{
if(c != NULL){
free(c);
c = NULL;
}
}
gsl_vector_float *mgsl_vector_float_subvector(gsl_vector_float_view *view, gsl_vector_float *v, size_t offset, size_t n)
{
*view = gsl_vector_float_subvector(v, offset, n);
return &view->vector;
}
gsl_vector_float *mgsl_vector_float_subvector_with_stride(gsl_vector_float_view *view, gsl_vector_float *v, size_t offset, size_t stride, size_t n)
{
*view = gsl_vector_float_subvector_with_stride(v, offset, stride, n);
return &view->vector;
}
gsl_vector_float *mgsl_vector_float_view_array(gsl_vector_float_view *view, float *base, size_t n)
{
*view = gsl_vector_float_view_array(base, n);
return &view->vector;
}
gsl_vector_float *mgsl_vector_float_view_array_with_stride(gsl_vector_float_view *view, float *base, size_t stride, size_t n)
{
*view = gsl_vector_float_view_array_with_stride(base, stride, n);
return &view->vector;
}
gsl_vector_int_view *alloc_gsl_vector_int_view(void)
{
gsl_vector_int_view *c = calloc(1, sizeof(gsl_vector_int_view));
return c;
}
void free_gsl_vector_int_view(gsl_vector_int_view *c)
{
if(c != NULL){
free(c);
c = NULL;
}
}
gsl_vector_int *mgsl_vector_int_subvector(gsl_vector_int_view *view, gsl_vector_int *v, size_t offset, size_t n)
{
*view = gsl_vector_int_subvector(v, offset, n);
return &view->vector;
}
gsl_vector_int *mgsl_vector_int_subvector_with_stride(gsl_vector_int_view *view, gsl_vector_int *v, size_t offset, size_t stride, size_t n)
{
*view = gsl_vector_int_subvector_with_stride(v, offset, stride, n);
return &view->vector;
}
gsl_vector_int *mgsl_vector_int_view_array(gsl_vector_int_view *view, int *base, size_t n)
{
*view = gsl_vector_int_view_array(base, n);
return &view->vector;
}
gsl_vector_int *mgsl_vector_int_view_array_with_stride(gsl_vector_int_view *view, int *base, size_t stride, size_t n)
{
*view = gsl_vector_int_view_array_with_stride(base, stride, n);
return &view->vector;
}
gsl_vector_uint_view *alloc_gsl_vector_uint_view(void)
{
gsl_vector_uint_view *c = calloc(1, sizeof(gsl_vector_uint_view));
return c;
}
void free_gsl_vector_uint_view(gsl_vector_uint_view *c)
{
if(c != NULL){
free(c);
c = NULL;
}
}
gsl_vector_uint *mgsl_vector_uint_subvector(gsl_vector_uint_view *view, gsl_vector_uint *v, size_t offset, size_t n)
{
*view = gsl_vector_uint_subvector(v, offset, n);
return &view->vector;
}
gsl_vector_uint *mgsl_vector_uint_subvector_with_stride(gsl_vector_uint_view *view, gsl_vector_uint *v, size_t offset, size_t stride, size_t n)
{
*view = gsl_vector_uint_subvector_with_stride(v, offset, stride, n);
return &view->vector;
}
gsl_vector_uint *mgsl_vector_uint_view_array(gsl_vector_uint_view *view, unsigned int *base, size_t n)
{
*view = gsl_vector_uint_view_array(base, n);
return &view->vector;
}
gsl_vector_uint *mgsl_vector_uint_view_array_with_stride(gsl_vector_uint_view *view, unsigned int *base, size_t stride, size_t n)
{
*view = gsl_vector_uint_view_array_with_stride(base, stride, n);
return &view->vector;
}
gsl_vector_long_view *alloc_gsl_vector_long_view(void)
{
gsl_vector_long_view *c = calloc(1, sizeof(gsl_vector_long_view));
return c;
}
void free_gsl_vector_long_view(gsl_vector_long_view *c)
{
if(c != NULL){
free(c);
c = NULL;
}
}
gsl_vector_long *mgsl_vector_long_subvector(gsl_vector_long_view *view, gsl_vector_long *v, size_t offset, size_t n)
{
*view = gsl_vector_long_subvector(v, offset, n);
return &view->vector;
}
gsl_vector_long *mgsl_vector_long_subvector_with_stride(gsl_vector_long_view *view, gsl_vector_long *v, size_t offset, size_t stride, size_t n)
{
*view = gsl_vector_long_subvector_with_stride(v, offset, stride, n);
return &view->vector;
}
gsl_vector_long *mgsl_vector_long_view_array(gsl_vector_long_view *view, long *base, size_t n)
{
*view = gsl_vector_long_view_array(base, n);
return &view->vector;
}
gsl_vector_long *mgsl_vector_long_view_array_with_stride(gsl_vector_long_view *view, long *base, size_t stride, size_t n)
{
*view = gsl_vector_long_view_array_with_stride(base, stride, n);
return &view->vector;
}
gsl_vector_ulong_view *alloc_gsl_vector_ulong_view(void)
{
gsl_vector_ulong_view *c = calloc(1, sizeof(gsl_vector_ulong_view));
return c;
}
void free_gsl_vector_ulong_view(gsl_vector_ulong_view *c)
{
if(c != NULL){
free(c);
c = NULL;
}
}
gsl_vector_ulong *mgsl_vector_ulong_subvector(gsl_vector_ulong_view *view, gsl_vector_ulong *v, size_t offset, size_t n)
{
*view = gsl_vector_ulong_subvector(v, offset, n);
return &view->vector;
}
gsl_vector_ulong *mgsl_vector_ulong_subvector_with_stride(gsl_vector_ulong_view *view, gsl_vector_ulong *v, size_t offset, size_t stride, size_t n)
{
*view = gsl_vector_ulong_subvector_with_stride(v, offset, stride, n);
return &view->vector;
}
gsl_vector_ulong *mgsl_vector_ulong_view_array(gsl_vector_ulong_view *view, unsigned long *base, size_t n)
{
*view = gsl_vector_ulong_view_array(base, n);
return &view->vector;
}
gsl_vector_ulong *mgsl_vector_ulong_view_array_with_stride(gsl_vector_ulong_view *view, unsigned long *base, size_t stride, size_t n)
{
*view = gsl_vector_ulong_view_array_with_stride(base, stride, n);
return &view->vector;
}
gsl_vector_short_view *alloc_gsl_vector_short_view(void)
{
gsl_vector_short_view *c = calloc(1, sizeof(gsl_vector_short_view));
return c;
}
void free_gsl_vector_short_view(gsl_vector_short_view *c)
{
if(c != NULL){
free(c);
c = NULL;
}
}
gsl_vector_short *mgsl_vector_short_subvector(gsl_vector_short_view *view, gsl_vector_short *v, size_t offset, size_t n)
{
*view = gsl_vector_short_subvector(v, offset, n);
return &view->vector;
}
gsl_vector_short *mgsl_vector_short_subvector_with_stride(gsl_vector_short_view *view, gsl_vector_short *v, size_t offset, size_t stride, size_t n)
{
*view = gsl_vector_short_subvector_with_stride(v, offset, stride, n);
return &view->vector;
}
gsl_vector_short *mgsl_vector_short_view_array(gsl_vector_short_view *view, short *base, size_t n)
{
*view = gsl_vector_short_view_array(base, n);
return &view->vector;
}
gsl_vector_short *mgsl_vector_short_view_array_with_stride(gsl_vector_short_view *view, short *base, size_t stride, size_t n)
{
*view = gsl_vector_short_view_array_with_stride(base, stride, n);
return &view->vector;
}
gsl_vector_ushort_view *alloc_gsl_vector_ushort_view(void)
{
gsl_vector_ushort_view *c = calloc(1, sizeof(gsl_vector_ushort_view));
return c;
}
void free_gsl_vector_ushort_view(gsl_vector_ushort_view *c)
{
if(c != NULL){
free(c);
c = NULL;
}
}
gsl_vector_ushort *mgsl_vector_ushort_subvector(gsl_vector_ushort_view *view, gsl_vector_ushort *v, size_t offset, size_t n)
{
*view = gsl_vector_ushort_subvector(v, offset, n);
return &view->vector;
}
gsl_vector_ushort *mgsl_vector_ushort_subvector_with_stride(gsl_vector_ushort_view *view, gsl_vector_ushort *v, size_t offset, size_t stride, size_t n)
{
*view = gsl_vector_ushort_subvector_with_stride(v, offset, stride, n);
return &view->vector;
}
gsl_vector_ushort *mgsl_vector_ushort_view_array(gsl_vector_ushort_view *view, unsigned short *base, size_t n)
{
*view = gsl_vector_ushort_view_array(base, n);
return &view->vector;
}
gsl_vector_ushort *mgsl_vector_ushort_view_array_with_stride(gsl_vector_ushort_view *view, unsigned short *base, size_t stride, size_t n)
{
*view = gsl_vector_ushort_view_array_with_stride(base, stride, n);
return &view->vector;
}
gsl_vector_char_view *alloc_gsl_vector_char_view(void)
{
gsl_vector_char_view *c = calloc(1, sizeof(gsl_vector_char_view));
return c;
}
void free_gsl_vector_char_view(gsl_vector_char_view *c)
{
if(c != NULL){
free(c);
c = NULL;
}
}
gsl_vector_char *mgsl_vector_char_subvector(gsl_vector_char_view *view, gsl_vector_char *v, size_t offset, size_t n)
{
*view = gsl_vector_char_subvector(v, offset, n);
return &view->vector;
}
gsl_vector_char *mgsl_vector_char_subvector_with_stride(gsl_vector_char_view *view, gsl_vector_char *v, size_t offset, size_t stride, size_t n)
{
*view = gsl_vector_char_subvector_with_stride(v, offset, stride, n);
return &view->vector;
}
gsl_vector_char *mgsl_vector_char_view_array(gsl_vector_char_view *view, char *base, size_t n)
{
*view = gsl_vector_char_view_array(base, n);
return &view->vector;
}
gsl_vector_char *mgsl_vector_char_view_array_with_stride(gsl_vector_char_view *view, char *base, size_t stride, size_t n)
{
*view = gsl_vector_char_view_array_with_stride(base, stride, n);
return &view->vector;
}
gsl_vector_uchar_view *alloc_gsl_vector_uchar_view(void)
{
gsl_vector_uchar_view *c = calloc(1, sizeof(gsl_vector_uchar_view));
return c;
}
void free_gsl_vector_uchar_view(gsl_vector_uchar_view *c)
{
if(c != NULL){
free(c);
c = NULL;
}
}
gsl_vector_uchar *mgsl_vector_uchar_subvector(gsl_vector_uchar_view *view, gsl_vector_uchar *v, size_t offset, size_t n)
{
*view = gsl_vector_uchar_subvector(v, offset, n);
return &view->vector;
}
gsl_vector_uchar *mgsl_vector_uchar_subvector_with_stride(gsl_vector_uchar_view *view, gsl_vector_uchar *v, size_t offset, size_t stride, size_t n)
{
*view = gsl_vector_uchar_subvector_with_stride(v, offset, stride, n);
return &view->vector;
}
gsl_vector_uchar *mgsl_vector_uchar_view_array(gsl_vector_uchar_view *view, unsigned char *base, size_t n)
{
*view = gsl_vector_uchar_view_array(base, n);
return &view->vector;
}
gsl_vector_uchar *mgsl_vector_uchar_view_array_with_stride(gsl_vector_uchar_view *view, unsigned char *base, size_t stride, size_t n)
{
*view = gsl_vector_uchar_view_array_with_stride(base, stride, n);
return &view->vector;
}
gsl_vector_complex_view *alloc_gsl_vector_complex_view(void)
{
gsl_vector_complex_view *c = calloc(1, sizeof(gsl_vector_complex_view));
return c;
}
void free_gsl_vector_complex_view(gsl_vector_complex_view *c)
{
if(c != NULL){
free(c);
c = NULL;
}
}
gsl_vector_complex *mgsl_vector_complex_subvector(gsl_vector_complex_view *view, gsl_vector_complex *v, size_t offset, size_t n)
{
*view = gsl_vector_complex_subvector(v, offset, n);
return &view->vector;
}
gsl_vector_complex *mgsl_vector_complex_subvector_with_stride(gsl_vector_complex_view *view, gsl_vector_complex *v, size_t offset, size_t stride, size_t n)
{
*view = gsl_vector_complex_subvector_with_stride(v, offset, stride, n);
return &view->vector;
}
gsl_vector_complex *mgsl_vector_complex_view_array(gsl_vector_complex_view *view, double *base, size_t n)
{
*view = gsl_vector_complex_view_array(base, n);
return &view->vector;
}
gsl_vector_complex *mgsl_vector_complex_view_array_with_stride(gsl_vector_complex_view *view, double *base, size_t stride, size_t n)
{
*view = gsl_vector_complex_view_array_with_stride(base, stride, n);
return &view->vector;
}
gsl_vector_complex_float_view *alloc_gsl_vector_complex_float_view(void)
{
gsl_vector_complex_float_view *c = calloc(1, sizeof(gsl_vector_complex_float_view));
return c;
}
void free_gsl_vector_complex_float_view(gsl_vector_complex_float_view *c)
{
if(c != NULL){
free(c);
c = NULL;
}
}
gsl_vector_complex_float *mgsl_vector_complex_float_subvector(gsl_vector_complex_float_view *view, gsl_vector_complex_float *v, size_t offset, size_t n)
{
*view = gsl_vector_complex_float_subvector(v, offset, n);
return &view->vector;
}
gsl_vector_complex_float *mgsl_vector_complex_float_subvector_with_stride(gsl_vector_complex_float_view *view, gsl_vector_complex_float *v, size_t offset, size_t stride, size_t n)
{
*view = gsl_vector_complex_float_subvector_with_stride(v, offset, stride, n);
return &view->vector;
}
gsl_vector_complex_float *mgsl_vector_complex_float_view_array(gsl_vector_complex_float_view *view, float *base, size_t n)
{
*view = gsl_vector_complex_float_view_array(base, n);
return &view->vector;
}
gsl_vector_complex_float *mgsl_vector_complex_float_view_array_with_stride(gsl_vector_complex_float_view *view, float *base, size_t stride, size_t n)
{
*view = gsl_vector_complex_float_view_array_with_stride(base, stride, n);
return &view->vector;
}
/* Complex vectors */
void mgsl_vector_complex_get(gsl_vector_complex *v, size_t i, gsl_complex *res)
{
*res = gsl_vector_complex_get(v, i);
}
void mgsl_vector_complex_set(gsl_vector_complex *v, size_t i, gsl_complex *x)
{
gsl_vector_complex_set(v, i, *x);
}
void mgsl_vector_complex_float_get(gsl_vector_complex_float *v, size_t i, gsl_complex_float *res)
{
*res = gsl_vector_complex_float_get(v, i);
}
void mgsl_vector_complex_float_set(gsl_vector_complex_float *v, size_t i, gsl_complex_float *x)
{
gsl_vector_complex_float_set(v, i, *x);
}
void mgsl_vector_complex_set_all(gsl_vector_complex *v, gsl_complex *x)
{
gsl_vector_complex_set_all(v, *x);
}
void mgsl_vector_complex_float_set_all(gsl_vector_complex_float *v, gsl_complex_float *x)
{
gsl_vector_complex_float_set_all(v, *x);
}
int mgsl_vector_complex_scale(gsl_vector_complex *a, gsl_complex *x)
{
return gsl_vector_complex_scale(a, *x);
}
int mgsl_vector_complex_float_scale(gsl_vector_complex_float *a, gsl_complex_float *x)
{
return gsl_vector_complex_float_scale(a, *x);
}
int mgsl_vector_complex_add_constant(gsl_vector_complex *a, gsl_complex *x)
{
return gsl_vector_complex_add_constant(a, *x);
}
int mgsl_vector_complex_float_add_constant(gsl_vector_complex_float *a, gsl_complex_float *x)
{
return gsl_vector_complex_float_add_constant(a, *x);
}
/* Matrix IO */
void mgsl_matrix_complex_get(gsl_matrix_complex *v, size_t i, size_t j, gsl_complex *res)
{
*res = gsl_matrix_complex_get(v, i, j);
}
void mgsl_matrix_complex_set(gsl_matrix_complex *v, size_t i, size_t j, gsl_complex *x)
{
gsl_matrix_complex_set(v, i, j, *x);
}
void mgsl_matrix_complex_float_get(gsl_matrix_complex_float *v, size_t i, size_t j, gsl_complex_float *res)
{
*res = gsl_matrix_complex_float_get(v, i, j);
}
void mgsl_matrix_complex_float_set(gsl_matrix_complex_float *v, size_t i, size_t j, gsl_complex_float *x)
{
gsl_matrix_complex_float_set(v, i, j, *x);
}
void mgsl_matrix_complex_set_all(gsl_matrix_complex *v, gsl_complex *x)
{
gsl_matrix_complex_set_all(v, *x);
}
void mgsl_matrix_complex_float_set_all(gsl_matrix_complex_float *v, gsl_complex_float *x)
{
gsl_matrix_complex_float_set_all(v, *x);
}
int mgsl_matrix_fwrite(const char *filename, const gsl_matrix *m)
{
FILE *fp;
if((fp = fopen(filename, "w")) == NULL) return GSL_EFAILED;
if(gsl_matrix_fwrite(fp, m) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
int mgsl_matrix_fread(const char *filename, gsl_matrix *m)
{
FILE *fp;
if((fp = fopen(filename, "r")) == NULL) return GSL_EFAILED;
if(gsl_matrix_fread(fp, m) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
int mgsl_matrix_fprintf(const char *filename, const gsl_matrix *m, const char *format)
{
FILE *fp;
if((fp = fopen(filename, "w")) == NULL) return GSL_EFAILED;
if(gsl_matrix_fprintf(fp, m, format) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
int mgsl_matrix_fscanf(const char *filename, gsl_matrix *m)
{
FILE *fp;
if((fp = fopen(filename, "r")) == NULL) return GSL_EFAILED;
if(gsl_matrix_fscanf(fp, m) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
int mgsl_matrix_float_fwrite(const char *filename, const gsl_matrix_float *m)
{
FILE *fp;
if((fp = fopen(filename, "w")) == NULL) return GSL_EFAILED;
if(gsl_matrix_float_fwrite(fp, m) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
int mgsl_matrix_float_fread(const char *filename, gsl_matrix_float *m)
{
FILE *fp;
if((fp = fopen(filename, "r")) == NULL) return GSL_EFAILED;
if(gsl_matrix_float_fread(fp, m) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
int mgsl_matrix_float_fprintf(const char *filename, const gsl_matrix_float *m, const char *format)
{
FILE *fp;
if((fp = fopen(filename, "w")) == NULL) return GSL_EFAILED;
if(gsl_matrix_float_fprintf(fp, m, format) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
int mgsl_matrix_float_fscanf(const char *filename, gsl_matrix_float *m)
{
FILE *fp;
if((fp = fopen(filename, "r")) == NULL) return GSL_EFAILED;
if(gsl_matrix_float_fscanf(fp, m) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
int mgsl_matrix_int_fwrite(const char *filename, const gsl_matrix_int *m)
{
FILE *fp;
if((fp = fopen(filename, "w")) == NULL) return GSL_EFAILED;
if(gsl_matrix_int_fwrite(fp, m) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
int mgsl_matrix_int_fread(const char *filename, gsl_matrix_int *m)
{
FILE *fp;
if((fp = fopen(filename, "r")) == NULL) return GSL_EFAILED;
if(gsl_matrix_int_fread(fp, m) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
int mgsl_matrix_int_fprintf(const char *filename, const gsl_matrix_int *m, const char *format)
{
FILE *fp;
if((fp = fopen(filename, "w")) == NULL) return GSL_EFAILED;
if(gsl_matrix_int_fprintf(fp, m, format) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
int mgsl_matrix_int_fscanf(const char *filename, gsl_matrix_int *m)
{
FILE *fp;
if((fp = fopen(filename, "r")) == NULL) return GSL_EFAILED;
if(gsl_matrix_int_fscanf(fp, m) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
int mgsl_matrix_uint_fwrite(const char *filename, const gsl_matrix_uint *m)
{
FILE *fp;
if((fp = fopen(filename, "w")) == NULL) return GSL_EFAILED;
if(gsl_matrix_uint_fwrite(fp, m) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
int mgsl_matrix_uint_fread(const char *filename, gsl_matrix_uint *m)
{
FILE *fp;
if((fp = fopen(filename, "r")) == NULL) return GSL_EFAILED;
if(gsl_matrix_uint_fread(fp, m) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
int mgsl_matrix_uint_fprintf(const char *filename, const gsl_matrix_uint *m, const char *format)
{
FILE *fp;
if((fp = fopen(filename, "w")) == NULL) return GSL_EFAILED;
if(gsl_matrix_uint_fprintf(fp, m, format) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
int mgsl_matrix_uint_fscanf(const char *filename, gsl_matrix_uint *m)
{
FILE *fp;
if((fp = fopen(filename, "r")) == NULL) return GSL_EFAILED;
if(gsl_matrix_uint_fscanf(fp, m) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
int mgsl_matrix_long_fwrite(const char *filename, const gsl_matrix_long *m)
{
FILE *fp;
if((fp = fopen(filename, "w")) == NULL) return GSL_EFAILED;
if(gsl_matrix_long_fwrite(fp, m) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
int mgsl_matrix_long_fread(const char *filename, gsl_matrix_long *m)
{
FILE *fp;
if((fp = fopen(filename, "r")) == NULL) return GSL_EFAILED;
if(gsl_matrix_long_fread(fp, m) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
int mgsl_matrix_long_fprintf(const char *filename, const gsl_matrix_long *m, const char *format)
{
FILE *fp;
if((fp = fopen(filename, "w")) == NULL) return GSL_EFAILED;
if(gsl_matrix_long_fprintf(fp, m, format) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
int mgsl_matrix_long_fscanf(const char *filename, gsl_matrix_long *m)
{
FILE *fp;
if((fp = fopen(filename, "r")) == NULL) return GSL_EFAILED;
if(gsl_matrix_long_fscanf(fp, m) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
int mgsl_matrix_ulong_fwrite(const char *filename, const gsl_matrix_ulong *m)
{
FILE *fp;
if((fp = fopen(filename, "w")) == NULL) return GSL_EFAILED;
if(gsl_matrix_ulong_fwrite(fp, m) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
int mgsl_matrix_ulong_fread(const char *filename, gsl_matrix_ulong *m)
{
FILE *fp;
if((fp = fopen(filename, "r")) == NULL) return GSL_EFAILED;
if(gsl_matrix_ulong_fread(fp, m) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
int mgsl_matrix_ulong_fprintf(const char *filename, const gsl_matrix_ulong *m, const char *format)
{
FILE *fp;
if((fp = fopen(filename, "w")) == NULL) return GSL_EFAILED;
if(gsl_matrix_ulong_fprintf(fp, m, format) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
int mgsl_matrix_ulong_fscanf(const char *filename, gsl_matrix_ulong *m)
{
FILE *fp;
if((fp = fopen(filename, "r")) == NULL) return GSL_EFAILED;
if(gsl_matrix_ulong_fscanf(fp, m) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
int mgsl_matrix_short_fwrite(const char *filename, const gsl_matrix_short *m)
{
FILE *fp;
if((fp = fopen(filename, "w")) == NULL) return GSL_EFAILED;
if(gsl_matrix_short_fwrite(fp, m) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
int mgsl_matrix_short_fread(const char *filename, gsl_matrix_short *m)
{
FILE *fp;
if((fp = fopen(filename, "r")) == NULL) return GSL_EFAILED;
if(gsl_matrix_short_fread(fp, m) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
int mgsl_matrix_short_fprintf(const char *filename, const gsl_matrix_short *m, const char *format)
{
FILE *fp;
if((fp = fopen(filename, "w")) == NULL) return GSL_EFAILED;
if(gsl_matrix_short_fprintf(fp, m, format) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
int mgsl_matrix_short_fscanf(const char *filename, gsl_matrix_short *m)
{
FILE *fp;
if((fp = fopen(filename, "r")) == NULL) return GSL_EFAILED;
if(gsl_matrix_short_fscanf(fp, m) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
int mgsl_matrix_ushort_fwrite(const char *filename, const gsl_matrix_ushort *m)
{
FILE *fp;
if((fp = fopen(filename, "w")) == NULL) return GSL_EFAILED;
if(gsl_matrix_ushort_fwrite(fp, m) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
int mgsl_matrix_ushort_fread(const char *filename, gsl_matrix_ushort *m)
{
FILE *fp;
if((fp = fopen(filename, "r")) == NULL) return GSL_EFAILED;
if(gsl_matrix_ushort_fread(fp, m) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
int mgsl_matrix_ushort_fprintf(const char *filename, const gsl_matrix_ushort *m, const char *format)
{
FILE *fp;
if((fp = fopen(filename, "w")) == NULL) return GSL_EFAILED;
if(gsl_matrix_ushort_fprintf(fp, m, format) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
int mgsl_matrix_ushort_fscanf(const char *filename, gsl_matrix_ushort *m)
{
FILE *fp;
if((fp = fopen(filename, "r")) == NULL) return GSL_EFAILED;
if(gsl_matrix_ushort_fscanf(fp, m) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
int mgsl_matrix_char_fwrite(const char *filename, const gsl_matrix_char *m)
{
FILE *fp;
if((fp = fopen(filename, "w")) == NULL) return GSL_EFAILED;
if(gsl_matrix_char_fwrite(fp, m) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
int mgsl_matrix_char_fread(const char *filename, gsl_matrix_char *m)
{
FILE *fp;
if((fp = fopen(filename, "r")) == NULL) return GSL_EFAILED;
if(gsl_matrix_char_fread(fp, m) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
int mgsl_matrix_char_fprintf(const char *filename, const gsl_matrix_char *m, const char *format)
{
FILE *fp;
if((fp = fopen(filename, "w")) == NULL) return GSL_EFAILED;
if(gsl_matrix_char_fprintf(fp, m, format) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
int mgsl_matrix_char_fscanf(const char *filename, gsl_matrix_char *m)
{
FILE *fp;
if((fp = fopen(filename, "r")) == NULL) return GSL_EFAILED;
if(gsl_matrix_char_fscanf(fp, m) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
int mgsl_matrix_uchar_fwrite(const char *filename, const gsl_matrix_uchar *m)
{
FILE *fp;
if((fp = fopen(filename, "w")) == NULL) return GSL_EFAILED;
if(gsl_matrix_uchar_fwrite(fp, m) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
int mgsl_matrix_uchar_fread(const char *filename, gsl_matrix_uchar *m)
{
FILE *fp;
if((fp = fopen(filename, "r")) == NULL) return GSL_EFAILED;
if(gsl_matrix_uchar_fread(fp, m) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
int mgsl_matrix_uchar_fprintf(const char *filename, const gsl_matrix_uchar *m, const char *format)
{
FILE *fp;
if((fp = fopen(filename, "w")) == NULL) return GSL_EFAILED;
if(gsl_matrix_uchar_fprintf(fp, m, format) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
int mgsl_matrix_uchar_fscanf(const char *filename, gsl_matrix_uchar *m)
{
FILE *fp;
if((fp = fopen(filename, "r")) == NULL) return GSL_EFAILED;
if(gsl_matrix_uchar_fscanf(fp, m) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
int mgsl_matrix_complex_fwrite(const char *filename, const gsl_matrix_complex *m)
{
FILE *fp;
if((fp = fopen(filename, "w")) == NULL) return GSL_EFAILED;
if(gsl_matrix_complex_fwrite(fp, m) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
int mgsl_matrix_complex_fread(const char *filename, gsl_matrix_complex *m)
{
FILE *fp;
if((fp = fopen(filename, "r")) == NULL) return GSL_EFAILED;
if(gsl_matrix_complex_fread(fp, m) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
int mgsl_matrix_complex_fprintf(const char *filename, const gsl_matrix_complex *m, const char *format)
{
FILE *fp;
if((fp = fopen(filename, "w")) == NULL) return GSL_EFAILED;
if(gsl_matrix_complex_fprintf(fp, m, format) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
int mgsl_matrix_complex_fscanf(const char *filename, gsl_matrix_complex *m)
{
FILE *fp;
if((fp = fopen(filename, "r")) == NULL) return GSL_EFAILED;
if(gsl_matrix_complex_fscanf(fp, m) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
int mgsl_matrix_complex_float_fwrite(const char *filename, const gsl_matrix_complex_float *m)
{
FILE *fp;
if((fp = fopen(filename, "w")) == NULL) return GSL_EFAILED;
if(gsl_matrix_complex_float_fwrite(fp, m) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
int mgsl_matrix_complex_float_fread(const char *filename, gsl_matrix_complex_float *m)
{
FILE *fp;
if((fp = fopen(filename, "r")) == NULL) return GSL_EFAILED;
if(gsl_matrix_complex_float_fread(fp, m) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
int mgsl_matrix_complex_float_fprintf(const char *filename, const gsl_matrix_complex_float *m, const char *format)
{
FILE *fp;
if((fp = fopen(filename, "w")) == NULL) return GSL_EFAILED;
if(gsl_matrix_complex_float_fprintf(fp, m, format) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
int mgsl_matrix_complex_float_fscanf(const char *filename, gsl_matrix_complex_float *m)
{
FILE *fp;
if((fp = fopen(filename, "r")) == NULL) return GSL_EFAILED;
if(gsl_matrix_complex_float_fscanf(fp, m) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
/* Matrix view */
gsl_matrix_view *alloc_gsl_matrix_view(void)
{
gsl_matrix_view *m = calloc(1, sizeof(gsl_matrix_view));
return m;
}
void free_gsl_matrix_view(gsl_matrix_view *m)
{
if(m != NULL){
free(m);
m = NULL;
}
}
gsl_matrix *mgsl_matrix_submatrix(gsl_matrix_view *view, gsl_matrix *m, size_t k1, size_t k2, size_t n1, size_t n2)
{
*view = gsl_matrix_submatrix(m, k1, k2, n1, n2);
return &view->matrix;
}
gsl_matrix *mgsl_matrix_view_array(gsl_matrix_view *view, double *base, size_t n1, size_t n2)
{
*view = gsl_matrix_view_array(base, n1, n2);
return &view->matrix;
}
gsl_matrix *mgsl_matrix_view_array_with_tda(gsl_matrix_view *view, double *base, size_t n1, size_t n2, size_t tda)
{
*view = gsl_matrix_view_array_with_tda(base, n1, n2, tda);
return &view->matrix;
}
gsl_matrix *mgsl_matrix_view_vector(gsl_matrix_view *view, gsl_vector *v, size_t n1, size_t n2)
{
*view = gsl_matrix_view_vector(v, n1, n2);
return &view->matrix;
}
gsl_matrix *mgsl_matrix_view_vector_with_tda(gsl_matrix_view *view, gsl_vector *v, size_t n1, size_t n2, size_t tda)
{
*view = gsl_matrix_view_vector_with_tda(v, n1, n2, tda);
return &view->matrix;
}
gsl_matrix_float_view *alloc_gsl_matrix_float_view(void)
{
gsl_matrix_float_view *m = calloc(1, sizeof(gsl_matrix_float_view));
return m;
}
void free_gsl_matrix_float_view(gsl_matrix_float_view *m)
{
if(m != NULL){
free(m);
m = NULL;
}
}
gsl_matrix_float *mgsl_matrix_float_submatrix(gsl_matrix_float_view *view, gsl_matrix_float *m, size_t k1, size_t k2, size_t n1, size_t n2)
{
*view = gsl_matrix_float_submatrix(m, k1, k2, n1, n2);
return &view->matrix;
}
gsl_matrix_float *mgsl_matrix_float_view_array(gsl_matrix_float_view *view, float *base, size_t n1, size_t n2)
{
*view = gsl_matrix_float_view_array(base, n1, n2);
return &view->matrix;
}
gsl_matrix_float *mgsl_matrix_float_view_array_with_tda(gsl_matrix_float_view *view, float *base, size_t n1, size_t n2, size_t tda)
{
*view = gsl_matrix_float_view_array_with_tda(base, n1, n2, tda);
return &view->matrix;
}
gsl_matrix_float *mgsl_matrix_float_view_vector(gsl_matrix_float_view *view, gsl_vector_float *v, size_t n1, size_t n2)
{
*view = gsl_matrix_float_view_vector(v, n1, n2);
return &view->matrix;
}
gsl_matrix_float *mgsl_matrix_float_view_vector_with_tda(gsl_matrix_float_view *view, gsl_vector_float *v, size_t n1, size_t n2, size_t tda)
{
*view = gsl_matrix_float_view_vector_with_tda(v, n1, n2, tda);
return &view->matrix;
}
gsl_matrix_int_view *alloc_gsl_matrix_int_view(void)
{
gsl_matrix_int_view *m = calloc(1, sizeof(gsl_matrix_int_view));
return m;
}
void free_gsl_matrix_int_view(gsl_matrix_int_view *m)
{
if(m != NULL){
free(m);
m = NULL;
}
}
gsl_matrix_int *mgsl_matrix_int_submatrix(gsl_matrix_int_view *view, gsl_matrix_int *m, size_t k1, size_t k2, size_t n1, size_t n2)
{
*view = gsl_matrix_int_submatrix(m, k1, k2, n1, n2);
return &view->matrix;
}
gsl_matrix_int *mgsl_matrix_int_view_array(gsl_matrix_int_view *view, int *base, size_t n1, size_t n2)
{
*view = gsl_matrix_int_view_array(base, n1, n2);
return &view->matrix;
}
gsl_matrix_int *mgsl_matrix_int_view_array_with_tda(gsl_matrix_int_view *view, int *base, size_t n1, size_t n2, size_t tda)
{
*view = gsl_matrix_int_view_array_with_tda(base, n1, n2, tda);
return &view->matrix;
}
gsl_matrix_int *mgsl_matrix_int_view_vector(gsl_matrix_int_view *view, gsl_vector_int *v, size_t n1, size_t n2)
{
*view = gsl_matrix_int_view_vector(v, n1, n2);
return &view->matrix;
}
gsl_matrix_int *mgsl_matrix_int_view_vector_with_tda(gsl_matrix_int_view *view, gsl_vector_int *v, size_t n1, size_t n2, size_t tda)
{
*view = gsl_matrix_int_view_vector_with_tda(v, n1, n2, tda);
return &view->matrix;
}
gsl_matrix_uint_view *alloc_gsl_matrix_uint_view(void)
{
gsl_matrix_uint_view *m = calloc(1, sizeof(gsl_matrix_uint_view));
return m;
}
void free_gsl_matrix_uint_view(gsl_matrix_uint_view *m)
{
if(m != NULL){
free(m);
m = NULL;
}
}
gsl_matrix_uint *mgsl_matrix_uint_submatrix(gsl_matrix_uint_view *view, gsl_matrix_uint *m, size_t k1, size_t k2, size_t n1, size_t n2)
{
*view = gsl_matrix_uint_submatrix(m, k1, k2, n1, n2);
return &view->matrix;
}
gsl_matrix_uint *mgsl_matrix_uint_view_array(gsl_matrix_uint_view *view, unsigned int *base, size_t n1, size_t n2)
{
*view = gsl_matrix_uint_view_array(base, n1, n2);
return &view->matrix;
}
gsl_matrix_uint *mgsl_matrix_uint_view_array_with_tda(gsl_matrix_uint_view *view, unsigned int *base, size_t n1, size_t n2, size_t tda)
{
*view = gsl_matrix_uint_view_array_with_tda(base, n1, n2, tda);
return &view->matrix;
}
gsl_matrix_uint *mgsl_matrix_uint_view_vector(gsl_matrix_uint_view *view, gsl_vector_uint *v, size_t n1, size_t n2)
{
*view = gsl_matrix_uint_view_vector(v, n1, n2);
return &view->matrix;
}
gsl_matrix_uint *mgsl_matrix_uint_view_vector_with_tda(gsl_matrix_uint_view *view, gsl_vector_uint *v, size_t n1, size_t n2, size_t tda)
{
*view = gsl_matrix_uint_view_vector_with_tda(v, n1, n2, tda);
return &view->matrix;
}
gsl_matrix_long_view *alloc_gsl_matrix_long_view(void)
{
gsl_matrix_long_view *m = calloc(1, sizeof(gsl_matrix_long_view));
return m;
}
void free_gsl_matrix_long_view(gsl_matrix_long_view *m)
{
if(m != NULL){
free(m);
m = NULL;
}
}
gsl_matrix_long *mgsl_matrix_long_submatrix(gsl_matrix_long_view *view, gsl_matrix_long *m, size_t k1, size_t k2, size_t n1, size_t n2)
{
*view = gsl_matrix_long_submatrix(m, k1, k2, n1, n2);
return &view->matrix;
}
gsl_matrix_long *mgsl_matrix_long_view_array(gsl_matrix_long_view *view, long *base, size_t n1, size_t n2)
{
*view = gsl_matrix_long_view_array(base, n1, n2);
return &view->matrix;
}
gsl_matrix_long *mgsl_matrix_long_view_array_with_tda(gsl_matrix_long_view *view, long *base, size_t n1, size_t n2, size_t tda)
{
*view = gsl_matrix_long_view_array_with_tda(base, n1, n2, tda);
return &view->matrix;
}
gsl_matrix_long *mgsl_matrix_long_view_vector(gsl_matrix_long_view *view, gsl_vector_long *v, size_t n1, size_t n2)
{
*view = gsl_matrix_long_view_vector(v, n1, n2);
return &view->matrix;
}
gsl_matrix_long *mgsl_matrix_long_view_vector_with_tda(gsl_matrix_long_view *view, gsl_vector_long *v, size_t n1, size_t n2, size_t tda)
{
*view = gsl_matrix_long_view_vector_with_tda(v, n1, n2, tda);
return &view->matrix;
}
gsl_matrix_ulong_view *alloc_gsl_matrix_ulong_view(void)
{
gsl_matrix_ulong_view *m = calloc(1, sizeof(gsl_matrix_ulong_view));
return m;
}
void free_gsl_matrix_ulong_view(gsl_matrix_ulong_view *m)
{
if(m != NULL){
free(m);
m = NULL;
}
}
gsl_matrix_ulong *mgsl_matrix_ulong_submatrix(gsl_matrix_ulong_view *view, gsl_matrix_ulong *m, size_t k1, size_t k2, size_t n1, size_t n2)
{
*view = gsl_matrix_ulong_submatrix(m, k1, k2, n1, n2);
return &view->matrix;
}
gsl_matrix_ulong *mgsl_matrix_ulong_view_array(gsl_matrix_ulong_view *view, unsigned long *base, size_t n1, size_t n2)
{
*view = gsl_matrix_ulong_view_array(base, n1, n2);
return &view->matrix;
}
gsl_matrix_ulong *mgsl_matrix_ulong_view_array_with_tda(gsl_matrix_ulong_view *view, unsigned long *base, size_t n1, size_t n2, size_t tda)
{
*view = gsl_matrix_ulong_view_array_with_tda(base, n1, n2, tda);
return &view->matrix;
}
gsl_matrix_ulong *mgsl_matrix_ulong_view_vector(gsl_matrix_ulong_view *view, gsl_vector_ulong *v, size_t n1, size_t n2)
{
*view = gsl_matrix_ulong_view_vector(v, n1, n2);
return &view->matrix;
}
gsl_matrix_ulong *mgsl_matrix_ulong_view_vector_with_tda(gsl_matrix_ulong_view *view, gsl_vector_ulong *v, size_t n1, size_t n2, size_t tda)
{
*view = gsl_matrix_ulong_view_vector_with_tda(v, n1, n2, tda);
return &view->matrix;
}
gsl_matrix_short_view *alloc_gsl_matrix_short_view(void)
{
gsl_matrix_short_view *m = calloc(1, sizeof(gsl_matrix_short_view));
return m;
}
void free_gsl_matrix_short_view(gsl_matrix_short_view *m)
{
if(m != NULL){
free(m);
m = NULL;
}
}
gsl_matrix_short *mgsl_matrix_short_submatrix(gsl_matrix_short_view *view, gsl_matrix_short *m, size_t k1, size_t k2, size_t n1, size_t n2)
{
*view = gsl_matrix_short_submatrix(m, k1, k2, n1, n2);
return &view->matrix;
}
gsl_matrix_short *mgsl_matrix_short_view_array(gsl_matrix_short_view *view, short *base, size_t n1, size_t n2)
{
*view = gsl_matrix_short_view_array(base, n1, n2);
return &view->matrix;
}
gsl_matrix_short *mgsl_matrix_short_view_array_with_tda(gsl_matrix_short_view *view, short *base, size_t n1, size_t n2, size_t tda)
{
*view = gsl_matrix_short_view_array_with_tda(base, n1, n2, tda);
return &view->matrix;
}
gsl_matrix_short *mgsl_matrix_short_view_vector(gsl_matrix_short_view *view, gsl_vector_short *v, size_t n1, size_t n2)
{
*view = gsl_matrix_short_view_vector(v, n1, n2);
return &view->matrix;
}
gsl_matrix_short *mgsl_matrix_short_view_vector_with_tda(gsl_matrix_short_view *view, gsl_vector_short *v, size_t n1, size_t n2, size_t tda)
{
*view = gsl_matrix_short_view_vector_with_tda(v, n1, n2, tda);
return &view->matrix;
}
gsl_matrix_ushort_view *alloc_gsl_matrix_ushort_view(void)
{
gsl_matrix_ushort_view *m = calloc(1, sizeof(gsl_matrix_ushort_view));
return m;
}
void free_gsl_matrix_ushort_view(gsl_matrix_ushort_view *m)
{
if(m != NULL){
free(m);
m = NULL;
}
}
gsl_matrix_ushort *mgsl_matrix_ushort_submatrix(gsl_matrix_ushort_view *view, gsl_matrix_ushort *m, size_t k1, size_t k2, size_t n1, size_t n2)
{
*view = gsl_matrix_ushort_submatrix(m, k1, k2, n1, n2);
return &view->matrix;
}
gsl_matrix_ushort *mgsl_matrix_ushort_view_array(gsl_matrix_ushort_view *view, unsigned short *base, size_t n1, size_t n2)
{
*view = gsl_matrix_ushort_view_array(base, n1, n2);
return &view->matrix;
}
gsl_matrix_ushort *mgsl_matrix_ushort_view_array_with_tda(gsl_matrix_ushort_view *view, unsigned short *base, size_t n1, size_t n2, size_t tda)
{
*view = gsl_matrix_ushort_view_array_with_tda(base, n1, n2, tda);
return &view->matrix;
}
gsl_matrix_ushort *mgsl_matrix_ushort_view_vector(gsl_matrix_ushort_view *view, gsl_vector_ushort *v, size_t n1, size_t n2)
{
*view = gsl_matrix_ushort_view_vector(v, n1, n2);
return &view->matrix;
}
gsl_matrix_ushort *mgsl_matrix_ushort_view_vector_with_tda(gsl_matrix_ushort_view *view, gsl_vector_ushort *v, size_t n1, size_t n2, size_t tda)
{
*view = gsl_matrix_ushort_view_vector_with_tda(v, n1, n2, tda);
return &view->matrix;
}
gsl_matrix_char_view *alloc_gsl_matrix_char_view(void)
{
gsl_matrix_char_view *m = calloc(1, sizeof(gsl_matrix_char_view));
return m;
}
void free_gsl_matrix_char_view(gsl_matrix_char_view *m)
{
if(m != NULL){
free(m);
m = NULL;
}
}
gsl_matrix_char *mgsl_matrix_char_submatrix(gsl_matrix_char_view *view, gsl_matrix_char *m, size_t k1, size_t k2, size_t n1, size_t n2)
{
*view = gsl_matrix_char_submatrix(m, k1, k2, n1, n2);
return &view->matrix;
}
gsl_matrix_char *mgsl_matrix_char_view_array(gsl_matrix_char_view *view, char *base, size_t n1, size_t n2)
{
*view = gsl_matrix_char_view_array(base, n1, n2);
return &view->matrix;
}
gsl_matrix_char *mgsl_matrix_char_view_array_with_tda(gsl_matrix_char_view *view, char *base, size_t n1, size_t n2, size_t tda)
{
*view = gsl_matrix_char_view_array_with_tda(base, n1, n2, tda);
return &view->matrix;
}
gsl_matrix_char *mgsl_matrix_char_view_vector(gsl_matrix_char_view *view, gsl_vector_char *v, size_t n1, size_t n2)
{
*view = gsl_matrix_char_view_vector(v, n1, n2);
return &view->matrix;
}
gsl_matrix_char *mgsl_matrix_char_view_vector_with_tda(gsl_matrix_char_view *view, gsl_vector_char *v, size_t n1, size_t n2, size_t tda)
{
*view = gsl_matrix_char_view_vector_with_tda(v, n1, n2, tda);
return &view->matrix;
}
gsl_matrix_uchar_view *alloc_gsl_matrix_uchar_view(void)
{
gsl_matrix_uchar_view *m = calloc(1, sizeof(gsl_matrix_uchar_view));
return m;
}
void free_gsl_matrix_uchar_view(gsl_matrix_uchar_view *m)
{
if(m != NULL){
free(m);
m = NULL;
}
}
gsl_matrix_uchar *mgsl_matrix_uchar_submatrix(gsl_matrix_uchar_view *view, gsl_matrix_uchar *m, size_t k1, size_t k2, size_t n1, size_t n2)
{
*view = gsl_matrix_uchar_submatrix(m, k1, k2, n1, n2);
return &view->matrix;
}
gsl_matrix_uchar *mgsl_matrix_uchar_view_array(gsl_matrix_uchar_view *view, unsigned char *base, size_t n1, size_t n2)
{
*view = gsl_matrix_uchar_view_array(base, n1, n2);
return &view->matrix;
}
gsl_matrix_uchar *mgsl_matrix_uchar_view_array_with_tda(gsl_matrix_uchar_view *view, unsigned char *base, size_t n1, size_t n2, size_t tda)
{
*view = gsl_matrix_uchar_view_array_with_tda(base, n1, n2, tda);
return &view->matrix;
}
gsl_matrix_uchar *mgsl_matrix_uchar_view_vector(gsl_matrix_uchar_view *view, gsl_vector_uchar *v, size_t n1, size_t n2)
{
*view = gsl_matrix_uchar_view_vector(v, n1, n2);
return &view->matrix;
}
gsl_matrix_uchar *mgsl_matrix_uchar_view_vector_with_tda(gsl_matrix_uchar_view *view, gsl_vector_uchar *v, size_t n1, size_t n2, size_t tda)
{
*view = gsl_matrix_uchar_view_vector_with_tda(v, n1, n2, tda);
return &view->matrix;
}
gsl_matrix_complex_view *alloc_gsl_matrix_complex_view(void)
{
gsl_matrix_complex_view *m = calloc(1, sizeof(gsl_matrix_complex_view));
return m;
}
void free_gsl_matrix_complex_view(gsl_matrix_complex_view *m)
{
if(m != NULL){
free(m);
m = NULL;
}
}
gsl_matrix_complex *mgsl_matrix_complex_submatrix(gsl_matrix_complex_view *view, gsl_matrix_complex *m, size_t k1, size_t k2, size_t n1, size_t n2)
{
*view = gsl_matrix_complex_submatrix(m, k1, k2, n1, n2);
return &view->matrix;
}
gsl_matrix_complex *mgsl_matrix_complex_view_array(gsl_matrix_complex_view *view, double *base, size_t n1, size_t n2)
{
*view = gsl_matrix_complex_view_array(base, n1, n2);
return &view->matrix;
}
gsl_matrix_complex *mgsl_matrix_complex_view_array_with_tda(gsl_matrix_complex_view *view, double *base, size_t n1, size_t n2, size_t tda)
{
*view = gsl_matrix_complex_view_array_with_tda(base, n1, n2, tda);
return &view->matrix;
}
gsl_matrix_complex *mgsl_matrix_complex_view_vector(gsl_matrix_complex_view *view, gsl_vector_complex *v, size_t n1, size_t n2)
{
*view = gsl_matrix_complex_view_vector(v, n1, n2);
return &view->matrix;
}
gsl_matrix_complex *mgsl_matrix_complex_view_vector_with_tda(gsl_matrix_complex_view *view, gsl_vector_complex *v, size_t n1, size_t n2, size_t tda)
{
*view = gsl_matrix_complex_view_vector_with_tda(v, n1, n2, tda);
return &view->matrix;
}
gsl_matrix_complex_float_view *alloc_gsl_matrix_complex_float_view(void)
{
gsl_matrix_complex_float_view *m = calloc(1, sizeof(gsl_matrix_complex_float_view));
return m;
}
void free_gsl_matrix_complex_float_view(gsl_matrix_complex_float_view *m)
{
if(m != NULL){
free(m);
m = NULL;
}
}
gsl_matrix_complex_float *mgsl_matrix_complex_float_submatrix(gsl_matrix_complex_float_view *view, gsl_matrix_complex_float *m, size_t k1, size_t k2, size_t n1, size_t n2)
{
*view = gsl_matrix_complex_float_submatrix(m, k1, k2, n1, n2);
return &view->matrix;
}
gsl_matrix_complex_float *mgsl_matrix_complex_float_view_array(gsl_matrix_complex_float_view *view, float *base, size_t n1, size_t n2)
{
*view = gsl_matrix_complex_float_view_array(base, n1, n2);
return &view->matrix;
}
gsl_matrix_complex_float *mgsl_matrix_complex_float_view_array_with_tda(gsl_matrix_complex_float_view *view, float *base, size_t n1, size_t n2, size_t tda)
{
*view = gsl_matrix_complex_float_view_array_with_tda(base, n1, n2, tda);
return &view->matrix;
}
gsl_matrix_complex_float *mgsl_matrix_complex_float_view_vector(gsl_matrix_complex_float_view *view, gsl_vector_complex_float *v, size_t n1, size_t n2)
{
*view = gsl_matrix_complex_float_view_vector(v, n1, n2);
return &view->matrix;
}
gsl_matrix_complex_float *mgsl_matrix_complex_float_view_vector_with_tda(gsl_matrix_complex_float_view *view, gsl_vector_complex_float *v, size_t n1, size_t n2, size_t tda)
{
*view = gsl_matrix_complex_float_view_vector_with_tda(v, n1, n2, tda);
return &view->matrix;
}
/* Matrix row and column view */
gsl_vector *mgsl_matrix_row(gsl_vector_view *view, gsl_matrix *m, size_t i)
{
*view = gsl_matrix_row(m, i);
return &view->vector;
}
gsl_vector_float *mgsl_matrix_float_row(gsl_vector_float_view *view, gsl_matrix_float *m, size_t i)
{
*view = gsl_matrix_float_row(m, i);
return &view->vector;
}
gsl_vector_int *mgsl_matrix_int_row(gsl_vector_int_view *view, gsl_matrix_int *m, size_t i)
{
*view = gsl_matrix_int_row(m, i);
return &view->vector;
}
gsl_vector_uint *mgsl_matrix_uint_row(gsl_vector_uint_view *view, gsl_matrix_uint *m, size_t i)
{
*view = gsl_matrix_uint_row(m, i);
return &view->vector;
}
gsl_vector_long *mgsl_matrix_long_row(gsl_vector_long_view *view, gsl_matrix_long *m, size_t i)
{
*view = gsl_matrix_long_row(m, i);
return &view->vector;
}
gsl_vector_ulong *mgsl_matrix_ulong_row(gsl_vector_ulong_view *view, gsl_matrix_ulong *m, size_t i)
{
*view = gsl_matrix_ulong_row(m, i);
return &view->vector;
}
gsl_vector_short *mgsl_matrix_short_row(gsl_vector_short_view *view, gsl_matrix_short *m, size_t i)
{
*view = gsl_matrix_short_row(m, i);
return &view->vector;
}
gsl_vector_ushort *mgsl_matrix_ushort_row(gsl_vector_ushort_view *view, gsl_matrix_ushort *m, size_t i)
{
*view = gsl_matrix_ushort_row(m, i);
return &view->vector;
}
gsl_vector_char *mgsl_matrix_char_row(gsl_vector_char_view *view, gsl_matrix_char *m, size_t i)
{
*view = gsl_matrix_char_row(m, i);
return &view->vector;
}
gsl_vector_uchar *mgsl_matrix_uchar_row(gsl_vector_uchar_view *view, gsl_matrix_uchar *m, size_t i)
{
*view = gsl_matrix_uchar_row(m, i);
return &view->vector;
}
gsl_vector_complex *mgsl_matrix_complex_row(gsl_vector_complex_view *view, gsl_matrix_complex *m, size_t i)
{
*view = gsl_matrix_complex_row(m, i);
return &view->vector;
}
gsl_vector_complex_float *mgsl_matrix_complex_float_row(gsl_vector_complex_float_view *view, gsl_matrix_complex_float *m, size_t i)
{
*view = gsl_matrix_complex_float_row(m, i);
return &view->vector;
}
gsl_vector *mgsl_matrix_column(gsl_vector_view *view, gsl_matrix *m, size_t j)
{
*view = gsl_matrix_column(m, j);
return &view->vector;
}
gsl_vector_float *mgsl_matrix_float_column(gsl_vector_float_view *view, gsl_matrix_float *m, size_t j)
{
*view = gsl_matrix_float_column(m, j);
return &view->vector;
}
gsl_vector_int *mgsl_matrix_int_column(gsl_vector_int_view *view, gsl_matrix_int *m, size_t j)
{
*view = gsl_matrix_int_column(m, j);
return &view->vector;
}
gsl_vector_uint *mgsl_matrix_uint_column(gsl_vector_uint_view *view, gsl_matrix_uint *m, size_t j)
{
*view = gsl_matrix_uint_column(m, j);
return &view->vector;
}
gsl_vector_long *mgsl_matrix_long_column(gsl_vector_long_view *view, gsl_matrix_long *m, size_t j)
{
*view = gsl_matrix_long_column(m, j);
return &view->vector;
}
gsl_vector_ulong *mgsl_matrix_ulong_column(gsl_vector_ulong_view *view, gsl_matrix_ulong *m, size_t j)
{
*view = gsl_matrix_ulong_column(m, j);
return &view->vector;
}
gsl_vector_short *mgsl_matrix_short_column(gsl_vector_short_view *view, gsl_matrix_short *m, size_t j)
{
*view = gsl_matrix_short_column(m, j);
return &view->vector;
}
gsl_vector_ushort *mgsl_matrix_ushort_column(gsl_vector_ushort_view *view, gsl_matrix_ushort *m, size_t j)
{
*view = gsl_matrix_ushort_column(m, j);
return &view->vector;
}
gsl_vector_char *mgsl_matrix_char_column(gsl_vector_char_view *view, gsl_matrix_char *m, size_t j)
{
*view = gsl_matrix_char_column(m, j);
return &view->vector;
}
gsl_vector_uchar *mgsl_matrix_uchar_column(gsl_vector_uchar_view *view, gsl_matrix_uchar *m, size_t j)
{
*view = gsl_matrix_uchar_column(m, j);
return &view->vector;
}
gsl_vector_complex *mgsl_matrix_complex_column(gsl_vector_complex_view *view, gsl_matrix_complex *m, size_t j)
{
*view = gsl_matrix_complex_column(m, j);
return &view->vector;
}
gsl_vector_complex_float *mgsl_matrix_complex_float_column(gsl_vector_complex_float_view *view, gsl_matrix_complex_float *m, size_t j)
{
*view = gsl_matrix_complex_float_column(m, j);
return &view->vector;
}
gsl_vector *mgsl_matrix_subrow(gsl_vector_view *view, gsl_matrix *m, size_t i, size_t offset, size_t n)
{
*view = gsl_matrix_subrow(m, i, offset, n);
return &view->vector;
}
gsl_vector_float *mgsl_matrix_float_subrow(gsl_vector_float_view *view, gsl_matrix_float *m, size_t i, size_t offset, size_t n)
{
*view = gsl_matrix_float_subrow(m, i, offset, n);
return &view->vector;
}
gsl_vector_int *mgsl_matrix_int_subrow(gsl_vector_int_view *view, gsl_matrix_int *m, size_t i, size_t offset, size_t n)
{
*view = gsl_matrix_int_subrow(m, i, offset, n);
return &view->vector;
}
gsl_vector_uint *mgsl_matrix_uint_subrow(gsl_vector_uint_view *view, gsl_matrix_uint *m, size_t i, size_t offset, size_t n)
{
*view = gsl_matrix_uint_subrow(m, i, offset, n);
return &view->vector;
}
gsl_vector_long *mgsl_matrix_long_subrow(gsl_vector_long_view *view, gsl_matrix_long *m, size_t i, size_t offset, size_t n)
{
*view = gsl_matrix_long_subrow(m, i, offset, n);
return &view->vector;
}
gsl_vector_ulong *mgsl_matrix_ulong_subrow(gsl_vector_ulong_view *view, gsl_matrix_ulong *m, size_t i, size_t offset, size_t n)
{
*view = gsl_matrix_ulong_subrow(m, i, offset, n);
return &view->vector;
}
gsl_vector_short *mgsl_matrix_short_subrow(gsl_vector_short_view *view, gsl_matrix_short *m, size_t i, size_t offset, size_t n)
{
*view = gsl_matrix_short_subrow(m, i, offset, n);
return &view->vector;
}
gsl_vector_ushort *mgsl_matrix_ushort_subrow(gsl_vector_ushort_view *view, gsl_matrix_ushort *m, size_t i, size_t offset, size_t n)
{
*view = gsl_matrix_ushort_subrow(m, i, offset, n);
return &view->vector;
}
gsl_vector_char *mgsl_matrix_char_subrow(gsl_vector_char_view *view, gsl_matrix_char *m, size_t i, size_t offset, size_t n)
{
*view = gsl_matrix_char_subrow(m, i, offset, n);
return &view->vector;
}
gsl_vector_uchar *mgsl_matrix_uchar_subrow(gsl_vector_uchar_view *view, gsl_matrix_uchar *m, size_t i, size_t offset, size_t n)
{
*view = gsl_matrix_uchar_subrow(m, i, offset, n);
return &view->vector;
}
gsl_vector_complex *mgsl_matrix_complex_subrow(gsl_vector_complex_view *view, gsl_matrix_complex *m, size_t i, size_t offset, size_t n)
{
*view = gsl_matrix_complex_subrow(m, i, offset, n);
return &view->vector;
}
gsl_vector_complex_float *mgsl_matrix_complex_float_subrow(gsl_vector_complex_float_view *view, gsl_matrix_complex_float *m, size_t i, size_t offset, size_t n)
{
*view = gsl_matrix_complex_float_subrow(m, i, offset, n);
return &view->vector;
}
gsl_vector *mgsl_matrix_subcolumn(gsl_vector_view *view, gsl_matrix *m, size_t j, size_t offset, size_t n)
{
*view = gsl_matrix_subcolumn(m, j, offset, n);
return &view->vector;
}
gsl_vector_float *mgsl_matrix_float_subcolumn(gsl_vector_float_view *view, gsl_matrix_float *m, size_t j, size_t offset, size_t n)
{
*view = gsl_matrix_float_subcolumn(m, j, offset, n);
return &view->vector;
}
gsl_vector_int *mgsl_matrix_int_subcolumn(gsl_vector_int_view *view, gsl_matrix_int *m, size_t j, size_t offset, size_t n)
{
*view = gsl_matrix_int_subcolumn(m, j, offset, n);
return &view->vector;
}
gsl_vector_uint *mgsl_matrix_uint_subcolumn(gsl_vector_uint_view *view, gsl_matrix_uint *m, size_t j, size_t offset, size_t n)
{
*view = gsl_matrix_uint_subcolumn(m, j, offset, n);
return &view->vector;
}
gsl_vector_long *mgsl_matrix_long_subcolumn(gsl_vector_long_view *view, gsl_matrix_long *m, size_t j, size_t offset, size_t n)
{
*view = gsl_matrix_long_subcolumn(m, j, offset, n);
return &view->vector;
}
gsl_vector_ulong *mgsl_matrix_ulong_subcolumn(gsl_vector_ulong_view *view, gsl_matrix_ulong *m, size_t j, size_t offset, size_t n)
{
*view = gsl_matrix_ulong_subcolumn(m, j, offset, n);
return &view->vector;
}
gsl_vector_short *mgsl_matrix_short_subcolumn(gsl_vector_short_view *view, gsl_matrix_short *m, size_t j, size_t offset, size_t n)
{
*view = gsl_matrix_short_subcolumn(m, j, offset, n);
return &view->vector;
}
gsl_vector_ushort *mgsl_matrix_ushort_subcolumn(gsl_vector_ushort_view *view, gsl_matrix_ushort *m, size_t j, size_t offset, size_t n)
{
*view = gsl_matrix_ushort_subcolumn(m, j, offset, n);
return &view->vector;
}
gsl_vector_char *mgsl_matrix_char_subcolumn(gsl_vector_char_view *view, gsl_matrix_char *m, size_t j, size_t offset, size_t n)
{
*view = gsl_matrix_char_subcolumn(m, j, offset, n);
return &view->vector;
}
gsl_vector_uchar *mgsl_matrix_uchar_subcolumn(gsl_vector_uchar_view *view, gsl_matrix_uchar *m, size_t j, size_t offset, size_t n)
{
*view = gsl_matrix_uchar_subcolumn(m, j, offset, n);
return &view->vector;
}
gsl_vector_complex *mgsl_matrix_complex_subcolumn(gsl_vector_complex_view *view, gsl_matrix_complex *m, size_t j, size_t offset, size_t n)
{
*view = gsl_matrix_complex_subcolumn(m, j, offset, n);
return &view->vector;
}
gsl_vector_complex_float *mgsl_matrix_complex_float_subcolumn(gsl_vector_complex_float_view *view, gsl_matrix_complex_float *m, size_t j, size_t offset, size_t n)
{
*view = gsl_matrix_complex_float_subcolumn(m, j, offset, n);
return &view->vector;
}
gsl_vector *mgsl_matrix_diagonal(gsl_vector_view *view, gsl_matrix *m)
{
*view = gsl_matrix_diagonal(m);
return &view->vector;
}
gsl_vector_float *mgsl_matrix_float_diagonal(gsl_vector_float_view *view, gsl_matrix_float *m)
{
*view = gsl_matrix_float_diagonal(m);
return &view->vector;
}
gsl_vector_int *mgsl_matrix_int_diagonal(gsl_vector_int_view *view, gsl_matrix_int *m)
{
*view = gsl_matrix_int_diagonal(m);
return &view->vector;
}
gsl_vector_uint *mgsl_matrix_uint_diagonal(gsl_vector_uint_view *view, gsl_matrix_uint *m)
{
*view = gsl_matrix_uint_diagonal(m);
return &view->vector;
}
gsl_vector_long *mgsl_matrix_long_diagonal(gsl_vector_long_view *view, gsl_matrix_long *m)
{
*view = gsl_matrix_long_diagonal(m);
return &view->vector;
}
gsl_vector_ulong *mgsl_matrix_ulong_diagonal(gsl_vector_ulong_view *view, gsl_matrix_ulong *m)
{
*view = gsl_matrix_ulong_diagonal(m);
return &view->vector;
}
gsl_vector_short *mgsl_matrix_short_diagonal(gsl_vector_short_view *view, gsl_matrix_short *m)
{
*view = gsl_matrix_short_diagonal(m);
return &view->vector;
}
gsl_vector_ushort *mgsl_matrix_ushort_diagonal(gsl_vector_ushort_view *view, gsl_matrix_ushort *m)
{
*view = gsl_matrix_ushort_diagonal(m);
return &view->vector;
}
gsl_vector_char *mgsl_matrix_char_diagonal(gsl_vector_char_view *view, gsl_matrix_char *m)
{
*view = gsl_matrix_char_diagonal(m);
return &view->vector;
}
gsl_vector_uchar *mgsl_matrix_uchar_diagonal(gsl_vector_uchar_view *view, gsl_matrix_uchar *m)
{
*view = gsl_matrix_uchar_diagonal(m);
return &view->vector;
}
gsl_vector_complex *mgsl_matrix_complex_diagonal(gsl_vector_complex_view *view, gsl_matrix_complex *m)
{
*view = gsl_matrix_complex_diagonal(m);
return &view->vector;
}
gsl_vector_complex_float *mgsl_matrix_complex_float_diagonal(gsl_vector_complex_float_view *view, gsl_matrix_complex_float *m)
{
*view = gsl_matrix_complex_float_diagonal(m);
return &view->vector;
}
gsl_vector *mgsl_matrix_subdiagonal(gsl_vector_view *view, gsl_matrix *m, size_t k)
{
*view = gsl_matrix_subdiagonal(m, k);
return &view->vector;
}
gsl_vector_float *mgsl_matrix_float_subdiagonal(gsl_vector_float_view *view, gsl_matrix_float *m, size_t k)
{
*view = gsl_matrix_float_subdiagonal(m, k);
return &view->vector;
}
gsl_vector_int *mgsl_matrix_int_subdiagonal(gsl_vector_int_view *view, gsl_matrix_int *m, size_t k)
{
*view = gsl_matrix_int_subdiagonal(m, k);
return &view->vector;
}
gsl_vector_uint *mgsl_matrix_uint_subdiagonal(gsl_vector_uint_view *view, gsl_matrix_uint *m, size_t k)
{
*view = gsl_matrix_uint_subdiagonal(m, k);
return &view->vector;
}
gsl_vector_long *mgsl_matrix_long_subdiagonal(gsl_vector_long_view *view, gsl_matrix_long *m, size_t k)
{
*view = gsl_matrix_long_subdiagonal(m, k);
return &view->vector;
}
gsl_vector_ulong *mgsl_matrix_ulong_subdiagonal(gsl_vector_ulong_view *view, gsl_matrix_ulong *m, size_t k)
{
*view = gsl_matrix_ulong_subdiagonal(m, k);
return &view->vector;
}
gsl_vector_short *mgsl_matrix_short_subdiagonal(gsl_vector_short_view *view, gsl_matrix_short *m, size_t k)
{
*view = gsl_matrix_short_subdiagonal(m, k);
return &view->vector;
}
gsl_vector_ushort *mgsl_matrix_ushort_subdiagonal(gsl_vector_ushort_view *view, gsl_matrix_ushort *m, size_t k)
{
*view = gsl_matrix_ushort_subdiagonal(m, k);
return &view->vector;
}
gsl_vector_char *mgsl_matrix_char_subdiagonal(gsl_vector_char_view *view, gsl_matrix_char *m, size_t k)
{
*view = gsl_matrix_char_subdiagonal(m, k);
return &view->vector;
}
gsl_vector_uchar *mgsl_matrix_uchar_subdiagonal(gsl_vector_uchar_view *view, gsl_matrix_uchar *m, size_t k)
{
*view = gsl_matrix_uchar_subdiagonal(m, k);
return &view->vector;
}
gsl_vector_complex *mgsl_matrix_complex_subdiagonal(gsl_vector_complex_view *view, gsl_matrix_complex *m, size_t k)
{
*view = gsl_matrix_complex_subdiagonal(m, k);
return &view->vector;
}
gsl_vector_complex_float *mgsl_matrix_complex_float_subdiagonal(gsl_vector_complex_float_view *view, gsl_matrix_complex_float *m, size_t k)
{
*view = gsl_matrix_complex_float_subdiagonal(m, k);
return &view->vector;
}
gsl_vector *mgsl_matrix_superdiagonal(gsl_vector_view *view, gsl_matrix *m, size_t k)
{
*view = gsl_matrix_superdiagonal(m, k);
return &view->vector;
}
gsl_vector_float *mgsl_matrix_float_superdiagonal(gsl_vector_float_view *view, gsl_matrix_float *m, size_t k)
{
*view = gsl_matrix_float_superdiagonal(m, k);
return &view->vector;
}
gsl_vector_int *mgsl_matrix_int_superdiagonal(gsl_vector_int_view *view, gsl_matrix_int *m, size_t k)
{
*view = gsl_matrix_int_superdiagonal(m, k);
return &view->vector;
}
gsl_vector_uint *mgsl_matrix_uint_superdiagonal(gsl_vector_uint_view *view, gsl_matrix_uint *m, size_t k)
{
*view = gsl_matrix_uint_superdiagonal(m, k);
return &view->vector;
}
gsl_vector_long *mgsl_matrix_long_superdiagonal(gsl_vector_long_view *view, gsl_matrix_long *m, size_t k)
{
*view = gsl_matrix_long_superdiagonal(m, k);
return &view->vector;
}
gsl_vector_ulong *mgsl_matrix_ulong_superdiagonal(gsl_vector_ulong_view *view, gsl_matrix_ulong *m, size_t k)
{
*view = gsl_matrix_ulong_superdiagonal(m, k);
return &view->vector;
}
gsl_vector_short *mgsl_matrix_short_superdiagonal(gsl_vector_short_view *view, gsl_matrix_short *m, size_t k)
{
*view = gsl_matrix_short_superdiagonal(m, k);
return &view->vector;
}
gsl_vector_ushort *mgsl_matrix_ushort_superdiagonal(gsl_vector_ushort_view *view, gsl_matrix_ushort *m, size_t k)
{
*view = gsl_matrix_ushort_superdiagonal(m, k);
return &view->vector;
}
gsl_vector_char *mgsl_matrix_char_superdiagonal(gsl_vector_char_view *view, gsl_matrix_char *m, size_t k)
{
*view = gsl_matrix_char_superdiagonal(m, k);
return &view->vector;
}
gsl_vector_uchar *mgsl_matrix_uchar_superdiagonal(gsl_vector_uchar_view *view, gsl_matrix_uchar *m, size_t k)
{
*view = gsl_matrix_uchar_superdiagonal(m, k);
return &view->vector;
}
gsl_vector_complex *mgsl_matrix_complex_superdiagonal(gsl_vector_complex_view *view, gsl_matrix_complex *m, size_t k)
{
*view = gsl_matrix_complex_superdiagonal(m, k);
return &view->vector;
}
gsl_vector_complex_float *mgsl_matrix_complex_float_superdiagonal(gsl_vector_complex_float_view *view, gsl_matrix_complex_float *m, size_t k)
{
*view = gsl_matrix_complex_float_superdiagonal(m, k);
return &view->vector;
}
| {
"alphanum_fraction": 0.7512769956,
"avg_line_length": 29.8852515507,
"ext": "c",
"hexsha": "88cd776c6575befa7c10cef5bb762cd4bf6a122f",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2021-12-30T16:00:43.000Z",
"max_forks_repo_forks_event_min_datetime": "2020-07-17T06:58:18.000Z",
"max_forks_repo_head_hexsha": "2f6c28062734dba9bf8be1b28f5b04d5344becec",
"max_forks_repo_licenses": [
"Artistic-2.0"
],
"max_forks_repo_name": "frithnanth/raku-Math-Libgsl-Matrix",
"max_forks_repo_path": "src/matrix.c",
"max_issues_count": 4,
"max_issues_repo_head_hexsha": "2f6c28062734dba9bf8be1b28f5b04d5344becec",
"max_issues_repo_issues_event_max_datetime": "2021-05-12T05:09:26.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-07-17T07:16:54.000Z",
"max_issues_repo_licenses": [
"Artistic-2.0"
],
"max_issues_repo_name": "frithnanth/raku-Math-Libgsl-Matrix",
"max_issues_repo_path": "src/matrix.c",
"max_line_length": 179,
"max_stars_count": 2,
"max_stars_repo_head_hexsha": "2f6c28062734dba9bf8be1b28f5b04d5344becec",
"max_stars_repo_licenses": [
"Artistic-2.0"
],
"max_stars_repo_name": "frithnanth/raku-Math-Libgsl-Matrix",
"max_stars_repo_path": "src/matrix.c",
"max_stars_repo_stars_event_max_datetime": "2021-12-30T16:00:28.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-01-15T13:54:30.000Z",
"num_tokens": 25271,
"size": 86727
} |
#include <gsl/gsl_vector.h>
#include <math.h>
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include "data.h"
#include "prob_functions.h"
void EM (Dataset *data)
{
int i, j;
const double THRESHOLD = 1E-10;
double Q, lastQ;
srand(time(NULL));
/* Initialize parameters to starting values */
for (i = 0; i < data->numLabelers; i++) {
data->alpha[i] = data->priorAlpha[i];
/*data->alpha[i] = (double) rand() / RAND_MAX * 4 - 2;*/
}
for (j = 0; j < data->numImages; j++) {
data->beta[j] = data->priorBeta[j];
/*data->beta[j] = (double) rand() / RAND_MAX * 3;*/
}
Q = 0;
EStep(data);
Q = computeQ(data);
/*printf("Q = %f\n", Q);*/
do {
lastQ = Q;
/* Re-estimate P(Z|L,alpha,beta) */
EStep(data);
Q = computeQ(data);
/*printf("Q = %f; L = %f\n", Q, 0.0 /*computeLikelihood(data)*/
/*outputResults(data);*/
MStep(data);
Q = computeQ(data);
/*printf("Q = %f; L = %f\n", Q, 0.0 /*computeLikelihood(data)*/
} while (fabs((Q - lastQ)/lastQ) > THRESHOLD);
/* outputResults(data); */
}
int main (int argc, char *argv[])
{
Dataset data;
if (argc < 2) {
fprintf(stdout, "Usage: em <data>\n");
fprintf(stdout, "where the specified data file is formatted as described in the README file.\n");
exit(1);
}
readData(argv[1], &data);
EM(&data);
free(data.priorAlpha);
free(data.priorBeta);
free(data.labels);
free(data.alpha);
free(data.beta);
free(data.probZ1);
free(data.probZ0);
}
| {
"alphanum_fraction": 0.6029005525,
"avg_line_length": 20.9855072464,
"ext": "c",
"hexsha": "9611e948f4bbf5873d63e76530b4f2a8554d2f4d",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2018-05-28T08:00:05.000Z",
"max_forks_repo_forks_event_min_datetime": "2018-05-28T08:00:05.000Z",
"max_forks_repo_head_hexsha": "76c3aace93ecd84f0590bb844483b499afa705e7",
"max_forks_repo_licenses": [
"BSD-2-Clause"
],
"max_forks_repo_name": "zhangyuygss/SVFSal",
"max_forks_repo_path": "em/em.c",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "76c3aace93ecd84f0590bb844483b499afa705e7",
"max_issues_repo_issues_event_max_datetime": "2021-04-09T08:03:26.000Z",
"max_issues_repo_issues_event_min_datetime": "2021-04-08T09:49:23.000Z",
"max_issues_repo_licenses": [
"BSD-2-Clause"
],
"max_issues_repo_name": "zhangyuygss/SVFSal",
"max_issues_repo_path": "em/em.c",
"max_line_length": 99,
"max_stars_count": 8,
"max_stars_repo_head_hexsha": "76c3aace93ecd84f0590bb844483b499afa705e7",
"max_stars_repo_licenses": [
"BSD-2-Clause"
],
"max_stars_repo_name": "zhangyuygss/SVFSal.caffe",
"max_stars_repo_path": "em/em.c",
"max_stars_repo_stars_event_max_datetime": "2021-06-23T11:24:08.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-08-20T12:47:43.000Z",
"num_tokens": 477,
"size": 1448
} |
/*****************************************************************\
__
/ /
/ / __ __
/ /______ _______ / / / / ________ __ __
/ ______ \ /_____ \ / / / / / _____ | / / / /
/ / | / _______| / / / / / / /____/ / / / / /
/ / / / / _____ / / / / / / _______/ / / / /
/ / / / / /____/ / / / / / / |______ / |______/ /
/_/ /_/ |________/ / / / / \_______/ \_______ /
/_/ /_/ / /
/ /
High Level Game Framework /_/
---------------------------------------------------------------
Copyright (c) 2007-2011 - Rodrigo Braz Monteiro.
This file is subject to the terms of halley_license.txt.
\*****************************************************************/
#pragma once
#include <cmath>
#include "angle.h"
#include "vector2.h"
#include "vector3.h"
#include <halley/utils/utils.h>
#include <gsl/gsl_assert>
namespace Halley {
template <typename T=float, int Alignment=4>
class alignas(Alignment * sizeof(T)) Vector4D {
private:
constexpr inline T mod(T a, T b) const { return a % b; }
public:
using ScalarType = T;
T x, y, z, w;
struct Uninitialized {};
// Constructors
constexpr inline Vector4D ()
: x(0)
, y(0)
, z(0)
, w(0)
{}
constexpr inline Vector4D(Uninitialized u) {}
constexpr inline Vector4D (T x, T y, T z, T w)
: x(x)
, y(y)
, z(z)
, w(w)
{}
constexpr inline Vector4D(const Vector4D& other) = default;
constexpr inline Vector4D(Vector4D&& other) noexcept = default;
template <typename V, int A>
constexpr inline explicit Vector4D (const Vector4D<V, A>& vec)
: x(T(vec.x))
, y(T(vec.y))
, z(T(vec.z))
, w(T(vec.w))
{}
template <typename V, int A>
constexpr inline explicit Vector4D (Vector4D<V, A>&& vec)
: x(T(vec.x))
, y(T(vec.y))
, z(T(vec.z))
, w(T(vec.w))
{}
constexpr inline explicit Vector4D(const Vector2D<T>& v, T z = 0, T w = 0)
: x(v.x)
, y(v.y)
, z(z)
, w(w)
{}
constexpr inline explicit Vector4D(const Vector3D<T>& v, T w = 0)
: x(v.x)
, y(v.y)
, z(v.z)
, w(w)
{}
~Vector4D() = default;
// Getter
constexpr inline T& operator[](size_t n)
{
Expects(n <= 3);
return (&x)[n];
}
constexpr inline const T& operator[](size_t n) const
{
Expects(n <= 3);
return (&x)[n];
}
T* data()
{
return &x;
}
const T* data() const
{
return &x;
}
// Assignment and comparison
constexpr inline Vector4D& operator=(const Vector4D& param) = default;
constexpr inline Vector4D& operator=(Vector4D&& param) = default;
constexpr inline Vector4D& operator=(T param) { x = param; y = param; z = param; w = param; return *this; }
constexpr inline bool operator==(Vector4D param) const { return x == param.x && y == param.y && z == param.z && w == param.w; }
constexpr inline bool operator!=(Vector4D param) const { return x != param.x || y != param.y || z != param.z || w != param.w; }
// Basic algebra
constexpr inline Vector4D operator+(Vector4D param) const { return Vector4D(x + param.x, y + param.y, z + param.z, w + param.w); }
constexpr inline Vector4D operator-(Vector4D param) const { return Vector4D(x - param.x, y - param.y, z - param.z, w - param.w); }
constexpr inline Vector4D operator*(Vector4D param) const { return Vector4D(x * param.x, y * param.y, z * param.z, w * param.w); }
constexpr inline Vector4D operator/(Vector4D param) const { return Vector4D(x / param.x, y / param.y, z / param.z, w / param.w); }
constexpr inline Vector4D operator%(Vector4D param) const { return Vector4D(mod(x, param.x), mod(y, param.y), mod(z, param.z), mod(w, param.w)); }
constexpr inline Vector4D modulo(Vector4D param) const { return Vector4D(Halley::modulo<T>(x, param.x), Halley::modulo<T>(y, param.y), Halley::modulo<T>(z, param.z), Halley::modulo<T>(w, param.w)); }
constexpr inline Vector4D floorDiv(Vector4D param) const { return Vector4D(Halley::floorDiv(x, param.x), Halley::floorDiv(y, param.y), Halley::floorDiv(z, param.z), Halley::floorDiv(w, param.w)); }
constexpr inline Vector4D operator-() const { return Vector4D(-x, -y, -z, -w); }
template <typename V>
constexpr inline Vector4D operator * (V param) const { return Vector4D(T(x * param), T(y * param), T(z * param), T(w * param)); }
template <typename V>
constexpr inline Vector4D operator / (V param) const { return Vector4D(T(x / param), T(y / param), T(z * param), T(w * param)); }
// In-place operations
constexpr inline Vector4D& operator += (Vector4D param) { x += param.x; y += param.y; z += param.z; w += param.w; return *this; }
constexpr inline Vector4D& operator -= (Vector4D param) { x -= param.x; y -= param.y; z -= param.z; w -= param.w; return *this; }
constexpr inline Vector4D& operator *= (Vector4D param) { x *= param.x; y *= param.y; z *= param.z; w *= param.w; return *this; }
constexpr inline Vector4D& operator /= (Vector4D param) { x /= param.x; y /= param.y; z /= param.z; w /= param.w; return *this; }
constexpr inline Vector4D& operator *= (const T param) { x *= param; y *= param; z *= param; w *= param; return *this; }
constexpr inline Vector4D& operator /= (const T param) { x /= param; y /= param; z /= param; w /= param; return *this; }
// Get the normalized vector (unit vector)
inline Vector4D unit () const
{
float len = length();
if (len != 0) {
return (*this) / len;
} else {
return Vector4D();
}
}
inline Vector4D normalized() const
{
return unit();
}
inline void normalize()
{
*this = unit();
}
// Dot product
constexpr inline T dot (Vector4D param) const
{
return (x * param.x) + (y * param.y) + (z * param.z) + (w * param.w);
}
// Length
constexpr inline T length () const { static_cast<T>(std::sqrt(squaredLength())); }
constexpr inline T len () const { return length(); }
// Squared length, often useful and much faster
constexpr inline T squaredLength () const { return x*x + y*y + z*z + w*w; }
// Floor
inline Vector4D floor() const { return Vector4D(floor(x), floor(y), floor(z), floor(w)); }
inline Vector4D ceil() const { return Vector4D(ceil(x), ceil(y), ceil(z), ceil(w)); }
constexpr Vector2D<T> toVector2() const
{
return Vector2D<T>(x / w, y / w);
}
constexpr Vector3D<T> toVector3() const
{
return Vector3D<T>(x / w, y / w, z / w);
}
// Some swizzles
constexpr Vector2D<T> xy() const { return Vector2D<T>(x, y); }
constexpr Vector2D<T> yz() const { return Vector2D<T>(y, z); }
constexpr Vector2D<T> zw() const { return Vector2D<T>(z, w); }
constexpr Vector3D<T> xyz() const { return Vector3D<T>(x, y, z); }
};
////////////////////
// Global operators
template <typename T, typename V>
constexpr inline Vector4D<T> operator * (V f, const Vector4D<T> &v)
{
return Vector4D<T>(T(v.x * f), T(v.y * f), T(v.z * f), T(v.w * f));
}
////////////
// Typedefs
using Vector4d = Vector4D<double, 4>;
using Vector4f = Vector4D<float, 4>;
using Vector4i = Vector4D<int, 4>;
using Vector4s = Vector4D<short, 4>;
using Vector4c = Vector4D<char, 4>;
}
| {
"alphanum_fraction": 0.5748107364,
"avg_line_length": 32.2888888889,
"ext": "h",
"hexsha": "f6b1f4d73d89734dad942afa1e45dedb629d6763",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2022-01-03T22:49:47.000Z",
"max_forks_repo_forks_event_min_datetime": "2022-01-03T22:49:47.000Z",
"max_forks_repo_head_hexsha": "5c85c889b76c69c6bdef6f4801c6aba282b7af80",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "code-disaster/halley",
"max_forks_repo_path": "src/engine/utils/include/halley/maths/vector4.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "5c85c889b76c69c6bdef6f4801c6aba282b7af80",
"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": "code-disaster/halley",
"max_issues_repo_path": "src/engine/utils/include/halley/maths/vector4.h",
"max_line_length": 201,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "5c85c889b76c69c6bdef6f4801c6aba282b7af80",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "code-disaster/halley",
"max_stars_repo_path": "src/engine/utils/include/halley/maths/vector4.h",
"max_stars_repo_stars_event_max_datetime": "2021-12-12T23:07:30.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-12-12T23:07:30.000Z",
"num_tokens": 2262,
"size": 7265
} |
#pragma once
#include <gsl.h>
#include <string>
#include <cstdarg>
#include <typeinfo>
#include <exception>
#include "HE_Assert.h"
#include "TMP_Helper.h"
// Utility function that calls the right variadic formatting functions and returns an RAII string
std::string CStringFormat(const char* sFormat, va_list args);
std::string CStringFormat(const char* sFormat, ...);
// Default to_string functions
using std::to_string;
using gsl::to_string;
std::string to_string(const std::exception& e);
std::string to_string(void* p);
inline std::string& to_string(std::string& s) { return s; }
inline std::string to_string(std::string&& s) { return s; }
inline const std::string& to_string(const std::string& s) { return s; }
inline std::string to_string(const char* s) { return{ s }; }
// Built-in type formats specifiers
// Can be used to format a built-in type to a string with a special format.
// Use HasFormatSpecifier<T> to test statically (ex: static_assert(...)) if a type supports
// a format specifier
// The format specifier is in the same format as printf (http://en.cppreference.com/w/cpp/io/c/fprintf),
// except that the conversion format specifier (aka the last letter[s]) can be ignored, in which case the
// default specifier for the type will be used (ex: d for int, u for unsigned, f for float, etc...)
// On top of that, for long sized types, only the conversion specifier without the argument type can be
// supplied. For example, for unsigned long, the format could be " .4o", which will be converted to
// " .4ol". Supplying " .4ol" itself would also work
std::string to_string(int val, const std::string& sFormat); // Defaults to %[sFormat]d
std::string to_string(unsigned int val, const std::string& sFormat); // Defaults to %[sFormat]u
std::string to_string(long val, const std::string& sFormat); // Defaults to %[sFormat]dl
std::string to_string(unsigned long val, const std::string& sFormat); // Defaults to %[sFormat]ul
std::string to_string(long long val, const std::string& sFormat); // Defaults to %[sFormat]dll
std::string to_string(unsigned long long val, const std::string& sFormat); // Defaults to %[sFormat]ull
std::string to_string(float val, const std::string& sFormat); // Defaults to %[sFormat]f
std::string to_string(double val, const std::string& sFormat); // Defaults to %[sFormat]f
std::string to_string(long double val, const std::string& sFormat); // Defaults to %[sFormat]fL
std::string to_string(void* val, const std::string& sFormat); // Defaults to %[sFormat]p
namespace HE
{
namespace Private
{
template<class T>
using try_format = decltype(to_string(std::declval<T>()));
template<class T>
using has_format = has_op < T, try_format >;
template<class T>
using try_format_specifier = decltype(to_string(std::declval<T>(), std::declval<std::string>()));
template<class T>
using has_format_specifier = has_op<T, try_format_specifier >;
template< typename Arg >
std::string FormatIthArgN(size_t i, size_t n, Arg&& arg)
{
ASSERT_MSG(i == n, "String format token number was higher than the number of arguments");
return to_string(std::forward<Arg>(arg));
}
template< typename Arg1, typename... Args >
std::string FormatIthArgN(size_t i, size_t n, Arg1&& arg, Args&&... args)
{
if (i == n)
{
return to_string(std::forward<Arg1>(arg));
}
else
{
return FormatIthArgN(i, n + 1, std::forward<Args>(args)...);
}
}
template< typename Arg>
auto FormatIthArgFN(size_t i, size_t n, const std::string& format, Arg&& arg)
-> std::enable_if_t<has_format_specifier<Arg>::value, std::string>
{
ASSERT_MSG(i == n, "String format token number was higher than the number of arguments");
return to_string(std::forward<Arg>(arg), format);
}
template< typename Arg >
auto FormatIthArgFN(size_t i, size_t n, const std::string& format, Arg&& arg)
-> std::enable_if_t<!has_format_specifier<Arg>::value, std::string>
{
ASSERT_MSG(false , "A format specifier was supplied with type "s + typeid(Arg).name() + " which that does not support it");
return "";
}
template< typename Arg1, typename... Args >
std::string FormatIthArgFN(size_t i, size_t n, const std::string& format, Arg1&& arg, Args&&... args)
{
if (i == n)
{
return FormatIthArgFN(i, n, format, std::forward<Arg1>(arg));
}
else
{
return FormatIthArgFN(i, n + 1, format, std::forward<Args>(args)...);
}
}
template< typename... Args >
std::string FormatIthArg(size_t i, Args&&... args)
{
return FormatIthArgN(i, 0, std::forward<Args>(args)...);
}
template< typename... Args >
std::string FormatIthArgF(size_t i, const std::string& format, Args&&... args)
{
return FormatIthArgFN(i, 0, format, std::forward<Args>(args)...);
}
}
// Can be used in statically evaluated context to test if the type can be formatted
// to a string and formatted with a format specifier
template< class... T >
constexpr bool HasFormat()
{
return and_<Private::has_format<T>...>::value;
}
template< class... T >
constexpr bool HasFormatSpecifier()
{
return and_<Private::has_format_specifier<T>...>::value;
}
// Form: Format(sFormat, args...) -> sFormatted
// Formats the string according to format tokens and arguments
// Format token have the format "{i}" or "{i:xxxx}", where i is a 0-based argument index to be
// converted to string or the character '_', which means next argument (starting at 0)
// "xxxx" is a format string to be passed to the argument
//
// In order to be featured in a format token, an argument must have a "to_string" function available
// either in the global namespace or in the same scope as the type of the argument, which
// will be found through ADL
// To have a format specifier, the argument must have a "to_string" which takes a string as
// second argument
// You can test for both of these conditions statically with HasFormat<T>() and HasFormatSpecifier<T>()
// Example: Format("{0:dd-mm-yyyy}", date) -> to_string(date, "dd-mm-yyyy")
// Pre-condition: The biggest index in the format string must be smaller than
// the number of arguments, and indices can't be negative
inline std::string Format(const std::string& sFormat)
{
return sFormat;
}
template< typename... Args>
std::string Format(const std::string& sFormat, Args&&... args)
{
static_assert(HasFormat<Args...>(), "An argument cannot be formatted (HasFormat returns false)");
using namespace HE::Private;
std::string sOutput;
size_t nNextArg = 0;
for (size_t i = 0; i < sFormat.size(); ++i)
{
// Find the next format token
auto const posToken = sFormat.find_first_of('{', i);
// Add to the output all the characters up until the next format token (or the end)
// and process the format token if necessary
if (posToken == std::string::npos)
{
sOutput += sFormat.substr(i);
break;
}
// The sequence "\{" is not a token start, so we continue as if it was a normal character
else if (posToken != 0 && sFormat[posToken - 1] == '\\')
{
sOutput += sFormat.substr(i, posToken - i);
i = posToken;
continue;
}
// Otherwise, we have a format token
else
{
sOutput += sFormat.substr(i, posToken - i); // Add everything before the token
auto const endToken = sFormat.find_first_of('}', posToken);
i = endToken;
ASSERT_MSG(endToken != std::string::npos, "Token error in string format \"" + sFormat + "\"");
// Find the index token inside the whole token
auto const sFormatToken = sFormat.substr(posToken + 1, (endToken - 1) - posToken);
auto const nSpecifierSentinel = sFormatToken.find_first_of(':');
auto const sIndexToken = [sFormatToken, nSpecifierSentinel]() {
if (nSpecifierSentinel == std::string::npos)
{
return sFormatToken;
}
else
{
return sFormatToken.substr(0, nSpecifierSentinel);
}
}();
// Find the index of the current arg for this token
auto const argPos = [sIndexToken, nNextArg]() -> size_t {
if (sIndexToken == "_")
{
return nNextArg;
}
else
{
return std::stoi(sIndexToken);
}
}();
nNextArg = argPos + 1;
// Add the formatted argument to the output
if (nSpecifierSentinel == std::string::npos)
{
sOutput += FormatIthArg(argPos, std::forward<Args>(args)...);
}
else
{
auto const sSpecifierToken = sFormatToken.substr(nSpecifierSentinel + 1);
sOutput += FormatIthArgF(argPos, sSpecifierToken, std::forward<Args>(args)...);
}
}
}
return sOutput;
}
// Thread-safe logging
void Log(const char* psMsg) noexcept;
inline void Log(const std::string& sMsg) noexcept { Log(sMsg.c_str()); }
void LogError(const char* psMsg) noexcept;
inline void LogError(const std::string& sMsg) noexcept { LogError(sMsg.c_str()); }
template< typename... Args>
void Log(const std::string& sFormat, Args&&... args)
{
Log(Format(sFormat, std::forward<Args>(args)...));
}
template< typename... Args>
void LogError(const std::string& sFormat, Args&&... args)
{
LogError(Format(sFormat, std::forward<Args>(args)...));
}
// Constexpr-friendly string
template<class Char = char>
class basic_constexpr_string
{
public:
template<size_t N>
constexpr basic_constexpr_string(const char(&a)[N]) noexcept :
m_pStr{ a }, m_nSize{ N - 1 } {}
constexpr Char operator[](size_t n) const
{
return n < m_nSize ? m_pStr[n] : throw std::out_of_range("");
}
constexpr size_t size() const noexcept { return m_nSize; }
private:
const Char* const m_pStr;
const size_t m_nSize;
};
using constexpr_string = basic_constexpr_string<char>;
using constexpr_wstring = basic_constexpr_string<wchar_t>;
using constexpr_u16string = basic_constexpr_string<char16_t>;
using constexpr_u32string = basic_constexpr_string<char32_t>;
} | {
"alphanum_fraction": 0.683981369,
"avg_line_length": 34.4111498258,
"ext": "h",
"hexsha": "1c5906bbac21fe14b073e7b9d15ff9d97fd7906f",
"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": "e5ab97f6ccbc2c77bd92dd9dc84f2f64670e586d",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "KABoissonneault/Hazel_Engine",
"max_forks_repo_path": "src/Source/SDK/HE_String.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "e5ab97f6ccbc2c77bd92dd9dc84f2f64670e586d",
"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": "KABoissonneault/Hazel_Engine",
"max_issues_repo_path": "src/Source/SDK/HE_String.h",
"max_line_length": 126,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "e5ab97f6ccbc2c77bd92dd9dc84f2f64670e586d",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "KABoissonneault/Hazel_Engine",
"max_stars_repo_path": "src/Source/SDK/HE_String.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 2714,
"size": 9876
} |
#ifndef TRANS_MYFUNC
#define TRANS_MYFUNC
#include <stdarg.h>
#include <gsl/gsl_vector.h>
#include "../include/type.h"
void mle_result_set(mle_result* mle, double sum, gsl_vector* psi1, gsl_vector* psi2,
double beta0, double beta1, double var1, double var2);
void log_vector(gsl_vector *vec);
double myfunc_multivar(const double x[], va_list argv);
void myfunc_multivar_der(const double x[], double res[], va_list argv);
double myfunc_1_2(const double x[], va_list argv);
void myfunc_der_1_2(const double x[], double res[], va_list argv);
double myfunc_marginal_1_2(const double x[], va_list argv);
void myfunc_marginal_1_2_der(const double x[], double res[], va_list argv);
double myfunc_individual(const double x[], va_list argv);
void myfunc_individual_der(const double x[], double res[], va_list argv);
double myfunc_marginal(const double x[], va_list argv);
void myfunc_marginal_der(const double x[], double res[], va_list argv);
int MLE_marginal_iteration(gsl_vector* i1, gsl_vector* i2,
gsl_vector* s1, gsl_vector* s2,
const int inclu_len, const int skip_len,
mle_result* mle);
int MLE_marginal_iteration_constrain(gsl_vector* i1, gsl_vector* i2,
gsl_vector* s1, gsl_vector* s2,
const int inclu_len, const int skip_len,
mle_result* mle);
void* thread_wrapper_for_LT(void* arg);
void* batch_wrapper_for_LT(void* arg);
double likelihood_test(gsl_vector *i1, gsl_vector *i2, gsl_vector *s1, gsl_vector *s2,
int inclu_len, int skip_len, int flag, char* id);
int vec2psi(gsl_vector* psi, gsl_vector *inc, gsl_vector *skp,
int inclu_len, int skip_len);
#endif
| {
"alphanum_fraction": 0.66430131,
"avg_line_length": 32.1403508772,
"ext": "h",
"hexsha": "9f18cbda5c21992b1537216ee4a822de61bd96e3",
"lang": "C",
"max_forks_count": 39,
"max_forks_repo_forks_event_max_datetime": "2022-03-19T09:14:46.000Z",
"max_forks_repo_forks_event_min_datetime": "2020-06-01T20:25:44.000Z",
"max_forks_repo_head_hexsha": "8a2ad659717a1ccd6dbecd593dc1370ba7c30621",
"max_forks_repo_licenses": [
"BSD-2-Clause-FreeBSD"
],
"max_forks_repo_name": "chunjie-sam-liu/rmats-turbo",
"max_forks_repo_path": "rMATS_C/include/myfunc.h",
"max_issues_count": 163,
"max_issues_repo_head_hexsha": "8a2ad659717a1ccd6dbecd593dc1370ba7c30621",
"max_issues_repo_issues_event_max_datetime": "2022-03-31T19:39:30.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-06-03T06:54:27.000Z",
"max_issues_repo_licenses": [
"BSD-2-Clause-FreeBSD"
],
"max_issues_repo_name": "chunjie-sam-liu/rmats-turbo",
"max_issues_repo_path": "rMATS_C/include/myfunc.h",
"max_line_length": 86,
"max_stars_count": 88,
"max_stars_repo_head_hexsha": "8a2ad659717a1ccd6dbecd593dc1370ba7c30621",
"max_stars_repo_licenses": [
"BSD-2-Clause-FreeBSD"
],
"max_stars_repo_name": "chunjie-sam-liu/rmats-turbo",
"max_stars_repo_path": "rMATS_C/include/myfunc.h",
"max_stars_repo_stars_event_max_datetime": "2022-03-18T17:34:39.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-06-01T20:20:01.000Z",
"num_tokens": 453,
"size": 1832
} |
/* Author: G. Jungman
*/
#include <config.h>
#include <stdlib.h>
#include <gsl/gsl_ieee_utils.h>
#include <gsl/gsl_qrng.h>
#include <gsl/gsl_test.h>
void test_sobol(void)
{
int status = 0;
double v[3];
/* int i; */
/* test in dimension 2 */
gsl_qrng * g = gsl_qrng_alloc(gsl_qrng_sobol, 2);
gsl_qrng_get(g, v);
gsl_qrng_get(g, v);
gsl_qrng_get(g, v);
status += ( v[0] != 0.25 || v[1] != 0.75 );
gsl_qrng_get(g, v);
status += ( v[0] != 0.375 || v[1] != 0.375 );
gsl_qrng_free(g);
gsl_test (status, "Sobol d=2");
status = 0;
/* test in dimension 3 */
g = gsl_qrng_alloc(gsl_qrng_sobol, 3);
gsl_qrng_get(g, v);
gsl_qrng_get(g, v);
gsl_qrng_get(g, v);
status += ( v[0] != 0.25 || v[1] != 0.75 || v[2] != 0.25 );
gsl_qrng_get(g, v);
status += ( v[0] != 0.375 || v[1] != 0.375 || v[2] != 0.625 );
gsl_test (status, "Sobol d=3");
status = 0;
gsl_qrng_init(g);
gsl_qrng_get(g, v);
gsl_qrng_get(g, v);
gsl_qrng_get(g, v);
status += ( v[0] != 0.25 || v[1] != 0.75 || v[2] != 0.25 );
gsl_qrng_get(g, v);
status += ( v[0] != 0.375 || v[1] != 0.375 || v[2] != 0.625 );
gsl_qrng_free(g);
gsl_test (status, "Sobol d=3 (reinitialized)");
}
void test_nied2(void)
{
int status = 0;
double v[3];
/* int i; */
/* test in dimension 2 */
gsl_qrng * g = gsl_qrng_alloc(gsl_qrng_niederreiter_2, 2);
gsl_qrng_get(g, v);
gsl_qrng_get(g, v);
gsl_qrng_get(g, v);
status += ( v[0] != 0.75 || v[1] != 0.25 );
gsl_qrng_get(g, v);
status += ( v[0] != 0.25 || v[1] != 0.75 );
gsl_qrng_get(g, v);
gsl_qrng_get(g, v);
gsl_qrng_get(g, v);
status += ( v[0] != 0.625 || v[1] != 0.125 );
gsl_qrng_free(g);
gsl_test (status, "Niederreiter d=2");
status = 0;
/* test in dimension 3 */
g = gsl_qrng_alloc(gsl_qrng_niederreiter_2, 3);
gsl_qrng_get(g, v);
gsl_qrng_get(g, v);
gsl_qrng_get(g, v);
status += ( v[0] != 0.75 || v[1] != 0.25 || v[2] != 0.3125 );
gsl_qrng_get(g, v);
status += ( v[0] != 0.25 || v[1] != 0.75 || v[2] != 0.5625 );
gsl_qrng_get(g, v);
gsl_qrng_get(g, v);
gsl_qrng_get(g, v);
status += ( v[0] != 0.625 || v[1] != 0.125 || v[2] != 0.6875 );
gsl_test (status, "Niederreiter d=3");
status = 0;
gsl_qrng_init(g);
gsl_qrng_get(g, v);
gsl_qrng_get(g, v);
gsl_qrng_get(g, v);
status += ( v[0] != 0.75 || v[1] != 0.25 || v[2] != 0.3125 );
gsl_qrng_get(g, v);
status += ( v[0] != 0.25 || v[1] != 0.75 || v[2] != 0.5625 );
gsl_qrng_get(g, v);
gsl_qrng_get(g, v);
gsl_qrng_get(g, v);
status += ( v[0] != 0.625 || v[1] != 0.125 || v[2] != 0.6875 );
gsl_qrng_free(g);
gsl_test (status, "Niederreiter d=3 (reinitialized)");
}
int main()
{
gsl_ieee_env_setup ();
test_sobol();
test_nied2();
exit (gsl_test_summary ());
}
| {
"alphanum_fraction": 0.551314368,
"avg_line_length": 22.5772357724,
"ext": "c",
"hexsha": "4b7d08f889e6b313f7e7872e35946432362fbfd8",
"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/qrng/test.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/qrng/test.c",
"max_line_length": 65,
"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/qrng/test.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": 1178,
"size": 2777
} |
/* wavelet/haar.c
*
* Copyright (C) 2004 Ivo Alxneit
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include <config.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_wavelet.h>
static const double ch_2[2] = { M_SQRT1_2, M_SQRT1_2 };
static const double cg_2[2] = { M_SQRT1_2, -(M_SQRT1_2) };
static int
haar_init (const double **h1, const double **g1, const double **h2,
const double **g2, size_t * nc, size_t * offset,
const size_t member)
{
if (member != 2)
{
return GSL_FAILURE;
}
*h1 = ch_2;
*g1 = cg_2;
*h2 = ch_2;
*g2 = cg_2;
*nc = 2;
*offset = 0;
return GSL_SUCCESS;
}
static int
haar_centered_init (const double **h1, const double **g1, const double **h2,
const double **g2, size_t * nc, size_t * offset,
const size_t member)
{
if (member != 2)
{
return GSL_FAILURE;
}
*h1 = ch_2;
*g1 = cg_2;
*h2 = ch_2;
*g2 = cg_2;
*nc = 2;
*offset = 1;
return GSL_SUCCESS;
}
static const gsl_wavelet_type haar_type = {
"haar",
&haar_init
};
static const gsl_wavelet_type haar_centered_type = {
"haar-centered",
&haar_centered_init
};
const gsl_wavelet_type *gsl_wavelet_haar = &haar_type;
const gsl_wavelet_type *gsl_wavelet_haar_centered = &haar_centered_type;
| {
"alphanum_fraction": 0.6698207171,
"avg_line_length": 24.487804878,
"ext": "c",
"hexsha": "8591cfda5bdc601a046fc214269e68b5df7e9b27",
"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/wavelet/haar.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/wavelet/haar.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/wavelet/haar.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": 607,
"size": 2008
} |
#ifndef PCH_H
#define PCH_H
#pragma once
// add tat ca cac cai thu vien, ham thuong xuyen dung trong suot chuong trinh
#include <fmt/format.h>
#include <QtCore/QObject>
#include <QtSql/QtSql>
#include <any>
#include <gsl/gsl>
#include <memory>
#include <optional>
#include "common.inl"
#include "database.inl"
#include "macros.inl"
#endif // !PCH_H
| {
"alphanum_fraction": 0.7314285714,
"avg_line_length": 21.875,
"ext": "h",
"hexsha": "799cd6f05df9c68dd634580dfe2a2b43e832833b",
"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": "b82d14dc22b8fd18dda7a79989785bc788f1370b",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "philong6297/electric-bill-management-system",
"max_forks_repo_path": "electric-bill-management-system/pch.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "b82d14dc22b8fd18dda7a79989785bc788f1370b",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "philong6297/electric-bill-management-system",
"max_issues_repo_path": "electric-bill-management-system/pch.h",
"max_line_length": 77,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "b82d14dc22b8fd18dda7a79989785bc788f1370b",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "philong6297/electric-bill-management-system",
"max_stars_repo_path": "electric-bill-management-system/pch.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 103,
"size": 350
} |
#pragma once
#include <optional>
#include <sam.h>
#include <gsl/span>
#include "clocks.h"
#include "utils.h"
namespace mcu {
class I2cMaster {
public:
I2cMaster(Sercom* sercom, const mcu::ClockGenerator& clock, const mcu::ClockGenerator& slowClock, unsigned frequency = 100000)
:port{sercom->I2CM}
{
int sercomIndex = mcu::util::getSercomIndex(sercom);
PM->APBCMASK.reg |= 1 << (PM_APBCMASK_SERCOM0_Pos + sercomIndex);
clock.routeToPeripheral(GCLK_CLKCTRL_ID_SERCOM0_CORE_Val + sercomIndex);
slowClock.routeToPeripheral(GCLK_CLKCTRL_ID_SERCOMX_SLOW_Val);
port.CTRLA.reg = SERCOM_I2CM_CTRLA_MODE_I2C_MASTER;
(void)port.CTRLB.reg;
volatile uint32_t ctrla = port.CTRLA.reg;
port.CTRLB.reg = 0;
port.BAUD.reg = computeBaud(frequency, clock.frequency);
while (port.STATUS.bit.SYNCBUSY);
port.CTRLA.bit.ENABLE = true;
while (port.STATUS.bit.SYNCBUSY);
port.STATUS.bit.BUSSTATE = BusstateIdle;
}
std::optional<std::byte> readReg(uint8_t slaveAddress, uint8_t reg)
{
port.ADDR.reg = (slaveAddress << 1) | 0;
while (port.INTFLAG.reg == 0);
port.INTFLAG.reg = SERCOM_I2CM_INTFLAG_MB | SERCOM_I2CM_INTFLAG_SB;
if (port.STATUS.reg & (StatusErrorMask | SERCOM_I2CM_STATUS_RXNACK) != 0) {
if (port.STATUS.bit.BUSSTATE == BusstateOwner)
port.CTRLB.reg = SERCOM_I2CM_CTRLB_CMD(CommandStop);
return std::nullopt;
}
port.DATA.reg = reg;
while (port.INTFLAG.reg == 0);
port.INTFLAG.reg = SERCOM_I2CM_INTFLAG_MB | SERCOM_I2CM_INTFLAG_SB;
if (port.STATUS.reg & StatusErrorMask) {
if (port.STATUS.bit.BUSSTATE == BusstateOwner)
port.CTRLB.reg = SERCOM_I2CM_CTRLB_CMD(CommandStop);
return std::nullopt;
}
port.ADDR.reg = (slaveAddress << 1) | 1;
while (port.INTFLAG.reg == 0);
port.INTFLAG.reg = SERCOM_I2CM_INTFLAG_MB | SERCOM_I2CM_INTFLAG_SB;
if (port.STATUS.reg & (StatusErrorMask | SERCOM_I2CM_STATUS_RXNACK) != 0) {
if (port.STATUS.bit.BUSSTATE == BusstateOwner)
port.CTRLB.reg = SERCOM_I2CM_CTRLB_CMD(CommandStop);
return std::nullopt;
}
std::byte result = static_cast<std::byte>(port.DATA.reg);
port.CTRLB.reg = SERCOM_I2CM_CTRLB_ACKACT | SERCOM_I2CM_CTRLB_CMD(CommandStop);
return result;
}
bool writeReg(uint8_t slaveAddress, uint8_t reg, std::byte data)
{
port.ADDR.reg = (slaveAddress << 1) | 0;
while (port.INTFLAG.reg == 0);
port.INTFLAG.reg = SERCOM_I2CM_INTFLAG_MB | SERCOM_I2CM_INTFLAG_SB;
if (port.STATUS.reg & (StatusErrorMask | SERCOM_I2CM_STATUS_RXNACK) != 0) {
if (port.STATUS.bit.BUSSTATE == BusstateOwner)
port.CTRLB.reg = SERCOM_I2CM_CTRLB_CMD(CommandStop);
return false;
}
port.DATA.reg = reg;
while (port.INTFLAG.reg == 0);
port.INTFLAG.reg = SERCOM_I2CM_INTFLAG_MB | SERCOM_I2CM_INTFLAG_SB;
if (port.STATUS.reg & (StatusErrorMask | SERCOM_I2CM_STATUS_RXNACK) != 0) {
if (port.STATUS.bit.BUSSTATE == BusstateOwner)
port.CTRLB.reg = SERCOM_I2CM_CTRLB_CMD(CommandStop);
return false;
}
port.DATA.reg = static_cast<uint8_t>(data);
while (port.INTFLAG.reg == 0);
port.INTFLAG.reg = SERCOM_I2CM_INTFLAG_MB | SERCOM_I2CM_INTFLAG_SB;
if (port.STATUS.reg & (StatusErrorMask) != 0) {
if (port.STATUS.bit.BUSSTATE == BusstateOwner)
port.CTRLB.reg = SERCOM_I2CM_CTRLB_CMD(CommandStop);
return false;
}
port.CTRLB.reg = SERCOM_I2CM_CTRLB_CMD(CommandStop);
return true;
}
private:
SercomI2cm& port;
static constexpr unsigned CommandRead = 0x2;
static constexpr unsigned CommandStop = 0x3;
static constexpr unsigned BusstateIdle = 0x1;
static constexpr unsigned BusstateOwner = 0x2;
static constexpr unsigned StatusErrorMask = SERCOM_I2CM_STATUS_ARBLOST;
static constexpr unsigned i2cRise = 215;
static constexpr uint16_t computeBaud(unsigned desiredFrequency, unsigned coreFrequency)
{
// coreFreq - (desiredFreq * 10) - (coreFreq * desiredFreq * i2cRise)
// BAUD + BAUDLOW = ------------------------------------------------------------------
// desiredFreq
int baudSum = (((coreFrequency - (desiredFrequency * 10) - (i2cRise * (desiredFrequency / 100) * (coreFrequency / 1000) / 10000)) * 10 + 5) / (desiredFrequency * 10));
assert(2 <= baudSum && baudSum <= 0xff*2);
if (baudSum % 2 == 1)
return (baudSum / 2) | ((baudSum / 2 + 1) << 8);
else
return baudSum / 2;
}
};
}
| {
"alphanum_fraction": 0.7026401112,
"avg_line_length": 34.544,
"ext": "h",
"hexsha": "8708a13127e83abda99574b16eedee7d502a0264",
"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": "520ecaefb0a0c1b92be281d5834f44e927995190",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "dachsei/platform-samd20",
"max_forks_repo_path": "include/i2c_master.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "520ecaefb0a0c1b92be281d5834f44e927995190",
"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": "dachsei/platform-samd20",
"max_issues_repo_path": "include/i2c_master.h",
"max_line_length": 169,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "520ecaefb0a0c1b92be281d5834f44e927995190",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "dachsei/platform-samd20",
"max_stars_repo_path": "include/i2c_master.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1367,
"size": 4318
} |
#pragma once
#include <glm/glm.hpp>
#include <gsl/span>
struct Bounds
{
static Bounds fromPoints(gsl::span<glm::vec3> points);
glm::vec3 getMin() const
{
return center - extent;
}
glm::vec3 getMax() const
{
return center + extent;
}
glm::vec3 center;
glm::vec3 extent;
float radius = 0.0f;
};
| {
"alphanum_fraction": 0.6058823529,
"avg_line_length": 14.1666666667,
"ext": "h",
"hexsha": "79e8a22e220d0f0a9e739ca0589203a1318b1555",
"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": "955f36bc95b6829bf1a1a89b430df7816c065ac0",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "aaronmjacobs/Swap",
"max_forks_repo_path": "Source/Math/Bounds.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "955f36bc95b6829bf1a1a89b430df7816c065ac0",
"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": "aaronmjacobs/Swap",
"max_issues_repo_path": "Source/Math/Bounds.h",
"max_line_length": 57,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "955f36bc95b6829bf1a1a89b430df7816c065ac0",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "aaronmjacobs/Swap",
"max_stars_repo_path": "Source/Math/Bounds.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 101,
"size": 340
} |
/* movstat/snacc.c
*
* Moving window S_n accumulator
*
* 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 <gsl/gsl_math.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_movstat.h>
#include <gsl/gsl_sort.h>
#include <gsl/gsl_statistics.h>
typedef double snacc_type_t;
typedef snacc_type_t ringbuf_type_t;
#include "ringbuf.c"
typedef struct
{
snacc_type_t *window; /* linear array for current window */
snacc_type_t *work; /* workspace */
ringbuf *rbuf; /* ring buffer storing current window */
} snacc_state_t;
static size_t
snacc_size(const size_t n)
{
size_t size = 0;
size += sizeof(snacc_state_t);
size += 2 * n * sizeof(snacc_type_t);
size += ringbuf_size(n);
return size;
}
static int
snacc_init(const size_t n, void * vstate)
{
snacc_state_t * state = (snacc_state_t *) vstate;
state->window = (snacc_type_t *) ((unsigned char *) vstate + sizeof(snacc_state_t));
state->work = (snacc_type_t *) ((unsigned char *) state->window + n * sizeof(snacc_type_t));
state->rbuf = (ringbuf *) ((unsigned char *) state->work + n * sizeof(snacc_type_t));
ringbuf_init(n, state->rbuf);
return GSL_SUCCESS;
}
static int
snacc_insert(const snacc_type_t x, void * vstate)
{
snacc_state_t * state = (snacc_state_t *) vstate;
/* add new element to ring buffer */
ringbuf_insert(x, state->rbuf);
return GSL_SUCCESS;
}
static int
snacc_delete(void * vstate)
{
snacc_state_t * state = (snacc_state_t *) vstate;
if (!ringbuf_is_empty(state->rbuf))
ringbuf_pop_back(state->rbuf);
return GSL_SUCCESS;
}
/* FIXME XXX: this is inefficient - could be improved by maintaining a sorted ring buffer */
static int
snacc_get(void * params, snacc_type_t * result, const void * vstate)
{
const snacc_state_t * state = (const snacc_state_t *) vstate;
size_t n = ringbuf_copy(state->window, state->rbuf);
(void) params;
gsl_sort(state->window, 1, n);
*result = gsl_stats_Sn_from_sorted_data(state->window, 1, n, state->work);
return GSL_SUCCESS;
}
static const gsl_movstat_accum sn_accum_type =
{
snacc_size,
snacc_init,
snacc_insert,
snacc_delete,
snacc_get
};
const gsl_movstat_accum *gsl_movstat_accum_Sn = &sn_accum_type;
| {
"alphanum_fraction": 0.7184237117,
"avg_line_length": 25.8173913043,
"ext": "c",
"hexsha": "de4dea6445d5d314e809f8e709140f9cc83b028b",
"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/snacc.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/snacc.c",
"max_line_length": 94,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "ielomariala/Hex-Game",
"max_stars_repo_path": "gsl-2.6/movstat/snacc.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": 817,
"size": 2969
} |
/***************************************************************************
* data_cf.h is part of Math Graphic Library
* Copyright (C) 2007-2016 Alexey Balakin <mathgl.abalakin@gmail.ru> *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU Library 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 Library 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 _MGL_DATA_CF_H_
#define _MGL_DATA_CF_H_
//-----------------------------------------------------------------------------
#include "mgl2/abstract.h"
//-----------------------------------------------------------------------------
#if MGL_HAVE_GSL
#include <gsl/gsl_vector.h>
#include <gsl/gsl_matrix.h>
#else
#ifdef __cplusplus
struct gsl_vector;
struct gsl_matrix;
#else
typedef void gsl_vector;
typedef void gsl_matrix;
#endif
#endif
//-----------------------------------------------------------------------------
#ifdef __cplusplus
extern "C" {
#endif
/// Get integer power of x
double MGL_EXPORT_CONST mgl_ipow(double x,int n);
double MGL_EXPORT_PURE mgl_ipow_(mreal *x,int *n);
/// Get number of seconds since 1970 for given string
double MGL_EXPORT mgl_get_time(const char *time, const char *fmt);
double MGL_EXPORT mgl_get_time_(const char *time, const char *fmt,int,int);
/// Create HMDT object
HMDT MGL_EXPORT mgl_create_data();
uintptr_t MGL_EXPORT mgl_create_data_();
/// Create HMDT object with specified sizes
HMDT MGL_EXPORT mgl_create_data_size(long nx, long ny, long nz);
uintptr_t MGL_EXPORT mgl_create_data_size_(int *nx, int *ny, int *nz);
/// Create HMDT object with data from file
HMDT MGL_EXPORT mgl_create_data_file(const char *fname);
uintptr_t MGL_EXPORT mgl_create_data_file_(const char *fname, int len);
/// Delete HMDT object
void MGL_EXPORT mgl_delete_data(HMDT dat);
void MGL_EXPORT mgl_delete_data_(uintptr_t *dat);
/// Rearange data dimensions
void MGL_EXPORT mgl_data_rearrange(HMDT dat, long mx,long my,long mz);
void MGL_EXPORT mgl_data_rearrange_(uintptr_t *dat, int *mx, int *my, int *mz);
/// Link external data array (don't delete it at exit)
void MGL_EXPORT mgl_data_link(HMDT dat, mreal *A,long mx,long my,long mz);
void MGL_EXPORT mgl_data_link_(uintptr_t *d, mreal *A, int *nx,int *ny,int *nz);
/// Allocate memory and copy the data from the (float *) array
void MGL_EXPORT mgl_data_set_float(HMDT dat, const float *A,long mx,long my,long mz);
void MGL_EXPORT mgl_data_set_float_(uintptr_t *dat, const float *A,int *NX,int *NY,int *NZ);
void MGL_EXPORT mgl_data_set_float1_(uintptr_t *d, const float *A,int *N1);
/// Allocate memory and copy the data from the (double *) array
void MGL_EXPORT mgl_data_set_double(HMDT dat, const double *A,long mx,long my,long mz);
void MGL_EXPORT mgl_data_set_double_(uintptr_t *dat, const double *A,int *NX,int *NY,int *NZ);
void MGL_EXPORT mgl_data_set_double1_(uintptr_t *d, const double *A,int *N1);
/// Allocate memory and copy the data from the (float **) array
void MGL_EXPORT mgl_data_set_float2(HMDT d, float const * const *A,long N1,long N2);
void MGL_EXPORT mgl_data_set_float2_(uintptr_t *d, const float *A,int *N1,int *N2);
/// Allocate memory and copy the data from the (double **) array
void MGL_EXPORT mgl_data_set_double2(HMDT d, double const * const *A,long N1,long N2);
void MGL_EXPORT mgl_data_set_double2_(uintptr_t *d, const double *A,int *N1,int *N2);
/// Allocate memory and copy the data from the (float ***) array
void MGL_EXPORT mgl_data_set_float3(HMDT d, float const * const * const *A,long N1,long N2,long N3);
void MGL_EXPORT mgl_data_set_float3_(uintptr_t *d, const float *A,int *N1,int *N2,int *N3);
/// Allocate memory and copy the data from the (double ***) array
void MGL_EXPORT mgl_data_set_double3(HMDT d, double const * const * const *A,long N1,long N2,long N3);
void MGL_EXPORT mgl_data_set_double3_(uintptr_t *d, const double *A,int *N1,int *N2,int *N3);
/// Import data from abstract type
void MGL_EXPORT mgl_data_set(HMDT dat, HCDT a);
void MGL_EXPORT mgl_data_set_(uintptr_t *dat, uintptr_t *a);
/// Allocate memory and copy the data from the gsl_vector
void MGL_EXPORT mgl_data_set_vector(HMDT dat, gsl_vector *v);
/// Allocate memory and copy the data from the gsl_matrix
void MGL_EXPORT mgl_data_set_matrix(HMDT dat, gsl_matrix *m);
/// Set value of data element [i,j,k]
void MGL_EXPORT mgl_data_set_value(HMDT dat, mreal v, long i, long j, long k);
void MGL_EXPORT mgl_data_set_value_(uintptr_t *d, mreal *v, int *i, int *j, int *k);
/// Get value of data element [i,j,k]
mreal MGL_EXPORT mgl_data_get_value(HCDT dat, long i, long j, long k);
mreal MGL_EXPORT mgl_data_get_value_(uintptr_t *d, int *i, int *j, int *k);
/// Allocate memory and scanf the data from the string
void MGL_EXPORT mgl_data_set_values(HMDT dat, const char *val, long nx, long ny, long nz);
void MGL_EXPORT mgl_data_set_values_(uintptr_t *d, const char *val, int *nx, int *ny, int *nz, int l);
/// Read data array from HDF file (parse HDF4 and HDF5 files)
int MGL_EXPORT mgl_data_read_hdf(HMDT d,const char *fname,const char *data);
int MGL_EXPORT mgl_data_read_hdf_(uintptr_t *d, const char *fname, const char *data,int l,int n);
/// Read data from tab-separated text file with auto determining size
int MGL_EXPORT mgl_data_read(HMDT dat, const char *fname);
int MGL_EXPORT mgl_data_read_(uintptr_t *d, const char *fname,int l);
/// Read data from text file with size specified at beginning of the file
int MGL_EXPORT mgl_data_read_mat(HMDT dat, const char *fname, long dim);
int MGL_EXPORT mgl_data_read_mat_(uintptr_t *dat, const char *fname, int *dim, int);
/// Read data from text file with specifeid size
int MGL_EXPORT mgl_data_read_dim(HMDT dat, const char *fname,long mx,long my,long mz);
int MGL_EXPORT mgl_data_read_dim_(uintptr_t *dat, const char *fname,int *mx,int *my,int *mz,int);
/// Read data from tab-separated text files with auto determining size which filenames are result of sprintf(fname,templ,t) where t=from:step:to
int MGL_EXPORT mgl_data_read_range(HMDT d, const char *templ, double n1, double n2, double step, int as_slice);
int MGL_EXPORT mgl_data_read_range_(uintptr_t *d, const char *fname, mreal *n1, mreal *n2, mreal *step, int *as_slice,int l);
/// Read data from tab-separated text files with auto determining size which filenames are satisfied to template (like "t_*.dat")
int MGL_EXPORT mgl_data_read_all(HMDT dat, const char *templ, int as_slice);
int MGL_EXPORT mgl_data_read_all_(uintptr_t *d, const char *fname, int *as_slice,int l);
/// Import data array from PNG file according color scheme
void MGL_EXPORT mgl_data_import(HMDT dat, const char *fname, const char *scheme,mreal v1,mreal v2);
void MGL_EXPORT mgl_data_import_(uintptr_t *dat, const char *fname, const char *scheme,mreal *v1,mreal *v2,int,int);
/// Scan textual file for template and fill data array
int MGL_EXPORT mgl_data_scan_file(HMDT dat,const char *fname, const char *templ);
int MGL_EXPORT mgl_data_scan_file_(uintptr_t *dat,const char *fname, const char *templ,int,int);
/// Read data array from Tektronix WFM file
/** Parse Tektronix TDS5000/B, TDS6000/B/C, TDS/CSA7000/B, MSO70000/C, DSA70000/B/C DPO70000/B/C DPO7000/ MSO/DPO5000. */
int MGL_EXPORT mgl_data_read_wfm(HMDT d,const char *fname, long num, long step, long start);
int MGL_EXPORT mgl_data_read_wfm_(uintptr_t *d, const char *fname, long *num, long *step, long *start,int l);
/// Read data array from Matlab MAT file (parse versions 4 and 5)
int MGL_EXPORT mgl_data_read_matlab(HMDT d,const char *fname,const char *data);
int MGL_EXPORT mgl_data_read_matlab_(uintptr_t *d, const char *fname, const char *data,int l,int n);
/// Create or recreate the array with specified size and fill it by zero
void MGL_EXPORT mgl_data_create(HMDT dat, long nx,long ny,long nz);
void MGL_EXPORT mgl_data_create_(uintptr_t *dat, int *nx,int *ny,int *nz);
/// Transpose dimensions of the data (generalization of Transpose)
void MGL_EXPORT mgl_data_transpose(HMDT dat, const char *dim);
void MGL_EXPORT mgl_data_transpose_(uintptr_t *dat, const char *dim,int);
/// Normalize the data to range [v1,v2]
void MGL_EXPORT mgl_data_norm(HMDT dat, mreal v1,mreal v2,int sym,long dim);
void MGL_EXPORT mgl_data_norm_(uintptr_t *dat, mreal *v1,mreal *v2,int *sym,int *dim);
/// Normalize the data to range [v1,v2] slice by slice
void MGL_EXPORT mgl_data_norm_slice(HMDT dat, mreal v1,mreal v2,char dir,long keep_en,long sym);
void MGL_EXPORT mgl_data_norm_slice_(uintptr_t *dat, mreal *v1,mreal *v2,char *dir,int *keep_en,int *sym,int l);
/// Limit the data to be inside [-v,v], keeping the original sign
void MGL_EXPORT mgl_data_limit(HMDT dat, mreal v);
void MGL_EXPORT mgl_data_limit_(uintptr_t *dat, mreal *v);
/// Project the periodical data to range [v1,v2] (like mod() function). Separate branches by NAN if sep=true.
void MGL_EXPORT mgl_data_coil(HMDT dat, mreal v1, mreal v2, int sep);
void MGL_EXPORT mgl_data_coil_(uintptr_t *dat, mreal *v1, mreal *v2, int *sep);
/// Get sub-array of the data with given fixed indexes
HMDT MGL_EXPORT mgl_data_subdata(HCDT dat, long xx,long yy,long zz);
uintptr_t MGL_EXPORT mgl_data_subdata_(uintptr_t *dat, int *xx,int *yy,int *zz);
/// Get sub-array of the data with given fixed indexes (like indirect access)
HMDT MGL_EXPORT mgl_data_subdata_ext(HCDT dat, HCDT xx, HCDT yy, HCDT zz);
uintptr_t MGL_EXPORT mgl_data_subdata_ext_(uintptr_t *dat, uintptr_t *xx,uintptr_t *yy,uintptr_t *zz);
/// Get column (or slice) of the data filled by formulas of named columns
HMDT MGL_EXPORT mgl_data_column(HCDT dat, const char *eq);
uintptr_t MGL_EXPORT mgl_data_column_(uintptr_t *dat, const char *eq,int l);
/// Get data from sections ids, separated by value val along specified direction.
/** If section id is negative then reverse order is used (i.e. -1 give last section). */
HMDT MGL_EXPORT mgl_data_section(HCDT dat, HCDT ids, char dir, mreal val);
uintptr_t MGL_EXPORT mgl_data_section_(uintptr_t *d, uintptr_t *ids, const char *dir, mreal *val,int);
/// Get data from section id, separated by value val along specified direction.
/** If section id is negative then reverse order is used (i.e. -1 give last section). */
HMDT MGL_EXPORT mgl_data_section_val(HCDT dat, long id, char dir, mreal val);
uintptr_t MGL_EXPORT mgl_data_section_val_(uintptr_t *d, int *id, const char *dir, mreal *val,int);
/// Get contour lines for dat[i,j]=val. NAN values separate the the curves
HMDT mgl_data_conts(mreal val, HCDT dat);
/// Equidistantly fill the data to range [x1,x2] in direction dir
void MGL_EXPORT mgl_data_fill(HMDT dat, mreal x1,mreal x2,char dir);
void MGL_EXPORT mgl_data_fill_(uintptr_t *dat, mreal *x1,mreal *x2,const char *dir,int);
/// Modify the data by specified formula assuming x,y,z in range [r1,r2]
void MGL_EXPORT mgl_data_fill_eq(HMGL gr, HMDT dat, const char *eq, HCDT vdat, HCDT wdat,const char *opt);
void MGL_EXPORT mgl_data_fill_eq_(uintptr_t *gr, uintptr_t *dat, const char *eq, uintptr_t *vdat, uintptr_t *wdat,const char *opt, int, int);
/// Fill dat by interpolated values of vdat parametrically depended on xdat for x in range [x1,x2] using global spline
void MGL_EXPORT mgl_data_refill_gs(HMDT dat, HCDT xdat, HCDT vdat, mreal x1, mreal x2, long sl);
void MGL_EXPORT mgl_data_refill_gs_(uintptr_t *dat, uintptr_t *xdat, uintptr_t *vdat, mreal *x1, mreal *x2, long *sl);
/// Fill dat by interpolated values of vdat parametrically depended on xdat for x in range [x1,x2]
void MGL_EXPORT mgl_data_refill_x(HMDT dat, HCDT xdat, HCDT vdat, mreal x1, mreal x2, long sl);
void MGL_EXPORT mgl_data_refill_x_(uintptr_t *dat, uintptr_t *xdat, uintptr_t *vdat, mreal *x1, mreal *x2, long *sl);
/// Fill dat by interpolated values of vdat parametrically depended on xdat,ydat for x,y in range [x1,x2]*[y1,y2]
void MGL_EXPORT mgl_data_refill_xy(HMDT dat, HCDT xdat, HCDT ydat, HCDT vdat, mreal x1, mreal x2, mreal y1, mreal y2, long sl);
void MGL_EXPORT mgl_data_refill_xy_(uintptr_t *dat, uintptr_t *xdat, uintptr_t *ydat, uintptr_t *vdat, mreal *x1, mreal *x2, mreal *y1, mreal *y2, long *sl);
/// Fill dat by interpolated values of vdat parametrically depended on xdat,ydat,zdat for x,y,z in range [x1,x2]*[y1,y2]*[z1,z2]
void MGL_EXPORT mgl_data_refill_xyz(HMDT dat, HCDT xdat, HCDT ydat, HCDT zdat, HCDT vdat, mreal x1, mreal x2, mreal y1, mreal y2, mreal z1, mreal z2);
void MGL_EXPORT mgl_data_refill_xyz_(uintptr_t *dat, uintptr_t *xdat, uintptr_t *ydat, uintptr_t *zdat, uintptr_t *vdat, mreal *x1, mreal *x2, mreal *y1, mreal *y2, mreal *z1, mreal *z2);
/// Fill dat by interpolated values of vdat parametrically depended on xdat,ydat,zdat for x,y,z in axis range
void MGL_EXPORT mgl_data_refill_gr(HMGL gr, HMDT dat, HCDT xdat, HCDT ydat, HCDT zdat, HCDT vdat, long sl, const char *opt);
void MGL_EXPORT mgl_data_refill_gr_(uintptr_t *gr, uintptr_t *dat, uintptr_t *xdat, uintptr_t *ydat, uintptr_t *zdat, uintptr_t *vdat, long *sl, const char *opt,int);
/// Set the data by triangulated surface values assuming x,y,z in range [r1,r2]
void MGL_EXPORT mgl_data_grid(HMGL gr, HMDT d, HCDT xdat, HCDT ydat, HCDT zdat,const char *opt);
void MGL_EXPORT mgl_data_grid_(uintptr_t *gr, uintptr_t *dat, uintptr_t *xdat, uintptr_t *ydat, uintptr_t *zdat, const char *opt,int);
/// Set the data by triangulated surface values assuming x,y,z in range [x1,x2]*[y1,y2]
void MGL_EXPORT mgl_data_grid_xy(HMDT d, HCDT xdat, HCDT ydat, HCDT zdat, mreal x1, mreal x2, mreal y1, mreal y2);
void MGL_EXPORT mgl_data_grid_xy_(uintptr_t *dat, uintptr_t *xdat, uintptr_t *ydat, uintptr_t *zdat, mreal *x1, mreal *x2, mreal *y1, mreal *y2);
/// Put value to data element(s)
void MGL_EXPORT mgl_data_put_val(HMDT dat, mreal val, long i, long j, long k);
void MGL_EXPORT mgl_data_put_val_(uintptr_t *dat, mreal *val, int *i, int *j, int *k);
/// Put array to data element(s)
void MGL_EXPORT mgl_data_put_dat(HMDT dat, HCDT val, long i, long j, long k);
void MGL_EXPORT mgl_data_put_dat_(uintptr_t *dat, uintptr_t *val, int *i, int *j, int *k);
/// Modify the data by specified formula
void MGL_EXPORT mgl_data_modify(HMDT dat, const char *eq,long dim);
void MGL_EXPORT mgl_data_modify_(uintptr_t *dat, const char *eq,int *dim,int);
/// Modify the data by specified formula
void MGL_EXPORT mgl_data_modify_vw(HMDT dat, const char *eq,HCDT vdat,HCDT wdat);
void MGL_EXPORT mgl_data_modify_vw_(uintptr_t *dat, const char *eq, uintptr_t *vdat, uintptr_t *wdat,int);
/// Reduce size of the data
void MGL_EXPORT mgl_data_squeeze(HMDT dat, long rx,long ry,long rz,long smooth);
void MGL_EXPORT mgl_data_squeeze_(uintptr_t *dat, int *rx,int *ry,int *rz,int *smooth);
/// Get array which is n-th pairs {x[i],y[i]} for iterated function system (fractal) generated by A
/** NOTE: A.nx must be >= 7. */
HMDT MGL_EXPORT mgl_data_ifs_2d(HCDT A, long n, long skip);
uintptr_t MGL_EXPORT mgl_data_ifs_2d_(uintptr_t *A, long *n, long *skip);
/// Get array which is n-th points {x[i],y[i],z[i]} for iterated function system (fractal) generated by A
/** NOTE: A.nx must be >= 13. */
HMDT MGL_EXPORT mgl_data_ifs_3d(HCDT A, long n, long skip);
uintptr_t MGL_EXPORT mgl_data_ifs_3d_(uintptr_t *A, long *n, long *skip);
/// Get array which is n-th points {x[i],y[i],z[i]} for iterated function system (fractal) defined in *.ifs file 'fname' and named as 'name'
HMDT MGL_EXPORT mgl_data_ifs_file(const char *fname, const char *name, long n, long skip);
uintptr_t mgl_data_ifs_file_(const char *fname, const char *name, long *n, long *skip,int l,int m);
/// Codes for flame fractal functions
enum {
mglFlame2d_linear=0, mglFlame2d_sinusoidal, mglFlame2d_spherical, mglFlame2d_swirl, mglFlame2d_horseshoe,
mglFlame2d_polar, mglFlame2d_handkerchief,mglFlame2d_heart, mglFlame2d_disc, mglFlame2d_spiral,
mglFlame2d_hyperbolic, mglFlame2d_diamond, mglFlame2d_ex, mglFlame2d_julia, mglFlame2d_bent,
mglFlame2d_waves, mglFlame2d_fisheye, mglFlame2d_popcorn, mglFlame2d_exponential, mglFlame2d_power,
mglFlame2d_cosine, mglFlame2d_rings, mglFlame2d_fan, mglFlame2d_blob, mglFlame2d_pdj,
mglFlame2d_fan2, mglFlame2d_rings2, mglFlame2d_eyefish, mglFlame2d_bubble, mglFlame2d_cylinder,
mglFlame2d_perspective, mglFlame2d_noise, mglFlame2d_juliaN, mglFlame2d_juliaScope, mglFlame2d_blur,
mglFlame2d_gaussian, mglFlame2d_radialBlur, mglFlame2d_pie, mglFlame2d_ngon, mglFlame2d_curl,
mglFlame2d_rectangles, mglFlame2d_arch, mglFlame2d_tangent, mglFlame2d_square, mglFlame2d_blade,
mglFlame2d_secant, mglFlame2d_rays, mglFlame2d_twintrian, mglFlame2d_cross, mglFlame2d_disc2,
mglFlame2d_supershape, mglFlame2d_flower, mglFlame2d_conic, mglFlame2d_parabola, mglFlame2d_bent2,
mglFlame2d_bipolar, mglFlame2d_boarders, mglFlame2d_butterfly, mglFlame2d_cell, mglFlame2d_cpow,
mglFlame2d_curve, mglFlame2d_edisc, mglFlame2d_elliptic, mglFlame2d_escher, mglFlame2d_foci,
mglFlame2d_lazySusan, mglFlame2d_loonie, mglFlame2d_preBlur, mglFlame2d_modulus, mglFlame2d_oscope,
mglFlame2d_polar2, mglFlame2d_popcorn2, mglFlame2d_scry, mglFlame2d_separation, mglFlame2d_split,
mglFlame2d_splits, mglFlame2d_stripes, mglFlame2d_wedge, mglFlame2d_wedgeJulia, mglFlame2d_wedgeSph,
mglFlame2d_whorl, mglFlame2d_waves2, mglFlame2d_exp, mglFlame2d_log, mglFlame2d_sin,
mglFlame2d_cos, mglFlame2d_tan, mglFlame2d_sec, mglFlame2d_csc, mglFlame2d_cot,
mglFlame2d_sinh, mglFlame2d_cosh, mglFlame2d_tanh, mglFlame2d_sech, mglFlame2d_csch,
mglFlame2d_coth, mglFlame2d_auger, mglFlame2d_flux, mglFlame2dLAST
};
/// Get array which is n-th pairs {x[i],y[i]} for Flame fractal generated by A with functions F
/** NOTE: A.nx must be >= 7 and F.nx >= 2 and F.nz=A.ny.
* F[0,i,j] denote function id. F[1,i,j] give function weight. F(2:5,i,j) provide function parameters.
* Resulting point is {xnew,ynew} = sum_i F[1,i,j]*F[0,i,j]{IFS2d(A[j]){x,y}}. */
HMDT MGL_EXPORT mgl_data_flame_2d(HCDT A, HCDT F, long n, long skip);
uintptr_t MGL_EXPORT mgl_data_flame_2d_(uintptr_t *A, uintptr_t *F, long *n, long *skip);
/// Get curves, separated by NAN, for maximal values of array d as function of x coordinate.
/** Noises below lvl amplitude are ignored.
* Parameter dy \in [0,ny] set the "attraction" distance of points to curve. */
HMDT MGL_EXPORT mgl_data_detect(HCDT d, mreal lvl, mreal dj, mreal di, mreal min_len);
uintptr_t MGL_EXPORT mgl_data_detect_(uintptr_t *d, mreal *lvl, mreal *dj, mreal *di, mreal *min_len);
/// Get array as solution of tridiagonal matrix solution a[i]*x[i-1]+b[i]*x[i]+c[i]*x[i+1]=d[i]
/** String \a how may contain:
* 'x', 'y', 'z' for solving along x-,y-,z-directions, or
* 'h' for solving along hexagonal direction at x-y plain (need nx=ny),
* 'c' for using periodical boundary conditions,
* 'd' for diffraction/diffuse calculation.
* NOTE: It work for flat data model only (i.e. for a[i,j]==a[i+nx*j]) */
HMDT MGL_EXPORT mgl_data_tridmat(HCDT A, HCDT B, HCDT C, HCDT D, const char *how);
uintptr_t MGL_EXPORT mgl_data_tridmat_(uintptr_t *A, uintptr_t *B, uintptr_t *C, uintptr_t *D, const char *how, int);
/// Returns pointer to data element [i,j,k]
MGL_EXPORT mreal *mgl_data_value(HMDT dat, long i,long j,long k);
/// Returns pointer to internal data array
MGL_EXPORT_PURE mreal *mgl_data_data(HMDT dat);
/// Gets the x-size of the data.
long MGL_EXPORT mgl_data_get_nx(HCDT d);
long MGL_EXPORT mgl_data_get_nx_(uintptr_t *d);
/// Gets the y-size of the data.
long MGL_EXPORT mgl_data_get_ny(HCDT d);
long MGL_EXPORT mgl_data_get_ny_(uintptr_t *d);
/// Gets the z-size of the data.
long MGL_EXPORT mgl_data_get_nz(HCDT d);
long MGL_EXPORT mgl_data_get_nz_(uintptr_t *d);
/// Get the data which is direct multiplication (like, d[i,j] = this[i]*a[j] and so on)
HMDT MGL_EXPORT mgl_data_combine(HCDT dat1, HCDT dat2);
uintptr_t MGL_EXPORT mgl_data_combine_(uintptr_t *dat1, uintptr_t *dat2);
/// Extend data dimensions
void MGL_EXPORT mgl_data_extend(HMDT dat, long n1, long n2);
void MGL_EXPORT mgl_data_extend_(uintptr_t *dat, int *n1, int *n2);
/// Insert data rows/columns/slices
void MGL_EXPORT mgl_data_insert(HMDT dat, char dir, long at, long num);
void MGL_EXPORT mgl_data_insert_(uintptr_t *dat, const char *dir, int *at, int *num, int);
/// Delete data rows/columns/slices
void MGL_EXPORT mgl_data_delete(HMDT dat, char dir, long at, long num);
void MGL_EXPORT mgl_data_delete_(uintptr_t *dat, const char *dir, int *at, int *num, int);
/// Joind another data array
void MGL_EXPORT mgl_data_join(HMDT dat, HCDT d);
void MGL_EXPORT mgl_data_join_(uintptr_t *dat, uintptr_t *d);
/// Smooth the data on specified direction or directions
/** String \a dir may contain:
* ‘x’, ‘y’, ‘z’ for 1st, 2nd or 3d dimension;
* ‘dN’ for linear averaging over N points;
* ‘3’ for linear averaging over 3 points;
* ‘5’ for linear averaging over 5 points.
* By default quadratic averaging over 5 points is used. */
void MGL_EXPORT mgl_data_smooth(HMDT d, const char *dirs, mreal delta);
void MGL_EXPORT mgl_data_smooth_(uintptr_t *dat, const char *dirs, mreal *delta,int);
/// Get array which is result of summation in given direction or directions
HMDT MGL_EXPORT mgl_data_sum(HCDT dat, const char *dir);
uintptr_t MGL_EXPORT mgl_data_sum_(uintptr_t *dat, const char *dir,int);
/// Get array which is result of maximal values in given direction or directions
HMDT MGL_EXPORT mgl_data_max_dir(HCDT dat, const char *dir);
uintptr_t MGL_EXPORT mgl_data_max_dir_(uintptr_t *dat, const char *dir,int);
/// Get array which is result of minimal values in given direction or directions
HMDT MGL_EXPORT mgl_data_min_dir(HCDT dat, const char *dir);
uintptr_t MGL_EXPORT mgl_data_min_dir_(uintptr_t *dat, const char *dir,int);
/// Get positions of local maximums and minimums
HMDT MGL_EXPORT mgl_data_minmax(HCDT dat);
uintptr_t MGL_EXPORT mgl_data_minmax_(uintptr_t *dat);
/// Get indexes of a set of connected surfaces for set of values {a_ijk,b_ijk} as dependent on j,k
/** NOTE: not optimized for general case!!! */
HMDT MGL_EXPORT mgl_data_connect(HCDT a, HCDT b);
uintptr_t MGL_EXPORT mgl_data_connect_(uintptr_t *a, uintptr_t *b);
/// Resort data values according found connected surfaces for set of values {a_ijk,b_ijk} as dependent on j,k
/** NOTE: not optimized for general case!!! */
void MGL_EXPORT mgl_data_connect_r(HMDT a, HMDT b);
void MGL_EXPORT mgl_data_connect_r_(uintptr_t *a, uintptr_t *b);
/// Cumulative summation the data in given direction or directions
void MGL_EXPORT mgl_data_cumsum(HMDT dat, const char *dir);
void MGL_EXPORT mgl_data_cumsum_(uintptr_t *dat, const char *dir,int);
/// Integrate (cumulative summation) the data in given direction or directions
void MGL_EXPORT mgl_data_integral(HMDT dat, const char *dir);
void MGL_EXPORT mgl_data_integral_(uintptr_t *dat, const char *dir,int);
/// Differentiate the data in given direction or directions
void MGL_EXPORT mgl_data_diff(HMDT dat, const char *dir);
void MGL_EXPORT mgl_data_diff_(uintptr_t *dat, const char *dir,int);
/// Differentiate the parametrically specified data along direction v1 with v2,v3=const (v3 can be NULL)
void MGL_EXPORT mgl_data_diff_par(HMDT dat, HCDT v1, HCDT v2, HCDT v3);
void MGL_EXPORT mgl_data_diff_par_(uintptr_t *dat, uintptr_t *v1, uintptr_t *v2, uintptr_t *v3);
/// Double-differentiate (like Laplace operator) the data in given direction
void MGL_EXPORT mgl_data_diff2(HMDT dat, const char *dir);
void MGL_EXPORT mgl_data_diff2_(uintptr_t *dat, const char *dir,int);
/// Swap left and right part of the data in given direction (useful for Fourier spectrum)
void MGL_EXPORT mgl_data_swap(HMDT dat, const char *dir);
void MGL_EXPORT mgl_data_swap_(uintptr_t *dat, const char *dir,int);
/// Roll data along direction dir by num slices
void MGL_EXPORT mgl_data_roll(HMDT dat, char dir, long num);
void MGL_EXPORT mgl_data_roll_(uintptr_t *dat, const char *dir, int *num, int);
/// Mirror the data in given direction (useful for Fourier spectrum)
void MGL_EXPORT mgl_data_mirror(HMDT dat, const char *dir);
void MGL_EXPORT mgl_data_mirror_(uintptr_t *dat, const char *dir,int);
/// Sort rows (or slices) by values of specified column
void MGL_EXPORT mgl_data_sort(HMDT dat, long idx, long idy);
void MGL_EXPORT mgl_data_sort_(uintptr_t *dat, int *idx, int *idy);
/// Return dilated array of 0 or 1 for data values larger val
void MGL_EXPORT mgl_data_dilate(HMDT dat, mreal val, long step);
void MGL_EXPORT mgl_data_dilate_(uintptr_t *dat, mreal *val, int *step);
/// Return eroded array of 0 or 1 for data values larger val
void MGL_EXPORT mgl_data_erode(HMDT dat, mreal val, long step);
void MGL_EXPORT mgl_data_erode_(uintptr_t *dat, mreal *val, int *step);
/// Apply Hankel transform
void MGL_EXPORT mgl_data_hankel(HMDT dat, const char *dir);
void MGL_EXPORT mgl_data_hankel_(uintptr_t *dat, const char *dir,int);
/// Apply Sin-Fourier transform
void MGL_EXPORT mgl_data_sinfft(HMDT dat, const char *dir);
void MGL_EXPORT mgl_data_sinfft_(uintptr_t *dat, const char *dir,int);
/// Apply Cos-Fourier transform
void MGL_EXPORT mgl_data_cosfft(HMDT dat, const char *dir);
void MGL_EXPORT mgl_data_cosfft_(uintptr_t *dat, const char *dir,int);
/// Fill data by coordinates/momenta samples for Hankel ('h') or Fourier ('f') transform
/** Parameter \a how may contain:
* ‘x‘,‘y‘,‘z‘ for direction (only one will be used),
* ‘k‘ for momenta samples,
* ‘h‘ for Hankel samples,
* ‘f‘ for Cartesian/Fourier samples (default). */
void MGL_EXPORT mgl_data_fill_sample(HMDT dat, const char *how);
void MGL_EXPORT mgl_data_fill_sample_(uintptr_t *dat, const char *how,int);
/// Find correlation between 2 data arrays
HMDT MGL_EXPORT mgl_data_correl(HCDT dat1, HCDT dat2, const char *dir);
uintptr_t MGL_EXPORT mgl_data_correl_(uintptr_t *dat1, uintptr_t *dat2, const char *dir,int);
/// Apply wavelet transform
/** Parameter \a dir may contain:
* ‘x‘,‘y‘,‘z‘ for directions,
* ‘d‘ for daubechies, ‘D‘ for centered daubechies,
* ‘h‘ for haar, ‘H‘ for centered haar,
* ‘b‘ for bspline, ‘B‘ for centered bspline,
* ‘i‘ for applying inverse transform. */
void MGL_EXPORT mgl_data_wavelet(HMDT dat, const char *how, int k);
void MGL_EXPORT mgl_data_wavelet_(uintptr_t *d, const char *dir, int *k,int);
/// Allocate and prepare data for Fourier transform by nthr threads
MGL_EXPORT void *mgl_fft_alloc(long n, void **space, long nthr);
MGL_EXPORT void *mgl_fft_alloc_thr(long n);
/// Free data for Fourier transform
void MGL_EXPORT mgl_fft_free(void *wt, void **ws, long nthr);
void MGL_EXPORT mgl_fft_free_thr(void *wt);
/// Make Fourier transform of data x of size n and step s between points
void MGL_EXPORT mgl_fft(double *x, long s, long n, const void *wt, void *ws, int inv);
/// Clear internal data for speeding up FFT and Hankel transforms
void MGL_EXPORT mgl_clear_fft();
/// Interpolate by cubic spline the data to given point x=[0...nx-1], y=[0...ny-1], z=[0...nz-1]
mreal MGL_EXPORT mgl_data_spline(HCDT dat, mreal x,mreal y,mreal z);
mreal MGL_EXPORT mgl_data_spline_(uintptr_t *dat, mreal *x,mreal *y,mreal *z);
/// Interpolate by cubic spline the data and return its derivatives at given point x=[0...nx-1], y=[0...ny-1], z=[0...nz-1]
mreal MGL_EXPORT mgl_data_spline_ext(HCDT dat, mreal x,mreal y,mreal z, mreal *dx,mreal *dy,mreal *dz);
mreal MGL_EXPORT mgl_data_spline_ext_(uintptr_t *dat, mreal *x,mreal *y,mreal *z, mreal *dx,mreal *dy,mreal *dz);
/// Prepare coefficients for global spline interpolation
HMDT MGL_EXPORT mgl_gspline_init(HCDT x, HCDT v);
uintptr_t MGL_EXPORT mgl_gspline_init_(uintptr_t *x, uintptr_t *v);
/// Evaluate global spline (and its derivatives d1, d2 if not NULL) using prepared coefficients \a coef
mreal MGL_EXPORT mgl_gspline(HCDT coef, mreal dx, mreal *d1, mreal *d2);
mreal MGL_EXPORT mgl_gspline_(uintptr_t *c, mreal *dx, mreal *d1, mreal *d2);
/// Return an approximated x-value (root) when dat(x) = val
mreal MGL_EXPORT mgl_data_solve_1d(HCDT dat, mreal val, int spl, long i0);
mreal MGL_EXPORT mgl_data_solve_1d_(uintptr_t *dat, mreal *val, int *spl, int *i0);
/// Return an approximated value (root) when dat(x) = val
HMDT MGL_EXPORT mgl_data_solve(HCDT dat, mreal val, char dir, HCDT i0, int norm);
uintptr_t MGL_EXPORT mgl_data_solve_(uintptr_t *dat, mreal *val, const char *dir, uintptr_t *i0, int *norm,int);
/// Get trace of the data array
HMDT MGL_EXPORT mgl_data_trace(HCDT d);
uintptr_t MGL_EXPORT mgl_data_trace_(uintptr_t *d);
/// Resize the data to new sizes
HMDT MGL_EXPORT mgl_data_resize(HCDT dat, long mx,long my,long mz);
uintptr_t MGL_EXPORT mgl_data_resize_(uintptr_t *dat, int *mx,int *my,int *mz);
/// Resize the data to new sizes of box [x1,x2]*[y1,y2]*[z1,z2]
HMDT MGL_EXPORT mgl_data_resize_box(HCDT dat, long mx,long my,long mz,mreal x1,mreal x2,mreal y1,mreal y2,mreal z1,mreal z2);
uintptr_t MGL_EXPORT mgl_data_resize_box_(uintptr_t *dat, int *mx,int *my,int *mz,mreal *x1,mreal *x2,mreal *y1,mreal *y2,mreal *z1,mreal *z2);
/// Create n-th points distribution of this data values in range [v1, v2]
HMDT MGL_EXPORT mgl_data_hist(HCDT dat, long n, mreal v1, mreal v2, long nsub);
uintptr_t MGL_EXPORT mgl_data_hist_(uintptr_t *dat, int *n, mreal *v1, mreal *v2, int *nsub);
/// Create n-th points distribution of this data values in range [v1, v2] with weight w
HMDT MGL_EXPORT mgl_data_hist_w(HCDT dat, HCDT weight, long n, mreal v1, mreal v2, long nsub);
uintptr_t MGL_EXPORT mgl_data_hist_w_(uintptr_t *dat, uintptr_t *weight, int *n, mreal *v1, mreal *v2, int *nsub);
/// Get momentum (1D-array) of data along direction 'dir'. String looks like "x1" for median in x-direction, "x2" for width in x-dir and so on.
HMDT MGL_EXPORT mgl_data_momentum(HCDT dat, char dir, const char *how);
uintptr_t MGL_EXPORT mgl_data_momentum_(uintptr_t *dat, char *dir, const char *how, int,int);
/// Get pulse properties: pulse maximum and its position, pulse duration near maximum and by half height.
HMDT MGL_EXPORT mgl_data_pulse(HCDT dat, char dir);
uintptr_t MGL_EXPORT mgl_data_pulse_(uintptr_t *dat, char *dir,int);
/// Get array which values is result of interpolation this for coordinates from other arrays
HMDT MGL_EXPORT mgl_data_evaluate(HCDT dat, HCDT idat, HCDT jdat, HCDT kdat, int norm);
uintptr_t MGL_EXPORT mgl_data_evaluate_(uintptr_t *dat, uintptr_t *idat, uintptr_t *jdat, uintptr_t *kdat, int *norm);
/// Set as the data envelop
void MGL_EXPORT mgl_data_envelop(HMDT dat, char dir);
void MGL_EXPORT mgl_data_envelop_(uintptr_t *dat, const char *dir, int);
/// Remove phase jump
void MGL_EXPORT mgl_data_sew(HMDT dat, const char *dirs, mreal da);
void MGL_EXPORT mgl_data_sew_(uintptr_t *dat, const char *dirs, mreal *da, int);
/// Crop the data
void MGL_EXPORT mgl_data_crop(HMDT dat, long n1, long n2, char dir);
void MGL_EXPORT mgl_data_crop_(uintptr_t *dat, int *n1, int *n2, const char *dir,int);
/// Crop the data to be most optimal for FFT (i.e. to closest value of 2^n*3^m*5^l)
void MGL_EXPORT mgl_data_crop_opt(HMDT dat, const char *how);
void MGL_EXPORT mgl_data_crop_opt_(uintptr_t *dat, const char *how,int);
/// Remove rows with duplicate values in column id
void MGL_EXPORT mgl_data_clean(HMDT dat, long id);
void MGL_EXPORT mgl_data_clean_(uintptr_t *dat, int *id);
/// Multiply the data by other one for each element
void MGL_EXPORT mgl_data_mul_dat(HMDT dat, HCDT d);
void MGL_EXPORT mgl_data_mul_dat_(uintptr_t *dat, uintptr_t *d);
/// Divide the data by other one for each element
void MGL_EXPORT mgl_data_div_dat(HMDT dat, HCDT d);
void MGL_EXPORT mgl_data_div_dat_(uintptr_t *dat, uintptr_t *d);
/// Add the other data
void MGL_EXPORT mgl_data_add_dat(HMDT dat, HCDT d);
void MGL_EXPORT mgl_data_add_dat_(uintptr_t *dat, uintptr_t *d);
/// Subtract the other data
void MGL_EXPORT mgl_data_sub_dat(HMDT dat, HCDT d);
void MGL_EXPORT mgl_data_sub_dat_(uintptr_t *dat, uintptr_t *d);
/// Multiply each element by the number
void MGL_EXPORT mgl_data_mul_num(HMDT dat, mreal d);
void MGL_EXPORT mgl_data_mul_num_(uintptr_t *dat, mreal *d);
/// Divide each element by the number
void MGL_EXPORT mgl_data_div_num(HMDT dat, mreal d);
void MGL_EXPORT mgl_data_div_num_(uintptr_t *dat, mreal *d);
/// Add the number
void MGL_EXPORT mgl_data_add_num(HMDT dat, mreal d);
void MGL_EXPORT mgl_data_add_num_(uintptr_t *dat, mreal *d);
/// Subtract the number
void MGL_EXPORT mgl_data_sub_num(HMDT dat, mreal d);
void MGL_EXPORT mgl_data_sub_num_(uintptr_t *dat, mreal *d);
/// Integral data transformation (like Fourier 'f' or 'i', Hankel 'h' or None 'n') for amplitude and phase
HMDT MGL_EXPORT mgl_transform_a(HCDT am, HCDT ph, const char *tr);
uintptr_t MGL_EXPORT mgl_transform_a_(uintptr_t *am, uintptr_t *ph, const char *tr, int);
/// Integral data transformation (like Fourier 'f' or 'i', Hankel 'h' or None 'n') for real and imaginary parts
HMDT MGL_EXPORT mgl_transform(HCDT re, HCDT im, const char *tr);
uintptr_t MGL_EXPORT mgl_transform_(uintptr_t *re, uintptr_t *im, const char *tr, int);
/// Apply Fourier transform for the data and save result into it
void MGL_EXPORT mgl_data_fourier(HMDT re, HMDT im, const char *dir);
void MGL_EXPORT mgl_data_fourier_(uintptr_t *re, uintptr_t *im, const char *dir, int l);
/// Short time Fourier analysis for real and imaginary parts. Output is amplitude of partial Fourier (result will have size {dn, floor(nx/dn), ny} for dir='x'
HMDT MGL_EXPORT mgl_data_stfa(HCDT re, HCDT im, long dn, char dir);
uintptr_t MGL_EXPORT mgl_data_stfa_(uintptr_t *re, uintptr_t *im, int *dn, char *dir, int);
/// Do something like Delone triangulation for 3d points
HMDT MGL_EXPORT mgl_triangulation_3d(HCDT x, HCDT y, HCDT z);
uintptr_t MGL_EXPORT mgl_triangulation_3d_(uintptr_t *x, uintptr_t *y, uintptr_t *z);
/// Do Delone triangulation for 2d points
HMDT MGL_EXPORT mgl_triangulation_2d(HCDT x, HCDT y);
uintptr_t MGL_EXPORT mgl_triangulation_2d_(uintptr_t *x, uintptr_t *y);
/// Find root for nonlinear equation
mreal MGL_EXPORT mgl_find_root(mreal (*func)(mreal val, void *par), mreal ini, void *par);
/// Find root for nonlinear equation defined by textual formula
mreal MGL_EXPORT mgl_find_root_txt(const char *func, mreal ini, char var_id);
mreal MGL_EXPORT mgl_find_root_txt_(const char *func, mreal *ini, const char *var_id,int,int);
/// Find roots for nonlinear equation defined by textual formula
HMDT MGL_EXPORT mgl_data_roots(const char *func, HCDT ini, char var_id);
uintptr_t MGL_EXPORT mgl_data_roots_(const char *func, uintptr_t *ini, const char *var_id,int,int);
/// Find roots for set of nonlinear equations defined by textual formulas
HMDT MGL_EXPORT mgl_find_roots_txt(const char *func, const char *vars, HCDT ini);
uintptr_t MGL_EXPORT mgl_find_roots_txt_(const char *func, const char *vars, uintptr_t *ini,int,int);
/// Find roots for set of nonlinear equations defined by function
int MGL_EXPORT mgl_find_roots(size_t n, void (*func)(const mreal *x, mreal *f, void *par), mreal *x0, void *par);
//-----------------------------------------------------------------------------
#ifdef __cplusplus
}
#endif
#endif
//-----------------------------------------------------------------------------
| {
"alphanum_fraction": 0.735805108,
"avg_line_length": 68.3370786517,
"ext": "h",
"hexsha": "d6e098720e2de2e4428a5453e51b3d013d683b1f",
"lang": "C",
"max_forks_count": 14,
"max_forks_repo_forks_event_max_datetime": "2022-03-10T00:47:15.000Z",
"max_forks_repo_forks_event_min_datetime": "2019-12-05T12:55:43.000Z",
"max_forks_repo_head_hexsha": "dc738b9fac053ef62381ecbe88add6f6fe949fe3",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "dickensas/kotlin-gradle-templates",
"max_forks_repo_path": "openal-mathgl-generate/include/mgl2/data_cf.h",
"max_issues_count": 2,
"max_issues_repo_head_hexsha": "dc738b9fac053ef62381ecbe88add6f6fe949fe3",
"max_issues_repo_issues_event_max_datetime": "2021-01-08T06:16:28.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-07-31T10:50:54.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "dickensas/kotlin-gradle-templates",
"max_issues_repo_path": "openal-mathgl-generate/include/mgl2/data_cf.h",
"max_line_length": 188,
"max_stars_count": 54,
"max_stars_repo_head_hexsha": "dc738b9fac053ef62381ecbe88add6f6fe949fe3",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "dickensas/kotlin-gradle-templates",
"max_stars_repo_path": "openal-mathgl-generate/include/mgl2/data_cf.h",
"max_stars_repo_stars_event_max_datetime": "2022-03-20T14:28:02.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-11-12T03:55:12.000Z",
"num_tokens": 11141,
"size": 36492
} |
/**
* Copyright (C) 2021 FISCO BCOS.
* SPDX-License-Identifier: Apache-2.0
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @brief implementation for BlockHeader
* @file BlockHeaderImpl.h
* @author: ancelmo
* @date 2021-04-20
*/
#pragma once
#include "bcos-tars-protocol/Common.h"
#include "bcos-tars-protocol/tars/Block.h"
#include <bcos-framework/interfaces/crypto/CommonType.h>
#include <bcos-framework/interfaces/crypto/CryptoSuite.h>
#include <bcos-framework/interfaces/protocol/BlockHeader.h>
#include <bcos-framework/interfaces/protocol/ProtocolTypeDef.h>
#include <gsl/span>
namespace bcostars
{
namespace protocol
{
class BlockHeaderImpl : public bcos::protocol::BlockHeader
{
public:
virtual ~BlockHeaderImpl() {}
BlockHeaderImpl() = delete;
BlockHeaderImpl(
bcos::crypto::CryptoSuite::Ptr cryptoSuite, std::function<bcostars::BlockHeader*()> inner)
: bcos::protocol::BlockHeader(cryptoSuite), m_inner(inner)
{}
void decode(bcos::bytesConstRef _data) override;
void encode(bcos::bytes& _encodeData) const override;
bcos::crypto::HashType hash() const override;
void clear() override;
int32_t version() const override { return m_inner()->data.version; }
gsl::span<const bcos::protocol::ParentInfo> parentInfo() const override;
bcos::crypto::HashType txsRoot() const override;
bcos::crypto::HashType stateRoot() const override;
bcos::crypto::HashType receiptsRoot() const override;
bcos::protocol::BlockNumber number() const override { return m_inner()->data.blockNumber; }
bcos::u256 gasUsed() const override;
int64_t timestamp() const override { return m_inner()->data.timestamp; }
int64_t sealer() const override { return m_inner()->data.sealer; }
gsl::span<const bcos::bytes> sealerList() const override
{
return gsl::span(reinterpret_cast<const bcos::bytes*>(m_inner()->data.sealerList.data()),
m_inner()->data.sealerList.size());
}
bcos::bytesConstRef extraData() const override
{
return bcos::bytesConstRef(
reinterpret_cast<const bcos::byte*>(m_inner()->data.extraData.data()),
m_inner()->data.extraData.size());
}
gsl::span<const bcos::protocol::Signature> signatureList() const override
{
return gsl::span(
reinterpret_cast<const bcos::protocol::Signature*>(m_inner()->signatureList.data()),
m_inner()->signatureList.size());
}
gsl::span<const uint64_t> consensusWeights() const override
{
return gsl::span(reinterpret_cast<const uint64_t*>(m_inner()->data.consensusWeights.data()),
m_inner()->data.consensusWeights.size());
}
void setVersion(int32_t _version) override { m_inner()->data.version = _version; }
void setParentInfo(gsl::span<const bcos::protocol::ParentInfo> const& _parentInfo) override;
void setParentInfo(bcos::protocol::ParentInfoList&& _parentInfo) override
{
setParentInfo(gsl::span(_parentInfo.data(), _parentInfo.size()));
}
void setTxsRoot(bcos::crypto::HashType _txsRoot) override
{
m_inner()->data.txsRoot.assign(_txsRoot.begin(), _txsRoot.end());
}
void setReceiptsRoot(bcos::crypto::HashType _receiptsRoot) override
{
m_inner()->data.receiptRoot.assign(_receiptsRoot.begin(), _receiptsRoot.end());
}
void setStateRoot(bcos::crypto::HashType _stateRoot) override
{
m_inner()->data.stateRoot.assign(_stateRoot.begin(), _stateRoot.end());
}
void setNumber(bcos::protocol::BlockNumber _blockNumber) override
{
m_inner()->data.blockNumber = _blockNumber;
}
void setGasUsed(bcos::u256 _gasUsed) override
{
m_inner()->data.gasUsed = boost::lexical_cast<std::string>(_gasUsed);
}
void setTimestamp(int64_t _timestamp) override { m_inner()->data.timestamp = _timestamp; }
void setSealer(int64_t _sealerId) override { m_inner()->data.sealer = _sealerId; }
void setSealerList(gsl::span<const bcos::bytes> const& _sealerList) override;
void setSealerList(std::vector<bcos::bytes>&& _sealerList) override
{
setSealerList(gsl::span(_sealerList.data(), _sealerList.size()));
}
void setConsensusWeights(gsl::span<const uint64_t> const& _weightList) override
{
m_inner()->data.consensusWeights.assign(_weightList.begin(), _weightList.end());
}
void setConsensusWeights(std::vector<uint64_t>&& _weightList) override
{
setConsensusWeights(gsl::span(_weightList.data(), _weightList.size()));
}
void setExtraData(bcos::bytes const& _extraData) override
{
m_inner()->data.extraData.assign(_extraData.begin(), _extraData.end());
}
void setExtraData(bcos::bytes&& _extraData) override
{
m_inner()->data.extraData.assign(_extraData.begin(), _extraData.end());
}
void setSignatureList(
gsl::span<const bcos::protocol::Signature> const& _signatureList) override;
void setSignatureList(bcos::protocol::SignatureList&& _signatureList) override
{
setSignatureList(gsl::span(_signatureList.data(), _signatureList.size()));
}
const bcostars::BlockHeader& inner() const { return *m_inner(); }
void setInner(const bcostars::BlockHeader& blockHeader) { *m_inner() = blockHeader; }
void setInner(bcostars::BlockHeader&& blockHeader) { *m_inner() = std::move(blockHeader); }
private:
std::function<bcostars::BlockHeader*()> m_inner;
mutable std::vector<bcos::protocol::ParentInfo> m_parentInfo;
};
} // namespace protocol
} // namespace bcostars | {
"alphanum_fraction": 0.6953328982,
"avg_line_length": 38.0621118012,
"ext": "h",
"hexsha": "45fd2e07fa4190c0b1688dc191883a1d5757a887",
"lang": "C",
"max_forks_count": 3,
"max_forks_repo_forks_event_max_datetime": "2021-12-06T06:35:57.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-09-08T02:39:58.000Z",
"max_forks_repo_head_hexsha": "737e08752e8904c7c24e3737f8f46bf5327ef792",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "xueying4402/FISCO-BCOS",
"max_forks_repo_path": "bcos-tars-protocol/protocol/BlockHeaderImpl.h",
"max_issues_count": 20,
"max_issues_repo_head_hexsha": "737e08752e8904c7c24e3737f8f46bf5327ef792",
"max_issues_repo_issues_event_max_datetime": "2021-12-07T14:19:09.000Z",
"max_issues_repo_issues_event_min_datetime": "2021-09-14T12:23:12.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "xueying4402/FISCO-BCOS",
"max_issues_repo_path": "bcos-tars-protocol/protocol/BlockHeaderImpl.h",
"max_line_length": 100,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "737e08752e8904c7c24e3737f8f46bf5327ef792",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "xueying4402/FISCO-BCOS",
"max_stars_repo_path": "bcos-tars-protocol/protocol/BlockHeaderImpl.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1543,
"size": 6128
} |
/*
* 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 typeof_027722a0_eb51_4e04_8f59_b9299ee17be6_h
#define typeof_027722a0_eb51_4e04_8f59_b9299ee17be6_h
#include <gslib/type.h>
__gslib_begin__
#define gs_register_typeof_bs(t) \
template<> \
struct typeof<t*> { typedef t type; }; \
template<> \
struct typeof<const t*> { typedef t type; };
#define gs_register_typeof(q, t) \
q t; /* for announcement. */ \
gs_register_typeof_bs(t);
#define gs_register_typeof_ns(ns, q, t) \
namespace ns { \
q t; /* for announcement. */ \
}; \
gs_register_typeof_bs(ns::t);
/* all pointer typeof operator should be registered here. */
gs_register_typeof_bs(int8);
gs_register_typeof_bs(int16);
gs_register_typeof_bs(int);
gs_register_typeof_bs(int64);
gs_register_typeof_bs(wchar);
gs_register_typeof_bs(real32);
gs_register_typeof_bs(real);
gs_register_typeof_bs(byte);
gs_register_typeof_bs(word);
gs_register_typeof_bs(dword);
gs_register_typeof_bs(qword);
gs_register_typeof_ns(rathen, struct, ps_data);
gs_register_typeof_ns(rathen, struct, ps_ref);
gs_register_typeof_ns(rathen, struct, ps_stdata);
gs_register_typeof_ns(rathen, struct, ps_stref);
gs_register_typeof_ns(ariel, class, button);
/* more to come ... */
__gslib_end__
#endif
| {
"alphanum_fraction": 0.7356412274,
"avg_line_length": 34.8219178082,
"ext": "h",
"hexsha": "02894a0454a9a38ed9e1206b803ae81167f2c513",
"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/typeof.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/typeof.h",
"max_line_length": 82,
"max_stars_count": 9,
"max_stars_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "lymastee/gslib",
"max_stars_repo_path": "include/gslib/typeof.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": 606,
"size": 2542
} |
// Copyright 2011-2021 GameParadiso, Inc. All Rights Reserved.
#pragma once
#include <conio.h>
#include <map>
#include <unordered_set>
#include <unordered_map>
#include <ranges>
#include <iostream>
#include <sstream>
#include <chrono>
#include <random>
#include <thread>
#define FMT_HEADER_ONLY
#include <fmt/format.h>
#define GLM_FORCE_MESSAGES
#define GLM_FORCE_INLINE
#define GLM_FORCE_EXPLICIT_CTOR
#define GLM_FORCE_ALIGNED_GENTYPES
#define GLM_FORCE_INTRINSICS
#include <glm/glm.hpp>
#include <glm/vec3.hpp>
#include <glm/vec4.hpp>
#include <glm/mat4x4.hpp>
#include <glm/gtc/quaternion.hpp>
#include <glm/gtx/quaternion.hpp>
#include <glm/ext/matrix_transform.hpp>
#include <glm/ext/matrix_clip_space.hpp>
#include <glm/gtx/matrix_decompose.hpp>
#include <glm/ext/scalar_constants.hpp>
#include <glm/gtc/type_aligned.hpp>
#include <gsl/gsl>
#include "Mathmatics.h"
#include "Util.h"
constexpr uint32_t NumEntities = 50000;
| {
"alphanum_fraction": 0.776119403,
"avg_line_length": 21.8139534884,
"ext": "h",
"hexsha": "64127b75d258137235153a0427fa4f26ade96614",
"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": "3f5be50c65959a44c95f2955e1afb6ccd50b7ff2",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "noirhero/MemoryChunkProfile",
"max_forks_repo_path": "pch.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "3f5be50c65959a44c95f2955e1afb6ccd50b7ff2",
"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": "noirhero/MemoryChunkProfile",
"max_issues_repo_path": "pch.h",
"max_line_length": 62,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "3f5be50c65959a44c95f2955e1afb6ccd50b7ff2",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "noirhero/MemoryChunkProfile",
"max_stars_repo_path": "pch.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 245,
"size": 938
} |
/* spoper.c
*
* Copyright (C) 2012 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_matrix.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_spmatrix.h>
#include <gsl/gsl_spblas.h>
int
gsl_spmatrix_scale(gsl_spmatrix *m, const double x)
{
size_t i;
for (i = 0; i < m->nz; ++i)
m->data[i] *= x;
return GSL_SUCCESS;
} /* gsl_spmatrix_scale() */
int
gsl_spmatrix_minmax(const gsl_spmatrix *m, double *min_out, double *max_out)
{
double min, max;
size_t n;
if (m->nz == 0)
{
GSL_ERROR("matrix is empty", GSL_EINVAL);
}
min = m->data[0];
max = m->data[0];
for (n = 1; n < m->nz; ++n)
{
double x = m->data[n];
if (x < min)
min = x;
if (x > max)
max = x;
}
*min_out = min;
*max_out = max;
return GSL_SUCCESS;
} /* gsl_spmatrix_minmax() */
/*
gsl_spmatrix_add()
Add two sparse matrices
Inputs: c - (output) a + b
a - (input) sparse matrix
b - (input) sparse matrix
Return: success or error
*/
int
gsl_spmatrix_add(gsl_spmatrix *c, const gsl_spmatrix *a,
const gsl_spmatrix *b)
{
const size_t M = a->size1;
const size_t N = a->size2;
if (b->size1 != M || b->size2 != N || c->size1 != M || c->size2 != N)
{
GSL_ERROR("matrices must have same dimensions", GSL_EBADLEN);
}
else if (a->sptype != b->sptype || a->sptype != c->sptype)
{
GSL_ERROR("matrices must have same sparse storage format",
GSL_EINVAL);
}
else if (GSL_SPMATRIX_ISTRIPLET(a))
{
GSL_ERROR("triplet format not yet supported", GSL_EINVAL);
}
else
{
int status = GSL_SUCCESS;
size_t *w = (size_t *) a->work;
double *x = (double *) b->work;
size_t *Cp, *Ci;
double *Cd;
size_t j, p;
size_t nz = 0; /* number of non-zeros in c */
size_t inner_size, outer_size;
if (GSL_SPMATRIX_ISCCS(a))
{
inner_size = M;
outer_size = N;
}
else if (GSL_SPMATRIX_ISCRS(a))
{
inner_size = N;
outer_size = M;
}
else
{
GSL_ERROR("unknown sparse matrix type", GSL_EINVAL);
}
if (c->nzmax < a->nz + b->nz)
{
status = gsl_spmatrix_realloc(a->nz + b->nz, c);
if (status)
return status;
}
/* initialize w = 0 */
for (j = 0; j < inner_size; ++j)
w[j] = 0;
Ci = c->i;
Cp = c->p;
Cd = c->data;
for (j = 0; j < outer_size; ++j)
{
Cp[j] = nz;
/* CCS: x += A(:,j); CRS: x += A(j,:) */
nz = gsl_spblas_scatter(a, j, 1.0, w, x, j + 1, c, nz);
/* CCS: x += B(:,j); CRS: x += B(j,:) */
nz = gsl_spblas_scatter(b, j, 1.0, w, x, j + 1, c, nz);
for (p = Cp[j]; p < nz; ++p)
Cd[p] = x[Ci[p]];
}
/* finalize last column of c */
Cp[j] = nz;
c->nz = nz;
return status;
}
} /* gsl_spmatrix_add() */
/*
gsl_spmatrix_d2sp()
Convert a dense gsl_matrix to sparse (triplet) format
Inputs: S - (output) sparse matrix in triplet format
A - (input) dense matrix to convert
*/
int
gsl_spmatrix_d2sp(gsl_spmatrix *S, const gsl_matrix *A)
{
int s = GSL_SUCCESS;
size_t i, j;
gsl_spmatrix_set_zero(S);
S->size1 = A->size1;
S->size2 = A->size2;
for (i = 0; i < A->size1; ++i)
{
for (j = 0; j < A->size2; ++j)
{
double x = gsl_matrix_get(A, i, j);
if (x != 0.0)
gsl_spmatrix_set(S, i, j, x);
}
}
return s;
} /* gsl_spmatrix_d2sp() */
/*
gsl_spmatrix_sp2d()
Convert a sparse matrix to dense format
*/
int
gsl_spmatrix_sp2d(gsl_matrix *A, const gsl_spmatrix *S)
{
if (A->size1 != S->size1 || A->size2 != S->size2)
{
GSL_ERROR("matrix sizes do not match", GSL_EBADLEN);
}
else
{
gsl_matrix_set_zero(A);
if (GSL_SPMATRIX_ISTRIPLET(S))
{
size_t n;
for (n = 0; n < S->nz; ++n)
{
size_t i = S->i[n];
size_t j = S->p[n];
double x = S->data[n];
gsl_matrix_set(A, i, j, x);
}
}
else
{
GSL_ERROR("non-triplet formats not yet supported", GSL_EINVAL);
}
return GSL_SUCCESS;
}
} /* gsl_spmatrix_sp2d() */
| {
"alphanum_fraction": 0.5442768755,
"avg_line_length": 22.0085106383,
"ext": "c",
"hexsha": "07268c18b5547dc3c8fb8e964010f63d1117f2e6",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "Brian-ning/HMNE",
"max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/spmatrix/spoper.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "Brian-ning/HMNE",
"max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/spmatrix/spoper.c",
"max_line_length": 81,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "857b6ee8866a2950aa5721d575d2d7d0797c4302",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "peterahrens/FillEstimationIPDPS2017",
"max_stars_repo_path": "gsl-2.4/spmatrix/spoper.c",
"max_stars_repo_stars_event_max_datetime": "2021-01-13T05:01:59.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-01-13T05:01:59.000Z",
"num_tokens": 1610,
"size": 5172
} |
/* DomSelfAdaptFWD.c
Forward-in-time simulation of an adaptive alleles with dominance and selfing, with linked neutral fragment.
This is the BATCH version - to be used on cluster machine to produce many simulation replicates at once.
Reps program: Reads in pre-calculated tables and introduces neutral mutations based on them. See README for more information.
Simulation uses routines found with the GNU Scientific Library (GSL)
(http://www.gnu.org/software/gsl/)
Since GSL is distributed under the GNU General Public License
(http://www.gnu.org/copyleft/gpl.html), you must download it
separately from this file.
*/
/* Preprocessor statements */
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <math.h>
#include <stddef.h>
#include <string.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
#include <sys/stat.h>
#include <sys/types.h>
/* Function prototypes */
void Wait();
void fitness(unsigned int N, double h, double s, unsigned int *inpop, double *outfit, double *outcf, double *fitsum);
double sumT_UI(unsigned int *Tin, unsigned int nrow);
unsigned int parchoose(unsigned int N, double *culfit, double *fitsum, const gsl_rng *r);
unsigned int bitswitch(unsigned int x);
void rec_sort(double *index, unsigned int nrow);
void generation(unsigned int N, double self, double R, unsigned int *nums, unsigned int *selin, unsigned int *selout, unsigned int **neutin, unsigned int **neutout, double *culfit, double *fitsum, unsigned int npoly, double *polypos, const gsl_rng *r);
void addpoly(unsigned int N, unsigned int **neutin, double *polyloc, unsigned int *npoly, double theta, unsigned int maxsize, const gsl_rng *r);
void reassign(unsigned int **neutin, unsigned int **neutout, unsigned int *selin, unsigned int *selout, unsigned int npoly, unsigned int N);
void reassign2(unsigned int **neutin, unsigned int **neutout, double *posin, double *posout, unsigned int npoly, unsigned int N);
void polyprint(unsigned int **neutin, double *posin, unsigned int npoly, unsigned int N);
void ptrim(unsigned int size, unsigned int **neutin, unsigned int **neutout, double *posin, double *posout, unsigned int npoly, unsigned int *npolyT, double *avpi);
void mutsamp(unsigned int N, unsigned int samps, unsigned int *selin, double *polypos, unsigned int **neutin, unsigned int *nums2, unsigned int npoly, unsigned int ei, unsigned int rep, const gsl_rng *r);
void popread(unsigned int **neutin, double *posin, unsigned int npoly, unsigned int N, unsigned int ei, unsigned int suffix);
void Wait(){
printf("Press Enter to Continue");
while( getchar() != '\n' );
printf("\n");
}
/* Fitness calculation routine */
void fitness(unsigned int N, double h, double s, unsigned int *inpop, double *outfit, double *outcf, double *fitsum){
unsigned int i; /* Pop counter */
unsigned int ac = 0; /* Allele copies in indv */
/* Calculating new fitnesses */
*fitsum = 0;
for(i = 0; i < N; i++){
ac = 0;
ac = (*(inpop + 2*i)) + (*(inpop + 2*i + 1));
if(ac == 0){
*(outfit + i) = 1;
}else if(ac == 1){
*(outfit + i) = 1 + h*s;
}else if(ac == 2){
*(outfit + i) = 1 + s;
}
*fitsum += *(outfit + i);
*(outcf + i) = *fitsum;
}
} /* End of fitness routine */
/* Summing entire table (unsigned int) */
double sumT_UI(unsigned int *Tin, unsigned int nrow){
unsigned int i;
double res = 0;
for(i = 0; i < nrow; i++){
res += (*(Tin + i));
}
return res;
}
/* Parent choosing */
unsigned int parchoose(unsigned int N, double *culfit, double *fitsum, const gsl_rng *r){
double a; /* Random number */
unsigned int done = 0; /* Signal to determine whether selection complete */
unsigned int cases = 0; /* Determines whether one should add up or decrease */
unsigned int choose1 = 0; /* Chromosome to be selected */
unsigned int firstgo = 0; /* First try at choosing progeny */
done = 0;
cases = 0;
choose1 = 0;
a = gsl_ran_flat(r,0.0,1.0);
firstgo = (int)N*a;
/* Choosing case */
if (((*(culfit + firstgo)/(*(fitsum))) >= a) && firstgo == 0){
cases = 3;
} else if (((*(culfit + firstgo)/(*(fitsum))) >= a) && firstgo != 0){
cases = 2;
} else {
cases = 1;
}
switch(cases)
{
case 1:
while(done != 1){
firstgo++;
if((*(culfit + firstgo)/(*(fitsum))) >= a){
choose1 = firstgo;
done = 1;
}
}
break;
case 2:
while(done != 1){
firstgo--;
if((*(culfit + firstgo)/(*(fitsum))) < a || firstgo == 0){
choose1 = (firstgo + 1);
done = 1;
}
}
break;
case 3:
choose1 = 0;
break;
}
return choose1;
}
/* Bit-switching routine */
unsigned int bitswitch(unsigned int x){
unsigned int ret;
switch(x)
{
case 0:
ret = 1;
break;
case 1:
ret = 0;
break;
default: /* If none of these cases chosen, exit with error message */
fprintf(stderr,"Error in bitswitch: input is not 0 or 1.\n");
exit(1);
break;
}
return ret;
}
/* Sorting rec events after choosing them */
void rec_sort(double *index, unsigned int nrow){
unsigned int j, i; /* Sorting indices */
double temp0; /* For swapping */
for(j = 1; j < nrow; j++){
i = j;
while( (i > 0) && ( *(index + (i - 1) ) > *(index + i) )){
/* Swapping entries */
temp0 = *(index + (i - 1));
*(index + (i - 1)) = *(index + (i));
*(index + (i)) = temp0;
i--;
}
}
}
/* Reproduction routine */
void generation(unsigned int N, double self, double R, unsigned int *nums, unsigned int *selin, unsigned int *selout, unsigned int **neutin, unsigned int **neutout, double *culfit, double *fitsum, unsigned int npoly, double *polypos, const gsl_rng *r){
unsigned int i, j, k; /* Pop counter, neutral marker counter, rec event counter */
unsigned int isself = 0; /* Is this a selfing reproduction? */
unsigned int choose1 = 0; /* Chromosome to be selected */
unsigned int choose2 = 0; /* Chromosome to be selected (2nd with outcrossing) */
unsigned int wc1 = 0; /* Which chrom (parent 1) */
unsigned int wc2 = 0; /* Which chrom (parent 2) */
unsigned int index1 = 0; /* Index of chosen sample 1 */
unsigned int index2 = 0; /* Index of chosen sample 2 */
unsigned int nself = 0; /* Number of selfing events */
unsigned int selfix = 0; /* Selfing index */
unsigned int recix1 = 0; /* Rec index chr 1 */
unsigned int recix2 = 0; /* Rec index chr 2 */
unsigned int nrec1 = 0; /* Number rec events chr 1 */
unsigned int nrec2 = 0; /* Number rec events chr 2 */
/* First deciding number of selfing events; creating vector of events + choosing */
nself = gsl_ran_binomial(r, self, N);
unsigned int *selfev = calloc(nself,sizeof(unsigned int));
gsl_ran_choose(r, selfev, nself, nums, N, sizeof(unsigned int));
for(i = 0; i < N; i++){ /* Regenerating population */
/* Choosing first parent, and relevant chromosomes */
choose1 = parchoose(N, culfit, fitsum, r);
wc1 = gsl_ran_bernoulli(r,0.5);
wc2 = gsl_ran_bernoulli(r,0.5);
index1 = 2*choose1 + wc1;
/* Copying over selected sites, first checking if selfing occurs */
isself = 0;
if(nself != 0){
if(*(selfev + selfix) == i){
isself = 1;
selfix++;
}
}
if(isself == 1){
index2 = 2*choose1 + wc2;
}else if(isself == 0){
choose2 = parchoose(N, culfit, fitsum, r);
index2 = 2*choose2 + wc2;
}
(*(selout + 2*i)) = (*(selin + index1));
(*(selout + 2*i + 1)) = (*(selin + index2));
/* Now copying over neutral fragment, accounting for recombination */
if(R != 0){
/* Choosing number of recombination events on arms 1, 2 */
recix1 = 0;
recix2 = 0;
nrec1 = gsl_ran_poisson(r,R);
nrec2 = gsl_ran_poisson(r,R);
double *recev1 = calloc(nrec1 + 1,sizeof(double));
double *recev2 = calloc(nrec2 + 1,sizeof(double));
for(k = 0; k < nrec1; k++){
*(recev1 + k) = gsl_ran_flat(r,0,1);
}
for(k = 0; k < nrec2; k++){
*(recev2 + k) = gsl_ran_flat(r,0,1);
}
*(recev1 + nrec1) = 1.01;
*(recev2 + nrec2) = 1.01;
rec_sort(recev1,nrec1 + 1);
rec_sort(recev2,nrec2 + 1);
for(j = 0; j < npoly; j++){
if( (*(polypos + j)) >= *(recev1 + recix1)){
wc1 = bitswitch(wc1);
index1 = 2*choose1 + wc1;
recix1++;
}
if( (*(polypos + j)) >= *(recev2 + recix2)){
wc2 = bitswitch(wc2);
if(isself == 1){
index2 = 2*choose1 + wc2;
}else if(isself == 0){
index2 = 2*choose2 + wc2;
}
recix2++;
}
*((*(neutout + 2*i)) + j) = *((*(neutin + index1)) + j);
*((*(neutout + 2*i + 1)) + j) = *((*(neutin + index2)) + j);
}
free(recev1);
free(recev2);
}else if (R == 0){
for(j = 0; j < npoly; j++){
*((*(neutout + 2*i)) + j) = *((*(neutin + index1)) + j);
*((*(neutout + 2*i + 1)) + j) = *((*(neutin + index2)) + j);
}
}
}
free(selfev);
} /* End of reproduction routine */
/* Adding neutral polymorphism routine */
void addpoly(unsigned int N, unsigned int **neutin, double *polyloc, unsigned int *npoly, double theta, unsigned int maxsize, const gsl_rng *r){
unsigned int i, j;
int k;
unsigned int newpoly = 0; /* Number of new polymorphisms added */
unsigned int pchr = 0; /* Chromosome of appearance */
unsigned int pfound = 0; /* Flag to denote if right index found */
double ploc = 0; /* Location of polymorphism */
/* FILE *ofp_poly; Pointer for polymorphisms output */
newpoly = gsl_ran_poisson(r,(0.5*theta));
/* printf("Add %d new polymorphisms\n",newpoly);*/
for(j = 0; j < newpoly; j++){
ploc = gsl_ran_flat(r,0.0,1.0);
/* printf("ploc is %lf\n",ploc); */
pchr = gsl_rng_uniform_int(r,2*N);
/* printf("pchr is %d\n",pchr); */
/* Inserting new polymorphism */
if(*(npoly) == 0){
/* printf("zero entry here\n"); */
*(polyloc + 0) = ploc;
for(i = 0; i < 2*N; i++){
*((*(neutin + i)) + 0) = 0;
}
*((*(neutin + pchr)) + 0) = 1;
}else if(*(npoly) > 0){
/* printf("non-zero entry here\n"); */
pfound = 0;
for(k = (*(npoly) - 1); k >= 0; k--){
/* printf("k is %d\n",k);*/
if(*(polyloc + k) > ploc){
/* printf("is here 1\n");*/
*(polyloc + k + 1) = *(polyloc + k);
for(i = 0; i < 2*N; i++){
*((*(neutin + i)) + k + 1) = *((*(neutin + i)) + k);
}
}else if(*(polyloc + k) <= ploc){
/* printf("is here 2\n"); */
pfound = 1;
*(polyloc + k + 1) = ploc;
for(i = 0; i < 2*N; i++){
*((*(neutin + i)) + k + 1) = 0;
}
*((*(neutin + pchr)) + k + 1) = 1;
break;
}
}
if(pfound == 0){ /* In this case polymorphism is inserted at the start */
*(polyloc + 0) = ploc;
for(i = 0; i < 2*N; i++){
*((*(neutin + i)) + 0) = 0;
}
*((*(neutin + pchr)) + 0) = 1;
}
}
*(npoly) += 1;
/* printf("n poly is %d\n",*(npoly)); */
if(*(npoly) == maxsize){
fprintf(stderr,"Too many neutral polymorphisms.\n");
exit(1);
}
}
}
/* Reassigning new population routine */
void reassign(unsigned int **neutin, unsigned int **neutout, unsigned int *selin, unsigned int *selout, unsigned int npoly, unsigned int N){
unsigned int i, j; /* pop counter, poly counter */
for(i = 0; i < 2*N; i++){
*(selout + i) = *(selin + i);
for(j = 0; j < npoly; j++){
*((*(neutout + i)) + j) = *((*(neutin + i)) + j);
}
}
} /* End of reassignment routine */
/* Reassigning new population routine (after trimming) */
void reassign2(unsigned int **neutin, unsigned int **neutout, double *posin, double *posout, unsigned int npoly, unsigned int N){
unsigned int i, j; /* pop counter, poly counter */
for(i = 0; i < 2*N; i++){
for(j = 0; j < npoly; j++){
*((*(neutout + i)) + j) = *((*(neutin + i)) + j);
if(i == 0){
*(posout + j) = *(posin + j);
}
}
}
} /* End of reassignment routine */
/* Printing polymorphism routines */
void polyprint(unsigned int **neutin, double *posin, unsigned int npoly, unsigned int N){
unsigned int i, j; /* pop counter, poly counter */
for(j = 0; j < npoly; j++){
printf("%lf ",*(posin + j));
for(i = 0; i < 2*N; i++){
printf("%d ",*((*(neutin + i)) + j));
}
printf("\n");
}
Wait();
} /* End of reassignment routine */
/* Cutting out non-polymorphic sites */
void ptrim(unsigned int size, unsigned int **neutin, unsigned int **neutout, double *posin, double *posout, unsigned int npoly, unsigned int *npolyT, double *avpi){
unsigned int i, j;
unsigned int newp = 0; /* New number of polymorphisms */
unsigned int count = 0; /* Polymorphism count */
double cumpi = 0; /* Cumulative pi (diversity) */
/* printf("Trimming routine activated\n"); */
for(j = 0; j < npoly; j++){
count = 0;
*(posout + newp) = *(posin + j);
for(i = 0; i < size; i++){
*((*(neutout + i)) + newp) = *((*(neutin + i)) + j);
count += *((*(neutin + i)) + j);
}
/* printf("For poly %d, count is %d\n",j,count);*/
if((count > 0) && (count < size)){
/* printf("Keeping poly %d\n",j); */
newp++;
cumpi += ((count*(size-count))/(1.0*size*size));
/* printf("Count is %d, freq is %lf, cumulative value is %lf\n",count,count/(1.0*size),cumpi); */
}
}
*npolyT = newp;
*avpi = (cumpi/(1.0*newp));
}
/* Producing mutational samples */
void mutsamp(unsigned int N, unsigned int samps, unsigned int *selin, double *polypos, unsigned int **neutin, unsigned int *nums2, unsigned int npoly, unsigned int ei, unsigned int rep, const gsl_rng *r){
unsigned int a, j, x;
unsigned int currsamp;
unsigned int npolyT;
double avpi;
char Mout[32]; /* String to hold filename in (Mutations) */
FILE *ofp_mut = NULL; /* Pointer for data output */
for(x = 0; x < rep; x++){
double *polyposF = calloc(npoly,sizeof(double)); /* Position of neutral mutations (final for polymorphism sampling) */
unsigned int *selsamp = calloc(samps,sizeof(unsigned int *)); /* State of selected locus after sim stops */
unsigned int **nsamp = calloc(samps,sizeof(unsigned int *)); /* Table of neutral markers per individual (final for sampling) */
unsigned int **nsampT = calloc(samps,sizeof(unsigned int *)); /* Table of neutral markers per individual (final for sampling) AFTER TRIMMING */
for(a = 0; a < samps; a++){
nsamp[a] = calloc(npoly,sizeof(unsigned int));
nsampT[a] = calloc(npoly,sizeof(unsigned int));
}
npolyT = npoly;
/* Choosing which haplotypes to sample */
unsigned int *thesamp = calloc(samps,sizeof(unsigned int));
gsl_ran_choose(r, thesamp, samps, nums2, 2*N, sizeof(unsigned int));
for(a = 0; a < samps; a++){
currsamp = *(thesamp + a);
*(selsamp + a) = *(selin + currsamp);
for(j = 0; j < npoly; j++){
*((*(nsamp + a)) + j) = *((*(neutin + currsamp)) + j);
}
}
/* Check, then include code to ONLY print out polymorphic sites in table? */
ptrim(samps, nsamp, nsampT, polypos, polyposF, npoly, &npolyT, &avpi);
/* Printing out sample table */
sprintf(Mout,"Mutations/Muts_%d.dat",ei*rep + x);
ofp_mut = fopen(Mout,"w");
/* State of selected site */
fprintf(ofp_mut,"0 ");
for(a = 0; a < samps; a++){
fprintf(ofp_mut,"%d ",*(selsamp + a));
}
fprintf(ofp_mut,"\n");
for(j = 0; j < npolyT; j++){
fprintf(ofp_mut,"%lf ",*(polyposF + j));
for(a = 0; a < samps; a++){
fprintf(ofp_mut,"%d ",*((*(nsampT + a)) + j));
}
fprintf(ofp_mut,"\n");
}
fclose(ofp_mut);
for(a = 0; a < samps; a++){
free(nsampT[a]);
free(nsamp[a]);
}
free(nsampT);
free(nsamp);
free(thesamp);
free(selsamp);
free(polyposF);
}
}
/* Reading population state from file */
void popread(unsigned int **neutin, double *posin, unsigned int npoly, unsigned int N, unsigned int ei, unsigned int suffix){
unsigned int i, j; /* pop counter, poly counter */
char Pin[32]; /* String to hold filename in (Mutations) */
FILE *ifp_poly = NULL; /* Pointer for data output */
/* Printing out polymorphism table */
sprintf(Pin,"Pop_%d.dat",ei + suffix);
ifp_poly = fopen(Pin,"r");
for(j = 0; j < npoly; j++){
/* Is this the right way of reading in the first column of file? */
for(i = 0; i < (2*N + 1); i++){
if(i == 0){
fscanf(ifp_poly,"%lf",&(posin[j]));
}else if(i > 0){
fscanf(ifp_poly,"%d",&(neutin[(i-1)][j]));
}
}
fprintf(ifp_poly,"\n");
}
fclose(ifp_poly);
} /* End of population reading routine */
/* Main program */
int main(int argc, char *argv[]){
/* Declare variables here */
unsigned int a, i, x; /* Counters */
unsigned int N = 0; /* Population Size */
unsigned int initp = 0; /* Initial location of mutant (individual) */
unsigned int done = 0; /* Is simulation done or not? */
unsigned int dcopies = 0; /* Number of copies of derived allele */
unsigned int afix = 0; /* Has allele fixed? */
unsigned int npoly = 0; /* Number of neutral alleles */
unsigned int npolyB = 0; /* BASELINE number of neutral alleles at simulation initiation */
unsigned int npolyT = 0; /* Number of neutral alleles (after cutting out fixed sites) */
unsigned int nowsel = 0; /* If derived allele selected for? */
unsigned int samps = 0; /* Number of samples to take */
unsigned int suffix = 0; /* Number of times to subsample from population */
unsigned int base = 0; /* Number of baseline forward-in-time simulations */
unsigned int rps = 0; /* Samples taken per baseline simulation */
unsigned int INITTS = 0; /* Initial size of mutation array */
/* unsigned int n = 0; sprintf counter */
double s = 0; /* Strength of selection */
double h = 0; /* Dominance level */
double self = 0; /* Selfing rate */
double Rin = 0; /* Recombination rate (input) */
double R = 0; /* Recombination rate (at a time) */
double x0 = 0; /* Initial allele frequency */
double xfix = 0; /* Final allele frequency (i.e. stop when allele reaches this frequency) */
double theta = 0; /* Rate of neutral mutation */
double fitsum = 0; /* Summed Fitness */
double scurr = 0; /* Current fitness of mutant (to account for initial neutrality) */
double avpi = 0;
char Pout[32]; /* String to hold filename in (Mutations) */
char Sout[32]; /* String to hold filename in (Seed) */
FILE *ofp_sd; /* Pointer for seed output */
FILE *ofp_poly; /* Pointer for polymorphisms output */
/* GSL random number definitions */
const gsl_rng_type * T;
gsl_rng * r;
/* Reading in data from command line */
if(argc != 14){
fprintf(stderr,"Not enough inputs (need: N s h self R x0 xfix theta basereps reps-per-sim samples suffix npoly).\n");
exit(1);
}
N = atoi(argv[1]);
if(N <= 0){
fprintf(stderr,"Total Population size N is zero or negative, not allowed.\n");
exit(1);
}
s = strtod(argv[2],NULL);
if(s < 0){
fprintf(stderr,"Allele strength s is negative, not allowed.\n");
exit(1);
}
h = strtod(argv[3],NULL);
if(h < 0 || h > 1){
fprintf(stderr,"Dominance value must lie between 0 and 1.\n");
exit(1);
}
self = strtod(argv[4],NULL);
if(self < 0 || self > 1){
fprintf(stderr,"Selfing rate must lie between 0 and 1 (inclusive).\n");
exit(1);
}
Rin = strtod(argv[5],NULL);
if(Rin < 0){
fprintf(stderr,"Recombination rate must be positive or zero.\n");
exit(1);
}
Rin /= 2.0*N;
x0 = strtod(argv[6],NULL);
if(x0 < (1.0/(2.0*N)) || x0 > 1.0-(1.0/(2.0*N)) ){
fprintf(stderr,"Initial mutant frequency must lie between 1/2N and 1-1/2N.\n");
exit(1);
}
xfix = strtod(argv[7],NULL);
if(xfix < 0 || xfix > 1.0 ){
fprintf(stderr,"Final mutant frequency must lie between 0 and 1.\n");
exit(1);
}
if(xfix <= x0){
fprintf(stderr,"Final mutant frequency must be greater than initial mutant frequency.\n");
exit(1);
}
theta = strtod(argv[8],NULL);
if(theta <= 0){
fprintf(stderr,"Mutation rate must be a positive value.\n");
exit(1);
}
base = atoi(argv[9]);
if(base <= 0){
fprintf(stderr,"Number of baseline simulations must be greater than zero.\n");
exit(1);
}
rps = atoi(argv[10]);
if(rps <= 0){
fprintf(stderr,"Number of reps per simulation must be > 0.\n");
exit(1);
}
samps = atoi(argv[11]);
if(samps <= 0){
fprintf(stderr,"Number of samples taken must be > 0.\n");
exit(1);
}
suffix = atoi(argv[12]);
if(argv[12] < 0){
fprintf(stderr,"File index must be greater than or equal to zero.\n");
exit(1);
}
npolyB = atoi(argv[13]);
INITTS = 2*npolyB;
/* create a generator chosen by the
environment variable GSL_RNG_TYPE */
mkdir("SeedsRep/", 0777);
gsl_rng_env_setup();
if (!getenv("GSL_RNG_SEED")) gsl_rng_default_seed = time(0);
T = gsl_rng_default;
r = gsl_rng_alloc(T);
sprintf(Sout,"SeedsRep/Seed_%d.dat",suffix);
ofp_sd = fopen(Sout,"w");
fprintf(ofp_sd,"%lu\n",gsl_rng_default_seed);
fclose(ofp_sd);
mkdir("Polymorphisms/", 0777);
mkdir("Mutations/", 0777);
/* Vector of 0 to (N-1) for sampling random numbers */
unsigned int *nums = calloc(N,sizeof(unsigned int));
unsigned int *nums2 = calloc(2*N,sizeof(unsigned int));
for(a = 0; a < 2*N; a++){
*(nums2 + a) = a;
if(a < N){
*(nums + a) = a;
}
}
/* Executing simulation */
for(i = 0; i < base; i++){
/* printf("Starting run %d\n",i);*/
afix = 0;
R = Rin;
while(afix != 1){
/* Setting up selection, neutral tables per individual */
double *fit = calloc(N,sizeof(double)); /* Fitness of each individual */
double *cumfit = calloc(N,sizeof(double)); /* Cumulative fitness of each individual */
double *polypos = calloc(INITTS,sizeof(double)); /* Position of neutral mutations */
double *polyposF = calloc(INITTS,sizeof(double)); /* Position of neutral mutations (final for polymorphism sampling) */
unsigned int *selindvP = calloc(2*N,sizeof(unsigned int)); /* Table of derived allele states per individual (parents) */
unsigned int *selindvO = calloc(2*N,sizeof(unsigned int)); /* Table of derived allele states per individual (offspring) */
unsigned int **neutindvP = calloc(2*N,sizeof(unsigned int *)); /* Table of neutral markers per individual (parents) */
unsigned int **neutindvO = calloc(2*N,sizeof(unsigned int *)); /* Table of neutral markers per individual (offspring) */
unsigned int **neutindvF = calloc(2*N,sizeof(unsigned int *)); /* Table of neutral markers per individual (final for sampling) */
for(a = 0; a < 2*N; a++){
neutindvP[a] = calloc(INITTS,sizeof(unsigned int));
neutindvO[a] = calloc(INITTS,sizeof(unsigned int));
neutindvF[a] = calloc(INITTS,sizeof(unsigned int));
}
/* Reassigning ancestral polymorphism state */
npoly = npolyB;
popread(neutindvP, polypos, npoly, N, i, suffix);
/*
polyprint(neutindvP, polypos, npoly, N);
exit(1);
*/
/* Assigning initial mutant, calculating fitness */
initp = gsl_rng_uniform_int(r,2*N);
*(selindvP + initp) = 1;
if(x0 == 1.0/(2.0*N)){
scurr = s;
nowsel = 1;
}else if(x0 > 1.0/(2.0*N)){
scurr = 0;
nowsel = 0;
}
/* printf("scurr is %lf\n",scurr); */
fitness(N, h, scurr, selindvP, fit, cumfit, &fitsum);
done = 0;
while(done != 1){
/* Generating new population */
generation(N,self,R,nums,selindvP,selindvO,neutindvP,neutindvO,cumfit,&fitsum,npoly,polypos,r);
/* Neutral Mutation phase */
addpoly(N, neutindvO, polypos, &npoly, theta, INITTS, r);
/* Reassigning matrices */
reassign(neutindvO, neutindvP, selindvO, selindvP, npoly, N);
/* Garbage collection of non-polymorphic sites */
ptrim(2*N, neutindvP, neutindvF, polypos, polyposF, npoly, &npolyT,&avpi);
npoly = npolyT;
reassign2(neutindvF, neutindvP, polyposF, polypos, npoly, N);
/* Checking derived allele copies and whether it has fixed or lost */
dcopies = sumT_UI(selindvP, 2.0*N);
/*
printf("Dcopies are %d\n",dcopies);
printf("copies are %d, npoly are %d\n",dcopies,npoly);
*/
if(dcopies == 0){
done = 1;
/* printf("Selected allele lost\n");*/
}
if(dcopies >= (int)(2.0*N*xfix)){
done = 1;
afix = 1;
}
/* Deciding if derived allele becomes selected for, then updating fitness */
if(((dcopies/(2.0*N)) >= x0) && nowsel == 0){
nowsel = 1;
scurr = s;
/* printf("scurr is %lf\n",scurr); */
}
fitness(N, h, scurr, selindvP, fit, cumfit, &fitsum);
}
/* Routine to print out polymorphisms if allele fixed */
if(afix == 1){
printf("Selected allele fixed\n");
/* First, remove non-polymorphic sites */
ptrim(2*N, neutindvP, neutindvF, polypos, polyposF, npoly, &npolyT,&avpi);
npoly = npolyT;
/* Printing out polymorphism table */
sprintf(Pout,"Polymorphisms/Poly_%d.dat",i + suffix);
ofp_poly = fopen(Pout,"w");
/* State of selected site */
fprintf(ofp_poly,"0 ");
for(x = 0; x < 2*N; x++){
fprintf(ofp_poly,"%d ",*(selindvP + x));
}
fprintf(ofp_poly,"\n");
/* State of neutral sites */
for(a = 0; a < npoly; a++){
fprintf(ofp_poly,"%lf ",*(polyposF + a));
for(x = 0; x < 2*N; x++){
fprintf(ofp_poly,"%d ",*((*(neutindvF + x)) + a));
}
fprintf(ofp_poly,"\n");
}
fclose(ofp_poly);
/* Then, sample from this table to produce pseudo-coalescent results */
mutsamp(N, samps, selindvP, polyposF, neutindvF, nums2, npoly, i + suffix, rps, r);
}
/* End of run; freeing memory */
for(a = 0; a < 2*N; a++){
free(neutindvF[a]);
free(neutindvO[a]);
free(neutindvP[a]);
}
free(neutindvF);
free(neutindvO);
free(neutindvP);
free(selindvO);
free(selindvP);
free(polyposF);
free(polypos);
free(cumfit);
free(fit);
}
}
free(nums2);
free(nums);
gsl_rng_free(r);
return 0;
} /* End of main program */
/* End of File */ | {
"alphanum_fraction": 0.6072623959,
"avg_line_length": 31.6818742293,
"ext": "c",
"hexsha": "f438adb58c2744d86162cefb023e0875a94c6941",
"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": "73cde4d7936bb6645397f9931dade99a818e4c49",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "MattHartfield/DomSelfAdapt",
"max_forks_repo_path": "DomSelfAdaptFWD_RepsRec.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "73cde4d7936bb6645397f9931dade99a818e4c49",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "MattHartfield/DomSelfAdapt",
"max_issues_repo_path": "DomSelfAdaptFWD_RepsRec.c",
"max_line_length": 252,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "73cde4d7936bb6645397f9931dade99a818e4c49",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "MattHartfield/DomSelfAdapt",
"max_stars_repo_path": "DomSelfAdaptFWD_RepsRec.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 8387,
"size": 25694
} |
#include <stdio.h>
#include <gsl/gsl_rng.h>
gsl_rng * r; /* global generator */
int
main (void)
{
const gsl_rng_type * T;
gsl_rng_env_setup();
T = gsl_rng_default;
r = gsl_rng_alloc (T);
printf ("generator type: %s\n", gsl_rng_name (r));
printf ("seed = %lu\n", gsl_rng_default_seed);
printf ("first value = %lu\n", gsl_rng_get (r));
gsl_rng_free (r);
return 0;
}
| {
"alphanum_fraction": 0.6368286445,
"avg_line_length": 17,
"ext": "c",
"hexsha": "633026414999fe73b803c3fff7ab3b9b667cfe42",
"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/rng.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/rng.c",
"max_line_length": 52,
"max_stars_count": 64,
"max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "manggoguy/parsec-modified",
"max_stars_repo_path": "pkgs/libs/gsl/src/doc/examples/rng.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": 122,
"size": 391
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.