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 file_d50c3538_0c5e_49a3_bc6f_5d6bc6144520_h
#define file_d50c3538_0c5e_49a3_bc6f_5d6bc6144520_h
#include <stdio.h>
#include <gslib/config.h>
#include <gslib/string.h>
__gslib_begin__
typedef FILE* fileptr;
typedef fpos_t fpos;
class file
{
protected:
fileptr _file;
public:
file(): _file(0) {}
file(const gchar* name, const gchar* mode): _file(0) { open(name, mode); }
~file() { close(); }
#ifndef _UNICODE
void open(const gchar* name, const gchar* mode) { fopen_s(&_file, name, mode); }
void open_text(const gchar* name, bool readonly)
{
readonly ? fopen_s(&_file, name, _t("r")) :
fopen_s(&_file, name, _t("w"));
}
int read(gchar buf[], int len)
{
assert(buf && len);
return fgets(buf, len, _file) ? strlen(buf) : 0;
}
int write(const gchar str[])
{
assert(str);
return (int)fputs(str, _file);
}
#else
void open(const gchar* name, const gchar* mode) { _wfopen_s(&_file, name, mode); }
void open_text(const gchar* name, bool readonly)
{
readonly ? _wfopen_s(&_file, name, _t("r,ccs=UNICODE")) :
_wfopen_s(&_file, name, _t("w,ccs=UNICODE"));
}
int read(gchar buf[], int len)
{
assert(buf && len);
return fgetws(buf, len, _file) ? wcslen(buf) : 0;
}
int write(const gchar str[])
{
assert(str);
return fputws(str, _file);
}
#endif
bool is_valid() const { return _file != 0; }
void flush() { fflush(_file); }
void rewind() { ::rewind(_file); }
int current() const { return ftell(_file); }
int seek(int offset, int sps) { return fseek(_file, offset, sps); }
int size()
{
int old = current();
seek(0, SEEK_END);
int pos = current();
seek(old, SEEK_SET);
return pos;
}
void close()
{
if (_file) {
fclose(_file);
_file = 0;
}
}
int read_fillup(gchar buf[], int len)
{
assert(buf && len > 0);
int acc = 0;
while(acc < len) {
int r = read(buf + acc, len - acc);
if(r <= 0)
break;
acc += r;
}
return acc;
}
int read(string& buf, int start, int len)
{
int lento = start + len;
if(lento && buf.size() < lento)
buf.resize(lento);
return read(&buf.front() + start, len);
}
void read_all(string& buf)
{
int total = size() + 1; /* a weird problem about fgetws. */
if(buf.size() < total)
buf.resize(total);
for(int i = 0, j; j = read(buf, i, total-i); i += j);
/* right trim */
int p = buf.find_last_not_of(_t('\0'));
if(p != string::npos) {
p += 1;
if(p <= buf.length())
buf.resize(p);
}
}
int write(const string& buf) { return write(&buf.front()); }
int get(byte buf[], int len) { return (int)fread_s(buf, len, 1, len, _file); }
int get(word buf[], int len) { return (int)fread_s(buf, len * 2, 2, len, _file); }
int get(dword buf[], int len) { return (int)fread_s(buf, len * 4, 4, len, _file); }
int get(qword buf[], int len) { return (int)fread_s(buf, len * 8, 8, len, _file); }
int put(const byte buf[], int len) { return (int)fwrite(buf, 1, len, _file); }
int put(const word buf[], int len) { return (int)fwrite(buf, 2, len, _file); }
int put(const dword buf[], int len) { return (int)fwrite(buf, 4, len, _file); }
int put(const qword buf[], int len) { return (int)fwrite(buf, 8, len, _file); }
public:
template<int _szelem>
int put_elem(const void* buf, int len) {}
template<>
int put_elem<1>(const void* buf, int len) { return put((const byte*)buf, len); }
template<>
int put_elem<2>(const void* buf, int len) { return put((const word*)buf, len); }
template<>
int put_elem<4>(const void* buf, int len) { return put((const dword*)buf, len); }
template<>
int put_elem<8>(const void* buf, int len) { return put((const qword*)buf, len); }
};
__gslib_end__
#endif
| {
"alphanum_fraction": 0.578285098,
"avg_line_length": 32.9171597633,
"ext": "h",
"hexsha": "e5d5b7c42a2471a119f566b577133a4348dc4148",
"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/file.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/file.h",
"max_line_length": 88,
"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/file.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": 1514,
"size": 5563
} |
#include <assert.h>
#include <gsl/gsl_statistics_double.h>
#include <hdf5.h>
#include <hdf5_hl.h>
#include <qdm.h>
qdm_evaluation *
qdm_evaluation_new(const qdm_parameters *parameters)
{
qdm_evaluation *e = malloc(sizeof(qdm_evaluation));
e->parameters = *parameters;
e->rng = gsl_rng_alloc(gsl_rng_default);
e->years_min = 0;
e->years_max = 0;
e->lower_bound = 0;
e->upper_bound = 0;
e->waic = 0;
e->pwaic = 0;
e->dic = 0;
e->pd = 0;
e->t = NULL;
e->mcmc = NULL;
e->theta_bar = NULL;
e->theta_star_bar = NULL;
e->xi_cov = NULL;
e->theta_star_cov = NULL;
e->xi_low_bar = 0;
e->xi_high_bar = 0;
e->theta_acc = NULL;
e->xi_acc = NULL;
e->m_knots = NULL;
e->rng_seed = 0;
e->elapsed = 0;
return e;
}
void
qdm_evaluation_free(qdm_evaluation *e)
{
if (e == NULL) {
return;
}
e->rng_seed = 0;
gsl_vector_free(e->m_knots);
e->m_knots = NULL;
gsl_vector_free(e->xi_acc);
e->xi_acc = NULL;
gsl_matrix_free(e->theta_acc);
e->theta_acc = NULL;
gsl_matrix_free(e->theta_star_cov);
e->theta_bar = NULL;
gsl_matrix_free(e->xi_cov);
e->theta_bar = NULL;
gsl_matrix_free(e->theta_star_bar);
e->theta_bar = NULL;
gsl_matrix_free(e->theta_bar);
e->theta_bar = NULL;
qdm_mcmc_free(e->mcmc);
e->mcmc = NULL;
qdm_tau_free(e->t);
e->t = NULL;
gsl_rng_free(e->rng);
e->rng = NULL;
free(e);
}
void
qdm_evaluation_fprint(
FILE *f,
const qdm_evaluation *e
)
{
const char *prefix = " ";
fprintf(f, "%sparameters:\n", prefix);
qdm_parameters_fprint(f, &e->parameters);
fprintf(f, "%syears_min: %f\n", prefix, e->years_min);
fprintf(f, "%syears_max: %f\n", prefix, e->years_max);
fprintf(f, "%slower_bound: %f\n", prefix, e->lower_bound);
fprintf(f, "%supper_bound: %f\n", prefix, e->upper_bound);
fprintf(f, "%swaic: %f\n", prefix, e->waic);
fprintf(f, "%spwaic: %f\n", prefix, e->pwaic);
fprintf(f, "%sdic: %f\n", prefix, e->dic);
fprintf(f, "%spd: %f\n", prefix, e->pd);
fprintf(f, "%smcmc r.s: %zu\n", prefix, e->mcmc->r.s);
fprintf(f, "%stheta_bar:\n", prefix);
qdm_matrix_csv_fwrite(f, e->theta_bar);
fprintf(f, "%stheta_star_bar:\n", prefix);
qdm_matrix_csv_fwrite(f, e->theta_star_bar);
fprintf(f, "%sxi_cov:\n", prefix);
qdm_matrix_csv_fwrite(f, e->xi_cov);
fprintf(f, "%stheta_star_cov:\n", prefix);
qdm_matrix_csv_fwrite(f, e->theta_star_cov);
fprintf(f, "%sxi_low_bar: %f\n", prefix, e->xi_low_bar);
fprintf(f, "%sxi_high_bar: %f\n", prefix, e->xi_high_bar);
fprintf(f, "%stheta_acc:\n", prefix);
qdm_matrix_csv_fwrite(f, e->theta_acc);
fprintf(f, "%sxi_acc:\n", prefix);
qdm_vector_csv_fwrite(f, e->xi_acc);
fprintf(f, "%sm_knots:\n", prefix);
qdm_vector_csv_fwrite(f, e->m_knots);
fprintf(f, "%srng_seed: %lu\n", prefix, e->rng_seed);
fprintf(f, "%selapsed: %f\n", prefix, e->elapsed);
}
int
qdm_evaluation_read(
hid_t id,
qdm_evaluation **e
)
{
int status = 0;
hid_t parameters_group = -1;
hid_t mcmc_group = -1;
parameters_group = H5Gopen(id, "parameters", H5P_DEFAULT);
if (parameters_group < 0) {
status = parameters_group;
goto cleanup;
}
qdm_parameters parameters = {0};
status = qdm_parameters_read(parameters_group, ¶meters);
if (status != 0) {
goto cleanup;
}
*e = qdm_evaluation_new(¶meters);
#define READ(t, n) \
status = H5LTread_dataset_##t(id, #n, &(*e)->n); \
if (status < 0) { \
goto cleanup; \
}
READ(double, years_min);
READ(double, years_max);
READ(double, lower_bound);
READ(double, upper_bound);
READ(double, waic);
READ(double, pwaic);
READ(double, dic);
READ(double, pd);
mcmc_group = H5Gopen(id, "mcmc", H5P_DEFAULT);
if (mcmc_group < 0) {
status = mcmc_group;
goto cleanup;
}
status = qdm_mcmc_read(mcmc_group, &(*e)->mcmc);
if (status != 0) {
goto cleanup;
}
status = qdm_matrix_hd5_read(id, "theta_bar", &(*e)->theta_bar);
if (status != 0) {
goto cleanup;
}
status = qdm_matrix_hd5_read(id, "theta_star_bar", &(*e)->theta_star_bar);
if (status != 0) {
goto cleanup;
}
status = qdm_matrix_hd5_read(id, "xi_cov", &(*e)->xi_cov);
if (status != 0) {
goto cleanup;
}
status = qdm_matrix_hd5_read(id, "theta_star_cov", &(*e)->theta_star_cov);
if (status != 0) {
goto cleanup;
}
READ(double, xi_high_bar);
READ(double, xi_low_bar);
status = qdm_matrix_hd5_read(id, "theta_acc", &(*e)->theta_acc);
if (status != 0) {
goto cleanup;
}
status = qdm_vector_hd5_read(id, "xi_acc", &(*e)->xi_acc);
if (status != 0) {
goto cleanup;
}
status = qdm_vector_hd5_read(id, "m_knots", &(*e)->m_knots);
if (status != 0) {
goto cleanup;
}
status = H5LTread_dataset(id, "rng_seed", H5T_NATIVE_ULONG, &(*e)->rng_seed);
if (status < 0) {
goto cleanup;
}
READ(double, elapsed);
#undef READ
(*e)->t = qdm_tau_alloc(
(*e)->parameters.tau_table,
(*e)->parameters.tau_low,
(*e)->parameters.tau_high,
(*e)->parameters.spline_df,
(*e)->m_knots
);
cleanup:
if (parameters_group >= 0) {
H5Gclose(parameters_group);
}
if (mcmc_group >= 0) {
H5Gclose(mcmc_group);
}
return status;
}
int
qdm_evaluation_write(
hid_t id,
const qdm_evaluation *e
)
{
int status = 0;
hid_t parameters_group = -1;
hid_t mcmc_group = -1;
#define WRITE_DOUBLE(n) \
status = qdm_double_write(id, #n, e->n); \
if (status != 0) { \
goto cleanup; \
}
parameters_group = qdm_data_create_group(id, "parameters");
if (parameters_group < 0) {
status = parameters_group;
goto cleanup;
}
status = qdm_parameters_write(parameters_group, &e->parameters);
if (status != 0) {
goto cleanup;
}
WRITE_DOUBLE(years_min);
WRITE_DOUBLE(years_max);
WRITE_DOUBLE(lower_bound);
WRITE_DOUBLE(upper_bound);
WRITE_DOUBLE(waic);
WRITE_DOUBLE(pwaic);
WRITE_DOUBLE(dic);
WRITE_DOUBLE(pd);
mcmc_group = qdm_data_create_group(id, "mcmc");
if (mcmc_group < 0) {
status = mcmc_group;
goto cleanup;
}
status = qdm_mcmc_write(mcmc_group, e->mcmc);
if (status != 0) {
goto cleanup;
}
status = qdm_matrix_hd5_write(id, "theta_bar", e->theta_bar);
if (status != 0) {
goto cleanup;
}
status = qdm_matrix_hd5_write(id, "theta_star_bar", e->theta_star_bar);
if (status != 0) {
goto cleanup;
}
status = qdm_matrix_hd5_write(id, "xi_cov", e->xi_cov);
if (status != 0) {
goto cleanup;
}
status = qdm_matrix_hd5_write(id, "theta_star_cov", e->theta_star_cov);
if (status != 0) {
goto cleanup;
}
WRITE_DOUBLE(xi_high_bar);
WRITE_DOUBLE(xi_low_bar);
status = qdm_matrix_hd5_write(id, "theta_acc", e->theta_acc);
if (status != 0) {
goto cleanup;
}
status = qdm_vector_hd5_write(id, "xi_acc", e->xi_acc);
if (status != 0) {
goto cleanup;
}
status = qdm_vector_hd5_write(id, "m_knots", e->m_knots);
if (status != 0) {
goto cleanup;
}
{
hsize_t dims[1] = {1};
unsigned long int data[1] = {e->rng_seed};
status = H5LTmake_dataset(id, "rng_seed", 1, dims, H5T_NATIVE_ULONG, data);
if (status < 0) {
goto cleanup;
}
}
WRITE_DOUBLE(elapsed);
#undef WRITE_DOUBLE
cleanup:
if (parameters_group >= 0) {
H5Gclose(parameters_group);
}
if (mcmc_group >= 0) {
H5Gclose(mcmc_group);
}
return status;
}
int
qdm_evaluation_run(
qdm_evaluation *e,
const gsl_matrix *data,
size_t data_year_idx,
size_t data_month_idx,
size_t data_value_idx
)
{
int status = 0;
clock_t started_at = clock();
gsl_vector *years = NULL;
gsl_vector *years_norm = NULL;
gsl_vector *values = NULL;
gsl_vector *values_sorted = NULL;
gsl_vector *interior_knots = NULL;
gsl_vector *m_knots = NULL;
gsl_matrix *theta = NULL;
gsl_vector *ll = NULL;
gsl_vector *tau = NULL;
gsl_matrix *theta_tune = NULL;
gsl_matrix *theta_acc = NULL;
gsl_vector *xi_tune = NULL;
gsl_vector *xi_acc = NULL;
gsl_vector *xi = gsl_vector_alloc(2);
gsl_vector_set(xi, 0, e->parameters.xi_low);
gsl_vector_set(xi, 1, e->parameters.xi_high);
/* Initialize RNG */
gsl_rng_set(e->rng, e->parameters.rng_seed);
/* Normalize Years */
{
years = qdm_matrix_filter(data, data_month_idx, e->parameters.month, data_year_idx);
years_norm = qdm_matrix_filter(data, data_month_idx, e->parameters.month, data_year_idx);
gsl_vector_minmax(years, &e->years_min, &e->years_max);
double years_range = e->years_max - e->years_min;
status = gsl_vector_add_constant(years_norm, -e->years_min);
if (status != 0) {
goto cleanup;
}
status = gsl_vector_scale(years_norm, 1 / years_range);
if (status != 0) {
goto cleanup;
}
}
/* Extract Values */
{
values = qdm_matrix_filter(data, data_month_idx, e->parameters.month, data_value_idx);
values_sorted = qdm_vector_sorted(values);
e->lower_bound = gsl_vector_get(values_sorted, 0) - e->parameters.bound;
e->upper_bound = gsl_vector_get(values_sorted, values_sorted->size - 1) + e->parameters.bound;
}
/* Optimize Knots */
{
gsl_vector *middle = qdm_vector_seq(e->parameters.tau_low, e->parameters.tau_high, 0.005);
double possible_low = e->parameters.tau_low + 0.1;
double possible_high = e->parameters.tau_high - 0.1;
double possible_delta = (possible_high - possible_low) / 19;
gsl_vector *possible_knots = qdm_vector_seq(possible_low, possible_high, possible_delta);
interior_knots = gsl_vector_calloc(e->parameters.knot);
status = qdm_knots_optimize(
interior_knots,
e->rng,
values_sorted,
middle,
possible_knots,
e->parameters.knot_try,
e->parameters.spline_df
);
if (status != 0) {
goto cleanup;
}
gsl_vector_free(possible_knots);
gsl_vector_free(middle);
}
/* Optimize Theta */
{
size_t m = e->parameters.spline_df + e->parameters.knot;
m_knots = qdm_knots_vector(e->parameters.spline_df, interior_knots);
e->t = qdm_tau_alloc(
e->parameters.tau_table,
e->parameters.tau_low,
e->parameters.tau_high,
e->parameters.spline_df,
m_knots
);
gsl_vector *middle = qdm_vector_seq(e->parameters.tau_low, e->parameters.tau_high, 0.01);
gsl_matrix *ix = gsl_matrix_alloc(middle->size, m+1);
qdm_ispline_matrix(ix, middle, e->parameters.spline_df, m_knots);
theta = gsl_matrix_alloc(2, ix->size2);
gsl_vector_view theta0 = gsl_matrix_row(theta, 0);
gsl_vector_view theta1 = gsl_matrix_row(theta, 1);
size_t theta_pivot = qdm_vector_greater_than(years_norm, 0.3);
gsl_vector_view values0 = gsl_vector_subvector(values, 0, theta_pivot);
gsl_vector_view values1 = gsl_vector_subvector(values, theta_pivot, values->size - theta_pivot);
assert(values0.vector.size + values1.vector.size == values->size);
gsl_vector *eq0 = qdm_vector_quantile(&values0.vector, middle);
status = qdm_theta_optimize(&theta0.vector, eq0, ix);
if (status != 0) {
goto cleanup;
}
gsl_vector *eq1 = NULL;
if (e->parameters.truncate) {
gsl_vector_set_zero(&theta1.vector);
} else {
eq1 = qdm_vector_quantile(&values1.vector, middle);
status = qdm_theta_optimize(&theta1.vector, eq1, ix);
if (status != 0) {
goto cleanup;
}
status = gsl_vector_sub(&theta1.vector, &theta0.vector);
if (status != 0) {
goto cleanup;
}
}
qdm_theta_matrix_constrain(theta, e->parameters.theta_min);
ll = gsl_vector_alloc(values->size);
tau = gsl_vector_alloc(values->size);
for (size_t i = 0; i < values->size; i++) {
qdm_logl_3(
&ll->data[i],
&tau->data[i],
gsl_vector_get(years_norm, i),
gsl_vector_get(values, i),
e->t,
xi,
theta
);
}
gsl_vector_free(eq1);
gsl_vector_free(eq0);
gsl_matrix_free(ix);
gsl_vector_free(middle);
}
/* MCMC */
{
qdm_mcmc_parameters mcmc_p = {
.rng = e->rng,
.burn = e->parameters.burn,
.iter = e->parameters.iter,
.thin = e->parameters.thin,
.acc_check = e->parameters.acc_check,
.spline_df = e->parameters.spline_df,
.xi = xi,
.ll = ll,
.tau = tau,
.theta = theta,
.xi_prior_mean = e->parameters.xi_prior_mean,
.xi_prior_var = e->parameters.xi_prior_var,
.xi_tune_sd = e->parameters.xi_tune_sd,
.theta_min = e->parameters.theta_min,
.theta_tune_sd = e->parameters.theta_tune_sd,
.x = years_norm,
.y = values,
.t = e->t,
.m_knots = m_knots,
.truncate = e->parameters.truncate,
};
e->mcmc = qdm_mcmc_alloc(mcmc_p);
status = qdm_mcmc_run(e->mcmc);
if (status != 0) {
goto cleanup;
}
}
/* Model Diagnostics */
{
// WAIC
gsl_vector *ll_exp = gsl_vector_calloc(e->mcmc->r.s);
gsl_vector *lppd = gsl_vector_calloc(values->size);
gsl_vector *vlog = gsl_vector_calloc(values->size);
for (size_t j = 0; j < values->size; j++) {
gsl_vector_view ll_k = qdm_ijk_get_k(e->mcmc->r.ll, 0, j);
for (size_t i = 0; i < ll_k.vector.size; i++) {
gsl_vector_set(ll_exp, i, exp(gsl_vector_get(&ll_k.vector, i)));
}
gsl_vector_set(lppd, j, log(gsl_stats_mean(ll_exp->data, ll_exp->stride, ll_exp->size)));
gsl_vector_set(vlog, j, gsl_stats_variance(ll_k.vector.data, ll_k.vector.stride, ll_k.vector.size));
}
status = gsl_vector_sub(lppd, vlog);
if (status != 0) {
goto cleanup;
}
e->waic = -2 * qdm_vector_sum(lppd);
e->pwaic = qdm_vector_sum(vlog);
// DIC
gsl_vector *ll_sum = gsl_vector_alloc(e->mcmc->r.s);
for (size_t k = 0; k < e->mcmc->r.s; k++) {
gsl_matrix_view ll_ij_m = qdm_ijk_get_ij(e->mcmc->r.ll, k);
gsl_vector_view ll_ij = gsl_matrix_row(&ll_ij_m.matrix, 0);
gsl_vector_set(ll_sum, k, qdm_vector_sum(&ll_ij.vector));
}
status = gsl_vector_scale(ll_sum, -2);
if (status != 0) {
goto cleanup;
}
double d_bar = gsl_stats_mean(ll_sum->data, ll_sum->stride, ll_sum->size);
double d_theta_bar = 0;
gsl_vector_view xi_low = qdm_ijk_get_k(e->mcmc->r.xi, 0, 0);
gsl_vector_view xi_high = qdm_ijk_get_k(e->mcmc->r.xi, 0, 1);
double xi_low_bar = gsl_stats_mean(xi_low.vector.data, xi_low.vector.stride, xi_low.vector.size);
double xi_high_bar = gsl_stats_mean(xi_high.vector.data, xi_high.vector.stride, xi_high.vector.size);
gsl_vector *xi_bar = gsl_vector_alloc(2);
gsl_vector_set(xi_bar, 0, xi_low_bar);
gsl_vector_set(xi_bar, 1, xi_high_bar);
gsl_matrix *theta_bar = gsl_matrix_alloc(theta->size1, theta->size2);
for (size_t i = 0; i < e->mcmc->r.theta->size1; i++) {
for (size_t j = 0; j < e->mcmc->r.theta->size2; j++) {
gsl_vector_view theta_k = qdm_ijk_get_k(e->mcmc->r.theta, i, j);
gsl_matrix_set(theta_bar, i, j, gsl_stats_mean(theta_k.vector.data, theta_k.vector.stride, theta_k.vector.size));
}
}
gsl_matrix *theta_star_bar = gsl_matrix_alloc(theta->size1, theta->size2);
for (size_t i = 0; i < e->mcmc->r.theta_star->size1; i++) {
for (size_t j = 0; j < e->mcmc->r.theta_star->size2; j++) {
gsl_vector_view theta_k = qdm_ijk_get_k(e->mcmc->r.theta_star, i, j);
gsl_matrix_set(theta_star_bar, i, j, gsl_stats_mean(theta_k.vector.data, theta_k.vector.stride, theta_k.vector.size));
}
}
for (size_t i = 0; i < values->size; i++) {
double theta_bar_ll = 0;
double tau_tmp = 0;
qdm_logl_3(
&theta_bar_ll,
&tau_tmp,
gsl_vector_get(years_norm, i),
gsl_vector_get(values, i),
e->t,
xi_bar,
theta_bar
);
d_theta_bar = d_theta_bar + -2 * theta_bar_ll;
}
e->pd = d_bar - d_theta_bar;
e->dic = e->pd + d_bar;
e->theta_bar = qdm_matrix_copy(theta_bar);
e->theta_star_bar = qdm_matrix_copy(theta_star_bar);
e->xi_cov = qdm_ijk_cov(e->mcmc->r.xi);
e->theta_star_cov = qdm_ijk_cov(e->mcmc->r.theta_star);
e->xi_low_bar = xi_low_bar;
e->xi_high_bar = xi_high_bar;
gsl_vector_free(xi_bar);
gsl_matrix_free(theta_star_bar);
gsl_matrix_free(theta_bar);
gsl_vector_free(ll_sum);
gsl_vector_free(vlog);
gsl_vector_free(lppd);
gsl_vector_free(ll_exp);
}
/* Results */
{
e->theta_acc = qdm_matrix_copy(e->mcmc->w.theta_acc);
e->xi_acc = qdm_vector_copy(e->mcmc->w.xi_acc);
e->m_knots = qdm_vector_copy(m_knots);
e->rng_seed = gsl_rng_get(e->rng);
}
gsl_vector_free(years);
gsl_vector_free(years_norm);
gsl_vector_free(values);
gsl_vector_free(values_sorted);
gsl_vector_free(interior_knots);
gsl_vector_free(m_knots);
gsl_matrix_free(theta);
gsl_vector_free(ll);
gsl_vector_free(tau);
gsl_matrix_free(theta_tune);
gsl_matrix_free(theta_acc);
gsl_vector_free(xi_tune);
gsl_vector_free(xi_acc);
cleanup:
e->elapsed = ((double)(clock() - started_at)) / CLOCKS_PER_SEC;
return status;
}
| {
"alphanum_fraction": 0.6371809745,
"avg_line_length": 22.7140974967,
"ext": "c",
"hexsha": "e4805061d6ef1609b84678abd62ff2083b455cc7",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "2ee95bec6c8be64f69e231c78f2be5fce3509c67",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "calebcase/qdm",
"max_forks_repo_path": "src/evaluation.c",
"max_issues_count": 3,
"max_issues_repo_head_hexsha": "2ee95bec6c8be64f69e231c78f2be5fce3509c67",
"max_issues_repo_issues_event_max_datetime": "2020-03-22T20:22:53.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-03-06T18:09:06.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "calebcase/qdm",
"max_issues_repo_path": "src/evaluation.c",
"max_line_length": 126,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "2ee95bec6c8be64f69e231c78f2be5fce3509c67",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "calebcase/qdm",
"max_stars_repo_path": "src/evaluation.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 5325,
"size": 17240
} |
#include "ccv.h"
#include "ccv_internal.h"
#if defined(HAVE_SSE2)
#include <xmmintrin.h>
#elif defined(HAVE_NEON)
#include <arm_neon.h>
#endif
#ifdef HAVE_GSL
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
#endif
#ifdef USE_OPENMP
#include <omp.h>
#endif
#ifdef USE_DISPATCH
#include <dispatch/dispatch.h>
#endif
#include "3rdparty/sqlite3/sqlite3.h"
const ccv_scd_param_t ccv_scd_default_params = {
.interval = 5,
.min_neighbors = 1,
.step_through = 4,
.size = {
.width = 48,
.height = 48,
},
};
#define CCV_SCD_CHANNEL (11)
// this uses a look up table for cubic root computation because rgb to luv only requires data within range of 0~1
static inline float fast_cube_root(const float d)
{
static const float cube_root[2048] = {
0.000000e+00, 7.875788e-02, 9.922871e-02, 1.135885e-01, 1.250203e-01, 1.346741e-01, 1.431126e-01, 1.506584e-01,
1.575158e-01, 1.638230e-01, 1.696787e-01, 1.751560e-01, 1.803105e-01, 1.851861e-01, 1.898177e-01, 1.942336e-01,
1.984574e-01, 2.025087e-01, 2.064040e-01, 2.101577e-01, 2.137818e-01, 2.172870e-01, 2.206827e-01, 2.239769e-01,
2.271770e-01, 2.302894e-01, 2.333199e-01, 2.362736e-01, 2.391553e-01, 2.419692e-01, 2.447191e-01, 2.474085e-01,
2.500407e-01, 2.526186e-01, 2.551450e-01, 2.576222e-01, 2.600528e-01, 2.624387e-01, 2.647821e-01, 2.670846e-01,
2.693482e-01, 2.715743e-01, 2.737645e-01, 2.759202e-01, 2.780428e-01, 2.801334e-01, 2.821933e-01, 2.842235e-01,
2.862251e-01, 2.881992e-01, 2.901465e-01, 2.920681e-01, 2.939647e-01, 2.958371e-01, 2.976862e-01, 2.995125e-01,
3.013168e-01, 3.030998e-01, 3.048621e-01, 3.066041e-01, 3.083267e-01, 3.100302e-01, 3.117152e-01, 3.133821e-01,
3.150315e-01, 3.166639e-01, 3.182795e-01, 3.198789e-01, 3.214625e-01, 3.230307e-01, 3.245837e-01, 3.261220e-01,
3.276460e-01, 3.291559e-01, 3.306521e-01, 3.321348e-01, 3.336045e-01, 3.350613e-01, 3.365056e-01, 3.379375e-01,
3.393574e-01, 3.407656e-01, 3.421622e-01, 3.435475e-01, 3.449216e-01, 3.462850e-01, 3.476377e-01, 3.489799e-01,
3.503119e-01, 3.516339e-01, 3.529460e-01, 3.542483e-01, 3.555412e-01, 3.568248e-01, 3.580992e-01, 3.593646e-01,
3.606211e-01, 3.618689e-01, 3.631082e-01, 3.643391e-01, 3.655617e-01, 3.667762e-01, 3.679827e-01, 3.691814e-01,
3.703723e-01, 3.715556e-01, 3.727314e-01, 3.738999e-01, 3.750610e-01, 3.762151e-01, 3.773621e-01, 3.785022e-01,
3.796354e-01, 3.807619e-01, 3.818818e-01, 3.829952e-01, 3.841021e-01, 3.852027e-01, 3.862970e-01, 3.873852e-01,
3.884673e-01, 3.895434e-01, 3.906136e-01, 3.916779e-01, 3.927365e-01, 3.937894e-01, 3.948367e-01, 3.958785e-01,
3.969149e-01, 3.979458e-01, 3.989714e-01, 3.999918e-01, 4.010071e-01, 4.020171e-01, 4.030222e-01, 4.040223e-01,
4.050174e-01, 4.060076e-01, 4.069931e-01, 4.079738e-01, 4.089499e-01, 4.099212e-01, 4.108880e-01, 4.118503e-01,
4.128081e-01, 4.137615e-01, 4.147105e-01, 4.156551e-01, 4.165955e-01, 4.175317e-01, 4.184637e-01, 4.193916e-01,
4.203153e-01, 4.212351e-01, 4.221508e-01, 4.230626e-01, 4.239704e-01, 4.248744e-01, 4.257746e-01, 4.266710e-01,
4.275636e-01, 4.284525e-01, 4.293377e-01, 4.302193e-01, 4.310973e-01, 4.319718e-01, 4.328427e-01, 4.337101e-01,
4.345741e-01, 4.354346e-01, 4.362918e-01, 4.371456e-01, 4.379961e-01, 4.388433e-01, 4.396872e-01, 4.405279e-01,
4.413654e-01, 4.421997e-01, 4.430309e-01, 4.438590e-01, 4.446840e-01, 4.455060e-01, 4.463249e-01, 4.471409e-01,
4.479539e-01, 4.487639e-01, 4.495711e-01, 4.503753e-01, 4.511767e-01, 4.519752e-01, 4.527710e-01, 4.535639e-01,
4.543541e-01, 4.551415e-01, 4.559263e-01, 4.567083e-01, 4.574877e-01, 4.582644e-01, 4.590385e-01, 4.598100e-01,
4.605789e-01, 4.613453e-01, 4.621091e-01, 4.628704e-01, 4.636292e-01, 4.643855e-01, 4.651394e-01, 4.658908e-01,
4.666398e-01, 4.673865e-01, 4.681307e-01, 4.688726e-01, 4.696122e-01, 4.703494e-01, 4.710843e-01, 4.718169e-01,
4.725473e-01, 4.732754e-01, 4.740013e-01, 4.747250e-01, 4.754464e-01, 4.761657e-01, 4.768828e-01, 4.775978e-01,
4.783106e-01, 4.790214e-01, 4.797300e-01, 4.804365e-01, 4.811410e-01, 4.818434e-01, 4.825437e-01, 4.832420e-01,
4.839384e-01, 4.846327e-01, 4.853250e-01, 4.860154e-01, 4.867038e-01, 4.873902e-01, 4.880748e-01, 4.887574e-01,
4.894381e-01, 4.901170e-01, 4.907939e-01, 4.914690e-01, 4.921423e-01, 4.928137e-01, 4.934832e-01, 4.941510e-01,
4.948170e-01, 4.954812e-01, 4.961436e-01, 4.968042e-01, 4.974631e-01, 4.981203e-01, 4.987757e-01, 4.994294e-01,
5.000814e-01, 5.007317e-01, 5.013803e-01, 5.020273e-01, 5.026726e-01, 5.033162e-01, 5.039582e-01, 5.045985e-01,
5.052372e-01, 5.058743e-01, 5.065099e-01, 5.071438e-01, 5.077761e-01, 5.084069e-01, 5.090362e-01, 5.096638e-01,
5.102900e-01, 5.109145e-01, 5.115376e-01, 5.121592e-01, 5.127792e-01, 5.133978e-01, 5.140148e-01, 5.146304e-01,
5.152445e-01, 5.158572e-01, 5.164684e-01, 5.170782e-01, 5.176865e-01, 5.182934e-01, 5.188988e-01, 5.195029e-01,
5.201056e-01, 5.207069e-01, 5.213068e-01, 5.219053e-01, 5.225024e-01, 5.230982e-01, 5.236927e-01, 5.242857e-01,
5.248775e-01, 5.254679e-01, 5.260570e-01, 5.266448e-01, 5.272312e-01, 5.278164e-01, 5.284002e-01, 5.289828e-01,
5.295641e-01, 5.301442e-01, 5.307229e-01, 5.313004e-01, 5.318767e-01, 5.324517e-01, 5.330254e-01, 5.335979e-01,
5.341693e-01, 5.347394e-01, 5.353082e-01, 5.358759e-01, 5.364423e-01, 5.370076e-01, 5.375717e-01, 5.381346e-01,
5.386963e-01, 5.392569e-01, 5.398163e-01, 5.403746e-01, 5.409316e-01, 5.414876e-01, 5.420424e-01, 5.425960e-01,
5.431486e-01, 5.437000e-01, 5.442503e-01, 5.447995e-01, 5.453476e-01, 5.458946e-01, 5.464405e-01, 5.469853e-01,
5.475290e-01, 5.480717e-01, 5.486133e-01, 5.491537e-01, 5.496932e-01, 5.502316e-01, 5.507689e-01, 5.513052e-01,
5.518404e-01, 5.523747e-01, 5.529078e-01, 5.534400e-01, 5.539711e-01, 5.545012e-01, 5.550303e-01, 5.555584e-01,
5.560855e-01, 5.566117e-01, 5.571368e-01, 5.576609e-01, 5.581840e-01, 5.587062e-01, 5.592273e-01, 5.597475e-01,
5.602668e-01, 5.607851e-01, 5.613024e-01, 5.618188e-01, 5.623342e-01, 5.628487e-01, 5.633622e-01, 5.638748e-01,
5.643865e-01, 5.648973e-01, 5.654072e-01, 5.659161e-01, 5.664241e-01, 5.669311e-01, 5.674374e-01, 5.679426e-01,
5.684470e-01, 5.689505e-01, 5.694531e-01, 5.699549e-01, 5.704557e-01, 5.709556e-01, 5.714548e-01, 5.719529e-01,
5.724503e-01, 5.729468e-01, 5.734424e-01, 5.739372e-01, 5.744311e-01, 5.749242e-01, 5.754164e-01, 5.759078e-01,
5.763984e-01, 5.768881e-01, 5.773770e-01, 5.778650e-01, 5.783523e-01, 5.788387e-01, 5.793243e-01, 5.798091e-01,
5.802931e-01, 5.807762e-01, 5.812586e-01, 5.817402e-01, 5.822210e-01, 5.827010e-01, 5.831801e-01, 5.836585e-01,
5.841362e-01, 5.846130e-01, 5.850891e-01, 5.855644e-01, 5.860389e-01, 5.865127e-01, 5.869856e-01, 5.874579e-01,
5.879294e-01, 5.884001e-01, 5.888700e-01, 5.893393e-01, 5.898077e-01, 5.902755e-01, 5.907425e-01, 5.912087e-01,
5.916742e-01, 5.921390e-01, 5.926031e-01, 5.930664e-01, 5.935290e-01, 5.939909e-01, 5.944521e-01, 5.949125e-01,
5.953723e-01, 5.958313e-01, 5.962896e-01, 5.967473e-01, 5.972042e-01, 5.976604e-01, 5.981160e-01, 5.985708e-01,
5.990250e-01, 5.994784e-01, 5.999312e-01, 6.003833e-01, 6.008347e-01, 6.012855e-01, 6.017355e-01, 6.021850e-01,
6.026337e-01, 6.030817e-01, 6.035291e-01, 6.039758e-01, 6.044219e-01, 6.048673e-01, 6.053120e-01, 6.057562e-01,
6.061996e-01, 6.066424e-01, 6.070846e-01, 6.075261e-01, 6.079670e-01, 6.084072e-01, 6.088468e-01, 6.092858e-01,
6.097241e-01, 6.101618e-01, 6.105989e-01, 6.110353e-01, 6.114712e-01, 6.119064e-01, 6.123410e-01, 6.127750e-01,
6.132084e-01, 6.136411e-01, 6.140732e-01, 6.145048e-01, 6.149357e-01, 6.153660e-01, 6.157957e-01, 6.162249e-01,
6.166534e-01, 6.170813e-01, 6.175086e-01, 6.179354e-01, 6.183616e-01, 6.187872e-01, 6.192122e-01, 6.196365e-01,
6.200604e-01, 6.204836e-01, 6.209063e-01, 6.213284e-01, 6.217499e-01, 6.221709e-01, 6.225913e-01, 6.230111e-01,
6.234304e-01, 6.238490e-01, 6.242672e-01, 6.246848e-01, 6.251017e-01, 6.255182e-01, 6.259341e-01, 6.263494e-01,
6.267643e-01, 6.271785e-01, 6.275922e-01, 6.280054e-01, 6.284180e-01, 6.288301e-01, 6.292416e-01, 6.296526e-01,
6.300631e-01, 6.304730e-01, 6.308824e-01, 6.312913e-01, 6.316996e-01, 6.321074e-01, 6.325147e-01, 6.329215e-01,
6.333277e-01, 6.337335e-01, 6.341386e-01, 6.345433e-01, 6.349475e-01, 6.353511e-01, 6.357543e-01, 6.361569e-01,
6.365590e-01, 6.369606e-01, 6.373618e-01, 6.377624e-01, 6.381625e-01, 6.385621e-01, 6.389612e-01, 6.393598e-01,
6.397579e-01, 6.401555e-01, 6.405526e-01, 6.409492e-01, 6.413454e-01, 6.417410e-01, 6.421362e-01, 6.425309e-01,
6.429250e-01, 6.433188e-01, 6.437120e-01, 6.441047e-01, 6.444970e-01, 6.448888e-01, 6.452801e-01, 6.456710e-01,
6.460613e-01, 6.464512e-01, 6.468406e-01, 6.472296e-01, 6.476181e-01, 6.480061e-01, 6.483937e-01, 6.487808e-01,
6.491674e-01, 6.495536e-01, 6.499393e-01, 6.503246e-01, 6.507094e-01, 6.510937e-01, 6.514776e-01, 6.518611e-01,
6.522441e-01, 6.526266e-01, 6.530087e-01, 6.533904e-01, 6.537716e-01, 6.541524e-01, 6.545327e-01, 6.549126e-01,
6.552920e-01, 6.556710e-01, 6.560495e-01, 6.564277e-01, 6.568054e-01, 6.571826e-01, 6.575595e-01, 6.579359e-01,
6.583118e-01, 6.586874e-01, 6.590625e-01, 6.594372e-01, 6.598114e-01, 6.601852e-01, 6.605586e-01, 6.609316e-01,
6.613042e-01, 6.616763e-01, 6.620481e-01, 6.624194e-01, 6.627903e-01, 6.631607e-01, 6.635308e-01, 6.639005e-01,
6.642697e-01, 6.646385e-01, 6.650070e-01, 6.653750e-01, 6.657426e-01, 6.661098e-01, 6.664766e-01, 6.668430e-01,
6.672090e-01, 6.675746e-01, 6.679398e-01, 6.683046e-01, 6.686690e-01, 6.690330e-01, 6.693966e-01, 6.697598e-01,
6.701226e-01, 6.704850e-01, 6.708471e-01, 6.712087e-01, 6.715700e-01, 6.719308e-01, 6.722913e-01, 6.726514e-01,
6.730111e-01, 6.733705e-01, 6.737294e-01, 6.740879e-01, 6.744461e-01, 6.748039e-01, 6.751614e-01, 6.755184e-01,
6.758750e-01, 6.762313e-01, 6.765872e-01, 6.769428e-01, 6.772979e-01, 6.776527e-01, 6.780071e-01, 6.783612e-01,
6.787149e-01, 6.790682e-01, 6.794212e-01, 6.797737e-01, 6.801260e-01, 6.804778e-01, 6.808293e-01, 6.811804e-01,
6.815312e-01, 6.818815e-01, 6.822316e-01, 6.825813e-01, 6.829306e-01, 6.832796e-01, 6.836282e-01, 6.839765e-01,
6.843244e-01, 6.846719e-01, 6.850191e-01, 6.853660e-01, 6.857125e-01, 6.860586e-01, 6.864043e-01, 6.867498e-01,
6.870949e-01, 6.874397e-01, 6.877841e-01, 6.881282e-01, 6.884719e-01, 6.888152e-01, 6.891583e-01, 6.895010e-01,
6.898433e-01, 6.901854e-01, 6.905270e-01, 6.908684e-01, 6.912094e-01, 6.915500e-01, 6.918904e-01, 6.922303e-01,
6.925700e-01, 6.929094e-01, 6.932484e-01, 6.935870e-01, 6.939254e-01, 6.942633e-01, 6.946011e-01, 6.949384e-01,
6.952754e-01, 6.956121e-01, 6.959485e-01, 6.962845e-01, 6.966202e-01, 6.969556e-01, 6.972907e-01, 6.976255e-01,
6.979599e-01, 6.982940e-01, 6.986278e-01, 6.989613e-01, 6.992944e-01, 6.996273e-01, 6.999598e-01, 7.002920e-01,
7.006239e-01, 7.009555e-01, 7.012867e-01, 7.016177e-01, 7.019483e-01, 7.022786e-01, 7.026086e-01, 7.029384e-01,
7.032678e-01, 7.035969e-01, 7.039256e-01, 7.042542e-01, 7.045823e-01, 7.049102e-01, 7.052377e-01, 7.055650e-01,
7.058919e-01, 7.062186e-01, 7.065449e-01, 7.068710e-01, 7.071967e-01, 7.075222e-01, 7.078474e-01, 7.081722e-01,
7.084967e-01, 7.088210e-01, 7.091449e-01, 7.094686e-01, 7.097920e-01, 7.101150e-01, 7.104378e-01, 7.107603e-01,
7.110825e-01, 7.114044e-01, 7.117260e-01, 7.120473e-01, 7.123684e-01, 7.126891e-01, 7.130095e-01, 7.133297e-01,
7.136496e-01, 7.139692e-01, 7.142885e-01, 7.146075e-01, 7.149262e-01, 7.152447e-01, 7.155629e-01, 7.158808e-01,
7.161984e-01, 7.165157e-01, 7.168328e-01, 7.171495e-01, 7.174660e-01, 7.177821e-01, 7.180981e-01, 7.184138e-01,
7.187291e-01, 7.190442e-01, 7.193590e-01, 7.196736e-01, 7.199879e-01, 7.203019e-01, 7.206156e-01, 7.209290e-01,
7.212422e-01, 7.215551e-01, 7.218677e-01, 7.221801e-01, 7.224922e-01, 7.228040e-01, 7.231156e-01, 7.234268e-01,
7.237378e-01, 7.240486e-01, 7.243591e-01, 7.246693e-01, 7.249793e-01, 7.252890e-01, 7.255983e-01, 7.259076e-01,
7.262164e-01, 7.265251e-01, 7.268335e-01, 7.271415e-01, 7.274494e-01, 7.277570e-01, 7.280643e-01, 7.283714e-01,
7.286782e-01, 7.289847e-01, 7.292911e-01, 7.295971e-01, 7.299029e-01, 7.302084e-01, 7.305137e-01, 7.308187e-01,
7.311234e-01, 7.314279e-01, 7.317322e-01, 7.320362e-01, 7.323400e-01, 7.326434e-01, 7.329467e-01, 7.332497e-01,
7.335525e-01, 7.338549e-01, 7.341572e-01, 7.344592e-01, 7.347609e-01, 7.350624e-01, 7.353637e-01, 7.356647e-01,
7.359655e-01, 7.362660e-01, 7.365662e-01, 7.368662e-01, 7.371660e-01, 7.374656e-01, 7.377649e-01, 7.380639e-01,
7.383628e-01, 7.386613e-01, 7.389597e-01, 7.392578e-01, 7.395556e-01, 7.398532e-01, 7.401506e-01, 7.404477e-01,
7.407446e-01, 7.410412e-01, 7.413377e-01, 7.416338e-01, 7.419298e-01, 7.422255e-01, 7.425209e-01, 7.428162e-01,
7.431112e-01, 7.434059e-01, 7.437005e-01, 7.439948e-01, 7.442889e-01, 7.445827e-01, 7.448763e-01, 7.451697e-01,
7.454628e-01, 7.457558e-01, 7.460485e-01, 7.463409e-01, 7.466331e-01, 7.469251e-01, 7.472169e-01, 7.475084e-01,
7.477998e-01, 7.480908e-01, 7.483817e-01, 7.486723e-01, 7.489627e-01, 7.492529e-01, 7.495428e-01, 7.498326e-01,
7.501221e-01, 7.504114e-01, 7.507005e-01, 7.509893e-01, 7.512779e-01, 7.515663e-01, 7.518545e-01, 7.521424e-01,
7.524302e-01, 7.527177e-01, 7.530050e-01, 7.532921e-01, 7.535789e-01, 7.538656e-01, 7.541520e-01, 7.544382e-01,
7.547241e-01, 7.550099e-01, 7.552955e-01, 7.555808e-01, 7.558660e-01, 7.561509e-01, 7.564356e-01, 7.567201e-01,
7.570043e-01, 7.572884e-01, 7.575722e-01, 7.578558e-01, 7.581393e-01, 7.584225e-01, 7.587055e-01, 7.589883e-01,
7.592708e-01, 7.595532e-01, 7.598354e-01, 7.601173e-01, 7.603990e-01, 7.606806e-01, 7.609619e-01, 7.612430e-01,
7.615239e-01, 7.618046e-01, 7.620851e-01, 7.623653e-01, 7.626454e-01, 7.629253e-01, 7.632049e-01, 7.634844e-01,
7.637637e-01, 7.640427e-01, 7.643216e-01, 7.646002e-01, 7.648786e-01, 7.651569e-01, 7.654349e-01, 7.657127e-01,
7.659904e-01, 7.662678e-01, 7.665451e-01, 7.668221e-01, 7.670989e-01, 7.673756e-01, 7.676520e-01, 7.679282e-01,
7.682042e-01, 7.684801e-01, 7.687557e-01, 7.690312e-01, 7.693064e-01, 7.695814e-01, 7.698563e-01, 7.701310e-01,
7.704054e-01, 7.706797e-01, 7.709538e-01, 7.712276e-01, 7.715013e-01, 7.717748e-01, 7.720481e-01, 7.723212e-01,
7.725941e-01, 7.728668e-01, 7.731394e-01, 7.734116e-01, 7.736838e-01, 7.739558e-01, 7.742275e-01, 7.744991e-01,
7.747704e-01, 7.750416e-01, 7.753126e-01, 7.755834e-01, 7.758540e-01, 7.761245e-01, 7.763947e-01, 7.766647e-01,
7.769346e-01, 7.772043e-01, 7.774737e-01, 7.777431e-01, 7.780122e-01, 7.782811e-01, 7.785498e-01, 7.788184e-01,
7.790868e-01, 7.793550e-01, 7.796230e-01, 7.798908e-01, 7.801584e-01, 7.804259e-01, 7.806932e-01, 7.809603e-01,
7.812271e-01, 7.814939e-01, 7.817604e-01, 7.820268e-01, 7.822930e-01, 7.825589e-01, 7.828248e-01, 7.830904e-01,
7.833558e-01, 7.836211e-01, 7.838862e-01, 7.841511e-01, 7.844158e-01, 7.846804e-01, 7.849448e-01, 7.852090e-01,
7.854730e-01, 7.857369e-01, 7.860005e-01, 7.862641e-01, 7.865273e-01, 7.867905e-01, 7.870535e-01, 7.873163e-01,
7.875788e-01, 7.878413e-01, 7.881036e-01, 7.883657e-01, 7.886276e-01, 7.888893e-01, 7.891509e-01, 7.894123e-01,
7.896735e-01, 7.899345e-01, 7.901954e-01, 7.904561e-01, 7.907166e-01, 7.909770e-01, 7.912372e-01, 7.914972e-01,
7.917571e-01, 7.920167e-01, 7.922763e-01, 7.925356e-01, 7.927948e-01, 7.930537e-01, 7.933126e-01, 7.935712e-01,
7.938297e-01, 7.940881e-01, 7.943462e-01, 7.946042e-01, 7.948620e-01, 7.951197e-01, 7.953772e-01, 7.956345e-01,
7.958916e-01, 7.961487e-01, 7.964054e-01, 7.966621e-01, 7.969186e-01, 7.971749e-01, 7.974311e-01, 7.976871e-01,
7.979429e-01, 7.981986e-01, 7.984541e-01, 7.987095e-01, 7.989646e-01, 7.992196e-01, 7.994745e-01, 7.997292e-01,
7.999837e-01, 8.002381e-01, 8.004923e-01, 8.007463e-01, 8.010002e-01, 8.012539e-01, 8.015075e-01, 8.017609e-01,
8.020141e-01, 8.022672e-01, 8.025202e-01, 8.027729e-01, 8.030255e-01, 8.032780e-01, 8.035302e-01, 8.037823e-01,
8.040344e-01, 8.042861e-01, 8.045378e-01, 8.047893e-01, 8.050406e-01, 8.052918e-01, 8.055428e-01, 8.057937e-01,
8.060444e-01, 8.062950e-01, 8.065454e-01, 8.067956e-01, 8.070457e-01, 8.072957e-01, 8.075454e-01, 8.077950e-01,
8.080446e-01, 8.082938e-01, 8.085430e-01, 8.087921e-01, 8.090409e-01, 8.092896e-01, 8.095381e-01, 8.097866e-01,
8.100348e-01, 8.102829e-01, 8.105308e-01, 8.107786e-01, 8.110263e-01, 8.112738e-01, 8.115211e-01, 8.117683e-01,
8.120154e-01, 8.122622e-01, 8.125089e-01, 8.127556e-01, 8.130020e-01, 8.132483e-01, 8.134944e-01, 8.137404e-01,
8.139862e-01, 8.142319e-01, 8.144775e-01, 8.147229e-01, 8.149682e-01, 8.152133e-01, 8.154582e-01, 8.157030e-01,
8.159477e-01, 8.161922e-01, 8.164365e-01, 8.166808e-01, 8.169249e-01, 8.171688e-01, 8.174126e-01, 8.176562e-01,
8.178997e-01, 8.181431e-01, 8.183863e-01, 8.186293e-01, 8.188722e-01, 8.191150e-01, 8.193576e-01, 8.196001e-01,
8.198425e-01, 8.200847e-01, 8.203267e-01, 8.205686e-01, 8.208104e-01, 8.210521e-01, 8.212935e-01, 8.215349e-01,
8.217760e-01, 8.220171e-01, 8.222581e-01, 8.224988e-01, 8.227395e-01, 8.229799e-01, 8.232203e-01, 8.234605e-01,
8.237006e-01, 8.239405e-01, 8.241804e-01, 8.244200e-01, 8.246595e-01, 8.248989e-01, 8.251381e-01, 8.253772e-01,
8.256162e-01, 8.258550e-01, 8.260937e-01, 8.263323e-01, 8.265706e-01, 8.268089e-01, 8.270471e-01, 8.272851e-01,
8.275229e-01, 8.277607e-01, 8.279983e-01, 8.282357e-01, 8.284730e-01, 8.287102e-01, 8.289472e-01, 8.291842e-01,
8.294209e-01, 8.296576e-01, 8.298941e-01, 8.301305e-01, 8.303667e-01, 8.306028e-01, 8.308387e-01, 8.310746e-01,
8.313103e-01, 8.315458e-01, 8.317813e-01, 8.320166e-01, 8.322517e-01, 8.324867e-01, 8.327217e-01, 8.329564e-01,
8.331911e-01, 8.334256e-01, 8.336599e-01, 8.338942e-01, 8.341283e-01, 8.343623e-01, 8.345962e-01, 8.348299e-01,
8.350635e-01, 8.352969e-01, 8.355302e-01, 8.357634e-01, 8.359964e-01, 8.362294e-01, 8.364622e-01, 8.366948e-01,
8.369274e-01, 8.371598e-01, 8.373921e-01, 8.376243e-01, 8.378563e-01, 8.380882e-01, 8.383200e-01, 8.385516e-01,
8.387831e-01, 8.390145e-01, 8.392458e-01, 8.394769e-01, 8.397079e-01, 8.399388e-01, 8.401695e-01, 8.404002e-01,
8.406307e-01, 8.408611e-01, 8.410913e-01, 8.413214e-01, 8.415514e-01, 8.417813e-01, 8.420110e-01, 8.422406e-01,
8.424702e-01, 8.426995e-01, 8.429288e-01, 8.431579e-01, 8.433869e-01, 8.436158e-01, 8.438445e-01, 8.440731e-01,
8.443016e-01, 8.445300e-01, 8.447582e-01, 8.449863e-01, 8.452144e-01, 8.454422e-01, 8.456700e-01, 8.458977e-01,
8.461251e-01, 8.463526e-01, 8.465798e-01, 8.468069e-01, 8.470340e-01, 8.472609e-01, 8.474877e-01, 8.477143e-01,
8.479409e-01, 8.481673e-01, 8.483936e-01, 8.486198e-01, 8.488458e-01, 8.490717e-01, 8.492976e-01, 8.495233e-01,
8.497488e-01, 8.499743e-01, 8.501996e-01, 8.504249e-01, 8.506500e-01, 8.508750e-01, 8.510998e-01, 8.513246e-01,
8.515491e-01, 8.517737e-01, 8.519981e-01, 8.522223e-01, 8.524465e-01, 8.526706e-01, 8.528944e-01, 8.531182e-01,
8.533419e-01, 8.535655e-01, 8.537889e-01, 8.540123e-01, 8.542355e-01, 8.544586e-01, 8.546816e-01, 8.549044e-01,
8.551272e-01, 8.553498e-01, 8.555723e-01, 8.557947e-01, 8.560170e-01, 8.562392e-01, 8.564612e-01, 8.566832e-01,
8.569050e-01, 8.571267e-01, 8.573483e-01, 8.575698e-01, 8.577912e-01, 8.580124e-01, 8.582336e-01, 8.584546e-01,
8.586755e-01, 8.588963e-01, 8.591169e-01, 8.593375e-01, 8.595580e-01, 8.597783e-01, 8.599985e-01, 8.602186e-01,
8.604387e-01, 8.606585e-01, 8.608783e-01, 8.610980e-01, 8.613176e-01, 8.615370e-01, 8.617563e-01, 8.619756e-01,
8.621947e-01, 8.624136e-01, 8.626326e-01, 8.628513e-01, 8.630700e-01, 8.632885e-01, 8.635070e-01, 8.637253e-01,
8.639436e-01, 8.641617e-01, 8.643796e-01, 8.645976e-01, 8.648154e-01, 8.650330e-01, 8.652506e-01, 8.654680e-01,
8.656853e-01, 8.659026e-01, 8.661197e-01, 8.663368e-01, 8.665537e-01, 8.667705e-01, 8.669872e-01, 8.672037e-01,
8.674202e-01, 8.676366e-01, 8.678529e-01, 8.680690e-01, 8.682851e-01, 8.685010e-01, 8.687168e-01, 8.689325e-01,
8.691481e-01, 8.693637e-01, 8.695791e-01, 8.697944e-01, 8.700095e-01, 8.702246e-01, 8.704396e-01, 8.706545e-01,
8.708693e-01, 8.710839e-01, 8.712984e-01, 8.715129e-01, 8.717272e-01, 8.719414e-01, 8.721556e-01, 8.723696e-01,
8.725836e-01, 8.727974e-01, 8.730111e-01, 8.732247e-01, 8.734382e-01, 8.736516e-01, 8.738649e-01, 8.740780e-01,
8.742912e-01, 8.745041e-01, 8.747170e-01, 8.749298e-01, 8.751425e-01, 8.753550e-01, 8.755675e-01, 8.757799e-01,
8.759921e-01, 8.762043e-01, 8.764163e-01, 8.766283e-01, 8.768401e-01, 8.770519e-01, 8.772635e-01, 8.774751e-01,
8.776865e-01, 8.778979e-01, 8.781091e-01, 8.783202e-01, 8.785312e-01, 8.787422e-01, 8.789530e-01, 8.791637e-01,
8.793744e-01, 8.795849e-01, 8.797953e-01, 8.800057e-01, 8.802159e-01, 8.804260e-01, 8.806360e-01, 8.808460e-01,
8.810558e-01, 8.812655e-01, 8.814751e-01, 8.816847e-01, 8.818941e-01, 8.821034e-01, 8.823127e-01, 8.825217e-01,
8.827308e-01, 8.829397e-01, 8.831486e-01, 8.833573e-01, 8.835659e-01, 8.837745e-01, 8.839829e-01, 8.841912e-01,
8.843995e-01, 8.846076e-01, 8.848156e-01, 8.850236e-01, 8.852314e-01, 8.854392e-01, 8.856469e-01, 8.858544e-01,
8.860618e-01, 8.862692e-01, 8.864765e-01, 8.866837e-01, 8.868908e-01, 8.870977e-01, 8.873046e-01, 8.875114e-01,
8.877181e-01, 8.879247e-01, 8.881311e-01, 8.883376e-01, 8.885438e-01, 8.887501e-01, 8.889562e-01, 8.891622e-01,
8.893681e-01, 8.895739e-01, 8.897797e-01, 8.899853e-01, 8.901908e-01, 8.903963e-01, 8.906016e-01, 8.908069e-01,
8.910121e-01, 8.912171e-01, 8.914221e-01, 8.916270e-01, 8.918318e-01, 8.920364e-01, 8.922410e-01, 8.924455e-01,
8.926499e-01, 8.928543e-01, 8.930585e-01, 8.932626e-01, 8.934667e-01, 8.936706e-01, 8.938744e-01, 8.940782e-01,
8.942819e-01, 8.944854e-01, 8.946889e-01, 8.948923e-01, 8.950956e-01, 8.952988e-01, 8.955019e-01, 8.957049e-01,
8.959078e-01, 8.961107e-01, 8.963134e-01, 8.965160e-01, 8.967186e-01, 8.969210e-01, 8.971235e-01, 8.973257e-01,
8.975279e-01, 8.977300e-01, 8.979320e-01, 8.981339e-01, 8.983358e-01, 8.985375e-01, 8.987392e-01, 8.989407e-01,
8.991421e-01, 8.993436e-01, 8.995448e-01, 8.997460e-01, 8.999471e-01, 9.001482e-01, 9.003491e-01, 9.005499e-01,
9.007506e-01, 9.009513e-01, 9.011519e-01, 9.013523e-01, 9.015527e-01, 9.017531e-01, 9.019532e-01, 9.021534e-01,
9.023534e-01, 9.025534e-01, 9.027532e-01, 9.029530e-01, 9.031526e-01, 9.033523e-01, 9.035518e-01, 9.037512e-01,
9.039505e-01, 9.041498e-01, 9.043489e-01, 9.045479e-01, 9.047469e-01, 9.049459e-01, 9.051446e-01, 9.053434e-01,
9.055420e-01, 9.057405e-01, 9.059390e-01, 9.061373e-01, 9.063356e-01, 9.065338e-01, 9.067319e-01, 9.069299e-01,
9.071279e-01, 9.073257e-01, 9.075235e-01, 9.077212e-01, 9.079187e-01, 9.081162e-01, 9.083136e-01, 9.085110e-01,
9.087082e-01, 9.089054e-01, 9.091024e-01, 9.092994e-01, 9.094964e-01, 9.096932e-01, 9.098899e-01, 9.100866e-01,
9.102831e-01, 9.104796e-01, 9.106760e-01, 9.108723e-01, 9.110685e-01, 9.112647e-01, 9.114607e-01, 9.116567e-01,
9.118526e-01, 9.120483e-01, 9.122441e-01, 9.124397e-01, 9.126353e-01, 9.128307e-01, 9.130261e-01, 9.132214e-01,
9.134166e-01, 9.136118e-01, 9.138068e-01, 9.140018e-01, 9.141967e-01, 9.143915e-01, 9.145862e-01, 9.147808e-01,
9.149753e-01, 9.151698e-01, 9.153642e-01, 9.155585e-01, 9.157528e-01, 9.159469e-01, 9.161409e-01, 9.163349e-01,
9.165288e-01, 9.167226e-01, 9.169164e-01, 9.171100e-01, 9.173036e-01, 9.174970e-01, 9.176905e-01, 9.178838e-01,
9.180770e-01, 9.182702e-01, 9.184632e-01, 9.186562e-01, 9.188492e-01, 9.190420e-01, 9.192348e-01, 9.194274e-01,
9.196200e-01, 9.198125e-01, 9.200049e-01, 9.201973e-01, 9.203895e-01, 9.205818e-01, 9.207739e-01, 9.209659e-01,
9.211578e-01, 9.213497e-01, 9.215415e-01, 9.217332e-01, 9.219248e-01, 9.221163e-01, 9.223078e-01, 9.224992e-01,
9.226905e-01, 9.228818e-01, 9.230729e-01, 9.232640e-01, 9.234550e-01, 9.236459e-01, 9.238367e-01, 9.240275e-01,
9.242182e-01, 9.244088e-01, 9.245993e-01, 9.247897e-01, 9.249801e-01, 9.251704e-01, 9.253606e-01, 9.255507e-01,
9.257408e-01, 9.259307e-01, 9.261206e-01, 9.263105e-01, 9.265002e-01, 9.266899e-01, 9.268795e-01, 9.270689e-01,
9.272584e-01, 9.274477e-01, 9.276370e-01, 9.278262e-01, 9.280154e-01, 9.282044e-01, 9.283934e-01, 9.285822e-01,
9.287710e-01, 9.289598e-01, 9.291484e-01, 9.293370e-01, 9.295255e-01, 9.297140e-01, 9.299023e-01, 9.300906e-01,
9.302788e-01, 9.304669e-01, 9.306549e-01, 9.308429e-01, 9.310308e-01, 9.312186e-01, 9.314064e-01, 9.315941e-01,
9.317816e-01, 9.319692e-01, 9.321566e-01, 9.323440e-01, 9.325313e-01, 9.327185e-01, 9.329057e-01, 9.330927e-01,
9.332797e-01, 9.334666e-01, 9.336535e-01, 9.338402e-01, 9.340270e-01, 9.342135e-01, 9.344001e-01, 9.345866e-01,
9.347730e-01, 9.349593e-01, 9.351455e-01, 9.353317e-01, 9.355178e-01, 9.357038e-01, 9.358898e-01, 9.360756e-01,
9.362615e-01, 9.364472e-01, 9.366328e-01, 9.368184e-01, 9.370039e-01, 9.371893e-01, 9.373747e-01, 9.375600e-01,
9.377452e-01, 9.379303e-01, 9.381154e-01, 9.383004e-01, 9.384854e-01, 9.386702e-01, 9.388550e-01, 9.390397e-01,
9.392243e-01, 9.394089e-01, 9.395934e-01, 9.397778e-01, 9.399621e-01, 9.401464e-01, 9.403306e-01, 9.405147e-01,
9.406988e-01, 9.408827e-01, 9.410667e-01, 9.412505e-01, 9.414343e-01, 9.416180e-01, 9.418016e-01, 9.419851e-01,
9.421686e-01, 9.423520e-01, 9.425353e-01, 9.427186e-01, 9.429018e-01, 9.430850e-01, 9.432680e-01, 9.434510e-01,
9.436339e-01, 9.438167e-01, 9.439995e-01, 9.441822e-01, 9.443648e-01, 9.445474e-01, 9.447299e-01, 9.449123e-01,
9.450946e-01, 9.452769e-01, 9.454591e-01, 9.456412e-01, 9.458233e-01, 9.460053e-01, 9.461872e-01, 9.463691e-01,
9.465508e-01, 9.467326e-01, 9.469142e-01, 9.470958e-01, 9.472773e-01, 9.474587e-01, 9.476401e-01, 9.478214e-01,
9.480026e-01, 9.481838e-01, 9.483649e-01, 9.485459e-01, 9.487268e-01, 9.489077e-01, 9.490886e-01, 9.492693e-01,
9.494500e-01, 9.496306e-01, 9.498111e-01, 9.499916e-01, 9.501719e-01, 9.503523e-01, 9.505326e-01, 9.507128e-01,
9.508929e-01, 9.510729e-01, 9.512529e-01, 9.514329e-01, 9.516127e-01, 9.517925e-01, 9.519722e-01, 9.521519e-01,
9.523315e-01, 9.525110e-01, 9.526904e-01, 9.528698e-01, 9.530491e-01, 9.532284e-01, 9.534075e-01, 9.535866e-01,
9.537657e-01, 9.539447e-01, 9.541236e-01, 9.543024e-01, 9.544812e-01, 9.546599e-01, 9.548386e-01, 9.550171e-01,
9.551957e-01, 9.553741e-01, 9.555525e-01, 9.557307e-01, 9.559090e-01, 9.560872e-01, 9.562653e-01, 9.564433e-01,
9.566213e-01, 9.567992e-01, 9.569771e-01, 9.571549e-01, 9.573326e-01, 9.575102e-01, 9.576878e-01, 9.578653e-01,
9.580427e-01, 9.582201e-01, 9.583974e-01, 9.585747e-01, 9.587519e-01, 9.589290e-01, 9.591061e-01, 9.592831e-01,
9.594600e-01, 9.596368e-01, 9.598137e-01, 9.599904e-01, 9.601671e-01, 9.603436e-01, 9.605201e-01, 9.606966e-01,
9.608730e-01, 9.610494e-01, 9.612256e-01, 9.614019e-01, 9.615780e-01, 9.617541e-01, 9.619301e-01, 9.621060e-01,
9.622819e-01, 9.624578e-01, 9.626336e-01, 9.628092e-01, 9.629849e-01, 9.631604e-01, 9.633359e-01, 9.635113e-01,
9.636867e-01, 9.638621e-01, 9.640373e-01, 9.642125e-01, 9.643876e-01, 9.645627e-01, 9.647377e-01, 9.649126e-01,
9.650874e-01, 9.652622e-01, 9.654370e-01, 9.656116e-01, 9.657863e-01, 9.659608e-01, 9.661353e-01, 9.663097e-01,
9.664841e-01, 9.666584e-01, 9.668326e-01, 9.670068e-01, 9.671809e-01, 9.673550e-01, 9.675289e-01, 9.677029e-01,
9.678767e-01, 9.680505e-01, 9.682242e-01, 9.683979e-01, 9.685715e-01, 9.687451e-01, 9.689186e-01, 9.690920e-01,
9.692653e-01, 9.694387e-01, 9.696119e-01, 9.697851e-01, 9.699582e-01, 9.701312e-01, 9.703043e-01, 9.704772e-01,
9.706500e-01, 9.708228e-01, 9.709955e-01, 9.711683e-01, 9.713409e-01, 9.715135e-01, 9.716859e-01, 9.718584e-01,
9.720308e-01, 9.722031e-01, 9.723753e-01, 9.725475e-01, 9.727197e-01, 9.728917e-01, 9.730637e-01, 9.732357e-01,
9.734076e-01, 9.735794e-01, 9.737512e-01, 9.739228e-01, 9.740945e-01, 9.742661e-01, 9.744377e-01, 9.746091e-01,
9.747805e-01, 9.749519e-01, 9.751231e-01, 9.752944e-01, 9.754655e-01, 9.756366e-01, 9.758077e-01, 9.759787e-01,
9.761496e-01, 9.763204e-01, 9.764913e-01, 9.766620e-01, 9.768327e-01, 9.770033e-01, 9.771739e-01, 9.773444e-01,
9.775148e-01, 9.776852e-01, 9.778556e-01, 9.780258e-01, 9.781960e-01, 9.783661e-01, 9.785362e-01, 9.787063e-01,
9.788762e-01, 9.790462e-01, 9.792160e-01, 9.793859e-01, 9.795555e-01, 9.797252e-01, 9.798949e-01, 9.800645e-01,
9.802339e-01, 9.804034e-01, 9.805728e-01, 9.807421e-01, 9.809114e-01, 9.810806e-01, 9.812497e-01, 9.814188e-01,
9.815878e-01, 9.817568e-01, 9.819257e-01, 9.820946e-01, 9.822634e-01, 9.824321e-01, 9.826008e-01, 9.827695e-01,
9.829381e-01, 9.831066e-01, 9.832750e-01, 9.834434e-01, 9.836118e-01, 9.837800e-01, 9.839482e-01, 9.841164e-01,
9.842845e-01, 9.844526e-01, 9.846206e-01, 9.847885e-01, 9.849564e-01, 9.851242e-01, 9.852920e-01, 9.854597e-01,
9.856274e-01, 9.857950e-01, 9.859625e-01, 9.861299e-01, 9.862974e-01, 9.864647e-01, 9.866320e-01, 9.867993e-01,
9.869665e-01, 9.871337e-01, 9.873008e-01, 9.874678e-01, 9.876347e-01, 9.878017e-01, 9.879685e-01, 9.881353e-01,
9.883021e-01, 9.884688e-01, 9.886354e-01, 9.888020e-01, 9.889685e-01, 9.891350e-01, 9.893014e-01, 9.894677e-01,
9.896340e-01, 9.898003e-01, 9.899665e-01, 9.901326e-01, 9.902986e-01, 9.904646e-01, 9.906306e-01, 9.907965e-01,
9.909624e-01, 9.911281e-01, 9.912939e-01, 9.914596e-01, 9.916252e-01, 9.917908e-01, 9.919563e-01, 9.921218e-01,
9.922872e-01, 9.924526e-01, 9.926178e-01, 9.927831e-01, 9.929483e-01, 9.931134e-01, 9.932785e-01, 9.934435e-01,
9.936085e-01, 9.937734e-01, 9.939383e-01, 9.941031e-01, 9.942678e-01, 9.944325e-01, 9.945971e-01, 9.947617e-01,
9.949263e-01, 9.950907e-01, 9.952552e-01, 9.954196e-01, 9.955838e-01, 9.957481e-01, 9.959123e-01, 9.960765e-01,
9.962406e-01, 9.964046e-01, 9.965686e-01, 9.967325e-01, 9.968964e-01, 9.970602e-01, 9.972240e-01, 9.973878e-01,
9.975514e-01, 9.977150e-01, 9.978786e-01, 9.980421e-01, 9.982055e-01, 9.983689e-01, 9.985323e-01, 9.986956e-01,
9.988588e-01, 9.990220e-01, 9.991851e-01, 9.993482e-01, 9.995112e-01, 9.996742e-01, 9.998372e-01, 1.000000e+00,
};
int i = (int)(d * 2047);
assert(i >= 0 && i < 2048);
return cube_root[i];
}
static inline void _ccv_rgb_to_luv(const float r, const float g, const float b, float* pl, float* pu, float* pv)
{
const float x = 0.412453f * r + 0.35758f * g + 0.180423f * b;
const float y = 0.212671f * r + 0.71516f * g + 0.072169f * b;
const float z = 0.019334f * r + 0.119193f * g + 0.950227f * b;
const float x_n = 0.312713f, y_n = 0.329016f;
const float uv_n_divisor = -2.f * x_n + 12.f * y_n + 3.f;
const float u_n = 4.f * x_n / uv_n_divisor;
const float v_n = 9.f * y_n / uv_n_divisor;
const float uv_divisor = ccv_max((x + 15.f * y + 3.f * z), FLT_EPSILON);
const float u = 4.f * x / uv_divisor;
const float v = 9.f * y / uv_divisor;
const float y_cube_root = fast_cube_root(y);
const float l_value = ccv_max(0.f, ((116.f * y_cube_root) - 16.f));
const float u_value = 13.f * l_value * (u - u_n);
const float v_value = 13.f * l_value * (v - v_n);
// L in [0, 100], U in [-134, 220], V in [-140, 122]
*pl = l_value * (255.f / 100.f);
*pu = (u_value + 134.f) * (255.f / (220.f + 134.f));
*pv = (v_value + 140.f) * (255.f / (122.f + 140.f));
}
void ccv_scd(ccv_dense_matrix_t* a, ccv_dense_matrix_t** b, int type)
{
int ch = CCV_GET_CHANNEL(a->type);
assert(ch == 1 || ch == 3);
ccv_declare_derived_signature(sig, a->sig != 0, ccv_sign_with_literal("ccv_scd"), a->sig, CCV_EOF_SIGN);
// diagonal u, v, x, y and LUV color, therefore 11 channels
ccv_dense_matrix_t* db = *b = ccv_dense_matrix_renew(*b, a->rows, a->cols, CCV_32F | 11, CCV_32F | 11, sig);
ccv_object_return_if_cached(, db);
ccv_dense_matrix_t* blur = 0;
ccv_blur(a, &blur, 0, 0.5); // do a modest blur, which suppresses noise
ccv_dense_matrix_t* dx = 0;
ccv_sobel(blur, &dx, 0, 1, 0);
ccv_dense_matrix_t* dy = 0;
ccv_sobel(blur, &dy, 0, 0, 1);
ccv_dense_matrix_t* du = 0;
ccv_sobel(blur, &du, 0, 1, 1);
ccv_dense_matrix_t* dv = 0;
ccv_sobel(blur, &dv, 0, -1, 1);
ccv_matrix_free(blur);
assert(CCV_GET_DATA_TYPE(dx->type) == CCV_GET_DATA_TYPE(dy->type));
assert(CCV_GET_DATA_TYPE(dy->type) == CCV_GET_DATA_TYPE(du->type));
assert(CCV_GET_DATA_TYPE(du->type) == CCV_GET_DATA_TYPE(dv->type));
assert(CCV_GET_CHANNEL(dx->type) == CCV_GET_CHANNEL(dy->type));
assert(CCV_GET_CHANNEL(dy->type) == CCV_GET_CHANNEL(du->type));
assert(CCV_GET_CHANNEL(du->type) == CCV_GET_CHANNEL(dv->type));
// this is a naive unoptimized implementation yet
int i, j, k;
unsigned char* a_ptr = a->data.u8;
unsigned char* dx_ptr = dx->data.u8;
unsigned char* dy_ptr = dy->data.u8;
unsigned char* du_ptr = du->data.u8;
unsigned char* dv_ptr = dv->data.u8;
float* dbp = db->data.f32;
if (ch == 1)
{
#define for_block(_for_get_d, _for_get_a) \
for (i = 0; i < a->rows; i++) \
{ \
for (j = 0; j < a->cols; j++) \
{ \
float fdx = _for_get_d(dx_ptr, j, 0), fdy = _for_get_d(dy_ptr, j, 0); \
float fdu = _for_get_d(du_ptr, j, 0), fdv = _for_get_d(dv_ptr, j, 0); \
float adx = fabsf(fdx), ady = fabsf(fdy); \
float adu = fabsf(fdu), adv = fabsf(fdv); \
dbp[0] = fdx, dbp[1] = fdy; \
dbp[2] = fdu, dbp[3] = fdv; \
dbp[4] = adx, dbp[5] = ady; \
dbp[6] = adu, dbp[7] = adv; \
dbp[8] = _for_get_a(a_ptr, j, 0) / 255.0; \
dbp[9] = dbp[10] = 0; \
dbp += 11; \
} \
a_ptr += a->step; \
dx_ptr += dx->step; \
dy_ptr += dy->step; \
du_ptr += du->step; \
dv_ptr += dv->step; \
}
ccv_matrix_getter(dx->type, ccv_matrix_getter_a, a->type, for_block);
#undef for_block
} else {
#define for_block(_for_get_d, _for_get_a) \
for (i = 0; i < a->rows; i++) \
{ \
for (j = 0; j < a->cols; j++) \
{ \
float fdx = _for_get_d(dx_ptr, j * ch, 0), fdy = _for_get_d(dy_ptr, j * ch, 0); \
float fdu = _for_get_d(du_ptr, j * ch, 0), fdv = _for_get_d(dv_ptr, j * ch, 0); \
float adx = fabsf(fdx), ady = fabsf(fdy); \
float adu = fabsf(fdu), adv = fabsf(fdv); \
/* select the strongest ones from all the channels */ \
for (k = 1; k < ch; k++) \
{ \
if (fabsf((float)_for_get_d(dx_ptr, j * ch + k, 0)) > adx) \
{ \
fdx = _for_get_d(dx_ptr, j * ch + k, 0); \
adx = fabsf(fdx); \
} \
if (fabsf((float)_for_get_d(dy_ptr, j * ch + k, 0)) > ady) \
{ \
fdy = _for_get_d(dy_ptr, j * ch + k, 0); \
ady = fabsf(fdy); \
} \
if (fabsf((float)_for_get_d(du_ptr, j * ch + k, 0)) > adu) \
{ \
fdu = _for_get_d(du_ptr, j * ch + k, 0); \
adu = fabsf(fdu); \
} \
if (fabsf((float)_for_get_d(dv_ptr, j * ch + k, 0)) > adv) \
{ \
fdv = _for_get_d(dv_ptr, j * ch + k, 0); \
adv = fabsf(fdv); \
} \
} \
dbp[0] = fdx, dbp[1] = fdy; \
dbp[2] = fdu, dbp[3] = fdv; \
dbp[4] = adx, dbp[5] = ady; \
dbp[6] = adu, dbp[7] = adv; \
_ccv_rgb_to_luv(_for_get_a(a_ptr, j * ch, 0) / 255.0, \
_for_get_a(a_ptr, j * ch + 1, 0) / 255.0, \
_for_get_a(a_ptr, j * ch + 2, 0) / 255.0, \
dbp + 8, dbp + 9, dbp + 10); \
dbp += 11; \
} \
a_ptr += a->step; \
dx_ptr += dx->step; \
dy_ptr += dy->step; \
du_ptr += du->step; \
dv_ptr += dv->step; \
}
ccv_matrix_getter(dx->type, ccv_matrix_getter_a, a->type, for_block);
#undef for_block
}
ccv_matrix_free(dx);
ccv_matrix_free(dy);
ccv_matrix_free(du);
ccv_matrix_free(dv);
}
#if defined(HAVE_SSE2)
static inline void _ccv_scd_run_feature_at_sse2(float* at, int cols, ccv_scd_stump_feature_t* feature, __m128 surf[8])
{
int i;
// extract feature
for (i = 0; i < 4; i++)
{
__m128 d0 = _mm_loadu_ps(at + (cols * feature->sy[i] + feature->sx[i]) * CCV_SCD_CHANNEL);
__m128 d1 = _mm_loadu_ps(at + 4 + (cols * feature->sy[i] + feature->sx[i]) * CCV_SCD_CHANNEL);
__m128 du0 = _mm_loadu_ps(at + (cols * feature->dy[i] + feature->sx[i]) * CCV_SCD_CHANNEL);
__m128 du1 = _mm_loadu_ps(at + 4 + (cols * feature->dy[i] + feature->sx[i]) * CCV_SCD_CHANNEL);
__m128 dv0 = _mm_loadu_ps(at + (cols * feature->sy[i] + feature->dx[i]) * CCV_SCD_CHANNEL);
__m128 dv1 = _mm_loadu_ps(at + 4 + (cols * feature->sy[i] + feature->dx[i]) * CCV_SCD_CHANNEL);
__m128 duv0 = _mm_loadu_ps(at + (cols * feature->dy[i] + feature->dx[i]) * CCV_SCD_CHANNEL);
__m128 duv1 = _mm_loadu_ps(at + 4 + (cols * feature->dy[i] + feature->dx[i]) * CCV_SCD_CHANNEL);
surf[i * 2] = _mm_sub_ps(_mm_add_ps(duv0, d0), _mm_add_ps(du0, dv0));
surf[i * 2 + 1] = _mm_sub_ps(_mm_add_ps(duv1, d1), _mm_add_ps(du1, dv1));
}
// L2Hys normalization
__m128 v0 = _mm_add_ps(_mm_mul_ps(surf[0], surf[0]), _mm_mul_ps(surf[1], surf[1]));
__m128 v1 = _mm_add_ps(_mm_mul_ps(surf[2], surf[2]), _mm_mul_ps(surf[3], surf[3]));
__m128 v2 = _mm_add_ps(_mm_mul_ps(surf[4], surf[4]), _mm_mul_ps(surf[5], surf[5]));
__m128 v3 = _mm_add_ps(_mm_mul_ps(surf[6], surf[6]), _mm_mul_ps(surf[7], surf[7]));
v0 = _mm_add_ps(v0, v1);
v2 = _mm_add_ps(v2, v3);
union {
float f[4];
__m128 p;
} vx;
vx.p = _mm_add_ps(v0, v2);
v0 = _mm_set1_ps(1.0 / (sqrtf(vx.f[0] + vx.f[1] + vx.f[2] + vx.f[3]) + 1e-6));
static float thlf = -2.0 / 5.65685424949; // -sqrtf(32)
static float thuf = 2.0 / 5.65685424949; // sqrtf(32)
const __m128 thl = _mm_set1_ps(thlf);
const __m128 thu = _mm_set1_ps(thuf);
for (i = 0; i < 8; i++)
{
surf[i] = _mm_mul_ps(surf[i], v0);
surf[i] = _mm_min_ps(surf[i], thu);
surf[i] = _mm_max_ps(surf[i], thl);
}
__m128 u0 = _mm_add_ps(_mm_mul_ps(surf[0], surf[0]), _mm_mul_ps(surf[1], surf[1]));
__m128 u1 = _mm_add_ps(_mm_mul_ps(surf[2], surf[2]), _mm_mul_ps(surf[3], surf[3]));
__m128 u2 = _mm_add_ps(_mm_mul_ps(surf[4], surf[4]), _mm_mul_ps(surf[5], surf[5]));
__m128 u3 = _mm_add_ps(_mm_mul_ps(surf[6], surf[6]), _mm_mul_ps(surf[7], surf[7]));
u0 = _mm_add_ps(u0, u1);
u2 = _mm_add_ps(u2, u3);
union {
float f[4];
__m128 p;
} ux;
ux.p = _mm_add_ps(u0, u2);
u0 = _mm_set1_ps(1.0 / (sqrtf(ux.f[0] + ux.f[1] + ux.f[2] + ux.f[3]) + 1e-6));
for (i = 0; i < 8; i++)
surf[i] = _mm_mul_ps(surf[i], u0);
}
#else
static inline void _ccv_scd_run_feature_at(float* at, int cols, ccv_scd_stump_feature_t* feature, float surf[32])
{
int i, j;
// extract feature
for (i = 0; i < 4; i++)
{
float* d = at + (cols * feature->sy[i] + feature->sx[i]) * CCV_SCD_CHANNEL;
float* du = at + (cols * feature->dy[i] + feature->sx[i]) * CCV_SCD_CHANNEL;
float* dv = at + (cols * feature->sy[i] + feature->dx[i]) * CCV_SCD_CHANNEL;
float* duv = at + (cols * feature->dy[i] + feature->dx[i]) * CCV_SCD_CHANNEL;
for (j = 0; j < 8; j++)
surf[i * 8 + j] = duv[j] - du[j] + d[j] - dv[j];
}
// L2Hys normalization
float v = 0;
for (i = 0; i < 32; i++)
v += surf[i] * surf[i];
v = 1.0 / (sqrtf(v) + 1e-6);
static float theta = 2.0 / 5.65685424949; // sqrtf(32)
float u = 0;
for (i = 0; i < 32; i++)
{
surf[i] = surf[i] * v;
surf[i] = ccv_clamp(surf[i], -theta, theta);
u += surf[i] * surf[i];
}
u = 1.0 / (sqrtf(u) + 1e-6);
for (i = 0; i < 32; i++)
surf[i] = surf[i] * u;
}
#endif
#ifdef HAVE_GSL
static ccv_array_t* _ccv_scd_collect_negatives(gsl_rng* rng, ccv_size_t size, ccv_array_t* hard_mine, int total, int grayscale)
{
ccv_array_t* negatives = ccv_array_new(ccv_compute_dense_matrix_size(size.height, size.width, CCV_8U | (grayscale ? CCV_C1 : CCV_C3)), total, 0);
int i, j, k;
for (i = 0; i < total;)
{
FLUSH(CCV_CLI_INFO, " - collect negatives %d%% (%d / %d)", (i + 1) * 100 / total, i + 1, total);
double ratio = (double)(total - i) / hard_mine->rnum;
for (j = 0; j < hard_mine->rnum && i < total; j++)
{
ccv_file_info_t* file_info = (ccv_file_info_t*)ccv_array_get(hard_mine, j);
ccv_dense_matrix_t* image = 0;
ccv_read(file_info->filename, &image, CCV_IO_ANY_FILE | (grayscale ? CCV_IO_GRAY : CCV_IO_RGB_COLOR));
if (image == 0)
{
PRINT(CCV_CLI_ERROR, "\n - %s: cannot be open, possibly corrupted\n", file_info->filename);
continue;
}
double max_scale_ratio = ccv_min((double)image->rows / size.height, (double)image->cols / size.width);
if (max_scale_ratio <= 0.5) // too small to be interesting
continue;
for (k = 0; k < ratio; k++)
if (k < (int)ratio || gsl_rng_uniform(rng) <= ccv_max(0.1, ratio - (int)ratio))
{
FLUSH(CCV_CLI_INFO, " - collect negatives %d%% (%d / %d)", (i + 1) * 100 / total, i + 1, total);
ccv_rect_t rect;
double scale_ratio = gsl_rng_uniform(rng) * (max_scale_ratio - 0.5) + 0.5;
rect.width = ccv_min(image->cols, (int)(size.width * scale_ratio + 0.5));
rect.height = ccv_min(image->rows, (int)(size.height * scale_ratio + 0.5));
rect.x = gsl_rng_uniform_int(rng, ccv_max(image->cols - rect.width + 1, 1));
rect.y = gsl_rng_uniform_int(rng, ccv_max(image->rows - rect.height + 1, 1));
ccv_dense_matrix_t* sliced = 0;
ccv_slice(image, (ccv_matrix_t**)&sliced, 0, rect.y, rect.x, rect.height, rect.width);
ccv_dense_matrix_t* b = 0;
if (size.width > rect.width)
ccv_resample(sliced, &b, 0, size.height, size.width, CCV_INTER_CUBIC);
else
ccv_resample(sliced, &b, 0, size.height, size.width, CCV_INTER_AREA);
ccv_matrix_free(sliced);
b->sig = 0;
// this leveraged the fact that because I know the ccv_dense_matrix_t is continuous in memory
ccv_array_push(negatives, b);
ccv_matrix_free(b);
++i;
if (i >= total)
break;
}
ccv_matrix_free(image);
}
}
PRINT(CCV_CLI_INFO, "\n");
ccv_make_array_immutable(negatives);
return negatives;
}
static ccv_array_t*_ccv_scd_collect_positives(ccv_size_t size, ccv_array_t* posfiles, int grayscale)
{
ccv_array_t* positives = ccv_array_new(ccv_compute_dense_matrix_size(size.height, size.width, CCV_8U | (grayscale ? CCV_C1 : CCV_C3)), posfiles->rnum, 0);
int i;
for (i = 0; i < posfiles->rnum; i++)
{
FLUSH(CCV_CLI_INFO, " - collect positives %d%% (%d / %d)", (i + 1) * 100 / posfiles->rnum, i + 1, posfiles->rnum);
ccv_file_info_t* file_info = (ccv_file_info_t*)ccv_array_get(posfiles, i);
ccv_dense_matrix_t* a = 0;
ccv_read(file_info->filename, &a, CCV_IO_ANY_FILE | (grayscale ? CCV_IO_GRAY : CCV_IO_RGB_COLOR));
a->sig = 0;
ccv_array_push(positives, a);
ccv_matrix_free(a);
}
PRINT(CCV_CLI_INFO, "\n");
ccv_make_array_immutable(positives);
return positives;
}
static ccv_array_t* _ccv_scd_stump_features(ccv_size_t base, int range_through, int step_through, ccv_size_t size)
{
ccv_array_t* features = ccv_array_new(sizeof(ccv_scd_stump_feature_t), 64, 0);
int x, y, w, h;
for (w = base.width; w <= size.width; w += range_through)
if (w % 4 == 0) // only allow 4:1
{
h = w / 4;
for (x = 0; x <= size.width - w; x += step_through)
for (y = 0; y <= size.height - h; y += step_through)
{
// 4x1 feature
ccv_scd_stump_feature_t feature;
feature.sx[0] = x;
feature.dx[0] = x + (w / 4);
feature.sx[1] = x + (w / 4);
feature.dx[1] = x + 2 * (w / 4);
feature.sx[2] = x + 2 * (w / 4);
feature.dx[2] = x + 3 * (w / 4);
feature.sx[3] = x + 3 * (w / 4);
feature.dx[3] = x + w;
feature.sy[0] = feature.sy[1] = feature.sy[2] = feature.sy[3] = y;
feature.dy[0] = feature.dy[1] = feature.dy[2] = feature.dy[3] = y + h;
ccv_array_push(features, &feature);
}
}
for (h = base.height; h <= size.height; h += range_through)
if (h % 4 == 0) // only allow 1:4
{
w = h / 4;
for (x = 0; x <= size.width - w; x += step_through)
for (y = 0; y <= size.height - h; y += step_through)
{
// 1x4 feature
ccv_scd_stump_feature_t feature;
feature.sx[0] = feature.sx[1] = feature.sx[2] = feature.sx[3] = x;
feature.dx[0] = feature.dx[1] = feature.dx[2] = feature.dx[3] = x + w;
feature.sy[0] = y;
feature.dy[0] = y + (h / 4);
feature.sy[1] = y + (h / 4);
feature.dy[1] = y + 2 * (h / 4);
feature.sy[2] = y + 2 * (h / 4);
feature.dy[2] = y + 3 * (h / 4);
feature.sy[3] = y + 3 * (h / 4);
feature.dy[3] = y + h;
ccv_array_push(features, &feature);
}
}
for (w = base.width; w <= size.width; w += range_through)
for (h = base.height; h <= size.height; h += range_through)
for (x = 0; x <= size.width - w; x += step_through)
for (y = 0; y <= size.height - h; y += step_through)
if (w % 2 == 0 && h % 2 == 0 &&
(w == h || w == h * 2 || w * 2 == h || w * 2 == h * 3 || w * 3 == h * 2)) // allow 1:1, 1:2, 2:1, 2:3, 3:2
{
// 2x2 feature
ccv_scd_stump_feature_t feature;
feature.sx[0] = feature.sx[1] = x;
feature.dx[0] = feature.dx[1] = x + (w / 2);
feature.sy[0] = feature.sy[2] = y;
feature.dy[0] = feature.dy[2] = y + (h / 2);
feature.sx[2] = feature.sx[3] = x + (w / 2);
feature.dx[2] = feature.dx[3] = x + w;
feature.sy[1] = feature.sy[3] = y + (h / 2);
feature.dy[1] = feature.dy[3] = y + h;
ccv_array_push(features, &feature);
}
return features;
}
typedef struct {
double value;
int index;
} ccv_scd_value_index_t;
#define more_than(s1, s2, aux) ((s1).value >= (s2).value)
static CCV_IMPLEMENT_QSORT(_ccv_scd_value_index_sortby_value, ccv_scd_value_index_t, more_than)
#undef more_than
#define less_than(s1, s2, aux) ((s1).index < (s2).index)
static CCV_IMPLEMENT_QSORT(_ccv_scd_value_index_sortby_index, ccv_scd_value_index_t, less_than)
#undef less_than
static float* _ccv_scd_get_surf_at(float* fv, int feature_no, int example_no, int positive_count, int negative_count)
{
return fv + ((off_t)example_no + feature_no * (positive_count + negative_count)) * 32;
}
static void _ccv_scd_precompute_feature_vectors(const ccv_array_t* features, const ccv_array_t* positives, const ccv_array_t* negatives, float* fv)
{
parallel_for(i, positives->rnum) {
int j;
if ((i + 1) % 4031 == 1)
FLUSH(CCV_CLI_INFO, " - precompute feature vectors of example %d / %d over %d features", (int)(i + 1), positives->rnum + negatives->rnum, features->rnum);
ccv_dense_matrix_t* a = (ccv_dense_matrix_t*)ccv_array_get(positives, i);
a->data.u8 = (unsigned char*)(a + 1);
ccv_dense_matrix_t* b = 0;
ccv_scd(a, &b, 0);
ccv_dense_matrix_t* sat = 0;
ccv_sat(b, &sat, 0, CCV_PADDING_ZERO);
ccv_matrix_free(b);
for (j = 0; j < features->rnum; j++)
{
ccv_scd_stump_feature_t* feature = (ccv_scd_stump_feature_t*)ccv_array_get(features, j);
// save to fv
#if defined(HAVE_SSE2)
_ccv_scd_run_feature_at_sse2(sat->data.f32, sat->cols, feature, (__m128*)_ccv_scd_get_surf_at(fv, j, i, positives->rnum, negatives->rnum));
#else
_ccv_scd_run_feature_at(sat->data.f32, sat->cols, feature, _ccv_scd_get_surf_at(fv, j, i, positives->rnum, negatives->rnum));
#endif
}
ccv_matrix_free(sat);
} parallel_endfor
parallel_for(i, negatives->rnum) {
int j;
if ((i + 1) % 731 == 1 || (i + 1) == negatives->rnum)
FLUSH(CCV_CLI_INFO, " - precompute feature vectors of example %d / %d over %d features", (int)(i + positives->rnum + 1), positives->rnum + negatives->rnum, features->rnum);
ccv_dense_matrix_t* a = (ccv_dense_matrix_t*)ccv_array_get(negatives, i);
a->data.u8 = (unsigned char*)(a + 1);
ccv_dense_matrix_t* b = 0;
ccv_scd(a, &b, 0);
ccv_dense_matrix_t* sat = 0;
ccv_sat(b, &sat, 0, CCV_PADDING_ZERO);
ccv_matrix_free(b);
for (j = 0; j < features->rnum; j++)
{
ccv_scd_stump_feature_t* feature = (ccv_scd_stump_feature_t*)ccv_array_get(features, j);
// save to fv
#if defined(HAVE_SSE2)
_ccv_scd_run_feature_at_sse2(sat->data.f32, sat->cols, feature, (__m128*)_ccv_scd_get_surf_at(fv, j, i + positives->rnum, positives->rnum, negatives->rnum));
#else
_ccv_scd_run_feature_at(sat->data.f32, sat->cols, feature, _ccv_scd_get_surf_at(fv, j, i + positives->rnum, positives->rnum, negatives->rnum));
#endif
}
ccv_matrix_free(sat);
} parallel_endfor
}
typedef struct {
int feature_no;
double C;
ccv_scd_value_index_t* pwidx;
ccv_scd_value_index_t* nwidx;
int positive_count;
int negative_count;
int active_positive_count;
int active_negative_count;
float* fv;
} ccv_loss_minimize_context_t;
static int _ccv_scd_stump_feature_gentle_adaboost_loss(const ccv_dense_matrix_t* x, double* f, ccv_dense_matrix_t* df, void* data)
{
ccv_loss_minimize_context_t* context = (ccv_loss_minimize_context_t*)data;
int i, j;
float loss = 0;
float* d = df->data.f32;
for (i = 0; i < 32; i++)
{
loss += context->C * fabs(x->data.f32[i]);
d[i] = x->data.f32[i] > 0 ? context->C : -context->C;
}
d[32] = 0;
float* surf = _ccv_scd_get_surf_at(context->fv, context->feature_no, 0, context->positive_count, context->negative_count);
for (i = 0; i < context->active_positive_count; i++)
{
float* cur_surf = surf + (off_t)(context->pwidx[i].index) * 32;
float v = x->data.f32[32];
for (j = 0; j < 32; j++)
v += cur_surf[j] * x->data.f32[j];
v = expf(v);
float tanh = (v - 1) / (v + 1);
loss += context->pwidx[i].value * (1.0 - tanh) * (1.0 - tanh);
float dv = -8.0 * context->pwidx[i].value * v / ((1.0 + v) * (1.0 + v) * (1.0 + v));
for (j = 0; j < 32; j++)
d[j] += dv * cur_surf[j];
d[32] += dv;
}
for (i = 0; i < context->active_negative_count; i++)
{
float* cur_surf = surf + (off_t)(context->nwidx[i].index + context->positive_count) * 32;
float v = x->data.f32[32];
for (j = 0; j < 32; j++)
v += cur_surf[j] * x->data.f32[j];
v = expf(v);
float tanh = (v - 1) / (v + 1);
loss += context->nwidx[i].value * (-1.0 - tanh) * (-1.0 - tanh);
float dv = 8.0 * context->nwidx[i].value * v * v / ((1.0 + v) * (1.0 + v) * (1.0 + v));
for (j = 0; j < 32; j++)
d[j] += dv * cur_surf[j];
d[32] += dv;
}
f[0] = loss;
return 0;
}
static int _ccv_scd_weight_trimming(ccv_scd_value_index_t* idx, int count, double weight_trimming)
{
int active_count = count;
int i;
double w = 0;
for (i = 0; i < count; i++)
{
w += idx[i].value;
if (w >= weight_trimming)
{
active_count = i + 1;
break;
}
}
assert(active_count > 0);
for (i = active_count; i < count; i++)
if (idx[i - 1].value == idx[i].value) // for exactly the same weight, we skip
active_count = i + 1;
else
break;
return active_count;
}
static void _ccv_scd_stump_feature_supervised_train(gsl_rng* rng, ccv_array_t* features, int positive_count, int negative_count, double* pw, double* nw, float* fv, double C, double weight_trimming)
{
int i;
ccv_scd_value_index_t* pwidx = (ccv_scd_value_index_t*)ccmalloc(sizeof(ccv_scd_value_index_t) * positive_count);
ccv_scd_value_index_t* nwidx = (ccv_scd_value_index_t*)ccmalloc(sizeof(ccv_scd_value_index_t) * negative_count);
for (i = 0; i < positive_count; i++)
pwidx[i].value = pw[i], pwidx[i].index = i;
for (i = 0; i < negative_count; i++)
nwidx[i].value = nw[i], nwidx[i].index = i;
_ccv_scd_value_index_sortby_value(pwidx, positive_count, 0);
_ccv_scd_value_index_sortby_value(nwidx, negative_count, 0);
int active_positive_count = _ccv_scd_weight_trimming(pwidx, positive_count, weight_trimming * 0.5); // the sum of positive weights is 0.5
int active_negative_count = _ccv_scd_weight_trimming(nwidx, negative_count, weight_trimming * 0.5); // the sum of negative weights is 0.5
_ccv_scd_value_index_sortby_index(pwidx, active_positive_count, 0);
_ccv_scd_value_index_sortby_index(nwidx, active_negative_count, 0);
parallel_for(i, features->rnum) {
if ((i + 1) % 31 == 1 || (i + 1) == features->rnum)
FLUSH(CCV_CLI_INFO, " - supervised train feature %d / %d with logistic regression, active set {%d, %d}", (int)(i + 1), features->rnum, active_positive_count, active_negative_count);
ccv_scd_stump_feature_t* feature = (ccv_scd_stump_feature_t*)ccv_array_get(features, i);
ccv_loss_minimize_context_t context = {
.feature_no = i,
.C = C,
.positive_count = positive_count,
.negative_count = negative_count,
.active_positive_count = active_positive_count,
.active_negative_count = active_negative_count,
.pwidx = pwidx,
.nwidx = nwidx,
.fv = fv,
};
ccv_dense_matrix_t* x = ccv_dense_matrix_new(1, 33, CCV_32F | CCV_C1, 0, 0);
int j;
for (j = 0; j < 33; j++)
x->data.f32[j] = gsl_rng_uniform_pos(rng) * 2 - 1.0;
ccv_minimize(x, 10, 1.0, _ccv_scd_stump_feature_gentle_adaboost_loss, ccv_minimize_default_params, &context);
for (j = 0; j < 32; j++)
feature->w[j] = x->data.f32[j];
feature->bias = x->data.f32[32];
ccv_matrix_free(x);
} parallel_endfor
ccfree(pwidx);
ccfree(nwidx);
}
static double _ccv_scd_auc(double* s, int posnum, int negnum)
{
ccv_scd_value_index_t* sidx = (ccv_scd_value_index_t*)ccmalloc(sizeof(ccv_scd_value_index_t) * (posnum + negnum));
int i;
for (i = 0; i < posnum + negnum; i++)
sidx[i].value = s[i], sidx[i].index = i;
_ccv_scd_value_index_sortby_value(sidx, posnum + negnum, 0);
int fp = 0, tp = 0, fp_prev = 0, tp_prev = 0;
double a = 0;
double f_prev = -DBL_MAX;
for (i = 0; i < posnum + negnum; i++)
{
if (sidx[i].value != f_prev)
{
a += (double)(fp - fp_prev) * (tp + tp_prev) * 0.5;
f_prev = sidx[i].value;
fp_prev = fp;
tp_prev = tp;
}
if (sidx[i].index < posnum)
++tp;
else
++fp;
}
ccfree(sidx);
a += (double)(negnum - fp_prev) * (posnum + tp_prev) * 0.5;
return a / ((double)posnum * negnum);
}
static int _ccv_scd_find_match_feature(ccv_scd_stump_feature_t* value, ccv_array_t* features)
{
int i;
for (i = 0; i < features->rnum; i++)
{
ccv_scd_stump_feature_t* feature = (ccv_scd_stump_feature_t*)ccv_array_get(features, i);
if (feature->sx[0] == value->sx[0] && feature->sy[0] == value->sy[0] &&
feature->dx[0] == value->dx[0] && feature->dy[0] == value->dy[0] &&
feature->sx[1] == value->sx[1] && feature->sy[1] == value->sy[1] &&
feature->dx[1] == value->dx[1] && feature->dy[1] == value->dy[1] &&
feature->sx[2] == value->sx[2] && feature->sy[2] == value->sy[2] &&
feature->dx[2] == value->dx[2] && feature->dy[2] == value->dy[2] &&
feature->sx[3] == value->sx[3] && feature->sy[3] == value->sy[3] &&
feature->dx[3] == value->dx[3] && feature->dy[3] == value->dy[3])
return i;
}
return -1;
}
static int _ccv_scd_best_feature_gentle_adaboost(double* s, ccv_array_t* features, double* pw, double* nw, int positive_count, int negative_count, float* fv)
{
int i;
double* error_rate = (double*)cccalloc(features->rnum, sizeof(double));
assert(positive_count + negative_count > 0);
parallel_for(i, features->rnum) {
int j, k;
if ((i + 1) % 331 == 1 || (i + 1) == features->rnum)
FLUSH(CCV_CLI_INFO, " - go through %d / %d (%.1f%%) for adaboost", (int)(i + 1), features->rnum, (float)(i + 1) * 100 / features->rnum);
ccv_scd_stump_feature_t* feature = (ccv_scd_stump_feature_t*)ccv_array_get(features, i);
for (j = 0; j < positive_count; j++)
{
float* surf = _ccv_scd_get_surf_at(fv, i, j, positive_count, negative_count);
float v = feature->bias;
for (k = 0; k < 32; k++)
v += surf[k] * feature->w[k];
v = expf(v);
v = (v - 1) / (v + 1); // probability
error_rate[i] += pw[j] * (1 - v) * (1 - v);
}
for (j = 0; j < negative_count; j++)
{
float* surf = _ccv_scd_get_surf_at(fv, i, j + positive_count, positive_count, negative_count);
float v = feature->bias;
for (k = 0; k < 32; k++)
v += surf[k] * feature->w[k];
v = expf(v);
v = (v - 1) / (v + 1); // probability
error_rate[i] += nw[j] * (-1 - v) * (-1 - v);
}
} parallel_endfor
double min_error_rate = error_rate[0];
int j = 0;
for (i = 1; i < features->rnum; i++)
if (error_rate[i] < min_error_rate)
{
min_error_rate = error_rate[i];
j = i;
}
ccfree(error_rate);
return j;
}
static float _ccv_scd_threshold_at_hit_rate(double* s, int posnum, int negnum, float hit_rate, float* tp_out, float* fp_out)
{
ccv_scd_value_index_t* psidx = (ccv_scd_value_index_t*)ccmalloc(sizeof(ccv_scd_value_index_t) * posnum);
int i;
for (i = 0; i < posnum; i++)
psidx[i].value = s[i], psidx[i].index = i;
_ccv_scd_value_index_sortby_value(psidx, posnum, 0);
float threshold = psidx[(int)((posnum - 0.5) * hit_rate - 0.5)].value - 1e-6;
ccfree(psidx);
int tp = 0;
for (i = 0; i < posnum; i++)
if (s[i] > threshold)
++tp;
int fp = 0;
for (i = 0; i < negnum; i++)
if (s[i + posnum] > threshold)
++fp;
if (tp_out)
*tp_out = (float)tp / posnum;
if (fp_out)
*fp_out = (float)fp / negnum;
return threshold;
}
static int _ccv_scd_classifier_cascade_pass(ccv_scd_classifier_cascade_t* cascade, ccv_dense_matrix_t* a)
{
#if defined(HAVE_SSE2)
__m128 surf[8];
#else
float surf[32];
#endif
ccv_dense_matrix_t* b = 0;
ccv_scd(a, &b, 0);
ccv_dense_matrix_t* sat = 0;
ccv_sat(b, &sat, 0, CCV_PADDING_ZERO);
ccv_matrix_free(b);
int pass = 1;
int i, j;
for (i = 0; i < cascade->count; i++)
{
ccv_scd_stump_classifier_t* classifier = cascade->classifiers + i;
float v = 0;
for (j = 0; j < classifier->count; j++)
{
ccv_scd_stump_feature_t* feature = classifier->features + j;
#if defined(HAVE_SSE2)
_ccv_scd_run_feature_at_sse2(sat->data.f32, sat->cols, feature, surf);
__m128 u0 = _mm_add_ps(_mm_mul_ps(surf[0], _mm_loadu_ps(feature->w)), _mm_mul_ps(surf[1], _mm_loadu_ps(feature->w + 4)));
__m128 u1 = _mm_add_ps(_mm_mul_ps(surf[2], _mm_loadu_ps(feature->w + 8)), _mm_mul_ps(surf[3], _mm_loadu_ps(feature->w + 12)));
__m128 u2 = _mm_add_ps(_mm_mul_ps(surf[4], _mm_loadu_ps(feature->w + 16)), _mm_mul_ps(surf[5], _mm_loadu_ps(feature->w + 20)));
__m128 u3 = _mm_add_ps(_mm_mul_ps(surf[6], _mm_loadu_ps(feature->w + 24)), _mm_mul_ps(surf[7], _mm_loadu_ps(feature->w + 28)));
u0 = _mm_add_ps(u0, u1);
u2 = _mm_add_ps(u2, u3);
union {
float f[4];
__m128 p;
} ux;
ux.p = _mm_add_ps(u0, u2);
float u = expf(feature->bias + ux.f[0] + ux.f[1] + ux.f[2] + ux.f[3]);
#else
_ccv_scd_run_feature_at(sat->data.f32, sat->cols, feature, surf);
float u = feature->bias;
int k;
for (k = 0; k < 32; k++)
u += surf[k] * feature->w[k];
u = expf(u);
#endif
v += (u - 1) / (u + 1);
}
if (v <= classifier->threshold)
{
pass = 0;
break;
}
}
ccv_matrix_free(sat);
return pass;
}
static ccv_array_t* _ccv_scd_hard_mining(gsl_rng* rng, ccv_scd_classifier_cascade_t* cascade, ccv_array_t* hard_mine, ccv_array_t* negatives, int negative_count, int grayscale, int even_dist)
{
ccv_array_t* hard_negatives = ccv_array_new(ccv_compute_dense_matrix_size(cascade->size.height, cascade->size.width, CCV_8U | (grayscale ? CCV_C1 : CCV_C3)), negative_count, 0);
int i, j, t;
for (i = 0; i < negatives->rnum; i++)
{
ccv_dense_matrix_t* a = (ccv_dense_matrix_t*)ccv_array_get(negatives, i);
a->data.u8 = (unsigned char*)(a + 1);
if (_ccv_scd_classifier_cascade_pass(cascade, a))
ccv_array_push(hard_negatives, a);
}
int n_per_mine = ccv_max((negative_count - hard_negatives->rnum) / hard_mine->rnum, 10);
// the hard mining comes in following fashion:
// 1). original, with n_per_mine set;
// 2). horizontal flip, with n_per_mine set;
// 3). vertical flip, with n_per_mine set;
// 4). 180 rotation, with n_per_mine set;
// 5~8). repeat above, but with no n_per_mine set;
// after above, if we still cannot collect enough, so be it.
for (t = (even_dist ? 0 : 4); t < 8 /* exhausted all variations */ && hard_negatives->rnum < negative_count; t++)
{
for (i = 0; i < hard_mine->rnum; i++)
{
FLUSH(CCV_CLI_INFO, " - hard mine negatives %d%% with %d-th permutation", 100 * hard_negatives->rnum / negative_count, t + 1);
ccv_file_info_t* file_info = (ccv_file_info_t*)ccv_array_get(hard_mine, i);
ccv_dense_matrix_t* image = 0;
ccv_read(file_info->filename, &image, CCV_IO_ANY_FILE | (grayscale ? CCV_IO_GRAY : CCV_IO_RGB_COLOR));
if (image == 0)
{
PRINT(CCV_CLI_ERROR, "\n - %s: cannot be open, possibly corrupted\n", file_info->filename);
continue;
}
if (t % 2 != 0)
ccv_flip(image, 0, 0, CCV_FLIP_X);
if (t % 4 >= 2)
ccv_flip(image, 0, 0, CCV_FLIP_Y);
if (t >= 4)
n_per_mine = negative_count; // no hard limit on n_per_mine anymore for the last pass
ccv_scd_param_t params = {
.interval = 3,
.min_neighbors = 0,
.step_through = 4,
.size = cascade->size,
};
ccv_array_t* objects = ccv_scd_detect_objects(image, &cascade, 1, params);
if (objects->rnum > 0)
{
gsl_ran_shuffle(rng, objects->data, objects->rnum, objects->rsize);
for (j = 0; j < ccv_min(objects->rnum, n_per_mine); j++)
{
ccv_rect_t* rect = (ccv_rect_t*)ccv_array_get(objects, j);
if (rect->x < 0 || rect->y < 0 || rect->x + rect->width > image->cols || rect->y + rect->height > image->rows)
continue;
ccv_dense_matrix_t* sliced = 0;
ccv_slice(image, (ccv_matrix_t**)&sliced, 0, rect->y, rect->x, rect->height, rect->width);
ccv_dense_matrix_t* resized = 0;
assert(sliced->rows >= cascade->size.height && sliced->cols >= cascade->size.width);
if (sliced->rows > cascade->size.height || sliced->cols > cascade->size.width)
{
ccv_resample(sliced, &resized, 0, cascade->size.height, cascade->size.width, CCV_INTER_CUBIC);
ccv_matrix_free(sliced);
} else {
resized = sliced;
}
if (_ccv_scd_classifier_cascade_pass(cascade, resized))
ccv_array_push(hard_negatives, resized);
ccv_matrix_free(resized);
if (hard_negatives->rnum >= negative_count)
break;
}
}
ccv_matrix_free(image);
if (hard_negatives->rnum >= negative_count)
break;
}
}
FLUSH(CCV_CLI_INFO, " - hard mine negatives : %d\n", hard_negatives->rnum);
ccv_make_array_immutable(hard_negatives);
return hard_negatives;
}
typedef struct {
ccv_function_state_reserve_field;
int t, k;
uint64_t array_signature;
ccv_array_t* features;
ccv_array_t* positives;
ccv_array_t* negatives;
double* s;
double* pw;
double* nw;
float* fv; // feature vector for examples * feature
double auc_prev;
double accu_true_positive_rate;
double accu_false_positive_rate;
ccv_scd_classifier_cascade_t* cascade;
ccv_scd_train_param_t params;
} ccv_scd_classifier_cascade_new_function_state_t;
static void _ccv_scd_classifier_cascade_new_function_state_read(const char* filename, ccv_scd_classifier_cascade_new_function_state_t* z)
{
ccv_scd_classifier_cascade_t* cascade = ccv_scd_classifier_cascade_read(filename);
if (!cascade)
return;
if (z->cascade)
ccv_scd_classifier_cascade_free(z->cascade);
z->cascade = cascade;
assert(z->cascade->size.width == z->params.size.width);
assert(z->cascade->size.height == z->params.size.height);
sqlite3* db = 0;
if (SQLITE_OK == sqlite3_open(filename, &db))
{
const char negative_data_qs[] =
"SELECT data, rnum, rsize FROM negative_data WHERE id=0;";
sqlite3_stmt* negative_data_stmt = 0;
if (SQLITE_OK == sqlite3_prepare_v2(db, negative_data_qs, sizeof(negative_data_qs), &negative_data_stmt, 0))
{
if (sqlite3_step(negative_data_stmt) == SQLITE_ROW)
{
int rsize = ccv_compute_dense_matrix_size(z->cascade->size.height, z->cascade->size.width, CCV_8U | (z->params.grayscale ? CCV_C1 : CCV_C3));
int rnum = sqlite3_column_int(negative_data_stmt, 1);
assert(sqlite3_column_int(negative_data_stmt, 2) == rsize);
size_t size = sqlite3_column_bytes(negative_data_stmt, 0);
assert(size == (size_t)rsize * rnum);
if (z->negatives)
ccv_array_clear(z->negatives);
else
z->negatives = ccv_array_new(rsize, rnum, 0);
int i;
const uint8_t* data = (const uint8_t*)sqlite3_column_blob(negative_data_stmt, 0);
for (i = 0; i < rnum; i++)
ccv_array_push(z->negatives, data + (off_t)i * rsize);
ccv_make_array_immutable(z->negatives);
z->array_signature = z->negatives->sig;
}
sqlite3_finalize(negative_data_stmt);
}
const char function_state_qs[] =
"SELECT t, k, positive_count, auc_prev, " // 4
"accu_true_positive_rate, accu_false_positive_rate, " // 6
"line_no, s, pw, nw FROM function_state WHERE fsid = 0;"; // 10
sqlite3_stmt* function_state_stmt = 0;
if (SQLITE_OK == sqlite3_prepare_v2(db, function_state_qs, sizeof(function_state_qs), &function_state_stmt, 0))
{
if (sqlite3_step(function_state_stmt) == SQLITE_ROW)
{
z->t = sqlite3_column_int(function_state_stmt, 0);
z->k = sqlite3_column_int(function_state_stmt, 1);
int positive_count = sqlite3_column_int(function_state_stmt, 2);
assert(positive_count == z->positives->rnum);
z->auc_prev = sqlite3_column_double(function_state_stmt, 3);
z->accu_true_positive_rate = sqlite3_column_double(function_state_stmt, 4);
z->accu_false_positive_rate = sqlite3_column_double(function_state_stmt, 5);
z->line_no = sqlite3_column_int(function_state_stmt, 6);
size_t size = sqlite3_column_bytes(function_state_stmt, 7);
const void* s = sqlite3_column_blob(function_state_stmt, 7);
memcpy(z->s, s, size);
size = sqlite3_column_bytes(function_state_stmt, 8);
const void* pw = sqlite3_column_blob(function_state_stmt, 8);
memcpy(z->pw, pw, size);
size = sqlite3_column_bytes(function_state_stmt, 9);
const void* nw = sqlite3_column_blob(function_state_stmt, 9);
memcpy(z->nw, nw, size);
}
sqlite3_finalize(function_state_stmt);
}
_ccv_scd_precompute_feature_vectors(z->features, z->positives, z->negatives, z->fv);
sqlite3_close(db);
}
}
static void _ccv_scd_classifier_cascade_new_function_state_write(ccv_scd_classifier_cascade_new_function_state_t* z, const char* filename)
{
ccv_scd_classifier_cascade_write(z->cascade, filename);
sqlite3* db = 0;
if (SQLITE_OK == sqlite3_open(filename, &db))
{
const char function_state_create_table_qs[] =
"CREATE TABLE IF NOT EXISTS function_state "
"(fsid INTEGER PRIMARY KEY ASC, t INTEGER, k INTEGER, positive_count INTEGER, auc_prev DOUBLE, accu_true_positive_rate DOUBLE, accu_false_positive_rate DOUBLE, line_no INTEGER, s BLOB, pw BLOB, nw BLOB);"
"CREATE TABLE IF NOT EXISTS negative_data "
"(id INTEGER PRIMARY KEY ASC, data BLOB, rnum INTEGER, rsize INTEGER);";
assert(SQLITE_OK == sqlite3_exec(db, function_state_create_table_qs, 0, 0, 0));
const char function_state_insert_qs[] =
"REPLACE INTO function_state "
"(fsid, t, k, positive_count, auc_prev, accu_true_positive_rate, accu_false_positive_rate, line_no, s, pw, nw) VALUES "
"(0, $t, $k, $positive_count, $auc_prev, $accu_true_positive_rate, $accu_false_positive_rate, $line_no, $s, $pw, $nw);";
sqlite3_stmt* function_state_insert_stmt = 0;
assert(SQLITE_OK == sqlite3_prepare_v2(db, function_state_insert_qs, sizeof(function_state_insert_qs), &function_state_insert_stmt, 0));
sqlite3_bind_int(function_state_insert_stmt, 1, z->t);
sqlite3_bind_int(function_state_insert_stmt, 2, z->k);
sqlite3_bind_int(function_state_insert_stmt, 3, z->positives->rnum);
sqlite3_bind_double(function_state_insert_stmt, 4, z->auc_prev);
sqlite3_bind_double(function_state_insert_stmt, 5, z->accu_true_positive_rate);
sqlite3_bind_double(function_state_insert_stmt, 6, z->accu_false_positive_rate);
sqlite3_bind_int(function_state_insert_stmt, 7, z->line_no);
sqlite3_bind_blob(function_state_insert_stmt, 8, z->s, sizeof(double) * (z->positives->rnum + z->negatives->rnum), SQLITE_STATIC);
sqlite3_bind_blob(function_state_insert_stmt, 9, z->pw, sizeof(double) * z->positives->rnum, SQLITE_STATIC);
sqlite3_bind_blob(function_state_insert_stmt, 10, z->nw, sizeof(double) * z->negatives->rnum, SQLITE_STATIC);
assert(SQLITE_DONE == sqlite3_step(function_state_insert_stmt));
sqlite3_finalize(function_state_insert_stmt);
if (z->array_signature != z->negatives->sig)
{
const char negative_data_insert_qs[] =
"REPLACE INTO negative_data "
"(id, data, rnum, rsize) VALUES (0, $data, $rnum, $rsize);";
sqlite3_stmt* negative_data_insert_stmt = 0;
assert(SQLITE_OK == sqlite3_prepare_v2(db, negative_data_insert_qs, sizeof(negative_data_insert_qs), &negative_data_insert_stmt, 0));
sqlite3_bind_blob(negative_data_insert_stmt, 1, z->negatives->data, z->negatives->rsize * z->negatives->rnum, SQLITE_STATIC);
sqlite3_bind_int(negative_data_insert_stmt, 2, z->negatives->rnum);
sqlite3_bind_int(negative_data_insert_stmt, 3, z->negatives->rsize);
assert(SQLITE_DONE == sqlite3_step(negative_data_insert_stmt));
sqlite3_finalize(negative_data_insert_stmt);
z->array_signature = z->negatives->sig;
}
sqlite3_close(db);
}
}
#endif
ccv_scd_classifier_cascade_t* ccv_scd_classifier_cascade_new(ccv_array_t* posfiles, ccv_array_t* hard_mine, int negative_count, const char* filename, ccv_scd_train_param_t params)
{
#ifdef HAVE_GSL
assert(posfiles->rnum > 0);
assert(hard_mine->rnum > 0);
gsl_rng_env_setup();
gsl_rng* rng = gsl_rng_alloc(gsl_rng_default);
ccv_scd_classifier_cascade_new_function_state_t z = {0};
z.features = _ccv_scd_stump_features(params.feature.base, params.feature.range_through, params.feature.step_through, params.size);
PRINT(CCV_CLI_INFO, " - using %d features\n", z.features->rnum);
int i, j, p, q;
z.positives = _ccv_scd_collect_positives(params.size, posfiles, params.grayscale);
double* h = (double*)ccmalloc(sizeof(double) * (z.positives->rnum + negative_count));
z.s = (double*)ccmalloc(sizeof(double) * (z.positives->rnum + negative_count));
assert(z.s);
z.pw = (double*)ccmalloc(sizeof(double) * z.positives->rnum);
assert(z.pw);
z.nw = (double*)ccmalloc(sizeof(double) * negative_count);
assert(z.nw);
ccmemalign((void**)&z.fv, 16, sizeof(float) * (z.positives->rnum + negative_count) * z.features->rnum * 32);
assert(z.fv);
z.params = params;
ccv_function_state_begin(_ccv_scd_classifier_cascade_new_function_state_read, z, filename);
z.negatives = _ccv_scd_collect_negatives(rng, params.size, hard_mine, negative_count, params.grayscale);
_ccv_scd_precompute_feature_vectors(z.features, z.positives, z.negatives, z.fv);
z.cascade = (ccv_scd_classifier_cascade_t*)ccmalloc(sizeof(ccv_scd_classifier_cascade_t));
z.cascade->margin = ccv_margin(0, 0, 0, 0);
z.cascade->size = params.size;
z.cascade->count = 0;
z.cascade->classifiers = 0;
z.accu_true_positive_rate = 1;
z.accu_false_positive_rate = 1;
ccv_function_state_resume(_ccv_scd_classifier_cascade_new_function_state_write, z, filename);
for (z.t = 0; z.t < params.boosting; z.t++)
{
for (i = 0; i < z.positives->rnum; i++)
z.pw[i] = 0.5 / z.positives->rnum;
for (i = 0; i < z.negatives->rnum; i++)
z.nw[i] = 0.5 / z.negatives->rnum;
memset(z.s, 0, sizeof(double) * (z.positives->rnum + z.negatives->rnum));
z.cascade->classifiers = (ccv_scd_stump_classifier_t*)ccrealloc(z.cascade->classifiers, sizeof(ccv_scd_stump_classifier_t) * (z.t + 1));
z.cascade->count = z.t + 1;
z.cascade->classifiers[z.t].threshold = 0;
z.cascade->classifiers[z.t].features = 0;
z.cascade->classifiers[z.t].count = 0;
z.auc_prev = 0;
assert(z.positives->rnum > 0 && z.negatives->rnum > 0);
// for the first prune stages, we have more restrictive number of features (faster)
for (z.k = 0; z.k < (z.t < params.stop_criteria.prune_stage ? params.stop_criteria.prune_feature : params.stop_criteria.maximum_feature); z.k++)
{
ccv_scd_stump_classifier_t* classifier = z.cascade->classifiers + z.t;
classifier->features = (ccv_scd_stump_feature_t*)ccrealloc(classifier->features, sizeof(ccv_scd_stump_feature_t) * (z.k + 1));
_ccv_scd_stump_feature_supervised_train(rng, z.features, z.positives->rnum, z.negatives->rnum, z.pw, z.nw, z.fv, params.C, params.weight_trimming);
int best_feature_no = _ccv_scd_best_feature_gentle_adaboost(z.s, z.features, z.pw, z.nw, z.positives->rnum, z.negatives->rnum, z.fv);
ccv_scd_stump_feature_t best_feature = *(ccv_scd_stump_feature_t*)ccv_array_get(z.features, best_feature_no);
for (i = 0; i < z.positives->rnum + z.negatives->rnum; i++)
{
float* surf = _ccv_scd_get_surf_at(z.fv, best_feature_no, i, z.positives->rnum, z.negatives->rnum);
float v = best_feature.bias;
for (j = 0; j < 32; j++)
v += best_feature.w[j] * surf[j];
v = expf(v);
h[i] = (v - 1) / (v + 1);
}
// compute the total score so far
for (i = 0; i < z.positives->rnum + z.negatives->rnum; i++)
z.s[i] += h[i];
// compute AUC
double auc = _ccv_scd_auc(z.s, z.positives->rnum, z.negatives->rnum);
float true_positive_rate = 0;
float false_positive_rate = 0;
// compute true positive / false positive rate
_ccv_scd_threshold_at_hit_rate(z.s, z.positives->rnum, z.negatives->rnum, params.stop_criteria.hit_rate, &true_positive_rate, &false_positive_rate);
FLUSH(CCV_CLI_INFO, " - at %d-th iteration, auc: %lf, TP rate: %f, FP rate: %f\n", z.k + 1, auc, true_positive_rate, false_positive_rate);
PRINT(CCV_CLI_INFO, " --- pick feature %s @ (%d, %d, %d, %d)\n", ((best_feature.dy[3] == best_feature.dy[0] ? "4x1" : (best_feature.dx[3] == best_feature.dx[0] ? "1x4" : "2x2"))), best_feature.sx[0], best_feature.sy[0], best_feature.dx[3], best_feature.dy[3]);
classifier->features[z.k] = best_feature;
classifier->count = z.k + 1;
double auc_prev = z.auc_prev;
z.auc_prev = auc;
// auc stop to improve, as well as the false positive rate goal reach, at that point, we stop
if (auc - auc_prev < params.stop_criteria.auc_crit && false_positive_rate < params.stop_criteria.false_positive_rate)
break;
// re-weight, with Gentle AdaBoost
for (i = 0; i < z.positives->rnum; i++)
z.pw[i] *= exp(-h[i]);
for (i = 0; i < z.negatives->rnum; i++)
z.nw[i] *= exp(h[i + z.positives->rnum]);
// re-normalize
double w = 0;
for (i = 0; i < z.positives->rnum; i++)
w += z.pw[i];
w = 0.5 / w;
for (i = 0; i < z.positives->rnum; i++)
z.pw[i] *= w;
w = 0;
for (i = 0; i < z.negatives->rnum; i++)
w += z.nw[i];
w = 0.5 / w;
for (i = 0; i < z.negatives->rnum; i++)
z.nw[i] *= w;
ccv_function_state_resume(_ccv_scd_classifier_cascade_new_function_state_write, z, filename);
}
// backtrack removal
while (z.cascade->classifiers[z.t].count > 1)
{
double max_auc = 0;
p = -1;
for (i = 0; i < z.cascade->classifiers[z.t].count; i++)
{
ccv_scd_stump_feature_t* feature = z.cascade->classifiers[z.t].features + i;
int k = _ccv_scd_find_match_feature(feature, z.features);
assert(k >= 0);
for (j = 0; j < z.positives->rnum + z.negatives->rnum; j++)
{
float* surf = _ccv_scd_get_surf_at(z.fv, k, j, z.positives->rnum, z.negatives->rnum);
float v = feature->bias;
for (q = 0; q < 32; q++)
v += feature->w[q]* surf[q];
v = expf(v);
h[j] = z.s[j] - (v - 1) / (v + 1);
}
double auc = _ccv_scd_auc(h, z.positives->rnum, z.negatives->rnum);
FLUSH(CCV_CLI_INFO, " - attempting without %d-th feature, auc: %lf", i + 1, auc);
if (auc >= max_auc)
max_auc = auc, p = i;
}
if (max_auc >= z.auc_prev)
{
FLUSH(CCV_CLI_INFO, " - remove %d-th feature with new auc %lf\n", p + 1, max_auc);
ccv_scd_stump_feature_t* feature = z.cascade->classifiers[z.t].features + p;
int k = _ccv_scd_find_match_feature(feature, z.features);
assert(k >= 0);
for (j = 0; j < z.positives->rnum + z.negatives->rnum; j++)
{
float* surf = _ccv_scd_get_surf_at(z.fv, k, j, z.positives->rnum, z.negatives->rnum);
float v = feature->bias;
for (q = 0; q < 32; q++)
v += feature->w[q] * surf[q];
v = expf(v);
z.s[j] -= (v - 1) / (v + 1);
}
z.auc_prev = _ccv_scd_auc(z.s, z.positives->rnum, z.negatives->rnum);
--z.cascade->classifiers[z.t].count;
if (p < z.cascade->classifiers[z.t].count)
memmove(z.cascade->classifiers[z.t].features + p + 1, z.cascade->classifiers[z.t].features + p, sizeof(ccv_scd_stump_feature_t) * (z.cascade->classifiers[z.t].count - p));
} else
break;
}
float true_positive_rate = 0;
float false_positive_rate = 0;
z.cascade->classifiers[z.t].threshold = _ccv_scd_threshold_at_hit_rate(z.s, z.positives->rnum, z.negatives->rnum, params.stop_criteria.hit_rate, &true_positive_rate, &false_positive_rate);
z.accu_true_positive_rate *= true_positive_rate;
z.accu_false_positive_rate *= false_positive_rate;
FLUSH(CCV_CLI_INFO, " - %d-th stage classifier TP rate : %f, FP rate : %f, ATP rate : %lf, AFP rate : %lg, at threshold : %f\n", z.t + 1, true_positive_rate, false_positive_rate, z.accu_true_positive_rate, z.accu_false_positive_rate, z.cascade->classifiers[z.t].threshold);
if (z.accu_false_positive_rate < params.stop_criteria.accu_false_positive_rate)
break;
ccv_function_state_resume(_ccv_scd_classifier_cascade_new_function_state_write, z, filename);
if (z.t < params.boosting - 1)
{
int pass = 0;
for (i = 0; i < z.positives->rnum; i++)
{
ccv_dense_matrix_t* a = (ccv_dense_matrix_t*)ccv_array_get(z.positives, i);
a->data.u8 = (unsigned char*)(a + 1);
if (_ccv_scd_classifier_cascade_pass(z.cascade, a))
++pass;
}
PRINT(CCV_CLI_INFO, " - %d-th stage classifier TP rate (with pass) : %f\n", z.t + 1, (float)pass / z.positives->rnum);
ccv_array_t* hard_negatives = _ccv_scd_hard_mining(rng, z.cascade, hard_mine, z.negatives, negative_count, params.grayscale, z.t < params.stop_criteria.prune_stage /* try to balance even distribution among negatives when we are in prune stage */);
ccv_array_free(z.negatives);
z.negatives = hard_negatives;
_ccv_scd_precompute_feature_vectors(z.features, z.positives, z.negatives, z.fv);
}
ccv_function_state_resume(_ccv_scd_classifier_cascade_new_function_state_write, z, filename);
}
ccv_array_free(z.negatives);
ccv_function_state_finish();
ccv_array_free(z.features);
ccv_array_free(z.positives);
ccfree(h);
ccfree(z.s);
ccfree(z.pw);
ccfree(z.nw);
ccfree(z.fv);
gsl_rng_free(rng);
return z.cascade;
#else
assert(0 && "ccv_scd_classifier_cascade_new requires GSL library and support");
return 0;
#endif
}
void ccv_scd_classifier_cascade_write(ccv_scd_classifier_cascade_t* cascade, const char* filename)
{
sqlite3* db = 0;
if (SQLITE_OK == sqlite3_open(filename, &db))
{
const char create_table_qs[] =
"CREATE TABLE IF NOT EXISTS cascade_params "
"(id INTEGER PRIMARY KEY ASC, count INTEGER, "
"margin_left INTEGER, margin_top INTEGER, margin_right INTEGER, margin_bottom INTEGER, "
"size_width INTEGER, size_height INTEGER);"
"CREATE TABLE IF NOT EXISTS classifier_params "
"(classifier INTEGER PRIMARY KEY ASC, count INTEGER, threshold DOUBLE);"
"CREATE TABLE IF NOT EXISTS feature_params "
"(classifier INTEGER, id INTEGER, "
"sx_0 INTEGER, sy_0 INTEGER, dx_0 INTEGER, dy_0 INTEGER, "
"sx_1 INTEGER, sy_1 INTEGER, dx_1 INTEGER, dy_1 INTEGER, "
"sx_2 INTEGER, sy_2 INTEGER, dx_2 INTEGER, dy_2 INTEGER, "
"sx_3 INTEGER, sy_3 INTEGER, dx_3 INTEGER, dy_3 INTEGER, "
"bias DOUBLE, w BLOB, UNIQUE (classifier, id));";
assert(SQLITE_OK == sqlite3_exec(db, create_table_qs, 0, 0, 0));
const char cascade_params_insert_qs[] =
"REPLACE INTO cascade_params "
"(id, count, "
"margin_left, margin_top, margin_right, margin_bottom, "
"size_width, size_height) VALUES "
"(0, $count, " // 0
"$margin_left, $margin_top, $margin_bottom, $margin_right, " // 4
"$size_width, $size_height);"; // 6
sqlite3_stmt* cascade_params_insert_stmt = 0;
assert(SQLITE_OK == sqlite3_prepare_v2(db, cascade_params_insert_qs, sizeof(cascade_params_insert_qs), &cascade_params_insert_stmt, 0));
sqlite3_bind_int(cascade_params_insert_stmt, 1, cascade->count);
sqlite3_bind_int(cascade_params_insert_stmt, 2, cascade->margin.left);
sqlite3_bind_int(cascade_params_insert_stmt, 3, cascade->margin.top);
sqlite3_bind_int(cascade_params_insert_stmt, 4, cascade->margin.right);
sqlite3_bind_int(cascade_params_insert_stmt, 5, cascade->margin.bottom);
sqlite3_bind_int(cascade_params_insert_stmt, 6, cascade->size.width);
sqlite3_bind_int(cascade_params_insert_stmt, 7, cascade->size.height);
assert(SQLITE_DONE == sqlite3_step(cascade_params_insert_stmt));
sqlite3_finalize(cascade_params_insert_stmt);
const char classifier_params_insert_qs[] =
"REPLACE INTO classifier_params "
"(classifier, count, threshold) VALUES "
"($classifier, $count, $threshold);";
sqlite3_stmt* classifier_params_insert_stmt = 0;
assert(SQLITE_OK == sqlite3_prepare_v2(db, classifier_params_insert_qs, sizeof(classifier_params_insert_qs), &classifier_params_insert_stmt, 0));
const char feature_params_insert_qs[] =
"REPLACE INTO feature_params "
"(classifier, id, "
"sx_0, sy_0, dx_0, dy_0, "
"sx_1, sy_1, dx_1, dy_1, "
"sx_2, sy_2, dx_2, dy_2, "
"sx_3, sy_3, dx_3, dy_3, "
"bias, w) VALUES "
"($classifier, $id, " // 1
"$sx_0, $sy_0, $dx_0, $dy_0, " // 5
"$sx_1, $sy_1, $dx_1, $dy_1, " // 9
"$sx_2, $sy_2, $dx_2, $dy_2, " // 13
"$sx_3, $sy_3, $dx_3, $dy_3, " // 17
"$bias, $w);"; // 19
sqlite3_stmt* feature_params_insert_stmt = 0;
assert(SQLITE_OK == sqlite3_prepare_v2(db, feature_params_insert_qs, sizeof(feature_params_insert_qs), &feature_params_insert_stmt, 0));
int i, j, k;
for (i = 0; i < cascade->count; i++)
{
ccv_scd_stump_classifier_t* classifier = cascade->classifiers + i;
sqlite3_bind_int(classifier_params_insert_stmt, 1, i);
sqlite3_bind_int(classifier_params_insert_stmt, 2, classifier->count);
sqlite3_bind_double(classifier_params_insert_stmt, 3, classifier->threshold);
assert(SQLITE_DONE == sqlite3_step(classifier_params_insert_stmt));
sqlite3_reset(classifier_params_insert_stmt);
sqlite3_clear_bindings(classifier_params_insert_stmt);
for (j = 0; j < classifier->count; j++)
{
ccv_scd_stump_feature_t* feature = classifier->features + j;
sqlite3_bind_int(feature_params_insert_stmt, 1, i);
sqlite3_bind_int(feature_params_insert_stmt, 2, j);
for (k = 0; k < 4; k++)
{
sqlite3_bind_int(feature_params_insert_stmt, 3 + k * 4, feature->sx[k]);
sqlite3_bind_int(feature_params_insert_stmt, 4 + k * 4, feature->sy[k]);
sqlite3_bind_int(feature_params_insert_stmt, 5 + k * 4, feature->dx[k]);
sqlite3_bind_int(feature_params_insert_stmt, 6 + k * 4, feature->dy[k]);
}
sqlite3_bind_double(feature_params_insert_stmt, 19, feature->bias);
sqlite3_bind_blob(feature_params_insert_stmt, 20, feature->w, sizeof(float) * 32, SQLITE_STATIC);
assert(SQLITE_DONE == sqlite3_step(feature_params_insert_stmt));
sqlite3_reset(feature_params_insert_stmt);
sqlite3_clear_bindings(feature_params_insert_stmt);
}
}
sqlite3_finalize(classifier_params_insert_stmt);
sqlite3_finalize(feature_params_insert_stmt);
sqlite3_close(db);
}
}
ccv_scd_classifier_cascade_t* ccv_scd_classifier_cascade_read(const char* filename)
{
int i;
sqlite3* db = 0;
ccv_scd_classifier_cascade_t* cascade = 0;
if (SQLITE_OK == sqlite3_open(filename, &db))
{
const char cascade_params_qs[] =
"SELECT count, " // 1
"margin_left, margin_top, margin_right, margin_bottom, " // 5
"size_width, size_height FROM cascade_params WHERE id = 0;"; // 7
sqlite3_stmt* cascade_params_stmt = 0;
if (SQLITE_OK == sqlite3_prepare_v2(db, cascade_params_qs, sizeof(cascade_params_qs), &cascade_params_stmt, 0))
{
if (sqlite3_step(cascade_params_stmt) == SQLITE_ROW)
{
cascade = (ccv_scd_classifier_cascade_t*)ccmalloc(sizeof(ccv_scd_classifier_cascade_t));
cascade->count = sqlite3_column_int(cascade_params_stmt, 0);
cascade->classifiers = (ccv_scd_stump_classifier_t*)cccalloc(cascade->count, sizeof(ccv_scd_stump_classifier_t));
cascade->margin = ccv_margin(sqlite3_column_int(cascade_params_stmt, 1), sqlite3_column_int(cascade_params_stmt, 2), sqlite3_column_int(cascade_params_stmt, 3), sqlite3_column_int(cascade_params_stmt, 4));
cascade->size = ccv_size(sqlite3_column_int(cascade_params_stmt, 5), sqlite3_column_int(cascade_params_stmt, 6));
}
sqlite3_finalize(cascade_params_stmt);
}
if (cascade)
{
const char classifier_params_qs[] =
"SELECT classifier, count, threshold FROM classifier_params ORDER BY classifier ASC;";
sqlite3_stmt* classifier_params_stmt = 0;
if (SQLITE_OK == sqlite3_prepare_v2(db, classifier_params_qs, sizeof(classifier_params_qs), &classifier_params_stmt, 0))
{
while (sqlite3_step(classifier_params_stmt) == SQLITE_ROW)
if (sqlite3_column_int(classifier_params_stmt, 0) < cascade->count)
{
ccv_scd_stump_classifier_t* classifier = cascade->classifiers + sqlite3_column_int(classifier_params_stmt, 0);
classifier->count = sqlite3_column_int(classifier_params_stmt, 1);
classifier->features = (ccv_scd_stump_feature_t*)ccmalloc(sizeof(ccv_scd_stump_feature_t) * classifier->count);
classifier->threshold = (float)sqlite3_column_double(classifier_params_stmt, 2);
}
sqlite3_finalize(classifier_params_stmt);
}
const char feature_params_qs[] =
"SELECT classifier, id, "
"sx_0, sy_0, dx_0, dy_0, "
"sx_1, sy_1, dx_1, dy_1, "
"sx_2, sy_2, dx_2, dy_2, "
"sx_3, sy_3, dx_3, dy_3, "
"bias, w FROM feature_params ORDER BY classifier, id ASC;";
sqlite3_stmt* feature_params_stmt = 0;
if (SQLITE_OK == sqlite3_prepare_v2(db, feature_params_qs, sizeof(feature_params_qs), &feature_params_stmt, 0))
{
while (sqlite3_step(feature_params_stmt) == SQLITE_ROW)
if (sqlite3_column_int(feature_params_stmt, 0) < cascade->count)
{
ccv_scd_stump_classifier_t* classifier = cascade->classifiers + sqlite3_column_int(feature_params_stmt, 0);
if (sqlite3_column_int(feature_params_stmt, 1) < classifier->count)
{
ccv_scd_stump_feature_t* feature = classifier->features + sqlite3_column_int(feature_params_stmt, 1);
for (i = 0; i < 4; i++)
{
feature->sx[i] = sqlite3_column_int(feature_params_stmt, 2 + i * 4);
feature->sy[i] = sqlite3_column_int(feature_params_stmt, 3 + i * 4);
feature->dx[i] = sqlite3_column_int(feature_params_stmt, 4 + i * 4);
feature->dy[i] = sqlite3_column_int(feature_params_stmt, 5 + i * 4);
}
feature->bias = (float)sqlite3_column_double(feature_params_stmt, 18);
int wnum = sqlite3_column_bytes(feature_params_stmt, 19);
assert(wnum == 32 * sizeof(float));
const void* w = sqlite3_column_blob(feature_params_stmt, 19);
memcpy(feature->w, w, sizeof(float) * 32);
}
}
sqlite3_finalize(feature_params_stmt);
}
}
sqlite3_close(db);
}
return cascade;
}
void ccv_scd_classifier_cascade_free(ccv_scd_classifier_cascade_t* cascade)
{
int i;
for (i = 0; i < cascade->count; i++)
{
ccv_scd_stump_classifier_t* classifier = cascade->classifiers + i;
ccfree(classifier->features);
}
ccfree(cascade->classifiers);
ccfree(cascade);
}
static int _ccv_is_equal_same_class(const void* _r1, const void* _r2, void* data)
{
const ccv_comp_t* r1 = (const ccv_comp_t*)_r1;
const ccv_comp_t* r2 = (const ccv_comp_t*)_r2;
if (r2->classification.id != r1->classification.id)
return 0;
int i = ccv_max(ccv_min(r2->rect.x + r2->rect.width, r1->rect.x + r1->rect.width) - ccv_max(r2->rect.x, r1->rect.x), 0) * ccv_max(ccv_min(r2->rect.y + r2->rect.height, r1->rect.y + r1->rect.height) - ccv_max(r2->rect.y, r1->rect.y), 0);
int m = ccv_min(r2->rect.width * r2->rect.height, r1->rect.width * r1->rect.height);
return i >= 0.3 * m; // IoM > 0.3 like HeadHunter does
}
ccv_array_t* ccv_scd_detect_objects(ccv_dense_matrix_t* a, ccv_scd_classifier_cascade_t** cascades, int count, ccv_scd_param_t params)
{
int i, j, k, x, y, p, q;
int scale_upto = 1;
float up_ratio = 1.0;
for (i = 0; i < count; i++)
up_ratio = ccv_max(up_ratio, ccv_max((float)cascades[i]->size.width / params.size.width, (float)cascades[i]->size.height / params.size.height));
if (up_ratio - 1.0 > 1e-4)
{
ccv_dense_matrix_t* resized = 0;
ccv_resample(a, &resized, 0, (int)(a->rows * up_ratio + 0.5), (int)(a->cols * up_ratio + 0.5), CCV_INTER_CUBIC);
a = resized;
}
for (i = 0; i < count; i++)
scale_upto = ccv_max(scale_upto, (int)(log(ccv_min((double)a->rows / (cascades[i]->size.height - cascades[i]->margin.top - cascades[i]->margin.bottom), (double)a->cols / (cascades[i]->size.width - cascades[i]->margin.left - cascades[i]->margin.right))) / log(2.) - DBL_MIN) + 1);
ccv_dense_matrix_t** pyr = (ccv_dense_matrix_t**)alloca(sizeof(ccv_dense_matrix_t*) * scale_upto);
pyr[0] = a;
for (i = 1; i < scale_upto; i++)
{
pyr[i] = 0;
ccv_sample_down(pyr[i - 1], &pyr[i], 0, 0, 0);
}
#if defined(HAVE_SSE2)
__m128 surf[8];
#else
float surf[32];
#endif
ccv_array_t** seq = (ccv_array_t**)alloca(sizeof(ccv_array_t*) * count);
for (i = 0; i < count; i++)
seq[i] = ccv_array_new(sizeof(ccv_comp_t), 64, 0);
for (i = 0; i < scale_upto; i++)
{
// run it
for (j = 0; j < count; j++)
{
double scale_ratio = pow(2., 1. / (params.interval + 1));
double scale = 1;
ccv_scd_classifier_cascade_t* cascade = cascades[j];
for (k = 0; k <= params.interval; k++)
{
int rows = (int)(pyr[i]->rows / scale + 0.5);
int cols = (int)(pyr[i]->cols / scale + 0.5);
if (rows < cascade->size.height || cols < cascade->size.width)
break;
ccv_dense_matrix_t* image = k == 0 ? pyr[i] : 0;
if (k > 0)
ccv_resample(pyr[i], &image, 0, rows, cols, CCV_INTER_AREA);
ccv_dense_matrix_t* scd = 0;
if (cascade->margin.left == 0 && cascade->margin.top == 0 && cascade->margin.right == 0 && cascade->margin.bottom == 0)
{
ccv_scd(image, &scd, 0);
if (k > 0)
ccv_matrix_free(image);
} else {
ccv_dense_matrix_t* bordered = 0;
ccv_border(image, (ccv_matrix_t**)&bordered, 0, cascade->margin);
if (k > 0)
ccv_matrix_free(image);
ccv_scd(bordered, &scd, 0);
ccv_matrix_free(bordered);
}
ccv_dense_matrix_t* sat = 0;
ccv_sat(scd, &sat, 0, CCV_PADDING_ZERO);
assert(CCV_GET_CHANNEL(sat->type) == CCV_SCD_CHANNEL);
ccv_matrix_free(scd);
float* ptr = sat->data.f32;
for (y = 0; y < rows; y += params.step_through)
{
if (y >= sat->rows - cascade->size.height - 1)
break;
for (x = 0; x < cols; x += params.step_through)
{
if (x >= sat->cols - cascade->size.width - 1)
break;
int pass = 1;
float sum = 0;
for (p = 0; p < cascade->count; p++)
{
ccv_scd_stump_classifier_t* classifier = cascade->classifiers + p;
float v = 0;
for (q = 0; q < classifier->count; q++)
{
ccv_scd_stump_feature_t* feature = classifier->features + q;
#if defined(HAVE_SSE2)
_ccv_scd_run_feature_at_sse2(ptr + x * CCV_SCD_CHANNEL, sat->cols, feature, surf);
__m128 u0 = _mm_add_ps(_mm_mul_ps(surf[0], _mm_loadu_ps(feature->w)), _mm_mul_ps(surf[1], _mm_loadu_ps(feature->w + 4)));
__m128 u1 = _mm_add_ps(_mm_mul_ps(surf[2], _mm_loadu_ps(feature->w + 8)), _mm_mul_ps(surf[3], _mm_loadu_ps(feature->w + 12)));
__m128 u2 = _mm_add_ps(_mm_mul_ps(surf[4], _mm_loadu_ps(feature->w + 16)), _mm_mul_ps(surf[5], _mm_loadu_ps(feature->w + 20)));
__m128 u3 = _mm_add_ps(_mm_mul_ps(surf[6], _mm_loadu_ps(feature->w + 24)), _mm_mul_ps(surf[7], _mm_loadu_ps(feature->w + 28)));
u0 = _mm_add_ps(u0, u1);
u2 = _mm_add_ps(u2, u3);
union {
float f[4];
__m128 p;
} ux;
ux.p = _mm_add_ps(u0, u2);
float u = expf(feature->bias + ux.f[0] + ux.f[1] + ux.f[2] + ux.f[3]);
#else
_ccv_scd_run_feature_at(ptr + x * CCV_SCD_CHANNEL, sat->cols, feature, surf);
float u = feature->bias;
int r;
for (r = 0; r < 32; r++)
u += surf[r] * feature->w[r];
u = expf(u);
#endif
v += (u - 1) / (u + 1);
}
if (v <= classifier->threshold)
{
pass = 0;
break;
}
sum = v / classifier->count;
}
if (pass)
{
ccv_comp_t comp;
comp.rect = ccv_rect((int)((x + 0.5) * (scale / up_ratio) * (1 << i) - 0.5),
(int)((y + 0.5) * (scale / up_ratio) * (1 << i) - 0.5),
(cascade->size.width - cascade->margin.left - cascade->margin.right) * (scale / up_ratio) * (1 << i),
(cascade->size.height - cascade->margin.top - cascade->margin.bottom) * (scale / up_ratio) * (1 << i));
comp.neighbors = 1;
comp.classification.id = j + 1;
comp.classification.confidence = sum + (cascade->count - 1);
ccv_array_push(seq[j], &comp);
}
}
ptr += sat->cols * CCV_SCD_CHANNEL * params.step_through;
}
ccv_matrix_free(sat);
scale *= scale_ratio;
}
}
}
for (i = 1; i < scale_upto; i++)
ccv_matrix_free(pyr[i]);
if (up_ratio - 1.0 > 1e-4)
ccv_matrix_free(a);
ccv_array_t* result_seq = ccv_array_new(sizeof(ccv_comp_t), 64, 0);
for (k = 0; k < count; k++)
{
/* simple non-maximum suppression, we merge when intersected area / min area > 0.3 */
if(params.min_neighbors == 0)
{
for (i = 0; i < seq[k]->rnum; i++)
{
ccv_comp_t* comp = (ccv_comp_t*)ccv_array_get(seq[k], i);
ccv_array_push(result_seq, comp);
}
} else {
ccv_array_t* idx_seq = 0;
// group retrieved rectangles in order to filter out noise
int ncomp = ccv_array_group(seq[k], &idx_seq, _ccv_is_equal_same_class, 0);
ccv_comp_t* comps = (ccv_comp_t*)cccalloc(ncomp + 1, sizeof(ccv_comp_t));
// count number of neighbors
for (i = 0; i < seq[k]->rnum; i++)
{
ccv_comp_t r1 = *(ccv_comp_t*)ccv_array_get(seq[k], i);
int idx = *(int*)ccv_array_get(idx_seq, i);
comps[idx].classification.id = r1.classification.id;
if (r1.classification.confidence > comps[idx].classification.confidence || comps[idx].neighbors == 0)
{
comps[idx].rect = r1.rect;
comps[idx].classification.confidence = r1.classification.confidence;
}
++comps[idx].neighbors;
}
// push merged bounding box to result_seq
for (i = 0; i < ncomp; i++)
{
int n = comps[i].neighbors;
if (n >= params.min_neighbors)
ccv_array_push(result_seq, comps + i);
}
ccv_array_free(idx_seq);
ccfree(comps);
}
ccv_array_free(seq[k]);
}
return result_seq;
}
| {
"alphanum_fraction": 0.6747504479,
"avg_line_length": 50.9331884845,
"ext": "c",
"hexsha": "cf45599adf04f48cae0650810b5d6f2a314a5a4e",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2019-05-18T15:50:49.000Z",
"max_forks_repo_forks_event_min_datetime": "2019-05-18T15:50:49.000Z",
"max_forks_repo_head_hexsha": "cf86aacc6a59fcc4f3e203eb3889a89c5e8f5c66",
"max_forks_repo_licenses": [
"CC0-1.0",
"CC-BY-4.0"
],
"max_forks_repo_name": "lyp365859350/ccv",
"max_forks_repo_path": "lib/ccv_scd.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "cf86aacc6a59fcc4f3e203eb3889a89c5e8f5c66",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"CC0-1.0",
"CC-BY-4.0"
],
"max_issues_repo_name": "lyp365859350/ccv",
"max_issues_repo_path": "lib/ccv_scd.c",
"max_line_length": 281,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "655cb2c4a95694a69b81eab5ccb823dbcaa805e4",
"max_stars_repo_licenses": [
"CC0-1.0",
"CC-BY-4.0"
],
"max_stars_repo_name": "xiaoye77/ccv",
"max_stars_repo_path": "lib/ccv_scd.c",
"max_stars_repo_stars_event_max_datetime": "2020-01-16T21:14:39.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-01-16T21:14:39.000Z",
"num_tokens": 41001,
"size": 93768
} |
/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
* Copyright 2018-Present Couchbase, Inc.
*
* Use of this software is governed by the Business Source License included
* in the file licenses/BSL-Couchbase.txt. As of the Change Date specified
* in that file, in accordance with the Business Source License, use of this
* software will be governed by the Apache License, Version 2.0, included in
* the file licenses/APL2.txt.
*/
#pragma once
#include "dcp/dcp-types.h"
#include "evp_engine_test.h"
#include "evp_store_single_threaded_test.h"
#include "vbucket_fwd.h"
#include <memcached/engine_error.h>
#include <gsl/gsl>
class Item;
class MockDcpProducer;
class MockActiveStream;
struct DcpMessageProducersIface;
/**
* Test fixture for unit tests related to DCP.
*/
class DCPTest : public EventuallyPersistentEngineTest {
protected:
void SetUp() override;
void TearDown() override;
// Create a DCP producer; initially with no streams associated.
void create_dcp_producer(
int flags = 0,
IncludeValue includeVal = IncludeValue::Yes,
IncludeXattrs includeXattrs = IncludeXattrs::Yes,
std::vector<std::pair<std::string, std::string>> controls = {});
// Setup a DCP producer and attach a stream and cursor to it.
void setup_dcp_stream(
int flags = 0,
IncludeValue includeVal = IncludeValue::Yes,
IncludeXattrs includeXattrs = IncludeXattrs::Yes,
std::vector<std::pair<std::string, std::string>> controls = {});
cb::engine_errc destroy_dcp_stream();
struct StreamRequestResult {
cb::engine_errc status;
uint64_t rollbackSeqno;
};
/**
* Helper function to simplify calling producer->streamRequest() - provides
* sensible default values for common invocations.
*/
static StreamRequestResult doStreamRequest(DcpProducer& producer,
uint64_t startSeqno = 0,
uint64_t endSeqno = ~0,
uint64_t snapStart = 0,
uint64_t snapEnd = ~0,
uint64_t vbUUID = 0);
/**
* Helper function to simplify the process of preparing DCP items to be
* fetched from the stream via step().
* Should be called once all expected items are present in the vbuckets'
* checkpoint, it will then run the correct background tasks to
* copy CheckpointManager items to the producers' readyQ.
*/
static void prepareCheckpointItemsForStep(
DcpMessageProducersIface& msgProducers,
MockDcpProducer& producer,
VBucket& vb);
/*
* Creates an item with the key \"key\", containing json data and xattrs.
* @return a unique_ptr to a newly created item.
*/
std::unique_ptr<Item> makeItemWithXattrs();
/*
* Creates an item with the key \"key\", containing json data and no xattrs.
* @return a unique_ptr to a newly created item.
*/
std::unique_ptr<Item> makeItemWithoutXattrs();
/* Add items onto the vbucket and wait for the checkpoint to be removed */
void addItemsAndRemoveCheckpoint(int numItems);
void removeCheckpoint(int numItems);
void runCheckpointProcessor(DcpMessageProducersIface& producers);
std::shared_ptr<MockDcpProducer> producer;
std::shared_ptr<MockActiveStream> stream;
VBucketPtr vb0;
/*
* Fake callback emulating dcp_add_failover_log
*/
static cb::engine_errc fakeDcpAddFailoverLog(
const std::vector<vbucket_failover_t>&) {
callbackCount++;
return cb::engine_errc::success;
}
// callbackCount needs to be static as its used inside of the static
// function fakeDcpAddFailoverLog.
static int callbackCount;
};
class FlowControlTest : public KVBucketTest,
public ::testing::WithParamInterface<bool> {
protected:
void SetUp() override;
bool flowControlEnabled;
}; | {
"alphanum_fraction": 0.6462650602,
"avg_line_length": 34.2975206612,
"ext": "h",
"hexsha": "4e13611789b8369032653a54a9be5585f8d94562",
"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": "78123c9aa2c2feb24b7c31eecc862bf2ed6325e4",
"max_forks_repo_licenses": [
"MIT",
"BSD-3-Clause"
],
"max_forks_repo_name": "BenHuddleston/kv_engine",
"max_forks_repo_path": "engines/ep/tests/module_tests/dcp_test.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "78123c9aa2c2feb24b7c31eecc862bf2ed6325e4",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT",
"BSD-3-Clause"
],
"max_issues_repo_name": "BenHuddleston/kv_engine",
"max_issues_repo_path": "engines/ep/tests/module_tests/dcp_test.h",
"max_line_length": 80,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "78123c9aa2c2feb24b7c31eecc862bf2ed6325e4",
"max_stars_repo_licenses": [
"MIT",
"BSD-3-Clause"
],
"max_stars_repo_name": "BenHuddleston/kv_engine",
"max_stars_repo_path": "engines/ep/tests/module_tests/dcp_test.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 937,
"size": 4150
} |
/* bspline/gsl_bspline.h
*
* Copyright (C) 2006 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 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_BSPLINE_H__
#define __GSL_BSPLINE_H__
#include <stdlib.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_vector.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 k; /* spline order */
size_t km1; /* k - 1 (polynomial order) */
size_t l; /* number of polynomial pieces on interval */
size_t nbreak; /* number of breakpoints (l + 1) */
size_t n; /* number of bspline basis functions (l + k - 1) */
gsl_vector *knots; /* knots vector */
gsl_vector *deltal; /* left delta */
gsl_vector *deltar; /* right delta */
gsl_vector *B; /* temporary spline results */
} gsl_bspline_workspace;
gsl_bspline_workspace *
gsl_bspline_alloc(const size_t k, const size_t nbreak);
void gsl_bspline_free(gsl_bspline_workspace *w);
size_t gsl_bspline_ncoeffs (gsl_bspline_workspace * w);
size_t gsl_bspline_order (gsl_bspline_workspace * w);
size_t gsl_bspline_nbreak (gsl_bspline_workspace * w);
double gsl_bspline_breakpoint (size_t i, gsl_bspline_workspace * w);
int
gsl_bspline_knots(const gsl_vector *breakpts, gsl_bspline_workspace *w);
int gsl_bspline_knots_uniform(const double a, const double b,
gsl_bspline_workspace *w);
int
gsl_bspline_eval(const double x, gsl_vector *B,
gsl_bspline_workspace *w);
__END_DECLS
#endif /* __GSL_BSPLINE_H__ */
| {
"alphanum_fraction": 0.7259450172,
"avg_line_length": 30.6315789474,
"ext": "h",
"hexsha": "26794ecb9b28ef924b2af48bf7a09ef89db5b651",
"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/bspline/gsl_bspline.h",
"max_issues_count": 12,
"max_issues_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af",
"max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "manggoguy/parsec-modified",
"max_issues_repo_path": "pkgs/libs/gsl/src/bspline/gsl_bspline.h",
"max_line_length": 81,
"max_stars_count": 64,
"max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "manggoguy/parsec-modified",
"max_stars_repo_path": "pkgs/libs/gsl/src/bspline/gsl_bspline.h",
"max_stars_repo_stars_event_max_datetime": "2022-03-24T13:26:53.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-03-06T00:30:56.000Z",
"num_tokens": 612,
"size": 2328
} |
#ifndef GSL_INTERFACE_H
#ifdef HAVE_GSL
#include <gsl/gsl_errno.h>
#include <gsl/gsl_integration.h>
namespace GSL{
static std::string errMsg;
static int gsl_errno;
void error_handler(const char* reason, const char* file, int line, int gsl_errno){
GSL::gsl_errno=gsl_errno;
errMsg=file+std::string(":")+std::to_string(line)+": "+reason;
}
void reset_gsl_error(){ gsl_errno=0; }
///\class
///\brief Container for GSL workspace to be use with the integrators.
class IntegrateWorkspace {
private:
public:
gsl_integration_workspace* ws;
IntegrateWorkspace(size_t limit) {
ws=gsl_integration_workspace_alloc(limit);
}
~IntegrateWorkspace() {
gsl_integration_workspace_free(ws);
}
};
///\brief One dimensional integral using GSL.
/// @param ws GSL integration workspace.
/// @param f Function to integrate.
/// @param a Lower integration limit.
/// @param b Upper integration limit.
/// @param acc Accuracy parameter.
/// @param max_iter Maximum number of iterations to perform the integral.
template<typename FunctionType>
double integrate(IntegrateWorkspace& ws, FunctionType&& f, double a, double b, double acc=1e-7, unsigned int max_iter=10000){
//precondition copied from gsl-1.16/integration/qag.c:122
//assuming epsabs=0 and epsrel=acc
if ((acc < 50 * GSL_DBL_EPSILON || acc < 0.5e-28))
throw std::runtime_error("Specified tolerance too small");
using FPtr=decltype(&f);
double (*wrapper)(double,void*)=[](double x, void* params)->double{
auto& f=*static_cast<FPtr>(params);
return(f(x));
};
double result, error;
gsl_function F;
F.function = wrapper;
F.params = &f;
gsl_integration_qag(&F, a, b, 0, acc, max_iter, GSL_INTEG_GAUSS15, ws.ws, &result, &error);
return(result);
}
///\brief One dimensional integral using GSL.
/// @param f Function to integrate.
/// @param a Lower integration limit.
/// @param b Upper integration limit.
/// @param acc Accuracy parameter.
/// @param max_iter Maximum number of iterations to perform the integral.
template<typename FunctionType>
double integrate(FunctionType&& f, double a, double b, double acc=1e-7, unsigned int max_iter=10000, size_t memory_alloc=10000){
IntegrateWorkspace ws(memory_alloc);
return integrate(ws, f, a, b, acc, max_iter);
}
} //namespace GSL
#endif //HAVE_GSL
#endif //GSL_INTERFACE_H | {
"alphanum_fraction": 0.7160389336,
"avg_line_length": 31.0921052632,
"ext": "h",
"hexsha": "047af7da8362d82b58c03b571468afc4da6d3e46",
"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": "6f99bdbf8f9ffdd25b1babfd9f4b46364ffb033a",
"max_forks_repo_licenses": [
"BSD-2-Clause"
],
"max_forks_repo_name": "cnweaver/AdaptiveQuad",
"max_forks_repo_path": "test/gsl_interface.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "6f99bdbf8f9ffdd25b1babfd9f4b46364ffb033a",
"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": "cnweaver/AdaptiveQuad",
"max_issues_repo_path": "test/gsl_interface.h",
"max_line_length": 129,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "6f99bdbf8f9ffdd25b1babfd9f4b46364ffb033a",
"max_stars_repo_licenses": [
"BSD-2-Clause"
],
"max_stars_repo_name": "cnweaver/AdaptiveQuad",
"max_stars_repo_path": "test/gsl_interface.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 640,
"size": 2363
} |
/* histogram/test2d_trap.c
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Brian Gough
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include <config.h>
#include <stdlib.h>
#include <stdio.h>
#include <gsl/gsl_histogram2d.h>
#include <gsl/gsl_test.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_ieee_utils.h>
#define N 107
#define M 239
static void my_error_handler (const char *reason, const char *file,
int line, int err);
static int status = 0;
void
test2d_trap (void)
{
gsl_histogram2d *h;
double result, lower, upper;
size_t i, j;
gsl_set_error_handler (&my_error_handler);
gsl_ieee_env_setup ();
status = 0;
h = gsl_histogram2d_calloc (0, 10);
gsl_test (!status, "gsl_histogram_calloc traps zero-width histogram");
gsl_test (h != 0,
"gsl_histogram2d_calloc returns NULL for zero-width histogram");
status = 0;
h = gsl_histogram2d_calloc (10, 0);
gsl_test (!status, "gsl_histogram_calloc traps zero-length histogram");
gsl_test (h != 0,
"gsl_histogram2d_calloc returns NULL for zero-length histogram");
status = 0;
h = gsl_histogram2d_calloc_uniform (0, 10, 0.0, 1.0, 0.0, 1.0);
gsl_test (!status,
"gsl_histogram2d_calloc_uniform traps zero-width histogram");
gsl_test (h != 0,
"gsl_histogram2d_calloc_uniform returns NULL for zero-width histogram");
status = 0;
h = gsl_histogram2d_calloc_uniform (10, 0, 0.0, 1.0, 0.0, 1.0);
gsl_test (!status,
"gsl_histogram2d_calloc_uniform traps zero-length histogram");
gsl_test (h != 0,
"gsl_histogram2d_calloc_uniform returns NULL for zero-length histogram");
status = 0;
h = gsl_histogram2d_calloc_uniform (10, 10, 0.0, 1.0, 1.0, 1.0);
gsl_test (!status,
"gsl_histogram2d_calloc_uniform traps equal endpoints");
gsl_test (h != 0,
"gsl_histogram2d_calloc_uniform returns NULL for equal endpoints");
status = 0;
h = gsl_histogram2d_calloc_uniform (10, 10, 1.0, 1.0, 0.0, 1.0);
gsl_test (!status,
"gsl_histogram2d_calloc_uniform traps equal endpoints");
gsl_test (h != 0,
"gsl_histogram2d_calloc_uniform returns NULL for equal endpoints");
status = 0;
h = gsl_histogram2d_calloc_uniform (10, 10, 0.0, 1.0, 2.0, 1.0);
gsl_test (!status,
"gsl_histogram2d_calloc_uniform traps invalid range");
gsl_test (h != 0,
"gsl_histogram2d_calloc_uniform returns NULL for invalid range");
status = 0;
h = gsl_histogram2d_calloc_uniform (10, 10, 2.0, 1.0, 0.0, 1.0);
gsl_test (!status,
"gsl_histogram2d_calloc_uniform traps invalid range");
gsl_test (h != 0,
"gsl_histogram2d_calloc_uniform returns NULL for invalid range");
h = gsl_histogram2d_calloc_uniform (N, M, 0.0, 1.0, 0.0, 1.0);
status = gsl_histogram2d_accumulate (h, 1.0, 0.0, 10.0);
gsl_test (status != GSL_EDOM, "gsl_histogram2d_accumulate traps x at xmax");
status = gsl_histogram2d_accumulate (h, 2.0, 0.0, 100.0);
gsl_test (status != GSL_EDOM, "gsl_histogram2d_accumulate traps x above xmax");
status = gsl_histogram2d_accumulate (h, -1.0, 0.0, 1000.0);
gsl_test (status != GSL_EDOM, "gsl_histogram2d_accumulate traps x below xmin");
status = gsl_histogram2d_accumulate (h, 0.0, 1.0, 10.0);
gsl_test (status != GSL_EDOM, "gsl_histogram2d_accumulate traps y at ymax");
status = gsl_histogram2d_accumulate (h, 0.0, 2.0, 100.0);
gsl_test (status != GSL_EDOM, "gsl_histogram2d_accumulate traps y above ymax");
status = gsl_histogram2d_accumulate (h, 0.0, -1.0, 1000.0);
gsl_test (status != GSL_EDOM, "gsl_histogram2d_accumulate traps y below ymin");
status = gsl_histogram2d_increment (h, 1.0, 0.0);
gsl_test (status != GSL_EDOM, "gsl_histogram2d_increment traps x at xmax");
status = gsl_histogram2d_increment (h, 2.0, 0.0);
gsl_test (status != GSL_EDOM, "gsl_histogram2d_increment traps x above xmax");
status = gsl_histogram2d_increment (h, -1.0, 0.0);
gsl_test (status != GSL_EDOM, "gsl_histogram2d_increment traps x below xmin");
status = gsl_histogram2d_increment (h, 0.0, 1.0);
gsl_test (status != GSL_EDOM, "gsl_histogram2d_increment traps y at ymax");
status = gsl_histogram2d_increment (h, 0.0, 2.0);
gsl_test (status != GSL_EDOM, "gsl_histogram2d_increment traps y above ymax");
status = gsl_histogram2d_increment (h, 0.0, -1.0);
gsl_test (status != GSL_EDOM, "gsl_histogram2d_increment traps y below ymin");
result = gsl_histogram2d_get (h, N, 0);
gsl_test (result != 0, "gsl_histogram2d_get traps x index at nx");
result = gsl_histogram2d_get (h, N + 1, 0);
gsl_test (result != 0, "gsl_histogram2d_get traps x index above nx");
result = gsl_histogram2d_get (h, 0, M);
gsl_test (result != 0, "gsl_histogram2d_get traps y index at ny");
result = gsl_histogram2d_get (h, 0, M + 1);
gsl_test (result != 0, "gsl_histogram2d_get traps y index above ny");
status = gsl_histogram2d_get_xrange (h, N, &lower, &upper);
gsl_test (status != GSL_EDOM, "gsl_histogram2d_get_xrange traps index at nx");
status = gsl_histogram2d_get_xrange (h, N + 1, &lower, &upper);
gsl_test (status != GSL_EDOM, "gsl_histogram2d_get_xrange traps index above nx");
status = gsl_histogram2d_get_yrange (h, M, &lower, &upper);
gsl_test (status != GSL_EDOM, "gsl_histogram2d_get_yrange traps index at ny");
status = gsl_histogram2d_get_yrange (h, M + 1, &lower, &upper);
gsl_test (status != GSL_EDOM, "gsl_histogram2d_get_yrange traps index above ny");
status = 0;
gsl_histogram2d_find (h, -0.01, 0.0, &i, &j);
gsl_test (status != GSL_EDOM, "gsl_histogram2d_find traps x below xmin");
status = 0;
gsl_histogram2d_find (h, 1.0, 0.0, &i, &j);
gsl_test (status != GSL_EDOM, "gsl_histogram2d_find traps x at xmax");
status = 0;
gsl_histogram2d_find (h, 1.1, 0.0, &i, &j);
gsl_test (status != GSL_EDOM, "gsl_histogram2d_find traps x above xmax");
status = 0;
gsl_histogram2d_find (h, 0.0, -0.01, &i, &j);
gsl_test (status != GSL_EDOM, "gsl_histogram2d_find traps y below ymin");
status = 0;
gsl_histogram2d_find (h, 0.0, 1.0, &i, &j);
gsl_test (status != GSL_EDOM, "gsl_histogram2d_find traps y at ymax");
status = 0;
gsl_histogram2d_find (h, 0.0, 1.1, &i, &j);
gsl_test (status != GSL_EDOM, "gsl_histogram2d_find traps y above ymax");
gsl_histogram2d_free (h);
}
static void
my_error_handler (const char *reason, const char *file, int line, int err)
{
if (0)
printf ("(caught [%s:%d: %s (%d)])\n", file, line, reason, err);
status = 1;
}
| {
"alphanum_fraction": 0.6962480964,
"avg_line_length": 35.4068627451,
"ext": "c",
"hexsha": "0e2929c17d818ad200bd536cf01d55d6cfe033a8",
"lang": "C",
"max_forks_count": 224,
"max_forks_repo_forks_event_max_datetime": "2022-03-30T00:57:48.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-11-12T21:17:03.000Z",
"max_forks_repo_head_hexsha": "70dc728926a835ba049ddd3f4627ef08db7c95a0",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "utdsimmons/ohpc",
"max_forks_repo_path": "tests/libs/gsl/tests/histogram/test2d_trap.c",
"max_issues_count": 1096,
"max_issues_repo_head_hexsha": "70dc728926a835ba049ddd3f4627ef08db7c95a0",
"max_issues_repo_issues_event_max_datetime": "2022-03-31T21:48:41.000Z",
"max_issues_repo_issues_event_min_datetime": "2015-11-12T09:08:22.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "utdsimmons/ohpc",
"max_issues_repo_path": "tests/libs/gsl/tests/histogram/test2d_trap.c",
"max_line_length": 83,
"max_stars_count": 692,
"max_stars_repo_head_hexsha": "70dc728926a835ba049ddd3f4627ef08db7c95a0",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "utdsimmons/ohpc",
"max_stars_repo_path": "tests/libs/gsl/tests/histogram/test2d_trap.c",
"max_stars_repo_stars_event_max_datetime": "2022-03-30T03:45:59.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-11-12T13:56:43.000Z",
"num_tokens": 2335,
"size": 7223
} |
/* hmm.c v0.0
Andrew D. Kern 8/24/05
*/
#include "hmm.h"
#include "adkGSL.h"
#include <math.h>
#include <assert.h>
#include <string.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_randist.h>
/* returns a pointer to a new instance of an HMM.
Currently an HMM is defined by a transition matrix (pMatrix),
and a vector representing the starting probabilities.
use of initHMM() fills the log score matrices. */
HMM* newHMM(gsl_matrix *pMatrix, gsl_vector *piStart, gsl_vector *piEnd, gsl_vector *otherData ) {
HMM *hmm = (HMM*)malloc(sizeof(HMM));
int i;
hmm->transition_matrix = pMatrix;
hmm->piStart = piStart;
hmm->piEnd = piEnd;
hmm->nstates = pMatrix->size1;
hmm->transition_score_matrix = NULL;
hmm->piStart_scores = NULL;
hmm->piEnd_scores = NULL;
hmm->otherData = otherData;
/* if piStart are NULL, make them uniform */
if (piStart == NULL) {
hmm->piStart = gsl_vector_alloc(pMatrix->size1);
for (i = 0; i < pMatrix->size1; i++)
gsl_vector_set(hmm->piStart, i, 1.0/pMatrix->size1);
}
if (piEnd == NULL) {
hmm->piEnd = gsl_vector_alloc(pMatrix->size1);
for (i = 0; i < pMatrix->size1; i++)
gsl_vector_set(hmm->piEnd, i, 1.0/pMatrix->size1);
}
return hmm;
}
/* initialize an HMM, this makes sure that things are kosher,
it checks that the row sums of the pMatrix == 1, that the sum
of the piStart vector == 1. then it initializes scores */
void initHMM(HMM *hmm){
gsl_matrix *pMatrixLogs;
gsl_vector *piStartLogs, *piEndLogs;
int i, j;
double piEndSum, piStartSum, prob;
//check piStartSum == 1
piStartSum = gsl_vector_sum(hmm->piStart, hmm->nstates);
assert(piStartSum == 1.0);
//make log transformed start probs
piStartLogs = gsl_vector_alloc(hmm->nstates);
for (i = 0; i < hmm->nstates; i++){
prob = gsl_vector_get(hmm->piStart, i);
gsl_vector_set(piStartLogs, i, log(prob));
}
//set hmm piEnd_scores
hmm->piStart_scores = piStartLogs;
//check piEndSum == 1
piEndSum = gsl_vector_sum(hmm->piEnd, hmm->nstates);
assert(piEndSum == 1.0);
//make log transformed start probs
piEndLogs = gsl_vector_alloc(hmm->nstates);
for (i = 0; i < hmm->nstates; i++){
prob = gsl_vector_get(hmm->piEnd, i);
gsl_vector_set(piEndLogs, i, log(prob));
}
//set hmm piEnd_scores
hmm->piEnd_scores = piEndLogs;
//check row sums for markov matrix
for(i = 0; i < hmm->nstates; i++){
assert(gsl_matrix_row_sum(hmm->transition_matrix, i, hmm->nstates) == 1.0);
}
//make log transformed transition matrix
pMatrixLogs = gsl_matrix_alloc(hmm->nstates, hmm->nstates);
for (i = 0; i < hmm->nstates; i++){
for (j = 0; j < hmm->nstates; j++){
prob = gsl_matrix_get(hmm->transition_matrix, i, j);
gsl_matrix_set(pMatrixLogs, i, j, log(prob));
}
}
//set hmm transition_score_matrix
hmm->transition_score_matrix = pMatrixLogs;
}
/* frees an entire hmm */
void freeHMM(HMM *hmm){
if (hmm->transition_matrix)
gsl_matrix_free(hmm->transition_matrix);
if (hmm->transition_score_matrix)
gsl_matrix_free(hmm->transition_score_matrix);
if (hmm->piStart)
gsl_vector_free(hmm->piStart);
if (hmm->piStart_scores)
gsl_vector_free(hmm->piStart_scores);
if (hmm->piEnd)
gsl_vector_free(hmm->piEnd);
if (hmm->piEnd_scores)
gsl_vector_free(hmm->piEnd_scores);
if (hmm->otherData)
gsl_vector_free(hmm->otherData);
free(hmm);
}
/*output hmm values: nstates, transition matrix, piStarts */
void printHMM(HMM *hmm){
printf("hmm output\nstates: %d \ntransition matrix:\n", hmm->nstates);
gsl_matrix_fprintf(stdout, hmm->transition_matrix, "%f");
printf("piStart vector:\n");
gsl_vector_fprintf(stdout, hmm->piStart, "%f");
printf("piEnd vector:\n");
gsl_vector_fprintf(stdout, hmm->piEnd, "%f");
if (hmm->transition_score_matrix != NULL){
printf("transition matrix (logs):\n");
gsl_matrix_fprintf(stdout, hmm->transition_score_matrix, "%f");
}
if (hmm->piStart_scores != NULL){
printf("piStart vector (logs):\n");
gsl_vector_fprintf(stdout, hmm->piStart_scores, "%f");
}
if (hmm->piEnd_scores != NULL){
printf("piEnd vector (logs):\n");
gsl_vector_fprintf(stdout, hmm->piEnd_scores, "%f");
}
if (hmm->otherData != NULL){
// printf("other data:\n");
//gsl_vector_fprintf(stdout, hmm->otherData, "%f");
}
}
/*output transition matrix of hmm values to file */
void printTransitions(HMM *h, char *outfileName){
FILE *outfile;
int i,j;
outfile = fopen(outfileName, "w");
if (outfile == NULL){
fprintf(stderr,"Error opening outfile! ARRRRR!!!!\n");
exit(1);
}
for(i = 0; i < h->nstates; i++){
for(j = 0; j < h->nstates; j++){
fprintf(outfile,"%f\t",gsl_matrix_get(h->transition_matrix,i,j));
}
fprintf(outfile,"\n");
}
fclose(outfile);
}
/* this normalizes the transition matrix so that rows sum to one */
void hmm_normalize_transitions(HMM *hmm){
int i, j;
double rowSum, tempVal;
for(i=0; i < hmm->nstates; i++){
rowSum = 0;
for(j=0; j < hmm->nstates; j++){
rowSum += gsl_matrix_get(hmm->transition_matrix,i,j);
}
if(rowSum == 0){
gsl_matrix_set(hmm->transition_matrix, i, i, 1.0);
}
else{
for(j= 0; j < hmm->nstates;j++){
tempVal = gsl_matrix_get(hmm->transition_matrix, i, j) / rowSum;
gsl_matrix_set(hmm->transition_matrix, i, j, tempVal);
}
}
}
}
void hmm_logify_transitions(HMM *hmm){
int i, j;
double prob;
//set log transition scores
for (i = 0; i < hmm->nstates; i++){
for (j = 0; j < hmm->nstates; j++){
prob = gsl_matrix_get(hmm->transition_matrix, i, j);
gsl_matrix_set(hmm->transition_score_matrix, i, j, log(prob));
}
}
//set log start and end scores
for (i = 0; i < hmm->nstates; i++){
prob = gsl_vector_get(hmm->piStart, i);
gsl_vector_set(hmm->piStart_scores, i, log(prob));
prob = gsl_vector_get(hmm->piEnd, i);
gsl_vector_set(hmm->piEnd_scores, i, log(prob));
}
}
/* forward algorithm- this fills a matrix (alphas) of Nstates * L observations
with the forward log probabilities. a matrix of emission probs (log!!!) with the same
dimensions as the forward matrix must be allocated and passed to this function.
returns probFor. */
double forwardAlg(HMM *hmm, gsl_matrix *alphas, gsl_matrix *emisLogs, int length, int transitionPowerFlag){
int i, j, power, last;
double prob, emit, prevSum, pFor;
gsl_vector_view prevCol;
gsl_vector *tempProbs;
gsl_matrix *logTransitions;
assert(length > 0 && hmm != NULL);
assert(alphas->size1 == hmm->nstates && alphas->size2 == length);
assert(emisLogs->size1 == hmm->nstates && emisLogs->size2 == length);
//initialization
for (i = 0; i < hmm->nstates; i++){
prob = gsl_vector_get(hmm->piStart_scores, i);
emit = gsl_matrix_get(emisLogs, i, 0);
gsl_matrix_set(alphas, i, 0, (prob + emit));
}
//are we using powers of the transition matrix? if so check to see we have location data
if (transitionPowerFlag){
assert(hmm->otherData != NULL);
//set "last" equal to the first location (stored in otherData) here's a totally non general assumption... FIX ME!!!
last = gsl_vector_get(hmm->otherData,0);
}
else {
last = 0; /* not used */
}
//fill em up!
for (j = 1; j < length; j++){ //iterate over obs
for (i = 0; i < hmm->nstates; i++){ //iterate over states
emit = gsl_matrix_get(emisLogs, i, j);
/* are we taking powers here? */
if (transitionPowerFlag){
//get power from data
power = gsl_vector_get(hmm->otherData,j) - last;
//get power of matrix in log scale
logTransitions = gsl_matrix_power_logs(hmm->transition_matrix, power);
prevSum = forwardSumPrevious(hmm, alphas, logTransitions, i, j);
gsl_matrix_free(logTransitions);
}
/* no powers */
else{
prevSum = forwardSumPrevious(hmm, alphas, hmm->transition_score_matrix, i, j);
//fprintf (stderr,"forwardAlg state %2d, index %2d, log.prevSum %g, emit %g\n",i,j,prevSum,emit);
}
gsl_matrix_set(alphas, i, j, (emit + prevSum));
}
if (transitionPowerFlag){
last = gsl_vector_get(hmm->otherData,j);
}
}
//return P(x)
tempProbs = gsl_vector_alloc(hmm->nstates);
prevCol = gsl_matrix_column(alphas, length - 1);
for(i = 0; i < hmm->nstates; i++){
gsl_vector_set(tempProbs, i, gsl_vector_get(&prevCol.vector, i));
}
pFor = log_sum(tempProbs);
gsl_vector_free(tempProbs);
return(pFor);
}
/* forward algorithm offset- identical to the normal forward algorithm except starts at an arbitrary
offset with respect to the observations. this is useful for getting probabilities from path subsets */
double forwardAlgOffset(HMM *hmm, gsl_matrix *alphas, gsl_matrix *emisLogs, int length, int offset, int transitionPowerFlag){
int i, j, power, last;
double prob, emit, prevSum, pFor;
gsl_vector_view prevCol;
gsl_vector *tempProbs;
gsl_matrix *logTransitions;
assert(length > 0 && hmm != NULL);
assert(alphas->size1 == hmm->nstates && alphas->size2 == length);
//initialization
for (i = 0; i < hmm->nstates; i++){
prob = gsl_vector_get(hmm->piStart_scores, i);
emit = gsl_matrix_get(emisLogs, i, offset);
gsl_matrix_set(alphas, i, 0, (prob + emit));
}
//are we using powers of the transition matrix? if so check to see we have location data
if (transitionPowerFlag){
assert(hmm->otherData != NULL);
//set "last" equal to the first location (stored in otherData) here's a totally non general assumption... FIX ME!!!
last = gsl_vector_get(hmm->otherData,offset);
}
else {
last = 0; /* not used */
}
//fill em up!
for (j = 1; j < length; j++){ //iterate over obs
for (i = 0; i < hmm->nstates; i++){ //iterate over states
emit = gsl_matrix_get(emisLogs, i, j + offset);
/* are we taking powers here? */
if (transitionPowerFlag){
//get power from data
power = gsl_vector_get(hmm->otherData,j + offset) - last;
//get power of matrix in log scale
logTransitions = gsl_matrix_power_logs(hmm->transition_matrix, power);
prevSum = forwardSumPrevious(hmm, alphas, logTransitions, i, j);
gsl_matrix_free(logTransitions);
}
/* no powers */
else{
prevSum = forwardSumPrevious(hmm, alphas, hmm->transition_score_matrix, i, j);
}
gsl_matrix_set(alphas, i, j, (emit + prevSum));
}
if (transitionPowerFlag){
last = gsl_vector_get(hmm->otherData,j+offset);
}
}
//return P(x)
tempProbs = gsl_vector_alloc(hmm->nstates);
prevCol = gsl_matrix_column(alphas, length - 1);
for(i = 0; i < hmm->nstates; i++){
gsl_vector_set(tempProbs, i, gsl_vector_get(&prevCol.vector, i));
}
pFor = log_sum(tempProbs);
gsl_vector_free(tempProbs);
return(pFor);
}
/* backward algorithm- this fills a matrix (betas) of Nstates * L observations
with the backward log probabilities. a matrix of emission probs (log!!!) with the same
dimensions as the backward matrix must be allocated and passed to this function.
returns probBack. */
double backwardAlg(HMM *hmm, gsl_matrix *betas, gsl_matrix *emisLogs, int length, int transitionPowerFlag){
int i, j, last, power;
gsl_vector_view nextCol;
gsl_vector *tempProbs;
gsl_matrix *logTransitions;
double pBack;
assert(length > 0 && hmm != NULL);
assert(betas->size1 == hmm->nstates && betas->size2 == length);
assert(emisLogs->size1 == hmm->nstates && emisLogs->size2 == length);
//initialization
for (i = 0; i < hmm->nstates; i++){
//prob = gsl_vector_get(hmm->piEnd_scores, i);
//emit = gsl_matrix_get(emisLogs, i, length - 1);
gsl_matrix_set(betas, i, length - 1, 0); //initialize to prob = 1.0, log = 0
}
//are we using powers of the transition matrix?
if (transitionPowerFlag){
assert(hmm->otherData != NULL);
//set "last" equal to the last location (stored in otherData) here's a totally non general assumption... FIX ME!!!
last = gsl_vector_get(hmm->otherData,length - 1);
}
else {
last = 0; /* not used */
}
//fill em up!
for (j = length - 2; j >=0; j--){ //iterate over obs
for (i = 0; i < hmm->nstates; i++){ //iterate over states
/* are we taking powers here? */
if (transitionPowerFlag){
//get power from data
power = last - gsl_vector_get(hmm->otherData,j);
//get power of matrix in log scale
logTransitions = gsl_matrix_power_logs(hmm->transition_matrix, power);
gsl_matrix_set(betas, i, j, backwardSumNext(hmm, betas,logTransitions,emisLogs, i, j));
gsl_matrix_free(logTransitions);
}
else{
gsl_matrix_set(betas, i, j, backwardSumNext(hmm, betas,hmm->transition_score_matrix,emisLogs, i, j));
}
}
if (transitionPowerFlag){
last = gsl_vector_get(hmm->otherData,j);
}
}
//return P(x)
tempProbs = gsl_vector_alloc(hmm->nstates);
nextCol = gsl_matrix_column(betas, 0);
for(i = 0; i < hmm->nstates; i++){
gsl_vector_set(tempProbs, i, (gsl_vector_get(&nextCol.vector, i) + gsl_matrix_get(emisLogs, i, 0) + gsl_vector_get(hmm->piStart_scores, i)));
}
pBack = log_sum(tempProbs);
gsl_vector_free(tempProbs);
return(pBack);
}
/* posterior probs- this fills a matrix (postProbMat) of nstates * L observations with the
posterior prob (not log !!) of being in that state at time i given the observations and the model.
calls forwardAlg and backwardAlg, checks that prob of observations determined by
forward and backward are (nearly) equal, and also (nearly) equal the sum of each column
before normalization to postProbMat.
a matrix of emission probs (log!!!) of dimensions nstates * L observations must be supplied. */
void posteriorProbs(HMM *hmm, gsl_matrix *postProbMat, gsl_matrix *emisLogs, int length, int transitionPowerFlag){
gsl_matrix *alphas, *betas;
gsl_vector *tempVec;
int i, j;
double pFor, pBack, sumProb;
//allocate matrices for forwards and backwards algs.
alphas = gsl_matrix_alloc(hmm->nstates, length);
betas = gsl_matrix_alloc(hmm->nstates, length);
//run forwards/backwards
pFor = forwardAlg(hmm, alphas, emisLogs, length, transitionPowerFlag);
pBack = backwardAlg(hmm, betas, emisLogs, length, transitionPowerFlag);
//check that Forward and Backward look okay
//assert(fabs(pFor - pBack) < 0.01);
//do the posterior probability thing- okay sir pull the switch
tempVec = gsl_vector_alloc(hmm->nstates);
for(j=0; j < length; j++){
//first get sum for denominator
for(i = 0; i < hmm->nstates; i++){
gsl_vector_set(tempVec, i, (gsl_matrix_get(alphas,i,j) + gsl_matrix_get(betas,i,j)));
}
sumProb = log_sum(tempVec);
//check that sum looks like pFor
assert(fabs(pFor - sumProb) < 0.01);
//then calculate marginal and set value (not log)
for(i = 0; i < hmm->nstates; i++){
gsl_matrix_set(postProbMat, i, j, exp(gsl_matrix_get(alphas,i,j) + gsl_matrix_get(betas,i,j) - sumProb));
}
}
//cleanup
gsl_matrix_free(alphas);
gsl_matrix_free(betas);
gsl_vector_free(tempVec);
}
/* posterior probs reduced- this fills a matrix of nstates * L observations with the
posterior probs as above except this time takes alphas and betas as args */
void posteriorProbsReduced(HMM *hmm, gsl_matrix *postProbMat, double pFor, gsl_matrix *alphas, gsl_matrix *betas, gsl_matrix *emisLogs, int length, int transitionPowerFlag){
gsl_vector *tempVec;
int i, j;
double sumProb;
//do the posterior probability thing- okay sir pull the switch
tempVec = gsl_vector_alloc(hmm->nstates);
for(j=0; j < length; j++){
//first get sum for denominator
for(i = 0; i < hmm->nstates; i++){
gsl_vector_set(tempVec, i, (gsl_matrix_get(alphas,i,j) + gsl_matrix_get(betas,i,j)));
}
sumProb = log_sum(tempVec);
//check that sum looks like pFor
//assert(fabs(pFor - sumProb) < 0.01);
//then calculate marginal and set value (not log)
for(i = 0; i < hmm->nstates; i++){
gsl_matrix_set(postProbMat, i, j, exp(gsl_matrix_get(alphas,i,j) + gsl_matrix_get(betas,i,j) - sumProb));
}
}
//cleanup
gsl_vector_free(tempVec);
}
/* posterior probs reduced log- this fills a matrix of nstates * L observations with the
posterior probs as above except this time takes alphas and betas as args */
void posteriorProbsReducedLog(HMM *hmm, gsl_matrix *postProbMat, double pFor, gsl_matrix *alphas, gsl_matrix *betas, gsl_matrix *emisLogs, int length, int transitionPowerFlag){
gsl_vector *tempVec;
int i, j;
double sumProb;
//do the posterior probability thing- okay sir pull the switch
tempVec = gsl_vector_alloc(hmm->nstates);
for(j=0; j < length; j++){
//first get sum for denominator
for(i = 0; i < hmm->nstates; i++){
gsl_vector_set(tempVec, i, (gsl_matrix_get(alphas,i,j) + gsl_matrix_get(betas,i,j)));
}
sumProb = log_sum(tempVec);
//check that sum looks like pFor
//assert(fabs(pFor - sumProb) < 0.01);
//then calculate marginal and set value
for(i = 0; i < hmm->nstates; i++){
gsl_matrix_set(postProbMat, i, j, gsl_matrix_get(alphas,i,j) + gsl_matrix_get(betas,i,j) - sumProb);
}
}
//cleanup
gsl_vector_free(tempVec);
}
/* meant to computer prob{state_i_t, state_j_t+1 | data, model} -- for restimating transitions, takes as an arg *jpMatArray an
array of gsl_matrix structs representing joint posterior probabilities -- log scale so need log posts */
void jointPosteriorProbsReduced(HMM *hmm, gsl_matrix **jpMatArray, double pFor, gsl_matrix *alphas, gsl_matrix *betas, gsl_matrix *emisLogs, int length, int transitionPowerFlag){
int i, j, t;
double sumProb, val = 0;
gsl_matrix *powTrans;
//for each obs
for(t=0; t < length - 1; t++){
gsl_matrix_set_all(jpMatArray[t],0);
//iterate i,j states
for(i = 0; i < hmm->nstates; i++){
for(j = 0; j < hmm->nstates; j++){
//transition stuff
if (transitionPowerFlag){
if (gsl_vector_get(hmm->otherData,t+1) - gsl_vector_get(hmm->otherData, t) > 1){
powTrans = gsl_matrix_power_logs(hmm->transition_matrix, gsl_vector_get(hmm->otherData,t+1) \
- gsl_vector_get(hmm->otherData, t));
val = gsl_matrix_get(alphas, i, t) + gsl_matrix_get(powTrans, i, j) \
+ gsl_matrix_get(emisLogs, j, t+1) + gsl_matrix_get(betas, j, t+1) - pFor;
gsl_matrix_free(powTrans);
}
else{
val = gsl_matrix_get(alphas, i, t) + gsl_matrix_get(hmm->transition_score_matrix, i, j) \
+ gsl_matrix_get(emisLogs, j, t+1) + gsl_matrix_get(betas, j, t+1) - pFor;
}
}
else{
val = gsl_matrix_get(alphas, i, t) + gsl_matrix_get(hmm->transition_score_matrix, i, j) \
+ gsl_matrix_get(emisLogs, j, t+1) + gsl_matrix_get(betas, j, t+1) - pFor;
}
//set i,j value in gsl_matrix at t
gsl_matrix_set(jpMatArray[t], i, j, val);
}
}
}
}
/*restimateTransitions-- uses posteriors and joint posteriors to reestimate the transition matrix based on EM */
void reestimateTransitions(HMM *hmm, gsl_matrix *postProbMat, gsl_matrix **jpMatArray, double pFor, gsl_matrix *alphas, \
gsl_matrix *betas, gsl_matrix *emisLogs, int length, int transitionPowerFlag){
double sum_gamma, sum_cosi, val;
int i, j, t,k;
gsl_vector *tmpVec1, *tmpVec2;
gsl_matrix *tempTrans, *powTrans;
gsl_vector *rowSums;
/* this is the joint posterior method- currently not operational */
/*
//calculate joints, no reason to do it twice...
// jointPosteriorProbsReduced(hmm, jpMatArray, pFor, alphas, betas, emisLogs, length ,transitionPowerFlag);
//allocate tmpVecs
tmpVec1 = gsl_vector_alloc(length - 2);
tmpVec2 = gsl_vector_alloc(length - 2);
//iterate over states
for(i = 0; i < hmm->nstates; i++){
for(j = 0; j < hmm->nstates; j++){
gsl_vector_set_all(tmpVec1,0);
gsl_vector_set_all(tmpVec2,0);
//sum up numerator and denom
for(t = 1; t < length - 1; t++){
// gsl_vector_set(tmpVec1, t - 1, gsl_matrix_get(postProbMat,i,t));
//gsl_vector_set(tmpVec2, t - 1, gsl_matrix_get(jpMatArray[t],i,j));
sum_gamma += gsl_matrix_get(postProbMat,i,t);
sum_cosi += gsl_matrix_get(jpMatArray[t],i,j);
}
//gsl_matrix_set(hmm->transition_matrix, i, j, exp(log_sum(tmpVec1) - log_sum(tmpVec2)));
// hmm_logify_transitions(hmm);
gsl_matrix_set(hmm->transition_matrix, i, j, sum_cosi / sum_gamma);
gsl_matrix_set(hmm->transition_score_matrix, i, j, log(sum_cosi / sum_gamma));
}
}
*/
/* older method */
tempTrans = gsl_matrix_alloc(hmm->nstates,hmm->nstates);
rowSums = gsl_vector_alloc(hmm->nstates);
gsl_matrix_set_all(tempTrans,0.0);
gsl_vector_set_all(rowSums, 0.0);
for(i = 1; i < length - 1; i++){
for(j = 0; j < hmm->nstates; j++){
for(k = 0; k < hmm->nstates; k++){
if (transitionPowerFlag){
if (gsl_vector_get(hmm->otherData,i + 1) - gsl_vector_get(hmm->otherData, i ) > 1){
powTrans = gsl_matrix_power_logs(hmm->transition_matrix, \
gsl_vector_get(hmm->otherData,i + 1) - gsl_vector_get(hmm->otherData, i));
val = exp(gsl_matrix_get(alphas, j, i) + gsl_matrix_get(powTrans, j, k) \
+ gsl_matrix_get(emisLogs, k, i+1) + gsl_matrix_get(betas, k, i+1) - pFor);
gsl_matrix_free(powTrans);
}
else{
val = exp(gsl_matrix_get(alphas, j, i) + gsl_matrix_get(hmm->transition_score_matrix, j, k) \
+ gsl_matrix_get(emisLogs, k, i+1) + gsl_matrix_get(betas, k, i+1) - pFor);
}
}
else{
val = exp(gsl_matrix_get(alphas, j, i) + gsl_matrix_get(hmm->transition_score_matrix, j, k) \
+ gsl_matrix_get(emisLogs, k, i+1) + gsl_matrix_get(betas, k, i+1) - pFor);
}
gsl_matrix_set(tempTrans, j, k, gsl_matrix_get(tempTrans,j,k) + val);
gsl_vector_set(rowSums, j, gsl_vector_get(rowSums, j) + val);
}
}
}
//update transition scores
for(j = 0; j < hmm->nstates; j++){
for(k = 0; k < hmm->nstates; k++){
val = gsl_matrix_get(tempTrans, j, k) / gsl_vector_get(rowSums, j);
gsl_matrix_set(hmm->transition_matrix, j, k, val);
gsl_matrix_set(hmm->transition_score_matrix, j, k, log(val));
}
}
gsl_matrix_free(tempTrans);
gsl_vector_free(rowSums);
}
/*restimateTransitions_vanilla-- uses posteriors to reestimate the transition matrix based on EM */
void reestimateTransitions_vanilla(HMM *hmm, double pFor, gsl_matrix *alphas, \
gsl_matrix *betas, gsl_matrix *emisLogs, int length){
double val;
int i, j,k;
gsl_vector *rowSums;
gsl_matrix *tempTrans;
/* older method */
tempTrans = gsl_matrix_alloc(hmm->nstates,hmm->nstates);
gsl_matrix_set_all(tempTrans,0.0);
rowSums = gsl_vector_alloc(hmm->nstates);
gsl_vector_set_all(rowSums, 0.0);
for(i = 1; i < length - 1; i++){
for(j = 0; j < hmm->nstates; j++){
for(k = 0; k < hmm->nstates; k++){
val = exp(gsl_matrix_get(alphas, j, i) + gsl_matrix_get(hmm->transition_score_matrix, j, k) \
+ gsl_matrix_get(emisLogs, k, i+1) + gsl_matrix_get(betas, k, i+1) - pFor);
gsl_matrix_set(tempTrans, j, k, gsl_matrix_get(tempTrans,j,k) + val);
gsl_vector_set(rowSums, j, gsl_vector_get(rowSums, j) + val);
}
}
}
//update transition scores
for(j = 0; j < hmm->nstates; j++){
for(k = 0; k < hmm->nstates; k++){
val = gsl_matrix_get(tempTrans, j, k) / gsl_vector_get(rowSums, j);
gsl_matrix_set(hmm->transition_matrix, j, k, val);
gsl_matrix_set(hmm->transition_score_matrix, j, k, log(val));
}
}
gsl_matrix_free(tempTrans);
gsl_vector_free(rowSums);
}
/* posteriorDecode-- fills a vector (posteriorPath) of length L observations
with the most probably state sequence based on posterior probabilities */
void posteriorDecode(HMM *hmm, gsl_vector *posteriorPath, gsl_matrix *posts, int length){
int i, j, maxState;
double maxProb;
assert(length > 0 && hmm != NULL);
assert(posteriorPath->size == length);
assert(posts->size1 == hmm->nstates && posts->size2 == length);
for(i=0; i < length; i++){
maxProb = 0;
maxState = 0;
for(j=0;j < hmm->nstates;j++){
if (gsl_matrix_get(posts, j, i) > maxProb){
maxProb = gsl_matrix_get(posts, j, i);
maxState = j;
}
}
gsl_vector_set(posteriorPath,i,maxState);
}
}
/* viterbi algorithm- this fills a vector (viterbiPath) of length L observations with
the most probable state sequence. it returns the prob of the most probable path.
a matrix of emission probs (log!!!) of dimensions nstates * L observations must be supplied. */
double viterbi(HMM *hmm, gsl_vector *viterbiPath, gsl_matrix *emisLogs, int length, int transitionPowerFlag){
gsl_matrix *deltas, *psi, *logTransitions;
gsl_vector_view col;
int i, j, lastState, tmp, last, power;
double tempProb,prob, emit;
int point;
assert(length > 0 && hmm != NULL);
assert(viterbiPath->size == length);
assert(emisLogs->size1 == hmm->nstates && emisLogs->size2 == length);
//if using transition powers, then check that we have other data
if (transitionPowerFlag){
assert(hmm->otherData != NULL);
//initialize last
last = gsl_vector_get(hmm->otherData,0);
}
else {
last = 0; /* not used */
}
//allocate matrices for deltas (log prob of most prob path to stateN,obsL) and psis (the backpointers)
deltas = gsl_matrix_alloc(hmm->nstates, length);
psi = gsl_matrix_alloc(hmm->nstates, length);
//initialization
for (i = 0; i < hmm->nstates; i++){
prob = gsl_vector_get(hmm->piStart_scores, i);
emit = gsl_matrix_get(emisLogs, i, 0);
gsl_matrix_set(deltas, i, 0, (prob + emit));
gsl_matrix_set(psi, i, 0, 0);
}
point = 666;
//recursion
for (j = 1; j < length; j++){
for(i = 0; i < hmm->nstates; i++){
/* transition powers? */
if (transitionPowerFlag){
power = gsl_vector_get(hmm->otherData,j) - last;
logTransitions = gsl_matrix_power_logs(hmm->transition_matrix, power);
tempProb = viterbiMaxPrevious(hmm, deltas, logTransitions, i, j, &point);
gsl_matrix_free(logTransitions);
}
else{
tempProb = viterbiMaxPrevious(hmm, deltas, hmm->transition_matrix, i, j, &point);
}
gsl_matrix_set(deltas, i, j, tempProb + gsl_matrix_get(emisLogs, i, j));
gsl_matrix_set(psi, i ,j , point);
}
if (transitionPowerFlag){
last = gsl_vector_get(hmm->otherData,j);
}
}
//termination
col = gsl_matrix_column(deltas, length - 1);
lastState = (int) gsl_vector_max_index(&col.vector);
//backtrack
gsl_vector_set(viterbiPath, length - 1, lastState);
for (j = length - 2; j >= 0; j--){
tmp = gsl_matrix_get(psi, lastState, j + 1);
lastState = tmp;
gsl_vector_set(viterbiPath, j , (int) lastState);
}
return gsl_vector_max(&col.vector);
gsl_matrix_free(deltas);
gsl_matrix_free(psi);
}
/* this returns the sum of the previous states for the forward probabilities */
double forwardSumPrevious(HMM *hmm, gsl_matrix *alphas, gsl_matrix *transition_score_matrix_i, int state, int obsIndex){
gsl_vector *tempProbs;
gsl_vector_view prevCol;
int i;
double tempProb;
tempProbs = gsl_vector_alloc(hmm->nstates);
prevCol = gsl_matrix_column(alphas, obsIndex - 1);
for(i = 0; i < hmm->nstates; i++){
tempProb = gsl_vector_get(&prevCol.vector, i) + gsl_matrix_get(transition_score_matrix_i, i, state);
gsl_vector_set(tempProbs, i, tempProb);
}
tempProb = log_sum(tempProbs);
gsl_vector_free(tempProbs);
return(tempProb);
}
/* this returns the sum of the "next" states for the backward probabilities */
double backwardSumNext(HMM *hmm, gsl_matrix *betas, gsl_matrix *transition_score_matrix_j,gsl_matrix *emisLogs, int state, int obsIndex){
gsl_vector *tempProbs;
gsl_vector_view nextCol;
int j;
double tempProb;
tempProbs = gsl_vector_alloc(hmm->nstates);
nextCol = gsl_matrix_column(betas, obsIndex + 1);
for(j = 0; j < hmm->nstates; j++){ //sum over begin states...
tempProb = gsl_vector_get(&nextCol.vector, j) + gsl_matrix_get(transition_score_matrix_j, state, j) + gsl_matrix_get(emisLogs, j,obsIndex + 1) ;
gsl_vector_set(tempProbs, j, tempProb);
}
tempProb = log_sum(tempProbs);
gsl_vector_free(tempProbs);
return(tempProb);
}
/* this returns the max of the previous states for the viterbi algorithm.
it also sets the back pointer (point) to that state. */
double viterbiMaxPrevious(HMM *hmm, gsl_matrix *deltas, gsl_matrix *transition_score_matrix_i, int state, int obsIndex, int *point){
gsl_vector *tempProbs;
gsl_vector_view prevCol;
int i;
double tempProb;
tempProbs = gsl_vector_alloc(hmm->nstates);
prevCol = gsl_matrix_column(deltas, obsIndex - 1);
for(i = 0; i < hmm->nstates; i++){
tempProb = gsl_vector_get(&prevCol.vector, i) + gsl_matrix_get(transition_score_matrix_i, i, state);
gsl_vector_set(tempProbs, i, tempProb);
}
*point = gsl_vector_max_index(tempProbs);
tempProb = gsl_vector_max(tempProbs);
gsl_vector_free(tempProbs);
return(tempProb);
}
/* This computes the log likelihood of an subpath of the data, for a specified set of the states defined
in the vector stateInclusion (1 for include, 0 for exclude). */
double hmm_subpath_score(HMM *hmm, gsl_matrix *emisLogs, gsl_vector *stateInclusion, int begin, int length, int transitionPowerFlag){
gsl_matrix *alphas, *real_trans ;
gsl_vector *real_begin;
int i, j, stateCount;
double score;
//initialize some matrices
alphas = gsl_matrix_alloc(hmm->nstates, length);
real_trans = gsl_matrix_alloc(hmm->nstates, hmm->nstates);
real_begin = gsl_vector_alloc(hmm->nstates);
//count number of states under consideration
stateCount = 0;
for(i = 0; i < hmm->nstates; i++){
stateCount += gsl_vector_get(stateInclusion, i);
}
//keep track of original transition matrix and "begin" vector
gsl_matrix_memcpy(real_trans,hmm->transition_matrix);
gsl_vector_memcpy(real_begin, hmm->piStart);
//set begin states to uniform distribution over states considered in subset
for(i = 0; i < hmm->nstates; i++){
if (gsl_vector_get(stateInclusion,i)){
gsl_vector_set(hmm->piStart, i, 1.0 / stateCount);
}
else{
gsl_vector_set(hmm->piStart, i, 0.0);
}
}
//renomalize transition matrix to reflect states included.
//go through transition matrix, shutting off those which aren't in subset
for(i = 0; i < hmm->nstates; i++){
for(j = 0; j < hmm->nstates; j++){
if (gsl_vector_get(stateInclusion,i) == 0 || gsl_vector_get(stateInclusion,j) == 0){
gsl_matrix_set( hmm->transition_matrix, i, j, 0.0);
}
}
}
//one is the magic number...
hmm_normalize_transitions(hmm);
hmm_logify_transitions(hmm);
//run the forward algorithm to get our answer!
score = forwardAlgOffset(hmm, alphas, emisLogs, length, begin, transitionPowerFlag);
//cleanup
gsl_matrix_memcpy(hmm->transition_matrix, real_trans);
gsl_vector_memcpy(hmm->piStart, real_begin);
hmm_logify_transitions(hmm);
gsl_matrix_free(alphas);
gsl_matrix_free(real_trans);
gsl_vector_free(real_begin);
return(score);
}
/* Calculates the log odds score for two competing sets of states, over a subset of the data
by comparing the ratio of their likelihoods */
double hmm_subpath_log_odds(HMM *hmm, gsl_matrix *emisLogs, gsl_vector *stateInclusion1,
gsl_vector *stateInclusion2,int begin, int length,
int transitionPowerFlag){
double score1, score2;
score1 = hmm_subpath_score(hmm, emisLogs, stateInclusion1, begin,length,transitionPowerFlag);
score2 = hmm_subpath_score(hmm, emisLogs, stateInclusion2, begin,length,transitionPowerFlag);
//printf("scores: %f %f\n",score1,score2);
return(score1 - score2);
}
/* simulatePath-- returns a vector snpNumber long that represents an instance
of the simulated markov state path through the data. takes as arguments,an hmm,
and a pointer to void which actually is an gsl random numb. gen, as well as the observation
number */
gsl_vector *simulatePath(HMM *h, void *r, int obsNumber){
int i, j, pastState;
double sum, rand;
gsl_rng * rn = (gsl_rng *) r;
gsl_vector *path;
path = gsl_vector_alloc(obsNumber);
/*choose initial state, set paths[0] */
rand = gsl_rng_uniform(rn);
sum = 0;
for(i = 0; i < h->nstates; i++){
sum += gsl_vector_get(h->piStart, i);
printf("%f %f\n",rand, sum);
if (rand <= sum){
printf("true\n");
gsl_vector_set(path,0,i);
rand = 2.0;
}
}
/* now go through obs, using transition matrix to choose states */
for(i = 1; i < obsNumber; i++){
pastState = gsl_vector_get(path, i-1);
rand = gsl_rng_uniform(rn);
sum = 0;
for(j = 0; j < h->nstates; j++){
sum += gsl_matrix_get(h->transition_matrix, pastState, j);
if (rand <= sum){
gsl_vector_set(path,i,j);
rand = 2.0;
}
}
}
return(path);
}
/* simulatePathSpaced-- just like simulatePath except takes two
added parameters, a pointer to a gsl_vector which will contain the
simulated snp locations, and a double for the exponential mean */
gsl_vector *simulatePathSpaced(HMM *h, void *r, int obsNumber, gsl_vector *locs, double mu){
int i, j, pastState;
double sum, rand;
gsl_rng * rn = (gsl_rng *) r;
gsl_vector *path;
gsl_matrix *matPower;
path = gsl_vector_alloc(obsNumber);
/*choose initial state, set paths[0] */
rand = gsl_rng_uniform(rn);
sum = 0;
for(i = 0; i < h->nstates; i++){
sum += gsl_vector_get(h->piStart, i);
printf("%f %f\n",rand, sum);
if (rand <= sum){
printf("true\n");
gsl_vector_set(path,0,i);
rand = 2.0;
}
}
/*set initial location to 1 by convention */
gsl_vector_set(locs,0,1);
//now go through obs and simulate spacing -- curently drawn from exp
for(i = 1; i < obsNumber; i++){
rand = gsl_ran_exponential(rn, mu);
gsl_vector_set(locs, i, gsl_vector_get(locs, i - 1) + ceil(rand));
}
/* now go through obs, using transition matrix and powers to choose states */
for(i = 1; i < obsNumber; i++){
pastState = gsl_vector_get(path, i-1);
matPower = gsl_matrix_power(h->transition_matrix, gsl_vector_get(locs,i) - gsl_vector_get(locs,i - 1));
rand = gsl_rng_uniform(rn);
sum = 0;
for(j = 0; j < h->nstates; j++){
sum += gsl_matrix_get(matPower, pastState, j);
if (rand <= sum){
gsl_vector_set(path,i,j);
rand = 2.0;
}
}
gsl_matrix_free(matPower);
}
return(path);
}
| {
"alphanum_fraction": 0.6803213794,
"avg_line_length": 33.865938431,
"ext": "c",
"hexsha": "0fbd9c01646dfa064fb1e3d34aadba8c6ba483be",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "ad97da6f6bc94f91e72d75f37fa33ca949d9bb60",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "andrewkern/segSiteHMM",
"max_forks_repo_path": "hmm/hmm.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "ad97da6f6bc94f91e72d75f37fa33ca949d9bb60",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "andrewkern/segSiteHMM",
"max_issues_repo_path": "hmm/hmm.c",
"max_line_length": 178,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "ad97da6f6bc94f91e72d75f37fa33ca949d9bb60",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "andrewkern/segSiteHMM",
"max_stars_repo_path": "hmm/hmm.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 10270,
"size": 34103
} |
#ifndef GMM_MODEL_H
#define GMM_MODEL_H
#include "DoubleVector.h"
#include "GMM/GmmAggregateNewComp.h"
#include "Handle.h"
#include "LambdaCreationFunctions.h"
#include "Object.h"
#include "PDBVector.h"
#include <gsl/gsl_blas.h>
#include <gsl/gsl_linalg.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_permutation.h>
#include <gsl/gsl_vector.h>
#include <math.h>
#include <vector>
// By Tania, October 2017
using namespace pdb;
/* This class contains our current GMM model, that is:
* - num of dimensions;
* - weights: set of (prior) weights for each component
* - means: mean for each component
* - covars: covariance for each component
* - inv_covars: inverse covariance for each component
* - dets: determinant of each covariance matrix
*/
class GmmModel : public Object {
private:
int ndim = 0;
int k = 0;
Handle<DoubleVector> weights;
Handle<Vector<Handle<DoubleVector>>> means; // k*ndim
Handle<Vector<Handle<DoubleVector>>> covars; // k*ndim*ndim
Handle<Vector<Handle<DoubleVector>>> inv_covars; // k*ndim*ndim
Handle<DoubleVector> dets;
public:
ENABLE_DEEP_COPY
GmmModel() {}
GmmModel(int k, int ndim) {
std::cout << "K= " << k << std::endl;
std::cout << "ndim= " << ndim << std::endl;
this->ndim = ndim;
this->k = k;
this->weights = pdb::makeObject<DoubleVector>(k);
this->dets = pdb::makeObject<DoubleVector>(k);
this->means = pdb::makeObject<Vector<Handle<DoubleVector>>>();
this->covars = pdb::makeObject<Vector<Handle<DoubleVector>>>();
this->inv_covars = pdb::makeObject<Vector<Handle<DoubleVector>>>();
for (int i = 0; i < k; i++) {
this->weights->setDouble(i, 1.0 / k);
this->means->push_back(makeObject<DoubleVector>(ndim));
this->covars->push_back(makeObject<DoubleVector>(ndim * ndim));
this->inv_covars->push_back(makeObject<DoubleVector>(ndim * ndim));
}
std::cout << "Model created!" << std::endl;
}
// this prints the first 10 elements of a DoubleVector
void print_vector(Handle<DoubleVector> v) {
int MAX = 10;
if (v->size < MAX)
MAX = v->size;
for (int i = 0; i < MAX; i++) {
std::cout << i << ": " << v->getDouble(i) << "; ";
}
std::cout << std::endl;
}
// Print current model
void print() {
// Print mean
std::cout << "**Current model**" << std::endl;
std::cout << "Weights: ";
print_vector(this->weights);
for (int i = 0; i < k; i++) {
std::cout << "**Component " << i << std::endl;
std::cout << "Mean: ";
print_vector((*this->means)[i]);
std::cout << "Covar: ";
print_vector((*this->covars)[i]);
std::cout << "Inv covars: ";
print_vector((*this->inv_covars)[i]);
}
}
int getNumK() { return k; }
int getNDim() { return ndim; }
double getWeight(int i) { return this->weights->getDouble(i); }
void updateWeights(std::vector<double> w) {
for (int i = 0; i < k; i++) {
this->weights->setDouble(i, w[i]);
}
std::cout << "updated weights";
print_vector(this->weights);
}
void updateMeans(std::vector<std::vector<double>> &m) {
for (int i = 0; i < k; i++) {
std::cout << "updated mean for comp " << i << std::endl;
double *mean = (*this->means)[i]->getRawData();
for (int j = 0; j < ndim; j++) {
mean[j] = m[i][j];
}
print_vector((*this->means)[i]);
}
}
void updateCovars(std::vector<std::vector<double>> &c) {
for (int i = 0; i < k; i++) {
std::cout << "updated covar for comp " << i << std::endl;
double *covar = (*this->covars)[i]->getRawData();
for (int j = 0; j < (ndim * ndim); j++) {
covar[j] = c[i][j];
}
print_vector((*this->covars)[i]);
}
// calcInvCovars();
}
// It calculates determinants and inverse covariances based on Cholesky
// decomposition
void calcInvCovars() {
for (int i = 0; i < this->getNumK(); i++) {
gsl_matrix_view covar =
gsl_matrix_view_array((*covars)[i]->data->c_ptr(), ndim, ndim);
gsl_matrix_view inv_covar =
gsl_matrix_view_array((*inv_covars)[i]->data->c_ptr(), ndim, ndim);
gsl_matrix_memcpy(&inv_covar.matrix, &covar.matrix);
// gsl_permutation *p = gsl_permutation_alloc(ndim);
gsl_linalg_cholesky_decomp(&inv_covar.matrix);
// Calculate determinant -> logdet
double ax = 0.0;
for (int i = 0; i < ndim; i++) {
ax += log(gsl_matrix_get(&inv_covar.matrix, i, i));
}
// Check for
gsl_linalg_cholesky_invert(&inv_covar.matrix);
dets->setDouble(i, ax);
}
}
// It returns the rvalue, responsability, posterior probability of the
// datapoint
// for GMM component i
double log_normpdf(int i, Handle<DoubleVector> inputData) {
gsl_vector_view data =
gsl_vector_view_array(inputData->data->c_ptr(), ndim);
gsl_vector_view mean =
gsl_vector_view_array((*means)[i]->data->c_ptr(), ndim);
gsl_matrix_view covar =
gsl_matrix_view_array((*covars)[i]->data->c_ptr(), ndim, ndim);
gsl_matrix_view inv_covar =
gsl_matrix_view_array((*inv_covars)[i]->data->c_ptr(), ndim, ndim);
double ax, ay;
int s;
gsl_vector *ym;
gsl_vector *datan = gsl_vector_alloc(ndim);
ax = dets->getDouble(i);
gsl_vector_memcpy(datan, &data.vector);
gsl_vector_sub(datan, &mean.vector);
ym = gsl_vector_alloc(ndim);
gsl_blas_dsymv(CblasUpper, 1.0, &inv_covar.matrix, datan, 0.0, ym);
gsl_blas_ddot(datan, ym, &ay);
gsl_vector_free(ym);
gsl_vector_free(datan);
ay = -ax - 0.5 * ay;
return ay;
}
// It calculates the sum of elements in vector v in log space
// To do this, we extract the maximum factor (maxVal) from
// all the values
double logSumExp(double *v, size_t size) {
double maxVal = v[0];
double sum = 0;
for (int i = 1; i < size; i++) {
if (v[i] > maxVal) {
maxVal = v[i];
}
}
for (int i = 0; i < size; i++) {
sum += exp(v[i] - maxVal);
}
return log(sum) + maxVal;
}
double logSumExp(DoubleVector &vector) {
return logSumExp(vector.getRawData(), vector.size);
}
double logSumExp(Vector<double> &vector) {
return logSumExp(vector.c_ptr(), vector.size());
}
// It uses the partial results from the Aggregate to update the model
double updateModel(GmmAggregateNewComp update) {
const double MIN_COVAR = 1e-6;
double *sumWeights = update.getSumWeights().c_ptr();
double totalSumR = 0.0;
for (int i = 0; i < k; i++) {
totalSumR += sumWeights[i];
}
// Update weights -> weights = sumR/totalSumR
gsl_vector_view gSumWeights = gsl_vector_view_array(sumWeights, k);
gsl_vector_view gweights =
gsl_vector_view_array((*weights).data->c_ptr(), k);
gsl_vector_memcpy(&gweights.vector, &gSumWeights.vector);
gsl_vector_scale(&gweights.vector, 1.0 / totalSumR);
// Update Mean and Covar for each component
for (int i = 0; i < k; i++) {
// Update means -> means = 1/sumR * weightedX
gsl_vector_view mean =
gsl_vector_view_array((*means)[i]->data->c_ptr(), ndim);
gsl_vector_view gsumMean =
gsl_vector_view_array(update.getSumMean(i).c_ptr(), ndim);
gsl_vector_memcpy(&mean.vector, &gsumMean.vector);
gsl_vector_scale(&mean.vector, 1.0 / sumWeights[i]);
// Update covars -> gsumCovarv / sumR - mean*mean^T
gsl_vector_view gsumCovarv =
gsl_vector_view_array(update.getSumCovar(i).c_ptr(), ndim * ndim);
gsl_vector_scale(&gsumCovarv.vector, 1.0 / sumWeights[i]);
gsl_matrix_view gsumCovarm =
gsl_matrix_view_array(update.getSumCovar(i).c_ptr(), ndim, ndim);
gsl_blas_dsyr(CblasUpper, -1.0, &mean.vector, &gsumCovarm.matrix);
// Add constant to diagonal and copy lower triangular
double d;
for (int row = 0; row < ndim; row++) {
d = gsl_matrix_get(&gsumCovarm.matrix, row, row);
gsl_matrix_set(&gsumCovarm.matrix, row, row, d + MIN_COVAR);
for (int col = row + 1; col < ndim; col++) {
// matrix[j][i] = matrix[i][j]
d = gsl_matrix_get(&gsumCovarm.matrix, row, col);
gsl_matrix_set(&gsumCovarm.matrix, col, row, d);
}
}
gsl_vector_view covar =
gsl_vector_view_array((*covars)[i]->data->c_ptr(), ndim * ndim);
gsl_vector_memcpy(&covar.vector, &gsumCovarv.vector);
}
// Finally, calculate inverse covariances and determinants to be used in the
// next iteration
calcInvCovars();
return update.getLogLikelihood();
}
~GmmModel() {}
};
#endif
| {
"alphanum_fraction": 0.6154643927,
"avg_line_length": 28.5460526316,
"ext": "h",
"hexsha": "0a723e111b71b105679ac5eabf0864ce5ee071d5",
"lang": "C",
"max_forks_count": 3,
"max_forks_repo_forks_event_max_datetime": "2022-03-06T19:28:19.000Z",
"max_forks_repo_forks_event_min_datetime": "2022-01-18T02:13:53.000Z",
"max_forks_repo_head_hexsha": "6c2dabd1a3b3f5901a97c788423fdd93cc0015d4",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "venkate5hgunda/CSE598-Spring22-Group22-NetsDB",
"max_forks_repo_path": "src/sharedLibraries/headers/GMM/GmmModel.h",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "6c2dabd1a3b3f5901a97c788423fdd93cc0015d4",
"max_issues_repo_issues_event_max_datetime": "2022-01-28T23:17:14.000Z",
"max_issues_repo_issues_event_min_datetime": "2022-01-28T23:17:14.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "venkate5hgunda/CSE598-Spring22-Group22-NetsDB",
"max_issues_repo_path": "src/sharedLibraries/headers/GMM/GmmModel.h",
"max_line_length": 80,
"max_stars_count": 13,
"max_stars_repo_head_hexsha": "6c2dabd1a3b3f5901a97c788423fdd93cc0015d4",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "venkate5hgunda/CSE598-Spring22-Group22-NetsDB",
"max_stars_repo_path": "src/sharedLibraries/headers/GMM/GmmModel.h",
"max_stars_repo_stars_event_max_datetime": "2022-03-30T02:06:04.000Z",
"max_stars_repo_stars_event_min_datetime": "2022-01-17T16:14:26.000Z",
"num_tokens": 2561,
"size": 8678
} |
#pragma once
/*** mathematics.h:
Mathematical and statistical functions. ***/
/** Avoid including this file twice. **/
#ifndef MATHEMATICS_H
#define MATHEMATICS_H
/** Libraries. **/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <complex.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
/** Constants. **/
#define MATH_PI 3.1415926535897932385 /* Pi. */
#define MATH_2PI 6.2831853071795864770 /* 2 pi. */
#define MATH_PI_2 1.57079632679489661925 /* Pi / 2. */
/* Coordinates / axes. */
#define MATH_X 0 /* Castesian. */
#define MATH_Y 1
#define MATH_Z 2
#define MATH_RADIUS 0 /* Spherical. */
#define MATH_POLAR 1
#define MATH_AZIMUTH 2
#define MATH_MU 1 /* Pseudospherical (mu = cos(polar) replacing polar). */
/** Variables. **/
/* Random numbers. */
gsl_rng *RandomNumberGenerator; /* Random number generator. */
unsigned RandomSeed; /* Random seed. */
unsigned SortComponent = 0; /* Component used for sorting vectors. */
/** Function prototypes. **/
int SortAscending(const void *, const void *);
int SortIndexesAscending(const void *, const void *);
double ScalarProduct(double *, double *, unsigned);
double Norm(double *, unsigned);
double NormSquared(double *, unsigned);
double AngleCosine(double *, double *);
void SphericalToCartesian(double *, double *);
void PseudoSphericalToCartesian(double *, double *);
void CartesianToSpherical(double *, double *);
void CartesianToPseudoSpherical(double *, double *);
void Rotate(double *, double *, unsigned, double);
unsigned GetRandomSeed();
int InitialiseRandom(const gsl_rng_type *);
int FinaliseRandom();
double MetropolisHastings(double *, double *, double *, double *, unsigned, unsigned, unsigned, unsigned, double *, double *, double *,
void (*)(double *, double *, double *, double *, double *, unsigned), double (*)(double *, double *, double *, double *, double *, unsigned),
double (*)(double *));
double ParallelTempering(double *, double *, double *, double *, unsigned, unsigned, unsigned, unsigned, double *, double *, double *,
void (*)(double *, double *, double *, double *, double *, unsigned), double (*)(double *, double *, double *, double *, double *, unsigned),
double (*)(double *), unsigned, double *, double);
void TanWeights(double *, double *, double *, double *, unsigned, unsigned, unsigned, double *, double *, double *,
double (*)(double *, double *, double *, double *, double *, unsigned), unsigned);
double TanNormalisation(double *, unsigned, double *);
double WeightAndSum(double *, double *, unsigned);
void UniformTransition(double *, double *, double *, double *, double *, unsigned);
double UniformTransitionPDF(double *, double *, double *, double *, double *, unsigned);
double PowerLawDeviate(double, double, double);
void IsotropicDirection(double, double *);
void StandardGaussianDeviates(double *);
void GaussianDeviates(double *, double, double);
complex ComplexGaussianDeviates(complex, complex);
/** SortAscending.
- Function designed to be an argument of qsort().
- Sorts the elements of a vector in ascending order. The vector elements are reorganised. **/
int SortAscending(const void *x, const void *y)
{
double difference;
difference = *((double *)x) - *((double *)y);
if (difference > 0.0)
return 1;
else if (difference < 0.0)
return -1;
else
return 0;
}
/** SortIndexesAscending.
- Function designed to be an argument of qsort().
- Sorts the indexes of a vector, in such a way that its elements are arranged in ascending order. The vector remains unchanged.
- 'SortComponent' indicates the component used to sort, in the case that the vector elements have more than one dimension. **/
int SortIndexesAscending(const void *x, const void *y)
{
double difference;
difference = *(*(double **)x + SortComponent) - *(*(double **)y + SortComponent);
if (difference > 0.0)
return 1;
else if (difference < 0.0)
return -1;
else
return 0;
}
/** ScalarProduct.
- Computes the scalar product between two vectors. **/
double ScalarProduct(double *vector_1, double *vector_2, unsigned vector_size)
{
unsigned i;
double product;
/* Compute components product and sum. */
product = 0.0;
for (i = 0; i < vector_size; i++)
product += vector_1[i] * vector_2[i];
return product;
}
/** Norm.
- Computes the norm of a vector. **/
double Norm(double *vector, unsigned vector_size)
{
unsigned i;
double *component_sq, max_component_sq, norm;
/* Generate an auxiliary vector of component squares, in ascending order. */
component_sq = malloc(vector_size * sizeof(double));
for (i = 0; i < vector_size; i++)
component_sq[i] = vector[i] * vector[i];
qsort(component_sq, vector_size, sizeof(double), SortAscending);
/* Divide component squares by the largest one to avoid overflow. */
max_component_sq = component_sq[vector_size-1];
if (max_component_sq <= 0.0) /* All components are null. */
return 0.0;
vector_size--;
for (i = 0; i < vector_size; i++)
component_sq[i] /= max_component_sq;
/* Sum component squares in ascending order, to avoid loss of significance. */
norm = 0.0;
for (i = 0; i < vector_size; i++)
norm += component_sq[i];
norm += 1.0;
/* Renormalise. */
norm = sqrt(max_component_sq * norm);
free(component_sq);
return norm;
}
/** NormSquared.
- Computes the square of the norm of a vector. **/
double NormSquared(double *vector, unsigned vector_size)
{
unsigned i;
double *component_sq, max_component_sq, norm;
/* Generate an auxiliary vector of component squares, in ascending order. */
component_sq = malloc(vector_size * sizeof(double));
for (i = 0; i < vector_size; i++)
component_sq[i] = vector[i] * vector[i];
qsort(component_sq, vector_size, sizeof(double), SortAscending);
/* Divide component squares by the largest one to avoid overflow. */
max_component_sq = component_sq[vector_size-1];
if (max_component_sq <= 0.0) /* All components are null. */
return 0.0;
vector_size--;
for (i = 0; i < vector_size; i++)
component_sq[i] /= max_component_sq;
/* Sum component squares in ascending order, to avoid loss of significance. */
norm = 0.0;
for (i = 0; i < vector_size; i++)
norm += component_sq[i];
norm += 1.0;
/* Renormalise. */
norm *= max_component_sq;
free(component_sq);
return norm;
}
/** AngleCosine.
- Computes the cosine of the angle between two 3D vectors. **/
double AngleCosine(double *vector_1, double *vector_2)
{
double norm_1, norm_2, cosine;
norm_1 = Norm(vector_1, 3);
norm_2 = Norm(vector_2, 3);
if (norm_1 <= 0.0 || norm_2 <= 0.0) /* At least one vector is null. */
return 0.0;
cosine = ScalarProduct(vector_1, vector_2, 3) / (norm_1 * norm_2);
if (cosine > 1.0) /* Correct eventual round-off errors. */
cosine = 1.0;
else if (cosine < -1.0)
cosine = -1.0;
return cosine;
}
/** SphericalToCartesian.
- Converts a 3D vector from spherical (radius, polar angle, azimuth) to Cartesian form.
- Initial and final vectors may be the same. **/
void SphericalToCartesian(double *vec_in, double *vec_out)
{
double sin_polar, cos_polar, radius, azimuth;
radius = vec_in[MATH_RADIUS];
sin_polar = sin(vec_in[MATH_POLAR]);
cos_polar = cos(vec_in[MATH_POLAR]);
azimuth = vec_in[MATH_AZIMUTH];
vec_out[MATH_X] = radius * sin_polar * cos(azimuth);
vec_out[MATH_Y] = radius * sin_polar * sin(azimuth);
vec_out[MATH_Z] = radius * cos_polar;
}
/** PseudoSphericalToCartesian.
- Converts a 3D vector from pseudo spherical (radius, polar angle cosine, azimuth) to Cartesian form.
- Initial and final vectors may be the same. **/
void PseudoSphericalToCartesian(double *vec_in, double *vec_out)
{
double cos_polar, sin_polar, radius, azimuth;
radius = vec_in[MATH_RADIUS];
azimuth = vec_in[MATH_AZIMUTH];
cos_polar = vec_in[MATH_MU];
sin_polar = 1.0 - cos_polar * cos_polar;
if (sin_polar <= 0.0) /* Correct eventual round-off errors. */
sin_polar = 0.0;
else
sin_polar = sqrt(sin_polar);
vec_out[MATH_X] = radius * sin_polar * cos(azimuth);
vec_out[MATH_Y] = radius * sin_polar * sin(azimuth);
vec_out[MATH_Z] = radius * cos_polar;
}
/** CartesianToSpherical.
- Converts a 3D vector from Cartesian to spherical (radius, polar angle, azimuth) form.
- Initial and final vectors may be the same. **/
void CartesianToSpherical(double *vec_in, double *vec_out)
{
double radius, azimuth, polar;
radius = Norm(vec_in, 3);
if (radius > 0.0)
polar = acos(vec_in[MATH_Z] / radius);
else
polar = 0.0;
azimuth = atan2(vec_in[MATH_Y], vec_in[MATH_X]);
vec_out[MATH_RADIUS] = radius;
vec_out[MATH_POLAR] = polar;
vec_out[MATH_AZIMUTH] = azimuth;
}
/** CartesianToPseudoSpherical.
- Converts a 3D vector from Cartesian to pseudo spherical (radius, polar angle cosine, azimuth) form.
- Initial and final vectors may be the same. **/
void CartesianToPseudoSpherical(double *vec_in, double *vec_out)
{
double radius, cos_polar, azimuth;
radius = Norm(vec_in, 3);
if (radius > 0.0)
cos_polar = vec_in[MATH_Z] / radius;
else
cos_polar = 1.0;
azimuth = atan2(vec_in[MATH_Y], vec_in[MATH_X]);
vec_out[MATH_RADIUS] = radius;
vec_out[MATH_MU] = cos_polar;
vec_out[MATH_AZIMUTH] = azimuth;
}
/** Rotate.
- Rotates a vector.
- Vector is rotated counterclockwise (or axes clockwise) as seen from the tip of the rotation axis specified by argument 'axis'.
- Initial and final vectors may be the same. **/
void Rotate(double *vec_in, double *vec_out, unsigned axis, double angle)
{
unsigned i, j;
double cos_angle, sin_angle, x, y;
cos_angle = cos(angle);
sin_angle = sin(angle);
axis %= 3;
vec_out[axis] = vec_in[axis];
i = (axis + 1) % 3;
j = (axis + 2) % 3;
x = vec_in[i];
y = vec_in[j];
vec_out[i] = x * cos_angle - y * sin_angle;
vec_out[j] = x * sin_angle + y * cos_angle;
}
/** GetRandomSeed.
- Provides a random seed by reading garbage from /dev/urandom. **/
unsigned GetRandomSeed()
{
FILE *random_file;
unsigned seed;
int error;
seed = 0;
random_file = fopen("/dev/urandom", "rb");
if (!random_file)
return 0;
do
{
error = fread(&seed, 1, sizeof(unsigned int), random_file);
if (error != sizeof(unsigned int))
return 0;
}
while (!seed);
fclose(random_file);
return seed;
}
/** InitialiseRandom.
- Initialises the random number generator. **/
int InitialiseRandom(const gsl_rng_type *random_generator)
{
RandomSeed = GetRandomSeed();
if (!RandomSeed)
return EXIT_FAILURE;
RandomNumberGenerator = gsl_rng_alloc(random_generator);
if (!RandomNumberGenerator)
return EXIT_FAILURE;
gsl_rng_set(RandomNumberGenerator, RandomSeed);
return EXIT_SUCCESS;
}
/** FinaliseRandom.
- Finalises the random number generator. **/
int FinaliseRandom()
{
/* Release random number generator memory. */
if (RandomNumberGenerator)
{
gsl_rng_free(RandomNumberGenerator);
return EXIT_SUCCESS;
}
return EXIT_FAILURE;
}
/** MetropolisHastings.
- Constructs a Markov chain using Metropolis-Hastings sampling from a given PDF ('sampling_pdf').
- 'states' contains the actual Markov chain, comprising 'chain_size' elements. Each element contains 'state_size' doubles. The initial state must be stored in
the first element of 'states'. 'states' must be allocated by the calling function.
- 'proposals' is the chain of proposals derived from each state (same length and element size as 'states'). It must be allocated by the calling function.
- 'lower_bound' and 'upper_bound' must contain the absolute bounds for the variables defining the state.
- 'step' must contain the parameter defining the size of the transition step.
- 'sampling_pdf' must point to a function computing the PDF sampled by the Markov chain. Its only argument is a state of the chain; any other parameter must be
passed through global variables.
- 'transition_pdf' must point to a function computing the PDF of a Metropolis-Hastings transition, given a Markov chain state. Its arguments are the final and
initial states of the transition, in this order. Any other parameter must be passed through global variables.
- 'transition' must point to a function computing the proposed final state of a Metropolis-Hastings transition, given a Markov chain state. Its arguments are the
final and initial states of the transition, in this order. Any other parameter must be passed through global variables.
- 'proposals_PDF' is an array of doubles of the same length of the Markov chain. It must be allocated by the calling function if storage of sampling PDF values
for the proposals is desired, or set to NULL otherwise.
- 'states_PDF' is an array of doubles of the same length of the Markov chain. It must be allocated by the calling function if storage of sampling PDF values
for the states is desired, or set to NULL otherwise.
- If the initial state set in 'states' has a null value of the sampling PDF, the first transition probability is set to unity. Once a state with a non-null value
of the sampling PDF is reached, the sampling PDF values do not vanish over the rest of the Markov chain by construction.
- The order of the state and proposal chains is the following: any element of 'proposals' is sampled from the corresponding element of 'states', whereas any
element of 'states' (except the first one) is the previous element of either 'states' or 'proposals'.
- If 'save_states' is set to null, only the final state and proposal are given. Otherwise, the full chains are saved.
- If 'log_flag' is non null, 'sampling_pdf' is assumed to give the natural logarithm of the PDF.
- Returns the acceptance ratio of the chain. **/
double MetropolisHastings(double *states, double *proposals, double *proposals_pdf, double *states_pdf, unsigned state_size, unsigned chain_size, unsigned save_states,
unsigned log_flag, double *lower_bound, double *upper_bound, double *step,
void (*transition)(double *, double *, double *, double *, double *, unsigned),
double (*transition_pdf)(double *, double *, double *, double *, double *, unsigned), double (*sampling_pdf)(double *))
{
unsigned i, accepted_transitions, state_size_bytes;
double direct_transition_pdf, inverse_transition_pdf, pdf_ratio, state_pdf, proposal_pdf, *proposal, *state, *old_state, acceptance_ratio;
/* Set initial stuff. */
state_size_bytes = state_size * sizeof(double);
proposal = proposals;
state = states;
state_pdf = sampling_pdf(state);
if (states_pdf)
states_pdf[0] = state_pdf;
/* Construct the Markov chain. */
accepted_transitions = 0;
chain_size--;
for (i = 0; i < chain_size; i++)
{
/* Set new proposal. */
transition(proposal, state, lower_bound, upper_bound, step, state_size);
proposal_pdf = sampling_pdf(proposal);
if (proposals_pdf && save_states)
proposals_pdf[i] = proposal_pdf;
/* Compute transition probabilities. */
direct_transition_pdf = transition_pdf(proposal, state, lower_bound, upper_bound, step, state_size);
inverse_transition_pdf = transition_pdf(state, proposal, lower_bound, upper_bound, step, state_size);
if (!log_flag && state_pdf <= 0.0)
pdf_ratio = 1.1;
else if (direct_transition_pdf <= 0.0)
pdf_ratio = -0.1;
else if (log_flag)
pdf_ratio = exp(proposal_pdf - state_pdf) * inverse_transition_pdf / direct_transition_pdf;
else
pdf_ratio = proposal_pdf * inverse_transition_pdf / (state_pdf * direct_transition_pdf);
/* Accept of reject transition. */
if (save_states)
{
old_state = state;
state += state_size;
}
if (gsl_rng_uniform(RandomNumberGenerator) < pdf_ratio)
{
memcpy(state, proposal, state_size_bytes);
state_pdf = proposal_pdf;
accepted_transitions++;
}
else if (save_states)
memcpy(state, old_state, state_size_bytes);
if (save_states)
{
proposal += state_size;
if (states_pdf)
states_pdf[i+1] = state_pdf;
}
}
/* Compute final stuff. */
transition(proposal, state, lower_bound, upper_bound, step, state_size);
acceptance_ratio = accepted_transitions / (double) chain_size;
if (proposals_pdf && save_states)
proposals_pdf[chain_size] = sampling_pdf(proposal);
return acceptance_ratio;
}
/** ParallelTempering.
- Constructs a Markov chain using Metropolis-Hastings sampling from a given PDF ('sampling_pdf'), with parallel tempering.
- 'states' contains the cold Markov chain, comprising 'chain_size' elements. Each element contains 'state_size' doubles. The initial state must be stored in
the first element of 'states'. 'states' must be allocated by the calling function.
- 'proposals' is the chain of proposals derived from each state (same length and element size as 'states'). It must be allocated by the calling function.
- 'lower_bound' and 'upper_bound' must contain the absolute bounds for the variables defining the state.
- 'step' must contain the parameter defining the size of the transition step.
- 'sampling_pdf' must point to a function computing the PDF sampled by the cold Markov chain. Its only argument is a state of the chain; any other parameter must
be passed through global variables.
- 'transition_pdf' must point to a function computing the PDF of a Metropolis-Hastings transition, given a Markov chain state. Its arguments are the final and
initial states of the transition, in this order. Any other parameter must be passed through global variables.
- 'transition' must point to a function computing the proposed final state of a Metropolis-Hastings transition, given a Markov chain state. Its arguments are the
final and initial states of the transition, in this order. Any other parameter must be passed through global variables.
- 'proposals_PDF' is an array of doubles of the same length of the Markov chain. It must be allocated by the calling function if storage of sampling PDF values
for the proposals is desired, or set to NULL otherwise.
- 'states_PDF' is an array of doubles of the same length of the Markov chain. It must be allocated by the calling function if storage of sampling PDF values
for the states is desired, or set to NULL otherwise.
- If the initial state set in 'states' has a null value of the sampling PDF, the first transition probability is set to unity. Once a state with a non-null value
of the sampling PDF is reached, the sampling PDF values do not vanish over the rest of the Markov chain by construction.
- The order of the state and proposal chains is the following: any element of 'proposals' is sampled from the corresponding element of 'states', whereas any
element of 'states' (except the first one) is the previous element of either 'states' or 'proposals'.
- If 'save_states' is set to null, only the final state and proposal are given. Otherwise, the full chains are saved.
- If 'log_flag' is non null, 'sampling_pdf' is assumed to give the natural logarithm of the PDF.
- The number of hot chains in the parallel-tempering scheme is 'hot_chains_count', which have tempering factors given by 'tempering_factors'.
- 'exchange_probability' gives the probability that two chains are interchanged in a given step.
- Returns the acceptance ratio of the chain. **/
double ParallelTempering(double *states, double *proposals, double *proposals_pdf, double *states_pdf, unsigned state_size, unsigned chain_size, unsigned save_states,
unsigned log_flag, double *lower_bound, double *upper_bound, double *step,
void (*transition)(double *, double *, double *, double *, double *, unsigned),
double (*transition_pdf)(double *, double *, double *, double *, double *, unsigned), double (*sampling_pdf)(double *),
unsigned hot_chains_count, double *tempering_factors, double exchange_probability)
{
unsigned i, j, accepted_transitions, state_size_bytes;
double direct_transition_pdf, inverse_transition_pdf, pdf_ratio, state_pdf, proposal_pdf, *proposal, *state, *old_state, acceptance_ratio, x, *aux_state;
double *cool_state, hot_proposals_pdf, factor, *hot_proposals, *hot_states, *hot_states_pdf, *cool_state_pdf;
/* Set initial stuff. */
state_size_bytes = state_size * sizeof(double);
proposal = proposals;
state = states;
state_pdf = sampling_pdf(state);
if (states_pdf)
states_pdf[0] = state_pdf;
hot_proposals = malloc(hot_chains_count * state_size_bytes);
hot_states = malloc(hot_chains_count * state_size_bytes);
aux_state = malloc(state_size_bytes);
for (i = 0; i < hot_chains_count; i++)
memcpy(hot_states + i * state_size, state, state_size_bytes); /* Copy initial state of cold chain to all hot chains. */
hot_states_pdf = malloc(hot_chains_count * sizeof(double));
for (i = 0; i < hot_chains_count; i++)
{
if (log_flag)
hot_states_pdf[i] = state_pdf * tempering_factors[i];
else
hot_states_pdf[i] = pow(state_pdf, tempering_factors[i]);
}
/* Construct the Markov chains. */
accepted_transitions = 0;
chain_size--;
for (i = 0; i < chain_size; i++)
{
/* Set new proposal for cold chain. */
transition(proposal, state, lower_bound, upper_bound, step, state_size);
proposal_pdf = sampling_pdf(proposal);
if (proposals_pdf && save_states)
proposals_pdf[i] = proposal_pdf;
/* Compute transition probabilities for cold chain. */
direct_transition_pdf = transition_pdf(proposal, state, lower_bound, upper_bound, step, state_size);
inverse_transition_pdf = transition_pdf(state, proposal, lower_bound, upper_bound, step, state_size);
if (!log_flag && state_pdf <= 0.0)
pdf_ratio = 1.1;
else if (direct_transition_pdf <= 0.0)
pdf_ratio = -0.1;
else if (log_flag)
pdf_ratio = exp(proposal_pdf - state_pdf) * inverse_transition_pdf / direct_transition_pdf;
else
pdf_ratio = proposal_pdf * inverse_transition_pdf / (state_pdf * direct_transition_pdf);
/* Accept of reject transition for cold chain. */
if (save_states)
{
old_state = state;
state += state_size;
}
if (gsl_rng_uniform(RandomNumberGenerator) < pdf_ratio)
{
memcpy(state, proposal, state_size_bytes);
state_pdf = proposal_pdf;
accepted_transitions++;
}
else if (save_states)
memcpy(state, old_state, state_size_bytes);
if (save_states)
{
proposal += state_size;
if (states_pdf)
states_pdf[i+1] = state_pdf;
}
/* Hot chains. */
for (j = 0; j < hot_chains_count; j++)
{
/* Set new proposal. */
transition(hot_proposals + j * state_size, hot_states + j * state_size, lower_bound, upper_bound, step, state_size);
hot_proposals_pdf = sampling_pdf(hot_proposals + j * state_size);
if (log_flag)
hot_proposals_pdf *= tempering_factors[j];
else
hot_proposals_pdf = pow(hot_proposals_pdf, tempering_factors[j]);
/* Compute transition probabilities. */
direct_transition_pdf = transition_pdf(hot_proposals + j * state_size, hot_states + j * state_size, lower_bound, upper_bound, step, state_size);
inverse_transition_pdf = transition_pdf(hot_states + j * state_size, hot_proposals + j * state_size, lower_bound, upper_bound, step, state_size);
if (!log_flag && hot_states_pdf[j] <= 0.0)
pdf_ratio = 1.1;
else if (direct_transition_pdf <= 0.0)
pdf_ratio = -0.1;
else if (log_flag)
pdf_ratio = exp(hot_proposals_pdf - hot_states_pdf[j]) * inverse_transition_pdf / direct_transition_pdf;
else
pdf_ratio = hot_proposals_pdf * inverse_transition_pdf / (hot_states_pdf[j] * direct_transition_pdf);
/* Accept of reject transition. */
if (gsl_rng_uniform(RandomNumberGenerator) < pdf_ratio)
{
memcpy(hot_states + j * state_size, hot_proposals + j * state_size, state_size_bytes);
hot_states_pdf[j] = hot_proposals_pdf;
}
}
/* Exchange chain states. */
if (gsl_rng_uniform(RandomNumberGenerator) < exchange_probability)
{
j = gsl_rng_uniform_int(RandomNumberGenerator, hot_chains_count);
factor = tempering_factors[j];
if (j)
{
factor /= tempering_factors[j-1];
cool_state_pdf = hot_states_pdf + j - 1;
cool_state = hot_states + (j - 1) * state_size;
}
else
{
cool_state_pdf = &state_pdf;
cool_state = state;
}
if (log_flag)
pdf_ratio = exp(*cool_state_pdf * (factor - 1.0) + hot_states_pdf[j] * (1.0 / factor - 1.0));
else
pdf_ratio = pow(*cool_state_pdf, factor - 1.0) * pow(hot_states_pdf[j], 1.0 / factor - 1.0);
if (gsl_rng_uniform(RandomNumberGenerator) < pdf_ratio)
{
if (log_flag)
{
x = hot_states_pdf[j];
hot_states_pdf[j] = *cool_state_pdf * factor;
*cool_state_pdf = x / factor;
}
else
{
x = hot_states_pdf[j];
hot_states_pdf[j] = pow(*cool_state_pdf, factor);
*cool_state_pdf = pow(x, 1.0 / factor);
}
memcpy(aux_state, hot_states + j * state_size, state_size_bytes);
memcpy(hot_states + j * state_size, cool_state, state_size_bytes);
memcpy(cool_state, aux_state, state_size_bytes);
}
}
}
transition(proposal, state, lower_bound, upper_bound, step, state_size);
acceptance_ratio = accepted_transitions / (double) chain_size;
if (proposals_pdf && save_states)
proposals_pdf[chain_size] = sampling_pdf(proposal);
free(hot_proposals);
free(hot_states);
free(hot_states_pdf);
free(aux_state);
return acceptance_ratio;
}
/** TanWeights.
- Computes the weights proposed by Tan (2006, J.Comp.Graph.Stat., 15, 735) to use Metropolis-Hastings sampling for the evaluation of integrals via the Monte
Carlo method.
- 'states' contains the actual Markov chain, comprising 'chain_size' elements. Each element contains 'state_size' doubles.
- 'proposals' contains the chain of proposals derived from each state (same length and element size as 'states').
- 'proposals_pdf' is an array of doubles of the same length of the Markov chain, containing the sampling PDF values for the proposals.
- If the present chain is an extension of an old one, 'old_chain_size' is the size of the latter.
- 'weights' is an array of 'chain_size' elements for storing the resulting weights. It must be allocated by the calling function. Elements of 'weights' between
'old_chain_size' and 'chain_size' are erased before computing.
- 'lower_bound' and 'upper_bound' must contain the absolute bounds for the variables defining the state.
- 'step' must contain the parameter defining the size of the transition step.
- 'sort_component' indicates the component of the state used for sorting them, to reduce the computational cost if the PDF is bound.
- 'transition_pdf' must point to a function computing the PDF of a Metropolis-Hastings transition, given a Markov chain state. Its arguments are the final and
initial states of the transition, in this order. Any other parameter must be passed through global variables. **/
void TanWeights(double *states, double *proposals, double *proposals_pdf, double *weights, unsigned state_size, unsigned chain_size, unsigned old_chain_size,
double *lower_bound, double *upper_bound, double *step, double (*transition_pdf)(double *, double *, double *, double *, double *, unsigned),
unsigned sort_component)
{
unsigned i, j, k, m, n;
double *proposal, **pointers, pdf;
if (sort_component >= state_size)
SortComponent = 0;
else
SortComponent = sort_component;
memset(weights + old_chain_size, 0, (chain_size - old_chain_size) * sizeof(double));
pointers = malloc(chain_size * sizeof(double *));
for (i = 0; i < chain_size; i++)
pointers[i] = states + i * state_size;
qsort(pointers, chain_size, sizeof(double *), SortIndexesAscending);
for (i = 0; i < chain_size; i++)
{
k = pointers[i] - states;
m = k / state_size;
proposal = proposals + k;
for (j = i; j < chain_size; j++)
{
n = (pointers[j] - states) / state_size;
if (m < old_chain_size && n < old_chain_size)
continue; /* Avoid re-computation of weights already computed. */
pdf = transition_pdf(proposal, pointers[j], lower_bound, upper_bound, step, state_size);
if (pdf <= 0.0)
break;
weights[m] += pdf;
}
for (j = 1; j <= i; j++)
{
n = (pointers[i-j] - states) / state_size;
if (m < old_chain_size && n < old_chain_size)
continue;
pdf = transition_pdf(proposal, pointers[i-j], lower_bound, upper_bound, step, state_size);
if (pdf <= 0.0)
break;
weights[m] += pdf;
}
if (weights[m] > 0.0)
weights[m] = proposals_pdf[m] / weights[m];
}
free(pointers);
}
/** TanNormalisation.
- Computes the PDF normalisation proposed by Tan (2006, J.Comp.Graph.Stat., 15, 735), together with an estimate of its undertainty ('error').
- 'weights' is the array of weights (of size 'element_count') computed by 'TanWeights'. **/
double TanNormalisation(double *weights, unsigned element_count, double *error)
{
unsigned i;
double norm, **pointers, x;
/* Perform weighted sum. */
pointers = malloc(element_count * sizeof(double *));
for (i = 0; i < element_count; i++)
pointers[i] = weights + i;
qsort(pointers, element_count, sizeof(double *), SortIndexesAscending);
norm = 0.0;
*error = 0.0;
for (i = 0; i < element_count; i++)
{
x = pointers[i][0];
norm += x;
*error += x * x;
}
*error = sqrt(*error - norm * norm / element_count);
free(pointers);
return norm;
}
/** TanMean.
- Computes the mean of a function as proposed by Tan (2006, J.Comp.Graph.Stat., 15, 735), together with an estimate of its undertainty ('error').
- 'weights' is the array of weights (of size 'element_count') computed by 'TanWeights'.
- 'norm' is the PDF normalisation computed by 'TanNormalisation'.
- 'function' is the array of function values (of size 'element_count') at the proposal states. **/
double TanMean(double *weights, double *function, double norm, unsigned element_count, double *error)
{
unsigned i;
double mean, x;
/* Perform weighted sum. */
mean = 0.0;
*error = 0.0;
for (i = 0; i < element_count; i++)
mean += weights[i] * function[i];
mean /= norm;
for (i = 0; i < element_count; i++)
{
x = (function[i] - mean) * weights[i];
*error += x * x;
}
*error = sqrt(*error) / norm;
return mean;
}
/** UniformTransition.
- Samples an n-dimensional transition in a Markov chain, from a uniform PDF.
- 'state' contains the present state of the Markov chain, comprising 'state_size' doubles.
- 'proposal' will store the resulting proposed state (same size as 'state').
- 'lower_bound' and 'upper_bound' must contain the absolute bounds for the variables defining the state.
- 'step' must contain the parameter defining the size of the transition step. **/
void UniformTransition(double *proposal, double *state, double *lower_bound, double *upper_bound, double *step, unsigned state_size)
{
unsigned i;
double min, max;
for (i = 0; i < state_size; i++)
{
if (step[i] <= 0.0)
proposal[i] = state[i];
else
{
min = state[i] - 0.5 * step[i];
max = min + step[i];
if (min < lower_bound[i])
min = lower_bound[i];
if (max > upper_bound[i])
max = upper_bound[i];
proposal[i] = min + (max - min) * gsl_rng_uniform(RandomNumberGenerator);
}
}
}
/** UniformTransitionPDF.
- Computes the n-dimensional PDF value of a Markov chain transition, using a uniform PDF.
- 'state' contains the state of the Markov chain from which the transition occurs, comprising 'state_size' doubles.
- 'proposal' contains the proposed state of the chain after the transition (same size as 'state').
- 'lower_bound' and 'upper_bound' must contain the absolute bounds for the variables defining the state.
- 'step' must contain the parameter defining the size of the transition step. **/
double UniformTransitionPDF(double *proposal, double *state, double *lower_bound, double *upper_bound, double *step, unsigned state_size)
{
unsigned i;
double min, max, density;
density = 1.0;
for (i = 0; i < state_size; i++)
{
if (step[i] <= 0.0)
continue;
min = state[i] - 0.5 * step[i];
max = min + step[i];
if (min < lower_bound[i])
min = lower_bound[i];
if (max > upper_bound[i])
max = upper_bound[i];
if (proposal[i] < min || proposal[i] > max)
return 0.0;
density /= max - min;
}
return density;
}
/** PowerLawDeviate.
- Generates a power-law deviate with an index 'index' in any closed interval ['min', 'max']. **/
double PowerLawDeviate(double min, double max, double index)
{
double deviate, std_deviate;
std_deviate = gsl_rng_uniform(RandomNumberGenerator);
if (index == -1.0)
deviate = min * exp(std_deviate * log(max / min));
else if (index == 0.0)
deviate = min + (max - min) * std_deviate;
else
{
index += 1.0;
min = pow(min, index);
max = pow(max, index);
deviate = pow(min + (max - min) * std_deviate, 1.0 / index);
}
return deviate;
}
/** IsotropicDirection.
- Generates a random direction isotropically distributed within a cone of a given semi-aperture 'semi_aperture'.
- The output direction has unit norm, by construction.
- Relies on the fact that, for an isotropic distribution of directions in three dimensions, the projection onto any axis is distributed uniformly in [-1,1]. **/
void IsotropicDirection(double semi_aperture, double *direction)
{
double cos_polar, sin_polar, azimuth, cos_polar_max;
/* Sample polar angle cosine with uniform PDF in [cos_polar_max, 1]. */
cos_polar_max = cos(semi_aperture);
cos_polar = cos_polar_max + gsl_rng_uniform(RandomNumberGenerator) * (1.0 - cos_polar_max);
sin_polar = 1.0 - cos_polar * cos_polar;
if (sin_polar > 0.0) /* Correct eventual round-off errors. */
sin_polar = sqrt(sin_polar);
else
sin_polar = 0.0;
/* Sample azimuth with uniform PDF in [0, 2 pi). */
azimuth = MATH_2PI * gsl_rng_uniform(RandomNumberGenerator);
/* Compute direction. */
direction[MATH_X] = sin_polar * cos(azimuth);
direction[MATH_Y] = sin_polar * sin(azimuth);
direction[MATH_Z] = cos_polar;
}
/** StandardGaussianDeviates.
- Generates a couple of standard gaussian deviates.
- Deviates are stored in 'deviates', which must be allocated by the calling program. **/
void StandardGaussianDeviates(double *deviates)
{
double x, y, r;
y = 2.0 * gsl_rng_uniform(RandomNumberGenerator) - 1.0;
do
{
x = y;
y = 2.0 * gsl_rng_uniform(RandomNumberGenerator) - 1.0;
r = x * x + y * y;
}
while (r == 0.0 || r >= 1.0);
r = sqrt(-2.0 * log(r) / r);
deviates[0] = x * r;
deviates[1] = y * r;
}
/** GaussianDeviates.
- Generates a couple of gaussian deviates with mean 'mean' and standard deviation 'std_dev'.
- Deviates are stored in 'deviates', which must be allocated by the calling program. **/
void GaussianDeviates(double *deviates, double mean, double std_dev)
{
double x, y, r;
y = 2.0 * gsl_rng_uniform(RandomNumberGenerator) - 1.0;
do
{
x = y;
y = 2.0 * gsl_rng_uniform(RandomNumberGenerator) - 1.0;
r = x * x + y * y;
}
while (r == 0.0 || r >= 1.0);
r = sqrt(-2.0 * log(r) / r) * std_dev;
deviates[0] = x * r + mean;
deviates[1] = y * r + mean;
}
/** ComplexGaussianDeviates.
- Generates a gaussian deviate with mean 'mean' and standard deviation 'std_dev' in the complex plane. **/
complex ComplexGaussianDeviates(complex mean, complex std_dev)
{
double x, y, r;
complex deviate;
y = 2.0 * gsl_rng_uniform(RandomNumberGenerator) - 1.0;
do
{
x = y;
y = 2.0 * gsl_rng_uniform(RandomNumberGenerator) - 1.0;
r = x * x + y * y;
}
while (r == 0.0 || r >= 1.0);
r = sqrt(-2.0 * log(r) / r);
deviate = mean + r * (x * creal(std_dev) + I * y * cimag(std_dev));
return deviate;
}
#endif
/*** End of 'mathematics.h'. ***/
| {
"alphanum_fraction": 0.6834913477,
"avg_line_length": 37.0704934542,
"ext": "h",
"hexsha": "32f3cf1c0ec8ca27053d3f8245143b0c190c85aa",
"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": "0e4166f04cce27fed2cbd2c7078023c10e0e8d12",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "eduardomgutierrez/RIAF_radproc",
"max_forks_repo_path": "src/lib/nrMath/mathematics.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "0e4166f04cce27fed2cbd2c7078023c10e0e8d12",
"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": "eduardomgutierrez/RIAF_radproc",
"max_issues_repo_path": "src/lib/nrMath/mathematics.h",
"max_line_length": 167,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "0e4166f04cce27fed2cbd2c7078023c10e0e8d12",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "eduardomgutierrez/RIAF_radproc",
"max_stars_repo_path": "src/lib/nrMath/mathematics.h",
"max_stars_repo_stars_event_max_datetime": "2021-08-30T06:56:03.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-08-30T06:56:03.000Z",
"num_tokens": 9415,
"size": 36811
} |
/***************************************************************************
* Copyright (C) 2006 by Reed A. Cartwright *
* reed@scit.us *
* *
* 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 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 EMDEL_H
#define EMDEL_H
#include <boost/config.hpp>
#include <boost/program_options.hpp>
namespace po = boost::program_options;
#include "em.h"
class emdel_app {
public:
emdel_app(int argc, char *argv[]);
virtual ~emdel_app() { }
virtual int run();
std::string args_comment() const;
po::options_description desc;
// use X-Macros to specify argument variables
struct arg_t {
# define XCMD(lname, sname, desc, type, def) type V(lname) ;
# include "emdel.cmds"
# undef XCMD
};
protected:
arg_t arg;
};
#include <ostream>
#include <iterator>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
namespace std {
template<typename _Tp, typename _CharT, typename _Traits>
basic_ostream<_CharT, _Traits>&
operator<<(basic_ostream<_CharT, _Traits>& os, const std::vector<_Tp> &v)
{
if(v.size() == 1)
{
os << v.front();
}
else if(v.size() > 1)
{
std::copy(v.begin(), v.end()-1, std::ostream_iterator<_Tp, _CharT, _Traits>(os, " "));
os << v.back();
}
return os;
}
}
#ifdef BOOST_WINDOWS
# include <process.h>
# define getpid _getpid
#endif
inline unsigned int rand_seed_start()
{
unsigned int u = static_cast<unsigned int>(time(NULL));
unsigned int v = static_cast<unsigned int>(getpid());
v += (v << 15) + (v >> 3); // Spread 5-decimal PID over 32-bit number
return u ^ (v + 0x9e3779b9u + (u<<6) + (u>>2));
}
inline unsigned int rand_seed()
{
static unsigned int u = rand_seed_start();
return (u = u*1664525u + 1013904223u);
}
class gslrand
{
public:
typedef unsigned int int_type;
typedef int_type seed_type;
typedef double real_type;
gslrand() {
//gsl_rng_env_setup();
T = gsl_rng_mt19937;
r = gsl_rng_alloc(T);
}
virtual ~gslrand() {
gsl_rng_free(r);
}
inline void seed(seed_type s) { gsl_rng_set(r, s); }
inline int_type get() { return gsl_rng_get(r); }
inline int_type operator()() { return get(); }
inline int_type uniform() { return get(); }
inline int_type uniform(int_type max) { return gsl_rng_uniform_int(r, max); }
inline real_type uniform01() { return gsl_rng_uniform(r); }
inline int_type geometric(real_type p) { return gsl_ran_geometric(r,p); }
private:
const gsl_rng_type *T;
gsl_rng *r;
};
extern gslrand myrand;
void set_rand_seed(unsigned int u);
#endif
| {
"alphanum_fraction": 0.5961777116,
"avg_line_length": 30.0671641791,
"ext": "h",
"hexsha": "6c6da23916b19c8f5f6d97d5ca43730a7a81f4c2",
"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": "58ea9d4db89c4a1852ba5405ef73c2eca6539ce3",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "reedacartwright/emdel",
"max_forks_repo_path": "src/emdel.h",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "58ea9d4db89c4a1852ba5405ef73c2eca6539ce3",
"max_issues_repo_issues_event_max_datetime": "2021-03-23T22:51:19.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-12-03T16:50:15.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "reedacartwright/emdel",
"max_issues_repo_path": "src/emdel.h",
"max_line_length": 88,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "58ea9d4db89c4a1852ba5405ef73c2eca6539ce3",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "reedacartwright/emdel",
"max_stars_repo_path": "src/emdel.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 937,
"size": 4029
} |
/* linalg/exponential.c
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2002 Gerard Jungman, Brian Gough
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
/* Author: G. Jungman */
/* Calculate the matrix exponential, following
* Moler + Van Loan, SIAM Rev. 20, 801 (1978).
*/
#include <config.h>
#include <stdlib.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_mode.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_blas.h>
#include "gsl_linalg.h"
/* store one of the suggested choices for the
* Taylor series / square method from Moler + VanLoan
*/
struct moler_vanloan_optimal_suggestion
{
int k;
int j;
};
typedef struct moler_vanloan_optimal_suggestion mvl_suggestion_t;
/* table from Moler and Van Loan
* mvl_tab[gsl_mode_t][matrix_norm_group]
*/
static mvl_suggestion_t mvl_tab[3][6] =
{
/* double precision */
{
{ 5, 1 }, { 5, 4 }, { 7, 5 }, { 9, 7 }, { 10, 10 }, { 8, 14 }
},
/* single precision */
{
{ 2, 1 }, { 4, 0 }, { 7, 1 }, { 6, 5 }, { 5, 9 }, { 7, 11 }
},
/* approx precision */
{
{ 1, 0 }, { 3, 0 }, { 5, 1 }, { 4, 5 }, { 4, 8 }, { 2, 11 }
}
};
inline
static double
sup_norm(const gsl_matrix * A)
{
double min, max;
gsl_matrix_minmax(A, &min, &max);
return GSL_MAX_DBL(fabs(min), fabs(max));
}
static
mvl_suggestion_t
obtain_suggestion(const gsl_matrix * A, gsl_mode_t mode)
{
const unsigned int mode_prec = GSL_MODE_PREC(mode);
const double norm_A = sup_norm(A);
if(norm_A < 0.01) return mvl_tab[mode_prec][0];
else if(norm_A < 0.1) return mvl_tab[mode_prec][1];
else if(norm_A < 1.0) return mvl_tab[mode_prec][2];
else if(norm_A < 10.0) return mvl_tab[mode_prec][3];
else if(norm_A < 100.0) return mvl_tab[mode_prec][4];
else if(norm_A < 1000.0) return mvl_tab[mode_prec][5];
else
{
/* outside the table we simply increase the number
* of squarings, bringing the reduced matrix into
* the range of the table; this is obviously suboptimal,
* but that is the price paid for not having those extra
* table entries
*/
const double extra = log(1.01*norm_A/1000.0) / M_LN2;
const int extra_i = (unsigned int) ceil(extra);
mvl_suggestion_t s = mvl_tab[mode][5];
s.j += extra_i;
return s;
}
}
/* use series representation to calculate matrix exponential;
* this is used for small matrices; we use the sup_norm
* to measure the size of the terms in the expansion
*/
static void
matrix_exp_series(
const gsl_matrix * B,
gsl_matrix * eB,
int number_of_terms
)
{
int count;
gsl_matrix * temp = gsl_matrix_calloc(B->size1, B->size2);
/* init the Horner polynomial evaluation,
* eB = 1 + B/number_of_terms; we use
* eB to collect the partial results
*/
gsl_matrix_memcpy(eB, B);
gsl_matrix_scale(eB, 1.0/number_of_terms);
gsl_matrix_add_diagonal(eB, 1.0);
for(count = number_of_terms-1; count >= 1; --count)
{
/* mult_temp = 1 + B eB / count */
gsl_blas_dgemm(CblasNoTrans, CblasNoTrans, 1.0, B, eB, 0.0, temp);
gsl_matrix_scale(temp, 1.0/count);
gsl_matrix_add_diagonal(temp, 1.0);
/* transfer partial result out of temp */
gsl_matrix_memcpy(eB, temp);
}
/* now eB holds the full result; we're done */
gsl_matrix_free(temp);
}
int
gsl_linalg_exponential_ss(
const gsl_matrix * A,
gsl_matrix * eA,
gsl_mode_t mode
)
{
if(A->size1 != A->size2)
{
GSL_ERROR("cannot exponentiate a non-square matrix", GSL_ENOTSQR);
}
else if(A->size1 != eA->size1 || A->size2 != eA->size2)
{
GSL_ERROR("exponential of matrix must have same dimension as matrix", GSL_EBADLEN);
}
else
{
int i;
const mvl_suggestion_t sugg = obtain_suggestion(A, mode);
const double divisor = exp(M_LN2 * sugg.j);
gsl_matrix * reduced_A = gsl_matrix_alloc(A->size1, A->size2);
/* decrease A by the calculated divisor */
gsl_matrix_memcpy(reduced_A, A);
gsl_matrix_scale(reduced_A, 1.0/divisor);
/* calculate exp of reduced matrix; store in eA as temp */
matrix_exp_series(reduced_A, eA, sugg.k);
/* square repeatedly; use reduced_A for scratch */
for(i = 0; i < sugg.j; ++i)
{
gsl_blas_dgemm(CblasNoTrans, CblasNoTrans, 1.0, eA, eA, 0.0, reduced_A);
gsl_matrix_memcpy(eA, reduced_A);
}
gsl_matrix_free(reduced_A);
return GSL_SUCCESS;
}
}
| {
"alphanum_fraction": 0.6673973695,
"avg_line_length": 26.6914893617,
"ext": "c",
"hexsha": "3d0df25c6521684ce0fb306d90d7c523b03a5655",
"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/linalg/exponential.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/linalg/exponential.c",
"max_line_length": 87,
"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/linalg/exponential.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": 1565,
"size": 5018
} |
/* Cholesky Decomposition
*
* Copyright (C) 2000 Thomas Walter
*
* 3 May 2000: Modified for GSL by Brian Gough
*
* 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 2, or (at your option) any
* later version.
*
* This source 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.
*/
/*
* Cholesky decomposition of a symmetrix positive definite matrix.
* This is useful to solve the matrix arising in
* periodic cubic splines
* approximating splines
*
* This algorthm does:
* A = L * L'
* with
* L := lower left triangle matrix
* L' := the transposed form of L.
*
*/
#include <config.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_blas.h>
#include <gsl/gsl_linalg.h>
int
gsl_linalg_cholesky_decomp (gsl_matrix * A)
{
const size_t M = A->size1;
const size_t N = A->size2;
if (M != N)
{
GSL_ERROR("cholesky decomposition requires square matrix", GSL_ENOTSQR);
}
else
{
size_t i,j,k;
int status = 0;
/* Do the first 2 rows explicitly. It is simple, and faster. And
* one can return if the matrix has only 1 or 2 rows.
*/
double A_00 = gsl_matrix_get (A, 0, 0);
double L_00 = sqrt(A_00);
if (A_00 <= 0)
{
status = GSL_EDOM ;
}
gsl_matrix_set (A, 0, 0, L_00);
if (M > 1)
{
double A_10 = gsl_matrix_get (A, 1, 0);
double A_11 = gsl_matrix_get (A, 1, 1);
double L_10 = A_10 / L_00;
double diag = A_11 - L_10 * L_10;
double L_11 = sqrt(diag);
if (diag <= 0)
{
status = GSL_EDOM;
}
gsl_matrix_set (A, 1, 0, L_10);
gsl_matrix_set (A, 1, 1, L_11);
}
for (k = 2; k < M; k++)
{
double A_kk = gsl_matrix_get (A, k, k);
for (i = 0; i < k; i++)
{
double sum = 0;
double A_ki = gsl_matrix_get (A, k, i);
double A_ii = gsl_matrix_get (A, i, i);
gsl_vector_view ci = gsl_matrix_row (A, i);
gsl_vector_view ck = gsl_matrix_row (A, k);
if (i > 0) {
gsl_vector_view di = gsl_vector_subvector(&ci.vector, 0, i);
gsl_vector_view dk = gsl_vector_subvector(&ck.vector, 0, i);
gsl_blas_ddot (&di.vector, &dk.vector, &sum);
}
A_ki = (A_ki - sum) / A_ii;
gsl_matrix_set (A, k, i, A_ki);
}
{
gsl_vector_view ck = gsl_matrix_row (A, k);
gsl_vector_view dk = gsl_vector_subvector (&ck.vector, 0, k);
double sum = gsl_blas_dnrm2 (&dk.vector);
double diag = A_kk - sum * sum;
double L_kk = sqrt(diag);
if (diag <= 0)
{
status = GSL_EDOM;
}
gsl_matrix_set (A, k, k, L_kk);
}
}
/* Now copy the transposed lower triangle to the upper triangle,
* the diagonal is common.
*/
for (i = 1; i < M; i++)
{
for (j = 0; j < i; j++)
{
double A_ij = gsl_matrix_get (A, i, j);
gsl_matrix_set (A, j, i, A_ij);
}
}
if (status == GSL_EDOM)
{
GSL_ERROR ("matrix must be positive definite", GSL_EDOM);
}
return GSL_SUCCESS;
}
}
int
gsl_linalg_cholesky_solve (const gsl_matrix * LLT,
const gsl_vector * b,
gsl_vector * x)
{
if (LLT->size1 != LLT->size2)
{
GSL_ERROR ("cholesky matrix must be square", GSL_ENOTSQR);
}
else if (LLT->size1 != b->size)
{
GSL_ERROR ("matrix size must match b size", GSL_EBADLEN);
}
else if (LLT->size2 != x->size)
{
GSL_ERROR ("matrix size must match solution size", GSL_EBADLEN);
}
else
{
/* Copy x <- b */
gsl_vector_memcpy (x, b);
/* Solve for c using forward-substitution, L c = b */
gsl_blas_dtrsv (CblasLower, CblasNoTrans, CblasNonUnit, LLT, x);
/* Perform back-substitution, U x = c */
gsl_blas_dtrsv (CblasUpper, CblasNoTrans, CblasNonUnit, LLT, x);
return GSL_SUCCESS;
}
}
int
gsl_linalg_cholesky_svx (const gsl_matrix * LLT,
gsl_vector * x)
{
if (LLT->size1 != LLT->size2)
{
GSL_ERROR ("cholesky matrix must be square", GSL_ENOTSQR);
}
else if (LLT->size2 != x->size)
{
GSL_ERROR ("matrix size must match solution size", GSL_EBADLEN);
}
else
{
/* Solve for c using forward-substitution, L c = b */
gsl_blas_dtrsv (CblasLower, CblasNoTrans, CblasNonUnit, LLT, x);
/* Perform back-substitution, U x = c */
gsl_blas_dtrsv (CblasUpper, CblasNoTrans, CblasNonUnit, LLT, x);
return GSL_SUCCESS;
}
}
| {
"alphanum_fraction": 0.5341454411,
"avg_line_length": 24.7397260274,
"ext": "c",
"hexsha": "f7c2203d70cb2cf33d6aa67ac1e169f751c9a6e7",
"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/linalg/cholesky.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/linalg/cholesky.c",
"max_line_length": 78,
"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/linalg/cholesky.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": 1527,
"size": 5418
} |
#include <stdio.h>
#include <stdlib.h>
#include <gsl/gsl_sf_expint.h>
#include <math.h>
/* Calculate the exponential integral function by invoking the GNU scientific
library */
/* Only intended to be used with R; not the most elegant integration but it
may do for now */
/* One argument, the value (double) at which to evaluate Ei(x) */
double x, ei; /* argument to exponential integral, value */
char *program_name; /* name program is invoked under, for errors */
int main(int argc, char* argv[]) {
void usage(void); /* Warn users about proper usage */
program_name = argv[0];
if (argc != 2) {
usage();
}
x = atof(&argv[1][0]);
ei = gsl_sf_expint_E1(x);
printf("%.18e\n",ei);
return(0);
}
void usage(void) {
(void) fprintf(stderr, "Usage is %s [floating-point argument]\n", program_name);
exit(8);
}
| {
"alphanum_fraction": 0.6654719235,
"avg_line_length": 25.3636363636,
"ext": "c",
"hexsha": "fc547bcf167f05fbd4eb0ae81a8e7a62454527a6",
"lang": "C",
"max_forks_count": 4,
"max_forks_repo_forks_event_max_datetime": "2022-03-02T10:29:33.000Z",
"max_forks_repo_forks_event_min_datetime": "2019-05-12T08:50:33.000Z",
"max_forks_repo_head_hexsha": "86bf0ff11882069b47c5663fa8a4ae386e8cb709",
"max_forks_repo_licenses": [
"Unlicense",
"MIT"
],
"max_forks_repo_name": "jguerber/spatialwarnings",
"max_forks_repo_path": "tests/testthat/pli-R-v0.0.3-2007-07-25/exponential-integral/exp_int.c",
"max_issues_count": 59,
"max_issues_repo_head_hexsha": "86bf0ff11882069b47c5663fa8a4ae386e8cb709",
"max_issues_repo_issues_event_max_datetime": "2022-03-10T16:25:24.000Z",
"max_issues_repo_issues_event_min_datetime": "2017-03-07T07:53:48.000Z",
"max_issues_repo_licenses": [
"Unlicense",
"MIT"
],
"max_issues_repo_name": "jguerber/spatialwarnings",
"max_issues_repo_path": "tests/testthat/pli-R-v0.0.3-2007-07-25/exponential-integral/exp_int.c",
"max_line_length": 82,
"max_stars_count": 10,
"max_stars_repo_head_hexsha": "86bf0ff11882069b47c5663fa8a4ae386e8cb709",
"max_stars_repo_licenses": [
"Unlicense",
"MIT"
],
"max_stars_repo_name": "jguerber/spatialwarnings",
"max_stars_repo_path": "tests/testthat/pli-R-v0.0.3-2007-07-25/exponential-integral/exp_int.c",
"max_stars_repo_stars_event_max_datetime": "2022-03-16T11:21:19.000Z",
"max_stars_repo_stars_event_min_datetime": "2018-07-06T14:32:17.000Z",
"num_tokens": 225,
"size": 837
} |
/*
* Copyright 2021 The DAPHNE Consortium
*
* 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 <runtime/local/context/DaphneContext.h>
#include <runtime/local/datastructures/DataObjectFactory.h>
#include <runtime/local/datastructures/DenseMatrix.h>
#include <cblas.h>
#include <lapacke.h>
#include <cassert>
#include <cstddef>
// ****************************************************************************
// Struct for partial template specialization
// ****************************************************************************
template<class DTRes, class DTLhs, class DTRhs>
struct Solve {
static void apply(DTRes *& res, const DTLhs * lhs, const DTRhs * rhs, DCTX(ctx)) = delete;
};
// ****************************************************************************
// Convenience function
// ****************************************************************************
template<class DTRes, class DTLhs, class DTRhs>
void solve(DTRes *& res, const DTLhs * lhs, const DTRhs * rhs, DCTX(ctx)) {
Solve<DTRes, DTLhs, DTRhs>::apply(res, lhs, rhs, ctx);
}
// ****************************************************************************
// (Partial) template specializations for different data/value types
// ****************************************************************************
// ----------------------------------------------------------------------------
// DenseMatrix <- DenseMatrix, DenseMatrix
// ----------------------------------------------------------------------------
template<>
struct Solve<DenseMatrix<float>, DenseMatrix<float>, DenseMatrix<float>> {
static void apply(DenseMatrix<float> *& res, const DenseMatrix<float> * lhs, const DenseMatrix<float> * rhs, DCTX(ctx)) {
const auto nr1 = static_cast<int>(lhs->getNumRows());
const auto nc1 = static_cast<int>(lhs->getNumCols());
const auto nc2 = static_cast<int>(rhs->getNumCols());
assert((nr1 == static_cast<int>(rhs->getNumRows())) && "#rows of lhs and #rows of rhs must be the same");
assert((nr1 == nc1) && "#rows and #cols of lhs must be the same");
assert((static_cast<int>(lhs->getRowSkip()) == nc1) && "#cols of lhs must match row skip");
assert((nc2==1) && "#cols of rhs must be 1");
if(res == nullptr)
res = DataObjectFactory::create<DenseMatrix<float>>(nr1, nc2, false);
// solve system of equations via LU decomposition
int ipiv[nr1]; // permutation indexes
float work[nr1*nc1]; // LU factorization of gesv
memcpy(work, lhs->getValues(), nr1*nc1*sizeof(float)); //for in-place A
memcpy(res->getValues(), rhs->getValues(), nr1*sizeof(float)); //for in-place b-out
[[maybe_unused]] int info = LAPACKE_sgesv(LAPACK_ROW_MAJOR, nr1, 1, work, nc1, ipiv, res->getValues(), 1);
assert((info<=0) && "A factor Ui is exactly singular, so the solution could not be computed");
}
};
template<>
struct Solve<DenseMatrix<double>, DenseMatrix<double>, DenseMatrix<double>> {
static void apply(DenseMatrix<double> *& res, const DenseMatrix<double> * lhs, const DenseMatrix<double> * rhs, DCTX(ctx)) {
const auto nr1 = static_cast<int>(lhs->getNumRows());
const auto nc1 = static_cast<int>(lhs->getNumCols());
const auto nc2 = static_cast<int>(rhs->getNumCols());
assert((nr1 == static_cast<int>(rhs->getNumRows())) && "#rows of lhs and #rows of rhs must be the same");
assert((nr1 == nc1) && "#rows and #cols of lhs must be the same");
assert((static_cast<int>(lhs->getRowSkip()) == nc1) && "#cols of lhs must match row skip");
assert((nc2==1) && "#cols of rhs must be 1");
if(res == nullptr)
res = DataObjectFactory::create<DenseMatrix<double>>(nr1, nc2, false);
// solve system of equations via LU decomposition
int ipiv[nr1]; // permutation indexes
double work[nr1*nc1]; // LU factorization of gesv
memcpy(work, lhs->getValues(), nr1*nc1*sizeof(double)); //for in-place A
memcpy(res->getValues(), rhs->getValues(), nr1*sizeof(double)); //for in-place b-out
[[maybe_unused]] int info = LAPACKE_dgesv(LAPACK_ROW_MAJOR, nr1, 1, work, nc1, ipiv, res->getValues(), 1);
assert((info<=0) && "A factor Ui is exactly singular, so the solution could not be computed");
}
};
| {
"alphanum_fraction": 0.5766170169,
"avg_line_length": 48.0490196078,
"ext": "h",
"hexsha": "cfccb6c9e890096b68933db7dbe15dc6f16bbe88",
"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": "64d4040132cf4059efaf184c4e363dbb921c87d6",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "daphne-eu/daphne",
"max_forks_repo_path": "src/runtime/local/kernels/Solve.h",
"max_issues_count": 3,
"max_issues_repo_head_hexsha": "64d4040132cf4059efaf184c4e363dbb921c87d6",
"max_issues_repo_issues_event_max_datetime": "2022-03-31T22:46:30.000Z",
"max_issues_repo_issues_event_min_datetime": "2022-03-31T22:10:10.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "daphne-eu/daphne",
"max_issues_repo_path": "src/runtime/local/kernels/Solve.h",
"max_line_length": 128,
"max_stars_count": 10,
"max_stars_repo_head_hexsha": "64d4040132cf4059efaf184c4e363dbb921c87d6",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "daphne-eu/daphne",
"max_stars_repo_path": "src/runtime/local/kernels/Solve.h",
"max_stars_repo_stars_event_max_datetime": "2022-03-31T23:37:06.000Z",
"max_stars_repo_stars_event_min_datetime": "2022-03-31T21:49:35.000Z",
"num_tokens": 1116,
"size": 4901
} |
#ifndef _EM_IO_H_
#define _EM_IO_H_ 1
#include <petsc.h>
struct EMContext;
PetscErrorCode read_mdl(const char *, EMContext *);
PetscErrorCode read_emd(const char *, EMContext *);
PetscErrorCode save_mesh(EMContext *, const char *, int);
PetscErrorCode save_rsp(EMContext *, const char *);
#endif
| {
"alphanum_fraction": 0.7574750831,
"avg_line_length": 20.0666666667,
"ext": "h",
"hexsha": "5a00e207e9c061b20a77a9a3d1eac29d53c88a98",
"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": "9129e28610d7fcb83a88021528575dfeaadad502",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "emfem/emfem",
"max_forks_repo_path": "src/em_io.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "9129e28610d7fcb83a88021528575dfeaadad502",
"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": "emfem/emfem",
"max_issues_repo_path": "src/em_io.h",
"max_line_length": 57,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "9129e28610d7fcb83a88021528575dfeaadad502",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "emfem/emfem",
"max_stars_repo_path": "src/em_io.h",
"max_stars_repo_stars_event_max_datetime": "2021-08-03T12:22:37.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-08-03T12:22:37.000Z",
"num_tokens": 77,
"size": 301
} |
#pragma once
#include <gsl\gsl>
#include <winrt\Windows.Foundation.h>
#include <d3d11.h>
#include "DrawableGameComponent.h"
#include "MatrixHelper.h"
#include "PointLight.h"
namespace Library
{
class ProxyModel;
}
namespace Rendering
{
class PointLightMaterial;
class PointLightDemo final : public Library::DrawableGameComponent
{
public:
PointLightDemo(Library::Game& game, const std::shared_ptr<Library::Camera>& camera);
PointLightDemo(const PointLightDemo&) = delete;
PointLightDemo(PointLightDemo&&) = default;
PointLightDemo& operator=(const PointLightDemo&) = default;
PointLightDemo& operator=(PointLightDemo&&) = default;
~PointLightDemo();
bool AnimationEnabled() const;
void SetAnimationEnabled(bool enabled);
void ToggleAnimation();
float AmbientLightIntensity() const;
void SetAmbientLightIntensity(float intensity);
float PointLightIntensity() const;
void SetPointLightIntensity(float intensity);
const DirectX::XMFLOAT3& LightPosition() const;
const DirectX::XMVECTOR LightPositionVector() const;
void SetLightPosition(const DirectX::XMFLOAT3& position);
void SetLightPosition(DirectX::FXMVECTOR position);
float LightRadius() const;
void SetLightRadius(float radius);
float SpecularIntensity() const;
void SetSpecularIntensity(float intensity);
float SpecularPower() const;
void SetSpecularPower(float power);
virtual void Initialize() override;
virtual void Update(const Library::GameTime& gameTime) override;
virtual void Draw(const Library::GameTime& gameTime) override;
private:
inline static const float RotationRate{ DirectX::XM_PI };
std::shared_ptr<PointLightMaterial> mMaterial;
DirectX::XMFLOAT4X4 mWorldMatrix{ Library::MatrixHelper::Identity };
winrt::com_ptr<ID3D11Buffer> mVertexBuffer;
winrt::com_ptr<ID3D11Buffer> mIndexBuffer;
std::uint32_t mIndexCount{ 0 };
Library::PointLight mPointLight;
std::unique_ptr<Library::ProxyModel> mProxyModel;
float mModelRotationAngle{ 0.0f };
bool mAnimationEnabled{ true };
bool mUpdateMaterial{ true };
};
} | {
"alphanum_fraction": 0.7708634829,
"avg_line_length": 29.1971830986,
"ext": "h",
"hexsha": "c8fcd269d5d9b11afa656905216b2cf99c3033bb",
"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/4.1_Point_Light/PointLightDemo.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/4.1_Point_Light/PointLightDemo.h",
"max_line_length": 86,
"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/4.1_Point_Light/PointLightDemo.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 508,
"size": 2073
} |
#ifndef GBNET_MODELBASE
#define GBNET_MODELBASE
#include <algorithm>
#include <cmath>
#include <csignal>
#include <time.h>
#include <gsl/gsl_rstat.h>
#include "GraphBase.h"
namespace gbn
{
typedef std::pair<std::string, double> varid_stat_pair_t;
typedef std::vector<varid_stat_pair_t> posterior_stat_vector_t;
typedef std::vector<std::pair<std::string, double>> gelman_rubin_vector_t;
class ModelBase
{
private:
protected:
int current_signal = 0;
public:
network_t network;
evidence_dict_t evidence = evidence_dict_t();
prior_active_tf_set_t active_tf_set = prior_active_tf_set_t();
unsigned int n_graphs = 3;
bool noise_listen_children = false;
std::vector<GraphBase *> graphs;
ModelBase(unsigned int = 3);
virtual ~ModelBase();
gelman_rubin_vector_t get_gelman_rubin();
double get_max_gelman_rubin();
void sample(unsigned int = 50000, unsigned int = 30);
void sample_n(unsigned int);
void burn_stats();
void print_stats();
posterior_stat_vector_t get_posterior_means(std::string);
posterior_stat_vector_t get_posterior_sdevs(std::string);
void set_signal(int);
};
}
#endif | {
"alphanum_fraction": 0.6332103321,
"avg_line_length": 24.6363636364,
"ext": "h",
"hexsha": "35e06761c2894e56e54b4068bb21e63d75a38418",
"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/ModelBase.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/ModelBase.h",
"max_line_length": 78,
"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/ModelBase.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 301,
"size": 1355
} |
#pragma once
#include <halley/maths/vector2.h>
#include <halley/time/halleytime.h>
#include <halley/core/graphics/sprite/sprite.h>
#include <gsl/gsl>
#include <thread>
#include <mutex>
#include <atomic>
namespace Halley
{
class RenderContext;
class TextureDescriptor;
class VideoAPI;
class AudioAPI;
class StreamingAudioClip;
class IAudioHandle;
class TextureRenderTarget;
enum class MoviePlayerState
{
Uninitialised,
Loading,
Paused,
StartingToPlay,
Playing,
Finished
};
enum class MoviePlayerStreamType
{
Unknown,
Video,
Audio,
Other
};
class MoviePlayerStream
{
public:
MoviePlayerStreamType type = MoviePlayerStreamType::Unknown;
bool playing = true;
bool eof = false;
};
struct PendingFrame
{
std::shared_ptr<Texture> texture;
Time time;
};
struct MoviePlayerAliveFlag
{
bool isAlive = true;
mutable std::mutex mutex;
};
class MoviePlayer
{
public:
MoviePlayer(VideoAPI& video, AudioAPI& audio);
virtual ~MoviePlayer();
void play();
void pause();
void reset();
void stop();
virtual bool hasError() const;
virtual void update(Time t);
void render(Resources& resources, RenderContext& rc);
Sprite getSprite(Resources& resources);
MoviePlayerState getState() const;
Vector2i getSize() const;
protected:
virtual void requestVideoFrame() = 0;
virtual void requestAudioFrame() = 0;
virtual void onReset();
virtual void onStartPlay();
virtual void waitForVideoInfo();
virtual bool needsYV12Conversion() const;
virtual bool shouldRecycleTextures() const;
virtual void onDoneUsingTexture(std::shared_ptr<Texture> texture);
virtual Rect4i getCropRect() const;
void setVideoSize(Vector2i size);
VideoAPI& getVideoAPI() const;
AudioAPI& getAudioAPI() const;
void onVideoFrameAvailable(Time time, TextureDescriptor&& descriptor);
void onVideoFrameAvailable(Time time, std::shared_ptr<Texture> texture);
void onAudioFrameAvailable(Time time, gsl::span<const short> samples);
void onAudioFrameAvailable(Time time, gsl::span<const float> samples);
std::shared_ptr<MoviePlayerAliveFlag> getAliveFlag() const;
std::vector<MoviePlayerStream> streams;
std::list<std::shared_ptr<Texture>> recycleTexture;
std::list<PendingFrame> pendingFrames;
int maxVideoFrames;
int maxAudioSamples;
private:
VideoAPI& video;
AudioAPI& audio;
MoviePlayerState state = MoviePlayerState::Uninitialised;
Vector2i videoSize;
std::shared_ptr<Texture> currentTexture;
std::shared_ptr<TextureRenderTarget> renderTarget;
std::shared_ptr<Texture> renderTexture;
std::shared_ptr<StreamingAudioClip> streamingClip;
std::shared_ptr<IAudioHandle> audioHandle;
std::atomic<bool> threadRunning;
std::atomic<bool> threadAborted;
std::thread workerThread;
std::shared_ptr<MoviePlayerAliveFlag> aliveFlag;
Time time = 0;
void startThread();
void stopThread();
void threadEntry();
virtual bool useCustomThreads() const;
virtual void stopCustomThreads();
bool needsMoreVideoFrames() const;
bool needsMoreAudioFrames() const;
};
}
| {
"alphanum_fraction": 0.7469996756,
"avg_line_length": 21.865248227,
"ext": "h",
"hexsha": "cff2dbf6798721f85a293f3f1341ce3ea8cecb75",
"lang": "C",
"max_forks_count": 193,
"max_forks_repo_forks_event_max_datetime": "2022-03-22T12:59:58.000Z",
"max_forks_repo_forks_event_min_datetime": "2017-10-23T06:08:41.000Z",
"max_forks_repo_head_hexsha": "fc4f153956cc34d7fa02b76850e22183b8e30e25",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "sunhay/halley",
"max_forks_repo_path": "src/engine/core/include/halley/core/graphics/movie/movie_player.h",
"max_issues_count": 53,
"max_issues_repo_head_hexsha": "fc4f153956cc34d7fa02b76850e22183b8e30e25",
"max_issues_repo_issues_event_max_datetime": "2022-01-10T13:52:37.000Z",
"max_issues_repo_issues_event_min_datetime": "2016-10-09T16:25:04.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "sunhay/halley",
"max_issues_repo_path": "src/engine/core/include/halley/core/graphics/movie/movie_player.h",
"max_line_length": 74,
"max_stars_count": 3262,
"max_stars_repo_head_hexsha": "fc4f153956cc34d7fa02b76850e22183b8e30e25",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "sunhay/halley",
"max_stars_repo_path": "src/engine/core/include/halley/core/graphics/movie/movie_player.h",
"max_stars_repo_stars_event_max_datetime": "2022-03-31T17:47:08.000Z",
"max_stars_repo_stars_event_min_datetime": "2016-04-10T15:24:10.000Z",
"num_tokens": 782,
"size": 3083
} |
/* This file is auto-generated from weight_functions.h.src */
#ifndef DOUBLE_PREC
#define DOUBLE_PREC
#endif
// # -*- mode: c -*-
#pragma once
#include "defs.h"
#include <stdint.h>
#include <gsl/gsl_matrix_double.h>
#include <gsl/gsl_linalg.h>
// Info about a particle pair that we will pass to the weight function
typedef struct
{
int64_t nprojbins;
int64_t nsbins;
double sqr_s;
double *supp_sqr; //proper way to have array in struct?
} proj_struct_double;
//typedef double (*weight_func_t_double)(const pair_struct_double*);
//////////////////////////////////
// Projection functions
//////////////////////////////////
static inline void tophat_double(const proj_struct_double *proj, double *u){
int ins = -1;
for(int p=0;p<proj->nsbins;p++){
u[p] = 0;
if (proj->sqr_s >= proj->supp_sqr[p] && proj->sqr_s < proj->supp_sqr[p+1]){
ins = p;
}
}
if (ins>=0 && ins<proj->nprojbins){
u[ins] = 1.0;
}
}
//////////////////////////////////
// Utility functions
//////////////////////////////////
static inline void compute_amplitudes(int nprojbins, int nd1, int nd2, int nr1, int nr2,
double *dd, double *dr, double *rd, double *rr, double *qq, double *amps){
printf("Computing amps\n");
printf("qq:\n");
for(int i=0;i<nprojbins;i++){
for (int j=0; j<nprojbins; j++){
printf(" %f", qq[i*nprojbins+j]);
}
printf("\n");
}
// Computer numerator of estimator
double numerator[nprojbins];
double qqnorm[nprojbins*nprojbins];
for (int i=0; i<nprojbins; i++){
double ddnorm = dd[i]/((double)nd1*(double)nd2);
double drnorm = dr[i]/((double)nd1*(double)nr2);
double rdnorm = rd[i]/((double)nr1*(double)nd2);
double rrnorm = rr[i]/((double)nr1*(double)nr2);
numerator[i] = ddnorm - drnorm - rdnorm + rrnorm;
for (int j=0; j<nprojbins; j++){
printf("%f", qq[i*nprojbins+j]);
qqnorm[i*nprojbins+j] = qq[i*nprojbins+j]/((double)nr1*(double)nr2);
}
}
printf("qqnorm:\n");
for(int i=0;i<nprojbins;i++){
for (int j=0; j<nprojbins; j++){
printf(" %f", qqnorm[i*nprojbins+j]);
}
printf("\n");
}
int s;
// Define all the used matrices
gsl_matrix *qq_mat = gsl_matrix_alloc(nprojbins, nprojbins);
gsl_matrix *qq_mat_inv = gsl_matrix_alloc(nprojbins, nprojbins);
gsl_permutation *perm = gsl_permutation_alloc(nprojbins);
// Fill the matrix m
for (int i=0; i<nprojbins; i++){
for (int j=0; j<nprojbins; j++){
gsl_matrix_set(qq_mat, i, j, qqnorm[i*nprojbins+j]);
}
}
// Make LU decomposition of matrix m
gsl_linalg_LU_decomp(qq_mat, perm, &s);
// Invert the matrix m
gsl_linalg_LU_invert(qq_mat, perm, qq_mat_inv);
printf("qqinv:\n");
for(int i=0;i<nprojbins;i++){
for (int j=0; j<nprojbins; j++){
printf(" %f", gsl_matrix_get(qq_mat_inv, i, j));
}
printf("\n");
}
// Take inner product of qqinv * numerator, get amplitude vector
// TODO: double check
for (int i=0; i<nprojbins; i++){
double aval = 0;
for (int j=0; j<nprojbins; j++){
aval += gsl_matrix_get(qq_mat_inv, i, j) * numerator[j];
}
amps[i] = aval;
}
}
static inline void evaluate_xi(int nprojbins, double *amps, int nsvals, double *svals,
int nsbins, double *sbins, double *xi){
// will need to generalize, projbins won't always be rela ted to sbins
double supp_sqr[nsbins];
//plus 1 because one more edge than number of bins
for (int i=0; i<nsbins+1; i++){
supp_sqr[i] = pow(sbins[i], 2);
}
// ns: number of s values at which to evaluate xi
for (int i=0; i<nsvals; i++){
//get basis function u for given value of s
double u[nprojbins];
double sqr_s = pow(svals[i], 2);
proj_struct_double projdata = {.nprojbins=nprojbins, .nsbins=nsbins, .sqr_s=sqr_s, .supp_sqr=supp_sqr};
tophat_double(&projdata, u);
//multiply u by the amplitudes to get xi in that s bin (xi is vector of length ns_toeval)
double xival = 0;
for (int j=0; j<nprojbins; j++){
xival += amps[j]*u[j];
}
xi[i] = xival;
}
}
/* Gives a pointer to the weight function for the given weighting method
* and instruction set.
*/
//static inline weight_func_t_double get_weight_func_by_method_double(const weight_method_t method){
// switch(method){
// case PAIR_PRODUCT:
// return &pair_product_double;
// default:
// case NONE:
// return NULL;
// }
//} | {
"alphanum_fraction": 0.5750684355,
"avg_line_length": 29.1349693252,
"ext": "h",
"hexsha": "e390852fee795a92a27be6f6ed6469308fbd29e9",
"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": "ff72167804f55c46486c3b35143c6da62cf2779a",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "kstoreyf/foo",
"max_forks_repo_path": "utils/proj_functions_double.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "ff72167804f55c46486c3b35143c6da62cf2779a",
"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": "kstoreyf/foo",
"max_issues_repo_path": "utils/proj_functions_double.h",
"max_line_length": 111,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "ff72167804f55c46486c3b35143c6da62cf2779a",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "kstoreyf/foo",
"max_stars_repo_path": "utils/proj_functions_double.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1352,
"size": 4749
} |
/* -*- mode: C; c-basic-offset: 4 -*- */
/* ex: set shiftwidth=4 tabstop=4 expandtab: */
/*
* Copyright (c) 2018, Colorado School of Mines
* All rights reserved.
*
* Author(s): Neil T. Dantam <ndantam@miens.edu>
* Georgia Tech Humanoid Robotics Lab
* Under Direction of Prof. Mike Stilman <mstilman@cc.gatech.edu>
*
*
* This file is provided under the following "BSD-style" License:
*
*
* Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the following
* conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
// uncomment to check that local allocs actually get freed
// #define AA_ALLOC_STACK_MAX 0
#include <stdlib.h>
#include <cblas.h>
#include "amino.h"
#include "amino/mat.h"
#include "amino/mat_internal.h"
#define VEC_LEN(X) ((int)(X->len))
#define MAT_ROWS(X) ((int)(X->rows))
#define MAT_COLS(X) ((int)(X->cols))
/******************/
/* Error Handling */
/******************/
static void
s_err_default( const char *message )
{
fprintf(stderr, "AMINO ERROR: %s\n",message);
abort();
exit(EXIT_FAILURE);
}
static aa_la_err_fun *s_err_fun = s_err_default;
void
aa_la_set_err( aa_la_err_fun *fun )
{
s_err_fun = fun;
}
AA_API void
aa_la_err( const char *message ) {
s_err_fun(message);
}
AA_API void
aa_la_fail_size( size_t a, size_t b )
{
const size_t size = 256;
char buf[size];
snprintf(buf,size, "Mismatched sizes: %lu != %lu\n", a, b);
aa_la_err(buf);
}
/****************/
/* Construction */
/****************/
AA_API void
aa_dvec_view( struct aa_dvec *vec, size_t len, double *data, size_t inc )
{
*vec = AA_DVEC_INIT(len,data,inc);
}
AA_API void
aa_dvec_slice( const struct aa_dvec *src,
size_t start,
size_t stop,
size_t step,
struct aa_dvec *dst )
{
if( stop > src->len || stop < start ) {
aa_la_err("Slice out-of-bounds\n");
}
*dst = AA_DVEC_INIT( (stop - start) / step,
src->data + src->inc*start,
src->inc*step );
}
AA_API void
aa_dmat_row_vec( const struct aa_dmat *src, size_t row, struct aa_dvec *dst )
{
if( row >= src->rows ) {
aa_la_err("Row vector out-of-bounds\n");
}
aa_dvec_view(dst,src->cols, src->data + row, src->ld);
}
AA_API void
aa_dmat_col_vec( const struct aa_dmat *src, size_t col, struct aa_dvec *dst )
{
if( col >= src->cols ) {
aa_la_err("Row vector out-of-bounds\n");
}
aa_dvec_view(dst, src->rows, src->data + col*src->ld, 1);
}
AA_API void
aa_dmat_diag_vec( const struct aa_dmat *src, struct aa_dvec *dst )
{
aa_dvec_view(dst, AA_MIN(src->rows, src->cols), src->data, src->ld + 1);
}
AA_API void
aa_dmat_view( struct aa_dmat *mat, size_t rows, size_t cols,
double *data, size_t ld )
{
*mat = AA_DMAT_INIT(rows,cols,data,ld);
}
AA_API void
aa_dmat_view_block( struct aa_dmat *dst,
const struct aa_dmat *src,
size_t row_start, size_t col_start,
size_t rows, size_t cols )
{
aa_dmat_block( src,
row_start, col_start,
row_start + rows, col_start + cols,
dst );
}
AA_API void
aa_dmat_block( const struct aa_dmat *src,
size_t row_start, size_t col_start,
size_t row_end, size_t col_end,
struct aa_dmat *dst )
{
size_t m = src->rows, n = src->cols;
if( row_start >= row_end ||
row_start >= m ||
row_end > m ||
col_start >= col_end ||
col_start >= n ||
col_end > n )
{
aa_la_err("Block out-of-bounds\n");
}
aa_dmat_view( dst,
row_end - row_start, col_end - col_start,
src->data + col_start*src->ld + row_start, src->ld );
}
AA_API struct aa_dvec *
aa_dvec_malloc( size_t len ) {
struct aa_dvec *r;
const size_t s_desc = sizeof(*r);
const size_t s_elem = sizeof(r->data[0]);
const size_t pad = s_elem - (s_desc % s_elem);
const size_t size = s_desc + pad + len * s_elem;
const size_t off = s_desc + pad;
char *ptr = (char*)malloc( size );
r = (struct aa_dvec*)ptr;
aa_dvec_view(r, len, (double*)(ptr+off), 1);
return r;
}
AA_API struct aa_dvec *
aa_dvec_alloc( struct aa_mem_region *reg, size_t len ) {
struct aa_dvec *r;
const size_t s_desc = sizeof(*r);
const size_t s_elem = sizeof(r->data[0]);
const size_t pad = s_elem - (s_desc % s_elem);
char *ptr = (char*)aa_mem_region_alloc(reg, s_desc + pad + len * s_elem );
r = (struct aa_dvec*)ptr;
aa_dvec_view(r, len, (double*)(ptr+s_desc+pad), 1);
return r;
}
AA_API struct aa_dvec *
aa_dvec_dup( struct aa_mem_region *reg, const struct aa_dvec *src)
{
struct aa_dvec *dst = aa_dvec_alloc(reg,src->len);
aa_dvec_copy(src,dst);
return dst;
}
AA_API struct aa_dmat *
aa_dmat_dup( struct aa_mem_region *reg, const struct aa_dmat *src)
{
struct aa_dmat *dst = aa_dmat_alloc(reg,src->rows,src->cols);
aa_dmat_copy(src,dst);
return dst;
}
AA_API struct aa_dmat *
aa_dmat_malloc( size_t rows, size_t cols )
{
struct aa_dmat *r;
const size_t s_desc = sizeof(*r);
const size_t s_elem = sizeof(r->data[0]);
const size_t pad = s_elem - (s_desc % s_elem);
char *ptr = (char*)malloc( s_desc + pad + rows*cols * s_elem );
r = (struct aa_dmat*)ptr;
aa_dmat_view(r, rows, cols, (double*)(ptr+s_desc+pad), rows);
return r;
}
AA_API struct aa_dmat *
aa_dmat_alloc( struct aa_mem_region *reg, size_t rows, size_t cols )
{
struct aa_dmat *r;
const size_t s_desc = sizeof(*r);
const size_t s_elem = sizeof(r->data[0]);
const size_t pad = s_elem - (s_desc % s_elem);
size_t size = s_desc + pad + rows*cols * s_elem ;
char *ptr = (char*)aa_mem_region_alloc(reg, size);
r = (struct aa_dmat*)ptr;
aa_dmat_view( r, rows, cols, (double*)(ptr+s_desc+pad), rows );
return r;
}
AA_API void
aa_dmat_set( struct aa_dmat *A, double alpha, double beta )
{
int mi = (int)(A->rows);
int ni = (int)(A->cols);
int ldai = (int)(A->ld);
dlaset_( "G", &mi, &ni,
&alpha, &beta,
A->data, &ldai );
}
AA_API void
aa_dvec_set( struct aa_dvec *vec, double alpha )
{
double *end = vec->data + vec->len*vec->inc;
for( double *x = vec->data; x < end; x += vec->inc ) {
*x = alpha;
}
}
void
aa_dvec_zero( struct aa_dvec *vec )
{
aa_dvec_set(vec,0);
}
AA_API void
aa_dmat_zero( struct aa_dmat *mat )
{
aa_dmat_set(mat, 0, 0);
}
/* Level 1 BLAS */
AA_API void
aa_dvec_swap( struct aa_dvec *x, struct aa_dvec *y )
{
aa_la_check_size(x->len, y->len);
cblas_dswap( VEC_LEN(x), AA_VEC_ARGS(x), AA_VEC_ARGS(y) );
}
AA_API void
aa_dvec_scal( double a, struct aa_dvec *x )
{
cblas_dscal( VEC_LEN(x), a, AA_VEC_ARGS(x) );
}
static void s_inc( size_t n, double alpha, double *x, size_t inc ) {
for( double *end = x + n*inc; x < end; x += inc ) {
*x += alpha;
}
}
AA_API void
aa_dvec_inc( double alpha, struct aa_dvec *x )
{
s_inc( x->len, alpha, x->data, x->inc );
}
AA_API void
aa_dvec_copy( const struct aa_dvec *x, struct aa_dvec *y )
{
aa_la_check_size(x->len, y->len);
cblas_dcopy( VEC_LEN(x), AA_VEC_ARGS(x), AA_VEC_ARGS(y) );
}
AA_API void
aa_dvec_axpy( double a, const struct aa_dvec *x, struct aa_dvec *y )
{
aa_la_check_size(x->len, y->len);
cblas_daxpy( VEC_LEN(x), a, AA_VEC_ARGS(x), AA_VEC_ARGS(y) );
}
AA_API double
aa_dvec_dot( const struct aa_dvec *x, struct aa_dvec *y )
{
aa_la_check_size(x->len, y->len);
return cblas_ddot( VEC_LEN(x), AA_VEC_ARGS(x), AA_VEC_ARGS(y) );
}
AA_API double
aa_dvec_nrm2( const struct aa_dvec *x )
{
return cblas_dnrm2( VEC_LEN(x), AA_VEC_ARGS(x) );
}
/* Level 2 BLAS */
AA_API void
aa_dmat_gemv( CBLAS_TRANSPOSE trans,
double alpha, const struct aa_dmat *A,
const struct aa_dvec *x,
double beta, struct aa_dvec *y )
{
if( CblasTrans == trans ) {
aa_la_check_size( A->rows, x->len );
aa_la_check_size( A->cols, y->len );
} else {
aa_la_check_size( A->rows, y->len );
aa_la_check_size( A->cols, x->len );
}
cblas_dgemv( CblasColMajor, trans,
MAT_ROWS(A), MAT_COLS(A),
alpha, AA_MAT_ARGS(A),
AA_VEC_ARGS(x),
beta, AA_VEC_ARGS(y) );
}
/* Level 3 BLAS */
AA_API void
aa_dmat_gemm( CBLAS_TRANSPOSE transA, CBLAS_TRANSPOSE transB,
double alpha, const struct aa_dmat *A,
const struct aa_dmat *B,
double beta, struct aa_dmat *C )
{
aa_la_check_size( A->rows, C->rows );
aa_la_check_size( A->cols, B->rows );
aa_la_check_size( B->cols, C->cols );
assert( A->rows <= A->ld );
assert( B->rows <= B->ld );
assert( C->rows <= C->ld );
cblas_dgemm( CblasColMajor,
transA, transB,
MAT_ROWS(A), MAT_COLS(B), MAT_COLS(A),
alpha, AA_MAT_ARGS(A),
AA_MAT_ARGS(B),
beta, AA_MAT_ARGS(C) );
}
/* LAPACK */
AA_API void
aa_dmat_lacpy( const char uplo[1],
const struct aa_dmat *A,
struct aa_dmat *B )
{
aa_la_check_size(A->rows,B->rows);
aa_la_check_size(A->cols,B->cols);
int mi = (int)(A->rows);
int ni = (int)(A->cols);
int ldai = (int)(A->ld);
int ldbi = (int)(B->ld);
dlacpy_(uplo, &mi, &ni,
A->data, &ldai,
B->data, &ldbi);
}
AA_API void
aa_dmat_copy( const struct aa_dmat *A, struct aa_dmat *B)
{
aa_dmat_lacpy("G",A,B);
}
/* Matrix Functions */
static double s_ssd( size_t n,
double a,
double *x, size_t incx,
double *y, size_t incy )
{
for( double *e = x + n*incx; x < e; x += incx, y+=incy ) {
double d = *x - *y;
a += d*d;
}
return a;
}
AA_API double
aa_dvec_ssd( const struct aa_dvec *x, const struct aa_dvec *y)
{
aa_la_check_size( x->len, y->len );
return s_ssd( x->len, 0,
x->data, x->inc,
y->data, y->inc );
}
AA_API double
aa_dmat_ssd( const struct aa_dmat *A, const struct aa_dmat *B)
{
size_t m = A->rows, n = A->cols;
aa_la_check_size( m, B->rows );
aa_la_check_size( n, B->cols );
double a = 0;
for( double *Ac=A->data, *Bc=B->data, *ec=A->data + n*A->ld;
Ac < ec;
Ac+=A->ld, Bc+=B->ld )
{
a = s_ssd( m, a, Ac, 1, Bc, 1 );
}
return a;
}
AA_API double
aa_dmat_nrm2( const struct aa_dmat *A )
{
int m=(int)A->rows, n=(int)A->cols, ld=(int)A->ld;
return dlange_("F", &m, &n, A->data, &ld, NULL );
}
AA_API void
aa_dmat_scal( struct aa_dmat *x, double alpha )
{
int m = (int)x->rows, n=(int)x->cols, ld=(int)x->ld;
double cfrom=1;
int info;
dlascl_("G", NULL, NULL,
&cfrom, &alpha,
&m, &n, x->data, &ld,
&info);
}
AA_API void
aa_dmat_inc( struct aa_dmat *A, double alpha )
{
size_t m=A->rows, n=A->cols, ld=A->ld;
double *x = A->data;
if( m == n ) {
s_inc(m*n, alpha, x, 1);
} else {
for( double *e = x + n*ld; x < e; x+=ld ) {
s_inc(m, alpha, x, 1);
}
}
}
AA_API void
aa_dmat_axpy( double alpha, const struct aa_dmat *X, struct aa_dmat *Y)
{
size_t m=X->rows, n=X->cols, ldX=X->ld, ldY=Y->ld;
double *x=X->data, *y=Y->data;
aa_la_check_size(m, Y->rows);
aa_la_check_size(n, Y->cols);
if( m == ldX && m == ldY ) {
cblas_daxpy( (int)(m*n), alpha, x,1, y,1 );
} else {
int mi = (int)m;
for( double *e = x + n*ldX; x < e; x+=ldX, y+=ldY ) {
cblas_daxpy( mi, alpha, x,1, y,1 );
}
}
}
void
aa_dmat_trans( const struct aa_dmat *A, struct aa_dmat *B)
{
const size_t m = A->rows;
const size_t n = A->cols;
const size_t lda = A->ld;
const size_t ldb = B->ld;
aa_la_check_size(m, B->cols);
aa_la_check_size(n, B->rows);
for ( double *Acol = A->data, *Brow=B->data, *Be=B->data + n;
Brow < Be;
Brow++, Acol+=lda )
{
cblas_dcopy( (int)m, Acol, 1, Brow, (int)ldb );
}
}
AA_API int
aa_dmat_inv( struct aa_dmat *A )
{
aa_la_check_size(A->rows,A->cols);
int info;
int *ipiv = (int*)
aa_mem_region_local_alloc(sizeof(int)*A->rows);
// LU-factor
info = aa_cla_dgetrf( MAT_ROWS(A), MAT_COLS(A), AA_MAT_ARGS(A), ipiv );
int lwork = -1;
while(1) {
double *work = (double*)
aa_mem_region_local_tmpalloc( sizeof(double)*
(size_t)(lwork < 0 ? 1 : lwork) );
aa_cla_dgetri( MAT_ROWS(A), AA_MAT_ARGS(A), ipiv, work, lwork );
if( lwork > 0 ) break;
assert( -1 == lwork );
lwork = (int)work[0];
}
aa_mem_region_local_pop(ipiv);
return info;
}
int s_svd_helper ( const struct aa_dmat *A,
struct aa_mem_region *reg,
size_t *pkmin, size_t *pkmax,
double **pU, double **pVt, double **pS )
{
size_t m = A->rows;
size_t n = A->cols;
// find min/max dimensions
if( m < n ) {
*pkmin = m;
*pkmax = n;
} else {
*pkmin = n;
*pkmax = m;
}
// This method uses the SVD
double *W = (double*)aa_mem_region_alloc( reg, sizeof(double) * (m*m + n*n + *pkmin) );
*pU = W; // size m*m
*pVt = *pU + m*m; // size n*n
*pS = *pVt + n*n; // size min(m,n)
// A = U S V^T
aa_la_d_svd( m,n,
A->data, A->ld,
*pU, m, *pS, *pVt, n );
return 0;
}
int
aa_dmat_pinv( const struct aa_dmat *A, double tol, struct aa_dmat *As )
{
aa_la_check_size(A->rows, As->cols);
aa_la_check_size(A->cols, As->rows);
struct aa_mem_region *reg = aa_mem_region_local_get();
void *ptrtop = aa_mem_region_ptr(reg);
size_t kmin, kmax;
double *U, *Vt, *S;
s_svd_helper( A, reg,
&kmin, &kmax, &U, &Vt, &S );
size_t m = A->rows;
const int mi = (int)(A->rows);
const int ni = (int)(A->cols);
if( tol < 0 ) {
tol = (double)kmax * S[0] * DBL_EPSILON;
}
// \sum 1/s_i * v_i * u_i^T
aa_dmat_zero(As);
double *Asd = As->data;
for( size_t i = 0; i < kmin && S[i] > tol; i ++ ) {
cblas_dger( CblasColMajor, ni, mi, 1/S[i],
Vt + i, ni,
U + m*i, 1,
Asd, ni
);
}
aa_mem_region_pop( reg, ptrtop );
return 0;
/* struct aa_mem_region *reg = aa_mem_region_local_get(); */
/* struct aa_dmat *Ap = aa_dmat_alloc(reg,m,n); */
/* // B = AA^T */
/* double *B; */
/* int ldb; */
/* if( m <= n ) { */
/* /\* Use A_star as workspace when it's big enough *\/ */
/* B = As->data; */
/* ldb = (int)(As->ld); */
/* } else { */
/* B = AA_MEM_REGION_NEW_N( reg, double, m*m ); */
/* ldb = (int)m; */
/* } */
/* aa_la_dlacpy( "A", A, Ap ); */
/* // B is symmetric. Only compute the upper half. */
/* cblas_dsyrk( CblasColMajor, CblasUpper, CblasNoTrans, */
/* MAT_ROWS(Ap), MAT_COLS(Ap), */
/* 1, AA_MAT_ARGS(Ap), */
/* 0, B, ldb ); */
/* // B += kI */
/* /\* for( size_t i = 0; i < m*(size_t)ldb; i += ((size_t)ldb+1) ) *\/ */
/* /\* B[i] += k; *\/ */
/* /\* Solve via Cholesky Decomp *\/ */
/* /\* B^T (A^*)^T = A and B = B^T (Hermitian) *\/ */
/* aa_cla_dposv( 'U', (int)m, (int)n, */
/* B, ldb, */
/* AA_MAT_ARGS(Ap) ); */
/* aa_dmat_trans( Ap, As ); */
/* aa_mem_region_pop( reg, Ap ); */
}
int
aa_dmat_dpinv( const struct aa_dmat *A, double k, struct aa_dmat *As)
{
aa_la_check_size(A->rows, As->cols);
aa_la_check_size(A->cols, As->rows);
// TODO: Try DGESV for non-positive-definite matrices
size_t m = A->rows;
size_t n = A->cols;
struct aa_mem_region *reg = aa_mem_region_local_get();
void *ptrtop = aa_mem_region_ptr(reg);
int r = -1;
/* As = inv(A'*A - k*I) * A' A'*inv(A*A' - k*I) */
if( m <= n ) {
/*
* (A^*) = A^T*inv(A*A^T - k*I)
* (A^*) = A^T*inv(B)
* (A^*)*B = A^T
* B^T (A^*)^T = A and B = B^T (Hermitian)
*
*/
/* Use A_star as workspace for B */
double *B = As->data;
int ldb = (int)(As->ld);
/* Ap = A */
struct aa_dmat *Ap = aa_dmat_alloc(reg,m,n);
aa_dmat_lacpy( "A", A, Ap );
// B is symmetric. Only compute the upper half.
// B = A * A'
cblas_dsyrk( CblasColMajor, CblasUpper, CblasNoTrans,
MAT_ROWS(Ap), MAT_COLS(Ap),
1, AA_MAT_ARGS(Ap),
0, B, ldb );
/* B += kI */
for( double *x = B, *e = B+(int)m*ldb; x < e; x+=ldb+1 )
*x += k;
/* B^T (A^*)^T = A and B = B^T (Hermitian) */
/* Solve via Cholesky (positive definite) */
r = aa_cla_dposv( 'U', (int)m, (int)n,
B, ldb,
AA_MAT_ARGS(Ap) );
/* Solve via LU */
/* int *ipiv = AA_MEM_REGION_NEW_N(reg,int,m); */
/* r = aa_la_d_sysv( "U", m, n, */
/* B, (size_t)ldb, */
/* ipiv, */
/* Ap->data, Ap->ld ); */
aa_dmat_trans( Ap, As );
} else {
/*
* (A^*) = inv(A^T*A - k*I) * A^T
* (A^*) = inv(B) * A^T
* B*(A^*) = A^T
*/
/* Use A_star as workspace for B */
double *B = AA_MEM_REGION_NEW_N(reg,double,n*n);
int ldb = (int)(n);
/* As = A^T */
aa_dmat_trans( A, As );
// B is symmetric. Only compute the upper half.
// B = A' * A = As * As'
cblas_dsyrk( CblasColMajor, CblasUpper, CblasNoTrans,
MAT_ROWS(As), MAT_COLS(As),
1, AA_MAT_ARGS(As),
0, B, ldb );
/* B += kI */
//for( size_t i = 0; i < n*(size_t)ldb; i += ((size_t)ldb+1) )
for( double *x = B, *e = B+n*n; x < e; x+=ldb+1 )
*x += k;
/* B * (A^*)^T = A and B = B^T (Hermitian) */
/* Solve via Cholesky (positive definite) */
r = aa_cla_dposv( 'U', (int)n, (int)m,
B, ldb,
AA_MAT_ARGS(As) );
/* Solve via LU */
/* int *ipiv = AA_MEM_REGION_NEW_N(reg,int,n); */
/* r = aa_la_d_sysv( "U", n, m, */
/* B, (size_t)ldb, */
/* ipiv, */
/* As->data, As->ld ); */
}
aa_mem_region_pop( reg, ptrtop );
return r;
}
int
aa_dmat_dzdpinv( const struct aa_dmat *A, double s_min, struct aa_dmat *As)
{
aa_la_check_size(A->rows, As->cols);
aa_la_check_size(A->cols, As->rows);
struct aa_mem_region *reg = aa_mem_region_local_get();
void *ptrtop = aa_mem_region_ptr(reg);
size_t kmin, kmax;
double *U, *Vt, *S;
s_svd_helper( A, reg,
&kmin, &kmax, &U, &Vt, &S );
size_t m = A->rows;
const int mi = (int)(A->rows);
const int ni = (int)(A->cols);
// \sum s_i/(s_i**2+k) * v_i * u_i^T
aa_dmat_zero(As);
double *Asd = As->data;
size_t i = 0;
// Undamped parts
for( ; i < kmin && S[i] >= s_min; i ++ ) {
cblas_dger( CblasColMajor, ni, mi, 1/S[i],
Vt + i, ni,
U + m*i, 1,
Asd, ni
);
}
// Damped parts
double s2 = s_min*s_min;
for( ; i < kmin; i ++ ) {
cblas_dger( CblasColMajor, ni, mi, S[i]/s2,
Vt + i, ni,
U + m*i, 1,
Asd, ni
);
}
aa_mem_region_pop( reg, ptrtop );
return 0;
}
| {
"alphanum_fraction": 0.5378104101,
"avg_line_length": 25.5167064439,
"ext": "c",
"hexsha": "b3291373a492b8f84300d23f0eab446b921be827",
"lang": "C",
"max_forks_count": 20,
"max_forks_repo_forks_event_max_datetime": "2022-02-22T01:32:20.000Z",
"max_forks_repo_forks_event_min_datetime": "2016-01-05T18:55:14.000Z",
"max_forks_repo_head_hexsha": "e3063ceeeed7d1a3d55fc0d3071c9aacb4466b22",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "dyalab/amino",
"max_forks_repo_path": "src/mat.c",
"max_issues_count": 28,
"max_issues_repo_head_hexsha": "e3063ceeeed7d1a3d55fc0d3071c9aacb4466b22",
"max_issues_repo_issues_event_max_datetime": "2021-03-22T23:43:23.000Z",
"max_issues_repo_issues_event_min_datetime": "2016-05-18T20:54:44.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "dyalab/amino",
"max_issues_repo_path": "src/mat.c",
"max_line_length": 92,
"max_stars_count": 32,
"max_stars_repo_head_hexsha": "e3063ceeeed7d1a3d55fc0d3071c9aacb4466b22",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "dyalab/amino",
"max_stars_repo_path": "src/mat.c",
"max_stars_repo_stars_event_max_datetime": "2022-03-14T16:49:22.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-06-02T20:06:09.000Z",
"num_tokens": 6691,
"size": 21383
} |
#include <gsl/gsl_math.h>
#include "gsl_cblas.h"
#include "cblas.h"
float
cblas_sdsdot (const int N, const float alpha, const float *X, const int incX,
const float *Y, const int incY)
{
#define INIT_VAL alpha
#define ACC_TYPE double
#define BASE float
#include "source_dot_r.h"
#undef ACC_TYPE
#undef BASE
#undef INIT_VAL
}
| {
"alphanum_fraction": 0.7335329341,
"avg_line_length": 19.6470588235,
"ext": "c",
"hexsha": "e7277e2a12703713e1db3518a3a5382d86d88346",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2015-10-02T01:32:59.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-10-02T01:32:59.000Z",
"max_forks_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "ICML14MoMCompare/spectral-learn",
"max_forks_repo_path": "code/em/treba/gsl-1.0/cblas/sdsdot.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "ICML14MoMCompare/spectral-learn",
"max_issues_repo_path": "code/em/treba/gsl-1.0/cblas/sdsdot.c",
"max_line_length": 77,
"max_stars_count": 14,
"max_stars_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "ICML14MoMCompare/spectral-learn",
"max_stars_repo_path": "code/em/treba/gsl-1.0/cblas/sdsdot.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": 96,
"size": 334
} |
/*
* 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 image_a41c29de_bd9b_4bbd_9012_6dc956f524b3_h
#define image_a41c29de_bd9b_4bbd_9012_6dc956f524b3_h
#include <gslib/type.h>
#include <gslib/string.h>
#include <ariel/dirty.h>
__ariel_begin__
class image
{
public:
enum image_format
{
fmt_gray, /* gray8 */
fmt_rgba, /* rgba8888 */
};
friend class imageio;
public:
image();
~image() { destroy(); }
bool is_valid() const;
image_format get_format() const { return _format; }
int get_depth() const { return _depth; }
bool create(image_format fmt, int w, int h);
void destroy();
void init(const color& cr);
void enable_alpha_channel(bool b) { _is_alpha_channel_valid = b; }
bool has_alpha() const { return _is_alpha_channel_valid; }
int get_width() const { return _width; }
int get_height() const { return _height; }
int get_bytes_per_line() const { return _bytes_per_line; }
int get_size() const { return _color_bytes; }
void set_xdpi(int dpi) { _xdpi = dpi; }
void set_ydpi(int dpi) { _ydpi = dpi; }
int get_xdpi() const { return _xdpi; }
int get_ydpi() const { return _ydpi; }
byte* get_data(int x, int y) const;
byte* get_bits() const { return _data; }
bool load(const string& filepath);
bool load(const gchar* filepath, int len) { return load(string(filepath, len)); }
bool save(const string& filepath) const;
void clear(byte b, const rect* rc = nullptr);
void clear(const color& cr, const rect* rc = nullptr);
void copy(const image& img);
void copy(const image& img, int x, int y, int cx, int cy, int sx, int sy);
protected:
image_format _format;
int _width;
int _height;
int _depth;
int _color_bytes;
int _bytes_per_line;
int _xdpi;
int _ydpi;
byte* _data;
bool _is_alpha_channel_valid;
};
__ariel_end__
#endif
| {
"alphanum_fraction": 0.6451038576,
"avg_line_length": 36.2365591398,
"ext": "h",
"hexsha": "3b6023e80d8cb955bf252424c052a36573101218",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2016-10-19T15:20:58.000Z",
"max_forks_repo_forks_event_min_datetime": "2016-10-19T15:20:58.000Z",
"max_forks_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "lymastee/gslib",
"max_forks_repo_path": "include/ariel/image.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "lymastee/gslib",
"max_issues_repo_path": "include/ariel/image.h",
"max_line_length": 86,
"max_stars_count": 9,
"max_stars_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "lymastee/gslib",
"max_stars_repo_path": "include/ariel/image.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": 816,
"size": 3370
} |
/**
* @file MeshHelpers.h
*
* @brief This header contains mesh related helper functions
*
* @author Stefan Reinhold
* @copyright Copyright (C) 2018 Stefan Reinhold -- All Rights Reserved.
* You may use, distribute and modify this code under the terms of
* the AFL 3.0 license; see LICENSE for full license details.
*/
#pragma once
#include "Mesh.h"
#include <Eigen/Core>
#include <gsl/gsl>
#include <igl/cotmatrix.h>
#include <igl/per_vertex_normals.h>
namespace CortidQCT {
namespace Internal {
template <class T = float>
using VertexMatrix = Eigen::Matrix<T, Eigen::Dynamic, 3>;
template <class T = float> using NormalMatrix = VertexMatrix<T>;
using FacetMatrix =
Eigen::Matrix<typename Mesh<float>::Index, Eigen::Dynamic, 3>;
using LabelVector =
Eigen::Matrix<typename Mesh<float>::Label, Eigen::Dynamic, 1>;
template <class T = float> using LaplacianMatrix = Eigen::SparseMatrix<T>;
/// Returns the Nx3 vertex matrix of the mesh
template <class T> inline VertexMatrix<T> vertexMatrix(Mesh<T> const &mesh) {
return mesh
.withUnsafeVertexPointer([&mesh](auto const *ptr) {
return Eigen::Map<Eigen::Matrix<T, 3, Eigen::Dynamic> const>{
ptr, 3, gsl::narrow<Eigen::Index>(mesh.vertexCount())};
})
.transpose();
}
/// Returns the Mx3 index matrix of the mesh
template <class T> inline FacetMatrix facetMatrix(Mesh<T> const &mesh) {
using Index = typename Mesh<T>::Index;
return mesh
.withUnsafeIndexPointer([&mesh](auto const *ptr) {
return Eigen::Map<Eigen::Matrix<Index, 3, Eigen::Dynamic> const>{
ptr, 3, gsl::narrow<Eigen::Index>(mesh.triangleCount())};
})
.transpose();
}
/// Returns a N-vector containing the per vertex labels
template <class T> inline LabelVector labelVector(Mesh<T> const &mesh) {
using Label = typename Mesh<T>::Label;
return mesh.withUnsafeLabelPointer([&mesh](auto const *ptr) {
return Eigen::Map<Eigen::Matrix<Label, Eigen::Dynamic, 1> const>{
ptr, gsl::narrow<Eigen::Index>(mesh.vertexCount())};
});
}
/// Returns a Nx3 matrix with per-vertex normals
template <class DerivedV, class DerivedF>
inline NormalMatrix<typename DerivedV::Scalar>
perVertexNormalMatrix(Eigen::MatrixBase<DerivedV> const &V,
Eigen::MatrixBase<DerivedF> const &F) {
// output matrix
NormalMatrix<typename DerivedV::Scalar> normals;
igl::per_vertex_normals(V, F, igl::PER_VERTEX_NORMALS_WEIGHTING_TYPE_ANGLE,
normals);
return normals;
}
/// Returns a Nx3 matrix with per-vertex normals
template <class T>
inline NormalMatrix<T> perVertexNormalMatrix(Mesh<T> const &mesh) {
return perVertexNormalMatrix(vertexMatrix(mesh), facetMatrix(mesh));
}
/// Returns the NxN sparse laplacian matrix (using cotangent weights)
template <class DerivedV, class DerivedF>
inline LaplacianMatrix<typename DerivedV::Scalar>
laplacianMatrix(Eigen::MatrixBase<DerivedV> const &V,
Eigen::MatrixBase<DerivedF> const &F) {
// output matrix
Eigen::SparseMatrix<typename DerivedV::Scalar> laplacian;
Expects(V.rows() > 0 && V.cols() == 3);
Expects(F.rows() > 0 && F.cols() == 3);
igl::cotmatrix(V, F, laplacian);
return laplacian;
}
/// Returns the NxN sparse laplacian matrix (using cotangent weights)
template <class T>
inline LaplacianMatrix<T> laplacianMatrix(Mesh<T> const &mesh) {
return laplacianMatrix(vertexMatrix(mesh), facetMatrix(mesh));
}
} // namespace Internal
} // namespace CortidQCT
| {
"alphanum_fraction": 0.6949632145,
"avg_line_length": 33.3396226415,
"ext": "h",
"hexsha": "33771933e0c95cc666b514fd1711bb10a6e617eb",
"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": "5b74c18a3cb7e16541b0cef16ec794c33ef9fa59",
"max_forks_repo_licenses": [
"AFL-3.0"
],
"max_forks_repo_name": "ithron/CortidQCT",
"max_forks_repo_path": "lib/MeshHelpers.h",
"max_issues_count": 28,
"max_issues_repo_head_hexsha": "5b74c18a3cb7e16541b0cef16ec794c33ef9fa59",
"max_issues_repo_issues_event_max_datetime": "2021-04-22T08:11:33.000Z",
"max_issues_repo_issues_event_min_datetime": "2018-10-23T10:51:36.000Z",
"max_issues_repo_licenses": [
"AFL-3.0"
],
"max_issues_repo_name": "ithron/CortidQCT",
"max_issues_repo_path": "lib/MeshHelpers.h",
"max_line_length": 77,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "5b74c18a3cb7e16541b0cef16ec794c33ef9fa59",
"max_stars_repo_licenses": [
"AFL-3.0"
],
"max_stars_repo_name": "ithron/CortidQCT",
"max_stars_repo_path": "lib/MeshHelpers.h",
"max_stars_repo_stars_event_max_datetime": "2021-08-21T17:30:23.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-08-21T17:30:23.000Z",
"num_tokens": 907,
"size": 3534
} |
/**
*
* @file core_stsmlq_corner.c
*
* PLASMA core_blas kernel
* PLASMA is a software package provided by Univ. of Tennessee,
* Univ. of California Berkeley and Univ. of Colorado Denver
*
* @version 2.6.0
* @author Hatem Ltaief
* @author Mathieu Faverge
* @author Azzam Haidar
* @date 2010-11-15
* @generated s Tue Jan 7 11:44:48 2014
*
**/
#include <lapacke.h>
#include "common.h"
#undef COMPLEX
#define REAL
/***************************************************************************//**
*
* @ingroup CORE_float
*
* CORE_stsmlq_corner: see CORE_stsmlq
*
* This kernel applies left and right transformations as depicted below:
* |I -VTV'| * | A1 A2 | * |I - VT'V'|
* | A2' A3 |
* where A1 and A3 are symmetric matrices.
* Only the lower part is referenced.
* This is an adhoc implementation, can be further optimized...
*
*******************************************************************************
*
* @param[in] m1
* The number of rows of the tile A1. m1 >= 0.
*
* @param[in] n1
* The number of columns of the tile A1. n1 >= 0.
*
* @param[in] m2
* The number of rows of the tile A2. m2 >= 0.
*
* @param[in] n2
* The number of columns of the tile A2. n2 >= 0.
*
* @param[in] m3
* The number of rows of the tile A3. m3 >= 0.
*
* @param[in] n3
* The number of columns of the tile A3. n3 >= 0.
*
* @param[in] k
* The number of elementary reflectors whose product defines
* the matrix Q.
*
* @param[in] ib
* The inner-blocking size. ib >= 0.
*
* @param[in] nb
* The blocking size. nb >= 0.
*
* @param[in,out] A1
* On entry, the m1-by-n1 tile A1.
* On exit, A1 is overwritten by the application of Q.
*
* @param[in] lda1
* The leading dimension of the array A1. lda1 >= max(1,m1).
*
* @param[in,out] A2
* On entry, the m2-by-n2 tile A2.
* On exit, A2 is overwritten by the application of Q.
*
* @param[in] lda2
* The leading dimension of the tile A2. lda2 >= max(1,m2).
*
* @param[in,out] A3
* On entry, the m3-by-n3 tile A3.
*
* @param[in] lda3
* The leading dimension of the tile A3. lda3 >= max(1,m3).
*
* @param[in] V
* The i-th row must contain the vector which defines the
* elementary reflector H(i), for i = 1,2,...,k, as returned by
* CORE_STSLQT in the first k rows of its array argument V.
*
* @param[in] ldv
* The leading dimension of the array V. ldv >= max(1,K).
*
* @param[in] T
* The IB-by-n1 triangular factor T of the block reflector.
* T is upper triangular by block (economic storage);
* The rest of the array is not referenced.
*
* @param[in] ldt
* The leading dimension of the array T. ldt >= IB.
*
* @param[out] WORK
* Workspace array of size
* LDWORK-by-m1 if side == PlasmaLeft
* LDWORK-by-IB if side == PlasmaRight
*
* @param[in] ldwork
* The leading dimension of the array WORK.
* LDWORK >= max(1,IB) if side == PlasmaLeft
* LDWORK >= max(1,n1) if side == PlasmaRight
*
*******************************************************************************
*
* @return
* \retval PLASMA_SUCCESS successful exit
* \retval <0 if -i, the i-th argument had an illegal value
*
******************************************************************************/
#if defined(PLASMA_HAVE_WEAK)
#pragma weak CORE_stsmlq_corner = PCORE_stsmlq_corner
#define CORE_stsmlq_corner PCORE_stsmlq_corner
#define CORE_stsmlq PCORE_stsmlq
int CORE_stsmlq(PLASMA_enum side, PLASMA_enum trans,
int m1, int n1, int m2, int n2, int K, int IB,
float *A1, int lda1,
float *A2, int lda2,
const float *V, int ldv,
const float *T, int ldt,
float *WORK, int LDWORK);
#endif
int CORE_stsmlq_corner( int m1, int n1, int m2, int n2, int m3, int n3,
int k, int ib, int nb,
float *A1, int lda1,
float *A2, int lda2,
float *A3, int lda3,
const float *V, int ldv,
const float *T, int ldt,
float *WORK, int ldwork)
{
PLASMA_enum side;
PLASMA_enum trans;
int i, j;
if ( m1 != n1 ) {
coreblas_error(1, "Illegal value of M1, N1");
return -1;
}
/* Rebuild the symmetric block: WORK <- A1 */
for (i = 0; i < m1; i++)
for (j = i; j < n1; j++){
*(WORK + i + j*ldwork) = *(A1 + i + j*lda1);
if (j > i){
*(WORK + j + i*ldwork) = ( *(WORK + i + j*ldwork) );
}
}
/* Copy the transpose of A2: WORK+nb*ldwork <- A2' */
for (j = 0; j < n2; j++)
for (i = 0; i < m2; i++){
*(WORK + j + (i + nb) * ldwork) = ( *(A2 + i + j*lda2) );
}
side = PlasmaRight;
trans = PlasmaTrans;
/* Right application on |A1 A2| */
CORE_stsmlq(side, trans, m1, n1, m2, n2, k, ib,
WORK, ldwork, A2, lda2,
V, ldv, T, ldt,
WORK+3*nb*ldwork, ldwork);
/* Rebuild the symmetric block: WORK+2*nb*ldwork <- A3 */
for (i = 0; i < m3; i++)
for (j = i; j < n3; j++){
*(WORK + i + (j + 2*nb) * ldwork) = *(A3 + i + j*lda3);
if (j > i){
*(WORK + j + (i + 2*nb) * ldwork) = ( *(WORK + i + (j + 2*nb) * ldwork) );
}
}
/* Right application on | A2' A3 | */
CORE_stsmlq(side, trans, n2, m2, m3, n3, k, ib,
WORK+nb*ldwork, ldwork, WORK+2*nb*ldwork, ldwork,
V, ldv, T, ldt,
WORK + 3*nb*ldwork, ldwork);
side = PlasmaLeft;
trans = PlasmaNoTrans;
/* Left application on | A1 | */
/* | A2' | */
CORE_stsmlq(side, trans, m1, n1, n2, m2, k, ib,
WORK, ldwork, WORK+nb*ldwork, ldwork,
V, ldv, T, ldt,
WORK + 3*nb*ldwork, ldwork);
/* Copy back the final result to the upper part of A1 */
/* A1 = WORK */
for (i = 0; i < m1; i++)
for (j = i; j < n1; j++)
*(A1 + i + j*lda1) = *(WORK + i + j*ldwork);
/* Left application on | A2 | */
/* | A3 | */
CORE_stsmlq(side, trans, m2, n2, m3, n3, k, ib,
A2, lda2, WORK+2*nb*ldwork, ldwork,
V, ldv, T, ldt,
WORK + 3*nb*ldwork, ldwork);
/* Copy back the final result to the upper part of A3 */
/* A3 = WORK+2*nb*ldwork */
for (i = 0; i < m3; i++)
for (j = i; j < n3; j++)
*(A3 + i + j*lda3) = *(WORK + i + (j+ 2*nb) * ldwork);
return PLASMA_SUCCESS;
}
| {
"alphanum_fraction": 0.4874692163,
"avg_line_length": 31.6651376147,
"ext": "c",
"hexsha": "65f1fcba3e50f15d82db4eb4b60876989d7d104f",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "zhuangsc/Plasma-ompss1",
"max_forks_repo_path": "core_blas/core_stsmlq_corner.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "zhuangsc/Plasma-ompss1",
"max_issues_repo_path": "core_blas/core_stsmlq_corner.c",
"max_line_length": 92,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "zhuangsc/Plasma-ompss1",
"max_stars_repo_path": "core_blas/core_stsmlq_corner.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 2124,
"size": 6903
} |
//
// Created by Harold on 2020/10/7.
//
#ifndef M_MATH_M_HIST_H
#define M_MATH_M_HIST_H
#include <gsl/gsl_histogram.h>
#include <gsl/gsl_histogram2d.h>
#include <vector>
#include <utility>
namespace M_MATH {
template<typename T>
class Histogram1D {
public:
// [min, max), it: <x>
template<typename IT>
Histogram1D(IT begin, IT end, T min, T max, size_t N);
~Histogram1D() { gsl_histogram_free(h); gsl_histogram_pdf_free(p); };
// counts in every bin
std::vector<size_t> counts();
// bins with [lower, upper] boundaries
std::vector<std::pair<T, T>> bins();
// probability distribution, r in [0, 1]
double pdf_sample(double r);
// standard deviation of the histogrammed variable
double sigma() { return gsl_histogram_sigma(h); }
// mean of the histogrammed variable
double mean() { return gsl_histogram_mean(h); }
// sum of all bin values
double sum() { return gsl_histogram_sum(h); }
// find x in which bin
size_t find(double x) { size_t idx; gsl_histogram_find(h, x, &idx); return idx; }
private:
gsl_histogram *h;
gsl_histogram_pdf *p;
};
template<typename T>
class Histogram2D {
public:
// [min, max), it: <x, y>
template<typename IT>
Histogram2D(IT begin, IT end, T xmin, T xmax, T ymin, T ymax, size_t xdim, size_t ydim);
~Histogram2D() { gsl_histogram2d_free(h); gsl_histogram2d_pdf_free(p); };
// counts in every bin
std::vector<size_t> counts();
// bins with [lower, upper] boundaries, <xrange, yrange>
std::pair<std::vector<std::pair<T, T>>, std::vector<std::pair<T, T>>> bins();
// probability distribution <x, y>, r1, r2 in [0, 1]
std::pair<double, double> pdf_sample(double r1, double r2);
// standard deviation of the histogrammed x and y variables
std::pair<double, double> sigma() { return std::make_pair(gsl_histogram2d_xsigma(h), gsl_histogram2d_ysigma(h)); }
// mean of the histogrammed x and y variables
std::pair<double, double> mean() { return std::make_pair(gsl_histogram2d_xmean(h), gsl_histogram2d_ymean(h)); }
// sum of all bin values
double sum() { return gsl_histogram2d_sum(h); }
// covariance of the histogrammed x and y variables
double cov() { return gsl_histogram2d_cov(h); }
// find x in which bin, <x, y>
std::pair<size_t, size_t> find(double x, double y) { size_t xidx, yidx; gsl_histogram2d_find(h, x, y, &xidx, &yidx); return std::make_pair(xidx, yidx); }
private:
gsl_histogram2d *h;
gsl_histogram2d_pdf *p;
};
template<typename T>
template<typename IT>
Histogram1D<T>::Histogram1D(IT const begin, IT const end, T min, T max, size_t N) : h(nullptr), p(nullptr) {
h = gsl_histogram_alloc(N);
gsl_histogram_set_ranges_uniform(h, min, max);
for (auto it = begin; it != end; ++it)
gsl_histogram_increment(h, *it);
}
template<typename T>
std::vector<size_t> Histogram1D<T>::counts() {
std::vector<size_t> res(h->n);
for (auto i = 0; i < h->n; ++i)
res[i] = gsl_histogram_get(h, i);
return res;
}
template<typename T>
std::vector<std::pair<T, T>> Histogram1D<T>::bins() {
std::vector<std::pair<T, T>> res(h->n);
double lower, upper;
for (auto i = 0; i < h->n; ++i) {
gsl_histogram_get_range(h, i, &lower, &upper);
res[i] = std::make_pair(lower, upper);
}
return res;
}
template<typename T>
double Histogram1D<T>::pdf_sample(double r) {
if (p == nullptr) {
p = gsl_histogram_pdf_alloc(h->n);
gsl_histogram_pdf_init(p, h);
}
return gsl_histogram_pdf_sample(p, r);
}
template<typename T>
template<typename IT>
Histogram2D<T>::Histogram2D(IT begin, IT end,
T xmin, T xmax,
T ymin, T ymax,
size_t xdim, size_t ydim) : h(nullptr), p(nullptr) {
h = gsl_histogram2d_alloc(xdim, ydim);
gsl_histogram2d_set_ranges_uniform(h, xmin, xmax, ymin, ymax);
for (auto it = begin; it != end; ++it)
gsl_histogram2d_increment(h, (*it).x, (*it).y);
}
template<typename T>
std::vector<size_t> Histogram2D<T>::counts() {
std::vector<size_t> res((h->nx) * (h->ny));
for (auto i = 0; i < h->nx; ++i)
for (auto j = 0; j < h->ny; ++j)
res[j * (h->nx) + i] = gsl_histogram2d_get(h, i, j);
return res;
}
template<typename T>
std::pair<std::vector<std::pair<T, T>>, std::vector<std::pair<T, T>>> Histogram2D<T>::bins() {
std::vector<std::pair<T, T>> xrange(h->nx), yrange(h->ny);
double lower, upper;
for (auto i = 0; i < h->nx; ++i) {
gsl_histogram2d_get_xrange(h, i, &lower, &upper);
xrange[i] = std::make_pair(lower, upper);
}
for (auto i = 0; i < h->ny; ++i) {
gsl_histogram2d_get_yrange(h, i, &lower, &upper);
yrange[i] = std::make_pair(lower, upper);
}
return std::make_pair(xrange, yrange);
}
template<typename T>
std::pair<double, double> Histogram2D<T>::pdf_sample(double r1, double r2) {
if (p == nullptr) {
p = gsl_histogram2d_pdf_alloc(h->nx, h->ny);
gsl_histogram2d_pdf_init(p, h);
}
double x, y;
gsl_histogram2d_pdf_sample(p, r1, r2, &x, &y);
return std::make_pair(x, y);
}
}
#endif //M_MATH_M_HIST_H
| {
"alphanum_fraction": 0.5730943265,
"avg_line_length": 37.0709677419,
"ext": "h",
"hexsha": "230cd969a6ac33eaa0861e870a66f7f73909f339",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2021-07-04T12:26:12.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-07-04T12:26:12.000Z",
"max_forks_repo_head_hexsha": "2815ed395b0c51a6cab2f20754a6edeee44bd495",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "Harold2017/m_math",
"max_forks_repo_path": "include/m_hist.h",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "2815ed395b0c51a6cab2f20754a6edeee44bd495",
"max_issues_repo_issues_event_max_datetime": "2021-08-04T06:32:29.000Z",
"max_issues_repo_issues_event_min_datetime": "2021-08-03T02:50:20.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "Harold2017/m_math",
"max_issues_repo_path": "include/m_hist.h",
"max_line_length": 161,
"max_stars_count": 2,
"max_stars_repo_head_hexsha": "2815ed395b0c51a6cab2f20754a6edeee44bd495",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "Harold2017/m_math",
"max_stars_repo_path": "include/m_hist.h",
"max_stars_repo_stars_event_max_datetime": "2021-08-18T08:00:15.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-07-04T12:26:11.000Z",
"num_tokens": 1580,
"size": 5746
} |
/* include */
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include <sys/time.h>
#include <time.h>
#include <globes/globes.h> /* GLoBES library */
#include <gsl/gsl_math.h> /* GNU Scientific library (required for root finding) */
#include <gsl/gsl_roots.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_deriv.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_cdf.h>
#include <gsl/gsl_randist.h>
#include <gsl/gsl_spline.h>
#include "hdf5.h"
#include <stdarg.h>
#define degree 0.0174
double min (int n, ...) {
/*
n是參數個數,後面才是參數本身
*/
int i;
double min_num = 1e20;
double input;
va_list vl;
va_start(vl,n);
for ( i = 0 ; i < n ; i++ ) {
input = va_arg(vl,double);
min_num = min_num > input ? input : min_num;
}
va_end(vl);
return min_num;
}
/***************************************************************************
* M A I N P R O G R A M *
***************************************************************************/
/* 定義3 sigma range 的Prior (For NO) */
double prior_3sigma_NO(const glb_params in, void* user_data) {
glb_params central_values = glbAllocParams();
glb_params input_errors = glbAllocParams();
glb_projection p = glbAllocProjection();
glbGetCentralValues(central_values);
glbGetInputErrors(input_errors);
glbGetProjection(p);
int i;
double pv = 0.0,
fit_theta12,
fit_theta13,
fit_theta23,
fit_deltacp,
fit_ldm,
fit_sdm;
/* 取得參數目前Fit Value */
fit_theta12 = glbGetOscParams(in,0);
fit_theta13 = glbGetOscParams(in,1);
fit_theta23 = glbGetOscParams(in,2);
fit_deltacp = glbGetOscParams(in,3);
fit_sdm = glbGetOscParams(in,4);
fit_ldm = glbGetOscParams(in,5);
/* 判斷參數是否要引入Prior */
if (glbGetProjectionFlag(p,0)==GLB_FREE){
if (fit_theta12 > 35.86 *degree || fit_theta12 < 31.27 *degree){
pv += 1e20;
}
}
if (glbGetProjectionFlag(p,1)==GLB_FREE){
if (fit_theta13 > 8.97 *degree || fit_theta13 < 8.20 *degree){
pv += 1e20;
}
}
if (glbGetProjectionFlag(p,2)==GLB_FREE){
if (fit_theta23 > 51.80 *degree || fit_theta23 < 39.60 *degree ){
pv += 1e20;
}
}
if (glbGetProjectionFlag(p,3)==GLB_FREE){
if (fit_deltacp == 0 *degree || fit_deltacp == 180 *degree || fit_deltacp < 0 *degree|| fit_deltacp > 360 *degree){
pv += 1e20;
}
}
if (glbGetProjectionFlag(p,4)==GLB_FREE){
if (fit_sdm > 8.04 *1e-5 || fit_sdm < 6.82 *1e-5){
pv += 1e20;
}
}
if (glbGetProjectionFlag(p,5)==GLB_FREE){
if (fit_ldm > 2.598 *1e-3 || fit_ldm < 2.431 *1e-3){
pv += 1e20;
}
}
glbFreeParams(central_values);
glbFreeParams(input_errors);
glbFreeProjection(p);
return pv;
}
/* 定義3 sigma range 的Prior (For IO) */
double prior_3sigma_IO(const glb_params in, void* user_data)
{
glb_params central_values = glbAllocParams();
glb_params input_errors = glbAllocParams();
glb_projection p = glbAllocProjection();
glbGetCentralValues(central_values);
glbGetInputErrors(input_errors);
glbGetProjection(p);
int i;
double pv = 0.0,
fit_theta12,
fit_theta13,
fit_theta23,
fit_deltacp,
fit_ldm,
fit_sdm;
/* 取得參數目前Fit Value */
fit_theta12 = glbGetOscParams(in,0);
fit_theta13 = glbGetOscParams(in,1);
fit_theta23 = glbGetOscParams(in,2);
fit_deltacp = glbGetOscParams(in,3);
fit_sdm = glbGetOscParams(in,4);
fit_ldm = glbGetOscParams(in,5);
/* 判斷參數是否要引入Prior */
if(glbGetProjectionFlag(p,0)==GLB_FREE){
if(fit_theta12 > 35.87 *degree || fit_theta12 < 31.27 *degree){
pv += 1e20;
}
}
if(glbGetProjectionFlag(p,1)==GLB_FREE){
if(fit_theta13 > 8.98 *degree || fit_theta13 < 8.24 *degree){
pv += 1e20;
}
}
if(glbGetProjectionFlag(p,2)==GLB_FREE){
if(fit_theta23 > 52.00 *degree || fit_theta23 < 39.90 *degree ){
pv += 1e20;
}
}
if(glbGetProjectionFlag(p,3)==GLB_FREE){
if(fit_deltacp == 0 *degree || fit_deltacp == 180 *degree ){
pv += 1e20;
}
}
if(glbGetProjectionFlag(p,4)==GLB_FREE){
if(fit_sdm > 8.04 *1e-5 || fit_sdm < 6.82 *1e-5){
pv += 1e20;
}
}
if(glbGetProjectionFlag(p,5)==GLB_FREE){
if(fit_ldm < -2.583 *1e-3 || fit_ldm > -2.412 *1e-3){
pv += 1e20;
}
}
glbFreeParams(central_values);
glbFreeParams(input_errors);
glbFreeProjection(p);
return pv;
}
/* Poisson亂數生成器 */
int random_poisson(double mu) {
const gsl_rng_type * T;
gsl_rng * r;
int test;
int i;
gsl_rng_env_setup();
struct timeval tv; // Seed generation based on time
gettimeofday(&tv,0);
unsigned long mySeed = tv.tv_sec + tv.tv_usec;
T = gsl_rng_default;
r = gsl_rng_alloc (T);
gsl_rng_set(r, mySeed);
unsigned int k = gsl_ran_poisson (r, mu);
gsl_rng_free (r);
return k;
}
/* 定義Poisson Likelihood Function */
inline double poisson_likelihood(double true_rate, double fit_rate) {
double res = 0 ;
true_rate = true_rate == 0 ? (true_rate+1e-9) : true_rate;
fit_rate = fit_rate == 0 ? (fit_rate+1e-9) : fit_rate;
res = fit_rate - true_rate;
if (fit_rate <= 0.0) {
res = 1e100;
} else if (true_rate > 0) {
res += true_rate * log(true_rate/fit_rate);
}
return 2.0 * res;
}
/* 對True Value Spectrum 做Poisson Fluctuation */
void do_poisson_fluctuation(glb_params test_values, int mode_expr, double* dataset, int* dset_info) {
glbSetOscillationParameters(test_values);
glbSetRates();
int ew_low,
ew_high,
i,
ladder = 0;
int count_dpf = 0;
int num_channel,
num_bins,
cumu_bins;
if (mode_expr == 0){
/* Deprecated
double *ve_dune = glbGetRuleRatePtr(0, 0);
double *vebar_dune = glbGetRuleRatePtr(0, 1);
double *vu_dune = glbGetRuleRatePtr(0, 2);
double *vubar_dune = glbGetRuleRatePtr(0, 3);
*/
num_channel = 4;
cumu_bins = 0;
for (int channel = 0; channel < num_channel; channel++){
double *target = glbGetRuleRatePtr(mode_expr, channel);
glbGetEnergyWindowBins(mode_expr, channel, &ew_low, &ew_high);
num_bins = ew_high - ew_low + 1;
count_dpf = 0;
for (i=ew_low; i <= ew_high; i++) {
*(dataset + cumu_bins + count_dpf) = random_poisson(target[i]);
count_dpf += 1;
}
cumu_bins += num_bins;
*(dset_info + channel) = num_bins;
}
} else if (mode_expr == 1){
/* Deprecated
double *ve_t2hk = glbGetRuleRatePtr(1, 0);
double *vu_t2hk = glbGetRuleRatePtr(1, 1);
double *vebar_t2hk = glbGetRuleRatePtr(1, 2);
double *vubar_t2hk = glbGetRuleRatePtr(1, 3);
*/
num_channel = 4;
cumu_bins = 0;
for (int channel = 0; channel < num_channel; channel++){
double *target = glbGetRuleRatePtr(mode_expr, channel);
glbGetEnergyWindowBins(mode_expr, channel, &ew_low, &ew_high);
num_bins = ew_high - ew_low + 1;
count_dpf = 0;
for (i=ew_low; i <= ew_high; i++) {
*(dataset + cumu_bins + count_dpf) = random_poisson(target[i]);
count_dpf += 1;
}
cumu_bins += num_bins;
*(dset_info + channel) = num_bins;
}
} else if (mode_expr == -1) {
/* Deprecated
double *ve_dune = glbGetRuleRatePtr(0, 0);
double *vebar_dune = glbGetRuleRatePtr(0, 1);
double *vu_dune = glbGetRuleRatePtr(0, 2);
double *vubar_dune = glbGetRuleRatePtr(0, 3);
double *ve_t2hk = glbGetRuleRatePtr(1, 0);
double *vu_t2hk = glbGetRuleRatePtr(1, 1);
double *vebar_t2hk = glbGetRuleRatePtr(1, 2);
double *vubar_t2hk = glbGetRuleRatePtr(1, 3);
*/
int num_expr = 2;
num_channel = 4;
cumu_bins = 0;
int expr;
for ( expr = 0; expr < num_expr; expr++) {
for (int channel = 0; channel < num_channel; channel++){
double *target = glbGetRuleRatePtr(expr, channel);
glbGetEnergyWindowBins(expr, channel, &ew_low, &ew_high);
num_bins = ew_high - ew_low + 1;
count_dpf = 0;
for (i=ew_low; i <= ew_high; i++) {
*(dataset + cumu_bins + count_dpf) = random_poisson(target[i]);
count_dpf += 1;
}
cumu_bins += num_bins;
*(dset_info + channel) = num_bins;
}
}
} else {
printf("Please inpuit a correct experiment protocol.");
}
}
/* 定義 Chi Square */
double chi2_poisson(int exp, int rule, int np, double *x, double *errors, void* user_data) {
double *signal_fit_rate = glbGetSignalFitRatePtr(exp, rule);
double *bg_fit_rate = glbGetBGFitRatePtr(exp, rule);
double fit_rate;
double chi2 = 0.0;
int i;
int ew_low,
ew_high;
glbGetEnergyWindowBins(exp, rule, &ew_low, &ew_high);
int sum_y = 0,
index,
pos,
count_cp;
int data_info_dune[4] = { 66, 66, 66, 66}; /* {(y_axis_length)} */
int data_info_t2hk[4] = { 8, 12, 8, 12};
int data_info_all[8] = { 66, 66, 66, 66, 8, 12, 8, 12};
switch (exp) {
case 0:
for ( pos = 0; pos < rule; pos ++){
sum_y += data_info_dune[pos];
}
for (i=ew_low; i <= ew_high; i++) {
fit_rate = signal_fit_rate[i] + bg_fit_rate[i];
chi2 += poisson_likelihood( *( (double*) user_data + sum_y + i), fit_rate);
}
break;
case 1:
for ( pos = 0; pos < rule; pos ++){
sum_y += data_info_t2hk[pos];
}
for (i=ew_low; i <= ew_high; i++) {
fit_rate = signal_fit_rate[i] + bg_fit_rate[i];
chi2 += poisson_likelihood( *( (double*) user_data + sum_y + i), fit_rate);
}
break;
}
return chi2;
}
/* 定義 Test Statistic (Delta Chi-Square) */
//參數:{CP : [0, 180, 1], MO : [1, -1] , CPV Hypothesis的deltacp}
// 0 : CPC at deltacp=0; 180 : CPC at deltacp=180; 1 : CPV at deltacp
//選定實驗EXP:[0,1,GLB_ALL]
double delta_chi2 (int CP, int MO, double deltacp, int EXP) {
double a = 0,
b = 0;
double chi_0_NO,
chi_0_IO,
chi_pi_NO,
chi_pi_IO,
chi_cpv_NO,
chi_cpv_IO;
int data_info_dune[6] = {4, 264, 66, 66, 66, 66}; /* {(y_axis_length)} */
int data_info_t2hk[6] = {4, 40, 8, 12, 8, 12};
int data_info_all[10] = {8, 304, 66, 66, 66, 66, 8, 12, 8, 12};
double *darray;
int sum_y = 0,
ladder = 0,
index_sum,
i_idx, j_idx;
int LENGTH = EXP != -1 ? 4 : 8;
int dset_y_info[LENGTH];
/* 定義global fit參數(Normal Ordering, NuFIT 5.0, 2020) */
double theta12_N = 33.44;
double theta13_N = 8.57;
double theta23_N = 49;
double sdm_N = 7.42;
double ldm_N = 2.514;
/* 定義global fit參數(Inverse Ordering, NuFIT 5.0, 2020) */
double theta12_I = 33.45;
double theta13_I = 8.61;
double theta23_I = 49.3;
double sdm_I = 7.42;
double ldm_I = -2.497;
switch (EXP){
case 0:
for ( index_sum = 2; index_sum < 6; index_sum++ ){
sum_y += data_info_dune[index_sum];
}
darray = malloc( data_info_dune[0] * sum_y * sizeof(double));
break;
case 1:
for ( index_sum = 2; index_sum < 6; index_sum++ ){
sum_y += data_info_t2hk[index_sum];
}
darray = malloc( data_info_t2hk[0] * sum_y * sizeof(double));
break;
case -1:
for ( index_sum = 2; index_sum < 10; index_sum++ ){
sum_y += data_info_all[index_sum];
}
darray = malloc( data_info_all[0] * sum_y * sizeof(double));
break;
}
//根據CP、MO的假設,生成Poisson Sample,計算其test statistic
/* 定義glb_params */
glb_params test_values_cpc_0_NO = glbAllocParams();
glb_params test_values_cpc_0_IO = glbAllocParams();
glb_params test_values_cpc_pi_NO = glbAllocParams();
glb_params test_values_cpc_pi_IO = glbAllocParams();
glb_params test_values_cpv_NO = glbAllocParams();
glb_params test_values_cpv_IO = glbAllocParams();
glb_params input_errors = glbAllocParams();
glb_params minimum = glbAllocParams(); //////////
/* 定義test_values_cpc_0_NO */
glbDefineParams(test_values_cpc_0_NO, theta12_N*degree, theta13_N*degree, theta23_N*degree, 0*degree, 1e-5*sdm_N, 1e-3*ldm_N);
glbSetDensityParams(test_values_cpc_0_NO,1.0,GLB_ALL);
/* 定義test_values_cpc_0_IO */
glbDefineParams(test_values_cpc_0_IO, theta12_I*degree, theta13_I*degree, theta23_I*degree, 0*degree, 1e-5*sdm_I, 1e-3*ldm_I);
glbSetDensityParams(test_values_cpc_0_IO,1.0,GLB_ALL);
/* 定義test_values_cpc_pi_NO */
glbDefineParams(test_values_cpc_pi_NO, theta12_N*degree, theta13_N*degree, theta23_N*degree, 180*degree, 1e-5*sdm_N, 1e-3*ldm_N);
glbSetDensityParams(test_values_cpc_pi_NO,1.0,GLB_ALL);
/* 定義test_values_cpc_pi_IO */
glbDefineParams(test_values_cpc_pi_IO, theta12_I*degree, theta13_I*degree, theta23_I*degree, 180*degree, 1e-5*sdm_I, 1e-3*ldm_I);
glbSetDensityParams(test_values_cpc_pi_IO,1.0,GLB_ALL);
/* 定義test_values_cpv_NO */ //deltacp為Input的值
glbDefineParams(test_values_cpv_NO, theta12_N*degree, theta13_N*degree, theta23_N*degree, deltacp*degree, 1e-5*sdm_N, 1e-3*ldm_N);
glbSetDensityParams(test_values_cpv_NO,1.0,GLB_ALL);
/* 定義test_values_cpv_IO */ //deltacp為Input的值
glbDefineParams(test_values_cpv_IO, theta12_I*degree, theta13_I*degree, theta23_I*degree, deltacp*degree, 1e-5*sdm_I, 1e-3*ldm_I);
glbSetDensityParams(test_values_cpv_IO,1.0,GLB_ALL);
/* 設定Projection */
glb_projection projection_cp_fixed = glbAllocProjection();
glb_projection projection_cp_free = glbAllocProjection();
//GLB_FIXED/GLB_FREE theta12 theta13 theta23 deltacp m21 m31
glbDefineProjection(projection_cp_fixed, GLB_FIXED, GLB_FREE, GLB_FREE, GLB_FIXED, GLB_FIXED, GLB_FREE);//deltacp theta12 m21 不動,其他可變
glbSetDensityProjectionFlag(projection_cp_fixed,GLB_FIXED,GLB_ALL);//matter density不變
//GLB_FIXED/GLB_FREE theta12 theta13 theta23 deltacp m21 m31
glbDefineProjection(projection_cp_free, GLB_FIXED, GLB_FREE, GLB_FREE, GLB_FREE, GLB_FIXED, GLB_FREE);// theta12 m21 不動,其他可變
glbSetDensityProjectionFlag(projection_cp_free,GLB_FIXED,GLB_ALL);//matter density不變
/* 關閉系統誤差 */
glbSwitchSystematics(GLB_ALL,GLB_ALL,GLB_OFF);
/* 設定Input_errors */
glbDefineParams(input_errors,0,0,0,0,0,0);
glbSetDensityParams(input_errors,0,GLB_ALL);
glbSetInputErrors(input_errors);
/* 根據MO,CP的假設,生成 Poisson Spectrum */
switch (MO) {
case 1:
if (CP == 0){ //CPC at deltacp=0
printf("生成deltacp = 0, NO 的Poisson Spectrum \n");
/* 根據CPC_0_NO的假設,生成Poisson True Spectrum */
do_poisson_fluctuation(test_values_cpc_0_NO, EXP, darray, dset_y_info);
}
if (CP == 180){ //CPC at deltacp=180
printf("生成deltacp = 180, NO 的Poisson Spectrum \n");
/* 根據CPC_0_IO的假設,生成Poisson True Spectrum */
do_poisson_fluctuation(test_values_cpc_pi_NO, EXP, darray, dset_y_info);
}
if (CP == 1){ //CPV
printf("生成deltacp = input value, NO 的Poisson Spectrum \n");
/* 根據CPV_NO的假設,生成Poisson True Spectrum */
do_poisson_fluctuation(test_values_cpv_NO, EXP, darray, dset_y_info);
}
break;
case -1:
if (CP == 0){ //CPC at deltacp=0
printf("生成deltacp = 0, IO 的Poisson Spectrum \n");
/* 根據CPC_0_NO的假設,生成Poisson True Spectrum */
do_poisson_fluctuation(test_values_cpc_0_IO, EXP, darray, dset_y_info);
}
if (CP == 180){ //CPC at deltacp=180
printf("生成deltacp = 180, IO 的Poisson Spectrum \n");
/* 根據CPC_0_IO的假設,生成Poisson True Spectrum */
do_poisson_fluctuation(test_values_cpc_pi_IO, EXP, darray, dset_y_info);
}
if (CP == 1){ //CPV
printf("生成deltacp = input value, IO 的Poisson Spectrum \n");
/* 根據CPV_IO的假設,生成Poisson True Spectrum */
do_poisson_fluctuation(test_values_cpv_IO, EXP, darray, dset_y_info);
}
break;
}
/* 計算CPC Hypothesis (4種情況)*/
/* 設定Prior (3 sigma range, Normal Ordering)*/
glbRegisterPriorFunction(prior_3sigma_NO,NULL,NULL,NULL);
/* 計算Chi square under cpc_0_NO */
glbSetProjection(projection_cp_fixed); //設定Projection deltacp_Fixed
glbSetOscillationParameters(test_values_cpc_0_NO);
glbSetRates();
glbDefineChiFunction(&chi2_poisson, 0, "chi2_poisson", darray);
glbSetChiFunction(GLB_ALL, GLB_ALL, GLB_OFF, "chi2_poisson", NULL);
glbSetCentralValues(test_values_cpc_0_NO);
chi_0_NO = glbChiNP(test_values_cpc_0_NO, minimum ,EXP);
/* 計算Chi square under cpc_pi_NO */
glbSetProjection(projection_cp_fixed); //設定Projection deltacp_Fixed
glbSetOscillationParameters(test_values_cpc_pi_NO);
glbSetRates();
glbDefineChiFunction(&chi2_poisson, 0, "chi2_poisson", darray);
glbSetChiFunction(GLB_ALL, GLB_ALL, GLB_OFF, "chi2_poisson", NULL);
glbSetCentralValues(test_values_cpc_pi_NO);
chi_pi_NO = glbChiNP(test_values_cpc_pi_NO, minimum ,EXP);
/* 設定Prior (3 sigma range, Inverse Ordering)*/
glbRegisterPriorFunction(prior_3sigma_IO,NULL,NULL,NULL);
/* 計算Chi square under cpc_0_IO */
glbSetProjection(projection_cp_fixed); //設定Projection deltacp_Fixed
glbSetOscillationParameters(test_values_cpc_0_IO);
glbSetRates();
glbDefineChiFunction(&chi2_poisson, 0, "chi2_poisson", darray);
glbSetChiFunction(GLB_ALL, GLB_ALL, GLB_OFF, "chi2_poisson", NULL);
glbSetCentralValues(test_values_cpc_0_IO);
chi_0_IO = glbChiNP(test_values_cpc_0_IO, minimum ,EXP);
/* 計算Chi square under cpc_pi_IO */
glbSetProjection(projection_cp_fixed); //設定Projection deltacp_Fixed
glbSetOscillationParameters(test_values_cpc_pi_IO);
glbSetRates();
glbDefineChiFunction(&chi2_poisson, 0, "chi2_poisson", darray);
glbSetChiFunction(GLB_ALL, GLB_ALL, GLB_OFF, "chi2_poisson", NULL);
glbSetCentralValues(test_values_cpc_pi_IO);
chi_pi_IO = glbChiNP(test_values_cpc_pi_IO, minimum ,EXP);
/* 取 chi_0_NO , chi_pi_NO, chi_0_IO , chi_pi_IO 四者之最小值 */
a = min(4, chi_0_NO, chi_pi_NO, chi_0_IO, chi_pi_IO);
/* 計算CPV Hypothesis (2種情況)*/
/* 設定Prior (3 sigma range, Normal Ordering)*/
glbRegisterPriorFunction(prior_3sigma_NO, NULL, NULL, NULL);
/* 設定Projection (deltacp_Free)*/
glbSetProjection(projection_cp_free);
/* 計算Chi square under cpv_NO */
glbSetOscillationParameters(test_values_cpv_NO);
glbSetRates();
glbDefineChiFunction(&chi2_poisson, 0, "chi2_poisson", darray);
glbSetChiFunction(GLB_ALL, GLB_ALL, GLB_OFF, "chi2_poisson", NULL);
glbSetCentralValues(test_values_cpv_NO);
chi_cpv_NO = glbChiNP(test_values_cpv_NO, minimum, EXP);
/* 設定Prior (3 sigma range, Inverse Ordering)*/
glbRegisterPriorFunction(prior_3sigma_IO, NULL, NULL, NULL);
/* 設定Projection (deltacp_Free)*/
glbSetProjection(projection_cp_free);
/* 計算Chi square under cpv_IO */
glbSetOscillationParameters(test_values_cpv_IO);
glbSetRates();
glbDefineChiFunction(&chi2_poisson, 0, "chi2_poisson", darray);
glbSetChiFunction(GLB_ALL, GLB_ALL, GLB_OFF, "chi2_poisson", NULL);
glbSetCentralValues(test_values_cpv_IO);
chi_cpv_IO = glbChiNP(test_values_cpv_IO, minimum, EXP);
/* 取 chi_cpv_NO , chi_cpv_IO 兩者之最小值 */
b = min(2, chi_cpv_NO, chi_cpv_IO);
/* 輸出Delta Chi square */
printf("a = %g, b = %g \n",a,b);
printf("a - b = %g \n",a-b);
free(darray);
return a-b;
}
int main(int argc, char *argv[]) {
char filename[32];
strcpy(filename, argv[1]);
int TOTALsample = atof(argv[2]);
double angle = atof(argv[3]);
int expr = atof(argv[4]);
/*
* Declare the variables for hdf5.
*/
hid_t file_id,
space_id,
dset_id,
group_id,
sub_group_id;
herr_t status;
hsize_t dims_q0[2] = {TOTALsample, 4},
dims_q1[1] = {TOTALsample};
glbInit(argv[0]);
glbInitExperiment("./DUNE2021/DUNE_GLoBES.glb",&glb_experiment_list[0],&glb_num_of_exps);
glbInitExperiment("./HK_globes/HK_combined_coarse.glb",&glb_experiment_list[0],&glb_num_of_exps);
printf("File name: %s\n",filename);
double q0, q1;
double Q0[TOTALsample][4],
Q1[TOTALsample];
for (int num_simulatiom = 0; num_simulatiom < TOTALsample; num_simulatiom++) {
q0 = delta_chi2(0 , 1 , angle, expr);
Q0[num_simulatiom][0] = q0;
q0 = delta_chi2(180, 1 , angle, expr);
Q0[num_simulatiom][1] = q0;
q0 = delta_chi2(0, -1 , angle, expr);
Q0[num_simulatiom][2] = q0;
q0 = delta_chi2(180, -1 , angle, expr);
Q0[num_simulatiom][3] = q0;
q1 = delta_chi2(1 , 1, angle, expr);
Q1[num_simulatiom] = q1;
}
file_id = H5Fcreate(filename, H5F_ACC_TRUNC, H5P_DEFAULT, H5P_DEFAULT);
space_id = H5Screate_simple(2, dims_q0, NULL);
dset_id = H5Dcreate(file_id, "q0", H5T_NATIVE_DOUBLE, space_id, H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT);
status = H5Dwrite(dset_id, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT, Q0);
status = H5Dclose(dset_id);
status = H5Sclose(space_id);
space_id = H5Screate_simple(1, dims_q1, NULL);
dset_id = H5Dcreate(file_id, "q1", H5T_NATIVE_DOUBLE, space_id, H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT);
status = H5Dwrite(dset_id, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT, Q1);
status = H5Dclose(dset_id);
status = H5Sclose(space_id);
status = H5Fclose(file_id);
return 0;
}
| {
"alphanum_fraction": 0.6690884433,
"avg_line_length": 31.8611111111,
"ext": "c",
"hexsha": "64829f2d8c97c24141d299e0ab14456c129d99e6",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2022-02-16T16:25:35.000Z",
"max_forks_repo_forks_event_min_datetime": "2022-02-16T16:25:35.000Z",
"max_forks_repo_head_hexsha": "5d9c6312180c06dfb9cb85bd28a40457849204d2",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "davidho27941/ML4NO",
"max_forks_repo_path": "script/simulation/poisson.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "5d9c6312180c06dfb9cb85bd28a40457849204d2",
"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": "davidho27941/ML4NO",
"max_issues_repo_path": "script/simulation/poisson.c",
"max_line_length": 134,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "5d9c6312180c06dfb9cb85bd28a40457849204d2",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "davidho27941/ML4NO",
"max_stars_repo_path": "script/simulation/poisson.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 7542,
"size": 20646
} |
/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
#pragma once
#include <event.h>
#include <memcached/engine_error.h>
#include <memcached/types.h>
#include <platform/socket.h>
#include <subdoc/operations.h>
#include <gsl/gsl>
#include <mutex>
#include <queue>
#include <unordered_map>
#include <vector>
/** \file
* The main memcached header holding commonly used data
* structures and function prototypes.
*/
/** Maximum length of a key. */
#define KEY_MAX_LENGTH 250
#define MAX_SENDBUF_SIZE (256 * 1024 * 1024)
/* Maximum length of config which can be validated */
#define CONFIG_VALIDATE_MAX_LENGTH (64 * 1024)
/* Maximum IOCTL get/set key and payload (body) length */
#define IOCTL_KEY_LENGTH 128
#define IOCTL_VAL_LENGTH 128
#define MAX_VERBOSITY_LEVEL 2
class Cookie;
class Connection;
struct thread_stats;
void initialize_buckets();
void cleanup_buckets();
void associate_initial_bucket(Connection& connection);
/*
* Functions such as the libevent-related calls that need to do cross-thread
* communication in multithreaded mode (rather than actually doing the work
* in the current thread) are called via "dispatch_" frontends, which are
* also #define-d to directly call the underlying code in singlethreaded mode.
*/
void worker_threads_init();
void threads_shutdown();
void threads_cleanup();
/**
* Create a socketpair and make it non-blocking
*
* @param sockets Where to store the sockets
* @return true if success, false otherwise (and the error reason logged)
*/
bool create_nonblocking_socketpair(std::array<SOCKET, 2>& sockets);
class ListeningPort;
void dispatch_conn_new(SOCKET sfd, std::shared_ptr<ListeningPort>& interface);
void threadlocal_stats_reset(std::vector<thread_stats>& thread_stats);
void notify_io_complete(gsl::not_null<const void*> cookie,
ENGINE_ERROR_CODE status);
void safe_close(SOCKET sfd);
int add_conn_to_pending_io_list(Connection* c,
Cookie* cookie,
ENGINE_ERROR_CODE status);
const char* get_server_version();
bool is_memcached_shutting_down();
/**
* Connection-related functions
*/
/**
* Increments topkeys count for the key specified within the command context
* provided by the cookie.
*/
void update_topkeys(const Cookie& cookie);
struct ServerApi;
ServerApi* get_server_api();
void shutdown_server();
bool associate_bucket(Connection& connection, const char* name);
void disassociate_bucket(Connection& connection);
void disable_listen();
bool is_listen_disabled();
/**
* The executor pool used to pick up the result for requests spawn by the
* client io threads and dispatched over to a background thread (in order
* to allow for out of order replies).
*/
namespace cb {
class ExecutorPool;
}
extern std::unique_ptr<cb::ExecutorPool> executorPool;
void iterate_all_connections(std::function<void(Connection&)> callback);
void start_stdin_listener(std::function<void()> function);
| {
"alphanum_fraction": 0.7443257677,
"avg_line_length": 27.2363636364,
"ext": "h",
"hexsha": "a6070a2b3b84f160c982cbc3e0154b6bb0c67cb2",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2020-04-06T09:20:15.000Z",
"max_forks_repo_forks_event_min_datetime": "2019-10-11T14:00:49.000Z",
"max_forks_repo_head_hexsha": "82f8b20bcd3851bf31c196bd0f228b8c45eb0632",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "daverigby/kv_engine",
"max_forks_repo_path": "daemon/memcached.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "82f8b20bcd3851bf31c196bd0f228b8c45eb0632",
"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": "daverigby/kv_engine",
"max_issues_repo_path": "daemon/memcached.h",
"max_line_length": 79,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "82f8b20bcd3851bf31c196bd0f228b8c45eb0632",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "daverigby/kv_engine",
"max_stars_repo_path": "daemon/memcached.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 642,
"size": 2996
} |
/* Output the current topic and POV assignments in text in text form
to stdout, optionally iteratively maximizing the assignments first
(to find a high-probability assignments). Even if performing
maximization, the current assignments should be post-burn-in for
best results. */
#include <assert.h>
#include <gsl/gsl_rng.h>
#include <inttypes.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include "index.h"
#include "parse_mmaps.h"
#include "probability.h"
#include "sample.h"
int main(int argc, char **argv) {
if (argc != 4) {
printf("Usage: %s mmap_directory maximization_iterations threads\n",
argv[0]);
exit(1);
}
int maximization_iterations = atoi(argv[2]);
int num_threads = atoi(argv[3]);
struct mmap_info mmap_info = open_mmaps_readonly(argv[1]);
int64_t count_revisions;
struct revision_assignment* revision_assignments;
get_revision_assignment_array(&mmap_info, &count_revisions, &revision_assignments);
if (maximization_iterations > 0) {
struct sample_threads sample_threads;
initialize_threads(&sample_threads, num_threads, &mmap_info);
for (int i = 0; i < maximization_iterations; ++i) {
resample_maximize(&sample_threads);
}
destroy_threads(&sample_threads);
}
for (int64_t revision_num = 0; revision_num < count_revisions; ++revision_num) {
if (revision_assignments[revision_num].pov < 0
|| revision_assignments[revision_num].topic < 0) {
continue;
}
printf("%" PRId64 " %d %d\n",
revision_num,
revision_assignments[revision_num].topic,
revision_assignments[revision_num].pov);
}
close_mmaps(mmap_info);
}
| {
"alphanum_fraction": 0.7174041298,
"avg_line_length": 31.3888888889,
"ext": "c",
"hexsha": "3dbb9e17a4a712d6e24a9119daa9168aead08f81",
"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": "c727087d0ac2d440d4e70fbea0c3342c3c734073",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "allenlavoie/topic-pov",
"max_forks_repo_path": "src/readout.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "c727087d0ac2d440d4e70fbea0c3342c3c734073",
"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": "allenlavoie/topic-pov",
"max_issues_repo_path": "src/readout.c",
"max_line_length": 85,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "c727087d0ac2d440d4e70fbea0c3342c3c734073",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "allenlavoie/topic-pov",
"max_stars_repo_path": "src/readout.c",
"max_stars_repo_stars_event_max_datetime": "2015-01-05T17:04:56.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-01-05T17:04:56.000Z",
"num_tokens": 433,
"size": 1695
} |
/*
* 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 init.c
* \brief initialize the program.
*/
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <math.h>
#include <string.h>
#include <float.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
#include <gsl/gsl_interp.h>
#include "brains.h"
/*!
* This function initialize the program.
*/
void init()
{
int i, j;
nq = 1 + parset.flag_trend;
num_params_trend = nq;
num_params_drw = 3; /* include systematic error */
if(parset.flag_dim == 0)
{
num_params_resp = 0; /* no A and Ag for 0D */
}
else
{
num_params_resp = 2; /* response A and Ag */
}
if(parset.flag_trend_diff > 0)
{
num_params_difftrend = parset.flag_trend_diff; /* differences of the trends between continuum and line */
}
else
{
num_params_difftrend = 0;
}
num_params_var = num_params_drw + num_params_trend + num_params_resp + num_params_difftrend;
/* number of parameters for narrow line, only valid for 2d RM. */
num_params_nlr = 0;
if(parset.flag_narrowline >= 2)
num_params_nlr = 3;
/* number of parameters for spectral broadening, only valid for 2d RM */
num_params_res = 1;
if(parset.flag_InstRes > 0)
num_params_res = n_line_data;
/* number of parameters for line center, only valid for 2d RM */
num_params_linecenter = 0;
if(parset.flag_linecenter > 0)
num_params_linecenter = 1;
else if(parset.flag_linecenter < 0)
num_params_linecenter = n_line_data;
switch(parset.flag_blrmodel)
{
case -1: /* user defined analytical transfer function */
BLRmodel_size = num_params_MyTransfun2d * sizeof(double);
set_blr_range_model = set_par_range_mytransfun;
break;
case 0:
BLRmodel_size = num_params_MyBLRmodel2d * sizeof(double);
set_blr_range_model = set_blr_range_mymodel;
break;
case 1:
BLRmodel_size = sizeof(BLRmodel1);
set_blr_range_model = set_blr_range_model1;
break;
case 2:
BLRmodel_size = sizeof(BLRmodel2);
set_blr_range_model = set_blr_range_model2;
break;
case 3:
BLRmodel_size = sizeof(BLRmodel3);
set_blr_range_model = set_blr_range_model3;
break;
case 4:
BLRmodel_size = sizeof(BLRmodel4);
set_blr_range_model = set_blr_range_model4;
break;
case 5:
BLRmodel_size = sizeof(BLRmodel5);
set_blr_range_model = set_blr_range_model5;
break;
case 6:
BLRmodel_size = sizeof(BLRmodel6);
set_blr_range_model = set_blr_range_model6;
break;
case 7:
BLRmodel_size = sizeof(BLRmodel7);
set_blr_range_model = set_blr_range_model7;
break;
case 8:
BLRmodel_size = sizeof(BLRmodel8);
set_blr_range_model = set_blr_range_model8;
break;
case 9:
BLRmodel_size = sizeof(BLRmodel9);
set_blr_range_model = set_blr_range_model9;
break;
default:
BLRmodel_size = sizeof(BLRmodel1);
set_blr_range_model = set_blr_range_model1;
break;
}
#ifdef SA
if(parset.flag_dim > 2 || parset.flag_dim < 0)
{
num_params_sa_extpar = sizeof(SAExtPar)/sizeof(double);
switch(parset.flag_sa_blrmodel)
{
case 0:
SABLRmodel_size = num_params_MyBLRmodel2d * sizeof(double);
set_sa_blr_range_model = set_sa_blr_range_mymodel;
break;
case 1:
SABLRmodel_size = sizeof(SABLRmodel1);
set_sa_blr_range_model = set_sa_blr_range_model1;
break;
case 2:
SABLRmodel_size = sizeof(SABLRmodel2);
set_sa_blr_range_model = set_sa_blr_range_model2;
break;
case 3:
SABLRmodel_size = sizeof(SABLRmodel3);
set_sa_blr_range_model = set_sa_blr_range_model3;
break;
case 4:
SABLRmodel_size = sizeof(SABLRmodel4);
set_sa_blr_range_model = set_sa_blr_range_model4;
break;
case 5:
SABLRmodel_size = sizeof(SABLRmodel5);
set_sa_blr_range_model = set_sa_blr_range_model5;
break;
case 6:
SABLRmodel_size = sizeof(SABLRmodel6);
set_sa_blr_range_model = set_sa_blr_range_model6;
break;
case 7:
SABLRmodel_size = sizeof(SABLRmodel7);
set_sa_blr_range_model = set_sa_blr_range_model7;
break;
case 8:
SABLRmodel_size = sizeof(SABLRmodel8);
set_sa_blr_range_model = set_sa_blr_range_model8;
break;
case 9:
SABLRmodel_size = sizeof(SABLRmodel9);
set_sa_blr_range_model = set_sa_blr_range_model9;
break;
default:
SABLRmodel_size = sizeof(SABLRmodel1);
set_sa_blr_range_model = set_sa_blr_range_model1;
break;
}
}
#endif
if(parset.flag_dim != 3)
{
/* set maximum continuum point */
n_con_max = parset.n_con_recon;
if(parset.flag_dim >=-1)
{
if(n_con_data > n_con_max)
n_con_max = n_con_data;
}
}
allocate_memory();
/* initialize GSL */
gsl_T = gsl_rng_default;
gsl_r = gsl_rng_alloc (gsl_T);
#ifndef Debug
if(parset.flag_rng_seed != 1)
{
gsl_rng_set(gsl_r, time(NULL)+thistask+1350);
}
else
{
gsl_rng_set(gsl_r, parset.rng_seed+thistask+1350);
}
#else
if(parset.flag_rng_seed != 1)
{
gsl_rng_set(gsl_r, 6666+thistask+1350);
printf("# debugging, task %d brains random seed %d.\n", thistask, 6666+thistask+1350);
}
else
{
gsl_rng_set(gsl_r, parset.rng_seed+thistask+1350);
}
#endif
/* default BH mass range */
mass_range[0] = 1.0;
mass_range[1] = 1.0e4;
/* default rcloud_max_set */
rcloud_max_set = 1.0e6;
/* not RM */
if(parset.flag_dim != 3)
{
gsl_acc = gsl_interp_accel_alloc();
gsl_linear = gsl_interp_alloc(gsl_interp_linear, parset.n_con_recon);
if(parset.flag_dim >=-1)
{
/* set Larr_data */
for(i=0;i<n_con_data;i++)
{
Larr_data[i*nq + 0]=1.0;
for(j=1; j<nq; j++)
Larr_data[i*nq + j] = pow(Tcon_data[i], j);
}
}
Tcad_data = 1.0;
Tspan_data = 1.0e4;
if(parset.flag_dim == 0)
{
/* set cadence and time span of data */
Tspan_data = (Tcon_data[n_con_data -1] - Tcon_data[0]);
Tspan_data_con = Tspan_data;
if(Tspan_data < 0.0)
{
if(thistask == roottask)
{
printf("# Incorrect epochs in continuum, please check the input data.\n");
exit(0);
}
}
Tcad_data = Tspan_data;
for(i=1; i< n_con_data; i++)
{
if(Tcad_data > Tcon_data[i] - Tcon_data[i-1])
Tcad_data = Tcon_data[i] - Tcon_data[i-1];
}
}
if(parset.flag_dim > 0 || parset.flag_dim == -1)
{
/* set cadence and time span of data */
Tspan_data_con = (Tcon_data[n_con_data -1] - Tcon_data[0]);
Tspan_data = (Tline_data[n_line_data -1] - Tcon_data[0]);
if(Tspan_data < 0.0)
{
if(thistask == roottask)
{
printf("# Incorrect epochs in continuum and line, please check the input data.\n");
exit(0);
}
}
Tcad_data = Tspan_data;
for(i=1; i< n_con_data; i++)
{
if(Tcad_data > Tcon_data[i] - Tcon_data[i-1])
Tcad_data = Tcon_data[i] - Tcon_data[i-1];
}
for(i=1; i< n_line_data; i++)
{
if(Tcad_data > Tline_data[i] - Tline_data[i-1])
Tcad_data = Tline_data[i] - Tline_data[i-1];
}
/* set mediate time of continuum data */
Tmed_data = 0.5*(Tcon_data[0] + Tcon_data[n_con_data-1]);
for(i=0; i<num_params_difftrend; i++)
{
pow_Tcon_data[i] = (pow(Tcon_data[n_con_data-1]-Tmed_data, i+2)
- pow(Tcon_data[0]-Tmed_data, i+2)) / (i+2) / Tspan_data_con;
}
/* set time back for continuum reconstruction */
time_back_set = Tspan_data_con + (Tcon_data[0] - Tline_data[0]);
time_back_set = fmax(2.0*Tcad_data, time_back_set);
/* make rcloud_max and time_back consistent with each other, rcloud_max has a higher priority */
double DT=Tcon_data[0] - time_back_set;
if(parset.rcloud_max > 0.0)
{
DT = fmax(DT, Tline_data[0] - parset.rcloud_max*2.0);
}
else if(parset.time_back > 0.0) /* neglect when parset.rcloud_max is set */
{
DT = fmax(DT, Tcon_data[0] - parset.time_back);
}
time_back_set = Tcon_data[0] - DT;
/* set the range of cloud radial distribution */
rcloud_min_set = 0.0;
rcloud_max_set = Tspan_data/2.0;
/* rcloud_max should smaller than (Tl0 - Tc0)/2 */
rcloud_max_set = fmin( rcloud_max_set, (Tline_data[0] - Tcon_data[0] + time_back_set)/2.0 );
if(parset.rcloud_max > 0.0)
rcloud_max_set = fmin(rcloud_max_set, parset.rcloud_max);
/* check whether n_con_recon is appropriate */
double med_cad, med_cad_recon;
//med_cad = get_mediate_cad(Tcon_data, n_con_data);
med_cad = (Tcon_data[n_con_data-1] - Tcon_data[0])/(n_con_data -1);
med_cad_recon = (Tcon_data[n_con_data-1] - Tcon_data[0] + time_back_set)/(parset.n_con_recon-1);
if(med_cad_recon > 1.05*med_cad)
{
if(thistask == roottask)
{
printf("# Too small NConRecon.\n"
"# Better to change it to %d or set RCloudMax/TimeBack to smaller than %f/%f.\n",
(int)(parset.n_con_recon * med_cad_recon/med_cad),
(Tline_data[0] - Tcon_data[0] + time_back_set)/2.0 ,time_back_set);
printf("\e[1;35m" "# Use '-f' option in command line if want to ignore this check.\n" "\e[0m");
}
if(parset.flag_force_run != 1)
{
exit(0);
}
}
}
if(thistask == roottask && parset.flag_dim >=-1)
{
printf("rcloud_min_max_set: %f %f\n", rcloud_min_set, rcloud_max_set);
}
// response range A and Ag
resp_range[0][0] = log(0.1);
resp_range[0][1] = log(10.0);
resp_range[1][0] = -1.0;
resp_range[1][1] = 3.0;
/* set the range of continuum variation */
var_range_model[0][0] = log(1.0); /* systematic error in continuum */
var_range_model[0][1] = log(1.0+10.0);
var_range_model[1][0] = -15.0; /* log(sigma) */
var_range_model[1][1] = -1.0;
var_range_model[2][0] = log(Tcad_data); /* log(tau) */
var_range_model[2][1] = log(Tspan_data);
var_range_model[3][0] = -10.0; /* mean value or trend parameter values */
var_range_model[3][1] = 10.0;
for(i=0; i<num_params_difftrend; i++)
{
var_range_model[4+i][0] = -1.0/pow(Tspan_data, i+1); /* slope of the trend in the differences between contiuum and line */
var_range_model[4+i][1] = 1.0/pow(Tspan_data, i+1);
}
var_range_model[4+num_params_difftrend][0] = -10.0; /* light curve values */
var_range_model[4+num_params_difftrend][1] = 10.0;
if(num_params_nlr > 1)
{
if(parset.flag_narrowline == 2) /* Gaussian prior */
{
nlr_range_model[0][0] = -10.0;
nlr_range_model[0][1] = 10.0;
nlr_prior_model[0] = GAUSSIAN;
}
else
{
nlr_range_model[0][0] = log(1.0e-1); /* logrithmic prior */
nlr_range_model[0][1] = log(1.0e4);
nlr_prior_model[0] = UNIFORM;
}
nlr_range_model[1][0] = -10.0;
nlr_range_model[1][1] = 10.0;
nlr_prior_model[1] = GAUSSIAN;
nlr_range_model[2][0] = -10.0;
nlr_range_model[2][1] = 10.0;
nlr_prior_model[2] = GAUSSIAN;
}
// range for systematic error
sys_err_line_range[0] = log(1.0);
sys_err_line_range[1] = log(1.0+10.0);
set_blr_range_model();
}
#ifdef SA
/* SA */
if(parset.flag_dim > 2)
{
set_sa_blr_range_model();
sa_extpar_range[0][0] = log(100.0); /* DA */
sa_extpar_range[0][1] = log(1000.0);
sa_extpar_range[1][0] = 0.0; /* PA */
sa_extpar_range[1][1] = 180.0;
sa_extpar_range[2][0] = log(0.5); /* FA */
sa_extpar_range[2][1] = log(2.0);
sa_extpar_range[3][0] = -(wave_sa_data[1]-wave_sa_data[0]); /* CO */
sa_extpar_range[3][1] = (wave_sa_data[1]-wave_sa_data[0]);
}
#endif
}
/*!
* This function allocates memory for variables used throughout the code.
*/
void allocate_memory()
{
int i;
if(parset.flag_dim != 3)
{
Tcon = malloc(parset.n_con_recon * sizeof(double));
Fcerrs = malloc(parset.n_con_recon * sizeof(double));
PSmat = malloc(parset.n_con_recon * parset.n_con_recon * sizeof(double));
//PNmat = malloc(parset.n_con_recon * parset.n_con_recon * sizeof(double));
USmat = malloc(parset.n_con_recon * n_con_data * sizeof(double));
PSmat_data = malloc(n_con_data * n_con_data * sizeof(double));
//PNmat_data = malloc(n_con_data * n_con_data * sizeof(double));
PCmat_data = malloc(n_con_data * n_con_data * sizeof(double));
IPCmat_data = malloc(n_con_data * n_con_data * sizeof(double));
PQmat = malloc(parset.n_con_recon * parset.n_con_recon * sizeof(double));
PEmat1 = malloc(parset.n_con_recon * n_con_data * sizeof(double));
PEmat2 = malloc(parset.n_con_recon * parset.n_con_recon * sizeof(double));
blr_range_model = malloc(BLRmodel_size/sizeof(double) * sizeof(double *));
for(i=0; i<BLRmodel_size/sizeof(double); i++)
{
blr_range_model[i] = malloc(2*sizeof(double));
}
workspace = malloc((n_con_data*nq + 7*n_con_max + nq*nq + nq)*sizeof(double));
workspace_uv = malloc(2*parset.n_con_recon*sizeof(double));
Larr_data = malloc(n_con_data*nq*sizeof(double));
Larr_rec = malloc(parset.n_con_recon*nq*sizeof(double));
pow_Tcon_data = malloc(num_params_difftrend*sizeof(double));
var_param = malloc(num_params_var * sizeof(double));
var_param_std = malloc(num_params_var * sizeof(double));
for(i=0; i<num_params_var; i++)
{
var_param[i] = var_param_std[i] = 0.0;
}
}
#ifdef SA
if(parset.flag_dim > 2 || parset.flag_dim < 0)
{
sa_extpar_range = malloc(num_params_sa_extpar * sizeof(double *));
for(i=0; i<num_params_sa_extpar; i++)
{
sa_extpar_range[i]=malloc(2*sizeof(double));
}
sa_blr_range_model = malloc(SABLRmodel_size/sizeof(double) * sizeof(double *));
for(i=0; i<SABLRmodel_size/sizeof(double); i++)
{
sa_blr_range_model[i] = malloc(2*sizeof(double));
}
if(parset.flag_sa_par_mutual != 0)
{
idx_sa_par_mutual = malloc(2*sizeof(int));
idx_rm_par_mutual = malloc(2*sizeof(int));
}
}
#endif
return;
}
/*!
* This function free memory.
*/
void free_memory()
{
int i;
if(parset.flag_dim != 3)
{
free(Tcon);
free(Fcerrs);
free(PSmat);
//(PNmat);
free(USmat);
free(PSmat_data);
//free(PNmat_data);
free(PCmat_data);
free(IPCmat_data);
free(PQmat);
free(PEmat1);
free(PEmat2);
for(i=0; i<BLRmodel_size/sizeof(double); i++)
{
free(blr_range_model[i]);
}
free(blr_range_model);
free(workspace);
free(workspace_uv);
free(Larr_data);
free(Larr_rec);
free(pow_Tcon_data);
free(var_param);
free(var_param_std);
}
#ifdef SA
if(parset.flag_dim > 2 || parset.flag_dim < 0)
{
for(i=0; i<num_params_sa_extpar; i++)
{
free(sa_extpar_range[i]);
}
free(sa_extpar_range);
for(i=0; i<SABLRmodel_size/sizeof(double); i++)
{
free(sa_blr_range_model[i]);
}
free(sa_blr_range_model);
if(parset.flag_sa_par_mutual != 0)
{
free(idx_sa_par_mutual);
free(idx_rm_par_mutual);
}
}
#endif
return;
}
/*!
* This function normalise the light curves to a scale of unity.
*/
void scale_con_line()
{
int i, j;
double ave_con, ave_line;
con_scale = 1.0;
line_scale = 1.0;
ave_con = 0.0;
ave_line = 0.0;
for(i=0; i<n_con_data; i++)
{
ave_con += Fcon_data[i];
}
ave_con /= n_con_data;
con_scale = 1.0/ave_con;
for(i=0; i<n_con_data; i++)
{
Fcon_data[i] *=con_scale;
Fcerrs_data[i] *=con_scale;
}
if(thistask == roottask)
printf("con scale: %e\t%e\n", con_scale, ave_con);
con_error_mean *= con_scale;
if(parset.flag_dim == 0)
{
return;
}
for(i=0; i<n_line_data; i++)
{
ave_line += Fline_data[i];
}
ave_line /=n_line_data;
line_scale = 1.0/ave_line;
if(thistask == roottask)
printf("line scale: %e\t%e\n", line_scale, ave_line);
for(i=0; i<n_line_data; i++)
{
// note mask with error < 0.0
if(Flerrs_data[i] > 0.0)
{
Fline_data[i] *= line_scale;
Flerrs_data[i] *= line_scale;
}
if(parset.flag_dim==2 || parset.flag_dim == -1 || parset.flag_dim == 5)
for(j=0; j<n_vel_data; j++)
{
// note mask with error < 0.0
if(Flerrs2d_data[i*n_vel_data + j] > 0.0)
{
Fline2d_data[i*n_vel_data + j] *= line_scale;
Flerrs2d_data[i*n_vel_data + j] *= line_scale;
}
}
}
line_error_mean *= line_scale;
if( (parset.flag_dim==2 || parset.flag_dim == -1 || parset.flag_dim == 5) && parset.flag_narrowline!=0)
{
parset.flux_narrowline *= line_scale;
parset.flux_narrowline_err *= line_scale;
}
return;
}
/*!
* This function copes with parameter fixing.\n
* Only fix BLR model parameters.
*/
void set_par_fix_blrmodel()
{
int i;
char *pstr;
npar_fix = 0;
if(thistask == roottask)
{
pstr = parset.str_par_fix_val;
// set the default value if not provided.
for(i=strlen(parset.str_par_fix); i<num_params_blr_model; i++)
parset.str_par_fix[i] = '0';
for(i=0; i<num_params_blr_model; i++)
{
if(parset.str_par_fix[i] == '0')
{
par_fix[i] = 0;
par_fix_val[i] = -DBL_MAX; /* set to be the smallest value */
}
else if(parset.str_par_fix[i] == '1')
{
if(pstr == NULL)
{
printf("# %d-th BLR parameter value is not provided (counting from 0).\n", i);
exit(0);
}
par_fix[i] = 1;
sscanf(pstr, "%lf", &par_fix_val[i]);
npar_fix++;
printf("# %d-th BLR parameter fixed, value= %f.\n", i, par_fix_val[i]);
pstr = strchr(pstr, ':'); /* values are separated by ":" */
if(pstr!=NULL)
{
pstr++;
}
}
else // default value
{
par_fix[i] = 0;
par_fix_val[i] = -DBL_MAX;
}
}
}
MPI_Bcast(par_fix, num_params_blr_model, MPI_INT, roottask, MPI_COMM_WORLD);
MPI_Bcast(par_fix_val, num_params_blr_model, MPI_DOUBLE, roottask, MPI_COMM_WORLD);
return;
}
/*
* setup BLR model parameter range.
*/
// model 1
void set_blr_range_model1()
{
int i;
i = 0;
//mu
blr_range_model[i][0] = log(0.1);
blr_range_model[i++][1] = log(rcloud_max_set*0.5);
//beta
blr_range_model[i][0] = 0.001;
blr_range_model[i++][1] = 2.0;
//F
blr_range_model[i][0] = 0.001;
blr_range_model[i++][1] = 0.999;
//inc
blr_range_model[i][0] = 0.0; // in cosine
blr_range_model[i++][1] = 1.0;
//opn
blr_range_model[i][0] = 0.0; // in rad
blr_range_model[i++][1] = 90.0;
//k
blr_range_model[i][0] = -0.5;
blr_range_model[i++][1] = 0.5;
//mbh
blr_range_model[i][0] = log(mass_range[0]);
blr_range_model[i++][1] = log(mass_range[1]);
//lambda
blr_range_model[i][0] = 0.0;
blr_range_model[i++][1] = 1.5;
//q
blr_range_model[i][0] = 0.0;
blr_range_model[i++][1] = 1.0;
//blr_range_model[2][1] = fmin(blr_range_model[2][1], log(rcloud_max_set));
return;
}
// model 2
void set_blr_range_model2()
{
int i;
i = 0;
//mu
blr_range_model[i][0] = log(0.1);
blr_range_model[i++][1] = log(rcloud_max_set*0.5);
//beta
blr_range_model[i][0] = 0.001;
blr_range_model[i++][1] = 2.0;
//F
blr_range_model[i][0] = 0.001;
blr_range_model[i++][1] = 0.999;
//inc
blr_range_model[i][0] = 0.0; // in cosine
blr_range_model[i++][1] = 1.0;
//opn
blr_range_model[i][0] = 0.0; // in rad
blr_range_model[i++][1] = 90.0;
//k
blr_range_model[i][0] = -0.5;
blr_range_model[i++][1] = 0.5;
//mbh
blr_range_model[i][0] = log(mass_range[0]);
blr_range_model[i++][1] = log(mass_range[1]);
//sigr
blr_range_model[i][0] = 0.0;
blr_range_model[i++][1] = 1.0;
//sigtheta
blr_range_model[i][0] = 0.0;
blr_range_model[i++][1] = 1.0;
return;
}
// model 3
void set_blr_range_model3()
{
int i;
i = 0;
//Rin
blr_range_model[i][0] = log(0.1);
blr_range_model[i++][1] = log(rcloud_max_set*0.5);
//F
blr_range_model[i][0] = log(1.0);
blr_range_model[i++][1] = log(1.0e2);
//alpha
blr_range_model[i][0] = -3.0;
blr_range_model[i++][1] = 3.0;
//inc
blr_range_model[i][0] = 0.0; // in cosine
blr_range_model[i++][1] = 1.0;
//opn
blr_range_model[i][0] = 0.0; // in rad
blr_range_model[i++][1] = 90.0;
//k
blr_range_model[i][0] = -0.5;
blr_range_model[i++][1] = 0.5;
//mbh
blr_range_model[i][0] = log(mass_range[0]);
blr_range_model[i++][1] = log(mass_range[1]);
//xi
blr_range_model[i][0] = 0.0;
blr_range_model[i++][1] = 1.0;
//q
blr_range_model[i][0] = 0.0;
blr_range_model[i++][1] = 1.0;
//rcloud_max_set = fmax(rcloud_max_set, exp(blr_range_model[3][1] + blr_range_model[4][1]));
return;
}
// model 4
void set_blr_range_model4()
{
int i;
i = 0;
//Rin
blr_range_model[i][0] = log(0.1);
blr_range_model[i++][1] = log(rcloud_max_set*0.5);
//F
blr_range_model[i][0] = log(1.0);
blr_range_model[i++][1] = log(1.0e2);
//alpha
blr_range_model[i][0] = -3.0;
blr_range_model[i++][1] = 3.0;
//inc
blr_range_model[i][0] = 0.0; // in cosine
blr_range_model[i++][1] = 1.0;
//opn
blr_range_model[i][0] = 0.0; // in rad
blr_range_model[i++][1] = 90.0;
//k
blr_range_model[i][0] = -0.5;
blr_range_model[i++][1] = 0.5;
//mbh
blr_range_model[i][0] = log(mass_range[0]);
blr_range_model[i++][1] = log(mass_range[1]);
//xi
blr_range_model[i][0] = 0.0;
blr_range_model[i++][1] = sqrt(2.0)/2.0;
//q
blr_range_model[i][0] = 0.0;
blr_range_model[i++][1] = 1.0;
//rcloud_max_set = fmax(rcloud_max_set, exp(blr_range_model[3][1] + blr_range_model[4][1]));
return;
}
// model 5
void set_blr_range_model5()
{
int i;
i = 0;
//mu
blr_range_model[i][0] = log(0.1);
blr_range_model[i++][1] = log(rcloud_max_set*0.5);
//Fin
blr_range_model[i][0] = 0.0;
blr_range_model[i++][1] = 1.0;
//Fout
blr_range_model[i][0] = log(1.0);
blr_range_model[i++][1] = log(10.0);
//alpha
blr_range_model[i][0] = 1.0;
blr_range_model[i++][1] = 3.0;
//inc
blr_range_model[i][0] = 0.0; // in cosine
blr_range_model[i++][1] = 1.0;
//opn
blr_range_model[i][0] = 0.0; // in degree
blr_range_model[i++][1] = 90.0;
//k
blr_range_model[i][0] = -0.5;
blr_range_model[i++][1] = 0.5;
//beta
blr_range_model[i][0] = 1.0;
blr_range_model[i++][1] = 5.0;
//xi
blr_range_model[i][0] = 0.0;
blr_range_model[i++][1] = 1.0;
//mbh
blr_range_model[i][0] = log(mass_range[0]);
blr_range_model[i++][1] = log(mass_range[1]);
//fellip
blr_range_model[i][0] = 0.0;
blr_range_model[i++][1] = 1.0;
//fflow
blr_range_model[i][0] = 0.0;
blr_range_model[i++][1] = 1.0;
//sigr_circ
blr_range_model[i][0] = log(0.001);
blr_range_model[i++][1] = log(0.1);
//sigthe_circ
blr_range_model[i][0] = log(0.001);
blr_range_model[i++][1] = log(1.0);
//sigr_rad
blr_range_model[i][0] = log(0.001);
blr_range_model[i++][1] = log(0.1);
//sigthe_rad
blr_range_model[i][0] = log(0.001);
blr_range_model[i++][1] = log(1.0);
//theta_rot
blr_range_model[i][0] = 0.0;
blr_range_model[i++][1] = 90.0;
//sig_turb
blr_range_model[i][0] = log(0.001);
blr_range_model[i++][1] = log(0.1);
//rcloud_max_set = fmax(rcloud_max_set, exp(blr_range_model[2][1] + blr_range_model[4][1]));
return;
}
// model 6
void set_blr_range_model6()
{
int i;
i = 0;
//mu
blr_range_model[i][0] = log(0.1);
blr_range_model[i++][1] = log(rcloud_max_set*0.5);
//beta
blr_range_model[i][0] = 0.001;
blr_range_model[i++][1] = 2.0;
//F
blr_range_model[i][0] = 0.0;
blr_range_model[i++][1] = 1.0;
//inc
blr_range_model[i][0] = 0.0; //in cosine
blr_range_model[i++][1] = 1.0;
//opn
blr_range_model[i][0] = 0.0; // in rad
blr_range_model[i++][1] = 90.0;
//k
blr_range_model[i][0] = -0.5;
blr_range_model[i++][1] = 0.5;
//gamma
blr_range_model[i][0] = 1.0;
blr_range_model[i++][1] = 5.0;
//xi
blr_range_model[i][0] = 0.0;
blr_range_model[i++][1] = 1.0;
//mbh
blr_range_model[i][0] = log(mass_range[0]);
blr_range_model[i++][1] = log(mass_range[1]);
//fellip
blr_range_model[i][0] = 0.0;
blr_range_model[i++][1] = 1.0;
//fflow
blr_range_model[i][0] = 0.0;
blr_range_model[i++][1] = 1.0;
//sigr_circ
blr_range_model[i][0] = log(0.001);
blr_range_model[i++][1] = log(0.1);
//sigthe_circ
blr_range_model[i][0] = log(0.001);
blr_range_model[i++][1] = log(1.0);
//sigr_rad
blr_range_model[i][0] = log(0.001);
blr_range_model[i++][1] = log(0.1);
//sigthe_rad
blr_range_model[i][0] = log(0.001);
blr_range_model[i++][1] = log(1.0);
//theta_rot
blr_range_model[i][0] = 0.0;
blr_range_model[i++][1] = 90.0;
//sig_turb
blr_range_model[i][0] = log(0.0001);
blr_range_model[i++][1] = log(0.1);
//rcloud_max_set = 44.85;
//blr_range_model[2][1] = fmin(blr_range_model[2][1], log(rcloud_max_set));
return;
}
// model 7
void set_blr_range_model7()
{
int i;
i = 0;
//mu
blr_range_model[i][0] = log(0.1);
blr_range_model[i++][1] = log(rcloud_max_set*0.5);
//beta
blr_range_model[i][0] = 0.001;
blr_range_model[i++][1] = 2.0;
//F
blr_range_model[i][0] = 0.0;
blr_range_model[i++][1] = 1.0;
//inc
blr_range_model[i][0] = 0.0; // in cosine
blr_range_model[i++][1] = 1.0;
//opn
blr_range_model[i][0] = 0.0; // in rad
blr_range_model[i++][1] = 90.0;
//k
blr_range_model[i][0] = -0.5;
blr_range_model[i++][1] = 0.5;
//gamma
blr_range_model[i][0] = 1.0;
blr_range_model[i++][1] = 5.0;
//xi
blr_range_model[i][0] = 0.0;
blr_range_model[i++][1] = 1.0;
//fsh
blr_range_model[i][0] = 0.0;
blr_range_model[i++][1] = 1.0;
//mu_un
blr_range_model[i][0] = log(0.1);
blr_range_model[i++][1] = log(rcloud_max_set*0.5);
//beta_un
blr_range_model[i][0] = 0.001;
blr_range_model[i++][1] = 2.0;
//F_un
blr_range_model[i][0] = 0.0;
blr_range_model[i++][1] = 1.0;
//opn_un
blr_range_model[i][0] = 0.0;
blr_range_model[i++][1] = 90.0;
//mbh
blr_range_model[i][0] = log(mass_range[0]);
blr_range_model[i++][1] = log(mass_range[1]);
//fellip
blr_range_model[i][0] = 0.0;
blr_range_model[i++][1] = 1.0;
//fflow
blr_range_model[i][0] = 0.0;
blr_range_model[i++][1] = 1.0;
//sigr_circ
blr_range_model[i][0] = log(0.001);
blr_range_model[i++][1] = log(0.1);
//sigthe_circ
blr_range_model[i][0] = log(0.001);
blr_range_model[i++][1] = log(1.0);
//sigr_rad
blr_range_model[i][0] = log(0.001);
blr_range_model[i++][1] = log(0.1);
//sigthe_rad
blr_range_model[i][0] = log(0.001);
blr_range_model[i++][1] = log(1.0);
//theta_rot
blr_range_model[i][0] = 0.0;
blr_range_model[i++][1] = 90.0;
//fellip_un
blr_range_model[i][0] = 0.0;
blr_range_model[i++][1] = 1.0;
//fflow_un
blr_range_model[i][0] = 0.0;
blr_range_model[i++][1] = 1.0;
//sig_turb
blr_range_model[i][0] = log(0.001);
blr_range_model[i++][1] = log(0.1);
return;
}
// model 8
void set_blr_range_model8()
{
int i;
i = 0;
//theta_min
blr_range_model[i][0] = 20.0; // in degree
blr_range_model[i++][1] = 90.0;
//dtheta_max
blr_range_model[i][0] = 0.0; // in degree
blr_range_model[i++][1] = 90.0;
//r_min
blr_range_model[i][0] = log(0.1);
blr_range_model[i++][1] = log(rcloud_max_set*0.25);
//fr_max
blr_range_model[i][0] = 1.0; //
blr_range_model[i++][1] = 10.0;
//gamma
blr_range_model[i][0] = 0.0; //
blr_range_model[i++][1] = 3.0;
//alpha
blr_range_model[i][0] = 0.0;
blr_range_model[i++][1] = 3.0;
//lambda
blr_range_model[i][0] = -3.0;
blr_range_model[i++][1] = 0.0;
//k
blr_range_model[i][0] = -0.5;
blr_range_model[i++][1] = 0.5;
//xi
blr_range_model[i][0] = 0.0;
blr_range_model[i++][1] = 1.0;
//Rv
blr_range_model[i][0] = log(10.0);
blr_range_model[i++][1] = log(50.0);
//Rblr
blr_range_model[i][0] = log(10.0);
blr_range_model[i++][1] = log(rcloud_max_set*0.5);
//inc
blr_range_model[i][0] = 0.0; // cos(inc)
blr_range_model[i++][1] = 1.0;
//mbh
blr_range_model[i][0] = log(mass_range[0]);
blr_range_model[i++][1] = log(mass_range[1]);
return;
}
// model 9
void set_blr_range_model9()
{
int i;
i = 0;
//mu
blr_range_model[i][0] = log(0.1);
blr_range_model[i++][1] = log(rcloud_max_set*0.5);
//beta
blr_range_model[i][0] = 0.001;
blr_range_model[i++][1] = 2.0;
//F
blr_range_model[i][0] = 0.001;
blr_range_model[i++][1] = 0.999;
//inc
blr_range_model[i][0] = 0.0; // in cosine
blr_range_model[i++][1] = 1.0;
//opn
blr_range_model[i][0] = 0.0; // in rad
blr_range_model[i++][1] = 90.0;
//mbh
blr_range_model[i][0] = log(mass_range[0]);
blr_range_model[i++][1] = log(mass_range[1]);
return;
}
/*
* set 1D BLR model and functions.
*/
void set_blr_model1d()
{
switch(parset.flag_blrmodel)
{
case -1:
num_params_blr_model = num_params_MyTransfun1d;
transfun_1d_cal = transfun_1d_cal_mytransfun;
break;
case 0:
num_params_blr_model = num_params_MyBLRmodel1d;
gen_cloud_sample = gen_cloud_sample_mymodel;
transfun_1d_cal = transfun_1d_cal_cloud;
break;
case 1:
num_params_blr_model = 6;
gen_cloud_sample = gen_cloud_sample_model1;
transfun_1d_cal = transfun_1d_cal_cloud;
break;
case 2:
num_params_blr_model = 6;
gen_cloud_sample = gen_cloud_sample_model1;
transfun_1d_cal = transfun_1d_cal_cloud;
break;
case 3:
num_params_blr_model = 6;
gen_cloud_sample = gen_cloud_sample_model3;
transfun_1d_cal = transfun_1d_cal_cloud;
break;
case 4:
num_params_blr_model = 6;
gen_cloud_sample = gen_cloud_sample_model3;
transfun_1d_cal = transfun_1d_cal_cloud;
break;
case 5:
num_params_blr_model = 9;
gen_cloud_sample = gen_cloud_sample_model5;
transfun_1d_cal = transfun_1d_cal_cloud;
break;
case 6:
num_params_blr_model = 8;
gen_cloud_sample = gen_cloud_sample_model6;
transfun_1d_cal = transfun_1d_cal_cloud;
break;
case 7:
num_params_blr_model = 13;
gen_cloud_sample = gen_cloud_sample_model7;
transfun_1d_cal = transfun_1d_cal_cloud;
break;
case 8:
num_params_blr_model = 13;
gen_cloud_sample = gen_cloud_sample_model8;
transfun_1d_cal = transfun_1d_cal_cloud;
break;
case 9:
num_params_blr_model = 5;
gen_cloud_sample = gen_cloud_sample_model9;
transfun_1d_cal = transfun_1d_cal_cloud;
break;
default:
num_params_blr_model = 6;
gen_cloud_sample = gen_cloud_sample_model1;
transfun_1d_cal = transfun_1d_cal_cloud;
break;
}
return;
}
/*
* set 2D BLR model and functions.
*/
void set_blr_model2d()
{
switch(parset.flag_blrmodel)
{
case -1:
num_params_blr_model = num_params_MyTransfun2d;
transfun_2d_cal = transfun_2d_cal_mytransfun;
break;
case 0:
num_params_blr_model = num_params_MyBLRmodel2d;
gen_cloud_sample = gen_cloud_sample_mymodel;
transfun_2d_cal = transfun_2d_cal_cloud;
break;
case 1:
num_params_blr_model = sizeof(BLRmodel1)/sizeof(double);
gen_cloud_sample = gen_cloud_sample_model1;
transfun_2d_cal = transfun_2d_cal_cloud;
break;
case 2:
num_params_blr_model = sizeof(BLRmodel2)/sizeof(double);
gen_cloud_sample = gen_cloud_sample_model2;
transfun_2d_cal = transfun_2d_cal_cloud;
break;
case 3:
num_params_blr_model = sizeof(BLRmodel3)/sizeof(double);
gen_cloud_sample = gen_cloud_sample_model3;
transfun_2d_cal = transfun_2d_cal_cloud;
break;
case 4:
num_params_blr_model = sizeof(BLRmodel4)/sizeof(double);
gen_cloud_sample = gen_cloud_sample_model4;
transfun_2d_cal = transfun_2d_cal_cloud;
break;
case 5:
num_params_blr_model = sizeof(BLRmodel5)/sizeof(double);
gen_cloud_sample = gen_cloud_sample_model5;
transfun_2d_cal = transfun_2d_cal_cloud;
break;
case 6:
num_params_blr_model = sizeof(BLRmodel6)/sizeof(double);
gen_cloud_sample = gen_cloud_sample_model6;
transfun_2d_cal = transfun_2d_cal_cloud;
break;
case 7:
num_params_blr_model = sizeof(BLRmodel7)/sizeof(double);
gen_cloud_sample = gen_cloud_sample_model7;
transfun_2d_cal = transfun_2d_cal_cloud;
break;
case 8:
num_params_blr_model = sizeof(BLRmodel8)/sizeof(double);
gen_cloud_sample = gen_cloud_sample_model8;
transfun_2d_cal = transfun_2d_cal_cloud;
break;
case 9:
num_params_blr_model = sizeof(BLRmodel9)/sizeof(double);
gen_cloud_sample = gen_cloud_sample_model9;
transfun_2d_cal = transfun_2d_cal_cloud;
break;
default:
num_params_blr_model = sizeof(BLRmodel1)/sizeof(double);
gen_cloud_sample = gen_cloud_sample_model1;
transfun_2d_cal = transfun_2d_cal_cloud;
break;
}
return;
} | {
"alphanum_fraction": 0.6151792864,
"avg_line_length": 25.6598173516,
"ext": "c",
"hexsha": "03f1650637216a22978725ec594d2f61ec794fdf",
"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/init.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/init.c",
"max_line_length": 128,
"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/init.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 11902,
"size": 33717
} |
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <math.h>
#include <string.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_odeiv.h>
#include <gsl/gsl_spline.h>
#include <gsl/gsl_interp2d.h>
#include <gsl/gsl_spline2d.h>
#include <gsl/gsl_integration.h>
#include "ccl.h"
//
// Macros for replacing relative paths
#define EXPAND_STR(s) STRING(s)
#define STRING(s) #s
const ccl_configuration default_config = {
ccl_boltzmann_class, ccl_halofit, ccl_nobaryons,
ccl_tinker10, ccl_duffy2008, ccl_emu_strict};
//Precision parameters
/**
* Default relative precision if not otherwise specified
*/
#define GSL_EPSREL 1E-4
/**
* Default number of iterations for integration and root-finding if not otherwise
* specified
*/
#define GSL_N_ITERATION 1000
/**
* Default number of Gauss-Kronrod points in QAG integration if not otherwise
* specified
*/
#define GSL_INTEGRATION_GAUSS_KRONROD_POINTS GSL_INTEG_GAUSS41
/**
* Relative precision in sigma_R calculations
*/
#define GSL_EPSREL_SIGMAR 1E-5
/**
* Relative precision in k_NL calculations
*/
#define GSL_EPSREL_KNL 1E-5
/**
* Relative precision in distance calculations
*/
#define GSL_EPSREL_DIST 1E-6
/**
* Relative precision in growth calculations
*/
#define GSL_EPSREL_GROWTH 1E-6
/**
* Relative precision in dNdz calculations
*/
#define GSL_EPSREL_DNDZ 1E-6
const ccl_gsl_params default_gsl_params = {
GSL_N_ITERATION, // N_ITERATION
GSL_INTEGRATION_GAUSS_KRONROD_POINTS,// INTEGRATION_GAUSS_KRONROD_POINTS
GSL_EPSREL, // INTEGRATION_EPSREL
GSL_INTEGRATION_GAUSS_KRONROD_POINTS,// INTEGRATION_LIMBER_GAUSS_KRONROD_POINTS
GSL_EPSREL, // INTEGRATION_LIMBER_EPSREL
GSL_EPSREL_DIST, // INTEGRATION_DISTANCE_EPSREL
GSL_EPSREL_SIGMAR, // INTEGRATION_SIGMAR_EPSREL
GSL_EPSREL_KNL, // INTEGRATION_KNL_EPSREL
GSL_EPSREL, // ROOT_EPSREL
GSL_N_ITERATION, // ROOT_N_ITERATION
GSL_EPSREL_GROWTH, // ODE_GROWTH_EPSREL
1E-6, // EPS_SCALEFAC_GROWTH
1E7, // HM_MMIN
1E17, // HM_MMAX
0.0, // HM_EPSABS
1E-4, // HM_EPSREL
1000, // HM_LIMIT
GSL_INTEG_GAUSS41 // HM_INT_METHOD
};
#undef GSL_EPSREL
#undef GSL_N_ITERATION
#undef GSL_INTEGRATION_GAUSS_KRONROD_POINTS
#undef GSL_EPSREL_SIGMAR
#undef GSL_EPSREL_KNL
#undef GSL_EPSREL_DIST
#undef GSL_EPSREL_GROWTH
#undef GSL_EPSREL_DNDZ
const ccl_spline_params default_spline_params = {
// scale factor spline params
250, // A_SPLINE_NA
0.1, // A_SPLINE_MIN
0.01, // A_SPLINE_MINLOG_PK
0.1, // A_SPLINE_MIN_PK,
0.01, // A_SPLINE_MINLOG_SM,
0.1, // A_SPLINE_MIN_SM,
1.0, // A_SPLINE_MAX,
0.0001, // A_SPLINE_MINLOG,
250, // A_SPLINE_NLOG,
// mass splines
0.025, // LOGM_SPLINE_DELTA
50, // LOGM_SPLINE_NM
6, // LOGM_SPLINE_MIN
17, // LOGM_SPLINE_MAX
// PS a and k spline
13, // A_SPLINE_NA_SM
6, // A_SPLINE_NLOG_SM
40, // A_SPLINE_NA_PK
11, // A_SPLINE_NLOG_PK
// k-splines and integrals
50, // K_MAX_SPLINE
1E3, // K_MAX
5E-5, // K_MIN
0.025, // DLOGK_INTEGRATION
167, // N_K
100000, // N_K_3DCOR
// correlation function parameters
0.01, // ELL_MIN_CORR
60000, // ELL_MAX_CORR
5000, // N_ELL_CORR
//Spline types
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL
};
ccl_physical_constants ccl_constants = {
/**
* Lightspeed / H0 in units of Mpc/h (from CODATA 2014)
*/
2997.92458,
/**
* Newton's gravitational constant in units of m^3/Kg/s^2
*/
//6.6738e-11, /(from PDG 2013) in m^3/Kg/s^2
//6.67428e-11, // CLASS VALUE
6.67408e-11, // from CODATA 2014
/**
* Solar mass in units of kg (from GSL)
*/
//GSL_CONST_MKSA_SOLAR_MASS,
//1.9885e30, //(from PDG 2015) in Kg
1.9884754153381438E+30, //from IAU 2015
/**
* Mpc to meters (from PDG 2016 and using M_PI)
*/
3.085677581491367399198952281E+22,
/**
* pc to meters (from PDG 2016 and using M_PI)
*/
3.085677581491367399198952281E+16,
/**
* Rho critical in units of M_sun/h / (Mpc/h)^3
*/
((3*100*100)/(8*M_PI*6.67408e-11)) * (1000*1000*3.085677581491367399198952281E+22/1.9884754153381438E+30),
/**
* Boltzmann constant in units of J/K
*/
//GSL_CONST_MKSA_BOLTZMANN,
1.38064852E-23, //from CODATA 2014
/**
* Stefan-Boltzmann constant in units of kg/s^3 / K^4
*/
//GSL_CONST_MKSA_STEFAN_BOLTZMANN_CONSTANT,
5.670367E-8, //from CODATA 2014
/**
* Planck's constant in units kg m^2 / s
*/
//GSL_CONST_MKSA_PLANCKS_CONSTANT_H,
6.626070040E-34, //from CODATA 2014
/**
* The speed of light in m/s
*/
//GSL_CONST_MKSA_SPEED_OF_LIGHT,
299792458.0, //from CODATA 2014
/**
* Electron volt to Joules convestion
*/
//GSL_CONST_MKSA_ELECTRON_VOLT,
1.6021766208e-19, //from CODATA 2014
/**
* Temperature of the CMB in K
*/
2.725,
//2.7255, // CLASS value
/**
* T_ncdm, as taken from CLASS, explanatory.ini
*/
0.71611,
/**
* neutrino mass splitting differences
* See Lesgourgues and Pastor, 2012 for these values.
* Adv. High Energy Phys. 2012 (2012) 608515,
* arXiv:1212.6154, page 13
*/
7.62E-5,
2.55E-3,
-2.43E-3
};
/* ------- ROUTINE: ccl_cosmology_create ------
INPUTS: ccl_parameters params
ccl_configuration config
TASK: creates the ccl_cosmology struct and passes some values to it
DEFINITIONS:
chi: comoving distance [Mpc]
growth: growth function (density)
fgrowth: logarithmic derivative of the growth (density) (dlnD/da?)
E: E(a)=H(a)/H0
growth0: growth at z=0, defined to be 1
sigma: ?
p_lnl: nonlinear matter power spectrum at z=0?
computed_distances, computed_growth,
computed_power, computed_sigma: store status of the computations
*/
ccl_cosmology * ccl_cosmology_create(ccl_parameters params, ccl_configuration config)
{
ccl_cosmology * cosmo = malloc(sizeof(ccl_cosmology));
cosmo->params = params;
cosmo->config = config;
cosmo->gsl_params = default_gsl_params;
cosmo->spline_params = default_spline_params;
cosmo->spline_params.A_SPLINE_TYPE = gsl_interp_akima;
cosmo->spline_params.K_SPLINE_TYPE = gsl_interp_akima;
cosmo->spline_params.M_SPLINE_TYPE = gsl_interp_akima;
cosmo->spline_params.D_SPLINE_TYPE = gsl_interp_akima;
cosmo->spline_params.PNL_SPLINE_TYPE = gsl_interp2d_bicubic;
cosmo->spline_params.PLIN_SPLINE_TYPE = gsl_interp2d_bicubic;
cosmo->spline_params.CORR_SPLINE_TYPE = gsl_interp_akima;
cosmo->data.chi = NULL;
cosmo->data.growth = NULL;
cosmo->data.fgrowth = NULL;
cosmo->data.E = NULL;
cosmo->data.growth0 = 1.;
cosmo->data.achi = NULL;
cosmo->data.logsigma = NULL;
cosmo->data.rsd_splines[0] = NULL;
cosmo->data.rsd_splines[1] = NULL;
cosmo->data.rsd_splines[2] = NULL;
cosmo->computed_distances = false;
cosmo->computed_growth = false;
cosmo->computed_sigma = false;
cosmo->status = 0;
ccl_cosmology_set_status_message(cosmo, "");
if(cosmo->spline_params.A_SPLINE_MAX !=1.) {
cosmo->status = CCL_ERROR_SPLINE;
ccl_cosmology_set_status_message(cosmo,
"ccl_core.c: ccl_cosmology_create(): "
"A_SPLINE_MAX needs to be 1.\n");
}
return cosmo;
}
/* ------ ROUTINE: ccl_parameters_fill_initial -------
INPUT: ccl_parameters: params
TASK: fill parameters not set by ccl_parameters_create with some initial values
DEFINITIONS:
Omega_g = (Omega_g*h^2)/h^2 is the radiation parameter; "g" is for photons, as in CLASS
T_CMB: CMB temperature in Kelvin
Omega_l: Lambda
A_s: amplitude of the primordial PS, enforced here to initially set to NaN
sigma8: variance in 8 Mpc/h spheres for normalization of matter PS, enforced here to initially set to NaN
z_star: recombination redshift
*/
void ccl_parameters_fill_initial(ccl_parameters * params, int *status)
{
// Fixed radiation parameters
// Omega_g * h**2 is known from T_CMB
params->T_CMB = ccl_constants.T_CMB;
// kg / m^3
double rho_g = 4. * ccl_constants.STBOLTZ / pow(ccl_constants.CLIGHT, 3) * pow(params->T_CMB, 4);
// kg / m^3
double rho_crit =
ccl_constants.RHO_CRITICAL *
ccl_constants.SOLAR_MASS/pow(ccl_constants.MPC_TO_METER, 3) *
pow(params->h, 2);
params->Omega_g = rho_g/rho_crit;
// Get the N_nu_rel from Neff and N_nu_mass
params->N_nu_rel = params->Neff - params->N_nu_mass * pow(ccl_constants.TNCDM, 4) / pow(4./11.,4./3.);
// Temperature of the relativistic neutrinos in K
double T_nu= (params->T_CMB) * pow(4./11.,1./3.);
// in kg / m^3
double rho_nu_rel =
params->N_nu_rel* 7.0/8.0 * 4. *
ccl_constants.STBOLTZ / pow(ccl_constants.CLIGHT, 3) *
pow(T_nu, 4);
params-> Omega_nu_rel = rho_nu_rel/rho_crit;
// If non-relativistic neutrinos are present, calculate the phase_space integral.
if((params->N_nu_mass)>0) {
params->Omega_nu_mass = ccl_Omeganuh2(
1.0, params->N_nu_mass, params->m_nu, params->T_CMB, status) / ((params->h)*(params->h));
}
else{
params->Omega_nu_mass = 0.;
}
params->Omega_m = params->Omega_b + params-> Omega_c + params->Omega_nu_mass;
params->Omega_l = 1.0 - params->Omega_m - params->Omega_g - params->Omega_nu_rel - params->Omega_k;
// Initially undetermined parameters - set to nan to trigger
// problems if they are mistakenly used.
if (isfinite(params->A_s)) {params->sigma8 = NAN;}
if (isfinite(params->sigma8)) {params->A_s = NAN;}
params->z_star = NAN;
if(fabs(params->Omega_k)<1E-6)
params->k_sign=0;
else if(params->Omega_k>0)
params->k_sign=-1;
else
params->k_sign=1;
params->sqrtk=sqrt(fabs(params->Omega_k))*params->h/ccl_constants.CLIGHT_HMPC;
}
/* ------ ROUTINE: ccl_parameters_create -------
INPUT: numbers for the basic cosmological parameters needed by CCL
TASK: fill params with some initial values provided by the user
DEFINITIONS:
Omega_c: cold dark matter
Omega_b: baryons
Omega_m: matter
Omega_k: curvature
little omega_x means Omega_x*h^2
Neff : Effective number of neutrino speces
mnu : Pointer to either sum of neutrino masses or list of three masses.
mnu_type : how the neutrino mass(es) should be treated
w0: Dark energy eq of state parameter
wa: Dark energy eq of state parameter, time variation
H0: Hubble's constant in km/s/Mpc.
h: Hubble's constant divided by (100 km/s/Mpc).
A_s: amplitude of the primordial PS
n_s: index of the primordial PS
*/
ccl_parameters ccl_parameters_create(double Omega_c, double Omega_b, double Omega_k,
double Neff, double* mnu, int n_mnu,
double w0, double wa, double h, double norm_pk,
double n_s, double bcm_log10Mc, double bcm_etab,
double bcm_ks, double mu_0, double sigma_0,
int nz_mgrowth, double *zarr_mgrowth,
double *dfarr_mgrowth, int *status)
{
#ifndef USE_GSL_ERROR
gsl_set_error_handler_off();
#endif
ccl_parameters params;
// Initialize params
params.m_nu = NULL;
params.z_mgrowth=NULL;
params.df_mgrowth=NULL;
params.sigma8 = NAN;
params.A_s = NAN;
params.Omega_c = Omega_c;
params.Omega_b = Omega_b;
params.Omega_k = Omega_k;
params.Neff = Neff;
params.m_nu = malloc(n_mnu*sizeof(double));
params.sum_nu_masses = 0.;
for(int i = 0; i<n_mnu; i=i+1){
params.m_nu[i] = mnu[i];
params.sum_nu_masses = params.sum_nu_masses + mnu[i];
}
if(params.sum_nu_masses<1e-15){
params.N_nu_mass = 0;
}else{
params.N_nu_mass = n_mnu;
}
// Dark Energy
params.w0 = w0;
params.wa = wa;
// Hubble parameters
params.h = h;
params.H0 = h*100;
// Primordial power spectra
if(norm_pk<1E-5)
params.A_s=norm_pk;
else
params.sigma8=norm_pk;
params.n_s = n_s;
//Baryonic params
if(bcm_log10Mc<0)
params.bcm_log10Mc=log10(1.2e14);
else
params.bcm_log10Mc=bcm_log10Mc;
if(bcm_etab<0)
params.bcm_etab=0.5;
else
params.bcm_etab=bcm_etab;
if(bcm_ks<0)
params.bcm_ks=55.0;
else
params.bcm_ks=bcm_ks;
// Params of the mu / Sigma parameterisation of MG
params.mu_0 = mu_0;
params.sigma_0 = sigma_0;
// Set remaining standard and easily derived parameters
ccl_parameters_fill_initial(¶ms, status);
//Trigger modified growth function if nz>0
if(nz_mgrowth>0) {
params.has_mgrowth=true;
params.nz_mgrowth=nz_mgrowth;
params.z_mgrowth=malloc(params.nz_mgrowth*sizeof(double));
params.df_mgrowth=malloc(params.nz_mgrowth*sizeof(double));
memcpy(params.z_mgrowth,zarr_mgrowth,params.nz_mgrowth*sizeof(double));
memcpy(params.df_mgrowth,dfarr_mgrowth,params.nz_mgrowth*sizeof(double));
}
else {
params.has_mgrowth=false;
params.nz_mgrowth=0;
params.z_mgrowth=NULL;
params.df_mgrowth=NULL;
}
return params;
}
/**
* Write a cosmology parameters object to a file in yaml format.
* @param cosmo Cosmological parameters
* @param f FILE* pointer opened for reading
* @return void
*/
void ccl_parameters_write_yaml(ccl_parameters * params, const char * filename, int *status)
{
FILE * f = fopen(filename, "w");
if (!f){
*status = CCL_ERROR_FILE_WRITE;
return;
}
#define WRITE_DOUBLE(name) fprintf(f, #name ": %le\n",params->name)
#define WRITE_INT(name) fprintf(f, #name ": %d\n",params->name)
// Densities: CDM, baryons, total matter, curvature
WRITE_DOUBLE(Omega_c);
WRITE_DOUBLE(Omega_b);
WRITE_DOUBLE(Omega_m);
WRITE_DOUBLE(Omega_k);
WRITE_INT(k_sign);
// Dark Energy
WRITE_DOUBLE(w0);
WRITE_DOUBLE(wa);
// Hubble parameters
WRITE_DOUBLE(H0);
WRITE_DOUBLE(h);
// Neutrino properties
WRITE_DOUBLE(Neff);
WRITE_INT(N_nu_mass);
WRITE_DOUBLE(N_nu_rel);
if (params->N_nu_mass>0){
fprintf(f, "m_nu: [");
for (int i=0; i<params->N_nu_mass; i++){
fprintf(f, "%le, ", params->m_nu[i]);
}
fprintf(f, "]\n");
}
WRITE_DOUBLE(sum_nu_masses);
WRITE_DOUBLE(Omega_nu_mass);
WRITE_DOUBLE(Omega_nu_rel);
// Primordial power spectra
WRITE_DOUBLE(A_s);
WRITE_DOUBLE(n_s);
// Radiation parameters
WRITE_DOUBLE(Omega_g);
WRITE_DOUBLE(T_CMB);
// BCM baryonic model parameters
WRITE_DOUBLE(bcm_log10Mc);
WRITE_DOUBLE(bcm_etab);
WRITE_DOUBLE(bcm_ks);
// Modified gravity parameters
WRITE_DOUBLE(mu_0);
WRITE_DOUBLE(sigma_0);
// Derived parameters
WRITE_DOUBLE(sigma8);
WRITE_DOUBLE(Omega_l);
WRITE_DOUBLE(z_star);
WRITE_INT(has_mgrowth);
WRITE_INT(nz_mgrowth);
if (params->has_mgrowth){
fprintf(f, "z_mgrowth: [");
for (int i=0; i<params->nz_mgrowth; i++){
fprintf(f, "%le, ", params->z_mgrowth[i]);
}
fprintf(f, "]\n");
fprintf(f, "df_mgrowth: [");
for (int i=0; i<params->nz_mgrowth; i++){
fprintf(f, "%le, ", params->df_mgrowth[i]);
}
fprintf(f, "]\n");
}
#undef WRITE_DOUBLE
#undef WRITE_INT
fclose(f);
}
/**
* Write a cosmology parameters object to a file in yaml format.
* @param cosmo Cosmological parameters
* @param f FILE* pointer opened for reading
* @return void
*/
ccl_parameters ccl_parameters_read_yaml(const char * filename, int *status) {
FILE * f = fopen(filename, "r");
if (!f) {
*status = CCL_ERROR_FILE_READ;
ccl_parameters bad_params;
ccl_raise_warning(CCL_ERROR_FILE_READ,
"ccl_core.c: ccl_parameters_read_yaml(): "
"Failed to read parameters from file.");
return bad_params;
}
#define READ_DOUBLE(name) double name; *status |= (0==fscanf(f, #name ": %le\n",&name));
#define READ_INT(name) int name; *status |= (0==fscanf(f, #name ": %d\n",&name))
// Densities: CDM, baryons, total matter, curvature
READ_DOUBLE(Omega_c);
READ_DOUBLE(Omega_b);
READ_DOUBLE(Omega_m);
READ_DOUBLE(Omega_k);
READ_INT(k_sign);
// Dark Energy
READ_DOUBLE(w0);
READ_DOUBLE(wa);
// Hubble parameters
READ_DOUBLE(H0);
READ_DOUBLE(h);
// Neutrino properties
READ_DOUBLE(Neff);
READ_INT(N_nu_mass);
READ_DOUBLE(N_nu_rel);
double mnu[3] = {0.0, 0.0, 0.0};
if (N_nu_mass>0){
*status |= (0==fscanf(f, "m_nu: ["));
for (int i=0; i<N_nu_mass; i++){
*status |= (0==fscanf(f, "%le, ", mnu+i));
}
*status |= (0==fscanf(f, "]\n"));
}
READ_DOUBLE(sum_nu_masses);
READ_DOUBLE(Omega_nu_mass);
READ_DOUBLE(Omega_nu_rel);
// Primordial power spectra
READ_DOUBLE(A_s);
READ_DOUBLE(n_s);
// Radiation parameters
READ_DOUBLE(Omega_g);
READ_DOUBLE(T_CMB);
// BCM baryonic model parameters
READ_DOUBLE(bcm_log10Mc);
READ_DOUBLE(bcm_etab);
READ_DOUBLE(bcm_ks);
// Modified gravity parameters
READ_DOUBLE(mu_0);
READ_DOUBLE(sigma_0);
// Derived parameters
READ_DOUBLE(sigma8);
READ_DOUBLE(Omega_l);
READ_DOUBLE(z_star);
READ_INT(has_mgrowth);
READ_INT(nz_mgrowth);
double *z_mgrowth;
double *df_mgrowth;
if (has_mgrowth){
z_mgrowth = malloc(nz_mgrowth*sizeof(double));
df_mgrowth = malloc(nz_mgrowth*sizeof(double));
*status |= (0==fscanf(f, "z_mgrowth: ["));
for (int i=0; i<nz_mgrowth; i++){
*status |= (0==fscanf(f, "%le, ", z_mgrowth+i));
}
*status |= (0==fscanf(f, "]\n"));
*status |= (0==fscanf(f, "df_mgrowth: ["));
for (int i=0; i<nz_mgrowth; i++){
*status |= (0==fscanf(f, "%le, ", df_mgrowth+i));
}
*status |= (0==fscanf(f, "]\n"));
}
else{
z_mgrowth = NULL;
df_mgrowth = NULL;
}
#undef READ_DOUBLE
#undef READ_INT
fclose(f);
if (*status) {
ccl_raise_warning(
*status,
"ccl_core.c: ccl_parameters_read_yaml():"
"Structure of YAML file incorrect: %s",
filename);
}
double norm_pk;
if (isnan(A_s)){
norm_pk = sigma8;
}
else{
norm_pk = A_s;
}
ccl_parameters params = ccl_parameters_create(
Omega_c, Omega_b, Omega_k,
Neff, mnu, N_nu_mass,
w0, wa, h, norm_pk,
n_s, bcm_log10Mc, bcm_etab,
bcm_ks, mu_0, sigma_0, nz_mgrowth, z_mgrowth,
df_mgrowth, status);
if(z_mgrowth) free(z_mgrowth);
if (df_mgrowth) free(df_mgrowth);
return params;
}
/* ------- ROUTINE: ccl_data_free --------
INPUT: ccl_data
TASK: free the input data
*/
void ccl_data_free(ccl_data * data) {
//We cannot assume that all of these have been allocated
//TODO: it would actually make more sense to do this within ccl_cosmology_free,
//where we could make use of the flags "computed_distances" etc. to figure out
//what to free up
gsl_spline_free(data->chi);
gsl_spline_free(data->growth);
gsl_spline_free(data->fgrowth);
gsl_spline_free(data->E);
gsl_spline_free(data->achi);
gsl_spline2d_free(data->logsigma);
ccl_f1d_t_free(data->rsd_splines[0]);
ccl_f1d_t_free(data->rsd_splines[1]);
ccl_f1d_t_free(data->rsd_splines[2]);
}
/* ------- ROUTINE: ccl_cosmology_set_status_message --------
INPUT: ccl_cosmology struct, status_string
TASK: set the status message safely.
*/
void ccl_cosmology_set_status_message(ccl_cosmology * cosmo, const char * message, ...) {
const int trunc = 480; /* must be < 500 - 4 */
va_list va;
va_start(va, message);
#pragma omp critical
{
vsnprintf(cosmo->status_message, trunc, message, va);
/* if truncation happens, message[trunc - 1] is not NULL, ... will show up. */
strcpy(&cosmo->status_message[trunc], "...");
}
va_end(va);
}
/* ------- ROUTINE: ccl_parameters_free --------
INPUT: ccl_parameters struct
TASK: free allocated quantities in the parameters struct
*/
void ccl_parameters_free(ccl_parameters * params) {
if (params->m_nu != NULL){
free(params->m_nu);
params->m_nu = NULL;
}
if (params->z_mgrowth != NULL){
free(params->z_mgrowth);
params->z_mgrowth = NULL;
}
if (params->df_mgrowth != NULL){
free(params->df_mgrowth);
params->df_mgrowth = NULL;
}
}
/* ------- ROUTINE: ccl_cosmology_free --------
INPUT: ccl_cosmology struct
TASK: free the input data and the cosmology struct
*/
void ccl_cosmology_free(ccl_cosmology * cosmo) {
if (cosmo != NULL)
ccl_data_free(&cosmo->data);
free(cosmo);
}
int ccl_get_pk_spline_na(ccl_cosmology *cosmo) {
return cosmo->spline_params.A_SPLINE_NA_PK + cosmo->spline_params.A_SPLINE_NLOG_PK - 1;
}
void ccl_get_pk_spline_a_array(ccl_cosmology *cosmo,int ndout,double* doutput,int *status) {
double *d = NULL;
if (ndout != ccl_get_pk_spline_na(cosmo))
*status = CCL_ERROR_INCONSISTENT;
if (*status == 0) {
d = ccl_linlog_spacing(cosmo->spline_params.A_SPLINE_MINLOG_PK,
cosmo->spline_params.A_SPLINE_MIN_PK,
cosmo->spline_params.A_SPLINE_MAX,
cosmo->spline_params.A_SPLINE_NLOG_PK,
cosmo->spline_params.A_SPLINE_NA_PK);
if (d == NULL)
*status = CCL_ERROR_MEMORY;
}
if(*status==0)
memcpy(doutput, d, ndout*sizeof(double));
free(d);
}
int ccl_get_pk_spline_nk(ccl_cosmology *cosmo) {
double ndecades = log10(cosmo->spline_params.K_MAX) - log10(cosmo->spline_params.K_MIN);
return (int)ceil(ndecades*cosmo->spline_params.N_K);
}
void ccl_get_pk_spline_lk_array(ccl_cosmology *cosmo,int ndout,double* doutput,int *status) {
double *d = NULL;
if (ndout != ccl_get_pk_spline_nk(cosmo))
*status = CCL_ERROR_INCONSISTENT;
if (*status == 0) {
d = ccl_log_spacing(cosmo->spline_params.K_MIN, cosmo->spline_params.K_MAX, ndout);
if (d == NULL)
*status = CCL_ERROR_MEMORY;
}
if (*status == 0) {
for(int ii=0; ii < ndout; ii++)
doutput[ii] = log(d[ii]);
}
free(d);
}
| {
"alphanum_fraction": 0.6752116977,
"avg_line_length": 26.1951515152,
"ext": "c",
"hexsha": "961ede46a4d121cda8053746cb3c9ee906e300bb",
"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": "6ddd35e49f9d2968cef3d3bc1bac8b55dbb4cf91",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "borisbolliet/CCL",
"max_forks_repo_path": "src/ccl_core.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "6ddd35e49f9d2968cef3d3bc1bac8b55dbb4cf91",
"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": "borisbolliet/CCL",
"max_issues_repo_path": "src/ccl_core.c",
"max_line_length": 108,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "6ddd35e49f9d2968cef3d3bc1bac8b55dbb4cf91",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "borisbolliet/CCL",
"max_stars_repo_path": "src/ccl_core.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 6853,
"size": 21611
} |
#include <cblas.h>
#include <stdio.h>
double m[] = {
3, 1, 3,
1, 5, 9,
2, 6, 5
};
double x[] = {
-1, 3, -3
};
#ifdef __cplusplus
extern "C" {
#endif
void dgesv_(int *n, int *nrhs, double *a, int *lda,
int *ipivot, double *b, int *ldb, int *info);
#ifdef __cplusplus
}
#endif
int main(void) {
int i;
// blas:
double A[6] = {1.0, 2.0, 1.0, -3.0, 4.0, -1.0};
double B[6] = {1.0, 2.0, 1.0, -3.0, 4.0, -1.0};
double C[9] = {.5, .5, .5, .5, .5, .5, .5, .5, .5};
cblas_dgemm(CblasColMajor, CblasNoTrans, CblasTrans,
3, 3, 2, 1, A, 3, B, 3, 2, C, 3);
for (i = 0; i < 9; i++)
printf("%f\n", C[i]);
// lapack:
int ipiv[3];
int j;
int info;
int n = 1;
int nrhs = 1;
int lda = 3;
int ldb = 3;
dgesv_(&n,&nrhs, &m[0], &lda, ipiv, &x[0], &ldb, &info);
for (i=0; i<3; ++i)
printf("%5.1f\n", x[i]);
return 0;
}
| {
"alphanum_fraction": 0.4763513514,
"avg_line_length": 17.76,
"ext": "c",
"hexsha": "2cb90fb8830c56a0089f3c027c4e114acc06e4f5",
"lang": "C",
"max_forks_count": 1793,
"max_forks_repo_forks_event_max_datetime": "2022-03-30T14:31:53.000Z",
"max_forks_repo_forks_event_min_datetime": "2017-11-04T07:45:50.000Z",
"max_forks_repo_head_hexsha": "6ae8d5c380c1f42094b05d38be26b03650aafb39",
"max_forks_repo_licenses": [
"ECL-2.0",
"Apache-2.0",
"MIT-0",
"MIT"
],
"max_forks_repo_name": "kkauder/spack",
"max_forks_repo_path": "var/spack/repos/builtin/packages/openblas/test_cblas_dgemm.c",
"max_issues_count": 13838,
"max_issues_repo_head_hexsha": "6ae8d5c380c1f42094b05d38be26b03650aafb39",
"max_issues_repo_issues_event_max_datetime": "2022-03-31T23:38:39.000Z",
"max_issues_repo_issues_event_min_datetime": "2017-11-04T07:49:45.000Z",
"max_issues_repo_licenses": [
"ECL-2.0",
"Apache-2.0",
"MIT-0",
"MIT"
],
"max_issues_repo_name": "kkauder/spack",
"max_issues_repo_path": "var/spack/repos/builtin/packages/openblas/test_cblas_dgemm.c",
"max_line_length": 59,
"max_stars_count": 2360,
"max_stars_repo_head_hexsha": "6ae8d5c380c1f42094b05d38be26b03650aafb39",
"max_stars_repo_licenses": [
"ECL-2.0",
"Apache-2.0",
"MIT-0",
"MIT"
],
"max_stars_repo_name": "kkauder/spack",
"max_stars_repo_path": "var/spack/repos/builtin/packages/openblas/test_cblas_dgemm.c",
"max_stars_repo_stars_event_max_datetime": "2022-03-31T14:45:33.000Z",
"max_stars_repo_stars_event_min_datetime": "2017-11-06T08:47:01.000Z",
"num_tokens": 435,
"size": 888
} |
/* interpolation/accel.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 3 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
/* Author: G. Jungman
*/
#include <config.h>
#include <stdlib.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_interp.h>
gsl_interp_accel *
gsl_interp_accel_alloc (void)
{
gsl_interp_accel *a = (gsl_interp_accel *) malloc (sizeof (gsl_interp_accel));
if (a == 0)
{
GSL_ERROR_NULL("could not allocate space for gsl_interp_accel", GSL_ENOMEM);
}
a->cache = 0;
a->hit_count = 0;
a->miss_count = 0;
return a;
}
int
gsl_interp_accel_reset (gsl_interp_accel * a)
{
a->cache = 0;
a->hit_count = 0;
a->miss_count = 0;
return GSL_SUCCESS;
}
void
gsl_interp_accel_free (gsl_interp_accel * a)
{
RETURN_IF_NULL (a);
free (a);
}
| {
"alphanum_fraction": 0.7074324324,
"avg_line_length": 25.0847457627,
"ext": "c",
"hexsha": "00063fd8c9c56882827ac1ebf2c65a5ea9b877db",
"lang": "C",
"max_forks_count": 14,
"max_forks_repo_forks_event_max_datetime": "2020-03-12T12:31:25.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-07-21T04:47:52.000Z",
"max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "Brian-ning/HMNE",
"max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/interpolation/accel.c",
"max_issues_count": 6,
"max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e",
"max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z",
"max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "Brian-ning/HMNE",
"max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/interpolation/accel.c",
"max_line_length": 82,
"max_stars_count": 14,
"max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "ielomariala/Hex-Game",
"max_stars_repo_path": "gsl-2.6/interpolation/accel.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": 415,
"size": 1480
} |
#include <qdm.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_randist.h>
#include <hdf5.h>
#include <hdf5_hl.h>
static
void
qdm_mcmc_workspace_init(
qdm_mcmc *mcmc
)
{
mcmc->w.xi = gsl_vector_calloc(mcmc->p.xi->size);
mcmc->w.xi_acc = gsl_vector_calloc(mcmc->p.xi->size);
mcmc->w.xi_p = gsl_vector_calloc(mcmc->p.xi->size);
mcmc->w.xi_tune = gsl_vector_calloc(mcmc->p.xi->size);
gsl_vector_memcpy(mcmc->w.xi, mcmc->p.xi);
gsl_vector_memcpy(mcmc->w.xi_p, mcmc->p.xi);
gsl_vector_set_all(mcmc->w.xi_tune, mcmc->p.xi_tune_sd);
mcmc->w.ll = gsl_vector_calloc(mcmc->p.ll->size);
mcmc->w.ll_p = gsl_vector_calloc(mcmc->p.ll->size);
gsl_vector_memcpy(mcmc->w.ll, mcmc->p.ll);
gsl_vector_memcpy(mcmc->w.ll_p, mcmc->p.ll);
mcmc->w.tau = gsl_vector_calloc(mcmc->p.tau->size);
mcmc->w.tau_p = gsl_vector_calloc(mcmc->p.tau->size);
gsl_vector_memcpy(mcmc->w.tau, mcmc->p.tau);
gsl_vector_memcpy(mcmc->w.tau_p, mcmc->p.tau);
mcmc->w.theta = gsl_matrix_calloc(mcmc->p.theta->size1, mcmc->p.theta->size2);
mcmc->w.theta_acc = gsl_matrix_calloc(mcmc->p.theta->size1, mcmc->p.theta->size2);
mcmc->w.theta_p = gsl_matrix_calloc(mcmc->p.theta->size1, mcmc->p.theta->size2);
mcmc->w.theta_star = gsl_matrix_calloc(mcmc->p.theta->size1, mcmc->p.theta->size2);
mcmc->w.theta_star_p = gsl_matrix_calloc(mcmc->p.theta->size1, mcmc->p.theta->size2);
mcmc->w.theta_tune = gsl_matrix_calloc(mcmc->p.theta->size1, mcmc->p.theta->size2);
gsl_matrix_memcpy(mcmc->w.theta, mcmc->p.theta);
gsl_matrix_memcpy(mcmc->w.theta_star, mcmc->p.theta);
gsl_matrix_set_all(mcmc->w.theta_tune, mcmc->p.theta_tune_sd);
}
static
void
qdm_mcmc_workspace_fini(
qdm_mcmc *mcmc
)
{
gsl_vector_free(mcmc->w.xi);
gsl_vector_free(mcmc->w.xi_acc);
gsl_vector_free(mcmc->w.xi_p);
gsl_vector_free(mcmc->w.xi_tune);
gsl_vector_free(mcmc->w.ll);
gsl_vector_free(mcmc->w.ll_p);
gsl_vector_free(mcmc->w.tau);
gsl_vector_free(mcmc->w.tau_p);
gsl_matrix_free(mcmc->w.theta);
gsl_matrix_free(mcmc->w.theta_acc);
gsl_matrix_free(mcmc->w.theta_p);
gsl_matrix_free(mcmc->w.theta_star);
gsl_matrix_free(mcmc->w.theta_star_p);
gsl_matrix_free(mcmc->w.theta_tune);
mcmc->w.xi = NULL;
mcmc->w.xi_acc = NULL;
mcmc->w.xi_p = NULL;
mcmc->w.xi_tune = NULL;
mcmc->w.ll = NULL;
mcmc->w.ll_p = NULL;
mcmc->w.tau = NULL;
mcmc->w.tau_p = NULL;
mcmc->w.theta = NULL;
mcmc->w.theta_acc = NULL;
mcmc->w.theta_p = NULL;
mcmc->w.theta_star = NULL;
mcmc->w.theta_star_p = NULL;
mcmc->w.theta_tune = NULL;
}
static
void
qdm_mcmc_results_init(
qdm_mcmc *mcmc
)
{
mcmc->r.s = mcmc->p.iter / mcmc->p.thin;
mcmc->r.theta = qdm_ijk_calloc(mcmc->p.theta->size1, mcmc->p.theta->size2, mcmc->r.s);
mcmc->r.theta_star = qdm_ijk_calloc(mcmc->p.theta->size1, mcmc->p.theta->size2, mcmc->r.s);
mcmc->r.ll = qdm_ijk_calloc(1, mcmc->p.ll->size, mcmc->r.s);
mcmc->r.tau = qdm_ijk_calloc(1, mcmc->p.tau->size, mcmc->r.s);
mcmc->r.xi = qdm_ijk_calloc(1, mcmc->p.xi->size, mcmc->r.s);
}
static
void
qdm_mcmc_results_fini(
qdm_mcmc *mcmc
)
{
qdm_ijk_free(mcmc->r.theta);
qdm_ijk_free(mcmc->r.theta_star);
qdm_ijk_free(mcmc->r.ll);
qdm_ijk_free(mcmc->r.tau);
qdm_ijk_free(mcmc->r.xi);
mcmc->r.theta = NULL;
mcmc->r.theta_star = NULL;
mcmc->r.ll = NULL;
mcmc->r.tau = NULL;
mcmc->r.xi = NULL;
}
qdm_mcmc *
qdm_mcmc_alloc(
qdm_mcmc_parameters p
)
{
qdm_mcmc *mcmc = malloc(sizeof(qdm_mcmc));
mcmc->p = p;
qdm_mcmc_workspace_init(mcmc);
qdm_mcmc_results_init(mcmc);
return mcmc;
}
void
qdm_mcmc_free(
qdm_mcmc *mcmc
)
{
if (mcmc == NULL) {
return;
}
qdm_mcmc_results_fini(mcmc);
qdm_mcmc_workspace_fini(mcmc);
free(mcmc);
}
int
qdm_mcmc_run(
qdm_mcmc *mcmc
)
{
int status = 0;
for (size_t i = 0; i < mcmc->p.burn; i++) {
status = qdm_mcmc_next(mcmc);
if (status != 0) {
goto cleanup;
}
if (i % mcmc->p.acc_check == 0) {
qdm_mcmc_update_tune(mcmc);
}
}
for (size_t i = 0; i < mcmc->p.iter; i++) {
status = qdm_mcmc_next(mcmc);
if (status != 0) {
goto cleanup;
}
if (i % mcmc->p.thin == 0) {
status = qdm_mcmc_save(mcmc, i / mcmc->p.thin);
if (status != 0) {
goto cleanup;
}
}
}
cleanup:
return status;
}
int
qdm_mcmc_next(
qdm_mcmc *mcmc
)
{
int status = 0;
status = qdm_mcmc_update_theta(mcmc);
if (status != 0) {
goto cleanup;
}
status = qdm_mcmc_update_xi(mcmc);
if (status != 0) {
goto cleanup;
}
cleanup:
return status;
}
void
qdm_mcmc_update_tune(
qdm_mcmc *mcmc
)
{
for (size_t p = 0; p < mcmc->w.theta->size1; p++) {
for (size_t m = 0; m < mcmc->w.theta->size2; m++) {
if (gsl_matrix_get(mcmc->w.theta_acc, p, m) / (double)mcmc->p.acc_check > 0.5) {
gsl_matrix_set(mcmc->w.theta_tune, p, m, gsl_min(gsl_matrix_get(mcmc->w.theta_tune, p, m) * 1.2, 5));
}
if (gsl_matrix_get(mcmc->w.theta_acc, p, m) / (double)mcmc->p.acc_check < 0.3) {
gsl_matrix_set(mcmc->w.theta_tune, p, m, gsl_matrix_get(mcmc->w.theta_tune, p, m) * 0.8);
}
}
}
if (gsl_vector_get(mcmc->w.xi_acc, 0) / mcmc->p.acc_check > 0.5) {
gsl_vector_set(mcmc->w.xi_tune, 0, gsl_min(gsl_vector_get(mcmc->w.xi_tune, 0) * 1.2, 5));
}
if (gsl_vector_get(mcmc->w.xi_acc, 0) / mcmc->p.acc_check < 0.3) {
gsl_vector_set(mcmc->w.xi_tune, 0, gsl_vector_get(mcmc->w.xi_tune, 0) * 0.8);
}
if (gsl_vector_get(mcmc->w.xi_acc, 1) / mcmc->p.acc_check > 0.5) {
gsl_vector_set(mcmc->w.xi_tune, 1, gsl_min(gsl_vector_get(mcmc->w.xi_tune, 1) * 1.2, 5));
}
if (gsl_vector_get(mcmc->w.xi_acc, 1) / mcmc->p.acc_check < 0.3) {
gsl_vector_set(mcmc->w.xi_tune, 1, gsl_vector_get(mcmc->w.xi_tune, 1) * 0.8);
}
/* Reset the acceptance counter. */
gsl_matrix_set_zero(mcmc->w.theta_acc);
gsl_vector_set_zero(mcmc->w.xi_acc);
}
int
qdm_mcmc_update_theta(
qdm_mcmc *mcmc
)
{
int status = 0;
/* Update the mth spline. */
size_t p_max = mcmc->w.theta->size1;
if (mcmc->p.truncate) {
p_max = 1;
}
for (size_t p = 0; p < p_max; p++) {
for (size_t m = 0; m < mcmc->w.theta->size2; m++) {
/* Propose new theta star. */
status = gsl_matrix_memcpy(mcmc->w.theta_star_p, mcmc->w.theta_star);
if (status != 0) {
goto cleanup;
}
double proposal =
gsl_matrix_get(mcmc->w.theta_tune, p, m) *
gsl_ran_ugaussian(mcmc->p.rng) +
gsl_matrix_get(mcmc->w.theta_star, p, m);
gsl_matrix_set(mcmc->w.theta_star_p, p, m, proposal);
gsl_matrix_memcpy(mcmc->w.theta_p, mcmc->w.theta_star_p);
qdm_theta_matrix_constrain(mcmc->w.theta_p, mcmc->p.theta_min);
for (size_t i = 0; i < mcmc->p.y->size; i++) {
qdm_logl_3(
gsl_vector_ptr(mcmc->w.ll_p, i),
gsl_vector_ptr(mcmc->w.tau_p, i),
gsl_vector_get(mcmc->p.x, i),
gsl_vector_get(mcmc->p.y, i),
mcmc->p.t,
mcmc->w.xi,
mcmc->w.theta_p
);
}
double ratio = qdm_vector_sum(mcmc->w.ll_p) - qdm_vector_sum(mcmc->w.ll);
if (log(gsl_rng_uniform(mcmc->p.rng)) < ratio) {
status = gsl_matrix_memcpy(mcmc->w.theta_star, mcmc->w.theta_star_p);
if (status != 0) {
goto cleanup;
}
status = gsl_matrix_memcpy(mcmc->w.theta, mcmc->w.theta_p);
if (status != 0) {
goto cleanup;
}
status = gsl_vector_memcpy(mcmc->w.ll, mcmc->w.ll_p);
if (status != 0) {
goto cleanup;
}
status = gsl_vector_memcpy(mcmc->w.tau, mcmc->w.tau_p);
if (status != 0) {
goto cleanup;
}
gsl_matrix_set(mcmc->w.theta_acc, p, m, gsl_matrix_get(mcmc->w.theta_acc, p, m) + 1);
}
}
}
cleanup:
return status;
}
int
qdm_mcmc_update_xi(
qdm_mcmc *mcmc
)
{
int status = 0;
/* Update xi_low. */
{
double xi_low = gsl_vector_get(mcmc->w.xi, 0);
double xi_low_p = exp(log(xi_low) + gsl_vector_get(mcmc->w.xi_tune, 0) * gsl_ran_ugaussian(mcmc->p.rng));
gsl_vector_memcpy(mcmc->w.xi_p, mcmc->w.xi);
gsl_vector_set(mcmc->w.xi_p, 0, xi_low_p);
for (size_t i = 0; i < mcmc->p.y->size; i++) {
qdm_logl_3(
gsl_vector_ptr(mcmc->w.ll_p, i),
gsl_vector_ptr(mcmc->w.tau_p, i),
gsl_vector_get(mcmc->p.x, i),
gsl_vector_get(mcmc->p.y, i),
mcmc->p.t,
mcmc->w.xi_p,
mcmc->w.theta
);
}
double ratio = -0.5 * (1 / mcmc->p.xi_prior_var) * pow(log(xi_low_p) - mcmc->p.xi_prior_mean, 2) +
0.5 * (1 / mcmc->p.xi_prior_var) * (pow(log(xi_low ) - mcmc->p.xi_prior_mean, 2) + qdm_vector_sum(mcmc->w.ll_p) - qdm_vector_sum(mcmc->w.ll));
if (log(gsl_rng_uniform(mcmc->p.rng)) < ratio) {
gsl_vector_set(mcmc->w.xi, 0, xi_low_p);
status = gsl_vector_memcpy(mcmc->w.ll, mcmc->w.ll_p);
if (status != 0) {
goto cleanup;
}
gsl_vector_set(mcmc->w.xi_acc, 0, gsl_vector_get(mcmc->w.xi_acc, 0) + 1);
}
}
/* Update xi_high. */
{
double xi_high = gsl_vector_get(mcmc->w.xi, 1);
double xi_high_p = exp(log(xi_high) + gsl_vector_get(mcmc->w.xi_tune, 1) * gsl_ran_ugaussian(mcmc->p.rng));
gsl_vector_memcpy(mcmc->w.xi_p, mcmc->w.xi);
gsl_vector_set(mcmc->w.xi_p, 1, xi_high_p);
for (size_t i = 0; i < mcmc->p.y->size; i++) {
qdm_logl_3(
gsl_vector_ptr(mcmc->w.ll_p, i),
gsl_vector_ptr(mcmc->w.tau_p, i),
gsl_vector_get(mcmc->p.x, i),
gsl_vector_get(mcmc->p.y, i),
mcmc->p.t,
mcmc->w.xi_p,
mcmc->w.theta
);
}
double ratio = -0.5 * (1 / mcmc->p.xi_prior_var) * pow(log(xi_high_p) - mcmc->p.xi_prior_mean, 2) +
0.5 * (1 / mcmc->p.xi_prior_var) * (pow(log(xi_high ) - mcmc->p.xi_prior_mean, 2) + qdm_vector_sum(mcmc->w.ll_p) - qdm_vector_sum(mcmc->w.ll));
if (log(gsl_rng_uniform(mcmc->p.rng)) < ratio) {
gsl_vector_set(mcmc->w.xi, 1, xi_high_p);
status = gsl_vector_memcpy(mcmc->w.ll, mcmc->w.ll_p);
if (status != 0) {
goto cleanup;
}
gsl_vector_set(mcmc->w.xi_acc, 1, gsl_vector_get(mcmc->w.xi_acc, 1) + 1);
}
}
cleanup:
return status;
}
int
qdm_mcmc_save(
qdm_mcmc *mcmc,
size_t k
)
{
int status = 0;
{
gsl_matrix_view m = qdm_ijk_get_ij(mcmc->r.theta, k);
status = gsl_matrix_memcpy(&m.matrix, mcmc->w.theta);
if (status != 0) {
goto cleanup;
}
}
{
gsl_matrix_view m = qdm_ijk_get_ij(mcmc->r.theta_star, k);
status = gsl_matrix_memcpy(&m.matrix, mcmc->w.theta_star);
if (status != 0) {
goto cleanup;
}
}
{
gsl_matrix_view m = qdm_ijk_get_ij(mcmc->r.ll, k);
status = gsl_matrix_set_row(&m.matrix, 0, mcmc->w.ll);
if (status != 0) {
goto cleanup;
}
}
{
gsl_matrix_view m = qdm_ijk_get_ij(mcmc->r.tau, k);
status = gsl_matrix_set_row(&m.matrix, 0, mcmc->w.tau);
if (status != 0) {
goto cleanup;
}
}
{
gsl_matrix_view m = qdm_ijk_get_ij(mcmc->r.xi, k);
status = gsl_matrix_set_row(&m.matrix, 0, mcmc->w.xi);
if (status != 0) {
goto cleanup;
}
}
cleanup:
return status;
}
int
qdm_mcmc_write(
hid_t id,
const qdm_mcmc *mcmc
)
{
int status = 0;
status = qdm_ijk_write(id, "theta", mcmc->r.theta);
if (status != 0) {
goto cleanup;
}
status = qdm_ijk_write(id, "theta_star", mcmc->r.theta_star);
if (status != 0) {
goto cleanup;
}
status = qdm_ijk_write(id, "ll", mcmc->r.ll);
if (status != 0) {
goto cleanup;
}
status = qdm_ijk_write(id, "tau", mcmc->r.tau);
if (status != 0) {
goto cleanup;
}
status = qdm_ijk_write(id, "xi", mcmc->r.xi);
if (status != 0) {
goto cleanup;
}
cleanup:
return status;
}
int
qdm_mcmc_read(
hid_t id,
qdm_mcmc **mcmc
)
{
int status = 0;
*mcmc = malloc(sizeof(qdm_mcmc));
status = qdm_ijk_read(id, "theta", &(*mcmc)->r.theta);
if (status != 0) {
goto cleanup;
}
status = qdm_ijk_read(id, "theta_star", &(*mcmc)->r.theta_star);
if (status != 0) {
goto cleanup;
}
status = qdm_ijk_read(id, "ll", &(*mcmc)->r.ll);
if (status != 0) {
goto cleanup;
}
status = qdm_ijk_read(id, "tau", &(*mcmc)->r.tau);
if (status != 0) {
goto cleanup;
}
status = qdm_ijk_read(id, "xi", &(*mcmc)->r.xi);
if (status != 0) {
goto cleanup;
}
(*mcmc)->r.s = (*mcmc)->r.theta->size3;
cleanup:
return status;
}
| {
"alphanum_fraction": 0.6002835986,
"avg_line_length": 22.9963768116,
"ext": "c",
"hexsha": "c9bece99e5317496e5efc4c5a813b9fed28f439e",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "2ee95bec6c8be64f69e231c78f2be5fce3509c67",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "calebcase/qdm",
"max_forks_repo_path": "src/mcmc.c",
"max_issues_count": 3,
"max_issues_repo_head_hexsha": "2ee95bec6c8be64f69e231c78f2be5fce3509c67",
"max_issues_repo_issues_event_max_datetime": "2020-03-22T20:22:53.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-03-06T18:09:06.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "calebcase/qdm",
"max_issues_repo_path": "src/mcmc.c",
"max_line_length": 164,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "2ee95bec6c8be64f69e231c78f2be5fce3509c67",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "calebcase/qdm",
"max_stars_repo_path": "src/mcmc.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 4587,
"size": 12694
} |
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
#include <gsl/gsl_blas.h>
#define RESOLUTION 28 // bmp image 28*28
#define LINE_LEN (RESOLUTION * RESOLUTION * 4) // All the pixel data stored within a line
#define DATA_NUM_WITHOUT_LABEL (RESOLUTION * RESOLUTION) // Data length without label
#define DATA_NUM_WITH_LABEL ((RESOLUTION * RESOLUTION) + 1) // For training, the first number is label, so +1
#define HIDDEN_NODE 250 // node number in hidden layer
#define OUTPUT_NODE 10 // output node number
#define LEARN_RATE 0.1
#define TRAIN_SET_SIZE 5000
#define TEST_SET_SIZE 1000
#define EPOCH 8
#define SIGMOID(x) (1.0 / (1.0 + (pow(M_E, -x))))
#define NOR_DIS_DEV(x) (pow(x, -0.5)) // For generating init weight
FILE* openfile(char* file_name);
void read_parse(FILE* fp, int input_data[], int* label, char* mode);
gsl_matrix* scale_input(int input_data[]);
gsl_matrix* vectorize_target(int label);
gsl_matrix* init_weight(int row, int col);
double get_output_error(gsl_matrix* target, gsl_matrix* output, gsl_matrix* output_error);
void training(gsl_matrix* better_input, gsl_matrix* target, gsl_matrix* input_weight, gsl_matrix* hidden_weight, gsl_matrix* hidden_x, gsl_matrix* hidden_o, gsl_matrix* output_o, gsl_matrix* output_x, gsl_matrix* output_error, gsl_matrix* hidden_error, double* error);
void store_weight(gsl_matrix* input_weight, gsl_matrix* hidden_weight);
void load_weight(gsl_matrix* input_weight, gsl_matrix* hidden_weight);
int recognize(gsl_matrix* better_input, gsl_matrix* input_weight, gsl_matrix* hidden_weight, gsl_matrix* hidden_x, gsl_matrix* hidden_o, gsl_matrix* output_x, gsl_matrix* output_o);
int main(int argc, char **argv)
{
int label;
double error;
double error_acc = 0.0;
char* file_name;
char* mode;
FILE* fp;
int input_data[DATA_NUM_WITHOUT_LABEL];
gsl_matrix* better_input;
gsl_matrix* target;
gsl_matrix* output_error = gsl_matrix_alloc(OUTPUT_NODE, 1);
gsl_matrix* hidden_error = gsl_matrix_alloc(HIDDEN_NODE, 1);
gsl_matrix* output_x = gsl_matrix_alloc(OUTPUT_NODE, 1);
gsl_matrix* output_o = gsl_matrix_alloc(OUTPUT_NODE, 1);
gsl_matrix* hidden_x = gsl_matrix_alloc(HIDDEN_NODE, 1);
gsl_matrix* hidden_o = gsl_matrix_alloc(HIDDEN_NODE, 1);
gsl_matrix* input_weight;
gsl_matrix* hidden_weight;
if(argc < 3){
fprintf(stderr, "Usage: %s [-t(raining), -r(cognizing), -e(poch)] [file_name]\n", argv[0]);
exit(EXIT_FAILURE);
}else{
mode = argv[1];
file_name = argv[2];
}
fp = openfile(file_name);
if(!strcmp(mode, "-t")){
//training
input_weight = init_weight(HIDDEN_NODE, DATA_NUM_WITHOUT_LABEL); // initiate the input-hidden weight
hidden_weight = init_weight(OUTPUT_NODE, HIDDEN_NODE); // initiate the hidden-output weight
int training_times = 0;
puts("Training started\n");
for (int i = 0; i < EPOCH; i++){
do{
read_parse(fp, input_data, &label, mode);
better_input = scale_input(input_data);
target = vectorize_target(label);
training(better_input, target, input_weight, hidden_weight, hidden_x, hidden_o, output_o, output_x, output_error, hidden_error, &error);
training_times++;
error_acc += error;
}while(training_times < TRAIN_SET_SIZE);
rewind(fp); // back to the start of the input file, start epoch
if(i == 0){
printf("In the first training, Accumulative Error = %f\n", error_acc);
puts("========Start Epoch=========");
}else{
printf("Epoch %d, Accumulative Error = %f\n", i, error_acc);
}
error_acc = 0.0;
training_times = 0;
}
gsl_matrix_free(better_input), gsl_matrix_free(target), gsl_matrix_free(output_error), gsl_matrix_free(hidden_error), gsl_matrix_free(output_x), gsl_matrix_free(output_o);
gsl_matrix_free(hidden_x), gsl_matrix_free(hidden_o);
store_weight(input_weight, hidden_weight);
puts("Training weight has been stored!");
gsl_matrix_free(input_weight), gsl_matrix_free(hidden_weight);
}
if(!strcmp(mode, "-r")){
input_weight = gsl_matrix_alloc(HIDDEN_NODE, DATA_NUM_WITHOUT_LABEL);
hidden_weight = gsl_matrix_alloc(OUTPUT_NODE, HIDDEN_NODE);
load_weight(input_weight, hidden_weight);
int test_times = 0;
int wrong_times = 0;
int anwser;
do{
read_parse(fp, input_data, &label, mode);
better_input = scale_input(input_data);
anwser = recognize(better_input, input_weight, hidden_weight, hidden_x, hidden_o, output_x, output_o);
printf("Label: %d, Guess: %d\n", label, anwser);
if(anwser != label) wrong_times++;
test_times++;
}while(test_times < TEST_SET_SIZE);
printf("Performance: %2f\n", (1 - ((float)wrong_times/(float)test_times)) * 100);
gsl_matrix_free(better_input), gsl_matrix_free(target), gsl_matrix_free(output_error), gsl_matrix_free(hidden_error), gsl_matrix_free(output_x), gsl_matrix_free(output_o);
gsl_matrix_free(hidden_x), gsl_matrix_free(hidden_o);
gsl_matrix_free(input_weight), gsl_matrix_free(hidden_weight);
}
fclose(fp);
return 0;
}
FILE* openfile(char* file_name)
{
FILE* fp;
if(!(fp = fopen(file_name, "r")))
fprintf(stderr, "Can't open the file\n");
return fp;
}
void read_parse(FILE* fp, int input_data[], int* label, char* mode)
{
char line[LINE_LEN];
char temp;
int line_c = 0;
int input_c = 0;
char* token;
while((temp = fgetc(fp)) != '\n'){
if(temp == EOF) break;
line[line_c++] = temp;
}
line[line_c] = '\0';
line_c = 0;
if(!strcmp(mode, "-t")){
token = strtok(line, ",");
*label = atoi(token);
while(token != NULL){
token = strtok(NULL, ",");
if(token == NULL) break;
input_data[input_c++] = atoi(token);
}
}
if(!strcmp(mode, "-r")){
token = strtok(line, ",");
*label = atoi(token);
while(token != NULL){
token = strtok(NULL, ",");
if(token == NULL) break;
input_data[input_c++] = atoi(token);
}
}
}
gsl_matrix* scale_input(int input_data[])
{
gsl_matrix* better_input = gsl_matrix_alloc(DATA_NUM_WITHOUT_LABEL, 1);
for(int i = 0; i < DATA_NUM_WITHOUT_LABEL; i++){
gsl_matrix_set(better_input, i, 0, ((double)input_data[i]/255.0*0.99)+0.01);
}
return better_input;
}
gsl_matrix* vectorize_target(int label)
{
gsl_matrix* target = gsl_matrix_alloc(10, 1);
for(int i = 0; i < 10; i++){
if(i == label){
gsl_matrix_set(target, i, 0, 0.99);
}else{
gsl_matrix_set(target, i, 0, 0.01);
}
}
return target;
}
gsl_matrix* init_weight(int row, int col)
{
gsl_matrix* input_weight = gsl_matrix_alloc(row, col);
const gsl_rng_type * T;
gsl_rng * r;
double sigma = NOR_DIS_DEV(col);
r = gsl_rng_alloc (gsl_rng_mt19937);
for(int i = 0; i < row; i++){
for(int j = 0; j < col; j++){
gsl_matrix_set(input_weight, i, j, gsl_ran_gaussian(r, sigma));
}
}
gsl_rng_free(r);
return input_weight;
}
double get_output_error(gsl_matrix* target, gsl_matrix* output, gsl_matrix* output_error)
{
double error = 0.0;
for (int i = 0; i < OUTPUT_NODE; i++){
gsl_matrix_set(output_error, i, 0, (gsl_matrix_get(target, i, 0) - gsl_matrix_get(output, i, 0)));
}
for (int i = 0; i < OUTPUT_NODE; i++){
error += pow(gsl_matrix_get(output_error, i, 0), 2);
}
return error;
}
void training(gsl_matrix* better_input, gsl_matrix* target, gsl_matrix* input_weight, gsl_matrix* hidden_weight, gsl_matrix* hidden_x, gsl_matrix* hidden_o, gsl_matrix* output_o, gsl_matrix* output_x, gsl_matrix* output_error, gsl_matrix* hidden_error, double* error)
{
gsl_matrix* delta_hidden_weight = gsl_matrix_alloc(OUTPUT_NODE, HIDDEN_NODE);
gsl_matrix* delta_input_weight = gsl_matrix_alloc(HIDDEN_NODE, DATA_NUM_WITHOUT_LABEL);
gsl_matrix* temp_hidden = gsl_matrix_alloc(OUTPUT_NODE, 1);
gsl_matrix* temp_input = gsl_matrix_alloc(HIDDEN_NODE, 1);
gsl_blas_dgemm(CblasNoTrans, CblasNoTrans, 1.0, input_weight, better_input, 0.0, hidden_x); // X = W*I
for(int i = 0; i < HIDDEN_NODE; i++){
gsl_matrix_set(hidden_o, i, 0, SIGMOID(gsl_matrix_get(hidden_x, i, 0)));
}
gsl_blas_dgemm(CblasNoTrans, CblasNoTrans, 1.0, hidden_weight, hidden_o, 0.0, output_x);
for(int i = 0; i < OUTPUT_NODE; i++){
gsl_matrix_set(output_o, i, 0, SIGMOID(gsl_matrix_get(output_x, i, 0)));
}
*error = get_output_error(target, output_o, output_error);
gsl_blas_dgemm(CblasTrans, CblasNoTrans, 1.0, hidden_weight, output_error, 0.0, hidden_error); // Error hidden
for(int i = 0; i < OUTPUT_NODE; i++){
gsl_matrix_set(temp_hidden, i, 0, (LEARN_RATE * gsl_matrix_get(output_error, i, 0) * gsl_matrix_get(output_o, i, 0) * (1.0 - gsl_matrix_get(output_o, i, 0))));
}
gsl_blas_dgemm(CblasNoTrans, CblasTrans, 1.0, temp_hidden, hidden_o, 0.0, delta_hidden_weight);
for(int i = 0; i < HIDDEN_NODE; i++){
gsl_matrix_set(temp_input, i, 0, (LEARN_RATE * gsl_matrix_get(hidden_error, i, 0) * gsl_matrix_get(hidden_o, i, 0) * (1.0 - gsl_matrix_get(hidden_error, i, 0))));
}
gsl_blas_dgemm(CblasNoTrans, CblasTrans, 1.0, temp_input, better_input, 0.0, delta_input_weight);
gsl_matrix_add(hidden_weight, delta_hidden_weight);
gsl_matrix_add(input_weight, delta_input_weight);
gsl_matrix_free(delta_input_weight);
gsl_matrix_free(delta_hidden_weight);
gsl_matrix_free(temp_input);
gsl_matrix_free(temp_hidden);
}
void store_weight(gsl_matrix* input_weight, gsl_matrix* hidden_weight)
{
FILE* fp = fopen("Good_Weight", "w+");
for(int i = 0; i < HIDDEN_NODE; i++){
for(int j = 0; j < DATA_NUM_WITHOUT_LABEL; j++){
fprintf(fp, "%f,", gsl_matrix_get(input_weight, i, j));
}
}
fseek(fp, -1, SEEK_CUR);
fputc('\n', fp);
for(int i = 0; i < OUTPUT_NODE; i++){
for(int j = 0; j < HIDDEN_NODE; j++){
fprintf(fp, "%f,", gsl_matrix_get(hidden_weight, i, j));
}
}
fseek(fp, -1, SEEK_CUR);
fputc('\n', fp);
fclose(fp);
}
void load_weight(gsl_matrix* input_weight, gsl_matrix* hidden_weight)
{
FILE* fp = fopen("Good_Weight", "r");
char num_temp[20];
double array[HIDDEN_NODE*DATA_NUM_WITHOUT_LABEL];
char c;
int j = 0, k;
if(fp == NULL){
fprintf(stderr, "No Good_Weight here, Please training first\n");
exit(EXIT_FAILURE);
}
while((c = fgetc(fp)) != '\n'){
if(c == ','){
k = 0;
array[j++] = atof(num_temp);
bzero(num_temp, sizeof(num_temp));
continue;
}
num_temp[k++] = c;
}
array[j] = atof(num_temp);
j = 0;
for(int n = 0; n < HIDDEN_NODE; n++){
for(int m = 0; m < DATA_NUM_WITHOUT_LABEL; m++){
gsl_matrix_set(input_weight, n, m, array[j++]);
}
}
j = 0;
k = 0;
while((c = fgetc(fp)) != '\n'){
if(c == ','){
k = 0;
array[j++] = atof(num_temp);
bzero(num_temp, sizeof(num_temp));
continue;
}
num_temp[k++] = c;
}
array[j] = atof(num_temp);
j = 0;
for(int n = 0; n < OUTPUT_NODE; n++){
for(int m = 0; m < HIDDEN_NODE; m++){
gsl_matrix_set(hidden_weight, n, m, array[j++]);
}
}
fclose(fp);
}
int recognize(gsl_matrix* better_input, gsl_matrix* input_weight, gsl_matrix* hidden_weight, gsl_matrix* hidden_x, gsl_matrix* hidden_o, gsl_matrix* output_x, gsl_matrix* output_o)
{
size_t row, col;
gsl_blas_dgemm(CblasNoTrans, CblasNoTrans, 1.0, input_weight, better_input, 0.0, hidden_x); // X = W*I
for(int i = 0; i < HIDDEN_NODE; i++){
gsl_matrix_set(hidden_o, i, 0, SIGMOID(gsl_matrix_get(hidden_x, i, 0)));
}
gsl_blas_dgemm(CblasNoTrans, CblasNoTrans, 1.0, hidden_weight, hidden_o, 0.0, output_x);
for(int i = 0; i < OUTPUT_NODE; i++){
gsl_matrix_set(output_o, i, 0, SIGMOID(gsl_matrix_get(output_x, i, 0)));
}
gsl_matrix_max_index(output_o, &row, &col);
return (int)row;
}
| {
"alphanum_fraction": 0.6895519836,
"avg_line_length": 30.6178010471,
"ext": "c",
"hexsha": "383408d22bc1028a7d480ffe9283a15dbfaa90c2",
"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": "66a5faefb1e4d74e35cccdf6711e4b9fad48686e",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "lochuan/number_recognization",
"max_forks_repo_path": "num_r.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "66a5faefb1e4d74e35cccdf6711e4b9fad48686e",
"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": "lochuan/number_recognization",
"max_issues_repo_path": "num_r.c",
"max_line_length": 268,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "66a5faefb1e4d74e35cccdf6711e4b9fad48686e",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "lochuan/number_recognization",
"max_stars_repo_path": "num_r.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 3467,
"size": 11696
} |
/* matrix/gsl_matrix_uchar.h
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman, Brian Gough
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#ifndef __GSL_MATRIX_UCHAR_H__
#define __GSL_MATRIX_UCHAR_H__
#include <stdlib.h>
#include <gsl/gsl_types.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_check_range.h>
#include <gsl/gsl_vector_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 size1;
size_t size2;
size_t tda;
unsigned char * data;
gsl_block_uchar * block;
int owner;
} gsl_matrix_uchar;
typedef struct
{
gsl_matrix_uchar matrix;
} _gsl_matrix_uchar_view;
typedef _gsl_matrix_uchar_view gsl_matrix_uchar_view;
typedef struct
{
gsl_matrix_uchar matrix;
} _gsl_matrix_uchar_const_view;
typedef const _gsl_matrix_uchar_const_view gsl_matrix_uchar_const_view;
/* Allocation */
GSL_EXPORT
gsl_matrix_uchar *
gsl_matrix_uchar_alloc (const size_t n1, const size_t n2);
GSL_EXPORT
gsl_matrix_uchar *
gsl_matrix_uchar_calloc (const size_t n1, const size_t n2);
GSL_EXPORT
gsl_matrix_uchar *
gsl_matrix_uchar_alloc_from_block (gsl_block_uchar * b,
const size_t offset,
const size_t n1,
const size_t n2,
const size_t d2);
GSL_EXPORT
gsl_matrix_uchar *
gsl_matrix_uchar_alloc_from_matrix (gsl_matrix_uchar * m,
const size_t k1,
const size_t k2,
const size_t n1,
const size_t n2);
GSL_EXPORT
gsl_vector_uchar *
gsl_vector_uchar_alloc_row_from_matrix (gsl_matrix_uchar * m,
const size_t i);
GSL_EXPORT
gsl_vector_uchar *
gsl_vector_uchar_alloc_col_from_matrix (gsl_matrix_uchar * m,
const size_t j);
GSL_EXPORT void gsl_matrix_uchar_free (gsl_matrix_uchar * m);
/* Views */
GSL_EXPORT
_gsl_matrix_uchar_view
gsl_matrix_uchar_submatrix (gsl_matrix_uchar * m,
const size_t i, const size_t j,
const size_t n1, const size_t n2);
GSL_EXPORT
_gsl_vector_uchar_view
gsl_matrix_uchar_row (gsl_matrix_uchar * m, const size_t i);
GSL_EXPORT
_gsl_vector_uchar_view
gsl_matrix_uchar_column (gsl_matrix_uchar * m, const size_t j);
GSL_EXPORT
_gsl_vector_uchar_view
gsl_matrix_uchar_diagonal (gsl_matrix_uchar * m);
GSL_EXPORT
_gsl_vector_uchar_view
gsl_matrix_uchar_subdiagonal (gsl_matrix_uchar * m, const size_t k);
GSL_EXPORT
_gsl_vector_uchar_view
gsl_matrix_uchar_superdiagonal (gsl_matrix_uchar * m, const size_t k);
GSL_EXPORT
_gsl_matrix_uchar_view
gsl_matrix_uchar_view_array (unsigned char * base,
const size_t n1,
const size_t n2);
GSL_EXPORT
_gsl_matrix_uchar_view
gsl_matrix_uchar_view_array_with_tda (unsigned char * base,
const size_t n1,
const size_t n2,
const size_t tda);
GSL_EXPORT
_gsl_matrix_uchar_view
gsl_matrix_uchar_view_vector (gsl_vector_uchar * v,
const size_t n1,
const size_t n2);
GSL_EXPORT
_gsl_matrix_uchar_view
gsl_matrix_uchar_view_vector_with_tda (gsl_vector_uchar * v,
const size_t n1,
const size_t n2,
const size_t tda);
GSL_EXPORT
_gsl_matrix_uchar_const_view
gsl_matrix_uchar_const_submatrix (const gsl_matrix_uchar * m,
const size_t i, const size_t j,
const size_t n1, const size_t n2);
GSL_EXPORT
_gsl_vector_uchar_const_view
gsl_matrix_uchar_const_row (const gsl_matrix_uchar * m,
const size_t i);
GSL_EXPORT
_gsl_vector_uchar_const_view
gsl_matrix_uchar_const_column (const gsl_matrix_uchar * m,
const size_t j);
GSL_EXPORT
_gsl_vector_uchar_const_view
gsl_matrix_uchar_const_diagonal (const gsl_matrix_uchar * m);
GSL_EXPORT
_gsl_vector_uchar_const_view
gsl_matrix_uchar_const_subdiagonal (const gsl_matrix_uchar * m,
const size_t k);
GSL_EXPORT
_gsl_vector_uchar_const_view
gsl_matrix_uchar_const_superdiagonal (const gsl_matrix_uchar * m,
const size_t k);
GSL_EXPORT
_gsl_matrix_uchar_const_view
gsl_matrix_uchar_const_view_array (const unsigned char * base,
const size_t n1,
const size_t n2);
GSL_EXPORT
_gsl_matrix_uchar_const_view
gsl_matrix_uchar_const_view_array_with_tda (const unsigned char * base,
const size_t n1,
const size_t n2,
const size_t tda);
GSL_EXPORT
_gsl_matrix_uchar_const_view
gsl_matrix_uchar_const_view_vector (const gsl_vector_uchar * v,
const size_t n1,
const size_t n2);
GSL_EXPORT
_gsl_matrix_uchar_const_view
gsl_matrix_uchar_const_view_vector_with_tda (const gsl_vector_uchar * v,
const size_t n1,
const size_t n2,
const size_t tda);
/* Operations */
GSL_EXPORT unsigned char gsl_matrix_uchar_get(const gsl_matrix_uchar * m, const size_t i, const size_t j);
GSL_EXPORT void gsl_matrix_uchar_set(gsl_matrix_uchar * m, const size_t i, const size_t j, const unsigned char x);
GSL_EXPORT unsigned char * gsl_matrix_uchar_ptr(gsl_matrix_uchar * m, const size_t i, const size_t j);
GSL_EXPORT const unsigned char * gsl_matrix_uchar_const_ptr(const gsl_matrix_uchar * m, const size_t i, const size_t j);
GSL_EXPORT void gsl_matrix_uchar_set_zero (gsl_matrix_uchar * m);
GSL_EXPORT void gsl_matrix_uchar_set_identity (gsl_matrix_uchar * m);
GSL_EXPORT void gsl_matrix_uchar_set_all (gsl_matrix_uchar * m, unsigned char x);
GSL_EXPORT int gsl_matrix_uchar_fread (FILE * stream, gsl_matrix_uchar * m) ;
GSL_EXPORT int gsl_matrix_uchar_fwrite (FILE * stream, const gsl_matrix_uchar * m) ;
GSL_EXPORT int gsl_matrix_uchar_fscanf (FILE * stream, gsl_matrix_uchar * m);
GSL_EXPORT int gsl_matrix_uchar_fprintf (FILE * stream, const gsl_matrix_uchar * m, const char * format);
GSL_EXPORT int gsl_matrix_uchar_memcpy(gsl_matrix_uchar * dest, const gsl_matrix_uchar * src);
GSL_EXPORT int gsl_matrix_uchar_swap(gsl_matrix_uchar * m1, gsl_matrix_uchar * m2);
GSL_EXPORT int gsl_matrix_uchar_swap_rows(gsl_matrix_uchar * m, const size_t i, const size_t j);
GSL_EXPORT int gsl_matrix_uchar_swap_columns(gsl_matrix_uchar * m, const size_t i, const size_t j);
GSL_EXPORT int gsl_matrix_uchar_swap_rowcol(gsl_matrix_uchar * m, const size_t i, const size_t j);
GSL_EXPORT int gsl_matrix_uchar_transpose (gsl_matrix_uchar * m);
GSL_EXPORT int gsl_matrix_uchar_transpose_memcpy (gsl_matrix_uchar * dest, const gsl_matrix_uchar * src);
GSL_EXPORT unsigned char gsl_matrix_uchar_max (const gsl_matrix_uchar * m);
GSL_EXPORT unsigned char gsl_matrix_uchar_min (const gsl_matrix_uchar * m);
GSL_EXPORT void gsl_matrix_uchar_minmax (const gsl_matrix_uchar * m, unsigned char * min_out, unsigned char * max_out);
GSL_EXPORT void gsl_matrix_uchar_max_index (const gsl_matrix_uchar * m, size_t * imax, size_t *jmax);
GSL_EXPORT void gsl_matrix_uchar_min_index (const gsl_matrix_uchar * m, size_t * imin, size_t *jmin);
GSL_EXPORT void gsl_matrix_uchar_minmax_index (const gsl_matrix_uchar * m, size_t * imin, size_t * jmin, size_t * imax, size_t * jmax);
GSL_EXPORT int gsl_matrix_uchar_isnull (const gsl_matrix_uchar * m);
GSL_EXPORT int gsl_matrix_uchar_add (gsl_matrix_uchar * a, const gsl_matrix_uchar * b);
GSL_EXPORT int gsl_matrix_uchar_sub (gsl_matrix_uchar * a, const gsl_matrix_uchar * b);
GSL_EXPORT int gsl_matrix_uchar_mul_elements (gsl_matrix_uchar * a, const gsl_matrix_uchar * b);
GSL_EXPORT int gsl_matrix_uchar_div_elements (gsl_matrix_uchar * a, const gsl_matrix_uchar * b);
GSL_EXPORT int gsl_matrix_uchar_scale (gsl_matrix_uchar * a, const double x);
GSL_EXPORT int gsl_matrix_uchar_add_constant (gsl_matrix_uchar * a, const double x);
GSL_EXPORT int gsl_matrix_uchar_add_diagonal (gsl_matrix_uchar * a, const double x);
/***********************************************************************/
/* The functions below are obsolete */
/***********************************************************************/
GSL_EXPORT int gsl_matrix_uchar_get_row(gsl_vector_uchar * v, const gsl_matrix_uchar * m, const size_t i);
GSL_EXPORT int gsl_matrix_uchar_get_col(gsl_vector_uchar * v, const gsl_matrix_uchar * m, const size_t j);
GSL_EXPORT int gsl_matrix_uchar_set_row(gsl_matrix_uchar * m, const size_t i, const gsl_vector_uchar * v);
GSL_EXPORT int gsl_matrix_uchar_set_col(gsl_matrix_uchar * m, const size_t j, const gsl_vector_uchar * v);
/* inline functions if you are using GCC */
#ifdef HAVE_INLINE
extern inline
unsigned char
gsl_matrix_uchar_get(const gsl_matrix_uchar * m, const size_t i, const size_t j)
{
#if GSL_RANGE_CHECK
if (i >= m->size1)
{
GSL_ERROR_VAL("first index out of range", GSL_EINVAL, 0) ;
}
else if (j >= m->size2)
{
GSL_ERROR_VAL("second index out of range", GSL_EINVAL, 0) ;
}
#endif
return m->data[i * m->tda + j] ;
}
extern inline
void
gsl_matrix_uchar_set(gsl_matrix_uchar * m, const size_t i, const size_t j, const unsigned char x)
{
#if GSL_RANGE_CHECK
if (i >= m->size1)
{
GSL_ERROR_VOID("first index out of range", GSL_EINVAL) ;
}
else if (j >= m->size2)
{
GSL_ERROR_VOID("second index out of range", GSL_EINVAL) ;
}
#endif
m->data[i * m->tda + j] = x ;
}
extern inline
unsigned char *
gsl_matrix_uchar_ptr(gsl_matrix_uchar * m, const size_t i, const size_t j)
{
#if GSL_RANGE_CHECK
if (i >= m->size1)
{
GSL_ERROR_NULL("first index out of range", GSL_EINVAL) ;
}
else if (j >= m->size2)
{
GSL_ERROR_NULL("second index out of range", GSL_EINVAL) ;
}
#endif
return (unsigned char *) (m->data + (i * m->tda + j)) ;
}
extern inline
const unsigned char *
gsl_matrix_uchar_const_ptr(const gsl_matrix_uchar * m, const size_t i, const size_t j)
{
#if GSL_RANGE_CHECK
if (i >= m->size1)
{
GSL_ERROR_NULL("first index out of range", GSL_EINVAL) ;
}
else if (j >= m->size2)
{
GSL_ERROR_NULL("second index out of range", GSL_EINVAL) ;
}
#endif
return (const unsigned char *) (m->data + (i * m->tda + j)) ;
}
#endif
__END_DECLS
#endif /* __GSL_MATRIX_UCHAR_H__ */
| {
"alphanum_fraction": 0.6819225861,
"avg_line_length": 34.2711370262,
"ext": "h",
"hexsha": "6a0809c33f8f26399d0f10fb1b2792da1ad2552a",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "f6ed9b75408f7ce6100ed59b7754f745e59be152",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "dynaryu/vaws",
"max_forks_repo_path": "src/core/gsl/include/gsl/gsl_matrix_uchar.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "f6ed9b75408f7ce6100ed59b7754f745e59be152",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "dynaryu/vaws",
"max_issues_repo_path": "src/core/gsl/include/gsl/gsl_matrix_uchar.h",
"max_line_length": 135,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "f6ed9b75408f7ce6100ed59b7754f745e59be152",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "dynaryu/vaws",
"max_stars_repo_path": "src/core/gsl/include/gsl/gsl_matrix_uchar.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 2990,
"size": 11755
} |
/* Dickman's rho function (to compute probability of success of ecm).
Copyright 2004, 2005, 2006, 2008, 2009, 2010, 2011, 2012, 2013
Alexander Kruppa, Paul Zimmermann.
This file is part of the ECM Library.
The ECM Library is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 3 of the License, or (at your
option) any later version.
The ECM Library is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
License for more details.
You should have received a copy of the GNU Lesser General Public License
along with the ECM Library; see the file COPYING.LIB. If not, see
http://www.gnu.org/licenses/ or write to the Free Software Foundation, Inc.,
51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. */
/* define TESTDRIVE to compile rho as a stand-alone program, in which case
you need to have libgsl installed */
#include "config.h"
#if defined(TESTDRIVE)
#define _ISOC99_SOURCE 1
#endif
#if defined(DEBUG_NUMINTEGRATE) || defined(TESTDRIVE)
# include <stdio.h>
#endif
#include <stdlib.h>
#include <math.h>
#if defined(TESTDRIVE)
#include <string.h>
#include "primegen.h"
#endif
#if defined(TESTDRIVE)
#include <gsl/gsl_math.h>
#include <gsl/gsl_sf_expint.h>
#include <gsl/gsl_integration.h>
#endif
#include "ecm-impl.h"
/* For Suyama's curves, we have a known torsion factor of 12 = 2^2*3^1, and
an average extra exponent of 1/2 for 2, and 1/3 for 3 due to the probability
that the group order divided by 12 is divisible by 2 or 3, thus on average
we should have 2^2.5*3^1.333 ~ 24.5, however experimentally we have
2^3.323*3^1.687 ~ 63.9 (see Alexander Kruppa's thesis, Table 5.1 page 96,
row sigma=2, http://tel.archives-ouvertes.fr/tel-00477005/en/).
The exp(ECM_EXTRA_SMOOTHNESS) value takes into account the extra
smoothness with respect to a random number. */
#ifndef ECM_EXTRA_SMOOTHNESS
#define ECM_EXTRA_SMOOTHNESS 3.134
#endif
#define M_PI_SQR 9.869604401089358619 /* Pi^2 */
#define M_PI_SQR_6 1.644934066848226436 /* Pi^2/6 */
/* gsl_math.h defines M_EULER */
#ifndef M_EULER
#define M_EULER 0.577215664901532861
#endif
#define M_EULER_1 0.422784335098467139 /* 1 - Euler */
#ifndef MAX
#define MAX(x,y) ((x) > (y) ? (x) : (y))
#endif
#ifndef MIN
#define MIN(x,y) ((x) < (y) ? (x) : (y))
#endif
void rhoinit (int, int); /* used in stage2.c */
static double *rhotable = NULL;
static int invh = 0;
static double h = 0.;
static int tablemax = 0;
#if defined(TESTDRIVE)
#define PRIME_PI_MAX 10000
#define PRIME_PI_MAP(x) (((x)+1)/2)
/* The number of primes up to i. Use prime_pi[PRIME_PI_MAP(i)].
Only correct for i >= 2. */
static unsigned int prime_pi[PRIME_PI_MAP(PRIME_PI_MAX)+1];
#endif
/* Fixme: need prime generating funcion without static state variables */
const unsigned char primemap[667] = {
254, 223, 239, 126, 182, 219, 61, 249, 213, 79, 30, 243, 234, 166, 237, 158,
230, 12, 211, 211, 59, 221, 89, 165, 106, 103, 146, 189, 120, 30, 166, 86,
86, 227, 173, 45, 222, 42, 76, 85, 217, 163, 240, 159, 3, 84, 161, 248, 46,
253, 68, 233, 102, 246, 19, 58, 184, 76, 43, 58, 69, 17, 191, 84, 140, 193,
122, 179, 200, 188, 140, 79, 33, 88, 113, 113, 155, 193, 23, 239, 84, 150,
26, 8, 229, 131, 140, 70, 114, 251, 174, 101, 146, 143, 88, 135, 210, 146,
216, 129, 101, 38, 227, 160, 17, 56, 199, 38, 60, 129, 235, 153, 141, 81,
136, 62, 36, 243, 51, 77, 90, 139, 28, 167, 42, 180, 88, 76, 78, 38, 246,
25, 130, 220, 131, 195, 44, 241, 56, 2, 181, 205, 205, 2, 178, 74, 148, 12,
87, 76, 122, 48, 67, 11, 241, 203, 68, 108, 36, 248, 25, 1, 149, 168, 92,
115, 234, 141, 36, 150, 43, 80, 166, 34, 30, 196, 209, 72, 6, 212, 58, 47,
116, 156, 7, 106, 5, 136, 191, 104, 21, 46, 96, 85, 227, 183, 81, 152, 8,
20, 134, 90, 170, 69, 77, 73, 112, 39, 210, 147, 213, 202, 171, 2, 131, 97,
5, 36, 206, 135, 34, 194, 169, 173, 24, 140, 77, 120, 209, 137, 22, 176, 87,
199, 98, 162, 192, 52, 36, 82, 174, 90, 64, 50, 141, 33, 8, 67, 52, 182,
210, 182, 217, 25, 225, 96, 103, 26, 57, 96, 208, 68, 122, 148, 154, 9, 136,
131, 168, 116, 85, 16, 39, 161, 93, 104, 30, 35, 200, 50, 224, 25, 3, 68,
115, 72, 177, 56, 195, 230, 42, 87, 97, 152, 181, 28, 10, 104, 197, 129,
143, 172, 2, 41, 26, 71, 227, 148, 17, 78, 100, 46, 20, 203, 61, 220, 20,
197, 6, 16, 233, 41, 177, 130, 233, 48, 71, 227, 52, 25, 195, 37, 10, 48,
48, 180, 108, 193, 229, 70, 68, 216, 142, 76, 93, 34, 36, 112, 120, 146,
137, 129, 130, 86, 38, 27, 134, 233, 8, 165, 0, 211, 195, 41, 176, 194, 74,
16, 178, 89, 56, 161, 29, 66, 96, 199, 34, 39, 140, 200, 68, 26, 198, 139,
130, 129, 26, 70, 16, 166, 49, 9, 240, 84, 47, 24, 210, 216, 169, 21, 6, 46,
12, 246, 192, 14, 80, 145, 205, 38, 193, 24, 56, 101, 25, 195, 86, 147, 139,
42, 45, 214, 132, 74, 97, 10, 165, 44, 9, 224, 118, 196, 106, 60, 216, 8,
232, 20, 102, 27, 176, 164, 2, 99, 54, 16, 49, 7, 213, 146, 72, 66, 18, 195,
138, 160, 159, 45, 116, 164, 130, 133, 120, 92, 13, 24, 176, 97, 20, 29, 2,
232, 24, 18, 193, 1, 73, 28, 131, 48, 103, 51, 161, 136, 216, 15, 12, 244,
152, 136, 88, 215, 102, 66, 71, 177, 22, 168, 150, 8, 24, 65, 89, 21, 181,
68, 42, 82, 225, 179, 170, 161, 89, 69, 98, 85, 24, 17, 165, 12, 163, 60,
103, 0, 190, 84, 214, 10, 32, 54, 107, 130, 12, 21, 8, 126, 86, 145, 1, 120,
208, 97, 10, 132, 168, 44, 1, 87, 14, 86, 160, 80, 11, 152, 140, 71, 108,
32, 99, 16, 196, 9, 228, 12, 87, 136, 11, 117, 11, 194, 82, 130, 194, 57,
36, 2, 44, 86, 37, 122, 49, 41, 214, 163, 32, 225, 177, 24, 176, 12, 138,
50, 193, 17, 50, 9, 197, 173, 48, 55, 8, 188, 145, 130, 207, 32, 37, 107,
156, 48, 143, 68, 38, 70, 106, 7, 73, 142, 9, 88, 16, 2, 37, 197, 196, 66,
90, 128, 160, 128, 60, 144, 40, 100, 20, 225, 3, 132, 81, 12, 46, 163, 138,
164, 8, 192, 71, 126, 211, 43, 3, 205, 84, 42, 0, 4, 179, 146, 108, 66, 41,
76, 131, 193, 146, 204, 28};
#ifdef TESTDRIVE
unsigned long
gcd (unsigned long a, unsigned long b)
{
unsigned long t;
while (b != 0)
{
t = a % b;
a = b;
b = t;
}
return a;
}
unsigned long
eulerphi (unsigned long n)
{
unsigned long phi = 1, p;
for (p = 2; p * p <= n; p += 2)
{
if (n % p == 0)
{
phi *= p - 1;
n /= p;
while (n % p == 0)
{
phi *= p;
n /= p;
}
}
if (p == 2)
p--;
}
/* now n is prime */
return (n == 1) ? phi : phi * (n - 1);
}
/* The number of positive integers up to x that have no prime factor up to y,
for x >= y >= 2. Uses Buchstab's identity */
unsigned long
Buchstab_Phi(unsigned long x, unsigned long y)
{
unsigned long p, s;
primegen pg[1];
if (x < 1)
return 0;
if (x <= y)
return 1;
#if 0
if (x < y^2)
return(1 + primepi(x) - primepi (y)));
#endif
s = 1;
primegen_init (pg);
primegen_skipto (pg, y + 1);
for (p = primegen_next(pg); p <= x; p = primegen_next(pg))
s += Buchstab_Phi(x / p, p - 1);
return (s);
}
/* The number of positive integers up to x that have no prime factor
greter than y, for x >= y >= 2. Uses Buchstab's identity */
unsigned long
Buchstab_Psi(const unsigned long x, const unsigned long y)
{
unsigned long r, p;
primegen pg[1];
if (x <= y)
return (x);
if (y == 1UL)
return (1);
/* If y^2 > x, then
Psi(x,y) = x - \sum_{y < p < x, p prime} floor(x/p)
We separate the sum into ranges where floor(x/p) = k,
which is x/(k+1) < p <= x/k.
We also need to satisfy y < p, so we need k < x/y - 1,
or k_max = ceil (x/y) - 2.
The primes y < p <= x/(k_max + 1) are summed separately. */
if (x <= PRIME_PI_MAX && x < y * y)
{
unsigned long kmax = x / y - 1;
unsigned long s1, s2, k;
s1 = (kmax + 1) * (prime_pi [PRIME_PI_MAP(x / (kmax + 1))] -
prime_pi [PRIME_PI_MAP(y)]);
s2 = 0;
for (k = 1; k <= kmax; k++)
s2 += prime_pi[PRIME_PI_MAP(x / k)];
s2 -= kmax * prime_pi [PRIME_PI_MAP(x / (kmax+1))];
return (x - s1 - s2);
}
r = 1;
primegen_init (pg);
for (p = primegen_next(pg); p <= y; p = primegen_next(pg))
r += Buchstab_Psi (x / p, p);
return (r);
}
#endif /* TESTDRIVE */
#if defined(TESTDRIVE)
static double
Li (const double x)
{
return (- gsl_sf_expint_E1 (- log(x)));
}
#endif
/*
Evaluate dilogarithm via the sum
\Li_{2}(z)=\sum_{k=1}^{\infty} \frac{z^k}{k^2},
see http://mathworld.wolfram.com/Dilogarithm.html
Assumes |z| <= 0.5, for which the sum converges quickly.
*/
static double
dilog_series (const double z)
{
double r = 0.0, zk; /* zk = z^k */
int k, k2; /* k2 = k^2 */
/* Doubles have 53 bits in significand, with |z| <= 0.5 the k+1-st term
is <= 1/(2^k k^2) of the result, so 44 terms should do */
for (k = 1, k2 = 1, zk = z; k <= 44; k2 += 2 * k + 1, k++, zk *= z)
r += zk / (double) k2;
return r;
}
static double
dilog (double x)
{
ASSERT(x <= -1.0); /* dilog(1-x) is called from rhoexact for 2 < x <= 3 */
if (x <= -2.0)
return -dilog_series (1./x) - M_PI_SQR_6 - 0.5 * log(-1./x) * log(-1./x);
else /* x <= -1.0 */
{
/* L2(z) = -L2(1 - z) + 1/6 * Pi^2 - ln(1 - z)*ln(z)
L2(z) = -L2(1/z) - 1/6 * Pi^2 - 0.5*ln^2(-1/z)
->
L2(z) = -(-L2(1/(1-z)) - 1/6 * Pi^2 - 0.5*ln^2(-1/(1-z))) + 1/6 * Pi^2 - ln(1 - z)*ln(z)
= L2(1/(1-z)) - 1/6 * Pi^2 + 0.5*ln(1 - z)^2 - ln(1 - z)*ln(-z)
z in [-1, -2) -> 1/(1-z) in [1/2, 1/3)
*/
double log1x = log (1. - x);
return dilog_series (1. / (1. - x))
- M_PI_SQR_6 + log1x * (0.5 * log1x - log (-x));
}
}
#if 0
static double
L2 (double x)
{
return log (x) * (1 - log (x-1)) + M_PI_SQR_6 - dilog (1 - x);
}
#endif
static double
rhoexact (double x)
{
ASSERT(x <= 3.);
if (x <= 0.)
return 0.;
else if (x <= 1.)
return 1.;
else if (x <= 2.)
return 1. - log (x);
else /* 2 < x <= 3 thus -2 <= 1-x < -1 */
return 1. - log (x) * (1. - log (x - 1.)) + dilog (1. - x) + 0.5 * M_PI_SQR_6;
}
#if defined(TESTDRIVE)
/* The Buchstab omega(x) function, exact for x <= 4 where it can be
evaluated without numerical integration, and approximated by
exp(gamma) for larger x. */
static double
Buchstab_omega (const double x)
{
/* magic = dilog(-1) + 1 = Pi^2/12 + 1 */
const double magic = 1.82246703342411321824;
if (x < 1.) return (0.);
if (x <= 2.) return (1. / x);
if (x <= 3.) return ((log (x - 1.) + 1.) / x);
if (x <= 4.)
return ((dilog(2. - x) + (1. + log(x - 2.)) * log(x - 1.) + magic) / x);
/* If argument is out of range, return the limiting value for
$x->\infty$: e^-gamma.
For x only a little larger than 4., this has relative error 2.2e-6,
for larger x the error rapidly drops further */
return 0.56145948356688516982;
}
#endif
void
rhoinit (int parm_invh, int parm_tablemax)
{
int i;
if (parm_invh == invh && parm_tablemax == tablemax)
return;
if (rhotable != NULL)
{
free (rhotable);
rhotable = NULL;
invh = 0;
h = 0.;
tablemax = 0;
}
/* The integration below expects 3 * invh > 4 */
if (parm_tablemax == 0 || parm_invh < 2)
return;
invh = parm_invh;
h = 1. / (double) invh;
tablemax = parm_tablemax;
rhotable = (double *) malloc (parm_invh * parm_tablemax * sizeof (double));
ASSERT_ALWAYS(rhotable != NULL);
for (i = 0; i < (3 < parm_tablemax ? 3 : parm_tablemax) * invh; i++)
rhotable[i] = rhoexact (i * h);
for (i = 3 * invh; i < parm_tablemax * invh; i++)
{
/* rho(i*h) = 1 - \int_{1}^{i*h} rho(x-1)/x dx
= rho((i-4)*h) - \int_{(i-4)*h}^{i*h} rho(x-1)/x dx */
rhotable[i] = rhotable[i - 4] - 2. / 45. * (
7. * rhotable[i - invh - 4] / (double)(i - 4)
+ 32. * rhotable[i - invh - 3] / (double)(i - 3)
+ 12. * rhotable[i - invh - 2] / (double)(i - 2)
+ 32. * rhotable[i - invh - 1] / (double)(i - 1)
+ 7. * rhotable[i - invh] / (double)i );
if (rhotable[i] < 0.)
{
#ifndef DEBUG_NUMINTEGRATE
rhotable[i] = 0.;
#else
printf (stderr, "rhoinit: rhotable[%d] = %.16f\n", i,
rhotable[i]);
exit (EXIT_FAILURE);
#endif
}
}
}
/* assumes alpha < tablemax */
static double
dickmanrho (double alpha)
{
ASSERT(alpha < tablemax);
if (alpha <= 3.)
return rhoexact (alpha);
{
int a = floor (alpha * invh);
double rho1 = rhotable[a];
double rho2 = (a + 1) < tablemax * invh ? rhotable[a + 1] : 0;
return rho1 + (rho2 - rho1) * (alpha * invh - (double) a);
}
}
#if 0
static double
dickmanrhosigma (double alpha, double x)
{
if (alpha <= 0.)
return 0.;
if (alpha <= 1.)
return 1.;
if (alpha < tablemax)
return dickmanrho (alpha) + M_EULER_1 * dickmanrho (alpha - 1.) / log (x);
return 0.;
}
static double
dickmanrhosigma_i (int ai, double x)
{
if (ai <= 0)
return 0.;
if (ai <= invh)
return 1.;
if (ai < tablemax * invh)
return rhotable[ai] - M_EULER * rhotable[ai - invh] / log(x);
return 0.;
}
#endif
static double
dickmanlocal (double alpha, double x)
{
if (alpha <= 1.)
return rhoexact (alpha);
if (alpha < tablemax)
return dickmanrho (alpha) - M_EULER * dickmanrho (alpha - 1.) / log (x);
return 0.;
}
static double
dickmanlocal_i (int ai, double x)
{
if (ai <= 0)
return 0.;
if (ai <= invh)
return 1.;
if (ai <= 2 * invh && ai < tablemax * invh)
return rhotable[ai] - M_EULER / log (x);
if (ai < tablemax * invh)
{
double logx = log (x);
return rhotable[ai] - (M_EULER * rhotable[ai - invh]
+ M_EULER_1 * rhotable[ai - 2 * invh] / logx) / logx;
}
return 0.;
}
static int
isprime(unsigned long n)
{
unsigned int r;
if (n % 2 == 0)
return (n == 2);
if (n % 3 == 0)
return (n == 3);
if (n % 5 == 0)
return (n == 5);
if (n / 30 >= sizeof (primemap))
abort();
r = n % 30; /* 8 possible values: 1,7,11,13,17,19,23,29 */
r = (r * 16 + r) / 64; /* maps the 8 values onto 0, ..., 7 */
return ((primemap[n / 30] & (1 << r)) != 0);
}
static double
dickmanmu_sum (const unsigned long B1, const unsigned long B2,
const double x)
{
double s = 0.;
const double logB1 = 1. / log(B1);
const double logx = log(x);
unsigned long p;
for (p = B1 + 1; p <= B2; p++)
if (isprime(p))
s += dickmanlocal ((logx - log(p)) * logB1, x / p) / p;
return (s);
}
static double
dickmanmu (double alpha, double beta, double x)
{
double a, b, sum;
int ai, bi, i;
ai = ceil ((alpha - beta) * invh);
if (ai > tablemax * invh)
ai = tablemax * invh;
a = (double) ai * h;
bi = floor ((alpha - 1.) * invh);
if (bi > tablemax * invh)
bi = tablemax * invh;
b = (double) bi * h;
sum = 0.;
for (i = ai + 1; i < bi; i++)
sum += dickmanlocal_i (i, x) / (alpha - i * h);
sum += 0.5 * dickmanlocal_i (ai, x) / (alpha - a);
sum += 0.5 * dickmanlocal_i (bi, x) / (alpha - b);
sum *= h;
sum += (a - alpha + beta) * 0.5 * (dickmanlocal_i (ai, x) / (alpha - a) + dickmanlocal (alpha - beta, x) / beta);
sum += (alpha - 1. - b) * 0.5 * (dickmanlocal (alpha - 1., x) + dickmanlocal_i (bi, x) / (alpha - b));
return sum;
}
static double
brentsuyama (double B1, double B2, double N, double nr)
{
double a, alpha, beta, sum;
int ai, i;
alpha = log (N) / log (B1);
beta = log (B2) / log (B1);
ai = floor ((alpha - beta) * invh);
if (ai > tablemax * invh)
ai = tablemax * invh;
a = (double) ai * h;
sum = 0.;
for (i = 1; i < ai; i++)
sum += dickmanlocal_i (i, N) / (alpha - i * h) * (1 - exp (-nr * pow (B1, (-alpha + i * h))));
sum += 0.5 * (1 - exp(-nr / pow (B1, alpha)));
sum += 0.5 * dickmanlocal_i (ai, N) / (alpha - a) * (1 - exp(-nr * pow (B1, (-alpha + a))));
sum *= h;
sum += 0.5 * (alpha - beta - a) * (dickmanlocal_i (ai, N) / (alpha - a) + dickmanlocal (alpha - beta, N) / beta);
return sum;
}
static double
brsudickson (double B1, double B2, double N, double nr, int S)
{
int i, f;
double sum;
sum = 0;
f = eulerphi (S) / 2;
for (i = 1; i <= S / 2; i++)
if (gcd (i, S) == 1)
sum += brentsuyama (B1, B2, N, nr * (gcd (i - 1, S) + gcd (i + 1, S) - 4) / 2);
return sum / (double)f;
}
static double
brsupower (double B1, double B2, double N, double nr, int S)
{
int i, f;
double sum;
sum = 0;
f = eulerphi (S);
for (i = 1; i < S; i++)
if (gcd (i, S) == 1)
sum += brentsuyama (B1, B2, N, nr * (gcd (i - 1, S) - 2));
return sum / (double)f;
}
/* Assume N is as likely smooth as a number around N/exp(delta) */
static double
prob (double B1, double B2, double N, double nr, int S, double delta)
{
const double sumthresh = 20000.;
double alpha, beta, stage1, stage2, brsu;
const double effN = N / exp (delta);
ASSERT(rhotable != NULL);
/* What to do if rhotable is not initialised and asserting is not enabled?
For now, bail out with 0. result. Not really pretty, either */
if (rhotable == NULL)
return 0.;
if (B1 < 2. || N <= 1.)
return 0.;
if (effN <= B1)
return 1.;
#ifdef TESTDRIVE
printf ("B1 = %f, B2 = %f, N = %.0f, nr = %f, S = %d\n", B1, B2, N, nr, S);
#endif
alpha = log (effN) / log (B1);
stage1 = dickmanlocal (alpha, effN);
stage2 = 0.;
if (B2 > B1)
{
if (B1 < sumthresh)
{
stage2 += dickmanmu_sum (B1, MIN(B2, sumthresh), effN);
beta = log (B2) / log (MIN(B2, sumthresh));
}
else
beta = log (B2) / log (B1);
if (beta > 1.)
stage2 += dickmanmu (alpha, beta, effN);
}
brsu = 0.;
if (S < -1)
brsu = brsudickson (B1, B2, effN, nr, -S * 2);
if (S > 1)
brsu = brsupower (B1, B2, effN, nr, S * 2);
#ifdef TESTDRIVE
printf ("stage 1 : %f, stage 2 : %f, Brent-Suyama : %f\n", stage1, stage2, brsu);
#endif
return (stage1 + stage2 + brsu) > 0. ? (stage1 + stage2 + brsu) : 0.;
}
double
ecmprob (double B1, double B2, double N, double nr, int S)
{
return prob (B1, B2, N, nr, S, ECM_EXTRA_SMOOTHNESS);
}
double
pm1prob (double B1, double B2, double N, double nr, int S, const mpz_t go)
{
mpz_t cof;
/* A prime power q^k divides p-1, p prime, with probability 1/(q^k-q^(k-1))
not with probability 1/q^k as for random numbers. This is taken into
account by the "smoothness" value here; a prime p-1 is about as likely
smooth as a random number around (p-1)/exp(smoothness).
smoothness = \sum_{q in Primes} log(q)/(q-1)^2 */
double smoothness = 1.2269688;
unsigned long i;
if (go != NULL && mpz_cmp_ui (go, 1UL) > 0)
{
mpz_init (cof);
mpz_set (cof, go);
for (i = 2; i < 100; i++)
if (mpz_divisible_ui_p (cof, i))
{
/* If we know that q divides p-1 with probability 1, we need to
adjust the smoothness parameter */
smoothness -= log ((double) i) / (double) ((i-1)*(i-1));
/* printf ("pm1prob: Dividing out %lu\n", i); */
while (mpz_divisible_ui_p (cof, i))
mpz_tdiv_q_ui (cof, cof, i);
}
/* printf ("pm1prob: smoothness after dividing out go primes < 100: %f\n",
smoothness); */
return prob (B1, B2, N, nr, S, smoothness + log(mpz_get_d (cof)));
mpz_clear (cof);
}
return prob (B1, B2, N, nr, S, smoothness);
}
#if defined(TESTDRIVE)
/* Compute probability for primes p == r (mod m) */
static double
pm1prob_rm (double B1, double B2, double N, double nr, int S, unsigned long r,
unsigned long m)
{
unsigned long cof;
double smoothness = 1.2269688;
unsigned long p;
cof = m;
for (p = 2UL; p < 100UL; p++)
if (cof % p == 0UL) /* For each prime in m */
{
unsigned long cof_r, k, i;
/* Divisibility by i is determined by r and m. We need to
adjust the smoothness parameter. In P-1, we had estimated the
expected value for the exponent of p as p/(p-1)^2. Undo that. */
smoothness -= (double)p / ((p-1)*(p-1)) * log ((double) p);
/* The expected value for the exponent of this prime is k s.t.
p^k || r, plus 1/(p-1) if p^k || m as well */
cof_r = gcd (r - 1UL, m);
for (k = 0UL; cof_r % p == 0UL; k++)
cof_r /= p;
smoothness += k * log ((double) p);
cof_r = m;
for (i = 0UL; cof_r % p == 0UL; i++)
cof_r /= p;
if (i == k)
smoothness += (1./(p - 1.) * log ((double) p));
while (cof % p == 0UL)
cof /= p;
printf ("pm1prob_rm: p = %lu, k = %lu, i = %lu, new smoothness = %f\n",
p, i, k, smoothness);
}
return prob (B1, B2, N, nr, S, smoothness);
}
/* The \Phi(x,y) function gives the number of natural numbers <= x
that have no prime factor <= y, see Tenenbaum,
"Introduction the analytical and probabilistic number theory", III.6.
This function estimates the \Phi(x,y) function via eq. (48) of the 1st
edition resp. equation (6.49) of the 3rd edition of Tenenbaum's book. */
static double
integrand1 (double x, double *y)
{
return pow (*y, x) / x * log(x-1.);
}
static double
integrand2 (double v, double *y)
{
return Buchstab_omega (v) * pow (*y, v);
}
/* Return approximate number of integers n with x1 < n <= x2
that have no prime factor <= y */
double
no_small_prime (double x1, double x2, double y)
{
double u1, u2;
ASSERT (x1 >= 2.);
ASSERT (x2 >= x1);
ASSERT (y >= 2.);
if (x1 == x2 || x2 <= y)
return 0.;
if (x1 < y)
x1 = y;
u1 = log(x1)/log(y);
u2 = log(x2)/log(y);
/* If no prime factors <= sqrt(x2), numbers must be a primes > y */
if (x2 <= y*y)
return (Li(x2) - Li(x1));
if (u2 <= 3)
{
double r, abserr;
size_t neval;
gsl_function f;
f.function = (double (*) (double, void *)) &integrand1;
f.params = &y;
/* intnum(v=1,u,buchstab(v)*y^v) */
/* First part: intnum(v=u1, u, y^v/v*log(v-1.)) */
gsl_integration_qng (&f, MAX(u1, 2.) , u2, 0., 0.001, &r, &abserr, &neval);
/* Second part: intnum(v=u1, u2, y^v/v) = Li(x2) - Li(x1) */
r += Li (x2) - Li (x1);
return r;
}
{
double r, abserr;
size_t neval;
gsl_function f;
f.function = (double (*) (double, void *)) &integrand2;
f.params = &y;
gsl_integration_qng (&f, u1, u2, 0., 0.001, &r, &abserr, &neval);
return r;
}
}
static double
integrand3 (double p, double *param)
{
const double x1 = param[0];
const double x2 = param[1];
const double y = param[2];
return no_small_prime (x1 / p, x2 / p, y) / log(p);
}
double
no_small_prime_factor (const double x1, const double x2, const double y,
const double z1, const double z2)
{
double r, abserr, param[3];
size_t neval;
gsl_function f;
param[0] = x1;
param[1] = x2;
param[2] = y;
f.function = (double (*) (double, void *)) &integrand3;
f.params = ¶m;
gsl_integration_qng (&f, z1, z2, 0., 0.01, &r, &abserr, &neval);
return r;
}
#endif
#ifdef TESTDRIVE
int
main (int argc, char **argv)
{
double B1, B2, N, nr, r, m;
int S;
unsigned long p, i, pi;
primegen pg[1];
primegen_init (pg);
i = pi = 0;
for (p = primegen_next (pg); p <= PRIME_PI_MAX; p = primegen_next (pg))
{
for ( ; i < p; i++)
prime_pi[PRIME_PI_MAP(i)] = pi;
pi++;
}
for ( ; i < p; i++)
prime_pi[PRIME_PI_MAP(i)] = pi;
if (argc < 2)
{
printf ("Usage: rho <B1> <B2> <N> <nr> <S> [<r> <m>]\n");
return 1;
}
if (strcmp (argv[1], "-Buchstab_Phi") == 0)
{
unsigned long x, y, r;
if (argc < 4)
{
printf ("-Buchstab_Phi needs x and y paramters\n");
exit (EXIT_FAILURE);
}
x = strtoul (argv[2], NULL, 10);
y = strtoul (argv[3], NULL, 10);
r = Buchstab_Phi (x, y);
printf ("Buchstab_Phi (%lu, %lu) = %lu\n", x, y, r);
exit (EXIT_SUCCESS);
}
else if (strcmp (argv[1], "-Buchstab_Psi") == 0)
{
unsigned long x, y, r;
if (argc < 4)
{
printf ("-Buchstab_Psi needs x and y paramters\n");
exit (EXIT_FAILURE);
}
x = strtoul (argv[2], NULL, 10);
y = strtoul (argv[3], NULL, 10);
r = Buchstab_Psi (x, y);
printf ("Buchstab_Psi (%lu, %lu) = %lu\n", x, y, r);
exit (EXIT_SUCCESS);
}
else if (strcmp (argv[1], "-nsp") == 0)
{
double x1, x2, y, r;
if (argc < 5)
{
printf ("-nsp needs x1, x2, and y paramters\n");
exit (EXIT_FAILURE);
}
x1 = atof (argv[2]);
x2 = atof (argv[3]);
y = atof (argv[4]);
r = no_small_prime (x1, x2, y);
printf ("no_small_prime(%f, %f, %f) = %f\n", x1, x2, y, r);
exit (EXIT_SUCCESS);
}
else if (strcmp (argv[1], "-nspf") == 0)
{
double x1, x2, y, z1, z2, r;
if (argc < 7)
{
printf ("-nspf needs x1, x2, y, z1, and z2 paramters\n");
exit (EXIT_FAILURE);
}
x1 = atof (argv[2]);
x2 = atof (argv[3]);
y = atof (argv[4]);
z1 = atof (argv[5]);
z2 = atof (argv[6]);
r = no_small_prime_factor (x1, x2, y, z1, z2);
printf ("no_small_prime(%f, %f, %f, %f, %f) = %f\n", x1, x2, y, z1, z2, r);
exit (EXIT_SUCCESS);
}
if (argc < 6)
{
printf ("Need 5 or 7 arguments: B1 B2 N nr S [r m]\n");
exit (EXIT_FAILURE);
}
B1 = atof (argv[1]);
B2 = atof (argv[2]);
N = atof (argv[3]);
nr = atof (argv[4]);
S = atoi (argv[5]);
r = 0; m = 1;
if (argc > 7)
{
r = atoi (argv[6]);
m = atoi (argv[7]);
}
rhoinit (256, 10);
if (N < 50.)
{
double sum;
sum = ecmprob(B1, B2, exp2 (N), nr, S);
sum += 4. * ecmprob(B1, B2, 3./2. * exp2 (N), nr, S);
sum += ecmprob(B1, B2, 2. * exp2 (N), nr, S);
sum *= 1./6.;
printf ("ECM: %.16f\n", sum);
sum = pm1prob_rm (B1, B2, exp2 (N), nr, S, r, m);
sum += 4. * pm1prob_rm (B1, B2, 3./2. * exp2 (N), nr, S, r, m);
sum += pm1prob_rm (B1, B2, 2. * exp2 (N), nr, S, r, m);
sum *= 1./6.;
printf ("P-1: %.16f\n", sum);
}
else
{
printf ("ECM: %.16f\n", ecmprob(B1, B2, N, nr, S));
printf ("P-1: %.16f\n", pm1prob_rm (B1, B2, N, nr, S, r, m));
}
rhoinit (0, 0);
return 0;
}
#endif
| {
"alphanum_fraction": 0.5436487193,
"avg_line_length": 27.5534979424,
"ext": "c",
"hexsha": "e32ee2bef9658da79835b389d14fd1deb28f348b",
"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": "b28c7b1e5f15a74fd62774da2b93aac225e38f57",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "beninato8/ctfs",
"max_forks_repo_path": "picoctf/EasyRsa/gmp-ecm/rho.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "b28c7b1e5f15a74fd62774da2b93aac225e38f57",
"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": "beninato8/ctfs",
"max_issues_repo_path": "picoctf/EasyRsa/gmp-ecm/rho.c",
"max_line_length": 115,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "b28c7b1e5f15a74fd62774da2b93aac225e38f57",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "beninato8/ctfs",
"max_stars_repo_path": "picoctf/EasyRsa/gmp-ecm/rho.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 10628,
"size": 26782
} |
/** @file matrix3d.c
* @author T J Atherton
*
* @brief Matrix math for 3d graphics
*/
#include "matrix3d.h"
#include <math.h>
#include <string.h>
/** Use Apple's Accelerate library for LAPACK and BLAS */
#ifdef __APPLE__
#include <Accelerate/Accelerate.h>
#else
#include <cblas.h>
#include <lapacke.h>
#define USE_LAPACKE
#endif
#define EPS 1e-16
/** @brief Normalizes a vector
* @param[in] in - input vector
* @param[out] out - output vector. */
void mat3d_vectornormalize(vec3 in, vec3 out) {
float norm=cblas_snrm2(3, in, 1);
if (norm>EPS) norm = 1.0/norm;
if (out!=in) cblas_scopy(3, in, 1, out, 1);
cblas_sscal(3, norm, out, 1);
}
/** @brief Stores the identity matrix in out.
* @param[out] out - output matrix. */
void mat3d_identity4x4(mat4x4 out) {
static float ident[] = { 1.0f, 0.0f, 0.0f, 0.0f,
0.0f, 1.0f, 0.0f, 0.0f,
0.0f, 0.0f, 1.0f, 0.0f,
0.0f, 0.0f, 0.0f, 1.0f };
cblas_scopy(16, ident, 1, out, 1);
}
/** @brief Stores the identity matrix in out.
* @param[out] out - output matrix. */
void mat3d_identity3x3(mat4x4 out) {
static float ident[] = { 1.0f, 0.0f, 0.0f,
0.0f, 1.0f, 0.0f,
0.0f, 0.0f, 1.0f };
cblas_scopy(9, ident, 1, out, 1);
}
/** @brief Multiply out = a*b
* @param[in] a input matrix
* @param[in] b input matrix
* @param[out] out filled with a*b
* @warning: out must be distinct from a and b */
void mat3d_mul4x4(mat4x4 a, mat4x4 b, mat4x4 out) {
cblas_sgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, 4, 4, 4, 1.0, a, 4, b, 4, 0.0, out, 4);
}
/** @brief Multiply: out = a*b
* @param[in] a input matrix
* @param[in] b input matrix
* @param[out] out filled with a*b
* @warning: out must be distinct from a and b */
void mat3d_mul3x3(mat3x3 a, mat3x3 b, mat3x3 out) {
cblas_sgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, 3, 3, 3, 1.0, a, 3, b, 3, 0.0, out, 3);
}
/** @brief Add with scale: out = a + alpha*b
* @param[in] a input matrix
* @param[in] b input matrix
* @param[out] out filled with a + alpha*b */
void mat3d_addscale3x3(mat3x3 a, float alpha, mat3x3 b, mat3x3 out) {
if (a!=out) cblas_scopy(9, a, 1, out, 1);
cblas_saxpy(9, alpha, b, 1, out, 1);
}
/** @brief Copy: out = a
* @param[in] a input matrix
* @param[out] out filled with a*b */
void mat3d_copy4x4(mat4x4 a, mat4x4 out) {
cblas_scopy(16, a, 1, out, 1);
}
/** @brief Matrix inversion
* @param[in] a input matrix
* @param[out] out filled with inverse(a) */
void mat3d_invert4x4(mat4x4 a, mat4x4 out) {
int m = 4, n = 4;
int piv[4];
int info;
/* Copy a into out */
memcpy(out, a, sizeof(float)*16);
/* Compute LU decomposition, storing result in place */
#ifdef USE_LAPACKE
info = LAPACKE_sgetrf(LAPACK_COL_MAJOR, m, n, out, m, piv);
#else
sgetrf_(&m, &n, out, &m, piv, &info);
#endif
if (!info) {
/* Now compute inverse */
#ifdef USE_LAPACKE
info=LAPACKE_sgetri(LAPACK_COL_MAJOR, n, out, n, piv);
#else
float work[16];
int lwork=16;
sgetri_(&n, out, &n, piv, work, &lwork, &info);
#endif
}
}
/** @brief Convert a 3x3 matrix to a 4x4 matrix
* @param[in] in input matrix
* @param[out] out filled with inverse(a) */
void mat3d_lift(mat3x3 in, mat4x4 out) {
mat4x4 new = { in[0], in[1], in[2], 0.0f, // Col major order!
in[3], in[4], in[5], 0.0f,
in[6], in[7], in[8], 0.0f,
0.0f, 0.0f, 0.0f, 1.0f };
cblas_scopy(16, new, 1, out, 1);
}
/** @brief Print a 3x3 matrix */
void mat3d_print3x3(mat3x3 in) {
for (unsigned int j=0; j<3; j++) { // row
printf("[ ");
for (unsigned int i=0; i<3; i++) { // column
printf("%g ", in[i*3+j]);
}
printf("]\n");
}
}
/** @brief Print a 3x3 matrix */
void mat3d_print4x4(mat4x4 in) {
for (unsigned int j=0; j<4; j++) { // row
printf("[ ");
for (unsigned int i=0; i<4; i++) { // column
printf("%g ", in[i*4+j]);
}
printf("]\n");
}
}
/** @brief Translate by a vector
* @param[in] in input matrix
* @param[in] vec translation vector
* @param[out] out on output, contains T*in where T is the translation matrix computed from vec */
void mat3d_translate(mat4x4 in, vec3 vec, mat4x4 out) {
mat4x4 tr = { 1.0f, 0.0f, 0.0f, 0.0f, // Col major order!
0.0f, 1.0f, 0.0f, 0.0f,
0.0f, 0.0f, 1.0f, 0.0f,
vec[0], vec[1], vec[2], 1.0f };
mat4x4 in2;
if (in==out) mat3d_copy4x4(in, in2); /* Use a copy if in and out are the same matrix */
if (in) mat3d_mul4x4(tr, (in==out ? in2 : in), out);
else mat3d_copy4x4(tr, out);
}
/** @brief Scale by a factor
* @param[in] in input matrix
* @param[in] scale scale factor
* @param[out] out on output, contains T*in where T is the translation matrix computed from vec */
void mat3d_scale(mat4x4 in, float scale, mat4x4 out) {
mat4x4 tr = { scale, 0.0f, 0.0f, 0.0f, // Col major order!
0.0f, scale, 0.0f, 0.0f,
0.0f, 0.0f, scale, 0.0f,
0.0f, 0.0f, 0.0f, 1.0f };
mat4x4 in2;
if (in==out) mat3d_copy4x4(in, in2); /* Use a copy if in and out are the same matrix */
if (in) mat3d_mul4x4(tr, (in==out ? in2 : in), out);
else mat3d_copy4x4(tr, out);
}
/** @brief Rotate by angle around an axis
* @param[in] in input matrix
* @param[in] axis rotation axis
* @param[in] angle rotation angle
* @param[out] out on output, contains R*in where R is the translation matrix computed from vec */
void mat3d_rotate(mat4x4 in, vec3 axis, float angle, mat4x4 out) {
vec3 u;
mat3x3 rot;
mat4x4 rot4;
mat4x4 in2;
if (in==out) mat3d_copy4x4(in, in2); /* Use a copy if in and out are the same matrix */
/* Construct rotation matrix from Rodrigues formula */
mat3d_vectornormalize(axis, u);
mat3x3 w = { 0.0f, u[2], -u[1], // Col major order
-u[2], 0.0f, u[0],
u[1], -u[0], 0.0f };
mat3x3 w2;
/* Rodrigues formula: R = I + sin(a) W + 2 sin(a/2)^2 W^2 */
mat3d_identity3x3(rot);
mat3d_addscale3x3(rot, sin(angle), w, rot);
mat3d_mul3x3(w, w, w2);
float phi = sin(angle/2);
mat3d_addscale3x3(rot, 2*phi*phi, w2, rot);
/* Convert to 4x4 matrix */
mat3d_lift(rot, rot4);
/* Multiply the input matrix by this */
if (in) mat3d_mul4x4(rot4, (in==out ? in2 : in), out);
else mat3d_copy4x4(rot4, out);
}
/** @brief Orthographic projection matrix
* @param[in] in input matrix
* @param[in] left } Bounds of the viewing area
* @param[in] right }
* @param[in] bottom }
* @param[in] top }
* @param[in] near }
* @param[in] far }
* @param[out] out on output, contains R*in where R is the translation matrix computed from vec */
void mat3d_ortho(mat4x4 in, mat4x4 out, float left, float right, float bottom, float top, float near, float far) {
mat4x4 pr = { 2.0f/(right-left), 0.0f, 0.0f, 0.0f, // Col major order!
0.0f, 2.0f/(top-bottom), 0.0f, 0.0f,
0.0f, 0.0f, -2.0f/(far-near), 0.0f,
0.0f, 0.0f, 0.0f, 1.0f };
mat4x4 in2;
if (in==out) mat3d_copy4x4(in, in2); /* Use a copy if in and out are the same matrix */
/* Multiply the input matrix by this */
if (in) mat3d_mul4x4(pr, (in==out ? in2 : in), out);
else mat3d_copy4x4(pr, out);
}
/** @brief Perspective projection matrix
* @param[in] in input matrix
* @param[in] left } Bounds of the viewing area
* @param[in] right }
* @param[in] bottom }
* @param[in] top }
* @param[in] near }
* @param[in] far }
* @param[out] out on output, contains R*in where R is the translation matrix computed from vec */
void mat3d_frustum(mat4x4 in, mat4x4 out, float left, float right, float bottom, float top, float near, float far) {
mat4x4 pr = { 2*near/(right-left), 0.0f, 0.0f, 0.0f, // Col major order!
0.0f, 2*near/(top-bottom), 0.0f, 0.0f,
(right+left)/(right-left), (top+bottom)/(top-bottom), -(far+near)/(far-near), -1.0f,
0.0f, 0.0f, -2*far*near/(far-near), 0.0f };
mat4x4 in2;
if (in==out) mat3d_copy4x4(in, in2); /* Use a copy if in and out are the same matrix */
/* Multiply the input matrix by this */
if (in) mat3d_mul4x4(pr, (in==out ? in2 : in), out);
else mat3d_copy4x4(pr, out);
}
| {
"alphanum_fraction": 0.5785972692,
"avg_line_length": 33.8695652174,
"ext": "c",
"hexsha": "3f555cf409690def174c0c3f4e3dd1401f913610",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2021-10-31T19:55:27.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-10-05T16:56:16.000Z",
"max_forks_repo_head_hexsha": "50bb935653c0675b81e9f2d78573cf117971a147",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "mattsep/morpho",
"max_forks_repo_path": "morphoview/matrix3d.c",
"max_issues_count": 79,
"max_issues_repo_head_hexsha": "50bb935653c0675b81e9f2d78573cf117971a147",
"max_issues_repo_issues_event_max_datetime": "2022-03-31T16:06:10.000Z",
"max_issues_repo_issues_event_min_datetime": "2021-10-05T17:33:19.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "mattsep/morpho",
"max_issues_repo_path": "morphoview/matrix3d.c",
"max_line_length": 116,
"max_stars_count": 10,
"max_stars_repo_head_hexsha": "50bb935653c0675b81e9f2d78573cf117971a147",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "mattsep/morpho",
"max_stars_repo_path": "morphoview/matrix3d.c",
"max_stars_repo_stars_event_max_datetime": "2022-03-26T11:41:50.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-09-18T14:44:14.000Z",
"num_tokens": 3174,
"size": 8569
} |
#ifndef H_LASER_DATA_INLINE
#define H_LASER_DATA_INLINE
//#include <gsl/gsl_math.h>
//#include <gsl/gsl_vector.h>
#include <limits>
//#include "csm.h"
/* Simple inline functions */
/*#warning Seen ld_valid_ray*/
INLINE int ld_valid_ray(LDP ld, int i) { return (i >= 0) && (i < ld->nrays) && (ld->valid[i]); }
INLINE int ld_valid_alpha(LDP ld, int i) { return ld->alpha_valid[i] != 0; }
INLINE void ld_set_null_correspondence(LDP ld, int i) {
ld->corr[i].valid = 0;
ld->corr[i].j1 = -1;
ld->corr[i].j2 = -1;
ld->corr[i].dist2_j1 = std::numeric_limits<double>::quiet_NaN(); // GSL_NAN;
}
INLINE void ld_set_correspondence(LDP ld, int i, int j1, int j2) {
ld->corr[i].valid = 1;
ld->corr[i].j1 = j1;
ld->corr[i].j2 = j2;
}
/** -1 if not found */
INLINE int ld_next_valid(LDP ld, int i, int dir) {
int j;
for (j = i + dir; (j < ld->nrays) && (j >= 0) && !ld_valid_ray(ld, j); j += dir)
;
return ld_valid_ray(ld, j) ? j : -1;
}
INLINE int ld_next_valid_up(LDP ld, int i) { return ld_next_valid(ld, i, +1); }
INLINE int ld_next_valid_down(LDP ld, int i) { return ld_next_valid(ld, i, -1); }
INLINE int ld_valid_corr(LDP ld, int i) { return ld->corr[i].valid; }
#endif
| {
"alphanum_fraction": 0.6361365529,
"avg_line_length": 25.5531914894,
"ext": "h",
"hexsha": "20384def0e35a5b2919a86964d82c1d9035d8185",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2022-02-14T01:59:48.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-09-23T06:35:49.000Z",
"max_forks_repo_head_hexsha": "0b84e90ad3582a7d303bfc2e4c3ed198c780bf0b",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "smallsunsun1/imu_veh_calib",
"max_forks_repo_path": "include/csm/laser_data_inline.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "0b84e90ad3582a7d303bfc2e4c3ed198c780bf0b",
"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": "smallsunsun1/imu_veh_calib",
"max_issues_repo_path": "include/csm/laser_data_inline.h",
"max_line_length": 96,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "0b84e90ad3582a7d303bfc2e4c3ed198c780bf0b",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "smallsunsun1/imu_veh_calib",
"max_stars_repo_path": "include/csm/laser_data_inline.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 418,
"size": 1201
} |
#pragma once
#include <gsl/gsl>
#include <iostream>
#include "General.h"
#include "HyperionUtils/Concepts.h"
#include "Random.h"
namespace hyperion::math {
using gsl::narrow_cast;
using utils::concepts::SignedNumeric, utils::concepts::Integral,
utils::concepts::SignedIntegral, utils::concepts::FloatingPoint;
enum class Vec3Idx : size_t
{
X = 0ULL,
Y,
Z
};
template<SignedNumeric T = float>
class Vec3 {
public:
/// @brief Creates a default `Vec3`
constexpr Vec3() noexcept = default;
/// @brief Creates a new `Vec3` with the given x, y, and z components
///
/// @param x - The x component
/// @param y - The y component
/// @param z - The z component
constexpr Vec3(T x, T y, T z) noexcept : elements{x, y, z} {
}
constexpr Vec3(const Vec3& vec) noexcept = default;
constexpr Vec3(Vec3&& vec) noexcept = default;
constexpr ~Vec3() noexcept = default;
/// @brief Returns the x component
///
/// @return a const ref to the x component
[[nodiscard]] inline constexpr auto x() const noexcept -> const T& {
return elements[X];
}
/// @brief Returns the x component
///
/// @return a mutable (ie: non-const) ref to the x component
[[nodiscard]] inline constexpr auto x() noexcept -> T& {
return elements[X];
}
/// @brief Returns the y component
///
/// @return a const ref to the y component
[[nodiscard]] inline constexpr auto y() const noexcept -> const T& {
return elements[Y];
}
/// @brief Returns the y component
///
/// @return a mutable (ie: non-const) ref to the y component
[[nodiscard]] inline constexpr auto y() noexcept -> T& {
return elements[Y];
}
/// @brief Returns the z component
///
/// @return a const ref to the z component
[[nodiscard]] inline constexpr auto z() const noexcept -> const T& {
return elements[Z];
}
/// @brief Returns the z component
///
/// @return a mutable (ie: non-const) ref to the z component
[[nodiscard]] inline constexpr auto z() noexcept -> T& {
return elements[Z];
}
/// @brief Returns the magnitude (length) of the vector
///
/// @return The magnitude
template<FloatingPoint TT = float>
[[nodiscard]] inline constexpr auto magnitude() const noexcept -> TT {
return General::sqrt(narrow_cast<TT>(magnitude_squared()));
}
/// @brief Returns the dot product of this and `vec`
///
/// @param vec - The vector to perform the dot product with
///
/// @return The dot product
template<FloatingPoint TT = float>
[[nodiscard]] inline constexpr auto dot_prod(const Vec3<TT>& vec) const noexcept -> TT {
return narrow_cast<TT>(x()) * vec.x() + narrow_cast<TT>(y()) * vec.y()
+ narrow_cast<TT>(z()) * vec.z();
}
/// @brief Returns the dot product of this and `vec`
///
/// @param vec - The vector to perform the dot product with
///
/// @return The dot product
template<SignedIntegral TT = int>
[[nodiscard]] inline constexpr auto dot_prod(const Vec3<TT>& vec) const noexcept -> T {
return x() * narrow_cast<T>(vec.x()) + y() * narrow_cast<T>(vec.y())
+ z() * narrow_cast<T>(vec.z());
}
/// @brief Performs the cross product
///
/// @param vec The vector to perform the cross product with
///
/// @return The cross product
template<FloatingPoint TT = float>
[[nodiscard]] inline constexpr auto
cross_prod(const Vec3<TT>& vec) const noexcept -> Vec3<TT> {
const auto _x = narrow_cast<TT>(y()) * vec.z() - narrow_cast<TT>(z()) * vec.y();
const auto _y = narrow_cast<TT>(z()) * vec.x() - narrow_cast<TT>(x()) * vec.z();
const auto _z = narrow_cast<TT>(x()) * vec.y() - narrow_cast<TT>(y()) * vec.x();
return {_x, _y, _z};
}
/// @brief Performs the cross product
///
/// @param vec The vector to perform the cross product with
///
/// @return The cross product
template<SignedIntegral TT = int>
[[nodiscard]] inline constexpr auto cross_prod(const Vec3<TT>& vec) const noexcept -> Vec3 {
const auto _x = y() * narrow_cast<T>(vec.z()) - z() * narrow_cast<T>(vec.y());
const auto _y = z() * narrow_cast<T>(vec.x()) - x() * narrow_cast<T>(vec.z());
const auto _z = x() * narrow_cast<T>(vec.y()) - y() * narrow_cast<T>(vec.x());
return {_x, _y, _z};
}
/// @brief Returns **a** vector normal to this one
/// @note this is not necessarily the **only** vector normal to this one
///
/// @return a vector normal to this
[[nodiscard]] inline constexpr auto normal() const noexcept -> Vec3 {
return cross_prod(
Vec3<T>(narrow_cast<T>(1.0), narrow_cast<T>(0.0), narrow_cast<T>(0.0)));
}
/// @brief Returns this vector with normalized magnitude
///
/// @return this vector, normalized
template<FloatingPoint TT = float>
[[nodiscard]] inline constexpr auto normalized() const noexcept -> Vec3<TT> {
return std::move(*this / magnitude<TT>());
}
template<SignedNumeric TT = float>
[[nodiscard]] inline static constexpr auto random() noexcept -> Vec3<TT> {
return {random_value<TT>(), random_value<TT>(), random_value<TT>()};
}
template<SignedNumeric TT = float>
[[nodiscard]] inline static constexpr auto random(TT min, TT max) noexcept -> Vec3<TT> {
return {random_value<TT>(min, max),
random_value<TT>(min, max),
random_value<TT>(min, max)};
}
template<FloatingPoint TT = float>
[[nodiscard]] inline static constexpr auto random_in_unit_sphere() noexcept -> Vec3<TT> {
do {
auto val = random<TT>(narrow_cast<TT>(-1), narrow_cast<TT>(1));
if(narrow_cast<TT>(val.magnitude_squared()) < narrow_cast<TT>(1)) {
return val;
}
} while(true);
}
template<FloatingPoint TT = float>
[[nodiscard]] inline static constexpr auto random_in_unit_disk() noexcept -> Vec3<TT> {
do {
auto val = random(narrow_cast<TT>(-1), narrow_cast<TT>(1));
val.z() = narrow_cast<TT>(0);
if(narrow_cast<TT>(val.magnitude_squared()) < narrow_cast<TT>(1)) {
return val;
}
} while(true);
}
[[nodiscard]] inline constexpr auto is_approx_zero() noexcept -> bool {
constexpr auto zero_tolerance = narrow_cast<T>(0.0001);
return (General::abs(x()) < zero_tolerance) && (General::abs(y()) < zero_tolerance)
&& (General::abs(z()) < zero_tolerance);
}
[[nodiscard]] inline constexpr auto
reflected(const Vec3& surface_normal) const noexcept -> Vec3 {
return std::move(
*this - narrow_cast<T>(2) * (this->dot_prod(surface_normal) * surface_normal));
}
[[nodiscard]] inline constexpr auto
refracted(const Vec3& surface_normal, T eta_external_over_eta_internal) noexcept -> Vec3 {
const auto uv = *this;
const auto cos_theta = General::min((-uv).dot_prod(surface_normal), narrow_cast<T>(1));
auto out_perpendicular
= eta_external_over_eta_internal * (uv + cos_theta * surface_normal);
auto out_parallel = -General::sqrt(General::abs(
narrow_cast<T>(1) - out_perpendicular.magnitude_squared()))
* surface_normal;
return out_perpendicular + out_parallel;
}
constexpr auto operator=(const Vec3& vec) noexcept -> Vec3& = default;
constexpr auto operator=(Vec3&& vec) noexcept -> Vec3& = default;
template<FloatingPoint TT = float>
inline constexpr auto operator==(const Vec3<TT>& vec) const noexcept -> bool {
const auto xEqual
= General::abs<TT>(narrow_cast<TT>(x()) - vec.x()) < narrow_cast<TT>(0.01);
const auto yEqual
= General::abs<TT>(narrow_cast<TT>(y()) - vec.y()) < narrow_cast<TT>(0.01);
const auto zEqual
= General::abs<TT>(narrow_cast<TT>(z()) - vec.z()) < narrow_cast<TT>(0.01);
return xEqual && yEqual && zEqual;
}
template<SignedIntegral TT = int>
inline constexpr auto operator==(const Vec3<TT>& vec) const noexcept -> bool {
if constexpr(FloatingPoint<T>) {
const auto xEqual
= General::abs<T>(x() - narrow_cast<T>(vec.x())) < narrow_cast<TT>(0.01);
const auto yEqual
= General::abs<T>(y() - narrow_cast<T>(vec.y())) < narrow_cast<TT>(0.01);
const auto zEqual
= General::abs<T>(z() - narrow_cast<T>(vec.z())) < narrow_cast<TT>(0.01);
return xEqual && yEqual && zEqual;
}
else {
return x() == narrow_cast<T>(vec.x()) && y() == narrow_cast<T>(vec.y())
&& z() == narrow_cast<T>(vec.z());
}
}
template<SignedNumeric TT = T>
inline constexpr auto operator!=(const Vec3<TT>& vec) const noexcept -> bool {
return !(*this == vec);
}
inline constexpr auto operator-() const noexcept -> Vec3 {
return {-x(), -y(), -z()};
}
inline constexpr auto operator[](Vec3Idx i) const noexcept -> T {
const auto index = static_cast<size_t>(i);
return elements[index]; // NOLINT
}
inline constexpr auto operator[](Vec3Idx i) noexcept -> T& {
const auto index = static_cast<size_t>(i);
return elements[index]; // NOLINT
}
template<FloatingPoint TT = float>
inline constexpr auto operator+(const Vec3<TT>& vec) const noexcept -> Vec3<TT> {
return {narrow_cast<TT>(x()) + vec.x(),
narrow_cast<TT>(y()) + vec.y(),
narrow_cast<TT>(z()) + vec.z()};
}
template<SignedIntegral TT = int>
inline constexpr auto operator+(const Vec3<TT>& vec) const noexcept -> Vec3 {
return {x() + narrow_cast<T>(vec.x()),
y() + narrow_cast<T>(vec.y()),
z() + narrow_cast<T>(vec.z())};
}
template<SignedNumeric TT = T>
inline constexpr auto operator+=(const Vec3<TT>& vec) noexcept -> Vec3 {
x() += narrow_cast<T>(vec.x());
y() += narrow_cast<T>(vec.y());
z() += narrow_cast<T>(vec.z());
return *this;
}
template<FloatingPoint TT = float>
inline constexpr auto operator-(const Vec3<TT>& vec) const noexcept -> Vec3<TT> {
return {narrow_cast<TT>(x()) - vec.x(),
narrow_cast<TT>(y()) - vec.y(),
narrow_cast<TT>(z()) - vec.z()};
}
template<SignedIntegral TT = int>
inline constexpr auto operator-(const Vec3<TT>& vec) const noexcept -> Vec3 {
return {x() - narrow_cast<T>(vec.x()),
y() - narrow_cast<T>(vec.y()),
z() - narrow_cast<T>(vec.z())};
}
template<SignedNumeric TT = T>
inline constexpr auto operator-=(const Vec3<TT>& vec) noexcept -> Vec3& {
x() -= narrow_cast<T>(vec.x());
y() -= narrow_cast<T>(vec.y());
z() -= narrow_cast<T>(vec.z());
return *this;
}
inline constexpr auto operator*(FloatingPoint auto s) const noexcept -> Vec3<decltype(s)> {
using TT = decltype(s);
return {narrow_cast<TT>(x()) * s, narrow_cast<TT>(y()) * s, narrow_cast<TT>(z()) * s};
}
inline constexpr auto operator*(SignedIntegral auto s) const noexcept -> Vec3 {
auto scalar = narrow_cast<T>(s);
return {x() * scalar, y() * scalar, z() * scalar};
}
friend inline constexpr auto
operator*(FloatingPoint auto lhs, const Vec3& rhs) noexcept -> Vec3<decltype(lhs)> {
return rhs * lhs;
}
friend inline constexpr auto
operator*(SignedIntegral auto lhs, const Vec3& rhs) noexcept -> Vec3 {
return rhs * lhs;
}
inline constexpr auto operator*=(FloatingPoint auto s) noexcept -> Vec3& {
using TT = decltype(s);
x() = narrow_cast<T>(narrow_cast<TT>(x()) * s);
y() = narrow_cast<T>(narrow_cast<TT>(y()) * s);
z() = narrow_cast<T>(narrow_cast<TT>(z()) * s);
return *this;
}
inline constexpr auto operator*=(SignedIntegral auto s) noexcept -> Vec3& {
auto scalar = narrow_cast<T>(s);
x() *= scalar;
y() *= scalar;
z() *= scalar;
return *this;
}
inline constexpr auto operator/(FloatingPoint auto s) const noexcept -> Vec3<decltype(s)> {
using TT = decltype(s);
return {narrow_cast<TT>(x()) / s, narrow_cast<TT>(y()) / s, narrow_cast<TT>(z()) / s};
}
inline constexpr auto operator/(SignedIntegral auto s) const noexcept -> Vec3 {
auto scalar = narrow_cast<T>(s);
return {x() / scalar, y() / scalar, z() / scalar};
}
friend inline constexpr auto
operator/(FloatingPoint auto lhs, const Vec3& rhs) noexcept -> Vec3<decltype(lhs)> {
return rhs / lhs;
}
friend inline constexpr auto
operator/(SignedIntegral auto lhs, const Vec3& rhs) noexcept -> Vec3 {
return rhs / lhs;
}
inline constexpr auto operator/=(FloatingPoint auto s) noexcept -> Vec3& {
using TT = decltype(s);
x() = narrow_cast<T>(narrow_cast<TT>(x()) / s);
y() = narrow_cast<T>(narrow_cast<TT>(y()) / s);
z() = narrow_cast<T>(narrow_cast<TT>(z()) / s);
return *this;
}
inline constexpr auto operator/=(SignedIntegral auto s) noexcept -> Vec3& {
auto scalar = narrow_cast<T>(s);
x() /= scalar;
y() /= scalar;
z() /= scalar;
return *this;
}
friend inline constexpr auto
operator<<(std::ostream& out, const Vec3& vec) noexcept -> std::ostream& {
return out << vec.x() << ' ' << vec.y() << ' ' << vec.z();
}
private:
static constexpr size_t NUM_ELEMENTS = static_cast<size_t>(Vec3Idx::Z) + 1;
T elements[NUM_ELEMENTS] // NOLINT
= {narrow_cast<T>(0), narrow_cast<T>(0), narrow_cast<T>(0)};
/// @brief Calculates the magnitude squared of this vector
///
/// @return The magnitude squared
[[nodiscard]] inline constexpr auto magnitude_squared() const noexcept -> T {
return x() * x() + y() * y() + z() * z();
}
/// Index for x component
static constexpr size_t X = static_cast<size_t>(Vec3Idx::X);
/// Index for y component
static constexpr size_t Y = static_cast<size_t>(Vec3Idx::Y);
/// Index for z component
static constexpr size_t Z = static_cast<size_t>(Vec3Idx::Z);
};
// Deduction Guides
template<FloatingPoint T>
explicit Vec3(T, T, T) -> Vec3<T>;
template<SignedIntegral T>
explicit Vec3(T, T, T) -> Vec3<T>;
} // namespace hyperion::math
| {
"alphanum_fraction": 0.6378533993,
"avg_line_length": 32.8810679612,
"ext": "h",
"hexsha": "1ea115dfc03f339817f0a5a9a58fddca7d7632ab",
"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": "77093e282b29747741fd4164b4e165fcef267471",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "braxtons12/Hyperion-Math",
"max_forks_repo_path": "include/HyperionMath/Vec3.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "77093e282b29747741fd4164b4e165fcef267471",
"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": "braxtons12/Hyperion-Math",
"max_issues_repo_path": "include/HyperionMath/Vec3.h",
"max_line_length": 94,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "77093e282b29747741fd4164b4e165fcef267471",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "braxtons12/Hyperion-Math",
"max_stars_repo_path": "include/HyperionMath/Vec3.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 3910,
"size": 13547
} |
#pragma once
#include <nextalign/nextalign.h>
#include <gsl/string_span>
#include <string>
#include "../nextalign_private.h"
#include "../utils/to_underlying.h"
using AminoacidSequenceSpan = SequenceSpan<Aminoacid>;
Aminoacid charToAa(char aa);
char aaToChar(Aminoacid aa);
inline std::ostream& operator<<(std::ostream& os, const Aminoacid& aminoacid) {
os << std::string{to_underlying(aminoacid)};
return os;
}
| {
"alphanum_fraction": 0.7423167849,
"avg_line_length": 20.1428571429,
"ext": "h",
"hexsha": "50e6079acc129efb0d1c5e36ac5ef7a4feec5fac",
"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": "f62d906034974c160eabb12ac9bf98a691646ee3",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "davidcroll/nextclade",
"max_forks_repo_path": "packages/nextalign/src/alphabet/aminoacids.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "f62d906034974c160eabb12ac9bf98a691646ee3",
"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": "davidcroll/nextclade",
"max_issues_repo_path": "packages/nextalign/src/alphabet/aminoacids.h",
"max_line_length": 79,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "f62d906034974c160eabb12ac9bf98a691646ee3",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "davidcroll/nextclade",
"max_stars_repo_path": "packages/nextalign/src/alphabet/aminoacids.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 111,
"size": 423
} |
/* gsl_histogram2d_copy.c
* Copyright (C) 2000 Simone Piccardi
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 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 library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*/
/***************************************************************
*
* File gsl_histogram2d_copy.c:
* Routine to copy a 2D histogram.
* Need GSL library and header.
*
* Author: S. Piccardi
* Jan. 2000
*
***************************************************************/
#include <config.h>
#include <stdlib.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_histogram2d.h>
/*
* gsl_histogram2d_copy:
* copy the contents of an histogram into another
*/
int
gsl_histogram2d_memcpy (gsl_histogram2d * dest, const gsl_histogram2d * src)
{
size_t nx = src->nx;
size_t ny = src->ny;
size_t i;
if (dest->nx != src->nx || dest->ny != src->ny)
{
GSL_ERROR ("histograms have different sizes, cannot copy",
GSL_EINVAL);
}
for (i = 0; i <= nx; i++)
{
dest->xrange[i] = src->xrange[i];
}
for (i = 0; i <= ny; i++)
{
dest->yrange[i] = src->yrange[i];
}
for (i = 0; i < nx * ny; i++)
{
dest->bin[i] = src->bin[i];
}
return GSL_SUCCESS;
}
/*
* gsl_histogram2d_duplicate:
* duplicate an histogram creating
* an identical new one
*/
gsl_histogram2d *
gsl_histogram2d_clone (const gsl_histogram2d * src)
{
size_t nx = src->nx;
size_t ny = src->ny;
size_t i;
gsl_histogram2d *h;
h = gsl_histogram2d_calloc_range (nx, ny, src->xrange, src->yrange);
if (h == 0)
{
GSL_ERROR_VAL ("failed to allocate space for histogram struct",
GSL_ENOMEM, 0);
}
for (i = 0; i < nx * ny; i++)
{
h->bin[i] = src->bin[i];
}
return h;
}
| {
"alphanum_fraction": 0.6115879828,
"avg_line_length": 24.0206185567,
"ext": "c",
"hexsha": "96086601240a7befaa18147ea727e72b7e5d707b",
"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/histogram/copy2d.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/histogram/copy2d.c",
"max_line_length": 76,
"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/histogram/copy2d.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": 650,
"size": 2330
} |
/* interpolation/interp_poly.c
*
* Copyright (C) 2001 DAN, HO-JIN
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
/* Modified for standalone use in polynomial directory, B.Gough 2001 */
#include <config.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_poly.h>
int
gsl_poly_dd_init (double dd[], const double xa[], const double ya[],
size_t size)
{
size_t i, j;
/* Newton's divided differences */
dd[0] = ya[0];
for (j = size - 1; j >= 1; j--)
{
dd[j] = (ya[j] - ya[j - 1]) / (xa[j] - xa[j - 1]);
}
for (i = 2; i < size; i++)
{
for (j = size - 1; j >= i; j--)
{
dd[j] = (dd[j] - dd[j - 1]) / (xa[j] - xa[j - i]);
}
}
return GSL_SUCCESS;
}
int
gsl_poly_dd_taylor (double c[], double xp,
const double dd[], const double xa[], size_t size,
double w[])
{
size_t i, j;
for (i = 0; i < size; i++)
{
c[i] = 0.0;
w[i] = 0.0;
}
w[size - 1] = 1.0;
c[0] = dd[0];
for (i = size - 1; i-- > 0;)
{
w[i] = -w[i + 1] * (xa[size - 2 - i] - xp);
for (j = i + 1; j < size - 1; j++)
{
w[j] = w[j] - w[j + 1] * (xa[size - 2 - i] - xp);
}
for (j = i; j < size; j++)
{
c[j - i] += w[j] * dd[size - i - 1];
}
}
return GSL_SUCCESS;
}
| {
"alphanum_fraction": 0.5396669931,
"avg_line_length": 23.7441860465,
"ext": "c",
"hexsha": "54f8024cff1af884d912c354e1aafcf3e12f96cd",
"lang": "C",
"max_forks_count": 14,
"max_forks_repo_forks_event_max_datetime": "2020-03-12T12:31:25.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-07-21T04:47:52.000Z",
"max_forks_repo_head_hexsha": "0cb4635af7602f2a243a9b739e5ed757424ab2a7",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "skair39/structured",
"max_forks_repo_path": "CMVS-PMVS/program/thirdParty/gsl-1.13/poly/dd.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "0cb4635af7602f2a243a9b739e5ed757424ab2a7",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "skair39/structured",
"max_issues_repo_path": "CMVS-PMVS/program/thirdParty/gsl-1.13/poly/dd.c",
"max_line_length": 81,
"max_stars_count": 14,
"max_stars_repo_head_hexsha": "92728bb89692fda1705a0dee436592d97922a6cb",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "parasol-ppl/PPL_utils",
"max_stars_repo_path": "folding_libs/gsl-1.14/poly/dd.c",
"max_stars_repo_stars_event_max_datetime": "2021-11-25T17:31:22.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-01-11T02:53:04.000Z",
"num_tokens": 640,
"size": 2042
} |
#include <stdio.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
#include <gsl/gsl_permutation.h>
int
main (void)
{
const size_t N = 10;
const gsl_rng_type * T;
gsl_rng * r;
gsl_permutation * p = gsl_permutation_alloc (N);
gsl_permutation * q = gsl_permutation_alloc (N);
gsl_rng_env_setup();
T = gsl_rng_default;
r = gsl_rng_alloc (T);
printf ("initial permutation:");
gsl_permutation_init (p);
gsl_permutation_fprintf (stdout, p, " %u");
printf ("\n");
printf (" random permutation:");
gsl_ran_shuffle (r, p->data, N, sizeof(size_t));
gsl_permutation_fprintf (stdout, p, " %u");
printf ("\n");
printf ("inverse permutation:");
gsl_permutation_inverse (q, p);
gsl_permutation_fprintf (stdout, q, " %u");
printf ("\n");
gsl_permutation_free (p);
gsl_permutation_free (q);
gsl_rng_free (r);
return 0;
}
| {
"alphanum_fraction": 0.6655211913,
"avg_line_length": 21.2926829268,
"ext": "c",
"hexsha": "72478641d42975cc83d252fc68cf693c87c37400",
"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/permshuffle.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/permshuffle.c",
"max_line_length": 50,
"max_stars_count": 64,
"max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "manggoguy/parsec-modified",
"max_stars_repo_path": "pkgs/libs/gsl/src/doc/examples/permshuffle.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": 264,
"size": 873
} |
#define _USE_MATH_DEFINES
#include <cmath>
#include <Eigen/Core>
#include <gsl/gsl_sf_gamma.h>
#include <gsl/gsl_sf_zeta.h>
#include <gsl/gsl_sf_fermi_dirac.h>
#include <vector>
//#include <iostream>
using Eigen::Matrix;
using Eigen::VectorXd;
void li(size_t k, double x, Matrix<double, -1, 1> &ans);
template<typename T>
class Distribution {
private:
T loc;
T scale;
Matrix<T, -1, 1> param;
size_t k;
//
Matrix<T, -1, 1> C;
Matrix<T, -1, 1> C_inf;
Matrix<T, -1, 1> Gamma;
Matrix<T, -1, -1> C_li;
Matrix<T, -1, -1> Col;
Matrix<T, -1, -1> Col_arg;
Matrix<T, -1, -1> Alpha;
Matrix<T, -1, 1> M;
Matrix<T, -1, 1> C_y;
std::vector<T> y_abs_pow;
Matrix<T, -1, 1> X_pow;
Matrix<T, -1, 1> Li;
Matrix<T, -1, 1> I;
Matrix<T, -1, 1> I_u;
Matrix<T, -1, -1> I_t;
public:
Distribution(T loc_, T scale_, Matrix<T, -1, 1> param_)
: loc(loc_), scale(scale_), param(std::move(param_)), k(param.size()),
C_y(Matrix<T, -1, 1>::Ones(2 * k - 2)), y_abs_pow(2 * k - 1), X_pow(Matrix<T, -1, 1>(2 * k - 2)),
Li(Matrix<T, -1, 1>(2 * k - 2)), I_u(Matrix<T, -1, 1>(2 * k - 1)) {
// Vector of i * Gamma(i) * (1 - 2^{1 - i}) * zeta(i)
C = Matrix<T, -1, 1>(2 * k - 2);
C[0] = M_LN2;
{
double curr = 0.5;
for (size_t i = 2; i <= 2 * k - 2; i++) {
C[i - 1] = i * gsl_sf_fact(i - 1) * (1 - curr) * gsl_sf_zeta_int(i);
curr /= 2;
}
}
C_inf = Matrix<T, -1, 1>::Ones(2 * k - 2);
for (size_t i = 0; i < 2 * k - 2; i += 2) {
C_inf[i] = -1;
}
// Vector of i * Gamma(i)
Gamma = Matrix<T, -1, 1>(2 * k - 2);
C_li = Matrix<T, -1, -1>::Zero(2 * k - 2, 2 * k - 2);
for (size_t i = 0; i < 2 * k - 2; i++) {
Gamma[i] = gsl_sf_fact(i + 1);
if (i != 0) {
C_li(i, 0) = 1 / Gamma[i - 1];
} else {
C_li(i, 0) = 1;
}
}
// Matrix of collocation coefficients
Col = Matrix<T, -1, -1>::Zero(2 * k - 1, 2 * k - 1);
for (size_t i = 0; i < 2 * k - 1; i++) {
for (size_t j = 0; j <= i; j++) {
Col(i, j) = gsl_sf_choose(i, j);
}
}
M = Matrix<T, -1, 1>(2 * k - 1);
M[0] = 1;
for (size_t i = 1; i < 2 * k - 1; i++) {
M[i] = i % 2 == 1 ? 0 : 2 * C[i - 1];
}
precalc();
}
void precalc() {
// Matrix of collocation coefficients
std::vector<T> locs(2 * k - 1), scales(2 * k - 1);
locs[0] = 1;
scales[0] = 1;
for (size_t i = 1; i < 2 * k - 1; i++) {
locs[i] = locs[i - 1] * loc;
scales[i] = scales[i - 1] * scale;
}
Col_arg = Col;
for (size_t i = 0; i < 2 * k - 1; i++) {
for (size_t j = 0; j <= i; j++) {
Col_arg(i, j) *= locs[i - j] * scales[j];
}
}
// Matrix of shifted alpha parameter vector
Alpha = Matrix<T, -1, -1>::Zero(k, 2 * k - 1);
for (size_t i = 0; i < k; i++) {
for (size_t j = i; j < i + k; j++) {
Alpha(i, j) = param[j - i];
}
}
Alpha = param.transpose() * Alpha;
}
void reset_param(T loc_, T scale_, Eigen::Matrix<T, -1, 1> ¶m_) {
loc = loc_;
scale = scale_;
param = param_;
precalc();
}
double cdf(T x) {
// std::cout << "x = " << x << std::endl;
T y = (x - loc) / scale;
T y_abs = abs(y);
if (y < 0) {
for (size_t i = 1; i < 2 * k - 2; i += 2) {
C_y[i] = -1;
}
} else {
for (size_t i = 1; i < 2 * k - 2; i += 2) {
C_y[i] = 1;
}
}
// Vector of pow(arg, i)
y_abs_pow[0] = 1;
for (size_t i = 1; i < 2 * k - 1; i++) {
y_abs_pow[i] = y_abs_pow[i - 1] * y_abs;
}
for (size_t i = 0; i < 2 * k - 2; i++) {
X_pow[i] = y_abs_pow[i + 1]; // (y_abs, i + 1);
}
X_pow = (0.5 * tanh(y_abs / 2) - 0.5) * X_pow;
// Polylogarithms vector
// for (size_t i = 0; i < 2 * k - 2; i++) {
// if (y_abs >= 690) Li[i] = 0;
// else Li[i] = -gsl_sf_fermi_dirac_int(i, -y_abs);
// }
double z = -std::exp(-y_abs);
li(2 * k - 2, z, Li);
// std::cout << "li = " << Li.transpose() << std::endl;
// Polylogarithm coefficients
Matrix<T, -1, -1> C_li_arg = C_li;
for (size_t i = 0; i < 2 * k - 2; i++) {
C_li_arg(i, 0) *= y_abs_pow[i]; // pow(y_abs, i);
for (size_t j = 1; j <= i; j++) {
C_li_arg(i, j) = C_li_arg(i - 1, j - 1);
}
}
C_li_arg = C_li_arg * Li;
C_li_arg = Gamma.array() * C_li_arg.array();
I = (C_inf + C_y).array() * C.array() + C_y.array() * X_pow.array() + C_y.array() * C_li_arg.array();
// from -infty to 0 + 0.5 * tanh
T C_y0 = y >= 0 ? 1 : -1;
I_u << 0.5 + C_y0 * 0.5 * tanh(y_abs / 2), I;
// Vector I^t
I_t = Col_arg * I_u;
T fx = (Alpha * I_t)(0);
T C_1 = 1 / (Alpha * Col_arg * M).sum();
// std::cout << "fx = " << C_1 * fx << std::endl;
return C_1 * fx;
}
};
| {
"alphanum_fraction": 0.407644477,
"avg_line_length": 29.3978494624,
"ext": "h",
"hexsha": "889fa09c299f79c9713da38dd26ae3e81b5e1eff",
"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": "c5a7481414bd2baa2b38b8c64c593348846b6660",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "ainmukh/project",
"max_forks_repo_path": "nychka/distribution/approx_class.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "c5a7481414bd2baa2b38b8c64c593348846b6660",
"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": "ainmukh/project",
"max_issues_repo_path": "nychka/distribution/approx_class.h",
"max_line_length": 111,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "c5a7481414bd2baa2b38b8c64c593348846b6660",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "ainmukh/project",
"max_stars_repo_path": "nychka/distribution/approx_class.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1985,
"size": 5468
} |
/* Copyright (c) 2011-2019, NVIDIA CORPORATION. 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.
* * Neither the name of NVIDIA CORPORATION nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``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.
*/
#pragma once
#include <util.h>
#include <amg.h>
#include <basic_types.h>
#include <types.h>
#include <norm.h>
#include <logger.h>
#include <matrix_distribution.h>
#include <iostream>
#include <iomanip>
#include <blas.h>
#include <multiply.h>
#include <amg_level.h>
#include <amgx_c.h>
#include <profile.h>
#include <misc.h>
#include <string>
#include <cassert>
#include <csr_multiply.h>
#include <memory_info.h>
#include <thrust/sort.h>
#include <thrust/remove.h>
#include <thrust/unique.h>
#include <thrust/binary_search.h>
#include <thrust/iterator/constant_iterator.h>
#define COARSE_CLA_CONSO 0 // used enable / disable coarse level consolidation (used in cycles files)
namespace amgx
{
/**********************************************************
* Glue ( Consolidation)
*********************************************************/
#ifdef AMGX_WITH_MPI
//------------------------
//---------Matrix-------------
//------------------------
template<class TConfig>
void compute_glue_info(Matrix<TConfig> &A)
{
// Fill distributed manager fields for consolidation
// Example
// destination_part = [0 0 0 0 4 4 4 4 8 8 8 8] (input from manager->computeDestinationPartitions)
// num_parts_to_consolidate = 4 for partitions 0,4,8 - (0 otherwise)
// parts_to_consolidate (rank 0)[0 1 2 3] (rank 4)[4 5 6 7] (rank 8)[8 9 10 11]
//coarse_part_to_fine_part = [0 4 8] num_coarse_partitions = 3
//fine_part_to_coarse_part = [0 0 0 0 1 1 1 1 2 2 2 2]
//ConsolidationArrayOffsets constains the offset of the nnz of each partitions in row pointer fashion : 0, pat1.NNZ, pat1.NNZ+part2.NNZ ... NNZ
typedef typename TConfig::template setMemSpace<AMGX_host>::Type TConfig_h;
typedef typename TConfig_h::template setVecPrec<AMGX_vecInt>::Type ivec_value_type_h;
typedef typename ivec_value_type_h::VecPrec VecInt_t;
bool is_root_partition = false;
int num_parts_to_consolidate = 0;
int num_parts = A.manager->getComms()->get_num_partitions();
int my_id = A.manager->global_id();
Vector<ivec_value_type_h> parts_to_consolidate;
Vector<ivec_value_type_h> dest_partitions = A.manager->getDestinationPartitions();
// compute is_root_partition and num_parts_to_consolidate
for (int i = 0; i < num_parts; i++)
{
if (dest_partitions[i] == my_id)
{
is_root_partition = true;
num_parts_to_consolidate++;
}
}
parts_to_consolidate.resize(num_parts_to_consolidate);
// parts_to_consolidate
int count = 0;
for (int i = 0; i < num_parts; i++)
{
if (dest_partitions[i] == my_id)
{
parts_to_consolidate[count] = i;
count++;
}
}
A.manager->setIsRootPartition(is_root_partition);
A.manager->setNumPartsToConsolidate(num_parts_to_consolidate);
A.manager->setPartsToConsolidate(parts_to_consolidate);
// We don't really use the following in the latest version of the glue path but they are useful information
// coarse_to_fine_part, fine_to_coarse_part
Vector<ivec_value_type_h> coarse_to_fine_part, fine_to_coarse_part(num_parts);
coarse_to_fine_part = dest_partitions;
thrust::sort(coarse_to_fine_part.begin(), coarse_to_fine_part.end());
cudaCheckError();
coarse_to_fine_part.erase(thrust::unique(coarse_to_fine_part.begin(), coarse_to_fine_part.end()), coarse_to_fine_part.end());
cudaCheckError();
thrust::lower_bound(coarse_to_fine_part.begin(), coarse_to_fine_part.end(), dest_partitions.begin(), dest_partitions.end(), fine_to_coarse_part.begin());
cudaCheckError();
A.manager->setCoarseToFine(coarse_to_fine_part);
A.manager->setFineToCoarse(fine_to_coarse_part);
Vector<ivec_value_type_h> consolidationArrayOffsets;
consolidationArrayOffsets.resize(num_parts);
}
template<class TConfig>
MPI_Comm compute_glue_matrices_communicator(Matrix<TConfig> &A)
{
// Create temporary communicators for each consilidated matrix
int rank;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
if (A.manager->getDestinationPartitions().size() != 0)
{
int color = A.manager->getDestinationPartitions()[rank];
MPI_Comm new_comm;
// Split a communicator into multiple, non-overlapping communicators by color(each destiation partition has its color)
// 1. Use MPI_Allgather to get the color and key from each process
// 2. Count the number of processes with the same color; create a
// communicator with that many processes. If this process has
// MPI_UNDEFINED as the color, create a process with a single member.
// 3. Use key to order the ranks
MPI_Comm_split(MPI_COMM_WORLD, color, rank, &new_comm);
return new_comm;
}
else
{
FatalError("NO DESTINATION PARTIONS", AMGX_ERR_CORE);
}
}
//function object (functor) for thrust calls (it is a unary operator to add a constant)
template<typename T>
class add_constant_op
{
const T c;
public:
add_constant_op(T _c) : c(_c) {}
__host__ __device__ T operator()(const T &x) const
{
return x + c;
}
};
template<class TConfig>
int create_part_offsets(MPI_Comm &mpicm, Matrix<TConfig> &nv_mtx)
{
/* WARNING: Notice that part_offsets_h & part_offsets have type int64_t.
Therefore we need to use MPI_INT64_T (or MPI_LONG_LONG) in MPI_Allgather.
Also, we need the send & recv buffers to be of the same type, therefore
we will create a temporary variable n64 of the correct type below. */
//create TConfig64, which is the same as TConfig, but with index type being int64_t
typedef typename TConfig::template setVecPrec<AMGX_vecInt64>::Type TConfig64;
typedef typename TConfig64::VecPrec t_VecPrec; //t_VecPrec = int64_t
int n, offset, mpist;
int nranks = 0; //nv_mtx.manager->get_num_partitions();
if (nv_mtx.manager != NULL)
{
//some initializations
nv_mtx.getOffsetAndSizeForView(OWNED, &offset, &n);
MPI_Comm_size(mpicm, &nranks);
nv_mtx.manager->part_offsets_h.resize(nranks + 1);
//gather the number of rows per partition on the host (on all ranks)
t_VecPrec n64 = n;
nv_mtx.manager->part_offsets_h[0] = 0; //first element is zero (the # of rows is gathered afterwards)
if (typeid(t_VecPrec) == typeid(int64_t))
{
mpist = MPI_Allgather(&n64, 1, MPI_INT64_T, nv_mtx.manager->part_offsets_h.raw() + 1, 1, MPI_INT64_T, mpicm);
}
else
{
FatalError("MPI_Gatherv of the vector has failed - incorrect vector data type", AMGX_ERR_CORE);
}
if (mpist != MPI_SUCCESS)
{
FatalError("MPI_Gatherv of the vector has failed - detected incorrect MPI return code", AMGX_ERR_CORE);
}
//perform a prefix sum
thrust::inclusive_scan(nv_mtx.manager->part_offsets_h.begin(), nv_mtx.manager->part_offsets_h.end(), nv_mtx.manager->part_offsets_h.begin());
//create the corresponding array on device (this is important)
nv_mtx.manager->part_offsets.resize(nranks + 1);
thrust::copy(nv_mtx.manager->part_offsets_h.begin(), nv_mtx.manager->part_offsets_h.end(), nv_mtx.manager->part_offsets.begin());
}
return 0;
}
template<class TConfig>
int glue_matrices(Matrix<TConfig> &nv_mtx, MPI_Comm &nv_mtx_com, MPI_Comm &temp_com)
{
typedef typename TConfig::IndPrec t_IndPrec;
typedef typename TConfig::MatPrec t_MatPrec;
int n, nnz, offset, l, k = 0, i;
int start, end, shift;
int mpist, root = 0;
//MPI call parameters
t_IndPrec *rc_ptr, *di_ptr;
t_IndPrec *hli_ptr, *hgi_ptr, *hgr_ptr, *i_ptr, *r_ptr;
t_MatPrec *hlv_ptr, *hgv_ptr, *v_ptr;
thrust::host_vector<t_IndPrec> rc;
thrust::host_vector<t_IndPrec> di;
//unpacked local matrix on the device and host
device_vector_alloc<t_IndPrec> Bp;
device_vector_alloc<t_IndPrec> Bi;
device_vector_alloc<t_MatPrec> Bv;
thrust::host_vector<t_IndPrec> hBp;
thrust::host_vector<t_IndPrec> hBi;
thrust::host_vector<t_MatPrec> hBv;
//Consolidated matrices on the host
thrust::host_vector<t_IndPrec> hAp;
thrust::host_vector<t_IndPrec> hAi;
thrust::host_vector<t_MatPrec> hAv;
//Consolidated matrices on the device
device_vector_alloc<t_IndPrec> Ap;
device_vector_alloc<t_IndPrec> Ai;
device_vector_alloc<t_MatPrec> Av;
//WARNING: this routine currently supports matrix only with block size =1 (it can be generalized in the future, though)
//initialize the defaults
mpist = MPI_SUCCESS;
if (nv_mtx.manager != NULL)
{
//int rank = nv_mtx.manager->global_id();
nv_mtx.getOffsetAndSizeForView(OWNED, &offset, &n);
nv_mtx.getNnzForView(OWNED, &nnz);
if (nv_mtx.manager->part_offsets_h.size() == 0 || nv_mtx.manager->part_offsets.size() == 0) // create part_offsets_h & part_offsets
{
create_part_offsets(nv_mtx_com, nv_mtx); // (if needed for aggregation path)
}
Bp.resize(n + 1);
Bi.resize(nnz);
Bv.resize(nnz);
hBp.resize(n + 1);
hBi.resize(nnz);
hBv.resize(nnz);
//--- unpack the matrix ---
nv_mtx.manager->unpack_partition(thrust::raw_pointer_cast(Bp.data()),
thrust::raw_pointer_cast(Bi.data()),
thrust::raw_pointer_cast(Bv.data()));
cudaCheckError();
//copy to host (should be able to optimize this out later on)
hBp = Bp;
hBi = Bi;
hBv = Bv;
cudaCheckError();
// --- Glue matrices ---
// construct global row pointers
// compute recvcounts and displacements for MPI_Gatherv
if (nv_mtx.manager->isRootPartition())
{
l = nv_mtx.manager->getNumPartsToConsolidate(); // number of partitions
rc.resize(l);
di.resize(l);
//compute recvcounts and displacements for MPI_Gatherv
for (i = 0; i < l; i++)
{
start = nv_mtx.manager->part_offsets_h[nv_mtx.manager->getPartsToConsolidate()[i]];
end = nv_mtx.manager->part_offsets_h[nv_mtx.manager->getPartsToConsolidate()[i] + 1];
rc[i] = end - start;
di[i] = k + 1;
k += rc[i];
}
hAp.resize(k + 1); // extra +1 is needed because row_offsets have one extra element at the end
}
cudaCheckError();
//alias raw pointers to thrust vector data (see thrust example unwrap_pointer for details)
rc_ptr = thrust::raw_pointer_cast(rc.data());
di_ptr = thrust::raw_pointer_cast(di.data());
hli_ptr = thrust::raw_pointer_cast(hBp.data());
hgr_ptr = thrust::raw_pointer_cast(hAp.data());
cudaCheckError();
//gather (on the host)
if (typeid(t_IndPrec) == typeid(int))
{
mpist = MPI_Gatherv(hli_ptr + 1, n, MPI_INT, hgr_ptr, rc_ptr, di_ptr, MPI_INT, root, temp_com);
}
else
{
FatalError("MPI_Gatherv of the vector has failed - incorrect vector data type", AMGX_ERR_CORE);
}
if (mpist != MPI_SUCCESS)
{
FatalError("MPI_Gatherv of the vector has failed - detected incorrect MPI return code", AMGX_ERR_CORE);
}
// Adjust row pointers, construct global column indices and values (recvcounts and displacements were computed above)
if (nv_mtx.manager->isRootPartition())
{
//adjust global row pointers and setup the recvcounts & displacements for subsequent MPI calls
for (i = 0; i < l; i++)
{
start = di[i] - 1;
end = di[i] + rc[i] - 1;
shift = hAp[start];
thrust::transform(hAp.begin() + start + 1, hAp.begin() + end + 1, hAp.begin() + start + 1, add_constant_op<t_IndPrec>(shift));
cudaCheckError();
di[i] = shift;
rc[i] = hAp[end] - hAp[start];
}
//some allocations/resizing
hAi.resize(hAp[k]);
hAv.resize(hAp[k]);
}
//alias raw pointers to thrust vector data (see thrust example unwrap_pointer for details)
rc_ptr = thrust::raw_pointer_cast(rc.data());
di_ptr = thrust::raw_pointer_cast(di.data());
hli_ptr = thrust::raw_pointer_cast(hBi.data());
hgi_ptr = thrust::raw_pointer_cast(hAi.data());
hlv_ptr = thrust::raw_pointer_cast(hBv.data());
hgv_ptr = thrust::raw_pointer_cast(hAv.data());
cudaCheckError();
//gather (on the host)
//columns indices
if (typeid(t_IndPrec) == typeid(int))
{
mpist = MPI_Gatherv(hli_ptr, nnz, MPI_INT, hgi_ptr, rc_ptr, di_ptr, MPI_INT, root, temp_com);
}
else
{
FatalError("MPI_Gatherv of the vector has failed - incorrect vector data type", AMGX_ERR_CORE);
}
if (mpist != MPI_SUCCESS)
{
FatalError("MPI_Gatherv of the vector has failed - detected incorrect MPI return code", AMGX_ERR_CORE);
}
//values
if (typeid(t_MatPrec) == typeid(float))
{
mpist = MPI_Gatherv(hlv_ptr, nnz, MPI_FLOAT, hgv_ptr, rc_ptr, di_ptr, MPI_FLOAT, root, temp_com);
}
else if (typeid(t_MatPrec) == typeid(double))
{
mpist = MPI_Gatherv(hlv_ptr, nnz, MPI_DOUBLE, hgv_ptr, rc_ptr, di_ptr, MPI_DOUBLE, root, temp_com);
}
else
{
FatalError("MPI_Gatherv of the vector has failed - incorrect vector data type", AMGX_ERR_CORE);
}
if (mpist != MPI_SUCCESS)
{
FatalError("MPI_Gatherv of the vector has failed - detected incorrect MPI return code", AMGX_ERR_CORE);
}
// --- Upload matrices ---
if (nv_mtx.manager->isRootPartition())
{
n = hAp.size() - 1;
nnz = hAi.size();
Ap.resize(hAp.size());
Ai.resize(hAi.size());
Av.resize(hAv.size());
thrust::copy(hAp.begin(), hAp.end(), Ap.begin());
thrust::copy(hAi.begin(), hAi.end(), Ai.begin());
thrust::copy(hAv.begin(), hAv.end(), Av.begin());
cudaCheckError();
}
else
{
n = 0;
nnz = 0;
Ap.resize(1); // warning row_ponter size is expected to be n+1.
Ap.push_back(0);
Ai.resize(0);
Av.resize(0);
cudaCheckError();
}
r_ptr = thrust::raw_pointer_cast(Ap.data());
i_ptr = thrust::raw_pointer_cast(Ai.data());
v_ptr = thrust::raw_pointer_cast(Av.data());
cudaCheckError();
upload_matrix_after_glue(n, nnz, r_ptr, i_ptr, v_ptr, nv_mtx);
}
else
{
/* ASSUMPTION: when manager has not been allocated you are running on a single rank */
}
return 0;
}
template<class TConfig>
int upload_matrix_after_glue(int n, int nnz, int *r_ptr, int *i_ptr, void *v_ptr, Matrix<TConfig> &nv_mtx)
{
// Using a path similar to AMGX_matrix_upload_all_global
typedef typename TConfig::IndPrec t_IndPrec;
typedef typename TConfig::MatPrec t_MatPrec;
typedef typename TConfig::template setMemSpace<AMGX_host>::Type TConfig_h;
typedef typename TConfig::template setVecPrec<AMGX_vecInt>::Type ivec_value_type;
typedef typename TConfig_h::template setVecPrec<AMGX_vecInt>::Type ivec_value_type_h;
typedef typename ivec_value_type_h::VecPrec VecInt_t;
typedef Vector<ivec_value_type> IVector;
// some parameters
int block_dimx, block_dimy, num_ranks, n_global, start, end, val;
t_IndPrec *part_vec_ptr;
thrust::host_vector<t_IndPrec> pv;
// set parameters
nv_mtx.setView(ALL); // not sure about this
n_global = nv_mtx.manager->part_offsets_h.back();
block_dimx = nv_mtx.get_block_dimx();
block_dimy = nv_mtx.get_block_dimy();
//MPI_Comm* mpi_comm = nv_mtx.getResources()->getMpiComm();
//MPI_Comm_size(*mpi_comm, &num_ranks);
num_ranks = nv_mtx.manager->getComms()->get_num_partitions();
// WARNING We create an artificial partition vectior that matches the new distribution
// example n = 8, num_ranks(ie. num partitions) = 4 , DestinationPartitions[0,0,2,2], partvec = [0,0,0,0,2,2,2,2]
// This might be an issue for the finest level if input_partvect !=NULL
Vector<ivec_value_type_h> dest_partitions = nv_mtx.manager->getDestinationPartitions();
for (int i = 0; i < num_ranks; i++)
{
val = dest_partitions[i];
start = nv_mtx.manager->part_offsets_h[i];
end = nv_mtx.manager->part_offsets_h[i + 1];
for (int j = 0; j < end - start; j++)
{
pv.push_back(val);
}
}
part_vec_ptr = thrust::raw_pointer_cast(pv.data());
cudaCheckError();
// Save some glue info
bool is_root_partition = nv_mtx.manager->isRootPartition();
int dest_part = nv_mtx.manager->getMyDestinationPartition();
int num_parts_to_consolidate = nv_mtx.manager->getNumPartsToConsolidate();
Vector<ivec_value_type_h> parts_to_consolidate = nv_mtx.manager->getPartsToConsolidate();
std::vector<int> cao;
for (int i = 0; i < nv_mtx.manager->part_offsets_h.size(); i++)
{
cao.push_back(nv_mtx.manager->part_offsets_h[i]);
}
// WARNING
// renumbering contains the inverse permutation to unreorder an amgx vector
// inverse_renumbering contains the permutaion to reorder an amgx vector
Vector<ivec_value_type> ir = nv_mtx.manager->inverse_renumbering;
Vector<ivec_value_type> r = nv_mtx.manager->renumbering;
// We need that to exchange the halo of unglued vectors (in coarse level consolidation)
Vector<ivec_value_type_h> nei = nv_mtx.manager->neighbors; // just neighbors before glue
std::vector<std::vector<VecInt_t> > b2lr = nv_mtx.manager->getB2Lrings(); //list of boundary nodes to export to other partitions.
Vector<ivec_value_type_h> ho = nv_mtx.manager->halo_offsets;
std::vector<IVector > b2lm = nv_mtx.manager->getB2Lmaps();
cudaCheckError();
// Create a fresh distributed manager
if (nv_mtx.manager != NULL )
{
delete nv_mtx.manager;
}
nv_mtx.manager = new DistributedManager<TConfig>(nv_mtx);
nv_mtx.set_initialized(0);
nv_mtx.delProps(DIAG);
// Load distributed matrix
MatrixDistribution mdist;
mdist.setPartitionVec(part_vec_ptr);
nv_mtx.manager->loadDistributedMatrix(n, nnz, block_dimx, block_dimy, r_ptr, i_ptr, (t_MatPrec *) v_ptr, num_ranks, n_global, NULL, mdist);
// Create B2L_maps for comm
nv_mtx.manager->renumberMatrixOneRing();
// WARNING WE SHOULD GET THE NUMBER OF RINGS AND DO THE FOLLOWING ONLY IF THERE ARE 2 RINGS
// Exchange 1 ring halo rows (for d2 interp)
// if (num_import_rings == 2)
nv_mtx.manager->createOneRingHaloRows();
nv_mtx.manager->getComms()->set_neighbors(nv_mtx.manager->num_neighbors());
nv_mtx.setView(OWNED);
nv_mtx.set_initialized(1);
cudaCheckError();
// restore some glue info to consolidate the vectors in the future
nv_mtx.manager->setDestinationPartitions(dest_partitions);
nv_mtx.manager->setIsRootPartition(is_root_partition);
nv_mtx.manager->setNumPartsToConsolidate(num_parts_to_consolidate);
nv_mtx.manager->setPartsToConsolidate(parts_to_consolidate);
nv_mtx.manager->setIsGlued(true);
nv_mtx.manager->setMyDestinationPartition(dest_part);
nv_mtx.manager->setConsolidationArrayOffsets(cao); // partions_offest before consolidation
// set fine level data structures, this is used to match the former distribution when we upload / download from the API
if (nv_mtx.amg_level_index == 0)
{
// just small copies inside fineLevelUpdate.
nv_mtx.manager->fineLevelUpdate();
}
nv_mtx.manager->renumbering_before_glue = r;
nv_mtx.manager->inverse_renumbering_before_glue = ir;
nv_mtx.manager->neighbors_before_glue = nei;
nv_mtx.manager->halo_offsets_before_glue = ho;
nv_mtx.manager->B2L_rings_before_glue = b2lr;
nv_mtx.manager->B2L_maps_before_glue = b2lm;
cudaCheckError();
return 0;
}
template<class TConfig>
int glue_vector(Matrix<TConfig> &nv_mtx, MPI_Comm &A_comm, Vector<TConfig> &nv_vec, MPI_Comm &temp_com)
{
// glu vecots based on dest_partitions (which contains partitions should be merged together)
typedef typename TConfig::IndPrec t_IndPrec;
typedef typename TConfig::VecPrec t_VecPrec;
int n, l, mpist, start, end, k = 0, root = 0, rank = 0;
//MPI call parameters
t_IndPrec *rc_ptr, *di_ptr;
t_VecPrec *hv_ptr, *hg_ptr, *v_ptr;
thrust::host_vector<t_IndPrec> rc;
thrust::host_vector<t_IndPrec> di;
//unreordered local vector on the host
thrust::host_vector<t_VecPrec> hv;
//constructed global vector on the host
thrust::host_vector<t_VecPrec> hg;
//constructed global vector on the device
device_vector_alloc<t_VecPrec> v;
//WARNING: this routine currently supports vectors only with block size =1 (it can be generalized in the future, though)
//initialize the defaults
mpist = MPI_SUCCESS;
if (nv_mtx.manager != NULL)
{
// some initializations
rank = nv_mtx.manager->global_id();
if (nv_mtx.manager->getComms() != NULL)
{
nv_mtx.manager->getComms()->get_mpi_comm();
}
n = nv_mtx.manager->getConsolidationArrayOffsets()[rank + 1] - nv_mtx.manager->getConsolidationArrayOffsets()[rank];
if (nv_mtx.manager->getConsolidationArrayOffsets().size() == 0)
{
std::cout << "ERROR part_offsets in glue path" << std::endl;
}
l = nv_mtx.manager->getNumPartsToConsolidate(); // number of partitions
//some allocations/resizing
hv.resize(nv_mtx.manager->renumbering_before_glue.size()); // host copy of nv_vec
if (nv_mtx.manager->isRootPartition())
{
// This works with neighbours only
hg.resize(nv_mtx.manager->getConsolidationArrayOffsets()[rank + l] - nv_mtx.manager->getConsolidationArrayOffsets()[rank]); // host copy of cvec
rc.resize(l);
di.resize(l);
}
cudaCheckError();
//--- unreorder the vector back (just like you did with the matrix, but only need to undo the interior-boundary reordering, because others do not apply) ---
// unreorder and copy the vector
// WARNING
// renumbering contains the inverse permutation to unreorder an amgx vector
// inverse_renumbering contains the permutaion to reorder an amgx vector
thrust::copy(thrust::make_permutation_iterator(nv_vec.begin(), nv_mtx.manager->renumbering_before_glue.begin() ),
thrust::make_permutation_iterator(nv_vec.begin(), nv_mtx.manager->renumbering_before_glue.begin() + nv_mtx.manager->renumbering_before_glue.size()),
hv.begin());
cudaCheckError();
hv.resize(n);
// --- construct global vector (rhs/sol) ---
//compute recvcounts and displacements for MPI_Gatherv
if (nv_mtx.manager->isRootPartition())
{
l = nv_mtx.manager->getNumPartsToConsolidate(); // number of partitions
//compute recvcounts and displacements for MPI_Gatherv
for (int i = 0; i < l; i++)
{
start = nv_mtx.manager->getConsolidationArrayOffsets()[nv_mtx.manager->getPartsToConsolidate()[i]];
end = nv_mtx.manager->getConsolidationArrayOffsets()[nv_mtx.manager->getPartsToConsolidate()[i] + 1];
rc[i] = end - start;
di[i] = k;
k += rc[i];
}
}
//alias raw pointers to thrust vector data (see thrust example unwrap_pointer for details)
rc_ptr = thrust::raw_pointer_cast(rc.data());
di_ptr = thrust::raw_pointer_cast(di.data());
hv_ptr = thrust::raw_pointer_cast(hv.data());
hg_ptr = thrust::raw_pointer_cast(hg.data());
cudaCheckError();
//gather (on the host)
if (typeid(t_VecPrec) == typeid(float))
{
mpist = MPI_Gatherv(hv_ptr, n, MPI_FLOAT, hg_ptr, rc_ptr, di_ptr, MPI_FLOAT, root, temp_com);
}
else if (typeid(t_VecPrec) == typeid(double))
{
mpist = MPI_Gatherv(hv_ptr, n, MPI_DOUBLE, hg_ptr, rc_ptr, di_ptr, MPI_DOUBLE, root, temp_com);
}
else
{
FatalError("MPI_Gatherv of the vector has failed - incorrect vector data type", AMGX_ERR_CORE);
}
if (mpist != MPI_SUCCESS)
{
FatalError("MPI_Gatherv of the vector has failed - detected incorrect MPI return code", AMGX_ERR_CORE);
}
// clean
nv_vec.in_transfer = IDLE;
//nv_vec.dirtybit = 0;
if (nv_vec.buffer != NULL)
{
delete nv_vec.buffer;
nv_vec.buffer = NULL;
nv_vec.buffer_size = 0;
}
if (nv_vec.linear_buffers_size != 0)
{
amgx::memory::cudaFreeHost(&(nv_vec.linear_buffers[0]));
nv_vec.linear_buffers_size = 0;
}
if (nv_vec.explicit_host_buffer)
{
amgx::memory::cudaFreeHost(nv_vec.explicit_host_buffer);
nv_vec.explicit_host_buffer = NULL;
nv_vec.explicit_buffer_size = 0;
cudaEventDestroy(nv_vec.mpi_event);
}
// resize
if (nv_mtx.manager->isRootPartition())
{
n = hg.size();
v.resize(hg.size());
thrust::copy(hg.begin(), hg.end(), v.begin());
cudaCheckError();
}
else
{
n = 0;
v.resize(0);
cudaCheckError();
}
// upload
v_ptr = thrust::raw_pointer_cast(v.data());
cudaCheckError();
upload_vector_after_glue(n, v_ptr, nv_vec, nv_mtx);
}
else
{
// ASSUMPTION: when manager has not been allocated you are running on a single rank
}
return 0;
}
template<class TConfig>
int upload_vector_after_glue(int n, void *v_ptr, Vector<TConfig> &nv_vec, Matrix<TConfig> &nv_mtx)
{
typedef typename TConfig::VecPrec t_VecPrec;
// vector bind
nv_vec.unsetManager();
cudaCheckError();
if (nv_mtx.manager != NULL)
{
nv_vec.setManager(*(nv_mtx.manager));
}
cudaCheckError();
if (nv_vec.is_transformed())
{
nv_vec.unset_transformed();
}
nv_vec.set_block_dimx(1);
nv_vec.set_block_dimy(nv_mtx.get_block_dimy());
// the dirtybit has to be set to one here in order to have correct results to ensure an exachange halo before the solve
// this is particulary important when the number of consolidated partitions is greater than 1 on large matrices such as drivaer9M
nv_vec.dirtybit = 1;
if (nv_mtx.manager != NULL)
{
nv_vec.getManager()->transformAndUploadVector(nv_vec, (t_VecPrec *)v_ptr, n, nv_vec.get_block_dimy());
}
MPI_Barrier(MPI_COMM_WORLD);
return 0;
}
template<class TConfig>
int unglue_vector(Matrix<TConfig> &nv_mtx, MPI_Comm &A_comm, Vector<TConfig> &nv_vec, MPI_Comm &temp_com, Vector<TConfig> &nv_vec_unglued)
{
// glue vecots based on dest_partitions (which contains partitions should be merged together)
typedef typename TConfig::IndPrec t_IndPrec;
typedef typename TConfig::VecPrec t_VecPrec;
int n_loc, l, mpist, start, end, k = 0, root = 0, rank = 0;
//MPI call parameters
t_IndPrec *sc_ptr, *di_ptr;
t_VecPrec *hv_ptr, *hg_ptr;
thrust::host_vector<t_IndPrec> sc;
thrust::host_vector<t_IndPrec> di;
//unreordered local vector on the host
thrust::host_vector<t_VecPrec> hv;
//constructed global vector on the host
thrust::host_vector<t_VecPrec> hg;
//constructed global vector on the device
device_vector_alloc<t_VecPrec> v;
//WARNING: this routine currently supports vectors only with block size =1 (it can be generalized in the future, though)
//initialize the defaults
mpist = MPI_SUCCESS;
if (nv_mtx.manager != NULL)
{
// some initializations
rank = nv_mtx.manager->global_id();
if (nv_mtx.manager->getComms() != NULL)
{
nv_mtx.manager->getComms()->get_mpi_comm();
}
n_loc = nv_mtx.manager->getConsolidationArrayOffsets()[rank + 1] - nv_mtx.manager->getConsolidationArrayOffsets()[rank];
if (nv_mtx.manager->getConsolidationArrayOffsets().size() == 0)
{
printf("ERROR part_offsets\n");
}
l = nv_mtx.manager->getNumPartsToConsolidate(); // number of partitions
//some allocations/resizing
hv.resize(n_loc); // host copy
if (nv_mtx.manager->isRootPartition())
{
hg.resize(nv_vec.size()); // host copy of cvec
}
sc.resize(l);
di.resize(l);
cudaCheckError();
// Exchange_halo before unreordering
// Do we need that?
nv_mtx.manager->exchange_halo(nv_vec, nv_vec.tag);
// unreorder the vector
if (nv_mtx.manager->isRootPartition())
{
// WARNING
// renumbering contains the inverse permutation to unreorder an amgx vector
// inverse_renumbering contains the permutaion to reorder an amgx vector
thrust::copy(thrust::make_permutation_iterator(nv_vec.begin(), nv_mtx.manager->renumbering.begin() ),
thrust::make_permutation_iterator(nv_vec.begin(), nv_mtx.manager->renumbering.begin() + nv_mtx.manager->renumbering.size()),
hg.begin());
cudaCheckError();
hg.resize(nv_mtx.manager->getConsolidationArrayOffsets()[rank + l] - nv_mtx.manager->getConsolidationArrayOffsets()[rank]);
}
// --- construct local vector (sol) ---
//compute sendcounts and displacements for MPI_Gatherv
for (int i = 0; i < l; i++)
{
start = nv_mtx.manager->getConsolidationArrayOffsets()[nv_mtx.manager->getPartsToConsolidate()[i]];
end = nv_mtx.manager->getConsolidationArrayOffsets()[nv_mtx.manager->getPartsToConsolidate()[i] + 1];
sc[i] = end - start;
di[i] = k;
k += sc[i];
}
//alias raw pointers to thrust vector data (see thrust example unwrap_pointer for details)
sc_ptr = thrust::raw_pointer_cast(sc.data());
di_ptr = thrust::raw_pointer_cast(di.data());
hv_ptr = thrust::raw_pointer_cast(hv.data());
hg_ptr = thrust::raw_pointer_cast(hg.data());
cudaCheckError();
// Scatter (on the host)
if (typeid(t_VecPrec) == typeid(float))
{
mpist = MPI_Scatterv(hg_ptr, sc_ptr, di_ptr, MPI_FLOAT, hv_ptr, n_loc, MPI_FLOAT, root, temp_com);
}
else if (typeid(t_VecPrec) == typeid(double))
{
mpist = MPI_Scatterv(hg_ptr, sc_ptr, di_ptr, MPI_DOUBLE, hv_ptr, n_loc, MPI_DOUBLE, root, temp_com);
}
else
{
FatalError("MPI_Gatherv of the vector has failed - incorrect vector data type", AMGX_ERR_CORE);
}
if (mpist != MPI_SUCCESS)
{
FatalError("MPI_Gatherv of the vector has failed - detected incorrect MPI return code", AMGX_ERR_CORE);
}
// --- Manual upload ---
// Cleaning
nv_vec_unglued.in_transfer = IDLE;
if (nv_vec_unglued.buffer != NULL)
{
delete nv_vec_unglued.buffer;
nv_vec_unglued.buffer = NULL;
nv_vec_unglued.buffer_size = 0;
}
if (nv_vec_unglued.linear_buffers_size != 0)
{
amgx::memory::cudaFreeHost(&(nv_vec_unglued.linear_buffers[0]));
nv_vec_unglued.linear_buffers_size = 0;
}
if (nv_vec_unglued.explicit_host_buffer)
{
amgx::memory::cudaFreeHost(nv_vec_unglued.explicit_host_buffer);
nv_vec_unglued.explicit_host_buffer = NULL;
nv_vec_unglued.explicit_buffer_size = 0;
cudaEventDestroy(nv_vec_unglued.mpi_event);
}
// We should avoid copies between nv_vec and hv here
nv_vec_unglued.resize( nv_mtx.manager->inverse_renumbering_before_glue.size());
thrust::fill( nv_vec_unglued.begin(), nv_vec_unglued.end(), 0.0 );
thrust::copy(hv.begin(), hv.end(), nv_vec_unglued.begin());
hv.resize( nv_mtx.manager->inverse_renumbering_before_glue.size());
cudaCheckError();
// Manual reordering
// Upload_vector_after_glue is not going to work because matrix managers has been modified during glued matrices, and don't match the new, glued, topology.
thrust::copy(thrust::make_permutation_iterator(nv_vec_unglued.begin(), nv_mtx.manager->inverse_renumbering_before_glue.begin() ),
thrust::make_permutation_iterator(nv_vec_unglued.begin(), nv_mtx.manager->inverse_renumbering_before_glue.begin() + nv_mtx.manager->inverse_renumbering_before_glue.size()),
hv.begin());
cudaCheckError();
thrust::fill( nv_vec_unglued.begin(), nv_vec_unglued.end(), 0.0 );
thrust::copy(hv.begin(), hv.end(), nv_vec_unglued.begin());
}
else
{
// ASSUMPTION: when manager has not been allocated you are running on a single rank
printf("Glue was called on a single rank\n");
}
return 0;
}
#if 0
// The folowing code is to perform an exhange halo using data that doesn't matches the topology of the matrix stored in its distributed manager
// We use instead other containers stored in the distributed manager. They are suffixed by "_before_glue"
// This allows to exchange vector halo between unglued vectors from glued matrices
template <class TConfig>
void exchange_halo_after_unglue(const Matrix<TConfig> &A, Vector<TConfig> &data, int tag, int num_ring = 1)
{
setup_after_unglue(data, A, num_ring); //set pointers to buffer
gather_B2L_after_unglue(A, data, num_ring); //write values to buffer
exchange_halo_after_unglue(data, A, num_ring); //exchange buffers
//scatter_L2H(data); //NULL op
}
/*
template <class TConfig>
void CommsMPIHostBufferStream<T_Config>::setup(DVector &b, const Matrix<TConfig> &m, int num_rings) { do_setup_after_unglue((b, m, num_rings);}
template <class T_Config>
void CommsMPIHostBufferStream<T_Config>::exchange_halo(DVector &b, const Matrix<TConfig> &m, cudaEvent_t event, int tag, int num_rings) { do_exchange_halo_after_unglue((b, m, num_rings);}
template <class T_Config>
void CommsMPIHostBufferStream<T_Config>::setup(FVector &b, const Matrix<TConfig> &m, int tag, int num_rings) { do_setup_after_unglue((b, m, num_rings);}
template <class T_Config>
void CommsMPIHostBufferStream<T_Config>::exchange_halo(FVector &b, const Matrix<TConfig> &m, cudaEvent_t event, int tag, int num_rings) { do_exchange_halo_after_unglue((b, m, num_rings);}
*/
template <class TConfig>
void setup_after_unglue(Vector<TConfig> &b, const Matrix<TConfig> &m, int num_rings)
{
/*
thrust::copy( m.manager->neighbors_before_glue.begin(), m.manager->neighbors_before_glue.end(), std::ostream_iterator<int64_t>(std::cout, " "));
thrust::copy( m.manager->halo_offsets_before_glue.begin(), m.manager->halo_offsets_before_glue.end(), std::ostream_iterator<int64_t>(std::cout, " "));
for (int i = 0; i < m.manager->B2L_rings_before_glue.size(); ++i)
{
thrust::copy( m.manager->B2L_rings_before_glue[i].begin(), m.manager->B2L_rings_before_glue[i].end(), std::ostream_iterator<int64_t>(std::cout, " "));
}
for (int i = 0; i < m.manager->B2L_maps_before_glue.size(); ++i)
{
thrust::copy( m.manager->B2L_maps_before_glue[i].begin(), m.manager->B2L_maps_before_glue[i].end(), std::ostream_iterator<int64_t>(std::cout, " "));
}
*/
if (TConfig::memSpace == AMGX_host)
{
FatalError("MPI Comms module no implemented for host", AMGX_ERR_NOT_IMPLEMENTED);
}
else
{
#ifdef AMGX_WITH_MPI
int bsize = b.get_block_size();
int num_cols = b.get_num_cols();
if (bsize != 1 && num_cols != 1)
FatalError("Error: vector cannot have block size and subspace size.",
AMGX_ERR_INTERNAL);
// set num neighbors = size of B2L_rings_before_glue
// need to do this because comms might have more neighbors than our matrix knows about
int neighbors = m.manager->B2L_rings_before_glue.size();
m.manager->getComms()->set_neighbors(m.manager->B2L_rings_before_glue.size());
if (b.in_transfer & SENDING)
{
b.in_transfer = IDLE;
}
typedef typename TConfig::template setVecPrec<(AMGX_VecPrecision)AMGX_GET_MODE_VAL(AMGX_MatPrecision, TConfig::mode)>::Type value_type;
b.requests.resize(2 * neighbors); //first part is sends second is receives
b.statuses.resize(2 * neighbors);
for (int i = 0; i < 2 * neighbors; i++)
{
b.requests[i] = MPI_REQUEST_NULL;
}
int total = 0;
for (int i = 0; i < neighbors; i++)
{
total += m.manager->B2L_rings_before_glue[i][num_rings] * bsize * num_cols;
}
b.buffer_size = total;
if (b.buffer == NULL)
{
b.buffer = new Vector<TConfig>(total);
}
else
{
if (total > b.buffer->size())
{
b.buffer->resize(total);
}
}
if (b.linear_buffers_size < neighbors)
{
if (b.linear_buffers_size != 0) { amgx::memory::cudaFreeHost(b.linear_buffers); }
amgx::memory::cudaMallocHost((void **) & (b.linear_buffers), neighbors * sizeof(value_type *));
b.linear_buffers_size = neighbors;
}
cudaCheckError();
total = 0;
bool linear_buffers_changed = false;
for (int i = 0; i < neighbors; i++)
{
if (b.linear_buffers[i] != b.buffer->raw() + total)
{
linear_buffers_changed = true;
}
b.linear_buffers[i] = b.buffer->raw() + total;
total += m.manager->B2L_rings_before_glue[i][num_rings] * bsize * num_cols;
}
// Copy to device
if (linear_buffers_changed)
{
b.linear_buffers_ptrs.resize(neighbors);
//thrust::copy(b.linear_buffers.begin(),b.linear_buffers.end(),b.linear_buffers_ptrs.begin());
cudaMemcpyAsync(thrust::raw_pointer_cast(&b.linear_buffers_ptrs[0]), &(b.linear_buffers[0]), neighbors * sizeof(value_type *), cudaMemcpyHostToDevice);
cudaCheckError();
}
int size = 0;
size = total + (m.manager->halo_offsets_before_glue[num_rings * neighbors] - m.manager->halo_offsets_before_glue[0]) * bsize * num_cols;
if (size > 0)
{
if (b.explicit_host_buffer == NULL)
{
b.host_buffer.resize(1);
cudaEventCreateWithFlags(&b.mpi_event, cudaEventDisableTiming);
cudaCheckError();
amgx::memory::cudaMallocHost((void **)&b.explicit_host_buffer, size * sizeof(value_type));
cudaCheckError();
}
else if (size > b.explicit_buffer_size)
{
amgx::memory::cudaFreeHost(b.explicit_host_buffer);
cudaCheckError();
amgx::memory::cudaMallocHost((void **)&b.explicit_host_buffer, size * sizeof(value_type));
cudaCheckError();
}
cudaCheckError();
b.explicit_buffer_size = size;
}
#else
FatalError("MPI Comms module requires compiling with MPI", AMGX_ERR_NOT_IMPLEMENTED);
#endif
}
}
template <class TConfig>
void gather_B2L_after_unglue(const Matrix<TConfig> &m, Vector<TConfig> &b, int num_rings = 1)
{
if (TConfig::memSpace == AMGX_host)
{
if (m.manager->neighbors_before_glue.size() > 0)
{
FatalError("Distributed solve only supported on devices", AMGX_ERR_NOT_IMPLEMENTED);
}
}
else
{
for (int i = 0; i < m.manager->neighbors_before_glue.size(); i++)
{
int size = m.manager->B2L_rings_before_glue[i][num_rings];
int num_blocks = min(4096, (size + 127) / 128);
if ( size != 0)
{
if (b.get_num_cols() == 1)
{
gatherToBuffer <<< num_blocks, 128>>>(b.raw(), m.manager->B2L_maps_before_glue[i].raw(), b.linear_buffers[i], b.get_block_size(), size);
}
else
{
gatherToBufferMultivector <<< num_blocks, 128>>>(b.raw(), m.manager->B2L_maps_before_glue[i].raw(), b.linear_buffers[i], b.get_num_cols(), b.get_lda(), size);
}
cudaCheckError();
}
}
}
}
template <class TConfig>
void exchange_halo_after_unglue(Vector<TConfig> &b, const Matrix<TConfig> &m, int num_rings)
{
if (TConfig::memSpace == AMGX_host)
{
FatalError("Halo exchanges not implemented for host", AMGX_ERR_NOT_IMPLEMENTED);
}
else
{
#ifdef AMGX_WITH_MPI
typedef typename TConfig::VecPrec VecPrec;
cudaCheckError();
int bsize = b.get_block_size();
int num_cols = b.get_num_cols();
int offset = 0;
int neighbors = m.manager->B2L_rings_before_glue.size();
MPI_Comm mpi_comm = m.manager->getComms()->get_mpi_comm();
if (b.buffer_size != 0)
{
cudaMemcpy(&(b.explicit_host_buffer[0]), b.buffer->raw(), b.buffer_size * sizeof(typename TConfig::VecPrec), cudaMemcpyDeviceToHost);
}
for (int i = 0; i < neighbors; i++)
{
int size = m.manager->B2L_rings_before_glue[i][num_rings] * bsize * num_cols;
if (size != 0)
{
MPI_Isend(&(b.explicit_host_buffer[offset]), size * sizeof(typename TConfig::VecPrec), MPI_BYTE, m.manager->neighbors_before_glue[i], m.manager->global_id(), mpi_comm, &b.requests[i]);
}
else
{
MPI_Isend(&(b.host_buffer[0]), size * sizeof(typename TConfig::VecPrec), MPI_BYTE, m.manager->neighbors_before_glue[i], m.manager->global_id(), mpi_comm, &b.requests[i]);
}
offset += size;
}
b.in_transfer = RECEIVING | SENDING;
offset = 0;
for (int i = 0; i < neighbors; i++)
{
// Count total size to receive from one neighbor
int size = 0;
for (int j = 0; j < num_rings; j++)
{
size += m.manager->halo_offsets_before_glue[j * neighbors + i + 1] * bsize * num_cols - m.manager->halo_offsets_before_glue[j * neighbors + i] * bsize * num_cols;
}
if (size != 0)
{
MPI_Irecv(&(b.explicit_host_buffer[b.buffer_size + offset]), size * sizeof(typename TConfig::VecPrec), MPI_BYTE, m.manager->neighbors_before_glue[i], m.manager->neighbors_before_glue[i], mpi_comm, &b.requests[neighbors + i]);
}
else
{
MPI_Irecv(&(b.host_buffer[0]), size * sizeof(typename TConfig::VecPrec), MPI_BYTE, m.manager->neighbors_before_glue[i], m.manager->neighbors_before_glue[i], mpi_comm, &b.requests[neighbors + i]);
}
offset += size;
int required_size = m.manager->halo_offsets_before_glue[0] * bsize * num_cols + offset;
if (required_size > b.size())
{
// happen because we have 2 ring
// required_size correspond to "n" in the FULL view of the unconsolidated matrix.
// In exchange halo this is a fatal error since it should never happen.
b.resize(required_size);
}
}
MPI_Waitall(2 * neighbors, &b.requests[0], /*&b.statuses[0]*/ MPI_STATUSES_IGNORE); //I only wait to receive data, I can start working before all my buffers were sent
b.dirtybit = 0;
b.in_transfer = IDLE;
// copy on host ring by ring
if (num_rings == 1)
{
if (num_cols == 1)
{
if (offset != 0)
{
cudaMemcpy(b.raw() + m.manager->halo_offsets_before_glue[0]*bsize, &(b.explicit_host_buffer[b.buffer_size]), offset * sizeof(typename TConfig::VecPrec), cudaMemcpyHostToDevice);
}
}
else
{
int lda = b.get_lda();
VecPrec *rank_start = &(b.explicit_host_buffer[b.buffer_size]);
for (int i = 0; i < neighbors; ++i)
{
int halo_size = m.manager->halo_offsets_before_glue[i + 1] - m.manager->halo_offsets_before_glue[i];
for (int s = 0; s < num_cols; ++s)
{
VecPrec *halo_start = b.raw() + lda * s + m.manager->halo_offsets_before_glue[i];
VecPrec *received_halo = rank_start + s * halo_size;
cudaMemcpy(halo_start, received_halo, halo_size * sizeof(VecPrec), cudaMemcpyHostToDevice);
}
rank_start += num_cols * halo_size;
}
}
}
else
{
if (num_cols == 1)
{
offset = 0;
// Copy into b, one neighbor at a time, one ring at a time
for (int i = 0 ; i < neighbors ; i++)
{
for (int j = 0; j < num_rings; j++)
{
int size = m.manager->halo_offsets_before_glue[j * neighbors + i + 1] * bsize - m.manager->halo_offsets_before_glue[j * neighbors + i] * bsize;
if (size != 0)
{
cudaMemcpy(b.raw() + m.manager->halo_offsets_before_glue[j * neighbors + i]*bsize, &(b.explicit_host_buffer[b.buffer_size + offset]), size * sizeof(typename TConfig::VecPrec), cudaMemcpyHostToDevice);
}
offset += size;
}
}
}
else
{
FatalError("num_rings != 1 && num_cols != 1 not supported\n", AMGX_ERR_NOT_IMPLEMENTED);
}
}
#else
FatalError("MPI Comms module requires compiling with MPI", AMGX_ERR_NOT_IMPLEMENTED);
#endif
}
}
#endif
// if 0
#endif
//MPI
} // namespace amgx | {
"alphanum_fraction": 0.6238848213,
"avg_line_length": 39.6737184703,
"ext": "h",
"hexsha": "7d8a47a67148565ba7cf880f8583f2498477c78f",
"lang": "C",
"max_forks_count": 112,
"max_forks_repo_forks_event_max_datetime": "2022-03-31T21:46:46.000Z",
"max_forks_repo_forks_event_min_datetime": "2017-10-16T11:00:10.000Z",
"max_forks_repo_head_hexsha": "5d2c8ab3d14b3fb16db35682336a1f96000698bb",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "neams-th-coe/nekRS",
"max_forks_repo_path": "3rd_party/AMGX/base/include/distributed/glue.h",
"max_issues_count": 143,
"max_issues_repo_head_hexsha": "5d2c8ab3d14b3fb16db35682336a1f96000698bb",
"max_issues_repo_issues_event_max_datetime": "2022-03-30T21:13:16.000Z",
"max_issues_repo_issues_event_min_datetime": "2017-10-18T10:30:34.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "neams-th-coe/nekRS",
"max_issues_repo_path": "3rd_party/AMGX/base/include/distributed/glue.h",
"max_line_length": 241,
"max_stars_count": 278,
"max_stars_repo_head_hexsha": "11af85608ea0f4720e03cbcc920521745f9e40e5",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "fizmat/AMGX",
"max_stars_repo_path": "base/include/distributed/glue.h",
"max_stars_repo_stars_event_max_datetime": "2022-03-27T03:54:04.000Z",
"max_stars_repo_stars_event_min_datetime": "2017-10-13T18:28:31.000Z",
"num_tokens": 12150,
"size": 48759
} |
#include <math.h>
#include <string.h>
#include <cblas.h>
#include "cnn.h"
#include "cnn_builtin_math.h"
#include "cnn_builtin_math_inline.h"
#include "cnn_config.h"
#include "cnn_init.h"
#include "cnn_macro.h"
#ifdef CNN_WITH_CUDA
#include <cuda_runtime.h>
#include "cnn_builtin_math_cu.h"
#endif
CNN_ACTIV_DEF((*cnn_activ_list[])) = {
cnn_softmax, //
cnn_relu, //
cnn_swish, //
cnn_sigmoid, //
cnn_tanh, //
cnn_gaussian, //
cnn_bent_identity, //
cnn_softplus, //
cnn_softsign, //
cnn_sinc, //
cnn_sinusoid, //
cnn_identity //
};
CNN_ACTIV_GRAD_DEF((*cnn_activ_grad_list[])) = {
cnn_softmax_grad, //
cnn_relu_grad, //
cnn_swish_grad, //
cnn_sigmoid_grad, //
cnn_tanh_grad, //
cnn_gaussian_grad, //
cnn_bent_identity_grad, //
cnn_softplus_grad, //
cnn_softsign_grad, //
cnn_sinc_grad, //
cnn_sinusoid_grad, //
cnn_identity_grad //
};
const char* cnn_activ_name[] = {
"Softmax", //
"ReLU", //
"Swish", //
"Sigmoid", //
"Hyperbolic Tangent", //
"Gaussian", //
"Bent Identity", //
"SoftPlus", //
"SoftSign", //
"Sinc", //
"Sinusoid", //
"Identity" //
};
CNN_ACTIV_DEF(cnn_softmax)
{
float max, sum;
#ifdef CNN_WITH_CUDA
// Find max value
cnn_max_gpu(&max, src, len, buf);
// Find shifted vector
cnn_add_gpu(buf, src, len, -max);
// Find exponential vector
cnn_exp_gpu(buf, buf, len);
// Find sum
cnn_sum_gpu(&sum, buf, len, dst);
// Find softmax
cnn_div_gpu(dst, buf, len, sum);
#else
int i;
// Find max value
max = src[0];
for (i = 1; i < len; i++)
{
if (src[i] > max)
{
max = src[i];
}
}
// Find exponential summation
sum = 0;
for (i = 0; i < len; i++)
{
dst[i] = src[i] - max;
sum += exp(dst[i]);
}
// Find softmax output
for (i = 0; i < len; i++)
{
dst[i] = exp(dst[i]) / sum;
}
#endif
}
CNN_ACTIV_GRAD_DEF(cnn_softmax_grad)
{
#ifdef CNN_WITH_CUDA
float alpha = 1.0;
float beta = 0.0;
// Find derivative matrix
cnn_smax_grad_gpu(buf, cache, len);
// Find layer gradient
cnn_assert_cu(cublasSgemm(cnnInit.blasHandle, CUBLAS_OP_N, CUBLAS_OP_N, //
len, 1, len, //
&alpha, //
buf, len, //
gradIn, len, //
&beta, //
gradOut, len));
#else
int i, j;
// Find softmax gradient matrix
for (i = 0; i < len; i++)
{
for (j = 0; j < len; j++)
{
buf[i * len + j] = cache[i] * ((float)(i == j) - cache[j]);
}
}
// Find layer gradient
cblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, //
1, len, len, //
1.0, //
gradIn, len, //
buf, len, //
0.0, //
gradOut, len);
#endif
}
CNN_ACTIV_DEF(cnn_relu)
{
#ifdef CNN_WITH_CUDA
cnn_relu_gpu(dst, src, len);
#else
#pragma omp parallel for
for (int i = 0; i < len; i++)
{
__cnn_relu(dst + i, src + i);
}
#endif
}
CNN_ACTIV_GRAD_DEF(cnn_relu_grad)
{
#ifdef CNN_WITH_CUDA
cnn_relu_grad_gpu(gradOut, gradIn, src, len, cache);
#else
// Find relu gradient
#pragma omp parallel for
for (int i = 0; i < len; i++)
{
__cnn_relu_grad(gradOut + i, gradIn + i, src + i, NULL);
}
#endif
}
CNN_ACTIV_DEF(cnn_swish)
{
#ifdef CNN_WITH_CUDA
cnn_swish_gpu(dst, src, len);
#else
#pragma omp parallel for
for (int i = 0; i < len; i++)
{
__cnn_swish(dst + i, src + i);
}
#endif
}
CNN_ACTIV_GRAD_DEF(cnn_swish_grad)
{
#ifdef CNN_WITH_CUDA
cnn_swish_grad_gpu(gradOut, gradIn, src, len, cache);
#else
// Find swish gradient
#pragma omp parallel for
for (int i = 0; i < len; i++)
{
__cnn_swish_grad(gradOut + i, gradIn + i, src + i, cache + i);
}
#endif
}
CNN_ACTIV_DEF(cnn_sigmoid)
{
#ifdef CNN_WITH_CUDA
cnn_sigmoid_gpu(dst, src, len);
#else
#pragma omp parallel for
for (int i = 0; i < len; i++)
{
__cnn_sigmoid(dst + i, src + i);
}
#endif
}
CNN_ACTIV_GRAD_DEF(cnn_sigmoid_grad)
{
#ifdef CNN_WITH_CUDA
cnn_sigmoid_grad_gpu(gradOut, gradIn, src, len, cache);
#else
// Find sigmoid gradient
#pragma omp parallel for
for (int i = 0; i < len; i++)
{
__cnn_sigmoid_grad(gradOut + i, gradIn + i, NULL, cache + i);
}
#endif
}
CNN_ACTIV_DEF(cnn_tanh)
{
#ifdef CNN_WITH_CUDA
cnn_tanh_gpu(dst, src, len);
#else
#pragma omp parallel
for (int i = 0; i < len; i++)
{
__cnn_tanh(dst + i, src + i);
}
#endif
}
CNN_ACTIV_GRAD_DEF(cnn_tanh_grad)
{
#ifdef CNN_WITH_CUDA
cnn_tanh_grad_gpu(gradOut, gradIn, src, len, cache);
#else
// Find tanh gradient
#pragma omp parallel for
for (int i = 0; i < len; i++)
{
__cnn_tanh_grad(gradOut + i, gradIn + i, NULL, cache + i);
}
#endif
}
CNN_ACTIV_DEF(cnn_gaussian)
{
#ifdef CNN_WITH_CUDA
cnn_gaussian_gpu(dst, src, len);
#else
#pragma omp parallel
for (int i = 0; i < len; i++)
{
__cnn_gaussian(dst + i, src + i);
}
#endif
}
CNN_ACTIV_GRAD_DEF(cnn_gaussian_grad)
{
#ifdef CNN_WITH_CUDA
cnn_gaussian_grad_gpu(gradOut, gradIn, src, len, cache);
#else
// Find gaussian gradient
#pragma omp parallel for
for (int i = 0; i < len; i++)
{
__cnn_gaussian_grad(gradOut + i, gradIn + i, src + i, cache + i);
}
#endif
}
CNN_ACTIV_DEF(cnn_bent_identity)
{
#ifdef CNN_WITH_CUDA
cnn_bent_identity_gpu(dst, src, len);
#else
#pragma omp parallel for
for (int i = 0; i < len; i++)
{
__cnn_bent_identity(dst + i, src + i);
}
#endif
}
CNN_ACTIV_GRAD_DEF(cnn_bent_identity_grad)
{
#ifdef CNN_WITH_CUDA
cnn_bent_identity_grad_gpu(gradOut, gradIn, src, len, cache);
#else
// Find bent indentity gradient
#pragma omp parallel for
for (int i = 0; i < len; i++)
{
__cnn_bent_identity_grad(gradOut + i, gradIn + i, src + i, NULL);
}
#endif
}
CNN_ACTIV_DEF(cnn_softplus)
{
#ifdef CNN_WITH_CUDA
cnn_softplus_gpu(dst, src, len);
#else
#pragma omp parallel for
for (int i = 0; i < len; i++)
{
__cnn_softplus(dst + i, src + i);
}
#endif
}
CNN_ACTIV_GRAD_DEF(cnn_softplus_grad)
{
#ifdef CNN_WITH_CUDA
cnn_softplus_grad_gpu(gradOut, gradIn, src, len, cache);
#else
// Find softplus gradient
#pragma omp parallel for
for (int i = 0; i < len; i++)
{
__cnn_softplus_grad(gradOut + i, gradIn + i, src + i, NULL);
}
#endif
}
CNN_ACTIV_DEF(cnn_softsign)
{
#ifdef CNN_WITH_CUDA
cnn_softsign_gpu(dst, src, len);
#else
#pragma omp parallel for
for (int i = 0; i < len; i++)
{
__cnn_softsign(dst + i, src + i);
}
#endif
}
CNN_ACTIV_GRAD_DEF(cnn_softsign_grad)
{
#ifdef CNN_WITH_CUDA
cnn_softsign_grad_gpu(gradOut, gradIn, src, len, cache);
#else
// Find softsign gradient
#pragma omp parallel for
for (int i = 0; i < len; i++)
{
__cnn_softsign_grad(gradOut + i, gradIn + i, src + i, NULL);
}
#endif
}
CNN_ACTIV_DEF(cnn_sinc)
{
#ifdef CNN_WITH_CUDA
cnn_sinc_gpu(dst, src, len);
#else
#pragma omp parallel for
for (int i = 0; i < len; i++)
{
__cnn_sinc(dst + i, src + i);
}
#endif
}
CNN_ACTIV_GRAD_DEF(cnn_sinc_grad)
{
#ifdef CNN_WITH_CUDA
cnn_sinc_grad_gpu(gradOut, gradIn, src, len, cache);
#else
// Find sinc gradient
#pragma omp parallel for
for (int i = 0; i < len; i++)
{
__cnn_sinc_grad(gradOut + i, gradIn + i, src + i, NULL);
}
#endif
}
CNN_ACTIV_DEF(cnn_sinusoid)
{
#ifdef CNN_WITH_CUDA
cnn_sin_gpu(dst, src, len);
#else
#pragma omp parallel for
for (int i = 0; i < len; i++)
{
__cnn_sinusoid(dst + i, src + i);
}
#endif
}
CNN_ACTIV_GRAD_DEF(cnn_sinusoid_grad)
{
#ifdef CNN_WITH_CUDA
cnn_sin_grad_gpu(gradOut, gradIn, src, len, cache);
#else
// Find sinusoid gradient
#pragma omp parallel for shared(gradOut, gradIn, src)
for (int i = 0; i < len; i++)
{
__cnn_sinusoid_grad(gradOut + i, gradIn + i, src + i, NULL);
}
#endif
}
CNN_ACTIV_DEF(cnn_identity)
{
#ifdef CNN_WITH_CUDA
cnn_identity_gpu(dst, src, len);
#else
#pragma omp parallel for
for (int i = 0; i < len; i++)
{
__cnn_identity(dst + i, src + i);
}
#endif
}
CNN_ACTIV_GRAD_DEF(cnn_identity_grad)
{
#ifdef CNN_WITH_CUDA
cnn_identity_grad_gpu(gradOut, gradIn, src, len, cache);
#else
// Find identity gradient
#pragma omp parallel for
for (int i = 0; i < len; i++)
{
__cnn_identity_grad(gradOut + i, gradIn + i, NULL, NULL);
}
#endif
}
int cnn_get_activ_id(const char* name)
{
int i;
int ret = CNN_PARSE_FAILED;
if (name != NULL)
{
for (i = 0; i < CNN_ACTIV_AMOUNT; i++)
{
ret = strcmp(name, cnn_activ_name[i]);
if (ret == 0)
{
ret = i;
goto RET;
}
}
}
RET:
return ret;
}
| {
"alphanum_fraction": 0.5420789554,
"avg_line_length": 20.8574468085,
"ext": "c",
"hexsha": "5a82313ac036b6741264beb3d0dce42d17db1fe9",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "8ba35edd4516f6b46a17a1bad672e38667600630",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "jamesljlster/cnn",
"max_forks_repo_path": "src/cnn_builtin_math.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "8ba35edd4516f6b46a17a1bad672e38667600630",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "jamesljlster/cnn",
"max_issues_repo_path": "src/cnn_builtin_math.c",
"max_line_length": 79,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "8ba35edd4516f6b46a17a1bad672e38667600630",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "jamesljlster/cnn",
"max_stars_repo_path": "src/cnn_builtin_math.c",
"max_stars_repo_stars_event_max_datetime": "2020-06-15T07:47:10.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-06-15T07:47:10.000Z",
"num_tokens": 2797,
"size": 9803
} |
/* Odeint solver */
#include <pygsl/utils.h>
#include <pygsl/block_helpers.h>
#include <pygsl/error_helpers.h>
#include <Python.h>
#include <gsl/gsl_odeiv.h>
#include <gsl/gsl_errno.h>
char odeiv_module_doc[] = "XXX odeiv module doc missing!\n";
static char this_file[] = __FILE__;
static PyObject *module = NULL; /* set by initodeiv */
#if 0
static void /* generic instance destruction */
generic_dealloc (PyObject *self)
{
DEBUG_MESS(1, " *** generic_dealloc %p\n", (void *) self);
PyMem_Free(self);
}
#endif
typedef struct {
PyObject_HEAD
gsl_odeiv_step * step;
gsl_odeiv_system system;
PyObject *py_func;
PyObject *py_jac;
PyObject *arguments;
jmp_buf buffer;
}
PyGSL_odeiv_step;
typedef struct {
PyObject_HEAD
PyGSL_odeiv_step * step;
gsl_odeiv_control * control;
} PyGSL_odeiv_control;
typedef struct {
PyObject_HEAD
PyGSL_odeiv_step * step;
PyGSL_odeiv_control * control;
gsl_odeiv_evolve * evolve;
} PyGSL_odeiv_evolve;
/*---------------------------------------------------------------------------
* Declaration of the various Methods
*---------------------------------------------------------------------------*/
/*
* stepper
*/
static int
PyGSL_odeiv_func(double t, const double y[], double f[], void *params);
static int
PyGSL_odeiv_jac(double t, const double y[], double *dfdy, double dfdt[],
void *params);
static PyObject *
PyGSL_odeiv_step_apply(PyGSL_odeiv_step *self, PyObject *args);
static PyObject *
PyGSL_odeiv_step_reset(PyGSL_odeiv_step *self, PyObject *args);
static PyObject *
PyGSL_odeiv_step_name(PyGSL_odeiv_step *self, PyObject *args);
static PyObject *
PyGSL_odeiv_step_order(PyGSL_odeiv_step *self, PyObject *args);
static void
PyGSL_odeiv_step_free(PyGSL_odeiv_step * self);
/*
* control
*/
static PyObject *
PyGSL_odeiv_control_hadjust(PyGSL_odeiv_control *self, PyObject *args);
static PyObject *
PyGSL_odeiv_control_name(PyGSL_odeiv_control *self, PyObject *args);
static void
PyGSL_odeiv_control_free(PyGSL_odeiv_control * self);
/*
* evolve
*/
static PyObject *
PyGSL_odeiv_evolve_apply(PyGSL_odeiv_evolve *self, PyObject *args);
static PyObject *
PyGSL_odeiv_evolve_apply_array(PyGSL_odeiv_evolve *self, PyObject *args);
static PyObject *
PyGSL_odeiv_evolve_reset(PyGSL_odeiv_evolve *self, PyObject *args);
static void
PyGSL_odeiv_evolve_free(PyGSL_odeiv_evolve * self);
/*---------------------------------------------------------------------------*/
static char PyGSL_odeiv_step_doc[] = "XXX Documentation missing\n";
static char PyGSL_odeiv_control_doc[] = "XXX Documentation missing\n";
static char PyGSL_odeiv_evolve_doc[] = "XXX Documentation missing\n";
static char odeiv_step_apply_doc[] = "XXX Documentation missing\n";
static char odeiv_step_name_doc[] = "XXX Documentation missing\n";
static char odeiv_step_order_doc[] = "XXX Documentation missing\n";
static char odeiv_step_reset_doc[] = "XXX Documentation missing\n";
static char odeiv_control_name_doc[] = "XXX Documentation missing\n";
static char odeiv_control_hadjust_doc[] = "XXX Documentation missing\n";
static char odeiv_evolve_apply_doc[] = "XXX Documentation missing\n";
static char odeiv_evolve_apply_array_doc[] = "XXX Documentation missing\n";
static char odeiv_evolve_reset_doc[] = "XXX Documentation missing\n";
static char * odeiv_step_init_err_msg = "odeiv_step.__init__";
static struct PyMethodDef PyGSL_odeiv_step_methods[] = {
{"apply", (PyCFunction) PyGSL_odeiv_step_apply, METH_VARARGS, odeiv_step_apply_doc},
{"reset", (PyCFunction) PyGSL_odeiv_step_reset, METH_VARARGS, odeiv_step_reset_doc},
{"name", (PyCFunction) PyGSL_odeiv_step_name, METH_VARARGS, odeiv_step_name_doc},
{"order", (PyCFunction) PyGSL_odeiv_step_order, METH_VARARGS, odeiv_step_order_doc},
{NULL, NULL}
};
static struct PyMethodDef PyGSL_odeiv_control_methods[] = {
{"hadjust", (PyCFunction) PyGSL_odeiv_control_hadjust, METH_VARARGS, odeiv_control_hadjust_doc},
{"name", (PyCFunction) PyGSL_odeiv_control_name, METH_VARARGS, odeiv_control_name_doc},
{NULL, NULL}
};
static struct PyMethodDef PyGSL_odeiv_evolve_methods[] = {
{"apply", (PyCFunction) PyGSL_odeiv_evolve_apply, METH_VARARGS, odeiv_evolve_apply_doc},
{"reset", (PyCFunction) PyGSL_odeiv_evolve_reset, METH_VARARGS, odeiv_evolve_reset_doc},
{"apply_array", (PyCFunction) PyGSL_odeiv_evolve_apply_array, METH_VARARGS, odeiv_evolve_apply_array_doc},
{NULL, NULL}
};
#define PyGSL_ODEIV_GENERIC_ALL \
static PyObject * \
PyGSL_ODEIV_GENERIC_GETATTR(PyGSL_ODEIV_GENERIC *self, char *name) \
{ \
PyObject *tmp = NULL; \
\
FUNC_MESS_BEGIN(); \
tmp = Py_FindMethod(PyGSL_ODEIV_GENERIC_METHODS, (PyObject *) self, name); \
if(NULL == tmp){ \
PyGSL_add_traceback(module, __FILE__, "odeiv.__attr__", __LINE__ - 1); \
return NULL; \
} \
FUNC_MESS_END(); \
return tmp; \
} \
static PyTypeObject PyGSL_ODEIV_GENERIC_PYTYPE = { \
PyObject_HEAD_INIT(NULL) /* fix up the type slot in initcrng */ \
0, /* ob_size */ \
PyGSL_ODEIV_GENERIC_NAME, /* tp_name */ \
sizeof(PyGSL_ODEIV_GENERIC), /* tp_basicsize */ \
0, /* tp_itemsize */ \
\
/* standard methods */ \
(destructor) PyGSL_ODEIV_GENERIC_DELETE, /* tp_dealloc ref-count==0 */ \
(printfunc) 0, /* tp_print "print x" */ \
(getattrfunc) PyGSL_ODEIV_GENERIC_GETATTR, /* tp_getattr "x.attr" */ \
(setattrfunc) 0, /* tp_setattr "x.attr=v" */ \
(cmpfunc) 0, /* tp_compare "x > y" */ \
(reprfunc) 0, /* tp_repr `x`, print x */ \
\
/* type categories */ \
0, /* tp_as_number +,-,*,/,%,&,>>,pow...*/ \
0, /* tp_as_sequence +,[i],[i:j],len, ...*/ \
0, /* tp_as_mapping [key], len, ...*/ \
\
/* more methods */ \
(hashfunc) 0, /* tp_hash "dict[x]" */ \
(ternaryfunc) 0, /* tp_call "x()" */ \
(reprfunc) 0, /* tp_str "str(x)" */ \
(getattrofunc) 0, /* tp_getattro */ \
(setattrofunc) 0, /* tp_setattro */ \
0, /* tp_as_buffer */ \
0L, /* tp_flags */ \
PyGSL_ODEIV_GENERIC_DOC /* doc */ \
};
#define PyGSL_ODEIV_GENERIC PyGSL_odeiv_step
#define PyGSL_ODEIV_GENERIC_NAME "PyGSL_odeiv_step"
#define PyGSL_ODEIV_GENERIC_PYTYPE PyGSL_odeiv_step_pytype
#define PyGSL_ODEIV_GENERIC_DOC PyGSL_odeiv_step_doc
#define PyGSL_ODEIV_GENERIC_GETATTR PyGSL_odeiv_step_getattr
#define PyGSL_ODEIV_GENERIC_METHODS PyGSL_odeiv_step_methods
#define PyGSL_ODEIV_GENERIC_DELETE PyGSL_odeiv_step_free
PyGSL_ODEIV_GENERIC_ALL
/**/;
#undef PyGSL_ODEIV_GENERIC
#undef PyGSL_ODEIV_GENERIC_NAME
#undef PyGSL_ODEIV_GENERIC_PYTYPE
#undef PyGSL_ODEIV_GENERIC_DOC
#undef PyGSL_ODEIV_GENERIC_GETATTR
#undef PyGSL_ODEIV_GENERIC_METHODS
#undef PyGSL_ODEIV_GENERIC_DELETE
#define PyGSL_ODEIV_GENERIC PyGSL_odeiv_control
#define PyGSL_ODEIV_GENERIC_NAME "PyGSL_odeiv_control"
#define PyGSL_ODEIV_GENERIC_PYTYPE PyGSL_odeiv_control_pytype
#define PyGSL_ODEIV_GENERIC_DOC PyGSL_odeiv_control_doc
#define PyGSL_ODEIV_GENERIC_GETATTR PyGSL_odeiv_control_getattr
#define PyGSL_ODEIV_GENERIC_METHODS PyGSL_odeiv_control_methods
#define PyGSL_ODEIV_GENERIC_DELETE PyGSL_odeiv_control_free
PyGSL_ODEIV_GENERIC_ALL
/**/;
#undef PyGSL_ODEIV_GENERIC
#undef PyGSL_ODEIV_GENERIC_NAME
#undef PyGSL_ODEIV_GENERIC_PYTYPE
#undef PyGSL_ODEIV_GENERIC_DOC
#undef PyGSL_ODEIV_GENERIC_GETATTR
#undef PyGSL_ODEIV_GENERIC_METHODS
#undef PyGSL_ODEIV_GENERIC_DELETE
#define PyGSL_ODEIV_GENERIC PyGSL_odeiv_evolve
#define PyGSL_ODEIV_GENERIC_NAME "PyGSL_odeiv_evolve"
#define PyGSL_ODEIV_GENERIC_PYTYPE PyGSL_odeiv_evolve_pytype
#define PyGSL_ODEIV_GENERIC_DOC PyGSL_odeiv_evolve_doc
#define PyGSL_ODEIV_GENERIC_GETATTR PyGSL_odeiv_evolve_getattr
#define PyGSL_ODEIV_GENERIC_METHODS PyGSL_odeiv_evolve_methods
#define PyGSL_ODEIV_GENERIC_DELETE PyGSL_odeiv_evolve_free
PyGSL_ODEIV_GENERIC_ALL
/**/;
#define PyGSL_ODEIV_STEP_Check(v) ((v)->ob_type == &PyGSL_odeiv_step_pytype)
#define PyGSL_ODEIV_CONTROL_Check(v) ((v)->ob_type == &PyGSL_odeiv_control_pytype)
#define PyGSL_ODEIV_EVOLVE_Check(v) ((v)->ob_type == &PyGSL_odeiv_evolve_pytype)
/*---------------------------------------------------------------------------
Wrapper functions to push call the approbriate Python Objects
---------------------------------------------------------------------------*/
static int
PyGSL_odeiv_func(double t, const double y[], double f[], void *params)
{
int dimension, flag = GSL_FAILURE;
PyObject *arglist = NULL, *result = NULL;
PyArrayObject *yo = NULL;
PyGSL_odeiv_step * step;
gsl_vector_view yv, fv;
PyGSL_error_info info;
FUNC_MESS_BEGIN();
step = (PyGSL_odeiv_step *) params;
if(!PyGSL_ODEIV_STEP_Check(step)){
PyGSL_add_traceback(module, this_file, __FUNCTION__,
__LINE__ - 2);
gsl_error("Param not a step type!",
this_file, __LINE__ -2, GSL_EFAULT);
goto fail;
}
dimension = step->system.dimension;
/* Do I need to copy the array ??? */
yv = gsl_vector_view_array((double *) y, dimension);
yo = PyGSL_copy_gslvector_to_pyarray(&yv.vector);
if (yo == NULL) goto fail;
FUNC_MESS("\t\tBuild args");
arglist = Py_BuildValue("(dOO)", t, yo, step->arguments);
FUNC_MESS("\t\tEnd Build args");
info.callback = step->py_func;
info.message = "odeiv_func";
result = PyEval_CallObject(step->py_func, arglist);
if((flag = PyGSL_CHECK_PYTHON_RETURN(result, 1, &info)) != GSL_SUCCESS){
goto fail;
}
info.argnum = 1;
fv = gsl_vector_view_array(f, dimension);
if((flag = PyGSL_copy_pyarray_to_gslvector(&fv.vector, result, dimension,
&info)) != GSL_SUCCESS){
goto fail;
}
Py_DECREF(arglist); arglist = NULL;
Py_DECREF(yo); yo = NULL;
Py_DECREF(result); result = NULL;
FUNC_MESS_END();
return GSL_SUCCESS;
fail:
FUNC_MESS(" IN Fail BEGIN");
Py_XDECREF(yo);
Py_XDECREF(result);
Py_XDECREF(arglist);
FUNC_MESS(" IN Fail END");
assert(flag != GSL_SUCCESS);
longjmp(step->buffer, flag);
return flag;
}
static int
PyGSL_odeiv_jac(double t, const double y[], double *dfdy, double dfdt[],
void *params)
{
int dimension, flag = GSL_FAILURE;
PyGSL_odeiv_step *step = NULL;
PyGSL_error_info info;
PyObject *arglist = NULL, *result = NULL, *tmp=NULL;
PyArrayObject *yo = NULL;
gsl_vector_view yv, dfdtv;
gsl_matrix_view dfdyv;
FUNC_MESS_BEGIN();
step = (PyGSL_odeiv_step *) params;
if(!PyGSL_ODEIV_STEP_Check(step)){
PyGSL_add_traceback(module, this_file, __FUNCTION__,
__LINE__ - 2);
gsl_error("Param not a step type!",
this_file, __LINE__ -2, GSL_EFAULT);
goto fail;
}
dimension = step->system.dimension;
yv = gsl_vector_view_array((double *) y, dimension);
yo = PyGSL_copy_gslvector_to_pyarray(&yv.vector);
if (yo == NULL) goto fail;
arglist = Py_BuildValue("(dOO)", t, yo, step->arguments);
assert(step->py_jac);
result = PyEval_CallObject(step->py_jac, arglist);
info.callback = step->py_jac;
info.message = "odeiv_jac";
if((flag = PyGSL_CHECK_PYTHON_RETURN(result, 2, &info)) != GSL_SUCCESS){
goto fail;
}
info.argnum = 1;
tmp = PyTuple_GET_ITEM(result, 0);
dfdyv = gsl_matrix_view_array((double *) dfdy, dimension, dimension);
if((flag = PyGSL_copy_pyarray_to_gslmatrix(&dfdyv.matrix, tmp, dimension, dimension, &info)) != GSL_SUCCESS){
goto fail;
}
info.argnum = 2;
tmp = PyTuple_GET_ITEM(result, 1);
dfdtv = gsl_vector_view_array((double *) dfdt, dimension);
if((flag = PyGSL_copy_pyarray_to_gslvector(&dfdtv.vector, tmp, dimension, &info)) != GSL_SUCCESS){
goto fail;
}
Py_DECREF(arglist); arglist = NULL;
Py_DECREF(result); result = NULL;
Py_DECREF(yo); yo = NULL;
FUNC_MESS_END();
return GSL_SUCCESS;
fail:
FUNC_MESS("IN Fail");
assert(flag != GSL_SUCCESS);
longjmp(step->buffer, flag);
return flag;
}
/* Wrappers for the evaluation of the system */
static PyObject *
PyGSL_odeiv_step_apply(PyGSL_odeiv_step *self, PyObject *args)
{
PyObject *result = NULL;
PyObject *y0_o = NULL, *dydt_in_o = NULL;
PyArrayObject *volatile y0 = NULL, * volatile yerr = NULL,
*volatile dydt_in = NULL, *volatile dydt_out = NULL,
*volatile yout = NULL;
double t=0, h=0, *volatile dydt_in_d;
int dimension, r, flag;
FUNC_MESS_BEGIN();
assert(PyGSL_ODEIV_STEP_Check(self));
if(! PyArg_ParseTuple(args, "ddOOO", &t, &h, &y0_o, &dydt_in_o)){
return NULL;
}
dimension = self->system.dimension;
y0 = PyGSL_PyArray_PREPARE_gsl_vector_view(y0_o, PyArray_DOUBLE, 1, dimension, 1, NULL);
if(y0 == NULL) goto fail;
if (Py_None == dydt_in_o){
dydt_in_d = NULL;
}else{
dydt_in = PyGSL_PyArray_PREPARE_gsl_vector_view(dydt_in_o, PyArray_DOUBLE, 1, dimension, 2, NULL);
if(dydt_in == NULL) goto fail;
dydt_in_d = (double *) dydt_in->data;
}
dydt_out = (PyArrayObject *) PyArray_FromDims(1, &dimension, PyArray_DOUBLE);
if (dydt_out == NULL) goto fail;
yerr = (PyArrayObject *) PyArray_FromDims(1, &dimension, PyArray_DOUBLE);
if(yerr == NULL) goto fail;
yout = (PyArrayObject *) PyArray_CopyFromObject((PyObject * ) y0, PyArray_DOUBLE, 1, 1);
if(yout == NULL) goto fail;
if((flag=setjmp(self->buffer)) == 0){
FUNC_MESS("\t\t Setting Jmp Buffer");
} else {
FUNC_MESS("\t\t Returning from Jmp Buffer");
goto fail;
}
r = gsl_odeiv_step_apply(self->step, t, h,
(double *) yout->data,
(double *) yerr->data,
dydt_in_d,
(double *) dydt_out->data,
&(self->system));
if (GSL_SUCCESS != r){
PyErr_SetString(PyExc_TypeError, "Error While evaluating gsl_odeiv");
goto fail;
}
FUNC_MESS(" Returnlist create ");
assert(yout != NULL);
assert(yerr != NULL);
assert(dydt_out != NULL);
result = Py_BuildValue("(OOO)", yout, yerr, dydt_out);
FUNC_MESS(" Memory free ");
/* Deleting the arrays */
Py_DECREF(y0); y0 = NULL;
Py_DECREF(yout); yout = NULL;
Py_DECREF(yerr); yerr = NULL;
Py_DECREF(dydt_out); dydt_out = NULL;
/* This array does not need to exist ... */
Py_XDECREF(dydt_in); dydt_in=NULL;
FUNC_MESS_END();
return result;
fail:
FUNC_MESS("IN Fail");
Py_XDECREF(y0);
Py_XDECREF(yout);
Py_XDECREF(yerr);
Py_XDECREF(dydt_in);
Py_XDECREF(dydt_out);
FUNC_MESS("IN Fail End");
return NULL;
}
static void
PyGSL_odeiv_step_free(PyGSL_odeiv_step * self)
{
assert(PyGSL_ODEIV_STEP_Check(self));
Py_DECREF(self->py_func);
Py_XDECREF(self->py_jac);
Py_DECREF(self->arguments);
gsl_odeiv_step_free(self->step);
PyMem_Free(self);
}
static PyObject *
PyGSL_odeiv_step_reset(PyGSL_odeiv_step *self, PyObject *args)
{
assert(PyGSL_ODEIV_STEP_Check(self));
gsl_odeiv_step_reset(self->step);
Py_INCREF(Py_None);
return Py_None;
}
static PyObject *
PyGSL_odeiv_step_name(PyGSL_odeiv_step *self, PyObject *args)
{
assert(PyGSL_ODEIV_STEP_Check(self));
return PyString_FromString(gsl_odeiv_step_name(self->step));
}
static PyObject *
PyGSL_odeiv_step_order(PyGSL_odeiv_step *self, PyObject *args)
{
assert(PyGSL_ODEIV_STEP_Check(self));
return PyInt_FromLong((long) gsl_odeiv_step_order(self->step));
}
/* --------------------------------------------------------------------------- */
/* control_hadjust needs a few arrays */
/*
extern int
gsl_odeiv_control_hadjust (gsl_odeiv_control * c, gsl_odeiv_step * s,
const double y0[], const double yerr[],
const double dydt[], double * h);
*/
static PyObject *
PyGSL_odeiv_control_hadjust(PyGSL_odeiv_control *self, PyObject *args)
{
PyObject *result = NULL;
PyObject *y0_o = NULL, *yerr_o = NULL, *dydt_o = NULL;
PyArrayObject *y0 = NULL, *yerr = NULL, *dydt = NULL;
double h = 0;
int r = 0;
size_t dimension = 0;
FUNC_MESS_BEGIN();
assert(PyGSL_ODEIV_CONTROL_Check(self));
if(!PyArg_ParseTuple(args, "OOOd", &y0_o, &yerr_o, &dydt_o, &h)){
return NULL;
}
dimension = self->step->system.dimension;
y0 = PyGSL_PyArray_PREPARE_gsl_vector_view(y0_o, PyArray_DOUBLE, 1, dimension, 1, NULL);
if(y0 == NULL) goto fail;
yerr = PyGSL_PyArray_PREPARE_gsl_vector_view(yerr_o, PyArray_DOUBLE, 1, dimension, 2, NULL);
if(yerr == NULL) goto fail;
dydt = PyGSL_PyArray_PREPARE_gsl_vector_view(yerr_o, PyArray_DOUBLE, 1, dimension, 3, NULL);
if(dydt == NULL) goto fail;
FUNC_MESS(" Array Pointers End");
r = gsl_odeiv_control_hadjust(self->control, self->step->step,
(double *) y0->data,
(double *) yerr->data,
(double *) dydt->data, &h);
FUNC_MESS(" Function End");
Py_DECREF(y0); y0 = NULL;
Py_DECREF(yerr); yerr = NULL;
Py_DECREF(dydt); dydt = NULL;
result = Py_BuildValue("di",h,r);
FUNC_MESS_END();
return result;
fail:
FUNC_MESS("IN Fail");
Py_XDECREF(y0);
Py_XDECREF(yerr);
Py_XDECREF(dydt);
FUNC_MESS("IN Fail END");
return NULL;
}
static void
PyGSL_odeiv_control_free(PyGSL_odeiv_control * self)
{
assert(PyGSL_ODEIV_CONTROL_Check(self));
Py_DECREF(self->step);
//gsl_odeiv_control_free(self->control);
PyMem_Free(self);
}
static PyObject *
PyGSL_odeiv_control_name(PyGSL_odeiv_control *self, PyObject *args)
{
assert(PyGSL_ODEIV_CONTROL_Check(self));
return PyString_FromString(gsl_odeiv_control_name(self->control));
}
static void
PyGSL_odeiv_evolve_free(PyGSL_odeiv_evolve * self)
{
assert(PyGSL_ODEIV_EVOLVE_Check(self));
Py_DECREF(self->step);
Py_DECREF(self->control);
gsl_odeiv_evolve_free(self->evolve);
PyMem_Free(self);
}
static PyObject *
PyGSL_odeiv_evolve_apply(PyGSL_odeiv_evolve *self, PyObject *args)
{
PyObject *result = NULL;
PyObject *y0_o = NULL;
PyArrayObject *volatile y0 = NULL, *volatile yout = NULL;
double t=0, h=0, t1 = 0, flag;
int dimension, r;
assert(PyGSL_ODEIV_EVOLVE_Check(self));
FUNC_MESS_BEGIN();
if(! PyArg_ParseTuple(args, "dddO",
&t, &t1, &h, &y0_o)){
return NULL;
}
dimension = self->step->system.dimension;
y0 = PyGSL_PyArray_PREPARE_gsl_vector_view(y0_o, PyArray_DOUBLE, 1, dimension, 1, NULL);
if(y0 == NULL) goto fail;
yout = (PyArrayObject *) PyArray_CopyFromObject((PyObject * ) y0, PyArray_DOUBLE, 1, 1);
if(yout == NULL) goto fail;
if((flag=setjmp(self->step->buffer)) == 0){
FUNC_MESS("\t\t Setting Jmp Buffer");
} else {
FUNC_MESS("\t\t Returning from Jmp Buffer");
goto fail;
}
r = gsl_odeiv_evolve_apply(self->evolve,
self->control->control,
self->step->step,
&(self->step->system), &t, t1, &h,
(double * )yout->data);
if (GSL_SUCCESS != r){
goto fail;
}
assert(yout != NULL);
result = Py_BuildValue("(ddO)", t, h, yout);
/* Deleting the arrays */
/* Do I need to do that??? Not transfered Py_DECREF(yout); yout = NULL; */
Py_DECREF(y0); y0=NULL;
FUNC_MESS_END();
return result;
fail:
FUNC_MESS("IN Fail");
PyGSL_add_traceback(module, this_file, odeiv_step_init_err_msg, __LINE__);
Py_XDECREF(y0);
Py_XDECREF(yout);
FUNC_MESS("IN Fail End");
return NULL;
}
static PyObject *
PyGSL_odeiv_evolve_apply_array(PyGSL_odeiv_evolve *self, PyObject *args)
{
PyObject *result = NULL;
PyObject *y0_o = NULL;
PyObject *t_o = NULL;
PyArrayObject *volatile y0 = NULL, *volatile yout = NULL, *volatile ta = NULL;
double t=0, h=0, t1 = 0, flag;
double *y0_data = NULL, *yout_data = NULL;
int dimension, r, dims[2];
int nlen=-1, i, j;
assert(PyGSL_ODEIV_EVOLVE_Check(self));
FUNC_MESS_BEGIN();
if(! PyArg_ParseTuple(args, "OdO", &t_o, &h, &y0_o)){
return NULL;
}
dimension = self->step->system.dimension;
ta = PyGSL_PyArray_PREPARE_gsl_vector_view(t_o, PyArray_DOUBLE, 1, -1, 1, NULL);
if(ta == NULL) goto fail;
nlen = ta->dimensions[0];
y0 = PyGSL_PyArray_PREPARE_gsl_vector_view(y0_o, PyArray_DOUBLE, 1, dimension, 1, NULL);
if(y0 == NULL) goto fail;
dims[0] = nlen;
dims[1] = dimension;
yout = (PyArrayObject *) PyArray_FromDims(2, dims, PyArray_DOUBLE);
if(yout == NULL) goto fail;
if((flag=setjmp(self->step->buffer)) == 0){
FUNC_MESS("\t\t Setting Jmp Buffer");
} else {
FUNC_MESS("\t\t Returning from Jmp Buffer");
goto fail;
}
DEBUG_MESS(5, "\t\t Yout Layout %p, shape=[%d,%d], strides=[%d,%d]",
yout->data, yout->dimensions[0], yout->dimensions[1], yout->strides[0], yout->strides[1]);
r = GSL_CONTINUE;
yout_data = (double *)(yout->data);
/* Copy the start vector */
for(j=0; j<dimension; j++){
yout_data[j] = *((double *)(y0->data + y0->strides[0] * j));
}
for(i=1; i<nlen; i++){
y0_data = (double *)(yout->data + yout->strides[0]*(i-1));
yout_data = (double *)(yout->data + yout->strides[0]*(i) );
/* Copy the start vector */
for(j=0; j<dimension; j++){
yout_data[j] = y0_data[j];
}
t = *((double *) (ta->data + ta->strides[0]*(i-1)) );
t1 = *((double *) (ta->data + ta->strides[0]*(i) ) );
while(t<t1){
r = gsl_odeiv_evolve_apply(self->evolve,
self->control->control,
self->step->step,
&(self->step->system), &t, t1, &h,
yout_data);
/* All GSL Errors are > 0. */
if (r != GSL_SUCCESS){
goto fail;
}
}
assert(r == GSL_SUCCESS);
}
result = (PyObject *) yout;
/* Deleting the arrays */
Py_DECREF(y0); y0=NULL;
Py_DECREF(ta);
FUNC_MESS_END();
return result;
fail:
FUNC_MESS("IN Fail");
PyGSL_add_traceback(module, this_file, odeiv_step_init_err_msg, __LINE__);
Py_XDECREF(ta); ta = NULL;
Py_XDECREF(y0); y0=NULL;
Py_XDECREF(yout);
FUNC_MESS("IN Fail End");
return NULL;
}
static PyObject *
PyGSL_odeiv_evolve_reset(PyGSL_odeiv_evolve *self, PyObject *args)
{
assert(PyGSL_ODEIV_EVOLVE_Check(self));
gsl_odeiv_evolve_reset(self->evolve);
Py_INCREF(Py_None);
return Py_None;
}
static PyObject *
PyGSL_odeiv_step_init(PyObject *self, PyObject *args, PyObject *kwdict, const gsl_odeiv_step_type * odeiv_type)
{
PyObject *func=NULL, *jac=NULL, *o_params=NULL;
PyGSL_odeiv_step *odeiv_step = NULL;
static char * kwlist[] = {"dimension", "func", "jac", "args", NULL};
int dim, has_jacobian = 0;
FUNC_MESS_BEGIN();
assert(args);
if (0 == PyArg_ParseTupleAndKeywords(args, kwdict, "iOOO:odeiv_step.__init__", kwlist,
&dim, &func, &jac, &o_params)){
PyGSL_add_traceback(module, this_file, odeiv_step_init_err_msg, __LINE__ - 2);
return NULL;
}
if (dim <= 0){
PyGSL_add_traceback(module, this_file, odeiv_step_init_err_msg, __LINE__ - 1);
gsl_error("The dimension of the problem must be at least 1",
this_file, __LINE__ -2, GSL_EDOM);
return NULL;
}
if(!PyCallable_Check(func)){
PyGSL_add_traceback(module, this_file, odeiv_step_init_err_msg, __LINE__ - 1);
gsl_error("The function object is not callable!",
this_file, __LINE__ -2, GSL_EBADFUNC);
goto fail;
}
if(jac == Py_None){
if(odeiv_type == gsl_odeiv_step_bsimp){
PyGSL_add_traceback(module, this_file, odeiv_step_init_err_msg, __LINE__ - 1);
gsl_error("The bsimp method needs a jacobian! You supplied None.",
this_file, __LINE__ -2, GSL_EBADFUNC);
goto fail;
}
}else{
if(!PyCallable_Check(jac)){
PyGSL_add_traceback(module, this_file, odeiv_step_init_err_msg, __LINE__ - 1);
gsl_error("The jacobian object must be None or callable!",
this_file, __LINE__ -2, GSL_EBADFUNC);
goto fail;
}
has_jacobian = 1;
}
odeiv_step = (PyGSL_odeiv_step *) PyObject_NEW(PyGSL_odeiv_step, &PyGSL_odeiv_step_pytype);
if(odeiv_step == NULL){
PyErr_NoMemory();
goto fail;
}
odeiv_step->step=NULL;
odeiv_step->py_func=NULL;
odeiv_step->py_jac=NULL;
odeiv_step->arguments=NULL;
odeiv_step->system.dimension = dim;
if(has_jacobian)
odeiv_step->system.jacobian = PyGSL_odeiv_jac;
else
odeiv_step->system.jacobian = NULL;
odeiv_step->system.function = PyGSL_odeiv_func;
odeiv_step->system.params = (void *) odeiv_step;
odeiv_step->step = gsl_odeiv_step_alloc(odeiv_type, dim);
if(odeiv_step->step == NULL){
Py_DECREF(odeiv_step);
PyErr_NoMemory();
return NULL;
}
odeiv_step->py_func=func;
if(has_jacobian)
odeiv_step->py_jac=jac;
odeiv_step->arguments = o_params;
Py_INCREF(odeiv_step->py_func);
Py_INCREF(odeiv_step->arguments);
Py_XINCREF(odeiv_step->py_jac);
FUNC_MESS_END();
return (PyObject *) odeiv_step;
fail:
return NULL;
}
#define ADD_ODESTEPPER(mytype) \
static PyObject * \
PyGSL_odeiv_step_init_ ## mytype (PyObject * self, PyObject * args, PyObject *kwdic)\
{ \
return PyGSL_odeiv_step_init(self, args, kwdic, gsl_odeiv_step_ ## mytype); \
}
ADD_ODESTEPPER(rk2)
ADD_ODESTEPPER(rk4)
ADD_ODESTEPPER(rkf45)
ADD_ODESTEPPER(rkck)
ADD_ODESTEPPER(rk8pd)
ADD_ODESTEPPER(rk2imp)
ADD_ODESTEPPER(rk4imp)
ADD_ODESTEPPER(bsimp)
ADD_ODESTEPPER(gear1)
ADD_ODESTEPPER(gear2)
static PyObject *
PyGSL_odeiv_control_init(PyObject *self, PyObject *args, void * type)
{
int nargs = -1, tmp=0;
double eps_abs, eps_rel, a_y, a_dydt;
PyGSL_odeiv_step *step=NULL;
PyGSL_odeiv_control *a_con=NULL;
gsl_odeiv_control *(*evaluator_5)(double , double , double , double ) = NULL;
gsl_odeiv_control *(*evaluator_3)(double , double ) = NULL;
FUNC_MESS_BEGIN();
/* The arguments depend on the type of control */
if(type == (void *) gsl_odeiv_control_standard_new){
/* step, eps_abs, eps_rel, a_y, a_dydt */
nargs = 5;
}else if(type == (void *) gsl_odeiv_control_y_new ||
type == (void *) gsl_odeiv_control_yp_new){
nargs = 3;
}else{
PyGSL_add_traceback(module, this_file, odeiv_step_init_err_msg,
__LINE__ - 2);
gsl_error("Unknown control type",
this_file, __LINE__ -2, GSL_EFAULT);
goto fail;
}
assert(nargs > -1);
switch(nargs){
case 5:
tmp == PyArg_ParseTuple(args, "O!dddd:odeiv_control.__init__",
&PyGSL_odeiv_step_pytype, &step, &eps_abs, &eps_rel, &a_y, &a_dydt);
break;
case 3:
tmp == PyArg_ParseTuple(args, "O!dd:odeiv_control.__init__",
&PyGSL_odeiv_step_pytype, &step, &eps_abs, &eps_rel);
break;
default:
fprintf(stderr, "nargs = %d\n", nargs);
gsl_error("Unknown number of arguments",
this_file, __LINE__ -2, GSL_EFAULT);
goto fail; break;
}
if(!step){
PyErr_SetString(PyExc_TypeError, "The first argument must be a step object!");
goto fail;
}
if(tmp){
PyGSL_add_traceback(module, this_file, odeiv_step_init_err_msg,
__LINE__ - 2);
return NULL;
}
a_con = PyObject_NEW(PyGSL_odeiv_control, &PyGSL_odeiv_control_pytype);
if (NULL == a_con){
PyErr_NoMemory();
goto fail;
}
a_con->control=NULL;
switch(nargs){
case 5:
evaluator_5 = type;
a_con->control = evaluator_5(eps_abs, eps_rel, a_y, a_dydt);
break;
case 3:
evaluator_3 = type;
a_con->control = evaluator_3(eps_abs, eps_rel);
break;
default:
goto fail;
}
if (NULL == a_con->control){
PyErr_NoMemory();
goto fail;
}
assert(step);
a_con->step = step;
Py_INCREF(step);
FUNC_MESS_END();
return (PyObject *) a_con;
fail:
FUNC_MESS("FAIL");
Py_XDECREF(a_con);
return NULL;
}
#define ADD_ODECONTROL(name) \
static PyObject * \
PyGSL_odeiv_control_init_ ## name (PyObject * self, PyObject * args) \
{ \
return PyGSL_odeiv_control_init(self, args, (void *) gsl_odeiv_control_ ## name); \
}
ADD_ODECONTROL(standard_new)
ADD_ODECONTROL(y_new)
ADD_ODECONTROL(yp_new)
static PyObject *
PyGSL_odeiv_evolve_init(PyObject *self, PyObject *args)
{
PyGSL_odeiv_step *step = NULL;
PyGSL_odeiv_control *control = NULL;
PyGSL_odeiv_evolve *a_ev = NULL;
/* step, control */
FUNC_MESS_BEGIN();
if(0== PyArg_ParseTuple(args, "O!O!:odeiv_evolve.__init__",
&PyGSL_odeiv_step_pytype, &step,
&PyGSL_odeiv_control_pytype, &control)){
return NULL;
}
if(!step){
PyErr_SetString(PyExc_TypeError, "The first argument must be a step object!");
goto fail;
}
if(!control){
PyErr_SetString(PyExc_TypeError, "The second argument must be a control object!");
goto fail;
}
a_ev = (PyGSL_odeiv_evolve *) PyObject_NEW(PyGSL_odeiv_evolve, &PyGSL_odeiv_evolve_pytype);
if(NULL == a_ev){
PyErr_NoMemory();
return NULL;
}
a_ev->step = step;
a_ev->control = control;
a_ev->evolve = gsl_odeiv_evolve_alloc(step->system.dimension);
if(NULL == a_ev){
PyErr_NoMemory();
goto fail;
}
Py_INCREF(step);
Py_INCREF(control);
FUNC_MESS_END();
return (PyObject *) a_ev;
fail:
FUNC_MESS("FAIL");
Py_DECREF(a_ev);
return NULL;
}
static PyMethodDef PyGSL_odeiv_module_functions[] = {
{"step_rk2", PyGSL_odeiv_step_init_rk2, METH_VARARGS|METH_KEYWORDS, NULL},
{"step_rk4", PyGSL_odeiv_step_init_rk4, METH_VARARGS|METH_KEYWORDS, NULL},
{"step_rkf45", PyGSL_odeiv_step_init_rkf45, METH_VARARGS|METH_KEYWORDS, NULL},
{"step_rkck", PyGSL_odeiv_step_init_rkck, METH_VARARGS|METH_KEYWORDS, NULL},
{"step_rk8pd", PyGSL_odeiv_step_init_rk8pd, METH_VARARGS|METH_KEYWORDS, NULL},
{"step_rk2imp", PyGSL_odeiv_step_init_rk2imp, METH_VARARGS|METH_KEYWORDS, NULL},
{"step_rk4imp", PyGSL_odeiv_step_init_rk4imp, METH_VARARGS|METH_KEYWORDS, NULL},
{"step_bsimp", PyGSL_odeiv_step_init_bsimp, METH_VARARGS|METH_KEYWORDS, NULL},
{"step_gear1", PyGSL_odeiv_step_init_gear1, METH_VARARGS|METH_KEYWORDS, NULL},
{"step_gear2", PyGSL_odeiv_step_init_gear2, METH_VARARGS|METH_KEYWORDS, NULL},
{"control_standard_new", PyGSL_odeiv_control_init_standard_new, METH_VARARGS, NULL},
{"control_y_new", PyGSL_odeiv_control_init_y_new, METH_VARARGS, NULL},
{"control_yp_new", PyGSL_odeiv_control_init_yp_new, METH_VARARGS, NULL},
{"evolve", PyGSL_odeiv_evolve_init, METH_VARARGS, NULL},
{NULL, NULL, 0} /* Sentinel */
};
void
initodeiv(void)
{
PyObject *m=NULL, *item=NULL, *dict=NULL;
FUNC_MESS_BEGIN();
fprintf(stderr, "Compiled at %s %s\n", __DATE__, __TIME__);
m = Py_InitModule("odeiv", PyGSL_odeiv_module_functions);
assert(m);
module = m;
import_array();
init_pygsl();
PyGSL_odeiv_step_pytype.ob_type = &PyType_Type;
PyGSL_odeiv_control_pytype.ob_type = &PyType_Type;
PyGSL_odeiv_evolve_pytype.ob_type = &PyType_Type;
dict = PyModule_GetDict(m);
/* create_odeiv_step_types(dict); */
if(!dict)
goto fail;
if (!(item = PyString_FromString(odeiv_module_doc))){
PyErr_SetString(PyExc_ImportError,
"I could not generate module doc string!");
goto fail;
}
if (PyDict_SetItemString(dict, "__doc__", item) != 0){
PyErr_SetString(PyExc_ImportError,
"I could not init doc string!");
goto fail;
}
FUNC_MESS_END();
return;
fail:
FUNC_MESS("Fail");
fprintf(stderr, "Import of module odeiv failed!\n");
}
| {
"alphanum_fraction": 0.6394473874,
"avg_line_length": 30.5087235996,
"ext": "c",
"hexsha": "ed47c8b20ab5d53c115e6ee40b8583772e17d618",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2018-10-02T06:18:07.000Z",
"max_forks_repo_forks_event_min_datetime": "2018-10-02T06:18:07.000Z",
"max_forks_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "juhnowski/FishingRod",
"max_forks_repo_path": "production/pygsl-0.9.5/testing/src/solvers/old/odeiv_old2.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "juhnowski/FishingRod",
"max_issues_repo_path": "production/pygsl-0.9.5/testing/src/solvers/old/odeiv_old2.c",
"max_line_length": 113,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "juhnowski/FishingRod",
"max_stars_repo_path": "production/pygsl-0.9.5/testing/src/solvers/old/odeiv_old2.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 9809,
"size": 33224
} |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
#pragma once
#include "arcana/functional/inplace_function.h"
#include "arcana/sentry.h"
#include "affinity.h"
#include "blocking_concurrent_queue.h"
#include <gsl/gsl>
#include <vector>
namespace mira
{
template<size_t WorkSize>
class dispatcher
{
public:
using callback_t = stdext::inplace_function<void(), WorkSize>;
static constexpr size_t work_size = WorkSize;
template<typename T>
void queue(T&& work)
{
m_work.push(std::forward<T>(work));
}
affinity get_affinity() const
{
return m_affinity;
}
dispatcher(const dispatcher&) = delete;
dispatcher& operator=(const dispatcher&) = delete;
virtual ~dispatcher() = default;
protected:
dispatcher() = default;
dispatcher& operator=(dispatcher&&) = default;
dispatcher(dispatcher&&) = default;
bool tick(const cancellation& token)
{
return internal_tick(token, false);
}
bool blocking_tick(const cancellation& token)
{
return internal_tick(token, true);
}
/*
Sets the dispatcher's tick thread affinity. Once this is set the methods
on this instance will need to be called by that thread.
*/
void set_affinity(const affinity& aff)
{
m_affinity = aff;
}
void cancelled()
{
m_work.cancelled();
}
void clear()
{
m_work.clear();
}
private:
bool internal_tick(const cancellation& token, bool block)
{
GSL_CONTRACT_CHECK("thread affinity", m_affinity.check());
if (block)
{
if (!m_work.blocking_drain(m_workload, token))
return false;
}
else
{
if (!m_work.try_drain(m_workload, token))
return false;
}
for (auto& work : m_workload)
{
work();
}
m_workload.clear();
return true;
}
blocking_concurrent_queue<callback_t> m_work;
affinity m_affinity;
std::vector<callback_t> m_workload;
};
template<size_t WorkSize>
class manual_dispatcher : public dispatcher<WorkSize>
{
public:
using dispatcher<WorkSize>::blocking_tick;
using dispatcher<WorkSize>::cancelled;
using dispatcher<WorkSize>::clear;
using dispatcher<WorkSize>::set_affinity;
using dispatcher<WorkSize>::tick;
};
template<size_t WorkSize>
class background_dispatcher : public dispatcher<WorkSize>
{
public:
background_dispatcher()
: m_registration{ m_cancellation.add_listener([this] { this->cancelled(); }) }
{
m_thread = std::thread{ [&]() {
// TODO: Set the affinity when usage bugs are fixed.
constexpr bool should_set_affinity{ false };
if (should_set_affinity)
{
this->set_affinity(std::this_thread::get_id());
}
while (!m_cancellation.cancelled())
{
this->blocking_tick(m_cancellation);
}
} };
}
void cancel()
{
m_cancellation.cancel();
if (m_thread.joinable())
{
m_thread.join();
}
this->clear();
}
~background_dispatcher()
{
cancel();
}
private:
std::thread m_thread;
cancellation_source m_cancellation;
cancellation_source::ticket m_registration;
};
}
| {
"alphanum_fraction": 0.5320348539,
"avg_line_length": 24.0864197531,
"ext": "h",
"hexsha": "53bf072b80cabc35b2e4da579bcdc900a5ee97c0",
"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/threading/dispatcher.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/threading/dispatcher.h",
"max_line_length": 90,
"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/threading/dispatcher.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": 764,
"size": 3902
} |
/** @file */
#ifndef __CCL_UTILS_H_INCLUDED__
#define __CCL_UTILS_H_INCLUDED__
#include <gsl/gsl_spline.h>
#define CCL_MIN(a, b) (((a) < (b)) ? (a) : (b))
#define CCL_MAX(a, b) (((a) > (b)) ? (a) : (b))
CCL_BEGIN_DECLS
typedef enum ccl_integration_t {
ccl_integration_qag_quad = 500, // GSL's quad
ccl_integration_spline = 501, // Spline integral
} ccl_integration_t;
/**
* Compute bin edges of N-1 linearly spaced bins on the interval [xmin,xmax]
* @param xmin minimum value of spacing
* @param xmax maximum value of spacing
* @param N number of bins plus one (number of bin edges)
* @return x, bin edges in range [xmin, xmax]
*/
double * ccl_linear_spacing(double xmin, double xmax, int N);
/**
* Compute bin edges of N-1 logarithmically and then linearly spaced bins on the interval [xmin,xmax]
* @param xminlog minimum value of spacing
* @param xmin value when logarithmical ends and linear spacing begins
* @param xmax maximum value of spacing
* @param Nlin number of linear bins plus one (number of bin edges)
* @param Nlog number of logarithmic bins plus one (number of bin edges)
* @return x, bin edges in range [xminlog, xmax]
*/
double * ccl_linlog_spacing(double xminlog, double xmin, double xmax, int Nlin, int Nlog);
/**
* Compute bin edges of N-1 logarithmically spaced bins on the interval [xmin,xmax]
* @param xmin minimum value of spacing
* @param xmax maximum value of spacing
* @param N number of bins plus one (number of bin edges)
* @return x, bin edges in range [xmin, xmax]
*/
double * ccl_log_spacing(double xmin, double xmax, int N);
//Returns array of N logarithmically-spaced values between xmin and xmax
double ccl_j_bessel(int l,double x);
//Spherical Bessel function of order l (adapted from CAMB)
/**
* Compute spline integral.
* @param nx number of elements in input array.
* @param ny number of y arrays.
* @param x input x-values.
* @param y input y-values (ny arrays with nx elements).
* @param a lower end of integration range.
* @param b upper end of integration range (use b<a if you just want to integrate over all of y).
* @param result array of output spline integral values.
* @param T spline type.
* @param status status flag.
*/
void ccl_integ_spline(int ny, int nx,double *x,double **y,
double a, double b, double *result,
const gsl_interp_type *T, int *status);
CCL_END_DECLS
#endif
| {
"alphanum_fraction": 0.7086256707,
"avg_line_length": 35.115942029,
"ext": "h",
"hexsha": "f26b1684e5220fb961a2b76db51e1305f96f23bf",
"lang": "C",
"max_forks_count": 54,
"max_forks_repo_forks_event_max_datetime": "2022-02-06T13:12:10.000Z",
"max_forks_repo_forks_event_min_datetime": "2017-07-12T13:08:25.000Z",
"max_forks_repo_head_hexsha": "a37cad61f060f3928fa5d47b1e2670db3e9bce6f",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "Jappenn/CCL",
"max_forks_repo_path": "include/ccl_utils.h",
"max_issues_count": 703,
"max_issues_repo_head_hexsha": "a37cad61f060f3928fa5d47b1e2670db3e9bce6f",
"max_issues_repo_issues_event_max_datetime": "2022-03-30T14:40:10.000Z",
"max_issues_repo_issues_event_min_datetime": "2017-07-07T16:27:17.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "Jappenn/CCL",
"max_issues_repo_path": "include/ccl_utils.h",
"max_line_length": 101,
"max_stars_count": 91,
"max_stars_repo_head_hexsha": "a37cad61f060f3928fa5d47b1e2670db3e9bce6f",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "Jappenn/CCL",
"max_stars_repo_path": "include/ccl_utils.h",
"max_stars_repo_stars_event_max_datetime": "2022-03-28T08:55:54.000Z",
"max_stars_repo_stars_event_min_datetime": "2017-07-14T02:45:59.000Z",
"num_tokens": 634,
"size": 2423
} |
/* fft/gsl_fft_halfcomplex.h
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Brian Gough
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#ifndef __GSL_FFT_HALFCOMPLEX_H__
#define __GSL_FFT_HALFCOMPLEX_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 <stddef.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_complex.h>
#include <gsl/gsl_fft.h>
#include <gsl/gsl_fft_real.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_FUN int gsl_fft_halfcomplex_radix2_backward (double data[], const size_t stride, const size_t n);
GSL_FUN int gsl_fft_halfcomplex_radix2_inverse (double data[], const size_t stride, const size_t n);
GSL_FUN int gsl_fft_halfcomplex_radix2_transform (double data[], const size_t stride, const size_t n);
typedef struct
{
size_t n;
size_t nf;
size_t factor[64];
gsl_complex *twiddle[64];
gsl_complex *trig;
}
gsl_fft_halfcomplex_wavetable;
GSL_FUN gsl_fft_halfcomplex_wavetable * gsl_fft_halfcomplex_wavetable_alloc (size_t n);
GSL_FUN void
gsl_fft_halfcomplex_wavetable_free (gsl_fft_halfcomplex_wavetable * wavetable);
GSL_FUN int gsl_fft_halfcomplex_backward (double data[], const size_t stride, const size_t n,
const gsl_fft_halfcomplex_wavetable * wavetable,
gsl_fft_real_workspace * work);
GSL_FUN int gsl_fft_halfcomplex_inverse (double data[], const size_t stride, const size_t n,
const gsl_fft_halfcomplex_wavetable * wavetable,
gsl_fft_real_workspace * work);
GSL_FUN int gsl_fft_halfcomplex_transform (double data[], const size_t stride, const size_t n,
const gsl_fft_halfcomplex_wavetable * wavetable,
gsl_fft_real_workspace * work);
GSL_FUN int
gsl_fft_halfcomplex_unpack (const double halfcomplex_coefficient[],
double complex_coefficient[],
const size_t stride, const size_t n);
GSL_FUN int
gsl_fft_halfcomplex_radix2_unpack (const double halfcomplex_coefficient[],
double complex_coefficient[],
const size_t stride, const size_t n);
__END_DECLS
#endif /* __GSL_FFT_HALFCOMPLEX_H__ */
| {
"alphanum_fraction": 0.7024842861,
"avg_line_length": 34.4432989691,
"ext": "h",
"hexsha": "f80611da2ea7b27eef8568cc30d3b4b025bd8b17",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2020-10-14T12:45:35.000Z",
"max_forks_repo_forks_event_min_datetime": "2020-10-14T12:45:35.000Z",
"max_forks_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "zzpwahaha/Chimera-Control-Trim",
"max_forks_repo_path": "Chimera/3rd_Party/GSL_MSVC/gsl/gsl_fft_halfcomplex.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "zzpwahaha/Chimera-Control-Trim",
"max_issues_repo_path": "Chimera/3rd_Party/GSL_MSVC/gsl/gsl_fft_halfcomplex.h",
"max_line_length": 102,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "zzpwahaha/Chimera-Control-Trim",
"max_stars_repo_path": "Chimera/3rd_Party/GSL_MSVC/gsl/gsl_fft_halfcomplex.h",
"max_stars_repo_stars_event_max_datetime": "2020-09-28T08:20:20.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-09-28T08:20:20.000Z",
"num_tokens": 798,
"size": 3341
} |
#pragma once
#include <random>
#include <type_traits>
#include <gsl-lite/gsl-lite.hpp>
namespace thrustshift {
namespace random {
template <class Range, class Distribution, class Engine>
void generate(Range&& range, Distribution& dist, Engine& rng) {
for (size_t i = 0; i < range.size(); ++i) {
range[i] = dist(rng);
}
}
template <class Range,
typename T = typename std::remove_reference<Range>::type::value_type>
void generate_uniform_real(Range&& range,
T min = T{0},
T max = T{1},
unsigned long long seed = 0) {
gsl_Expects(min <= max);
std::default_random_engine rng(seed);
std::uniform_real_distribution<T> dist(min, max);
generate(std::forward<Range>(range), dist, rng);
}
template <class Range,
typename T = typename std::remove_reference<
Range>::type::value_type::value_type>
void generate_uniform_complex(Range&& range,
T min = T{0},
T max = T{1},
unsigned long long seed = 0) {
gsl_Expects(min <= max);
using Complex = typename std::remove_reference<Range>::type::value_type;
std::default_random_engine rng(seed);
std::uniform_real_distribution<T> dist(min, max);
auto cdist = [&](auto& rng) -> Complex { return {dist(rng), dist(rng)}; };
generate(std::forward<Range>(range), cdist, rng);
}
template <class Range,
typename T = typename std::remove_reference<Range>::type::value_type>
void generate_normal_real(Range&& range,
T mean = T{0},
T stddev = T{1},
unsigned long long seed = 0) {
gsl_Expects(stddev >= 0);
std::default_random_engine rng(seed);
std::normal_distribution<T> dist(mean, stddev);
generate(std::forward<Range>(range), dist, rng);
}
template <class Range,
typename T = typename std::remove_reference<
Range>::type::value_type::value_type>
void generate_normal_complex(Range&& range,
T mean = T{0},
T stddev = T{1},
unsigned long long seed = 0) {
gsl_Expects(stddev >= 0);
using Complex = typename std::remove_reference<Range>::type::value_type;
std::default_random_engine rng(seed);
std::normal_distribution<T> dist(mean, stddev);
auto cdist = [&](auto& rng) -> Complex { return {dist(rng), dist(rng)}; };
generate(std::forward<Range>(range), cdist, rng);
}
} // namespace random
} // namespace thrustshift
| {
"alphanum_fraction": 0.6015533981,
"avg_line_length": 33.8815789474,
"ext": "h",
"hexsha": "ef2624f2c16be97a955e701ce7c3fea9d9a1168b",
"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": "763805f862e3121374286c927dd6949960bffb84",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "pauleonix/thrustshift",
"max_forks_repo_path": "include/thrustshift/random.h",
"max_issues_count": 2,
"max_issues_repo_head_hexsha": "763805f862e3121374286c927dd6949960bffb84",
"max_issues_repo_issues_event_max_datetime": "2021-06-17T11:40:04.000Z",
"max_issues_repo_issues_event_min_datetime": "2021-03-23T14:12:08.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "pauleonix/thrustshift",
"max_issues_repo_path": "include/thrustshift/random.h",
"max_line_length": 79,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "763805f862e3121374286c927dd6949960bffb84",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "pauleonix/thrustshift",
"max_stars_repo_path": "include/thrustshift/random.h",
"max_stars_repo_stars_event_max_datetime": "2021-12-16T13:01:46.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-12-16T13:01:46.000Z",
"num_tokens": 584,
"size": 2575
} |
/** @file kjg_fpca.h
* @brief Runs fastPCA.
* This module also has methods to multiply a genotype matrix against the GSL
* matrices.
*/
#ifndef KJG_FPCA_H_
#define KJG_FPCA_H_
#include <gsl/gsl_matrix.h>
extern size_t KJG_FPCA_ROWS; // number of rows to process at once
/** Performs a fast PCA
* @param *eval eigenvalues
* @param *evec eigenvectors
* @param K number of eigenvalues/vectors
* @param L width of projection matrix
* @param I iterations to do exponentiation
*/
void kjg_fpca (size_t K, size_t L, size_t I, double *eval, double *evec);
/** Multiplies B=X*A1 and A2 = XT*B = XT*X*A1
* @param *A1 some matrix
* @param *B intermediate matrix
* @param *A2 next matrix
*/
void kjg_fpca_XTXA (const gsl_matrix * A1, gsl_matrix * B, gsl_matrix * A2);
/** Multiplies B = X*A
* @param *A some matrix
* @param *B another matrix
*/
void kjg_fpca_XA (const gsl_matrix * A, gsl_matrix * B);
/** Multiplies A = XT*B
* @param *B some matrix
* @param *A another matrix
*/
void kjg_fpca_XTB (const gsl_matrix * B, gsl_matrix * A);
#endif /* KJG_FPCA_H_ */
| {
"alphanum_fraction": 0.6934441367,
"avg_line_length": 23.0425531915,
"ext": "h",
"hexsha": "ed36845807f8e94b8adf913414f61945599956cf",
"lang": "C",
"max_forks_count": 63,
"max_forks_repo_forks_event_max_datetime": "2022-01-31T18:57:58.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-04-20T08:57:41.000Z",
"max_forks_repo_head_hexsha": "f7b857d4d347d44c57f70194bb4588fad5b1ffed",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "nevrome/EIG",
"max_forks_repo_path": "include/kjg_fpca.h",
"max_issues_count": 73,
"max_issues_repo_head_hexsha": "f7b857d4d347d44c57f70194bb4588fad5b1ffed",
"max_issues_repo_issues_event_max_datetime": "2022-03-30T11:30:51.000Z",
"max_issues_repo_issues_event_min_datetime": "2016-03-27T14:57:04.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "nevrome/EIG",
"max_issues_repo_path": "include/kjg_fpca.h",
"max_line_length": 77,
"max_stars_count": 142,
"max_stars_repo_head_hexsha": "f7b857d4d347d44c57f70194bb4588fad5b1ffed",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "nevrome/EIG",
"max_stars_repo_path": "include/kjg_fpca.h",
"max_stars_repo_stars_event_max_datetime": "2022-03-29T14:29:55.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-03-12T07:58:32.000Z",
"num_tokens": 333,
"size": 1083
} |
/* randist/hyperg.c
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000 James Theiler, Brian Gough
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include <config.h>
#include <math.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
#include <gsl/gsl_sf_gamma.h>
/* The hypergeometric distribution has the form,
prob(k) = choose(n1,t) choose(n2, t-k) / choose(n1+n2,t)
where choose(a,b) = a!/(b!(a-b)!)
n1 + n2 is the total population (tagged plus untagged)
n1 is the tagged population
t is the number of samples taken (without replacement)
k is the number of tagged samples found
*/
unsigned int
gsl_ran_hypergeometric (const gsl_rng * r, unsigned int n1, unsigned int n2,
unsigned int t)
{
const unsigned int n = n1 + n2;
unsigned int i = 0;
unsigned int a = n1;
unsigned int b = n1 + n2;
unsigned int k = 0;
if (t > n)
{
t = n ;
}
if (t < n / 2)
{
for (i = 0 ; i < t ; i++)
{
double u = gsl_rng_uniform(r) ;
if (b * u < a)
{
k++ ;
if (k == n1)
return k ;
a-- ;
}
b-- ;
}
return k;
}
else
{
for (i = 0 ; i < n - t ; i++)
{
double u = gsl_rng_uniform(r) ;
if (b * u < a)
{
k++ ;
if (k == n1)
return n1 - k ;
a-- ;
}
b-- ;
}
return n1 - k;
}
}
double
gsl_ran_hypergeometric_pdf (const unsigned int k,
const unsigned int n1,
const unsigned int n2,
unsigned int t)
{
if (t > n1 + n2)
{
t = n1 + n2 ;
}
if (k > n1 || k > t)
{
return 0 ;
}
else if (t > n2 && k + n2 < t )
{
return 0 ;
}
else
{
double p;
double c1 = gsl_sf_lnchoose(n1,k);
double c2 = gsl_sf_lnchoose(n2,t-k);
double c3 = gsl_sf_lnchoose(n1+n2,t);
p = exp(c1 + c2 - c3) ;
return p;
}
}
| {
"alphanum_fraction": 0.5224302367,
"avg_line_length": 22.648,
"ext": "c",
"hexsha": "c15de09c43159f26e77b1b2372c91d4e94035adb",
"lang": "C",
"max_forks_count": 40,
"max_forks_repo_forks_event_max_datetime": "2022-03-03T23:23:37.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-02-26T15:31:16.000Z",
"max_forks_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "manggoguy/parsec-modified",
"max_forks_repo_path": "pkgs/libs/gsl/src/randist/hyperg.c",
"max_issues_count": 12,
"max_issues_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af",
"max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "manggoguy/parsec-modified",
"max_issues_repo_path": "pkgs/libs/gsl/src/randist/hyperg.c",
"max_line_length": 81,
"max_stars_count": 64,
"max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "manggoguy/parsec-modified",
"max_stars_repo_path": "pkgs/libs/gsl/src/randist/hyperg.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": 800,
"size": 2831
} |
////////////////////////////////////////////////////////////
//
// Copyright (c) 2018 Jan Filipowicz, Filip Turobos
//
// 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 GENETIC_ALGORITHM_LIBRARY_EVALUATED_SPECIMEN_H
#define GENETIC_ALGORITHM_LIBRARY_EVALUATED_SPECIMEN_H
#include <optional>
#include <utility>
#include <tuple>
#include <type_traits>
#include <gsl/gsl_assert>
template<class Specimen, class Rating>
class evaluated_specimen {
public:
using value_type = Specimen;
using rating_type = Rating;
template<class... Args, class = std::enable_if_t<!std::is_same_v<std::tuple<std::decay_t<Args>...>, std::tuple<evaluated_specimen>>>>
constexpr evaluated_specimen(Args&&... args) noexcept(sizeof...(Args) == 0);
constexpr value_type& value() & noexcept;
constexpr const value_type& value() const& noexcept;
constexpr bool has_rating() const noexcept;
constexpr rating_type rating() const;
template<class Function>
void evaluate(Function&& evaluator);
private:
value_type specimen;
std::optional<rating_type> grade;
};
template<class Specimen, class Rating>
template<class... Args, class>
constexpr evaluated_specimen<Specimen, Rating>::evaluated_specimen(Args&&... args) noexcept(sizeof...(Args) == 0)
: specimen(std::forward<Args>(args)...) {}
template<class Specimen, class Rating>
constexpr auto evaluated_specimen<Specimen, Rating>::value() & noexcept -> value_type& {
return specimen;
}
template<class Specimen, class Rating>
constexpr auto evaluated_specimen<Specimen, Rating>::value() const& noexcept -> const value_type& {
return specimen;
}
template<class Specimen, class Rating>
constexpr bool evaluated_specimen<Specimen, Rating>::has_rating() const noexcept {
return grade.has_value();
}
template<class Specimen, class Rating>
constexpr auto evaluated_specimen<Specimen, Rating>::rating() const -> rating_type {
return grade.value();
}
template<class Specimen, class Rating>
template<class Function>
inline void evaluated_specimen<Specimen, Rating>::evaluate(Function&& evaluator) {
grade.emplace(evaluator(std::as_const(specimen)));
Ensures(has_rating());
}
#endif
| {
"alphanum_fraction": 0.7383847833,
"avg_line_length": 37.7294117647,
"ext": "h",
"hexsha": "8699e6a0ffded186ca97e3178cbe7c77ba21cb33",
"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": "8a093d42ca935556e7d6ccaee5a57b8dd0c6b3e2",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "SirEmentaler/Eugenics-Wars",
"max_forks_repo_path": "Genetic-Algorithm-Library/evaluated_specimen.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "8a093d42ca935556e7d6ccaee5a57b8dd0c6b3e2",
"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": "SirEmentaler/Eugenics-Wars",
"max_issues_repo_path": "Genetic-Algorithm-Library/evaluated_specimen.h",
"max_line_length": 134,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "8a093d42ca935556e7d6ccaee5a57b8dd0c6b3e2",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "SirEmentaler/Eugenics-Wars",
"max_stars_repo_path": "Genetic-Algorithm-Library/evaluated_specimen.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 682,
"size": 3207
} |
#pragma once
#include "BasicBox.h"
#include "BasicTypes.h"
#include "BoxTypes.h"
#include "General.h"
#include "NodeDim.h"
#include "NodeListDim.h"
#include <gsl.h>
namespace formulae{ namespace node {
/**
*
* @param width
* @param node center node -> reference point, (must be Box0 or Rule !!!)
* @param upList above center, enumerated from bottom to top
* @param dnList below center, enumerated from top to bottom
* @return
*/
template<typename VList1=vlist_t, typename VList2=vlist_t, typename Node=NodeRef>
box_t makeVBox(dist_t width, Node && node,
VList1 && upList, VList2 && dnList) {
using general::revAppend;
using general::transfer;
auto h = vlistVsize(upList) + node.height();
auto d = vlistVsize(dnList) + node.depth();
std::remove_reference_t<VList1> emptyList;
auto nodeList = revAppend(std::forward<VList1>(upList), emptyList);
nodeList.push_back(std::forward<Node>(node));
transfer(nodeList, std::forward<VList2>(dnList));
return vbox(dim_t{width, h, d}, std::move(nodeList));
}
/**
*
* @param width
* @param center center node -> reference point,
* @param upList above center, enumerated from bottom to top
* @return
*/
template <typename Box = box_t, typename VList = vlist_t>
box_t upVBox(dist_t width, Box && center, VList&& upList) {
std::remove_reference_t<VList> emptyList;
return makeVBox(width, NodeRef{Box0(std::forward<Box>(center))},
std::forward<VList>(upList), emptyList);
}
/**
*
* @param width
* @param center center node -> reference point
* @param dnList below center, enumerated from top to bottom
* @return
*/
template <typename Box = box_t, typename VList = vlist_t>
box_t dnVBox(dist_t width, Box && center, VList && dnList) {
std::remove_reference_t<VList> emptyList;
return makeVBox(width, Box0(std::forward<Box>(center)), emptyList, std::forward<VList>(dnList));
}
/**
*
* @param n1
* @param dist1 distance from bottom of n1 to baseline
* @param dist vertical distance between n1 and n2
* @param n2
* @return
*/
template <typename Node = NodeRef, typename DownNode=NodeRef>
NodeRef above(Node && n1, dist_t dist1, dist_t dist, DownNode && n2) {
auto w = std::max(n1.vwidth(), n2.vwidth());
auto h = n1.vsize() + dist1;
auto d = n2.vsize() + dist - dist1;
using E = std::remove_reference_t<Node>;
list_t<E> nodeList;
nodeList.push_back(std::forward<Node>(n1));
nodeList.push_back(Kern_t::create(dist));
nodeList.push_back(std::forward<DownNode>(n2));
return Box0(vbox(dim_t{w, h, d}, std::move(nodeList)));
};
}
} | {
"alphanum_fraction": 0.6889320388,
"avg_line_length": 29.2613636364,
"ext": "h",
"hexsha": "1e7e7738656a99aa861ef37138e2663468cffde2",
"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": "4b691e515b30508fb5e29c68426bad51d9629e72",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "robin33n/formulae-cxx",
"max_forks_repo_path": "include/node/MakeVBox.h",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "4b691e515b30508fb5e29c68426bad51d9629e72",
"max_issues_repo_issues_event_max_datetime": "2019-09-26T11:32:00.000Z",
"max_issues_repo_issues_event_min_datetime": "2019-09-25T11:10:39.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "robin33n/formulae-cxx",
"max_issues_repo_path": "include/node/MakeVBox.h",
"max_line_length": 98,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "4b691e515b30508fb5e29c68426bad51d9629e72",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "robin33n/formulae-cxx",
"max_stars_repo_path": "include/node/MakeVBox.h",
"max_stars_repo_stars_event_max_datetime": "2019-11-25T04:00:03.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-11-25T04:00:03.000Z",
"num_tokens": 731,
"size": 2575
} |
#ifndef __COMPLEX_ARRAY_H__
#define __COMPLEX_ARRAY_H__
#include <complex>
#include <vector>
#include <iostream>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_fft_complex.h>
#define REAL(z,i) ((z)[2*(i)])
#define IMAG(z,i) ((z)[2*(i)+1])
namespace mspass::algorithms::deconvolution{
typedef std::complex<double> Complex64;
typedef std::complex<float> Complex32;
typedef struct FortranComplex32 {
float real;
float imag;
} FortranComplex32;
typedef struct FortranComplex64 {
double real;
double imag;
} FortranComplex64;
/* \brief Interfacing object to ease conversion between FORTRAN and C++ complex.
*/
class ComplexArray
{
public:
/*! Empty constructor. */
ComplexArray();
/*! Construct from stl vector container of complex. */
ComplexArray(std::vector<Complex64> &d);
/*! Similar for 32 bit version */
ComplexArray(std::vector<Complex32> &d);
/*! Construct from a FORTRAN data array.
Fortran stores complex numbers in a mulitplexed array
structure (real(1), imag(1), real(2), imag(2), etc.).
The constructors below provide a mechanism for building
this object from various permutations of this.
\param nsamp is the number of elements in the C vector
\param d is the pointer to the first compoment of the
fortran vector.
*/
ComplexArray(int nsamp, FortranComplex32 *d);
ComplexArray(int nsamp, FortranComplex64 *d);
ComplexArray(int nsamp, float *d);
ComplexArray(int nsamp, double *d);
ComplexArray(int nsamp);
/*! Construct from different length of vector, adds zoeros to it
And construct a constant arrays
*/
template<class T> ComplexArray(int nsamp, std::vector<T> d);
template<class T> ComplexArray(int nsamp, T d);
/*! Construct from magnitude and phase arrays.*/
ComplexArray(std::vector<double> mag,std::vector<double> phase);
/* These will need to be implemented. Likely cannot
depend on the compiler to generate them correctly */
ComplexArray(const ComplexArray &parent);
ComplexArray& operator=(const ComplexArray &parent);
~ComplexArray();
/* These are kind of the inverse of the constructor.
Independent of what the internal representation is they
will return useful interface representations. */
/*! Return a pointer to a fortran array containing
the data vector.
The array linked to the returned pointer should be
created with the new operator and the caller should
be sure to use delete [] to free this memory when
finished. */
template<class T> T *FortranData();
/* This is same for what I think fortran calls
double complex */
// double *FortranData();
/* C representation. This can be templated easily.
See below. The syntax is weird and should probably
be wrapped with a typedef */
template<class T> std::vector<std::complex<T> > CPPData();
/* Operators are the most important elements of this
thing to make life easier. */
/*! Index operator.
Cannot make it work by getting the address from reference.
Have to call the ptr() function to get the address.
\param sample is the sample number to return.
\return contents of vector at position sample.
*/
Complex64 operator[](int sample);
double *ptr();
double *ptr(int sample);
ComplexArray& operator +=(const ComplexArray& other) noexcept(false);
ComplexArray& operator -=(const ComplexArray& other) noexcept(false);
/* This actually is like .* in matlab - sample by sample multiply not
a dot product */
ComplexArray& operator *= (const ComplexArray& other)noexcept(false);
/* This is like *= but complex divide element by element */
ComplexArray& operator /= (const ComplexArray& other)noexcept(false);
const ComplexArray operator +(const ComplexArray& other)const noexcept(false);
//template<class T> ComplexArray operator +(const vector<T> &other);
//template<class T> ComplexArray operator +(const T &other);
const ComplexArray operator -(const ComplexArray& other)const noexcept(false);
//template<class T> ComplexArray operator -(const vector<T> &other);
//template<class T> ComplexArray operator -(const T &other);
const ComplexArray operator *(const ComplexArray& other)const noexcept(false);
const ComplexArray operator /(const ComplexArray& other)const noexcept(false);
/*! product of complex and real vectors */
//template<class T> ComplexArray operator *(const vector<T> &other);
//template<class T> friend ComplexArray operator *(const vector<T> &lhs,const ComplexArray &rhs);
/*! product of complex and a number */
//template<class T> ComplexArray operator *(const T &other);
//template<class T> friend ComplexArray operator *(const T &lhs,const ComplexArray &rhs);
/*! Change vector to complex conjugates. */
void conj();
/* Return stl vector of amplitude spectrum. */
std::vector<double> abs() const;
/* Return rms value. */
double rms() const;
/* Return 2-norm value. */
double norm2() const;
/* Return stl vector of phase */
std::vector<double> phase() const;
/* Return size of the array*/
int size() const;
private:
/* Here is an implementation detail. There are three ways
I can think to do this. First, we could internally store
data as fortran array of 32 bit floats. That is probably
the best because we can use BLAS routines (if you haven't
heard of this - likely - I need to educate you.) to do
most of the numerics fast. Second, we could use stl
vector container of std::complex. The third is excessively
messy but technically feasible - I would not recommend it.
That is, one could store pointers to either representation
and internally convert back and forth. Ugly and dangerous
I think.
I suggest we store a FORTRAN 32 bit form since that is
what standard numeric libraries (e.g. most fft routines)
use. */
/*I decided to use 64 bit, since the GSL's fft routine is using that.*/
FortranComplex64 *data;
int nsamp;
};
/* This would normally be in the .h file and since I don't think
you've used templates worth showing you how it would work. */
template <class T> std::vector<std::complex<T> > ComplexArray::CPPData()
{
std::vector<std::complex<T> > result;
result.reserve(nsamp);
int i;
for(i=0; i<nsamp; ++i)
{
std::complex<T> z(data[i].real, data[i].imag);
result.push_back(z);
}
return result;
}
template<class T> T* ComplexArray::FortranData()
{
T* result=new T[nsamp];
for(int i=0; i<nsamp; i++)
result[i]=data[i];
return result;
}
template<class T> ComplexArray::ComplexArray(int n, std::vector<T> d)
{
nsamp=n;
if(nsamp>d.size())
{
data=new FortranComplex64[nsamp];
for(int i=0; i<d.size(); i++)
{
data[i].real=d[i];
data[i].imag=0.0;
}
for(int i=d.size(); i<nsamp; i++)
{
data[i].real=0.0;
data[i].imag=0.0;
}
}
else
{
data=new FortranComplex64[nsamp];
for(int i=0; i<nsamp; i++)
{
data[i].real=d[i];
data[i].imag=0.0;
}
}
}
template<class T> ComplexArray::ComplexArray(int n, T d)
{
nsamp=n;
data=new FortranComplex64[nsamp];
for(int i=0; i<nsamp; i++)
{
data[i].real=d;
data[i].imag=0.0;
}
}
/*
template<class T> ComplexArray ComplexArray::operator +(const vector<T> &other)
{
ComplexArray result(*this);
int n;
if(nsamp>other.size())
n=other.size();
else
n=nsamp;
for(int i=0; i<n; i++)
{
result.data[i].real=data[i].real+other[i];
}
return result;
}
template<class T> ComplexArray ComplexArray::operator +(const T &other)
{
ComplexArray result(*this);
for(int i=0; i<nsamp; i++)
{
result.data[i].real=data[i].real+other;
}
return result;
}
template<class T> ComplexArray ComplexArray::operator -(const vector<T> &other)
{
ComplexArray result(*this);
int n;
if(nsamp>other.size())
n=other.size();
else
n=nsamp;
for(int i=0; i<n; i++)
{
result.data[i].real=data[i].real-other[i];
}
return result;
}
template<class T> ComplexArray ComplexArray::operator -(const T &other)
{
ComplexArray result(*this);
for(int i=0; i<nsamp; i++)
{
result.data[i].real=data[i].real-other;
}
return result;
}
template<class T> ComplexArray ComplexArray::operator *(const vector<T> &other)
{
ComplexArray result(*this);
int n;
if(nsamp>other.size())
n=other.size();
else
n=nsamp;
for(int i=0; i<n; i++)
{
result.data[i].real=data[i].real*other[i];
result.data[i].imag=data[i].imag*other[i];
}
return result;
}
template<class T> ComplexArray operator *(const vector<T>& lhs,const ComplexArray& rhs)
{
return rhs*lhs;
}
template<class T> ComplexArray ComplexArray::operator *(const T &other)
{
ComplexArray result(*this);
for(int i=0; i<nsamp; i++)
{
result.data[i].real=data[i].real*other;
result.data[i].imag=data[i].imag*other;
}
return result;
}
template<class T> ComplexArray operator *(const T& lhs,const ComplexArray& rhs)
{
return rhs*lhs;
}
*/
}
#endif
| {
"alphanum_fraction": 0.6468977141,
"avg_line_length": 32.2891156463,
"ext": "h",
"hexsha": "d301584273f6220d0a8bf0b33bb12939cbcad7e0",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2021-10-01T05:59:50.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-08-03T18:40:04.000Z",
"max_forks_repo_head_hexsha": "7ac6db4afa7577f0e67981490fd89d50e35bf4c7",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "Yangzhengtang/mspass",
"max_forks_repo_path": "cxx/include/mspass/algorithms/deconvolution/ComplexArray.h",
"max_issues_count": 151,
"max_issues_repo_head_hexsha": "7ac6db4afa7577f0e67981490fd89d50e35bf4c7",
"max_issues_repo_issues_event_max_datetime": "2021-06-22T03:41:09.000Z",
"max_issues_repo_issues_event_min_datetime": "2019-09-27T23:19:55.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "Yangzhengtang/mspass",
"max_issues_repo_path": "cxx/include/mspass/algorithms/deconvolution/ComplexArray.h",
"max_line_length": 101,
"max_stars_count": 11,
"max_stars_repo_head_hexsha": "7ac6db4afa7577f0e67981490fd89d50e35bf4c7",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "Yangzhengtang/mspass",
"max_stars_repo_path": "cxx/include/mspass/algorithms/deconvolution/ComplexArray.h",
"max_stars_repo_stars_event_max_datetime": "2021-05-19T14:59:03.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-08-28T16:02:44.000Z",
"num_tokens": 2366,
"size": 9493
} |
#pragma once
#include <SDL2/SDL.h>
#include <SDL2/SDL_audio.h>
#include <chrono>
#include <cstdint>
#include <gsl/span>
#include <queue>
class CSound
{
private:
static constexpr std::int32_t Frequency{ 44100 };
struct SBeep
{
double Frequency;
std::uint32_t SamplesLeft;
};
SDL_AudioDeviceID mDeviceID;
std::queue<SBeep> mBeeps;
double mV;
public:
CSound();
~CSound();
void Beep(double frequency, std::chrono::milliseconds duration);
private:
void GenerateSamples(gsl::span<std::int16_t> stream);
static void SdlCallback(CSound* self, std::uint8_t* stream, std::int32_t len);
};
| {
"alphanum_fraction": 0.7242524917,
"avg_line_length": 17.2,
"ext": "h",
"hexsha": "4933509cf87bcbf8b47cac72f2a09d4db2eeb5a7",
"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": "56ad90665956b874537ee2c525f16cad7f6efa07",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "alexguirre/chip8-interpreter",
"max_forks_repo_path": "src/application/Sound.h",
"max_issues_count": 18,
"max_issues_repo_head_hexsha": "56ad90665956b874537ee2c525f16cad7f6efa07",
"max_issues_repo_issues_event_max_datetime": "2019-10-20T01:23:28.000Z",
"max_issues_repo_issues_event_min_datetime": "2019-09-29T18:10:54.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "alexguirre/chip8-interpreter",
"max_issues_repo_path": "src/application/Sound.h",
"max_line_length": 79,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "56ad90665956b874537ee2c525f16cad7f6efa07",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "alexguirre/chip8-interpreter",
"max_stars_repo_path": "src/application/Sound.h",
"max_stars_repo_stars_event_max_datetime": "2021-08-10T00:17:05.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-08-10T00:17:05.000Z",
"num_tokens": 170,
"size": 602
} |
/* Author: G. Jungman
*/
#include <config.h>
#include <gsl/gsl_ieee_utils.h>
#include "gsl_qrng.h"
int 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);
/* 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_qrng_free(g);
return status;
}
int 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);
/* 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_qrng_free(g);
return status;
}
int main()
{
int status = 0;
gsl_ieee_env_setup ();
status += test_sobol();
status += test_nied2();
return status;
}
| {
"alphanum_fraction": 0.5554359526,
"avg_line_length": 21.1136363636,
"ext": "c",
"hexsha": "915ef76419ab6ac2de2c1d21bc46e1109eba0a90",
"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/qrng/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/qrng/test.c",
"max_line_length": 65,
"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/qrng/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": 773,
"size": 1858
} |
/*
* Copyright 2014 Marc Normandin
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef INC_PARTICLE_H
#define INC_PARTICLE_H
#include <iostream>
#include <vector>
#include <algorithm>
#include <functional>
#include <cmath>
#include <cstdlib>
#include <gsl/gsl_rng.h>
#include <limits>
#include <fstream>
#include <cassert>
#include "rng.h"
#include "dim.h"
class Particle
{
public:
typedef std::vector<dim_t> dvector;
Particle();
Particle(const std::vector<Dim>& dim);
Particle(const dvector& pos, const prob_t fitness = -1.0 * std::numeric_limits<dim_t>::max());
const dvector& getPosition() const;
dvector getVelocity() const;
double getFitness() const;
dvector getPBestPosition() const;
double getPBestFitness() const;
void updateFitness(const prob_t newFitness);
void updatePosition(const Particle& GBest, const std::vector<Dim>& dim, const double C1, const double C2,
const RandomNumberGenerator& rng, const double inertiaWeight);
size_t size() const;
friend bool operator<(const Particle& p1, const Particle& p2);
private:
dvector mPos;
dvector mVel;
prob_t mFitness;
// The particles best position
dvector mPBestPos;
prob_t mPBestFitness;
};
bool operator<(const Particle& p1, const Particle& p2);
#endif // #ifndef INC_PARTICLE_H
| {
"alphanum_fraction": 0.6751140395,
"avg_line_length": 25.6233766234,
"ext": "h",
"hexsha": "e087cccaba8bbf2e06ba7c4cceef2b8311871da0",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "6690fde0de155acd44ba5a3eab4224276f120ed5",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "marcnormandin/ParticleSwarmOptimization",
"max_forks_repo_path": "particle.h",
"max_issues_count": 6,
"max_issues_repo_head_hexsha": "6690fde0de155acd44ba5a3eab4224276f120ed5",
"max_issues_repo_issues_event_max_datetime": "2015-06-11T20:48:15.000Z",
"max_issues_repo_issues_event_min_datetime": "2015-05-27T05:48:44.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "marcnormandin/ParticleSwarmOptimization",
"max_issues_repo_path": "particle.h",
"max_line_length": 109,
"max_stars_count": 5,
"max_stars_repo_head_hexsha": "6690fde0de155acd44ba5a3eab4224276f120ed5",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "marcnormandin/ParticleSwarmOptimization",
"max_stars_repo_path": "particle.h",
"max_stars_repo_stars_event_max_datetime": "2018-04-09T21:25:19.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-05-28T05:27:28.000Z",
"num_tokens": 465,
"size": 1973
} |
#include <gsl/gsl_qrng.h>
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char* argv[]) {
if (argc < 3) {
printf("Usage: ./sampling <dimensions> <samples>\n");
return 0;
}
int dimensions = atoi(argv[1]);
int samples = atoi(argv[2]);
if (samples < 0) {
printf("Invalid number of samples: %d\n", samples);
return 0;
}
gsl_qrng * q;
if (dimensions <= 0) {
printf("Invalid number of dimensions\n");
return 1;
}
else if (dimensions <= 12) q = gsl_qrng_alloc (gsl_qrng_niederreiter_2, dimensions);
else if (dimensions <= 40) q = gsl_qrng_alloc (gsl_qrng_sobol, dimensions);
else if (dimensions <= 1229) q = gsl_qrng_alloc (gsl_qrng_halton, dimensions);
else {
printf("Invalid number of dimensions (max 1229 supported): dimensions\n", dimensions);
return 1;
}
for (int i = 0; i < samples; i++) {
double v[dimensions];
gsl_qrng_get(q, v);
for (int d = 0; d < dimensions; d++) {
printf("%f ", v[d]);
}
printf ("\n");
}
gsl_qrng_free(q);
return 0;
}
| {
"alphanum_fraction": 0.56069869,
"avg_line_length": 25.4444444444,
"ext": "c",
"hexsha": "f5160fbd05a4fceefb0545bb803d34940cf5d306",
"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": "cf3da8aff88df63331ce8cd2b43d50e6a2f9b3b1",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "EDACC/edacc_aac",
"max_forks_repo_path": "contrib/sampling/sampling.c",
"max_issues_count": 2,
"max_issues_repo_head_hexsha": "cf3da8aff88df63331ce8cd2b43d50e6a2f9b3b1",
"max_issues_repo_issues_event_max_datetime": "2017-10-17T09:03:53.000Z",
"max_issues_repo_issues_event_min_datetime": "2017-10-17T08:22:47.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "EDACC/edacc_aac",
"max_issues_repo_path": "contrib/sampling/sampling.c",
"max_line_length": 94,
"max_stars_count": 2,
"max_stars_repo_head_hexsha": "cf3da8aff88df63331ce8cd2b43d50e6a2f9b3b1",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "EDACC/edacc_aac",
"max_stars_repo_path": "contrib/sampling/sampling.c",
"max_stars_repo_stars_event_max_datetime": "2017-04-18T17:27:50.000Z",
"max_stars_repo_stars_event_min_datetime": "2016-07-13T20:06:12.000Z",
"num_tokens": 328,
"size": 1145
} |
/*
FRACTAL - A program growing fractals to benchmark parallelization and drawing
libraries.
Copyright 2009-2021, Javier Burguete Tolosa.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY Javier Burguete Tolosa ``AS IS'' AND ANY EXPRESS
OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
EVENT SHALL Javier Burguete Tolosa OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* \file fractal.c
* \brief Source file to define the fractal data and functions.
* \author Javier Burguete Tolosa.
* \copyright Copyright 2009-2021, Javier Burguete Tolosa.
*/
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <time.h>
#if HAVE_SYSINFO
#include <sys/sysinfo.h>
#endif
#include <gsl/gsl_rng.h>
#include <libxml/parser.h>
#include <glib.h>
#if HAVE_GTOP
#include <glibtop.h>
#include <glibtop/close.h>
#endif
#ifdef G_OS_WIN32
#include <windows.h>
#endif
#include <libintl.h>
#include <GL/glew.h>
#include <ft2build.h>
#include FT_FREETYPE_H
#include <gtk/gtk.h>
#include "config.h"
#include "fractal.h"
#include "simulator.h"
extern void draw ();
unsigned int width = WIDTH; ///< Medium width.
unsigned int height = HEIGHT; ///< Medium height.
unsigned int length = LENGTH; ///< Medium length.
unsigned int area; ///< Medium area.
unsigned int medium_bytes; ///< Number of bytes used by the medium.
unsigned int breaking = 0; ///< 1 on breaking, 0 otherwise.
unsigned int simulating = 0; ///< 1 on simulating, 0 otherwise.
unsigned int animating = 1; ///< 1 on animating, 0 otherwise.
unsigned int fractal_type = FRACTAL_TYPE_TREE; ///< Fractal type.
unsigned int fractal_3D = 0; ///< 1 on 3D fractals, 0 on 2D fractals.
unsigned int fractal_diagonal = 0;
///< 1 on diagonal point movement, 0 otherwise.
unsigned long t0; ///< Computational time.
unsigned int max_d = 0; ///< Maximum fractal size.
unsigned int *medium = NULL; ///< Array of fractal points.
Point3D *point = NULL; ///< Array of 3D points.
unsigned int npoints = 0; ///< Number of points.
unsigned int random_algorithm = 0;
///< Type of random numbers generator algorithm.
unsigned int random_seed_type = 1; ///< Type of random seed.
unsigned long random_seed = SEED; ///< Random seed.
static void *(*parallel_fractal) (gsl_rng * rng);
///< Pointer to the function to calculate the fractal.
static const float color3f[16][3] = {
{0., 0., 0.},
{1., 0., 0.},
{0., 1., 0.},
{0., 0., 1.},
{0.5, 0.5, 0.},
{0.5, 0., 0.5},
{0., 0.5, 0.5},
{0.5, 0.25, 0.25},
{0.25, 0.5, 0.25},
{0.25, 0.25, 0.5},
{0.75, 0.25, 0.},
{0.75, 0., 0.25},
{0.25, 0.75, 0.},
{0., 0.75, 0.25},
{0.25, 0., 0.75},
{0., 0.25, 0.75}
}; ///< Array of colors.
DialogOptions dialog_options[1];
///< DialogOptions to set the fractal options.
DialogSimulator dialog_simulator[1];
///< DialogSimulator to show the main window.
// PARALLELIZING DATA
unsigned int nthreads; ///< Threads number.
GMutex mutex[1]; ///< Mutex to lock memory saves.
// END
/**
* Function to return the square of an unsigned int.
* \return square.
*/
static inline unsigned int
sqr (int x) ///< unsigned int.
{
return x * x;
}
/**
* Function to get the number of cores of the CPU.
*
* \return CPU number of cores.
*/
int
threads_number ()
{
#if HAVE_GTOP
int ncores;
glibtop *top;
top = glibtop_init ();
ncores = top->ncpu + 1;
glibtop_close ();
return ncores;
#elif HAVE_GET_NPROCS
return get_nprocs ();
#elif defined(G_OS_WIN32)
SYSTEM_INFO sysinfo;
GetSystemInfo (&sysinfo);
return sysinfo.dwNumberOfProcessors;
#else
return (int) sysconf (_SC_NPROCESSORS_ONLN);
#endif
}
/**
* Function to add a point to the array.
*/
static inline void
points_add (int x, ///< Point x-coordinate.
int y, ///< Point y-coordinate.
int z, ///< Point z-coordinate.
unsigned int c) ///< Point color.
{
Point3D *p;
++npoints;
point = (Point3D *) g_realloc (point, npoints * sizeof (Point3D));
p = point + npoints - 1;
p->r[0] = x;
p->r[1] = y;
p->r[2] = z;
memcpy (p->c, color3f[c], 3 * sizeof (float));
}
/**
* Function to make a random 2D movement on a point.
*/
static inline void
point_2D_move (int *x, ///< Point x-coordinate.
int *y, ///< Point y-coordinate.
gsl_rng * rng) ///< Pseudo-random number generator.
{
register unsigned int k;
static const int mx[4] = { 0, 0, 1, -1 }, my[4] = { 1, -1, 0, 0 };
k = gsl_rng_uniform_int (rng, 4);
*x += mx[k];
*y += my[k];
}
/**
* Function to make a random 2D movement on a point enabling diagonals.
*/
static inline void
point_2D_move_diagonal (int *x, ///< Point x-coordinate.
int *y, ///< Point y-coordinate.
gsl_rng * rng) ///< Pseudo-random number generator.
{
register unsigned int k;
static const int mx[8] = { 1, 1, 1, 0, -1, -1, -1, 0 },
my[8] = { 1, 0, -1, -1, -1, 0, 1, 1 };
k = gsl_rng_uniform_int (rng, 8);
*x += mx[k];
*y += my[k];
}
/**
* Function to make a random 3D movement on a point.
*/
static inline void
point_3D_move (int *x, ///< Point x-coordinate.
int *y, ///< Point y-coordinate.
int *z, ///< Point z-coordinate.
gsl_rng * rng) ///< Pseudo-random number generator.
{
register unsigned int k;
static const int mx[6] = { 0, 1, -1, 0, 0, 0 },
my[6] = { 0, 0, 0, 1, -1, 0 }, mz[6] = { 1, 0, 0, 0, 0, -1 };
k = gsl_rng_uniform_int (rng, 6);
*x += mx[k];
*y += my[k];
*z += mz[k];
}
/**
* Function to make a random 3D movement on a point enabling diagonals.
*/
static inline void
point_3D_move_diagonal (int *x, ///< Point x-coordinate.
int *y, ///< Point y-coordinate.
int *z, ///< Point z-coordinate.
gsl_rng * rng) ///< Pseudo-random number generator.
{
register int k;
static const int mx[26] = {
1, 1, 1, 0, 0, 0, -1, -1, -1,
1, 1, 1, 0, 0, -1, -1, -1,
1, 1, 1, 0, 0, 0, -1, -1, -1
}, my[26] = {
1, 0, -1, 1, 0, -1, 1, 0, -1,
1, 0, -1, 1, -1, 1, 0, -1, 1, 0, -1, 1, 0, -1, 1, 0, -1
}, mz[26] = {
1, 1, 1, 1, 1, 1, 1, 1, 1,
0, 0, 0, 0, 0, 0, 0, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1
};
k = gsl_rng_uniform_int (rng, 26);
*x += mx[k];
*y += my[k];
*z += mz[k];
}
/**
* Function to start a new 2D tree point.
*/
static inline void
tree_2D_point_new (int *x, ///< Point x-coordinate.
int *y, ///< Point y-coordinate.
gsl_rng * rng) ///< Pseudo-random number generator.
{
*x = gsl_rng_uniform_int (rng, width);
*y = max_d;
#if DEBUG
printf ("New point x %d y %d\n", *x, *y);
#endif
}
/**
* Function to check the limits of a 2D tree point.
*/
static inline void
tree_2D_point_boundary (int *x, ///< Point x-coordinate.
int *y, ///< Point y-coordinate.
gsl_rng * rng) ///< Pseudo-random number generator.
{
if (*y < 0 || *y == (int) height)
{
tree_2D_point_new (x, y, rng);
return;
}
if (*x < 0)
*x = width - 1;
else if (*x == (int) width)
*x = 0;
#if DEBUG
printf ("Boundary point x %d y %d\n", *x, *y);
#endif
}
/**
* Function to fix a 2D tree point.
*
* \return 1 on fixing point, 0 on otherwise.
*/
static inline unsigned int
tree_2D_point_fix (int x, ///< Point x-coordinate.
int y) ///< Point y-coordinate.
{
register unsigned int *point;
#if DEBUG
printf ("x=%d y=%d max_d=%d width=%d height=%d\n", x, y, max_d, width,
height);
#endif
if (y > (int) max_d || x == 0 || y == 0 || x == (int) width - 1
|| y == (int) height - 1)
return 0;
point = medium + y * width + x;
if (point[1] || point[-1] || point[width] || point[-(int) width])
{
#if DEBUG
printf ("fixing point\n");
#endif
// PARALLELIZING MUTEX
g_mutex_lock (mutex);
point[0] = 2;
points_add (x, y, 0, 2);
g_mutex_unlock (mutex);
// END
return 1;
}
return 0;
}
/**
* Function to init a 2D tree.
*/
static inline void
tree_2D_init ()
{
medium[width / 2] = 2;
}
/**
* Function to check the end a 2D tree.
*
* \return 1 on ending, 0 on continuing.
*/
static inline unsigned int
tree_2D_end (int y) ///< Point y-coordinate.
{
if (y == (int) max_d)
{
// PARALLELIZING MUTEX
g_mutex_lock (mutex);
++max_d;
g_mutex_unlock (mutex);
// END
}
if (max_d >= height - 1)
{
// PARALLELIZING MUTEX
g_mutex_lock (mutex);
max_d = height - 1;
g_mutex_unlock (mutex);
// END
return 1;
}
return 0;
}
/**
* Function to start a new 3D tree point.
*/
static inline void
tree_3D_point_new (int *x, ///< Point x-coordinate.
int *y, ///< Point y-coordinate.
int *z, ///< Point z-coordinate.
gsl_rng * rng) ///< Pseudo-random number generator.
{
*x = gsl_rng_uniform_int (rng, length);
*y = gsl_rng_uniform_int (rng, width);
*z = max_d;
#if DEBUG
printf ("New point x %d y %d z %d\n", *x, *y, *z);
#endif
}
/**
* Function to check the limits of a 2D tree point.
*/
static inline void
tree_3D_point_boundary (int *x, ///< Point x-coordinate.
int *y, ///< Point y-coordinate.
int *z, ///< Point z-coordinate.
gsl_rng * rng) ///< Pseudo-random number generator.
{
if (*z < 0 || *z == (int) height)
{
tree_3D_point_new (x, y, z, rng);
return;
}
if (*x < 0)
*x = length - 1;
else if (*x == (int) length)
*x = 0;
if (*y < 0)
*y = width - 1;
else if (*y == (int) width)
*y = 0;
#if DEBUG
printf ("New point x %d y %d z %d\n", *x, *y, *z);
#endif
}
/**
* Function to fix a 2D tree point.
*
* \return 1 on fixing point, 0 on otherwise.
*/
static inline unsigned int
tree_3D_point_fix (int x, ///< Point x-coordinate.
int y, ///< Point y-coordinate.
int z) ///< point z-coordinate.
{
register unsigned int *point;
if (z > (int) max_d || z == 0 || y == 0 || x == 0 || z == (int) height - 1
|| y == (int) width - 1 || x == (int) length - 1)
return 0;
point = medium + z * area + y * length + x;
if (point[1] || point[-1] || point[length] || point[-(int) length]
|| point[area] || point[-(int) area])
{
// PARALLELIZING MUTEX
g_mutex_lock (mutex);
point[0] = 2;
points_add (x, y, z, 2);
g_mutex_unlock (mutex);
// END
return 1;
}
return 0;
}
/**
* Function to init a 3D tree.
*/
static inline void
tree_3D_init ()
{
medium[length * (width / 2) + length / 2] = 2;
}
/**
* Function to check the end a 3D tree.
*
* \return 1 on ending, 0 on continuing.
*/
static inline unsigned int
tree_3D_end (int z) ///< Point z-coordinate.
{
if (z == (int) max_d)
{
// PARALLELIZING MUTEX
g_mutex_lock (mutex);
++max_d;
g_mutex_unlock (mutex);
// END
}
if (max_d >= height - 1)
{
// PARALLELIZING MUTEX
g_mutex_lock (mutex);
max_d = height - 1;
g_mutex_unlock (mutex);
// END
return 1;
}
return 0;
}
/**
* Function to check the limits of a 2D forest point.
*/
static inline void
forest_2D_point_boundary (int *x, ///< Point x-coordinate.
int *y, ///< Point y-coordinate.
gsl_rng * rng)
///< Pseudo-random number generator.
{
if (*y == (int) height || *y < 0)
{
tree_2D_point_new (x, y, rng);
return;
}
if (*x < 0)
*x = width - 1;
else if (*x == (int) width)
*x = 0;
#if DEBUG
printf ("Boundary point x %d y %d\n", *x, *y);
#endif
}
/**
* Function to fix a 2D forest point.
*
* \return 1 on fixing point, 0 on otherwise.
*/
static inline unsigned int
forest_2D_point_fix (int x, ///< Point x-coordinate.
int y, ///< Point y-coordinate.
gsl_rng * rng) ///< Pseudo-random number generator.
{
register unsigned int k, *point;
if (y > (int) max_d || x == 0 || x == (int) width - 1
|| y == (int) height - 1)
return 0;
point = medium + y * width + x;
if (y == 0)
{
k = 1 + gsl_rng_uniform_int (rng, 15);
goto forest;
}
k = point[1];
if (k)
goto forest;
k = point[-1];
if (k)
goto forest;
k = point[width];
if (k)
goto forest;
k = point[-(int) width];
if (k)
goto forest;
return 0;
forest:
// PARALLELIZING MUTEX
g_mutex_lock (mutex);
point[0] = k;
points_add (x, y, 0, k);
g_mutex_unlock (mutex);
// END
return k;
}
/**
* Function to check the limits of a 3D forest point.
*/
static inline void
forest_3D_point_boundary (int *x, ///< Point x-coordinate.
int *y, ///< Point y-coordinate.
int *z, ///< Point z-coordinate.
gsl_rng * rng)
///< Pseudo-random number generator.
{
if (*z == (int) height || *z < 0)
{
tree_3D_point_new (x, y, z, rng);
return;
}
if (*y < 0)
*y = width - 1;
else if (*y == (int) width)
*y = 0;
if (*x < 0)
*x = length - 1;
else if (*x == (int) length)
*x = 0;
#if DEBUG
printf ("Boundary point x %d y %d z %d\n", *x, *y, *z);
#endif
}
/**
* Function to fix a 3D forest point.
*
* \return 1 on fixing point, 0 on otherwise.
*/
static inline unsigned int
forest_3D_point_fix (int x, ///< Point x-coordinate.
int y, ///< Point y-coordinate.
int z, ///< Point z-coordinate.
gsl_rng * rng) ///< Pseudo-random number generator.
{
register unsigned int k, *point;
if (z > (int) max_d || y == 0 || x == 0 || z == (int) height - 1
|| y == (int) width - 1 || x == (int) length - 1)
return 0;
point = medium + z * area + y * length + x;
if (z == 0)
{
k = 1 + gsl_rng_uniform_int (rng, 15);
goto forest;
}
k = point[1];
if (k)
goto forest;
k = point[-1];
if (k)
goto forest;
k = point[length];
if (k)
goto forest;
k = point[-(int) length];
if (k)
goto forest;
k = point[area];
if (k)
goto forest;
k = point[-(int) area];
if (k)
goto forest;
return 0;
forest:
// PARALLELIZING MUTEX
g_mutex_lock (mutex);
point[0] = k;
points_add (x, y, z, k);
g_mutex_unlock (mutex);
// END
return k;
}
/**
* Function to start a new 2D neuron point.
*/
static inline void
neuron_2D_point_new (int *x, ///< Point x-coordinate.
int *y, ///< Point y-coordinate.
gsl_rng * rng) ///< Pseudo-random number generator.
{
register double angle;
angle = 2 * M_PI * gsl_rng_uniform (rng);
*x = width / 2 + max_d * cos (angle);
*y = height / 2 + max_d * sin (angle);
#if DEBUG
printf ("New point x %d y %d\n", *x, *y);
#endif
}
/**
* Function to check the limits of a 2D neuron point.
*/
static inline void
neuron_2D_point_boundary (int *x, ///< Point x-coordinate.
int *y, ///< Point y-coordinate.
gsl_rng * rng)
///< Pseudo-random number generator.
{
if (*y < 0 || *y == (int) height || *x < 0 || *x == (int) width)
{
neuron_2D_point_new (x, y, rng);
#if DEBUG
printf ("Boundary point x %d y %d\n", *x, *y);
#endif
}
}
/**
* Function to fix a 2D neuron point.
*
* \return 1 on fixing point, 0 on otherwise.
*/
static inline unsigned int
neuron_2D_point_fix (int x, ///< Point x-coordinate.
int y) ///< Point y-coordinate.
{
register unsigned int *point;
if (x == 0 || y == 0 || x == (int) width - 1 || y == (int) height - 1)
return 0;
point = medium + y * width + x;
if (point[1] || point[-1] || point[width] || point[-(int) width])
{
// PARALLELIZING MUTEX
g_mutex_lock (mutex);
point[0] = 2;
points_add (x, y, 0, 2);
g_mutex_unlock (mutex);
// END
return 1;
}
return 0;
}
/**
* Function to init a 2D neuron.
*/
static inline void
neuron_2D_init ()
{
medium[(height / 2) * width + width / 2] = 2;
}
/**
* Function to check the end a 2D neuron.
*
* \return 1 on ending, 0 on continuing.
*/
static inline unsigned int
neuron_2D_end (int x, ///< Point x-coordinate.
int y) ///< Point y-coordinate.
{
register int r, k;
r = 1 + round (sqrt (sqr (x - width / 2) + sqr (y - height / 2)));
if (r >= (int) max_d)
{
// PARALLELIZING MUTEX
g_mutex_lock (mutex);
++max_d;
g_mutex_unlock (mutex);
// END
}
if (height < width)
k = height;
else
k = width;
k = k / 2 - 1;
if ((int) max_d >= k)
{
// PARALLELIZING MUTEX
g_mutex_lock (mutex);
max_d = k;
g_mutex_unlock (mutex);
// END
return 1;
}
return 0;
}
/**
* Function to start a new 3D neuron point.
*/
static inline void
neuron_3D_point_new (int *x, ///< Point x-coordinate.
int *y, ///< Point y-coordinate.
int *z, ///< Point z-coordinate.
gsl_rng * rng) ///< Pseudo-random number generator.
{
double c1, s1, c2, s2;
sincos (2. * M_PI * gsl_rng_uniform (rng), &s1, &c1);
sincos (asin (2. * gsl_rng_uniform (rng) - 1), &s2, &c2);
*x = length / 2 + max_d * c1 * c2;
*y = width / 2 + max_d * s1 * c2;
*z = height / 2 + max_d * s2;
#if DEBUG
printf ("New point x %d y %d z %d\n", *x, *y, *z);
#endif
}
/**
* Function to check the limits of a 3D neuron point.
*/
static inline void
neuron_3D_point_boundary (int *x, ///< Point x-coordinate.
int *y, ///< Point y-coordinate.
int *z, ///< Point z-coordinate.
gsl_rng * rng)
///< Pseudo-random number generator.
{
if (*z < 0 || *y < 0 || *x < 0 || *z == (int) height || *y == (int) width
|| *x == (int) length)
{
neuron_3D_point_new (x, y, z, rng);
#if DEBUG
printf ("Boundary point x %d y %d z %d\n", *x, *y, *z);
#endif
}
}
/**
* Function to fix a 3D neuron point.
*
* \return 1 on fixing point, 0 on otherwise.
*/
static inline unsigned int
neuron_3D_point_fix (int x, ///< Point x-coordinate.
int y, ///< Point y-coordinate.
int z) ///< Point z-coordinate.
{
register unsigned int *point;
if (z == 0 || y == 0 || x == 0 || z == (int) height - 1
|| y == (int) width - 1 || x == (int) length - 1)
return 0;
point = medium + z * area + y * length + x;
if (point[1] || point[-1] || point[length] || point[-(int) length] ||
point[area] || point[-(int) area])
{
// PARALLELIZING MUTEX
g_mutex_lock (mutex);
point[0] = 2;
points_add (x, y, z, 2);
g_mutex_unlock (mutex);
// END
return 1;
}
return 0;
}
/**
* Function to init a 3D neuron.
*/
static inline void
neuron_3D_init ()
{
medium[area * (height / 2) + length * (width / 2) + length / 2] = 2;
}
/**
* Function to check the end a 3D neuron.
*
* \return 1 on ending, 0 on continuing.
*/
static inline unsigned int
neuron_3D_end (int x, ///< Point x-coordinate.
int y, ///< Point y-coordinate.
int z) ///< Point z-coordinate.
{
register int r, k;
r = 1 + sqrt (sqr (x - length / 2) + sqr (y - width / 2)
+ sqr (z - height / 2));
if (r >= (int) max_d)
{
// PARALLELIZING MUTEX
g_mutex_lock (mutex);
++max_d;
g_mutex_unlock (mutex);
// END
}
k = length;
if ((int) width < k)
k = width;
if ((int) height < k)
k = height;
k = k / 2 - 1;
if ((int) max_d >= k)
{
// PARALLELIZING MUTEX
g_mutex_lock (mutex);
max_d = k;
g_mutex_unlock (mutex);
// END
return 1;
}
return 0;
}
/**
* Function to stop the fractal simulation.
*/
void
fractal_stop ()
{
// PARALLELIZING MUTEX
g_mutex_lock (mutex);
breaking = 1;
g_mutex_unlock (mutex);
// END
}
// PARALLELIZED FUNCTIONS
/**
* Function to create a 2D fractal tree.
*
* \return NULL.
*/
void *
parallel_fractal_tree_2D (gsl_rng * rng)
///< Pseudo-random number generator.
{
int x, y;
long t0;
#if DEBUG
printf ("parallel_fractal_tree_2D: start\n");
#endif
t0 = time (NULL);
do
{
#if DEBUG
printf ("creating point\n");
#endif
tree_2D_point_new (&x, &y, rng);
#if DEBUG
printf ("checking fix\n");
#endif
while (!breaking && !tree_2D_point_fix (x, y))
{
#if DEBUG
printf ("moving point\n");
#endif
point_2D_move (&x, &y, rng);
#if DEBUG
printf ("checking boundary\n");
#endif
tree_2D_point_boundary (&x, &y, rng);
}
#if DEBUG
printf ("checking end\n");
#endif
if (animating && time (NULL) > t0)
break;
if (tree_2D_end (y))
fractal_stop ();
}
while (!breaking);
g_thread_exit (NULL);
return NULL;
}
/**
* Function to create a 3D fractal tree.
*
* \return NULL.
*/
void *
parallel_fractal_tree_3D (gsl_rng * rng)
///< Pseudo-random number generator.
{
int x, y, z;
long t0;
t0 = time (NULL);
do
{
tree_3D_point_new (&x, &y, &z, rng);
while (!breaking && !tree_3D_point_fix (x, y, z))
{
point_3D_move (&x, &y, &z, rng);
tree_3D_point_boundary (&x, &y, &z, rng);
}
if (animating && time (NULL) > t0)
break;
if (tree_3D_end (z))
fractal_stop ();
}
while (!breaking);
g_thread_exit (NULL);
return NULL;
}
/**
* Function to create a 2D fractal forest.
*
* \return NULL.
*/
void *
parallel_fractal_forest_2D (gsl_rng * rng)
///< Pseudo-random number generator.
{
int x, y;
long t0;
t0 = time (NULL);
do
{
tree_2D_point_new (&x, &y, rng);
while (!breaking && !forest_2D_point_fix (x, y, rng))
{
point_2D_move (&x, &y, rng);
forest_2D_point_boundary (&x, &y, rng);
}
if (animating && time (NULL) > t0)
break;
if (tree_2D_end (y))
fractal_stop ();
}
while (!breaking);
g_thread_exit (NULL);
return NULL;
}
/**
* Function to create a 3D fractal forest.
*
* \return NULL.
*/
void *
parallel_fractal_forest_3D (gsl_rng * rng)
///< Pseudo-random number generator.
{
int x, y, z;
long t0;
t0 = time (NULL);
do
{
tree_3D_point_new (&x, &y, &z, rng);
while (!breaking && !forest_3D_point_fix (x, y, z, rng))
{
point_3D_move (&x, &y, &z, rng);
forest_3D_point_boundary (&x, &y, &z, rng);
}
if (animating && time (NULL) > t0)
break;
if (tree_3D_end (z))
fractal_stop ();
}
while (!breaking);
g_thread_exit (NULL);
return NULL;
}
/**
* Function to create a 2D fractal neuron.
*
* \return NULL.
*/
void *
parallel_fractal_neuron_2D (gsl_rng * rng)
///< Pseudo-random number generator.
{
int x, y;
long t0;
t0 = time (NULL);
do
{
neuron_2D_point_new (&x, &y, rng);
while (!breaking && !neuron_2D_point_fix (x, y))
{
point_2D_move (&x, &y, rng);
neuron_2D_point_boundary (&x, &y, rng);
}
if (animating && time (NULL) > t0)
break;
if (neuron_2D_end (x, y))
fractal_stop ();
}
while (!breaking);
g_thread_exit (NULL);
return NULL;
}
/**
* Function to create a 3D fractal neuron.
*
* \return NULL.
*/
void *
parallel_fractal_neuron_3D (gsl_rng * rng)
///< Pseudo-random number generator.
{
int x, y, z;
long t0;
t0 = time (NULL);
do
{
neuron_3D_point_new (&x, &y, &z, rng);
while (!breaking && !neuron_3D_point_fix (x, y, z))
{
point_3D_move (&x, &y, &z, rng);
neuron_3D_point_boundary (&x, &y, &z, rng);
}
if (animating && time (NULL) > t0)
break;
if (neuron_3D_end (x, y, z))
fractal_stop ();
}
while (!breaking);
g_thread_exit (NULL);
return NULL;
}
/**
* Function to create a 2D fractal tree with diagonal movements.
*
* \return NULL.
*/
void *
parallel_fractal_tree_2D_diagonal (gsl_rng * rng)
///< Pseudo-random number generator.
{
int x, y;
long t0;
t0 = time (NULL);
do
{
tree_2D_point_new (&x, &y, rng);
while (!breaking && !tree_2D_point_fix (x, y))
{
point_2D_move (&x, &y, rng);
tree_2D_point_boundary (&x, &y, rng);
}
if (animating && time (NULL) > t0)
break;
if (tree_2D_end (y))
fractal_stop ();
}
while (!breaking);
g_thread_exit (NULL);
return NULL;
}
/**
* Function to create a 3D fractal tree with diagonal movements.
*
* \return NULL.
*/
void *
parallel_fractal_tree_3D_diagonal (gsl_rng * rng)
///< Pseudo-random number generator.
{
int x, y, z;
long t0;
t0 = time (NULL);
do
{
tree_3D_point_new (&x, &y, &z, rng);
while (!breaking && !tree_3D_point_fix (x, y, z))
{
point_3D_move (&x, &y, &z, rng);
tree_3D_point_boundary (&x, &y, &z, rng);
}
if (animating && time (NULL) > t0)
break;
if (tree_3D_end (z))
fractal_stop ();
}
while (!breaking);
g_thread_exit (NULL);
return NULL;
}
/**
* Function to create a 2D fractal forest with diagonal movements.
*
* \return NULL.
*/
void *
parallel_fractal_forest_2D_diagonal (gsl_rng * rng)
///< Pseudo-random number generator.
{
int x, y;
long t0;
t0 = time (NULL);
do
{
tree_2D_point_new (&x, &y, rng);
while (!breaking && !forest_2D_point_fix (x, y, rng))
{
point_2D_move_diagonal (&x, &y, rng);
forest_2D_point_boundary (&x, &y, rng);
}
if (animating && time (NULL) > t0)
break;
if (tree_2D_end (y))
fractal_stop ();
}
while (!breaking);
g_thread_exit (NULL);
return NULL;
}
/**
* Function to create a 3D fractal forest with diagonal movements.
*
* \return NULL.
*/
void *
parallel_fractal_forest_3D_diagonal (gsl_rng * rng)
///< Pseudo-random number generator.
{
int x, y, z;
long t0;
t0 = time (NULL);
do
{
tree_3D_point_new (&x, &y, &z, rng);
while (!breaking && !forest_3D_point_fix (x, y, z, rng))
{
point_3D_move_diagonal (&x, &y, &z, rng);
forest_3D_point_boundary (&x, &y, &z, rng);
}
if (animating && time (NULL) > t0)
break;
if (tree_3D_end (z))
fractal_stop ();
}
while (!breaking);
g_thread_exit (NULL);
return NULL;
}
/**
* Function to create a 2D fractal neuron with diagonal movements.
*
* \return NULL.
*/
void *
parallel_fractal_neuron_2D_diagonal (gsl_rng * rng)
///< Pseudo-random number generator.
{
int x, y;
long t0;
t0 = time (NULL);
do
{
neuron_2D_point_new (&x, &y, rng);
while (!breaking && !neuron_2D_point_fix (x, y))
{
point_2D_move_diagonal (&x, &y, rng);
neuron_2D_point_boundary (&x, &y, rng);
}
if (animating && time (NULL) > t0)
break;
if (neuron_2D_end (x, y))
fractal_stop ();
}
while (!breaking);
g_thread_exit (NULL);
return NULL;
}
/**
* Function to create a 3D fractal neuron with diagonal movements.
*
* \return NULL.
*/
void *
parallel_fractal_neuron_3D_diagonal (gsl_rng * rng)
///< Pseudo-random number generator.
{
int x, y, z;
long t0;
t0 = time (NULL);
do
{
neuron_3D_point_new (&x, &y, &z, rng);
while (!breaking && !neuron_3D_point_fix (x, y, z))
{
point_3D_move_diagonal (&x, &y, &z, rng);
neuron_3D_point_boundary (&x, &y, &z, rng);
}
if (animating && time (NULL) > t0)
break;
if (neuron_3D_end (x, y, z))
fractal_stop ();
}
while (!breaking);
g_thread_exit (NULL);
return NULL;
}
//END OF PARALLELIZED FUNCTIONS
/**
* Function to start the fractal functions and data.
*/
void
medium_start ()
{
register int i, j;
#if DEBUG
printf ("Deleting points\n");
#endif
g_free (point);
point = NULL;
npoints = 0;
j = area = width * length;
if (fractal_3D)
j *= length;
medium_bytes = j * sizeof (unsigned int);
medium = (unsigned int *) g_slice_alloc (medium_bytes);
for (i = j; --i >= 0;)
medium[i] = 0;
#if DEBUG
printf ("Medium size=%d pointer=%ld\n", j, (size_t) medium);
#endif
#if DEBUG
printf ("Setting functions\n");
#endif
if (fractal_diagonal)
{
if (fractal_3D)
{
switch (fractal_type)
{
case FRACTAL_TYPE_TREE:
tree_3D_init ();
parallel_fractal = parallel_fractal_tree_3D_diagonal;
max_d = 1;
break;
case FRACTAL_TYPE_FOREST:
parallel_fractal = parallel_fractal_forest_3D_diagonal;
max_d = 1;
break;
default:
neuron_3D_init ();
parallel_fractal = parallel_fractal_neuron_3D_diagonal;
max_d = 2;
}
}
else
{
switch (fractal_type)
{
case FRACTAL_TYPE_TREE:
tree_2D_init ();
parallel_fractal = parallel_fractal_tree_2D_diagonal;
max_d = 1;
break;
case FRACTAL_TYPE_FOREST:
parallel_fractal = parallel_fractal_forest_2D_diagonal;
max_d = 1;
break;
default:
neuron_2D_init ();
parallel_fractal = parallel_fractal_neuron_2D_diagonal;
max_d = 2;
}
}
}
else
{
if (fractal_3D)
{
switch (fractal_type)
{
case FRACTAL_TYPE_TREE:
tree_3D_init ();
parallel_fractal = parallel_fractal_tree_3D;
max_d = 1;
break;
case FRACTAL_TYPE_FOREST:
parallel_fractal = parallel_fractal_forest_3D;
max_d = 1;
break;
default:
neuron_3D_init ();
parallel_fractal = parallel_fractal_neuron_3D;
max_d = 2;
}
}
else
{
switch (fractal_type)
{
case FRACTAL_TYPE_TREE:
tree_2D_init ();
parallel_fractal = parallel_fractal_tree_2D;
max_d = 1;
break;
case FRACTAL_TYPE_FOREST:
parallel_fractal = parallel_fractal_forest_2D;
max_d = 1;
break;
default:
neuron_2D_init ();
parallel_fractal = parallel_fractal_neuron_2D;
max_d = 2;
}
}
}
}
/**
* Function to get an unsigned integer number of a XML node property.
*
* \return Unsigned integer number value.
*/
static unsigned int
xml_node_get_uint_with_default (xmlNode * node, ///< XML node.
const xmlChar * prop, ///< XML property.
unsigned int default_value, ///< Default value.
int *error_code) ///< Error code.
{
unsigned int i = 0;
xmlChar *buffer;
buffer = xmlGetProp (node, prop);
*error_code = 0;
if (!buffer)
return default_value;
else
{
if (sscanf ((char *) buffer, "%u", &i) != 1)
*error_code = 1;
xmlFree (buffer);
}
return i;
}
/**
* Function to get an unsigned long integer number of a XML node property.
*
* \return Unsigned long integer number value.
*/
static unsigned long
xml_node_get_ulong_with_default (xmlNode * node, ///< XML node.
const xmlChar * prop, ///< XML property.
unsigned long default_value,
///< Default value.
int *error_code) ///< Error code.
{
unsigned long i = 0l;
xmlChar *buffer;
buffer = xmlGetProp (node, prop);
*error_code = 0;
if (!buffer)
return default_value;
else
{
if (sscanf ((char *) buffer, "%lu", &i) != 1)
*error_code = 1;
xmlFree (buffer);
}
return i;
}
/**
* Function to open the fractal data on a file.
*
* \return 1 on success, 0 on error.
*/
int
fractal_input (char *filename) ///< File name.
{
xmlDoc *doc;
xmlNode *node;
xmlChar *buffer;
const char *error_message;
int error_code;
buffer = NULL;
xmlKeepBlanksDefault (0);
doc = xmlParseFile ((const char *) filename);
if (!doc)
{
error_message = _("Unable to parse the input file");
goto exit_on_error;
}
node = xmlDocGetRootElement (doc);
if (!node || xmlStrcmp (node->name, XML_FRACTAL))
{
error_message = _("Bad XML root node");
goto exit_on_error;
}
width = xml_node_get_uint_with_default (node, XML_WIDTH, WIDTH, &error_code);
if (error_code)
{
error_message = _("Bad width");
goto exit_on_error;
}
height
= xml_node_get_uint_with_default (node, XML_HEIGHT, HEIGHT, &error_code);
if (error_code)
{
error_message = _("Bad height");
goto exit_on_error;
}
length
= xml_node_get_uint_with_default (node, XML_LENGTH, LENGTH, &error_code);
if (error_code)
{
error_message = _("Bad length");
goto exit_on_error;
}
random_seed
= xml_node_get_ulong_with_default (node, XML_SEED, SEED, &error_code);
if (error_code)
{
error_message = _("Bad random seed");
goto exit_on_error;
}
nthreads
= xml_node_get_uint_with_default (node, XML_THREADS, threads_number (),
&error_code);
if (!nthreads || error_code)
{
error_message = _("Bad threads number");
goto exit_on_error;
}
buffer = xmlGetProp (node, XML_DIAGONAL);
if (!buffer || !xmlStrcmp (buffer, XML_NO))
fractal_diagonal = 0;
else if (!xmlStrcmp (buffer, XML_YES))
fractal_diagonal = 1;
else
{
error_message = _("Bad diagonal movement");
goto exit_on_error;
}
xmlFree (buffer);
buffer = xmlGetProp (node, XML_3D);
if (!buffer || !xmlStrcmp (buffer, XML_NO))
fractal_3D = 0;
else if (!xmlStrcmp (buffer, XML_YES))
fractal_3D = 1;
else
{
error_message = _("Bad 3D");
goto exit_on_error;
}
xmlFree (buffer);
buffer = xmlGetProp (node, XML_ANIMATE);
if (!buffer || !xmlStrcmp (buffer, XML_YES))
animating = 1;
else if (!xmlStrcmp (buffer, XML_NO))
animating = 0;
else
{
error_message = _("Bad animation");
goto exit_on_error;
}
xmlFree (buffer);
buffer = xmlGetProp (node, XML_TYPE);
if (!buffer || !xmlStrcmp (buffer, XML_TREE))
fractal_type = FRACTAL_TYPE_TREE;
else if (!xmlStrcmp (buffer, XML_FOREST))
fractal_type = FRACTAL_TYPE_FOREST;
else if (!xmlStrcmp (buffer, XML_NEURON))
fractal_type = FRACTAL_TYPE_NEURON;
else
{
error_message = _("Unknown fractal type");
goto exit_on_error;
}
xmlFree (buffer);
buffer = xmlGetProp (node, XML_RANDOM_SEED);
if (!buffer || !xmlStrcmp (buffer, XML_CLOCK))
random_seed_type = RANDOM_SEED_TYPE_CLOCK;
else if (!xmlStrcmp (buffer, XML_DEFAULT))
random_seed_type = RANDOM_SEED_TYPE_DEFAULT;
else if (!xmlStrcmp (buffer, XML_FIXED))
random_seed_type = RANDOM_SEED_TYPE_FIXED;
else
{
error_message = _("Unknown random seed type");
goto exit_on_error;
}
xmlFree (buffer);
buffer = xmlGetProp (node, XML_RANDOM_TYPE);
if (!buffer || !xmlStrcmp (buffer, XML_MT19937))
random_algorithm = 0;
else if (!xmlStrcmp (buffer, XML_RANLXS0))
random_algorithm = 1;
else if (!xmlStrcmp (buffer, XML_RANLXS1))
random_algorithm = 2;
else if (!xmlStrcmp (buffer, XML_RANLXS2))
random_algorithm = 3;
else if (!xmlStrcmp (buffer, XML_RANLXD1))
random_algorithm = 4;
else if (!xmlStrcmp (buffer, XML_RANLXD2))
random_algorithm = 5;
else if (!xmlStrcmp (buffer, XML_RANLUX))
random_algorithm = 6;
else if (!xmlStrcmp (buffer, XML_RANLUX389))
random_algorithm = 7;
else if (!xmlStrcmp (buffer, XML_CMRG))
random_algorithm = 8;
else if (!xmlStrcmp (buffer, XML_MRG))
random_algorithm = 9;
else if (!xmlStrcmp (buffer, XML_TAUS2))
random_algorithm = 10;
else if (!xmlStrcmp (buffer, XML_GFSR4))
random_algorithm = 11;
else
{
error_message = _("Unknown random algorithm");
goto exit_on_error;
}
xmlFree (buffer);
xmlFreeDoc (doc);
return 1;
exit_on_error:
show_error (error_message);
xmlFree (buffer);
xmlFreeDoc (doc);
return 0;
}
/**
* Function with the main bucle to draw the fractal.
*/
void
fractal ()
{
const gsl_rng_type *random_type[N_RANDOM_TYPES] = {
gsl_rng_mt19937,
gsl_rng_ranlxs0,
gsl_rng_ranlxs1,
gsl_rng_ranlxs2,
gsl_rng_ranlxd1,
gsl_rng_ranlxd2,
gsl_rng_ranlux,
gsl_rng_ranlux389,
gsl_rng_cmrg,
gsl_rng_mrg,
gsl_rng_taus2,
gsl_rng_gfsr4
};
FILE *file;
unsigned int i;
// PARALLELIZING DATA
gsl_rng *rng[nthreads];
GThread *thread[nthreads];
t0 = time (NULL);
#if DEBUG
printf ("t0=%lu\n", t0);
#endif
#if DEBUG
printf ("Opening log file\n");
#endif
file = fopen ("log", "w");
#if DEBUG
printf ("Opening pseudo-random generators\n");
#endif
for (i = 0; i < nthreads; ++i)
{
rng[i] = gsl_rng_alloc (random_type[random_algorithm]);
switch (random_seed_type)
{
case RANDOM_SEED_TYPE_DEFAULT:
break;
case RANDOM_SEED_TYPE_CLOCK:
gsl_rng_set (rng[i], (unsigned long) clock () + i);
break;
default:
gsl_rng_set (rng[i], random_seed + i);
}
}
// END
breaking = 0;
simulating = 1;
#if DEBUG
printf ("Updating simulator dialog\n");
#endif
dialog_simulator_update ();
#if DEBUG
printf ("Starting medium\n");
#endif
medium_start ();
#if DEBUG
printf ("Main bucle\n");
#endif
do
{
#if DEBUG
printf ("Calculating fractal\n");
#endif
// PARALLELIZING CALLS
for (i = 0; i < nthreads; ++i)
thread[i] = g_thread_new (NULL, (void (*)) parallel_fractal, rng[i]);
for (i = 0; i < nthreads; ++i)
g_thread_join (thread[i]);
// END
#if DEBUG
printf ("Updating simulator dialog\n");
#endif
dialog_simulator_progress ();
// DISPLAYING DRAW
#if DEBUG
printf ("Redisplaying draw\n");
#endif
draw ();
// END
#if DEBUG
printf ("Saving log data\n");
#endif
fprintf (file, "%d %d\n", max_d, npoints);
}
while (!breaking);
#if DEBUG
printf ("Closing log file\n");
#endif
fclose (file);
#if DEBUG
printf ("Updating simulator dialog\n");
#endif
breaking = simulating = 0;
dialog_simulator_update ();
#if DEBUG
printf ("Freeing threads\n");
#endif
for (i = 0; i < nthreads; ++i)
gsl_rng_free (rng[i]);
g_slice_free1 (medium_bytes, medium);
}
| {
"alphanum_fraction": 0.5638490323,
"avg_line_length": 23.9058056872,
"ext": "c",
"hexsha": "f68511d16a91a5adced31ec3afe7fbb5fbe6e12c",
"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": "95d711dcb7b385556fb77794bc01737b21e99774",
"max_forks_repo_licenses": [
"BSD-2-Clause"
],
"max_forks_repo_name": "jburguete/fractal",
"max_forks_repo_path": "3.4.15/fractal.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "95d711dcb7b385556fb77794bc01737b21e99774",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-2-Clause"
],
"max_issues_repo_name": "jburguete/fractal",
"max_issues_repo_path": "3.4.15/fractal.c",
"max_line_length": 83,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "95d711dcb7b385556fb77794bc01737b21e99774",
"max_stars_repo_licenses": [
"BSD-2-Clause"
],
"max_stars_repo_name": "jburguete/fractal",
"max_stars_repo_path": "3.4.15/fractal.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 12068,
"size": 40353
} |
#ifndef bcfunctions_h
#define bcfunctions_h
#include <petsc.h>
PetscErrorCode BCsDiff(PetscInt dim, PetscReal time, const PetscReal x[],
PetscInt num_comp_u, PetscScalar *u, void *ctx);
PetscErrorCode BCsMass(PetscInt dim, PetscReal time, const PetscReal x[],
PetscInt num_comp_u, PetscScalar *u, void *ctx);
#endif // bcfunctions_h
| {
"alphanum_fraction": 0.6884816754,
"avg_line_length": 31.8333333333,
"ext": "h",
"hexsha": "b272a64db6da1b4d5e702712e7c1f67b380bfd06",
"lang": "C",
"max_forks_count": 41,
"max_forks_repo_forks_event_max_datetime": "2022-03-01T13:02:07.000Z",
"max_forks_repo_forks_event_min_datetime": "2017-12-27T22:35:13.000Z",
"max_forks_repo_head_hexsha": "aae8ce39fa1e28b745979a9cbffc67a790eb3f5e",
"max_forks_repo_licenses": [
"BSD-2-Clause"
],
"max_forks_repo_name": "AdelekeBankole/libCEED",
"max_forks_repo_path": "examples/petsc/include/bcfunctions.h",
"max_issues_count": 781,
"max_issues_repo_head_hexsha": "aae8ce39fa1e28b745979a9cbffc67a790eb3f5e",
"max_issues_repo_issues_event_max_datetime": "2022-03-29T21:34:34.000Z",
"max_issues_repo_issues_event_min_datetime": "2017-12-22T17:20:35.000Z",
"max_issues_repo_licenses": [
"BSD-2-Clause"
],
"max_issues_repo_name": "AdelekeBankole/libCEED",
"max_issues_repo_path": "examples/petsc/include/bcfunctions.h",
"max_line_length": 73,
"max_stars_count": 123,
"max_stars_repo_head_hexsha": "aae8ce39fa1e28b745979a9cbffc67a790eb3f5e",
"max_stars_repo_licenses": [
"BSD-2-Clause"
],
"max_stars_repo_name": "AdelekeBankole/libCEED",
"max_stars_repo_path": "examples/petsc/include/bcfunctions.h",
"max_stars_repo_stars_event_max_datetime": "2022-03-21T18:13:48.000Z",
"max_stars_repo_stars_event_min_datetime": "2018-01-29T02:04:05.000Z",
"num_tokens": 96,
"size": 382
} |
//
// trsm.h
// Linear Algebra Template Library
//
// Created by Rodney James on 1/5/12.
// Copyright (c) 2012 University of Colorado Denver. All rights reserved.
//
#ifndef _trsm_h
#define _trsm_h
/// @file trsm.h Solves triangular matrix equations.
#include <cctype>
#include "latl.h"
namespace LATL
{
/// @brief Solves a real triangular matrix equation.
///
/// For a real upper or lower triangular matrix A, real rectangular matrix B and real scalar alpha,
///
/// A*X=alpha*B or A'*X=alpha*B or X*A=alpha*B or X*A'=alpha*B
/// is solved for the matrix X.
/// @return 0 if success.
/// @return -i if the ith argument is invalid.
/// @tparam real_t Floating point type.
/// @param side Specifies whether the matrix A appears on the left or right side as follows:
///
/// if side = 'L' or 'l' then A*X=alpha*B or A'*X=alpha*B is solved
/// if side = 'R' or 'r' then X*A=alpha*B or X*A'=alpha*B is solved
/// @param uplo Specifies whether A is stored as upper or lower triangular.
///
/// if uplo = 'U' or 'u' then A is upper triangular
/// if uplo = 'L' or 'l' then A is lower triangular
/// @param trans Specifies whether the transpose or conjugate transpose of A is to be used:
///
/// if trans = 'N' or 'n' then A*X=alpha*B or X*A=alpha*B is solved
/// if trans = 'T' or 't' then A'*X=alpha*B or X*A'=alpha*B is solved
/// if trans = 'C' or 'c' then A'*X=alpha*B or X*A'=alpha*B is solved
/// @param diag specifies whether or not A is unit triangular as follows:
///
/// if diag = 'U' or 'u' then A is assumed to be unit triangular
/// if diag = 'N' or 'n' then A is not assumed to be unit triangular.
/// If A is unit triangular, the diagonal elements are assumed to be unity and are not referenced.
/// @param m Specifies the number of rows of the matrix B. m>=0
/// @param n Specifies the number of columns of the matrix B. n>=0
/// @param alpha Real scalar.
/// @param A Pointer to real triangular matrix A. The order of A is n if side = 'L' or 'l';
/// the order of A is m is side = 'R' or 'r'.
/// If uplo = 'U' or 'u, A is upper triangular and the lower triangular part is not referenced.
/// If uplo = 'L' or 'l A is lower triangular and the upper triangular part is not referenced.
/// @param ldA Column length of the matrix A. If side='L' or 'l' then ldA>=n; if side='R' or 'r' then ldA>=m.
/// @param B Pointer to real m-by-n matrix B. On entry, B contains the right hand side matrix B.
/// On exit, B is overwritten with the solution matrix X.
/// @param ldB Column length of the matrix B. ldB>=m.
/// @ingroup BLAS
template <typename real_t>
int TRSM(char side, char uplo, char trans, char diag, int_t m, int_t n, real_t alpha, real_t *A, int_t ldA, real_t *B, int_t ldB)
{
using std::toupper;
const real_t zero(0.0);
const real_t one(1.0);
int_t i,j,k;
real_t *a,*b,*bt;
real_t t;
bool nounit;
side=toupper(side);
uplo=toupper(uplo);
trans=toupper(trans);
diag=toupper(diag);
nounit=(diag=='N')?1:0;
if((side!='L')&&(side!='R'))
return -1;
else if((uplo!='U')&&(uplo!='L'))
return -2;
else if((trans!='N')&&(trans!='T')&&(trans!='C'))
return -3;
else if((diag!='U')&&(diag!='N'))
return -4;
else if(m<0)
return -5;
else if(n<0)
return -6;
else if(ldA<((side=='L')?m:n))
return -9;
else if(ldB<m)
return -11;
else if((m==0)||(n==0))
return 0;
if(alpha==zero)
{
b=B;
for(j=0;j<n;j++)
{
for(i=0;i<m;i++)
b[i]=zero;
b+=ldB;
}
}
else
{
if(side=='L')
{
if(trans=='N')
{
if(uplo=='U')
{
b=B;
for(j=0;j<n;j++)
{
for(i=0;i<m;i++)
b[i]*=alpha;
a=A+m*ldA;
for(k=m-1;k>=0;k--)
{
a-=ldA;
if(nounit)
b[k]=b[k]/a[k];
for(i=0;i<k;i++)
b[i]-=b[k]*a[i];
}
b+=ldB;
}
}
else
{
b=B;
for(j=0;j<n;j++)
{
for(i=0;i<m;i++)
b[i]*=alpha;
a=A;
for(k=0;k<m;k++)
{
if(nounit)
b[k]=b[k]/a[k];
for(i=k+1;i<m;i++)
b[i]-=b[k]*a[i];
a+=ldA;
}
b+=ldB;
}
}
}
else
{
if(uplo=='U')
{
b=B;
for(j=0;j<n;j++)
{
a=A;
for(i=0;i<m;i++)
{
t=alpha*b[i];
for(k=0;k<i;k++)
t-=a[k]*b[k];
if(nounit)
t=t/a[i];
b[i]=t;
a+=ldA;
}
b+=ldB;
}
}
else
{
b=B;
for(j=0;j<n;j++)
{
a=A+m*ldA;
for(i=m-1;i>=0;i--)
{
a-=ldA;
t=alpha*b[i];
for(k=i+1;k<m;k++)
t-=a[k]*b[k];
if(nounit)
t=t/a[i];
b[i]=t;
}
b+=ldB;
}
}
}
}
else
{
if(trans=='N')
{
if(uplo=='U')
{
b=B;
a=A;
for(j=0;j<n;j++)
{
for(i=0;i<m;i++)
b[i]*=alpha;
bt=B;
for(k=0;k<j;k++)
{
for(i=0;i<m;i++)
b[i]-=a[k]*bt[i];
bt+=ldB;
}
if(nounit)
{
t=one/a[j];
for(i=0;i<m;i++)
b[i]*=t;
}
a+=ldA;
b+=ldB;
}
}
else
{
b=B+n*ldB;
a=A+n*ldA;
for(j=n-1;j>=0;j--)
{
a-=ldA;
b-=ldB;
for(i=0;i<m;i++)
b[i]*=alpha;
bt=B+(j+1)*ldB;
for(k=j+1;k<n;k++)
{
for(i=0;i<m;i++)
b[i]-=a[k]*bt[i];
bt+=ldB;
}
if(nounit)
{
t=one/a[j];
for(i=0;i<m;i++)
b[i]*=t;
}
}
}
}
else
{
if(uplo=='U')
{
b=B+n*ldB;
a=A+n*ldA;
for(k=n-1;k>=0;k--)
{
a-=ldA;
b-=ldB;
if(nounit)
{
t=one/a[k];
for(i=0;i<m;i++)
b[i]*=t;
}
bt=B;
for(j=0;j<k;j++)
{
t=a[j];
for(i=0;i<m;i++)
bt[i]-=t*b[i];
bt+=ldB;
}
for(i=0;i<m;i++)
b[i]*=alpha;
}
}
else
{
a=A;
b=B;
for(k=0;k<n;k++)
{
if(nounit)
{
t=one/a[k];
for(i=0;i<m;i++)
b[i]*=t;
}
bt=B+(k+1)*ldB;
for(j=k+1;j<n;j++)
{
t=a[j];
for(i=0;i<m;i++)
bt[i]-=t*b[i];
bt+=ldB;
}
for(i=0;i<m;i++)
b[i]*=alpha;
a+=ldA;
b+=ldB;
}
}
}
}
}
return 0;
}
/// @brief Solves a complex triangular matrix equation.
///
/// For a complex upper or lower triangular matrix A, complex rectangular matrix B and complex scalar alpha,
///
/// A*X=alpha*B or A'*X=alpha*B or A.'*X=alpha*B or X*A=alpha*B or X*A'=alpha*B or X*A.'=alpha*B
/// is solved for the matrix X.
/// @return 0 if success.
/// @return -i if the ith argument is invalid.
/// @tparam real_t Floating point type.
/// @param side Specifies whether the matrix A appears on the left or right side as follows:
///
/// if side = 'L' or 'l' then A*X=alpha*B or A'*X=alpha*B is solved
/// if side = 'R' or 'r' then X*A=alpha*B or X*A'=alpha*B is solved
/// @param uplo Specifies whether A is stored as upper or lower triangular.
///
/// if uplo = 'U' or 'u' then A is upper triangular
/// if uplo = 'L' or 'l' then A is lower triangular
/// @param trans Specifies whether the transpose of A is to be used or not:
///
/// if trans = 'N' or 'n' then A*X=alpha*B or X*A=alpha*B is solved
/// if trans = 'T' or 't' then A.'*X=alpha*B or X*A.'=alpha*B is solved
/// if trans = 'C' or 'c' then A'*X=alpha*B or X*A'=alpha*B is solved
/// @param diag specifies whether or not A is unit triangular as follows:
///
/// if diag = 'U' or 'u' then A is assumed to be unit triangular
/// if diag = 'N' or 'n' then A is not assumed to be unit triangular.
/// If A is unit triangular, the diagonal elements are assumed to be unity and are not referenced.
/// @param m Specifies the number of rows of the matrix B. m>=0
/// @param n Specifies the number of columns of the matrix B. n>=0
/// @param alpha Complex scalar.
/// @param A Pointer to complex triangular matrix A. The order of A is n if side = 'L' or 'l';
/// the order of A is m is side = 'R' or 'r'.
/// If uplo = 'U' or 'u, A is upper triangular and the lower triangular part is not referenced.
/// If uplo = 'L' or 'l A is lower triangular and the upper triangular part is not referenced.
/// @param ldA Column length of the matrix A. If side='L' or 'l' then ldA>=n; if side='R' or 'r' then ldA>=m.
/// @param B Pointer to complex m-by-n matrix B. On entry, B contains the right hand side matrix B.
/// On exit, B is overwritten with the solution matrix X.
/// @param ldB Column length of the matrix B. ldB>=m.
/// @ingroup BLAS
template <typename real_t>
int TRSM(char side, char uplo, char trans, char diag, int_t m, int_t n, complex<real_t> alpha, complex<real_t> *A, int_t ldA, complex<real_t> *B, int_t ldB)
{
using std::conj;
using std::toupper;
const complex<real_t> zero(0.0,0.0);
const complex<real_t> one(1.0,0.0);
int_t i,j,k;
complex<real_t> *a,*b,*bt;
complex<real_t> t;
bool nounit;
side=toupper(side);
uplo=toupper(uplo);
trans=toupper(trans);
diag=toupper(diag);
nounit=(diag=='N')?1:0;
if((side!='L')&&(side!='R'))
return -1;
else if((uplo!='U')&&(uplo!='L'))
return -2;
else if((trans!='N')&&(trans!='T')&&(trans!='C'))
return -3;
else if((diag!='U')&&(diag!='N'))
return -4;
else if(m<0)
return -5;
else if(n<0)
return -6;
else if(ldA<((side=='L')?m:n))
return -9;
else if(ldB<m)
return -11;
else if((m==0)||(n==0))
return 0;
if(alpha==zero)
{
b=B;
for(j=0;j<n;j++)
{
for(i=0;i<m;i++)
b[i]=zero;
b+=ldB;
}
}
else
{
if(side=='L')
{
if(trans=='N')
{
if(uplo=='U')
{
b=B;
for(j=0;j<n;j++)
{
for(i=0;i<m;i++)
b[i]*=alpha;
a=A+m*ldA;
for(k=m-1;k>=0;k--)
{
a-=ldA;
if(nounit)
b[k]=b[k]/a[k];
for(i=0;i<k;i++)
b[i]-=b[k]*a[i];
}
b+=ldB;
}
}
else
{
b=B;
for(j=0;j<n;j++)
{
for(i=0;i<m;i++)
b[i]*=alpha;
a=A;
for(k=0;k<m;k++)
{
if(nounit)
b[k]=b[k]/a[k];
for(i=k+1;i<m;i++)
b[i]-=b[k]*a[i];
a+=ldA;
}
b+=ldB;
}
}
}
else if(trans=='T')
{
if(uplo=='U')
{
b=B;
for(j=0;j<n;j++)
{
a=A;
for(i=0;i<m;i++)
{
t=alpha*b[i];
for(k=0;k<i;k++)
t-=a[k]*b[k];
if(nounit)
t=t/a[i];
b[i]=t;
a+=ldA;
}
b+=ldB;
}
}
else
{
b=B;
for(j=0;j<n;j++)
{
a=A+m*ldA;
for(i=m-1;i>=0;i--)
{
a-=ldA;
t=alpha*b[i];
for(k=i+1;k<m;k++)
t-=a[k]*b[k];
if(nounit)
t=t/a[i];
b[i]=t;
}
b+=ldB;
}
}
}
else if(trans=='C')
{
if(uplo=='U')
{
b=B;
for(j=0;j<n;j++)
{
a=A;
for(i=0;i<m;i++)
{
t=alpha*b[i];
for(k=0;k<i;k++)
t-=conj(a[k])*b[k];
if(nounit)
t=t/conj(a[i]);
b[i]=t;
a+=ldA;
}
b+=ldB;
}
}
else
{
b=B;
for(j=0;j<n;j++)
{
a=A+m*ldA;
for(i=m-1;i>=0;i--)
{
a-=ldA;
t=alpha*b[i];
for(k=i+1;k<m;k++)
t-=conj(a[k])*b[k];
if(nounit)
t=t/conj(a[i]);
b[i]=t;
}
b+=ldB;
}
}
}
}
else
{
if(trans=='N')
{
if(uplo=='U')
{
b=B;
a=A;
for(j=0;j<n;j++)
{
for(i=0;i<m;i++)
b[i]*=alpha;
bt=B;
for(k=0;k<j;k++)
{
for(i=0;i<m;i++)
b[i]-=a[k]*bt[i];
bt+=ldB;
}
if(nounit)
{
t=one/a[j];
for(i=0;i<m;i++)
b[i]*=t;
}
a+=ldA;
b+=ldB;
}
}
else
{
b=B+n*ldB;
a=A+n*ldA;
for(j=n-1;j>=0;j--)
{
a-=ldA;
b-=ldB;
for(i=0;i<m;i++)
b[i]*=alpha;
bt=B+(j+1)*ldB;
for(k=j+1;k<n;k++)
{
for(i=0;i<m;i++)
b[i]-=a[k]*bt[i];
bt+=ldB;
}
if(nounit)
{
t=one/a[j];
for(i=0;i<m;i++)
b[i]*=t;
}
}
}
}
else if(trans=='T')
{
if(uplo=='U')
{
b=B+n*ldB;
a=A+n*ldA;
for(k=n-1;k>=0;k--)
{
a-=ldA;
b-=ldB;
if(nounit)
{
t=one/a[k];
for(i=0;i<m;i++)
b[i]*=t;
}
bt=B;
for(j=0;j<k;j++)
{
t=a[j];
for(i=0;i<m;i++)
bt[i]-=t*b[i];
bt+=ldB;
}
for(i=0;i<m;i++)
b[i]*=alpha;
}
}
else
{
a=A;
b=B;
for(k=0;k<n;k++)
{
if(nounit)
{
t=one/a[k];
for(i=0;i<m;i++)
b[i]*=t;
}
bt=B+(k+1)*ldB;
for(j=k+1;j<n;j++)
{
t=a[j];
for(i=0;i<m;i++)
bt[i]-=t*b[i];
bt+=ldB;
}
for(i=0;i<m;i++)
b[i]*=alpha;
a+=ldA;
b+=ldB;
}
}
}
else if(trans=='C')
{
if(uplo=='U')
{
b=B+n*ldB;
a=A+n*ldA;
for(k=n-1;k>=0;k--)
{
a-=ldA;
b-=ldB;
if(nounit)
{
t=one/conj(a[k]);
for(i=0;i<m;i++)
b[i]*=t;
}
bt=B;
for(j=0;j<k;j++)
{
t=conj(a[j]);
for(i=0;i<m;i++)
bt[i]-=t*b[i];
bt+=ldB;
}
for(i=0;i<m;i++)
b[i]*=alpha;
}
}
else
{
a=A;
b=B;
for(k=0;k<n;k++)
{
if(nounit)
{
t=one/conj(a[k]);
for(i=0;i<m;i++)
b[i]*=t;
}
bt=B+(k+1)*ldB;
for(j=k+1;j<n;j++)
{
t=conj(a[j]);
for(i=0;i<m;i++)
bt[i]-=t*b[i];
bt+=ldB;
}
for(i=0;i<m;i++)
b[i]*=alpha;
a+=ldA;
b+=ldB;
}
}
}
}
}
return 0;
}
#ifdef __latl_cblas
#include <cblas.h>
template <> int TRSM<float>(char side, char uplo, char trans, char diag, int_t m, int_t n, float alpha, float *A, int_t ldA, float *B, int_t ldB)
{
using std::toupper;
side=toupper(side);
uplo=toupper(uplo);
trans=toupper(trans);
diag=toupper(diag);
if((side!='L')&&(side!='R'))
return -1;
else if((uplo!='U')&&(uplo!='L'))
return -2;
else if((trans!='N')&&(trans!='T')&&(trans!='C'))
return -3;
else if((diag!='U')&&(diag!='N'))
return -4;
else if(m<0)
return -5;
else if(n<0)
return -6;
else if(ldA<((side=='L')?m:n))
return -9;
else if(ldB<m)
return -11;
else if((m==0)||(n==0))
return 0;
const CBLAS_SIDE Side=(side=='L')?CblasLeft:CblasRight;
const CBLAS_UPLO Uplo=(uplo=='U')?CblasUpper:CblasLower;
const CBLAS_TRANSPOSE Trans=(trans=='N')?CblasNoTrans:((trans=='T')?CblasTrans:CblasConjTrans);
const CBLAS_DIAG Diag=(diag=='N')?CblasNonUnit:CblasUnit;
cblas_strsm(CblasColMajor,Side,Uplo,Trans,Diag,m,n,alpha,A,ldA,B,ldB);
return 0;
}
template <> int TRSM<double>(char side, char uplo, char trans, char diag, int_t m, int_t n, double alpha, double *A, int_t ldA, double *B, int_t ldB)
{
using std::toupper;
side=toupper(side);
uplo=toupper(uplo);
trans=toupper(trans);
diag=toupper(diag);
if((side!='L')&&(side!='R'))
return -1;
else if((uplo!='U')&&(uplo!='L'))
return -2;
else if((trans!='N')&&(trans!='T')&&(trans!='C'))
return -3;
else if((diag!='U')&&(diag!='N'))
return -4;
else if(m<0)
return -5;
else if(n<0)
return -6;
else if(ldA<((side=='L')?m:n))
return -9;
else if(ldB<m)
return -11;
else if((m==0)||(n==0))
return 0;
const CBLAS_SIDE Side=(side=='L')?CblasLeft:CblasRight;
const CBLAS_UPLO Uplo=(uplo=='U')?CblasUpper:CblasLower;
const CBLAS_TRANSPOSE Trans=(trans=='N')?CblasNoTrans:((trans=='T')?CblasTrans:CblasConjTrans);
const CBLAS_DIAG Diag=(diag=='N')?CblasNonUnit:CblasUnit;
cblas_dtrsm(CblasColMajor,Side,Uplo,Trans,Diag,m,n,alpha,A,ldA,B,ldB);
return 0;
}
template <> int TRSM<float>(char side, char uplo, char trans, char diag, int_t m, int_t n, complex<float> alpha, complex<float> *A, int_t ldA, complex<float> *B, int_t ldB)
{
using std::toupper;
side=toupper(side);
uplo=toupper(uplo);
trans=toupper(trans);
diag=toupper(diag);
if((side!='L')&&(side!='R'))
return -1;
else if((uplo!='U')&&(uplo!='L'))
return -2;
else if((trans!='N')&&(trans!='T')&&(trans!='C'))
return -3;
else if((diag!='U')&&(diag!='N'))
return -4;
else if(m<0)
return -5;
else if(n<0)
return -6;
else if(ldA<((side=='L')?m:n))
return -9;
else if(ldB<m)
return -11;
else if((m==0)||(n==0))
return 0;
const CBLAS_SIDE Side=(side=='L')?CblasLeft:CblasRight;
const CBLAS_UPLO Uplo=(uplo=='U')?CblasUpper:CblasLower;
const CBLAS_TRANSPOSE Trans=(trans=='N')?CblasNoTrans:((trans=='T')?CblasTrans:CblasConjTrans);
const CBLAS_DIAG Diag=(diag=='N')?CblasNonUnit:CblasUnit;
cblas_ctrsm(CblasColMajor,Side,Uplo,Trans,Diag,m,n,&alpha,A,ldA,B,ldB);
return 0;
}
template <> int TRSM<double>(char side, char uplo, char trans, char diag, int_t m, int_t n, complex<double> alpha, complex<double> *A, int_t ldA, complex<double> *B, int_t ldB)
{
using std::toupper;
side=toupper(side);
uplo=toupper(uplo);
trans=toupper(trans);
diag=toupper(diag);
if((side!='L')&&(side!='R'))
return -1;
else if((uplo!='U')&&(uplo!='L'))
return -2;
else if((trans!='N')&&(trans!='T')&&(trans!='C'))
return -3;
else if((diag!='U')&&(diag!='N'))
return -4;
else if(m<0)
return -5;
else if(n<0)
return -6;
else if(ldA<((side=='L')?m:n))
return -9;
else if(ldB<m)
return -11;
else if((m==0)||(n==0))
return 0;
const CBLAS_SIDE Side=(side=='L')?CblasLeft:CblasRight;
const CBLAS_UPLO Uplo=(uplo=='U')?CblasUpper:CblasLower;
const CBLAS_TRANSPOSE Trans=(trans=='N')?CblasNoTrans:((trans=='T')?CblasTrans:CblasConjTrans);
const CBLAS_DIAG Diag=(diag=='N')?CblasNonUnit:CblasUnit;
cblas_ztrsm(CblasColMajor,Side,Uplo,Trans,Diag,m,n,&alpha,A,ldA,B,ldB);
return 0;
}
#endif
}
#endif
| {
"alphanum_fraction": 0.3354482967,
"avg_line_length": 31.3349112426,
"ext": "h",
"hexsha": "3a23de1de6c3c1e8b3dae441f9ff3c300b37a2c1",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2022-02-09T23:18:24.000Z",
"max_forks_repo_forks_event_min_datetime": "2019-02-01T06:46:36.000Z",
"max_forks_repo_head_hexsha": "df838fb44a1ef5c77b57bf60bd46eaeff8db3492",
"max_forks_repo_licenses": [
"BSD-3-Clause-Open-MPI"
],
"max_forks_repo_name": "langou/latl",
"max_forks_repo_path": "include/trsm.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "df838fb44a1ef5c77b57bf60bd46eaeff8db3492",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-3-Clause-Open-MPI"
],
"max_issues_repo_name": "langou/latl",
"max_issues_repo_path": "include/trsm.h",
"max_line_length": 179,
"max_stars_count": 6,
"max_stars_repo_head_hexsha": "df838fb44a1ef5c77b57bf60bd46eaeff8db3492",
"max_stars_repo_licenses": [
"BSD-3-Clause-Open-MPI"
],
"max_stars_repo_name": "langou/latl",
"max_stars_repo_path": "include/trsm.h",
"max_stars_repo_stars_event_max_datetime": "2022-02-09T23:18:22.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-12-13T09:10:11.000Z",
"num_tokens": 6450,
"size": 26478
} |
/* bst/gsl_bst.h
*
* Copyright (C) 2018, 2019 Patrick Alken
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#ifndef __GSL_BST_H__
#define __GSL_BST_H__
#include <gsl/gsl_math.h>
#include <gsl/gsl_bst_avl.h>
#include <gsl/gsl_bst_rb.h>
#include <gsl/gsl_bst_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
/* type of binary search tree */
typedef struct
{
const char *name;
const size_t node_size;
int (*init)(const gsl_bst_allocator * allocator,
gsl_bst_cmp_function * compare, void * params, void * vtable);
size_t (*nodes) (const void * vtable);
void * (*insert) (void * item, void * vtable);
void * (*find) (const void *item, const void * vtable);
void * (*remove) (const void *item, void * vtable);
int (*empty) (void * vtable);
int (*trav_init) (void * vtrav, const void * vtable);
void * (*trav_first) (void * vtrav, const void * vtable);
void * (*trav_last) (void * vtrav, const void * vtable);
void * (*trav_find) (const void * item, void * vtrav, const void * vtable);
void * (*trav_insert) (void * item, void * vtrav, void * vtable);
void * (*trav_copy) (void * vtrav, const void * vsrc);
void * (*trav_next) (void * vtrav);
void * (*trav_prev) (void * vtrav);
void * (*trav_cur) (const void * vtrav);
void * (*trav_replace) (void * vtrav, void * new_item);
} gsl_bst_type;
typedef struct
{
const gsl_bst_type * type; /* binary search tree type */
union
{
gsl_bst_avl_table avl_table;
gsl_bst_rb_table rb_table;
} table;
} gsl_bst_workspace;
typedef struct
{
const gsl_bst_type * type; /* binary search tree type */
union
{
gsl_bst_avl_traverser avl_trav;
gsl_bst_rb_traverser rb_trav;
} trav_data;
} gsl_bst_trav;
/* tree types */
GSL_VAR const gsl_bst_type * gsl_bst_avl;
GSL_VAR const gsl_bst_type * gsl_bst_rb;
/*
* Prototypes
*/
gsl_bst_workspace * gsl_bst_alloc(const gsl_bst_type * T, const gsl_bst_allocator * allocator,
gsl_bst_cmp_function * compare, void * params);
void gsl_bst_free(gsl_bst_workspace * w);
int gsl_bst_empty(gsl_bst_workspace * w);
void * gsl_bst_insert(void * item, gsl_bst_workspace * w);
void * gsl_bst_find(const void * item, const gsl_bst_workspace * w);
void * gsl_bst_remove(const void * item, gsl_bst_workspace * w);
size_t gsl_bst_nodes(const gsl_bst_workspace * w);
size_t gsl_bst_node_size(const gsl_bst_workspace * w);
const char * gsl_bst_name(const gsl_bst_workspace * w);
int gsl_bst_trav_init(gsl_bst_trav * trav, const gsl_bst_workspace * w);
void * gsl_bst_trav_first(gsl_bst_trav * trav, const gsl_bst_workspace * w);
void * gsl_bst_trav_last (gsl_bst_trav * trav, const gsl_bst_workspace * w);
void * gsl_bst_trav_find (const void * item, gsl_bst_trav * trav, const gsl_bst_workspace * w);
void * gsl_bst_trav_insert (void * item, gsl_bst_trav * trav, gsl_bst_workspace * w);
void * gsl_bst_trav_copy(gsl_bst_trav * dest, const gsl_bst_trav * src);
void * gsl_bst_trav_next(gsl_bst_trav * trav);
void * gsl_bst_trav_prev(gsl_bst_trav * trav);
void * gsl_bst_trav_cur(const gsl_bst_trav * trav);
void * gsl_bst_trav_replace (gsl_bst_trav * trav, void * new_item);
__END_DECLS
#endif /* __GSL_BST_H__ */
| {
"alphanum_fraction": 0.7119764879,
"avg_line_length": 34.8974358974,
"ext": "h",
"hexsha": "c5988a6e802fcc41e2d13b4c8467ae61dd2d381c",
"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": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "ielomariala/Hex-Game",
"max_forks_repo_path": "gsl-2.6/gsl/gsl_bst.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_bst.h",
"max_line_length": 95,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "ielomariala/Hex-Game",
"max_stars_repo_path": "gsl-2.6/gsl/gsl_bst.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1211,
"size": 4083
} |
static char help[] =
"Coupled reaction-diffusion equations (Pearson 1993). Option prefix -ptn_.\n"
"Demonstrates form F(t,Y,dot Y) = G(t,Y) where F() is IFunction and G() is\n"
"RHSFunction(). Implements IJacobian() and RHSJacobian(). Defaults to\n"
"ARKIMEX (= adaptive Runge-Kutta implicit-explicit) TS type.\n\n";
#include <petsc.h>
typedef struct {
PetscReal u, v;
} Field;
typedef struct {
PetscReal L, // domain side length
Du, // diffusion coefficient: u equation
Dv, // v equation
phi, // "dimensionless feed rate" (F in Pearson 1993)
kappa; // "dimensionless rate constant" (k in Pearson 1993)
PetscBool IFcn_called, IJac_called, RHSFcn_called, RHSJac_called;
} PatternCtx;
extern PetscErrorCode InitialState(DM, Vec, PetscReal, PatternCtx*);
extern PetscErrorCode FormRHSFunctionLocal(DMDALocalInfo*, PetscReal, Field**,
Field**, PatternCtx*);
extern PetscErrorCode FormRHSJacobianLocal(DMDALocalInfo*, PetscReal, Field**,
Mat, Mat, PatternCtx*);
extern PetscErrorCode FormIFunctionLocal(DMDALocalInfo*, PetscReal, Field**, Field**,
Field **, PatternCtx*);
extern PetscErrorCode FormIJacobianLocal(DMDALocalInfo*, PetscReal, Field**, Field**,
PetscReal, Mat, Mat, PatternCtx*);
int main(int argc,char **argv)
{
PetscErrorCode ierr;
PatternCtx user;
TS ts;
Vec x;
DM da;
DMDALocalInfo info;
PetscReal noiselevel = -1.0; // negative value means no initial noise
PetscBool no_rhsjacobian = PETSC_FALSE,
no_ijacobian = PETSC_FALSE,
call_back_report = PETSC_FALSE;
TSType type;
ierr = PetscInitialize(&argc,&argv,NULL,help); if (ierr) return ierr;
// parameter values from pages 21-22 in Hundsdorfer & Verwer (2003)
user.L = 2.5;
user.Du = 8.0e-5;
user.Dv = 4.0e-5;
user.phi = 0.024;
user.kappa = 0.06;
user.IFcn_called = PETSC_FALSE;
user.IJac_called = PETSC_FALSE;
user.RHSFcn_called = PETSC_FALSE;
user.RHSJac_called = PETSC_FALSE;
ierr = PetscOptionsBegin(PETSC_COMM_WORLD, "ptn_", "options for patterns", ""); CHKERRQ(ierr);
ierr = PetscOptionsBool("-call_back_report","report on which user-supplied call-backs were actually called",
"pattern.c",call_back_report,&(call_back_report),NULL);CHKERRQ(ierr);
ierr = PetscOptionsReal("-Du","diffusion coefficient of first equation",
"pattern.c",user.Du,&user.Du,NULL);CHKERRQ(ierr);
ierr = PetscOptionsReal("-Dv","diffusion coefficient of second equation",
"pattern.c",user.Dv,&user.Dv,NULL);CHKERRQ(ierr);
ierr = PetscOptionsReal("-kappa","dimensionless rate constant (=k in (Pearson, 1993))",
"pattern.c",user.kappa,&user.kappa,NULL);CHKERRQ(ierr);
ierr = PetscOptionsReal("-L","square domain side length; recommend L >= 0.5",
"pattern.c",user.L,&user.L,NULL);CHKERRQ(ierr);
ierr = PetscOptionsBool("-no_ijacobian","do not set call-back DMDATSSetIJacobian()",
"pattern.c",no_ijacobian,&(no_ijacobian),NULL);CHKERRQ(ierr);
ierr = PetscOptionsBool("-no_rhsjacobian","do not set call-back DMDATSSetRHSJacobian()",
"pattern.c",no_rhsjacobian,&(no_rhsjacobian),NULL);CHKERRQ(ierr);
ierr = PetscOptionsReal("-noisy_init",
"initialize u,v with this much random noise (e.g. 0.2) on top of usual initial values",
"pattern.c",noiselevel,&noiselevel,NULL);CHKERRQ(ierr);
ierr = PetscOptionsReal("-phi","dimensionless feed rate (=F in (Pearson, 1993))",
"pattern.c",user.phi,&user.phi,NULL);CHKERRQ(ierr);
ierr = PetscOptionsEnd(); CHKERRQ(ierr);
ierr = DMDACreate2d(PETSC_COMM_WORLD,
DM_BOUNDARY_PERIODIC, DM_BOUNDARY_PERIODIC,
DMDA_STENCIL_BOX, // for 9-point stencil
3,3,PETSC_DECIDE,PETSC_DECIDE,
2, 1, // degrees of freedom, stencil width
NULL,NULL,&da); CHKERRQ(ierr);
ierr = DMSetFromOptions(da); CHKERRQ(ierr);
ierr = DMSetUp(da); CHKERRQ(ierr);
ierr = DMDASetFieldName(da,0,"u"); CHKERRQ(ierr);
ierr = DMDASetFieldName(da,1,"v"); CHKERRQ(ierr);
ierr = DMDAGetLocalInfo(da,&info); CHKERRQ(ierr);
if (info.mx != info.my) {
SETERRQ(PETSC_COMM_SELF,1,"pattern.c requires mx == my");
}
ierr = DMDASetUniformCoordinates(da, 0.0, user.L, 0.0, user.L, -1.0, -1.0); CHKERRQ(ierr);
ierr = PetscPrintf(PETSC_COMM_WORLD,
"running on %d x %d grid with square cells of side h = %.6f ...\n",
info.mx,info.my,user.L/(PetscReal)(info.mx)); CHKERRQ(ierr);
//STARTTSSETUP
ierr = TSCreate(PETSC_COMM_WORLD,&ts); CHKERRQ(ierr);
ierr = TSSetProblemType(ts,TS_NONLINEAR); CHKERRQ(ierr);
ierr = TSSetDM(ts,da); CHKERRQ(ierr);
ierr = TSSetApplicationContext(ts,&user); CHKERRQ(ierr);
ierr = DMDATSSetRHSFunctionLocal(da,INSERT_VALUES,
(DMDATSRHSFunctionLocal)FormRHSFunctionLocal,&user); CHKERRQ(ierr);
if (!no_rhsjacobian) {
ierr = DMDATSSetRHSJacobianLocal(da,
(DMDATSRHSJacobianLocal)FormRHSJacobianLocal,&user); CHKERRQ(ierr);
}
ierr = DMDATSSetIFunctionLocal(da,INSERT_VALUES,
(DMDATSIFunctionLocal)FormIFunctionLocal,&user); CHKERRQ(ierr);
if (!no_ijacobian) {
ierr = DMDATSSetIJacobianLocal(da,
(DMDATSIJacobianLocal)FormIJacobianLocal,&user); CHKERRQ(ierr);
}
ierr = TSSetType(ts,TSARKIMEX); CHKERRQ(ierr);
ierr = TSSetTime(ts,0.0); CHKERRQ(ierr);
ierr = TSSetMaxTime(ts,200.0); CHKERRQ(ierr);
ierr = TSSetTimeStep(ts,5.0); CHKERRQ(ierr);
ierr = TSSetExactFinalTime(ts,TS_EXACTFINALTIME_MATCHSTEP); CHKERRQ(ierr);
ierr = TSSetFromOptions(ts);CHKERRQ(ierr);
//ENDTSSETUP
ierr = DMCreateGlobalVector(da,&x); CHKERRQ(ierr);
ierr = InitialState(da,x,noiselevel,&user); CHKERRQ(ierr);
ierr = TSSolve(ts,x); CHKERRQ(ierr);
// optionally report on call-backs
if (call_back_report) {
ierr = TSGetType(ts,&type);CHKERRQ(ierr);
ierr = PetscPrintf(PETSC_COMM_WORLD,"CALL-BACK REPORT\n solver type: %s\n",type); CHKERRQ(ierr);
ierr = PetscPrintf(PETSC_COMM_WORLD," IFunction: %D | IJacobian: %D\n",
(int)user.IFcn_called,(int)user.IJac_called); CHKERRQ(ierr);
ierr = PetscPrintf(PETSC_COMM_WORLD," RHSFunction: %D | RHSJacobian: %D\n",
(int)user.RHSFcn_called,(int)user.RHSJac_called); CHKERRQ(ierr);
}
VecDestroy(&x); TSDestroy(&ts); DMDestroy(&da);
return PetscFinalize();
}
// Formulas from page 22 of Hundsdorfer & Verwer (2003). Interpretation here is
// to always generate 0.5 x 0.5 non-trivial patch in (0,L) x (0,L) domain.
PetscErrorCode InitialState(DM da, Vec Y, PetscReal noiselevel, PatternCtx* user) {
PetscErrorCode ierr;
DMDALocalInfo info;
PetscInt i,j;
PetscReal sx,sy;
const PetscReal ledge = (user->L - 0.5) / 2.0, // nontrivial initial values on
redge = user->L - ledge; // ledge < x,y < redge
DMDACoor2d **aC;
Field **aY;
ierr = VecSet(Y,0.0); CHKERRQ(ierr);
if (noiselevel > 0.0) {
// noise added to usual initial condition is uniform on [0,noiselevel],
// independently for each location and component
ierr = VecSetRandom(Y,NULL); CHKERRQ(ierr);
ierr = VecScale(Y,noiselevel); CHKERRQ(ierr);
}
ierr = DMDAGetLocalInfo(da,&info); CHKERRQ(ierr);
ierr = DMDAGetCoordinateArray(da,&aC); CHKERRQ(ierr);
ierr = DMDAVecGetArray(da,Y,&aY); CHKERRQ(ierr);
for (j = info.ys; j < info.ys+info.ym; j++) {
for (i = info.xs; i < info.xs+info.xm; i++) {
if ((aC[j][i].x >= ledge) && (aC[j][i].x <= redge)
&& (aC[j][i].y >= ledge) && (aC[j][i].y <= redge)) {
sx = PetscSinReal(4.0 * PETSC_PI * aC[j][i].x);
sy = PetscSinReal(4.0 * PETSC_PI * aC[j][i].y);
aY[j][i].v += 0.5 * sx * sx * sy * sy;
}
aY[j][i].u += 1.0 - 2.0 * aY[j][i].v;
}
}
ierr = DMDAVecRestoreArray(da,Y,&aY); CHKERRQ(ierr);
ierr = DMDARestoreCoordinateArray(da,&aC); CHKERRQ(ierr);
return 0;
}
// in system form F(t,Y,dot Y) = G(t,Y), compute G():
// G^u(t,u,v) = - u v^2 + phi (1 - u)
// G^v(t,u,v) = + u v^2 - (phi + kappa) v
//STARTRHSFUNCTION
PetscErrorCode FormRHSFunctionLocal(DMDALocalInfo *info,
PetscReal t, Field **aY, Field **aG, PatternCtx *user) {
PetscInt i, j;
PetscReal uv2;
user->RHSFcn_called = PETSC_TRUE;
for (j = info->ys; j < info->ys + info->ym; j++) {
for (i = info->xs; i < info->xs + info->xm; i++) {
uv2 = aY[j][i].u * aY[j][i].v * aY[j][i].v;
aG[j][i].u = - uv2 + user->phi * (1.0 - aY[j][i].u);
aG[j][i].v = + uv2 - (user->phi + user->kappa) * aY[j][i].v;
}
}
return 0;
}
//ENDRHSFUNCTION
PetscErrorCode FormRHSJacobianLocal(DMDALocalInfo *info,
PetscReal t, Field **aY,
Mat J, Mat P, PatternCtx *user) {
PetscErrorCode ierr;
PetscInt i, j;
PetscReal v[2], uv, v2;
MatStencil col[2],row;
user->RHSJac_called = PETSC_TRUE;
for (j = info->ys; j < info->ys+info->ym; j++) {
row.j = j; col[0].j = j; col[1].j = j;
for (i = info->xs; i < info->xs+info->xm; i++) {
row.i = i; col[0].i = i; col[1].i = i;
uv = aY[j][i].u * aY[j][i].v;
v2 = aY[j][i].v * aY[j][i].v;
// u equation
row.c = 0; col[0].c = 0; col[1].c = 1;
v[0] = - v2 - user->phi;
v[1] = - 2.0 * uv;
ierr = MatSetValuesStencil(P,1,&row,2,col,v,INSERT_VALUES); CHKERRQ(ierr);
// v equation
row.c = 1; col[0].c = 0; col[1].c = 1;
v[0] = v2;
v[1] = 2.0 * uv - (user->phi + user->kappa);
ierr = MatSetValuesStencil(P,1,&row,2,col,v,INSERT_VALUES); CHKERRQ(ierr);
}
}
ierr = MatAssemblyBegin(P,MAT_FINAL_ASSEMBLY); CHKERRQ(ierr);
ierr = MatAssemblyEnd(P,MAT_FINAL_ASSEMBLY); CHKERRQ(ierr);
if (J != P) {
ierr = MatAssemblyBegin(J,MAT_FINAL_ASSEMBLY); CHKERRQ(ierr);
ierr = MatAssemblyEnd(J,MAT_FINAL_ASSEMBLY); CHKERRQ(ierr);
}
return 0;
}
// in system form F(t,Y,dot Y) = G(t,Y), compute F():
// F^u(t,u,v,u_t,v_t) = u_t - D_u Laplacian u
// F^v(t,u,v,u_t,v_t) = v_t - D_v Laplacian v
//STARTIFUNCTION
PetscErrorCode FormIFunctionLocal(DMDALocalInfo *info, PetscReal t,
Field **aY, Field **aYdot, Field **aF,
PatternCtx *user) {
PetscInt i, j;
const PetscReal h = user->L / (PetscReal)(info->mx),
Cu = user->Du / (6.0 * h * h),
Cv = user->Dv / (6.0 * h * h);
PetscReal u, v, lapu, lapv;
user->IFcn_called = PETSC_TRUE;
for (j = info->ys; j < info->ys + info->ym; j++) {
for (i = info->xs; i < info->xs + info->xm; i++) {
u = aY[j][i].u;
v = aY[j][i].v;
lapu = aY[j+1][i-1].u + 4.0*aY[j+1][i].u + aY[j+1][i+1].u
+ 4.0*aY[j][i-1].u - 20.0*u + 4.0*aY[j][i+1].u
+ aY[j-1][i-1].u + 4.0*aY[j-1][i].u + aY[j-1][i+1].u;
lapv = aY[j+1][i-1].v + 4.0*aY[j+1][i].v + aY[j+1][i+1].v
+ 4.0*aY[j][i-1].v - 20.0*v + 4.0*aY[j][i+1].v
+ aY[j-1][i-1].v + 4.0*aY[j-1][i].v + aY[j-1][i+1].v;
aF[j][i].u = aYdot[j][i].u - Cu * lapu;
aF[j][i].v = aYdot[j][i].v - Cv * lapv;
}
}
return 0;
}
//ENDIFUNCTION
// in system form F(t,Y,dot Y) = G(t,Y), compute combined/shifted
// Jacobian of F():
// J = (shift) dF/d(dot Y) + dF/dY
//STARTIJACOBIAN
PetscErrorCode FormIJacobianLocal(DMDALocalInfo *info,
PetscReal t, Field **aY, Field **aYdot,
PetscReal shift, Mat J, Mat P,
PatternCtx *user) {
PetscErrorCode ierr;
PetscInt i, j, s, c;
const PetscReal h = user->L / (PetscReal)(info->mx),
Cu = user->Du / (6.0 * h * h),
Cv = user->Dv / (6.0 * h * h);
PetscReal val[9], CC;
MatStencil col[9], row;
ierr = MatZeroEntries(P); CHKERRQ(ierr); // workaround to address PETSc issue #734
user->IJac_called = PETSC_TRUE;
for (j = info->ys; j < info->ys + info->ym; j++) {
row.j = j;
for (i = info->xs; i < info->xs + info->xm; i++) {
row.i = i;
for (c = 0; c < 2; c++) { // u,v equations are c=0,1
row.c = c;
CC = (c == 0) ? Cu : Cv;
for (s = 0; s < 9; s++)
col[s].c = c;
col[0].i = i; col[0].j = j;
val[0] = shift + 20.0 * CC;
col[1].i = i-1; col[1].j = j; val[1] = - 4.0 * CC;
col[2].i = i+1; col[2].j = j; val[2] = - 4.0 * CC;
col[3].i = i; col[3].j = j-1; val[3] = - 4.0 * CC;
col[4].i = i; col[4].j = j+1; val[4] = - 4.0 * CC;
col[5].i = i-1; col[5].j = j-1; val[5] = - CC;
col[6].i = i-1; col[6].j = j+1; val[6] = - CC;
col[7].i = i+1; col[7].j = j-1; val[7] = - CC;
col[8].i = i+1; col[8].j = j+1; val[8] = - CC;
ierr = MatSetValuesStencil(P,1,&row,9,col,val,INSERT_VALUES); CHKERRQ(ierr);
}
}
}
ierr = MatAssemblyBegin(P,MAT_FINAL_ASSEMBLY); CHKERRQ(ierr);
ierr = MatAssemblyEnd(P,MAT_FINAL_ASSEMBLY); CHKERRQ(ierr);
if (J != P) {
ierr = MatAssemblyBegin(J,MAT_FINAL_ASSEMBLY); CHKERRQ(ierr);
ierr = MatAssemblyEnd(J,MAT_FINAL_ASSEMBLY); CHKERRQ(ierr);
}
return 0;
}
//ENDIJACOBIAN
| {
"alphanum_fraction": 0.5609999288,
"avg_line_length": 43.6055900621,
"ext": "c",
"hexsha": "1d06e3b273ac32c4b77d192457ba15534dd1cd43",
"lang": "C",
"max_forks_count": 46,
"max_forks_repo_forks_event_max_datetime": "2022-03-22T07:43:17.000Z",
"max_forks_repo_forks_event_min_datetime": "2016-07-23T09:26:58.000Z",
"max_forks_repo_head_hexsha": "421fd3d809b1e23e5a6f3c3e51252cb275a76140",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "thw1021/p4pdes",
"max_forks_repo_path": "c/ch5/pattern.c",
"max_issues_count": 52,
"max_issues_repo_head_hexsha": "421fd3d809b1e23e5a6f3c3e51252cb275a76140",
"max_issues_repo_issues_event_max_datetime": "2021-11-29T12:36:20.000Z",
"max_issues_repo_issues_event_min_datetime": "2015-09-24T17:42:48.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "thw1021/p4pdes",
"max_issues_repo_path": "c/ch5/pattern.c",
"max_line_length": 110,
"max_stars_count": 115,
"max_stars_repo_head_hexsha": "421fd3d809b1e23e5a6f3c3e51252cb275a76140",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "thw1021/p4pdes",
"max_stars_repo_path": "c/ch5/pattern.c",
"max_stars_repo_stars_event_max_datetime": "2022-03-05T23:12:02.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-03-13T04:35:40.000Z",
"num_tokens": 4554,
"size": 14041
} |
/* ode-initval/rk4imp.c
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
/* Runge-Kutta 4, Gaussian implicit */
/* Author: G. Jungman */
#include <config.h>
#include <stdlib.h>
#include <string.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_odeiv.h>
#include "odeiv_util.h"
typedef struct
{
double *k1nu;
double *k2nu;
double *ytmp1;
double *ytmp2;
}
rk4imp_state_t;
static void *
rk4imp_alloc (size_t dim)
{
rk4imp_state_t *state = (rk4imp_state_t *) malloc (sizeof (rk4imp_state_t));
if (state == 0)
{
GSL_ERROR_NULL ("failed to allocate space for rk4imp_state",
GSL_ENOMEM);
}
state->k1nu = (double *) malloc (dim * sizeof (double));
if (state->k1nu == 0)
{
free (state);
GSL_ERROR_NULL ("failed to allocate space for k1nu", GSL_ENOMEM);
}
state->k2nu = (double *) malloc (dim * sizeof (double));
if (state->k2nu == 0)
{
free (state->k1nu);
free (state);
GSL_ERROR_NULL ("failed to allocate space for k2nu", GSL_ENOMEM);
}
state->ytmp1 = (double *) malloc (dim * sizeof (double));
if (state->ytmp1 == 0)
{
free (state->k2nu);
free (state->k1nu);
free (state);
GSL_ERROR_NULL ("failed to allocate space for ytmp1", GSL_ENOMEM);
}
state->ytmp2 = (double *) malloc (dim * sizeof (double));
if (state->ytmp2 == 0)
{
free (state->ytmp1);
free (state->k2nu);
free (state->k1nu);
free (state);
GSL_ERROR_NULL ("failed to allocate space for ytmp2", GSL_ENOMEM);
}
return state;
}
static int
rk4imp_apply (void *vstate,
size_t dim,
double t,
double h,
double y[],
double yerr[],
const double dydt_in[],
double dydt_out[],
const gsl_odeiv_system * sys)
{
rk4imp_state_t *state = (rk4imp_state_t *) vstate;
const double ir3 = 1.0 / M_SQRT3;
const int iter_steps = 3;
int status = 0;
int nu;
size_t i;
double *const k1nu = state->k1nu;
double *const k2nu = state->k2nu;
double *const ytmp1 = state->ytmp1;
double *const ytmp2 = state->ytmp2;
/* initialization step */
if (dydt_in != 0)
{
DBL_MEMCPY (k1nu, dydt_in, dim);
}
else
{
int s = GSL_ODEIV_FN_EVAL (sys, t, y, k1nu);
GSL_STATUS_UPDATE (&status, s);
}
DBL_MEMCPY (k2nu, k1nu, dim);
/* iterative solution */
for (nu = 0; nu < iter_steps; nu++)
{
for (i = 0; i < dim; i++)
{
ytmp1[i] =
y[i] + h * (0.25 * k1nu[i] + 0.5 * (0.5 - ir3) * k2nu[i]);
ytmp2[i] =
y[i] + h * (0.25 * k2nu[i] + 0.5 * (0.5 + ir3) * k1nu[i]);
}
{
int s =
GSL_ODEIV_FN_EVAL (sys, t + 0.5 * h * (1.0 - ir3), ytmp1, k1nu);
GSL_STATUS_UPDATE (&status, s);
}
{
int s =
GSL_ODEIV_FN_EVAL (sys, t + 0.5 * h * (1.0 + ir3), ytmp2, k2nu);
GSL_STATUS_UPDATE (&status, s);
}
}
/* assignment */
for (i = 0; i < dim; i++)
{
const double d_i = 0.5 * (k1nu[i] + k2nu[i]);
if (dydt_out != NULL)
dydt_out[i] = d_i;
y[i] += h * d_i;
yerr[i] = h * h * d_i; /* FIXME: is this an overestimate ? */
}
return status;
}
static int
rk4imp_reset (void *vstate, size_t dim)
{
rk4imp_state_t *state = (rk4imp_state_t *) vstate;
DBL_ZERO_MEMSET (state->k1nu, dim);
DBL_ZERO_MEMSET (state->k2nu, dim);
DBL_ZERO_MEMSET (state->ytmp1, dim);
DBL_ZERO_MEMSET (state->ytmp2, dim);
return GSL_SUCCESS;
}
static unsigned int
rk4imp_order (void *vstate)
{
rk4imp_state_t *state = (rk4imp_state_t *) vstate;
state = 0; /* prevent warnings about unused parameters */
return 4;
}
static void
rk4imp_free (void *vstate)
{
rk4imp_state_t *state = (rk4imp_state_t *) vstate;
free (state->k1nu);
free (state->k2nu);
free (state->ytmp1);
free (state->ytmp2);
free (state);
}
static const gsl_odeiv_step_type rk4imp_type = { "rk4imp", /* name */
1, /* can use dydt_in */
0, /* gives exact dydt_out */
&rk4imp_alloc,
&rk4imp_apply,
&rk4imp_reset,
&rk4imp_order,
&rk4imp_free
};
const gsl_odeiv_step_type *gsl_odeiv_step_rk4imp = &rk4imp_type;
| {
"alphanum_fraction": 0.591735864,
"avg_line_length": 24.0857142857,
"ext": "c",
"hexsha": "7f31eac0ff5a598906bdbf7ccbc9ff42a6a67716",
"lang": "C",
"max_forks_count": 14,
"max_forks_repo_forks_event_max_datetime": "2021-06-10T03:09:53.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-04-29T20:31:00.000Z",
"max_forks_repo_head_hexsha": "c0d957265608b15f216ece67363c827d01122102",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "pvnuffel/test_repos",
"max_forks_repo_path": "gsl_subset/ode-initval/rk4imp.c",
"max_issues_count": 2,
"max_issues_repo_head_hexsha": "c0d957265608b15f216ece67363c827d01122102",
"max_issues_repo_issues_event_max_datetime": "2020-07-20T16:32:02.000Z",
"max_issues_repo_issues_event_min_datetime": "2017-11-07T05:42:56.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "pvnuffel/test_repos",
"max_issues_repo_path": "gsl_subset/ode-initval/rk4imp.c",
"max_line_length": 78,
"max_stars_count": 30,
"max_stars_repo_head_hexsha": "c0d957265608b15f216ece67363c827d01122102",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "pvnuffel/test_repos",
"max_stars_repo_path": "gsl_subset/ode-initval/rk4imp.c",
"max_stars_repo_stars_event_max_datetime": "2022-03-21T02:07:41.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-04-29T05:13:02.000Z",
"num_tokens": 1612,
"size": 5058
} |
/*
* This file is part of the GROMACS molecular simulation package.
*
* Copyright (c) 1991-2000, University of Groningen, The Netherlands.
* Copyright (c) 2001-2004, The GROMACS development team,
* check out http://www.gromacs.org for more information.
* Copyright (c) 2012,2013, by the GROMACS development team, led by
* David van der Spoel, Berk Hess, Erik Lindahl, and including many
* others, as listed in the AUTHORS file in the top-level source
* directory and at http://www.gromacs.org.
*
* GROMACS is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation; either version 2.1
* of the License, or (at your option) any later version.
*
* GROMACS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with GROMACS; if not, see
* http://www.gnu.org/licenses, or write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
* If you want to redistribute modifications to GROMACS, please
* consider that scientific software is very special. Version
* control is crucial - bugs must be traceable. We will be happy to
* consider code for inclusion in the official distribution, but
* derived work must not be called official GROMACS. Details are found
* in the README & COPYING files - if they are missing, get the
* official version at http://www.gromacs.org.
*
* To help us fund GROMACS development, we humbly ask that you cite
* the research papers on the package. Check out http://www.gromacs.org.
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#ifdef HAVE_LIBGSL
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_blas.h>
#include <gsl/gsl_multimin.h>
#include <gsl/gsl_multifit_nlin.h>
#include <gsl/gsl_sf.h>
#include <gsl/gsl_version.h>
#endif
#include <math.h>
#include "typedefs.h"
#include "smalloc.h"
#include "vec.h"
#include "geminate.h"
#include "gmx_omp.h"
/* The first few sections of this file contain functions that were adopted,
* and to some extent modified, by Erik Marklund (erikm[aT]xray.bmc.uu.se,
* http://folding.bmc.uu.se) from code written by Omer Markovitch (email, url).
* This is also the case with the function eq10v2().
*
* The parts menetioned in the previous paragraph were contributed under the BSD license.
*/
/* This first part is from complex.c which I recieved from Omer Markowitch.
* - Erik Marklund
*
* ------------- from complex.c ------------- */
/* Complexation of a paired number (r,i) */
static gem_complex gem_cmplx(double r, double i)
{
gem_complex value;
value.r = r;
value.i = i;
return value;
}
/* Complexation of a real number, x */
static gem_complex gem_c(double x)
{
gem_complex value;
value.r = x;
value.i = 0;
return value;
}
/* Magnitude of a complex number z */
static double gem_cx_abs(gem_complex z)
{
return (sqrt(z.r*z.r+z.i*z.i));
}
/* Addition of two complex numbers z1 and z2 */
static gem_complex gem_cxadd(gem_complex z1, gem_complex z2)
{
gem_complex value;
value.r = z1.r+z2.r;
value.i = z1.i+z2.i;
return value;
}
/* Addition of a complex number z1 and a real number r */
static gem_complex gem_cxradd(gem_complex z, double r)
{
gem_complex value;
value.r = z.r + r;
value.i = z.i;
return value;
}
/* Subtraction of two complex numbers z1 and z2 */
static gem_complex gem_cxsub(gem_complex z1, gem_complex z2)
{
gem_complex value;
value.r = z1.r-z2.r;
value.i = z1.i-z2.i;
return value;
}
/* Multiplication of two complex numbers z1 and z2 */
static gem_complex gem_cxmul(gem_complex z1, gem_complex z2)
{
gem_complex value;
value.r = z1.r*z2.r-z1.i*z2.i;
value.i = z1.r*z2.i+z1.i*z2.r;
return value;
}
/* Square of a complex number z */
static gem_complex gem_cxsq(gem_complex z)
{
gem_complex value;
value.r = z.r*z.r-z.i*z.i;
value.i = z.r*z.i*2.;
return value;
}
/* multiplication of a complex number z and a real number r */
static gem_complex gem_cxrmul(gem_complex z, double r)
{
gem_complex value;
value.r = z.r*r;
value.i = z.i*r;
return value;
}
/* Division of two complex numbers z1 and z2 */
static gem_complex gem_cxdiv(gem_complex z1, gem_complex z2)
{
gem_complex value;
double num;
num = z2.r*z2.r+z2.i*z2.i;
if (num == 0.)
{
fprintf(stderr, "ERROR in gem_cxdiv function\n");
}
value.r = (z1.r*z2.r+z1.i*z2.i)/num; value.i = (z1.i*z2.r-z1.r*z2.i)/num;
return value;
}
/* division of a complex z number by a real number x */
static gem_complex gem_cxrdiv(gem_complex z, double r)
{
gem_complex value;
value.r = z.r/r;
value.i = z.i/r;
return value;
}
/* division of a real number r by a complex number x */
static gem_complex gem_rxcdiv(double r, gem_complex z)
{
gem_complex value;
double f;
f = r/(z.r*z.r+z.i*z.i);
value.r = f*z.r;
value.i = -f*z.i;
return value;
}
/* Exponential of a complex number-- exp (z)=|exp(z.r)|*{cos(z.i)+I*sin(z.i)}*/
static gem_complex gem_cxdexp(gem_complex z)
{
gem_complex value;
double exp_z_r;
exp_z_r = exp(z.r);
value.r = exp_z_r*cos(z.i);
value.i = exp_z_r*sin(z.i);
return value;
}
/* Logarithm of a complex number -- log(z)=log|z|+I*Arg(z), */
/* where -PI < Arg(z) < PI */
static gem_complex gem_cxlog(gem_complex z)
{
gem_complex value;
double mag2;
mag2 = z.r*z.r+z.i*z.i;
if (mag2 < 0.)
{
fprintf(stderr, "ERROR in gem_cxlog func\n");
}
value.r = log(sqrt(mag2));
if (z.r == 0.)
{
value.i = PI/2.;
if (z.i < 0.)
{
value.i = -value.i;
}
}
else
{
value.i = atan2(z.i, z.r);
}
return value;
}
/* Square root of a complex number z = |z| exp(I*the) -- z^(1/2) */
/* z^(1/2)=|z|^(1/2)*[cos(the/2)+I*sin(the/2)] */
/* where 0 < the < 2*PI */
static gem_complex gem_cxdsqrt(gem_complex z)
{
gem_complex value;
double sq;
sq = gem_cx_abs(z);
value.r = sqrt(fabs((sq+z.r)*0.5)); /* z'.r={|z|*[1+cos(the)]/2}^(1/2) */
value.i = sqrt(fabs((sq-z.r)*0.5)); /* z'.i={|z|*[1-cos(the)]/2}^(1/2) */
if (z.i < 0.)
{
value.r = -value.r;
}
return value;
}
/* Complex power of a complex number z1^z2 */
static gem_complex gem_cxdpow(gem_complex z1, gem_complex z2)
{
gem_complex value;
value = gem_cxdexp(gem_cxmul(gem_cxlog(z1), z2));
return value;
}
/* ------------ end of complex.c ------------ */
/* This next part was derived from cubic.c, also received from Omer Markovitch.
* ------------- from cubic.c ------------- */
/* Solver for a cubic equation: x^3-a*x^2+b*x-c=0 */
static void gem_solve(gem_complex *al, gem_complex *be, gem_complex *gam,
double a, double b, double c)
{
double t1, t2, two_3, temp;
gem_complex ctemp, ct3;
two_3 = pow(2., 1./3.); t1 = -a*a+3.*b; t2 = 2.*a*a*a-9.*a*b+27.*c;
temp = 4.*t1*t1*t1+t2*t2;
ctemp = gem_cmplx(temp, 0.); ctemp = gem_cxadd(gem_cmplx(t2, 0.), gem_cxdsqrt(ctemp));
ct3 = gem_cxdpow(ctemp, gem_cmplx(1./3., 0.));
ctemp = gem_rxcdiv(-two_3*t1/3., ct3);
ctemp = gem_cxadd(ctemp, gem_cxrdiv(ct3, 3.*two_3));
*gam = gem_cxadd(gem_cmplx(a/3., 0.), ctemp);
ctemp = gem_cxmul(gem_cxsq(*gam), gem_cxsq(gem_cxsub(*gam, gem_cmplx(a, 0.))));
ctemp = gem_cxadd(ctemp, gem_cxmul(gem_cmplx(-4.*c, 0.), *gam));
ctemp = gem_cxdiv(gem_cxdsqrt(ctemp), *gam);
*al = gem_cxrmul(gem_cxsub(gem_cxsub(gem_cmplx(a, 0.), *gam), ctemp), 0.5);
*be = gem_cxrmul(gem_cxadd(gem_cxsub(gem_cmplx(a, 0.), *gam), ctemp), 0.5);
}
/* ------------ end of cubic.c ------------ */
/* This next part was derived from cerror.c and rerror.c, also received from Omer Markovitch.
* ------------- from [cr]error.c ------------- */
/************************************************************/
/* Real valued error function and related functions */
/* x, y : real variables */
/* erf(x) : error function */
/* erfc(x) : complementary error function */
/* omega(x) : exp(x*x)*erfc(x) */
/* W(x,y) : exp(-x*x)*omega(x+y)=exp(2*x*y+y^2)*erfc(x+y) */
/************************************************************/
/*---------------------------------------------------------------------------*/
/* Utilzed the series approximation of erf(x) */
/* Relative error=|err(x)|/erf(x)<EPS */
/* Handbook of Mathematical functions, Abramowitz, p 297 */
/* Note: When x>=6 series sum deteriorates -> Asymptotic series used instead */
/*---------------------------------------------------------------------------*/
/* This gives erfc(z) correctly only upto >10-15 */
static double gem_erf(double x)
{
double n, sum, temp, exp2, xm, x2, x4, x6, x8, x10, x12;
temp = x;
sum = temp;
xm = 26.;
x2 = x*x;
x4 = x2*x2;
x6 = x4*x2;
x8 = x6*x2;
x10 = x8*x2;
x12 = x10*x2;
exp2 = exp(-x2);
if (x <= xm)
{
for (n = 1.; n <= 2000.; n += 1.)
{
temp *= 2.*x2/(2.*n+1.);
sum += temp;
if (fabs(temp/sum) < 1.E-16)
{
break;
}
}
if (n >= 2000.)
{
fprintf(stderr, "In Erf calc - iteration exceeds %lg\n", n);
}
sum *= 2./sPI*exp2;
}
else
{
/* from the asymptotic expansion of experfc(x) */
sum = (1. - 0.5/x2 + 0.75/x4
- 1.875/x6 + 6.5625/x8
- 29.53125/x10 + 162.421875/x12)
/ sPI/x;
sum *= exp2; /* now sum is erfc(x) */
sum = -sum+1.;
}
return x >= 0.0 ? sum : -sum;
}
/* Result --> Alex's code for erfc and experfc behaves better than this */
/* complementray error function. Returns 1.-erf(x) */
static double gem_erfc(double x)
{
double t, z, ans;
z = fabs(x);
t = 1.0/(1.0+0.5*z);
ans = t * exp(-z*z - 1.26551223 +
t*(1.00002368 +
t*(0.37409196 +
t*(0.09678418 +
t*(-0.18628806 +
t*(0.27886807 +
t*(-1.13520398 +
t*(1.48851587 +
t*(-0.82215223 +
t*0.17087277)))))))));
return x >= 0.0 ? ans : 2.0-ans;
}
/* omega(x)=exp(x^2)erfc(x) */
static double gem_omega(double x)
{
double xm, ans, xx, x4, x6, x8, x10, x12;
xm = 26;
xx = x*x;
x4 = xx*xx;
x6 = x4*xx;
x8 = x6*xx;
x10 = x8*xx;
x12 = x10*xx;
if (x <= xm)
{
ans = exp(xx)*gem_erfc(x);
}
else
{
/* Asymptotic expansion */
ans = (1. - 0.5/xx + 0.75/x4 - 1.875/x6 + 6.5625/x8 - 29.53125/x10 + 162.421875/x12) / sPI/x;
}
return ans;
}
/*---------------------------------------------------------------------------*/
/* Utilzed the series approximation of erf(z=x+iy) */
/* Relative error=|err(z)|/|erf(z)|<EPS */
/* Handbook of Mathematical functions, Abramowitz, p 299 */
/* comega(z=x+iy)=cexp(z^2)*cerfc(z) */
/*---------------------------------------------------------------------------*/
static gem_complex gem_comega(gem_complex z)
{
gem_complex value;
double x, y;
double sumr, sumi, n, n2, f, temp, temp1;
double x2, y2, cos_2xy, sin_2xy, cosh_2xy, sinh_2xy, cosh_ny, sinh_ny, exp_y2;
x = z.r;
y = z.i;
x2 = x*x;
y2 = y*y;
sumr = 0.;
sumi = 0.;
cos_2xy = cos(2.*x*y);
sin_2xy = sin(2.*x*y);
cosh_2xy = cosh(2.*x*y);
sinh_2xy = sinh(2.*x*y);
exp_y2 = exp(-y2);
for (n = 1.0, temp = 0.; n <= 2000.; n += 1.0)
{
n2 = n*n;
cosh_ny = cosh(n*y);
sinh_ny = sinh(n*y);
f = exp(-n2/4.)/(n2+4.*x2);
/* if(f<1.E-200) break; */
sumr += (2.*x - 2.*x*cosh_ny*cos_2xy + n*sinh_ny*sin_2xy)*f;
sumi += (2.*x*cosh_ny*sin_2xy + n*sinh_ny*cos_2xy)*f;
temp1 = sqrt(sumr*sumr+sumi*sumi);
if (fabs((temp1-temp)/temp1) < 1.E-16)
{
break;
}
temp = temp1;
}
if (n == 2000.)
{
fprintf(stderr, "iteration exceeds %lg\n", n);
}
sumr *= 2./PI;
sumi *= 2./PI;
if (x != 0.)
{
f = 1./2./PI/x;
}
else
{
f = 0.;
}
value.r = gem_omega(x)-(f*(1.-cos_2xy)+sumr);
value.i = -(f*sin_2xy+sumi);
value = gem_cxmul(value, gem_cmplx(exp_y2*cos_2xy, exp_y2*sin_2xy));
return (value);
}
/* ------------ end of [cr]error.c ------------ */
/*_ REVERSIBLE GEMINATE RECOMBINATION
*
* Here are the functions for reversible geminate recombination. */
/* Changes the unit from square cm per s to square Ångström per ps,
* since Omers code uses the latter units while g_mds outputs the former.
* g_hbond expects a diffusion coefficent given in square cm per s. */
static double sqcm_per_s_to_sqA_per_ps (real D)
{
fprintf(stdout, "Diffusion coefficient is %f A^2/ps\n", D*1e4);
return (double)(D*1e4);
}
static double eq10v2(double theoryCt[], double time[], int manytimes,
double ka, double kd, t_gemParams *params)
{
/* Finding the 3 roots */
int i;
double kD, D, r, a, b, c, tsqrt, sumimaginary;
gem_complex
alpha, beta, gamma,
c1, c2, c3, c4,
oma, omb, omc,
part1, part2, part3, part4;
kD = params->kD;
D = params->D;
r = params->sigma;
a = (1.0 + ka/kD) * sqrt(D)/r;
b = kd;
c = kd * sqrt(D)/r;
gem_solve(&alpha, &beta, &gamma, a, b, c);
/* Finding the 3 roots */
sumimaginary = 0;
part1 = gem_cxmul(alpha, gem_cxmul(gem_cxadd(beta, gamma), gem_cxsub(beta, gamma))); /* 1(2+3)(2-3) */
part2 = gem_cxmul(beta, gem_cxmul(gem_cxadd(gamma, alpha), gem_cxsub(gamma, alpha))); /* 2(3+1)(3-1) */
part3 = gem_cxmul(gamma, gem_cxmul(gem_cxadd(alpha, beta), gem_cxsub(alpha, beta))); /* 3(1+2)(1-2) */
part4 = gem_cxmul(gem_cxsub(gamma, alpha), gem_cxmul(gem_cxsub(alpha, beta), gem_cxsub(beta, gamma))); /* (3-1)(1-2)(2-3) */
#pragma omp parallel for \
private(i, tsqrt, oma, omb, omc, c1, c2, c3, c4) \
reduction(+:sumimaginary) \
default(shared) \
schedule(guided)
for (i = 0; i < manytimes; i++)
{
tsqrt = sqrt(time[i]);
oma = gem_comega(gem_cxrmul(alpha, tsqrt));
c1 = gem_cxmul(oma, gem_cxdiv(part1, part4));
omb = gem_comega(gem_cxrmul(beta, tsqrt));
c2 = gem_cxmul(omb, gem_cxdiv(part2, part4));
omc = gem_comega(gem_cxrmul(gamma, tsqrt));
c3 = gem_cxmul(omc, gem_cxdiv(part3, part4));
c4.r = c1.r+c2.r+c3.r;
c4.i = c1.i+c2.i+c3.i;
theoryCt[i] = c4.r;
sumimaginary += c4.i * c4.i;
}
return sumimaginary;
} /* eq10v2 */
/* This returns the real-valued index(!) to an ACF, equidistant on a log scale. */
static double getLogIndex(const int i, const t_gemParams *params)
{
return (exp(((double)(i)) * params->logQuota) -1);
}
extern t_gemParams *init_gemParams(const double sigma, const double D,
const real *t, const int len, const int nFitPoints,
const real begFit, const real endFit,
const real ballistic, const int nBalExp, const gmx_bool bDt)
{
double tDelta;
t_gemParams *p;
snew(p, 1);
/* A few hardcoded things here. For now anyway. */
/* p->ka_min = 0; */
/* p->ka_max = 100; */
/* p->dka = 10; */
/* p->kd_min = 0; */
/* p->kd_max = 2; */
/* p->dkd = 0.2; */
p->ka = 0;
p->kd = 0;
/* p->lsq = -1; */
/* p->lifetime = 0; */
p->sigma = sigma*10; /* Omer uses Å, not nm */
/* p->lsq_old = 99999; */
p->D = sqcm_per_s_to_sqA_per_ps(D);
p->kD = 4*acos(-1.0)*sigma*p->D;
/* Parameters used by calcsquare(). Better to calculate them
* here than in calcsquare every time it's called. */
p->len = len;
/* p->logAfterTime = logAfterTime; */
tDelta = (t[len-1]-t[0]) / len;
if (tDelta <= 0)
{
gmx_fatal(FARGS, "Time between frames is non-positive!");
}
else
{
p->tDelta = tDelta;
}
p->nExpFit = nBalExp;
/* p->nLin = logAfterTime / tDelta; */
p->nFitPoints = nFitPoints;
p->begFit = begFit;
p->endFit = endFit;
p->logQuota = (double)(log(p->len))/(p->nFitPoints-1);
/* if (p->nLin <= 0) { */
/* fprintf(stderr, "Number of data points in the linear regime is non-positive!\n"); */
/* sfree(p); */
/* return NULL; */
/* } */
/* We want the same number of data points in the log regime. Not crucial, but seems like a good idea. */
/* p->logDelta = log(((float)len)/p->nFitPoints) / p->nFitPoints;/\* log(((float)len)/p->nLin) / p->nLin; *\/ */
/* p->logPF = p->nFitPoints*p->nFitPoints/(float)len; /\* p->nLin*p->nLin/(float)len; *\/ */
/* logPF and logDelta are stitched together with the macro GETLOGINDEX defined in geminate.h */
/* p->logMult = pow((float)len, 1.0/nLin);/\* pow(t[len-1]-t[0], 1.0/p->nLin); *\/ */
p->ballistic = ballistic;
return p;
}
/* There was a misunderstanding regarding the fitting. From our
* recent correspondence it appears that Omer's code require
* the ACF data on a log-scale and does not operate on the raw data.
* This needs to be redone in gemFunc_residual() as well as in the
* t_gemParams structure. */
#ifdef HAVE_LIBGSL
static double gemFunc_residual2(const gsl_vector *p, void *data)
{
gemFitData *GD;
int i, iLog, nLin, nFitPoints, nData;
double r, residual2, *ctTheory, *y;
GD = (gemFitData *)data;
nLin = GD->params->nLin;
nFitPoints = GD->params->nFitPoints;
nData = GD->nData;
residual2 = 0;
ctTheory = GD->ctTheory;
y = GD->y;
/* Now, we'd save a lot of time by not calculating eq10v2 for all
* time points, but only those that we sample to calculate the mse.
*/
eq10v2(GD->ctTheory, GD->doubleLogTime /* GD->time */, nFitPoints /* GD->nData */,
gsl_vector_get(p, 0), gsl_vector_get(p, 1),
GD->params);
fixGemACF(GD->ctTheory, nFitPoints);
/* Removing a bunch of points from the log-part. */
#pragma omp parallel for schedule(dynamic) \
firstprivate(nData, ctTheory, y, nFitPoints) \
private (i, iLog, r) \
reduction(+:residual2) \
default(shared)
for (i = 0; i < nFitPoints; i++)
{
iLog = GD->logtime[i];
r = log(ctTheory[i /* iLog */]);
residual2 += sqr(r-log(y[iLog]));
}
residual2 /= nFitPoints; /* Not really necessary for the fitting, but gives more meaning to the returned data. */
/* printf("ka=%3.5f\tkd=%3.5f\trmse=%3.5f\n", gsl_vector_get(p,0), gsl_vector_get(p,1), residual2); */
return residual2;
/* for (i=0; i<nLin; i++) { */
/* /\* Linear part ----------*\/ */
/* r = ctTheory[i]; */
/* residual2 += sqr(r-y[i]); */
/* /\* Log part -------------*\/ */
/* iLog = GETLOGINDEX(i, GD->params); */
/* if (iLog >= nData) */
/* gmx_fatal(FARGS, "log index out of bounds: %i", iLog); */
/* r = ctTheory[iLog]; */
/* residual2 += sqr(r-y[iLog]); */
/* } */
/* residual2 /= GD->n; */
/* return residual2; */
}
#endif
static real* d2r(const double *d, const int nn);
extern real fitGemRecomb(double *ct, double *time, double **ctFit,
const int nData, t_gemParams *params)
{
int nThreads, i, iter, status, maxiter;
real size, d2, tol, *dumpdata;
size_t p, n;
gemFitData *GD;
char *dumpstr, dumpname[128];
/* nmsimplex2 had convergence problems prior to gsl v1.14,
* but it's O(N) instead of O(N) operations, so let's use it if v >= 1.14 */
#ifdef HAVE_LIBGSL
gsl_multimin_fminimizer *s;
gsl_vector *x, *dx; /* parameters and initial step size */
gsl_multimin_function fitFunc;
#ifdef GSL_MAJOR_VERSION
#ifdef GSL_MINOR_VERSION
#if ((GSL_MAJOR_VERSION == 1 && GSL_MINOR_VERSION >= 14) || \
(GSL_MAJOR_VERSION > 1))
const gsl_multimin_fminimizer_type *T = gsl_multimin_fminimizer_nmsimplex2;
#else
const gsl_multimin_fminimizer_type *T = gsl_multimin_fminimizer_nmsimplex;
#endif /* #if ... */
#endif /* GSL_MINOR_VERSION */
#else
const gsl_multimin_fminimizer_type *T = gsl_multimin_fminimizer_nmsimplex;
#endif /* GSL_MAJOR_VERSION */
fprintf(stdout, "Will fit ka and kd to the ACF according to the reversible geminate recombination model.\n");
#else /* HAVE_LIBGSL */
fprintf(stderr, "Sorry, can't do reversible geminate recombination without gsl. "
"Recompile using --with-gsl.\n");
return -1;
#endif /* HAVE_LIBGSL */
#ifdef HAVE_LIBGSL
#ifdef GMX_OPENMP
nThreads = gmx_omp_get_max_threads();
gmx_omp_set_num_threads(nThreads);
fprintf(stdout, "We will be using %i threads.\n", nThreads);
#endif
iter = 0;
status = 0;
maxiter = 100;
tol = 1e-10;
p = 2; /* Number of parameters to fit. ka and kd. */
n = params->nFitPoints; /* params->nLin*2 */; /* Number of points in the reduced dataset */
if (params->D <= 0)
{
fprintf(stderr, "Fitting of D is not implemented yet. It must be provided on the command line.\n");
return -1;
}
/* if (nData<n) { */
/* fprintf(stderr, "Reduced data set larger than the complete data set!\n"); */
/* n=nData; */
/* } */
snew(dumpdata, nData);
snew(GD, 1);
GD->n = n;
GD->y = ct;
GD->ctTheory = NULL;
snew(GD->ctTheory, nData);
GD->LinLog = NULL;
snew(GD->LinLog, n);
GD->time = time;
GD->ka = 0;
GD->kd = 0;
GD->tDelta = time[1]-time[0];
GD->nData = nData;
GD->params = params;
snew(GD->logtime, params->nFitPoints);
snew(GD->doubleLogTime, params->nFitPoints);
for (i = 0; i < params->nFitPoints; i++)
{
GD->doubleLogTime[i] = (double)(getLogIndex(i, params));
GD->logtime[i] = (int)(GD->doubleLogTime[i]);
GD->doubleLogTime[i] *= GD->tDelta;
if (GD->logtime[i] >= nData)
{
fprintf(stderr, "Ayay. It seems we're indexing out of bounds.\n");
params->nFitPoints = i;
}
}
fitFunc.f = &gemFunc_residual2;
fitFunc.n = 2;
fitFunc.params = (void*)GD;
x = gsl_vector_alloc (fitFunc.n);
dx = gsl_vector_alloc (fitFunc.n);
gsl_vector_set (x, 0, 25);
gsl_vector_set (x, 1, 0.5);
gsl_vector_set (dx, 0, 0.1);
gsl_vector_set (dx, 1, 0.01);
s = gsl_multimin_fminimizer_alloc (T, fitFunc.n);
gsl_multimin_fminimizer_set (s, &fitFunc, x, dx);
gsl_vector_free (x);
gsl_vector_free (dx);
do
{
iter++;
status = gsl_multimin_fminimizer_iterate (s);
if (status != 0)
{
gmx_fatal(FARGS, "Something went wrong in the iteration in minimizer %s:\n \"%s\"\n",
gsl_multimin_fminimizer_name(s), gsl_strerror(status));
}
d2 = gsl_multimin_fminimizer_minimum(s);
size = gsl_multimin_fminimizer_size(s);
params->ka = gsl_vector_get (s->x, 0);
params->kd = gsl_vector_get (s->x, 1);
if (status)
{
fprintf(stderr, "%s\n", gsl_strerror(status));
break;
}
status = gsl_multimin_test_size(size, tol);
if (status == GSL_SUCCESS)
{
fprintf(stdout, "Converged to minimum at\n");
}
printf ("iter %5d: ka = %2.5f kd = %2.5f f() = %7.3f size = %.3f chi2 = %2.5f\n",
iter,
params->ka,
params->kd,
s->fval, size, d2);
if (iter%1 == 0)
{
eq10v2(GD->ctTheory, time, nData, params->ka, params->kd, params);
/* fixGemACF(GD->ctTheory, nFitPoints); */
sprintf(dumpname, "Iter_%i.xvg", iter);
for (i = 0; i < GD->nData; i++)
{
dumpdata[i] = (real)(GD->ctTheory[i]);
if (!gmx_isfinite(dumpdata[i]))
{
gmx_fatal(FARGS, "Non-finite value in acf.");
}
}
dumpN(dumpdata, GD->nData, dumpname);
}
}
while ((status == GSL_CONTINUE) && (iter < maxiter));
/* /\* Calculate the theoretical ACF from the parameters one last time. *\/ */
eq10v2(GD->ctTheory, time, nData, params->ka, params->kd, params);
*ctFit = GD->ctTheory;
sfree(GD);
gsl_multimin_fminimizer_free (s);
return d2;
#endif /* HAVE_LIBGSL */
}
#ifdef HAVE_LIBGSL
static int balFunc_f(const gsl_vector *x, void *data, gsl_vector *f)
{
/* C + sum{ A_i * exp(-B_i * t) }*/
balData *BD;
int n, i, j, nexp;
double *y, *A, *B, C, /* There are the parameters to be optimized. */
t, ct;
BD = (balData *)data;
n = BD->n;
nexp = BD->nexp;
y = BD->y,
snew(A, nexp);
snew(B, nexp);
for (i = 0; i < nexp; i++)
{
A[i] = gsl_vector_get(x, i*2);
B[i] = gsl_vector_get(x, i*2+1);
}
C = gsl_vector_get(x, nexp*2);
for (i = 0; i < n; i++)
{
t = i*BD->tDelta;
ct = 0;
for (j = 0; j < nexp; j++)
{
ct += A[j] * exp(B[j] * t);
}
ct += C;
gsl_vector_set (f, i, ct - y[i]);
}
return GSL_SUCCESS;
}
/* The derivative stored in jacobian form (J)*/
static int balFunc_df(const gsl_vector *params, void *data, gsl_matrix *J)
{
balData *BD;
size_t n, i, j;
double *y, *A, *B, C, /* There are the parameters. */
t;
int nexp;
BD = (balData*)data;
n = BD->n;
y = BD->y;
nexp = BD->nexp;
snew(A, nexp);
snew(B, nexp);
for (i = 0; i < nexp; i++)
{
A[i] = gsl_vector_get(params, i*2);
B[i] = gsl_vector_get(params, i*2+1);
}
C = gsl_vector_get(params, nexp*2);
for (i = 0; i < n; i++)
{
t = i*BD->tDelta;
for (j = 0; j < nexp; j++)
{
gsl_matrix_set (J, i, j*2, exp(B[j]*t)); /* df(t)/dA_j */
gsl_matrix_set (J, i, j*2+1, A[j]*t*exp(B[j]*t)); /* df(t)/dB_j */
}
gsl_matrix_set (J, i, nexp*2, 1); /* df(t)/dC */
}
return GSL_SUCCESS;
}
/* Calculation of the function and its derivative */
static int balFunc_fdf(const gsl_vector *params, void *data,
gsl_vector *f, gsl_matrix *J)
{
balFunc_f(params, data, f);
balFunc_df(params, data, J);
return GSL_SUCCESS;
}
#endif /* HAVE_LIBGSL */
/* Removes the ballistic term from the beginning of the ACF,
* just like in Omer's paper.
*/
extern void takeAwayBallistic(double *ct, double *t, int len, real tMax, int nexp, gmx_bool bDerivative)
{
/* Use nonlinear regression with GSL instead.
* Fit with 4 exponentials and one constant term,
* subtract the fatest exponential. */
int nData, i, status, iter;
balData *BD;
double *guess, /* Initial guess. */
*A, /* The fitted parameters. (A1, B1, A2, B2,... C) */
a[2],
ddt[2];
gmx_bool sorted;
size_t n;
size_t p;
nData = 0;
do
{
nData++;
}
while (t[nData] < tMax+t[0] && nData < len);
p = nexp*2+1; /* Number of parameters. */
#ifdef HAVE_LIBGSL
const gsl_multifit_fdfsolver_type *T
= gsl_multifit_fdfsolver_lmsder;
gsl_multifit_fdfsolver *s; /* The solver itself. */
gsl_multifit_function_fdf fitFunction; /* The function to be fitted. */
gsl_matrix *covar; /* Covariance matrix for the parameters.
* We'll not use the result, though. */
gsl_vector_view theParams;
nData = 0;
do
{
nData++;
}
while (t[nData] < tMax+t[0] && nData < len);
guess = NULL;
n = nData;
snew(guess, p);
snew(A, p);
covar = gsl_matrix_alloc (p, p);
/* Set up an initial gess for the parameters.
* The solver is somewhat sensitive to the initial guess,
* but this worked fine for a TIP3P box with -geminate dd
* EDIT: In fact, this seems like a good starting pont for other watermodels too. */
for (i = 0; i < nexp; i++)
{
guess[i*2] = 0.1;
guess[i*2+1] = -0.5 + (((double)i)/nexp - 0.5)*0.3;
}
guess[nexp * 2] = 0.01;
theParams = gsl_vector_view_array(guess, p);
snew(BD, 1);
BD->n = n;
BD->y = ct;
BD->tDelta = t[1]-t[0];
BD->nexp = nexp;
fitFunction.f = &balFunc_f;
fitFunction.df = &balFunc_df;
fitFunction.fdf = &balFunc_fdf;
fitFunction.n = nData;
fitFunction.p = p;
fitFunction.params = BD;
s = gsl_multifit_fdfsolver_alloc (T, nData, p);
if (s == NULL)
{
gmx_fatal(FARGS, "Could not set up the nonlinear solver.");
}
gsl_multifit_fdfsolver_set(s, &fitFunction, &theParams.vector);
/* \=============================================/ */
iter = 0;
do
{
iter++;
status = gsl_multifit_fdfsolver_iterate (s);
if (status)
{
break;
}
status = gsl_multifit_test_delta (s->dx, s->x, 1e-4, 1e-4);
}
while (iter < 5000 && status == GSL_CONTINUE);
if (iter == 5000)
{
fprintf(stderr, "The non-linear fitting did not converge in 5000 steps.\n"
"Check the quality of the fit!\n");
}
else
{
fprintf(stderr, "Non-linear fitting of ballistic term converged in %d steps.\n\n", (int)iter);
}
for (i = 0; i < nexp; i++)
{
fprintf(stdout, "%c * exp(%c * t) + ", 'A'+(char)i*2, 'B'+(char)i*2);
}
fprintf(stdout, "%c\n", 'A'+(char)nexp*2);
fprintf(stdout, "Here are the actual numbers for A-%c:\n", 'A'+nexp*2);
for (i = 0; i < nexp; i++)
{
A[i*2] = gsl_vector_get(s->x, i*2);
A[i*2+1] = gsl_vector_get(s->x, i*2+1);
fprintf(stdout, " %g*exp(%g * x) +", A[i*2], A[i*2+1]);
}
A[i*2] = gsl_vector_get(s->x, i*2); /* The last and constant term */
fprintf(stdout, " %g\n", A[i*2]);
fflush(stdout);
/* Implement some check for parameter quality */
for (i = 0; i < nexp; i++)
{
if (A[i*2] < 0 || A[i*2] > 1)
{
fprintf(stderr, "WARNING: ----------------------------------\n"
" | A coefficient does not lie within [0,1].\n"
" | This may or may not be a problem.\n"
" | Double check the quality of the fit!\n");
}
if (A[i*2+1] > 0)
{
fprintf(stderr, "WARNING: ----------------------------------\n"
" | One factor in the exponent is positive.\n"
" | This could be a problem if the coefficient\n"
" | is large. Double check the quality of the fit!\n");
}
}
if (A[i*2] < 0 || A[i*2] > 1)
{
fprintf(stderr, "WARNING: ----------------------------------\n"
" | The constant term does not lie within [0,1].\n"
" | This may or may not be a problem.\n"
" | Double check the quality of the fit!\n");
}
/* Sort the terms */
sorted = (nexp > 1) ? FALSE : TRUE;
while (!sorted)
{
sorted = TRUE;
for (i = 0; i < nexp-1; i++)
{
ddt[0] = A[i*2] * A[i*2+1];
ddt[1] = A[i*2+2] * A[i*2+3];
if ((bDerivative && (ddt[0] < 0 && ddt[1] < 0 && ddt[0] > ddt[1])) || /* Compare derivative at t=0... */
(!bDerivative && (A[i*2+1] > A[i*2+3]))) /* Or just the coefficient in the exponent */
{
sorted = FALSE;
a[0] = A[i*2]; /* coefficient */
a[1] = A[i*2+1]; /* parameter in the exponent */
A[i*2] = A[i*2+2];
A[i*2+1] = A[i*2+3];
A[i*2+2] = a[0];
A[i*2+3] = a[1];
}
}
}
/* Subtract the fastest component */
fprintf(stdout, "Fastest component is %g * exp(%g * t)\n"
"Subtracting fastest component from ACF.\n", A[0], A[1]);
for (i = 0; i < len; i++)
{
ct[i] = (ct[i] - A[0] * exp(A[1] * i*BD->tDelta)) / (1-A[0]);
}
sfree(guess);
sfree(A);
gsl_multifit_fdfsolver_free(s);
gsl_matrix_free(covar);
fflush(stdout);
#else
/* We have no gsl. */
fprintf(stderr, "Sorry, can't take away ballistic component without gsl. "
"Recompile using --with-gsl.\n");
return;
#endif /* HAVE_LIBGSL */
}
extern void dumpN(const real *e, const int nn, char *fn)
{
/* For debugging only */
int i;
FILE *f;
char standardName[] = "Nt.xvg";
if (fn == NULL)
{
fn = standardName;
}
f = fopen(fn, "w");
fprintf(f,
"@ type XY\n"
"@ xaxis label \"Frame\"\n"
"@ yaxis label \"N\"\n"
"@ s0 line type 3\n");
for (i = 0; i < nn; i++)
{
fprintf(f, "%-10i %-g\n", i, e[i]);
}
fclose(f);
}
static real* d2r(const double *d, const int nn)
{
real *r;
int i;
snew(r, nn);
for (i = 0; i < nn; i++)
{
r[i] = (real)d[i];
}
return r;
}
static void _patchBad(double *ct, int n, double dy)
{
/* Just do lin. interpolation for now. */
int i;
for (i = 1; i < n; i++)
{
ct[i] = ct[0]+i*dy;
}
}
static void patchBadPart(double *ct, int n)
{
_patchBad(ct, n, (ct[n] - ct[0])/n);
}
static void patchBadTail(double *ct, int n)
{
_patchBad(ct+1, n-1, ct[1]-ct[0]);
}
extern void fixGemACF(double *ct, int len)
{
int i, j, b, e;
gmx_bool bBad;
/* Let's separate two things:
* - identification of bad parts
* - patching of bad parts.
*/
b = 0; /* Start of a bad stretch */
e = 0; /* End of a bad stretch */
bBad = FALSE;
/* An acf of binary data must be one at t=0. */
if (abs(ct[0]-1.0) > 1e-6)
{
ct[0] = 1.0;
fprintf(stderr, "|ct[0]-1.0| = %1.6d. Setting ct[0] to 1.0.\n", abs(ct[0]-1.0));
}
for (i = 0; i < len; i++)
{
#ifdef HAS_ISFINITE
if (isfinite(ct[i]))
#elif defined(HAS__ISFINITE)
if (_isfinite(ct[i]))
#else
if (1)
#endif
{
if (!bBad)
{
/* Still on a good stretch. Proceed.*/
continue;
}
/* Patch up preceding bad stretch. */
if (i == (len-1))
{
/* It's the tail */
if (b <= 1)
{
gmx_fatal(FARGS, "The ACF is mostly NaN or Inf. Aborting.");
}
patchBadTail(&(ct[b-2]), (len-b)+1);
}
e = i;
patchBadPart(&(ct[b-1]), (e-b)+1);
bBad = FALSE;
}
else
{
if (!bBad)
{
b = i;
bBad = TRUE;
}
}
}
}
| {
"alphanum_fraction": 0.515555915,
"avg_line_length": 29.7449879711,
"ext": "c",
"hexsha": "d9e69984502dc1f6ad5855c63de2ac8aa62625fe",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2022-02-08T00:11:00.000Z",
"max_forks_repo_forks_event_min_datetime": "2022-02-08T00:11:00.000Z",
"max_forks_repo_head_hexsha": "ffa674110bcd15de851a8b6a703b4f4bc96fcd2d",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "farajilab/gifs_release",
"max_forks_repo_path": "gromacs-4.6.5/src/tools/geminate.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "ffa674110bcd15de851a8b6a703b4f4bc96fcd2d",
"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": "farajilab/gifs_release",
"max_issues_repo_path": "gromacs-4.6.5/src/tools/geminate.c",
"max_line_length": 135,
"max_stars_count": 2,
"max_stars_repo_head_hexsha": "ffa674110bcd15de851a8b6a703b4f4bc96fcd2d",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "farajilab/gifs_release",
"max_stars_repo_path": "gromacs-4.6.5/src/tools/geminate.c",
"max_stars_repo_stars_event_max_datetime": "2022-03-22T16:49:22.000Z",
"max_stars_repo_stars_event_min_datetime": "2022-03-04T18:56:08.000Z",
"num_tokens": 11263,
"size": 37092
} |
/* matrix/gsl_matrix_float.h
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman, Brian Gough
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#ifndef __GSL_MATRIX_FLOAT_H__
#define __GSL_MATRIX_FLOAT_H__
#include <stdlib.h>
#include <gsl/gsl_types.h>
#include <gsl/gsl_errno.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_EXPORT
gsl_matrix_float *
gsl_matrix_float_alloc (const size_t n1, const size_t n2);
GSL_EXPORT
gsl_matrix_float *
gsl_matrix_float_calloc (const size_t n1, const size_t n2);
GSL_EXPORT
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_EXPORT
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_EXPORT
gsl_vector_float *
gsl_vector_float_alloc_row_from_matrix (gsl_matrix_float * m,
const size_t i);
GSL_EXPORT
gsl_vector_float *
gsl_vector_float_alloc_col_from_matrix (gsl_matrix_float * m,
const size_t j);
GSL_EXPORT void gsl_matrix_float_free (gsl_matrix_float * m);
/* Views */
GSL_EXPORT
_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_EXPORT
_gsl_vector_float_view
gsl_matrix_float_row (gsl_matrix_float * m, const size_t i);
GSL_EXPORT
_gsl_vector_float_view
gsl_matrix_float_column (gsl_matrix_float * m, const size_t j);
GSL_EXPORT
_gsl_vector_float_view
gsl_matrix_float_diagonal (gsl_matrix_float * m);
GSL_EXPORT
_gsl_vector_float_view
gsl_matrix_float_subdiagonal (gsl_matrix_float * m, const size_t k);
GSL_EXPORT
_gsl_vector_float_view
gsl_matrix_float_superdiagonal (gsl_matrix_float * m, const size_t k);
GSL_EXPORT
_gsl_matrix_float_view
gsl_matrix_float_view_array (float * base,
const size_t n1,
const size_t n2);
GSL_EXPORT
_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_EXPORT
_gsl_matrix_float_view
gsl_matrix_float_view_vector (gsl_vector_float * v,
const size_t n1,
const size_t n2);
GSL_EXPORT
_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_EXPORT
_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_EXPORT
_gsl_vector_float_const_view
gsl_matrix_float_const_row (const gsl_matrix_float * m,
const size_t i);
GSL_EXPORT
_gsl_vector_float_const_view
gsl_matrix_float_const_column (const gsl_matrix_float * m,
const size_t j);
GSL_EXPORT
_gsl_vector_float_const_view
gsl_matrix_float_const_diagonal (const gsl_matrix_float * m);
GSL_EXPORT
_gsl_vector_float_const_view
gsl_matrix_float_const_subdiagonal (const gsl_matrix_float * m,
const size_t k);
GSL_EXPORT
_gsl_vector_float_const_view
gsl_matrix_float_const_superdiagonal (const gsl_matrix_float * m,
const size_t k);
GSL_EXPORT
_gsl_matrix_float_const_view
gsl_matrix_float_const_view_array (const float * base,
const size_t n1,
const size_t n2);
GSL_EXPORT
_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_EXPORT
_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_EXPORT
_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 */
GSL_EXPORT float gsl_matrix_float_get(const gsl_matrix_float * m, const size_t i, const size_t j);
GSL_EXPORT void gsl_matrix_float_set(gsl_matrix_float * m, const size_t i, const size_t j, const float x);
GSL_EXPORT float * gsl_matrix_float_ptr(gsl_matrix_float * m, const size_t i, const size_t j);
GSL_EXPORT const float * gsl_matrix_float_const_ptr(const gsl_matrix_float * m, const size_t i, const size_t j);
GSL_EXPORT void gsl_matrix_float_set_zero (gsl_matrix_float * m);
GSL_EXPORT void gsl_matrix_float_set_identity (gsl_matrix_float * m);
GSL_EXPORT void gsl_matrix_float_set_all (gsl_matrix_float * m, float x);
GSL_EXPORT int gsl_matrix_float_fread (FILE * stream, gsl_matrix_float * m) ;
GSL_EXPORT int gsl_matrix_float_fwrite (FILE * stream, const gsl_matrix_float * m) ;
GSL_EXPORT int gsl_matrix_float_fscanf (FILE * stream, gsl_matrix_float * m);
GSL_EXPORT int gsl_matrix_float_fprintf (FILE * stream, const gsl_matrix_float * m, const char * format);
GSL_EXPORT int gsl_matrix_float_memcpy(gsl_matrix_float * dest, const gsl_matrix_float * src);
GSL_EXPORT int gsl_matrix_float_swap(gsl_matrix_float * m1, gsl_matrix_float * m2);
GSL_EXPORT int gsl_matrix_float_swap_rows(gsl_matrix_float * m, const size_t i, const size_t j);
GSL_EXPORT int gsl_matrix_float_swap_columns(gsl_matrix_float * m, const size_t i, const size_t j);
GSL_EXPORT int gsl_matrix_float_swap_rowcol(gsl_matrix_float * m, const size_t i, const size_t j);
GSL_EXPORT int gsl_matrix_float_transpose (gsl_matrix_float * m);
GSL_EXPORT int gsl_matrix_float_transpose_memcpy (gsl_matrix_float * dest, const gsl_matrix_float * src);
GSL_EXPORT float gsl_matrix_float_max (const gsl_matrix_float * m);
GSL_EXPORT float gsl_matrix_float_min (const gsl_matrix_float * m);
GSL_EXPORT void gsl_matrix_float_minmax (const gsl_matrix_float * m, float * min_out, float * max_out);
GSL_EXPORT void gsl_matrix_float_max_index (const gsl_matrix_float * m, size_t * imax, size_t *jmax);
GSL_EXPORT void gsl_matrix_float_min_index (const gsl_matrix_float * m, size_t * imin, size_t *jmin);
GSL_EXPORT void gsl_matrix_float_minmax_index (const gsl_matrix_float * m, size_t * imin, size_t * jmin, size_t * imax, size_t * jmax);
GSL_EXPORT int gsl_matrix_float_isnull (const gsl_matrix_float * m);
GSL_EXPORT int gsl_matrix_float_add (gsl_matrix_float * a, const gsl_matrix_float * b);
GSL_EXPORT int gsl_matrix_float_sub (gsl_matrix_float * a, const gsl_matrix_float * b);
GSL_EXPORT int gsl_matrix_float_mul_elements (gsl_matrix_float * a, const gsl_matrix_float * b);
GSL_EXPORT int gsl_matrix_float_div_elements (gsl_matrix_float * a, const gsl_matrix_float * b);
GSL_EXPORT int gsl_matrix_float_scale (gsl_matrix_float * a, const double x);
GSL_EXPORT int gsl_matrix_float_add_constant (gsl_matrix_float * a, const double x);
GSL_EXPORT int gsl_matrix_float_add_diagonal (gsl_matrix_float * a, const double x);
/***********************************************************************/
/* The functions below are obsolete */
/***********************************************************************/
GSL_EXPORT int gsl_matrix_float_get_row(gsl_vector_float * v, const gsl_matrix_float * m, const size_t i);
GSL_EXPORT int gsl_matrix_float_get_col(gsl_vector_float * v, const gsl_matrix_float * m, const size_t j);
GSL_EXPORT int gsl_matrix_float_set_row(gsl_matrix_float * m, const size_t i, const gsl_vector_float * v);
GSL_EXPORT 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 */
#ifdef HAVE_INLINE
extern inline
float
gsl_matrix_float_get(const gsl_matrix_float * m, const size_t i, const size_t j)
{
#if GSL_RANGE_CHECK
if (i >= m->size1)
{
GSL_ERROR_VAL("first index out of range", GSL_EINVAL, 0) ;
}
else if (j >= m->size2)
{
GSL_ERROR_VAL("second index out of range", GSL_EINVAL, 0) ;
}
#endif
return m->data[i * m->tda + j] ;
}
extern inline
void
gsl_matrix_float_set(gsl_matrix_float * m, const size_t i, const size_t j, const float x)
{
#if GSL_RANGE_CHECK
if (i >= m->size1)
{
GSL_ERROR_VOID("first index out of range", GSL_EINVAL) ;
}
else if (j >= m->size2)
{
GSL_ERROR_VOID("second index out of range", GSL_EINVAL) ;
}
#endif
m->data[i * m->tda + j] = x ;
}
extern inline
float *
gsl_matrix_float_ptr(gsl_matrix_float * m, const size_t i, const size_t j)
{
#if GSL_RANGE_CHECK
if (i >= m->size1)
{
GSL_ERROR_NULL("first index out of range", GSL_EINVAL) ;
}
else if (j >= m->size2)
{
GSL_ERROR_NULL("second index out of range", GSL_EINVAL) ;
}
#endif
return (float *) (m->data + (i * m->tda + j)) ;
}
extern inline
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 (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.6791411572,
"avg_line_length": 33.8104956268,
"ext": "h",
"hexsha": "d1f912004027f52e84b7029e7142ad96415f9517",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "f6ed9b75408f7ce6100ed59b7754f745e59be152",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "dynaryu/vaws",
"max_forks_repo_path": "src/core/gsl/include/gsl/gsl_matrix_float.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "f6ed9b75408f7ce6100ed59b7754f745e59be152",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "dynaryu/vaws",
"max_issues_repo_path": "src/core/gsl/include/gsl/gsl_matrix_float.h",
"max_line_length": 135,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "f6ed9b75408f7ce6100ed59b7754f745e59be152",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "dynaryu/vaws",
"max_stars_repo_path": "src/core/gsl/include/gsl/gsl_matrix_float.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 2792,
"size": 11597
} |
/* vector/gsl_vector_short.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_SHORT_H__
#define __GSL_VECTOR_SHORT_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_short.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;
short *data;
gsl_block_short *block;
int owner;
}
gsl_vector_short;
typedef struct
{
gsl_vector_short vector;
} _gsl_vector_short_view;
typedef _gsl_vector_short_view gsl_vector_short_view;
typedef struct
{
gsl_vector_short vector;
} _gsl_vector_short_const_view;
typedef const _gsl_vector_short_const_view gsl_vector_short_const_view;
/* Allocation */
GSL_FUN gsl_vector_short *gsl_vector_short_alloc (const size_t n);
GSL_FUN gsl_vector_short *gsl_vector_short_calloc (const size_t n);
GSL_FUN gsl_vector_short *gsl_vector_short_alloc_from_block (gsl_block_short * b,
const size_t offset,
const size_t n,
const size_t stride);
GSL_FUN gsl_vector_short *gsl_vector_short_alloc_from_vector (gsl_vector_short * v,
const size_t offset,
const size_t n,
const size_t stride);
GSL_FUN void gsl_vector_short_free (gsl_vector_short * v);
/* Views */
GSL_FUN _gsl_vector_short_view
gsl_vector_short_view_array (short *v, size_t n);
GSL_FUN _gsl_vector_short_view
gsl_vector_short_view_array_with_stride (short *base,
size_t stride,
size_t n);
GSL_FUN _gsl_vector_short_const_view
gsl_vector_short_const_view_array (const short *v, size_t n);
GSL_FUN _gsl_vector_short_const_view
gsl_vector_short_const_view_array_with_stride (const short *base,
size_t stride,
size_t n);
GSL_FUN _gsl_vector_short_view
gsl_vector_short_subvector (gsl_vector_short *v,
size_t i,
size_t n);
GSL_FUN _gsl_vector_short_view
gsl_vector_short_subvector_with_stride (gsl_vector_short *v,
size_t i,
size_t stride,
size_t n);
GSL_FUN _gsl_vector_short_const_view
gsl_vector_short_const_subvector (const gsl_vector_short *v,
size_t i,
size_t n);
GSL_FUN _gsl_vector_short_const_view
gsl_vector_short_const_subvector_with_stride (const gsl_vector_short *v,
size_t i,
size_t stride,
size_t n);
/* Operations */
GSL_FUN void gsl_vector_short_set_zero (gsl_vector_short * v);
GSL_FUN void gsl_vector_short_set_all (gsl_vector_short * v, short x);
GSL_FUN int gsl_vector_short_set_basis (gsl_vector_short * v, size_t i);
GSL_FUN int gsl_vector_short_fread (FILE * stream, gsl_vector_short * v);
GSL_FUN int gsl_vector_short_fwrite (FILE * stream, const gsl_vector_short * v);
GSL_FUN int gsl_vector_short_fscanf (FILE * stream, gsl_vector_short * v);
GSL_FUN int gsl_vector_short_fprintf (FILE * stream, const gsl_vector_short * v,
const char *format);
GSL_FUN int gsl_vector_short_memcpy (gsl_vector_short * dest, const gsl_vector_short * src);
GSL_FUN int gsl_vector_short_reverse (gsl_vector_short * v);
GSL_FUN int gsl_vector_short_swap (gsl_vector_short * v, gsl_vector_short * w);
GSL_FUN int gsl_vector_short_swap_elements (gsl_vector_short * v, const size_t i, const size_t j);
GSL_FUN short gsl_vector_short_max (const gsl_vector_short * v);
GSL_FUN short gsl_vector_short_min (const gsl_vector_short * v);
GSL_FUN void gsl_vector_short_minmax (const gsl_vector_short * v, short * min_out, short * max_out);
GSL_FUN size_t gsl_vector_short_max_index (const gsl_vector_short * v);
GSL_FUN size_t gsl_vector_short_min_index (const gsl_vector_short * v);
GSL_FUN void gsl_vector_short_minmax_index (const gsl_vector_short * v, size_t * imin, size_t * imax);
GSL_FUN int gsl_vector_short_add (gsl_vector_short * a, const gsl_vector_short * b);
GSL_FUN int gsl_vector_short_sub (gsl_vector_short * a, const gsl_vector_short * b);
GSL_FUN int gsl_vector_short_mul (gsl_vector_short * a, const gsl_vector_short * b);
GSL_FUN int gsl_vector_short_div (gsl_vector_short * a, const gsl_vector_short * b);
GSL_FUN int gsl_vector_short_scale (gsl_vector_short * a, const double x);
GSL_FUN int gsl_vector_short_add_constant (gsl_vector_short * a, const double x);
GSL_FUN int gsl_vector_short_isnull (const gsl_vector_short * v);
GSL_FUN int gsl_vector_short_ispos (const gsl_vector_short * v);
GSL_FUN int gsl_vector_short_isneg (const gsl_vector_short * v);
GSL_FUN int gsl_vector_short_isnonneg (const gsl_vector_short * v);
GSL_FUN INLINE_DECL short gsl_vector_short_get (const gsl_vector_short * v, const size_t i);
GSL_FUN INLINE_DECL void gsl_vector_short_set (gsl_vector_short * v, const size_t i, short x);
GSL_FUN INLINE_DECL short * gsl_vector_short_ptr (gsl_vector_short * v, const size_t i);
GSL_FUN INLINE_DECL const short * gsl_vector_short_const_ptr (const gsl_vector_short * v, const size_t i);
#ifdef HAVE_INLINE
INLINE_FUN
short
gsl_vector_short_get (const gsl_vector_short * 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_short_set (gsl_vector_short * v, const size_t i, short 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
short *
gsl_vector_short_ptr (gsl_vector_short * 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 (short *) (v->data + i * v->stride);
}
INLINE_FUN
const short *
gsl_vector_short_const_ptr (const gsl_vector_short * 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 short *) (v->data + i * v->stride);
}
#endif /* HAVE_INLINE */
__END_DECLS
#endif /* __GSL_VECTOR_SHORT_H__ */
| {
"alphanum_fraction": 0.6689840224,
"avg_line_length": 34.4495798319,
"ext": "h",
"hexsha": "51218c5543da469d23cca218a90d3e32c5593f39",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "099b66cb1285d19955e953f916ec6c12c68f2242",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "berkus/music-cs",
"max_forks_repo_path": "deps/include/gsl/gsl_vector_short.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "099b66cb1285d19955e953f916ec6c12c68f2242",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "berkus/music-cs",
"max_issues_repo_path": "deps/include/gsl/gsl_vector_short.h",
"max_line_length": 107,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "099b66cb1285d19955e953f916ec6c12c68f2242",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "berkus/music-cs",
"max_stars_repo_path": "deps/include/gsl/gsl_vector_short.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1931,
"size": 8199
} |
#ifndef mooney_rivlin_h
#define mooney_rivlin_h
#include <petsc.h>
#include "../include/structs.h"
#ifndef PHYSICS_STRUCT_MR
#define PHYSICS_STRUCT_MR
typedef struct Physics_MR_ *Physics_MR;
struct Physics_MR_ {
// Material properties for MR
CeedScalar mu_1;
CeedScalar mu_2;
CeedScalar lambda;
};
#endif // PHYSICS_STRUCT_MR
// Create context object
PetscErrorCode PhysicsContext_MR(MPI_Comm comm, Ceed ceed, Units *units,
CeedQFunctionContext *ctx);
PetscErrorCode PhysicsSmootherContext_MR(MPI_Comm comm, Ceed ceed,
CeedQFunctionContext ctx, CeedQFunctionContext *ctx_smoother);
// Process physics options - Mooney-Rivlin
PetscErrorCode ProcessPhysics_MR(MPI_Comm comm, Physics_MR phys, Units units);
#endif // mooney_rivlin_h
| {
"alphanum_fraction": 0.7692307692,
"avg_line_length": 27.8571428571,
"ext": "h",
"hexsha": "1ca82e829413f2372b30349cb2602247f265fc61",
"lang": "C",
"max_forks_count": 41,
"max_forks_repo_forks_event_max_datetime": "2022-03-01T13:02:07.000Z",
"max_forks_repo_forks_event_min_datetime": "2017-12-27T22:35:13.000Z",
"max_forks_repo_head_hexsha": "aae8ce39fa1e28b745979a9cbffc67a790eb3f5e",
"max_forks_repo_licenses": [
"BSD-2-Clause"
],
"max_forks_repo_name": "AdelekeBankole/libCEED",
"max_forks_repo_path": "examples/solids/problems/mooney-rivlin.h",
"max_issues_count": 781,
"max_issues_repo_head_hexsha": "aae8ce39fa1e28b745979a9cbffc67a790eb3f5e",
"max_issues_repo_issues_event_max_datetime": "2022-03-29T21:34:34.000Z",
"max_issues_repo_issues_event_min_datetime": "2017-12-22T17:20:35.000Z",
"max_issues_repo_licenses": [
"BSD-2-Clause"
],
"max_issues_repo_name": "AdelekeBankole/libCEED",
"max_issues_repo_path": "examples/solids/problems/mooney-rivlin.h",
"max_line_length": 78,
"max_stars_count": 123,
"max_stars_repo_head_hexsha": "aae8ce39fa1e28b745979a9cbffc67a790eb3f5e",
"max_stars_repo_licenses": [
"BSD-2-Clause"
],
"max_stars_repo_name": "AdelekeBankole/libCEED",
"max_stars_repo_path": "examples/solids/problems/mooney-rivlin.h",
"max_stars_repo_stars_event_max_datetime": "2022-03-21T18:13:48.000Z",
"max_stars_repo_stars_event_min_datetime": "2018-01-29T02:04:05.000Z",
"num_tokens": 200,
"size": 780
} |
#ifndef SVGP_H
#define SVGP_H
#define M_PI 3.14159265358979323846
#include "Vector.h"
#include "Matrix.h"
#include "GaussianProcess.h"
#include <gsl/gsl_math.h>
class SVGP //: public GaussianProcess
{
protected:
Matrix X; ///< Samples (N x M)
Vector Y; ///< Output (N x 1)
int N; ///< Number of samples
int d;
// Kernel parameters
real noise_var;
real sig_var;
Vector scale_length;
/// SVI parameters
int num_inducing; ///< inducing inputs (J)
Matrix Z; ///< Hidden variables (N x J)
Vector u; ///< Global variables (N x 1) (targets)
// variational distribution parametrization
Matrix S;
Vector m;
real l; //step length
int samples; //not currently used.. but should be
Vector p_mean;
Matrix p_var;
Matrix Kmm;
Matrix Knm;
Matrix Kmn;
Matrix Knn;
Matrix invKmm;
Matrix K_tilde;
real Beta;
real KL;
real L;
Matrix currentSample;
Vector currentObservation;
//preferably these could be done in minibatches but only with single examples for now
//the example is repeated <subsamples> times as in Hoffman et al [2013]
virtual void local_update(); //updating Z (local/latent variables)
virtual void global_update(const Matrix& X_samples, const Vector& Y_samples); //updating m, S (which parametrizes q(u) and in turn gives global param u)
//virtual Vector optimize_Z(int max_iters);
virtual void init();
//virtual real LogLikelihood(double* data); //computes the likelihood given a Z*, to use for optimizing the position of Z
virtual void getSamples(Matrix& X_, Vector& Y_);
public:
SVGP(Matrix& X, Vector& Y, Matrix& Z, real noise_var, real sig_var, Vector scale_length, int samples);
//initializes Z through k-means
SVGP(Matrix& X, Vector& Y, int num_inducing, real noise_var, real sig_var, Vector scale_length, int samples);
virtual Matrix Kernel(const Matrix& A, const Matrix& B);
virtual void Prediction(const Vector& x, real& mean, real& var);
virtual void UpdateGaussianProcess(); //update
virtual void FullUpdateGaussianProcess();
virtual real LogLikelihood();
//virtual real LogLikelihood(const gsl_vector *v);
virtual void AddObservation(const Vector& x, const real& y);
virtual void AddObservation(const std::vector<Vector>& x, const std::vector<real>& y);
virtual void Clear();
};
#endif
| {
"alphanum_fraction": 0.6973518285,
"avg_line_length": 30.8961038961,
"ext": "h",
"hexsha": "1fe0f3e8d38fafd7a4c86095104f4d8d5289504c",
"lang": "C",
"max_forks_count": 4,
"max_forks_repo_forks_event_max_datetime": "2018-10-29T12:46:41.000Z",
"max_forks_repo_forks_event_min_datetime": "2018-01-14T14:23:18.000Z",
"max_forks_repo_head_hexsha": "ba974b17fbb46ac98960f31dea66115be470000e",
"max_forks_repo_licenses": [
"OLDAP-2.3"
],
"max_forks_repo_name": "revorg7/beliefbox",
"max_forks_repo_path": "src/SVI/svgp.h",
"max_issues_count": 2,
"max_issues_repo_head_hexsha": "ba974b17fbb46ac98960f31dea66115be470000e",
"max_issues_repo_issues_event_max_datetime": "2018-10-14T13:08:40.000Z",
"max_issues_repo_issues_event_min_datetime": "2015-12-02T19:47:57.000Z",
"max_issues_repo_licenses": [
"OLDAP-2.3"
],
"max_issues_repo_name": "revorg7/beliefbox",
"max_issues_repo_path": "src/SVI/svgp.h",
"max_line_length": 160,
"max_stars_count": 4,
"max_stars_repo_head_hexsha": "ba974b17fbb46ac98960f31dea66115be470000e",
"max_stars_repo_licenses": [
"OLDAP-2.3"
],
"max_stars_repo_name": "revorg7/beliefbox",
"max_stars_repo_path": "src/SVI/svgp.h",
"max_stars_repo_stars_event_max_datetime": "2018-01-07T10:54:36.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-12-02T23:16:44.000Z",
"num_tokens": 615,
"size": 2379
} |
#include "ccv.h"
#include "ccv_internal.h"
#if defined(HAVE_SSE2)
#include <xmmintrin.h>
#elif defined(HAVE_NEON)
#include <arm_neon.h>
#endif
#ifdef HAVE_GSL
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
#endif
#ifdef USE_DISPATCH
#include <dispatch/dispatch.h>
#endif
#include "3rdparty/sqlite3/sqlite3.h"
const ccv_scd_param_t ccv_scd_default_params = {
.interval = 5,
.min_neighbors = 1,
.step_through = 4,
.size = {
.width = 48,
.height = 48,
},
};
void ccv_scd(ccv_dense_matrix_t* a, ccv_dense_matrix_t** b, int type)
{
int ch = CCV_GET_CHANNEL(a->type);
assert(ch == 1 || ch == 3);
ccv_declare_derived_signature(sig, a->sig != 0, ccv_sign_with_literal("ccv_scd"), a->sig, CCV_EOF_SIGN);
// diagonal u v, and x, y, therefore 8 channels
ccv_dense_matrix_t* db = *b = ccv_dense_matrix_renew(*b, a->rows, a->cols, CCV_32F | 8, CCV_32F | 8, sig);
ccv_object_return_if_cached(, db);
ccv_dense_matrix_t* blur = 0;
ccv_blur(a, &blur, 0, 0.5); // do a modest blur, which suppresses noise
ccv_dense_matrix_t* dx = 0;
ccv_sobel(blur, &dx, 0, 1, 0);
ccv_dense_matrix_t* dy = 0;
ccv_sobel(blur, &dy, 0, 0, 1);
ccv_dense_matrix_t* du = 0;
ccv_sobel(blur, &du, 0, 1, 1);
ccv_dense_matrix_t* dv = 0;
ccv_sobel(blur, &dv, 0, -1, 1);
ccv_matrix_free(blur);
assert(CCV_GET_DATA_TYPE(dx->type) == CCV_GET_DATA_TYPE(dy->type));
assert(CCV_GET_DATA_TYPE(dy->type) == CCV_GET_DATA_TYPE(du->type));
assert(CCV_GET_DATA_TYPE(du->type) == CCV_GET_DATA_TYPE(dv->type));
assert(CCV_GET_CHANNEL(dx->type) == CCV_GET_CHANNEL(dy->type));
assert(CCV_GET_CHANNEL(dy->type) == CCV_GET_CHANNEL(du->type));
assert(CCV_GET_CHANNEL(du->type) == CCV_GET_CHANNEL(dv->type));
// this is a naive unoptimized implementation yet
int i, j, k;
unsigned char* dx_ptr = dx->data.u8;
unsigned char* dy_ptr = dy->data.u8;
unsigned char* du_ptr = du->data.u8;
unsigned char* dv_ptr = dv->data.u8;
float* dbp = db->data.f32;
if (ch == 1)
{
#define for_block(_, _for_get) \
for (i = 0; i < a->rows; i++) \
{ \
for (j = 0; j < a->cols; j++) \
{ \
float fdx = _for_get(dx_ptr, j, 0), fdy = _for_get(dy_ptr, j, 0); \
float fdu = _for_get(du_ptr, j, 0), fdv = _for_get(dv_ptr, j, 0); \
float adx = fabsf(fdx), ady = fabsf(fdy); \
float adu = fabsf(fdu), adv = fabsf(fdv); \
dbp[0] = fdx, dbp[1] = fdy; \
dbp[2] = fdu, dbp[3] = fdv; \
dbp[4] = adx, dbp[5] = ady; \
dbp[6] = adu, dbp[7] = adv; \
dbp += 8; \
} \
dx_ptr += dx->step; \
dy_ptr += dy->step; \
du_ptr += du->step; \
dv_ptr += dv->step; \
}
ccv_matrix_getter(dx->type, for_block);
#undef for_block
} else {
#define for_block(_, _for_get) \
for (i = 0; i < a->rows; i++) \
{ \
for (j = 0; j < a->cols; j++) \
{ \
float fdx = _for_get(dx_ptr, j * ch, 0), fdy = _for_get(dy_ptr, j * ch, 0); \
float fdu = _for_get(du_ptr, j * ch, 0), fdv = _for_get(dv_ptr, j * ch, 0); \
float adx = fabsf(fdx), ady = fabsf(fdy); \
float adu = fabsf(fdu), adv = fabsf(fdv); \
/* select the strongest ones from all the channels */ \
for (k = 1; k < ch; k++) \
{ \
if (fabsf((float)_for_get(dx_ptr, j * ch + k, 0)) > adx) \
{ \
fdx = _for_get(dx_ptr, j * ch + k, 0); \
adx = fabsf(fdx); \
} \
if (fabsf((float)_for_get(dy_ptr, j * ch + k, 0)) > ady) \
{ \
fdy = _for_get(dy_ptr, j * ch + k, 0); \
ady = fabsf(fdy); \
} \
if (fabsf((float)_for_get(du_ptr, j * ch + k, 0)) > adu) \
{ \
fdu = _for_get(du_ptr, j * ch + k, 0); \
adu = fabsf(fdu); \
} \
if (fabsf((float)_for_get(dv_ptr, j * ch + k, 0)) > adv) \
{ \
fdv = _for_get(dv_ptr, j * ch + k, 0); \
adv = fabsf(fdv); \
} \
} \
dbp[0] = fdx, dbp[1] = fdy; \
dbp[2] = fdu, dbp[3] = fdv; \
dbp[4] = adx, dbp[5] = ady; \
dbp[6] = adu, dbp[7] = adv; \
dbp += 8; \
} \
dx_ptr += dx->step; \
dy_ptr += dy->step; \
du_ptr += du->step; \
dv_ptr += dv->step; \
}
ccv_matrix_getter(dx->type, for_block);
#undef for_block
}
ccv_matrix_free(dx);
ccv_matrix_free(dy);
ccv_matrix_free(du);
ccv_matrix_free(dv);
}
#if defined(HAVE_SSE2)
static inline void _ccv_scd_run_feature_at_sse2(float* at, int cols, ccv_scd_stump_feature_t* feature, __m128 surf[8])
{
int i;
// extract feature
for (i = 0; i < 4; i++)
{
__m128 d0 = _mm_loadu_ps(at + (cols * feature->sy[i] + feature->sx[i]) * 8);
__m128 d1 = _mm_loadu_ps(at + 4 + (cols * feature->sy[i] + feature->sx[i]) * 8);
__m128 du0 = _mm_loadu_ps(at + (cols * feature->dy[i] + feature->sx[i]) * 8);
__m128 du1 = _mm_loadu_ps(at + 4 + (cols * feature->dy[i] + feature->sx[i]) * 8);
__m128 dv0 = _mm_loadu_ps(at + (cols * feature->sy[i] + feature->dx[i]) * 8);
__m128 dv1 = _mm_loadu_ps(at + 4 + (cols * feature->sy[i] + feature->dx[i]) * 8);
__m128 duv0 = _mm_loadu_ps(at + (cols * feature->dy[i] + feature->dx[i]) * 8);
__m128 duv1 = _mm_loadu_ps(at + 4 + (cols * feature->dy[i] + feature->dx[i]) * 8);
surf[i * 2] = _mm_sub_ps(_mm_add_ps(duv0, d0), _mm_add_ps(du0, dv0));
surf[i * 2 + 1] = _mm_sub_ps(_mm_add_ps(duv1, d1), _mm_add_ps(du1, dv1));
}
// L2Hys normalization
__m128 v0 = _mm_add_ps(_mm_mul_ps(surf[0], surf[0]), _mm_mul_ps(surf[1], surf[1]));
__m128 v1 = _mm_add_ps(_mm_mul_ps(surf[2], surf[2]), _mm_mul_ps(surf[3], surf[3]));
__m128 v2 = _mm_add_ps(_mm_mul_ps(surf[4], surf[4]), _mm_mul_ps(surf[5], surf[5]));
__m128 v3 = _mm_add_ps(_mm_mul_ps(surf[6], surf[6]), _mm_mul_ps(surf[7], surf[7]));
v0 = _mm_add_ps(v0, v1);
v2 = _mm_add_ps(v2, v3);
union {
float f[4];
__m128 p;
} vx;
vx.p = _mm_add_ps(v0, v2);
v0 = _mm_set1_ps(1.0 / (sqrtf(vx.f[0] + vx.f[1] + vx.f[2] + vx.f[3]) + 1e-6));
static float thlf = -2.0 / 5.65685424949; // -sqrtf(32)
static float thuf = 2.0 / 5.65685424949; // sqrtf(32)
const __m128 thl = _mm_set1_ps(thlf);
const __m128 thu = _mm_set1_ps(thuf);
for (i = 0; i < 8; i++)
{
surf[i] = _mm_mul_ps(surf[i], v0);
surf[i] = _mm_min_ps(surf[i], thu);
surf[i] = _mm_max_ps(surf[i], thl);
}
__m128 u0 = _mm_add_ps(_mm_mul_ps(surf[0], surf[0]), _mm_mul_ps(surf[1], surf[1]));
__m128 u1 = _mm_add_ps(_mm_mul_ps(surf[2], surf[2]), _mm_mul_ps(surf[3], surf[3]));
__m128 u2 = _mm_add_ps(_mm_mul_ps(surf[4], surf[4]), _mm_mul_ps(surf[5], surf[5]));
__m128 u3 = _mm_add_ps(_mm_mul_ps(surf[6], surf[6]), _mm_mul_ps(surf[7], surf[7]));
u0 = _mm_add_ps(u0, u1);
u2 = _mm_add_ps(u2, u3);
union {
float f[4];
__m128 p;
} ux;
ux.p = _mm_add_ps(u0, u2);
u0 = _mm_set1_ps(1.0 / (sqrtf(ux.f[0] + ux.f[1] + ux.f[2] + ux.f[3]) + 1e-6));
for (i = 0; i < 8; i++)
surf[i] = _mm_mul_ps(surf[i], u0);
}
#else
static inline void _ccv_scd_run_feature_at(float* at, int cols, ccv_scd_stump_feature_t* feature, float surf[32])
{
int i, j;
// extract feature
for (i = 0; i < 4; i++)
{
float* d = at + (cols * feature->sy[i] + feature->sx[i]) * 8;
float* du = at + (cols * feature->dy[i] + feature->sx[i]) * 8;
float* dv = at + (cols * feature->sy[i] + feature->dx[i]) * 8;
float* duv = at + (cols * feature->dy[i] + feature->dx[i]) * 8;
for (j = 0; j < 8; j++)
surf[i * 8 + j] = duv[j] - du[j] + d[j] - dv[j];
}
// L2Hys normalization
float v = 0;
for (i = 0; i < 32; i++)
v += surf[i] * surf[i];
v = 1.0 / (sqrtf(v) + 1e-6);
static float theta = 2.0 / 5.65685424949; // sqrtf(32)
float u = 0;
for (i = 0; i < 32; i++)
{
surf[i] = surf[i] * v;
surf[i] = ccv_clamp(surf[i], -theta, theta);
u += surf[i] * surf[i];
}
u = 1.0 / (sqrtf(u) + 1e-6);
for (i = 0; i < 32; i++)
surf[i] = surf[i] * u;
}
#endif
#ifdef HAVE_GSL
static ccv_array_t* _ccv_scd_collect_negatives(gsl_rng* rng, ccv_size_t size, ccv_array_t* hard_mine, int total, int grayscale)
{
ccv_array_t* negatives = ccv_array_new(ccv_compute_dense_matrix_size(size.height, size.width, CCV_8U | (grayscale ? CCV_C1 : CCV_C3)), total, 0);
int i, j, k;
for (i = 0; i < total;)
{
FLUSH(CCV_CLI_INFO, " - collect negatives %d%% (%d / %d)", (i + 1) * 100 / total, i + 1, total);
double ratio = (double)(total - i) / hard_mine->rnum;
for (j = 0; j < hard_mine->rnum && i < total; j++)
{
ccv_file_info_t* file_info = (ccv_file_info_t*)ccv_array_get(hard_mine, j);
ccv_dense_matrix_t* image = 0;
ccv_read(file_info->filename, &image, CCV_IO_ANY_FILE | (grayscale ? CCV_IO_GRAY : CCV_IO_RGB_COLOR));
if (image == 0)
{
PRINT(CCV_CLI_ERROR, "\n - %s: cannot be open, possibly corrupted\n", file_info->filename);
continue;
}
double max_scale_ratio = ccv_min((double)image->rows / size.height, (double)image->cols / size.width);
if (max_scale_ratio <= 0.5) // too small to be interesting
continue;
for (k = 0; k < ratio; k++)
if (k < (int)ratio || gsl_rng_uniform(rng) <= ccv_max(0.1, ratio - (int)ratio))
{
FLUSH(CCV_CLI_INFO, " - collect negatives %d%% (%d / %d)", (i + 1) * 100 / total, i + 1, total);
ccv_rect_t rect;
double scale_ratio = gsl_rng_uniform(rng) * (max_scale_ratio - 0.5) + 0.5;
rect.width = ccv_min(image->cols, (int)(size.width * scale_ratio + 0.5));
rect.height = ccv_min(image->rows, (int)(size.height * scale_ratio + 0.5));
rect.x = gsl_rng_uniform_int(rng, ccv_max(image->cols - rect.width + 1, 1));
rect.y = gsl_rng_uniform_int(rng, ccv_max(image->rows - rect.height + 1, 1));
ccv_dense_matrix_t* sliced = 0;
ccv_slice(image, (ccv_matrix_t**)&sliced, 0, rect.y, rect.x, rect.height, rect.width);
ccv_dense_matrix_t* b = 0;
if (size.width > rect.width)
ccv_resample(sliced, &b, 0, size.height, size.width, CCV_INTER_CUBIC);
else
ccv_resample(sliced, &b, 0, size.height, size.width, CCV_INTER_AREA);
ccv_matrix_free(sliced);
b->sig = 0;
// this leveraged the fact that because I know the ccv_dense_matrix_t is continuous in memory
ccv_array_push(negatives, b);
ccv_matrix_free(b);
++i;
if (i >= total)
break;
}
ccv_matrix_free(image);
}
}
PRINT(CCV_CLI_INFO, "\n");
ccv_make_array_immutable(negatives);
return negatives;
}
static ccv_array_t*_ccv_scd_collect_positives(ccv_size_t size, ccv_array_t* posfiles, int grayscale)
{
ccv_array_t* positives = ccv_array_new(ccv_compute_dense_matrix_size(size.height, size.width, CCV_8U | (grayscale ? CCV_C1 : CCV_C3)), posfiles->rnum, 0);
int i;
for (i = 0; i < posfiles->rnum; i++)
{
FLUSH(CCV_CLI_INFO, " - collect positives %d%% (%d / %d)", (i + 1) * 100 / posfiles->rnum, i + 1, posfiles->rnum);
ccv_file_info_t* file_info = (ccv_file_info_t*)ccv_array_get(posfiles, i);
ccv_dense_matrix_t* a = 0;
ccv_read(file_info->filename, &a, CCV_IO_ANY_FILE | (grayscale ? CCV_IO_GRAY : CCV_IO_RGB_COLOR));
a->sig = 0;
ccv_array_push(positives, a);
ccv_matrix_free(a);
}
PRINT(CCV_CLI_INFO, "\n");
ccv_make_array_immutable(positives);
return positives;
}
static ccv_array_t* _ccv_scd_stump_features(ccv_size_t base, int range_through, int step_through, ccv_size_t size)
{
ccv_array_t* features = ccv_array_new(sizeof(ccv_scd_stump_feature_t), 64, 0);
int x, y, w, h;
for (w = base.width; w <= size.width; w += range_through)
if (w % 4 == 0) // only allow 4:1
{
h = w / 4;
for (x = 0; x <= size.width - w; x += step_through)
for (y = 0; y <= size.height - h; y += step_through)
{
// 4x1 feature
ccv_scd_stump_feature_t feature;
feature.sx[0] = x;
feature.dx[0] = x + (w / 4);
feature.sx[1] = x + (w / 4);
feature.dx[1] = x + 2 * (w / 4);
feature.sx[2] = x + 2 * (w / 4);
feature.dx[2] = x + 3 * (w / 4);
feature.sx[3] = x + 3 * (w / 4);
feature.dx[3] = x + w;
feature.sy[0] = feature.sy[1] = feature.sy[2] = feature.sy[3] = y;
feature.dy[0] = feature.dy[1] = feature.dy[2] = feature.dy[3] = y + h;
ccv_array_push(features, &feature);
}
}
for (h = base.height; h <= size.height; h += range_through)
if (h % 4 == 0) // only allow 1:4
{
w = h / 4;
for (x = 0; x <= size.width - w; x += step_through)
for (y = 0; y <= size.height - h; y += step_through)
{
// 1x4 feature
ccv_scd_stump_feature_t feature;
feature.sx[0] = feature.sx[1] = feature.sx[2] = feature.sx[3] = x;
feature.dx[0] = feature.dx[1] = feature.dx[2] = feature.dx[3] = x + w;
feature.sy[0] = y;
feature.dy[0] = y + (h / 4);
feature.sy[1] = y + (h / 4);
feature.dy[1] = y + 2 * (h / 4);
feature.sy[2] = y + 2 * (h / 4);
feature.dy[2] = y + 3 * (h / 4);
feature.sy[3] = y + 3 * (h / 4);
feature.dy[3] = y + h;
ccv_array_push(features, &feature);
}
}
for (w = base.width; w <= size.width; w += range_through)
for (h = base.height; h <= size.height; h += range_through)
for (x = 0; x <= size.width - w; x += step_through)
for (y = 0; y <= size.height - h; y += step_through)
if (w % 2 == 0 && h % 2 == 0 &&
(w == h || w == h * 2 || w * 2 == h || w * 2 == h * 3 || w * 3 == h * 2)) // allow 1:1, 1:2, 2:1, 2:3, 3:2
{
// 2x2 feature
ccv_scd_stump_feature_t feature;
feature.sx[0] = feature.sx[1] = x;
feature.dx[0] = feature.dx[1] = x + (w / 2);
feature.sy[0] = feature.sy[2] = y;
feature.dy[0] = feature.dy[2] = y + (h / 2);
feature.sx[2] = feature.sx[3] = x + (w / 2);
feature.dx[2] = feature.dx[3] = x + w;
feature.sy[1] = feature.sy[3] = y + (h / 2);
feature.dy[1] = feature.dy[3] = y + h;
ccv_array_push(features, &feature);
}
return features;
}
typedef struct {
double value;
int index;
} ccv_scd_value_index_t;
#define more_than(s1, s2, aux) ((s1).value >= (s2).value)
static CCV_IMPLEMENT_QSORT(_ccv_scd_value_index_sortby_value, ccv_scd_value_index_t, more_than)
#undef more_than
#define less_than(s1, s2, aux) ((s1).index < (s2).index)
static CCV_IMPLEMENT_QSORT(_ccv_scd_value_index_sortby_index, ccv_scd_value_index_t, less_than)
#undef less_than
static float* _ccv_scd_get_surf_at(float* fv, int feature_no, int example_no, int positive_count, int negative_count)
{
return fv + ((off_t)example_no + feature_no * (positive_count + negative_count)) * 32;
}
static void _ccv_scd_precompute_feature_vectors(const ccv_array_t* features, const ccv_array_t* positives, const ccv_array_t* negatives, float* fv)
{
parallel_for(i, positives->rnum) {
int j;
if ((i + 1) % 4031 == 1)
FLUSH(CCV_CLI_INFO, " - precompute feature vectors of example %d / %d over %d features", (int)(i + 1), positives->rnum + negatives->rnum, features->rnum);
ccv_dense_matrix_t* a = (ccv_dense_matrix_t*)ccv_array_get(positives, i);
a->data.u8 = (unsigned char*)(a + 1);
ccv_dense_matrix_t* b = 0;
ccv_scd(a, &b, 0);
ccv_dense_matrix_t* sat = 0;
ccv_sat(b, &sat, 0, CCV_PADDING_ZERO);
ccv_matrix_free(b);
for (j = 0; j < features->rnum; j++)
{
ccv_scd_stump_feature_t* feature = (ccv_scd_stump_feature_t*)ccv_array_get(features, j);
// save to fv
#if defined(HAVE_SSE2)
_ccv_scd_run_feature_at_sse2(sat->data.f32, sat->cols, feature, (__m128*)_ccv_scd_get_surf_at(fv, j, i, positives->rnum, negatives->rnum));
#else
_ccv_scd_run_feature_at(sat->data.f32, sat->cols, feature, _ccv_scd_get_surf_at(fv, j, i, positives->rnum, negatives->rnum));
#endif
}
ccv_matrix_free(sat);
} parallel_endfor
parallel_for(i, negatives->rnum) {
int j;
if ((i + 1) % 731 == 1 || (i + 1) == negatives->rnum)
FLUSH(CCV_CLI_INFO, " - precompute feature vectors of example %d / %d over %d features", (int)(i + positives->rnum + 1), positives->rnum + negatives->rnum, features->rnum);
ccv_dense_matrix_t* a = (ccv_dense_matrix_t*)ccv_array_get(negatives, i);
a->data.u8 = (unsigned char*)(a + 1);
ccv_dense_matrix_t* b = 0;
ccv_scd(a, &b, 0);
ccv_dense_matrix_t* sat = 0;
ccv_sat(b, &sat, 0, CCV_PADDING_ZERO);
ccv_matrix_free(b);
for (j = 0; j < features->rnum; j++)
{
ccv_scd_stump_feature_t* feature = (ccv_scd_stump_feature_t*)ccv_array_get(features, j);
// save to fv
#if defined(HAVE_SSE2)
_ccv_scd_run_feature_at_sse2(sat->data.f32, sat->cols, feature, (__m128*)_ccv_scd_get_surf_at(fv, j, i + positives->rnum, positives->rnum, negatives->rnum));
#else
_ccv_scd_run_feature_at(sat->data.f32, sat->cols, feature, _ccv_scd_get_surf_at(fv, j, i + positives->rnum, positives->rnum, negatives->rnum));
#endif
}
ccv_matrix_free(sat);
} parallel_endfor
}
typedef struct {
int feature_no;
double C;
ccv_scd_value_index_t* pwidx;
ccv_scd_value_index_t* nwidx;
int positive_count;
int negative_count;
int active_positive_count;
int active_negative_count;
float* fv;
} ccv_loss_minimize_context_t;
static int _ccv_scd_stump_feature_gentle_adaboost_loss(const ccv_dense_matrix_t* x, double* f, ccv_dense_matrix_t* df, void* data)
{
ccv_loss_minimize_context_t* context = (ccv_loss_minimize_context_t*)data;
int i, j;
float loss = 0;
float* d = df->data.f32;
for (i = 0; i < 32; i++)
{
loss += context->C * fabs(x->data.f32[i]);
d[i] = x->data.f32[i] > 0 ? context->C : -context->C;
}
d[32] = 0;
float* surf = _ccv_scd_get_surf_at(context->fv, context->feature_no, 0, context->positive_count, context->negative_count);
for (i = 0; i < context->active_positive_count; i++)
{
float* cur_surf = surf + (off_t)(context->pwidx[i].index) * 32;
float v = x->data.f32[32];
for (j = 0; j < 32; j++)
v += cur_surf[j] * x->data.f32[j];
v = expf(v);
float tanh = (v - 1) / (v + 1);
loss += context->pwidx[i].value * (1.0 - tanh) * (1.0 - tanh);
float dv = -8.0 * context->pwidx[i].value * v / ((1.0 + v) * (1.0 + v) * (1.0 + v));
for (j = 0; j < 32; j++)
d[j] += dv * cur_surf[j];
d[32] += dv;
}
for (i = 0; i < context->active_negative_count; i++)
{
float* cur_surf = surf + (off_t)(context->nwidx[i].index + context->positive_count) * 32;
float v = x->data.f32[32];
for (j = 0; j < 32; j++)
v += cur_surf[j] * x->data.f32[j];
v = expf(v);
float tanh = (v - 1) / (v + 1);
loss += context->nwidx[i].value * (-1.0 - tanh) * (-1.0 - tanh);
float dv = 8.0 * context->nwidx[i].value * v * v / ((1.0 + v) * (1.0 + v) * (1.0 + v));
for (j = 0; j < 32; j++)
d[j] += dv * cur_surf[j];
d[32] += dv;
}
f[0] = loss;
return 0;
}
static int _ccv_scd_weight_trimming(ccv_scd_value_index_t* idx, int count, double weight_trimming)
{
int active_count = count;
int i;
double w = 0;
for (i = 0; i < count; i++)
{
w += idx[i].value;
if (w >= weight_trimming)
{
active_count = i + 1;
break;
}
}
assert(active_count > 0);
for (i = active_count; i < count; i++)
if (idx[i - 1].value == idx[i].value) // for exactly the same weight, we skip
active_count = i + 1;
else
break;
return active_count;
}
static void _ccv_scd_stump_feature_supervised_train(gsl_rng* rng, ccv_array_t* features, int positive_count, int negative_count, double* pw, double* nw, float* fv, double C, double weight_trimming)
{
int i;
ccv_scd_value_index_t* pwidx = (ccv_scd_value_index_t*)ccmalloc(sizeof(ccv_scd_value_index_t) * positive_count);
ccv_scd_value_index_t* nwidx = (ccv_scd_value_index_t*)ccmalloc(sizeof(ccv_scd_value_index_t) * negative_count);
for (i = 0; i < positive_count; i++)
pwidx[i].value = pw[i], pwidx[i].index = i;
for (i = 0; i < negative_count; i++)
nwidx[i].value = nw[i], nwidx[i].index = i;
_ccv_scd_value_index_sortby_value(pwidx, positive_count, 0);
_ccv_scd_value_index_sortby_value(nwidx, negative_count, 0);
int active_positive_count = _ccv_scd_weight_trimming(pwidx, positive_count, weight_trimming * 0.5); // the sum of positive weights is 0.5
int active_negative_count = _ccv_scd_weight_trimming(nwidx, negative_count, weight_trimming * 0.5); // the sum of negative weights is 0.5
_ccv_scd_value_index_sortby_index(pwidx, active_positive_count, 0);
_ccv_scd_value_index_sortby_index(nwidx, active_negative_count, 0);
parallel_for(i, features->rnum) {
if ((i + 1) % 31 == 1 || (i + 1) == features->rnum)
FLUSH(CCV_CLI_INFO, " - supervised train feature %d / %d with logistic regression, active set {%d, %d}", (int)(i + 1), features->rnum, active_positive_count, active_negative_count);
ccv_scd_stump_feature_t* feature = (ccv_scd_stump_feature_t*)ccv_array_get(features, i);
ccv_loss_minimize_context_t context = {
.feature_no = i,
.C = C,
.positive_count = positive_count,
.negative_count = negative_count,
.active_positive_count = active_positive_count,
.active_negative_count = active_negative_count,
.pwidx = pwidx,
.nwidx = nwidx,
.fv = fv,
};
ccv_dense_matrix_t* x = ccv_dense_matrix_new(1, 33, CCV_32F | CCV_C1, 0, 0);
int j;
for (j = 0; j < 33; j++)
x->data.f32[j] = gsl_rng_uniform_pos(rng) * 2 - 1.0;
ccv_minimize(x, 10, 1.0, _ccv_scd_stump_feature_gentle_adaboost_loss, ccv_minimize_default_params, &context);
for (j = 0; j < 32; j++)
feature->w[j] = x->data.f32[j];
feature->bias = x->data.f32[32];
ccv_matrix_free(x);
} parallel_endfor
ccfree(pwidx);
ccfree(nwidx);
}
static double _ccv_scd_auc(double* s, int posnum, int negnum)
{
ccv_scd_value_index_t* sidx = (ccv_scd_value_index_t*)ccmalloc(sizeof(ccv_scd_value_index_t) * (posnum + negnum));
int i;
for (i = 0; i < posnum + negnum; i++)
sidx[i].value = s[i], sidx[i].index = i;
_ccv_scd_value_index_sortby_value(sidx, posnum + negnum, 0);
int fp = 0, tp = 0, fp_prev = 0, tp_prev = 0;
double a = 0;
double f_prev = -DBL_MAX;
for (i = 0; i < posnum + negnum; i++)
{
if (sidx[i].value != f_prev)
{
a += (double)(fp - fp_prev) * (tp + tp_prev) * 0.5;
f_prev = sidx[i].value;
fp_prev = fp;
tp_prev = tp;
}
if (sidx[i].index < posnum)
++tp;
else
++fp;
}
ccfree(sidx);
a += (double)(negnum - fp_prev) * (posnum + tp_prev) * 0.5;
return a / ((double)posnum * negnum);
}
static int _ccv_scd_find_match_feature(ccv_scd_stump_feature_t* value, ccv_array_t* features)
{
int i;
for (i = 0; i < features->rnum; i++)
{
ccv_scd_stump_feature_t* feature = (ccv_scd_stump_feature_t*)ccv_array_get(features, i);
if (feature->sx[0] == value->sx[0] && feature->sy[0] == value->sy[0] &&
feature->dx[0] == value->dx[0] && feature->dy[0] == value->dy[0] &&
feature->sx[1] == value->sx[1] && feature->sy[1] == value->sy[1] &&
feature->dx[1] == value->dx[1] && feature->dy[1] == value->dy[1] &&
feature->sx[2] == value->sx[2] && feature->sy[2] == value->sy[2] &&
feature->dx[2] == value->dx[2] && feature->dy[2] == value->dy[2] &&
feature->sx[3] == value->sx[3] && feature->sy[3] == value->sy[3] &&
feature->dx[3] == value->dx[3] && feature->dy[3] == value->dy[3])
return i;
}
return -1;
}
static int _ccv_scd_best_feature_gentle_adaboost(double* s, ccv_array_t* features, double* pw, double* nw, int positive_count, int negative_count, float* fv)
{
int i;
double* error_rate = (double*)cccalloc(features->rnum, sizeof(double));
assert(positive_count + negative_count > 0);
parallel_for(i, features->rnum) {
int j, k;
if ((i + 1) % 331 == 1 || (i + 1) == features->rnum)
FLUSH(CCV_CLI_INFO, " - go through %d / %d (%.1f%%) for adaboost", (int)(i + 1), features->rnum, (float)(i + 1) * 100 / features->rnum);
ccv_scd_stump_feature_t* feature = (ccv_scd_stump_feature_t*)ccv_array_get(features, i);
for (j = 0; j < positive_count; j++)
{
float* surf = _ccv_scd_get_surf_at(fv, i, j, positive_count, negative_count);
float v = feature->bias;
for (k = 0; k < 32; k++)
v += surf[k] * feature->w[k];
v = expf(v);
v = (v - 1) / (v + 1); // probability
error_rate[i] += pw[j] * (1 - v) * (1 - v);
}
for (j = 0; j < negative_count; j++)
{
float* surf = _ccv_scd_get_surf_at(fv, i, j + positive_count, positive_count, negative_count);
float v = feature->bias;
for (k = 0; k < 32; k++)
v += surf[k] * feature->w[k];
v = expf(v);
v = (v - 1) / (v + 1); // probability
error_rate[i] += nw[j] * (-1 - v) * (-1 - v);
}
} parallel_endfor
double min_error_rate = error_rate[0];
int j = 0;
for (i = 1; i < features->rnum; i++)
if (error_rate[i] < min_error_rate)
{
min_error_rate = error_rate[i];
j = i;
}
ccfree(error_rate);
return j;
}
static float _ccv_scd_threshold_at_hit_rate(double* s, int posnum, int negnum, float hit_rate, float* tp_out, float* fp_out)
{
ccv_scd_value_index_t* psidx = (ccv_scd_value_index_t*)ccmalloc(sizeof(ccv_scd_value_index_t) * posnum);
int i;
for (i = 0; i < posnum; i++)
psidx[i].value = s[i], psidx[i].index = i;
_ccv_scd_value_index_sortby_value(psidx, posnum, 0);
float threshold = psidx[(int)((posnum - 0.5) * hit_rate - 0.5)].value - 1e-6;
ccfree(psidx);
int tp = 0;
for (i = 0; i < posnum; i++)
if (s[i] > threshold)
++tp;
int fp = 0;
for (i = 0; i < negnum; i++)
if (s[i + posnum] > threshold)
++fp;
if (tp_out)
*tp_out = (float)tp / posnum;
if (fp_out)
*fp_out = (float)fp / negnum;
return threshold;
}
static int _ccv_scd_classifier_cascade_pass(ccv_scd_classifier_cascade_t* cascade, ccv_dense_matrix_t* a)
{
#if defined(HAVE_SSE2)
__m128 surf[8];
#else
float surf[32];
#endif
ccv_dense_matrix_t* b = 0;
ccv_scd(a, &b, 0);
ccv_dense_matrix_t* sat = 0;
ccv_sat(b, &sat, 0, CCV_PADDING_ZERO);
ccv_matrix_free(b);
int pass = 1;
int i, j;
for (i = 0; i < cascade->count; i++)
{
ccv_scd_stump_classifier_t* classifier = cascade->classifiers + i;
float v = 0;
for (j = 0; j < classifier->count; j++)
{
ccv_scd_stump_feature_t* feature = classifier->features + j;
#if defined(HAVE_SSE2)
_ccv_scd_run_feature_at_sse2(sat->data.f32, sat->cols, feature, surf);
__m128 u0 = _mm_add_ps(_mm_mul_ps(surf[0], _mm_loadu_ps(feature->w)), _mm_mul_ps(surf[1], _mm_loadu_ps(feature->w + 4)));
__m128 u1 = _mm_add_ps(_mm_mul_ps(surf[2], _mm_loadu_ps(feature->w + 8)), _mm_mul_ps(surf[3], _mm_loadu_ps(feature->w + 12)));
__m128 u2 = _mm_add_ps(_mm_mul_ps(surf[4], _mm_loadu_ps(feature->w + 16)), _mm_mul_ps(surf[5], _mm_loadu_ps(feature->w + 20)));
__m128 u3 = _mm_add_ps(_mm_mul_ps(surf[6], _mm_loadu_ps(feature->w + 24)), _mm_mul_ps(surf[7], _mm_loadu_ps(feature->w + 28)));
u0 = _mm_add_ps(u0, u1);
u2 = _mm_add_ps(u2, u3);
union {
float f[4];
__m128 p;
} ux;
ux.p = _mm_add_ps(u0, u2);
float u = expf(feature->bias + ux.f[0] + ux.f[1] + ux.f[2] + ux.f[3]);
#else
_ccv_scd_run_feature_at(sat->data.f32, sat->cols, feature, surf);
float u = feature->bias;
int k;
for (k = 0; k < 32; k++)
u += surf[k] * feature->w[k];
u = expf(u);
#endif
v += (u - 1) / (u + 1);
}
if (v <= classifier->threshold)
{
pass = 0;
break;
}
}
ccv_matrix_free(sat);
return pass;
}
static ccv_array_t* _ccv_scd_hard_mining(gsl_rng* rng, ccv_scd_classifier_cascade_t* cascade, ccv_array_t* hard_mine, ccv_array_t* negatives, int negative_count, int grayscale, int even_dist)
{
ccv_array_t* hard_negatives = ccv_array_new(ccv_compute_dense_matrix_size(cascade->size.height, cascade->size.width, CCV_8U | (grayscale ? CCV_C1 : CCV_C3)), negative_count, 0);
int i, j, t;
for (i = 0; i < negatives->rnum; i++)
{
ccv_dense_matrix_t* a = (ccv_dense_matrix_t*)ccv_array_get(negatives, i);
a->data.u8 = (unsigned char*)(a + 1);
if (_ccv_scd_classifier_cascade_pass(cascade, a))
ccv_array_push(hard_negatives, a);
}
int n_per_mine = ccv_max((negative_count - hard_negatives->rnum) / hard_mine->rnum, 10);
// the hard mining comes in following fashion:
// 1). original, with n_per_mine set;
// 2). horizontal flip, with n_per_mine set;
// 3). vertical flip, with n_per_mine set;
// 4). 180 rotation, with n_per_mine set;
// 5~8). repeat above, but with no n_per_mine set;
// after above, if we still cannot collect enough, so be it.
for (t = (even_dist ? 0 : 4); t < 8 /* exhausted all variations */ && hard_negatives->rnum < negative_count; t++)
{
for (i = 0; i < hard_mine->rnum; i++)
{
FLUSH(CCV_CLI_INFO, " - hard mine negatives %d%% with %d-th permutation", 100 * hard_negatives->rnum / negative_count, t + 1);
ccv_file_info_t* file_info = (ccv_file_info_t*)ccv_array_get(hard_mine, i);
ccv_dense_matrix_t* image = 0;
ccv_read(file_info->filename, &image, CCV_IO_ANY_FILE | (grayscale ? CCV_IO_GRAY : CCV_IO_RGB_COLOR));
if (image == 0)
{
PRINT(CCV_CLI_ERROR, "\n - %s: cannot be open, possibly corrupted\n", file_info->filename);
continue;
}
if (t % 2 != 0)
ccv_flip(image, 0, 0, CCV_FLIP_X);
if (t % 4 >= 2)
ccv_flip(image, 0, 0, CCV_FLIP_Y);
if (t >= 4)
n_per_mine = negative_count; // no hard limit on n_per_mine anymore for the last pass
ccv_scd_param_t params = {
.interval = 3,
.min_neighbors = 0,
.step_through = 4,
.size = cascade->size,
};
ccv_array_t* objects = ccv_scd_detect_objects(image, &cascade, 1, params);
if (objects->rnum > 0)
{
gsl_ran_shuffle(rng, objects->data, objects->rnum, objects->rsize);
for (j = 0; j < ccv_min(objects->rnum, n_per_mine); j++)
{
ccv_rect_t* rect = (ccv_rect_t*)ccv_array_get(objects, j);
if (rect->x < 0 || rect->y < 0 || rect->x + rect->width > image->cols || rect->y + rect->height > image->rows)
continue;
ccv_dense_matrix_t* sliced = 0;
ccv_slice(image, (ccv_matrix_t**)&sliced, 0, rect->y, rect->x, rect->height, rect->width);
ccv_dense_matrix_t* resized = 0;
assert(sliced->rows >= cascade->size.height && sliced->cols >= cascade->size.width);
if (sliced->rows > cascade->size.height || sliced->cols > cascade->size.width)
{
ccv_resample(sliced, &resized, 0, cascade->size.height, cascade->size.width, CCV_INTER_CUBIC);
ccv_matrix_free(sliced);
} else {
resized = sliced;
}
if (_ccv_scd_classifier_cascade_pass(cascade, resized))
ccv_array_push(hard_negatives, resized);
ccv_matrix_free(resized);
if (hard_negatives->rnum >= negative_count)
break;
}
}
ccv_matrix_free(image);
if (hard_negatives->rnum >= negative_count)
break;
}
}
FLUSH(CCV_CLI_INFO, " - hard mine negatives : %d\n", hard_negatives->rnum);
ccv_make_array_immutable(hard_negatives);
return hard_negatives;
}
typedef struct {
ccv_function_state_reserve_field;
int t, k;
uint64_t array_signature;
ccv_array_t* features;
ccv_array_t* positives;
ccv_array_t* negatives;
double* s;
double* pw;
double* nw;
float* fv; // feature vector for examples * feature
double auc_prev;
double accu_true_positive_rate;
double accu_false_positive_rate;
ccv_scd_classifier_cascade_t* cascade;
ccv_scd_train_param_t params;
} ccv_scd_classifier_cascade_new_function_state_t;
static void _ccv_scd_classifier_cascade_new_function_state_read(const char* filename, ccv_scd_classifier_cascade_new_function_state_t* z)
{
ccv_scd_classifier_cascade_t* cascade = ccv_scd_classifier_cascade_read(filename);
if (!cascade)
return;
if (z->cascade)
ccv_scd_classifier_cascade_free(z->cascade);
z->cascade = cascade;
assert(z->cascade->size.width == z->params.size.width);
assert(z->cascade->size.height == z->params.size.height);
sqlite3* db = 0;
if (SQLITE_OK == sqlite3_open(filename, &db))
{
const char negative_data_qs[] =
"SELECT data, rnum, rsize FROM negative_data WHERE id=0;";
sqlite3_stmt* negative_data_stmt = 0;
if (SQLITE_OK == sqlite3_prepare_v2(db, negative_data_qs, sizeof(negative_data_qs), &negative_data_stmt, 0))
{
if (sqlite3_step(negative_data_stmt) == SQLITE_ROW)
{
int rsize = ccv_compute_dense_matrix_size(z->cascade->size.height, z->cascade->size.width, CCV_8U | (z->params.grayscale ? CCV_C1 : CCV_C3));
int rnum = sqlite3_column_int(negative_data_stmt, 1);
assert(sqlite3_column_int(negative_data_stmt, 2) == rsize);
size_t size = sqlite3_column_bytes(negative_data_stmt, 0);
assert(size == (size_t)rsize * rnum);
if (z->negatives)
ccv_array_clear(z->negatives);
else
z->negatives = ccv_array_new(rsize, rnum, 0);
int i;
const uint8_t* data = (const uint8_t*)sqlite3_column_blob(negative_data_stmt, 0);
for (i = 0; i < rnum; i++)
ccv_array_push(z->negatives, data + (off_t)i * rsize);
ccv_make_array_immutable(z->negatives);
z->array_signature = z->negatives->sig;
}
sqlite3_finalize(negative_data_stmt);
}
const char function_state_qs[] =
"SELECT t, k, positive_count, auc_prev, " // 4
"accu_true_positive_rate, accu_false_positive_rate, " // 6
"line_no, s, pw, nw FROM function_state WHERE fsid = 0;"; // 10
sqlite3_stmt* function_state_stmt = 0;
if (SQLITE_OK == sqlite3_prepare_v2(db, function_state_qs, sizeof(function_state_qs), &function_state_stmt, 0))
{
if (sqlite3_step(function_state_stmt) == SQLITE_ROW)
{
z->t = sqlite3_column_int(function_state_stmt, 0);
z->k = sqlite3_column_int(function_state_stmt, 1);
int positive_count = sqlite3_column_int(function_state_stmt, 2);
assert(positive_count == z->positives->rnum);
z->auc_prev = sqlite3_column_double(function_state_stmt, 3);
z->accu_true_positive_rate = sqlite3_column_double(function_state_stmt, 4);
z->accu_false_positive_rate = sqlite3_column_double(function_state_stmt, 5);
z->line_no = sqlite3_column_int(function_state_stmt, 6);
size_t size = sqlite3_column_bytes(function_state_stmt, 7);
const void* s = sqlite3_column_blob(function_state_stmt, 7);
memcpy(z->s, s, size);
size = sqlite3_column_bytes(function_state_stmt, 8);
const void* pw = sqlite3_column_blob(function_state_stmt, 8);
memcpy(z->pw, pw, size);
size = sqlite3_column_bytes(function_state_stmt, 9);
const void* nw = sqlite3_column_blob(function_state_stmt, 9);
memcpy(z->nw, nw, size);
}
sqlite3_finalize(function_state_stmt);
}
_ccv_scd_precompute_feature_vectors(z->features, z->positives, z->negatives, z->fv);
sqlite3_close(db);
}
}
static void _ccv_scd_classifier_cascade_new_function_state_write(ccv_scd_classifier_cascade_new_function_state_t* z, const char* filename)
{
ccv_scd_classifier_cascade_write(z->cascade, filename);
sqlite3* db = 0;
if (SQLITE_OK == sqlite3_open(filename, &db))
{
const char function_state_create_table_qs[] =
"CREATE TABLE IF NOT EXISTS function_state "
"(fsid INTEGER PRIMARY KEY ASC, t INTEGER, k INTEGER, positive_count INTEGER, auc_prev DOUBLE, accu_true_positive_rate DOUBLE, accu_false_positive_rate DOUBLE, line_no INTEGER, s BLOB, pw BLOB, nw BLOB);"
"CREATE TABLE IF NOT EXISTS negative_data "
"(id INTEGER PRIMARY KEY ASC, data BLOB, rnum INTEGER, rsize INTEGER);";
assert(SQLITE_OK == sqlite3_exec(db, function_state_create_table_qs, 0, 0, 0));
const char function_state_insert_qs[] =
"REPLACE INTO function_state "
"(fsid, t, k, positive_count, auc_prev, accu_true_positive_rate, accu_false_positive_rate, line_no, s, pw, nw) VALUES "
"(0, $t, $k, $positive_count, $auc_prev, $accu_true_positive_rate, $accu_false_positive_rate, $line_no, $s, $pw, $nw);";
sqlite3_stmt* function_state_insert_stmt = 0;
assert(SQLITE_OK == sqlite3_prepare_v2(db, function_state_insert_qs, sizeof(function_state_insert_qs), &function_state_insert_stmt, 0));
sqlite3_bind_int(function_state_insert_stmt, 1, z->t);
sqlite3_bind_int(function_state_insert_stmt, 2, z->k);
sqlite3_bind_int(function_state_insert_stmt, 3, z->positives->rnum);
sqlite3_bind_double(function_state_insert_stmt, 4, z->auc_prev);
sqlite3_bind_double(function_state_insert_stmt, 5, z->accu_true_positive_rate);
sqlite3_bind_double(function_state_insert_stmt, 6, z->accu_false_positive_rate);
sqlite3_bind_int(function_state_insert_stmt, 7, z->line_no);
sqlite3_bind_blob(function_state_insert_stmt, 8, z->s, sizeof(double) * (z->positives->rnum + z->negatives->rnum), SQLITE_STATIC);
sqlite3_bind_blob(function_state_insert_stmt, 9, z->pw, sizeof(double) * z->positives->rnum, SQLITE_STATIC);
sqlite3_bind_blob(function_state_insert_stmt, 10, z->nw, sizeof(double) * z->negatives->rnum, SQLITE_STATIC);
assert(SQLITE_DONE == sqlite3_step(function_state_insert_stmt));
sqlite3_finalize(function_state_insert_stmt);
if (z->array_signature != z->negatives->sig)
{
const char negative_data_insert_qs[] =
"REPLACE INTO negative_data "
"(id, data, rnum, rsize) VALUES (0, $data, $rnum, $rsize);";
sqlite3_stmt* negative_data_insert_stmt = 0;
assert(SQLITE_OK == sqlite3_prepare_v2(db, negative_data_insert_qs, sizeof(negative_data_insert_qs), &negative_data_insert_stmt, 0));
sqlite3_bind_blob(negative_data_insert_stmt, 1, z->negatives->data, z->negatives->rsize * z->negatives->rnum, SQLITE_STATIC);
sqlite3_bind_int(negative_data_insert_stmt, 2, z->negatives->rnum);
sqlite3_bind_int(negative_data_insert_stmt, 3, z->negatives->rsize);
assert(SQLITE_DONE == sqlite3_step(negative_data_insert_stmt));
sqlite3_finalize(negative_data_insert_stmt);
z->array_signature = z->negatives->sig;
}
sqlite3_close(db);
}
}
#endif
ccv_scd_classifier_cascade_t* ccv_scd_classifier_cascade_new(ccv_array_t* posfiles, ccv_array_t* hard_mine, int negative_count, const char* filename, ccv_scd_train_param_t params)
{
#ifdef HAVE_GSL
assert(posfiles->rnum > 0);
assert(hard_mine->rnum > 0);
gsl_rng_env_setup();
gsl_rng* rng = gsl_rng_alloc(gsl_rng_default);
ccv_scd_classifier_cascade_new_function_state_t z = {0};
z.features = _ccv_scd_stump_features(params.feature.base, params.feature.range_through, params.feature.step_through, params.size);
PRINT(CCV_CLI_INFO, " - using %d features\n", z.features->rnum);
int i, j, p, q;
z.positives = _ccv_scd_collect_positives(params.size, posfiles, params.grayscale);
double* h = (double*)ccmalloc(sizeof(double) * (z.positives->rnum + negative_count));
z.s = (double*)ccmalloc(sizeof(double) * (z.positives->rnum + negative_count));
assert(z.s);
z.pw = (double*)ccmalloc(sizeof(double) * z.positives->rnum);
assert(z.pw);
z.nw = (double*)ccmalloc(sizeof(double) * negative_count);
assert(z.nw);
ccmemalign((void**)&z.fv, 16, sizeof(float) * (z.positives->rnum + negative_count) * z.features->rnum * 32);
assert(z.fv);
z.params = params;
ccv_function_state_begin(_ccv_scd_classifier_cascade_new_function_state_read, z, filename);
z.negatives = _ccv_scd_collect_negatives(rng, params.size, hard_mine, negative_count, params.grayscale);
_ccv_scd_precompute_feature_vectors(z.features, z.positives, z.negatives, z.fv);
z.cascade = (ccv_scd_classifier_cascade_t*)ccmalloc(sizeof(ccv_scd_classifier_cascade_t));
z.cascade->margin = ccv_margin(0, 0, 0, 0);
z.cascade->size = params.size;
z.cascade->count = 0;
z.cascade->classifiers = 0;
z.accu_true_positive_rate = 1;
z.accu_false_positive_rate = 1;
ccv_function_state_resume(_ccv_scd_classifier_cascade_new_function_state_write, z, filename);
for (z.t = 0; z.t < params.boosting; z.t++)
{
for (i = 0; i < z.positives->rnum; i++)
z.pw[i] = 0.5 / z.positives->rnum;
for (i = 0; i < z.negatives->rnum; i++)
z.nw[i] = 0.5 / z.negatives->rnum;
memset(z.s, 0, sizeof(double) * (z.positives->rnum + z.negatives->rnum));
z.cascade->classifiers = (ccv_scd_stump_classifier_t*)ccrealloc(z.cascade->classifiers, sizeof(ccv_scd_stump_classifier_t) * (z.t + 1));
z.cascade->count = z.t + 1;
z.cascade->classifiers[z.t].threshold = 0;
z.cascade->classifiers[z.t].features = 0;
z.cascade->classifiers[z.t].count = 0;
z.auc_prev = 0;
assert(z.positives->rnum > 0 && z.negatives->rnum > 0);
// for the first prune stages, we have more restrictive number of features (faster)
for (z.k = 0; z.k < (z.t < params.stop_criteria.prune_stage ? params.stop_criteria.prune_feature : params.stop_criteria.maximum_feature); z.k++)
{
ccv_scd_stump_classifier_t* classifier = z.cascade->classifiers + z.t;
classifier->features = (ccv_scd_stump_feature_t*)ccrealloc(classifier->features, sizeof(ccv_scd_stump_feature_t) * (z.k + 1));
_ccv_scd_stump_feature_supervised_train(rng, z.features, z.positives->rnum, z.negatives->rnum, z.pw, z.nw, z.fv, params.C, params.weight_trimming);
int best_feature_no = _ccv_scd_best_feature_gentle_adaboost(z.s, z.features, z.pw, z.nw, z.positives->rnum, z.negatives->rnum, z.fv);
ccv_scd_stump_feature_t best_feature = *(ccv_scd_stump_feature_t*)ccv_array_get(z.features, best_feature_no);
for (i = 0; i < z.positives->rnum + z.negatives->rnum; i++)
{
float* surf = _ccv_scd_get_surf_at(z.fv, best_feature_no, i, z.positives->rnum, z.negatives->rnum);
float v = best_feature.bias;
for (j = 0; j < 32; j++)
v += best_feature.w[j] * surf[j];
v = expf(v);
h[i] = (v - 1) / (v + 1);
}
// compute the total score so far
for (i = 0; i < z.positives->rnum + z.negatives->rnum; i++)
z.s[i] += h[i];
// compute AUC
double auc = _ccv_scd_auc(z.s, z.positives->rnum, z.negatives->rnum);
float true_positive_rate = 0;
float false_positive_rate = 0;
// compute true positive / false positive rate
_ccv_scd_threshold_at_hit_rate(z.s, z.positives->rnum, z.negatives->rnum, params.stop_criteria.hit_rate, &true_positive_rate, &false_positive_rate);
FLUSH(CCV_CLI_INFO, " - at %d-th iteration, auc: %lf, TP rate: %f, FP rate: %f\n", z.k + 1, auc, true_positive_rate, false_positive_rate);
PRINT(CCV_CLI_INFO, " --- pick feature %s @ (%d, %d, %d, %d)\n", ((best_feature.dy[3] == best_feature.dy[0] ? "4x1" : (best_feature.dx[3] == best_feature.dx[0] ? "1x4" : "2x2"))), best_feature.sx[0], best_feature.sy[0], best_feature.dx[3], best_feature.dy[3]);
classifier->features[z.k] = best_feature;
classifier->count = z.k + 1;
double auc_prev = z.auc_prev;
z.auc_prev = auc;
// auc stop to improve, as well as the false positive rate goal reach, at that point, we stop
if (auc - auc_prev < params.stop_criteria.auc_crit && false_positive_rate < params.stop_criteria.false_positive_rate)
break;
// re-weight, with Gentle AdaBoost
for (i = 0; i < z.positives->rnum; i++)
z.pw[i] *= exp(-h[i]);
for (i = 0; i < z.negatives->rnum; i++)
z.nw[i] *= exp(h[i + z.positives->rnum]);
// re-normalize
double w = 0;
for (i = 0; i < z.positives->rnum; i++)
w += z.pw[i];
w = 0.5 / w;
for (i = 0; i < z.positives->rnum; i++)
z.pw[i] *= w;
w = 0;
for (i = 0; i < z.negatives->rnum; i++)
w += z.nw[i];
w = 0.5 / w;
for (i = 0; i < z.negatives->rnum; i++)
z.nw[i] *= w;
ccv_function_state_resume(_ccv_scd_classifier_cascade_new_function_state_write, z, filename);
}
// backtrack removal
while (z.cascade->classifiers[z.t].count > 1)
{
double max_auc = 0;
p = -1;
for (i = 0; i < z.cascade->classifiers[z.t].count; i++)
{
ccv_scd_stump_feature_t* feature = z.cascade->classifiers[z.t].features + i;
int k = _ccv_scd_find_match_feature(feature, z.features);
assert(k >= 0);
for (j = 0; j < z.positives->rnum + z.negatives->rnum; j++)
{
float* surf = _ccv_scd_get_surf_at(z.fv, k, j, z.positives->rnum, z.negatives->rnum);
float v = feature->bias;
for (q = 0; q < 32; q++)
v += feature->w[q]* surf[q];
v = expf(v);
h[j] = z.s[j] - (v - 1) / (v + 1);
}
double auc = _ccv_scd_auc(h, z.positives->rnum, z.negatives->rnum);
FLUSH(CCV_CLI_INFO, " - attempting without %d-th feature, auc: %lf", i + 1, auc);
if (auc >= max_auc)
max_auc = auc, p = i;
}
if (max_auc >= z.auc_prev)
{
FLUSH(CCV_CLI_INFO, " - remove %d-th feature with new auc %lf\n", p + 1, max_auc);
ccv_scd_stump_feature_t* feature = z.cascade->classifiers[z.t].features + p;
int k = _ccv_scd_find_match_feature(feature, z.features);
assert(k >= 0);
for (j = 0; j < z.positives->rnum + z.negatives->rnum; j++)
{
float* surf = _ccv_scd_get_surf_at(z.fv, k, j, z.positives->rnum, z.negatives->rnum);
float v = feature->bias;
for (q = 0; q < 32; q++)
v += feature->w[q] * surf[q];
v = expf(v);
z.s[j] -= (v - 1) / (v + 1);
}
z.auc_prev = _ccv_scd_auc(z.s, z.positives->rnum, z.negatives->rnum);
--z.cascade->classifiers[z.t].count;
if (p < z.cascade->classifiers[z.t].count)
memmove(z.cascade->classifiers[z.t].features + p + 1, z.cascade->classifiers[z.t].features + p, sizeof(ccv_scd_stump_feature_t) * (z.cascade->classifiers[z.t].count - p));
} else
break;
}
float true_positive_rate = 0;
float false_positive_rate = 0;
z.cascade->classifiers[z.t].threshold = _ccv_scd_threshold_at_hit_rate(z.s, z.positives->rnum, z.negatives->rnum, params.stop_criteria.hit_rate, &true_positive_rate, &false_positive_rate);
z.accu_true_positive_rate *= true_positive_rate;
z.accu_false_positive_rate *= false_positive_rate;
FLUSH(CCV_CLI_INFO, " - %d-th stage classifier TP rate : %f, FP rate : %f, ATP rate : %lf, AFP rate : %lg, at threshold : %f\n", z.t + 1, true_positive_rate, false_positive_rate, z.accu_true_positive_rate, z.accu_false_positive_rate, z.cascade->classifiers[z.t].threshold);
if (z.accu_false_positive_rate < params.stop_criteria.accu_false_positive_rate)
break;
ccv_function_state_resume(_ccv_scd_classifier_cascade_new_function_state_write, z, filename);
if (z.t < params.boosting - 1)
{
int pass = 0;
for (i = 0; i < z.positives->rnum; i++)
{
ccv_dense_matrix_t* a = (ccv_dense_matrix_t*)ccv_array_get(z.positives, i);
a->data.u8 = (unsigned char*)(a + 1);
if (_ccv_scd_classifier_cascade_pass(z.cascade, a))
++pass;
}
PRINT(CCV_CLI_INFO, " - %d-th stage classifier TP rate (with pass) : %f\n", z.t + 1, (float)pass / z.positives->rnum);
ccv_array_t* hard_negatives = _ccv_scd_hard_mining(rng, z.cascade, hard_mine, z.negatives, negative_count, params.grayscale, z.t < params.stop_criteria.prune_stage /* try to balance even distribution among negatives when we are in prune stage */);
ccv_array_free(z.negatives);
z.negatives = hard_negatives;
_ccv_scd_precompute_feature_vectors(z.features, z.positives, z.negatives, z.fv);
}
ccv_function_state_resume(_ccv_scd_classifier_cascade_new_function_state_write, z, filename);
}
ccv_array_free(z.negatives);
ccv_function_state_finish();
ccv_array_free(z.features);
ccv_array_free(z.positives);
ccfree(h);
ccfree(z.s);
ccfree(z.pw);
ccfree(z.nw);
ccfree(z.fv);
gsl_rng_free(rng);
return z.cascade;
#else
assert(0 && "ccv_scd_classifier_cascade_new requires GSL library and support");
return 0;
#endif
}
void ccv_scd_classifier_cascade_write(ccv_scd_classifier_cascade_t* cascade, const char* filename)
{
sqlite3* db = 0;
if (SQLITE_OK == sqlite3_open(filename, &db))
{
const char create_table_qs[] =
"CREATE TABLE IF NOT EXISTS cascade_params "
"(id INTEGER PRIMARY KEY ASC, count INTEGER, "
"margin_left INTEGER, margin_top INTEGER, margin_right INTEGER, margin_bottom INTEGER, "
"size_width INTEGER, size_height INTEGER);"
"CREATE TABLE IF NOT EXISTS classifier_params "
"(classifier INTEGER PRIMARY KEY ASC, count INTEGER, threshold DOUBLE);"
"CREATE TABLE IF NOT EXISTS feature_params "
"(classifier INTEGER, id INTEGER, "
"sx_0 INTEGER, sy_0 INTEGER, dx_0 INTEGER, dy_0 INTEGER, "
"sx_1 INTEGER, sy_1 INTEGER, dx_1 INTEGER, dy_1 INTEGER, "
"sx_2 INTEGER, sy_2 INTEGER, dx_2 INTEGER, dy_2 INTEGER, "
"sx_3 INTEGER, sy_3 INTEGER, dx_3 INTEGER, dy_3 INTEGER, "
"bias DOUBLE, w BLOB, UNIQUE (classifier, id));";
assert(SQLITE_OK == sqlite3_exec(db, create_table_qs, 0, 0, 0));
const char cascade_params_insert_qs[] =
"REPLACE INTO cascade_params "
"(id, count, "
"margin_left, margin_top, margin_right, margin_bottom, "
"size_width, size_height) VALUES "
"(0, $count, " // 0
"$margin_left, $margin_top, $margin_bottom, $margin_right, " // 4
"$size_width, $size_height);"; // 6
sqlite3_stmt* cascade_params_insert_stmt = 0;
assert(SQLITE_OK == sqlite3_prepare_v2(db, cascade_params_insert_qs, sizeof(cascade_params_insert_qs), &cascade_params_insert_stmt, 0));
sqlite3_bind_int(cascade_params_insert_stmt, 1, cascade->count);
sqlite3_bind_int(cascade_params_insert_stmt, 2, cascade->margin.left);
sqlite3_bind_int(cascade_params_insert_stmt, 3, cascade->margin.top);
sqlite3_bind_int(cascade_params_insert_stmt, 4, cascade->margin.right);
sqlite3_bind_int(cascade_params_insert_stmt, 5, cascade->margin.bottom);
sqlite3_bind_int(cascade_params_insert_stmt, 6, cascade->size.width);
sqlite3_bind_int(cascade_params_insert_stmt, 7, cascade->size.height);
assert(SQLITE_DONE == sqlite3_step(cascade_params_insert_stmt));
sqlite3_finalize(cascade_params_insert_stmt);
const char classifier_params_insert_qs[] =
"REPLACE INTO classifier_params "
"(classifier, count, threshold) VALUES "
"($classifier, $count, $threshold);";
sqlite3_stmt* classifier_params_insert_stmt = 0;
assert(SQLITE_OK == sqlite3_prepare_v2(db, classifier_params_insert_qs, sizeof(classifier_params_insert_qs), &classifier_params_insert_stmt, 0));
const char feature_params_insert_qs[] =
"REPLACE INTO feature_params "
"(classifier, id, "
"sx_0, sy_0, dx_0, dy_0, "
"sx_1, sy_1, dx_1, dy_1, "
"sx_2, sy_2, dx_2, dy_2, "
"sx_3, sy_3, dx_3, dy_3, "
"bias, w) VALUES "
"($classifier, $id, " // 1
"$sx_0, $sy_0, $dx_0, $dy_0, " // 5
"$sx_1, $sy_1, $dx_1, $dy_1, " // 9
"$sx_2, $sy_2, $dx_2, $dy_2, " // 13
"$sx_3, $sy_3, $dx_3, $dy_3, " // 17
"$bias, $w);"; // 19
sqlite3_stmt* feature_params_insert_stmt = 0;
assert(SQLITE_OK == sqlite3_prepare_v2(db, feature_params_insert_qs, sizeof(feature_params_insert_qs), &feature_params_insert_stmt, 0));
int i, j, k;
for (i = 0; i < cascade->count; i++)
{
ccv_scd_stump_classifier_t* classifier = cascade->classifiers + i;
sqlite3_bind_int(classifier_params_insert_stmt, 1, i);
sqlite3_bind_int(classifier_params_insert_stmt, 2, classifier->count);
sqlite3_bind_double(classifier_params_insert_stmt, 3, classifier->threshold);
assert(SQLITE_DONE == sqlite3_step(classifier_params_insert_stmt));
sqlite3_reset(classifier_params_insert_stmt);
sqlite3_clear_bindings(classifier_params_insert_stmt);
for (j = 0; j < classifier->count; j++)
{
ccv_scd_stump_feature_t* feature = classifier->features + j;
sqlite3_bind_int(feature_params_insert_stmt, 1, i);
sqlite3_bind_int(feature_params_insert_stmt, 2, j);
for (k = 0; k < 4; k++)
{
sqlite3_bind_int(feature_params_insert_stmt, 3 + k * 4, feature->sx[k]);
sqlite3_bind_int(feature_params_insert_stmt, 4 + k * 4, feature->sy[k]);
sqlite3_bind_int(feature_params_insert_stmt, 5 + k * 4, feature->dx[k]);
sqlite3_bind_int(feature_params_insert_stmt, 6 + k * 4, feature->dy[k]);
}
sqlite3_bind_double(feature_params_insert_stmt, 19, feature->bias);
sqlite3_bind_blob(feature_params_insert_stmt, 20, feature->w, sizeof(float) * 32, SQLITE_STATIC);
assert(SQLITE_DONE == sqlite3_step(feature_params_insert_stmt));
sqlite3_reset(feature_params_insert_stmt);
sqlite3_clear_bindings(feature_params_insert_stmt);
}
}
sqlite3_finalize(classifier_params_insert_stmt);
sqlite3_finalize(feature_params_insert_stmt);
sqlite3_close(db);
}
}
ccv_scd_classifier_cascade_t* ccv_scd_classifier_cascade_read(const char* filename)
{
int i;
sqlite3* db = 0;
ccv_scd_classifier_cascade_t* cascade = 0;
if (SQLITE_OK == sqlite3_open(filename, &db))
{
const char cascade_params_qs[] =
"SELECT count, " // 1
"margin_left, margin_top, margin_right, margin_bottom, " // 5
"size_width, size_height FROM cascade_params WHERE id = 0;"; // 7
sqlite3_stmt* cascade_params_stmt = 0;
if (SQLITE_OK == sqlite3_prepare_v2(db, cascade_params_qs, sizeof(cascade_params_qs), &cascade_params_stmt, 0))
{
if (sqlite3_step(cascade_params_stmt) == SQLITE_ROW)
{
cascade = (ccv_scd_classifier_cascade_t*)ccmalloc(sizeof(ccv_scd_classifier_cascade_t));
cascade->count = sqlite3_column_int(cascade_params_stmt, 0);
cascade->classifiers = (ccv_scd_stump_classifier_t*)cccalloc(cascade->count, sizeof(ccv_scd_stump_classifier_t));
cascade->margin = ccv_margin(sqlite3_column_int(cascade_params_stmt, 1), sqlite3_column_int(cascade_params_stmt, 2), sqlite3_column_int(cascade_params_stmt, 3), sqlite3_column_int(cascade_params_stmt, 4));
cascade->size = ccv_size(sqlite3_column_int(cascade_params_stmt, 5), sqlite3_column_int(cascade_params_stmt, 6));
}
sqlite3_finalize(cascade_params_stmt);
}
if (cascade)
{
const char classifier_params_qs[] =
"SELECT classifier, count, threshold FROM classifier_params ORDER BY classifier ASC;";
sqlite3_stmt* classifier_params_stmt = 0;
if (SQLITE_OK == sqlite3_prepare_v2(db, classifier_params_qs, sizeof(classifier_params_qs), &classifier_params_stmt, 0))
{
while (sqlite3_step(classifier_params_stmt) == SQLITE_ROW)
if (sqlite3_column_int(classifier_params_stmt, 0) < cascade->count)
{
ccv_scd_stump_classifier_t* classifier = cascade->classifiers + sqlite3_column_int(classifier_params_stmt, 0);
classifier->count = sqlite3_column_int(classifier_params_stmt, 1);
classifier->features = (ccv_scd_stump_feature_t*)ccmalloc(sizeof(ccv_scd_stump_feature_t) * classifier->count);
classifier->threshold = (float)sqlite3_column_double(classifier_params_stmt, 2);
}
sqlite3_finalize(classifier_params_stmt);
}
const char feature_params_qs[] =
"SELECT classifier, id, "
"sx_0, sy_0, dx_0, dy_0, "
"sx_1, sy_1, dx_1, dy_1, "
"sx_2, sy_2, dx_2, dy_2, "
"sx_3, sy_3, dx_3, dy_3, "
"bias, w FROM feature_params ORDER BY classifier, id ASC;";
sqlite3_stmt* feature_params_stmt = 0;
if (SQLITE_OK == sqlite3_prepare_v2(db, feature_params_qs, sizeof(feature_params_qs), &feature_params_stmt, 0))
{
while (sqlite3_step(feature_params_stmt) == SQLITE_ROW)
if (sqlite3_column_int(feature_params_stmt, 0) < cascade->count)
{
ccv_scd_stump_classifier_t* classifier = cascade->classifiers + sqlite3_column_int(feature_params_stmt, 0);
if (sqlite3_column_int(feature_params_stmt, 1) < classifier->count)
{
ccv_scd_stump_feature_t* feature = classifier->features + sqlite3_column_int(feature_params_stmt, 1);
for (i = 0; i < 4; i++)
{
feature->sx[i] = sqlite3_column_int(feature_params_stmt, 2 + i * 4);
feature->sy[i] = sqlite3_column_int(feature_params_stmt, 3 + i * 4);
feature->dx[i] = sqlite3_column_int(feature_params_stmt, 4 + i * 4);
feature->dy[i] = sqlite3_column_int(feature_params_stmt, 5 + i * 4);
}
feature->bias = (float)sqlite3_column_double(feature_params_stmt, 18);
int wnum = sqlite3_column_bytes(feature_params_stmt, 19);
assert(wnum == 32 * sizeof(float));
const void* w = sqlite3_column_blob(feature_params_stmt, 19);
memcpy(feature->w, w, sizeof(float) * 32);
}
}
sqlite3_finalize(feature_params_stmt);
}
}
sqlite3_close(db);
}
return cascade;
}
void ccv_scd_classifier_cascade_free(ccv_scd_classifier_cascade_t* cascade)
{
int i;
for (i = 0; i < cascade->count; i++)
{
ccv_scd_stump_classifier_t* classifier = cascade->classifiers + i;
ccfree(classifier->features);
}
ccfree(cascade->classifiers);
ccfree(cascade);
}
static int _ccv_is_equal_same_class(const void* _r1, const void* _r2, void* data)
{
const ccv_comp_t* r1 = (const ccv_comp_t*)_r1;
const ccv_comp_t* r2 = (const ccv_comp_t*)_r2;
if (r2->classification.id != r1->classification.id)
return 0;
int i = ccv_max(ccv_min(r2->rect.x + r2->rect.width, r1->rect.x + r1->rect.width) - ccv_max(r2->rect.x, r1->rect.x), 0) * ccv_max(ccv_min(r2->rect.y + r2->rect.height, r1->rect.y + r1->rect.height) - ccv_max(r2->rect.y, r1->rect.y), 0);
int m = ccv_min(r2->rect.width * r2->rect.height, r1->rect.width * r1->rect.height);
return i >= 0.3 * m; // IoM > 0.3 like HeadHunter does
}
ccv_array_t* ccv_scd_detect_objects(ccv_dense_matrix_t* a, ccv_scd_classifier_cascade_t** cascades, int count, ccv_scd_param_t params)
{
int i, j, k, x, y, p, q;
int scale_upto = 1;
float up_ratio = 1.0;
for (i = 0; i < count; i++)
up_ratio = ccv_max(up_ratio, ccv_max((float)cascades[i]->size.width / params.size.width, (float)cascades[i]->size.height / params.size.height));
if (up_ratio - 1.0 > 1e-4)
{
ccv_dense_matrix_t* resized = 0;
ccv_resample(a, &resized, 0, (int)(a->rows * up_ratio + 0.5), (int)(a->cols * up_ratio + 0.5), CCV_INTER_CUBIC);
a = resized;
}
for (i = 0; i < count; i++)
scale_upto = ccv_max(scale_upto, (int)(log(ccv_min((double)a->rows / (cascades[i]->size.height - cascades[i]->margin.top - cascades[i]->margin.bottom), (double)a->cols / (cascades[i]->size.width - cascades[i]->margin.left - cascades[i]->margin.right))) / log(2.) - DBL_MIN) + 1);
ccv_dense_matrix_t** pyr = (ccv_dense_matrix_t**)alloca(sizeof(ccv_dense_matrix_t*) * scale_upto);
pyr[0] = a;
for (i = 1; i < scale_upto; i++)
{
pyr[i] = 0;
ccv_sample_down(pyr[i - 1], &pyr[i], 0, 0, 0);
}
#if defined(HAVE_SSE2)
__m128 surf[8];
#else
float surf[32];
#endif
ccv_array_t** seq = (ccv_array_t**)alloca(sizeof(ccv_array_t*) * count);
for (i = 0; i < count; i++)
seq[i] = ccv_array_new(sizeof(ccv_comp_t), 64, 0);
for (i = 0; i < scale_upto; i++)
{
// run it
for (j = 0; j < count; j++)
{
double scale_ratio = pow(2., 1. / (params.interval + 1));
double scale = 1;
ccv_scd_classifier_cascade_t* cascade = cascades[j];
for (k = 0; k <= params.interval; k++)
{
int rows = (int)(pyr[i]->rows / scale + 0.5);
int cols = (int)(pyr[i]->cols / scale + 0.5);
if (rows < cascade->size.height || cols < cascade->size.width)
break;
ccv_dense_matrix_t* image = k == 0 ? pyr[i] : 0;
if (k > 0)
ccv_resample(pyr[i], &image, 0, rows, cols, CCV_INTER_AREA);
ccv_dense_matrix_t* scd = 0;
if (cascade->margin.left == 0 && cascade->margin.top == 0 && cascade->margin.right == 0 && cascade->margin.bottom == 0)
{
ccv_scd(image, &scd, 0);
if (k > 0)
ccv_matrix_free(image);
} else {
ccv_dense_matrix_t* bordered = 0;
ccv_border(image, (ccv_matrix_t**)&bordered, 0, cascade->margin);
if (k > 0)
ccv_matrix_free(image);
ccv_scd(bordered, &scd, 0);
ccv_matrix_free(bordered);
}
ccv_dense_matrix_t* sat = 0;
ccv_sat(scd, &sat, 0, CCV_PADDING_ZERO);
assert(CCV_GET_CHANNEL(sat->type) == 8);
ccv_matrix_free(scd);
float* ptr = sat->data.f32;
for (y = 0; y < rows; y += params.step_through)
{
if (y >= sat->rows - cascade->size.height - 1)
break;
for (x = 0; x < cols; x += params.step_through)
{
if (x >= sat->cols - cascade->size.width - 1)
break;
int pass = 1;
float sum = 0;
for (p = 0; p < cascade->count; p++)
{
ccv_scd_stump_classifier_t* classifier = cascade->classifiers + p;
float v = 0;
for (q = 0; q < classifier->count; q++)
{
ccv_scd_stump_feature_t* feature = classifier->features + q;
#if defined(HAVE_SSE2)
_ccv_scd_run_feature_at_sse2(ptr + x * 8, sat->cols, feature, surf);
__m128 u0 = _mm_add_ps(_mm_mul_ps(surf[0], _mm_loadu_ps(feature->w)), _mm_mul_ps(surf[1], _mm_loadu_ps(feature->w + 4)));
__m128 u1 = _mm_add_ps(_mm_mul_ps(surf[2], _mm_loadu_ps(feature->w + 8)), _mm_mul_ps(surf[3], _mm_loadu_ps(feature->w + 12)));
__m128 u2 = _mm_add_ps(_mm_mul_ps(surf[4], _mm_loadu_ps(feature->w + 16)), _mm_mul_ps(surf[5], _mm_loadu_ps(feature->w + 20)));
__m128 u3 = _mm_add_ps(_mm_mul_ps(surf[6], _mm_loadu_ps(feature->w + 24)), _mm_mul_ps(surf[7], _mm_loadu_ps(feature->w + 28)));
u0 = _mm_add_ps(u0, u1);
u2 = _mm_add_ps(u2, u3);
union {
float f[4];
__m128 p;
} ux;
ux.p = _mm_add_ps(u0, u2);
float u = expf(feature->bias + ux.f[0] + ux.f[1] + ux.f[2] + ux.f[3]);
#else
_ccv_scd_run_feature_at(ptr + x * 8, sat->cols, feature, surf);
float u = feature->bias;
int r;
for (r = 0; r < 32; r++)
u += surf[r] * feature->w[r];
u = expf(u);
#endif
v += (u - 1) / (u + 1);
}
if (v <= classifier->threshold)
{
pass = 0;
break;
}
sum = v / classifier->count;
}
if (pass)
{
ccv_comp_t comp;
comp.rect = ccv_rect((int)((x + 0.5) * (scale / up_ratio) * (1 << i) - 0.5),
(int)((y + 0.5) * (scale / up_ratio) * (1 << i) - 0.5),
(cascade->size.width - cascade->margin.left - cascade->margin.right) * (scale / up_ratio) * (1 << i),
(cascade->size.height - cascade->margin.top - cascade->margin.bottom) * (scale / up_ratio) * (1 << i));
comp.neighbors = 1;
comp.classification.id = j + 1;
comp.classification.confidence = sum + (cascade->count - 1);
ccv_array_push(seq[j], &comp);
}
}
ptr += sat->cols * 8 * params.step_through;
}
ccv_matrix_free(sat);
scale *= scale_ratio;
}
}
}
for (i = 1; i < scale_upto; i++)
ccv_matrix_free(pyr[i]);
if (up_ratio - 1.0 > 1e-4)
ccv_matrix_free(a);
ccv_array_t* result_seq = ccv_array_new(sizeof(ccv_comp_t), 64, 0);
for (k = 0; k < count; k++)
{
/* simple non-maximum suppression, we merge when intersected area / min area > 0.3 */
if(params.min_neighbors == 0)
{
for (i = 0; i < seq[k]->rnum; i++)
{
ccv_comp_t* comp = (ccv_comp_t*)ccv_array_get(seq[k], i);
ccv_array_push(result_seq, comp);
}
} else {
ccv_array_t* idx_seq = 0;
// group retrieved rectangles in order to filter out noise
int ncomp = ccv_array_group(seq[k], &idx_seq, _ccv_is_equal_same_class, 0);
ccv_comp_t* comps = (ccv_comp_t*)cccalloc(ncomp + 1, sizeof(ccv_comp_t));
// count number of neighbors
for (i = 0; i < seq[k]->rnum; i++)
{
ccv_comp_t r1 = *(ccv_comp_t*)ccv_array_get(seq[k], i);
int idx = *(int*)ccv_array_get(idx_seq, i);
comps[idx].classification.id = r1.classification.id;
if (r1.classification.confidence > comps[idx].classification.confidence || comps[idx].neighbors == 0)
{
comps[idx].rect = r1.rect;
comps[idx].classification.confidence = r1.classification.confidence;
}
++comps[idx].neighbors;
}
// push merged bounding box to result_seq
for (i = 0; i < ncomp; i++)
{
int n = comps[i].neighbors;
if (n >= params.min_neighbors)
ccv_array_push(result_seq, comps + i);
}
ccv_array_free(idx_seq);
ccfree(comps);
}
ccv_array_free(seq[k]);
}
return result_seq;
}
| {
"alphanum_fraction": 0.6625981099,
"avg_line_length": 40.6975228162,
"ext": "c",
"hexsha": "11c2bb3df1b7b0b4fbc7a23d1062fef91b15f92c",
"lang": "C",
"max_forks_count": 18,
"max_forks_repo_forks_event_max_datetime": "2021-07-11T17:57:28.000Z",
"max_forks_repo_forks_event_min_datetime": "2016-02-18T08:34:17.000Z",
"max_forks_repo_head_hexsha": "3a8cc247c1f4c36cb910c94fad0abeafe3e029b0",
"max_forks_repo_licenses": [
"CC-BY-4.0"
],
"max_forks_repo_name": "sunkaianna/ccv",
"max_forks_repo_path": "lib/ccv_scd.c",
"max_issues_count": 3,
"max_issues_repo_head_hexsha": "3a8cc247c1f4c36cb910c94fad0abeafe3e029b0",
"max_issues_repo_issues_event_max_datetime": "2021-02-23T16:48:05.000Z",
"max_issues_repo_issues_event_min_datetime": "2017-07-24T03:41:53.000Z",
"max_issues_repo_licenses": [
"CC-BY-4.0"
],
"max_issues_repo_name": "sunkaianna/ccv",
"max_issues_repo_path": "lib/ccv_scd.c",
"max_line_length": 281,
"max_stars_count": 38,
"max_stars_repo_head_hexsha": "3a8cc247c1f4c36cb910c94fad0abeafe3e029b0",
"max_stars_repo_licenses": [
"CC-BY-4.0"
],
"max_stars_repo_name": "sunkaianna/ccv",
"max_stars_repo_path": "lib/ccv_scd.c",
"max_stars_repo_stars_event_max_datetime": "2021-07-02T15:14:13.000Z",
"max_stars_repo_stars_event_min_datetime": "2016-06-08T19:47:43.000Z",
"num_tokens": 21509,
"size": 62430
} |
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <iniparser.h>
#include "parmt_utils.h"
#include "tdsearch_greens.h"
#include "tdsearch_commands.h"
#ifdef TDSEARCH_USE_INTEL
#include <mkl_blas.h>
#else
#include <cblas.h>
#endif
#include "tdsearch_struct.h"
#include "tdsearch_hudson.h"
#include "ispl/process.h"
#include "iscl/array/array.h"
#include "iscl/fft/fft.h"
#include "iscl/memory/memory.h"
#include "iscl/os/os.h"
static int getPrimaryArrival(const struct sacHeader_struct hdr,
double *time, char phaseName[8]);
/*!
* @brief Reads the generic Green's functions pre-processing files from
* the ini file.
*
* @param[in] iniFile Name of ini file.
* @param[in] nobs Number of observations.
*
* @param[in,out] grns On input contains the number of observations.
* On exit contains the generic Green's functions
* processing commands for the observations.
*
* @result 0 indicates success.
*
* @author Ben Baker, ISTI
*
* @ingroup tdsearch_greens
*
* @bug Add an option to read a processing list file.
*
*/
int tdsearch_greens_setPreprocessingCommandsFromIniFile(
const char *iniFile,
const int nobs,
struct tdSearchGreens_struct *grns)
{
dictionary *ini;
char **cmds;
const char *s;
char varname[128];
size_t lenos;
int ierr, k, ncmds, ncmdsWork;
ierr = 0;
grns->nobs = nobs;
if (grns->nobs < 1){return 0;}
if (!os_path_isfile(iniFile))
{
fprintf(stderr, "%s: Error ini file %s doesn't exist\n",
__func__, iniFile);
return -1;
}
ini = iniparser_load(iniFile);
ncmds = iniparser_getint(ini, "tdSearch:greens:nCommands\0", 0);
grns->cmds = (struct tdSearchDataProcessingCommands_struct *)
calloc((size_t) nobs, //ncmds,
sizeof(struct tdSearchDataProcessingCommands_struct));
//if (!luseProcessingList)
{
if (ncmds > 0)
{
ncmdsWork = ncmds;
ncmds = 0;
cmds = (char **) calloc((size_t) ncmdsWork, sizeof(char *));
for (k=0; k<ncmdsWork; k++)
{
memset(varname, 0, 128*sizeof(char));
sprintf(varname, "tdSearch:greens:command_%d", k+1);
s = iniparser_getstring(ini, varname, NULL);
if (s == NULL){continue;}
lenos = strlen(s);
cmds[ncmds] = (char *) calloc(lenos+1, sizeof(char));
strcpy(cmds[ncmds], s);
//printf("%s\n", cmds[ncmds]);
ncmds = ncmds + 1;
}
// Attach these to the data processing structure
for (k=0; k<grns->nobs; k++)
{
ierr = tdsearch_greens_attachCommandsToGreens(
k, ncmds, (const char **) cmds, grns);
}
// Free space
for (k=0; k<ncmdsWork; k++)
{
if (cmds[k] != NULL){free(cmds[k]);}
}
free(cmds);
}
}
iniparser_freedict(ini);
return ierr;
}
//============================================================================//
/*!
* @brief Attaches the Green's functions processing commands to the Green's
* structure.
*
* @param[in] iobs Observation number to attach commands to.
* @param[in] ncmds Number of commands.
* @param[in] cmds Pre-processing commands for the Green's functions
* corresponding to the iobs'th observation [ncmds].
*
* @param[in,out] grns On input has the Green's functions (depths and t*'s)
* corresponding to the observations.
* On output contains the pre-processing commands
* for Green's functions corresponding to the
* observations.
*
* @result 0 indicates success.
*
* @ingroup tdsearch_greens
*
* @author Ben Baker, ISTI
*
*/
int tdsearch_greens_attachCommandsToGreens(const int iobs, const int ncmds,
const char **cmds,
struct tdSearchGreens_struct *grns)
{
int i;
size_t lenos;
// Make sure iobs is in bounds
if (iobs < 0 || iobs >= grns->nobs)
{
fprintf(stderr, "%s: Error iobs=%d is out of bounds [0,%d]\n",
__func__, iobs, grns->nobs);
return -1;
}
// Try to handle space allocation if not already done
if (grns->cmds == NULL && grns->nobs > 0)
{
grns->cmds = (struct tdSearchDataProcessingCommands_struct *)
calloc((size_t) grns->nobs,
sizeof(struct tdSearchDataProcessingCommands_struct));
}
if (grns->cmds == NULL)
{
fprintf(stderr, "%s: Error grns->cmds is NULL\n", __func__);
return -1;
}
if (ncmds == 0){return 0;}
grns->cmds[iobs].ncmds = ncmds;
grns->cmds[iobs].cmds = (char **) calloc((size_t) ncmds, sizeof(char *));
if (cmds == NULL){printf("problem 1\n");}
for (i=0; i<ncmds; i++)
{
if (cmds[i] == NULL){printf("problem 2\n");}
lenos = strlen(cmds[i]);
grns->cmds[iobs].cmds[i] = (char *) calloc(lenos+1, sizeof(char));
strcpy(grns->cmds[iobs].cmds[i], cmds[i]);
}
return 0;
}
//============================================================================//
/*!
* @brief Convenience function which returns the index of the Green's
* function on the Green's function structure.
*
* @param[in] GMT_TERM Name of the desired Green's function:
* (G11_TERM, G22_TERM, ..., G23_TERM).
* @param[in] iobs Desired observation number (C numbering).
* @param[in] itstar Desired t* (C numbering).
* @param[in] idepth Desired depth (C numbering).
* @param[in] grns Contains the number of observations, depths, and t*'s
* on the Green's functions structure.
*
* @result Negative indicates failure. Otherwise, this is the index in
* grns.grns corresponding to the desired
* (iobs, idepth, itstar, G??_GRNS) coordinate.
*
* @ingroup tdsearch_greens
*
* @author Ben Baker, ISTI
*
*/
int tdsearch_greens_getGreensFunctionIndex(
const enum prepmtGreens_enum GMT_TERM,
const int iobs, const int itstar, const int idepth,
const struct tdSearchGreens_struct grns)
{
int igx, indx;
indx =-1;
igx = (int) GMT_TERM - 1;
if (igx < 0 || igx > 5)
{
fprintf(stderr, "%s: Can't classify Green's functions index\n",
__func__);
return indx;
}
indx = iobs*(6*grns.ntstar*grns.ndepth)
+ idepth*(6*grns.ntstar)
+ itstar*6
+ igx;
if (indx >= grns.ngrns)
{
fprintf(stdout, "%s: indx out of bounds - segfault is coming\n",
__func__);
return -1;
}
return indx;
}
//============================================================================//
/*!
* @brief Convenience function for extracting the:
* \$ \{ G_{xx}, G_{yy}, G_{zz}, G_{xy}, G_{xz}, G_{yz} \} \$
* Green's functions indices for the observation, t*, and depth.
*
* @param[in] iobs Observation number.
* @param[in] itstar t* index. This is C numbered.
* @param[in] idepth Depth index. This is C numbered.
* @param[in] grns Contains the Green's functions.
* @param[out] indices Contains the Green's functions indices defining
* the indices that return the:
* \$ \{ G_{xx}, G_{yy}, G_{zz},
* G_{xy}, G_{xz}, G_{yz} \} \$
* for this observation, t*, and depth.
*
* @result 0 indicates success.
*
* @ingroup tdsearch_greens
*
* @author Ben Baker, ISTI
*
*/
int tdsearch_greens_getGreensFunctionsIndices(
const int iobs, const int itstar, const int idepth,
const struct tdSearchGreens_struct grns, int indices[6])
{
int i, ierr;
const enum prepmtGreens_enum mtTerm[6] =
{G11_GRNS, G22_GRNS, G33_GRNS, G12_GRNS, G13_GRNS, G23_GRNS};
ierr = 0;
for (i=0; i<6; i++)
{
indices[i] = tdsearch_greens_getGreensFunctionIndex(mtTerm[i],
iobs, itstar, idepth,
grns);
if (indices[i] < 0){ierr = ierr + 1;}
}
return ierr;
}
//============================================================================//
/*!
* @brief Releases memory on the Greens functions structure.
*
* @param[out] grns On exit all memory has been freed and variables set to
* 0 or NULL.
*
* @result 0 indicates success.
*
* @ingroup tdsearch_greens
*
* @author Ben Baker, ISTI
*
*/
int tdsearch_greens_free(struct tdSearchGreens_struct *grns)
{
int i, k;
if (grns->grns != NULL && grns->ngrns > 0)
{
for (k=0; k<grns->ngrns; k++)
{
sacio_free(&grns->grns[k]);
}
free(grns->grns);
}
if (grns->cmds != NULL)
{
for (k=0; k<grns->nobs; k++)
{
if (grns->cmds[k].cmds != NULL)
{
for (i=0; i<grns->cmds[k].ncmds; i++)
{
if (grns->cmds[k].cmds[i] != NULL)
{
free(grns->cmds[k].cmds[i]);
grns->cmds[k].cmds[i] = NULL;
}
}
free(grns->cmds[k].cmds);
grns->cmds[k].cmds = NULL;
}
}
free(grns->cmds);
grns->cmds = NULL;
}
if (grns->cmdsGrns != NULL)
{
for (k=0; k<grns->ngrns; k++)
{
if (grns->cmdsGrns[k].cmds != NULL)
{
for (i=0; i<grns->cmdsGrns[k].ncmds; i++)
{
if (grns->cmdsGrns[k].cmds != NULL)
{
free(grns->cmdsGrns[k].cmds[i]);
grns->cmdsGrns[k].cmds[i] = NULL;
}
}
free(grns->cmdsGrns[k].cmds);
grns->cmdsGrns[k].cmds = NULL;
}
}
free(grns->cmdsGrns);
grns->cmdsGrns = NULL;
}
memset(grns, 0, sizeof(struct tdSearchGreens_struct));
return 0;
}
//============================================================================//
/*!
* @brief Converts the fundamental faults Green's functions to Green's
* functions that can be used by tdsearch.
*
* @param[in] data tdSearch data structure.
* @param[in] ffGrns fundamental fault Green's functions for every t* and
* depth in the grid search for each observation.
*
* @param[out] grns Contains the Green's functions that can be applied to
* a moment tensor to produce a synthetic for every t*
* and depth in the grid search for each observation.
*
* @result 0 indicates success.
*
* @ingroup tdsearch_greens
*
* @author Ben Baker, ISTI
*
*/
int tdsearch_greens_ffGreensToGreens(const struct tdSearchData_struct data,
const struct tdSearchHudson_struct ffGrns,
struct tdSearchGreens_struct *grns)
{
char knetwk[8], kstnm[8], kcmpnm[8], khole[8], phaseName[8],
phaseNameGrns[8];
double az, baz, cmpaz, cmpinc, cmpincSEED, dt0, epoch, epochNew,
evla, evlo, o, pick, pickTime, pickTimeGrns, stel, stla, stlo;
int i, icomp, id, ierr, idx, indx, iobs, it, kndx, l, npts;
const char *kcmpnms[6] = {"GXX\0", "GYY\0", "GZZ\0",
"GXY\0", "GXZ\0", "GYZ\0"};
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 int nTimeVars = 11;
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};
//memset(grns, 0, sizeof(struct tdSearchGreens_struct));
grns->ntstar = ffGrns.ntstar;
grns->ndepth = ffGrns.ndepth;
grns->nobs = data.nobs;
grns->ngrns = 6*grns->ntstar*grns->ndepth*grns->nobs;
if (grns->ngrns < 1)
{
fprintf(stderr, "%s: Error grns is empty\n", __func__);
return -1;
}
grns->grns = (struct sacData_struct *)
calloc((size_t) grns->ngrns, sizeof(struct sacData_struct));
for (iobs=0; iobs<data.nobs; iobs++)
{
ierr = 0;
ierr += sacio_getFloatHeader(SAC_FLOAT_AZ,
data.obs[iobs].header, &az);
ierr += sacio_getFloatHeader(SAC_FLOAT_BAZ,
data.obs[iobs].header, &baz);
ierr += sacio_getFloatHeader(SAC_FLOAT_CMPINC,
data.obs[iobs].header, &cmpinc);
ierr += sacio_getFloatHeader(SAC_FLOAT_CMPAZ,
data.obs[iobs].header, &cmpaz);
ierr += sacio_getFloatHeader(SAC_FLOAT_EVLA,
data.obs[iobs].header, &evla);
ierr += sacio_getFloatHeader(SAC_FLOAT_EVLO,
data.obs[iobs].header, &evlo);
ierr += sacio_getFloatHeader(SAC_FLOAT_STLA,
data.obs[iobs].header, &stla);
ierr += sacio_getFloatHeader(SAC_FLOAT_STLO,
data.obs[iobs].header, &stlo);
ierr += sacio_getFloatHeader(SAC_FLOAT_DELTA,
data.obs[iobs].header, &dt0);
ierr += sacio_getCharacterHeader(SAC_CHAR_KNETWK,
data.obs[iobs].header, knetwk);
ierr += sacio_getCharacterHeader(SAC_CHAR_KSTNM,
data.obs[iobs].header, kstnm);
ierr += sacio_getCharacterHeader(SAC_CHAR_KCMPNM,
data.obs[iobs].header, kcmpnm);
// this one isn't critical
sacio_getFloatHeader(SAC_FLOAT_STEL,
data.obs[iobs].header, &stel);
if (ierr != 0)
{
fprintf(stderr, "%s: Error reading header variables\n", __func__);
break;
}
// Station location code is not terribly important
sacio_getCharacterHeader(SAC_CHAR_KHOLE, data.obs[iobs].header, khole);
cmpincSEED = cmpinc - 90.0; // SAC to SEED convention
// Get the primary arrival
ierr = sacio_getEpochalStartTime(data.obs[iobs].header, &epoch);
if (ierr != 0)
{
fprintf(stderr, "%s: Error getting start time\n", __func__);
break;
}
ierr += getPrimaryArrival(data.obs[iobs].header, &pickTime, phaseName);
if (ierr != 0)
{
fprintf(stderr, "%s: Error getting primary pick\n", __func__);
break;
}
// Need to figure out the component
icomp = 1;
if (kcmpnm[2] == 'Z' || kcmpnm[2] == 'z' || kcmpnm[2] == '1')
{
icomp = 1;
}
else if (kcmpnm[2] == 'N' || kcmpnm[2] == 'n' || kcmpnm[2] == '2')
{
icomp = 2;
}
else if (kcmpnm[2] == 'E' || kcmpnm[2] == 'e' || kcmpnm[2] == '3')
{
icomp = 3;
}
else
{
fprintf(stderr, "%s: Can't classify component: %s\n",
__func__, kcmpnm);
}
// Process all Green's functions in this block
for (id=0; id<ffGrns.ndepth; id++)
{
for (it=0; it<ffGrns.ntstar; it++)
{
idx = tdsearch_hudson_observationDepthTstarToIndex(iobs, id, it,
ffGrns);
kndx = 10*idx;
sacio_getFloatHeader(SAC_FLOAT_O, ffGrns.grns[kndx].header, &o);
getPrimaryArrival(ffGrns.grns[kndx].header,
&pickTimeGrns, phaseNameGrns);
if (strcasecmp(phaseNameGrns, phaseName) != 0)
{
fprintf(stdout, "%s: Phase name mismatch %s %s\n",
__func__, phaseName, phaseNameGrns);
}
npts = ffGrns.grns[kndx].npts;
indx = tdsearch_greens_getGreensFunctionIndex(G11_GRNS,
iobs, it, id,
*grns);
for (i=0; i<6; i++)
{
sacio_copy(ffGrns.grns[kndx], &grns->grns[indx+i]);
if (data.obs[iobs].pz.lhavePZ)
{
sacio_copyPolesAndZeros(data.obs[iobs].pz,
&grns->grns[indx+i].pz);
}
sacio_setFloatHeader(SAC_FLOAT_AZ, az,
&grns->grns[indx+i].header);
sacio_setFloatHeader(SAC_FLOAT_BAZ, baz,
&grns->grns[indx+i].header);
sacio_setFloatHeader(SAC_FLOAT_CMPAZ, cmpaz,
&grns->grns[indx+i].header);
sacio_setFloatHeader(SAC_FLOAT_CMPINC, cmpinc,
&grns->grns[indx+i].header);
sacio_setFloatHeader(SAC_FLOAT_EVLA, evla,
&grns->grns[indx+i].header);
sacio_setFloatHeader(SAC_FLOAT_EVLO, evlo,
&grns->grns[indx+i].header);
sacio_setFloatHeader(SAC_FLOAT_STLA, stla,
&grns->grns[indx+i].header);
sacio_setFloatHeader(SAC_FLOAT_STLO, stlo,
&grns->grns[indx+i].header);
sacio_setFloatHeader(SAC_FLOAT_STEL, stel,
&grns->grns[indx+i].header);
sacio_setCharacterHeader(SAC_CHAR_KNETWK, knetwk,
&grns->grns[indx+i].header);
sacio_setCharacterHeader(SAC_CHAR_KSTNM, kstnm,
&grns->grns[indx+i].header);
sacio_setCharacterHeader(SAC_CHAR_KHOLE, khole,
&grns->grns[indx+i].header);
sacio_setCharacterHeader(SAC_CHAR_KCMPNM, kcmpnms[i],
&grns->grns[indx+i].header);
sacio_setCharacterHeader(SAC_CHAR_KEVNM, "SYNTHETIC\0",
&grns->grns[indx+i].header);
// Set the start time by aligning on the arrival
epochNew = epoch + (pickTime - o) - pickTimeGrns;
sacio_setEpochalStartTime(epochNew,
&grns->grns[indx+i].header);
// Update the pick times
for (l=0; l<11; l++)
{
ierr = sacio_getFloatHeader(pickVars[l],
grns->grns[indx+i].header,
&pick);
if (ierr == 0)
{
pick = pick + o;
sacio_setFloatHeader(pickVars[l],
pick,
&grns->grns[indx+i].header);
}
}
}
ierr = parmt_utils_ff2mtGreens64f(npts, icomp,
az, baz,
cmpaz, cmpincSEED,
ffGrns.grns[kndx+0].data,
ffGrns.grns[kndx+1].data,
ffGrns.grns[kndx+2].data,
ffGrns.grns[kndx+3].data,
ffGrns.grns[kndx+4].data,
ffGrns.grns[kndx+5].data,
ffGrns.grns[kndx+6].data,
ffGrns.grns[kndx+7].data,
ffGrns.grns[kndx+8].data,
ffGrns.grns[kndx+9].data,
grns->grns[indx+0].data,
grns->grns[indx+1].data,
grns->grns[indx+2].data,
grns->grns[indx+3].data,
grns->grns[indx+4].data,
grns->grns[indx+5].data);
if (ierr != 0)
{
fprintf(stderr, "%s: Failed to rotate Greens functions\n",
__func__);
}
// Fix the characteristic magnitude scaling in CPS
for (i=0; i<6; i++)
{
cblas_dscal(npts, xscal, grns->grns[indx+i].data, 1);
}
}
}
}
return 0;
}
//============================================================================//
/*!
* @brief Repicks the Green's functions onset time with an STA/LTA picker.
*
* @param[in] sta Short term average window length (seconds).
* @param[in] lta Long term average window length (seconds).
* @param[in] threshPct Percentage of max STA/LTA after which an arrival
* is declared.
* @param[in] iobs C numbered observation index.
* @param[in] itstar C numbered t* index.
* @param[in] idepth C numbered depth index.
*
* @param[in,out] grns On input contains the Green's functions.
* On output the first arrival time has been modified
* with an STA/LTA picker.
*
* @brief 0 indicates success.
*
* @ingroup tdsearch_greens
*
* @author Ben Baker, ISTI
*
*/
int tdsearch_greens_repickGreensWithSTALTA(
const double sta, const double lta, const double threshPct,
const int iobs, const int itstar, const int idepth,
struct tdSearchGreens_struct *grns)
{
struct stalta_struct stalta;
double *charFn, *g, *Gxx, *Gyy, *Gzz, *Gxy, *Gxz, *Gyz,
*gxxPad, *gyyPad, *gzzPad, *gxyPad, *gxzPad, *gyzPad,
charMax, dt, tpick;
int indices[6], ierr, k, npts, nlta, npad, nsta, nwork, prePad;
// Check STA/LTA
ierr = 0;
memset(&stalta, 0, sizeof(struct stalta_struct));
if (lta < sta || sta < 0.0)
{
if (lta < sta){fprintf(stderr,"%s: Error lta < sta\n", __func__);}
if (sta < 0.0){fprintf(stderr,"%s: Error sta is negative\n", __func__);}
return -1;
}
ierr = tdsearch_greens_getGreensFunctionsIndices(iobs, itstar, idepth,
*grns, indices);
if (ierr != 0)
{
fprintf(stderr, "%s: Failed to get Greens functions indicies\n",
__func__);
return -1;
}
ierr = sacio_getIntegerHeader(SAC_INT_NPTS,
grns->grns[indices[0]].header, &npts);
if (ierr != 0 || npts < 1)
{
if (ierr != 0)
{
fprintf(stderr, "%s: Error getting number of points from header\n",
__func__);
}
else
{
fprintf(stderr, "%s: ERror no data points\n", __func__);
}
return -1;
}
ierr = sacio_getFloatHeader(SAC_FLOAT_DELTA,
grns->grns[indices[0]].header, &dt);
if (ierr != 0 || dt <= 0.0)
{
if (ierr != 0){fprintf(stderr, "%s: failed to get dt\n", __func__);}
if (dt <= 0.0){fprintf(stderr, "%s: invalid sampling period\n", __func__);}
return -1;
}
// Define the windows
nsta = (int) (sta/dt + 0.5);
nlta = (int) (lta/dt + 0.5);
prePad = MAX(64, fft_nextpow2(nlta, &ierr));
npad = prePad + npts;
// Set space
gxxPad = memory_calloc64f(npad);
gyyPad = memory_calloc64f(npad);
gzzPad = memory_calloc64f(npad);
gxyPad = memory_calloc64f(npad);
gxzPad = memory_calloc64f(npad);
gyzPad = memory_calloc64f(npad);
charFn = memory_calloc64f(npad);
// Reference pointers
Gxx = grns->grns[indices[0]].data;
Gyy = grns->grns[indices[1]].data;
Gzz = grns->grns[indices[2]].data;
Gxy = grns->grns[indices[3]].data;
Gxz = grns->grns[indices[4]].data;
Gyz = grns->grns[indices[5]].data;
// Pre-pad signals
array_set64f_work(prePad, Gxx[0], gxxPad);
array_set64f_work(prePad, Gyy[0], gyyPad);
array_set64f_work(prePad, Gzz[0], gzzPad);
array_set64f_work(prePad, Gxy[0], gxyPad);
array_set64f_work(prePad, Gxz[0], gxzPad);
array_set64f_work(prePad, Gyz[0], gyzPad);
// Copy rest of array
array_copy64f_work(npts, Gxx, &gxxPad[prePad]);
array_copy64f_work(npts, Gyy, &gyyPad[prePad]);
array_copy64f_work(npts, Gzz, &gzzPad[prePad]);
array_copy64f_work(npts, Gxy, &gxyPad[prePad]);
array_copy64f_work(npts, Gxz, &gxzPad[prePad]);
array_copy64f_work(npts, Gyz, &gyzPad[prePad]);
// apply the sta/lta
for (k=0; k<6; k++)
{
g = NULL;
if (k == 0)
{
g = gxxPad;
}
else if (k == 1)
{
g = gyyPad;
}
else if (k == 2)
{
g = gzzPad;
}
else if (k == 3)
{
g = gxyPad;
}
else if (k == 4)
{
g = gxzPad;
}
else if (k == 5)
{
g = gyzPad;
}
ierr = stalta_setShortAndLongTermAverage(nsta, nlta, &stalta);
if (ierr != 0)
{
printf("%s: Error setting STA/LTA\n", __func__);
break;
}
ierr = stalta_setData64f(npad, g, &stalta);
if (ierr != 0)
{
printf("%s: Error setting data\n", __func__);
break;
}
ierr = stalta_applySTALTA(&stalta);
if (ierr != 0)
{
printf("%s: Error applying STA/LTA\n", __func__);
break;
}
ierr = stalta_getData64f(stalta, npad, &nwork, g);
if (ierr != 0)
{
printf("%s: Error getting result\n", __func__);
break;
}
cblas_daxpy(npad, 1.0, g, 1, charFn, 1);
stalta_resetInitialConditions(&stalta);
stalta_resetFinalConditions(&stalta);
g = NULL;
}
// Compute the pick time
charMax = array_max64f(npts, &charFn[prePad], &ierr);
tpick =-1.0;
for (k=prePad; k<npad; k++)
{
if (charFn[k] > 0.01*threshPct*charMax)
{
tpick = (double) (k - prePad)*dt;
break;
}
}
if (tpick ==-1.0)
{
tpick = (double) (array_argmax64f(npad, charFn, &ierr) - prePad)*dt;
}
// Overwrite the pick; by this point should be on SAC_FLOAT_A
//double apick;
//sacio_getFloatHeader(SAC_FLOAT_A, grns->grns[indices[0]].header, &apick);
for (k=0; k<6; k++)
{
sacio_setFloatHeader(SAC_FLOAT_A, tpick,
&grns->grns[indices[k]].header);
}
// Dereference pointers and free space
Gxx = NULL;
Gyy = NULL;
Gzz = NULL;
Gxy = NULL;
Gxz = NULL;
Gyz = NULL;
memory_free64f(&gxxPad);
memory_free64f(&gyyPad);
memory_free64f(&gzzPad);
memory_free64f(&gxyPad);
memory_free64f(&gxzPad);
memory_free64f(&gyzPad);
memory_free64f(&charFn);
stalta_free(&stalta);
return ierr;
}
//============================================================================//
/*!
* @brief Modifies the Green's functions processing commands.
*
* @param[in] iodva The output units for the hudson96 Green's functions.
* @param[in] iodva 0 indicates the Green's functions have units
* of displacement.
* @param[in] iodva 1 indicates the Green's functions have units
* of velocity.
* @param[in] iodva 2 indicates the Green's functions have units
* of acceleration.
* @param[in] cut0 The cut time in seconds relative to the pick time
* to begin the window around the arrival.
* @parma[in] cut1 The cut time in seconds relative to the pick time
* to end the window around the arrival.
* @param[in] targetDt Desired sampling period in seconds to which the Green's
* functions should be resampled as to match the data.
*
* @param[in,out] grns On input input contains the genreci Green's functions
* processing commands.
* @param[in,out] grns On exit the Green's functions processing have been
* made specific to the input Green's functions.
*
* @result 0 indicates success.
*
* @ingroup tdsearch_greens
*
*/
int tdsearch_greens_modifyProcessingCommands(
const int iodva,
const double cut0, const double cut1, const double targetDt,
struct tdSearchGreens_struct *grns)
{
struct tdSearchModifyCommands_struct options;
const char **cmds;
char **newCmds;
size_t lenos;
int i, ierr, iobs, k, kndx1, kndx2, ncmds;
ierr = 0;
grns->cmdsGrns = (struct tdSearchDataProcessingCommands_struct *)
calloc((size_t) grns->ngrns,
sizeof(struct tdSearchDataProcessingCommands_struct));
for (iobs=0; iobs<grns->nobs; iobs++)
{
newCmds = NULL;
ncmds = grns->cmds[iobs].ncmds;
if (ncmds < 1){continue;} // Nothing to do
cmds = (const char **) grns->cmds[iobs].cmds;
options.cut0 = cut0;
options.cut1 = cut1;
options.targetDt = targetDt;
options.ldeconvolution = false;
options.iodva = iodva;
kndx1 = iobs*(6*grns->ntstar*grns->ndepth);
kndx2 = (iobs+1)*(6*grns->ntstar*grns->ndepth);
newCmds = tdsearch_commands_modifyCommands(ncmds, (const char **) cmds,
options,
grns->grns[kndx1], &ierr);
if (ierr != 0)
{
fprintf(stderr, "%s: Failed to set processing commands\n", __func__);
goto ERROR;
}
// Expand the processing commands
for (k=kndx1; k<kndx2; k++)
{
grns->cmdsGrns[k].ncmds = ncmds;
grns->cmdsGrns[k].cmds = (char **)
calloc((size_t) ncmds, sizeof(char *));
for (i=0; i<ncmds; i++)
{
lenos = strlen(newCmds[i]);
grns->cmdsGrns[k].cmds[i] = (char *)
calloc(lenos+1, sizeof(char));
strcpy(grns->cmdsGrns[k].cmds[i], newCmds[i]);
}
}
// Release the memory
if (newCmds != NULL)
{
for (i=0; i<ncmds; i++)
{
if (newCmds[i] != NULL){free(newCmds[i]);}
}
free(newCmds);
}
}
ERROR:;
return ierr;
}
//============================================================================//
/*!
* @brief Processes the Green's functions.
*
* @param[in,out] grns On input contains the Green's functions for all
* observations, depths, and t*'s as well as the
* processing chains.
* On output contains the filtered Green's functions
* for all observations, depths, and t*'s.
*
* @result 0 indicates success.
*
* @ingroup tdsearch_greens
*
* @author Ben Baker, ISTI
*
*/
int tdsearch_greens_process(struct tdSearchGreens_struct *grns)
{
double *data;
struct serialCommands_struct commands;
struct parallelCommands_struct parallelCommands;
double dt, dt0, epoch, epoch0, time;
int dataPtr[7], i, i0, ierr, iobs, idep, it, kndx, l, npts, npts0, nq,
nwork, ny, ns;
bool lnewDt, lnewStartTime;
const int nsignals = 6;
const int nTimeVars = 12;
const enum sacHeader_enum timeVars[12]
= {SAC_FLOAT_A, SAC_FLOAT_O,
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};
// Loop on the observations
for (iobs=0; iobs<grns->nobs; iobs++)
{
for (idep=0; idep<grns->ndepth; idep++)
{
for (it=0; it<grns->ntstar; it++)
{
memset(¶llelCommands, 0,
sizeof(struct parallelCommands_struct));
memset(&commands, 0, sizeof(struct serialCommands_struct));
kndx = tdsearch_greens_getGreensFunctionIndex(G11_GRNS,
iobs, it, idep,
*grns);
ierr = process_stringsToSerialCommandsOptions(
grns->cmdsGrns[kndx].ncmds,
(const char **) grns->cmdsGrns[kndx].cmds,
&commands);
if (ierr != 0)
{
fprintf(stderr, "%s: Error setting serial command string\n", __func__);
goto ERROR;
}
// Determine some characteristics of the processing
sacio_getEpochalStartTime(grns->grns[kndx].header, &epoch0);
sacio_getFloatHeader(SAC_FLOAT_DELTA,
grns->grns[kndx].header, &dt0);
lnewDt = false;
lnewStartTime = false;
epoch = epoch0;
dt = dt0;
for (i=0; i<commands.ncmds; i++)
{
if (commands.commands[i].type == CUT_COMMAND)
{
i0 = commands.commands[i].cut.i0;
epoch = epoch + (double) i0*dt;
lnewStartTime = true;
}
if (commands.commands[i].type == DOWNSAMPLE_COMMAND)
{
nq = commands.commands[i].downsample.nq;
dt = dt*(double) nq;
lnewDt = true;
}
if (commands.commands[i].type == DECIMATE_COMMAND)
{
nq = commands.commands[i].decimate.nqAll;
dt = dt*(double) nq;
lnewDt = true;
}
}
dataPtr[0] = 0;
for (i=0; i<nsignals; i++)
{
dataPtr[i+1] = dataPtr[i] + grns->grns[kndx+i].npts;
}
process_setCommandOnAllParallelCommands(nsignals, commands,
¶llelCommands);
data = memory_calloc64f(dataPtr[nsignals]);
for (i=0; i<nsignals; i++)
{
ierr = array_copy64f_work(grns->grns[kndx+i].npts,
grns->grns[kndx+i].data,
&data[dataPtr[i]]);
if (ierr != 0)
{
fprintf(stderr, "%s: Failed to copy data\n", __func__);
goto ERROR;
}
}
ierr = process_setParallelCommandsData64f(nsignals, dataPtr,
data,
¶llelCommands);
if (ierr != 0)
{
fprintf(stderr, "%s: Failed to set data\n", __func__);
goto ERROR;
}
ierr = process_applyParallelCommands(¶llelCommands);
if (ierr != 0)
{
fprintf(stderr ,"%s: Failed to process data\n", __func__);
goto ERROR;
}
// Get the data
nwork = dataPtr[nsignals];
ierr = process_getParallelCommandsData64f(parallelCommands,
-1, nsignals,
&ny, &ns,
dataPtr, data);
if (ny > nwork)
{
memory_free64f(&data);
data = memory_calloc64f(ny);
}
nwork = ny;
ierr = process_getParallelCommandsData64f(parallelCommands,
nwork, nsignals,
&ny, &ns,
dataPtr, data);
for (i=0; i<nsignals; i++)
{
sacio_getIntegerHeader(SAC_INT_NPTS,
grns->grns[kndx+i].header, &npts0);
npts = dataPtr[i+1] - dataPtr[i];
// Resize event
if (npts != npts0)
{
sacio_freeData(&grns->grns[kndx+i]);
grns->grns[kndx+i].data = sacio_malloc64f(npts);
grns->grns[kndx+i].npts = npts;
sacio_setIntegerHeader(SAC_INT_NPTS, npts,
&grns->grns[kndx+i].header);
ierr = array_copy64f_work(npts,
&data[dataPtr[i]],
grns->grns[kndx+i].data);
}
else
{
ierr = array_copy64f_work(npts,
&data[dataPtr[i]],
grns->grns[kndx+i].data);
}
}
// Update the times
if (lnewStartTime)
{
for (i=0; i<nsignals; i++)
{
// Update the picks
for (l=0; l<nTimeVars; l++)
{
ierr = sacio_getFloatHeader(timeVars[l],
grns->grns[kndx+i].header, &time);
if (ierr == 0)
{
time = time + epoch0; // Turn to real time
time = time - epoch; // Relative to new time
sacio_setFloatHeader(timeVars[l], time,
&grns->grns[kndx+i].header);
}
} // Loop on picks
sacio_setEpochalStartTime(epoch,
&grns->grns[kndx+i].header);
} // Loop on signals
}
// Update the sampling period
if (lnewDt)
{
for (i=0; i<nsignals; i++)
{
sacio_setFloatHeader(SAC_FLOAT_DELTA, dt,
&grns->grns[kndx+i].header);
}
}
process_freeSerialCommands(&commands);
process_freeParallelCommands(¶llelCommands);
memory_free64f(&data);
//TODO fix this
tdsearch_greens_repickGreensWithSTALTA(2.0, 10.0, 80.0, iobs, it, idep, grns);
}
}
}
ERROR:;
return 0;
}
//============================================================================//
/*!
* @brief Writes the Green's functions corresponding to the iobs'th observation
* for the given tstar, depth index.
*
* @param[in] dirnm Directory name where the Green's functions should be
* written. If this is NULL then the Green's functions
* will be written to the current working directory.
* @param[in] iobs Observation index in the range [0,nobs-1].
* @param[in] itstar The t* index in the range [0,ntstar-1].
* @param[in] idepth The depth index in the range [0,ndepth-1].
* @param[in] grns The structure containing the Green's functions.
*
* @result 0 indicates success.
*
* @ingroup tdsearch_greens
*
*/
int tdsearch_greens_writeSelectGreensFunctions(
const char *dirnm,
const int iobs, const int itstar, const int idepth,
const struct tdSearchGreens_struct grns)
{
char fileName[PATH_MAX], rootName[PATH_MAX];
size_t lenos;
int i, ierr, indx;
memset(rootName, 0, PATH_MAX*sizeof(char));
if (dirnm == NULL)
{
strcpy(rootName, "./\0");
}
else
{
lenos = strlen(dirnm);
if (lenos > 0)
{
strcpy(rootName, dirnm);
if (rootName[lenos-1] != '/'){strcat(rootName, "/\0");}
}
else
{
strcpy(rootName, "./\0");
}
}
if (!os_path_isdir(rootName))
{
ierr = os_makedirs(rootName);
if (ierr != 0)
{
fprintf(stderr, "%s: Failed to make output directory %s\n",
__func__, rootName);
return -1;
}
}
// Get the indices to write
indx = tdsearch_greens_getGreensFunctionIndex(G11_GRNS,
iobs, itstar, idepth,
grns);
if (indx < 0)
{
fprintf(stderr, "%s: Invalid index\n", __func__);
return -1;
}
for (i=0; i<6; i++)
{
memset(fileName, 0, PATH_MAX*sizeof(char));
sprintf(fileName, "%s%s.%s.%s.%s.DEPTH_%d.TSTAR_%d.SAC",
rootName, grns.grns[indx+i].header.knetwk,
grns.grns[indx+i].header.kstnm,
grns.grns[indx+i].header.kcmpnm,
grns.grns[indx+i].header.khole, idepth, itstar);
sacio_writeTimeSeriesFile(fileName, grns.grns[indx+i]);
}
return 0;
}
//============================================================================//
static int getPrimaryArrival(const struct sacHeader_struct hdr,
double *time, char phaseName[8])
{
const enum sacHeader_enum timeVars[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 timeVarNames[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};
int i, ifound1, ifound2;
memset(phaseName, 0, 8*sizeof(char));
for (i=0; i<11; i++)
{
ifound1 = sacio_getFloatHeader(timeVars[i], hdr, time);
ifound2 = sacio_getCharacterHeader(timeVarNames[i], hdr, phaseName);
if (ifound1 == 0 && ifound2 == 0){return 0;}
}
printf("%s: Failed to get primary pick\n", __func__);
*time =-12345.0;
memset(phaseName, 0, 8*sizeof(char));
strcpy(phaseName, "-12345");
return -1;
}
| {
"alphanum_fraction": 0.4762627164,
"avg_line_length": 38.8086580087,
"ext": "c",
"hexsha": "ae3e33e621a99d46f63828cecef62e86a5679c46",
"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": "fc65471b097aa6a92fcaf558dfa50622345c4025",
"max_forks_repo_licenses": [
"Intel"
],
"max_forks_repo_name": "bakerb845/tdsearch",
"max_forks_repo_path": "src/greens.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "fc65471b097aa6a92fcaf558dfa50622345c4025",
"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/tdsearch",
"max_issues_repo_path": "src/greens.c",
"max_line_length": 91,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "fc65471b097aa6a92fcaf558dfa50622345c4025",
"max_stars_repo_licenses": [
"Intel"
],
"max_stars_repo_name": "bakerb845/tdsearch",
"max_stars_repo_path": "src/greens.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 11023,
"size": 44824
} |
/* linalg/test_lq.c
*
* Copyright (C) 2018 Patrick Alken
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include <config.h>
#include <stdlib.h>
#include <gsl/gsl_test.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_ieee_utils.h>
#include <gsl/gsl_permute_vector.h>
#include <gsl/gsl_blas.h>
#include <gsl/gsl_linalg.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_permutation.h>
int test_LQ_solve_dim(const gsl_matrix * m, const double * actual, double eps);
int test_LQ_solve(void);
int test_LQ_LQsolve_dim(const gsl_matrix * m, const double * actual, double eps);
int test_LQ_LQsolve(void);
int test_LQ_lssolve_T_dim(const gsl_matrix * m, const double * actual, double eps);
int test_LQ_lssolve_T(void);
int test_LQ_lssolve_dim(const gsl_matrix * m, const double * actual, double eps);
int test_LQ_lssolve(void);
int test_LQ_decomp_dim(const gsl_matrix * m, double eps);
int test_LQ_decomp(void);
int test_PTLQ_solve_dim(const gsl_matrix * m, const double * actual, double eps);
int test_PTLQ_solve(void);
int test_PTLQ_LQsolve_dim(const gsl_matrix * m, const double * actual, double eps);
int test_PTLQ_LQsolve(void);
int test_PTLQ_decomp_dim(const gsl_matrix * m, double eps);
int test_PTLQ_decomp(void);
int test_LQ_update_dim(const gsl_matrix * m, double eps);
int test_LQ_update(void);
int
test_LQ_solve_dim(const gsl_matrix * m, const double * actual, double eps)
{
int s = 0;
unsigned long i, dim = m->size1;
gsl_vector * rhs = gsl_vector_alloc(dim);
gsl_matrix * lq = gsl_matrix_alloc(dim,dim);
gsl_vector * d = gsl_vector_alloc(dim);
gsl_vector * x = gsl_vector_alloc(dim);
gsl_matrix_transpose_memcpy(lq,m);
for(i=0; i<dim; i++) gsl_vector_set(rhs, i, i+1.0);
s += gsl_linalg_LQ_decomp(lq, d);
s += gsl_linalg_LQ_solve_T(lq, d, rhs, x);
for(i=0; i<dim; i++) {
int foo = check(gsl_vector_get(x, i), actual[i], eps);
if(foo) {
printf("%3lu[%lu]: %22.18g %22.18g\n", dim, i, gsl_vector_get(x, i), actual[i]);
}
s += foo;
}
gsl_vector_free(x);
gsl_vector_free(d);
gsl_matrix_free(lq);
gsl_vector_free(rhs);
return s;
}
int
test_LQ_solve(void)
{
int f;
int s = 0;
f = test_LQ_solve_dim(hilb2, hilb2_solution, 2 * 8.0 * GSL_DBL_EPSILON);
gsl_test(f, " LQ_solve hilbert(2)");
s += f;
f = test_LQ_solve_dim(hilb3, hilb3_solution, 2 * 64.0 * GSL_DBL_EPSILON);
gsl_test(f, " LQ_solve hilbert(3)");
s += f;
f = test_LQ_solve_dim(hilb4, hilb4_solution, 4 * 1024.0 * GSL_DBL_EPSILON);
gsl_test(f, " LQ_solve hilbert(4)");
s += f;
f = test_LQ_solve_dim(hilb12, hilb12_solution, 0.5);
gsl_test(f, " LQ_solve hilbert(12)");
s += f;
f = test_LQ_solve_dim(vander2, vander2_solution, 8.0 * GSL_DBL_EPSILON);
gsl_test(f, " LQ_solve vander(2)");
s += f;
f = test_LQ_solve_dim(vander3, vander3_solution, 64.0 * GSL_DBL_EPSILON);
gsl_test(f, " LQ_solve vander(3)");
s += f;
f = test_LQ_solve_dim(vander4, vander4_solution, 1024.0 * GSL_DBL_EPSILON);
gsl_test(f, " LQ_solve vander(4)");
s += f;
f = test_LQ_solve_dim(vander12, vander12_solution, 0.05);
gsl_test(f, " LQ_solve vander(12)");
s += f;
return s;
}
int
test_LQ_LQsolve_dim(const gsl_matrix * m, const double * actual, double eps)
{
int s = 0;
unsigned long i, dim = m->size1;
gsl_vector * rhs = gsl_vector_alloc(dim);
gsl_matrix * lq = gsl_matrix_alloc(dim,dim);
gsl_matrix * q = gsl_matrix_alloc(dim,dim);
gsl_matrix * l = gsl_matrix_alloc(dim,dim);
gsl_vector * d = gsl_vector_alloc(dim);
gsl_vector * x = gsl_vector_alloc(dim);
gsl_matrix_transpose_memcpy(lq,m);
for(i=0; i<dim; i++) gsl_vector_set(rhs, i, i+1.0);
s += gsl_linalg_LQ_decomp(lq, d);
s += gsl_linalg_LQ_unpack(lq, d, q, l);
s += gsl_linalg_LQ_LQsolve(q, l, rhs, x);
for(i=0; i<dim; i++) {
int foo = check(gsl_vector_get(x, i), actual[i], eps);
if(foo) {
printf("%3lu[%lu]: %22.18g %22.18g\n", dim, i, gsl_vector_get(x, i), actual[i]);
}
s += foo;
}
gsl_vector_free(x);
gsl_vector_free(d);
gsl_matrix_free(lq);
gsl_matrix_free(q);
gsl_matrix_free(l);
gsl_vector_free(rhs);
return s;
}
int
test_LQ_LQsolve(void)
{
int f;
int s = 0;
f = test_LQ_LQsolve_dim(hilb2, hilb2_solution, 2 * 8.0 * GSL_DBL_EPSILON);
gsl_test(f, " LQ_LQsolve hilbert(2)");
s += f;
f = test_LQ_LQsolve_dim(hilb3, hilb3_solution, 2 * 64.0 * GSL_DBL_EPSILON);
gsl_test(f, " LQ_LQsolve hilbert(3)");
s += f;
f = test_LQ_LQsolve_dim(hilb4, hilb4_solution, 4 * 1024.0 * GSL_DBL_EPSILON);
gsl_test(f, " LQ_LQsolve hilbert(4)");
s += f;
f = test_LQ_LQsolve_dim(hilb12, hilb12_solution, 0.5);
gsl_test(f, " LQ_LQsolve hilbert(12)");
s += f;
f = test_LQ_LQsolve_dim(vander2, vander2_solution, 8.0 * GSL_DBL_EPSILON);
gsl_test(f, " LQ_LQsolve vander(2)");
s += f;
f = test_LQ_LQsolve_dim(vander3, vander3_solution, 64.0 * GSL_DBL_EPSILON);
gsl_test(f, " LQ_LQsolve vander(3)");
s += f;
f = test_LQ_LQsolve_dim(vander4, vander4_solution, 1024.0 * GSL_DBL_EPSILON);
gsl_test(f, " LQ_LQsolve vander(4)");
s += f;
f = test_LQ_LQsolve_dim(vander12, vander12_solution, 0.05);
gsl_test(f, " LQ_LQsolve vander(12)");
s += f;
return s;
}
int
test_LQ_lssolve_T_dim(const gsl_matrix * m, const double * actual, double eps)
{
int s = 0;
unsigned long i, M = m->size1, N = m->size2;
gsl_vector * rhs = gsl_vector_alloc(M);
gsl_matrix * lq = gsl_matrix_alloc(N,M);
gsl_vector * d = gsl_vector_alloc(N);
gsl_vector * x = gsl_vector_alloc(N);
gsl_vector * r = gsl_vector_alloc(M);
gsl_vector * res = gsl_vector_alloc(M);
gsl_matrix_transpose_memcpy(lq,m);
for(i=0; i<M; i++) gsl_vector_set(rhs, i, i+1.0);
s += gsl_linalg_LQ_decomp(lq, d);
s += gsl_linalg_LQ_lssolve_T(lq, d, rhs, x, res);
for(i=0; i<N; i++) {
int foo = check(gsl_vector_get(x, i), actual[i], eps);
if(foo) {
printf("(%3lu,%3lu)[%lu]: %22.18g %22.18g\n", M, N, i, gsl_vector_get(x, i), actual[i]);
}
s += foo;
}
/* compute residual r = b - m x */
if (M == N) {
gsl_vector_set_zero(r);
} else {
gsl_vector_memcpy(r, rhs);
gsl_blas_dgemv(CblasNoTrans, -1.0, m, x, 1.0, r);
};
for(i=0; i<N; i++) {
int foo = check(gsl_vector_get(res, i), gsl_vector_get(r,i), sqrt(eps));
if(foo) {
printf("(%3lu,%3lu)[%lu]: %22.18g %22.18g\n", M, N, i, gsl_vector_get(res, i), gsl_vector_get(r,i));
}
s += foo;
}
gsl_vector_free(r);
gsl_vector_free(res);
gsl_vector_free(x);
gsl_vector_free(d);
gsl_matrix_free(lq);
gsl_vector_free(rhs);
return s;
}
int
test_LQ_lssolve_dim(const gsl_matrix * m, const double * actual, double eps)
{
int s = 0;
unsigned long i, M = m->size1, N = m->size2;
gsl_vector * rhs = gsl_vector_alloc(M);
gsl_matrix * lq = gsl_matrix_alloc(M, N);
gsl_vector * tau = gsl_vector_alloc(N);
gsl_vector * x = gsl_vector_alloc(N);
gsl_vector * r = gsl_vector_alloc(M);
gsl_vector * res = gsl_vector_alloc(M);
for (i = 0; i < M; i++)
gsl_vector_set(rhs, i, i + 1.0);
gsl_matrix_memcpy(lq, m);
gsl_linalg_LQ_decomp(lq, tau);
gsl_linalg_LQ_lssolve(lq, tau, rhs, x, res);
for (i = 0; i < N; i++)
{
int foo = check(gsl_vector_get(x, i), actual[i], eps);
if(foo) {
printf("(%3lu,%3lu)[%lu]: %22.18g %22.18g\n", M, N, i, gsl_vector_get(x, i), actual[i]);
}
s += foo;
}
/* compute residual r = b - m x */
if (M == N) {
gsl_vector_set_zero(r);
} else {
gsl_vector_memcpy(r, rhs);
gsl_blas_dgemv(CblasNoTrans, -1.0, m, x, 1.0, r);
};
for (i = 0; i < N; i++)
{
int foo = check(gsl_vector_get(res, i), gsl_vector_get(r,i), sqrt(eps));
if(foo) {
printf("(%3lu,%3lu)[%lu]: %22.18g %22.18g\n", M, N, i, gsl_vector_get(res, i), gsl_vector_get(r,i));
}
s += foo;
}
gsl_vector_free(r);
gsl_vector_free(res);
gsl_vector_free(x);
gsl_vector_free(tau);
gsl_matrix_free(lq);
gsl_vector_free(rhs);
return s;
}
int
test_LQ_lssolve_T(void)
{
int f;
int s = 0;
f = test_LQ_lssolve_T_dim(m53, m53_lssolution, 2 * 64.0 * GSL_DBL_EPSILON);
gsl_test(f, " LQ_lssolve_T m(5,3)");
s += f;
f = test_LQ_lssolve_T_dim(hilb2, hilb2_solution, 2 * 8.0 * GSL_DBL_EPSILON);
gsl_test(f, " LQ_lssolve_T hilbert(2)");
s += f;
f = test_LQ_lssolve_T_dim(hilb3, hilb3_solution, 2 * 64.0 * GSL_DBL_EPSILON);
gsl_test(f, " LQ_lssolve_T hilbert(3)");
s += f;
f = test_LQ_lssolve_T_dim(hilb4, hilb4_solution, 4 * 1024.0 * GSL_DBL_EPSILON);
gsl_test(f, " LQ_lssolve_T hilbert(4)");
s += f;
f = test_LQ_lssolve_T_dim(hilb12, hilb12_solution, 0.5);
gsl_test(f, " LQ_lssolve_T hilbert(12)");
s += f;
f = test_LQ_lssolve_T_dim(vander2, vander2_solution, 8.0 * GSL_DBL_EPSILON);
gsl_test(f, " LQ_lssolve_T vander(2)");
s += f;
f = test_LQ_lssolve_T_dim(vander3, vander3_solution, 64.0 * GSL_DBL_EPSILON);
gsl_test(f, " LQ_lssolve_T vander(3)");
s += f;
f = test_LQ_lssolve_T_dim(vander4, vander4_solution, 1024.0 * GSL_DBL_EPSILON);
gsl_test(f, " LQ_lssolve_T vander(4)");
s += f;
f = test_LQ_lssolve_T_dim(vander12, vander12_solution, 0.05);
gsl_test(f, " LQ_lssolve_T vander(12)");
s += f;
return s;
}
int
test_LQ_lssolve(void)
{
int f;
int s = 0;
f = test_LQ_lssolve_dim(hilb2, hilb2_solution, 2 * 8.0 * GSL_DBL_EPSILON);
gsl_test(f, " LQ_lssolve hilbert(2)");
s += f;
f = test_LQ_lssolve_dim(hilb3, hilb3_solution, 2 * 64.0 * GSL_DBL_EPSILON);
gsl_test(f, " LQ_lssolve hilbert(3)");
s += f;
f = test_LQ_lssolve_dim(hilb4, hilb4_solution, 4 * 1024.0 * GSL_DBL_EPSILON);
gsl_test(f, " LQ_lssolve hilbert(4)");
s += f;
f = test_LQ_lssolve_dim(hilb12, hilb12_solution, 0.5);
gsl_test(f, " LQ_lssolve hilbert(12)");
s += f;
f = test_LQ_lssolve_dim(vander2, vander2_solution, 8.0 * GSL_DBL_EPSILON);
gsl_test(f, " LQ_lssolve vander(2)");
s += f;
f = test_LQ_lssolve_dim(vander3, vander3_solution, 64.0 * GSL_DBL_EPSILON);
gsl_test(f, " LQ_lssolve vander(3)");
s += f;
f = test_LQ_lssolve_dim(vander4, vander4_solution, 1024.0 * GSL_DBL_EPSILON);
gsl_test(f, " LQ_lssolve vander(4)");
s += f;
f = test_LQ_lssolve_dim(vander12, vander12_solution, 0.05);
gsl_test(f, " LQ_lssolve vander(12)");
s += f;
return s;
}
int
test_LQ_decomp_dim(const gsl_matrix * m, double eps)
{
int s = 0;
unsigned long i,j, M = m->size1, N = m->size2;
gsl_matrix * lq = gsl_matrix_alloc(M,N);
gsl_matrix * a = gsl_matrix_alloc(M,N);
gsl_matrix * q = gsl_matrix_alloc(N,N);
gsl_matrix * l = gsl_matrix_alloc(M,N);
gsl_vector * d = gsl_vector_alloc(GSL_MIN(M,N));
gsl_matrix_memcpy(lq,m);
s += gsl_linalg_LQ_decomp(lq, d);
s += gsl_linalg_LQ_unpack(lq, d, q, l);
/* compute a = q r */
gsl_blas_dgemm (CblasNoTrans, CblasNoTrans, 1.0, l, q, 0.0, a);
for(i=0; i<M; i++) {
for(j=0; j<N; j++) {
double aij = gsl_matrix_get(a, i, j);
double mij = gsl_matrix_get(m, i, j);
int foo = check(aij, mij, eps);
if(foo) {
printf("(%3lu,%3lu)[%lu,%lu]: %22.18g %22.18g\n", M, N, i,j, aij, mij);
}
s += foo;
}
}
gsl_vector_free(d);
gsl_matrix_free(lq);
gsl_matrix_free(a);
gsl_matrix_free(q);
gsl_matrix_free(l);
return s;
}
int
test_LQ_decomp(void)
{
int f;
int s = 0;
f = test_LQ_decomp_dim(m35, 2 * 8.0 * GSL_DBL_EPSILON);
gsl_test(f, " LQ_decomp m(3,5)");
s += f;
f = test_LQ_decomp_dim(m53, 2 * 64.0 * GSL_DBL_EPSILON);
gsl_test(f, " LQ_decomp m(5,3)");
s += f;
f = test_LQ_decomp_dim(hilb2, 2 * 8.0 * GSL_DBL_EPSILON);
gsl_test(f, " LQ_decomp hilbert(2)");
s += f;
f = test_LQ_decomp_dim(hilb3, 2 * 64.0 * GSL_DBL_EPSILON);
gsl_test(f, " LQ_decomp hilbert(3)");
s += f;
f = test_LQ_decomp_dim(hilb4, 4 * 1024.0 * GSL_DBL_EPSILON);
gsl_test(f, " LQ_decomp hilbert(4)");
s += f;
f = test_LQ_decomp_dim(hilb12, 2 * 1024.0 * GSL_DBL_EPSILON);
gsl_test(f, " LQ_decomp hilbert(12)");
s += f;
f = test_LQ_decomp_dim(vander2, 8.0 * GSL_DBL_EPSILON);
gsl_test(f, " LQ_decomp vander(2)");
s += f;
f = test_LQ_decomp_dim(vander3, 64.0 * GSL_DBL_EPSILON);
gsl_test(f, " LQ_decomp vander(3)");
s += f;
f = test_LQ_decomp_dim(vander4, 1024.0 * GSL_DBL_EPSILON);
gsl_test(f, " LQ_decomp vander(4)");
s += f;
f = test_LQ_decomp_dim(vander12, 0.0005); /* FIXME: bad accuracy */
gsl_test(f, " LQ_decomp vander(12)");
s += f;
return s;
}
int
test_PTLQ_solve_dim(const gsl_matrix * m, const double * actual, double eps)
{
int s = 0;
int signum;
unsigned long i, dim = m->size1;
gsl_permutation * perm = gsl_permutation_alloc(dim);
gsl_vector * rhs = gsl_vector_alloc(dim);
gsl_matrix * lq = gsl_matrix_alloc(dim,dim);
gsl_vector * d = gsl_vector_alloc(dim);
gsl_vector * x = gsl_vector_alloc(dim);
gsl_vector * norm = gsl_vector_alloc(dim);
gsl_matrix_transpose_memcpy(lq,m);
for(i=0; i<dim; i++) gsl_vector_set(rhs, i, i+1.0);
s += gsl_linalg_PTLQ_decomp(lq, d, perm, &signum, norm);
s += gsl_linalg_PTLQ_solve_T(lq, d, perm, rhs, x);
for(i=0; i<dim; i++) {
int foo = check(gsl_vector_get(x, i), actual[i], eps);
if(foo) {
printf("%3lu[%lu]: %22.18g %22.18g\n", dim, i, gsl_vector_get(x, i), actual[i]);
}
s += foo;
}
gsl_vector_free(norm);
gsl_vector_free(x);
gsl_vector_free(d);
gsl_matrix_free(lq);
gsl_vector_free(rhs);
gsl_permutation_free(perm);
return s;
}
int test_PTLQ_solve(void)
{
int f;
int s = 0;
f = test_PTLQ_solve_dim(hilb2, hilb2_solution, 2 * 8.0 * GSL_DBL_EPSILON);
gsl_test(f, " PTLQ_solve hilbert(2)");
s += f;
f = test_PTLQ_solve_dim(hilb3, hilb3_solution, 2 * 64.0 * GSL_DBL_EPSILON);
gsl_test(f, " PTLQ_solve hilbert(3)");
s += f;
f = test_PTLQ_solve_dim(hilb4, hilb4_solution, 2 * 2048.0 * GSL_DBL_EPSILON);
gsl_test(f, " PTLQ_solve hilbert(4)");
s += f;
f = test_PTLQ_solve_dim(hilb12, hilb12_solution, 0.5);
gsl_test(f, " PTLQ_solve hilbert(12)");
s += f;
f = test_PTLQ_solve_dim(vander2, vander2_solution, 8.0 * GSL_DBL_EPSILON);
gsl_test(f, " PTLQ_solve vander(2)");
s += f;
f = test_PTLQ_solve_dim(vander3, vander3_solution, 64.0 * GSL_DBL_EPSILON);
gsl_test(f, " PTLQ_solve vander(3)");
s += f;
f = test_PTLQ_solve_dim(vander4, vander4_solution, 1024.0 * GSL_DBL_EPSILON);
gsl_test(f, " PTLQ_solve vander(4)");
s += f;
f = test_PTLQ_solve_dim(vander12, vander12_solution, 0.05);
gsl_test(f, " PTLQ_solve vander(12)");
s += f;
return s;
}
int
test_PTLQ_LQsolve_dim(const gsl_matrix * m, const double * actual, double eps)
{
int s = 0;
int signum;
unsigned long i, dim = m->size1;
gsl_permutation * perm = gsl_permutation_alloc(dim);
gsl_vector * rhs = gsl_vector_alloc(dim);
gsl_matrix * lq = gsl_matrix_alloc(dim,dim);
gsl_matrix * q = gsl_matrix_alloc(dim,dim);
gsl_matrix * l = gsl_matrix_alloc(dim,dim);
gsl_vector * d = gsl_vector_alloc(dim);
gsl_vector * x = gsl_vector_alloc(dim);
gsl_vector * norm = gsl_vector_alloc(dim);
gsl_matrix_transpose_memcpy(lq,m);
for(i=0; i<dim; i++) gsl_vector_set(rhs, i, i+1.0);
s += gsl_linalg_PTLQ_decomp2(lq, q, l, d, perm, &signum, norm);
s += gsl_linalg_PTLQ_LQsolve_T(q, l, perm, rhs, x);
for(i=0; i<dim; i++) {
int foo = check(gsl_vector_get(x, i), actual[i], eps);
if(foo) {
printf("%3lu[%lu]: %22.18g %22.18g\n", dim, i, gsl_vector_get(x, i), actual[i]);
}
s += foo;
}
gsl_vector_free(norm);
gsl_vector_free(x);
gsl_vector_free(d);
gsl_matrix_free(lq);
gsl_vector_free(rhs);
gsl_permutation_free(perm);
return s;
}
int test_PTLQ_LQsolve(void)
{
int f;
int s = 0;
f = test_PTLQ_LQsolve_dim(hilb2, hilb2_solution, 2 * 8.0 * GSL_DBL_EPSILON);
gsl_test(f, " PTLQ_LQsolve hilbert(2)");
s += f;
f = test_PTLQ_LQsolve_dim(hilb3, hilb3_solution, 2 * 64.0 * GSL_DBL_EPSILON);
gsl_test(f, " PTLQ_LQsolve hilbert(3)");
s += f;
f = test_PTLQ_LQsolve_dim(hilb4, hilb4_solution, 2 * 2048.0 * GSL_DBL_EPSILON);
gsl_test(f, " PTLQ_LQsolve hilbert(4)");
s += f;
f = test_PTLQ_LQsolve_dim(hilb12, hilb12_solution, 0.5);
gsl_test(f, " PTLQ_LQsolve hilbert(12)");
s += f;
f = test_PTLQ_LQsolve_dim(vander2, vander2_solution, 8.0 * GSL_DBL_EPSILON);
gsl_test(f, " PTLQ_LQsolve vander(2)");
s += f;
f = test_PTLQ_LQsolve_dim(vander3, vander3_solution, 64.0 * GSL_DBL_EPSILON);
gsl_test(f, " PTLQ_LQsolve vander(3)");
s += f;
f = test_PTLQ_LQsolve_dim(vander4, vander4_solution, 1024.0 * GSL_DBL_EPSILON);
gsl_test(f, " PTLQ_LQsolve vander(4)");
s += f;
f = test_PTLQ_LQsolve_dim(vander12, vander12_solution, 0.05);
gsl_test(f, " PTLQ_LQsolve vander(12)");
s += f;
return s;
}
int
test_PTLQ_decomp_dim(const gsl_matrix * m, double eps)
{
int s = 0, signum;
unsigned long i,j, M = m->size1, N = m->size2;
gsl_matrix * lq = gsl_matrix_alloc(N,M);
gsl_matrix * a = gsl_matrix_alloc(N,M);
gsl_matrix * q = gsl_matrix_alloc(M,M);
gsl_matrix * l = gsl_matrix_alloc(N,M);
gsl_vector * d = gsl_vector_alloc(GSL_MIN(M,N));
gsl_vector * norm = gsl_vector_alloc(N);
gsl_permutation * perm = gsl_permutation_alloc(N);
gsl_matrix_transpose_memcpy(lq,m);
s += gsl_linalg_PTLQ_decomp(lq, d, perm, &signum, norm);
s += gsl_linalg_LQ_unpack(lq, d, q, l);
/* compute a = l q */
gsl_blas_dgemm (CblasNoTrans, CblasNoTrans, 1.0, l, q, 0.0, a);
/* Compute P LQ by permuting the rows of LQ */
for (i = 0; i < M; i++) {
gsl_vector_view col = gsl_matrix_column (a, i);
gsl_permute_vector_inverse (perm, &col.vector);
}
for(i=0; i<M; i++) {
for(j=0; j<N; j++) {
double aij = gsl_matrix_get(a, j, i);
double mij = gsl_matrix_get(m, i, j);
int foo = check(aij, mij, eps);
if(foo) {
printf("(%3lu,%3lu)[%lu,%lu]: %22.18g %22.18g\n", M, N, i,j, aij, mij);
}
s += foo;
}
}
gsl_permutation_free (perm);
gsl_vector_free(norm);
gsl_vector_free(d);
gsl_matrix_free(lq);
gsl_matrix_free(a);
gsl_matrix_free(q);
gsl_matrix_free(l);
return s;
}
int test_PTLQ_decomp(void)
{
int f;
int s = 0;
f = test_PTLQ_decomp_dim(m35, 2 * 8.0 * GSL_DBL_EPSILON);
gsl_test(f, " PTLQ_decomp m(3,5)");
s += f;
f = test_PTLQ_decomp_dim(m53, 2 * 8.0 * GSL_DBL_EPSILON);
gsl_test(f, " PTLQ_decomp m(5,3)");
s += f;
f = test_PTLQ_decomp_dim(s35, 2 * 8.0 * GSL_DBL_EPSILON);
gsl_test(f, " PTLQ_decomp s(3,5)");
s += f;
f = test_PTLQ_decomp_dim(s53, 2 * 8.0 * GSL_DBL_EPSILON);
gsl_test(f, " PTLQ_decomp s(5,3)");
s += f;
f = test_PTLQ_decomp_dim(hilb2, 2 * 8.0 * GSL_DBL_EPSILON);
gsl_test(f, " PTLQ_decomp hilbert(2)");
s += f;
f = test_PTLQ_decomp_dim(hilb3, 2 * 64.0 * GSL_DBL_EPSILON);
gsl_test(f, " PTLQ_decomp hilbert(3)");
s += f;
f = test_PTLQ_decomp_dim(hilb4, 2 * 1024.0 * GSL_DBL_EPSILON);
gsl_test(f, " PTLQ_decomp hilbert(4)");
s += f;
f = test_PTLQ_decomp_dim(hilb12, 2 * 1024.0 * GSL_DBL_EPSILON);
gsl_test(f, " PTLQ_decomp hilbert(12)");
s += f;
f = test_PTLQ_decomp_dim(vander2, 8.0 * GSL_DBL_EPSILON);
gsl_test(f, " PTLQ_decomp vander(2)");
s += f;
f = test_PTLQ_decomp_dim(vander3, 64.0 * GSL_DBL_EPSILON);
gsl_test(f, " PTLQ_decomp vander(3)");
s += f;
f = test_PTLQ_decomp_dim(vander4, 1024.0 * GSL_DBL_EPSILON);
gsl_test(f, " PTLQ_decomp vander(4)");
s += f;
f = test_PTLQ_decomp_dim(vander12, 0.0005); /* FIXME: bad accuracy */
gsl_test(f, " PTLQ_decomp vander(12)");
s += f;
return s;
}
int
test_LQ_update_dim(const gsl_matrix * m, double eps)
{
int s = 0;
unsigned long i,j, M = m->size1, N = m->size2;
gsl_matrix * lq1 = gsl_matrix_alloc(N,M);
gsl_matrix * lq2 = gsl_matrix_alloc(N,M);
gsl_matrix * q1 = gsl_matrix_alloc(M,M);
gsl_matrix * l1 = gsl_matrix_alloc(N,M);
gsl_matrix * q2 = gsl_matrix_alloc(M,M);
gsl_matrix * l2 = gsl_matrix_alloc(N,M);
gsl_vector * d2 = gsl_vector_alloc(GSL_MIN(M,N));
gsl_vector * u = gsl_vector_alloc(M);
gsl_vector * v = gsl_vector_alloc(N);
gsl_vector * w = gsl_vector_alloc(M);
gsl_matrix_transpose_memcpy(lq1,m);
gsl_matrix_transpose_memcpy(lq2,m);
for(i=0; i<M; i++) gsl_vector_set(u, i, sin(i+1.0));
for(i=0; i<N; i++) gsl_vector_set(v, i, cos(i+2.0) + sin(i*i+3.0));
/* lq1 is updated */
gsl_blas_dger(1.0, v, u, lq1);
/* lq2 is first decomposed, updated later */
s += gsl_linalg_LQ_decomp(lq2, d2);
s += gsl_linalg_LQ_unpack(lq2, d2, q2, l2);
/* compute w = Q^T u */
gsl_blas_dgemv(CblasNoTrans, 1.0, q2, u, 0.0, w);
/* now lq2 is updated */
s += gsl_linalg_LQ_update(q2, l2, v, w);
/* multiply q2*l2 */
gsl_blas_dgemm(CblasNoTrans,CblasNoTrans,1.0,l2,q2,0.0,lq2);
/* check lq1==lq2 */
for(i=0; i<N; i++) {
for(j=0; j<M; j++) {
double s1 = gsl_matrix_get(lq1, i, j);
double s2 = gsl_matrix_get(lq2, i, j);
int foo = check(s1, s2, eps);
#if 0
if(foo) {
printf("LQ:(%3lu,%3lu)[%lu,%lu]: %22.18g %22.18g\n", M, N, i,j, s1, s2);
}
#endif
s += foo;
}
}
gsl_vector_free(d2);
gsl_vector_free(u);
gsl_vector_free(v);
gsl_vector_free(w);
gsl_matrix_free(lq1);
gsl_matrix_free(lq2);
gsl_matrix_free(q1);
gsl_matrix_free(l1);
gsl_matrix_free(q2);
gsl_matrix_free(l2);
return s;
}
int
test_LQ_update(void)
{
int f;
int s = 0;
f = test_LQ_update_dim(m35, 2 * 512.0 * GSL_DBL_EPSILON);
gsl_test(f, " LQ_update m(3,5)");
s += f;
f = test_LQ_update_dim(m53, 2 * 2048.0 * GSL_DBL_EPSILON);
gsl_test(f, " LQ_update m(5,3)");
s += f;
f = test_LQ_update_dim(hilb2, 2 * 512.0 * GSL_DBL_EPSILON);
gsl_test(f, " LQ_update hilbert(2)");
s += f;
f = test_LQ_update_dim(hilb3, 2 * 512.0 * GSL_DBL_EPSILON);
gsl_test(f, " LQ_update hilbert(3)");
s += f;
f = test_LQ_update_dim(hilb4, 2 * 1024.0 * GSL_DBL_EPSILON);
gsl_test(f, " LQ_update hilbert(4)");
s += f;
f = test_LQ_update_dim(hilb12, 2 * 1024.0 * GSL_DBL_EPSILON);
gsl_test(f, " LQ_update hilbert(12)");
s += f;
f = test_LQ_update_dim(vander2, 8.0 * GSL_DBL_EPSILON);
gsl_test(f, " LQ_update vander(2)");
s += f;
f = test_LQ_update_dim(vander3, 64.0 * GSL_DBL_EPSILON);
gsl_test(f, " LQ_update vander(3)");
s += f;
f = test_LQ_update_dim(vander4, 1024.0 * GSL_DBL_EPSILON);
gsl_test(f, " LQ_update vander(4)");
s += f;
f = test_LQ_update_dim(vander12, 0.0005); /* FIXME: bad accuracy */
gsl_test(f, " LQ_update vander(12)");
s += f;
return s;
}
| {
"alphanum_fraction": 0.6484963215,
"avg_line_length": 26.716091954,
"ext": "c",
"hexsha": "ba673a9d616e2dc795012af2a9e8c601075bfcc4",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z",
"max_forks_repo_head_hexsha": "83fd1fc4cbd053a4f9b673d5cd5841823ddd4d8b",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "karanbirsandhu/nu-sense",
"max_forks_repo_path": "test/lib/gsl-2.6/linalg/test_lq.c",
"max_issues_count": 6,
"max_issues_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a",
"max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z",
"max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "ielomariala/Hex-Game",
"max_issues_repo_path": "gsl-2.6/linalg/test_lq.c",
"max_line_length": 110,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "ielomariala/Hex-Game",
"max_stars_repo_path": "gsl-2.6/linalg/test_lq.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": 8571,
"size": 23243
} |
/* randist/test.c
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007, 2010 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 <config.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_randist.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_test.h>
#include <gsl/gsl_ieee_utils.h>
#include <gsl/gsl_integration.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_blas.h>
#include <gsl/gsl_linalg.h>
#include <gsl/gsl_cdf.h>
#define N 100000
/* Convient test dimension for multivariant distributions */
#define MULTI_DIM 10
void testMoments (double (*f) (void), const char *name,
double a, double b, double p);
void testPDF (double (*f) (void), double (*pdf) (double), const char *name);
void testDiscretePDF (double (*f) (void), double (*pdf) (unsigned int),
const char *name);
void test_shuffle (void);
void test_choose (void);
double test_beta (void);
double test_beta_pdf (double x);
double test_bernoulli (void);
double test_bernoulli_pdf (unsigned int n);
double test_binomial (void);
double test_binomial_pdf (unsigned int n);
double test_binomial_large (void);
double test_binomial_large_pdf (unsigned int n);
double test_binomial_huge (void);
double test_binomial_huge_pdf (unsigned int n);
double test_binomial_max (void);
double test_binomial_max_pdf (unsigned int n);
double test_binomial0 (void);
double test_binomial0_pdf (unsigned int n);
double test_binomial1 (void);
double test_binomial1_pdf (unsigned int n);
double test_binomial_knuth (void);
double test_binomial_knuth_pdf (unsigned int n);
double test_binomial_large_knuth (void);
double test_binomial_large_knuth_pdf (unsigned int n);
double test_binomial_huge_knuth (void);
double test_binomial_huge_knuth_pdf (unsigned int n);
double test_cauchy (void);
double test_cauchy_pdf (double x);
double test_chisq (void);
double test_chisq_pdf (double x);
double test_chisqnu2 (void);
double test_chisqnu2_pdf (double x);
double test_dirichlet (void);
double test_dirichlet_pdf (double x);
double test_dirichlet_small (void);
double test_dirichlet_small_pdf (double x);
void test_dirichlet_moments (void);
double test_discrete1 (void);
double test_discrete1_pdf (unsigned int n);
double test_discrete2 (void);
double test_discrete2_pdf (unsigned int n);
double test_discrete3 (void);
double test_discrete3_pdf (unsigned int n);
double test_erlang (void);
double test_erlang_pdf (double x);
double test_exponential (void);
double test_exponential_pdf (double x);
double test_exppow0 (void);
double test_exppow0_pdf (double x);
double test_exppow1 (void);
double test_exppow1_pdf (double x);
double test_exppow1a (void);
double test_exppow1a_pdf (double x);
double test_exppow2 (void);
double test_exppow2_pdf (double x);
double test_exppow2a (void);
double test_exppow2a_pdf (double x);
double test_exppow2b (void);
double test_exppow2b_pdf (double x);
double test_fdist (void);
double test_fdist_pdf (double x);
double test_fdist_large (void);
double test_fdist_large_pdf (double x);
double test_flat (void);
double test_flat_pdf (double x);
double test_gamma (void);
double test_gamma_pdf (double x);
double test_gamma1 (void);
double test_gamma1_pdf (double x);
double test_gamma_int (void);
double test_gamma_int_pdf (double x);
double test_gamma_large (void);
double test_gamma_large_pdf (double x);
double test_gamma_vlarge (void);
double test_gamma_vlarge_pdf (double x);
double test_gamma_small (void);
double test_gamma_small_pdf (double x);
double test_gamma_mt (void);
double test_gamma_mt_pdf (double x);
double test_gamma_mt1 (void);
double test_gamma_mt1_pdf (double x);
double test_gamma_mt_int (void);
double test_gamma_mt_int_pdf (double x);
double test_gamma_mt_large (void);
double test_gamma_mt_large_pdf (double x);
double test_gamma_mt_small (void);
double test_gamma_mt_small_pdf (double x);
double test_gamma_knuth_vlarge (void);
double test_gamma_knuth_vlarge_pdf (double x);
double test_gaussian (void);
double test_gaussian_pdf (double x);
double test_gaussian_ratio_method (void);
double test_gaussian_ratio_method_pdf (double x);
double test_gaussian_ziggurat (void);
double test_gaussian_ziggurat_pdf (double x);
double test_gaussian_tail (void);
double test_gaussian_tail_pdf (double x);
double test_gaussian_tail1 (void);
double test_gaussian_tail1_pdf (double x);
double test_gaussian_tail2 (void);
double test_gaussian_tail2_pdf (double x);
double test_ugaussian (void);
double test_ugaussian_pdf (double x);
double test_ugaussian_ratio_method (void);
double test_ugaussian_ratio_method_pdf (double x);
double test_ugaussian_tail (void);
double test_ugaussian_tail_pdf (double x);
double test_bivariate_gaussian1 (void);
double test_bivariate_gaussian1_pdf (double x);
double test_bivariate_gaussian2 (void);
double test_bivariate_gaussian2_pdf (double x);
double test_bivariate_gaussian3 (void);
double test_bivariate_gaussian3_pdf (double x);
double test_bivariate_gaussian4 (void);
double test_bivariate_gaussian4_pdf (double x);
void test_multivariate_gaussian_log_pdf (void);
void test_multivariate_gaussian_pdf (void);
void test_multivariate_gaussian (void);
double test_gumbel1 (void);
double test_gumbel1_pdf (double x);
double test_gumbel2 (void);
double test_gumbel2_pdf (double x);
double test_geometric (void);
double test_geometric_pdf (unsigned int x);
double test_geometric1 (void);
double test_geometric1_pdf (unsigned int x);
double test_hypergeometric1 (void);
double test_hypergeometric1_pdf (unsigned int x);
double test_hypergeometric2 (void);
double test_hypergeometric2_pdf (unsigned int x);
double test_hypergeometric3 (void);
double test_hypergeometric3_pdf (unsigned int x);
double test_hypergeometric4 (void);
double test_hypergeometric4_pdf (unsigned int x);
double test_hypergeometric5 (void);
double test_hypergeometric5_pdf (unsigned int x);
double test_hypergeometric6 (void);
double test_hypergeometric6_pdf (unsigned int x);
double test_landau (void);
double test_landau_pdf (double x);
double test_levy1 (void);
double test_levy1_pdf (double x);
double test_levy2 (void);
double test_levy2_pdf (double x);
double test_levy1a (void);
double test_levy1a_pdf (double x);
double test_levy2a (void);
double test_levy2a_pdf (double x);
double test_levy_skew1 (void);
double test_levy_skew1_pdf (double x);
double test_levy_skew2 (void);
double test_levy_skew2_pdf (double x);
double test_levy_skew1a (void);
double test_levy_skew1a_pdf (double x);
double test_levy_skew2a (void);
double test_levy_skew2a_pdf (double x);
double test_levy_skew1b (void);
double test_levy_skew1b_pdf (double x);
double test_levy_skew2b (void);
double test_levy_skew2b_pdf (double x);
double test_logistic (void);
double test_logistic_pdf (double x);
double test_lognormal (void);
double test_lognormal_pdf (double x);
double test_logarithmic (void);
double test_logarithmic_pdf (unsigned int n);
double test_multinomial (void);
double test_multinomial_pdf (unsigned int n);
double test_multinomial_large (void);
double test_multinomial_large_pdf (unsigned int n);
void test_multinomial_moments (void);
double test_negative_binomial (void);
double test_negative_binomial_pdf (unsigned int n);
double test_pascal (void);
double test_pascal_pdf (unsigned int n);
double test_pareto (void);
double test_pareto_pdf (double x);
double test_poisson (void);
double test_poisson_pdf (unsigned int x);
double test_poisson_large (void);
double test_poisson_large_pdf (unsigned int x);
double test_dir2d (void);
double test_dir2d_pdf (double x);
double test_dir2d_trig_method (void);
double test_dir2d_trig_method_pdf (double x);
double test_dir3dxy (void);
double test_dir3dxy_pdf (double x);
double test_dir3dyz (void);
double test_dir3dyz_pdf (double x);
double test_dir3dzx (void);
double test_dir3dzx_pdf (double x);
double test_rayleigh (void);
double test_rayleigh_pdf (double x);
double test_rayleigh_tail (void);
double test_rayleigh_tail_pdf (double x);
double test_tdist1 (void);
double test_tdist1_pdf (double x);
double test_tdist2 (void);
double test_tdist2_pdf (double x);
double test_laplace (void);
double test_laplace_pdf (double x);
double test_weibull (void);
double test_weibull_pdf (double x);
double test_weibull1 (void);
double test_weibull1_pdf (double x);
gsl_rng *r_global;
static gsl_ran_discrete_t *g1 = NULL;
static gsl_ran_discrete_t *g2 = NULL;
static gsl_ran_discrete_t *g3 = NULL;
int
main (void)
{
gsl_ieee_env_setup ();
gsl_rng_env_setup ();
r_global = gsl_rng_alloc (gsl_rng_default);
#define FUNC(x) test_ ## x, "test gsl_ran_" #x
#define FUNC2(x) test_ ## x, test_ ## x ## _pdf, "test gsl_ran_" #x
test_shuffle ();
test_choose ();
testMoments (FUNC (ugaussian), 0.0, 100.0, 0.5);
testMoments (FUNC (ugaussian), -1.0, 1.0, 0.6826895);
testMoments (FUNC (ugaussian), 3.0, 3.5, 0.0011172689);
testMoments (FUNC (ugaussian_tail), 3.0, 3.5, 0.0011172689 / 0.0013498981);
testMoments (FUNC (exponential), 0.0, 1.0, 1 - exp (-0.5));
testMoments (FUNC (cauchy), 0.0, 10000.0, 0.5);
testMoments (FUNC (discrete1), -0.5, 0.5, 0.59);
testMoments (FUNC (discrete1), 0.5, 1.5, 0.40);
testMoments (FUNC (discrete1), 1.5, 3.5, 0.01);
testMoments (FUNC (discrete2), -0.5, 0.5, 1.0/45.0 );
testMoments (FUNC (discrete2), 8.5, 9.5, 0 );
testMoments (FUNC (discrete3), -0.5, 0.5, 0.05 );
testMoments (FUNC (discrete3), 0.5, 1.5, 0.05 );
testMoments (FUNC (discrete3), -0.5, 9.5, 0.5 );
test_dirichlet_moments ();
test_multinomial_moments ();
testPDF (FUNC2 (beta));
testPDF (FUNC2 (cauchy));
testPDF (FUNC2 (chisq));
testPDF (FUNC2 (chisqnu2));
testPDF (FUNC2 (dirichlet));
testPDF (FUNC2 (dirichlet_small));
testPDF (FUNC2 (erlang));
testPDF (FUNC2 (exponential));
testPDF (FUNC2 (exppow0));
testPDF (FUNC2 (exppow1));
testPDF (FUNC2 (exppow1a));
testPDF (FUNC2 (exppow2));
testPDF (FUNC2 (exppow2a));
testPDF (FUNC2 (exppow2b));
testPDF (FUNC2 (fdist));
testPDF (FUNC2 (fdist_large));
testPDF (FUNC2 (flat));
testPDF (FUNC2 (gamma));
testPDF (FUNC2 (gamma1));
testPDF (FUNC2 (gamma_int));
testPDF (FUNC2 (gamma_large));
testPDF (FUNC2 (gamma_vlarge));
testPDF (FUNC2 (gamma_knuth_vlarge));
testPDF (FUNC2 (gamma_small));
testPDF (FUNC2 (gamma_mt));
testPDF (FUNC2 (gamma_mt1));
testPDF (FUNC2 (gamma_mt_int));
testPDF (FUNC2 (gamma_mt_large));
testPDF (FUNC2 (gamma_mt_small));
testPDF (FUNC2 (gaussian));
testPDF (FUNC2 (gaussian_ratio_method));
testPDF (FUNC2 (gaussian_ziggurat));
testPDF (FUNC2 (ugaussian));
testPDF (FUNC2 (ugaussian_ratio_method));
testPDF (FUNC2 (gaussian_tail));
testPDF (FUNC2 (gaussian_tail1));
testPDF (FUNC2 (gaussian_tail2));
testPDF (FUNC2 (ugaussian_tail));
testPDF (FUNC2 (bivariate_gaussian1));
testPDF (FUNC2 (bivariate_gaussian2));
testPDF (FUNC2 (bivariate_gaussian3));
testPDF (FUNC2 (bivariate_gaussian4));
test_multivariate_gaussian_log_pdf ();
test_multivariate_gaussian_pdf ();
test_multivariate_gaussian ();
testPDF (FUNC2 (gumbel1));
testPDF (FUNC2 (gumbel2));
testPDF (FUNC2 (landau));
testPDF (FUNC2 (levy1));
testPDF (FUNC2 (levy2));
testPDF (FUNC2 (levy1a));
testPDF (FUNC2 (levy2a));
testPDF (FUNC2 (levy_skew1));
testPDF (FUNC2 (levy_skew2));
testPDF (FUNC2 (levy_skew1a));
testPDF (FUNC2 (levy_skew2a));
testPDF (FUNC2 (levy_skew1b));
testPDF (FUNC2 (levy_skew2b));
testPDF (FUNC2 (logistic));
testPDF (FUNC2 (lognormal));
testPDF (FUNC2 (pareto));
testPDF (FUNC2 (rayleigh));
testPDF (FUNC2 (rayleigh_tail));
testPDF (FUNC2 (tdist1));
testPDF (FUNC2 (tdist2));
testPDF (FUNC2 (laplace));
testPDF (FUNC2 (weibull));
testPDF (FUNC2 (weibull1));
testPDF (FUNC2 (dir2d));
testPDF (FUNC2 (dir2d_trig_method));
testPDF (FUNC2 (dir3dxy));
testPDF (FUNC2 (dir3dyz));
testPDF (FUNC2 (dir3dzx));
testDiscretePDF (FUNC2 (discrete1));
testDiscretePDF (FUNC2 (discrete2));
testDiscretePDF (FUNC2 (discrete3));
testDiscretePDF (FUNC2 (poisson));
testDiscretePDF (FUNC2 (poisson_large));
testDiscretePDF (FUNC2 (bernoulli));
testDiscretePDF (FUNC2 (binomial));
testDiscretePDF (FUNC2 (binomial0));
testDiscretePDF (FUNC2 (binomial1));
testDiscretePDF (FUNC2 (binomial_knuth));
testDiscretePDF (FUNC2 (binomial_large));
testDiscretePDF (FUNC2 (binomial_large_knuth));
testDiscretePDF (FUNC2 (binomial_huge));
testDiscretePDF (FUNC2 (binomial_huge_knuth));
testDiscretePDF (FUNC2 (binomial_max));
testDiscretePDF (FUNC2 (geometric));
testDiscretePDF (FUNC2 (geometric1));
testDiscretePDF (FUNC2 (hypergeometric1));
testDiscretePDF (FUNC2 (hypergeometric2));
testDiscretePDF (FUNC2 (hypergeometric3));
testDiscretePDF (FUNC2 (hypergeometric4));
testDiscretePDF (FUNC2 (hypergeometric5));
testDiscretePDF (FUNC2 (hypergeometric6));
testDiscretePDF (FUNC2 (logarithmic));
testDiscretePDF (FUNC2 (multinomial));
testDiscretePDF (FUNC2 (multinomial_large));
testDiscretePDF (FUNC2 (negative_binomial));
testDiscretePDF (FUNC2 (pascal));
gsl_rng_free (r_global);
gsl_ran_discrete_free (g1);
gsl_ran_discrete_free (g2);
gsl_ran_discrete_free (g3);
exit (gsl_test_summary ());
}
void
test_shuffle (void)
{
double count[10][10];
int x[10] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int i, j, status = 0;
for (i = 0; i < 10; i++)
{
for (j = 0; j < 10; j++)
{
count[i][j] = 0;
}
}
for (i = 0; i < N; i++)
{
for (j = 0; j < 10; j++)
x[j] = j;
gsl_ran_shuffle (r_global, x, 10, sizeof (int));
for (j = 0; j < 10; j++)
count[x[j]][j]++;
}
for (i = 0; i < 10; i++)
{
for (j = 0; j < 10; j++)
{
double expected = N / 10.0;
double d = fabs (count[i][j] - expected);
double sigma = d / sqrt (expected);
if (sigma > 5 && d > 1)
{
status = 1;
gsl_test (status,
"gsl_ran_shuffle %d,%d (%g observed vs %g expected)",
i, j, count[i][j] / N, 0.1);
}
}
}
gsl_test (status, "gsl_ran_shuffle on {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}");
}
void
test_choose (void)
{
double count[10];
int x[10] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int y[3] = { 0, 1, 2 };
int i, j, status = 0;
for (i = 0; i < 10; i++)
{
count[i] = 0;
}
for (i = 0; i < N; i++)
{
for (j = 0; j < 10; j++)
x[j] = j;
gsl_ran_choose (r_global, y, 3, x, 10, sizeof (int));
for (j = 0; j < 3; j++)
count[y[j]]++;
}
for (i = 0; i < 10; i++)
{
double expected = 3.0 * N / 10.0;
double d = fabs (count[i] - expected);
double sigma = d / sqrt (expected);
if (sigma > 5 && d > 1)
{
status = 1;
gsl_test (status,
"gsl_ran_choose %d (%g observed vs %g expected)",
i, count[i] / N, 0.1);
}
}
gsl_test (status, "gsl_ran_choose (3) on {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}");
}
void
testMoments (double (*f) (void), const char *name,
double a, double b, double p)
{
int i;
double count = 0, expected, sigma;
int status;
for (i = 0; i < N; i++)
{
double r = f ();
if (r < b && r > a)
count++;
}
expected = p * N;
sigma = (expected > 0) ? fabs (count - expected) / sqrt (expected) : fabs(count - expected);
status = (sigma > 3);
gsl_test (status, "%s [%g,%g] (%g observed vs %g expected)",
name, a, b, count / N, p);
}
#define BINS 100
typedef double pdf_func(double);
/* Keep track of invalid values during integration */
static int pdf_errors = 0;
static double pdf_errval = 0.0;
double
wrapper_function (double x, void *params)
{
pdf_func * pdf = (pdf_func *)params;
double P = pdf(x);
if (!gsl_finite(P)) {
pdf_errors++;
pdf_errval = P;
P = 0; /* skip invalid value now, but return pdf_errval at the end */
}
return P;
}
double
integrate (pdf_func * pdf, double a, double b)
{
double result, abserr;
size_t n = 1000;
gsl_function f;
gsl_integration_workspace * w = gsl_integration_workspace_alloc (n);
f.function = &wrapper_function;
f.params = (void *)pdf;
pdf_errors = 0;
gsl_integration_qags (&f, a, b, 1e-16, 1e-4, n, w, &result, &abserr);
gsl_integration_workspace_free (w);
if (pdf_errors) return pdf_errval;
return result;
}
void
testPDF (double (*f) (void), double (*pdf) (double), const char *name)
{
double count[BINS], edge[BINS], p[BINS];
double a = -5.0, b = +5.0;
double dx = (b - a) / BINS;
double bin;
double total = 0, mean;
int i, j, status = 0, status_i = 0, attempts = 0;
long int n0 = 0, n = N;
for (i = 0; i < BINS; i++)
{
/* Compute the integral of p(x) from x to x+dx */
double x = a + i * dx;
if (fabs (x) < 1e-10) /* hit the origin exactly */
x = 0.0;
p[i] = integrate (pdf, x, x+dx);
}
for (i = 0; i < BINS; i++)
{
count[i] = 0;
edge[i] = 0;
}
trial:
attempts++;
for (i = n0; i < n; i++)
{
double r = f ();
total += r;
if (r < b && r > a)
{
double u = (r - a) / dx;
double f = modf(u, &bin);
j = (int)bin;
if (f == 0)
edge[j]++;
else
count[j]++;
}
}
/* Sort out where the hits on the edges should go */
for (i = 0; i < BINS; i++)
{
/* If the bin above is empty, its lower edge hits belong in the
lower bin */
if (i + 1 < BINS && count[i+1] == 0) {
count[i] += edge[i+1];
edge[i+1] = 0;
}
count[i] += edge[i];
edge[i] = 0;
}
mean = (total / n);
status = !gsl_finite(mean);
if (status) {
gsl_test (status, "%s, finite mean, observed %g", name, mean);
return;
}
for (i = 0; i < BINS; i++)
{
double x = a + i * dx;
double d = fabs (count[i] - n * p[i]);
if (!gsl_finite(p[i]))
{
status_i = 1;
}
else if (p[i] != 0)
{
double s = d / sqrt (n * p[i]);
status_i = (s > 5) && (d > 2);
}
else
{
status_i = (count[i] != 0);
}
/* Extend the sample if there is an outlier on the first attempt
to avoid spurious failures when running large numbers of tests. */
if (status_i && attempts < 50)
{
n0 = n;
n = 2.0*n;
goto trial;
}
status |= status_i;
if (status_i)
gsl_test (status_i, "%s [%g,%g) (%g/%d=%g observed vs %g expected)",
name, x, x + dx, count[i], n, count[i] / n, p[i]);
}
if (status == 0)
gsl_test (status, "%s, sampling against pdf over range [%g,%g) ",
name, a, b);
}
void
testDiscretePDF (double (*f) (void), double (*pdf) (unsigned int),
const char *name)
{
double count[BINS], p[BINS];
unsigned int i;
int status = 0, status_i = 0;
for (i = 0; i < BINS; i++)
count[i] = 0;
for (i = 0; i < N; i++)
{
int r = (int) (f ());
if (r >= 0 && r < BINS)
count[r]++;
}
for (i = 0; i < BINS; i++)
p[i] = pdf (i);
for (i = 0; i < BINS; i++)
{
double d = fabs (count[i] - N * p[i]);
if (p[i] != 0)
{
double s = d / sqrt (N * p[i]);
status_i = (s > 5) && (d > 1);
}
else
{
status_i = (count[i] != 0);
}
status |= status_i;
if (status_i)
gsl_test (status_i, "%s i=%d (%g observed vs %g expected)",
name, i, count[i] / N, p[i]);
}
if (status == 0)
gsl_test (status, "%s, sampling against pdf over range [%d,%d) ",
name, 0, BINS);
}
double
test_beta (void)
{
return gsl_ran_beta (r_global, 2.0, 3.0);
}
double
test_beta_pdf (double x)
{
return gsl_ran_beta_pdf (x, 2.0, 3.0);
}
double
test_bernoulli (void)
{
return gsl_ran_bernoulli (r_global, 0.3);
}
double
test_bernoulli_pdf (unsigned int n)
{
return gsl_ran_bernoulli_pdf (n, 0.3);
}
double
test_binomial (void)
{
return gsl_ran_binomial (r_global, 0.3, 5);
}
double
test_binomial_pdf (unsigned int n)
{
return gsl_ran_binomial_pdf (n, 0.3, 5);
}
double
test_binomial0 (void)
{
return gsl_ran_binomial (r_global, 0, 8);
}
double
test_binomial0_pdf (unsigned int n)
{
return gsl_ran_binomial_pdf (n, 0, 8);
}
double
test_binomial1 (void)
{
return gsl_ran_binomial (r_global, 1, 8);
}
double
test_binomial1_pdf (unsigned int n)
{
return gsl_ran_binomial_pdf (n, 1, 8);
}
double
test_binomial_knuth (void)
{
return gsl_ran_binomial_knuth (r_global, 0.3, 5);
}
double
test_binomial_knuth_pdf (unsigned int n)
{
return gsl_ran_binomial_pdf (n, 0.3, 5);
}
double
test_binomial_large (void)
{
return gsl_ran_binomial (r_global, 0.3, 55);
}
double
test_binomial_large_pdf (unsigned int n)
{
return gsl_ran_binomial_pdf (n, 0.3, 55);
}
double
test_binomial_large_knuth (void)
{
return gsl_ran_binomial_knuth (r_global, 0.3, 55);
}
double
test_binomial_large_knuth_pdf (unsigned int n)
{
return gsl_ran_binomial_pdf (n, 0.3, 55);
}
double
test_binomial_huge (void)
{
return gsl_ran_binomial (r_global, 0.3, 5500);
}
double
test_binomial_huge_pdf (unsigned int n)
{
return gsl_ran_binomial_pdf (n, 0.3, 5500);
}
double
test_binomial_huge_knuth (void)
{
return gsl_ran_binomial_knuth (r_global, 0.3, 5500);
}
double
test_binomial_huge_knuth_pdf (unsigned int n)
{
return gsl_ran_binomial_pdf (n, 0.3, 5500);
}
double
test_binomial_max (void)
{
return gsl_ran_binomial (r_global, 1e-8, 1<<31);
}
double
test_binomial_max_pdf (unsigned int n)
{
return gsl_ran_binomial_pdf (n, 1e-8, 1<<31);
}
double
test_cauchy (void)
{
return gsl_ran_cauchy (r_global, 2.0);
}
double
test_cauchy_pdf (double x)
{
return gsl_ran_cauchy_pdf (x, 2.0);
}
double
test_chisq (void)
{
return gsl_ran_chisq (r_global, 13.0);
}
double
test_chisq_pdf (double x)
{
return gsl_ran_chisq_pdf (x, 13.0);
}
double
test_chisqnu2 (void)
{
return gsl_ran_chisq (r_global, 2.0);
}
double
test_chisqnu2_pdf (double x)
{
return gsl_ran_chisq_pdf (x, 2.0);
}
double
test_dir2d (void)
{
double x = 0, y = 0, theta;
gsl_ran_dir_2d (r_global, &x, &y);
theta = atan2 (x, y);
return theta;
}
double
test_dir2d_pdf (double x)
{
if (x > -M_PI && x <= M_PI)
{
return 1 / (2 * M_PI);
}
else
{
return 0;
}
}
double
test_dir2d_trig_method (void)
{
double x = 0, y = 0, theta;
gsl_ran_dir_2d_trig_method (r_global, &x, &y);
theta = atan2 (x, y);
return theta;
}
double
test_dir2d_trig_method_pdf (double x)
{
if (x > -M_PI && x <= M_PI)
{
return 1 / (2 * M_PI);
}
else
{
return 0;
}
}
double
test_dir3dxy (void)
{
double x = 0, y = 0, z = 0, theta;
gsl_ran_dir_3d (r_global, &x, &y, &z);
theta = atan2 (x, y);
return theta;
}
double
test_dir3dxy_pdf (double x)
{
if (x > -M_PI && x <= M_PI)
{
return 1 / (2 * M_PI);
}
else
{
return 0;
}
}
double
test_dir3dyz (void)
{
double x = 0, y = 0, z = 0, theta;
gsl_ran_dir_3d (r_global, &x, &y, &z);
theta = atan2 (y, z);
return theta;
}
double
test_dir3dyz_pdf (double x)
{
if (x > -M_PI && x <= M_PI)
{
return 1 / (2 * M_PI);
}
else
{
return 0;
}
}
double
test_dir3dzx (void)
{
double x = 0, y = 0, z = 0, theta;
gsl_ran_dir_3d (r_global, &x, &y, &z);
theta = atan2 (z, x);
return theta;
}
double
test_dir3dzx_pdf (double x)
{
if (x > -M_PI && x <= M_PI)
{
return 1 / (2 * M_PI);
}
else
{
return 0;
}
}
double
test_dirichlet (void)
{
/* This is a bit of a lame test, since when K=2, the Dirichlet distribution
becomes a beta distribution */
size_t K = 2;
double alpha[2] = { 2.5, 5.0 };
double theta[2] = { 0.0, 0.0 };
gsl_ran_dirichlet (r_global, K, alpha, theta);
return theta[0];
}
double
test_dirichlet_pdf (double x)
{
size_t K = 2;
double alpha[2] = { 2.5, 5.0 };
double theta[2];
if (x <= 0.0 || x >= 1.0)
return 0.0; /* Out of range */
theta[0] = x;
theta[1] = 1.0 - x;
return gsl_ran_dirichlet_pdf (K, alpha, theta);
}
double
test_dirichlet_small (void)
{
size_t K = 2;
double alpha[2] = { 2.5e-3, 5.0e-3};
double theta[2] = { 0.0, 0.0 };
gsl_ran_dirichlet (r_global, K, alpha, theta);
return theta[0];
}
double
test_dirichlet_small_pdf (double x)
{
size_t K = 2;
double alpha[2] = { 2.5e-3, 5.0e-3 };
double theta[2];
if (x <= 0.0 || x >= 1.0)
return 0.0; /* Out of range */
theta[0] = x;
theta[1] = 1.0 - x;
return gsl_ran_dirichlet_pdf (K, alpha, theta);
}
/* Check that the observed means of the Dirichlet variables are
within reasonable statistical errors of their correct values. */
#define DIRICHLET_K 10
void
test_dirichlet_moments (void)
{
double alpha[DIRICHLET_K];
double theta[DIRICHLET_K];
double theta_sum[DIRICHLET_K];
double alpha_sum = 0.0;
double mean, obs_mean, sd, sigma;
int status, k, n;
for (k = 0; k < DIRICHLET_K; k++)
{
alpha[k] = gsl_ran_exponential (r_global, 0.1);
alpha_sum += alpha[k];
theta_sum[k] = 0.0;
}
for (n = 0; n < N; n++)
{
gsl_ran_dirichlet (r_global, DIRICHLET_K, alpha, theta);
for (k = 0; k < DIRICHLET_K; k++)
theta_sum[k] += theta[k];
}
for (k = 0; k < DIRICHLET_K; k++)
{
mean = alpha[k] / alpha_sum;
sd =
sqrt ((alpha[k] * (1. - alpha[k] / alpha_sum)) /
(alpha_sum * (alpha_sum + 1.)));
obs_mean = theta_sum[k] / N;
sigma = sqrt ((double) N) * fabs (mean - obs_mean) / sd;
status = (sigma > 3.0);
gsl_test (status,
"test gsl_ran_dirichlet: mean (%g observed vs %g expected)",
obs_mean, mean);
}
}
/* Check that the observed means of the multinomial variables are
within reasonable statistical errors of their correct values. */
void
test_multinomial_moments (void)
{
const unsigned int sum_n = 100;
const double p[MULTI_DIM] ={ 0.2, 0.20, 0.17, 0.14, 0.12,
0.07, 0.05, 0.02, 0.02, 0.01 };
unsigned int x[MULTI_DIM];
double x_sum[MULTI_DIM];
double mean, obs_mean, sd, sigma;
int status, k, n;
for (k = 0; k < MULTI_DIM; k++)
x_sum[k] =0.0;
for (n = 0; n < N; n++)
{
gsl_ran_multinomial (r_global, MULTI_DIM, sum_n, p, x);
for (k = 0; k < MULTI_DIM; k++)
x_sum[k] += x[k];
}
for (k = 0; k < MULTI_DIM; k++)
{
mean = p[k] * sum_n;
sd = p[k] * (1.-p[k]) * sum_n;
obs_mean = x_sum[k] / N;
sigma = sqrt ((double) N) * fabs (mean - obs_mean) / sd;
status = (sigma > 3.0);
gsl_test (status,
"test gsl_ran_multinomial: mean (%g observed vs %g expected)",
obs_mean, mean);
}
}
double
test_discrete1 (void)
{
static double P[3] = { 0.59, 0.4, 0.01 };
if (g1 == NULL)
{
g1 = gsl_ran_discrete_preproc (3, P);
}
return gsl_ran_discrete (r_global, g1);
}
double
test_discrete1_pdf (unsigned int n)
{
return gsl_ran_discrete_pdf ((size_t) n, g1);
}
double
test_discrete2 (void)
{
static double P[10] = { 1, 9, 3, 4, 5, 8, 6, 7, 2, 0 };
if (g2 == NULL)
{
g2 = gsl_ran_discrete_preproc (10, P);
}
return gsl_ran_discrete (r_global, g2);
}
double
test_discrete2_pdf (unsigned int n)
{
return gsl_ran_discrete_pdf ((size_t) n, g2);
}
double
test_discrete3 (void)
{
static double P[20];
if (g3 == NULL)
{ int i;
for (i=0; i<20; ++i) P[i]=1.0/20;
g3 = gsl_ran_discrete_preproc (20, P);
}
return gsl_ran_discrete (r_global, g3);
}
double
test_discrete3_pdf (unsigned int n)
{
return gsl_ran_discrete_pdf ((size_t) n, g3);
}
double
test_erlang (void)
{
return gsl_ran_erlang (r_global, 3.0, 4.0);
}
double
test_erlang_pdf (double x)
{
return gsl_ran_erlang_pdf (x, 3.0, 4.0);
}
double
test_exponential (void)
{
return gsl_ran_exponential (r_global, 2.0);
}
double
test_exponential_pdf (double x)
{
return gsl_ran_exponential_pdf (x, 2.0);
}
double
test_exppow0 (void)
{
return gsl_ran_exppow (r_global, 3.7, 0.3);
}
double
test_exppow0_pdf (double x)
{
return gsl_ran_exppow_pdf (x, 3.7, 0.3);
}
double
test_exppow1 (void)
{
return gsl_ran_exppow (r_global, 3.7, 1.0);
}
double
test_exppow1_pdf (double x)
{
return gsl_ran_exppow_pdf (x, 3.7, 1.0);
}
double
test_exppow1a (void)
{
return gsl_ran_exppow (r_global, 3.7, 1.9);
}
double
test_exppow1a_pdf (double x)
{
return gsl_ran_exppow_pdf (x, 3.7, 1.9);
}
double
test_exppow2 (void)
{
return gsl_ran_exppow (r_global, 3.7, 2.0);
}
double
test_exppow2_pdf (double x)
{
return gsl_ran_exppow_pdf (x, 3.7, 2.0);
}
double
test_exppow2a (void)
{
return gsl_ran_exppow (r_global, 3.7, 3.5);
}
double
test_exppow2a_pdf (double x)
{
return gsl_ran_exppow_pdf (x, 3.7, 3.5);
}
double
test_exppow2b (void)
{
return gsl_ran_exppow (r_global, 3.7, 7.5);
}
double
test_exppow2b_pdf (double x)
{
return gsl_ran_exppow_pdf (x, 3.7, 7.5);
}
double
test_fdist (void)
{
return gsl_ran_fdist (r_global, 3.0, 4.0);
}
double
test_fdist_pdf (double x)
{
return gsl_ran_fdist_pdf (x, 3.0, 4.0);
}
/* Test case for bug #28500: overflow in gsl_ran_fdist_pdf */
double
test_fdist_large (void)
{
return gsl_ran_fdist (r_global, 8.0, 249.0);
}
double
test_fdist_large_pdf (double x)
{
return gsl_ran_fdist_pdf (x, 8.0, 249.0);
}
double
test_flat (void)
{
return gsl_ran_flat (r_global, 3.0, 4.0);
}
double
test_flat_pdf (double x)
{
return gsl_ran_flat_pdf (x, 3.0, 4.0);
}
double
test_gamma (void)
{
return gsl_ran_gamma (r_global, 2.5, 2.17);
}
double
test_gamma_pdf (double x)
{
return gsl_ran_gamma_pdf (x, 2.5, 2.17);
}
double
test_gamma1 (void)
{
return gsl_ran_gamma (r_global, 1.0, 2.17);
}
double
test_gamma1_pdf (double x)
{
return gsl_ran_gamma_pdf (x, 1.0, 2.17);
}
double
test_gamma_int (void)
{
return gsl_ran_gamma (r_global, 10.0, 2.17);
}
double
test_gamma_int_pdf (double x)
{
return gsl_ran_gamma_pdf (x, 10.0, 2.17);
}
double
test_gamma_large (void)
{
return gsl_ran_gamma (r_global, 20.0, 2.17);
}
double
test_gamma_large_pdf (double x)
{
return gsl_ran_gamma_pdf (x, 20.0, 2.17);
}
double
test_gamma_small (void)
{
return gsl_ran_gamma (r_global, 0.92, 2.17);
}
double
test_gamma_small_pdf (double x)
{
return gsl_ran_gamma_pdf (x, 0.92, 2.17);
}
double
test_gamma_vlarge (void)
{
/* Scale the distribution to get it into the range [-5,5] */
double c = 2.71828181565;
double b = 6.32899304917e-10;
double d = 1e4;
return (gsl_ran_gamma (r_global, 4294967296.0, b) - c) * d;
}
double
test_gamma_vlarge_pdf (double x)
{
double c = 2.71828181565;
double b = 6.32899304917e-10;
double d = 1e4;
return gsl_ran_gamma_pdf ((x / d) + c, 4294967296.0, b) / d;
}
double
test_gamma_mt (void)
{
return gsl_ran_gamma_mt (r_global, 2.5, 2.17);
}
double
test_gamma_mt_pdf (double x)
{
return gsl_ran_gamma_pdf (x, 2.5, 2.17);
}
double
test_gamma_mt1 (void)
{
return gsl_ran_gamma_mt (r_global, 1.0, 2.17);
}
double
test_gamma_mt1_pdf (double x)
{
return gsl_ran_gamma_pdf (x, 1.0, 2.17);
}
double
test_gamma_mt_int (void)
{
return gsl_ran_gamma_mt (r_global, 10.0, 2.17);
}
double
test_gamma_mt_int_pdf (double x)
{
return gsl_ran_gamma_pdf (x, 10.0, 2.17);
}
double
test_gamma_mt_large (void)
{
return gsl_ran_gamma_mt (r_global, 20.0, 2.17);
}
double
test_gamma_mt_large_pdf (double x)
{
return gsl_ran_gamma_pdf (x, 20.0, 2.17);
}
double
test_gamma_mt_small (void)
{
return gsl_ran_gamma_mt (r_global, 0.92, 2.17);
}
double
test_gamma_mt_small_pdf (double x)
{
return gsl_ran_gamma_pdf (x, 0.92, 2.17);
}
double
test_gamma_knuth_vlarge (void)
{
/* Scale the distribution to get it into the range [-5,5] */
double c = 2.71828181565;
double b = 6.32899304917e-10;
double d = 1e4;
return (gsl_ran_gamma_knuth (r_global, 4294967296.0, b) - c) * d;
}
double
test_gamma_knuth_vlarge_pdf (double x)
{
double c = 2.71828181565;
double b = 6.32899304917e-10;
double d = 1e4;
return gsl_ran_gamma_pdf ((x / d) + c, 4294967296.0, b) / d;
}
double
test_gaussian (void)
{
return gsl_ran_gaussian (r_global, 3.0);
}
double
test_gaussian_pdf (double x)
{
return gsl_ran_gaussian_pdf (x, 3.0);
}
double
test_gaussian_ratio_method (void)
{
return gsl_ran_gaussian_ratio_method (r_global, 3.0);
}
double
test_gaussian_ratio_method_pdf (double x)
{
return gsl_ran_gaussian_pdf (x, 3.0);
}
double
test_gaussian_ziggurat (void)
{
return gsl_ran_gaussian_ziggurat (r_global, 3.12);
}
double
test_gaussian_ziggurat_pdf (double x)
{
return gsl_ran_gaussian_pdf (x, 3.12);
}
double
test_gaussian_tail (void)
{
return gsl_ran_gaussian_tail (r_global, 1.7, 0.25);
}
double
test_gaussian_tail_pdf (double x)
{
return gsl_ran_gaussian_tail_pdf (x, 1.7, 0.25);
}
double
test_gaussian_tail1 (void)
{
return gsl_ran_gaussian_tail (r_global, -1.7, 5.0);
}
double
test_gaussian_tail1_pdf (double x)
{
return gsl_ran_gaussian_tail_pdf (x, -1.7, 5.0);
}
double
test_gaussian_tail2 (void)
{
return gsl_ran_gaussian_tail (r_global, 0.1, 2.0);
}
double
test_gaussian_tail2_pdf (double x)
{
return gsl_ran_gaussian_tail_pdf (x, 0.1, 2.0);
}
double
test_ugaussian (void)
{
return gsl_ran_ugaussian (r_global);
}
double
test_ugaussian_pdf (double x)
{
return gsl_ran_ugaussian_pdf (x);
}
double
test_ugaussian_ratio_method (void)
{
return gsl_ran_ugaussian_ratio_method (r_global);
}
double
test_ugaussian_ratio_method_pdf (double x)
{
return gsl_ran_ugaussian_pdf (x);
}
double
test_ugaussian_tail (void)
{
return gsl_ran_ugaussian_tail (r_global, 3.0);
}
double
test_ugaussian_tail_pdf (double x)
{
return gsl_ran_ugaussian_tail_pdf (x, 3.0);
}
double
test_bivariate_gaussian1 (void)
{
double x = 0, y = 0;
gsl_ran_bivariate_gaussian (r_global, 3.0, 2.0, 0.3, &x, &y);
return x;
}
double
test_bivariate_gaussian1_pdf (double x)
{
return gsl_ran_gaussian_pdf (x, 3.0);
}
double
test_bivariate_gaussian2 (void)
{
double x = 0, y = 0;
gsl_ran_bivariate_gaussian (r_global, 3.0, 2.0, 0.3, &x, &y);
return y;
}
double
test_bivariate_gaussian2_pdf (double y)
{
int i, n = 10;
double sum = 0;
double a = -10, b = 10, dx = (b - a) / n;
for (i = 0; i < n; i++)
{
double x = a + i * dx;
sum += gsl_ran_bivariate_gaussian_pdf (x, y, 3.0, 2.0, 0.3) * dx;
}
return sum;
}
double
test_bivariate_gaussian3 (void)
{
double x = 0, y = 0;
gsl_ran_bivariate_gaussian (r_global, 3.0, 2.0, 0.3, &x, &y);
return x + y;
}
double
test_bivariate_gaussian3_pdf (double x)
{
double sx = 3.0, sy = 2.0, r = 0.3;
double su = (sx + r * sy);
double sv = sy * sqrt (1 - r * r);
double sigma = sqrt (su * su + sv * sv);
return gsl_ran_gaussian_pdf (x, sigma);
}
double
test_bivariate_gaussian4 (void)
{
double x = 0, y = 0;
gsl_ran_bivariate_gaussian (r_global, 3.0, 2.0, -0.5, &x, &y);
return x + y;
}
double
test_bivariate_gaussian4_pdf (double x)
{
double sx = 3.0, sy = 2.0, r = -0.5;
double su = (sx + r * sy);
double sv = sy * sqrt (1 - r * r);
double sigma = sqrt (su * su + sv * sv);
return gsl_ran_gaussian_pdf (x, sigma);
}
/* Examples from R (GPL): http://www.r-project.org/
* library(mvtnorm); packageVersion("mvtnorm") # 1.0.5
* mu <- c(1, 2)
* Sigma <- matrix(c(4,2, 2,3), ncol=2)
* x <- c(0, 0)
* sprintf("%.15f", dmvnorm(x=x, mean=mu, sigma=Sigma, log=TRUE)) # -3.565097837249263
*/
void
test_multivariate_gaussian_log_pdf (void)
{
size_t d = 2;
const double exp_res = -3.565097837249263;
double obs_res;
gsl_vector * mu = gsl_vector_calloc(d);
gsl_matrix * Sigma = gsl_matrix_calloc(d, d);
gsl_matrix * L = gsl_matrix_calloc(d, d);
gsl_vector * x = gsl_vector_calloc(d);
gsl_vector * work = gsl_vector_calloc(d);
gsl_vector_set(mu, 0, 1);
gsl_vector_set(mu, 1, 2);
gsl_matrix_set(Sigma, 0, 0, 4);
gsl_matrix_set(Sigma, 1, 1, 3);
gsl_matrix_set(Sigma, 0, 1, 2);
gsl_matrix_set(Sigma, 1, 0, 2);
gsl_matrix_memcpy(L, Sigma);
gsl_linalg_cholesky_decomp1(L);
gsl_ran_multivariate_gaussian_log_pdf(x, mu, L, &obs_res, work);
gsl_test_rel(obs_res, exp_res, 1.0e-10, "gsl_ran_multivariate_gaussian_log_pdf");
gsl_vector_free(mu);
gsl_matrix_free(Sigma);
gsl_matrix_free(L);
gsl_vector_free(x);
gsl_vector_free(work);
}
/* Examples from R (GPL): http://www.r-project.org/
* library(mvtnorm); packageVersion("mvtnorm") # 1.0.5
* mu <- c(1, 2)
* Sigma <- matrix(c(4,2, 2,3), ncol=2)
* x <- c(0, 0)
* sprintf("%.15f", dmvnorm(x=x, mean=mu, sigma=Sigma, log=FALSE)) # 0.028294217120391
*/
void
test_multivariate_gaussian_pdf (void)
{
size_t d = 2;
const double exp_res = 0.028294217120391;
double obs_res = 0;
gsl_vector * mu = gsl_vector_calloc(d);
gsl_matrix * Sigma = gsl_matrix_calloc(d, d);
gsl_matrix * L = gsl_matrix_calloc(d, d);
gsl_vector * x = gsl_vector_calloc(d);
gsl_vector * work = gsl_vector_calloc(d);
gsl_vector_set(mu, 0, 1);
gsl_vector_set(mu, 1, 2);
gsl_matrix_set(Sigma, 0, 0, 4);
gsl_matrix_set(Sigma, 1, 1, 3);
gsl_matrix_set(Sigma, 0, 1, 2);
gsl_matrix_set(Sigma, 1, 0, 2);
gsl_matrix_memcpy(L, Sigma);
gsl_linalg_cholesky_decomp1(L);
gsl_ran_multivariate_gaussian_pdf(x, mu, L, &obs_res, work);
gsl_test_rel(obs_res, exp_res, 1.0e-10, "gsl_ran_multivariate_gaussian_pdf");
gsl_vector_free(mu);
gsl_matrix_free(Sigma);
gsl_matrix_free(L);
gsl_vector_free(x);
gsl_vector_free(work);
}
/* Draw N random vectors according to a given MVN(mu,Sigma). Then, check that
* one can't reject the null hypothesis that the sample mean is equal to
* the true mean, using Hotelling's test statistic at 95% confidence level.
* Details in "Applied Multivariate Statistical Analysis" by Johnson & Wichern
* (2001), section 5, page 212.
*/
void
test_multivariate_gaussian (void)
{
size_t d = 2, i = 0;
int status = 0;
double T2 = 0, threshold = 0, alpha = 0.05, pvalue = 0;
gsl_vector * mu = gsl_vector_calloc(d);
gsl_matrix * Sigma = gsl_matrix_calloc(d, d);
gsl_matrix * L = gsl_matrix_calloc(d, d);
gsl_vector * sample = gsl_vector_calloc(d);
gsl_matrix * samples = gsl_matrix_calloc(N, d);
gsl_vector * mu_hat = gsl_vector_calloc(d);
gsl_matrix * Sigma_hat = gsl_matrix_calloc(d, d);
gsl_vector * mu_hat_ctr = gsl_vector_calloc(d);
gsl_matrix * Sigma_hat_inv = gsl_matrix_calloc(d, d);
gsl_vector * tmp = gsl_vector_calloc(d);
/* set the true values of parameters mu and Sigma */
gsl_vector_set(mu, 0, 1);
gsl_vector_set(mu, 1, 2);
gsl_matrix_set(Sigma, 0, 0, 4);
gsl_matrix_set(Sigma, 1, 1, 3);
gsl_matrix_set(Sigma, 0, 1, 2);
gsl_matrix_set(Sigma, 1, 0, 2);
/* draw N random vectors */
gsl_matrix_memcpy(L, Sigma);
gsl_linalg_cholesky_decomp1(L);
for (i = 0; i < N; ++i) {
gsl_ran_multivariate_gaussian(r_global, mu, L, sample);
gsl_matrix_set_row(samples, i, sample);
}
/* compute the maximum-likelihood estimates */
gsl_ran_multivariate_gaussian_mean (samples, mu_hat);
gsl_ran_multivariate_gaussian_vcov (samples, Sigma_hat);
/* compute Hotelling's test statistic:
T^2 = n (hat{mu} - mu)' hat{Sigma}^-1 (hat{mu} - mu) */
gsl_vector_memcpy(mu_hat_ctr, mu_hat);
gsl_vector_sub(mu_hat_ctr, mu);
gsl_matrix_memcpy(Sigma_hat_inv, Sigma_hat);
gsl_linalg_cholesky_decomp1(Sigma_hat_inv);
gsl_linalg_cholesky_invert(Sigma_hat_inv);
gsl_blas_dgemv(CblasNoTrans, 1, Sigma_hat_inv, mu_hat_ctr, 0, tmp);
gsl_blas_ddot(mu_hat_ctr, tmp, &T2);
T2 *= N;
/* test if the null hypothesis (hat{mu} = mu) can be rejected
at the alpha level*/
threshold = (N-1) * d / (double)(N-d) * gsl_cdf_fdist_Pinv(1-alpha, d, N-d);
status = (T2 > threshold);
gsl_test(status,
"test gsl_ran_multivariate_gaussian: T2 %f < %f",
T2, threshold);
pvalue = gsl_cdf_fdist_Q(T2, d, N-d);
status = (pvalue < alpha);
gsl_test(status,
"test gsl_ran_multivariate_gaussian: p value %f > %f",
pvalue, alpha);
gsl_vector_free(mu);
gsl_matrix_free(Sigma);
gsl_matrix_free(L);
gsl_vector_free(sample);
gsl_matrix_free(samples);
gsl_vector_free(mu_hat);
gsl_matrix_free(Sigma_hat);
gsl_vector_free(mu_hat_ctr);
gsl_matrix_free(Sigma_hat_inv);
gsl_vector_free(tmp);
}
double
test_geometric (void)
{
return gsl_ran_geometric (r_global, 0.5);
}
double
test_geometric_pdf (unsigned int n)
{
return gsl_ran_geometric_pdf (n, 0.5);
}
double
test_geometric1 (void)
{
return gsl_ran_geometric (r_global, 1.0);
}
double
test_geometric1_pdf (unsigned int n)
{
return gsl_ran_geometric_pdf (n, 1.0);
}
double
test_hypergeometric1 (void)
{
return gsl_ran_hypergeometric (r_global, 5, 7, 4);
}
double
test_hypergeometric1_pdf (unsigned int n)
{
return gsl_ran_hypergeometric_pdf (n, 5, 7, 4);
}
double
test_hypergeometric2 (void)
{
return gsl_ran_hypergeometric (r_global, 5, 7, 11);
}
double
test_hypergeometric2_pdf (unsigned int n)
{
return gsl_ran_hypergeometric_pdf (n, 5, 7, 11);
}
double
test_hypergeometric3 (void)
{
return gsl_ran_hypergeometric (r_global, 5, 7, 1);
}
double
test_hypergeometric3_pdf (unsigned int n)
{
return gsl_ran_hypergeometric_pdf (n, 5, 7, 1);
}
double
test_hypergeometric4 (void)
{
return gsl_ran_hypergeometric (r_global, 5, 7, 20);
}
double
test_hypergeometric4_pdf (unsigned int n)
{
return gsl_ran_hypergeometric_pdf (n, 5, 7, 20);
}
double
test_hypergeometric5 (void)
{
return gsl_ran_hypergeometric (r_global, 2, 7, 5);
}
double
test_hypergeometric5_pdf (unsigned int n)
{
return gsl_ran_hypergeometric_pdf (n, 2, 7, 5);
}
double
test_hypergeometric6 (void)
{
return gsl_ran_hypergeometric (r_global, 2, 10, 3);
}
double
test_hypergeometric6_pdf (unsigned int n)
{
return gsl_ran_hypergeometric_pdf (n, 2, 10, 3);
}
double
test_gumbel1 (void)
{
return gsl_ran_gumbel1 (r_global, 3.12, 4.56);
}
double
test_gumbel1_pdf (double x)
{
return gsl_ran_gumbel1_pdf (x, 3.12, 4.56);
}
double
test_gumbel2 (void)
{
return gsl_ran_gumbel2 (r_global, 3.12, 4.56);
}
double
test_gumbel2_pdf (double x)
{
return gsl_ran_gumbel2_pdf (x, 3.12, 4.56);
}
double
test_landau (void)
{
return gsl_ran_landau (r_global);
}
double
test_landau_pdf (double x)
{
return gsl_ran_landau_pdf (x);
}
double
test_levy1 (void)
{
return gsl_ran_levy (r_global, 5.0, 1.0);
}
double
test_levy1_pdf (double x)
{
return gsl_ran_cauchy_pdf (x, 5.0);
}
double
test_levy2 (void)
{
return gsl_ran_levy (r_global, 5.0, 2.0);
}
double
test_levy2_pdf (double x)
{
return gsl_ran_gaussian_pdf (x, sqrt (2.0) * 5.0);
}
double
test_levy1a (void)
{
return gsl_ran_levy (r_global, 5.0, 1.01);
}
double
test_levy1a_pdf (double x)
{
return gsl_ran_cauchy_pdf (x, 5.0);
}
double
test_levy2a (void)
{
return gsl_ran_levy (r_global, 5.0, 1.99);
}
double
test_levy2a_pdf (double x)
{
return gsl_ran_gaussian_pdf (x, sqrt (2.0) * 5.0);
}
double
test_levy_skew1 (void)
{
return gsl_ran_levy_skew (r_global, 5.0, 1.0, 0.0);
}
double
test_levy_skew1_pdf (double x)
{
return gsl_ran_cauchy_pdf (x, 5.0);
}
double
test_levy_skew2 (void)
{
return gsl_ran_levy_skew (r_global, 5.0, 2.0, 0.0);
}
double
test_levy_skew2_pdf (double x)
{
return gsl_ran_gaussian_pdf (x, sqrt (2.0) * 5.0);
}
double
test_levy_skew1a (void)
{
return gsl_ran_levy_skew (r_global, 5.0, 1.01, 0.0);
}
double
test_levy_skew1a_pdf (double x)
{
return gsl_ran_cauchy_pdf (x, 5.0);
}
double
test_levy_skew2a (void)
{
return gsl_ran_levy_skew (r_global, 5.0, 1.99, 0.0);
}
double
test_levy_skew2a_pdf (double x)
{
return gsl_ran_gaussian_pdf (x, sqrt (2.0) * 5.0);
}
double
test_levy_skew1b (void)
{
return gsl_ran_levy_skew (r_global, 5.0, 1.01, 0.001);
}
double
test_levy_skew1b_pdf (double x)
{
return gsl_ran_cauchy_pdf (x, 5.0);
}
double
test_levy_skew2b (void)
{
return gsl_ran_levy_skew (r_global, 5.0, 1.99, 0.001);
}
double
test_levy_skew2b_pdf (double x)
{
return gsl_ran_gaussian_pdf (x, sqrt (2.0) * 5.0);
}
double
test_logistic (void)
{
return gsl_ran_logistic (r_global, 3.1);
}
double
test_logistic_pdf (double x)
{
return gsl_ran_logistic_pdf (x, 3.1);
}
double
test_logarithmic (void)
{
return gsl_ran_logarithmic (r_global, 0.4);
}
double
test_logarithmic_pdf (unsigned int n)
{
return gsl_ran_logarithmic_pdf (n, 0.4);
}
double
test_lognormal (void)
{
return gsl_ran_lognormal (r_global, 2.7, 1.3);
}
double
test_lognormal_pdf (double x)
{
return gsl_ran_lognormal_pdf (x, 2.7, 1.3);
}
double
test_multinomial (void)
{
const size_t K = 3;
const unsigned int sum_n = BINS;
unsigned int n[3];
/* Test use of weights instead of probabilities. */
const double p[] = { 2., 7., 1.};
gsl_ran_multinomial ( r_global, K, sum_n, p, n);
return n[0];
}
double
test_multinomial_pdf (unsigned int n_0)
{
/* The margional distribution of just 1 variate is binomial. */
size_t K = 2;
/* Test use of weights instead of probabilities */
double p[] = { 0.4, 1.6};
const unsigned int sum_n = BINS;
unsigned int n[2];
n[0] = n_0;
n[1] =sum_n - n_0;
return gsl_ran_multinomial_pdf (K, p, n);
}
double
test_multinomial_large (void)
{
const unsigned int sum_n = BINS;
unsigned int n[MULTI_DIM];
const double p[MULTI_DIM] = { 0.2, 0.20, 0.17, 0.14, 0.12,
0.07, 0.05, 0.04, 0.01, 0.00 };
gsl_ran_multinomial ( r_global, MULTI_DIM, sum_n, p, n);
return n[0];
}
double
test_multinomial_large_pdf (unsigned int n_0)
{
return test_multinomial_pdf(n_0);
}
double
test_negative_binomial (void)
{
return gsl_ran_negative_binomial (r_global, 0.3, 20.0);
}
double
test_negative_binomial_pdf (unsigned int n)
{
return gsl_ran_negative_binomial_pdf (n, 0.3, 20.0);
}
double
test_pascal (void)
{
return gsl_ran_pascal (r_global, 0.8, 3);
}
double
test_pascal_pdf (unsigned int n)
{
return gsl_ran_pascal_pdf (n, 0.8, 3);
}
double
test_pareto (void)
{
return gsl_ran_pareto (r_global, 1.9, 2.75);
}
double
test_pareto_pdf (double x)
{
return gsl_ran_pareto_pdf (x, 1.9, 2.75);
}
double
test_rayleigh (void)
{
return gsl_ran_rayleigh (r_global, 1.9);
}
double
test_rayleigh_pdf (double x)
{
return gsl_ran_rayleigh_pdf (x, 1.9);
}
double
test_rayleigh_tail (void)
{
return gsl_ran_rayleigh_tail (r_global, 2.7, 1.9);
}
double
test_rayleigh_tail_pdf (double x)
{
return gsl_ran_rayleigh_tail_pdf (x, 2.7, 1.9);
}
double
test_poisson (void)
{
return gsl_ran_poisson (r_global, 5.0);
}
double
test_poisson_pdf (unsigned int n)
{
return gsl_ran_poisson_pdf (n, 5.0);
}
double
test_poisson_large (void)
{
return gsl_ran_poisson (r_global, 30.0);
}
double
test_poisson_large_pdf (unsigned int n)
{
return gsl_ran_poisson_pdf (n, 30.0);
}
double
test_tdist1 (void)
{
return gsl_ran_tdist (r_global, 1.75);
}
double
test_tdist1_pdf (double x)
{
return gsl_ran_tdist_pdf (x, 1.75);
}
double
test_tdist2 (void)
{
return gsl_ran_tdist (r_global, 12.75);
}
double
test_tdist2_pdf (double x)
{
return gsl_ran_tdist_pdf (x, 12.75);
}
double
test_laplace (void)
{
return gsl_ran_laplace (r_global, 2.75);
}
double
test_laplace_pdf (double x)
{
return gsl_ran_laplace_pdf (x, 2.75);
}
double
test_weibull (void)
{
return gsl_ran_weibull (r_global, 3.14, 2.75);
}
double
test_weibull_pdf (double x)
{
return gsl_ran_weibull_pdf (x, 3.14, 2.75);
}
double
test_weibull1 (void)
{
return gsl_ran_weibull (r_global, 2.97, 1.0);
}
double
test_weibull1_pdf (double x)
{
return gsl_ran_weibull_pdf (x, 2.97, 1.0);
}
| {
"alphanum_fraction": 0.6688211441,
"avg_line_length": 20.6727659574,
"ext": "c",
"hexsha": "10800a0ad4129e11ccae7d35d767bbf004fb4cbd",
"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/randist/test.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/randist/test.c",
"max_line_length": 94,
"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/randist/test.c",
"max_stars_repo_stars_event_max_datetime": "2020-10-18T13:15:00.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-10-18T13:15:00.000Z",
"num_tokens": 16789,
"size": 48581
} |
#ifndef __MATH_FUNCTINS_H__
#define __MATH_FUNCTINS_H__
#include <stdint.h>
#include <cmath> // for std::fabs and std::signbit
#include <cblas.h>
#include <cudnn.h>
#include <cublas_v2.h>
#include <cuda.h>
#include <cuda_runtime.h>
#include <curand.h>
#include <driver_types.h> // cuda driver types
#include <algorithm>
#include <glog/logging.h>
#define PERMUTELAYER_ORDERNUM 4
#define BLOCK 512
//
// CUDA macros
//
// CUDA: various checks for different function calls.
#define CUDA_CHECK(condition) \
/* Code block avoids redefinition of cudaError_t error */ \
do { \
cudaError_t error = condition; \
CHECK_EQ(error, cudaSuccess) << " " << cudaGetErrorString(error); \
} while (0)
#define CUBLAS_CHECK(condition) \
do { \
cublasStatus_t status = condition; \
CHECK_EQ(status, CUBLAS_STATUS_SUCCESS) << " " \
<< cublasGetErrorString(status); \
} while (0)
#define CURAND_CHECK(condition) \
do { \
curandStatus_t status = condition; \
CHECK_EQ(status, CURAND_STATUS_SUCCESS) << " " \
<< curandGetErrorString(status); \
} while (0)
// CUDA: grid stride looping
#define CUDA_KERNEL_LOOP(i, n) \
for (int i = blockIdx.x * blockDim.x + threadIdx.x; \
i < (n); \
i += blockDim.x * gridDim.x)
// CUDA: check for error after kernel execution and exit loudly if there is one.
#define CUDA_POST_KERNEL_CHECK CUDA_CHECK(cudaPeekAtLastError())
// CUDA: library error reporting.
const char* cublasGetErrorString(cublasStatus_t error);
const char* curandGetErrorString(curandStatus_t error);
// CUDA: use 512 threads per block
const int TENSORRT_CUDA_NUM_THREADS = 256;
// CUDA: number of blocks for threads.
inline int TENSORRT_GET_BLOCKS(const int N) {
return (N + TENSORRT_CUDA_NUM_THREADS - 1) / TENSORRT_CUDA_NUM_THREADS;
}
/*
* function: X[i] = alpha,initialize X with constant alpha
*
*/
template <typename Dtype>
void tensorrt_gpu_set(const int N, const Dtype alpha, Dtype *X);
/*
* function: y[index] = pow(a[index], alpha)
*@params n: the dims of matrix a
*@params a: matrix
*@params y: vector
*/
template <typename Dtype>
void tensorrt_gpu_powx(const int n, const Dtype* a, const Dtype alpha, Dtype* y);
/*
*function:y = alpha*A*x + beta*y;
*@params handle: handle
*@params TransA: transpose flag
*@params M: the rows of A
*@params N: the cols of A
*@params alpha: the coefficient of A*x
*@params A: matrix [M x N]
*@params x: vector x
*@params beta: the coefficient of y
*@params y: vector y
*/
template <typename Dtype>
void tensorrt_gpu_gemv(cublasHandle_t handle,const CBLAS_TRANSPOSE TransA, const int M, const int N,
const Dtype alpha, const Dtype* A, const Dtype* x, const Dtype beta,
Dtype* y);
template <typename Dtype>
void tensorrt_gpu_divbsx(const int nthreads, const Dtype* A,
const Dtype* v, const int rows, const int cols, const CBLAS_TRANSPOSE trans,
Dtype* B);
template <typename Dtype>
void tensorrt_gpu_mulbsx(const int nthreads, const Dtype* A,
const Dtype* v, const int rows, const int cols, const CBLAS_TRANSPOSE trans,
Dtype* B);
cudaError_t tensorrt_gpu_permute(const int nthreads,float* const bottom_data,const bool forward,
const int* permute_order,const int* old_steps,const int* new_steps,const int num_axes,float* const top_data,cudaStream_t stream);
cudaError_t SoftmaxLayer(const float *bottom_data, int count, int channels, int outer_num_, int inner_num_, float *scale_data, float *top_data, cudaStream_t stream);
cudaError_t ConcatLayer(int nthreads, const float *bottom_data, bool kForward, int num_concats_, int concat_input_size_, int top_concat_axis, int bottom_concat_axis, int offset_concat_axis, float *top_data, cudaStream_t stream);
//cudaError_t cudaSoftmax(int n, int channels, float* x, float*y, cudaStream_t stream);
//virtual void Forward_gpu(const vector<Blob<Dtype>*>& bottom,const vector<Blob<Dtype>*>& top);
cudaError_t cudaSoftmax_caffe(int count,int channels,float* x,float* y, cudaStream_t stream);
cudaError_t cudaDetectionOutput_caffe( int bottom0_count,
int bottom1_count,
float* loc_data,
float* bottom1,
float* prior_data,
float* bottom3,
float* bottom4,
float* y,
cudaStream_t stream);
#endif
| {
"alphanum_fraction": 0.6630785791,
"avg_line_length": 33.9051094891,
"ext": "h",
"hexsha": "82d73a61d10e6ec509bed909fa21fdccc25a7046",
"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": "accae48e081f9fc55df64273c4c1285572283fdf",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "niekai1982/MultiCamer-tx2",
"max_forks_repo_path": "include/mathFunctions.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "accae48e081f9fc55df64273c4c1285572283fdf",
"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": "niekai1982/MultiCamer-tx2",
"max_issues_repo_path": "include/mathFunctions.h",
"max_line_length": 229,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "accae48e081f9fc55df64273c4c1285572283fdf",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "niekai1982/MultiCamer-tx2",
"max_stars_repo_path": "include/mathFunctions.h",
"max_stars_repo_stars_event_max_datetime": "2019-01-21T06:20:59.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-01-21T06:20:59.000Z",
"num_tokens": 1117,
"size": 4645
} |
#include <stdio.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_histogram2d.h>
int
main (void)
{
const gsl_rng_type * T;
gsl_rng * r;
gsl_histogram2d * h = gsl_histogram2d_alloc (10, 10);
gsl_histogram2d_set_ranges_uniform (h,
0.0, 1.0,
0.0, 1.0);
gsl_histogram2d_accumulate (h, 0.3, 0.3, 1);
gsl_histogram2d_accumulate (h, 0.8, 0.1, 5);
gsl_histogram2d_accumulate (h, 0.7, 0.9, 0.5);
gsl_rng_env_setup ();
T = gsl_rng_default;
r = gsl_rng_alloc (T);
{
int i;
gsl_histogram2d_pdf * p
= gsl_histogram2d_pdf_alloc (h->nx, h->ny);
gsl_histogram2d_pdf_init (p, h);
for (i = 0; i < 1000; i++) {
double x, y;
double u = gsl_rng_uniform (r);
double v = gsl_rng_uniform (r);
gsl_histogram2d_pdf_sample (p, u, v, &x, &y);
printf ("%g %g\n", x, y);
}
gsl_histogram2d_pdf_free (p);
}
gsl_histogram2d_free (h);
gsl_rng_free (r);
return 0;
}
| {
"alphanum_fraction": 0.5612840467,
"avg_line_length": 20.1568627451,
"ext": "c",
"hexsha": "3fcabb48efb1e0cb169938ebfba0d161bc1e82cf",
"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/histogram2d.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/histogram2d.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/histogram2d.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": 351,
"size": 1028
} |
// Copyright (C) 2021 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
#ifndef _HEBench_ClearText_BE_DataPack_H_7e5fa8c2415240ea93eff148ed73539b
#define _HEBench_ClearText_BE_DataPack_H_7e5fa8c2415240ea93eff148ed73539b
#include <memory>
#include <vector>
#include <gsl/gsl>
#include "clear_error.h"
#include "hebench/api_bridge/types.h"
#include "hebench/api_bridge/cpp/hebench.hpp"
template <class T>
/**
* @brief Encapsulates a HEBench DataPack.
*/
class ClearDataPack : public hebench::cpp::ITaggedObject
{
private:
HEBERROR_DECLARE_CLASS_NAME(ClearDataPack)
public:
explicit ClearDataPack(const hebench::APIBridge::DataPack &data_pack);
/**
* @brief Creates a new data pack with specified data sizes.
* @param sample_count[in] Number of data samples to be contained in this pack.
* @param p_sample_sizes[in] List of number of items per data sample.
* @param position[in] Parameter position corresponding to hebench::APIBridge::DataPack::param_position.
* @details This constructor initializes vector<vector<T>> data structure of the shape
* @code
* data = vector<vector<T>>(sample_count)
* @endcode
* and
* @code
* data[i] = vector<T>(p_sample_sizes[i])
* @endcode
*/
explicit ClearDataPack(std::uint64_t sample_count,
const std::uint64_t *p_sample_sizes,
std::uint64_t position);
~ClearDataPack() override {}
/**
* @brief Fills pre-allocated HEBench data pack with the data contained in this
* data pack.
* @param data_pack[out] HEBench data pack where to store the data.
* @param b_pad[in] If true, any extra space in \p data_pack will be padded with
* zeroes. Otherwise, extra space will not be overwritten.
* @details This method is the inverse of the constructor. Thus, if the constructor
* performs some type of conversion, it must be reversible, and this method
* reverses the conversion.
*
* Default implementation is a simple copy of the data.
*/
virtual void fillHEBenchDataPack(hebench::APIBridge::DataPack &data_pack, bool b_pad) const;
std::uint64_t getSamplesCount() const { return m_data.size(); }
gsl::span<T> getSample(std::uint64_t sample_index);
gsl::span<const T> getSample(std::uint64_t sample_index) const;
/**
* @brief Copies the data contained in \p sample_data into this data pack's
* sample specified by \p sample index.
* @param sample_index[in] Index of data sample in this data pack to overwrite.
* @param sample_data[in] Data to copy into this data pack sample.
* @details The size of this data pack sample will be resized to match the
* size of specified \p sample-data.
*/
void setSample(std::uint64_t sample_index, const gsl::span<T> &sample_data);
/**
* @brief Copies the data contained in \p sample_data into this data pack's
* sample specified by \p sample index.
* @param sample_index[in] Index of data sample in this data pack to overwrite.
* @param sample_data[in] Data to copy into this data pack sample.
* @param pad_value[in] Value to be used for padding if needed.
* @details The size of this data pack sample will remain constant. If not
* enough space, this method will copy as much data as it can from \p sample_data
* into the specified sample. If this data pack's sample's size is more than
* the supplied data in \p sample_data, the remaining space will be padded
* with the specified padding value \p pad_value.
*/
void setSample(std::uint64_t sample_index, const gsl::span<T> &sample_data, const T &pad_value);
std::uint64_t position() const { return m_position; }
protected:
std::vector<std::vector<T>> m_data;
ClearDataPack(std::uint64_t position = 0) :
m_position(position) {}
void allocateBuffers(std::uint64_t sample_count, const std::uint64_t *p_sample_sizes);
void allocateBuffers(const hebench::APIBridge::DataPack &data_pack);
/**
* @brief Performs a simple copy.
* @param data_pack
*/
virtual void fillFromHEBenchDataPack(const hebench::APIBridge::DataPack &data_pack);
private:
std::uint64_t m_position;
};
#include "inl/data_container.inl"
#endif // defined _HEBench_ClearText_BE_DataPack_H_7e5fa8c2415240ea93eff148ed73539b
| {
"alphanum_fraction": 0.7054404735,
"avg_line_length": 39.5765765766,
"ext": "h",
"hexsha": "fccdf51c73f1c521ee6a89d79ba8a55df7ec15c4",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2021-11-05T18:01:48.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-11-05T18:01:48.000Z",
"max_forks_repo_head_hexsha": "ff74311abd749809b732f1f2f63fe78e245c726d",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "jlakness-intel/backend-cpu-helib",
"max_forks_repo_path": "include/data_container.h",
"max_issues_count": 2,
"max_issues_repo_head_hexsha": "ff74311abd749809b732f1f2f63fe78e245c726d",
"max_issues_repo_issues_event_max_datetime": "2021-12-16T23:37:53.000Z",
"max_issues_repo_issues_event_min_datetime": "2021-12-06T19:37:42.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "jlakness-intel/backend-cpu-helib",
"max_issues_repo_path": "include/data_container.h",
"max_line_length": 108,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "ff74311abd749809b732f1f2f63fe78e245c726d",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "jlakness-intel/backend-cpu-helib",
"max_stars_repo_path": "include/data_container.h",
"max_stars_repo_stars_event_max_datetime": "2022-02-28T17:57:32.000Z",
"max_stars_repo_stars_event_min_datetime": "2022-02-28T17:57:32.000Z",
"num_tokens": 1110,
"size": 4393
} |
#pragma once
#include "poll_event.h"
#include "poll_response.h"
#include "poll_target.h"
#include <cstddef>
#include <optional>
#include <string>
#include <vector>
#include <gsl/span>
namespace wrappers::zmq {
class context;
class socket final {
public:
enum class type {
pair,
pub,
sub,
req,
rep,
dealer,
router,
pull,
push,
xpub,
xsub,
stream,
};
explicit socket(context &ctx, type socket_type) noexcept;
socket(const socket &other) = delete;
socket &operator=(const socket &other) = delete;
socket(socket &&other) noexcept;
socket &operator=(socket &&other) noexcept;
~socket() noexcept;
[[nodiscard]] bool bind(const std::string &endpoint) noexcept;
[[nodiscard]] bool connect(const std::string &endpoint) noexcept;
[[nodiscard]] bool blocking_send() noexcept;
[[nodiscard]] bool blocking_send(gsl::span<std::byte> message) noexcept;
[[nodiscard]] std::optional<std::vector<std::byte>>
blocking_receive() noexcept;
[[nodiscard]] bool
async_receive(void *data,
void (*callback)(void *, gsl::span<std::byte>)) noexcept;
friend std::optional<std::vector<poll_response>>
blocking_poll(gsl::span<poll_target> targets) noexcept;
private:
void *m_socket = nullptr;
};
} // namespace wrappers::zmq
| {
"alphanum_fraction": 0.6328571429,
"avg_line_length": 21.5384615385,
"ext": "h",
"hexsha": "f7b41233c09db224b291b007d63906e9dc56e837",
"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": "a76b08fa4f20a3612988a0d84e5b14f7822638ee",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "Longhanks/linkollector-win",
"max_forks_repo_path": "src/wrappers/zmq/socket.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "a76b08fa4f20a3612988a0d84e5b14f7822638ee",
"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": "Longhanks/linkollector-win",
"max_issues_repo_path": "src/wrappers/zmq/socket.h",
"max_line_length": 76,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "a76b08fa4f20a3612988a0d84e5b14f7822638ee",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "Longhanks/linkollector-win",
"max_stars_repo_path": "src/wrappers/zmq/socket.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 320,
"size": 1400
} |
/*
* MathUtils.h
*
* Author:
* Oleg Kalashev
*
* Copyright (c) 2020 Institute for Nuclear Research, RAS
*
* 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 MATHUTILS_H_
#define MATHUTILS_H_
#include <gsl/gsl_roots.h>
#include <gsl/gsl_integration.h>
#include <iostream>
#include "Utils.h"
#include <limits>
namespace Utils {
template<typename X = double >
class FunctionX
{
public:
virtual X f(X _x) const = 0;
virtual X Xmin() const {return -std::numeric_limits<X>::max();}
virtual X Xmax() const {return std::numeric_limits<X>::max();}
inline X operator()(X _x) const {return f(_x);};
virtual ~FunctionX(){};
virtual FunctionX<X>* Clone() const { NOT_IMPLEMENTED; return 0; }
inline operator gsl_function() const
{
gsl_function result = {GslProxyFunc, (void*)this};
return result;
}
void Print(std::ostream& aOut, int nIntervals, bool aLogScale, double aXmin=-DBL_MAX, double aXmax=DBL_MAX) const
{
if(aXmin<Xmin())
aXmin = Xmin();
if(aXmax>Xmax())
aXmax = Xmax();
ASSERT(aXmin<=aXmax);
ASSERT(aXmax<DBL_MAX);
ASSERT(aXmin>-DBL_MAX);
ASSERT(nIntervals>=1);
ASSERT((!aLogScale) || aXmin>0);
double step = aLogScale?pow(aXmax/aXmin,1./nIntervals) : (aXmax-aXmin)/nIntervals;
double x = aXmin;
for(int i=0; i<=nIntervals; i++, (x = aLogScale ? x*step : x+step) )
aOut << x << "\t" << f(x) << "\n";
}
private:
static double GslProxyFunc (double x, void * params)
{
const FunctionX<X>* f = (const FunctionX<X>*)params;
return f->f(x);
}
};
template<typename X = double >
class Function2X
{
public:
virtual X f(X x, X y) const = 0;
virtual X MinArg(int aArgNo) const {return std::numeric_limits<X>::min();}
virtual X MaxArg(int aArgNo) const {return std::numeric_limits<X>::max();}
virtual inline X operator()(X _x, X _y) const {return f(_x,_y);};
virtual ~Function2X(){};
};
template<typename X = double >
class IFunctionCallHandlerX
{
public:
virtual void OnCall(const FunctionX<X>& aFunc, X aX, X aY) const = 0;
};
template<typename X = double >
class DebugFunctionX : public FunctionX<X>
{
public:
DebugFunctionX(const FunctionX<X>& aOrigFunc, const IFunctionCallHandlerX<X>& aDebugger):fOrigFunc(aOrigFunc),fDebugger(aDebugger){};
virtual X f(X _x) const
{
X y = fOrigFunc.f(_x);
fDebugger.OnCall(fOrigFunc, _x, y);
return y;
}
virtual ~DebugFunctionX(){};
virtual FunctionX<X>* Clone() const { return new DebugFunctionX<X>(fOrigFunc,fDebugger); }
private:
const FunctionX<X>& fOrigFunc;
const IFunctionCallHandlerX<X>& fDebugger;
};
template<typename X = double >
class FunctionCallLoggerX : public IFunctionCallHandlerX<X>
{
public:
FunctionCallLoggerX(std::ostream& aOutput) : fOutput(aOutput){}
virtual void OnCall(const FunctionX<X>& aFunc, X aX, X aY) const
{
((std::ostream&)fOutput) << aX << "\t" << aY << "\n";
}
virtual ~FunctionCallLoggerX()
{
fOutput << std::endl;
}
private:
std::ostream& fOutput;
};
typedef FunctionX<double> Function;
typedef Function2X<double> Function2;
template<typename X = double >
class ParamlessFunctionX : public FunctionX<X>
{
public:
ParamlessFunctionX(X (*aFunction)(X)):fFunction(aFunction){}
X f(X _x) const { return fFunction(_x); }
private:
X (*fFunction)(X);
};
typedef ParamlessFunctionX<double> ParamlessFunction;
template<typename X = double >
class ISampler {
public:
virtual X sample(const FunctionX<X> &f, X aTmin, X aTmax, X aRand,
X &aTotRate, X aRelErr, X aAbsErr = 1e300) = 0;
void UnitTest();
};
/// Mathematical functions
/// Static methods are thread-safe
/// Non-static methods are not guaranteed to be thread-safe
///TODO: make implementation using boost odeint and dense output and get rid of nr library
class MathUtils {
public:
MathUtils();
~MathUtils();
static inline double RelDifference(double aVal1, double aVal2){
double meanNorm = 0.5*fabs(aVal1)+fabs(aVal2);
return meanNorm==0. ? 0.:fabs(aVal1-aVal2)/meanNorm;
}
static double SolveEquation(
double (*aEquation) (double, void*),
double x_lo, double x_hi, void* aEquationPars = 0,
const double relError=1e-3, const int max_iter=100,
const gsl_root_fsolver_type *T = gsl_root_fsolver_bisection);
static double SolveEquation(
gsl_function f, double x_lo, double x_hi,
const double relError=1e-3, const int max_iter=100,
const gsl_root_fsolver_type *T = gsl_root_fsolver_bisection);
double Integration_qag (
gsl_function aFunction,
double aXmin,
double aXmax,
double epsabs,
double epsrel,
size_t limit,
int key=GSL_INTEG_GAUSS15);
template<typename X> bool SampleLogscaleDistribution(const Function& aDistrib, double aRand, X& aOutputX, X& aOutputIntegral, int nStepsS, X xMin, X xMax, double aRelError);
static bool SampleDistribution(const Function& aDistrib, double aRand, double& aOutputX, double& aOutputIntegral, double xMin, double xMax, double aRelError);
static bool SampleLogDistribution(const Function& aDistrib, double aRand, double& aOutputX, double& aOutputIntegral, double xMin, double xMax, double aRelError);
static bool SampleLogDistributionBoost(const Function& aDistrib, double aRand, double& aOutputX, double& aOutputIntegral, double xMin, double xMax, double aRelError);
static bool SampleLogDistributionNR(const Function& aDistrib, double aRand, double& aOutputX, double& aOutputIntegral, double xMin, double xMax, double aRelError);
template<typename X> static void RelAccuracy(X& aOutput);
static void SetLogger(IFunctionCallHandlerX<double>* aLogger) { fLogger = aLogger; }
static int UnitTest();
private:
static double GslProxySampleLogscaleDistributionFunc (double x, void * params)
{
x=exp(x);
const Function* f = (const Function*)params;
return x*f->f(x);
}
gsl_integration_workspace* gslQAGintegrator;
static IFunctionCallHandlerX<double>* fLogger;
};
class GslProxyFunction : public Function
{
public:
GslProxyFunction(gsl_function aFunction, double aXmin=-DBL_MAX, double aXmax=DBL_MAX) :
fFunction(aFunction),
fXmin(aXmin),
fXmax(aXmax){};
virtual double f(double _x) const
{
return fFunction.function(_x,fFunction.params);
}
virtual double Xmin() const {return fXmin;}
virtual double Xmax() const {return fXmax;}
Function* Clone() const
{//There is no way to clone fFunction.params
ASSERT(0);
Exception::Throw("GslProxyFunction doesn't support Clone");
return 0;
}
private:
gsl_function fFunction;
double fXmin;
double fXmax;
};
template<typename X = double >
class ConstFunctionX : public FunctionX<X>
{
public:
ConstFunctionX(X aValue, X aXmin=-std::numeric_limits<X>::max(), X aXmax=std::numeric_limits<X>::max()) :
fValue(aValue),
fXmin(aXmin),
fXmax(aXmax){};
virtual X f(X _x) const
{
return fValue;
}
virtual X Xmin() const {return fXmin;}
virtual X Xmax() const {return fXmax;}
FunctionX<X>* Clone() const
{
return new ConstFunctionX<X>(fValue, fXmin, fXmax);
}
private:
X fValue;
X fXmin;
X fXmax;
};
typedef ConstFunctionX<double> ConstFunction;
} /* namespace Utils */
#endif /* MATHUTILS_H_ */
| {
"alphanum_fraction": 0.7249659611,
"avg_line_length": 30.6022727273,
"ext": "h",
"hexsha": "f13823e35d28d82e7f2a60e324dd0bb45af6da6e",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2022-01-10T21:05:54.000Z",
"max_forks_repo_forks_event_min_datetime": "2020-12-16T08:23:34.000Z",
"max_forks_repo_head_hexsha": "2cfa58d2cd6f872612f6396d65781ad83211c06c",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "alexkorochkin/mcray",
"max_forks_repo_path": "src/lib/MathUtils.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "2cfa58d2cd6f872612f6396d65781ad83211c06c",
"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": "alexkorochkin/mcray",
"max_issues_repo_path": "src/lib/MathUtils.h",
"max_line_length": 174,
"max_stars_count": 7,
"max_stars_repo_head_hexsha": "2cfa58d2cd6f872612f6396d65781ad83211c06c",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "alexkorochkin/mcray",
"max_stars_repo_path": "src/lib/MathUtils.h",
"max_stars_repo_stars_event_max_datetime": "2022-01-15T22:56:26.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-12-16T08:23:31.000Z",
"num_tokens": 2264,
"size": 8079
} |
/* multimin/simplex2.c
*
* Copyright (C) 2007, 2008, 2009 Brian Gough
* Copyright (C) 2002 Tuomo Keskitalo, 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 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.
*/
/*
- Originally written by Tuomo Keskitalo <tuomo.keskitalo@iki.fi>
- Corrections to nmsimplex_iterate and other functions
by Ivo Alxneit <ivo.alxneit@psi.ch>
- Additional help by Brian Gough <bjg@network-theory.co.uk>
- Optimisations added by Brian Gough <bjg@network-theory.co.uk>
+ use BLAS for frequently-called functions
+ keep track of the center to avoid unnecessary computation
+ compute size as RMS value, allowing linear update on each step
instead of recomputing from all N+1 vectors.
*/
/* The Simplex method of Nelder and Mead, also known as the polytope
search alogorithm. Ref: Nelder, J.A., Mead, R., Computer Journal 7
(1965) pp. 308-313.
This implementation uses n+1 corner points in the simplex.
*/
#include <config.h>
#include <stdlib.h>
#include <gsl/gsl_blas.h>
#include <gsl/gsl_multimin.h>
#include <gsl/gsl_matrix_double.h>
typedef struct
{
gsl_matrix *x1; /* simplex corner points */
gsl_vector *y1; /* function value at corner points */
gsl_vector *ws1; /* workspace 1 for algorithm */
gsl_vector *ws2; /* workspace 2 for algorithm */
gsl_vector *center; /* center of all points */
gsl_vector *delta; /* current step */
gsl_vector *xmc; /* x - center (workspace) */
double S2;
unsigned long count;
}
nmsimplex_state_t;
static int
compute_center (const nmsimplex_state_t * state, gsl_vector * center);
static double
compute_size (nmsimplex_state_t * state, const gsl_vector * center);
static double
try_corner_move (const double coeff,
const nmsimplex_state_t * state,
size_t corner,
gsl_vector * xc, const gsl_multimin_function * f)
{
/* moves a simplex corner scaled by coeff (negative value represents
mirroring by the middle point of the "other" corner points)
and gives new corner in xc and function value at xc as a
return value
*/
gsl_matrix *x1 = state->x1;
const size_t P = x1->size1;
double newval;
/* xc = (1-coeff)*(P/(P-1)) * center(all) + ((P*coeff-1)/(P-1))*x_corner */
{
double alpha = (1 - coeff) * P / (P - 1.0);
double beta = (P * coeff - 1.0) / (P - 1.0);
gsl_vector_const_view row = gsl_matrix_const_row (x1, corner);
gsl_vector_memcpy (xc, state->center);
gsl_blas_dscal (alpha, xc);
gsl_blas_daxpy (beta, &row.vector, xc);
}
newval = GSL_MULTIMIN_FN_EVAL (f, xc);
return newval;
}
static void
update_point (nmsimplex_state_t * state, size_t i,
const gsl_vector * x, double val)
{
gsl_vector_const_view x_orig = gsl_matrix_const_row (state->x1, i);
const size_t P = state->x1->size1;
/* Compute delta = x - x_orig */
gsl_vector_memcpy (state->delta, x);
gsl_blas_daxpy (-1.0, &x_orig.vector, state->delta);
/* Compute xmc = x_orig - c */
gsl_vector_memcpy (state->xmc, &x_orig.vector);
gsl_blas_daxpy (-1.0, state->center, state->xmc);
/* Update size: S2' = S2 + (2/P) * (x_orig - c).delta + (P-1)*(delta/P)^2 */
{
double d = gsl_blas_dnrm2 (state->delta);
double xmcd;
gsl_blas_ddot (state->xmc, state->delta, &xmcd);
state->S2 += (2.0 / P) * xmcd + ((P - 1.0) / P) * (d * d / P);
}
/* Update center: c' = c + (x - x_orig) / P */
{
double alpha = 1.0 / P;
gsl_blas_daxpy (-alpha, &x_orig.vector, state->center);
gsl_blas_daxpy (alpha, x, state->center);
}
gsl_matrix_set_row (state->x1, i, x);
gsl_vector_set (state->y1, i, val);
}
static int
contract_by_best (nmsimplex_state_t * state, size_t best,
gsl_vector * xc, gsl_multimin_function * f)
{
/* Function contracts the simplex in respect to best valued
corner. That is, all corners besides the best corner are moved.
(This function is rarely called in practice, since it is the last
choice, hence not optimised - BJG) */
/* the xc vector is simply work space here */
gsl_matrix *x1 = state->x1;
gsl_vector *y1 = state->y1;
size_t i, j;
double newval;
int status = GSL_SUCCESS;
for (i = 0; i < x1->size1; i++)
{
if (i != best)
{
for (j = 0; j < x1->size2; j++)
{
newval = 0.5 * (gsl_matrix_get (x1, i, j)
+ gsl_matrix_get (x1, best, j));
gsl_matrix_set (x1, i, j, newval);
}
/* evaluate function in the new point */
gsl_matrix_get_row (xc, x1, i);
newval = GSL_MULTIMIN_FN_EVAL (f, xc);
gsl_vector_set (y1, i, newval);
/* notify caller that we found at least one bad function value.
we finish the contraction (and do not abort) to allow the user
to handle the situation */
if (!gsl_finite (newval))
{
status = GSL_EBADFUNC;
}
}
}
/* We need to update the centre and size as well */
compute_center (state, state->center);
compute_size (state, state->center);
return status;
}
static int
compute_center (const nmsimplex_state_t * state, gsl_vector * center)
{
/* calculates the center of the simplex and stores in center */
gsl_matrix *x1 = state->x1;
const size_t P = x1->size1;
size_t i;
gsl_vector_set_zero (center);
for (i = 0; i < P; i++)
{
gsl_vector_const_view row = gsl_matrix_const_row (x1, i);
gsl_blas_daxpy (1.0, &row.vector, center);
}
{
const double alpha = 1.0 / P;
gsl_blas_dscal (alpha, center);
}
return GSL_SUCCESS;
}
static double
compute_size (nmsimplex_state_t * state, const gsl_vector * center)
{
/* calculates simplex size as rms sum of length of vectors
from simplex center to corner points:
sqrt( sum ( || y - y_middlepoint ||^2 ) / n )
*/
gsl_vector *s = state->ws1;
gsl_matrix *x1 = state->x1;
const size_t P = x1->size1;
size_t i;
double ss = 0.0;
for (i = 0; i < P; i++)
{
double t;
gsl_matrix_get_row (s, x1, i);
gsl_blas_daxpy (-1.0, center, s);
t = gsl_blas_dnrm2 (s);
ss += t * t;
}
/* Store squared size in the state */
state->S2 = (ss / P);
return sqrt (ss / P);
}
static int
nmsimplex_alloc (void *vstate, size_t n)
{
nmsimplex_state_t *state = (nmsimplex_state_t *) vstate;
if (n == 0)
{
GSL_ERROR ("invalid number of parameters specified", GSL_EINVAL);
}
state->x1 = gsl_matrix_alloc (n + 1, n);
if (state->x1 == NULL)
{
GSL_ERROR ("failed to allocate space for x1", GSL_ENOMEM);
}
state->y1 = gsl_vector_alloc (n + 1);
if (state->y1 == NULL)
{
gsl_matrix_free (state->x1);
GSL_ERROR ("failed to allocate space for y", GSL_ENOMEM);
}
state->ws1 = gsl_vector_alloc (n);
if (state->ws1 == NULL)
{
gsl_matrix_free (state->x1);
gsl_vector_free (state->y1);
GSL_ERROR ("failed to allocate space for ws1", GSL_ENOMEM);
}
state->ws2 = gsl_vector_alloc (n);
if (state->ws2 == NULL)
{
gsl_matrix_free (state->x1);
gsl_vector_free (state->y1);
gsl_vector_free (state->ws1);
GSL_ERROR ("failed to allocate space for ws2", GSL_ENOMEM);
}
state->center = gsl_vector_alloc (n);
if (state->center == NULL)
{
gsl_matrix_free (state->x1);
gsl_vector_free (state->y1);
gsl_vector_free (state->ws1);
gsl_vector_free (state->ws2);
GSL_ERROR ("failed to allocate space for center", GSL_ENOMEM);
}
state->delta = gsl_vector_alloc (n);
if (state->delta == NULL)
{
gsl_matrix_free (state->x1);
gsl_vector_free (state->y1);
gsl_vector_free (state->ws1);
gsl_vector_free (state->ws2);
gsl_vector_free (state->center);
GSL_ERROR ("failed to allocate space for delta", GSL_ENOMEM);
}
state->xmc = gsl_vector_alloc (n);
if (state->xmc == NULL)
{
gsl_matrix_free (state->x1);
gsl_vector_free (state->y1);
gsl_vector_free (state->ws1);
gsl_vector_free (state->ws2);
gsl_vector_free (state->center);
gsl_vector_free (state->delta);
GSL_ERROR ("failed to allocate space for xmc", GSL_ENOMEM);
}
state->count = 0;
return GSL_SUCCESS;
}
static void
nmsimplex_free (void *vstate)
{
nmsimplex_state_t *state = (nmsimplex_state_t *) vstate;
gsl_matrix_free (state->x1);
gsl_vector_free (state->y1);
gsl_vector_free (state->ws1);
gsl_vector_free (state->ws2);
gsl_vector_free (state->center);
gsl_vector_free (state->delta);
gsl_vector_free (state->xmc);
}
static int
nmsimplex_set (void *vstate, gsl_multimin_function * f,
const gsl_vector * x,
double *size, const gsl_vector * step_size)
{
int status;
size_t i;
double val;
nmsimplex_state_t *state = (nmsimplex_state_t *) vstate;
gsl_vector *xtemp = state->ws1;
if (xtemp->size != x->size)
{
GSL_ERROR ("incompatible size of x", GSL_EINVAL);
}
if (xtemp->size != step_size->size)
{
GSL_ERROR ("incompatible size of step_size", GSL_EINVAL);
}
/* first point is the original x0 */
val = GSL_MULTIMIN_FN_EVAL (f, x);
if (!gsl_finite (val))
{
GSL_ERROR ("non-finite function value encountered", GSL_EBADFUNC);
}
gsl_matrix_set_row (state->x1, 0, x);
gsl_vector_set (state->y1, 0, val);
/* following points are initialized to x0 + step_size */
for (i = 0; i < x->size; i++)
{
status = gsl_vector_memcpy (xtemp, x);
if (status != 0)
{
GSL_ERROR ("vector memcopy failed", GSL_EFAILED);
}
{
double xi = gsl_vector_get (x, i);
double si = gsl_vector_get (step_size, i);
gsl_vector_set (xtemp, i, xi + si);
val = GSL_MULTIMIN_FN_EVAL (f, xtemp);
}
if (!gsl_finite (val))
{
GSL_ERROR ("non-finite function value encountered", GSL_EBADFUNC);
}
gsl_matrix_set_row (state->x1, i + 1, xtemp);
gsl_vector_set (state->y1, i + 1, val);
}
compute_center (state, state->center);
/* Initialize simplex size */
*size = compute_size (state, state->center);
state->count++;
return GSL_SUCCESS;
}
static int
nmsimplex_iterate (void *vstate, gsl_multimin_function * f,
gsl_vector * x, double *size, double *fval)
{
/* Simplex iteration tries to minimize function f value */
/* Includes corrections from Ivo Alxneit <ivo.alxneit@psi.ch> */
nmsimplex_state_t *state = (nmsimplex_state_t *) vstate;
/* xc and xc2 vectors store tried corner point coordinates */
gsl_vector *xc = state->ws1;
gsl_vector *xc2 = state->ws2;
gsl_vector *y1 = state->y1;
gsl_matrix *x1 = state->x1;
const size_t n = y1->size;
size_t i;
size_t hi, s_hi, lo;
double dhi, ds_hi, dlo;
int status;
double val, val2;
if (xc->size != x->size)
{
GSL_ERROR ("incompatible size of x", GSL_EINVAL);
}
/* get index of highest, second highest and lowest point */
dhi = dlo = gsl_vector_get (y1, 0);
hi = 0;
lo = 0;
ds_hi = gsl_vector_get (y1, 1);
s_hi = 1;
for (i = 1; i < n; i++)
{
val = (gsl_vector_get (y1, i));
if (val < dlo)
{
dlo = val;
lo = i;
}
else if (val > dhi)
{
ds_hi = dhi;
s_hi = hi;
dhi = val;
hi = i;
}
else if (val > ds_hi)
{
ds_hi = val;
s_hi = i;
}
}
/* try reflecting the highest value point */
val = try_corner_move (-1.0, state, hi, xc, f);
if (gsl_finite (val) && val < gsl_vector_get (y1, lo))
{
/* reflected point is lowest, try expansion */
val2 = try_corner_move (-2.0, state, hi, xc2, f);
if (gsl_finite (val2) && val2 < gsl_vector_get (y1, lo))
{
update_point (state, hi, xc2, val2);
}
else
{
update_point (state, hi, xc, val);
}
}
else if (!gsl_finite (val) || val > gsl_vector_get (y1, s_hi))
{
/* reflection does not improve things enough, or we got a
non-finite function value */
if (gsl_finite (val) && val <= gsl_vector_get (y1, hi))
{
/* if trial point is better than highest point, replace
highest point */
update_point (state, hi, xc, val);
}
/* try one-dimensional contraction */
val2 = try_corner_move (0.5, state, hi, xc2, f);
if (gsl_finite (val2) && val2 <= gsl_vector_get (y1, hi))
{
update_point (state, hi, xc2, val2);
}
else
{
/* contract the whole simplex about the best point */
status = contract_by_best (state, lo, xc, f);
if (status != GSL_SUCCESS)
{
GSL_ERROR ("contraction failed", GSL_EFAILED);
}
}
}
else
{
/* trial point is better than second highest point. Replace
highest point by it */
update_point (state, hi, xc, val);
}
/* return lowest point of simplex as x */
lo = gsl_vector_min_index (y1);
gsl_matrix_get_row (x, x1, lo);
*fval = gsl_vector_get (y1, lo);
/* Update simplex size */
{
double S2 = state->S2;
if (S2 > 0)
{
*size = sqrt (S2);
}
else
{
/* recompute if accumulated error has made size invalid */
*size = compute_size (state, state->center);
}
}
return GSL_SUCCESS;
}
static const gsl_multimin_fminimizer_type nmsimplex_type =
{ "nmsimplex2", /* name */
sizeof (nmsimplex_state_t),
&nmsimplex_alloc,
&nmsimplex_set,
&nmsimplex_iterate,
&nmsimplex_free
};
const gsl_multimin_fminimizer_type
* gsl_multimin_fminimizer_nmsimplex2 = &nmsimplex_type;
static inline double
ran_unif (unsigned long *seed)
{
unsigned long s = *seed;
*seed = (s * 69069 + 1) & 0xffffffffUL;
return (*seed) / 4294967296.0;
}
static int
nmsimplex_set_rand (void *vstate, gsl_multimin_function * f,
const gsl_vector * x,
double *size, const gsl_vector * step_size)
{
size_t i, j;
double val;
nmsimplex_state_t *state = (nmsimplex_state_t *) vstate;
gsl_vector *xtemp = state->ws1;
if (xtemp->size != x->size)
{
GSL_ERROR ("incompatible size of x", GSL_EINVAL);
}
if (xtemp->size != step_size->size)
{
GSL_ERROR ("incompatible size of step_size", GSL_EINVAL);
}
/* first point is the original x0 */
val = GSL_MULTIMIN_FN_EVAL (f, x);
if (!gsl_finite (val))
{
GSL_ERROR ("non-finite function value encountered", GSL_EBADFUNC);
}
gsl_matrix_set_row (state->x1, 0, x);
gsl_vector_set (state->y1, 0, val);
{
gsl_matrix_view m =
gsl_matrix_submatrix (state->x1, 1, 0, x->size, x->size);
/* generate a random orthornomal basis */
unsigned long seed = state->count ^ 0x12345678;
ran_unif (&seed); /* warm it up */
gsl_matrix_set_identity (&m.matrix);
/* start with random reflections */
for (i = 0; i < x->size; i++)
{
double s = ran_unif (&seed);
if (s > 0.5) gsl_matrix_set (&m.matrix, i, i, -1.0);
}
/* apply random rotations */
for (i = 0; i < x->size; i++)
{
for (j = i + 1; j < x->size; j++)
{
/* rotate columns i and j by a random angle */
double angle = 2.0 * M_PI * ran_unif (&seed);
double c = cos (angle), s = sin (angle);
gsl_vector_view c_i = gsl_matrix_column (&m.matrix, i);
gsl_vector_view c_j = gsl_matrix_column (&m.matrix, j);
gsl_blas_drot (&c_i.vector, &c_j.vector, c, s);
}
}
/* scale the orthonormal basis by the user-supplied step_size in
each dimension, and use as an offset from the central point x */
for (i = 0; i < x->size; i++)
{
double x_i = gsl_vector_get (x, i);
double s_i = gsl_vector_get (step_size, i);
gsl_vector_view c_i = gsl_matrix_column (&m.matrix, i);
for (j = 0; j < x->size; j++)
{
double x_ij = gsl_vector_get (&c_i.vector, j);
gsl_vector_set (&c_i.vector, j, x_i + s_i * x_ij);
}
}
/* compute the function values at each offset point */
for (i = 0; i < x->size; i++)
{
gsl_vector_view r_i = gsl_matrix_row (&m.matrix, i);
val = GSL_MULTIMIN_FN_EVAL (f, &r_i.vector);
if (!gsl_finite (val))
{
GSL_ERROR ("non-finite function value encountered", GSL_EBADFUNC);
}
gsl_vector_set (state->y1, i + 1, val);
}
}
compute_center (state, state->center);
/* Initialize simplex size */
*size = compute_size (state, state->center);
state->count++;
return GSL_SUCCESS;
}
static const gsl_multimin_fminimizer_type nmsimplex2rand_type =
{ "nmsimplex2rand", /* name */
sizeof (nmsimplex_state_t),
&nmsimplex_alloc,
&nmsimplex_set_rand,
&nmsimplex_iterate,
&nmsimplex_free
};
const gsl_multimin_fminimizer_type
* gsl_multimin_fminimizer_nmsimplex2rand = &nmsimplex2rand_type;
| {
"alphanum_fraction": 0.6339389704,
"avg_line_length": 24.4615384615,
"ext": "c",
"hexsha": "59dd57dbe6a8d3e02b14e4595f75165bd728380d",
"lang": "C",
"max_forks_count": 14,
"max_forks_repo_forks_event_max_datetime": "2020-03-12T12:31:25.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-07-21T04:47:52.000Z",
"max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "Brian-ning/HMNE",
"max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/multimin/simplex2.c",
"max_issues_count": 6,
"max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e",
"max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z",
"max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "Brian-ning/HMNE",
"max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/multimin/simplex2.c",
"max_line_length": 81,
"max_stars_count": 14,
"max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "ielomariala/Hex-Game",
"max_stars_repo_path": "gsl-2.6/multimin/simplex2.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": 5249,
"size": 17172
} |
#ifndef LIB_INCLUDE_TICK_ARRAY_VECTOR_OPERATIONS_H_
#define LIB_INCLUDE_TICK_ARRAY_VECTOR_OPERATIONS_H_
// License: BSD 3 clause
#include <atomic>
#include <vector>
#include <numeric>
#include <algorithm>
#include <type_traits>
#include "promote.h"
#include "tick/base/defs.h"
#if defined(TICK_USE_MKL)
#include "mkl.h"
#elif defined(TICK_USE_CBLAS)
#if defined(__APPLE__)
#include <Accelerate/Accelerate.h>
// TODO(svp) Disabling this feature until we find
// a good way to determine if ATLAS is actually available
#else
extern "C" {
#include <cblas.h>
}
#endif // defined(__APPLE__)
#else
#include "tick/array/vector/ops_unoptimized.h"
namespace tick {
template <typename T>
using vector_operations = detail::vector_operations_unoptimized<T>;
}
#endif
#if defined(TICK_USE_MKL) || defined(TICK_USE_CBLAS)
#include "tick/array/vector/ops_blas.h"
namespace tick {
template <typename T>
using vector_operations = detail::vector_operations_cblas<T>;
}
#endif
#include "tick/array/vector/ops_unoptimized_impl.h"
#endif // LIB_INCLUDE_TICK_ARRAY_VECTOR_OPERATIONS_H_
| {
"alphanum_fraction": 0.7751152074,
"avg_line_length": 20.0925925926,
"ext": "h",
"hexsha": "bb288e98d09b991dacd20587d2b805bfeb4df702",
"lang": "C",
"max_forks_count": 102,
"max_forks_repo_forks_event_max_datetime": "2022-02-15T11:45:49.000Z",
"max_forks_repo_forks_event_min_datetime": "2017-04-25T11:47:53.000Z",
"max_forks_repo_head_hexsha": "bbc561804eb1fdcb4c71b9e3e2d83a66e7b13a48",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "saurabhdash/tick",
"max_forks_repo_path": "lib/include/tick/array/vector_operations.h",
"max_issues_count": 345,
"max_issues_repo_head_hexsha": "bbc561804eb1fdcb4c71b9e3e2d83a66e7b13a48",
"max_issues_repo_issues_event_max_datetime": "2022-03-26T00:46:22.000Z",
"max_issues_repo_issues_event_min_datetime": "2017-04-13T14:53:20.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "saurabhdash/tick",
"max_issues_repo_path": "lib/include/tick/array/vector_operations.h",
"max_line_length": 67,
"max_stars_count": 411,
"max_stars_repo_head_hexsha": "1b56924a35463e12f7775bc0aec182364f26f2c6",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "sumau/tick",
"max_stars_repo_path": "lib/include/tick/array/vector_operations.h",
"max_stars_repo_stars_event_max_datetime": "2022-03-27T01:58:34.000Z",
"max_stars_repo_stars_event_min_datetime": "2017-03-30T15:22:05.000Z",
"num_tokens": 263,
"size": 1085
} |
#ifndef __MATH_LOGSPACE_H__
#define __MATH_LOGSPACE_H__
#include <cmath>
#include <vector>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_sf_gamma.h>
#include "logspace_base.h"
#include "specialfunc.h"
// Given two log vectors, log a_i and log b_i, compute
// log sum (a_i * b_i).
double log_dot_product(const gsl_vector* log_a, const gsl_vector* log_b);
// Given a log vector, log a_i, compute log sum a_i. Returns the sum.
double log_normalize(gsl_vector* x);
// Compute the log sum over all elements in the vector
double log_sum(const gsl_vector* x);
// Given a log matrix, log a_i, compute log sum a_i. Returns the sum.
double log_normalize_matrix(gsl_matrix* x);
double log_dirichlet_likelihood(const double sum,
const double prior_sum,
const std::vector<int>& counts,
bool debug = false);
double log_dirichlet_likelihood(const double sum,
const double prior_scale,
const gsl_vector* prior,
const std::vector<int>& counts);
#endif // __MATH_LOGSPACE_H__
| {
"alphanum_fraction": 0.6433978133,
"avg_line_length": 33.9714285714,
"ext": "h",
"hexsha": "4d6589b54d39d7403a6c094b31d7953624c993f4",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2018-11-27T01:35:33.000Z",
"max_forks_repo_forks_event_min_datetime": "2018-11-27T01:35:33.000Z",
"max_forks_repo_head_hexsha": "159aab87f04b745d874b53f64fd30703b4d5a70c",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "boomsbloom/dtm-fmri",
"max_forks_repo_path": "DTM/dtm-master/lib/math/logspace.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "159aab87f04b745d874b53f64fd30703b4d5a70c",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "boomsbloom/dtm-fmri",
"max_issues_repo_path": "DTM/dtm-master/lib/math/logspace.h",
"max_line_length": 73,
"max_stars_count": 4,
"max_stars_repo_head_hexsha": "159aab87f04b745d874b53f64fd30703b4d5a70c",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "boomsbloom/dtm-fmri",
"max_stars_repo_path": "DTM/dtm-master/lib/math/logspace.h",
"max_stars_repo_stars_event_max_datetime": "2022-01-27T01:17:11.000Z",
"max_stars_repo_stars_event_min_datetime": "2018-11-27T01:35:30.000Z",
"num_tokens": 264,
"size": 1189
} |
/*
* iaf_cond_exp_sfa_rr.h
*
* This file is part of NEST.
*
* Copyright (C) 2004 The NEST Initiative
*
* NEST is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version.
*
* NEST is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with NEST. If not, see <http://www.gnu.org/licenses/>.
*
*/
#ifndef IAF_COND_EXP_SFA_RR_H
#define IAF_COND_EXP_SFA_RR_H
// Generated includes:
#include "config.h"
#ifdef HAVE_GSL
// External includes:
#include <gsl/gsl_errno.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_odeiv.h>
// Includes from nestkernel:
#include "archiving_node.h"
#include "connection.h"
#include "event.h"
#include "nest_types.h"
#include "recordables_map.h"
#include "ring_buffer.h"
#include "universal_data_logger.h"
/* BeginDocumentation
Name: iaf_cond_exp_sfa_rr - Simple conductance based leaky integrate-and-fire
neuron model.
Description:
iaf_cond_exp_sfa_rr is an iaf_cond_exp_sfa_rr i.e. an implementation of a
spiking neuron using IAF dynamics with conductance-based synapses,
with additional spike-frequency adaptation and relative refractory
mechanisms as described in Dayan+Abbott, 2001, page 166.
As for the iaf_cond_exp_sfa_rr, Incoming spike events induce a post-synaptic
change of conductance modelled by an exponential function. The
exponential function is normalised such that an event of weight 1.0
results in a peak current of 1 nS.
Outgoing spike events induce a change of the adaptation and relative
refractory conductances by q_sfa and q_rr, respectively. Otherwise
these conductances decay exponentially with time constants tau_sfa
and tau_rr, respectively.
Parameters:
The following parameters can be set in the status dictionary.
V_m double - Membrane potential in mV
E_L double - Leak reversal potential in mV.
C_m double - Capacity of the membrane in pF
t_ref double - Duration of refractory period in ms.
V_th double - Spike threshold in mV.
V_reset double - Reset potential of the membrane in mV.
E_ex double - Excitatory reversal potential in mV.
E_in double - Inhibitory reversal potential in mV.
g_L double - Leak conductance in nS;
tau_syn_ex double - Time constant of the excitatory synaptic exponential
function in ms.
tau_syn_in double - Time constant of the inhibitory synaptic exponential
function in ms.
q_sfa double - Outgoing spike activated quantal spike-frequency adaptation
conductance increase in nS.
q_rr double - Outgoing spike activated quantal relative refractory
conductance increase in nS.
tau_sfa double - Time constant of spike-frequency adaptation in ms.
tau_rr double - Time constant of the relative refractory mechanism in ms.
E_sfa double - spike-frequency adaptation conductance reversal potential in
mV.
E_rr double - relative refractory mechanism conductance reversal potential
in mV.
I_e double - an external stimulus current in pA.
Sends: SpikeEvent
Receives: SpikeEvent, CurrentEvent, DataLoggingRequest
References:
Meffin, H., Burkitt, A. N., & Grayden, D. B. (2004). An analytical
model for the large, fluctuating synaptic conductance state typical of
neocortical neurons in vivo. J. Comput. Neurosci., 16, 159-175.
Dayan, P. and Abbott, L. F. (2001). Theoretical Neuroscience, MIT Press (p166)
Author: Sven Schrader, Eilif Muller
SeeAlso: iaf_cond_exp_sfa_rr, aeif_cond_alpha, iaf_psc_delta, iaf_psc_exp,
iaf_cond_alpha
*/
namespace nest
{
/**
* Function computing right-hand side of ODE for GSL solver.
* @note Must be declared here so we can befriend it in class.
* @note Must have C-linkage for passing to GSL. Internally, it is
* a first-class C++ function, but cannot be a member function
* because of the C-linkage.
* @note No point in declaring it inline, since it is called
* through a function pointer.
* @param void* Pointer to model neuron instance.
*/
extern "C" int
iaf_cond_exp_sfa_rr_dynamics( double, const double*, double*, void* );
class iaf_cond_exp_sfa_rr : public Archiving_Node
{
public:
iaf_cond_exp_sfa_rr();
iaf_cond_exp_sfa_rr( const iaf_cond_exp_sfa_rr& );
~iaf_cond_exp_sfa_rr();
/**
* Import sets of overloaded virtual functions.
* @see Technical Issues / Virtual Functions: Overriding, Overloading, and
* Hiding
*/
using Node::handle;
using Node::handles_test_event;
port send_test_event( Node&, rport, synindex, bool );
void handle( SpikeEvent& );
void handle( CurrentEvent& );
void handle( DataLoggingRequest& );
port handles_test_event( SpikeEvent&, rport );
port handles_test_event( CurrentEvent&, rport );
port handles_test_event( DataLoggingRequest&, rport );
void get_status( DictionaryDatum& ) const;
void set_status( const DictionaryDatum& );
private:
void init_state_( const Node& proto );
void init_buffers_();
void calibrate();
void update( Time const&, const long, const long );
// END Boilerplate function declarations ----------------------------
// Friends --------------------------------------------------------
// make dynamics function quasi-member
friend int
iaf_cond_exp_sfa_rr_dynamics( double, const double*, double*, void* );
// The next two classes need to be friends to access the State_ class/member
friend class RecordablesMap< iaf_cond_exp_sfa_rr >;
friend class UniversalDataLogger< iaf_cond_exp_sfa_rr >;
private:
// ----------------------------------------------------------------
//! Independent parameters
struct Parameters_
{
double V_th_; //!< Threshold Potential in mV
double V_reset_; //!< Reset Potential in mV
double t_ref_; //!< Refractory period in ms
double g_L; //!< Leak Conductance in nS
double C_m; //!< Membrane Capacitance in pF
double E_ex; //!< Excitatory reversal Potential in mV
double E_in; //!< Inhibitory reversal Potential in mV
double E_L; //!< Leak reversal Potential (aka resting potential) in mV
double tau_synE; //!< Synaptic Time Constant Excitatory Synapse in ms
double tau_synI; //!< Synaptic Time Constant for Inhibitory Synapse in ms
double I_e; //!< Constant Current in pA
double tau_sfa; //!< spike-frequency adaptation (sfa) time constant
double tau_rr; //!< relative refractory (rr) time constant
double E_sfa; //!< spike-frequency adaptation (sfa) reversal Potential
//!< in mV
double E_rr; //!< relative refractory (rr) reversal Potential in mV
double q_sfa; //!< spike-frequency adaptation (sfa) quantal conductance
//!< increase in nS
double q_rr; //!< relative refractory (rr) quantal conductance increase
//!< in nS
Parameters_(); //!< Sets default parameter values
void get( DictionaryDatum& ) const; //!< Store current values in dictionary
void set( const DictionaryDatum& ); //!< Set values from dicitonary
};
public:
// ----------------------------------------------------------------
/**
* State variables of the model.
* @note Copy constructor and assignment operator required because
* of C-style array.
*/
struct State_
{
//! Symbolic indices to the elements of the state vector y
enum StateVecElems
{
V_M = 0,
G_EXC,
G_INH,
G_SFA,
G_RR,
STATE_VEC_SIZE
};
//! neuron state, must be C-array for GSL solver
double y_[ STATE_VEC_SIZE ];
int r_; //!< number of refractory steps remaining
State_( const Parameters_& ); //!< Default initialization
State_( const State_& );
State_& operator=( const State_& );
void get( DictionaryDatum& ) const;
void set( const DictionaryDatum&, const Parameters_& );
};
private:
// ----------------------------------------------------------------
/**
* Buffers of the model.
*/
struct Buffers_
{
Buffers_( iaf_cond_exp_sfa_rr& ); //!<Sets buffer pointers to 0
//! Sets buffer pointers to 0
Buffers_( const Buffers_&, iaf_cond_exp_sfa_rr& );
//! Logger for all analog data
UniversalDataLogger< iaf_cond_exp_sfa_rr > logger_;
/** buffers and sums up incoming spikes/currents */
RingBuffer spike_exc_;
RingBuffer spike_inh_;
RingBuffer currents_;
/** GSL ODE stuff */
gsl_odeiv_step* s_; //!< stepping function
gsl_odeiv_control* c_; //!< adaptive stepsize control function
gsl_odeiv_evolve* e_; //!< evolution function
gsl_odeiv_system sys_; //!< struct describing system
// IntergrationStep_ should be reset with the neuron on ResetNetwork,
// but remain unchanged during calibration. Since it is initialized with
// step_, and the resolution cannot change after nodes have been created,
// it is safe to place both here.
double step_; //!< step size in ms
double IntegrationStep_; //!< current integration time step, updated by GSL
/**
* Input current injected by CurrentEvent.
* This variable is used to transport the current applied into the
* _dynamics function computing the derivative of the state vector.
* It must be a part of Buffers_, since it is initialized once before
* the first simulation, but not modified before later Simulate calls.
*/
double I_stim_;
};
// ----------------------------------------------------------------
/**
* Internal variables of the model.
*/
struct Variables_
{
int RefractoryCounts_;
};
// Access functions for UniversalDataLogger -------------------------------
//! Read out state vector elements, used by UniversalDataLogger
template < State_::StateVecElems elem >
double
get_y_elem_() const
{
return S_.y_[ elem ];
}
// ----------------------------------------------------------------
Parameters_ P_;
State_ S_;
Variables_ V_;
Buffers_ B_;
//! Mapping of recordables names to access functions
static RecordablesMap< iaf_cond_exp_sfa_rr > recordablesMap_;
};
inline port
nest::iaf_cond_exp_sfa_rr::send_test_event( Node& target,
rport receptor_type,
synindex,
bool )
{
SpikeEvent e;
e.set_sender( *this );
return target.handles_test_event( e, receptor_type );
}
inline port
iaf_cond_exp_sfa_rr::handles_test_event( SpikeEvent&, rport receptor_type )
{
if ( receptor_type != 0 )
{
throw UnknownReceptorType( receptor_type, get_name() );
}
return 0;
}
inline port
iaf_cond_exp_sfa_rr::handles_test_event( CurrentEvent&, rport receptor_type )
{
if ( receptor_type != 0 )
{
throw UnknownReceptorType( receptor_type, get_name() );
}
return 0;
}
inline port
iaf_cond_exp_sfa_rr::handles_test_event( DataLoggingRequest& dlr,
rport receptor_type )
{
if ( receptor_type != 0 )
{
throw UnknownReceptorType( receptor_type, get_name() );
}
return B_.logger_.connect_logging_device( dlr, recordablesMap_ );
}
inline void
iaf_cond_exp_sfa_rr::get_status( DictionaryDatum& d ) const
{
P_.get( d );
S_.get( d );
Archiving_Node::get_status( d );
( *d )[ names::recordables ] = recordablesMap_.get_list();
}
inline void
iaf_cond_exp_sfa_rr::set_status( const DictionaryDatum& d )
{
Parameters_ ptmp = P_; // temporary copy in case of errors
ptmp.set( d ); // throws if BadProperty
State_ stmp = S_; // temporary copy in case of errors
stmp.set( d, ptmp ); // throws if BadProperty
// We now know that (ptmp, stmp) are consistent. We do not
// write them back to (P_, S_) before we are also sure that
// the properties to be set in the parent class are internally
// consistent.
Archiving_Node::set_status( d );
// if we get here, temporaries contain consistent set of properties
P_ = ptmp;
S_ = stmp;
}
} // namespace
#endif // HAVE_GSL
#endif // IAF_COND_EXP_SFA_RR_H
| {
"alphanum_fraction": 0.6767481248,
"avg_line_length": 31.6301020408,
"ext": "h",
"hexsha": "557edfecf4a927a58f3fce27a1ff1d93278dee06",
"lang": "C",
"max_forks_count": 10,
"max_forks_repo_forks_event_max_datetime": "2021-03-25T09:32:56.000Z",
"max_forks_repo_forks_event_min_datetime": "2019-12-09T06:45:59.000Z",
"max_forks_repo_head_hexsha": "14f86a76edf4e8763b58f84960876e95d4efc43a",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "OpenHEC/SNN-simulator-on-PYNQcluster",
"max_forks_repo_path": "NEST-14.0-FPGA/models/iaf_cond_exp_sfa_rr.h",
"max_issues_count": 2,
"max_issues_repo_head_hexsha": "14f86a76edf4e8763b58f84960876e95d4efc43a",
"max_issues_repo_issues_event_max_datetime": "2021-09-08T02:33:46.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-05-23T05:34:21.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "zlchai/SNN-simulator-on-PYNQcluster",
"max_issues_repo_path": "NEST-14.0-FPGA/models/iaf_cond_exp_sfa_rr.h",
"max_line_length": 80,
"max_stars_count": 45,
"max_stars_repo_head_hexsha": "14f86a76edf4e8763b58f84960876e95d4efc43a",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "OpenHEC/SNN-simulator-on-PYNQcluster",
"max_stars_repo_path": "NEST-14.0-FPGA/models/iaf_cond_exp_sfa_rr.h",
"max_stars_repo_stars_event_max_datetime": "2022-01-29T12:16:41.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-12-09T06:45:53.000Z",
"num_tokens": 3034,
"size": 12399
} |
#ifndef S3D_VIDEO_FILE_PARSER_FFMPEG_SEEKER_H
#define S3D_VIDEO_FILE_PARSER_FFMPEG_SEEKER_H
#include <chrono>
#include <gsl/gsl>
struct AVFormatContext;
namespace s3d {
class Seeker {
public:
Seeker(gsl::not_null<AVFormatContext*> formatContext, int streamIndex);
void seekTo(std::chrono::microseconds timestamp);
private:
AVFormatContext* formatContext_;
int streamIndex_;
};
} // namespace s3d
#endif // S3D_VIDEO_FILE_PARSER_FFMPEG_SEEKER_H
| {
"alphanum_fraction": 0.7870967742,
"avg_line_length": 17.8846153846,
"ext": "h",
"hexsha": "96826a11d548a66cbe606a0776def2f9d8d0f711",
"lang": "C",
"max_forks_count": 6,
"max_forks_repo_forks_event_max_datetime": "2021-05-18T16:22:03.000Z",
"max_forks_repo_forks_event_min_datetime": "2017-07-13T21:51:09.000Z",
"max_forks_repo_head_hexsha": "4ffad16f9b0973404b59eb1424cc45f68754fe12",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "hugbed/OpenS3D",
"max_forks_repo_path": "src/core/ffmpeg/include/s3d/video/file_parser/ffmpeg/seeker.h",
"max_issues_count": 40,
"max_issues_repo_head_hexsha": "4ffad16f9b0973404b59eb1424cc45f68754fe12",
"max_issues_repo_issues_event_max_datetime": "2017-12-21T18:41:23.000Z",
"max_issues_repo_issues_event_min_datetime": "2017-04-12T17:24:44.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "hugbed/OpenS3D",
"max_issues_repo_path": "src/core/ffmpeg/include/s3d/video/file_parser/ffmpeg/seeker.h",
"max_line_length": 73,
"max_stars_count": 8,
"max_stars_repo_head_hexsha": "4ffad16f9b0973404b59eb1424cc45f68754fe12",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "hugbed/OpenS3D",
"max_stars_repo_path": "src/core/ffmpeg/include/s3d/video/file_parser/ffmpeg/seeker.h",
"max_stars_repo_stars_event_max_datetime": "2020-04-20T03:23:15.000Z",
"max_stars_repo_stars_event_min_datetime": "2017-04-16T16:38:15.000Z",
"num_tokens": 130,
"size": 465
} |
#pragma once
#include <cstddef>
#include <memory>
#include <iostream>
#include <array>
#include <gsl\gsl>
#include "../utils/CRSP.h"
#include "./Pool.h"
#include "../math/OtherMath.h"
#include "../types/def.h"
namespace config {
/**
Default pool size for our Small Memory Allocator pools.
*/
constexpr size_t sma_pool_size = 1024 * 1024;
constexpr size_t sma_pool_amount = 10;
} // namespace config
/**
Our allocator class that will be the general interface for any future
allocation. Inherits from the Curiously Recurring Singleton Pattern in order to
have just one global one.
@see CRSP
*/
class SmallMemoryAllocator : public CRSP<SmallMemoryAllocator> {
private:
friend class CRSP<SmallMemoryAllocator>;
SmallMemoryAllocator();
~SmallMemoryAllocator();
public:
Pool * get_pool_for_size(size_t size);
bool fits(size_t size) const;
void* alloc(size_t size);
template <typename T>
T* alloc() {
return reinterpret_cast<T*>(alloc(sizeof(T)));
}
void dealloc(void* elem);
void print_status(std::ostream& stream);
void print_status(void* elem, std::ostream& stream) const;
private:
size_t get_pool_index(size_t size) const;
std::array<std::unique_ptr<Pool>, config::sma_pool_amount> m_pool_array{};
std::array<size_t, config::sma_pool_amount + 1> m_extra_requested_elements{};
std::array<size_t, config::sma_pool_amount> m_max_allocated_elements{};
byte* m_general_pool{ nullptr };
};
| {
"alphanum_fraction": 0.7092008059,
"avg_line_length": 22.5606060606,
"ext": "h",
"hexsha": "26d6192988ec2d6bb228cceb4cf28b351461eb63",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2021-05-14T14:57:31.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-03-07T12:53:44.000Z",
"max_forks_repo_head_hexsha": "c28887f233d3485b9e95fa3882a0333e4180c655",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "osor-io/NGene",
"max_forks_repo_path": "NGene/src/memory/SmallMemoryAllocator.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "c28887f233d3485b9e95fa3882a0333e4180c655",
"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": "osor-io/NGene",
"max_issues_repo_path": "NGene/src/memory/SmallMemoryAllocator.h",
"max_line_length": 80,
"max_stars_count": 2,
"max_stars_repo_head_hexsha": "c28887f233d3485b9e95fa3882a0333e4180c655",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "osor-io/NGene",
"max_stars_repo_path": "NGene/src/memory/SmallMemoryAllocator.h",
"max_stars_repo_stars_event_max_datetime": "2021-08-05T04:00:41.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-05-14T14:57:30.000Z",
"num_tokens": 359,
"size": 1489
} |
#pragma once
#if __has_include(<span>) && (__cplusplus > 201703L)
#include <span>
#else
#include <gsl/span>
namespace std {
template <class T, std::size_t Extent = gsl::dynamic_extent>
using span = gsl::span<T, Extent>;
}
#endif
| {
"alphanum_fraction": 0.7043478261,
"avg_line_length": 19.1666666667,
"ext": "h",
"hexsha": "66496e0962b5343c2cee36d8457d15f55ceeb6b5",
"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": "2a95a112439b21ff9125c2e6e29810a418b94a4d",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "VITObelgium/cpp-infra",
"max_forks_repo_path": "include/infra/span.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "2a95a112439b21ff9125c2e6e29810a418b94a4d",
"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": "VITObelgium/cpp-infra",
"max_issues_repo_path": "include/infra/span.h",
"max_line_length": 60,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "2a95a112439b21ff9125c2e6e29810a418b94a4d",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "VITObelgium/cpp-infra",
"max_stars_repo_path": "include/infra/span.h",
"max_stars_repo_stars_event_max_datetime": "2022-02-23T03:15:54.000Z",
"max_stars_repo_stars_event_min_datetime": "2022-02-23T03:15:54.000Z",
"num_tokens": 65,
"size": 230
} |
/*
The following program solves the second-order nonlinear
Van der Pol oscillator equation (see Landau/Paez 14.12, part 1),
x"(t) + \mu x'(t) (x(t)^2 - 1) + x(t) = 0
This can be converted into a first order system suitable for
use with the library by introducing a separate variable for
the velocity, v = x'(t). We assign x --> y[0] and v --> y[1].
So the equations are:
x' = v ==> dy[0]/dt = f[0] = y[1]
v' = -x + \mu v (1-x^2) ==> dy[1]/dt = f[1] = -y[0] + mu*y[1]*(1-y[0]*y[0])
x"(t) = - \mu x'(t) (x(t)^2 - 1) - x(t)
x''(t) + x'(t) + x(t) = 0
x''(t) = -x'(t) - x(t)
x' = v ===> dy[0]/dt = f[0] = y[1]
v' = -v - x
*/
#include <stdio.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_odeiv.h>
/* function prototypes */
int rhs (double t, const double y[], double f[], void *params_ptr);
//int jacobian (double t, const double y[], double *dfdy, double dfdt[], void *params_ptr);
/*************************** main program ****************************/
int *jac;
int
main (void)
{
int dimension = 2; /* number of differential equations */
double eps_abs = 1.e-8; /* absolute error requested */
double eps_rel = 1.e-10; /* relative error requested */
/* define the type of routine for making steps: */
const gsl_odeiv_step_type *type_ptr = gsl_odeiv_step_rkf45;
/* some other possibilities (see GSL manual):
= gsl_odeiv_step_rk4;
= gsl_odeiv_step_rkck;
= gsl_odeiv_step_rk8pd;
= gsl_odeiv_step_rk4imp;
= gsl_odeiv_step_bsimp;
= gsl_odeiv_step_gear1;
= gsl_odeiv_step_gear2;
*/
/*
allocate/initialize the stepper, the control function, and the
evolution function.
*/
// 룬게쿠타 방식의 2계 미분 방정식으로 stepping을 진행합니다.
gsl_odeiv_step *step_ptr = gsl_odeiv_step_alloc (type_ptr, dimension);
// 허용 오차
gsl_odeiv_control *control_ptr = gsl_odeiv_control_y_new (eps_abs, eps_rel);
// 계산하는 차원
gsl_odeiv_evolve *evolve_ptr = gsl_odeiv_evolve_alloc (dimension);
gsl_odeiv_system my_system; /* structure with the rhs function, etc. */
double mu = 10; /* parameter for the diffeq */
double y[2]; /* current solution vector */
double t, t_next; /* current and next independent variable */
double tmin, tmax, delta_t; /* range of t and step size for output */
double h = 1e-6; /* starting step size for ode solver */
/* load values into the my_system structure */
my_system.function = rhs; /* the right-hand-side functions dy[i]/dt */
//my_system.jacobian = jacobian; /* the Jacobian df[i]/dy[j] */
my_system.jacobian = NULL;
my_system.dimension = dimension; /* number of diffeq's */
//my_system.params = μ /* parameters to pass to rhs and jacobian */
my_system.params = NULL;
tmin = 0.; /* starting t value */
tmax = 10.; /* final t value */
delta_t = 1.;
// 주의점이라면 2계 미분 방정식은 최소 2개의 초기값이 필요하다는 부분을 주의!
y[0] = 1.; /* initial x value */
y[1] = 0.; /* initial v value */
t = tmin; /* initialize t */
printf ("%.5e %.5e %.5e\n", t, y[0], y[1]); /* initial values */
/* step to tmax from tmin */
for (t_next = tmin + delta_t; t_next <= tmax; t_next += delta_t)
{
while (t < t_next) /* evolve from t to t_next */
{
gsl_odeiv_evolve_apply (evolve_ptr, control_ptr, step_ptr,
&my_system, &t, t_next, &h, y);
}
// y[0], y[1] 결과 확인이 필요함
printf ("%.5e %.5e %.5e\n", t, y[0], y[1]); /* print at t=t_next */
}
/* all done; free up the gsl_odeiv stuff */
gsl_odeiv_evolve_free (evolve_ptr);
gsl_odeiv_control_free (control_ptr);
gsl_odeiv_step_free (step_ptr);
return 0;
}
/*************************** rhs ****************************/
/*
x''(t) + x'(t) + x(t) = 0
x''(t) = -x'(t) - x(t)
x' = v ===> dy[0]/dt = f[0] = y[1]
v' = -v - x ===> dy[1]/dt = f[1] = -y[1] - y[0]
*/
// https://www.wolframalpha.com/input/?i=y%27%27+%2B+y%27+%2B+y+%3D+0%2C+y%280%29+%3D+1%2C+y%27%280%29+%3D+0, y(0) = 1
// https://www.wolframalpha.com/input/?i=%28sqrt%283%29+*+sin%28sqrt%283%29+%2F+2%29+%2B+3+*+cos%28sqrt%283%29+%2F+2%29%29+%2F+%283+*+sqrt%28e%29%29, y(1)
// (sqrt(3) * sin(sqrt(3) / 2) + 3 * cos(sqrt(3) / 2)) / (3 * sqrt(e)), y(1) = 0.6597001...
int
rhs (double t, const double v[], double f[], void *params_ptr)
//rhs (double t, const double y[], double f[], void *params_ptr)
{
/*
f[0] = y[1];
f[1] = -y[0] + mu * y[1] * (1. - y[0] * y[0]);
*/
// * 코드 작성 팁: 미분항은 f에 배치합니다.
// 1계와 마찬가지로 반드시 표준형이어야 합니다!
// 첫번째 1차 미분이 무엇(치환)입니다 ~
f[0] = v[1];
// 두번째 2차 미분을 치환을 기반으로 어떻게 표현해야 하는지를 기록합니다.
f[1] = -v[1] - v[0];
/* Tip: 배열의 인덱스는 결국 미분의 횟수라고 생각해도 좋습니다 */
// 현재 초기값이 있으니까 두 개의 근이 나오지 않고 한 개의 근이 나옴!
return GSL_SUCCESS; /* GSL_SUCCESS defined in gsl/errno.h as 0 */
}
/*************************** Jacobian ****************************/
/*
Define the Jacobian matrix using GSL matrix routines.
(see the GSL manual under "Ordinary Differential Equations")
* params is a void pointer that is used in many GSL routines
to pass parameters to a function
*/
#if 0
int
jacobian (double t, const double y[], double *dfdy,
double dfdt[], void *params_ptr)
{
/* get parameter(s) from params_ptr; here, just a double */
double mu = *(double *) params_ptr;
gsl_matrix_view dfdy_mat = gsl_matrix_view_array (dfdy, 2, 2);
gsl_matrix *m_ptr = &dfdy_mat.matrix; /* m_ptr points to the matrix */
/* fill the Jacobian matrix as shown */
gsl_matrix_set (m_ptr, 0, 0, 0.0); /* df[0]/dy[0] = 0 */
gsl_matrix_set (m_ptr, 0, 1, 1.0); /* df[0]/dy[1] = 1 */
gsl_matrix_set (m_ptr, 1, 0, -2.0 * mu * y[0] * y[1] - 1.0); /* df[1]/dy[0] */
gsl_matrix_set (m_ptr, 1, 1, -mu * (y[0] * y[0] - 1.0)); /* df[1]/dy[1] */
/* set explicit t dependence of f[i] */
dfdt[0] = 0.0;
dfdt[1] = 0.0;
return GSL_SUCCESS; /* GSL_SUCCESS defined in gsl/errno.h as 0 */
}
#endif
| {
"alphanum_fraction": 0.5656383328,
"avg_line_length": 34.0446927374,
"ext": "c",
"hexsha": "a5b01333cdbddf1636a688e19c65379f33df0429",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2022-03-19T01:22:06.000Z",
"max_forks_repo_forks_event_min_datetime": "2022-03-19T01:22:06.000Z",
"max_forks_repo_head_hexsha": "245385b79807c25081dfe2014c72843226716f92",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "EDDI-RobotAcademy/E4DS-DSP-Basic-Mathematics",
"max_forks_repo_path": "ch5/src/main/second_ode.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "245385b79807c25081dfe2014c72843226716f92",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "EDDI-RobotAcademy/E4DS-DSP-Basic-Mathematics",
"max_issues_repo_path": "ch5/src/main/second_ode.c",
"max_line_length": 154,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "245385b79807c25081dfe2014c72843226716f92",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "EDDI-RobotAcademy/E4DS-DSP-Basic-Mathematics",
"max_stars_repo_path": "ch5/src/main/second_ode.c",
"max_stars_repo_stars_event_max_datetime": "2021-10-22T00:39:04.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-10-22T00:39:04.000Z",
"num_tokens": 2259,
"size": 6094
} |
#ifdef __cplusplus
extern "C" {
#endif
#include "src/allvars.h"
#include "src/proto.h"
#include "src/tags.h"
#include <gsl/gsl_rng.h>
typedef struct {
double mass; /// mass
double x, y, z; /// position
double vx, vy, vz; /// velocity
} dynamics_state;
typedef struct {
double mass; /// mass
double x, y, z; /// position
double vx, vy, vz; /// velocity
double u; /// entropy
#ifdef MORRIS97VISC
double alpha, dalphadt; ///viscosity
#endif
} sph_state;
void begrun(void);
double second(void);
int found_particle(int index_of_the_particle, int *local_index);
void update_particle_map(void);
void hydro_state_at_point(FLOAT pos[3], FLOAT vel[3], FLOAT *h_out,
FLOAT *ngb_out, FLOAT *dhsml_out, FLOAT *rho_out, FLOAT *rhov_out,
FLOAT *rhov2_out, FLOAT *rhoe_out);
#ifdef __cplusplus
}
#endif
| {
"alphanum_fraction": 0.5237659963,
"avg_line_length": 27.35,
"ext": "h",
"hexsha": "cadbb4a388cc45104d9e59cef4d58c2c89b2de0d",
"lang": "C",
"max_forks_count": 102,
"max_forks_repo_forks_event_max_datetime": "2022-02-09T13:29:43.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-01-22T10:00:29.000Z",
"max_forks_repo_head_hexsha": "3ac3b6b8f922643657279ddee5c8ab3fc0440d5e",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "rieder/amuse",
"max_forks_repo_path": "src/amuse/community/gadget2/interface.h",
"max_issues_count": 690,
"max_issues_repo_head_hexsha": "85d5bdcc29cfc87dc69d91c264101fafd6658aec",
"max_issues_repo_issues_event_max_datetime": "2022-03-31T16:15:58.000Z",
"max_issues_repo_issues_event_min_datetime": "2015-10-17T12:18:08.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "rknop/amuse",
"max_issues_repo_path": "src/amuse/community/gadget2/interface.h",
"max_line_length": 68,
"max_stars_count": 131,
"max_stars_repo_head_hexsha": "85d5bdcc29cfc87dc69d91c264101fafd6658aec",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "rknop/amuse",
"max_stars_repo_path": "src/amuse/community/gadget2/interface.h",
"max_stars_repo_stars_event_max_datetime": "2022-02-01T12:11:29.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-06-04T09:06:57.000Z",
"num_tokens": 246,
"size": 1094
} |
#include <petsc.h>
#include <petscmath.h>
#include "compressibleFlow.h"
#include "mesh.h"
#include "petscdmplex.h"
#include "petscts.h"
//MMS from Verification of a Compressible CFD Code using the Method of Manufactured Solutions, Christopher J. Roy,† Thomas M. Smith,‡ and Curtis C. Ober§
// Define
#define Pi PETSC_PI
#define Sin PetscSinReal
#define Cos PetscCosReal
#define Power PetscPowReal
typedef struct {
PetscReal phiO;
PetscReal phiX;
PetscReal phiY;
PetscReal phiZ;
PetscReal aPhiX;
PetscReal aPhiY;
PetscReal aPhiZ;
} PhiConstants;
typedef struct {
PetscInt dim;
PhiConstants rho;
PhiConstants u;
PhiConstants v;
PhiConstants w;
PhiConstants p;
PetscReal L;
PetscReal gamma;
PetscReal R;
PetscReal mu;
} Constants;
typedef struct {
Constants constants;
FlowData flowData;
} ProblemSetup;
static PetscErrorCode EulerExact(PetscInt dim, PetscReal time, const PetscReal xyz[], PetscInt Nf, PetscScalar *u, void *ctx) {
PetscFunctionBeginUser;
Constants *constants = (Constants *)ctx;
PetscReal L = constants->L;
PetscReal gamma = constants->gamma;
PetscReal rhoO = constants->rho.phiO;
PetscReal rhoX = constants->rho.phiX;
PetscReal rhoY = constants->rho.phiY;
PetscReal rhoZ = constants->rho.phiZ;
PetscReal aRhoX = constants->rho.aPhiX;
PetscReal aRhoY = constants->rho.aPhiY;
PetscReal aRhoZ = constants->rho.aPhiZ;
PetscReal uO = constants->u.phiO;
PetscReal uX = constants->u.phiX;
PetscReal uY = constants->u.phiY;
PetscReal uZ = constants->u.phiZ;
PetscReal aUX = constants->u.aPhiX;
PetscReal aUY = constants->u.aPhiY;
PetscReal aUZ = constants->u.aPhiZ;
PetscReal vO = constants->v.phiO;
PetscReal vX = constants->v.phiX;
PetscReal vY = constants->v.phiY;
PetscReal vZ = constants->v.phiZ;
PetscReal aVX = constants->v.aPhiX;
PetscReal aVY = constants->v.aPhiY;
PetscReal aVZ = constants->v.aPhiZ;
PetscReal wO = constants->w.phiO;
PetscReal wX = constants->w.phiX;
PetscReal wY = constants->w.phiY;
PetscReal wZ = constants->w.phiZ;
PetscReal aWX = constants->w.aPhiX;
PetscReal aWY = constants->w.aPhiY;
PetscReal aWZ = constants->w.aPhiZ;
PetscReal pO = constants->p.phiO;
PetscReal pX = constants->p.phiX;
PetscReal pY = constants->p.phiY;
PetscReal pZ = constants->p.phiZ;
PetscReal aPX = constants->p.aPhiX;
PetscReal aPY = constants->p.aPhiY;
PetscReal aPZ = constants->p.aPhiZ;
PetscReal x = xyz[0];
PetscReal y = xyz[1];
PetscReal z = dim > 2? xyz[2] : 0.0;
u[RHO] = rhoO + rhoY*Cos((aRhoY*Pi*y)/L) + rhoX*Sin((aRhoX*Pi*x)/L) + rhoZ*Sin((aRhoZ*Pi*z)/L);
u[RHOE] = (rhoO + rhoY*Cos((aRhoY*Pi*y)/L) + rhoX*Sin((aRhoX*Pi*x)/L) + rhoZ*Sin((aRhoZ*Pi*z)/L))*((pO + pX*Cos((aPX*Pi*x)/L) + pZ*Cos((aPZ*Pi*z)/L) + pY*Sin((aPY*Pi*y)/L))/((-1. + gamma)*(rhoO + rhoY*Cos((aRhoY*Pi*y)/L) + rhoX*Sin((aRhoX*Pi*x)/L) + rhoZ*Sin((aRhoZ*Pi*z)/L))) +
(Power(uO + uY*Cos((aUY*Pi*y)/L) + uZ*Cos((aUZ*Pi*z)/L) + uX*Sin((aUX*Pi*x)/L),2) + Power(wO + wZ*Cos((aWZ*Pi*z)/L) + wX*Sin((aWX*Pi*x)/L) + wY*Sin((aWY*Pi*y)/L),2) + Power(vO + vX*Cos((aVX*Pi*x)/L) + vY*Sin((aVY*Pi*y)/L) + vZ*Sin((aVZ*Pi*z)/L),2))/2.);
u[RHOU + 0] = (uO + uY*Cos((aUY*Pi*y)/L) + uZ*Cos((aUZ*Pi*z)/L) + uX*Sin((aUX*Pi*x)/L))*
(rhoO + rhoY*Cos((aRhoY*Pi*y)/L) + rhoX*Sin((aRhoX*Pi*x)/L) + rhoZ*Sin((aRhoZ*Pi*z)/L));
u[RHOU + 1] = (rhoO + rhoY*Cos((aRhoY*Pi*y)/L) + rhoX*Sin((aRhoX*Pi*x)/L) + rhoZ*Sin((aRhoZ*Pi*z)/L))*
(vO + vX*Cos((aVX*Pi*x)/L) + vY*Sin((aVY*Pi*y)/L) + vZ*Sin((aVZ*Pi*z)/L));
if(dim > 2){
u[RHOU + 2] = (wO + wZ*Cos((aWZ*Pi*z)/L) + wX*Sin((aWX*Pi*x)/L) + wY*Sin((aWY*Pi*y)/L))*
(rhoO + rhoY*Cos((aRhoY*Pi*y)/L) + rhoX*Sin((aRhoX*Pi*x)/L) + rhoZ*Sin((aRhoZ*Pi*z)/L));
}
PetscFunctionReturn(0);
}
static PetscErrorCode EulerExactTimeDerivative(PetscInt dim, PetscReal time, const PetscReal xyz[], PetscInt Nf, PetscScalar *u, void *ctx) {
PetscFunctionBeginUser;
u[RHO] = 0.0;
u[RHOE] = 0.0;
u[RHOU + 0] = 0.0;
u[RHOU + 1] = 0.0;
if(dim > 2) {
u[RHOU + 2] = 0.0;
}
PetscFunctionReturn(0);
}
static PetscErrorCode MonitorError(TS ts, PetscInt step, PetscReal time, Vec u, void *ctx) {
PetscFunctionBeginUser;
PetscErrorCode ierr;
// Get the DM
DM dm;
ierr = TSGetDM(ts, &dm);CHKERRQ(ierr);
ierr = VecViewFromOptions(u, NULL, "-sol_view");CHKERRQ(ierr);
ierr = PetscPrintf(PetscObjectComm((PetscObject)dm), "TS at %f\n", time);CHKERRQ(ierr);
// Compute the error
void *exactCtxs[1];
PetscErrorCode (*exactFuncs[1])(PetscInt dim, PetscReal time, const PetscReal x[], PetscInt Nf, PetscScalar *u, void *ctx);
PetscDS ds;
ierr = DMGetDS(dm, &ds);CHKERRQ(ierr);
// Get the exact solution
ierr = PetscDSGetExactSolution(ds, 0, &exactFuncs[0], &exactCtxs[0]);CHKERRQ(ierr);
// Create an vector to hold the exact solution
Vec exactVec;
ierr = VecDuplicate(u, &exactVec);CHKERRQ(ierr);
ierr = DMProjectFunction(dm,time,exactFuncs,exactCtxs,INSERT_ALL_VALUES,exactVec);CHKERRQ(ierr);
// For each component, compute the l2 norms
ierr = VecAXPY(exactVec, -1.0, u);CHKERRQ(ierr);
PetscReal ferrors[4];
ierr = VecSetBlockSize(exactVec, 4);CHKERRQ(ierr);
// Compute the L2 Difference
ierr = PetscPrintf(PETSC_COMM_WORLD, "Timestep: %04d time = %-8.4g \t\n", (int) step, (double) time);CHKERRQ(ierr);
ierr = VecStrideNormAll(exactVec, NORM_2,ferrors);CHKERRQ(ierr);
ierr = PetscPrintf(PETSC_COMM_WORLD, "\tL_2 Error: [%2.3g, %2.3g, %2.3g, %2.3g]\n", (double) ferrors[0], (double) ferrors[1], (double) ferrors[2], (double) ferrors[3]);CHKERRQ(ierr);
ierr = VecStrideNormAll(exactVec, NORM_INFINITY,ferrors);CHKERRQ(ierr);
ierr = PetscPrintf(PETSC_COMM_WORLD, "\tL_Inf Error: [%2.3g, %2.3g, %2.3g, %2.3g]\n", (double) ferrors[0], (double) ferrors[1], (double) ferrors[2], (double) ferrors[3]);CHKERRQ(ierr);
ierr = VecDestroy(&exactVec);CHKERRQ(ierr);
PetscFunctionReturn(0);
}
static PetscErrorCode SourceRho(PetscInt dim, PetscReal time, const PetscReal xyz[], PetscInt Nf, PetscScalar *u, void *ctx) {
PetscFunctionBeginUser;
Constants *constants = (Constants *)ctx;
PetscReal L = constants->L;
PetscReal gamma = constants->gamma;
PetscReal rhoO = constants->rho.phiO;
PetscReal rhoX = constants->rho.phiX;
PetscReal rhoY = constants->rho.phiY;
PetscReal rhoZ = constants->rho.phiZ;
PetscReal aRhoX = constants->rho.aPhiX;
PetscReal aRhoY = constants->rho.aPhiY;
PetscReal aRhoZ = constants->rho.aPhiZ;
PetscReal uO = constants->u.phiO;
PetscReal uX = constants->u.phiX;
PetscReal uY = constants->u.phiY;
PetscReal uZ = constants->u.phiZ;
PetscReal aUX = constants->u.aPhiX;
PetscReal aUY = constants->u.aPhiY;
PetscReal aUZ = constants->u.aPhiZ;
PetscReal vO = constants->v.phiO;
PetscReal vX = constants->v.phiX;
PetscReal vY = constants->v.phiY;
PetscReal vZ = constants->v.phiZ;
PetscReal aVX = constants->v.aPhiX;
PetscReal aVY = constants->v.aPhiY;
PetscReal aVZ = constants->v.aPhiZ;
PetscReal wO = constants->w.phiO;
PetscReal wX = constants->w.phiX;
PetscReal wY = constants->w.phiY;
PetscReal wZ = constants->w.phiZ;
PetscReal aWX = constants->w.aPhiX;
PetscReal aWY = constants->w.aPhiY;
PetscReal aWZ = constants->w.aPhiZ;
PetscReal pO = constants->p.phiO;
PetscReal pX = constants->p.phiX;
PetscReal pY = constants->p.phiY;
PetscReal pZ = constants->p.phiZ;
PetscReal aPX = constants->p.aPhiX;
PetscReal aPY = constants->p.aPhiY;
PetscReal aPZ = constants->p.aPhiZ;
PetscReal x = xyz[0];
PetscReal y = xyz[1];
PetscReal z = dim > 2? xyz[2] : 0.0;
u[0] = (aRhoX*Pi*rhoX*Cos((aRhoX*Pi*x)/L)*(uO + uY*Cos((aUY*Pi*y)/L) + uZ*Cos((aUZ*Pi*z)/L) +
uX*Sin((aUX*Pi*x)/L)))/L + (aRhoZ*Pi*rhoZ*Cos((aRhoZ*Pi*z)/L)*
(wO + wZ*Cos((aWZ*Pi*z)/L) + wX*Sin((aWX*Pi*x)/L) + wY*Sin((aWY*Pi*y)/L)))/L +
(aUX*Pi*uX*Cos((aUX*Pi*x)/L)*(rhoO + rhoY*Cos((aRhoY*Pi*y)/L) + rhoX*Sin((aRhoX*Pi*x)/L) +
rhoZ*Sin((aRhoZ*Pi*z)/L)))/L + (aVY*Pi*vY*Cos((aVY*Pi*y)/L)*
(rhoO + rhoY*Cos((aRhoY*Pi*y)/L) + rhoX*Sin((aRhoX*Pi*x)/L) + rhoZ*Sin((aRhoZ*Pi*z)/L)))/L -
(aRhoY*Pi*rhoY*Sin((aRhoY*Pi*y)/L)*(vO + vX*Cos((aVX*Pi*x)/L) + vY*Sin((aVY*Pi*y)/L) +
vZ*Sin((aVZ*Pi*z)/L)))/L - (aWZ*Pi*wZ*
(rhoO + rhoY*Cos((aRhoY*Pi*y)/L) + rhoX*Sin((aRhoX*Pi*x)/L) + rhoZ*Sin((aRhoZ*Pi*z)/L))*
Sin((aWZ*Pi*z)/L))/L;
PetscFunctionReturn(0);
}
static PetscErrorCode SourceRhoU(PetscInt dim, PetscReal time, const PetscReal xyz[], PetscInt Nf, PetscScalar *u, void *ctx) {
PetscFunctionBeginUser;
Constants *constants = (Constants *)ctx;
PetscReal L = constants->L;
PetscReal gamma = constants->gamma;
PetscReal rhoO = constants->rho.phiO;
PetscReal rhoX = constants->rho.phiX;
PetscReal rhoY = constants->rho.phiY;
PetscReal rhoZ = constants->rho.phiZ;
PetscReal aRhoX = constants->rho.aPhiX;
PetscReal aRhoY = constants->rho.aPhiY;
PetscReal aRhoZ = constants->rho.aPhiZ;
PetscReal uO = constants->u.phiO;
PetscReal uX = constants->u.phiX;
PetscReal uY = constants->u.phiY;
PetscReal uZ = constants->u.phiZ;
PetscReal aUX = constants->u.aPhiX;
PetscReal aUY = constants->u.aPhiY;
PetscReal aUZ = constants->u.aPhiZ;
PetscReal vO = constants->v.phiO;
PetscReal vX = constants->v.phiX;
PetscReal vY = constants->v.phiY;
PetscReal vZ = constants->v.phiZ;
PetscReal aVX = constants->v.aPhiX;
PetscReal aVY = constants->v.aPhiY;
PetscReal aVZ = constants->v.aPhiZ;
PetscReal wO = constants->w.phiO;
PetscReal wX = constants->w.phiX;
PetscReal wY = constants->w.phiY;
PetscReal wZ = constants->w.phiZ;
PetscReal aWX = constants->w.aPhiX;
PetscReal aWY = constants->w.aPhiY;
PetscReal aWZ = constants->w.aPhiZ;
PetscReal pO = constants->p.phiO;
PetscReal pX = constants->p.phiX;
PetscReal pY = constants->p.phiY;
PetscReal pZ = constants->p.phiZ;
PetscReal aPX = constants->p.aPhiX;
PetscReal aPY = constants->p.aPhiY;
PetscReal aPZ = constants->p.aPhiZ;
PetscReal x = xyz[0];
PetscReal y = xyz[1];
PetscReal z = dim > 2? xyz[2] : 0.0;
u[0] = -((aPX*Pi*pX*Sin((aPX*Pi*x)/L))/L) + (aRhoX*Pi*rhoX*Cos((aRhoX*Pi*x)/L)*
Power(uO + uY*Cos((aUY*Pi*y)/L) + uZ*Cos((aUZ*Pi*z)/L) + uX*Sin((aUX*Pi*x)/L),2))/L +
(aRhoZ*Pi*rhoZ*Cos((aRhoZ*Pi*z)/L)*(uO + uY*Cos((aUY*Pi*y)/L) + uZ*Cos((aUZ*Pi*z)/L) +
uX*Sin((aUX*Pi*x)/L))*(wO + wZ*Cos((aWZ*Pi*z)/L) + wX*Sin((aWX*Pi*x)/L) + wY*Sin((aWY*Pi*y)/L)))/
L + (2*aUX*Pi*uX*Cos((aUX*Pi*x)/L)*(uO + uY*Cos((aUY*Pi*y)/L) + uZ*Cos((aUZ*Pi*z)/L) +
uX*Sin((aUX*Pi*x)/L))*(rhoO + rhoY*Cos((aRhoY*Pi*y)/L) + rhoX*Sin((aRhoX*Pi*x)/L) +
rhoZ*Sin((aRhoZ*Pi*z)/L)))/L + (aVY*Pi*vY*Cos((aVY*Pi*y)/L)*
(uO + uY*Cos((aUY*Pi*y)/L) + uZ*Cos((aUZ*Pi*z)/L) + uX*Sin((aUX*Pi*x)/L))*
(rhoO + rhoY*Cos((aRhoY*Pi*y)/L) + rhoX*Sin((aRhoX*Pi*x)/L) + rhoZ*Sin((aRhoZ*Pi*z)/L)))/L -
(aUZ*Pi*uZ*(wO + wZ*Cos((aWZ*Pi*z)/L) + wX*Sin((aWX*Pi*x)/L) + wY*Sin((aWY*Pi*y)/L))*
(rhoO + rhoY*Cos((aRhoY*Pi*y)/L) + rhoX*Sin((aRhoX*Pi*x)/L) + rhoZ*Sin((aRhoZ*Pi*z)/L))*
Sin((aUZ*Pi*z)/L))/L - (aRhoY*Pi*rhoY*
(uO + uY*Cos((aUY*Pi*y)/L) + uZ*Cos((aUZ*Pi*z)/L) + uX*Sin((aUX*Pi*x)/L))*Sin((aRhoY*Pi*y)/L)*
(vO + vX*Cos((aVX*Pi*x)/L) + vY*Sin((aVY*Pi*y)/L) + vZ*Sin((aVZ*Pi*z)/L)))/L -
(aUY*Pi*uY*Sin((aUY*Pi*y)/L)*(rhoO + rhoY*Cos((aRhoY*Pi*y)/L) + rhoX*Sin((aRhoX*Pi*x)/L) +
rhoZ*Sin((aRhoZ*Pi*z)/L))*(vO + vX*Cos((aVX*Pi*x)/L) + vY*Sin((aVY*Pi*y)/L) +
vZ*Sin((aVZ*Pi*z)/L)))/L - (aWZ*Pi*wZ*
(uO + uY*Cos((aUY*Pi*y)/L) + uZ*Cos((aUZ*Pi*z)/L) + uX*Sin((aUX*Pi*x)/L))*
(rhoO + rhoY*Cos((aRhoY*Pi*y)/L) + rhoX*Sin((aRhoX*Pi*x)/L) + rhoZ*Sin((aRhoZ*Pi*z)/L))*
Sin((aWZ*Pi*z)/L))/L;
u[1] = (aPY*Pi*pY*Cos((aPY*Pi*y)/L))/L - (aVX*Pi*vX*
(uO + uY*Cos((aUY*Pi*y)/L) + uZ*Cos((aUZ*Pi*z)/L) + uX*Sin((aUX*Pi*x)/L))*Sin((aVX*Pi*x)/L)*
(rhoO + rhoY*Cos((aRhoY*Pi*y)/L) + rhoX*Sin((aRhoX*Pi*x)/L) + rhoZ*Sin((aRhoZ*Pi*z)/L)))/L +
(aVZ*Pi*vZ*Cos((aVZ*Pi*z)/L)*(wO + wZ*Cos((aWZ*Pi*z)/L) + wX*Sin((aWX*Pi*x)/L) +
wY*Sin((aWY*Pi*y)/L))*(rhoO + rhoY*Cos((aRhoY*Pi*y)/L) + rhoX*Sin((aRhoX*Pi*x)/L) +
rhoZ*Sin((aRhoZ*Pi*z)/L)))/L + (aRhoX*Pi*rhoX*Cos((aRhoX*Pi*x)/L)*
(uO + uY*Cos((aUY*Pi*y)/L) + uZ*Cos((aUZ*Pi*z)/L) + uX*Sin((aUX*Pi*x)/L))*
(vO + vX*Cos((aVX*Pi*x)/L) + vY*Sin((aVY*Pi*y)/L) + vZ*Sin((aVZ*Pi*z)/L)))/L +
(aRhoZ*Pi*rhoZ*Cos((aRhoZ*Pi*z)/L)*(wO + wZ*Cos((aWZ*Pi*z)/L) + wX*Sin((aWX*Pi*x)/L) +
wY*Sin((aWY*Pi*y)/L))*(vO + vX*Cos((aVX*Pi*x)/L) + vY*Sin((aVY*Pi*y)/L) + vZ*Sin((aVZ*Pi*z)/L)))/
L + (aUX*Pi*uX*Cos((aUX*Pi*x)/L)*(rhoO + rhoY*Cos((aRhoY*Pi*y)/L) + rhoX*Sin((aRhoX*Pi*x)/L) +
rhoZ*Sin((aRhoZ*Pi*z)/L))*(vO + vX*Cos((aVX*Pi*x)/L) + vY*Sin((aVY*Pi*y)/L) +
vZ*Sin((aVZ*Pi*z)/L)))/L + (2*aVY*Pi*vY*Cos((aVY*Pi*y)/L)*
(rhoO + rhoY*Cos((aRhoY*Pi*y)/L) + rhoX*Sin((aRhoX*Pi*x)/L) + rhoZ*Sin((aRhoZ*Pi*z)/L))*
(vO + vX*Cos((aVX*Pi*x)/L) + vY*Sin((aVY*Pi*y)/L) + vZ*Sin((aVZ*Pi*z)/L)))/L -
(aRhoY*Pi*rhoY*Sin((aRhoY*Pi*y)/L)*Power(vO + vX*Cos((aVX*Pi*x)/L) + vY*Sin((aVY*Pi*y)/L) +
vZ*Sin((aVZ*Pi*z)/L),2))/L - (aWZ*Pi*wZ*
(rhoO + rhoY*Cos((aRhoY*Pi*y)/L) + rhoX*Sin((aRhoX*Pi*x)/L) + rhoZ*Sin((aRhoZ*Pi*z)/L))*
(vO + vX*Cos((aVX*Pi*x)/L) + vY*Sin((aVY*Pi*y)/L) + vZ*Sin((aVZ*Pi*z)/L))*Sin((aWZ*Pi*z)/L))/L;
if(dim >2){
u[2] = (aRhoX*Pi*rhoX*Cos((aRhoX*Pi*x)/L)*(uO + uY*Cos((aUY*Pi*y)/L) + uZ*Cos((aUZ*Pi*z)/L) +
uX*Sin((aUX*Pi*x)/L))*(wO + wZ*Cos((aWZ*Pi*z)/L) + wX*Sin((aWX*Pi*x)/L) + wY*Sin((aWY*Pi*y)/L)))/
L + (aRhoZ*Pi*rhoZ*Cos((aRhoZ*Pi*z)/L)*
Power(wO + wZ*Cos((aWZ*Pi*z)/L) + wX*Sin((aWX*Pi*x)/L) + wY*Sin((aWY*Pi*y)/L),2))/L -
(aPZ*Pi*pZ*Sin((aPZ*Pi*z)/L))/L + (aWX*Pi*wX*Cos((aWX*Pi*x)/L)*
(uO + uY*Cos((aUY*Pi*y)/L) + uZ*Cos((aUZ*Pi*z)/L) + uX*Sin((aUX*Pi*x)/L))*
(rhoO + rhoY*Cos((aRhoY*Pi*y)/L) + rhoX*Sin((aRhoX*Pi*x)/L) + rhoZ*Sin((aRhoZ*Pi*z)/L)))/L +
(aUX*Pi*uX*Cos((aUX*Pi*x)/L)*(wO + wZ*Cos((aWZ*Pi*z)/L) + wX*Sin((aWX*Pi*x)/L) +
wY*Sin((aWY*Pi*y)/L))*(rhoO + rhoY*Cos((aRhoY*Pi*y)/L) + rhoX*Sin((aRhoX*Pi*x)/L) +
rhoZ*Sin((aRhoZ*Pi*z)/L)))/L + (aVY*Pi*vY*Cos((aVY*Pi*y)/L)*
(wO + wZ*Cos((aWZ*Pi*z)/L) + wX*Sin((aWX*Pi*x)/L) + wY*Sin((aWY*Pi*y)/L))*
(rhoO + rhoY*Cos((aRhoY*Pi*y)/L) + rhoX*Sin((aRhoX*Pi*x)/L) + rhoZ*Sin((aRhoZ*Pi*z)/L)))/L -
(aRhoY*Pi*rhoY*Sin((aRhoY*Pi*y)/L)*(wO + wZ*Cos((aWZ*Pi*z)/L) + wX*Sin((aWX*Pi*x)/L) +
wY*Sin((aWY*Pi*y)/L))*(vO + vX*Cos((aVX*Pi*x)/L) + vY*Sin((aVY*Pi*y)/L) + vZ*Sin((aVZ*Pi*z)/L)))/
L + (aWY*Pi*wY*Cos((aWY*Pi*y)/L)*(rhoO + rhoY*Cos((aRhoY*Pi*y)/L) + rhoX*Sin((aRhoX*Pi*x)/L) +
rhoZ*Sin((aRhoZ*Pi*z)/L))*(vO + vX*Cos((aVX*Pi*x)/L) + vY*Sin((aVY*Pi*y)/L) +
vZ*Sin((aVZ*Pi*z)/L)))/L - (2*aWZ*Pi*wZ*
(wO + wZ*Cos((aWZ*Pi*z)/L) + wX*Sin((aWX*Pi*x)/L) + wY*Sin((aWY*Pi*y)/L))*
(rhoO + rhoY*Cos((aRhoY*Pi*y)/L) + rhoX*Sin((aRhoX*Pi*x)/L) + rhoZ*Sin((aRhoZ*Pi*z)/L))*
Sin((aWZ*Pi*z)/L))/L;
}
PetscFunctionReturn(0);
}
static PetscErrorCode SourceRhoE(PetscInt dim, PetscReal time, const PetscReal xyz[], PetscInt Nf, PetscScalar *u, void *ctx) {
PetscFunctionBeginUser;
Constants *constants = (Constants *)ctx;
PetscReal L = constants->L;
PetscReal gamma = constants->gamma;
PetscReal rhoO = constants->rho.phiO;
PetscReal rhoX = constants->rho.phiX;
PetscReal rhoY = constants->rho.phiY;
PetscReal rhoZ = constants->rho.phiZ;
PetscReal aRhoX = constants->rho.aPhiX;
PetscReal aRhoY = constants->rho.aPhiY;
PetscReal aRhoZ = constants->rho.aPhiZ;
PetscReal uO = constants->u.phiO;
PetscReal uX = constants->u.phiX;
PetscReal uY = constants->u.phiY;
PetscReal uZ = constants->u.phiZ;
PetscReal aUX = constants->u.aPhiX;
PetscReal aUY = constants->u.aPhiY;
PetscReal aUZ = constants->u.aPhiZ;
PetscReal vO = constants->v.phiO;
PetscReal vX = constants->v.phiX;
PetscReal vY = constants->v.phiY;
PetscReal vZ = constants->v.phiZ;
PetscReal aVX = constants->v.aPhiX;
PetscReal aVY = constants->v.aPhiY;
PetscReal aVZ = constants->v.aPhiZ;
PetscReal wO = constants->w.phiO;
PetscReal wX = constants->w.phiX;
PetscReal wY = constants->w.phiY;
PetscReal wZ = constants->w.phiZ;
PetscReal aWX = constants->w.aPhiX;
PetscReal aWY = constants->w.aPhiY;
PetscReal aWZ = constants->w.aPhiZ;
PetscReal pO = constants->p.phiO;
PetscReal pX = constants->p.phiX;
PetscReal pY = constants->p.phiY;
PetscReal pZ = constants->p.phiZ;
PetscReal aPX = constants->p.aPhiX;
PetscReal aPY = constants->p.aPhiY;
PetscReal aPZ = constants->p.aPhiZ;
PetscReal x = xyz[0];
PetscReal y = xyz[1];
PetscReal z = dim > 2? xyz[2] : 0.0;
u[0] = -((aPX*Pi*pX*Sin((aPX*Pi*x)/L)*(uO + uY*Cos((aUY*Pi*y)/L) + uZ*Cos((aUZ*Pi*z)/L) + uX*Sin((aUX*Pi*x)/L)))/L) + (aUX*Pi*uX*Cos((aUX*Pi*x)/L)*(pO + pX*Cos((aPX*Pi*x)/L) + pZ*Cos((aPZ*Pi*z)/L) + pY*Sin((aPY*Pi*y)/L)))/L +
(aVY*Pi*vY*Cos((aVY*Pi*y)/L)*(pO + pX*Cos((aPX*Pi*x)/L) + pZ*Cos((aPZ*Pi*z)/L) + pY*Sin((aPY*Pi*y)/L)))/L - (aPZ*Pi*pZ*(wO + wZ*Cos((aWZ*Pi*z)/L) + wX*Sin((aWX*Pi*x)/L) + wY*Sin((aWY*Pi*y)/L))*Sin((aPZ*Pi*z)/L))/L +
(aPY*Pi*pY*Cos((aPY*Pi*y)/L)*(vO + vX*Cos((aVX*Pi*x)/L) + vY*Sin((aVY*Pi*y)/L) + vZ*Sin((aVZ*Pi*z)/L)))/L + (rhoO + rhoY*Cos((aRhoY*Pi*y)/L) + rhoX*Sin((aRhoX*Pi*x)/L) + rhoZ*Sin((aRhoZ*Pi*z)/L))*(vO + vX*Cos((aVX*Pi*x)/L) + vY*Sin((aVY*Pi*y)/L) + vZ*Sin((aVZ*Pi*z)/L))*
((aRhoY*Pi*rhoY*(pO + pX*Cos((aPX*Pi*x)/L) + pZ*Cos((aPZ*Pi*z)/L) + pY*Sin((aPY*Pi*y)/L))*Sin((aRhoY*Pi*y)/L))/((-1. + gamma)*L*Power(rhoO + rhoY*Cos((aRhoY*Pi*y)/L) + rhoX*Sin((aRhoX*Pi*x)/L) + rhoZ*Sin((aRhoZ*Pi*z)/L),2)) +
(aPY*Pi*pY*Cos((aPY*Pi*y)/L))/((-1. + gamma)*L*(rhoO + rhoY*Cos((aRhoY*Pi*y)/L) + rhoX*Sin((aRhoX*Pi*x)/L) + rhoZ*Sin((aRhoZ*Pi*z)/L))) +
((-2*aUY*Pi*uY*(uO + uY*Cos((aUY*Pi*y)/L) + uZ*Cos((aUZ*Pi*z)/L) + uX*Sin((aUX*Pi*x)/L))*Sin((aUY*Pi*y)/L))/L + (2*aWY*Pi*wY*Cos((aWY*Pi*y)/L)*(wO + wZ*Cos((aWZ*Pi*z)/L) + wX*Sin((aWX*Pi*x)/L) + wY*Sin((aWY*Pi*y)/L)))/L +
(2*aVY*Pi*vY*Cos((aVY*Pi*y)/L)*(vO + vX*Cos((aVX*Pi*x)/L) + vY*Sin((aVY*Pi*y)/L) + vZ*Sin((aVZ*Pi*z)/L)))/L)/2.) + (uO + uY*Cos((aUY*Pi*y)/L) + uZ*Cos((aUZ*Pi*z)/L) + uX*Sin((aUX*Pi*x)/L))*(rhoO + rhoY*Cos((aRhoY*Pi*y)/L) + rhoX*Sin((aRhoX*Pi*x)/L) + rhoZ*Sin((aRhoZ*Pi*z)/L))*
(-((aRhoX*Pi*rhoX*Cos((aRhoX*Pi*x)/L)*(pO + pX*Cos((aPX*Pi*x)/L) + pZ*Cos((aPZ*Pi*z)/L) + pY*Sin((aPY*Pi*y)/L)))/((-1. + gamma)*L*Power(rhoO + rhoY*Cos((aRhoY*Pi*y)/L) + rhoX*Sin((aRhoX*Pi*x)/L) + rhoZ*Sin((aRhoZ*Pi*z)/L),2))) -
(aPX*Pi*pX*Sin((aPX*Pi*x)/L))/((-1. + gamma)*L*(rhoO + rhoY*Cos((aRhoY*Pi*y)/L) + rhoX*Sin((aRhoX*Pi*x)/L) + rhoZ*Sin((aRhoZ*Pi*z)/L))) +
((2*aUX*Pi*uX*Cos((aUX*Pi*x)/L)*(uO + uY*Cos((aUY*Pi*y)/L) + uZ*Cos((aUZ*Pi*z)/L) + uX*Sin((aUX*Pi*x)/L)))/L + (2*aWX*Pi*wX*Cos((aWX*Pi*x)/L)*(wO + wZ*Cos((aWZ*Pi*z)/L) + wX*Sin((aWX*Pi*x)/L) + wY*Sin((aWY*Pi*y)/L)))/L -
(2*aVX*Pi*vX*Sin((aVX*Pi*x)/L)*(vO + vX*Cos((aVX*Pi*x)/L) + vY*Sin((aVY*Pi*y)/L) + vZ*Sin((aVZ*Pi*z)/L)))/L)/2.) + (aRhoX*Pi*rhoX*Cos((aRhoX*Pi*x)/L)*(uO + uY*Cos((aUY*Pi*y)/L) + uZ*Cos((aUZ*Pi*z)/L) + uX*Sin((aUX*Pi*x)/L))*
((pO + pX*Cos((aPX*Pi*x)/L) + pZ*Cos((aPZ*Pi*z)/L) + pY*Sin((aPY*Pi*y)/L))/((-1. + gamma)*(rhoO + rhoY*Cos((aRhoY*Pi*y)/L) + rhoX*Sin((aRhoX*Pi*x)/L) + rhoZ*Sin((aRhoZ*Pi*z)/L))) +
(Power(uO + uY*Cos((aUY*Pi*y)/L) + uZ*Cos((aUZ*Pi*z)/L) + uX*Sin((aUX*Pi*x)/L),2) + Power(wO + wZ*Cos((aWZ*Pi*z)/L) + wX*Sin((aWX*Pi*x)/L) + wY*Sin((aWY*Pi*y)/L),2) + Power(vO + vX*Cos((aVX*Pi*x)/L) + vY*Sin((aVY*Pi*y)/L) + vZ*Sin((aVZ*Pi*z)/L),2))/2.))/L +
(aRhoZ*Pi*rhoZ*Cos((aRhoZ*Pi*z)/L)*(wO + wZ*Cos((aWZ*Pi*z)/L) + wX*Sin((aWX*Pi*x)/L) + wY*Sin((aWY*Pi*y)/L))*((pO + pX*Cos((aPX*Pi*x)/L) + pZ*Cos((aPZ*Pi*z)/L) + pY*Sin((aPY*Pi*y)/L))/((-1. + gamma)*(rhoO + rhoY*Cos((aRhoY*Pi*y)/L) + rhoX*Sin((aRhoX*Pi*x)/L) + rhoZ*Sin((aRhoZ*Pi*z)/L))) +
(Power(uO + uY*Cos((aUY*Pi*y)/L) + uZ*Cos((aUZ*Pi*z)/L) + uX*Sin((aUX*Pi*x)/L),2) + Power(wO + wZ*Cos((aWZ*Pi*z)/L) + wX*Sin((aWX*Pi*x)/L) + wY*Sin((aWY*Pi*y)/L),2) + Power(vO + vX*Cos((aVX*Pi*x)/L) + vY*Sin((aVY*Pi*y)/L) + vZ*Sin((aVZ*Pi*z)/L),2))/2.))/L +
(aUX*Pi*uX*Cos((aUX*Pi*x)/L)*(rhoO + rhoY*Cos((aRhoY*Pi*y)/L) + rhoX*Sin((aRhoX*Pi*x)/L) + rhoZ*Sin((aRhoZ*Pi*z)/L))*((pO + pX*Cos((aPX*Pi*x)/L) + pZ*Cos((aPZ*Pi*z)/L) + pY*Sin((aPY*Pi*y)/L))/((-1. + gamma)*(rhoO + rhoY*Cos((aRhoY*Pi*y)/L) + rhoX*Sin((aRhoX*Pi*x)/L) + rhoZ*Sin((aRhoZ*Pi*z)/L))) +
(Power(uO + uY*Cos((aUY*Pi*y)/L) + uZ*Cos((aUZ*Pi*z)/L) + uX*Sin((aUX*Pi*x)/L),2) + Power(wO + wZ*Cos((aWZ*Pi*z)/L) + wX*Sin((aWX*Pi*x)/L) + wY*Sin((aWY*Pi*y)/L),2) + Power(vO + vX*Cos((aVX*Pi*x)/L) + vY*Sin((aVY*Pi*y)/L) + vZ*Sin((aVZ*Pi*z)/L),2))/2.))/L +
(aVY*Pi*vY*Cos((aVY*Pi*y)/L)*(rhoO + rhoY*Cos((aRhoY*Pi*y)/L) + rhoX*Sin((aRhoX*Pi*x)/L) + rhoZ*Sin((aRhoZ*Pi*z)/L))*((pO + pX*Cos((aPX*Pi*x)/L) + pZ*Cos((aPZ*Pi*z)/L) + pY*Sin((aPY*Pi*y)/L))/((-1. + gamma)*(rhoO + rhoY*Cos((aRhoY*Pi*y)/L) + rhoX*Sin((aRhoX*Pi*x)/L) + rhoZ*Sin((aRhoZ*Pi*z)/L))) +
(Power(uO + uY*Cos((aUY*Pi*y)/L) + uZ*Cos((aUZ*Pi*z)/L) + uX*Sin((aUX*Pi*x)/L),2) + Power(wO + wZ*Cos((aWZ*Pi*z)/L) + wX*Sin((aWX*Pi*x)/L) + wY*Sin((aWY*Pi*y)/L),2) + Power(vO + vX*Cos((aVX*Pi*x)/L) + vY*Sin((aVY*Pi*y)/L) + vZ*Sin((aVZ*Pi*z)/L),2))/2.))/L -
(aRhoY*Pi*rhoY*Sin((aRhoY*Pi*y)/L)*(vO + vX*Cos((aVX*Pi*x)/L) + vY*Sin((aVY*Pi*y)/L) + vZ*Sin((aVZ*Pi*z)/L))*((pO + pX*Cos((aPX*Pi*x)/L) + pZ*Cos((aPZ*Pi*z)/L) + pY*Sin((aPY*Pi*y)/L))/((-1. + gamma)*(rhoO + rhoY*Cos((aRhoY*Pi*y)/L) + rhoX*Sin((aRhoX*Pi*x)/L) + rhoZ*Sin((aRhoZ*Pi*z)/L))) +
(Power(uO + uY*Cos((aUY*Pi*y)/L) + uZ*Cos((aUZ*Pi*z)/L) + uX*Sin((aUX*Pi*x)/L),2) + Power(wO + wZ*Cos((aWZ*Pi*z)/L) + wX*Sin((aWX*Pi*x)/L) + wY*Sin((aWY*Pi*y)/L),2) + Power(vO + vX*Cos((aVX*Pi*x)/L) + vY*Sin((aVY*Pi*y)/L) + vZ*Sin((aVZ*Pi*z)/L),2))/2.))/L -
(aWZ*Pi*wZ*(pO + pX*Cos((aPX*Pi*x)/L) + pZ*Cos((aPZ*Pi*z)/L) + pY*Sin((aPY*Pi*y)/L))*Sin((aWZ*Pi*z)/L))/L - (aWZ*Pi*wZ*(rhoO + rhoY*Cos((aRhoY*Pi*y)/L) + rhoX*Sin((aRhoX*Pi*x)/L) + rhoZ*Sin((aRhoZ*Pi*z)/L))*
((pO + pX*Cos((aPX*Pi*x)/L) + pZ*Cos((aPZ*Pi*z)/L) + pY*Sin((aPY*Pi*y)/L))/((-1. + gamma)*(rhoO + rhoY*Cos((aRhoY*Pi*y)/L) + rhoX*Sin((aRhoX*Pi*x)/L) + rhoZ*Sin((aRhoZ*Pi*z)/L))) +
(Power(uO + uY*Cos((aUY*Pi*y)/L) + uZ*Cos((aUZ*Pi*z)/L) + uX*Sin((aUX*Pi*x)/L),2) + Power(wO + wZ*Cos((aWZ*Pi*z)/L) + wX*Sin((aWX*Pi*x)/L) + wY*Sin((aWY*Pi*y)/L),2) + Power(vO + vX*Cos((aVX*Pi*x)/L) + vY*Sin((aVY*Pi*y)/L) + vZ*Sin((aVZ*Pi*z)/L),2))/2.)*Sin((aWZ*Pi*z)/L))/L +
(wO + wZ*Cos((aWZ*Pi*z)/L) + wX*Sin((aWX*Pi*x)/L) + wY*Sin((aWY*Pi*y)/L))*(rhoO + rhoY*Cos((aRhoY*Pi*y)/L) + rhoX*Sin((aRhoX*Pi*x)/L) + rhoZ*Sin((aRhoZ*Pi*z)/L))*
(-((aRhoZ*Pi*rhoZ*Cos((aRhoZ*Pi*z)/L)*(pO + pX*Cos((aPX*Pi*x)/L) + pZ*Cos((aPZ*Pi*z)/L) + pY*Sin((aPY*Pi*y)/L)))/((-1. + gamma)*L*Power(rhoO + rhoY*Cos((aRhoY*Pi*y)/L) + rhoX*Sin((aRhoX*Pi*x)/L) + rhoZ*Sin((aRhoZ*Pi*z)/L),2))) -
(aPZ*Pi*pZ*Sin((aPZ*Pi*z)/L))/((-1. + gamma)*L*(rhoO + rhoY*Cos((aRhoY*Pi*y)/L) + rhoX*Sin((aRhoX*Pi*x)/L) + rhoZ*Sin((aRhoZ*Pi*z)/L))) +
((-2*aUZ*Pi*uZ*(uO + uY*Cos((aUY*Pi*y)/L) + uZ*Cos((aUZ*Pi*z)/L) + uX*Sin((aUX*Pi*x)/L))*Sin((aUZ*Pi*z)/L))/L + (2*aVZ*Pi*vZ*Cos((aVZ*Pi*z)/L)*(vO + vX*Cos((aVX*Pi*x)/L) + vY*Sin((aVY*Pi*y)/L) + vZ*Sin((aVZ*Pi*z)/L)))/L -
(2*aWZ*Pi*wZ*(wO + wZ*Cos((aWZ*Pi*z)/L) + wX*Sin((aWX*Pi*x)/L) + wY*Sin((aWY*Pi*y)/L))*Sin((aWZ*Pi*z)/L))/L)/2.);
PetscFunctionReturn(0);
}
static PetscErrorCode PhysicsBoundary_Euler(PetscReal time, const PetscReal *c, const PetscReal *n, const PetscScalar *a_xI, PetscScalar *a_xG, void *ctx) {
PetscFunctionBeginUser;
Constants *constants = (Constants *)ctx;
// Offset the calc assuming the cells are square
PetscReal x[3];
for(PetscInt i =0; i < constants->dim; i++){
x[i] = c[i] + n[i]*0.5;
}
EulerExact(constants->dim, time, x, 0, a_xG, ctx);
PetscFunctionReturn(0);
}
static PetscErrorCode ComputeRHSWithSourceTerms(DM dm, PetscReal time, Vec locXVec, Vec globFVec, void *ctx){
PetscFunctionBeginUser;
PetscErrorCode ierr;
ProblemSetup *setup = (ProblemSetup *)ctx;
// Call the flux calculation
ierr = DMPlexTSComputeRHSFunctionFVM(dm, time, locXVec, globFVec, setup->flowData);CHKERRQ(ierr);
// Convert the dm to a plex
DM plex;
DMConvert(dm, DMPLEX, &plex);
// Extract the cell geometry, and the dm that holds the information
Vec cellgeom;
DM dmCell;
const PetscScalar *cgeom;
ierr = DMPlexGetGeometryFVM(plex, NULL, &cellgeom, NULL);CHKERRQ(ierr);
ierr = VecGetDM(cellgeom, &dmCell);CHKERRQ(ierr);
ierr = VecGetArrayRead(cellgeom, &cgeom);CHKERRQ(ierr);
// Get the cell start and end for the fv cells
PetscInt cStart, cEnd;
ierr = DMPlexGetSimplexOrBoxCells(dmCell, 0, &cStart, &cEnd);CHKERRQ(ierr);
// create a local f vector
Vec locFVec;
PetscScalar *locFArray;
ierr = DMGetLocalVector(dm, &locFVec);CHKERRQ(ierr);
ierr = VecZeroEntries(locFVec);CHKERRQ(ierr);
ierr = VecGetArray(locFVec, &locFArray);CHKERRQ(ierr);
// get the current values
const PetscScalar *locXArray;
ierr = VecGetArrayRead(locXVec, &locXArray);CHKERRQ(ierr);
PetscInt rank;
MPI_Comm_rank(PETSC_COMM_WORLD, &rank);
// March over each cell volume
for (PetscInt c = cStart; c < cEnd; ++c) {
PetscFVCellGeom *cg;
const PetscReal *xc;
PetscReal *fc;
ierr = DMPlexPointLocalRead(dmCell, c, cgeom, &cg);CHKERRQ(ierr);
ierr = DMPlexPointLocalFieldRead(plex, c, 0, locXArray, &xc);CHKERRQ(ierr);
ierr = DMPlexPointGlobalFieldRef(plex, c, 0, locFArray, &fc);CHKERRQ(ierr);
if(fc) { // must be real cell and not ghost
SourceRho(setup->constants.dim, time, cg->centroid, 0, fc + RHO, &setup->constants);
SourceRhoE(setup->constants.dim, time, cg->centroid, 0, fc + RHOE, &setup->constants);
SourceRhoU(setup->constants.dim, time, cg->centroid, 0, fc + RHOU, &setup->constants);
}
}
// restore the cell geometry
ierr = VecRestoreArrayRead(cellgeom, &cgeom);CHKERRQ(ierr);
ierr = VecRestoreArrayRead(locXVec, &locXArray);CHKERRQ(ierr);
ierr = VecRestoreArray(locFVec, &locFArray);CHKERRQ(ierr);
ierr = DMLocalToGlobalBegin(dm, locFVec, ADD_VALUES, globFVec);CHKERRQ(ierr);
ierr = DMLocalToGlobalEnd(dm, locFVec, ADD_VALUES, globFVec);CHKERRQ(ierr);
ierr = DMRestoreLocalVector(dm, &locFVec);CHKERRQ(ierr);
// {// check rhs,
// // temp read current residual
// const PetscScalar *currentFArray;
// ierr = VecGetArrayRead(globFVec, ¤tFArray);CHKERRQ(ierr);
// ierr = VecGetArrayRead(cellgeom, &cgeom);CHKERRQ(ierr);
//
// // March over each cell volume
// for (PetscInt c = cStart; c < cEnd; ++c) {
// PetscFVCellGeom *cg;
// const PetscReal *fcCurrent;
//
// ierr = DMPlexPointLocalRead(dmCell, c, cgeom, &cg);CHKERRQ(ierr);
// ierr = DMPlexPointGlobalFieldRead(plex, c, 0, currentFArray, &fcCurrent);CHKERRQ(ierr);
//
// if(fcCurrent) { // must be real cell and not ghost
// if(PetscAbsReal(cg->centroid[0] - .5 ) < 1E-8 && PetscAbsReal(cg->centroid[1] - .5 ) < 1E-8){
// printf("Residual(%f, %f): %f %f %f %f\n", cg->centroid[0], cg->centroid[1], fcCurrent[0], fcCurrent[1], fcCurrent[2], fcCurrent[3]);
// }
// }
// }
//
// // temp return current residual
// ierr = VecRestoreArrayRead(globFVec, ¤tFArray);CHKERRQ(ierr);
// ierr = VecRestoreArrayRead(cellgeom, &cgeom);CHKERRQ(ierr);
// }
PetscFunctionReturn(0);
}
PetscErrorCode ComputeRHS(TS ts, DM dm, PetscReal t, Vec u, PetscInt blockSize, PetscReal residualNorm2[], PetscReal residualNormInf[], PetscReal start[], PetscReal end[])
{
MPI_Comm comm;
Vec r;
PetscErrorCode ierr;
PetscFunctionBeginUser;
Vec sol;
ierr = VecDuplicate(u, &sol);CHKERRQ(ierr);
ierr = VecCopy(u, sol);CHKERRQ(ierr);
ierr = PetscObjectGetComm((PetscObject) ts, &comm);CHKERRQ(ierr);
ierr = DMComputeExactSolution(dm, t, sol, NULL);CHKERRQ(ierr);
ierr = VecDuplicate(u, &r);CHKERRQ(ierr);
ierr = TSComputeRHSFunction(ts, t, sol, r);CHKERRQ(ierr);
// zero out the norms
for(PetscInt b =0; b < blockSize; b++){
residualNorm2[b] = 0.0;
residualNormInf[b] = 0.0;
}
{//March over each cell
// Extract the cell geometry, and the dm that holds the information
Vec cellgeom;
DM dmCell;
PetscInt dim;
const PetscScalar *cgeom;
ierr = DMPlexGetGeometryFVM(dm, NULL, &cellgeom, NULL);CHKERRQ(ierr);
ierr = VecGetDM(cellgeom, &dmCell);CHKERRQ(ierr);
ierr = DMGetDimension(dm, &dim);CHKERRQ(ierr);
// Get the cell start and end for the fv cells
PetscInt cStart, cEnd;
ierr = DMPlexGetSimplexOrBoxCells(dmCell, 0, &cStart, &cEnd);CHKERRQ(ierr);
// temp read current residual
const PetscScalar *currentRHS;
ierr = VecGetArrayRead(cellgeom, &cgeom);CHKERRQ(ierr);
ierr = VecGetArrayRead(r, ¤tRHS);CHKERRQ(ierr);
// Count up the cells
PetscInt count = 0;
// March over each cell volume
for (PetscInt c = cStart; c < cEnd; ++c) {
PetscFVCellGeom *cg;
const PetscReal *rhsCurrent;
ierr = DMPlexPointLocalRead(dmCell, c, cgeom, &cg);CHKERRQ(ierr);
ierr = DMPlexPointGlobalFieldRead(dm, c, 0, currentRHS, &rhsCurrent);CHKERRQ(ierr);
PetscBool countCell = PETSC_TRUE;
for(PetscInt d =0; d < dim; d++){
countCell = cg->centroid[d] < start[d] || cg->centroid[d] > end[d] ? PETSC_FALSE : countCell;
}
if(rhsCurrent && countCell ) { // must be real cell and not ghost
for(PetscInt b =0; b < blockSize; b++){
residualNorm2[b] += PetscSqr(rhsCurrent[b]);
residualNormInf[b] = PetscMax(residualNormInf[b], PetscAbs(rhsCurrent[b]));
}
count++;
}
}
// normalize the norm2
for(PetscInt b =0; b < blockSize; b++){
residualNorm2[b] = PetscSqrtReal(residualNorm2[b]/count);
}
// temp return current residual
ierr = VecRestoreArrayRead(cellgeom, &cgeom);CHKERRQ(ierr);
ierr = VecRestoreArrayRead(r, ¤tRHS);CHKERRQ(ierr);
}
ierr = VecDestroy(&sol);CHKERRQ(ierr);
ierr = VecDestroy(&r);CHKERRQ(ierr);
PetscFunctionReturn(0);
}
int main(int argc, char **argv)
{
// Setup the problem
Constants constants;
// sub sonic
constants.dim = 2;
constants.L = 1.0;
constants.gamma = 1.4;
constants.R = 287.0;
constants.mu = 10;
constants.rho.phiO = 1.0;
constants.rho.phiX = 0.15;
constants.rho.phiY = -0.1;
constants.rho.phiZ = 0.0;
constants.rho.aPhiX = 1.0;
constants.rho.aPhiY = 0.5;
constants.rho.aPhiZ = 0.0;
constants.u.phiO = 70;
constants.u.phiX = 5;
constants.u.phiY = -7;
constants.u.phiZ = 0.0;
constants.u.aPhiX = 1.5;
constants.u.aPhiY = 0.6;
constants.u.aPhiZ = 0.0;
constants.v.phiO = 90;
constants.v.phiX = -15;
constants.v.phiY = -8.5;
constants.v.phiZ = 0.0;
constants.v.aPhiX = 0.5;
constants.v.aPhiY = 2.0/3.0;
constants.v.aPhiZ = 0.0;
constants.w.phiO = 0.0;
constants.w.phiX = 0.0;
constants.w.phiY = 0.0;
constants.w.phiZ = 0.0;
constants.w.aPhiX = 0.0;
constants.w.aPhiY = 0.0;
constants.w.aPhiZ = 0.0;
constants.p.phiO = 1E5;
constants.p.phiX = 0.2E5;
constants.p.phiY = 0.5E5;
constants.p.phiZ = 0.0;
constants.p.aPhiX = 2.0;
constants.p.aPhiY = 1.0;
constants.p.aPhiZ = 0.0;
PetscErrorCode ierr;
// create the mesh
// setup the ts
DM dm; /* problem definition */
TS ts; /* timestepper */
// initialize petsc and mpi
PetscInitialize(&argc, &argv, NULL, "HELP");
// Create a ts
ierr = TSCreate(PETSC_COMM_WORLD, &ts);CHKERRQ(ierr);
ierr = TSSetProblemType(ts, TS_NONLINEAR);CHKERRQ(ierr);
ierr = TSSetType(ts, TSEULER);CHKERRQ(ierr);
ierr = TSSetExactFinalTime(ts, TS_EXACTFINALTIME_MATCHSTEP);CHKERRQ(ierr);
// Create a mesh
// hard code the problem setup
PetscReal start[] = {0.0, 0.0};
PetscReal end[] = {constants.L, constants.L};
PetscInt nx[] = {4, 4};
DMBoundaryType bcType[] = {DM_BOUNDARY_NONE, DM_BOUNDARY_NONE};
ierr = DMPlexCreateBoxMesh(PETSC_COMM_WORLD, constants.dim, PETSC_FALSE, nx, start, end, bcType, PETSC_TRUE, &dm);CHKERRQ(ierr);
// Setup the flow data
FlowData flowData; /* store some of the flow data*/
ierr = FlowCreate(&flowData);CHKERRQ(ierr);
// Combine the flow data
ProblemSetup problemSetup;
problemSetup.flowData = flowData;
problemSetup.constants = constants;
//Setup
CompressibleFlow_SetupDiscretization(flowData, &dm);
// Add in the flow parameters
PetscScalar params[TOTAL_COMPRESSIBLE_FLOW_PARAMETERS];
params[CFL] = 0.5;
params[GAMMA] = constants.gamma;
// set up the finite volume fluxes
CompressibleFlow_StartProblemSetup(flowData, TOTAL_COMPRESSIBLE_FLOW_PARAMETERS, params);
DMView(flowData->dm, PETSC_VIEWER_STDERR_SELF);
// Add in any boundary conditions
PetscDS prob;
ierr = DMGetDS(flowData->dm, &prob);
CHKERRABORT(PETSC_COMM_WORLD, ierr);
const PetscInt idsLeft[]= {1, 2, 3, 4};
ierr = PetscDSAddBoundary(prob, DM_BC_NATURAL_RIEMANN, "wall left", "Face Sets", 0, 0, NULL, (void (*)(void))PhysicsBoundary_Euler, NULL, 4, idsLeft, &constants);CHKERRQ(ierr);
// Complete the problem setup
ierr = CompressibleFlow_CompleteProblemSetup(flowData, ts);
CHKERRABORT(PETSC_COMM_WORLD, ierr);
// Override the flow calc for now
ierr = DMTSSetRHSFunctionLocal(flowData->dm, ComputeRHSWithSourceTerms, &problemSetup);CHKERRQ(ierr);
// Name the flow field
ierr = PetscObjectSetName(((PetscObject)flowData->flowField), "Numerical Solution");
CHKERRABORT(PETSC_COMM_WORLD, ierr);
// Setup the TS
ierr = TSSetFromOptions(ts);
CHKERRABORT(PETSC_COMM_WORLD, ierr);
ierr = TSMonitorSet(ts, MonitorError, &constants, NULL);CHKERRQ(ierr);
CHKERRABORT(PETSC_COMM_WORLD, ierr);
ierr = TSSetMaxTime(ts, 0.01);CHKERRQ(ierr);
// set the initial conditions
PetscErrorCode (*func[2]) (PetscInt dim, PetscReal time, const PetscReal x[], PetscInt Nf, PetscScalar *u, void *ctx) = {EulerExact};
void* ctxs[1] ={&constants};
ierr = DMProjectFunction(flowData->dm,0.0,func,ctxs,INSERT_ALL_VALUES,flowData->flowField);CHKERRQ(ierr);
// for the mms, add the exact solution
ierr = PetscDSSetExactSolution(prob, 0, EulerExact, &constants);CHKERRQ(ierr);
ierr = PetscDSSetExactSolutionTimeDerivative(prob, 0, EulerExactTimeDerivative, &constants);CHKERRQ(ierr);
// Output the mesh
ierr = DMViewFromOptions(dm, NULL, "-dm_view");CHKERRQ(ierr);
TSSetMaxSteps(ts, 1);
ierr = TSSolve(ts,flowData->flowField);CHKERRQ(ierr);
// Check the current residual
PetscReal l2Residual[4];
PetscReal infResidual[4];
// Only take the residual over the central 1/3
PetscReal resStart[2] = {1.0/3.0, 1.0/3.0};
PetscReal resEnd[2] = {2.0/3.0, 2.0/3.0};
ierr = ComputeRHS(ts, flowData->dm, 0.0, flowData->flowField, 4, l2Residual, infResidual, resStart, resEnd);CHKERRQ(ierr);
ierr = PetscPrintf(PETSC_COMM_WORLD, "\tL_2 Residual: [%2.3g, %2.3g, %2.3g, %2.3g]\n", (double) l2Residual[0], (double) l2Residual[1], (double) l2Residual[2], (double) l2Residual[3]);CHKERRQ(ierr);
ierr = PetscPrintf(PETSC_COMM_WORLD, "\tL_Inf Residual: [%2.3g, %2.3g, %2.3g, %2.3g]\n", (double) infResidual[0], (double) infResidual[1], (double) infResidual[2], (double) infResidual[3]);CHKERRQ(ierr);
PetscReal time = 0.0;
// {
// Vec sol;
// VecDuplicate(flowData->flowField, &sol);
// VecCopy(flowData->flowField, sol);
//
// SNES snes;
// ierr = TSGetSNES(ts, &snes);CHKERRQ(ierr);
// ierr = DMSNESCheckDiscretization(snes, flowData->dm, time, sol, -1.0, NULL);CHKERRQ(ierr);
//
// Vec u_t;
// ierr = DMGetGlobalVector(flowData->dm, &u_t);CHKERRQ(ierr);
// ierr = DMTSCheckResidual(ts, flowData->dm, time, sol, u_t, -1.0, NULL);CHKERRQ(ierr);
// ierr = DMRestoreGlobalVector(flowData->dm, &u_t);CHKERRQ(ierr);
//
// VecDestroy(&sol);
// }
// {
// Vec sol;
// VecDuplicate(flowData->flowField, &sol);
// VecCopy(flowData->flowField, sol);
//
// SNES snes;
// ierr = TSGetSNES(ts, &snes);CHKERRQ(ierr);
// ierr = DMSNESCheckDiscretization(snes, flowData->dm, time, sol, -1.0, NULL);CHKERRQ(ierr);
//
// Vec u_t;
// ierr = DMGetGlobalVector(flowData->dm, &u_t);CHKERRQ(ierr);
// ierr = DMTSCheckResidual(ts, flowData->dm, time, sol, u_t, -1.0, NULL);CHKERRQ(ierr);
// ierr = DMRestoreGlobalVector(flowData->dm, &u_t);CHKERRQ(ierr);
//
// VecDestroy(&sol);
// }
return PetscFinalize();
} | {
"alphanum_fraction": 0.5167544497,
"avg_line_length": 54.113022113,
"ext": "c",
"hexsha": "70551590619ff2c38b05f12f08d7f3c08f7e073d",
"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": "1ef7ca77b447a07fdd14d1e2e902abe3e281b651",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "mmcgurn/MattFlowCases",
"max_forks_repo_path": "euler2DMMS.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "1ef7ca77b447a07fdd14d1e2e902abe3e281b651",
"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": "mmcgurn/MattFlowCases",
"max_issues_repo_path": "euler2DMMS.c",
"max_line_length": 612,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "1ef7ca77b447a07fdd14d1e2e902abe3e281b651",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "mmcgurn/MattFlowCases",
"max_stars_repo_path": "euler2DMMS.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 15399,
"size": 44048
} |
#include <gsl/gsl_sf_bessel.h>
#include "ccl.h"
#include "ctest.h"
#include "ccl_params.h"
#include "ccl_core.h"
CTEST(spacing_tests, linear_spacing_simple) {
double * m = ccl_linear_spacing(0.0, 1.0, 5);
ASSERT_NOT_NULL(m);
ASSERT_DBL_NEAR_TOL(0.0, m[0], 1e-10);
ASSERT_DBL_NEAR_TOL(0.25, m[1], 1e-10);
ASSERT_DBL_NEAR_TOL(0.5, m[2], 1e-10);
ASSERT_DBL_NEAR_TOL(0.75, m[3], 1e-10);
ASSERT_DBL_NEAR_TOL(1.0, m[4], 1e-10);
free(m);
}
CTEST(spacing_tests, log_spacing_simple) {
double * m = ccl_log_spacing(1.0, 16.0, 5);
ASSERT_NOT_NULL(m);
ASSERT_DBL_NEAR_TOL(1.0, m[0], 1e-10);
ASSERT_DBL_NEAR_TOL(2.0, m[1], 1e-10);
ASSERT_DBL_NEAR_TOL(4.0, m[2], 1e-10);
ASSERT_DBL_NEAR_TOL(8.0, m[3], 1e-10);
ASSERT_DBL_NEAR_TOL(16.0, m[4], 1e-10);
free(m);
}
CTEST(spacing_tests, linlog_spacing_simple) {
double * m = ccl_linlog_spacing(1.0, 16.0, 32.0, 5, 9);
ASSERT_NOT_NULL(m);
ASSERT_DBL_NEAR_TOL(1.0, m[0], 1e-10);
ASSERT_DBL_NEAR_TOL(2.0, m[1], 1e-10);
ASSERT_DBL_NEAR_TOL(4.0, m[2], 1e-10);
ASSERT_DBL_NEAR_TOL(8.0, m[3], 1e-10);
ASSERT_DBL_NEAR_TOL(16.0, m[4], 1e-10);
ASSERT_DBL_NEAR_TOL(18.0, m[5], 1e-10);
ASSERT_DBL_NEAR_TOL(20.0, m[6], 1e-10);
ASSERT_DBL_NEAR_TOL(22.0, m[7], 1e-10);
ASSERT_DBL_NEAR_TOL(24.0, m[8], 1e-10);
ASSERT_DBL_NEAR_TOL(26.0, m[9], 1e-10);
ASSERT_DBL_NEAR_TOL(28.0, m[10], 1e-10);
ASSERT_DBL_NEAR_TOL(30.0, m[11], 1e-10);
ASSERT_DBL_NEAR_TOL(32.0, m[12], 1e-10);
free(m);
}
CTEST(spherical_bessel_tests, compare_gsl) {
int l, i;
double xmin = 0.0;
double xmax = 10.0;
int Nx = 10000;
double x, dx;
dx = (xmax - xmin) / (Nx - 1);
for (l=0; l < 15; ++l) {
for (i=0; i < Nx; ++i) {
x = dx * i + xmin;
ASSERT_DBL_NEAR_TOL(
ccl_j_bessel(l, x),
gsl_sf_bessel_jl(l, x),
1e-4);
}
}
}
| {
"alphanum_fraction": 0.6379027854,
"avg_line_length": 27.328358209,
"ext": "c",
"hexsha": "4e2b24fb2f877edb3546912fb7e5dc6528a878c5",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "1cdc4ecb8ae6fb23806540b39799cc3317473e71",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "Russell-Jones-OxPhys/CCL",
"max_forks_repo_path": "tests/ccl_test_utils.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "1cdc4ecb8ae6fb23806540b39799cc3317473e71",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "Russell-Jones-OxPhys/CCL",
"max_issues_repo_path": "tests/ccl_test_utils.c",
"max_line_length": 57,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "1cdc4ecb8ae6fb23806540b39799cc3317473e71",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "Russell-Jones-OxPhys/CCL",
"max_stars_repo_path": "tests/ccl_test_utils.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 831,
"size": 1831
} |
/**
* This file is part of the "libterminal" project
* Copyright (c) 2019-2020 Christian Parpart <christian@parpart.family>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <terminal/GraphicsAttributes.h>
#include <terminal/primitives.h>
#include <crispy/Comparison.h>
#include <crispy/assert.h>
#include <gsl/span>
#include <gsl/span_ext>
#include <iterator>
#include <sstream>
#include <string>
#include <vector>
namespace terminal
{
enum class LineFlags : uint8_t
{
None = 0x0000,
Wrappable = 0x0001,
Wrapped = 0x0002,
Marked = 0x0004,
// TODO: DoubleWidth = 0x0010,
// TODO: DoubleHeight = 0x0020,
};
template <typename, bool>
struct OptionalProperty;
template <typename T>
struct OptionalProperty<T, false>
{
};
template <typename T>
struct OptionalProperty<T, true>
{
T value;
};
struct SimpleLineBuffer
{
GraphicsAttributes attributes;
std::string text; // TODO: Try std::string_view later to avoid scattered copies.
ColumnCount width; // page display width
};
template <typename Cell>
using InflatedLineBuffer = std::vector<Cell>;
template <typename Cell>
InflatedLineBuffer<Cell> inflate(SimpleLineBuffer const& input);
template <typename Cell>
using LineStorage = std::variant<SimpleLineBuffer, InflatedLineBuffer<Cell>>;
/**
* Line<Cell> API.
*
* TODO: Use custom allocator for ensuring cache locality of Cells to sibling lines.
* TODO: Make the line optimization work.
*/
template <typename Cell, bool Optimize = false>
class Line
{
public:
Line() = default;
Line(Line const&) = default;
Line(Line&&) noexcept = default;
Line& operator=(Line const&) = default;
Line& operator=(Line&&) noexcept = default;
using InflatedBuffer = InflatedLineBuffer<Cell>;
using Storage = LineStorage<Cell>;
using value_type = Cell;
using iterator = typename InflatedBuffer::iterator;
using reverse_iterator = typename InflatedBuffer::reverse_iterator;
using const_iterator = typename InflatedBuffer::const_iterator;
Line(ColumnCount _width, LineFlags _flags, Cell _template = {}):
buffer_(_width.as<size_t>(), _template /*, _allocator*/), flags_ { static_cast<unsigned>(_flags) }
{
}
Line(ColumnCount _width, InflatedBuffer _buffer, LineFlags _flags):
buffer_ { std::move(_buffer) }, flags_ { static_cast<unsigned>(_flags) }
{
buffer_.resize(unbox<size_t>(_width));
}
Line(InflatedBuffer _buffer, LineFlags _flags):
buffer_ { std::move(_buffer) }, flags_ { static_cast<unsigned>(_flags) }
{
}
constexpr static inline bool ColumnOptimized = Optimize;
// This is experimental (aka. buggy) and going to be replaced with another optimization idea soon.
//#define LINE_AVOID_CELL_RESET 1
void reset(LineFlags _flags,
GraphicsAttributes _attributes) noexcept // TODO: optimize by having no need to O(n) iterate
// through all buffer cells.
{
flags_ = static_cast<unsigned>(_flags);
// if constexpr (ColumnOptimized)
// {
// #if !defined(LINE_AVOID_CELL_RESET)
// if (buffer_.back().backgroundColor() != _attributes.backgroundColor)
// // TODO: also styles and UL color
// markUsedFirst(ColumnCount::cast_from(buffer_.size()));
//
// for (auto i = 0; i < *columnsUsed(); ++i)
// buffer_[i].reset(_attributes);
// #endif
// markUsedFirst(ColumnCount(0));
// }
// else
{
for (Cell& cell: buffer_)
cell.reset(_attributes);
}
}
void markUsedFirst(ColumnCount /*_n*/) noexcept
{
// if constexpr (ColumnOptimized)
// usedColumns_.value = _n;
}
void reset(LineFlags _flags,
GraphicsAttributes const& _attributes,
char32_t _codepoint,
uint8_t _width) noexcept
{
flags_ = static_cast<unsigned>(_flags);
markUsedFirst(size());
for (Cell& cell: buffer_)
{
cell.reset();
cell.write(_attributes, _codepoint, _width);
}
}
/**
* Fills this line with the given content.
*
* @p _start offset into this line of the first charater
* @p _sgr graphics rendition for the line starting at @c _start until the end
* @p _ascii the US-ASCII characters to fill with
*/
void fill(ColumnOffset _start, GraphicsAttributes const& _sgr, std::string_view _ascii)
{
auto& buffer = editable();
assert(unbox<size_t>(_start) + _ascii.size() <= buffer.size());
auto constexpr ASCII_Width = 1;
auto const* s = _ascii.data();
Cell* i = &buffer_[unbox<size_t>(_start)];
Cell* e = i + _ascii.size();
while (i != e)
(i++)->write(_sgr, static_cast<char32_t>(*s++), ASCII_Width);
// if constexpr (ColumnOptimized)
// {
// #if !defined(LINE_AVOID_CELL_RESET)
// auto const e2 = buffer.data() + unbox<long>(columnsUsed());
// while (i != e2)
// (i++)->reset();
// #endif
// usedColumns_.value = boxed_cast<ColumnCount>(_start) + ColumnCount::cast_from(_ascii.size());
// }
// else
{
auto const e2 = buffer.data() + buffer.size();
while (i != e2)
(i++)->reset();
}
}
ColumnCount size() const noexcept { return ColumnCount::cast_from(buffer_.size()); }
ColumnCount columnsUsed() const noexcept
{
// if constexpr (ColumnOptimized)
// return usedColumns_.value;
// else
return size();
}
void resize(ColumnCount _count);
gsl::span<Cell const> trim_blank_right() const noexcept;
gsl::span<Cell const> cells() const noexcept { return buffer_; }
gsl::span<Cell> useRange(ColumnOffset _start, ColumnCount _count) noexcept
{
markUsedFirst(std::max(columnsUsed(), boxed_cast<ColumnCount>(_start) + _count));
#if defined(__FreeBSD__)
auto const bufferSpan = gsl::span(buffer_);
return bufferSpan.subspan(unbox<size_t>(_start), unbox<size_t>(_count));
#else
// NOTE: On FreeBSD the line below does not compile.
return gsl::span(buffer_).subspan(unbox<size_t>(_start), unbox<size_t>(_count));
#endif
}
iterator begin() noexcept { return buffer_.begin(); }
iterator end() noexcept { return std::next(std::begin(buffer_), unbox<int>(columnsUsed())); }
const_iterator begin() const noexcept { return buffer_.begin(); }
const_iterator end() const noexcept { return std::next(buffer_.begin(), unbox<int>(columnsUsed())); }
reverse_iterator rbegin() noexcept { return buffer_.rbegin(); }
reverse_iterator rend() noexcept { return buffer_.rend(); }
Cell& front() noexcept { return buffer_.front(); }
Cell const& front() const noexcept { return buffer_.front(); }
Cell& back() noexcept { return *std::next(buffer_.begin(), unbox<int>(columnsUsed() - 1)); }
Cell const& back() const noexcept { return *std::next(buffer_.begin(), unbox<int>(columnsUsed() - 1)); }
Cell& useCellAt(ColumnOffset _column) noexcept
{
Require(ColumnOffset(0) <= _column);
Require(_column <= ColumnOffset::cast_from(buffer_.size())); // Allow off-by-one for sentinel.
return editable()[unbox<size_t>(_column)];
}
Cell const& at(ColumnOffset _column) const noexcept
{
Require(ColumnOffset(0) <= _column);
Require(_column <= ColumnOffset::cast_from(buffer_.size())); // Allow off-by-one for sentinel.
return buffer_[unbox<size_t>(_column)];
}
LineFlags flags() const noexcept { return static_cast<LineFlags>(flags_); }
bool marked() const noexcept { return isFlagEnabled(LineFlags::Marked); }
void setMarked(bool _enable) { setFlag(LineFlags::Marked, _enable); }
bool wrapped() const noexcept { return isFlagEnabled(LineFlags::Wrapped); }
void setWrapped(bool _enable) { setFlag(LineFlags::Wrapped, _enable); }
bool wrappable() const noexcept { return isFlagEnabled(LineFlags::Wrappable); }
void setWrappable(bool _enable) { setFlag(LineFlags::Wrappable, _enable); }
LineFlags wrappableFlag() const noexcept { return wrappable() ? LineFlags::Wrappable : LineFlags::None; }
LineFlags wrappedFlag() const noexcept { return marked() ? LineFlags::Wrapped : LineFlags::None; }
LineFlags markedFlag() const noexcept { return marked() ? LineFlags::Marked : LineFlags::None; }
LineFlags inheritableFlags() const noexcept
{
auto constexpr Inheritables = unsigned(LineFlags::Wrappable) | unsigned(LineFlags::Marked);
return static_cast<LineFlags>(flags_ & Inheritables);
}
void setFlag(LineFlags _flag, bool _enable) noexcept
{
if (_enable)
flags_ |= static_cast<unsigned>(_flag);
else
flags_ &= ~static_cast<unsigned>(_flag);
}
bool isFlagEnabled(LineFlags _flag) const noexcept
{
return (flags_ & static_cast<unsigned>(_flag)) != 0;
}
InflatedBuffer reflow(ColumnCount _newColumnCount);
std::string toUtf8() const;
std::string toUtf8Trimmed() const;
// Returns a reference to this mutable grid-line buffer.
//
// If this line has been stored in an optimized state, then
// the line will be first unpacked into a vector of grid cells.
InflatedBuffer& editable();
private:
InflatedBuffer buffer_;
Storage storage_;
unsigned flags_ = 0;
// OptionalProperty<ColumnCount, ColumnOptimized> usedColumns_;
};
constexpr LineFlags operator|(LineFlags a, LineFlags b) noexcept
{
return LineFlags(unsigned(a) | unsigned(b));
}
constexpr LineFlags operator~(LineFlags a) noexcept
{
return LineFlags(~unsigned(a));
}
constexpr LineFlags operator&(LineFlags a, LineFlags b) noexcept
{
return LineFlags(unsigned(a) & unsigned(b));
}
template <typename Cell, bool Optimize>
inline typename Line<Cell, Optimize>::InflatedBuffer& Line<Cell, Optimize>::editable()
{
// TODO: when we impement the line text buffer optimization,
// then this is the place where we want to *promote* a possibly
// optimized text buffer to a full grid line buffer.
#if 0
if (std::holds_alternative<SimpleLineBuffer>(storage_))
storage_ = inflate<Cell>(std::get<SimpleLineBuffer>(storage_));
return std::get<InflatedBuffer>(storage_);
#else
return buffer_;
#endif
}
} // namespace terminal
namespace fmt // {{{
{
template <>
struct formatter<terminal::LineFlags>
{
template <typename ParseContext>
auto parse(ParseContext& ctx)
{
return ctx.begin();
}
template <typename FormatContext>
auto format(const terminal::LineFlags _flags, FormatContext& ctx) const
{
static const std::array<std::pair<terminal::LineFlags, std::string_view>, 3> nameMap = {
std::pair { terminal::LineFlags::Wrappable, std::string_view("Wrappable") },
std::pair { terminal::LineFlags::Wrapped, std::string_view("Wrapped") },
std::pair { terminal::LineFlags::Marked, std::string_view("Marked") },
};
std::string s;
for (auto const& mapping: nameMap)
{
if ((mapping.first & _flags) != terminal::LineFlags::None)
{
if (!s.empty())
s += ",";
s += mapping.second;
}
}
return format_to(ctx.out(), s);
}
};
} // namespace fmt
| {
"alphanum_fraction": 0.6426801058,
"avg_line_length": 32.6253369272,
"ext": "h",
"hexsha": "500ac343ec67d82c40987990553549c8c38de395",
"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": "f0004230be75bb99fc899851a216f41d1dca2a81",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "sebastianrakel/contour",
"max_forks_repo_path": "src/terminal/Line.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "f0004230be75bb99fc899851a216f41d1dca2a81",
"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": "sebastianrakel/contour",
"max_issues_repo_path": "src/terminal/Line.h",
"max_line_length": 109,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "f0004230be75bb99fc899851a216f41d1dca2a81",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "sebastianrakel/contour",
"max_stars_repo_path": "src/terminal/Line.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 2877,
"size": 12104
} |
#ifndef _DSGLD_LDA_MODEL_H__
#define _DSGLD_LDA_MODEL_H__
#include <El.hpp>
#include <gsl/gsl_rng.h>
#include "sgld_model.h"
using std::string;
using std::vector;
namespace dsgld {
class LDAModel : public SGLDModel<double, int> {
public:
LDAModel(
const El::Matrix<int>& X,
const int K,
const double alpha,
const double beta);
~LDAModel() {};
El::Matrix<double> sgldEstimate(const El::Matrix<double>& theta) override;
El::Matrix<double> nablaLogPrior(const El::Matrix<double>& theta) const override;
void writePerplexities(const string& filename);
int NumGibbsSteps() const;
LDAModel* NumGibbsSteps(const int);
protected:
void gibbsSample(
const El::Matrix<int>& doc,
const El::Matrix<double>& theta,
El::Matrix<int>& index_to_topic,
El::Matrix<int>& topic_counts) const;
double estimatePerplexity(
const El::Matrix<double>& theta,
const El::Matrix<double>& theta_sum_over_w,
const int num_words_in_doc,
const El::Matrix<int>& topic_counts) const;
private:
const double alpha_;
const double beta_;
const int W;
const int K;
int numGibbsSteps_;
vector<double> perplexities_;
const gsl_rng* rng;
};
} // namespace dsgld
#endif // _DSGLD_LDA_MODEL_H__
| {
"alphanum_fraction": 0.690625,
"avg_line_length": 20.9836065574,
"ext": "h",
"hexsha": "4302e04af7637837aad70ef5430057bec248a87a",
"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": "2442178679e8ec29ac8532205dd9640f546f87fc",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "feynmanliang/travelling-cluster-chain",
"max_forks_repo_path": "lda_model.h",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "2442178679e8ec29ac8532205dd9640f546f87fc",
"max_issues_repo_issues_event_max_datetime": "2018-04-20T05:06:53.000Z",
"max_issues_repo_issues_event_min_datetime": "2018-04-20T05:06:53.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "feynmanliang/travelling-cluster-chain",
"max_issues_repo_path": "lda_model.h",
"max_line_length": 83,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "2442178679e8ec29ac8532205dd9640f546f87fc",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "feynmanliang/travelling-cluster-chain",
"max_stars_repo_path": "lda_model.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 344,
"size": 1280
} |
/* spgetset.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_errno.h>
#include <gsl/gsl_spmatrix.h>
#include "avl.c"
static void *tree_find(const gsl_spmatrix *m, const size_t i, const size_t j);
double
gsl_spmatrix_get(const gsl_spmatrix *m, const size_t i, const size_t j)
{
if (i >= m->size1)
{
GSL_ERROR_VAL("first index out of range", GSL_EINVAL, 0.0);
}
else if (j >= m->size2)
{
GSL_ERROR_VAL("second index out of range", GSL_EINVAL, 0.0);
}
else if (m->nz == 0)
{
/* no non-zero elements added to matrix */
return (0.0);
}
else
{
if (GSL_SPMATRIX_ISTRIPLET(m))
{
/* traverse binary tree to search for (i,j) element */
void *ptr = tree_find(m, i, j);
double x = ptr ? *(double *) ptr : 0.0;
return x;
}
else if (GSL_SPMATRIX_ISCCS(m))
{
const size_t *mi = m->i;
const size_t *mp = m->p;
size_t p;
/* loop over column j and search for row index i */
for (p = mp[j]; p < mp[j + 1]; ++p)
{
if (mi[p] == i)
return m->data[p];
}
}
else if (GSL_SPMATRIX_ISCRS(m))
{
const size_t *mj = m->i;
const size_t *mp = m->p;
size_t p;
/* loop over row i and search for column index j */
for (p = mp[i]; p < mp[i + 1]; ++p)
{
if (mj[p] == j)
return m->data[p];
}
}
else
{
GSL_ERROR_VAL("unknown sparse matrix type", GSL_EINVAL, 0.0);
}
/* element not found; return 0 */
return 0.0;
}
} /* gsl_spmatrix_get() */
/*
gsl_spmatrix_set()
Add an element to a matrix in triplet form
Inputs: m - spmatrix
i - row index
j - column index
x - matrix value
*/
int
gsl_spmatrix_set(gsl_spmatrix *m, const size_t i, const size_t j,
const double x)
{
if (!GSL_SPMATRIX_ISTRIPLET(m))
{
GSL_ERROR("matrix not in triplet representation", GSL_EINVAL);
}
else if (x == 0.0)
{
/* traverse binary tree to search for (i,j) element */
void *ptr = tree_find(m, i, j);
/*
* just set the data element to 0; it would be easy to
* delete the node from the tree with avl_delete(), but
* we'd also have to delete it from the data arrays which
* is less simple
*/
if (ptr != NULL)
*(double *) ptr = 0.0;
return GSL_SUCCESS;
}
else
{
int s = GSL_SUCCESS;
void *ptr;
/* check if matrix needs to be realloced */
if (m->nz >= m->nzmax)
{
s = gsl_spmatrix_realloc(2 * m->nzmax, m);
if (s)
return s;
}
/* store the triplet (i, j, x) */
m->i[m->nz] = i;
m->p[m->nz] = j;
m->data[m->nz] = x;
ptr = avl_insert(m->tree_data->tree, &m->data[m->nz]);
if (ptr != NULL)
{
/* found duplicate entry (i,j), replace with new x */
*((double *) ptr) = x;
}
else
{
/* no duplicate (i,j) found, update indices as needed */
/* increase matrix dimensions if needed */
m->size1 = GSL_MAX(m->size1, i + 1);
m->size2 = GSL_MAX(m->size2, j + 1);
++(m->nz);
}
return s;
}
} /* gsl_spmatrix_set() */
double *
gsl_spmatrix_ptr(gsl_spmatrix *m, const size_t i, const size_t j)
{
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);
}
else
{
if (GSL_SPMATRIX_ISTRIPLET(m))
{
/* traverse binary tree to search for (i,j) element */
void *ptr = tree_find(m, i, j);
return (double *) ptr;
}
else if (GSL_SPMATRIX_ISCCS(m))
{
const size_t *mi = m->i;
const size_t *mp = m->p;
size_t p;
/* loop over column j and search for row index i */
for (p = mp[j]; p < mp[j + 1]; ++p)
{
if (mi[p] == i)
return &(m->data[p]);
}
}
else if (GSL_SPMATRIX_ISCRS(m))
{
const size_t *mj = m->i;
const size_t *mp = m->p;
size_t p;
/* loop over row i and search for column index j */
for (p = mp[i]; p < mp[i + 1]; ++p)
{
if (mj[p] == j)
return &(m->data[p]);
}
}
else
{
GSL_ERROR_NULL("unknown sparse matrix type", GSL_EINVAL);
}
/* element not found; return 0 */
return NULL;
}
} /* gsl_spmatrix_ptr() */
/*
tree_find()
Find node in tree corresponding to matrix entry (i,j). Adapted
from avl_find()
Inputs: m - spmatrix
i - row index
j - column index
Return: pointer to tree node data if found, NULL if not found
*/
static void *
tree_find(const gsl_spmatrix *m, const size_t i, const size_t j)
{
const struct avl_table *tree = (struct avl_table *) m->tree_data->tree;
const struct avl_node *p;
for (p = tree->avl_root; p != NULL; )
{
size_t n = (double *) p->avl_data - m->data;
size_t pi = m->i[n];
size_t pj = m->p[n];
int cmp = gsl_spmatrix_compare_idx(i, j, pi, pj);
if (cmp < 0)
p = p->avl_link[0];
else if (cmp > 0)
p = p->avl_link[1];
else /* |cmp == 0| */
return p->avl_data;
}
return NULL;
} /* tree_find() */
| {
"alphanum_fraction": 0.5265760198,
"avg_line_length": 25.1828793774,
"ext": "c",
"hexsha": "2c5d2ea6d35a29f43cd83064aa298775524a7672",
"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/spgetset.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/spgetset.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/spgetset.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": 1835,
"size": 6472
} |
#pragma once
#include <gsl/span>
#include "aas/aas_math.h"
namespace aas {
struct AnimPlayerStream;
class AnimatedModel;
struct SkelAnim;
struct SkelAnimEvent;
struct SkelBoneState;
class IAnimEventHandler;
class Skeleton;
struct AnimEvent;
class AnimPlayer {
public:
AnimatedModel * ownerAnim;
char field_D;
char field_E;
char field_F;
float weight; // 1.0 = Fully weighted, otherwise weighted with primary anims
float fadingSpeed; // Velocity with which weight is being changed
int eventHandlingDepth;
AnimPlayer * nextRunningAnim;
AnimPlayer * prevRunningAnim;
const SkelAnim * animation;
int streamCount;
AnimPlayerStream * streams[4];
float streamFps[4]; // "frames per drive unit"
int8_t streamVariationIndices[4]; // indices into streamVariationIds
int8_t streamVariationIds[4];
int8_t variationId[4];
float currentTimeEvents;
float currentTime;
float duration;
float frameRate;
float distancePerSecond;
std::vector<AnimEvent> events;
IAnimEventHandler* eventHandler;
public:
AnimPlayer();
~AnimPlayer();
void GetDistPerSec(float* distPerSec);
void GetRotationPerSec(float* rotationPerSec);
void AdvanceEvents(float timeChanged, float distanceChanged, float rotationChanged);
void FadeInOrOut(float timeChanged);
void method6(gsl::span<SkelBoneState> boneStateOut, float timeChanged, float distanceChanged, float rotationChanged);
void SetTime(float time);
float GetCurrentFrame();
float method9();
float method10();
void EnterEventHandling();
void LeaveEventHandling();
int GetEventHandlingDepth();
void Attach(AnimatedModel *owner, int animIdx, IAnimEventHandler *eventHandler);
void Setup2(float a);
private:
void SetEvents(const AnimatedModel *owner, const SkelAnim *anim);
};
AnimPlayerStream * CreateAnimPlayerStream(Skeleton* skeleton);
}
| {
"alphanum_fraction": 0.7639784946,
"avg_line_length": 25.4794520548,
"ext": "h",
"hexsha": "7ffe2196addf9d6b71f7951a4b993e3c86a23f33",
"lang": "C",
"max_forks_count": 25,
"max_forks_repo_forks_event_max_datetime": "2021-11-15T23:14:51.000Z",
"max_forks_repo_forks_event_min_datetime": "2016-02-04T21:19:53.000Z",
"max_forks_repo_head_hexsha": "f0e552289822fea908f16daa379fa568b1bd286d",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "edoipi/TemplePlus",
"max_forks_repo_path": "Infrastructure/src/aas/aas_anim_player.h",
"max_issues_count": 457,
"max_issues_repo_head_hexsha": "f0e552289822fea908f16daa379fa568b1bd286d",
"max_issues_repo_issues_event_max_datetime": "2022-03-31T02:19:10.000Z",
"max_issues_repo_issues_event_min_datetime": "2015-05-01T22:07:45.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "edoipi/TemplePlus",
"max_issues_repo_path": "Infrastructure/src/aas/aas_anim_player.h",
"max_line_length": 119,
"max_stars_count": 69,
"max_stars_repo_head_hexsha": "f0e552289822fea908f16daa379fa568b1bd286d",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "edoipi/TemplePlus",
"max_stars_repo_path": "Infrastructure/src/aas/aas_anim_player.h",
"max_stars_repo_stars_event_max_datetime": "2022-02-15T06:13:04.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-05-05T14:09:25.000Z",
"num_tokens": 463,
"size": 1860
} |
#include <stdio.h>
#include <string.h>
#include <gsl/gsl_eigen.h>
#include <gsl/gsl_linalg.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_vector.h>
#include "chmath.h"
#include "err.h"
static char* me = "chmath";
static double get(const gsl_matrix* m, int i, int j) {
return gsl_matrix_get(m, i, j);
}
int chmath_eig_values(const double A[6], /**/ double VAL[3]) {
enum { XX, XY, XZ, YY, YZ, ZZ };
enum { YX = XY, ZX = XZ, ZY = YZ };
enum { X, Y, Z };
double B[3 * 3];
gsl_matrix_view m;
gsl_vector* val;
gsl_matrix* vec;
gsl_eigen_symmv_workspace* w;
int i, status;
val = gsl_vector_alloc(3);
vec = gsl_matrix_alloc(3, 3);
w = gsl_eigen_symmv_alloc(3);
i = 0;
B[i++] = A[XX];
B[i++] = A[XY];
B[i++] = A[XZ];
B[i++] = A[YX];
B[i++] = A[YY];
B[i++] = A[YZ];
B[i++] = A[ZX];
B[i++] = A[ZY];
B[i++] = A[ZZ];
m = gsl_matrix_view_array(B, 3, 3);
status = gsl_eigen_symmv(&m.matrix, val, vec, w);
if (status != GSL_SUCCESS) ERR(("gsl_eigen_symmv failed"));
gsl_eigen_symmv_sort(val, vec, GSL_EIGEN_SORT_ABS_ASC);
i = 0;
VAL[i] = gsl_vector_get(val, i);
i++;
VAL[i] = gsl_vector_get(val, i);
i++;
VAL[i] = gsl_vector_get(val, i);
gsl_vector_free(val);
gsl_matrix_free(vec);
gsl_eigen_symmv_free(w);
return 0;
}
int chmath_eig_vectors(
const double A[6], /**/ double a[3], double b[3], double c[3]) {
enum { XX, XY, XZ, YY, YZ, ZZ };
enum { YX = XY, ZX = XZ, ZY = YZ };
enum { X, Y, Z };
double B[3 * 3];
gsl_matrix_view m;
gsl_vector* val;
gsl_matrix* vec;
gsl_eigen_symmv_workspace* w;
int i, status;
val = gsl_vector_alloc(3);
vec = gsl_matrix_alloc(3, 3);
w = gsl_eigen_symmv_alloc(3);
i = 0;
B[i++] = A[XX];
B[i++] = A[XY];
B[i++] = A[XZ];
B[i++] = A[YX];
B[i++] = A[YY];
B[i++] = A[YZ];
B[i++] = A[ZX];
B[i++] = A[ZY];
B[i++] = A[ZZ];
m = gsl_matrix_view_array(B, 3, 3);
status = gsl_eigen_symmv(&m.matrix, val, vec, w);
if (status != GSL_SUCCESS) ERR(("gsl_eigen_symmv failed"));
gsl_eigen_symmv_sort(val, vec, GSL_EIGEN_SORT_ABS_ASC);
i = 0;
a[X] = get(vec, X, X);
a[Y] = get(vec, Y, X);
a[Z] = get(vec, Z, X);
b[X] = get(vec, X, Y);
b[Y] = get(vec, Y, Y);
b[Z] = get(vec, Z, Y);
c[X] = get(vec, X, Z);
c[Y] = get(vec, Y, Z);
c[Z] = get(vec, Z, Z);
gsl_vector_free(val);
gsl_matrix_free(vec);
gsl_eigen_symmv_free(w);
return 0;
}
| {
"alphanum_fraction": 0.5760690789,
"avg_line_length": 21.9099099099,
"ext": "c",
"hexsha": "4829610191622a264c53d05a38df981dc07e8333",
"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": "18af982a50e350a8bf6979ae5bd25b2ef4d3792a",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "ChristopherKotthoff/Aphros-with-GraphContraction",
"max_forks_repo_path": "deploy/lib/chmath/main.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "18af982a50e350a8bf6979ae5bd25b2ef4d3792a",
"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": "ChristopherKotthoff/Aphros-with-GraphContraction",
"max_issues_repo_path": "deploy/lib/chmath/main.c",
"max_line_length": 68,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "18af982a50e350a8bf6979ae5bd25b2ef4d3792a",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "ChristopherKotthoff/Aphros-with-GraphContraction",
"max_stars_repo_path": "deploy/lib/chmath/main.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 929,
"size": 2432
} |
#include <math.h>
#include <gmp.h>
#if BLAS_IMPL == openblas
#include <blas/cblas.h>
#else
#include <cblas.h>
#endif
#include "attrib.h"
#include "math.h"
#define CLEANUP \
return err; \
error: \
if (ctx->err == 0) \
strcpy(ctx->err_msg, "Unexpected math."); \
ctx->err = err; \
return err;
#define CHECK(expr) \
if ((err = (expr))) goto error;
VIO_CONST
uint32_t vmaxui(uint32_t a, uint32_t b) {
return a > b ? a : b;
}
#define OP_IMPL(name) \
vio_err_t generic_##name(vio_ctx *ctx, vio_val *a, vio_val *b) { \
vio_err_t err = 0; \
vio_val *va, *vb; \
if (a->what == vv_str || b->what == vv_str || a->what == vv_quot || b->what == vv_quot || \
a->what == vv_tagword || b->what == vv_tagword) { \
err = vio_raise(ctx, VE_WRONG_TYPE, \
"Function '" #name "' expects numeric types or vectors; received '%s' and '%s' operands.", \
vio_val_type_name(a->what), vio_val_type_name(b->what));\
goto error; \
}
#define END_OP(_name) \
CLEANUP \
}
#define GIVEN_VECF \
if (a->what == vv_vecf && b->what == vv_vecf && a->vlen == b->vlen) {
#define DONE_VECF }
#define GIVEN_NUMERIC \
else if (vio_is_numeric(a) && vio_is_numeric(b)) { \
CHECK(vio_coerce(ctx, b, &vb, a->what)) \
if (vb == NULL) { \
CHECK(vio_coerce(ctx, a, &va, b->what)) \
if (va == NULL) { \
err = VE_NUMERIC_CONVERSION_FAIL; \
goto error; \
} \
a = b; \
b = va; \
} \
else \
b = vb; \
switch (a->what) {
#define DONE_NUMERIC \
default: err = VE_WRONG_TYPE; goto error; \
} \
}
#define STANDARD_NUMERIC(op, fop) \
GIVEN_NUMERIC \
case vv_int: CHECK(vio_push_int(ctx, b->i32 op a->i32)) break; \
case vv_float: CHECK(vio_push_float(ctx, b->f32 op a->f32)) break; \
case vv_num: { mpf_t c; mpf_init(c); mpf_##fop(c, b->n, a->n); CHECK(vio_push_num(ctx, c)) break; } \
DONE_NUMERIC
#define GIVEN_VEC \
else CHECK(vio_coerce(ctx, a, &va, vv_vec)) \
else CHECK(vio_coerce(ctx, b, &vb, vv_vec)) \
else if (va && vb) { \
#define DONE_VEC }
#define AUTO_VECTORIZE(name) \
GIVEN_VEC \
uint32_t maxl = vmaxui(va->vlen, vb->vlen); \
for (uint32_t i = 0; i < maxl; ++i) \
CHECK(generic_##name(ctx, va->vv[i % va->vlen], vb->vv[i % vb->vlen])) \
CHECK(vio_push_vec(ctx, maxl)) \
DONE_VEC
OP_IMPL(add)
GIVEN_VECF
cblas_daxpy(b->vlen, 1, a->vf32, 1, b->vf32, 1);
CHECK(vio_push_vecf32(ctx, b->vlen, b->vf32))
DONE_VECF
STANDARD_NUMERIC(+, add)
AUTO_VECTORIZE(add)
END_OP(add)
OP_IMPL(sub)
GIVEN_VECF
cblas_daxpy(b->vlen, -1.0, a->vf32, 1, b->vf32, 1);
CHECK(vio_push_vecf32(ctx, b->vlen, b->vf32))
DONE_VECF
STANDARD_NUMERIC(-, sub)
AUTO_VECTORIZE(sub)
END_OP(sub)
OP_IMPL(mul)
if (b->what == vv_vecf && a->what == vv_float) {
va = a;
a = b;
b = va;
}
if (a->what == vv_vecf && b->what == vv_float) {
cblas_dscal(a->vlen, b->f32, a->vf32, 1);
CHECK(vio_push_vecf32(ctx, a->vlen, a->vf32))
}
else GIVEN_VECF
for (uint32_t i = 0; i < a->vlen; ++i)
a->vf32[i] *= b->vf32[i];
CHECK(vio_push_vecf32(ctx, a->vlen, a->vf32))
DONE_VECF
STANDARD_NUMERIC(*, mul)
AUTO_VECTORIZE(mul)
END_OP(mul)
OP_IMPL(div)
if (b->what == vv_vecf && a->what == vv_float) {
va = a;
a = b;
b = va;
}
if (a->what == vv_vecf && b->what == vv_float) {
cblas_dscal(a->vlen, 1.0 / b->f32, a->vf32, 1);
CHECK(vio_push_vecf32(ctx, a->vlen, a->vf32))
}
else GIVEN_VECF
for (uint32_t i = 0; i < a->vlen; ++i)
a->vf32[i] /= b->vf32[i];
CHECK(vio_push_vecf32(ctx, a->vlen, a->vf32))
DONE_VECF
STANDARD_NUMERIC(/, div)
AUTO_VECTORIZE(div)
END_OP(div)
#define BIN_OP(name) \
vio_err_t vio_##name(vio_ctx *ctx) { \
vio_err_t err = 0; \
VIO__ENSURE_ATLEAST(2) \
\
vio_val *a = ctx->stack[--ctx->sp], *b; \
b = ctx->stack[--ctx->sp]; \
err = generic_##name(ctx, a, b); \
\
CLEANUP \
}
BIN_OP(add)
BIN_OP(sub)
BIN_OP(mul)
BIN_OP(div)
#define UN_IMPL(f) \
vio_err_t vio_##f(vio_ctx *ctx) { \
vio_err_t err = 0; \
vio_float x, y; \
VIO__CHECK(vio_pop_float(ctx, &x)); \
y = f(x); \
VIO__CHECK(vio_push_float(ctx, y)); \
return 0; \
error: \
return err; \
}
LIST_MATH_UNARY(UN_IMPL)
| {
"alphanum_fraction": 0.5332909245,
"avg_line_length": 26.6440677966,
"ext": "c",
"hexsha": "699dfa5a8c09e0eda53f26179b4ae85906ab4824",
"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": "1c1bb0e27a27d0e65e92ea8ae8badb44e877047f",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "alpha123/vio",
"max_forks_repo_path": "src/math.c",
"max_issues_count": 6,
"max_issues_repo_head_hexsha": "1c1bb0e27a27d0e65e92ea8ae8badb44e877047f",
"max_issues_repo_issues_event_max_datetime": "2017-07-17T12:09:20.000Z",
"max_issues_repo_issues_event_min_datetime": "2015-12-15T18:31:47.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "alpha123/vio",
"max_issues_repo_path": "src/math.c",
"max_line_length": 120,
"max_stars_count": 16,
"max_stars_repo_head_hexsha": "1c1bb0e27a27d0e65e92ea8ae8badb44e877047f",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "alpha123/vio",
"max_stars_repo_path": "src/math.c",
"max_stars_repo_stars_event_max_datetime": "2021-01-05T18:20:21.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-11-19T04:36:31.000Z",
"num_tokens": 1541,
"size": 4716
} |
// mimetic_bayes program
// Alessandro Casalino, University of Trento
// For licence informations, see the Github repository license
//
// Compile with: gcc-8 -O2 -DHAVE_INLINE -DGSL_RANGE_CHECK_OFF Ligo_abc_gsl.c -o Ligo_abc_gsl.o -lgsl -lgslcblas -fopenmp
// Run with: ./Ligo_abc_gsl.o
// Test running time: time ./Ligo_abc_gsl.o
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_blas.h>
#include <gsl/gsl_linalg.h>
#include <sys/time.h>
#include <omp.h>
// PROGRAM VARIABLES
// Variables for parallelization with OpenMP
// Info on OpenMP: https://bisqwit.iki.fi/story/howto/openmp/#Syntax
// Enable OpenMP
int OPENMP = 1;
// Number of threads used by OpenMP (can't be bigger than the number of threads available on your computer)
// If 0, the number of threads available on the computer is used
int OMP_THREAD_NUM = 0;
// Number of Chains (for higher efficiency, consider N_CHAIN as a multiple of OMP_THREAD_NUM)
int N_CHAINS = 8;
// Make the Lag test (can make the computation very long!)
int LAG_TEST = 0;
// Ratio of lag function computed with respect to the total number of points in every chain
// Smaller values make the computation faster
double LAG_TEST_STOP_RATIO = 0.001;
// Write (in the terminal) debug informations and informations that might be considered in order to improve results
int DEBUG = 1;
// Write .csv files
#define CSV 1
// Write covariant matrix in .csv file
int CSV_COV = 1;
// Write correlation matrix (Pearson coefficients) in .csv file
int CSV_CORR = 1;
// NUMERICAL VARIABLES
// Chain evaluation dimension (every step found from proposal distribution is multiplied by this quantity)
// This is also used to define the covariance matrix for the Gaussian proposal
double SPEED[] = {1e-1,5e-16,4e-16};
// Mean value for Gaussian proposal (PROPOSAL=1)
double MEAN_P1[] = {0.,0.,0.};
// Number of points in every chain
int N = 1e6;
// PHYSICAL VARIABLES
// Choose to use the constraint on Ct2 in the prior
int CT2_CONSTR = 1;
// Choose the proposal distribution
int PROPOSAL = 1;
// Note that the constraints are defined in rho(pos)
// PROGRAM
typedef struct chain {
gsl_vector * mean;
gsl_matrix * covariance;
double acceptance_ratio;
} chain_res;
inline double cT2 (gsl_vector * pos) {
double a=gsl_vector_get(pos,0), b=gsl_vector_get(pos,1), c=gsl_vector_get(pos,2);
return (2.0-2.0*a)/(2.0-2.0*a+b);
}
inline double cS2 (gsl_vector * pos) {
double a=gsl_vector_get(pos,0), b=gsl_vector_get(pos,1), c=gsl_vector_get(pos,2);
return (b-c)*(2.0*a-2.0)/(2.0*a-b-2.0)/(4.0-4.0*a-b+3.0*c);
}
inline double MPl2 (gsl_vector * pos) {
double a=gsl_vector_get(pos,0), b=gsl_vector_get(pos,1), c=gsl_vector_get(pos,2);
return 4.0-4.0*a-b+3.0*c;
}
inline double rho(gsl_vector * pos){
double a=gsl_vector_get(pos,0), b=gsl_vector_get(pos,1), c=gsl_vector_get(pos,2);
// Value of the sound speed squared
double cs2=cS2(pos);
// Value of the tensor speed squared
double ct2=cT2(pos);
// Value of the Planck mass rescaling factor
double Mpl2=MPl2(pos);
// Value of the argument of the Gaussian in the Likelihood
double delta=fabs(sqrt(ct2)-1.0);
// This is the experimental sigma on cT2
double sigma = 4.5e-16;
double result = 0.;
// With these ifs I'm introducing the constraints on cT2, cS2 and on the parameters a and c
// To eliminate these constraints, put CT2_CONSTR=0 at the beginning of the file
//
// OLD constraint: CT2_CONSTR==1 && a>=-1. && a<=1. && b>=0. && b<=1. && ct2>=0.0 && ct2<= 1.0 && cs2>=0.0 && cs2<=1.0
//
// NEW (correct) constraint: CT2_CONSTR==1 && a>=-1. && a<=1. && Mpl2>=0. && c<=1. && c>=0 && ct2>=0.0 && ct2<= 1.0 && cs2<=0.0
//
if (CT2_CONSTR==1 && a>=-1. && a<=1. && c>=0. && c<=1. && ct2>=0. && ct2<=1. && cs2>=0. && cs2<=1.){
result=exp(-0.5 * pow(delta/sigma,2.0) );
}
else if(CT2_CONSTR==1){
result=exp(-1e90);
}
else{
result=exp(-0.5 * pow(delta/sigma,2.0) );
}
return result;
}
chain_res chain_analysis(double (* chain)[3]){
chain_res result;
gsl_vector * mean = gsl_vector_alloc(3);
int i,k,s;
for(k=0;k<3;k++){
double mean_temp = 0.;
for(i=0;i<N;i++){
mean_temp = mean_temp + chain[i][k];
}
gsl_vector_set(mean, k, mean_temp);
}
gsl_vector_scale(mean,1./N);
gsl_matrix * cm = gsl_matrix_alloc(3,3);
for(k=0;k<3;k++){
double mean_row = gsl_vector_get(mean,k);
for(s=0;s<3;s++){
double mean_column = gsl_vector_get(mean,s);
double cm_temp = 0.;
for(i=0;i<N;i++){
cm_temp = cm_temp + (chain[i][k]-mean_row)*(chain[i][s]-mean_column);
}
gsl_matrix_set(cm, k, s, cm_temp);
}
}
gsl_matrix_scale(cm,1./(N-1.));
result.mean = gsl_vector_alloc(3);
gsl_vector_memcpy(result.mean,mean);
result.covariance = gsl_matrix_alloc(3,3);
gsl_matrix_memcpy(result.covariance,cm);
gsl_matrix_free(cm);
gsl_vector_free(mean);
return result;
}
inline double Gaussian_proposal(double mean, double sigma, double u1, double u2) {
// Box Muller transform from flat distribution to Guassian distribution
return mean + sigma * sqrt(-2.*log(u1)) * cos(2.*M_PI*u2);
}
void C_Delta(double (* chain)[3], chain_res results, double f_stop, int chain_number){
int id_thread = omp_get_thread_num();
double mean_X = gsl_vector_get(results.mean,0);
double mean_Y = gsl_vector_get(results.mean,1);
double mean_Z = gsl_vector_get(results.mean,2);
double cm_XX = gsl_matrix_get(results.covariance,0,0);
double cm_YY = gsl_matrix_get(results.covariance,1,1);
double cm_ZZ = gsl_matrix_get(results.covariance,2,2);
int stop = N*f_stop;
double * C_Delta_X; double * C_Delta_Y; double * C_Delta_Z;
C_Delta_X = (double *) malloc(sizeof(double) * stop);
C_Delta_Y = (double *) malloc(sizeof(double) * stop);
C_Delta_Z = (double *) malloc(sizeof(double) * stop);
int i,j;
for(i=0;i<stop;i++){
for(j=0;j<N-i;j++){
C_Delta_X[i]=C_Delta_X[i]+(chain[j][0]-mean_X)*(chain[j+i][0]-mean_X);
C_Delta_Y[i]=C_Delta_Y[i]+(chain[j][1]-mean_Y)*(chain[j+i][1]-mean_Y);
C_Delta_Z[i]=C_Delta_Z[i]+(chain[j][2]-mean_Z)*(chain[j+i][2]-mean_Z);
}
C_Delta_X[i]=C_Delta_X[i]/(N-i)/cm_XX;
C_Delta_Y[i]=C_Delta_Y[i]/(N-i)/cm_YY;
C_Delta_Z[i]=C_Delta_Z[i]/(N-i)/cm_ZZ;
}
FILE *fp;
char filename[25];
sprintf(filename,"Ligo_abc_DeltaC_t%d.csv",chain_number);
fp = fopen (filename, "w+");
for(i=0;i<stop;i++){
fprintf(fp, "%d,%.8e,%.8e,%.8e\n", i, C_Delta_X[i], C_Delta_Y[i], C_Delta_Z[i]);
}
fclose(fp);
free(C_Delta_X);
free(C_Delta_Y);
free(C_Delta_Z);
}
chain_res LHSampling(int proposal, int chain_number){
int k;
int id_thread=omp_get_thread_num();
const gsl_rng_type * T;
gsl_rng * r;
gsl_rng_env_setup();
T = gsl_rng_default;
r = gsl_rng_alloc (T);
unsigned long seed = time(NULL) + chain_number;
gsl_rng_set(r, seed);
gsl_vector * pos_ini = gsl_vector_alloc(3);
for(k=0;k<3;k++){
if(k==0){
double random_number = 2. * gsl_rng_uniform (r) - 1.;
gsl_vector_set(pos_ini,k,SPEED[k]*random_number);
}
else if (k==1){
double random_number = gsl_rng_uniform (r);
gsl_vector_set(pos_ini,k,SPEED[k]*random_number);
}
else {
double random_number = gsl_rng_uniform (r);
gsl_vector_set(pos_ini,k,SPEED[k]*random_number);
}
}
// Here definitions only for the Gaussian proposal distribution
gsl_vector * pos_mean_p1 = gsl_vector_alloc(3);
for(k=0;k<3;k++){
gsl_vector_set(pos_mean_p1, k, MEAN_P1[k]);
}
gsl_matrix * S = gsl_matrix_calloc(3,3);
gsl_matrix * L = gsl_matrix_alloc(3,3);
gsl_vector * pos_temp2 = gsl_vector_alloc(3);
gsl_matrix_set(S,0,0,pow(SPEED[0],2.));
gsl_matrix_set(S,1,1,pow(SPEED[1],2.));
gsl_matrix_set(S,2,2,pow(SPEED[2],2.));
gsl_matrix_memcpy(L,S);
gsl_linalg_cholesky_decomp1(L);
// End of Gaussian proposal definitions
gsl_vector * pos = gsl_vector_alloc(3);
gsl_vector_memcpy(pos,pos_ini);
#if CSV==1
FILE *fp;
char filename[25];
sprintf(filename,"Ligo_abc_%d.txt",chain_number);
fp = fopen (filename, "w+");
#endif
double (* chain)[3] = malloc(sizeof(* chain) * N);
int i = 0; int j = 0; int rc = 1;
while (i<N) {
double f0 = rho(pos);
gsl_vector * pos_temp = gsl_vector_calloc(3);
// NOTE: Introducing the proposal distributions here
if(proposal==0){
for(k=0;k<3;k++){
double random_number = 2. * gsl_rng_uniform (r) - 1.;
gsl_vector_set(pos_temp, k, SPEED[k]*random_number);
}
gsl_vector_add(pos_temp,pos);
}
else if(proposal=!0){
for(k=0;k<3;k++){
gsl_vector_set(pos_temp2, k, Gaussian_proposal(0., 1., gsl_rng_uniform (r), gsl_rng_uniform (r)));
}
gsl_blas_dgemv (CblasNoTrans,
1., L, pos_temp2,
0., pos_temp);
gsl_vector_add(pos_temp,pos_mean_p1);
gsl_vector_add(pos_temp,pos);
}
double f1 = rho(pos_temp);
// NOTE: here we also print data in .csv file (if CSV==1) in Getdist ready format
// Getdist output with (no commas): repetitions count log(rho) {parameters} {(optional) other outputs - not considered by Getdist}
if (f1>f0) {
gsl_vector_memcpy(pos,pos_temp);
j++;
#if CSV==1
fprintf(fp, "%d %.8e %.8e %.8e %.8e\n", rc, -log(rho(pos)), gsl_vector_get(pos,0), gsl_vector_get(pos,1), gsl_vector_get(pos,2));
#endif
rc = 1;
}
else {
double ra = gsl_rng_uniform (r);
if (ra<f1/f0) {
gsl_vector_memcpy(pos,pos_temp);
j++;
#if CSV==1
fprintf(fp, "%d %.8e %.8e %.8e %.8e\n", rc, -log(rho(pos)), gsl_vector_get(pos,0), gsl_vector_get(pos,1), gsl_vector_get(pos,2));
#endif
rc = 1;
}
else{
rc++;
}
}
for(k=0;k<3;k++){
chain[i][k]=gsl_vector_get(pos,k);
}
gsl_vector_free(pos_temp);
i++;
}
chain_res result;
result = chain_analysis(chain);
result.acceptance_ratio = (double) j/i;
if(DEBUG==1 && result.acceptance_ratio<0.05) printf("\n WARNING (chain %d): Acceptance ratio at %e. The chain seems stuck at initial point. \n", chain_number, result.acceptance_ratio);
if(DEBUG==1 && result.acceptance_ratio>0.8) printf("\n WARNING (chain %d): Acceptance ratio at %e. The chain seems evolving too slowly. \n", chain_number, result.acceptance_ratio);
// Check of correlation (with lag)
if(LAG_TEST==1){
printf(" Computing Lag function..\n");
if(DEBUG==1) printf(" Note: This computation can take a lot of computational time.\n");
if(DEBUG==1) printf(" Lower LAG_TEST_STOP_RATIO for faster results.\n");
C_Delta(chain,result,LAG_TEST_STOP_RATIO, chain_number);
}
#if CSV==1
if(CSV_COV==1){
FILE *fp2;
sprintf(filename,"Ligo_abc_%d.covmat",chain_number);
fp2 = fopen (filename, "w+");
fprintf(fp2, "%.8e %.8e %.8e\n", gsl_matrix_get(result.covariance,0,0),gsl_matrix_get(result.covariance,0,1),gsl_matrix_get(result.covariance,0,2));
fprintf(fp2, "%.8e %.8e %.8e\n", gsl_matrix_get(result.covariance,1,0),gsl_matrix_get(result.covariance,1,1),gsl_matrix_get(result.covariance,1,2));
fprintf(fp2, "%.8e %.8e %.8e\n", gsl_matrix_get(result.covariance,2,0),gsl_matrix_get(result.covariance,2,1),gsl_matrix_get(result.covariance,2,2));
fclose(fp2);
}
#endif
#if CSV==1
if(CSV_CORR==1){
FILE *fp3;
sprintf(filename,"Ligo_abc_%d.corr",chain_number);
fp3 = fopen (filename, "w+");
fprintf(fp3, "%.8e %.8e %.8e\n", 1.,gsl_matrix_get(result.covariance,0,1)/sqrt(fabs(gsl_matrix_get(result.covariance,0,0)))/sqrt(fabs(gsl_matrix_get(result.covariance,1,1))),gsl_matrix_get(result.covariance,0,2)/sqrt(fabs(gsl_matrix_get(result.covariance,0,0)))/sqrt(fabs(gsl_matrix_get(result.covariance,2,2))));
fprintf(fp3, "%.8e %.8e %.8e\n", gsl_matrix_get(result.covariance,1,0)/sqrt(fabs(gsl_matrix_get(result.covariance,0,0)))/sqrt(fabs(gsl_matrix_get(result.covariance,1,1))),1.,gsl_matrix_get(result.covariance,1,2)/sqrt(fabs(gsl_matrix_get(result.covariance,1,1)))/sqrt(fabs(gsl_matrix_get(result.covariance,2,2))));
fprintf(fp3, "%.8e %.8e %.8e\n", gsl_matrix_get(result.covariance,2,0)/sqrt(fabs(gsl_matrix_get(result.covariance,0,0)))/sqrt(fabs(gsl_matrix_get(result.covariance,2,2))),gsl_matrix_get(result.covariance,2,1)/sqrt(fabs(gsl_matrix_get(result.covariance,1,1)))/sqrt(fabs(gsl_matrix_get(result.covariance,2,2))),1.);
fclose(fp3);
}
#endif
// Free all the variables
free(chain);
gsl_vector_free(pos_ini);
gsl_vector_free(pos_mean_p1);
gsl_vector_free(pos);
gsl_rng_free(r);
gsl_vector_free(pos_temp2);
gsl_matrix_free(S);
gsl_matrix_free(L);
#if CSV==1
fclose(fp);
#endif
return result;
}
inline double R(double sigma2_chain, double sigma2_mean){
int noc = N_CHAINS;
return sqrt(((N-1.)/N*sigma2_chain + (noc+1.)/N/noc*sigma2_mean)/sigma2_chain);
}
gsl_vector * GR_Test(chain_res * chain_results) {
int i, k;
int noc = N_CHAINS;
gsl_vector * mean = gsl_vector_alloc(3);
gsl_vector * sigma2_chain = gsl_vector_alloc(3);
gsl_vector * sigma2_mean = gsl_vector_alloc(3);
for(k=0;k<3;k++){
double mean_temp = 0.;
double sigma2_temp = 0.;
for(i=0;i<noc;i++){
mean_temp = mean_temp + gsl_vector_get(chain_results[i].mean,k)/noc;
sigma2_temp = sigma2_temp + fabs(gsl_matrix_get(chain_results[i].covariance,k,k))/noc;
}
gsl_vector_set(mean, k, mean_temp);
gsl_vector_set(sigma2_chain, k, sigma2_temp);
}
for(k=0;k<3;k++){
double mean_temp = 0.;
double sigma2_temp = 0.;
for(i=0;i<noc;i++){
sigma2_temp = sigma2_temp + pow(gsl_vector_get(mean,k)-gsl_vector_get(chain_results[i].mean,k),2.)*N/(noc-1.);
}
gsl_vector_set(sigma2_mean, k, sigma2_temp);
}
double R_a = R(gsl_vector_get(sigma2_chain,0), gsl_vector_get(sigma2_mean,0));
double R_b = R(gsl_vector_get(sigma2_chain,1), gsl_vector_get(sigma2_mean,1));
double R_c = R(gsl_vector_get(sigma2_chain,2), gsl_vector_get(sigma2_mean,2));
printf("\n Gelman-Rubin test.\n");
printf(" \t- R_a : %f\n", R_a);
printf(" \t- R_b : %f\n", R_b);
printf(" \t- R_c : %f\n", R_c);
if(DEBUG==1) printf(" Converge if (approximately) R < 1.2. For better results R < 1.01.\n");
printf("\n ------------------------------------------------------------------------ \n");
gsl_vector_free(mean);
gsl_vector_free(sigma2_chain);
gsl_vector_free(sigma2_mean);
gsl_vector * result = gsl_vector_alloc(3);
gsl_vector_set(result,0,R_a);gsl_vector_set(result,1,R_b);gsl_vector_set(result,2,R_c);
return result;
}
void init_msg(int proposal){
printf(" Starting the MCMC computation with Metropolis-Hastings algorithm.\n");
printf(" Properties of the chains:\n");
if(proposal==0){
printf(" \t- Proposal distribution: flat.\n");
}
if(proposal!=0){
printf(" \t- Proposal distribution: Gaussian.\n");
}
if(OPENMP==0){
printf(" \t- The chain will be %d points long.\n", N);
}
if(OPENMP==1){
printf(" \t- Each of the %d chains will be %d points long.\n", N_CHAINS, N);
}
printf(" ------------------------------------------------------------------------ \n");
}
int main(){
int proposal=PROPOSAL;
printf(" ------------------------------------------------------------------------ \n");
printf("\t mimetic_bayes program ");
if(DEBUG==1) printf("(with DEBUG mode on)");
printf("\n");
printf(" ------------------------------------------------------------------------ \n");
if(OPENMP==1){
int i;
chain_res * chain_results;
chain_results = (chain_res *) malloc(sizeof(chain_res) * N_CHAINS);
if(OMP_THREAD_NUM==0) OMP_THREAD_NUM = omp_get_max_threads();
if(DEBUG==1) {
printf(" Info on OpenMP on this computer. \n");
printf(" \t- Number of processors available = %d\n", omp_get_num_procs ( ) );
printf(" \t- Number of threads = %d\n", omp_get_max_threads ( ) );
printf(" \t- Number of working threads = %d\n", OMP_THREAD_NUM );
printf(" Specify the number of working threads in .c file.\n");
printf(" ------------------------------------------------------------------------ \n");
}
printf(" Number of chains requested = %d. \n", N_CHAINS);
printf(" ------------------------------------------------------------------------ \n");
if(OMP_THREAD_NUM>omp_get_max_threads()){
printf(" Fatal Error. Can't set number of threads (OMP_THREAD_NUM = %d) bigger than the available number of threads (%d). \n",OMP_THREAD_NUM, omp_get_max_threads());
printf(" \t Change OMP_THREAD_NUM and try again. \n");
printf(" The program will be terminated. \n");
exit(0);
}
omp_set_num_threads(OMP_THREAD_NUM);
init_msg(proposal);
printf("\n Doing parallelized workflow. Please wait. \n\n");
if(DEBUG==1) printf(" NOTE: Some WARNING might be shown. \n");
if(DEBUG==1) printf(" Consider to stop the program and check the parameters if WARNINGs appear. \n\n");
#pragma omp parallel for
for(i=1;i<=N_CHAINS;i++)
{
int current_thread = omp_get_thread_num();
if(DEBUG==1) printf(" Thread %d working on chain %d .\n", current_thread, i);
chain_results[i-1]=LHSampling(proposal, i);
if(DEBUG==1) printf(" Thread %d finished working on chain %d. \n", current_thread, i);
}
printf(" ------------------------------------------------------------------------ \n");
for(i=0;i<N_CHAINS;i++){
printf(" CHAIN %d RESULTS. \n", i+1);
printf("\n Acceptance ratio: %f \n\n", chain_results[i].acceptance_ratio);
printf(" Results: Mean value pm sqrt(covariant_ii).\n");
printf(" \ta: %e pm %e\n", gsl_vector_get(chain_results[i].mean,0), sqrt(fabs(gsl_matrix_get(chain_results[i].covariance,0,0))));
printf(" \tb: %e pm %e\n", gsl_vector_get(chain_results[i].mean,1), sqrt(fabs(gsl_matrix_get(chain_results[i].covariance,1,1))));
printf(" \tc: %e pm %e\n", gsl_vector_get(chain_results[i].mean,2), sqrt(fabs(gsl_matrix_get(chain_results[i].covariance,2,2))));
printf("\n Results: Correlation coefficients.\n");
printf(" \tab: %e \n", gsl_matrix_get(chain_results[i].covariance,0,1)/sqrt(fabs(gsl_matrix_get(chain_results[i].covariance,0,0)))/sqrt(fabs(gsl_matrix_get(chain_results[i].covariance,1,1))));
printf(" \tac: %e \n", gsl_matrix_get(chain_results[i].covariance,0,2)/sqrt(fabs(gsl_matrix_get(chain_results[i].covariance,0,0)))/sqrt(fabs(gsl_matrix_get(chain_results[i].covariance,2,2))));
printf(" \tbc: %e \n", gsl_matrix_get(chain_results[i].covariance,1,2)/sqrt(fabs(gsl_matrix_get(chain_results[i].covariance,1,1)))/sqrt(fabs(gsl_matrix_get(chain_results[i].covariance,2,2))));
printf(" These are the Pearson coefficients : covariant_ij / sigma_i sigma_j\n\n");
printf(" ------------------------------------------------------------------------ \n");
}
gsl_vector * GR_test_result = gsl_vector_alloc(3);
GR_test_result = GR_Test(chain_results);
double R_a = gsl_vector_get(GR_test_result,0);
double R_b = gsl_vector_get(GR_test_result,1);
double R_c = gsl_vector_get(GR_test_result,2);
if(DEBUG==1){
int k = 0;
double C00 = sqrt(gsl_matrix_get(chain_results[0].covariance,0,0));
double C11 = sqrt(gsl_matrix_get(chain_results[0].covariance,1,1));
double C22 = sqrt(gsl_matrix_get(chain_results[0].covariance,2,2));
printf("\n INFORMATIONS for better convergence. \n\n");
printf(" WARNING: These are hints based on the results and thumb rules. \n");
printf(" Follow these hints at your own risk. \n\n");
if(R_a>1.2||R_b>1.2||R_c>1.2) {
printf(" - An R_i>1.2 : Chains are sampling different parameter spaces.\n");
printf(" There might be some troubles in your SPEED vector definition.\n");
k++;
}
if((R_a<1.2&&R_a>1.01)||(R_b<1.2&&R_b>1.01)||(R_c<1.2&&R_c>1.01)) {
printf(" - An R_i>1.01 : The results might be good, but the results can be improved.\n");
printf(" Try different values for the SPEED vector to achieve better results.\n");
k++;
}
double p_value = 0.5;
if(fabs(SPEED[0]-C00/4.)/fabs(SPEED[0]+C00/4.)>p_value){
printf(" - From covariance matrix: Try with a SPEED[0] = %e .\n",C00/4.);
k++;
}
if(fabs(SPEED[1]-C11/4.)/fabs(SPEED[1]+C11/4.)>p_value){
printf(" - From covariance matrix: Try with a SPEED[1] = %e .\n",C11/4.);
k++;
}
if(fabs(SPEED[2]-C22/4.)/fabs(SPEED[2]+C22/4.)>p_value){
printf(" - From covariance matrix: Try with a SPEED[2] = %e .\n",C22/4.);
k++;
}
int j=0, r=0;
for(i=0;i<N_CHAINS;i++){
if(chain_results[i].acceptance_ratio>0.5) j++;
if(chain_results[i].acceptance_ratio<0.1) r++;
}
if(j>0){
printf(" - From acceptance rations: Maybe some acceptance ratios are too big.\n");
printf(" The configuration space might be explored slowly.\n");
printf(" This is not necessarily a problem,\n");
printf(" but if the results are not good:\n");
printf(" try with different SPEED vector values.\n");
k++;
}
if(r>0){
printf(" - From acceptance rations: Maybe some acceptance ratios are too small.\n");
printf(" The configuration space might be explored very inefficiently.\n");
printf(" This is not necessarily a problem,\n");
printf(" but if the results are not good:\n");
printf(" try with different SPEED vector values.\n");
k++;
}
double mean_a = gsl_vector_get(chain_results[0].mean,0);
double sigma_a = sqrt(fabs(gsl_matrix_get(chain_results[0].covariance,0,0)));
if(PROPOSAL==1 && (fabs(mean_a-MEAN_P1[0])/fabs(mean_a+MEAN_P1[0])>3.*sigma_a)) {
printf(" - A burn-in removal might be needed: Try with MEAN_P1[0] = %e.\n",mean_a);
printf(" Note that this can improve but also worsen the results.\n");
printf(" Revert the result and make a burn-in removal instead if the results get worse.\n");
}
double mean_b = gsl_vector_get(chain_results[0].mean,1);
double sigma_b = sqrt(fabs(gsl_matrix_get(chain_results[0].covariance,1,1)));
if(PROPOSAL==1 && (fabs(mean_b-MEAN_P1[1])/fabs(mean_b+MEAN_P1[1])>3.*sigma_b)) {
printf(" - A burn-in removal might be needed: Try with MEAN_P1[1] = %e.\n",mean_b);
printf(" Note that this can improve but also worsen the results.\n");
printf(" Revert the result and make a burn-in removal instead if the results get worse.\n");
}
double mean_c = gsl_vector_get(chain_results[0].mean,2);
double sigma_c = sqrt(fabs(gsl_matrix_get(chain_results[0].covariance,2,2)));
if(PROPOSAL==1 && (fabs(mean_a-MEAN_P1[2])/fabs(mean_a+MEAN_P1[2])>3.*sigma_c)) {
printf(" - A burn-in removal might be needed: Try with MEAN_P1[2] = %e .\n",mean_c);
printf(" Note that this can improve but also worsen the results.\n");
printf(" Revert the result and make a burn-in removal instead if the results get worse.\n");
}
if(k==0){
printf(" Congratulations! The convercence seems good. \n");
}
printf("\n ------------------------------------------------------------------------ \n");
}
free(chain_results);
}
else{
init_msg(proposal);
LHSampling(proposal, 0);
printf(" ------------------------------------------------------------------------ \n");
}
return 0;
}
| {
"alphanum_fraction": 0.6234128471,
"avg_line_length": 33.22406639,
"ext": "c",
"hexsha": "ab5dad315a8c114a53887bfadbd4407a524afcc9",
"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": "c3580027ef49fbe12619a4f76a02b7bbc455c5c8",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "alessandrocasalino/mimetic_bayes",
"max_forks_repo_path": "Ligo_abc_gsl.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "c3580027ef49fbe12619a4f76a02b7bbc455c5c8",
"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": "alessandrocasalino/mimetic_bayes",
"max_issues_repo_path": "Ligo_abc_gsl.c",
"max_line_length": 319,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "c3580027ef49fbe12619a4f76a02b7bbc455c5c8",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "alessandrocasalino/mimetic_bayes",
"max_stars_repo_path": "Ligo_abc_gsl.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 7008,
"size": 24021
} |
#ifndef MITRO_GRAPH_H
#define MITRO_GRAPH_H
#include <algorithm>
#include <cstdint>
#include <functional>
#include <memory>
#include <set>
#include <string>
#include <vector>
#include <gsl.h>
class Graph;
struct GraphEdge
{
double weight = 0;
int from = -1;
int to = -1;
GraphEdge(double weight, int from, int to) : weight(weight), from(from), to(to) {}
bool operator<(const GraphEdge& other) const { return std::make_tuple(weight, from, to) < std::make_tuple(other.weight, other.from, other.to); }
int otherEnd(int oneEnd) const
{
if (oneEnd != from && oneEnd != to)
throw "Invalid end";
return (oneEnd == from) ? to : from;
}
};
struct EdgePtrCompare
{
bool operator() (const GraphEdge* lhs, const GraphEdge* rhs)
{
return *lhs < *rhs;
}
};
typedef std::set<gsl::not_null<GraphEdge*>, EdgePtrCompare> EdgePtrSet;
typedef std::vector<GraphEdge*> EdgePtrVector;
template <class ValueType, class WrappedValueType, bool is_const_iterator = false>
class basic_graph_iterator
{
using vector_in_creator = std::vector<WrappedValueType>;
using iterator_in_creator = typename std::conditional<is_const_iterator,
typename vector_in_creator::const_iterator,
typename vector_in_creator::iterator
>::type;
public:
using iterator_category = std::random_access_iterator_tag;
using difference_type = typename iterator_in_creator::difference_type;
using value_type = ValueType;
using pointer = typename std::conditional<is_const_iterator, const value_type*, value_type*>::type;
using reference = typename std::conditional<is_const_iterator, const value_type&, value_type&>::type;
basic_graph_iterator(const basic_graph_iterator& other) = default;
basic_graph_iterator& operator=(const basic_graph_iterator& other) = default;
explicit basic_graph_iterator(const iterator_in_creator &it) : it(it) {}
friend bool operator==(const basic_graph_iterator& l, const basic_graph_iterator& r) { return l.it == r.it; }
friend bool operator!=(const basic_graph_iterator& l, const basic_graph_iterator& r) { return l.it != r.it; }
friend bool operator<(const basic_graph_iterator& l, const basic_graph_iterator& r) { return l.it < r.it; }
reference operator*() { return **it; }
pointer operator->() { return *it; }
basic_graph_iterator& operator++()
{
++it;
return *this;
}
basic_graph_iterator operator++(int)
{
basic_graph_iterator tmp(*this);
++it;
return tmp;
}
private:
iterator_in_creator it;
};
class GraphNode
{
public:
friend class Graph;
using edge_iterator = basic_graph_iterator<GraphEdge, gsl::not_null<GraphEdge*>, false>;
using const_edge_iterator = basic_graph_iterator<GraphEdge, gsl::not_null<GraphEdge*>, true>;
GraphNode(double weight = 0.0): weight(weight) {};
~GraphNode() = default;
GraphNode &operator=(const GraphNode &other) = delete;
GraphNode(const GraphNode &other) = default;
void setWeight(double w) { weight = w; }
double getWeight() const { return weight; }
const_edge_iterator begin() const { return const_edge_iterator{ edges.begin() }; }
const_edge_iterator end() const { return const_edge_iterator{ edges.end() }; }
edge_iterator begin() { return edge_iterator{ edges.begin() }; }
edge_iterator end() { return edge_iterator{ edges.end() }; }
int getEdgeCount() const { return int(edges.size()); }
const GraphEdge& getEdge(int idx) const { return *edges[idx]; }
private:
void addEdge(gsl::not_null<GraphEdge*> edge) { edges.push_back(edge); }
void removeEdge(gsl::not_null<GraphEdge*> edge) { edges.erase(std::remove(edges.begin(), edges.end(), edge), edges.end()); }
std::vector<gsl::not_null<GraphEdge*>> edges;
double weight;
};
class Graph
{
public:
friend class GraphNode;
friend std::istream &operator>>(std::istream &is, Graph &g);
friend std::ostream &operator<<(std::ostream &os, const Graph &g);
using node_iterator = basic_graph_iterator<GraphNode, std::unique_ptr<GraphNode>, false>;
using const_node_iterator = basic_graph_iterator<GraphNode, std::unique_ptr<GraphNode>, true>;
using edge_iterator = basic_graph_iterator<GraphEdge, std::unique_ptr<GraphEdge>, false>;
using const_edge_iterator = basic_graph_iterator<GraphEdge, std::unique_ptr<GraphEdge>, true>;
explicit Graph(bool dir) : directed(dir) {}
~Graph() = default;
Graph &operator=(const Graph &other) = delete;
Graph(const Graph &other) = delete;
int addNode(double weight = 0.0);
void addEdge(int from, int to, double weight = 0.0);
void removeEdge(int from, int to);
bool hasEdge(int from, int to);
const_node_iterator begin() const { return const_node_iterator{nodes.begin()}; }
const_node_iterator end() const { return const_node_iterator{nodes.end()}; }
node_iterator begin() { return node_iterator{nodes.begin()}; }
node_iterator end() { return node_iterator{nodes.end()}; }
const_edge_iterator edges_begin() const { return const_edge_iterator{edges.begin()}; }
const_edge_iterator edges_end() const { return const_edge_iterator{edges.end()}; }
edge_iterator edges_begin() { return edge_iterator{edges.begin()}; }
edge_iterator edges_end() { return edge_iterator{edges.end()}; }
void resize(int newNodes);
GraphNode &getNode(int idx) { return *nodes[idx]; }
const GraphNode &getNode(int idx) const { return *nodes[idx]; }
int getNodeCount() const { return int(nodes.size()); }
bool isDirected() const { return directed; }
bool hasWeightedNodes() const { return weightedNodes; }
void setWeightedNodes(bool weighted) { weightedNodes = weighted; }
bool hasWeightedEdges() const { return weightedEdges; }
void setWeightedEdges(bool weighted) { weightedEdges = weighted; }
void clear(bool newDirected);
private:
bool directed;
bool weightedNodes = false;
bool weightedEdges = true;
using node_vector = std::vector<std::unique_ptr<GraphNode>>;
using edge_vector = std::vector<std::unique_ptr<GraphEdge>>;
node_vector nodes;
edge_vector edges;
};
std::istream &operator>>(std::istream &is, Graph &g);
std::ostream &operator<<(std::ostream &os, const Graph &g);
#endif // MITRO_UTIL_GRAPH_H
| {
"alphanum_fraction": 0.7032706589,
"avg_line_length": 33.664893617,
"ext": "h",
"hexsha": "6f35b9eb77842d4bab4db5c452e96c07224839c3",
"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": "f30b93fb5c1f61f5abc6c239b351e923e9168ff3",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "mitro42/Graph",
"max_forks_repo_path": "include/Graph.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "f30b93fb5c1f61f5abc6c239b351e923e9168ff3",
"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": "mitro42/Graph",
"max_issues_repo_path": "include/Graph.h",
"max_line_length": 148,
"max_stars_count": 3,
"max_stars_repo_head_hexsha": "f30b93fb5c1f61f5abc6c239b351e923e9168ff3",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "mitro42/Graph",
"max_stars_repo_path": "include/Graph.h",
"max_stars_repo_stars_event_max_datetime": "2016-07-02T07:29:09.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-12-14T15:38:07.000Z",
"num_tokens": 1515,
"size": 6329
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.