Search is not available for this dataset
text string | meta dict |
|---|---|
/* linalg/test_tri.c
*
* Copyright (C) 2019 Patrick Alken
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#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_blas.h>
#include <gsl/gsl_linalg.h>
#include <gsl/gsl_rng.h>
static int
test_symmtd_decomp_eps(const gsl_matrix * m, const double eps, const char * desc)
{
int s = 0;
const size_t N = m->size1;
size_t i, j;
gsl_matrix * Q = gsl_matrix_alloc(N, N);
gsl_matrix * T = gsl_matrix_calloc(N, N);
gsl_matrix * A = gsl_matrix_alloc(N, N);
gsl_matrix * B = gsl_matrix_alloc(N, N);
gsl_vector * tau = gsl_vector_alloc(N - 1);
gsl_vector_view diag = gsl_matrix_diagonal(T);
gsl_vector_view subdiag = gsl_matrix_subdiagonal(T, 1);
gsl_vector_view superdiag = gsl_matrix_superdiagonal(T, 1);
gsl_matrix_memcpy(A, m);
s += gsl_linalg_symmtd_decomp(A, tau);
s += gsl_linalg_symmtd_unpack(A, tau, Q, &diag.vector, &subdiag.vector);
gsl_vector_memcpy(&superdiag.vector, &subdiag.vector);
gsl_blas_dgemm(CblasNoTrans, CblasNoTrans, 1.0, Q, T, 0.0, A); /* A := Q T */
gsl_blas_dgemm(CblasNoTrans, CblasTrans, 1.0, A, Q, 0.0, B); /* B := Q T Q^T */
for (i = 0; i < N; i++)
{
for (j = 0; j <= i; j++)
{
double bij = gsl_matrix_get(B, i, j);
double mij = gsl_matrix_get(m, i, j);
gsl_test_rel(bij, mij, eps, "%s (%3lu)[%lu,%lu]: %22.18g %22.18g\n",
desc, N, i, j, bij, mij);
}
}
gsl_matrix_free(T);
gsl_matrix_free(A);
gsl_matrix_free(Q);
gsl_matrix_free(B);
gsl_vector_free(tau);
return s;
}
static int
test_symmtd_decomp(gsl_rng * r)
{
int s = 0;
size_t N;
for (N = 2; N <= 50; ++N)
{
gsl_matrix * A = gsl_matrix_alloc(N, N);
create_symm_matrix(A, r);
s += test_symmtd_decomp_eps(A, 1.0e5 * N * GSL_DBL_EPSILON, "symmtd_decomp random");
gsl_matrix_free(A);
}
return s;
}
static int
test_hermtd_decomp_eps(const gsl_matrix_complex * m, const double eps, const char * desc)
{
int s = 0;
const size_t N = m->size1;
size_t i, j;
gsl_matrix_complex * Q = gsl_matrix_complex_alloc(N, N);
gsl_matrix_complex * T = gsl_matrix_complex_calloc(N, N);
gsl_matrix_complex * A = gsl_matrix_complex_alloc(N, N);
gsl_matrix_complex * B = gsl_matrix_complex_alloc(N, N);
gsl_vector_complex * tau = gsl_vector_complex_alloc(N - 1);
gsl_vector_view diag, subdiag, superdiag;
gsl_vector_complex_view v;
v = gsl_matrix_complex_diagonal(T);
diag = gsl_vector_complex_real(&v.vector);
v = gsl_matrix_complex_subdiagonal(T, 1);
subdiag = gsl_vector_complex_real(&v.vector);
v = gsl_matrix_complex_superdiagonal(T, 1);
superdiag = gsl_vector_complex_real(&v.vector);
gsl_matrix_complex_memcpy(A, m);
s += gsl_linalg_hermtd_decomp(A, tau);
s += gsl_linalg_hermtd_unpack(A, tau, Q, &diag.vector, &subdiag.vector);
gsl_vector_memcpy(&superdiag.vector, &subdiag.vector);
gsl_blas_zgemm(CblasNoTrans, CblasNoTrans, GSL_COMPLEX_ONE, Q, T, GSL_COMPLEX_ZERO, A); /* A := Q T */
gsl_blas_zgemm(CblasNoTrans, CblasConjTrans, GSL_COMPLEX_ONE, A, Q, GSL_COMPLEX_ZERO, B); /* B := Q T Q^T */
for (i = 0; i < N; i++)
{
for (j = 0; j <= i; j++)
{
gsl_complex bij = gsl_matrix_complex_get(B, i, j);
gsl_complex mij = gsl_matrix_complex_get(m, i, j);
gsl_test_rel(GSL_REAL(bij), GSL_REAL(mij), eps, "%s real (%3lu)[%lu,%lu]: %22.18g %22.18g\n",
desc, N, i, j, GSL_REAL(bij), GSL_REAL(mij));
gsl_test_rel(GSL_IMAG(bij), GSL_IMAG(mij), eps, "%s imag (%3lu)[%lu,%lu]: %22.18g %22.18g\n",
desc, N, i, j, GSL_IMAG(bij), GSL_IMAG(mij));
}
}
gsl_matrix_complex_free(T);
gsl_matrix_complex_free(A);
gsl_matrix_complex_free(Q);
gsl_matrix_complex_free(B);
gsl_vector_complex_free(tau);
return s;
}
static int
test_hermtd_decomp(gsl_rng * r)
{
int s = 0;
size_t N;
for (N = 2; N <= 50; ++N)
{
gsl_matrix_complex * A = gsl_matrix_complex_alloc(N, N);
create_herm_matrix(A, r);
s += test_hermtd_decomp_eps(A, 1.0e5 * N * GSL_DBL_EPSILON, "hermtd_decomp random");
gsl_matrix_complex_free(A);
}
return s;
}
| {
"alphanum_fraction": 0.659,
"avg_line_length": 29.7619047619,
"ext": "c",
"hexsha": "cca1d280309e244501e8ff879be7ce3396a54782",
"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_tri.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_tri.c",
"max_line_length": 111,
"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_tri.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": 1547,
"size": 5000
} |
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <stdarg.h>
#include <gbpLib.h>
#include <gbpMath.h>
#include <gbpCosmo_mass_functions.h>
#include <gsl/gsl_integration.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_spline.h>
// Compute cumulative comoving mass function
typedef struct mass_function_cumulative_params_struct mass_function_cumulative_params;
struct mass_function_cumulative_params_struct {
cosmo_info **cosmo;
double z;
int mode;
double * P;
};
double mass_function_cumulative_integrand(double lM, void *params_in);
double mass_function_cumulative_integrand(double lM, void *params_in) {
mass_function_cumulative_params *params;
params = (mass_function_cumulative_params *)params_in;
double M = take_alog10(lM);
double r_val = mass_function(M, params->z, params->cosmo, params->mode, params->P);
return (r_val);
}
double mass_function_cumulative(double M_interp, double z, cosmo_info **cosmo, int mode, ...) {
va_list vargs;
va_start(vargs, mode);
// Get passed parameters (if mode specifies they are there).
double *P = NULL;
if(SID_CHECK_BITFIELD_SWITCH(mode, MF_PASS_PARAMS))
P = (double *)va_arg(vargs, double *);
// Initialize integral
if(!ADaPS_exist((*cosmo), "lk_P"))
init_power_spectrum_TF(cosmo);
double *lk_P = (double *)ADaPS_fetch((*cosmo), "lk_P");
double limit_lo = take_log10(M_interp);
double limit_hi = take_log10(M_of_k(take_alog10(lk_P[0]), (*cosmo)));
// Perform integral
int n_int = 5000;
double rel_accuracy = 1e-4;
double r_val = 0.;
if(limit_lo < limit_hi) {
double abs_error;
mass_function_cumulative_params params;
gsl_function integrand;
gsl_integration_workspace * wspace;
params.z = z;
params.cosmo = cosmo;
params.mode = mode;
params.P = P;
integrand.function = mass_function_cumulative_integrand;
integrand.params = (void *)(¶ms);
wspace = gsl_integration_workspace_alloc(n_int);
// Integrate mass function
gsl_integration_qag(&integrand, limit_lo, limit_hi, 0, rel_accuracy, n_int, GSL_INTEG_GAUSS61, wspace, &r_val, &abs_error);
// Clean-up
gsl_integration_workspace_free(wspace);
}
va_end(vargs);
return (r_val);
}
| {
"alphanum_fraction": 0.6519114688,
"avg_line_length": 35,
"ext": "c",
"hexsha": "bd965e2ecefbd99704919a5df49d027283704c2c",
"lang": "C",
"max_forks_count": 4,
"max_forks_repo_forks_event_max_datetime": "2016-08-01T08:14:24.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-01-23T00:50:40.000Z",
"max_forks_repo_head_hexsha": "5157d2e377edbd4806258d1c16b329373186d43a",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "gbpoole/gbpCode",
"max_forks_repo_path": "src/gbpAstro/gbpCosmo/mass_functions/mass_function_cumulative.c",
"max_issues_count": 2,
"max_issues_repo_head_hexsha": "5157d2e377edbd4806258d1c16b329373186d43a",
"max_issues_repo_issues_event_max_datetime": "2019-06-18T00:40:46.000Z",
"max_issues_repo_issues_event_min_datetime": "2017-07-30T11:10:49.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "gbpoole/gbpCode",
"max_issues_repo_path": "src/gbpAstro/gbpCosmo/mass_functions/mass_function_cumulative.c",
"max_line_length": 131,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "5157d2e377edbd4806258d1c16b329373186d43a",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "gbpoole/gbpCode",
"max_stars_repo_path": "src/gbpAstro/gbpCosmo/mass_functions/mass_function_cumulative.c",
"max_stars_repo_stars_event_max_datetime": "2015-10-20T11:39:53.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-10-20T11:39:53.000Z",
"num_tokens": 627,
"size": 2485
} |
#ifndef DETERMINISTIC_NETWORK_SIR_H
#define DETERMINISTIC_NETWORK_SIR_H
#include <gsl/gsl_odeiv.h>
#include <gsl/gsl_errno.h>
#include <iostream>
#include <math.h>
#include "DiffEq_Sim.h"
using namespace std;
class Deterministic_Network_SIR_Sim : public DiffEq_Sim {
private:
const double r;
const double mu;
const vector<double> deg_dist;
public:
Deterministic_Network_SIR_Sim() : r(0.0), mu(0.0) { nbins=4;}
Deterministic_Network_SIR_Sim(double r_param, double mu_param, vector<double> deg_dist_param):
r(r_param),
mu(mu_param),
deg_dist(deg_dist_param) {
nbins=4;
}
~Deterministic_Network_SIR_Sim() {};
void initialize( double theta, double pS, double pI, double I) {
y = new double[nbins];
y[0] = theta;
y[1] = pS;
y[2] = pI;
y[3] = I;
}
double current_susceptible() { return g( y[0] ); }
double current_infectious() { return y[3]; }
double current_recovered() { return 1.0 - current_susceptible() - current_infectious(); }
double g( double theta) {
double val = 0;
for (unsigned int i = 0; i<deg_dist.size(); i++) {
val += deg_dist[i] * pow(theta,i);
}
return val;
}
double dg( double theta) {
double val = 0;
for (unsigned int i = 1; i<deg_dist.size(); i++) {
val += (i) * deg_dist[i] * pow(theta,i-1);
}
return val;
}
double ddg( double theta) {
double val = 0;
for (unsigned int i = 2; i<deg_dist.size(); i++) {
val += (i) * (i-1) *deg_dist[i] * pow(theta,i-2);
}
return val;
}
void derivative(double const y[], double dydt[]) {
const double theta = y[0];
const double pS = y[1];
const double pI = y[2];
const double I = y[3];
dydt[0] = -r * pI * theta; // dtheta.dt
dydt[1] = r * pS * pI * (1 - theta * ddg(theta)/dg(theta)); // dpS.dt
dydt[2] = r * pI * pS * theta * ddg(theta)/dg(theta) - pI*(1-pI)*r- pI*mu; // dpI.dt
dydt[3] = r * pI * theta * dg(theta) - mu*I;
}
};
#endif
| {
"alphanum_fraction": 0.4889615699,
"avg_line_length": 30.1975308642,
"ext": "h",
"hexsha": "e3c50c8f26abbf017a9affe6590a86dd9b8857a6",
"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": "src/Deterministic_Network_SIR_Sim.h",
"max_issues_count": 2,
"max_issues_repo_head_hexsha": "c0d957265608b15f216ece67363c827d01122102",
"max_issues_repo_issues_event_max_datetime": "2020-07-20T16:32:02.000Z",
"max_issues_repo_issues_event_min_datetime": "2017-11-07T05:42:56.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "pvnuffel/test_repos",
"max_issues_repo_path": "src/Deterministic_Network_SIR_Sim.h",
"max_line_length": 102,
"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": "src/Deterministic_Network_SIR_Sim.h",
"max_stars_repo_stars_event_max_datetime": "2022-03-21T02:07:41.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-04-29T05:13:02.000Z",
"num_tokens": 676,
"size": 2446
} |
/****************************************************************************
* *
* Author : lukasz.iwaszkiewicz@gmail.com *
* ~~~~~~~~ *
* License : see COPYING file for details. *
* ~~~~~~~~~ *
****************************************************************************/
#pragma once
#include "Condition.h"
#include <gsl/gsl>
/**
* Sequence is like AndCondition, but inputs must fulfill conditions in order.
*/
template <typename EventT = LIB_STATE_MACHINE_DEFAULT_EVENT_TYPE> class SequenceCondition : public Condition<EventT> {
public:
using EventType = EventT;
SequenceCondition (Condition<EventT> *a, Condition<EventT> *b) : a (a), b (b) {}
virtual ~SequenceCondition () = default;
bool getResult () const override { return a->getResult () && b->getResult (); }
void reset () override
{
a->reset ();
b->reset ();
}
bool check (EventType &event, EventType &retainedEvent) const override
{
if (!a->getResult ()) {
a->check (event, retainedEvent);
}
if (a->getResult () && !b->getResult ()) {
b->check (event, retainedEvent);
}
return getResult ();
}
private:
gsl::not_null <Condition<EventType>*> a;
gsl::not_null <Condition<EventType>*> b;
};
template <typename EventT = LIB_STATE_MACHINE_DEFAULT_EVENT_TYPE> SequenceCondition<EventT> *seq (Condition<EventT> *a, Condition<EventT> *b)
{
return new SequenceCondition<EventT> (a, b);
}
| {
"alphanum_fraction": 0.4391534392,
"avg_line_length": 35.6603773585,
"ext": "h",
"hexsha": "27318c6a3ceed87547d9b973ff28cbba91aba217",
"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": "6e6accc3085bd2d5ea130665a9618b16fea38980",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "iwasz/libstatemachine",
"max_forks_repo_path": "src/SequenceCondition.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "6e6accc3085bd2d5ea130665a9618b16fea38980",
"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": "iwasz/libstatemachine",
"max_issues_repo_path": "src/SequenceCondition.h",
"max_line_length": 141,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "6e6accc3085bd2d5ea130665a9618b16fea38980",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "iwasz/libstatemachine",
"max_stars_repo_path": "src/SequenceCondition.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 337,
"size": 1890
} |
#include "ccv.h"
#include "ccv_internal.h"
#include <sys/time.h>
#ifdef HAVE_GSL
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
#endif
#ifdef USE_OPENMP
#include <omp.h>
#endif
const ccv_bbf_param_t ccv_bbf_default_params = {
.interval = 5,
.min_neighbors = 2,
.accurate = 1,
.flags = 0,
.size = {
24,
24,
},
};
#define _ccv_width_padding(x) (((x) + 3) & -4)
static inline int _ccv_run_bbf_feature(ccv_bbf_feature_t *feature, int *step, unsigned char **u8)
{
#define pf_at(i) (*(u8[feature->pz[i]] + feature->px[i] + feature->py[i] * step[feature->pz[i]]))
#define nf_at(i) (*(u8[feature->nz[i]] + feature->nx[i] + feature->ny[i] * step[feature->nz[i]]))
unsigned char pmin = pf_at(0), nmax = nf_at(0);
/* check if every point in P > every point in N, and take a shortcut */
if (pmin <= nmax)
return 0;
int i;
for (i = 1; i < feature->size; i++)
{
if (feature->pz[i] >= 0)
{
int p = pf_at(i);
if (p < pmin)
{
if (p <= nmax)
return 0;
pmin = p;
}
}
if (feature->nz[i] >= 0)
{
int n = nf_at(i);
if (n > nmax)
{
if (pmin <= n)
return 0;
nmax = n;
}
}
}
#undef pf_at
#undef nf_at
return 1;
}
static int _ccv_read_bbf_stage_classifier(const char *file, ccv_bbf_stage_classifier_t *classifier)
{
FILE *r = fopen(file, "r");
if (r == 0)
return -1;
int stat = 0;
stat |= fscanf(r, "%d", &classifier->count);
union {
float fl;
int i;
} fli;
stat |= fscanf(r, "%d", &fli.i);
classifier->threshold = fli.fl;
classifier->feature = (ccv_bbf_feature_t *)ccmalloc(classifier->count * sizeof(ccv_bbf_feature_t));
classifier->alpha = (float *)ccmalloc(classifier->count * 2 * sizeof(float));
int i, j;
for (i = 0; i < classifier->count; i++)
{
stat |= fscanf(r, "%d", &classifier->feature[i].size);
for (j = 0; j < classifier->feature[i].size; j++)
{
stat |= fscanf(r, "%d %d %d", &classifier->feature[i].px[j], &classifier->feature[i].py[j], &classifier->feature[i].pz[j]);
stat |= fscanf(r, "%d %d %d", &classifier->feature[i].nx[j], &classifier->feature[i].ny[j], &classifier->feature[i].nz[j]);
}
union {
float fl;
int i;
} flia, flib;
stat |= fscanf(r, "%d %d", &flia.i, &flib.i);
classifier->alpha[i * 2] = flia.fl;
classifier->alpha[i * 2 + 1] = flib.fl;
}
fclose(r);
return 0;
}
#ifdef HAVE_GSL
static unsigned int _ccv_bbf_time_measure()
{
struct timeval tv;
gettimeofday(&tv, 0);
return tv.tv_sec * 1000000 + tv.tv_usec;
}
#define less_than(a, b, aux) ((a) < (b))
CCV_IMPLEMENT_QSORT(_ccv_sort_32f, float, less_than)
#undef less_than
static void _ccv_bbf_eval_data(ccv_bbf_stage_classifier_t *classifier, unsigned char **posdata, int posnum, unsigned char **negdata, int negnum, ccv_size_t size, float *peval, float *neval)
{
int i, j;
int steps[] = {_ccv_width_padding(size.width),
_ccv_width_padding(size.width >> 1),
_ccv_width_padding(size.width >> 2)};
int isizs0 = steps[0] * size.height;
int isizs01 = isizs0 + steps[1] * (size.height >> 1);
for (i = 0; i < posnum; i++)
{
unsigned char *u8[] = {posdata[i], posdata[i] + isizs0, posdata[i] + isizs01};
float sum = 0;
float *alpha = classifier->alpha;
ccv_bbf_feature_t *feature = classifier->feature;
for (j = 0; j < classifier->count; ++j, alpha += 2, ++feature)
sum += alpha[_ccv_run_bbf_feature(feature, steps, u8)];
peval[i] = sum;
}
for (i = 0; i < negnum; i++)
{
unsigned char *u8[] = {negdata[i], negdata[i] + isizs0, negdata[i] + isizs01};
float sum = 0;
float *alpha = classifier->alpha;
ccv_bbf_feature_t *feature = classifier->feature;
for (j = 0; j < classifier->count; ++j, alpha += 2, ++feature)
sum += alpha[_ccv_run_bbf_feature(feature, steps, u8)];
neval[i] = sum;
}
}
static int _ccv_prune_positive_data(ccv_bbf_classifier_cascade_t *cascade, unsigned char **posdata, int posnum, ccv_size_t size)
{
float *peval = (float *)ccmalloc(posnum * sizeof(float));
int i, j, k, rpos = posnum;
for (i = 0; i < cascade->count; i++)
{
_ccv_bbf_eval_data(cascade->stage_classifier + i, posdata, rpos, 0, 0, size, peval, 0);
k = 0;
for (j = 0; j < rpos; j++)
if (peval[j] >= cascade->stage_classifier[i].threshold)
{
posdata[k] = posdata[j];
++k;
}
else
{
ccfree(posdata[j]);
}
rpos = k;
}
ccfree(peval);
return rpos;
}
static int _ccv_prepare_background_data(ccv_bbf_classifier_cascade_t *cascade, char **bgfiles, int bgnum, unsigned char **negdata, int negnum)
{
int t, i, j, k, q;
int negperbg;
int negtotal = 0;
int steps[] = {_ccv_width_padding(cascade->size.width),
_ccv_width_padding(cascade->size.width >> 1),
_ccv_width_padding(cascade->size.width >> 2)};
int isizs0 = steps[0] * cascade->size.height;
int isizs1 = steps[1] * (cascade->size.height >> 1);
int isizs2 = steps[2] * (cascade->size.height >> 2);
int *idcheck = (int *)ccmalloc(negnum * sizeof(int));
gsl_rng_env_setup();
gsl_rng *rng = gsl_rng_alloc(gsl_rng_default);
gsl_rng_set(rng, (unsigned long int)idcheck);
ccv_size_t imgsz = cascade->size;
int rneg = negtotal;
for (t = 0; negtotal < negnum; t++)
{
PRINT(CCV_CLI_INFO, "preparing negative data ... 0%%");
for (i = 0; i < bgnum; i++)
{
negperbg = (t < 2) ? (negnum - negtotal) / (bgnum - i) + 1 : negnum - negtotal;
ccv_dense_matrix_t *image = 0;
ccv_read(bgfiles[i], &image, CCV_IO_GRAY | CCV_IO_ANY_FILE);
assert((image->type & CCV_C1) && (image->type & CCV_8U));
if (image == 0)
{
PRINT(CCV_CLI_ERROR, "\n%s file corrupted\n", bgfiles[i]);
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);
ccv_bbf_param_t params = {.interval = 3, .min_neighbors = 0, .accurate = 1, .flags = 0, .size = cascade->size};
ccv_array_t *detected = ccv_bbf_detect_objects(image, &cascade, 1, params);
memset(idcheck, 0, ccv_min(detected->rnum, negperbg) * sizeof(int));
for (j = 0; j < ccv_min(detected->rnum, negperbg); j++)
{
int r = gsl_rng_uniform_int(rng, detected->rnum);
int flag = 1;
ccv_rect_t *rect = (ccv_rect_t *)ccv_array_get(detected, r);
while (flag)
{
flag = 0;
for (k = 0; k < j; k++)
if (r == idcheck[k])
{
flag = 1;
r = gsl_rng_uniform_int(rng, detected->rnum);
break;
}
rect = (ccv_rect_t *)ccv_array_get(detected, r);
if ((rect->x < 0) || (rect->y < 0) || (rect->width + rect->x > image->cols) || (rect->height + rect->y > image->rows))
{
flag = 1;
r = gsl_rng_uniform_int(rng, detected->rnum);
}
}
idcheck[j] = r;
ccv_dense_matrix_t *temp = 0;
ccv_dense_matrix_t *imgs0 = 0;
ccv_dense_matrix_t *imgs1 = 0;
ccv_dense_matrix_t *imgs2 = 0;
ccv_slice(image, (ccv_matrix_t **)&temp, 0, rect->y, rect->x, rect->height, rect->width);
ccv_resample(temp, &imgs0, 0, imgsz.height, imgsz.width, CCV_INTER_AREA);
assert(imgs0->step == steps[0]);
ccv_matrix_free(temp);
ccv_sample_down(imgs0, &imgs1, 0, 0, 0);
assert(imgs1->step == steps[1]);
ccv_sample_down(imgs1, &imgs2, 0, 0, 0);
assert(imgs2->step == steps[2]);
negdata[negtotal] = (unsigned char *)ccmalloc(isizs0 + isizs1 + isizs2);
unsigned char *u8s0 = negdata[negtotal];
unsigned char *u8s1 = negdata[negtotal] + isizs0;
unsigned char *u8s2 = negdata[negtotal] + isizs0 + isizs1;
unsigned char *u8[] = {u8s0, u8s1, u8s2};
memcpy(u8s0, imgs0->data.u8, imgs0->rows * imgs0->step);
ccv_matrix_free(imgs0);
memcpy(u8s1, imgs1->data.u8, imgs1->rows * imgs1->step);
ccv_matrix_free(imgs1);
memcpy(u8s2, imgs2->data.u8, imgs2->rows * imgs2->step);
ccv_matrix_free(imgs2);
flag = 1;
ccv_bbf_stage_classifier_t *classifier = cascade->stage_classifier;
for (k = 0; k < cascade->count; ++k, ++classifier)
{
float sum = 0;
float *alpha = classifier->alpha;
ccv_bbf_feature_t *feature = classifier->feature;
for (q = 0; q < classifier->count; ++q, alpha += 2, ++feature)
sum += alpha[_ccv_run_bbf_feature(feature, steps, u8)];
if (sum < classifier->threshold)
{
flag = 0;
break;
}
}
if (!flag)
ccfree(negdata[negtotal]);
else
{
++negtotal;
if (negtotal >= negnum)
break;
}
}
ccv_array_free(detected);
ccv_matrix_free(image);
ccv_drain_cache();
PRINT(CCV_CLI_INFO, "\rpreparing negative data ... %2d%%", 100 * negtotal / negnum);
fflush(0);
if (negtotal >= negnum)
break;
}
if (rneg == negtotal)
break;
rneg = negtotal;
PRINT(CCV_CLI_INFO, "\nentering additional round %d\n", t + 1);
}
gsl_rng_free(rng);
ccfree(idcheck);
ccv_drain_cache();
PRINT(CCV_CLI_INFO, "\n");
return negtotal;
}
static void _ccv_prepare_positive_data(ccv_dense_matrix_t **posimg, unsigned char **posdata, ccv_size_t size, int posnum)
{
PRINT(CCV_CLI_INFO, "preparing positive data ... 0%%");
int i;
for (i = 0; i < posnum; i++)
{
ccv_dense_matrix_t *imgs0 = posimg[i];
ccv_dense_matrix_t *imgs1 = 0;
ccv_dense_matrix_t *imgs2 = 0;
assert((imgs0->type & CCV_C1) && (imgs0->type & CCV_8U) && imgs0->rows == size.height && imgs0->cols == size.width);
ccv_sample_down(imgs0, &imgs1, 0, 0, 0);
ccv_sample_down(imgs1, &imgs2, 0, 0, 0);
int isizs0 = imgs0->rows * imgs0->step;
int isizs1 = imgs1->rows * imgs1->step;
int isizs2 = imgs2->rows * imgs2->step;
posdata[i] = (unsigned char *)ccmalloc(isizs0 + isizs1 + isizs2);
memcpy(posdata[i], imgs0->data.u8, isizs0);
memcpy(posdata[i] + isizs0, imgs1->data.u8, isizs1);
memcpy(posdata[i] + isizs0 + isizs1, imgs2->data.u8, isizs2);
PRINT(CCV_CLI_INFO, "\rpreparing positive data ... %2d%%", 100 * (i + 1) / posnum);
fflush(0);
ccv_matrix_free(imgs1);
ccv_matrix_free(imgs2);
}
ccv_drain_cache();
PRINT(CCV_CLI_INFO, "\n");
}
typedef struct
{
double fitness;
int pk, nk;
int age;
double error;
ccv_bbf_feature_t feature;
} ccv_bbf_gene_t;
static inline void _ccv_bbf_genetic_fitness(ccv_bbf_gene_t *gene)
{
gene->fitness = (1 - gene->error) * exp(-0.01 * gene->age) * exp((gene->pk + gene->nk) * log(1.015));
}
static inline int _ccv_bbf_exist_gene_feature(ccv_bbf_gene_t *gene, int x, int y, int z)
{
int i;
for (i = 0; i < gene->pk; i++)
if (z == gene->feature.pz[i] && x == gene->feature.px[i] && y == gene->feature.py[i])
return 1;
for (i = 0; i < gene->nk; i++)
if (z == gene->feature.nz[i] && x == gene->feature.nx[i] && y == gene->feature.ny[i])
return 1;
return 0;
}
static inline void _ccv_bbf_randomize_gene(gsl_rng *rng, ccv_bbf_gene_t *gene, int *rows, int *cols)
{
int i;
do
{
gene->pk = gsl_rng_uniform_int(rng, CCV_BBF_POINT_MAX - 1) + 1;
gene->nk = gsl_rng_uniform_int(rng, CCV_BBF_POINT_MAX - 1) + 1;
} while (gene->pk + gene->nk < CCV_BBF_POINT_MIN); /* a hard restriction of at least 3 points have to be examed */
gene->feature.size = ccv_max(gene->pk, gene->nk);
gene->age = 0;
for (i = 0; i < CCV_BBF_POINT_MAX; i++)
{
gene->feature.pz[i] = -1;
gene->feature.nz[i] = -1;
}
int x, y, z;
for (i = 0; i < gene->pk; i++)
{
do
{
z = gsl_rng_uniform_int(rng, 3);
x = gsl_rng_uniform_int(rng, cols[z]);
y = gsl_rng_uniform_int(rng, rows[z]);
} while (_ccv_bbf_exist_gene_feature(gene, x, y, z));
gene->feature.pz[i] = z;
gene->feature.px[i] = x;
gene->feature.py[i] = y;
}
for (i = 0; i < gene->nk; i++)
{
do
{
z = gsl_rng_uniform_int(rng, 3);
x = gsl_rng_uniform_int(rng, cols[z]);
y = gsl_rng_uniform_int(rng, rows[z]);
} while (_ccv_bbf_exist_gene_feature(gene, x, y, z));
gene->feature.nz[i] = z;
gene->feature.nx[i] = x;
gene->feature.ny[i] = y;
}
}
static inline double _ccv_bbf_error_rate(ccv_bbf_feature_t *feature, unsigned char **posdata, int posnum, unsigned char **negdata, int negnum, ccv_size_t size, double *pw, double *nw)
{
int i;
int steps[] = {_ccv_width_padding(size.width),
_ccv_width_padding(size.width >> 1),
_ccv_width_padding(size.width >> 2)};
int isizs0 = steps[0] * size.height;
int isizs01 = isizs0 + steps[1] * (size.height >> 1);
double error = 0;
for (i = 0; i < posnum; i++)
{
unsigned char *u8[] = {posdata[i], posdata[i] + isizs0, posdata[i] + isizs01};
if (!_ccv_run_bbf_feature(feature, steps, u8))
error += pw[i];
}
for (i = 0; i < negnum; i++)
{
unsigned char *u8[] = {negdata[i], negdata[i] + isizs0, negdata[i] + isizs01};
if (_ccv_run_bbf_feature(feature, steps, u8))
error += nw[i];
}
return error;
}
#define less_than(fit1, fit2, aux) ((fit1).fitness >= (fit2).fitness)
static CCV_IMPLEMENT_QSORT(_ccv_bbf_genetic_qsort, ccv_bbf_gene_t, less_than)
#undef less_than
static ccv_bbf_feature_t _ccv_bbf_genetic_optimize(unsigned char **posdata, int posnum, unsigned char **negdata, int negnum, int ftnum, ccv_size_t size, double *pw, double *nw)
{
ccv_bbf_feature_t best;
/* seed (random method) */
gsl_rng_env_setup();
gsl_rng *rng = gsl_rng_alloc(gsl_rng_default);
union {
unsigned long int li;
double db;
} dbli;
dbli.db = pw[0] + nw[0];
gsl_rng_set(rng, dbli.li);
int i, j;
int pnum = ftnum * 100;
assert(pnum > 0);
ccv_bbf_gene_t *gene = (ccv_bbf_gene_t *)ccmalloc(pnum * sizeof(ccv_bbf_gene_t));
int rows[] = {size.height, size.height >> 1, size.height >> 2};
int cols[] = {size.width, size.width >> 1, size.width >> 2};
for (i = 0; i < pnum; i++)
_ccv_bbf_randomize_gene(rng, &gene[i], rows, cols);
unsigned int timer = _ccv_bbf_time_measure();
#ifdef USE_OPENMP
#pragma omp parallel for private(i) schedule(dynamic)
#endif
for (i = 0; i < pnum; i++)
gene[i].error = _ccv_bbf_error_rate(&gene[i].feature, posdata, posnum, negdata, negnum, size, pw, nw);
timer = _ccv_bbf_time_measure() - timer;
for (i = 0; i < pnum; i++)
_ccv_bbf_genetic_fitness(&gene[i]);
double best_err = 1;
int rnum = ftnum * 39; /* number of randomize */
int mnum = ftnum * 40; /* number of mutation */
int hnum = ftnum * 20; /* number of hybrid */
/* iteration stop crit : best no change in 40 iterations */
int it = 0, t;
for (t = 0; it < 40; ++it, ++t)
{
int min_id = 0;
double min_err = gene[0].error;
for (i = 1; i < pnum; i++)
if (gene[i].error < min_err)
{
min_id = i;
min_err = gene[i].error;
}
min_err = gene[min_id].error = _ccv_bbf_error_rate(&gene[min_id].feature, posdata, posnum, negdata, negnum, size, pw, nw);
if (min_err < best_err)
{
best_err = min_err;
memcpy(&best, &gene[min_id].feature, sizeof(best));
PRINT(CCV_CLI_INFO, "best bbf feature with error %f\n|-size: %d\n|-positive point: ", best_err, best.size);
for (i = 0; i < best.size; i++)
PRINT(CCV_CLI_INFO, "(%d %d %d), ", best.px[i], best.py[i], best.pz[i]);
PRINT(CCV_CLI_INFO, "\n|-negative point: ");
for (i = 0; i < best.size; i++)
PRINT(CCV_CLI_INFO, "(%d %d %d), ", best.nx[i], best.ny[i], best.nz[i]);
PRINT(CCV_CLI_INFO, "\n");
it = 0;
}
PRINT(CCV_CLI_INFO, "minimum error achieved in round %d(%d) : %f with %d ms\n", t, it, min_err, timer / 1000);
_ccv_bbf_genetic_qsort(gene, pnum, 0);
for (i = 0; i < ftnum; i++)
++gene[i].age;
for (i = ftnum; i < ftnum + mnum; i++)
{
int parent = gsl_rng_uniform_int(rng, ftnum);
memcpy(gene + i, gene + parent, sizeof(ccv_bbf_gene_t));
/* three mutation strategy : 1. add, 2. remove, 3. refine */
int pnm, pn = gsl_rng_uniform_int(rng, 2);
int *pnk[] = {&gene[i].pk, &gene[i].nk};
int *pnx[] = {gene[i].feature.px, gene[i].feature.nx};
int *pny[] = {gene[i].feature.py, gene[i].feature.ny};
int *pnz[] = {gene[i].feature.pz, gene[i].feature.nz};
int x, y, z;
int victim, decay = 1;
do
{
switch (gsl_rng_uniform_int(rng, 3))
{
case 0: /* add */
if (gene[i].pk == CCV_BBF_POINT_MAX && gene[i].nk == CCV_BBF_POINT_MAX)
break;
while (*pnk[pn] + 1 > CCV_BBF_POINT_MAX)
pn = gsl_rng_uniform_int(rng, 2);
do
{
z = gsl_rng_uniform_int(rng, 3);
x = gsl_rng_uniform_int(rng, cols[z]);
y = gsl_rng_uniform_int(rng, rows[z]);
} while (_ccv_bbf_exist_gene_feature(&gene[i], x, y, z));
pnz[pn][*pnk[pn]] = z;
pnx[pn][*pnk[pn]] = x;
pny[pn][*pnk[pn]] = y;
++(*pnk[pn]);
gene[i].feature.size = ccv_max(gene[i].pk, gene[i].nk);
decay = gene[i].age = 0;
break;
case 1: /* remove */
if (gene[i].pk + gene[i].nk <= CCV_BBF_POINT_MIN) /* at least 3 points have to be examed */
break;
while (*pnk[pn] - 1 <= 0) // || *pnk[pn] + *pnk[!pn] - 1 < CCV_BBF_POINT_MIN)
pn = gsl_rng_uniform_int(rng, 2);
victim = gsl_rng_uniform_int(rng, *pnk[pn]);
for (j = victim; j < *pnk[pn] - 1; j++)
{
pnz[pn][j] = pnz[pn][j + 1];
pnx[pn][j] = pnx[pn][j + 1];
pny[pn][j] = pny[pn][j + 1];
}
pnz[pn][*pnk[pn] - 1] = -1;
--(*pnk[pn]);
gene[i].feature.size = ccv_max(gene[i].pk, gene[i].nk);
decay = gene[i].age = 0;
break;
case 2: /* refine */
pnm = gsl_rng_uniform_int(rng, *pnk[pn]);
do
{
z = gsl_rng_uniform_int(rng, 3);
x = gsl_rng_uniform_int(rng, cols[z]);
y = gsl_rng_uniform_int(rng, rows[z]);
} while (_ccv_bbf_exist_gene_feature(&gene[i], x, y, z));
pnz[pn][pnm] = z;
pnx[pn][pnm] = x;
pny[pn][pnm] = y;
decay = gene[i].age = 0;
break;
}
} while (decay);
}
for (i = ftnum + mnum; i < ftnum + mnum + hnum; i++)
{
/* hybrid strategy: taking positive points from dad, negative points from mum */
int dad, mum;
do
{
dad = gsl_rng_uniform_int(rng, ftnum);
mum = gsl_rng_uniform_int(rng, ftnum);
} while (dad == mum || gene[dad].pk + gene[mum].nk < CCV_BBF_POINT_MIN); /* at least 3 points have to be examed */
for (j = 0; j < CCV_BBF_POINT_MAX; j++)
{
gene[i].feature.pz[j] = -1;
gene[i].feature.nz[j] = -1;
}
gene[i].pk = gene[dad].pk;
for (j = 0; j < gene[i].pk; j++)
{
gene[i].feature.pz[j] = gene[dad].feature.pz[j];
gene[i].feature.px[j] = gene[dad].feature.px[j];
gene[i].feature.py[j] = gene[dad].feature.py[j];
}
gene[i].nk = gene[mum].nk;
for (j = 0; j < gene[i].nk; j++)
{
gene[i].feature.nz[j] = gene[mum].feature.nz[j];
gene[i].feature.nx[j] = gene[mum].feature.nx[j];
gene[i].feature.ny[j] = gene[mum].feature.ny[j];
}
gene[i].feature.size = ccv_max(gene[i].pk, gene[i].nk);
gene[i].age = 0;
}
for (i = ftnum + mnum + hnum; i < ftnum + mnum + hnum + rnum; i++)
_ccv_bbf_randomize_gene(rng, &gene[i], rows, cols);
timer = _ccv_bbf_time_measure();
#ifdef USE_OPENMP
#pragma omp parallel for private(i) schedule(dynamic)
#endif
for (i = 0; i < pnum; i++)
gene[i].error = _ccv_bbf_error_rate(&gene[i].feature, posdata, posnum, negdata, negnum, size, pw, nw);
timer = _ccv_bbf_time_measure() - timer;
for (i = 0; i < pnum; i++)
_ccv_bbf_genetic_fitness(&gene[i]);
}
ccfree(gene);
gsl_rng_free(rng);
return best;
}
#define less_than(fit1, fit2, aux) ((fit1).error < (fit2).error)
static CCV_IMPLEMENT_QSORT(_ccv_bbf_best_qsort, ccv_bbf_gene_t, less_than)
#undef less_than
static ccv_bbf_gene_t _ccv_bbf_best_gene(ccv_bbf_gene_t *gene, int pnum, int point_min, unsigned char **posdata, int posnum, unsigned char **negdata, int negnum, ccv_size_t size, double *pw, double *nw)
{
int i;
unsigned int timer = _ccv_bbf_time_measure();
#ifdef USE_OPENMP
#pragma omp parallel for private(i) schedule(dynamic)
#endif
for (i = 0; i < pnum; i++)
gene[i].error = _ccv_bbf_error_rate(&gene[i].feature, posdata, posnum, negdata, negnum, size, pw, nw);
timer = _ccv_bbf_time_measure() - timer;
_ccv_bbf_best_qsort(gene, pnum, 0);
int min_id = 0;
double min_err = gene[0].error;
for (i = 0; i < pnum; i++)
if (gene[i].nk + gene[i].pk >= point_min)
{
min_id = i;
min_err = gene[i].error;
break;
}
PRINT(CCV_CLI_INFO, "local best bbf feature with error %f\n|-size: %d\n|-positive point: ", min_err, gene[min_id].feature.size);
for (i = 0; i < gene[min_id].feature.size; i++)
PRINT(CCV_CLI_INFO, "(%d %d %d), ", gene[min_id].feature.px[i], gene[min_id].feature.py[i], gene[min_id].feature.pz[i]);
PRINT(CCV_CLI_INFO, "\n|-negative point: ");
for (i = 0; i < gene[min_id].feature.size; i++)
PRINT(CCV_CLI_INFO, "(%d %d %d), ", gene[min_id].feature.nx[i], gene[min_id].feature.ny[i], gene[min_id].feature.nz[i]);
PRINT(CCV_CLI_INFO, "\nthe computation takes %d ms\n", timer / 1000);
return gene[min_id];
}
static ccv_bbf_feature_t _ccv_bbf_convex_optimize(unsigned char **posdata, int posnum, unsigned char **negdata, int negnum, ccv_bbf_feature_t *best_feature, ccv_size_t size, double *pw, double *nw)
{
ccv_bbf_gene_t best_gene;
/* seed (random method) */
gsl_rng_env_setup();
gsl_rng *rng = gsl_rng_alloc(gsl_rng_default);
union {
unsigned long int li;
double db;
} dbli;
dbli.db = pw[0] + nw[0];
gsl_rng_set(rng, dbli.li);
int i, j, k, q, p, g, t;
int rows[] = {size.height, size.height >> 1, size.height >> 2};
int cols[] = {size.width, size.width >> 1, size.width >> 2};
int pnum = rows[0] * cols[0] + rows[1] * cols[1] + rows[2] * cols[2];
ccv_bbf_gene_t *gene = (ccv_bbf_gene_t *)ccmalloc((pnum * (CCV_BBF_POINT_MAX * 2 + 1) * 2 + CCV_BBF_POINT_MAX * 2 + 1) * sizeof(ccv_bbf_gene_t));
if (best_feature == 0)
{
/* bootstrapping the best feature, start from two pixels, one for positive, one for negative
* the bootstrapping process go like this: first, it will assign a random pixel as positive
* and enumerate every possible pixel as negative, and pick the best one. Then, enumerate every
* possible pixel as positive, and pick the best one, until it converges */
memset(&best_gene, 0, sizeof(ccv_bbf_gene_t));
for (i = 0; i < CCV_BBF_POINT_MAX; i++)
best_gene.feature.pz[i] = best_gene.feature.nz[i] = -1;
best_gene.pk = 1;
best_gene.nk = 0;
best_gene.feature.size = 1;
best_gene.feature.pz[0] = gsl_rng_uniform_int(rng, 3);
best_gene.feature.px[0] = gsl_rng_uniform_int(rng, cols[best_gene.feature.pz[0]]);
best_gene.feature.py[0] = gsl_rng_uniform_int(rng, rows[best_gene.feature.pz[0]]);
for (t = 0;; ++t)
{
g = 0;
if (t % 2 == 0)
{
for (i = 0; i < 3; i++)
for (j = 0; j < cols[i]; j++)
for (k = 0; k < rows[i]; k++)
if (i != best_gene.feature.pz[0] || j != best_gene.feature.px[0] || k != best_gene.feature.py[0])
{
gene[g] = best_gene;
gene[g].pk = gene[g].nk = 1;
gene[g].feature.nz[0] = i;
gene[g].feature.nx[0] = j;
gene[g].feature.ny[0] = k;
g++;
}
}
else
{
for (i = 0; i < 3; i++)
for (j = 0; j < cols[i]; j++)
for (k = 0; k < rows[i]; k++)
if (i != best_gene.feature.nz[0] || j != best_gene.feature.nx[0] || k != best_gene.feature.ny[0])
{
gene[g] = best_gene;
gene[g].pk = gene[g].nk = 1;
gene[g].feature.pz[0] = i;
gene[g].feature.px[0] = j;
gene[g].feature.py[0] = k;
g++;
}
}
PRINT(CCV_CLI_INFO, "bootstrapping round : %d\n", t);
ccv_bbf_gene_t local_gene = _ccv_bbf_best_gene(gene, g, 2, posdata, posnum, negdata, negnum, size, pw, nw);
if (local_gene.error >= best_gene.error - 1e-10)
break;
best_gene = local_gene;
}
}
else
{
best_gene.feature = *best_feature;
best_gene.pk = best_gene.nk = best_gene.feature.size;
for (i = 0; i < CCV_BBF_POINT_MAX; i++)
if (best_feature->pz[i] == -1)
{
best_gene.pk = i;
break;
}
for (i = 0; i < CCV_BBF_POINT_MAX; i++)
if (best_feature->nz[i] == -1)
{
best_gene.nk = i;
break;
}
}
/* after bootstrapping, the float search technique will do the following permutations:
* a). add a new point to positive or negative
* b). remove a point from positive or negative
* c). move an existing point in positive or negative to another position
* the three rules applied exhaustively, no heuristic used. */
for (t = 0;; ++t)
{
g = 0;
for (i = 0; i < 3; i++)
for (j = 0; j < cols[i]; j++)
for (k = 0; k < rows[i]; k++)
if (!_ccv_bbf_exist_gene_feature(&best_gene, j, k, i))
{
/* add positive point */
if (best_gene.pk < CCV_BBF_POINT_MAX - 1)
{
gene[g] = best_gene;
gene[g].feature.pz[gene[g].pk] = i;
gene[g].feature.px[gene[g].pk] = j;
gene[g].feature.py[gene[g].pk] = k;
gene[g].pk++;
gene[g].feature.size = ccv_max(gene[g].pk, gene[g].nk);
g++;
}
/* add negative point */
if (best_gene.nk < CCV_BBF_POINT_MAX - 1)
{
gene[g] = best_gene;
gene[g].feature.nz[gene[g].nk] = i;
gene[g].feature.nx[gene[g].nk] = j;
gene[g].feature.ny[gene[g].nk] = k;
gene[g].nk++;
gene[g].feature.size = ccv_max(gene[g].pk, gene[g].nk);
g++;
}
/* refine positive point */
for (q = 0; q < best_gene.pk; q++)
{
gene[g] = best_gene;
gene[g].feature.pz[q] = i;
gene[g].feature.px[q] = j;
gene[g].feature.py[q] = k;
g++;
}
/* add positive point, remove negative point */
if (best_gene.pk < CCV_BBF_POINT_MAX - 1 && best_gene.nk > 1)
{
for (q = 0; q < best_gene.nk; q++)
{
gene[g] = best_gene;
gene[g].feature.pz[gene[g].pk] = i;
gene[g].feature.px[gene[g].pk] = j;
gene[g].feature.py[gene[g].pk] = k;
gene[g].pk++;
for (p = q; p < best_gene.nk - 1; p++)
{
gene[g].feature.nz[p] = gene[g].feature.nz[p + 1];
gene[g].feature.nx[p] = gene[g].feature.nx[p + 1];
gene[g].feature.ny[p] = gene[g].feature.ny[p + 1];
}
gene[g].feature.nz[gene[g].nk - 1] = -1;
gene[g].nk--;
gene[g].feature.size = ccv_max(gene[g].pk, gene[g].nk);
g++;
}
}
/* refine negative point */
for (q = 0; q < best_gene.nk; q++)
{
gene[g] = best_gene;
gene[g].feature.nz[q] = i;
gene[g].feature.nx[q] = j;
gene[g].feature.ny[q] = k;
g++;
}
/* add negative point, remove positive point */
if (best_gene.pk > 1 && best_gene.nk < CCV_BBF_POINT_MAX - 1)
{
for (q = 0; q < best_gene.pk; q++)
{
gene[g] = best_gene;
gene[g].feature.nz[gene[g].nk] = i;
gene[g].feature.nx[gene[g].nk] = j;
gene[g].feature.ny[gene[g].nk] = k;
gene[g].nk++;
for (p = q; p < best_gene.pk - 1; p++)
{
gene[g].feature.pz[p] = gene[g].feature.pz[p + 1];
gene[g].feature.px[p] = gene[g].feature.px[p + 1];
gene[g].feature.py[p] = gene[g].feature.py[p + 1];
}
gene[g].feature.pz[gene[g].pk - 1] = -1;
gene[g].pk--;
gene[g].feature.size = ccv_max(gene[g].pk, gene[g].nk);
g++;
}
}
}
if (best_gene.pk > 1)
for (q = 0; q < best_gene.pk; q++)
{
gene[g] = best_gene;
for (i = q; i < best_gene.pk - 1; i++)
{
gene[g].feature.pz[i] = gene[g].feature.pz[i + 1];
gene[g].feature.px[i] = gene[g].feature.px[i + 1];
gene[g].feature.py[i] = gene[g].feature.py[i + 1];
}
gene[g].feature.pz[gene[g].pk - 1] = -1;
gene[g].pk--;
gene[g].feature.size = ccv_max(gene[g].pk, gene[g].nk);
g++;
}
if (best_gene.nk > 1)
for (q = 0; q < best_gene.nk; q++)
{
gene[g] = best_gene;
for (i = q; i < best_gene.nk - 1; i++)
{
gene[g].feature.nz[i] = gene[g].feature.nz[i + 1];
gene[g].feature.nx[i] = gene[g].feature.nx[i + 1];
gene[g].feature.ny[i] = gene[g].feature.ny[i + 1];
}
gene[g].feature.nz[gene[g].nk - 1] = -1;
gene[g].nk--;
gene[g].feature.size = ccv_max(gene[g].pk, gene[g].nk);
g++;
}
gene[g] = best_gene;
g++;
PRINT(CCV_CLI_INFO, "float search round : %d\n", t);
ccv_bbf_gene_t local_gene = _ccv_bbf_best_gene(gene, g, CCV_BBF_POINT_MIN, posdata, posnum, negdata, negnum, size, pw, nw);
if (local_gene.error >= best_gene.error - 1e-10)
break;
best_gene = local_gene;
}
ccfree(gene);
gsl_rng_free(rng);
return best_gene.feature;
}
static int _ccv_write_bbf_stage_classifier(const char *file, ccv_bbf_stage_classifier_t *classifier)
{
FILE *w = fopen(file, "wb");
if (w == 0)
return -1;
fprintf(w, "%d\n", classifier->count);
union {
float fl;
int i;
} fli;
fli.fl = classifier->threshold;
fprintf(w, "%d\n", fli.i);
int i, j;
for (i = 0; i < classifier->count; i++)
{
fprintf(w, "%d\n", classifier->feature[i].size);
for (j = 0; j < classifier->feature[i].size; j++)
{
fprintf(w, "%d %d %d\n", classifier->feature[i].px[j], classifier->feature[i].py[j], classifier->feature[i].pz[j]);
fprintf(w, "%d %d %d\n", classifier->feature[i].nx[j], classifier->feature[i].ny[j], classifier->feature[i].nz[j]);
}
union {
float fl;
int i;
} flia, flib;
flia.fl = classifier->alpha[i * 2];
flib.fl = classifier->alpha[i * 2 + 1];
fprintf(w, "%d %d\n", flia.i, flib.i);
}
fclose(w);
return 0;
}
static int _ccv_read_background_data(const char *file, unsigned char **negdata, int *negnum, ccv_size_t size)
{
int stat = 0;
FILE *r = fopen(file, "rb");
if (r == 0)
return -1;
stat |= fread(negnum, sizeof(int), 1, r);
int i;
int isizs012 = _ccv_width_padding(size.width) * size.height +
_ccv_width_padding(size.width >> 1) * (size.height >> 1) +
_ccv_width_padding(size.width >> 2) * (size.height >> 2);
for (i = 0; i < *negnum; i++)
{
negdata[i] = (unsigned char *)ccmalloc(isizs012);
stat |= fread(negdata[i], 1, isizs012, r);
}
fclose(r);
return 0;
}
static int _ccv_write_background_data(const char *file, unsigned char **negdata, int negnum, ccv_size_t size)
{
FILE *w = fopen(file, "w");
if (w == 0)
return -1;
fwrite(&negnum, sizeof(int), 1, w);
int i;
int isizs012 = _ccv_width_padding(size.width) * size.height +
_ccv_width_padding(size.width >> 1) * (size.height >> 1) +
_ccv_width_padding(size.width >> 2) * (size.height >> 2);
for (i = 0; i < negnum; i++)
fwrite(negdata[i], 1, isizs012, w);
fclose(w);
return 0;
}
static int _ccv_resume_bbf_cascade_training_state(const char *file, int *i, int *k, int *bg, double *pw, double *nw, int posnum, int negnum)
{
int stat = 0;
FILE *r = fopen(file, "r");
if (r == 0)
return -1;
stat |= fscanf(r, "%d %d %d", i, k, bg);
int j;
union {
double db;
int i[2];
} dbi;
for (j = 0; j < posnum; j++)
{
stat |= fscanf(r, "%d %d", &dbi.i[0], &dbi.i[1]);
pw[j] = dbi.db;
}
for (j = 0; j < negnum; j++)
{
stat |= fscanf(r, "%d %d", &dbi.i[0], &dbi.i[1]);
nw[j] = dbi.db;
}
fclose(r);
return 0;
}
static int _ccv_save_bbf_cacade_training_state(const char *file, int i, int k, int bg, double *pw, double *nw, int posnum, int negnum)
{
FILE *w = fopen(file, "w");
if (w == 0)
return -1;
fprintf(w, "%d %d %d\n", i, k, bg);
int j;
union {
double db;
int i[2];
} dbi;
for (j = 0; j < posnum; ++j)
{
dbi.db = pw[j];
fprintf(w, "%d %d ", dbi.i[0], dbi.i[1]);
}
fprintf(w, "\n");
for (j = 0; j < negnum; ++j)
{
dbi.db = nw[j];
fprintf(w, "%d %d ", dbi.i[0], dbi.i[1]);
}
fprintf(w, "\n");
fclose(w);
return 0;
}
void ccv_bbf_classifier_cascade_new(ccv_dense_matrix_t **posimg, int posnum, char **bgfiles, int bgnum, int negnum, ccv_size_t size, const char *dir, ccv_bbf_new_param_t params)
{
int i, j, k;
/* allocate memory for usage */
ccv_bbf_classifier_cascade_t *cascade = (ccv_bbf_classifier_cascade_t *)ccmalloc(sizeof(ccv_bbf_classifier_cascade_t));
cascade->count = 0;
cascade->size = size;
cascade->stage_classifier = (ccv_bbf_stage_classifier_t *)ccmalloc(sizeof(ccv_bbf_stage_classifier_t));
unsigned char **posdata = (unsigned char **)ccmalloc(posnum * sizeof(unsigned char *));
unsigned char **negdata = (unsigned char **)ccmalloc(negnum * sizeof(unsigned char *));
double *pw = (double *)ccmalloc(posnum * sizeof(double));
double *nw = (double *)ccmalloc(negnum * sizeof(double));
float *peval = (float *)ccmalloc(posnum * sizeof(float));
float *neval = (float *)ccmalloc(negnum * sizeof(float));
double inv_balance_k = 1. / params.balance_k;
/* balance factor k, and weighted with 0.01 */
params.balance_k *= 0.01;
inv_balance_k *= 0.01;
int steps[] = {_ccv_width_padding(cascade->size.width),
_ccv_width_padding(cascade->size.width >> 1),
_ccv_width_padding(cascade->size.width >> 2)};
int isizs0 = steps[0] * cascade->size.height;
int isizs01 = isizs0 + steps[1] * (cascade->size.height >> 1);
i = 0;
k = 0;
int bg = 0;
int cacheK = 10;
/* state resume code */
char buf[1024];
sprintf(buf, "%s/stat.txt", dir);
_ccv_resume_bbf_cascade_training_state(buf, &i, &k, &bg, pw, nw, posnum, negnum);
if (i > 0)
{
cascade->count = i;
ccfree(cascade->stage_classifier);
cascade->stage_classifier = (ccv_bbf_stage_classifier_t *)ccmalloc(i * sizeof(ccv_bbf_stage_classifier_t));
for (j = 0; j < i; j++)
{
sprintf(buf, "%s/stage-%d.txt", dir, j);
_ccv_read_bbf_stage_classifier(buf, &cascade->stage_classifier[j]);
}
}
if (k > 0)
cacheK = k;
int rpos, rneg = 0;
if (bg)
{
sprintf(buf, "%s/negs.txt", dir);
_ccv_read_background_data(buf, negdata, &rneg, cascade->size);
}
for (; i < params.layer; i++)
{
if (!bg)
{
rneg = _ccv_prepare_background_data(cascade, bgfiles, bgnum, negdata, negnum);
/* save state of background data */
sprintf(buf, "%s/negs.txt", dir);
_ccv_write_background_data(buf, negdata, rneg, cascade->size);
bg = 1;
}
double totalw;
/* save state of cascade : level, weight etc. */
sprintf(buf, "%s/stat.txt", dir);
_ccv_save_bbf_cacade_training_state(buf, i, k, bg, pw, nw, posnum, negnum);
ccv_bbf_stage_classifier_t classifier;
if (k > 0)
{
/* resume state of classifier */
sprintf(buf, "%s/stage-%d.txt", dir, i);
_ccv_read_bbf_stage_classifier(buf, &classifier);
}
else
{
/* initialize classifier */
for (j = 0; j < posnum; j++)
pw[j] = params.balance_k;
for (j = 0; j < rneg; j++)
nw[j] = inv_balance_k;
classifier.count = k;
classifier.threshold = 0;
classifier.feature = (ccv_bbf_feature_t *)ccmalloc(cacheK * sizeof(ccv_bbf_feature_t));
classifier.alpha = (float *)ccmalloc(cacheK * 2 * sizeof(float));
}
_ccv_prepare_positive_data(posimg, posdata, cascade->size, posnum);
rpos = _ccv_prune_positive_data(cascade, posdata, posnum, cascade->size);
PRINT(CCV_CLI_INFO, "%d postivie data and %d negative data in training\n", rpos, rneg);
/* reweight to 1.00 */
totalw = 0;
for (j = 0; j < rpos; j++)
totalw += pw[j];
for (j = 0; j < rneg; j++)
totalw += nw[j];
for (j = 0; j < rpos; j++)
pw[j] = pw[j] / totalw;
for (j = 0; j < rneg; j++)
nw[j] = nw[j] / totalw;
for (;; k++)
{
/* get overall true-positive, false-positive rate and threshold */
double tp = 0, fp = 0, etp = 0, efp = 0;
_ccv_bbf_eval_data(&classifier, posdata, rpos, negdata, rneg, cascade->size, peval, neval);
_ccv_sort_32f(peval, rpos, 0);
classifier.threshold = peval[(int)((1. - params.pos_crit) * rpos)] - 1e-6;
for (j = 0; j < rpos; j++)
{
if (peval[j] >= 0)
++tp;
if (peval[j] >= classifier.threshold)
++etp;
}
tp /= rpos;
etp /= rpos;
for (j = 0; j < rneg; j++)
{
if (neval[j] >= 0)
++fp;
if (neval[j] >= classifier.threshold)
++efp;
}
fp /= rneg;
efp /= rneg;
PRINT(CCV_CLI_INFO, "stage classifier real TP rate : %f, FP rate : %f\n", tp, fp);
PRINT(CCV_CLI_INFO, "stage classifier TP rate : %f, FP rate : %f at threshold : %f\n", etp, efp, classifier.threshold);
if (k > 0)
{
/* save classifier state */
sprintf(buf, "%s/stage-%d.txt", dir, i);
_ccv_write_bbf_stage_classifier(buf, &classifier);
sprintf(buf, "%s/stat.txt", dir);
_ccv_save_bbf_cacade_training_state(buf, i, k, bg, pw, nw, posnum, negnum);
}
if (etp > params.pos_crit && efp < params.neg_crit)
break;
/* TODO: more post-process is needed in here */
/* select the best feature in current distribution through genetic algorithm optimization */
ccv_bbf_feature_t best;
if (params.optimizer == CCV_BBF_GENETIC_OPT)
{
best = _ccv_bbf_genetic_optimize(posdata, rpos, negdata, rneg, params.feature_number, cascade->size, pw, nw);
}
else if (params.optimizer == CCV_BBF_FLOAT_OPT)
{
best = _ccv_bbf_convex_optimize(posdata, rpos, negdata, rneg, 0, cascade->size, pw, nw);
}
else
{
best = _ccv_bbf_genetic_optimize(posdata, rpos, negdata, rneg, params.feature_number, cascade->size, pw, nw);
best = _ccv_bbf_convex_optimize(posdata, rpos, negdata, rneg, &best, cascade->size, pw, nw);
}
double err = _ccv_bbf_error_rate(&best, posdata, rpos, negdata, rneg, cascade->size, pw, nw);
double rw = (1 - err) / err;
totalw = 0;
/* reweight */
for (j = 0; j < rpos; j++)
{
unsigned char *u8[] = {posdata[j], posdata[j] + isizs0, posdata[j] + isizs01};
if (!_ccv_run_bbf_feature(&best, steps, u8))
pw[j] *= rw;
pw[j] *= params.balance_k;
totalw += pw[j];
}
for (j = 0; j < rneg; j++)
{
unsigned char *u8[] = {negdata[j], negdata[j] + isizs0, negdata[j] + isizs01};
if (_ccv_run_bbf_feature(&best, steps, u8))
nw[j] *= rw;
nw[j] *= inv_balance_k;
totalw += nw[j];
}
for (j = 0; j < rpos; j++)
pw[j] = pw[j] / totalw;
for (j = 0; j < rneg; j++)
nw[j] = nw[j] / totalw;
double c = log(rw);
PRINT(CCV_CLI_INFO, "coefficient of feature %d: %f\n", k + 1, c);
classifier.count = k + 1;
/* resizing classifier */
if (k >= cacheK)
{
ccv_bbf_feature_t *feature = (ccv_bbf_feature_t *)ccmalloc(cacheK * 2 * sizeof(ccv_bbf_feature_t));
memcpy(feature, classifier.feature, cacheK * sizeof(ccv_bbf_feature_t));
ccfree(classifier.feature);
float *alpha = (float *)ccmalloc(cacheK * 4 * sizeof(float));
memcpy(alpha, classifier.alpha, cacheK * 2 * sizeof(float));
ccfree(classifier.alpha);
classifier.feature = feature;
classifier.alpha = alpha;
cacheK *= 2;
}
/* setup new feature */
classifier.feature[k] = best;
classifier.alpha[k * 2] = -c;
classifier.alpha[k * 2 + 1] = c;
}
cascade->count = i + 1;
ccv_bbf_stage_classifier_t *stage_classifier = (ccv_bbf_stage_classifier_t *)ccmalloc(cascade->count * sizeof(ccv_bbf_stage_classifier_t));
memcpy(stage_classifier, cascade->stage_classifier, i * sizeof(ccv_bbf_stage_classifier_t));
ccfree(cascade->stage_classifier);
stage_classifier[i] = classifier;
cascade->stage_classifier = stage_classifier;
k = 0;
bg = 0;
for (j = 0; j < rpos; j++)
ccfree(posdata[j]);
for (j = 0; j < rneg; j++)
ccfree(negdata[j]);
}
ccfree(neval);
ccfree(peval);
ccfree(nw);
ccfree(pw);
ccfree(negdata);
ccfree(posdata);
ccfree(cascade);
}
#else
void ccv_bbf_classifier_cascade_new(ccv_dense_matrix_t **posimg, int posnum, char **bgfiles, int bgnum, int negnum, ccv_size_t size, const char *dir, ccv_bbf_new_param_t params)
{
fprintf(stderr, " ccv_bbf_classifier_cascade_new requires libgsl support, please compile ccv with libgsl.\n");
}
#endif
static int _ccv_is_equal(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;
int distance = (int)(r1->rect.width * 0.25 + 0.5);
return r2->rect.x <= r1->rect.x + distance &&
r2->rect.x >= r1->rect.x - distance &&
r2->rect.y <= r1->rect.y + distance &&
r2->rect.y >= r1->rect.y - distance &&
r2->rect.width <= (int)(r1->rect.width * 1.5 + 0.5) &&
(int)(r2->rect.width * 1.5 + 0.5) >= r1->rect.width;
}
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;
int distance = (int)(r1->rect.width * 0.25 + 0.5);
return r2->classification.id == r1->classification.id &&
r2->rect.x <= r1->rect.x + distance &&
r2->rect.x >= r1->rect.x - distance &&
r2->rect.y <= r1->rect.y + distance &&
r2->rect.y >= r1->rect.y - distance &&
r2->rect.width <= (int)(r1->rect.width * 1.5 + 0.5) &&
(int)(r2->rect.width * 1.5 + 0.5) >= r1->rect.width;
}
ccv_array_t *ccv_bbf_detect_objects(ccv_dense_matrix_t *a, ccv_bbf_classifier_cascade_t **_cascade, int count, ccv_bbf_param_t params)
{
int hr = a->rows / params.size.height;
int wr = a->cols / params.size.width;
double scale = pow(2., 1. / (params.interval + 1.));
int next = params.interval + 1;
int scale_upto = (int)(log((double)ccv_min(hr, wr)) / log(scale));
ccv_dense_matrix_t **pyr = (ccv_dense_matrix_t **)alloca((scale_upto + next * 2) * 4 * sizeof(ccv_dense_matrix_t *));
memset(pyr, 0, (scale_upto + next * 2) * 4 * sizeof(ccv_dense_matrix_t *));
if (params.size.height != _cascade[0]->size.height || params.size.width != _cascade[0]->size.width)
ccv_resample(a, &pyr[0], 0, a->rows * _cascade[0]->size.height / params.size.height, a->cols * _cascade[0]->size.width / params.size.width, CCV_INTER_AREA);
else
pyr[0] = a;
int i, j, k, t, x, y, q;
for (i = 1; i < ccv_min(params.interval + 1, scale_upto + next * 2); i++)
ccv_resample(pyr[0], &pyr[i * 4], 0, (int)(pyr[0]->rows / pow(scale, i)), (int)(pyr[0]->cols / pow(scale, i)), CCV_INTER_AREA);
for (i = next; i < scale_upto + next * 2; i++)
ccv_sample_down(pyr[i * 4 - next * 4], &pyr[i * 4], 0, 0, 0);
if (params.accurate)
for (i = next * 2; i < scale_upto + next * 2; i++)
{
ccv_sample_down(pyr[i * 4 - next * 4], &pyr[i * 4 + 1], 0, 1, 0);
ccv_sample_down(pyr[i * 4 - next * 4], &pyr[i * 4 + 2], 0, 0, 1);
ccv_sample_down(pyr[i * 4 - next * 4], &pyr[i * 4 + 3], 0, 1, 1);
}
ccv_array_t *idx_seq;
ccv_array_t *seq = ccv_array_new(sizeof(ccv_comp_t), 64, 0);
ccv_array_t *seq2 = ccv_array_new(sizeof(ccv_comp_t), 64, 0);
ccv_array_t *result_seq = ccv_array_new(sizeof(ccv_comp_t), 64, 0);
/* detect in multi scale */
for (t = 0; t < count; t++)
{
ccv_bbf_classifier_cascade_t *cascade = _cascade[t];
float scale_x = (float)params.size.width / (float)cascade->size.width;
float scale_y = (float)params.size.height / (float)cascade->size.height;
ccv_array_clear(seq);
for (i = 0; i < scale_upto; i++)
{
int dx[] = {0, 1, 0, 1};
int dy[] = {0, 0, 1, 1};
int i_rows = pyr[i * 4 + next * 8]->rows - (cascade->size.height >> 2);
int steps[] = {pyr[i * 4]->step, pyr[i * 4 + next * 4]->step, pyr[i * 4 + next * 8]->step};
int i_cols = pyr[i * 4 + next * 8]->cols - (cascade->size.width >> 2);
int paddings[] = {pyr[i * 4]->step * 4 - i_cols * 4,
pyr[i * 4 + next * 4]->step * 2 - i_cols * 2,
pyr[i * 4 + next * 8]->step - i_cols};
for (q = 0; q < (params.accurate ? 4 : 1); q++)
{
unsigned char *u8[] = {pyr[i * 4]->data.u8 + dx[q] * 2 + dy[q] * pyr[i * 4]->step * 2, pyr[i * 4 + next * 4]->data.u8 + dx[q] + dy[q] * pyr[i * 4 + next * 4]->step, pyr[i * 4 + next * 8 + q]->data.u8};
for (y = 0; y < i_rows; y++)
{
for (x = 0; x < i_cols; x++)
{
float sum;
int flag = 1;
ccv_bbf_stage_classifier_t *classifier = cascade->stage_classifier;
for (j = 0; j < cascade->count; ++j, ++classifier)
{
sum = 0;
float *alpha = classifier->alpha;
ccv_bbf_feature_t *feature = classifier->feature;
for (k = 0; k < classifier->count; ++k, alpha += 2, ++feature)
sum += alpha[_ccv_run_bbf_feature(feature, steps, u8)];
if (sum < classifier->threshold)
{
flag = 0;
break;
}
}
if (flag)
{
ccv_comp_t comp;
comp.rect = ccv_rect((int)((x * 4 + dx[q] * 2) * scale_x + 0.5), (int)((y * 4 + dy[q] * 2) * scale_y + 0.5), (int)(cascade->size.width * scale_x + 0.5), (int)(cascade->size.height * scale_y + 0.5));
comp.neighbors = 1;
comp.classification.id = t;
comp.classification.confidence = sum;
ccv_array_push(seq, &comp);
}
u8[0] += 4;
u8[1] += 2;
u8[2] += 1;
}
u8[0] += paddings[0];
u8[1] += paddings[1];
u8[2] += paddings[2];
}
}
scale_x *= scale;
scale_y *= scale;
}
/* the following code from OpenCV's haar feature implementation */
if (params.min_neighbors == 0)
{
for (i = 0; i < seq->rnum; i++)
{
ccv_comp_t *comp = (ccv_comp_t *)ccv_array_get(seq, i);
ccv_array_push(result_seq, comp);
}
}
else
{
idx_seq = 0;
ccv_array_clear(seq2);
// group retrieved rectangles in order to filter out noise
int ncomp = ccv_array_group(seq, &idx_seq, _ccv_is_equal_same_class, 0);
ccv_comp_t *comps = (ccv_comp_t *)ccmalloc((ncomp + 1) * sizeof(ccv_comp_t));
memset(comps, 0, (ncomp + 1) * sizeof(ccv_comp_t));
// count number of neighbors
for (i = 0; i < seq->rnum; i++)
{
ccv_comp_t r1 = *(ccv_comp_t *)ccv_array_get(seq, i);
int idx = *(int *)ccv_array_get(idx_seq, i);
if (comps[idx].neighbors == 0)
comps[idx].classification.confidence = r1.classification.confidence;
++comps[idx].neighbors;
comps[idx].rect.x += r1.rect.x;
comps[idx].rect.y += r1.rect.y;
comps[idx].rect.width += r1.rect.width;
comps[idx].rect.height += r1.rect.height;
comps[idx].classification.id = r1.classification.id;
comps[idx].classification.confidence = ccv_max(comps[idx].classification.confidence, r1.classification.confidence);
}
// calculate average bounding box
for (i = 0; i < ncomp; i++)
{
int n = comps[i].neighbors;
if (n >= params.min_neighbors)
{
ccv_comp_t comp;
comp.rect.x = (comps[i].rect.x * 2 + n) / (2 * n);
comp.rect.y = (comps[i].rect.y * 2 + n) / (2 * n);
comp.rect.width = (comps[i].rect.width * 2 + n) / (2 * n);
comp.rect.height = (comps[i].rect.height * 2 + n) / (2 * n);
comp.neighbors = comps[i].neighbors;
comp.classification.id = comps[i].classification.id;
comp.classification.confidence = comps[i].classification.confidence;
ccv_array_push(seq2, &comp);
}
}
// filter out small face rectangles inside large face rectangles
for (i = 0; i < seq2->rnum; i++)
{
ccv_comp_t r1 = *(ccv_comp_t *)ccv_array_get(seq2, i);
int flag = 1;
for (j = 0; j < seq2->rnum; j++)
{
ccv_comp_t r2 = *(ccv_comp_t *)ccv_array_get(seq2, j);
int distance = (int)(r2.rect.width * 0.25 + 0.5);
if (i != j &&
r1.classification.id == r2.classification.id &&
r1.rect.x >= r2.rect.x - distance &&
r1.rect.y >= r2.rect.y - distance &&
r1.rect.x + r1.rect.width <= r2.rect.x + r2.rect.width + distance &&
r1.rect.y + r1.rect.height <= r2.rect.y + r2.rect.height + distance &&
(r2.neighbors > ccv_max(3, r1.neighbors) || r1.neighbors < 3))
{
flag = 0;
break;
}
}
if (flag)
ccv_array_push(result_seq, &r1);
}
ccv_array_free(idx_seq);
ccfree(comps);
}
}
ccv_array_free(seq);
ccv_array_free(seq2);
ccv_array_t *result_seq2;
/* the following code from OpenCV's haar feature implementation */
if (params.flags & CCV_BBF_NO_NESTED)
{
result_seq2 = ccv_array_new(sizeof(ccv_comp_t), 64, 0);
idx_seq = 0;
// group retrieved rectangles in order to filter out noise
int ncomp = ccv_array_group(result_seq, &idx_seq, _ccv_is_equal, 0);
ccv_comp_t *comps = (ccv_comp_t *)ccmalloc((ncomp + 1) * sizeof(ccv_comp_t));
memset(comps, 0, (ncomp + 1) * sizeof(ccv_comp_t));
// count number of neighbors
for (i = 0; i < result_seq->rnum; i++)
{
ccv_comp_t r1 = *(ccv_comp_t *)ccv_array_get(result_seq, i);
int idx = *(int *)ccv_array_get(idx_seq, i);
if (comps[idx].neighbors == 0 || comps[idx].classification.confidence < r1.classification.confidence)
{
comps[idx].classification.confidence = r1.classification.confidence;
comps[idx].neighbors = 1;
comps[idx].rect = r1.rect;
comps[idx].classification.id = r1.classification.id;
}
}
// calculate average bounding box
for (i = 0; i < ncomp; i++)
if (comps[i].neighbors)
ccv_array_push(result_seq2, &comps[i]);
ccv_array_free(result_seq);
ccfree(comps);
}
else
{
result_seq2 = result_seq;
}
for (i = 1; i < scale_upto + next * 2; i++)
ccv_matrix_free(pyr[i * 4]);
if (params.accurate)
for (i = next * 2; i < scale_upto + next * 2; i++)
{
ccv_matrix_free(pyr[i * 4 + 1]);
ccv_matrix_free(pyr[i * 4 + 2]);
ccv_matrix_free(pyr[i * 4 + 3]);
}
if (params.size.height != _cascade[0]->size.height || params.size.width != _cascade[0]->size.width)
ccv_matrix_free(pyr[0]);
return result_seq2;
}
ccv_bbf_classifier_cascade_t *ccv_bbf_read_classifier_cascade(const char *directory)
{
char buf[1024];
sprintf(buf, "%s/cascade.txt", directory);
int s, i;
FILE *r = fopen(buf, "r");
if (r == 0)
return 0;
ccv_bbf_classifier_cascade_t *cascade = (ccv_bbf_classifier_cascade_t *)ccmalloc(sizeof(ccv_bbf_classifier_cascade_t));
s = fscanf(r, "%d %d %d", &cascade->count, &cascade->size.width, &cascade->size.height);
assert(s > 0);
cascade->stage_classifier = (ccv_bbf_stage_classifier_t *)ccmalloc(cascade->count * sizeof(ccv_bbf_stage_classifier_t));
for (i = 0; i < cascade->count; i++)
{
sprintf(buf, "%s/stage-%d.txt", directory, i);
if (_ccv_read_bbf_stage_classifier(buf, &cascade->stage_classifier[i]) < 0)
{
cascade->count = i;
break;
}
}
fclose(r);
return cascade;
}
ccv_bbf_classifier_cascade_t *ccv_bbf_classifier_cascade_read_binary(char *s)
{
int i;
ccv_bbf_classifier_cascade_t *cascade = (ccv_bbf_classifier_cascade_t *)ccmalloc(sizeof(ccv_bbf_classifier_cascade_t));
memcpy(&cascade->count, s, sizeof(cascade->count));
s += sizeof(cascade->count);
memcpy(&cascade->size.width, s, sizeof(cascade->size.width));
s += sizeof(cascade->size.width);
memcpy(&cascade->size.height, s, sizeof(cascade->size.height));
s += sizeof(cascade->size.height);
ccv_bbf_stage_classifier_t *classifier = cascade->stage_classifier = (ccv_bbf_stage_classifier_t *)ccmalloc(cascade->count * sizeof(ccv_bbf_stage_classifier_t));
for (i = 0; i < cascade->count; i++, classifier++)
{
memcpy(&classifier->count, s, sizeof(classifier->count));
s += sizeof(classifier->count);
memcpy(&classifier->threshold, s, sizeof(classifier->threshold));
s += sizeof(classifier->threshold);
classifier->feature = (ccv_bbf_feature_t *)ccmalloc(classifier->count * sizeof(ccv_bbf_feature_t));
classifier->alpha = (float *)ccmalloc(classifier->count * 2 * sizeof(float));
memcpy(classifier->feature, s, classifier->count * sizeof(ccv_bbf_feature_t));
s += classifier->count * sizeof(ccv_bbf_feature_t);
memcpy(classifier->alpha, s, classifier->count * 2 * sizeof(float));
s += classifier->count * 2 * sizeof(float);
}
return cascade;
}
int ccv_bbf_classifier_cascade_write_binary(ccv_bbf_classifier_cascade_t *cascade, char *s, int slen)
{
int i;
int len = sizeof(cascade->count) + sizeof(cascade->size.width) + sizeof(cascade->size.height);
ccv_bbf_stage_classifier_t *classifier = cascade->stage_classifier;
for (i = 0; i < cascade->count; i++, classifier++)
len += sizeof(classifier->count) + sizeof(classifier->threshold) + classifier->count * sizeof(ccv_bbf_feature_t) + classifier->count * 2 * sizeof(float);
if (slen >= len)
{
memcpy(s, &cascade->count, sizeof(cascade->count));
s += sizeof(cascade->count);
memcpy(s, &cascade->size.width, sizeof(cascade->size.width));
s += sizeof(cascade->size.width);
memcpy(s, &cascade->size.height, sizeof(cascade->size.height));
s += sizeof(cascade->size.height);
classifier = cascade->stage_classifier;
for (i = 0; i < cascade->count; i++, classifier++)
{
memcpy(s, &classifier->count, sizeof(classifier->count));
s += sizeof(classifier->count);
memcpy(s, &classifier->threshold, sizeof(classifier->threshold));
s += sizeof(classifier->threshold);
memcpy(s, classifier->feature, classifier->count * sizeof(ccv_bbf_feature_t));
s += classifier->count * sizeof(ccv_bbf_feature_t);
memcpy(s, classifier->alpha, classifier->count * 2 * sizeof(float));
s += classifier->count * 2 * sizeof(float);
}
}
return len;
}
void ccv_bbf_classifier_cascade_free(ccv_bbf_classifier_cascade_t *cascade)
{
int i;
for (i = 0; i < cascade->count; ++i)
{
ccfree(cascade->stage_classifier[i].feature);
ccfree(cascade->stage_classifier[i].alpha);
}
ccfree(cascade->stage_classifier);
ccfree(cascade);
} | {
"alphanum_fraction": 0.5692611324,
"avg_line_length": 36.0769230769,
"ext": "c",
"hexsha": "f0094b3fa8f4a7e4d814d68bdf38335f31edb112",
"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": "f82d35040455ff35c2475e76a43426dfccd0ad39",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "byurhanbeyzat/vsc-material-theme",
"max_forks_repo_path": "test/source.cc",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "f82d35040455ff35c2475e76a43426dfccd0ad39",
"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": "byurhanbeyzat/vsc-material-theme",
"max_issues_repo_path": "test/source.cc",
"max_line_length": 212,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "f82d35040455ff35c2475e76a43426dfccd0ad39",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "byurhanbeyzat/vsc-material-theme",
"max_stars_repo_path": "test/source.c",
"max_stars_repo_stars_event_max_datetime": "2019-04-16T12:05:26.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-04-16T12:05:26.000Z",
"num_tokens": 18105,
"size": 56749
} |
/* linalg/test_ldlt.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_blas.h>
#include <gsl/gsl_linalg.h>
#include <gsl/gsl_rng.h>
static double
test_ldlt_norm1(const gsl_matrix * m)
{
const size_t N = m->size2;
double value = 0.0;
size_t j;
for (j = 0; j < N; ++j)
{
gsl_vector_const_view v = gsl_matrix_const_column(m, j);
double sum = gsl_blas_dasum(&v.vector);
value = GSL_MAX(value, sum);
}
return value;
}
static int
test_ldlt_decomp_eps(const gsl_matrix * m, const double expected_rcond,
const double eps, const char * desc)
{
int s = 0;
size_t i, j, N = m->size2;
gsl_matrix * V = gsl_matrix_alloc(N, N);
gsl_matrix * A = gsl_matrix_alloc(N, N);
gsl_matrix * L = gsl_matrix_calloc(N, N);
gsl_matrix * LT = gsl_matrix_calloc(N, N);
gsl_vector_view d;
gsl_matrix_memcpy(V, m);
s += gsl_linalg_ldlt_decomp(V);
/* compute L and LT */
gsl_matrix_tricpy(CblasLower, CblasUnit, L, V);
d = gsl_matrix_diagonal(L);
gsl_vector_set_all(&d.vector, 1.0);
gsl_matrix_transpose_tricpy(CblasLower, CblasNonUnit, LT, L);
/* compute L <- L D */
d = gsl_matrix_diagonal(V);
for (i = 0; i < N; ++i)
{
gsl_vector_view c = gsl_matrix_column(L, i);
double di = gsl_vector_get(&d.vector, i);
gsl_vector_scale(&c.vector, di);
}
/* compute A = L D LT */
gsl_blas_dgemm (CblasNoTrans, CblasNoTrans, 1.0, L, LT, 0.0, A);
for (i = 0; i < N; i++)
{
for (j = 0; j < N; j++)
{
double Aij = gsl_matrix_get(A, i, j);
double mij = gsl_matrix_get(m, i, j);
gsl_test_rel(Aij, mij, eps,
"%s: (%3lu,%3lu)[%lu,%lu]: %22.18g %22.18g\n",
desc, N, N, i, j, Aij, mij);
}
}
if (expected_rcond > 0)
{
gsl_vector *work = gsl_vector_alloc(3 * N);
double rcond;
gsl_linalg_ldlt_rcond(V, &rcond, work);
gsl_test_rel(rcond, expected_rcond, 1.0e-6,
"%s rcond: (%3lu,%3lu): %22.18g %22.18g\n",
desc, N, N, rcond, expected_rcond);
gsl_vector_free(work);
}
gsl_matrix_free(V);
gsl_matrix_free(A);
gsl_matrix_free(L);
gsl_matrix_free(LT);
return s;
}
static int
test_ldlt_decomp(gsl_rng * r)
{
int s = 0;
const size_t N_max = 50;
size_t N;
for (N = 1; N <= N_max; ++N)
{
gsl_matrix * m = gsl_matrix_alloc(N, N);
create_posdef_matrix(m, r);
test_ldlt_decomp_eps(m, -1.0, 1.0e2 * N * GSL_DBL_EPSILON, "ldlt_decomp random");
if (N <= 12)
{
double expected_rcond = -1.0;
if (hilb_rcond[N - 1] > 1.0e-12)
expected_rcond = hilb_rcond[N - 1];
create_hilbert_matrix2(m);
test_ldlt_decomp_eps(m, expected_rcond, N * GSL_DBL_EPSILON, "ldlt_decomp hilbert");
}
gsl_matrix_free(m);
}
return s;
}
int
test_ldlt_solve_eps(const gsl_matrix * m, const gsl_vector * rhs,
const gsl_vector * sol, const double eps,
const char * desc)
{
int s = 0;
size_t i, N = m->size1;
gsl_matrix * u = gsl_matrix_alloc(N, N);
gsl_vector * x = gsl_vector_calloc(N);
gsl_matrix_memcpy(u, m);
s += gsl_linalg_ldlt_decomp(u);
s += gsl_linalg_ldlt_solve(u, rhs, x);
for (i = 0; i < N; i++)
{
double xi = gsl_vector_get(x, i);
double yi = gsl_vector_get(sol, i);
gsl_test_rel(xi, yi, eps,
"%s: %3lu[%lu]: %22.18g %22.18g\n",
desc, N, i, xi, yi);
}
gsl_vector_free(x);
gsl_matrix_free(u);
return s;
}
static int
test_ldlt_solve(gsl_rng * r)
{
int s = 0;
const size_t N_max = 50;
size_t N;
for (N = 1; N <= N_max; ++N)
{
gsl_matrix * m = gsl_matrix_alloc(N, N);
gsl_vector * rhs = gsl_vector_alloc(N);
gsl_vector * sol = gsl_vector_alloc(N);
create_posdef_matrix(m, r);
create_random_vector(sol, r);
gsl_blas_dsymv(CblasLower, 1.0, m, sol, 0.0, rhs);
test_ldlt_solve_eps(m, rhs, sol, 64.0 * N * GSL_DBL_EPSILON, "ldlt_solve random");
if (N <= 3)
{
create_hilbert_matrix2(m);
gsl_blas_dsymv(CblasLower, 1.0, m, sol, 0.0, rhs);
test_ldlt_solve_eps(m, rhs, sol, 1024.0 * N * GSL_DBL_EPSILON, "ldlt_solve hilbert");
}
gsl_matrix_free(m);
gsl_vector_free(rhs);
gsl_vector_free(sol);
}
return s;
}
static int
test_ldlt_band_decomp_eps(const size_t p, const gsl_matrix * m, const double eps, const char * desc)
{
int s = 0;
size_t i, j, N = m->size2;
double rcond, rcond_expected;
gsl_matrix * V = gsl_matrix_alloc(N, p + 1);
gsl_matrix * A = gsl_matrix_alloc(N, N);
gsl_matrix * L = gsl_matrix_calloc(N, N);
gsl_matrix * LT = gsl_matrix_calloc(N, N);
gsl_vector * D = gsl_vector_alloc(N);
gsl_vector * work = gsl_vector_alloc(3 * N);
/* convert m to packed banded format */
symm2band_matrix(p, m, V);
s += gsl_linalg_ldlt_band_decomp(V);
/* compute L and LT */
gsl_linalg_ldlt_band_unpack(V, L, D);
gsl_matrix_transpose_tricpy(CblasLower, CblasNonUnit, LT, L);
/* compute L <- L D */
for (i = 0; i < N; ++i)
{
gsl_vector_view c = gsl_matrix_column(L, i);
double di = gsl_vector_get(D, i);
gsl_vector_scale(&c.vector, di);
}
/* compute A = L D LT */
gsl_blas_dgemm (CblasNoTrans, CblasNoTrans, 1.0, L, LT, 0.0, A);
for (i = 0; i < N; i++)
{
for (j = 0; j < N; j++)
{
double Aij = gsl_matrix_get(A, i, j);
double mij = gsl_matrix_get(m, i, j);
gsl_test_rel(Aij, mij, eps,
"%s: (p=%zu,N=%zu)[%lu,%lu]: %22.18g %22.18g\n",
desc, p, N, i, j, Aij, mij);
}
}
/* test 1-norm calculation */
if (p > 0)
{
double norm1_expected = test_ldlt_norm1(m);
double norm1 = gsl_matrix_get(V, N - 1, p);
gsl_test_rel(norm1, norm1_expected, eps,
"%s: (p=%zu,N=%zu) 1-norm: %22.18g %22.18g\n",
desc, p, N, norm1, norm1_expected);
}
/* test rcond */
gsl_matrix_memcpy(A, m);
s += gsl_linalg_ldlt_decomp(A);
s += gsl_linalg_ldlt_rcond(A, &rcond_expected, work);
s += gsl_linalg_ldlt_band_rcond(V, &rcond, work);
gsl_test_rel(rcond, rcond_expected, eps,
"%s: (p=%zu,N=%zu) rcond: %22.18g %22.18g\n",
desc, p, N, rcond, rcond_expected);
gsl_matrix_free(V);
gsl_matrix_free(A);
gsl_matrix_free(L);
gsl_matrix_free(LT);
gsl_vector_free(D);
gsl_vector_free(work);
return s;
}
static int
test_ldlt_band_decomp(gsl_rng * r)
{
int s = 0;
const size_t N_max = 50;
size_t N, p;
for (N = 1; N <= N_max; ++N)
{
gsl_matrix * m = gsl_matrix_alloc(N, N);
for (p = 0; p < GSL_MIN(N, 10); ++p)
{
create_posdef_band_matrix(p, m, r);
s += test_ldlt_band_decomp_eps(p, m, 1.0e3 * N * GSL_DBL_EPSILON, "ldlt_band_decomp random");
}
gsl_matrix_free(m);
}
return s;
}
int
test_ldlt_band_solve_eps(const size_t p, const gsl_matrix * m, const gsl_vector * rhs,
const gsl_vector * sol, const double eps, const char * desc)
{
int s = 0;
size_t i, N = m->size1;
gsl_matrix * u = gsl_matrix_alloc(N, p + 1);
gsl_vector * x = gsl_vector_alloc(N);
/* convert m to packed banded format */
symm2band_matrix(p, m, u);
s += gsl_linalg_ldlt_band_decomp(u);
s += gsl_linalg_ldlt_band_solve(u, rhs, x);
for (i = 0; i < N; i++)
{
double xi = gsl_vector_get(x, i);
double yi = gsl_vector_get(sol, i);
gsl_test_rel(xi, yi, eps,
"%s: p=%zu N=%zu [%lu]: %22.18g %22.18g\n",
desc, p, N, i, xi, yi);
}
gsl_vector_free(x);
gsl_matrix_free(u);
return s;
}
static int
test_ldlt_band_solve(gsl_rng * r)
{
int s = 0;
const size_t N_max = 50;
size_t N, p;
for (N = 1; N <= N_max; ++N)
{
gsl_matrix * m = gsl_matrix_alloc(N, N);
gsl_vector * rhs = gsl_vector_alloc(N);
gsl_vector * sol = gsl_vector_alloc(N);
for (p = 0; p < GSL_MIN(N, 10); ++p)
{
create_posdef_band_matrix(p, m, r);
create_random_vector(sol, r);
gsl_blas_dsymv(CblasLower, 1.0, m, sol, 0.0, rhs);
test_ldlt_band_solve_eps(p, m, rhs, sol, 64.0 * N * GSL_DBL_EPSILON, "ldlt_band_solve random");
}
gsl_matrix_free(m);
gsl_vector_free(rhs);
gsl_vector_free(sol);
}
return s;
}
| {
"alphanum_fraction": 0.5911696031,
"avg_line_length": 25.2600536193,
"ext": "c",
"hexsha": "f742e72595af01b389afb272d42cee2724826a26",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z",
"max_forks_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "zzpwahaha/Chimera-Control-Trim",
"max_forks_repo_path": "Chimera/3rd_Party/GSL_MSVC/linalg/test_ldlt.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "zzpwahaha/Chimera-Control-Trim",
"max_issues_repo_path": "Chimera/3rd_Party/GSL_MSVC/linalg/test_ldlt.c",
"max_line_length": 105,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "zzpwahaha/Chimera-Control-Trim",
"max_stars_repo_path": "Chimera/3rd_Party/GSL_MSVC/linalg/test_ldlt.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": 2994,
"size": 9422
} |
/*****************************************
Emitting C Generated Code
*******************************************/
#include <cblas.h>
#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>
#include <stdbool.h>
/**************** Snippet ****************/
void Snippet(int x0) {
float x1[3] = { 1.0, 2.0, 3.0 };
float x2[6] = { 1.0, 2.0, 3.0, 4.0, 5.0, 6.0 };
float x3[6] = { 1.0, 2.0, 3.0, 4.0, 5.0, 6.0 };
float* x4 = (float*)malloc(1 * sizeof(float));
int x5 = 0;
while (x5 != 3) {
int x6 = x5;
x4[0] = x4[0] + x1[x6] * x1[x6];
x5 = x5 + 1;
}
int x7 = 0;
while (x7 != 1) {
printf("%f ", x4[x7]);
x7 = x7 + 1;
}
float* x8 = (float*)malloc(2 * sizeof(float));
cblas_sgemv(CblasRowMajor, CblasNoTrans, 2, 3, 1.0, x2, 3, x1, 1, 0.0, x8, 1);
int x9 = 0;
while (x9 != 2) {
printf("%f ", x8[x9]);
x9 = x9 + 1;
}
float* x10 = (float*)malloc(4 * sizeof(float));
cblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, 2, 2, 3, 1.0, x2, 3, x3, 2, 0.0, x10, 2);
int x11 = 0;
while (x11 != 4) {
printf("%f ", x10[x11]);
x11 = x11 + 1;
}
}
/*****************************************
End of C Generated Code
*******************************************/
int main(int argc, char *argv[]) {
if (argc != 2) {
printf("usage: %s <arg>\n", argv[0]);
return 0;
}
Snippet(atoi(argv[1]));
return 0;
}
| {
"alphanum_fraction": 0.444606414,
"avg_line_length": 26.3846153846,
"ext": "c",
"hexsha": "aa664a285934a236c5b0f73fb5c89f6b01a180d6",
"lang": "C",
"max_forks_count": 20,
"max_forks_repo_forks_event_max_datetime": "2022-02-03T04:45:52.000Z",
"max_forks_repo_forks_event_min_datetime": "2016-10-20T12:16:10.000Z",
"max_forks_repo_head_hexsha": "46dcf45b297bb537ce90d9c787dbf3700b47d54c",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "Shangyint/lms-clean",
"max_forks_repo_path": "src/out/transformer/tensor2/dot.check.c",
"max_issues_count": 30,
"max_issues_repo_head_hexsha": "46dcf45b297bb537ce90d9c787dbf3700b47d54c",
"max_issues_repo_issues_event_max_datetime": "2022-01-14T21:22:03.000Z",
"max_issues_repo_issues_event_min_datetime": "2019-09-10T01:17:19.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "Shangyint/lms-clean",
"max_issues_repo_path": "src/out/transformer/tensor2/dot.check.c",
"max_line_length": 98,
"max_stars_count": 50,
"max_stars_repo_head_hexsha": "46dcf45b297bb537ce90d9c787dbf3700b47d54c",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "Shangyint/lms-clean",
"max_stars_repo_path": "src/out/transformer/tensor2/dot.check.c",
"max_stars_repo_stars_event_max_datetime": "2022-03-24T04:14:18.000Z",
"max_stars_repo_stars_event_min_datetime": "2017-04-19T17:19:00.000Z",
"num_tokens": 558,
"size": 1372
} |
/* -*- mode: C; c-basic-offset: 4 -*- */
/* ex: set shiftwidth=4 tabstop=4 expandtab: */
/*
* Copyright (c) 2013, Georgia Tech Research Corporation
* Copyright (c) 2015, Rice University
* Copyright (c) 2018-2019, Colorado School of Mines
* All rights reserved.
*
* Author(s): Neil T. Dantam <ntd@gatech.edu>
* Georgia Tech Humanoid Robotics Lab
* Under Direction of Prof. Mike Stilman <mstilman@cc.gatech.edu>
*
*
* This file is provided under the following "BSD-style" License:
*
*
* Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the following
* conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
*
* * Neither the name of the Rice University nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
#include <nlopt.h>
#include "amino.h"
#include "amino/diffeq.h"
/* static double */
/* s_nlobj_jpinv(unsigned n, const double *q, double *dq, void *vcx) */
/* { */
/* struct kin_solve_cx *cx = (struct kin_solve_cx*)vcx; */
/* void *ptrtop = aa_mem_region_ptr(cx->reg); */
/* struct aa_dvec vq = AA_DVEC_INIT(n,(double*)q,1); */
/* aa_rx_fk_sub(cx->fk, cx->ssg, &vq); */
/* double *E_act = aa_rx_fk_ref(cx->fk, cx->frame); */
/* if( dq ) { */
/* struct aa_dvec v_dq = AA_DVEC_INIT(n,dq,1); */
/* s_ksol_jpinv(cx,q, &v_dq); */
/* aa_dvec_scal(-1,&v_dq); */
/* } */
/* double x = s_serr( E_act, cx->TF_ref->data ); */
/* aa_mem_region_pop(cx->reg, ptrtop); */
/* return x; */
/* } */
static double s_nlobj_dq_fd_helper( void *vcx, const struct aa_dvec *x)
{
struct kin_solve_cx *cx = (struct kin_solve_cx*)vcx;
void *ptrtop = aa_mem_region_ptr(cx->reg);
assert(1 == x->inc);
aa_rx_fk_sub(cx->fk, cx->ssg, x);
double *E_act = aa_rx_fk_ref(cx->fk, cx->frame);
double S_act[8], S_ref[8], S_err[8], S_ln[8];
aa_tf_qutr2duqu(E_act, S_act);
aa_tf_qutr2duqu(cx->TF_ref->data, S_ref);
aa_tf_duqu_cmul(S_act,S_ref,S_err);
aa_tf_duqu_minimize(S_err);
aa_tf_duqu_ln(S_err, S_ln);
double result = aa_la_dot(8,S_ln,S_ln);
aa_mem_region_pop(cx->reg, ptrtop);
return result;
}
AA_API double
aa_rx_ik_opt_err_dqln_fd( void *vcx, const double *q, double *dq )
{
struct kin_solve_cx *cx = (struct kin_solve_cx*)vcx;
size_t n = aa_rx_sg_sub_config_count(cx->ssg);
struct aa_dvec vq = AA_DVEC_INIT(n,(double*)q,1);
double x = s_nlobj_dq_fd_helper(vcx, &vq);
if( dq ) {
struct aa_dvec vdq = AA_DVEC_INIT(n,dq,1);
// TODO: make epsilon a parameter
double eps = 1e-6;
aa_de_grad_fd( s_nlobj_dq_fd_helper, vcx,
&vq, eps, &vdq );
}
return x;
}
static void
mv_block_helper (const double *A, const double *x, double *y)
{
cblas_dgemv(CblasColMajor, CblasTrans, 8, 4,
1, A, 8, x, 1,
0, y, 1);
cblas_dgemv(CblasColMajor, CblasTrans, 4, 4,
1, A, 8, x+4, 1,
0, y+4, 1);
}
static void
duqu_rmul_helper( const double *Sr, const double *x, double *y )
{
double M[8*8];
aa_tf_duqu_matrix_r(Sr,M,8);
mv_block_helper(M, x, y);
}
AA_API double
aa_rx_ik_opt_err_dqln( void *vcx, double *q, double *dq ) {
struct kin_solve_cx *cx = (struct kin_solve_cx*)vcx;
void *ptrtop = aa_mem_region_ptr(cx->reg);
size_t n = aa_rx_sg_sub_config_count(cx->ssg);
struct aa_dvec vq = AA_DVEC_INIT(n,(double*)q,1);
aa_rx_fk_sub(cx->fk, cx->ssg, &vq );
double *E_act = aa_rx_fk_ref(cx->fk, cx->frame);
double S_act[8], S_ref[8], S_err[8], S_ln[8];
aa_tf_qutr2duqu(E_act, S_act);
aa_tf_qutr2duqu(cx->TF_ref->data, S_ref);
aa_tf_duqu_cmul(S_act,S_ref,S_err);
// Apply a negative factor in gradient when we have to minimze the
// error quaternion
int needs_min = (S_err[AA_TF_DUQU_REAL_W] < 0 );
if( needs_min ) {
for( size_t i = 0; i < 8; i ++ ) S_err[i] *= -1;
} else {
}
aa_tf_duqu_ln(S_err, S_ln);
double result = aa_la_dot(8,S_ln,S_ln);
if( dq ) {
if( needs_min ) {
for( size_t i = 0; i < 8; i ++ ) S_ln[i] *= -1;
}
struct aa_dvec v_dq = AA_DVEC_INIT(n,dq,1);
/*
* g_sumsq * J_ln*[S_ref]_r*J_conj*J_S
* -> J_ln^T g_sumsq * [S_ref]_r*J_conj*J_S
* -> [S_ref]_r^T (J_ln^T g_sumsq) *J_conj*J_S
* -> J_conj^T*[S_ref]_r^T (J_ln^T g_sumsq) * J_S
* -> J_S^T J_conj^T * [S_ref]_r^T * J_ln^T g_sumsq
*/
double a[8], b[8], dJ[8*8];
struct aa_dmat vJ_8x8 = AA_DMAT_INIT(8,8,dJ,8);
struct aa_dmat *J_8x8 = &vJ_8x8;
{
struct aa_dmat *J_ln = J_8x8;
aa_tf_duqu_ln_jac(S_err,J_ln);
/*
* struct aa_dvec v_S_ln = AA_DVEC_INIT(8,S_ln,1);
* //aa_dmat_gemv( CblasTrans, 2, J_8x8, &v_S_ln, 0, &va );
*
* Avoid multiplying by the zero block:
*
* J_ln = [J_r 0] J_ln^T = [J_r^T J_d^T]
* [J_d J_r] [ 0 J_r^T]
*
* J_ln^T * del(S_ln^T*S_ln)^T = 2*J_ln^T S_ln
*
* 2*J_ln^T S_ln = 2*[J_r^T J_d^T] (S_ln_r)
* [ 0 J_r^T] (S_ln_d)
*
*/
mv_block_helper(dJ, S_ln, a);
}
/*
* dS/dphi = [S]_R V J
* g [S]_R V J
* -> [S]_R^T g V J
* -> V^T [S]_R^T g J
* -> J^T V [S]_R^T g
*/
duqu_rmul_helper( S_ref, a, b );
aa_tf_duqu_conj1(b);
duqu_rmul_helper( S_act, b, a ); /* TODO: Pure result, some
* extra multiplies here. */
// a is now a pure dual quaternion
{
double c[6];
struct aa_dvec vc = AA_DVEC_INIT(6,c,1);
// Using Twist Jacobian
aa_tf_duqu2pure(a,c);
struct aa_dmat *Jtw = aa_rx_sg_sub_jac_twist_get(cx->ssg, cx->reg, cx->fk);
aa_dmat_gemv( CblasTrans, 1, Jtw, &vc, 0, &v_dq );
// Using Velocity Jacobian
/* aa_tf_cross_a(a+AA_TF_DUQU_DUAL_XYZ,E_act+AA_TF_QUTR_V,a); */
/* aa_tf_duqu2pure(a,c); */
/* struct aa_dmat *J_vel = aa_rx_sg_sub_get_jacobian(cx->ssg,cx->reg,cx->TF); */
/* aa_dmat_gemv( CblasTrans, 1, J_vel, &vc, 0, &v_dq ); */
}
/* { */
/* struct aa_dvec *v_dq_fd = aa_dvec_alloc(cx->reg,n); */
/* double eps = 1e-6; */
/* aa_de_grad_fd( s_nlobj_dq_fd_helper, vcx, */
/* &vq, eps, v_dq_fd ); */
/* printf("--\n"); */
/* printf("needs min: %d\n", needs_min); */
/* printf("ad: "); */
/* aa_dump_vec(stdout,v_dq_fd->data,n); */
/* printf("an: "); */
/* aa_dump_vec(stdout,dq,n); */
/* assert( aa_dvec_ssd(v_dq_fd, &v_dq) < 1e-3 ); */
/* } */
}
aa_mem_region_pop(cx->reg, ptrtop);
return result;
}
static double s_nlobj_qv_fd_trans_helper( void *vcx, const struct aa_dvec *x)
{
struct kin_solve_cx *cx = (struct kin_solve_cx*)vcx;
assert(1 == x->inc);
aa_rx_fk_sub(cx->fk, cx->ssg, x);
double *E_act = aa_rx_fk_ref(cx->fk, cx->frame);
double *v_act = E_act + AA_TF_QUTR_V;
double *E_ref = cx->TF_ref->data;
double *v_ref = E_ref + AA_TF_QUTR_V;
double E_err[7];
double *v_err = E_err + AA_TF_QUTR_V;
for(size_t i = 0; i < 3; i ++ ) v_err[i] = v_act[i] - v_ref[i];
double result = aa_tf_vdot(v_err,v_err);
return result;
}
AA_API double
aa_rx_ik_opt_err_trans_fd( void *vcx, const double *q, double *dq )
{
struct kin_solve_cx *cx = (struct kin_solve_cx*)vcx;
size_t n = aa_rx_sg_sub_config_count(cx->ssg);
struct aa_dvec vq = AA_DVEC_INIT(n,(double*)q,1);
double x = s_nlobj_qv_fd_trans_helper(vcx, &vq);
if( dq ) {
struct aa_dvec vdq = AA_DVEC_INIT(n,dq,1);
// TODO: make epsilon a parameter
double eps = 1e-6;
aa_de_grad_fd( s_nlobj_qv_fd_trans_helper, vcx,
&vq, eps, &vdq );
}
/* fprintf(stdout, "fd error: %2.2f\n", x); */
return x;
}
static double s_nlobj_qv_fd_helper( void *vcx, const struct aa_dvec *x)
{
struct kin_solve_cx *cx = (struct kin_solve_cx*)vcx;
void *ptrtop = aa_mem_region_ptr(cx->reg);
assert(1 == x->inc);
aa_rx_fk_sub(cx->fk, cx->ssg, x);
double *E_act = aa_rx_fk_ref(cx->fk, cx->frame);
double *v_act = E_act + AA_TF_QUTR_V;
double *q_act = E_act + AA_TF_QUTR_Q;
double *E_ref = cx->TF_ref->data;
double *v_ref = E_ref + AA_TF_QUTR_V;
double *q_ref = E_ref + AA_TF_QUTR_Q;
double E_err[7];
double *v_err = E_err + AA_TF_QUTR_V;
double *q_err = E_err + AA_TF_QUTR_Q;
aa_tf_qcmul(q_act,q_ref,q_err);
double q_ln[4];
aa_tf_qminimize(q_err);
aa_tf_duqu_ln(q_err, q_ln);
for(size_t i = 0; i < 3; i ++ ) v_err[i] = v_act[i] - v_ref[i];
double result = ( aa_tf_qdot(q_ln,q_ln)
+
aa_tf_vdot(v_err,v_err) );
aa_mem_region_pop(cx->reg, ptrtop);
return result;
}
AA_API double
aa_rx_ik_opt_err_qlnpv_fd( void *vcx, const double *q, double *dq )
{
struct kin_solve_cx *cx = (struct kin_solve_cx*)vcx;
size_t n = aa_rx_sg_sub_config_count(cx->ssg);
struct aa_dvec vq = AA_DVEC_INIT(n,(double*)q,1);
double x = s_nlobj_qv_fd_helper(vcx, &vq);
if( dq ) {
struct aa_dvec vdq = AA_DVEC_INIT(n,dq,1);
// TODO: make epsilon a parameter
double eps = 1e-6;
aa_de_grad_fd( s_nlobj_qv_fd_helper, vcx,
&vq, eps, &vdq );
}
return x;
}
AA_API double
aa_rx_ik_opt_err_trans( void *vcx, const double *q, double *dq )
{
struct kin_solve_cx *cx = (struct kin_solve_cx*)vcx;
void *ptrtop = aa_mem_region_ptr(cx->reg);
size_t n = aa_rx_sg_sub_config_count(cx->ssg);
struct aa_dvec vq = AA_DVEC_INIT(n,(double*)q,1);
aa_rx_fk_sub(cx->fk, cx->ssg, &vq );
double *E_act = aa_rx_fk_ref(cx->fk, cx->frame);
double *v_act = E_act + AA_TF_QUTR_V;
double *E_ref = cx->TF_ref->data;
double *v_ref = E_ref + AA_TF_QUTR_V;
double E_err[7];
double *v_err = E_err + AA_TF_QUTR_V;
// Apply a negative factor in gradient when we have to minimze the
// error quaternion
for(size_t i = 0; i < 3; i ++ ) v_err[i] = v_act[i] - v_ref[i];
double result = aa_tf_vdot(v_err,v_err);
if( dq ) {
struct aa_dvec v_dq = AA_DVEC_INIT(n,dq,1);
struct aa_dmat *Jvel = aa_rx_sg_sub_jac_vel_get(cx->ssg, cx->reg, cx->fk);
struct aa_dmat Jr, Jv;
aa_dmat_view_block(&Jv, Jvel, AA_TF_DX_V, 0, 3, Jvel->cols);
aa_dmat_view_block(&Jr, Jvel, AA_TF_DX_W, 0, 3, Jvel->cols);
// Translational Part
struct aa_dvec v_v_err = AA_DVEC_INIT(3,v_err,1);
aa_dmat_gemv(CblasTrans, 2, &Jv, &v_v_err, 0, &v_dq);
}
aa_mem_region_pop(cx->reg, ptrtop);
/* printf("err: %f\n", result); */
return result;
}
static void
q_rmul_helper( const double *q, const struct aa_dvec *x, struct aa_dvec *y )
{
double dM[4*4];
struct aa_dmat M = AA_DMAT_INIT(4,4,dM,4);
aa_tf_qmat_r(q,&M);
aa_dmat_gemv(CblasTrans, 1, &M, x, 0, y);
}
AA_API double
aa_rx_ik_opt_err_qlnpv( void *vcx, const double *q, double *dq )
{
struct kin_solve_cx *cx = (struct kin_solve_cx*)vcx;
void *ptrtop = aa_mem_region_ptr(cx->reg);
size_t n = aa_rx_sg_sub_config_count(cx->ssg);
struct aa_dvec vq = AA_DVEC_INIT(n,(double*)q,1);
aa_rx_fk_sub(cx->fk, cx->ssg, &vq );
double *E_act = aa_rx_fk_ref(cx->fk, cx->frame);
double *v_act = E_act + AA_TF_QUTR_V;
double *q_act = E_act + AA_TF_QUTR_Q;
double *E_ref = cx->TF_ref->data;
double *v_ref = E_ref + AA_TF_QUTR_V;
double *q_ref = E_ref + AA_TF_QUTR_Q;
double E_err[7];
double *v_err = E_err + AA_TF_QUTR_V;
double *q_err = E_err + AA_TF_QUTR_Q;
aa_tf_qcmul(q_act,q_ref,q_err);
// Apply a negative factor in gradient when we have to minimze the
// error quaternion
int needs_min = (E_err[AA_TF_QUAT_W] < 0 );
if( needs_min ) {
for( size_t i = 0; i < 4; i ++ ) E_err[i] *= -1;
}
double q_ln[4];
aa_tf_qln(E_err, q_ln);
for(size_t i = 0; i < 3; i ++ ) v_err[i] = v_act[i] - v_ref[i];
double result = ( aa_tf_qdot(q_ln,q_ln) +
+ aa_tf_vdot(v_err,v_err) );
if( dq ) {
struct aa_dvec v_dq = AA_DVEC_INIT(n,dq,1);
struct aa_dmat *Jvel = aa_rx_sg_sub_jac_vel_get(cx->ssg, cx->reg, cx->fk);
struct aa_dmat Jr, Jv;
aa_dmat_view_block(&Jv, Jvel, AA_TF_DX_V, 0, 3, Jvel->cols);
aa_dmat_view_block(&Jr, Jvel, AA_TF_DX_W, 0, 3, Jvel->cols);
// Translational Part
struct aa_dvec v_v_err = AA_DVEC_INIT(3,v_err,1);
aa_dmat_gemv(CblasTrans, 2, &Jv, &v_v_err, 0, &v_dq);
// Rotational Part
if( needs_min ) {
for( size_t i = 0; i < 4; i ++ ) q_ln[i] *= -1;
}
double a[4], b[4], dJ[4*4];
struct aa_dvec va = AA_DVEC_INIT(4,a,1);
struct aa_dvec vb = AA_DVEC_INIT(4,b,1);
struct aa_dvec vln = AA_DVEC_INIT(4,q_ln,1);
struct aa_dmat vJ_4x4 = AA_DMAT_INIT(4,4,dJ,4);
struct aa_dmat *J_4x4 = &vJ_4x4;
{
struct aa_dmat *J_ln = J_4x4;
aa_tf_qln_jac(q_err,J_ln);
aa_dmat_gemv(CblasTrans, 1, J_ln, &vln, 0, &va);
}
q_rmul_helper( q_ref, &va, &vb );
aa_tf_qconj1(b);
q_rmul_helper( q_act, &vb, &va ); /* TODO: Pure result, some
* extra multiplies here. */
// a is now a pure dual quaternion */
{
struct aa_dvec va3 = AA_DVEC_INIT(3,a,1);
aa_dmat_gemv( CblasTrans, 1, &Jr, &va3, 1, &v_dq );
}
/* { */
/* struct aa_dvec *v_dq_fd = aa_dvec_alloc(cx->reg,n); */
/* double eps = 1e-6; */
/* aa_de_grad_fd( s_nlobj_qv_fd_helper, vcx, */
/* &vq, eps, v_dq_fd ); */
/* printf("--\n"); */
/* printf("needs min: %d\n", needs_min); */
/* printf("ad: "); */
/* aa_dump_vec(stdout,v_dq_fd->data,n); */
/* printf("an: "); */
/* aa_dump_vec(stdout,dq,n); */
/* assert( aa_dvec_ssd(v_dq_fd, &v_dq) < 1e-3 ); */
/* } */
}
aa_mem_region_pop(cx->reg, ptrtop);
//printf("err: %f\n", result);
return result;
}
// TODO: weighted error
AA_API double
aa_rx_ik_opt_err_jcenter( void *vcx, const double *q, double *dq )
{
struct kin_solve_cx *cx = (struct kin_solve_cx*)vcx;
struct aa_mem_region *reg = cx->reg;
void *ptrtop = aa_mem_region_ptr(reg);
size_t n = aa_rx_sg_sub_config_count(cx->ssg);
struct aa_dvec *q_center = aa_dvec_alloc(reg,n);
aa_rx_sg_sub_center_configv(cx->ssg,q_center);
double result = 0;
if( dq ) { // error and gradient
for( size_t i = 0; i < n; i ++ ) {
double d = q[i] - AA_DVEC_REF(q_center,i);
result += (d*d);
dq[i] = d;
}
//printf("--\n");
//printf("q: "); aa_dump_vec(stdout,q,n);
//printf("qc: "); aa_dump_vec(stdout,q_center->data,n);
//printf("dq: "); aa_dump_vec(stdout,dq,n);
} else { // error only
for( size_t i = 0; i < n; i ++ ) {
double d = q[i] - AA_DVEC_REF(q_center,i);
result += (d*d);
}
}
aa_mem_region_pop(cx->reg, ptrtop);
return result / 2;
}
struct err_cx {
void *cx;
aa_rx_ik_opt_fun *fun;
};
static double
s_err_cx_dispatch(unsigned n, const double *q, double *dq, void *vcx)
{
(void)n;
struct err_cx *cx = (struct err_cx *)vcx;
return cx->fun(cx->cx, q, dq);
}
static int
s_ik_nlopt( struct kin_solve_cx *cx,
struct aa_dvec *q )
{
struct aa_mem_region *reg = cx->reg;
void *ptrtop = aa_mem_region_ptr(reg);
const struct aa_rx_sg_sub *ssg = cx->ssg;
const struct aa_rx_sg *sg = cx->ssg->scenegraph;
if( 1 != cx->q_sub->inc || 1 != cx->q_all->inc ) {
return AA_RX_INVALID_PARAMETER;
}
size_t n_sub = cx->q_sub->len;
nlopt_algorithm alg = NLOPT_LD_SLSQP;
nlopt_opt opt = nlopt_create(alg, (unsigned)n_sub); /* algorithm and dimensionality */
struct err_cx ocx, eqctcx;
ocx.cx = cx;
ocx.fun = cx->ik_cx->opts->obj_fun;
nlopt_set_min_objective(opt, s_err_cx_dispatch, &ocx);
if( cx->ik_cx->opts->eqct_fun ) {
eqctcx.cx = cx;
eqctcx.fun = cx->ik_cx->opts->eqct_fun;
nlopt_add_equality_constraint(opt, s_err_cx_dispatch, &eqctcx,
cx->ik_cx->opts->eqct_tol);
}
//nlopt_set_xtol_rel(opt, 1e-4); // TODO: make a parameter
if( cx->opts->tol_obj_abs >= 0 )
nlopt_set_ftol_abs(opt, cx->opts->tol_obj_abs );
if( cx->opts->tol_obj_rel >= 0 )
nlopt_set_ftol_rel(opt, cx->opts->tol_obj_rel );
if( cx->opts->tol_dq >= 0 )
nlopt_set_xtol_rel(opt, cx->opts->tol_dq );
double *lb = AA_MEM_REGION_NEW_N(reg,double,n_sub);
double *ub = AA_MEM_REGION_NEW_N(reg,double,n_sub);
{ // bounds
for( size_t i = 0; i < n_sub; i ++ ) {
aa_rx_config_id id = aa_rx_sg_sub_config(ssg,i);
if( aa_rx_sg_get_limit_pos(sg, id, lb+i, ub+i) )
{
lb[i] = -DBL_MAX;
ub[i] = DBL_MAX;
}
}
}
nlopt_set_lower_bounds(opt, lb);
nlopt_set_upper_bounds(opt, ub);
double minf;
nlopt_result ores = nlopt_optimize(opt, cx->q_sub->data, &minf);
if( cx->opts->debug ) {
/* fprintf("AMINO IK NLOPT RESULT: %s (%d)", */
/* nlopt_result_to_string(ores), ores); */
fprintf(stderr, "AMINO IK NLOPT RESULT: %d\n", ores);
}
aa_dvec_copy( cx->q_sub, q );
aa_rx_fk_sub(cx->fk, cx->ssg, q);
double *E_act = aa_rx_fk_ref(cx->fk, cx->frame);
int result = s_check(cx->ik_cx, cx->TF_ref, E_act );
nlopt_destroy(opt);
aa_mem_region_pop(reg,ptrtop);
return result;
}
| {
"alphanum_fraction": 0.5811926606,
"avg_line_length": 30.4186046512,
"ext": "c",
"hexsha": "a53d432597318d55f5b230e1ee0ee3c89596b329",
"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": "e3063ceeeed7d1a3d55fc0d3071c9aacb4466b22",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "dyalab/amino",
"max_forks_repo_path": "src/rx/ik_nlopt.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "e3063ceeeed7d1a3d55fc0d3071c9aacb4466b22",
"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": "dyalab/amino",
"max_issues_repo_path": "src/rx/ik_nlopt.c",
"max_line_length": 92,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "e3063ceeeed7d1a3d55fc0d3071c9aacb4466b22",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "dyalab/amino",
"max_stars_repo_path": "src/rx/ik_nlopt.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 6489,
"size": 19620
} |
/***********************************************************
* Program Name: conv.
*
* A program used to process the data from mcml -
* A Monte Carlo simulation of photon distribution in
* multi-layered turbid media in ANSI Standard C.
****
* Creation Date: 11/1991.
* Current Date: 6/1992.
*
* Lihong Wang, Ph. D.
* Steven L. Jacques, Ph. D.
* Laser Biology Research Laboratory - 17
* M.D. Anderson Cancer Center
* University of Texas
* 1515 Holcombe Blvd.
* Houston, TX 77030
* USA
*
****
* General Naming Conventions:
* Preprocessor names: all capital letters,
* e.g. #define PREPROCESSORS
* Globals: first letter of each word is capital, no
* underscores,
* e.g. short GlobalVar;
* Dummy variables: first letter of each word is capital,
* and words are connected by underscores,
* e.g. void NiceFunction(char Dummy_Var);
* Local variables: all lower cases, words are connected
* by underscores,
* e.g. short local_var;
* Function names or data types: same as Globals.
*
****
* Dimension of length: cm.
*
****/
#ifndef __MCML_CONV_H__
#define __MCML_CONV_H__
#include <math.h>
#include <new>
#include <string>
#include <algorithm>
#include <gsl/gsl_integration.h>
#include <gsl/gsl_sf_bessel.h>
#include "mcml_model.h"
#define GAUSSLIMIT 4
#define PI 3.1415926
#define SIGN(x) ((x)>=0 ? 1:-1)
/****************** Classes *****************************/
class Beam {
/* Beam class - incident light beam class
Parameters to describe a photon beam.
Pencil: infinitely narrow beam. This is default for the
beam from the mcml output.
Flat: Flat beam with radius R.
Gaussian: Gaussian with 1/e2 radius R.
Others: general beam described by points with interpolation.
Class instance variables:
type - incident beam type, FLAT or GAUSSIAN
P - total beam power/energy [W or J]
R - beam radius, defined as 1/e^2 for Gaussian beam [cm]
Methods:
*/
public:
enum BeamType {
FLAT,
GAUSSIAN
};
BeamType type; // beam type
double P; // total power. [J or W]
double R; // radius. [cm]
};
class Node {
/* Node class - node link list binary tree class
Data structures for the binary tree used to store part of
the integrand evaluation.
Class instance variables:
x - x grid node position
y - y grid node position
left - left node pointer
right - right node pointer
Methods:
*/
public:
double x;
double y;
Node * left;
Node * right;
Node () : left (nullptr), right (nullptr) {};
static Node * FillNode(double x, double y);
static Node * SearchNode(Node * tree, double x);
static void InsertNode(Node * tree, double x, double y);
static void FreeTree(Node * tree);
};
class ConvVar {
/* ConvVar class - convoluation variables class
A global structure to pass the current coordinate of the
physical quantities being evaluated and the pointers of the
input and output parameters to the integration function.
Class instance variables:
r - r position
iz - iz index
ia - ia index
tree - A tree to store ITheta() & ExpBessI0().
Methods:
*/
public:
double r;
short iz;
short ia;
Node * tree; // A tree to store ITheta() & ExpBessI0().
ConvVar () : tree (nullptr) {};
};
class ConvInput {
/* ConvInput class - beam convolution input class
Input parameters for each independent run.
z and r are for the cylindrical coordinate system. [cm]
a is for the angle alpha between the photon exiting
direction and the surface normal. [radian]
The grid line separations in z, r, and alpha
directions are dz, dr, and da respectively. The numbers
of grid lines in z, r, and alpha directions are
nz, nr, and na respectively.
The member layerspecs will point to an array of
structures which store parameters of each layer.
This array has (number_layers + 2) elements. One
element is for a layer.
The layers 0 and (num_layers + 1) are for top ambient
medium and the bottom ambient medium respectively.
For convolution, the grid line separations in z, and alpha
directions are still dz, and da respectively. The numbers
of grid lines in z, and alpha directions are still
nz, and na respectively. However, the grid line separation
and the number of grid lines in r direction are drc and
nrc respectively.
Class instance variables:
beam - incident beam class instance object
drc - convolution r grid separation.[cm]
nrc - convolution array range 0..nrc-1.
eps - relative error in convolution
Methods:
*/
public:
Beam beam; // incident beam of finite size
double drc;
short nrc;
MCMLModel mcmlModel;
ConvVar convVar;
void SelectConvInput (MCMLModel mcmlModelSet,
Beam::BeamType beamType = Beam::FLAT, double P = 1.0, double R = 0);
void FreeConvInput();
};
class MCMLConv : public ConvInput {
/* MCMLConv class - multi-layered photon scattering model beam convolution
inherits from ConvInput beam setup
Structures for scored physical quantities
from mcml and to be convolved for photon
beams of finite size. Therefore, "Out"
here means the output of both mcml and conv.
The member allocated is used to keep the status
of the arrays. It is set to 1 if all the arrays
are allocated and assigned values. It is set to
0 otherwise.
z and r represent z and r coordinates of the
cylindrical coordinate system. [cm]
a is the angle alpha between the photon exiting
direction and the normal to the surfaces. [radian]
See comments of the InputStruct.
See manual for the physcial quantities.
Class instance variables:
Rd_rac - convolved data. [J/(cm2 sr)]
Rd_rc - 1D radial distribution of diffuse reflectance [J/cm2]
A_rzc - 2D probability density in turbid media over r & z [J/cm3]
Tt_rac - 2D distribution of total transmittance [J/(cm2 sr)]
Tt_rc - 1D radial distribution of transmittance [J/cm2]
Methods:
*/
private:
void ConvRd_ra ();
void ConvRd_r ();
void ConvA_rz ();
void ConvTt_ra ();
void ConvTt_r ();
void ConvA2F();
public:
double ** Rd_rac;
double * Rd_rc;
double ** A_rzc;
double ** Tt_rac;
double * Tt_rc;
double ** F_rzc;
MCMLConv () : Rd_rac (nullptr), Rd_rc (nullptr), A_rzc (nullptr),
Tt_rac (nullptr), Tt_rc (nullptr), F_rzc (nullptr) {};
void SelectMCMLConv (MCMLModel mcmlModelSet, std::string beamType,
double P, double R);
void FreeMCMLConv ();
void RunConv ();
double CenterHalfMaxDepth ();
double SurfaceHalfMaxWidth ();
};
#endif //__MCML_CONV_H__
| {
"alphanum_fraction": 0.6167237834,
"avg_line_length": 30.1446280992,
"ext": "h",
"hexsha": "0da282e58b1de27e7f2a244ffa40bb4a3b1210a7",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2021-10-02T16:54:12.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-10-02T16:54:12.000Z",
"max_forks_repo_head_hexsha": "a60c399beced68778bc96ed5527666f7ce5bed7d",
"max_forks_repo_licenses": [
"Unlicense"
],
"max_forks_repo_name": "harveyiliu/mcml-photon-scattering-cpp",
"max_forks_repo_path": "mcml_conv.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "a60c399beced68778bc96ed5527666f7ce5bed7d",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"Unlicense"
],
"max_issues_repo_name": "harveyiliu/mcml-photon-scattering-cpp",
"max_issues_repo_path": "mcml_conv.h",
"max_line_length": 78,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "a60c399beced68778bc96ed5527666f7ce5bed7d",
"max_stars_repo_licenses": [
"Unlicense"
],
"max_stars_repo_name": "harveyiliu/mcml-photon-scattering-cpp",
"max_stars_repo_path": "mcml_conv.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1768,
"size": 7295
} |
#ifndef PROGRESS_BAR_OBSERVER_H_0L8ZR7QT
#define PROGRESS_BAR_OBSERVER_H_0L8ZR7QT
#include "rang.hpp"
#include <atomic>
#include <cmath>
#include <cstdint>
#include <gsl/gsl>
#include <iomanip>
#include <sens_loc/util/console.h>
#include <taskflow/core/observer.hpp>
namespace sens_loc::util {
class progress_bar_observer : public tf::ExecutorObserverInterface {
public:
constexpr static int max_bars = 50;
progress_bar_observer(std::int64_t total_tasks)
: _total_tasks{total_tasks}
, _done{0} {
Expects(total_tasks >= 1);
}
progress_bar_observer(const progress_bar_observer&) = delete;
progress_bar_observer(progress_bar_observer&&) = delete;
progress_bar_observer& operator=(const progress_bar_observer&) = delete;
progress_bar_observer& operator=(progress_bar_observer&&) = delete;
~progress_bar_observer() override = default;
void set_up(unsigned /*num_workers*/) override {}
void on_entry(unsigned /*worker_id*/, tf::TaskView /*task_view*/) override;
void on_exit(unsigned /*worker_id*/, tf::TaskView /*task_view*/) override;
private:
void print_bar(bool increment) noexcept;
std::int64_t _total_tasks;
std::int64_t _done;
std::atomic<bool> _inital_output = false;
};
} // namespace sens_loc::util
#endif /* end of include guard: PROGRESS_BAR_OBSERVER_H_0L8ZR7QT */
| {
"alphanum_fraction": 0.7125621008,
"avg_line_length": 30.6304347826,
"ext": "h",
"hexsha": "b9db10fe050e876fdc8e978d64cfee4eb5d3ca65",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "5c8338276565d846c07673e83f94f6841006872b",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "JonasToth/depth-conversions",
"max_forks_repo_path": "src/include/sens_loc/util/progress_bar_observer.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "5c8338276565d846c07673e83f94f6841006872b",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "JonasToth/depth-conversions",
"max_issues_repo_path": "src/include/sens_loc/util/progress_bar_observer.h",
"max_line_length": 79,
"max_stars_count": 2,
"max_stars_repo_head_hexsha": "5c8338276565d846c07673e83f94f6841006872b",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "JonasToth/depth-conversions",
"max_stars_repo_path": "src/include/sens_loc/util/progress_bar_observer.h",
"max_stars_repo_stars_event_max_datetime": "2022-03-14T09:14:35.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-09-30T07:09:49.000Z",
"num_tokens": 340,
"size": 1409
} |
#include <gsl/gsl_math.h>
#include "gsl_cblas.h"
#include "cblas.h"
void
cblas_drotm (const int N, double *X, const int incX, double *Y,
const int incY, const double *P)
{
#define BASE double
#include "source_rotm.h"
#undef BASE
}
| {
"alphanum_fraction": 0.7016806723,
"avg_line_length": 18.3076923077,
"ext": "c",
"hexsha": "0c0142a11baefa6b6b2165c2317966d83be791c1",
"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/drotm.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/drotm.c",
"max_line_length": 63,
"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/drotm.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": 75,
"size": 238
} |
#include <stdio.h>
#include <gsl/gsl_statistics.h>
#include <stdlib.h>
#include <float.h>
#ifndef N
#define N 32
#endif
#define K N/2
#include <klee/klee.h>
int
main(void)
{
double data[K], w[K];
float input[N];
// symbolic inputs
klee_make_symbolic(&input, sizeof(input), "input");
int i;
for (i = 0; i < K; i++){
w[i] = input[i] / FLT_MAX * 100;
}
for (i = 0; i < K; i++){
data[i] = input[i+K] / FLT_MAX * 100;
}
double wtss, wmean;
wmean = gsl_stats_wmean(w, 1, data, 1, K);
wtss = gsl_stats_wtss_m(w, 1, data, 1, K, wmean);
printf ("The sample variance is %g\n", wtss);
return 0;
}
| {
"alphanum_fraction": 0.5791925466,
"avg_line_length": 17.4054054054,
"ext": "c",
"hexsha": "4d1d213be361bc06d95b767e7bb4cfbbd3db97bd",
"lang": "C",
"max_forks_count": 5,
"max_forks_repo_forks_event_max_datetime": "2022-01-04T19:22:30.000Z",
"max_forks_repo_forks_event_min_datetime": "2020-06-27T11:11:07.000Z",
"max_forks_repo_head_hexsha": "4fa9a35cc5695d65509296790accd4b34071432d",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "snipekill/FPGen",
"max_forks_repo_path": "benchmarks/gsl/wtss-m/wtss-m-SYMBOLIC.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "4fa9a35cc5695d65509296790accd4b34071432d",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "snipekill/FPGen",
"max_issues_repo_path": "benchmarks/gsl/wtss-m/wtss-m-SYMBOLIC.c",
"max_line_length": 55,
"max_stars_count": 3,
"max_stars_repo_head_hexsha": "4fa9a35cc5695d65509296790accd4b34071432d",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "snipekill/FPGen",
"max_stars_repo_path": "benchmarks/gsl/wtss-m/wtss-m-SYMBOLIC.c",
"max_stars_repo_stars_event_max_datetime": "2022-02-20T21:02:18.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-07-06T02:44:11.000Z",
"num_tokens": 235,
"size": 644
} |
#include <stdio.h>
#include <math.h>
#include <gsl/gsl_integration.h>
void integral_gen (int nmin, int nmax, double vals[]);
double f (double x, void *params);
double f (double x, void *params)
{
double n = (double) *(int *) params;
double f = exp (-x) * pow (x, n);
return f;
}
void integral_gen (int nmin, int nmax, double vals[])
{
double a = 0., b = 1.; // limits of integration
double abserr = 0., relerr = 1.e-8; // requested errors
double result; // the integral value
double error; // the error estimate
int n;
size_t np = 1000; // work area size
gsl_integration_workspace *w = gsl_integration_workspace_alloc (np);
gsl_function F;
F.function = &f;
F.params = &n;
for (n = nmin; n <= nmax; n++)
{
gsl_integration_qag (&F, a, b, abserr, relerr, np, GSL_INTEG_GAUSS15,
w, &result, &error);
vals[n] = result;
}
gsl_integration_workspace_free (w);
}
| {
"alphanum_fraction": 0.5828343313,
"avg_line_length": 23.8571428571,
"ext": "c",
"hexsha": "6944771946bc5fe578df5825ef36bb4f5d7e9559",
"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": "66be149e44bf9f0fcf17ffd5c1a99eafaf1a8b96",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "mtariq1994/hw07",
"max_forks_repo_path": "integral_gen.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "66be149e44bf9f0fcf17ffd5c1a99eafaf1a8b96",
"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": "mtariq1994/hw07",
"max_issues_repo_path": "integral_gen.c",
"max_line_length": 77,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "66be149e44bf9f0fcf17ffd5c1a99eafaf1a8b96",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "mtariq1994/hw07",
"max_stars_repo_path": "integral_gen.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 287,
"size": 1002
} |
// Standard libraries.
#include <math.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// Libraries from packages outside ASF.
#include <glib.h>
#include <gsl/gsl_blas.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_spline.h>
#include <gsl/gsl_statistics_double.h>
// Libraries developed at ASF.
#include <asf.h>
#include <asf_meta.h>
#include <asf_raster.h>
#include "float_image.h"
#include "uint8_image.h"
#include <libasf_proj.h>
#include <spheroids.h>
#include <asf_contact.h>
void usage()
{
printf("Usage: flip [v|h|vh] <input basename> <output basename>\n");
exit(1);
}
int main(int argc, char *argv[])
{
handle_common_asf_args(&argc, &argv, "flip");
if (argc != 4) {
usage();
}
if ( ! (strcmp(argv[1], "v") == 0 ||
strcmp(argv[1], "h") == 0 ||
strcmp(argv[1], "hv") == 0 ||
strcmp(argv[1], "vh") == 0))
{
usage();
}
int vert = strchr(argv[1], 'v') != NULL;
int horz = strchr(argv[1], 'h') != NULL;
if (!vert && !horz) {
usage();
}
char *input_meta_name = appendExt(argv[2], ".meta");
char *input_data_name = appendExt(argv[2], ".img");
char *output_meta_name = appendExt(argv[3], ".meta");
char *output_data_name = appendExt(argv[3], ".img");
printf("Flipping image %s.\n",
vert && horz ? "vertically and horizontally" :
(vert ? "vertically" : "horizontally"));
printf("Input data file: %s\n", input_data_name);
printf("Output data file: %s\n", output_data_name);
meta_parameters *imd = meta_read(input_meta_name);
meta_write(imd, output_meta_name);
FloatImage *finput = NULL;
UInt8Image *binput = NULL;
if (imd->optical || imd->general->data_type == BYTE) {
binput = uint8_image_new_from_file(imd->general->sample_count,
imd->general->line_count,
input_data_name, 0);
}
else {
finput = float_image_new_from_file(imd->general->sample_count,
imd->general->line_count,
input_data_name, 0,
FLOAT_IMAGE_BYTE_ORDER_BIG_ENDIAN);
}
if (imd->optical || imd->general->data_type == BYTE) {
if (horz)
uint8_image_flip_x(binput);
if (vert)
uint8_image_flip_y(binput);
uint8_image_store(binput, output_data_name);
uint8_image_free(binput);
}
else {
if (horz)
float_image_flip_x(finput);
if (vert)
float_image_flip_y(finput);
float_image_store(finput, output_data_name,
FLOAT_IMAGE_BYTE_ORDER_BIG_ENDIAN);
float_image_free(finput);
}
meta_free(imd);
free(input_data_name);
free(input_meta_name);
free(output_data_name);
free(output_meta_name);
return EXIT_SUCCESS;
}
| {
"alphanum_fraction": 0.6127188282,
"avg_line_length": 24.3391304348,
"ext": "c",
"hexsha": "ce2ad7cfd61cdbe381541b7ea204e34abb2e798f",
"lang": "C",
"max_forks_count": 7,
"max_forks_repo_forks_event_max_datetime": "2020-05-15T08:01:09.000Z",
"max_forks_repo_forks_event_min_datetime": "2017-04-26T18:18:33.000Z",
"max_forks_repo_head_hexsha": "c9065400a64c87be46418ab32e3a251ca2f55fd5",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "glshort/MapReady",
"max_forks_repo_path": "src/flip/flip.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "c9065400a64c87be46418ab32e3a251ca2f55fd5",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "glshort/MapReady",
"max_issues_repo_path": "src/flip/flip.c",
"max_line_length": 74,
"max_stars_count": 3,
"max_stars_repo_head_hexsha": "c9065400a64c87be46418ab32e3a251ca2f55fd5",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "glshort/MapReady",
"max_stars_repo_path": "src/flip/flip.c",
"max_stars_repo_stars_event_max_datetime": "2021-07-28T01:51:22.000Z",
"max_stars_repo_stars_event_min_datetime": "2017-12-31T05:33:28.000Z",
"num_tokens": 762,
"size": 2799
} |
/* Cholesky Decomposition
*
* Copyright (C) 2000 Thomas Walter
* Copyright (C) 2000, 2001, 2002, 2003, 2005, 2007 Brian Gough, Gerard Jungman
* Copyright (C) 2016, 2019 Patrick Alken
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 3, or (at your option) any
* later version.
*
* This 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.
*
* 03 May 2000: Modified for GSL by Brian Gough
* 29 Jul 2005: Additions by Gerard Jungman
* 04 Mar 2016: Change Cholesky algorithm to gaxpy version by Patrick Alken
* 26 May 2019: implement recursive Cholesky with Level 3 BLAS by Patrick Alken
*/
/*
* Cholesky decomposition of a symmetric positive definite matrix.
*
* This algorithm 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>
#include "recurse.h"
static double cholesky_norm1(const gsl_matrix * LLT, gsl_vector * work);
static int cholesky_Ainv(CBLAS_TRANSPOSE_t TransA, gsl_vector * x, void * params);
static int cholesky_decomp_L2 (gsl_matrix * A);
static int cholesky_decomp_L3 (gsl_matrix * A);
/*
In GSL 2.2, we decided to modify the behavior of the Cholesky decomposition
to store the Cholesky factor in the lower triangle, and store the original
matrix in the upper triangle. Previous versions stored the Cholesky factor in
both places. The routine gsl_linalg_cholesky_decomp1 was added for the new
behavior, and gsl_linalg_cholesky_decomp is maintained for backward compatibility.
It will be removed in a future release.
*/
int
gsl_linalg_cholesky_decomp (gsl_matrix * A)
{
int status;
status = gsl_linalg_cholesky_decomp1(A);
if (status == GSL_SUCCESS)
{
gsl_matrix_transpose_tricpy(CblasLower, CblasUnit, A, A);
}
return status;
}
/*
gsl_linalg_cholesky_decomp1()
Perform Cholesky decomposition of a symmetric positive
definite matrix using lower triangle using Level 3 BLAS algorithm.
Inputs: A - (input) symmetric, positive definite matrix
(output) lower triangle contains Cholesky factor
Return: success/error
Notes:
1) original matrix is saved in upper triangle on output
*/
int
gsl_linalg_cholesky_decomp1 (gsl_matrix * A)
{
const size_t N = A->size1;
if (N != A->size2)
{
GSL_ERROR("Cholesky decomposition requires square matrix", GSL_ENOTSQR);
}
else
{
/* save original matrix in upper triangle for later rcond calculation */
gsl_matrix_transpose_tricpy(CblasLower, CblasUnit, A, A);
return cholesky_decomp_L3(A);
}
}
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
{
int status;
/* copy x <- b */
gsl_vector_memcpy (x, b);
status = gsl_linalg_cholesky_svx(LLT, x);
return status;
}
}
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, L^T x = c */
gsl_blas_dtrsv (CblasLower, CblasTrans, CblasNonUnit, LLT, x);
return GSL_SUCCESS;
}
}
int
gsl_linalg_cholesky_solve_mat (const gsl_matrix * LLT,
const gsl_matrix * B,
gsl_matrix * X)
{
if (LLT->size1 != LLT->size2)
{
GSL_ERROR ("cholesky matrix must be square", GSL_ENOTSQR);
}
else if (LLT->size1 != B->size1)
{
GSL_ERROR ("matrix size must match B size", GSL_EBADLEN);
}
else if (LLT->size2 != X->size1)
{
GSL_ERROR ("matrix size must match solution size", GSL_EBADLEN);
}
else
{
int status;
/* copy X <- B */
gsl_matrix_memcpy (X, B);
status = gsl_linalg_cholesky_svx_mat(LLT, X);
return status;
}
}
int
gsl_linalg_cholesky_svx_mat (const gsl_matrix * LLT,
gsl_matrix * X)
{
if (LLT->size1 != LLT->size2)
{
GSL_ERROR ("cholesky matrix must be square", GSL_ENOTSQR);
}
else if (LLT->size2 != X->size1)
{
GSL_ERROR ("matrix size must match solution size", GSL_EBADLEN);
}
else
{
/* solve for C using forward-substitution, L C = B */
gsl_blas_dtrsm (CblasLeft, CblasLower, CblasNoTrans, CblasNonUnit, 1.0,
LLT, X);
/* perform back-substitution, L^T X = C */
gsl_blas_dtrsm (CblasLeft, CblasLower, CblasTrans, CblasNonUnit, 1.0,
LLT, X);
return GSL_SUCCESS;
}
}
/*
gsl_linalg_cholesky_invert()
Compute the inverse of a symmetric positive definite matrix in
Cholesky form.
Inputs: LLT - matrix in cholesky form on input
A^{-1} = L^{-t} L^{-1} on output
Return: success or error
*/
int
gsl_linalg_cholesky_invert(gsl_matrix * LLT)
{
if (LLT->size1 != LLT->size2)
{
GSL_ERROR ("cholesky matrix must be square", GSL_ENOTSQR);
}
else
{
int status;
/* invert the lower triangle of LLT */
status = gsl_linalg_tri_invert(CblasLower, CblasNonUnit, LLT);
if (status)
return status;
/* compute A^{-1} = L^{-T} L^{-1} */
status = gsl_linalg_tri_LTL(LLT);
if (status)
return status;
/* copy lower triangle to upper */
gsl_matrix_transpose_tricpy(CblasLower, CblasUnit, LLT, LLT);
return GSL_SUCCESS;
}
}
int
gsl_linalg_cholesky_decomp_unit(gsl_matrix * A, gsl_vector * D)
{
const size_t N = A->size1;
size_t i, j;
/* initial Cholesky */
int stat_chol = gsl_linalg_cholesky_decomp1(A);
if(stat_chol == GSL_SUCCESS)
{
/* calculate D from diagonal part of initial Cholesky */
for(i = 0; i < N; ++i)
{
const double C_ii = gsl_matrix_get(A, i, i);
gsl_vector_set(D, i, C_ii*C_ii);
}
/* multiply initial Cholesky by 1/sqrt(D) on the right */
for(i = 0; i < N; ++i)
{
for(j = 0; j < N; ++j)
{
gsl_matrix_set(A, i, j, gsl_matrix_get(A, i, j) / sqrt(gsl_vector_get(D, j)));
}
}
/* Because the initial Cholesky contained both L and transpose(L),
the result of the multiplication is not symmetric anymore;
but the lower triangle _is_ correct. Therefore we reflect
it to the upper triangle and declare victory.
*/
for(i = 0; i < N; ++i)
for(j = i + 1; j < N; ++j)
gsl_matrix_set(A, i, j, gsl_matrix_get(A, j, i));
}
return stat_chol;
}
/*
gsl_linalg_cholesky_scale()
This function computes scale factors diag(S), such that
diag(S) A diag(S)
has a condition number within a factor N of the matrix
with the smallest condition number over all possible
diagonal scalings. See Corollary 7.6 of:
N. J. Higham, Accuracy and Stability of Numerical Algorithms (2nd Edition),
SIAM, 2002.
Inputs: A - symmetric positive definite matrix
S - (output) scale factors, S_i = 1 / sqrt(A_ii)
*/
int
gsl_linalg_cholesky_scale(const gsl_matrix * A, gsl_vector * S)
{
const size_t M = A->size1;
const size_t N = A->size2;
if (M != N)
{
GSL_ERROR("A is not a square matrix", GSL_ENOTSQR);
}
else if (N != S->size)
{
GSL_ERROR("S must have length N", GSL_EBADLEN);
}
else
{
size_t i;
/* compute S_i = 1/sqrt(A_{ii}) */
for (i = 0; i < N; ++i)
{
double Aii = gsl_matrix_get(A, i, i);
if (Aii <= 0.0)
gsl_vector_set(S, i, 1.0); /* matrix not positive definite */
else
gsl_vector_set(S, i, 1.0 / sqrt(Aii));
}
return GSL_SUCCESS;
}
}
/*
gsl_linalg_cholesky_scale_apply()
This function applies scale transformation to A:
A <- diag(S) A diag(S)
Inputs: A - (input/output)
on input, symmetric positive definite matrix
on output, diag(S) * A * diag(S) in lower triangle
S - (input) scale factors
*/
int
gsl_linalg_cholesky_scale_apply(gsl_matrix * A, const gsl_vector * S)
{
const size_t M = A->size1;
const size_t N = A->size2;
if (M != N)
{
GSL_ERROR("A is not a square matrix", GSL_ENOTSQR);
}
else if (N != S->size)
{
GSL_ERROR("S must have length N", GSL_EBADLEN);
}
else
{
size_t i, j;
/* compute: A <- diag(S) A diag(S) using lower triangle */
for (j = 0; j < N; ++j)
{
double sj = gsl_vector_get(S, j);
for (i = j; i < N; ++i)
{
double si = gsl_vector_get(S, i);
double *Aij = gsl_matrix_ptr(A, i, j);
*Aij *= si * sj;
}
}
return GSL_SUCCESS;
}
}
int
gsl_linalg_cholesky_decomp2(gsl_matrix * A, gsl_vector * S)
{
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 if (N != S->size)
{
GSL_ERROR("S must have length N", GSL_EBADLEN);
}
else
{
int status;
/* compute scaling factors to reduce cond(A) */
status = gsl_linalg_cholesky_scale(A, S);
if (status)
return status;
/* apply scaling factors */
status = gsl_linalg_cholesky_scale_apply(A, S);
if (status)
return status;
/* compute Cholesky decomposition of diag(S) A diag(S) */
status = gsl_linalg_cholesky_decomp1(A);
if (status)
return status;
return GSL_SUCCESS;
}
}
int
gsl_linalg_cholesky_svx2 (const gsl_matrix * LLT,
const gsl_vector * S,
gsl_vector * x)
{
if (LLT->size1 != LLT->size2)
{
GSL_ERROR ("cholesky matrix must be square", GSL_ENOTSQR);
}
else if (LLT->size2 != S->size)
{
GSL_ERROR ("matrix size must match S", GSL_EBADLEN);
}
else if (LLT->size2 != x->size)
{
GSL_ERROR ("matrix size must match solution size", GSL_EBADLEN);
}
else
{
/* b~ = diag(S) b */
gsl_vector_mul(x, S);
/* Solve for c using forward-substitution, L c = b~ */
gsl_blas_dtrsv (CblasLower, CblasNoTrans, CblasNonUnit, LLT, x);
/* Perform back-substitution, L^T x~ = c */
gsl_blas_dtrsv (CblasLower, CblasTrans, CblasNonUnit, LLT, x);
/* compute original solution vector x = S x~ */
gsl_vector_mul(x, S);
return GSL_SUCCESS;
}
}
int
gsl_linalg_cholesky_solve2 (const gsl_matrix * LLT,
const gsl_vector * S,
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 != S->size)
{
GSL_ERROR ("matrix size must match S size", GSL_EBADLEN);
}
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
{
int status;
/* Copy x <- b */
gsl_vector_memcpy (x, b);
status = gsl_linalg_cholesky_svx2(LLT, S, x);
return status;
}
}
int
gsl_linalg_cholesky_rcond (const gsl_matrix * LLT, double * rcond,
gsl_vector * work)
{
const size_t M = LLT->size1;
const size_t N = LLT->size2;
if (M != N)
{
GSL_ERROR ("cholesky matrix must be square", GSL_ENOTSQR);
}
else if (work->size != 3 * N)
{
GSL_ERROR ("work vector must have length 3*N", GSL_EBADLEN);
}
else
{
int status;
double Anorm = cholesky_norm1(LLT, work); /* ||A||_1 */
double Ainvnorm; /* ||A^{-1}||_1 */
*rcond = 0.0;
/* don't continue if matrix is singular */
if (Anorm == 0.0)
return GSL_SUCCESS;
/* estimate ||A^{-1}||_1 */
status = gsl_linalg_invnorm1(N, cholesky_Ainv, (void *) LLT, &Ainvnorm, work);
if (status)
return status;
if (Ainvnorm != 0.0)
*rcond = (1.0 / Anorm) / Ainvnorm;
return GSL_SUCCESS;
}
}
/* compute 1-norm of original matrix, stored in upper triangle of LLT;
* diagonal entries have to be reconstructed */
static double
cholesky_norm1(const gsl_matrix * LLT, gsl_vector * work)
{
const size_t N = LLT->size1;
double max = 0.0;
size_t i, j;
for (j = 0; j < N; ++j)
{
double sum = 0.0;
gsl_vector_const_view lj = gsl_matrix_const_subrow(LLT, j, 0, j + 1);
double Ajj;
/* compute diagonal (j,j) entry of A */
gsl_blas_ddot(&lj.vector, &lj.vector, &Ajj);
for (i = 0; i < j; ++i)
{
double *wi = gsl_vector_ptr(work, i);
double Aij = gsl_matrix_get(LLT, i, j);
double absAij = fabs(Aij);
sum += absAij;
*wi += absAij;
}
gsl_vector_set(work, j, sum + fabs(Ajj));
}
for (i = 0; i < N; ++i)
{
double wi = gsl_vector_get(work, i);
max = GSL_MAX(max, wi);
}
return max;
}
/* x := A^{-1} x = A^{-t} x, A = L L^T */
static int
cholesky_Ainv(CBLAS_TRANSPOSE_t TransA, gsl_vector * x, void * params)
{
int status;
gsl_matrix * A = (gsl_matrix * ) params;
(void) TransA; /* unused parameter warning */
/* compute L^{-1} x */
status = gsl_blas_dtrsv(CblasLower, CblasNoTrans, CblasNonUnit, A, x);
if (status)
return status;
/* compute L^{-t} x */
status = gsl_blas_dtrsv(CblasLower, CblasTrans, CblasNonUnit, A, x);
if (status)
return status;
return GSL_SUCCESS;
}
/*
cholesky_decomp_L2()
Perform Cholesky decomposition of a symmetric positive
definite matrix using lower triangle
Inputs: A - (input) symmetric, positive definite matrix
(output) lower triangle contains Cholesky factor
Return: success/error
Notes:
1) Based on algorithm 4.2.1 (Gaxpy Cholesky) of Golub and
Van Loan, Matrix Computations (4th ed), using Level 2 BLAS.
*/
static int
cholesky_decomp_L2 (gsl_matrix * A)
{
const size_t N = A->size1;
if (N != A->size2)
{
GSL_ERROR("Cholesky decomposition requires square matrix", GSL_ENOTSQR);
}
else
{
size_t j;
for (j = 0; j < N; ++j)
{
double ajj;
gsl_vector_view v = gsl_matrix_subcolumn(A, j, j, N - j); /* A(j:n,j) */
if (j > 0)
{
gsl_vector_view w = gsl_matrix_subrow(A, j, 0, j); /* A(j,1:j-1)^T */
gsl_matrix_view m = gsl_matrix_submatrix(A, j, 0, N - j, j); /* A(j:n,1:j-1) */
gsl_blas_dgemv(CblasNoTrans, -1.0, &m.matrix, &w.vector, 1.0, &v.vector);
}
ajj = gsl_matrix_get(A, j, j);
if (ajj <= 0.0)
{
GSL_ERROR("matrix is not positive definite", GSL_EDOM);
}
ajj = sqrt(ajj);
gsl_vector_scale(&v.vector, 1.0 / ajj);
}
return GSL_SUCCESS;
}
}
/*
cholesky_decomp_L3()
Perform Cholesky decomposition of a symmetric positive
definite matrix using Level 3 BLAS.
Inputs: A - (input) symmetric, positive definite matrix in lower triangle
(output) lower triangle contains Cholesky factor
Return: success/error
Notes:
1) Based on ReLAPACK recursive block Cholesky algorithm using Level 3 BLAS
2) 28 May 2019: performed several benchmark tests of this recursive variant
against the right-looking block variant from LAPACK. This recursive variant
performed faster in all cases, so it is now the default algorithm.
*/
static int
cholesky_decomp_L3 (gsl_matrix * A)
{
const size_t N = A->size1;
if (N != A->size2)
{
GSL_ERROR("Cholesky decomposition requires square matrix", GSL_ENOTSQR);
}
else if (N <= CROSSOVER_CHOLESKY)
{
/* use unblocked Level 2 algorithm */
return cholesky_decomp_L2(A);
}
else
{
/*
* partition matrix:
*
* A11 A12
* A21 A22
*
* where A11 is N1-by-N1
*/
int status;
const size_t N1 = GSL_LINALG_SPLIT(N);
const size_t N2 = N - N1;
gsl_matrix_view A11 = gsl_matrix_submatrix(A, 0, 0, N1, N1);
gsl_matrix_view A21 = gsl_matrix_submatrix(A, N1, 0, N2, N1);
gsl_matrix_view A22 = gsl_matrix_submatrix(A, N1, N1, N2, N2);
/* recursion on A11 */
status = cholesky_decomp_L3(&A11.matrix);
if (status)
return status;
/* A21 = A21 * L11^{-T} */
gsl_blas_dtrsm(CblasRight, CblasLower, CblasTrans, CblasNonUnit, 1.0, &A11.matrix, &A21.matrix);
/* A22 -= L21 L21^T */
gsl_blas_dsyrk(CblasLower, CblasNoTrans, -1.0, &A21.matrix, 1.0, &A22.matrix);
/* recursion on A22 */
status = cholesky_decomp_L3(&A22.matrix);
if (status)
return status;
return GSL_SUCCESS;
}
}
| {
"alphanum_fraction": 0.604971298,
"avg_line_length": 24.7489655172,
"ext": "c",
"hexsha": "24a58b44f4a1ec6c1fb530b8491555f30e8b1c3d",
"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/cholesky.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/cholesky.c",
"max_line_length": 102,
"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/cholesky.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": 5281,
"size": 17943
} |
#include "ll.h"
#include "gslsupp.h"
#include <math.h>
#include <gsl/gsl_sf.h>
double log_fact(size_t n)
{
gsl_sf_result res;
if (n <= UINT_MAX)
{
if (gsl_sf_lnfact_e((unsigned) n, &res) == GSL_SUCCESS) return res.val;
}
else
{
if (gsl_sf_lngamma_e((double) n + 1., &res) == GSL_SUCCESS) return res.val;
}
return nan(__func__);
}
double log_choose(size_t n, size_t m)
{
if (m > n) return nan(__func__);
if (m == n || !m) return 0.;
return m > (n >> 1) ? log_fact(n) - log_fact(n - m) - log_fact(m) : log_fact(n) - log_fact(m) - log_fact(n - m); // Addition here may be not associative
}
double pdf_hypergeom(size_t k, size_t n1, size_t n2, size_t t)
{
size_t car, n12 = size_add(&car, n1, n2);
if (car) return nan(__func__);
if (t > n12) t = n12;
if (k > n1 || k > t || (t > n2 && k < t - n2)) return 0.;
return exp(log_choose(n1, k) + log_choose(n2, t - k) - log_choose(n12, t));
}
double gamma_inc_P(double a, double x)
{
gsl_sf_result res;
if (gsl_sf_gamma_inc_P_e(a, x, &res) == GSL_SUCCESS) return res.val;
return nan(__func__);
}
double gamma_inc_Q(double a, double x)
{
gsl_sf_result res;
if (gsl_sf_gamma_inc_Q_e(a, x, &res) == GSL_SUCCESS) return res.val;
return nan(__func__);
}
double cdf_gamma_Q(double x, double a, double b)
{
if (x <= 0.) return 1.;
double y = x / b;
return y < a ? 1. - gamma_inc_P(a, y) : gamma_inc_Q(a, y);
}
double cdf_chisq_Q(double x, double df)
{
return cdf_gamma_Q(x, df / 2., 2.);
} | {
"alphanum_fraction": 0.6060606061,
"avg_line_length": 25.4262295082,
"ext": "c",
"hexsha": "8b01f181c7ab73e4605cbb099c4f5a0c2024b7c4",
"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": "b416ed24df0178244061a9f2aa75c513b3d8df9c",
"max_forks_repo_licenses": [
"Unlicense"
],
"max_forks_repo_name": "DobzhanskyCenterSPBU/RegionsMT.Update",
"max_forks_repo_path": "src/gslsupp.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "b416ed24df0178244061a9f2aa75c513b3d8df9c",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"Unlicense"
],
"max_issues_repo_name": "DobzhanskyCenterSPBU/RegionsMT.Update",
"max_issues_repo_path": "src/gslsupp.c",
"max_line_length": 156,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "b416ed24df0178244061a9f2aa75c513b3d8df9c",
"max_stars_repo_licenses": [
"Unlicense"
],
"max_stars_repo_name": "DobzhanskyCenterSPBU/RegionsMT.Update",
"max_stars_repo_path": "src/gslsupp.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 526,
"size": 1551
} |
#ifndef KGS_GSL_HELPERS_H
#define KGS_GSL_HELPERS_H
#include <string>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_vector.h>
/** Print matrix to cout */
void gsl_matrix_cout ( const gsl_matrix *m);
/** Print matrix to file specified by `filename` */
void gsl_matrix_outtofile ( const gsl_matrix *m, const std::string& filename );
/** Print vector to file specified by `filename` */
void gsl_vector_outtofile ( const gsl_vector *v, const std::string& filename );
/** Print vector to output-stream */
void gsl_vector_out (const gsl_vector *v, std::ostream& os);
/** Print vector to cout */
void gsl_vector_cout (const gsl_vector *v);
/** Return length of vector */
double gsl_vector_length( const gsl_vector *v );
/** Scale vector to length 1.0 */
void gsl_vector_normalize ( gsl_vector *v );
/** Scale vector to specified length */
void gsl_vector_scale_to_length(gsl_vector* ret, double length);
/** Scale vector so largest absolute value of any component is at most `maxComponent`.
* If the values of all components are less than `maxComponent` no scaling is performed. */
void gsl_vector_scale_max_component(gsl_vector* v, double maxComponent);
/** Make a copy of the vector */
gsl_vector* gsl_vector_copy(gsl_vector*);
gsl_matrix* gsl_matrix_trans(gsl_matrix* A);
gsl_matrix* gsl_matrix_mul(gsl_matrix* A, gsl_matrix* B);
gsl_vector* gsl_matrix_vector_mul(gsl_matrix* A, gsl_vector* v);
gsl_matrix* pca (gsl_matrix* sample_matrix);
gsl_vector* RandomUnitVector (int size);
double frobenius_norm (const gsl_matrix *m);
/** Compute Shannon entropy (as in JCIM paper: fraction of significant contributors) for given input vector**/
double fractionOfSignificantContributors(const gsl_vector *v);
/** Compute Shannon entropy unnormalized: number of significant contributors of given input vector**/
double significantContributors(const gsl_vector *v);
/** Compute Shannon entropy from information theory in bits for given input vector**/
double shannonEntropyInBits(const gsl_vector* v);
/** Compute Shannon entropy from information theory in bits for given input vector**/
double shannonEntropyUnnormalizedInBits(const gsl_vector* v);
#endif //KGS_GSL_HELPERS_H
| {
"alphanum_fraction": 0.7662573897,
"avg_line_length": 33.8307692308,
"ext": "h",
"hexsha": "68ad83408515aafcfa10c2f98c63739731e6de44",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "117c4a3d39ec6285eccc1d3b8e5de9a21db21ec9",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "XiyuChenFAU/kgs_vibration_entropy",
"max_forks_repo_path": "src/math/gsl_helpers.h",
"max_issues_count": 8,
"max_issues_repo_head_hexsha": "117c4a3d39ec6285eccc1d3b8e5de9a21db21ec9",
"max_issues_repo_issues_event_max_datetime": "2021-02-06T16:06:30.000Z",
"max_issues_repo_issues_event_min_datetime": "2017-01-26T19:54:38.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "XiyuChenFAU/kgs_vibration_entropy",
"max_issues_repo_path": "src/math/gsl_helpers.h",
"max_line_length": 110,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "117c4a3d39ec6285eccc1d3b8e5de9a21db21ec9",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "XiyuChenFAU/kgs_vibration_entropy",
"max_stars_repo_path": "src/math/gsl_helpers.h",
"max_stars_repo_stars_event_max_datetime": "2020-05-23T18:26:14.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-05-23T18:26:14.000Z",
"num_tokens": 507,
"size": 2199
} |
/* tz_fcmp.c
*
* 19-Nov-2007 Initial write: Ting Zhao
*/
#include <gsl/gsl_math.h>
#include "tz_mexutils.h"
void check_argin(int nrhs, const mxArray *prhs[])
{
if (nrhs > 3 || nrhs < 2)
mxErrMsgTxt("TZ_FCMP takes 2~3 arguments.");
if (!(mxIsDouble(prhs[0]) && mxIsDouble(prhs[1])))
mxErrMsgTxt("The first two arguments must be both double arrays.");
if (!tz_mxSameSize(prhs[0], prhs[1]) && !tz_mxIsScalar(prhs[0]) &&
!tz_mxIsScalar(prhs[1]))
mxErrMsgTxt("The first two arguments must have the same size if neither of them is a scalar.");
if (nrhs == 3) {
if (!tz_mxIsDoubleScalar(prhs[2]))
mxErrMsgTxt("The third arguments must be a double scalar.");
}
}
/* tz_fcmp(x1, x2) compare two double float numbers.
* tz_fcmp(x1, x2, ep) compare the double float numbers at the accuracy ep,
* which is 1e-5 by default.
*/
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
check_argin(nrhs, prhs);
double epsilon = 1e-5;
if (nrhs == 3) {
epsilon = *mxGetPr(prhs[2]);
}
mwSize length;
mwSize length1 = tz_mxGetL(prhs[0]);
mwSize length2 = tz_mxGetL(prhs[1]);
const mxArray *array = NULL;
if (mxIsScalar(prhs[0]) && mxIsScalar(prhs[1])) {
plhs[0] = mxCreateNumericMatrix(1, 1, mxINT8_CLASS, mxREAL);
length = 1;
} else if (!mxIsScalar(prhs[0]) && !mxIsScalar(prhs[1])) {
plhs[0] = mxCreateNumericArray(mxGetNumberOfDimensions(prhs[0]),
mxGetDimensions(prhs[0]), mxINT8_CLASS,
mxREAL);
length = length1;
} else {
if (length1 == 1) {
array = prhs[1];
length = length2;
} else {
array = prhs[0];
length = length1;
}
plhs[0] = mxCreateNumericArray(mxGetNumberOfDimensions(array),
mxGetDimensions(array), mxINT8_CLASS,
mxREAL);
}
INT8_T *y = (INT8_T *) mxGetPr(plhs[0]);
double *x1 = mxGetPr(prhs[0]);
double *x2 = mxGetPr(prhs[1]);
mwSize i;
if (length1 == length2) {
for (i = 0; i < length; i++) {
y[i] = (INT8_T) gsl_fcmp(x1[i], x2[i], epsilon);
}
} else if (length1 > length2) {
for (i = 0; i < length; i++) {
y[i] = (INT8_T) gsl_fcmp(x1[i], x2[0], epsilon);
}
} else {
for (i = 0; i < length; i++) {
y[i] = (INT8_T) gsl_fcmp(x1[0], x2[i], epsilon);
}
}
}
| {
"alphanum_fraction": 0.6038961039,
"avg_line_length": 26.5517241379,
"ext": "c",
"hexsha": "44a5a2759bd8dc4e61416818eac4b8f9ee9880dd",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "3ca418add85a59ac7e805d55a600b78330d7e53d",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "zzhmark/vaa3d_tools",
"max_forks_repo_path": "released_plugins/v3d_plugins/neurontracing_neutube/src_neutube/neurolabi/mex/tz_fcmp.c",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "3ca418add85a59ac7e805d55a600b78330d7e53d",
"max_issues_repo_issues_event_max_datetime": "2016-12-03T05:33:13.000Z",
"max_issues_repo_issues_event_min_datetime": "2016-12-03T05:33:13.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "zzhmark/vaa3d_tools",
"max_issues_repo_path": "released_plugins/v3d_plugins/neurontracing_neutube/src_neutube/neurolabi/mex/tz_fcmp.c",
"max_line_length": 99,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "3ca418add85a59ac7e805d55a600b78330d7e53d",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "zzhmark/vaa3d_tools",
"max_stars_repo_path": "released_plugins/v3d_plugins/neurontracing_neutube/src_neutube/neurolabi/mex/tz_fcmp.c",
"max_stars_repo_stars_event_max_datetime": "2021-12-27T19:14:03.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-12-27T19:14:03.000Z",
"num_tokens": 791,
"size": 2310
} |
#pragma once
#include <algorithm>
#include <array>
#include <bitset>
#include <cassert>
#include <cctype>
#include <cerrno>
#include <chrono>
#include <climits>
#include <cmath>
#include <csignal>
#include <cstdarg>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <memory>
#include <numeric>
#include <sstream>
#include <stdexcept>
#include <string>
#include <thread>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include <vector>
#ifdef __linux__
#define LINUX
#endif
#ifdef _MSC_VER
#pragma warning(disable : 4267)
#endif
#include "Base64.h"
#include <GLTFAccessor.h>
#include <GLTFAsset.h>
#include <GLTFBuffer.h>
#include <GLTFBufferView.h>
#include <GLTFMesh.h>
#include <GLTFPrimitive.h>
#include <GLTFScene.h>
#include <GLTFTargetNames.h>
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable : 4996)
#pragma warning(default : 4267)
#endif
#include "rapidjson/document.h"
#ifdef _MSC_VER
#pragma warning(pop)
#endif
#include "rapidjson/prettywriter.h"
#include "rapidjson/stringbuffer.h"
#include "rapidjson/writer.h"
#include <gsl/span>
#include <coveo/enumerable.h>
#include <coveo/linq.h>
#include <maya/M3dView.h>
#include <maya/MAnimControl.h>
#include <maya/MAnimUtil.h>
#include <maya/MArgDatabase.h>
#include <maya/MArgList.h>
#include <maya/MDagModifier.h>
#include <maya/MDagPath.h>
#include <maya/MDagPathArray.h>
#include <maya/MFileIO.h>
#include <maya/MFileObject.h>
#include <maya/MFloatMatrix.h>
#include <maya/MFloatPointArray.h>
#include <maya/MFloatVectorArray.h>
#include <maya/MFnAttribute.h>
#include <maya/MFnBlendShapeDeformer.h>
#include <maya/MFnBlinnShader.h>
#include <maya/MFnCamera.h>
#include <maya/MFnComponentListData.h>
#include <maya/MFnLambertShader.h>
#include <maya/MFnMatrixData.h>
#include <maya/MFnMesh.h>
#include <maya/MFnMessageAttribute.h>
#include <maya/MFnNumericAttribute.h>
#include <maya/MFnPhongShader.h>
#include <maya/MFnSet.h>
#include <maya/MFnSingleIndexedComponent.h>
#include <maya/MFnSkinCluster.h>
#include <maya/MFnStringArrayData.h>
#include <maya/MFnTransform.h>
#include <maya/MFnTypedAttribute.h>
#include <maya/MGlobal.h>
#include <maya/MIOStream.h>
#include <maya/MImage.h>
#include <maya/MItDependencyGraph.h>
#include <maya/MItDependencyNodes.h>
#include <maya/MItGeometry.h>
#include <maya/MItMeshFaceVertex.h>
#include <maya/MItMeshPolygon.h>
#include <maya/MMatrix.h>
#include <maya/MPointArray.h>
#include <maya/MPxCommand.h>
#include <maya/MQuaternion.h>
#include <maya/MRenderSetup.h>
#include <maya/MSelectionList.h>
#include <maya/MStreamUtils.h>
#include <maya/MSyntax.h>
#include <maya/MTime.h>
#include <maya/MUuid.h>
#ifdef isnan
# undef isnan
#endif
| {
"alphanum_fraction": 0.7631483497,
"avg_line_length": 23.1680672269,
"ext": "h",
"hexsha": "b03c37cb6c34c51f598f8f18ed2c8fcc2c0a7913",
"lang": "C",
"max_forks_count": 10,
"max_forks_repo_forks_event_max_datetime": "2022-01-20T13:44:52.000Z",
"max_forks_repo_forks_event_min_datetime": "2020-11-21T09:58:25.000Z",
"max_forks_repo_head_hexsha": "3da15de118e98a10d2edc49b77ad9e61daee5ff1",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "yjcnbnbnb200/Maya2glTF",
"max_forks_repo_path": "src/externals.h",
"max_issues_count": 55,
"max_issues_repo_head_hexsha": "3da15de118e98a10d2edc49b77ad9e61daee5ff1",
"max_issues_repo_issues_event_max_datetime": "2022-03-04T15:05:14.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-07-16T13:27:08.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "yjcnbnbnb200/Maya2glTF",
"max_issues_repo_path": "src/externals.h",
"max_line_length": 43,
"max_stars_count": 86,
"max_stars_repo_head_hexsha": "3da15de118e98a10d2edc49b77ad9e61daee5ff1",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "infinitedescent/Maya2glTF",
"max_stars_repo_path": "src/externals.h",
"max_stars_repo_stars_event_max_datetime": "2022-03-25T09:46:13.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-08-05T01:51:23.000Z",
"num_tokens": 780,
"size": 2757
} |
#pragma once
#include "Sampler.h"
#include "GradUtil.h"
#ifndef _NOGSL
#include <gsl/gsl_vector.h>
#else
#include "FakeGSL.h"
#endif
#include "ActualEvaluators.h"
class BasicSampler : public Sampler {
Interface* interf;
BooleanDAG* dag;
ActualEvaluators* actualEval;
doublereal* xlow;
doublereal* xupp;
int ncontrols;
gsl_vector* tmp;
int RANDOM_SEARCH = 10;
set<int> assertConstraints;
int minimizeNode;
public:
BasicSampler(BooleanDAG* dag_, Interface* interf_, ActualEvaluators* actualEval_, int ncontrols_, doublereal* xlow_, doublereal* xupp_): dag(dag_), interf(interf_), actualEval(actualEval_), ncontrols(ncontrols_), xlow(xlow_), xupp(xupp_) {
minimizeNode = -1;
for (int i = 0; i < dag->size(); i++) { // TODO: this should also be set by caller class
bool_node* n = (*dag)[i];
if (n->type == bool_node::ASSERT && ((ASSERT_node*)n)->isHard()) {
minimizeNode = i;
} else if (n->type == bool_node::ASSERT || Util::isSqrt(n)) {
assertConstraints.insert(i);
} else if (n->type == bool_node::CTRL && n->getOtype() == OutType::BOOL) {
assertConstraints.insert(i);
}
}
tmp = gsl_vector_alloc(ncontrols);
}
virtual void sampleState(gsl_vector* state) {
double best = GradUtil::MAXVAL;
bool foundValid = false;
for (int i = 0; i < RANDOM_SEARCH; i++) {
randomize(tmp);
cout << "Trying: ";
for (int j = 0; j < tmp->size; j++) {
cout << gsl_vector_get(tmp, j) << ", ";
}
actualEval->run(tmp);
double error = getError();
cout << "Error: " << error << endl;
if (error < best) {
best = error;
gsl_vector_memcpy(state, tmp);
}
}
}
void randomize(gsl_vector* state) {
for (int i = 0; i < state->size; i++) {
double low = xlow[i];
double high = xupp[i];
double r = low + (rand() % (int)((high - low) * 10.0))/10.0;
gsl_vector_set(state, i, r);
}
}
double getError() {
double error = 0.0;
double e;
if (minimizeNode >= 0) {
e = actualEval->getErrorOnConstraint(minimizeNode);
if (e > 0.0) {
error += e; // TODO : change this
}
}
for (auto it = assertConstraints.begin(); it != assertConstraints.end(); it++) {
e = actualEval->getErrorOnConstraint(*it);
if (e < 0.0) {
error += -e;
}
}
return error;
}
};
| {
"alphanum_fraction": 0.5345152773,
"avg_line_length": 28.8152173913,
"ext": "h",
"hexsha": "04e1ee83898f0b0bd9e98a0fa348b4d2ae8b7517",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2020-12-06T01:45:04.000Z",
"max_forks_repo_forks_event_min_datetime": "2020-12-04T20:47:51.000Z",
"max_forks_repo_head_hexsha": "6ecbb6f724149d50d290997fef5e2e1e92ab3d9e",
"max_forks_repo_licenses": [
"X11"
],
"max_forks_repo_name": "natebragg/sketch-backend",
"max_forks_repo_path": "src/SketchSolver/NumericalSynthesis/Samplers/BasicSampler.h",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "6ecbb6f724149d50d290997fef5e2e1e92ab3d9e",
"max_issues_repo_issues_event_max_datetime": "2022-03-04T04:02:09.000Z",
"max_issues_repo_issues_event_min_datetime": "2022-03-01T16:53:05.000Z",
"max_issues_repo_licenses": [
"X11"
],
"max_issues_repo_name": "natebragg/sketch-backend",
"max_issues_repo_path": "src/SketchSolver/NumericalSynthesis/Samplers/BasicSampler.h",
"max_line_length": 244,
"max_stars_count": 17,
"max_stars_repo_head_hexsha": "6ecbb6f724149d50d290997fef5e2e1e92ab3d9e",
"max_stars_repo_licenses": [
"X11"
],
"max_stars_repo_name": "natebragg/sketch-backend",
"max_stars_repo_path": "src/SketchSolver/NumericalSynthesis/Samplers/BasicSampler.h",
"max_stars_repo_stars_event_max_datetime": "2022-03-31T00:28:40.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-08-20T14:54:11.000Z",
"num_tokens": 710,
"size": 2651
} |
#include <math.h>
#include <stdio.h>
#include <gsl/gsl_rng.h>
#include "matrix_operations.c"
#include "ellipsoid/parametric_function_roots.c"
#include "polynomial.c"
void characteristic_ellipsoid_matrix(double *X, double *R, double phi, double *rotax, double exponent)
{
double w, x, y, z;
w = cos(phi / 2.0);
x = sin(phi / 2.0) * rotax[0];
y = sin(phi / 2.0) * rotax[1];
z = sin(phi / 2.0) * rotax[2];
// Rotation matrix
double Q[3][3] = {{ 0 }};
Q[0][0] = 1.0 - 2.0 * (pow(y, 2) + pow(z, 2));
Q[0][1] = 2.0 * (x * y + w * z);
Q[0][2] = 2.0 * (x * z - w * y);
Q[1][0] = 2.0 * (x * y - w * z);
Q[1][1] = 1.0 - 2.0 * (pow(x, 2) + pow(z, 2));
Q[1][2] = 2.0 * (y * z + w * x);
Q[2][0] = 2.0 * (x * z + w * y);
Q[2][1] = 2.0 * (y * z - w * x);
Q[2][2] = 1.0 - 2.0 * (pow(x, 2) + pow(y, 2));
//Rotation matrix transpose
double Qt[3][3] = {{ 0 }};
matrix_transpose(&Qt[0][0], &Q[0][0], 3, 3);
// radii matrix
double O[3][3] = {{ 0 }};
double diag_vals[3];
diag_vals[0] = pow(R[0], exponent * -2.0);
diag_vals[1] = pow(R[1], exponent * -2.0);
diag_vals[2] = pow(R[2], exponent * -2.0);
set_diagonal(&O[0][0], diag_vals, 3, 3);
// characteristic ellipse matrix
double X_temp[3][3] = {{ 0 }};
matrix_multiply(&X_temp[0][0], &O[0][0], &Q[0][0], 3, 3, 3);
matrix_multiply(X, &Qt[0][0], &X_temp[0][0], 3, 3, 3);
}
double ellipsoid_overlap(double *rA, double *radiiA, double phiA, double *rotaxA,
double *rB, double *radiiB, double phiB, double *rotaxB)
{
// find XA^(-1) and XB^(1/2)
double XA[3][3] = {{ 0 }};
double XB[3][3] = {{ 0 }};
characteristic_ellipsoid_matrix(&XA[0][0], &radiiA[0], phiA, &rotaxA[0], -1.0);
characteristic_ellipsoid_matrix(&XB[0][0], &radiiB[0], phiB, &rotaxB[0], 0.5);
// find A_AB
double A_AB[3][3] = {{ 0 }};
double A_temp[3][3] = {{ 0 }};
matrix_multiply(&A_temp[0][0], &XA[0][0], &XB[0][0], 3, 3, 3);
matrix_multiply(&A_AB[0][0], &XB[0][0], &A_temp[0][0], 3, 3, 3);
// find r_AB
double rAB[3];
rAB[0] = rB[0] - rA[0];
rAB[1] = rB[1] - rA[1];
rAB[2] = rB[2] - rA[2];
// find a_AB
double a_AB[3];
matrix_multiply(&a_AB[0], &XB[0][0], &rAB[0], 3, 3, 1);
// extract elements of the matrix A_AB and a_AB
double a11, a12, a13, a21, a22, a23, a31, a32, a33;
double b1, b2, b3;
a11 = A_AB[0][0];
a12 = A_AB[0][1];
a13 = A_AB[0][2];
a21 = A_AB[1][0];
a22 = A_AB[1][1];
a23 = A_AB[1][2];
a31 = A_AB[2][0];
a32 = A_AB[2][1];
a33 = A_AB[2][2];
b1 = a_AB[0];
b2 = a_AB[1];
b3 = a_AB[2];
// find coefficients for the parametric polynomial derivative used to find max
double h[7];
double z[12] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
size_t n = 7;
h[0] = h0(a11, a12, a13, a21, a22, a23, a31, a32, a33, b1, b2, b3);
h[1] = h1(a11, a12, a13, a21, a22, a23, a31, a32, a33, b1, b2, b3);
h[2] = h2(a11, a12, a13, a21, a22, a23, a31, a32, a33, b1, b2, b3);
h[3] = h3(a11, a12, a13, a21, a22, a23, a31, a32, a33, b1, b2, b3);
h[4] = h4(a11, a12, a13, a21, a22, a23, a31, a32, a33, b1, b2, b3);
h[5] = h5(a11, a12, a13, a21, a22, a23, a31, a32, a33, b1, b2, b3);
h[6] = h6(a11, a12, a13, a21, a22, a23, a31, a32, a33, b1, b2, b3);
// find roots
size_t m;
m = find_roots(&z[0], &h[0], n);
double F;
int i;
if (m > 1)
{
if (f(0, a11, a12, a13, a21, a22, a23, a31, a32, a33, b1, b2, b3) > f(1, a11, a12, a13, a21, a22, a23, a31, a32, a33, b1, b2, b3))
{
F = f(0, a11, a12, a13, a21, a22, a23, a31, a32, a33, b1, b2, b3);
}
else
{
F = f(1, a11, a12, a13, a21, a22, a23, a31, a32, a33, b1, b2, b3);
}
for(i=0; i<=m-2; i++)
{
if (( z[2 * i + 1] == 0 ) & (z[2 * i] > 0) & (z[2 * i] < 1))
{
F = f(z[2 * i], a11, a12, a13, a21, a22, a23, a31, a32, a33, b1, b2, b3);
}
}
}
else
{
F = 0.;
}
return F;
}
double container_cube_overlap_potential(double *rA, double *radiiA, double phiA, double *rotaxA)
{
double rB[3];
double radiiB[3];
double phiB;
double rotaxB[3];
double top, bottom, left, right, front, back;
// top
rB[0] = 0.5;
rB[1] = 0.5;
rB[2] = 2;
radiiB[0] = INFINITY;
radiiB[1] = INFINITY;
radiiB[2] = 1;
rotaxB[0] = 1;
rotaxB[1] = 0;
rotaxB[2] = 0;
phiB = 0.0;
top = ellipsoid_overlap(&rA[0], &radiiA[0], phiA, &rotaxA[0], &rB[0], &radiiB[0], phiB, &rotaxB[0]);
// bottom
rB[0] = 0.5;
rB[1] = 0.5;
rB[2] = -1;
radiiB[0] = INFINITY;
radiiB[1] = INFINITY;
radiiB[2] = 1.0;
rotaxB[0] = 1;
rotaxB[1] = 0;
rotaxB[2] = 0;
phiB = 0;
bottom = ellipsoid_overlap(&rA[0], &radiiA[0], phiA, &rotaxA[0], &rB[0], &radiiB[0], phiB, &rotaxB[0]);
// left
rB[0] = 0.5;
rB[1] = -1.0;
rB[2] = 0.5;
radiiB[0] = INFINITY;
radiiB[1] = 1;
radiiB[2] = INFINITY;
rotaxB[0] = 1;
rotaxB[1] = 0;
rotaxB[2] = 0;
phiB = 0;
left = ellipsoid_overlap(&rA[0], &radiiA[0], phiA, &rotaxA[0], &rB[0], &radiiB[0], phiB, &rotaxB[0]);
// right
rB[0] = 0.5;
rB[1] = 2;
rB[2] = 0.5;
radiiB[0] = INFINITY;
radiiB[1] = 1;
radiiB[2] = INFINITY;
rotaxB[0] = 1;
rotaxB[1] = 0;
rotaxB[2] = 0;
phiB = 0;
right = ellipsoid_overlap(&rA[0], &radiiA[0], phiA, &rotaxA[0], &rB[0], &radiiB[0], phiB, &rotaxB[0]);
// front
rB[0] = -1.0;
rB[1] = 0.5;
rB[2] = 0.5;
radiiB[0] = 1.0;
radiiB[1] = INFINITY;
radiiB[2] = INFINITY;
rotaxB[0] = 1.0;
rotaxB[1] = 0.0;
rotaxB[2] = 0.0;
phiB = 0.0;
front = ellipsoid_overlap(&rA[0], &radiiA[0], phiA, &rotaxA[0], &rB[0], &radiiB[0], phiB, &rotaxB[0]);
// back
rB[0] = 2.0;
rB[1] = 0.5;
rB[2] = 0.5;
radiiB[0] = 1;
radiiB[1] = INFINITY;
radiiB[2] = INFINITY;
rotaxB[0] = 1.0;
rotaxB[1] = 0.0;
rotaxB[2] = 0.0;
phiB = 0;
back = ellipsoid_overlap(&rA[0], &radiiA[0], phiA, &rotaxA[0], &rB[0], &radiiB[0], phiB, &rotaxB[0]);
return fminf(top, fminf(bottom, fminf(left, fminf(right, fminf(front, back)))));
}
void random_point_on_sphere(double *rotax, double theta, double z)
{
double x, y;
x = sqrt(1 - pow(z, 2)) * cos(theta);
y = sqrt(1 - pow(z, 2)) * sin(theta);
rotax[0] = x;
rotax[1] = y;
rotax[2] = z;
}
size_t rsa_align_cube(double *x, double *y, double *z,
size_t npoints, double *radius, double *rotax, double phi,
int step_limit, unsigned long randSeed)
{
// Setup GSL random number generator
const gsl_rng_type * T;
gsl_rng * r;
T = gsl_rng_default;
r = gsl_rng_alloc (T);
// Set the seed
// srand ( time(NULL) );
// unsigned long randSeed = rand();
gsl_rng_set(r, randSeed);
double rA[3];
double radiiA[3];
double phiA;
double rotaxA[3];
double rB[3];
double radiiB[3];
double phiB;
double rotaxB[3];
size_t valid_pts;
double F, G;
int k, flag, step;
step = 0;
valid_pts = 1;
// Get new ellipsoid position and orientation
G = 0;
while (G < 1)
{
rB[0] = gsl_rng_uniform (r);
rB[1] = gsl_rng_uniform (r);
rB[2] = gsl_rng_uniform (r);
radiiB[0] = radius[0];
radiiB[1] = radius[1];
radiiB[2] = radius[2];
phiB = phi;
rotaxB[0] = rotax[0];
rotaxB[1] = rotax[1];
rotaxB[2] = rotax[2];
G = container_cube_overlap_potential(&rB[0], &radiiB[0], phiB, &rotaxB[0]);
}
// store ellipsoid position
x[0] = rB[0];
y[0] = rB[1];
z[0] = rB[2];
// Generate ellipsoid positions
while ((valid_pts < npoints) & (step < step_limit))
{
// Get new ellipsoid position and orientation
G = 0;
while (G < 1)
{
rB[0] = gsl_rng_uniform (r);
rB[1] = gsl_rng_uniform (r);
rB[2] = gsl_rng_uniform (r);
radiiB[0] = radius[0];
radiiB[1] = radius[1];
radiiB[2] = radius[2];
phiB = phi;
rotaxB[0] = rotax[0];
rotaxB[1] = rotax[1];
rotaxB[2] = rotax[2];
G = container_cube_overlap_potential(&rB[0], &radiiB[0], phiB, &rotaxB[0]);
}
flag = 1;
for (k = 0; k < valid_pts; k++)
{
rA[0] = x[k];
rA[1] = y[k];
rA[2] = z[k];
radiiA[0] = radius[0];
radiiA[1] = radius[1];
radiiA[2] = radius[2];
phiA = phi;
rotaxA[0] = rotax[0];
rotaxA[1] = rotax[1];
rotaxA[2] = rotax[2];
F = ellipsoid_overlap(&rA[0], &radiiA[0], phiA, &rotaxA[0],
&rB[0], &radiiB[0], phiB, &rotaxB[0]);
if (F < 1.0)
{
flag = 0;
break;
}
}
if (flag == 1)
{
x[valid_pts] = rB[0];
y[valid_pts] = rB[1];
z[valid_pts] = rB[2];
valid_pts += 1;
}
step += 1;
}
gsl_rng_free (r);
return valid_pts;
}
size_t rsa_cube(double *x, double *y, double *z,
size_t npoints, double *radius,
double *rtx, double *rty, double *rtz, double *phi,
int step_limit, unsigned long randSeed)
{
// Setup GSL random number generator
const gsl_rng_type * T;
gsl_rng * r;
T = gsl_rng_default;
r = gsl_rng_alloc (T);
// Set the seed
// srand ( time(NULL) );
// unsigned long randSeed = rand();
gsl_rng_set(r, randSeed);
double rA[3];
double radiiA[3];
double phiA;
double rotaxA[3];
double rB[3];
double radiiB[3];
double phiB;
double rotaxB[3];
double theta, sz;
size_t valid_pts;
double F, G;
int k, flag, step;
step = 0;
valid_pts = 1;
// Get new ellipsoid position and orientation
G = 0;
while (G < 1)
{
rB[0] = gsl_rng_uniform (r);
rB[1] = gsl_rng_uniform (r);
rB[2] = gsl_rng_uniform (r);
radiiB[0] = radius[0];
radiiB[1] = radius[1];
radiiB[2] = radius[2];
phiB = 2 * M_PI * gsl_rng_uniform (r);
// random rotation axis
theta = 2 * M_PI * gsl_rng_uniform (r);
sz = 2 * gsl_rng_uniform (r) - 1;
random_point_on_sphere(&rotaxB[0], theta, sz);
G = container_cube_overlap_potential(&rB[0], &radiiB[0], phiB, &rotaxB[0]);
}
// store ellipsoid position
x[0] = rB[0];
y[0] = rB[1];
z[0] = rB[2];
rtx[0] = rotaxB[0];
rty[0] = rotaxB[1];
rtz[0] = rotaxB[2];
phi[0] = phiB;
// Generate ellipsoid positions
while ((valid_pts < npoints) & (step < step_limit))
{
// Get new ellipsoid position and orientation
G = 0;
while (G < 1)
{
rB[0] = gsl_rng_uniform (r);
rB[1] = gsl_rng_uniform (r);
rB[2] = gsl_rng_uniform (r);
radiiB[0] = radius[0];
radiiB[1] = radius[1];
radiiB[2] = radius[2];
phiB = 2 * M_PI * gsl_rng_uniform (r);
// random rotation axis
theta = 2 * M_PI * gsl_rng_uniform (r);
sz = 2 * gsl_rng_uniform (r) - 1;
random_point_on_sphere(&rotaxB[0], theta, sz);
G = container_cube_overlap_potential(&rB[0], &radiiB[0], phiB, &rotaxB[0]);
}
flag = 1;
for (k = 0; k < valid_pts; k++)
{
rA[0] = x[k];
rA[1] = y[k];
rA[2] = z[k];
radiiA[0] = radius[0];
radiiA[1] = radius[1];
radiiA[2] = radius[2];
phiA = phi[k];
rotaxA[0] = rtx[k];
rotaxA[1] = rty[k];
rotaxA[2] = rtz[k];
F = ellipsoid_overlap(&rA[0], &radiiA[0], phiA, &rotaxA[0],
&rB[0], &radiiB[0], phiB, &rotaxB[0]);
if (F < 1.0)
{
flag = 0;
break;
}
}
if (flag == 1)
{
x[valid_pts] = rB[0];
y[valid_pts] = rB[1];
z[valid_pts] = rB[2];
rtx[valid_pts] = rotaxB[0];
rty[valid_pts] = rotaxB[1];
rtz[valid_pts] = rotaxB[2];
phi[valid_pts] = phiB;
valid_pts += 1;
}
step += 1;
}
gsl_rng_free (r);
return valid_pts;
} | {
"alphanum_fraction": 0.476223995,
"avg_line_length": 19.8540372671,
"ext": "c",
"hexsha": "f8af763794094503799982eed71447a152965448",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "127603a519ae25979de6c6197810a7ea38ec945b",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "aluchies/particle_packing",
"max_forks_repo_path": "particle_packing/cython/c/ellipsoid.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "127603a519ae25979de6c6197810a7ea38ec945b",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "aluchies/particle_packing",
"max_issues_repo_path": "particle_packing/cython/c/ellipsoid.c",
"max_line_length": 138,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "127603a519ae25979de6c6197810a7ea38ec945b",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "aluchies/particle_packing",
"max_stars_repo_path": "particle_packing/cython/c/ellipsoid.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 5108,
"size": 12786
} |
#pragma once
#include <gsl/span>
#include "halley/data_structures/vector.h"
#include "component_schema.h"
#include "custom_type_schema.h"
#include "halley/data_structures/hash_map.h"
#include "halley/text/halleystring.h"
#include "message_schema.h"
#include "system_message_schema.h"
#include "system_schema.h"
namespace YAML
{
class Node;
}
namespace Halley {
struct CodegenSourceInfo {
String filename;
gsl::span<const gsl::byte> data;
bool generate = false;
};
class Codegen;
class ECSData {
public:
void loadSources(Vector<CodegenSourceInfo> files);
const HashMap<String, ComponentSchema>& getComponents() const;
const HashMap<String, SystemSchema>& getSystems() const;
const HashMap<String, MessageSchema>& getMessages() const;
const HashMap<String, SystemMessageSchema>& getSystemMessages() const;
const HashMap<String, CustomTypeSchema>& getCustomTypes() const;
void clear();
int getRevision() const;
private:
void addSource(CodegenSourceInfo sourceInfo);
void addComponent(YAML::Node rootNode, bool generate);
void addSystem(YAML::Node rootNode, bool generate);
void addMessage(YAML::Node rootNode, bool generate);
void addSystemMessage(YAML::Node rootNode, bool generate);
void addType(YAML::Node rootNode);
String getInclude(String typeName) const;
void validate();
void process();
HashMap<String, ComponentSchema> components;
HashMap<String, SystemSchema> systems;
HashMap<String, MessageSchema> messages;
HashMap<String, SystemMessageSchema> systemMessages;
HashMap<String, CustomTypeSchema> types;
int revision = 0;
};
}
| {
"alphanum_fraction": 0.7486204782,
"avg_line_length": 27.6440677966,
"ext": "h",
"hexsha": "e53befdc4674af2306603ab78c8450f6e645c3ed",
"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": "5f6a5dd7d44b9c12d2c124436969ff2dfa69e3f4",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "amrezzd/halley",
"max_forks_repo_path": "src/tools/tools/include/halley/tools/ecs/ecs_data.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "5f6a5dd7d44b9c12d2c124436969ff2dfa69e3f4",
"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": "amrezzd/halley",
"max_issues_repo_path": "src/tools/tools/include/halley/tools/ecs/ecs_data.h",
"max_line_length": 72,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "5f6a5dd7d44b9c12d2c124436969ff2dfa69e3f4",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "amrezzd/halley",
"max_stars_repo_path": "src/tools/tools/include/halley/tools/ecs/ecs_data.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 371,
"size": 1631
} |
#ifndef __INTEGRAL_H__
#define __INTEGRAL_H__
#include "basis.h"
#include "gslextra.h"
#include <math.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_sf.h>
typedef struct gaussian_chain{
double R[3];
int a[3];
double exponent;
double coefficient;
gaussian_chain * NEXT;
}gaussian_chain;
gaussian_chain * gaussian_chain_calloc();
void gaussian_chain_free(gaussian_chain * HEAD);
double gaussian_chain_get(gaussian_chain * HEAD,double x, double y, double z);
double orbital_get(orbital * orbital,double x, double y, double z);
double SIntegral(double ra[3], double rb[3], int ax, int ay, int az, int bx, int by, int bz, double alpha,double beta);
double gaussian_chain_SIntegral(gaussian_chain * a, gaussian_chain * b);
double gaussian_chain_full_SIntegral(gaussian_chain * a_HEAD, gaussian_chain * b_HEAD);
void single_electron_transform(gaussian_chain * HEAD, orbital * a);
double orbital_SIntegral(orbital * a,orbital * b);
void orbital_S_matrix(gsl_matrix * dest, orbital * HEAD, int length);
#endif | {
"alphanum_fraction": 0.7539756782,
"avg_line_length": 26.0731707317,
"ext": "h",
"hexsha": "befbfeda1bc974f9259c2f868a7350ac9ac17a8a",
"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": "daddeb4b81bd93cd5450b1a172c8653dbbfc26d6",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "Walter-Feng/Overlap",
"max_forks_repo_path": "include/integral.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "daddeb4b81bd93cd5450b1a172c8653dbbfc26d6",
"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": "Walter-Feng/Overlap",
"max_issues_repo_path": "include/integral.h",
"max_line_length": 119,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "daddeb4b81bd93cd5450b1a172c8653dbbfc26d6",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "Walter-Feng/Overlap",
"max_stars_repo_path": "include/integral.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 268,
"size": 1069
} |
/******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* 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 <cblas.h>
#include <cuda_runtime_api.h>
#include <boost/shared_ptr.hpp>
#include <fstream>
#include <iostream>
#include <map>
#include <string>
#include <vector>
#include "modules/perception/base/blob.h"
#include "modules/perception/base/image.h"
namespace apollo {
namespace perception {
namespace inference {
class GPUL2Norm {
public:
void L2Norm(base::Blob<float> *input_data);
private:
base::Blob<float> scale_;
base::Blob<float> ones_;
base::Blob<float> square_;
};
void GPUGemmFloat(const CBLAS_TRANSPOSE TransA, const CBLAS_TRANSPOSE TransB,
const int M, const int N, const int K, const float alpha,
const float *A, const float *B, const float beta, float *C);
void GPUMultiFloat(const int n, const float *a, const float *b, float *result);
void GPUMSetFloat(const int n, const float alpha, float *result);
} // namespace inference
} // namespace perception
} // namespace apollo
| {
"alphanum_fraction": 0.6607245543,
"avg_line_length": 32.2037037037,
"ext": "h",
"hexsha": "37b194c0d21180f39f2b703b19931cee4bf341bc",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2019-02-24T06:20:29.000Z",
"max_forks_repo_forks_event_min_datetime": "2019-02-24T06:20:29.000Z",
"max_forks_repo_head_hexsha": "808f1d20a08efea23b718b4e423d6619c9d4b412",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "thomasgui76/apollo",
"max_forks_repo_path": "modules/perception/inference/utils/gemm.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "808f1d20a08efea23b718b4e423d6619c9d4b412",
"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": "thomasgui76/apollo",
"max_issues_repo_path": "modules/perception/inference/utils/gemm.h",
"max_line_length": 79,
"max_stars_count": 2,
"max_stars_repo_head_hexsha": "002eba4a1635d6af7f1ebd2118464bca6f86b106",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "ghdawn/apollo",
"max_stars_repo_path": "modules/perception/inference/utils/gemm.h",
"max_stars_repo_stars_event_max_datetime": "2019-03-15T06:31:33.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-03-15T06:28:38.000Z",
"num_tokens": 373,
"size": 1739
} |
/* specfunc/hyperg.c
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
/* Author: G. Jungman */
/* Miscellaneous implementations of use
* for evaluation of hypergeometric functions.
*/
#include <config.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_errno.h>
#include "gsl_sf_exp.h"
#include "gsl_sf_gamma.h"
#include "error.h"
#include "hyperg.h"
#define SUM_LARGE (1.0e-5*GSL_DBL_MAX)
int
gsl_sf_hyperg_1F1_series_e(const double a, const double b, const double x,
gsl_sf_result * result
)
{
double an = a;
double bn = b;
double n = 1.0;
double del = 1.0;
double abs_del = 1.0;
double max_abs_del = 1.0;
double sum_val = 1.0;
double sum_err = 0.0;
while(abs_del/fabs(sum_val) > GSL_DBL_EPSILON) {
double u, abs_u;
if(bn == 0.0) {
DOMAIN_ERROR(result);
}
if(an == 0.0 || n > 1000.0) {
result->val = sum_val;
result->err = sum_err;
result->err += 2.0 * GSL_DBL_EPSILON * n * fabs(sum_val);
return GSL_SUCCESS;
}
u = x * (an/(bn*n));
abs_u = fabs(u);
if(abs_u > 1.0 && max_abs_del > GSL_DBL_MAX/abs_u) {
result->val = sum_val;
result->err = fabs(sum_val);
GSL_ERROR ("overflow", GSL_EOVRFLW);
}
del *= u;
sum_val += del;
if(fabs(sum_val) > SUM_LARGE) {
result->val = sum_val;
result->err = fabs(sum_val);
GSL_ERROR ("overflow", GSL_EOVRFLW);
}
abs_del = fabs(del);
max_abs_del = GSL_MAX_DBL(abs_del, max_abs_del);
sum_err += 2.0*GSL_DBL_EPSILON*abs_del;
an += 1.0;
bn += 1.0;
n += 1.0;
}
result->val = sum_val;
result->err = sum_err;
result->err += abs_del;
result->err += 2.0 * GSL_DBL_EPSILON * n * fabs(sum_val);
return GSL_SUCCESS;
}
int
gsl_sf_hyperg_1F1_large_b_e(const double a, const double b, const double x, gsl_sf_result * result)
{
if(fabs(x/b) < 1.0) {
const double u = x/b;
const double v = 1.0/(1.0-u);
const double pre = pow(v,a);
const double uv = u*v;
const double uv2 = uv*uv;
const double t1 = a*(a+1.0)/(2.0*b)*uv2;
const double t2a = a*(a+1.0)/(24.0*b*b)*uv2;
const double t2b = 12.0 + 16.0*(a+2.0)*uv + 3.0*(a+2.0)*(a+3.0)*uv2;
const double t2 = t2a*t2b;
result->val = pre * (1.0 - t1 + t2);
result->err = pre * GSL_DBL_EPSILON * (1.0 + fabs(t1) + fabs(t2));
result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val);
return GSL_SUCCESS;
}
else {
DOMAIN_ERROR(result);
}
}
int
gsl_sf_hyperg_U_large_b_e(const double a, const double b, const double x,
gsl_sf_result * result,
double * ln_multiplier
)
{
double N = floor(b); /* b = N + eps */
double eps = b - N;
if(fabs(eps) < GSL_SQRT_DBL_EPSILON) {
double lnpre_val;
double lnpre_err;
gsl_sf_result M;
if(b > 1.0) {
double tmp = (1.0-b)*log(x);
gsl_sf_result lg_bm1;
gsl_sf_result lg_a;
gsl_sf_lngamma_e(b-1.0, &lg_bm1);
gsl_sf_lngamma_e(a, &lg_a);
lnpre_val = tmp + x + lg_bm1.val - lg_a.val;
lnpre_err = lg_bm1.err + lg_a.err + GSL_DBL_EPSILON * (fabs(x) + fabs(tmp));
gsl_sf_hyperg_1F1_large_b_e(1.0-a, 2.0-b, -x, &M);
}
else {
gsl_sf_result lg_1mb;
gsl_sf_result lg_1pamb;
gsl_sf_lngamma_e(1.0-b, &lg_1mb);
gsl_sf_lngamma_e(1.0+a-b, &lg_1pamb);
lnpre_val = lg_1mb.val - lg_1pamb.val;
lnpre_err = lg_1mb.err + lg_1pamb.err;
gsl_sf_hyperg_1F1_large_b_e(a, b, x, &M);
}
if(lnpre_val > GSL_LOG_DBL_MAX-10.0) {
result->val = M.val;
result->err = M.err;
*ln_multiplier = lnpre_val;
GSL_ERROR ("overflow", GSL_EOVRFLW);
}
else {
gsl_sf_result epre;
int stat_e = gsl_sf_exp_err_e(lnpre_val, lnpre_err, &epre);
result->val = epre.val * M.val;
result->err = epre.val * M.err + epre.err * fabs(M.val);
result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val);
*ln_multiplier = 0.0;
return stat_e;
}
}
else {
double omb_lnx = (1.0-b)*log(x);
gsl_sf_result lg_1mb; double sgn_1mb;
gsl_sf_result lg_1pamb; double sgn_1pamb;
gsl_sf_result lg_bm1; double sgn_bm1;
gsl_sf_result lg_a; double sgn_a;
gsl_sf_result M1, M2;
double lnpre1_val, lnpre2_val;
double lnpre1_err, lnpre2_err;
double sgpre1, sgpre2;
gsl_sf_hyperg_1F1_large_b_e( a, b, x, &M1);
gsl_sf_hyperg_1F1_large_b_e(1.0-a, 2.0-b, x, &M2);
gsl_sf_lngamma_sgn_e(1.0-b, &lg_1mb, &sgn_1mb);
gsl_sf_lngamma_sgn_e(1.0+a-b, &lg_1pamb, &sgn_1pamb);
gsl_sf_lngamma_sgn_e(b-1.0, &lg_bm1, &sgn_bm1);
gsl_sf_lngamma_sgn_e(a, &lg_a, &sgn_a);
lnpre1_val = lg_1mb.val - lg_1pamb.val;
lnpre1_err = lg_1mb.err + lg_1pamb.err;
lnpre2_val = lg_bm1.val - lg_a.val - omb_lnx - x;
lnpre2_err = lg_bm1.err + lg_a.err + GSL_DBL_EPSILON * (fabs(omb_lnx)+fabs(x));
sgpre1 = sgn_1mb * sgn_1pamb;
sgpre2 = sgn_bm1 * sgn_a;
if(lnpre1_val > GSL_LOG_DBL_MAX-10.0 || lnpre2_val > GSL_LOG_DBL_MAX-10.0) {
double max_lnpre_val = GSL_MAX(lnpre1_val,lnpre2_val);
double max_lnpre_err = GSL_MAX(lnpre1_err,lnpre2_err);
double lp1 = lnpre1_val - max_lnpre_val;
double lp2 = lnpre2_val - max_lnpre_val;
double t1 = sgpre1*exp(lp1);
double t2 = sgpre2*exp(lp2);
result->val = t1*M1.val + t2*M2.val;
result->err = fabs(t1)*M1.err + fabs(t2)*M2.err;
result->err += GSL_DBL_EPSILON * exp(max_lnpre_err) * (fabs(t1*M1.val) + fabs(t2*M2.val));
result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val);
*ln_multiplier = max_lnpre_val;
GSL_ERROR ("overflow", GSL_EOVRFLW);
}
else {
double t1 = sgpre1*exp(lnpre1_val);
double t2 = sgpre2*exp(lnpre2_val);
result->val = t1*M1.val + t2*M2.val;
result->err = fabs(t1) * M1.err + fabs(t2)*M2.err;
result->err += GSL_DBL_EPSILON * (exp(lnpre1_err)*fabs(t1*M1.val) + exp(lnpre2_err)*fabs(t2*M2.val));
result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val);
*ln_multiplier = 0.0;
return GSL_SUCCESS;
}
}
}
/* [Carlson, p.109] says the error in truncating this asymptotic series
* is less than the absolute value of the first neglected term.
*
* A termination argument is provided, so that the series will
* be summed at most up to n=n_trunc. If n_trunc is set negative,
* then the series is summed until it appears to start diverging.
*/
int
gsl_sf_hyperg_2F0_series_e(const double a, const double b, const double x,
int n_trunc,
gsl_sf_result * result
)
{
const int maxiter = 2000;
double an = a;
double bn = b;
double n = 1.0;
double sum = 1.0;
double del = 1.0;
double abs_del = 1.0;
double max_abs_del = 1.0;
double last_abs_del = 1.0;
while(abs_del/fabs(sum) > GSL_DBL_EPSILON && n < maxiter) {
double u = an * (bn/n * x);
double abs_u = fabs(u);
if(abs_u > 1.0 && (max_abs_del > GSL_DBL_MAX/abs_u)) {
result->val = sum;
result->err = fabs(sum);
GSL_ERROR ("overflow", GSL_EOVRFLW);
}
del *= u;
sum += del;
abs_del = fabs(del);
if(abs_del > last_abs_del) break; /* series is probably starting to grow */
last_abs_del = abs_del;
max_abs_del = GSL_MAX(abs_del, max_abs_del);
an += 1.0;
bn += 1.0;
n += 1.0;
if(an == 0.0 || bn == 0.0) break; /* series terminated */
if(n_trunc >= 0 && n >= n_trunc) break; /* reached requested timeout */
}
result->val = sum;
result->err = GSL_DBL_EPSILON * n + abs_del;
if(n >= maxiter)
GSL_ERROR ("error", GSL_EMAXITER);
else
return GSL_SUCCESS;
}
| {
"alphanum_fraction": 0.612823819,
"avg_line_length": 29.9333333333,
"ext": "c",
"hexsha": "a13950fb99ea69c3099e1f32f9bb618a26e7bfaf",
"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/specfunc/hyperg.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/specfunc/hyperg.c",
"max_line_length": 107,
"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/specfunc/hyperg.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": 2874,
"size": 8531
} |
/*
* Copyright (c) 1997-1999 Massachusetts Institute of Technology
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
#ifndef FFTW_MPI_H
#define FFTW_MPI_H
#include <fftw.h>
#include <mpi.h> /* need access to the MPI type definitions */
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
/***********************************************************************/
typedef fftw_real TRANSPOSE_EL_TYPE;
typedef struct {
int block_num, dest_pe, send_size, recv_size;
} transpose_mpi_exchange;
typedef struct {
MPI_Comm comm;
int n_pes, my_pe;
int nx,ny,local_nx,local_ny;
transpose_mpi_exchange *exchange;
int num_steps, send_block_size, recv_block_size;
MPI_Datatype el_type;
MPI_Request request[2];
int *perm_block_dest;
int num_perm_blocks, perm_block_size;
int all_blocks_equal;
int *send_block_sizes, *send_block_offsets;
int *recv_block_sizes, *recv_block_offsets;
char *move;
int move_size;
} transpose_mpi_plan_struct;
typedef transpose_mpi_plan_struct *transpose_mpi_plan;
extern void transpose_mpi_get_local_size(int n, int my_pe, int n_pes,
int *local_n, int *local_start);
extern int transpose_mpi_get_local_storage_size(int nx, int ny,
int my_pe, int n_pes);
extern transpose_mpi_plan transpose_mpi_create_plan(int nx, int ny,
MPI_Comm comm);
extern void transpose_mpi_destroy_plan(transpose_mpi_plan p);
extern void transpose_mpi(transpose_mpi_plan p, int el_size,
TRANSPOSE_EL_TYPE *local_data,
TRANSPOSE_EL_TYPE *work);
typedef enum { BEFORE_TRANSPOSE, AFTER_TRANSPOSE } transpose_in_place_which;
typedef enum { TRANSPOSE_SYNC, TRANSPOSE_ASYNC } transpose_sync_type;
extern void transpose_in_place_local(transpose_mpi_plan p,
int el_size, TRANSPOSE_EL_TYPE *local_data,
transpose_in_place_which which);
extern TRANSPOSE_EL_TYPE *transpose_allocate_send_buf(transpose_mpi_plan p,
int el_size);
extern void transpose_get_send_block(transpose_mpi_plan p, int step,
int *block_y_start, int *block_ny);
extern void transpose_start_exchange_step(transpose_mpi_plan p,
int el_size,
TRANSPOSE_EL_TYPE *local_data,
TRANSPOSE_EL_TYPE *send_buf,
int step,
transpose_sync_type sync_type);
extern void transpose_finish_exchange_step(transpose_mpi_plan p, int step);
/***********************************************************************/
typedef struct {
fftw_plan p_fft_x; /* plan for first dimension */
fftwnd_plan p_fft; /* plan for subsequent dimensions */
transpose_mpi_plan p_transpose, p_transpose_inv;
fftw_complex *work; /* extra workspace, if needed */
} fftwnd_mpi_plan_data;
typedef fftwnd_mpi_plan_data *fftwnd_mpi_plan;
typedef enum {
FFTW_NORMAL_ORDER,
FFTW_TRANSPOSED_ORDER
} fftwnd_mpi_output_order;
extern fftwnd_mpi_plan fftwnd_mpi_create_plan(MPI_Comm comm,
int rank, const int *n,
fftw_direction dir,
int flags);
extern fftwnd_mpi_plan fftw2d_mpi_create_plan(MPI_Comm comm,
int nx, int ny,
fftw_direction dir, int flags);
extern fftwnd_mpi_plan fftw3d_mpi_create_plan(MPI_Comm comm,
int nx, int ny, int nz,
fftw_direction dir, int flags);
extern void fftwnd_mpi_destroy_plan(fftwnd_mpi_plan p);
extern void fftwnd_mpi_local_sizes(fftwnd_mpi_plan p,
int *local_nx,
int *local_x_start,
int *local_ny_after_transpose,
int *local_y_start_after_transpose,
int *total_local_size);
extern void fftwnd_mpi(fftwnd_mpi_plan p,
int n_fields,
fftw_complex *local_data, fftw_complex *work,
fftwnd_mpi_output_order output_order);
extern void fftw_mpi_die(const char *error_string);
/***********************************************************************/
typedef struct fftw_mpi_twiddle_struct {
int rows, rowstart, cols, n;
fftw_complex *W;
int refcount;
struct fftw_mpi_twiddle_struct *next;
} fftw_mpi_twiddle;
typedef struct fftw_mpi_plan_struct {
int n, m, r, local_m, local_m_start, local_r, local_r_start;
fftw_complex *fft_work;
fftw_mpi_twiddle *tw;
transpose_mpi_plan p_transpose, p_transpose_inv;
fftw_plan pm, pr;
int flags;
fftw_direction dir;
} *fftw_mpi_plan;
/* new flags for the MPI planner: */
#define FFTW_SCRAMBLED_INPUT (8192)
#define FFTW_SCRAMBLED_OUTPUT (16384)
extern void fftw_mpi_local_sizes(fftw_mpi_plan p,
int *local_n,
int *local_start,
int *local_n_after_transform,
int *local_start_after_transform,
int *total_local_size);
extern fftw_mpi_plan fftw_mpi_create_plan(MPI_Comm comm,
int n,
fftw_direction dir, int flags);
extern void fftw_mpi_destroy_plan(fftw_mpi_plan p);
extern void fftw_mpi(fftw_mpi_plan p, int n_fields,
fftw_complex *local_data, fftw_complex *work);
extern void fftw_mpi_print_plan(fftw_mpi_plan p);
/***********************************************************************/
#ifdef __cplusplus
} /* extern "C" */
#endif /* __cplusplus */
#endif /* FFTW_MPI_H */
| {
"alphanum_fraction": 0.6976345561,
"avg_line_length": 31.0319148936,
"ext": "h",
"hexsha": "9a9914978254afce6a374b3d1f4b246d83ef9a95",
"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": "3361d1f18bf529958b78231fdcf139b1c1c1f232",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "albertsgrc/ftdock-opt",
"max_forks_repo_path": "original/lib/fftw-2.1.3/mpi/fftw_mpi.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "3361d1f18bf529958b78231fdcf139b1c1c1f232",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "albertsgrc/ftdock-opt",
"max_issues_repo_path": "original/lib/fftw-2.1.3/mpi/fftw_mpi.h",
"max_line_length": 76,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "3361d1f18bf529958b78231fdcf139b1c1c1f232",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "albertsgrc/ftdock-opt",
"max_stars_repo_path": "original/lib/fftw-2.1.3/mpi/fftw_mpi.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1339,
"size": 5834
} |
#include <gsl/gsl_test.h>
#include <gsl/gsl_ieee_utils.h>
#include <gsl/gsl_math.h>
#include "gsl_cblas.h"
#include "tests.h"
void
test_syrk (void) {
const double flteps = 1e-4, dbleps = 1e-6;
{
int order = 101;
int uplo = 121;
int trans = 111;
int N = 2;
int K = 1;
float alpha = -1.0f;
float beta = 0.1f;
float A[] = { 0.412f, -0.229f };
int lda = 1;
float C[] = { 0.628f, -0.664f, -0.268f, 0.096f };
int ldc = 2;
float C_expected[] = { -0.106944f, 0.027948f, -0.268f, -0.042841f };
cblas_ssyrk(order, uplo, trans, N, K, alpha, A, lda, beta, C, ldc);
{
int i;
for (i = 0; i < 4; i++) {
gsl_test_rel(C[i], C_expected[i], flteps, "ssyrk(case 1566)");
}
};
};
{
int order = 102;
int uplo = 121;
int trans = 111;
int N = 2;
int K = 1;
float alpha = -1.0f;
float beta = 0.1f;
float A[] = { 0.101f, -0.653f };
int lda = 2;
float C[] = { 0.432f, 0.107f, -0.952f, -0.532f };
int ldc = 2;
float C_expected[] = { 0.032999f, 0.107f, -0.029247f, -0.479609f };
cblas_ssyrk(order, uplo, trans, N, K, alpha, A, lda, beta, C, ldc);
{
int i;
for (i = 0; i < 4; i++) {
gsl_test_rel(C[i], C_expected[i], flteps, "ssyrk(case 1567)");
}
};
};
{
int order = 101;
int uplo = 121;
int trans = 112;
int N = 2;
int K = 1;
float alpha = 1.0f;
float beta = 0.1f;
float A[] = { 0.79f, 0.595f };
int lda = 2;
float C[] = { 0.257f, 0.183f, -0.021f, -0.053f };
int ldc = 2;
float C_expected[] = { 0.6498f, 0.48835f, -0.021f, 0.348725f };
cblas_ssyrk(order, uplo, trans, N, K, alpha, A, lda, beta, C, ldc);
{
int i;
for (i = 0; i < 4; i++) {
gsl_test_rel(C[i], C_expected[i], flteps, "ssyrk(case 1568)");
}
};
};
{
int order = 102;
int uplo = 121;
int trans = 112;
int N = 2;
int K = 1;
float alpha = 1.0f;
float beta = 0.1f;
float A[] = { -0.181f, -0.654f };
int lda = 1;
float C[] = { -0.4f, 0.615f, 0.147f, -0.163f };
int ldc = 2;
float C_expected[] = { -0.007239f, 0.615f, 0.133074f, 0.411416f };
cblas_ssyrk(order, uplo, trans, N, K, alpha, A, lda, beta, C, ldc);
{
int i;
for (i = 0; i < 4; i++) {
gsl_test_rel(C[i], C_expected[i], flteps, "ssyrk(case 1569)");
}
};
};
{
int order = 101;
int uplo = 122;
int trans = 111;
int N = 2;
int K = 1;
float alpha = 0.0f;
float beta = -1.0f;
float A[] = { -0.191f, 0.584f };
int lda = 1;
float C[] = { -0.719f, -0.681f, -0.003f, 0.544f };
int ldc = 2;
float C_expected[] = { 0.719f, -0.681f, 0.003f, -0.544f };
cblas_ssyrk(order, uplo, trans, N, K, alpha, A, lda, beta, C, ldc);
{
int i;
for (i = 0; i < 4; i++) {
gsl_test_rel(C[i], C_expected[i], flteps, "ssyrk(case 1570)");
}
};
};
{
int order = 102;
int uplo = 122;
int trans = 111;
int N = 2;
int K = 1;
float alpha = 0.0f;
float beta = -1.0f;
float A[] = { 0.788f, 0.041f };
int lda = 2;
float C[] = { 0.029f, 0.365f, 0.739f, -0.769f };
int ldc = 2;
float C_expected[] = { -0.029f, -0.365f, 0.739f, 0.769f };
cblas_ssyrk(order, uplo, trans, N, K, alpha, A, lda, beta, C, ldc);
{
int i;
for (i = 0; i < 4; i++) {
gsl_test_rel(C[i], C_expected[i], flteps, "ssyrk(case 1571)");
}
};
};
{
int order = 101;
int uplo = 122;
int trans = 112;
int N = 2;
int K = 1;
float alpha = -0.3f;
float beta = -1.0f;
float A[] = { 0.733f, 0.678f };
int lda = 2;
float C[] = { -0.941f, 0.96f, 0.07f, -0.295f };
int ldc = 2;
float C_expected[] = { 0.779813f, 0.96f, -0.219092f, 0.157095f };
cblas_ssyrk(order, uplo, trans, N, K, alpha, A, lda, beta, C, ldc);
{
int i;
for (i = 0; i < 4; i++) {
gsl_test_rel(C[i], C_expected[i], flteps, "ssyrk(case 1572)");
}
};
};
{
int order = 102;
int uplo = 122;
int trans = 112;
int N = 2;
int K = 1;
float alpha = -0.3f;
float beta = -1.0f;
float A[] = { -0.87f, 0.675f };
int lda = 1;
float C[] = { -0.602f, -0.432f, -0.984f, 0.384f };
int ldc = 2;
float C_expected[] = { 0.37493f, 0.608175f, -0.984f, -0.520687f };
cblas_ssyrk(order, uplo, trans, N, K, alpha, A, lda, beta, C, ldc);
{
int i;
for (i = 0; i < 4; i++) {
gsl_test_rel(C[i], C_expected[i], flteps, "ssyrk(case 1573)");
}
};
};
{
int order = 101;
int uplo = 121;
int trans = 111;
int N = 2;
int K = 1;
double alpha = 0.1;
double beta = -0.3;
double A[] = { 0.169, -0.875 };
int lda = 1;
double C[] = { 0.159, 0.277, 0.865, 0.346 };
int ldc = 2;
double C_expected[] = { -0.0448439, -0.0978875, 0.865, -0.0272375 };
cblas_dsyrk(order, uplo, trans, N, K, alpha, A, lda, beta, C, ldc);
{
int i;
for (i = 0; i < 4; i++) {
gsl_test_rel(C[i], C_expected[i], dbleps, "dsyrk(case 1574)");
}
};
};
{
int order = 102;
int uplo = 121;
int trans = 111;
int N = 2;
int K = 1;
double alpha = 0.1;
double beta = -0.3;
double A[] = { 0.536, -0.725 };
int lda = 2;
double C[] = { 0.154, -0.445, -0.841, -0.91 };
int ldc = 2;
double C_expected[] = { -0.0174704, -0.445, 0.21344, 0.3255625 };
cblas_dsyrk(order, uplo, trans, N, K, alpha, A, lda, beta, C, ldc);
{
int i;
for (i = 0; i < 4; i++) {
gsl_test_rel(C[i], C_expected[i], dbleps, "dsyrk(case 1575)");
}
};
};
{
int order = 101;
int uplo = 121;
int trans = 112;
int N = 2;
int K = 1;
double alpha = 0;
double beta = -1;
double A[] = { -0.07, 0.8 };
int lda = 2;
double C[] = { 0.823, -0.88, -0.136, 0.793 };
int ldc = 2;
double C_expected[] = { -0.823, 0.88, -0.136, -0.793 };
cblas_dsyrk(order, uplo, trans, N, K, alpha, A, lda, beta, C, ldc);
{
int i;
for (i = 0; i < 4; i++) {
gsl_test_rel(C[i], C_expected[i], dbleps, "dsyrk(case 1576)");
}
};
};
{
int order = 102;
int uplo = 121;
int trans = 112;
int N = 2;
int K = 1;
double alpha = 0;
double beta = -1;
double A[] = { -0.058, 0.649 };
int lda = 1;
double C[] = { -0.187, 0.294, -0.004, -0.933 };
int ldc = 2;
double C_expected[] = { 0.187, 0.294, 0.004, 0.933 };
cblas_dsyrk(order, uplo, trans, N, K, alpha, A, lda, beta, C, ldc);
{
int i;
for (i = 0; i < 4; i++) {
gsl_test_rel(C[i], C_expected[i], dbleps, "dsyrk(case 1577)");
}
};
};
{
int order = 101;
int uplo = 122;
int trans = 111;
int N = 2;
int K = 1;
double alpha = 1;
double beta = -1;
double A[] = { 0.263, -0.289 };
int lda = 1;
double C[] = { 0.554, -0.679, 0.993, 0.758 };
int ldc = 2;
double C_expected[] = { -0.484831, -0.679, -1.069007, -0.674479 };
cblas_dsyrk(order, uplo, trans, N, K, alpha, A, lda, beta, C, ldc);
{
int i;
for (i = 0; i < 4; i++) {
gsl_test_rel(C[i], C_expected[i], dbleps, "dsyrk(case 1578)");
}
};
};
{
int order = 102;
int uplo = 122;
int trans = 111;
int N = 2;
int K = 1;
double alpha = 1;
double beta = -1;
double A[] = { -0.265, -0.837 };
int lda = 2;
double C[] = { -0.994, 0.967, -0.34, -0.069 };
int ldc = 2;
double C_expected[] = { 1.064225, -0.745195, -0.34, 0.769569 };
cblas_dsyrk(order, uplo, trans, N, K, alpha, A, lda, beta, C, ldc);
{
int i;
for (i = 0; i < 4; i++) {
gsl_test_rel(C[i], C_expected[i], dbleps, "dsyrk(case 1579)");
}
};
};
{
int order = 101;
int uplo = 122;
int trans = 112;
int N = 2;
int K = 1;
double alpha = -0.3;
double beta = 1;
double A[] = { -0.464, 0.394 };
int lda = 2;
double C[] = { -0.45, -0.447, 0.649, 0.055 };
int ldc = 2;
double C_expected[] = { -0.5145888, -0.447, 0.7038448, 0.0084292 };
cblas_dsyrk(order, uplo, trans, N, K, alpha, A, lda, beta, C, ldc);
{
int i;
for (i = 0; i < 4; i++) {
gsl_test_rel(C[i], C_expected[i], dbleps, "dsyrk(case 1580)");
}
};
};
{
int order = 102;
int uplo = 122;
int trans = 112;
int N = 2;
int K = 1;
double alpha = -0.3;
double beta = 1;
double A[] = { 0.815, 0.168 };
int lda = 1;
double C[] = { 0.817, -0.957, -0.395, -0.382 };
int ldc = 2;
double C_expected[] = { 0.6177325, -0.998076, -0.395, -0.3904672 };
cblas_dsyrk(order, uplo, trans, N, K, alpha, A, lda, beta, C, ldc);
{
int i;
for (i = 0; i < 4; i++) {
gsl_test_rel(C[i], C_expected[i], dbleps, "dsyrk(case 1581)");
}
};
};
{
int order = 101;
int uplo = 121;
int trans = 111;
int N = 2;
int K = 1;
float alpha[2] = {0.0f, 0.0f};
float beta[2] = {-0.3f, 0.1f};
float A[] = { 0.447f, -0.507f, -0.425f, 0.701f };
int lda = 1;
float C[] = { 0.16f, -0.245f, 0.922f, -0.437f, 0.24f, 0.008f, -0.095f, 0.749f };
int ldc = 2;
float C_expected[] = { -0.0235f, 0.0895f, -0.2329f, 0.2233f, 0.24f, 0.008f, -0.0464f, -0.2342f };
cblas_csyrk(order, uplo, trans, N, K, alpha, A, lda, beta, C, ldc);
{
int i;
for (i = 0; i < 4; i++) {
gsl_test_rel(C[2*i], C_expected[2*i], flteps, "csyrk(case 1582) real");
gsl_test_rel(C[2*i+1], C_expected[2*i+1], flteps, "csyrk(case 1582) imag");
};
};
};
{
int order = 102;
int uplo = 121;
int trans = 111;
int N = 2;
int K = 1;
float alpha[2] = {0.0f, 0.0f};
float beta[2] = {-0.3f, 0.1f};
float A[] = { -0.421f, -0.435f, -0.914f, -0.493f };
int lda = 2;
float C[] = { -0.761f, -0.38f, 0.043f, -0.999f, 0.779f, 0.238f, 0.082f, 0.394f };
int ldc = 2;
float C_expected[] = { 0.2663f, 0.0379f, 0.043f, -0.999f, -0.2575f, 0.0065f, -0.064f, -0.11f };
cblas_csyrk(order, uplo, trans, N, K, alpha, A, lda, beta, C, ldc);
{
int i;
for (i = 0; i < 4; i++) {
gsl_test_rel(C[2*i], C_expected[2*i], flteps, "csyrk(case 1583) real");
gsl_test_rel(C[2*i+1], C_expected[2*i+1], flteps, "csyrk(case 1583) imag");
};
};
};
{
int order = 101;
int uplo = 121;
int trans = 112;
int N = 2;
int K = 1;
float alpha[2] = {-1.0f, 0.0f};
float beta[2] = {-0.3f, 0.1f};
float A[] = { 0.827f, -0.896f, 0.417f, 0.865f };
int lda = 2;
float C[] = { -0.349f, -0.31f, 0.972f, 0.794f, -0.906f, -0.595f, -0.089f, -0.333f };
int ldc = 2;
float C_expected[] = { 0.254587f, 1.54008f, -1.4909f, -0.482723f, -0.906f, -0.595f, 0.634336f, -0.63041f };
cblas_csyrk(order, uplo, trans, N, K, alpha, A, lda, beta, C, ldc);
{
int i;
for (i = 0; i < 4; i++) {
gsl_test_rel(C[2*i], C_expected[2*i], flteps, "csyrk(case 1584) real");
gsl_test_rel(C[2*i+1], C_expected[2*i+1], flteps, "csyrk(case 1584) imag");
};
};
};
{
int order = 102;
int uplo = 121;
int trans = 112;
int N = 2;
int K = 1;
float alpha[2] = {-1.0f, 0.0f};
float beta[2] = {-0.3f, 0.1f};
float A[] = { 0.607f, 0.747f, -0.889f, 0.333f };
int lda = 1;
float C[] = { 0.244f, 0.564f, 0.009f, 0.578f, -0.827f, 0.558f, -0.337f, 0.731f };
int ldc = 2;
float C_expected[] = { 0.05996f, -1.05166f, 0.009f, 0.578f, 0.980674f, 0.211852f, -0.651432f, 0.339074f };
cblas_csyrk(order, uplo, trans, N, K, alpha, A, lda, beta, C, ldc);
{
int i;
for (i = 0; i < 4; i++) {
gsl_test_rel(C[2*i], C_expected[2*i], flteps, "csyrk(case 1585) real");
gsl_test_rel(C[2*i+1], C_expected[2*i+1], flteps, "csyrk(case 1585) imag");
};
};
};
{
int order = 101;
int uplo = 121;
int trans = 113;
int N = 2;
int K = 1;
float alpha[2] = {1.0f, 0.0f};
float beta[2] = {0.0f, 1.0f};
float A[] = { 0.784f, -0.281f, -0.88f, 0.479f };
int lda = 2;
float C[] = { 0.491f, 0.531f, 0.805f, -0.097f, 0.728f, 0.674f, -0.705f, -0.754f };
int ldc = 2;
float C_expected[] = { 0.004695f, 0.050392f, -0.458321f, 1.42782f, 0.728f, 0.674f, 1.29896f, -1.54804f };
cblas_csyrk(order, uplo, trans, N, K, alpha, A, lda, beta, C, ldc);
{
int i;
for (i = 0; i < 4; i++) {
gsl_test_rel(C[2*i], C_expected[2*i], flteps, "csyrk(case 1586) real");
gsl_test_rel(C[2*i+1], C_expected[2*i+1], flteps, "csyrk(case 1586) imag");
};
};
};
{
int order = 102;
int uplo = 121;
int trans = 113;
int N = 2;
int K = 1;
float alpha[2] = {1.0f, 0.0f};
float beta[2] = {0.0f, 1.0f};
float A[] = { 0.272f, -0.146f, 0.155f, 0.038f };
int lda = 1;
float C[] = { 0.533f, -0.41f, -0.904f, 0.301f, -0.836f, 0.57f, -0.374f, -0.293f };
int ldc = 2;
float C_expected[] = { 0.462668f, 0.453576f, -0.904f, 0.301f, -0.522292f, -0.848294f, 0.315581f, -0.36222f };
cblas_csyrk(order, uplo, trans, N, K, alpha, A, lda, beta, C, ldc);
{
int i;
for (i = 0; i < 4; i++) {
gsl_test_rel(C[2*i], C_expected[2*i], flteps, "csyrk(case 1587) real");
gsl_test_rel(C[2*i+1], C_expected[2*i+1], flteps, "csyrk(case 1587) imag");
};
};
};
{
int order = 101;
int uplo = 122;
int trans = 111;
int N = 2;
int K = 1;
float alpha[2] = {0.0f, 1.0f};
float beta[2] = {-1.0f, 0.0f};
float A[] = { -0.055f, -0.127f, -0.896f, -0.625f };
int lda = 1;
float C[] = { -0.619f, 0.511f, -0.877f, 0.557f, -0.801f, -0.437f, -0.922f, 0.332f };
int ldc = 2;
float C_expected[] = { 0.60503f, -0.524104f, -0.877f, 0.557f, 0.652833f, 0.406905f, -0.198f, 0.080191f };
cblas_csyrk(order, uplo, trans, N, K, alpha, A, lda, beta, C, ldc);
{
int i;
for (i = 0; i < 4; i++) {
gsl_test_rel(C[2*i], C_expected[2*i], flteps, "csyrk(case 1588) real");
gsl_test_rel(C[2*i+1], C_expected[2*i+1], flteps, "csyrk(case 1588) imag");
};
};
};
{
int order = 102;
int uplo = 122;
int trans = 111;
int N = 2;
int K = 1;
float alpha[2] = {0.0f, 1.0f};
float beta[2] = {-1.0f, 0.0f};
float A[] = { -0.528f, 0.759f, -0.079f, 0.952f };
int lda = 2;
float C[] = { 0.775f, 0.855f, 0.786f, 0.525f, 0.85f, 0.044f, 0.658f, 0.947f };
int ldc = 2;
float C_expected[] = { 0.026504f, -1.1523f, -0.223383f, -1.20586f, 0.85f, 0.044f, -0.507584f, -1.84706f };
cblas_csyrk(order, uplo, trans, N, K, alpha, A, lda, beta, C, ldc);
{
int i;
for (i = 0; i < 4; i++) {
gsl_test_rel(C[2*i], C_expected[2*i], flteps, "csyrk(case 1589) real");
gsl_test_rel(C[2*i+1], C_expected[2*i+1], flteps, "csyrk(case 1589) imag");
};
};
};
{
int order = 101;
int uplo = 122;
int trans = 112;
int N = 2;
int K = 1;
float alpha[2] = {1.0f, 0.0f};
float beta[2] = {1.0f, 0.0f};
float A[] = { -0.049f, -0.687f, -0.434f, 0.294f };
int lda = 2;
float C[] = { 0.937f, -0.113f, 0.796f, 0.293f, 0.876f, -0.199f, -0.757f, -0.103f };
int ldc = 2;
float C_expected[] = { 0.467432f, -0.045674f, 0.796f, 0.293f, 1.09924f, 0.084752f, -0.65508f, -0.358192f };
cblas_csyrk(order, uplo, trans, N, K, alpha, A, lda, beta, C, ldc);
{
int i;
for (i = 0; i < 4; i++) {
gsl_test_rel(C[2*i], C_expected[2*i], flteps, "csyrk(case 1590) real");
gsl_test_rel(C[2*i+1], C_expected[2*i+1], flteps, "csyrk(case 1590) imag");
};
};
};
{
int order = 102;
int uplo = 122;
int trans = 112;
int N = 2;
int K = 1;
float alpha[2] = {1.0f, 0.0f};
float beta[2] = {1.0f, 0.0f};
float A[] = { 0.359f, -0.364f, 0.926f, -0.69f };
int lda = 1;
float C[] = { 0.306f, 0.249f, 0.28f, 0.229f, 0.866f, 0.092f, 0.886f, -0.283f };
int ldc = 2;
float C_expected[] = { 0.302385f, -0.012352f, 0.361274f, -0.355774f, 0.866f, 0.092f, 1.26738f, -1.56088f };
cblas_csyrk(order, uplo, trans, N, K, alpha, A, lda, beta, C, ldc);
{
int i;
for (i = 0; i < 4; i++) {
gsl_test_rel(C[2*i], C_expected[2*i], flteps, "csyrk(case 1591) real");
gsl_test_rel(C[2*i+1], C_expected[2*i+1], flteps, "csyrk(case 1591) imag");
};
};
};
{
int order = 101;
int uplo = 122;
int trans = 113;
int N = 2;
int K = 1;
float alpha[2] = {-0.3f, 0.1f};
float beta[2] = {0.0f, 0.0f};
float A[] = { 0.607f, 0.555f, -0.85f, 0.831f };
int lda = 2;
float C[] = { 0.069f, 0.368f, 0.551f, -0.912f, -0.243f, -0.063f, -0.924f, 0.192f };
int ldc = 2;
float C_expected[] = { -0.0855042f, -0.196089f, 0.551f, -0.912f, 0.28988f, -0.107516f, 0.131688f, 0.427004f };
cblas_csyrk(order, uplo, trans, N, K, alpha, A, lda, beta, C, ldc);
{
int i;
for (i = 0; i < 4; i++) {
gsl_test_rel(C[2*i], C_expected[2*i], flteps, "csyrk(case 1592) real");
gsl_test_rel(C[2*i+1], C_expected[2*i+1], flteps, "csyrk(case 1592) imag");
};
};
};
{
int order = 102;
int uplo = 122;
int trans = 113;
int N = 2;
int K = 1;
float alpha[2] = {-0.3f, 0.1f};
float beta[2] = {0.0f, 0.0f};
float A[] = { 0.427f, 0.86f, -0.136f, 0.002f };
int lda = 1;
float C[] = { 0.398f, -0.47f, 0.011f, -0.547f, -0.106f, 0.016f, 0.681f, 0.246f };
int ldc = 2;
float C_expected[] = { 0.0937373f, -0.276059f, 0.0295482f, 0.0288526f, -0.106f, 0.016f, -0.0054932f, 0.0020124f };
cblas_csyrk(order, uplo, trans, N, K, alpha, A, lda, beta, C, ldc);
{
int i;
for (i = 0; i < 4; i++) {
gsl_test_rel(C[2*i], C_expected[2*i], flteps, "csyrk(case 1593) real");
gsl_test_rel(C[2*i+1], C_expected[2*i+1], flteps, "csyrk(case 1593) imag");
};
};
};
{
int order = 101;
int uplo = 121;
int trans = 111;
int N = 2;
int K = 1;
double alpha[2] = {-0.3, 0.1};
double beta[2] = {1, 0};
double A[] = { 0.718, 0.023, 0.355, -0.492 };
int lda = 1;
double C[] = { -0.637, -0.727, -0.475, -0.776, 0.802, -0.55, -0.837, 0.222 };
int ldc = 2;
double C_expected[] = { -0.7948013, -0.6854089, -0.5203527, -0.6458521, 0.802, -0.55, -0.7672563, 0.3151921 };
cblas_zsyrk(order, uplo, trans, N, K, alpha, A, lda, beta, C, ldc);
{
int i;
for (i = 0; i < 4; i++) {
gsl_test_rel(C[2*i], C_expected[2*i], dbleps, "zsyrk(case 1594) real");
gsl_test_rel(C[2*i+1], C_expected[2*i+1], dbleps, "zsyrk(case 1594) imag");
};
};
};
{
int order = 102;
int uplo = 121;
int trans = 111;
int N = 2;
int K = 1;
double alpha[2] = {-0.3, 0.1};
double beta[2] = {1, 0};
double A[] = { 0.209, 0.139, -0.202, -0.223 };
int lda = 2;
double C[] = { -0.695, 0.524, 0.212, -0.88, -0.752, 0.291, 0.684, -0.124 };
int ldc = 2;
double C_expected[] = { -0.7081182, 0.5090054, 0.212, -0.88, -0.7411652, 0.3122834, 0.6776683, -0.1519201 };
cblas_zsyrk(order, uplo, trans, N, K, alpha, A, lda, beta, C, ldc);
{
int i;
for (i = 0; i < 4; i++) {
gsl_test_rel(C[2*i], C_expected[2*i], dbleps, "zsyrk(case 1595) real");
gsl_test_rel(C[2*i+1], C_expected[2*i+1], dbleps, "zsyrk(case 1595) imag");
};
};
};
{
int order = 101;
int uplo = 121;
int trans = 112;
int N = 2;
int K = 1;
double alpha[2] = {-0.3, 0.1};
double beta[2] = {1, 0};
double A[] = { -0.365, -0.624, 0.632, 0.348 };
int lda = 2;
double C[] = { 0.877, 0.927, -0.377, 0.967, 0.008, 0.292, -0.779, 0.794 };
int ldc = 2;
double C_expected[] = { 0.9082933, 0.7647289, -0.3208028, 1.1220636, 0.008, 0.292, -0.9064832, 0.6898704 };
cblas_zsyrk(order, uplo, trans, N, K, alpha, A, lda, beta, C, ldc);
{
int i;
for (i = 0; i < 4; i++) {
gsl_test_rel(C[2*i], C_expected[2*i], dbleps, "zsyrk(case 1596) real");
gsl_test_rel(C[2*i+1], C_expected[2*i+1], dbleps, "zsyrk(case 1596) imag");
};
};
};
{
int order = 102;
int uplo = 121;
int trans = 112;
int N = 2;
int K = 1;
double alpha[2] = {-0.3, 0.1};
double beta[2] = {1, 0};
double A[] = { -0.067, -0.586, 0.208, 0.331 };
int lda = 1;
double C[] = { 0.584, -0.454, 0.93, 0.782, 0.489, -0.278, 0.081, -0.919 };
int ldc = 2;
double C_expected[] = { 0.6778197, -0.5114479, 0.93, 0.782, 0.4493975, -0.2167775, 0.0871195, -0.9669385 };
cblas_zsyrk(order, uplo, trans, N, K, alpha, A, lda, beta, C, ldc);
{
int i;
for (i = 0; i < 4; i++) {
gsl_test_rel(C[2*i], C_expected[2*i], dbleps, "zsyrk(case 1597) real");
gsl_test_rel(C[2*i+1], C_expected[2*i+1], dbleps, "zsyrk(case 1597) imag");
};
};
};
{
int order = 101;
int uplo = 121;
int trans = 113;
int N = 2;
int K = 1;
double alpha[2] = {0, 0.1};
double beta[2] = {0, 0.1};
double A[] = { -0.617, 0.179, -0.626, 0.334 };
int lda = 2;
double C[] = { 0.346, -0.903, 0.022, -0.839, -0.715, 0.049, -0.338, 0.149 };
int ldc = 2;
double C_expected[] = { 0.1123886, 0.0694648, 0.1157132, 0.0348456, -0.715, 0.049, 0.0269168, -0.005768 };
cblas_zsyrk(order, uplo, trans, N, K, alpha, A, lda, beta, C, ldc);
{
int i;
for (i = 0; i < 4; i++) {
gsl_test_rel(C[2*i], C_expected[2*i], dbleps, "zsyrk(case 1598) real");
gsl_test_rel(C[2*i+1], C_expected[2*i+1], dbleps, "zsyrk(case 1598) imag");
};
};
};
{
int order = 102;
int uplo = 121;
int trans = 113;
int N = 2;
int K = 1;
double alpha[2] = {0, 0.1};
double beta[2] = {0, 0.1};
double A[] = { -0.356, -0.308, 0.493, -0.351 };
int lda = 1;
double C[] = { -0.898, -0.905, 0.002, -0.219, 0.881, 0.879, 0.275, -0.351 };
int ldc = 2;
double C_expected[] = { 0.0685704, -0.0866128, 0.002, -0.219, -0.0852112, 0.0597384, 0.0697086, 0.0394848 };
cblas_zsyrk(order, uplo, trans, N, K, alpha, A, lda, beta, C, ldc);
{
int i;
for (i = 0; i < 4; i++) {
gsl_test_rel(C[2*i], C_expected[2*i], dbleps, "zsyrk(case 1599) real");
gsl_test_rel(C[2*i+1], C_expected[2*i+1], dbleps, "zsyrk(case 1599) imag");
};
};
};
{
int order = 101;
int uplo = 122;
int trans = 111;
int N = 2;
int K = 1;
double alpha[2] = {0, 0.1};
double beta[2] = {1, 0};
double A[] = { -0.103, -0.951, -0.601, -0.041 };
int lda = 1;
double C[] = { -0.918, -0.018, 0.991, -0.789, -0.698, -0.067, 0.956, -0.599 };
int ldc = 2;
double C_expected[] = { -0.9375906, -0.1073792, 0.991, -0.789, -0.7555774, -0.0647088, 0.9510718, -0.563048 };
cblas_zsyrk(order, uplo, trans, N, K, alpha, A, lda, beta, C, ldc);
{
int i;
for (i = 0; i < 4; i++) {
gsl_test_rel(C[2*i], C_expected[2*i], dbleps, "zsyrk(case 1600) real");
gsl_test_rel(C[2*i+1], C_expected[2*i+1], dbleps, "zsyrk(case 1600) imag");
};
};
};
{
int order = 102;
int uplo = 122;
int trans = 111;
int N = 2;
int K = 1;
double alpha[2] = {0, 0.1};
double beta[2] = {1, 0};
double A[] = { -0.237, 0.925, -0.904, -0.091 };
int lda = 2;
double C[] = { -0.572, 0.915, 0.398, 0.222, 0.016, 0.288, -0.078, -0.507 };
int ldc = 2;
double C_expected[] = { -0.528155, 0.8350544, 0.4794633, 0.2518423, 0.016, 0.288, -0.0944528, -0.4261065 };
cblas_zsyrk(order, uplo, trans, N, K, alpha, A, lda, beta, C, ldc);
{
int i;
for (i = 0; i < 4; i++) {
gsl_test_rel(C[2*i], C_expected[2*i], dbleps, "zsyrk(case 1601) real");
gsl_test_rel(C[2*i+1], C_expected[2*i+1], dbleps, "zsyrk(case 1601) imag");
};
};
};
{
int order = 101;
int uplo = 122;
int trans = 112;
int N = 2;
int K = 1;
double alpha[2] = {-0.3, 0.1};
double beta[2] = {0, 0};
double A[] = { 0.963, -0.23, -0.435, 0.289 };
int lda = 2;
double C[] = { 0.282, -0.272, -0.516, -0.594, -0.001, 0.155, -0.39, -0.354 };
int ldc = 2;
double C_expected[] = { -0.2180427, 0.2203409, -0.516, -0.594, 0.0678948, -0.1487506, -0.0065682, 0.0859994 };
cblas_zsyrk(order, uplo, trans, N, K, alpha, A, lda, beta, C, ldc);
{
int i;
for (i = 0; i < 4; i++) {
gsl_test_rel(C[2*i], C_expected[2*i], dbleps, "zsyrk(case 1602) real");
gsl_test_rel(C[2*i+1], C_expected[2*i+1], dbleps, "zsyrk(case 1602) imag");
};
};
};
{
int order = 102;
int uplo = 122;
int trans = 112;
int N = 2;
int K = 1;
double alpha[2] = {-0.3, 0.1};
double beta[2] = {0, 0};
double A[] = { 0.674, 0.1, -0.098, 0.552 };
int lda = 1;
double C[] = { 0.089, -0.523, -0.551, 0.618, 0.67, 0.247, 0.975, -0.714 };
int ldc = 2;
double C_expected[] = { -0.1467628, 0.0039876, 0.0001508, -0.1207996, 0.67, 0.247, 0.0993492, 0.0029476 };
cblas_zsyrk(order, uplo, trans, N, K, alpha, A, lda, beta, C, ldc);
{
int i;
for (i = 0; i < 4; i++) {
gsl_test_rel(C[2*i], C_expected[2*i], dbleps, "zsyrk(case 1603) real");
gsl_test_rel(C[2*i+1], C_expected[2*i+1], dbleps, "zsyrk(case 1603) imag");
};
};
};
{
int order = 101;
int uplo = 122;
int trans = 113;
int N = 2;
int K = 1;
double alpha[2] = {0, 1};
double beta[2] = {1, 0};
double A[] = { 0.033, -0.864, 0.168, 0.524 };
int lda = 2;
double C[] = { 0.788, 0.016, -0.436, 0.749, -0.89, -0.87, 0.421, -0.203 };
int ldc = 2;
double C_expected[] = { 0.845024, -0.729407, -0.436, 0.749, -0.76214, -0.41172, 0.244936, -0.449352 };
cblas_zsyrk(order, uplo, trans, N, K, alpha, A, lda, beta, C, ldc);
{
int i;
for (i = 0; i < 4; i++) {
gsl_test_rel(C[2*i], C_expected[2*i], dbleps, "zsyrk(case 1604) real");
gsl_test_rel(C[2*i+1], C_expected[2*i+1], dbleps, "zsyrk(case 1604) imag");
};
};
};
{
int order = 102;
int uplo = 122;
int trans = 113;
int N = 2;
int K = 1;
double alpha[2] = {0, 1};
double beta[2] = {1, 0};
double A[] = { 0.957, -0.079, 0.935, 0.232 };
int lda = 1;
double C[] = { -0.744, -0.061, 0.195, -0.574, 0.551, 0.478, -0.337, 0.1 };
int ldc = 2;
double C_expected[] = { -0.592794, 0.848608, 0.046841, 0.339123, 0.551, 0.478, -0.77084, 0.920401 };
cblas_zsyrk(order, uplo, trans, N, K, alpha, A, lda, beta, C, ldc);
{
int i;
for (i = 0; i < 4; i++) {
gsl_test_rel(C[2*i], C_expected[2*i], dbleps, "zsyrk(case 1605) real");
gsl_test_rel(C[2*i+1], C_expected[2*i+1], dbleps, "zsyrk(case 1605) imag");
};
};
};
}
| {
"alphanum_fraction": 0.511018078,
"avg_line_length": 27.4843096234,
"ext": "c",
"hexsha": "5f4b5fd2b3233a45444120725acb8d84c77cc55b",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2015-10-02T01:32:59.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-10-02T01:32:59.000Z",
"max_forks_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "ICML14MoMCompare/spectral-learn",
"max_forks_repo_path": "code/em/treba/gsl-1.0/cblas/test_syrk.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "ICML14MoMCompare/spectral-learn",
"max_issues_repo_path": "code/em/treba/gsl-1.0/cblas/test_syrk.c",
"max_line_length": 117,
"max_stars_count": 14,
"max_stars_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "ICML14MoMCompare/spectral-learn",
"max_stars_repo_path": "code/em/treba/gsl-1.0/cblas/test_syrk.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": 11985,
"size": 26275
} |
/***
* Copyright 2019 The Katla Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef KATLA_SOCKET_H
#define KATLA_SOCKET_H
#include "posix-errors.h"
#include "katla/core/error.h"
#include "katla/core/core.h"
#include <gsl/span>
#include <net/ethernet.h>
#include <memory>
#include <optional>
#include <system_error>
#include <chrono>
#include <string>
namespace outcome = OUTCOME_V2_NAMESPACE;
namespace katla {
class PosixSocket {
public:
enum class ProtocolDomain { Unix, IPv4, IPv6, Packet, Can, Bluetooth, VSock};
enum class Type { Stream, Datagram, SequencedPacket, Raw};
enum class FrameType : uint16_t { All = ETH_P_ALL, EtherCat = 0x88a4 };
struct SocketOptions {
ProtocolDomain domain {ProtocolDomain::IPv4};
Type type {Type::Stream};
FrameType frameType {FrameType::All};
bool nonBlocking {false};
bool reuseAddress {false};
};
static constexpr SocketOptions IPv4SocketOptions {ProtocolDomain::IPv4, Type::Stream, FrameType::All, false, false};
struct WaitResult {
bool dataToRead {0};
bool urgentDataToRead {0};
bool writingWillNotBlock {0};
bool readHangup {0};
bool writeHangup {0};
bool error {0};
bool invalid {0};
bool wakeup {0};
};
PosixSocket();
PosixSocket(ProtocolDomain protocolDomain, Type type, FrameType frameType, bool nonBlocking);
PosixSocket(const PosixSocket&) = delete;
~PosixSocket();
static outcome::result<std::array<std::shared_ptr<PosixSocket>, 2>, Error> createUnnamedPair(ProtocolDomain protocolDomain, Type type, FrameType frameType, bool nonBlocking);
outcome::result<void, Error> bind(std::string url);
outcome::result<void, Error> bindIPv4(std::string ip, int port, SocketOptions options = IPv4SocketOptions);
outcome::result<void, Error> listen();
outcome::result<std::unique_ptr<PosixSocket>, Error> accept();
std::optional<Error> error();
outcome::result<void, Error> connect(std::string url, SocketOptions options);
outcome::result<void, Error> connectIPv4(std::string ip, int port, SocketOptions options = IPv4SocketOptions);
// TODO add wakeup to interrupt wait -> multithreading??
outcome::result<WaitResult, Error> poll(std::chrono::milliseconds timeout, bool writePending = false);
outcome::result<ssize_t, Error> read(const gsl::span<std::byte>& buffer);
outcome::result<ssize_t, Error> write(const gsl::span<std::byte>& buffer);
outcome::result<ssize_t, Error> receiveFrom(const gsl::span<std::byte>& buffer);
outcome::result<ssize_t, Error> sendTo(std::string url, const gsl::span<std::byte>& buffer);
outcome::result<void, Error> wakeup();
outcome::result<void, Error> close();
private:
outcome::result<void, Error> create();
PosixSocket & operator=(const PosixSocket&) = delete;
PosixSocket(ProtocolDomain protocolDomain, Type type, FrameType frameType, bool nonBlocking, int fd, int wakeupFd);
static int mapProtocolDomain (ProtocolDomain protocolDomain);
static int mapType (Type type);
int _fd {-1};
int _wakeupFd {-1};
ProtocolDomain _protocolDomain {ProtocolDomain::IPv4};
Type _type {Type::Stream};
FrameType _frameType {FrameType::All};
std::string _url;
bool _nonBlocking {false};
};
}
#endif // KATLA_SOCKET_H
| {
"alphanum_fraction": 0.7029728344,
"avg_line_length": 32.2479338843,
"ext": "h",
"hexsha": "3f37b631039ca9b1ec10068cc0e157a03a7797d2",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2020-08-26T13:32:36.000Z",
"max_forks_repo_forks_event_min_datetime": "2020-08-26T13:32:36.000Z",
"max_forks_repo_head_hexsha": "aaaeb8baf041bba7259275beefc71c8452a16223",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "plok/katla",
"max_forks_repo_path": "core/posix-socket.h",
"max_issues_count": 3,
"max_issues_repo_head_hexsha": "aaaeb8baf041bba7259275beefc71c8452a16223",
"max_issues_repo_issues_event_max_datetime": "2021-11-16T14:21:56.000Z",
"max_issues_repo_issues_event_min_datetime": "2021-03-25T14:33:22.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "plok/katla",
"max_issues_repo_path": "core/posix-socket.h",
"max_line_length": 178,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "aaaeb8baf041bba7259275beefc71c8452a16223",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "plok/katla",
"max_stars_repo_path": "core/posix-socket.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 951,
"size": 3902
} |
/* histogram/add.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 <gsl/gsl_errno.h>
#include <gsl/gsl_histogram.h>
#include "find.c"
int
gsl_histogram_increment (gsl_histogram * h, double x)
{
int status = gsl_histogram_accumulate (h, x, 1.0);
return status;
}
int
gsl_histogram_accumulate (gsl_histogram * h, double x, double weight)
{
const size_t n = h->n;
size_t index = 0;
int status = find (h->n, h->range, x, &index);
if (status)
{
return GSL_EDOM;
}
if (index >= n)
{
GSL_ERROR ("index lies outside valid range of 0 .. n - 1",
GSL_ESANITY);
}
h->bin[index] += weight;
return GSL_SUCCESS;
}
| {
"alphanum_fraction": 0.6850828729,
"avg_line_length": 25.8571428571,
"ext": "c",
"hexsha": "634c7186af1c754bb583e48469d75493b98541ea",
"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/histogram/add.c",
"max_issues_count": 6,
"max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e",
"max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z",
"max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "Brian-ning/HMNE",
"max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/histogram/add.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/histogram/add.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": 397,
"size": 1448
} |
/*********************************************************************
* Program: psimci.c
* Author: Mauricio Caceres Bravo <caceres@nber.org>
* Created: Sun Feb 12 19:28:43 EST 2017
* Updated: Tue May 30 18:11:50 EDT 2017
* Purpose: Stata plugin to simulate a CI under H0: b = 0 for a
* treatment effect given a regression specification.
* Note: See stata.com/plugins for more on Stata plugins
*********************************************************************/
/**
* @file psimci.c
* @author Mauricio Caceres bravo
* @date 30 May 2017
* @brief Stata plugin to simulate a CI for a placebo treatment.
*
* See the documentation for simci.ado (e.g. help simci from Stata)
*
* @see http://www.stata.com/plugins
*/
#include <math.h>
#include <omp.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <gsl/gsl_blas.h>
#include <gsl/gsl_linalg.h>
#include <gsl/gsl_matrix_double.h>
#include <gsl/gsl_permutation.h>
#include <gsl/gsl_randist.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_sort_vector.h>
#include "psimci.h"
#include "stplugin.h"
#include "stutils.c"
/**
* @brief Main function call will execute as Stata plugin
*
* The function takes the first variable in @argc as the dependent
* variable and the next k - 1 variables are covariates. @argc contains
* the comma options passed by Stata. Currently just the proportion
* randomzed and the number of simulations to run. See documentation for
* simci.ado or sim_ci below for moew.
*
* @param argc List of variables to use
* @param argv Comma options from Stata
* @return Modified variables in Stata
* @see Documentation for simci.ado
* @warning This is meant to be run from simci.ado and not by itself
*/
STDLL stata_call(int argc, char *argv[])
{
// Simple call to see if the plugin loaded
char buffer[16]; strcpy (buffer, argv[0]);
if ( strcmp(buffer, "check") == 0 ) return (0);
// Initialize the variables to use
ST_int i, j ;
ST_double z ;
ST_retcode rc ;
// Get P and number of reps. Note the 0-based indexing! So the
// functiona ssumes P and reps were the 1st and 3nd argument.
double P = strtod (argv[0], NULL);
int reps = strtod (argv[1], NULL);
const size_t n = SF_in2();
const int k = SF_nvars();
// If too few variables (at least 2 for regressio), exit
if (k < 2) {
return (102) ;
}
// Initialize GSL elements where to store data
gsl_matrix *X = gsl_matrix_alloc (n, k + 1);
gsl_vector *y = gsl_vector_alloc (n);
// Not sure if there is another way to read data vs the double loop.
// Note: Careful with the 0-based indexing!
for (i = SF_in1(); i <= SF_in2(); i++) {
if (SF_ifobs(i)) {
// Variables 2 through k are covariates
for (j = 2; j <= k; j++) {
// Note we leave the first column empty
if ( (rc = SF_vdata(j, i, &z)) ) return(rc);
gsl_matrix_set (X, i - 1, j - 1, z);
}
// Note we add the constant
gsl_matrix_set (X, i - 1, k, 1.0);
// Variable 1 is the dependent variable
if ( (rc = SF_vdata(1, i, &z)) ) return(rc);
gsl_vector_set (y, i - 1, z);
}
}
// Now we call the simulation function and output the results into b, mu
gsl_vector *b = gsl_vector_alloc (reps);
gsl_vector *mu = gsl_vector_alloc (reps);
sim_ci (X, y, P, reps, b, mu);
// Not sure that there is a good way to output this into Stata So I
// write to a file and read it back.
char outb[64], outmu[64];
strcpy (outb, argv[2]);
strcpy (outmu, argv[2]);
strcat (outb, "b");
strcat (outmu, "mu");
FILE *fb = fopen (outb, "wb");
FILE *fmu = fopen (outmu, "wb");
gsl_vector_fprintf (fb, b, "%15.9f");
gsl_vector_fprintf (fmu, mu, "%15.9f");
fclose (fb);
fclose (fmu);
// Cleanup
gsl_matrix_free (X);
gsl_vector_free (y);
gsl_vector_free (b);
gsl_vector_free (mu);
return (0);
}
/**
* @brief Simulate a confidence interval given X, y
*
* The idea is to simulate a non-parametric CI based on placebo
* assignments of a treatment variable. The program assigns
* treatment at random, hence a null effect, to individuals or
* clusters, optionally stratifying by any number of variables (or
* the means thereof, in the case of clusters). Consider
*
* Y_ij = a + b T_j + g X_ij + e_ij
*
* There are C = J choose PJ ways to treat the clusters (or C =
* P choose PN in the case of individuals). If we computed b_ols
* for c = 1, ..., C we would know the exact distribution of our
* estimator, conditional on the data being representative of the
* study data. C is typically intractably large, hence we simulate
* K draws with sum(T_jk = PJ) and run
*
* Y_ij = a + b_k T_jk + g X_ij + e_ij
*
* Let Fhat be the empirical cdf of b_k; a valid 1 - alpha CI for
* b is given by
*
* CI(1 - a) = [Fhat^-1(a / 2), Fhat^-1(1 - a / 2)]
*
* The function takes the @X as the covariate matrix, which
* must have k + 1 columns with the first column free, @y as
* the dependent variable, and outputs the results to @b, @mu
*
* @param X Covariate matrix with first column blank
* @param y Dependent variable
* @param P Proportion in treatment
* @param reps Number of reprtitions
* @param b Vector of length @reps; will output coefficients here
* @param mu Vector of length @reps; will output control means here
* @return Modified @b, @mu with coefficients and means
* @see Documentation for simci.ado
*/
int sim_ci (const gsl_matrix * X,
const gsl_vector * y,
const double P,
const int reps,
gsl_vector * b,
gsl_vector * mu)
{
const size_t n = X->size1;
const int k = X->size2;
const int np = ceil(n * P);
const int nc = n - np;
double *sy = malloc (sizeof(double));
gsl_vector *ones = gsl_vector_alloc (n);
gsl_vector_set_all (ones, 1.0);
gsl_blas_ddot (ones, y, sy);
// Set the random seed based on the time of day (seconds)
srand (time(NULL));
gsl_rng *rng = gsl_rng_alloc (gsl_rng_default);
gsl_rng_set (rng, rand());
// Get vector of 1s and 0s
gsl_vector *T = gsl_vector_alloc (n);
gsl_vector_set_zero (T);
for (int i = 0; i < np; i++) {
gsl_vector_set (T, i, 1.0);
}
// Initialize elements for parallel loop
gsl_vector *Tp ;
gsl_matrix *Xp ;
int nloops ;
double *sty ;
// Get the number of threads available to OMP
sf_printf("Parallelizing simulation; %d threads found:\n",
get_omp_num_threads());
// Parallelize execution: Note We need a copy of Xp and Tp for each
// thread since they will be modified at each iteration y does not
// change, so it's shared.
#pragma omp parallel private(Xp, Tp, nloops, sty) shared(y, b, sy)
{
nloops = 0;
// Allocate to each therad their own copy
Tp = gsl_vector_alloc (n);
Xp = gsl_matrix_alloc (n, k);
sty = malloc (sizeof(double));
gsl_vector_memcpy (Tp, T);
gsl_matrix_memcpy (Xp, X);
// Parallel for loop through simulation
#pragma omp for
for (int r = 0; r < reps; r++) {
// 1. Shuffle treatment
// 2. Set as first column of covariate matrix
// 3. Get mean of y over controls
// 4. Store coefficient/mean
// 5. Repeat 1-4
// 6. ...
// 7. Profit?
gsl_ran_shuffle (rng, Tp->data, n, sizeof(size_t));
gsl_matrix_set_col (Xp, 0, Tp);
gsl_vector_set (b, r, sim_ols(Xp, y));
gsl_blas_ddot (Tp, y, sty);
gsl_vector_set (mu, r, (*sy - *sty) / nc);
++nloops;
}
// I want to print a pretty message saying how many iterations
// each thread completed. Since threads finish on their own,
// messages would be print at disparate times. However, one can
// specify "critical" code which is executed only after all
// threads are done running.
#pragma omp critical
{
sf_printf("\tThread %d performed %d simulations.\n",
omp_get_thread_num(), nloops);
}
// Cleanup
gsl_matrix_free (Xp);
gsl_vector_free (Tp);
}
// Cleanup
gsl_vector_free (T);
gsl_rng_free (rng);
return (0);
}
/**
* @brief Number of threads available to OMP
*
* Short wrapper to get number of threads available to OMP
*
* @return Number of threads available to OMP
*/
int get_omp_num_threads()
{
int thread_id;
int nthreads = 0;
#pragma omp parallel private(thread_id) shared(nthreads)
{
thread_id = omp_get_thread_num();
#pragma omp critical
{
nthreads = thread_id > nthreads? thread_id: nthreads;
}
}
nthreads++;
return (nthreads);
}
/**
* @brief Wrapper to run a linear regression
*
* All I want is the first coefficient of a linear regression. For
*
* Y = X beta
*
* I want (X' X)^-1 X' Y. GSL has solvers for a system of the form
*
* Ax = b
*
* Where A is a symmetric matrix. Take A = X' X and b = X' y, then
* we can use any number of routines to find x (especially since A
* is now symmetric).
*
* @param X A n by k gsl matrix containing covariates.
* @param y A n by 1 gsl vector containing the dependent variable
* @return The first coefficient of a linear regression.
* @warning This is meant to be run within the main loop of stata_call
*/
double sim_ols(const gsl_matrix * X, const gsl_vector * y)
{
// Allocate memory to express the system as Ax = b
gsl_matrix *A = gsl_matrix_alloc (X->size2, X->size2);
gsl_vector *b = gsl_vector_alloc (X->size2);
gsl_vector *x = gsl_vector_alloc (X->size2);
// Set A = X' X and b = X' y
gsl_blas_dgemm (CblasTrans, CblasNoTrans, 1.0, X, X, 0.0, A);
gsl_blas_dgemv (CblasTrans, 1.0, X, y, 0.0, b);
// Cholesky decomposition
gsl_linalg_cholesky_decomp1 (A);
gsl_linalg_cholesky_solve (A, b, x);
// You don't have to use Cholesky; a number of methods are available
//
// int s;
// gsl_permutation * P = gsl_permutation_alloc (X->size2);
// gsl_vector * tau = gsl_vector_alloc (X->size2);
//
// Householder
// gsl_linalg_HH_solve (A, b, x);
//
// LU decomposition
// gsl_linalg_LU_decomp (A, P, &s);
// gsl_linalg_LU_solve (A, P, b, x);
// gsl_permutation_free (P);
//
// QR decomposition
// gsl_linalg_QR_decomp (A, tau);
// gsl_linalg_QR_solve (A, tau, b, x);
// gsl_vector_free (tau);
// Free up space
gsl_matrix_free (A);
gsl_vector_free (b);
return (gsl_vector_get(x, 0));
}
/**
* @brief Get pctile of a function
*
* Basic wrapper to get the @pctile percentile of a function.
*
* @param x n by 1 gsl vector whose percentile we want.
* @param pctile Percentile
* @return @pctile percentile of x
*/
double sim_pctile(gsl_vector * x, double pctile)
{
gsl_sort_vector (x);
int n = x->size;
int i = floor(n * pctile);
double qq = gsl_vector_get (x, i);
if (i / n == pctile) {
qq = (qq + gsl_vector_get (x, i + 1)) / 2;
}
return (qq);
}
| {
"alphanum_fraction": 0.6074022224,
"avg_line_length": 30.7231182796,
"ext": "c",
"hexsha": "5f18a743ef85b40ed0e321c329d5d0dabfae36ef",
"lang": "C",
"max_forks_count": 6,
"max_forks_repo_forks_event_max_datetime": "2020-11-05T17:05:13.000Z",
"max_forks_repo_forks_event_min_datetime": "2017-08-06T16:32:12.000Z",
"max_forks_repo_head_hexsha": "8d224e77b389bbb049158166f75e9c4bb10a088e",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "arlionn/stata-power",
"max_forks_repo_path": "src/psimci.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "8d224e77b389bbb049158166f75e9c4bb10a088e",
"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": "arlionn/stata-power",
"max_issues_repo_path": "src/psimci.c",
"max_line_length": 76,
"max_stars_count": 4,
"max_stars_repo_head_hexsha": "8d224e77b389bbb049158166f75e9c4bb10a088e",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "mcaceresb/stata-power",
"max_stars_repo_path": "src/psimci.c",
"max_stars_repo_stars_event_max_datetime": "2020-11-12T15:43:37.000Z",
"max_stars_repo_stars_event_min_datetime": "2017-06-20T21:43:56.000Z",
"num_tokens": 3234,
"size": 11429
} |
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include "compearth.h"
#ifdef COMPEARTH_USE_MKL
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wreserved-id-macro"
#pragma clang diagnostic ignored "-Wstrict-prototypes"
#endif
#include <mkl_cblas.h>
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#else
#include <cblas.h>
#endif
#define CHKERR(t1, t2, tol, name, str)\
{\
if (fabs(t1-t2) > tol){\
printf("%s: %s %e %e\n", name, str, t1, t2);\
return EXIT_FAILURE;\
}\
}
int check_lam2nualpha(void);
int check_Udetcheck(void);
int check_Uorth(void);
int check_lam2lune(void);
int check_CMTdecom(void);
int check_fangleSigned(void);
int check_CMT2faultpar(void);
int check_CMT2TT(void);
int check_TT2CMT(void);
int check_normal2strdip(void);
int check_CMT2omega(void);
int main(void)
{
int ierr;
ierr = check_lam2nualpha();
if (ierr != 0){printf("failed lam2nualpha\n"); return EXIT_FAILURE;}
printf("lam2nualpha was successful\n");
ierr = check_fangleSigned();
if (ierr != 0){printf("failed fangleSigned\n"); return EXIT_FAILURE;}
printf("fangleSigned was successful\n");
ierr = check_Udetcheck();
if (ierr != 0){printf("failed Udetcheck\n"); return EXIT_FAILURE;}
printf("udetcheck was successful\n");
ierr = check_Uorth();
if (ierr != 0){printf("failed Uorth\n"); return EXIT_FAILURE;}
printf("Uorth was successful\n");
ierr = check_lam2lune();
if (ierr != 0){printf("failed lam2lune\n"); return EXIT_FAILURE;}
printf("lam2lune was succesful\n");
ierr = check_CMTdecom();
if (ierr != 0){printf("failed CMTdecom\n"); return EXIT_FAILURE;}
printf("CMTdecom was successful\n");
ierr = check_CMT2TT();
if (ierr != 0){printf("failed CMT2TT\n"); return EXIT_FAILURE;}
printf("CMT2TT was successful\n");
ierr = check_TT2CMT();
if (ierr != 0){printf("failed TT2CMT\n"); return EXIT_FAILURE;}
printf("TT2CMT was successful\n");
ierr = check_CMT2faultpar();
if (ierr != 0){printf("failed CMT2faultpar\n"); return EXIT_FAILURE;}
printf("CMT2faultpar was successful\n");
ierr = check_normal2strdip();
if (ierr != 0){printf("failed noraml2strdip\n"); return EXIT_FAILURE;}
printf("normal2strdip was successful\n");
ierr = check_CMT2omega();
if (ierr != 0){printf("failed CMT2Omega\n"); return EXIT_FAILURE;}
printf("CMT2Omega was successful\n");
return EXIT_SUCCESS;
}
//============================================================================//
int check_fangleSigned(void)
{
const char *fcnm = "check_fangleSigned\0";
const double va[3] = {1, 0, 0};
const double vb[3] = {0, 0, 3};
const double vnor[3] = {0, -2, 0};
int ierr;
double stheta;
stheta = compearth_eulerUtil_fangleSigned(3, va,vb,vnor, &ierr);
if (fabs(stheta - 90.0) > 1.e-14 || ierr != 0)
{
printf("%s: failed test 1 %f %d\n", fcnm, stheta, ierr);
return EXIT_FAILURE;
}
const double vnor2[3] = {0, 2, 0};
stheta = compearth_eulerUtil_fangleSigned(3, va,vb,vnor2, &ierr);
if (fabs(stheta + 90.0) > 1.e-14 || ierr != 0)
{
printf("%s: failed test 2 %f %d\n", fcnm, stheta, ierr);
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
//============================================================================//
int check_Udetcheck(void)
{
const char *fcnm = "check_Udetcheck\0";
const double U[9] = {0.6948, 0.3171, 0.9502, // col 1
0.0344, 0.4387, 0.3816, // col 2
0.7655, 0.7952, 0.1869}; // col 3
const double Ur[9] = {0.6948, 0.3171, 0.9502, // col 1
-0.0344, -0.4387, -0.3816, // col 2 negated
0.7655, 0.7952, 0.1869};
double Un[9], Un2[9];
int i, ierr;
ierr = compearth_Udetcheck(1, U, Un);
if (ierr != 0)
{
printf("%s: Error in Udetcheck1\n", fcnm);
return EXIT_FAILURE;
}
ierr = compearth_Udetcheck(1, Un, Un2);
if (ierr != 0)
{
printf("%s: Error in Udetcheck2\n", fcnm);
return EXIT_FAILURE;
}
for (i=0; i<9; i++)
{
if (fabs(Ur[i] - Un[i]) > 1.e-12)
{
printf("%s: Udetcheck failed; %f %f\n", fcnm, Ur[i], Un[i]);
return EXIT_FAILURE;
}
if (fabs(Un[i] - Un2[i]) > 1.e-12)
{
printf("%s: Udetcheck2 failed; %f %f\n", fcnm, Un[i], Un2[i]);
return EXIT_FAILURE;
}
}
return EXIT_SUCCESS;
}
//============================================================================//
int check_lam2nualpha(void)
{
const char *fcnm = "check_lam2nualpha\0";
// example from TT2013, App A.
double lam[3] = { 8.802, 2.584, -1.851};
double lamcheck[3], nu, alpha, mag;
const double nu1 = 0.371745072651417;
const double alpha1 = 80.365019327257144;
int ierr;
ierr = compearth_lam2nualpha(1, lam, &nu, &alpha);
if (ierr != 0)
{
printf("%s: error calling lam2nualpha\n", fcnm);
return EXIT_FAILURE;
}
CHKERR(nu, nu1, 1.e-10, fcnm, "error computing nu 1");
CHKERR(alpha, alpha1, 1.e-10, fcnm, "error computing alpha 1");
ierr = compearth_nualpha2lam(1, &nu, &alpha, lamcheck);
if (ierr != 0)
{
printf("%s: error caling nualpha2lam\n", fcnm);
return EXIT_FAILURE;
}
mag = cblas_dnrm2(3, lam, 1);
lam[0] = lam[0]/mag;
lam[1] = lam[1]/mag;
lam[2] = lam[2]/mag;
CHKERR(lam[0], lamcheck[0], 1.e-10, fcnm, "error computing lam 1");
CHKERR(lam[1], lamcheck[1], 1.e-10, fcnm, "error computing lam 2");
CHKERR(lam[2], lamcheck[2], 1.e-10, fcnm, "error computing lam 3");
//lam / norm(lam)
return EXIT_SUCCESS;
}
//============================================================================//
int check_CMT2faultpar(void)
{
const double M[6] = {3.108304932835845, 3.044425632830430, 3.382269434333724,
-4.855033301709626,-1.949280336439431, 1.110527600460120};
double nu, alpha, N1[3], N2[3], lam[3];
const double nuRef = 0.371745072651417;
const double alphaRef = 80.365019327257144;
const double N1ref[3] = {-0.050351975426048, 0.930119048707825, 0.363790095799137};
const double N2ref[3] = {-0.977452142939121, 0.046467470073259, 0.205980781843140};
const double lamref[3] = { 8.802000000000001, 2.584000000000001, -1.851000000000002};
int ierr;
int nmt = 1;
ierr = compearth_CMT2faultpar(nmt, M,
&nu, &alpha, N1, N2, lam);
if (ierr != 0)
{
fprintf(stderr, "Error calling CMT2faultpar\n");
return EXIT_FAILURE;
}
CHKERR(nu, nuRef, 1.e-10, __func__, "error computing nu");
CHKERR(alpha, alphaRef, 1.e-10, __func__, "error computing alpha");
CHKERR(N1[0], N1ref[0], 1.e-10, __func__, "error checking N1[0]");
CHKERR(N1[1], N1ref[1], 1.e-10, __func__, "error checking N1[1]");
CHKERR(N1[2], N1ref[2], 1.e-10, __func__, "error checking N1[2]");
CHKERR(N2[0], N2ref[0], 1.e-10, __func__, "error checking N2[0]");
CHKERR(N2[1], N2ref[1], 1.e-10, __func__, "error checking N2[1]");
CHKERR(N2[2], N2ref[2], 1.e-10, __func__, "error checking N2[2]");
CHKERR(lam[0], lamref[0], 1.e-10, __func__, "error checking lam[0]");
CHKERR(lam[1], lamref[1], 1.e-10, __func__, "error checking lam[1]");
CHKERR(lam[2], lamref[2], 1.e-10, __func__, "error checking lam[2]");
return EXIT_SUCCESS;
}
//============================================================================//
int check_TT2CMT(void)
{
const double M01[1] = {1.0};
const double delta1[1] = {0.0};
const double gamma1[1] = {0.0};
const double kappa1[1] = {320.0};
const double theta1[1] = {10.0};
const double sigma1[1] = {20.0};
const double lam1Ref[3] = {1.0, 0.0, -1.0};
const double M61Ref[6] = { 0.116977778440511,
0.112364502228240,
-0.229342280668750,
-0.502322271868946,
-0.841048248646006,
0.029265111955970};
const double U1Ref[9] = {-0.434841577578901, -0.515496946820204,
0.738360142632131, 0.856848940622339,
-0.489063917059259, 0.163175911166535,
0.276988619555150, 0.703618776646631,
0.654368338007907};
double M61[6], lam1[3], U91[9];
int i, ierr, j;
memset(U91, 0, 9*sizeof(double));
ierr = compearth_TT2CMT(1, gamma1, delta1, M01, kappa1, theta1, sigma1,
M61, lam1, U91);
if (ierr != 0)
{
fprintf(stderr, "%s: error calling TT2CMT\n", __func__);
return EXIT_FAILURE;
}
CHKERR(M61[0], M61Ref[0], 1.e-10, __func__, "error checking M61[0]");
CHKERR(M61[1], M61Ref[1], 1.e-10, __func__, "error checking M61[1]");
CHKERR(M61[2], M61Ref[2], 1.e-10, __func__, "error checking M61[2]");
CHKERR(M61[3], M61Ref[3], 1.e-10, __func__, "error checking M61[3]");
CHKERR(M61[4], M61Ref[4], 1.e-10, __func__, "error checking M61[4]");
CHKERR(M61[5], M61Ref[5], 1.e-10, __func__, "error checking M61[5]");
CHKERR(lam1[0], lam1Ref[0], 1.e-10, __func__, "error checking lam[0]");
CHKERR(lam1[1], lam1Ref[1], 1.e-10, __func__, "error checking lam[1]");
CHKERR(lam1[2], lam1Ref[2], 1.e-10, __func__, "error checking lam[2]");
CHKERR(U91[0], U1Ref[0], 1.e-10, __func__, "error checking U1[0]");
CHKERR(U91[1], U1Ref[1], 1.e-10, __func__, "error checking U1[1]");
CHKERR(U91[2], U1Ref[2], 1.e-10, __func__, "error checking U1[2]");
CHKERR(U91[3], U1Ref[3], 1.e-10, __func__, "error checking U1[3]");
CHKERR(U91[4], U1Ref[4], 1.e-10, __func__, "error checking U1[4]");
CHKERR(U91[5], U1Ref[5], 1.e-10, __func__, "error checking U1[5]");
CHKERR(U91[6], U1Ref[6], 1.e-10, __func__, "error checking U1[6]");
CHKERR(U91[7], U1Ref[7], 1.e-10, __func__, "error checking U1[7]");
CHKERR(U91[8], U1Ref[8], 1.e-10, __func__, "error checking U1[8]");
// At this stage in the game CMT2TT works. So let's use it to verify
// its inverse operator.
int ng = 3;
double gamLoc[3] = {-29.0, 0.0, 29.0};
int nd = 3;
double deltaLoc[3] = {-89, 0.0, 89.0};
int nk = 5;
double kappaLoc[5] = {1.0, 90.0, 180.0, 270.0, 359.};
int ns = 3;
double sigmaLoc[3] = {-179.0, 1.0, 179.0};
int nt = 3;
double thetaLoc[3] = {10.0, 45.0, 80.0};
int nm = 3;
double M0loc[3] = {1.0, 2.0, 3.0};
int nmt = ng*nd*nk*ns*nt*nm;
double *gamma, *delta, *kappa, *sigma, *theta, *M0, *M, *U, *lam;
gamma = (double *) calloc((size_t) nmt, sizeof(double));
delta = (double *) calloc((size_t) nmt, sizeof(double));
kappa = (double *) calloc((size_t) nmt, sizeof(double));
sigma = (double *) calloc((size_t) nmt, sizeof(double));
theta = (double *) calloc((size_t) nmt, sizeof(double));
M0 = (double *) calloc((size_t) nmt, sizeof(double));
int ig, id, ik, is, im, imt, it;
imt = 0;
for (im=0; im<nm; im++)
{
for (ig=0; ig<ng; ig++)
{
for (id=0; id<nd; id++)
{
for (ik=0; ik<nk; ik++)
{
for (it=0; it<nt; it++)
{
for (is=0; is<ns; is++)
{
gamma[imt] = gamLoc[ig];
delta[imt] = deltaLoc[id];
kappa[imt] = kappaLoc[ik];
sigma[imt] = sigmaLoc[is];
theta[imt] = thetaLoc[it];
M0[imt] = M0loc[im];
imt = imt + 1;
}
}
}
}
}
}
M = (double *) calloc((size_t) (6*nmt), sizeof(double));
lam = (double *) calloc((size_t) (3*nmt), sizeof(double));
U = (double *) calloc((size_t) (9*nmt), sizeof(double));
ierr = compearth_TT2CMT(nmt, gamma, delta, M0, kappa, theta, sigma,
M, lam, U);
if (ierr != 0)
{
fprintf(stderr, "%s: error calling TT2CMT\n", __func__);
return EXIT_FAILURE;
}
/*
printf("\n");
for (i=0; i<nmt; i++)
{
printf("%d\n", 6*i);
printf("%e %e %e %e %e %e\n", M[6*i], M[6*i+1], M[6*i+2], M[6*i+3], M[6*i+4], M[6*i+5]);
}
getchar();
*/
bool ldisplay = false;
double *gammaNew = (double *) calloc((size_t) nmt, sizeof(double));
double *deltaNew = (double *) calloc((size_t) nmt, sizeof(double));
double *M0New = (double *) calloc((size_t) nmt, sizeof(double));
double *kappaNew = (double *) calloc((size_t) nmt, sizeof(double));
double *thetaNew = (double *) calloc((size_t) nmt, sizeof(double));
double *sigmaNew = (double *) calloc((size_t) nmt, sizeof(double));
double *K = (double *) calloc((size_t) (3*nmt), sizeof(double));
double *N = (double *) calloc((size_t) (3*nmt), sizeof(double));
double *S = (double *) calloc((size_t) (3*nmt), sizeof(double));
double *thetadc = (double *) calloc((size_t) nmt, sizeof(double));
double *lamNew = (double *) calloc((size_t) (3*nmt), sizeof(double));
double *UNew = (double *) calloc((size_t) (9*nmt), sizeof(double));
ierr = compearth_CMT2TT(nmt, M, ldisplay,
gammaNew, deltaNew, M0New,
kappaNew, thetaNew, sigmaNew,
K, N, S, thetadc,
lamNew, UNew);
if (ierr != 0)
{
fprintf(stderr, "%s: Error calling CMT2TT\n", __func__);
return EXIT_FAILURE;
}
double kappa2, theta2, sigma2;
for (i=0; i<nmt; i++)
{
ierr = compearth_auxiliaryPlane(1,
&kappaNew[i], &thetaNew[i], &sigmaNew[i],
&kappa2, &theta2, &sigma2);
if (fabs(gammaNew[i] - gamma[i]) > 1.e-10)
{
fprintf(stderr, "%s: Failed to compute gamma %e %e %d\n",
__func__, gamma[i], gammaNew[i], i);
return -1;
}
if (fabs(deltaNew[i] - delta[i]) > 1.e-10)
{
fprintf(stderr, "%s: Failed to compute delta %e %e %d\n",
__func__, delta[i], deltaNew[i], i);
return -1;
}
if (fabs(M0[i] - M0New[i]) > 1.e-10)
{
fprintf(stderr, "%s: Failed to compute M0 %e %e %d\n",
__func__, M0[i], M0New[i], i);
return -1;
}
if (fabs(kappaNew[i] - kappa[i]) > 1.e-10 &&
fabs(kappa2 - kappa[i]) > 1.e-10)
{
fprintf(stderr, "%s: Failed to compute kappa %e %e %e %d\n",
__func__, kappa[i], kappaNew[i], kappa2, i);
return -1;
}
if (fabs(thetaNew[i] - theta[i]) > 1.e-10 &&
fabs(theta2 - theta[i]) > 1.e-10)
{
fprintf(stderr, "%s: Failed to compute theta %e %e %d\n",
__func__, theta[i], thetaNew[i], i);
return -1;
}
if (fabs(sigmaNew[i] - sigma[i]) > 1.e-10 &&
fabs(sigma2 - sigma[i]) > 1.e-10)
{
fprintf(stderr, "%s: Failed to compute sigma %e %e %d\n",
__func__, sigma[i], sigmaNew[i], i);
return -1;
}
for (j=0; j<3; j++)
{
if (fabs(lamNew[3*i+j] - lam[3*i+j]) > 1.e-10)
{
fprintf(stderr, "%s: Failed to compute lam %e %e %d\n",
__func__, lam[3*i+j], lamNew[3*i+j], i);
return -1;
}
}
for (j=0; j<9; j++)
{
// Can be off up to a sign factor
if (fabs(UNew[9*i+j] - U[9*i+j]) > 1.e-10 &&
fabs(UNew[9*i+j] + U[9*i+j]) > 1.e-10)
{
fprintf(stderr, "%s: Failed to compute U %e %e %d\n",
__func__, UNew[9*i+j], U[9*i+j], i);
}
}
}
// Free space
free(gammaNew);
free(deltaNew);
free(M0New);
free(kappaNew);
free(thetaNew);
free(sigmaNew);
free(K);
free(N);
free(S);
free(thetadc);
free(lamNew);
free(UNew);
free(gamma);
free(delta);
free(kappa);
free(sigma);
free(theta);
free(M0);
free(M);
free(U);
free(lam);
return EXIT_SUCCESS;
}
//============================================================================//
int check_CMT2TT(void)
{
const char *fcnm = "check_CMT2TT\0";
const double M[6] = {3.108304932835845, 3.044425632830430,
3.382269434333724,-4.855033301709626,
-1.949280336439431, 1.110527600460120};
double U[9], lam[3];
bool ldisplay;
double gamma, delta, M0, kappa, sigma, theta, thetadc;
double K[3], N[3], S[3];
const double gamma1 = -5.519441015228609;
const double delta1 = 36.032871051674995;
const double M01 = 6.617343160211657;
const double kappa1 = 69.492561954605137;
const double theta1 = 88.144957350922951;
const double sigma1 = -79.788954797632840;
const double thetadc1 = 36.396475670817210;
const double KR1[3] = {-0.350328975576259, 0.936626718000127, 0};
const double NR1[3] = {0.936135854045508, 0.350145376429380, 0.032370945856051};
const double SR1[3] = {-0.032265105849630, 0.177200864349715, -0.983645676358224};
const double lam1[3] = {8.802000000000000, 2.584000000000003, -1.851000000000001};
const double UR1[9] = {-0.639133135365464,-0.372890102888132, 0.672652812709492,
0.350155145207092,-0.919781533321278,-0.177181560118875,
0.684762885649414, 0.122290237260530, 0.718432243365964};
// Test 2; problem child of horizontal fault
const double M2[6] = {0, 0, 0, -sqrt(3)/2., .5, 0};
const double gamma2 = 0.0; const double delta2 = 0.0;
const double M02 = 1.0; const double kappa2 = 300.0;
const double theta2 = 90.0; const double sigma2 = 90.0;
const double thetadc2 = 1.207418269725733e-06;
const double KR2[3] = {-0.500000000000000, -0.866025403784439, 0};
const double NR2[3] = {-0.866025403784439, 0.500000000000000, 0};
const double SR2[3] = {0, 0, 1};
const double lam2[3] = {1, 0, -1};
const double UR2[9] = {-0.612372435695794,0.353553390593274,0.707106781186547,
0.500000000000000,0.866025403784439,0,
-0.612372435695794,0.353553390593274,-0.707106781186547};
int i, ierr;
ldisplay = false;
ierr = compearth_CMT2TT(1, M, ldisplay,
&gamma, &delta, &M0, &kappa, &theta, &sigma,
K, N, S, &thetadc,
lam, U);
if (ierr != 0)
{
printf("%s: Error calling CMT2TT test 1\n", fcnm);
return EXIT_FAILURE;
}
CHKERR(gamma, gamma1, 1.e-10, fcnm, "error computing gamma 1");
CHKERR(delta, delta1, 1.e-10, fcnm, "error computing delta 1");
CHKERR(M0, M01, 1.e-10, fcnm, "error computing M0 1");
CHKERR(kappa, kappa1, 1.e-10, fcnm, "error computing kappa 1");
CHKERR(theta, theta1, 1.e-10, fcnm, "error computing theta 1");
CHKERR(sigma, sigma1, 1.e-10, fcnm, "error computing sigma 1");
CHKERR(thetadc, thetadc1, 1.e-10, fcnm, "error computing thetadc 1");
for (i=0; i<3; i++)
{
if (fabs(KR1[i] - K[i]) > 1.e-10)
{
printf("%s: Error computing K 1\n", fcnm);
return EXIT_FAILURE;
}
if (fabs(NR1[i] - N[i]) > 1.e-10)
{
printf("%s: Error computing N 1\n", fcnm);
return EXIT_FAILURE;
}
if (fabs(SR1[i] - S[i]) > 1.e-10)
{
printf("%s: Error computing S 1\n", fcnm);
return EXIT_FAILURE;
}
if (fabs(lam1[i] - lam[i]) > 1.e-10)
{
printf("%s: Error computing lam 1\n", fcnm);
return EXIT_FAILURE;
}
}
for (i=0; i<9; i++)
{
if (fabs(U[i] - UR1[i]) > 1.e-10)
{
printf("%s: Error computing U 1\n", fcnm);
return EXIT_FAILURE;
}
}
ierr = compearth_CMT2TT(1, M2, ldisplay,
&gamma, &delta, &M0, &kappa, &theta, &sigma,
K, N, S, &thetadc,
lam, U);
if (ierr != 0)
{
printf("%s: Error calling CMT2TT horizontal fault\n", fcnm);
return EXIT_FAILURE;
}
CHKERR(gamma, gamma2, 1.e-10, fcnm, "error computing gamma 2");
CHKERR(delta, delta2, 1.e-10, fcnm, "error computing delta 2");
CHKERR(M0, M02, 1.e-10, fcnm, "error computing M0 2");
CHKERR(kappa, kappa2, 1.e-10, fcnm, "error computing kappa 2");
CHKERR(theta, theta2, 1.e-10, fcnm, "error computing theta 2");
CHKERR(sigma, sigma2, 1.e-10, fcnm, "error computing sigma 2");
CHKERR(thetadc, thetadc2, 1.e-10, fcnm, "error computing thetadc 2");
for (i=0; i<3; i++)
{
if (fabs(KR2[i] - K[i]) > 1.e-10)
{
printf("%s: Error computing K 2\n", fcnm);
return EXIT_FAILURE;
}
if (fabs(NR2[i] - N[i]) > 1.e-10)
{
printf("%s: Error computing N 2\n", fcnm);
return EXIT_FAILURE;
}
if (fabs(SR2[i] - S[i]) > 1.e-10)
{
printf("%s: Error computing S 2\n", fcnm);
return EXIT_FAILURE;
}
if (fabs(lam2[i] - lam[i]) > 1.e-10)
{
printf("%s: Error computing lam 2\n", fcnm);
return EXIT_FAILURE;
}
}
for (i=0; i<9; i++)
{
if (fabs(U[i] - UR2[i]) > 1.e-10)
{
printf("%s: Error computing U 2\n", fcnm);
return EXIT_FAILURE;
}
}
return EXIT_SUCCESS;
}
//============================================================================//
int check_CMTdecom(void)
{
const char *fcnm = "check_CMTdecom\0";
const double M[6] = {3.108304932835845, 3.044425632830430,
3.382269434333724,-4.855033301709626,
-1.949280336439431, 1.110527600460120};
double U[9], lam[3];
double lamRef1[3] = {8.8020000000e+00, 2.5840000000e+00, -1.8510000000e+00};
double lamRef2[3] = {-1.851000000000002, 2.584000000000001, 8.802000000000001};
double *lamRef3 = lamRef1;
double *lamRef4 = lamRef2;
double URef1[9] = {-0.672652812709492, 0.639133135365464, 0.372890102888132,
0.177181560118875,-0.350155145207092, 0.919781533321279,
0.718432243365964, 0.684762885649414, 0.122290237260530};
double URef2[9] = { 0.718432243365964, 0.684762885649414, 0.122290237260530,
-0.177181560118875, 0.350155145207092,-0.919781533321279,
-0.672652812709492, 0.639133135365464, 0.372890102888132};
double *URef3 = URef1;
double *URef4 = URef2;
int i, ierr;
ierr = compearth_CMTdecom(1, M, 1, lam, U);
if (ierr != 0)
{
printf("%s: Error 1 calling CMTdecom\n", fcnm);
return EXIT_FAILURE;
}
for (i=0; i<3; i++)
{
if (fabs(lam[i] - lamRef1[i]) > 1.e-13)
{
printf("%s: lam 1 is wrong %e %e\n", fcnm, lam[i], lamRef1[i]);
return EXIT_FAILURE;
}
}
for (i=0; i<9; i++)
{
if (fabs(U[i] - URef1[i]) > 1.e-13)
{
printf("%s: U 1 is wrong %d %e %e\n", fcnm, i, U[i], URef1[i]);
return EXIT_FAILURE;
}
}
ierr = compearth_CMTdecom(1, M, 2, lam, U);
if (ierr != 0)
{
printf("%s: Error 2 calling CMTdecom\n", fcnm);
return EXIT_FAILURE;
}
for (i=0; i<3; i++)
{
if (fabs(lam[i] - lamRef2[i]) > 1.e-13)
{
printf("%s: lam 2 is wrong %e %e\n", fcnm, lam[i], lamRef2[i]);
return EXIT_FAILURE;
}
}
for (i=0; i<9; i++)
{
if (fabs(U[i] - URef2[i]) > 1.e-13)
{
printf("%s: U 2 is wrong %d %e %e\n", fcnm, i, U[i], URef2[i]);
return EXIT_FAILURE;
}
}
ierr = compearth_CMTdecom(1, M, 3, lam, U);
if (ierr != 0)
{
printf("%s: Error calling CMTdecom 3\n", fcnm);
return EXIT_FAILURE;
}
for (i=0; i<3; i++)
{
if (fabs(lam[i] - lamRef3[i]) > 1.e-13)
{
printf("%s: lam 3 is wrong %e %e\n", fcnm, lam[i], lamRef3[i]);
return EXIT_FAILURE;
}
}
for (i=0; i<9; i++)
{
if (fabs(U[i] - URef3[i]) > 1.e-13)
{
printf("%s: U 3 is wrong %d %e %e\n", fcnm, i, U[i], URef3[i]);
return EXIT_FAILURE;
}
}
ierr = compearth_CMTdecom(1, M, 4, lam, U);
if (ierr != 0)
{
printf("%s: Error calling CMTdecom 4\n", fcnm);
return EXIT_FAILURE;
}
for (i=0; i<3; i++)
{
if (fabs(lam[i] - lamRef4[i]) > 1.e-13)
{
printf("%s: lam 4 is wrong %e %e\n", fcnm, lam[i], lamRef4[i]);
return EXIT_FAILURE;
}
}
for (i=0; i<9; i++)
{
if (fabs(U[i] - URef4[i]) > 1.e-13)
{
printf("%s: U 4 is wrong %d %e %e\n", fcnm, i, U[i], URef4[i]);
return EXIT_FAILURE;
}
}
return EXIT_SUCCESS;
}
//============================================================================//
int check_lam2lune(void)
{
const char *fcnm = "check_lam2lune\0";
const double lamRef1[6] = {
-7.9621992143e+15,-8.2644837610e+15,-8.2644837610e+15,
-7.5915701171e+15,-8.4370629711e+15,-8.4370629711e+15};
double *gamma0, *gamma, *delta, *delta0, *lam, *M0, *M00;
double *thetadc, *lamdev, *lamiso;
int i, ib, ierr, ig, indx;
const int ng = 100;
const int nb = 100;
int nmt = ng*nb;
const double dg = (30.0 - -30.0)/(double) (ng - 1);
const double db = (89.0 - -89.0)/(double) (nb - 1);
gamma0 = (double *) calloc((size_t) nmt, sizeof(double));
delta0 = (double *) calloc((size_t) nmt, sizeof(double));
M00 = (double *) calloc((size_t) nmt, sizeof(double));
gamma = (double *) calloc((size_t) nmt, sizeof(double));
delta = (double *) calloc((size_t) nmt, sizeof(double));
M0 = (double *) calloc((size_t) nmt, sizeof(double));
lam = (double *) calloc((size_t) (3*nmt), sizeof(double));
for (ig=0; ig<ng; ig++)
{
for (ib=0; ib<nb; ib++)
{
indx = ig*nb + ib;
gamma0[indx] =-30.0 + (double) ig*dg;
delta0[indx] =-89.0 + (double) ib*db; // use latitude instead of colat
M00[indx] = 1.e16;
}
}
compearth_lune2lam(nmt, gamma0, delta0, M00, lam);
// Verify the first two computations are right
for (i=0; i<6; i++)
{
if (fabs(lam[i] - lamRef1[i])/1.e16 > 1.e-10)
{
printf("%s: error in lune2lam: %.10e %.10e\n",
fcnm, lam[i], lamRef1[i]);
return EXIT_FAILURE;
}
}
// Now perform the inverse operation
thetadc = NULL;
lamdev = NULL;
lamiso = NULL;
ierr = compearth_lam2lune(nmt, lam,
gamma, delta, M0,
thetadc, lamdev, lamiso);
if (ierr != 0)
{
printf("%s: error calling lam2lune\n", fcnm);
return EXIT_FAILURE;
}
// See how close i was
for (i=0; i<nmt; i++)
{
if (fabs(gamma[i] - gamma0[i]) > 1.e-12)
{
printf("%s: gamma[%d] different %e %e %e\n",
__func__, i, gamma[i], gamma0[i],
fabs(gamma[i] - gamma0[i]));
return EXIT_FAILURE;
}
if (fabs(delta[i] - delta0[i]) > 1.e-12)
{
printf("%s: delta[%d] different %e %e %e\n",
__func__, i, delta[i], delta0[i],
fabs(delta[i] - delta0[i]));
return EXIT_FAILURE;
}
if (fabs(M0[i] - M00[i])/1.e15 > 1.e-12)
{
printf("%s: M0[%d] different %e %e %e\n",
__func__, i, M0[i], M00[i], fabs(M0[i] - M00[i]));
return EXIT_FAILURE;
}
}
free(gamma0);
free(delta0);
free(M00);
free(gamma);
free(delta);
free(M0);
free(lam);
return EXIT_SUCCESS;
}
int check_CMT2omega(void)
{
const double M1[6] = {1, 0, -1, 0, 0, 0};
const double M2[6] = {1, 2, 3, 4, 5, 6};
double *Mvec1, *Mvec2, *omega, *refOmega, om1;
const double omRef1 = 96.263952719927232;
int i, ierr, j, nmt1, nmt2;
ierr = compearth_CMT2omega(1, M1, 1, M2, &om1);
if (ierr != 0)
{
fprintf(stderr, "%s: Error calling CMT2omega 1\n", __func__);
return EXIT_FAILURE;
}
CHKERR(om1, omRef1, 1.e-10, __func__, "error computing CMT2Omega1");
nmt2 = 80;
Mvec1 = (double *) calloc((size_t) (6*nmt2), sizeof(double));
Mvec2 = (double *) calloc((size_t) (6*nmt2), sizeof(double));
omega = (double *) calloc((size_t) nmt2, sizeof(double));
refOmega = (double *) calloc((size_t) nmt2, sizeof(double));
for (i=0; i<nmt2; i++)
{
cblas_dcopy(6, M2, 1, &Mvec2[6*i], 1);
}
// one to many
ierr = compearth_CMT2omega(1, M1, nmt2, Mvec2, omega);
if (ierr != 0)
{
fprintf(stderr, "%s: Error calling CMT2omega 2\n", __func__);
return EXIT_FAILURE;
}
for (i=0; i<nmt2; i++)
{
CHKERR(omega[i], omRef1, 1.e-10, __func__,
"error computing CMT2Omega2");
}
// flip roles
ierr = compearth_CMT2omega(nmt2, Mvec2, 1, M1, omega);
if (ierr != 0)
{
fprintf(stderr, "%s: Error calling CMT2omega 3\n", __func__);
return EXIT_FAILURE;
}
for (i=0; i<nmt2; i++)
{
CHKERR(omega[i], omRef1, 1.e-10, __func__,
"error computing CMT2Omega3");
}
// many to many
nmt1 = nmt2;
srand(4093);
for (i=0; i<nmt1; i++)
{
for (j=0; j<6; j++)
{
Mvec1[6*i+j] = ((double) (rand())/RAND_MAX - 0.5)*2.0;
Mvec2[6*i+j] = ((double) (rand())/RAND_MAX - 0.5)*2.0;
}
compearth_CMT2omega(1, &Mvec1[6*i], 1, &Mvec2[6*i], &refOmega[i]);
}
ierr = compearth_CMT2omega(nmt1, Mvec1, nmt2, Mvec2, omega);
if (ierr != 0)
{
fprintf(stderr, "%s: Error calling CMT2omega 4\n", __func__);
return EXIT_FAILURE;
}
for (i=0; i<nmt2; i++)
{
CHKERR(omega[i], refOmega[i], 1.e-10, __func__,
"error computing CMT2Omega4");
}
free(Mvec1);
free(Mvec2);
free(omega);
free(refOmega);
return EXIT_SUCCESS;
}
int check_normal2strdip(void)
{
const double Xin[3] = {-0.171010071662835, 0.969846310392954,
0.173648177666930};
double Xout[2];
compearth_normal2strdip(1, Xin, Xout);
CHKERR(Xout[0], 350.0, 1.e-10, __func__, "error computing Xout[0]");
CHKERR(Xout[1], 80.0, 1.e-10, __func__, "error computing Xout[1]");
return EXIT_SUCCESS;
}
int check_Uorth(void)
{
const double T[9] = {0.998800000000000, 0.047900000000000, 0.017300000000000,
-0.048200000000000, 0.998800000000000, 0.015900000000000,
-0.016500000000000,-0.016700000000000, 0.999800000000000};
const double Tref[9] = { 0.998702105045258, 0.047907730990670, 0.017290306229078,
-0.048183355871821, 0.998712063377127, 0.015892724182219,
-0.016506653055635, -0.016705202073855, 0.999724195280165};
const double detInRef1 = 1.000261915677000;
const double detOutRef1 = 1.0;
double Tout[9], detIn, detOut;
int i, j, ierr;
ierr = compearth_Uorth(1, CE_ORTH_SVD, T, Tout, &detIn, &detOut);
if (ierr != 0)
{
fprintf(stderr, "%s: Error calling Uorth_svd\n", __func__);
return EXIT_FAILURE;
}
for (i=0; i<3; i++)
{
for (j=0; j<3; j++)
{
if (fabs(Tout[3*j+i] - Tref[3*j+i]) > 1.e-14)
{
printf("%s: Failed calculating T(%d,%d)=%f ",
__func__, i+1,j+1, Tout[3*j+i] - Tref[3*j+i]);
return EXIT_FAILURE;
}
}
}
CHKERR(detIn, detInRef1, 1.e-10, __func__, "error computing detIn1");
CHKERR(detOut, detOutRef1, 1.e-10, __func__, "error computing detOUt1");
return EXIT_SUCCESS;
}
| {
"alphanum_fraction": 0.5216834791,
"avg_line_length": 35.8220524017,
"ext": "c",
"hexsha": "3daf615666ea4e0ae60fe7636ede859a15eee727",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2017-10-26T19:49:45.000Z",
"max_forks_repo_forks_event_min_datetime": "2017-10-26T19:49:45.000Z",
"max_forks_repo_head_hexsha": "53e75a00bf5be939730ec02ede49e65ef140ee41",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "bakerb845/compearth",
"max_forks_repo_path": "momenttensor/c_src/unit_tests/checks.c",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "53e75a00bf5be939730ec02ede49e65ef140ee41",
"max_issues_repo_issues_event_max_datetime": "2017-11-02T17:30:53.000Z",
"max_issues_repo_issues_event_min_datetime": "2017-11-02T17:30:53.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "bakerb845/compearth",
"max_issues_repo_path": "momenttensor/c_src/unit_tests/checks.c",
"max_line_length": 89,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "53e75a00bf5be939730ec02ede49e65ef140ee41",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "bakerb845/compearth",
"max_stars_repo_path": "momenttensor/c_src/unit_tests/checks.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 11085,
"size": 32813
} |
#include <stdio.h>
#include <gsl/gsl_block.h>
int
main (void)
{
gsl_block * b = gsl_block_alloc (100);
printf ("length of block = %zu\n", b->size);
printf ("block data address = %p\n", b->data);
gsl_block_free (b);
return 0;
}
| {
"alphanum_fraction": 0.6198347107,
"avg_line_length": 16.1333333333,
"ext": "c",
"hexsha": "ca6e80e3d733baf32b3090b7b78f1d66270204da",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z",
"max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "Brian-ning/HMNE",
"max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/doc/examples/block.c",
"max_issues_count": 6,
"max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e",
"max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z",
"max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "Brian-ning/HMNE",
"max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/doc/examples/block.c",
"max_line_length": 48,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "ielomariala/Hex-Game",
"max_stars_repo_path": "gsl-2.6/doc/examples/block.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": 77,
"size": 242
} |
#pragma once
#include "rev/gl/Context.h"
#include "rev/gl/Resource.h"
#include <gsl/span>
namespace rev {
using Buffer = Resource<singleCreate<gl::genBuffers>, singleDestroy<gl::deleteBuffers>>;
} // namespace rev
| {
"alphanum_fraction": 0.7305936073,
"avg_line_length": 16.8461538462,
"ext": "h",
"hexsha": "f4fd4547f95588980fc0a1429eea81c639d76b65",
"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": "d8abdf0a0016e309942932c9af9df1f8a2b02448",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "eyebrowsoffire/rev",
"max_forks_repo_path": "engine/include/rev/gl/Buffer.h",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "d8abdf0a0016e309942932c9af9df1f8a2b02448",
"max_issues_repo_issues_event_max_datetime": "2019-01-27T16:52:41.000Z",
"max_issues_repo_issues_event_min_datetime": "2019-01-27T16:52:41.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "eyebrowsoffire/rev",
"max_issues_repo_path": "engine/include/rev/gl/Buffer.h",
"max_line_length": 88,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "d8abdf0a0016e309942932c9af9df1f8a2b02448",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "eyebrowsoffire/rev",
"max_stars_repo_path": "engine/include/rev/gl/Buffer.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 55,
"size": 219
} |
/// @file UniquePtr.h
/// @author Braxton Salyer <braxtonsalyer@gmail.com>
/// @brief This includes Hyperion's `constexpr` equivalents and extensions to the C++ standard
/// library's `std::unique_ptr<T, Deleter>`
/// @version 0.1
/// @date 2021-11-05
///
/// MIT License
/// @copyright Copyright (c) 2021 Braxton Salyer <braxtonsalyer@gmail.com>
///
/// Permission is hereby granted, free of charge, to any person obtaining a copy
/// of this software and associated documentation files (the "Software"), to deal
/// in the Software without restriction, including without limitation the rights
/// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
/// copies of the Software, and to permit persons to whom the Software is
/// furnished to do so, subject to the following conditions:
///
/// The above copyright notice and this permission notice shall be included in all
/// copies or substantial portions of the Software.
///
/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
/// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
/// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
/// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
/// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
/// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
/// SOFTWARE.
#pragma once
#include <Hyperion/Concepts.h>
#include <Hyperion/HyperionDef.h>
#include <Hyperion/memory/CompressedPair.h>
#include <gsl/gsl>
/// @ingroup memory
/// @{
/// @defgroup UniquePtr UniquePtr
/// Hyperion provides a `constexpr` equivalent to the C++ standard library's
/// `std::unique_ptr<T, Deleter>` in our `UniquePtr`, with additional functionality like allocator
/// aware factory functions (`allocate_unique`).
///
/// Example:
///
/// auto ptr = hyperion::make_unique<i32>(42);
/// ptr.reset(24);
///
/// auto ptr2 = hyperion::allocate_unique<i32>(std::allocator<i32>(), 42);
/// ptr2.reset(24);
/// @headerfile "Hyperion/memory/UniquePtr.h"
/// @}
namespace hyperion {
/// @brief Default Deleter type for Hyperion smart pointers
/// This is the default deleter type used by Hyperion smart pointers
/// such as `hyperion::UniquePtr<T, Deleter>`
///
/// @tparam T The type to handle deletion for (eg, `i32`, `std::string`)
///
/// # Requirements
/// - `concepts::Deletable<T>`: T must be a deletable type
/// - `concepts::NotFunction<T>`: T must NOT be a function type
/// @ingroup memory
/// @headerfile "Hyperion/memory/UniquePtr.h"
template<typename T>
requires concepts::Deletable<T> && concepts::NotFunction<T>
struct DefaultDeleter {
/// @brief Default constructs a `DefaultDeleter`
/// @ingroup memory
constexpr DefaultDeleter() noexcept = default;
/// @brief Copy-constructs a `DefaultDeleter` from the given one
/// @ingroup memory
constexpr DefaultDeleter(const DefaultDeleter&) noexcept = default;
/// @brief Move-constructs a `DefaultDeleter` from the given one
/// @ingroup memory
constexpr DefaultDeleter(DefaultDeleter&&) noexcept = default;
/// @brief Destructs a `DefaultDeleter`
/// @ingroup memory
constexpr ~DefaultDeleter() noexcept = default;
/// @brief Constructs a `DefaultDeleter<T>` from a `DefaultDeleter<U>`
///
/// @tparam U - The type managed by the given deleter
///
/// @param deleter - The deleter to construct this from
///
/// # Requirements
/// - `concepts::Convertible<U*, T*>`: The pointer type of `deleter` must be convertible two
/// the pointer type of `DefaultDeleter<T>` in order to construct a `DefaultDeleter` from it
/// @ingroup memory
template<typename U>
requires concepts::Convertible<U*, T*>
explicit DefaultDeleter([[maybe_unused]] const DefaultDeleter<U>& deleter) noexcept {
}
/// @brief Deletes the data at the given pointer
///
/// @param ptr - The pointer to the data to delete
/// @ingroup memory
constexpr auto
operator()(gsl::owner<T*> ptr) const noexcept(concepts::NoexceptDeletable<T>) {
delete ptr;
}
/// @brief Copy-assigns this `DefaultDeleter` from the given one
/// @ingroup memory
constexpr auto operator=(const DefaultDeleter&) noexcept -> DefaultDeleter& = default;
/// @brief Move-assigns this `DefaultDeleter` from the given one
/// @ingroup memory
constexpr auto operator=(DefaultDeleter&&) noexcept -> DefaultDeleter& = default;
};
template<typename T>
requires concepts::Deletable<T[]> && concepts::NotFunction<T>
struct DefaultDeleter<T[]> { // NOLINT
constexpr DefaultDeleter() noexcept = default;
constexpr DefaultDeleter(const DefaultDeleter&) noexcept = default;
constexpr DefaultDeleter(DefaultDeleter&&) noexcept = default;
constexpr ~DefaultDeleter() noexcept = default;
template<typename U>
requires concepts::Convertible<U (*)[], T (*)[]> // NOLINT
explicit DefaultDeleter([[maybe_unused]] const DefaultDeleter<U[]>& deleter) // NOLINT
noexcept {
}
constexpr auto
operator()(gsl::owner<T*> ptr) const noexcept(concepts::NoexceptDeletable<T[]>) // NOLINT
{
delete[] ptr;
}
constexpr auto operator=(const DefaultDeleter&) noexcept -> DefaultDeleter& = default;
constexpr auto operator=(DefaultDeleter&&) noexcept -> DefaultDeleter& = default;
};
/// @brief `UniquePtr<T, Deleter>` is Hyperion's `constexpr` equivalent to the standard
/// library's `std::unique_ptr<T, Deleter>`
///
/// `UniquePtr<T, Deleter>` is a `constexpr` implementation of a unique owning pointer, with
/// almost complete semantic equivalence with `std::unique_ptr<T, Deleter>`.
/// It is a drop-in replacement in almost all situations(1).
/// Hyperion also provides extended functionality for `UniquePtr<T, Deleter>`
/// over `std::unique_ptr<T, Deleter>`, eg: an allocator-aware factory function set in
/// `allocate_unique`
///
/// @tparam T - The type to store in the `UniquePtr`
/// @tparam Deleter - The deleter type to handle deletion of the stored `T`, by default, this is
/// `hyperion::DefaultDeleter<T>`. This type only needs to be explicitly provided when custom
/// deletion or resource-freeing strategies are required.
///
/// # Requirements
/// - `!std::is_rvalue_reference_v<Deleter>`: `Deleter` cannot be an r-value reference type
///
/// @note(1): The exception is in situations where destructor ordering is required and code was
/// compiled with Clang. `UniquePtr<T, Deleter>` makes use of Clang's `trivial_abi` attribute,
/// which allows `UniquePtr<T, Deleter>` to be passed via register in function calls
/// (and thus removes its overhead compared to a raw pointer), but moves the call to its
/// destructor from the calling code to the callee. The result is that the destructor for
/// `UniquePtr<T, Deleter>` will not nest in the same way as `std::unique_ptr<T, Deleter>`, and
/// code relying on that behavior may experience issues. This is identical behavior to
/// `std::unique_ptr<T, Deleter>` when `_LIBCPP_ABI_ENABLE_UNIQUE_PTR_TRIVIAL_ABI` is defined
/// @ingroup UniquePtr
/// @headerfile "Hyperion/memory/UniquePtr.h"
template<typename T, typename Deleter = DefaultDeleter<T>>
requires concepts::NotRValueReference<Deleter>
class HYPERION_TRIVIAL_ABI UniquePtr {
public:
/// @brief The element type allocated in the `UniquePtr`
/// @ingroup UniquePtr
using element_type = T;
/// @brief The deleter type used by the `UniquePtr`
/// @ingroup UniquePtr
using deleter_type = Deleter;
/// @brief The pointer type stored in the `UniquePtr`
/// @ingroup UniquePtr
using pointer = T*;
/// @brief The pointer type stored in the `UniquePtr`, as a pointer to const
/// @ingroup UniquePtr
using pointer_to_const = const T*;
/// @brief Constructs a default `UniquePtr<T, Deleter>`, managing no pointer
///
/// # Requirements
/// - `concepts::NoexceptDefaultConstructible<deleter_type>`: `deleter_type` must be
/// noexcept default constructible in order to default construct a `UniquePtr`
/// - `concepts::NotPointer<deleter_type>`: `deleter_type` must not be a pointer
/// in order to default construct a `UniquePtr`
/// @ingroup UniquePtr
constexpr UniquePtr() noexcept requires concepts::NoexceptDefaultConstructible<
deleter_type> && concepts::NotPointer<deleter_type>
: m_ptr(pointer(), DefaultInitTag<deleter_type>()) {
}
/// @brief Constructs a `UniquePtr<T, Deleter>` managing no pointer
///
/// @param ptr - The `nullptr` signaling this `UniquePtr` should manage no pointer
///
/// # Requirements
/// - `concepts::NoexceptDefaultConstructible<deleter_type>`: `deleter_type` must be
/// noexcept default constructible in order to construct a `UniquePtr` from only a `nullptr`
/// - `concepts::NotPointer<deleter_type>`: `deleter_type` must not be a pointer
/// in order to construct a `UniquePtr` from only a `nullptr`
/// @ingroup UniquePtr
constexpr UniquePtr(std::nullptr_t ptr) noexcept // NOLINT
requires concepts::NoexceptDefaultConstructible<deleter_type> && concepts::NotPointer<
deleter_type> : m_ptr(ptr, DefaultInitTag<deleter_type>()) {
}
/// @brief Constructs a `UniquePtr<T, Deleter>` managing the given pointer
///
/// @param ptr - The pointer to manage with this `UniquePtr`
///
/// # Requirements
/// - `concepts::NoexceptDefaultConstructible<deleter_type>`: `deleter_type` must be
/// noexcept default constructible in order to construct a `UniquePtr` from only a `pointer`
/// - `concepts::NotPointer<deleter_type>`: `deleter_type` must not be a pointer
/// in order to construct a `UniquePtr` from only a `pointer`
/// @ingroup UniquePtr
explicit constexpr UniquePtr(pointer ptr) noexcept requires concepts::
NoexceptDefaultConstructible<deleter_type> && concepts::NotPointer<deleter_type>
: m_ptr(ptr, DefaultInitTag<deleter_type>()) {
}
/// @brief Constructs a `UniquePtr<T, Deleter>` managing the given pointer
///
/// @tparam U - The type of the pointer to manage in this `UniquePtr`
///
/// @param ptr - The pointer to manage with this `UniquePtr`
///
/// # Requirements
/// - `concepts::Convertible<U, pointer>`: `U` must be convertible to `pointer` to construct
/// a `UniquePtr` from it
/// - `concepts::NoexceptDefaultConstructible<deleter_type>`: `deleter_type` must be
/// noexcept default constructible in order to construct a `UniquePtr` from only a `pointer`
/// - `concepts::NotPointer<deleter_type>`: `deleter_type` must not be a pointer
/// in order to construct a `UniquePtr` from only a `pointer`
/// @ingroup UniquePtr
template<typename U>
requires concepts::Convertible<U, pointer> && concepts::NoexceptDefaultConstructible<
deleter_type> && concepts::NotPointer<deleter_type>
explicit constexpr UniquePtr(U ptr) noexcept : m_ptr(ptr, DefaultInitTag<deleter_type>()) {
}
/// @brief Constructs a `UniquePtr<T, Deleter>` managing the given pointer
///
/// @param ptr - The pointer to manage with this `UniquePtr`
/// @param deleter - The deleter to delete `ptr` with when the destructor of this
/// `UniquePtr` is called
///
/// @ingroup UniquePtr
constexpr UniquePtr(pointer ptr, const Deleter& deleter) noexcept requires
concepts::NoexceptCopyConstructible<Deleter> : m_ptr(ptr, deleter) {
}
/// @brief Constructs a `UniquePtr<T, Deleter>` managing the given pointer
///
/// @param ptr - The pointer to manage with this `UniquePtr`
/// @param deleter - The deleter to delete `ptr` with when the destructor of this
/// `UniquePtr` is called
///
/// @ingroup UniquePtr
constexpr UniquePtr(pointer ptr, Deleter&& deleter) noexcept requires
concepts::NoexceptMoveConstructible<Deleter> && concepts::NotRValueReference<Deleter>
: m_ptr(ptr, std::move(deleter)) {
}
/// @brief Constructs a `UniquePtr<T, Deleter>` managing the given pointer
///
/// @tparam U - The type of the pointer to manage in this `UniquePtr`
///
/// @param ptr - The pointer to manage with this `UniquePtr`
/// @param deleter - The deleter to delete `ptr` with when the destructor of this
/// `UniquePtr` is called
///
/// # Requirements
/// - `concepts::Convertible<U, pointer>`: `U` must be convertible to `pointer` to construct
/// a `UniquePtr` from it
/// @ingroup UniquePtr
template<typename U>
requires concepts::Convertible<U, pointer> && concepts::NotSame<U, pointer> && concepts::
NoexceptCopyConstructible<Deleter>
constexpr UniquePtr(U ptr, const Deleter& deleter) noexcept : m_ptr(ptr, deleter) {
}
/// @brief Constructs a `UniquePtr<T, Deleter>` managing the given pointer
///
/// @tparam U - The type of the pointer to manage in this `UniquePtr`
///
/// @param ptr - The pointer to manage with this `UniquePtr`
/// @param deleter - The deleter to delete `ptr` with when the destructor of this
/// `UniquePtr` is called
///
/// # Requirements
/// - `concepts::Convertible<U, pointer>`: `U` must be convertible to `pointer` to construct
/// a `UniquePtr` from it
/// @ingroup UniquePtr
template<typename U>
requires concepts::Convertible<U, pointer> && concepts::NotSame<U, pointer> && concepts::
NoexceptMoveConstructible<Deleter> && concepts::NotRValueReference<Deleter>
constexpr UniquePtr(U ptr, Deleter&& deleter) noexcept : m_ptr(ptr, std::move(deleter)) {
}
/// @brief Constructs a `UniquePtr<T, Deleter>` managing no pointer
///
/// @param ptr - The `nullptr` signaling this `UniquePtr` should manage no pointer
/// @param deleter - The deleter to delete a managed pointer with when the destructor of
/// this `UniquePtr` is called
///
/// @ingroup UniquePtr
constexpr UniquePtr(std::nullptr_t ptr, const Deleter& deleter) noexcept requires
concepts::NoexceptCopyConstructible<Deleter> : m_ptr(ptr, deleter) {
}
/// @brief Constructs a `UniquePtr<T, Deleter>` managing no pointer
///
/// @param ptr - The `nullptr` signaling this `UniquePtr` should manage no pointer
/// @param deleter - The deleter to delete a managed pointer with when the destructor of
/// this `UniquePtr` is called
///
/// @ingroup UniquePtr
constexpr UniquePtr(std::nullptr_t ptr, Deleter&& deleter) noexcept requires
concepts::NoexceptMoveConstructible<Deleter> && concepts::NotRValueReference<Deleter>
: m_ptr(ptr, std::move(deleter)) {
}
/// @brief Constructs a `UniquePtr<T, Deleter>` from the given moved `UniquePtr<U, D>`
///
/// @param ptr - The `UniquePtr` to construct this one from
///
/// # Requirements
/// - `concepts::NoexceptConstructibleFrom<deleter_type,
/// decltype((std::forward<D>(ptr.get_deleter())))`: `deleter_type` must be noexcept
/// constructible from the deleter type returned by `ptr.get_deleter()`
/// - `concepts::Convertible<typename UniquePtr<U, D>::pointer, pointer>`: The pointer type
/// of `UniquePtr<U, D>` must be convertible to `pointer`
/// - `concepts::Convertible<typename UniquePtr<U, D>::deleter_type, deleter_type>`: The
/// deleter type of `UniquePtr<U, D>` must be convertible to `deleter_type`
/// @ingroup UniquePtr
template<typename U, typename D>
explicit constexpr UniquePtr(UniquePtr<U, D>&& ptr) noexcept requires concepts::
NoexceptConstructibleFrom<deleter_type,
decltype((std::forward<D>(ptr.get_deleter())))> && concepts::
Convertible<typename UniquePtr<U, D>::pointer, pointer> && concepts::
Convertible<typename UniquePtr<U, D>::deleter_type, deleter_type>
: m_ptr(ptr.release(), std::forward<D>(ptr.get_deleter())) {
}
/// @brief `UniquePtr` cannot be copied
/// @ingroup UniquePtr
UniquePtr(const UniquePtr&) = delete;
/// @brief Move Constructs a `UniquePtr` from the given one
///
/// @param ptr - The `UniquePtr` to move
///
/// # Requirements
/// - `concepts::NoexceptMoveConstructible<deleter_type>`: `deleter_type` must be noexcept
/// move constructible in order to move construct a `UniquePtr`
/// @ingroup UniquePtr
constexpr UniquePtr(
UniquePtr&& ptr) noexcept requires concepts::NoexceptMoveConstructible<deleter_type>
: m_ptr(ptr.release(), std::forward<deleter_type>(ptr.get_deleter())) {
}
/// @brief `UniquePtr` destructor
///
/// # Requirements
/// - `noexcept(std::declval<deleter_type>()(std::declval<pointer>()))`: Deleting the
/// managed pointer via the associated `deleter_type`'s call operator must be noexcept
/// @ingroup UniquePtr
constexpr ~UniquePtr() noexcept
requires(noexcept(std::declval<deleter_type>()(std::declval<pointer>()))) // NOLINT
{
reset();
}
/// @brief Releases ownership of the managed pointer and returns it
///
/// @return The managed pointer
/// @ingroup UniquePtr
[[nodiscard]] inline constexpr auto release() noexcept -> pointer {
auto* ptr = m_ptr.first();
m_ptr.first() = pointer();
return ptr;
}
/// @brief Deletes the currently managed pointer, if any, and begins managing the given one
///
/// @param ptr - The new pointer to manage with this `UniquePtr`
///
/// # Requirements
/// - `noexcept(std::declval<deleter_type>()(std::declval<pointer>()))`: Deleting the
/// managed pointer via the associated `deleter_type`'s call operator must be noexcept
inline constexpr auto reset(pointer ptr = pointer()) noexcept -> void requires(
noexcept(std::declval<deleter_type>()(std::declval<pointer>()))) // NOLINT
{
gsl::owner<pointer> tmp = m_ptr.first(); // NOLINT
m_ptr.first() = ptr;
m_ptr.second()(tmp);
}
/// @brief Deletes the currently managed pointer, if any, and begins managing the given one
///
/// @tparam U - The type of the new pointer to manage
///
/// @param ptr - The new pointer to manage with this `UniquePtr`
///
/// # Requirements
/// - `concepts::Convertible<U, pointer>`: `U` must be convertible to `pointer` in order for
/// this `UniquePtr` to manage a `U`
/// - `noexcept(std::declval<deleter_type>()(std::declval<pointer>()))`: Deleting the
/// managed pointer via the associated `deleter_type`'s call operator must be noexcept
/// @ingroup UniquePtr
template<typename U>
requires concepts::Convertible<U, pointer>
inline constexpr auto reset(U ptr) noexcept -> void requires(
noexcept(std::declval<deleter_type>()(std::declval<pointer>()))) // NOLINT
{
gsl::owner<pointer> tmp = m_ptr.first(); // NOLINT
m_ptr.first() = ptr;
m_ptr.second()(tmp);
}
/// @brief Swaps the managed pointer and deleter of this `UniquePtr` with the given one
///
/// @param ptr - The `UniquePtr` to swap with
///
/// # Requirements
/// - `std::is_nothrow_swappable_v<CompressedPair<pointer, deleter_type>>`:
/// `CompressedPair<pointer, deleter_type> must be noexcept swappable in order to
/// swap two `UniquePtr`s. (`CompressedPair` is used internally to store the managed pointer
/// and deleter, to allow for
/// [Empty Base Class Optimization](https://en.cppreference.com/w/cpp/language/ebo) )
/// @ingroup UniquePtr
inline constexpr auto swap(UniquePtr& ptr) noexcept
-> void requires concepts::NoexceptSwappable<CompressedPair<pointer, deleter_type>> {
m_ptr.swap(ptr.m_ptr);
}
/// @brief Returns the managed pointer
///
/// Returns the managed pointer. This does not release ownership of the pointer, it only
/// provides unmanaged access to it. Use of the returned pointer after the lifetime of this
/// `UniquePtr` has ended results in undefined behavior.
///
/// @return The managed pointer
/// @ingroup UniquePtr
[[nodiscard]] inline constexpr auto get() noexcept -> pointer {
return m_ptr.first();
}
/// @brief Returns the managed pointer
///
/// Returns the managed pointer. This does not release ownership of the pointer, it only
/// provides unmanaged access to it. Use of the returned pointer after the lifetime of this
/// `UniquePtr` has ended results in undefined behavior.
///
/// @return The managed pointer
/// @ingroup UniquePtr
[[nodiscard]] inline constexpr auto get() const noexcept -> pointer_to_const {
return m_ptr.first();
}
/// @brief Returns the associated deleter
///
/// @return The associated deleter
/// @ingroup UniquePtr
[[nodiscard]] inline constexpr auto get_deleter() const noexcept -> const deleter_type& {
return m_ptr.second();
}
/// @brief Returns the associated deleter
///
/// @return The associated deleter
/// @ingroup UniquePtr
[[nodiscard]] inline constexpr auto get_deleter() noexcept -> deleter_type& {
return m_ptr.second();
}
/// @brief Converts this `UniquePtr` to a `bool`
///
/// Returns `true` if the managed pointer is not null, `false` otherwise.
/// @return this, as a `bool`
/// @ingroup UniquePtr
explicit constexpr operator bool() const noexcept {
return m_ptr.first() != nullptr;
}
constexpr auto operator*() const -> typename std::add_lvalue_reference_t<T> {
return *(m_ptr.first());
}
constexpr auto operator->() const noexcept -> pointer {
return m_ptr.first();
}
inline constexpr auto operator==(const UniquePtr& ptr) const noexcept -> bool {
return m_ptr.first() == ptr.first();
}
inline constexpr auto operator==(std::nullptr_t) const noexcept -> bool {
return m_ptr.first() == nullptr;
}
auto operator=(const UniquePtr&) -> UniquePtr& = delete;
/// @brief Move-assigns this `UniquePtr` from the given one
///
/// @param ptr - The `UniquePtr` to move into this one
///
/// # Requirements
/// - `concepts::NoexceptMoveAssignable<deleter_type>`: `deleter_type` must be noexcept move
/// assignable in order to move assign a `UniquePtr`
/// - `noexcept(std::declval<deleter_type>()(std::declval<pointer>()))`: Deleting the
/// managed pointer via the associated `deleter_type`'s call operator must be noexcept
///
/// @return this
/// @ingroup UniquePtr
constexpr auto operator=(UniquePtr&& ptr) noexcept
-> UniquePtr& requires concepts::NoexceptMoveAssignable<deleter_type> &&(
noexcept(std::declval<deleter_type>()(std::declval<pointer>()))) // NOLINT
{
if(this == &ptr) {
return *this;
}
reset(ptr.release());
m_ptr.second() = std::forward<deleter_type>(ptr.get_deleter());
return *this;
}
/// @brief Move-assigns this `UniquePtr` from the given one
///
/// @tparam U - The managed type of the given `UniquePtr`
/// @tparam D - The deleter type of the given `UniquePtr`
///
/// @param ptr - The `UniquePtr<U, D>` to move into this one
///
/// # Requirements
/// - `concepts::NoexceptAssignable<deleter_type,
/// decltype(std::forward<D>(ptr.get_deleter()))>`: `deleter_type` must be assignable with
/// the deleter type returned by `ptr`'s `get_deleter()` member function
/// - `concepts::Convertible<typename UniquePtr<U, D>::pointer, pointer>`: The pointer type
/// of `ptr` must be convertible to the pointer type of `this` in order to assign from
/// it
/// - `concepts::Convertible<typename UniquePtr<U, D>::deleter_type, deleter_type>`:
/// The deleter type of `ptr` must be convertible to the pointer type of `this` in order to
/// assign from it
/// - `noexcept(std::declval<deleter_type>()(std::declval<pointer>()))`: Deleting the
/// managed pointer via the associated `deleter_type`'s call operator must be noexcept
///
/// @return this
/// @ingroup UniquePtr
template<typename U, typename D>
constexpr auto operator=(UniquePtr<U, D>&& ptr) noexcept -> UniquePtr& requires
concepts::NoexceptAssignable<deleter_type,
decltype(std::forward<D>(ptr.get_deleter()))> && concepts::
Convertible<typename UniquePtr<U, D>::pointer, pointer> && concepts::
Convertible<typename UniquePtr<U, D>::deleter_type, deleter_type> &&(
noexcept(std::declval<deleter_type>()(std::declval<pointer>()))) // NOLINT
{
reset(ptr.release());
m_ptr.second() = std::forward<D>(ptr.get_deleter());
return *this;
}
/// @brief Assigns this `UniquePtr` with `nullptr`
///
/// Calls the deleter on the managed pointer and replaces it with `nullptr`
///
/// # Requirements
/// - `noexcept(std::declval<deleter_type>()(std::declval<pointer>()))`: Deleting the
/// managed pointer via the associated `deleter_type`'s call operator must be noexcept
///
/// @return this
/// @ingroup UniquePtr
constexpr auto operator=(std::nullptr_t) noexcept -> UniquePtr& requires(
noexcept(std::declval<deleter_type>()(std::declval<pointer>()))) // NOLINT
{
reset();
return *this;
}
/// @brief Assigns this `UniquePtr` with `ptr`
///
/// Calls the deleter on the managed pointer and replaces it with `ptr`
///
/// # Requirements
/// - `noexcept(std::declval<deleter_type>()(std::declval<pointer>()))`: Deleting the
/// managed pointer via the associated `deleter_type`'s call operator must be noexcept
///
/// @return this
/// @ingroup UniquePtr
constexpr auto operator=(pointer ptr) noexcept -> UniquePtr& requires(
noexcept(std::declval<deleter_type>()(std::declval<pointer>()))) // NOLINT
{
reset(ptr);
return *this;
}
// clang-format off
private:
template<typename T_, typename Deleter_>
using CompressedPair = CompressedPair<T_, Deleter_>;
template<typename T_>
using DefaultInitTag = DefaultInitTag<T_>;
CompressedPair<pointer, deleter_type> m_ptr;
// clang-format on
};
template<typename T, typename Deleter>
requires concepts::NotRValueReference<Deleter>
class HYPERION_TRIVIAL_ABI UniquePtr<T[], Deleter> { // NOLINT
public:
using element_type = T;
using deleter_type = Deleter;
using pointer = std::add_pointer_t<element_type>;
using pointer_to_const = std::add_pointer_t<std::add_const_t<element_type>>;
constexpr UniquePtr() noexcept requires concepts::NoexceptDefaultConstructible<
deleter_type> && concepts::NotPointer<deleter_type>
: m_ptr(pointer(), DefaultInitTag<deleter_type>()) {
}
constexpr UniquePtr(std::nullptr_t ptr) noexcept // NOLINT
requires concepts::NoexceptDefaultConstructible<deleter_type> && concepts::NotPointer<
deleter_type> : m_ptr(ptr, DefaultInitTag<deleter_type>()) {
}
explicit constexpr UniquePtr(pointer ptr) noexcept requires concepts::
NoexceptDefaultConstructible<deleter_type> && concepts::NotPointer<deleter_type>
: m_ptr(ptr, DefaultInitTag<deleter_type>()) {
}
template<typename U>
requires concepts::Convertible<U, pointer> && concepts::NoexceptDefaultConstructible<
deleter_type> && concepts::NotPointer<deleter_type> && concepts::NotSame<U, pointer>
explicit constexpr UniquePtr(U ptr) noexcept : m_ptr(ptr, DefaultInitTag<deleter_type>()) {
}
constexpr UniquePtr(pointer ptr, const Deleter& deleter) noexcept requires
concepts::NoexceptCopyConstructible<Deleter> : m_ptr(ptr, deleter) {
}
constexpr UniquePtr(pointer ptr, Deleter&& deleter) noexcept requires
concepts::NoexceptMoveConstructible<Deleter> && concepts::NotRValueReference<Deleter>
: m_ptr(ptr, std::move(deleter)) {
}
template<typename U>
requires concepts::Convertible<U, pointer> && concepts::NotSame<U, pointer> && concepts::
NoexceptCopyConstructible<Deleter>
constexpr UniquePtr(U ptr, const Deleter& deleter) noexcept : m_ptr(ptr, deleter) {
}
template<typename U>
requires concepts::Convertible<U, pointer> && concepts::NotSame<U, pointer> && concepts::
NoexceptMoveConstructible<Deleter> && concepts::NotRValueReference<Deleter>
constexpr UniquePtr(U ptr, Deleter&& deleter) noexcept : m_ptr(ptr, std::move(deleter)) {
}
constexpr UniquePtr(std::nullptr_t ptr, const Deleter& deleter) noexcept requires
concepts::NoexceptCopyConstructible<Deleter> : m_ptr(ptr, deleter) {
}
constexpr UniquePtr(std::nullptr_t ptr, Deleter&& deleter) noexcept requires
concepts::NoexceptMoveConstructible<Deleter> && concepts::NotRValueReference<Deleter>
: m_ptr(ptr, std::move(deleter)) {
}
// clang-format off
template<typename U, typename D>
requires std::is_array_v<U>
explicit constexpr UniquePtr(UniquePtr<U, D>&& ptr)
noexcept(concepts::NoexceptConstructibleFrom<deleter_type,
decltype((std::forward<D>(ptr.get_deleter())))>)
requires concepts::Convertible<typename UniquePtr<U, D>::element_type(*)[], // NOLINT
element_type (*)[] > // NOLINT
&& concepts::Convertible<typename UniquePtr<U, D>::deleter_type, deleter_type>
: m_ptr(ptr.release(), std::forward<D>(ptr.get_deleter())) {
}
// clang-format on
UniquePtr(const UniquePtr&) = delete;
constexpr UniquePtr(
UniquePtr&& ptr) noexcept requires concepts::NoexceptMoveConstructible<deleter_type>
: m_ptr(ptr.release(), std::forward<deleter_type>(ptr.get_deleter())) {
}
constexpr ~UniquePtr() noexcept
requires(noexcept(std::declval<deleter_type>()(std::declval<pointer>()))) // NOLINT
{
reset();
}
[[nodiscard]] inline constexpr auto release() noexcept -> pointer {
auto* ptr = m_ptr.first();
m_ptr.first() = pointer();
return ptr;
}
inline constexpr auto reset(pointer ptr = pointer()) noexcept -> void requires(
noexcept(std::declval<deleter_type>()(std::declval<pointer>()))) // NOLINT
{
gsl::owner<pointer> tmp = m_ptr.first(); // NOLINT
m_ptr.first() = ptr;
m_ptr.second()(tmp);
}
template<typename U>
requires concepts::Convertible<U, pointer>
inline constexpr auto reset(U ptr) noexcept -> void requires(
noexcept(std::declval<deleter_type>()(std::declval<pointer>()))) // NOLINT
{
gsl::owner<pointer> tmp = m_ptr.first(); // NOLINT
m_ptr.first() = ptr;
m_ptr.second()(tmp);
}
inline constexpr auto swap(UniquePtr& ptr) noexcept
-> void requires concepts::NoexceptSwappable<CompressedPair<pointer, deleter_type>> {
m_ptr.swap(ptr.m_ptr);
}
[[nodiscard]] inline constexpr auto get() noexcept -> pointer {
return m_ptr.first();
}
[[nodiscard]] inline constexpr auto get() const noexcept -> pointer_to_const {
return m_ptr.first();
}
[[nodiscard]] inline constexpr auto get_deleter() const noexcept -> const deleter_type& {
return m_ptr.second();
}
[[nodiscard]] inline constexpr auto get_deleter() noexcept -> deleter_type& {
return m_ptr.second();
}
explicit constexpr operator bool() const noexcept {
return m_ptr.first() != nullptr;
}
inline constexpr auto operator==(const UniquePtr& ptr) const noexcept -> bool {
return m_ptr.first() == ptr.first();
}
inline constexpr auto operator==(std::nullptr_t) const noexcept -> bool {
return m_ptr.first() == nullptr;
}
// constexpr inline auto operator[](concepts::Integral auto i) const
// noexcept -> std::add_const_t<std::add_lvalue_reference_t<element_type>> {
// return m_ptr.first()[i];
// }
inline constexpr auto operator[](concepts::Integral auto index) const noexcept
-> std::add_lvalue_reference_t<element_type> {
return m_ptr.first()[index];
}
auto operator=(const UniquePtr&) -> UniquePtr& = delete;
constexpr auto operator=(UniquePtr&& ptr) noexcept
-> UniquePtr& requires concepts::NoexceptMoveAssignable<deleter_type> &&(
noexcept(std::declval<deleter_type>()(std::declval<pointer>()))) // NOLINT
{
if(this == &ptr) {
return *this;
}
reset(ptr.release());
m_ptr.second() = std::forward<deleter_type>(ptr.get_deleter());
return *this;
}
// clang-format off
template<typename U, typename D>
requires std::is_array_v<U>
constexpr auto operator=(UniquePtr<U, D>&& ptr) noexcept -> UniquePtr&
requires concepts::NoexceptAssignable<deleter_type,
decltype(std::forward<D>(ptr.get_deleter()))>
&& concepts::Convertible<typename UniquePtr<U, D>::element_type(*) [], // NOLINT
element_type(*)[]> // NOLINT
&& concepts::Convertible<typename UniquePtr<U, D>::deleter_type, deleter_type>
&& (noexcept(std::declval<deleter_type>()(std::declval<pointer>()))) // NOLINT
{
reset(ptr.release());
m_ptr.second() = std::forward<D>(ptr.get_deleter());
return *this;
}
// clang-format on
constexpr auto operator=(std::nullptr_t) noexcept -> UniquePtr& requires(
noexcept(std::declval<deleter_type>()(std::declval<pointer>()))) // NOLINT
{
reset();
return *this;
}
constexpr auto operator=(pointer ptr) noexcept -> UniquePtr& requires(
noexcept(std::declval<deleter_type>()(std::declval<pointer>()))) // NOLINT
{
reset(ptr);
return *this;
}
// clang-format off
private:
template<typename T_, typename Deleter_>
using CompressedPair = CompressedPair<T_, Deleter_>;
template<typename T_>
using DefaultInitTag = DefaultInitTag<T_>;
CompressedPair<pointer, deleter_type> m_ptr;
// clang-format on
};
template<typename T, typename Deleter>
UniquePtr(T*, Deleter) -> UniquePtr<T, Deleter>;
/// @brief Swaps the managed pointer and deleter of the two `UniquePtr`s
///
/// @tparam T - The type held by the `UniquePtr`s
/// @tparam Deleter - The deleter type used by the `UniquePtr`s
///
/// @param first - The `UniquePtr` to swap to
/// @param second - The `UniquePtr` to swap from
/// @ingroup UniquePtr
template<typename T, typename Deleter>
requires concepts::Swappable<Deleter>
inline constexpr auto
swap(UniquePtr<T, Deleter>& first, UniquePtr<T, Deleter>& second) noexcept -> void {
first.swap(second);
}
// clang-format off
IGNORE_UNUSED_TEMPLATES_START
/// @brief Constructs a `UniquePtr<T, Deleter>` from the given arguments
///
/// Constructs a `UniquePtr<T, Deleter>` from the given arguments, passing them directly
/// to `T`'s constructor
///
/// @tparam T - The type to hold in the `UniquePtr`
/// @tparam Deleter - The deleter type to free the resources associated with `T`
/// @tparam Args - The types of the arguments to pass to `T`'s constructor
///
/// @param args - The arguments to pass to `T`'s constructor
///
/// # Requirements
/// - `concepts::ConstructibleFrom<T, Args...>`: `T` must be constructible from the given
/// arguments in order to make a `UniquePtr` from them
/// - `!std::is_array_v<T>`: Cannot make a `UniquePtr` holding an array type from a set of
/// constructor arguments. Use the overload for arrays to make a `UniquePtr<T[]>`.
///
/// @return a `UniquePtr<T, Deleter>` with the `T` constructed from the given arguments
/// @ingroup UniquePtr
template<typename T, typename Deleter = DefaultDeleter<T>, typename... Args>
requires concepts::ConstructibleFrom<T, Args...> && (!std::is_unbounded_array_v<T>)
inline static constexpr auto make_unique(Args&&... args)
noexcept(concepts::NoexceptConstructibleFrom<T, Args...>)
-> UniquePtr<T, Deleter>
{
// NOLINTNEXTLINE(modernize-use-auto,hicpp-use-auto,bugprone-unhandled-exception-at-new)
gsl::owner<T*> ptr = new T(std::forward<Args>(args)...);
// NOLINTNEXTLINE(clang-analyzer-cplusplus.NewDeleteLeaks)
return UniquePtr<T, Deleter>(ptr);
}
// clang-format on
/// @brief Constructs a `UniquePtr` holding array type `T` of size `N`
///
/// Constructs a `UniquePtr<T, Deleter>`, where `T` is an unbounded array type with initial
/// size of `N`.
///
/// @tparam T - The array type to hold in the `UniquePtr`
/// @tparam Deleter - The deleter type to free the resources associated with `T`
/// @tparam ElementType - The element type of the array
///
/// @param N - The initial size of the array managed by the `UniquePtr`
///
/// # Requirements
/// - `std::is_unbounded_array_v<T>`: `T` must be an unbounded array type to make a `UniquePtr`
/// managing an array.
///
/// @return a `UniquePtr<T, Deleter>` managing an array of `N` `ElementType`s
/// @note The array managed by the returned `UniquePtr` will be uninitialized, and thus each
/// element must be appropriately initialized before use. Otherwise, the result is undefined
/// behavior.
/// @ingroup UniquePtr
template<typename T,
typename Deleter = DefaultDeleter<T>,
typename ElementType = std::remove_extent_t<T>> // NOLINT
requires std::is_unbounded_array_v<T>
inline static constexpr auto make_unique(usize N) noexcept -> UniquePtr<T, Deleter> {
// NOLINTNEXTLINE(modernize-use-auto,hicpp-use-auto,bugprone-unhandled-exception-at-new)
gsl::owner<ElementType*> ptr = new ElementType[N];
// NOLINTNEXTLINE(clang-analyzer-cplusplus.NewDeleteLeaks)
return UniquePtr<T, Deleter>(ptr);
}
IGNORE_UNUSED_TEMPLATES_STOP
IGNORE_PADDING_START
/// @brief An allocator-aware deleter type for Hyperion smart pointers
///
/// `AllocatorAwareDeleter` is useful for using smart pointers in situations that require custom
/// allocation strategies. It allows use of smart pointers in an allocator-aware fashion.
///
/// @tparam T - The type to manage deletion for
/// @tparam Allocator - The allocator type allocation was performed with
/// @tparam ElementType - The element type of the managed deletion, in the case that `T` is an
/// array
///
/// # Requirements
/// - `concepts::Allocatable<ElementType, Allocator>`: `AllocatorAwareDeleter` can't be
/// instantiated for an `ElementType`-`Allocator` pair where the element type `ElementType`
/// isn't allocatable by the associated allocator type, `Allocator`
/// @note In the case that `T` is an array type, `AllocatorAwareDeleter` requires that the
/// managed array is fully-initialized and the same size as when the `AllocatorAwareDeleter`
/// was constructed with it (by a call to one of the factory functions, `allocate_unique`, or
/// `allocate_shared`) when its call operator is used to free the resources associated with the
/// array.
/// @note If `T` is an array type and the array is resized, the deleter associated with it in
/// the owning smart pointer must be set to a new one to match the changed state.
/// @note If `T` is an array type and the members of the array are not all initialized when the
/// call operator of this deleter is used to free the resources associated with it, the result
/// is undefined behavior.
/// @ingroup memory
template<typename T,
typename Allocator = std::allocator<T>,
typename ElementType = std::remove_cv_t<std::remove_all_extents_t<T>>>
requires concepts::Allocatable<ElementType, Allocator>
class AllocatorAwareDeleter {
public:
/// @brief The rebound allocator type for this deleter
/// @ingroup memory
using Alloc = typename std::allocator_traits<Allocator>::template rebind_alloc<ElementType>;
/// @brief The `std::allocator_traits` type for this deleter
/// @ingroup memory
using Traits = std::allocator_traits<Alloc>;
/// @brief The pointer type for the associated allocator traits for this deleter
/// @ingroup memory
using pointer = typename Traits::pointer;
/// @brief Default-Constructs an `AllocatorAwareDeleter`
///
/// # Requirements
/// - `concepts::NoexceptDefaultConstructible<Alloc>`: The associated allocator type must be
/// noexcept default constructible in order to construct an `AllocatorAwareDeleter` with one
/// @ingroup memory
constexpr AllocatorAwareDeleter() noexcept requires
concepts::NoexceptDefaultConstructible<Alloc> : m_allocator() {
}
/// @brief Constructs an `AllocatorAwareDeleter` from the given allocator
///
/// @param alloc - The allocator to construct the allocator associated with this from
///
/// # Requirements
/// - `concepts::NoexceptConstructibleFrom<Alloc, decltype(alloc)>`: The associated
/// allocator type must be noexcept constructible from the given allocator in order to
/// construct an `AllocatorAwareDeleter` from it
/// @ingroup memory
explicit constexpr AllocatorAwareDeleter(const Allocator& alloc) noexcept requires
concepts::NoexceptConstructibleFrom<Alloc, decltype(alloc)> : m_allocator(alloc) {
}
/// @brief Copy-Constructs an `AllocatorAwareDeleter` from the given one
///
/// # Requirements
/// - `concepts::NoexceptCopyConstructible<Alloc>`: The associated allocator type must be
/// noexcept copy constructible in order to copy construct an `AllocatorAwareDeleter`
/// @ingroup memory
constexpr AllocatorAwareDeleter(const AllocatorAwareDeleter&) noexcept requires
concepts::NoexceptCopyConstructible<Alloc>
= default;
/// @brief Move-Constructs an `AllocatorAwareDeleter` from the given one
///
/// # Requirements
/// - `concepts::NoexceptMoveConstructible<Alloc>`: The associated allocator type must be
/// noexcept move constructible in order to copy construct an `AllocatorAwareDeleter`
/// @ingroup memory
constexpr AllocatorAwareDeleter(
AllocatorAwareDeleter&&) noexcept requires concepts::NoexceptMoveConstructible<Alloc>
= default;
/// @brief Destructs this `AllocatorAwareDeleter`
/// @ingroup memory
constexpr ~AllocatorAwareDeleter() noexcept = default;
/// @brief Frees the resources associated with the pointed-to object
///
/// @param p - Pointer to the object to free associated resources of
/// @ingroup memory
inline constexpr auto operator()(pointer p) const noexcept {
Alloc allocator = m_allocator;
Traits::destroy(allocator, std::addressof(*p));
Traits::deallocate(allocator, p, 1);
}
/// @brief Copy-Assigns this `AllocatorAwareDeleter` from the given one
///
/// # Requirements
/// - `concepts::NoexceptCopyAssignable<Alloc>`: The associated allocator type must be
/// noexcept copy assignable in order to copy assign this `AllocatorAwareDeleter`
/// @ingroup memory
constexpr auto operator=(const AllocatorAwareDeleter&) noexcept
-> AllocatorAwareDeleter& requires concepts::NoexceptCopyAssignable<Alloc>
= default;
/// @brief Move-Assigns this `AllocatorAwareDeleter` from the given one
///
/// # Requirements
/// - `concepts::NoexceptMoveAssignable<Alloc>`: The associated allocator type must be
/// noexcept move assignable in order to move assign this `AllocatorAwareDeleter`
/// @ingroup memory
constexpr auto operator=(AllocatorAwareDeleter&&) noexcept
-> AllocatorAwareDeleter& requires concepts::NoexceptMoveAssignable<Alloc>
= default;
private:
Alloc m_allocator;
};
template<typename T, typename Allocator, typename ElementType>
requires concepts::Allocatable<ElementType, Allocator>
class AllocatorAwareDeleter<T[], Allocator, ElementType> { // NOLINT
public:
using Alloc = typename std::allocator_traits<Allocator>::template rebind_alloc<ElementType>;
using Traits = std::allocator_traits<Alloc>;
using pointer = typename Traits::pointer;
constexpr AllocatorAwareDeleter() noexcept requires
concepts::NoexceptDefaultConstructible<Alloc> : m_allocator() {
}
explicit constexpr AllocatorAwareDeleter(const Allocator& alloc,
usize num_elements) noexcept requires
concepts::NoexceptConstructibleFrom<Alloc, decltype(alloc)>
: m_allocator(alloc),
m_num_elements(num_elements) {
}
constexpr AllocatorAwareDeleter(const AllocatorAwareDeleter&) noexcept requires
concepts::NoexceptCopyConstructible<Alloc>
= default;
constexpr AllocatorAwareDeleter(
AllocatorAwareDeleter&&) noexcept requires concepts::NoexceptMoveConstructible<Alloc>
= default;
constexpr ~AllocatorAwareDeleter() noexcept = default;
inline constexpr auto operator()(pointer p) const noexcept {
Alloc allocator = m_allocator;
auto i = m_num_elements >= 1_usize ? m_num_elements - 1_usize : 0_usize;
// we need to use do-while to ensure we destroy the 0th element
// in a 1 element array
do {
Traits::destroy(allocator, std::addressof(*p) + i); // NOLINT
--i;
} while(i != 0_usize);
Traits::deallocate(allocator, p, m_num_elements);
}
constexpr auto operator=(const AllocatorAwareDeleter&) noexcept
-> AllocatorAwareDeleter& requires concepts::NoexceptCopyAssignable<Alloc>
= default;
constexpr auto operator=(AllocatorAwareDeleter&&) noexcept
-> AllocatorAwareDeleter& requires concepts::NoexceptMoveAssignable<Alloc>
= default;
private:
Alloc m_allocator;
usize m_num_elements = 1_usize;
};
IGNORE_PADDING_STOP
/// @brief Constructs an allocator-aware `UniquePtr`
///
/// Constructs a `UniquePtr<T, AllocatorAwareDeleter<T, Alloc>>`. The managed `T` will be
/// constructed from the given arguments, `args`, passing them directly to `T`'s constructor.
/// Allocation of the managed `T` will be performed by the given allocator.
///
/// @tparam T - The type to manage in the `UniquePtr`
/// @tparam Allocator - The type of the allocator to use for allocation and deletion of the `T`
/// @tparam ElementType - The element type of the array, in the case that `T` is an unbounded
/// array type
/// @tparam Alloc - The allocator type `Allocator` rebound to the element type, `ElementType`
///
/// @param alloc - The allocator to perform allocation and deallocation with
/// @param args - The arguments to pass to `T`'s constructor
///
/// # Requirements
/// - `concepts::NoexceptConstructibleFrom<ElementType, Args...>`: `ElementType` must be
/// noexcept constructible from `args` in order to make a `UniquePtr` from them
/// - `concepts::Allocatable<ElementType, Alloc>`: `AllocatorAwareDeleter` can't be
/// instantiated for an `ElementType`-`Alloc` pair where the element type `ElementType`
/// isn't allocatable by the associated allocator type, `Alloc`
/// - `!std::is_array_v<T>`: Cannot make a `UniquePtr` holding an array type from a set of
/// constructor arguments. Use the overload for arrays to make a `UniquePtr<T[]>`.
/// - `concepts::NoexceptConstructibleFrom<Alloc, decltype(alloc)>`: The associated allocator
/// type, `Alloc`, must be noexcept constructible from the given allocator in order to create
/// a `UniquePtr` using it
/// @ingroup UniquePtr
template<typename T,
typename Allocator = std::allocator<T>,
typename ElementType = std::remove_cv_t<std::remove_all_extents_t<T>>,
typename Alloc =
typename std::allocator_traits<Allocator>::template rebind_alloc<ElementType>,
typename... Args>
requires concepts::NoexceptConstructibleFrom<ElementType, Args...> && concepts::
Allocatable<ElementType, Alloc> &&(!std::is_unbounded_array_v<T>)
[[nodiscard]] inline constexpr auto allocate_unique(const Allocator& alloc,
Args&&... args) noexcept
-> UniquePtr<T, AllocatorAwareDeleter<T, Alloc>>
requires concepts::NoexceptConstructibleFrom<Alloc, decltype(alloc)> {
using Traits = std::allocator_traits<Alloc>;
using Deleter = AllocatorAwareDeleter<T, Alloc>;
Alloc allocator(alloc);
auto* p = Traits::allocate(allocator, 1);
Traits::construct(allocator, std::addressof(*p), std::forward<Args>(args)...);
// NOLINTNEXTLINE(clang-analyzer-cplusplus.NewDeleteLeaks)
return UniquePtr<T, Deleter>(p, Deleter(allocator));
}
/// @brief Constructs an allocator-aware `UniquePtr`
///
/// Constructs a `UniquePtr<T, AllocatorAwareDeleter<T, Alloc>>`, where `T` is an unbounded
/// array type. The managed array will have its elements default constructed in place.
/// Allocation of the managed array will be performed by the given allocator.
///
/// @tparam T - The type to manage in the `UniquePtr`
/// @tparam Allocator - The type of the allocator to use for allocation and deletion of the `T`
/// @tparam ElementType - The element type of the array, in the case that `T` is an unbounded
/// array type
/// @tparam Alloc - The allocator type `Allocator` rebound to the element type, `ElementType`
///
/// @param alloc - The allocator to perform allocation and deallocation with
/// @param N - The number of elements to allocate in the array
///
/// # Requirements
/// - `concepts::NoexceptDefaultConstructible<ElementType>`: `ElementType` must be
/// noexcept default-constructible in order to make a `UniquePtr` managing an array of them
/// - `concepts::Allocatable<ElementType, Alloc>`: `AllocatorAwareDeleter` can't be
/// instantiated for an `ElementType`-`Alloc` pair where the element type `ElementType`
/// isn't allocatable by the associated allocator type, `Alloc`
/// - `std::is_unbounded_array_v<T>`: `T` must be an unbounded array type to make a `UniquePtr`
/// managing an array.
/// - `concepts::NoexceptConstructibleFrom<Alloc, decltype(alloc)>`: The associated allocator
/// type, `Alloc`, must be noexcept constructible from the given allocator in order to create
/// a `UniquePtr` using it
/// @ingroup UniquePtr
template<typename T,
typename Allocator = std::allocator<T>,
typename ElementType = std::remove_cv_t<std::remove_all_extents_t<T>>,
typename Alloc =
typename std::allocator_traits<Allocator>::template rebind_alloc<ElementType>>
requires concepts::NoexceptDefaultConstructible<
ElementType> && concepts::Allocatable<ElementType, Alloc> && std::is_unbounded_array_v<T>
[[nodiscard]] inline constexpr auto allocate_unique(const Allocator& alloc, usize N) noexcept
-> UniquePtr<T, AllocatorAwareDeleter<T, Alloc>>
requires concepts::NoexceptConstructibleFrom<Alloc, decltype(alloc)> {
using Traits = std::allocator_traits<Alloc>;
using Deleter = AllocatorAwareDeleter<ElementType[], Alloc>; // NOLINT (c arrays)
Alloc allocator(alloc);
auto* p = Traits::allocate(allocator, N);
// we need to use do-while to make sure we construct the 0th element in a one element array
auto i = 0_usize;
do {
Traits::construct(allocator, std::addressof(*p) + i); // NOLINT
++i;
} while(i < N);
// NOLINTNEXTLINE(clang-analyzer-cplusplus.NewDeleteLeaks)
return UniquePtr<ElementType[], Deleter>(p, Deleter(allocator, N)); // NOLINT ( c arrays)
}
/// @brief Constructs an allocator-aware `UniquePtr`
///
/// Constructs a `UniquePtr<T, AllocatorAwareDeleter<T, Alloc>>`, where `T` is an unbounded
/// array type. The managed array will have its elements default constructed in place.
/// Allocation of the managed array will be performed by the given allocator.
///
/// @tparam T - The type to manage in the `UniquePtr`
/// @tparam Allocator - The type of the allocator to use for allocation and deletion of the `T`
/// @tparam ElementType - The element type of the array, in the case that `T` is an unbounded
/// array type
/// @tparam Alloc - The allocator type `Allocator` rebound to the element type, `ElementType`
/// @tparam Args - The types of the arguments to use to default-construct the elements of the
/// array
///
/// @param alloc - The allocator to perform allocation and deallocation with
/// @param N - The number of elements to allocate in the array
///
/// # Requirements
/// - `concepts::NoexceptDefaultConstructible<ElementType>`: `ElementType` must be
/// noexcept default-constructible in order to make a `UniquePtr` managing an array of them
/// - `concepts::Allocatable<ElementType, Alloc>`: `AllocatorAwareDeleter` can't be
/// instantiated for an `ElementType`-`Alloc` pair where the element type `ElementType`
/// isn't allocatable by the associated allocator type, `Alloc`
/// - `std::is_unbounded_array_v<T>`: `T` must be an unbounded array type to make a `UniquePtr`
/// managing an array.
/// - `concepts::NoexceptConstructibleFrom<Alloc, decltype(alloc)>`: The associated allocator
/// type, `Alloc`, must be noexcept constructible from the given allocator in order to create
/// a `UniquePtr` using it
/// @ingroup UniquePtr
template<typename T,
typename Allocator = std::allocator<T>,
typename ElementType = std::remove_cv_t<std::remove_all_extents_t<T>>,
typename Alloc =
typename std::allocator_traits<Allocator>::template rebind_alloc<ElementType>,
typename... Args>
requires concepts::NoexceptConstructibleFrom<ElementType, Args...> && mpl::for_all_types_v<
std::is_nothrow_copy_constructible,
std::true_type,
mpl::list<Args...>> && concepts::Allocatable<ElementType,
Alloc> && std::is_unbounded_array_v<T>
[[nodiscard]] inline constexpr auto
allocate_unique(const Allocator& alloc, usize N, Args&&... args) noexcept
-> UniquePtr<T, AllocatorAwareDeleter<T, Alloc>>
requires concepts::NoexceptConstructibleFrom<Alloc, decltype(alloc)> {
using Traits = std::allocator_traits<Alloc>;
using Deleter = AllocatorAwareDeleter<ElementType[], Alloc>; // NOLINT (c arrays)
Alloc allocator(alloc);
auto* p = Traits::allocate(allocator, N);
auto tuple = std::make_tuple(std::forward<Args>(args)...);
// we need to use do-while to make sure we construct the 0th element in a one element array
auto i = 0_usize;
do {
auto t = std::tuple(tuple);
Traits::construct(allocator,
std::addressof(*p) + i,
std::make_from_tuple<ElementType>(std::move(t))); // NOLINT
++i;
} while(i < N);
return UniquePtr<ElementType[], Deleter>(p, Deleter(allocator, N)); // NOLINT (c arrays)
}
#if HYPERION_DEFINE_TESTS
// NOLINTNEXTLINE(modernize-use-trailing-return-type)
TEST_SUITE("UniquePtr") {
TEST_CASE("Constructor") {
auto ptr1 = UniquePtr<i32>();
// NOLINTNEXTLINE
auto ptr2 = UniquePtr<i32>(new i32(3_i32));
auto ptr3 = hyperion::make_unique<i32>(2_i32);
CHECK_EQ(ptr1, nullptr);
CHECK_NE(ptr2, nullptr);
CHECK_NE(ptr3, nullptr);
CHECK_EQ(*ptr2, 3_i32);
CHECK_EQ(*ptr3, 2_i32);
SUBCASE("move") {
auto ptr4 = std::move(ptr3);
// NOLINTNEXTLINE(bugprone-use-after-move,hicpp-invalid-access-moved)
CHECK_EQ(ptr3, nullptr);
CHECK_NE(ptr4, nullptr);
CHECK_EQ(*ptr4, 2_i32);
}
SUBCASE("accessors_and_modifiers") {
CHECK(ptr3);
CHECK(static_cast<bool>(ptr3));
CHECK_NE(ptr3.get(), nullptr);
CHECK_EQ(*(ptr3.get()), 2_i32);
auto* ptr4 = ptr3.release();
CHECK_EQ(ptr3, nullptr);
CHECK_NE(ptr4, nullptr);
CHECK_EQ(*ptr4, 2_i32);
*ptr4 = 4_i32;
ptr3.reset(ptr4);
CHECK_NE(ptr3, nullptr);
CHECK(ptr3);
CHECK_EQ(*ptr3, 4_i32);
CHECK_EQ(*(ptr3.get()), 4_i32);
}
}
}
#endif // HYPERION_DEFINE_TESTS
} // namespace hyperion
| {
"alphanum_fraction": 0.7077128746,
"avg_line_length": 42.541864139,
"ext": "h",
"hexsha": "48789ec95ea449c192aada384a86c91d318179b9",
"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": "3873a116e2ea76fc74c9c056925f3740eee6dcd8",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "braxtons12/Hyperion-Utils",
"max_forks_repo_path": "include/Hyperion/memory/UniquePtr.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "3873a116e2ea76fc74c9c056925f3740eee6dcd8",
"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-Utils",
"max_issues_repo_path": "include/Hyperion/memory/UniquePtr.h",
"max_line_length": 98,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "3873a116e2ea76fc74c9c056925f3740eee6dcd8",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "braxtons12/Hyperion-Utils",
"max_stars_repo_path": "include/Hyperion/memory/UniquePtr.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 14724,
"size": 53858
} |
#pragma once
#include <cassert>
#include <functional>
#include <map>
#include <type_traits>
#include <vector>
#include <gsl/assert>
namespace xmol::utils {
class DeadObserverAccessError : public std::runtime_error {
public:
using std::runtime_error::runtime_error;
};
template <typename Observer>
class DeadObserverAccessErrorT : public DeadObserverAccessError { /// todo: parametrize on error message instead
public:
using DeadObserverAccessError::DeadObserverAccessError;
};
enum class ObserverState { ANY, ACTIVE, INVALID };
/// @brief Implements base primitives for observable entity
template <typename Observer> class Observable {
static_assert(!std::is_reference<Observer>::value);
static_assert(!std::is_pointer<Observer>::value);
public:
Observable() = default;
Observable(Observable&& rhs) noexcept = default;
Observable(const Observable& rhs) = default;
Observable& operator=(Observable&& rhs) noexcept = default;
Observable& operator=(const Observable& rhs) = default;
protected:
template <ObserverState apply_to = ObserverState::ANY, typename... Args, typename Func = void (Observer::*)(Args...)>
void notify(Func func, Args&&... args) const {
static_assert(apply_to != ObserverState::INVALID);
for (auto& [observer, state] : observers) {
if (state == ObserverState::ACTIVE) {
std::invoke(func, observer, std::forward<Args>(args)...);
} else {
if (GSL_UNLIKELY(apply_to == ObserverState::ANY)) {
throw DeadObserverAccessErrorT<Observer>("");
}
}
}
}
void add_observer(Observer& ptr) const { observers.emplace(&ptr, ObserverState::ACTIVE); }
void remove_observer(Observer& ptr) const {
auto count = observers.erase(&ptr);
static_cast<void>(count);
assert(count == 1);
}
void clear_observers() const { observers.clear(); }
/// @brief marks observer as invalid
/// next broadcast notify would fire an exception
void invalidate_observer(Observer& ptr) const {
auto it = observers.find(&ptr);
assert(it != observers.end());
it->second = ObserverState::INVALID;
}
void move_observer(Observer& from, Observer& to) const {
remove_observer(from);
add_observer(to);
}
public:
void on_move(Observer& from, Observer& to) {
remove_observer(from);
add_observer(to);
}
void on_delete(Observer& o) { remove_observer(o); }
void on_copy(Observer& o) { add_observer(o); }
protected:
mutable std::map<Observer*, ObserverState> observers;
};
} // namespace xmol
| {
"alphanum_fraction": 0.7,
"avg_line_length": 27.8021978022,
"ext": "h",
"hexsha": "01508b77aa2c6cd9517b3a47239f80f66f125a1d",
"lang": "C",
"max_forks_count": 6,
"max_forks_repo_forks_event_max_datetime": "2022-03-12T11:05:54.000Z",
"max_forks_repo_forks_event_min_datetime": "2018-06-04T09:16:26.000Z",
"max_forks_repo_head_hexsha": "9395ba1b1ddc957e0b33dc6decccdb711e720764",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "sizmailov/pyxmolpp2",
"max_forks_repo_path": "include/xmol/utils/Observable.h",
"max_issues_count": 84,
"max_issues_repo_head_hexsha": "9395ba1b1ddc957e0b33dc6decccdb711e720764",
"max_issues_repo_issues_event_max_datetime": "2020-06-17T15:03:37.000Z",
"max_issues_repo_issues_event_min_datetime": "2018-04-22T12:29:31.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "sizmailov/pyxmolpp2",
"max_issues_repo_path": "include/xmol/utils/Observable.h",
"max_line_length": 119,
"max_stars_count": 4,
"max_stars_repo_head_hexsha": "9395ba1b1ddc957e0b33dc6decccdb711e720764",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "sizmailov/pyxmolpp2",
"max_stars_repo_path": "include/xmol/utils/Observable.h",
"max_stars_repo_stars_event_max_datetime": "2022-01-15T23:00:30.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-06-24T11:07:57.000Z",
"num_tokens": 586,
"size": 2530
} |
/*
Copyright [2017-2020] [IBM Corporation]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#ifndef __FABRIC_CONNECTION_BASE_H__
#define __FABRIC_CONNECTION_BASE_H__
#include "mcas_config.h"
#include "buffer_manager.h" /* Buffer_manager */
#include <api/fabric_itf.h> /* IFabric_memory_region, IFabric_server */
#include <gsl/pointers>
#include <algorithm>
#include <list>
#include <queue>
namespace mcas
{
struct open_connection_construct_key;
struct open_connection
{
private:
gsl::not_null<component::IFabric_server_factory *> _factory;
gsl::not_null<component::IFabric_server *> _transport;
public:
open_connection(
gsl::not_null<component::IFabric_server_factory *> factory_
, gsl::not_null<component::IFabric_server *> transport_
, const open_connection_construct_key &
)
: _factory(factory_)
, _transport(transport_)
{}
open_connection(const open_connection &) = delete;
open_connection &operator=(const open_connection &) = delete;
auto transport() const { return _transport; }
~open_connection()
{
/* close connection */
_factory->close_connection(_transport);
}
};
class Fabric_connection_base : protected common::log_source {
public:
friend class Connection;
friend class Shard;
using memory_region_t = component::IFabric_memory_region *;
protected:
using buffer_t = Buffer_manager<component::IFabric_memory_control>::buffer_internal;
using pool_t = component::IKVStore::pool_t;
enum class action_type {
ACTION_NONE = 0, /* unused */
ACTION_RELEASE_VALUE_LOCK_SHARED,
#if 0
ACTION_RELEASE_VALUE_LOCK_EXCLUSIVE, /* unused */
ACTION_POOL_DELETE, /* unused */
#endif
};
/* deferred actions */
struct action_t {
action_type op;
void *parm;
};
enum class Completion_state {
COMPLETIONS,
CLIENT_DISCONNECT,
NONE,
};
private:
std::unique_ptr<component::IFabric_endpoint_unconnected_server> _preconnection;
Buffer_manager<component::IFabric_memory_control> _bm;
/* xx_buffer_outstanding is the signal for completion,
xx_buffer is the buffer pointer that needs to be freed (and set to null)
*/
protected:
unsigned _recv_buffer_posted_count;
private:
unsigned _send_buffer_posted_count;
protected:
/* values for two-phase get
*/
unsigned _send_value_posted_count;
private:
std::list<buffer_t *> _completed_recv_buffers;
open_connection _oc;
protected:
size_t _max_message_size;
/* Filled by base class check_for_posted_value_complete
* Drained by derived class check_network_completions
*/
std::queue<action_t> _deferred_unlock;
/**
* Ctor
*
* @param factory
* @param fabric_connection
*/
explicit Fabric_connection_base( //
unsigned debug_level_,
gsl::not_null<component::IFabric_server_factory *>factory,
std::unique_ptr<component::IFabric_endpoint_unconnected_server> && preconnection);
Fabric_connection_base(const Fabric_connection_base &) = delete;
Fabric_connection_base &operator=(const Fabric_connection_base &) = delete;
virtual ~Fabric_connection_base();
static void static_send_callback(void *cnxn, buffer_t *iob) noexcept
{
static_cast<Fabric_connection_base *>(cnxn)->send_callback(iob);
}
void send_callback(buffer_t *iob) noexcept
{
--_send_buffer_posted_count;
posted_count_log();
CPLOG(2, "Completed send (%p) freeing buffer", common::p_fmt(iob));
free_buffer(iob);
}
static void static_recv_callback(void *cnxn, buffer_t *iob) noexcept
{
static_cast<Fabric_connection_base *>(cnxn)->recv_callback(iob);
}
void recv_callback(buffer_t *iob) noexcept
{
--_recv_buffer_posted_count;
posted_count_log();
_completed_recv_buffers.push_front(iob);
CPLOG(2, "Completed recv (%p) (complete %zu)", common::p_fmt(iob), _completed_recv_buffers.size());
}
static void completion_callback(void * context,
status_t st,
std::uint64_t, // completion_flags,
std::size_t len,
void * error_data,
void * cnxn) noexcept
{
if (LIKELY(st == S_OK)) {
auto iob = static_cast<buffer_t *>(context);
iob->completion_cb(cnxn, iob);
}
else {
PERR("Fabric_connection_base: fabric operation failed st != S_OK (st=%d, "
"context=%p, len=%lu)",
st, context, len);
PERR("Error: %s", static_cast<char *>(error_data));
}
}
bool check_for_posted_recv_complete()
{
/* don't free buffer (such as above); it will be used for response */
// return _recv_buffer_posted_outstanding == false;
return _completed_recv_buffers.size() > 0;
}
void free_recv_buffer()
{
for (auto b : _completed_recv_buffers) {
free_buffer(b);
}
}
size_t recv_buffer_posted_count() const {
return _recv_buffer_posted_count;
}
void post_recv_buffer(buffer_t *buffer)
{
_preconnection->post_recv(buffer->iov, buffer->iov + 1, buffer->desc, buffer);
++_recv_buffer_posted_count;
posted_count_log();
CPLOG(2, "Posted recv (%p) (complete %zu)", common::p_fmt(buffer), _completed_recv_buffers.size());
}
void post_send_buffer(gsl::not_null<buffer_t *> buffer)
{
const auto iov = buffer->iov;
/* if packet is small enough use inject */
if (iov->iov_len <= transport()->max_inject_size()) {
CPLOG(2, "Fabric_connection_base: posting send with inject (iob %p %p,len=%lu)",
common::p_fmt(buffer), iov->iov_base, iov->iov_len);
transport()->inject_send(iov->iov_base, iov->iov_len);
CPLOG(2, "%s: buffer %p", __func__, common::p_fmt(buffer));
free_buffer(buffer); /* buffer is immediately complete fi_inject */
}
else {
CPLOG(2, "Fabric_connection_base: posting send (%p, %p)", common::p_fmt(buffer), iov->iov_base);
transport()->post_send(iov, iov + 1, buffer->desc, buffer);
++_send_buffer_posted_count;
posted_count_log();
CPLOG(2, "%s buffer (%p)", __func__, common::p_fmt(buffer));
}
}
void post_send_buffer2(gsl::not_null<buffer_t *> buffer, const ::iovec &val_iov, void *val_desc)
{
buffer->iov[1] = val_iov;
buffer->desc[1] = val_desc;
++_send_buffer_posted_count;
posted_count_log();
CPLOG(2, "Posted send (%p) ... value (%.*s) (len=%lu,ptr=%p)", common::p_fmt(buffer),
int(val_iov.iov_len), static_cast<char *>(val_iov.iov_base), val_iov.iov_len, val_iov.iov_base);
transport()->post_send(buffer->iov, buffer->iov + 2, buffer->desc, buffer);
}
buffer_t *posted_recv()
{
if (_completed_recv_buffers.size() == 0) return nullptr;
auto iob = _completed_recv_buffers.back();
_completed_recv_buffers.pop_back();
CPLOG(2, "Presented recv (%p) (complete %zu)", common::p_fmt(iob), _completed_recv_buffers.size());
return iob;
}
void posted_count_log() const
{
CPLOG(2, "POSTs recv %u send %u value %u", _recv_buffer_posted_count, _send_buffer_posted_count,
_send_value_posted_count);
}
Completion_state poll_completions()
{
if (_recv_buffer_posted_count != 0 || _send_buffer_posted_count != 0 || _send_value_posted_count != 0) {
#if 0
PLOG("%s posted_recv %u posted_send %u posted_value %u", __func__, _recv_buffer_posted_count, _send_buffer_posted_count, _send_value_posted_count);
#endif
try {
transport()->poll_completions(&Fabric_connection_base::completion_callback, this);
return Completion_state::COMPLETIONS;
}
catch (const std::logic_error &e) {
return Completion_state::CLIENT_DISCONNECT;
}
}
return Completion_state::NONE;
}
/**
* Forwarders that allow us to avoid exposing transport() and _bm
*
*/
public:
inline auto register_memory(const void *base, size_t len, std::uint64_t key, std::uint64_t flags)
{
return transport()->register_memory(base, len, key, flags); /* flags not supported for verbs */
}
inline void deregister_memory(memory_region_t region) { return transport()->deregister_memory(region); }
inline void *get_memory_descriptor(memory_region_t region) { return transport()->get_memory_descriptor(region); }
inline uint64_t get_memory_remote_key(memory_region_t region) { return transport()->get_memory_remote_key(region); }
protected:
inline auto allocate(buffer_t::completion_t c) { return _bm.allocate(c); }
inline void free_buffer(buffer_t *buffer) { _bm.free(buffer); }
inline size_t IO_buffer_size() const { return Buffer_manager<component::IFabric_memory_control>::BUFFER_LEN; }
gsl::not_null<component::IFabric_server *> transport() const { return _oc.transport(); }
inline std::string get_local_addr() { return transport()->get_local_addr(); }
};
struct open_connection_construct_key
{
private:
open_connection_construct_key() {};
public:
friend class Fabric_connection_base;
};
} // namespace mcas
#endif // __FABRIC_CONNECTION_BASE_H__
| {
"alphanum_fraction": 0.6876550868,
"avg_line_length": 30.8025477707,
"ext": "h",
"hexsha": "b77983ba1712bba0ad70c148e89a3696db8be530",
"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": "efaf438eb20cffa18b13f176c74a2b3153f89c07",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "fQuinzan/mcas",
"max_forks_repo_path": "src/server/mcas/src/fabric_connection_base.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "efaf438eb20cffa18b13f176c74a2b3153f89c07",
"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": "fQuinzan/mcas",
"max_issues_repo_path": "src/server/mcas/src/fabric_connection_base.h",
"max_line_length": 153,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "efaf438eb20cffa18b13f176c74a2b3153f89c07",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "fQuinzan/mcas",
"max_stars_repo_path": "src/server/mcas/src/fabric_connection_base.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 2364,
"size": 9672
} |
/*
ODE: a program to get optime Runge-Kutta and multi-steps methods.
Copyright 2011-2019, Javier Burguete Tolosa.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY Javier Burguete Tolosa ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
SHALL Javier Burguete Tolosa OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* \file rk_6_4.c
* \brief Source file to optimize Runge-Kutta 6 steps 4th order methods.
* \author Javier Burguete Tolosa.
* \copyright Copyright 2011-2019.
*/
#define _GNU_SOURCE
#include <string.h>
#include <math.h>
#include <libxml/parser.h>
#include <glib.h>
#include <libintl.h>
#include <gsl/gsl_rng.h>
#include "config.h"
#include "utils.h"
#include "optimize.h"
#include "rk.h"
#include "rk_6_4.h"
#define DEBUG_RK_6_4 0 ///< macro to debug.
/**
* Function to obtain the coefficients of a 6 steps 4th order Runge-Kutta
* method.
*/
int
rk_tb_6_4 (Optimize * optimize) ///< Optimize struct.
{
long double A[4], B[4], C[4], D[4], E[4];
long double *tb, *r;
#if DEBUG_RK_6_4
fprintf (stderr, "rk_tb_6_4: start\n");
#endif
tb = optimize->coefficient;
r = optimize->random_data;
t6 (tb) = 1.L;
t1 (tb) = r[0];
t2 (tb) = r[1];
b21 (tb) = r[2];
t3 (tb) = r[3];
b31 (tb) = r[4];
b32 (tb) = r[5];
t4 (tb) = r[6];
b41 (tb) = r[7];
b42 (tb) = r[8];
b43 (tb) = r[9];
t5 (tb) = r[10];
b54 (tb) = r[11];
b65 (tb) = r[12];
A[0] = t1 (tb);
B[0] = t2 (tb);
C[0] = t3 (tb);
D[0] = t4 (tb);
E[0] = 0.5L - b65 (tb) * t5 (tb);
A[1] = A[0] * t1 (tb);
B[1] = B[0] * t2 (tb);
C[1] = C[0] * t3 (tb);
D[1] = D[0] * t4 (tb);
E[1] = 1.L / 3.L - b65 (tb) * sqr (t5 (tb));
A[2] = A[1] * t1 (tb);
B[2] = B[1] * t2 (tb);
C[2] = C[1] * t3 (tb);
D[2] = D[1] * t4 (tb);
E[2] = 0.25L - b65 (tb) * sqr (t5 (tb)) * t5 (tb);
A[3] = 0.L;
B[3] = b21 (tb) * t1 (tb) * (t2 (tb) - t5 (tb));
C[3] = (b31 (tb) * t1 (tb) + b32 (tb) * t2 (tb)) * (t3 (tb) - t5 (tb));
D[3] = (b41 (tb) * t1 (tb) + b42 (tb) * t2 (tb) + b43 (tb) * t3 (tb))
* (t4 (tb) - t5 (tb));
E[3] = 0.125L - 1.L / 6.L * t5 (tb);
solve_4 (A, B, C, D, E);
if (isnan (E[0]) || isnan (E[1]) || isnan (E[2]) || isnan (E[3]))
return 0;
b64 (tb) = E[3];
b63 (tb) = E[2];
b62 (tb) = E[1];
b61 (tb) = E[0];
A[0] = t1 (tb);
B[0] = t2 (tb);
C[0] = t3 (tb);
D[0] = (1.L / 6.L - b62 (tb) * b21 (tb) * t1 (tb)
- b63 (tb) * (b31 (tb) * t1 (tb) + b32 (tb) * t2 (tb))
- b64 (tb) * (b41 (tb) * t1 (tb) + b42 (tb) * t2 (tb)
+ b43 (tb) * t3 (tb))) / b65 (tb) - b54 (tb) * t4 (tb);
A[1] = A[0] * t1 (tb);
B[1] = B[0] * t2 (tb);
C[1] = C[0] * t3 (tb);
D[1] = (1.L / 12.L - b62 (tb) * b21 (tb) * sqr (t1 (tb))
- b63 (tb) * (b31 (tb) * sqr (t1 (tb)) + b32 (tb) * sqr (t2 (tb)))
- b64 (tb) * (b41 (tb) * sqr (t1 (tb)) + b42 (tb) * sqr (t2 (tb))
+ b43 (tb) * sqr (t3 (tb)))) / b65 (tb)
- b54 (tb) * sqr (t4 (tb));
A[2] = 0.L;
B[2] = b21 (tb) * t1 (tb);
C[2] = b31 (tb) * t1 (tb) + b32 (tb) * t2 (tb);
D[2] = (1.L / 24.L - b63 (tb) * b32 (tb) * b21 (tb) * t1 (tb)
- b64 (tb) * (b42 (tb) * b21 (tb) * t1 (tb)
+ b43 (tb) * (b31 (tb) * t1 (tb) + b32 (tb) * t2 (tb))))
/ b65 (tb) - b54 (tb) * (b41 (tb) * t1 (tb) + b42 (tb) * t2 (tb)
+ b43 (tb) * t3 (tb));
solve_3 (A, B, C, D);
if (isnan (D[0]) || isnan (D[1]) || isnan (D[2]))
return 0;
b53 (tb) = D[2];
b52 (tb) = D[1];
b51 (tb) = D[0];
rk_b_6 (tb);
#if DEBUG_RK_6_4
fprintf (stderr, "rk_tb_6_4: end\n");
#endif
return 1;
}
/**
* Function to obtain the coefficients of a 6 steps 4th order, 5th order in
* equations depending only on time, Runge-Kutta method.
*/
int
rk_tb_6_4t (Optimize * optimize) ///< Optimize struct.
{
long double A[5], B[5], C[5], D[5], E[5], F[5];
long double *tb, *r;
#if DEBUG_RK_6_4
fprintf (stderr, "rk_tb_6_4t: start\n");
#endif
tb = optimize->coefficient;
r = optimize->random_data;
t6 (tb) = 1.L;
t1 (tb) = r[0];
t2 (tb) = r[1];
b21 (tb) = r[2];
t3 (tb) = r[3];
b31 (tb) = r[4];
b32 (tb) = r[5];
t4 (tb) = r[6];
b41 (tb) = r[7];
b42 (tb) = r[8];
b43 (tb) = r[9];
t5 (tb) = r[10];
b54 (tb) = r[11];
A[0] = t1 (tb);
B[0] = t2 (tb);
C[0] = t3 (tb);
D[0] = t4 (tb);
E[0] = t5 (tb);
F[0] = 0.5L;
A[1] = A[0] * t1 (tb);
B[1] = B[0] * t2 (tb);
C[1] = C[0] * t3 (tb);
D[1] = D[0] * t4 (tb);
E[1] = E[0] * t5 (tb);
F[1] = 1.L / 3.L;
A[2] = A[1] * t1 (tb);
B[2] = B[1] * t2 (tb);
C[2] = C[1] * t3 (tb);
D[2] = D[1] * t4 (tb);
E[2] = E[1] * t5 (tb);
F[2] = 0.25L;
A[3] = A[2] * t1 (tb);
B[3] = B[2] * t2 (tb);
C[3] = C[2] * t3 (tb);
D[3] = D[2] * t4 (tb);
E[3] = E[2] * t5 (tb);
F[3] = 0.2L;
A[4] = A[3] * t1 (tb);
B[4] = B[3] * t2 (tb);
C[4] = C[3] * t3 (tb);
D[4] = D[3] * t4 (tb);
E[4] = E[3] * t5 (tb);
F[4] = 1.L / 6.L;
solve_5 (A, B, C, D, E, F);
if (isnan (F[0]) || isnan (F[1]) || isnan (F[2]) || isnan (F[3])
|| isnan (F[4]))
return 0;
b65 (tb) = F[4];
b64 (tb) = F[3];
b63 (tb) = F[2];
b62 (tb) = F[1];
b61 (tb) = F[0];
A[0] = t1 (tb);
B[0] = t2 (tb);
C[0] = t3 (tb);
D[0] = (1.L / 6.L - b62 (tb) * b21 (tb) * t1 (tb)
- b63 (tb) * (b31 (tb) * t1 (tb) + b32 (tb) * t2 (tb))
- b64 (tb) * (b41 (tb) * t1 (tb) + b42 (tb) * t2 (tb)
+ b43 (tb) * t3 (tb))) / b65 (tb) - b54 (tb) * t4 (tb);
A[1] = A[0] * t1 (tb);
B[1] = B[0] * t2 (tb);
C[1] = C[0] * t3 (tb);
D[1] = (1.L / 12.L - b62 (tb) * b21 (tb) * sqr (t1 (tb))
- b63 (tb) * (b31 (tb) * sqr (t1 (tb)) + b32 (tb) * sqr (t2 (tb)))
- b64 (tb) * (b41 (tb) * sqr (t1 (tb)) + b42 (tb) * sqr (t2 (tb))
+ b43 (tb) * sqr (t3 (tb)))) / b65 (tb)
- b54 (tb) * sqr (t4 (tb));
A[2] = 0.L;
B[2] = b21 (tb) * t1 (tb);
C[2] = b31 (tb) * t1 (tb) + b32 (tb) * t2 (tb);
D[2] = (1.L / 24.L - b63 (tb) * b32 (tb) * b21 (tb) * t1 (tb)
- b64 (tb) * (b42 (tb) * b21 (tb) * t1 (tb)
+ b43 (tb) * (b31 (tb) * t1 (tb) + b32 (tb) * t2 (tb))))
/ b65 (tb) - b54 (tb) * (b41 (tb) * t1 (tb) + b42 (tb) * t2 (tb)
+ b43 (tb) * t3 (tb));
solve_3 (A, B, C, D);
if (isnan (D[0]) || isnan (D[1]) || isnan (D[2]))
return 0;
b53 (tb) = D[2];
b52 (tb) = D[1];
b51 (tb) = D[0];
rk_b_6 (tb);
#if DEBUG_RK_6_4
rk_print_tb (optimize, "rk_tb_6_4t", stderr);
fprintf (stderr, "rk_tb_6_4t: end\n");
#endif
return 1;
}
/**
* Function to obtain the coefficients of a 6 steps 3th-4th order Runge-Kutta
* pair.
*/
int
rk_tb_6_4p (Optimize * optimize) ///< Optimize struct.
{
long double A[4], B[4], C[4], D[4], E[4], AA[4], BB[4], CC[4], DD[4], EE[4];
long double *tb, *r;
#if DEBUG_RK_6_4
fprintf (stderr, "rk_tb_6_4p: start\n");
#endif
tb = optimize->coefficient;
r = optimize->random_data;
t6 (tb) = 1.L;
t1 (tb) = r[0];
t2 (tb) = r[1];
b21 (tb) = r[2];
t3 (tb) = r[3];
b31 (tb) = r[4];
b32 (tb) = r[5];
t4 (tb) = r[6];
b41 (tb) = r[7];
b42 (tb) = r[8];
b43 (tb) = r[9];
t5 (tb) = r[10];
b54 (tb) = r[11];
b65 (tb) = r[12];
A[0] = AA[0] = t1 (tb);
B[0] = BB[0] = t2 (tb);
C[0] = CC[0] = t3 (tb);
D[0] = DD[0] = t4 (tb);
EE[0] = 0.5L;
E[0] = 0.5L - b65 (tb) * t5 (tb);
A[1] = AA[1] = A[0] * t1 (tb);
B[1] = BB[1] = B[0] * t2 (tb);
C[1] = CC[1] = C[0] * t3 (tb);
D[1] = DD[1] = D[0] * t4 (tb);
EE[1] = 1.L / 3.L;
E[1] = 1.L / 3.L - b65 (tb) * sqr (t5 (tb));
A[2] = AA[2] = A[1] * t1 (tb);
B[2] = BB[2] = B[1] * t2 (tb);
C[2] = CC[2] = C[1] * t3 (tb);
D[2] = DD[2] = D[1] * t4 (tb);
EE[2] = 0.25L;
E[2] = 0.25L - b65 (tb) * sqr (t5 (tb)) * t5 (tb);
A[3] = AA[3] = 0.L;
BB[3] = b21 (tb) * t1 (tb);
B[3] = BB[3] * (t2 (tb) - t5 (tb));
CC[3] = (b31 (tb) * t1 (tb) + b32 (tb) * t2 (tb));
C[3] = CC[3] * (t3 (tb) - t5 (tb));
DD[3] = (b41 (tb) * t1 (tb) + b42 (tb) * t2 (tb) + b43 (tb) * t3 (tb));
D[3] = DD[3] * (t4 (tb) - t5 (tb));
EE[3] = 1.L / 6.L;
E[3] = 0.125L - 1.L / 6.L * t5 (tb);
solve_4 (A, B, C, D, E);
if (isnan (E[0]) || isnan (E[1]) || isnan (E[2]) || isnan (E[3]))
return 0;
b64 (tb) = E[3];
b63 (tb) = E[2];
b62 (tb) = E[1];
b61 (tb) = E[0];
solve_4 (AA, BB, CC, DD, EE);
if (isnan (EE[0]) || isnan (EE[1]) || isnan (EE[2]) || isnan (EE[3]))
return 0;
e64 (tb) = EE[3];
e63 (tb) = EE[2];
e62 (tb) = EE[1];
e61 (tb) = EE[0];
A[0] = t1 (tb);
B[0] = t2 (tb);
C[0] = t3 (tb);
D[0] = (1.L / 6.L - b62 (tb) * b21 (tb) * t1 (tb)
- b63 (tb) * (b31 (tb) * t1 (tb) + b32 (tb) * t2 (tb))
- b64 (tb) * (b41 (tb) * t1 (tb) + b42 (tb) * t2 (tb)
+ b43 (tb) * t3 (tb))) / b65 (tb) - b54 (tb) * t4 (tb);
A[1] = A[0] * t1 (tb);
B[1] = B[0] * t2 (tb);
C[1] = C[0] * t3 (tb);
D[1] = (1.L / 12.L - b62 (tb) * b21 (tb) * sqr (t1 (tb))
- b63 (tb) * (b31 (tb) * sqr (t1 (tb)) + b32 (tb) * sqr (t2 (tb)))
- b64 (tb) * (b41 (tb) * sqr (t1 (tb)) + b42 (tb) * sqr (t2 (tb))
+ b43 (tb) * sqr (t3 (tb)))) / b65 (tb)
- b54 (tb) * sqr (t4 (tb));
A[2] = 0.L;
B[2] = b21 (tb) * t1 (tb);
C[2] = b31 (tb) * t1 (tb) + b32 (tb) * t2 (tb);
D[2] = (1.L / 24.L - b63 (tb) * b32 (tb) * b21 (tb) * t1 (tb)
- b64 (tb) * (b42 (tb) * b21 (tb) * t1 (tb)
+ b43 (tb) * (b31 (tb) * t1 (tb) + b32 (tb) * t2 (tb))))
/ b65 (tb) - b54 (tb) * (b41 (tb) * t1 (tb) + b42 (tb) * t2 (tb)
+ b43 (tb) * t3 (tb));
solve_3 (A, B, C, D);
if (isnan (D[0]) || isnan (D[1]) || isnan (D[2]))
return 0;
b53 (tb) = D[2];
b52 (tb) = D[1];
b51 (tb) = D[0];
rk_b_6 (tb);
rk_e_6 (tb);
#if DEBUG_RK_6_4
fprintf (stderr, "rk_tb_6_4p: end\n");
#endif
return 1;
}
/**
* Function to obtain the coefficients of a 6 steps 3rd-4th order, 4th-5th order
* in equations depending only on time, Runge-Kutta method.
*/
int
rk_tb_6_4tp (Optimize * optimize) ///< Optimize struct.
{
long double A[5], B[5], C[5], D[5], E[5], F[5], AA[4], BB[4], CC[4], DD[4],
EE[4];
long double *tb, *r;
#if DEBUG_RK_6_4
fprintf (stderr, "rk_tb_6_4tp: start\n");
#endif
tb = optimize->coefficient;
r = optimize->random_data;
t6 (tb) = 1.L;
t1 (tb) = r[0];
t2 (tb) = r[1];
t3 (tb) = r[2];
b31 (tb) = r[3];
b32 (tb) = r[4];
t4 (tb) = r[5];
b41 (tb) = r[6];
b42 (tb) = r[7];
b43 (tb) = r[8];
t5 (tb) = r[9];
b54 (tb) = r[10];
b65 (tb) = r[11];
A[0] = AA[0] = t1 (tb);
B[0] = BB[0] = t2 (tb);
C[0] = CC[0] = t3 (tb);
D[0] = DD[0] = t4 (tb);
E[0] = t5 (tb);
F[0] = EE[0] = 0.5L;
A[1] = AA[1] = A[0] * t1 (tb);
B[1] = BB[1] = B[0] * t2 (tb);
C[1] = CC[1] = C[0] * t3 (tb);
D[1] = DD[1] = D[0] * t4 (tb);
E[1] = E[0] * t5 (tb);
F[1] = EE[1] = 1.L / 3.L;
A[2] = AA[2] = A[1] * t1 (tb);
B[2] = BB[2] = B[1] * t2 (tb);
C[2] = CC[2] = C[1] * t3 (tb);
D[2] = DD[2] = D[1] * t4 (tb);
E[2] = E[1] * t5 (tb);
F[2] = EE[2] = 0.25L;
A[3] = AA[3] = A[2] * t1 (tb);
B[3] = BB[3] = B[2] * t2 (tb);
C[3] = CC[3] = C[2] * t3 (tb);
D[3] = DD[3] = D[2] * t4 (tb);
E[3] = E[2] * t5 (tb);
F[3] = EE[3] = 0.2L;
A[4] = A[3] * t1 (tb);
B[4] = B[3] * t2 (tb);
C[4] = C[3] * t3 (tb);
D[4] = D[3] * t4 (tb);
E[4] = E[3] * t5 (tb);
F[4] = 1.L / 6.L;
solve_4 (AA, BB, CC, DD, EE);
if (isnan (EE[0]) || isnan (EE[1]) || isnan (EE[2]) || isnan (EE[3]))
return 0;
e64 (tb) = EE[3];
e63 (tb) = EE[2];
e62 (tb) = EE[1];
e61 (tb) = EE[0];
solve_5 (A, B, C, D, E, F);
if (isnan (F[0]) || isnan (F[1]) || isnan (F[2]) || isnan (F[3])
|| isnan (F[4]))
return 0;
b65 (tb) = F[4];
b64 (tb) = F[3];
b63 (tb) = F[2];
b62 (tb) = F[1];
b61 (tb) = F[0];
b21 (tb) = (1.L / 6.L - e63 (tb) * (b31 (tb) * t1 (tb) + b32 (tb) * t2 (tb))
- e64 (tb) * (b41 (tb) * t1 (tb) + b42 (tb) * t2 (tb)
+ b43 (tb) * t3 (tb))) / (e62 (tb) * t1 (tb));
if (isnan (b21 (tb)))
return 0;
A[0] = t1 (tb);
B[0] = t2 (tb);
C[0] = t3 (tb);
D[0] = (1.L / 6.L - b62 (tb) * b21 (tb) * t1 (tb)
- b63 (tb) * (b31 (tb) * t1 (tb) + b32 (tb) * t2 (tb))
- b64 (tb) * (b41 (tb) * t1 (tb) + b42 (tb) * t2 (tb)
+ b43 (tb) * t3 (tb))) / b65 (tb) - b54 (tb) * t4 (tb);
A[1] = A[0] * t1 (tb);
B[1] = B[0] * t2 (tb);
C[1] = C[0] * t3 (tb);
D[1] = (1.L / 12.L - b62 (tb) * b21 (tb) * sqr (t1 (tb))
- b63 (tb) * (b31 (tb) * sqr (t1 (tb)) + b32 (tb) * sqr (t2 (tb)))
- b64 (tb) * (b41 (tb) * sqr (t1 (tb)) + b42 (tb) * sqr (t2 (tb))
+ b43 (tb) * sqr (t3 (tb)))) / b65 (tb)
- b54 (tb) * sqr (t4 (tb));
A[2] = 0.L;
B[2] = b21 (tb) * t1 (tb);
C[2] = b31 (tb) * t1 (tb) + b32 (tb) * t2 (tb);
D[2] = (1.L / 24.L - b63 (tb) * b32 (tb) * b21 (tb) * t1 (tb)
- b64 (tb) * (b42 (tb) * b21 (tb) * t1 (tb)
+ b43 (tb) * (b31 (tb) * t1 (tb) + b32 (tb) * t2 (tb))))
/ b65 (tb) - b54 (tb) * (b41 (tb) * t1 (tb) + b42 (tb) * t2 (tb)
+ b43 (tb) * t3 (tb));
solve_3 (A, B, C, D);
if (isnan (D[0]) || isnan (D[1]) || isnan (D[2]))
return 0;
b53 (tb) = D[2];
b52 (tb) = D[1];
b51 (tb) = D[0];
rk_b_6 (tb);
#if DEBUG_RK_6_4
rk_print_tb (optimize, "rk_tb_6_4t", stderr);
fprintf (stderr, "rk_tb_6_4t: end\n");
#endif
return 1;
}
/**
* Function to calculate the objective function of a 6 steps 4th order
* Runge-Kutta method.
*
* \return objective function value.
*/
long double
rk_objective_tb_6_4 (RK * rk) ///< RK struct.
{
long double *tb;
long double o;
#if DEBUG_RK_6_4
fprintf (stderr, "rk_objective_tb_6_4: start\n");
#endif
tb = rk->tb->coefficient;
o = fminl (0.L, b20 (tb));
if (b30 (tb) < 0.L)
o += b30 (tb);
if (b40 (tb) < 0.L)
o += b40 (tb);
if (b50 (tb) < 0.L)
o += b50 (tb);
if (b51 (tb) < 0.L)
o += b51 (tb);
if (b52 (tb) < 0.L)
o += b52 (tb);
if (b53 (tb) < 0.L)
o += b53 (tb);
if (b60 (tb) < 0.L)
o += b60 (tb);
if (b61 (tb) < 0.L)
o += b61 (tb);
if (b62 (tb) < 0.L)
o += b62 (tb);
if (b63 (tb) < 0.L)
o += b63 (tb);
if (b64 (tb) < 0.L)
o += b64 (tb);
if (o < 0.L)
{
o = 40.L - o;
goto end;
}
o = 30.L
+ fmaxl (1.L,
fmaxl (t1 (tb),
fmaxl (t2 (tb),
fmaxl (t3 (tb), fmaxl (t4 (tb), t5 (tb))))));
if (rk->strong)
{
rk_bucle_ac (rk);
o = fminl (o, *rk->ac0->optimal);
}
end:
#if DEBUG_RK_6_4
fprintf (stderr, "rk_objective_tb_6_4: optimal=%Lg\n", o);
fprintf (stderr, "rk_objective_tb_6_4: end\n");
#endif
return o;
}
/**
* Function to calculate the objective function of a 6 steps 4th order, 5th
* order in equations depending only on time, Runge-Kutta method.
*
* \return objective function value.
*/
long double
rk_objective_tb_6_4t (RK * rk) ///< RK struct.
{
long double *tb;
long double o;
#if DEBUG_RK_6_4
fprintf (stderr, "rk_objective_tb_6_4t: start\n");
#endif
tb = rk->tb->coefficient;
#if DEBUG_RK_6_4
rk_print_tb (optimize, "rk_objective_tb_6_4t", stderr);
#endif
o = fminl (0.L, b20 (tb));
if (b30 (tb) < 0.L)
o += b30 (tb);
if (b40 (tb) < 0.L)
o += b40 (tb);
if (b50 (tb) < 0.L)
o += b50 (tb);
if (b51 (tb) < 0.L)
o += b51 (tb);
if (b52 (tb) < 0.L)
o += b52 (tb);
if (b53 (tb) < 0.L)
o += b53 (tb);
if (b60 (tb) < 0.L)
o += b60 (tb);
if (b61 (tb) < 0.L)
o += b61 (tb);
if (b62 (tb) < 0.L)
o += b62 (tb);
if (b63 (tb) < 0.L)
o += b63 (tb);
if (b64 (tb) < 0.L)
o += b64 (tb);
if (b65 (tb) < 0.L)
o += b65 (tb);
if (o < 0.L)
{
o = 40.L - o;
goto end;
}
o = 30.L
+ fmaxl (1.L,
fmaxl (t1 (tb),
fmaxl (t2 (tb),
fmaxl (t3 (tb), fmaxl (t4 (tb), t5 (tb))))));
if (rk->strong)
{
rk_bucle_ac (rk);
o = fminl (o, *rk->ac0->optimal);
}
end:
#if DEBUG_RK_6_4
fprintf (stderr, "rk_objective_tb_6_4t: optimal=%Lg\n", o);
fprintf (stderr, "rk_objective_tb_6_4t: end\n");
#endif
return o;
}
/**
* Function to calculate the objective function of a 6 steps 3rd-4th order
* Runge-Kutta pair.
*
* \return objective function value.
*/
long double
rk_objective_tb_6_4p (RK * rk) ///< RK struct.
{
long double *tb;
long double o;
#if DEBUG_RK_6_4
fprintf (stderr, "rk_objective_tb_6_4p: start\n");
#endif
tb = rk->tb->coefficient;
o = fminl (0.L, b20 (tb));
if (b30 (tb) < 0.L)
o += b30 (tb);
if (b40 (tb) < 0.L)
o += b40 (tb);
if (b50 (tb) < 0.L)
o += b50 (tb);
if (b51 (tb) < 0.L)
o += b51 (tb);
if (b52 (tb) < 0.L)
o += b52 (tb);
if (b53 (tb) < 0.L)
o += b53 (tb);
if (b60 (tb) < 0.L)
o += b60 (tb);
if (b61 (tb) < 0.L)
o += b61 (tb);
if (b62 (tb) < 0.L)
o += b62 (tb);
if (b63 (tb) < 0.L)
o += b63 (tb);
if (b64 (tb) < 0.L)
o += b64 (tb);
if (e60 (tb) < 0.L)
o += e60 (tb);
if (e61 (tb) < 0.L)
o += e61 (tb);
if (e62 (tb) < 0.L)
o += e62 (tb);
if (e63 (tb) < 0.L)
o += e63 (tb);
if (e64 (tb) < 0.L)
o += e64 (tb);
if (o < 0.L)
{
o = 40.L - o;
goto end;
}
o = 30.L
+ fmaxl (1.L,
fmaxl (t1 (tb),
fmaxl (t2 (tb),
fmaxl (t3 (tb), fmaxl (t4 (tb), t5 (tb))))));
if (rk->strong)
{
rk_bucle_ac (rk);
o = fminl (o, *rk->ac0->optimal);
}
end:
#if DEBUG_RK_6_4
fprintf (stderr, "rk_objective_tb_6_4p: optimal=%Lg\n", o);
fprintf (stderr, "rk_objective_tb_6_4p: end\n");
#endif
return o;
}
/**
* Function to calculate the objective function of a 6 steps 3rd-4th order,
* 4th-5th order in equations depending only in time, Runge-Kutta pair.
*
* \return objective function value.
*/
long double
rk_objective_tb_6_4tp (RK * rk) ///< RK struct.
{
long double *tb;
long double o;
#if DEBUG_RK_6_4
fprintf (stderr, "rk_objective_tb_6_4tp: start\n");
#endif
tb = rk->tb->coefficient;
#if DEBUG_RK_6_4
rk_print_tb (optimize, "rk_objective_tb_6_4tp", stderr);
#endif
o = fminl (0.L, b20 (tb));
if (b21 (tb) < 0.L)
o += b21 (tb);
if (b30 (tb) < 0.L)
o += b30 (tb);
if (b40 (tb) < 0.L)
o += b40 (tb);
if (b50 (tb) < 0.L)
o += b50 (tb);
if (b51 (tb) < 0.L)
o += b51 (tb);
if (b52 (tb) < 0.L)
o += b52 (tb);
if (b53 (tb) < 0.L)
o += b53 (tb);
if (b60 (tb) < 0.L)
o += b60 (tb);
if (b61 (tb) < 0.L)
o += b61 (tb);
if (b62 (tb) < 0.L)
o += b62 (tb);
if (b63 (tb) < 0.L)
o += b63 (tb);
if (b64 (tb) < 0.L)
o += b64 (tb);
if (b65 (tb) < 0.L)
o += b65 (tb);
if (e60 (tb) < 0.L)
o += e60 (tb);
if (e61 (tb) < 0.L)
o += e61 (tb);
if (e62 (tb) < 0.L)
o += e62 (tb);
if (e63 (tb) < 0.L)
o += e63 (tb);
if (e64 (tb) < 0.L)
o += e64 (tb);
if (o < 0.L)
{
o = 40.L - o;
goto end;
}
o = 30.L
+ fmaxl (1.L,
fmaxl (t1 (tb),
fmaxl (t2 (tb),
fmaxl (t3 (tb), fmaxl (t4 (tb), t5 (tb))))));
if (rk->strong)
{
rk_bucle_ac (rk);
o = fminl (o, *rk->ac0->optimal);
}
end:
#if DEBUG_RK_6_4
fprintf (stderr, "rk_objective_tb_6_4tp: optimal=%Lg\n", o);
fprintf (stderr, "rk_objective_tb_6_4tp: end\n");
#endif
return o;
}
| {
"alphanum_fraction": 0.4639576143,
"avg_line_length": 27.7638326586,
"ext": "c",
"hexsha": "9e3438664d501d13220fce89a4c50e21b3d46ca2",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "463b8402ed4aac140a4c4ca2295a69dcce98b061",
"max_forks_repo_licenses": [
"BSD-2-Clause"
],
"max_forks_repo_name": "jburguete/ode",
"max_forks_repo_path": "rk_6_4.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "463b8402ed4aac140a4c4ca2295a69dcce98b061",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-2-Clause"
],
"max_issues_repo_name": "jburguete/ode",
"max_issues_repo_path": "rk_6_4.c",
"max_line_length": 80,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "463b8402ed4aac140a4c4ca2295a69dcce98b061",
"max_stars_repo_licenses": [
"BSD-2-Clause"
],
"max_stars_repo_name": "jburguete/ode",
"max_stars_repo_path": "rk_6_4.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 9525,
"size": 20573
} |
#pragma once
#include <string>
#include <vector>
#include <boost/random.hpp>
#include <cblas.h>
namespace con {
using std::vector;
using std::cout;
using std::cerr;
using std::endl;
using std::string;
static boost::mt19937 rng(0);
#define BUG(x) std::cout<<#x<<" = "<<(x)<<std::endl;
typedef double Real;
typedef vector<Real> Vec;
Real sigmoid(const Real &z) {
return 1.0 / (1.0 + std::exp(-z));
}
Real derivativeSigmoid(const Real &v) {
return v * (1.0 - v);
}
Real sqr(const Real &x) {
return x * x;
}
Real randomize(const Real &min, const Real &max) {
boost::uniform_real<Real> dst(min, max);
return dst(rng);
}
void randomizeVec(const Real &min, const Real &max, Vec *a) {
for (auto it = a->begin(); it != a->end(); it++) {
(*it) = randomize(min, max);
}
}
void gaussianRng(const Real &mean, const Real &std, Vec *a) {
boost::normal_distribution<Real> random_distribution(mean, std);
boost::variate_generator<boost::mt19937, boost::normal_distribution<Real>>
variate_generator(rng, random_distribution);
for (auto it = a->begin(); it != a->end(); it++) {
*it = variate_generator();
}
}
void clear(Vec *a) {
for (auto it = a->begin(); it != a->end(); it++) {
(*it) = 0;
}
}
void clear(vector<Vec> *a) {
for (int i = 0; i < a->size(); i++) {
clear(&a->at(i));
}
}
void print(const Vec &a) {
for (auto x : a) {
cout << x << " ";
}
cout << endl;
}
void reshape(const int num, const int width, const int height, const int depth, vector<Vec> *a) {
a->resize(num);
for (int i = 0; i < num; i++) {
a->at(i).resize(width * height * depth);
}
}
int ceilDiv(const int &x, const int &y) {
return (x + y - 1) / y;
}
void gemm(
const CBLAS_TRANSPOSE &TransA, const CBLAS_TRANSPOSE &TransB,
const int &M, const int &N, const int &K,
const Real &alpha, const Vec &vecA, const Vec &vecB,
const Real &beta, Vec *vecC) {
const Real *A = &vecA[0];
const Real *B = &vecB[0];
Real *C = &vecC->at(0);
int lda = (TransA == CblasNoTrans) ? K : M;
int ldb = (TransB == CblasNoTrans) ? N : K;
cblas_dgemm(CblasRowMajor, TransA, TransB, M, N, K, alpha, A, lda, B,
ldb, beta, C, N);
}
void gemv(
const CBLAS_TRANSPOSE &TransA,
const int &M, const int &N,
const Real &alpha, const Vec &matA, const Vec &vecX,
const double beta, Vec *vecY) {
const Real *A = &matA[0];
const Real *x = &vecX[0];
Real *y = &vecY->at(0);
cblas_dgemv(CblasRowMajor, TransA, M, N, alpha, A, N, x, 1, beta, y, 1);
}
void vexp(const int &n, const Vec &input, Vec *output) {
// vsExp(n, &input[0], &output->at(0));
for (int i = 0; i < n; i++) {
output->at(i) = exp(input[i]);
}
}
void vdiv(const int &n, const Vec &a, const Vec &b, Vec *c) {
// vsDiv(n, &a[0], &b[0], &c->at(0));
for (int i = 0; i < n; i++) {
c->at(i) = a[i] / b[i];
}
}
void copy(const int &n, const Vec &input, Vec *output) {
for (int i = 0; i < n; i++) {
output->at(i) = input[i];
}
}
void ones(const int &n, Vec *v) {
v->resize(n);
std::fill(v->begin(), v->end(), 1.0);
}
}
| {
"alphanum_fraction": 0.5440194293,
"avg_line_length": 23.034965035,
"ext": "h",
"hexsha": "4ac832f5ca6c25116efe44dbc1298fb7088078b2",
"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": "c9643a958bfbfcfcaeb413bf42e5080c6f0c1df5",
"max_forks_repo_licenses": [
"BSD-2-Clause"
],
"max_forks_repo_name": "robgrzel/OpenMPI_Examples",
"max_forks_repo_path": "Noob_Examples/TempCode/deep-learning/cifar/10/lkmtue/util.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "c9643a958bfbfcfcaeb413bf42e5080c6f0c1df5",
"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": "robgrzel/OpenMPI_Examples",
"max_issues_repo_path": "Noob_Examples/TempCode/deep-learning/cifar/10/lkmtue/util.h",
"max_line_length": 99,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "c9643a958bfbfcfcaeb413bf42e5080c6f0c1df5",
"max_stars_repo_licenses": [
"BSD-2-Clause"
],
"max_stars_repo_name": "robgrzel/OpenMPI_Examples",
"max_stars_repo_path": "Noob_Examples/TempCode/deep-learning/cifar/10/lkmtue/util.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1112,
"size": 3294
} |
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <gbpLib.h>
#include <gbpMath.h>
#include <gbpCosmo_core.h>
#include <gbpCosmo_NFW_etc.h>
#include <gsl/gsl_sf_expint.h>
// From Alam et al '02
double R_half_V_max_NFW(double M_vir, double z, int mode, cosmo_info **cosmo) {
double c_vir;
double R_vir;
double r_o;
double r_val = 0.;
set_NFW_params(M_vir, z, mode, cosmo, &c_vir, &R_vir);
r_o = R_vir / c_vir;
r_val = 0.13 * r_o;
return (r_val);
}
| {
"alphanum_fraction": 0.66,
"avg_line_length": 20.8333333333,
"ext": "c",
"hexsha": "cf691eb10dcead249572fb05fa052cc354be3442",
"lang": "C",
"max_forks_count": 4,
"max_forks_repo_forks_event_max_datetime": "2016-08-01T08:14:24.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-01-23T00:50:40.000Z",
"max_forks_repo_head_hexsha": "5157d2e377edbd4806258d1c16b329373186d43a",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "gbpoole/gbpCode",
"max_forks_repo_path": "src/gbpAstro/gbpCosmo/NFW_etc/R_half_V_max_NFW.c",
"max_issues_count": 2,
"max_issues_repo_head_hexsha": "5157d2e377edbd4806258d1c16b329373186d43a",
"max_issues_repo_issues_event_max_datetime": "2019-06-18T00:40:46.000Z",
"max_issues_repo_issues_event_min_datetime": "2017-07-30T11:10:49.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "gbpoole/gbpCode",
"max_issues_repo_path": "src/gbpAstro/gbpCosmo/NFW_etc/R_half_V_max_NFW.c",
"max_line_length": 79,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "5157d2e377edbd4806258d1c16b329373186d43a",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "gbpoole/gbpCode",
"max_stars_repo_path": "src/gbpAstro/gbpCosmo/NFW_etc/R_half_V_max_NFW.c",
"max_stars_repo_stars_event_max_datetime": "2015-10-20T11:39:53.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-10-20T11:39:53.000Z",
"num_tokens": 179,
"size": 500
} |
/*
** LISA, 2nd level using design matrix
**
** G.Lohmann, July 2018
*/
#include <viaio/Vlib.h>
#include <viaio/VImage.h>
#include <viaio/mu.h>
#include <viaio/option.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_blas.h>
#include <gsl/gsl_randist.h>
#include <gsl/gsl_cdf.h>
#include <gsl/gsl_math.h>
#define ABS(x) ((x) > 0 ? (x) : -(x))
#define SQR(x) ((x)*(x))
extern gsl_matrix *PseudoInv(gsl_matrix *A,gsl_matrix *B);
extern gsl_matrix *XRead2ndLevel(VString);
extern double t2z(double t,double df);
double EstimateVariance(gsl_matrix *XInv,gsl_vector *con)
{
int nbeta = XInv->size1;
double var=0;
gsl_matrix *bcov = gsl_matrix_calloc(nbeta,nbeta);
gsl_blas_dgemm(CblasNoTrans,CblasTrans,1.0,XInv,XInv,0.0,bcov);
gsl_vector *tmp = gsl_vector_alloc(nbeta);
gsl_blas_dgemv(CblasTrans,1.0,bcov,con,0.0,tmp);
gsl_blas_ddot (tmp,con,&var);
double sigma = sqrt(var);
gsl_matrix_free(bcov);
gsl_vector_free(tmp);
return sigma;
}
/*
** get effective degrees of freedom
*/
double DoF(gsl_matrix *X,gsl_matrix *XInv,double *xtrace)
{
int i,nimages = X->size1;
gsl_matrix *R = gsl_matrix_calloc (nimages,nimages);
gsl_matrix *P = gsl_matrix_calloc (nimages,nimages);
gsl_blas_dgemm(CblasNoTrans,CblasNoTrans,1.0,X,XInv,0.0,P);
gsl_matrix_set_identity(R);
gsl_matrix_sub(R,P);
double trace = 0;
for (i=0; i<nimages; i++)
trace += gsl_matrix_get(R,i,i);
gsl_blas_dgemm(CblasNoTrans,CblasNoTrans,1.0,R,R,0.0,P);
gsl_matrix_free(R);
double trace2 = 0;
for (i=0; i<nimages; i++) {
trace2 += gsl_matrix_get(P,i,i);
}
gsl_matrix_free(P);
(*xtrace) = trace;
double df = (trace*trace) / trace2;
return df;
}
/*
** general linear regression, 2nd level
*/
void GLM2(VImage *src,gsl_matrix *X,gsl_vector *contrast,int *permflag,int *permtable,int *signtable,int signswitch,VImage dest)
{
int i,j,ip,b,r,c;
double t=0,z=0,sum=0,tsigma=0,d=0,err=0,var=0,u=0,tiny=TINY;
int ncols = VImageNColumns(src[0]);
int nrows = VImageNRows(src[0]);
int nslices = VImageNBands(src[0]);
int nimages = X->size1;
VFillImage(dest,VAllBands,0);
/* permutation or sign switching applied to design matrix */
gsl_matrix *XP = gsl_matrix_calloc(X->size1,X->size2);
gsl_matrix_memcpy(XP,X);
if (signswitch >= 0) { /* sign switching (one-sample test) */
for (i=0; i<X->size1; i++) {
if (signtable[i] < 0) {
u = gsl_matrix_get(X,i,signswitch);
gsl_matrix_set(XP,i,signswitch,-u);
}
}
}
else { /* permutations */
for (i=0; i<X->size1; i++) {
ip = permtable[i];
for (j=0; j<X->size2; j++) {
if (permflag[j] > 0) { /* do not permute columns containing nuisance covariates */
u = gsl_matrix_get(X,i,j);
gsl_matrix_set(XP,ip,j,u);
}
}
}
}
/* pseudo inverse */
gsl_matrix *XInv = PseudoInv(XP,NULL);
/* get DoF and variance */
double trace = 0;
double df = DoF(XP,XInv,&trace);
double sigma = EstimateVariance(XInv,contrast);
if (df < tiny) VError(" Zero degrees of freedom");
if (sigma < tiny) VError(" No variance in design/contrast");
/* main loop */
gsl_set_error_handler_off();
gsl_vector *y = gsl_vector_alloc (nimages);
gsl_vector *yz = gsl_vector_alloc (nimages);
gsl_vector *beta = gsl_vector_alloc (X->size2);
for (b=0; b<nslices; b++) {
for (r=0; r<nrows; r++) {
for (c=0; c<ncols; c++) {
int nonzero=0;
for (j=0; j<nimages; j++) {
y->data[j] = VGetPixel(src[j],b,r,c);
if (fabs(y->data[j]) > 0) nonzero++;
}
if (nonzero < nimages-2) continue;
/* compute beta's */
gsl_blas_dgemv(CblasNoTrans,1.0,XInv,y,0.0,beta);
/* residuals */
gsl_blas_dgemv(CblasNoTrans,1.0,XP,beta,0.0,yz);
err = 0;
for (j=0; j<nimages; j++) {
d = y->data[j] - yz->data[j];
err += d*d;
}
/* get z-value */
t = z = sum = 0;
gsl_blas_ddot (beta,contrast,&sum);
if (fabs(sum) < tiny) continue;
var = err / trace;
tsigma = sqrt(var) * sigma;
if (tsigma > tiny) {
t = sum / tsigma;
z = t2z(t,df);
if (sum < 0) z = -z;
}
VPixel(dest,b,r,c,VFloat) = z;
}
}
}
gsl_vector_free(y);
gsl_vector_free(yz);
gsl_vector_free(beta);
gsl_matrix_free(XP);
gsl_matrix_free(XInv);
}
| {
"alphanum_fraction": 0.6402128644,
"avg_line_length": 22.8677248677,
"ext": "c",
"hexsha": "032eed4adffa69d01d0d649e8dfacda50efa746a",
"lang": "C",
"max_forks_count": 8,
"max_forks_repo_forks_event_max_datetime": "2022-03-22T08:05:46.000Z",
"max_forks_repo_forks_event_min_datetime": "2017-09-29T10:33:53.000Z",
"max_forks_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "zrajna/lipsia",
"max_forks_repo_path": "src/stats/vlisa_2ndlevel/2ndLevel.c",
"max_issues_count": 7,
"max_issues_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014",
"max_issues_repo_issues_event_max_datetime": "2022-02-16T13:42:05.000Z",
"max_issues_repo_issues_event_min_datetime": "2019-11-12T15:47:56.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "zrajna/lipsia",
"max_issues_repo_path": "src/stats/vlisa_2ndlevel/2ndLevel.c",
"max_line_length": 128,
"max_stars_count": 17,
"max_stars_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "zrajna/lipsia",
"max_stars_repo_path": "src/stats/vlisa_2ndlevel/2ndLevel.c",
"max_stars_repo_stars_event_max_datetime": "2022-03-18T10:55:03.000Z",
"max_stars_repo_stars_event_min_datetime": "2017-04-10T16:33:42.000Z",
"num_tokens": 1482,
"size": 4322
} |
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <glib.h>
#include <omp.h>
// libgsl0-dev
#include <gsl/gsl_math.h>
#include <gsl/gsl_rng.h>
#include <sys/time.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_sort_double.h>
double pi(int n, int batch) {
const gsl_rng_type * T;
gsl_rng * r;
gsl_rng_env_setup();
T = gsl_rng_default;
r = gsl_rng_alloc (T);
int end = (n / batch);
double sum = 0;
int i, j;
// GRand * grand = g_rand_new ();
//g_rand_double(grand);
#pragma omp parallel for default(shared) firstprivate(r) private(j) reduction (+:sum)
for (i = 0; i < end; i++) {
for (j=0; j<batch; j++) {
double a = gsl_rng_uniform_pos (r);
double b = gsl_rng_uniform_pos (r);
double c = (a * a) + (b * b);
if (c <= 1) {
sum += c;
}
}
}
return 8 * sum / n;
}
int main () {
printf("%0.15f\n", pi(100000000, 1000));
}
| {
"alphanum_fraction": 0.5368314834,
"avg_line_length": 20.6458333333,
"ext": "c",
"hexsha": "432f1a9667a5e1fa0224af8f723d9b417c6c5430",
"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": "dcea8eb26ec47e5048193ace367e5746b0411cec",
"max_forks_repo_licenses": [
"Unlicense"
],
"max_forks_repo_name": "papaloizouc/100days",
"max_forks_repo_path": "9.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "dcea8eb26ec47e5048193ace367e5746b0411cec",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"Unlicense"
],
"max_issues_repo_name": "papaloizouc/100days",
"max_issues_repo_path": "9.c",
"max_line_length": 91,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "dcea8eb26ec47e5048193ace367e5746b0411cec",
"max_stars_repo_licenses": [
"Unlicense"
],
"max_stars_repo_name": "papaloizouc/100days",
"max_stars_repo_path": "9.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 305,
"size": 991
} |
// Authors: David Blei (blei@cs.princeton.edu)
// Sean Gerrish (sgerrish@cs.princeton.edu)
//
// Copyright 2011 Sean Gerrish and David Blei
// All Rights Reserved.
//
// See the README for this package for details about modifying or
// distributing this software.
#ifndef LDA_H
#define LDA_H
#include <gsl/gsl_vector.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_sf_gamma.h>
#include <gsl/gsl_sf_psi.h>
#include <gsl/gsl_sf_lambert.h>
#include <gsl/gsl_rng.h>
#include "param.h"
#include "data.h"
#include "gsl-wrappers.h"
/*
* functions for posterior inference in the latent dirichlet
* allocation model.
*
*/
#define LDA_INFERENCE_CONVERGED 1e-8
#define LDA_SEED_INIT 1
#define LDA_INIT_SMOOTH 1.0
#define LDA_EM_CONVERGED 5e-5
#define LDA_USE_VAR_BAYES 0
#define LDA_TOPIC_DIR_PARAM 0.001
// lda model
typedef struct lda {
int ntopics; // number of topics
int nterms; // vocabulary size
gsl_matrix* topics; // each column is a topic (V X K)
gsl_vector* alpha; // dirichlet parameters
} lda;
// lda posterior
typedef struct lda_post {
doc_t* doc; // document associated to this posterior
lda* model; // lda model
gsl_matrix* phi; // variational mult parameters (nterms x K)
gsl_matrix* log_phi; // convenient for computation (nterms x K)
gsl_vector* gamma; // variational dirichlet parameters (K)
gsl_vector* lhood; // a K+1 vector, sums to the lhood bound
gsl_vector* doc_weight; // Not owned by this structure.
gsl_vector* renormalized_doc_weight; // Not owned by this structure.
} lda_post;
// lda sufficient statistics
typedef struct lda_suff_stats {
gsl_matrix* topics_ss;
} lda_suff_stats;
// new lda model and suff stats
lda* new_lda_model(int ntopics, int nterms);
void free_lda_model(lda* m);
lda_suff_stats* new_lda_suff_stats(lda* model);
void reset_lda_suff_stats(lda_suff_stats* ss);
lda_post* new_lda_post(int ntopics, int max_length);
void free_lda_post(lda_post* p);
void initialize_lda_ss_from_data(corpus_t* data, lda_suff_stats* ss);
// posterior inference
double fit_lda_post(int doc_number, int time,
lda_post* p, lda_seq* var,
gsl_matrix* g,
gsl_matrix* g3,
gsl_matrix* g4,
gsl_matrix* g5);
void init_lda_post(lda_post* p);
void update_gamma(lda_post* p);
void update_phi(int doc_number, int time,
lda_post* p, lda_seq* var,
gsl_matrix* g);
void update_phi_dim(int doc_number, int time,
lda_post* p, lda_seq* var,
gsl_matrix* g);
void update_phi_fixed(int doc_number, int time,
lda_post* p, lda_seq* var,
gsl_matrix* g3_matrix,
gsl_matrix* g4_matrix,
gsl_matrix* g5_matrix);
void update_phi_multiple(int doc_number, int time,
lda_post* p, lda_seq* var,
gsl_matrix* g);
// compute the likelihood bound
double compute_lda_lhood(lda_post* p);
// EM algorithm
double lda_e_step(lda* model, corpus_t* data, lda_suff_stats* ss);
double lda_m_step(lda* model, lda_suff_stats* ss);
void lda_em(lda* model,
lda_suff_stats* ss,
corpus_t* data,
int max_iter,
char* outname);
// reading and writing
lda_suff_stats* read_lda_suff_stats(char* filename, int ntopics, int nterms);
void write_lda(lda* model, char* name);
void write_lda_suff_stats(lda_suff_stats* ss, char* name);
lda* read_lda(int ntopics, int nterms, char* name);
void initialize_lda_ss_from_random(corpus_t* data, lda_suff_stats* ss);
#endif
| {
"alphanum_fraction": 0.7188221709,
"avg_line_length": 27.4920634921,
"ext": "h",
"hexsha": "ea2ba7629ce9a88e88b1e3bcfe3c98710412c742",
"lang": "C",
"max_forks_count": 7,
"max_forks_repo_forks_event_max_datetime": "2020-07-10T09:29:17.000Z",
"max_forks_repo_forks_event_min_datetime": "2019-03-15T04:11:00.000Z",
"max_forks_repo_head_hexsha": "07c936c07d268208dcc2f19e07fb8d2a18e39ba8",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "iwangjian/topic-extractor",
"max_forks_repo_path": "scripts/lib/DTM/dtm/lda.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "07c936c07d268208dcc2f19e07fb8d2a18e39ba8",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "iwangjian/topic-extractor",
"max_issues_repo_path": "scripts/lib/DTM/dtm/lda.h",
"max_line_length": 77,
"max_stars_count": 11,
"max_stars_repo_head_hexsha": "07c936c07d268208dcc2f19e07fb8d2a18e39ba8",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "iwangjian/dtm-lab",
"max_stars_repo_path": "scripts/lib/DTM/dtm/lda.h",
"max_stars_repo_stars_event_max_datetime": "2020-04-22T08:34:34.000Z",
"max_stars_repo_stars_event_min_datetime": "2018-07-12T11:05:51.000Z",
"num_tokens": 984,
"size": 3464
} |
/* ode-initval2/driver.c
*
* Copyright (C) 2009, 2010 Tuomo Keskitalo
*
* 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.
*/
/* Driver routine for odeiv2. This is a wrapper for low level GSL
functions that allows a simple interface to step, control and
evolve layers.
*/
#include <config.h>
#include <math.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_odeiv2.h>
#include <gsl/gsl_machine.h>
static gsl_odeiv2_driver *
driver_alloc (const gsl_odeiv2_system * sys, const double hstart,
const gsl_odeiv2_step_type * T)
{
/* Allocates and initializes an ODE driver system. Step and evolve
objects are allocated here, but control object is allocated in
another function.
*/
gsl_odeiv2_driver *state =
(gsl_odeiv2_driver *) malloc (sizeof (gsl_odeiv2_driver));
if (state == NULL)
{
GSL_ERROR_NULL ("failed to allocate space for driver state",
GSL_ENOMEM);
}
if (sys == NULL)
{
GSL_ERROR_NULL ("gsl_odeiv2_system must be defined", GSL_EINVAL);
}
{
const size_t dim = sys->dimension;
if (dim == 0)
{
GSL_ERROR_NULL
("gsl_odeiv2_system dimension must be a positive integer",
GSL_EINVAL);
}
state->sys = sys;
state->s = gsl_odeiv2_step_alloc (T, dim);
if (state->s == NULL)
{
free (state);
GSL_ERROR_NULL ("failed to allocate step object", GSL_ENOMEM);
}
state->e = gsl_odeiv2_evolve_alloc (dim);
}
if (state->e == NULL)
{
gsl_odeiv2_step_free (state->s);
free (state);
GSL_ERROR_NULL ("failed to allocate evolve object", GSL_ENOMEM);
}
if (hstart > 0.0 || hstart < 0.0)
{
state->h = hstart;
}
else
{
GSL_ERROR_NULL ("invalid hstart", GSL_EINVAL);
}
state->h = hstart;
state->hmin = 0.0;
state->hmax = GSL_DBL_MAX;
state->nmax = 0;
state->n = 0;
state->c = NULL;
return state;
}
int
gsl_odeiv2_driver_set_hmin (gsl_odeiv2_driver * d, const double hmin)
{
/* Sets minimum allowed step size fabs(hmin) for driver. It is
required that hmin <= fabs(h) <= hmax. */
if ((fabs (hmin) > fabs (d->h)) || (fabs (hmin) > d->hmax))
{
GSL_ERROR_NULL ("hmin <= fabs(h) <= hmax required", GSL_EINVAL);
}
d->hmin = fabs (hmin);
return GSL_SUCCESS;
}
int
gsl_odeiv2_driver_set_hmax (gsl_odeiv2_driver * d, const double hmax)
{
/* Sets maximum allowed step size fabs(hmax) for driver. It is
required that hmin <= fabs(h) <= hmax. */
if ((fabs (hmax) < fabs (d->h)) || (fabs (hmax) < d->hmin))
{
GSL_ERROR_NULL ("hmin <= fabs(h) <= hmax required", GSL_EINVAL);
}
if (hmax > 0.0 || hmax < 0.0)
{
d->hmax = fabs (hmax);
}
else
{
GSL_ERROR_NULL ("invalid hmax", GSL_EINVAL);
}
return GSL_SUCCESS;
}
int
gsl_odeiv2_driver_set_nmax (gsl_odeiv2_driver * d,
const unsigned long int nmax)
{
/* Sets maximum number of allowed steps (nmax) for driver */
d->nmax = nmax;
return GSL_SUCCESS;
}
gsl_odeiv2_driver *
gsl_odeiv2_driver_alloc_y_new (const gsl_odeiv2_system * sys,
const gsl_odeiv2_step_type * T,
const double hstart,
const double epsabs, const double epsrel)
{
/* Initializes an ODE driver system with control object of type y_new. */
gsl_odeiv2_driver *state = driver_alloc (sys, hstart, T);
if (state == NULL)
{
GSL_ERROR_NULL ("failed to allocate driver object", GSL_ENOMEM);
}
if (epsabs >= 0.0 && epsrel >= 0.0)
{
state->c = gsl_odeiv2_control_y_new (epsabs, epsrel);
if (state->c == NULL)
{
gsl_odeiv2_driver_free (state);
GSL_ERROR_NULL ("failed to allocate control object", GSL_ENOMEM);
}
}
else
{
gsl_odeiv2_driver_free (state);
GSL_ERROR_NULL ("epsabs and epsrel must be positive", GSL_EINVAL);
}
/* Distribute pointer to driver object */
gsl_odeiv2_step_set_driver (state->s, state);
gsl_odeiv2_evolve_set_driver (state->e, state);
gsl_odeiv2_control_set_driver (state->c, state);
return state;
}
gsl_odeiv2_driver *
gsl_odeiv2_driver_alloc_yp_new (const gsl_odeiv2_system * sys,
const gsl_odeiv2_step_type * T,
const double hstart,
const double epsabs, const double epsrel)
{
/* Initializes an ODE driver system with control object of type yp_new. */
gsl_odeiv2_driver *state = driver_alloc (sys, hstart, T);
if (state == NULL)
{
GSL_ERROR_NULL ("failed to allocate driver object", GSL_ENOMEM);
}
if (epsabs >= 0.0 && epsrel >= 0.0)
{
state->c = gsl_odeiv2_control_yp_new (epsabs, epsrel);
if (state->c == NULL)
{
gsl_odeiv2_driver_free (state);
GSL_ERROR_NULL ("failed to allocate control object", GSL_ENOMEM);
}
}
else
{
gsl_odeiv2_driver_free (state);
GSL_ERROR_NULL ("epsabs and epsrel must be positive", GSL_EINVAL);
}
/* Distribute pointer to driver object */
gsl_odeiv2_step_set_driver (state->s, state);
gsl_odeiv2_evolve_set_driver (state->e, state);
gsl_odeiv2_control_set_driver (state->c, state);
return state;
}
gsl_odeiv2_driver *
gsl_odeiv2_driver_alloc_standard_new (const gsl_odeiv2_system * sys,
const gsl_odeiv2_step_type * T,
const double hstart,
const double epsabs,
const double epsrel, const double a_y,
const double a_dydt)
{
/* Initializes an ODE driver system with control object of type
standard_new.
*/
gsl_odeiv2_driver *state = driver_alloc (sys, hstart, T);
if (state == NULL)
{
GSL_ERROR_NULL ("failed to allocate driver object", GSL_ENOMEM);
}
if (epsabs >= 0.0 && epsrel >= 0.0)
{
state->c =
gsl_odeiv2_control_standard_new (epsabs, epsrel, a_y, a_dydt);
if (state->c == NULL)
{
gsl_odeiv2_driver_free (state);
GSL_ERROR_NULL ("failed to allocate control object", GSL_ENOMEM);
}
}
else
{
gsl_odeiv2_driver_free (state);
GSL_ERROR_NULL ("epsabs and epsrel must be positive", GSL_EINVAL);
}
/* Distribute pointer to driver object */
gsl_odeiv2_step_set_driver (state->s, state);
gsl_odeiv2_evolve_set_driver (state->e, state);
gsl_odeiv2_control_set_driver (state->c, state);
return state;
}
gsl_odeiv2_driver *
gsl_odeiv2_driver_alloc_scaled_new (const gsl_odeiv2_system * sys,
const gsl_odeiv2_step_type * T,
const double hstart,
const double epsabs, const double epsrel,
const double a_y, const double a_dydt,
const double scale_abs[])
{
/* Initializes an ODE driver system with control object of type
scaled_new.
*/
gsl_odeiv2_driver *state = driver_alloc (sys, hstart, T);
if (state == NULL)
{
GSL_ERROR_NULL ("failed to allocate driver object", GSL_ENOMEM);
}
if (epsabs >= 0.0 && epsrel >= 0.0)
{
state->c = gsl_odeiv2_control_scaled_new (epsabs, epsrel, a_y, a_dydt,
scale_abs, sys->dimension);
if (state->c == NULL)
{
gsl_odeiv2_driver_free (state);
GSL_ERROR_NULL ("failed to allocate control object", GSL_ENOMEM);
}
}
else
{
gsl_odeiv2_driver_free (state);
GSL_ERROR_NULL ("epsabs and epsrel must be positive", GSL_EINVAL);
}
/* Distribute pointer to driver object */
gsl_odeiv2_step_set_driver (state->s, state);
gsl_odeiv2_evolve_set_driver (state->e, state);
gsl_odeiv2_control_set_driver (state->c, state);
return state;
}
int
gsl_odeiv2_driver_apply (gsl_odeiv2_driver * d, double *t,
const double t1, double y[])
{
/* Main driver function that evolves the system from t to t1. In
beginning vector y contains the values of dependent variables at
t. This function returns values at t=t1 in y. In case of
unrecoverable error, y and t contains the values after the last
successful step.
*/
int sign = 0;
d->n = 0;
/* Determine integration direction sign */
if (d->h > 0.0)
{
sign = 1;
}
else
{
sign = -1;
}
/* Check that t, t1 and step direction are sensible */
if (sign * (t1 - *t) < 0.0)
{
GSL_ERROR_NULL
("integration limits and/or step direction not consistent",
GSL_EINVAL);
}
/* Evolution loop */
while (sign * (t1 - *t) > 0.0)
{
int s = gsl_odeiv2_evolve_apply (d->e, d->c, d->s, d->sys,
t, t1, &(d->h), y);
if (s != GSL_SUCCESS)
{
return s;
}
/* Check for maximum allowed steps */
if ((d->nmax > 0) && (d->n > d->nmax))
{
return GSL_EMAXITER;
}
/* Set step size if maximum size is exceeded */
if (fabs (d->h) > d->hmax)
{
d->h = sign * d->hmax;
}
/* Check for too small step size */
if (fabs (d->h) < d->hmin)
{
return GSL_ENOPROG;
}
d->n++;
}
return GSL_SUCCESS;
}
int
gsl_odeiv2_driver_apply_fixed_step (gsl_odeiv2_driver * d, double *t,
const double h, const unsigned long int n,
double y[])
{
/* Alternative driver function that evolves the system from t using
* n steps of size h. In the beginning vector y contains the values
* of dependent variables at t. This function returns values at t =
* t + n * h in y. In case of an unrecoverable error, y and t
* contains the values after the last successful step.
*/
unsigned long int i;
d->n = 0;
/* Evolution loop */
for (i = 0; i < n; i++)
{
int s = gsl_odeiv2_evolve_apply_fixed_step (d->e, d->c, d->s, d->sys,
t, h, y);
if (s != GSL_SUCCESS)
{
return s;
}
d->n++;
}
return GSL_SUCCESS;
}
int
gsl_odeiv2_driver_reset (gsl_odeiv2_driver * d)
{
/* Reset the driver. Resets evolve and step objects. */
{
int s = gsl_odeiv2_evolve_reset (d->e);
if (s != GSL_SUCCESS)
{
return s;
}
}
{
int s = gsl_odeiv2_step_reset (d->s);
if (s != GSL_SUCCESS)
{
return s;
}
}
return GSL_SUCCESS;
}
int
gsl_odeiv2_driver_reset_hstart (gsl_odeiv2_driver * d, const double hstart)
{
/* Resets current driver and sets initial step size to hstart */
gsl_odeiv2_driver_reset (d);
if ((d->hmin > fabs (hstart)) || (fabs (hstart) > d->hmax))
{
GSL_ERROR_NULL ("hmin <= fabs(h) <= hmax required", GSL_EINVAL);
}
if (hstart > 0.0 || hstart < 0.0)
{
d->h = hstart;
}
else
{
GSL_ERROR_NULL ("invalid hstart", GSL_EINVAL);
}
return GSL_SUCCESS;
}
void
gsl_odeiv2_driver_free (gsl_odeiv2_driver * state)
{
if (state->c != NULL)
{
gsl_odeiv2_control_free (state->c);
}
gsl_odeiv2_evolve_free (state->e);
gsl_odeiv2_step_free (state->s);
free (state);
}
| {
"alphanum_fraction": 0.5928805237,
"avg_line_length": 24.8879837067,
"ext": "c",
"hexsha": "d0db988a592d6b17cff7dc141bb4e54db752df1f",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2015-10-02T01:32:59.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-10-02T01:32:59.000Z",
"max_forks_repo_head_hexsha": "2ad5bfb9c9684b1c800e96732a9e2f1e844b856f",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "ruslankuzmin/julia",
"max_forks_repo_path": "oldjuila/juliakernel/ext_libraries/gsl/ode-initval2/driver.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "2ad5bfb9c9684b1c800e96732a9e2f1e844b856f",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "ruslankuzmin/julia",
"max_issues_repo_path": "oldjuila/juliakernel/ext_libraries/gsl/ode-initval2/driver.c",
"max_line_length": 81,
"max_stars_count": 14,
"max_stars_repo_head_hexsha": "2ad5bfb9c9684b1c800e96732a9e2f1e844b856f",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "ruslankuzmin/julia",
"max_stars_repo_path": "oldjuila/juliakernel/ext_libraries/gsl/ode-initval2/driver.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": 3373,
"size": 12220
} |
#ifdef HAVE_CONFIG_H
#include "../config.h"
#endif /* HAVE_CONFIG_H */
#ifndef DO_WITH_GSL
/* This test is not performed */
int main()
{
return 0;
}
#else
#include <stdio.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
#include <gsl/gsl_histogram.h>
int main(void)
{
FILE* out_file; /* output stream*/
int i;
double cut_off;
double sigma;
const int sample_no=100000; /* sample numbers */
const int bin_no=100; /* number of bins in histogram */
gsl_histogram* my_hist;
gsl_rng* my_rng;
out_file=stdout;
my_hist=gsl_histogram_calloc_uniform(bin_no,-10,10);
my_rng=gsl_rng_alloc(gsl_rng_default);
sigma=1;
cut_off=-4;
fprintf(out_file,"plot '-' using 1:3 title '1st',");
fprintf(out_file,"'-' using 1:3 title '2nd',");
fprintf(out_file,"'-' using 1:3 title '3rd'\n");
while (cut_off<=4)
{
fprintf(out_file,"# cut_off %f, sigma %f\n",cut_off,sigma);
gsl_histogram_reset(my_hist);
for (i=0;i<sample_no;i++)
gsl_histogram_increment(my_hist,gsl_ran_gaussian_tail(my_rng,cut_off,sigma));
gsl_histogram_fprintf(out_file,my_hist,"%f","%f");
fprintf(out_file,"e\n");
cut_off+=4;
}
return 0;
}
#endif
| {
"alphanum_fraction": 0.6658333333,
"avg_line_length": 21.4285714286,
"ext": "c",
"hexsha": "5f61af109d36e9166463f43db530cd75f841bfe0",
"lang": "C",
"max_forks_count": 25,
"max_forks_repo_forks_event_max_datetime": "2020-12-29T13:23:10.000Z",
"max_forks_repo_forks_event_min_datetime": "2016-10-18T03:31:44.000Z",
"max_forks_repo_head_hexsha": "2ad5bfb9c9684b1c800e96732a9e2f1e844b856f",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "ruslankuzmin/julia",
"max_forks_repo_path": "Trash/sandbox/hmm/ghmm-0.9-rc3/tests/test_gsl_ran_gaussian_tail.c",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "2ad5bfb9c9684b1c800e96732a9e2f1e844b856f",
"max_issues_repo_issues_event_max_datetime": "2021-05-29T19:54:52.000Z",
"max_issues_repo_issues_event_min_datetime": "2021-05-29T19:54:02.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "ruslankuzmin/julia",
"max_issues_repo_path": "Trash/sandbox/hmm/ghmm-0.9-rc3/tests/test_gsl_ran_gaussian_tail.c",
"max_line_length": 78,
"max_stars_count": 7,
"max_stars_repo_head_hexsha": "2ad5bfb9c9684b1c800e96732a9e2f1e844b856f",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "ruslankuzmin/julia",
"max_stars_repo_path": "Trash/sandbox/hmm/ghmm-0.9-rc3/tests/test_gsl_ran_gaussian_tail.c",
"max_stars_repo_stars_event_max_datetime": "2021-09-27T16:51:22.000Z",
"max_stars_repo_stars_event_min_datetime": "2017-03-13T17:32:26.000Z",
"num_tokens": 357,
"size": 1200
} |
#ifndef __GSL_VECTOR_H__
#define __GSL_VECTOR_H__
#include <gsl/vector/gsl_vector_double.h>
#endif /* __GSL_VECTOR_H__ */
| {
"alphanum_fraction": 0.792,
"avg_line_length": 15.625,
"ext": "h",
"hexsha": "2b15303aede2fc801c85668d70ad625b6b1b8e86",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "58778f148e65749e1dfc443043e9fc054ca3ff4d",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "MontyThibault/centre-of-mass-awareness",
"max_forks_repo_path": "Cartwheel/cartwheel-3d/gsl/vector/gsl_vector.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "58778f148e65749e1dfc443043e9fc054ca3ff4d",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "MontyThibault/centre-of-mass-awareness",
"max_issues_repo_path": "Cartwheel/cartwheel-3d/gsl/vector/gsl_vector.h",
"max_line_length": 41,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "58778f148e65749e1dfc443043e9fc054ca3ff4d",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "MontyThibault/centre-of-mass-awareness",
"max_stars_repo_path": "Cartwheel/cartwheel-3d/gsl/vector/gsl_vector.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 34,
"size": 125
} |
/**
*
* @file pclarft_blgtrd.c
*
* PLASMA auxiliary routines
* PLASMA is a software package provided by Univ. of Tennessee,
* Univ. of California Berkeley and Univ. of Colorado Denver
*
* @version 2.6.0
* @author Azzam Haidar
@date 2011-05-15
* @generated c Tue Jan 7 11:45:13 2014
*
**/
#include "common.h"
#include <lapacke.h>
#define V(m) &(V[(m)])
#define TAU(m) &(TAU[(m)])
#define T(m) &(T[(m)])
/***************************************************************************/
/**
* Parallel compute T2 from bulgechasing of Symetric matrix - static scheduling
* Lower case is supported
**/
/***************************************************************************/
void plasma_pclarft_blgtrd(plasma_context_t *plasma)
{
int my_core_id = PLASMA_RANK;
int cores_num = plasma->world_size;
/*===========================*/
int N, NB,Vblksiz;
PLASMA_Complex32_t *V;
PLASMA_Complex32_t *T;
PLASMA_Complex32_t *TAU;
PLASMA_sequence *sequence;
PLASMA_request *request;
/*===========================
* local variables
*===========================*/
int LDT, LDV;
int Vm, Vn, mt, nt;
int myrow, mycol, blkj, blki;
int firstrow;
int blkid,vpos,taupos,tpos;
int blkpercore,blkcnt, myid;
plasma_unpack_args_8(N, NB, Vblksiz, V, T, TAU, sequence, request);
if (sequence->status != PLASMA_SUCCESS)
return;
/* Quick return */
if (N == 0){
return;
}
if (NB == 0){
return;
}
if (NB == 1){
return;
}
findVTsiz(N, NB, Vblksiz, &blkcnt, &LDV);
blkpercore = blkcnt/cores_num;
blkpercore = blkpercore==0 ? 1:blkpercore;
LDT = Vblksiz;
LDV = NB+Vblksiz-1;
/*========================================
* compute the T's in parallel.
* The Ts are independent so each core pick
* a T and compute it. The loop is based on
* the version 113 of the pcunmqr_blgtrd.c
* which go over the losange block_column
* by block column. but it is not important
* here the order because Ts are independent.
* ========================================
*/
nt = plasma_ceildiv((N-1),Vblksiz);
for (blkj=nt-1; blkj>=0; blkj--) {
/* the index of the first row on the top of block (blkj) */
firstrow = blkj * Vblksiz + 1;
/*find the number of tile for this block */
if( blkj == nt-1 )
mt = plasma_ceildiv( N - firstrow, NB);
else
mt = plasma_ceildiv( N - (firstrow+1), NB);
/*loop over the tiles find the size of the Vs and apply it */
for (blki=mt; blki>0; blki--) {
/*calculate the size of each losange of Vs= (Vm,Vn)*/
myrow = firstrow + (mt-blki)*NB;
mycol = blkj*Vblksiz;
Vm = min( NB+Vblksiz-1, N-myrow);
if( ( blkj == nt-1 ) && ( blki == mt ) ){
Vn = min (Vblksiz, Vm);
} else {
Vn = min (Vblksiz, Vm-1);
}
/*calculate the pointer to the Vs and the Ts.
* Note that Vs and Ts have special storage done
* by the bulgechasing function*/
findVTpos(N,NB,Vblksiz,mycol,myrow, &vpos, &taupos, &tpos, &blkid);
myid = blkid/blkpercore;
if( my_core_id==(myid%cores_num) ){
if( ( Vm > 0 ) && ( Vn > 0 ) ){
LAPACKE_clarft_work(LAPACK_COL_MAJOR,
lapack_const(PlasmaForward),
lapack_const(PlasmaColumnwise),
Vm, Vn, V(vpos), LDV, TAU(taupos), T(tpos), LDT);
}
}
}
}
}
#undef V
#undef TAU
#undef T
/***************************************************************************/
| {
"alphanum_fraction": 0.4843628845,
"avg_line_length": 31.4552845528,
"ext": "c",
"hexsha": "fa0c8abac2e99053e06b3acc1ddb47f86bb621a0",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "zhuangsc/Plasma-ompss1",
"max_forks_repo_path": "compute/pclarft_blgtrd.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "zhuangsc/Plasma-ompss1",
"max_issues_repo_path": "compute/pclarft_blgtrd.c",
"max_line_length": 83,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "zhuangsc/Plasma-ompss1",
"max_stars_repo_path": "compute/pclarft_blgtrd.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1101,
"size": 3869
} |
/*
* Licensed to the OpenAirInterface (OAI) Software Alliance under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The OpenAirInterface Software Alliance licenses this file to You under
* the OAI Public License, Version 1.1 (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.openairinterface.org/?page_id=698
*
* 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.
*-------------------------------------------------------------------------------
* For more information about the OpenAirInterface (OAI) Software Alliance:
* contact@openairinterface.org
*/
#include <string.h>
#include <math.h>
#include <unistd.h>
#include <stdint.h>
#include <stdio.h>
#include <time.h>
#include <cblas.h>
#include "SIMULATION/TOOLS/defs.h"
#include "SIMULATION/RF/defs.h"
#include "PHY/types.h"
#include "PHY/defs.h"
#include "PHY/extern.h"
#include "oaisim_config.h"
#ifdef OPENAIR2
#include "LAYER2/MAC/defs.h"
#include "LAYER2/MAC/extern.h"
#include "UTIL/LOG/log_if.h"
#include "UTIL/LOG/log_extern.h"
#include "RRC/LITE/extern.h"
#include "PHY_INTERFACE/extern.h"
#include "UTIL/OCG/OCG.h"
#include "UTIL/OMG/omg.h"
#include "UTIL/OPT/opt.h" // to test OPT
#endif
#include "SCHED/defs.h"
#include "SCHED/extern.h"
#include "oaisim.h"
#define PI 3.1416
#define Am 20
#define MCL (-70) /*minimum coupling loss (MCL) in dB*/
//double sinr[NUMBER_OF_eNB_MAX][2*25];
/*
extern double sinr_bler_map[MCS_COUNT][2][16];
extern double sinr_bler_map_up[MCS_COUNT][2][16];
double SINRpost_eff[301];
extern double MI_map_4qam[3][162];
extern double MI_map_16qam[3][197];
extern double MI_map_64qam[3][227];
*/
// Extract the positions of UE and ENB from the mobility model
void extract_position (node_list* input_node_list, node_desc_t **node_data, int nb_nodes)
{
int i;
for (i=0; i<nb_nodes; i++) {
if ((input_node_list != NULL) && (node_data[i] != NULL)) {
node_data[i]->x = input_node_list->node->x_pos;
if (node_data[i]->x <0.0)
node_data[i]->x = 0.0;
node_data[i]->y = input_node_list->node->y_pos;
if (node_data[i]->y <0.0)
node_data[i]->y = 0.0;
LOG_D(OCM, "extract_position: added node_data %d with position X: %f and Y: %f \n", i,input_node_list->node->x_pos, input_node_list->node->y_pos );
input_node_list = input_node_list->next;
} else {
LOG_E(OCM, "extract_position: Null pointer!!!\n");
//exit(-1);
}
}
}
void extract_position_fixed_enb (node_desc_t **node_data, int nb_nodes, frame_t frame)
{
int i;
for (i=0; i<nb_nodes; i++) {
if (i==0) {
node_data[i]->x = 0;
node_data[i]->y = 500;
} else if (i == 1 ) {
node_data[i]->x = 866;//
node_data[i]->y = 1000;
} else if (i == 2 ) {
node_data[i]->x = 866;
node_data[i]->y = 0;
}
}
}
void extract_position_fixed_ue (node_desc_t **node_data, int nb_nodes, frame_t frame)
{
int i;
if(frame<50)
for (i=0; i<nb_nodes; i++) {
if (i==0) {
node_data[i]->x = 2050;
node_data[i]->y = 1500;
} else {
node_data[i]->x = 2150;
node_data[i]->y = 1500;
}
}
else {
for (i=0; i<nb_nodes; i++) {
if (i==0) {
node_data[i]->x = 1856 - (frame - 49);
// if(node_data[i]->x > 2106)
// node_data[i]->x = 2106;
node_data[i]->y = 1813 + (frame - 49);
// if(node_data[i]->y < 1563)
// node_data[i]->y = 1563;
// if( node_data[i]->x == 2106)
// node_data[i]->x = 2106 - (frame - 49);
} else {
node_data[i]->x = 2106 - (frame - 49);
// if(node_data[i]->x < 1856)
// node_data[i]->x = 1856;
node_data[i]->y = 1563 + (frame - 49);
// if(node_data[i]->y < 1813)
// node_data[i]->y = 1813;
}
}
}
}
void init_ue(node_desc_t *ue_data, UE_Antenna ue_ant) //changed from node_struct
{
ue_data->n_sectors = 1;
ue_data->phi_rad = 2 * PI;
ue_data->ant_gain_dBi = ue_ant.antenna_gain_dBi;
ue_data->tx_power_dBm = ue_ant.tx_power_dBm;
ue_data->rx_noise_level = ue_ant.rx_noise_level_dB; //value in db
}
void init_enb(node_desc_t *enb_data, eNB_Antenna enb_ant) //changed from node_struct
{
int i;
double sect_angle[3]= {0,2*PI/3,4*PI/3};
enb_data->n_sectors = enb_ant.number_of_sectors;
for (i=0; i<enb_data->n_sectors; i++)
enb_data->alpha_rad[i] = sect_angle[i]; //enb_ant.alpha_rad[i];
enb_data->phi_rad = enb_ant.beam_width_dB;
enb_data->ant_gain_dBi = enb_ant.antenna_gain_dBi;
enb_data->tx_power_dBm = enb_ant.tx_power_dBm;
enb_data->rx_noise_level = enb_ant.rx_noise_level_dB;
}
void calc_path_loss(node_desc_t* enb_data, node_desc_t* ue_data, channel_desc_t *ch_desc, Environment_System_Config env_desc, double **Shad_Fad)
{
double dist;
double path_loss;
double gain_max;
double gain_sec[3];
double alpha, theta;
int count;
dist = sqrt(pow((enb_data->x - ue_data->x), 2) + pow((enb_data->y - ue_data->y), 2));
path_loss = env_desc.fading.free_space_model_parameters.pathloss_0_dB -
10*env_desc.fading.free_space_model_parameters.pathloss_exponent * log10(dist/1000);
LOG_D(OCM,"dist %f, Path loss %f\n",dist,ch_desc->path_loss_dB);
/* Calculating the angle in the range -pi to pi from the slope */
alpha = atan2((ue_data->y - enb_data->y),(ue_data->x - enb_data->x));
if (alpha < 0)
alpha += 2*PI;
//printf("angle in radians is %lf\n", ue_data[UE_id]->alpha_rad[eNB_id]);
ch_desc->aoa = alpha;
ch_desc->random_aoa = 0;
if (enb_data->n_sectors==1) //assume omnidirectional antenna
gain_max = 0;
else {
gain_max = -1000;
for(count = 0; count < enb_data->n_sectors; count++) {
theta = enb_data->alpha_rad[count] - alpha;
/* gain = -min(Am , 12 * (theta/theta_3dB)^2) */
gain_sec[count] = -(Am < (12 * pow((theta/enb_data->phi_rad),2)) ? Am : (12 * pow((theta/enb_data->phi_rad),2)));
if (gain_sec[count]>gain_max) //take the sector that we are closest too (or where the gain is maximum)
gain_max = gain_sec[count];
}
}
path_loss += enb_data->ant_gain_dBi + gain_max + ue_data->ant_gain_dBi;
if (Shad_Fad!=NULL)
path_loss += Shad_Fad[(int)ue_data->x][(int)ue_data->y];
ch_desc->path_loss_dB = MCL < path_loss ? MCL : path_loss;
//LOG_D(OCM,"x_coordinate\t%f\t,y_coordinate\t%f\t, path_loss %f\n",ue_data->x,ue_data->y,ch_desc->path_loss_dB);
}
void init_snr(channel_desc_t* eNB2UE, node_desc_t *enb_data, node_desc_t *ue_data, double* sinr_dB, double* N0, uint8_t transmission_mode, uint16_t q, uint8_t dl_power_off, uint16_t nb_rb)
{
double thermal_noise,abs_channel,channelx, channely,channelx_i, channely_i ;
int count;
int aarx,aatx;
uint8_t qq;
/* Thermal noise is calculated using 10log10(K*T*B) K = Boltzmann's constant T = room temperature B = bandwidth*/
thermal_noise = -174 + 10*log10(15000); //per RE; value in dBm
//for (aarx=0; aarx<eNB2UE->nb_rx; aarx++)
*N0 = thermal_noise + ue_data->rx_noise_level;
LOG_D(OCM,"Path loss %lf, noise (N0) %lf, signal %lf, snr %lf\n",
eNB2UE->path_loss_dB,
thermal_noise + ue_data->rx_noise_level,
enb_data->tx_power_dBm + eNB2UE->path_loss_dB,
enb_data->tx_power_dBm + eNB2UE->path_loss_dB - (thermal_noise + ue_data->rx_noise_level));
if(transmission_mode == 5 && dl_power_off==1)
transmission_mode = 6;
switch(transmission_mode) {
case 1:
//printf ("coupling factor is %lf\n", coupling);
for (count = 0; count < (12 * nb_rb); count++) {
sinr_dB[count] = enb_data->tx_power_dBm
+ eNB2UE->path_loss_dB
- (thermal_noise + ue_data->rx_noise_level)
+ 10 * log10 (pow(eNB2UE->chF[0][count].x, 2)
+ pow(eNB2UE->chF[0][count].y, 2));
//printf("sinr_dB[%d]: %1f\n",count,sinr_dB[count]);
//printf("Dl_link SNR for res. block %d is %lf\n", count, sinr[eNB_id][count]);
}
break;
case 2:
for (count = 0; count < (12 * nb_rb); count++) {
abs_channel=0;
for (aarx=0; aarx<eNB2UE->nb_rx; aarx++) {
for (aatx=0; aatx<eNB2UE->nb_tx; aatx++) {
abs_channel += (pow(eNB2UE->chF[aarx+(aatx*eNB2UE->nb_rx)][count].x, 2) + pow(eNB2UE->chF[aarx+(aatx*eNB2UE->nb_rx)][count].y, 2));
}
}
sinr_dB[count] = enb_data->tx_power_dBm
+ eNB2UE->path_loss_dB
- (thermal_noise + ue_data->rx_noise_level)
+ 10 * log10 (abs_channel/2);
// printf("sinr_dB[%d]: %1f\n",count,sinr_dB[count]);
}
break;
case 5:
for (count = 0; count < (12 * nb_rb); count++) {
channelx=0;
channely=0;
channelx_i=0;
channely_i=0;
qq = (q>>(((count/12)>>2)<<1))&3;
//printf("pmi_alloc %d: rb %d, pmi %d\n",q,count/12,qq);
// qq = q;
for (aarx=0; aarx<eNB2UE->nb_rx; aarx++) {
for (aatx=0; aatx<eNB2UE->nb_tx; aatx++) {
switch(qq) {
case 0:
if (channelx==0 || channely==0) {
channelx = eNB2UE->chF[aarx+(aatx*eNB2UE->nb_rx)][count].x;
channely = eNB2UE->chF[aarx+(aatx*eNB2UE->nb_rx)][count].y;
channelx_i = eNB2UE->chF[aarx+(aatx*eNB2UE->nb_rx)][count].x;
channely_i = eNB2UE->chF[aarx+(aatx*eNB2UE->nb_rx)][count].y;
} else {
channelx += eNB2UE->chF[aarx+(aatx*eNB2UE->nb_rx)][count].x;
channely += eNB2UE->chF[aarx+(aatx*eNB2UE->nb_rx)][count].y;
channelx_i -= eNB2UE->chF[aarx+(aatx*eNB2UE->nb_rx)][count].x;
channely_i -= eNB2UE->chF[aarx+(aatx*eNB2UE->nb_rx)][count].y;
}
break;
case 1:
if (channelx==0 || channely==0) {
channelx = eNB2UE->chF[aarx+(aatx*eNB2UE->nb_rx)][count].x;
channely = eNB2UE->chF[aarx+(aatx*eNB2UE->nb_rx)][count].y;
channelx_i = eNB2UE->chF[aarx+(aatx*eNB2UE->nb_rx)][count].x;
channely_i = eNB2UE->chF[aarx+(aatx*eNB2UE->nb_rx)][count].y;
} else {
channelx -= eNB2UE->chF[aarx+(aatx*eNB2UE->nb_rx)][count].x;
channely -= eNB2UE->chF[aarx+(aatx*eNB2UE->nb_rx)][count].y;
channelx_i += eNB2UE->chF[aarx+(aatx*eNB2UE->nb_rx)][count].x;
channely_i += eNB2UE->chF[aarx+(aatx*eNB2UE->nb_rx)][count].y;
}
break;
case 2:
if (channelx==0 || channely==0) {
channelx = eNB2UE->chF[aarx+(aatx*eNB2UE->nb_rx)][count].x;
channely = eNB2UE->chF[aarx+(aatx*eNB2UE->nb_rx)][count].y;
channelx_i = eNB2UE->chF[aarx+(aatx*eNB2UE->nb_rx)][count].x;
channely_i = eNB2UE->chF[aarx+(aatx*eNB2UE->nb_rx)][count].y;
} else {
channelx -= eNB2UE->chF[aarx+(aatx*eNB2UE->nb_rx)][count].y;
channely += eNB2UE->chF[aarx+(aatx*eNB2UE->nb_rx)][count].x;
channelx_i += eNB2UE->chF[aarx+(aatx*eNB2UE->nb_rx)][count].y;
channely_i -= eNB2UE->chF[aarx+(aatx*eNB2UE->nb_rx)][count].x;
}
break;
case 3:
if (channelx==0 || channely==0) {
channelx = eNB2UE->chF[aarx+(aatx*eNB2UE->nb_rx)][count].x;
channely = eNB2UE->chF[aarx+(aatx*eNB2UE->nb_rx)][count].y;
channelx_i = eNB2UE->chF[aarx+(aatx*eNB2UE->nb_rx)][count].x;
channely_i = eNB2UE->chF[aarx+(aatx*eNB2UE->nb_rx)][count].y;
} else {
channelx += eNB2UE->chF[aarx+(aatx*eNB2UE->nb_rx)][count].y;
channely -= eNB2UE->chF[aarx+(aatx*eNB2UE->nb_rx)][count].x;
channelx_i -= eNB2UE->chF[aarx+(aatx*eNB2UE->nb_rx)][count].y;
channely_i += eNB2UE->chF[aarx+(aatx*eNB2UE->nb_rx)][count].x;
}
break;
default:
LOG_E(EMU,"Problem in SINR Calculation for TM5 \n");
break;
}//switch(q)
}//aatx
}//aarx
/* sinr_dB[count] = enb_data->tx_power_dBm
+ eNB2UE->path_loss_dB
- (thermal_noise + ue_data->rx_noise_level)
+ 10 * log10 ((pow(channelx,2) + pow(channely,2))/2) - 10 * log10 ((pow(channelx_i,2) + pow(channely_i,2))/2);
*/
sinr_dB[count] = enb_data->tx_power_dBm
+ eNB2UE->path_loss_dB
- (thermal_noise + ue_data->rx_noise_level)
+ 10 * log10 ((pow(channelx,2) + pow(channely,2))) - 10 * log10 ((pow(channelx_i,2) + pow(channely_i,2))) - 3; // 3dB is subtracted as the tx_power_dBm is to be adjusted on per user basis
// printf("sinr_dB[%d]: %1f\n",count,sinr_dB[count]);
}
break;
case 6:
for (count = 0; count < (12 * nb_rb); count++) {
channelx=0;
channely=0;
qq = (q>>(((count/12)>>2)<<1))&3;
//printf("pmi_alloc %d: rb %d, pmi %d\n",q,count/12,qq);
// qq = q;
for (aarx=0; aarx<eNB2UE->nb_rx; aarx++) {
for (aatx=0; aatx<eNB2UE->nb_tx; aatx++) {
switch(qq) {
case 0:
if (channelx==0 || channely==0) {
channelx = eNB2UE->chF[aarx+(aatx*eNB2UE->nb_rx)][count].x;
channely = eNB2UE->chF[aarx+(aatx*eNB2UE->nb_rx)][count].y;
} else {
channelx += eNB2UE->chF[aarx+(aatx*eNB2UE->nb_rx)][count].x;
channely += eNB2UE->chF[aarx+(aatx*eNB2UE->nb_rx)][count].y;
}
break;
case 1:
if (channelx==0 || channely==0) {
channelx = eNB2UE->chF[aarx+(aatx*eNB2UE->nb_rx)][count].x;
channely = eNB2UE->chF[aarx+(aatx*eNB2UE->nb_rx)][count].y;
} else {
channelx -= eNB2UE->chF[aarx+(aatx*eNB2UE->nb_rx)][count].x;
channely -= eNB2UE->chF[aarx+(aatx*eNB2UE->nb_rx)][count].y;
}
break;
case 2:
if (channelx==0 || channely==0) {
channelx = eNB2UE->chF[aarx+(aatx*eNB2UE->nb_rx)][count].x;
channely = eNB2UE->chF[aarx+(aatx*eNB2UE->nb_rx)][count].y;
} else {
channelx -= eNB2UE->chF[aarx+(aatx*eNB2UE->nb_rx)][count].y;
channely += eNB2UE->chF[aarx+(aatx*eNB2UE->nb_rx)][count].x;
}
break;
case 3:
if (channelx==0 || channely==0) {
channelx = eNB2UE->chF[aarx+(aatx*eNB2UE->nb_rx)][count].x;
channely = eNB2UE->chF[aarx+(aatx*eNB2UE->nb_rx)][count].y;
} else {
channelx += eNB2UE->chF[aarx+(aatx*eNB2UE->nb_rx)][count].y;
channely -= eNB2UE->chF[aarx+(aatx*eNB2UE->nb_rx)][count].x;
}
break;
default:
LOG_E(EMU,"Problem in SINR Calculation for TM6 \n");
break;
}//switch(q)
}//aatx
}//aarx
sinr_dB[count] = enb_data->tx_power_dBm
+ eNB2UE->path_loss_dB
- (thermal_noise + ue_data->rx_noise_level)
+ 10 * log10 ((pow(channelx,2) + pow(channely,2))/2);
// printf("sinr_dB[%d]: %1f\n",count,sinr_dB[count]);
}
break;
default:
LOG_E(EMU,"Problem in SINR Initialization in sinr_sim.c\n");
break;
}//switch
}//function ends
void calculate_sinr(channel_desc_t* eNB2UE, node_desc_t *enb_data, node_desc_t *ue_data, double *sinr_dB, uint16_t nb_rb)
{
double sir, thermal_noise;
short count;
/* Thermal noise is calculated using 10log10(K*T*B) K = Boltzmann's constant T = room temperature B = bandwidth */
thermal_noise = -174 + 10*log10(15000); //per RE, value in dBm
for (count = 0; count < 12 * nb_rb; count++) {
sir = enb_data->tx_power_dBm
+ eNB2UE->path_loss_dB
- (thermal_noise + ue_data->rx_noise_level)
+ 10 * log10 (pow(eNB2UE->chF[0][count].x, 2)
+ pow(eNB2UE->chF[0][count].y, 2));
if (sir > 0)
sinr_dB[count] -= sir;
//printf("*****sinr% lf \n",sinr_dB[count]);
}
}
void get_beta_map()
{
char *file_path = NULL;
//int table_len = 0;
int t,u;
int mcs = 0;
char *sinr_bler;
char buffer[1000];
FILE *fp;
double perf_array[13];
file_path = (char*) malloc(512);
for (mcs = 0; mcs < MCS_COUNT; mcs++) {
snprintf( file_path, 512, "%s/SIMULATION/LTE_PHY/BLER_SIMULATIONS/AWGN/AWGN_results/bler_tx1_chan18_nrx1_mcs%d.csv", getenv("OPENAIR1_DIR"), mcs );
fp = fopen(file_path,"r");
if (fp == NULL) {
LOG_E(OCM,"ERROR: Unable to open the file %s! Exitng.\n", file_path);
exit(-1);
}
// else {
if (fgets (buffer, 1000, fp) != NULL) {
if (fgets (buffer, 1000, fp) != NULL) {
table_length[mcs] = 0;
while (!feof (fp)) {
u = 0;
sinr_bler = strtok (buffer, ";");
while (sinr_bler != NULL) {
perf_array[u] = atof (sinr_bler);
u++;
sinr_bler = strtok (NULL, ";");
}
if ((perf_array[4] / perf_array[5]) < 1) {
sinr_bler_map[mcs][0][table_length[mcs]] = perf_array[0];
sinr_bler_map[mcs][1][table_length[mcs]] = (perf_array[4] / perf_array[5]);
table_length[mcs]++;
if (table_length[mcs]>MCS_TABLE_LENGTH_MAX) {
LOG_E(OCM,"Error reading MCS table. Increase MCS_TABLE_LENGTH_MAX (mcs %d)!\n",mcs);
exit(-1);
}
}
if (fgets (buffer, 1000, fp) != NULL) {
}
}
}
}
fclose(fp);
// }
LOG_D(OCM,"Print the table for mcs %d\n",mcs);
for (t = 0; t<table_length[mcs]; t++)
LOG_D(OCM,"%lf %lf \n ",sinr_bler_map[mcs][0][t],sinr_bler_map[mcs][1][t]);
}
free(file_path);
}
//this function reads and stores the Mutual information tables for the MIESM abstraction.
void get_MIESM_param()
{
char *file_path = NULL;
char buffer[10000];
FILE *fp;
int qam[3] = {4,16,64};
int q,cnt;
char *result = NULL;
int table_len=0;
int t;
file_path = (char*) malloc(512);
for (q=0; q<3; q++) {
sprintf(file_path,"%s/SIMU/USER/files/MI_%dqam.csv",getenv("OPENAIR_TARGETS"),qam[q]);
fp = fopen(file_path,"r");
if (fp == NULL) {
printf("ERROR: Unable to open the file %s\n", file_path);
exit(-1);
} else {
cnt=-1;
switch(qam[q]) {
case 4:
while (!feof(fp)) {
table_len =0;
cnt++;
if (fgets(buffer, 10000, fp) != NULL) {
result = strtok (buffer, ",");
while (result != NULL) {
MI_map_4qam[cnt][table_len] = atof (result);
result = strtok (NULL, ",");
table_len++;
}
}
}
for (t = 0; t < 162; t++) {
// MI_map_4Qam[0][t] = pow(10,0.1*(MI_map_4Qam[0][t]));
LOG_D(OCM, "MIESM 4QAM Table: %lf %lf %1f\n ",MI_map_4qam[0][t],MI_map_4qam[1][t], MI_map_4qam[2][t]);
// printf("MIESM 4QAM Table: %lf %lf %1f\n ",MI_map_4qam[0][t],MI_map_4qam[1][t], MI_map_4qam[2][t]);
}
break;
case 16:
while (!feof(fp)) {
table_len =0;
cnt++;
if (fgets (buffer, 10000, fp) != NULL) {
result = strtok (buffer, ",");
while (result != NULL) {
MI_map_16qam[cnt][table_len] = atof (result);
result = strtok (NULL, ",");
table_len++;
}
}
}
for (t = 0; t < 197; t++) {
// MI_map_16Qam[0][t] = pow(10,0.1*(MI_map_16Qam[0][t]));
LOG_D(OCM, "MIESM 16 QAM Table: %lf %lf %1f\n ",MI_map_16qam[0][t],MI_map_16qam[1][t], MI_map_16qam[2][t]);
// printf("MIESM 16 QAM Table: %lf %lf %1f\n ",MI_map_16qam[0][t],MI_map_16qam[1][t], MI_map_16qam[2][t]);
}
break;
case 64:
while (!feof(fp)) {
table_len=0;
cnt++;
if(cnt==3)
break;
if (fgets (buffer, 10000, fp) != NULL) {
result = strtok(buffer, ",");
while (result != NULL) {
MI_map_64qam[cnt][table_len]= atof(result);
result = strtok(NULL, ",");
table_len++;
}
}
}
for (t = 0; t < 227; t++) {
//MI_map_64Qam[0][t] = pow(10,0.1*(MI_map_64Qam[0][t]));
LOG_D(OCM, "MIESM 64QAM Table: %lf %lf %1f\n ",MI_map_64qam[0][t],MI_map_64qam[1][t], MI_map_64qam[2][t]);
// printf("MIESM 64QAM Table: %lf %lf %1f\n ",MI_map_64qam[0][t],MI_map_64qam[1][t], MI_map_64qam[2][t]);
}
break;
default:
LOG_E(EMU,"Error, bad input, quitting\n");
break;
}
}
fclose(fp);
}
free(file_path);
}
| {
"alphanum_fraction": 0.5609493493,
"avg_line_length": 31.3685756241,
"ext": "c",
"hexsha": "7c752ce432f2b268cc7d11b2efd1f770a2c2482b",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2019-06-07T13:49:42.000Z",
"max_forks_repo_forks_event_min_datetime": "2019-06-07T13:49:42.000Z",
"max_forks_repo_head_hexsha": "a082c3e8af06cd7583c003a69ec517eb73d175b3",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "davidraditya/OAI-Powder",
"max_forks_repo_path": "targets/SIMU/USER/sinr_sim.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "a082c3e8af06cd7583c003a69ec517eb73d175b3",
"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": "davidraditya/OAI-Powder",
"max_issues_repo_path": "targets/SIMU/USER/sinr_sim.c",
"max_line_length": 210,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "a082c3e8af06cd7583c003a69ec517eb73d175b3",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "davidraditya/OAI-Powder",
"max_stars_repo_path": "targets/SIMU/USER/sinr_sim.c",
"max_stars_repo_stars_event_max_datetime": "2021-06-16T00:00:04.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-06-16T00:00:04.000Z",
"num_tokens": 7152,
"size": 21362
} |
// Copyright (c) 2013-2014 Anton Kozhevnikov, Thomas Schulthess
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are permitted provided that
// the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the
// following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions
// and the following disclaimer in the documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
// PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
/** \file utils.h
*
* \brief Contains definition and partial implementation of sirius::Utils class.
*/
#ifndef __UTILS_H__
#define __UTILS_H__
#include <gsl/gsl_sf_erf.h>
#include <fstream>
#include <string>
#include <complex>
#include "sirius_internal.h"
#include "typedefs.h"
#include "constants.h"
#include "sddk.hpp"
/// Utility class.
class Utils
{
public:
/// Maximum number of \f$ \ell, m \f$ combinations for a given \f$ \ell_{max} \f$
static inline int lmmax(int lmax)
{
return (lmax + 1) * (lmax + 1);
}
static inline int lm_by_l_m(int l, int m)
{
return (l * l + l + m);
}
static inline int lmax_by_lmmax(int lmmax__)
{
int lmax = int(std::sqrt(double(lmmax__)) + 1e-8) - 1;
if (lmmax(lmax) != lmmax__) {
TERMINATE("wrong lmmax");
}
return lmax;
}
static inline bool file_exists(const std::string file_name)
{
std::ifstream ifs(file_name.c_str());
return ifs.is_open();
}
static inline double fermi_dirac_distribution(double e)
{
double kT = 0.001;
if (e > 100 * kT) return 0.0;
if (e < -100 * kT) return 1.0;
return (1.0 / (exp(e / kT) + 1.0));
}
static inline double gaussian_smearing(double e, double delta)
{
return 0.5 * (1 - gsl_sf_erf(e / delta));
}
static inline double cold_smearing(double e)
{
double a = -0.5634;
if (e < -10.0) return 1.0;
if (e > 10.0) return 0.0;
return 0.5 * (1 - gsl_sf_erf(e)) - 1 - 0.25 * exp(-e * e) * (a + 2 * e - 2 * a * e * e) / sqrt(pi);
}
static std::string double_to_string(double val, int precision = -1)
{
char buf[100];
double abs_val = std::abs(val);
if (precision == -1)
{
if (abs_val > 1.0)
{
precision = 6;
}
else if (abs_val > 1e-14)
{
precision = int(-std::log(abs_val) / std::log(10.0)) + 7;
}
else
{
return std::string("0.0");
}
}
std::stringstream fmt;
fmt << "%." << precision << "f";
int len = snprintf(buf, 100, fmt.str().c_str(), val);
for (int i = len - 1; i >= 1; i--)
{
if (buf[i] == '0' && buf[i - 1] == '0')
{
buf[i] = 0;
}
else
{
break;
}
}
return std::string(buf);
}
static inline double phi_by_sin_cos(double sinp, double cosp)
{
double phi = std::atan2(sinp, cosp);
if (phi < 0) {
phi += twopi;
}
return phi;
}
static inline long double factorial(int n)
{
assert(n >= 0);
long double result = 1.0L;
for (int i = 1; i <= n; i++) {
result *= i;
}
return result;
}
/// Simple hash function.
/** Example: printf("hash: %16llX\n", hash()); */
static uint64_t hash(void const* buff, size_t size, uint64_t h = 5381)
{
unsigned char const* p = static_cast<unsigned char const*>(buff);
for(size_t i = 0; i < size; i++) {
h = ((h << 5) + h) + p[i];
}
return h;
}
static void write_matrix(const std::string& fname,
mdarray<double_complex, 2>& matrix,
int nrow,
int ncol,
bool write_upper_only = true,
bool write_abs_only = false,
std::string fmt = "%18.12f")
{
static int icount = 0;
if (nrow < 0 || nrow > (int)matrix.size(0) || ncol < 0 || ncol > (int)matrix.size(1))
TERMINATE("wrong number of rows or columns");
icount++;
std::stringstream s;
s << icount;
std::string full_name = s.str() + "_" + fname;
FILE* fout = fopen(full_name.c_str(), "w");
for (int icol = 0; icol < ncol; icol++)
{
fprintf(fout, "column : %4i\n", icol);
for (int i = 0; i < 80; i++) fprintf(fout, "-");
fprintf(fout, "\n");
if (write_abs_only)
{
fprintf(fout, " row, absolute value\n");
}
else
{
fprintf(fout, " row, real part, imaginary part, absolute value\n");
}
for (int i = 0; i < 80; i++) fprintf(fout, "-");
fprintf(fout, "\n");
int max_row = (write_upper_only) ? std::min(icol, nrow - 1) : (nrow - 1);
for (int j = 0; j <= max_row; j++)
{
if (write_abs_only)
{
std::string s = "%4i " + fmt + "\n";
fprintf(fout, s.c_str(), j, abs(matrix(j, icol)));
}
else
{
fprintf(fout, "%4i %18.12f %18.12f %18.12f\n", j, real(matrix(j, icol)), imag(matrix(j, icol)),
abs(matrix(j, icol)));
}
}
fprintf(fout,"\n");
}
fclose(fout);
}
static void write_matrix(std::string const& fname,
bool write_all,
mdarray<double, 2>& matrix)
{
static int icount = 0;
icount++;
std::stringstream s;
s << icount;
std::string full_name = s.str() + "_" + fname;
FILE* fout = fopen(full_name.c_str(), "w");
for (int icol = 0; icol < (int)matrix.size(1); icol++)
{
fprintf(fout, "column : %4i\n", icol);
for (int i = 0; i < 80; i++) fprintf(fout, "-");
fprintf(fout, "\n");
fprintf(fout, " row\n");
for (int i = 0; i < 80; i++) fprintf(fout, "-");
fprintf(fout, "\n");
int max_row = (write_all) ? ((int)matrix.size(0) - 1) : std::min(icol, (int)matrix.size(0) - 1);
for (int j = 0; j <= max_row; j++)
{
fprintf(fout, "%4i %18.12f\n", j, matrix(j, icol));
}
fprintf(fout,"\n");
}
fclose(fout);
}
static void write_matrix(std::string const& fname,
bool write_all,
matrix<double_complex> const& mtrx)
{
static int icount = 0;
icount++;
std::stringstream s;
s << icount;
std::string full_name = s.str() + "_" + fname;
FILE* fout = fopen(full_name.c_str(), "w");
for (int icol = 0; icol < (int)mtrx.size(1); icol++)
{
fprintf(fout, "column : %4i\n", icol);
for (int i = 0; i < 80; i++) fprintf(fout, "-");
fprintf(fout, "\n");
fprintf(fout, " row\n");
for (int i = 0; i < 80; i++) fprintf(fout, "-");
fprintf(fout, "\n");
int max_row = (write_all) ? ((int)mtrx.size(0) - 1) : std::min(icol, (int)mtrx.size(0) - 1);
for (int j = 0; j <= max_row; j++)
{
fprintf(fout, "%4i %18.12f %18.12f\n", j, real(mtrx(j, icol)), imag(mtrx(j, icol)));
}
fprintf(fout,"\n");
}
fclose(fout);
}
template <typename T>
static void check_hermitian(const std::string& name, matrix<T> const& mtrx, int n = -1)
{
assert(mtrx.size(0) == mtrx.size(1));
double maxdiff = 0.0;
int i0 = -1;
int j0 = -1;
if (n == -1) {
n = static_cast<int>(mtrx.size(0));
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
double diff = std::abs(mtrx(i, j) - type_wrapper<T>::conjugate(mtrx(j, i)));
if (diff > maxdiff) {
maxdiff = diff;
i0 = i;
j0 = j;
}
}
}
if (maxdiff > 1e-10) {
std::stringstream s;
s << name << " is not a symmetric or hermitian matrix" << std::endl
<< " maximum error: i, j : " << i0 << " " << j0 << " diff : " << maxdiff;
WARNING(s);
}
}
template <typename T>
static inline double check_hermitian(dmatrix<T>& mtrx__, int n__)
{
dmatrix<T> tmp(n__, n__, mtrx__.blacs_grid(), mtrx__.bs_row(), mtrx__.bs_col());
linalg<CPU>::tranc(n__, n__, mtrx__, 0, 0, tmp, 0, 0);
splindex<block_cyclic> spl_r(n__, mtrx__.blacs_grid().num_ranks_row(), mtrx__.blacs_grid().rank_row(), mtrx__.bs_row());
splindex<block_cyclic> spl_c(n__, mtrx__.blacs_grid().num_ranks_col(), mtrx__.blacs_grid().rank_col(), mtrx__.bs_col());
double max_diff{0};
for (int i = 0; i < spl_c.local_size(); i++) {
for (int j = 0; j < spl_r.local_size(); j++) {
max_diff = std::max(max_diff, std::abs(mtrx__(j, i) - tmp(j, i)));
}
}
mtrx__.blacs_grid().comm().template allreduce<double, mpi_op_t::max>(&max_diff, 1);
return max_diff;
}
static double confined_polynomial(double r, double R, int p1, int p2, int dm)
{
double t = 1.0 - std::pow(r / R, 2);
switch (dm)
{
case 0: {
return (std::pow(r, p1) * std::pow(t, p2));
}
case 2: {
return (-4 * p1 * p2 * std::pow(r, p1) * std::pow(t, p2 - 1) / std::pow(R, 2) +
p1 * (p1 - 1) * std::pow(r, p1 - 2) * std::pow(t, p2) +
std::pow(r, p1) * (4 * (p2 - 1) * p2 * std::pow(r, 2) * std::pow(t, p2 - 2) / std::pow(R, 4) -
2 * p2 * std::pow(t, p2 - 1) / std::pow(R, 2)));
}
default: {
TERMINATE("wrong derivative order");
return 0.0;
}
}
}
static std::vector<int> l_by_lm(int lmax)
{
std::vector<int> v(lmmax(lmax));
for (int l = 0; l <= lmax; l++) {
for (int m = -l; m <= l; m++) {
v[lm_by_l_m(l, m)] = l;
}
}
return std::move(v);
}
static std::vector<std::pair<int, int>> l_m_by_lm(int lmax)
{
std::vector<std::pair<int, int>> v(lmmax(lmax));
for (int l = 0; l <= lmax; l++) {
for (int m = -l; m <= l; m++) {
int lm = lm_by_l_m(l, m);
v[lm].first = l;
v[lm].second = m;
}
}
return std::move(v);
}
inline static double round(double a__, int n__)
{
double a0 = std::floor(a__);
double b = std::round((a__ - a0) * std::pow(10, n__)) / std::pow(10, n__);
return a0 + b;
}
template <typename T>
inline static int sign(T val)
{
return (T(0) < val) - (val < T(0));
}
static json serialize_timers() // TODO: here in wrong place; move somewhere else
{
json dict;
/* collect local timers */
for (auto& it: sddk::timer::timers()) {
sddk::timer::timer_stats ts;
ts.count = static_cast<int>(it.second.size());
ts.total_value = 0.0;
ts.min_value = 1e100;
ts.max_value = 0.0;
for (int i = 0; i < ts.count; i++) {
ts.total_value += it.second[i];
ts.min_value = std::min(ts.min_value, it.second[i]);
ts.max_value = std::max(ts.max_value, it.second[i]);
}
ts.average_value = (ts.count == 0) ? 0.0 : ts.total_value / ts.count;
if (ts.count == 0) {
ts.min_value = 0.0;
}
dict[it.first] = {ts.total_value, ts.average_value, ts.min_value, ts.max_value};
}
return std::move(dict);
}
};
#endif
| {
"alphanum_fraction": 0.4346539315,
"avg_line_length": 34.8990610329,
"ext": "h",
"hexsha": "ed00cdd80c7e3648a62d82aa80b883f70f16d7f6",
"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": "8ab09ca7cc69e9a7dc76475b7b562b20d56deea3",
"max_forks_repo_licenses": [
"BSD-2-Clause"
],
"max_forks_repo_name": "cocteautwins/SIRIUS-develop",
"max_forks_repo_path": "src/utils.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "8ab09ca7cc69e9a7dc76475b7b562b20d56deea3",
"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": "cocteautwins/SIRIUS-develop",
"max_issues_repo_path": "src/utils.h",
"max_line_length": 132,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "8ab09ca7cc69e9a7dc76475b7b562b20d56deea3",
"max_stars_repo_licenses": [
"BSD-2-Clause"
],
"max_stars_repo_name": "cocteautwins/SIRIUS-develop",
"max_stars_repo_path": "src/utils.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 3684,
"size": 14867
} |
#ifndef NUFFTW_PLAN_H
#define NUFFTW_PLAN_H
#include <complex>
#include <cmath>
#include <limits> // st::numeric_limits
#include <algorithm> // std::max
#include <gsl/gsl_sf_bessel.h> // Bessel functions
#include <gsl/gsl_sf_lambert.h> // Lambert W functions
#include <fftw3.h>
#include "timer.h"
namespace nufftw
{
using namespace std::complex_literals;
typedef std::complex<double> complex;
struct options
{
double tol = std::numeric_limits<double>::epsilon();
unsigned int fftw_flags = FFTW_ESTIMATE;
};
namespace details
{
void cheb_vals(int n, int p, const double* x, double* vals);
void bessel_coeffs(int r, double gam, complex* cfs);
}
class plan_base
{
public:
plan_base(const int* ns_, complex* in_, complex* out_, const options& opts_ = options()) :
in(in_), out(out_), opts(opts_)
{
n=1;
for (int i=0; i<N; ++i) {
ns[i]=ns_[i];
n*=ns[i];
}
}
virtual ~plan_base()
{
fftw_destroy_plan(fp);
}
virtual void execute() = 0;
protected:
int m; // Number of nonuniform points
int ns[N]; // Size of the problem in each dimension
int n; // Total size of the problem
complex* in; // Input coefficients
complex* out; // Output values
fftw_plan fp; // FFTW plans
options opts; // Options
double gam; // Perturbation parameter
int r; // Rank parameter
};
class plan1 : public plan_base<N>
{
public:
plan1(const int* n_, complex* in_, complex* out_, const double* omega_, const options& opts_ = options()) :
plan_base<N>(n_, in_, out_, opts_), omega(omega_)
{}
virtual ~plan1();
virtual void execute();
protected:
const double* omega;
plan1<1>* plans;
};
class plan1_2d : public plan_base
{
};
class plan1_1d : public plan_base
{
public:
plan1(int n_, complex* in_, complex* out_, const double* omega_, const options& opts_ = options()) :
plan_base<1>(&n_, in_, out_, opts_), omega(omega_), t(new int[n]),
er(new double[n]), temp(new double[n])
{
timer::tic();
gam = 0;
for (int i=0; i<n; ++i) {
int s = std::round(omega[i]);
t[i] = s%n;
er[i] = omega[i]-s;
gam = std::max(gam, std::abs(er[i]));
}
timer::toc("Compute gamma");
timer::tic();
r = 1;
if (gam>opts.tol) {
// Asymptotic approximation to Lambert-W:
// double xi = std::log(std::log(10./opts.tol)/(7.*gam);
// double log_xi=std::log(xi), inv_xi=1./xi;
// double lw = xi-log_xi*(1+inv_xi*(1+inv_xi*(0.5*log_xi-1)));
double lw = gsl_sf_lambert_W0(std::log(10./opts.tol)/(7.*gam));
r = std::ceil(5.*gam*std::exp(lw));
}
timer::toc("Compute r");
timer::tic();
// Plan the FFTs
fft_data = reinterpret_cast<complex*>(fftw_alloc_complex(n*r));
// int stride = r;
int stride = 1;
// int dist = 1;
int dist = n;
fp = fftw_plan_many_dft(1, &n, r,
reinterpret_cast<fftw_complex*>(fft_data), NULL, stride, dist,
reinterpret_cast<fftw_complex*>(fft_data), NULL, stride, dist,
FFTW_BACKWARD, opts.fftw_flags
);
timer::toc("Plan the FFTs");
// Construct a low rank approximation, using Chebyshev expansions
// for A_K = exp(-2*pi*1im*(x[j]-j/N)*k):
// Construct a low rank approximation to
// A_{jk} = exp(-2*pi*1i*(x_j-s_j/N)*k), 0<=j,k<=N-1,
// where |x_j-j/N|<= gam <=1/2. See [1].
u = new complex[n*r];
v = new double[n*r];
// Compute u
timer::tic();
double* cheb = new double[n*r];
complex* bess = new complex[r*r];
timer::tic();
double fac = 1./gam;
for (int i=0; i<n; ++i) temp[i]=er[i]*fac;
details::cheb_vals(n, r, temp, cheb);
timer::toc("Chebyshev");
timer::tic();
details::bessel_coeffs(r, gam, bess);
timer::toc("Bessel");
timer::tic();
for (int i=0; i<n; ++i) {
complex scl = std::exp(-1i*M_PI*er[i]);
for (int j=0; j<r; ++j) {
u[r*i+j]=0;
for (int k=0; k<r; ++k) {
u[r*i+j]+=cheb[r*i+k]*bess[r*j+k];
}
u[r*i+j]*=scl;
}
}
timer::toc("Matrix multiply");
delete [] bess;
delete [] cheb;
timer::toc("Compute u");
// Compute v
timer::tic();
fac = 2./n;
temp[0]=-1;
for (int i=1; i<n; ++i) temp[i]=temp[i-1]+fac;
details::cheb_vals(n, r, temp, v);
timer::toc("Compute v");
}
virtual ~plan1()
{
delete [] t;
delete [] er;
delete [] u;
delete [] v;
delete [] temp;
fftw_free(reinterpret_cast<fftw_complex*>(fft_data));
}
virtual void execute()
{
for (int i=0; i<n*r; ++i) fft_data[i]=0;
for (int i=0; i<n; ++i) {
for (int j=0; j<r; ++j) {
// fft_data[r*t[i]+j] += std::conj(in[i]*u[r*i+j]);
fft_data[n*j+t[i]] += std::conj(in[i]*u[r*i+j]);
}
}
// Do the FFTs
timer::tic();
fftw_execute(fp); // normalize?
timer::toc("Call FFTW");
for (int i=0; i<n; ++i) {
out[i]=0;
for (int j=0; j<r; ++j) {
// out[i] += v[r*i+j]*std::conj(fft_data[r*i+j]);
out[i] += v[r*i+j]*std::conj(fft_data[n*j+i]);
}
}
}
protected:
const double* omega; // FFT samples
int* t; // Closest equispaced FFT samples to omega
double* er; // Perturbation error
complex* u; // Low rank approximation
double* v; // Low rank approximation
double* temp; // Temporary storage
complex* fft_data; // Data for FFTW
};
// template<int N>
// class plan2 : public plan_base<N>
// {
// public:
// plan2();
// virtual ~plan2();
// };
// template<>
// class plan2<1> : public plan_base<1>
// {
// public:
// plan2();
// virtual ~plan2();
// };
// template<int N>
// class plan3 : public plan_base<N>
// {
// public:
// plan3();
// virtual ~plan3();
// };
// template<>
// class plan3<1> : public plan_base<1>
// {
// public:
// plan3();
// virtual ~plan3();
// };
typedef plan_base* plan;
// Methods for planning
template<int N>
void destroy_plan(plan<N> p)
{
if (p) delete p;
}
template<int N>
void execute(const plan<N> p)
{
p->execute();
}
namespace details
{
/** Evaluate Chebyshev polynomials of degree 0,...,p-1 at x.
* (row-major order) */
void cheb_vals(int n, int p, const double* x, double* vals)
{
for (int i=0; i<n; ++i) {
vals[p*i]=1;
vals[p*i+1]=x[i];
}
for (int i=0; i<n; ++i) {
for (int j=1; j<p-1; ++j) {
vals[p*i+(j+1)] = 2.*x[i]*vals[p*i+j] - vals[p*i+(j-1)];
}
}
}
/** The bivarate Chebyshev coefficients for the function
* f(x,y) = exp(-i*x.*y) on the domain [-gam, gam]x[0,2*pi], as given
* by Lemma A.2 of Townsend's DPhil thesis. (column-major order) */
void bessel_coeffs(int r, double gam, complex* cfs)
{
double arg = -0.5*gam*M_PI;
for (int p=0; p<r; ++p) {
for (int q=p%2; q<r; q+=2) {
cfs[r*q+p] = 4.*std::pow(1i,q)*gsl_sf_bessel_Jn((p+q)*0.5,arg)*gsl_sf_bessel_Jn((q-p)*0.5,arg);
}
}
for (int p=0; p<r; ++p) cfs[p]*=0.5;
for (int q=0; q<r; ++q) cfs[r*q]*=0.5;
}
}
}
#endif
| {
"alphanum_fraction": 0.4148132606,
"avg_line_length": 32.3118644068,
"ext": "h",
"hexsha": "5a1be68070ebec8530a21fbfccae3ab6d84e022a",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2021-01-08T07:19:57.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-01-08T07:19:57.000Z",
"max_forks_repo_head_hexsha": "0fb1ecff607048be637e4a069cf390ad950897a5",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "danfortunato/nufftw",
"max_forks_repo_path": "plan.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "0fb1ecff607048be637e4a069cf390ad950897a5",
"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": "danfortunato/nufftw",
"max_issues_repo_path": "plan.h",
"max_line_length": 119,
"max_stars_count": 4,
"max_stars_repo_head_hexsha": "0fb1ecff607048be637e4a069cf390ad950897a5",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "danfortunato/nufftw",
"max_stars_repo_path": "plan.h",
"max_stars_repo_stars_event_max_datetime": "2021-12-31T15:30:17.000Z",
"max_stars_repo_stars_event_min_datetime": "2017-06-14T23:32:24.000Z",
"num_tokens": 2401,
"size": 9532
} |
#ifndef AMICI_HDF5_H
#define AMICI_HDF5_H
#include <string>
#include <memory>
#include <vector>
#include <H5Cpp.h>
#include <gsl/gsl-lite.hpp>
#undef AMI_HDF5_H_DEBUG
/* Macros for enabling/disabling HDF5 error auto-printing
* AMICI_H5_SAVE_ERROR_HANDLER and AMICI_H5_RESTORE_ERROR_HANDLER must be called
* within the same context, otherwise the stack handler is lost. */
#define AMICI_H5_SAVE_ERROR_HANDLER \
herr_t (*old_func)(void *); \
void *old_client_data; \
H5Eget_auto1(&old_func, &old_client_data); \
H5Eset_auto1(NULL, NULL)
#define AMICI_H5_RESTORE_ERROR_HANDLER H5Eset_auto1(old_func, old_client_data)
namespace amici {
class ReturnData;
class ExpData;
class Model;
class Solver;
namespace hdf5 {
/* Functions for reading and writing AMICI data to/from HDF5 files. */
/**
* @brief Open the given file for writing. Append if exists, create if not.
* @param hdf5filename
* @return
*/
H5::H5File createOrOpenForWriting(std::string const& hdf5filename);
/**
* @brief Read solver options from HDF5 file
* @param fileId hdf5 file handle to read from
* @param solver solver to set options on
* @param datasetPath Path inside the HDF5 file
*/
void readSolverSettingsFromHDF5(const H5::H5File &file, Solver& solver,
std::string const& datasetPath);
/**
* @brief Read solver options from HDF5 file
* @param hdffile Name of HDF5 file
* @param solver solver to set options on
* @param datasetPath Path inside the HDF5 file
*/
void readSolverSettingsFromHDF5(std::string const& hdffile, Solver& solver,
std::string const& datasetPath);
/**
* @brief Read model data from HDF5 file
* @param hdffile Name of HDF5 file
* @param model model to set data on
* @param datasetPath Path inside the HDF5 file
*/
void readModelDataFromHDF5(std::string const& hdffile, Model& model,
std::string const& datasetPath);
/**
* @brief Read model data from HDF5 file
* @param fileId hdf5 file handle to read from
* @param model model to set data on
* @param datasetPath Path inside the HDF5 file
*/
void readModelDataFromHDF5(H5::H5File const&file, Model& model,
std::string const& datasetPath);
/**
* @brief Write ReturnData struct to HDF5 dataset
* @param rdata Data to write
* @param hdffile Filename of HDF5 file
* @param datasetPath Full dataset path inside the HDF5 file (will be created)
*/
void writeReturnData(const ReturnData &rdata,
H5::H5File const& file,
const std::string& hdf5Location);
void writeReturnData(const ReturnData &rdata,
std::string const& hdf5Filename,
const std::string& hdf5Location);
void writeReturnDataDiagnosis(const ReturnData &rdata,
H5::H5File const& file,
const std::string& hdf5Location);
/**
* @brief Create the given group and possibly parents
* @param file
* @param groupPath
* @param recursively
*/
void createGroup(const H5::H5File &file,
std::string const& groupPath,
bool recursively = true);
/**
* @brief readSimulationExpData reads AMICI experimental data from
* attributes in HDF5 file.
* @param hdf5Filename Name of HDF5 file
* @param hdf5Root Path inside the HDF5 file to object having ExpData as
* attributes
* @param model The model for which data is to be read
* @return
*/
std::unique_ptr<ExpData> readSimulationExpData(const std::string &hdf5Filename,
const std::string &hdf5Root,
const Model &model);
/**
* @brief writeSimulationExpData writes AMICI experimental data to
* attributes in HDF5 file.
* @param edata The experimental data which is to be written
* @param hdf5Filename Name of HDF5 file
* @param hdf5Root Path inside the HDF5 file to object having ExpData as
* attributes
*/
void writeSimulationExpData(const ExpData &edata,
H5::H5File const& file,
const std::string &hdf5Location);
/**
* @brief attributeExists Check whether an attribute with the given
* name exists on the given dataset
* @param fileId The HDF5 file object
* @param datasetPath Dataset of which attributes should be checked
* @param attributeName Name of the attribute of interest
* @return
*/
bool attributeExists(H5::H5File const& file,
const std::string &optionsObject,
const std::string &attributeName);
bool attributeExists(H5::H5Object const& object,
const std::string &attributeName);
void createAndWriteInt1DDataset(H5::H5File const& file,
std::string const& datasetName,
gsl::span<const int> buffer);
void createAndWriteInt2DDataset(H5::H5File const& file,
std::string const& datasetName,
gsl::span<const int> buffer, hsize_t m,
hsize_t n);
void createAndWriteDouble1DDataset(H5::H5File const& file,
std::string const& datasetName,
gsl::span<const double> buffer);
void createAndWriteDouble2DDataset(H5::H5File const& file,
std::string const& datasetName,
gsl::span<const double> buffer, hsize_t m,
hsize_t n);
void createAndWriteDouble3DDataset(H5::H5File const& file,
std::string const& datasetName,
gsl::span<const double> buffer, hsize_t m,
hsize_t n, hsize_t o);
double getDoubleScalarAttribute(const H5::H5File& file,
const std::string &optionsObject,
const std::string &attributeName);
int getIntScalarAttribute(const H5::H5File &file,
const std::string &optionsObject,
const std::string &attributeName);
std::vector<int> getIntDataset1D(const H5::H5File &file,
std::string const& name);
std::vector<double> getDoubleDataset1D(const H5::H5File &file,
std::string const& name);
std::vector<double> getDoubleDataset2D(const H5::H5File &file,
std::string const& name,
hsize_t &m, hsize_t &n);
std::vector<double> getDoubleDataset3D(const H5::H5File &file,
std::string const& name,
hsize_t &m, hsize_t &n, hsize_t &o);
/**
* @brief Check if the given location (group, link or dataset) exists in the
* given file
* @param filename
* @param location
* @return
*/
bool locationExists(std::string const& filename, std::string const& location);
bool locationExists(H5::H5File const& file, std::string const& location);
} // namespace hdf5
} // namespace amici
#endif
| {
"alphanum_fraction": 0.6042230644,
"avg_line_length": 34.523364486,
"ext": "h",
"hexsha": "49f27f890569bfed54a0a061770925f426c3dc3d",
"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": "a0407673453d6e18a9abec5b6f73758dd09f7aaf",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "paszkow/AMICI",
"max_forks_repo_path": "include/amici/hdf5.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "a0407673453d6e18a9abec5b6f73758dd09f7aaf",
"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": "paszkow/AMICI",
"max_issues_repo_path": "include/amici/hdf5.h",
"max_line_length": 80,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "a0407673453d6e18a9abec5b6f73758dd09f7aaf",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "paszkow/AMICI",
"max_stars_repo_path": "include/amici/hdf5.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1643,
"size": 7388
} |
#pragma once
#include "options.h"
#include "predict.h"
#include "progress.h"
#include <gsl/gsl-lite.hpp>
namespace angonoka::cli {
namespace detail {
/**
Check if an event is the final one.
@param evt Event
@return True if this is the final event.
*/
bool is_final_event(ProgressEvent& evt) noexcept;
/**
Helper constant that checks if a given class is
a specialization of std::future.
*/
template <typename T> inline constexpr bool is_future = false;
template <typename T>
inline constexpr bool is_future<std::future<T>> = true;
} // namespace detail
/**
Prediction events handler.
Prints various progress messages and results as
the prediction algorithm runs.
@var progress Chosen progress bar implementation
@var options CLI options
*/
struct EventHandler {
gsl::not_null<Progress*> progress;
gsl::not_null<const Options*> options;
/**
Handler events without attributes.
@param e Event
*/
void operator()(const SimpleProgressEvent& e) const;
/**
Handle schedule optimization events.
@param e Event
*/
void operator()(const ScheduleOptimizationEvent& e) const;
/**
Handle schedule optimization completion.
@param e Event
*/
void operator()(const ScheduleOptimizationComplete& e) const;
};
/**
Awaitable result of the prediction.
*/
template <typename T>
concept Prediction = detail::is_future<T>;
/**
Consumes prediction events from the queue.
@param queue Prediction events queue
@param prediction Prediction result
@param handler Events handler
*/
void consume_events(
Queue<ProgressEvent>& queue,
Prediction auto& prediction,
EventHandler handler)
{
Expects(prediction.valid());
using namespace std::literals::chrono_literals;
using boost::variant2::visit;
constexpr auto event_timeout = 100ms;
ProgressEvent evt;
while (!detail::is_final_event(evt)) {
if (!queue.try_dequeue(evt)) {
prediction.wait_for(event_timeout);
continue;
}
visit(handler, evt);
}
Ensures(prediction.valid());
}
} // namespace angonoka::cli
| {
"alphanum_fraction": 0.6562916852,
"avg_line_length": 22.9489795918,
"ext": "h",
"hexsha": "4706f630cb8eb3aaaa169d41fbe49021f79bab1e",
"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": "a8a4a79da4092630c5243c2081f92ba39d0b056c",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "coffee-lord/angonoka",
"max_forks_repo_path": "src/cli/events.h",
"max_issues_count": 3,
"max_issues_repo_head_hexsha": "a8a4a79da4092630c5243c2081f92ba39d0b056c",
"max_issues_repo_issues_event_max_datetime": "2022-02-12T19:55:52.000Z",
"max_issues_repo_issues_event_min_datetime": "2022-02-12T19:52:27.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "coffee-lord/angonoka",
"max_issues_repo_path": "src/cli/events.h",
"max_line_length": 66,
"max_stars_count": 2,
"max_stars_repo_head_hexsha": "a8a4a79da4092630c5243c2081f92ba39d0b056c",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "coffee-lord/angonoka",
"max_stars_repo_path": "src/cli/events.h",
"max_stars_repo_stars_event_max_datetime": "2022-02-21T21:53:24.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-10-23T18:05:25.000Z",
"num_tokens": 476,
"size": 2249
} |
/* $Id$ */
/*--------------------------------------------------------------------*/
/*; Copyright (C) 2006-2013 */
/*; Associated Universities, Inc. Washington DC, USA. */
/*; */
/*; 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 Massachusetts Ave, Cambridge, */
/*; MA 02139, USA. */
/*; */
/*;Correspondence about this software should be addressed as follows: */
/*; Internet email: bcotton@nrao.edu. */
/*; Postal address: William Cotton */
/*; National Radio Astronomy Observatory */
/*; 520 Edgemont Road */
/*; Charlottesville, VA 22903-2475 USA */
/*--------------------------------------------------------------------*/
#include "ObitIonCal.h"
#include "ObitTableVZ.h"
#include "ObitSkyGeom.h"
#include "ObitPBUtil.h"
#include "ObitZernike.h"
#include "ObitUVUtil.h"
#include "ObitDConCleanVis.h"
#include "ObitTableNX.h"
#include "ObitIoN2SolNTable.h"
#include "ObitTableNI.h"
#include "ObitMem.h"
#include "ObitUtil.h"
#if HAVE_GSL==1 /* GSL stuff */
#include <gsl/gsl_multifit.h>
#endif /* GSL stuff */
/*----------------Obit: Merx mollis mortibus nuper ------------------*/
/**
* \file ObitIonCal.c
* ObitIonCal class function definitions.
* This class is derived from the Obit base class.
*/
/** name of the class defined in this file */
static gchar *myClassName = "ObitIonCal";
/** Function to obtain parent ClassInfo */
static ObitGetClassFP ObitParentGetClass = ObitGetClass;
/* Catalog list management */
/** Calibrator list element structure */
typedef struct {
/** catalog celestial position */
odouble ra, dec;
/** Offset on Zernike plane (deg) */
ofloat ZernXY[2];
/** shift from reference position */
ofloat shift[2];
/** expected pixel in reference image */
ofloat pixel[2];
/** Estimated catalog flux density */
ofloat flux;
/** measured offset from expected position (deg) */
ofloat offset[2];
/** measured peak flux density (image units) */
ofloat peak;
/** measured integrated flux density (image units) */
ofloat fint;
/** determined weight */
ofloat wt;
/** catalog quality code */
olong qual;
/** calibrator number (0-rel) */
olong calNo;
/** epoch number */
olong epoch;
} CalListElem;
/** Private: CalListElem Constructor */
static CalListElem*
newCalListElem (odouble ra, odouble dec, ofloat ZernXy[2], ofloat shift[2],
ofloat pixel[2], ofloat flux, ofloat offset[2],
ofloat peak, ofloat fint,ofloat wt, olong qual,
olong calNo, olong epoch);
/** Private: Update contents of an CalListElem */
static void
CalListElemUpdate (CalListElem *elem, odouble ra, odouble dec,
ofloat ZernXY[2], ofloat shift[2], ofloat pixel[2],
ofloat flux, ofloat offset[2], ofloat peak, ofloat fint,
ofloat wt, olong qual, olong calNo, olong epoch);
/** Private: Print contents of an CalListElem */
static void
CalListElemPrint (CalListElem *elem, FILE *file);
/** Private: CalListElem Destructor */
static void freeCalListElem(CalListElem *me);
/** CalList structure. */
typedef struct {
/** Number of entries */
olong number;
/** glib singly linked list */
GSList* list;
} CalList;
/** Private: CalList structure.constructor. */
static CalList* newCalList (void);
/** Private: Add an CalListElem to the CalList */
static void CalListAdd (CalList *in, CalListElem *elem);
/** Private: Remove a CalListElem from the list. */
static void CalListRemove (CalList *in, CalListElem *elem);
/** Private: Remove all items from the list. */
static void CalListClear (CalList *in);
/** Private: Remove all items from the list. */
static void CalListPrint (CalList *in, FILE *file);
/** Private: destructor. */
static void freeCalList (CalList *in);
/**
* ClassInfo structure ObitIonCalClassInfo.
* This structure is used by class objects to access class functions.
*/
static ObitIonCalClassInfo myClassInfo = {FALSE};
/*--------------- File Global Variables ----------------*/
/*---------------Private function prototypes----------------*/
/** Private: Initialize newly instantiated object. */
void ObitIonCalInit (gpointer in);
/** Private: Deallocate members. */
void ObitIonCalClear (gpointer in);
/** Private: Set Class function pointers. */
static void ObitIonCalClassInfoDefFn (gpointer inClass);
/** Private: Fit positions of calibrator(s) in an image. */
static void CalPosFit (ObitImage *image, ofloat inPixel[2], olong* imsi,
ofloat pixelOff[2], ofloat* souflx, ofloat* souint,
ObitErr *err);
/** Private: CLEAN failed - mark observations bad. */
static void CalBadTime (ObitIonCal *in, ObitImageMosaic* mosaic,
olong epoch, ObitErr *err);
/** Private: Lookup calibrators in an image from a catalog. */
static void
FindCalImage (ObitImage *image, gchar *Catalog, olong catDisk,
ofloat OutlierFlux, ofloat OutlierSI, olong qual, ofloat AntDiam,
CalList *calList, olong prtLv, ObitErr *err);
/** Private: Fit Zernike model for single time */
static ofloat
IonFit1 (olong nobs, olong* isou, ofloat* x, ofloat* y,
ofloat* dx, ofloat* dy, ofloat* w,
olong* ncoef, ofloat* coef, olong prtLv, ObitErr *err);
/** Private: Edit data for single time */
static gboolean
IonEdit1 (olong nobs, olong* isou, ofloat* x, ofloat* y,
ofloat* dx, ofloat* dy, ofloat* w,
ofloat MaxRMS, olong ncoef, ofloat* coef, olong prtLv,
ObitErr *err);
/** Private: Determine timerange for next segment */
static gboolean NextTime (ObitTableNX *NXtab, ofloat solInt,
ofloat timer[2], olong* suba, ObitErr* err);
/** Private: Get calibrator list from an ImageMosaic */
static void
FindCalMosaic (ObitIonCal *in, ObitImageMosaic *mosaic,
CalList *calList, olong prtLv, ObitErr *err);
/** Private: Get calibrator info from catalog */
static void
LookupCals (ObitIonCal *in, ObitImageMosaic *mosaic, CalList *calList,
olong prtLv, ObitErr *err);
/** Private: Filter and fit multiepoch offset measurements */
static ObitTableNI*
FitAll (ObitIonCal *in, olong ncoef,
olong nEpoch, ofloat *timeEpoch, ofloat *timeIEpoch, olong *subaEpoch,
odouble refFreq, ofloat *seeing, ObitErr* err);
/** Private: convert timerange to a printable string. */
static void TR2String (ofloat timer[2], gchar *msgBuf);
/* Private: Fit time sequence of Zernike models */
static ObitTableNI*
doIonFitAll (ObitUV *inUV, ofloat MaxRMS, ofloat MinRat, ofloat FCStrong, gboolean doINEdit,
olong ncoef, olong nsou, olong* isou, ofloat* x, ofloat* y,
olong nTime, ofloat* Time, ofloat* TimeI, olong* isuba,
olong n, olong* iTime, ofloat* xoff, ofloat* yoff,
ofloat* flux, ofloat *wt, olong* flqual, ofloat* sint,
olong prtLv, odouble refFreq, ofloat* totRMS, ObitErr* err);
/* Private: Initilize Zernike time series */
static gboolean
initIonModel (olong nobs, olong nsou, olong nTime, olong maxcoe, olong* isou,
olong* iTime, ofloat* x, ofloat* y, ofloat* dx, ofloat* dy,
ofloat* w, olong* flqual, olong* ncoef, gboolean* gotsou,
gboolean* fitsou, ofloat* soffx, ofloat* soffy, ofloat** coef,
olong prtLv, ObitErr* err);
/* Private: Least Squares Fit Zernike time series and source offsets */
static void
FitIonSeries (olong nobs, olong nsou, olong nTime, olong maxcoe, olong* isou, olong* iTime,
ofloat* x, ofloat* y, ofloat* dx, ofloat* dy, ofloat* w, olong* ncoef,
gboolean* gotsou, gboolean* fitsou, ofloat* soffx, ofloat* soffy,
ofloat** coef, ofloat* trms, olong prtLv, ObitErr* err) ;
/* Private: Edit data based on Zernike time series */
static gboolean
IonEditSeries (olong nobs, olong nsou, olong nTime,
olong maxcoe, olong* isou, olong* iTime, ofloat* x, ofloat* y,
ofloat* dx, ofloat* dy, ofloat* w, ofloat MaxRMS, olong* ncoef,
ofloat* soffx, ofloat* soffy, ofloat** coef, olong prtLv, ObitErr* err);
/* Private: Time series editing based on amplitudes */
static gboolean
IonEditAmp (olong nobs, olong nsou, olong nTime, olong* isou, olong* iTime,
ofloat MinRat, ofloat FCStrong, ofloat* flux, olong* ncoef, ofloat* wt,
olong prtLv, ObitErr* err);
/* Private: Edit data for a given source based on Zernike time series */
static void
IonEditSource (olong source, olong nobs, olong nTime, olong maxcoe, olong nsou,
olong* isou, olong* iTime, ofloat* x, ofloat* y,
ofloat* dx, ofloat* dy, ofloat* w, ofloat MaxRMS, olong* ncoef,
ofloat* soffx, ofloat* soffy, ofloat** coef,
ofloat *gdx, ofloat *gdy, olong* stoss, olong prtLv, ObitErr* err);
/* Private: Get minimum fluxes for strong (required) calibrators */
static ofloat*
getStrong (olong nobs, olong nsou, olong nTime, olong* isou, olong* iTime,
ofloat MinRat, ofloat FCStrong, ofloat* flux, olong prtLv,
ObitErr* err);
static void PosImage (ObitImage *image, ofloat pixel[2], ofloat minflux,
ofloat mxcdis, olong FitSize,
ofloat offset[2], ofloat *peak, ofloat *fint, ObitErr *err);
static olong pfit (ofloat a[9][9], ofloat *s, ofloat dx[2], ofloat fblank);
static olong momnt (ofloat ara[9][9], ofloat x, ofloat y, olong nx, olong ny,
ofloat momar[6], ofloat fblank);
static void matvmul (ofloat m[3][3], ofloat vi[3], ofloat vo[3], olong n);
static void rd2zer (odouble ra, odouble dec, ofloat xshift, ofloat yshift,
ofloat* xzer, ofloat* yzer, olong *ierr);
static void zerrot (odouble ra, odouble dec, ofloat xshift, ofloat yshift,
ofloat* rotate);
static void FitZernike (olong nobs, olong* isou, ofloat *x, ofloat *y,
ofloat *dx, ofloat *dy, ofloat *wt,
olong nZern, ofloat *coef);
/*----------------------Public functions---------------------------*/
/**
* Constructor.
* Initializes class if needed on first call.
* \param name An optional name for the object.
* \return the new object.
*/
ObitIonCal* newObitIonCal (gchar* name)
{
ObitIonCal* out;
/* Class initialization if needed */
if (!myClassInfo.initialized) ObitIonCalClassInit();
/* allocate/init structure */
out = g_malloc0(sizeof(ObitIonCal));
/* initialize values */
if (name!=NULL) out->name = g_strdup(name);
else out->name = g_strdup("Noname");
/* set ClassInfo */
out->ClassInfo = (gpointer)&myClassInfo;
/* initialize other stuff */
ObitIonCalInit((gpointer)out);
return out;
} /* end newObitIonCal */
/**
* Returns ClassInfo pointer for the class.
* \return pointer to the class structure.
*/
gconstpointer ObitIonCalGetClass (void)
{
/* Class initialization if needed */
if (!myClassInfo.initialized) ObitIonCalClassInit();
return (gconstpointer)&myClassInfo;
} /* end ObitIonCalGetClass */
/**
* Make a deep copy of an ObitIonCal.
* \param in The object to copy
* \param out An existing object pointer for output or NULL if none exists.
* \param err Obit error stack object.
* \return pointer to the new object.
*/
ObitIonCal* ObitIonCalCopy (ObitIonCal *in, ObitIonCal *out, ObitErr *err)
{
const ObitClassInfo *ParentClass;
gboolean oldExist;
gchar *outName;
/* error checks */
g_assert (ObitErrIsA(err));
if (err->error) return out;
g_assert (ObitIsA(in, &myClassInfo));
if (out) g_assert (ObitIsA(out, &myClassInfo));
/* Create if it doesn't exist */
oldExist = out!=NULL;
if (!oldExist) {
/* derive object name */
outName = g_strconcat ("Copy: ",in->name,NULL);
out = newObitIonCal(outName);
g_free(outName);
}
/* deep copy any base class members */
ParentClass = myClassInfo.ParentClass;
g_assert ((ParentClass!=NULL) && (ParentClass->ObitCopy!=NULL));
ParentClass->ObitCopy (in, out, err);
/* copy this class */
out->myData = ObitUVRef(in->myData);
return out;
} /* end ObitIonCalCopy */
/**
* Make a copy of a object but do not copy the actual data
* This is useful to create an IonCal similar to the input one.
* \param in The object to copy
* \param out An existing object pointer for output, must be defined.
* \param err Obit error stack object.
*/
void ObitIonCalClone (ObitIonCal *in, ObitIonCal *out, ObitErr *err)
{
const ObitClassInfo *ParentClass;
/* error checks */
g_assert (ObitErrIsA(err));
if (err->error) return;
g_assert (ObitIsA(in, &myClassInfo));
g_assert (ObitIsA(out, &myClassInfo));
/* deep copy any base class members */
ParentClass = myClassInfo.ParentClass;
g_assert ((ParentClass!=NULL) && (ParentClass->ObitCopy!=NULL));
ParentClass->ObitCopy (in, out, err);
/* copy this class */
out->myData = ObitUVRef(in->myData);
} /* end ObitIonCalClone */
/**
* Creates an ObitIonCal
* \param name An optional name for the object.
* \return the new object.
*/
ObitIonCal* ObitIonCalCreate (gchar* name)
{
ObitIonCal* out;
/* Create basic structure */
out = newObitIonCal (name);
return out;
} /* end ObitIonCalCreate */
/**
* Attach UV data, unreferences any old data
* \param in Object to attach UV data to
* \param inUV UV data to attach
*/
void ObitIonCalSetData (ObitIonCal *in, ObitUV *inUV)
{
in->myData = ObitUVUnref(in->myData); /* out with the old */
in->myData = ObitUVRef(inUV); /* in with the new */
} /* end ObitIonCalSetData */
/**
* Fills the calList member with a list of calibrator sources
* selected from a given catalog whose position are inside the
* field of view of image.
* Previous contents of the CalList are cleared
* \param in IonCal object
* Control parameters are on the info member.
* \li Catalog OBIT_char (?,1,1) AIPSVZ format FITS catalog for defining outliers,
* 'Default' or blank = use default catalog.
* \li catDisk OBIT_int (1,1,1) FITS disk for catalog [def 1]
* \li OutlierFlux OBIT_float (1,1,1) Minimum estimated flux density include cal. fields
* from Catalog. [default 0.1 Jy ]
* \li OutlierSI OBIT_float (1,1,1) Spectral index to use to convert catalog flux
* density to observed frequency. [default = -0.75]
* \li MaxQual OBIT_int (1,1,1) Max. cal. quality code [def 1]
* \li prtLv OBIT_int (1,1,1) Print level >=2 => give list [def 0]
*
* calList Calibrator list each element of which has:
* \li ra position RA (deg) of calibrators
* \li dec position Dec (deg) of calibrators
* \li shift Offset in field [x,y] on unit Zernike circle of position
* \li pixel Expected pixel in reference image
* \li flux Estimated catalog flux density
* \li offset Measured offset [x,y] from expected position (deg)
* \li peak Measured peak flux density (image units)
* \li fint Measured integrated flux density (image units)
* \li wt Determined weight
* \li qual Catalog quality code
* \param image Image object
* \param err Error stack
*/
void ObitIonCalFindImage (ObitIonCal *in, ObitImage* image, ObitErr* err)
{
CalList *calList;
gint32 dim[MAXINFOELEMDIM] = {1,1,1,1,1};
ObitInfoType type;
gchar Catalog[257];
olong catDisk, qual, prtLv;
ofloat OutlierFlux, OutlierSI, AntDiam;
gchar *routine = "ObitIonCalFindImage";
/* Error checks */
g_assert(ObitErrIsA(err));
if (err->error) return ; /* previous error? */
g_assert(ObitIonCalIsA(in));
/* Clear any entries in calList */
calList = (CalList*)in->calList;
CalListClear (calList);
/* Control information. */
sprintf (Catalog, "Default");
ObitInfoListGetTest(in->info, "Catalog", &type, dim, Catalog);
if (err->error) Obit_traceback_msg (err, routine, in->name);
if (!strncmp(Catalog, " ", 4)) sprintf (Catalog, "Default");
if (!strncmp(Catalog, "Default", 7)) sprintf (Catalog, "NVSSVZ.FIT");
catDisk = 1;
ObitInfoListGetTest(in->info, "CatDisk", &type, dim, &catDisk);
OutlierFlux = 1.0;
ObitInfoListGetTest(in->info, "OutlierFlux", &type, dim, &OutlierFlux);
OutlierSI = -0.75;
ObitInfoListGetTest(in->info, "OutlierSI", &type, dim, &OutlierSI);
AntDiam = 25.0;
ObitInfoListGetTest(in->info, "AntDiam", &type, dim, &AntDiam);
qual = 1;
ObitInfoListGetTest(in->info, "MaxQual", &type, dim, &qual);
prtLv = 0;
ObitInfoListGetTest(in->info, "prtLv", &type, dim, &prtLv);
/* Search Catalog */
FindCalImage (image, Catalog, catDisk, OutlierFlux, OutlierSI, qual,
AntDiam, calList, prtLv, err);
if (err->error) Obit_traceback_msg (err, routine, in->name);
} /* end ObitIonCalFindImage */
/**
* Determines calibrator position offsets from a single image.
* Given an image containing calibrator sources, return fitted fluxes
* and position offsets.
* Resultant positions are all referred to a tangent plane at the
* pointing center, this is referred to as the Zernike plane as this
* plane will be used to fit the phase screen. The "Zernike Unit
* Circle" defines the phase screen. Source position offsets are in
* the X and Y (RA, Dec) as defined by this plane.
* Routine translated from the AIPSish CALPOS.FOR/CALPOS
* \param in IonCal object
* Control parameters are on the info member.
* \li "FitDist" OBIT_int (1,1,1) dist, from expected location to search
* asec [10 pixels]
* \li "MinPeak" OBIT_float (1,1,1) Min. acceptable image peak (Jy) [1.0]
* \li "MaxDist" OBIT_float (1,1,1) Max. distance (deg/10) to accept calibrator [1.]
* \li "MaxWt" OBIT_float (1,1,1) Max. weight [10.0]
* \li prtLv OBIT_int (1,1,1) Print level >=1 => give fits
* \param image Image object
* \param calList Calibrator list each element of which has:
* \li ra position RA (deg) of calibrators
* \li dec position Dec (deg) of calibrators
* \li shift Offset in field [x,y] on unit Zernike circle of position
* \li pixel Expected pixel in reference image
* \li flux Estimated catalog flux density
* \li offset Measured offset [x,y] from expected position (deg)
* \li peak Measured peak flux density (image units)
* \li fint Measured integrated flux density (image units)
* \li wt Determined weight
* \li qual Catalog quality code
* \param err Error stack
*/
void ObitIonCalPosMul (ObitIonCal *in, ObitImage* image, ObitErr* err)
{
olong i, FitSize, good, imsi[2], epoch=1, prtLv;
olong blc[IM_MAXDIM] = {1,1,1,1,1,1,1};
olong trc[IM_MAXDIM] = {0,0,0,0,0,0,0};
ofloat FitDist, flux;
ofloat mxcdis,maxwt;
gint32 dim[MAXINFOELEMDIM] = {1,1,1,1,1};
ObitInfoType type;
ObitIOSize IOBy;
gboolean bad;
ofloat offset[2], peak, fint,wt, dist;
ofloat area, pixelOff[2];
CalListElem *elem=NULL, *nelem=NULL;
GSList *tmp;
CalList *calList;
gchar *routine = "ObitIonCalPosMul";
/* Error checks */
g_assert(ObitErrIsA(err));
if (err->error) return ; /* previous error? */
g_assert(ObitIonCalIsA(in));
calList = (CalList*)in->calList;
/* Control information. */
maxwt = 10.0;
ObitInfoListGetTest(in->info, "MaxWt", &type, dim, &maxwt);
flux = 1.0;
ObitInfoListGetTest(in->info, "MinPeak", &type, dim, &flux);
mxcdis = 1.0;
ObitInfoListGetTest(in->info, "MaxDist", &type, dim, &mxcdis);
FitDist = 0.0;
ObitInfoListGetTest(in->info, "FitDist", &type, dim, &FitDist);
prtLv = 0;
ObitInfoListGetTest(in->info, "prtLv", &type, dim, &prtLv);
/* Open and read image full plane */
IOBy = OBIT_IO_byPlane;
dim[0] = 1;
ObitInfoListPut (image->info, "IOBy", OBIT_long, dim, &IOBy, err);
dim[0] = 7;
for (i=0; i<IM_MAXDIM; i++) {blc[i] = 1; trc[i] = 0;}
ObitInfoListPut (image->info, "BLC", OBIT_long, dim, blc, err);
ObitInfoListPut (image->info, "TRC", OBIT_long, dim, trc, err);
image->extBuffer = FALSE; /* Make sure it has buffer */
if (err->error) Obit_traceback_msg (err, routine, image->name);
if ((ObitImageOpen (image, OBIT_IO_ReadOnly, err)
!= OBIT_IO_OK) || (err->error>0)) { /* error test */
Obit_log_error(err, OBIT_Error,
"ERROR opening image %s", image->name);
return;
}
ObitImageRead (image, NULL, err);
if (err->error) Obit_traceback_msg (err, routine, image->name);
/* Convert FitDist to pixels */
if (FitDist<=0.0) FitDist = 10.0 * fabs(image->myDesc->cdelt[0]);
FitSize = (olong)((FitDist / fabs(image->myDesc->cdelt[0]))+0.5);
FitSize = MAX (10, FitSize);
imsi[0] = imsi[1] = FitSize;
/* Loop over sources */
good = 0;
tmp = calList->list;
while (tmp!=NULL) { /* loop 100 */
elem = (CalListElem*)tmp->data;
/* if find epoch > 0 then quit loop */
if (elem->epoch>0) break;
bad = FALSE;
/* fit source */
CalPosFit (image, elem->pixel, imsi, pixelOff, &peak, &fint, err);
if (err->error) Obit_traceback_msg (err, routine, image->name);
/* find anything? */
if (peak<flux) { /* Nope */
bad = TRUE;
} else { /* yes */
/* Offset */
offset[0] = pixelOff[0] * image->myDesc->cdelt[0];
offset[1] = pixelOff[1] * image->myDesc->cdelt[1];
/* Normalize integrated flux by beam area in pixels */
area = 1.1331 * image->myDesc->beamMaj * image->myDesc->beamMin /
(fabs (image->myDesc->cdelt[0]) * fabs (image->myDesc->cdelt[1])) ;
if (area < 0.001) area = 1.0;
fint /= area;
/* Within maximum distance? */
dist = sqrt(elem->ZernXY[0]*elem->ZernXY[0] + elem->ZernXY[1]*elem->ZernXY[1]);
if (dist <= mxcdis) wt = MIN (maxwt, peak);
else wt = 0.0;
if (bad) wt = 0.0;
/* Update CalList */
nelem = newCalListElem (elem->ra, elem->dec, elem->ZernXY, elem->shift,
elem->pixel, elem->flux, offset, peak, fint, wt,
elem->qual, elem->calNo, epoch);
CalListAdd (calList, nelem);
good++; /* This one OK */
/* diagnostics? */
if (prtLv>=1) {
Obit_log_error(err, OBIT_InfoErr,
"Fit E=%5d C=%5d Z= %7.4f %7.4f off=%7.2f %7.2f Peak=%6.2f int=%6.2f qual=%d",
epoch, elem->calNo, elem->ZernXY[0], elem->ZernXY[1],
offset[0]*3600.0, offset[1]*3600.0, peak, fint, elem->qual);
}
} /* End if detected */
tmp = g_slist_next(tmp); /* next item in list */
} /* end loop L100: over calibrator*/
/* Close image */
ObitImageClose (image, err);
if (err->error) Obit_traceback_msg (err, routine, image->name);
image->image = ObitImageUnref(image->image); /* Free buffer */
/* tell how many */
Obit_log_error(err, OBIT_InfoErr, "%s: Fitted %d calibrator offsets",
routine, good);
} /* end of routine ObitIonCalPosMul */
/**
* Fit Zernike model to single epoch image distortion
* Uses fitted data in calList member.
* Iteratively edits most discrepant point if needed to get RMS
* residual down to MaxRMS.
* \param in IonCal object
* Control parameters are on the info member.
* \li "nZern" OBIT_int (1,1,1) Zernike polynomial order requested [def 5]
* \li "MaxRMS" OBIT_float (1,1,1) Target RMS residual (asec), default 10 asec
* \li prtLv OBIT_int (1,1,1) Print level >=3 => give fitting diagnostics
* [def. 0]
* \param epoch 1-rel time index i measurements
* \param coef [out] Fitted coefficients
* \param err Error stack
* \return RMS residual in deg, -1 on error
*/
ofloat ObitIonCalFit1 (ObitIonCal *in, olong epoch, ofloat *coef,
ObitErr* err)
{
CalListElem *elem=NULL;
ofloat out = -1.0;
GSList *tmp;
olong nZern, count, badCount, prtLv;
gboolean doMore;
ofloat rms, MaxRMS, MaxRMS2;
ofloat *x=NULL, *y=NULL, *dx=NULL, *dy=NULL, *w=NULL;
olong *isou=NULL;
gint32 dim[MAXINFOELEMDIM] = {1,1,1,1,1};
ObitInfoType type;
CalList *calList;
gchar *routine = "ObitIonCalFit1";
/* Error checks */
g_assert(ObitErrIsA(err));
if (err->error) return out; /* previous error? */
g_assert(ObitIonCalIsA(in));
calList = (CalList*)in->calList;
/* Control information. */
nZern = 5;
ObitInfoListGetTest(in->info, "nZern", &type, dim, &nZern);
/* Coerce to range [2,17] */
nZern = MAX (2, MIN (17, nZern));
MaxRMS = 10.0;
ObitInfoListGetTest(in->info, "MaxRMS", &type, dim, &MaxRMS);
MaxRMS /= 3600.0; /* to deg */
MaxRMS2 = 2.0 * MaxRMS; /* relax for finding sources */
prtLv = 0;
ObitInfoListGetTest(in->info, "prtLv", &type, dim, &prtLv);
/* How many measurements at epoch epoch? */
count = 0;
/* Loop over calList */
tmp = calList->list;
while (tmp!=NULL) {
elem = (CalListElem*)tmp->data;
if (elem->epoch==epoch) count++;
if (elem->epoch>epoch) break; /* done? */
tmp = g_slist_next(tmp); /* next item in list */
}
/* allocate memory */
x = g_malloc(count*sizeof(ofloat));
y = g_malloc(count*sizeof(ofloat));
dx = g_malloc(count*sizeof(ofloat));
dy = g_malloc(count*sizeof(ofloat));
w = g_malloc(count*sizeof(ofloat));
isou = g_malloc(count*sizeof(olong));
/* Copy data to arrays - Loop over calList */
tmp = calList->list;
count = 0;
while (tmp!=NULL) {
elem = (CalListElem*)tmp->data;
if (elem->epoch==epoch) {
/* Unit circle = 10 deg */
x[count] = elem->ZernXY[0];
y[count] = elem->ZernXY[1];
dx[count] = elem->offset[0];
dy[count] = elem->offset[1];
w[count] = elem->wt;
isou[count] = count;
count++;
}
if (elem->epoch>epoch) break; /* done? */
tmp = g_slist_next(tmp); /* next item in list */
}
/* Fit model */
doMore = TRUE;
badCount = 0;
while (doMore) {
rms = IonFit1 (count, isou, x, y, dx, dy, w, &nZern, coef, prtLv, err);
if (rms<MaxRMS2) break;
doMore = IonEdit1 (count, isou, x, y, dx, dy, w, MaxRMS2, nZern, coef, prtLv, err);
if (doMore) badCount++;
}
/* tell how many flagged */
Obit_log_error(err, OBIT_InfoErr, "%s: Flagged %d of %d calibrators",
routine, badCount, count);
Obit_log_error(err, OBIT_InfoErr, "%s: Final RMS %f",
routine, 3600.0*rms);
/* cleanup */
if (x) g_free(x);
if (y) g_free(y);
if (dy) g_free(dx);
if (dy) g_free(dy);
if (w) g_free(w);
if (isou) g_free(isou);
return rms;
} /* end of routine ObitIonCalFit1 */
/**
* Ionospheric calibration for a uv data set.
* Loops over time slices, imaging and deconvolving selected fields.
* Then determines position offsets and fits an ionospheric model.
* Results are stored in an 'NI' table attached to inUV.
* Current maximum 1024 epochs.
* Routine translated from the AIPSish IONCAL.FOR/IONCAL
* \param in IonCal object, must have myData UV data attached.
* If myData is a multisource file, then
* selection (1 source) , calibration and editing controls
* must be set on the info member.
* Control parameters on the myData info member.
* \li Catalog OBIT_char (?,1,1) AIPSVZ format FITS catalog for defining outliers,
* 'Default' or blank = use default catalog.
* \li catDisk OBIT_int (1,1,1) FITS disk for catalog [def 1]
* \li OutlierDist OBIT_float (1,1,1) How far from pointing to add calibrators
* \li OutlierFlux OBIT_float (1,1,1) Minimum estimated flux density include outlier fields
* from Catalog. [default 0.1 Jy ]
* \li OutlierSI OBIT_float (1,1,1) Spectral index to use to convert catalog flux
* density to observed frequency. [default = -0.75]
* \li Niter OBIT_int (1,1,1) Max. number of components to clean
* \li minFlux OBIT_float (1,1,1) Minimum flux density to CLEAN
* \li autoWindow OBIT_boolean (1,1,1)True if autoWindow feature wanted.
* \li dispURL OBIT_string (1,1,1) URL of display server
* \li do3D OBIT_bool (1,1,1) Use 3D imaging? def TRUE.
*
* Control parameters on the in->info member.
* \li nZern OBIT_int (1,1,1) Zernike polynomial order requested [def 5]
* \li MaxQual OBIT_int (1,1,1) Max. cal. quality code [def 1]
* \li prtLv OBIT_int (1,1,1) Print level >=2 => give list [def 0]
* \li MaxRMS OBIT_float (1,1,1) Maximum allowable RMS in arcsec. [def 20]
* \li MinRat OBIT_float (1,1,1) Minimum acceptable ratio to average flux [def 0.1]
* \li FCStrong OBIT_float (1,1,1) Min. Flux for strong (required) cal [def big]
* \li FitDist OBIT_int (1,1,1) Dist, from expected location to search
* asec [10 pixels]
* \li MinPeak OBIT_float (1,1,1) Min. acceptable image peak (Jy) [1.0]
* If not given OutlierFlux is used
* \li MaxDist OBIT_float (1,1,1) Max. distance (deg/10) to accept calibrator [1.]
* \li MaxWt OBIT_float (1,1,1) Max. weight [10.0]
* \li doINEdit OBIT_boolean (1,1,1) If true flag solutions for which the seeing
* residual could not be determined or exceeds
* MaxRMS [def TRUE]
* \li doSN OBIT_boolean (1,1,1) If true, convert IN table to an SN table
* attached to inUV. [def False]
* \li solInt OBIT_float (1,1,1) Solution interval (min). [def 1]
* \param err Error code: 0 => ok, -1 => all data flagged
*/
void ObitIonCaldoCal (ObitIonCal*in, ObitErr* err)
{
const ObitDConCleanVisClassInfo *ClnClass;
gboolean doSN;
ofloat solInt, maxWt, Flux, mxcDis, OutlierFlux;
olong qual, prtLv, cprtLv;
olong ncal, ncoef, suba;
olong i, ver;
#define MAXEPOCH 1024 /* Maximum number of epochs */
olong nZern, nEpoch=0, subaEpoch[MAXEPOCH];
ofloat timeEpoch[MAXEPOCH], timeIEpoch[MAXEPOCH];
gint32 dim[MAXINFOELEMDIM] = {1,1,1,1,1};
ObitInfoType type;
ofloat MaxRMS, off[2], timer[2] = {-1.0e20, 0.0};
odouble refFreq=0.0;
ObitUV *inUV = NULL;
ObitDConCleanVis* myClean=NULL;
ObitImageMosaic* myMosaic=NULL;
ObitTableNX *NXtab=NULL;
ObitTableSN *SNtab=NULL;
ObitTableNI *NItab=NULL;
CalList *calList;
ofloat FOV, oldFOV, Beam[3], seeing, maxGap;
gboolean badTime, *gotit=NULL, Tr=TRUE, Fl=FALSE;;
odouble obsra, obsdec;
gchar msgtxt[101], *Stokes="I ";
/* Parameters to copy from inUV to CLEAN object */
gchar *ParmList[] = {"Niter", "minFlux", "dispURL", "autoWindow", NULL};
/* Parameters to copy from inUV to IonCal object */
gchar *IonParmList[] = {"Catalog", "CatDisk", "OutlierFlux", "OutlierSI",
NULL};
gchar *routine = "ObitIonCaldoCal";
/*----------------------------------------------------------------------- */
/* Previous error condition? */
if (err->error) return ;
/* Error checks */
inUV = in->myData; /* data on in */
g_assert(ObitUVIsA(inUV));
/* Get control parameters */
qual = 1;
ObitInfoListGetTest(in->info, "MaxQual", &type, dim, &qual);
prtLv = 0;
ObitInfoListGetTest(in->info, "prtLv", &type, dim, &prtLv);
doSN = FALSE;
ObitInfoListGetTest(in->info, "doSN", &type, dim, &doSN);
solInt = 1.0;
ObitInfoListGetTest(in->info, "solInt", &type, dim, &solInt);
if (solInt<=0.0) solInt = 1.0;
maxWt = 10.0;
ObitInfoListGetTest(in->info, "MaxWt", &type, dim, &maxWt);
/* Default MinPeak is &OutlierFlux */
Flux = 1.0;
if (!ObitInfoListGetTest(in->info, "MinPeak", &type, dim, &Flux)) {
OutlierFlux = 1.0;
ObitInfoListGetTest(in->info, "OutlierFlux", &type, dim, &OutlierFlux);
Flux = OutlierFlux;
dim[0] = dim[1] = dim[2] = 1;
ObitInfoListAlwaysPut(in->info, "MinPeak", OBIT_float, dim, &Flux);
}
mxcDis = 1.0;
ObitInfoListGetTest(in->info, "MaxDist", &type, dim, &mxcDis);
MaxRMS = 20.0;
ObitInfoListGetTest(in->info, "MaxRMS", &type, dim, &MaxRMS);
nZern = 5;
ObitInfoListGetTest(in->info, "nZern", &type, dim, &nZern);
/* Make sure inUV indexed */
maxGap = solInt; /* Max. time gap in indexing */
dim[0] = dim[1] = dim[2] = 1;
ObitInfoListAlwaysPut(inUV->info, "maxGap", OBIT_float, dim, &maxGap);
ObitUVUtilIndex(inUV, err);
if (err->error) Obit_traceback_msg (err, routine, inUV->name);
/* Get NX table */
ver = 1;
NXtab = newObitTableNXValue ("IonCal NX table", (ObitData*)inUV, &ver,
OBIT_IO_ReadOnly, err);
if (err->error) goto cleanup;
/* Set FOV to 0 then restore */
oldFOV = 0.0;
ObitInfoListGetTest(inUV->info, "FOV", &type, dim, &oldFOV);
FOV = 0.0;
ObitInfoListAlwaysPut (inUV->info, "FOV", type, dim, &FOV);
/* Enable data selection by timerange */
dim[0] = 1;
ObitInfoListAlwaysPut(inUV->info, "doCalSelect", OBIT_bool, dim, &Tr);
/* Stokes 'I' */
dim[0] = 4;
ObitInfoListAlwaysPut(inUV->info, "Stokes", OBIT_string, dim, Stokes);
/* Create Clean (and calibrator mosaic) */
myClean = ObitDConCleanVisCreate ("IonCal Clean", inUV, err);
if (err->error) goto cleanup;
ClnClass = (ObitDConCleanVisClassInfo*)myClean->ClassInfo; /* class structure */
/* Reset FOV to previous value */
ObitInfoListAlwaysPut (inUV->info, "FOV", OBIT_float, dim, &oldFOV);
/* Local pointer to calibrator mosaic */
myMosaic = ObitUVImagerGetMosaic (myClean->imager, err);
if (err->error) goto cleanup;
/* Only summary CLEAN messages */
cprtLv = 0; dim[0] = dim[1] = 1;
if (prtLv>=4) cprtLv = prtLv;
ObitInfoListAlwaysPut (myClean->info, "prtLv", OBIT_long, dim, &cprtLv);
/* No need to cross restore */
dim[0] = 1;
ObitInfoListAlwaysPut(myClean->info, "doXRestore", OBIT_bool, dim, &Fl);
/* ... or flatten */
dim[0] = 1;
ObitInfoListAlwaysPut(myClean->info, "doFlatten", OBIT_bool, dim, &Fl);
/* Make beam each time */
dim[0] = 1;
ObitInfoListAlwaysPut(myClean->info, "doBeam", OBIT_bool, dim, &Tr);
/* ... and weight data */
dim[0] = 1;
ObitInfoListAlwaysPut(myClean->info, "doWeight", OBIT_bool, dim, &Tr);
/* Copy CLEAN control parameters */
ObitInfoListCopyList (inUV->info, myClean->info, ParmList);
/* Copy IonCal control parameters */
ObitInfoListCopyList (inUV->info, in->info, IonParmList);
/* Default Beam */
Beam[0] = Beam[1] = Beam[2] = 0.0;
dim[0] = 3; dim[1] = 1;
ObitInfoListAlwaysPut (myClean->info, "Beam", OBIT_float, dim, Beam);
/* Diagnostic info*/
if (prtLv>0) {
g_snprintf (msgtxt,100,"calibrating ionosphere, max RMS seeing= %6.2f qual=%5d",
MaxRMS, qual);
Obit_log_error(err, OBIT_InfoWarn, msgtxt);
g_snprintf (msgtxt,100,"observing date = %s", inUV->myDesc->obsdat);
Obit_log_error(err, OBIT_InfoWarn, msgtxt);
ObitImageDescGetPoint (myMosaic->images[0]->myDesc, &obsra, &obsdec);
g_snprintf (msgtxt,100,"pointing ra=%10.6f dec=%10.6f deg", obsra, obsdec);
Obit_log_error(err, OBIT_InfoWarn, msgtxt);
}
ObitErrLog(err); /* show any messages on err */
/* Clear any entries in calList */
calList = (CalList*)in->calList;
CalListClear (calList);
/* Generate calibrator list from mosaic */
FindCalMosaic (in, myMosaic, calList, prtLv, err);
if (err->error) goto cleanup;
/* arrays per calibrator */
ncal = myMosaic->numberImages;
gotit = g_malloc(ncal*sizeof(gboolean)); /* calibrator ever found? */
for (i=0; i<ncal; i++) gotit[i] = FALSE; /* Not found anything yet. */
/* How many coefficients to solve for? */
ncoef = nZern;
ObitErrLog(err); /* show any messages on err */
/* Loop over time slices */
for (i=1; i<=100000; i++) { /* loop 500 */
if (!NextTime(NXtab, solInt, timer, &suba, err)) break;
if (err->error) goto cleanup;
/* Set timerange, subarray */
dim[0] = 2; dim[1] = 1;
ObitInfoListAlwaysPut (inUV->info, "timeRange", OBIT_float, dim, timer);
dim[0] = 1;
ObitInfoListAlwaysPut (inUV->info, "Subarray", OBIT_long, dim, &suba);
/* Use fitted beam */
dim[0] = 3; dim[1] = 1;
ObitInfoListAlwaysPut (myClean->info, "Beam", OBIT_float, dim, Beam);
/* Reset Windows first time */
if (i==1) ClnClass->ObitDConCleanDefWindow((ObitDConClean*)myClean, err);
if (err->error) goto cleanup;
ObitErrLog(err); /* Make sure message stack shown */
/* Image/deconvolve this one */
ClnClass->ObitDConDeconvolve ((ObitDCon*)myClean, err);
/* Be somewhat tolerant of failures here */
if (myClean->prtLv>2) ObitErrLog(err); /* Debug errors */
if (err->error) {
badTime = TRUE;
ObitErrClearErr (err); /* Clear error messages and condition */
} else badTime = FALSE;
/* Diagnostic info*/
if (prtLv>0) {
/* Tell time range */
TR2String (timer, msgtxt);
Obit_log_error(err, OBIT_InfoErr, "Timerange %s", msgtxt);
if (myClean->Pixels) {
Obit_log_error(err, OBIT_InfoErr,
"Total CLEAN flux density = %8.1f, resid = %8.1f Jy",
myClean->Pixels->totalFlux, myClean->Pixels->maxResid);
} else {
Obit_log_error(err, OBIT_InfoErr, "CLEAN failed");
}
ObitErrLog(err);
}
/* Save epoch information */
nEpoch = i;
if (nEpoch<=MAXEPOCH) {
subaEpoch[nEpoch-1] = suba;
timeEpoch[nEpoch-1] = (timer[0]+timer[1]) * 0.5;
timeIEpoch[nEpoch-1] = timer[1] - timer[0];
} else { /* blew arrays */
Obit_log_error(err, OBIT_InfoWarn,
"%s: Overflowed internal arrays (%d) stopping IonCal",
routine, MAXEPOCH);
break; /* Full, stop calibrating */
}
/* save image reference frequency */
refFreq = myMosaic->images[0]->myDesc->crval[myMosaic->images[0]->myDesc->jlocf];
/* Do fits to each image in mosaic if CLEAN succeeded */
if (!badTime) {
/* Digest CLEAN images */
ObitIonCalPosMosaic (in, myMosaic, nEpoch, err);
} else {
/* Mark entries bad */
CalBadTime (in, myMosaic, nEpoch, err);
Obit_log_error(err, OBIT_InfoWarn, "%s: CLEAN Failed this time slice",
routine);
/* Mark entries bad */
}
if (err->error) goto cleanup;
/* Keep track of epoch times, subarrays */
/* Diagnostic info*/
if (prtLv>0) {
/* Print solutions for this epoch */
ObitErrLog(err); /* show any messages on err */
}
} /* end loop L500: over snapshots */
/* Fit model, write IN table */
NItab = FitAll (in, ncoef, nEpoch, timeEpoch, timeIEpoch, subaEpoch,
refFreq, &seeing, err);
/* Save seeing */
dim[0] = dim[1] = dim[2] = 1;
ObitInfoListAlwaysPut(inUV->info, "seeing", OBIT_float, dim, &seeing);
/* If requested convert to SN */
if (doSN) {
off[0] = off[1] = 0.0;
SNtab = ObitIoN2SolNTableConvert (inUV, NItab, NULL, off, err);
if (err->error) goto cleanup;
}
/* Cleanup */
cleanup: myClean = ObitDConCleanVisUnref(myClean);
NXtab = ObitTableNXUnref(NXtab);
SNtab = ObitTableSNUnref(SNtab);
NItab = ObitTableNIUnref(NItab);
if (gotit) g_free(gotit);
ObitImageMosaicZapImage (myMosaic, -1, err);
myMosaic = ObitImageMosaicUnref (myMosaic);
if (err->error) Obit_traceback_msg (err, routine, inUV->name);
/* Reset timerange, subarray */
dim[0] = 2; dim[1] = 1;
timer[0] = -1.0e20; timer[1] = 1.0e20;
ObitInfoListAlwaysPut (inUV->info, "timeRange", OBIT_float, dim, timer);
dim[0] = 1;
suba = 0;
ObitInfoListAlwaysPut (inUV->info, "Subarray", OBIT_long, dim, &suba);
} /* end of routine ObitIonCaldoCal */
/**
* Determines calibrator position offsets from images in a mosaic.
* Asumes given a calList with entries corresponding to entries in an
* Image mosaic, fit the actual positioins in the mosaic and write new
* entries in the CalList with offsets for acceptable fits.
* Resultant positions are all referred to a tangent plane at the
* pointing center, this is referred to as the Zernike plane as this
* plane will be used to fit the phase screen. The "Zernike Unit
* Circle" defines the phase screen. Source position offsets are in
* the X and Y (RA, Dec) as defined by this plane.
* Routine adapted from the AIPSish CALPOS.FOR/CALPOS
* \param in IonCal object
* Control parameters are on the info member.
* \li "nZern" OBIT_int (1,1,1) Zernike polynomial order requested [def 5]
* \li FitDist OBIT_int (1,1,1) dist, from expected location to search
* asec [10 pixels]
* \li MinPeak OBIT_float (1,1,1) Min. acceptable image peak (Jy) [1.0]
* \li MaxDist OBIT_float (1,1,1) Max. distance (deg/10) to accept calibrator [1.]
* \li MaxWt OBIT_float (1,1,1) Max. weight [10.0]
* \li MaxQual OBIT_int (1,1,1) Max. cal. quality code [def 1]
* \li prtLv OBIT_int (1,1,1) Print level >=1 => give fits
* \param mosaic Image mosaic object
* \param calList Calibrator list each element of which has:
* \li ra position RA (deg) of calibrators
* \li dec position Dec (deg) of calibrators
* \li shift Offset in field [x,y] on unit Zernike circle of position
* \li pixel Expected pixel in reference image
* \li flux Estimated catalog flux density
* \li offset Measured offset [x,y] from expected position (deg)
* \li peak Measured peak flux density (image units)
* \li fint Measured integrated flux density (image units)
* \li wt Determined weight
* \li qual Catalog quality code
* \param err Error stack
* \param epoch Epoch number
*/
void ObitIonCalPosMosaic (ObitIonCal *in, ObitImageMosaic* mosaic,
olong epoch, ObitErr* err)
{
olong field, j, good, FitSize=0, prtLv, ncoef, nobs, maxQual, addSize, nZern;
olong number, total;
ofloat flux, FitDist, dist;
ofloat mxcdis, maxwt, MaxRMS, MaxRMS2, rms;
gint32 dim[MAXINFOELEMDIM] = {1,1,1,1,1};
ObitInfoType type;
ofloat offset[2], pixel[2], corr[2], coef[17], peak, fint, dr, dd, wt;
ObitImage *image=NULL;
CalListElem *elem=NULL, *nelem=NULL;
GSList *tmp;
CalList *calList;
gboolean doMore;
ofloat *x=NULL, *y=NULL, *dx=NULL, *dy=NULL, *w=NULL;
olong *isou=NULL;
gchar *routine = "ObitIonCalPosMosaic";
/* Error checks */
g_assert(ObitErrIsA(err));
if (err->error) return ; /* previous error? */
g_assert(ObitIonCalIsA(in));
g_assert(ObitImageMosaicIsA(mosaic));
calList = (CalList*)in->calList;
/* Control information. */
maxwt = 10.0;
ObitInfoListGetTest(in->info, "MaxWt", &type, dim, &maxwt);
flux = 1.0;
ObitInfoListGetTest(in->info, "MinPeak", &type, dim, &flux);
mxcdis = 1.0;
ObitInfoListGetTest(in->info, "MaxDist", &type, dim, &mxcdis);
maxQual = 1;
ObitInfoListGetTest(in->info, "MaxQual", &type, dim, &maxQual);
FitDist = 0.0;
ObitInfoListGetTest(in->info, "FitDist", &type, dim, &FitDist);
FitDist /= 3600.0; /* to degrees */
nZern = 5;
ObitInfoListGetTest(in->info, "nZern", &type, dim, &nZern);
ncoef = nZern;
prtLv = 0;
ObitInfoListGetTest(in->info, "prtLv", &type, dim, &prtLv);
MaxRMS = 10.0;
ObitInfoListGetTest(in->info, "MaxRMS", &type, dim, &MaxRMS);
MaxRMS /= 3600.0; /* to deg */
MaxRMS2 = 2.0 * MaxRMS; /* relax for finding sources */
/* lenient RMS = 3 pixels
MaxRMS = 3.0*fabs(mosaic->images[0]->myDesc->cdelt[0]); */
/* First pass to get basic geometric distortions */
/* allocate memory */
nobs = mosaic->numberImages;
x = g_malloc0(nobs*sizeof(ofloat));
y = g_malloc0(nobs*sizeof(ofloat));
dx = g_malloc0(nobs*sizeof(ofloat));
dy = g_malloc0(nobs*sizeof(ofloat));
w = g_malloc0(nobs*sizeof(ofloat));
isou = g_malloc0(nobs*sizeof(olong));
/* Loop getting initial positions */
nobs = 0;
for (field=0; field<mosaic->numberImages; field++) {
image = mosaic->images[field];
/* Convert FitDist to pixels */
if (FitDist<=0.0) FitDist = 10.0 * fabs(image->myDesc->cdelt[0]) / 3600.0;
FitSize = (olong)((FitDist / fabs(image->myDesc->cdelt[0]))+0.5);
FitSize = MAX (10, FitSize);
/* Find cal info */
tmp = calList->list;
while (tmp!=NULL) { /* loop 100 */
elem = (CalListElem*)tmp->data;
if (elem->calNo == (field+1)) break; /* found it */
tmp = g_slist_next(tmp); /* next item in list */
} /* end loop L100: over calibrator list */
PosImage (image, elem->pixel, flux, mxcdis, FitSize,
offset, &peak, &fint, err);
if (err->error) goto cleanup;
if (peak>flux) { /* Valid datum? */
/* Within maximum distance? */
dist = sqrt(elem->ZernXY[0]*elem->ZernXY[0] + elem->ZernXY[1]*elem->ZernXY[1]);
if (dist <= mxcdis) w[nobs] = MIN (maxwt, peak);
else w[nobs] = 0.0;
if (elem->qual>maxQual) w[nobs] = 0.0; /* Only acceptable quality */
x[nobs] = elem->ZernXY[0];
y[nobs] = elem->ZernXY[1];
dx[nobs] = offset[0];
dy[nobs] = offset[1];
isou[nobs] = nobs;
nobs++; /* This one OK */
/* diagnostics? */
if (prtLv>=3) {
Obit_log_error(err, OBIT_InfoErr,
"Initial E=%5d C=%5d Z= %7.4f %7.4f off=%7.2f %7.2f Peak=%6.2f int=%6.2f qual=%d",
epoch, elem->calNo, elem->ZernXY[0], elem->ZernXY[1],
offset[0]*3600.0, offset[1]*3600.0, peak, fint, elem->qual);
}
} /* End if detected */
} /* end loop over fields */
/* Work out Zernike model for field - fit and edit */
doMore = TRUE;
while (doMore) {
rms = IonFit1 (nobs, isou, x, y, dx, dy, w, &ncoef, coef, prtLv, err);
if (rms<MaxRMS2) break;
doMore = IonEdit1 (nobs, isou, x, y, dx, dy, w, MaxRMS2, ncoef, coef, prtLv, err);
if (err->error) goto cleanup;
}
/* Was it happy with the results? */
good = 0;
for (j=0; j<nobs; j++) if (w[j]>0.0) good++;
if ((good<=2) || (rms>MaxRMS2)) { /* need at least 3, no? - use no distortion */
ncoef = 2;
coef[0] = coef[1] = 0;
FitSize = MAX (10, FitSize);
} else { /* OK - set size of fitting region */
FitSize = 10;
/* Add an amount propostional to tip/tilt */
addSize = 0.5 + (0.1 * (sqrt (coef[0]*coef[0]+coef[1]*coef[1]) /
fabs(mosaic->images[0]->myDesc->cdelt[0])) +
/* Add a tern for the rms residual */
+ rms/fabs(mosaic->images[0]->myDesc->cdelt[0]));
FitSize += addSize;
}
if (prtLv>=2) {
Obit_log_error(err, OBIT_InfoErr,
"%s: Initial no. cal %d rms %f Search Size %d",
routine, good, rms*3600.0, FitSize);
}
cleanup:
if (x) g_free(x); x =NULL;
if (y) g_free(y); y =NULL;
if (dx) g_free(dx); dx=NULL;
if (dy) g_free(dy); dy=NULL;
if (w) g_free(w); w =NULL;
if (isou) g_free(isou);
if (err->error) Obit_traceback_msg (err, routine, image->name);
/* Loop over images getting final positions */
good = 0;
for (field=0; field<mosaic->numberImages; field++) {
image = mosaic->images[field];
/* Find cal info */
tmp = calList->list;
while (tmp!=NULL) { /* loop 100 */
elem = (CalListElem*)tmp->data;
if (elem->calNo == (field+1)) break; /* found it */
tmp = g_slist_next(tmp); /* next item in list */
} /* end loop L100: over calibrator list */
/* Work out expected position */
dr = 0.0;
dd = 0.0;
for (j=0; j<ncoef; j++) {
dr += coef[j]*ObitZernikeGradX(j+2, elem->ZernXY[0], elem->ZernXY[1]);
dd += coef[j]*ObitZernikeGradY(j+2, elem->ZernXY[0], elem->ZernXY[1]);
}
corr[0] = dr / image->myDesc->cdelt[0];
corr[1] = dd / image->myDesc->cdelt[1];
pixel[0] = elem->pixel[0] - corr[0];
pixel[1] = elem->pixel[1] - corr[1];
PosImage (image, pixel, flux, mxcdis, FitSize,
offset, &peak, &fint, err);
if (err->error) Obit_traceback_msg (err, routine, image->name);
/* Adjust result for quess of position */
offset[0] += dr;
offset[1] += dd;
if (peak>flux) { /* Valid datum? */
/* Within maximum distance? */
dist = sqrt(elem->ZernXY[0]*elem->ZernXY[0] + elem->ZernXY[1]*elem->ZernXY[1]);
if (dist <= mxcdis) wt = MIN (maxwt, peak);
else wt = 0.0;
/* Update CalList */
nelem = newCalListElem (elem->ra, elem->dec, elem->ZernXY, elem->shift,
elem->pixel, elem->flux, offset, peak, fint, wt,
elem->qual, field+1, epoch);
CalListAdd (calList, nelem);
good++; /* This one OK */
/* diagnostics? */
if (prtLv>=1) {
Obit_log_error(err, OBIT_InfoErr,
"Fit E=%5d C=%5d Z= %7.4f %7.4f off=%7.2f %7.2f Peak=%6.2f int=%6.2f qual=%d",
epoch, elem->calNo, elem->ZernXY[0], elem->ZernXY[1],
offset[0]*3600.0, offset[1]*3600.0, peak, fint, elem->qual);
}
} /* End if detected */
} /* end loop over fields */
if (prtLv>=5) {
/*ObitMemPrint (stdout);DEBUG*/
ObitMemSummary (&number, &total);
Obit_log_error(err, OBIT_InfoErr, "%s: Memory use, %d entries %d MByte)",
routine, number, total);
}
/* tell how many */
Obit_log_error(err, OBIT_InfoErr, "%s: Fitted %d calibrator offsets",
routine, good);
/* If there aren't any - flag time */
if (good<1) {
CalBadTime (in, mosaic, epoch, err);
Obit_log_error(err, OBIT_InfoWarn, "%s: CLEAN Failed this time slice",
routine);
}
} /* end of routine ObitIonCalPosMosaic */
/**
* Search for a source at the given position return fitted
* flux density and offsets from the expected positions.
* A source is only accepted if the peak is within
* 0.5*min(imsi[0],imsi[1]) pixels of the center.
* \param image Image open and plane read and attached
* \param pixel Expected pixel (1-rel) of centroid
* \param minflux Min. allowed peak flux density
* \param mxcdis Max. distance from center - not used here
* \param FitSize Full width in pixels of search window around pixel
* \param offset [out] Offset from expected position in cells
* \param peak [out] Peak flux density
* \param fint [out] integrated flux density
* \param err Error stack
*/
static void PosImage (ObitImage *image, ofloat pixel[2], ofloat minflux,
ofloat mxcdis, olong FitSize,
ofloat offset[2], ofloat *peak, ofloat *fint, ObitErr *err)
{
olong j, imsi[2];
olong blc[IM_MAXDIM] = {1,1,1,1,1,1,1};
olong trc[IM_MAXDIM] = {0,0,0,0,0,0,0};
gint32 dim[MAXINFOELEMDIM] = {1,1,1,1,1};
ObitIOSize IOBy;
ofloat area, pixelOff[2];
gchar *routine = "PosImage";
/* Open and read image full plane */
IOBy = OBIT_IO_byPlane;
dim[0] = 1;
ObitInfoListAlwaysPut (image->info, "IOBy", OBIT_long, dim, &IOBy);
dim[0] = 7;
for (j=0; j<IM_MAXDIM; j++) {blc[j] = 1; trc[j] = 0;}
ObitInfoListAlwaysPut (image->info, "BLC", OBIT_long, dim, blc);
ObitInfoListAlwaysPut (image->info, "TRC", OBIT_long, dim, trc);
image->extBuffer = FALSE; /* Make sure it has buffer */
ObitImageOpen (image, OBIT_IO_ReadOnly, err);
ObitImageRead (image, NULL, err);
if (err->error) Obit_traceback_msg (err, routine, image->name);
/* fit source */
imsi[0] = imsi[1] = FitSize;
CalPosFit (image, pixel, imsi, pixelOff, peak, fint, err);
if (err->error) Obit_traceback_msg (err, routine, image->name);
/* Close image */
ObitImageClose (image, err);
if (err->error) Obit_traceback_msg (err, routine, image->name);
image->image = ObitImageUnref(image->image); /* Free buffer */
/* find anything? */
if (*peak<minflux) { /* Nope */
*peak = 0.0;
} else { /* yes */
/* Offset */
offset[0] = pixelOff[0] * image->myDesc->cdelt[0];
offset[1] = pixelOff[1] * image->myDesc->cdelt[1];
/* Normalize integrated flux by beam area in pixels */
area = 1.1331 * image->myDesc->beamMaj * image->myDesc->beamMin /
(fabs (image->myDesc->cdelt[0]) * fabs (image->myDesc->cdelt[1])) ;
if (area < 0.001) area = 1.0;
*fint /= area;
}
} /* end PosImage */
/**
* Initialize global ClassInfo Structure.
*/
void ObitIonCalClassInit (void)
{
if (myClassInfo.initialized) return; /* only once */
/* Set name and parent for this class */
myClassInfo.ClassName = g_strdup(myClassName);
myClassInfo.ParentClass = ObitParentGetClass();
/* Set function pointers */
ObitIonCalClassInfoDefFn ((gpointer)&myClassInfo);
myClassInfo.initialized = TRUE; /* Now initialized */
} /* end ObitIonCalClassInit */
/**
* Initialize global ClassInfo Function pointers.
*/
static void ObitIonCalClassInfoDefFn (gpointer inClass)
{
ObitIonCalClassInfo *theClass = (ObitIonCalClassInfo*)inClass;
ObitClassInfo *ParentClass = (ObitClassInfo*)myClassInfo.ParentClass;
if (theClass->initialized) return; /* only once */
/* Check type of inClass */
g_assert (ObitInfoIsA(inClass, (ObitClassInfo*)&myClassInfo));
/* Initialize (recursively) parent class first */
if ((ParentClass!=NULL) &&
(ParentClass->ObitClassInfoDefFn!=NULL))
ParentClass->ObitClassInfoDefFn(theClass);
/* function pointers defined or overloaded this class */
theClass->ObitClassInit = (ObitClassInitFP)ObitIonCalClassInit;
theClass->newObit = (newObitFP)newObitIonCal;
theClass->ObitClassInfoDefFn = (ObitClassInfoDefFnFP)ObitIonCalClassInfoDefFn;
theClass->ObitGetClass = (ObitGetClassFP)ObitIonCalGetClass;
theClass->ObitCopy = (ObitCopyFP)ObitIonCalCopy;
theClass->ObitClone = NULL;
theClass->ObitClear = (ObitClearFP)ObitIonCalClear;
theClass->ObitInit = (ObitInitFP)ObitIonCalInit;
theClass->ObitIonCalCreate = (ObitIonCalCreateFP)ObitIonCalCreate;
} /* end ObitIonCalClassDefFn */
/*---------------Private functions--------------------------*/
/**
* Creates empty member objects, initialize reference count.
* Parent classes portions are (recursively) initialized first
* \param inn Pointer to the object to initialize.
*/
void ObitIonCalInit (gpointer inn)
{
ObitClassInfo *ParentClass;
ObitIonCal *in = inn;
/* error checks */
g_assert (in != NULL);
/* recursively initialize parent class members */
ParentClass = (ObitClassInfo*)(myClassInfo.ParentClass);
if ((ParentClass!=NULL) && ( ParentClass->ObitInit!=NULL))
ParentClass->ObitInit (inn);
/* set members in this class */
in->thread = newObitThread();
in->info = newObitInfoList();
in->calList = (gpointer)newCalList();
in->myData = NULL;
} /* end ObitIonCalInit */
/**
* Deallocates member objects.
* Does (recursive) deallocation of parent class members.
* \param inn Pointer to the object to deallocate.
* Actually it should be an ObitIonCal* cast to an Obit*.
*/
void ObitIonCalClear (gpointer inn)
{
ObitClassInfo *ParentClass;
ObitIonCal *in = inn;
/* error checks */
g_assert (ObitIsA(in, &myClassInfo));
/* delete this class members */
in->thread = ObitThreadUnref(in->thread);
in->info = ObitInfoListUnref(in->info);
freeCalList((CalList*)in->calList); in->calList=NULL;
in->myData = ObitUVUnref(in->myData);
/* unlink parent class members */
ParentClass = (ObitClassInfo*)(myClassInfo.ParentClass);
/* delete parent class members */
if ((ParentClass!=NULL) && ( ParentClass->ObitClear!=NULL))
ParentClass->ObitClear (inn);
} /* end ObitIonCalClear */
/**
* Search for a source at the given position return fitted
* flux density and offsets from the expected positions.
* A source is only accepted if the peak is within
* 0.5*min(imsi[0],imsi[1]) pixels of the center.
* Routine translated from the AIPSish CALPOS.FOR/FXPFIT
* \param image Image open and plane read and attached
* \param inPixel Expected pixel (1-rel) of centroid
* \param imsi Full width of the window to search around inPixel
* \param pixelOff Fitted offset from expected pixel (pixels)
* \param souflx Fitted peak flux density
* Value < 0.0 indicate source not found or
* otherwise unacceptable.
* \param souint Integrated flux density in 9x9 (not normalized by
* beam area)
* \param err Error stack
*/
static void CalPosFit (ObitImage *image, ofloat inPixel[2], olong* imsi,
ofloat pixelOff[2], ofloat* souflx, ofloat* souint,
ObitErr *err)
{
ofloat s, dx[2], dis, maxdis;
olong i1, i2, j1, j2, ic, jc;
olong blc[2], trc[2], pos[7], iX, iY, iXp, iYp, iXcen, iYcen;
ofloat data[9][9], pixval=0.0, *pixP, sum, fblank= ObitMagicF();
ObitFArray *fitData;
gchar *routine = "CalPosFit";
/* Initial values */
*souflx = -1.0;
*souint = -1.0;
pixelOff[0] = 0.0;
pixelOff[1] = 0.0;
/* Find peak, copy data */
ic = inPixel[0] + 0.5; /* Closest pixel */
jc = inPixel[1] + 0.5;
i1 = ic - imsi[0] / 2 ;
i2 = ic + (imsi[0] / 2) - 1;
j1 = jc - imsi[1] / 2 ;
j2 = jc + (imsi[1] / 2) - 1;
i1 = MAX (MIN (i1, image->myDesc->inaxes[0]), 1);
i2 = MIN (MAX (i2, i1), image->myDesc->inaxes[0]);
j1 = MAX (MIN (j1, image->myDesc->inaxes[1]), 1);
j2 = MIN (MAX (j2, j1), image->myDesc->inaxes[1]);
blc[0] = i1-1; blc[1] = j1-1; /* to zero rel */
trc[0] = i2-1; trc[1] = j2-1;
fitData = ObitFArraySubArr (image->image, blc, trc, err);
if (err->error) Obit_traceback_msg (err, routine, image->name);
/* Peak */
s = ObitFArrayMax (fitData, pos);
*souflx = s;
/* use 9x9 values around center */
iXcen = pos[0];
iYcen = pos[1];
sum = 0.0;
for (iY=0; iY<9; iY++) {
iYp = iYcen + iY - 4;
pos[1] = iYp;
for (iX=0; iX<9; iX++) {
iXp = iXcen + iX - 4;
pos[0] = iXp;
/* get value */
pixP = ObitFArrayIndex (fitData, pos);
if (pixP) pixval = *pixP; /* in array? */
else pixval = fblank;
if (pixval!=fblank) {
data[iY][iX] = pixval;
sum += pixval;
} else /* blank */
data [iY][iX] = fblank;
}
} /* end of loop loading image data in array */
/* Cleanup */
fitData = ObitFArrayUnref(fitData);
/* Fit peak in data */
if (pfit (data, &s, dx, fblank)) {
*souflx = -1.0; /* fit failed */
*souint = -1.0;
return;
}
*souflx = s; /* Fitted peak */
*souint = sum; /* Integral is sum */
/* get offset from expected */
dx[0] += iXcen; /* offset in fitData */
dx[1] += iYcen;
/* revert to 1-rel */
pixelOff[0] = (-(dx[0] + blc[0] + 1 - inPixel[0]));
pixelOff[1] = (-(dx[1] + blc[1] + 1 - inPixel[1]));
/* Is he close enough to the center? */
maxdis = (0.5 * MIN (imsi[0], imsi[1]))*(0.5 * MIN (imsi[0], imsi[1]));
dis = pixelOff[0]*pixelOff[0] + pixelOff[1]*pixelOff[1];
if (dis > maxdis) { /* Nope */
*souflx = -1.0;
*souint = -1.0;
return;
}
} /* end of routine CalPosFit */
/**
* Searches Catalog for calibrators an image and with an estimated flux
* density in excess of a given limit taking into account the estimated
* single-dish beam
* Adapted from the AIPSish ADNVSS in $FOURMASS/SUB/ADDFIELDS.FOR
* \param image image in question
* \param Catalog FITS AIPSVZ format catalog file name
* \param catDisk FITS disk number for Catalog
* \param OutlierFlux Minimum estimated flux density
* \param OutlierSI Spectral index to use to convert catalog flux density
* \param qual Maximum qualifier quality code
* \param AntDiam Primary antenna diameter (m) [default 25]
* \param calList calibrator list, a linked list of calibrators
* \param prtLv Print level >=3 => give list
* \param err Error stack, returns if not empty.
*/
static void
FindCalImage (ObitImage *image, gchar *Catalog, olong catDisk,
ofloat OutlierFlux, ofloat OutlierSI, olong qual, ofloat AntDiam,
CalList *calList, olong prtLv, ObitErr *err)
{
olong count, cqual;
odouble Freq, ra, dec, ra2000, dc2000, ra2000d, dc2000d;
odouble xx, yy, zz, dist, refreq;
ofloat radius, radRA, minflx, asize, alpha, pbf;
ofloat flux, scale;
gboolean doJ2B, doJinc, wanted;
olong blc[IM_MAXDIM] = {1,1,1,1,1};
olong trc[IM_MAXDIM] = {0,0,0,0,0};
olong ver, nrows, irow;
olong bad, calNo, ierr, epoch=0;
ofloat shift[2], pixel[2], offset[2]={0.0,0.0}, peak=0.0, fint=0.0, wt=0.0;
ofloat ZernXY[2];
ObitIOCode retCode;
ObitImageDesc *desc=NULL;
ObitImage *VZImage=NULL;
ObitTableVZ *VZTable=NULL;
ObitTableVZRow *VZRow=NULL;
CalListElem *elem=NULL;
gchar *routine = "FindCalImage";
/* error checks */
if (err->error) return;
g_assert(ObitImageIsA(image));
/* get control parameters */
minflx = OutlierFlux;
alpha = OutlierSI;
asize = AntDiam;
/* set defaults. */
if (asize <= 0.0) asize = 25.0;
if (alpha == 0.0) alpha = -0.75;
/* Is image in B1950? */
desc = image->myDesc;
doJ2B = (fabs(image->myDesc->equinox-1950.0) < 1.0) ||
(fabs(desc->epoch-1950.0) < 1.0);
/* get j2000 position to lookup in Catalog in radians */
ra2000 = DG2RAD * desc->crval[desc->jlocr];
dc2000 = DG2RAD * desc->crval[desc->jlocd];;
if (doJ2B) ObitSkyGeomBtoJ (&ra2000, &dc2000);
ra2000d = ra2000 * RAD2DG;
dc2000d = dc2000 * RAD2DG;
/* set crude search radius = 0.5*sqrt(2)*MAX (x_size, Y_size) */
radius = 0.5 * sqrt (2.0) *
MIN (fabs(desc->cdelt[desc->jlocr]*desc->inaxes[desc->jlocr]),
fabs(desc->cdelt[desc->jlocd]*desc->inaxes[desc->jlocd]));
radRA = radius / cos(dc2000);
/* Observing frequency */
if (desc->jlocf>=0) Freq = desc->crval[desc->jlocf];
else Freq = 1.0e9;
/* which beam model to use */
doJinc = (Freq >= 1.0e9);
/* Open Catalog (VZ table on an image) */
VZImage = newObitImage("Catalog image");
ObitImageSetFITS(VZImage, OBIT_IO_byPlane, catDisk, Catalog, blc, trc, err);
/* Open to fully instantiate */
ObitImageOpen(VZImage, OBIT_IO_ReadOnly, err);
if (err->error) Obit_traceback_msg (err, routine, VZImage->name);
/* Now get VZ table */
ver = 1;
VZTable = newObitTableVZValue("Catalog table", (ObitData*)VZImage, &ver,
OBIT_IO_ReadOnly, err);
ObitTableVZOpen(VZTable, OBIT_IO_ReadOnly, err);
VZRow = newObitTableVZRow (VZTable); /* Table row */
if (err->error) Obit_traceback_msg (err, routine, VZTable->name);
/* Get table info */
refreq = VZTable->refFreq;
nrows = VZTable->myDesc->nrow;
/* frequency scaling */
scale = pow ((Freq / refreq), alpha);
/* loop through table */
count = 0;
for (irow= 1; irow<=nrows; irow++) { /* loop 500 */
/* read */
retCode = ObitTableVZReadRow (VZTable, irow, VZRow, err);
if (err->error) Obit_traceback_msg (err, routine, VZTable->name);
/* spectral scaling of flux density */
flux = VZRow->PeakInt * scale;
/* position, etc */
ra = VZRow->Ra2000;
dec = VZRow->Dec2000;
cqual = VZRow->Quality;
/* select (crude) */
if ((fabs(dc2000d-dec) <= radius) && (fabs(ra2000d-ra) <= radRA) &&
(flux >= minflx)) {
/* separation from pointing center */
xx = DG2RAD * ra;
yy = DG2RAD * dec;
zz = sin (yy) * sin (dc2000) + cos (yy) * cos (dc2000) * cos (xx-ra2000);
zz = MIN (zz, 1.000);
dist = acos (zz) * RAD2DG;
if (dist>radius) continue;
/* primary beam correction to flux density */
if (doJinc) {
pbf = ObitPBUtilJinc (dist, Freq, asize, 0.05);
} else {
pbf = ObitPBUtilPoly (dist, Freq, 0.05);
}
flux *= MAX (0.05, pbf); /* Don't trust below 5% */
/* Convert position to pixel and see if in image*/
bad =
ObitSkyGeomXYpix(ra, dec,
desc->crval[desc->jlocr], desc->crval[desc->jlocd],
desc->crpix[desc->jlocr], desc->crpix[desc->jlocd],
desc->cdelt[desc->jlocr], desc->cdelt[desc->jlocd],
desc->crota[desc->jlocd], &desc->ctype[desc->jlocr][4],
&pixel[0], &pixel[1]);
bad = bad || (pixel[0]<1.0) || (pixel[0]>desc->inaxes[0]) ||
(pixel[1]<1.0) || (pixel[1]>desc->inaxes[1]);
/* select (fine) */
wanted = ((flux >= minflx) && (dist <= radius)) && (bad==0) && (cqual<=qual);
if (wanted) {
if (doJ2B) { /* precess if necessary */
ra *= DG2RAD;
dec *= DG2RAD;
ObitSkyGeomBtoJ (&ra, &dec);
ra *= RAD2DG;
dec *= RAD2DG;
}
/* get shift needed */
ObitSkyGeomShiftXY (desc->crval[desc->jlocr], desc->crval[desc->jlocd],
desc->crota[desc->jlocd], ra, dec,
&shift[0], &shift[1]);
/* Offset on Zernike plane */
ObitSkyGeomRADec2Zern (desc->crval[desc->jlocr], desc->crval[desc->jlocd],
shift[0], shift[1], &ZernXY[0], &ZernXY[1], &ierr);
Obit_return_if_fail((ierr==0), err,
"%s: Error projecting onto Zernike Unit circle", routine);
/* Add to CalList */
calNo = count;
elem = newCalListElem (ra, dec, ZernXY, shift, pixel, flux, offset,
peak, fint, wt, cqual, calNo, epoch);
CalListAdd (calList, elem);
count++;
} /* end if wanted */
} /* end crude selection */
} /* end loop over table */
/* tell how many */
Obit_log_error(err, OBIT_InfoErr, "%s: Found %d calibrators", routine, count);
/* Close up */
ObitImageClose(VZImage, err);
retCode = ObitTableVZClose(VZTable, err);
if (err->error) Obit_traceback_msg (err, routine, VZTable->name);
VZImage->image = ObitImageUnref(VZImage->image); /* Free buffer */
/* Diagnostics? */
if (prtLv>=3) {
CalListPrint(calList, stdout);
}
/* clean up */
VZImage = ObitImageUnref(VZImage);
VZTable = ObitTableUnref(VZTable);
VZRow = ObitTableRowUnref(VZRow);
} /* end of routine FindCalImage */
/**
* Edit Zernike data.
* Edit data in attempt to get rms residual under MaxRMS
* by zeroing weight of most discrepant datum which must have
* at least 1.5 x the average contribution to the variance.
* Also checks that there is enough data to overdetermine the model.
* Routine adapted from the AIPSish IONCAL.FOR/IONEDT
* \param nobs Number of observations
* \param isou Source number per obs. (0-rel)
* \param x Offset in field X (RA) on unit Zernike circle per source
* \param y Offset in field Y (Dec) on unit Zernike circle per source
* \param dx Apparent RA position shifts on the Zernike plane (deg)
* \param dy Apparent dec position shifts on the Zernike plane (deg)
* \param w Weight per source, may be set to zero,
* \param MaxRMS Target RMS residual (units of dx, dy)
* \param ncoef number of coefficients in coef
* \param coef Zernike coefficients to use
* \param prtLv Print level >=2 tell about editing
* \param err Error stack
* \return True if data was edited
*/
static gboolean
IonEdit1 (olong nobs, olong* isou, ofloat* x, ofloat* y, ofloat* dx, ofloat* dy,
ofloat* w, ofloat MaxRMS, olong ncoef, ofloat* coef, olong prtLv,
ObitErr* err)
{
olong i, j, is, rmscnt, ibad;
gboolean out = FALSE;
ofloat dr, dd, rx, ry, rms;
ofloat *gdx=NULL, *gdy=NULL, var, *ResidV=NULL, baddest;
gchar *routine = "IonEdit1";
if (nobs<=0) return FALSE; /* Something to do? */
/* Allocate memory */
gdx = g_malloc(nobs*ncoef*sizeof(ofloat));
gdy = g_malloc(nobs*ncoef*sizeof(ofloat));
ResidV = g_malloc(nobs*sizeof(ofloat));
/* Compute Zernike gradients */
for (i=0; i<nobs; i++) {
is = isou[i];
for (j=0; j<ncoef; j++) {
gdx[j*nobs+i] = ObitZernikeGradX(j+2, x[is], y[is]);
gdy[j*nobs+i] = ObitZernikeGradY(j+2, x[is], y[is]);
} /* end loop over coefficients */
} /* end loop over sources */
/* get RMS and residuals */
rms = 0.0;
rmscnt = 0;
for (i=0; i<nobs; i++) {
if (w[i] > 0.0) {
dr = 0.0;
dd = 0.0;
for (j=0; j<ncoef; j++) {
dr += coef[j]*gdx[j*nobs+i];
dd += coef[j]*gdy[j*nobs+i];
}
rx = dx[i] - dr;
ry = dy[i] - dd;
var = rx*rx + ry*ry;
ResidV[i] = var;
rms += var;
rmscnt++;
}
}
/* must have enough data to be over determined */
if ((2*rmscnt) < (ncoef+1)) goto cleanup;
var = rms/rmscnt;
rms = sqrt (var);
/* Is the current version OK? */
if (rms <= MaxRMS) goto cleanup;
/* find the most discrepent */
ibad = -1;
baddest = 0.0;
for (i=0; i<nobs; i++) {
if ((w[i]>0.0) && (ResidV[i]> baddest)) {
baddest = ResidV[i];
ibad = i;
}
}
/* Is the bad one at least 1.5x average variance? */
if (baddest<(1.5*var)) goto cleanup;
w[ibad] = 0.0; /* Flag it */
out = TRUE; /* Flagged something */
/* Diagnostics */
if (prtLv>=2) {
Obit_log_error(err, OBIT_InfoErr,
"%s: Flag obs %d variance=%f rms=%f",
routine, ibad+1, baddest*3600.0, rms*3600.0);
}
/* Deallocate memory */
cleanup:
g_free(ResidV);
g_free(gdx);
g_free(gdy);
return out;
} /* end IonEdit1 */
/**
* Get timerange of next interval
* Routine translated from the AIPSish IONCAL.FOR/ICNXTI
* \param NXtab Index table
* \param solInt Solution interval in min.
* \param timer In: previous timerange (days), -1 => none.
* Out: next time range
* \param suba [out] Subarray number
* \param err Error code: 0 => ok, -1 = no more.
* \return TRUE if there is more data to process
*/
static gboolean NextTime (ObitTableNX *NXtab, ofloat solInt,
ofloat timer[2], olong* suba, ObitErr* err)
{
gboolean out = FALSE;
olong numNX, npiece;
olong irow, NXrow=0;
ofloat si, tbeg, tend, vtend=0, vtbeg=0, ts, te;
ObitTableNXRow *row;
gchar *routine = "NextTime";
/* Error checks */
if (err->error) return FALSE; /* previous error? */
g_assert(ObitTableNXIsA(NXtab));
if (err->error) return FALSE; /* previous error? */
/* Create table row */
row = newObitTableNXRow (NXtab);
/* Open table */
ObitTableNXOpen(NXtab, OBIT_IO_ReadOnly, err);
if (err->error) goto cleanup;
numNX = NXtab->myDesc->nrow;
/* Save initial timerange */
tbeg = timer[0];
tend = timer[1];
si = solInt / 1440.0;
/* Find next scan */
for (irow= 1; irow<= numNX; irow++) { /* loop 200 */
NXrow = irow;
ObitTableNXReadRow (NXtab, NXrow, row, err);
if (err->error) goto cleanup;
if (row->status<0) continue; /* valid row? */
/* time range of this scan */
vtbeg = row->Time - 0.5 * row->TimeI;
vtend = row->Time + 0.5 * row->TimeI;
/* Ends before previous start? */
if (vtend < tbeg) continue;
/* Is previous end in this scan? */
if ((tend > vtbeg) && (tend < vtend) &&
/* Anything left? */
((tend+0.5*si) < vtend)) break;
/* Past last scan, take this one */
if (tend < vtbeg) break;
} /* end loop L200: */
out = TRUE; /* got here without failing */
/* Are we done? */
if ((NXrow == numNX) && ((tend+0.5*si) > vtend)) {
out = FALSE;
goto cleanup;
}
/* Divide scan into equal pieces */
npiece = 0.5 + row->TimeI / si;
npiece = MAX (1, npiece);
si = row->TimeI / npiece;
/* which one is this? */
ts = MAX (vtbeg, tend);
te = ts + si;
/* Set output */
timer[0] = ts;
timer[1] = te;
*suba = MAX (1, row->SubA);
/* Found it, close table */
cleanup: ObitTableNXClose(NXtab, err);
row = ObitTableNXRowUnref (row);
if (err->error) Obit_traceback_val (err, routine, NXtab->name, out);
return out;
} /* end of routine NextTime */
/**
* Generate a Calibrator list from an ImageMosaic
* This assumes that the expected calibrator position is the
* reference pixel in the image.
* Calibrators added to CalList as epoch 0;
* \param in IonCal object (used for catalog info )
* \param mosaic Mosaic to use
* \param calList calibrator list, a linked list of calibrators
* \param prtLv Print level >=1, give cal info >=3 => give full list
* \param err Error stack, returns if not empty.
*/
static void
FindCalMosaic (ObitIonCal *in, ObitImageMosaic *mosaic,
CalList *calList, olong prtLv, ObitErr *err)
{
olong field, calNo, cqual, ierr, epoch=0;
ofloat flux, peak=0.0, fint=0.0, wt=0.0;
ofloat ZernXY[2], shift[2], pixel[2], offset[2]={0.0,0.0};
odouble ra, dec, raPnt, decPnt;
ObitImageDesc *desc=NULL;
CalListElem *elem=NULL;
gchar *routine = "FindCalMosaic";
/* error checks */
if (err->error) return;
g_assert(ObitImageMosaicIsA(mosaic));
/* Get pointing position for offsets */
desc = mosaic->images[0]->myDesc;
ObitImageDescGetPoint (desc, &raPnt, &decPnt);
/* Loop over images */
for (field=0; field<mosaic->numberImages; field++) {
calNo = field+1;
/* Info from Mosaic */
desc = mosaic->images[field]->myDesc;
ra = desc->crval[desc->jlocr];
dec = desc->crval[desc->jlocd];
pixel[0] = desc->crpix[desc->jlocr];
pixel[1] = desc->crpix[desc->jlocd];
/* Some items to be filled in from catalog */
cqual = -1;
flux = -1.0;
/* get shift needed */
ObitSkyGeomShiftXY (raPnt, decPnt, desc->crota[desc->jlocd], ra, dec,
&shift[0], &shift[1]);
/* Offset on Zernike plane */
ObitSkyGeomRADec2Zern ( raPnt, decPnt, shift[0], shift[1],
&ZernXY[0], &ZernXY[1], &ierr);
Obit_return_if_fail((ierr==0), err,
"%s: Error projecting onto Zernike Unit circle", routine);
/* Add to CalList */
elem = newCalListElem (ra, dec, ZernXY, shift, pixel, flux, offset,
peak, fint, wt, cqual, calNo, epoch);
CalListAdd (calList, elem);
} /* end loop over fields */
/* Get calibrator information from calList */
LookupCals (in, mosaic, calList, prtLv, err);
if (err->error) Obit_traceback_msg (err, routine, in->name);
/* Diagnostics? */
if (prtLv>=3) {
CalListPrint(calList, stdout);
}
} /* end FindCalMosaic */
/**
* Looks up calibrators in calList in the catalog specified (or implied)
* by in->info and fills in catalog information.
* Adapted from the AIPSish ADNVSS in $FOURMASS/SUB/ADDFIELDS.FOR
* \param in IonCal with catalog information
* \param mosaic ImageMosaic to describing calList fields
* \param calList calibrator list, a linked list of calibrators
* \param prtLv Print level >=1 => give list
* \param err Error stack, returns if not empty.
*/
static void
LookupCals (ObitIonCal *in, ObitImageMosaic *mosaic, CalList *calList,
olong prtLv, ObitErr *err)
{
gint32 dim[MAXINFOELEMDIM] = {1,1,1,1,1};
ObitInfoType type;
gchar Catalog[257];
olong catDisk;
olong count, cqual;
odouble Freq, ra, dec, rar, decr, raPntr, decPntr;
odouble xx, yy, zz, dist, refreq;
ofloat radius, radRA, asize, alpha, pbf;
ofloat equinox, flux, scale;
gboolean doJ2B, doJinc;
olong blc[IM_MAXDIM] = {1,1,1,1,1};
olong trc[IM_MAXDIM] = {0,0,0,0,0};
olong ver, nrows, irow;
ObitIOCode retCode;
ObitImage *VZImage=NULL;
ObitTableVZ *VZTable=NULL;
ObitTableVZRow *VZRow=NULL;
ObitImageDesc *desc=NULL;
GSList *tmp;
CalListElem *elem=NULL;
gchar *routine = "LookupCals";
/* error checks */
if (err->error) return;
g_assert(ObitImageMosaicIsA(mosaic));
/* get control parameters */
/* Control information. */
sprintf (Catalog, "Default");
ObitInfoListGetTest(in->info, "Catalog", &type, dim, Catalog);
if (err->error) Obit_traceback_msg (err, routine, in->name);
if (!strncmp(Catalog, " ", 4)) sprintf (Catalog, "Default");
if (!strncmp(Catalog, "Default", 7)) sprintf (Catalog, "NVSSVZ.FIT");
catDisk = 1;
ObitInfoListGetTest(in->info, "CatDisk", &type, dim, &catDisk);
alpha = -0.75;
ObitInfoListGetTest(in->info, "OutlierSI", &type, dim, &alpha);
asize = 25.0;
ObitInfoListGetTest(in->info, "AntDiam", &type, dim, &asize);
/* set defaults. */
if (asize <= 0.0) asize = 25.0;
if (alpha == 0.0) alpha = -0.75;
/* set crude search radius = 0.5*sqrt(2)*MAX (x_size, Y_size) */
desc = mosaic->images[0]->myDesc;
radius = 0.5 * sqrt (2.0) *
MIN (fabs(desc->cdelt[desc->jlocr]*desc->inaxes[desc->jlocr]),
fabs(desc->cdelt[desc->jlocd]*desc->inaxes[desc->jlocd]));
radRA = radius / cos(desc->crval[desc->jlocd]*DG2RAD);
/* Get pointing position for offsets */
ObitImageDescGetPoint (desc, &raPntr, &decPntr);
raPntr *= DG2RAD;
decPntr *= DG2RAD;
/* Observing frequency */
if (desc->jlocf>=0) Freq = desc->crval[desc->jlocf];
else Freq = 1.0e9;
/* which beam model to use */
doJinc = (Freq >= 1.0e9);
/* Need precession? */
equinox = in->myData->myDesc->equinox; /* Clear up confusion in AIPS */
if (equinox<1.0) equinox = in->myData->myDesc->epoch;
doJ2B = (equinox!=2000.0) ; /* need to precess? */
/* Open Catalog (VZ table on an image) */
VZImage = newObitImage("Catalog image");
ObitImageSetFITS(VZImage, OBIT_IO_byPlane, catDisk, Catalog, blc, trc, err);
if (err->error) goto cleanup;
/* Open to fully instantiate */
ObitImageOpen(VZImage, OBIT_IO_ReadOnly, err);
if (err->error) goto cleanup;
/* Now get VZ table */
ver = 1;
VZTable = newObitTableVZValue("Catalog table", (ObitData*)VZImage, &ver,
OBIT_IO_ReadOnly, err);
ObitTableVZOpen(VZTable, OBIT_IO_ReadOnly, err);
VZRow = newObitTableVZRow (VZTable); /* Table row */
if (err->error) goto cleanup;
/* Get table info */
refreq = VZTable->refFreq;
nrows = VZTable->myDesc->nrow;
/* frequency scaling */
scale = pow ((Freq / refreq), alpha);
/* loop through table */
count = 0;
for (irow= 1; irow<=nrows; irow++) { /* loop 500 */
/* read */
retCode = ObitTableVZReadRow (VZTable, irow, VZRow, err);
if (err->error) goto cleanup;
/* spectral scaling of flux density */
flux = VZRow->PeakInt * scale;
/* position, etc */
ra = VZRow->Ra2000;
dec = VZRow->Dec2000;
/* Need in 1950? */
if (doJ2B) ObitSkyGeomJtoB (&ra, &dec);
rar = ra * DG2RAD;
decr = dec * DG2RAD;
cqual = VZRow->Quality;
/* Loop over calList */
tmp = calList->list;
while (tmp!=NULL) {
elem = (CalListElem*)tmp->data;
/* select (crude) */
if ((fabs(dec-elem->dec) <= radius) && (fabs(ra-elem->ra) <= radRA)) {
/* separation from pointing center */
xx = DG2RAD * elem->ra;
yy = DG2RAD * elem->dec;
zz = sin (yy) * sin (decr) + cos (yy) * cos (decr) * cos (xx-rar);
zz = MIN (zz, 1.000);
dist = acos (zz) * RAD2DG;
/* Must be within a pixel */
if (dist<fabs(desc->cdelt[desc->jlocr])) {
/* Distance from pointing center */
zz = sin (yy) * sin (decPntr) + cos (yy) * cos (decPntr) * cos (xx-raPntr);
zz = MIN (zz, 1.000);
dist = acos (zz) * RAD2DG;
/* primary beam correction to flux density */
if (doJinc) {
pbf = ObitPBUtilJinc (dist, Freq, asize, 0.05);
} else {
pbf = ObitPBUtilPoly (dist, Freq, 0.05);
}
flux *= MAX (0.05, pbf); /* Don't trust below 5% */
/* update CalList */
CalListElemUpdate (elem, elem->ra, elem->dec, elem->ZernXY, elem->shift,
elem->pixel, flux, elem->offset,
elem->peak, elem->fint, elem->wt, cqual,
elem->calNo, elem->epoch);
count++;
/* Diagnostics? */
if (prtLv>=1) {
Obit_log_error(err, OBIT_InfoErr,
"Cal %4d RA=%8.5f Dec=%9.5f Z= %7.4f %7.4f Flux=%6.2f qual=%d",
elem->calNo, elem->ra, elem->dec, elem->ZernXY[0], elem->ZernXY[1],
flux, cqual);
}
} /* End update entry */
} /* end crude selection */
tmp = g_slist_next(tmp); /* next item in list */
} /* end loop over calList */
} /* end loop over table */
/* tell how many */
Obit_log_error(err, OBIT_InfoErr, "%s: Found %d calibrators", routine, count);
/* Close up */
ObitImageClose(VZImage, err);
retCode = ObitTableVZClose(VZTable, err);
if (err->error) goto cleanup;
/* clean up */
cleanup: VZImage = ObitImageUnref(VZImage);
VZTable = ObitTableUnref(VZTable);
VZRow = ObitTableRowUnref(VZRow);
if (err->error) Obit_traceback_msg (err, routine, VZTable->name);
} /* end of routine LookupCals */
/**
* Filter position offset solutions and fit Zernike models to each epoch.
* Results written into NI table which is returned.
* Routine adapted from the AIPSish IONCAL.FOR/IONFIT
* \param in IonCal object
* Control parameters are on the info member.
* \li "FitDist" OBIT_int (1,1,1) dist, from expected location to search
* asec [10 pixels]
* \li "MinPeak" OBIT_float (1,1,1) Min. acceptable image peak (Jy) [1.0]
* \li "MaxDist" OBIT_float (1,1,1) Max. distance (deg/10) to accept calibrator [1.]
* \li "MaxWt" OBIT_float (1,1,1) Max. weight [10.0]
* \li prtLv OBIT_int (1,1,1) Print level >=1 => give fits
* \param calList Calibrator list each element of which has:
* \li ra position RA (deg) of calibrators
* \li dec position Dec (deg) of calibrators
* \li shift Offset in field [x,y] on unit Zernike circle of position
* \li pixel Expected pixel in reference image
* \li flux Estimated catalog flux density
* \li offset Measured offset [x,y] from expected position (deg)
* \li peak Measured peak flux density (image units)
* \li fint Measured integrated flux density (image units)
* \li wt Determined weight
* \li qual Catalog quality code
* \param ncoef Maximum number of coefficients to fit
* \param nEpoch Number of epochs
* \param timeEpoch Center time of each Epoch (day)
* \param timeIEpoch Time interval of each Epoch (day)
* \param subaEpoch Epoch subarray
* \param refFreq Reference Frequency for NI table (Hz)
* \param seeing [out] RMS residual to final fits (asec).
* \param err Error stack
*/
static ObitTableNI*
FitAll (ObitIonCal *in, olong ncoef, olong nEpoch,
ofloat *timeEpoch, ofloat *timeIEpoch, olong *subaEpoch,
odouble refFreq, ofloat *seeing, ObitErr* err)
{
ObitTableNI* out = NULL;
ObitUV *inUV=NULL;
CalListElem *elem=NULL;
GSList *tmp;
CalList *calList;
ofloat maxWt, MaxRMS, MinRat, MinPeak, FCStrong;
gboolean doINEdit;
olong prtLv, nobs, nTime, nsou, maxQual, is;
gint32 dim[MAXINFOELEMDIM] = {1,1,1,1,1};
ObitInfoType type;
olong *isou=NULL, *iTime=NULL, *flqual=NULL;
ofloat *x=NULL, *y=NULL, *xoff=NULL, *yoff=NULL,
*flux=NULL, *wt=NULL, *sint=NULL;
gchar *routine = "FitAll";
/* Error checks */
if (err->error) return NULL; /* previous error? */
g_assert(ObitIonCalIsA(in));
*seeing = -1.0;
calList = (CalList*)in->calList;
inUV = in->myData;
/* Control information. */
maxWt = 10.0;
ObitInfoListGetTest(in->info, "MaxWt", &type, dim, &maxWt);
prtLv = 0;
ObitInfoListGetTest(in->info, "prtLv", &type, dim, &prtLv);
MaxRMS = 10;
ObitInfoListGetTest(in->info, "MaxRMS", &type, dim, &MaxRMS);
MaxRMS /= 3600.0; /* to degrees */
doINEdit = TRUE;
ObitInfoListGetTest(in->info, "doINEdit", &type, dim, &doINEdit);
maxQual = 1;
ObitInfoListGetTest(in->info, "MaxQual", &type, dim, &maxQual);
MinRat = 0.1;
ObitInfoListGetTest(in->info, "MinRat", &type, dim, &MinRat);
MinPeak = 1.0;
ObitInfoListGetTest(in->info, "MinPeak", &type, dim, &MinPeak);
FCStrong = 1.0e6;
ObitInfoListGetTest(in->info, "FCStrong", &type, dim, &FCStrong);
/* Count number of sources, number of times and number of obs */
nobs = nTime = nsou = 0;
tmp = calList->list;
while (tmp!=NULL) { /* loop 100 */
elem = (CalListElem*)tmp->data;
if (elem->epoch > 0) {
nobs++;
nTime = MAX (nTime, elem->epoch);
nsou = MAX (nsou, elem->calNo);
}
/* if find epoch > 0 then quit loop */
tmp = g_slist_next(tmp); /* next item in list */
} /* end loop L100: over calibrator*/
/* Create arrays */
isou = g_malloc0(nobs*sizeof(olong));
iTime = g_malloc0(nobs*sizeof(olong));
flqual = g_malloc0(nobs*sizeof(olong));
x = g_malloc0((nsou+1)*sizeof(ofloat));
y = g_malloc0((nsou+1)*sizeof(ofloat));
xoff = g_malloc0(nobs*sizeof(ofloat));
yoff = g_malloc0(nobs*sizeof(ofloat));
flux = g_malloc0(nobs*sizeof(ofloat));
wt = g_malloc0(nobs*sizeof(ofloat));
sint = g_malloc0(nobs*sizeof(ofloat));
/* Extract data from calList */
nobs = 0;
tmp = calList->list;
while (tmp!=NULL) { /* loop 100 */
elem = (CalListElem*)tmp->data;
if (elem->epoch > 0) {
isou[nobs] = elem->calNo-1;
iTime[nobs] = elem->epoch-1;
flqual[nobs] = elem->qual;
is = MAX (0, MIN (isou[nobs], nsou));
x[is] = elem->ZernXY[0];
y[is] = elem->ZernXY[1];
xoff[nobs] = elem->offset[0];
yoff[nobs] = elem->offset[1];
flux [nobs] = elem->peak;
sint[nobs] = elem->fint;
/* Impose maximum Quality */
if (elem->qual<=maxQual) wt[nobs] = elem->wt;
else wt[nobs] = 0.0;
wt[nobs] = MIN (wt[nobs], maxWt);
/* Impose minimum flux density */
if (flux[nobs]<MinPeak) wt[nobs] = 0.0;
nobs++;
}
/* if find epoch > 0 then quit loop */
tmp = g_slist_next(tmp); /* next item in list */
} /* end loop L100: over calibrator*/
/* do fitting */
out = doIonFitAll (inUV, MaxRMS, MinRat, FCStrong, doINEdit,
ncoef, nsou, isou, x, y, nEpoch,
timeEpoch, timeIEpoch, subaEpoch,
nobs, iTime, xoff, yoff, flux, wt, flqual, sint,
prtLv, refFreq, seeing, err);
/* deallocate arrays */
/* cleanup:*/
if (isou) g_free(isou);
if (iTime) g_free(iTime);
if (flqual) g_free(flqual);
if (x) g_free(x);
if (y) g_free(y);
if (xoff) g_free(xoff);
if (yoff) g_free(yoff);
if (flux) g_free(flux);
if (wt) g_free(wt);
if (sint) g_free(sint);
if (err->error) Obit_traceback_val (err, routine, in->name, out);
return out;
} /* end of routine FitAll */
/**
* Weighted fit ionospheric model to data using Zernike polynomials.
* Also filters data on basis of RMS residual if RMS exceeds MaxRMS.
* Writes values to the output IoN (NI) table.
* Ignores sources further than 10 degrees from the pointing
* Position are all referred to a tangent plane at the
* pointing center, this is referred to as the Zernike plane as this
* plane will be used to fit the phase screen. The "Zernike Unit
* Circle" defines the phase screen. Source position offsets are in
* the x and y (RA, Dec) as defined by this plane.
* Routine translated from the AIPSish IONCAL.FOR/IONFIT
* Input:
* \param inUV UV data to which output NI table is to be attached.
* \param MaxRMS Max. allowable RMS before filtering data. (deg)
* \param MinRat Minimum acceptable ratio to average flux
* \param FCStrong Min. Flux for strong (required) cal
* \param doINEdit if true flag solutions for which the seeing residual
* could not be determined or exceeds MAXRMS
* \param ncoef Number of Zernike coeffients to solve for.
* \param nsou Number of sources
* \param isou Source numbers (0-rel)
* \param x X Offset (RA) in field on unit Zernike circle per source
* \param y Y Offset (Dec) in field on unit Zernike circle per source
* \param nTime Number of time intervals
* \param Time Center time of each integration
* \param TimeI Time Interval of each integration
* \param isuba Subarray number per time
* \param n Number of data points (observations)
* \param iTime Time interval number per observation.(0-rel)
* \param xoff Apparent RA position shifts on the Zernike plane (deg)
* per observation
* \param yoff Apparent dec position shifts on the Zernike plane (deg)
* per observation
* \param flux Array of measured peak flux densities
* per observation
* \param wt Array of weights, per observation
* \param flqual Field quality (crowding) code. Used in determining
* if the apparent position of a source can be moved.
* per observation
* \param sint Array of measured integrated flux densities
* per observation
* \param prtLv Print level >=1 => give fitting diagnostics
* \param refFreq Reference Frequency for NI table (Hz)
* \param totRMS [out] Total residual RMS seeing in asec
* \param err Error stack
* \return ObitTableNI into which values were written (ver 1)
*/
static ObitTableNI*
doIonFitAll (ObitUV *inUV, ofloat MaxRMS, ofloat MinRat, ofloat FCStrong, gboolean doINEdit,
olong ncoef, olong nsou, olong* isou, ofloat* x, ofloat* y,
olong nTime, ofloat* Time, ofloat* TimeI, olong* isuba,
olong n, olong* iTime, ofloat* xoff, ofloat* yoff,
ofloat* flux, ofloat *wt, olong* flqual, ofloat* sint,
olong prtLv, odouble refFreq, ofloat* totRMS, ObitErr* err)
{
ObitTableNI *outTab = NULL;
ObitTableNIRow *NIrow=NULL;
olong i, j, ntoss;
ofloat xy, timer[2], fblank = ObitMagicF();
gboolean redo, redo2;
olong *mcoef=NULL, ngood, nbad, maxcoef;
ofloat **coef=NULL, *soffx=NULL, *soffy=NULL, *rms=NULL;
gboolean *gotsou=NULL, *fitsou=NULL, allFlag, OK;
olong ver, rowNo;
gchar msgtxt[80];
gchar *routine = "doIonFitAll";
/* Error checks */
if (err->error) return outTab; /* previous error? */
g_assert(ObitUVIsA(inUV));
/* Something to do? */
if ((n<1) || (nsou<1)) return outTab;
/* allocate arrays */
mcoef = g_malloc0(nTime*sizeof(olong));
rms = g_malloc0((nTime+1)*sizeof(ofloat));
soffx = g_malloc0(nsou*sizeof(ofloat));
soffy = g_malloc0(nsou*sizeof(ofloat));
gotsou = g_malloc0(nsou*sizeof(gboolean));
fitsou = g_malloc0(nsou*sizeof(gboolean));
coef = g_malloc0(nTime*sizeof(ofloat*));
for (i=0; i<nTime; i++) coef[i] = g_malloc0(ncoef*sizeof(ofloat));
/* Diagnostics - show input data */
if (prtLv>=3) {
/* Source info */
for (i=0; i<nsou; i++) {
Obit_log_error(err, OBIT_InfoErr,
"Source %4d Zernike offset = %10.6f %10.6f", i+1, x[i], y[i]);
}
/* Epoch info */
for (i=0; i<nTime; i++) {
Obit_log_error(err, OBIT_InfoErr,
"Time %4d Time %10.6f hr dTime%10.6f min Subarray %4d",
i+1, Time[i]*24.0, TimeI[i]*1440.0, isuba[i]);
}
/* Measurement data */
for (i=0; i<n; i++) {
Obit_log_error(err, OBIT_InfoErr,
"Obs %4d Time %5d Sou %5d Offset %6.2f %6.2f Peak %6.2f Int %6.2f qual %2d",
i+1, iTime[i]+1, isou[i]+1, xoff[i]*3600.0, yoff[i]*3600.0, flux[i], sint[i], flqual[i]);
}
ObitErrLog(err);
} /* end diagnostics */
allFlag = TRUE;
for (j=0; j<nsou; j++) { /* loop 50 */
/* Diagnostics */
if (prtLv>=3) {
Obit_log_error(err, OBIT_InfoErr,
"%s: S=%4d x=%10.5f y=%10.5f", routine, j+1, x[j], y[j]);
}
/* Flag data for sources further than 10 deg (1 on unit circle) */
xy = sqrt (x[j]*x[j] + y[j]*y[j]);
if (xy > 1.0) {
for (i=0; i<n; i++) { /* loop 40 */
if (isou[i] == (j+1)) flux[i] = 0.0;
} /* end loop L40: */;
}
} /* end loop L50: */
/* further constraints on weights */
for (i=0; i<n; i++) { /* loop 60 */
/* Toss data if integrated value less than a third the peak
if (sint[i] < (0.35*flux[i])) wt[i] = 0.0; */
if (sint[i] < (0.05*flux[i])) wt[i] = 0.0; /* DEBUG */
/* ... more than thrice the peak */
if (sint[i] > (3.0*flux[i])) wt[i] = 0.0;
} /* end loop L60: */
/* Init Ionospheric model */
OK = initIonModel (n, nsou, nTime, ncoef, isou, iTime, x, y, xoff, yoff, wt,
flqual, mcoef, gotsou, fitsou, soffx, soffy, coef, prtLv, err);
if (err->error) goto cleanup;
if (!OK) {allFlag=TRUE; goto AllBad;} /* Fell flat */
/* How many sources actually have data? */
ngood = 0;
for (i=0; i<nsou; i++) { /* loop 70 */
if (gotsou[i]) ngood++;
} /* end loop L70: */
/* Fit Ionospheric model if enough data */
if (ngood > 3)
FitIonSeries (n, nsou, nTime, ncoef, isou, iTime, x, y, xoff, yoff, wt,
mcoef, gotsou, fitsou, soffx, soffy, coef, rms, prtLv, err);
if (err->error) goto cleanup;
/* If only one source dummy rms at 1 asec */
if (ngood==1) {
for (i=0; i<nTime; i++) rms[i] = 1.0/ 3600.0;
}
/* Edit Ionospheric model */
if (doINEdit && (ngood > 3)) {
redo = IonEditSeries (n, nsou, nTime, ncoef, isou, iTime, x, y,
xoff, yoff, wt, MaxRMS, mcoef,
soffx, soffy, coef, prtLv, err);
if (err->error) goto cleanup;
/* Edit By amplitude */
redo2 = IonEditAmp (n, nsou, nTime, isou, iTime, MinRat, FCStrong, flux, mcoef, wt,
prtLv, err);
redo = redo || redo2;
if (err->error) goto cleanup;
/* Redo Ionospheric model if data edited */
if (redo) {
OK = initIonModel (n, nsou, nTime, ncoef, isou, iTime, x, y, xoff, yoff,
wt, flqual, mcoef, gotsou, fitsou, soffx, soffy, coef,
prtLv, err);
if (err->error) goto cleanup;
if (!OK) {allFlag = TRUE; goto AllBad;}
}
/* Refit Ionospheric model */
FitIonSeries (n, nsou, nTime, ncoef, isou, iTime, x, y, xoff, yoff,
wt, mcoef, gotsou, fitsou, soffx, soffy, coef, rms, prtLv, err);
if (err->error) goto cleanup;
} /* end editing */
/* Only take solutions with the maximum number of terms */
maxcoef = -1;
ntoss = nbad = 0;
for (j=0; j<nTime; j++) maxcoef = MAX (maxcoef, mcoef[j]);
/* Create outputNI table */
ver = 1;
outTab = newObitTableNIValue ("IonCal NI table", (ObitData*)inUV, &ver,
OBIT_IO_WriteOnly, ncoef, err);
if (err->error) goto cleanup;
NIrow = newObitTableNIRow (outTab); /* Row structure */
NIrow->antNo = 0; /* No antenna specific */
NIrow->SourId = 0; /* no source ID */
/* Clear any existing rows */
ObitTableClearRows ((ObitTable*)outTab, err);
if (err->error) goto cleanup;
/* Open output NI table */
ObitTableNIOpen (outTab, OBIT_IO_WriteOnly, err);
ObitTableNISetRow (outTab, NIrow, err); /* Attach row for writing */
if (err->error) goto cleanup;
/* Header keywords */
outTab->heightIon = 1.0e7; /* Height of ionosphere = large */
outTab->refFreq = refFreq; /* image reference freq */
/* Loop over times writing results */
for (i=0; i<nTime; i++) { /* loop 200 */
/* Set IN table entry bad if mcoef[i] = 0 */
if ((mcoef[i]<maxcoef) && (mcoef[i]>0)) ntoss++;
if ((mcoef[i] >= maxcoef) && (rms[i] > 0.0)) {
NIrow->weight = 1.0 / MAX (0.001, rms[i]);
} else {
nbad++; /* Count the bad */
NIrow->weight = 0.0;
rms[i] = -1.0;
for (j=0; j<ncoef; j++) coef[i][j] = fblank;
}
/* Fill row structure */
NIrow->Time = Time[i];
NIrow->TimeI = TimeI[i];
NIrow->SubA = isuba[i];
for (j=0; j<ncoef; j++) NIrow->coef[j] = coef[i][j];
/* Write */
rowNo = -1;
ObitTableNIWriteRow (outTab, rowNo, NIrow, err);
if (err->error) goto cleanup;
/* Tell about it */
if (prtLv>=1) {
timer[0] = Time[i]-0.5*TimeI[i]; timer[1] = Time[i]+0.5*TimeI[i];
TR2String (timer, msgtxt);
Obit_log_error(err, OBIT_InfoErr,
"%5d Time %s RMS bias corr resid = %7.1f asec",i+1, msgtxt,rms[i]*3600.0);
/* Give coefficients if fitted */
if (NIrow->weight<=0.0) {
Obit_log_error(err, OBIT_InfoWarn, "This interval to be ignored");
} else { /* OK */
if (maxcoef==2)
Obit_log_error(err, OBIT_InfoErr, " %10.2f %10.2f ",
3600.0*coef[i][0], 3600.0*coef[i][1]);
else
Obit_log_error(err, OBIT_InfoErr, " %10.2f %10.2f %10.2f %10.2f %10.2f",
3600.0*coef[i][0], 3600.0*coef[i][1], 3600.0*coef[i][2],
3600.0*coef[i][3], 3600.0*coef[i][4]);
if (maxcoef>5) {
Obit_log_error(err, OBIT_InfoErr, " %10.2f %10.2f %10.2f %10.2f %10.2f",
3600.0*coef[i][5], 3600.0*coef[i][6], 3600.0*coef[i][7],
3600.0*coef[i][8], 3600.0*coef[i][9]);
}
if (maxcoef>10) {
Obit_log_error(err, OBIT_InfoErr, " %10.2f %10.2f %10.2f %10.2f %10.2f",
3600.0*coef[i][10], 3600.0*coef[i][11], 3600.0*coef[i][12],
3600.0*coef[i][13], 3600.0*coef[i][14]);
}
if (maxcoef>15) {
Obit_log_error(err, OBIT_InfoErr, " %10.2f %10.2f %10.2f %10.2f %10.2f",
3600.0*coef[i][15], 3600.0*coef[i][16], 3600.0*coef[i][17],
3600.0*coef[i][18], 3600.0*coef[i][19]);
}
}
} /* end diagnostics */
} /* end loop L200: */
/* Close NI table */
ObitTableNIClose (outTab, err);
if (err->error) goto cleanup;
/* Total RMS */
(*totRMS) = 3600.0 * rms[nTime];
/* Tell about it */
if (prtLv>=1) {
if (ntoss>0)
Obit_log_error(err, OBIT_InfoErr, "%s: Flagged %d of %d intervals for too few Zernike coef.",
routine, ntoss, nTime);
if (nbad>0)
Obit_log_error(err, OBIT_InfoErr, "%s: Flagged total %d of %d intervals",
routine, nbad, nTime);
Obit_log_error(err, OBIT_InfoErr, "Total corrected rms residual = %7.1f asec",
*totRMS);
/* Source offsets */
for (i=0; i<nsou; i++) { /* loop 240 */
if (gotsou[i] && fitsou[i]) {
Obit_log_error(err, OBIT_InfoErr, "Source %5d offset = %7.1f%7.1f ",
i+1, 3600.0*soffx[i], 3600.0*soffy[i]);
}
} /* end loop L240: */
} /* end diagnostics */
goto cleanup;
/* Solution failed */
AllBad:
if (allFlag) Obit_log_error(err, OBIT_Error,
"%s: All ionospheric solutions bad", routine);
/* cleanup - deallocate arrays */
cleanup:
NIrow = ObitTableNIRowUnref (NIrow);
/* deallocate arrays */
if (mcoef) g_free(mcoef);
if (rms) g_free(rms);
if (soffx) g_free(soffx);
if (soffy) g_free(soffy);
if (gotsou) g_free(gotsou);
if (fitsou) g_free(fitsou);
if (coef) {
for (i=0; i<nTime; i++) g_free(coef[i]);
g_free(coef);
}
if (err->error) Obit_traceback_val (err, routine, inUV->name, outTab);
return outTab;
} /* end of routine doIonFitAll */
/**
* Initialize Zernike model to apparent position offsets for a time
* series allowing for a systematic offset on the apparent source
* positions.
* Each time is analysed with fixed source positions and the soffx and
* soffy are set based on the average residual. A comparison of the
* average residual with the total rms residual is used to decide if an
* offset is to be fitted to each source (fitsou).
* Offsets are only allowed for flqual values > 0
* Routine translated from the AIPSish IONCAL.FOR/INCINI
* \param nobs Number of observations
* \param nsou Number of sources
* \param nTime Number of times
* \param maxcoe Leading dimension of COEF
* \param isou Source number per obs. (0-rel)
* \param iTime Time interval number per observation.
* \param x Offset in field X (RA) on unit Zernike circle /source
* \param y Offset in field Y (Dec) on unit Zernike circle /source
* \param dx Apparent RA position shifts on the Zernike plane (deg) /obs
* \param dy Apparent dec position shifts on the Zernike plane (deg) /obs
* \param w Weight of observations /obs
* \param flqual Field quality (crowding) code. Used in determining
* if the apparent position of a source can be moved.
* \param ncoef Number of coefficents fitted per time
* \param gotsou If true, there is data for this souce
* \param fitsou If true fit offset correction for each source
* \param soffx Initial guess for source offset in x=ra (deg)
* \param soffy Initial guess for source offset in y=dec (deg)
* \param coef Initial guess for Zernike coefficients (term,time)
* \param prtLv Print level >=1 => give fitting diagnostics
* \param err Error/message stack
* \return TRUE if data OK, else too little data
*/
static gboolean
initIonModel (olong nobs, olong nsou, olong nTime, olong maxcoe, olong* isou,
olong* iTime, ofloat* x, ofloat* y, ofloat* dx, ofloat* dy,
ofloat* w, olong* flqual, olong* ncoef, gboolean* gotsou,
gboolean* fitsou, ofloat* soffx, ofloat* soffy, ofloat** coef,
olong prtLv, ObitErr* err)
{
gboolean out=FALSE;
olong i, j, k, it, is, itim, rmscnt, numobs, numprm, itlast, itb, ite, js, ntgood;
olong qual;
ofloat rms, dr, dd, rx, ry, rr;
ofloat *sum2p1=NULL, *sum2p2=NULL, *sum3p1=NULL, *sum3p2=NULL;
ofloat *tcoef=NULL, *gdx=NULL, *gdy=NULL;
gchar *routine = "initIonModel";
/* Error checks */
g_assert(ObitErrIsA(err));
if (err->error) return out; /* previous error? */
/* Initial guess (0's) */
for (itim=0; itim<nTime; itim++) { /* loop 30 */
ncoef[itim] = 0;
for (i=0; i<maxcoe; i++) { /* loop 20 */
coef[itim][i] = 0.0;
} /* end loop L20: */
} /* end loop L30: */
/* if only one source just use tip and tilt */
if (nsou==1) {
for (itim=0; itim<nTime; itim++) { /* loop 30 */
if (w[itim]>0.0) {
gotsou[0] = TRUE;
ncoef[itim] = 2;
coef[itim][0] = dx[itim];
coef[itim][1] = dy[itim];
out = TRUE;
}
}
return out;
} /* end 1 source */
/* Allocate work arrays */
tcoef = g_malloc(maxcoe*sizeof(ofloat));
gdx = g_malloc(nsou*maxcoe*sizeof(ofloat));
gdy = g_malloc(nsou*maxcoe*sizeof(ofloat));
sum2p1 = g_malloc(nsou*sizeof(ofloat));
sum2p2 = g_malloc(nsou*sizeof(ofloat));
sum3p1 = g_malloc(nsou*sizeof(ofloat));
sum3p2 = g_malloc(nsou*sizeof(ofloat));
for (is=0; is<nsou; is++) { /* loop 40 */
soffx[is] = 0.0;
soffy[is] = 0.0;
gotsou[is] = FALSE ;
fitsou[is] = FALSE ;
sum2p1[is] = 0.0;
sum2p2[is] = 1.0e-20;
sum3p1[is] = 0.0;
sum3p2[is] = 1.0e-20;
} /* end loop L40: */
/* How many coeffients can actually be fitted? */
for (i=0; i<nobs; i++) { /* loop 60 */
it = iTime[i];
is = isou[i];
if (w[i] > 0.0) {
ncoef[it]++;
gotsou[is] = TRUE;
}
} /* end loop L60: */
for (itim=0; itim<nTime; itim++) { /* loop 70 */
ncoef[itim] = MIN (maxcoe, ncoef[itim]*2);
if (ncoef[itim] < 5) ncoef[itim] = MIN (2, ncoef[itim]);
} /* end loop L70: */;
/* Compute Zernike gradients */
for (i=0; i<nsou; i++) {
for (j=0; j<maxcoe; j++) {
gdx[j*nsou+i] = ObitZernikeGradX(j+2, x[i], y[i]);
gdy[j*nsou+i] = ObitZernikeGradY(j+2, x[i], y[i]);
} /* end loop over coefficients */
} /* end loop over sources */
rms = 0.0;
rmscnt = 0;
numobs = 0;
numprm = 0;
itlast = 0;
itb = 0;
ntgood = 0;
/* Loop over data fitting each time */
for (i=0; i<nobs; i++) { /* loop 200 */
it = iTime[i];
if ((it > 0) && (ncoef[it] > 0)) {
is = isou[i];
ite = i-1;
/* New time? */
if (it != itlast) {
IonFit1 (i-itb, &isou[itb], x, y, &dx[itb], &dy[itb],& w[itb],
&ncoef[itlast], &coef[itlast][0], prtLv, err);
numprm = numprm + ncoef[itlast];
if (ncoef[itlast] > 0) ntgood++;
/* If fewer than 4 sources don't bother */
if (nsou >= 4) {
/* Debug Diagnostics */
if ((prtLv>=3) && (ncoef[itlast]<5)) {
Obit_log_error(err, OBIT_InfoErr,
"%s: Bad time=%4d ncoef=%4d numobs=%5d numprm=%5d W= %10.3f %10.3f %10.3f %10.3f %10.3f ",
routine, itlast, ncoef[itlast], numobs, numprm,
w[itb], w[itb+1], w[itb+2], w[itb+3], w[itb+4]);
}
/* Get residuals */
for (j= itb; j<=ite; j++) { /* loop 150 */
if (w[j] > 0.0) {
js = isou[j];
/* current model */
dr = 0.0;
dd = 0.0;
for (k=0; k<ncoef[itlast]; k++) { /* loop 140 */
/* model offset */
dr += coef[itlast][k]*gdx[k*nsou+js];
dd += coef[itlast][k]*gdy[k*nsou+js];
} /* end loop L140: */;
/* Calculate residuals */
rx = dx[j] - dr;
ry = dy[j] - dd;
/* Residual statistics */
/* Debug Diagnostics */
if (prtLv>=3) {
Obit_log_error(err, OBIT_InfoErr,
"%s: S=%4d E= %5d resid %10.3f %10.3f ncoef=%4d",
routine, js+1, itlast+1, rx*3600.0, ry*3600.0, ncoef[itlast]);
if (fabs(rx)>300.0)
Obit_log_error(err, OBIT_InfoErr,
" coef: %10.3f %10.3f %10.3f %10.3f %10.3f ",
coef[itlast][0], coef[itlast][1], coef[itlast][2],
coef[itlast][3], coef[itlast][4]);
}
rms += rx*rx + ry*ry;
rmscnt++;
/* Accululate sums */
sum2p1[js] += rx * w[j];
sum2p2[js] += w[j];
sum3p1[js] += ry * w[j];
sum3p2[js] += w[j];
numobs += 2;
} /* end if positive weight */
} /* end loop L150: */
} /* end if too few source */
/* For next time interval */
itb = i;
itlast = it;
}
}
} /* end loop L200: */
/* Last time */
itlast = nTime-1;
ite = nobs-1;
IonFit1 (i-itb, &isou[itb], x, y, &dx[itb], &dy[itb], &w[itb],
&ncoef[itlast], &coef[itlast][0], prtLv, err);
numprm += ncoef[itlast];
if (ncoef[itlast] > 0) ntgood++;
/* If fewer than 4 sources don't bother */
if (nsou >= 4) {
/* Get residuals */
for (j= itb; j<=ite; j++) { /* loop 250 */
if (w[j] > 0.0) {
js = isou[j];
/* current model */
dr = 0.0;
dd = 0.0;
for (k=0; k<ncoef[itlast]; k++) { /* loop 240 */
/* model offset */
dr = dr + coef[itlast][k]*gdx[k*nsou+js];
dd = dd + coef[itlast][k]*gdy[k*nsou+js];
} /* end loop L240: */;
/* Calculate residuals */
rx = dx[j] - dr;
ry = dy[j] - dd;
rms += rx*rx + ry*ry;
rmscnt++;
/* Accululate sums */
sum2p1[js] += rx * w[j];
sum2p2[js] += w[j];
sum3p1[js] += ry * w[j];
sum3p2[js] += w[j];
numobs += 2;
}
} /* end loop L250: */;
} /* end if enough data */
/* If too few sources skip */
if (nsou < 4) goto cleanup;
/* Bail out if no data */
if (ntgood < 2)
Obit_log_error(err, OBIT_Error,
"%s: Insufficient data for ionospheric model", routine);
/* RMS */
if (numobs > numprm) rms = sqrt ((rms/rmscnt) * (numobs / (numobs - numprm)));
else rms = -1.0;
/* Tell about it */
if (prtLv>=1) {
Obit_log_error(err, OBIT_InfoErr,
"%s: initial rms residual is %17.5f asec", routine, rms*3600.0);
}
/* Decide which sources to fit and initial values */
for (is=0; is<nsou; is++) { /* loop 300 */
if (gotsou[is]) {
rx = sum2p1[is] / sum2p2[is];
ry = sum3p1[is] / sum3p2[is];
rr = sqrt (rx*rx + ry*ry);
/* Diagnostics */
if (prtLv>=3) {
Obit_log_error(err, OBIT_InfoErr,
"%s: source %4d x_off %10.4f y_off %10.4f bad %d",
routine, is+1, rx*3600.0, ry*3600.0, (rr>(0.5*rms)));
}
/* Find qual */
qual = -1;
for (k=0; k<nobs; k++) {
if (is == isou[k]) {
qual = flqual[k];
break;
}
}
/* Fit if residual > 0.5*RMS and quality worse than 0 */
if ((rr > (0.5*rms)) && (qual > 0)) {
/*debug IF ((RR.GT.(0.5*RMS))) THEN */
soffx[is] = rx;
soffy[is] = ry;
fitsou[is] = TRUE;
}
}
} /* end loop L300: */
out = TRUE; /* OK */
/* Deallocate work arrays */
cleanup:
if (tcoef) g_free(tcoef);
if (gdx) g_free(gdx);
if (gdy) g_free(gdy);
if (sum2p1) g_free(sum2p1);
if (sum2p2) g_free(sum2p2);
if (sum3p1) g_free(sum3p1);
if (sum3p2) g_free(sum3p2);
return out;
} /* end of routine initIonModel */
/**
* Final Ionospheric model for each time, uses fitted source offsets
* Routine translated from the AIPSish IONCAL.FOR/INCINI
* \param nobs Number of observations
* \param nsou Number of sources
* \param nTime Number of times
* \param maxcoe Leading dimension of COEF
* \param isou Source number per obs. (0-rel)
* \param iTime Time interval number per observation.
* \param x Offset in field X (RA) on unit Zernike circle /source
* \param y Offset in field Y (Dec) on unit Zernike circle /source
* \param dx Apparent RA position shifts on the Zernike plane (deg) /obs
* \param dy Apparent dec position shifts on the Zernike plane (deg) /obs
* \param w Weight of observations /obs
* \param ncoef Number of coefficents fitted per time
* \param fitsou If true fit offset correction for each source
* \param soffx Source offset in x=ra (deg)
* \param soffy Source offset in y=dec (deg)
* \param coef Initial guess for Zernike coefficients (term,time) ,
* updated on return
* \param prtLv Print level >=1 => give fitting diagnostics
* \param err Error/message stack
* \return TRUE if data OK, else too little data
*/
static void
finalIonModel (olong nobs, olong nsou, olong nTime, olong maxcoe, olong* isou,
olong* iTime, ofloat* x, ofloat* y, ofloat* dx, ofloat* dy,
ofloat* w, olong* ncoef, gboolean* fitsou,
ofloat* soffx, ofloat* soffy, ofloat** coef,
olong prtLv, ObitErr* err)
{
olong i, j, k, it, is, itim, rmscnt, numobs, numprm, itlast, itb, ite, js, ntgood;
ofloat rms, dr, dd, rx, ry;
ofloat *tcoef=NULL, *gdx=NULL, *gdy=NULL;
gchar *routine = "finalIonModel";
/* Error checks */
g_assert(ObitErrIsA(err));
if (err->error) return; /* previous error? */
/* if only one source just use tip and tilt */
if (nsou==1) {
for (itim=0; itim<nTime; itim++) { /* loop 30 */
if (w[itim]>0.0) {
ncoef[itim] = 2;
coef[itim][0] = dx[itim];
coef[itim][1] = dy[itim];
}
}
} /* end 1 source */
/* Allocate work arrays */
tcoef = g_malloc(maxcoe*sizeof(ofloat));
gdx = g_malloc(nsou*maxcoe*sizeof(ofloat));
gdy = g_malloc(nsou*maxcoe*sizeof(ofloat));
/* Compute Zernike gradients */
for (i=0; i<nsou; i++) {
for (j=0; j<maxcoe; j++) {
gdx[j*nsou+i] = ObitZernikeGradX(j+2, x[i], y[i]);
gdy[j*nsou+i] = ObitZernikeGradY(j+2, x[i], y[i]);
} /* end loop over coefficients */
} /* end loop over sources */
rms = 0.0;
rmscnt = 0;
numobs = 0;
numprm = 0;
itlast = 0;
itb = 0;
ntgood = 0;
/* Loop over data fitting each time */
for (i=0; i<nobs; i++) { /* loop 200 */
it = iTime[i];
if ((it > 0) && (ncoef[it] > 0)) {
is = isou[i];
ite = i-1;
/* New time? */
if (it != itlast) {
IonFit1 (i-itb, &isou[itb], x, y, &dx[itb], &dy[itb],& w[itb],
&ncoef[itlast], &coef[itlast][0], prtLv, err);
numprm += ncoef[itlast];
if (ncoef[itlast] > 0) ntgood++;
/* If fewer than 4 sources don't bother */
if (nsou >= 4) {
/* Debug Diagnostics */
if ((prtLv>=3) && (ncoef[itlast]<5)) {
Obit_log_error(err, OBIT_InfoErr,
"%s: Bad time=%4d ncoef=%4d numobs=%5d numprm=%5d W= %10.3f %10.3f %10.3f %10.3f %10.3f ",
routine, itlast, ncoef[itlast], numobs, numprm,
w[itb], w[itb+1], w[itb+2], w[itb+3], w[itb+4]);
}
/* Get residuals */
for (j= itb; j<=ite; j++) { /* loop 150 */
if (w[j] > 0.0) {
js = isou[j];
/* current model */
dr = 0.0;
dd = 0.0;
for (k=0; k<ncoef[itlast]; k++) { /* loop 140 */
/* model offset */
dr += coef[itlast][k]*gdx[k*nsou+js];
dd += coef[itlast][k]*gdy[k*nsou+js];
} /* end loop L140: */;
/* Calculate residuals */
rx = dx[j] - dr;
ry = dy[j] - dd;
/* Residual statistics */
/* Debug Diagnostics */
if (prtLv>=3) {
Obit_log_error(err, OBIT_InfoErr,
"%s: S=%4d E= %5d resid %10.3f %10.3f ncoef=%4d",
routine, js+1, itlast+1, rx*3600.0, ry*3600.0, ncoef[itlast]);
if (fabs(rx)>300.0)
Obit_log_error(err, OBIT_InfoErr,
" coef: %10.3f %10.3f %10.3f %10.3f %10.3f ",
coef[itlast][0], coef[itlast][1], coef[itlast][2],
coef[itlast][3], coef[itlast][4]);
}
rms += rx*rx + ry*ry;
rmscnt++;
numobs += 2;
} /* end if positive weight */
} /* end loop L150: */
} /* end if too few source */
/* For next time interval */
itb = i;
itlast = it;
}
}
} /* end loop L200: */
/* Last time */
itlast = nTime-1;
ite = nobs-1;
IonFit1 (i-itb, &isou[itb], x, y, &dx[itb], &dy[itb], &w[itb],
&ncoef[itlast], &coef[itlast][0], prtLv, err);
numprm += ncoef[itlast];
if (ncoef[itlast] > 0) ntgood++;
/* If fewer than 4 sources don't bother */
if (nsou >= 4) {
/* Get residuals */
for (j= itb; j<=ite; j++) { /* loop 250 */
if (w[j] > 0.0) {
js = isou[j];
/* current model */
dr = 0.0;
dd = 0.0;
for (k=0; k<ncoef[itlast]; k++) { /* loop 240 */
/* model offset */
dr = dr + coef[itlast][k]*gdx[k*nsou+js];
dd = dd + coef[itlast][k]*gdy[k*nsou+js];
} /* end loop L240: */;
/* Calculate residuals */
rx = dx[j] - dr;
ry = dy[j] - dd;
rms += rx*rx + ry*ry;
rmscnt++;
numobs += 2;
}
} /* end loop L250: */;
} /* end if enough data */
/* If too few sources skip */
if (nsou < 4) goto cleanup;
/* Bail out if no data */
if (ntgood < 2)
Obit_log_error(err, OBIT_Error,
"%s: Insufficient data for ionospheric model", routine);
/* RMS */
if (numobs > numprm) rms = sqrt ((rms/rmscnt) * (numobs / (numobs - numprm)));
else rms = -1.0;
/* Tell about it */
if (prtLv>=1) {
Obit_log_error(err, OBIT_InfoErr,
"%s: initial rms residual is %17.5f asec", routine, rms*3600.0);
}
/* Deallocate work arrays */
cleanup:
if (tcoef) g_free(tcoef);
if (gdx) g_free(gdx);
if (gdy) g_free(gdy);
return;
} /* end of routine finalIonModel */
/**
* Fit Zernike model to apparent position offsets for a time series
* allowing for a systematic offset on the apparent source positions.
* Solution uses a relaxation method from Fred Schwab:
* Pn+1 = Pn + atan2 (dChi2/dP), (d2Chi2/dP2))
* for each parameter P where n or n+1 indicates a given iteration,
* dChi2/dP is the first partial derivative of Chi squared wrt P,
* d2Chi2/d2P is the second partial derivative of Chi squared wrt P,
* Chi2 = Sum (w Abs(dxj - oxk - Sum (Pi Gxik))**2) +
* Sum (w Abs(dyj - oyk - Sum (Pi Gyik))**2)
* Must be initialized by a call to initIonModel.
* Routine translated from the AIPSish IONCAL.FOR/IOALFT
*
* dxj = apparent offset in x of obs j
* dyj = apparent offset in y of obs j
* oxk = correction to source k offset in x, k = f(j)
* oyk = correction to source k offset in y, k = f(j)
* Pi = Zernike coefficient i [COEF(I) below],
* Gxik = Zernike x gradient term i for source k
* Gyik = Zernike y gradient term i for source k
* \param nobs Number of observations
* \param nsou Number of sources
* \param nTime Number of times
* \param maxcoe Max. number of coefficients
* \param isou Source number per obs. (0-rel)
* \param iTime Time interval number per observation
* \param x Offset in field X (RA) on unit Zernike circle /source
* \param y Offset in field Y (Dec) on unit Zernike circle /source
* \param dx Apparent RA position shifts on the Zernike plane (deg)
* \param dy Apparent dec position shifts on the Zernike plane
* \param w Weights of observations
* \param ncoef Number of coefficents fitted per time
* \param gotsou If true, there is data for this souce
* \param fitsou If true fit offset correctsion for each source
* \param soffx Correction to source offset in x=ra (deg)
* input: initial guess, output: fitted values
* \param soffy Correction to source offset in y=dec (deg)
* input: initial guess, output: fitted values
* \param coef Zernike coefficients fitted (term,time)
* input: initial guess, output: fitted values
* \param trms RMS residual for each time interval (deg)
* value [nTime+] is the total corrected RMS
* Values corrected for the number of parameters.
* -1 => not determined.
* \param prtLv Print level >=1 => give fitting diagnostics
* \param err Error stack
*/
static void
FitIonSeries (olong nobs, olong nsou, olong nTime, olong maxcoe, olong* isou, olong* iTime,
ofloat* x, ofloat* y, ofloat* dx, ofloat* dy, ofloat* w, olong* ncoef,
gboolean* gotsou, gboolean* fitsou, ofloat* soffx, ofloat* soffy,
ofloat** coef, ofloat* trms, olong prtLv, ObitErr* err)
{
olong i, j, it, is, itim, rmscnt, numobs, numprm, iter;
gboolean convgd, OK;
ofloat rms=0.0, dr, dd, delta, tol, norm=0.0, test, rx, ry, pd1, pd2, wx, rmslst ;
ofloat **sum1p1=NULL, **sum1p2=NULL, *sum2p1=NULL, *sum2p2=NULL, *sum3p1=NULL, *sum3p2=NULL;
ofloat **tcoef=NULL, *tsoffx=NULL, *tsoffy=NULL, *gdx=NULL, *gdy=NULL, *sum1=NULL, *sum2=NULL;
/* Penalty terms by order of Zernike 1-4 */
ofloat pen[]={0.001, 0.001,
0.01, 0.01, 0.01,
0.03, 0.03, 0.03, 0.03, 0.03,
0.05, 0.05, 0.05,0.05, 0.05, 0.05, 0.05,
0.08, 0.08, 0.08, 0.08, 0.08, 0.08, 0.08, 0.08};
ofloat *sumWt=NULL;
gchar *routine = "FitIonSeries";
/* Error checks */
g_assert(ObitErrIsA(err));
if (err->error) return ; /* previous error? */
/* Allocate work arrays */
tsoffx = g_malloc(nsou*sizeof(ofloat));
tsoffy = g_malloc(nsou*sizeof(ofloat));
gdx = g_malloc(nsou*maxcoe*sizeof(ofloat));
gdy = g_malloc(nsou*maxcoe*sizeof(ofloat));
sum2p1 = g_malloc(nsou*sizeof(ofloat));
sum2p2 = g_malloc(nsou*sizeof(ofloat));
sum3p1 = g_malloc(nsou*sizeof(ofloat));
sum3p2 = g_malloc(nsou*sizeof(ofloat));
sum1 = g_malloc(nTime*sizeof(ofloat));
sum2 = g_malloc(nTime*sizeof(ofloat));
sum1p1 = g_malloc(nTime*sizeof(ofloat*));
sum1p2 = g_malloc(nTime*sizeof(ofloat*));
tcoef = g_malloc(nTime*sizeof(ofloat*));
sumWt = g_malloc(nTime*sizeof(ofloat));
for (i=0; i<nTime; i++) {
sum1p1[i] = g_malloc(maxcoe*sizeof(ofloat));
sum1p2[i] = g_malloc(maxcoe*sizeof(ofloat));
tcoef[i] = g_malloc(maxcoe*sizeof(ofloat));
}
/* Compute Zernike gradients */
for (i=0; i<nsou; i++) {
for (j=0; j<maxcoe; j++) {
gdx[j*nsou+i] = ObitZernikeGradX(j+2, x[i], y[i]);
gdy[j*nsou+i] = ObitZernikeGradY(j+2, x[i], y[i]);
} /* end loop over coefficients */
} /* end loop over sources */
rmslst = 1.0e20;
for (i=0; i<nTime; i++) trms[i] = 1.0;
/* Loop over iterations */
for (iter=1; iter<=200; iter++) { /* loop 600 */
convgd = TRUE; /* Can decide otherwise: */
/* Zero sums */
for (j=0; j<maxcoe; j++) { /* loop 130 */
for (itim=0; itim<nTime; itim++) { /* loop 120 */
sum1p1[itim][j] = 0.0;
sum1p2[itim][j] = 1.0e-20;
} /* end loop L120: */;
} /* end loop L130: */
for (j=0; j<nsou; j++) {
sum2p1[j] = 0.0;
sum2p2[j] = 1.0e-20;
sum3p1[j] = 0.0;
sum3p2[j] = 1.0e-20;
}
/* Loop over data doing sums */
for (it=0; it<nTime; it++) sumWt[it] = 0.0;
for (i=0; i<nobs; i++) { /* loop 200 */
if (w[i] > 0.0) {
it = iTime[i];
is = isou[i];
sumWt[it] += w[i]; /* Sum weights per time*/
/* current model */
dr = 0.0;
dd = 0.0;
for (j=0; j<ncoef[it]; j++) { /* loop 140 */
/* model offset */
dr += coef[it][j]*gdx[j*nsou+is];
dd += coef[it][j]*gdy[j*nsou+is];
} /* end loop L140: */;
/* Calculate residuals */
if (fitsou[is]) {
rx = dx[i] - soffx[is] - dr;
ry = dy[i] - soffy[is] - dd;
} else {
rx = dx[i] - dr;
ry = dy[i] - dd;
}
/* Partial derivatives for coef */
for (j=0; j<ncoef[it]; j++) { /* loop 150 */
pd1 = -rx * gdx[j*nsou+is] - ry * gdy[j*nsou+is];
pd2 = gdx[j*nsou+is]*gdx[j*nsou+is] + gdy[j*nsou+is]*gdy[j*nsou+is];
/* Sum */
sum1p1[it][j] += w[i] * pd1;
sum1p2[it][j] += w[i] * pd2;
} /* end loop L150: */;
/* Fitting this source? */
if (fitsou[is]) {
/* Partial derivatives for soffx */
pd1 = -rx;
pd2 = 1.0;
/* Sum */
sum2p1[is] += w[i] * pd1;
sum2p2[is] += w[i] * pd2;
/* Partial derivatives for soffy */
pd1 = -ry;
pd2 = 1.0;
/* Sum */
sum3p1[is] += w[i] * pd1;
sum3p2[is] += w[i] * pd2;
}
}
} /* end loop L200: */
/* Penalty functions for non zero higher order Zernike coefs */
for (it=0; it<nTime; it++) { /* loop 230 */
for (j=0; j<ncoef[it]; j++) {
sum1p1[it][j] += coef[it][j] * sumWt[it]*pen[j];
sum1p2[it][j] += sumWt[it]*pen[j];
}
}
/* Update solutions */
wx = 1.6;
OK = FALSE;
while (!OK) {
wx = wx * 0.5;
/* don't loop forever */
if (wx < 1.0e-10) goto converged;
/* Convergence criterion - lower the bar */
tol = 5.0e-6 + iter * 1.0e-5;
norm = 0.0;
numobs = 0;
numprm = 0;
/* Coefficients */
for (itim=0; itim<nTime; itim++) { /* loop 230 */
if (sumWt[itim] > 0.0) {
for (j=0; j<ncoef[itim]; j++) { /* loop 220 */
numprm++;
delta = atan2 (sum1p1[itim][j], sum1p2[itim][j]);
test = tol;
tcoef[itim][j] = coef[itim][j] - wx * delta;
/* DEBUG
if (fabs(tcoef[itim][j])>1.0) {
fprintf (stdout, "Lookout time %d parm %d coef %f part %f %f\n",
itim, j,tcoef[itim][j], sum1p1[itim][j], sum1p2[itim][j]);
} End DEBUG */
/* Convergence test */
convgd = convgd && (fabs(delta) <= test);
norm += delta*delta;
} /* end loop L220: */;
} /* end valid data for interval */
else { /* don't change coefs */
for (j=0; j<ncoef[itim]; j++) tcoef[itim][j] = coef[itim][j];
}
} /* end loop L230: */;
/* Position offsets */
for (is=0; is<nsou; is++) { /* loop 250 */
if (gotsou[is] && fitsou[is]) {
/* X offset */
delta = atan2 (sum2p1[is], sum2p2[is]);
test = tol ;
tsoffx[is] = soffx[is] - wx * delta;
/* Convergence test */
convgd = convgd && (fabs(delta) <= test);
norm +=delta*delta;
/* Y offset */
delta = atan2 (sum3p1[is], sum3p2[is]);
test = tol ;
tsoffy[is] = soffy[is] - wx * delta;
/* Convergence test */
convgd = convgd && (fabs(delta) <= test);
numprm += 2;
norm += delta*delta;
/* Debug Diagnostics */
if (prtLv>=4) {
Obit_log_error(err, OBIT_InfoErr,
"%s: iter %d source %4d off_x=%8.2f off_y=%8.2f delta_y=%8.2f",
routine, iter+1, is+1, soffx[is]*3600.0, soffy[is]*3600.0, delta*3600.0);
}
} else {
tsoffy[is] = 0.0;
tsoffx[is] = 0.0;
}
} /* end loop L250: */
/* Determine RMS */
rms = 0.0;
rmscnt = 0;
/* Time RMS sums */
for (j=0; j<nTime; j++) { /* loop 310 */
sum1[j] = 0.0;
sum2[j] = 1.0e-20;
} /* end loop L310: */;
for (i=0; i<nobs; i++) { /* loop 340 */
if (w[i] > 0.0) {
it = iTime[i];
is = isou[i];
numobs += 2;
/* current model */
dr = 0.0;
dd = 0.0;
for (j=0; j<ncoef[it]; j++) { /* loop 330 */
/* model offset */
dr += tcoef[it][j]*gdx[j*nsou+is];
dd += tcoef[it][j]*gdy[j*nsou+is];
} /* end loop L330: */;
/* Calculate residuals */
if (fitsou[is]) {
rx = dx[i] - tsoffx[is] - dr;
ry = dy[i] - tsoffy[is] - dd;
} else {
rx = dx[i] - dr;
ry = dy[i] - dd;
}
/* Residual statistics */
rms += rx*rx + ry*ry; /* Total */
rmscnt++;
sum1[it] += rx*rx + ry*ry; /* Per time */
sum2[it] += 1.0; /* NOTE: this was wrong in AIPS */
/* DEBUG
if (it==4)
fprintf (stdout,"Src %5d residX %10.5f residY %10.5f model %10.5f%10.5f \n",
is+1, rx*3600.0, ry*3600.0, dr*3600.0, dd*3600.0); */
}
} /* end loop L340: */
/* Force residuals to decrease */
if (numobs > numprm) rms = sqrt ((rms/rmscnt) * (numobs / (numobs - numprm)));
else rms = -1.0;
OK = (rms <= rmslst);
rmslst = rms;
} /* end of loop seeking improvement of fit */
/* Save values */
trms[nTime] = rms; /* total RMS */
for (j=0; j<nTime; j++) { /* loop 360 */
/* Any data and enought deg. of freedom to fit? */
if ((sumWt[j]>0.0) && ((2.0*sum2[j]) > (ncoef[j]+1))) {
trms[j] = sqrt ((sum1[j] / sum2[j]) *
(2.0*sum2[j] / (2.0*sum2[j] - ncoef[j]))) ;
/* DEBUG
if (j==4)
fprintf (stdout, "RMS %10.5f\n",trms[j]*3600.0);*/
} else {
trms[j] = -1.0;
}
/* DEBUG
if ((fabs(tcoef[j][0])>1.0) || (fabs(tcoef[j][1])>1.0)) {
fprintf (stdout, "Bother iter %d time %d coef %f %f\n",
it, j+1, tcoef[j][0], tcoef[j][1]);
} End DEBUG */
for (i=0; i<ncoef[j]; i++) { /* loop 350 */
coef[j][i] = tcoef[j][i];
} /* end loop L350: */;
} /* end loop L360: */;
for (i=0; i<nsou; i++) { /* loop 370 */
soffx[i] = tsoffx[i];
soffy[i] = tsoffy[i];
} /* end loop L370: */;
/* Debug Diagnostics */
if ((prtLv>=3) && (iter<=2)) {
/*j = nTime-1;
Obit_log_error(err, OBIT_InfoErr,
"iter %4d coef %10.5f %10.5f %10.5f %10.5f %10.5f ",
iter, 3600.0*coef[j][0], 3600.0*coef[j][1], 3600.0*coef[j][2],
3600.0*coef[j][3], 3600.0*coef[j][4]);*/
Obit_log_error(err, OBIT_InfoErr,
"iter %4d rms=%10.5f norm=%12.5g", iter, rms*3600.0, norm);
}
/* Converged? */
if (convgd) break;
} /* end loop iteration L600: */;
/* Converged */
converged:
/* Tell about it */
if (prtLv>=2) {
Obit_log_error(err, OBIT_InfoErr,
"%s: No. iteration %5d RMS resid=%17.5f norm=%12.5g",
routine, iter+1, rms*3600.0, norm);
}
/* Deallocate work arrays */
if (tsoffx) g_free(tsoffx);
if (tsoffy) g_free(tsoffy);
if (sumWt) g_free(sumWt);
if (gdx) g_free(gdx);
if (gdy) g_free(gdy);
if (sum2p1) g_free(sum2p1);
if (sum2p2) g_free(sum2p2);
if (sum3p1) g_free(sum3p1);
if (sum3p2) g_free(sum3p2);
if (sum1) g_free(sum1);
if (sum2) g_free(sum2);
if (tcoef) {
for (i=0; i<nTime; i++) {
if (tcoef[i]) g_free(tcoef[i]);
}
g_free(tcoef);
}
if (sum1p1){
for (i=0; i<nTime; i++) {
if (sum1p1[i]) g_free(sum1p1[i]);
}
g_free(sum1p1);
}
if (sum1p2){
for (i=0; i<nTime; i++) {
if (sum1p2[i]) g_free(sum1p2[i]);
}
g_free(sum1p2);
}
} /* end of routine FitIonSeries */
/**
* Edit ionospheric data based on model fit.
* Times with either insufficient data to determine a decent solution
* (4 sources) or excessive RMS residuals will be flagged by setting
* the corresponding ncoef to zero.
* Ant intervals with fewer coefficients in the model than the maximum
* will be flagged.
* Routine translated from the AIPSish IONCAL.FOR/IONEDT
* \param nobs Number of observations
* \param nsou Number of sources
* \param nTime Number of times
* \param maxcoe Maximum number of coefficients
* \param isou Source number per obs. (0-rel)
* \param iTime Time interval number per observation.
* \param x Offset in field X (RA) on unit Zernike circle /source
* \param y Offset in field Y (Dec) on unit Zernike circle /source
* \param dx Apparent RA position shifts on the Zernike plane (deg)
* \param dy Apparent dec position shifts on the Zernike plane (deg)
* \param w Weight of observations
* On output, set to zero to remove datum
* \param MaxRMS Maximum acceptable RMS residual (deg)
* \param ncoef Number of coefficents fitted per time
* On output, set to -1 to remove time.
* \param soffx Source offset in x=ra (deg)
* \param soffy Source offset in y=dec (deg)
* \param coef Zernike coefficients (term,time)
* \param prtLv Print level >=1 => give fitting diagnostics
* \param err Error/message stack
* \return TRUE if data edited.
*/
static gboolean
IonEditSeries (olong nobs, olong nsou, olong nTime,
olong maxcoe, olong* isou, olong* iTime, ofloat* x, ofloat* y,
ofloat* dx, ofloat* dy, ofloat* w, ofloat MaxRMS, olong* ncoef,
ofloat* soffx, ofloat* soffy, ofloat** coef, olong prtLv, ObitErr* err)
{
gboolean out=FALSE;
olong i, j, it, itlast, itb, ite, count, ntoss, stoss, numt;
gboolean doMore;
ofloat rms;
ofloat *lx=NULL, *ly=NULL, *gdx=NULL, *gdy=NULL;
gchar *routine = "IonEditSeries";
/* Error checks */
if (err->error) return out; /* previous error? */
/* Allocate work arrays */
gdx = g_malloc(nsou*maxcoe*sizeof(ofloat));
gdy = g_malloc(nsou*maxcoe*sizeof(ofloat));
lx = g_malloc(nsou*sizeof(ofloat));
ly = g_malloc(nsou*sizeof(ofloat));
/* Compute Zernike gradients */
for (i=0; i<nsou; i++) {
for (j=0; j<maxcoe; j++) {
gdx[j*nsou+i] = ObitZernikeGradX(j+2, x[i], y[i]);
gdy[j*nsou+i] = ObitZernikeGradY(j+2, x[i], y[i]);
} /* end loop over coefficients */
} /* end loop over sources */
numt = 0;
ntoss = 0;
stoss = 0;
itlast = iTime[0];
itb = 0;
/* Loop over data examining each time */
for (i=0; i<nobs; i++) { /* loop 200 */
it = iTime[i];
ite = i-1;
/* New time? Last? */
if ((it != itlast) || (i == (nobs-1))) {
if (i == (nobs-1)) ite = i; /* Last? */
/* Debug Diagnostics */
if (prtLv>=3) {
Obit_log_error(err, OBIT_InfoErr,
"%s: time %4d coef %10.5f %10.5f %10.5f %10.5f %10.5f ",
routine,itlast+1, 3600.0*coef[itlast][0], 3600.0*coef[itlast][1],
3600.0*coef[itlast][2], 3600.0*coef[itlast][3],
3600.0*coef[itlast][4]);
}
/* Begin editing loop */
/* Copy actual source Zernike offsets to lx, ly */
count = 0;
for (i=itb; i<=ite; i++) {
lx[count] = x[isou[i]];
ly[count] = y[isou[i]];
count++;
}
/* Fit model/edit loop */
doMore = TRUE;
while (doMore) {
rms = IonFit1 (count, &isou[itb], x, y, &dx[itb], &dy[itb], &w[itb],
&ncoef[itlast], &coef[itlast][0], prtLv, err);
if (rms<MaxRMS) break; /* Reached goal? */
doMore = IonEdit1 (count, &isou[itb], x, y, &dx[itb], &dy[itb], &w[itb],
MaxRMS, ncoef[itlast], &coef[itlast][0], prtLv, err);
if (doMore) stoss++;
}
/* If RMS still excessive toss interval */
if (rms > MaxRMS) {
if (prtLv>=2) {
Obit_log_error(err, OBIT_InfoErr,
"%s: Flagged time %d, excessive rms %f > %f",
routine, itlast+1, rms*3600.0, MaxRMS*3600.0);
}
ncoef[itlast] = -1;
ntoss++;
/* Reject data */
for (j= itb; j<=ite; j++) { /* loop 180 */
w[j] = 0.0;
} /* end loop L180: */
}
/* For next time interval */
itb = i;
itlast = it;
numt = MAX (numt, itlast);
} /* end if new time */
} /* end loop L200: */
/* Filter each source */
for (i=0; i<nsou; i++) { /* loop 10 */
/* Have adjusted the positions with no source offsets */
soffx[i] = 0.0;
soffy[i] = 0.0;
IonEditSource (i, nobs, nTime, maxcoe, nsou, isou, iTime, x, y, dx, dy, w,
MaxRMS, ncoef, soffx, soffy, coef, gdx, gdy, &stoss,
prtLv, err);
} /* end loop L10: */
/* Tell about it */
if (prtLv>=1) {
Obit_log_error(err, OBIT_InfoErr,
"%s: rejected %5d of %5d intervals, %6d single obs.",
routine, ntoss, numt+1, stoss);
}
/* Do anything? */
out = ((ntoss > 0) || (stoss > 0));
/* Deallocate work arrays */
if (lx) g_free(lx);
if (ly) g_free(ly);
if (gdx) g_free(gdx);
if (gdy) g_free(gdy);
return out;
} /* end of routine IonEditSeries */
/**
* Edit times if average measured flux is less that MinRat wrt average
* Sources brighter than FCStrong are required in all solutions at al least
* MinRat of their average.
* Times will be flagged by setting the corresponding ncoef to zero.
* Routine translated from the AIPSish IONCAL.FOR/IONAED
* \param nobs Number of observations
* \param nsou Number of sources
* \param nTime Number of times
* \param isou Source number per obs. (0-rel)
* \param iTime Time number per obs.
* \param MinRat Minimum acceptable ratio to average flux
* \param FCStrong Min. Flux for strong (required) cal
* \param flux Peak flux density of observations
* \param ncoef Number of coefficents fitted per time
* On output, set to -1 to remove time.
* \param wt Weights of observations, set to 0 if flagged
* \param prtLv Print level >=1 => give fitting diagnostics
* \param err Error/message stack
* \return TRUE if data edited.
*/
static gboolean
IonEditAmp (olong nobs, olong nsou, olong nTime, olong* isou, olong* iTime,
ofloat MinRat, ofloat FCStrong, ofloat* flux, olong* ncoef, ofloat* wt,
olong prtLv, ObitErr* err)
{
gboolean out = FALSE;
olong *cntflx=NULL, i, j, isss, ittt, ilast, drop=0, total, ib, ie;
gboolean bad, allStrong;
ofloat *sumflx=NULL, *strong=NULL, sumt1, sumt2;
gchar flg[11];
gchar *routine = "IonEditAmp";
/* Error checks */
g_assert(ObitErrIsA(err));
if (err->error) return out; /* previous error? */
/* allocate arrays */
cntflx = g_malloc0(nsou*sizeof(olong));
sumflx = g_malloc0(nsou*sizeof(ofloat));
/* get strong required flux densities */
strong = getStrong (nobs, nsou, nTime, isou, iTime, MinRat, FCStrong, flux, prtLv, err);
if (err->error) goto cleanup;
if (prtLv>=1) {
Obit_log_error(err, OBIT_InfoErr,
"Filtering solutions with min. flux ratio %10.5f",
MinRat );
Obit_log_error(err, OBIT_InfoErr,
"Strong (required) cal level %10.5f Jy",
FCStrong);
}
drop = 0;
total = 0;
/* Average source flux densities */
for (i=0; i<nsou; i++) cntflx[i] = 0;
for (i=0; i<nsou; i++) sumflx[i] = 0.0;
for (i=0; i<nobs; i++) { /* loop 20 */
if (flux[i] > 0) {
isss = isou[i];
cntflx[isss]++;
sumflx[isss] += flux[i];
}
} /* end loop L20: */
/* Normalize */
for (i=0; i<nsou; i++) { /* loop 40 */
if (cntflx[i] > 0) sumflx[i] /= cntflx[i];
} /* end loop L40: */;
/* Loop over times summing measured and averaged fluxes */
ilast = 0;
ib = 0;
ie = 0;
sumt1 = 0.0;
sumt2 = 0.0;
allStrong = TRUE;
for (i=0; i<nobs; i++) { /* loop 100 */
if (iTime[i] > ilast) {
total++;
/* New time - check results */
if (sumt2 > 0.0) sumt1 /= sumt2;
bad = (sumt1 < MinRat) || (!allStrong);
ittt = iTime[i];
if (bad) {
/* Flag time/data */
ncoef[ittt] = -1;
for (j= ib; j<= ie; j++) { /* loop 80 */
flux[j] = 0.0;
wt[j] = 0.0;
} /* end loop L80: */;
drop++;
}
/* Debug Diagnostics*/
strcpy (flg, " ");
if (bad) strcpy (flg, "flagged");
if (prtLv>=3) {
Obit_log_error(err, OBIT_InfoErr,
"%s: Time %4d average flux= %10.2f %s",
routine,ilast, sumt1, flg);
}
sumt1 = 0.0;
sumt2 = 0.0;
allStrong = TRUE;
ilast = ittt;
ib = i;
}
ie = i;
/* Check for required calibrators */
isss = isou[i];
allStrong = allStrong && (flux[i] >= strong[isss]);
/* Diagnostics */
if ((prtLv>=3) && (flux[i]< strong[isss])) {
Obit_log_error(err, OBIT_InfoErr,
"%s: Flag time %4.4d for source %4.4d since %f < %f",
routine,iTime[i],isss+1,flux[i],strong[isss]);
}
/* Sum Fluxes and average values for source. */
if (flux[i] > 0.0) {
isss = isou[i];
sumt1 += flux[i];
sumt2 += sumflx[isss];
}
} /* end loop L100: */
/* Deal with last average */
if (sumt2 > 0.0) sumt1 /= sumt2;
bad = (sumt1 < MinRat) || (!allStrong);
if (bad) {
/* Flag time/data */
ncoef[ilast] = -1;
for (j= ib; j<= ie; j++) { /* loop 120 */
wt[j] = 0.0;
flux[j] = 0.0;
} /* end loop L120: */;
drop++;
}
/* Debug Diagnostics */
strcpy (flg, " ");
if (bad) strcpy (flg, "flagged");
if (prtLv>=3) {
Obit_log_error(err, OBIT_InfoErr,
"%s: Time %4d average flux= %10.2f %s",
routine, ilast, sumt1, flg);
}
/* Tell results */
if (prtLv>=1) {
Obit_log_error(err, OBIT_InfoErr,
"%s: reject %4d of %4d times due to low peak",
routine, drop, total);
}
/* cleanup - deallocate arrays */
cleanup:
if (cntflx) g_free(cntflx);
if (sumflx) g_free(sumflx);
if (strong) g_free(strong);
out = (drop >0); /* Do anything? */
if (err->error) Obit_traceback_val (err, routine, "editing amp data", out);
return out;
} /* end of routine IonEditAmp */
/**
* Edit ionospheric data based on model fit for a given source.
* Routine translated from the AIPSish IONCAL.FOR/INESOU
* \param source Source number to edit
* \param nobs Number of observations
* \param nTime Number of times
* \param maxcoe Maximum number of coefficients
* \param nsou Number of sources
* \param isou Source number per obs. (0-rel)
* \param iTime Time interval number per observation.
* \param x Offset in field X (RA) on unit Zernike circle /source
* \param y Offset in field Y (Dec) on unit Zernike circle /source
* \param dx Apparent RA position shifts on the Zernike plane (deg)
* \param dy Apparent dec position shifts on the Zernike plane (deg)
* \param w Weight of observations
* On output, set to zero to remove datum
* \param MaxRMS Maximum acceptable RMS residual
* \param ncoef Number of coefficents fitted per time
* On output, set to -1 to remove time.
* \param soffx source offset in x=ra (deg)
* \param soffy source offset in y=dec (deg)
* \param coef Zernike coefficients (term,time)
* \param gdx Zernike gradients in X per source, coef
* \param gdy Zernike gradients in Y per source, coef
* \param stoss [in/out] Number of observations rejected
* \param prtLv Print level >=1 => give fitting diagnostics
* \param err Error stack
*/
static void IonEditSource (olong source, olong nobs, olong nTime, olong maxcoe, olong nsou,
olong* isou, olong* iTime, ofloat* x, ofloat* y,
ofloat* dx, ofloat* dy, ofloat* w, ofloat MaxRMS, olong* ncoef,
ofloat* soffx, ofloat* soffy, ofloat** coef,
ofloat *gdx, ofloat *gdy, olong* stoss, olong prtLv, ObitErr* err)
{
olong i, j, k, it, rmscnt, js, numt, *ktime, count, i1, i2, wid, idt, nt, *iobs;
ofloat rms, dr, dd, sum;
ofloat *resid, rx, ry, test, rmst;
gchar *routine = "IonEditSource";
/* allocate arrays */
resid = g_malloc0(nTime*sizeof(ofloat));
ktime = g_malloc0(nTime*sizeof(olong));
iobs = g_malloc0(nTime*sizeof(olong));
numt = 0;
rms = 0.0;
rmscnt = 0;
/* Loop over data examining each time */
for (i=0; i<nobs; i++) { /* loop 200 */
if ((isou[i] == source) && (w[i] > 0.0)) {
it = iTime[i];
ktime[numt] = iTime[i];
iobs[numt] = i;
js = isou[i];
/* current model */
dr = 0.0;
dd = 0.0;
for (k=0; k<ncoef[it]; k++) { /* loop 140 */
/* model offset */
dr += coef[it][k]*gdx[k*nsou+js];
dd += coef[it][k]*gdy[k*nsou+js];
} /* end loop L140: */
/* Calculate residuals */
rx = dx[i] - soffx[js] - dr;
ry = dy[i] - soffy[js] - dd;
resid[numt] = sqrt (rx*rx + ry*ry);
/* Residual statistics */
rms += rx*rx + ry*ry;
rmscnt++;
numt++; /* How many found? */
}
} /* end loop L200: */;
/* Enough on this source to bother? */
if (numt <= 5) goto cleanup;
/* Source RMS */
rms = sqrt (rms/rmscnt);
/* Can't be more than target */
rmst = MIN (rms, MaxRMS);
/* Loop comparing with 7 point running mean. */
nt = 0;
wid = MIN (3, numt/2);
/* (Best leave this loop 1-rel indexing) */
for (i= 1; i<=numt; i++) { /* loop 300 */
sum = 0.0;
count = 0;
i1 = i - wid;
i2 = i + wid;
if (i1 < 1) {
i2 = MIN (numt, 2*wid+1);
i1 = 1;
}
if (i2 > numt) {
i2 = MIN (numt, i2);
i1 = MAX (1, i2-2*wid);
}
/* Sum points within WID of current integration but excluding it. */
for (j= i1; j<=i2; j++) { /* loop 210 */
idt = abs (ktime[i-1]-ktime[j-1]);
if ((idt > 0) && (idt <= wid)) {
sum += resid[j-1];
count++;
}
} /* end loop L210: */
/* Need at least 2 to compare with */
if (count > 1) {
test = resid[i-1] - (sum / count);
/* Toss it if difference greater than 2 sigma. */
if (test > 2.0*rmst) {
(*stoss)++;
nt++;
w[iobs[i-1]] = 0.0;
}
} else {
/* Too little to compare - toss */
(*stoss)++;
nt++;
w[iobs[i-1]] = 0.0;
}
} /* end loop L300: */
/* Tell results */
if (prtLv>=1) {
Obit_log_error(err, OBIT_InfoErr,
"%s: Source %4d rejected %4d of %4d RMS = %10.3f",
routine, source+1, nt, numt, 3600.0*rms);
}
/* deallocate arrays */
cleanup:
if (resid) g_free(resid);
if (ktime) g_free(ktime);
if (iobs) g_free(iobs);
} /* end of routine IonEditSource */
/**
* Get minimum fluxes for strong (required) calibrators
* At least max(5, nTime/2) good observations needed for a calibrator
* to be considered
* \param nobs Number of observations
* \param nsou Number of sources
* \param nTime Number of times
* \param isou Source number per obs. (0-rel)
* \param iTime Time number per obs.
* \param MinRat Minimum acceptable ratio to average flux
* \param FCStrong Min. Flux for strong (required) cal
* \param flux Peak flux density of observations
* \param prtLv Print level >=1 => give fitting diagnostics
* \param err Error/message stack
* \return array of minimum required flux density for each source
*/
static ofloat*
getStrong (olong nobs, olong nsou, olong nTime, olong* isou, olong* iTime,
ofloat MinRat, ofloat FCStrong, ofloat* flux, olong prtLv,
ObitErr* err)
{
ofloat *strong=NULL;
olong i, ngot, navg, isss, jsou;
ofloat *srtflx=NULL, sflux;
gchar *routine = "getStrong";
/* Error checks */
g_assert(ObitErrIsA(err));
if (err->error) return strong; /* previous error? */
/* allocate arrays */
strong = g_malloc0(nsou*sizeof(ofloat));
srtflx = g_malloc0(nTime*sizeof(ofloat));
/* Loop over sources */
for (jsou=0; jsou<nsou; jsou++) {
/* Loop over observations collecting */
ngot = 0;
for (i=0; i<nobs; i++) {
if (flux[i] > 0) {
isss = isou[i];
if (isss==jsou) srtflx[ngot++] = flux[i];
}
} /* end loop over observations */
/* Get flux density */
navg = MAX (3, ngot/4);
if (ngot>=MAX(5, nTime/2))
sflux = medianAvg(srtflx, 1, navg, FALSE, ngot);
else
sflux = 0.0;
/* Set minimum allowable */
if (sflux>=FCStrong) {
strong[jsou] = MinRat * sflux;
/* Tell results */
if (prtLv>=2) {
Obit_log_error(err, OBIT_InfoErr,
"%s: Minimum flux density for source %4d = %10.3f",
routine,jsou+1, strong[jsou]);
}
} else strong[jsou] = -1.0e20;
} /* end loop over source */
if (srtflx) g_free(srtflx); /* Cleanup */
return strong;
} /* end of routine getStrong */
/**
* Fit Zernike model to apparent position offsets.
* Solution uses gsl fitting
* dxj = apparent offset in x of obs j
* dyj = apparent offset in y of obs j
* Pi = Zernike coefficient i [COEF(I) below],
* Gxij = Zernike x gradient term i for obs j
* Gyij = Zernike y gradient term i for obs j
* \param nobs Number of observations
* \param isou Source number per obs. (0-rel)
* \param x Offset in field X (RA) on unit Zernike circle per source
* \param y Offset in field Y (Dec) on unit Zernike circle per source
* \param dx Apparent RA position shifts on the Zernike plane (deg)
* \param dy Apparent dec position shifts on the Zernike plane (deg)
* \param w Weight per source.
* \param ncoef [in] Maximum number of coefficients
* [out] actual number
* \param coef [out] Zernike coefficients fitted
* \param prtLv Print level >=3 give diagnostics
* \param err Error stack
* \return RMS residual (deg) -1 on failure
*/
static ofloat
IonFit1 (olong nobs, olong* isou, ofloat* x, ofloat* y,
ofloat* dx, ofloat* dy, ofloat* w,
olong* ncoef, ofloat* coef, olong prtLv, ObitErr* err)
{
olong i, j, is, rmscnt, mcoef;
ofloat out = -1.0;
ofloat rms=0.0, dr, dd, rx, ry;
gchar *routine = "IonFit1";
/* initial values 0 */
for (i=0; i<*ncoef; i++) coef[i] = 0.0;
/* How many coeffients can actually be fitted? */
rmscnt = 0;
for (i=0; i<nobs; i++) { /* loop 10 */
if (w[i] > 0.0) rmscnt++;
} /* end loop L10: */;
*ncoef = MIN (*ncoef, rmscnt*2);
if (*ncoef < 17) (*ncoef) = MIN (10, *ncoef);
if (*ncoef < 10) (*ncoef) = MIN (5, *ncoef);
if (*ncoef < 5) (*ncoef) = MIN (2, *ncoef);
/* Better have something to work with */
if (*ncoef <= 0) return out;
mcoef = *ncoef;
/* Use gsl fit */
FitZernike ((olong)nobs, isou, x, y, dx, dy, w, (olong)mcoef, coef);
/* Get RMS */
rms = 0.0;
rmscnt = 0;
for (i=0; i<nobs; i++) {
if (w[i] > 0.0) {
is = isou[i];
dr = 0.0;
dd = 0.0;
for (j=0; j<mcoef; j++) {
dr += coef[j]*ObitZernikeGradX(j+2, x[is], y[is]);
dd += coef[j]*ObitZernikeGradY(j+2, x[is], y[is]);
}
rx = dx[i] - dr;
ry = dy[i] - dd;
rms += rx*rx + ry*ry;
rmscnt++;
/* Diagnostics */
if (prtLv>=3) {
Obit_log_error(err, OBIT_InfoErr,
"%s: obs %5d o=%7.2f %7.2f m=%7.2f %7.2f r=%7.2f %7.2f w=%6.2f",
routine, i+1, dx[i]*3600.0, dy[i]*3600.0, dr*3600.0, dd*3600.0,
rx*3600.0, ry*3600.0, w[i]);
} /* End Diagnostics */
}
} /* end print loop */
rms = sqrt (rms/rmscnt);
Obit_log_error(err, OBIT_InfoErr,
"%s: RMS residual=%9.2f asec",routine, 3600.0*rms);
ObitErrLog(err); /* show any messages on err */
out = rms;
return out;
} /* end IonFit1 */
/**
* Make a parabolic least-squares fit to a 9x9 matrix about the
* peak value in an array and determine strength and position
* of maximum.
* 0.5*min(imsi[0],imsi[1]) pixels of the center.
* Routine translated from the AIPSish CALPOS.FOR/FXPFIT
* \param a Data input array[dec][RA]
* \param dx Position of max relative to a[5][5]
* \param s Strength of max
* \param fblank Value for blanked pixel
* \return 0=OK else failed
*/
static olong pfit (ofloat a[9][9], ofloat *s, ofloat dx[2], ofloat fblank)
{
float absmax, x, y, temp[6], momar[6], d;
float mat[3][3] = {{0.55555, -0.33333, -0.33333}, {-0.33333, 0.5, 0.0},
{-0.33333, 0.0, 0.5}};
int ix, iy, ixmax, iymax;
/* default return values */
dx[0] = 0;
dx[1] = 0;
*s = a[3][3];
/* find peak in array */
absmax = 0.0; ixmax = -1; iymax = -1;
for (ix=0; ix<9; ix++) {
for (iy=0; iy<9; iy++) {
if ((a[iy][ix]!=fblank) && (fabs(a[iy][ix])>absmax))
{absmax=fabs(a[iy][ix]); ixmax = ix; iymax = iy;}
}
}
/* check for valid data */
if ((ixmax<0) || (iymax<0)) return 1;
/* 00, 01, 02, 10, 11, 20 */
x = ixmax+1;
y = iymax+1;
/* default values */
dx[0] = x - 5.0;
dx[1] = y - 5.0;
*s = a[iymax][ixmax];
if (momnt (a, x, y, 3, 3, momar, fblank)) return 1;
/* multiply matrix * even moms yields const & quadratic terms */
temp[0] = momar[0];
temp[1] = momar[2];
temp[2] = momar[5];
matvmul (mat, temp, &temp[3], 3);
/* pick up linear & cross term */
temp[0] = momar[1] / 6.;
temp[1] = momar[3] / 6.;
temp[2] = momar[4] / 4.;
/* offset of peak */
d = 4.* temp[4] * temp[5] - (temp[2]*temp[2]);
if (d==0.0) return 2;
dx[0] = (temp[2]*temp[0] - 2.*temp[1]*temp[4]) / d;
dx[1] = (temp[2]*temp[1] - 2.*temp[0]*temp[5]) / d;
/* value of peak */
*s = temp[3] + dx[0]*(temp[1] + dx[0]*temp[5]
+ dx[1]*temp[2]) + dx[1]*(temp[0]+dx[1]*temp[4]);
dx[0] = dx[0] + x - 5.0; /* correct wrt center of input array */
dx[1] = dx[1] + y - 5.0;
return 0;
} /* end of pfit */
/**
* Calculate all 0th, 1st, and 2nd moments of a nx*ny subarray of ara
* centered at x,y. nx and ny should be odd.
* \param ara Input data array
* \param x x-center for moment calculation (1-rel)
* \param nx # of points to include in x-direction. nx
* should be odd.
* The points will be centered about x (rounded)
* \param ny # of points in y-direction
* \param momar 00,10,20,01,11,02 yx-moments of ara
* \param fblank Value for blanked pixel
* \return 0=OK else failed 1 => subarray doesn't fit in main array
*/
static olong
momnt (ofloat ara[9][9], ofloat x, ofloat y, olong nx, olong ny,
ofloat momar[6], ofloat fblank)
{
olong ind, i, j, k, nj, indx, indy, iax1, iax2, iay1, iay2;
ofloat s, t, arg, prod;
/* compute loop limits (1-rel) */
i = x + 0.5;
iax1 = i - nx/2;
iax2 = iax1 + nx - 1;
i = y + 0.5;
iay1 = i - ny/2;
iay2 = iay1+ ny - 1;
/* check loop limits */
if ((iax1<1) || (iax2>9) || (iay1<1) || (iay2>9)) return 1;
/* compute moments */
ind = 0;
for (i = 1; i<=3; i++) {
nj = 4 - i;
for (j=1; j<=nj; j++) {
ind = ind + 1;
s = 0.0;
for (indx=iax1; indx<=iax2; indx++) {
for (indy=iay1; indy<=iay2; indy++) {
t = ara[indy-1][indx-1];
if (t!=fblank) {
if (i>1) {
prod = 1.0;
arg = indx - x;
for (k=1; k<i; k++) prod *= arg;
t = t * prod;} /* ((indx - x)**(i-1)); */
if (j>1) {
prod = 1.0;
arg = indy - y;
for (k=1; k<j; k++) prod *= arg;
t = t * prod;} /* ((indy - y)**(j-1));*/
s = s + t;}
}
}
momar[ind-1] = s;
}
}
return 0;
} /* end of momnt */
/**
* Matrix-vector multiplication vo = vi * m
* \param m Input matrix
* \param vi Input vector
* \param n Array dimension
* \param vo [out] Output vector
*/
static void matvmul (ofloat m[3][3], ofloat vi[3], ofloat vo[3], olong n)
{
int i, j;
float s;
for (i=0; i<n; i++) {
s = 0.0;
for (j=0; j<n; j++) s = s + m[j][i] * vi[j];
vo[i] = s;
}
} /* end of matvmul */
/**
* Converts from celestial coordinates, expressed in terms of
* a reference position and a shift from this position to coordinates
* in a plane for fitting an Ionospheric phase screen model
* consisting of Zernike polynomials. The output coordinates are
* normalized to unity at a 10 deg radius from the reference position.
* The coordinates are projected onto a plane tangent to the sky at
* the reference position.
* Routine translated from the AIPSish ZERGEOM.FOR/RD2ZER
* \param ra Right Ascention of reference position (deg)
* \param dec Declination of reference position (deg)
* \param xshift Shift in X (RA) to desired position (deg)
* \param yshift Shift in Y (Dec) to desired position (deg)
* \param xzer [out] x-coordinate on Zernike plane
* \param yzer [out] y-coordinate on Zernike plane
* \param ierr 0 ok, 1 out of range
*/
static void rd2zer (odouble ra, odouble dec, ofloat xshift, ofloat yshift,
ofloat* xzer, ofloat* yzer, olong *ierr)
{
odouble dx, dy, a, b, ax, ay, xxinc, coss, sins, sint, dt;
odouble pi, twopi, zernor;
/* Constants */
pi = 3.14159265358979323846e0;
twopi = 2.0e0*pi;
/* Zernike normalization to Unit circle (10 deg) */
zernor = 1.0 / (10.0e0 * DG2RAD);
/* initial values */
*xzer = 0.0;
*yzer = 0.0;
*ierr = 0;
/* Convert to radians */
a = DG2RAD * ra;
b = DG2RAD * dec;
/* Convert shift to position */
xxinc = cos (DG2RAD * dec);
if (xxinc != 0) {
ax = ra + xshift / xxinc;
} else {
ax = ra;
}
ay = dec + yshift;
ax = ax * DG2RAD;
ay = ay * DG2RAD;
/* Get projection cosines */
*ierr = 1;
if (fabs(ay) > pi/2.0e0) return;
if (fabs(b) > pi/2.0e0) return;
*ierr = 0;
coss = cos (ay);
sins = sin (ay);
dt = ax - a;
if (dt > pi) dt = dt - twopi;
if (dt < -pi) dt = dt + twopi;
dx = sin (dt) * coss;
sint = sins * sin (b) + coss * cos (b) * cos (dt);
/* SIN projection */
/* IF (SINT.LT.0.0D0) IERR = 2 */
if (sint < 0.0e0) {
*ierr= 1;
return;
}
dy = sins * cos (b) - coss * sin (b) * cos (dt);
/* Normalize to Zernike unit sphere */
*xzer = dx * zernor;
*yzer = dy * zernor;
return;
} /* end of routine rd2zer */
/**
* Given an offset from a given field center, return the rotation of
* the coordinates of the offset wrt the field center.
* This is just the difference in RA.
* Routine translated from the AIPSish ZERGEOM.FOR/ZERROT
* \param ra Initial RA in degrees: ref point
* \param dec Initial Declination in degrees: ref point
* \param xshift Shift in "X" in degrees - simple shifts not -SIN
* \param yshift Shift in "Y" in degrees
* \param rotate [out] Image rotation in degrees
*/
static void zerrot (odouble ra, odouble dec, ofloat xshift, ofloat yshift,
ofloat* rotate)
{
odouble xxinc, xra, xdec;
/* simple shifts */
xdec = dec + yshift;
xxinc = cos (DG2RAD * dec);
if (xxinc != 0) {
xra = ra + xshift / xxinc;
} else {
xra = ra;
}
/* Difference in RA */
(*rotate) = (ra - xra);
/* Fold to range (-180,+180) */
if (*rotate > +180.0e0) (*rotate) -= 360.0e0;
if (*rotate < -180.0e0) (*rotate) += 360.0e0;
} /* end of routine zerrot */
/**
* Convert a timerange as time in days to a printable string
* \param timer Beginning time, end time in days
* \msgBuff Human readable string as "dd/hh:mm:ss.s-dd/hh:mm:ss.s"
* must be allocated at least 30 characters
*/
static void TR2String (ofloat timer[2], gchar *msgBuf)
{
ofloat rtemp, rt1, rt2;
olong id1, id2, it1, it2, it3, it4;
id1 = timer[0];
rtemp = 24.0 * (timer[0] - id1);
it1 = rtemp;
it1 = MIN (23, it1);
rtemp = (rtemp - it1)*60.0;
it2 = rtemp;
it2 = MIN (59, it2);
rt1 = (rtemp - it2)*60.0;
id2 = timer[1];
rtemp = 24.0 * (timer[1] - id2);
it3 = rtemp;
it3 = MIN (23, it3);
rtemp = (rtemp - it3)*60.0;
it4 = rtemp;
it4 = MIN (59, it4);
rt2 = (rtemp - it4)*60.0;
g_snprintf (msgBuf, 30, "%2.2d/%2.2d:%2.2d:%5.2f-%2.2d/%2.2d:%2.2d:%5.2f",
id1, it1, it2, rt1, id2, it3, it4, rt2);
} /* end of routine TR2String */
/* CalListElem functions */
/**
* CalListElem Constructor
* \param ra Catalog celestial position RA (deg)
* \param dec Catalog celestial position RA (deg)
* \param ZernXY Offset on Zernike plane (deg)
* \param shift Shift from reference position
* \param pixel Expected pixel in reference image
* \param flux Estimated catalog flux density
* \param offset Measured offset from expected position (pixels)
* \param peak Measured peak flux density (image units)
* \param fint Measured integrated flux density (image units)
* \param wt Determined weight
* \param qual Catalog quality code
* \param calNo Calibrator number
* \param epoch Epoch number
* \return the new object.
*/
static CalListElem*
newCalListElem (odouble ra, odouble dec, ofloat ZernXY[2], ofloat shift[2],
ofloat pixel[2], ofloat flux, ofloat offset[2],
ofloat peak, ofloat fint, ofloat wt, olong qual,
olong calNo, olong epoch)
{
CalListElem *out=NULL;
out = g_malloc0(sizeof(CalListElem));
out->ra = ra;
out->dec = dec;
out->ZernXY[0] = ZernXY[0];
out->ZernXY[1] = ZernXY[1];
out->shift[0] = shift[0];
out->shift[1] = shift[1];
out->pixel[0] = pixel[0];
out->pixel[1] = pixel[1];
out->flux = flux;
out->offset[0] = offset[0];
out->offset[1] = offset[1];
out->peak = peak;
out->fint = fint;
out->wt = wt;
out->qual = qual;
out->calNo = calNo;
out->epoch = epoch;
return out;
} /* end newCalListElem */
/**
* Update CalListElem
* \param elem CalListElem to update
* \param ra Catalog celestial position RA (deg)
* \param dec Catalog celestial position Dec (deg)
* \param ZernXY Offset on Zernike plane (deg)
* \param shift Shift from reference position
* \param pixel Expected pixel in reference image
* \param flux Estimated catalog flux density
* \param offset Measured offset from expected position (pixels)
* \param peak Measured peak flux density (image units)
* \param fint Measured integrated flux density (image units)
* \param wt Determined weight
* \param qual Catalog quality code
* \param calNo Calibrator number
* \param epoch Epoch number
* \return the new object.
*/
static void
CalListElemUpdate (CalListElem *elem, odouble ra, odouble dec,
ofloat ZernXY[2], ofloat shift[2], ofloat pixel[2],
ofloat flux, ofloat offset[2], ofloat peak, ofloat fint,
ofloat wt, olong qual, olong calNo, olong epoch)
{
elem->ra = ra;
elem->dec = dec;
elem->ZernXY[0] = ZernXY[0];
elem->ZernXY[1] = ZernXY[1];
elem->shift[0] = shift[0];
elem->shift[1] = shift[1];
elem->pixel[0] = pixel[0];
elem->pixel[1] = pixel[1];
elem->flux = flux;
elem->offset[0] = offset[0];
elem->offset[1] = offset[1];
elem->peak = peak;
elem->fint = fint;
elem->wt = wt;
elem->qual = qual;
elem->calNo = calNo;
elem->epoch = epoch;
} /* end CalListElemUpdate */
/**
* Print contents
* \param in Object to print
* \param file FILE* to write to
*/
static void CalListElemPrint (CalListElem *in, FILE *file)
{
if (!in) return;
fprintf (file, "Cal. no.=%d, epoch=%d\n",in->calNo, in->epoch);
fprintf (file, "RA=%lf, Dec=%lf\n",in->ra, in->dec);
fprintf (file, "Offset (deg) on Zernike plane [%f,%f]\n",
in->ZernXY[0],in->ZernXY[1]);
fprintf (file, "Position shift (deg) [%f,%f]\n",
in->shift[0],in->shift[1]);
fprintf (file, "Expected pixel [%f,%f]\n",
in->pixel[0],in->pixel[1]);
fprintf (file, "Expected flux density %f, quality %d\n",
in->flux,in->qual);
fprintf (file, "Measured position offset (asec) [%f,%f]\n",
in->offset[0]*3600.0,in->offset[1]*3600.0);
fprintf (file, "Measured peak %f, integ. %f, wt %f\n",
in->peak,in->fint, in->wt);
} /* end CalListElemPrint */
/**
* Destructor
* \param in Object to delete
*/
static void freeCalListElem (CalListElem *in)
{
if (in) g_free(in);
} /* end freeCalListElem */
/* CalList functions */
/**
* CalList Constructor
* \return the new CalList structure.
*/
static CalList* newCalList (void)
{
CalList *out=NULL;
out = g_malloc0(sizeof(CalList));
out->number = 0;
out->list = NULL;
return out;
} /* end newCalListElem */
/**
* Attach elem to list in
* \param in list to add elem to
* \param elem the element to add.
*/
static void CalListAdd (CalList *in, CalListElem *elem)
{
/* link to list */
in->list = g_slist_append (in->list, elem);
in->number++;
} /* end CalListAdd */
/**
* Remove elem from list in
* \param in list to remove elem from
* \param elem the element to remove.
*/
static void CalListRemove (CalList *in, CalListElem *elem)
{
/* remove from list */
in->list = g_slist_remove(in->list, elem);
in->number--; /* keep count */
} /* end CalListRemove */
/**
* Remove all elements from list in
* \param in list to remove elem from
* \param elem the element to remove.
*/
static void CalListClear (CalList *in)
{
GSList *tmp;
if (in==NULL) return; /* Does it exist? */
if (in->list==NULL) return; /* Anything in it? */
/* loop through list deleting elements */
tmp = in->list;
while (tmp!=NULL) {
if (tmp->data) freeCalListElem(tmp->data);
tmp = g_slist_next(tmp);
}
/* delete members */
g_slist_free(in->list);
in->list = NULL;
in->number = 0;
} /* end CalListClear */
/**
* Print all elements in list in to file
* \param in list to remove elem from
* \param elem the element to remove.
*/
static void CalListPrint (CalList *in, FILE *file)
{
GSList *tmp;
if (in==NULL) return; /* Does it exist? */
if (in->list==NULL) return; /* Anything in it? */
fprintf (file, "Listing Of CalList\n");
/* loop through list deleting elements */
tmp = in->list;
while (tmp!=NULL) {
if (tmp->data) CalListElemPrint(tmp->data, file);
tmp = g_slist_next(tmp);
}
} /* end CalListPrint */
/**
* Destructor
* \param in Object to delete
*/
static void freeCalList (CalList *in)
{
/* Clear List */
CalListClear(in);
/* delete object */
g_free(in);
} /* end freeCalListElem */
/**
* Fit Zernike polynomial to position offset pairs
* Use gsl package.
* \param nobs Number of data measurements
* \param isou Source number per obs. (0-rel)
* \param x Zernike X on unit circle per source
* \param y Zernike Y on unit circle per source
* \param dx X offset (deg)
* \param dy X offset (deg)
* \param wt Data weights
* \param nZern Number of Zernike coefficients to fit
* \param coef [out] Zernike coefficients
*/
void FitZernike (olong nobs, olong* isou, ofloat *x, ofloat *y,
ofloat *dx, ofloat *dy, ofloat *wt,
olong nZern, ofloat *coef)
{
#if HAVE_GSL==1 /* GSL stuff */
olong i, j, k, is, good, p=nZern, npen;
double xi, chisq, sumwt, penWt;
gsl_matrix *X, *cov;
gsl_vector *yy, *w, *c;
gsl_multifit_linear_workspace *work;
/* Penalty terms by order of Zernike 1-4 */
ofloat pen[]={0.001, 0.001,
0.01, 0.01, 0.01,
0.03, 0.03, 0.03, 0.03, 0.03,
0.05, 0.05, 0.05,0.05, 0.05, 0.05, 0.05,
0.08, 0.08, 0.08, 0.08, 0.08, 0.08, 0.08, 0.08};
/* Only use good data (2 per measurement) */
good = 0;sumwt = 0.0;
for (i=0; i<nobs; i++) if (wt[i]>0.0)
{good += 2; sumwt += wt[i];}
/* Number of penalty terms */
npen = nZern;
/* allocate arrays */
X = gsl_matrix_alloc(good+npen, p);
yy = gsl_vector_alloc(good+npen);
w = gsl_vector_alloc(good+npen);
c = gsl_vector_alloc(p);
cov = gsl_matrix_alloc(p, p);
work = gsl_multifit_linear_alloc (good+npen, p);
/* set data */
k = 0;
for (i=0; i<nobs; i++) {
if (wt[i]>0.0) {
is = isou[i];
/* X offset */
gsl_vector_set(yy, k, dx[i]);
gsl_vector_set(w, k, wt[i]);
for (j=0; j<p; j++) {
xi = ObitZernikeGradX(j+2, x[is], y[is]);
gsl_matrix_set(X, k, j, xi);
}
k++;
/* Y offset */
gsl_vector_set(yy, k, dy[i]);
gsl_vector_set(w, k, wt[i]);
for (j=0; j<p; j++) {
xi = ObitZernikeGradY(j+2, x[is], y[is]);
gsl_matrix_set(X, k, j, xi);
}
k++;
}
}
/* Penalty terms - try to get coefficients as small as possible */
penWt = sumwt / good; /* Penalty weight data dependency */
for (i=0; i<npen; i++) {
gsl_vector_set(yy, k, 0.0);
gsl_vector_set(w, k, penWt*pen[i]);
for (j=0; j<p; j++) {
if (j==i) xi = 1.0;
else xi = 0.0;
gsl_matrix_set(X, k, j, xi);
}
k++;
} /* end penalty loop */
/* Fit */
gsl_multifit_wlinear (X, w, yy, c, cov, &chisq, work);
/* get results */
for (j=0; j<nZern; j++) coef[j] = gsl_vector_get(c, j);
/* Deallocate arrays */
gsl_matrix_free(X);
gsl_vector_free(yy);
gsl_vector_free(w);
gsl_vector_free(c);
gsl_matrix_free(cov);
gsl_multifit_linear_free (work);
#else /* No GSL - stubb */
g_error ("FitZernike: GSL not available - cannot do fit");
#endif /* GSL stuff */
} /* end FitZernike */
/**
* Called when CLEAN failed to mark first 5 entries as failed.
* \param in IonCal object
* \param mosaic Image mosaic object
* \param calList Calibrator list each element of which has:
* \li ra position RA (deg) of calibrators
* \li dec position Dec (deg) of calibrators
* \li shift Offset in field [x,y] on unit Zernike circle of position
* \li pixel Expected pixel in reference image
* \li flux Estimated catalog flux density
* \li offset Measured offset [x,y] from expected position (deg)
* \li peak set to 0.0
* \li fint set to 0.0
* \li wt set to 0.0
* \li qual Catalog quality code
* \param err Error stack
* \param epoch Epoch number
*/
static void CalBadTime (ObitIonCal *in, ObitImageMosaic* mosaic,
olong epoch, ObitErr* err)
{
olong field;
ofloat offset[2], peak, fint, wt;
ObitImage *image=NULL;
CalListElem *elem=NULL, *nelem=NULL;
GSList *tmp;
CalList *calList;
/*gchar *routine = "CalBadTime";*/
/* Error checks */
g_assert(ObitErrIsA(err));
if (err->error) return ; /* previous error? */
g_assert(ObitIonCalIsA(in));
g_assert(ObitImageMosaicIsA(mosaic));
calList = (CalList*)in->calList;
/* do up to 5 fields Loop over images */
for (field=0; field<MIN (5, mosaic->numberImages); field++) {
image = mosaic->images[field];
/* Find cal info */
tmp = calList->list;
while (tmp!=NULL) { /* loop 100 */
elem = (CalListElem*)tmp->data;
if (elem->calNo == (field+1)) break; /* found it */
tmp = g_slist_next(tmp); /* next item in list */
} /* end loop L100: over calibrator list */
/* zero it out */
offset[0] = offset[1] = 0.0;
peak = 0.0;
fint = 0.0;
wt = 0.0;
/* Update CalList */
nelem = newCalListElem (elem->ra, elem->dec, elem->ZernXY, elem->shift,
elem->pixel, elem->flux, offset, peak, fint, wt,
elem->qual, field+1, epoch);
CalListAdd (calList, nelem);
} /* end loop over fields */
} /* end of routine CalBadTime */
| {
"alphanum_fraction": 0.6015357897,
"avg_line_length": 33.3246622303,
"ext": "c",
"hexsha": "2b570c85d8933d05b1985be7984d23a39a8ad929",
"lang": "C",
"max_forks_count": 8,
"max_forks_repo_forks_event_max_datetime": "2022-03-31T12:16:08.000Z",
"max_forks_repo_forks_event_min_datetime": "2017-08-29T15:12:32.000Z",
"max_forks_repo_head_hexsha": "e4ce6029e9beb2a8c0316ee81ea710b66b2b7986",
"max_forks_repo_licenses": [
"Linux-OpenIB"
],
"max_forks_repo_name": "sarrvesh/Obit",
"max_forks_repo_path": "ObitSystem/Obit/src/ObitIonCal.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "e4ce6029e9beb2a8c0316ee81ea710b66b2b7986",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"Linux-OpenIB"
],
"max_issues_repo_name": "sarrvesh/Obit",
"max_issues_repo_path": "ObitSystem/Obit/src/ObitIonCal.c",
"max_line_length": 99,
"max_stars_count": 5,
"max_stars_repo_head_hexsha": "e4ce6029e9beb2a8c0316ee81ea710b66b2b7986",
"max_stars_repo_licenses": [
"Linux-OpenIB"
],
"max_stars_repo_name": "sarrvesh/Obit",
"max_stars_repo_path": "ObitSystem/Obit/src/ObitIonCal.c",
"max_stars_repo_stars_event_max_datetime": "2020-10-20T01:08:59.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-08-26T06:53:08.000Z",
"num_tokens": 56505,
"size": 165257
} |
#include <mpi.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <gsl/gsl_math.h>
#include "allvars.h"
#include "proto.h"
/*! \file second_order.c
* \brief produce actual ICs from special 2nd order lpt ICs
*/
double F1_Omega(double a)
{
double omega_a;
omega_a = All.Omega0 / (All.Omega0 + a * (1 - All.Omega0 - All.OmegaLambda) + a * a * a * All.OmegaLambda);
return pow(omega_a, 5.0 / 9);
}
double F2_Omega(double a)
{
double omega_a;
omega_a = All.Omega0 / (All.Omega0 + a * (1 - All.Omega0 - All.OmegaLambda) + a * a * a * All.OmegaLambda);
return 2.0 * pow(omega_a, 6.0 / 11);
}
void second_order_ics(void)
{
int i, j;
double a, hubble, fac1, fac2, fac3;
double ax, ay, az;
if(ThisTask == 0)
{
printf("\nNow producing ICs based on 2nd-order LPT\n\n");
fflush(stdout);
}
a = All.TimeBegin;
hubble = hubble_function(a);
fac1 = 1.0 / (a * a * hubble * F1_Omega(a)); /* this factor converts the Zeldovich peculiar velocity
(expressed as a^2*dX/dt to comoving displacement */
fac2 = header.lpt_scalingfactor;
fac3 = fac2 * a * a * hubble * F2_Omega(a);
if(ThisTask == 0)
printf("fac1=%g fac2=%g fac3=%g\n", fac1, fac2, fac3);
for(i = 0; i < NumPart; i++)
{
for(j = 0; j < 3; j++)
P[i].Pos[j] += fac1 * P[i].Vel[j]; /* Zeldovich displacement */
#ifdef PMGRID
for(j = 0; j < 3; j++)
P[i].Pos[j] += fac2 * (P[i].GravPM[j] + P[i].g.GravAccel[j]); /* second order lpt displacement */
for(j = 0; j < 3; j++)
P[i].Vel[j] += fac3 * (P[i].GravPM[j] + P[i].g.GravAccel[j]); /* second order lpt velocity correction */
#else
for(j = 0; j < 3; j++)
P[i].Pos[j] += fac2 * (P[i].g.GravAccel[j]); /* second order lpt displacement */
for(j = 0; j < 3; j++)
P[i].Vel[j] += fac3 * (P[i].g.GravAccel[j]); /* second order lpt velocity correction */
#endif
}
/* now set the masses correctly */
for(i = 0; i < NumPart; i++)
{
P[i].Mass = P[i].OldAcc;
if(All.MassTable[P[i].Type] != 0)
P[i].Mass = All.MassTable[P[i].Type];
}
if(All.ComovingIntegrationOn)
if(All.PeriodicBoundariesOn == 1)
check_omega(); /* check again whether we have plausible mass density */
/* recompute long range force */
All.DoDynamicUpdate = 1;
domain_Decomposition(); /* redo domain decomposition because particles may have shifted */
CPU_Step[CPU_MISC] += measure_time();
#ifdef PMGRID
long_range_force();
#endif
CPU_Step[CPU_MESH] += measure_time();
gravity_tree();
for(i = 0; i < NumPart; i++)
{
#ifdef PMGRID
ax = (P[i].g.GravAccel[0] + P[i].GravPM[0]) / All.G;
ay = (P[i].g.GravAccel[1] + P[i].GravPM[1]) / All.G;
az = (P[i].g.GravAccel[2] + P[i].GravPM[2]) / All.G;
#else
ax = P[i].g.GravAccel[0] / All.G;
ay = P[i].g.GravAccel[1] / All.G;
az = P[i].g.GravAccel[2] / All.G;
#endif
P[i].OldAcc = sqrt(ax * ax + ay * ay + az * az);
}
if(All.TypeOfOpeningCriterion == 1)
{
All.ErrTolTheta = 0; /* This will switch to the relative opening criterion for the following force computations */
gravity_tree();
}
}
| {
"alphanum_fraction": 0.5883092395,
"avg_line_length": 23.9248120301,
"ext": "c",
"hexsha": "f98e0e56ba4c07c3763649b671d2d5e7742d5a98",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "5e82c2de9e6884795b4ee89f2b15ed5dde70388f",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "egpbos/egp",
"max_forks_repo_path": "testing/icgen/random_verschillende_resoluties_N-GenIC/gadget3_64/second_order.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "5e82c2de9e6884795b4ee89f2b15ed5dde70388f",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "egpbos/egp",
"max_issues_repo_path": "testing/icgen/random_verschillende_resoluties_N-GenIC/gadget3_64/second_order.c",
"max_line_length": 120,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "5e82c2de9e6884795b4ee89f2b15ed5dde70388f",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "egpbos/egp",
"max_stars_repo_path": "testing/icgen/random_verschillende_resoluties_N-GenIC/gadget3_64/second_order.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1099,
"size": 3182
} |
#include <stdio.h>
#include <stdlib.h>
#include <lapacke.h>
void inverse(double* A, lapack_int N)
{
lapack_int *IPIV = (lapack_int *) malloc(N * sizeof(lapack_int));
int INFO;
/*
DGETRF computes an LU factorization of a general M-by-N matrix A
using partial pivoting with row interchanges.
The factorization has the form
A = P * L * U
where P is a permutation matrix, L is lower triangular with unit
diagonal elements (lower trapezoidal if m > n), and U is upper
triangular (upper trapezoidal if m < n).
This is the right-looking Level 3 BLAS version of the algorithm.
lapack_int LAPACKE_dgetrf( int matrix_layout, lapack_int m, lapack_int n,
double* a, lapack_int lda, lapack_int* ipiv );
INFO is INTEGER
= 0: successful exit
< 0: if INFO = -i, the i-th argument had an illegal value
> 0: if INFO = i, U(i,i) is exactly zero. The factorization
has been completed, but the factor U is exactly
singular, and division by zero will occur if it is used
to solve a system of equations.
*/
INFO = LAPACKE_dgetrf(LAPACK_ROW_MAJOR,N,N,A,N,IPIV);
printf("%d ", INFO);
//DGETRI computes the inverse of a matrix using the LU factorization
//computed by DGETRF.
//This method inverts U and then computes inv(A) by solving the system
//inv(A)*L = inv(U) for inv(A).
//lapack_int LAPACKE_dgetri( int matrix_layout, lapack_int n, double* a,
// lapack_int lda, const lapack_int* ipiv );
INFO = LAPACKE_dgetri(LAPACK_ROW_MAJOR,N,A,N,IPIV);
printf("%d \n", INFO);
free(IPIV);
}
int main(){
double A [2*2] = {
1,2,
3,4
};
inverse(A, 2);
printf("%f %f\n", A[0], A[1]);
printf("%f %f\n", A[2], A[3]);
return 0;
}
| {
"alphanum_fraction": 0.5978090767,
"avg_line_length": 29.953125,
"ext": "c",
"hexsha": "a6b4fe7840a17cf8733700b933a8d3df72f7769b",
"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": "84a3b4446b825735618f541a7ce9adcf3753fe22",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "agnusfeec/lc",
"max_forks_repo_path": "main.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "84a3b4446b825735618f541a7ce9adcf3753fe22",
"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": "agnusfeec/lc",
"max_issues_repo_path": "main.c",
"max_line_length": 81,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "84a3b4446b825735618f541a7ce9adcf3753fe22",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "agnusfeec/lc",
"max_stars_repo_path": "main.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 541,
"size": 1917
} |
/* poly/zsolve_cubic.c
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000 Brian Gough
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
/* zsolve_cubic.c - finds the complex roots of x^3 + a x^2 + b x + c = 0 */
#include <config.h>
#include <math.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_complex.h>
#include <gsl/gsl_poly.h>
#define SWAP(a,b) do { double tmp = b ; b = a ; a = tmp ; } while(0)
int
gsl_poly_complex_solve_cubic (double a, double b, double c,
gsl_complex *z0, gsl_complex *z1,
gsl_complex *z2)
{
double q = (a * a - 3 * b);
double r = (2 * a * a * a - 9 * a * b + 27 * c);
double Q = q / 9;
double R = r / 54;
double Q3 = Q * Q * Q;
double R2 = R * R;
double CR2 = 729 * r * r;
double CQ3 = 2916 * q * q * q;
if (R == 0 && Q == 0)
{
GSL_REAL (*z0) = -a / 3;
GSL_IMAG (*z0) = 0;
GSL_REAL (*z1) = -a / 3;
GSL_IMAG (*z1) = 0;
GSL_REAL (*z2) = -a / 3;
GSL_IMAG (*z2) = 0;
return 3;
}
else if (CR2 == CQ3)
{
/* this test is actually R2 == Q3, written in a form suitable
for exact computation with integers */
/* Due to finite precision some double roots may be missed, and
will be considered to be a pair of complex roots z = x +/-
epsilon i close to the real axis. */
double sqrtQ = sqrt (Q);
if (R > 0)
{
GSL_REAL (*z0) = -2 * sqrtQ - a / 3;
GSL_IMAG (*z0) = 0;
GSL_REAL (*z1) = sqrtQ - a / 3;
GSL_IMAG (*z1) = 0;
GSL_REAL (*z2) = sqrtQ - a / 3;
GSL_IMAG (*z2) = 0;
}
else
{
GSL_REAL (*z0) = -sqrtQ - a / 3;
GSL_IMAG (*z0) = 0;
GSL_REAL (*z1) = -sqrtQ - a / 3;
GSL_IMAG (*z1) = 0;
GSL_REAL (*z2) = 2 * sqrtQ - a / 3;
GSL_IMAG (*z2) = 0;
}
return 3;
}
else if (CR2 < CQ3) /* equivalent to R2 < Q3 */
{
double sqrtQ = sqrt (Q);
double sqrtQ3 = sqrtQ * sqrtQ * sqrtQ;
double theta = acos (R / sqrtQ3);
double norm = -2 * sqrtQ;
double r0 = norm * cos (theta / 3) - a / 3;
double r1 = norm * cos ((theta + 2.0 * M_PI) / 3) - a / 3;
double r2 = norm * cos ((theta - 2.0 * M_PI) / 3) - a / 3;
/* Sort r0, r1, r2 into increasing order */
if (r0 > r1)
SWAP (r0, r1);
if (r1 > r2)
{
SWAP (r1, r2);
if (r0 > r1)
SWAP (r0, r1);
}
GSL_REAL (*z0) = r0;
GSL_IMAG (*z0) = 0;
GSL_REAL (*z1) = r1;
GSL_IMAG (*z1) = 0;
GSL_REAL (*z2) = r2;
GSL_IMAG (*z2) = 0;
return 3;
}
else
{
double sgnR = (R >= 0 ? 1 : -1);
double A = -sgnR * pow (fabs (R) + sqrt (R2 - Q3), 1.0 / 3.0);
double B = Q / A;
if (A + B < 0)
{
GSL_REAL (*z0) = A + B - a / 3;
GSL_IMAG (*z0) = 0;
GSL_REAL (*z1) = -0.5 * (A + B) - a / 3;
GSL_IMAG (*z1) = -(sqrt (3.0) / 2.0) * fabs(A - B);
GSL_REAL (*z2) = -0.5 * (A + B) - a / 3;
GSL_IMAG (*z2) = (sqrt (3.0) / 2.0) * fabs(A - B);
}
else
{
GSL_REAL (*z0) = -0.5 * (A + B) - a / 3;
GSL_IMAG (*z0) = -(sqrt (3.0) / 2.0) * fabs(A - B);
GSL_REAL (*z1) = -0.5 * (A + B) - a / 3;
GSL_IMAG (*z1) = (sqrt (3.0) / 2.0) * fabs(A - B);
GSL_REAL (*z2) = A + B - a / 3;
GSL_IMAG (*z2) = 0;
}
return 3;
}
}
| {
"alphanum_fraction": 0.5181150241,
"avg_line_length": 25.6298701299,
"ext": "c",
"hexsha": "4fcf2931a1aab06d12037733853eb47426818ad0",
"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/poly/zsolve_cubic.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/poly/zsolve_cubic.c",
"max_line_length": 75,
"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/poly/zsolve_cubic.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": 1489,
"size": 3947
} |
// Copyright 2019, Winfield Chen and Lloyd T. Elliott.
#ifndef __STATISTICS_H_
# define __STATISTICS_H_
#include <gsl/gsl_sf.h>
#include "matrix.h"
double tcdf1m(double t, double nu);
double log_tcdf1m(double t, double nu);
void regression(t_matrix g,
t_matrix y,
t_matrix yt,
t_matrix obs,
t_matrix denom,
t_matrix beta,
t_matrix se,
t_matrix tstat,
t_matrix pval,
t_matrix b1,
t_matrix w1,
t_matrix w2);
#endif
| {
"alphanum_fraction": 0.5144694534,
"avg_line_length": 25.9166666667,
"ext": "h",
"hexsha": "f749440310e9d52365110257aa753ff146b92b7d",
"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": "af915c89b89738159f331531aaceb610dc9e380c",
"max_forks_repo_licenses": [
"BSD-2-Clause"
],
"max_forks_repo_name": "wnfldchen/agent",
"max_forks_repo_path": "include/statistics.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "af915c89b89738159f331531aaceb610dc9e380c",
"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": "wnfldchen/agent",
"max_issues_repo_path": "include/statistics.h",
"max_line_length": 54,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "af915c89b89738159f331531aaceb610dc9e380c",
"max_stars_repo_licenses": [
"BSD-2-Clause"
],
"max_stars_repo_name": "wnfldchen/agent",
"max_stars_repo_path": "include/statistics.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 144,
"size": 622
} |
#pragma once
/*
* (C) Copyright 2020-2021 UCAR
*
* This software is licensed under the terms of the Apache Licence Version 2.0
* which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
*/
/*! \addtogroup ioda_cxx_variable
*
* @{
* \file FillPolicy.h
* \brief Default fill values for ioda files.
*/
#include <gsl/gsl-lite.hpp>
#include <memory>
#include <string>
#include "ioda/Variables/Fill.h"
#include "ioda/Exception.h"
#include "ioda/defs.h"
namespace ioda {
/// \brief This option describes the default fill values that will be used if the user does not
/// manually specify a fill value.
/// \ingroup ioda_cxx_variable
enum class FillValuePolicy {
HDF5, ///< Set all fill values to zero or null strings.
NETCDF4 ///< Use NetCDF4 default fill values. This is the default option for ioda files.
};
/// \brief Holds the different default fill values used in ioda files produced by different
/// backends.
/// \ingroup ioda_cxx_variable
/// \details This matters for netCDF4 vs HDF5-produced files. They have different default
/// fill values.
namespace FillValuePolicies {
template <class T>
T HDF5_default() {
return 0;
}
template <>
inline std::string HDF5_default<std::string>() {
return std::string();
}
/// \ingroup ioda_cxx_variable
/// \see netcdf.h, starting around line 62, for these values
/// netcdf uses "ints" and "shorts", but these are all defined as fixed-width types.
template <class T>
T netCDF4_default() {
return 0;
}
template <>
inline std::string netCDF4_default<std::string>() {
return std::string();
}
template <>
inline signed char netCDF4_default<signed char>() {
return static_cast<signed char>(-127);
}
template <>
inline char netCDF4_default<char>() {
return static_cast<char>(0);
}
template <>
inline int16_t netCDF4_default<int16_t>() {
return static_cast<int16_t>(-32767);
}
template <>
inline int32_t netCDF4_default<int32_t>() {
return -2147483647;
}
template <>
inline float netCDF4_default<float>() {
return 9.9692099683868690e+36f;
}
template <>
inline double netCDF4_default<double>() {
return 9.9692099683868690e+36;
}
template <>
inline unsigned char netCDF4_default<unsigned char>() {
return static_cast<unsigned char>(255);
}
template <>
inline uint16_t netCDF4_default<uint16_t>() {
return static_cast<unsigned short>(65535);
}
template <>
inline uint32_t netCDF4_default<uint32_t>() {
return 4294967295U;
}
template <>
inline int64_t netCDF4_default<int64_t>() {
return -9223372036854775806LL;
}
template <>
inline uint64_t netCDF4_default<uint64_t>() {
return 18446744073709551614ULL;
}
/// \brief Applies the fill value policy. This sets default fill values when fill values are not
/// already provided.
/// \ingroup ioda_cxx_variable
template <class T>
void applyFillValuePolicy(FillValuePolicy pol, detail::FillValueData_t& fvd) {
if (fvd.set_) return; // If already set, then do nothing.
if (pol == FillValuePolicy::HDF5)
detail::assignFillValue(fvd, HDF5_default<T>());
else if (pol == FillValuePolicy::NETCDF4)
detail::assignFillValue(fvd, netCDF4_default<T>());
else
throw Exception("Unsupported fill value policy.", ioda_Here());
}
} // namespace FillValuePolicies
} // namespace ioda
/// @}
| {
"alphanum_fraction": 0.7260989856,
"avg_line_length": 26.024,
"ext": "h",
"hexsha": "322fef2cc1eb48d40c67abd0bcc02510a57527aa",
"lang": "C",
"max_forks_count": 3,
"max_forks_repo_forks_event_max_datetime": "2021-11-14T09:19:25.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-06-09T16:12:02.000Z",
"max_forks_repo_head_hexsha": "5bd372e548eb61d5f7b56a0b3d4cf0ca05e49e75",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "Gibies/ioda",
"max_forks_repo_path": "src/engines/ioda/include/ioda/Variables/FillPolicy.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "5bd372e548eb61d5f7b56a0b3d4cf0ca05e49e75",
"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": "Gibies/ioda",
"max_issues_repo_path": "src/engines/ioda/include/ioda/Variables/FillPolicy.h",
"max_line_length": 96,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "5bd372e548eb61d5f7b56a0b3d4cf0ca05e49e75",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "Gibies/ioda",
"max_stars_repo_path": "src/engines/ioda/include/ioda/Variables/FillPolicy.h",
"max_stars_repo_stars_event_max_datetime": "2021-06-09T16:11:50.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-06-09T16:11:50.000Z",
"num_tokens": 863,
"size": 3253
} |
/**
* Subroutines to correct for the intra-pixel sensitivity
* variation in e.g. NICMOS pixels. There are routines
* to corect both, an extracted SPC's and a list
* of PET pixels.
*
*/
#include "fitsio.h"
#include <gsl/gsl_interp.h>
#include <gsl/gsl_roots.h>
#include <gsl/gsl_multifit_nlin.h>
#include "aXe_grism.h"
#include "aXe_utils.h"
#include "aXe_errors.h"
#include "spc_spc.h"
#include "spce_pathlength.h"
#include "fringe_conf.h"
#include "spc_wl_calib.h"
#include "trfit_utils.h"
#include "ipixcorr_utils.h"
#define MAX(x,y) (((x)>(y))?(x):(y))
#define MIN(x,y) (((x)<(y))?(x):(y))
/**
* Function: get_intpix_corr
* The function determines and returns a correction factor with
* values stored in an interpolator at a certain wavelength.
* To derive the result the dispersion solution is inverted,
* then the trace position for the wavelength is determined.
* The the fractional pixel value in y is computed and the
* corresponding correction factor is returned.
*
* Parameters:
* @param actbeam - beam to correct
* @param cdisp - the dispersion coefficients for the beam
* @param ipcorr - the correction values stored in an interpolator
* @param lambda - the wavelength to correct
*
* Returns:
* @return cfactor - the correction factor
*/
double
get_intpix_corr(beam *actbeam, gsl_vector *cdisp, interpolator *ipcorr,
float lambda)
{
double tlength;
double xvalue;
double yfract;
double cfactor=0.0;
// get the trace length for the dispersion
// solution and wavelength
tlength = get_tlength_from_dispersion(cdisp, lambda);
// compute the x-offset from the reference point
// for this trace length value
xvalue = get_xvalue_from_tlength(actbeam, tlength);
// compute the fractional y-value
yfract = get_yfract_for_xvalue(actbeam, xvalue);
// get the correction factor
cfactor = eval_interp(ipcorr, yfract);
fprintf(stdout, "xdiff: %e, yfrac: %e, factor: %e ", xvalue, yfract, cfactor);
//fprintf(stdout, "lambda: %f, tlength: %f, xval: %f, yval: %f, yfract: %f, cfactor: %f\n",
// lambda, tlength, actbeam->refpoint.x+xvalue, actbeam->refpoint.y+actbeam->spec_trace->func (xvalue, actbeam->spec_trace->data),yfract, cfactor);
// return the correction factor
return cfactor;
}
/**
* Function: get_yfract_for_xvalue
* The function computes the fractional y-value for a trace
* position in a beam. The trace position is given as the
* x-offset position with respect to the reference position
*
* Parameters:
* @param actbeam - beam to correct
* @param xvalue - the x-value
*
* Returns:
* @return yfract - the fractional y-value
*/
double
get_yfract_for_xvalue(const beam *actbeam, double xvalue)
{
double dy;
double yabs;
double yfract;
// compute the y-value relative to the reference point
dy = actbeam->spec_trace->func (xvalue, actbeam->spec_trace->data);
// compute the absolute y-value on the chip
yabs = actbeam->refpoint.y + dy;
// compute the fractional pixel of this y-value
yfract = yabs - floor(yabs);
// return the fractional y-value
return yfract;
}
/**
* Function: get_xvalue_from_tlength
* The function computes the x-offset position from the reference point
* for a given tracelength in a given beam.
* The solution is numerically derived and therefore
* does work for any reasonable tracefunction.
*
* Parameters:
* @param actbeam - the beam to compute the x-offset
* @param tlength - tracelength
*
* Returns:
* @return xdiff - the x-offset
*/
double
get_xvalue_from_tlength(beam *actbeam, double tlength)
{
int iter=0;
int status;
double xdiff=0.0;
d_point x_interv;
// define and initialize the solver
const gsl_root_fsolver_type *T = gsl_root_fsolver_brent;
gsl_root_fsolver *s = gsl_root_fsolver_alloc (T);
gsl_function F;
tlength_pars *tpars;
// derive the x-interval from the beam boundaries
x_interv = get_xinterv_from_beam(actbeam);
// fprintf(stdout, "xpos: %f, ypos: %f\n", x_interv.x, x_interv.y);
// allocate and fill the parameters
tpars = (tlength_pars *) malloc(sizeof(tlength_pars));
tpars->actbeam = actbeam;
tpars->tlength = tlength;
// fille the GSL-function
F.function = &zero_tlength;
F.params = tpars;
// set the boundaries for the solver
gsl_root_fsolver_set (s, &F, x_interv.x, x_interv.y);
// iterate to find the zeropoint
do
{
// increment the iteration counter
iter++;
// iterate on the solver
status = gsl_root_fsolver_iterate (s);
// get a new guess from the solver
xdiff = gsl_root_fsolver_root (s);
// derive and set new boundaries
x_interv.x = gsl_root_fsolver_x_lower (s);
x_interv.y = gsl_root_fsolver_x_upper (s);
// check the accuracy
status = gsl_root_test_interval (x_interv.x, x_interv.y,
0, 0.0001);
//--------------CAVEAT---------------------------------------
// until March 28th 08 the code, wriongly was:
//status = gsl_root_test_interval (x_interv.x, x_interv.x,
// 0, 0.0001);
// somehow this made no difference.....
//-----------------------------------------------------------
}
// check for the break condition
while (status == GSL_CONTINUE && iter < MAX_ITER);
// free the memory
free(tpars);
// free the memory
gsl_root_fsolver_free (s);
// return the result
return xdiff;
}
/**
* Function: zero_tlength
* Helper function for the 1D-root finding routine.
* Evaluates a functional value at the position given
* in the first parameter using the values given
* as second parameter.
*
* Parameters:
* @param x - the independent value
* @param params - ingredients to evaluate the function value
*
* Returns:
* @return tzero - the function value
*/
double
zero_tlength (double x, void *params)
{
double tzero;
// extract the components from the parameter-structure
beam *actbeam = ((tlength_pars *) params)->actbeam;
double tlength = ((tlength_pars *) params)->tlength;
// compute the function value
tzero = actbeam->spec_trace->path_len (x, actbeam->spec_trace->data) - tlength;
// return the function value
return tzero;
}
/**
* Function: get_xinterv_from_beam
* Determines the maximum and minimum extension of a given
* beam along the x-axis. For security the interval is extended
* at both ends by a fixed amount (quantified in the header-file).
*
* Parameters:
* @param actbeam - the beam
*
* Returns:
* @return x_interv - xmin, xmax covered by the beam
*/
d_point
get_xinterv_from_beam(const beam *actbeam)
{
d_point x_interv;
// compute the beam extension
// towards the negative x-axis
x_interv.x = (double)MIN(actbeam->corners[0].x,
MIN(actbeam->corners[1].x,
MIN(actbeam->corners[2].x,
actbeam->corners[3].x)))-actbeam->refpoint.x - INTERVEXT;
// compute the beam extension
// towards the positive x-axis
x_interv.y = (double)MAX(actbeam->corners[0].x,
MAX(actbeam->corners[1].x,
MAX(actbeam->corners[2].x,
actbeam->corners[3].x)))-actbeam->refpoint.x + INTERVEXT;
// return the interval
return x_interv;
}
/**
* Function: get_tlength_from_dispersion
* The function computes and returnes the trace length for
* a given diseprsion solution and wavelength. The tracelength
* value is returned. Currently only linear and quadratic
* dispersio solution are considered.
*
* Parameters:
* @param cdisp - the dispersion coefficient polynomial
* @param lambda - the wavelength
*
* Returns:
* @return tlength - the trace length
*/
double
get_tlength_from_dispersion(gsl_vector *cdisp, float lambda)
{
double tlength=0.0;
//double tlength_a=0.0;
double det;
// check whether the polynomial is linear
if (cdisp->size == 2)
{
// compute the tracelength for linear dispersion
tlength = (lambda-gsl_vector_get(cdisp, 0))/gsl_vector_get(cdisp, 1);
}
// check whether the polynomial is quadratic
else if (cdisp->size == 3)
{
// compute the determinante
det = gsl_vector_get(cdisp, 1) * gsl_vector_get(cdisp, 1)
- 4.0 * gsl_vector_get(cdisp, 0) * gsl_vector_get(cdisp, 2);
// gove error if det < 0.0
if (det < 0.0)
aXe_message (aXe_M_FATAL, __FILE__, __LINE__,
"get_tlength_from_dispersion: Can not determine the tracelength since det < 0.0!\n");
// compute the tracelength
tlength = (-gsl_vector_get(cdisp, 1)+sqrt(det))/(2.0*gsl_vector_get(cdisp, 2));
// tlength_a = (-gsl_vector_get(cdisp, 1)-sqrt(det))/(2.0*gsl_vector_get(cdisp, 2));
// fprintf(stdout, "plus: %f, minus: f\n", tlength, tlength_a);
}
else
{
aXe_message (aXe_M_FATAL, __FILE__, __LINE__,
"get_tlength_from_dispersion: The dispersion solution has %i coefficients and can not be inverted!\n", cdisp->size);
}
// return the tracelength
return tlength;
}
/**
* Function: condense_dispersion
* The function strips off leading zeroes in the high order terms
* of the dispersion solution derived from the configuration file.
* These usually become a problem in the inversion to derive the
* tracelength.
*
* Parameters:
* @param disp__input - the configuration file dispersion
*
* Returns:
* @return cdisp - the effective dispersion relation
*/
gsl_vector *
condense_dispersion(gsl_vector *disp_input)
{
int index;
int i;
gsl_vector *cdisp;
// get the size of the incomingg dispersion
// vector
index = disp_input->size;
// determine the true size by subtracting
// high order zeros
while (index > -1 && !gsl_vector_get(disp_input, index-1))
index--;
// allocate space for the new vector
cdisp = gsl_vector_alloc(index);
// tranasfer the relevant values
// from the old to the new vector
for (i=0; i < index; i++)
gsl_vector_set(cdisp, i, gsl_vector_get(disp_input, i));
// return the new dispersion vector
return cdisp;
}
/**
* Function: fitting_ipc_corr
*
* Parameters:
* @param actbeam - the beam to examine
* @param conf_file_path - the full pathname too the configuration file
* @param ipcorr - the interpolator with the correction factor
* @param SPC - the full spectrum to correct
* @param obs - the grism image
* @param data_matrix - background subtracted grism image
* @param ipc_file_path - file name for the phase data
*
* Returns:
* @return icorr - marker whether the correction was applied or not (1/0)
*/
int
fitting_ipc_corr(beam act_beam, char conf_file_path[], interpolator *ipcorr,
full_spectr *SPC, observation *obs, gsl_matrix *data_matrix,
char ipc_file_path[], beam *beam_ptr)
{
aperture_conf *conf;
d_point fit_qual;
int icorr = 0;
trace_func *tracefun = act_beam.spec_trace;
double *tracedata = (double *)(tracefun->data);
// load the configuration file
conf = get_aperture_descriptor(conf_file_path);
// determine the phase data and fix the phase
// by fitting a function to it
fit_qual = kappa_sigma_klipp_ipc(conf, obs, data_matrix, act_beam, ipc_file_path);
// report on the shift and the quality
fprintf(stdout, "shift-difference: %e, quality: %e\n", fit_qual.x, fit_qual.y);
// check whether the quality is good enough
if (fit_qual.y < MAXQUALITY)
{
// apply a correction to the
// reference point to achive the
// right corrections
act_beam.refpoint.y += fit_qual.x;
beam_ptr->refpoint.y += fit_qual.x;
beam_ptr->ignore = -100;
// report the new y-shift
fprintf(stdout, "new y-shift: %e\n", act_beam.refpoint.y - (double)(int)(act_beam.refpoint.y + tracedata[1]));
// apply the sensitivity correction to the spectrum
intpix_corr_beam(act_beam, conf_file_path, ipcorr, SPC);
// set the correction marker
icorr=1;
}
// free allocated memory
free_aperture_conf(conf);
// return the marker
return icorr;
}
/**
* Function: intpix_corr_beam
* The functio corrects a full spectrum for the intrapixel sensitivity
* variations.
* For every spectral element its fractional y-value is determined,
* and then the correction factor for this y-value is computed
* and applied to the appropriate elements of the spectral bin.
*
* Parameters:
* @param actbeam - the beam to examine
* @param conf_file_path - the full pathname too the configuration file
* @param ipcorr - the interpolator with the correction factor
* @param SPC - the full spectrum to correct
*
* Returns:
* @return -
*/
void
intpix_corr_beam(beam actbeam, char conf_file_path[], interpolator *ipcorr,
full_spectr *SPC)
{
int index=0;
int for_grism=1;
double cfactor;
double lambda;
gsl_vector *cdisp;
d_point pixel;
dispstruct *beam_disp;
aperture_conf *conf;
// load the configuration file
conf = get_aperture_descriptor(conf_file_path);
// check whether it is grism (for_grism=1)
// or prism (for_grism=0) data
// give an error if there is a prism solution
for_grism = check_for_grism (conf_file_path, actbeam.ID);
if (!for_grism)
aXe_message (aXe_M_FATAL, __FILE__, __LINE__,
"intpix_corr_beam: Only grism dispersion solution can be corrected.\n");
// get the wavelength dispersion relation at
// position "refpoint". conf->refx and conf->refy
// are used at this point to allow for a non (0,0) centered
// 2D field dependence.
pixel.x = actbeam.refpoint.x - conf->refx;
pixel.y = actbeam.refpoint.y - conf->refy;
// derive the dispersion at the object position
beam_disp = get_dispstruct_at_pos(conf_file_path, for_grism,
actbeam.ID, pixel);
// skipp high order zeroes in the dispersion solution
cdisp = condense_dispersion(beam_disp->pol);
for (index=0; index < SPC->nelems; index++)
{
lambda = SPC->fgr_spec->spec[index].lambda_mean;
if (!gsl_isnan (lambda) && lambda)
{
cfactor = get_intpix_corr(&actbeam, cdisp, ipcorr, lambda);
fprintf(stdout, "lambda: %e, factor: %e\n", lambda, cfactor);
/*
SPC->fgr_spec->spec[index].count = SPC->fgr_spec->spec[index].count / cfactor;
SPC->fgr_spec->spec[index].error = SPC->fgr_spec->spec[index].error / cfactor;
SPC->fgr_spec->spec[index].flux = SPC->fgr_spec->spec[index].flux / cfactor;
SPC->fgr_spec->spec[index].ferror = SPC->fgr_spec->spec[index].ferror / cfactor;
SPC->bck_spec->spec[index].count = SPC->bck_spec->spec[index].count / cfactor;
SPC->bck_spec->spec[index].error = SPC->bck_spec->spec[index].error / cfactor;
SPC->bck_spec->spec[index].flux = SPC->bck_spec->spec[index].flux / cfactor;
SPC->bck_spec->spec[index].ferror = SPC->bck_spec->spec[index].ferror / cfactor;
SPC->obj_spec->spec[index].count = SPC->obj_spec->spec[index].count / cfactor;
SPC->obj_spec->spec[index].error = SPC->obj_spec->spec[index].error / cfactor;
SPC->obj_spec->spec[index].flux = SPC->obj_spec->spec[index].flux / cfactor;
SPC->obj_spec->spec[index].ferror = SPC->obj_spec->spec[index].ferror / cfactor;
this is the wqrong version!!
SPC->fgr_spec->spec[index].count = SPC->fgr_spec->spec[index].count * cfactor;
SPC->fgr_spec->spec[index].error = SPC->fgr_spec->spec[index].error * cfactor;
SPC->fgr_spec->spec[index].flux = SPC->fgr_spec->spec[index].flux * cfactor;
SPC->fgr_spec->spec[index].ferror = SPC->fgr_spec->spec[index].ferror * cfactor;
SPC->bck_spec->spec[index].count = SPC->bck_spec->spec[index].count * cfactor;
SPC->bck_spec->spec[index].error = SPC->bck_spec->spec[index].error * cfactor;
SPC->bck_spec->spec[index].flux = SPC->bck_spec->spec[index].flux * cfactor;
SPC->bck_spec->spec[index].ferror = SPC->bck_spec->spec[index].ferror * cfactor;
SPC->obj_spec->spec[index].count = SPC->obj_spec->spec[index].count * cfactor;
SPC->obj_spec->spec[index].error = SPC->obj_spec->spec[index].error * cfactor;
SPC->obj_spec->spec[index].flux = SPC->obj_spec->spec[index].flux * cfactor;
SPC->obj_spec->spec[index].ferror = SPC->obj_spec->spec[index].ferror * cfactor;
*/
}
}
// free the configuration structure
free_aperture_conf(conf);
// free the dispersion struct
free_dispstruct(beam_disp);
// free the memory for the dispersion
gsl_vector_free(cdisp);
}
/**
* Function: get_ipc_lambdas
* The function computes the wavelengths for a list of x-offsets from the
* reference point of a certain beam. The wavelength values are
* returned as a gsl-vector.
*
* Parameters:
* @param actbeam - the beam
* @param conf_file_path - the full path to the aXe configuration file
* @param xvalues - the list of x-offsets
*
* Returns:
* @return lambdas - the list of wavelength values
*/
gsl_vector *
get_ipc_lambdas(const beam actbeam, char conf_file_path[], gsl_vector *xvalues)
{
aperture_conf *conf;
dispstruct *disp;
calib_function *wl_calib;
gsl_vector *lambdas;
d_point pixel;
int for_grism;
int i;
// load the configuration file
conf = get_aperture_descriptor(conf_file_path);
// check whether it is grism (for_grism=1)
// or prism (for_grism=0) data
for_grism = check_for_grism (conf_file_path, actbeam.ID);
// determine the referencee point position
pixel.x = actbeam.refpoint.x - conf->refx;
pixel.y = actbeam.refpoint.y - conf->refy;
// determine the dispersion at the reference point
disp = get_dispstruct_at_pos(conf_file_path, for_grism,
actbeam.ID,pixel);
// make a calibration structure from the dispersion
wl_calib = create_calib_from_gsl_vector(for_grism, disp->pol);
// convert the x-values to tracelength-values
abscissa_to_pathlength (actbeam.spec_trace, xvalues);
// allocate memory for the wavelengths
lambdas = gsl_vector_alloc(xvalues->size);
// go over all tracelength values
for (i=0; i < (int)xvalues->size; i++)
{
// determine and store the wavelength for each tracelength
gsl_vector_set(lambdas, i,
wl_calib->func(gsl_vector_get(xvalues, i), wl_calib->order,
wl_calib->coeffs));
}
// free the configuration structure
free_aperture_conf(conf);
// free the memory in the calibration structure
free_calib(wl_calib);
// free the dispersion structure
free_dispstruct(disp);
// return the wavelengths
return lambdas;
}
/**
* Function: get_ipc_cvalues
* The function computes the intra-pixel correction factors for a certain
* beam on a set of trace positions specified by their x-offset from
* the reference point.
* For every x-offset position the trace positon and its fractional y-pixel
* (in absolute coordinates) is evaluated. Then the correction factor is
* determined using the input interpolator.
*
* Parameters:
* @param actbeam - the beam to correct
* @param ipcorr - the correction values depending on fractional y-pixel
* @param xvalues - the list x-offsets from the reference point
*
* Returns:
* @return cvalues - the list of correction values
*/
gsl_vector *
get_ipc_cvalues(const beam actbeam, interpolator *ipcorr, gsl_vector *xvalues)
{
gsl_vector *cvalues;
double yfract=0.0;
int i;
// allocate memory
cvalues = gsl_vector_alloc(xvalues->size);
// go over all x-values
for (i=0; i < (int)xvalues->size; i++)
{
// determine the y-fraction for the x-value
yfract = get_yfract_for_xvalue(&actbeam, gsl_vector_get(xvalues, i));
// detyermine and store the correction factor in the array
gsl_vector_set(cvalues, i, eval_interp(ipcorr, yfract));
}
// return the array
return cvalues;
}
/**
* Function: get_ipc_xvalues
* The function computes a list of x-offsets from the reference
* point of a beam. the regularly space offsets span the range
* of x-values covered by the pixels of the beam.
*
* Parameters:
* @param actbeam - the beam to compute the x-offsets for
*
* Returns:
* @return xvalues - the list of x-offsets
*/
gsl_vector *
get_ipc_xvalues(const beam actbeam)
{
gsl_vector *xvalues;
d_point xrange;
int npoints;
int i;
// determine the x-range covered by the beam
xrange = get_xinterv_from_beam(&actbeam);
// determine the number of points within the x-range
npoints = (xrange.y - xrange.x) / XSTEPSIZE + 1;
// allocate and fill a proper vector
// with the x-values
xvalues = gsl_vector_alloc(npoints);
for (i=0; i < npoints; i++)
{
gsl_vector_set(xvalues, i, xrange.x + (double)i * XSTEPSIZE);
}
// return the vector with the x-values
return xvalues;
}
/**
* Function: get_ipclambda
* The function creates an interpolator for the intra-pixel correction
* as a function of wavelength based on this correction as function
* of fractional y-pixel and the full calibration information
* on a beam.
* The interpolator is created after stepping along the beam trace
* and combining the wavelength values with the correction values
* at the trace positions.
*
* Parameters:
* @param actbeam - the beam to find the correction values for
* @param conf_file_path - the full path to the aXe cofiguration file
* @param ipcorr - the correction values as function of y-fraction
*
* Returns:
* @return ipclambda - the correction values as function of wavelength
*/
interpolator *
get_ipclambda(beam actbeam, char conf_file_path[],
interpolator *ipcorr)
{
gsl_vector *xvalues;
gsl_vector *cvalues;
gsl_vector *lambdas;
double *cv;
double *lv;
interpolator *ipclambda;
int i=0;
int j=0;
// get the x values around the reference point
xvalues = get_ipc_xvalues(actbeam);
// get the correction factors for these x-values
cvalues = get_ipc_cvalues(actbeam, ipcorr, xvalues);
// get the wavelength at the correction factors
lambdas = get_ipc_lambdas(actbeam, conf_file_path, xvalues);
// allocate memory for the dependent values
cv = (double *) malloc(cvalues->size * sizeof(double));
if (!cv) {
aXe_message (aXe_M_ERROR, __FILE__, __LINE__,
"Memory allocation failed");
}
// allocate memory for the independent values
lv = (double *) malloc(cvalues->size * sizeof(double));
if (!lv) {
aXe_message (aXe_M_ERROR, __FILE__, __LINE__,
"Memory allocation failed");
}
if (gsl_vector_get(lambdas, lambdas->size-1) > gsl_vector_get(lambdas, 0))
{
// transfer the values from the
// gsl vectors to the c-vectors
for (i = 0; i < (int)cvalues->size; i++)
{
cv[i] = gsl_vector_get(cvalues, i);
lv[i] = gsl_vector_get(lambdas, i);
}
}
else
{
// transfer the values from the
// gsl vectors to the c-vectors
// invert the order from the
// gsl-vectors
j = cvalues->size - 1;
for (i = 0; i < (int)cvalues->size; i++)
{
cv[j] = gsl_vector_get(cvalues, i);
lv[j] = gsl_vector_get(lambdas, i);
j--;
}
}
// create the interpolator
ipclambda = create_interp(cvalues->size, FILTER_INTERP_TYPE, lv, cv);
// free the memory allocated to
// the vectors
gsl_vector_free(xvalues);
gsl_vector_free(cvalues);
gsl_vector_free(lambdas);
// return the interpolator
return ipclambda;
}
/**
* Function: apply_corr_pet
* The function applies an intra-pixel sensitivity correction to
* a list of PET pixels. The correction values are given depending
* on the wavelength of the pixel, and are applied to the PET pixels
* in place.
*
* Parameters:
* @param ipclambda - the ipc correction factor as function of wavelength
* @param PET - the list of PET pixels to correct
*
* Returns:
* -
*/
void
apply_corr_pet(interpolator *ipclambda, ap_pixel *PET)
{
int j = 0;
double cvalue=0.0;
// go along the PET pixels until you meet
// the last
while (PET[j].p_x != -1)
{
// get the correction factor
cvalue = eval_interp(ipclambda, PET[j].lambda);
// apply the corection factor
// to the counts and the error
PET[j].count = PET[j].count / cvalue;
PET[j].error = PET[j].error / cvalue;
// fprintf(stdout, "lambda: %f, correction: %f\n", PET[j].lambda, cvalue);
j++;
}
}
/**
* Function: intpix_corr_pet
* The function applies the intra-pixel sensitivity correction to
* a list of PET pixels. The values in the pixels are corrected in
* place using the correction function, gemoetrical parameters and
* dispersion relation in the various parameters.
*
* Parameters:
* @param actbeam - the beam to correct
* @param conf_file_path - full path to the axe configuration file
* @param ipcorr - the ipc correction function
* @param PET - the list of PET pixels to correct
*
* Returns:
* -
*/
void
intpix_corr_pet(beam actbeam, char conf_file_path[],
interpolator *ipcorr, ap_pixel *PET)
{
interpolator *ipclambda;
aperture_conf *conf;
int for_grism=0;
// load the configuration file
conf = get_aperture_descriptor(conf_file_path);
// check whether it is grism (for_grism=1)
// or prism (for_grism=0) data
// give an error if there is a prism solution
for_grism = check_for_grism (conf_file_path, actbeam.ID);
if (!for_grism)
aXe_message (aXe_M_FATAL, __FILE__, __LINE__,
"intpix_corr_beam: Only grism dispersion solution can be corrected.\n");
// determine the correction factor versus wavelength
ipclambda = get_ipclambda(actbeam, conf_file_path, ipcorr);
print_interp(ipclambda);
// apply the correction to the PET
apply_corr_pet(ipclambda, PET);
// free the configuration structure
free_aperture_conf(conf);
// free the memory in the interpolator
free_interp(ipclambda);
}
/**
* Function: is_pointlike
* The function evaluates all criteria to decide whether an object
* is pointlike or not. In the current implementation an object
* is considered pointlike if a special OAF is given and the
* the beam is NOT excluded OR if the spatial extension of the
* object is smaller than the maximal extension.
*
* Parameters:
* @param actbeam - the beam to examine
* @param spec_OAF - indicates a special OAF file
* @param max_ext - the maximal allowed extension
*
* Returns:
* @return point_like - pointer to the opened fits file
*/
int
is_pointlike(beam actbeam, int spec_OAF, double max_ext)
{
int point_like=0;
int OAF_crit=0;
int EXT_crit=0;
// check whether a special OAF is given
// and the beam should NOT be ignored
if (spec_OAF && !actbeam.ignore)
OAF_crit=1;
// check whether the maximal extension
// is given and the object extension
// is smaller;
// also check whether non-default values
// for the object width are set
if (actbeam.awidth > -1.0 && actbeam.bwidth > -1.0 && max_ext && actbeam.awidth < max_ext && actbeam.bwidth < max_ext)
EXT_crit=1;
// set to pointlike if at least
// one of the criteria is set
if (OAF_crit || EXT_crit)
point_like=1;
// return the result
return point_like;
}
/**
* Function: get_SPC_opened
* The function opens an existing SPC file and returns the pointer
* to it.
* As of now, the mode of opening it is automatically READWRITE.
* Later on a differentiation using the free parameter "mode"
* might be added to generalize the function.
*
* Parameters:
* @param SPCname - name of the SPC file
* @param mode - mode to open it (not yet used)
*
* Returns:
* @return SPC_ptr - pointer to the opened fits file
*
*/
fitsfile *
get_SPC_opened(char SPCname[], int mode)
{
fitsfile *SPC_ptr;
int f_status=0;
// Open the OPET file for reading/writing
fits_open_file (&SPC_ptr, SPCname, READWRITE, &f_status);
if (f_status)
{
ffrprt (stdout, f_status);
aXe_message (aXe_M_FATAL, __FILE__, __LINE__,
"aXe_INTPIXCORR: Could not open file: %s\n",
SPCname);
}
// return the pointer to the fits file
return SPC_ptr;
}
/**
* Function: get_ALL_from_next_in_SPC
* The function creates and fills a full spectrum structure with
* the content of a SPC table extension. This is only done when,
* according to the beam ID, this beam should be corrected.
* For extensions with higher order beams which are not corrected
* an emply structure is returned.
*
* Parameters:
* @param SPCn_ptr - pointer to the opened SPC file
* @param aperID - pointer to aperture identification number
* @param beamID - pointer to beam identification number
*
* Returns:
* @return SPC - the full spectrum structure
*/
full_spectr *
get_ALL_from_next_in_SPC(fitsfile *SPC_ptr, int *aperID, int *beamID)
{
int f_status=0, hdutype;
long tmp;
//long nrows=0;
char comment[FLEN_COMMENT];
full_spectr *SPC;
fits_movrel_hdu (SPC_ptr, 1, &hdutype, &f_status);
if (f_status)
{
*aperID = -1;
*beamID = -1;
SPC = NULL;
return SPC;
}
// read the beam ID number
fits_read_key_lng (SPC_ptr, "BEAMID", &tmp, comment, &f_status);
if (f_status)
{
ffrprt (stderr, f_status);
aXe_message (aXe_M_FATAL, __FILE__, __LINE__,
"get_ALL_from_next_in_SPC: Error getting index keyword OBJECTID");
}
*beamID = (int)tmp;
// check whether this beam should be correct
if (*beamID > CORRMAX)
{
// set it to NULL and return
SPC = NULL;
// fprintf (stdout, "aXe_PETFF: Skipping beam: %c.\n", BEAM(*beamID));
return SPC;
}
// the beam shall be corrected and
// first must be read in
SPC = (full_spectr *) malloc (sizeof (full_spectr ));
// transfer the beam ID
SPC->beamID = (int)tmp;
// read the aperture number
fits_read_key_lng (SPC_ptr, "OBJECTID", &tmp, comment, &f_status);
if (f_status)
{
ffrprt (stderr, f_status);
aXe_message (aXe_M_FATAL, __FILE__, __LINE__,
"get_ALL_from_next_in_SPC: Error getting index keyword OBJECTID");
}
// transfer the aperture ID
*aperID = (int)tmp;
SPC->aperID = (int)tmp;
// Get the number of rows
fits_get_num_rows (SPC_ptr, &tmp, &f_status);
if (f_status) {
ffrprt (stderr, f_status);
aXe_message (aXe_M_FATAL, __FILE__, __LINE__,
"get_ALL_from_next_in_SPC: "
"Could not determine the number of rows in"
" correction function table!");
}
SPC->nelems = (int)tmp;
// load the background subtracted object spectrum
SPC->obj_spec = get_spectrum_from_SPC(SPC_ptr, "COUNT", "ERROR", SPC->nelems);
// load the total object spectrum
SPC->fgr_spec = get_spectrum_from_SPC(SPC_ptr, "TCOUNT", "TERROR", SPC->nelems);
// load the background spectrum
SPC->bck_spec = get_spectrum_from_SPC(SPC_ptr, "BCOUNT", "BERROR", SPC->nelems);
// return the filled structure
return SPC;
}
/**
* Function: free_full_spectr
* The function frees the memory allocated in a full
* spectrum structure.
*
* Parameters:
* @param SPC - the full spectrum structure
*
* Returns:
* @return -
*/
void
free_full_spectr(full_spectr *SPC)
{
// free the three spectra in the
// full spectrum structure
free_spectrum(SPC->obj_spec);
free_spectrum(SPC->fgr_spec);
free_spectrum(SPC->bck_spec);
// free the full spectrum
free(SPC);
// set the structure to NULL
SPC = NULL;
}
/**
* Function: get_spectrum_from_SPC
* The function fills a spectrum structure with data in an SPC extension.
* There is more data in an SPC extension than can be stored in a
* spectrum structure. Two parameters in this function specify partly which
* data should be loaded.
*
* Parameters:
* @param SPC_ptr - pointer to the SPC extension
* @param count_col - column to load for 'count'
* @param error_col - column to load for 'error'
* @param nelems - the number ol elements in the spectrum
*
* Returns:
* @return act_spec - the filled spectrum structure
*/
spectrum *
get_spectrum_from_SPC(fitsfile *SPC_ptr, char count_col[],
char error_col[], int nelems)
{
int index=0;
spectrum *act_spec;
double *count;
double *lambda;
double *error;
double *flux;
double *ferror;
double *weight;
double *contam;
long *dq;
// allocate the spectrum
act_spec = allocate_spectrum (nelems);
// transfer the column entries into a vector
lambda = get_dcolumn_from_SPC_opened(SPC_ptr, "LAMBDA", nelems);
count = get_dcolumn_from_SPC_opened(SPC_ptr, count_col, nelems);
error = get_dcolumn_from_SPC_opened(SPC_ptr, error_col, nelems);
flux = get_dcolumn_from_SPC_opened(SPC_ptr, "FLUX", nelems);
ferror = get_dcolumn_from_SPC_opened(SPC_ptr, "FERROR", nelems);
weight = get_dcolumn_from_SPC_opened(SPC_ptr, "WEIGHT", nelems);
contam = get_dcolumn_from_SPC_opened(SPC_ptr, "CONTAM", nelems);
dq = get_lcolumn_from_SPC_opened(SPC_ptr, "DQ", nelems);
// transfer the data from the vector into the
// spectrum structure
for (index = 0; index < nelems; index++)
{
act_spec->spec[index].lambda_mean = lambda[index];
act_spec->spec[index].count = count[index];
act_spec->spec[index].error = error[index];
act_spec->spec[index].flux = flux[index];
act_spec->spec[index].ferror = ferror[index];
act_spec->spec[index].weight = weight[index];
act_spec->spec[index].contam = contam[index];
act_spec->spec[index].dq = dq[index];
}
// free the arrays
free(lambda);
free(count);
free(error);
free(flux);
free(ferror);
free(weight);
free(contam);
free(dq);
// return the spectrum
return act_spec;
}
/**
* Function: get_dcolumn_from_SPC_opened
* The function reads the values from a double column specified
* by its name into a array of doubles. The array is returned.
*
* Parameters:
* @param SPC_ptr - pointer to the SPC extension
* @param count_col - name of the column to load
* @param nelems - number of elements in the column
*
* Returns:
* @return values - pointer to a filled array
*/
double *
get_dcolumn_from_SPC_opened(fitsfile *SPC_ptr, char colname[], int nelems)
{
int colnum=0;
int anynul;
int f_status=0;
double *values;
// allocate the return array;
// give an error if allocation fails
values = (double *) malloc(nelems * sizeof(double));
if (!values) {
aXe_message (aXe_M_ERROR, __FILE__, __LINE__,
"Memory allocation failed");
}
// get the desired column number;
// give an error if the column name
// can not be read
fits_get_colnum (SPC_ptr, CASEINSEN, colname, &colnum, &f_status);
if (f_status)
{
ffrprt (stderr, f_status);
aXe_message (aXe_M_FATAL, __FILE__, __LINE__,
"get_dcolumn_from_SPC_opened: "
"Could not determine column %s in "
" table!\n", colname);
}
// read all data in the column
fits_read_col (SPC_ptr, TDOUBLE, colnum, 1, 1, nelems, NULL, values,
&anynul, &f_status);
if (f_status)
{
ffrprt (stderr, f_status);
aXe_message (aXe_M_FATAL, __FILE__, __LINE__,
"get_dcolumn_from_SPC_opened: "
"Could not read column %s"
" from BINARY table!",colname);
}
// return the filled vector
return values;
}
/**
* Function: get_lcolumn_from_SPC_opened
* The function reads the values from a column with long specified
* by its name into a array of type long. The array is returned.
*
* Parameters:
* @param SPC_ptr - pointer to the SPC extension
* @param count_col - name of the column to load
* @param nelems - number of elements in the column
*
* Returns:
* @return values - pointer to a filled array
*/
long *
get_lcolumn_from_SPC_opened(fitsfile *SPC_ptr, char colname[], int nelems)
{
int colnum=0;
int anynul;
int f_status=0;
long *values;
// allocate the return array;
// give an error if allocation fails
values = (long *) malloc(nelems * sizeof(long));
if (!values) {
aXe_message (aXe_M_ERROR, __FILE__, __LINE__,
"Memory allocation failed");
}
// get the desired column number;
// give an error if the column name
// can not be read
fits_get_colnum (SPC_ptr, CASEINSEN, colname, &colnum, &f_status);
if (f_status)
{
ffrprt (stderr, f_status);
aXe_message (aXe_M_FATAL, __FILE__, __LINE__,
"get_dcolumn_from_SPC_opened: "
"Could not determine column %s in "
" table!\n", colname);
}
// read all data in the column
fits_read_col (SPC_ptr, TLONG, colnum, 1, 1, nelems, NULL, values,
&anynul, &f_status);
if (f_status)
{
ffrprt (stderr, f_status);
aXe_message (aXe_M_FATAL, __FILE__, __LINE__,
"get_dcolumn_from_SPC_opened: "
"Could not read column %s"
" from BINARY table!",colname);
}
// return the filled array
return values;
}
/**
* Function: create_nlincor
* The function creates an interpolator for the nonlinearity
* correction applied to NICMOS data.
*
* Parameters:
*
* Returns:
* @return nlincorr - the interpolator created
*/
interpolator *
create_nlincor()
{
interpolator *nlincorr;
/*
double x[14] = {8250.0, 8750.0, 9250.0, 9750.0, 11000.0, 12000.0, 13000.0, 14000.0, 15000.0, 16000.0, 17000.0, 18000.0, 19000.0, 20000.0};
double y[14] = { .069, .057, .052, .050, .049, .048, .041, .023, .013, .008, .004, .0, .0, .0};
*/
double *xx;
double *yy;
xx = (double *) malloc(14 * sizeof(double));
yy = (double *) malloc(14 * sizeof(double));
xx[0] = 8250.0;
xx[1] = 8750.0;
xx[2] = 9250.0;
xx[3] = 9750.0;
xx[4] = 11000.0;
xx[5] = 12000.0;
xx[6] = 13000.0;
xx[7] = 14000.0;
xx[8] = 15000.0;
xx[9] = 16000.0;
xx[10] = 17000.0;
xx[11] = 18000.0;
xx[12] = 19000.0;
xx[13] = 20000.0;
yy[0] = .069;
yy[1] = .057;
yy[2] = .052;
yy[3] = .050;
yy[4] = .049;
yy[5] = .048;
yy[6] = .041;
yy[7] = .023;
yy[8] = .013;
yy[9] = .008;
yy[10] = .004;
yy[11] = .0;
yy[12] = .0;
yy[13] = .0;
// create the interpolator
nlincorr = create_interp(14, NLINCORR_INTERP_TYPE, xx, yy);
// return the interpolator
return nlincorr;
}
/**
* Function: nlin_corr_beam
*
* Parameters:
* @param nlincorr - the interpolator with the correction factor
* @param SPC - the full spectrum to correct
*
* Returns:
* @return -
*/
void
nlin_corr_beam(interpolator *nlincorr, double adcgain, full_spectr *SPC)
{
int index=0;
// int for_grism=1;
double cfactor;
double cps;
double lambda;
for (index=0; index < SPC->nelems; index++)
{
// get the independent spectral values,
// the wavelenth and the cps value
lambda = SPC->obj_spec->spec[index].lambda_mean;
cps = SPC->obj_spec->spec[index].count;
// check whether the spectral element
// is not corrupt
if (!gsl_isnan (lambda) && lambda)
{
if (cps > 0.0)
// compute the correction factor
cfactor = get_nlin_corr(nlincorr, lambda, cps/adcgain);
else
// make a dummy factor
cfactor = 1.0;
// correct what should be corrected
SPC->fgr_spec->spec[index].count = SPC->fgr_spec->spec[index].count / cfactor;
SPC->fgr_spec->spec[index].error = SPC->fgr_spec->spec[index].error / cfactor;
SPC->fgr_spec->spec[index].flux = SPC->fgr_spec->spec[index].flux / cfactor;
SPC->fgr_spec->spec[index].ferror = SPC->fgr_spec->spec[index].ferror / cfactor;
SPC->bck_spec->spec[index].count = SPC->bck_spec->spec[index].count / cfactor;
SPC->bck_spec->spec[index].error = SPC->bck_spec->spec[index].error / cfactor;
SPC->bck_spec->spec[index].flux = SPC->bck_spec->spec[index].flux / cfactor;
SPC->bck_spec->spec[index].ferror = SPC->bck_spec->spec[index].ferror / cfactor;
SPC->obj_spec->spec[index].count = SPC->obj_spec->spec[index].count / cfactor;
SPC->obj_spec->spec[index].error = SPC->obj_spec->spec[index].error / cfactor;
SPC->obj_spec->spec[index].flux = SPC->obj_spec->spec[index].flux / cfactor;
SPC->obj_spec->spec[index].ferror = SPC->obj_spec->spec[index].ferror / cfactor;
}
}
}
/*
* Function: get_nlin_corr
*
* Parameters:
* @param nlincorr - the interpolator with the parameter
* @param lamda - the full spectrum to correct
* @param cps - the count rate
*
* Returns:
* @return cfactor - the correction factor
*/
double
get_nlin_corr(interpolator *nlincorr, const double lambda, const double cps)
{
double cfactor;
double bbb;
// evaluate the parameter
bbb = eval_interp(nlincorr, lambda);
// compute the correction factor
cfactor = 1.0 - 2.0 * bbb + bbb * log10(cps);
// return the correction factor
return cfactor;
}
| {
"alphanum_fraction": 0.6769606152,
"avg_line_length": 28.0983379501,
"ext": "c",
"hexsha": "d6445280e6b6d347db19d066df931d60a38251a8",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "sosey/pyaxe",
"max_forks_repo_path": "cextern/src/ipixcorr_utils.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "sosey/pyaxe",
"max_issues_repo_path": "cextern/src/ipixcorr_utils.c",
"max_line_length": 152,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "sosey/pyaxe",
"max_stars_repo_path": "cextern/src/ipixcorr_utils.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 11597,
"size": 40574
} |
/**
*
* RV-GOMEA
*
* If you use this software for any purpose, please cite the most recent publication:
* A. Bouter, C. Witteveen, T. Alderliesten, P.A.N. Bosman. 2017.
* Exploiting Linkage Information in Real-Valued Optimization with the Real-Valued
* Gene-pool Optimal Mixing Evolutionary Algorithm. In Proceedings of the Genetic
* and Evolutionary Computation Conference (GECCO 2017).
* DOI: 10.1145/3071178.3071272
*
* Copyright (c) 1998-2017 Peter A.N. Bosman
*
* The software in this file is the proprietary information of
* Peter A.N. Bosman.
*
* IN NO EVENT WILL THE AUTHOR OF THIS SOFTWARE BE LIABLE TO YOU FOR ANY
* DAMAGES, INCLUDING BUT NOT LIMITED TO LOST PROFITS, LOST SAVINGS, OR OTHER
* INCIDENTIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR THE INABILITY
* TO USE SUCH PROGRAM, EVEN IF THE AUTHOR HAS BEEN ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGES, OR FOR ANY CLAIM BY ANY OTHER PARTY. THE AUTHOR MAKES NO
* REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF THE SOFTWARE, EITHER
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT. THE
* AUTHOR SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY ANYONE AS A RESULT OF
* USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES.
*
* The software in this file is the result of (ongoing) scientific research.
* The following people have been actively involved in this research over
* the years:
* - Peter A.N. Bosman
* - Dirk Thierens
* - Jörn Grahl
* - Anton Bouter
*
*/
#pragma once
#include <stdio.h>
#include <iostream>
#include <stdlib.h>
#include <math.h>
#include <time.h>
#include <sys/time.h>
#include <eigen3/Eigen/Dense>
#include <cblas.h>
#include <lapack.h>
using Eigen::MatrixXd;
#define PI 3.14159265358979323846264338327950288419716939937510582097494459230781640628620899862803482534211706798
#define FALSE 0
#define TRUE 1
namespace GOMEA
{
void *
Malloc(long size);
void
shrunkCovariance(MatrixXd & emp_cov, const double alpha);
void
shrunkCovarianceOAS(MatrixXd & emp_cov, const int pop_size);
float
choleskyDecomposition(MatrixXd & result, MatrixXd & matrix, int n);
void
lowerTriangularMatrixInverse(MatrixXd & A, const int n);
int *
mergeSort(double * array, int array_size);
void
mergeSortWithinBounds(double * array, int * sorted, int * tosort, int p, int q);
void
mergeSortWithinBoundsInt(int * array, int * sorted, int * tosort, int p, int q);
void
mergeSortMerge(double * array, int * sorted, int * tosort, int p, int r, int q);
int *
mergeSortInt(int * array, int array_size);
void
mergeSortMergeInt(int * array, int * sorted, int * tosort, int p, int r, int q);
int *
getRanks(double * array, int array_size);
int *
getRanksFromSorted(int * sorted, int array_size);
double
randomRealUniform01(void);
int
randomInt(int maximum);
double
random1DNormalUnit(void);
double
random1DNormalParameterized(double mean, double variance);
void
initializeRandomNumberGenerator(void);
int *
randomPermutation(int n);
int **
allPermutations(int length, int * numberOfPermutations);
int **
allPermutationsSubroutine(int from, int length, int * numberOfPermutations);
double
max(double x, double y);
double
min(double x, double y);
double
distanceEuclidean(double * solution_a, double * solution_b, int n);
double
distanceEuclidean2D(double x1, double y1, double x2, double y2);
double *
matrixVectorPartialMultiplication(double ** matrix,
double * vector,
int n0,
int number_of_elements,
int * element_indices);
extern int64_t random_seed, /* The seed used for the random-number generator. */
random_seed_changing; /* Internally used variable for randomly setting a random seed. */
extern double haveNextNextGaussian, /* Internally used variable for sampling the normal distribution. */
nextNextGaussian;
}
| {
"alphanum_fraction": 0.733482922,
"avg_line_length": 32.088,
"ext": "h",
"hexsha": "99031d848cddb355fec72a2374376daeb3385a26",
"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": "c765ca8959fc288c19b0c7f75875b70f939581de",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "joasiee/elastix",
"max_forks_repo_path": "Components/Optimizers/RVGOMEA/util/Tools.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "c765ca8959fc288c19b0c7f75875b70f939581de",
"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": "joasiee/elastix",
"max_issues_repo_path": "Components/Optimizers/RVGOMEA/util/Tools.h",
"max_line_length": 114,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "c765ca8959fc288c19b0c7f75875b70f939581de",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "joasiee/elastix",
"max_stars_repo_path": "Components/Optimizers/RVGOMEA/util/Tools.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1011,
"size": 4011
} |
/*
Written by John MacCallum, The Center for New Music and Audio Technologies,
University of California, Berkeley. Copyright (c) 2006-09, The Regents of
the University of California (Regents).
Permission to use, copy, modify, distribute, and distribute modified versions
of this software and its documentation without fee and without a signed
licensing agreement, is hereby granted, provided that the above copyright
notice, this paragraph and the following two paragraphs appear in all copies,
modifications, and distributions.
IN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,
SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS, ARISING
OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF REGENTS HAS
BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE SOFTWARE AND ACCOMPANYING DOCUMENTATION, IF ANY, PROVIDED
HEREUNDER IS PROVIDED "AS IS". REGENTS HAS NO OBLIGATION TO PROVIDE
MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
NAME: randdist
DESCRIPTION: Random number generator with over 30 statistical distributions.
AUTHORS: John MacCallum
COPYRIGHT_YEARS: 2006-09
DRUPAL_NODE: /patch/4023
SVN_REVISION: $LastChangedRevision: 587 $
VERSION 1.1: Changed the way the random seed it made
VERSION 1.2: Universal binary
VERSION 1.2.1: Changed the license to be GPL compatible
VERSION 1.3: The object now takes arguments to specify the distribution
VERSION 1.3.1: Use of the buffering system is now optional and off by default
VERSION 1.3.2: Fixed a bug that would cause a crash if randdist was instantiated with a number instead of a symbol as its first arg.
VERSION 1.3.3: Added Gaussdist faker to helpfile, bump version to re-release. -mzed
VERSION 1.4: Default state, changed dump to distlist, user-defined pmfs are now done with the nonparametric message, bugfixes.
VERSION 2.0: Rewritten with common code between randdist and randdist~ put in libranddist.h/c
VERSION 2.1: Re-re-factored. Nonparametric now uses gsl_ran_discrete().
VERSION 2.1.1: Fixed a bug that occurred when distlist was used with nonparametric
VERSION 2.1.2: Fixed a bug with the multinomial distribution
VERSION 2.1.3: Added multivariate hypergeometric distribution
VERSION 2.1.4: fixed a bug with the way that multinomial arguments were being handled
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
*/
#include "ext.h"
#include "ext_obex.h"
#include "ext_obex_util.h"
#include "libranddist.h"
#include "version.h"
#include "version.c"
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
#define RDIST_DEFAULT_BUF_SIZE 1024
typedef struct _rdist{
t_object r_ob;
void *r_out0;
void *r_out1;
gsl_rng *r_rng; // random number generator
gsl_ran_discrete_t *r_g; // lookup table for nonparametric pdf sampling
t_atom r_vars[R_MAX_N_VARS];
t_symbol *r_dist;
t_atom *r_arIn;
short r_pmfLength;
int r_numVars;
int r_stride;
void (*r_function)(gsl_rng*, int, void*, int, float*);
t_atom *r_output_buffer;
} t_rdist;
void *rdist_class;
void rdist_anything(t_rdist *x, t_symbol *msg, short argc, t_atom *argv);
void rdist_bang(t_rdist *x);
void rdist_distlist(t_rdist *x, long n);
void rdist_assist(t_rdist *x, void *b, long m, long a, char *s);
void *rdist_new(t_symbol *msg, short argc, t_atom *argv);
void rdist_anything(t_rdist *x, t_symbol *msg, short argc, t_atom *argv);
void rdist_list(t_rdist *x, t_symbol *msg, short argc, t_atom *argv);
void rdist_nonparametric(t_rdist *x, t_symbol *msg, short argc, t_atom *argv);
void rdist_int(t_rdist *x, long n);
void rdist_float(t_rdist *x, double n);
void rdist_seed(t_rdist *x, long s);
void rdist_free(t_rdist *x);
void rdist_tellmeeverything(t_rdist *x);
void rdist_errorHandler(const char * reason, const char * file, int line, int gsl_errno);
int main(void){
setup((t_messlist **)&rdist_class, (method)rdist_new, (method)rdist_free, (short)sizeof(t_rdist), 0L, A_GIMME, 0);
addmess((method)version, "version", 0);
addmess((method)rdist_assist, "assist", A_CANT, 0);
addbang((method)rdist_bang);
addmess((method)rdist_distlist, "distlist", A_DEFLONG, 0);
addint((method)rdist_int);
addfloat((method)rdist_float);
addmess((method)rdist_list, "list", A_GIMME, 0);
addmess((method)rdist_anything, "anything", A_GIMME, 0);
addmess((method)rdist_nonparametric, "nonparametric", A_GIMME, 0);
addmess((method)rdist_seed, "seed", A_LONG, 0);
addmess((method)rdist_tellmeeverything, "tellmeeverything", 0);
version(0);
return 0;
}
void *rdist_new(t_symbol *msg, short argc, t_atom *argv){
t_rdist *x;
int i;
t_atom ar[2];
x = (t_rdist *)newobject(rdist_class); // create a new instance of this object
x->r_out0 = outlet_new(x, 0);
x->r_numVars = 0;
// set up the random number generator
gsl_rng_env_setup();
// waterman14 was the fastest according to my tests
x->r_rng = gsl_rng_alloc((const gsl_rng_type *)gsl_rng_waterman14);
// seed it by reading from /dev/random on mac os x and
// something similar on windows
gsl_rng_set(x->r_rng, makeseed());
// this is really fucking important. if there's an error and the gsl's
// default handler gets called, it aborts the program!
gsl_set_error_handler(rdist_errorHandler);
// setup a workspace
x->r_output_buffer = (t_atom *)malloc(RDIST_DEFAULT_BUF_SIZE * sizeof(t_atom));
// init the lib. just gensyms all the distribution names
librdist_init();
// handle the args. this should be done with attributes.
if(argc){
if(argv[0].a_type == A_SYM){
rdist_anything(x, argv[0].a_w.w_sym, argc - 1, argv + 1);
}
} else {
SETFLOAT(&(ar[0]), 0.);
SETFLOAT(&(ar[1]), 1.);
rdist_anything(x, gensym("uniform"), 2, ar);
}
return x;
}
void rdist_bang(t_rdist *x){
int stride = x->r_stride;
float out[stride];
int i;
t_symbol *msg;
//msg = (stride > 1) ? gensym("list") : gensym("float");
//post("buffer: %d, pos: %d, val: %f", x->r_whichBuffer, x->r_bufferPos, out[0].a_w.w_float);
if(x->r_dist == ps_nonparametric){
x->r_function(x->r_rng, 0, x->r_g, stride, out);
}else{
x->r_function(x->r_rng, x->r_numVars, x->r_vars, stride, out);
}
if(stride > 1){
for(i = 0; i < stride; i++){
SETFLOAT(x->r_output_buffer + i, out[i]);
}
outlet_list(x->r_out0, NULL, stride, x->r_output_buffer);
}else{
outlet_float(x->r_out0, out[0]);
}
//outlet_anything(x->r_out0, msg, stride, x->r_output_buffer);
}
void rdist_anything(t_rdist *x, t_symbol *msg, short argc, t_atom *argv){
if(argc > R_MAX_N_VARS){
error("randdist: too many variables");
return;
}
// need to check that this is a valid dist.
x->r_dist = msg;
int i;
if(x->r_dist == gensym("multinomial")){
double sum = 0;
for(i = 1; i < argc; i++){
sum += atom_getfloat(argv + i);
}
x->r_vars[0] = argv[0];
for(i = 1; i < argc; i++){
atom_setfloat(x->r_vars + i, atom_getfloat(argv + i) / sum);
}
}else{
memcpy(x->r_vars, argv, argc * sizeof(t_atom));
}
x->r_numVars = (int)argc;
if(x->r_dist == ps_bivariate_gaussian){
x->r_stride = 2;
}else if(x->r_dist == ps_dirichlet){
x->r_stride = x->r_numVars;
}else if(x->r_dist == ps_multinomial || x->r_dist == ps_multivariate_hypergeometric){
x->r_stride = x->r_numVars - 1;
}else{
x->r_stride = 1;
}
x->r_function = librdist_get_function(x->r_dist);
}
void rdist_nonparametric(t_rdist *x, t_symbol *msg, short argc, t_atom *argv){
double f[argc];
int i;
x->r_dist = msg;
for(i = 0; i < argc; i++){
f[i] = librdist_atom_getfloat(argv + i);
//post("%d, %f", i, f[i]);
}
if(x->r_g){
gsl_ran_discrete_free(x->r_g);
}
x->r_g = gsl_ran_discrete_preproc(argc, f);
x->r_function = librdist_nonparametric;
}
void rdist_list(t_rdist *x, t_symbol *msg, short argc, t_atom *argv){
rdist_anything(x, x->r_dist, argc, argv);
}
void rdist_int(t_rdist *x, long n){
t_atom argv[1];
SETFLOAT(argv, (double)n);
rdist_anything(x, x->r_dist, 1, argv);
}
void rdist_float(t_rdist *x, double n){
t_atom argv[1];
SETFLOAT(argv, n);
rdist_anything(x, x->r_dist, 1, argv);
}
void rdist_distlist(t_rdist *x, long n){
int i, j;
int stride = x->r_stride;
float out[n * stride];
if(stride * n > RDIST_DEFAULT_BUF_SIZE){
error("randdist: output list is too long (%d > %d)",
n * stride,
RDIST_DEFAULT_BUF_SIZE);
return;
}
if(n < 1){
error("randdist: distlist argument must be >= 1.");
return;
}
for(i = 0; i < n; i++){
if(x->r_dist == gensym("nonparametric")){
x->r_function(x->r_rng, x->r_numVars, x->r_g, stride, out);
}else{
x->r_function(x->r_rng, x->r_numVars, x->r_vars, stride, out);
}
for(j = 0; j < stride; j++){
SETFLOAT(x->r_output_buffer + ((i * stride) + j), out[j]);
}
}
outlet_anything(x->r_out0, gensym("list"), n * stride, x->r_output_buffer);
}
void rdist_assist(t_rdist *x, void *b, long m, long a, char *s){
if (m == ASSIST_INLET)
sprintf(s,"Probability distribution and arguments");
else {
switch (a) {
case 0:
sprintf(s,"Random variate");
break;
}
}
}
void rdist_tellmeeverything(t_rdist *x){
int i;
float vars[x->r_numVars];
post("Distribution: %s", x->r_dist->s_name);
post("Args:");
for(i = 0; i < x->r_numVars; i++){
post("\t%f", x->r_vars[i]);
}
}
void rdist_free(t_rdist *x){
if(x->r_rng){
gsl_rng_free(x->r_rng);
}
if(x->r_g){
gsl_ran_discrete_free(x->r_g);
}
if(x->r_arIn){
free(x->r_arIn);
}
if(x->r_output_buffer){
free(x->r_output_buffer);
}
}
void rdist_errorHandler(const char * reason, const char * file, int line, int gsl_errno){
error("randdist: a(n) %s has occured in file %s at line %d (error %d)", reason, file, line, gsl_errno);
}
| {
"alphanum_fraction": 0.6913730255,
"avg_line_length": 30.7663551402,
"ext": "c",
"hexsha": "27eea858202630e6a04f03ffe04681ec776ad92b",
"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": "84a5f38bb4012abbf57c939fb7e1069e0aa86b55",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "hems/ag.granular.suite",
"max_forks_repo_path": "dependencies/randdist.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "84a5f38bb4012abbf57c939fb7e1069e0aa86b55",
"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": "hems/ag.granular.suite",
"max_issues_repo_path": "dependencies/randdist.c",
"max_line_length": 132,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "84a5f38bb4012abbf57c939fb7e1069e0aa86b55",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "hems/ag.granular.suite",
"max_stars_repo_path": "dependencies/randdist.c",
"max_stars_repo_stars_event_max_datetime": "2016-09-18T05:56:22.000Z",
"max_stars_repo_stars_event_min_datetime": "2016-09-18T05:56:22.000Z",
"num_tokens": 3082,
"size": 9876
} |
/*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*
** **
** This file forms part of the Underworld geophysics modelling application. **
** **
** For full license and copyright information, please refer to the LICENSE.md file **
** located at the project root, or contact the authors. **
** **
**~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*/
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <mpi.h>
#include <petsc.h>
#include <petscvec.h>
#include <petscmat.h>
#include <petscksp.h>
#include <petscpc.h>
#include <petscsnes.h>
#include <petscversion.h>
#if ( (PETSC_VERSION_MAJOR >= 3) && (PETSC_VERSION_MINOR >=3) )
#if (PETSC_VERSION_MINOR >=6)
#include "petsc/private/kspimpl.h"
#else
#include "petsc-private/kspimpl.h" /*I "petscksp.h" I*/
#endif
#else
#include "private/kspimpl.h" /*I "petscksp.h" I*/
#endif
#include <StGermain/StGermain.h>
#include <StgDomain/StgDomain.h>
#include <StgFEM/StgFEM.h>
#include <PICellerator/PICellerator.h>
#include <Underworld/Underworld.h>
#include <Solvers/Solvers.h>
#include "petsccompat.h"
#include "TestKSP.h"
#define KSPTEST "test"
EXTERN_C_BEGIN
EXTERN PetscErrorCode PETSCKSP_DLLEXPORT KSPCreate_TEST(KSP);
EXTERN_C_END
#undef __FUNCT__
#define __FUNCT__ "KSPRegisterTEST"
PetscErrorCode PETSCKSP_DLLEXPORT KSPRegisterTEST(const char path[])
{
PetscErrorCode ierr;
PetscFunctionBegin;
ierr = Stg_KSPRegister(KSPTEST, path, "KSPCreate_TEST", KSPCreate_TEST );CHKERRQ(ierr);
PetscFunctionReturn(0);
}
#undef __FUNCT__
#define __FUNCT__ "KSPSolve_TEST"
PetscErrorCode KSPSolve_TEST(KSP ksp)
{
PetscPrintf( PETSC_COMM_WORLD, "----- In KSP Solver %s\n",__func__);
PetscFunctionReturn(0);
}
#undef __FUNCT__
#define __FUNCT__ "KSPDestroy_TEST"
PetscErrorCode KSPDestroy_TEST(KSP ksp)
{
PetscErrorCode ierr;
PetscFunctionBegin;
ierr = KSPDefaultDestroy(ksp);CHKERRQ(ierr);
PetscFunctionReturn(0);
}
#undef __FUNCT__
#define __FUNCT__ "KSPSetFromOptions_TEST"
PetscErrorCode KSPSetFromOptions_TEST(KSP ksp)
{
PetscFunctionReturn(0);
}
#undef __FUNCT__
#define __FUNCT__ "KSPView_TEST"
PetscErrorCode KSPView_TEST(KSP ksp,PetscViewer viewer)
{
PetscFunctionReturn(0);
}
#undef __FUNCT__
#define __FUNCT__ "KSPSetUp_TEST"
PetscErrorCode KSPSetUp_TEST(KSP ksp)
{
PetscFunctionReturn(0);
}
EXTERN_C_BEGIN
#undef __FUNCT__
#define __FUNCT__ "KSPCreate_TEST"
PetscErrorCode PETSCKSP_DLLEXPORT KSPCreate_TEST(KSP ksp)
{
PetscErrorCode ierr;
PetscFunctionBegin;
#if ( (PETSC_VERSION_MAJOR >= 3) && (PETSC_VERSION_MINOR >= 2 ) )
ierr = KSPSetSupportedNorm(ksp,KSP_NORM_NONE,PC_LEFT,1);CHKERRQ(ierr);
#endif
/*
Sets the functions that are associated with this data structure
(in C++ this is the same as defining virtual functions)
*/
ksp->ops->setup = KSPSetUp_TEST;
ksp->ops->solve = KSPSolve_TEST;
ksp->ops->destroy = KSPDestroy_TEST;
ksp->ops->view = KSPView_TEST;
ksp->ops->setfromoptions = KSPSetFromOptions_TEST;
ksp->ops->buildsolution = KSPDefaultBuildSolution;
ksp->ops->buildresidual = KSPDefaultBuildResidual;
PetscFunctionReturn(0);
}
EXTERN_C_END
| {
"alphanum_fraction": 0.6201040811,
"avg_line_length": 28.0846153846,
"ext": "c",
"hexsha": "b3ba18150aedf0a49ed5ed9fcb3c7b159a6911ca",
"lang": "C",
"max_forks_count": 68,
"max_forks_repo_forks_event_max_datetime": "2021-08-25T04:54:26.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-12-14T21:57:46.000Z",
"max_forks_repo_head_hexsha": "5c8acc17fa4d97e86a62b13b8bfb2af6e81a8ee4",
"max_forks_repo_licenses": [
"CC-BY-4.0"
],
"max_forks_repo_name": "longgangfan/underworld2",
"max_forks_repo_path": "underworld/libUnderworld/Solvers/KSPSolvers/src/Test/TestKSP.c",
"max_issues_count": 561,
"max_issues_repo_head_hexsha": "5c8acc17fa4d97e86a62b13b8bfb2af6e81a8ee4",
"max_issues_repo_issues_event_max_datetime": "2022-03-22T23:37:29.000Z",
"max_issues_repo_issues_event_min_datetime": "2015-09-29T06:05:50.000Z",
"max_issues_repo_licenses": [
"CC-BY-4.0"
],
"max_issues_repo_name": "longgangfan/underworld2",
"max_issues_repo_path": "underworld/libUnderworld/Solvers/KSPSolvers/src/Test/TestKSP.c",
"max_line_length": 91,
"max_stars_count": 116,
"max_stars_repo_head_hexsha": "5c8acc17fa4d97e86a62b13b8bfb2af6e81a8ee4",
"max_stars_repo_licenses": [
"CC-BY-4.0"
],
"max_stars_repo_name": "longgangfan/underworld2",
"max_stars_repo_path": "underworld/libUnderworld/Solvers/KSPSolvers/src/Test/TestKSP.c",
"max_stars_repo_stars_event_max_datetime": "2022-03-22T04:12:38.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-09-28T10:30:55.000Z",
"num_tokens": 1090,
"size": 3651
} |
/* siman/siman.c
*
* Copyright (C) 2007 Brian Gough
* Copyright (C) 1996, 1997, 1998, 1999, 2000 Mark Galassi
*
* 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 <math.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <gsl/gsl_machine.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_siman.h>
static inline double
boltzmann(double E, double new_E, double T, gsl_siman_params_t *params)
{
double x = -(new_E - E) / (params->k * T);
/* avoid underflow errors for large uphill steps */
return (x < GSL_LOG_DBL_MIN) ? 0.0 : exp(x);
}
static inline void
copy_state(void *src, void *dst, size_t size, gsl_siman_copy_t copyfunc)
{
if (copyfunc) {
copyfunc(src, dst);
} else {
memcpy(dst, src, size);
}
}
/* implementation of a basic simulated annealing algorithm */
void
gsl_siman_solve (const gsl_rng * r, void *x0_p, gsl_siman_Efunc_t Ef,
gsl_siman_step_t take_step,
gsl_siman_metric_t distance,
gsl_siman_print_t print_position,
gsl_siman_copy_t copyfunc,
gsl_siman_copy_construct_t copy_constructor,
gsl_siman_destroy_t destructor,
size_t element_size,
gsl_siman_params_t params)
{
void *x, *new_x, *best_x;
double E, new_E, best_E;
int i;
double T, T_factor;
int n_evals = 1, n_iter = 0, n_accepts, n_rejects, n_eless;
/* this function requires that either the dynamic functions (copy,
copy_constructor and destrcutor) are passed, or that an element
size is given */
assert((copyfunc != NULL && copy_constructor != NULL && destructor != NULL)
|| (element_size != 0));
distance = 0 ; /* This parameter is not currently used */
E = Ef(x0_p);
if (copyfunc) {
x = copy_constructor(x0_p);
new_x = copy_constructor(x0_p);
best_x = copy_constructor(x0_p);
} else {
x = (void *) malloc (element_size);
memcpy (x, x0_p, element_size);
new_x = (void *) malloc (element_size);
best_x = (void *) malloc (element_size);
memcpy (best_x, x0_p, element_size);
}
best_E = E;
T = params.t_initial;
T_factor = 1.0 / params.mu_t;
if (print_position) {
printf ("#-iter #-evals temperature position energy\n");
}
while (1) {
n_accepts = 0;
n_rejects = 0;
n_eless = 0;
for (i = 0; i < params.iters_fixed_T; ++i) {
copy_state(x, new_x, element_size, copyfunc);
take_step (r, new_x, params.step_size);
new_E = Ef (new_x);
if(new_E <= best_E){
if (copyfunc) {
copyfunc(new_x,best_x);
} else {
memcpy (best_x, new_x, element_size);
}
best_E=new_E;
}
++n_evals; /* keep track of Ef() evaluations */
/* now take the crucial step: see if the new point is accepted
or not, as determined by the boltzmann probability */
if (new_E < E) {
if (new_E < best_E) {
copy_state(new_x, best_x, element_size, copyfunc);
best_E = new_E;
}
/* yay! take a step */
copy_state(new_x, x, element_size, copyfunc);
E = new_E;
++n_eless;
} else if (gsl_rng_uniform(r) < boltzmann(E, new_E, T, ¶ms)) {
/* yay! take a step */
copy_state(new_x, x, element_size, copyfunc);
E = new_E;
++n_accepts;
} else {
++n_rejects;
}
}
if (print_position) {
/* see if we need to print stuff as we go */
/* printf("%5d %12g %5d %3d %3d %3d", n_iter, T, n_evals, */
/* 100*n_eless/n_steps, 100*n_accepts/n_steps, */
/* 100*n_rejects/n_steps); */
printf ("%5d %7d %12g", n_iter, n_evals, T);
print_position (x);
printf (" %12g %12g\n", E, best_E);
}
/* apply the cooling schedule to the temperature */
/* FIXME: I should also introduce a cooling schedule for the iters */
T *= T_factor;
++n_iter;
if (T < params.t_min) {
break;
}
}
/* at the end, copy the result onto the initial point, so we pass it
back to the caller */
copy_state(best_x, x0_p, element_size, copyfunc);
if (copyfunc) {
destructor(x);
destructor(new_x);
destructor(best_x);
} else {
free (x);
free (new_x);
free (best_x);
}
}
/* implementation of a simulated annealing algorithm with many tries */
void
gsl_siman_solve_many (const gsl_rng * r, void *x0_p, gsl_siman_Efunc_t Ef,
gsl_siman_step_t take_step,
gsl_siman_metric_t distance,
gsl_siman_print_t print_position,
size_t element_size,
gsl_siman_params_t params)
{
/* the new set of trial points, and their energies and probabilities */
void *x, *new_x;
double *energies, *probs, *sum_probs;
double Ex; /* energy of the chosen point */
double T, T_factor; /* the temperature and a step multiplier */
int i;
double u; /* throw the die to choose a new "x" */
int n_iter;
if (print_position) {
printf ("#-iter temperature position");
printf (" delta_pos energy\n");
}
x = (void *) malloc (params.n_tries * element_size);
new_x = (void *) malloc (params.n_tries * element_size);
energies = (double *) malloc (params.n_tries * sizeof (double));
probs = (double *) malloc (params.n_tries * sizeof (double));
sum_probs = (double *) malloc (params.n_tries * sizeof (double));
T = params.t_initial;
T_factor = 1.0 / params.mu_t;
memcpy (x, x0_p, element_size);
n_iter = 0;
while (1)
{
Ex = Ef (x);
for (i = 0; i < params.n_tries - 1; ++i)
{ /* only go to N_TRIES-2 */
/* center the new_x[] around x, then pass it to take_step() */
sum_probs[i] = 0;
memcpy ((char *)new_x + i * element_size, x, element_size);
take_step (r, (char *)new_x + i * element_size, params.step_size);
energies[i] = Ef ((char *)new_x + i * element_size);
probs[i] = boltzmann(Ex, energies[i], T, ¶ms);
}
/* now add in the old value of "x", so it is a contendor */
memcpy ((char *)new_x + (params.n_tries - 1) * element_size, x, element_size);
energies[params.n_tries - 1] = Ex;
probs[params.n_tries - 1] = boltzmann(Ex, energies[i], T, ¶ms);
/* now throw biased die to see which new_x[i] we choose */
sum_probs[0] = probs[0];
for (i = 1; i < params.n_tries; ++i)
{
sum_probs[i] = sum_probs[i - 1] + probs[i];
}
u = gsl_rng_uniform (r) * sum_probs[params.n_tries - 1];
for (i = 0; i < params.n_tries; ++i)
{
if (u < sum_probs[i])
{
memcpy (x, (char *) new_x + i * element_size, element_size);
break;
}
}
if (print_position)
{
printf ("%5d\t%12g\t", n_iter, T);
print_position (x);
printf ("\t%12g\t%12g\n", distance (x, x0_p), Ex);
}
T *= T_factor;
++n_iter;
if (T < params.t_min)
{
break;
}
}
/* now return the value via x0_p */
memcpy (x0_p, x, element_size);
/* printf("the result is: %g (E=%g)\n", x, Ex); */
free (x);
free (new_x);
free (energies);
free (probs);
free (sum_probs);
}
| {
"alphanum_fraction": 0.5871672187,
"avg_line_length": 29.7481751825,
"ext": "c",
"hexsha": "65b9177fe074f08ea0082ddbfe7908b39c6a3404",
"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/siman/siman.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/siman/siman.c",
"max_line_length": 84,
"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/siman/siman.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": 2288,
"size": 8151
} |
#ifndef DOCH
#define DOCH
#include <gsl/gsl_vector.h>
#include <assert.h>
#include "utils.h"
#include "topic.h"
#include "typedefs.h"
#define OFFSET 0
#define MH_GEM_STDEV 0.05
#define MH_GEM_MEAN_STDEV 0.05
#define MH_GEM_STDEV 0.05
/*
* resample the levels of a document
*
*/
void doc_sample_levels(doc* d, short do_permute, short do_remove);
/*
* update a level count
*
*/
void doc_update_level(doc* d, int l, double update);
/*
* read corpus from data
*
*/
void read_corpus(char* filename, corpus* c, int depth);
/*
* allocate a new corpus
*
*/
corpus* corpus_new(double mean, double scale);
/*
* score the corpus
*
*/
double gem_score(corpus* corp);
/*
* GEM MH updates
*
*/
void corpus_mh_update_gem(corpus* corp);
void corpus_mh_update_gem_mean(corpus* corp);
void corpus_mh_update_gem_scale(corpus* corp);
void compute_log_p_level(doc* d, double gem_mean, double gem_scale);
/*
* write the document clustering to a file
*
*/
void write_corpus_assignment(corpus* corp, FILE* file);
void write_corpus_levels(corpus* corp, FILE* file);
// free a corpus
void free_corpus(corpus* corp);
void free_doc(doc* d);
#endif
| {
"alphanum_fraction": 0.7125645439,
"avg_line_length": 15.2894736842,
"ext": "h",
"hexsha": "308922e8bb0018875105a4fe1be88592d5ed7295",
"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": "0200fca1bd80de290c5fc01e389d6f0fa736868d",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "thatindiandude/PGM-Project",
"max_forks_repo_path": "Algorithms/OurAlgo/hlda-c/doc.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "0200fca1bd80de290c5fc01e389d6f0fa736868d",
"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": "thatindiandude/PGM-Project",
"max_issues_repo_path": "Algorithms/OurAlgo/hlda-c/doc.h",
"max_line_length": 68,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "0200fca1bd80de290c5fc01e389d6f0fa736868d",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "thatindiandude/PGM-Project",
"max_stars_repo_path": "Algorithms/OurAlgo/hlda-c/doc.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 310,
"size": 1162
} |
#ifndef __GSL_VERSION_H__
#define __GSL_VERSION_H__
#include <gsl/gsl_types.h>
#undef __BEGIN_DECLS
#undef __END_DECLS
#ifdef __cplusplus
# define __BEGIN_DECLS extern "C" {
# define __END_DECLS }
#else
# define __BEGIN_DECLS /* empty */
# define __END_DECLS /* empty */
#endif
__BEGIN_DECLS
#define GSL_VERSION "2.2.1"
#define GSL_MAJOR_VERSION 2
#define GSL_MINOR_VERSION 2
GSL_VAR const char * gsl_version;
__END_DECLS
#endif /* __GSL_VERSION_H__ */
| {
"alphanum_fraction": 0.7717391304,
"avg_line_length": 17.037037037,
"ext": "h",
"hexsha": "c5bac549d166fff750f05f0c28c423fa12b1dcd8",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2022-02-20T15:50:01.000Z",
"max_forks_repo_forks_event_min_datetime": "2022-02-20T15:50:01.000Z",
"max_forks_repo_head_hexsha": "0ad5e82b49a973cf710f85daa9dffc45261b36ae",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "Tjoppen/fmigo",
"max_forks_repo_path": "3rdparty/wingsl/include/gsl/gsl_version.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "0ad5e82b49a973cf710f85daa9dffc45261b36ae",
"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": "Tjoppen/fmigo",
"max_issues_repo_path": "3rdparty/wingsl/include/gsl/gsl_version.h",
"max_line_length": 35,
"max_stars_count": 7,
"max_stars_repo_head_hexsha": "0ad5e82b49a973cf710f85daa9dffc45261b36ae",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "Tjoppen/fmigo",
"max_stars_repo_path": "3rdparty/wingsl/include/gsl/gsl_version.h",
"max_stars_repo_stars_event_max_datetime": "2021-05-14T07:38:05.000Z",
"max_stars_repo_stars_event_min_datetime": "2018-12-18T16:35:21.000Z",
"num_tokens": 123,
"size": 460
} |
/* Copyright (c) Kyrylo Polezhaiev and contributors. All rights reserved.
Released under the MIT license. See LICENSE file in the project root for full license information. */
#include "leopenblas.h"
#include <assert.h>
#include <le/le.h>
#include <le/tensors/letensor-imp.h>
#include <cblas.h>
LeTensor *
le_openblas_matrix_new_product(const LeTensor *a, bool transpose_a, const LeTensor *b, bool transpose_b)
{
/// @todo: Take stride into account
assert(a->element_type == LE_TYPE_FLOAT32);
assert(b->element_type == LE_TYPE_FLOAT32);
assert(a->shape->num_dimensions == 2);
assert(b->shape->num_dimensions == 2);
assert(le_tensor_contiguous(a));
assert(le_tensor_contiguous(b));
unsigned size_a = transpose_a ? a->shape->sizes[0] : a->shape->sizes[1];
unsigned size_b = transpose_b ? b->shape->sizes[1] : b->shape->sizes[0];
assert(size_a == size_b);
unsigned c_height = transpose_a ? a->shape->sizes[1] : a->shape->sizes[0];
unsigned c_width = transpose_b ? b->shape->sizes[0] : b->shape->sizes[1];
LeTensor *c = le_matrix_new_uninitialized(LE_TYPE_FLOAT32, c_height, c_width);
cblas_sgemm(CblasRowMajor,
transpose_a ? CblasTrans : CblasNoTrans,
transpose_b ? CblasTrans : CblasNoTrans,
c_height, c_width, size_a,
1.0f,
a->data, a->shape->sizes[1],
b->data, b->shape->sizes[1],
0.0f,
c->data, c->shape->sizes[1]);
return c;
}
float
le_openblas_dot_product(const LeTensor *a, const LeTensor *b)
{
assert(a->element_type == LE_TYPE_FLOAT32);
assert(b->element_type == LE_TYPE_FLOAT32);
assert(a->shape->num_dimensions == 2);
assert(b->shape->num_dimensions == 2);
/** @todo: Test results against transposed a multiplied by b */
assert(a->shape->sizes[0] == b->shape->sizes[0]);
assert(a->shape->sizes[1] == 1);
assert(b->shape->sizes[1] == 1);
return cblas_sdot(a->shape->sizes[0], a->data, a->stride, b->data, b->stride);
}
| {
"alphanum_fraction": 0.6342281879,
"avg_line_length": 36.5964912281,
"ext": "c",
"hexsha": "74420ae2c6e29cf893c8ada81735bcb6d00ba765",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2021-04-02T17:49:08.000Z",
"max_forks_repo_forks_event_min_datetime": "2019-04-23T05:37:27.000Z",
"max_forks_repo_head_hexsha": "8da0e1c6094ae8886e42e48a99120a0d01a882ae",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "neonkingfr/le",
"max_forks_repo_path": "platform/openblas/leopenblas.c",
"max_issues_count": 42,
"max_issues_repo_head_hexsha": "8da0e1c6094ae8886e42e48a99120a0d01a882ae",
"max_issues_repo_issues_event_max_datetime": "2020-12-16T22:04:25.000Z",
"max_issues_repo_issues_event_min_datetime": "2018-01-02T22:55:58.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "neonkingfr/le",
"max_issues_repo_path": "platform/openblas/leopenblas.c",
"max_line_length": 104,
"max_stars_count": 23,
"max_stars_repo_head_hexsha": "8da0e1c6094ae8886e42e48a99120a0d01a882ae",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "neonkingfr/le",
"max_stars_repo_path": "platform/openblas/leopenblas.c",
"max_stars_repo_stars_event_max_datetime": "2022-01-06T19:27:09.000Z",
"max_stars_repo_stars_event_min_datetime": "2018-07-16T16:15:20.000Z",
"num_tokens": 583,
"size": 2086
} |
// Copyright Jean Pierre Cimalando 2019.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE.md or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#pragma once
#include <gsl/gsl>
#include <string>
struct fmidi_smf;
struct SMF_Encoding_Detector {
public:
void scan(const fmidi_smf &smf);
std::string general_encoding() const;
std::string encoding_for_text(gsl::cstring_span input) const;
std::string decode_to_utf8(gsl::cstring_span input) const;
private:
static gsl::cstring_span encoding_from_marker(gsl::cstring_span input);
static gsl::cstring_span strip_encoding_marker(gsl::cstring_span text, gsl::cstring_span enc);
private:
std::string encoding_;
};
| {
"alphanum_fraction": 0.7321899736,
"avg_line_length": 27.0714285714,
"ext": "h",
"hexsha": "cb1f2fbbb9a4546ae9577181fb6cb668abe2b971",
"lang": "C",
"max_forks_count": 3,
"max_forks_repo_forks_event_max_datetime": "2021-11-22T08:05:13.000Z",
"max_forks_repo_forks_event_min_datetime": "2020-07-10T18:48:10.000Z",
"max_forks_repo_head_hexsha": "9978db5c9fa8b6eebe558eee212a2c0ed5c9e1bb",
"max_forks_repo_licenses": [
"BSL-1.0"
],
"max_forks_repo_name": "jpcima/smf-dsp",
"max_forks_repo_path": "sources/player/smftext.h",
"max_issues_count": 19,
"max_issues_repo_head_hexsha": "9978db5c9fa8b6eebe558eee212a2c0ed5c9e1bb",
"max_issues_repo_issues_event_max_datetime": "2022-01-16T20:44:07.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-07-05T23:59:33.000Z",
"max_issues_repo_licenses": [
"BSL-1.0"
],
"max_issues_repo_name": "jpcima/smf-dsp",
"max_issues_repo_path": "sources/player/smftext.h",
"max_line_length": 98,
"max_stars_count": 22,
"max_stars_repo_head_hexsha": "9978db5c9fa8b6eebe558eee212a2c0ed5c9e1bb",
"max_stars_repo_licenses": [
"BSL-1.0"
],
"max_stars_repo_name": "jpcima/smf-dsp",
"max_stars_repo_path": "sources/player/smftext.h",
"max_stars_repo_stars_event_max_datetime": "2022-03-26T23:08:17.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-07-08T15:23:44.000Z",
"num_tokens": 186,
"size": 758
} |
/* specfunc/legendre_P.c
*
* Copyright (C) 2009-2013 Patrick Alken
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include <config.h>
#include <stdlib.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_sf_legendre.h>
/*
* The routines in this module compute associated Legendre functions
* (ALFs) up to order and degree 2700, using the method described
* in
*
* [1] S. A. Holmes and W. E. Featherstone, A unified approach
* to the Clenshaw summation and the recursive computation of very
* high degree and order normalised associated Legendre functions,
* Journal of Geodesy, 76, pg. 279-299, 2002.
*
* Further information on ALFs can be found in
*
* [2] Abramowitz and Stegun, Handbook of Mathematical Functions,
* Chapter 8, 1972.
*/
static void legendre_sqrts(const size_t lmax, double *array);
#define LEGENDRE
#include "legendre_source.c"
#undef LEGENDRE
#define LEGENDRE_DERIV
#include "legendre_source.c"
#undef LEGENDRE_DERIV
#define LEGENDRE_DERIV_ALT
#include "legendre_source.c"
#undef LEGENDRE_DERIV_ALT
#define LEGENDRE_DERIV2
#include "legendre_source.c"
#undef LEGENDRE_DERIV2
#define LEGENDRE_DERIV2_ALT
#include "legendre_source.c"
#undef LEGENDRE_DERIV2_ALT
/* number of P_{lm} functions for a given lmax */
size_t
gsl_sf_legendre_nlm(const size_t lmax)
{
return ((lmax + 1) * (lmax + 2) / 2);
}
/*
gsl_sf_legendre_array_n()
This routine returns the minimum result_array[] size needed
for a given lmax
*/
size_t
gsl_sf_legendre_array_n(const size_t lmax)
{
size_t nlm = gsl_sf_legendre_nlm(lmax);
size_t nsqrt = 2 * lmax + 2; /* extra room to precompute sqrt factors */
return (nlm + nsqrt);
} /* gsl_sf_legendre_array_n() */
/*
gsl_sf_legendre_array_index()
This routine computes the index into a result_array[] corresponding
to a given (l,m)
*/
size_t
gsl_sf_legendre_array_index(const size_t l, const size_t m)
{
return (l * (l + 1) / 2 + m);
} /* gsl_sf_legendre_array_index() */
/*********************************************************
* INTERNAL ROUTINES *
*********************************************************/
/*
legendre_sqrts()
Precompute square root factors needed for Legendre recurrence.
On output, array[i] = sqrt(i)
*/
static void
legendre_sqrts(const size_t lmax, double *array)
{
size_t l;
for (l = 0; l <= 2 * lmax + 1; ++l)
array[l] = sqrt((double) l);
}
| {
"alphanum_fraction": 0.6937660668,
"avg_line_length": 27.0608695652,
"ext": "c",
"hexsha": "45e26fa22d691fc10f4bfd3cb5b1fe986f04f0ec",
"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/specfunc/legendre_P.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/specfunc/legendre_P.c",
"max_line_length": 81,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "ielomariala/Hex-Game",
"max_stars_repo_path": "gsl-2.6/specfunc/legendre_P.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": 838,
"size": 3112
} |
#pragma once
#ifndef _NOSNOPT
#include <fstream>
#include <iostream>
#include "BasicError.h"
#ifndef _NOGSL
#include <gsl/gsl_vector.h>
#else
#include "FakeGSL.h"
#endif
#include "OptSolver.h"
#include "snopt.hh"
#include "snoptProblem.hh"
using namespace std;
class SnoptSolver : public OptSolver {
snoptProblem snoptProb;
integer n; integer neF; integer lenA; integer lenG;
integer *iAfun;
integer *jAvar;
doublereal *A;
integer *iGfun;
integer *jGvar;
doublereal *x;
doublereal *xlow;
doublereal *xupp;
doublereal *xmul;
integer *xstate;
doublereal *F;
doublereal *Flow;
doublereal *Fupp;
doublereal *Fmul;
integer *Fstate;
integer nxnames;
integer nFnames = 1;
char *xnames;
char *Fnames;
gsl_vector* result;
double objectiveVal;
integer Cold = 0, Basis = 1, Warm = 2;
public:
SnoptSolver(integer n_, integer neF_, integer lenA_): n(n_), neF(neF_), lenA(lenA_) {
iAfun = new integer[lenA];
jAvar = new integer[lenA];
A = new doublereal[lenA];
lenG = n*neF;
iGfun = new integer[lenG];
jGvar = new integer[lenG];
x = new doublereal[n];
xlow = new doublereal[n];
xupp = new doublereal[n];
xmul = new doublereal[n];
xstate = new integer[n];
F = new doublereal[neF];
Flow = new doublereal[neF];
Fupp = new doublereal[neF];
Fmul = new doublereal[neF];
Fstate = new integer[neF];
nxnames = 1;
nFnames = 1;
xnames = new char[nxnames*8];
Fnames = new char[nFnames*8];
snoptProb.setXNames(xnames, nxnames);
snoptProb.setFNames(Fnames, nFnames);
result = gsl_vector_alloc(n);
}
~SnoptSolver() {
delete []iAfun; delete []jAvar; delete []A;
delete []iGfun; delete []jGvar;
delete []x; delete []xlow; delete []xupp;
delete []xmul; delete []xstate;
delete []F; delete []Flow; delete []Fupp;
delete []Fmul; delete []Fstate;
delete []xnames; delete []Fnames;
}
virtual void init(char* workspace, integer nef_, DFT df, integer ObjRow, doublereal ObjAdd, doublereal *xlow_, doublereal *xupp_, doublereal *Flow_, doublereal *Fupp_);
bool optimize(gsl_vector* initState, bool suppressPrint = false);
virtual gsl_vector* getResults() {
return result;
}
virtual double getObjectiveVal() {
return objectiveVal;
}
};
#endif
| {
"alphanum_fraction": 0.6833702882,
"avg_line_length": 19.7807017544,
"ext": "h",
"hexsha": "b92fd49fafb7516eb6b0181216f882234ec5e15b",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2020-12-06T01:45:04.000Z",
"max_forks_repo_forks_event_min_datetime": "2020-12-04T20:47:51.000Z",
"max_forks_repo_head_hexsha": "6ecbb6f724149d50d290997fef5e2e1e92ab3d9e",
"max_forks_repo_licenses": [
"X11"
],
"max_forks_repo_name": "natebragg/sketch-backend",
"max_forks_repo_path": "src/SketchSolver/NumericalSynthesis/Optimizers/Snopt.h",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "6ecbb6f724149d50d290997fef5e2e1e92ab3d9e",
"max_issues_repo_issues_event_max_datetime": "2022-03-04T04:02:09.000Z",
"max_issues_repo_issues_event_min_datetime": "2022-03-01T16:53:05.000Z",
"max_issues_repo_licenses": [
"X11"
],
"max_issues_repo_name": "natebragg/sketch-backend",
"max_issues_repo_path": "src/SketchSolver/NumericalSynthesis/Optimizers/Snopt.h",
"max_line_length": 169,
"max_stars_count": 17,
"max_stars_repo_head_hexsha": "6ecbb6f724149d50d290997fef5e2e1e92ab3d9e",
"max_stars_repo_licenses": [
"X11"
],
"max_stars_repo_name": "natebragg/sketch-backend",
"max_stars_repo_path": "src/SketchSolver/NumericalSynthesis/Optimizers/Snopt.h",
"max_stars_repo_stars_event_max_datetime": "2022-03-31T00:28:40.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-08-20T14:54:11.000Z",
"num_tokens": 757,
"size": 2255
} |
/* vector/gsl_vector_ulong.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., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#ifndef __GSL_VECTOR_ULONG_H__
#define __GSL_VECTOR_ULONG_H__
#include <stdlib.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_block_ulong.h>
#undef __BEGIN_DECLS
#undef __END_DECLS
#ifdef __cplusplus
# define __BEGIN_DECLS extern "C" {
# define __END_DECLS }
#else
# define __BEGIN_DECLS /* empty */
# define __END_DECLS /* empty */
#endif
__BEGIN_DECLS
typedef struct
{
size_t size;
size_t stride;
unsigned long *data;
gsl_block_ulong *block;
int owner;
}
gsl_vector_ulong;
typedef struct
{
gsl_vector_ulong vector;
} _gsl_vector_ulong_view;
typedef _gsl_vector_ulong_view gsl_vector_ulong_view;
typedef struct
{
gsl_vector_ulong vector;
} _gsl_vector_ulong_const_view;
typedef const _gsl_vector_ulong_const_view gsl_vector_ulong_const_view;
/* Allocation */
gsl_vector_ulong *gsl_vector_ulong_alloc (const size_t n);
gsl_vector_ulong *gsl_vector_ulong_calloc (const size_t n);
gsl_vector_ulong *gsl_vector_ulong_alloc_from_block (gsl_block_ulong * b,
const size_t offset,
const size_t n,
const size_t stride);
gsl_vector_ulong *gsl_vector_ulong_alloc_from_vector (gsl_vector_ulong * v,
const size_t offset,
const size_t n,
const size_t stride);
void gsl_vector_ulong_free (gsl_vector_ulong * v);
/* Views */
_gsl_vector_ulong_view
gsl_vector_ulong_view_array (unsigned long *v, size_t n);
_gsl_vector_ulong_view
gsl_vector_ulong_view_array_with_stride (unsigned long *base,
size_t stride,
size_t n);
_gsl_vector_ulong_const_view
gsl_vector_ulong_const_view_array (const unsigned long *v, size_t n);
_gsl_vector_ulong_const_view
gsl_vector_ulong_const_view_array_with_stride (const unsigned long *base,
size_t stride,
size_t n);
_gsl_vector_ulong_view
gsl_vector_ulong_subvector (gsl_vector_ulong *v,
size_t i,
size_t n);
_gsl_vector_ulong_view
gsl_vector_ulong_subvector_with_stride (gsl_vector_ulong *v,
size_t i,
size_t stride,
size_t n);
_gsl_vector_ulong_const_view
gsl_vector_ulong_const_subvector (const gsl_vector_ulong *v,
size_t i,
size_t n);
_gsl_vector_ulong_const_view
gsl_vector_ulong_const_subvector_with_stride (const gsl_vector_ulong *v,
size_t i,
size_t stride,
size_t n);
/* Operations */
unsigned long gsl_vector_ulong_get (const gsl_vector_ulong * v, const size_t i);
void gsl_vector_ulong_set (gsl_vector_ulong * v, const size_t i, unsigned long x);
unsigned long *gsl_vector_ulong_ptr (gsl_vector_ulong * v, const size_t i);
const unsigned long *gsl_vector_ulong_const_ptr (const gsl_vector_ulong * v, const size_t i);
void gsl_vector_ulong_set_zero (gsl_vector_ulong * v);
void gsl_vector_ulong_set_all (gsl_vector_ulong * v, unsigned long x);
int gsl_vector_ulong_set_basis (gsl_vector_ulong * v, size_t i);
int gsl_vector_ulong_fread (FILE * stream, gsl_vector_ulong * v);
int gsl_vector_ulong_fwrite (FILE * stream, const gsl_vector_ulong * v);
int gsl_vector_ulong_fscanf (FILE * stream, gsl_vector_ulong * v);
int gsl_vector_ulong_fprintf (FILE * stream, const gsl_vector_ulong * v,
const char *format);
int gsl_vector_ulong_memcpy (gsl_vector_ulong * dest, const gsl_vector_ulong * src);
int gsl_vector_ulong_reverse (gsl_vector_ulong * v);
int gsl_vector_ulong_swap (gsl_vector_ulong * v, gsl_vector_ulong * w);
int gsl_vector_ulong_swap_elements (gsl_vector_ulong * v, const size_t i, const size_t j);
unsigned long gsl_vector_ulong_max (const gsl_vector_ulong * v);
unsigned long gsl_vector_ulong_min (const gsl_vector_ulong * v);
void gsl_vector_ulong_minmax (const gsl_vector_ulong * v, unsigned long * min_out, unsigned long * max_out);
size_t gsl_vector_ulong_max_index (const gsl_vector_ulong * v);
size_t gsl_vector_ulong_min_index (const gsl_vector_ulong * v);
void gsl_vector_ulong_minmax_index (const gsl_vector_ulong * v, size_t * imin, size_t * imax);
int gsl_vector_ulong_add (gsl_vector_ulong * a, const gsl_vector_ulong * b);
int gsl_vector_ulong_sub (gsl_vector_ulong * a, const gsl_vector_ulong * b);
int gsl_vector_ulong_mul (gsl_vector_ulong * a, const gsl_vector_ulong * b);
int gsl_vector_ulong_div (gsl_vector_ulong * a, const gsl_vector_ulong * b);
int gsl_vector_ulong_scale (gsl_vector_ulong * a, const double x);
int gsl_vector_ulong_add_constant (gsl_vector_ulong * a, const double x);
int gsl_vector_ulong_isnull (const gsl_vector_ulong * v);
extern int gsl_check_range;
#ifdef HAVE_INLINE
extern inline
unsigned long
gsl_vector_ulong_get (const gsl_vector_ulong * v, const size_t i)
{
#ifndef GSL_RANGE_CHECK_OFF
if (i >= v->size)
{
GSL_ERROR_VAL ("index out of range", GSL_EINVAL, 0);
}
#endif
return v->data[i * v->stride];
}
extern inline
void
gsl_vector_ulong_set (gsl_vector_ulong * v, const size_t i, unsigned long x)
{
#ifndef GSL_RANGE_CHECK_OFF
if (i >= v->size)
{
GSL_ERROR_VOID ("index out of range", GSL_EINVAL);
}
#endif
v->data[i * v->stride] = x;
}
extern inline
unsigned long *
gsl_vector_ulong_ptr (gsl_vector_ulong * v, const size_t i)
{
#ifndef GSL_RANGE_CHECK_OFF
if (i >= v->size)
{
GSL_ERROR_NULL ("index out of range", GSL_EINVAL);
}
#endif
return (unsigned long *) (v->data + i * v->stride);
}
extern inline
const unsigned long *
gsl_vector_ulong_const_ptr (const gsl_vector_ulong * v, const size_t i)
{
#ifndef GSL_RANGE_CHECK_OFF
if (i >= v->size)
{
GSL_ERROR_NULL ("index out of range", GSL_EINVAL);
}
#endif
return (const unsigned long *) (v->data + i * v->stride);
}
#endif /* HAVE_INLINE */
__END_DECLS
#endif /* __GSL_VECTOR_ULONG_H__ */
| {
"alphanum_fraction": 0.6793712616,
"avg_line_length": 31.6696035242,
"ext": "h",
"hexsha": "3269205933ae0315d30f963782ef42c13b0e7e6b",
"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/vector/gsl_vector_ulong.h",
"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/vector/gsl_vector_ulong.h",
"max_line_length": 108,
"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/vector/gsl_vector_ulong.h",
"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": 1659,
"size": 7189
} |
#pragma once
#include <GLES2/gl2.h>
#include <GLES2/gl2ext.h>
#include <GLES3/gl3.h>
#include <GLES3/gl3ext.h>
#include <GLES3/gl3platform.h>
#include <EGL/egl.h>
#include <EGL/eglext.h>
#include <gsl/gsl>
namespace android::OpenGLHelpers
{
constexpr GLint GetTextureUnit(GLenum texture)
{
return texture - GL_TEXTURE0;
}
GLuint CreateShaderProgram(const char* vertShaderSource, const char* fragShaderSource);
namespace GLTransactions
{
inline auto SetCapability(GLenum capability, bool isEnabled)
{
const auto setCapability{ [capability](bool isEnabled)
{
if (isEnabled)
{
glEnable(capability);
}
else
{
glDisable(capability);
}
}};
const auto wasEnabled{ glIsEnabled(capability) };
setCapability(isEnabled);
return gsl::finally([wasEnabled, setCapability]() { setCapability(wasEnabled); });
}
inline auto BindFrameBuffer(GLuint frameBufferId)
{
GLint previousFrameBufferId;
glGetIntegerv(GL_FRAMEBUFFER_BINDING, &previousFrameBufferId);
glBindFramebuffer(GL_FRAMEBUFFER, frameBufferId);
return gsl::finally([previousFrameBufferId]() { glBindFramebuffer(GL_FRAMEBUFFER, static_cast<GLuint>(previousFrameBufferId)); });
}
inline auto DepthMask(GLboolean depthMask)
{
GLboolean previousDepthMask;
glGetBooleanv(GL_DEPTH_WRITEMASK, &previousDepthMask);
glDepthMask(depthMask);
return gsl::finally([previousDepthMask]() { glDepthMask(previousDepthMask); });
}
inline auto BindSampler(GLenum unit, GLuint id)
{
glActiveTexture(unit);
GLint previousId;
glGetIntegerv(GL_SAMPLER_BINDING, &previousId);
glBindSampler(unit - GL_TEXTURE0, id);
return gsl::finally([unit, id{ previousId }]() { glActiveTexture(unit); glBindSampler(unit - GL_TEXTURE0, id); });
}
inline auto MakeCurrent(EGLDisplay display, EGLSurface drawSurface, EGLSurface readSurface, EGLContext context)
{
EGLDisplay previousDisplay{ eglGetDisplay(EGL_DEFAULT_DISPLAY) };
EGLSurface previousDrawSurface{ eglGetCurrentSurface(EGL_DRAW) };
EGLSurface previousReadSurface{ eglGetCurrentSurface(EGL_READ) };
EGLContext previousContext{ eglGetCurrentContext() };
eglMakeCurrent(display, drawSurface, readSurface, context);
return gsl::finally([previousDisplay, previousDrawSurface, previousReadSurface, previousContext]() { eglMakeCurrent(previousDisplay, previousDrawSurface, previousReadSurface, previousContext); });
}
}
} | {
"alphanum_fraction": 0.636931621,
"avg_line_length": 37.4155844156,
"ext": "h",
"hexsha": "743801ce16965de5afd2d3fc1b74ebb83a5d6c48",
"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": "7f1f9fd23bf649c9c8a1260f2b93752145b0c024",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "chiamaka-123/BabylonNative",
"max_forks_repo_path": "Dependencies/AndroidExtensions/Include/AndroidExtensions/OpenGLHelpers.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "7f1f9fd23bf649c9c8a1260f2b93752145b0c024",
"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": "chiamaka-123/BabylonNative",
"max_issues_repo_path": "Dependencies/AndroidExtensions/Include/AndroidExtensions/OpenGLHelpers.h",
"max_line_length": 208,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "7f1f9fd23bf649c9c8a1260f2b93752145b0c024",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "chiamaka-123/BabylonNative",
"max_stars_repo_path": "Dependencies/AndroidExtensions/Include/AndroidExtensions/OpenGLHelpers.h",
"max_stars_repo_stars_event_max_datetime": "2021-02-23T17:39:12.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-02-23T17:39:12.000Z",
"num_tokens": 597,
"size": 2881
} |
/***************************************************************************
File : muParserScript.h
Project : QtiPlot
--------------------------------------------------------------------
Copyright : (C) 2006 by Ion Vasilief, Knut Franke
Email (use @ for *) : ion_vasilief*yahoo.fr, knut.franke*gmx.de
Description : Evaluate mathematical expressions using muParser
***************************************************************************/
/***************************************************************************
* *
* 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 MUPARSER_SCRIPT_H
#define MUPARSER_SCRIPT_H
#include "ScriptingEnv.h"
#include "Script.h"
#include <muParser.h>
#include "math.h"
#include <gsl/gsl_sf.h>
#include <q3asciidict.h>
//! TODO
class muParserScript: public Script
{
Q_OBJECT
public:
muParserScript(ScriptingEnv *env, const QString &code, QObject *context=0, const QString &name="<input>", bool checkMultilineCode = true);
public slots:
bool compile(bool asFunction=true);
QVariant eval();
double evalSingleLine();
QString evalSingleLineToString(const QLocale& locale, char f, int prec);
bool exec();
bool setQObject(QObject *val, const char *name);
bool setInt(int val, const char* name);
bool setDouble(double val, const char* name);
double* defineVariable(const char *name, double val = 0.0);
int codeLines(){return muCode.size();};
private:
double col(const QString &arg);
double tablecol(const QString &arg);
double cell(int row, int col);
double tableCell(int col, int row);
double *addVariable(const char *name);
double *addVariableR(const char *name);
static double *mu_addVariableR(const char *name) { return current->addVariableR(name); }
static double mu_col(const char *arg) { return current->col(arg); }
static double mu_cell(double row, double col) { return current->cell(qRound(row), qRound(col)); }
static double mu_tableCell(double col, double row) { return current->tableCell(qRound(col), qRound(row)); }
static double mu_tablecol(const char *arg) { return current->tablecol(arg); }
static double *mu_addVariable(const char *name, void *){ return current->addVariable(name); }
static double *mu_addVariableR(const char *name, void *) { return current->addVariableR(name); }
static QString compileColArg(const QString& in);
mu::Parser parser, rparser;
Q3AsciiDict<double> variables, rvariables;
QStringList muCode;
//! Flag telling is the parser should warn users on multiline code input
bool d_warn_multiline_code;
public:
static muParserScript *current;
};
#endif
| {
"alphanum_fraction": 0.5512756378,
"avg_line_length": 45.4318181818,
"ext": "h",
"hexsha": "685d6737580789bd6b94c8221ab93cd9b36811d9",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2017-12-06T12:16:47.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-03-25T15:50:31.000Z",
"max_forks_repo_head_hexsha": "9abd34048274b2ce9dbbb685124177b02d6a34ca",
"max_forks_repo_licenses": [
"IJG"
],
"max_forks_repo_name": "hoehnp/SpaceDesignTool",
"max_forks_repo_path": "thirdparty/qtiplot/qtiplot/src/muParserScript.h",
"max_issues_count": 2,
"max_issues_repo_head_hexsha": "9abd34048274b2ce9dbbb685124177b02d6a34ca",
"max_issues_repo_issues_event_max_datetime": "2015-08-14T03:15:42.000Z",
"max_issues_repo_issues_event_min_datetime": "2015-02-07T19:09:21.000Z",
"max_issues_repo_licenses": [
"IJG"
],
"max_issues_repo_name": "hoehnp/SpaceDesignTool",
"max_issues_repo_path": "thirdparty/qtiplot/qtiplot/src/muParserScript.h",
"max_line_length": 142,
"max_stars_count": 6,
"max_stars_repo_head_hexsha": "9abd34048274b2ce9dbbb685124177b02d6a34ca",
"max_stars_repo_licenses": [
"IJG"
],
"max_stars_repo_name": "hoehnp/SpaceDesignTool",
"max_stars_repo_path": "thirdparty/qtiplot/qtiplot/src/muParserScript.h",
"max_stars_repo_stars_event_max_datetime": "2021-07-01T05:34:23.000Z",
"max_stars_repo_stars_event_min_datetime": "2018-09-05T12:41:59.000Z",
"num_tokens": 802,
"size": 3998
} |
#include <math.h>
#include <cblas.h>
#ifdef _MSC_VER
# define inline __inline
#endif
/*
* General Cholesky Delete.
* Remove an element from the cholesky factorization
* m = columns
* n = rows
*
* TODO: put transpose as an option
*/
static inline void cholesky_delete_dbl(int m, int n, double *L, int go_out)
{
double c, s;
/* delete row go_out */
double *L1 = L + (go_out * m);
int i;
for (i = go_out; i < n - 1; ++i) {
cblas_dcopy (i + 2, L1 + m , 1, L1, 1);
L1 += m;
}
L1 = L + (go_out * m);
for (i=go_out; i < n - 1; ++i) {
cblas_drotg(L1 + i, L1 + i + 1, &c, &s);
if (L1[i] < 0) {
/* Diagonals cannot be negative */
L1[i] = fabs(L1[i]);
c = -c;
s = -s;
}
L1[i+1] = 0.; /* just for cleanup */
L1 += m;
cblas_drot(n - (i + 2), L1 + i, m, L1 + i + 1,
m, c, s);
}
}
static inline void cholesky_delete_flt(int m, int n, float *L, int go_out)
{
float c, s;
/* delete row go_out */
float *L1 = L + (go_out * m);
int i;
for (i = go_out; i < n - 1; ++i) {
cblas_scopy (i + 2, L1 + m , 1, L1, 1);
L1 += m;
}
L1 = L + (go_out * m);
for (i=go_out; i < n - 1; ++i) {
cblas_srotg(L1 + i, L1 + i + 1, &c, &s);
if (L1[i] < 0) {
/* Diagonals cannot be negative */
L1[i] = fabsf(L1[i]);
c = -c;
s = -s;
}
L1[i+1] = 0.; /* just for cleanup */
L1 += m;
cblas_srot(n - (i + 2), L1 + i, m, L1 + i + 1,
m, c, s);
}
}
| {
"alphanum_fraction": 0.430471584,
"avg_line_length": 21.4805194805,
"ext": "h",
"hexsha": "6e20a2b003ed72af3c03d740b966b463b3078a0b",
"lang": "C",
"max_forks_count": 1228,
"max_forks_repo_forks_event_max_datetime": "2022-03-29T05:57:40.000Z",
"max_forks_repo_forks_event_min_datetime": "2017-07-18T09:03:13.000Z",
"max_forks_repo_head_hexsha": "8d7ace2b3b2a58fb33af225c2997106d9402aaf5",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "WangWenjun559/MITS",
"max_forks_repo_path": "summary/sumy/sklearn/utils/src/cholesky_delete.h",
"max_issues_count": 1978,
"max_issues_repo_head_hexsha": "8d7ace2b3b2a58fb33af225c2997106d9402aaf5",
"max_issues_repo_issues_event_max_datetime": "2022-03-31T14:28:43.000Z",
"max_issues_repo_issues_event_min_datetime": "2017-07-18T09:17:58.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "WangWenjun559/MITS",
"max_issues_repo_path": "summary/sumy/sklearn/utils/src/cholesky_delete.h",
"max_line_length": 75,
"max_stars_count": 6989,
"max_stars_repo_head_hexsha": "8d7ace2b3b2a58fb33af225c2997106d9402aaf5",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "WangWenjun559/MITS",
"max_stars_repo_path": "summary/sumy/sklearn/utils/src/cholesky_delete.h",
"max_stars_repo_stars_event_max_datetime": "2022-03-31T15:58:36.000Z",
"max_stars_repo_stars_event_min_datetime": "2017-07-18T06:23:18.000Z",
"num_tokens": 606,
"size": 1654
} |
/**
*
* @file core_zgetrf_reclap.c
*
* PLASMA core_blas kernel
* PLASMA is a software package provided by Univ. of Tennessee,
* Univ. of California Berkeley and Univ. of Colorado Denver
*
* @version 2.8.0
* @author Hatem Ltaief
* @author Mathieu Faverge
* @author Piotr Luszczek
* @date 2009-11-15
*
* @precisions normal z -> c d s
*
**/
#include <math.h>
#include <cblas.h>
#include <lapacke.h>
#include "common.h"
struct CORE_zgetrf_data_s {
volatile PLASMA_Complex64_t *CORE_zamax;
volatile int *CORE_zstep;
};
static inline void
CORE_zgetrf_reclap_update(CORE_zgetrf_data_t *data,
int M, int column, int n1, int n2,
PLASMA_Complex64_t *A, int LDA, int *IPIV,
int thidx, int thcnt);
static inline void
CORE_zgetrf_reclap_rec(CORE_zgetrf_data_t *data,
int M, int N,
PLASMA_Complex64_t *A, int LDA,
int *IPIV, int *info,
int thidx, int thcnt, int column);
/***************************************************************************//**
*
* @ingroup dplasma_cores_complex64
*
* CORE_zgetrf_reclap computes a LU factorization of a general M-by-N
* matrix A stored in CCRB layout using partial pivoting with row
* interchanges.
*
* The factorization has the form
*
* A = P * L * U
*
* where P is a permutation matrix, L is lower triangular with unit
* diagonal elements (lower trapezoidal if m > n), and U is upper
* triangular (upper trapezoidal if m < n).
*
* This is the recursive version of the algorithm applied on column
* major layout.
*
* WARNINGS:
* - The function CORE_zgetrf_reclap_init has to be called prior
* to any call to this function.
* - You cannot call this kernel on different matrices at the same
* time.
* - The matrix A cannot be more than one tile wide.
* - The number of threads calling this function has to be excatly
* the number defined by info[2] with each one of them a different
* index between 0 included and info[2] excluded.
*
*******************************************************************************
*
* @param[in] data
* Common data structure to all threads initialized by
* CORE_zgetrf_reclap_init() that contains information for thread
* synchronization and maximum reductions. All threads working on a
* given matrix A must provide the same data structure.
*
* @param[in] M
* The number of rows of the matrix A. M >= 0.
*
* @param[in] N
* The number of columns of the matrix A. N >= 0.
*
* @param[in,out] A
* On entry, the M-by-N matrix to be factorized.
* On exit, the factors L and U from the factorization
* A = P*L*U; the unit diagonal elements of L are not stored.
*
* @param[in] LDA
* The leading dimension of the array A. LDA >= max(1,M).
*
* @param[out] IPIV
* The pivot indices; for 1 <= i <= min(M,N), row i of the
* matrix was interchanged with row IPIV(i).
* 1 <= IPIV[i] <= M.
*
* @param[in,out] info
* Array of 3 integers
* - info[0], see returned value
* - info[1], is the thread index 0 <= info[0] < info[2]
* - info[2], on entry is the number of threads trying to
* participate to the factorization,
* on exit is the real number of threads used to
* perform the factorization.
* Info[2] threads, and exactly info[2], have to call this function
* to avoid dead lock.
*
*******************************************************************************
*
* @return
* \retval PLASMA_SUCCESS successful exit
* \retval -k, the k-th argument had an illegal value
* \retval k if U(k,k) is exactly zero. The factorization
* has been completed, but the factor U is exactly
* singular, and division by zero will occur if it is used
* to solve a system of equations.
*
*/
#if defined(PLASMA_HAVE_WEAK)
#pragma weak CORE_zgetrf_reclap = PCORE_zgetrf_reclap
#define CORE_zgetrf_reclap PCORE_zgetrf_reclap
#endif
int CORE_zgetrf_reclap(CORE_zgetrf_data_t *data,
int M, int N,
PLASMA_Complex64_t *A, int LDA,
int *IPIV, int *info)
{
int thidx = info[1];
int divmn = M / N;
int thcnt = min( info[2], ((divmn == 0) && (M != 0))? 1 : divmn );
int minMN = min(M, N);
info[0] = 0;
info[2] = thcnt;
if( M < 0 ) {
coreblas_error(1, "illegal value of M");
return -1;
}
if( N < 0 ) {
coreblas_error(2, "illegal value of N");
return -2;
}
if( LDA < max(1, M) ) {
coreblas_error(5, "illegal value of LDA");
return -5;
}
/*
* Quick return
*/
if ( (M == 0) || (N == 0) || (thidx >= thcnt) ){
return PLASMA_SUCCESS;
}
*info = 0;
CORE_zgetrf_reclap_rec( data, M, minMN, A, LDA, IPIV, info,
thidx, thcnt, 0 );
if ( N > minMN ) {
CORE_zgetrf_reclap_update(data, M, 0, minMN, N-minMN,
A, LDA, IPIV,
thidx, thcnt);
}
return info[0];
}
/*******************************************************************
* Additional routines
*/
static double sfmin = 0.;
CORE_zgetrf_data_t *
CORE_zgetrf_reclap_init(int nbthrd)
{
int i;
CORE_zgetrf_data_t *data;
data = (CORE_zgetrf_data_t*)malloc( nbthrd * (sizeof(PLASMA_Complex64_t)+sizeof(int))
+ 2 * sizeof(void*) );
data->CORE_zamax = (PLASMA_Complex64_t*)((char*)data + 2 * sizeof(void*));
data->CORE_zstep = (int*)((char*)data + 2 * sizeof(void*) + nbthrd * sizeof(PLASMA_Complex64_t));
for (i = 0; i < nbthrd; ++i) {
data->CORE_zamax[i] = 0.;
data->CORE_zstep[i] = -1;
}
if ( sfmin == 0. ) {
sfmin = LAPACKE_dlamch_work('S');
}
return data;
}
static inline void
psplit(int n, int pidx, int pcnt, int *poff_p, int *psiz_p)
{
int q = n / pcnt, r = n % pcnt;
if (pidx < r) {
q++;
*psiz_p = q;
*poff_p = pidx * q;
} else {
*psiz_p = q;
*poff_p = r * (q + 1) + (pidx - r) * q;
}
}
static inline void
CORE_zamax1_thread(CORE_zgetrf_data_t *data,
PLASMA_Complex64_t localamx,
int thidx, int thcnt, int *thwinner,
PLASMA_Complex64_t *globalamx,
int pividx, int *ipiv)
{
volatile PLASMA_Complex64_t *CORE_zamax = data->CORE_zamax;
volatile int *CORE_zstep = data->CORE_zstep;
if (thidx == 0) {
int i, j = 0;
PLASMA_Complex64_t curval = localamx, tmp;
double curamx = cabs(localamx);
/* make sure everybody filled in their value */
for (i = 1; i < thcnt; ++i) {
while (CORE_zstep[i] == -1) { /* wait for thread i to store its value */
}
}
/* better not fuse the loop above and below to make sure data is sync'd */
for (i = 1; i < thcnt; ++i) {
tmp = CORE_zamax[i];
if (cabs(tmp) > curamx) {
curamx = cabs(tmp);
curval = tmp;
j = i;
}
}
if (0 == j)
ipiv[0] = pividx;
/* make sure everybody knows the amax value */
for (i = 1; i < thcnt; ++i)
CORE_zamax[ i ] = curval;
CORE_zstep[0] = -j - 2; /* set the index of the winning thread */
*thwinner = j;
*globalamx = curval;
for (i = 1; i < thcnt; ++i)
CORE_zstep[i] = -3;
/* make sure everybody read the max value */
for (i = 1; i < thcnt; ++i) {
while (CORE_zstep[i] != -1) {
}
}
CORE_zstep[0] = -1;
} else {
CORE_zamax[thidx] = localamx;
CORE_zstep[thidx] = -2; /* announce to thread 0 that local amax was stored */
while (CORE_zstep[0] == -1) { /* wait for thread 0 to finish calculating the global amax */
}
while (CORE_zstep[thidx] != -3) { /* wait for thread 0 to store amax */
}
*thwinner = -CORE_zstep[0] - 2;
*globalamx = CORE_zamax[thidx]; /* read the amax from the location adjacent to the one in the above loop */
CORE_zstep[thidx] = -1; /* signal thread 0 that this thread is done reading */
if (thidx == *thwinner)
ipiv[0] = pividx;
while (CORE_zstep[0] != -1) { /* wait for thread 0 to finish */
}
}
}
static inline void
CORE_zbarrier_thread(CORE_zgetrf_data_t *data,
int thidx, int thcnt)
{
int idum1, idum2;
PLASMA_Complex64_t ddum2 = 0.;
/* it's probably faster to implement a dedicated barrier */
CORE_zamax1_thread( data, 1.0, thidx, thcnt, &idum1, &ddum2, 0, &idum2 );
}
static inline void
CORE_zlaswap1(int ncol, PLASMA_Complex64_t *a, int lda,
int idxStart, int idxMax, const int *piv)
{
int i, j;
PLASMA_Complex64_t tmp;
for (j = 0; j < ncol; ++j) {
for (i = idxStart; i < idxMax; ++i) {
tmp = a[j*lda + piv[i] - 1];
a[j*lda + piv[i] - 1] = a[i + j*lda];
a[i + j*lda] = tmp;
}
}
}
static inline void
CORE_zgetrf_reclap_update(CORE_zgetrf_data_t *data,
int M, int column, int n1, int n2,
PLASMA_Complex64_t *A, int LDA, int *IPIV,
int thidx, int thcnt)
{
static PLASMA_Complex64_t posone = 1.0;
static PLASMA_Complex64_t negone = -1.0;
PLASMA_Complex64_t *Atop = A + column*LDA;
PLASMA_Complex64_t *Atop2 = Atop + n1 *LDA;
int coff, ccnt, lm, loff;
CORE_zbarrier_thread( data, thidx, thcnt );
psplit( n2, thidx, thcnt, &coff, &ccnt );
if (ccnt > 0) {
CORE_zlaswap1( ccnt, Atop2 + coff*LDA, LDA, column, n1 + column, IPIV ); /* swap to the right */
cblas_ztrsm( CblasColMajor, CblasLeft, CblasLower, CblasNoTrans, CblasUnit,
n1, ccnt, CBLAS_SADDR(posone), Atop + column, LDA, Atop2 + coff*LDA + column, LDA );
}
/* __sync_synchronize(); */ /* hopefully we will not need memory fences */
/* need to wait for pivoting and triangular solve to finish */
CORE_zbarrier_thread( data, thidx, thcnt );
psplit( M, thidx, thcnt, &loff, &lm );
if (thidx == 0) {
loff = column + n1;
lm -= column + n1;
};
cblas_zgemm( CblasColMajor, CblasNoTrans, CblasNoTrans, lm, n2, n1,
CBLAS_SADDR(negone), Atop+loff, LDA, Atop2 + column, LDA, CBLAS_SADDR(posone), Atop2+loff, LDA );
}
static void
CORE_zgetrf_reclap_rec(CORE_zgetrf_data_t *data, int M, int N,
PLASMA_Complex64_t *A, int LDA,
int *IPIV, int *info,
int thidx, int thcnt, int column)
{
int jp, n1, n2, lm, loff;
PLASMA_Complex64_t tmp1, tmp2, tmp3;
PLASMA_Complex64_t *Atop = A + column*LDA;
/* Assumption: N = min( M, N ); */
if (N > 1) {
int coff, ccnt;
n1 = N / 2;
n2 = N - n1;
CORE_zgetrf_reclap_rec( data, M, n1, A, LDA, IPIV, info,
thidx, thcnt, column );
if ( *info != 0 )
return;
CORE_zgetrf_reclap_update(data, M, column, n1, n2,
A, LDA, IPIV,
thidx, thcnt);
CORE_zgetrf_reclap_rec( data, M, n2, A, LDA, IPIV, info,
thidx, thcnt, column + n1 );
if ( *info != 0 )
return;
psplit( n1, thidx, thcnt, &coff, &ccnt );
if (ccnt > 0) {
CORE_zlaswap1( ccnt, Atop+coff*LDA, LDA, n1 + column, N + column, IPIV ); /* swap to the left */
}
} else {
int thrd;
CORE_zbarrier_thread( data, thidx, thcnt );
psplit( M, thidx, thcnt, &loff, &lm );
if (thidx == 0) {
loff = column;
lm -= column;
}
tmp2 = Atop[column]; /* all threads read the pivot element in case they need it */
jp = cblas_izamax( lm, Atop + loff, 1 );
tmp1 = Atop[loff + jp];
CORE_zamax1_thread( data, tmp1, thidx, thcnt, &thrd,
&tmp3, loff + jp + 1, IPIV + column );
Atop[column] = tmp3; /* all threads set the pivot element: no need for synchronization */
if ( tmp3 != 0.0 ) {
if ( cabs(tmp3) >= sfmin ) {
PLASMA_Complex64_t tmp = (PLASMA_Complex64_t)1.0 / tmp3;
n1 = (thidx == 0) ? 1 : 0;
cblas_zscal( lm - n1, CBLAS_SADDR(tmp), Atop + loff + n1, 1 );
} else {
int i;
PLASMA_Complex64_t *Atop2;
n1 = (thidx == 0) ? 1 : 0;
Atop2 = Atop + loff + n1;
for( i=0; i < lm-n1; i++, Atop2++)
*Atop2 = *Atop2 / tmp3;
}
if (thrd == thidx) { /* the thread that owns the best pivot */
if (loff + jp != column) /* if there is a need to exchange the pivot */
Atop[loff + jp] = tmp2 / tmp3;
}
} else {
*info = column + 1;
return;
}
CORE_zbarrier_thread( data, thidx, thcnt );
}
}
| {
"alphanum_fraction": 0.5226373626,
"avg_line_length": 31.4516129032,
"ext": "c",
"hexsha": "8883762f5ec0b1e8f16507e543602ecd81e943e6",
"lang": "C",
"max_forks_count": 5,
"max_forks_repo_forks_event_max_datetime": "2022-03-30T01:53:32.000Z",
"max_forks_repo_forks_event_min_datetime": "2022-02-28T21:24:37.000Z",
"max_forks_repo_head_hexsha": "fa687f0ceec07f03249217b93e8a707aa9fd8ef3",
"max_forks_repo_licenses": [
"BSD-3-Clause-Open-MPI"
],
"max_forks_repo_name": "therault/dplasma",
"max_forks_repo_path": "src/cores/core_zgetrf_reclap.c",
"max_issues_count": 5,
"max_issues_repo_head_hexsha": "fa687f0ceec07f03249217b93e8a707aa9fd8ef3",
"max_issues_repo_issues_event_max_datetime": "2022-03-21T15:22:21.000Z",
"max_issues_repo_issues_event_min_datetime": "2022-03-02T21:42:26.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause-Open-MPI"
],
"max_issues_repo_name": "therault/dplasma",
"max_issues_repo_path": "src/cores/core_zgetrf_reclap.c",
"max_line_length": 119,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "fa687f0ceec07f03249217b93e8a707aa9fd8ef3",
"max_stars_repo_licenses": [
"BSD-3-Clause-Open-MPI"
],
"max_stars_repo_name": "therault/dplasma",
"max_stars_repo_path": "src/cores/core_zgetrf_reclap.c",
"max_stars_repo_stars_event_max_datetime": "2022-03-17T19:36:41.000Z",
"max_stars_repo_stars_event_min_datetime": "2022-03-17T19:36:41.000Z",
"num_tokens": 4061,
"size": 13650
} |
#ifndef COMPUTE_SIGNAL_H
#define COMPUTE_SIGNAL_H
#include <gsl/gsl_rng.h>
#include <gsl/gsl_histogram.h>
void compute_signal(double * signal, const size_t length, const double delta,
gsl_rng * r, gsl_histogram * hist);
#endif
| {
"alphanum_fraction": 0.764957265,
"avg_line_length": 21.2727272727,
"ext": "h",
"hexsha": "2de39cc48d2fdcad30f91b02e295f4573d1fddb6",
"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": "6204ac9d212fd6c73751d215c49e95373b573430",
"max_forks_repo_licenses": [
"Unlicense"
],
"max_forks_repo_name": "JuliusRuseckas/numerical-sde-variable-step",
"max_forks_repo_path": "compute_signal.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "6204ac9d212fd6c73751d215c49e95373b573430",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"Unlicense"
],
"max_issues_repo_name": "JuliusRuseckas/numerical-sde-variable-step",
"max_issues_repo_path": "compute_signal.h",
"max_line_length": 77,
"max_stars_count": 2,
"max_stars_repo_head_hexsha": "6204ac9d212fd6c73751d215c49e95373b573430",
"max_stars_repo_licenses": [
"Unlicense"
],
"max_stars_repo_name": "JuliusRuseckas/numerical-sde-variable-step",
"max_stars_repo_path": "compute_signal.h",
"max_stars_repo_stars_event_max_datetime": "2022-03-25T07:04:28.000Z",
"max_stars_repo_stars_event_min_datetime": "2017-03-28T09:12:48.000Z",
"num_tokens": 59,
"size": 234
} |
// Data Structure and Routines for peak fiting
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_blas.h>
#include <gsl/gsl_multifit_nlin.h>
#include <errno.h>
#include "grid.h"
#include "grid_operations.h"
#include "minmax.h"
#include "point.h"
#ifndef _FITTOFUNCTION_H_
#define _FITTOFUNCTION_H_
typedef struct {
size_t n;
double * y;
} ObservedValues ;
void fitToFunctionLorentz(Grid *image, double *fitx, double *fity,
double *background, double *intens,
double *widthx, double *widthy, double *tilt,double *chisq);
void fitToFunctionGauss(Grid *image, double *fitx, double *fity,
double *background, double *intens,
double *widthx, double *widthy, double *tilt,double *chisq);
#endif
| {
"alphanum_fraction": 0.7232250301,
"avg_line_length": 22.4594594595,
"ext": "h",
"hexsha": "9631c18c10ea512a572a4ebdbef6310924d57942",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2022-01-21T17:48:28.000Z",
"max_forks_repo_forks_event_min_datetime": "2022-01-21T17:48:28.000Z",
"max_forks_repo_head_hexsha": "2738e6e9ccfd13007ac4fd987bf1a75656d358bd",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "carterbox/cold",
"max_forks_repo_path": "legacy/peaksearch/include/fitToFunction.h",
"max_issues_count": 6,
"max_issues_repo_head_hexsha": "2738e6e9ccfd13007ac4fd987bf1a75656d358bd",
"max_issues_repo_issues_event_max_datetime": "2022-03-31T10:34:20.000Z",
"max_issues_repo_issues_event_min_datetime": "2022-01-21T17:14:55.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "carterbox/cold",
"max_issues_repo_path": "legacy/peaksearch/include/fitToFunction.h",
"max_line_length": 67,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "2738e6e9ccfd13007ac4fd987bf1a75656d358bd",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "carterbox/cold",
"max_stars_repo_path": "legacy/peaksearch/include/fitToFunction.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 244,
"size": 831
} |
/*
learn.h
*/
#ifndef LEARN_H
#define LEARN_H
#include <stdlib.h>
#include <gsl/gsl_rng.h>
#include "feature.h"
//#define RANDOM ((double)rand()/(double)RAND_MAX)
int sampling_multinomial(gsl_rng *r, double *p, double *cum_sum_p, int len_p);
extern void mvslda_learn(document *data,
double **resp,
double *alpha,
double beta,
double nu2, double sigma2,
int nclass, int nlex, int dlenmax, int nresp,
int maxiter,
double **phi, double **theta, double **eta,
int **n_mz, int **n_zw,
FILE *likp, FILE *hyperp,
unsigned long int random_seed);
#endif
| {
"alphanum_fraction": 0.6287519747,
"avg_line_length": 23.4444444444,
"ext": "h",
"hexsha": "2cccbda38880dc853ee21aff27de172b653c54ee",
"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": "b3db46a01a5561b92c64c7662571f26a6aa9eb6d",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "khigashi1987/mvsLDA",
"max_forks_repo_path": "src/learn.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "b3db46a01a5561b92c64c7662571f26a6aa9eb6d",
"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": "khigashi1987/mvsLDA",
"max_issues_repo_path": "src/learn.h",
"max_line_length": 78,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "b3db46a01a5561b92c64c7662571f26a6aa9eb6d",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "khigashi1987/mvsLDA",
"max_stars_repo_path": "src/learn.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 176,
"size": 633
} |
#include <stdio.h>
#include <math.h>
#include <unistd.h> /* for getopt */
#include <string.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_odeiv2.h>
#include "defaults.h"
#include "h2ocalc.h"
//#include"h2ocalc_test.h"
/* gcc h2ocalc.c -o h2ocalc -lgsl -lgslcblas -lm -Wall */
/* struct ODE_param{ */
/* int a[NEQ]; /\* dont worry let just run with global vars for now *\/ */
/* float b[NEQ]; */
/* }; */
int nbprint(double x, double y[], int n) {
int i;
double sum = 0;
printf("%6.4f ", x);
for (i = 0; i < n; i++) {
printf("%6.2f ", y[i]);
sum += y[i];
}
printf(" %6.2f\n",sum);
return 0;
}
int nbeprint(double x, double y[], int n) {
int i;
double sum = 0;
printf("%6.4e ",x);
for (i = 0; i < n; i++) {
printf("%6.2e ", y[i]);
sum += y[i];
}
printf(" %6.2e\n", sum);
return 0;
}
int func (double t, const double y[],double f[], void *params) {
// struct ODE_param *p = (struct ODE_params *) params;
int i,j,k;
double rate[NEQ];
//printf("func\n");
/* for each species ... */
for (k = 0; k < NSPECIES; k++) {
//printf("SPECIES %i\n",k);
f[k] = 0;
/* ...find all contributing and removing things */
for (j = 0; j < NEQ; j++) {
if (nmatrix[j][k] != 0) {
rate[j] = nmatrix [j][k]; /* build the final equation */
//printf("%3i ",nmatrix[j][k]);
/* add generate I equations */
rate[j] *= rconst[j]; /* get rate for reaction I_j */
//printf(" * k%i ",j);
for (i = 0; i < NSPECIES; i++) {
if (nmatrix[j][i] == -1 ) {
rate[j] *= y[i]; /* first order kinetics */
//printf("* y[%i] ",i);
}
if (nmatrix[j][i] == -2 ) {
rate[j] *= y[i]*y[i]; // second order kinetics
//printf("* y[%i]^2 ",i);
}
}
f[k] += rate[j];
//printf(" + \n");
}
}
//printf(" ---- k f[k]: %i %e ---- \n",k,f[k]);
// nbeprint(t,y,NSPECIES);
// if (k ==8)
// exit(0);
}
//nbeprint(t,y,NSPECIES);
//nbeprint(t,f,NSPECIES);
/* add function for radiation, assumed in last bin */
//f[NEQ-1] = 0;
return GSL_SUCCESS;
}
int main(int argc, char **argv) {
// struct ODE_param *p = (struct ODE_params *) params;
double dummy_param = 0;
gsl_odeiv2_system sys = {func, NULL, NSPECIES, &dummy_param};
gsl_odeiv2_driver *d = gsl_odeiv2_driver_alloc_y_new(&sys,
gsl_odeiv2_step_rk8pd,
1e-6,
1e-6,
0.0);
int i,j,status;
double t = NSTART;
// double t1 = NSTOP;
//double foobar; /* trash parameter */
double ti;
double y[NSPECIES];
double freq = FREQ;
double doser = DOSER;
double simtime = SIMTIME;
double resol = RESOL;
double period = 0;
double dpulse = 0;
double tick = 0;
double ta = 1e-3; /* plotting clocks*/
int pulse_left = 0;
int pulse_counter = 0;
signed long int tick_counter = 0;
char *fname;
int c;
int flagp = 0, flagl = 0, flagc = 1; /* default: print each tick */
/* parse options */
opterr = 0;
while ((c = getopt(argc, argv, "f:d:o:r:t:")) != -1) {
switch(c) {
case 'l':
flagl = 1;
flagp = 0;
flagc = 0;
break;
case 'p':
flagl = 0;
flagp = 1;
flagc = 0;
break;
case 'c':
flagl = 0;
flagp = 0;
flagc = 1;
break;
case 'f':
sscanf(optarg, "%lf", &freq);
break;
case 'd':
sscanf(optarg, "%lf", &doser);
break;
case 'o':
fname = optarg; /* not implemented */
break;
case 'r':
sscanf(optarg, "%lf", &resol);
break;
case 't':
sscanf(optarg, "%lf", &simtime);
break;
case '?':
printf("Options:\n");
printf(" -p output per pulse\n");
printf(" -c output per tick\n");
printf(" -l only end of output\n");
printf(" -f frequency [Hz]\n");
printf(" -d dose rate [Gy/min]\n");
printf(" -o output file\n");
printf(" -r tick resolution [sec]\n");
printf(" -t simulation time [sec]\n");
printf("\n");
exit(0);
break;
default:
printf ("?? no handle ?? %i\n", c);
exit(-1);
}
}
period = 1 / freq;
dpulse = (doser / 60.0) / freq * EVJ; // in eV per pulse per liter
if (period < resol) {
printf(" *** Error: ");
printf("Period must be larger than tick resolution.\n");
exit(-1);
}
/* find ticksize closest to the requested one */
tick = period/(round(period/ resol));
/* number of pulses to be simulated */
pulse_left = (int) ((simtime-RSTART) * freq);
/* print a header */
printf("# Frequency : %.3e Hz \n", freq);
printf("# Period : %.3e sec\n", period);
printf("#\n");
printf("# Tick size : %.3e sec\n", tick);
printf("# Time for sim : %.3e sec\n", simtime);
printf("#\n");
printf("# Dose rate : %.3e Gy/min\n", doser );
printf("# Pulse size : %.3e eV/l/pulse\n", dpulse );
printf("# Pulse count : %i pulses\n", pulse_left);
printf("#\n");
printf("# Total delivered dose for this simulation\n");
printf("# : %.6e Gy \n", pulse_left * dpulse / EVJ);
printf("#\n");
/* copy start conditions into working array */
for (i = 0; i < NSPECIES; i++)
y[i] = ystart[i];
/* Print first line with starting conditions. */
nbeprint(t, y, NSPECIES);
/* loop over all pulses */
while (pulse_left != 0) {
/* check if we are at a pulse time step */
if (t >= ((pulse_counter * period) + RSTART)) {
if (flagp) /* print per pulse (pre pulse) */
nbeprint(t, y, NSPECIES);
printf("# Pulse! %i \n", pulse_left);
for (j=0; j < NSPECIES; j++)
y[j] += dpulse * gval[j] * 0.01 / NA;
pulse_left--;
pulse_counter++;
}
tick_counter++;
ti = tick_counter * tick;
status = gsl_odeiv2_driver_apply(d, &t, ti, y);
if (status != GSL_SUCCESS) {
printf("error, return value = %d\n", status);
break;
}
if (flagc) /* print per tick */
nbeprint(t, y, NSPECIES);
} /* end pulses left iterator */
if (flagl) /* print last */
nbeprint(t, y, NSPECIES);
gsl_odeiv2_driver_free(d);
return 0;
}
| {
"alphanum_fraction": 0.4488722845,
"avg_line_length": 26.7666666667,
"ext": "c",
"hexsha": "59e6eeba0ada657c0b880bba90f7f1c90bcaa09e",
"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": "3353241cce578ac5b25076c5db27044517f5c457",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "nbassler/simwater",
"max_forks_repo_path": "src/h2ocalc.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "3353241cce578ac5b25076c5db27044517f5c457",
"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": "nbassler/simwater",
"max_issues_repo_path": "src/h2ocalc.c",
"max_line_length": 79,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "3353241cce578ac5b25076c5db27044517f5c457",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "nbassler/simwater",
"max_stars_repo_path": "src/h2ocalc.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 2018,
"size": 7227
} |
#ifndef libCV_ellipse
#define libCV_ellipse
#include <objc/Object.h>
#include "cvtypes.h"
#include "util.h"
#include "Array.h"
#include "math.h"
#include <gsl/gsl_math.h>
#include <gsl/gsl_linalg.h>
#include <gsl/gsl_blas.h>
#include <gsl/gsl_eigen.h>
@interface Ellipse : Object {
f64 x_axis;
f64 y_axis;
f64 x_center;
f64 y_center;
f64 rotation;
f64 general[6];
f64 bounds[4];
}
+(id) newAtX:(f64)xc andY:(f64)yc withXAxis:(f64)xa andYAxis:(f64)ya rotatedBy:(f64)phi;
+(id) newWithA:(f64)a b:(f64)b c:(f64)c d:(f64)d e:(f64)e f:(f64)f;
+(id) newFromPoints:(ArrayP)points;
-(void) drawInArray:(ArrayP)array;
-(void) toGeneralConic;
-(void) toGeneralEllipse;
-(void) findBounds;
// Get and set general ellipse parameters
-(f64) x_axis;
-(f64) y_axis;
-(f64) major_axis;
-(f64) minor_axis;
-(f64) rotation;
-(f64) majorRotation;
-(f64) minorRotation;
-(f64) x_center;
-(f64) y_center;
-(void) setX_axis:(f64)newx;
-(void) setY_axis:(f64)newy;
-(void) setX_center:(f64)newx;
-(void) setY_center:(f64)newy;
-(void) setRotation:(f64)newr;
-(void) setX_axis:(f64)xa y_axis:(f64)ya x_center:(f64)xc y_center:(f64)yc rotation:(f64)r;
// Get and set general conic parameters
-(f64) A;
-(f64) B;
-(f64) C;
-(f64) D;
-(f64) E;
-(f64) F;
-(f64 *) general;
-(void) setA:(f64)A;
-(void) setB:(f64)B;
-(void) setC:(f64)C;
-(void) setD:(f64)D;
-(void) setE:(f64)E;
-(void) setF:(f64)F;
-(void) setGeneralA:(f64)A B:(f64)B C:(f64)C D:(f64)D E:(f64)E F:(f64)F;
-(void) printInfoTo:(FILE *)fp;
-(u08) isValid;
-(id) free;
@end
enum ellipseindices {
AX,
BX,
CX,
DX,
EX,
FX,
};
enum ellipsebounds {
XHI,
XLO,
YHI,
YLO,
};
typedef Ellipse * EllipseP;
void originCenteredLSQEllipse( f64 x_values[], f64 y_values[], u64 number_of_points, f64 ellipse[] );
void generateBoundEllipses( f64 e[], f64 b1[], f64 b2[], f64 treshold );
f64 ellipseCircumference( f64 e[] );
EllipseP ellipseRANSAC( ArrayP edges, f64 fit_treshold, f64 min_percent_inliers, f64 certainty_probability, u64 max_iterations );
#endif
| {
"alphanum_fraction": 0.68,
"avg_line_length": 18.75,
"ext": "h",
"hexsha": "ead855260ec2c6946884f0abd7086eb3f080c88e",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2019-09-05T20:58:37.000Z",
"max_forks_repo_forks_event_min_datetime": "2019-09-05T20:58:37.000Z",
"max_forks_repo_head_hexsha": "974b8a48245222de0d9cfb0f433533487ecce60d",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "leschzinerlab/myami-3.2-freeHand",
"max_forks_repo_path": "programs/ace2/Ellipse.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "974b8a48245222de0d9cfb0f433533487ecce60d",
"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": "leschzinerlab/myami-3.2-freeHand",
"max_issues_repo_path": "programs/ace2/Ellipse.h",
"max_line_length": 129,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "974b8a48245222de0d9cfb0f433533487ecce60d",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "leschzinerlab/myami-3.2-freeHand",
"max_stars_repo_path": "programs/ace2/Ellipse.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 749,
"size": 2025
} |
// Copyright (c) 2021 Stig Rune Sellevag
//
// This file is distributed under the MIT License. See the accompanying file
// LICENSE.txt or http://www.opensource.org/licenses/mit-license.php for terms
// and conditions.
#ifndef SCILIB_LINALG_LAPACK_TYPES_H
#define SCILIB_LINALG_LAPACK_TYPES_H
//------------------------------------------------------------------------------
// Define integer type for use with BLAS, LAPACK and Intel MKL.
#ifdef USE_MKL
#include <mkl.h>
#define BLAS_INT MKL_INT
#else
#include <cblas.h>
#ifdef blasint
#define BLAS_INT blasint
#else
#define BLAS_INT int
#endif
#endif
//------------------------------------------------------------------------------
// Define complex type for use with LAPACK.
#ifndef USE_MKL
#include <complex>
#define lapack_complex_float std::complex<float>
#define lapack_complex_double std::complex<double>
#endif
#endif // SCILIB_LINALG_LAPACK_TYPES_H
| {
"alphanum_fraction": 0.6440306681,
"avg_line_length": 26.0857142857,
"ext": "h",
"hexsha": "6b6cd5f894d1170839dbb4b5d6599c9d6acfe43b",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "c49f1f882bf2031a4de537e0f5701b2648af181f",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "stigrs/scilib",
"max_forks_repo_path": "include/scilib/linalg_impl/lapack_types.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "c49f1f882bf2031a4de537e0f5701b2648af181f",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "stigrs/scilib",
"max_issues_repo_path": "include/scilib/linalg_impl/lapack_types.h",
"max_line_length": 80,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "c49f1f882bf2031a4de537e0f5701b2648af181f",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "stigrs/scilib",
"max_stars_repo_path": "include/scilib/linalg_impl/lapack_types.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 201,
"size": 913
} |
/**
*/
#include <time.h>
#include <math.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_sort_vector.h>
#include <gsl/gsl_interp.h>
#include <gsl/gsl_sort_double.h>
#include "inout_aper.h"
#include "aXe_grism.h"
#include "spce_sect.h"
#include "spc_back.h"
#include "spce_PET.h"
#include "spc_wl_calib.h"
#include "aXe_errors.h"
#include "fringe_conf.h"
#include "spc_resp.h"
#include "spce_pathlength.h"
#include "aper_conf.h"
#include "specmodel_utils.h"
#include "model_utils.h"
#include "spc_fluxcube.h"
#include "fringe_conf.h"
#include "dirimage_model.h"
#define MAX(x,y) (((x)>(y))?(x):(y))
#define MIN(x,y) (((x)<(y))?(x):(y))
#define SQR(x) ((x)*(x))
int
compute_dirimage_model(char dirim_file[], char conf_file[], char tpass_file[],
char specmod_file[], char objmod_file[], char aper_file[],
const double model_scale, const double tel_area, const double lambda_psf,
observation *obs, char map_file[])
{
object **oblist;
dirobject **dirlist;
spectral_models *spec_mod;
object_models *obj_mod;
interpolator *tpass;
gsl_matrix *dirimage_matrix=NULL;
px_point npixels;
// load the object list
fprintf (stdout, "aXe_DIRIMAGE: Loading object aperture list...");
oblist = file_to_object_list_seq (aper_file, obs);
fprintf (stdout,"%d objects loaded.\n",object_list_size(oblist));
// check whether highres models
// are given
if (strlen(specmod_file) > 0)
// load the spectral models
spec_mod = load_spectral_models(specmod_file);
else
// or set the struct to NULL
spec_mod = NULL;
// check whether direct emission models
// are given
if (strlen(objmod_file) > 0)
obj_mod = load_object_models(objmod_file);
else
obj_mod = NULL;
// get the sensitivity curve of the total passband
tpass = get_filter_sensitivity(tpass_file, tel_area);
// get the image dimensions
npixels = get_npixel(obs);
// create the list of direct objects to be simulated
// the interpolation type is fixed to linear
dirlist = oblist_to_dirlist2(dirim_file, conf_file, npixels, oblist,
spec_mod, obj_mod, model_scale, 1);
// determine the XOFF and YOFF values
// for the various beams
fill_xy_offsets(dirlist, conf_file);
// create and fill the pixel matrix for the direct images
dirimage_matrix = make_dirimage(oblist, dirlist, npixels, lambda_psf, tpass);
// store the contamination image
gsl_to_FITSimage (dirimage_matrix, map_file, 1, NULL);
// check if memory must be released;
// do it if necessary
if (spec_mod != NULL)
free_spectral_models(spec_mod);
if (obj_mod != NULL)
free_object_models(obj_mod);
if (oblist !=NULL)
free_oblist (oblist);
// always release these
// objects
free_dirlist(dirlist);
gsl_matrix_free(dirimage_matrix);
free_interp(tpass);
// return always '1'
return 1;
}
gsl_matrix *
make_dirimage(object **oblist, dirobject **dirlist, const px_point npixels,
const double lambda_psf, interpolator *tpass)
{
dirobject *actdir;
beam actbeam;
gsl_matrix *dirimage_matrix;
double cps = 0.0;
double sval = 0.0;
double value = 0.0;
int ii=0;
int nx=0;
int ny=0;
d_point dpixel;
// allocate memory for the image matrix
dirimage_matrix = gsl_matrix_alloc(npixels.x, npixels.y);
gsl_matrix_set_all(dirimage_matrix,0.0);
// go over each beam model
ii = 0;
while (oblist[ii] != NULL)
{
// get the direct object for the actual model spectrum
actdir = get_dirobject_from_list(dirlist, oblist[ii]->ID);
// get the beam for the actual model spectrum
actbeam = oblist[ii]->beams[0];
// report onto the screen
fprintf(stdout, "aXe_DIRIMAGE: modelling object %i ...", oblist[ii]->ID);
// get the integrated direct image intensity in cps
cps = get_cps_for_dirobject(tpass, actdir);
// correct the direct image positions for
// the offset values introduced by building
// the direct image objects around the reference
// position, which is shifted from the true
// direct image position by XOFF and YOFF as
// given in the aXe configuration file
actdir->ix_min -= (int)floor(actdir->xy_off[actbeam.ID].x + 0.5);
actdir->ix_max -= (int)floor(actdir->xy_off[actbeam.ID].x + 0.5);
actdir->iy_min -= (int)floor(actdir->xy_off[actbeam.ID].y + 0.5);
actdir->iy_max -= (int)floor(actdir->xy_off[actbeam.ID].y + 0.5);
actbeam.refpoint.x -= actdir->xy_off[actbeam.ID].x;
actbeam.refpoint.y -= actdir->xy_off[actbeam.ID].y;
// go over each pixel in the direct object area
for (nx=actdir->ix_min; nx<=actdir->ix_max; nx++)
{
// make sure to be inside the image
if (nx < 0 || nx >= (int)dirimage_matrix->size1)
// skip column if not
continue;
for (ny=actdir->iy_min; ny<=actdir->iy_max; ny++)
{
// make sure to be inside the image
if (ny < 0 || ny >= (int)dirimage_matrix->size2)
// skip element if not
continue;
// fill the dpixel structure
dpixel.x = (double)nx;
dpixel.y = (double)ny;
// check whether there is
// an image template
if (actdir->dirim)
// get the pixel intensity from the image template
sval = get_diremission_value(actdir->dirim, dpixel.x - actbeam.refpoint.x, dpixel.y - actbeam.refpoint.y);
else
// get the Gaussian pixel intensity;
//
// do a subsampling over the pixel
// to get a more appropriate value for the
// emission val
sval = get_sub_emodel_value(dpixel, actbeam, actdir->drzscale);
// compute and set the new pixel values
value = gsl_matrix_get(dirimage_matrix, nx, ny) + sval*cps;
gsl_matrix_set(dirimage_matrix, nx, ny, value);
}
}
// release the space for the various structures
fprintf(stdout, " Done\n");
ii++;
}
// return the image matrix
return dirimage_matrix;
}
double
get_cps_for_dirobject(interpolator *tpass, dirobject *actdir)
{
interpolator *combine;
double cps=0.0;
// create aa new multiplicator
// interpolator
combine = combine_tpass_SED(tpass, actdir);
// integrate over the interpolator
cps = integrate_interpolator(combine);
// release memory
free_interp(combine);
// return the cps value
return cps;
}
double
integrate_interpolator(interpolator *combine)
{
double integral=0.0;
int index;
for (index=1; index < combine->nvals-1; index++)
// add the increment
integral += combine->yvals[index] * (combine->xvals[index+1] - combine->xvals[index-1]);
// dont forget the start and end piece
integral += combine->yvals[0] * (combine->xvals[1] - combine->xvals[0]);
integral += combine->yvals[combine->nvals-1] * (combine->xvals[combine->nvals-1] - combine->xvals[combine->nvals-2]);
// then return the half
return integral/2.0;
}
interpolator *
combine_tpass_SED(interpolator *tpass, dirobject *actdir)
{
interpolator *combine;
int index=0;
int n_additional=0;
int act_index;
gsl_vector *indep_data;
// go over all SED data points
for (index = 0; index < actdir->SED->npoints; index++)
{
// transform to Angstrom
actdir->SED->wavelength[index] *= 10.0;
// check whether the independent data point
// falls in the area of the sensitivity
if (actdir->SED->wavelength[index] < tpass->xmax
&& actdir->SED->wavelength[index] > tpass->xmin)
// enhance the number
// of additional data points
n_additional += 1;
}
// allocate memory for the new independent value list
indep_data = gsl_vector_alloc(tpass->nvals + n_additional);
// go over all sensitivity data points and fill in
// the independent values
for (index = 0; index < tpass->nvals; index++)
gsl_vector_set(indep_data, index, tpass->xvals[index]);
// set the counter to the next free index
act_index = tpass->nvals;
// go over all SED data points
for (index = 0; index < actdir->SED->npoints; index++)
// check whether the independent data point
// falls in the area of the sensitivity
if (actdir->SED->wavelength[index] < tpass->xmax
&& actdir->SED->wavelength[index] > tpass->xmin)
{
// fill in the additional independent data point
// from the SED
gsl_vector_set(indep_data, act_index, actdir->SED->wavelength[index]);
// enhance the counter
act_index += 1;
}
// sort the vector
gsl_sort_vector(indep_data);
// compose a new interpolator from the independent values
combine = get_combined_tpass_SED(indep_data, tpass, actdir);
// release memory in the weight vector
gsl_vector_free(indep_data);
// go over all SED data points
for (index = 0; index < actdir->SED->npoints; index++)
// transform to nm
actdir->SED->wavelength[index] /= 10.0;
// return the interpolator
return combine;
}
interpolator *
get_combined_tpass_SED(gsl_vector *indep_data, interpolator *tpass, dirobject *actdir)
{
interpolator *combine;
gsl_vector_int *indep_weight;
int n_new=0;
int index;
int act_index;
double *xvals_new;
double *yvals_new;
// allocat memory for the weight vector
indep_weight = gsl_vector_int_alloc(indep_data->size);
// set all the weights
gsl_vector_int_set_all(indep_weight, 1);
// go over the independent data
for (index = 1; index < (int)indep_data->size; index++)
// check whether the current entry is equal the previous one
if (gsl_vector_get(indep_data, index) == gsl_vector_get(indep_data, index-1))
// set the weight of the current entry to zero
gsl_vector_int_set(indep_weight,index, 0);
// initialize the
// final number
n_new = 0;
// go over the weight array
for (index=0; index < (int)indep_weight->size; index++)
// just count the weights
n_new += gsl_vector_int_get(indep_weight, index);
// allocate memory for the interpolator data
xvals_new = (double *)malloc(n_new * sizeof(double));
yvals_new = (double *)malloc(n_new * sizeof(double));
// go over the weight array
act_index=0;
for (index=0; index < (int)indep_weight->size; index++)
// check for weight
if (gsl_vector_int_get(indep_weight, index))
{
// take the independent value from the vector
xvals_new[act_index] = gsl_vector_get(indep_data, index);
// compute the new dependent value bye multiplying
// the brightness with the sensitivity
yvals_new[act_index] = eval_interp(tpass, xvals_new[act_index])
* get_flux_from_SED(actdir->SED, xvals_new[act_index]);
// enhance the counter
act_index++;
}
// create a new interpolator
combine = create_interp(n_new, TPASS_INTERP_TYPE, xvals_new, yvals_new);
// release memory in the weight vector
gsl_vector_int_free(indep_weight);
// return the interpolator
return combine;
}
/*
* Function: get_filter_sensitivity
* The function reads in a total passband file from fits format
* and stroes the data as an interpolation function. The dependent
* data values are transformed from throughput to sensitivity,
* and the interpolation function is returned.
*
* Parameters:
* @param tpass_file - the full name of the total passband
* @param tel_are - the collecting area of the telescope
*
* Returns:
* @return tpass - the filter sensitivity
*/
interpolator *
get_filter_sensitivity(const char tpass_file[], const double tel_area)
{
interpolator *tpass;
double h_erg = 6.6260693E-27;
double c_cm = 2.99792458E+10;
double factor = 0.0;
int index=0;
fprintf(stdout, "Load Total bandpass table :%s\n", tpass_file);
tpass = create_interp_ftable(tpass_file, 2,"WAVELENGTH","THROUGHPUT", TPASS_INTERP_TYPE);
for (index=0; index < tpass->nvals; index++)
{
// compute the conversion factor
factor = tel_area / (h_erg * c_cm / (1.0E-08 * tpass->xvals[index]));
// apply the conversion factor
tpass->yvals[index] = tpass->yvals[index] * factor;
}
// return the filter sensitivity
return tpass;
}
| {
"alphanum_fraction": 0.6797450542,
"avg_line_length": 27.7087155963,
"ext": "c",
"hexsha": "99c2c3a04edd345cbafbb91068d5b1cbb3ea2533",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "sosey/pyaxe",
"max_forks_repo_path": "cextern/src/dirimage_model.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "sosey/pyaxe",
"max_issues_repo_path": "cextern/src/dirimage_model.c",
"max_line_length": 120,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "sosey/pyaxe",
"max_stars_repo_path": "cextern/src/dirimage_model.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 3389,
"size": 12081
} |
#pragma once
#include "datastructures/PointBuffer.h"
#include "io/PointsPersistence.h"
#include "math/AABB.h"
#include "point_source/PointSource.h"
#include "pointcloud/FileStats.h"
#include "pointcloud/PointAttributes.h"
#include "tiling/Sampling.h"
#include "util/Definitions.h"
#include "util/Transformation.h"
#include <reflection/StaticReflection.h>
#include <threading/Semaphore.h>
#include <threading/TaskSystem.h>
#include <atomic>
#include <deque>
#include <gsl/gsl>
#include <string>
#include <thread>
#include <taskflow/taskflow.hpp>
struct ProgressReporter;
struct TilingAlgorithmBase;
struct ThroughputSampler;
/**
* Which tiling strategy to use?
*/
enum class TilingStrategy
{
/**
* Use the accurate strategy that samples from the root node. This will be
* slower than the 'Fast' strategy, that skips the first couple of levels and
* reconstructs them afterwards
*/
Accurate,
/**
* Use the fast strategy that skips the first couple of levels and starts
* tiling deeper in the octree to enable increased parallelism. The skipped
* levels are reconstructed and thus contain duplicated data
*/
Fast
};
struct FixedThreadCount
{
uint32_t num_threads_for_reading;
uint32_t num_threads_for_indexing;
};
struct AdaptiveThreadCount
{
uint32_t num_threads;
};
/**
* Thread number configuration. Either a fixed number of read and index threads, or
* a total fixed number of threads that are scheduled adaptively
*/
using ThreadConfig = std::variant<FixedThreadCount, AdaptiveThreadCount>;
struct TilerMetaParameters
{
float spacing_at_root;
uint32_t max_depth;
size_t max_points_per_node;
size_t batch_read_size;
size_t internal_cache_size;
bool shift_points_to_origin;
bool create_journal;
TilingStrategy tiling_strategy;
std::variant<FixedThreadCount, AdaptiveThreadCount> thread_count;
};
/**
* Abstract command for reading points from a file.
*/
struct ReadCommand
{
const fs::path* file_path;
size_t to_read_count;
};
struct Tiler
{
Tiler(DatasetMetadata dataset_metadata,
TilerMetaParameters meta_parameters,
SamplingStrategy sampling_strategy,
ProgressReporter* progress_reporter,
MultiReaderPointSource point_source,
PointsPersistence& persistence,
const PointAttributes& input_attributes,
fs::path output_directory);
~Tiler();
/**
* Run the tiler. Returns the total number of points that were processed
*/
size_t run();
private:
void swap_point_buffers(size_t produced_points_count);
bool build_execution_graph_for_reading(tf::Taskflow& tf,
uint32_t num_read_threads,
ThroughputSampler& throughput_sampler);
void execute_read_commands(const std::vector<ReadCommand>& read_commands,
util::Range<PointBuffer::PointIterator> read_destination);
void build_execution_graph_for_indexing(tf::Taskflow& tf,
uint32_t num_indexing_threads,
ThroughputSampler& throughput_sampler);
void create_read_commands();
void adjust_read_thread_count(size_t num_read_threads);
uint32_t max_read_parallelism() const;
void estimate_read_throughput(ThroughputSampler& sampler, size_t num_points_in_last_cycle) const;
void estimate_index_throughput(ThroughputSampler& sampler, size_t num_points_in_last_cycle) const;
DatasetMetadata _dataset_metadata;
TilerMetaParameters _meta_parameters;
SamplingStrategy _sampling_strategy;
ProgressReporter* _progress_reporter;
MultiReaderPointSource _point_source;
PointsPersistence& _persistence;
AABB _bounds;
const PointAttributes& _input_attributes;
fs::path _output_directory;
PointBuffer _points_cache_for_producers, _points_cache_for_consumers;
size_t _produced_points_count;
std::deque<ReadCommand> _remaining_read_commands;
std::vector<ReadCommand> _next_read_commands_per_thread;
std::unique_ptr<TilingAlgorithmBase> _tiling_algorithm;
Semaphore _producers, _consumers;
std::chrono::high_resolution_clock::time_point _begin_read_cycle_time;
std::chrono::high_resolution_clock::time_point _begin_index_cycle_time;
}; | {
"alphanum_fraction": 0.751819676,
"avg_line_length": 28.9727891156,
"ext": "h",
"hexsha": "8ee93ac35a1f53408705117635439af0dfedf144",
"lang": "C",
"max_forks_count": 3,
"max_forks_repo_forks_event_max_datetime": "2022-02-08T11:45:45.000Z",
"max_forks_repo_forks_event_min_datetime": "2020-12-03T13:50:42.000Z",
"max_forks_repo_head_hexsha": "e3e041f87c93985394444ee056ce8ba7ae62194b",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "igd-geo/schwarzwald",
"max_forks_repo_path": "schwarzwald/core/process/Tiler.h",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "e3e041f87c93985394444ee056ce8ba7ae62194b",
"max_issues_repo_issues_event_max_datetime": "2022-03-30T06:28:06.000Z",
"max_issues_repo_issues_event_min_datetime": "2022-03-25T08:37:30.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "igd-geo/schwarzwald",
"max_issues_repo_path": "schwarzwald/core/process/Tiler.h",
"max_line_length": 100,
"max_stars_count": 10,
"max_stars_repo_head_hexsha": "e3e041f87c93985394444ee056ce8ba7ae62194b",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "igd-geo/schwarzwald",
"max_stars_repo_path": "schwarzwald/core/process/Tiler.h",
"max_stars_repo_stars_event_max_datetime": "2022-02-13T00:15:17.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-01-06T14:16:31.000Z",
"num_tokens": 929,
"size": 4259
} |
/*
* Implement Heap sort -- direct and indirect sorting
* Based on descriptions in Sedgewick "Algorithms in C"
*
* Copyright (C) 1999 Thomas Walter
*
* 18 February 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.
*/
#include <config.h>
#include <stdlib.h>
#include <gsl/gsl_heapsort.h>
static inline void swap (void *base, size_t size, size_t i, size_t j);
static inline void downheap (void *data, const size_t size, const size_t N, size_t k, gsl_comparison_fn_t compare);
/* Inline swap function for moving objects around */
static inline void
swap (void *base, size_t size, size_t i, size_t j)
{
register char *a = size * i + (char *) base;
register char *b = size * j + (char *) base;
register size_t s = size;
if (i == j)
return;
do
{
char tmp = *a;
*a++ = *b;
*b++ = tmp;
}
while (--s > 0);
}
#define CMP(data,size,j,k) (compare((char *)(data) + (size) * (j), (char *)(data) + (size) * (k)))
static inline void
downheap (void *data, const size_t size, const size_t N, size_t k, gsl_comparison_fn_t compare)
{
while (k <= N / 2)
{
size_t j = 2 * k;
if (j < N && CMP (data, size, j, j + 1) < 0)
{
j++;
}
if (CMP (data, size, k, j) < 0)
{
swap (data, size, j, k);
}
else
{
break;
}
k = j;
}
}
void
gsl_heapsort (void *data, size_t count, size_t size, gsl_comparison_fn_t compare)
{
/* Sort the array in ascending order. This is a true inplace
algorithm with N log N operations. Worst case (an already sorted
array) is something like 20% slower */
size_t N;
size_t k;
if (count == 0)
{
return; /* No data to sort */
}
/* We have n_data elements, last element is at 'n_data-1', first at
'0' Set N to the last element number. */
N = count - 1;
k = N / 2;
k++; /* Compensate the first use of 'k--' */
do
{
k--;
downheap (data, size, N, k, compare);
}
while (k > 0);
while (N > 0)
{
/* first swap the elements */
swap (data, size, 0, N);
/* then process the heap */
N--;
downheap (data, size, N, 0, compare);
}
}
| {
"alphanum_fraction": 0.586244943,
"avg_line_length": 23.6434782609,
"ext": "c",
"hexsha": "9e86ab0b076ab1b13c3a82238d529b9ef7e7e984",
"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/sort/sort.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/sort/sort.c",
"max_line_length": 115,
"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/sort/sort.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": 776,
"size": 2719
} |
#include <cblas.h>
#include <math.h>
#include <stdlib.h>
#include <string.h>
/**
* C BLAS function wrappers.
*/
inline void copy_vector_cblas(
const double* const x, double* const y,
const unsigned int rows )
{
cblas_dcopy( rows, x, 1, y, 1 );
}
inline double inner_product_cblas(
const double* const x, const double* const y,
const unsigned int rows )
{
return cblas_ddot( rows, x, 1, y, 1 );
}
inline void outer_product_cblas(
const double* const x, const double* const y,
const double alpha, const unsigned int rows_x, const unsigned int rows_y,
double* m )
{
cblas_dger( CblasRowMajor, rows_x, rows_y, alpha, x, 1, y, 1, m, rows_y);
}
inline void vector_vector_sum_cblas(
const double* const x, double* const y,
const double alpha, const unsigned int rows )
{
cblas_daxpy( rows, alpha, x, 1, y, 1);
}
/**
* Helper functions.
*/
inline void copy_matrix(
const double* const m0, double* const m1,
const unsigned int rows, const unsigned int cols )
{
for ( unsigned int i = 0; i < rows; ++i )
{
for ( unsigned int j = 0; j < cols; ++j )
{
m1[ i * cols + j ] = m0[ i * cols + j ];
}
}
}
inline void matrix_matrix_sum(
const double* const m0, const double* const m1,
const double alpha, const unsigned int rows, const unsigned int cols,
double* m2 )
{
for ( unsigned int i = 0; i < rows; ++i )
{
for ( unsigned int j = 0; j < cols; ++j )
{
m2[ i * cols + j ] = m0[ i * cols + j ] + alpha * m1[ i * cols + j ];
}
}
}
inline void zero_vector(
const unsigned int rows,
double* x )
{
memset(x, 0, rows * sizeof( double ) );
}
inline void zero_matrix(
const unsigned int rows, const unsigned int cols,
double* m )
{
memset(m, 0, rows * cols * sizeof( double ) );
}
inline void zero_diagonal(
const unsigned int rows, const unsigned int cols,
double* m )
{
for ( unsigned int i = 0; i < rows; ++i )
{
m[ i * cols + i ] = 0;
}
}
inline double rand_double( void )
{
return ( double ) rand() / ( double )( RAND_MAX );
}
inline unsigned int rand_int( const unsigned int max )
{
return rand() % max;
}
inline unsigned int logistic( const double h )
{
return 1. / ( 1. + exp( -h ) ) > rand_double();
}
/**
* Train a fully visible Boltzmann machine with CD-1.
*/
void ctrain(
double* W, double* b, unsigned int rows, unsigned int cols,
double* data, unsigned int episodes,
double epsilon_w, double epsilon_b,
unsigned int batchsize, unsigned int seed,
const double momentum_constant, const double decay_constant )
{
double dW[ rows * cols ];
double db[ cols ];
double dW_minus[ rows * cols ];
double db_minus[ cols ];
double u;
const double effective_epsilon_w = 1 / ( double )( batchsize ) * epsilon_w;
const double effective_epsilon_b = 1 / ( double )( batchsize ) * epsilon_b;
srand( seed );
// initialize momentum terms to zero at start of learning
zero_matrix( rows, cols, dW_minus );
zero_vector( rows, db_minus );
for ( unsigned int i = 0; i < episodes / batchsize; ++i )
{
// initialize weights and bias change to zero at start of batch
zero_matrix( rows, cols, dW );
zero_vector( rows, db );
for ( unsigned int j = 0; j < batchsize; ++j )
{
// compute \Delta W += <ss>_0
outer_product_cblas( &data[ i * batchsize * cols + j * cols], &data[ i * batchsize * cols + j * cols], 1., rows, cols, dW );
// compute \Delta b += <s>_0
vector_vector_sum_cblas( &data[ i * batchsize * cols + j * cols], db, 1, rows );
// perform a single Gibbs step (update all units once) directly
// on data vector to avoid copying
for ( unsigned int k = 0; k < cols; ++k )
{
u = inner_product_cblas( &W[ k * cols ], &data[ i * batchsize * cols + j * cols], cols );
data[ i * batchsize * cols + j * cols + k ] = logistic( u + b[ k ] );
}
// compute \Delta W -= <ss>_1
outer_product_cblas( &data[ i * batchsize * cols + j * cols ], &data[ i * batchsize * cols + j * cols ], -1., rows, cols, dW );
// compute \Delta b -= <s>_1
vector_vector_sum_cblas( &data[ i * batchsize * cols + j * cols ], db, -1, rows );
}
// add momentum
if ( momentum_constant > 0. )
{
matrix_matrix_sum( dW, dW_minus, momentum_constant, rows, cols, dW );
vector_vector_sum_cblas( db_minus, db, momentum_constant, rows );
copy_matrix( dW, dW_minus, rows, cols );
copy_vector_cblas( db, db_minus, rows );
}
// decay weights
if ( decay_constant > 0. )
{
// need to devide by learning rate, since dW is multiplied by it
// below
matrix_matrix_sum( dW, W, -decay_constant / effective_epsilon_w, rows, cols, dW );
}
// updates weights and biases
matrix_matrix_sum( W, dW, effective_epsilon_w, rows, cols, W );
vector_vector_sum_cblas( db, b, effective_epsilon_b, rows );
// set diagonal of weight matrix to zero
zero_diagonal( rows, cols, W );
}
}
/**
* Sample from a fully visible Boltzmann machine.
*/
void csample(
const double* W, const double* b, const unsigned int rows, const unsigned int cols,
const unsigned int episodes, const unsigned int seed,
double* s, double* samples )
{
double u;
srand( seed );
unsigned int i = 0;
while(1)
{
// perform a single Gibbs step (update all units once on average)
for ( unsigned int k = 0; k < cols; ++k )
{
const unsigned int j = rand_int( cols );
u = inner_product_cblas( &W[ j * cols ], s, cols );
s[ j ] = logistic( u + b[ j ] );
}
copy_vector_cblas( s, &samples[ i * rows], rows );
++i;
if( i == episodes)
{
return;
}
}
}
| {
"alphanum_fraction": 0.6168043593,
"avg_line_length": 26.0963302752,
"ext": "h",
"hexsha": "39c7335acb79bd77f463317880c72f88d75fd728",
"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": "46eaff859e49e3682e4ca2f4a2f8c494d5ac4ba6",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "jakobj/python-vbm",
"max_forks_repo_path": "vbm.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "46eaff859e49e3682e4ca2f4a2f8c494d5ac4ba6",
"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": "jakobj/python-vbm",
"max_issues_repo_path": "vbm.h",
"max_line_length": 133,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "46eaff859e49e3682e4ca2f4a2f8c494d5ac4ba6",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "jakobj/python-vbm",
"max_stars_repo_path": "vbm.h",
"max_stars_repo_stars_event_max_datetime": "2017-08-17T14:31:52.000Z",
"max_stars_repo_stars_event_min_datetime": "2017-08-17T14:31:52.000Z",
"num_tokens": 1659,
"size": 5689
} |
/* ******************************************************************************
*
*
* This program and the accompanying materials are made available under the
* terms of the Apache License, Version 2.0 which is available at
* https://www.apache.org/licenses/LICENSE-2.0.
*
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*
* SPDX-License-Identifier: Apache-2.0
******************************************************************************/
//
// @author raver119@gmail.com
//
#ifndef LIBND4J_BLAS_HELPER_H
#define LIBND4J_BLAS_HELPER_H
// work around conflict with OpenBLAS
struct bfloat16;
#define BFLOAT16 BFLOAT16
#include <cblas.h>
#include <helpers/logger.h>
#include <types/float16.h>
#ifdef _WIN32
#define CUBLASWINAPI __stdcall
#define CUSOLVERAPI __stdcall
#else
#define CUBLASWINAPI
#define CUSOLVERAPI
#endif
namespace sd {
typedef enum {
CUBLAS_STATUS_SUCCESS = 0,
CUBLAS_STATUS_NOT_INITIALIZED = 1,
CUBLAS_STATUS_ALLOC_FAILED = 3,
CUBLAS_STATUS_INVALID_VALUE = 7,
CUBLAS_STATUS_ARCH_MISMATCH = 8,
CUBLAS_STATUS_MAPPING_ERROR = 11,
CUBLAS_STATUS_EXECUTION_FAILED = 13,
CUBLAS_STATUS_INTERNAL_ERROR = 14,
CUBLAS_STATUS_NOT_SUPPORTED = 15,
CUBLAS_STATUS_LICENSE_ERROR = 16
} cublasStatus_t;
typedef enum { CUBLAS_OP_N = 0, CUBLAS_OP_T = 1, CUBLAS_OP_C = 2 } cublasOperation_t;
struct cublasContext;
typedef struct cublasContext *cublasHandle_t;
typedef enum {
CUDA_R_16F = 2, /* real as a half */
CUDA_C_16F = 6, /* complex as a pair of half numbers */
CUDA_R_32F = 0, /* real as a float */
CUDA_C_32F = 4, /* complex as a pair of float numbers */
CUDA_R_64F = 1, /* real as a double */
CUDA_C_64F = 5, /* complex as a pair of double numbers */
CUDA_R_8I = 3, /* real as a signed char */
CUDA_C_8I = 7, /* complex as a pair of signed char numbers */
CUDA_R_8U = 8, /* real as a unsigned char */
CUDA_C_8U = 9, /* complex as a pair of unsigned char numbers */
CUDA_R_32I = 10, /* real as a signed int */
CUDA_C_32I = 11, /* complex as a pair of signed int numbers */
CUDA_R_32U = 12, /* real as a unsigned int */
CUDA_C_32U = 13 /* complex as a pair of unsigned int numbers */
} cublasDataType_t;
typedef void (*CblasSgemv)(CBLAS_ORDER Layout, CBLAS_TRANSPOSE TransA, int M, int N, float alpha, float *A, int lda,
float *X, int incX, float beta, float *Y, int incY);
typedef void (*CblasDgemv)(CBLAS_ORDER Layout, CBLAS_TRANSPOSE TransA, int M, int N, double alpha, double *A, int lda,
double *X, int incX, double beta, double *Y, int incY);
typedef void (*CblasSgemm)(CBLAS_ORDER Layout, CBLAS_TRANSPOSE TransA, CBLAS_TRANSPOSE TransB, int M, int N, int K,
float alpha, float *A, int lda, float *B, int ldb, float beta, float *C, int ldc);
typedef void (*CblasDgemm)(CBLAS_ORDER Layout, CBLAS_TRANSPOSE TransA, CBLAS_TRANSPOSE TransB, int M, int N, int K,
double alpha, double *A, int lda, double *B, int ldb, double beta, double *C, int ldc);
typedef void (*CblasSgemmBatch)(CBLAS_ORDER Layout, CBLAS_TRANSPOSE *TransA_Array, CBLAS_TRANSPOSE *TransB_Array,
int *M_Array, int *N_Array, int *K_Array, float *alpha_Array, float **A_Array,
int *lda_Array, float **B_Array, int *ldb_Array, float *beta_Array, float **C_Array,
int *ldc_Array, int group_count, int *group_size);
typedef void (*CblasDgemmBatch)(CBLAS_ORDER Layout, CBLAS_TRANSPOSE *TransA_Array, CBLAS_TRANSPOSE *TransB_Array,
int *M_Array, int *N_Array, int *K_Array, double *alpha_Array, double **A_Array,
int *lda_Array, double **B_Array, int *ldb_Array, double *beta_Array, double **C_Array,
int *ldc_Array, int group_count, int *group_size);
#ifdef LAPACK_ROW_MAJOR
#undef LAPACK_ROW_MAJOR
#endif
#ifdef LAPACK_COL_MAJOR
#undef LAPACK_COL_MAJOR
#endif
enum LAPACK_LAYOUT { LAPACK_ROW_MAJOR = 101, LAPACK_COL_MAJOR = 102 };
typedef int (*LapackeSgesvd)(LAPACK_LAYOUT matrix_layout, char jobu, char jobvt, int m, int n, float *a, int lda,
float *s, float *u, int ldu, float *vt, int ldvt, float *superb);
typedef int (*LapackeDgesvd)(LAPACK_LAYOUT matrix_layout, char jobu, char jobvt, int m, int n, double *a, int lda,
double *s, double *u, int ldu, double *vt, int ldvt, double *superb);
typedef int (*LapackeSgesdd)(LAPACK_LAYOUT matrix_layout, char jobz, int m, int n, float *a, int lda, float *s,
float *u, int ldu, float *vt, int ldvt);
typedef int (*LapackeDgesdd)(LAPACK_LAYOUT matrix_layout, char jobz, int m, int n, double *a, int lda, double *s,
double *u, int ldu, double *vt, int ldvt);
typedef cublasStatus_t(CUBLASWINAPI *CublasSgemv)(cublasHandle_t handle, cublasOperation_t trans, int m, int n,
float *alpha, /* host or device pointer */
float *A, int lda, float *x, int incx,
float *beta, /* host or device pointer */
float *y, int incy);
typedef cublasStatus_t(CUBLASWINAPI *CublasDgemv)(cublasHandle_t handle, cublasOperation_t trans, int m, int n,
double *alpha, /* host or device pointer */
double *A, int lda, double *x, int incx,
double *beta, /* host or device pointer */
double *y, int incy);
typedef cublasStatus_t(CUBLASWINAPI *CublasHgemm)(cublasHandle_t handle, cublasOperation_t transa,
cublasOperation_t transb, int m, int n, int k,
__half *alpha, /* host or device pointer */
__half *A, int lda, __half *B, int ldb,
__half *beta, /* host or device pointer */
__half *C, int ldc);
typedef cublasStatus_t(CUBLASWINAPI *CublasSgemm)(cublasHandle_t handle, cublasOperation_t transa,
cublasOperation_t transb, int m, int n, int k,
float *alpha, /* host or device pointer */
float *A, int lda, float *B, int ldb,
float *beta, /* host or device pointer */
float *C, int ldc);
typedef cublasStatus_t(CUBLASWINAPI *CublasDgemm)(cublasHandle_t handle, cublasOperation_t transa,
cublasOperation_t transb, int m, int n, int k,
double *alpha, /* host or device pointer */
double *A, int lda, double *B, int ldb,
double *beta, /* host or device pointer */
double *C, int ldc);
typedef cublasStatus_t(CUBLASWINAPI *CublasSgemmEx)(cublasHandle_t handle, cublasOperation_t transa,
cublasOperation_t transb, int m, int n, int k,
float *alpha, /* host or device pointer */
void *A, cublasDataType_t Atype, int lda, void *B,
cublasDataType_t Btype, int ldb,
float *beta, /* host or device pointer */
void *C, cublasDataType_t Ctype, int ldc);
typedef cublasStatus_t(CUBLASWINAPI *CublasHgemmBatched)(cublasHandle_t handle, cublasOperation_t transa,
cublasOperation_t transb, int m, int n, int k,
__half *alpha, /* host or device pointer */
__half *Aarray[], int lda, __half *Barray[], int ldb,
__half *beta, /* host or device pointer */
__half *Carray[], int ldc, int batchCount);
typedef cublasStatus_t(CUBLASWINAPI *CublasSgemmBatched)(cublasHandle_t handle, cublasOperation_t transa,
cublasOperation_t transb, int m, int n, int k,
float *alpha, /* host or device pointer */
float *Aarray[], int lda, float *Barray[], int ldb,
float *beta, /* host or device pointer */
float *Carray[], int ldc, int batchCount);
typedef cublasStatus_t(CUBLASWINAPI *CublasDgemmBatched)(cublasHandle_t handle, cublasOperation_t transa,
cublasOperation_t transb, int m, int n, int k,
double *alpha, /* host or device pointer */
double *Aarray[], int lda, double *Barray[], int ldb,
double *beta, /* host or device pointer */
double *Carray[], int ldc, int batchCount);
typedef enum {
CUSOLVER_STATUS_SUCCESS = 0,
CUSOLVER_STATUS_NOT_INITIALIZED = 1,
CUSOLVER_STATUS_ALLOC_FAILED = 2,
CUSOLVER_STATUS_INVALID_VALUE = 3,
CUSOLVER_STATUS_ARCH_MISMATCH = 4,
CUSOLVER_STATUS_MAPPING_ERROR = 5,
CUSOLVER_STATUS_EXECUTION_FAILED = 6,
CUSOLVER_STATUS_INTERNAL_ERROR = 7,
CUSOLVER_STATUS_MATRIX_TYPE_NOT_SUPPORTED = 8,
CUSOLVER_STATUS_NOT_SUPPORTED = 9,
CUSOLVER_STATUS_ZERO_PIVOT = 10,
CUSOLVER_STATUS_INVALID_LICENSE = 11
} cusolverStatus_t;
typedef enum { CUSOLVER_EIG_TYPE_1 = 1, CUSOLVER_EIG_TYPE_2 = 2, CUSOLVER_EIG_TYPE_3 = 3 } cusolverEigType_t;
typedef enum { CUSOLVER_EIG_MODE_NOVECTOR = 0, CUSOLVER_EIG_MODE_VECTOR = 1 } cusolverEigMode_t;
struct cusolverDnContext;
typedef struct cusolverDnContext *cusolverDnHandle_t;
typedef cusolverStatus_t(CUSOLVERAPI *CusolverDnSgesvdBufferSize)(cusolverDnHandle_t handle, int m, int n, int *lwork);
typedef cusolverStatus_t(CUSOLVERAPI *CusolverDnDgesvdBufferSize)(cusolverDnHandle_t handle, int m, int n, int *lwork);
typedef cusolverStatus_t(CUSOLVERAPI *CusolverDnSgesvd)(cusolverDnHandle_t handle, signed char jobu, signed char jobvt,
int m, int n, float *A, int lda, float *S, float *U, int ldu,
float *VT, int ldvt, float *work, int lwork, float *rwork,
int *info);
typedef cusolverStatus_t(CUSOLVERAPI *CusolverDnDgesvd)(cusolverDnHandle_t handle, signed char jobu, signed char jobvt,
int m, int n, double *A, int lda, double *S, double *U, int ldu,
double *VT, int ldvt, double *work, int lwork, double *rwork,
int *info);
enum BlasFunctions {
GEMV = 0,
GEMM = 1,
};
class BlasHelper {
private:
bool _hasHgemv = false;
bool _hasHgemm = false;
bool _hasHgemmBatch = false;
bool _hasSgemv = false;
bool _hasSgemm = false;
bool _hasSgemmBatch = false;
bool _hasDgemv = false;
bool _hasDgemm = false;
bool _hasDgemmBatch = false;
CblasSgemv cblasSgemv;
CblasDgemv cblasDgemv;
CblasSgemm cblasSgemm;
CblasDgemm cblasDgemm;
CblasSgemmBatch cblasSgemmBatch;
CblasDgemmBatch cblasDgemmBatch;
LapackeSgesvd lapackeSgesvd;
LapackeDgesvd lapackeDgesvd;
LapackeSgesdd lapackeSgesdd;
LapackeDgesdd lapackeDgesdd;
CublasSgemv cublasSgemv;
CublasDgemv cublasDgemv;
CublasHgemm cublasHgemm;
CublasSgemm cublasSgemm;
CublasDgemm cublasDgemm;
CublasSgemmEx cublasSgemmEx;
CublasHgemmBatched cublasHgemmBatched;
CublasSgemmBatched cublasSgemmBatched;
CublasDgemmBatched cublasDgemmBatched;
CusolverDnSgesvdBufferSize cusolverDnSgesvdBufferSize;
CusolverDnDgesvdBufferSize cusolverDnDgesvdBufferSize;
CusolverDnSgesvd cusolverDnSgesvd;
CusolverDnDgesvd cusolverDnDgesvd;
public:
static BlasHelper &getInstance();
void initializeFunctions(sd::Pointer *functions);
void initializeDeviceFunctions(sd::Pointer *functions);
template <typename T>
bool hasGEMV();
template <typename T>
bool hasGEMM();
bool hasGEMM(const sd::DataType dtype);
bool hasGEMV(const sd::DataType dtype);
template <typename T>
bool hasBatchedGEMM();
CblasSgemv sgemv();
CblasDgemv dgemv();
CblasSgemm sgemm();
CblasDgemm dgemm();
CblasSgemmBatch sgemmBatched();
CblasDgemmBatch dgemmBatched();
LapackeSgesvd sgesvd();
LapackeDgesvd dgesvd();
LapackeSgesdd sgesdd();
LapackeDgesdd dgesdd();
// destructor
~BlasHelper() noexcept;
};
} // namespace sd
#endif
| {
"alphanum_fraction": 0.5806887719,
"avg_line_length": 46.6910299003,
"ext": "h",
"hexsha": "b3682e36ed471b0a562cc8fecddc0048f7d979ea",
"lang": "C",
"max_forks_count": 572,
"max_forks_repo_forks_event_max_datetime": "2022-03-31T16:46:46.000Z",
"max_forks_repo_forks_event_min_datetime": "2019-06-12T22:13:57.000Z",
"max_forks_repo_head_hexsha": "4653c97a713cc59e41d4313ddbafc5ff527f8714",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "steljord2/deeplearning4j",
"max_forks_repo_path": "libnd4j/include/helpers/BlasHelper.h",
"max_issues_count": 1685,
"max_issues_repo_head_hexsha": "4653c97a713cc59e41d4313ddbafc5ff527f8714",
"max_issues_repo_issues_event_max_datetime": "2022-03-29T21:45:15.000Z",
"max_issues_repo_issues_event_min_datetime": "2019-06-12T17:41:33.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "steljord2/deeplearning4j",
"max_issues_repo_path": "libnd4j/include/helpers/BlasHelper.h",
"max_line_length": 120,
"max_stars_count": 2206,
"max_stars_repo_head_hexsha": "4653c97a713cc59e41d4313ddbafc5ff527f8714",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "steljord2/deeplearning4j",
"max_stars_repo_path": "libnd4j/include/helpers/BlasHelper.h",
"max_stars_repo_stars_event_max_datetime": "2022-03-29T08:14:27.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-06-12T18:57:14.000Z",
"num_tokens": 3546,
"size": 14054
} |
/*
ODE: a program to get optime Runge-Kutta and multi-steps methods.
Copyright 2011-2019, Javier Burguete Tolosa.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY Javier Burguete Tolosa ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
SHALL Javier Burguete Tolosa OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* \file ode.c
* \brief Source file with the main function.
* \author Javier Burguete Tolosa.
* \copyright Copyright 2011-2019.
*/
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <getopt.h>
#include <math.h>
#include <string.h>
#include <alloca.h>
#include <time.h>
#include <unistd.h>
#include <libxml/parser.h>
#include <glib.h>
#include <gsl/gsl_rng.h>
#include <libintl.h>
#if HAVE_MPI
#include <mpi.h>
#endif
#include "config.h"
#include "utils.h"
#include "optimize.h"
#include "steps.h"
#include "rk.h"
// OPTIMES
//
// RK_2_2 (cfl=1, cfl/steps=1/2)
// t1=1 t2=1
// a10=1 a20=a21=1/2
// b10=1 b20=b21=1/2
// c10=1 c20=0 c21=1
//
// RK_3_2 (cfl=2, cfl/steps=2/3)
// t1=1/2 t2=t3=1
// a10=1 a20=0 a21=1 a30=1/3 a31=0 a32=2/3
// b10=1/2 b20=b21=1/2 b30=b31=b32=1/3
// c10=1/2 c20=0 c21=1/2 c30=0 c31=0 c32=1/2
//
// RK_4_2 (cfl=3, cfl/steps=3/4)
// t1=1/3 t2=2/3 t3=t4=1
// a10=1 a20=0 a21=1 a30=a31=0 a32=1 a40=1/4 a41=a42=0 a43=3/4
// b10=1/3 b20=b21=1/2 b30=b31=b32=1/3
// c10=1/3 c20=0 c21=1/3 c30=c31=0 c32=1/3 c40=c41=c42=0 c43=1/3
//
// RK_5_2 (cfl=4, cfl/steps=4/5)
// t1=1/4 t2=1/2 t3=3/4 t4=t5=1
// a10=1 a20=0 a21=1 a30=a31=0 a32=1 a40=a41=a42=0 a43=1
// a50=1/5 a51=a52=a53=0 a54=4/5
// b10=b20=b21=b30=b31=b32=b40=b41=b42=b43=1/4 b50=b51=b52=b53=b54=1/5
// c10=1/4 c20=0 c21=1/4 c30=c31=0 c32=1/4 c40=c41=c42=0 c43=1/4
// c50=c51=c52=c53=0 c54=1/4
//
// RK_6_2 (cfl=5, cfl/steps=5/6)
// t1=1/5 t2=2/5 t3=3/5 t4=4/5 t5=t6=1
// a10=1 a20=0 a21=1 a30=a31=0 a32=1 a40=a41=a42=0 a43=1 a50=a51=a52=a53=0 a54=1
// a60=1/6 a61=a62=a63=a64=0 a65=5/6
// b10=b20=b21=b30=b31=b32=b40=b41=b42=b43b50=b51=b52=b53=b54=1/5
// b60=b61=b62=b63=b64=b65=1/6
// c10=1/5 c20=0 c21=1/5 c30=c31=0 c32=1/5 c40=c41=c42=0 c43=1/5
// c50=c51=c52=c53=0 c54=1/5 c60=c61=c62=c63=c64=0 c65=1/5
//
// RK_7_2 (cfl=6, cfl/steps=6/7)
// t1=1/6 t2=2/6 t3=3/6 t4=4/6 t5=5/6 t6=t7=1
// a10=1 a20=0 a21=1 a30=a31=0 a32=1 a40=a41=a42=0 a43=1 a50=a51=a52=a53=0 a54=1
// a60=a61=a62=a63=a64=0 a65=1 a70=1/7 a71=a72=a73=a74=a75=0 a76=6/7
// b10=b20=b21=b30=b31=b32=b40=b41=b42=b43b50=b51=b52=b53=b54=b60=b61=b62=b63
// =b64=b65=1/6 b70=b71=b72=b73=b74=b75=b76=1/7
// c10=1/6 c20=0 c21=1/6 c30=c31=0 c32=1/6 c40=c41=c42=0 c43=1/6
// c50=c51=c52=c53=0 c54=1/6 c60=c61=c62=c63=c64=0 c65=1/6
// c70=c71=c73=c74=c75=0 c76=1/6
//
// STEPS_3_2 (cfl=1/2)
// a0=3/4 a1=0 a2=1/4
// b0=3/2 b1=b2=0
// c0=2 c1=c2=0
//
// STEPS_4_2 (cfl=2/3)
// a0=8/9 a1=a2=0 a3=1/9
// b0=4/3 b1=b2=b3=0
// c0=3/2 c1=c2=c3=0
//
// STEPS_5_2 (cfl=3/4)
// a0=15/16 a1=a2=a3=0 a4=1/16
// b0=5/4 b1=b2=b3=b4=0
// c0=4/3 c1=c2=c3=c4=0
//
// STEPS_6_2 (cfl=4/5)
// a0=24/25 a1=a2=a3=a4=0 a5=1/25
// b0=6/5 b1=b2=b3=b4=b5=0
// c0=5/4 c1=c2=c3=c4=c5=0
//
// STEPS_7_2 (cfl=5/6)
// a0=35/36 a1=a2=a3=a4=0 a5=1/36
// b0=7/6 b1=b2=b3=b4=b5=0
// c0=6/5 c1=c2=c3=c4=c5=0
//
// STEPS_8_2 (cfl=6/7)
// a0=48/49 a1=a2=a3=a4=0 a5=1/49
// b0=8/7 b1=b2=b3=b4=b5=0
// c0=7/6 c1=c2=c3=c4=c5=0
//
// RK_3_3 (cfl=1, cfl/steps=1/3)
// t1=t3=1 t2=1/2
// a10=1 a20=3/4 a21=1/4 a30=1/3 a31=0 a32=2/3
// b10=1 b20=b21=1/4 b30=b31=1/6 b32=2/3
// c10=1 c20=0 c21=1 c30=0 c31=0 c32=1
//
// RK_4_3 (cfl=2, cfl/steps=1/2)
// t1=t3=1/2 t2=1
// a10=1 a20=0 a21=1 a30=2/3 a31=0 a32=1/3 a40=a41=a42=0 a43=1
// b10=b20=b21=1/2 b30=b31=b32=b40=b41=b42=1/6 b43=1/2
// c10=c20=c21=1/2 c30=0 c31=c32=c40=c41=c42=c43=1/2
//
// STEPS_4_3 (cfl=1/3)
// a0=16/27 a1=a2=0 a3=11/27
// b0=16/9 b1=b2=0 b3=4/9
// c0=3 c1=c2=0 c3=12/11
//
// STEPS_5_3 (cfl=1/2)
// a0=25/32 a1=a2=a3=0 a4=7/32
// b0=25/16 b1=b2=b3=0 b4=5/16
// c0=2 c1=c2=c3=0 c4=10/7
//
// STEPS_6_3 (cfl=0.58282164314264111327)
// a0=0.85070887167257828565 // (1-a4-a5)
// a1=a2=a3=0
// a4=0.030664864534382320725 // (sqrt(10*a5-1)-10*a5+1)/8
// a5=0.11862626379303939363
// (63*sqrt(2614)+3221)^(1/3)-5*(63*sqrt(2614)+3221)^(-1/3)-13)/45
// b0=1.4596384360152765194 // a0*c0
// b1=b2=b3=0
// b4=0.052614491749197671863 // a4*c4
// b5=0.20353784933825205974 // a5*c5
// c0=c4=c5=1.715790777102726251 // (1+4*a4+5*a5)
// c1=c2=c3=0
//
// RK_4_4
// b20=b30=b31=0
// t1=t2=b10=b21=1/2
// t3=t4=b32=1
// b40=b43=1/6
// b41=b42=1/3
//
// RK_5_4 (cfl=5.7383119999072648693e-01)
// a10=1
// a20=7.6291847536448934231e-01
// a21=2.3708152463551065768e-01
// a30=2.8277566215397998339e-03
// a31=9.4483076489543642366e-01
// a32=5.2341478483023776481e-02
// a40=6.6309349322657261432e-01
// a41=4.4608078655530437600e-04
// a42=3.3644655897571642926e-01
// a43=1.3867011155652078012e-05
// a50=6.1508837844244168818e-01
// a51=1.6215445203250317099e-01
// a52=1.5031540295088349761e-03
// a53=2.9995002701206228898e-03
// a54=2.1825451522542568299e-01
// b10=4.5307898578512145396e-01
// b20=1.0742850906542086858e-01
// b21=4.1289584245869493973e-01
// b30=4.3724780003845571699e-01
// b31=1.6681424138984873981e+00
// b32=9.0588475806896936944e-02
// b40=3.6664090929447934446e-02
// b41=1.3964776663947759666e-01
// b42=5.8495388577489235762e-01
// b43=1.9355255172522962676e-05
// b50=1.8734964237542205069e-01
// b51=3.0001844590932289148e-01
// b52=1.2903718344972795025e-01
// b53=3.4166232498545846666e-03
// b54=3.8017810501567252292e-01
// c10=4.5307898578512145396e-01
// c20=1.5535519922690283242e-05
// c21=1.7415774725317857109e+00
// c30=1.2525364871787093798e+00
// c31=1.7426727581493662919e+00
// c32=1.7307206145557779180e+00
// c40=4.7046995817421687883e-04
// c41=1.5854730818354572705e+00
// c42=1.7386197420604550316e+00
// c43=1.3957769958693602267e+00
// c50=1.6974106727520458494e-01
// c51=1.6275559956612365566e+00
// c52=7.2955698585694530597e-01
// c53=1.1376557995384390896e+00
// c54=1.7419025884665109550e+00
//
// STEPS_6_4 (cfl=1.6475925238473621578e-01)
// a0=3.4246085571701207596e-01
// a1=a2=0
// a3=1.9179825943473607269e-01
// a4=9.3562124939009442453e-02
// a5=3.721787599092424089e-01
// b0=2.078553105578055306e+00
// b1=b2=b5=0
// b3=1.1641122222796929277e+00
// b4=5.6787174974870979874e-01
// c0=c3=c4=6.0694618695213438363e+00
// c1=c2=c5=0
/**
* enum to define the method type.
*/
enum
{
METHOD_TYPE_RUNGE_KUTTA = 1, ///< Runge-Kutta method.
METHOD_TYPE_STEPS = 2, ///< multi-steps method.
} MethodType;
/**
* enum to define the program error code.
*/
enum
{
ERROR_CODE_NARGS = 1, ///< bad command line arguments number.
ERROR_CODE_BAD_DOC = 2, ///< bad XML file.
ERROR_CODE_NO_XML_ROOT = 3, ///< no XML root node.
ERROR_CODE_BAD_RK = 4, ///< bad Runge-Kutta method.
ERROR_CODE_BAD_STEPS = 5, ///< bad multi-steps method.
ERROR_CODE_UNKNOWN_METHOD = 6, ///< unknown method.
ERROR_CODE_UNKNOWN_OPTION = 7, ///< unknown option.
} ErrorCode;
unsigned int nsteps; ///< steps number.
unsigned int order; ///< accuracy order.
/**
* Main function
*
* \return 0 on succes, error code on error.
*/
int
main (int argn, ///< arguments number.
char **argc) ///< argument chains array.
{
const struct option options[] = {
{"help", no_argument, NULL, 'h'},
{"seed", required_argument, NULL, 's'},
{"threads", required_argument, NULL, 't'},
{NULL, 0, NULL, 0}
};
const char *usage = _("Usage is:\n"
"./ode "
"[-t --threads threads_number] "
"[-s --seed random_seed] "
"input_file [variables_file]");
xmlDoc *doc;
xmlNode *node;
gsl_rng *rng0, **rng;
time_t d0;
clock_t t0;
unsigned long int seed = 7l;
int o, option_index;
unsigned int i, j, k, h = 0;
#if HAVE_MPI
// Init MPI
MPI_Init (&argn, &argc);
#endif
// Enabling spaces in XML files
xmlKeepBlanksDefault (0);
// Setting the threads as the number of processors
nthreads = sysconf (_SC_NPROCESSORS_CONF);
// Parsing command line options
while (1)
{
o = getopt_long (argn, argc, "hs:t:", options, &option_index);
if (o == -1)
break;
switch (o)
{
case 's':
seed = atol (optarg);
break;
case 't':
nthreads = atoi (optarg);
break;
case 'h':
printf ("%s\n", usage);
h = 1;
break;
default:
show_error (_("Unknown option"));
return ERROR_CODE_UNKNOWN_OPTION;
}
}
argn -= optind;
if (argn != 1 && argn != 2)
{
if (h)
return 0;
show_error (usage);
return ERROR_CODE_NARGS;
}
// Init the clock
t0 = clock ();
d0 = time (NULL);
#if HAVE_MPI
// Nodes number
MPI_Comm_size (MPI_COMM_WORLD, &nnodes);
// Actual node
MPI_Comm_rank (MPI_COMM_WORLD, &rank);
#else
nnodes = 1;
rank = 0;
#endif
// Select the numerical model
printf ("Rank=%d nnodes=%d nthreads=%u\n", rank, nnodes, nthreads);
printf ("Selecting method optind=%d\n", optind);
doc = xmlParseFile (argc[optind]);
if (!doc)
{
show_error (_("Unable to parse the input file"));
return ERROR_CODE_BAD_DOC;
}
node = xmlDocGetRootElement (doc);
if (!node)
{
show_error (_("No XML root node"));
return ERROR_CODE_NO_XML_ROOT;
}
// Init a random numbers generator per node and thread
printf ("Initing random numbers\n");
rng = (gsl_rng **) g_slice_alloc (nnodes * nthreads * sizeof (gsl_rng *));
rng0 = gsl_rng_alloc (gsl_rng_ranlxs2);
gsl_rng_set (rng0, seed);
for (i = k = 0; (int) i < nnodes; ++i)
for (j = 0; j < nthreads; ++j, ++k)
{
rng[k] = gsl_rng_alloc (gsl_rng_taus2);
gsl_rng_set (rng[k], gsl_rng_get (rng0));
}
if (argn == 2)
file_variables = fopen (argc[++optind], "w");
j = rank * nthreads;
if (!xmlStrcmp (node->name, XML_RUNGE_KUTTA))
{
if (!rk_run (node, rng))
{
show_error (error_message);
return ERROR_CODE_BAD_RK;
}
}
else if (!xmlStrcmp (node->name, XML_STEPS))
{
if (!steps_run (node, rng))
{
show_error (error_message);
return ERROR_CODE_BAD_STEPS;
}
}
else
{
show_error (_("Unknown method type"));
return ERROR_CODE_UNKNOWN_METHOD;
}
printf ("cpu time=%lg real time=%lu\n",
(clock () - t0) / ((double) CLOCKS_PER_SEC), time (NULL) - d0);
// Free memory
xmlFreeDoc (doc);
if (file_variables)
fclose (file_variables);
j = nnodes * nthreads;
for (i = 0; i < j; ++i)
gsl_rng_free (rng[i]);
g_slice_free1 (j * sizeof (gsl_rng *), rng);
gsl_rng_free (rng0);
#if HAVE_MPI
// Close MPI
MPI_Finalize ();
#endif
return 0;
}
| {
"alphanum_fraction": 0.6409719313,
"avg_line_length": 27.9508196721,
"ext": "c",
"hexsha": "aaca8a38d0e829acb199bbf7f372a339530f80fb",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "463b8402ed4aac140a4c4ca2295a69dcce98b061",
"max_forks_repo_licenses": [
"BSD-2-Clause"
],
"max_forks_repo_name": "jburguete/ode",
"max_forks_repo_path": "ode.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "463b8402ed4aac140a4c4ca2295a69dcce98b061",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-2-Clause"
],
"max_issues_repo_name": "jburguete/ode",
"max_issues_repo_path": "ode.c",
"max_line_length": 80,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "463b8402ed4aac140a4c4ca2295a69dcce98b061",
"max_stars_repo_licenses": [
"BSD-2-Clause"
],
"max_stars_repo_name": "jburguete/ode",
"max_stars_repo_path": "ode.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 5020,
"size": 11935
} |
#ifndef __INTERP_2D_H__
#define __INTERP_2D_H__
#include <string.h>
//#include <gsl/gsl_vector.h>
//#include <gsl/gsl_matrix.h>
//#include <gsl/gsl_math.h>
#include <gsl/gsl_spline.h>
#include "cubic_bspline_2d_coeffs.h"
#include "cubic_bspline_2d_interpol.h"
enum
{
INTERP_2D_LINEAR=0,
INTERP_2D_CUBIC_BSPLINE=1
};
typedef struct
{
int size1;
int size2;
double * xa;
double * ya;
double * za;
int type;
}interp_2d;
interp_2d * interp_2d_alloc(int size1, int size2);
void interp_2d_free(interp_2d * i2d);
void interp_2d_init(interp_2d * i2d, const double * xa, const double * ya, const double * za, int type);
double interp_2d_eval(interp_2d * i2d, double x, double y, gsl_interp_accel * accx, gsl_interp_accel * accy);
void interp_2d_eval_grad(interp_2d * i2d, double x, double y, double * grad, gsl_interp_accel * accx, gsl_interp_accel * accy);
double interp_2d_eval_cubic_bspline(interp_2d * i2d, double x, double y, gsl_interp_accel * accx,gsl_interp_accel * accy);
#endif
| {
"alphanum_fraction": 0.7315175097,
"avg_line_length": 25.7,
"ext": "h",
"hexsha": "c254bdef8f92c50b207aaeb1f091462ae0869d5b",
"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": "93a1b6fc8d138899922127086cc66184919c8cba",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "fardal/galpy",
"max_forks_repo_path": "galpy/util/interp_2d/interp_2d.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "93a1b6fc8d138899922127086cc66184919c8cba",
"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": "fardal/galpy",
"max_issues_repo_path": "galpy/util/interp_2d/interp_2d.h",
"max_line_length": 127,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "93a1b6fc8d138899922127086cc66184919c8cba",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "fardal/galpy",
"max_stars_repo_path": "galpy/util/interp_2d/interp_2d.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 340,
"size": 1028
} |
//
// Created by robin on 2018/9/1.
// Copyright (c) 2018 Robin. All rights reserved.
//
#pragma once
#include <gsl/gsl>
namespace satz {
template <typename P>
const P zero = P::ZERO;
template <typename P>
const P one = P::ONE;
template <typename P>
const P X = P::X;
/**
* @brief Compute $b^e$.
* @param b base
* @param e exponent
* @param acc
* @pre $e \ge 0, acc = 1$.
*/
template <typename P, typename N>
P pow (P b, N e, P acc = one<P>) {
Expects(e >= 0);
while (e) {
if (e % 2) acc = acc * b;
b = b * b;
e = e / 2;
}
return acc;
}
/**
* @brief Compute $(b^e) mod m$.
* @param b base
* @param e exponent
* @param m modulus
* @param acc
* @pre $e >= 0, acc = 1$
*/
template <typename P, typename N>
P mod_pow (P b, N e, const P& m, P acc = one<P>) {
Expects(e >= 0);
while (e) {
if (e % 2) acc = (acc * b) % m;
b = (b * b) % m;
e = e / 2;
}
return acc;
}
template <typename P>
P gcd (P a, P b) {
while (b) {
std::tie(a, b) = std::make_pair(b, a % b);
}
return a;
}
/**
* @brief Compute $(x^{2^p} - x) mod m$.
* @param p
* @param m modulus
*/
template <typename P, typename N>
P reduce_exponent (N p, const P& m) {
auto r = X<P>;
for (; p > 0; --p) r = (r * r) % m;
return (r - X<P>) % m;
}
/**
* @brief Given a polynomial p over GF(2) return whether it is irreducible
* with Ben-Or's algorithm.
* @param p polynomial over GF(2)
* @return true if p is irreducible.
* @pre p is non-constant.
*/
template <typename P>
bool ben_or_test (const P& p) {
Expects(p.degree() > 0);
auto d = p.degree();
for (decltype(d) i = 1; i <= d / 2; ++i) {
auto b = reduce_exponent(i, p);
auto g = gcd(p, b);
if (g != one<P>) return false;
}
return true;
}
/**
* @brief Given a polynomial p over GF(2), return whether it is irreducible.
* @param p polynomial over GF(2)
* @return true if p is irreducible.
*/
template <typename P>
bool is_irreducible (const P& p) {
if (p.degree() > 0) return ben_or_test(p);
else return false;
}
}
| {
"alphanum_fraction": 0.5563654033,
"avg_line_length": 17.8956521739,
"ext": "h",
"hexsha": "03fbc522b69ab5f05176ff15e330f47d46e09271",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2021-03-26T11:41:15.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-03-26T11:41:15.000Z",
"max_forks_repo_head_hexsha": "834d2d52e4c5967fe4b7aa6026742cc82c6bc031",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "lie-yan/rabin-fingerprint",
"max_forks_repo_path": "src/arithmetic.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "834d2d52e4c5967fe4b7aa6026742cc82c6bc031",
"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": "lie-yan/rabin-fingerprint",
"max_issues_repo_path": "src/arithmetic.h",
"max_line_length": 76,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "834d2d52e4c5967fe4b7aa6026742cc82c6bc031",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "lie-yan/rabin-fingerprint",
"max_stars_repo_path": "src/arithmetic.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 715,
"size": 2058
} |
#ifndef LADMM_H
#define LADMM_H
#include "Matrix.h"
#include <string>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
#include <stdio.h> /* printf */
#include <time.h>
#include <fstream>
#include <algorithm>
#include <iomanip>
#include <ctime>
#include <sstream>
//#include "cmd_line.h"
//This class implements the method LADMM
/*
The optimization problem to solve is:
min \sum_i f^i(A_ix)+ \sum_i h^i(y^i)+ g(x)
s.t. Mx= y
Assumption 1: For each i, f_i is smooth, g(x) is seperable
*/
template<typename L, typename D>
class LADMM
{
private:
std::vector<D> Ax;
std::vector<D> old_Ax;
std::vector<D> Mx;
std::vector<D> old_Mx;
std::vector<D> Mty;
std::vector<D> old_Mty;
std::vector<D> Mtlambda;
std::vector<D> old_Mtlambda;
std::vector<D> gradient;
std::vector<D> MtMx;
protected:
Matrix<L, D> data_A;
Matrix<L, D> data_M;
std::vector<D> x;
std::vector<D> old_x;
std::vector<D> y;
std::vector<D> old_y;
std::vector<D> lambda;
std::vector<D> old_lambda;
D beta;
L m_1;
L m_2;
L m_3;
D rho;
D tau;
D sigma;
D L_phi;
D function_value;
D infeas;
L print_every_N_ADMM;
D running_time_ADMM;
L nb_outer_iters;
ofstream samp_ADMM;
public:
D lambda_f;
D mu_g;
D lambda1;
D lambda2;
D L_h;
virtual inline D value_of_f_j(D, L){return D(NULL);}
virtual inline D value_of_h_j(D, L){return D(NULL);}
virtual inline D gradient_of_f_j(D, L){return D(NULL);}
virtual inline D prox_of_h_j(D,D, L){return D(NULL);}
virtual inline D value_of_g_j(D, L){return D(NULL);}
virtual inline D prox_of_g_j(D, D, L){return D(NULL);}
virtual inline void set_matrix_M(){}
virtual inline void set_matrix_A(){}
/*
LADMM(const char* matrix_file, const char* matrix_file2)
: Primal_Dual_LOOPLESS_Katyusha0<L,D>(),data_A(matrix_file), data_M(matrix_file2)
{
this->matrix_merge(data_A,data_M);
this->gamma=1;
}
*/
inline void set_L_phi(){
if (data_A.nsamples== 0){
L_phi= 0;
}
else{
L_phi= compute_lambda_max_A(10);
}
}
D compute_lambda_max_A(L K){
std::vector<D> bk(data_A.nfeatures);
for (L j=0;j<data_A.nfeatures;j++)
{
bk[j]=1;
}
std::vector<D> yk(data_A.nsamples);
D normk;
D tmp;
for(L kk=0;kk<K;kk++){
for (L i=0;i<data_A.nsamples;i++){
tmp=0;
for (L k = data_A.ptr[i]; k < data_A.ptr[i + 1]; k++)
{
L j=data_A.row_idx[k];
tmp+=data_A.A[k]*bk[j];
}
yk[i]=tmp;
}
normk=0;
for (L j=0;j<data_A.nfeatures;j++){
bk[j]=0;
for (L k = data_A.ptr_t[j]; k < data_A.ptr_t[j + 1]; k++)
{
L i=data_A.col_idx[k];
bk[j]+=data_A.A_t[k]*yk[i]*lambda_f;
}
normk+=bk[j]*bk[j];
}
normk=sqrt(normk);
for (L j=0;j<data_A.nfeatures;j++)
{bk[j]=bk[j]/normk; }
}
cout<<endl;
D res=0;
normk=0;
for (L i=0;i<data_A.nsamples;i++){
tmp=0;
for (L k = data_A.ptr[i]; k < data_A.ptr[i + 1]; k++)
{
L j=data_A.row_idx[k];
tmp+=data_A.A[k]*bk[j];
}
yk[i]=tmp;
normk+=yk[i]*yk[i];
}
std::vector<D> bk2(data_A.nfeatures);
for (L j=0;j<data_A.nfeatures;j++){
bk2[j]=0;
for (L k = data_A.ptr_t[j]; k < data_A.ptr_t[j + 1]; k++)
{
L i=data_A.col_idx[k];
bk2[j]+=data_A.A_t[k]*yk[i]*lambda_f;
}
}
for (L j=0;j<data_A.nfeatures;j++)
res+=bk2[j]*bk[j];
return res;
}
D compute_lambda_max_M(L K){
std::vector<D> bk(data_M.nfeatures);
for (L j=0;j<data_M.nfeatures- 1;j++)
{
bk[j]=1;
}
bk[data_M.nfeatures- 1]= 2;
std::vector<D> yk(data_M.nsamples);
D normk;
D tmp;
for(L kk=0;kk<K;kk++){
for (L i=0;i<data_M.nsamples;i++){
tmp=0;
for (L k = data_M.ptr[i]; k < data_M.ptr[i + 1]; k++)
{
L j=data_M.row_idx[k];
tmp+=data_M.A[k]*bk[j];
}
yk[i]=tmp;
}
normk=0;
for (L j=0;j<data_M.nfeatures;j++){
bk[j]=0;
for (L k = data_M.ptr_t[j]; k < data_M.ptr_t[j + 1]; k++)
{
L i=data_M.col_idx[k];
bk[j]+=data_M.A_t[k]*yk[i];
}
normk+=bk[j]*bk[j];
}
normk=sqrt(normk);
for (L j=0;j<data_M.nfeatures;j++)
{bk[j]=bk[j]/normk; }
}
D res=0;
normk=0;
for (L i=0;i<data_M.nsamples;i++){
tmp=0;
for (L k = data_M.ptr[i]; k < data_M.ptr[i + 1]; k++)
{
L j=data_M.row_idx[k];
tmp+=data_M.A[k]*bk[j];
}
yk[i]=tmp;
normk+=yk[i]*yk[i];
}
std::vector<D> bk2(data_M.nfeatures);
for (L j=0;j<data_M.nfeatures;j++){
bk2[j]=0;
for (L k = data_M.ptr_t[j]; k < data_M.ptr_t[j + 1]; k++)
{
L i=data_M.col_idx[k];
bk2[j]+=data_M.A_t[k]*yk[i];
}
}
for (L j=0;j<data_M.nfeatures;j++)
res+=bk2[j]*bk[j];
return res;
}
L get_nb_features(){
return data_A.get_d();
}
/* inline D get_lambda1(){return lambda1;}
inline D get_lambda2(){return lambda2;}
*/
void update_x(){
for (L i= 0; i< m_1; i++){
gradient[i]= 0;
for (L k = data_A.ptr_t[i]; k < data_A.ptr_t[i + 1];k++)
{
L j=data_A.col_idx[k];
gradient[i]+= data_A.A_t[k]*gradient_of_f_j(Ax[j],j);
}
MtMx[i]= 0;
for (L k = data_M.ptr_t[i]; k < data_M.ptr_t[i + 1];k++)
{
L j=data_M.col_idx[k];
MtMx[i]+= data_M.A_t[k]*Mx[j];
}
x[i]= prox_of_g_j(x[i]- (Mtlambda[i]+ gradient[i]+ beta*MtMx[i]- beta*Mty[i])/(beta*tau+ L_phi), beta*tau+ L_phi, i);
}
for (L i= 0; i< m_2; i++){
Ax[i]= compute_AiTx(i);
}
for (L i= 0; i< m_3; i++){
Mx[i]= compute_MiTx(i);
}
}
void update_y(){
for (L i=0; i< m_3; i++){
y[i]= prox_of_h_j(y[i]+ (lambda[i]+ beta*Mx[i]- beta*y[i])/(beta*sigma), beta*sigma, i);
}
for (L i=0; i< m_1; i++){
Mty[i]= compute_MTiTy(i);
}
}
D compute_AiTx(L i){
D res=0;
for (L k = data_A.ptr[i]; k < data_A.ptr[i + 1];k++)
{
L j=data_A.row_idx[k];
res+= data_A.A[k]*x[j];
}
return res;
}
D compute_MiTx(L i){
D res=0;
for (L k = data_M.ptr[i]; k < data_M.ptr[i + 1];k++)
{
L j=data_M.row_idx[k];
res+= data_M.A[k]*x[j];
}
return res;
}
D compute_MTiTy(L i){
D res=0;
for (L k = data_M.ptr_t[i]; k < data_M.ptr_t[i + 1];k++)
{
L j=data_M.col_idx[k];
res+= data_M.A_t[k]*y[j];
}
return res;
}
D compute_MTiTlambda(L i){
D res=0;
for (L k = data_M.ptr_t[i]; k < data_M.ptr_t[i + 1];k++)
{
L j=data_M.col_idx[k];
res+= data_M.A_t[k]*lambda[j];
}
return res;
}
void compute_function_value(){
D res= 0;
for (L i= 0; i< data_A.nfeatures; i++){
res+= value_of_g_j(x[i],i);
}
for (L i= 0; i< data_M.nsamples; i++){
res+= value_of_h_j(Mx[i],i);
}
for (L i= 0; i<data_A.nsamples; i++){
res+= value_of_f_j(Ax[i],i);
}
function_value= res;
}
void compute_infeasibility(){
D res = 0;
for (L i= 0; i< data_M.nsamples; i++){
res+= (Mx[i]- data_M.b[i])*(Mx[i]- data_M.b[i]);
}
infeas= sqrt(res);
}
void update_lambda(){
for(L j=0;j<m_3;j++)
{
lambda[j]= lambda[j]+ beta*(Mx[j]- y[j]);
}
for (L i=0; i< m_1; i++){
Mtlambda[i]= compute_MTiTlambda(i);
}
}
void Initialize(D beta_0, D val_rho, vector<D> & x0,vector<D> & y0, vector<D> & lambda0){
cout<<"start initializing"<<endl;
set_matrix_M();
set_matrix_A();
m_1=data_A.get_d();
m_2=data_A.get_n();
m_3=data_M.get_n();
cout<<"m_1="<<m_1<<endl;
cout<<"m_2="<<m_2<<endl;
cout<<"m_3="<<m_3<<endl;
beta=beta_0;
//tau= data_A.nsamples;
tau= 1.02*compute_lambda_max_M(10);
sigma= 1;
rho=val_rho;
x.resize(m_1,0);
old_x.resize(m_1,0);
y.resize(m_3,0);
old_y.resize(m_3,0);
lambda.resize(m_3,0);
old_lambda.resize(m_3,0);
for(L i=0;i<m_1;i++){
x[i]=x0[i];
}
for(L j=0;j<m_3;j++){
y[j]=y0[j];
}
for(L j=0;j<m_3;j++){
lambda[j]=lambda0[j];
}
Ax.clear();
Ax.resize(m_2,0);
Mx.clear();
Mx.resize(m_3,0);
Mty.clear();
Mty.resize(m_1,0);
Mtlambda.clear();
Mtlambda.resize(m_1,0);
gradient.clear();
gradient.resize(m_1,0);
MtMx.clear();
MtMx.resize(m_1,0);
L_phi= 0;
set_L_phi();
cout<< "L_phi= "<< L_phi << " beta= "<< beta<< " rho= "<< rho<< " tau= "<< tau<< " sigma= "<< sigma<<endl;
}
void reset_everything(){
beta*=rho;
}
inline void compute_and_record_res(){
if(nb_outer_iters%print_every_N_ADMM==0){
compute_function_value();
compute_infeasibility();
cout<<setprecision(9)<<"Iteration: "<<nb_outer_iters<<"; time="<<running_time_ADMM<< "; function value="<<function_value<< "; infeasibility="<< infeas<< endl;
samp_ADMM<<setprecision(9)<<nb_outer_iters<<" "<<running_time_ADMM<<" "<< function_value<<" "<< infeas<< endl;
}
}
void ADMM_solve_with_Linear(D beta_0, D val_rho,vector<D> & x0,vector<D> & y0, vector<D> & lambda0, L max_nb_outer, L p_N_1, string filename1, D time){
Initialize(beta_0,val_rho, x0, y0, lambda0);
nb_outer_iters=0;
//string sampname2= ALGparam.data_dir +"/results/L_Katyusha_"+filename2;
//filename1= ALGparam.data_dir +"/results/ADMM_"+filename1;
filename1= "results/ADMM_"+filename1;
samp_ADMM.open(filename1.c_str());
running_time_ADMM=0;
print_every_N_ADMM=p_N_1;
compute_and_record_res();
D start;
D res_x, res_y, res_l;
/*
for(L i=0;i<m_3;i++){
old_lambda[i]=lambda[i];
}
*/
while(nb_outer_iters<max_nb_outer){
//rescale();
for(L i=0;i<m_1;i++){
old_x[i]=x[i];
}
for(L i=0;i<m_3;i++){
old_y[i]=y[i];
}
for(L i=0;i<m_3;i++){
old_lambda[i]=lambda[i];
}
start = std::clock();
update_x();
update_y();
update_lambda();
nb_outer_iters++;
running_time_ADMM+=( std::clock() - start ) / (double) CLOCKS_PER_SEC;
compute_and_record_res();
/*
res_x= 0;
for(L i=0;i<m_1;i++){
res_x+= (old_x[i]- x[i])*(old_x[i]- x[i]);
}
res_y= 0;
for(L i=0;i<m_3;i++){
res_y= (old_y[i]- y[i])*(old_y[i]- y[i]);
}
res_l= 0;
for(L i=0;i<m_3;i++){
res_l= (old_lambda[i]- lambda[i])*(old_lambda[i]- lambda[i]);
}
cout<< "res_x= "<< res_x<< " res_y= "<< res_y<< " res_l= "<< res_l<< endl;
system("pause");
*/
start = std::clock();
reset_everything();
running_time_ADMM+=( std::clock() - start ) / (double) CLOCKS_PER_SEC;
if (running_time_ADMM> time){
break;
}
}
}
};
#endif /* MIN_SMOOTH_CONVEX_H */
| {
"alphanum_fraction": 0.5470835278,
"avg_line_length": 21.092519685,
"ext": "h",
"hexsha": "1e42c801399a8f17b690fe0eb72ac2d72c6e1f77",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2021-01-15T04:23:24.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-01-15T04:23:24.000Z",
"max_forks_repo_head_hexsha": "3d5d8c281411fdfd6379480429a1fbb9b21464ff",
"max_forks_repo_licenses": [
"BSD-Source-Code"
],
"max_forks_repo_name": "lifei16/supplementary_code",
"max_forks_repo_path": "IPALM/LADMM.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "3d5d8c281411fdfd6379480429a1fbb9b21464ff",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-Source-Code"
],
"max_issues_repo_name": "lifei16/supplementary_code",
"max_issues_repo_path": "IPALM/LADMM.h",
"max_line_length": 162,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "3d5d8c281411fdfd6379480429a1fbb9b21464ff",
"max_stars_repo_licenses": [
"BSD-Source-Code"
],
"max_stars_repo_name": "lifei16/supplementary_code",
"max_stars_repo_path": "IPALM/LADMM.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 3732,
"size": 10715
} |
/**
*
* @file qwrapper_spotrf.c
*
* PLASMA core_blas quark wrapper
* PLASMA is a software package provided by Univ. of Tennessee,
* Univ. of California Berkeley and Univ. of Colorado Denver
*
* @version 2.6.0
* @author Hatem Ltaief
* @author Mathieu Faverge
* @author Jakub Kurzak
* @date 2010-11-15
* @generated s Tue Jan 7 11:44:56 2014
*
**/
#include <lapacke.h>
#include "common.h"
/***************************************************************************//**
*
**/
void QUARK_CORE_spotrf(Quark *quark, Quark_Task_Flags *task_flags,
PLASMA_enum uplo, int n, int nb,
float *A, int lda,
PLASMA_sequence *sequence, PLASMA_request *request,
int iinfo)
{
DAG_CORE_POTRF;
QUARK_Insert_Task(quark, CORE_spotrf_quark, task_flags,
sizeof(PLASMA_enum), &uplo, VALUE,
sizeof(int), &n, VALUE,
sizeof(float)*nb*nb, A, INOUT,
sizeof(int), &lda, VALUE,
sizeof(PLASMA_sequence*), &sequence, VALUE,
sizeof(PLASMA_request*), &request, VALUE,
sizeof(int), &iinfo, VALUE,
0);
}
/***************************************************************************//**
*
**/
#if defined(PLASMA_HAVE_WEAK)
#pragma weak CORE_spotrf_quark = PCORE_spotrf_quark
#define CORE_spotrf_quark PCORE_spotrf_quark
#endif
void CORE_spotrf_quark(Quark *quark)
{
PLASMA_enum uplo;
int n;
float *A;
int lda;
PLASMA_sequence *sequence;
PLASMA_request *request;
int iinfo;
int info;
quark_unpack_args_7(quark, uplo, n, A, lda, sequence, request, iinfo);
info = LAPACKE_spotrf_work(
LAPACK_COL_MAJOR,
lapack_const(uplo),
n, A, lda);
if (sequence->status == PLASMA_SUCCESS && info != 0)
plasma_sequence_flush(quark, sequence, request, iinfo+info);
}
| {
"alphanum_fraction": 0.5350790514,
"avg_line_length": 29.7647058824,
"ext": "c",
"hexsha": "3ade8abb0bd9c50bb0cc4d811bae9a26ef2a53f5",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "zhuangsc/Plasma-ompss1",
"max_forks_repo_path": "core_blas-qwrapper/qwrapper_spotrf.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "zhuangsc/Plasma-ompss1",
"max_issues_repo_path": "core_blas-qwrapper/qwrapper_spotrf.c",
"max_line_length": 80,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "zhuangsc/Plasma-ompss1",
"max_stars_repo_path": "core_blas-qwrapper/qwrapper_spotrf.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 527,
"size": 2024
} |
/*
Copyright (C) 2019-2020 JingWeiZhangHuai <jingweizhanghuai@163.com>
Licensed under the Apache License, Version 2.0; you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
#include <cblas.h>
#include "morn_tensor.h"
void DeconvTensorToMatData(MTensor *tns,int bc,float *mdata,int knl_height,int knl_width,int y_stride,int x_stride)
{
int height = tns->height;
int width = tns->width;
int channel= tns->channel;
int out_width = width*x_stride;
int out_height=height*y_stride;
int mwidth = knl_height*knl_width*channel+1;
int mheight= out_height*out_width;
memset(mdata,0,mwidth*mheight*sizeof(float));
float *tdata = tns->data[bc];
int tsize = tns->height*tns->width;
int i,j,c;
for(j=0;j<mheight;j++)
{
int n=j/out_width-knl_height/2;
int m=j%out_width-knl_width/2;
for(i=0;i<mwidth-1;i+=channel)
{
int h= i/(knl_width*channel) +n;if(h%y_stride!=0) continue;h=h/y_stride;
int w=(i%(knl_width*channel))/channel+m;if(w%x_stride!=0) continue;w=w/x_stride;
if(h<0)h=0;else if(h>=height)h=height-1;
if(w<0)w=0;else if(w>= width)w= width-1;
for(c=0;c<channel;c++)
mdata[(j*mwidth)+i+c]=tdata[c*tsize+h*width+w];
}
mdata[(j*mwidth)+mwidth-1]=1.0f;
}
}
void DeconvMatDataToTensor(float *mdata,MTensor *tns,int bc,int knl_height,int knl_width,int y_stride,int x_stride)
{
int height = tns->height;
int width = tns->width;
int channel= tns->channel;
int out_width = width*x_stride;
int out_height=height*y_stride;
int mwidth = knl_height*knl_width*channel+1;
int mheight= out_height*out_width;
float *tdata = tns->data[bc];
int tsize = tns->height*tns->width;
int i,j,c;
for(j=0;j<mheight;j++)
{
int n=j/out_width-knl_height/2;
int m=j%out_width-knl_width/2;
for(i=0;i<mwidth-1;i+=channel)
{
int h= i/(knl_width*channel) +n;if(h%y_stride!=0) continue;h=h/y_stride;
int w=(i%(knl_width*channel))/channel+m;if(w%x_stride!=0) continue;w=w/x_stride;
if(h<0)h=0;else if(h>=height)h=height-1;
if(w<0)w=0;else if(w>= width)w= width-1;
for(c=0;c<channel;c++)
tdata[c*tsize+h*width+w]+=mdata[(j*mwidth)+i+c];
}
mdata[(j*mwidth)+mwidth-1]=1.0f;
}
}
struct TensorDeconvPara
{
MLayer *prev;
int knl_num;
int knl_height;
int knl_width;
int x_stride;
int y_stride;
int res_valid;
float rate;
float decay;
float momentum;
};
void *mTensorDeconvPara(MFile *ini,char *name)
{
struct TensorDeconvPara *para = (struct TensorDeconvPara *)mMalloc(sizeof(struct TensorDeconvPara));
char *value = mINIRead(ini,name,"prev");
para->prev = mNetworkLayer(ini,value);
mException((para->prev == NULL),EXIT,"invalid prev");
para->res_valid = (strcmp("Input",mLayerType(para->prev))!=0);
value = mINIRead(ini,name,"knl_num");
if(value != NULL) para->knl_num= atoi(value);else para->knl_num= 1;
value = mINIRead(ini,name,"knl_height");
if(value != NULL) para->knl_height= atoi(value);else para->knl_height= 1;
value = mINIRead(ini,name,"knl_width");
if(value != NULL) para->knl_width= atoi(value);else para->knl_width= 1;
value = mINIRead(ini,name,"x_stride");
if(value != NULL) para->x_stride= atoi(value);else para->x_stride= 1;
value = mINIRead(ini,name,"y_stride");
if(value != NULL) para->y_stride= atoi(value);else para->y_stride= 1;
value = mINIRead(ini,name,"rate");
if(value != NULL) para->rate = atof(value);
else
{
value = mINIRead(ini,"para","rate");
if(value != NULL) para->rate = atof(value);
else para->rate = 0.001;
}
value = mINIRead(ini,name,"decay");
if(value != NULL) para->decay = atof(value);
else
{
value = mINIRead(ini,"para","decay");
if(value != NULL) para->decay = atof(value);
else para->decay = 0.01;
}
mException((para->decay<0.0f)||(para->decay>=1.0f),EXIT,"invalid para decay");
value = mINIRead(ini,name,"momentum");
if(value != NULL) para->momentum = atof(value);
else
{
value = mINIRead(ini,"para","momentum");
if(value != NULL) para->momentum = atof(value);
else para->momentum = 0.9;
}
return para;
}
struct HandleTensorDeconv
{
float *mat;
float *kernel;
float *update;
};
void endTensorDeconv(void *info)
{
struct HandleTensorDeconv *handle = (struct HandleTensorDeconv *)info;
if(handle->mat != NULL) mFree(handle->mat);
if(handle->kernel!= NULL) mFree(handle->kernel);
if(handle->update!= NULL) mFree(handle->update);
}
#define HASH_TensorDeconv 0x9087d39c
void TensorDeconvSet(MLayer *layer)
{
if(layer->state != DFLT) return;
struct TensorDeconvPara *para = (struct TensorDeconvPara *)(layer->para);
MTensor *in = para->prev->tns;
MTensor *res= para->prev->res;
MTensor *out=layer->tns;
MHandle *hdl=mHandle(out,TensorDeconv);
struct HandleTensorDeconv *handle = (struct HandleTensorDeconv *)(hdl->handle);
int out_height= in->height*para->y_stride;
int out_width = in->width *para->x_stride;
int mheight = (out_height*out_width);
int mwidth = para->knl_height*para->knl_width*in->channel+1;
int data_size = para->knl_num*mwidth;
mTensorRedefine(out,in->batch,para->knl_num,out_height,out_width,NULL);
if(morn_network_flag == MORN_TRAIN)
{
if(INVALID_TENSOR(res)) mTensorRedefine(res,in->batch,in->channel,in->height,in->width,in->data);
else mTensorRedefine(res,in->batch,in->channel,in->height,in->width,NULL);
if(handle->update != NULL) mFree(handle->update);
handle->update =(float *)mMalloc(data_size*sizeof(float));
memset(handle->update,0,data_size*sizeof(float));
}
if(handle->kernel !=NULL) mFree(handle->kernel);
handle->kernel = (float *)mMalloc(data_size*sizeof(float));
if(morn_network_parafile==NULL)
{
float scale = sqrt(2.0f/mwidth);
for(int i=0;i<data_size;i++)
handle->kernel[i] = scale*mNormalRand(0.0f,1.0f);
}
else
mNetworkParaRead(layer,"kernel",handle->kernel,data_size*sizeof(float));
if(handle->mat!=NULL) mFree(handle->mat);
handle->mat = (float *)mMalloc(mheight*mwidth*sizeof(float));
hdl->valid = 1;
}
void mTensorDeconvForward(MLayer *layer)
{
mException(INVALID_POINTER(layer),EXIT,"invalid input");
mException(strcmp("Deconv",mLayerType(layer)),EXIT,"invalid layer type");
struct TensorDeconvPara *para = (struct TensorDeconvPara *)(layer->para);
MTensor *in = para->prev->tns;
MTensor *out=layer->tns;
TensorDeconvSet(layer);
MHandle *hdl=mHandle(out,TensorDeconv);
struct HandleTensorDeconv *handle = (struct HandleTensorDeconv *)(hdl->handle);
int mheight = (out->height*out->width);
int mwidth = para->knl_height*para->knl_width*in->channel+1;
float *kernel_data= handle->kernel;
float *in_data = handle->mat;
for(int b=0;b<in->batch;b++)
{
DeconvTensorToMatData(in,b,in_data,para->knl_height,para->knl_width,para->y_stride,para->x_stride);
float *out_data = out->data[b];
in_data[mwidth-1]=1.0f;
cblas_sgemm(CblasRowMajor,CblasNoTrans,CblasTrans,
para->knl_num,mheight,mwidth,
1.0f,
kernel_data,mwidth,
in_data,mwidth,
0.0f, out_data,mheight);
}
layer->state = MORN_FORWARD;
}
void mTensorDeconvBackward(MLayer *layer)
{
mException(INVALID_POINTER(layer),EXIT,"invalid input");
mException(strcmp("Deconv",mLayerType(layer)),EXIT,"invalid layer type");
struct TensorDeconvPara *para = (struct TensorDeconvPara *)(layer->para);
MTensor *in = para->prev->tns;
MTensor *res= para->prev->res;
MTensor *out=layer->res;
MHandle *hdl=mHandle(layer->tns,TensorDeconv);
struct HandleTensorDeconv *handle = (struct HandleTensorDeconv *)(hdl->handle);
mException((hdl->valid == 0),EXIT,"no forward operate");
int mheight = (out->height*out->width);
int mwidth = para->knl_height*para->knl_width*in->channel+1;
float *kernel_data= handle->kernel;
float *update_data= handle->update;
float * in_data= handle->mat;
float * res_data= handle->mat;
mNetworkParaWrite(layer,"kernel",kernel_data,para->knl_num*mwidth*sizeof(float));
for(int b=0;b<in->batch;b++)
{
DeconvTensorToMatData(in,b,in_data,para->knl_height,para->knl_width,para->y_stride,para->x_stride);
float *out_data = out->data[b];
in_data[mwidth-1]=1.0f;
cblas_sgemm(CblasRowMajor,CblasNoTrans,CblasNoTrans,
para->knl_num,mwidth,mheight,
1.0f,
out_data,mheight,
in_data,mwidth,
(b==0)?para->momentum:1.0f,
update_data,mwidth);
}
cblas_saxpby(para->knl_num*mwidth,
(0.0f-(para->rate/(float)(in->batch))),update_data,1,
(1.0f-(para->decay*para->rate)) ,kernel_data,1);
if(para->res_valid==0) return;
if(para->prev->state == MORN_FORWARD)
{
for(int b=0;b<res->batch;b++)
memset(res->data[b],0,in->height*in->width*in->channel*sizeof(float));
para->prev->state = MORN_BACKWARD;
}
for(int b=0;b<in->batch;b++)
{
float *out_data = out->data[b];
cblas_sgemm(CblasRowMajor,CblasTrans,CblasNoTrans,
mheight,mwidth,para->knl_num,
1.0f,
out_data,mheight,
kernel_data,mwidth,
0.0, res_data,mwidth);
DeconvMatDataToTensor(res_data,res,b,para->knl_height,para->knl_width,para->y_stride,para->x_stride);
}
}
| {
"alphanum_fraction": 0.6086755884,
"avg_line_length": 33.236196319,
"ext": "c",
"hexsha": "2eb044f8852e81ab201ad0c353e86cdb6d6879f4",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2021-06-23T08:08:02.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-06-23T08:08:02.000Z",
"max_forks_repo_head_hexsha": "fa4f0aae3d7c22f8643665c4bc1297b14b50c9d0",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "Shaka0723/Morn",
"max_forks_repo_path": "src/deep_learning/morn_tensor_deconv.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "fa4f0aae3d7c22f8643665c4bc1297b14b50c9d0",
"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": "Shaka0723/Morn",
"max_issues_repo_path": "src/deep_learning/morn_tensor_deconv.c",
"max_line_length": 501,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "fa4f0aae3d7c22f8643665c4bc1297b14b50c9d0",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "Shaka0723/Morn",
"max_stars_repo_path": "src/deep_learning/morn_tensor_deconv.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 3092,
"size": 10835
} |
#include "spinodal_spect.h"
#include <gsl/gsl_rng.h>
// Generate array of random numbers between 0 and 1
double *rand_ZeroToOne(int Nx, int Ny, int seed, double *random_ZeroToOne_array) {
const gsl_rng_type *T;
gsl_rng *r;
int i,
NxNy = Nx * Ny;
gsl_rng_env_setup();
T = gsl_rng_default;
r = gsl_rng_alloc(T);
gsl_rng_set(r, seed);
// Generate array of random numbers between 0 and 1
for (i = 0; i < NxNy; i++) {
random_ZeroToOne_array[i] = gsl_rng_uniform(r);
}
gsl_rng_free(r);
return random_ZeroToOne_array;
} | {
"alphanum_fraction": 0.5915492958,
"avg_line_length": 24.5769230769,
"ext": "c",
"hexsha": "a7ef702cc9eb1ccf3050ccaa4b6057f5bb403da9",
"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": "bf19ebb08527d6a10720e535cefb4492ce152d55",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "jitinnair1/hello-again-phasefield",
"max_forks_repo_path": "spinodal_binary_spectral/rand_ZeroToOne.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "bf19ebb08527d6a10720e535cefb4492ce152d55",
"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": "jitinnair1/hello-again-phasefield",
"max_issues_repo_path": "spinodal_binary_spectral/rand_ZeroToOne.c",
"max_line_length": 82,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "bf19ebb08527d6a10720e535cefb4492ce152d55",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "jitinnair1/hello-again-phasefield",
"max_stars_repo_path": "spinodal_binary_spectral/rand_ZeroToOne.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 167,
"size": 639
} |
/* specfunc/test_coulomb.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 <gsl/gsl_test.h>
#include <gsl/gsl_sf.h>
#include "test_sf.h"
#define PRINT(n) printf("%22.18g %22.18g %22.18g %22.18g\n", F[n], Fp[n], G[n], Gp[n])
#define WKB_TOL (1.0e+04 * TEST_SQRT_TOL0)
int test_coulomb(void)
{
gsl_sf_result r;
int status = 0;
int s = 0;
char message_buff[2048];
/* const int kmax = 20; */
/* double F[kmax+1], Fp[kmax+1], G[kmax+1], Gp[kmax+1]; */
gsl_sf_result F, Fp, G, Gp;
double Fe, Ge;
double lam_min;
double lam_F;
double eta, x;
int k_G;
TEST_SF(s, gsl_sf_hydrogenicR_1_e, (3.0, 2.0, &r), 0.025759948256148471036, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hydrogenicR_1_e, (3.0, 10.0, &r), 9.724727052062819704e-13, TEST_TOL1, GSL_SUCCESS);
status += s;
TEST_SF(s, gsl_sf_hydrogenicR_e, (4, 1, 3.0, 0.0, &r), 0.0, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hydrogenicR_e, (4, 0, 3.0, 2.0, &r), -0.03623182256981820062, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hydrogenicR_e, (4, 1, 3.0, 2.0, &r), -0.028065049083129581005, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hydrogenicR_e, (4, 2, 3.0, 2.0, &r), 0.14583027278668431009, TEST_TOL0, GSL_SUCCESS);
status += s;
TEST_SF(s, gsl_sf_hydrogenicR_e, (100, 0, 3.0, 2.0, &r), -0.00007938950980052281367, TEST_TOL3, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hydrogenicR_e, (100, 10, 3.0, 2.0, &r), 7.112823375353605977e-12, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hydrogenicR_e, (100, 90, 3.0, 2.0, &r), 5.845231751418131548e-245, TEST_TOL2, GSL_SUCCESS);
status += s;
lam_F = 0.0;
k_G = 0;
eta = 1.0;
x = 5.0;
gsl_sf_coulomb_wave_FG_e(eta, x, lam_F, k_G, &F, &Fp, &G, &Gp, &Fe, &Ge);
s = 0;
message_buff[0] = 0;
s += test_sf_check_result(message_buff, F, 0.6849374120059439677, TEST_TOL3);
s += test_sf_check_result(message_buff, Fp, -0.7236423862556063963, TEST_TOL3);
s += test_sf_check_result(message_buff, G, -0.8984143590920205487, TEST_TOL3);
s += test_sf_check_result(message_buff, Gp, -0.5108047585190350106, TEST_TOL3);
printf("%s", message_buff);
gsl_test(s," gsl_sf_coulomb_wave_FG_e(1.0, 5.0, lam_F=0, lam_G=0)");
status += s;
lam_F = 10.0;
k_G = 2;
eta = 1.0;
x = 5.0;
gsl_sf_coulomb_wave_FG_e(eta, x, lam_F, k_G, &F, &Fp, &G, &Gp, &Fe, &Ge);
s = 0;
message_buff[0] = 0;
s += test_sf_check_result(message_buff, F, 0.0006423773354915823698, TEST_TOL3);
s += test_sf_check_result(message_buff, Fp, 0.0013299570958719702545, TEST_TOL3);
s += test_sf_check_result(message_buff, G, 33.27615734455096130, TEST_TOL3);
s += test_sf_check_result(message_buff, Gp, -45.49180102261540580, TEST_TOL3);
printf("%s", message_buff);
gsl_test(s," gsl_sf_coulomb_wave_FG_e(1.0, 5.0, lam_F=10, lam_G=8)");
status += s;
lam_F = 4.0;
k_G = 2;
eta = 50.0;
x = 120.0;
gsl_sf_coulomb_wave_FG_e(eta, x, lam_F, k_G, &F, &Fp, &G, &Gp, &Fe, &Ge);
s = 0;
message_buff[0] = 0;
s += test_sf_check_result(message_buff, F, 0.0735194711823798495, TEST_TOL3);
s += test_sf_check_result(message_buff, Fp, 0.6368149124126783325, TEST_TOL3);
/*
s += test_sf_check_result(message_buff, G, , TEST_TOL5);
s += test_sf_check_result(message_buff, Gp, , TEST_TOL5);
*/
printf("%s", message_buff);
gsl_test(s," gsl_sf_coulomb_wave_FG_e(50.0, 120.0, lam_F=4, lam_G=2)");
status += s;
lam_F = 0.0;
k_G = 0;
eta = -1000.0;
x = 1.0;
gsl_sf_coulomb_wave_FG_e(eta, x, lam_F, k_G, &F, &Fp, &G, &Gp, &Fe, &Ge);
s = 0;
message_buff[0] = 0;
s += test_sf_check_result(message_buff, F, 9.68222518991341e-02, TEST_TOL3);
s += test_sf_check_result(message_buff, Fp, 5.12063396274631e+00, TEST_TOL3);
s += test_sf_check_result(message_buff, G, 1.13936784379472e-01, TEST_TOL3);
s += test_sf_check_result(message_buff, Gp, -4.30243486522438e+00, TEST_TOL3);
printf("%s", message_buff);
gsl_test(s, " gsl_sf_coulomb_wave_FG_e(-1000.0, 1.0, lam_F=0, lam_G=0)");
status += s;
lam_min = 0.0;
eta = -50.0;
x = 5.0;
gsl_sf_coulomb_wave_FG_e(eta, x, lam_F, k_G, &F, &Fp, &G, &Gp, &Fe, &Ge);
s = 0;
message_buff[0] = 0;
s += test_sf_check_result(message_buff, F, 1.52236975714236e-01, TEST_TOL3);
s += test_sf_check_result(message_buff, Fp, 2.03091041166137e+00, TEST_TOL3);
s += test_sf_check_result(message_buff, G, 4.41680690236251e-01, TEST_TOL3);
s += test_sf_check_result(message_buff, Gp, -6.76485374766869e-01, TEST_TOL3);
printf("%s", message_buff);
gsl_test(s, " gsl_sf_coulomb_wave_FG_e(-50.0, 5.0, lam_F=0, lam_G=0)");
status += s;
lam_min = 0.0;
eta = -50.0;
x = 1000.0;
gsl_sf_coulomb_wave_FG_e(eta, x, lam_F, k_G, &F, &Fp, &G, &Gp, &Fe, &Ge);
s = 0;
message_buff[0] = 0;
s += test_sf_check_result(message_buff, F, -0.2267212182760888523, TEST_TOL3);
s += test_sf_check_result(message_buff, Fp, -0.9961306810018401525, TEST_TOL3);
s += test_sf_check_result(message_buff, G, -0.9497684438900352186, TEST_TOL3);
s += test_sf_check_result(message_buff, Gp, 0.2377656295411961399, TEST_TOL3);
printf("%s", message_buff);
gsl_test(s, " gsl_sf_coulomb_wave_FG_e(-50.0, 1000.0, lam_F=0, lam_G=0)");
status += s;
lam_F = 10.0;
k_G = 0;
eta = -50.0;
x = 5.0;
gsl_sf_coulomb_wave_FG_e(eta, x, lam_F, k_G, &F, &Fp, &G, &Gp, &Fe, &Ge);
s = 0;
message_buff[0] = 0;
s += test_sf_check_result(message_buff, F, -3.681143602184922e-01, TEST_TOL3);
s += test_sf_check_result(message_buff, Fp, 1.338467510317215e+00, TEST_TOL3);
s += test_sf_check_result(message_buff, G, 3.315883246109351e-01, TEST_TOL3);
s += test_sf_check_result(message_buff, Gp, 1.510888628136180e+00, TEST_TOL3);
printf("%s", message_buff);
gsl_test(s, " gsl_sf_coulomb_wave_FG_e(-50.0, 5.0, lam_F=10, lam_G=10)");
status += s;
lam_F = 0.0;
k_G = 0;
eta = -4.0;
x = 5.0;
gsl_sf_coulomb_wave_FG_e(eta, x, lam_F, k_G, &F, &Fp, &G, &Gp, &Fe, &Ge);
s = 0;
message_buff[0] = 0;
s += test_sf_check_result(message_buff, F, 4.078627230056172e-01, TEST_TOL3);
s += test_sf_check_result(message_buff, Fp, 1.098212336357310e+00, TEST_TOL3);
s += test_sf_check_result(message_buff, G, 6.743270353832442e-01, TEST_TOL3);
s += test_sf_check_result(message_buff, Gp, -6.361104272804447e-01, TEST_TOL3);
printf("%s", message_buff);
gsl_test(s, " gsl_sf_coulomb_wave_FG_e(-4.0, 5.0, lam_F=0, lam_G=0");
status += s;
lam_F = 3.0;
k_G = 0;
eta = -4.0;
x = 5.0;
gsl_sf_coulomb_wave_FG_e(eta, x, lam_F, k_G, &F, &Fp, &G, &Gp, &Fe, &Ge);
s = 0;
message_buff[0] = 0;
s += test_sf_check_result(message_buff, F, -2.568630935581323e-01, TEST_TOL3);
s += test_sf_check_result(message_buff, Fp, 1.143229422014827e+00, TEST_TOL3);
s += test_sf_check_result(message_buff, G, 7.879899223927996e-01, TEST_TOL3);
s += test_sf_check_result(message_buff, Gp, 3.859905878106713e-01, TEST_TOL3);
printf("%s", message_buff);
gsl_test(s, " gsl_sf_coulomb_wave_FG_e(-4.0, 5.0, lam_F=3, lam_G=3");
status += s;
lam_F = 0.0;
k_G = 0;
eta = 1.0;
x = 2.0;
gsl_sf_coulomb_wave_FG_e(eta, x, lam_F, k_G, &F, &Fp, &G, &Gp, &Fe, &Ge);
s = 0;
message_buff[0] = 0;
s += test_sf_check_result(message_buff, F, 6.61781613832681e-01, TEST_TOL3);
s += test_sf_check_result(message_buff, Fp, 4.81557455709949e-01, TEST_TOL3);
s += test_sf_check_result(message_buff, G, 1.27577878476828e+00, TEST_TOL3);
s += test_sf_check_result(message_buff, Gp, -5.82728813097184e-01, TEST_TOL3);
printf("%s", message_buff);
gsl_test(s, " gsl_sf_coulomb_wave_FG_e(1.0, 2.0, lam_F=0, lam_G=0)");
status += s;
lam_F = 0.0;
k_G = 0;
eta = 1.0;
x = 0.5;
gsl_sf_coulomb_wave_FG_e(eta, x, lam_F, k_G, &F, &Fp, &G, &Gp, &Fe, &Ge);
s = 0;
message_buff[0] = 0;
s += test_sf_check_result(message_buff, F, 0.08315404535022023302, TEST_TOL3);
s += test_sf_check_result(message_buff, Fp, 0.22693874616222787568, TEST_TOL3);
s += test_sf_check_result(message_buff, G, 3.1060069279548875140, TEST_TOL3);
s += test_sf_check_result(message_buff, Gp, -3.549156038719924236, TEST_TOL3);
printf("%s", message_buff);
gsl_test(s, " gsl_sf_coulomb_wave_FG_e(1.0, 0.5, lam_F=0, lam_G=0)");
status += s;
lam_F = 0.5;
k_G = 0;
eta = 1.0;
x = 0.5;
gsl_sf_coulomb_wave_FG_e(eta, x, lam_F, k_G, &F, &Fp, &G, &Gp, &Fe, &Ge);
s = 0;
message_buff[0] = 0;
s += test_sf_check_result(message_buff, F, 0.04049078073829290935, TEST_TOL3);
s += test_sf_check_result(message_buff, Fp, 0.14194939168094778795, TEST_TOL3);
s += test_sf_check_result(message_buff, G, 4.720553853049677897, TEST_TOL3);
s += test_sf_check_result(message_buff, Gp, -8.148033852319180005, TEST_TOL3);
printf("%s", message_buff);
gsl_test(s, " gsl_sf_coulomb_wave_FG_e(1.0, 0.5, lam_F=0.5, lam_G=0.5)");
status += s;
lam_F = 0.1;
k_G = 0;
eta = 1.0;
x = 0.5;
gsl_sf_coulomb_wave_FG_e(eta, x, lam_F, k_G, &F, &Fp, &G, &Gp, &Fe, &Ge);
s = 0;
message_buff[0] = 0;
s += test_sf_check_result(message_buff, F, 0.07365466672379703418, TEST_TOL5);
s += test_sf_check_result(message_buff, Fp, 0.21147121807178518647, TEST_TOL5);
s += test_sf_check_result(message_buff, G, 3.306705446241024890, TEST_TOL5);
s += test_sf_check_result(message_buff, Gp, -4.082931670935696644, TEST_TOL5);
printf("%s", message_buff);
gsl_test(s, " gsl_sf_coulomb_wave_FG_e(1.0, 0.5, lam_F=0.1, lam_G=0.1)");
status += s;
lam_F = 0.0;
k_G = 0;
eta = 8.0;
x = 1.05;
gsl_sf_coulomb_wave_FG_e(eta, x, lam_F, k_G, &F, &Fp, &G, &Gp, &Fe, &Ge);
s = 0;
message_buff[0] = 0;
s += test_sf_check_result(message_buff, F, 9.882706082810274357e-09, TEST_TOL5);
s += test_sf_check_result(message_buff, Fp, 4.005167028235547770e-08, TEST_TOL5);
s += test_sf_check_result(message_buff, G, 1.333127992006686320e+07, TEST_SQRT_TOL0);
s += test_sf_check_result(message_buff, Gp, -4.715914530842402330e+07, TEST_SQRT_TOL0);
printf("%s", message_buff);
gsl_test(s, " gsl_sf_coulomb_wave_FG_e(8.0, 1.05, lam_F=0, lam_G=0)");
status += s;
lam_F = 0.1;
k_G = 0;
eta = 8.0;
x = 1.05;
gsl_sf_coulomb_wave_FG_e(eta, x, lam_F, k_G, &F, &Fp, &G, &Gp, &Fe, &Ge);
s = 0;
message_buff[0] = 0;
s += test_sf_check_result(message_buff, F, 9.611416736061987761e-09, TEST_TOL5);
s += test_sf_check_result(message_buff, Fp, 3.909628126126824140e-08, TEST_TOL5);
s += test_sf_check_result(message_buff, G, 1.365928464219262581e+07, 4.0*TEST_SQRT_TOL0);
s += test_sf_check_result(message_buff, Gp, -4.848117385783386850e+07, 4.0*TEST_SQRT_TOL0);
printf("%s", message_buff);
gsl_test(s, " gsl_sf_coulomb_wave_FG_e(8.0, 1.05, lam_F=0.1, lam_G=0.1)");
status += s;
lam_F = 0.0;
k_G = 0;
eta = 50.0;
x = 0.1;
gsl_sf_coulomb_wave_FG_e(eta, x, lam_F, k_G, &F, &Fp, &G, &Gp, &Fe, &Ge);
s = 0;
message_buff[0] = 0;
s += test_sf_check_result(message_buff, F, 2.807788027954216071e-67, TEST_TOL5);
s += test_sf_check_result(message_buff, Fp, 9.677600748751576606e-66, TEST_TOL5);
s += test_sf_check_result(message_buff, G, 5.579810686998358766e+64, TEST_SQRT_TOL0);
s += test_sf_check_result(message_buff, Gp, -1.638329512756321424e+66, TEST_SQRT_TOL0);
printf("%s", message_buff);
gsl_test(s, " gsl_sf_coulomb_wave_FG_e(50.0, 0.1, lam_F=0, lam_G=0)");
status += s;
lam_F = 0.0;
k_G = 0;
eta = 10.0;
x = 5.0;
gsl_sf_coulomb_wave_FG_e(eta, x, lam_F, k_G, &F, &Fp, &G, &Gp, &Fe, &Ge);
s = 0;
message_buff[0] = 0;
s += test_sf_check_result(message_buff, F, 1.7207454091787930614e-06, 10.0*WKB_TOL);
s += test_sf_check_result(message_buff, Fp, 3.0975994706405458046e-06, 10.0*WKB_TOL);
s += test_sf_check_result(message_buff, G, 167637.56609459967623, 10.0*WKB_TOL);
s += test_sf_check_result(message_buff, Gp, -279370.76655361803075, 10.0*WKB_TOL);
printf("%s", message_buff);
gsl_test(s, " gsl_sf_coulomb_wave_FG_e(10.0, 5.0, lam_F=0, lam_G=0)");
status += s;
lam_F = 0.0;
k_G = 0;
eta = 25.0;
x = 10.0;
gsl_sf_coulomb_wave_FG_e(eta, x, lam_F, k_G, &F, &Fp, &G, &Gp, &Fe, &Ge);
s = 0;
message_buff[0] = 0;
s += test_sf_check_result(message_buff, F, 1.5451274501076114315e-16, 5.0*WKB_TOL);
s += test_sf_check_result(message_buff, Fp, 3.1390869393378630928e-16, 5.0*WKB_TOL);
s += test_sf_check_result(message_buff, G, 1.6177129008336318136e+15, 5.0*WKB_TOL);
s += test_sf_check_result(message_buff, Gp, -3.1854062013149740860e+15, 5.0*WKB_TOL);
printf("%s", message_buff);
gsl_test(s, " gsl_sf_coulomb_wave_FG_e(25.0, 10.0, lam_F=0, lam_G=0)");
status += s;
lam_F = 0.0;
k_G = 0;
eta = 1.0;
x = 9.2;
gsl_sf_coulomb_wave_FG_e(eta, x, lam_F, k_G, &F, &Fp, &G, &Gp, &Fe, &Ge);
s = 0;
message_buff[0] = 0;
s += test_sf_check_result(message_buff, F, -0.25632012319757955655, TEST_TOL5);
s += test_sf_check_result(message_buff, Fp, 0.91518792286724220370, TEST_TOL5);
s += test_sf_check_result(message_buff, G, 1.03120585918973466110, TEST_SQRT_TOL0);
s += test_sf_check_result(message_buff, Gp, 0.21946326717491250193, TEST_SQRT_TOL0);
printf("%s", message_buff);
gsl_test(s, " gsl_sf_coulomb_wave_FG_e(1.0, 9.2, lam_F=0, lam_G=0)");
status += s;
lam_F = 0.0;
eta = 10.0;
x = 10.0;
gsl_sf_coulomb_wave_FG_e(eta, x, lam_F, k_G, &F, &Fp, &G, &Gp, &Fe, &Ge);
s = 0;
message_buff[0] = 0;
s += test_sf_check_result(message_buff, F, 0.0016262711250135878249, WKB_TOL);
s += test_sf_check_result(message_buff, Fp, 0.0017060476320792806014, WKB_TOL);
s += test_sf_check_result(message_buff, G, 307.87321661090837987, WKB_TOL);
s += test_sf_check_result(message_buff, Gp, -291.92772380826822871, WKB_TOL);
printf("%s", message_buff);
gsl_test(s, " gsl_sf_coulomb_wave_FG_e(10.0, 10.0, lam_F=0, lam_G=0)");
status += s;
lam_F = 0.0;
eta = 100.0;
x = 1.0;
gsl_sf_coulomb_wave_FG_e(eta, x, lam_F, k_G, &F, &Fp, &G, &Gp, &Fe, &Ge);
s = 0;
message_buff[0] = 0;
s += test_sf_check_result(message_buff, F, 8.999367996930662705e-126, 10.0*WKB_TOL);
s += test_sf_check_result(message_buff, Fp, 1.292746745757069321e-124, 10.0*WKB_TOL);
s += test_sf_check_result(message_buff, G, 3.936654148133683610e+123, 10.0*WKB_TOL);
s += test_sf_check_result(message_buff, Gp, -5.456942268061526371e+124, 10.0*WKB_TOL);
printf("%s", message_buff);
gsl_test(s, " gsl_sf_coulomb_wave_FG_e(100.0, 1.0, lam_F=0, lam_G=0)");
status += s;
/* compute F_1(eta=0,x=3.25), F'_1 and G_1(eta=0,x=3.25), G'_1 */
lam_F = 1.0;
eta = 0.0;
x = 3.25;
k_G = 0;
gsl_sf_coulomb_wave_FG_e(eta, x, lam_F, k_G, &F, &Fp, &G, &Gp, &Fe, &Ge);
s = 0;
message_buff[0] = 0;
s += test_sf_check_result(message_buff, F, sin(x)/x - cos(x), TEST_TOL3);
s += test_sf_check_result(message_buff, Fp, -sin(x)/(x*x) + cos(x)/x +sin(x), TEST_TOL3);
s += test_sf_check_result(message_buff, G, cos(x)/x + sin(x), TEST_TOL3);
s += test_sf_check_result(message_buff, Gp, -cos(x)/(x*x) - sin(x)/x + cos(x), TEST_TOL3);
printf("%s", message_buff);
gsl_test(s, " gsl_sf_coulomb_wave_FG_e(3.25, 0.0, lam_F=1, lam_G=1)");
status += s;
/* compute F_1(eta=0,x=3.25), F'_1 and G_0(eta=0,x=3.25), G'_0 */
lam_F = 1.0;
eta = 0.0;
x = 3.25;
k_G = 1;
gsl_sf_coulomb_wave_FG_e(eta, x, lam_F, k_G, &F, &Fp, &G, &Gp, &Fe, &Ge);
s = 0;
message_buff[0] = 0;
s += test_sf_check_result(message_buff, F, sin(x)/x - cos(x), TEST_TOL3);
s += test_sf_check_result(message_buff, Fp, -sin(x)/(x*x) + cos(x)/x +sin(x), TEST_TOL3);
s += test_sf_check_result(message_buff, G, cos(x), TEST_TOL3);
s += test_sf_check_result(message_buff, Gp, -sin(x), TEST_TOL3);
printf("%s", message_buff);
gsl_test(s, " gsl_sf_coulomb_wave_FG_e(3.25, 0.0, lam_F=1, lam_G=0)");
status += s;
return status;
}
| {
"alphanum_fraction": 0.6721193168,
"avg_line_length": 40.2615012107,
"ext": "c",
"hexsha": "85dff620dd87fe27c6526db3c3d44fe40d2ca28e",
"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/specfunc/test_coulomb.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/specfunc/test_coulomb.c",
"max_line_length": 112,
"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/specfunc/test_coulomb.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": 7024,
"size": 16628
} |
//A one-stop wrapper for Quadrature calculations
//https://scicomp.stackexchange.com/questions/20786/c-library-for-numerical-intergration-quadrature
#ifndef __FIXEDPOINT_QUADRATURE_H__
#define __FIXEDPOINT_QUADRATURE_H__
#include <iostream>
#include <cmath>
#include <functional>
#include <memory>
#include <utility>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_integration.h>
template < typename F >
class gsl_fixedpoint_quad
{
protected:
F f;
int limit;
std::unique_ptr < gsl_integration_glfixed_table,
std::function < void(gsl_integration_glfixed_table*) >
> workspace;
static double gsl_wrapper(double x, void * p)
{
gsl_fixedpoint_quad * t = reinterpret_cast<gsl_fixedpoint_quad*>(p);
return t->f(x);
}
public:
gsl_fixedpoint_quad(F f, int limit)
: f(f)
, limit(limit)
, workspace(gsl_integration_glfixed_table_alloc(limit), gsl_integration_glfixed_table_free)
{}
virtual ~gsl_fixedpoint_quad(){};
double integrate(double min, double max)
{
gsl_function gsl_f;
gsl_f.function = &gsl_wrapper;
gsl_f.params = this;
return gsl_integration_glfixed ( &gsl_f, min, max, workspace.get());
}
};
template < typename F >
double GSLFixedPointQuadrature(F func,
std::pair<double,double> const& range,
int limit = 5)
{
return gsl_fixedpoint_quad<F>(func, limit).integrate(range.first, range.second);
}
#endif //__FIXEDPOINT_QUADRATURE_H__
| {
"alphanum_fraction": 0.6368068251,
"avg_line_length": 28.2931034483,
"ext": "h",
"hexsha": "3881ab8aa90c4443ff1112161bc131d1270c4a77",
"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": "e946b921f18b480cb8b1c4fe6de4a27c8b6e843a",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "muhammadhasyim/pyglasstools",
"max_forks_repo_path": "pyglasstools/irvingkirkwood/cgfunc/FixedPointQuadrature.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "e946b921f18b480cb8b1c4fe6de4a27c8b6e843a",
"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": "muhammadhasyim/pyglasstools",
"max_issues_repo_path": "pyglasstools/irvingkirkwood/cgfunc/FixedPointQuadrature.h",
"max_line_length": 103,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "e946b921f18b480cb8b1c4fe6de4a27c8b6e843a",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "muhammadhasyim/pyglasstools",
"max_stars_repo_path": "pyglasstools/irvingkirkwood/cgfunc/FixedPointQuadrature.h",
"max_stars_repo_stars_event_max_datetime": "2022-03-09T05:42:00.000Z",
"max_stars_repo_stars_event_min_datetime": "2022-03-09T05:42:00.000Z",
"num_tokens": 371,
"size": 1641
} |
/*
* Copyright (c) 2018-2021 Aleksas Mazeliauskas, Stefan Floerchinger,
* Eduardo Grossi, and Derek Teaney
* All rights reserved.
*
* FastReso is distributed under MIT license;
* see the LICENSE file that should be present in the root
* of the source distribution, or alternately available at:
* https://github.com/amazeliauskas/FastReso/
*/
#ifndef FASTRESO_TFastReso_h
#define FASTRESO_TFastReso_h
#include <fstream>
#include <memory>
#include <map>
#include <vector>
#include <string>
#include <gsl/gsl_integration.h>
// The class storing the properties of particles and their irreducible distrubtion
// function components f_i. Printing out routines are also defined there.
#include "TParticle.h"
// List of parameters controlling the momentum discretization of irreducible components
// See also TParticle class definition
#include "grid_params.h"
//! TFastReso class is the top wrapper class of the fast freeze-out implementation.
class TFastReso {
public:
int fParticleNumber;
//! reads the inputfile of resonances and creates TParticle entry in fParticleData vector.
//! This routine should be edited by the user to match their input file format.
//! Currently accepted format is (sstr is a string stream from the input file) is the one used
//! in particle.data file in THERMINATOR 2 [arXiv:1102.0273]
//! Name Mass Gamma Sppin Isospin I3 Nq Ns Naq Nas Nc Nac PDGCode;
//! Lines starting with '#' are ignored.
virtual void read_particles_data(std::string inputname, std::string comps, bool verbose=false) = 0;
//! The function call to initialized the particle distribution functions in fParticleData. Input parameters
//! are the freeze-out temperature, chemical potential and (optionally), speed of sound (only needed for bulk perturbations).
virtual void do_thermal(double Tfo, double MuB=0, double MuI3=0, double MuS=0, double MuC=0, double Cs2=0.14) = 0;
//! Read in the input file of resonance decays and perfom the decays on the fly. It is important that decays
//! are mass ordered to included all feeddown contributions to lower mass resonances.
//! The table format is the same as decays.data in THERMINATOR 2 [arXiv:1102.0273]
//! Father Child1 Child2 (optional Child3) BranchingRatio ClebschGordanCoeff
//! Note that ClebschGordanCoeff term is 0 or 1 identifying if the branching ration needs
//! to be reweighted by actual Clebsch Gordon coefficients.
virtual void do_decays(std::string inputname, bool verbose=false) = 0;
public:
//TFastReso(std::string comps);
//! routine to get the pointer to TParticle class for a particle particle name"
int getNumberOfParticles(){return fParticleNumber;};
//virtual TParticle * getParticle(std::string name);
//virtual TParticle * getParticle(int i);
};
// Speed of sound squared as a function of temperature T=x in GeV
inline double cs2FluiduM(double x) {
return (x*x*(0.0010461910330715387 + x*(-0.016997351850612453 + x*(0.12595528994069613 + (-0.510477729039857 + x)*x)))*
(3.831255349484765e-8 + x*(0.00002140058802480486 + x*(-0.00008693192041426982 +
x*(-0.018444802527704172 + x*(0.5368632648594895 + x*(-7.4522565817870365 + x*(62.30776783074574 + x*(-336.8744183413884 + x*(1191.026405027395 + x*(-2590.1225767072065 + 2712.1934046206975*x)))))))))
))/(7.313548422127797e-15 + x*(8.356306148115294e-12 + x*(2.3387986355395423e-9 +
x*(-6.605395132516945e-9 + x*(-1.790148526211301e-6 + x*(8.958041058260661e-6 +
x*(0.0014381954623440515 + x*(-0.045458133957877116 + x*(0.726263758547687 +
x*(-7.564793448616153 + x*(56.12131032495715 + x*(-308.4534327185232 +
x*(1271.3766801470479 + x*(-3884.3701789306033 + x*(8436.311867208919 + x*(-11805.768858200583 + 8136.580213862093*x))))))))))))))));
}
#endif
| {
"alphanum_fraction": 0.7049056604,
"avg_line_length": 53,
"ext": "h",
"hexsha": "ed2530c6d21a0cbd54723fed9bb720cb782a602b",
"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": "a694de368e79e3d21afa5d57b47209d5c9c55ed9",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "amazeliauskas/FastReso",
"max_forks_repo_path": "TFastReso.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "a694de368e79e3d21afa5d57b47209d5c9c55ed9",
"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": "amazeliauskas/FastReso",
"max_issues_repo_path": "TFastReso.h",
"max_line_length": 213,
"max_stars_count": 2,
"max_stars_repo_head_hexsha": "a694de368e79e3d21afa5d57b47209d5c9c55ed9",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "amazeliauskas/FastReso",
"max_stars_repo_path": "TFastReso.h",
"max_stars_repo_stars_event_max_datetime": "2020-09-22T14:25:58.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-07-11T02:48:59.000Z",
"num_tokens": 1136,
"size": 3975
} |
/**
*
* @file core_zpltmg_chebvand.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 Mathieu Faverge
* @date 2010-11-15
* @precisions normal z -> c d s
*
**/
#include <lapacke.h>
#include <math.h>
#include "common.h"
/***************************************************************************//**
*
* @ingroup CORE_PLASMA_Complex64_t
*
* CORE_zpltmg_chebvand is a kernel used in Vandermonde-like matrix generation
*
* See http://www.mathworks.fr/fr/help/matlab/ref/gallery.html#f84-999859
*
* Vandermonde-like matrix for the Chebyshev polynomials
*
* Produces the (primal) Chebyshev Vandermonde matrix based on the vector of
* points p, which define where the Chebyshev polynomial is calculated.
*
* If seed != 0, C(i,j) = Ti – 1(p(j)) where Ti – 1 is the Chebyshev
* polynomial of degree i – 1, and p is a vector of N equally spaced points on
* the interval [0,1].
*
*******************************************************************************
*
* @param[in] M
* The number of rows of the tile A to initialize. M >= 2.
*
* @param[in] N
* The number of columns of the tile A to initialize. N >= 0.
*
* @param[out] A
* On entry, the M-by-N tile to be initialized.
* On exit, each element of A is defined by:
* A(i,j) = Ti – 1(p(j)) where Ti – 1 is the Chebyshev polynomial of
* degree i – 1
*
* @param[in] LDA
* The leading dimension of the tile A. LDA >= max(1,M).
*
* @param[in] gN
* The global number of columns of the full matrix, A is belonging to. gN >= (n0+gN).
*
* @param[in] m0
* The index of the first row of tile A in the full matrix. m0 >= 0.
*
* @param[in] n0
* The index of the first column of tile A in the full matrix. n0 >= 0.
*
* @param[in] gN
* The global number of columns of the full matrix, A is belonging to. gN >= (n0+gN).
*
* @param[in,out] W
* Workspace of size 2-by-N, that contains the N triplets:
* ( A( m0-2, j), A(m0-1, j) )
* On entry, if m == 0, W is uinitialized, otherwise contains the data
* described above.
* On exit, contains the triplets ( A(m0+M-2, j), A(m0+M-1, j) )
*
*******************************************************************************
*
* @return
* \retval PLASMA_SUCCESS successful exit
* \retval <0 if INFO = -k, the k-th argument had an illegal value
*
******************************************************************************/
#if defined(PLASMA_HAVE_WEAK)
#pragma weak CORE_zpltmg_chebvand = PCORE_zpltmg_chebvand
#define CORE_zpltmg_chebvand PCORE_zpltmg_chebvand
#endif
int CORE_zpltmg_chebvand( int M, int N, PLASMA_Complex64_t *A, int LDA,
int gN, int m0, int n0,
PLASMA_Complex64_t *W )
{
PLASMA_Complex64_t step;
int i, j, jj;
/* Check input arguments */
if (M < 0) {
coreblas_error(1, "Illegal value of M");
return -1;
}
if (N < 0) {
coreblas_error(2, "Illegal value of N");
return -2;
}
if ((LDA < max(1,M)) && (M > 0)) {
coreblas_error(4, "Illegal value of LDA");
return -4;
}
if (m0 < 0) {
coreblas_error(6, "Illegal value of m0");
return -6;
}
if (n0 < 0) {
coreblas_error(7, "Illegal value of n0");
return -7;
}
if (gN < n0+N) {
coreblas_error(5, "Illegal value of gN");
return -5;
}
step = (PLASMA_Complex64_t)1. / (gN - 1.);
/* Initialize W if required */
if (m0 == 0) {
for (j=0, jj=n0; j<N; j++, jj++) {
W[2*j ] = 1.;
W[2*j+1] = jj * step;
}
if ( M == 1 ) {
LAPACKE_zlacpy_work( LAPACK_COL_MAJOR, 'A',
1, N, W, 2, A, LDA );
return PLASMA_SUCCESS;
}
LAPACKE_zlacpy_work( LAPACK_COL_MAJOR, 'A',
2, N, W, 2, A, LDA );
M -= 2;
A += 2;
}
/* Case NB=1, W contains row 0 and 1 and M should be 1 */
if (m0 == 1) {
if (M != 1) {
coreblas_error(1, "Illegal value of M for m0 = 1");
return -1;
}
LAPACKE_zlacpy_work( LAPACK_COL_MAJOR, 'A',
1, N, W+1, 2, A, LDA );
return PLASMA_SUCCESS;
}
for (j=0, jj=n0; j<N; j++, jj++) {
/* First line */
if (M > 0) {
A[LDA*j] = 2. * jj * step * W[j*2 + 1] - W[j*2 ];
}
/* Second line */
if (M > 1) {
A[LDA*j+1] = 2. * jj * step * A[LDA*j ] - W[j*2+1];
}
for (i=2; i<M; i++) {
A[LDA*j+i] = 2. * jj * step * A[LDA*j+i-1] - A[LDA*j+i-2];
}
}
if ( M == 1 ) {
cblas_zcopy( N, W+1, 2, W, 2 );
cblas_zcopy( N, A+M-1, LDA, W+1, 2 );
}
else {
LAPACKE_zlacpy_work( LAPACK_COL_MAJOR, 'A',
2, N, A + M - 2, LDA, W, 2 );
}
return PLASMA_SUCCESS;
}
| {
"alphanum_fraction": 0.4892307692,
"avg_line_length": 29.3785310734,
"ext": "c",
"hexsha": "fde1e84c699be492446d182a75a820ea4d4c497d",
"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_zpltmg_chebvand.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_zpltmg_chebvand.c",
"max_line_length": 93,
"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_zpltmg_chebvand.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1613,
"size": 5200
} |
#include <mpi.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <gsl/gsl_math.h>
#include "allvars.h"
#include "proto.h"
/*! \file b_from_rot_a.c
* \brief calculates ror(b) to aloow an initial vector potential
*
* This file is only called once after reading the initial condition.
* It is used to calculate b_ini from a initial vector potential, if needed.
*/
#ifdef BFROMROTA
void rot_a(void)
{
long long ntot, ntotleft;
int ndone;
int *noffset, *nbuffer, *nsend, *nsend_local, *numlist, *ndonelist;
int i, j, n;
int npleft;
int maxfill, source;
int level, ngrp, sendTask, recvTask;
int place, nexport;
double dmax1, dmax2, fac;
double sumt, sumcomm;
MPI_Status status;
noffset = (int *) mymalloc(sizeof(int) * NTask); /* offsets of bunches in common list */
nbuffer = (int *) mymalloc(sizeof(int) * NTask);
nsend_local = (int *) mymalloc(sizeof(int) * NTask);
nsend = (int *) mymalloc(sizeof(int) * NTask * NTask);
ndonelist = (int *) mymalloc(sizeof(int) * NTask);
NumSphUpdate = N_gas;
numlist = (int *) mymalloc(NTask * sizeof(int) * NTask);
MPI_Allgather(&NumSphUpdate, 1, MPI_INT, numlist, 1, MPI_INT, MPI_COMM_WORLD);
for(i = 0, ntot = 0; i < NTask; i++)
ntot += numlist[i];
myfree(numlist);
i = 0; /* beginn with this index */
ntotleft = ntot; /* particles left for all tasks together */
while(ntotleft > 0)
{
for(j = 0; j < NTask; j++)
nsend_local[j] = 0;
/* do local particles and prepare export list */
for(nexport = 0, ndone = 0; i < N_gas && nexport < All.BunchSizeDensity - NTask; i++)
{
ndone++;
for(j = 0; j < NTask; j++)
Exportflag[j] = 0;
rot_a_evaluate(i, 0);
for(j = 0; j < NTask; j++)
{
if(Exportflag[j])
{
DensDataIn[nexport].Pos[0] = P[i].Pos[0];
DensDataIn[nexport].Pos[1] = P[i].Pos[1];
DensDataIn[nexport].Pos[2] = P[i].Pos[2];
/* using velocity structure for BPred ... */
DensDataIn[nexport].Vel[0] = SphP[i].BPred[0];
DensDataIn[nexport].Vel[1] = SphP[i].BPred[1];
DensDataIn[nexport].Vel[2] = SphP[i].BPred[2];
DensDataIn[nexport].Hsml = PPP[i].Hsml;
DensDataIn[nexport].Index = i;
DensDataIn[nexport].Task = j;
nexport++;
nsend_local[j]++;
}
}
}
qsort(DensDataIn, nexport, sizeof(struct densdata_in), dens_compare_key);
for(j = 1, noffset[0] = 0; j < NTask; j++)
noffset[j] = noffset[j - 1] + nsend_local[j - 1];
MPI_Allgather(nsend_local, NTask, MPI_INT, nsend, NTask, MPI_INT, MPI_COMM_WORLD);
/* now do the particles that need to be exported */
for(level = 1; level < (1 << PTask); level++)
{
for(j = 0; j < NTask; j++)
nbuffer[j] = 0;
for(ngrp = level; ngrp < (1 << PTask); ngrp++)
{
maxfill = 0;
for(j = 0; j < NTask; j++)
{
if((j ^ ngrp) < NTask)
if(maxfill < nbuffer[j] + nsend[(j ^ ngrp) * NTask + j])
maxfill = nbuffer[j] + nsend[(j ^ ngrp) * NTask + j];
}
if(maxfill >= All.BunchSizeDensity)
break;
sendTask = ThisTask;
recvTask = ThisTask ^ ngrp;
if(recvTask < NTask)
{
if(nsend[ThisTask * NTask + recvTask] > 0 || nsend[recvTask * NTask + ThisTask] > 0)
{
/* get the particles */
MPI_Sendrecv(&DensDataIn[noffset[recvTask]],
nsend_local[recvTask] * sizeof(struct densdata_in), MPI_BYTE,
recvTask, TAG_DENS_A,
&DensDataGet[nbuffer[ThisTask]],
nsend[recvTask * NTask + ThisTask] * sizeof(struct densdata_in),
MPI_BYTE, recvTask, TAG_DENS_A, MPI_COMM_WORLD, &status);
}
}
for(j = 0; j < NTask; j++)
if((j ^ ngrp) < NTask)
nbuffer[j] += nsend[(j ^ ngrp) * NTask + j];
}
for(j = 0; j < nbuffer[ThisTask]; j++)
{
rot_a_evaluate(j, 1);
}
MPI_Barrier(MPI_COMM_WORLD);
for(j = 0; j < NTask; j++)
nbuffer[j] = 0;
for(ngrp = level; ngrp < (1 << PTask); ngrp++)
{
maxfill = 0;
for(j = 0; j < NTask; j++)
{
if((j ^ ngrp) < NTask)
if(maxfill < nbuffer[j] + nsend[(j ^ ngrp) * NTask + j])
maxfill = nbuffer[j] + nsend[(j ^ ngrp) * NTask + j];
}
if(maxfill >= All.BunchSizeDensity)
break;
sendTask = ThisTask;
recvTask = ThisTask ^ ngrp;
if(recvTask < NTask)
{
if(nsend[ThisTask * NTask + recvTask] > 0 || nsend[recvTask * NTask + ThisTask] > 0)
{
/* send the results */
MPI_Sendrecv(&DensDataResult[nbuffer[ThisTask]],
nsend[recvTask * NTask + ThisTask] * sizeof(struct densdata_out),
MPI_BYTE, recvTask, TAG_DENS_B,
&DensDataPartialResult[noffset[recvTask]],
nsend_local[recvTask] * sizeof(struct densdata_out),
MPI_BYTE, recvTask, TAG_DENS_B, MPI_COMM_WORLD, &status);
/* add the result to the particles */
for(j = 0; j < nsend_local[recvTask]; j++)
{
source = j + noffset[recvTask];
place = DensDataIn[source].Index;
SphP[place].BSmooth[0] += DensDataPartialResult[source].BSmooth[0];
SphP[place].BSmooth[1] += DensDataPartialResult[source].BSmooth[1];
SphP[place].BSmooth[2] += DensDataPartialResult[source].BSmooth[2];
SphP[place].DensityNorm += DensDataPartialResult[source].DensityNorm;
}
}
}
for(j = 0; j < NTask; j++)
if((j ^ ngrp) < NTask)
nbuffer[j] += nsend[(j ^ ngrp) * NTask + j];
}
level = ngrp - 1;
}
MPI_Allgather(&ndone, 1, MPI_INT, ndonelist, 1, MPI_INT, MPI_COMM_WORLD);
for(j = 0; j < NTask; j++)
ntotleft -= ndonelist[j];
}
for(i = 0; i < N_gas; i++)
for(j = 0; j < 3; j++)
#ifndef IGNORE_PERIODIC_IN_ROTA
SphP[i].B[j] = SphP[i].BPred[j] = SphP[i].BSmooth[j] / SphP[i].d.Density;
#else
SphP[i].B[j] = SphP[i].BPred[j] = SphP[i].BSmooth[j] / SphP[i].DensityNorm;
#endif
myfree(ndonelist);
myfree(nsend);
myfree(nsend_local);
myfree(nbuffer);
myfree(noffset);
}
/*! This function represents the core of the calculus of rot of vector potential
* target particle may either be local, or reside in the communication
* buffer.
*/
void rot_a_evaluate(int target, int mode)
{
int j, n;
int startnode, numngb, numngb_inbox;
double h, h2, fac, hinv, hinv3, hinv4;
double wk, dwk;
double dx, dy, dz, r, r2, u, mass_j, rho;
double dbx, dby, dbz;
double rotb[3];
MyFloat *pos, *b;
rho = rotb[0] = rotb[1] = rotb[2] = 0;
if(mode == 0)
{
pos = P[target].Pos;
b = SphP[target].BPred;
h = PPP[target].Hsml;
}
else
{
pos = DensDataGet[target].Pos;
b = DensDataGet[target].Vel; /* Using Vel structure for BPred !!!! */
h = DensDataGet[target].Hsml;
}
h2 = h * h;
hinv = 1.0 / h;
#ifndef TWODIMS
hinv3 = hinv * hinv * hinv;
#else
hinv3 = hinv * hinv / boxSize_Z;
#endif
hinv4 = hinv3 * hinv;
startnode = All.MaxPart;
do
{
numngb_inbox = ngb_treefind_variable(&pos[0], 2 * h, &startnode);
for(n = 0; n < numngb_inbox; n++)
{
j = Ngblist[n];
dx = pos[0] - P[j].Pos[0];
dy = pos[1] - P[j].Pos[1];
dz = pos[2] - P[j].Pos[2];
dbx = b[0] - SphP[j].BPred[0];
dby = b[1] - SphP[j].BPred[1];
dbz = b[2] - SphP[j].BPred[2];
#ifndef IGNORE_PERIODIC_IN_ROTA
#ifdef PERIODIC /* now find the closest image in the given box size */
if(dx > boxHalf_X)
dx -= boxSize_X;
if(dx < -boxHalf_X)
dx += boxSize_X;
if(dy > boxHalf_Y)
{
#ifdef BRIOWU
dbz /= dy;
#endif
dy -= boxSize_Y;
#ifdef BRIOWU
dbz *= dy;
#endif
}
if(dy < -boxHalf_Y)
{
#ifdef BRIOWU
dbz /= dy;
#endif
dy += boxSize_Y;
#ifdef BRIOWU
dbz *= dy;
#endif
}
if(dz > boxHalf_Z)
{
#ifdef BRIOWU
dbx /= dz;
#endif
dz -= boxSize_Z;
#ifdef BRIOWU
dbx *= dz;
#endif
}
if(dz < -boxHalf_Z)
{
#ifdef BRIOWU
dbx /= dz;
#endif
dz += boxSize_Z;
#ifdef BRIOWU
dbx *= dz;
#endif
}
#endif
#endif
r2 = dx * dx + dy * dy + dz * dz;
if(r2 < h2)
{
r = sqrt(r2);
u = r * hinv;
if(u < 0.5)
{
wk = hinv3 * (KERNEL_COEFF_1 + KERNEL_COEFF_2 * (u - 1) * u * u);
dwk = hinv4 * u * (KERNEL_COEFF_3 * u - KERNEL_COEFF_4);
}
else
{
wk = hinv3 * KERNEL_COEFF_5 * (1.0 - u) * (1.0 - u) * (1.0 - u);
dwk = hinv4 * KERNEL_COEFF_6 * (1.0 - u) * (1.0 - u);
}
mass_j = P[j].Mass;
rho += mass_j * wk;
if(r > 0)
{
fac = mass_j * dwk / r;
#ifndef BRIOWU
rotb[0] += FLT(fac * (dz * dby - dy * dbz));
rotb[1] += FLT(fac * (dx * dbz - dz * dbx));
rotb[2] += FLT(fac * (dy * dbx - dx * dby));
#else
rotb[0] += FLT(fac * (-dy * dbz));
rotb[1] += FLT(fac * (-dz * dbx));
rotb[2] += FLT(fac * (0.0));
#endif
}
}
}
}
while(startnode >= 0);
if(mode == 0)
{
SphP[target].BSmooth[0] = rotb[0]; /* giving back rot(B) in the Smooth */
SphP[target].BSmooth[1] = rotb[1]; /* Data structure !!! */
SphP[target].BSmooth[2] = rotb[2];
SphP[target].DensityNorm = rho;
}
else
{
DensDataResult[target].BSmooth[0] = rotb[0];
DensDataResult[target].BSmooth[1] = rotb[1];
DensDataResult[target].BSmooth[2] = rotb[2];
DensDataResult[target].DensityNorm = rho;
}
}
#endif
| {
"alphanum_fraction": 0.5681988642,
"avg_line_length": 24.4319371728,
"ext": "c",
"hexsha": "cca8a0fe8155fc3da45ae100cdb68837260cc218",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "5e82c2de9e6884795b4ee89f2b15ed5dde70388f",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "egpbos/egp",
"max_forks_repo_path": "testing/icgen/random_verschillende_resoluties_N-GenIC/gadget3_64/b_from_rot_a.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "5e82c2de9e6884795b4ee89f2b15ed5dde70388f",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "egpbos/egp",
"max_issues_repo_path": "testing/icgen/random_verschillende_resoluties_N-GenIC/gadget3_64/b_from_rot_a.c",
"max_line_length": 91,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "5e82c2de9e6884795b4ee89f2b15ed5dde70388f",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "egpbos/egp",
"max_stars_repo_path": "testing/icgen/random_verschillende_resoluties_N-GenIC/gadget3_64/b_from_rot_a.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 3331,
"size": 9333
} |
/**
* Various binning and weighting routines for aperture pixel tables.
*/
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_vector.h>
#include "aXe_grism.h"
#include "aper_conf.h"
#include "spc_driz.h"
#include "spce_output.h"
#include "spc_optimum.h"
#include "spce_binning.h"
#define SQR(x) ((x)*(x))
#define MIN(x,y) (((x)<(y))?(x):(y))
#define MAX(x,y) (((x)>(y))?(x):(y))
#define DEBUG_ME 0x200
#define PIXWEIGHT(x1,y1,x2,y2,pix) ((pix)->weight_function((x1), (y1), (x2),\
(y2),(pix)))
#define NAIVE_VAL_TO_BININD(x) ((int)floor((x)+1e-6))
/**
* Function: add_to_spec_table
* adds some count to an entry in the spectrum table
*
* Parameters:
* @param spec the spectrum table to work on
* @param bin index of spectrum table entry to add cur_p to
* @param cur_p the ap_pixel to add
* @param weight weight of the count
*/
static void
add_to_spec_table (spectrum * const spec, const int bin,
const ap_pixel * const cur_p, const int quant_cont,
const double weight)
{
spc_entry *const sp_e = spec->spec + bin;
// some conditions which should not be violated
if ((bin < 0) || (bin > spec->spec_len))
{
aXe_message (aXe_M_WARN4, __FILE__, __LINE__,
"Assignment out of spectrum: %d", bin);
return;
}
if (weight < 0)
{
aXe_message (aXe_M_FATAL, __FILE__, __LINE__,
"Weight cannot be negative " "but is %f", weight);
}
// check whether the spectral element is new
// and without values up to now
if (isnan (sp_e->lambda_mean))
{
// initialize the spectral element
sp_e->lambda_mean = cur_p->lambda;
sp_e->dlambda = cur_p->dlambda;
sp_e->lambda_max = cur_p->lambda;
sp_e->lambda_min = cur_p->lambda;
sp_e->weight = weight;
sp_e->count = cur_p->count * weight;
sp_e->error = fabs(cur_p->error) * weight;
sp_e->dq = cur_p->dq;
// initialize the contamination
// this is different for quantitative and
// geometrical contamination
if (quant_cont)
{
if ((int)(sp_e->contam==-1)&&((int)cur_p->contam!=-1))
{
sp_e->contam = cur_p->contam * weight;
}
}
else
{
if ((int)(sp_e->contam==-1)&&((int)cur_p->contam!=-1))
{
sp_e->contam = cur_p->contam;
}
}
}
else
{
// update an existing spectral bin
// find new maxima and minima
sp_e->lambda_max = MAX (cur_p->lambda, sp_e->lambda_max);
sp_e->lambda_min = MIN (cur_p->lambda, sp_e->lambda_min);
// find new mean lambda via weighted summation
sp_e->lambda_mean =
(sp_e->lambda_mean * sp_e->weight +
cur_p->lambda * weight) / (weight + sp_e->weight);
// NEWNEWNEW::
// find dlambda via weighted summation
sp_e->dlambda =
(sp_e->dlambda * sp_e->weight +
cur_p->dlambda * weight) / (weight + sp_e->weight);
// add the weight
sp_e->weight += weight;
// add the counts
sp_e->count += cur_p->count * weight;
// process the error
sp_e->error = sqrt (SQR (sp_e->error) + SQR (fabs(cur_p->error) * weight));
// logically XOR the dq
sp_e->dq = (sp_e->dq | cur_p->dq);
// update the contamination,
// take into account the quantitative
// contamination
if (quant_cont)
{
if (((int)sp_e->contam==-1)&&((int)cur_p->contam!=-1))
{
sp_e->contam = cur_p->contam * weight;
}
if (((int)sp_e->contam!=-1)&&((int)cur_p->contam!=-1))
{
sp_e->contam += cur_p->contam * weight;
}
}
else
{
if (((int)sp_e->contam==-1)&&((int)cur_p->contam!=-1))
{
sp_e->contam = cur_p->contam;
}
if (((int)sp_e->contam!=-1)&&((int)cur_p->contam!=-1))
{
sp_e->contam += cur_p->contam;
}
}
}
}
/**
* Function: pixweight_x
* computes a weight for the bin between coordinates (x1,y1) and (x2,y2)
* if the pi/4<=angle<=3 pi/4.
*
* Parameters:
* @param x1 - x coordinate for the start point of the bin on the trace
* @param y1 - y coordinate for the start point of the bin on the trace
* @param x2 - x coordinate for the end point of the bin on the trace
* @param y2 - y coordinate for the end point of the bin on the trace
* @param pix the pixel to compute the weight for in the form of a
* w_pixel structure filled out by fill_w_pixel
*
* Returns:
* @return sum - the pixel weight
*/
double
pixweight_x (const double x1, const double y1, const double x2,
const double y2, const struct w_pixel_s *const pix)
{
double a, b;
double sum = 0;
a = x1 - pix->cota * (y1 - pix->y0);
b = x2 - pix->cota * (y2 - pix->y0);
if ((b >= pix->p0) && (a <= pix->p1))
{
sum += pix->slope / 2 * (MIN (b, pix->p1) - MAX (a, pix->p0))
* (MAX (a, pix->p0) - 2 * pix->p0 + MIN (b, pix->p1))
* sin (pix->angle);
}
if ((b >= pix->p1) && (a <= pix->p2))
{
sum += pix->fmax * (MIN (b, pix->p2) - MAX (a, pix->p1))
* sin (pix->angle);
}
if ((b >= pix->p2) && (a <= pix->p3))
{
sum += pix->slope / 2 * (MAX (a, pix->p2) - MIN (b, pix->p3))
* (MAX (a, pix->p2) - 2 * pix->p3 + MIN (b, pix->p3))
* sin (pix->angle);
}
return sum;
}
/**
* Funtion: pixweight_y
* Computes a weight for the bin between coordinates (x1,y1) and (x2,y2)
* if the angle<=pi/4 or 3 pi/4<=angle.
*
* @param x1 - x coordinate for the start point of the bin on the trace
* @param y1 - y coordinate for the start point of the bin on the trace
* @param x2 - x coordinate for the end point of the bin on the trace
* @param y2 - y coordinate for the end point of the bin on the trace
* @param pix - the pixel to compute the weight for in the form of a
* w_pixel structure filled out by fill_w_pixel
*
* Returns:
* @return sum - the pixel weight
*/
double
pixweight_y (const double x1, const double y1, const double x2,
const double y2, const struct w_pixel_s *const pix)
{
double a, b;
double sum = 0;
a = y1 + pix->tana * (pix->x0 - x1);
b = y2 + pix->tana * (pix->x0 - x2);
if (a > b)
{
double tmp;
tmp = a;
a = b;
b = tmp;
}
if ((b >= pix->p0) && (a <= pix->p1))
{
sum += pix->slope / 2 * (MIN (b, pix->p1) - MAX (a, pix->p0))
* (MAX (a, pix->p0) - 2 * pix->p0 + MIN (b, pix->p1))
* cos (pix->angle);
}
if ((b >= pix->p1) && (a <= pix->p2))
{
sum += pix->fmax * (MIN (b, pix->p2) - MAX (a, pix->p1))
* cos (pix->angle);
}
if ((b >= pix->p2) && (a <= pix->p3))
{
sum += pix->slope / 2 * (MAX (a, pix->p2) - MIN (b, pix->p3))
* (MAX (a, pix->p2) - 2 * pix->p3 + MIN (b, pix->p3))
* cos (pix->angle);
}
return sum;
}
/**
* Function: fill_w_pixel
* precomputes some properties of a given pixel for purposes
* of computing the weights it contributes to a given xi bin.
*
* Parameters:
* @param pix a pointer to the w_pix structure to fill
* @param x0 the x coordinate of the pixel's lower left corner
* @param y0 the y coordinate of the pixel's lower left corner
* @param size the size of the pixel
* @param angle the orientation of the object that has generated the
* spectrum
*/
/* since we're only interested in weights here, the size of the square
* doesn't matter. Where I left explicit ones, you could write size
* and get the true area instead of the fraction of the total area.
* Dunno why you'd want to do this, though.
*/
static void
fill_w_pixel (w_pixel * const pix, const double x0, const double y0,
const double angle)
{
pix->tana = tan (angle);
pix->cota = 1 / pix->tana;
pix->angle = angle;
pix->x0 = x0;
pix->y0 = y0;
if ((angle >= M_PI / 4) && (angle <= 3 * M_PI / 4))
{
pix->p0 = MIN (x0, x0 - 1 * pix->cota);
pix->p1 = MAX (x0, x0 - 1 * pix->cota);
pix->p2 = MIN (x0 + 1, x0 + 1 - 1 * pix->cota);
pix->p3 = MAX (x0 + 1, x0 + 1 - 1 * pix->cota);
pix->fmax = 1 / sin (angle);
if (fabs (pix->p1 - pix->p0) < 1e-7)
pix->slope = 0;
else
pix->slope = pix->fmax / (pix->p1 - pix->p0);
pix->weight_function = &pixweight_x;
}
else
{ /* angle between 0 and pi/4 or 3*pi/4 and pi */
pix->p0 = MIN (y0, y0 - 1 * pix->tana);
pix->p1 = MAX (y0, y0 - 1 * pix->tana);
pix->p2 = MIN (y0 + 1, y0 + 1 - 1 * pix->tana);
pix->p3 = MAX (y0 + 1, y0 + 1 - 1 * pix->tana);
pix->fmax = 1 / cos (angle);
if (fabs (pix->p1 - pix->p0) < 1e-7)
pix->slope = 0;
else
pix->slope = pix->fmax / (pix->p1 - pix->p0);
pix->weight_function = &pixweight_y;
}
}
/**
* Function: bin_naive
* computes a spectrum from a table of aperture pixels generated from
* spc_extract. This is adds up the pixel values, distributing them
* over the trace, taking into account the fracton of the pixel that
* projects onto the given [xi,xi+1] interval.
* Return NULL if ap_p is NULL
*
* Parameters:
* @param ap_p the table of aperture pixels
* @param px_width width of a pixel (=1 if not subsampled)
* @param ob_width the width of the object that has generated the spectrum
* @param ob_orientation the orientation of the object that has
* generated the spectrum
* @param flags problems that were accumulated in generating ap_p;
* possible flags are defined for the warning member of the spectrum struct
*
* Returns:
* @return spec - the 1D spectrum
*/
spectrum *
bin_naive (const ap_pixel * const ap_p, const double ob_width,
const double ob_orient, const int quant_cont)
{
const ap_pixel *cur_p;
int upper, lower;
int bin;
spectrum *spec, *tspec;
double phi_trace;
spc_entry *spec_table;
double d, frac;
// immediately return empty PET's
if (ap_p==NULL)
return NULL;
// go through the PET,
// find the minimum and
// maximum in trace distance
cur_p = ap_p;
upper = NAIVE_VAL_TO_BININD (cur_p->xi);
lower = NAIVE_VAL_TO_BININD (cur_p->xi);
while (cur_p->p_x != -1)
{
bin = NAIVE_VAL_TO_BININD (cur_p->xi);
upper = MAX (bin, upper);
lower = MIN (bin, lower);
cur_p++;
}
// check whether the spectrum
// will ahve a finite length,
// exit if not
if (upper == lower)
{
aXe_message (aXe_M_WARN4, __FILE__, __LINE__,
"Pixel table empty.\n");
return NULL;
}
// Thresh in some headway so we don't need to worry too much about
// accessing invalid elements now and then
lower -= 10;
upper += 10;
spec = allocate_spectrum (upper - lower);
spec_table = spec->spec;
cur_p = ap_p;
while (cur_p->p_x != -1)
{
// Compute any fractional pixel that might fall within the
//desired extraction width
d = ob_width;
frac = 1.;
// continue if the pixel is outside
// of the extraction region
if (fabs (cur_p->dist) > d + .5)
{
cur_p++;
continue;
}
if ((fabs (cur_p->dist) >= d - .5) && (fabs (cur_p->dist) <= d + .5))
{
frac = fabs (d - (fabs (cur_p->dist) - 0.5));
}
// store the local trace angle
phi_trace = cur_p->dxs;
if (1)
{
double xi;
w_pixel pix;
double sinp = sin (phi_trace);
double cosp = cos (phi_trace);
double xc, yc;
double w;
double sum = 0;
fill_w_pixel (&pix, cur_p->x, cur_p->y, ob_orient);
xc = cur_p->xs;
yc = cur_p->ys;
// at cur_p->xi, there has to be some contribution. We go back
// collecting, until w is zero
for (xi = cur_p->xi;; xi -= 1)
{
bin = NAIVE_VAL_TO_BININD (xi);
w = PIXWEIGHT (xc + (bin - cur_p->xi) * cosp,
yc + (bin - cur_p->xi) * sinp,
xc + (bin + 1 - cur_p->xi) * cosp,
yc + (bin + 1 - cur_p->xi) * sinp,
&pix);
if (w < 1e-10)
break;
add_to_spec_table (spec, bin - lower, cur_p, quant_cont,
w * frac * cur_p->weight);
// if (cur_p->weight > 10.0){
// fprintf(stdout,"weight: %f, distance: %f, ewidth: %f\n",
// cur_p->weight, cur_p->dist, d+0.5);
// }
sum += w;
}
/* Now collect contributions upward of cur_p->xi */
for (xi = cur_p->xi + 1;; xi += 1)
{
bin = NAIVE_VAL_TO_BININD (xi);
w = PIXWEIGHT (xc + (bin - cur_p->xi) * cosp,
yc + (bin - cur_p->xi) * sinp,
xc + (bin + 1 - cur_p->xi) * cosp,
yc + (bin + 1 - cur_p->xi) * sinp,
&pix);
if (w < 1e-10)
break;
add_to_spec_table (spec, bin - lower, cur_p, quant_cont,
w * frac * cur_p->weight);
sum += w;
}
if (fabs (sum - 1) > 1e-6)
{
fprintf(stdout,
"Weights added up to only %f for pixel from %4d,%4d\n",
sum, cur_p->p_x, cur_p->p_y);
}
}
cur_p++;
}
/* Trimming the INDEF beginning and ending values in spectrum */
tspec = trim_spectrum (spec);
free_spectrum (spec);
spec = NULL;
// return the spectrum
return tspec;
}
/**
* Function: bin_optimal
* computes a spectrum from a table of aperture pixels generated from
* spc_extract. This is adds up the pixel values, distributing them
* over the trace, taking into account the fracton of the pixel that
* projects onto the given [xi,xi+1] interval.
* Return NULL if ap_p is NULL
*
* Parameters:
* @param ap_p the table of aperture pixels
* @param px_width width of a pixel (=1 if not subsampled)
* @param ob_width the width of the object that has generated the spectrum
* @param ob_orientation the orientation of the object that has
* generated the spectrum
* @param flags problems that were accumulated in generating ap_p;
* possible flags are defined for the warning member of the spectrum struct
*
* Returns:
* @return spec - the 1D spectrum
*/
spectrum *
bin_optimal (const ap_pixel * const ap_p, const beam curbeam,
const int quant_cont, const gsl_matrix *weights,
const drzstamp_dim dimension,gsl_matrix *coverage)
{
const ap_pixel *cur_p;
ap_pixel *tmp_p;
spectrum *spec;
spectrum *tspec;
spc_entry *spec_table;
quadrangle quad;
// drzstamp_dim dimension;
double jacob, arr;
double frac, totweight;
int jcen, icen;
int jupp, iupp;
int jlow, ilow;
int ii, jj;
int stpi, stpj;
// return NULL if
// empty PET
if (ap_p==NULL)
return NULL;
// allocate memory
tmp_p = (ap_pixel *) malloc(sizeof(ap_pixel));
// allocate memory for the spectrum
spec = allocate_spectrum (weights->size1);
spec_table = spec->spec;
// go over each PET pixel
cur_p = ap_p;
for (cur_p = ap_p; cur_p->p_x != -1; cur_p++)
{
// continue if the pixel is outside
// of the extraction region
if (fabs (cur_p->dist) > curbeam.width + .5)
continue;
// determine which fraction
// of the pixel is inside of the extraction area
if ((fabs (cur_p->dist) >= curbeam.width - .5) && (fabs (cur_p->dist) <= curbeam.width + .5))
frac = fabs (curbeam.width - (fabs (cur_p->dist) - 0.5));
else
frac = 1.;
// transfer values to the temporary pixel
tmp_p->lambda = cur_p->xi;
tmp_p->dist = cur_p->dist;
tmp_p->dxs = cur_p->dxs;
tmp_p->dlambda = 1.0;
// create the quadrangle for the current pixel
quad = get_quad_from_pixel(tmp_p, curbeam.orient, dimension);
// get the jacobian (well, easy here)
// the term "cos(cur_p->dxs)" must be there
// to correct the enlargement necessary
// to cover the whole lambda-crossdispersion area!
// NOT COMPLETELY understood
jacob = cos(cur_p->dxs);
// get the central pixel (icen, jcen) of the current PET-pixel
icen = (int) floor(cur_p->xi - dimension.xstart+.5);
jcen = (int) floor(cur_p->dist - dimension.ystart+.5);
// get the uper and lower extend of the quadrangle in x
iupp = (int)floor(quad.xmax - (double)icen + 0.5)+1;
ilow = (int)floor(quad.xmin - (double)icen + 0.5);
// get the uper and lower extend of the quadrangle in x
jupp = (int)floor(quad.ymax - (double)jcen + 0.5)+1;
jlow = (int)floor(quad.ymin - (double)jcen + 0.5);
// go over the extend in x
for (ii=ilow;ii<iupp;ii++)
{
// go over the extend in x
for (jj=jlow;jj<jupp;jj++)
{
// get the coordinates of the current output pixel
stpi = icen+ii;
stpj = jcen+jj;
// check whether the current output pixel is within
// the stamp image; continue if not
if ( (stpi>=dimension.xsize)||(stpi<0)||(stpj>=dimension.ysize)||(stpj<0) )
continue;
// get the area which falls onto the current output pixel
arr = boxer(stpi,stpj,quad.x,quad.y);
// compute the pixel weight from
// the various inputs
totweight = arr*frac*jacob*gsl_matrix_get(weights, stpi, stpj);
//totweight = arr*frac*jacob;//*gsl_matrix_get(weights, stpi, stpj);
//gsl_matrix_set(coverage, stpi, stpj, gsl_matrix_get(coverage, stpi, stpj) + arr*frac*jacob);
// add the pixel to the spectrum
if (totweight > 0.0)
add_to_spec_table (spec, stpi, cur_p, quant_cont,totweight);
// gsl_matrix_set(coverage, stpi, stpj, sqrt (SQR (gsl_matrix_get(coverage, stpi, stpj)) + SQR (fabs(cur_p->error) * totweight)));
}
}
}
/* Trimming the INDEF beginning and ending values in spectrum */
tspec = trim_spectrum (spec);
free_spectrum (spec);
spec = NULL;
free(tmp_p);
// return the spectrum
return tspec;
}
/**
does a straight forward summation/binning of an aperture pixel table
with appropriate weights (cf. Hornes 1986)
@param ap_p the table of aperture pixels
@param ob_orient the orientation of the object that has
generated the spectrum
@param flags problems that were accumulated in generating ap_p;
possible flags are defined for the warning member of the spectrum struct
@param n_sub subsampling factor
@return an allocated spectrum
@see spectrum
*/
spectrum *
bin_weighted (const ap_pixel * const ap_p, const double ob_orient,
const trace_func * const trace, const int n_sub,
const int flags)
{
gsl_vector *binned_table;
gsl_vector *wei_table;
gsl_vector *wei2_table;
double xi, d, w, wei, wei2;
int xii, num_bin, bin;
const ap_pixel *cur_p = ap_p;
double upper = cur_p->xi, lower = cur_p->xi;
spectrum *spec;
while (cur_p->p_x != -1)
{
upper = MAX (cur_p->xi, upper);
lower = MIN (cur_p->xi, lower);
cur_p++;
}
lower -= 10;
upper += 10;
lower = floor (lower);
upper = floor (upper + 1);
num_bin = floor ((upper - lower) / n_sub);
spec = allocate_spectrum (num_bin);
binned_table = gsl_vector_alloc (num_bin);
wei_table = gsl_vector_alloc (num_bin);
wei2_table = gsl_vector_alloc (num_bin);
gsl_vector_set_all (binned_table, 0);
gsl_vector_set_all (wei_table, 0);
gsl_vector_set_all (wei2_table, 0);
cur_p = ap_p;
while (cur_p->p_x != -1)
{
xi = (cur_p->xi - lower) / n_sub;
xii = floor (xi);
d = fabs(cur_p->dist);
w = exp (-d * d / (2 * 6.66));
w = 1.;
add_to_spec_table (spec, xii - 1,cur_p, 0, w * (1 - (xi - xii)));
add_to_spec_table (spec, xii , cur_p, 0, w * (xi - xii));
gsl_vector_set (wei_table, xii - 1,
gsl_vector_get (wei_table, xii - 1) + w);
gsl_vector_set (wei_table, xii,
gsl_vector_get (wei_table, xii) + w);
gsl_vector_set (wei2_table, xii - 1,
gsl_vector_get (wei2_table, xii - 1) + w * w);
gsl_vector_set (wei2_table, xii,
gsl_vector_get (wei2_table, xii) + w * w);
//fprintf(stderr,"%f,%d,%d\n",xi,xii,xii+1);
cur_p++;
}
cur_p = ap_p;
for (bin = 0; bin < num_bin; bin++)
{
wei = gsl_vector_get (wei_table, bin);
wei2 = gsl_vector_get (wei2_table, bin);
if (wei2 != 0)
{
spec->spec[bin].count = spec->spec[bin].count * wei / wei2;
}
}
spec->warning = 0;
return spec;
}
| {
"alphanum_fraction": 0.5981650456,
"avg_line_length": 27.6260387812,
"ext": "c",
"hexsha": "efa8003cc91e456f2044012f40ae59056b112005",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "sosey/pyaxe",
"max_forks_repo_path": "cextern/src/spce_binning.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "sosey/pyaxe",
"max_issues_repo_path": "cextern/src/spce_binning.c",
"max_line_length": 143,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "sosey/pyaxe",
"max_stars_repo_path": "cextern/src/spce_binning.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 6229,
"size": 19946
} |
#pragma once
#include "nkg_point.h"
#include "nkg_rect.h"
#include "utility/types.h"
#include <stb_image.h>
#include <gsl/gsl>
#include <memory>
#include <vector>
#include <stdlib.h>
namespace cws80 {
class im_image {
public:
im_image();
~im_image();
void load(const char *filename, uint desired_channels);
void load_from_memory(const u8 *buffer, uint length, uint desired_channels);
void load_from_memory(gsl::span<const u8> memory, uint desired_channels)
{
load_from_memory(memory.data(), memory.size(), desired_channels);
}
const u8 *pixel(uint x, uint y) const;
u8 alpha(uint x, uint y) const;
bool is_transparent_column(uint x) const;
bool is_transparent_row(uint y) const;
im_image cut(const im_recti &r) const;
std::vector<im_image> hsplit() const;
std::vector<im_image> vsplit() const;
im_recti rect() const;
im_recti crop_alpha_border() const;
const u8 *data() const { return data_.get(); }
uint width() const { return w_; }
uint height() const { return h_; }
uint channels() const { return c_; }
im_image(im_image &&other) = default;
im_image &operator=(im_image &&other) = default;
private:
uint w_{}, h_{}, n_{}, c_{};
std::unique_ptr<u8[], void (*)(void *)> data_{nullptr, &stbi_image_free};
public:
class exception : public std::runtime_error {
public:
using std::runtime_error::runtime_error;
};
};
} // namespace cws80
| {
"alphanum_fraction": 0.6657608696,
"avg_line_length": 25.3793103448,
"ext": "h",
"hexsha": "9b3310e3c5ea72a930f96127abbd9d63b3565759",
"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": "ce37a49caed50a4b7baccfed288c2f5555af91c7",
"max_forks_repo_licenses": [
"BSL-1.0"
],
"max_forks_repo_name": "jpcima/cws80",
"max_forks_repo_path": "sources/ui/detail/nki_image.h",
"max_issues_count": 5,
"max_issues_repo_head_hexsha": "ce37a49caed50a4b7baccfed288c2f5555af91c7",
"max_issues_repo_issues_event_max_datetime": "2019-06-23T21:33:33.000Z",
"max_issues_repo_issues_event_min_datetime": "2019-05-21T12:56:22.000Z",
"max_issues_repo_licenses": [
"BSL-1.0"
],
"max_issues_repo_name": "jpcima/cws80",
"max_issues_repo_path": "sources/ui/detail/nki_image.h",
"max_line_length": 80,
"max_stars_count": 4,
"max_stars_repo_head_hexsha": "ce37a49caed50a4b7baccfed288c2f5555af91c7",
"max_stars_repo_licenses": [
"BSL-1.0"
],
"max_stars_repo_name": "jpcima/cws80",
"max_stars_repo_path": "sources/ui/detail/nki_image.h",
"max_stars_repo_stars_event_max_datetime": "2019-11-03T04:21:53.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-05-20T19:27:09.000Z",
"num_tokens": 386,
"size": 1472
} |
/*
* author: Achim Gaedke
* created: January 2001
* file: pygsl/src/histogrammodule.c
* $Id: matrixmodule.c,v 1.2 2003/07/25 17:15:16 schnizer Exp $
*/
#include <Python.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_matrix.h>
#include <pygsl/error_helpers.h>
/*
* matrix
*/
/* my typedef */
staticforward PyTypeObject matrix_matrixType;
typedef struct {
PyObject_HEAD
gsl_matrix* m;
} matrix_matrixObject;
static PyObject* matrix_matrix_get(PyObject *self,
PyObject *args
)
{
gsl_matrix* matrix;
long int i;
long int j;
matrix=(gsl_matrix*)((matrix_matrixObject*)self)->m;
if (matrix==NULL) {
PyErr_SetString(PyExc_RuntimeError, "matrix.get got a NULL pointer");
return NULL;
}
/* get index */
if (0==PyArg_ParseTuple(args,"ll",&i,&j))
return NULL;
if (i<0 || i>=matrix->size1) {
gsl_error ("1st index lies outside valid range of 0 .. size1 - 1",
__FILE__,
__LINE__,
GSL_EDOM );
return NULL;
}
if (j<0 || j>=matrix->size2) {
gsl_error ("2nd index lies outside valid range of 0 .. size2 - 1",
__FILE__,
__LINE__,
GSL_EDOM );
return NULL;
}
return PyFloat_FromDouble(gsl_matrix_get(matrix,i,j));
}
static PyObject* matrix_matrix_set(PyObject *self,
PyObject *args
)
{
gsl_matrix* matrix;
long int i;
long int j;
double x;
matrix=(gsl_matrix*)((matrix_matrixObject*)self)->m;
if (matrix==NULL) {
PyErr_SetString(PyExc_RuntimeError, "matrix.get got a NULL pointer");
return NULL;
}
/* get index */
if (0==PyArg_ParseTuple(args,"lld",&i,&j,&x))
return NULL;
if (i<0 || i>=matrix->size1) {
gsl_error ("1st index lies outside valid range of 0 .. size1 - 1",
__FILE__,
__LINE__,
GSL_EDOM );
return NULL;
}
if (j<0 || j>=matrix->size2) {
gsl_error ("2nd index lies outside valid range of 0 .. size2 - 1",
__FILE__,
__LINE__,
GSL_EDOM );
return NULL;
}
gsl_matrix_set(matrix,i,j,x);
Py_INCREF(Py_None);
return Py_None;
}
static PyObject* matrix_matrix_set_all(PyObject *self,
PyObject* args)
{
gsl_matrix* matrix;
double x;
matrix=(gsl_matrix*)((matrix_matrixObject*)self)->m;
if (0==PyArg_ParseTuple(args,"d",&x))
return NULL;
if (matrix==NULL) {
PyErr_SetString(PyExc_RuntimeError, "matrix.size got a NULL pointer");
return NULL;
}
gsl_matrix_set_all(matrix,x);
Py_INCREF(Py_None);
return Py_None;
}
static PyObject* matrix_matrix_set_identity(PyObject *self)
{
gsl_matrix* matrix;
matrix=(gsl_matrix*)((matrix_matrixObject*)self)->m;
if (matrix==NULL) {
PyErr_SetString(PyExc_RuntimeError, "matrix.size got a NULL pointer");
return NULL;
}
gsl_matrix_set_identity(matrix);
Py_INCREF(Py_None);
return Py_None;
}
static PyObject* matrix_matrix_set_zero(PyObject *self)
{
gsl_matrix* matrix;
matrix=(gsl_matrix*)((matrix_matrixObject*)self)->m;
if (matrix==NULL) {
PyErr_SetString(PyExc_RuntimeError, "matrix.size got a NULL pointer");
return NULL;
}
gsl_matrix_set_zero(matrix);
Py_INCREF(Py_None);
return Py_None;
}
static PyObject* matrix_matrix_transpose(PyObject *self)
{
gsl_matrix* matrix;
matrix=(gsl_matrix*)((matrix_matrixObject*)self)->m;
if (matrix==NULL) {
PyErr_SetString(PyExc_RuntimeError, "matrix.size got a NULL pointer");
return NULL;
}
gsl_matrix_transpose(matrix);
Py_INCREF(Py_None);
return Py_None;
}
static PyObject* matrix_matrix_size(PyObject *self)
{
gsl_matrix* matrix;
matrix=(gsl_matrix*)((matrix_matrixObject*)self)->m;
if (matrix==NULL) {
PyErr_SetString(PyExc_RuntimeError, "matrix.size got a NULL pointer");
return NULL;
}
return Py_BuildValue("(ll)",matrix->size1,matrix->size2);
}
static PyObject* matrix_matrix_add(PyObject *self,
PyObject *arg) {
gsl_matrix* matrix=(gsl_matrix*)((matrix_matrixObject*)self)->m;
gsl_matrix* matrix2;
int result;
if (matrix==NULL) {
PyErr_SetString(PyExc_RuntimeError, "matrix.add got a NULL pointer");
return NULL;
}
Py_INCREF(arg);
/* get histogram from argument */
if (arg==NULL || !PyObject_TypeCheck(arg,&matrix_matrixType)) {
PyErr_SetString(PyExc_TypeError, "matrix.add requires pygsl.matrix.matrix");
Py_DECREF(arg);
return NULL;
}
matrix2=(gsl_matrix*)((matrix_matrixObject*)arg)->m;
if (matrix2==NULL) {
PyErr_SetString(PyExc_RuntimeError, "matrix in argument has a NULL pointer");
return NULL;
}
result=gsl_matrix_add(matrix,matrix2);
Py_DECREF(arg);
if (result!=GSL_SUCCESS) {
return NULL;
}
Py_INCREF(Py_None);
return Py_None;
}
static PyMethodDef matrix_matrix_methods[] = {
/* {"alloc",(PyCFunction)histogram_histogram_alloc,METH_VARARGS,"allocate necessary space"}, */
{"get",(PyCFunction)matrix_matrix_get,METH_VARARGS,"gets the (i,j) element"},
{"size",(PyCFunction)matrix_matrix_size,METH_NOARGS,"returns the size as tuple"},
{"add",(PyCFunction)matrix_matrix_add,METH_O,"adds the given matrix"},
{"set",(PyCFunction)matrix_matrix_set,METH_VARARGS,"sets the (i,j) element"},
{"set_zero",(PyCFunction)matrix_matrix_set_zero,METH_NOARGS,"sets all to 0"},
{"set_identity",(PyCFunction)matrix_matrix_set_identity,METH_NOARGS,"sets diagonal to 1 and others to 0"},
{"set_all",(PyCFunction)matrix_matrix_set_identity,METH_O,"sets all entries to x"},
{"transpose",(PyCFunction)matrix_matrix_transpose,METH_NOARGS,"transposes the matrix in place"},
{NULL, NULL, 0, NULL} /* sentinel */
};
static int matrix_matrix_init(PyObject *self,
PyObject *args,
PyObject *kwds
)
{
PyObject* orig_matrix;
long int n1;
long int n2;
static char *kwlist1[] = {"matrix",NULL};
static char *kwlist2[] = {"size1","size2",NULL};
/* initialise histogram pointer */
((matrix_matrixObject*)self)->m=NULL;
/* test two call alternatives: */
if (PyArg_ParseTupleAndKeywords(args, kwds,"O!",kwlist1,&matrix_matrixType,&orig_matrix)) {
gsl_matrix* matrix;
gsl_matrix* matrix2=(gsl_matrix*)((matrix_matrixObject*)orig_matrix)->m;
if (matrix2==NULL) {
PyErr_SetString(PyExc_RuntimeError, "matrix in argument has a NULL pointer");
return -1;
}
matrix=gsl_matrix_calloc(matrix2->size1,matrix2->size2);
if (matrix==NULL)
return -1;
gsl_matrix_memcpy(matrix,matrix2);
((matrix_matrixObject*)self)->m=matrix;
return 0;
}
else {
/* reset exception */
PyErr_Clear();
}
if (PyArg_ParseTupleAndKeywords(args, kwds,"ll",kwlist2,&n1,&n2)) {
gsl_matrix* matrix;
if (n1<=0 || n2<=0) {
gsl_error ("matrix length must be positive",
__FILE__,
__LINE__,
GSL_EDOM );
return -1;
}
matrix=gsl_matrix_calloc(n1,n2);
if (matrix==NULL)
return -1;
((matrix_matrixObject*)self)->m=matrix;
return 0;
}
else {
/* set own error message */
PyErr_Clear();
PyErr_SetString(PyExc_TypeError, "matrix.init requires pygsl.matrix.matirx object or two long int argument");
return -1;
}
}
static PyObject*
matrix_matrix_getattr(PyObject* obj, char *name)
{
return Py_FindMethod(matrix_matrix_methods, obj, name);
}
static void
matrix_matrix_dealloc(PyObject* self)
{
gsl_matrix* matrix;
matrix=(gsl_matrix*)((matrix_matrixObject*)self)->m;
if (matrix!=NULL) gsl_matrix_free(matrix);
self->ob_type->tp_free(self);
}
static
PyTypeObject matrix_matrixType = {
PyObject_HEAD_INIT(NULL)
0,
"pygsl.matrix.matrix",
sizeof(matrix_matrixObject),
0,
(destructor)matrix_matrix_dealloc, /* tp_dealloc */
0, /* tp_print */
matrix_matrix_getattr, /* tp_getattr */
0, /* tp_setattr */
0, /* tp_compare */
0, /* tp_repr */
0, /* tp_as_number */
0, /* tp_as_sequence */
0, /* &matrix_marix_as_mapping,*/ /* tp_as_mapping */
0, /* tp_hash */
0, /* tp_call */
0, /* tp_str */
0, /* tp_getattro */
0, /* tp_setattro */
0, /* tp_as_buffer */
Py_TPFLAGS_DEFAULT, /* tp_flags */
0, /* tp_doc */
0, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
0, /* tp_methods */
0, /* tp_members */
0, /* tp_getset */
0, /* tp_base */
0, /* tp_dict */
0, /* tp_descr_get */
0, /* tp_descr_set */
0, /* tp_dictoffset */
(initproc)matrix_matrix_init, /* tp_init */
NULL, /* tp_alloc */
NULL, /* tp_new */
NULL /* tp_free */
};
static PyMethodDef matrixMethods[] = {
{NULL, NULL, 0, NULL} /* Sentinel */
};
void
initmatrix(void)
{
PyObject* m;
m=Py_InitModule("matrix", matrixMethods);
init_pygsl();
/* init histogram type */
matrix_matrixType.ob_type = &PyType_Type;
matrix_matrixType.tp_alloc = PyType_GenericAlloc;
matrix_matrixType.tp_new = PyType_GenericNew;
matrix_matrixType.tp_free = _PyObject_Del;
/* install histogram type */
/* important! must increment histogram type reference counter */
Py_INCREF((PyObject*)&matrix_matrixType);
PyModule_AddObject(m,"matrix", (PyObject*)&matrix_matrixType);
}
| {
"alphanum_fraction": 0.6438153586,
"avg_line_length": 26.9715099715,
"ext": "c",
"hexsha": "4de5f02ada0b1e7dc806ac81d09e59ff84e51d23",
"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/src/matrixmodule.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/src/matrixmodule.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/src/matrixmodule.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 2579,
"size": 9467
} |
/* Copyright (c) 2014, Giuseppe Argentieri <giuseppe.argentieri@ts.infn.it>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
/*
*
*
* Filename: red_gen.c
*
* Description: Redfield-type Generator
*
* Version: 1.0
* Created: 25/04/2014 22:28:19
* Revision: none
* License: BSD
*
* Author: Giuseppe Argentieri (ga), giuseppe.argentieri@ts.infn.it
* Organization: Università degli Studi di Trieste
*
*
*/
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_math.h>
#include <math.h>
#include "funcs.h"
/*
* FUNCTION
* Name: red_mat
* Description: Creating the Redfield generator matrix in Bloch form, taking as
* arguments all the integrals, the physical parameters
* and the pointer to the matrix
*
*/
int red_mat ( gsl_matrix* red_mx , void* params )
{
double integrals[12] ;
if ( integration(params,integrals) != 0 )
return -1;
/* Setting the integrals */
double rcc, icc, rss, iss, rsc, isc, rcs, ics, rc0, ic0, rs0, is0 ;
rcc = integrals[0] ;
icc = integrals[1] ;
rss = integrals[2] ;
iss = integrals[3] ;
rsc = integrals[4] ;
isc = integrals[5] ;
rcs = integrals[6] ;
ics = integrals[7] ;
rc0 = integrals[8] ;
ic0 = integrals[9] ;
rs0 = integrals[10] ;
is0 = integrals[11] ;
/* Copying the parameters */
struct f_params* pars = (struct f_params*) params ;
double o_c, b, O, o_1 ;
assign_p ( pars, &o_c, &b, &O, &o_1 ) ;
double D = sqrt(POW_2(o_1)-POW_2(O)) ;
/* Ensuring that the matrix is zeroed */
gsl_matrix_set_zero ( red_mx ) ;
/* Building the matrix */
gsl_matrix_set ( red_mx, 1, 0, (D/o_1)*(-(O/o_1)*ic0+iss+(O/o_1)*icc) ) ;
gsl_matrix_set ( red_mx, 1, 1, POW_2(D/o_1)*rc0+(O/o_1)*rss+POW_2(O/o_1)*rcc ) ;
gsl_matrix_set ( red_mx, 1, 2, o_1/4+(O/o_1)*rsc-POW_2(O/o_1)*rcs ) ;
gsl_matrix_set ( red_mx, 1, 3, (D/o_1)*(rsc-(O/o_1)*rcs) ) ;
gsl_matrix_set ( red_mx, 2, 0, (D/o_1)*(is0+isc-(O/o_1)*ics) ) ;
gsl_matrix_set ( red_mx, 2, 1, -(o_1/4)-(O/o_1)*rsc+rcs ) ;
gsl_matrix_set ( red_mx, 2, 2, POW_2(D/o_1)*rc0+rcc+(O/o_1)*rss ) ;
gsl_matrix_set ( red_mx, 2, 3, -(D/o_1)*((O/o_1)*rcc+rss) ) ;
gsl_matrix_set ( red_mx, 3, 0, (1+POW_2(O/o_1))*ics-2*(O/o_1)*isc ) ;
gsl_matrix_set ( red_mx, 3, 1, -(D/o_1)*rs0 ) ;
gsl_matrix_set ( red_mx, 3, 2, -(O*D/(o_1*o_1))*rc0 ) ;
gsl_matrix_set ( red_mx, 3, 3, (1+POW_2(O/o_1))*rcc+2*(O/o_1)*rss ) ;
/* Multiplies times -4 to obtain the Bloch matrix */
gsl_matrix_scale ( red_mx, -4 ) ;
return 0;
} /* ----- end of function red_mat ----- */
| {
"alphanum_fraction": 0.6676225235,
"avg_line_length": 33.9469026549,
"ext": "c",
"hexsha": "682f7ff433585c6862b33848283520dfbda88d86",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "54132a3c7dd0e83e27375f6c5f6ec154065a9695",
"max_forks_repo_licenses": [
"BSD-2-Clause"
],
"max_forks_repo_name": "j-silver/quantum_dots",
"max_forks_repo_path": "red_gen.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "54132a3c7dd0e83e27375f6c5f6ec154065a9695",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-2-Clause"
],
"max_issues_repo_name": "j-silver/quantum_dots",
"max_issues_repo_path": "red_gen.c",
"max_line_length": 81,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "54132a3c7dd0e83e27375f6c5f6ec154065a9695",
"max_stars_repo_licenses": [
"BSD-2-Clause"
],
"max_stars_repo_name": "j-silver/quantum_dots",
"max_stars_repo_path": "red_gen.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1250,
"size": 3836
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.