Search is not available for this dataset
text string | meta dict |
|---|---|
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_integration.h>
#include <gsl/gsl_sf_expint.h>
#include <gsl/gsl_roots.h>
#include "ccl.h"
// Analytic FT of NFW profile, from Cooray & Sheth (2002; Section 3 of https://arxiv.org/abs/astro-ph/0206508)
// Normalised such that U(k=0)=1
static double u_nfw_c(ccl_cosmology *cosmo, double rv, double c, double k, int *status) {
double rs, ks;
double f1, f2, f3, fc;
// Special case to prevent numerical problems if k=0,
// the result should be unity here because of the normalisation
if (k==0.) {
return 1.;
}
// The general k case
else{
// Scale radius for NFW (rs=rv/c)
rs = rv/c;
// Dimensionless wave-number variable
ks = k*rs;
// Various bits for summing together to get final result
f1 = sin(ks)*(gsl_sf_Si(ks*(1.+c))-gsl_sf_Si(ks));
f2 = cos(ks)*(gsl_sf_Ci(ks*(1.+c))-gsl_sf_Ci(ks));
f3 = sin(c*ks)/(ks*(1.+c));
fc = log(1.+c)-c/(1.+c);
return (f1+f2-f3)/fc;
}
}
/*----- ROUTINE: ccl_halo_concentration -----
INPUT: cosmology, a halo mass [Msun], scale factor, halo definition, concentration model label
TASK: Computes halo concentration; the ratio of virial raidus to scale radius for an NFW halo.
*/
double ccl_halo_concentration(ccl_cosmology *cosmo, double halomass,
double a, double odelta, int *status) {
double gz, g0, nu, delta_c, a_form;
double Mpiv, A, B, C;
switch(cosmo->config.halo_concentration_method){
// Bhattacharya et al. (2011; 1005.2239; Delta = 200rho_m; Table 2)
case ccl_bhattacharya2011:
if (odelta != 200.) {
*status = CCL_ERROR_CONC_DV;
ccl_cosmology_set_status_message(
cosmo,
"ccl_halomod.c: halo_concentration(): Bhattacharya (2011) concentration "
"relation only valid for Delta_v = 200");
return NAN;
}
gz = ccl_growth_factor(cosmo,a,status);
g0 = ccl_growth_factor(cosmo,1.0,status);
delta_c = 1.686;
nu = delta_c/ccl_sigmaM(cosmo, log10(halomass), a, status);
return 9.*pow(nu,-0.29)*pow(gz/g0,1.15);
// Duffy et al. (2008; 0804.2486; Table 1)
case ccl_duffy2008:
Mpiv = 2e12/cosmo->params.h; // Pivot mass in Msun (note in the paper units are Msun/h)
if (odelta == Dv_BryanNorman(cosmo, a, status)) {
// Duffy et al. (2008) for virial density haloes (second section in Table 1)
A = 7.85;
B = -0.081;
C = -0.71;
return A*pow(halomass/Mpiv,B)*pow(a,-C);
} else if (odelta == 200.) {
// Duffy et al. (2008) for x200 mean-matter-density haloes (third section in Table 1)
A = 10.14;
B = -0.081;
C = -1.01;
return A*pow(halomass/Mpiv,B)*pow(a,-C);
} else {
*status = CCL_ERROR_CONC_DV;
ccl_cosmology_set_status_message(
cosmo,
"ccl_halomod.c: halo_concentration(): Duffy (2008) virial "
"concentration only valid for virial Delta_v or 200\n");
return NAN;
}
// Constant concentration (good for tests)
case ccl_constant_concentration:
return 4.;
// Something went wrong
default:
*status = CCL_ERROR_HALOCONC;
ccl_raise_gsl_warning(*status, "ccl_halomod.c: concentration-mass relation specified incorrectly");
return NAN;
}
}
// Fourier Transforms of halo profiles
static double window_function(ccl_cosmology *cosmo, double m, double k,
double a, double odelta, ccl_win_label label,
int *status) {
double rho_matter, c, rv;
switch(label){
case ccl_nfw:
// The mean background matter density in Msun/Mpc^3
rho_matter = ccl_rho_x(cosmo, 1., ccl_species_m_label, 1, status);
// The halo virial radius
rv = r_delta(cosmo, m, a, odelta, status);
// The halo concentration for this halo mass and at this scale factor
c = ccl_halo_concentration(cosmo, m, a, odelta, status);
// The function U is normalised to 1 for k<<1 so multiplying by M/rho turns units to overdensity
return m*u_nfw_c(cosmo, rv, c, k, status)/rho_matter;
// Something went wrong
default:
*status = CCL_ERROR_HALOWIN;
ccl_raise_warning(*status, "ccl_halomod.c: Window function specified incorrectly");
return NAN;
}
}
// Parameters structure for the one-halo integrand
typedef struct{
ccl_cosmology *cosmo;
double k, a;
int *status;
} Int_one_halo_Par;
// Integrand for the one-halo integral
static double one_halo_integrand(double log10mass, void *params){
Int_one_halo_Par *p = (Int_one_halo_Par *)params;;
double halomass = pow(10,log10mass);
double odelta = Dv_BryanNorman(p->cosmo, p->a, p->status); // Virial density for haloes
// The normalised Fourier Transform of a halo density profile
double wk = window_function(p->cosmo,halomass, p->k, p->a, odelta, ccl_nfw, p->status);
// Fairly sure that there should be no ln(10) factor should be here since the integration is being specified in log10 range
double dn_dlogM = ccl_massfunc(p->cosmo, halomass, p->a, odelta, p->status);
return dn_dlogM*pow(wk,2);
}
// The one-halo term integral using gsl
static double one_halo_integral(ccl_cosmology *cosmo, double k, double a, int *status){
int one_halo_integral_status = 0, qagstatus;
double result = 0, eresult;
double log10mmin = log10(cosmo->gsl_params.HM_MMIN);
double log10mmax = log10(cosmo->gsl_params.HM_MMAX);
Int_one_halo_Par ipar;
gsl_function F;
gsl_integration_workspace *w = NULL;
w = gsl_integration_workspace_alloc(cosmo->gsl_params.HM_LIMIT);
if (w == NULL) {
*status = CCL_ERROR_MEMORY;
}
if (*status == 0) {
// Structure required for the gsl integration
ipar.cosmo = cosmo;
ipar.k = k;
ipar.a = a;
ipar.status = &one_halo_integral_status;
F.function = &one_halo_integrand;
F.params = &ipar;
// Actually does the integration
qagstatus = gsl_integration_qag(
&F, log10mmin, log10mmax,
cosmo->gsl_params.HM_EPSABS,
cosmo->gsl_params.HM_EPSREL,
cosmo->gsl_params.HM_LIMIT,
cosmo->gsl_params.HM_INT_METHOD, w,
&result, &eresult);
// Check for errors
if (qagstatus != GSL_SUCCESS) {
ccl_raise_gsl_warning(qagstatus, "ccl_halomod.c: one_halo_integral():");
*status = CCL_ERROR_ONE_HALO_INT;
ccl_cosmology_set_status_message(cosmo, "ccl_halomod.c: one_halo_integral(): Integration failure\n");
result = NAN;
}
}
// Clean up
gsl_integration_workspace_free(w);
return result;
}
// Parameters structure for the two-halo integrand
typedef struct{
ccl_cosmology *cosmo;
double k, a;
int *status;
} Int_two_halo_Par;
// Integrand for the two-halo integral
static double two_halo_integrand(double log10mass, void *params){
Int_two_halo_Par *p = (Int_two_halo_Par *)params;
double halomass = pow(10,log10mass);
double odelta = Dv_BryanNorman(p->cosmo, p->a, p->status); // Virial density for haloes
// The normalised Fourier Transform of a halo density profile
double wk = window_function(p->cosmo, halomass, p->k, p->a, odelta, ccl_nfw, p->status);
// Fairly sure that there should be no ln(10) factor should be here since the integration is being specified in log10 range
double dn_dlogM = ccl_massfunc(p->cosmo, halomass, p->a, odelta, p->status);
// Halo bias
double b = ccl_halo_bias(p->cosmo, halomass, p->a, odelta, p->status);
return b*dn_dlogM*wk;
}
// The two-halo term integral using gsl
static double two_halo_integral(ccl_cosmology *cosmo, double k, double a, int *status){
int two_halo_integral_status = 0, qagstatus;
double result = 0, eresult;
double log10mmin = log10(cosmo->gsl_params.HM_MMIN);
double log10mmax = log10(cosmo->gsl_params.HM_MMAX);
Int_two_halo_Par ipar;
gsl_function F;
gsl_integration_workspace *w = NULL;
w = gsl_integration_workspace_alloc(cosmo->gsl_params.HM_LIMIT);
if (w == NULL) {
*status = CCL_ERROR_MEMORY;
}
if (*status == 0) {
// Structure required for the gsl integration
ipar.cosmo = cosmo;
ipar.k = k;
ipar.a = a;
ipar.status = &two_halo_integral_status;
F.function = &two_halo_integrand;
F.params = &ipar;
// Actually does the integration
qagstatus = gsl_integration_qag(
&F, log10mmin, log10mmax,
cosmo->gsl_params.HM_EPSABS,
cosmo->gsl_params.HM_EPSREL,
cosmo->gsl_params.HM_LIMIT,
cosmo->gsl_params.HM_INT_METHOD, w,
&result, &eresult);
// Check for errors
if (qagstatus != GSL_SUCCESS) {
ccl_raise_gsl_warning(qagstatus, "ccl_halomod.c: two_halo_integral():");
*status = CCL_ERROR_TWO_HALO_INT;
ccl_cosmology_set_status_message(cosmo, "ccl_halomod.c: two_halo_integral(): Integration failure\n");
result = NAN;
}
}
// Clean up
gsl_integration_workspace_free(w);
return result;
}
/*----- ROUTINE: ccl_twohalo_matter_power -----
INPUT: cosmology, wavenumber [Mpc^-1], scale factor
TASK: Computes the two-halo power spectrum term in the halo model assuming NFW haloes
*/
double ccl_twohalo_matter_power(ccl_cosmology *cosmo, double k, double a, int *status){
// Get the integral
double I2h = two_halo_integral(cosmo, k, a, status);
// The addative correction is the missing part of the integral below the lower-mass limit
double A = 1.-two_halo_integral(cosmo, 0., a, status);
// Virial overdensity for haloes
double odelta = Dv_BryanNorman(cosmo, a, status);
// ...multiplied by the ratio of window functions
double W1 = window_function(cosmo, cosmo->gsl_params.HM_MMIN, k, a, odelta, ccl_nfw, status);
double W2 = window_function(cosmo, cosmo->gsl_params.HM_MMIN, 0., a, odelta, ccl_nfw, status);
A = A*W1/W2;
// Add the additive correction to the calculated integral
I2h = I2h+A;
return ccl_linear_matter_power(cosmo, k, a, status)*I2h*I2h;
}
/*----- ROUTINE: ccl_onehalo_matter_power -----
INPUT: cosmology, wavenumber [Mpc^-1], scale factor
TASK: Computes the one-halo power spectrum term in the halo model assuming NFW haloes
*/
double ccl_onehalo_matter_power(ccl_cosmology *cosmo, double k, double a, int *status){
return one_halo_integral(cosmo, k, a, status);
}
/*----- ROUTINE: ccl_onehalo_matter_power -----
INPUT: cosmology, wavenumber [Mpc^-1], scale factor
TASK: Computes the halo model power spectrum by summing the two- and one-halo terms
*/
double ccl_halomodel_matter_power(ccl_cosmology *cosmo, double k, double a, int *status){
// This matter power spectrum method doesn't work if mu / Sigma parameterisation of modified gravity
// Is turned on:
if (fabs(cosmo->params.mu_0)>1e-14 || fabs(cosmo->params.sigma_0)>1e-14){
*status = CCL_ERROR_NOT_IMPLEMENTED;
strcpy(cosmo->status_message,
"ccl_halofmod.c: ccl_halomodel_matter_power(): The halo model power spectrum "
"is not implemented the mu / Sigma modified gravity parameterisation.\n");
return NAN;
}
// Standard sum of two- and one-halo terms
return ccl_twohalo_matter_power(cosmo, k, a, status)+ccl_onehalo_matter_power(cosmo, k, a, status);
}
| {
"alphanum_fraction": 0.6865457158,
"avg_line_length": 30.8421052632,
"ext": "c",
"hexsha": "659c7ae6a002267380647f758b0f08dfa0c6647a",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2021-02-10T07:35:07.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-02-10T07:35:07.000Z",
"max_forks_repo_head_hexsha": "3a5f9dec72c6ce602ac8b11ceed0ee6c0460a926",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "benediktdiemer/CCL",
"max_forks_repo_path": "src/ccl_halomod.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "3a5f9dec72c6ce602ac8b11ceed0ee6c0460a926",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "benediktdiemer/CCL",
"max_issues_repo_path": "src/ccl_halomod.c",
"max_line_length": 125,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "3a5f9dec72c6ce602ac8b11ceed0ee6c0460a926",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "benediktdiemer/CCL",
"max_stars_repo_path": "src/ccl_halomod.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 3408,
"size": 11134
} |
/* specfunc/poch.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 */
#include <config.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_errno.h>
#include "gsl_sf_exp.h"
#include "gsl_sf_log.h"
#include "gsl_sf_pow_int.h"
#include "gsl_sf_psi.h"
#include "gsl_sf_gamma.h"
#include "error.h"
static const double bern[21] = {
0.0 /* no element 0 */,
+0.833333333333333333333333333333333e-01,
-0.138888888888888888888888888888888e-02,
+0.330687830687830687830687830687830e-04,
-0.826719576719576719576719576719576e-06,
+0.208767569878680989792100903212014e-07,
-0.528419013868749318484768220217955e-09,
+0.133825365306846788328269809751291e-10,
-0.338968029632258286683019539124944e-12,
+0.858606205627784456413590545042562e-14,
-0.217486869855806187304151642386591e-15,
+0.550900282836022951520265260890225e-17,
-0.139544646858125233407076862640635e-18,
+0.353470703962946747169322997780379e-20,
-0.895351742703754685040261131811274e-22,
+0.226795245233768306031095073886816e-23,
-0.574472439520264523834847971943400e-24,
+0.145517247561486490186626486727132e-26,
-0.368599494066531017818178247990866e-28,
+0.933673425709504467203255515278562e-30,
-0.236502241570062993455963519636983e-31
};
/* ((a)_x - 1)/x in the "small x" region where
* cancellation must be controlled.
*
* Based on SLATEC DPOCH1().
*/
/*
C When ABS(X) is so small that substantial cancellation will occur if
C the straightforward formula is used, we use an expansion due
C to Fields and discussed by Y. L. Luke, The Special Functions and Their
C Approximations, Vol. 1, Academic Press, 1969, page 34.
C
C The ratio POCH(A,X) = GAMMA(A+X)/GAMMA(A) is written by Luke as
C (A+(X-1)/2)**X * polynomial in (A+(X-1)/2)**(-2) .
C In order to maintain significance in POCH1, we write for positive a
C (A+(X-1)/2)**X = EXP(X*LOG(A+(X-1)/2)) = EXP(Q)
C = 1.0 + Q*EXPREL(Q) .
C Likewise the polynomial is written
C POLY = 1.0 + X*POLY1(A,X) .
C Thus,
C POCH1(A,X) = (POCH(A,X) - 1) / X
C = EXPREL(Q)*(Q/X + Q*POLY1(A,X)) + POLY1(A,X)
C
*/
static
int
pochrel_smallx(const double a, const double x, gsl_sf_result * result)
{
/*
SQTBIG = 1.0D0/SQRT(24.0D0*D1MACH(1))
ALNEPS = LOG(D1MACH(3))
*/
const double SQTBIG = 1.0/(2.0*M_SQRT2*M_SQRT3*GSL_SQRT_DBL_MIN);
const double ALNEPS = GSL_LOG_DBL_EPSILON - M_LN2;
if(x == 0.0) {
return gsl_sf_psi_e(a, result);
}
else {
const double bp = ( (a < -0.5) ? 1.0-a-x : a );
const int incr = ( (bp < 10.0) ? 11.0-bp : 0 );
const double b = bp + incr;
double dpoch1;
gsl_sf_result dexprl;
int stat_dexprl;
int i;
double var = b + 0.5*(x-1.0);
double alnvar = log(var);
double q = x*alnvar;
double poly1 = 0.0;
if(var < SQTBIG) {
const int nterms = (int)(-0.5*ALNEPS/alnvar + 1.0);
const double var2 = (1.0/var)/var;
const double rho = 0.5 * (x + 1.0);
double term = var2;
double gbern[24];
int k, j;
gbern[1] = 1.0;
gbern[2] = -rho/12.0;
poly1 = gbern[2] * term;
if(nterms > 20) {
/* NTERMS IS TOO BIG, MAYBE D1MACH(3) IS BAD */
/* nterms = 20; */
result->val = 0.0;
result->err = 0.0;
GSL_ERROR ("error", GSL_ESANITY);
}
for(k=2; k<=nterms; k++) {
double gbk = 0.0;
for(j=1; j<=k; j++) {
gbk += bern[k-j+1]*gbern[j];
}
gbern[k+1] = -rho*gbk/k;
term *= (2*k-2-x)*(2*k-1-x)*var2;
poly1 += gbern[k+1]*term;
}
}
stat_dexprl = gsl_sf_expm1_e(q, &dexprl);
if(stat_dexprl != GSL_SUCCESS) {
result->val = 0.0;
result->err = 0.0;
return stat_dexprl;
}
dexprl.val = dexprl.val/q;
poly1 *= (x - 1.0);
dpoch1 = dexprl.val * (alnvar + q * poly1) + poly1;
for(i=incr-1; i >= 0; i--) {
/*
C WE HAVE DPOCH1(B,X), BUT BP IS SMALL, SO WE USE BACKWARDS RECURSION
C TO OBTAIN DPOCH1(BP,X).
*/
double binv = 1.0/(bp+i);
dpoch1 = (dpoch1 - binv) / (1.0 + x*binv);
}
if(bp == a) {
result->val = dpoch1;
result->err = 2.0 * GSL_DBL_EPSILON * (fabs(incr) + 1.0) * fabs(result->val);
return GSL_SUCCESS;
}
else {
/*
C WE HAVE DPOCH1(BP,X), BUT A IS LT -0.5. WE THEREFORE USE A
C REFLECTION FORMULA TO OBTAIN DPOCH1(A,X).
*/
double sinpxx = sin(M_PI*x)/x;
double sinpx2 = sin(0.5*M_PI*x);
double t1 = sinpxx/tan(M_PI*b);
double t2 = 2.0*sinpx2*(sinpx2/x);
double trig = t1 - t2;
result->val = dpoch1 * (1.0 + x*trig) + trig;
result->err = (fabs(dpoch1*x) + 1.0) * GSL_DBL_EPSILON * (fabs(t1) + fabs(t2));
result->err += 2.0 * GSL_DBL_EPSILON * (fabs(incr) + 1.0) * fabs(result->val);
return GSL_SUCCESS;
}
}
}
/* Assumes a>0 and a+x>0.
*/
static
int
lnpoch_pos(const double a, const double x, gsl_sf_result * result)
{
double absx = fabs(x);
if(absx > 0.1*a || absx*log(GSL_MAX_DBL(a,2.0)) > 0.1) {
if(a < GSL_SF_GAMMA_XMAX && a+x < GSL_SF_GAMMA_XMAX) {
/* If we can do it by calculating the gamma functions
* directly, then that will be more accurate than
* doing the subtraction of the logs.
*/
gsl_sf_result g1;
gsl_sf_result g2;
gsl_sf_gammainv_e(a, &g1);
gsl_sf_gammainv_e(a+x, &g2);
result->val = -log(g2.val/g1.val);
result->err = g1.err/fabs(g1.val) + g2.err/fabs(g2.val);
result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val);
return GSL_SUCCESS;
}
else {
/* Otherwise we must do the subtraction.
*/
gsl_sf_result lg1;
gsl_sf_result lg2;
int stat_1 = gsl_sf_lngamma_e(a, &lg1);
int stat_2 = gsl_sf_lngamma_e(a+x, &lg2);
result->val = lg2.val - lg1.val;
result->err = lg2.err + lg1.err;
result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val);
return GSL_ERROR_SELECT_2(stat_1, stat_2);
}
}
else if(absx < 0.1*a && a > 15.0) {
/* Be careful about the implied subtraction.
* Note that both a+x and and a must be
* large here since a is not small
* and x is not relatively large.
* So we calculate using Stirling for Log[Gamma(z)].
*
* Log[Gamma(a+x)/Gamma(a)] = x(Log[a]-1) + (x+a-1/2)Log[1+x/a]
* + (1/(1+eps) - 1) / (12 a)
* - (1/(1+eps)^3 - 1) / (360 a^3)
* + (1/(1+eps)^5 - 1) / (1260 a^5)
* - (1/(1+eps)^7 - 1) / (1680 a^7)
* + ...
*/
const double eps = x/a;
const double den = 1.0 + eps;
const double d3 = den*den*den;
const double d5 = d3*den*den;
const double d7 = d5*den*den;
const double c1 = -eps/den;
const double c3 = -eps*(3.0+eps*(3.0+eps))/d3;
const double c5 = -eps*(5.0+eps*(10.0+eps*(10.0+eps*(5.0+eps))))/d5;
const double c7 = -eps*(7.0+eps*(21.0+eps*(35.0+eps*(35.0+eps*(21.0+eps*(7.0+eps))))))/d7;
const double p8 = gsl_sf_pow_int(1.0+eps,8);
const double c8 = 1.0/p8 - 1.0; /* these need not */
const double c9 = 1.0/(p8*(1.0+eps)) - 1.0; /* be very accurate */
const double a4 = a*a*a*a;
const double a6 = a4*a*a;
const double ser_1 = c1 + c3/(30.0*a*a) + c5/(105.0*a4) + c7/(140.0*a6);
const double ser_2 = c8/(99.0*a6*a*a) - 691.0/360360.0 * c9/(a6*a4);
const double ser = (ser_1 + ser_2)/ (12.0*a);
double term1 = x * log(a/M_E);
double term2;
gsl_sf_result ln_1peps;
gsl_sf_log_1plusx_e(eps, &ln_1peps); /* log(1 + x/a) */
term2 = (x + a - 0.5) * ln_1peps.val;
result->val = term1 + term2 + ser;
result->err = GSL_DBL_EPSILON*fabs(term1);
result->err += fabs((x + a - 0.5)*ln_1peps.err);
result->err += fabs(ln_1peps.val) * GSL_DBL_EPSILON * (fabs(x) + fabs(a) + 0.5);
result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val);
return GSL_SUCCESS;
}
else {
gsl_sf_result poch_rel;
int stat_p = pochrel_smallx(a, x, &poch_rel);
double eps = x*poch_rel.val;
int stat_e = gsl_sf_log_1plusx_e(eps, result);
result->err = 2.0 * fabs(x * poch_rel.err / (1.0 + eps));
result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val);
return GSL_ERROR_SELECT_2(stat_e, stat_p);
}
}
/*-*-*-*-*-*-*-*-*-*-*-* Functions with Error Codes *-*-*-*-*-*-*-*-*-*-*-*/
int
gsl_sf_lnpoch_e(const double a, const double x, gsl_sf_result * result)
{
/* CHECK_POINTER(result) */
if(a <= 0.0 || a+x <= 0.0) {
DOMAIN_ERROR(result);
}
else if(x == 0.0) {
result->val = 1.0;
result->err = 0.0;
return GSL_SUCCESS;
}
else {
return lnpoch_pos(a, x, result);
}
}
int
gsl_sf_lnpoch_sgn_e(const double a, const double x,
gsl_sf_result * result, double * sgn)
{
if(a == 0.0 || a+x == 0.0) {
*sgn = 0.0;
DOMAIN_ERROR(result);
}
else if(x == 0.0) {
*sgn = 1.0;
result->val = 1.0;
result->err = 0.0;
return GSL_SUCCESS;
}
else if(a > 0.0 && a+x > 0.0) {
*sgn = 1.0;
return lnpoch_pos(a, x, result);
}
else if(a < 0.0 && a+x < 0.0) {
/* Reduce to positive case using reflection.
*/
double sin_1 = sin(M_PI * (1.0 - a));
double sin_2 = sin(M_PI * (1.0 - a - x));
if(sin_1 == 0.0 || sin_2 == 0.0) {
*sgn = 0.0;
DOMAIN_ERROR(result);
}
else {
gsl_sf_result lnp_pos;
int stat_pp = lnpoch_pos(1.0-a, -x, &lnp_pos);
double lnterm = log(fabs(sin_1/sin_2));
result->val = lnterm - lnp_pos.val;
result->err = lnp_pos.err;
result->err += 2.0 * GSL_DBL_EPSILON * (fabs(1.0-a) + fabs(1.0-a-x)) * fabs(lnterm);
result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val);
*sgn = GSL_SIGN(sin_1*sin_2);
return stat_pp;
}
}
else {
/* Evaluate gamma ratio directly.
*/
gsl_sf_result lg_apn;
gsl_sf_result lg_a;
double s_apn, s_a;
int stat_apn = gsl_sf_lngamma_sgn_e(a+x, &lg_apn, &s_apn);
int stat_a = gsl_sf_lngamma_sgn_e(a, &lg_a, &s_a);
if(stat_apn == GSL_SUCCESS && stat_a == GSL_SUCCESS) {
result->val = lg_apn.val - lg_a.val;
result->err = lg_apn.err + lg_a.err;
result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val);
*sgn = s_a * s_apn;
return GSL_SUCCESS;
}
else if(stat_apn == GSL_EDOM || stat_a == GSL_EDOM){
*sgn = 0.0;
DOMAIN_ERROR(result);
}
else {
result->val = 0.0;
result->err = 0.0;
*sgn = 0.0;
return GSL_FAILURE;
}
}
}
int
gsl_sf_poch_e(const double a, const double x, gsl_sf_result * result)
{
/* CHECK_POINTER(result) */
if(x == 0.0) {
result->val = 1.0;
result->err = 0.0;
return GSL_SUCCESS;
}
else {
gsl_sf_result lnpoch;
double sgn;
int stat_lnpoch = gsl_sf_lnpoch_sgn_e(a, x, &lnpoch, &sgn);
int stat_exp = gsl_sf_exp_err_e(lnpoch.val, lnpoch.err, result);
result->val *= sgn;
result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val);
return GSL_ERROR_SELECT_2(stat_exp, stat_lnpoch);
}
}
int
gsl_sf_pochrel_e(const double a, const double x, gsl_sf_result * result)
{
const double absx = fabs(x);
const double absa = fabs(a);
/* CHECK_POINTER(result) */
if(absx > 0.1*absa || absx*log(GSL_MAX(absa,2.0)) > 0.1) {
gsl_sf_result lnpoch;
double sgn;
int stat_poch = gsl_sf_lnpoch_sgn_e(a, x, &lnpoch, &sgn);
if(lnpoch.val > GSL_LOG_DBL_MAX) {
OVERFLOW_ERROR(result);
}
else {
const double el = exp(lnpoch.val);
result->val = (sgn*el - 1.0)/x;
result->err = fabs(result->val) * (lnpoch.err + 2.0 * GSL_DBL_EPSILON);
result->err += 2.0 * GSL_DBL_EPSILON * (fabs(sgn*el) + 1.0) / fabs(x);
return stat_poch;
}
}
else {
return pochrel_smallx(a, x, result);
}
}
/*-*-*-*-*-*-*-*-*-* Functions w/ Natural Prototypes *-*-*-*-*-*-*-*-*-*-*/
#include "eval.h"
double gsl_sf_lnpoch(const double a, const double x)
{
EVAL_RESULT(gsl_sf_lnpoch_e(a, x, &result));
}
double gsl_sf_poch(const double a, const double x)
{
EVAL_RESULT(gsl_sf_poch_e(a, x, &result));
}
double gsl_sf_pochrel(const double a, const double x)
{
EVAL_RESULT(gsl_sf_pochrel_e(a, x, &result));
}
| {
"alphanum_fraction": 0.5883967371,
"avg_line_length": 30.0848623853,
"ext": "c",
"hexsha": "594f760dec025f38612a010d7f5b5f642fb12cba",
"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/poch.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/poch.c",
"max_line_length": 94,
"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/poch.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": 4716,
"size": 13117
} |
#pragma once
#include <vector>
#include <array>
#include <gsl/gsl>
#pragma warning(push)
#include <CppCoreCheck/Warnings.h>
#pragma warning(disable: ALL_CPPCORECHECK_WARNINGS)
#include <glm/glm.hpp>
#define GLM_ENABLE_EXPERIMENTAL
#include <glm/gtx/hash.hpp>
#pragma warning(pop)
#include <vulkan/vulkan.h>
#include "../utils/Utils.h"
#include "./RenderUtils.h"
#include "../Configuration.h"
#define VMA_USE_ALLOCATOR
#ifdef VMA_USE_ALLOCATOR
#pragma warning(push)
#include <CppCoreCheck/Warnings.h>
#pragma warning(disable: ALL_CPPCORECHECK_WARNINGS)
#include "vk_mem_alloc.h"
#pragma warning(pop)
/**
Our main unsigned in type to accomodate
vulkan's needs
*/
using uint = uint32_t;
/**
Wrapps a Vulkan Buffer with allocation information tied to it
*/
struct AllocatedBuffer {
VkBuffer buffer{};
VmaAllocation allocation{};
VmaAllocationInfo allocation_info{};
};
/**
Wrapps a Vulkan Image with allocation information tied to it
*/
struct AllocatedImage {
VkImage image{};
VmaAllocation allocation{};
VmaAllocationInfo allocation_info{};
};
#else
#pragma message ( "This program is meant to currently use VMA allocation" )
#error Current code needs to use VMA allocation
struct AllocatedBuffer {
VkBuffer buffer{};
VkDeviceMemory memory{};
};
struct AllocatedImage {
VkImage image{};
VkDeviceMemory memory{};
};
#endif
/**
Wraps a Vulkan Command Buffer with relevant
type and state information tied to it
*/
struct WrappedCommandBuffer {
VkCommandBuffer buffer{};
CommandType type{};
bool recording{ false };
};
/**
Wraps a Vulkan Render Target with all the relevant information to
render to it like the image, memory, view, width, heigth and if it has
been initializated.
We are not using an "AllocatedImage" because allocation of a render target
is done with a custom method because of the special requirements of it being
a render target.
*/
struct WrappedRenderTarget {
VkImage image{};
VkDeviceMemory memory{};
VkImageView view{};
uint width{};
uint heigth{};
bool init{ false };
};
/**
Struct that holds dynamic configuration parameters of the renderer
*/
struct RenderConfiguration {
short multisampling_samples{ config::initial_multisampling_samples };
};
struct Vertex {
glm::vec3 pos{};
glm::vec3 color{};
glm::vec2 tex_coord{};
auto static getBindingDescription() noexcept ->VkVertexInputBindingDescription {
auto binding_description = VkVertexInputBindingDescription{};
binding_description.binding = 0;
binding_description.stride = sizeof(Vertex);
binding_description.inputRate = VK_VERTEX_INPUT_RATE_VERTEX;
return binding_description;
}
auto static getAttributeDescriptions() noexcept->std::array<VkVertexInputAttributeDescription, 3> {
auto attribute_descriptions = std::array<VkVertexInputAttributeDescription, 3>{};
attribute_descriptions[0].binding = 0;
attribute_descriptions[0].location = 0;
attribute_descriptions[0].format = VK_FORMAT_R32G32B32_SFLOAT;
attribute_descriptions[0].offset = offsetof(Vertex, pos);
attribute_descriptions[1].binding = 0;
attribute_descriptions[1].location = 1;
attribute_descriptions[1].format = VK_FORMAT_R32G32B32_SFLOAT;
attribute_descriptions[1].offset = offsetof(Vertex, color);
attribute_descriptions[2].binding = 0;
attribute_descriptions[2].location = 2;
attribute_descriptions[2].format = VK_FORMAT_R32G32_SFLOAT;
attribute_descriptions[2].offset = offsetof(Vertex, tex_coord);
return attribute_descriptions;
}
auto operator==(const Vertex& other) const ->bool {
return pos == other.pos &&
color == other.color &&
tex_coord == other.tex_coord;
}
};
namespace std {
template<> struct hash<Vertex> {
size_t operator()(Vertex const& vertex) const {
return(
(hash<glm::vec3>()(vertex.pos) ^
(hash<glm::vec3>()(vertex.color) << 1)) >> 1) ^
(hash<glm::vec2>()(vertex.tex_coord) << 1);
}
};
}
/*
MVP model.
http://www.opengl-tutorial.org/es/beginners-tutorials/tutorial-3-matrices/
https://solarianprogrammer.com/2013/05/22/opengl-101-matrices-projection-view-model/
*/
struct UniformBufferObject {
glm::mat4 model{};
glm::mat4 view{};
glm::mat4 proj{};
};
struct SimpleObjScene {
std::vector<Vertex> vertices;
std::vector<uint32_t> indices;
AllocatedImage m_texture_image{};
VkImageView m_texture_image_view{};
};
#if 0
#pragma warning(push)
#include <CppCoreCheck/Warnings.h>
#pragma warning(disable: 26426)
const auto vertices = std::vector<Vertex>{
{ { -0.5f, -0.5f, 0.0f },{ 1.0f, 0.0f, 0.0f }, { 1.0f, 0.0f} },
{ { 0.5f, -0.5f, 0.0f },{ 0.0f, 1.0f, 0.0f }, { 0.0f, 0.0f } },
{ { 0.5f, 0.5f, 0.0f },{ 0.0f, 0.0f, 1.0f }, { 0.0f, 1.0f } },
{ { -0.5f, 0.5f, 0.0f },{ 1.0f, 1.0f, 1.0f }, { 1.0f, 1.0f } },
{ { -0.5f, -0.5f, -0.5f },{ 1.0f, 0.0f, 0.0f },{ 1.0f, 0.0f } },
{ { 0.5f, -0.5f, -0.5f },{ 0.0f, 1.0f, 0.0f },{ 0.0f, 0.0f } },
{ { 0.5f, 0.5f, -0.5f },{ 0.0f, 0.0f, 1.0f },{ 0.0f, 1.0f } },
{ { -0.5f, 0.5f, -0.5f },{ 1.0f, 1.0f, 1.0f },{ 1.0f, 1.0f } },
};
const auto indices = std::vector<uint16_t>{
0, 1, 2, 2, 3, 0,
4, 5, 6, 6, 7, 4
};
#pragma warning(pop)
#endif
| {
"alphanum_fraction": 0.7076953278,
"avg_line_length": 24.7281553398,
"ext": "h",
"hexsha": "e4fcef97090e6e5b8677f2809affe54310280cfe",
"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": "82e0335ee86cc9cc32d784c4b1b55ab884ae0414",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "Jazzzy/VR_ButNotReally",
"max_forks_repo_path": "VR_ButNotReally/src/render/RenderData.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "82e0335ee86cc9cc32d784c4b1b55ab884ae0414",
"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": "Jazzzy/VR_ButNotReally",
"max_issues_repo_path": "VR_ButNotReally/src/render/RenderData.h",
"max_line_length": 100,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "82e0335ee86cc9cc32d784c4b1b55ab884ae0414",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "Jazzzy/VR_ButNotReally",
"max_stars_repo_path": "VR_ButNotReally/src/render/RenderData.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1551,
"size": 5094
} |
/* monte/gsl_monte_miser.h
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000 Michael Booth
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
/* Author: MJB */
#ifndef __GSL_MONTE_MISER_H__
#define __GSL_MONTE_MISER_H__
#include <gsl/gsl_rng.h>
#include <gsl/gsl_monte.h>
#include <gsl/gsl_monte_plain.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 min_calls;
size_t min_calls_per_bisection;
double dither;
double estimate_frac;
double alpha;
size_t dim;
int estimate_style;
int depth;
int verbose;
double * x;
double * xmid;
double * sigma_l;
double * sigma_r;
double * fmax_l;
double * fmax_r;
double * fmin_l;
double * fmin_r;
double * fsum_l;
double * fsum_r;
double * fsum2_l;
double * fsum2_r;
size_t * hits_l;
size_t * hits_r;
} gsl_monte_miser_state;
int gsl_monte_miser_integrate(gsl_monte_function * f,
const double xl[], const double xh[],
size_t dim, size_t calls,
gsl_rng *r,
gsl_monte_miser_state* state,
double *result, double *abserr);
gsl_monte_miser_state* gsl_monte_miser_alloc(size_t dim);
int gsl_monte_miser_init(gsl_monte_miser_state* state);
void gsl_monte_miser_free(gsl_monte_miser_state* state);
__END_DECLS
#endif /* __GSL_MONTE_MISER_H__ */
| {
"alphanum_fraction": 0.6925465839,
"avg_line_length": 26.8333333333,
"ext": "h",
"hexsha": "d08cb8c8a883e746a9dfdee8ca759cfa5b56b145",
"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/monte/gsl_monte_miser.h",
"max_issues_count": 12,
"max_issues_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af",
"max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "manggoguy/parsec-modified",
"max_issues_repo_path": "pkgs/libs/gsl/src/monte/gsl_monte_miser.h",
"max_line_length": 81,
"max_stars_count": 64,
"max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "manggoguy/parsec-modified",
"max_stars_repo_path": "pkgs/libs/gsl/src/monte/gsl_monte_miser.h",
"max_stars_repo_stars_event_max_datetime": "2022-03-24T13:26:53.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-03-06T00:30:56.000Z",
"num_tokens": 608,
"size": 2254
} |
/**
* @file bblas_cutil.c
*
* @brief BBLAS testing utilities for float _Complex routines.
*
* BBLAS is a software package provided by Univ. of Manchester,
* Univ. of Tennessee.
*
* @version 1.0.0
* @author Samuel D. Relton
* @author Pedro V. Lara
* @author Mawussi Zounon
* @date 2016-02-20
*
* Contains routines used in the testing to modify randomly generated matrices
* and compute the average error over an entire batch etc.
*
**/
#ifndef DOXYGEN_SHOULD_SKIP_THIS
/**
* Code generation
* @generated from bblas_zutil.c normal z -> c, Mon Jun 6 09:44:14 2016
**/
#endif
#include "bblas_common.h"
#if defined(BBLAS_WITH_MKL)
#include <mkl_lapacke.h>
#else
#include <lapacke.h>
#endif
/** Include complex functions since using float complex precision **/
#define COMPLEX
/** Quick access to the matrix elements **/
#define A(i,j) A[i + j*lda]
/**
* Make a matrix symmetric/Hermitian. Makes diagonal real.
* Sets Aji = conj( Aij ) for j < i, that is, copy & conjugate
* lower triangle to upper triangle.
**/
void bblas_cmake_hermitian(int lda, int N, BBLAS_Complex32_t* A)
{
int i, j;
for( i=0; i < N; ++i ) {
A(i,i) = creal( A(i,i) );
for( j=0; j < i; ++j ) {
A(j,i) = conj( A(i,j) );
}
}
}
#ifdef COMPLEX
/**
* Make a matrix complex-symmetric
* Does NOT make diagonal real.
* Sets Aji = Aij for j < i, that is,
* copy lower triangle to upper triangle.
**/
void bblas_cmake_symmetric(int lda, int N, BBLAS_Complex32_t* A)
{
int i, j;
for( i=0; i < N; ++i ) {
for( j=0; j < i; ++j ) {
A(j,i) = A(i,j);
}
}
}
#endif
/**
* irandRange generates a random value (int)
* in the range min_n and max_n
**/
int irandRange(int min_n, int max_n)
{
return rand() % (max_n - min_n + 1) + min_n;
}
/**
* bblas_crandRange generates a random value (BBLAS_Complex32_t)
* in the range [0,max_n]: TODO replace by generic
*/
BBLAS_Complex32_t bblas_crandRange( int max_n )
{
return ( BBLAS_Complex32_t )rand()/( BBLAS_Complex32_t )( RAND_MAX/max_n );
}
/**
* Computes statistics of the relative errors to summarise them for the user.
**/
void bblas_cstatistic(bblas_ctest_t *test)
{
enum BBLAS_ROUTINE routine = test->routine;
/*Compute avg(M), avg(N), avg(K) */
if(test->batch_opts == BBLAS_VARIABLE)
{
if ((routine == BBLAS_GEMM) || (routine == BBLAS_SYMM) ||
(routine == BBLAS_HEMM) || (routine == BBLAS_TRMM) ||
(routine == BBLAS_TRSM))
{
test->avgM = bblas_avgarrayI(test->M, test->batch_count);
}
if ((routine == BBLAS_GEMM) || (routine == BBLAS_SYRK) ||
(routine == BBLAS_HERK) || (routine == BBLAS_SYR2K) ||
(routine == BBLAS_HER2K))
{
test->avgK = bblas_avgarrayI(test->K, test->batch_count);
}
test->avgN = bblas_avgarrayI(test->N, test->batch_count);
} else if (test->batch_opts == BBLAS_FIXED)
{
if ((routine == BBLAS_GEMM) || (routine == BBLAS_SYMM) ||
(routine == BBLAS_HEMM) || (routine == BBLAS_TRMM) ||
(routine == BBLAS_TRSM))
{
test->avgM = test->M[0];
}
if ((routine == BBLAS_GEMM) || (routine == BBLAS_SYRK) ||
(routine == BBLAS_HERK) || (routine == BBLAS_SYR2K) ||
(routine == BBLAS_HER2K))
{
test->avgK = test->K[0];
}
test->avgN = test->N[0];
} else
{
bblas_error("testing_cgemm_batch.c", "wrong batch_opts value");
}
/*Statistics on the error */
switch(test->target)
{
case BBLAS_MKL:
test->mkl_min_error = bblas_cminarrayD(test->mkl_error, test->batch_count);
test->mkl_avg_error = bblas_cavgarrayD(test->mkl_error, test->batch_count);
test->mkl_max_error = bblas_cmaxarrayD(test->mkl_error, test->batch_count);
test->mkl_std_error = bblas_cstdarrayD(test->mkl_error, test->batch_count);
break;
case BBLAS_CUBLAS:
case BBLAS_MAGMA:
test->device_min_error = bblas_cminarrayD(test->device_error, test->batch_count);
test->device_avg_error = bblas_cavgarrayD(test->device_error, test->batch_count);
test->device_max_error = bblas_cmaxarrayD(test->device_error, test->batch_count);
test->device_std_error = bblas_cstdarrayD(test->device_error, test->batch_count);
break;
case BBLAS_OTHER:
test->other_min_error = bblas_cminarrayD(test->other_error, test->batch_count);
test->other_avg_error = bblas_cavgarrayD(test->other_error, test->batch_count);
test->other_max_error = bblas_cmaxarrayD(test->other_error, test->batch_count);
test->other_std_error = bblas_cstdarrayD(test->other_error, test->batch_count);
break;
default:
printf("In bblas_cstatistic(): Target no defined\n");
exit(EXIT_FAILURE);
}
}
/**
* Print a matrix.
**/
void bblas_cprintmatrix(BBLAS_Complex32_t *matrix, int row, int col)
{
/*Local variables */
int i, j;
for (i=0; i < row; i++)
{
printf("\n\n");
for (j=0; j < col; j++)
{
#ifdef COMPLEX
printf("%1.2f + %1.2f\t", creal(matrix[i*col+j]), cimag(matrix[i*col+j]));
#else
printf("%1.2f",matrix[i*col+j]);
#endif
}
}
printf("\n");
}
/**
* Decide whether a batch is fixed or variable.
**/
char* bblas_getoption(enum BBLAS_OPTS opts)
{
/*Local variable */
char funcname[] = "bblas_getoption";
switch(opts)
{
case BBLAS_VARIABLE:
return "BATCH OPTION: VARIABLE";
break;
case BBLAS_FIXED:
return "BATCH OPTION: FIXED";
break;
default:
printf("ERROR in %s, undefined bblas routine name\n",funcname);
exit(EXIT_FAILURE);
}
}
/**
* Get the name of the current test routine.
**/
char* bblas_getroutine(enum BBLAS_ROUTINE routine)
{
/*Local variable */
char funcname[] = "bblas_getroutine";
switch(routine)
{
case BBLAS_GEMM:
return "CGEMM";
break;
case BBLAS_HEMM:
return "CHEMM";
break;
case BBLAS_HER2K:
return "CHER2K";
break;
case BBLAS_HERK:
return "CHERK";
break;
case BBLAS_SYMM:
return "CSYMM";
break;
case BBLAS_SYR2K:
return "CSYR2K";
break;
case BBLAS_SYRK:
return "CSYRK";
break;
case BBLAS_TRMM:
return "CTRMM";
break;
case BBLAS_TRSM:
return "CTRSM";
break;
default:
printf("ERROR in %s, undefined bblas routine name\n",funcname);
exit(EXIT_FAILURE);
}
}
/**
* Computes the maximum value of an array of real floats.
**/
float bblas_cmaxarrayD(float *myArray, int size)
{
int iter;
float maxValue = myArray[0];
for (iter = 0; iter < size; ++iter)
{
if ( myArray[iter] > maxValue )
{
maxValue = myArray[iter];
}
}
return maxValue;
}
/**
* Computes the minimum value of an array of real floats.
**/
float bblas_cminarrayD(float *myArray, int size)
{
int iter;
float minValue = myArray[0];
for (iter = 0; iter < size; ++iter)
{
if ( myArray[iter] < minValue )
{
minValue = myArray[iter];
}
}
return minValue;
}
/**
* Computes the mean value of an array of real floats.
**/
float bblas_cavgarrayD(float *myArray, int size)
{
int iter;
float avg = 0.;
for (iter = 0; iter < size; ++iter)
{
avg += myArray[iter];
}
return avg/size;
}
/**
* Computes the standard deviation of an array of real floats.
**/
float bblas_cstdarrayD(float *myArray, int size)
{
int iter;
float avg, sd=0.;
avg = bblas_cavgarrayD(myArray, size);
for (iter = 0; iter < size; ++iter)
{
sd += (myArray[iter] -avg)*(myArray[iter] -avg);
}
return sd/size;
}
/**
* Computes the minimum value of an array of integers.
**/
int bblas_minarrayI(int *myArray, int size)
{
int iter;
int minValue = myArray[0];
for (iter = 0; iter < size; ++iter)
{
if ( myArray[iter] < minValue )
{
minValue = myArray[iter];
}
}
return minValue;
}
/**
* Computes the mean of an array of integers.
**/
int bblas_avgarrayI(int *myArray, int size)
{
int iter;
int avg = 0;
for (iter = 0; iter < size; ++iter)
{
avg += myArray[iter];
}
return avg/size;
}
/**
* Transform BBLAS enum values for <tt>trans</tt>, <tt>uplo</tt> etc. to human-readable strings.
**/
char* bblas_op2char(unsigned int op)
{
char *opname = (char*)malloc(30*sizeof(char));
switch(op)
{
case BblasNoTrans:
strcpy(opname,"CblasNoTrans");
break;
case BblasTrans:
strcpy(opname,"CblasTrans");
break;
case BblasConjTrans:
strcpy(opname,"CblasConjTrans");
break;
case BblasLower:
strcpy(opname,"CblasLower");
break;
case BblasUpper:
strcpy(opname,"CblasUpper");
break;
case BblasNonUnit:
strcpy(opname,"CblasNonUnit");
break;
case BblasUnit:
strcpy(opname,"CblasUnit");
break;
case BblasLeft:
strcpy(opname,"CblasLeft");
break;
case BblasRight:
strcpy(opname,"CblasRight");
break;
default:
return 0;
exit(EXIT_FAILURE);
}
return opname;
}
/**
* Get the amount of data needed.
**/
int bblas_cnbdata(bblas_ctest_t *test)
{
enum BBLAS_OPTS batch_opts = test->batch_opts;
int nb_data;
char function_name[NAME_LENGTH] ="bblas_getdatacount";
switch(batch_opts)
{
case BBLAS_VARIABLE:
nb_data = test->batch_count;
break;
case BBLAS_FIXED:
nb_data = 1;
break;
default:
bblas_fatal_error(function_name, "wrong batch_opts value");
}
return nb_data;
}
/**
* Inject an error into the computation if this is set in the input file.
**/
void bblas_cset_error(bblas_ctest_t *test)
{
int nb_data = bblas_cnbdata(test);
int routine = test->routine;
int error_index = irandRange(0, nb_data);
if (test->global_error){
test->batch_count = -1;
return;
}
if (test->batch_opts == BBLAS_FIXED)
{
error_index = 0;
}
if (test->set_error)
{
if ((routine == BBLAS_GEMM) || (routine == BBLAS_SYMM) ||
(routine == BBLAS_HEMM) || (routine == BBLAS_TRMM) ||
(routine == BBLAS_TRSM))
{
test->M[error_index] = -1;
}else if ((routine == BBLAS_SYRK) || (routine == BBLAS_HERK) ||
(routine == BBLAS_SYR2K)|| (routine == BBLAS_HER2K))
{
test->K[error_index] = -1;
}
}
}
/**
* Check whether a computation has passed or failed our accuracy test.
* When new_accuracy=1 in the input file this uses an appropriate
* forward/backward error bound,
* otherwise this looks at the relative error.
**/
void bblas_cpassed_failed(bblas_ctest_t *test, float error, char *result, int info)
{
float eps = LAPACKE_slamch_work('e');
/* Use our new accuracy test based on forward/backward error analysis*/
if (test->new_accuracy)
{
if( (error > 1) || (info))
{
strcpy(result, "FAILED");
}else
{
strcpy(result, "PASSED");
}
}else
{
/* Use old accuracy test based on the relative error */
if((error > eps*test->tolerance) || (info))
{
strcpy(result, "FAILED");
}else
{
strcpy(result, "PASSED");
}
}
}
/**
* Set the batch_count.
**/
void bblas_cset_batch_count(bblas_ctest_t *test)
{
test->batch_count = test->minbatch_count* (test->current_iter+1);
}
#undef COMPLEX
| {
"alphanum_fraction": 0.6128891221,
"avg_line_length": 20.4946236559,
"ext": "c",
"hexsha": "b10cead5b5d4072c25b92b458d77a3d5e207a34c",
"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": "7f3bef184d4d7a9a8b5685185e16f77e5d317e6d",
"max_forks_repo_licenses": [
"BSD-2-Clause"
],
"max_forks_repo_name": "NLAFET/BBLAS-ref",
"max_forks_repo_path": "testing/bblas_cutil.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "7f3bef184d4d7a9a8b5685185e16f77e5d317e6d",
"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": "NLAFET/BBLAS-ref",
"max_issues_repo_path": "testing/bblas_cutil.c",
"max_line_length": 96,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "7f3bef184d4d7a9a8b5685185e16f77e5d317e6d",
"max_stars_repo_licenses": [
"BSD-2-Clause"
],
"max_stars_repo_name": "NLAFET/BBLAS-ref",
"max_stars_repo_path": "testing/bblas_cutil.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 3372,
"size": 11436
} |
/* rng/g05faf.c
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 James Theiler, Brian Gough
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include <config.h>
#include <math.h>
#include <stdlib.h>
#include <gsl/gsl_rng.h>
/* This is the NAG G05FAF generator. The generator returns the
upper 32 bits from each term of the sequence,
x_{n+1} = (a x_n) mod m
using 59-bit unsigned arithmetic, with a = 13^{13} and m =
2^59. The seed specifies the upper 32 bits of the initial value,
x_1, with the lower 16 bits set to 0x330E.
The theoretical value of x_{10001} is 244131582646046.
The period of this generator is ? FIXME (probably around 2^48). */
static inline void g05faf_advance (void *vstate);
static unsigned long int g05faf_get (void *vstate);
static double g05faf_get_double (void *vstate);
static void g05faf_set (void *state, unsigned long int s);
static const unsigned short int a0 = 0xFD ;
static const unsigned short int a1 = 0xC5 ;
static const unsigned short int a2 = 0x23 ;
static const unsigned short int a3 = 0x9B ;
static const unsigned short int a4 = 0x76 ;
static const unsigned short int a5 = 0x13 ;
static const unsigned short int a6 = 0x01 ;
static const unsigned short int a7 = 0x00 ;
typedef struct
{
unsigned short int x0, x1, x2, x3, x4, x5, x6, x7 ;
}
g05faf_state_t;
static inline void
g05faf_advance (void *vstate)
{
g05faf_state_t *state = (g05faf_state_t *) vstate;
const unsigned short int x0 = state->x0 ;
const unsigned short int x1 = state->x1 ;
const unsigned short int x2 = state->x2 ;
const unsigned short int x3 = state->x3 ;
const unsigned short int x4 = state->x4 ;
const unsigned short int x5 = state->x5 ;
const unsigned short int x6 = state->x6 ;
const unsigned short int x7 = state->x7 ;
unsigned long int a ;
/* This looks like it will be pretty slow. Maybe someone can produce
a more efficient implementation (it has to be portable though) */
a = a0 * x0 ;
state->x0 = (a & 0x000000FFUL) ;
a >>= 8 ;
a += a0 * x1 + a1 * x0 ;
state->x1 = (a & 0x000000FFUL) ;
a >>= 8 ;
a += a0 * x2 + a1 * x1 + a2 * x0 ;
state->x2 = (a & 0x000000FFUL) ;
a >>= 8 ;
a += a0 * x3 + a1 * x2 + a2 * x1 + a3 * x0 ;
state->x3 = (a & 0x000000FFUL) ;
a >>= 8 ;
a += a0 * x4 + a1 * x3 + a2 * x2 + a3 * x1 + a4 * x0 ;
state->x4 = (a & 0x000000FFUL) ;
a >>= 8 ;
a += a0 * x5 + a1 * x4 + a2 * x3 + a3 * x2 + a4 * x1 + a5 * x0 ;
state->x5 = (a & 0x000000FFUL) ;
a >>= 8 ;
a += a0 * x6 + a1 * x5 + a2 * x4 + a3 * x3 + a4 * x2 + a5 * x1 + a6 * x0 ;
state->x6 = (a & 0x000000FFUL) ;
a >>= 8 ;
a += (a0 * x7 + a1 * x6 + a2 * x5 + a3 * x4 + a4 * x3 + a5 * x2 + a6 * x1
+ a7 * x0) ;
state->x7 = (a & 0x00000007UL) ;
}
static unsigned long int
g05faf_get (void *vstate)
{
g05faf_state_t *state = (g05faf_state_t *) vstate;
g05faf_advance (state) ;
return ((state->x7 << 29) + (state->x6 << 21) +
(state->x5 << 13) + (state->x4 << 5) + (state->x3 >> 3));
}
static double
g05faf_get_double (void * vstate)
{
g05faf_state_t *state = (g05faf_state_t *) vstate;
g05faf_advance (state) ;
return (ldexp((double) state->x7, -3)
+ ldexp((double) state->x6, -11)
+ ldexp((double) state->x5, -19)
+ ldexp((double) state->x4, -27)
+ ldexp((double) state->x3, -35)
+ ldexp((double) state->x2, -43)
+ ldexp((double) state->x1, -51)
+ ldexp((double) state->x0, -59)) ;
}
static void
g05faf_set (void *vstate, unsigned long int s)
{
g05faf_state_t *state = (g05faf_state_t *) vstate;
if (s == 0) /* default seed */
s = 1 ;
/* FIXME: I have no idea what the nag seeding procedure is */
return;
}
static const gsl_rng_type g05faf_type =
{"g05faf", /* name */
0xffffffffUL, /* RAND_MAX */
0, /* RAND_MIN */
sizeof (g05faf_state_t),
&g05faf_set,
&g05faf_get,
&g05faf_get_double
};
const gsl_rng_type *gsl_rng_g05faf = &g05faf_type;
| {
"alphanum_fraction": 0.6258173381,
"avg_line_length": 29.0858895706,
"ext": "c",
"hexsha": "83e428d112228f722e9929ff6a0fd68bd8e84dc6",
"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/rng/g05faf.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/rng/g05faf.c",
"max_line_length": 81,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "zzpwahaha/Chimera-Control-Trim",
"max_stars_repo_path": "Chimera/3rd_Party/GSL_MSVC/rng/g05faf.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": 1609,
"size": 4741
} |
#ifndef __GSL_STATISTICS_H__
#define __GSL_STATISTICS_H__
#if !defined( GSL_FUN )
# if !defined( GSL_DLL )
# define GSL_FUN extern
# elif defined( BUILD_GSL_DLL )
# define GSL_FUN extern __declspec(dllexport)
# else
# define GSL_FUN extern __declspec(dllimport)
# endif
#endif
#include <gsl/gsl_statistics_long_double.h>
#include <gsl/gsl_statistics_double.h>
#include <gsl/gsl_statistics_float.h>
#include <gsl/gsl_statistics_ulong.h>
#include <gsl/gsl_statistics_long.h>
#include <gsl/gsl_statistics_uint.h>
#include <gsl/gsl_statistics_int.h>
#include <gsl/gsl_statistics_ushort.h>
#include <gsl/gsl_statistics_short.h>
#include <gsl/gsl_statistics_uchar.h>
#include <gsl/gsl_statistics_char.h>
#endif /* __GSL_STATISTICS_H__ */
| {
"alphanum_fraction": 0.7792553191,
"avg_line_length": 24.2580645161,
"ext": "h",
"hexsha": "71531ea8314b06daccbc0b5676f91b955b58d2fe",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2020-10-14T12:45:35.000Z",
"max_forks_repo_forks_event_min_datetime": "2020-10-14T12:45:35.000Z",
"max_forks_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "zzpwahaha/Chimera-Control-Trim",
"max_forks_repo_path": "Chimera/3rd_Party/GSL_MSVC/gsl/gsl_statistics.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "zzpwahaha/Chimera-Control-Trim",
"max_issues_repo_path": "Chimera/3rd_Party/GSL_MSVC/gsl/gsl_statistics.h",
"max_line_length": 48,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "zzpwahaha/Chimera-Control-Trim",
"max_stars_repo_path": "Chimera/3rd_Party/GSL_MSVC/gsl/gsl_statistics.h",
"max_stars_repo_stars_event_max_datetime": "2020-09-28T08:20:20.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-09-28T08:20:20.000Z",
"num_tokens": 204,
"size": 752
} |
#ifndef VM_CODE_CODE_VIEW_H
#define VM_CODE_CODE_VIEW_H
#include <cstddef>
#include <cstring>
#include <cstdint>
#include <type_traits>
#include <array>
#include <bitset>
#include <optional>
#include <variant>
#include <algorithm>
#include <iosfwd>
#include <ostream>
#include <iomanip>
#include <gsl/span>
#include <gsl/gsl>
#include "wasm_base.h"
namespace wasm::opc {
namespace detail {
template <class It>
[[gnu::pure]]
std::tuple<wasm_uint32_t, wasm_uint32_t, It> read_memory_immediate(It first, It last)
{
alignas(wasm_uint32_t) char buff1[sizeof(wasm_uint32_t)];
alignas(wasm_uint32_t) char buff2[sizeof(wasm_uint32_t)];
wasm_uint32_t flags;
wasm_uint32_t offset;
for(auto& chr: buff1)
{
assert(first != last);
chr = *first++;
}
for(auto& chr: buff2)
{
assert(first != last);
chr = *first++;
}
std::memcpy(&flags, buff1, sizeof(flags));
std::memcpy(&offset, buff1, sizeof(offset));
return std::make_tuple(flags, offset, first);
}
template <class T, class It>
[[gnu::pure]]
std::pair<T, It> read_serialized_immediate(It first, It last)
{
static_assert(std::is_trivially_copyable_v<T>);
T value;
alignas(T) char buff[sizeof(T)];
for(auto& chr: buff)
{
assert(first != last);
chr = *first++;
}
std::memcpy(&value, buff, sizeof(value));
return std::make_pair(value, first);
}
} /* namespace detail */
struct BadOpcodeError:
public std::logic_error
{
BadOpcodeError(OpCode op, const char* msg):
std::logic_error(msg),
opcode(op)
{
}
const OpCode opcode;
};
template <class It, class Visitor>
decltype(auto) visit_opcode(Visitor visitor, It first, It last)
{
assert(first != last);
OpCode op;
auto pos = first;
using value_type = typename std::iterator_traits<It>::value_type;
using underlying_type = std::underlying_type_t<OpCode>;
if constexpr(not std::is_same_v<value_type, OpCode>)
{
value_type opcode = *pos++;
op = static_cast<OpCode>(opcode);
assert(static_cast<value_type>(op) == opcode);
}
else
{
op = *pos++;
}
// Handling the invalid opcode case is optional.
if constexpr(std::is_invocable_v<Visitor, OpCode, std::nullopt_t>)
{
if(not opcode_exists(static_cast<underlying_type>(op)))
{
return visitor(
first,
last,
pos,
op,
BadOpcodeError(op, "Given op is not a valid WASM opcode.")
);
}
}
else
{
if(not opcode_exists(static_cast<underlying_type>(op)))
assert(false);
}
if(op >= OpCode::I32_LOAD and op <= OpCode::I64_STORE32)
{
wasm_uint32_t flags, offset;
std::tie(flags, offset, pos) = detail::read_memory_immediate(pos, last);
return visitor(first, last, pos, op, flags, offset);
}
else if(
(op >= OpCode::GET_LOCAL and op <= OpCode::SET_GLOBAL)
or (op == OpCode::CALL or op == OpCode::CALL_INDIRECT)
or (op == OpCode::BR or op == OpCode::BR_IF)
or (op == OpCode::ELSE)
)
{
wasm_uint32_t value;
std::tie(value, pos) = detail::read_serialized_immediate<wasm_uint32_t>(pos, last);
return visitor(first, last, pos, op, value);
}
else if(op == OpCode::BLOCK or op == OpCode::IF)
{
assert(first != last);
LanguageType tp = static_cast<LanguageType>(*first++);
wasm_uint32_t label;
std::tie(label, pos) = detail::read_serialized_immediate<wasm_uint32_t>(pos, last);
return visitor(first, last, pos, op, tp, label);
}
else if(op == OpCode::LOOP)
{
assert(first != last);
LanguageType tp = static_cast<LanguageType>(*first++);
return visitor(first, last, pos, op, tp);
}
else if(op == OpCode::BR_TABLE)
{
wasm_uint32_t len;
std::tie(len, pos) = detail::read_serialized_immediate<wasm_uint32_t>(pos, last);
auto base = pos;
std::advance(pos, (1 + len) * sizeof(wasm_uint32_t));
return visitor(first, last, pos, op, base, len);
}
switch(op)
{
case OpCode::I32_CONST: {
wasm_sint32_t v;
std::tie(v, pos) = detail::read_serialized_immediate<wasm_sint32_t>(pos, last);
return visitor(first, last, pos, op, v);
break;
}
case OpCode::I64_CONST: {
wasm_sint64_t v;
std::tie(v, pos) = detail::read_serialized_immediate<wasm_sint64_t>(pos, last);
return visitor(first, last, pos, op, v);
break;
}
case OpCode::F32_CONST: {
wasm_float32_t v;
std::tie(v, pos) = detail::read_serialized_immediate<wasm_float32_t>(pos, last);
return visitor(first, last, pos, op, v);
break;
}
case OpCode::F64_CONST: {
wasm_float64_t v;
std::tie(v, pos) = detail::read_serialized_immediate<wasm_float64_t>(pos, last);
return visitor(first, last, pos, op, v);
break;
}
default:
return visitor(op, first, pos, last);
}
assert(false and "Internal Error: All cases should have been handled by this point.");
}
struct MemoryImmediate:
public std::pair<const wasm_uint32_t, const wasm_uint32_t>
{
using std::pair<const wasm_uint32_t, const wasm_uint32_t>::pair;
};
wasm_uint32_t flags(const MemoryImmediate& immed)
{ return immed.first; }
wasm_uint32_t offset(const MemoryImmediate& immed)
{ return immed.second; }
struct BlockImmediate:
public std::pair<const LanguageType, const wasm_uint32_t>
{
using std::pair<const LanguageType, const wasm_uint32_t>::pair;
};
gsl::span<const LanguageType> signature(const BlockImmediate& immed)
{ return gsl::span<const LanguageType>(&(immed.first), 1u); }
std::size_t arity(const BlockImmediate& immed)
{ return signature(immed).size(); }
wasm_uint32_t offset(const BlockImmediate& immed)
{ return immed.second; }
struct BranchTableImmediate
{
template <class ... T>
BranchTableImmediate(T&& ... args):
table_(std::forward<T>(args)...)
{
}
wasm_uint32_t at(wasm_uint32_t idx) const
{
idx = std::min(std::size_t(table_.size() - 1u), std::size_t(idx));
wasm_uint32_t depth;
std::memcpy(&depth, table_.data() + idx, sizeof(depth));
return depth;
}
private:
const gsl::span<const char[sizeof(wasm_uint32_t)]> table_;
};
struct CodeView
{
struct Iterator;
using value_type = WasmInstruction;
using pointer = WasmInstruction*;
using const_pointer = const WasmInstruction*;
using reference = WasmInstruction&;
using const_reference = WasmInstruction&;
using size_type = std::string_view::size_type;
using difference_type = std::string_view::difference_type;
using iterator = Iterator;
using const_iterator = iterator;
private:
struct InstructionVisitor {
template <class ... T>
WasmInstruction operator()(
const char* first,
const char* last,
const char* pos,
OpCode op,
T&& ... args
)
{
assert(first < pos);
assert(pos <= last);
return make_instr(
std::string_view(first, pos - first),
op,
last,
std::forward<T>(args)...
);
}
private:
// Overload for instructions with immediate operands
WasmInstruction make_instr(std::string_view view, OpCode op, const char* last)
{ return WasmInstruction(view, op, last, std::monostate()); }
template <
class T,
/* enable overloads for the simple alternatives. */
class = std::enable_if_t<
std::disjunction_v<
std::is_same_v<std::decay_t<T>, wasm_uint32_t>,
std::is_same_v<std::decay_t<T>, wasm_sint32_t>,
std::is_same_v<std::decay_t<T>, wasm_sint64_t>,
std::is_same_v<std::decay_t<T>, wasm_float32_t>,
std::is_same_v<std::decay_t<T>, wasm_float64_t>
>
>
>
WasmInstruction make_instr(std::string_view view, OpCode op, const char* last, T&& arg)
{ return WasmInstruction(view, op, last, std::forward<T>(arg)); }
/// Loop overload
WasmInstruction make_instr(std::string_view view, OpCode op, const char* last, LanguageType tp)
{ return WasmInstruction(view, op, last, tp); }
/// Branch table overload
WasmInstruction make_instr(std::string_view view, OpCode op, const char* last, const char* base, wasm_uint32_t len)
{
assert(last > base);
std::size_t byte_count = base - last;
std::size_t bytes_needed = sizeof(wasm_uint32_t) * (len + 1u);
assert(byte_count >= bytes_needed);
// the table and 'view' should end at the same byte address
assert(view.data() + view.size() == (base + (len + 1u) * sizeof(wasm_uint32_t)));
using buffer_type = const char[sizeof(wasm_uint32_t)];
auto table = gsl::span<buffer_type>(reinterpret_cast<buffer_type*>(base), len + 1u);
return WasmInstruction(view, op, last, table);
}
/// Block overload
WasmInstruction make_instr(std::string_view view, OpCode op, const char* last, LanguageType tp, wasm_uint32_t label)
{ return WasmInstruction(view, op, last, BlockImmediate(tp, label)); }
/// Memory overload
WasmInstruction make_instr(std::string_view view, OpCode op, const char* last, wasm_uint32_t flags, wasm_uint32_t offset)
{ return WasmInstruction(view, op, last, MemoryImmediate(flags, offset)); }
/// Invalid opcode overload
[[noreturn]]
WasmInstruction make_instr(std::string_view, OpCode, const char*, const BadOpCodeError& err)
{ throw err; }
};
public:
struct Iterator {
using value_type = CodeView::value_type;
using difference_type = CodeView::difference_type;
using pointer = CodeView::pointer;
using reference = CodeView::value_type;
using iterator_category = std::input_iterator_tag;
friend bool operator==(const Iterator& left, const Iterator& right)
{ return left.code_ == right.code_; }
friend bool operator!=(const Iterator& left, const Iterator& right)
{ return not (left == right); }
private:
gsl::not_null<CodeView*> code_;
};
CodeView(const WasmFunction& func):
function_(&func),
code_(code(func))
{
}
const WasmFunction* function() const
{ return function_; }
OpCode current_op() const
{
assert(ready());
return static_cast<WasmInstruction>(code_.front());
}
bool done() const
{ return not code_.empty(); }
std::optional<WasmInstruction> next_instruction() const
{
assert(ready());
if(code_.size() == 0)
return std::nullopt;
return visit_opcode(InstructionVisitor{}, code_.data(), code_.data() + code_.size());
}
const char* pos() const
{ return code_.data(); }
void advance(const CodeView& other)
{
assert(function() == other.function());
assert(ready());
assert(code_.data() + code_.size() == other.code_.data() + other.code_.size());
assert(code_.data() < other.code_.data());
code_ = other.code_;
}
private:
bool ready() const
{
if(done())
return false;
assert(opcode_exists(code_.front()));
return true;
}
const WasmFunction* function_;
std::string_view code_;
};
} /* namespace opc */
} /* namespace wasm */
#endif /* VM_CODE_CODE_VIEW_H */
| {
"alphanum_fraction": 0.6959777287,
"avg_line_length": 25.5945945946,
"ext": "h",
"hexsha": "36136a29384c3830decc21768fbf5d5191b9ea91",
"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": "8a56c1706e2723ece36e3642bae9e36792dbd7b2",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "tvanslyke/wasm-cpp",
"max_forks_repo_path": "include/vm/code/CodeView.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "8a56c1706e2723ece36e3642bae9e36792dbd7b2",
"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": "tvanslyke/wasm-cpp",
"max_issues_repo_path": "include/vm/code/CodeView.h",
"max_line_length": 123,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "8a56c1706e2723ece36e3642bae9e36792dbd7b2",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "tvanslyke/wasm-cpp",
"max_stars_repo_path": "include/vm/code/CodeView.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 2910,
"size": 10417
} |
// Copyright (c) 2005 - 2009 Marc de Kamps, Dave Harrison
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
// * Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software
// without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY
// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
// USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// If you use this software in work leading to a scientific publication, you should cite
// the 'currently valid reference', which can be found at http://miind.sourceforge.net
#ifndef _CODE_LIBS_NUMTOOLSLIB_INTERPOLATION_INCLUDE_GUARD
#define _CODE_LIBS_NUMTOOLSLIB_INTERPOLATION_INCLUDE_GUARD
// Date: 9-02-2009
// Author: Dave Harrison
#include <valarray>
#include <utility>
#include <gsl/gsl_interp.h>
namespace NumtoolsLib
{
//! Define types of interpolation
enum InterpType
{
INTERP_LINEAR,
INTERP_CSPLINE,
INTERP_AKIMA
};
class Interpolator
{
public:
/*!
Interpolator object to wrap GSL interpolation functions
interp_type Type of Interpolation to use: INTERP_LINEAR/_CSPLINE/_AKIMA
xs Array of x values
ys array of y values
Throws NumtoolsException on GSL error
*/
Interpolator(const InterpType interp_type, const std::valarray<double>& xs,
const std::valarray<double>& ys);
~Interpolator();
/*!
Retrieve an interpolated y value for position x
Throws NumtoolsLibException on error
*/
double InterpValue(const double x);
private:
//! The accelerator object
gsl_interp_accel* _acc;
//! The interpolation object
gsl_interp* _interp;
//! The x values
std::valarray<double>& _x;
//! The y values
std::valarray<double>& _y;
//! The size of the x & y arrays
const size_t _size;
};
}
#endif // include guard
| {
"alphanum_fraction": 0.6690497468,
"avg_line_length": 44.76,
"ext": "h",
"hexsha": "c388f43e4053a9028b085b3ccc9b323439dad246",
"lang": "C",
"max_forks_count": 9,
"max_forks_repo_forks_event_max_datetime": "2022-03-08T12:18:18.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-09-14T20:52:07.000Z",
"max_forks_repo_head_hexsha": "4b321c62c2bd27eb0d5d8336a16a9e840ba63856",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "dekamps/miind",
"max_forks_repo_path": "libs/NumtoolsLib/Interpolation.h",
"max_issues_count": 41,
"max_issues_repo_head_hexsha": "4b321c62c2bd27eb0d5d8336a16a9e840ba63856",
"max_issues_repo_issues_event_max_datetime": "2022-03-21T16:20:37.000Z",
"max_issues_repo_issues_event_min_datetime": "2015-08-25T07:50:55.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "dekamps/miind",
"max_issues_repo_path": "libs/NumtoolsLib/Interpolation.h",
"max_line_length": 163,
"max_stars_count": 13,
"max_stars_repo_head_hexsha": "4b321c62c2bd27eb0d5d8336a16a9e840ba63856",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "dekamps/miind",
"max_stars_repo_path": "libs/NumtoolsLib/Interpolation.h",
"max_stars_repo_stars_event_max_datetime": "2022-03-22T20:26:47.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-09-15T17:28:25.000Z",
"num_tokens": 679,
"size": 3357
} |
/*
Copyright (C) 2006-2007 M.A.L. Marques
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include "util.h"
#include "xc.h"
void func(double *x, int n, void *ex)
{
int i;
for(i=0; i<n;i++)
x[i] = cos(x[i]);
}
void test_integration()
{
double a, b, result;
for(b=1e-8; b<5; b+=0.001){
result = xc_integrate(func, NULL, a, b);
printf("%lf %lf\n", b, result);
}
}
#include <gsl/gsl_sf_expint.h>
#include <gsl/gsl_sf_bessel.h>
void test_expi()
{
double b, r1, r2, r3, r4;
int n;
n = 1;
for(b=1e-3; b<50; b+=0.01){
r1 = xc_bessel_K0(b);
//r2 = gsl_sf_bessel_K0(b);
//r3 = bessi1(b);
printf("%5.3lf %12.10lf %12.10lf %12.10lf\n", b, r1, r2, r3);
}
}
void test_lda()
{
xc_func_type l1, l2, l3;
int i;
//xc_func_init(&l1, XC_LDA_XC_KSDT2, XC_POLARIZED);
//xc_func_init(&l1, XC_LDA_C_PW, XC_UNPOLARIZED);
xc_func_init(&l3, XC_LDA_X, XC_UNPOLARIZED);
//xc_lda_xc_ksdt_set_params(&l1, 1000.0);
//xc_lda_c_1d_csc_set_params(&l2, 1, 1.0);
for(i=0; i<=1000; i++){
double dens, rs, zeta, rho[2];
double ec1, vc1[2], fxc1[3], kxc1[4];
double ec2, vc2[2], fxc2[3], kxc2[4];
double ec3, vc3[2], fxc3[3], kxc3[4];
//rs = 0.5 + i/500.0;
//zeta = -1.0 + 2.0*i/1000000000.0;
//dens = 1.0/(4.0/3.0*M_PI*pow(rs,3)); /* 3D */
//dens = 1.0/(2.0*rs); /* 1D */
//rho[0] = dens*(1.0 + zeta)/2.0;
//rho[1] = dens*(1.0 - zeta)/2.0;
rho[0] = 0.05 + i/1000.0;
rho[1] = 0.001;
//rho[0] = 1.0/(2.0*rs);
//rho[1] = 0.0;
//dens = rho[0] + rho[1];
//xc_lda_exc_vxc_fxc(&l1, 1, rho, &ec1, vc1, NULL, NULL);
//xc_lda(&l2, 1, rho, &ec2, vc2, NULL, NULL);
//xc_lda_fxc_fd(&l2, rho, fxc2);
//xc_lda_kxc_fd(&l2, rho, kxc2);
//rho[0] = dens; rho[1] = 0.0;
//xc_lda(&l3, rho, &ec3, vc3, fxc3, kxc3);
// printf("%e\t%e\t%e\n", dens, (fxc1[0]+2.0*fxc1[1]+fxc1[2])/4.0, fxc3[0]);
// printf("%e\t%e\t%e\n", dens, (kxc1[0]+3.0*kxc1[1]+3.0*kxc1[2]+kxc1[3])/8.0, kxc3[0]);
printf("%e\t%e\t%e\n", rho[0], (rho[0] + rho[1])*ec1, vc1[0]);
}
}
void test_ak13()
{
xc_func_type gga;
double beta = 0.13;
double x, rho[2] = {0.0, 0.0}, sigma[3] = {0.0, 0.0, 0.0}, zk, vrho[2], vsigma[3];
double tmp1, tmp2;
int i;
xc_func_init(&gga, XC_GGA_X_AK13, XC_POLARIZED);
for(i=0; i<=10000; i++){
x = 500.0*i/(10000.0);
rho[0] = 0.12*exp(-beta * x);
sigma[0] = 0.12*0.12*beta*beta * rho[0]*rho[0];
xc_gga_exc_vxc(&gga, 1, rho, sigma, &zk, vrho, vsigma);
tmp2 = 1.74959015598863046792081721182*beta*x/3.0- 1.62613336586517367779736042170*log(x);
fprintf(stderr, "%16.10lf\t%16.10lf\t%16.10lf\t%16.10lf\n", x, vrho[0], vsigma[0]*sqrt(sigma[0]),
-X_FACTOR_C*X2S*tmp2/2.0);
}
}
void test_enhance()
{
double x, f, dfdx, d2fdx2, d3fdx3;
xc_func_type gga1, gga2, gga3, gga4;
xc_func_init(&gga1, XC_GGA_X_B88, XC_POLARIZED);
xc_func_init(&gga2, XC_GGA_X_GG99, XC_POLARIZED);
for(x=0.01; x<200; x+=0.01){
//printf("%le", x);
//xc_gga_x_b88_enhance(&gga1, 1, x, &f, &dfdx, &d2fdx2, &d3fdx3);
//printf("\t%le", -f*X_FACTOR_C);
//xc_gga_x_gg99_enhance(&gga2, 1, x, &f, &dfdx, &d2fdx2, &d3fdx3);
printf("%le\t%le\t%le\n", x, f, dfdx);
}
}
void test_gga()
{
xc_func_type gga, ggap;
int i, npoints = 1;
double *rho, *sigma;
double *zk, zkp, *vrho, vrhop[2], *vsigma, vsigmap[3];
double *v2rho2, *v2rhosigma, *v2sigma2;
double *v3rho3, *v3rho2sigma, *v3rhosigma2, *v3sigma3;
rho = libxc_malloc( 2*npoints*sizeof(double));
sigma = libxc_malloc( 3*npoints*sizeof(double));
zk = libxc_malloc( 1*npoints*sizeof(double));
vrho = libxc_malloc( 2*npoints*sizeof(double));
vsigma = libxc_malloc( 3*npoints*sizeof(double));
v2rho2 = libxc_malloc( 3*npoints*sizeof(double));
v2rhosigma = libxc_malloc( 6*npoints*sizeof(double));
v2sigma2 = libxc_malloc( 6*npoints*sizeof(double));
v3rho3 = libxc_malloc( 4*npoints*sizeof(double));
v3rho2sigma = libxc_malloc( 9*npoints*sizeof(double));
v3rhosigma2 = libxc_malloc(12*npoints*sizeof(double));
v3sigma3 = libxc_malloc(10*npoints*sizeof(double));
xc_func_init(&gga, XC_GGA_C_PW91, XC_POLARIZED);
/*
for(i=1; i<=10000; i++){
double x = 30.0*i/(10000.0), f, df, d2f, d3f;
double c2 = 10.0/81.0;
xc_gga_x_b88_enhance(&gga, 3, x, &f, &df, &d2f, &d3f);
printf("%20.14e %20.14e", X2S*X2S*x*x, (f-1.0)/(c2*X2S*X2S*x*x));
xc_gga_x_ev93_enhance(&gga, 3, x, &f, &df, &d2f, &d3f);
printf(" %20.14e\n", (f-1.0)/(c2*X2S*X2S*x*x));
}
exit(0);
*/
for(i=0; i<=10000; i++){
rho[0] = .01;
rho[1] = 0.2;
sigma[0] = 0.1;
sigma[1] = 0.00002;
sigma[2] = 0.5 + i/1000.0;
//xc_gga(&gga, 1, rho, sigma, zk, vrho, vsigma, v2rho2, v2rhosigma, v2sigma2, NULL, v3rho2sigma, v3rhosigma2, v3sigma3);
fprintf(stderr, "%16.10le\t%16.10le\t%16.10le\n", sigma[2], vsigma[2], v2sigma2[5]);
}
/*
for(i=0; i<npoints; i++){
rho[2*i + 0] = 0.048 + i/10000.0;
rho[2*i + 1] = 0.025;
sigma[3*i + 0] = 0.0046;
sigma[3*i + 1] = 0.0044;
sigma[3*i + 2] = 0.0041;
}
xc_gga(&gga, npoints, rho, sigma, zk, vrho, vsigma, v2rho2, v2rhosigma, v2sigma2, v3rho3, v3rho2sigma, v3rhosigma2, v3sigma3);
for(i=0; i<npoints; i++){
fprintf(stderr, "%16.10lf\t%16.10lf\t%16.10lf\n", rho[2*i + 0], vrho[2*i + 0], v2rho2[3*i + 0]);
}
*/
xc_func_end(&gga);
libxc_free(rho); libxc_free(sigma);
libxc_free(zk); libxc_free(vrho); libxc_free(vsigma);
libxc_free(v2rho2); libxc_free(v2rhosigma); libxc_free(v2sigma2);
libxc_free(v3rho3); libxc_free(v3rho2sigma); libxc_free(v3rhosigma2); libxc_free(v3sigma3);
}
void test_mgga()
{
xc_func_type mgga1, mgga2;
int i;
xc_func_init(&mgga1, XC_GGA_C_LYP, XC_POLARIZED);
xc_func_init(&mgga2, XC_MGGA_X_SCAN, XC_POLARIZED);
//xc_mgga_c_tpss_init(tpss2.mgga);
for(i=0; i<=1000; i++){
double rho[2], sigma[3], tau[2], lapl[2];
double zk, vrho[2], vsigma[3], vtau[2], vlapl[2];
double zk2, vrho2[2], vsigma2[3], vtau2[2], vlapl2[2];
double v2rho2[3], v2sigma2[6], v2lapl2[3], v2tau2[3];
double v2rhosigma[6], v2rholapl[3], v2rhotau[3];
double v2sigmalapl[6], v2sigmatau[6], v2lapltau[3];
rho[0] = 0.3;
rho[1] = 0.4;
sigma[0] = 0.2032882206468622;
sigma[1] = 0.11;
sigma[2] = 0.7 + i/10.0;
tau[0] = 1.0;
tau[1] = 0.15;
lapl[0] = -0.1518421131246519;
lapl[1] = 0.12;
//xc_mgga(&mgga1, 1, rho, sigma, lapl, tau,
// &zk, vrho, vsigma, vlapl, vtau,
// v2rho2, v2sigma2, v2lapl2, v2tau2, v2rhosigma, v2rholapl, v2rhotau,
// v2sigmalapl, v2sigmatau, v2lapltau);
//xc_mgga(&mgga2, 1, rho, sigma, lapl, tau,
// &zk2, vrho2, vsigma2, vlapl2, vtau2,
// NULL, v2sigma2, v2lapl2, v2tau2, v2rhosigma, v2rholapl, v2rhotau,
// v2sigmalapl, v2sigmatau, v2lapltau);
//xc_mgga_exc(&mgga2, 1, rho, sigma, lapl, tau,
// &zk2);
xc_gga_exc_vxc(&mgga1, 1, rho, sigma,
&zk, vrho, vsigma);
xc_mgga_exc_vxc(&mgga2, 1, rho, sigma, lapl, tau,
&zk2, vrho2, vsigma2, vlapl2, vtau2);
fprintf(stderr, "%16.10lf\t%16.10lf\t%16.10lf\n", sigma[2], zk2*(rho[0]+rho[1]), vsigma2[2]);
}
xc_func_end(&mgga1);
xc_func_end(&mgga2);
}
void test_neg_rho()
{
xc_func_type func;
double rho[5][2] = {
{9.03897273e-06, -1.00463992e-06},
{8.48383564e-06, -3.51231267e-07},
{1.45740621e-08, -2.94546705e-09},
{2.62778445e-07, -1.00191745e-07},
{2.55745103e-06, -1.54789964e-06}
};
double sigma[5][3] = {
{1.20122271e-08, 4.83240746e-09, 6.24774836e-09},
{1.54146602e-07, 1.41584609e-07, 1.36663204e-07},
{2.75312438e-08, 2.75224049e-08, 2.75135719e-08},
{1.90251649e-07, 1.91241798e-07, 1.92240989e-07},
{9.29562712e-09, 7.83940082e-09, 8.05714636e-09}
};
double vsigma[5][3];
double zk[5], vk[5][2];
int i, func_id;
for(func_id=1; func_id<1000; func_id++){
if(xc_func_init(&func, func_id, XC_POLARIZED) != 0) continue;
if(func_id == XC_LDA_C_2D_PRM || func_id == XC_GGA_X_LB) goto end;
printf("\n%s:\n", func.info->name);
switch(func.info->family){
case XC_FAMILY_LDA:
xc_lda_exc_vxc(&func, 5, &rho[0][0], zk, &vk[0][0]);
break;
case XC_FAMILY_GGA:
xc_gga_exc_vxc(&func, 5, &rho[0][0], &sigma[0][0], zk, &vk[0][0], &vsigma[0][0]);
break;
}
switch(func.info->family){
case XC_FAMILY_LDA:
for(i=0; i<5; i+=1)
printf("%.8e %.8e %.8e %.8e %.8e\n",
rho[i][0], rho[i][1], zk[i], vk[i][0], vk[i][1]);
break;
case XC_FAMILY_GGA:
for(i=0; i<5; i+=1)
printf("%.8e %.8e %.8e %.8e %.8e %.8e %.8e %.8e %.8e %.8e %.8e\n",
rho[i][0], rho[i][1], sigma[i][0], sigma[i][1], sigma[i][2],
zk[i], vk[i][0], vk[i][1], vsigma[i][0], vsigma[i][1], vsigma[i][2]);
break;
}
end:
xc_func_end(&func);
}
}
double xc_mgga_x_mbrxc_get_x(double Q);
double xc_mgga_x_br89_get_x(double Q);
void test_mbrxc()
{
double Q, x, rhs, Q2;
for(Q=-10.1e4; Q<10.1e4; Q+=.01e4){
printf("Q = %lf ", Q);
fflush(stdout);
//x = xc_mgga_x_mbrxc_get_x(Q);
//rhs = pow(1.0 + x, 5.0/3.0)*exp(-2.0*x/3.0)/(x - 3.0);
//Q2 = pow(32.0*M_PI, 2.0/3.0)/(6.0*rhs);
x = xc_mgga_x_br89_get_x(Q);
rhs = x*exp(-2.0*x/3.0)/(x - 2.0);
Q2 = 2.0/3.0*pow(M_PI, 2.0/3.0)/rhs;
printf("Q2 = %lf x = %lf\n", Q2, x);
}
}
int main()
{
//test_expi();
//test_integration();
//test_neg_rho();
//test_lda();
//test_enhance();
//test_gga();
//test_ak13();
//test_mgga();
test_mbrxc();
//printf("number = '%d'; key = '%s'", 25, xc_functional_get_name(25));
return 0;
}
| {
"alphanum_fraction": 0.5802581166,
"avg_line_length": 27.7039106145,
"ext": "c",
"hexsha": "27dc68a841b6dc6e4ff1b7ebd6150c7726195498",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2022-01-03T18:16:26.000Z",
"max_forks_repo_forks_event_min_datetime": "2022-01-03T18:16:26.000Z",
"max_forks_repo_head_hexsha": "3c5f266812cad0b6d570bef9f5abb590d044ef92",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "pmu2022/lsms",
"max_forks_repo_path": "external/libxc-5.1.6/src/test.c",
"max_issues_count": 3,
"max_issues_repo_head_hexsha": "3c5f266812cad0b6d570bef9f5abb590d044ef92",
"max_issues_repo_issues_event_max_datetime": "2021-09-25T14:05:10.000Z",
"max_issues_repo_issues_event_min_datetime": "2021-09-14T01:30:26.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "pmu2022/lsms",
"max_issues_repo_path": "external/libxc-5.1.6/src/test.c",
"max_line_length": 134,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "3c5f266812cad0b6d570bef9f5abb590d044ef92",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "pmu2022/lsms",
"max_stars_repo_path": "external/libxc-5.1.6/src/test.c",
"max_stars_repo_stars_event_max_datetime": "2022-01-27T14:45:51.000Z",
"max_stars_repo_stars_event_min_datetime": "2022-01-27T14:45:51.000Z",
"num_tokens": 4464,
"size": 9918
} |
/**
* Set of routines to handle absolute flux calibration of a spectrum
* structure.
* The response curves can be in ASCII or (preferably) in FITS
* binary format (first extension). ASCI format is simply three
* space separated colums (WAVELENGTH, THROUGHPUT, ERROR). The FITS
* binary table must contain three columns with names WAVELENGTH,
* SENSITIVITY, ERROR. The throughput should be DN/s per Erg/cm^2/s/A.
*/
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_interp.h>
#include <gsl/gsl_roots.h>
#include "aXe_grism.h"
#include "disp_conf.h"
#include "fringe_conf.h"
#include "spc_wl_calib.h"
#include "spc_resp.h"
#define MIN(x,y) (((x)<(y))?(x):(y))
#define MAX(x,y) (((x)>(y))?(x):(y))
/**
* Function: get_response_function_from_FITS
* This function reads a FITS table, reads the WAVELENGTH,
* SENSITIVITY, and ERROR columns and returns a spectrum
* structure which has been populated with this throughput.
*
* Parameters:
* @param filename - a pointer to a char array containing the
* name of an existing FITS file
* @param hdunum - the extension number to read (2 for STSDAS tables)
*
* Returns:
* @return res - a pointer to a newly allocated spectrum structure
*/
spectrum *get_response_function_from_FITS(char filename[], int hdunum)
{
fitsfile *input;
int f_status = 0;
int hdutype, anynul;
double *lambda, *resp, *error;
double tmp;
long numrows;
int colnum, i;
spectrum *res;
// Open the file for reading
fits_open_file (&input, filename, READONLY, &f_status);
if (f_status)
{
ffrprt (stderr, f_status);
aXe_message (aXe_M_FATAL, __FILE__, __LINE__,
"get_response_function_fromFITS: "
"Could not open" " file: %s",
filename);
}
/* Move to first hdu */
fits_movabs_hdu (input, hdunum, &hdutype, &f_status);
if (f_status)
{
ffrprt (stderr, f_status);
aXe_message (aXe_M_FATAL, __FILE__, __LINE__,
"get_response_function_fromFITS: "
"Could not read extention %d from file: %s",
hdunum, filename);
}
/* Get number of rows */
fits_get_num_rows (input, &numrows, &f_status);
if (f_status) {
ffrprt (stderr, f_status);
aXe_message (aXe_M_FATAL, __FILE__, __LINE__,
"get_response_function_fromFITS: "
"Could not determine the number of rows in"
" table %s",filename);
}
/* Allocate temporary memory space */
lambda = (double *) malloc(numrows*sizeof(double));
if (!lambda) {
aXe_message (aXe_M_ERROR, __FILE__, __LINE__,
"Memory allocation failed");
}
resp = (double *) malloc(numrows*sizeof(double));
if (!resp) {
aXe_message (aXe_M_ERROR, __FILE__, __LINE__,
"Memory allocation failed");
}
error = (double *) malloc(numrows*sizeof(double));
if (!error) {
aXe_message (aXe_M_ERROR, __FILE__, __LINE__,
"Memory allocation failed");
}
/**************************/
/* Read the WAVELENGTH column */
/**************************/
/* Get column number */
fits_get_colnum (input, CASEINSEN, "WAVELENGTH", &colnum, &f_status);
if (f_status)
{
ffrprt (stderr, f_status);
aXe_message (aXe_M_FATAL, __FILE__, __LINE__,
"get_response_function_fromFITS: "
"Could not determine WAVELENGTH column number in "
" table %s",filename);
}
/* Read the data */
fits_read_col (input, TDOUBLE, colnum, 1, 1, numrows, NULL, lambda,
&anynul, &f_status);
if (f_status)
{
ffrprt (stderr, f_status);
aXe_message (aXe_M_FATAL, __FILE__, __LINE__,
"get_response_function_fromFITS: "
"Could not read content of WAVELENGTH column "
" from BINARY table %s",filename);
}
/**************************/
/* Read the SENSITIVITY column */
/**************************/
/* Get column number */
fits_get_colnum (input, CASEINSEN, "SENSITIVITY", &colnum, &f_status);
if (f_status)
{
ffrprt (stderr, f_status);
aXe_message (aXe_M_FATAL, __FILE__, __LINE__,
"get_response_function_fromFITS: "
"Could not determine SENSITIVITY column number in "
" table %s",filename);
}
/* Read the data */
fits_read_col (input, TDOUBLE, colnum, 1, 1, numrows, NULL, resp,
&anynul, &f_status);
if (f_status)
{
ffrprt (stderr, f_status);
aXe_message (aXe_M_FATAL, __FILE__, __LINE__,
"get_response_function_fromFITS: "
"Could not read content of SENSITIVITY column "
" from BINARY table %s",filename);
}
/**************************/
/* Read the ERROR column */
/**************************/
/* Get column number */
fits_get_colnum (input, CASEINSEN, "ERROR", &colnum, &f_status);
if (f_status)
{
ffrprt (stderr, f_status);
aXe_message (aXe_M_FATAL, __FILE__, __LINE__,
"get_response_function_fromFITS: "
"Could not determine ERROR column number in "
" table %s",filename);
}
/* Read the data */
fits_read_col (input, TDOUBLE, colnum, 1, 1, numrows, NULL, error,
&anynul, &f_status);
if (f_status)
{
ffrprt (stderr, f_status);
aXe_message (aXe_M_FATAL, __FILE__, __LINE__,
"get_response_function_fromFITS: "
"Could not read content of ERROR column "
" from BINARY table %s",filename);
}
/* Allocate memory */
res = (spectrum *) malloc(sizeof(spectrum));
if(!res) {
aXe_message (aXe_M_ERROR, __FILE__, __LINE__,
"Memory allocation failed");
}
res->spec = (spc_entry *) malloc(numrows*sizeof(spc_entry));
if(!(res->spec)) {
aXe_message (aXe_M_ERROR, __FILE__, __LINE__,
"Memory allocation failed");
}
for (i=0;i<numrows;i++) {
res->spec[i].lambda_mean = lambda[i];
res->spec[i].flux = resp[i];
res->spec[i].ferror = error[i];
}
res->spec_len=i;
// define the minimum and maximum wavelength
res->lambdamin=res->spec[0].lambda_mean;
res->lambdamax=res->spec[numrows-1].lambda_mean;
// check whether the wavelength is raising.
// switch minimum and maximum for falling spectrum
if (res->lambdamin > res->lambdamax)
{
tmp = res->lambdamin;
res->lambdamin = res->lambdamax;
res->lambdamax = tmp;
}
fits_close_file(input,&f_status);
if (f_status) {
aXe_message (aXe_M_ERROR, __FILE__, __LINE__,
"Could not close %s",filename);
}
free(lambda);
free(resp);
free(error);
return res;
}
/**
* Function: apply_response_function
* This function applies a thoughput curve to a given spectrum
* by dividing the count attribute of the spectrum. The flux
* and ferror attributes of the spectrum are populated.
* gsl spline interpolation is used to compute the throughput
* curve at the needed spectral wavelengths.
*
* Parameters:
* @param spec - a pointer to an existing spectrum array
* @param resp - a pointer to a spectrum structure containing
* a throughput curve previously loaded
* @param exptime - the exposure time
* @param gain - the gain
*
* Returns
* @return -
*/
void
apply_response_function(spectrum *spec, spectrum *resp, const int quant_cont)
{
gsl_interp_accel *acc1 = gsl_interp_accel_alloc();
gsl_spline *spline1 = gsl_spline_alloc (gsl_interp_cspline, resp->spec_len);
gsl_interp_accel *acc2 = gsl_interp_accel_alloc();
gsl_spline *spline2 = gsl_spline_alloc (gsl_interp_cspline, resp->spec_len);
double *x1,*y1, *x2, *y2;
int i,j;
double r1, r2, fr, fr1, fr2;
double min_l, max_l;
// test
// int nguess;
// double tval=0.0;
if ((int) resp->spec_len <= 0){
aXe_message(aXe_M_ERROR, __FILE__, __LINE__,
"apply_response_function: response spec length invalid: %i", resp->spec_len);
gsl_spline_free(spline1);
gsl_interp_accel_free(acc1);
gsl_spline_free(spline2);
gsl_interp_accel_free(acc2);
return;
}
if ( spec==NULL)
{
aXe_message (aXe_M_WARN4, __FILE__, __LINE__,
"apply_response_function: spectra empty.");
gsl_spline_free(spline1);
gsl_interp_accel_free(acc1);
gsl_spline_free(spline2);
gsl_interp_accel_free(acc2);
return;
}
x1 = malloc((double)(resp->spec_len) *sizeof(double));
y1 = malloc((double)(resp->spec_len) *sizeof(double));
x2 = malloc((double)(resp->spec_len) *sizeof(double));
y2 = malloc((double)(resp->spec_len) *sizeof(double));
min_l = 1e32;
max_l = -1e32;
for (i=0;i<resp->spec_len; i++) {
if (resp->spec[i].lambda_mean > max_l) {
max_l = resp->spec[i].lambda_mean;
}
if (resp->spec[i].lambda_mean < min_l) {
min_l = resp->spec[i].lambda_mean;
}
x1[i] = resp->spec[i].lambda_mean;
y1[i] = resp->spec[i].flux - resp->spec[i].ferror;
x2[i] = resp->spec[i].lambda_mean;
y2[i] = resp->spec[i].flux + resp->spec[i].ferror;
}
gsl_spline_init (spline1, x1, y1, resp->spec_len);
gsl_spline_init (spline2, x2, y2, resp->spec_len);
// test
// nguess = 0;
for (j=0; j<spec->spec_len; j++) {
fprintf(stderr,"%f %f %f\n",spec->spec[j].lambda_mean, min_l, max_l);
if ((spec->spec[j].lambda_mean>=min_l) && (spec->spec[j].lambda_mean <= max_l)) {
// fprintf(stderr,"lambda mean between min and max\n\t%f : %f %f\n", spec->spec[j].lambda_mean, min_l, max_l);
r1 = gsl_spline_eval(spline1, spec->spec[j].lambda_mean, acc1);
r2 = gsl_spline_eval(spline2, spec->spec[j].lambda_mean, acc2);
}
else {
r1 = 0;
r2 = 0;
}
/* Need to divide by the pixel width of the
wavelength calibration at the given lambda */
if ((r2+r1)!=0) {
// test
// spec->spec[j].flux = spec->spec[j].count / tval;
spec->spec[j].flux = spec->spec[j].count / ((r2+r1)/2.);
spec->spec[j].flux = spec->spec[j].flux/spec->spec[j].dlambda;
// fprintf(stdout, "# %f %f %f\n", spec->spec[j].lambda_mean, spec->spec[j].dlambda, spec->spec[j].weight);
if (quant_cont && (int)spec->spec[j].contam != -1)
{
// test
// spec->spec[j].contam = spec->spec[j].contam / tval;
spec->spec[j].contam = spec->spec[j].contam / ((r2+r1)/2.);
spec->spec[j].contam = spec->spec[j].contam/spec->spec[j].dlambda;
}
} else {
spec->spec[j].flux = GSL_NAN;
}
fr1 = spec->spec[j].error / spec->spec[j].count; /* frac. error */
fr2 = fabs((r2-r1)/((r1+r2)/2.0)); /* frac. error in resp. */
fr = sqrt(fr1*fr1+fr2*fr2);
spec->spec[j].ferror = fabs(spec->spec[j].flux) * fr;
}
gsl_spline_free(spline1);
gsl_interp_accel_free(acc1);
gsl_spline_free(spline2);
gsl_interp_accel_free(acc2);
free(x1);
free(x2);
free(y1);
free(y2);
}
/**
* Function: apply_response_functionII
* This function applies a thoughput curve to a given spectrum
* by dividing the count attribute of the spectrum. The flux
* and ferror attributes of the spectrum are populated.
*
* Parameters:
* @param spec - a pointer to an existing spectrum array
* @param resp_func - a pointer to a spectrum structure containing
* a throughput curve previously loaded
* @param quant_cont - the exposure time
*
* Returns
* @return -
*/
void
apply_response_functionII(spectrum *spec, response_function *resp_func, const int quant_cont)
{
long j;
double fr, fr1, fr2;
double *resp_vals = malloc( 2 * sizeof(double));
// immediately return
// an empty spectrum
if ( spec==NULL)
{
aXe_message (aXe_M_WARN4, __FILE__, __LINE__,
"apply_response_function: spectra empty.");
return;
}
// go over all elements
for (j=0;j<spec->spec_len;j++)
{
// get the sensitivity value plus error
get_response_values(resp_func, spec->spec[j].lambda_mean, resp_vals);
// make sure you can compute the flux value
if (resp_vals[0] != 0.0)
{
// compute the flux value
spec->spec[j].flux = spec->spec[j].count / resp_vals[0];
spec->spec[j].flux = spec->spec[j].flux/spec->spec[j].dlambda;
// compute the flux error
fr1 = spec->spec[j].error / spec->spec[j].count; /* frac. error */
fr2 = fabs(resp_vals[1] / resp_vals[0]); /* frac. error in resp. */
fr = sqrt(fr1*fr1+fr2*fr2);
spec->spec[j].ferror = fabs(spec->spec[j].flux) * fr;
// check whether the contamination value is necessary
if (quant_cont && (int)spec->spec[j].contam != -1)
{
// compute the contamination value
spec->spec[j].contam = spec->spec[j].contam / resp_vals[0];
spec->spec[j].contam = spec->spec[j].contam/spec->spec[j].dlambda;
}
}
else
{
// set the flux and the error to NaN
spec->spec[j].flux = GSL_NAN;
spec->spec[j].ferror = GSL_NAN;
}
}
// free the memory
free(resp_vals);
}
/**
* Function: get_smooth_pars_for_beam
* The function determines the smoothing parameters for an object beam
* and a given indicator. If smoothed calibration is requested, the source
* size (in dispersion direction) is compared to the poin-like object size.
* For non poin-like objects, the adjustment factor is extracted and
* the smoothing size from the object is derived.
*
* Parameters:
* @param conf - the configuarion file structure
* @param smooth_conv - boolean for smooth conversion
* @param actbeam - the beam to be calibrated
*
* Returns
* @return smooth_pars - the paramters used in the smoothing
*/
d_point
get_smooth_pars_for_beam(const aperture_conf *conf, const int smooth_conv, beam actbeam)
{
d_point smooth_pars;
// initialize the return
smooth_pars.x = -1.0;
smooth_pars.y = -1.0;
// if there is nothing to
// do, return the default
if (!smooth_conv)
return smooth_pars;
// check whether the relevant information
// does exist
if (smooth_conv && actbeam.slitgeom[2] < 0.0)
aXe_message (aXe_M_FATAL, __FILE__, __LINE__,
"Smoothed flux conversion is impossible"
" since the OAF\ndoes not contain the slit width!\n");
//fprintf(stdout, "smoothing factor: %f, point-like size: %f\n", conf->smfactor, conf->pobjsize);
// check whether the objects is smaller than a psf-object
// in dispersion direction
if (conf->pobjsize < actbeam.slitgeom[2])
{
// compute the smoothing size from the objects;
// transfer the adjustment factor
smooth_pars.x = pow((actbeam.slitgeom[2]* actbeam.slitgeom[2]) - (conf->pobjsize*conf->pobjsize), 0.5);
smooth_pars.y = conf->smfactor;
}
// return the
// smoothing parameters
return smooth_pars;
}
/**
* Function: check_conf_for_smoothing
* The functions checks whether a smoothed flux conversion
* is possible or not. In case that keywords in the configuration
* files are missing, it is NOT possible, and 0 is returned.
*
* Parameters:
* @param conf - the configuarion file structure
* @param smooth_conv - boolean for smooth conversion
*
* Returns
* @return is_possible - the paramters used in the smoothing
*/
int
check_conf_for_smoothing(const aperture_conf *conf, const int smooth_conv)
{
int is_possible=1;
// make sure that, if smoothed covnersion is requested,
// a point-like objects size and an adjustment factor is defined
if (smooth_conv && (conf->pobjsize < 0.0 || conf->smfactor < 0.0))
// change the switch
is_possible = 0;
// return the pointer
return is_possible;
}
/**
* Function: apply_smoothed_response
* Convert a spectrum from e/s to flux units in f_lambda. The conversion is done
* using smoothed sensitivity values that take the object width into account
* by smoothing the sensitivity function. Gaussian smoothing is applied, taking
* into account that the original calibration function was derived for a point
* like object with a finite size.
*
* Parameters:
* @param spec - a pointer to an existing spectrum array
* @param resp_func - a pointer to a spectrum structure containing
* a throughput curve
* @param quant_cont - indicator for quantitative contamination
* @param bwidth - the B_IMAGE value of the beam
* @param psf_ext - the width of a point-like object
* @param wl_calibration - the wavelength calibration structure
*
* Returns
* @return -
*/
void
apply_smoothed_response(const calib_function *wl_calibration, const int for_grism,
const int quant_cont, response_function *resp_func,
const d_point smooth_pars, spectrum *spec)
{
long j;
double fr, fr1, fr2;
//double sigma_wav=10.0;
double *resp_vals = malloc( 2 * sizeof(double));
//double *tmp_vals = malloc( 2 * sizeof(double));
gsl_vector *weights;
// allocate memory for the vectors
weights = gsl_vector_alloc(2 * RESP_SMOOTH_LENGTH + 1);
// immediately return
// if an empty spectrum
if ( (spec==NULL) || (spec->spec_len == 0))
{
aXe_message (aXe_M_WARN4, __FILE__, __LINE__,
"apply_response_function: spectra empty.");
return;
}
// fill the weight vector
// for smoothing
fill_weight(weights);
// output to screen
fprintf(stdout, "aXe_PET2SPC: Gaussian smoothing in tracelength: %.2f * %.2f = %.2f pix\n", smooth_pars.x, smooth_pars.y, smooth_pars.x * smooth_pars.y);
// go over all elements
for (j=0;j<spec->spec_len;j++)
{
// get the smoothed sensitivity value plus error
get_smoothed_response(spec->spec[j].lambda_mean, smooth_pars, wl_calibration,
for_grism, weights, resp_func, resp_vals);
// make sure you can compute the flux value
if (resp_vals[0] != 0.0)
{
// compute the flux value
spec->spec[j].flux = spec->spec[j].count / resp_vals[0];
spec->spec[j].flux = spec->spec[j].flux/spec->spec[j].dlambda;
// compute the flux error
fr1 = spec->spec[j].error / spec->spec[j].count; /* frac. error */
fr2 = fabs(resp_vals[1] / resp_vals[0]); /* frac. error in resp. */
fr = sqrt(fr1*fr1+fr2*fr2);
spec->spec[j].ferror = fabs(spec->spec[j].flux) * fr;
// check whether the contamination value is necessary
if (quant_cont && (int)spec->spec[j].contam != -1)
{
// compute the contamination value
spec->spec[j].contam = spec->spec[j].contam / resp_vals[0];
spec->spec[j].contam = spec->spec[j].contam/spec->spec[j].dlambda;
}
}
else
{
// set the flux and the error to NaN
spec->spec[j].flux = GSL_NAN;
spec->spec[j].ferror = GSL_NAN;
}
}
// free the memory
free(resp_vals);
gsl_vector_free(weights);
}
/**
* Function: find_wavelength
* For a given trace-length value, the function returns the difference
* between the actual and the targeted wavelength.
* The function is designed t be called by a gsl root-solving procedure.
*
* Parameters:
* @param x - guess value for the tracelength
* @param params - structure with input parameters
*
* Returns
* @return wav_zero - difference between actual and targeted wavelength
*/
double
find_wavelength(double x, void *params)
{
double wav_zero;
// extract the components from the parameter-structure
const calib_function *wl_calib = ((trlength_search *) params)->wl_calibration;
double wavelength = ((trlength_search *) params)->wavelength;
// compute the function value
wav_zero = wl_calib->func (x, wl_calib->order, wl_calib->coeffs) - wavelength;
// return the function value
return wav_zero;
}
/**
* Function: get_tlength_prismwav
* The function determines the tracelength value for a given wavelength
* value and dispersion function. Should be called only for a prism dispersion.
* The gsl root solver is used.
*
* Parameters:
* @param wavelength - the wavelength value
* @param wl_calibration - the dispersion solution
*
* Returns
* @return wav_zero - difference between actual and targeted wavelength
*/
double
get_tlength_prismwav(const double wavelength, const calib_function *wl_calibration)
{
int iter=0;
int status;
d_point x_interv;
double tr_length=0.0;
// 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;
trlength_search *tr_pars;
// allocate and fill the parameters
tr_pars = (trlength_search *) malloc(sizeof(trlength_search));
tr_pars->wl_calibration = wl_calibration;
tr_pars->wavelength = wavelength;
// fille the GSL-function
F.function = &find_wavelength;
F.params = tr_pars;
// initialize the intervall variable
x_interv.x = gsl_vector_get(wl_calibration->pr_range, 0) + wl_calibration->coeffs[0];
x_interv.y = gsl_vector_get(wl_calibration->pr_range, 1) + wl_calibration->coeffs[0];
// 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
tr_length = 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);
}
// check for the break condition
while (status == GSL_CONTINUE && iter < MAX_ITER_TL);
// free the memory
free(tr_pars);
// free the memory
gsl_root_fsolver_free (s);
// return the result
return tr_length;
}
/**
* Function: get_tlength_prismwav
* The function determines the tracelength value for a given wavelength
* value and dispersion function. Should be called only for a prism dispersion.
* The gsl root solver is used.
*
* Parameters:
* @param wavelength - the wavelength value
* @param wl_calibration - the dispersion solution
* @param for_grism - boolean to indicate grism/prism dispersion solution
*
* Returns
* @return wav_zero - difference between actual and targeted wavelength
*/
double
get_central_tracelength(const double wavelength, const calib_function *wl_calibration,
const int for_grism)
{
double tl_central=0.0;
double a, b, c;
// checc whether it's a grism
if (for_grism)
{
// solve a linear dispersion
if (wl_calibration->order == 1)
{
tl_central = (wavelength - wl_calibration->coeffs[0]) / wl_calibration->coeffs[1];
}
// solve a quadratic dispersion
else if (wl_calibration->order == 2)
{
// make the quantities
a = wl_calibration->coeffs[2];
b = wl_calibration->coeffs[1];
c = wl_calibration->coeffs[0] - wavelength;
// compute the central tracelength
//tl_central = (-b + sqrt(b*b - 4.0*a*c)) / (2.0*c);
tl_central = (-b + sqrt(b*b - 4.0*a*c)) / (2.0*a);
//fprintf(stdout, "I should be here... %g %g %g %g\n", tl_central, a, b, c);
}
else
{
// give error message
aXe_message (aXe_M_FATAL, __FILE__, __LINE__,
"Smoothed flux conversion is impossible for grism "
"data with dispersion solution of order: %i", wl_calibration->order);
}
}
else
{
// use the root finder to get the tace-length value
// for the given wavelength
if (isnan(wavelength))
tl_central = GSL_NAN;
else
tl_central = get_tlength_prismwav(wavelength, wl_calibration);
}
// return the central
// tracelength value
return tl_central;
}
/**
* Function: get_smoothed_response
* The function determine a smoothe sensitivity value and its error.
* Gaussian smoothing is applied, but the Gaussian weights are delivered
* as a function parameter (for perfomrance reasons). The function detemines
* the response values over the weight window and then combines these values
* with the weights to get one weighted sensitivity value at the desired
* wavelength.
*
* Parameters:
* @param wavelength - the central wavelength
* @param smooth_pars - the smoothing parameters
* @param calib_function - the wavelength calibration function
* @param for_grism - boolean to indicate grism/prism solution
* @param weights - the weight vector
* @param resp_func - the response function
* @param resp_vals - vector for the response values
*
* Returns
* @return -
*/
void
get_smoothed_response(const double wavelength, const d_point smooth_pars,
const calib_function *wl_calibration, const int for_grism,
const gsl_vector *weights, response_function *resp_func, double *resp_vals)
{
int j;
double tl_incr;
double tl_act;
double tl_central;
double lambda_act;
gsl_vector *pixvalues;
gsl_vector *errvalues;
gsl_vector *pmask;
double *tmp_vals = malloc( 2 * sizeof(double));
// allocate memory for the vectors
pixvalues = gsl_vector_alloc(2 * RESP_SMOOTH_LENGTH + 1);
errvalues = gsl_vector_alloc(2 * RESP_SMOOTH_LENGTH + 1);
pmask = gsl_vector_alloc(2 * RESP_SMOOTH_LENGTH + 1);
// set all mask points to zero
gsl_vector_set_all(pmask, 0.0);
// determine the tracelength value
tl_central = get_central_tracelength(wavelength, wl_calibration, for_grism);
// determine the wavelength increments
//wav_incr = (double)RESP_SMOOTH_NSIG * sigma_wav / (double)RESP_SMOOTH_LENGTH;
tl_incr = smooth_pars.x * smooth_pars.y * (double)RESP_SMOOTH_NSIG / (double)RESP_SMOOTH_LENGTH;
// set the initial wavelength value
//value = wavelength - sigma_wav * (double)RESP_SMOOTH_NSIG;
tl_act = tl_central - 1.0 * smooth_pars.x * smooth_pars.y * (double)RESP_SMOOTH_NSIG;
// print the starting and central wavelength
//fprintf(stdout, " %.5g < %.5g",
// wl_calibration->func(tl_act, wl_calibration->order, wl_calibration->coeffs),
// wl_calibration->func(tl_central, wl_calibration->order, wl_calibration->coeffs));
// go over the array
for (j=0; j < (int)pixvalues->size; j++)
{
// determine the wavelength value
lambda_act = wl_calibration->func(tl_act, wl_calibration->order, wl_calibration->coeffs);
// check whether the actual wavelength is inside
// the defined sensitivity interval
if (lambda_act < resp_func->xmin || lambda_act > resp_func->xmax)
{
// for outside values:
// set everything to zero
gsl_vector_set(pixvalues, j, 0.0);
gsl_vector_set(errvalues, j, 0.0);
gsl_vector_set(pmask, j, 0.0);
}
else
{
// for inside values:
// compute and set the response
get_response_values(resp_func, lambda_act, tmp_vals);
gsl_vector_set(pixvalues, j, tmp_vals[0]);
gsl_vector_set(errvalues, j, tmp_vals[1]);
gsl_vector_set(pmask, j, 1.0);
}
// increment trace length
tl_act += tl_incr;
}
// print the ending wavelength
//fprintf(stdout, " > %.5g;", wl_calibration->func(tl_act, wl_calibration->order, wl_calibration->coeffs));
// get the weighted response values
get_weighted_sensitivity(pixvalues, errvalues, weights, pmask, resp_vals);
// free the memory
free(tmp_vals);
gsl_vector_free(pixvalues);
gsl_vector_free(errvalues);
gsl_vector_free(pmask);
}
/**
* Function: get_weighted_sensitivity
* Combines the weigh values, the sensitivity and error at the weight point
* to a single sensitivity value plus error. A mask array defines at which
* points values do exist.
*
* Parameters:
* @param pixvalues - the central wavelength
* @param errvalues - the Gaussian sigma used in smoothing
* @param weights - the weight vector
* @param pmask - the response function
* @param resp_vals - vector for the response values
*
* Returns
* @return
*/
void
get_weighted_sensitivity(const gsl_vector *pixvalues, const gsl_vector *errvalues, const gsl_vector *weights,
const gsl_vector *pmask, double *resp_vals)
{
int index;
// initialize the total
// sum and weight
double val_sum = 0.0;
double err_sum = 0.0;
double www=0.0;
// go over all indices of an array
for (index=0; index < (int)pixvalues->size; index ++)
{
// check whether the index is masked
if (gsl_vector_get(pmask, index) != 0.0)
{
// enhance the total sum
val_sum += gsl_vector_get(pixvalues, index) * gsl_vector_get(weights, index);
err_sum += gsl_vector_get(errvalues, index) * gsl_vector_get(errvalues, index)
* gsl_vector_get(weights, index) * gsl_vector_get(weights, index);
// enhance the total weight
www += gsl_vector_get(weights, index);
}
}
// check whether there
// were weights at all
if (www)
{
// return the total sum,
// divided by the total weight
resp_vals[0] = val_sum / www;
resp_vals[1] = sqrt(err_sum) / www;
}
else
{
// set zero sensitivity
resp_vals[0] = 0.0;
resp_vals[1] = 0.0;
}
}
/**
* Function: fill_weight
* The function fills an array with Gaussian values.
* The number of points and the extend are all defined in
* global variables in the h-file.
*
* Parameters:
* @param weights - the weight vector
*
* Returns
* @return -
*/
void
fill_weight(gsl_vector *weights)
{
int j;
double d_incr;
double value;
// determine the increments
d_incr = (double)RESP_SMOOTH_NSIG / (double)RESP_SMOOTH_LENGTH;
// compute the initial exponent
// go over the weights vector
value = -(double)RESP_SMOOTH_NSIG;
for (j=0; j < (int)weights->size; j++)
{
// compute and set the weight
gsl_vector_set(weights, j, exp(-1.0*value * value));
// increment the exponent
value += d_incr;
}
}
/**
* Function: get_troughput_table_name
* Parses a configuration file and get the name of the SENSITIVITY
* curve defined for a wanted beamID
*
* Parameters:
* @param filename - a pointer to a string containing the name of the
* configuration file
* @param beamID - the beam ID number (see BEAM())
* @param table_name - a pointer pointing to a string to contain the name
* of the file.
*
* Returns:
* @return -
*/
void
get_troughput_table_name(char *filename, int beamID, char *table_name)
{
char beam[MAXCHAR];
char name[MAXCHAR];
int i=0;
struct CfgStrings ThrConfig[] = {
{NULL, NULL},
{NULL,NULL}
};
ThrConfig[0].name = beam;
sprintf (beam, "SENSITIVITY_%c", BEAM(beamID));
CfgRead (filename, ThrConfig);
if ((ThrConfig[0].name == beam) && (ThrConfig[0].data != NULL))
{
strcpy(name,ThrConfig[0].data);
} else {
aXe_message (aXe_M_FATAL, __FILE__, __LINE__,
"get_throughput_table_name: %s was not found in "
"%s",beam,filename);
}
// release memory
i=0;
while(ThrConfig[i].name!=NULL)
free(ThrConfig[i++].data);
strcpy(table_name,name);
}
/**
* Function: get_response_value_plus
* The function determines the sensitivity at a given wavelength
* in a sensitivity curve. A guess value helps to start searching
* around the estimated position of the wavelength in the vector
* of the sensitifity curve. This should considerably speed up the
* code. the guess value is updated in case that a sensitivity
* value could be determined. The return value is interpolated
* between the adjacent tabulated values.
*
* Parameters:
* @param resp - the sensitivity spectrum
* @param wavelength - the wavelength to determine the sensitivity for
* @param nguess - the guess value for the array to start searching from
*
* Returns:
* @return ret - the sensitivity value at the input wavelength
*/
double
get_response_value_plus(const spectrum *resp, const double wavelength,
int *nguess)
{
double ret;
double factor;
int nact;
// check whether the wavelength is within the range of
//the sensitivity curve return GSL_NAN if not
if (wavelength < resp->lambdamin || wavelength > resp->lambdamax)
return GSL_NAN;
// check whether you have to search upwards or downwards
if (wavelength >= resp->spec[*nguess].lambda_mean)
{
// in case that you search upwards, go up
// the spectrum until you find the right interval
nact = *nguess + 1;
while(wavelength > resp->spec[nact].lambda_mean)
nact++;
}
else
{
// in case that you search upwards, go up
// the spectrum until you find the right interval
nact = *nguess;
while(wavelength < resp->spec[nact-1].lambda_mean)
nact--;
}
// interpolate within the interval to calculate the
// sensitivity
factor = (wavelength - resp->spec[nact-1].lambda_mean) /
(resp->spec[nact].lambda_mean - resp->spec[nact-1].lambda_mean);
ret = resp->spec[nact-1].flux + factor * (resp->spec[nact].flux - resp->spec[nact-1].flux);
// update the guess value
*nguess = nact;
// return the sensitivity value
return ret;
}
/**
* Function: get_response_values
* The function evaluates the response function at the desired
* independent value. The sensitivity and it error are returned
* in an array parameter.
*
* Parameters:
* @param resp_func - the response function
* @param wavelength - the independent value
* @param resp_vals - the dependent value and its error
*
* Returns:
* @return -
*/
void
get_response_values(response_function *resp_func, double wavelength, double* resp_vals)
{
// check whether the independent value is outside the deifned range
if (wavelength < resp_func->xmin || wavelength > resp_func->xmax)
{
// give the default
// outside values
resp_vals[0] = 0.0;
resp_vals[1] = 0.0;
}
else
{
// get the response value and its error
resp_vals[0] = eval_interp(resp_func->resp_values, wavelength);
resp_vals[1] = eval_interp(resp_func->resp_errors, wavelength);
}
}
/**
* Function: create_response_function
* Load the sensitivity file and creates a new response
* function. Relies heavily on other subroutines
*
* Parameters:
* @param filename - sensitivity file name
*
* Returns:
* @return resp_func - the response function created
*/
response_function *
create_response_function(char *filename)
{
response_function *resp_func;
// allocate space for the return structure;
// complain if this fails
resp_func = (response_function *)malloc (sizeof (response_function));
if (resp_func == NULL)
aXe_message (aXe_M_FATAL, __FILE__, __LINE__,
"Could not allocate memory for response function");
// load the two intgerpolators
resp_func->resp_values = create_interp_ftable(filename, 2, "WAVELENGTH", "SENSITIVITY", RESP_FUNC_INTERP_TYPE);
resp_func->resp_errors = create_interp_ftable(filename, 2, "WAVELENGTH", "ERROR", RESP_FUNC_INTERP_TYPE);
// transfer the min and max values from the interpolator
resp_func->xmin = resp_func->resp_values->xmin;
resp_func->xmax = resp_func->resp_values->xmax;
// return the respons function
return resp_func;
}
/**
* Function: free_response_function
* Releases the memory allocated in a response function
*
* Parameters:
* @param resp_func - the response function
*
* Returns:
* @return -
*/
void
free_response_function(response_function *resp_func)
{
// free the two interpolators
free_interp(resp_func->resp_values);
free_interp(resp_func->resp_errors);
// free the rest
free(resp_func);
// set it to NULL
resp_func = NULL;
}
/**
* Function: get_calfunc_for_beam
* The subroutine determines and returns the calibration function
* for a certain beam and configuration file. The coefficients of
* the wavelength calibration are evaluated at the position of the
* beam object.
*
* Parameters:
* @param actbeam - the current beam
* @param for_grism - indicator for grism or prism dispersion
* @param CONF_file - full pathname to configuration file
* @param conf - the configuration structure
*
* Returns:
* @return wl_calibration - the calibration function
*/
calib_function *
get_calfunc_for_beam(const beam actbeam, const int for_grism, char CONF_file[],
const aperture_conf * conf)
{
calib_function *wl_calibration;
dispstruct *disp;
d_point pixel;
// get the reference point right
pixel.x = actbeam.refpoint.x - conf->refx;
pixel.y = actbeam.refpoint.y - conf->refy;
// get the dispersion structure
disp = get_dispstruct_at_pos(CONF_file, for_grism, actbeam.ID, pixel);
// transform the dispersion structure into the
// wavelength calibration
wl_calibration = create_calib_from_gsl_vector(for_grism, disp->pol);
if (!for_grism)
wl_calibration->pr_range = get_prange (CONF_file, actbeam.ID);
// free the whole structure
free_dispstruct(disp);
// return the wavelength calibration
return wl_calibration;
}
| {
"alphanum_fraction": 0.645585917,
"avg_line_length": 31.0693877551,
"ext": "c",
"hexsha": "3c0f327c6ebd65717fc064ee3bbaac5b32d44368",
"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/spc_resp.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/spc_resp.c",
"max_line_length": 155,
"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/spc_resp.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 9889,
"size": 38060
} |
/* linalg/lu.c
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007, 2009 Gerard Jungman, Brian Gough
* Copyright (C) 2019 Patrick Alken
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include <config.h>
#include <stdlib.h>
#include <string.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_permute_vector.h>
#include <gsl/gsl_blas.h>
#include <gsl/gsl_linalg.h>
#include "recurse.h"
static int LU_decomp_L2 (gsl_matrix * A, gsl_vector_uint * ipiv);
static int LU_decomp_L3 (gsl_matrix * A, gsl_vector_uint * ipiv);
static int singular (const gsl_matrix * LU);
static int apply_pivots(gsl_matrix * A, const gsl_vector_uint * ipiv);
/* Factorise a general N x N matrix A into,
*
* P A = L U
*
* where P is a permutation matrix, L is unit lower triangular and U
* is upper triangular.
*
* L is stored in the strict lower triangular part of the input
* matrix. The diagonal elements of L are unity and are not stored.
*
* U is stored in the diagonal and upper triangular part of the
* input matrix.
*
* P is stored in the permutation p. Column j of P is column k of the
* identity matrix, where k = permutation->data[j]
*
* signum gives the sign of the permutation, (-1)^n, where n is the
* number of interchanges in the permutation.
*
* See Golub & Van Loan, Matrix Computations, Algorithm 3.4.1 (Gauss
* Elimination with Partial Pivoting).
*/
int
gsl_linalg_LU_decomp (gsl_matrix * A, gsl_permutation * p, int *signum)
{
const size_t M = A->size1;
if (p->size != M)
{
GSL_ERROR ("permutation length must match matrix size1", GSL_EBADLEN);
}
else
{
int status;
const size_t N = A->size2;
const size_t minMN = GSL_MIN(M, N);
gsl_vector_uint * ipiv = gsl_vector_uint_alloc(minMN);
gsl_matrix_view AL = gsl_matrix_submatrix(A, 0, 0, M, minMN);
size_t i;
status = LU_decomp_L3 (&AL.matrix, ipiv);
/* process remaining right matrix */
if (M < N)
{
gsl_matrix_view AR = gsl_matrix_submatrix(A, 0, M, M, N - M);
/* apply pivots to AR */
apply_pivots(&AR.matrix, ipiv);
/* AR = AL^{-1} AR */
gsl_blas_dtrsm(CblasLeft, CblasLower, CblasNoTrans, CblasUnit, 1.0, &AL.matrix, &AR.matrix);
}
/* convert ipiv array to permutation */
gsl_permutation_init(p);
*signum = 1;
for (i = 0; i < minMN; ++i)
{
unsigned int pivi = gsl_vector_uint_get(ipiv, i);
if (p->data[pivi] != p->data[i])
{
size_t tmp = p->data[pivi];
p->data[pivi] = p->data[i];
p->data[i] = tmp;
*signum = -(*signum);
}
}
gsl_vector_uint_free(ipiv);
return status;
}
}
/*
LU_decomp_L2
LU decomposition with partial pivoting using Level 2 BLAS
Inputs: A - on input, matrix to be factored; on output, L and U factors
ipiv - (output) array containing row swaps
Notes:
1) Based on LAPACK DGETF2
*/
static int
LU_decomp_L2 (gsl_matrix * A, gsl_vector_uint * ipiv)
{
const size_t M = A->size1;
const size_t N = A->size2;
const size_t minMN = GSL_MIN(M, N);
if (ipiv->size != minMN)
{
GSL_ERROR ("ipiv length must equal MIN(M,N)", GSL_EBADLEN);
}
else
{
size_t i, j;
for (j = 0; j < minMN; ++j)
{
/* find maximum in the j-th column */
gsl_vector_view v = gsl_matrix_subcolumn(A, j, j, M - j);
size_t j_pivot = j + gsl_blas_idamax(&v.vector);
gsl_vector_view v1, v2;
gsl_vector_uint_set(ipiv, j, j_pivot);
if (j_pivot != j)
{
/* swap rows j and j_pivot */
v1 = gsl_matrix_row(A, j);
v2 = gsl_matrix_row(A, j_pivot);
gsl_blas_dswap(&v1.vector, &v2.vector);
}
if (j < M - 1)
{
double Ajj = gsl_matrix_get(A, j, j);
if (fabs(Ajj) >= GSL_DBL_MIN)
{
v1 = gsl_matrix_subcolumn(A, j, j + 1, M - j - 1);
gsl_blas_dscal(1.0 / Ajj, &v1.vector);
}
else
{
for (i = 1; i < M - j; ++i)
{
double * ptr = gsl_matrix_ptr(A, j + i, j);
*ptr /= Ajj;
}
}
}
if (j < minMN - 1)
{
gsl_matrix_view A22 = gsl_matrix_submatrix(A, j + 1, j + 1, M - j - 1, N - j - 1);
v1 = gsl_matrix_subcolumn(A, j, j + 1, M - j - 1);
v2 = gsl_matrix_subrow(A, j, j + 1, N - j - 1);
gsl_blas_dger(-1.0, &v1.vector, &v2.vector, &A22.matrix);
}
}
return GSL_SUCCESS;
}
}
/*
LU_decomp_L3
LU decomposition with partial pivoting using Level 3 BLAS
Inputs: A - on input, matrix to be factored; on output, L and U factors
ipiv - (output) array containing row swaps
Notes:
1) Based on ReLAPACK DGETRF
*/
static int
LU_decomp_L3 (gsl_matrix * A, gsl_vector_uint * ipiv)
{
const size_t M = A->size1;
const size_t N = A->size2;
if (M < N)
{
GSL_ERROR ("matrix must have M >= N", GSL_EBADLEN);
}
else if (ipiv->size != GSL_MIN(M, N))
{
GSL_ERROR ("ipiv length must equal MIN(M,N)", GSL_EBADLEN);
}
else if (N <= CROSSOVER_LU)
{
/* use Level 2 algorithm */
return LU_decomp_L2(A, ipiv);
}
else
{
/*
* partition matrix:
*
* N1 N2
* N1 [ A11 A12 ]
* M2 [ A21 A22 ]
*
* and
* N1 N2
* M [ AL AR ]
*/
int status;
const size_t N1 = GSL_LINALG_SPLIT(N);
const size_t N2 = N - N1;
const size_t M2 = M - N1;
gsl_matrix_view A11 = gsl_matrix_submatrix(A, 0, 0, N1, N1);
gsl_matrix_view A12 = gsl_matrix_submatrix(A, 0, N1, N1, N2);
gsl_matrix_view A21 = gsl_matrix_submatrix(A, N1, 0, M2, N1);
gsl_matrix_view A22 = gsl_matrix_submatrix(A, N1, N1, M2, N2);
gsl_matrix_view AL = gsl_matrix_submatrix(A, 0, 0, M, N1);
gsl_matrix_view AR = gsl_matrix_submatrix(A, 0, N1, M, N2);
/*
* partition ipiv = [ ipiv1 ] N1
* [ ipiv2 ] N2
*/
gsl_vector_uint_view ipiv1 = gsl_vector_uint_subvector(ipiv, 0, N1);
gsl_vector_uint_view ipiv2 = gsl_vector_uint_subvector(ipiv, N1, N2);
size_t i;
/* recursion on (AL, ipiv1) */
status = LU_decomp_L3(&AL.matrix, &ipiv1.vector);
if (status)
return status;
/* apply ipiv1 to AR */
apply_pivots(&AR.matrix, &ipiv1.vector);
/* A12 = A11^{-1} A12 */
gsl_blas_dtrsm(CblasLeft, CblasLower, CblasNoTrans, CblasUnit, 1.0, &A11.matrix, &A12.matrix);
/* A22 = A22 - A21 * A12 */
gsl_blas_dgemm(CblasNoTrans, CblasNoTrans, -1.0, &A21.matrix, &A12.matrix, 1.0, &A22.matrix);
/* recursion on (A22, ipiv2) */
status = LU_decomp_L3(&A22.matrix, &ipiv2.vector);
if (status)
return status;
/* apply pivots to A21 */
apply_pivots(&A21.matrix, &ipiv2.vector);
/* shift pivots */
for (i = 0; i < N2; ++i)
{
unsigned int * ptr = gsl_vector_uint_ptr(&ipiv2.vector, i);
*ptr += N1;
}
return GSL_SUCCESS;
}
}
int
gsl_linalg_LU_solve (const gsl_matrix * LU, const gsl_permutation * p, const gsl_vector * b, gsl_vector * x)
{
if (LU->size1 != LU->size2)
{
GSL_ERROR ("LU matrix must be square", GSL_ENOTSQR);
}
else if (LU->size1 != p->size)
{
GSL_ERROR ("permutation length must match matrix size", GSL_EBADLEN);
}
else if (LU->size1 != b->size)
{
GSL_ERROR ("matrix size must match b size", GSL_EBADLEN);
}
else if (LU->size2 != x->size)
{
GSL_ERROR ("matrix size must match solution size", GSL_EBADLEN);
}
else if (singular (LU))
{
GSL_ERROR ("matrix is singular", GSL_EDOM);
}
else
{
int status;
/* copy x <- b */
gsl_vector_memcpy (x, b);
/* solve for x */
status = gsl_linalg_LU_svx (LU, p, x);
return status;
}
}
int
gsl_linalg_LU_svx (const gsl_matrix * LU, const gsl_permutation * p, gsl_vector * x)
{
if (LU->size1 != LU->size2)
{
GSL_ERROR ("LU matrix must be square", GSL_ENOTSQR);
}
else if (LU->size1 != p->size)
{
GSL_ERROR ("permutation length must match matrix size", GSL_EBADLEN);
}
else if (LU->size1 != x->size)
{
GSL_ERROR ("matrix size must match solution/rhs size", GSL_EBADLEN);
}
else if (singular (LU))
{
GSL_ERROR ("matrix is singular", GSL_EDOM);
}
else
{
/* apply permutation to RHS */
gsl_permute_vector (p, x);
/* solve for c using forward-substitution, L c = P b */
gsl_blas_dtrsv (CblasLower, CblasNoTrans, CblasUnit, LU, x);
/* perform back-substitution, U x = c */
gsl_blas_dtrsv (CblasUpper, CblasNoTrans, CblasNonUnit, LU, x);
return GSL_SUCCESS;
}
}
int
gsl_linalg_LU_refine (const gsl_matrix * A, const gsl_matrix * LU, const gsl_permutation * p, const gsl_vector * b, gsl_vector * x, gsl_vector * work)
{
if (A->size1 != A->size2)
{
GSL_ERROR ("matrix a must be square", GSL_ENOTSQR);
}
else if (LU->size1 != LU->size2)
{
GSL_ERROR ("LU matrix must be square", GSL_ENOTSQR);
}
else if (A->size1 != LU->size2)
{
GSL_ERROR ("LU matrix must be decomposition of a", GSL_ENOTSQR);
}
else if (LU->size1 != p->size)
{
GSL_ERROR ("permutation length must match matrix size", GSL_EBADLEN);
}
else if (LU->size1 != b->size)
{
GSL_ERROR ("matrix size must match b size", GSL_EBADLEN);
}
else if (LU->size1 != x->size)
{
GSL_ERROR ("matrix size must match solution size", GSL_EBADLEN);
}
else if (LU->size1 != work->size)
{
GSL_ERROR ("matrix size must match workspace size", GSL_EBADLEN);
}
else if (singular (LU))
{
GSL_ERROR ("matrix is singular", GSL_EDOM);
}
else
{
int status;
/* compute residual = (A * x - b) */
gsl_vector_memcpy (work, b);
gsl_blas_dgemv (CblasNoTrans, 1.0, A, x, -1.0, work);
/* find correction, delta = - (A^-1) * residual, and apply it */
status = gsl_linalg_LU_svx (LU, p, work);
gsl_blas_daxpy (-1.0, work, x);
return status;
}
}
int
gsl_linalg_LU_invert (const gsl_matrix * LU, const gsl_permutation * p, gsl_matrix * inverse)
{
if (LU->size1 != LU->size2)
{
GSL_ERROR ("LU matrix must be square", GSL_ENOTSQR);
}
else if (LU->size1 != p->size)
{
GSL_ERROR ("permutation length must match matrix size", GSL_EBADLEN);
}
else if (inverse->size1 != LU->size1 || inverse->size2 != LU->size2)
{
GSL_ERROR ("inverse matrix must match LU matrix dimensions", GSL_EBADLEN);
}
else
{
gsl_matrix_memcpy(inverse, LU);
return gsl_linalg_LU_invx (inverse, p);
}
}
int
gsl_linalg_LU_invx (gsl_matrix * LU, const gsl_permutation * p)
{
if (LU->size1 != LU->size2)
{
GSL_ERROR ("LU matrix must be square", GSL_ENOTSQR);
}
else if (LU->size1 != p->size)
{
GSL_ERROR ("permutation length must match matrix size", GSL_EBADLEN);
}
else if (singular (LU))
{
GSL_ERROR ("matrix is singular", GSL_EDOM);
}
else
{
int status;
const size_t N = LU->size1;
size_t i;
/* compute U^{-1} */
status = gsl_linalg_tri_invert(CblasUpper, CblasNonUnit, LU);
if (status)
return status;
/* compute L^{-1} */
status = gsl_linalg_tri_invert(CblasLower, CblasUnit, LU);
if (status)
return status;
/* compute U^{-1} L^{-1} */
status = gsl_linalg_tri_UL(LU);
if (status)
return status;
/* apply permutation to columns of A^{-1} */
for (i = 0; i < N; ++i)
{
gsl_vector_view v = gsl_matrix_row(LU, i);
gsl_permute_vector_inverse(p, &v.vector);
}
return GSL_SUCCESS;
}
}
double
gsl_linalg_LU_det (gsl_matrix * LU, int signum)
{
size_t i, n = LU->size1;
double det = (double) signum;
for (i = 0; i < n; i++)
{
det *= gsl_matrix_get (LU, i, i);
}
return det;
}
double
gsl_linalg_LU_lndet (gsl_matrix * LU)
{
size_t i, n = LU->size1;
double lndet = 0.0;
for (i = 0; i < n; i++)
{
lndet += log (fabs (gsl_matrix_get (LU, i, i)));
}
return lndet;
}
int
gsl_linalg_LU_sgndet (gsl_matrix * LU, int signum)
{
size_t i, n = LU->size1;
int s = signum;
for (i = 0; i < n; i++)
{
double u = gsl_matrix_get (LU, i, i);
if (u < 0)
{
s *= -1;
}
else if (u == 0)
{
s = 0;
break;
}
}
return s;
}
static int
singular (const gsl_matrix * LU)
{
size_t i, n = LU->size1;
for (i = 0; i < n; i++)
{
double u = gsl_matrix_get (LU, i, i);
if (u == 0) return 1;
}
return 0;
}
static int
apply_pivots(gsl_matrix * A, const gsl_vector_uint * ipiv)
{
if (A->size1 < ipiv->size)
{
GSL_ERROR("matrix does not match pivot vector", GSL_EBADLEN);
}
else
{
size_t i;
for (i = 0; i < ipiv->size; ++i)
{
size_t pi = gsl_vector_uint_get(ipiv, i);
if (i != pi)
{
/* swap rows i and pi */
gsl_vector_view v1 = gsl_matrix_row(A, i);
gsl_vector_view v2 = gsl_matrix_row(A, pi);
gsl_blas_dswap(&v1.vector, &v2.vector);
}
}
return GSL_SUCCESS;
}
}
| {
"alphanum_fraction": 0.56947122,
"avg_line_length": 25.0413793103,
"ext": "c",
"hexsha": "e3bf04aea17ed9055b58a6453c733cb146a72a7e",
"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/lu.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/lu.c",
"max_line_length": 150,
"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/lu.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": 4379,
"size": 14524
} |
#include <math.h>
#include <stdlib.h>
#include <stdio.h>
#include <gsl/gsl_math.h>
#include "scf.h"
/* Computing Phi_nl(r), which is the radial part of the basis functions
*
* The Gegenbauer polynomials for the host halo and subhalos can either be computed
* using my own hard coded implementation (see gegenbauer.c) or GSL's implementation.
*
*/
double int_power(float x, int n)
{
return gsl_pow_int(x, n);
}
#ifdef USE_GSL_GEGENBAUER_HOST
float Phi_nl(double Cna, int l, float r)
{
return -1.0f * int_power(r,l)/int_power(1.0f+r, 2.0*l+1) * (float)Cna * ROOT_FOUR_PI;
}
float dPhi_nl_dr(double Cna, float phinl, int n, int l, float r)
{
int two_l = 2*l;
float r1 = r+1.f;
float val = phinl * ( l/r - (two_l+1.0f)/r1 );
if(n>0)
{
val -= ROOT_FOUR_PI * int_power(r,l)*4.0f*(two_l+1.5f) * (float)Cna / int_power(r1,two_l+3);
}
return val;
}
#else
float Phi_nl(int n, int l, float r)
{
float xi = (r-1.0f)/(r+1.0f);
return -1.0f * int_power(r,l)/int_power(1.0f+r, 2.0*l+1) * Cna(n,2.0f*l+1.5f,xi) * ROOT_FOUR_PI;
}
float dPhi_nl_dr(float phinl, int n, int l, float r)
{
int two_l = 2*l;
float r1 = r+1.f;
float val = phinl * ( l/r - (two_l+1.0f)/r1 );
if(n>0)
{
float xi = (r-1.f)/r1;
val -= ROOT_FOUR_PI * int_power(r,l)*4.0f*(two_l+1.5f) * Cna(n-1,two_l+2.5f,xi) / int_power(r1,two_l+3);
}
return val;
}
#endif
#ifdef USE_GSL_GEGENBAUER_SUBHALO
float Phi_n0(double Cna, float r)
{
return -1.0f / (1.0f+r) * (float)Cna * ROOT_FOUR_PI;
}
float dPhi_n0_dr(double Cna, float phin0, int n, float r)
{
float r1 = r+1.f;
float val = phin0 * -1.f/r1;
if(n>0)
{
val -= ROOT_FOUR_PI * 6.f/r1/r1/r1 * (float)Cna;
}
return val;
}
#else
float Phi_n0(int n, float r)
{
float xi = (r-1.0f)/(r+1.0f);
return -1.0f / (1.0f+r) * Cna(n,1.5f,xi) * ROOT_FOUR_PI;
}
float dPhi_n0_dr(float phin0, int n, float r)
{
float r1 = r+1.f;
float val = phin0 * -1.f/r1;
if(n>0)
{
float xi = (r-1.f)/r1;
val -= ROOT_FOUR_PI * 6.f/r1/r1/r1 * Cna(n-1,2.5f,xi);
}
return val;
}
#endif
| {
"alphanum_fraction": 0.5962703963,
"avg_line_length": 18.982300885,
"ext": "c",
"hexsha": "a87260f29715f593ce1bfdad14aec4a05eab988d",
"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": "e04d8738e92333f546ec6ef4b4f61c7e87456aba",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "wayne927/vl2-scf",
"max_forks_repo_path": "Phi_nl.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "e04d8738e92333f546ec6ef4b4f61c7e87456aba",
"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": "wayne927/vl2-scf",
"max_issues_repo_path": "Phi_nl.c",
"max_line_length": 106,
"max_stars_count": 3,
"max_stars_repo_head_hexsha": "e04d8738e92333f546ec6ef4b4f61c7e87456aba",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "wayne927/vl2-scf",
"max_stars_repo_path": "Phi_nl.c",
"max_stars_repo_stars_event_max_datetime": "2017-03-08T23:45:46.000Z",
"max_stars_repo_stars_event_min_datetime": "2016-04-07T19:05:02.000Z",
"num_tokens": 855,
"size": 2145
} |
/*
* C version of Diffusive Nested Sampling (DNest4) by Brendon J. Brewer
*
* Yan-Rong Li, liyanrong@mail.ihep.ac.cn
* Jun 30, 2016
*
*/
#ifndef _MODEL2_H
#define _MODEL2_H
#include <stdbool.h>
#include <gsl/gsl_rng.h>
/* data type */
typedef struct
{
double x;
double y;
}DataType;
/* number of model parameters */
extern int num_params;
/* data storage */
extern int num_data_points;
extern DataType *data;
extern int which_particle_update; // which particule to be updated
extern int which_level_update;
extern double *limits;
extern int thistask, totaltask;
extern DNestFptrSet *fptrset_thismodel2;
/* functions */
void from_prior_thismodel2(void *model);
void data_load_thismodel2();
void print_particle_thismodel2(FILE *fp, const void *model);
double log_likelihoods_cal_thismodel2(const void *model);
double perturb_thismodel2(void *model);
void restart_action_model2(int iflag);
#endif
| {
"alphanum_fraction": 0.7584699454,
"avg_line_length": 20.3333333333,
"ext": "h",
"hexsha": "6efdf6ea5ce8c2c1d59c455c167fc8b25d1563c2",
"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": "afb6b869ce1c4ebd76662b20310f1d9d3db4e26e",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "LiyrAstroph/DNest_C",
"max_forks_repo_path": "src/model2.h",
"max_issues_count": 2,
"max_issues_repo_head_hexsha": "afb6b869ce1c4ebd76662b20310f1d9d3db4e26e",
"max_issues_repo_issues_event_max_datetime": "2021-01-06T02:04:19.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-05-14T10:04:48.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "LiyrAstroph/DNest_C",
"max_issues_repo_path": "src/model2.h",
"max_line_length": 71,
"max_stars_count": 6,
"max_stars_repo_head_hexsha": "afb6b869ce1c4ebd76662b20310f1d9d3db4e26e",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "LiyrAstroph/CDNest",
"max_stars_repo_path": "src/model2.h",
"max_stars_repo_stars_event_max_datetime": "2020-10-16T12:14:05.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-09-11T03:34:45.000Z",
"num_tokens": 238,
"size": 915
} |
/* linalg/test_cholesky.c
*
* Copyright (C) 2016 Patrick Alken
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include <config.h>
#include <stdlib.h>
#include <gsl/gsl_test.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_ieee_utils.h>
#include <gsl/gsl_permute_vector.h>
#include <gsl/gsl_blas.h>
#include <gsl/gsl_linalg.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_permutation.h>
#include "test_common.c"
static int test_cholesky_decomp_eps(const int scale, const gsl_matrix * m,
const double expected_rcond, const double eps,
const char * desc);
static int test_cholesky_decomp(gsl_rng * r);
int test_cholesky_invert_eps(const gsl_matrix * m, const double eps, const char *desc);
int test_cholesky_invert(gsl_rng * r);
static int test_pcholesky_decomp_eps(const int scale, const gsl_matrix * m,
const double expected_rcond, const double eps,
const char * desc);
static int test_pcholesky_decomp(gsl_rng * r);
int test_pcholesky_solve_eps(const int scale, const gsl_matrix * m, const gsl_vector * rhs,
const gsl_vector * sol, const double eps,
const char * desc);
static int test_pcholesky_solve(gsl_rng * r);
int test_pcholesky_invert_eps(const gsl_matrix * m, const double eps, const char *desc);
int test_pcholesky_invert(gsl_rng * r);
static int test_mcholesky_decomp_eps(const int posdef, const int scale, const gsl_matrix * m,
const double expected_rcond, const double eps, const char * desc);
/* Hilbert matrix condition numbers, as calculated by LAPACK DPOSVX */
double hilb_rcond[] = { 1.000000000000e+00, 3.703703703704e-02, 1.336898395722e-03,
3.524229074890e-05, 1.059708198754e-06, 3.439939465186e-08,
1.015027593823e-09, 2.952221630602e-11, 9.093751565191e-13,
2.828277420229e-14, 8.110242564869e-16, 2.409320075800e-17 };
static int
test_cholesky_decomp_eps(const int scale, 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 * S = gsl_vector_alloc(N);
gsl_matrix_memcpy(V, m);
if (scale)
s += gsl_linalg_cholesky_decomp2(V, S);
else
s += gsl_linalg_cholesky_decomp1(V);
/* compute L and LT */
gsl_matrix_tricpy('L', 1, L, V);
gsl_matrix_transpose_tricpy('L', 1, LT, L);
if (scale)
{
/* L <- S^{-1} L, LT <- LT S^{-1} */
for (i = 0; i < N; ++i)
{
double Si = gsl_vector_get(S, i);
gsl_vector_view v = gsl_matrix_row(L, i);
gsl_vector_view w = gsl_matrix_column(LT, i);
gsl_vector_scale(&v.vector, 1.0 / Si);
gsl_vector_scale(&w.vector, 1.0 / Si);
}
}
/* compute A = L 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 && !scale)
{
gsl_vector *work = gsl_vector_alloc(3 * N);
double rcond;
gsl_linalg_cholesky_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);
gsl_vector_free(S);
return s;
}
static int
test_cholesky_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_cholesky_decomp_eps(0, m, -1.0, 1.0e2 * N * GSL_DBL_EPSILON, "cholesky_decomp unscaled random");
test_cholesky_decomp_eps(1, m, -1.0, 1.0e2 * N * GSL_DBL_EPSILON, "cholesky_decomp scaled 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_cholesky_decomp_eps(0, m, expected_rcond, N * GSL_DBL_EPSILON, "cholesky_decomp unscaled hilbert");
test_cholesky_decomp_eps(1, m, expected_rcond, N * GSL_DBL_EPSILON, "cholesky_decomp scaled hilbert");
}
gsl_matrix_free(m);
}
return s;
}
int
test_cholesky_invert_eps(const gsl_matrix * m, const double eps, const char *desc)
{
int s = 0;
size_t i, j, N = m->size1;
gsl_matrix * v = gsl_matrix_alloc(N, N);
gsl_matrix * c = gsl_matrix_alloc(N, N);
gsl_matrix_memcpy(v, m);
s += gsl_linalg_cholesky_decomp1(v);
s += gsl_linalg_cholesky_invert(v);
/* c = m m^{-1} */
gsl_blas_dsymm(CblasLeft, CblasUpper, 1.0, m, v, 0.0, c);
/* c should be the identity matrix */
for (i = 0; i < N; ++i)
{
for (j = 0; j < N; ++j)
{
double cij = gsl_matrix_get(c, i, j);
double expected = (i == j) ? 1.0 : 0.0;
gsl_test_rel(cij, expected, eps, "%s (%3lu,%3lu)[%lu,%lu]: %22.18g %22.18g\n",
desc, N, N, i, j, cij, expected);
}
}
gsl_matrix_free(v);
gsl_matrix_free(c);
return s;
}
int
test_cholesky_invert(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_cholesky_invert_eps(m, N * GSL_DBL_EPSILON, "cholesky_invert unscaled random");
if (N <= 4)
{
create_hilbert_matrix2(m);
test_cholesky_invert_eps(m, N * 256.0 * GSL_DBL_EPSILON, "cholesky_invert unscaled hilbert");
}
gsl_matrix_free(m);
}
return s;
}
static int
test_mcholesky_decomp_eps(const int posdef, const int scale, 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 * LDLT = gsl_matrix_alloc(N, N);
gsl_matrix * V = gsl_matrix_alloc(N, N);
gsl_matrix * A = gsl_matrix_alloc(N, N);
gsl_matrix * L = gsl_matrix_alloc(N, N);
gsl_matrix * LT = gsl_matrix_alloc(N, N);
gsl_vector * S = gsl_vector_alloc(N);
gsl_vector * E = gsl_vector_alloc(N);
gsl_permutation * perm = gsl_permutation_alloc(N);
gsl_vector_view D = gsl_matrix_diagonal(LDLT);
gsl_matrix_memcpy(LDLT, m);
s += gsl_linalg_mcholesky_decomp(LDLT, perm, E);
/* check that the upper triangle of LDLT equals original matrix */
for (i = 0; i < N; ++i)
{
for (j = i + 1; j < N; ++j)
{
double mij = gsl_matrix_get(m, i, j);
double aij = gsl_matrix_get(LDLT, i, j);
gsl_test_rel(aij, mij, 1.0e-12,
"%s upper triangle: (%3lu,%3lu)[%lu,%lu]: %22.18g %22.18g\n",
desc, N, N, i, j, aij, mij);
}
}
if (posdef)
{
/* ||E|| should be 0 */
double norm = gsl_blas_dnrm2(E);
s = norm != 0.0;
gsl_test(s, "%s: (%zu,%zu): ||E|| = %.12e",
desc, N, N, norm);
/* check that D is decreasing */
s = 0;
for (i = 1; i < N; ++i)
{
double dprev = gsl_vector_get(&D.vector, i - 1);
double di = gsl_vector_get(&D.vector, i);
if (di > dprev)
s = 1;
}
gsl_test(s, "%s: (%zu,%zu): D is not decreasing",
desc, N, N);
}
/* compute L and LT */
gsl_matrix_set_identity(L);
gsl_matrix_set_identity(LT);
gsl_matrix_tricpy('L', 0, L, LDLT);
gsl_matrix_transpose_tricpy('L', 0, LT, L);
/* compute (L sqrt(D)) and (sqrt(D) LT) */
for (i = 0; i < N; ++i)
{
gsl_vector_view v = gsl_matrix_column(L, i);
gsl_vector_view w = gsl_matrix_row(LT, i);
double di = gsl_vector_get(&D.vector, i);
gsl_vector_scale(&v.vector, sqrt(di));
gsl_vector_scale(&w.vector, sqrt(di));
}
/* compute A = L D LT */
gsl_blas_dgemm (CblasNoTrans, CblasNoTrans, 1.0, L, LT, 0.0, A);
/* compute V = P (S M S + E) P^T */
gsl_matrix_memcpy(V, m);
D = gsl_matrix_diagonal(V);
/* compute S M S */
if (scale)
{
gsl_linalg_cholesky_scale_apply(V, S);
gsl_matrix_transpose_tricpy('L', 0, V, V);
}
/* compute S M S + E */
gsl_vector_add(&D.vector, E);
/* compute M P^T */
for (i = 0; i < N; ++i)
{
gsl_vector_view v = gsl_matrix_row(V, i);
gsl_permute_vector(perm, &v.vector);
}
/* compute P M P^T */
for (i = 0; i < N; ++i)
{
gsl_vector_view v = gsl_matrix_column(V, i);
gsl_permute_vector(perm, &v.vector);
}
for (i = 0; i < N; i++)
{
double Ei = gsl_vector_get(E, i);
for (j = 0; j < N; j++)
{
double Aij = gsl_matrix_get(A, i, j); /* L D L^T */
double Bij = gsl_matrix_get(V, i, j); /* P M P^T */
double Cij; /* P M P^T + E */
if (i == j)
Cij = Bij + Ei*0;
else
Cij = Bij;
gsl_test_rel(Aij, Cij, eps,
"%s: (%3lu,%3lu)[%lu,%lu]: %22.18g %22.18g\n",
desc, N, N, i, j, Aij, Cij);
}
}
if (expected_rcond > 0 && !scale)
{
gsl_vector *work = gsl_vector_alloc(3 * N);
double rcond;
gsl_linalg_mcholesky_rcond(LDLT, perm, &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(LDLT);
gsl_matrix_free(V);
gsl_matrix_free(A);
gsl_matrix_free(L);
gsl_matrix_free(LT);
gsl_vector_free(S);
gsl_vector_free(E);
gsl_permutation_free(perm);
return s;
}
static int
test_mcholesky_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_mcholesky_decomp_eps(1, 0, m, -1.0, 128.0 * N * GSL_DBL_EPSILON, "mcholesky_decomp unscaled random posdef");
create_symm_matrix(m, r);
test_mcholesky_decomp_eps(0, 0, m, -1.0, 8192.0 * N * GSL_DBL_EPSILON, "mcholesky_decomp unscaled random symm");
if (N <= 8)
{
double expected_rcond = -1.0;
if (hilb_rcond[N - 1] > 1.0e-12)
expected_rcond = hilb_rcond[N - 1];
create_hilbert_matrix2(m);
test_mcholesky_decomp_eps(1, 0, m, expected_rcond, 128.0 * N * GSL_DBL_EPSILON, "mcholesky_decomp unscaled hilbert");
}
gsl_matrix_free(m);
}
return s;
}
int
test_mcholesky_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_vector * S = gsl_vector_alloc(N);
gsl_permutation * perm = gsl_permutation_alloc(N);
gsl_matrix_memcpy(u, m);
s += gsl_linalg_mcholesky_decomp(u, perm, NULL);
s += gsl_linalg_mcholesky_solve(u, perm, 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_vector_free(S);
gsl_matrix_free(u);
gsl_permutation_free(perm);
return s;
}
static int
test_mcholesky_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_mcholesky_solve_eps(m, rhs, sol, 64.0 * N * GSL_DBL_EPSILON, "mcholesky_solve random");
if (N <= 3)
{
create_hilbert_matrix2(m);
gsl_blas_dsymv(CblasLower, 1.0, m, sol, 0.0, rhs);
test_mcholesky_solve_eps(m, rhs, sol, 1.0e3 * N * GSL_DBL_EPSILON, "mcholesky_solve hilbert");
}
gsl_matrix_free(m);
gsl_vector_free(rhs);
gsl_vector_free(sol);
}
return s;
}
int
test_mcholesky_invert_eps(const gsl_matrix * m, const double eps, const char *desc)
{
int s = 0;
size_t i, j, N = m->size1;
gsl_matrix * v = gsl_matrix_alloc(N, N);
gsl_matrix * c = gsl_matrix_alloc(N, N);
gsl_matrix * minv = gsl_matrix_alloc(N, N);
gsl_vector * E = gsl_vector_alloc(N);
gsl_permutation * p = gsl_permutation_alloc(N);
gsl_matrix_memcpy(v, m);
s += gsl_linalg_mcholesky_decomp(v, p, E);
s += gsl_linalg_mcholesky_invert(v, p, minv);
/* c = m m^{-1} */
gsl_blas_dsymm(CblasLeft, CblasUpper, 1.0, m, minv, 0.0, c);
/* c should be the identity matrix */
for (i = 0; i < N; ++i)
{
for (j = 0; j < N; ++j)
{
double cij = gsl_matrix_get(c, i, j);
double expected = (i == j) ? 1.0 : 0.0;
gsl_test_rel(cij, expected, eps, "%s (%3lu,%3lu)[%lu,%lu]: %22.18g %22.18g\n",
desc, N, N, i, j, cij, expected);
}
}
gsl_matrix_free(v);
gsl_matrix_free(c);
gsl_matrix_free(minv);
gsl_vector_free(E);
gsl_permutation_free(p);
return s;
}
int
test_mcholesky_invert(gsl_rng * r)
{
int s = 0;
const size_t N_max = 30;
size_t N;
for (N = 1; N <= N_max; ++N)
{
gsl_matrix * m = gsl_matrix_alloc(N, N);
create_posdef_matrix(m, r);
test_mcholesky_invert_eps(m, N * GSL_DBL_EPSILON, "mcholesky_invert unscaled random");
if (N <= 4)
{
create_hilbert_matrix2(m);
test_mcholesky_invert_eps(m, 256.0 * N * GSL_DBL_EPSILON, "mcholesky_invert unscaled hilbert");
}
gsl_matrix_free(m);
}
return s;
}
static int
test_pcholesky_decomp_eps(const int scale, 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 * LDLT = gsl_matrix_alloc(N, N);
gsl_matrix * V = gsl_matrix_alloc(N, N);
gsl_matrix * A = gsl_matrix_alloc(N, N);
gsl_matrix * L = gsl_matrix_alloc(N, N);
gsl_matrix * LT = gsl_matrix_alloc(N, N);
gsl_vector * S = gsl_vector_alloc(N);
gsl_permutation * perm = gsl_permutation_alloc(N);
gsl_vector_view D = gsl_matrix_diagonal(LDLT);
gsl_matrix_memcpy(LDLT, m);
if (scale)
s += gsl_linalg_pcholesky_decomp2(LDLT, perm, S);
else
s += gsl_linalg_pcholesky_decomp(LDLT, perm);
/* check that the upper triangle of LDLT equals original matrix */
for (i = 0; i < N; ++i)
{
for (j = i + 1; j < N; ++j)
{
double mij = gsl_matrix_get(m, i, j);
double aij = gsl_matrix_get(LDLT, i, j);
gsl_test_rel(aij, mij, 1.0e-12,
"%s upper triangle: (%3lu,%3lu)[%lu,%lu]: %22.18g %22.18g\n",
desc, N, N, i, j, aij, mij);
}
}
/* check that D is decreasing */
s = 0;
for (i = 1; i < N; ++i)
{
double dprev = gsl_vector_get(&D.vector, i - 1);
double di = gsl_vector_get(&D.vector, i);
if (di > dprev)
s = 1;
}
gsl_test(s, "%s: (%zu,%zu): D is not decreasing",
desc, N, N);
/* compute L and LT */
gsl_matrix_set_identity(L);
gsl_matrix_set_identity(LT);
gsl_matrix_tricpy('L', 0, L, LDLT);
gsl_matrix_transpose_tricpy('L', 0, LT, L);
/* compute (L sqrt(D)) and (sqrt(D) LT) */
for (i = 0; i < N; ++i)
{
gsl_vector_view v = gsl_matrix_column(L, i);
gsl_vector_view w = gsl_matrix_row(LT, i);
double di = gsl_vector_get(&D.vector, i);
gsl_vector_scale(&v.vector, sqrt(di));
gsl_vector_scale(&w.vector, sqrt(di));
}
/* compute A = L D LT */
gsl_blas_dgemm (CblasNoTrans, CblasNoTrans, 1.0, L, LT, 0.0, A);
/* compute V = P S M S P^T */
gsl_matrix_memcpy(V, m);
/* compute S M S */
if (scale)
{
gsl_linalg_cholesky_scale_apply(V, S);
gsl_matrix_transpose_tricpy('L', 0, V, V);
}
/* compute M P^T */
for (i = 0; i < N; ++i)
{
gsl_vector_view v = gsl_matrix_row(V, i);
gsl_permute_vector(perm, &v.vector);
}
/* compute P M P^T */
for (i = 0; i < N; ++i)
{
gsl_vector_view v = gsl_matrix_column(V, i);
gsl_permute_vector(perm, &v.vector);
}
for (i = 0; i < N; i++)
{
for (j = 0; j < N; j++)
{
double Aij = gsl_matrix_get(A, i, j); /* L D L^T */
double Bij = gsl_matrix_get(V, i, j); /* P M P^T */
gsl_test_rel(Aij, Bij, eps,
"%s: (%3lu,%3lu)[%lu,%lu]: %22.18g %22.18g\n",
desc, N, N, i, j, Aij, Bij);
}
}
if (expected_rcond > 0 && !scale)
{
gsl_vector *work = gsl_vector_alloc(3 * N);
double rcond;
gsl_linalg_pcholesky_rcond(LDLT, perm, &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(LDLT);
gsl_matrix_free(V);
gsl_matrix_free(A);
gsl_matrix_free(L);
gsl_matrix_free(LT);
gsl_vector_free(S);
gsl_permutation_free(perm);
return s;
}
static int
test_pcholesky_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_pcholesky_decomp_eps(0, m, -1.0, 1024.0 * N * GSL_DBL_EPSILON, "pcholesky_decomp unscaled random");
test_pcholesky_decomp_eps(1, m, -1.0, 1024.0 * N * GSL_DBL_EPSILON, "pcholesky_decomp scaled 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_pcholesky_decomp_eps(0, m, expected_rcond, 1024.0 * N * GSL_DBL_EPSILON, "pcholesky_decomp unscaled hilbert");
test_pcholesky_decomp_eps(1, m, expected_rcond, 1024.0 * N * GSL_DBL_EPSILON, "pcholesky_decomp scaled hilbert");
}
gsl_matrix_free(m);
}
return s;
}
int
test_pcholesky_solve_eps(const int scale, 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_vector * S = gsl_vector_alloc(N);
gsl_permutation * perm = gsl_permutation_alloc(N);
gsl_matrix_memcpy(u, m);
if (scale)
{
s += gsl_linalg_pcholesky_decomp2(u, perm, S);
s += gsl_linalg_pcholesky_solve2(u, perm, S, rhs, x);
}
else
{
s += gsl_linalg_pcholesky_decomp(u, perm);
s += gsl_linalg_pcholesky_solve(u, perm, 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_vector_free(S);
gsl_matrix_free(u);
gsl_permutation_free(perm);
return s;
}
static int
test_pcholesky_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_pcholesky_solve_eps(0, m, rhs, sol, 64.0 * N * GSL_DBL_EPSILON, "pcholesky_solve unscaled random");
test_pcholesky_solve_eps(1, m, rhs, sol, 64.0 * N * GSL_DBL_EPSILON, "pcholesky_solve scaled random");
if (N <= 3)
{
create_hilbert_matrix2(m);
gsl_blas_dsymv(CblasLower, 1.0, m, sol, 0.0, rhs);
test_pcholesky_solve_eps(0, m, rhs, sol, 1024.0 * N * GSL_DBL_EPSILON, "pcholesky_solve unscaled hilbert");
test_pcholesky_solve_eps(1, m, rhs, sol, 2048.0 * N * GSL_DBL_EPSILON, "pcholesky_solve scaled hilbert");
}
gsl_matrix_free(m);
gsl_vector_free(rhs);
gsl_vector_free(sol);
}
return s;
}
int
test_pcholesky_invert_eps(const gsl_matrix * m, const double eps, const char *desc)
{
int s = 0;
size_t i, j, N = m->size1;
gsl_matrix * v = gsl_matrix_alloc(N, N);
gsl_matrix * c = gsl_matrix_alloc(N, N);
gsl_matrix * minv = gsl_matrix_alloc(N, N);
gsl_permutation * p = gsl_permutation_alloc(N);
gsl_matrix_memcpy(v, m);
s += gsl_linalg_pcholesky_decomp(v, p);
s += gsl_linalg_pcholesky_invert(v, p, minv);
/* c = m m^{-1} */
gsl_blas_dsymm(CblasLeft, CblasUpper, 1.0, m, minv, 0.0, c);
/* c should be the identity matrix */
for (i = 0; i < N; ++i)
{
for (j = 0; j < N; ++j)
{
double cij = gsl_matrix_get(c, i, j);
double expected = (i == j) ? 1.0 : 0.0;
gsl_test_rel(cij, expected, eps, "%s (%3lu,%3lu)[%lu,%lu]: %22.18g %22.18g\n",
desc, N, N, i, j, cij, expected);
}
}
gsl_matrix_free(v);
gsl_matrix_free(c);
gsl_matrix_free(minv);
gsl_permutation_free(p);
return s;
}
int
test_pcholesky_invert(gsl_rng * r)
{
int s = 0;
const size_t N_max = 30;
size_t N;
for (N = 1; N <= N_max; ++N)
{
gsl_matrix * m = gsl_matrix_alloc(N, N);
create_posdef_matrix(m, r);
test_pcholesky_invert_eps(m, N * GSL_DBL_EPSILON, "pcholesky_invert unscaled random");
if (N <= 4)
{
create_hilbert_matrix2(m);
test_pcholesky_invert_eps(m, 1024.0 * N * GSL_DBL_EPSILON, "pcholesky_invert unscaled hilbert");
}
gsl_matrix_free(m);
}
return s;
}
| {
"alphanum_fraction": 0.5814780327,
"avg_line_length": 26.8782707622,
"ext": "c",
"hexsha": "fef882a7eeede6d723c0f015eb2b3840e5d74024",
"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/linalg/test_cholesky.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "Brian-ning/HMNE",
"max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/linalg/test_cholesky.c",
"max_line_length": 127,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "857b6ee8866a2950aa5721d575d2d7d0797c4302",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "peterahrens/FillEstimationIPDPS2017",
"max_stars_repo_path": "gsl-2.4/linalg/test_cholesky.c",
"max_stars_repo_stars_event_max_datetime": "2021-01-13T05:01:59.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-01-13T05:01:59.000Z",
"num_tokens": 7605,
"size": 23626
} |
#ifndef ASSOCIATION_H
#define ASSOCIATION_H
#define TRUE 1
#define FALSE 0
#include <iostream>
// #include <omp.h>
#include <mkl.h>
extern "C" {
#include <gsl/gsl_rng.h>
#include <gsl/gsl_const_mksa.h>
}
#include "matrix.h"
#include "connectivity.h"
#include "potential.h"
/* #include "trajectory.h" */
/* #include "read_file_condition.h" */
#include "file_IO.h"
#include "geometry.h"
class ASSOCIATION
: public CONNECTIVITY
{
public:
MKL_LONG Nc; // number of chains per micelle
MKL_LONG Tec; // tolerance of end chains
MKL_LONG N_min; // 2Nc - Tec
MKL_LONG N_max; // 2Nc + Tec
MKL_LONG N_ASSOCIATION;
bool MULTIPLE_CONNECTIONS;
bool NUMBER_RESTRICTION;
bool PROBABILITY_AREA;
MATRIX N_ASSOCIATION_PARTICLE;
MATRIX *weight;
// related with suggestion probability (selecting a degenerated pair)
MATRIX *CASE_SUGGESTION;
MATRIX *dPDF_SUGGESTION;
MATRIX *dCDF_SUGGESTION;
double *Z_SUGGESTION;
// related with association probability
MATRIX *dCDF_ASSOCIATION;
/* size_t **INDEX_ASSOCIATION; */
MATRIX *INDEX_ASSOCIATION;
MKL_LONG *TOKEN_ASSOCIATION;
// member variables
/* MKL_LONG flag_other, flag_new, flag_itself, flag_hash_other; */
static const MKL_LONG flag_other = 0;
static const MKL_LONG flag_new = 1;
static const MKL_LONG flag_itself = 2;
static const MKL_LONG flag_hash_other = 3;
static const MKL_LONG flag_hash_backtrace = 4;
bool
(*ADD_ASSOCIATION)
(ASSOCIATION& CONNECT, MKL_LONG index_set[]);
bool
(*OPP_DEL_ASSOCIATION)
(ASSOCIATION& CONNECT, MKL_LONG index_set[]);
bool
(*CANCEL_ASSOCIATION)
(ASSOCIATION& CONNECT, MKL_LONG index_set[]);
bool
(*CHECK_N_ADD_ASSOCIATION)
(ASSOCIATION& CONNECT, MKL_LONG index_set[]);
bool
(*CHECK_N_MOV_ASSOCIATION)
(ASSOCIATION& CONNECT, MKL_LONG index_set[]);
bool
(*CHECK_N_OPP_DEL_ASSOCIATION)
(ASSOCIATION& CONNECT, MKL_LONG index_set[]);
MKL_LONG
N_TOTAL_ASSOCIATION
();
MKL_LONG
N_PARTICLE_ASSOCIATION
(MKL_LONG index_particle);
MKL_LONG
N_CONNECTED_ENDS
(MKL_LONG given_index);
MKL_LONG
N_TOTAL_CONNECTED_ENDS
();
bool
CHECK_EXIST
(MKL_LONG index_A, MKL_LONG index_B);
bool
CHECK_EXIST_1D
(MKL_LONG index_A, MKL_LONG index_B);
MKL_LONG
add_association
(const MKL_LONG index_particle, MKL_LONG index_target);
MKL_LONG
add_association_INFO
(POTENTIAL_SET& POTs, const MKL_LONG index_particle, MKL_LONG index_target, double distance);
MKL_LONG
opp_del_association
(const MKL_LONG index_particle, MKL_LONG index_target);
MKL_LONG
opp_del_association_hash
(const MKL_LONG index_particle, MKL_LONG hash_index_target);
MKL_LONG
opp_del_association_IK
(MKL_LONG index_I, MKL_LONG hash_index_K);
MKL_LONG
opp_del_association_grab_IK
(MKL_LONG index_I, MKL_LONG hash_index_K);
MKL_LONG
GET_INDEX_HASH_FROM_ROLL
(const MKL_LONG index_particle, double rolled_p);
MKL_LONG
GET_HASH_FROM_ROLL
(const MKL_LONG index_particle, double rolled_p);
MKL_LONG
FIND_HASH_INDEX
(MKL_LONG index_A, MKL_LONG index_B);
MKL_LONG
update_N_association
();
MKL_LONG
get_N_association_particle
(MKL_LONG index_particle);
// At the moment, there is no namespace dependence between KINETICS::NORMALIZED and KINETICS::METROPOLIS.
// The dependency is set with the w_function and transtion_probability that is developed with lib_potential.
// For better performance, it would be better to tune the following with specific dependencies (future works).
double
update_CASE_SUGGESTION_particle_hash_target
(POTENTIAL_SET& POTs, const MKL_LONG index_particle, MKL_LONG hash_index_target, double distance);
double
update_CASE_SUGGESTION_particle_target
(POTENTIAL_SET& POTs, const MKL_LONG index_particle, MKL_LONG index_target, double distance);
double
update_Z_SUGGESTION_particle
(const MKL_LONG index_particle);
double
update_dPDF_SUGGESTION_particle
(const MKL_LONG index_particle);
double
update_dCDF_SUGGESTION_particle
(const MKL_LONG index_particle);
double
update_CHAIN_SUGGESTION_MAP_particle
(const MKL_LONG index_particle, POTENTIAL_SET& POTs, RDIST& R_boost);
double
update_ASSOCIATION_MAP_particle
(const MKL_LONG index_particle, POTENTIAL_SET& POTs, RDIST& R_boost);
MKL_LONG
return_multiplicity
(const MKL_LONG index_particle, const MKL_LONG target_particle)
// this additional function is useful for tracking individual chain
{
for(MKL_LONG j=0; j<TOKEN[index_particle]; j++)
{
if(HASH[index_particle](j) == target_particle)
return weight[index_particle](j);
}
return 0;
}
ASSOCIATION()
: CONNECTIVITY(){}
ASSOCIATION
(COND& given_condition);
ASSOCIATION
(MKL_LONG number_of_particles, MKL_LONG number_of_chains_per_particles, MKL_LONG tolerance_connection, bool ALLOWING_MULTIPLE_CONNECTIONS);
MKL_LONG
dynamic_alloc
();
MKL_LONG
set_initial_condition
();
MKL_LONG
initial
();
MKL_LONG
initial_inheritance
();
virtual
~ASSOCIATION()
{
delete[] weight;
// related with suggestion probability
delete[] CASE_SUGGESTION;
delete[] dPDF_SUGGESTION;
delete[] dCDF_SUGGESTION;
delete[] Z_SUGGESTION;
// related with association probability
delete[] dCDF_ASSOCIATION;
delete[] INDEX_ASSOCIATION;
delete[] TOKEN_ASSOCIATION;
}
MKL_LONG
read_exist_weight
(const char* fn_weight, MKL_LONG N_steps);
};
MKL_LONG
index_set_val
(size_t* index, MKL_LONG given_val, MKL_LONG size_of_arr);
namespace TRUTH_MAP
{
namespace MULTIPLE
{
bool
CHECK_N_ADD_BOOST
(ASSOCIATION& CONNECT, MKL_LONG index_set[]);
bool
CHECK_N_OPP_DEL_BOOST
(ASSOCIATION& CONNECT, MKL_LONG index_set[]);
bool
CHECK_N_MOV_BOOST
(ASSOCIATION& CONNECT, MKL_LONG index_set[]);
namespace NO_RESTRICTION // this option is used when there are no restriction for number of attached chain ends
{
bool
return_TRUE
(ASSOCIATION& CONNECT, MKL_LONG index_set[]);
}
}
namespace SINGLE
{
bool
CHECK_N_ADD_BOOST
(ASSOCIATION& CONNECT, MKL_LONG index_set[]);
bool
CHECK_N_MOV_BOOST
(ASSOCIATION& CONNECT, MKL_LONG index_set[]);
bool
CHECK_N_OPP_DEL_BOOST
(ASSOCIATION& CONNECT, MKL_LONG index_set[]);
}
bool
CANCEL_ASSOCIATION_BOOST
(ASSOCIATION& CONNECT, MKL_LONG index_set[]);
bool
ADD_ASSOCIATION_BOOST
(ASSOCIATION& CONNECT, MKL_LONG index_set[]);
bool
OPP_DEL_ASSOCIATION_BOOST
(ASSOCIATION& CONNECT, MKL_LONG index_set[]);
bool
OPP_DEL_ASSOCIATION_BASIC
(ASSOCIATION& CONNECT, MKL_LONG index_itself, MKL_LONG index_target, MKL_LONG index_new);
bool
NEW_ASSOCIATION_BASIC
(ASSOCIATION& CONNECT, MKL_LONG index_itself, MKL_LONG index_target, MKL_LONG index_new);
bool
NEW_ASSOCIATION_SINGLE
(ASSOCIATION& CONNECT, MKL_LONG index_itself, MKL_LONG index_target, MKL_LONG index_new);
bool
MOV_ASSOCIATION_BASIC
(ASSOCIATION& CONNECT, MKL_LONG index_itself, MKL_LONG index_target, MKL_LONG index_new);
bool
MOV_ASSOCIATION_SINGLE
(ASSOCIATION& CONNECT, MKL_LONG index_itself, MKL_LONG index_target, MKL_LONG index_new);
}
namespace MICELLE
{
double
update_SOFT_REPULSION_P2(POTENTIAL_SET& given_POT, ASSOCIATION& CONNECT);
double
update_SOFT_REPULSION_P2_particle(POTENTIAL_SET& given_POT, ASSOCIATION& CONNECT, MKL_LONG index_particle);
}
namespace KINETICS
{
double
CONNECTIVITY_update_dCDF_SUGGESTION_particle
(ASSOCIATION* CONNECT, const MKL_LONG index_particle);
double
CONNECTIVITY_update_CASE_SUGGESTION_particle_hash_target
(ASSOCIATION* CONNECT, POTENTIAL_SET& POTs, const MKL_LONG index_particle, MKL_LONG hash_index_target, double distance);
double
CONNECTIVITY_update_CASE_SUGGESTION_particle_target
(ASSOCIATION* CONNECT, POTENTIAL_SET& POTs, const MKL_LONG index_particle, MKL_LONG index_target, double distance);
double
CONNECTIVITY_update_Z_SUGGESTION_particle
(ASSOCIATION* CONNECT, const MKL_LONG index_particle);
double
CONNECTIVITY_update_dPDF_SUGGESTION_particle
(ASSOCIATION* CONNECT, const MKL_LONG index_particle);
}
class CHAIN_INFORMATION
{
/*
The CHAIN class is using CHAIN_NODE without inheritance.
It contains dynamically allocated CHAIN_NODE.
*/
public:
CHAIN_NODE *CHAIN;
MKL_LONG N_chains;
MKL_LONG N_particles;
bool INITIALIZATION;
MKL_LONG&
HEAD
(MKL_LONG given_chain_index)
{
return CHAIN[given_chain_index].HEAD;
}
MKL_LONG&
TAIL
(MKL_LONG given_chain_index)
{
return CHAIN[given_chain_index].TAIL;
}
/*
On the same reason, the ATTACHED will return pointer variable rather than reference variable. This break the existing interface.
*/
MKL_LONG&
ATTACHED
(MKL_LONG given_chain_index, MKL_LONG flag_HEAD_TAIL)
{
return CHAIN[given_chain_index].index(flag_HEAD_TAIL);
}
MKL_LONG
mov_attachment
(MKL_LONG target_particle, MKL_LONG given_chain_index, MKL_LONG flag_HEAD_TAIL)
{
/*
flag_HEAD_TAIL is 0 for HEAD while 1 for TAIL.
*/
ATTACHED(given_chain_index, flag_HEAD_TAIL) = target_particle;
return 0;
}
MKL_LONG
add_attachment
(const MKL_LONG index_particle, MKL_LONG given_chain_index, MKL_LONG flag_HEAD_TAIL)
{
// there is no distingushable between add and mov attachment for chain node
mov_attachment(index_particle, given_chain_index, flag_HEAD_TAIL);
return 0;
}
MKL_LONG
del_attachment
(MKL_LONG given_chain_index, MKL_LONG flag_HEAD_TAIL)
{
// it make detachment for subjected chain ends
// then attach to particles which other chain ends are attached
mov_attachment(ATTACHED(given_chain_index, (flag_HEAD_TAIL + 1)%2), given_chain_index, flag_HEAD_TAIL);
return 0;
}
MKL_LONG
initial
(MKL_LONG number_of_chains, MKL_LONG number_of_particles)
{
printf("ST:initial:CHAIN_INFORMATION\n");
N_chains = number_of_chains;
N_particles = number_of_particles;
CHAIN = new CHAIN_NODE [N_chains];
for(MKL_LONG i=0; i<N_chains; i++)
{
/*
it allocate the equivalent number of chain ends per particles
*/
HEAD(i) = i%N_particles;
TAIL(i) = i%N_particles;
}
INITIALIZATION = TRUE;
return INITIALIZATION;
}
MKL_LONG
initial
(ASSOCIATION& CONNECT)
{
N_chains = CONNECT.Nc*CONNECT.Np;
N_particles = CONNECT.Np;
CHAIN = new CHAIN_NODE [N_chains];
MKL_LONG cnt = 0;
for(MKL_LONG i=0; i<N_particles; i++)
{
for(MKL_LONG j=i; j<N_particles; j++) // it includes i=j which is loop and prevents j<i means all the pair is once accounted.
{
MKL_LONG wij = CONNECT.return_multiplicity(i, j);
if(i==j)
{
// note that weight count chain end rather than chain
// when i != j, the duplication is removed because we only count the pair with condition j>i
// when i == j, the duplication happens in the wij.
wij /=2;
}
for(MKL_LONG w=0; w<wij; w++)
{
HEAD(cnt) = i;
TAIL(cnt) = j;
if(cnt++ > N_chains)
printf("Err: counted number of chain overflood\n");
}
}
}
printf("end_particle_allocation\n");
INITIALIZATION = TRUE;
return INITIALIZATION;
}
MKL_LONG
inheritance_chain
(COND& given_condition, ASSOCIATION& CONNECT)
{
N_chains = CONNECT.Nc*CONNECT.Np;
N_particles = CONNECT.Np;
/* CHAIN = (CHAIN_NODE*)mkl_malloc(N_chains*sizeof(CHAIN_NODE), BIT); */
// the problem of the original is that 'malloc' will not call the constructor
CHAIN = new CHAIN_NODE [N_chains];
MKL_LONG cnt = 0;
ifstream GIVEN_CHAIN_FILE;
GIVEN_CHAIN_FILE.open(given_condition("CONTINUATION_CHAIN_FN").c_str());
string line;
while(getline(GIVEN_CHAIN_FILE, line))
cnt ++;
GIVEN_CHAIN_FILE.clear();
GIVEN_CHAIN_FILE.seekg(0);
MKL_LONG N_steps = atoi(given_condition("CONTINUATION_STEP").c_str());
if(N_steps == -1)
{
for(MKL_LONG i=0; i<cnt-1; i++)
getline(GIVEN_CHAIN_FILE, line);
}
else
{
for(MKL_LONG i=0; i<N_steps; i++)
getline(GIVEN_CHAIN_FILE, line);
}
for(MKL_LONG k=0; k<N_chains; k++)
GIVEN_CHAIN_FILE >> HEAD(k); // index from 0 to N_chains-1 : HEAD
for(MKL_LONG k=0; k<N_chains; k++)
GIVEN_CHAIN_FILE >> TAIL(k); // index from N_chains to 2*N_chains-1 : TAIL
GIVEN_CHAIN_FILE.close();
INITIALIZATION = TRUE;
return INITIALIZATION;
}
CHAIN_INFORMATION()
{
std::cout << "ERR: CHAIN Class must have initialization argument\n";
}
CHAIN_INFORMATION(MKL_LONG number_of_chains, MKL_LONG number_of_particles)
{
initial(number_of_chains, number_of_particles);
}
CHAIN_INFORMATION(COND& given_condition)
{
if(given_condition("tracking_individual_chain") == "TRUE")
{
if(given_condition("CONTINUATION_CHAIN") == "TRUE")
{
printf("ERR: Without CONTINUATION TOPOLOGICAL INFORMATION (.hash, .weight), the tracking individual chain cannot inherit existing .chain file information\n");
}
else
{
printf("ST:Constructor:CHAIN_INFORMATION\n");
initial(atoi(given_condition("N_chains_per_particle").c_str())*atoi(given_condition("Np").c_str()), atoi(given_condition("Np").c_str()));
printf("END:Constructor:CHAIN_INFORMATION\n");
}
}
}
CHAIN_INFORMATION(COND& given_condition, ASSOCIATION& CONNECT)
// it initialize based on the CONNECT information
{
if(given_condition("tracking_individual_chain") == "TRUE")
{
if(given_condition("CONTINUATION_CHAIN") == "TRUE")
{
inheritance_chain(given_condition, CONNECT);
}
else
{
printf("ST:Constructor:CHAIN_INFORMATION\n");
initial(CONNECT);
printf("END:Constructor:CHAIN_INFORMATION\n");
}
}
}
virtual ~CHAIN_INFORMATION()
{
if(INITIALIZATION)
delete[] CHAIN;
}
};
// double inline MICELLE::update_SOFT_REPULSION_P2_particle(POTENTIAL_SET& given_POT, ASSOCIATION& CONNECT, MKL_LONG index_particle)
// {
// given_POT.force_variables.C_rep_arr(index_particle) = given_POT.force_variables.repulsion_coefficient_base*CONNECT.N_ASSOCIATION_PARTICLE(index_particle)*CONNECT.N_ASSOCIATION_PARTICLE(index_particle);
// // C_rep(p) = C_0 * p^2
// return given_POT.force_variables.C_rep_arr(index_particle);
// }
#endif
| {
"alphanum_fraction": 0.6929650238,
"avg_line_length": 27.6483516484,
"ext": "h",
"hexsha": "dbeca21e59ff59934bd4c85b729fc6c97f52bec5",
"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": "0b0a3687533379ec75171ae6b906aeff5bedfbba",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "gwpark-git/dynamics_of_networks_and_colloids",
"max_forks_repo_path": "lib/association.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "0b0a3687533379ec75171ae6b906aeff5bedfbba",
"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": "gwpark-git/dynamics_of_networks_and_colloids",
"max_issues_repo_path": "lib/association.h",
"max_line_length": 206,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "0b0a3687533379ec75171ae6b906aeff5bedfbba",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "gwpark-git/dynamics_of_networks_and_colloids",
"max_stars_repo_path": "lib/association.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 4032,
"size": 15096
} |
//====---- Sudoku/Board_Section_iterator.h ----====//
//
// Location aware iterator implementation for Sections
//====--------------------------------------------------------------------====//
//
// The iterator can return a Location object.
// Included by Board_Section.h
//
//====--------------------------------------------------------------------====//
#pragma once
#include "Sudoku/Location.h"
#include "Sudoku/Location_Utilities.h"
#include "Sudoku/traits.h"
#include <gsl/gsl> // index
#include <iterator>
#include <type_traits>
#include "Board.fwd.h" // Forward declarations
#include <cassert>
namespace Sudoku::Board_Section
{
template<typename T, int N, Section S, bool is_const, bool is_reverse>
class Section_iterator;
//====--- Aliases --------------------------------------------------------====//
template<typename T, int N>
using Row_iterator = Section_iterator<T, N, Section::row, false, false>;
template<typename T, int N>
using Col_iterator = Section_iterator<T, N, Section::col, false, false>;
template<typename T, int N>
using Block_iterator = Section_iterator<T, N, Section::block, false, false>;
template<typename T, int N>
using const_Row_iterator = Section_iterator<T, N, Section::row, true, false>;
template<typename T, int N>
using const_Col_iterator = Section_iterator<T, N, Section::col, true, false>;
template<typename T, int N>
using const_Block_iterator =
Section_iterator<T, N, Section::block, true, false>;
template<typename T, int N>
using reverse_Row_iterator = Section_iterator<T, N, Section::row, false, true>;
template<typename T, int N>
using reverse_Col_iterator = Section_iterator<T, N, Section::col, false, true>;
template<typename T, int N>
using reverse_Block_iterator =
Section_iterator<T, N, Section::block, false, true>;
template<typename T, int N>
using const_reverse_Row_iterator =
Section_iterator<T, N, Section::row, true, true>;
template<typename T, int N>
using const_reverse_Col_iterator =
Section_iterator<T, N, Section::col, true, true>;
template<typename T, int N>
using const_reverse_Block_iterator =
Section_iterator<T, N, Section::block, true, true>;
//====--------------------------------------------------------------------====//
template<typename T, int N, Section S, bool is_const, bool is_reverse>
class Section_iterator
{
using owner_type =
std::conditional_t<is_const, Board<T, N> const, Board<T, N>>;
using Location = ::Sudoku::Location<N>;
using Location_Block = ::Sudoku::Location_Block<N>;
public:
// member types
using difference_type = std::ptrdiff_t;
using value_type = T;
using pointer = std::conditional_t<is_const, T const*, T*>;
using reference = std::conditional_t<is_const, T const&, T&>;
using iterator_category = std::random_access_iterator_tag;
// Constructors
constexpr Section_iterator() noexcept
{ // defaults to [r]begin()
if constexpr (is_reverse)
elem_ = elem_size<N> - 1;
}
template<
typename idT,
typename elT,
typename = std::enable_if_t<is_int_v<idT> && is_int_v<elT>>>
constexpr Section_iterator(owner_type* owner, idT id, elT elem) noexcept
: board_(owner), id_(id), elem_(elem)
{
assert(is_valid_size<N>(id));
}
// [[implicit]] Type Conversion to const_(reverse_)iterator
// NOLINTNEXTLINE(google-explicit-constructor, hicpp-explicit-conversions)
constexpr operator Section_iterator<T, N, S, true, is_reverse>()
const noexcept // (guide format)
{
return Section_iterator<T, N, S, true, is_reverse>(board_, id_, elem_);
}
//====----------------------------------------------------------------====//
[[nodiscard]] constexpr Location location() const noexcept
{
assert(is_valid_size<N>(elem_));
using ::Sudoku::Board_Section::Section;
switch (S)
{
case Section::row: return Location(id_, elem_); break;
case Section::col: return Location(elem_, id_); break;
case Section::block: return Location_Block(id_, elem_); break;
}
}
// Allows for conversion to Location
explicit constexpr operator Location() const noexcept { return location(); }
//====----------------------------------------------------------------====//
[[nodiscard]] constexpr reference operator*() const noexcept
{ // Only valid in a dereferenceable location:
assert(board_ != nullptr && is_valid_size<N>(elem_));
return board_->operator[](location());
}
[[nodiscard]] constexpr pointer operator->() const noexcept
{ // member access; equivalent to (*p).member
return std::pointer_traits<pointer>::pointer_to(**this);
}
//====----------------------------------------------------------------====//
constexpr Section_iterator& operator++() noexcept;
constexpr Section_iterator operator++(int) noexcept;
constexpr Section_iterator& operator--() noexcept;
constexpr Section_iterator operator--(int) noexcept;
constexpr Section_iterator&
operator+=(const difference_type offset) noexcept;
constexpr Section_iterator&
operator-=(const difference_type offset) noexcept;
[[nodiscard]] friend constexpr difference_type operator-(
Section_iterator const& left, Section_iterator const& right) noexcept
{ // difference
assert(is_same_Section(left, right));
if constexpr (is_reverse)
return right.elem_ - left.elem_;
else
return left.elem_ - right.elem_;
}
[[nodiscard]] constexpr reference
operator[](const difference_type offset) const noexcept
{
return (*(*this + offset));
}
//====----------------------------------------------------------------====//
[[nodiscard]] friend constexpr bool operator==(
Section_iterator const& left, Section_iterator const& right) noexcept
{
assert(is_same_Section(left, right));
return is_same_Section(left, right) && left.elem_ == right.elem_;
}
[[nodiscard]] friend constexpr bool operator<(
Section_iterator const& left, Section_iterator const& right) noexcept
{
assert(is_same_Section(left, right));
if constexpr (is_reverse)
return left.elem_ > right.elem_;
else
return left.elem_ < right.elem_;
}
private:
owner_type* board_{nullptr};
gsl::index id_{0};
gsl::index elem_{0};
friend constexpr bool is_same_Section(
Section_iterator const& A, Section_iterator const& B) noexcept
{ // compare address of:
return A.board_ == B.board_ && A.id_ == B.id_;
}
};
//====--------------------------------------------------------------------====//
template<typename T, int N, Section S, bool C, bool is_reverse>
constexpr Section_iterator<T, N, S, C, is_reverse>&
Section_iterator<T, N, S, C, is_reverse>::operator++() noexcept
{ // pre-increment
assert(board_ != nullptr);
if constexpr (is_reverse)
{
assert(elem_ >= 0);
--elem_;
}
else
{
assert(elem_ < elem_size<N>);
++elem_;
}
return (*this);
}
template<typename T, int N, Section S, bool C, bool R>
constexpr Section_iterator<T, N, S, C, R> // NOLINTNEXTLINE(readability/casting)
Section_iterator<T, N, S, C, R>::operator++(int) noexcept
{ // post-increment
const Section_iterator pre{*this};
operator++();
return pre;
}
template<typename T, int N, Section S, bool C, bool is_reverse>
constexpr Section_iterator<T, N, S, C, is_reverse>&
Section_iterator<T, N, S, C, is_reverse>::operator--() noexcept
{ // pre-decrement
assert(board_ != nullptr);
if constexpr (is_reverse)
{
assert(elem_ < elem_size<N> - 1);
++elem_;
}
else
{
assert(elem_ > 0);
--elem_;
}
return (*this);
}
template<typename T, int N, Section S, bool C, bool R>
constexpr Section_iterator<T, N, S, C, R> // NOLINTNEXTLINE(readability/casting)
Section_iterator<T, N, S, C, R>::operator--(int) noexcept
{ // post-decrement
const Section_iterator pre{*this};
operator--();
return pre;
}
template<typename T, int N, Section S, bool C, bool is_reverse>
constexpr Section_iterator<T, N, S, C, is_reverse>&
Section_iterator<T, N, S, C, is_reverse>::operator+=(
const difference_type offset) noexcept
{
assert(offset == 0 || board_ != nullptr);
if constexpr (is_reverse)
{
elem_ -= offset;
assert(elem_ >= -1);
assert(elem_ < elem_size<N>);
}
else
{
elem_ += offset;
assert(elem_ >= 0);
assert(elem_ <= elem_size<N>);
}
return (*this);
}
template<typename T, int N, Section S, bool C, bool is_reverse>
constexpr Section_iterator<T, N, S, C, is_reverse>&
Section_iterator<T, N, S, C, is_reverse>::operator-=(
const difference_type offset) noexcept
{
return operator+=(-offset);
}
//====--------------------------------------------------------------------====//
// Free functions (non-friend)
//====--------------------------------------------------------------------====//
template<typename T, int N, Section S, bool is_const, bool is_reverse>
[[nodiscard]] constexpr auto operator+(
Section_iterator<T, N, S, is_const, is_reverse> left,
typename Section_iterator<T, N, S, is_const, is_reverse>::
difference_type const offset) noexcept
{ // itr + offset
return (left += offset);
}
template<typename T, int N, Section S, bool is_const, bool is_reverse>
[[nodiscard]] inline constexpr auto operator+(
typename Section_iterator<T, N, S, is_const, is_reverse>::
difference_type const offset,
Section_iterator<T, N, S, is_const, is_reverse> itr) noexcept
{ // offset + itr
return (itr += offset);
}
template<typename T, int N, Section S, bool is_const, bool is_reverse>
[[nodiscard]] constexpr auto operator-(
Section_iterator<T, N, S, is_const, is_reverse> left,
typename Section_iterator<T, N, S, is_const, is_reverse>::
difference_type const offset) noexcept
{ // itr - offset
return (left += -offset);
}
template<typename T, int N, Section S, bool is_const, bool is_reverse>
[[nodiscard]] inline constexpr bool operator!=(
Section_iterator<T, N, S, is_const, is_reverse> const& left,
Section_iterator<T, N, S, is_const, is_reverse> const& right) noexcept
{
return !(left == right);
}
template<typename T, int N, Section S, bool is_const, bool is_reverse>
[[nodiscard]] inline constexpr bool operator>(
Section_iterator<T, N, S, is_const, is_reverse> const& left,
Section_iterator<T, N, S, is_const, is_reverse> const& right) noexcept
{
return (right < left);
}
template<typename T, int N, Section S, bool is_const, bool is_reverse>
[[nodiscard]] inline constexpr bool operator<=(
Section_iterator<T, N, S, is_const, is_reverse> const& left,
Section_iterator<T, N, S, is_const, is_reverse> const& right) noexcept
{
return !(right < left);
}
template<typename T, int N, Section S, bool is_const, bool is_reverse>
[[nodiscard]] inline constexpr bool operator>=(
Section_iterator<T, N, S, is_const, is_reverse> const& left,
Section_iterator<T, N, S, is_const, is_reverse> const& right) noexcept
{
return !(left < right);
}
} // namespace Sudoku::Board_Section
| {
"alphanum_fraction": 0.661952042,
"avg_line_length": 33.3625,
"ext": "h",
"hexsha": "49e5751c315592f8e627c945f299640ee22e6579",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2020-04-20T16:26:42.000Z",
"max_forks_repo_forks_event_min_datetime": "2020-04-20T16:26:42.000Z",
"max_forks_repo_head_hexsha": "05652d80fae2780f1327467225580e2c67dfa692",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "Farwaykorse/fwkSudoku",
"max_forks_repo_path": "Sudoku/Sudoku/Board/Section_iterator.h",
"max_issues_count": 38,
"max_issues_repo_head_hexsha": "05652d80fae2780f1327467225580e2c67dfa692",
"max_issues_repo_issues_event_max_datetime": "2021-07-17T01:22:35.000Z",
"max_issues_repo_issues_event_min_datetime": "2018-12-28T18:15:15.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "Farwaykorse/fwkSudoku",
"max_issues_repo_path": "Sudoku/Sudoku/Board/Section_iterator.h",
"max_line_length": 80,
"max_stars_count": 2,
"max_stars_repo_head_hexsha": "05652d80fae2780f1327467225580e2c67dfa692",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "Farwaykorse/fwkSudoku",
"max_stars_repo_path": "Sudoku/Sudoku/Board/Section_iterator.h",
"max_stars_repo_stars_event_max_datetime": "2019-08-18T19:26:28.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-03-17T18:27:16.000Z",
"num_tokens": 2601,
"size": 10676
} |
#include <stdio.h>
#include <cblas.h>
#include <sys/time.h>
#include <stdlib.h>
#include <omp.h>
#define NUM 64
#define GEMM_K 320
#define GEMM_N 4096
#define GEMM_M 256
void PACKA(float* A, float* Ac, long M, long K, long LK)
{
long ii, jj, kk;
for( ii = 0 ; ii < M; ii = ii + 8)
{
float *temp = A + ii * LK + kk;
asm volatile(
" ldr x0, %[Ac] \n"
" ldr x1, %[K] \n"
" ldr x2, %[temp] \n"
" ldr x30, %[LK] \n"
" add x3, x2, x30, lsl #2 \n"
" add x4, x2, x30, lsl #3 \n"
" add x5, x3, x30, lsl #3 \n"
" add x6, x4, x30, lsl #3 \n"
" add x7, x5, x30, lsl #3 \n"
" add x8, x6, x30, lsl #3 \n"
" add x9, x7, x30, lsl #3 \n"
" lsr x21, x1, #3 \n"
" cmp x21, #0 \n"
" beq PACKA_END \n"
"PACKA: \n"
" prfm PLDL1KEEP, [x2, #128] \n"
" prfm PLDL1KEEP, [x3, #128] \n"
" ldr q0, [x2], #16 \n"
" ldr q1, [x3], #16 \n"
" ldr q2, [x4], #16 \n"
" ldr q3, [x5], #16 \n"
" prfm PLDL1KEEP, [x4, #128] \n"
" prfm PLDL1KEEP, [x5, #128] \n"
" st4 {v0.s, v1.s, v2.s, v3.s}[0], [x0], #16 \n"
" ldr q4, [x6], #16 \n"
" ldr q5, [x7], #16 \n"
" ldr q6, [x8], #16 \n"
" ldr q7, [x9], #16 \n"
" st4 {v4.s, v5.s, v6.s, v7.s}[0], [x0], #16 \n"
" prfm PLDL1KEEP, [x6, #128] \n"
" prfm PLDL1KEEP, [x7, #128] \n"
" ldr q8, [x2], #16 \n"
" st4 {v0.s, v1.s, v2.s, v3.s}[1], [x0], #16 \n"
" ldr q9, [x3], #16 \n"
" st4 {v4.s, v5.s, v6.s, v7.s}[1], [x0], #16 \n"
" ldr q10, [x4], #16 \n"
" st4 {v0.s, v1.s, v2.s, v3.s}[2], [x0], #16 \n"
" ldr q11, [x5], #16 \n"
" st4 {v4.s, v5.s, v6.s, v7.s}[2], [x0], #16 \n"
" prfm PLDL1KEEP, [x8, #128] \n"
" prfm PLDL1KEEP, [x9, #128] \n"
" ldr q12, [x6], #16 \n"
" st4 {v0.s, v1.s, v2.s, v3.s}[3], [x0], #16 \n"
" ldr q13, [x7], #16 \n"
" st4 {v4.s, v5.s, v6.s, v7.s}[3], [x0], #16 \n"
" ldr q14, [x8], #16 \n"
" st4 {v8.s, v9.s, v10.s, v11.s}[0], [x0], #16 \n"
" ldr q15, [x9], #16 \n"
" st4 {v12.s, v13.s, v14.s, v15.s}[0], [x0], #16 \n"
" subs x21, x21, #1 \n"
" st4 {v8.s, v9.s, v10.s, v11.s}[1], [x0], #16 \n"
" st4 {v12.s, v13.s, v14.s, v15.s}[1], [x0], #16 \n"
" st4 {v8.s, v9.s, v10.s, v11.s}[2], [x0], #16 \n"
" st4 {v12.s, v13.s, v14.s, v15.s}[2], [x0], #16 \n"
" st4 {v8.s, v9.s, v10.s, v11.s}[3], [x0], #16 \n"
" st4 {v12.s, v13.s, v14.s, v15.s}[3], [x0], #16 \n"
" bgt PACKA \n"
" ands x22, x1, #7 \n"
" beq PACKA_END \n"
" cmp x22, #4 \n"
" blt K1_PACKA \n"
"K4_PACKA: \n"
" ldr q0, [x2], #16 \n"
" ldr q1, [x3], #16 \n"
" ldr q2, [x4], #16 \n"
" ldr q3, [x5], #16 \n"
" st4 {v0.s, v1.s, v2.s, v3.s}[0], [x0], #16 \n"
" ldr q4, [x6], #16 \n"
" st4 {v0.s, v1.s, v2.s, v3.s}[1], [x0], #16 \n"
" ldr q5, [x7], #16 \n"
" st4 {v0.s, v1.s, v2.s, v3.s}[2], [x0], #16 \n"
" ldr q6, [x8], #16 \n"
" st4 {v0.s, v1.s, v2.s, v3.s}[3], [x0], #16 \n"
" ldr q7, [x9], #16 \n"
" st4 {v4.s, v5.s, v6.s, v7.s}[0], [x0], #16 \n"
" st4 {v4.s, v5.s, v6.s, v7.s}[1], [x0], #16 \n"
" st4 {v4.s, v5.s, v6.s, v7.s}[2], [x0], #16 \n"
" st4 {v4.s, v5.s, v6.s, v7.s}[3], [x0], #16 \n"
" subs x22, x22, #4 \n"
" beq PACKA_END \n"
"K1_PACKA: \n"
" ldr s0, [x2], #4 \n"
" ldr s1, [x3], #4 \n"
" ldr s2, [x4], #4 \n"
" ldr s3, [x5], #4 \n"
" subs x22, x22, #1 \n"
" st4 {v0.s, v1.s, v2.s, v3.s}[0], [x0], #16 \n"
" ldr s4, [x6], #4 \n"
" ldr s5, [x7], #4 \n"
" ldr s6, [x8], #4 \n"
" ldr s7, [x9], #4 \n"
" st4 {v4.s, v5.s, v6.s, v7.s}[0], [x0], #16 \n"
" bgt K1_PACKA \n"
"PACKA_END: \n"
:
:
[temp] "m" (temp),
[Ac] "m" (Ac),
[K] "m" (K),
[LK] "m" (LK)
:"x0", "x1", "x2", "x3", "x4", "x5", "x6", "x7", "x8",
"x9", "x10", "x11", "x12", "x13","x14", "x15", "x16",
"x17", "x18", "x19", "x20", "x21", "x22", "x23", "x24","x25",
"x26", "x27", "x28", "x29", "x30",
"v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7",
"v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15",
"v16", "v17", "v18", "v19", "v20", "v21", "v22", "v23",
"v24", "v25", "v26", "v27", "v28", "v29", "v30", "v31"
);
Ac = Ac + K * 8;
}
}
void Sin_PACK(float* A, float* Ac, long M, long K, long LK)
{
long ii, jj, kk;
long Kc;
for( kk =0 ; kk < K; kk = kk + Kc)
{
Kc = GEMM_K;
if(K - kk < GEMM_K)
Kc= K - kk;
for( ii = 0 ; ii < M; ii = ii + 8)
{
float *temp = A + ii * LK + kk;
asm volatile(
" ldr x0, %[Ac] \n"
" ldr x1, %[Kc] \n"
" ldr x2, %[temp] \n"
" ldr x30, %[LK] \n"
" add x3, x2, x30, lsl #2 \n"
" add x4, x2, x30, lsl #3 \n"
" add x5, x3, x30, lsl #3 \n"
" add x6, x4, x30, lsl #3 \n"
" add x7, x5, x30, lsl #3 \n"
" add x8, x6, x30, lsl #3 \n"
" add x9, x7, x30, lsl #3 \n"
" lsr x21, x1, #3 \n"
" cmp x21, #0 \n"
" beq Sin_PACKA_END \n"
"Sin_PACKA: \n"
" prfm PLDL1KEEP, [x2, #128] \n"
" prfm PLDL1KEEP, [x3, #128] \n"
" ldr q0, [x2], #16 \n"
" ldr q1, [x3], #16 \n"
" ldr q2, [x4], #16 \n"
" ldr q3, [x5], #16 \n"
" prfm PLDL1KEEP, [x4, #128] \n"
" prfm PLDL1KEEP, [x5, #128] \n"
" st4 {v0.s, v1.s, v2.s, v3.s}[0], [x0], #16 \n"
" ldr q4, [x6], #16 \n"
" ldr q5, [x7], #16 \n"
" ldr q6, [x8], #16 \n"
" ldr q7, [x9], #16 \n"
" st4 {v4.s, v5.s, v6.s, v7.s}[0], [x0], #16 \n"
" prfm PLDL1KEEP, [x6, #128] \n"
" prfm PLDL1KEEP, [x7, #128] \n"
" ldr q8, [x2], #16 \n"
" st4 {v0.s, v1.s, v2.s, v3.s}[1], [x0], #16 \n"
" ldr q9, [x3], #16 \n"
" st4 {v4.s, v5.s, v6.s, v7.s}[1], [x0], #16 \n"
" ldr q10, [x4], #16 \n"
" st4 {v0.s, v1.s, v2.s, v3.s}[2], [x0], #16 \n"
" ldr q11, [x5], #16 \n"
" st4 {v4.s, v5.s, v6.s, v7.s}[2], [x0], #16 \n"
" prfm PLDL1KEEP, [x8, #128] \n"
" prfm PLDL1KEEP, [x9, #128] \n"
" ldr q12, [x6], #16 \n"
" st4 {v0.s, v1.s, v2.s, v3.s}[3], [x0], #16 \n"
" ldr q13, [x7], #16 \n"
" st4 {v4.s, v5.s, v6.s, v7.s}[3], [x0], #16 \n"
" ldr q14, [x8], #16 \n"
" st4 {v8.s, v9.s, v10.s, v11.s}[0], [x0], #16 \n"
" ldr q15, [x9], #16 \n"
" st4 {v12.s, v13.s, v14.s, v15.s}[0], [x0], #16 \n"
" subs x21, x21, #1 \n"
" st4 {v8.s, v9.s, v10.s, v11.s}[1], [x0], #16 \n"
" st4 {v12.s, v13.s, v14.s, v15.s}[1], [x0], #16 \n"
" st4 {v8.s, v9.s, v10.s, v11.s}[2], [x0], #16 \n"
" st4 {v12.s, v13.s, v14.s, v15.s}[2], [x0], #16 \n"
" st4 {v8.s, v9.s, v10.s, v11.s}[3], [x0], #16 \n"
" st4 {v12.s, v13.s, v14.s, v15.s}[3], [x0], #16 \n"
" bgt Sin_PACKA \n"
" ands x22, x1, #7 \n"
" beq Sin_PACKA_END \n"
" cmp x22, #4 \n"
" blt Sin_K1_PACKA \n"
"Sin_K4_PACKA: \n"
" ldr q0, [x2], #16 \n"
" ldr q1, [x3], #16 \n"
" ldr q2, [x4], #16 \n"
" ldr q3, [x5], #16 \n"
" st4 {v0.s, v1.s, v2.s, v3.s}[0], [x0], #16 \n"
" ldr q4, [x6], #16 \n"
" st4 {v0.s, v1.s, v2.s, v3.s}[1], [x0], #16 \n"
" ldr q5, [x7], #16 \n"
" st4 {v0.s, v1.s, v2.s, v3.s}[2], [x0], #16 \n"
" ldr q6, [x8], #16 \n"
" st4 {v0.s, v1.s, v2.s, v3.s}[3], [x0], #16 \n"
" ldr q7, [x9], #16 \n"
" st4 {v4.s, v5.s, v6.s, v7.s}[0], [x0], #16 \n"
" st4 {v4.s, v5.s, v6.s, v7.s}[1], [x0], #16 \n"
" st4 {v4.s, v5.s, v6.s, v7.s}[2], [x0], #16 \n"
" st4 {v4.s, v5.s, v6.s, v7.s}[3], [x0], #16 \n"
" subs x22, x22, #4 \n"
" beq Sin_PACKA_END \n"
"Sin_K1_PACKA: \n"
" ldr s0, [x2], #4 \n"
" ldr s1, [x3], #4 \n"
" ldr s2, [x4], #4 \n"
" ldr s3, [x5], #4 \n"
" subs x22, x22, #1 \n"
" st4 {v0.s, v1.s, v2.s, v3.s}[0], [x0], #16 \n"
" ldr s4, [x6], #4 \n"
" ldr s5, [x7], #4 \n"
" ldr s6, [x8], #4 \n"
" ldr s7, [x9], #4 \n"
" st4 {v4.s, v5.s, v6.s, v7.s}[0], [x0], #16 \n"
" bgt Sin_K1_PACKA \n"
"Sin_PACKA_END: \n"
:
:
[temp] "m" (temp),
[Ac] "m" (Ac),
[Kc] "m" (Kc),
[LK] "m" (LK)
:"x0", "x1", "x2", "x3", "x4", "x5", "x6", "x7", "x8",
"x9", "x10", "x11", "x12", "x13","x14", "x15", "x16",
"x17", "x18", "x19", "x20", "x21", "x22", "x23", "x24","x25",
"x26", "x27", "x28", "x29", "x30",
"v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7",
"v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15",
"v16", "v17", "v18", "v19", "v20", "v21", "v22", "v23",
"v24", "v25", "v26", "v27", "v28", "v29", "v30", "v31"
);
Ac = Ac + Kc * 8;
}
}
}
| {
"alphanum_fraction": 0.37857992,
"avg_line_length": 26.2869318182,
"ext": "h",
"hexsha": "a67e3da7875dca2341a19abf0efcc6f862fe714e",
"lang": "C",
"max_forks_count": 3,
"max_forks_repo_forks_event_max_datetime": "2022-01-07T07:51:15.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-06-04T14:40:41.000Z",
"max_forks_repo_head_hexsha": "2497123bf3bfd12f215b428ae83afd223cd072fc",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "ProgrammerAnonymousWLY/MYLIB",
"max_forks_repo_path": "NN_LIB/PACK.h",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "2497123bf3bfd12f215b428ae83afd223cd072fc",
"max_issues_repo_issues_event_max_datetime": "2021-06-23T17:16:12.000Z",
"max_issues_repo_issues_event_min_datetime": "2021-06-23T17:16:12.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "ProgrammerAnonymousWLY/MYLIB",
"max_issues_repo_path": "NN_LIB/PACK.h",
"max_line_length": 70,
"max_stars_count": 12,
"max_stars_repo_head_hexsha": "2497123bf3bfd12f215b428ae83afd223cd072fc",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "AnonymousYWL/MYLIB",
"max_stars_repo_path": "NN_LIB/PACK.h",
"max_stars_repo_stars_event_max_datetime": "2022-02-21T10:45:29.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-06-04T14:39:37.000Z",
"num_tokens": 5224,
"size": 9253
} |
/********************************************************
Stanford Driving Software
Copyright (c) 2011 Stanford University
All rights reserved.
Redistribution and use in source and binary forms, with
or without modification, are permitted provided that the
following conditions are met:
* Redistributions of source code must retain the above
copyright notice, this list of conditions and the
following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the
following disclaimer in the documentation and/or other
materials provided with the distribution.
* The names of the contributors may not be used to endorse
or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
DAMAGE.
********************************************************/
#ifndef KALMAN_FILTER_H_
#define KALMAN_FILTER_H_
#include <vector>
#include <stdint.h>
#include <gsl/gsl_blas.h>
#include <gsl/gsl_linalg.h>
#include <gsl/gsl_multifit.h>
#include "gsl.h"
namespace vlr {
class KalmanFilter {
public:
KalmanFilter();
KalmanFilter(int state_dim);
KalmanFilter(const KalmanFilter& kf);
virtual ~KalmanFilter();
void transitionUpdate();
void observationUpdate(gsl_vector* innovation_vector);
virtual gsl_vector* predictTransition(gsl_vector* orig);
virtual void predictTransitions(std::vector<gsl_vector*>& orig_pts, std::vector<gsl_vector*>& next_pts);
virtual gsl_vector* predictObservation(gsl_vector* pt);
virtual void predictObservations(std::vector<gsl_vector*>& pts, std::vector<gsl_vector*>& obs);
protected:
void calculateKalmanGain();
public:
int getStateDim() const { return state_dim_; }
void setStateDim(int state_dim);
int getObservationDim() const { return observation_mat_->size1; }
gsl_vector* getMean() const { return mean_; }
gsl_matrix* getCovariance() const { return covariance_; }
gsl_matrix* getKalmanGain() const { return kalman_gain_; }
gsl_matrix* getTransitionMatrix() const { return transition_mat_; }
void setTransitionMatrix(gsl_matrix* transition_mat) { transition_mat_ = transition_mat; }
gsl_matrix* getTransitionCovariance() const { return transition_cov_; }
void setTransitionCovariance(gsl_matrix* transition_cov) { transition_cov_ = transition_cov; }
gsl_matrix* getObservationMatrix() const { return observation_mat_; }
void setObservationMatrix(gsl_matrix* observation_mat) { observation_mat_ = observation_mat; }
gsl_matrix* getObservationCovariance() const { return observation_cov_; }
void setObservationCovariance(gsl_matrix* observation_cov) { observation_cov_ = observation_cov; }
double getYaw() const { return yaw_; }
void setYaw(double yaw) { yaw_ = yaw; }
void print() const;
protected:
int state_dim_;
gsl_vector* mean_;
gsl_matrix* covariance_;
// temp vars
gsl_matrix* kalman_gain_;
gsl_matrix* observation_mat_;
gsl_matrix* observation_cov_;
/*
* TRANSITION MATRIX
*
* (for linear KF
* transition_mat_ is A)
*
* A = [ 1 0 dt 0 ]
* [ 0 1 0 dt ]
* [ 0 0 1 0 ]
* [ 0 0 0 1 ]
*/
gsl_matrix* transition_mat_;
// do we own the pointer?
uint32_t my_trans_mat_;
/*
* TRANSITION COVARIANCE
*
* Q = [ 0 0 0 0 ]
* [ 0 0 0 0 ]
* [ 0 0 q^2 0 ]
* [ 0 0 0 q^2 ]
*/
gsl_matrix* transition_cov_;
// do we own the pointer?
uint32_t my_trans_cov_;
double yaw_;
};
} // namespace vlr
#endif /*KALMAN_FILTER_H_*/
| {
"alphanum_fraction": 0.7145823719,
"avg_line_length": 30.9571428571,
"ext": "h",
"hexsha": "99e60c6e166e3056d4e66f745f73f27f1d30f320",
"lang": "C",
"max_forks_count": 3,
"max_forks_repo_forks_event_max_datetime": "2022-01-23T13:16:09.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-10-10T00:58:29.000Z",
"max_forks_repo_head_hexsha": "02ff7b0fa7b131a2f2203505ef5cc7e43b40bc47",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "yinflight/autonomous_learning",
"max_forks_repo_path": "11_learning_materials/stanford_self_driving_car/libraries/filter/include/kalman_filter.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "02ff7b0fa7b131a2f2203505ef5cc7e43b40bc47",
"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": "yinflight/autonomous_learning",
"max_issues_repo_path": "11_learning_materials/stanford_self_driving_car/libraries/filter/include/kalman_filter.h",
"max_line_length": 106,
"max_stars_count": 14,
"max_stars_repo_head_hexsha": "02ff7b0fa7b131a2f2203505ef5cc7e43b40bc47",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "EatAllBugs/autonomous_learning",
"max_stars_repo_path": "11_learning_materials/stanford_self_driving_car/libraries/filter/include/kalman_filter.h",
"max_stars_repo_stars_event_max_datetime": "2022-02-21T08:49:57.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-09-01T14:25:45.000Z",
"num_tokens": 1066,
"size": 4334
} |
/*
* Copyright (c) 1997-1999 Massachusetts Institute of Technology
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
/* This file was automatically generated --- DO NOT EDIT */
/* Generated on Sun Nov 7 20:44:04 EST 1999 */
#include <fftw-int.h>
#include <fftw.h>
/* Generated by: ./genfft -magic-alignment-check -magic-twiddle-load-all -magic-variables 4 -magic-loopi -notwiddleinv 5 */
/*
* This function contains 32 FP additions, 12 FP multiplications,
* (or, 26 additions, 6 multiplications, 6 fused multiply/add),
* 16 stack variables, and 20 memory accesses
*/
static const fftw_real K250000000 = FFTW_KONST(+0.250000000000000000000000000000000000000000000);
static const fftw_real K951056516 = FFTW_KONST(+0.951056516295153572116439333379382143405698634);
static const fftw_real K587785252 = FFTW_KONST(+0.587785252292473129168705954639072768597652438);
static const fftw_real K559016994 = FFTW_KONST(+0.559016994374947424102293417182819058860154590);
/*
* Generator Id's :
* $Id: exprdag.ml,v 1.41 1999/05/26 15:44:14 fftw Exp $
* $Id: fft.ml,v 1.43 1999/05/17 19:44:18 fftw Exp $
* $Id: to_c.ml,v 1.25 1999/10/26 21:41:32 stevenj Exp $
*/
void fftwi_no_twiddle_5(const fftw_complex *input, fftw_complex *output, int istride, int ostride)
{
fftw_real tmp1;
fftw_real tmp27;
fftw_real tmp8;
fftw_real tmp10;
fftw_real tmp21;
fftw_real tmp22;
fftw_real tmp14;
fftw_real tmp28;
fftw_real tmp26;
fftw_real tmp17;
ASSERT_ALIGNED_DOUBLE;
tmp1 = c_re(input[0]);
tmp27 = c_im(input[0]);
{
fftw_real tmp2;
fftw_real tmp3;
fftw_real tmp4;
fftw_real tmp5;
fftw_real tmp6;
fftw_real tmp7;
ASSERT_ALIGNED_DOUBLE;
tmp2 = c_re(input[istride]);
tmp3 = c_re(input[4 * istride]);
tmp4 = tmp2 + tmp3;
tmp5 = c_re(input[2 * istride]);
tmp6 = c_re(input[3 * istride]);
tmp7 = tmp5 + tmp6;
tmp8 = tmp4 + tmp7;
tmp10 = K559016994 * (tmp4 - tmp7);
tmp21 = tmp2 - tmp3;
tmp22 = tmp5 - tmp6;
}
{
fftw_real tmp12;
fftw_real tmp13;
fftw_real tmp24;
fftw_real tmp15;
fftw_real tmp16;
fftw_real tmp25;
ASSERT_ALIGNED_DOUBLE;
tmp12 = c_im(input[istride]);
tmp13 = c_im(input[4 * istride]);
tmp24 = tmp12 + tmp13;
tmp15 = c_im(input[2 * istride]);
tmp16 = c_im(input[3 * istride]);
tmp25 = tmp15 + tmp16;
tmp14 = tmp12 - tmp13;
tmp28 = tmp24 + tmp25;
tmp26 = K559016994 * (tmp24 - tmp25);
tmp17 = tmp15 - tmp16;
}
c_re(output[0]) = tmp1 + tmp8;
{
fftw_real tmp18;
fftw_real tmp20;
fftw_real tmp11;
fftw_real tmp19;
fftw_real tmp9;
ASSERT_ALIGNED_DOUBLE;
tmp18 = (K587785252 * tmp14) - (K951056516 * tmp17);
tmp20 = (K951056516 * tmp14) + (K587785252 * tmp17);
tmp9 = tmp1 - (K250000000 * tmp8);
tmp11 = tmp9 - tmp10;
tmp19 = tmp10 + tmp9;
c_re(output[2 * ostride]) = tmp11 - tmp18;
c_re(output[3 * ostride]) = tmp11 + tmp18;
c_re(output[ostride]) = tmp19 - tmp20;
c_re(output[4 * ostride]) = tmp19 + tmp20;
}
c_im(output[0]) = tmp27 + tmp28;
{
fftw_real tmp23;
fftw_real tmp31;
fftw_real tmp30;
fftw_real tmp32;
fftw_real tmp29;
ASSERT_ALIGNED_DOUBLE;
tmp23 = (K951056516 * tmp21) + (K587785252 * tmp22);
tmp31 = (K587785252 * tmp21) - (K951056516 * tmp22);
tmp29 = tmp27 - (K250000000 * tmp28);
tmp30 = tmp26 + tmp29;
tmp32 = tmp29 - tmp26;
c_im(output[ostride]) = tmp23 + tmp30;
c_im(output[4 * ostride]) = tmp30 - tmp23;
c_im(output[2 * ostride]) = tmp31 + tmp32;
c_im(output[3 * ostride]) = tmp32 - tmp31;
}
}
fftw_codelet_desc fftwi_no_twiddle_5_desc =
{
"fftwi_no_twiddle_5",
(void (*)()) fftwi_no_twiddle_5,
5,
FFTW_BACKWARD,
FFTW_NOTW,
122,
0,
(const int *) 0,
};
| {
"alphanum_fraction": 0.670603967,
"avg_line_length": 30.5238095238,
"ext": "c",
"hexsha": "3c2ab12dd276b4313ac6a1c77583aba78efd6bf7",
"lang": "C",
"max_forks_count": 8,
"max_forks_repo_forks_event_max_datetime": "2022-03-29T02:59:10.000Z",
"max_forks_repo_forks_event_min_datetime": "2017-11-20T07:52:01.000Z",
"max_forks_repo_head_hexsha": "3361d1f18bf529958b78231fdcf139b1c1c1f232",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "albertsgrc/ftdock-opt",
"max_forks_repo_path": "original/lib/fftw-2.1.3/fftw/fni_5.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "3361d1f18bf529958b78231fdcf139b1c1c1f232",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "albertsgrc/ftdock-opt",
"max_issues_repo_path": "original/lib/fftw-2.1.3/fftw/fni_5.c",
"max_line_length": 123,
"max_stars_count": 9,
"max_stars_repo_head_hexsha": "3361d1f18bf529958b78231fdcf139b1c1c1f232",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "albertsgrc/ftdock-opt",
"max_stars_repo_path": "original/lib/fftw-2.1.3/fftw/fni_5.c",
"max_stars_repo_stars_event_max_datetime": "2022-01-08T14:37:24.000Z",
"max_stars_repo_stars_event_min_datetime": "2018-10-03T19:57:47.000Z",
"num_tokens": 1488,
"size": 4487
} |
#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
#include <Python.h>
#include <numpy/arrayobject.h>
#include <math.h>
#ifdef __INTEL_COMPILER
#include <mkl_cblas.h>
#else
#include <cblas.h>
#define kmp_set_blocktime(k)
#endif
static inline int min (int a, int b) { return a < b ? a : b; }
static inline int max (int a, int b) { return a < b ? b : a; }
static inline int square(int x) { return x*x; }
static void max_filter_1d(const float *vals, float *out_vals, int32_t *I,
int s, int step, int n, float a, float b) {
int i;
for (i = 0; i < n; i++) {
float max_val = -INFINITY;
int argmax = 0;
int first = max(0, i-s);
int last = min(n-1, i+s);
int j;
for (j = first; j <= last; j++) {
float val = *(vals + j*step) - a*square(i-j) - b*(i-j);
if (val > max_val) {
max_val = val;
argmax = j;
}
}
*(out_vals + i*step) = max_val;
*(I + i*step) = argmax;
}
}
PyObject * deformation_cost (PyArrayObject * pydata, float ax, float bx, float ay, float by, int s) {
npy_intp * dims = PyArray_DIMS(pydata);
npy_intp * stride = PyArray_STRIDES(pydata);
if (PyArray_NDIM(pydata) != 2) {
PyErr_SetString(PyExc_TypeError, "data must be 2 dimensional.");
return NULL;
}
if (PyArray_DESCR(pydata)->type_num != NPY_FLOAT) {
PyErr_SetString(PyExc_TypeError, "data must be single precision floating point.");
return NULL;
}
if (stride[0] != dims[1]*sizeof(float)) {
PyErr_SetString(PyExc_TypeError, "Stride[0] must be sizeof(float).");
return NULL;
}
if (stride[1] != sizeof(float)) {
PyErr_SetString(PyExc_TypeError, "Stride[1] must be Dims[0]*sizeof(float).");
return NULL;
}
PyArrayObject * pydeformed = (PyArrayObject*)PyArray_SimpleNew((npy_intp)2, dims, NPY_FLOAT);
PyArrayObject * pyIx = (PyArrayObject*)PyArray_SimpleNew((npy_intp)2, dims, NPY_INT32);
PyArrayObject * pyIy = (PyArrayObject*)PyArray_SimpleNew((npy_intp)2, dims, NPY_INT32);
float *tmpM = (float *)calloc(dims[0]*dims[1], sizeof(float));
int32_t *tmpIx = (int32_t*)calloc(dims[0]*dims[1], sizeof(int32_t));
int32_t *tmpIy = (int32_t*)calloc(dims[0]*dims[1], sizeof(int32_t));
int x, y;
for (y = 0; y < dims[0]; y++)
max_filter_1d((float*)PyArray_GETPTR2(pydata, y, 0), tmpM+y*dims[1], tmpIx+y*dims[1], s, 1, dims[1], ax, bx);
for (x = 0; x < dims[1]; x++)
max_filter_1d(tmpM+x, (float*)PyArray_GETPTR2(pydeformed, 0, x), tmpIy+x, s, dims[1], dims[0], ay, by);
for (x = 0; x < dims[1]; ++x) {
for (y = 0; y < dims[0]; ++y) {
*(int32_t*)PyArray_GETPTR2(pyIy, y, x) = tmpIy[y*dims[1]+x];
*(int32_t*)PyArray_GETPTR2(pyIx, y, x) = tmpIx[tmpIy[y*dims[1]+x]*dims[1]+x];
}
}
free(tmpM);
free(tmpIx);
free(tmpIy);
return Py_BuildValue("NNN", pydeformed, pyIx, pyIy);
}
PyObject * filter_image (PyArrayObject * pyfeatures, PyArrayObject * pyfilter, float bias, int width, int height) {
npy_intp * features_dims = PyArray_DIMS(pyfeatures);
npy_intp * filter_dims = PyArray_DIMS(pyfilter);
int a, b, l;
PyArrayObject * pyfiltered = NULL;
npy_intp * features_stride = PyArray_STRIDES(pyfeatures);
npy_intp * filtered_stride = NULL;
npy_intp filtered_dims[2] = {0, 0};
int tight_width;
int tight_height;
if (PyArray_NDIM(pyfeatures) != 3) {
PyErr_SetString(PyExc_TypeError, "Features must be 3 dimensional.");
return NULL;
}
if (PyArray_NDIM(pyfilter) != 3) {
PyErr_SetString(PyExc_TypeError, "Filter must be 3 dimensional.");
return NULL;
}
if (PyArray_DESCR(pyfeatures)->type_num != NPY_FLOAT) {
PyErr_SetString(PyExc_TypeError, "Features must be single precision floating point.");
return NULL;
}
if (PyArray_DESCR(pyfilter)->type_num != NPY_FLOAT) {
PyErr_SetString(PyExc_TypeError, "Filter must be a single precision floating point.");
return NULL;
}
if (features_dims[2] != 32) {
PyErr_SetString(PyExc_TypeError, "features' feature dimsionality should be 32.");
return NULL;
}
if (filter_dims[2] != 32) {
PyErr_SetString(PyExc_TypeError, "filters' feature dimensionality should be 32.");
return NULL;
}
tight_height = features_dims[0]-filter_dims[0]+1;
tight_width = features_dims[1]-filter_dims[1]+1;
filtered_dims[0] = height ? height : tight_height;
filtered_dims[1] = width ? width : tight_width;
if (filtered_dims[0] < 1 || filtered_dims[1] < 1) {
PyErr_SetString(PyExc_TypeError, "Input features are too small for filter.");
return NULL;
}
#pragma omp critical
pyfiltered = (PyArrayObject*)PyArray_SimpleNew((npy_intp)2, filtered_dims, NPY_FLOAT);
filtered_stride = PyArray_STRIDES(pyfiltered);
/* zero out array */
for (a = 0; a < tight_height; ++a) {
for (b = 0; b < tight_width; ++b) {
*(float*)PyArray_GETPTR2(pyfiltered, a, b) = -bias;
}
}
/* iterate over filter which should be tiny compared to the image */
int i;
int stride_src = features_stride[1]/sizeof(float);
int stride_dst = filtered_stride[1]/sizeof(float);
for (i = 0; i < filter_dims[0]; ++i) {
int j;
for (j = 0; j < filter_dims[1]; ++j) {
int k;
for (k = 0; k < tight_height; ++k) {
float * out = (float*)PyArray_GETPTR2(pyfiltered, k, 0);
/* for each layer */
for (l = 0; l < 32; ++l) {
float weight = *(float*)PyArray_GETPTR3(pyfilter, i, j, l);
float * in = (float*)PyArray_GETPTR3(pyfeatures, i+k, j, l);
cblas_saxpy(tight_width, weight, in, stride_src, out, stride_dst);
}
}
}
}
for (a = tight_height; a < filtered_dims[0]; ++a) {
for (b = 0; b < filtered_dims[1]; ++b) {
*(float*)PyArray_GETPTR2(pyfiltered, a, b) = -INFINITY;
}
}
for (a = 0; a < tight_height; ++a) {
for (b = tight_width; b < filtered_dims[1]; ++b) {
*(float*)PyArray_GETPTR2(pyfiltered, a, b) = -INFINITY;
}
}
return Py_BuildValue("N", pyfiltered);
}
static PyObject * DeformationCost(PyObject * self, PyObject * args)
{
PyArrayObject * pydata;
float ax = 0.0f, bx = 0.0f, ay = 0.0f, by = 0.0f;
int s = 0;
if (!PyArg_ParseTuple(args, "O!ffffi", &PyArray_Type, &pydata, &ax, &bx, &ay, &by, &s))
return NULL;
return deformation_cost(pydata, ax, bx, ay, by, s);
}
static PyObject * FilterImage(PyObject * self, PyObject * args)
{
PyArrayObject * pyfeatures;
PyArrayObject * pyfilter;
float bias = 0.0f;
int width = 0;
int height = 0;
if (!PyArg_ParseTuple(args, "O!O!|fii", &PyArray_Type, &pyfeatures, &PyArray_Type, &pyfilter, &bias, &width, &height))
return NULL;
return filter_image(pyfeatures, pyfilter, bias, width, height);
}
static PyObject * FilterImages(PyObject * self, PyObject * args)
{
PyObject * pyfeatures_list;
PyObject * pydims_list = NULL;
PyArrayObject * pyfilter;
float bias = 0.0f;
int numfilters;
int numdims = 0;
int i;
PyObject ** objs = NULL;
PyObject ** results = NULL;
PyObject * pyresults_list;
if (!PyArg_ParseTuple(args, "O!O!|fO!", &PyList_Type, &pyfeatures_list, &PyArray_Type, &pyfilter, &bias, &PyList_Type, &pydims_list))
return NULL;
numfilters = PyList_Size(pyfeatures_list);
if (pydims_list) {
numdims = PyList_Size(pydims_list);
}
if (numdims && numdims != numfilters) {
PyErr_SetString(PyExc_TypeError, "If pad dims are specified, then it must be the same length as the features list.");
return NULL;
}
objs = (PyObject**)calloc(numfilters, sizeof(PyObject*));
int* widths = (int*)calloc(numfilters, sizeof(int));
int* heights = (int*)calloc(numfilters, sizeof(int));
results = (PyObject**)calloc(numfilters, sizeof(PyObject*));
for (i = 0; i < numfilters; ++i) {
objs[i] = PyList_GetItem(pyfeatures_list, i);
if (!PyArray_Check(objs[i])) {
free(objs);
free(widths);
free(heights);
free(results);
PyErr_SetString(PyExc_TypeError, "Must contain a list of numpy arrays.");
return NULL;
}
if (pydims_list) {
PyObject * dims = PyList_GetItem(pydims_list, i);
if (!PyTuple_Check(dims) || 2 != PyTuple_Size(dims)) {
free(objs);
free(widths);
free(heights);
free(results);
PyErr_SetString(PyExc_TypeError, "Must contain a list of tuples.");
return NULL;
}
heights[i] = PyInt_AsLong(PyTuple_GetItem(dims, 0));
widths[i] = PyInt_AsLong(PyTuple_GetItem(dims, 1));
} else {
widths[i] = 0;
heights[i] = 0;
}
}
kmp_set_blocktime(0);
#pragma omp parallel for schedule(dynamic)
for (i = 0; i < numfilters; ++i) {
PyArrayObject * pyfeatures = (PyArrayObject*)objs[i];
results[i] = filter_image(pyfeatures, pyfilter, bias, widths[i], heights[i]);
}
free(objs);
free(widths);
free(heights);
pyresults_list = PyList_New(numfilters);
for (i = 0; i < numfilters; ++i) {
PyList_SetItem(pyresults_list, i, results[i]);
}
free(results);
return Py_BuildValue("N", pyresults_list);
}
#if PY_MAJOR_VERSION >= 3
static struct PyModuleDef moduledef = {
PyModuleDef_HEAD_INIT,
"_detection",
"Native convolution detection routine.",
-1,
NULL,
NULL,
NULL,
NULL,
NULL
};
#endif
#if PY_MAJOR_VERSION < 3
static PyMethodDef _detection_methods[] = {
{"FilterImage", FilterImage, METH_VARARGS, "Compute a 2D cross correlation between a filter and image features. Optionally add bias term."},
{"FilterImages", FilterImages, METH_VARARGS, "Compute a 2D cross correlation between a filter and several image features in parallel. Optionally add bias term."},
{"DeformationCost", DeformationCost, METH_VARARGS, "Compute a fast bounded distance transform for the deformation cost."},
{NULL}
};
#endif
#if PY_MAJOR_VERSION >= 3
PyMODINIT_FUNC
PyInit__detection(void)
#else
PyMODINIT_FUNC
init_detection(void)
#endif
{
import_array();
#if PY_MAJOR_VERSION >= 3
PyObject *m = PyModule_Create(&moduledef);
#else
Py_InitModule3("_detection", _detection_methods, "Native convolution detection routine.");
#endif
#if PY_MAJOR_VERSION >= 3
return m;
#endif
}
| {
"alphanum_fraction": 0.6133905259,
"avg_line_length": 31.4486803519,
"ext": "c",
"hexsha": "a73ea5929985acf1ef27d050a9c23487f5fe89d4",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2017-04-30T07:30:11.000Z",
"max_forks_repo_forks_event_min_datetime": "2016-08-20T14:21:54.000Z",
"max_forks_repo_head_hexsha": "00286cb99a58e4c49fe79b08d8ae041cf8ee173c",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "kmatzen/pydro",
"max_forks_repo_path": "src/pydro/_detection.c",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "00286cb99a58e4c49fe79b08d8ae041cf8ee173c",
"max_issues_repo_issues_event_max_datetime": "2017-02-06T07:54:15.000Z",
"max_issues_repo_issues_event_min_datetime": "2017-02-06T07:54:15.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "caomw/pydro",
"max_issues_repo_path": "src/pydro/_detection.c",
"max_line_length": 167,
"max_stars_count": 15,
"max_stars_repo_head_hexsha": "00286cb99a58e4c49fe79b08d8ae041cf8ee173c",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "caomw/pydro",
"max_stars_repo_path": "src/pydro/_detection.c",
"max_stars_repo_stars_event_max_datetime": "2017-04-24T01:25:25.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-01-05T23:41:08.000Z",
"num_tokens": 3144,
"size": 10724
} |
/**
*
* @file testing_csymm.c
*
* PLASMA testing 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 Mathieu Faverge
* @date 2010-11-15
* @generated c Tue Jan 7 11:45:18 2014
*
**/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <plasma.h>
#include <cblas.h>
#include <lapacke.h>
#include <core_blas.h>
#include "testing_cmain.h"
static int check_solution(PLASMA_enum transA, PLASMA_enum transB, int M, int N,
PLASMA_Complex32_t alpha, PLASMA_Complex32_t *A, int LDA,
PLASMA_Complex32_t *B, int LDB,
PLASMA_Complex32_t beta, PLASMA_Complex32_t *Cref, PLASMA_Complex32_t *Cplasma, int LDC);
int testing_csymm(int argc, char **argv)
{
/* Check for number of arguments*/
if ( argc != 7 ){
USAGE("SYMM", "alpha beta M N K LDA LDB LDC",
" - alpha : alpha coefficient \n"
" - beta : beta coefficient \n"
" - M : number of rows of matrices A and C \n"
" - N : number of columns of matrices B and C \n"
" - LDA : leading dimension of matrix A \n"
" - LDB : leading dimension of matrix B \n"
" - LDC : leading dimension of matrix C\n");
return -1;
}
PLASMA_Complex32_t alpha = (PLASMA_Complex32_t) atol(argv[0]);
PLASMA_Complex32_t beta = (PLASMA_Complex32_t) atol(argv[1]);
int M = atoi(argv[2]);
int N = atoi(argv[3]);
int LDA = atoi(argv[4]);
int LDB = atoi(argv[5]);
int LDC = atoi(argv[6]);
int MNmax = max(M, N);
float eps;
int info_solution;
int i, j, s, u;
int LDAxM = LDA*MNmax;
int LDBxN = LDB*N;
int LDCxN = LDC*N;
PLASMA_Complex32_t *A = (PLASMA_Complex32_t *)malloc(LDAxM*sizeof(PLASMA_Complex32_t));
PLASMA_Complex32_t *B = (PLASMA_Complex32_t *)malloc(LDBxN*sizeof(PLASMA_Complex32_t));
PLASMA_Complex32_t *C = (PLASMA_Complex32_t *)malloc(LDCxN*sizeof(PLASMA_Complex32_t));
PLASMA_Complex32_t *Cinit = (PLASMA_Complex32_t *)malloc(LDCxN*sizeof(PLASMA_Complex32_t));
PLASMA_Complex32_t *Cfinal = (PLASMA_Complex32_t *)malloc(LDCxN*sizeof(PLASMA_Complex32_t));
/* Check if unable to allocate memory */
if ((!A)||(!B)||(!Cinit)||(!Cfinal)){
printf("Out of Memory \n ");
return -2;
}
eps = LAPACKE_slamch_work('e');
printf("\n");
printf("------ TESTS FOR PLASMA CSYMM ROUTINE ------- \n");
printf(" Size of the Matrix %d by %d\n", M, N);
printf("\n");
printf(" The matrix A is randomly generated for each test.\n");
printf("============\n");
printf(" The relative machine precision (eps) is to be %e \n",eps);
printf(" Computational tests pass if scaled residuals are less than 10.\n");
/*----------------------------------------------------------
* TESTING CSYMM
*/
/* Initialize A */
PLASMA_cplgsy( (float)0., MNmax, A, LDA, 51 );
/* Initialize B */
LAPACKE_clarnv_work(IONE, ISEED, LDBxN, B);
/* Initialize C */
LAPACKE_clarnv_work(IONE, ISEED, LDCxN, C);
for (s=0; s<2; s++) {
for (u=0; u<2; u++) {
/* Initialize Cinit / Cfinal */
for ( i = 0; i < M; i++)
for ( j = 0; j < N; j++)
Cinit[LDC*j+i] = C[LDC*j+i];
for ( i = 0; i < M; i++)
for ( j = 0; j < N; j++)
Cfinal[LDC*j+i] = C[LDC*j+i];
/* PLASMA CSYMM */
PLASMA_csymm(side[s], uplo[u], M, N, alpha, A, LDA, B, LDB, beta, Cfinal, LDC);
/* Check the solution */
info_solution = check_solution(side[s], uplo[u], M, N, alpha, A, LDA, B, LDB, beta, Cinit, Cfinal, LDC);
if (info_solution == 0) {
printf("***************************************************\n");
printf(" ---- TESTING CSYMM (%5s, %5s) ....... PASSED !\n", sidestr[s], uplostr[u]);
printf("***************************************************\n");
}
else {
printf("************************************************\n");
printf(" - TESTING CSYMM (%s, %s) ... FAILED !\n", sidestr[s], uplostr[u]);
printf("************************************************\n");
}
}
}
free(A); free(B); free(C);
free(Cinit); free(Cfinal);
return 0;
}
/*--------------------------------------------------------------
* Check the solution
*/
static int check_solution(PLASMA_enum side, PLASMA_enum uplo, int M, int N,
PLASMA_Complex32_t alpha, PLASMA_Complex32_t *A, int LDA,
PLASMA_Complex32_t *B, int LDB,
PLASMA_Complex32_t beta, PLASMA_Complex32_t *Cref, PLASMA_Complex32_t *Cplasma, int LDC)
{
int info_solution, NrowA;
float Anorm, Bnorm, Cinitnorm, Cplasmanorm, Clapacknorm, Rnorm;
float eps;
PLASMA_Complex32_t beta_const;
float result;
float *work = (float *)malloc(max(M, N)* sizeof(float));
beta_const = (PLASMA_Complex32_t)-1.0;
NrowA = (side == PlasmaLeft) ? M : N;
Anorm = LAPACKE_clange_work(LAPACK_COL_MAJOR, lapack_const(PlasmaInfNorm), NrowA, NrowA, A, LDA, work);
Bnorm = LAPACKE_clange_work(LAPACK_COL_MAJOR, lapack_const(PlasmaInfNorm), M, N, B, LDB, work);
Cinitnorm = LAPACKE_clange_work(LAPACK_COL_MAJOR, lapack_const(PlasmaInfNorm), M, N, Cref, LDC, work);
Cplasmanorm = LAPACKE_clange_work(LAPACK_COL_MAJOR, lapack_const(PlasmaInfNorm), M, N, Cplasma, LDC, work);
cblas_csymm(CblasColMajor, (CBLAS_SIDE)side, (CBLAS_UPLO)uplo, M, N, CBLAS_SADDR(alpha), A, LDA, B, LDB, CBLAS_SADDR(beta), Cref, LDC);
Clapacknorm = LAPACKE_clange_work(LAPACK_COL_MAJOR, lapack_const(PlasmaInfNorm), M, N, Cref, LDC, work);
cblas_caxpy(LDC * N, CBLAS_SADDR(beta_const), Cplasma, 1, Cref, 1);
Rnorm = LAPACKE_clange_work(LAPACK_COL_MAJOR, lapack_const(PlasmaInfNorm), M, N, Cref, LDC, work);
eps = LAPACKE_slamch_work('e');
printf("Rnorm %e, Anorm %e, Bnorm %e, Cinitnorm %e, Cplasmanorm %e, Clapacknorm %e\n",Rnorm,Anorm,Bnorm,Cinitnorm,Cplasmanorm,Clapacknorm);
result = Rnorm / ((Anorm + Bnorm + Cinitnorm) * N * eps);
printf("============\n");
printf("Checking the norm of the difference against reference CSYMM \n");
printf("-- ||Cplasma - Clapack||_oo/((||A||_oo+||B||_oo+||C||_oo).N.eps) = %e \n", result );
if ( isinf(Clapacknorm) || isinf(Cplasmanorm) || isnan(result) || isinf(result) || (result > 10.0) ) {
printf("-- The solution is suspicious ! \n");
info_solution = 1;
}
else {
printf("-- The solution is CORRECT ! \n");
info_solution= 0 ;
}
free(work);
return info_solution;
}
| {
"alphanum_fraction": 0.5528189066,
"avg_line_length": 37.5614973262,
"ext": "c",
"hexsha": "9e0f583a33772b98b7301fbd3f0c14a49cd0c2c6",
"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": "testing/testing_csymm.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": "testing/testing_csymm.c",
"max_line_length": 143,
"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": "testing/testing_csymm.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 2188,
"size": 7024
} |
#ifndef QDM_IJK_H
#define QDM_IJK_H 1
#include <stddef.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_vector.h>
#include <hdf5.h>
typedef struct {
size_t size1;
size_t size2;
size_t size3;
double *data;
bool owner;
} qdm_ijk;
typedef struct {
qdm_ijk ijk;
} qdm_ijk_view;
qdm_ijk *
qdm_ijk_alloc(
size_t size1,
size_t size2,
size_t size3
);
qdm_ijk *
qdm_ijk_calloc(
size_t size1,
size_t size2,
size_t size3
);
void
qdm_ijk_free(qdm_ijk *t);
qdm_ijk_view
qdm_ijk_view_array(
double *base,
size_t size1,
size_t size2,
size_t size3
);
gsl_vector_view
qdm_ijk_get_k(
qdm_ijk *t,
size_t i,
size_t j
);
gsl_matrix_view
qdm_ijk_get_ij(
qdm_ijk *t,
size_t k
);
double
qdm_ijk_get(
qdm_ijk *t,
size_t i,
size_t j,
size_t k
);
gsl_matrix *
qdm_ijk_cov(
qdm_ijk *t
);
int
qdm_ijk_write(
hid_t id,
const char *name,
const qdm_ijk *t
);
int
qdm_ijk_read(
hid_t id,
const char *name,
qdm_ijk **t
);
#endif /* QDM_IJK_H */
| {
"alphanum_fraction": 0.656759348,
"avg_line_length": 11.7191011236,
"ext": "h",
"hexsha": "1dd700ef458f473b08896e0b9417a1d5454e3a3b",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "2ee95bec6c8be64f69e231c78f2be5fce3509c67",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "calebcase/qdm",
"max_forks_repo_path": "include/qdm/ijk.h",
"max_issues_count": 3,
"max_issues_repo_head_hexsha": "2ee95bec6c8be64f69e231c78f2be5fce3509c67",
"max_issues_repo_issues_event_max_datetime": "2020-03-22T20:22:53.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-03-06T18:09:06.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "calebcase/qdm",
"max_issues_repo_path": "include/qdm/ijk.h",
"max_line_length": 27,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "2ee95bec6c8be64f69e231c78f2be5fce3509c67",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "calebcase/qdm",
"max_stars_repo_path": "include/qdm/ijk.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 385,
"size": 1043
} |
#include <gsl/gsl_math.h>
#include "gsl_cblas.h"
#include "cblas.h"
void
cblas_drot (const int N, double *X, const int incX, double *Y, const int incY,
const double c, const double s)
{
#define BASE double
#include "source_rot.h"
#undef BASE
}
| {
"alphanum_fraction": 0.708,
"avg_line_length": 19.2307692308,
"ext": "c",
"hexsha": "fcc7476d29701589f5e84a7d82d88dfe8074eb2e",
"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/drot.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/drot.c",
"max_line_length": 78,
"max_stars_count": 14,
"max_stars_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "ICML14MoMCompare/spectral-learn",
"max_stars_repo_path": "code/em/treba/gsl-1.0/cblas/drot.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": 76,
"size": 250
} |
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_vector.h>
#include "cimple_polytope_library.h"
/**
* "Constructor" Dynamically allocates the space a polytope needs
*/
struct polytope *polytope_alloc(size_t k,
size_t n)
{
struct polytope *return_polytope = malloc (sizeof (struct polytope));
return_polytope->H = gsl_matrix_alloc(k, n);
if (return_polytope->H == NULL) {
free (return_polytope);
return NULL;
}
return_polytope->G = gsl_vector_alloc(k);
if (return_polytope->H == NULL) {
free (return_polytope);
return NULL;
}
return_polytope->chebyshev_center = malloc(n* sizeof (double));
if (return_polytope->chebyshev_center == NULL) {
free (return_polytope);
return NULL;
}
return return_polytope;
};
/**
* "Destructor" Deallocates the dynamically allocated memory of the polytope
*/
void polytope_free(polytope *polytope)
{
gsl_matrix_free(polytope->H);
gsl_vector_free(polytope->G);
free(polytope->chebyshev_center);
free(polytope);
};
/**
* "Constructor" Dynamically allocates the space a polytope needs
*/
struct cell *cell_alloc(size_t k,
size_t n,
int time_horizon)
{
struct cell *return_cell = malloc (sizeof (struct cell));
return_cell->safe_mode = malloc(sizeof(polytope)*time_horizon);
if (return_cell->safe_mode == NULL) {
free (return_cell);
return NULL;
}
return_cell->polytope_description = polytope_alloc(k,n);
if (return_cell->polytope_description == NULL) {
free (return_cell);
return NULL;
}
return return_cell;
};
/**
* "Destructor" Deallocates the dynamically allocated memory of the region of polytopes
*/
void cell_free(cell *cell)
{
polytope_free(cell->polytope_description);
free(cell->safe_mode);
free(cell);
};
/**
* "Constructor" Dynamically allocates the space a region of polytope needs
*/
struct abstract_state *abstract_state_alloc(size_t *k,
size_t k_hull,
size_t n,
int transitions_in_count,
int transitions_out_count,
int cells_count,
int time_horizon)
{
struct abstract_state *return_abstract_state = malloc (sizeof (struct abstract_state));
/*
* Default values: at initialization safe mode is not yet computed.
* Thus it is assumed that the state does not contain an invariant set => invariant_set = NULL
* next_state (next state the system has to transition to reach an invariant set) is unknown at initialization.
*/
return_abstract_state->next_state = NULL;
return_abstract_state->invariant_set = NULL;
// return_abstract_state->distance_invariant_set = INFINITY;
return_abstract_state->cells = malloc(sizeof(cell)*cells_count);
if (return_abstract_state->cells == NULL) {
free (return_abstract_state);
return NULL;
}
for(int i = 0; i < cells_count; i++){
return_abstract_state->cells[i] = cell_alloc(*(k+i), n, time_horizon);
if (return_abstract_state->cells[i] == NULL) {
free (return_abstract_state);
return NULL;
}
}
return_abstract_state->cells_count = cells_count;
return_abstract_state->transitions_in = malloc(sizeof(struct abstract_state) * transitions_in_count);
if (return_abstract_state->transitions_in == NULL) {
free (return_abstract_state);
return NULL;
}
return_abstract_state->transitions_in_count = transitions_in_count;
return_abstract_state->transitions_out = malloc(sizeof(struct abstract_state) * transitions_out_count);
if (return_abstract_state->transitions_out == NULL) {
free (return_abstract_state);
return NULL;
}
return_abstract_state->transitions_out_count = transitions_out_count;
return_abstract_state->convex_hull = polytope_alloc(k_hull, n);
if (return_abstract_state->convex_hull == NULL) {
free (return_abstract_state);
return NULL;
}
return return_abstract_state;
};
/**
* "Destructor" Deallocates the dynamically allocated memory of the region of polytopes
*/
void abstract_state_free(abstract_state * abstract_state){
polytope_free(abstract_state->convex_hull);
for(int i = 0; i< abstract_state->cells_count; i++){
cell_free(abstract_state->cells[i]);
}
free(abstract_state->transitions_out);
free(abstract_state->transitions_in);
free(abstract_state->cells);
free(abstract_state);
};
/**
* Converts two C arrays to a polytope consistent of a left side matrix (i.e. H) and right side vector (i.e. G)
*/
void polytope_from_arrays(polytope *polytope,
double *left_side,
double *right_side,
double *cheby,
char*name)
{
gsl_matrix_from_array(polytope->H, left_side, name);
gsl_vector_from_array(polytope->G, right_side, name);
for(int i = 0; i < polytope->H->size2; i++){
polytope->chebyshev_center[i] = cheby[i];
}
};
/**
* Converts a polytope in gsl form to cdd constraint form
*/
dd_PolyhedraPtr polytope_to_cdd(polytope *original,
dd_ErrorType *err)
{
dd_PolyhedraPtr new;
dd_MatrixPtr constraints;
constraints = dd_CreateMatrix(original->H->size1, (original->H->size2+1));
for (size_t k = 0; k < (original->H->size1); k++) {
double value = gsl_vector_get(original->G, k);
dd_set_d(constraints->matrix[k][0],value);
}
for(size_t i = 0; i<original->H->size1; i++){
for (size_t j = 1; j < (original->H->size2+1); j++) {
double value = gsl_matrix_get(original->H, i, j-1);
dd_set_d(constraints->matrix[i][j],-1*value);
}
}
constraints->representation=dd_Inequality;
new = dd_DDMatrix2Poly(constraints, err);
dd_FreeMatrix(constraints);
return new;
};
/**
* Converts a polytope in cdd constraint form to gsl form
*/
polytope * cdd_to_polytope(dd_PolyhedraPtr *original)
{
dd_MatrixPtr constraints;
constraints = dd_CopyInequalities(*original);
polytope *new = polytope_alloc(constraints->rowsize, constraints->colsize-1);
for (size_t k = 0; k < (constraints->rowsize); k++) {
double value = dd_get_d(constraints->matrix[k][0]);
gsl_vector_set(new->G, k, value);
}
for(size_t i = 0; i<constraints->rowsize; i++){
for (size_t j = 0; j < (constraints->colsize-1); j++) {
double value = dd_get_d(constraints->matrix[i][j+1]);
gsl_matrix_set(new->H,i,j,-value);
}
}
dd_FreeMatrix(constraints);
return new;
};
/**
* Generate a polytope representing a scaled unit cube
*/
polytope * polytope_scaled_unit_cube(double scale,
int dimensions)
{
dd_PolyhedraPtr cube = cdd_scaled_unit_cube(scale, dimensions);
polytope * return_cube = cdd_to_polytope(&cube);
dd_FreePolyhedra(cube);
return return_cube;
};
/**
* Checks whether a state is in a certain polytope
*/
bool polytope_check_state(polytope *polytope,
gsl_vector *x)
{
gsl_vector * result = gsl_vector_alloc(polytope->G->size);
gsl_blas_dgemv(CblasNoTrans, 1.0, polytope->H, x, 0.0, result);
for(size_t i = 0; i< polytope->G->size; i++){
if(gsl_vector_get(result, i) > gsl_vector_get(polytope->G, i)){
gsl_vector_free(result);
return false;
}
}
gsl_vector_free(result);
return true;
};
/**
* Checks whether polytope P1 \ issubset P2
*/
bool polytope_is_subset(polytope *P1,
polytope *P2)
{
dd_ErrorType err = dd_NoError;
dd_PolyhedraPtr first = polytope_to_cdd(P1, &err);
dd_MatrixPtr verticesFirst = dd_CopyGenerators(first);
gsl_vector *vertex = gsl_vector_alloc(P1->H->size2);
gsl_vector_set_zero(vertex);
int is_included;
bool is_subset = true;
for(int i = 0; i<verticesFirst->rowsize;i++){
double valueFirst0 = dd_get_d(verticesFirst->matrix[i][0]);
if(valueFirst0 == 1){
for(int j = 0; j<vertex->size; j++){
double valueFirstj = dd_get_d(verticesFirst->matrix[i][j+1]);
gsl_vector_set(vertex,(size_t)j, valueFirstj);
}
is_included = polytope_check_state(P2,vertex);
if(!is_included){
is_subset = false;
break;
}
}
}
gsl_vector_free(vertex);
dd_FreePolyhedra(first);
dd_FreeMatrix(verticesFirst);
return is_subset;
};
/**
* Unite inequalities of P1 and P2 in new polytope and remove redundancies
*/
polytope * polytope_unite_inequalities(polytope *P1,
polytope *P2)
{
polytope *united = polytope_alloc(P1->H->size1+P2->H->size1,P1->H->size2);
//Unite H
gsl_matrix_set_zero(united->H);
gsl_matrix_view H_P1 = gsl_matrix_submatrix(united->H, 0, 0, P1->H->size1, P1->H->size2);
gsl_matrix_memcpy(&H_P1.matrix, P1->H);
gsl_matrix_view H_P2 = gsl_matrix_submatrix(united->H, P1->H->size1, 0, P2->H->size1, P2->H->size2);
gsl_matrix_memcpy(&H_P2.matrix, P2->H);
//Unite G
gsl_vector_set_zero(united->G);
gsl_vector_view G_P1 = gsl_vector_subvector(united->G, 0, P1->G->size);
gsl_vector_memcpy(&G_P1.vector, P1->G);
gsl_vector_view G_P2 = gsl_vector_subvector(united->G, P1->G->size,P2->G->size);
gsl_vector_memcpy(&G_P2.vector, P2->G);
polytope * return_polytope = polytope_minimize(united);
polytope_free(united);
return return_polytope;
};
/**
* Project original polytope (in cdd format) to the first n dimensions
*/
polytope * polytope_projection(polytope * original,
size_t n)
{
dd_ErrorType err;
dd_PolyhedraPtr orig_cdd = polytope_to_cdd(original, &err);
dd_PolyhedraPtr new_cdd = NULL;
cdd_projection(&orig_cdd, &new_cdd, n, &err);
polytope * new = cdd_to_polytope(&new_cdd);
dd_FreePolyhedra(orig_cdd);
dd_FreePolyhedra(new_cdd);
return new;
};
polytope * polytope_linear_transform(polytope *original,
gsl_matrix *scale){
dd_ErrorType err = dd_NoError;
dd_PolyhedraPtr orig_cdd = polytope_to_cdd(original, &err);
dd_MatrixPtr vertices = dd_CopyGenerators(orig_cdd);
dd_MatrixPtr transformed_vertices = dd_CreateMatrix(1, scale->size1+1);
dd_MatrixPtr transformed_vertex = dd_CreateMatrix(1, scale->size1+1);
bool new_matrix_started = false;
gsl_vector *vertex = gsl_vector_alloc((vertices->colsize - 1));
gsl_vector *scaled_vertex = gsl_vector_alloc(scale->size1);
gsl_vector_set_zero(vertex);
gsl_vector_set_zero(scaled_vertex);
for(int i = 0; i<vertices->rowsize; i++) {
//Check whether row represents ray or vertex
double is_vertex = dd_get_d(vertices->matrix[i][0]);
if (is_vertex == 1) {
for (size_t j = 1; j < vertices->colsize; j++) {
double value = dd_get_d(vertices->matrix[i][j]);
gsl_vector_set(vertex, j-1, value);
}
gsl_blas_dgemv(CblasNoTrans, 1.0, scale, vertex, 0.0, scaled_vertex);
if (new_matrix_started) {
dd_set_d(transformed_vertex->matrix[0][0], 1);
for (size_t j = 0; j < scaled_vertex->size; j++) {
dd_set_d(transformed_vertex->matrix[0][j + 1], gsl_vector_get(scaled_vertex, j));
}
dd_MatrixAppendTo(&transformed_vertices, transformed_vertex);
} else {
dd_set_d(transformed_vertices->matrix[0][0], 1);
for (size_t j = 0; j < scaled_vertex->size; j++) {
dd_set_d(transformed_vertices->matrix[0][j + 1], gsl_vector_get(scaled_vertex, j));
}
new_matrix_started = true;
}
}
}
transformed_vertices->representation = dd_Generator;
dd_PolyhedraPtr transformed_cdd = dd_DDMatrix2Poly(transformed_vertices, &err);
polytope *transformed = cdd_to_polytope(&transformed_cdd);
//Clean up
dd_FreeMatrix(transformed_vertex);
dd_FreeMatrix(transformed_vertices);
dd_FreePolyhedra(orig_cdd);
dd_FreePolyhedra(transformed_cdd);
dd_FreeMatrix(vertices);
gsl_vector_free(vertex);
gsl_vector_free(scaled_vertex);
return transformed;
};
/**
* Remove redundancies from gsl polytope inequalities
*/
polytope * polytope_minimize(polytope *original)
{
dd_ErrorType err = dd_NoError;
dd_MatrixPtr min_matrix;
dd_PolyhedraPtr cdd_original = polytope_to_cdd(original, &err);
dd_PolyhedraPtr cdd_minimized = cdd_minimize(&cdd_original, &err);
min_matrix = dd_CopyInequalities(cdd_minimized);
polytope * minimized = cdd_to_polytope(&cdd_minimized);
dd_FreeMatrix(min_matrix);
dd_FreePolyhedra(cdd_original);
dd_FreePolyhedra(cdd_minimized);
return minimized;
};
/**
* Compute Minkowski sum of two polytopes
*/
polytope * polytope_minkowski(polytope *P1,
polytope *P2)
{
dd_ErrorType err = dd_NoError;
dd_PolyhedraPtr A = polytope_to_cdd(P1, &err);
dd_PolyhedraPtr B = polytope_to_cdd(P2, &err);
dd_PolyhedraPtr C = cdd_minkowski(A,B);
polytope * returnPolytope = cdd_to_polytope(&C);
dd_FreePolyhedra(A);
dd_FreePolyhedra(B);
dd_FreePolyhedra(C);
return returnPolytope;
};
/**
* Compute Pontryagin difference C = A-B s.t.:
* A-B = {c \in A-B| c+b \in A, \forall b \in B}
*/
polytope * polytope_pontryagin(polytope* A,
polytope* B)
{
dd_ErrorType err;
dd_MatrixPtr verticesA, verticesB;
//create cddPoly A,B
dd_PolyhedraPtr cddA = polytope_to_cdd(A, &err);
dd_PolyhedraPtr cddB = polytope_to_cdd(B, &err);
polytope *C = NULL;
verticesA = dd_CopyGenerators(cddA);
verticesB = dd_CopyGenerators(cddB);
for(int i = 0; i<verticesB->rowsize; i++){
//Check whether row represents ray or vertex
double value_B0 = dd_get_d(verticesB->matrix[i][0]);
if(value_B0 == 1){
dd_MatrixPtr tempA;
//A-b (where b is the vertex)
tempA = dd_CreateMatrix(verticesA->rowsize,verticesA->colsize);
//each vertex of A displaced by b
for(int j = 0; j<verticesA->rowsize; j++){
double value_A0 = dd_get_d(verticesA->matrix[j][0]);
if(value_A0 == 1){
dd_set_d(tempA->matrix[j][0], 1);
for(int k = 1; k<verticesA->colsize; k++){
double value_Ak = dd_get_d(verticesA->matrix[j][k]);
double value_Bk = dd_get_d(verticesB->matrix[i][k]);
dd_set_d(tempA->matrix[j][k],(value_Ak-value_Bk));
}
}else{
dd_set_d(tempA->matrix[j][0], 0);
for(int k = 1; k<verticesA->colsize; k++){
double value_Ak = dd_get_d(verticesA->matrix[j][k]);
dd_set_d(tempA->matrix[j][k],(value_Ak));
}
}
}
dd_PolyhedraPtr cdd_temp;
tempA->representation = dd_Generator;
cdd_temp = dd_DDMatrix2Poly(tempA, &err);
polytope *tempC = cdd_to_polytope(&cdd_temp);
dd_FreePolyhedra(cdd_temp);
if(C == NULL){
C = polytope_alloc(tempC->H->size1,tempC->H->size2);
gsl_matrix_memcpy(C->H,tempC->H);
gsl_vector_memcpy(C->G,tempC->G);
polytope_free(tempC);
}else{
polytope *copyC = C;
C = polytope_unite_inequalities(copyC, tempC);
polytope_free(tempC);
polytope_free(copyC);
}
dd_FreeMatrix(tempA);
}
}
dd_FreeMatrix(verticesA);
dd_FreeMatrix(verticesB);
dd_FreePolyhedra(cddA);
dd_FreePolyhedra(cddB);
return C;
};
/**
* Set up constraints in quadratic problem for GUROBI
*/
int polytope_to_constraints_gurobi(polytope *constraints,
GRBmodel *model,
size_t N)
{
int error = 0;
double constraint_val[N];
int ind[N];
for(size_t i = 0; i < constraints->H->size1;i++){
char constraint_name[5];
sprintf(constraint_name, "c_%d", (int)i);
for(size_t j = 0; j < N;j++){
ind[j] = (int)j;
constraint_val[j] = gsl_matrix_get(constraints->H,i,j);
}
error = GRBaddconstr(model, (int)N, ind, constraint_val, GRB_LESS_EQUAL, gsl_vector_get(constraints->G,i), constraint_name);
if(error){
return error;
}
}
return error;
};
/**
* Generate a polytope representing a scaled unit cube
*/
dd_PolyhedraPtr cdd_scaled_unit_cube(double scale,
int dimensions)
{
dd_MatrixPtr constraints;
dd_PolyhedraPtr cube = NULL;
dd_ErrorType err = dd_NoError;
constraints = dd_CreateMatrix(dimensions*2,dimensions+1);
for(int i = 0; i<(dimensions); i++){
dd_set_d(constraints->matrix[2*i][0],(scale*0.5));
dd_set_d(constraints->matrix[2*i][i+1],-1);
dd_set_d(constraints->matrix[2*i+1][0],(scale*0.5));
dd_set_d(constraints->matrix[2*i+1][i+1],1);
}
constraints->representation=dd_Inequality;
cube = dd_DDMatrix2Poly(constraints, &err);
dd_FreeMatrix(constraints);
return cube;
};
/**
* Project original polytope (in cdd format) to the first n dimensions
*/
void cdd_projection(dd_PolyhedraPtr *original,
dd_PolyhedraPtr *new,
size_t n,
dd_ErrorType *err)
{
dd_MatrixPtr full=NULL,projected=NULL;
full = dd_CopyInequalities(*original);
dd_colrange j,d;
dd_rowset redset,impl_linset;
dd_colset delset;
dd_rowindex newpos;
d=full->colsize;
set_initialize(&delset, d);
for (j=n+1; j<d; j++){
set_addelem(delset, j+1);
}
projected=dd_BlockElimination(full, delset, err);
dd_MatrixCanonicalize(&projected,&impl_linset,&redset,&newpos,err);
dd_FreeMatrix(full);
projected->representation = dd_Inequality;
*new = dd_DDMatrix2Poly(projected, err);
dd_FreeMatrix(projected);
set_free(delset);
set_free(redset);
set_free(impl_linset);
free(newpos);
};
/**
* Remove redundancies from cdd polytope inequalities
*/
dd_PolyhedraPtr cdd_minimize(dd_PolyhedraPtr *original,
dd_ErrorType *err)
{
dd_rowset redset,impl_linset;
dd_rowindex newpos;
dd_MatrixPtr full=NULL;
full = dd_CopyInequalities(*original);
dd_MatrixCanonicalize(&full,&impl_linset,&redset,&newpos,err);
full->representation = dd_Inequality;
dd_PolyhedraPtr new = dd_DDMatrix2Poly(full, err);
dd_FreeMatrix(full);
set_free(redset);
set_free(impl_linset);
free(newpos);
return new;
}; | {
"alphanum_fraction": 0.6184629611,
"avg_line_length": 31.2958199357,
"ext": "c",
"hexsha": "28c77a4f009be1dd20d8f75b66d48391e6b08504",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2018-10-06T12:58:52.000Z",
"max_forks_repo_forks_event_min_datetime": "2018-10-06T12:58:52.000Z",
"max_forks_repo_head_hexsha": "56cf4d58a9d7e17b6f6aebe6de8d5a1231035671",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "shaesaert/TuLiPXML",
"max_forks_repo_path": "Interface/Cimple/cimple_polytope_library.c",
"max_issues_count": 2,
"max_issues_repo_head_hexsha": "56cf4d58a9d7e17b6f6aebe6de8d5a1231035671",
"max_issues_repo_issues_event_max_datetime": "2018-08-21T09:50:09.000Z",
"max_issues_repo_issues_event_min_datetime": "2017-10-03T18:54:08.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "shaesaert/TuLiPXML",
"max_issues_repo_path": "Interface/Cimple/cimple_polytope_library.c",
"max_line_length": 132,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "56cf4d58a9d7e17b6f6aebe6de8d5a1231035671",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "shaesaert/TuLiPXML",
"max_stars_repo_path": "Interface/Cimple/cimple_polytope_library.c",
"max_stars_repo_stars_event_max_datetime": "2021-05-28T23:44:28.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-05-28T23:44:28.000Z",
"num_tokens": 5106,
"size": 19466
} |
/* -*- Mode: C; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
#pragma once
#include <mcbp/protocol/status.h>
#include <stdint.h>
#include <gsl/gsl>
struct EngineIface;
/**
* Callback for any function producing stats.
*
* @param key the stat's key
* @param klen length of the key
* @param val the stat's value in an ascii form (e.g. text form of a number)
* @param vlen length of the value
* @param cookie magic callback cookie
*/
typedef void (*ADD_STAT)(const char* key,
const uint16_t klen,
const char* val,
const uint32_t vlen,
gsl::not_null<const void*> cookie);
/**
* Callback for adding a response backet
* @param key The key to put in the response
* @param keylen The length of the key
* @param ext The data to put in the extended field in the response
* @param extlen The number of bytes in the ext field
* @param body The data body
* @param bodylen The number of bytes in the body
* @param datatype This is currently not used and should be set to 0
* @param status The status code of the return packet (see in protocol_binary
* for the legal values)
* @param cas The cas to put in the return packet
* @param cookie The cookie provided by the frontend
* @return true if return message was successfully created, false if an
* error occured that prevented the message from being sent
*/
typedef bool (*ADD_RESPONSE)(const void* key,
uint16_t keylen,
const void* ext,
uint8_t extlen,
const void* body,
uint32_t bodylen,
uint8_t datatype,
cb::mcbp::Status status,
uint64_t cas,
const void* cookie);
| {
"alphanum_fraction": 0.5816959669,
"avg_line_length": 37.9215686275,
"ext": "h",
"hexsha": "cf3629d2e3dd2b53a46304dc004e61130d5c3f90",
"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": "24d4546220f3181678d7eadedc68b4ea088d3538",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "t3rm1n4l/kv_engine",
"max_forks_repo_path": "include/memcached/engine_common.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "24d4546220f3181678d7eadedc68b4ea088d3538",
"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": "t3rm1n4l/kv_engine",
"max_issues_repo_path": "include/memcached/engine_common.h",
"max_line_length": 77,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "24d4546220f3181678d7eadedc68b4ea088d3538",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "t3rm1n4l/kv_engine",
"max_stars_repo_path": "include/memcached/engine_common.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 418,
"size": 1934
} |
/*
Copyright [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 _MCAS_NUPM_ARENA_
#define _MCAS_NUPM_ARENA_
#include <nupm/region_descriptor.h>
#include <common/logging.h>
#include <common/string_view.h>
#include <gsl/pointers> /* not_null */
#include <sys/uio.h> /* ::iovec */
#include <cstddef>
#include <vector>
namespace nupm
{
struct registry_memory_mapped;
struct space_registered;
}
struct arena
: private common::log_source
{
using region_descriptor = nupm::region_descriptor;
using registry_memory_mapped = nupm::registry_memory_mapped;
using space_registered = nupm::space_registered;
using string_view = common::string_view;
arena(const common::log_source &ls) : common::log_source(ls) {}
virtual ~arena() {}
virtual void debug_dump() const = 0;
virtual region_descriptor region_get(const string_view &id) = 0;
virtual region_descriptor region_create(const string_view &id, gsl::not_null<registry_memory_mapped *> mh, std::size_t size) = 0;
virtual void region_resize(gsl::not_null<space_registered *> mh, std::size_t size) = 0;
/* It is unknown whether region_erase may be used on an open region.
* arena_fs assumes that it may, just as ::unlink can be used against
* an open file.
*/
virtual void region_erase(const string_view &id, gsl::not_null<registry_memory_mapped *> mh) = 0;
virtual std::size_t get_max_available() = 0;
virtual bool is_file_backed() const = 0;
protected:
using common::log_source::debug_level;
};
#endif
| {
"alphanum_fraction": 0.7470414201,
"avg_line_length": 34.9655172414,
"ext": "h",
"hexsha": "d6fe918b5219d968a2fac91bbd94c9025f955f78",
"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": "a6af06bc278993fb3ffe780f230d2396b2287c26",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "moshik1/mcas",
"max_forks_repo_path": "src/lib/libnupm/src/arena.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "a6af06bc278993fb3ffe780f230d2396b2287c26",
"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": "moshik1/mcas",
"max_issues_repo_path": "src/lib/libnupm/src/arena.h",
"max_line_length": 131,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "a6af06bc278993fb3ffe780f230d2396b2287c26",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "moshik1/mcas",
"max_stars_repo_path": "src/lib/libnupm/src/arena.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 502,
"size": 2028
} |
#include <stdlib.h>
#include <gsl/vector/gsl_vector.h>
#include <gsl/gsl_errno.h>
#define BASE_DOUBLE
#include <gsl/templates_on.h>
#include <gsl/vector/prop_source.c>
#include <gsl/templates_off.h>
#undef BASE_DOUBLE
| {
"alphanum_fraction": 0.7612612613,
"avg_line_length": 17.0769230769,
"ext": "c",
"hexsha": "96e9400c201baae4e6a76a1b42d62d99b176c54a",
"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/prop.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "58778f148e65749e1dfc443043e9fc054ca3ff4d",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "MontyThibault/centre-of-mass-awareness",
"max_issues_repo_path": "Cartwheel/cartwheel-3d/gsl/vector/prop.c",
"max_line_length": 35,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "58778f148e65749e1dfc443043e9fc054ca3ff4d",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "MontyThibault/centre-of-mass-awareness",
"max_stars_repo_path": "Cartwheel/cartwheel-3d/gsl/vector/prop.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 58,
"size": 222
} |
#ifndef _density_constructions_h
#define _density_constructions_h
#include "montecarlo.h"
#include "two_body_analytical.h"
#include <float.h>
#include <limits.h>
#include <gsl/gsl_sort.h>
int r_final_uniform(double x, double y, double vz, double mu, double t_peri ,int N, double a, char * directory);
int Vector_distribution(double x, double y, double vz, double mu, double t_peri, int N, double a, char * directory);
typedef struct{
double v[6];
} state_Vector;
int Save_Vector_Index(state_Vector *state_vector, int index, int N, char* directory);
int Chi_Square_Euler(double x, double y, double vz, double mu, int N, char * directory, size_t Npoints);
#endif // ! _density_constructions_h
| {
"alphanum_fraction": 0.7517630465,
"avg_line_length": 30.8260869565,
"ext": "h",
"hexsha": "6a08b3ca4c4d5c9571dd27766d39975e32cc65c1",
"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": "02710dba80121b0757c7abcd7000499578002d26",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "Andresfgomez970/Astrocomputationalphysics",
"max_forks_repo_path": "Project/densities_constructions.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "02710dba80121b0757c7abcd7000499578002d26",
"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": "Andresfgomez970/Astrocomputationalphysics",
"max_issues_repo_path": "Project/densities_constructions.h",
"max_line_length": 117,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "02710dba80121b0757c7abcd7000499578002d26",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "Andresfgomez970/Astrocomputationalphysics",
"max_stars_repo_path": "Project/densities_constructions.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 188,
"size": 709
} |
/**
*
* @file qwrapper_ztrtri.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 Julien Langou
* @author Henricus Bouwmeester
* @author Mathieu Faverge
* @date 2010-11-15
* @precisions normal z -> c d s
*
**/
#include <lapacke.h>
#include "common.h"
/***************************************************************************//**
*
**/
void QUARK_CORE_ztrtri(Quark *quark, Quark_Task_Flags *task_flags,
PLASMA_enum uplo, PLASMA_enum diag,
int n, int nb,
PLASMA_Complex64_t *A, int lda,
PLASMA_sequence *sequence, PLASMA_request *request,
int iinfo)
{
QUARK_Insert_Task(
quark, CORE_ztrtri_quark, task_flags,
sizeof(PLASMA_enum), &uplo, VALUE,
sizeof(PLASMA_enum), &diag, VALUE,
sizeof(int), &n, VALUE,
sizeof(PLASMA_Complex64_t)*nb*nb, A, INOUT,
sizeof(int), &lda, VALUE,
sizeof(PLASMA_sequence*), &sequence, VALUE,
sizeof(PLASMA_request*), &request, VALUE,
sizeof(int), &iinfo, VALUE,
0);
}
/***************************************************************************//**
*
**/
#if defined(PLASMA_HAVE_WEAK)
#pragma weak CORE_ztrtri_quark = PCORE_ztrtri_quark
#define CORE_ztrtri_quark PCORE_ztrtri_quark
#endif
void CORE_ztrtri_quark(Quark *quark)
{
PLASMA_enum uplo;
PLASMA_enum diag;
int N;
PLASMA_Complex64_t *A;
int LDA;
PLASMA_sequence *sequence;
PLASMA_request *request;
int iinfo;
int info;
quark_unpack_args_8(quark, uplo, diag, N, A, LDA, sequence, request, iinfo);
info = LAPACKE_ztrtri_work(
LAPACK_COL_MAJOR,
lapack_const(uplo), lapack_const(diag),
N, A, LDA);
if ((sequence->status == PLASMA_SUCCESS) && (info > 0))
plasma_sequence_flush(quark, sequence, request, iinfo + info);
}
| {
"alphanum_fraction": 0.5366515837,
"avg_line_length": 31.1267605634,
"ext": "c",
"hexsha": "30c6d25b58526bc1069be3d462ac3ce2bb29866b",
"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_ztrtri.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_ztrtri.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_ztrtri.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 584,
"size": 2210
} |
#include <stdio.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_monte.h> //Relevant GSL functions for VEGAS numerical integration
#include <gsl/gsl_monte_vegas.h>
#include "timer.c" //Timing Functions
#include "plotfun.h" //Automatic Plotting Function
void timer_start (void);
double timer_stop (void);
void pfun(double x[], double y[], double u[], double v[], int points);
extern double g (double *t, size_t dim, void *params);
struct my_params {double r;};
double f (double x1, double x2, double y1, double y2, double z1, double z2, double r);
double dipole_approx (double r);
int main (void)
{
int np = 20;
double distance[20];
double vegas_energy[20];
double res, err;
double error1[20];
double error2[20];
size_t dim = 6;
double xl[] = {0., 0., 0., 0., 0., 0.};
double xu[] = {1., 1., 1., 1., 1., 1.};
gsl_rng *r = gsl_rng_alloc (gsl_rng_taus2);
unsigned long seed = 1UL;
gsl_rng_set (r, seed);
size_t calls = 1000000;
double dd = (4.-1.001)/np;
timer_start();
for(int q = 0; q < np; q++)
{
distance[q] = 1.001 + q*dd;
}
//VEGAS Integration
for(int j = 0; j < np; j++)
{
struct my_params params = {distance[j]};
gsl_monte_function G = { &g, dim , ¶ms};
gsl_monte_vegas_state *sv = gsl_monte_vegas_alloc (dim);
gsl_monte_vegas_init (sv);
gsl_monte_vegas_integrate (&G, xl, xu, dim, calls / 10, r, sv, &res, &err);
do
{
gsl_monte_vegas_integrate (&G, xl, xu, dim, calls, r, sv, &res, &err);
fflush (stdout);
}
while (fabs (gsl_monte_vegas_chisq (sv) - 1.0) > 0.2);
vegas_energy[j] = fabs(res);
error1[j] = fabs(err);
gsl_monte_vegas_free (sv);
}
double t1 = timer_stop();
gsl_rng_free (r);
int iterations = 1000000;
int tot = 20;
double x1, x2, y1, y2, z1, z2;
double handmade_energy[20];
gsl_rng *zed = gsl_rng_alloc (gsl_rng_taus2);
gsl_rng_set (zed, seed);
timer_start();
//Handmade Monte Carlo Integrator
for(int j = 0; j < 20.; j++)
{
double d = 1.001 + j * dd;
double ival = 0;
double i2val = 0;
for(int z = 0; z < 16; z++)
{
double value = 0;
for (int q = 0; q < iterations; q++)
{
x1 = gsl_rng_uniform(zed);
x2 = gsl_rng_uniform(zed);
y1 = gsl_rng_uniform(zed);
y2 = gsl_rng_uniform(zed);
z1 = gsl_rng_uniform(zed);
z2 = gsl_rng_uniform(zed);
value += f(x1, x2, y1, y2, z1, z2, d);
}
ival += value;
i2val += value*value;
}
double result = ival/iterations/16;
double result2 = i2val/iterations/iterations/16;
error2[j] = sqrt(fabs((result*result)-result2));
handmade_energy[j] = fabs(result);
}
double t2 = timer_stop();
//Dipole Approximation
double dipole_energy[20];
for(int u = 0; u < tot; u++)
{
dipole_energy[u] = dipole_approx(distance[u]);
}
printf("Distance VEGAS Error Handmade Error Dipole\n");
for(int w = 0; w < tot; w++)
{
printf("%.6f %.6f %.6f %.6f %.6f %.6f\n", distance[w], vegas_energy[w], error1[w], handmade_energy[w], error2[w], dipole_energy[w]);
}
printf("Time for VEGAS: %.6f\nTime for HANDMADE: %.6f\n", t1, t2);
//Plots the 3 methods vs. distance automatically (function in plotfun.h)
pfun(distance, vegas_energy, handmade_energy, dipole_energy, 20);
return 0;
}
double g (double *t, size_t dim, void *params)
{
double dist2, delta;
double rho1, rho2;
int sdim = ((int) dim)/2;
double r = *((double *) params);
dist2 = 0.;
for (int i = 0; i < sdim; i++)
{
delta = t[i] - t[i + sdim];
if (i == 0)
{
delta += r;
}
dist2 += delta*delta;
}
double norm = 512./(9.*(M_PI - 2.));
rho1 = norm * atan(2*(t[0]-.5))*pow(sin(M_PI*t[1]),4.)*pow(sin(M_PI*t[2]),4.);
rho2 = norm * atan(2*(t[3]-.5))*pow(sin(M_PI*t[4]),4.)*pow(sin(M_PI*t[5]),4.);
return rho1*rho2/sqrt(dist2);
}
double f (double x1, double x2, double y1, double y2, double z1, double z2, double r)
{
double dist2;
double rho1, rho2;
dist2 = (x1 - x2 + r)*(x1 - x2 + r) + (y1 - y2)*(y1 - y2) + (z1 - z2)*(z1 - z2);
double norm = 512./(9.*(M_PI - 2.));
rho1 = norm * atan(2*(x1-.5))*pow(sin(M_PI*y1),4.)*pow(sin(M_PI*z1),4.);
rho2 = norm * atan(2*(x2-.5))*pow(sin(M_PI*y2),4.)*pow(sin(M_PI*z2),4.);
return rho1*rho2/sqrt(dist2);
}
double dipole_approx (double r)
{
return 2/(r*r*r);
}
| {
"alphanum_fraction": 0.5764549679,
"avg_line_length": 23.1743589744,
"ext": "c",
"hexsha": "1799d58dd8df82bce5d4c9ac81843e144a58a193",
"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": "d13fa38b59a96c79e21f9775cf18398a30128578",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "connor-occhialini/fin2",
"max_forks_repo_path": "main.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "d13fa38b59a96c79e21f9775cf18398a30128578",
"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": "connor-occhialini/fin2",
"max_issues_repo_path": "main.c",
"max_line_length": 145,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "d13fa38b59a96c79e21f9775cf18398a30128578",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "connor-occhialini/fin2",
"max_stars_repo_path": "main.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1572,
"size": 4519
} |
// Copyright (c) 2005 - 2011 Marc de Kamps
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
// * Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software
// without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY
// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
// USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// If you use this software in work leading to a scientific publication, you should cite
// the 'currently valid reference', which can be found at http://miind.sourceforge.net
#ifndef _CODE_LIBS_NUMTOOLSLIB_RANDOMGENERATOR_INCLUDE_GUARD
#define _CODE_LIBS_NUMTOOLSLIB_RANDOMGENERATOR_INCLUDE_GUARD
#include <vector>
#include <iostream>
#include <gsl/gsl_rng.h>
#include "ChangeSeedException.h"
using std::vector;
namespace NumtoolsLib
{
//! Global default seed for RandomGenerator
const long GLOBAL_SEED = 9875987L;
//! This class contains a specific uniform random generator that can be used to generate other distributions
//! GaussianDistribution and UniformDistribution, for example, use this random generator, which gsl_rng_mt19937
//! of the Gnu Scietific Library. This class can be used to modify the seed and to keep track of the number
//! of draws made by the generator. Distributions use one copy of this class.
class RandomGenerator
{
public:
RandomGenerator(long lseed = GLOBAL_SEED);
~RandomGenerator();
double NextSampleValue();
private:
RandomGenerator(const RandomGenerator&);
RandomGenerator& operator=(const RandomGenerator&);
double Ran2(long*);
// new, uniformly distributed value
void AddOne (){ std::cout << "zopa" << std::endl; ++_number_of_draws; }
long _initial_seed; // initial seed value
unsigned long _number_of_draws; // number of calls to NextSampleValue
gsl_rng* _p_generator;
}; // end of RandomGenerator
//! Global Random Generator
extern RandomGenerator GLOBAL_RANDOM_GENERATOR;
inline double RandomGenerator::NextSampleValue()
{
AddOne();
return gsl_rng_uniform(_p_generator);
}
} // end of Numtools
#endif // include guard
| {
"alphanum_fraction": 0.7621914509,
"avg_line_length": 36.5054945055,
"ext": "h",
"hexsha": "a3362dadded7ff6e219c55ac08b0877bf467d49f",
"lang": "C",
"max_forks_count": 9,
"max_forks_repo_forks_event_max_datetime": "2022-03-08T12:18:18.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-09-14T20:52:07.000Z",
"max_forks_repo_head_hexsha": "4b321c62c2bd27eb0d5d8336a16a9e840ba63856",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "dekamps/miind",
"max_forks_repo_path": "libs/NumtoolsLib/RandomGenerator.h",
"max_issues_count": 41,
"max_issues_repo_head_hexsha": "4b321c62c2bd27eb0d5d8336a16a9e840ba63856",
"max_issues_repo_issues_event_max_datetime": "2022-03-21T16:20:37.000Z",
"max_issues_repo_issues_event_min_datetime": "2015-08-25T07:50:55.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "dekamps/miind",
"max_issues_repo_path": "libs/NumtoolsLib/RandomGenerator.h",
"max_line_length": 163,
"max_stars_count": 13,
"max_stars_repo_head_hexsha": "4b321c62c2bd27eb0d5d8336a16a9e840ba63856",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "dekamps/miind",
"max_stars_repo_path": "libs/NumtoolsLib/RandomGenerator.h",
"max_stars_repo_stars_event_max_datetime": "2022-03-22T20:26:47.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-09-15T17:28:25.000Z",
"num_tokens": 716,
"size": 3322
} |
/*
* Copyright 2008-2016 Jan Gasthaus
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Functions for computing and tabulating the generalized stirling numbers
* of type (-1,-d,0).
*
*/
#ifndef STIRLING_H_
#define STIRLING_H_
#include <cmath>
#include <vector>
#include <string>
#include <iostream>
#include <cassert>
#include <gsl/gsl_sf_gamma.h>
namespace gatsby { namespace libplump {
typedef std::vector<double> d_vec;
typedef std::vector<d_vec> d_vec_vec;
/**
* computes log(exp(a) + exp(b)) while avoiding numerical
* instabilities.
*/
inline double fast_logsumexp(double a, double b) {
if (a>b) {
return log(1+exp(b-a)) + a;
} else {
return log(1+exp(a-b)) + b;
}
}
/**
* computes log(exp(a) - exp(b)) while avoiding numerical
* instabilities.
*/
inline double fast_logminusexp(double a, double b) {
if (a>b) {
return log(1-exp(b-a)) + a;
} else {
return log(1-exp(a-b)) + b;
}
}
/**
* Compute S_d(c,t) recursively by directly applying the recursion
* S_d(c,t) = S_d(c-1,t-1) + (c-1 - t*d)S_d(c-1,t)
*
* This does a _lot_ of duplicate work and should only be used for debugging!
*/
double gen_stirling_recursive(double d, int c, int t);
/**
* Compute S_d(c,t) recursively in log space by directly applying the recursion
* S_d(c,t) = S_d(c-1,t-1) + (c-1 - t*d)S_d(c-1,t)
*
* This does a _lot_ of duplicate work and should only be used for debugging!
*/
double log_gen_stirling_recursive(double d, int c, int t);
/**
* Compute S_d(c,t) directly in log space using the recursion
* S_d(c,t) = S_d(c-1,t-1) + (c-1 - t*d)S_d(c-1,t)
*/
double log_gen_stirling_direct(double d, int c, int t);
double log_gen_stirling_ratio(double d, int c, int t);
d_vec_vec log_gen_stirling_table(double d, int c);
void log_gen_stirling_table_extend(double d, int c, d_vec_vec& table);
double log_get_stirling_from_table(d_vec_vec& table, int c, int t);
class stirling_generator_recompute_log {
public:
stirling_generator_recompute_log(double d, int c, int t);
double ratio(int c, int t);
static std::string statsToString();
private:
double d;
};
class stirling_generator_fast_log {
public:
stirling_generator_fast_log(double d, int c, int t);
double get(int c, int t);
double ratio(int c, int t);
static std::string statsToString();
private:
void incC();
void decC();
double d;
int current_c;
d_vec row, col, prev_col;
};
/**
* Class to encapsulate the generation of ratios of stirling numbers
* for removing customers from restaurants.
*
* One of these objects should be constructed for each restaurant,
* providing the current number of tables, and the total number of customers.
*/
class stirling_generator_full_log {
public:
stirling_generator_full_log(double d, int c, int t);
double ratio(int c, int t);
double getLog(int c, int t);
static std::string statsToString();
private:
static int global_c_max, num_ratio_calls, num_extends, num_construct;
d_vec_vec table;
int c_max;
double d;
};
inline double log_get_stirling_from_table(d_vec_vec& table, int c, int t) {
// c and t must be non-negative
assert(c >= 0 && t>= 0);
if ((c == 1 && t == 1) || (c == 0 && t == 0))
return 0;
if (c == 0 || t == 0)
return -INFINITY;
if (t > c)
return -INFINITY;
if(c == t)
return 0;
if (t > (int)table.size() || (c - t) > (int)table[t-1].size()) {
std::cout<< c << ", " << t << std::endl;
}
return table[t-1][c-t-1];
}
inline double log_stirling_asymptotic(double d, int c, int t) {
return gsl_sf_lngamma(c)
- gsl_sf_lngamma(1 - d)
- gsl_sf_lngamma(t)
- (t-1) * log(d)
- d * log(c);
}
// class log_gen_stirling_table {
// private:
// std::vector<std::vector<double> > table;
// size_t c_cur, t_cur;
//
// /*
// * Grow the arrays to the required size.
// */
// void _grow(size_t c_max, size_t t_max) {
// for(int i=t_cur;i<t_max;i++) {
// std::vector<double> tmp(c_cur,0);
// table.push_back(std::vector<double>());
// }
// }
//
// /*
// * Tabulate up to the specified limits
// */
// void _tabulate(size_t c_max, size_t t_max) {
// for t in xrange(1,max_t):
// for c in xrange(t,max_c):
// a[c,t] = a[c-1,t-1] + (c-1-d*t)*a[c-1,t]
//
// }
//
// public:
// double d;
// gen_stirling_table(double d) : d(d), c_cur(0), t_cur(0) {}
//
// };
}} // namespace gatsby::libplump
#endif /* STIRLING_H_ */
| {
"alphanum_fraction": 0.6216890595,
"avg_line_length": 23.1555555556,
"ext": "h",
"hexsha": "616b2cfcc2314f3ba7a0a87faab731593c08c07f",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2016-11-20T00:56:17.000Z",
"max_forks_repo_forks_event_min_datetime": "2016-11-17T19:19:37.000Z",
"max_forks_repo_head_hexsha": "18e5911575e3c9a054482b08d637dc91b0cd05b9",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "jgasthaus/libPLUMP",
"max_forks_repo_path": "src/libplump/stirling.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "18e5911575e3c9a054482b08d637dc91b0cd05b9",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "jgasthaus/libPLUMP",
"max_issues_repo_path": "src/libplump/stirling.h",
"max_line_length": 79,
"max_stars_count": 13,
"max_stars_repo_head_hexsha": "18e5911575e3c9a054482b08d637dc91b0cd05b9",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "jgasthaus/libPLUMP",
"max_stars_repo_path": "src/libplump/stirling.h",
"max_stars_repo_stars_event_max_datetime": "2021-02-16T03:50:37.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-02-02T21:46:58.000Z",
"num_tokens": 1461,
"size": 5210
} |
#ifndef __MMA__
#define __MMA__
#include <petsc.h>
/* -----------------------------------------------------------------------------
Authors: Niels Aage
Copyright (C) 2013-2020,
This MMA implementation is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This Module is distributed in the hope that it will be useful,implementation
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this Module; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
-------------------------------------------------------------------------- */
class MMA {
public:
// Construct using defaults subproblem penalization
MMA(PetscInt n, PetscInt m, Vec x);
// User defined subproblem penalization
MMA(PetscInt n, PetscInt m, Vec x, PetscScalar* a, PetscScalar* c, PetscScalar* d);
// Initialize with restart from itr
MMA(PetscInt n, PetscInt m, PetscInt itr, Vec xo1, Vec xo2, Vec U, Vec L);
// Initialize with restart and specify subproblem parameters
MMA(PetscInt n, PetscInt m, PetscInt itr, Vec xo1, Vec xo2, Vec U, Vec L, PetscScalar* a, PetscScalar* c,
PetscScalar* d);
// Destructor
~MMA();
// Set and solve a subproblem: return new xval
PetscErrorCode Update(Vec xval, Vec dfdx, PetscScalar* gx, Vec* dgdx, Vec xmin, Vec xmax);
// Return necessary data for possible restart
PetscErrorCode Restart(Vec xo1, Vec xo2, Vec U, Vec L);
// Set the aggresivity of the moving asymptotes
PetscErrorCode SetAsymptotes(PetscScalar init, PetscScalar decrease, PetscScalar increase);
// do/don't add convexity approx to constraints: default=false
PetscErrorCode ConstraintModification(PetscBool conMod) {
constraintModification = conMod;
return 0;
};
// val=0: default, val=1: increase robustness, i.e
// control the spacing between L < alp < x < beta < U,
PetscErrorCode SetRobustAsymptotesType(PetscInt val);
// Sets outer movelimits on all primal design variables
// This is often requires to prevent the solver from oscilating
PetscErrorCode SetOuterMovelimit(PetscScalar Xmin, PetscScalar Xmax, PetscScalar movelim, Vec x, Vec xmin,
Vec xmax);
// Return KKT residual norms (norm2 and normInf)
PetscErrorCode KKTresidual(Vec xval, Vec dfdx, PetscScalar* gx, Vec* dgdx, Vec xmin, Vec xmax, PetscScalar* norm2,
PetscScalar* normInf);
// Inf norm on diff between two vectors: SHOULD NOT BE HERE - USE BASIC
// PETSc!!!!!
PetscScalar DesignChange(Vec x, Vec xold);
private:
// Set up the MMA subproblem based on old x's and xval
PetscErrorCode GenSub(Vec xval, Vec dfdx, PetscScalar* gx, Vec* dgdx, Vec xmin, Vec xmax);
// Interior point solver for the subproblem
PetscErrorCode SolveDIP(Vec xval);
// Compute primal vars based on dual solution
PetscErrorCode XYZofLAMBDA(Vec x);
// Dual gradient
PetscErrorCode DualGrad(Vec x);
// Dual Hessian
PetscErrorCode DualHess(Vec x);
// Dual line search
PetscErrorCode DualLineSearch();
// Dual residual
PetscScalar DualResidual(Vec x, PetscScalar epsi);
// Problem size and iteration counter
PetscInt n, m, k;
// "speed-control" for the asymptotes
PetscScalar asyminit, asymdec, asyminc;
// do/don't add convexity constraint approximation in subproblem
PetscBool constraintModification; // default = FALSE
// Bool specifying if non lin constraints are included or not
PetscBool NonLinConstraints;
// 0: (default) span between alp L x U beta,
// 1: increase the span for further robustness
PetscInt RobustAsymptotesType;
// Local vectors: penalty numbers for subproblem
PetscScalar *a, *c, *d;
// Local vectors: elastic variables
PetscScalar* y;
PetscScalar z;
// Local vectors: Lagrange multipliers:
PetscScalar *lam, *mu, *s;
// Global: Asymptotes, bounds, objective approx., constraint approx.
Vec L, U, alpha, beta, p0, q0, *pij, *qij;
// Local: subproblem constant terms, dual gradient, dual hessian
PetscScalar *b, *grad, *Hess;
// Global: Old design variables
Vec xo1, xo2;
// Math helpers
PetscErrorCode Factorize(PetscScalar* K, PetscInt nn);
PetscErrorCode Solve(PetscScalar* K, PetscScalar* x, PetscInt nn);
PetscScalar Min(PetscScalar d1, PetscScalar d2);
PetscScalar Max(PetscScalar d1, PetscScalar d2);
PetscInt Min(PetscInt d1, PetscInt d2);
PetscInt Max(PetscInt d1, PetscInt d2);
PetscScalar Abs(PetscScalar d1);
};
#endif
| {
"alphanum_fraction": 0.6802452047,
"avg_line_length": 37.4592592593,
"ext": "h",
"hexsha": "1f24e3b266e175bcf3a7a75a46b69ccfbf301420",
"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": "7f590a4cc5b0d17080ec9acb9896c3739791dad1",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "TTitscher/BitJug",
"max_forks_repo_path": "py_mma/MMA.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "7f590a4cc5b0d17080ec9acb9896c3739791dad1",
"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": "TTitscher/BitJug",
"max_issues_repo_path": "py_mma/MMA.h",
"max_line_length": 118,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "7f590a4cc5b0d17080ec9acb9896c3739791dad1",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "TTitscher/BitJug",
"max_stars_repo_path": "py_mma/MMA.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1284,
"size": 5057
} |
#pragma once
#include <vector>
#include <gsl/gsl>
#include "halley/utils/utils.h"
namespace Halley
{
class NetworkPacketBase
{
public:
size_t copyTo(gsl::span<gsl::byte> dst) const;
size_t getSize() const;
gsl::span<const gsl::byte> getBytes() const;
NetworkPacketBase(NetworkPacketBase&& other) = delete;
NetworkPacketBase& operator=(NetworkPacketBase&& other) = delete;
protected:
NetworkPacketBase();
NetworkPacketBase(gsl::span<const gsl::byte> data, size_t prePadding);
size_t dataStart;
std::vector<gsl::byte> data;
};
class OutboundNetworkPacket : public NetworkPacketBase
{
public:
OutboundNetworkPacket(const OutboundNetworkPacket& other);
explicit OutboundNetworkPacket(OutboundNetworkPacket&& other) noexcept;
explicit OutboundNetworkPacket(gsl::span<const gsl::byte> data);
explicit OutboundNetworkPacket(const Bytes& data);
void addHeader(gsl::span<const gsl::byte> src);
template <typename T>
void addHeader(const T& h)
{
addHeader(gsl::as_bytes(gsl::span<const T>(&h, 1)));
}
OutboundNetworkPacket& operator=(OutboundNetworkPacket&& other) noexcept;
};
class InboundNetworkPacket : public NetworkPacketBase
{
public:
InboundNetworkPacket();
explicit InboundNetworkPacket(InboundNetworkPacket&& other);
explicit InboundNetworkPacket(gsl::span<const gsl::byte> data);
void extractHeader(gsl::span<gsl::byte> dst);
template <typename T>
void extractHeader(T& h)
{
extractHeader(gsl::as_writeable_bytes(gsl::span<T>(&h, 1)));
}
InboundNetworkPacket& operator=(InboundNetworkPacket&& other);
};
}
| {
"alphanum_fraction": 0.7410658307,
"avg_line_length": 25.7258064516,
"ext": "h",
"hexsha": "eba42788a5c886ee17d496040c8a2c7a6810b8e5",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "fc4f153956cc34d7fa02b76850e22183b8e30e25",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "sunhay/halley",
"max_forks_repo_path": "src/engine/net/include/halley/net/connection/network_packet.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "fc4f153956cc34d7fa02b76850e22183b8e30e25",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "sunhay/halley",
"max_issues_repo_path": "src/engine/net/include/halley/net/connection/network_packet.h",
"max_line_length": 75,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "fc4f153956cc34d7fa02b76850e22183b8e30e25",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "sunhay/halley",
"max_stars_repo_path": "src/engine/net/include/halley/net/connection/network_packet.h",
"max_stars_repo_stars_event_max_datetime": "2019-11-27T20:23:45.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-11-27T20:23:45.000Z",
"num_tokens": 431,
"size": 1595
} |
#include <config.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_sum.h>
gsl_sum_levin_u_workspace *
gsl_sum_levin_u_alloc (size_t n)
{
gsl_sum_levin_u_workspace * w;
if (n == 0)
{
GSL_ERROR_VAL ("length n must be positive integer", GSL_EDOM, 0);
}
w = (gsl_sum_levin_u_workspace *) malloc(sizeof(gsl_sum_levin_u_workspace));
if (w == NULL)
{
GSL_ERROR_VAL ("failed to allocate struct", GSL_ENOMEM, 0);
}
w->q_num = (double *) malloc (n * sizeof (double));
if (w->q_num == NULL)
{
free(w) ; /* error in constructor, prevent memory leak */
GSL_ERROR_VAL ("failed to allocate space for q_num", GSL_ENOMEM, 0);
}
w->q_den = (double *) malloc (n * sizeof (double));
if (w->q_den == NULL)
{
free (w->q_num);
free (w) ; /* error in constructor, prevent memory leak */
GSL_ERROR_VAL ("failed to allocate space for q_den", GSL_ENOMEM, 0);
}
w->dq_num = (double *) malloc (n * n * sizeof (double));
if (w->dq_num == NULL)
{
free (w->q_den);
free (w->q_num);
free(w) ; /* error in constructor, prevent memory leak */
GSL_ERROR_VAL ("failed to allocate space for dq_num", GSL_ENOMEM, 0);
}
w->dq_den = (double *) malloc (n * n * sizeof (double));
if (w->dq_den == NULL)
{
free (w->dq_num);
free (w->q_den);
free (w->q_num);
free (w) ; /* error in constructor, prevent memory leak */
GSL_ERROR_VAL ("failed to allocate space for dq_den", GSL_ENOMEM, 0);
}
w->dsum = (double *) malloc (n * sizeof (double));
if (w->dsum == NULL)
{
free (w->dq_den);
free (w->dq_num);
free (w->q_den);
free (w->q_num);
free (w) ; /* error in constructor, prevent memory leak */
GSL_ERROR_VAL ("failed to allocate space for dsum", GSL_ENOMEM, 0);
}
w->size = n;
w->terms_used = 0;
w->sum_plain = 0;
return w;
}
void
gsl_sum_levin_u_free (gsl_sum_levin_u_workspace * w)
{
free (w->dsum);
free (w->dq_den);
free (w->dq_num);
free (w->q_den);
free (w->q_num);
free (w);
}
| {
"alphanum_fraction": 0.5893446488,
"avg_line_length": 22.3263157895,
"ext": "c",
"hexsha": "3f7052b30d2294b6c6c849b04616239aa9e24ca7",
"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/sum/work_u.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/sum/work_u.c",
"max_line_length": 78,
"max_stars_count": 64,
"max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "manggoguy/parsec-modified",
"max_stars_repo_path": "pkgs/libs/gsl/src/sum/work_u.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": 661,
"size": 2121
} |
#include <stdio.h> /* standard I/O routines */
#include <stdlib.h>
#include <string.h>
#include <stdio.h> /* standard I/O routines */
#include <omp.h>
#include <mpi.h>
#include <sys/time.h>
#include "utils.h"
//#include <cblas.h>
#ifdef PAPI
#include "cscs_papi.h"
#endif
#define NN 8000;
#define NTIMES 10
#if 0
extern "C"{
void dgemm_ (char *transa,
char *transb,
int *m, int *n, int *k,
double *alpha, double *A, int *lda,
double *B, int *ldb,
double *beta, double *C, int *ldc) ;
}
#endif
double mysecond()
{
struct timeval tp;
struct timezone tzp;
int i;
i = gettimeofday(&tp,&tzp);
return ( (double) tp.tv_sec + (double) tp.tv_usec * 1.e-6 );
}
int main (int argc, char *argv[])
{
int N = NN;
int M = NN;
int K = NN;
int ii;
/* Find out my identity in the default communicator */
int Ncpu = 0;
if ( argc == 2 )
{
N = atoi(argv[1]);
M = N;
K = N;
}
double alpha = 1.;
double beta = -1.;
int lda = M;
int ldb = K;
int ldc = M;
int size_A = K*lda;
int size_B = N*ldb;
int size_C = N*ldc;
double *A = (double*) malloc(sizeof(double)*size_A);
if (A == 0) printf("Could not allocate A.\n");
double *B = (double*) malloc(sizeof(double)*size_B);
if (B == 0) printf("Could not allocate B.\n");
double *C = (double*) malloc(sizeof(double)*size_C);
if (C == 0) printf("Could not allocate C.\n");
double *Cg = (double*) malloc(sizeof(double)*size_C);
if (Cg == 0) printf("Could not allocate Cg.\n");
fill(A, size_A, 31.);
eye (B, ldb, N );
fill(C, size_C, 31.);
fill(Cg, size_C, 31.);
int t;
int nthreads, tid, procs, maxthreads, inpar, dynamic, nested;
char transa = 'n';
char transb = 'n';
/* Get environment information */
#ifdef _OPENMP
procs = omp_get_num_procs();
nthreads = omp_get_num_threads();
maxthreads = omp_get_max_threads();
inpar = omp_in_parallel();
dynamic = omp_get_dynamic();
nested = omp_get_nested();
/* Print environment information */
printf("Number of processors = %d\n", procs);
printf("Number of threads = %d\n", nthreads);
printf("Max threads = %d\n", maxthreads);
printf("In parallel? = %d\n", inpar);
printf("Dynamic threads enabled? = %d\n", dynamic);
printf("Nested parallelism supported? = %d\n", nested);
#endif
double otime = 0.;
otime -= mysecond();
for (ii = 0; ii < NTIMES; ++ii)
dgemm_(&transa, &transb,
&M, &N, &K,
&alpha, A, &lda,
B, &ldb,
&beta, Cg, &ldc);
otime += mysecond();
otime /= NTIMES;
printf("Size = %d, Gflops Max: %f Min: %f Avg: %f\n", N, 2.*M*N*K/otime/1e9, 2.*M*N*K/otime/1e9, 2.*M*N*K/otime/1e9);
free(A);
free(B);
free(C);
free(Cg);
exit(0);
}
| {
"alphanum_fraction": 0.5793251974,
"avg_line_length": 20.3357664234,
"ext": "c",
"hexsha": "025e7cc5ef284fca6ae84b4801f77a83e82abf01",
"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": "0bf3a81214f094dbddec868d3d133986b31f4b01",
"max_forks_repo_licenses": [
"BSD-2-Clause"
],
"max_forks_repo_name": "vkeller/math-454",
"max_forks_repo_path": "Exos/Serie03/Dgemm/dgemm.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "0bf3a81214f094dbddec868d3d133986b31f4b01",
"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": "vkeller/math-454",
"max_issues_repo_path": "Exos/Serie03/Dgemm/dgemm.c",
"max_line_length": 121,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "0bf3a81214f094dbddec868d3d133986b31f4b01",
"max_stars_repo_licenses": [
"BSD-2-Clause"
],
"max_stars_repo_name": "vkeller/math-454",
"max_stars_repo_path": "Exos/Serie03/Dgemm/dgemm.c",
"max_stars_repo_stars_event_max_datetime": "2021-05-19T13:31:49.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-05-19T13:31:49.000Z",
"num_tokens": 897,
"size": 2786
} |
//g++ open_blas_measure.cpp -I /include/ -L/lib/ -lopenblas -lpthread
// #include <cblas.h>
#include <stdio.h>
#include <iostream>
#ifndef OPEN_BLAS
#define OPEN_BLAS
extern "C"{
int dgemm_(char *, char *, int *, int *, int *, double *, double *, int *,
double *, int *, double *, double *, int *);
}
/* Assuming row major order of matrices.
This function is used to call open_blas multiplication. It takes the paramters given and
puts the result of multiplication in *C.
To be used in multiplication by open_blas
*/
void call_open_blas(double *A, int rowA, double *B, int colB, int commonSide, double *C) {
char t = 'N';
double alpha =1.0;
double beta = 0.0;
dgemm_(&t, &t, &rowA, &colB, &commonSide, &alpha, A, &rowA, B, &commonSide, &beta, C, &rowA);
}
#endif
| {
"alphanum_fraction": 0.643296433,
"avg_line_length": 28.0344827586,
"ext": "h",
"hexsha": "5a4b63a7a91935de508d7a5b9e203f3cf6db13b3",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2019-03-05T14:55:56.000Z",
"max_forks_repo_forks_event_min_datetime": "2019-03-05T14:55:56.000Z",
"max_forks_repo_head_hexsha": "cdbc51bfd990a94b0829873a94800404cf871d45",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "jaymalk/A-Small-Image-Processing-Library",
"max_forks_repo_path": "Subtask 2/include/impl/OBM.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "cdbc51bfd990a94b0829873a94800404cf871d45",
"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": "jaymalk/A-Small-Image-Processing-Library",
"max_issues_repo_path": "Subtask 2/include/impl/OBM.h",
"max_line_length": 97,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "cdbc51bfd990a94b0829873a94800404cf871d45",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "jaymalk/A-Small-Image-Processing-Library",
"max_stars_repo_path": "Subtask 2/include/impl/OBM.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 244,
"size": 813
} |
/* specfunc/gsl_sf_fermi_dirac.h
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
/* Author: G. Jungman */
#ifndef __GSL_SF_FERMI_DIRAC_H__
#define __GSL_SF_FERMI_DIRAC_H__
#if !defined( GSL_FUN )
# if !defined( GSL_DLL )
# define GSL_FUN extern
# elif defined( BUILD_GSL_DLL )
# define GSL_FUN extern __declspec(dllexport)
# else
# define GSL_FUN extern __declspec(dllimport)
# endif
#endif
#include <gsl/gsl_sf_result.h>
#undef __BEGIN_DECLS
#undef __END_DECLS
#ifdef __cplusplus
# define __BEGIN_DECLS extern "C" {
# define __END_DECLS }
#else
# define __BEGIN_DECLS /* empty */
# define __END_DECLS /* empty */
#endif
__BEGIN_DECLS
/* Complete Fermi-Dirac Integrals:
*
* F_j(x) := 1/Gamma[j+1] Integral[ t^j /(Exp[t-x] + 1), {t,0,Infinity}]
*
*
* Incomplete Fermi-Dirac Integrals:
*
* F_j(x,b) := 1/Gamma[j+1] Integral[ t^j /(Exp[t-x] + 1), {t,b,Infinity}]
*/
/* Complete integral F_{-1}(x) = e^x / (1 + e^x)
*
* exceptions: GSL_EUNDRFLW
*/
GSL_FUN int gsl_sf_fermi_dirac_m1_e(const double x, gsl_sf_result * result);
GSL_FUN double gsl_sf_fermi_dirac_m1(const double x);
/* Complete integral F_0(x) = ln(1 + e^x)
*
* exceptions: GSL_EUNDRFLW
*/
GSL_FUN int gsl_sf_fermi_dirac_0_e(const double x, gsl_sf_result * result);
GSL_FUN double gsl_sf_fermi_dirac_0(const double x);
/* Complete integral F_1(x)
*
* exceptions: GSL_EUNDRFLW, GSL_EOVRFLW
*/
GSL_FUN int gsl_sf_fermi_dirac_1_e(const double x, gsl_sf_result * result);
GSL_FUN double gsl_sf_fermi_dirac_1(const double x);
/* Complete integral F_2(x)
*
* exceptions: GSL_EUNDRFLW, GSL_EOVRFLW
*/
GSL_FUN int gsl_sf_fermi_dirac_2_e(const double x, gsl_sf_result * result);
GSL_FUN double gsl_sf_fermi_dirac_2(const double x);
/* Complete integral F_j(x)
* for integer j
*
* exceptions: GSL_EUNDRFLW, GSL_EOVRFLW
*/
GSL_FUN int gsl_sf_fermi_dirac_int_e(const int j, const double x, gsl_sf_result * result);
GSL_FUN double gsl_sf_fermi_dirac_int(const int j, const double x);
/* Complete integral F_{-1/2}(x)
*
* exceptions: GSL_EUNDRFLW, GSL_EOVRFLW
*/
GSL_FUN int gsl_sf_fermi_dirac_mhalf_e(const double x, gsl_sf_result * result);
GSL_FUN double gsl_sf_fermi_dirac_mhalf(const double x);
/* Complete integral F_{1/2}(x)
*
* exceptions: GSL_EUNDRFLW, GSL_EOVRFLW
*/
GSL_FUN int gsl_sf_fermi_dirac_half_e(const double x, gsl_sf_result * result);
GSL_FUN double gsl_sf_fermi_dirac_half(const double x);
/* Complete integral F_{3/2}(x)
*
* exceptions: GSL_EUNDRFLW, GSL_EOVRFLW
*/
GSL_FUN int gsl_sf_fermi_dirac_3half_e(const double x, gsl_sf_result * result);
GSL_FUN double gsl_sf_fermi_dirac_3half(const double x);
/* Incomplete integral F_0(x,b) = ln(1 + e^(b-x)) - (b-x)
*
* exceptions: GSL_EUNDRFLW, GSL_EDOM
*/
GSL_FUN int gsl_sf_fermi_dirac_inc_0_e(const double x, const double b, gsl_sf_result * result);
GSL_FUN double gsl_sf_fermi_dirac_inc_0(const double x, const double b);
__END_DECLS
#endif /* __GSL_SF_FERMI_DIRAC_H__ */
| {
"alphanum_fraction": 0.6996943454,
"avg_line_length": 28.6569343066,
"ext": "h",
"hexsha": "049c1daacd5437340518cb63eb26d54d22a0f4e6",
"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": "099b66cb1285d19955e953f916ec6c12c68f2242",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "berkus/music-cs",
"max_forks_repo_path": "deps/include/gsl/gsl_sf_fermi_dirac.h",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "099b66cb1285d19955e953f916ec6c12c68f2242",
"max_issues_repo_issues_event_max_datetime": "2021-01-13T16:28:48.000Z",
"max_issues_repo_issues_event_min_datetime": "2021-01-11T01:08:01.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "berkus/music-cs",
"max_issues_repo_path": "deps/include/gsl/gsl_sf_fermi_dirac.h",
"max_line_length": 100,
"max_stars_count": 2,
"max_stars_repo_head_hexsha": "099b66cb1285d19955e953f916ec6c12c68f2242",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "berkus/music-cs",
"max_stars_repo_path": "deps/include/gsl/gsl_sf_fermi_dirac.h",
"max_stars_repo_stars_event_max_datetime": "2021-01-09T16:18:47.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-01-09T05:48:44.000Z",
"num_tokens": 1175,
"size": 3926
} |
/*
* -----------------------------------------------------------------
* thrm_lib.h
* Thermochemistry Library
* Version: 2.0
* Last Update: Nov 3, 2019
*
* Programmer: Americo Barbosa da Cunha Junior
* americo.cunhajr@gmail.com
* -----------------------------------------------------------------
* Copyright (c) 2010-2019, Americo Barbosa da Cunha Junior
* All rights reserved.
* -----------------------------------------------------------------
* This is the header file for THRM_LIB module, a computational
* library with thermochemistry routines.
* -----------------------------------------------------------------
*/
#ifndef __THRM_LIB_H__
#define __THRM_LIB_H__
#include <gsl/gsl_vector.h>
#include <nvector/nvector_serial.h>
/*
* ------------------------------------------------------------
* Types: struct thrm_struct, thrm_wrk
* ------------------------------------------------------------
* This structure contains fields of the Chemkin workspace.
*
* last update: Mar 5, 2009
* ------------------------------------------------------------
*/
typedef struct thrm_struct
{
int *iwk; /* integer work vector */
double *rwk; /* real work vector */
char *cwk; /* character work vector */
int leniwk; /* iwk dimension */
int lenrwk; /* rwk dimension */
int lencwk; /* cwk dimension */
int n_e; /* # of chemical elements */
int n_s; /* # of elementary species */
int n_r; /* # of elementary reactions */
} thrm_wrk;
/*------------------------------------------------------------*/
/*
*------------------------------------------------------------
* function prototypes
*------------------------------------------------------------
*/
void thrm_title();
void thrm_mech(int n_e,
int n_s,
int n_r,
char *mech);
int thrm_input(int *steps,
double *t0,
double *delta_t,
double *Tmax,
double *Tmin,
double *tol);
thrm_wrk* thrm_alloc();
void thrm_free(void **thrm_bl);
int thrm_init(thrm_wrk *thrm);
void thrm_composition(thrm_wrk *thrm,
gsl_vector *phi);
void thrm_page_heading0(FILE *file);
double thrm_h2T(thrm_wrk *thrm,
double *phi,
double Tmax,
double Tmin,
double tol);
void thrm_temp_meanvar(int Np,
gsl_vector **ps,
thrm_wrk *thrm,
double Tmax,
double Tmin,
double tol,
double *mean,
double *var);
double thrm_rrsum(gsl_vector *phi);
double thrm_mfsum(gsl_vector *phi);
int thrm_mfsign(gsl_vector *phi);
int thrm_eqs(double t,
N_Vector phi,
N_Vector Rphi,
void *thrm_data);
int thrm_eqs2(double t,
N_Vector phi,
N_Vector Sphi,
void *thrm_data);
#endif /* __THRM_LIB_H__ */
| {
"alphanum_fraction": 0.442043222,
"avg_line_length": 24.8292682927,
"ext": "h",
"hexsha": "a7bcf3b3210073993b5a6973cbf2c697ef413967",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2021-12-30T01:44:13.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-11-15T03:57:44.000Z",
"max_forks_repo_head_hexsha": "35b67f798c1c33118c028691f42b98ba06220eeb",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "americocunhajr/CRFlowLib",
"max_forks_repo_path": "CRFlowLib-2.0/include/thrm_lib.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "35b67f798c1c33118c028691f42b98ba06220eeb",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "americocunhajr/CRFlowLib",
"max_issues_repo_path": "CRFlowLib-2.0/include/thrm_lib.h",
"max_line_length": 67,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "35b67f798c1c33118c028691f42b98ba06220eeb",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "americocunhajr/CRFlowLib",
"max_stars_repo_path": "CRFlowLib-2.0/include/thrm_lib.h",
"max_stars_repo_stars_event_max_datetime": "2020-12-29T12:56:14.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-12-29T12:56:14.000Z",
"num_tokens": 656,
"size": 3054
} |
#ifndef VolViz_AtomicCache_h
#define VolViz_AtomicCache_h
#include <gsl/gsl>
#include <atomic>
#pragma clang diagnostic ignored "-Wpadded"
namespace VolViz {
/// Class represening a cached value, that has a very basic thread safety.
/// The thread saftey is as follows: the cache'd value must not be accessed
/// from different threads (at least without external synchronization), but
/// the cache can be marked dirty from any thread.
/// A typical use case is to cache a derived property that depends on some
/// shared (beween threads) resources (e.g. AtomicWrapper<> objects) and the
/// cached value is frequently accessed but the dependent resource does not
/// change so often.
///
/// @tparam T the cached type
template <class T> class AtomicCache {
public:
/// Creates a dirty cache with the given fetch operation.
/// @tparam FetchOp the fetch operation. It takes no parameter and returns an
/// object convertible to T.
/// @note At construction no fetch operation is issued.
template <class FetchOp>
AtomicCache(FetchOp fetchOperation)
: fetchOperation_(fetchOperation) {
Expects(fetchOperation_);
dirtyFlag_.clear();
}
/// Marks the cache as dirty, i.e. a fetch operations must be perfomed on the
/// next read.
/// @note this method is thread safe.
inline void markAsDirty() noexcept { dirtyFlag_.clear(); }
/// Returns the cached object. If the cache is dirty, a fetch operations is
/// performed first.
/// @note This method must not be called from more than one thread.
inline operator T const &() const noexcept {
if (dirtyFlag_.test_and_set()) return value_;
Expects(fetchOperation_);
value_ = std::move(fetchOperation_());
return value_;
}
private:
/// The caced value
mutable T value_;
/// The atomic dirty flag
mutable std::atomic_flag dirtyFlag_;
/// The fetch operation
std::function<T()> const fetchOperation_;
};
} // namespace VolViz
#endif // VolViz_AtomicCache_h
| {
"alphanum_fraction": 0.7200606367,
"avg_line_length": 30.4461538462,
"ext": "h",
"hexsha": "09d3afdb60cab7659d4260811effd7cc330501b2",
"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": "e79f36563d908d9ba1bd71c3e760792521dd5e7a",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "ithron/VolViz",
"max_forks_repo_path": "include/VolViz/src/AtomicCache.h",
"max_issues_count": 17,
"max_issues_repo_head_hexsha": "e79f36563d908d9ba1bd71c3e760792521dd5e7a",
"max_issues_repo_issues_event_max_datetime": "2016-10-28T12:23:59.000Z",
"max_issues_repo_issues_event_min_datetime": "2016-06-09T07:38:52.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "ithron/VolViz",
"max_issues_repo_path": "include/VolViz/src/AtomicCache.h",
"max_line_length": 79,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "e79f36563d908d9ba1bd71c3e760792521dd5e7a",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "ithron/VolViz",
"max_stars_repo_path": "include/VolViz/src/AtomicCache.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 465,
"size": 1979
} |
/* linalg/householdercomplex.c
*
* Copyright (C) 2001 Brian Gough
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <config.h>
#include <stdlib.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_blas.h>
#include <gsl/gsl_complex_math.h>
#include "gsl_linalg.h"
gsl_complex
gsl_linalg_complex_householder_transform (gsl_vector_complex * v)
{
/* replace v[0:n-1] with a householder vector (v[0:n-1]) and
coefficient tau that annihilate v[1:n-1] */
const size_t n = v->size ;
if (n == 1)
{
gsl_complex alpha = gsl_vector_complex_get (v, 0) ;
double absa = gsl_complex_abs (alpha);
double beta_r = - (GSL_REAL(alpha) >= 0 ? +1 : -1) * absa ;
gsl_complex tau;
GSL_REAL(tau) = (beta_r - GSL_REAL(alpha)) / beta_r ;
GSL_IMAG(tau) = - GSL_IMAG(alpha) / beta_r ;
{
gsl_complex beta = gsl_complex_rect (beta_r, 0.0);
gsl_vector_complex_set (v, 0, beta) ;
}
return tau;
}
else
{
gsl_complex tau ;
double beta_r;
gsl_vector_complex_view x = gsl_vector_complex_subvector (v, 1, n - 1) ;
gsl_complex alpha = gsl_vector_complex_get (v, 0) ;
double absa = gsl_complex_abs (alpha);
double xnorm = gsl_blas_dznrm2 (&x.vector);
if (xnorm == 0 && GSL_IMAG(alpha) == 0)
{
gsl_complex zero = gsl_complex_rect(0.0, 0.0);
return zero; /* tau = 0 */
}
beta_r = - (GSL_REAL(alpha) >= 0 ? +1 : -1) * hypot(absa, xnorm) ;
GSL_REAL(tau) = (beta_r - GSL_REAL(alpha)) / beta_r ;
GSL_IMAG(tau) = - GSL_IMAG(alpha) / beta_r ;
{
gsl_complex amb = gsl_complex_sub_real(alpha, beta_r);
gsl_complex s = gsl_complex_inverse(amb);
gsl_blas_zscal (s, &x.vector);
}
{
gsl_complex beta = gsl_complex_rect (beta_r, 0.0);
gsl_vector_complex_set (v, 0, beta) ;
}
return tau;
}
}
int
gsl_linalg_complex_householder_hm (gsl_complex tau, const gsl_vector_complex * v, gsl_matrix_complex * A)
{
/* applies a householder transformation v,tau to matrix m */
size_t i, j;
if (GSL_REAL(tau) == 0.0 && GSL_IMAG(tau) == 0.0)
{
return GSL_SUCCESS;
}
/* w = (v' A)^T */
for (j = 0; j < A->size2; j++)
{
gsl_complex tauwj;
gsl_complex wj = gsl_matrix_complex_get(A,0,j);
for (i = 1; i < A->size1; i++) /* note, computed for v(0) = 1 above */
{
gsl_complex Aij = gsl_matrix_complex_get(A,i,j);
gsl_complex vi = gsl_vector_complex_get(v,i);
gsl_complex Av = gsl_complex_mul (Aij, gsl_complex_conjugate(vi));
wj = gsl_complex_add (wj, Av);
}
tauwj = gsl_complex_mul (tau, wj);
/* A = A - v w^T */
{
gsl_complex A0j = gsl_matrix_complex_get (A, 0, j);
gsl_complex Atw = gsl_complex_sub (A0j, tauwj);
/* store A0j - tau * wj */
gsl_matrix_complex_set (A, 0, j, Atw);
}
for (i = 1; i < A->size1; i++)
{
gsl_complex vi = gsl_vector_complex_get (v, i);
gsl_complex tauvw = gsl_complex_mul(vi, tauwj);
gsl_complex Aij = gsl_matrix_complex_get (A, i, j);
gsl_complex Atwv = gsl_complex_sub (Aij, tauvw);
/* store Aij - tau * vi * wj */
gsl_matrix_complex_set (A, i, j, Atwv);
}
}
return GSL_SUCCESS;
}
| {
"alphanum_fraction": 0.6025917927,
"avg_line_length": 29.3450704225,
"ext": "c",
"hexsha": "9f0f5e91cdac3746c9714dbe61ab4b1230b6c383",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2015-10-02T01:32:59.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-10-02T01:32:59.000Z",
"max_forks_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "ICML14MoMCompare/spectral-learn",
"max_forks_repo_path": "code/em/treba/gsl-1.0/linalg/householdercomplex.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "ICML14MoMCompare/spectral-learn",
"max_issues_repo_path": "code/em/treba/gsl-1.0/linalg/householdercomplex.c",
"max_line_length": 105,
"max_stars_count": 14,
"max_stars_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "ICML14MoMCompare/spectral-learn",
"max_stars_repo_path": "code/em/treba/gsl-1.0/linalg/householdercomplex.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": 1211,
"size": 4167
} |
/*
*
* A cross-platform way of providing access to gsl_ieee_env_setup
* from Fortran on any system MITgcm runs on currently.
*/
#ifdef USE_GSL_IEEE
#include <gsl/gsl_math.h>
#include <gsl/gsl_ieee_utils.h>
void fgsl_ieee_env_setup ()
{
gsl_ieee_env_setup ();
}
void fgsl_ieee_env_setup_ ()
{
gsl_ieee_env_setup ();
}
void fgsl_ieee_env_setup__ ()
{
gsl_ieee_env_setup ();
}
void FGSL_IEEE_ENV_SETUP ()
{
gsl_ieee_env_setup ();
}
#endif
| {
"alphanum_fraction": 0.7252747253,
"avg_line_length": 14.6774193548,
"ext": "c",
"hexsha": "0e3157ddfd5da21dfca2158d055587a62f1b2169",
"lang": "C",
"max_forks_count": 209,
"max_forks_repo_forks_event_max_datetime": "2022-03-30T06:24:43.000Z",
"max_forks_repo_forks_event_min_datetime": "2018-01-31T20:58:49.000Z",
"max_forks_repo_head_hexsha": "9e3cbd9dd7b61dbea201517a5c776fc7748f82af",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "ElizabethYankovsky/MITgcm",
"max_forks_repo_path": "eesupp/src/gsl_ieee_env.c",
"max_issues_count": 580,
"max_issues_repo_head_hexsha": "9e3cbd9dd7b61dbea201517a5c776fc7748f82af",
"max_issues_repo_issues_event_max_datetime": "2022-03-31T22:43:30.000Z",
"max_issues_repo_issues_event_min_datetime": "2018-01-31T21:38:08.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "ElizabethYankovsky/MITgcm",
"max_issues_repo_path": "eesupp/src/gsl_ieee_env.c",
"max_line_length": 66,
"max_stars_count": 247,
"max_stars_repo_head_hexsha": "9e3cbd9dd7b61dbea201517a5c776fc7748f82af",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "ElizabethYankovsky/MITgcm",
"max_stars_repo_path": "eesupp/src/gsl_ieee_env.c",
"max_stars_repo_stars_event_max_datetime": "2022-03-31T08:55:55.000Z",
"max_stars_repo_stars_event_min_datetime": "2018-02-07T08:33:08.000Z",
"num_tokens": 132,
"size": 455
} |
#ifndef __SphericalHarmonicsInterpolationFilter_h
#define __SphericalHarmonicsInterpolationFilter_h
// this code builds on the ImageToImageFilter.
#include "itkImageToImageFilter.h"
#include "itkImage.h"
// Legendre code from GNU Scientific Library
// #include <gsl/gsl_sf_legendre.h>
#include <string.h>
#include <math.h>
#include <vector>
#include <set>
// itk includes go here
#include <itkImage.h>
#include <itkImageFileReader.h>
#include <itkImageFileWriter.h>
#include <itkExceptionObject.h>
#include <itkMetaDataObject.h>
#include <itkNrrdImageIO.h>
#include <itkNthElementImageAdaptor.h>
#include <itkImageToVectorImageFilter.h>
#include <itkResampleImageFilter.h>
#include <itkVersion.h>
#define DIMENSION 3
#define PI 3.14159265358
namespace itk
{
/** \class SphericalHarmonicsInterpolationFilter
*
* \sa Image
*/
template <class TInputImage, class TOutputImage>
class ITK_EXPORT SphericalHarmonicsInterpolationFilter :
public ImageToImageFilter<TInputImage, TOutputImage>
{
public:
/** Extract dimension from input image. */
itkStaticConstMacro(InputImageDimension, unsigned int,
TInputImage::ImageDimension);
itkStaticConstMacro(OutputImageDimension, unsigned int,
TInputImage::ImageDimension);
/** Convenient typedefs for simplifying declarations. */
typedef TInputImage InputImageType;
typedef typename InputImageType::Pointer InputImagePointer;
typedef typename InputImageType::RegionType InputImageRegionType;
typedef typename InputImageType::PixelType InputImagePixelType; // variable sized vector of valuetype
typedef typename InputImageType::PixelType::ValueType ImageValueType; // USE THIS TO DETERMINE INDIVIDUAL
// VECTOR VALUES
typedef TOutputImage OutputImageType;
typedef typename OutputImageType::Pointer OutputImagePointer;
typedef typename OutputImageType::RegionType OutputImageRegionType;
typedef typename OutputImageType::PixelType OutputImagePixelType;
/** Standard class typedefs. */
typedef SphericalHarmonicsInterpolationFilter Self;
typedef ImageToImageFilter<InputImageType, OutputImageType> Superclass;
typedef SmartPointer<Self> Pointer;
typedef SmartPointer<const Self> ConstPointer;
/** Typedef to describe the output and input image index and size types. */
typedef typename TOutputImage::IndexType OutputImageIndexType;
typedef typename TInputImage::IndexType InputImageIndexType;
typedef typename TOutputImage::SizeType OutputImageSizeType;
typedef typename TInputImage::SizeType InputImageSizeType;
typedef InputImageSizeType SizeType;
/** Method for creation through the object factory. */
itkNewMacro(Self);
/** Run-time type information (and related methods). */
itkTypeMacro(SphericalHarmonicsInterpolationFilter, ImageToImageFilter);
// TODO:
/** Extra public functions go here */
void SetOrder(int neworder)
{
order = neworder;
};
void SetLambda(double lmbda)
{
lambda = lmbda;
};
void SetNewGradients(vnl_matrix<double> & newgrads)
{
newgvectors = newgrads; numPixelComponents = (newgrads.rows() + countBaselines() );
};
// void SetNewGradients(vnl_matrix<double> &newgrads) { newgvectors = newgrads; };
int GetBValue()
{
return bvalue;
};
int GetNumBaselines()
{
return num_baselines;
};
#ifdef ITK_USE_CONCEPT_CHECKING
/** Begin concept checking */
itkConceptMacro(SameDimensionCheck,
(Concept::SameDimension<InputImageDimension, OutputImageDimension> ) );
itkConceptMacro(InputConvertibleToOutputCheck,
(Concept::Convertible<InputImagePixelType, OutputImagePixelType> ) );
/** End concept checking */
#endif
protected:
SphericalHarmonicsInterpolationFilter()
{
// newgvectors = NULL;
newgvectors.clear();
order = -1;
bvalue = -1;
numPixelComponents = -1;
lambda = 0;
}
virtual ~SphericalHarmonicsInterpolationFilter()
{
}
void PrintSelf(std::ostream& os, Indent indent) const;
void GenerateOutputInformation();
void GenerateInputRequestedRegion() throw (InvalidRequestedRegionError);
void GenerateData();
private:
SphericalHarmonicsInterpolationFilter(const Self &); // purposely not implemented
void operator=(const Self &); // purposely not implemented
// extra private functions go here
double factorial(int n);
int findMaxOrder(int numgvectors);
int getNumTerms(int orderval);
void cart2sph(vnl_matrix<double> & gvectors, vnl_matrix<double> & sgvectors );
double getSphericalHarmonic(int l, int m, double theta, double phi);
double getBasisMatrixValue(int curterm, double theta, double phi);
void generateSHBasisMatrix(int numterms, int numgradients, vnl_matrix<double> & sgradients,
vnl_matrix<double> & basismat);
int countBaselines();
// extra private variables go here
vnl_matrix<double> newgvectors;
int order;
double lambda;
int bvalue;
int numPixelComponents;
int num_baselines;
std::set<int> baseline_indices;
};
} // end namespace itk
#ifndef ITK_MANUAL_INSTANTIATION
#include "SphericalHarmonicsInterpolationFilter.txx"
#endif
#endif
| {
"alphanum_fraction": 0.6966934763,
"avg_line_length": 32.1551724138,
"ext": "h",
"hexsha": "59abc942d399b88848c03a5df51164607981f1fb",
"lang": "C",
"max_forks_count": 8,
"max_forks_repo_forks_event_max_datetime": "2019-11-25T19:50:40.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-04-24T23:16:46.000Z",
"max_forks_repo_head_hexsha": "bdd4ae24c6fef1f674978dd096b1e581c134bc8f",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "BRAINSia/DTIProcessToolkit",
"max_forks_repo_path": "Applications/dwiAtlas/SphericalHarmonicsInterpolationFilter.h",
"max_issues_count": 24,
"max_issues_repo_head_hexsha": "bdd4ae24c6fef1f674978dd096b1e581c134bc8f",
"max_issues_repo_issues_event_max_datetime": "2022-02-25T22:19:51.000Z",
"max_issues_repo_issues_event_min_datetime": "2015-01-13T16:59:37.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "BRAINSia/DTIProcessToolkit",
"max_issues_repo_path": "Applications/dwiAtlas/SphericalHarmonicsInterpolationFilter.h",
"max_line_length": 117,
"max_stars_count": 5,
"max_stars_repo_head_hexsha": "bdd4ae24c6fef1f674978dd096b1e581c134bc8f",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "BRAINSia/DTIProcessToolkit",
"max_stars_repo_path": "Applications/dwiAtlas/SphericalHarmonicsInterpolationFilter.h",
"max_stars_repo_stars_event_max_datetime": "2021-02-09T03:02:54.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-11-08T08:44:23.000Z",
"num_tokens": 1283,
"size": 5595
} |
/***************************************************************************
* Copyright (C) 2007 by Mikhail Zaslavskiy *
* *
* *
* 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 GRAPH_H
#define GRAPH_H
#include <iostream>
#include "rpc.h"
#include <math.h>
#include <gsl/gsl_blas.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_permutation.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
#include <gsl/gsl_linalg.h>
#include <vector>
/**
Graph class, it implements graph matching algorithms
@author Mikhail Zaslavskiy
*/
class graph : public rpc
{
public:
//class constructor
graph(std::string fconfig="config.txt");
graph(graph & _graph);
const graph & operator =(graph &);
//load graph routine
int load_graph(std::string fgraph,char ftype='A',char cformat='D',std::string fvertexlst_name="");
//adjacency matrix control
const gsl_matrix* get_adjmatrix(){return gm_A;};
int set_adjmatrix(const gsl_matrix* _gm_A);
gsl_matrix* get_descmatrix(char dmt);
int printout(std::string fname_out);
void printdot(std::string fname_out, gsl_matrix* =NULL);
~graph();
int add_dummy_nodes(int id);
long long getN();
protected:
gsl_matrix* gm_A;//adjacency matrix
long long N;
};
double gsl_matrix_norm(const gsl_matrix* gm,double p);
int gsl_matrix_abs(gsl_matrix* gm);
double gsl_matrix_min(gsl_matrix* gm_A,double ic);//minimum greater than ic
double gsl_vector_sum(gsl_vector* gv);
int gsl_matrix_printout(const gsl_matrix * gm,std::string,std::string);
int gsl_matrix_printout(gsl_vector * gv,std::string,std::string);
int gsl_matrix_printout(gsl_permutation * gv,std::string,std::string);
int gsl_matrix_printout(std::string sout,std::string );
double abs(double);
void gsl_matrix_sum(gsl_matrix* A,int idim,gsl_vector* gv_res);
double gsl_matrix_sum(gsl_matrix* A);
double gsl_matrix_max_abs(gsl_matrix* A);
double gsl_matrix_min_abs(gsl_matrix* gm);
//global min in [0,1]^2 of a quadratic function
void qglob_min(double a_11,double a_12,double a_22,double a_1,double a_2,double &dalpha_1,double &dalpha_2);
#endif
| {
"alphanum_fraction": 0.6088672943,
"avg_line_length": 42.2179487179,
"ext": "h",
"hexsha": "36d903e3bb0f6b023c52b575d28bc13f6de7c3a4",
"lang": "C",
"max_forks_count": 7,
"max_forks_repo_forks_event_max_datetime": "2021-08-06T01:41:25.000Z",
"max_forks_repo_forks_event_min_datetime": "2016-08-23T11:44:05.000Z",
"max_forks_repo_head_hexsha": "52f579a07d106cb241d21dbc29a2ec9e9c77b254",
"max_forks_repo_licenses": [
"Unlicense"
],
"max_forks_repo_name": "mk2510/jointGraphMatchingAndClustering",
"max_forks_repo_path": "code/clustered_setup/fgm-master/LSGMcode-master/algorithms/graphm-0.52/graph.h",
"max_issues_count": 2,
"max_issues_repo_head_hexsha": "52f579a07d106cb241d21dbc29a2ec9e9c77b254",
"max_issues_repo_issues_event_max_datetime": "2016-08-24T11:14:00.000Z",
"max_issues_repo_issues_event_min_datetime": "2015-02-20T01:53:58.000Z",
"max_issues_repo_licenses": [
"Unlicense"
],
"max_issues_repo_name": "mk2510/jointGraphMatchingAndClustering",
"max_issues_repo_path": "code/clustered_setup/fgm-master/LSGMcode-master/algorithms/graphm-0.52/graph.h",
"max_line_length": 108,
"max_stars_count": 10,
"max_stars_repo_head_hexsha": "52f579a07d106cb241d21dbc29a2ec9e9c77b254",
"max_stars_repo_licenses": [
"Unlicense"
],
"max_stars_repo_name": "mk2510/jointGraphMatchingAndClustering",
"max_stars_repo_path": "code/clustered_setup/fgm-master/LSGMcode-master/algorithms/graphm-0.52/graph.h",
"max_stars_repo_stars_event_max_datetime": "2021-02-08T21:38:55.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-08-27T14:10:38.000Z",
"num_tokens": 737,
"size": 3293
} |
/**
* @file coroutine/unix.h
* @author github.com/luncliff (luncliff@gmail.com)
* @copyright CC BY 4.0
*/
#ifndef COROUTINE_SYSTEM_WRAPPER_H
#define COROUTINE_SYSTEM_WRAPPER_H
#if !(defined(unix) || defined(__APPLE__) || defined(__FreeBSD__))
#error "expect UNIX platform for this file"
#endif
#include <sys/event.h> // for BSD kqueue
#include <gsl/gsl>
#include <coroutine/return.h>
/**
* @defgroup BSD
*/
namespace coro {
/**
* @brief RAII wrapping for kqueue file descriptor
* @ingroup BSD
*/
class kqueue_owner final {
int64_t kqfd;
public:
/**
* @brief create a fd with `kqueue`. Throw if the function fails.
* @see kqeueue
* @throw system_error
*/
kqueue_owner() noexcept(false);
/**
* @brief close the current kqueue file descriptor
*/
~kqueue_owner() noexcept;
kqueue_owner(const kqueue_owner&) = delete;
kqueue_owner(kqueue_owner&&) = delete;
kqueue_owner& operator=(const kqueue_owner&) = delete;
kqueue_owner& operator=(kqueue_owner&&) = delete;
public:
/**
* @brief bind the event to kqueue
* @param req
* @see kevent64
* @throw system_error
*
* The function is named `change` because
* the given argument is used for 'change list' fo `kqueue64`
*/
void change(kevent64_s& req) noexcept(false);
/**
* @brief fetch all events for the given kqeueue descriptor
* @param wait_time
* @param list
* @return ptrdiff_t
* @see kevent64
* @throw system_error
*
* The function is named `events` because
* the given argument is used for 'event list' fo `kqueue64`
*
* Timeout is not an error for this function
*/
ptrdiff_t events(const timespec& wait_time,
gsl::span<kevent64_s> list) noexcept(false);
public:
/**
* @brief return temporary awaitable object for given event
* @param req input for `change` operation
* @see change
*
* There is no guarantee of reusage of returned awaiter object
* When it is awaited, and `req.udata` is null(0),
* the value is set to `coroutine_handle<void>`
*
* @code
* auto read_async(kqueue_owner& kq, uint64_t fd) -> frame_t {
* kevent64_s req{.ident = fd,
* .filter = EVFILT_READ,
* .flags = EV_ADD | EV_ENABLE | EV_ONESHOT};
* co_await kq.submit(req);
* // ...
* co_await kq.submit(req);
* // ...
* }
* @endcode
*/
[[nodiscard]] auto submit(kevent64_s& req) noexcept {
class awaiter final : public suspend_always {
kqueue_owner& kq;
kevent64_s& req;
public:
constexpr awaiter(kqueue_owner& _kq, kevent64_s& _req)
: kq{_kq}, req{_req} {
}
public:
void await_suspend(coroutine_handle<void> coro) noexcept(false) {
if (req.udata == 0)
req.udata = reinterpret_cast<uint64_t>(coro.address());
return kq.change(req);
}
};
return awaiter{*this, req};
}
};
} // namespace coro
#endif // COROUTINE_SYSTEM_WRAPPER_H
| {
"alphanum_fraction": 0.5896328294,
"avg_line_length": 27.0083333333,
"ext": "h",
"hexsha": "5404743185aa6ecba3a1e4ea9e28df7e5d918cca",
"lang": "C",
"max_forks_count": 29,
"max_forks_repo_forks_event_max_datetime": "2022-02-11T17:36:55.000Z",
"max_forks_repo_forks_event_min_datetime": "2018-12-26T14:03:47.000Z",
"max_forks_repo_head_hexsha": "c90caab988f96997f5bc1bd6f1958b80524fa14a",
"max_forks_repo_licenses": [
"CC-BY-4.0"
],
"max_forks_repo_name": "lanza/coroutine",
"max_forks_repo_path": "interface/coroutine/unix.h",
"max_issues_count": 35,
"max_issues_repo_head_hexsha": "c90caab988f96997f5bc1bd6f1958b80524fa14a",
"max_issues_repo_issues_event_max_datetime": "2022-01-27T01:10:02.000Z",
"max_issues_repo_issues_event_min_datetime": "2018-11-09T04:38:20.000Z",
"max_issues_repo_licenses": [
"CC-BY-4.0"
],
"max_issues_repo_name": "lanza/coroutine",
"max_issues_repo_path": "interface/coroutine/unix.h",
"max_line_length": 77,
"max_stars_count": 368,
"max_stars_repo_head_hexsha": "c90caab988f96997f5bc1bd6f1958b80524fa14a",
"max_stars_repo_licenses": [
"CC-BY-4.0"
],
"max_stars_repo_name": "lanza/coroutine",
"max_stars_repo_path": "interface/coroutine/unix.h",
"max_stars_repo_stars_event_max_datetime": "2022-03-31T04:04:54.000Z",
"max_stars_repo_stars_event_min_datetime": "2018-11-22T22:57:04.000Z",
"num_tokens": 852,
"size": 3241
} |
/* Copyright (c) 2016, 2017 Bradley Worley <geekysuavo@gmail.com>
* Released under the MIT License
*/
/* ensure once-only inclusion. */
#ifndef __MATTE_OBJECT_H__
#define __MATTE_OBJECT_H__
/* include required standard c library headers. */
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <stddef.h>
#include <string.h>
#include <stdbool.h>
/* include required c math library headers. */
#include <math.h>
#include <complex.h>
/* include the blas/lapack headers. */
#include <cblas.h>
#include <clapack.h>
/* include the required matte headers. */
#include <matte/zone.h>
/* type definitions of blas/lapack enumerations:
* MatteTranspose: transpose options.
* MatteTriangle: triangle options.
* MatteDiagonal: diagonal options.
*/
typedef enum CBLAS_TRANSPOSE MatteTranspose;
typedef enum CBLAS_UPLO MatteTriangle;
typedef enum CBLAS_DIAG MatteDiagonal;
/* MATTE_TYPE: macro to obtain the type structure pointer of an object.
*/
#define MATTE_TYPE(obj) \
(((Object) obj)->type)
/* MATTE_TYPE_CHECK: macro to check that a matte object has a specific type.
*/
#define MATTE_TYPE_CHECK(obj,typ) \
((obj) && MATTE_TYPE(obj) == typ)
/* OBJECT_BASE: macro to place at the beginning of every matte object.
* this allows all objects to be directly cast into the base object
* type for memory management, dynamic dispatch, etc.
*/
#define OBJECT_BASE \
Object base;
/* ObjectType: pointer to a struct _ObjectType. */
typedef struct _ObjectType *ObjectType;
/* Object: pointer to a struct _Object. */
typedef struct _Object *Object;
/* ObjectMethods: pointer to a struct _ObjectMethod. */
typedef struct _ObjectMethod *ObjectMethods;
/* general-purpose function pointer type definition:
*/
typedef Object (*matte_func) (Zone, Object);
/* function pointer type definitions for matte objects:
*/
typedef Object (*obj_constructor) (Zone, Object);
typedef void (*obj_destructor) (Zone, Object);
typedef int (*obj_display) (Zone, Object);
typedef int (*obj_assert) (Object);
typedef Object (*obj_unary) (Zone, Object);
typedef Object (*obj_binary) (Zone, Object, Object);
typedef Object (*obj_ternary) (Zone, Object, Object, Object);
typedef Object (*obj_variadic) (Zone, int, va_list);
typedef Object (*obj_method) (Zone, Object, Object);
/* _ObjectMethod: structure that holds information about a matte object
* method.
*/
struct _ObjectMethod {
/* @name: string name of the method.
* @fn: method function pointer.
*/
const char *name;
obj_method fn;
};
/* _ObjectType: structure that holds the core set of information required
* by the matte object system.
*/
struct _ObjectType {
/* core object information:
* @name: string name of the matte type.
* @size: base size of the type struct.
* @precedence: object precedence for dynamic dispatch.
*/
const char *name;
unsigned int size;
unsigned int precedence;
/* core object method table:
*/
obj_constructor fn_new;
obj_constructor fn_copy;
obj_destructor fn_delete;
obj_display fn_disp;
obj_assert fn_true;
/* numeric method table:
*/
obj_binary fn_plus; /* a+b binary addition. */
obj_binary fn_minus; /* a-b binary subtraction. */
obj_unary fn_uminus; /* -a unary minus. */
obj_binary fn_times; /* a.*b element-wise multiplication. */
obj_binary fn_mtimes; /* a*b matrix multiplication. */
obj_binary fn_rdivide; /* a./b element-wise right division. */
obj_binary fn_ldivide; /* a.\b element-wise left division. */
obj_binary fn_mrdivide; /* a/b matrix right division. */
obj_binary fn_mldivide; /* a\b matrix left division. */
obj_binary fn_power; /* a.^b element-wise power. */
obj_binary fn_mpower; /* a^b matrix power. */
obj_binary fn_lt; /* a<b less than. */
obj_binary fn_gt; /* a>b greater than. */
obj_binary fn_le; /* a<=b less than or equal to. */
obj_binary fn_ge; /* a>=b greater than or equal to. */
obj_binary fn_ne; /* a!=b inequality. */
obj_binary fn_eq; /* a==b equality. */
obj_binary fn_and; /* a&b logical and. */
obj_binary fn_or; /* a|b logical or. */
obj_binary fn_mand; /* a&&b matrix logical and. */
obj_binary fn_mor; /* a||b matrix logical or. */
obj_unary fn_not; /* !a logical negation. */
obj_ternary fn_colon; /* a:d:b colon operator. */
obj_unary fn_ctranspose; /* a' conjugate transpose. */
obj_unary fn_transpose; /* a.' matrix transpose. */
obj_variadic fn_horzcat; /* [a,b] horizontal concatenation. */
obj_variadic fn_vertcat; /* [a;b] vertical concatenation. */
obj_binary fn_subsref; /* a(s) subscripted reference. */
obj_ternary fn_subsasgn; /* a(s)=b subscripted assignment. */
obj_unary fn_subsindex; /* b(a) subscript index. */
/* general-purpose method table:
*/
ObjectMethods methods;
};
/* _Object: structure for type-casting between any number of matte objects.
* holds a pointer to the object type structure as its first element.
*/
struct _Object {
/* @type: the type of matte object that is located
* at the current address in memory.
*/
ObjectType type;
/* in all other matte objects, object instance variables go here. */
};
/* function declarations (object.c): */
Object object_alloc (Zone z, ObjectType type);
Object object_copy (Zone z, Object obj);
void object_free (Zone z, void *ptr);
void object_free_all (Zone z);
int object_disp (Zone z, Object obj);
int object_display (Zone z, Object obj, const char *var);
int object_true (Object obj);
/* object method declarations (object.c): */
Object object_plus (Zone z, Object a, Object b);
Object object_minus (Zone z, Object a, Object b);
Object object_uminus (Zone z, Object a);
Object object_times (Zone z, Object a, Object b);
Object object_mtimes (Zone z, Object a, Object b);
Object object_rdivide (Zone z, Object a, Object b);
Object object_ldivide (Zone z, Object a, Object b);
Object object_mrdivide (Zone z, Object a, Object b);
Object object_mldivide (Zone z, Object a, Object b);
Object object_power (Zone z, Object a, Object b);
Object object_mpower (Zone z, Object a, Object b);
Object object_lt (Zone z, Object a, Object b);
Object object_gt (Zone z, Object a, Object b);
Object object_le (Zone z, Object a, Object b);
Object object_ge (Zone z, Object a, Object b);
Object object_ne (Zone z, Object a, Object b);
Object object_eq (Zone z, Object a, Object b);
Object object_and (Zone z, Object a, Object b);
Object object_or (Zone z, Object a, Object b);
Object object_mand (Zone z, Object a, Object b);
Object object_mor (Zone z, Object a, Object b);
Object object_not (Zone z, Object a);
Object object_colon (Zone z, Object a, Object b, Object c);
Object object_ctranspose (Zone z, Object a);
Object object_transpose (Zone z, Object a);
Object object_horzcat (Zone z, int n, ...);
Object object_vertcat (Zone z, int n, ...);
Object object_subsref (Zone z, Object a, Object b);
Object object_subsasgn (Zone z, Object a, Object b, Object c);
Object object_subsindex (Zone z, Object a);
/* utility function declarations: */
char *strdup (const char *s);
#endif /* !__MATTE_OBJECT_H__ */
| {
"alphanum_fraction": 0.6392717158,
"avg_line_length": 36.4470046083,
"ext": "h",
"hexsha": "a64a60ff816e0b1e12f87ca83fe2a32932bc745d",
"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": "5bfbddb5aa3c9ff7451b47cbf6561b7f000a7cff",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "geekysuavo/matte",
"max_forks_repo_path": "matte/object.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "5bfbddb5aa3c9ff7451b47cbf6561b7f000a7cff",
"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": "geekysuavo/matte",
"max_issues_repo_path": "matte/object.h",
"max_line_length": 76,
"max_stars_count": 2,
"max_stars_repo_head_hexsha": "5bfbddb5aa3c9ff7451b47cbf6561b7f000a7cff",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "geekysuavo/matte",
"max_stars_repo_path": "matte/object.h",
"max_stars_repo_stars_event_max_datetime": "2020-09-03T23:47:43.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-09-03T07:58:09.000Z",
"num_tokens": 1978,
"size": 7909
} |
#pragma once
#include "utility/scope_guard.h"
#include "utility/types.h"
#include <gsl/gsl>
#include <cfenv>
#include <cassert>
#define scoped_fesetround(mode) \
int SCOPE_GUARD_PP_UNIQUE(_rounding_mode) = fegetround(); \
int SCOPE_GUARD_PP_UNIQUE(_rounding_ret) = fesetround(mode); \
(void)SCOPE_GUARD_PP_UNIQUE(_rounding_ret); \
assert(SCOPE_GUARD_PP_UNIQUE(_rounding_ret) == 0); \
SCOPE(exit) { fesetround(SCOPE_GUARD_PP_UNIQUE(_rounding_mode)); }
template <class T> inline T square(T a) { return a * a; }
template <class T> inline T cube(T a) { return a * a * a; }
template <class T> inline T clamp(T x, T min, T max)
{
x = (x < min) ? min : x;
x = (x > max) ? max : x;
return x;
}
// linear interpolator
template <class R> R itp_linear(const R y[], R mu)
{
return y[0] * (1 - mu) + y[1] * mu;
}
// Catmull-Rom interpolator
template <class R> R itp_catmull(const R y[], R mu)
{
R mu2 = mu * mu;
R mu3 = mu2 * mu;
R a[] = {-R(0.5) * y[0] + R(1.5) * y[1] - R(1.5) * y[2] + R(0.5) * y[3],
y[0] - R(2.5) * y[1] + R(2) * y[2] - R(0.5) * y[3],
-R(0.5) * y[0] + R(0.5) * y[2], y[1]};
return a[0] * mu3 + a[1] * mu2 + a[2] * mu + a[3];
}
//------------------------------------------------------------------------------
// Fixed point routines
// suffix 'xN', N = bit size of the integer part
// prefix 'l' = 64-bit operation, 32-bit otherwise
//
// 'fx' number to fixed
// 'ix' integer part, 'rx' fractional part
// 'ffx' fixed to f32, 'dfx' fixed to f64
// number to Q32,32
template <class R> inline constexpr i64 lfx32(R x)
{
return i64(x * (i64)4294967296);
}
// number to Q16,16
template <class R> inline constexpr i32 fx16(R x)
{
return i32(x * (i32)65536);
}
// number to Q16,48
template <class R> inline constexpr i64 lfx16(R x)
{
return i64(x * (i64)281474976710656);
}
// number to Q8,24
template <class R> inline constexpr i32 fx8(R x)
{
return i32(x * (i32)16777216);
}
// number to Q8,56
template <class R> inline constexpr i64 lfx8(R x)
{
return i64(x * (i64)72057594037927936);
}
// Q32,32 integer part
inline constexpr i64 lix32(i64 x) { return x / 4294967296; }
inline constexpr u64 lix32(u64 x) { return x / 4294967296; }
template <class T> T lix32(T) = delete;
// Q16,16 integer part
inline constexpr i32 ix16(i32 x) { return x / 65536; }
inline constexpr u32 ix16(u32 x) { return x / 65536; }
template <class T> T ix16(T) = delete;
// Q16,48 integer part
inline constexpr i64 lix16(i64 x) { return x / 281474976710656; }
inline constexpr u64 lix16(u64 x) { return x / 281474976710656; }
template <class T> T lix16(T) = delete;
// Q8,24 integer part
inline constexpr i32 ix8(i32 x) { return x / 16777216; }
inline constexpr u32 ix8(u32 x) { return x / 16777216; }
template <class T> T ix8(T) = delete;
// Q8,56 integer part
inline constexpr i64 lix8(i64 x) { return x / 72057594037927936; }
inline constexpr u64 lix8(u64 x) { return x / 72057594037927936; }
template <class T> T lix8(T) = delete;
// Q32,32 fractional part
inline constexpr u64 lrx32(i64 x) { return x & 4294967295; }
inline constexpr u64 lrx32(u64 x) { return x & 4294967295; }
template <class T> T lrx32(T) = delete;
// Q16,16 fractional part
inline constexpr u32 rx16(i32 x) { return x & 65535; }
inline constexpr u32 rx16(u32 x) { return x & 65535; }
template <class T> T rx16(T) = delete;
// Q16,48 fractional part
inline constexpr u64 lrx16(i64 x) { return x & 281474976710655; }
inline constexpr u64 lrx16(u64 x) { return x & 281474976710655; }
template <class T> T lrx16(T) = delete;
// Q8,24 fractional part
inline constexpr u32 rx8(i32 x) { return x & 16777215; }
inline constexpr u32 rx8(u32 x) { return x & 16777215; }
template <class T> T rx8(T) = delete;
// Q8,56 fractional part
inline constexpr u64 lrx8(i64 x) { return x & 72057594037927935; }
inline constexpr u64 lrx8(u64 x) { return x & 72057594037927935; }
template <class T> T lrx8(T) = delete;
// Q32,32 number to real
inline constexpr f32 lffx32(i64 x) { return x / 4294967296.0f; }
inline constexpr f32 lffx32(u64 x) { return x / 4294967296.0f; }
template <class T> f32 lffx32(T x) = delete;
inline constexpr f64 ldfx32(i64 x) { return x / 4294967296.0; }
inline constexpr f64 ldfx32(u64 x) { return x / 4294967296.0; }
template <class T> f64 ldfx32(T x) = delete;
// Q16,16 number to real
inline constexpr f32 ffx16(i32 x) { return x / 65536.0f; }
inline constexpr f32 ffx16(u32 x) { return x / 65536.0f; }
template <class T> f32 ffx16(T x) = delete;
inline constexpr f64 dfx16(i32 x) { return x / 65536.0; }
inline constexpr f64 dfx16(u32 x) { return x / 65536.0; }
template <class T> f64 dfx16(T x) = delete;
// Q16,48 number to real
inline constexpr f32 lffx16(i64 x) { return x / 281474976710656.0f; }
inline constexpr f32 lffx16(u64 x) { return x / 281474976710656.0f; }
template <class T> f32 lffx16(T x) = delete;
inline constexpr f64 ldfx16(i64 x) { return x / 281474976710656.0; }
inline constexpr f64 ldfx16(u64 x) { return x / 281474976710656.0; }
template <class T> f64 ldfx16(T x) = delete;
// Q8,24 number to real
inline constexpr f32 ffx8(i32 x) { return x / 16777216.0f; }
inline constexpr f32 ffx8(u32 x) { return x / 16777216.0f; }
template <class T> f32 ffx8(T x) = delete;
inline constexpr f64 dfx8(i32 x) { return x / 16777216.0; }
inline constexpr f64 dfx8(u32 x) { return x / 16777216.0; }
template <class T> f64 dfx8(T x) = delete;
// Q8,56 number to real
inline constexpr f32 lffx8(i64 x) { return x / 72057594037927936.0f; }
inline constexpr f32 lffx8(u64 x) { return x / 72057594037927936.0f; }
template <class T> f32 lffx8(T x) = delete;
inline constexpr f64 ldfx8(i64 x) { return x / 72057594037927936.0; }
inline constexpr f64 ldfx8(u64 x) { return x / 72057594037927936.0; }
template <class T> f64 ldfx8(T x) = delete;
| {
"alphanum_fraction": 0.6569293478,
"avg_line_length": 37.9870967742,
"ext": "h",
"hexsha": "d7546179aba8344d6086b1ce00d438d76d73dd47",
"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/utility/arithmetic.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/utility/arithmetic.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/utility/arithmetic.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": 2114,
"size": 5888
} |
/* gsl_histogram_maxval.c
* Copyright (C) 2000 Simone Piccardi
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this library; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
/***************************************************************
*
* File gsl_histogram_maxval.c:
* Routine to find maximum and minumum content of a hisogram.
* Need GSL library and header.
* Contains the routines:
* gsl_histogram_max_val find max content values
* gsl_histogram_min_val find min content values
* gsl_histogram_bin_max find coordinates of max contents bin
* gsl_histogram_bin_min find coordinates of min contents bin
*
* Author: S. Piccardi
* Jan. 2000
*
***************************************************************/
#include <config.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_histogram.h>
double
gsl_histogram_max_val (const gsl_histogram * h)
{
const size_t n = h->n;
size_t i;
double max = h->bin[0];
for (i = 0; i < n; i++)
{
if (h->bin[i] > max)
{
max = h->bin[i];
}
}
return max;
}
size_t
gsl_histogram_max_bin (const gsl_histogram * h)
{
size_t i;
size_t imax = 0;
double max = h->bin[0];
for (i = 0; i < h->n; i++)
{
if (h->bin[i] > max)
{
max = h->bin[i];
imax = i;
}
}
return imax;
}
double
gsl_histogram_min_val (const gsl_histogram * h)
{
size_t i;
double min = h->bin[0];
for (i = 0; i < h->n; i++)
{
if (h->bin[i] < min)
{
min = h->bin[i];
}
}
return min;
}
size_t
gsl_histogram_min_bin (const gsl_histogram * h)
{
size_t i;
size_t imin = 0;
double min = h->bin[0];
for (i = 0; i < h->n; i++)
{
if (h->bin[i] < min)
{
min = h->bin[i];
imin = i;
}
}
return imin;
}
| {
"alphanum_fraction": 0.5893004115,
"avg_line_length": 24.0594059406,
"ext": "c",
"hexsha": "a914c1ce29cca5e81c54b00ed7a0a27e31dbd587",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z",
"max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "Brian-ning/HMNE",
"max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/histogram/maxval.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/maxval.c",
"max_line_length": 74,
"max_stars_count": 14,
"max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "ielomariala/Hex-Game",
"max_stars_repo_path": "gsl-2.6/histogram/maxval.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": 664,
"size": 2430
} |
/*
** overall concordance correlation coefficient (OCCC)
** Barnhart et al. (2002), Biometrics, 58, 1020-1027.
**
** G.Lohmann, July 2010
*/
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_errno.h>
#include <math.h>
#include <stdio.h>
#include <string.h>
#define SQR(x) ((x) * (x))
#define ABS(x) ((x) > 0 ? (x) : -(x))
double Cov(double *arr1,double *arr2,int n)
{
int i;
double nx,sum,ave1,ave2;
nx = (double)n;
sum = 0;
for (i=0; i<n; i++) sum += arr1[i];
ave1 = sum/nx;
sum = 0;
for (i=0; i<n; i++) sum += arr2[i];
ave2 = sum/nx;
sum = 0;
for (i=0; i<n; i++)
sum += (arr1[i] - ave1)*(arr2[i] - ave2);
return sum/(nx-1);
}
void AveVar(double *arr,int n,double *ave,double *var)
{
int i;
double u,sum1,sum2,nx,mean;
nx = (double)n;
sum1 = sum2 = 0;
for (i=0; i<n; i++) {
u = arr[i];
sum1 += u;
sum2 += u*u;
}
mean = sum1/nx;
*ave = mean;
*var = (sum2 - nx * mean * mean) / (nx - 1.0);
}
double VOCCC(gsl_matrix *data,int nvoxels,int verbose)
{
int i,j,k;
double sum1,sum2,sum3,mean,varx,u,v;
static gsl_matrix *cov=NULL;
static gsl_vector *ave=NULL,*var=NULL;
int nsubjects = data->size1;
if (ave == NULL) {
ave = gsl_vector_calloc(nsubjects);
var = gsl_vector_calloc(nsubjects);
cov = gsl_matrix_calloc(nsubjects,nsubjects);
}
for (i=0; i<nsubjects; i++) {
double *ptr1 = gsl_matrix_ptr(data,i,0);
AveVar(ptr1,nvoxels,&mean,&varx);
gsl_vector_set(ave,i,mean);
gsl_vector_set(var,i,varx);
for (j=0; j<nsubjects; j++) {
double *ptr1 = gsl_matrix_ptr(data,i,0);
double *ptr2 = gsl_matrix_ptr(data,j,0);
u = Cov(ptr1,ptr2,nvoxels);
gsl_matrix_set(cov,i,j,u);
}
}
if (verbose > 0) {
for (i=0; i<nsubjects; i++) {
for (j=0; j<nsubjects; j++) {
fprintf(stderr," %8.5f",gsl_matrix_get(cov,i,j));
}
fprintf(stderr,"\n");
}
fprintf(stderr,"\n");
exit(0);
}
sum1 = 0;
for (j=1; j<=nsubjects-1; j++) {
for (k=j+1; k<=nsubjects; k++) {
u = gsl_matrix_get(cov,j-1,k-1);
sum1 += u;
}
}
sum1 *= 2.0;
sum2 = 0;
for (j=0; j<nsubjects; j++) {
sum2 += gsl_vector_get(var,j);
}
sum2 *= (double)(nsubjects-1);
sum3 = 0;
for (j=1; j<=nsubjects-1; j++) {
for (k=j+1; k<=nsubjects; k++) {
u = gsl_vector_get(ave,j-1);
v = gsl_vector_get(ave,k-1);
sum3 += (u-v)*(u-v);
}
}
if (sum2 + sum3 < 1.0e-6) return 0;
return sum1 / (sum2 + sum3);
}
| {
"alphanum_fraction": 0.5506903353,
"avg_line_length": 19.5,
"ext": "c",
"hexsha": "430273b9fdb5dc41b23318a1d59e4a65f174b28d",
"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/nets/vccm/OCCC.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/nets/vccm/OCCC.c",
"max_line_length": 54,
"max_stars_count": 17,
"max_stars_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "zrajna/lipsia",
"max_stars_repo_path": "src/nets/vccm/OCCC.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": 942,
"size": 2535
} |
#pragma once
#include "gdx/algo/algorithm.h"
#include "gdx/exception.h"
#include <gsl/span>
#include <numeric>
#include <type_traits>
#include <unordered_map>
namespace gdx {
template <class T>
struct has_sum_member
{
template <typename U, U u>
struct reallyHas;
template <typename C>
static constexpr std::true_type test(reallyHas<double (C::*)(), &C::sum>* /*unused*/)
{
return {};
}
template <typename C>
static constexpr std::true_type test(reallyHas<double (C::*)() const, &C::sum>* /*unused*/)
{
return {};
}
template <typename>
static std::false_type test(...)
{
return {};
}
static constexpr bool value = decltype(test<T>(0))::value;
};
template <typename T>
inline constexpr bool has_sum_member_v = has_sum_member<T>::value;
template <typename RasterType>
typename std::enable_if_t<has_sum_member_v<RasterType>, double> sum(const RasterType& ras)
{
return ras.template sum<double>();
}
template <typename RasterType>
typename std::enable_if_t<!has_sum_member_v<RasterType>, double> sum(const RasterType& ras)
{
double sum = 0.0;
const auto size = ras.size();
for (std::size_t i = 0; i < size; ++i) {
if (!ras.is_nodata(i)) {
sum += ras[i];
}
}
return sum;
}
template <typename RasterType>
double ssum(const RasterType& ras)
{
using T = typename RasterType::value_type;
return static_cast<double>(std::accumulate(value_begin(ras), value_end(ras), T(0), std::plus<T>()));
}
}
| {
"alphanum_fraction": 0.6431803491,
"avg_line_length": 21.4861111111,
"ext": "h",
"hexsha": "698e90a3b1c13b271dffdc3babb06eb701591e1d",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2021-06-16T11:55:27.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-06-16T11:55:27.000Z",
"max_forks_repo_head_hexsha": "6d3323bc4cae1b85e26afdceab2ecf3686b11369",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "VITObelgium/geodynamix",
"max_forks_repo_path": "algorithms/include/gdx/algo/sum.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "6d3323bc4cae1b85e26afdceab2ecf3686b11369",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "VITObelgium/geodynamix",
"max_issues_repo_path": "algorithms/include/gdx/algo/sum.h",
"max_line_length": 104,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "6d3323bc4cae1b85e26afdceab2ecf3686b11369",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "VITObelgium/geodynamix",
"max_stars_repo_path": "algorithms/include/gdx/algo/sum.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 402,
"size": 1547
} |
#include "../include/paralleltt.h"
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <stdio.h>
#include <cblas.h>
#include <lapacke.h>
#include <unistd.h>
#include <mpi.h>
#define NUM_THREAD 1
#define min(a,b) ((a)>(b)?(b):(a))
#define VERBOSE ((int) 1)
#ifndef HEAD
#define HEAD ((int) 0)
#endif
#define BUF ((int) 2)
tensor_train* TT_init(const int d, const int* restrict n)
{
tensor_train* sim = (tensor_train*) malloc(sizeof(tensor_train));
sim->d = d;
sim->n = (int*) malloc(sizeof(int)*d);
sim->r = (int*) malloc(sizeof(int)*(d+1));
sim->trains = (double**) malloc(sizeof(double*)*d);
sim->r[0] = 1;
for (int j = 0; j < d; ++j) {
sim->n[j] = n[j];
if (j < d-1) {
sim->r[j+1] = n[j];
}
}
sim->r[d] = 1;
for (int j = 0; j < d; ++j) {
sim->trains[j] = (double*) malloc(sizeof(double)*(sim->r[j])*(sim->n[j])*(sim->r[j+1]));
}
return sim;
}
tensor_train* TT_init_rank(const int d, const int* restrict n, const int* restrict r)
{
tensor_train* sim = (tensor_train*) malloc(sizeof(tensor_train));
sim->d = d;
sim->n = (int*) malloc(sizeof(int)*d);
sim->r = (int*) malloc(sizeof(int)*(d+1));
sim->trains = (double**) malloc(sizeof(double*)*d);
for (int j = 0; j < d; ++j) {
sim->n[j] = n[j];
}
for (int j = 0; j < d+1; ++j) {
sim->r[j] = r[j];
}
for (int j = 0; j < d; ++j) {
sim->trains[j] = (double*) malloc(sizeof(double)*(sim->r[j])*(sim->n[j])*(sim->r[j+1]));
}
return sim;
}
tensor_train* TT_copy(tensor_train* X)
{
int d = X->d;
int* n = X->n;
int* r = X->r;
tensor_train* Y = TT_init_rank(d, n, r);
for (int j = 0; j < X->d; ++j) {
int N = r[j] * n[j] * r[j+1];
memcpy(Y->trains[j], X->trains[j], N * sizeof(double));
}
return Y;
}
void TT_free(tensor_train* sim)
{
for (int j = 0; j < sim->d; ++j) {
free(sim->trains[j]); sim->trains[j] = NULL;
}
free(sim->trains); sim->trains = NULL;
free(sim->r); sim->r = NULL;
free(sim->n); sim->n = NULL;
free(sim);
}
void TT_print(tensor_train* tt)
{
int d = tt->d;
int* n = tt->n;
int* r = tt->r;
double** trains = tt->trains;
printf("Printing the tensor train with d = %d\n",d);
for (int ii = 0; ii < d; ++ii){
printf("\nTensor %d/d (r[%d] = %d, n[%d]=%d, r[%d]=%d):\n",ii,ii,r[ii],ii,n[ii],ii+1,r[ii+1]);
matrix_tt* A = matrix_tt_wrap(r[ii], n[ii] * r[ii+1], trains[ii]);
matrix_tt_print(A, 1);
free(A); A = NULL;
}
}
void tt_broadcast(MPI_Comm comm, tensor_train* tt){
for (int ii = 0; ii < tt->d; ++ii){
matrix_tt* A = matrix_tt_wrap((tt->r[ii]) * (tt->n[ii]) * (tt->r[ii+1]), 1, tt->trains[ii]);
matrix_tt_broadcast(comm, A);
free(A);
}
}
double get_compression(const tensor_train* tt)
{
long N = 1;
for (int ii = 0; ii < tt->d; ++ii)
{
N = N * tt->n[ii];
}
long Ntt = 0;
for (int ii = 0; ii < tt->d; ++ii)
{
Ntt = Ntt + ((tt->r[ii])*(tt->n[ii])*(tt->r[ii+1]));
}
double compression = (double) Ntt/N;
return compression;
}
| {
"alphanum_fraction": 0.5065217391,
"avg_line_length": 22.8368794326,
"ext": "c",
"hexsha": "eefd45d2024f9bd83bda1ce4bdc44cc0948d333b",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "e2c00c289d75d3ac1df32ed2b95af579a517fcbf",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "SidShi/Parallel_TT_sketching",
"max_forks_repo_path": "src/tt.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "e2c00c289d75d3ac1df32ed2b95af579a517fcbf",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "SidShi/Parallel_TT_sketching",
"max_issues_repo_path": "src/tt.c",
"max_line_length": 102,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "e2c00c289d75d3ac1df32ed2b95af579a517fcbf",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "SidShi/Parallel_TT_sketching",
"max_stars_repo_path": "src/tt.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1114,
"size": 3220
} |
#ifndef INCLUDED_BLAS_DETAIL_H
#define INCLUDED_BLAS_DETAIL_H
#include <cblas.h>
#include "telepath/blas/traits.h"
namespace blas{
namespace matrix{
namespace matrix_detail{
template< typename T, bool = BlasCast<T>::value >
struct BlasMatImpl { };
template< typename T >
struct BlasMatImpl< T, true >{
using mat_t = decltype( BlasCast<T>::blas_cast(
std::declval<T>() ) );
mat_t mat;
constexpr BlasMatImpl( const T& m )
: mat( BlasCast<T>::blas_cast( m ) ) { }
operator mat_t&() { return mat; }
operator const mat_t&() const{ return mat; }
};
template< typename T >
struct BlasMatImpl< T, false >{
using mat_t = T;
mat_t& mat;
constexpr BlasMatImpl( T& m ) : mat( m ) { }
operator mat_t&() { return mat; }
operator const mat_t&() const{ return mat; }
};
template< typename T, bool = BlasCast<T>::value >
struct ConstBlasMatImpl { };
template< typename T >
struct ConstBlasMatImpl< T, true >{
using mat_t = decltype( BlasCast<T>::blas_cast(
std::declval<T>() ) );
mat_t mat;
constexpr ConstBlasMatImpl( const T& m )
: mat( BlasCast<T>::blas_cast( m ) ) { }
operator const mat_t&() const{ return mat; }
};
template< typename T >
struct ConstBlasMatImpl< T, false >{
using mat_t = T;
const mat_t& mat;
constexpr ConstBlasMatImpl( const T& m ) : mat( m ) { }
operator const mat_t&() const{ return mat; }
};
} //namespace matrix_detail
template< typename T >
struct Mat : public matrix_detail::BlasMatImpl<T> {
using impl = typename matrix_detail::BlasMatImpl<T>;
using impl::impl;
};
template< typename T >
struct ConstMat : public matrix_detail::ConstBlasMatImpl<T>{
using impl = typename matrix_detail::ConstBlasMatImpl<T>;
using impl::impl;
};
template< typename T >
using scalar_t = typename MatrixTraits<T>::scalar_t;
template< typename T >
constexpr CBLAS_ORDER layout( const T& x ){
return MatrixTraits<T>::layout( x );
}
template< typename T >
constexpr CBLAS_TRANSPOSE trans( const T& x ){
return MatrixTraits<T>::trans( x );
}
template< typename T >
constexpr CBLAS_UPLO uplo( const T& x ){
return MatrixTraits<T>::uplo( x );
}
template< typename T >
constexpr std::size_t nrows( const T& x ){
return MatrixTraits<T>::nrows( x );
}
template< typename T >
constexpr std::size_t ncols( const T& x ){
return MatrixTraits<T>::ncols( x );
}
template< typename T >
constexpr std::size_t ld( const T& x ){
return MatrixTraits<T>::ld( x );
}
template< typename T >
constexpr auto array( T& x ){
return MatrixTraits<T>::array( x );
}
template< typename T >
constexpr auto array( const T& x ){
return MatrixTraits<T>::array( x );
}
} //namespace matrix
template< typename T >
inline auto blas_matrix( T& x ){
return matrix::Mat<T>( x );
}
template< typename T >
inline auto blas_matrix( const T& x ){
return matrix::ConstMat<T>( x );
}
template< typename T >
struct MatrixTraits< matrix::Mat<T> >
: public MatrixTraits< typename matrix::Mat<T>::mat_t > { };
template< typename T >
struct MatrixTraits< matrix::ConstMat<T> >
: public MatrixTraits< typename matrix::ConstMat<T>::mat_t > { };
namespace vector{
namespace vector_detail{
template< typename T, bool = BlasCast<T>::value >
struct BlasVecImpl { };
template< typename T >
struct BlasVecImpl< T, true >{
using vec_t = decltype( BlasCast<T>::blas_cast(
std::declval<T>() ) );
vec_t vec;
constexpr BlasVecImpl( const T& v )
: vec( BlasCast<T>::blas_cast( v ) ) { }
operator vec_t&() { return vec; }
operator const vec_t&() const{ return vec; }
};
template< typename T >
struct BlasVecImpl< T, false >{
using vec_t = T;
vec_t& vec;
BlasVecImpl( const T& v ) : vec( v ) { }
operator vec_t&() { return vec; }
operator const vec_t&() const{ return vec; }
};
} //namespace vector_detail
template< typename T >
struct Vec : public vector_detail::BlasVecImpl<T> {
using impl = typename vector_detail::BlasVecImpl<T>;
using impl::impl;
};
template< typename T >
using scalar_t = typename VectorTraits<T>::scalar_t;
template< typename T >
constexpr auto length( const T& x ){
return VectorTraits<T>::length( x );
}
template< typename T >
constexpr auto inc( const T& x ){
return VectorTraits<T>::inc( x );
}
template< typename T >
constexpr auto array( T& x ){
return VectorTraits<T>::array( x );
}
template< typename T >
constexpr auto array( const T& x ){
return VectorTraits<T>::array( x );
}
} //namespace vector
template< typename T >
struct VectorTraits< vector::Vec<T> >
: public VectorTraits< typename vector::Vec<T>::vec_t > { };
} //namespace blas
#endif
| {
"alphanum_fraction": 0.5072558291,
"avg_line_length": 30.5124378109,
"ext": "h",
"hexsha": "132500f2ccb7ddba7f177426d5e7864ca14cd8c5",
"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": "636f7345b6479d5c48dbf03cb17343b14c305c7c",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "tbepler/telepath",
"max_forks_repo_path": "include/telepath/blas/detail.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "636f7345b6479d5c48dbf03cb17343b14c305c7c",
"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": "tbepler/telepath",
"max_issues_repo_path": "include/telepath/blas/detail.h",
"max_line_length": 73,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "636f7345b6479d5c48dbf03cb17343b14c305c7c",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "tbepler/telepath",
"max_stars_repo_path": "include/telepath/blas/detail.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1369,
"size": 6133
} |
//
// Created by bessermt on 6/3/18.
//
#ifndef SRSGRADE_TIMESTAMP_H
#define SRSGRADE_TIMESTAMP_H
#include <iostream>
#include <iomanip>
#include <chrono>
#include <gsl.h>
class Timestamp
{
private:
std::chrono::system_clock::time_point time_point_{};
void set(const std::string date_string, const std::string time_string);
friend std::istream& operator>>(std::istream& is, Timestamp& timestamp)
{
std::string date_string;
is >> date_string;
Ensures(!date_string.empty());
char time_cstr[256]{};
constexpr auto max_time_len{ std::extent<decltype(time_cstr)>::value };
is >> std::ws;
is.getline(time_cstr, max_time_len, ',');
const auto time_len{ strlen(time_cstr) };
Ensures(time_len > 0 && time_len < max_time_len);
const auto time_string{ std::string(time_cstr) };
timestamp.set(date_string, time_string);
return is;
}
friend bool operator<(const Timestamp lhs, const Timestamp rhs)
{
return lhs.time_point_ < rhs.time_point_;
}
public:
auto is_good() const
{
const auto is_past{ time_point_ < std::chrono::system_clock::now() };
return is_past; // TODO: Any better tests?
}
};
#endif // SRSGRADE_TIMESTAMP_H
| {
"alphanum_fraction": 0.6764466178,
"avg_line_length": 21.1551724138,
"ext": "h",
"hexsha": "c641da73ff49ed12b265bcabe0cc2afee4891a7f",
"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": "2e5f274dbaba950a9ec406b77544be2ca210a8ac",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "labermt/SRSGrade",
"max_forks_repo_path": "SRSGrade/timestamp.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "2e5f274dbaba950a9ec406b77544be2ca210a8ac",
"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": "labermt/SRSGrade",
"max_issues_repo_path": "SRSGrade/timestamp.h",
"max_line_length": 75,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "2e5f274dbaba950a9ec406b77544be2ca210a8ac",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "labermt/SRSGrade",
"max_stars_repo_path": "SRSGrade/timestamp.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 317,
"size": 1227
} |
/*
* C version of Diffusive Nested Sampling (DNest4) by Brendon J. Brewer
*
* Yan-Rong Li, liyanrong@mail.ihep.ac.cn
* Jun 30, 2016
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#include <math.h>
#include <float.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
#include "dnestvars.h"
double dnest(int argc, char** argv, DNestFptrSet *fptrset, int num_params,
char *sample_dir, int max_num_saves, double ptol, const void *arg)
{
int opt;
dnest_arg = arg;
dnest_check_fptrset(fptrset);
// cope with argv
dnest_post_temp = 1.0;
dnest_flag_restart = 0;
dnest_flag_postprc = 0;
dnest_flag_sample_info = 0;
dnest_flag_limits = 0;
strcpy(file_save_restart, "restart_dnest.txt");
strcpy(dnest_sample_postfix, "\0");
strcpy(dnest_sample_tag, "\0");
opterr = 0;
optind = 0;
while( (opt = getopt(argc, argv, "r:s:pt:clx:g:")) != -1)
{
switch(opt)
{
case 'r':
dnest_flag_restart = 1;
strcpy(file_restart, optarg);
printf("# Dnest restarts.\n");
break;
case 's':
strcpy(file_save_restart, optarg);
//printf("# Dnest sets restart file %s.\n", file_save_restart);
break;
case 'p':
dnest_flag_postprc = 1;
dnest_post_temp = 1.0;
printf("# Dnest does postprocess.\n");
break;
case 't':
dnest_post_temp = atof(optarg);
printf("# Dnest sets a temperature %f.\n", dnest_post_temp);
if(dnest_post_temp == 0.0)
{
printf("# Dnest incorrect option -t %s.\n", optarg);
exit(0);
}
if(dnest_post_temp < 1.0)
{
printf("# Dnest temperature should >= 1.0\n");
exit(0);
}
break;
case 'c':
dnest_flag_sample_info = 1;
printf("# Dnest recalculates sample information.\n");
break;
case 'l':
dnest_flag_limits = 1;
printf("# Dnest level-dependent sampling.\n");
break;
case 'x':
strcpy(dnest_sample_postfix, optarg);
printf("# Dnest sets sample postfix %s.\n", dnest_sample_postfix);
break;
case 'g':
strcpy(dnest_sample_tag, optarg);
printf("# Dnest sets sample tag %s.\n", dnest_sample_tag);
break;
case '?':
printf("# Dnest incorrect option -%c %s.\n", optopt, optarg);
exit(0);
break;
default:
break;
}
}
setup(argc, argv, fptrset, num_params, sample_dir, max_num_saves, ptol);
if(dnest_flag_postprc == 1)
{
dnest_postprocess(dnest_post_temp, max_num_saves, ptol);
finalise();
return post_logz;
}
if(dnest_flag_sample_info == 1)
{
dnest_postprocess(dnest_post_temp, max_num_saves, ptol);
finalise();
return post_logz;
}
if(dnest_flag_restart==1)
dnest_restart();
initialize_output_file();
dnest_run();
close_output_file();
dnest_postprocess(dnest_post_temp, max_num_saves, ptol);
finalise();
return post_logz;
}
// postprocess, calculate evidence, generate posterior sample.
void dnest_postprocess(double temperature, int max_num_saves, double ptol)
{
options_load(max_num_saves, ptol);
postprocess(temperature);
}
void dnest_run()
{
int i, j, k, size_all_above_incr;
Level *pl, *levels_orig;
int *buf_size_above, *buf_displs;
double *plimits;
printf("# Start diffusive nested sampling.\n");
while(true)
{
//check for termination
if(options.max_num_saves !=0 &&
count_saves != 0 && (count_saves%options.max_num_saves == 0))
break;
dnest_mcmc_run();
count_mcmc_steps += options.thread_steps;
if(dnest_flag_limits == 1)
{
// limits of smaller levels should be larger than those of higher levels
for(j=size_levels-2; j >= 0; j--)
for(k=0; k<particle_offset_double; k++)
{
limits[ j * particle_offset_double *2 + k*2 ] = fmin( limits[ j * particle_offset_double *2 + k*2 ],
limits[ (j+1) * particle_offset_double *2 + k*2 ] );
limits[ j * particle_offset_double *2 + k*2 + 1] = fmax( limits[ j * particle_offset_double *2 + k*2 +1 ],
limits[ (j+1) * particle_offset_double *2 + k*2 + 1 ] );
}
}
do_bookkeeping();
if(count_mcmc_steps >= (count_saves + 1)*options.save_interval)
{
save_particle();
// save levels, limits, sync samples when running a number of steps
if( count_saves % num_saves == 0 )
{
if(size_levels <= options.max_num_levels)
{
save_levels();
printf("# Save levels at N= %d.\n", count_saves);
}
if(dnest_flag_limits == 1)
save_limits();
fflush(fsample_info);
fsync(fileno(fsample_info));
fflush(fsample);
fsync(fileno(fsample));
printf("# Save limits, and sync samples at N= %d.\n", count_saves);
}
//if( count_saves % num_saves_restart == 0 )
//{
// dnest_save_restart();
//}
}
}
//dnest_save_restart();
//save levels
save_levels();
if(dnest_flag_limits == 1)
save_limits();
/* output state of sampler */
FILE *fp;
fp = fopen(options.sampler_state_file, "w");
fprintf(fp, "%d %d\n", size_levels, count_saves);
fclose(fp);
}
void do_bookkeeping()
{
int i;
//bool created_level = false;
if(!enough_levels(levels, size_levels) && size_above >= options.new_level_interval)
{
// in descending order
qsort(above, size_above, sizeof(LikelihoodType), dnest_cmp);
int index = (int)( (1.0/compression) * size_above);
Level level_tmp = {above[index], 0.0, 0, 0, 0, 0};
levels[size_levels] = level_tmp;
size_levels++;
printf("# Creating level %d with log likelihood = %e.\n",
size_levels-1, levels[size_levels-1].log_likelihood.value);
// clear out the last index records
for(i=index; i<size_above; i++)
{
above[i].value = 0.0;
above[i].tiebreaker = 0.0;
}
size_above = index;
if(enough_levels(levels, size_levels))
{
renormalise_visits();
options.max_num_levels = size_levels;
printf("# Done creating levles.\n");
}
else
{
kill_lagging_particles();
}
}
recalculate_log_X();
}
void recalculate_log_X()
{
int i;
levels[0].log_X = 0.0;
for(i=1; i<size_levels; i++)
{
levels[i].log_X = levels[i-1].log_X
+ log( (double)( (levels[i-1].exceeds + 1.0/compression * regularisation)
/(levels[i-1].visits + regularisation) ) );
}
}
void renormalise_visits()
{
size_t i;
for(i=0; i<size_levels; i++)
{
if(levels[i].tries >= regularisation)
{
levels[i].accepts = ((double)(levels[i].accepts+1) / (double)(levels[i].tries+1)) * regularisation;
levels[i].tries = regularisation;
}
if(levels[i].visits >= regularisation)
{
levels[i].exceeds = ( (double) (levels[i].exceeds+1) / (double)(levels[i].visits + 1) ) * regularisation;
levels[i].visits = regularisation;
}
}
}
void kill_lagging_particles()
{
static unsigned int deletions = 0;
bool *good;
good = (bool *)malloc(options.num_particles * sizeof(bool));
double max_log_push = -DBL_MAX;
double kill_probability = 0.0;
unsigned int num_bad = 0;
size_t i;
for(i=0; i<options.num_particles; i++)good[i] = true;
for(i=0; i<options.num_particles; i++)
{
if( log_push(level_assignments[i]) > max_log_push)
max_log_push = log_push(level_assignments[i]);
kill_probability = pow(1.0 - 1.0/(1.0 + exp(-log_push(level_assignments[i]) - 4.0)), 3);
if(gsl_rng_uniform(dnest_gsl_r) <= kill_probability)
{
good[i] = false;
++num_bad;
}
}
if(num_bad < options.num_particles)
{
for(i=0; i< options.num_particles; i++)
{
if(!good[i])
{
int i_copy;
do
{
i_copy = gsl_rng_uniform_int(dnest_gsl_r, options.num_particles);
}while(!good[i_copy] || gsl_rng_uniform(dnest_gsl_r) >= exp(log_push(level_assignments[i_copy]) - max_log_push));
memcpy(particles+i*particle_offset_size, particles + i_copy*particle_offset_size, dnest_size_of_modeltype);
log_likelihoods[i] = log_likelihoods[i_copy];
level_assignments[i] = level_assignments[i_copy];
kill_action(i, i_copy);
deletions++;
printf("# Replacing lagging particle.\n");
printf("# This has happened %d times.\n", deletions);
}
}
}
else
printf("# Warning: all particles lagging!.\n");
free(good);
}
/* save levels */
void save_levels()
{
if(!save_to_disk)
return;
int i;
FILE *fp;
fp = fopen(options.levels_file, "w");
fprintf(fp, "# log_X, log_likelihood, tiebreaker, accepts, tries, exceeds, visits\n");
for(i=0; i<size_levels; i++)
{
fprintf(fp, "%14.12g %14.12g %f %llu %llu %llu %llu\n", levels[i].log_X, levels[i].log_likelihood.value,
levels[i].log_likelihood.tiebreaker, levels[i].accepts,
levels[i].tries, levels[i].exceeds, levels[i].visits);
}
fclose(fp);
/* update state of sampler */
fp = fopen(options.sampler_state_file, "w");
fprintf(fp, "%d %d\n", size_levels, count_saves);
fclose(fp);
}
void save_limits()
{
int i, j;
FILE *fp;
fp = fopen(options.limits_file, "w");
for(i=0; i<size_levels; i++)
{
fprintf(fp, "%d ", i);
for(j=0; j<particle_offset_double; j++)
fprintf(fp, "%f %f ", limits[i*2*particle_offset_double+j*2], limits[i*2*particle_offset_double+j*2+1]);
fprintf(fp, "\n");
}
fclose(fp);
}
/* save particle */
void save_particle()
{
count_saves++;
if(!save_to_disk)
return;
int whichparticle, whichtask;
void *particle_message;
if(count_saves%10 == 0)
printf("#[%.1f%%] Saving sample N= %d.\n", 100.0*count_saves/options.max_num_saves, count_saves);
whichparticle = gsl_rng_uniform_int(dnest_gsl_r,options.num_particles);
print_particle(fsample, particles + whichparticle * particle_offset_size, dnest_arg);
fprintf(fsample_info, "%d %e %f %d\n", level_assignments[whichparticle],
log_likelihoods[whichparticle].value,
log_likelihoods[whichparticle].tiebreaker,
whichparticle);
}
void dnest_mcmc_run()
{
unsigned int which;
unsigned int i;
for(i = 0; i<options.thread_steps; i++)
{
/* randomly select out one particle to update */
which = gsl_rng_uniform_int(dnest_gsl_r, options.num_particles);
dnest_which_particle_update = which;
//if(count_mcmc_steps >= 10000)printf("FFFF\n");
//printf("%d\n", which);
//printf("%f %f %f\n", particles[which].param[0], particles[which].param[1], particles[which].param[2]);
//printf("level:%d\n", level_assignments[which]);
//printf("%e\n", log_likelihoods[which].value);
if(gsl_rng_uniform(dnest_gsl_r) <= 0.5)
{
update_particle(which);
update_level_assignment(which);
}
else
{
update_level_assignment(which);
update_particle(which);
}
if( !enough_levels(levels, size_levels) && levels[size_levels-1].log_likelihood.value < log_likelihoods[which].value)
{
above[size_above] = log_likelihoods[which];
size_above++;
}
}
}
void update_particle(unsigned int which)
{
void *particle = particles+ which*particle_offset_size;
LikelihoodType *logl = &(log_likelihoods[which]);
Level *level = &(levels[level_assignments[which]]);
void *proposal = (void *)malloc(dnest_size_of_modeltype);
LikelihoodType logl_proposal;
double log_H;
memcpy(proposal, particle, dnest_size_of_modeltype);
dnest_which_level_update = level_assignments[which];
log_H = perturb(proposal, dnest_arg);
logl_proposal.value = log_likelihoods_cal(proposal, dnest_arg);
logl_proposal.tiebreaker = (*logl).tiebreaker + gsl_rng_uniform(dnest_gsl_r);
dnest_wrap(&logl_proposal.tiebreaker, 0.0, 1.0);
if(log_H > 0.0)
log_H = 0.0;
dnest_perturb_accept[which] = 0;
if( gsl_rng_uniform(dnest_gsl_r) <= exp(log_H) && level->log_likelihood.value < logl_proposal.value)
{
memcpy(particle, proposal, dnest_size_of_modeltype);
memcpy(logl, &logl_proposal, sizeof(LikelihoodType));
level->accepts++;
dnest_perturb_accept[which] = 1;
accept_action();
account_unaccepts[which] = 0; /* reset the number of unaccepted perturb */
}
else
{
account_unaccepts[which] += 1; /* number of unaccepted perturb */
}
level->tries++;
unsigned int current_level = level_assignments[which];
for(; current_level < size_levels-1; ++current_level)
{
levels[current_level].visits++;
if(levels[current_level+1].log_likelihood.value < log_likelihoods[which].value)
levels[current_level].exceeds++;
else
break; // exit the loop if it does not satify higher levels
}
free(proposal);
}
void update_level_assignment(unsigned int which)
{
int i;
int proposal = level_assignments[which]
+ (int)( pow(10.0, 2*gsl_rng_uniform(dnest_gsl_r))*gsl_ran_ugaussian(dnest_gsl_r));
if(proposal == level_assignments[which])
proposal = ((gsl_rng_uniform(dnest_gsl_r) < 0.5)?(proposal-1):(proposal+1));
proposal=mod_int(proposal, size_levels);
double log_A = -levels[proposal].log_X + levels[level_assignments[which]].log_X;
log_A += log_push(proposal) - log_push(level_assignments[which]);
if(size_levels == options.max_num_levels)
log_A += options.beta*log( (double)(levels[level_assignments[which]].tries +1)/ (levels[proposal].tries +1) );
if(log_A > 0.0)
log_A = 0.0;
if( gsl_rng_uniform(dnest_gsl_r) <= exp(log_A) && levels[proposal].log_likelihood.value < log_likelihoods[which].value)
{
level_assignments[which] = proposal;
// update the limits of the level
if(dnest_flag_limits == 1)
{
double *particle = (double *) (particles+ which*particle_offset_size);
for(i=0; i<particle_offset_double; i++)
{
limits[proposal * 2 * particle_offset_double + i*2] =
fmin(limits[proposal * 2* particle_offset_double + i*2], particle[i]);
limits[proposal * 2 * particle_offset_double + i*2+1] =
fmax(limits[proposal * 2 * particle_offset_double + i*2+1], particle[i]);
}
}
}
}
double log_push(unsigned int which_level)
{
if(which_level > size_levels)
{
printf("level overflow %d %d.\n", which_level, size_levels);
exit(0);
}
if(enough_levels(levels, size_levels))
return 0.0;
int i = which_level - (size_levels - 1);
return ((double)i)/options.lambda;
}
bool enough_levels(Level *l, int size_l)
{
int i;
if(options.max_num_levels == 0)
{
if(size_l >= LEVEL_NUM_MAX)
return true;
if(size_l < 10)
return false;
int num_levels_to_check = 20;
if(size_l > 80)
num_levels_to_check = (int)(sqrt(20) * sqrt(0.25*size_l));
int k = size_l - 1, kc = 0;
double tot = 0.0;
double max = -DBL_MAX;
double diff;
for(i= 0; i<num_levels_to_check; i++)
{
diff = l[k].log_likelihood.value - l[k-1].log_likelihood.value;
tot += diff;
if(diff > max)
max = diff;
k--;
kc++;
if( k < 1 )
break;
}
if(tot/kc < options.max_ptol && max < options.max_ptol*1.1)
return true;
else
return false;
}
return (size_l >= options.max_num_levels);
}
void initialize_output_file()
{
if(dnest_flag_restart !=1)
fsample = fopen(options.sample_file, "w");
else
fsample = fopen(options.sample_file, "a");
if(fsample==NULL)
{
fprintf(stderr, "# Cannot open file sample.txt.\n");
exit(0);
}
if(dnest_flag_restart != 1)
fprintf(fsample, "# \n");
if(dnest_flag_restart != 1)
fsample_info = fopen(options.sample_info_file, "w");
else
fsample_info = fopen(options.sample_info_file, "a");
if(fsample_info==NULL)
{
fprintf(stderr, "# Cannot open file %s.\n", options.sample_info_file);
exit(0);
}
if(dnest_flag_restart != 1)
fprintf(fsample_info, "# level assignment, log likelihood, tiebreaker, ID.\n");
}
void close_output_file()
{
fclose(fsample);
fclose(fsample_info);
}
void setup(int argc, char** argv, DNestFptrSet *fptrset, int num_params, char *sample_dir, int max_num_saves, double ptol)
{
int i, j;
// root task.
dnest_root = 0;
// setup function pointers
from_prior = fptrset->from_prior;
log_likelihoods_cal = fptrset->log_likelihoods_cal;
log_likelihoods_cal_initial = fptrset->log_likelihoods_cal_initial;
log_likelihoods_cal_restart = fptrset->log_likelihoods_cal_restart;
perturb = fptrset->perturb;
print_particle = fptrset->print_particle;
read_particle = fptrset->read_particle;
restart_action = fptrset->restart_action;
accept_action = fptrset->accept_action;
kill_action = fptrset->kill_action;
strcpy(dnest_sample_dir, sample_dir);
// random number generator
dnest_gsl_T = (gsl_rng_type *) gsl_rng_default;
dnest_gsl_r = gsl_rng_alloc (dnest_gsl_T);
#ifndef Debug
gsl_rng_set(dnest_gsl_r, time(NULL));
#else
gsl_rng_set(dnest_gsl_r, 9999);
printf("# debugging, dnest random seed %d\n", 9999);
#endif
dnest_num_params = num_params;
dnest_size_of_modeltype = dnest_num_params * sizeof(double);
// read options
options_load(max_num_saves, ptol);
//dnest_post_temp = 1.0;
compression = exp(1.0);
regularisation = options.new_level_interval*sqrt(options.lambda);
save_to_disk = true;
// particles
particle_offset_size = dnest_size_of_modeltype/sizeof(void);
particle_offset_double = dnest_size_of_modeltype/sizeof(double);
particles = (void *)malloc(options.num_particles*dnest_size_of_modeltype);
// initialise sampler
above = (LikelihoodType *)malloc(2*options.new_level_interval * sizeof(LikelihoodType));
log_likelihoods = (LikelihoodType *)malloc(2*options.num_particles * sizeof(LikelihoodType));
level_assignments = (unsigned int*)malloc(options.num_particles * sizeof(unsigned int));
account_unaccepts = (unsigned int *)malloc(options.num_particles * sizeof(unsigned int));
for(i=0; i<options.num_particles; i++)
{
account_unaccepts[i] = 0;
}
if(options.max_num_levels != 0)
{
levels = (Level *)malloc(options.max_num_levels * sizeof(Level));
if(dnest_flag_limits == 1)
{
limits = malloc(options.max_num_levels * particle_offset_double * 2 * sizeof(double));
for(i=0; i<options.max_num_levels; i++)
{
for(j=0; j<particle_offset_double; j++)
{
limits[i*2*particle_offset_double+ j*2] = DBL_MAX;
limits[i*2*particle_offset_double + j*2 + 1] = -DBL_MAX;
}
}
}
}
else
{
levels = (Level *)malloc(LEVEL_NUM_MAX * sizeof(Level));
if(dnest_flag_limits == 1)
{
limits = malloc(LEVEL_NUM_MAX * particle_offset_double * 2 * sizeof(double));
for(i=0; i<LEVEL_NUM_MAX; i++)
{
for(j=0; j<particle_offset_double; j++)
{
limits[i*2*particle_offset_double + j*2] = DBL_MAX;
limits[i*2*particle_offset_double + j*2 + 1] = -DBL_MAX;
}
}
}
}
dnest_perturb_accept = malloc(options.num_particles * sizeof(int));
for(i=0; i<options.num_particles; i++)
{
dnest_perturb_accept[i] = 0;
}
count_mcmc_steps = 0;
count_saves = 0;
num_saves = (int)fmax(0.02*options.max_num_saves, 1.0);
num_saves_restart = (int)fmax(0.2 * options.max_num_saves, 1.0);
// first level
size_levels = 0;
size_above = 0;
LikelihoodType like_tmp = {-DBL_MAX, gsl_rng_uniform(dnest_gsl_r)};
Level level_tmp = {like_tmp, 0.0, 0, 0, 0, 0};
levels[size_levels] = level_tmp;
size_levels++;
for(i=0; i<options.num_particles; i++)
{
dnest_which_particle_update = i;
dnest_which_level_update = 0;
from_prior(particles+i*particle_offset_size, dnest_arg);
log_likelihoods[i].value = log_likelihoods_cal_initial(particles+i*particle_offset_size, dnest_arg);
log_likelihoods[i].tiebreaker = dnest_rand();
level_assignments[i] = 0;
}
/*ModelType proposal;
printf("%f %f %f \n", particles[0].param[0], particles[0].param[1], particles[0].param[2] );
proposal = particles[0];
printf("%f %f %f \n", proposal.param[0], proposal.param[1], proposal.param[2] );*/
}
void finalise()
{
free(particles);
free(above);
free(log_likelihoods);
free(level_assignments);
free(levels);
free(account_unaccepts);
if(dnest_flag_limits == 1)
free(limits);
gsl_rng_free(dnest_gsl_r);
free(dnest_perturb_accept);
printf("# Finalizing dnest.\n");
}
void options_load(int max_num_saves, double ptol)
{
//sscanf(buf, "%d", &options.num_particles);
options.num_particles = 2;
//fgets(buf, BUF_MAX_LENGTH, fp);
//sscanf(buf, "%d", &options.new_level_interval);
options.new_level_interval = options.num_particles * dnest_num_params*10;
//fgets(buf, BUF_MAX_LENGTH, fp);
//sscanf(buf, "%d", &options.save_interval);
options.save_interval = options.new_level_interval;
//fgets(buf, BUF_MAX_LENGTH, fp);
//sscanf(buf, "%d", &options.thread_steps);
options.thread_steps = options.new_level_interval;
//fgets(buf, BUF_MAX_LENGTH, fp);
//sscanf(buf, "%d", &options.max_num_levels);
options.max_num_levels = 0;
//fgets(buf, BUF_MAX_LENGTH, fp);
//sscanf(buf, "%lf", &options.lambda);
options.lambda = 10.0;
//fgets(buf, BUF_MAX_LENGTH, fp);
//sscanf(buf, "%lf", &options.beta);
options.beta = 100.0;
//fgets(buf, BUF_MAX_LENGTH, fp);
//sscanf(buf, "%d", &options.max_num_saves);
options.max_num_saves = max_num_saves;
options.max_ptol = ptol;
//fgets(buf, BUF_MAX_LENGTH, fp);
//sscanf(buf, "%s", options.sample_file);
strcpy(options.sample_file, dnest_sample_dir);
strcat(options.sample_file,"/sample");
strcat(options.sample_file, dnest_sample_tag);
strcat(options.sample_file, ".txt");
strcat(options.sample_file, dnest_sample_postfix);
//fgets(buf, BUF_MAX_LENGTH, fp);
//sscanf(buf, "%s", options.sample_info_file);
strcpy(options.sample_info_file, dnest_sample_dir);
strcat(options.sample_info_file,"/sample_info");
strcat(options.sample_info_file, dnest_sample_tag);
strcat(options.sample_info_file, ".txt");
strcat(options.sample_info_file, dnest_sample_postfix);
//fgets(buf, BUF_MAX_LENGTH, fp);
//sscanf(buf, "%s", options.levels_file);
strcpy(options.levels_file, dnest_sample_dir);
strcat(options.levels_file,"/levels");
strcat(options.levels_file, dnest_sample_tag);
strcat(options.levels_file, ".txt");
strcat(options.levels_file, dnest_sample_postfix);
//fgets(buf, BUF_MAX_LENGTH, fp);
//sscanf(buf, "%s", options.sampler_state_file);
strcpy(options.sampler_state_file, dnest_sample_dir);
strcat(options.sampler_state_file,"/sampler_state");
strcat(options.sampler_state_file, dnest_sample_tag);
strcat(options.sampler_state_file, ".txt");
strcat(options.sampler_state_file, dnest_sample_postfix);
//fgets(buf, BUF_MAX_LENGTH, fp);
//sscanf(buf, "%s", options.posterior_sample_file);
strcpy(options.posterior_sample_file, dnest_sample_dir);
strcat(options.posterior_sample_file,"/posterior_sample");
strcat(options.posterior_sample_file, dnest_sample_tag);
strcat(options.posterior_sample_file, ".txt");
strcat(options.posterior_sample_file, dnest_sample_postfix);
//fgets(buf, BUF_MAX_LENGTH, fp);
//sscanf(buf, "%s", options.posterior_sample_info_file);
strcpy(options.posterior_sample_info_file, dnest_sample_dir);
strcat(options.posterior_sample_info_file,"/posterior_sample_info");
strcat(options.posterior_sample_info_file, dnest_sample_tag);
strcat(options.posterior_sample_info_file, ".txt");
strcat(options.posterior_sample_info_file, dnest_sample_postfix);
//fgets(buf, BUF_MAX_LENGTH, fp);
//sscanf(buf, "%s", options.limits_file);
strcpy(options.limits_file, dnest_sample_dir);
strcat(options.limits_file,"/limits");
strcat(options.limits_file, dnest_sample_tag);
strcat(options.limits_file, ".txt");
strcat(options.limits_file, dnest_sample_postfix);
// check options.
if(options.new_level_interval < options.thread_steps)
{
printf("# incorrect options:\n");
printf("# new level interval should be equal to or larger than");
printf(" totaltask * thread step.\n");
exit(0);
}
/* strcpy(options.sample_file, "sample.txt");
strcpy(options.sample_info_file, "sample_info.txt");
strcpy(options.levels_file, "levels.txt");
strcpy(options.sampler_state_file, "sampler_state.txt");*/
}
double mod(double y, double x)
{
if(x > 0.0)
{
return (y/x - floor(y/x))*x;
}
else if(x == 0.0)
{
return 0.0;
}
else
{
printf("Warning in mod(double, double) %e\n", x);
exit(0);
}
}
void dnest_wrap(double *x, double min, double max)
{
*x = mod(*x - min, max - min) + min;
}
void wrap_limit(double *x, double min, double max)
{
*x = fmax(fmin(*x, max), min);
}
int mod_int(int y, int x)
{
if(y >= 0)
return y - (y/x)*x;
else
return (x-1) - mod_int(-y-1, x);
}
double dnest_randh()
{
return pow(10.0, 1.5 - 3.0*fabs(gsl_ran_tdist(dnest_gsl_r, 2))) * gsl_ran_ugaussian(dnest_gsl_r);
}
double dnest_rand()
{
return gsl_rng_uniform(dnest_gsl_r);
}
int dnest_rand_int(int size)
{
return gsl_rng_uniform_int(dnest_gsl_r, size);
}
double dnest_randn()
{
return gsl_ran_ugaussian(dnest_gsl_r);
}
int dnest_cmp(const void *pa, const void *pb)
{
LikelihoodType *a = (LikelihoodType *)pa;
LikelihoodType *b = (LikelihoodType *)pb;
// in decesending order
if(a->value > b->value)
return false;
if( a->value == b->value && a->tiebreaker > b->tiebreaker)
return false;
return true;
}
int dnest_get_size_levels()
{
return size_levels;
}
int dnest_get_which_level_update()
{
return dnest_which_level_update;
}
int dnest_get_which_particle_update()
{
return dnest_which_particle_update;
}
unsigned int dnest_get_which_num_saves()
{
return num_saves;
}
unsigned int dnest_get_count_saves()
{
return count_saves;
}
unsigned long long int dnest_get_count_mcmc_steps()
{
return count_mcmc_steps;
}
void dnest_get_posterior_sample_file(char *fname)
{
strcpy(fname, options.posterior_sample_file);
return;
}
/*
* version check
*
* 1: greater
* 0: equal
* -1: lower
*/
int dnest_check_version(char *version_str)
{
int major, minor, patch;
sscanf(version_str, "%d.%d.%d", &major, &minor, &patch);
if(major > DNEST_MAJOR_VERSION)
return 1;
if(major < DNEST_MAJOR_VERSION)
return -1;
if(minor > DNEST_MINOR_VERSION)
return 1;
if(minor < DNEST_MINOR_VERSION)
return -1;
if(patch > DNEST_PATCH_VERSION)
return 1;
if(patch > DNEST_PATCH_VERSION)
return -1;
return 0;
}
void dnest_check_fptrset(DNestFptrSet *fptrset)
{
if(fptrset->from_prior == NULL)
{
printf("\"from_prior\" function is not defined.\n");
exit(0);
}
if(fptrset->print_particle == NULL)
{
//printf("\"print_particle\" function is not defined. \
// \nSet to be default function in dnest.\n");
fptrset->print_particle = dnest_print_particle;
}
if(fptrset->read_particle == NULL)
{
//printf("\"read_particle\" function is not defined. \
// \nSet to be default function in dnest.\n");
fptrset->read_particle = dnest_read_particle;
}
if(fptrset->log_likelihoods_cal == NULL)
{
printf("\"log_likelihoods_cal\" function is not defined.\n");
exit(0);
}
if(fptrset->log_likelihoods_cal_initial == NULL)
{
//printf("\"log_likelihoods_cal_initial\" function is not defined. \
// \nSet to the same as \"log_likelihoods_cal\" function.\n");
fptrset->log_likelihoods_cal_initial = fptrset->log_likelihoods_cal;
}
if(fptrset->log_likelihoods_cal_restart == NULL)
{
//printf("\"log_likelihoods_cal_restart\" function is not defined. \
// \nSet to the same as \"log_likelihoods_cal\" function.\n");
fptrset->log_likelihoods_cal_restart = fptrset->log_likelihoods_cal;
}
if(fptrset->perturb == NULL)
{
printf("\"perturb\" function is not defined.\n");
exit(0);
}
if(fptrset->restart_action == NULL)
{
//printf("\"restart_action\" function is not defined.\
// \nSet to the default function in dnest.\n");
fptrset->restart_action = dnest_restart_action;
}
if(fptrset->accept_action == NULL)
{
//printf("\"accept_action\" function is not defined.\
// \nSet to the default function in dnest.\n");
fptrset->accept_action = dnest_accept_action;
}
if(fptrset->kill_action == NULL)
{
//printf("\"kill_action\" function is not defined.\
// \nSet to the default function in dnest.\n");
fptrset->kill_action = dnest_kill_action;
}
return;
}
DNestFptrSet * dnest_malloc_fptrset()
{
DNestFptrSet * fptrset;
fptrset = (DNestFptrSet *)malloc(sizeof(DNestFptrSet));
fptrset->from_prior = NULL;
fptrset->log_likelihoods_cal = NULL;
fptrset->log_likelihoods_cal_initial = NULL;
fptrset->log_likelihoods_cal_restart = NULL;
fptrset->perturb = NULL;
fptrset->print_particle = NULL;
fptrset->read_particle = NULL;
fptrset->restart_action = NULL;
fptrset->accept_action = NULL;
fptrset->kill_action = NULL;
return fptrset;
}
void dnest_free_fptrset(DNestFptrSet * fptrset)
{
free(fptrset);
return;
}
/*!
* Save sampler state for later restart.
*/
void dnest_save_restart()
{
FILE *fp;
int i, j;
void *particles_all;
LikelihoodType *log_likelihoods_all;
unsigned int *level_assignments_all;
char str[200];
sprintf(str, "%s_%d", file_save_restart, count_saves);
fp = fopen(str, "wb");
if(fp == NULL)
{
fprintf(stderr, "# Error: Cannot open file %s. \n", file_save_restart);
exit(0);
}
printf("# Save restart data to file %s.\n", str);
//fprintf(fp, "%d %d\n", count_saves, count_mcmc_steps);
//fprintf(fp, "%d\n", size_levels_combine);
fwrite(&count_saves, sizeof(int), 1, fp);
fwrite(&count_mcmc_steps, sizeof(int), 1, fp);
fwrite(&size_levels, sizeof(int), 1, fp);
for(i=0; i<size_levels; i++)
{
//fprintf(fp, "%14.12g %14.12g %f %llu %llu %llu %llu\n", levels_combine[i].log_X, levels_combine[i].log_likelihood.value,
// levels_combine[i].log_likelihood.tiebreaker, levels_combine[i].accepts,
// levels_combine[i].tries, levels[i].exceeds, levels_combine[i].visits);
fwrite(&levels[i], sizeof(Level), 1, fp);
}
for(i=0; i<options.num_particles; i++)
{
//fprintf(fp, "%d %e %f\n", level_assignments_all[j*options.num_particles + i],
// log_likelihoods_all[j*options.num_particles + i].value,
// log_likelihoods_all[j*options.num_particles + i].tiebreaker);
fwrite(&level_assignments[j*options.num_particles + i], sizeof(int), 1, fp);
fwrite(&log_likelihoods[j*options.num_particles + i], sizeof(LikelihoodType), 1, fp);
}
if(dnest_flag_limits == 1)
{
for(i=0; i<size_levels; i++)
{
//fprintf(fp, "%d ", i);
for(j=0; j<particle_offset_double; j++)
{
//fprintf(fp, "%f %f ", limits[i*2*particle_offset_double+j*2], limits[i*2*particle_offset_double+j*2+1]);
fwrite(&limits[i*2*particle_offset_double+j*2], sizeof(double), 2, fp);
}
//fprintf(fp, "\n");
}
}
for(i=0; i<options.num_particles; i++)
{
//print_particle(fp, particles_all + (j * options.num_particles + i) * particle_offset_size);
fwrite(particles + (j * options.num_particles + i) * particle_offset_size, dnest_size_of_modeltype, 1, fp);
}
fclose(fp);
restart_action(0);
}
void dnest_restart()
{
FILE *fp;
int i, j;
void *particles_all;
unsigned int *level_assignments_all;
LikelihoodType *log_likelihoods_all;
void *particle;
fp = fopen(file_restart, "rb");
if(fp == NULL)
{
fprintf(stderr, "# Error: Cannot open file %s. \n", file_restart);
exit(0);
}
printf("# Reading %s\n", file_restart);
fread(&count_saves, sizeof(int), 1, fp);
fread(&count_mcmc_steps, sizeof(int), 1, fp);
fread(&size_levels, sizeof(int), 1, fp);
/* consider that the newly input max_num_levels may be different from the save one */
if(options.max_num_levels != 0)
{
if(size_levels > options.max_num_levels)
{
printf("# input max_num_levels %d smaller than the one in restart data %d.\n", options.max_num_levels, size_levels);
size_levels = options.max_num_levels;
}
}
// read levels
for(i=0; i<size_levels; i++)
{
if(i<size_levels) // not read all the levels
fread(&levels[i], sizeof(Level), 1, fp);
else
fseek(fp, sizeof(Level), SEEK_CUR); /* offset the file point */
}
memcpy(levels, levels, size_levels * sizeof(Level));
// read level assignment
for(i=0; i<options.num_particles; i++)
{
fread(&level_assignments[j*options.num_particles + i], sizeof(int), 1, fp);
fread(&log_likelihoods[j*options.num_particles + i], sizeof(LikelihoodType), 1, fp);
/* reset the level assignment that exceeds the present maximum level */
if(level_assignments[j*options.num_particles + i] > size_levels -1)
{
level_assignments[j*options.num_particles + i] = size_levels - 1;
}
}
// read limits
if(dnest_flag_limits == 1)
{
for(i=0; i<size_levels; i++)
{
if(i < size_levels)
{
for(j=0; j<particle_offset_double; j++)
{
fread(&limits[i*2*particle_offset_double+j*2], sizeof(double), 2, fp);
}
}
else
{
fseek(fp, sizeof(double) * 2 * particle_offset_double, SEEK_CUR); /* offset the file point */
}
}
}
// read particles
for(i=0; i<options.num_particles; i++)
{
particle = (particles + (j * options.num_particles + i) * dnest_size_of_modeltype);
fread(particle, dnest_size_of_modeltype, 1, fp);
}
fclose(fp);
if(count_saves > options.max_num_saves)
{
printf("# Number of samples already larger than the input number, exit!\n");
exit(0);
}
num_saves = (int)fmax(0.02*(options.max_num_saves-count_saves), 1.0); /* reset num_saves */
num_saves_restart = (int)fmax(0.2 * (options.max_num_saves-count_saves), 1.0); /* reset num_saves_restart */
restart_action(1);
for(i=0; i<options.num_particles; i++)
{
dnest_which_particle_update = i;
dnest_which_level_update = level_assignments[i];
//printf("%d %d %f\n", thistask, i, log_likelihoods[i].value);
log_likelihoods[i].value = log_likelihoods_cal_restart(particles+i*particle_offset_size, dnest_arg);
//printf("%d %d %f\n", thistask, i, log_likelihoods[i].value);
//due to randomness, the original level assignment may be incorrect. re-asign the level
while(log_likelihoods[i].value < levels[level_assignments[i]].log_likelihood.value)
{
printf("# level assignment decrease %d %f %f %d.\n", i, log_likelihoods[i].value,
levels[level_assignments[i]].log_likelihood.value, level_assignments[i]);
level_assignments[i]--;
}
}
return;
}
void dnest_print_particle(FILE *fp, const void *model, const void *arg)
{
int i;
double *pm = (double *)model;
for(i=0; i<dnest_num_params; i++)
{
fprintf(fp, "%e ", pm[i] );
}
fprintf(fp, "\n");
return;
}
void dnest_read_particle(FILE *fp, void *model)
{
int j;
double *psample = (double *)model;
for(j=0; j < dnest_num_params; j++)
{
if(fscanf(fp, "%lf", psample+j) < 1)
{
printf("%f\n", *psample);
fprintf(stderr, "#Error: Cannot read file %s.\n", options.sample_file);
exit(0);
}
}
return;
}
void dnest_restart_action(int iflag)
{
return;
}
void dnest_accept_action()
{
return;
}
void dnest_kill_action(int i, int i_copy)
{
return;
}
| {
"alphanum_fraction": 0.6566070334,
"avg_line_length": 26.3093841642,
"ext": "c",
"hexsha": "f82a64930ba2fa3f0e93806d8ebad0852a14698a",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2021-02-06T11:26:06.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-02-05T02:01:57.000Z",
"max_forks_repo_head_hexsha": "e232531b5c6f7817b6e3bd34dbb31463807ae2b0",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "LiyrAstroph/pyCALI",
"max_forks_repo_path": "src/pycali/cdnest/dnest.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "e232531b5c6f7817b6e3bd34dbb31463807ae2b0",
"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": "LiyrAstroph/pyCALI",
"max_issues_repo_path": "src/pycali/cdnest/dnest.c",
"max_line_length": 127,
"max_stars_count": 3,
"max_stars_repo_head_hexsha": "e232531b5c6f7817b6e3bd34dbb31463807ae2b0",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "LiyrAstroph/PyCALI",
"max_stars_repo_path": "src/pycali/cdnest/dnest.c",
"max_stars_repo_stars_event_max_datetime": "2022-01-13T09:23:59.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-01-14T01:32:41.000Z",
"num_tokens": 10224,
"size": 35886
} |
/** @file */
#ifndef __CCL_F2D_H_INCLUDED__
#define __CCL_F2D_H_INCLUDED__
#include <gsl/gsl_spline.h>
#include <gsl/gsl_interp2d.h>
#include <gsl/gsl_spline2d.h>
CCL_BEGIN_DECLS
//f2d extrapolation types for early times
typedef enum ccl_f2d_extrap_growth_t
{
ccl_f2d_cclgrowth = 401, //Use CCL's linear growth
ccl_f2d_customgrowth = 402, //Use a custom growth function
ccl_f2d_constantgrowth = 403, //Use a constant growth factor
ccl_f2d_no_extrapol = 404, //Do not extrapolate, just throw an exception
} ccl_f2d_extrap_growth_t;
//f2d interpolation types
typedef enum ccl_f2d_interp_t
{
ccl_f2d_3 = 303, //Bicubic interpolation
} ccl_f2d_interp_t;
/**
* Struct containing a 2D power spectrum
*/
typedef struct {
double lkmin,lkmax; /**< Edges in log(k)*/
double amin,amax; /**< Edges in a*/
int is_factorizable; /**< Is this factorizable into k- and a-dependent functions? */
int is_k_constant; /**< no k-dependence, just return 1*/
int is_a_constant; /**< no a-dependence, just return 1*/
int extrap_order_lok; /**< Order of extrapolating polynomial in log(k) for low k (0, 1 or 2)*/
int extrap_order_hik; /**< Order of extrapolating polynomial in log(k) for high k (0, 1 or 2)*/
ccl_f2d_extrap_growth_t extrap_linear_growth; /**< Extrapolation type at high redshifts*/
int is_log; /**< Do I hold the values of log(f(k,a))?*/
double (*growth)(double); /**< Custom extrapolating growth function*/
double growth_factor_0; /**< Constant extrapolating growth factor*/
int growth_exponent; /**< Power to which growth should be exponentiated*/
gsl_spline *fk; /**< Spline holding the values of the k-dependent factor*/
gsl_spline *fa; /**< Spline holding the values of the a-dependent factor*/
gsl_spline2d *fka; /**< Spline holding the values of f(k,a)*/
} ccl_f2d_t;
/**
* Create a ccl_f2d_t structure.
* @param na number of elements in a_arr.
* @param a_arr array of scale factor values at which the function is defined. The array should be ordered.
* @param nk number of elements of lk_arr.
* @param lk_arr array of logarithmic wavenumbers at which the function is defined (i.e. this array contains ln(k), NOT k). The array should be ordered.
* @param fka_arr array of size na * nk containing the 2D function. The 2D ordering is such that fka_arr[ia*nk+ik] = f(k=exp(lk_arr[ik]),a=a_arr[ia]).
* @param fk_arr array of size nk containing the k-dependent part of the function. Only relevant if is_factorizable is true.
* @param fa_arr array of size na containing the a-dependent part of the function. Only relevant if is_factorizable is true.
* @param is_factorizable if not 0, fk_arr and fa_arr will be used as 1-D arrays to construct a factorizable 2D function.
* @param extrap_order_lok Order of the polynomial that extrapolates on wavenumbers smaller than the minimum of lk_arr. Allowed values: 0 (constant), 1 (linear extrapolation) and 2 (quadratic extrapolation). Extrapolation happens in ln(k).
* @param extrap_order_hik Order of the polynomial that extrapolates on wavenumbers larger than the maximum of lk_arr. Allowed values: 0 (constant), 1 (linear extrapolation) and 2 (quadratic extrapolation). Extrapolation happens in ln(k).
* @param extrap_linear_growth: ccl_f2d_extrap_growth_t value defining how the function with scale factors below the interpolation range. Allowed values: ccl_f2d_cclgrowth (scale with the CCL linear growth factor), ccl_f2d_customgrowth (scale with a custom function of redshift passed through `growth`), ccl_f2d_constantgrowth (scale by multiplying the function at the earliest available scale factor by a constant number, defined by `growth_factor_0`), ccl_f2d_no_extrapol (throw an error if the function is ever evaluated outside the interpolation range in a). Note that, above the interpolation range (i.e. for low redshifts), the function will be assumed constant.
* @param is_fka_log: if not zero, `fka_arr` contains ln(f(k,a)) instead of f(k,a). If the function is factorizable, then `fk_arr` holds ln(K(k)) and `fa_arr` holds ln(A(a)), where f(k,a)=K(k)*A(a).
* @param growth: custom growth function. Irrelevant if extrap_linear_growth!=ccl_f2d_customgrowth.
* @param growth_factor_0: custom growth function. Irrelevant if extrap_linear_growth!=ccl_f2d_constantgrowth.
* @param growth_exponent: power to which the extrapolating growth factor should be exponentiated when extrapolating (e.g. usually 2 for linear power spectra).
* @param interp_type: 2D interpolation method. Currently only ccl_f2d_3 is implemented (bicubic interpolation).
* @param status Status flag. 0 if there are no errors, nonzero otherwise.
*/
ccl_f2d_t *ccl_f2d_t_new(int na,double *a_arr,
int nk,double *lk_arr,
double *fka_arr,
double *fk_arr,
double *fa_arr,
int is_factorizable,
int extrap_order_lok,
int extrap_order_hik,
ccl_f2d_extrap_growth_t extrap_linear_growth,
int is_fka_log,
double (*growth)(double),
double growth_factor_0,
int growth_exponent,
ccl_f2d_interp_t interp_type,
int *status);
/**
* Evaluate 2D function of k and a defined by ccl_f2d_t structure.
* @param fka ccl_f2d_t structure defining f(k,a).
* @param lk Natural logarithm of the wavenumber.
* @param a Scale factor.
* @param cosmo ccl_cosmology structure, only needed if evaluating f(k,a) at small scale factors outside the interpolation range, and if fka was initialized with extrap_linear_growth = ccl_f2d_cclgrowth.
* @param status Status flag. 0 if there are no errors, nonzero otherwise.
*/
double ccl_f2d_t_eval(ccl_f2d_t *fka,double lk,double a,void *cosmo,
int *status);
/**
* F2D structure destructor.
* Frees up all memory associated with a f2d structure.
* @param fka Structure to be freed.
*/
void ccl_f2d_t_free(ccl_f2d_t *fka);
CCL_END_DECLS
#endif
| {
"alphanum_fraction": 0.7567521073,
"avg_line_length": 55.3619047619,
"ext": "h",
"hexsha": "a51892ae3b3ce048473fff6fe7376bb6b76d6343",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2021-02-10T07:35:07.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-02-10T07:35:07.000Z",
"max_forks_repo_head_hexsha": "3a5f9dec72c6ce602ac8b11ceed0ee6c0460a926",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "benediktdiemer/CCL",
"max_forks_repo_path": "include/ccl_f2d.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "3a5f9dec72c6ce602ac8b11ceed0ee6c0460a926",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "benediktdiemer/CCL",
"max_issues_repo_path": "include/ccl_f2d.h",
"max_line_length": 668,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "3a5f9dec72c6ce602ac8b11ceed0ee6c0460a926",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "benediktdiemer/CCL",
"max_stars_repo_path": "include/ccl_f2d.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1597,
"size": 5813
} |
#pragma once
#pragma warning(disable:4201) // nonstandard extension used : nameless struct/union
#pragma warning(disable:4238) // nonstandard extension used : class rvalue used as lvalue
#pragma warning(disable:4324) // structure was padded due to __declspec(align())
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include <windows.h>
#include <d3d12.h>
#pragma comment(lib, "d3d12.lib")
#pragma comment(lib, "dxgi.lib")
#define MY_IID_PPV_ARGS IID_PPV_ARGS
#define D3D12_GPU_VIRTUAL_ADDRESS_NULL ((D3D12_GPU_VIRTUAL_ADDRESS)0)
#define D3D12_GPU_VIRTUAL_ADDRESS_UNKNOWN ((D3D12_GPU_VIRTUAL_ADDRESS)-1)
#pragma region
#include <d3dx12.h>
#include <d3d12shader.h>
#include <d3dcompiler.h>
#pragma endregion
#pragma region
#pragma comment (lib, "d3dcompiler.lib")
#pragma endregion
#include <cstdint>
#include <cstdio>
#include <cstdarg>
#include <vector>
#include <memory>
#include <string>
#include <exception>
#include <numeric>
#include <wrl.h>
#include <ppltasks.h>
#include <gsl\gsl>
#include "Utility.h"
#include "VectorMath.h"
#include "EngineTuning.h"
#include "EngineProfiling.h"
template< typename T >
using NotNull = gsl::not_null< T >;
#define SHADER_ARGS(shader) (shader), \
sizeof(shader)
template<typename T, std::size_t N>
struct Array :public std::array<T, N>
{
static inline std::function<T(T, T)> multiply = [](T priview, T current) {
return priview * current;
};
public:
T product()
{
return std::accumulate(begin(), end(), 1, multiply);
}
};
using U8 = uint8_t;
using U32 = uint32_t;
using U32x1 = U32;
using U32x2 = Array<U32, 2>;
using U32x3 = Array<U32, 3>;
using U32x4 = Array<U32, 4>;
using F32 = float;
using F32x2 = Array<F32, 2>;
using F32x3 = Array<F32, 3>;
using F32x4 = Array<F32, 4>;
#pragma region voxel
#define VOXEL_RESOLUTION 128
#define CLIP_REGION_COUNT 6
#define FACE_COUNT 6
#pragma endregion
template <typename T, size_t N > Array<T, N> DivideByMultiple(Array <T, N> value, Array <T, N> alignment)
{
Array <T, N> result;
for (size_t i = 0; i < N; i++)
{
result[i] = (T)((value[i] + alignment[i] - 1) / alignment[i]);
}
return result;
} | {
"alphanum_fraction": 0.6987522282,
"avg_line_length": 22.2178217822,
"ext": "h",
"hexsha": "6b2d2cb9936f289a9c2e9f767c79bf24b1e1501a",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2020-04-08T05:22:40.000Z",
"max_forks_repo_forks_event_min_datetime": "2020-01-21T13:11:34.000Z",
"max_forks_repo_head_hexsha": "3c75fc8e6367816882955888a0e9ea7021d46a62",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "sienaiwun/D3D12Practice",
"max_forks_repo_path": "Core/pch.h",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "3c75fc8e6367816882955888a0e9ea7021d46a62",
"max_issues_repo_issues_event_max_datetime": "2020-04-08T03:27:46.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-03-30T05:20:30.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "sienaiwun/D3D12Practice",
"max_issues_repo_path": "Core/pch.h",
"max_line_length": 105,
"max_stars_count": 9,
"max_stars_repo_head_hexsha": "3c75fc8e6367816882955888a0e9ea7021d46a62",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "sienaiwun/D3D12Practice",
"max_stars_repo_path": "Core/pch.h",
"max_stars_repo_stars_event_max_datetime": "2022-02-23T03:51:11.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-01-21T13:11:01.000Z",
"num_tokens": 656,
"size": 2244
} |
#include <string.h>
#include <alloca.h>
#include <math.h>
#include <mpi.h>
#include <kdcount/kdtree.h>
#include <fastpm/libfastpm.h>
#include <gsl/gsl_rng.h>
#include <fastpm/prof.h>
#include <fastpm/logging.h>
#include <fastpm/store.h>
#include <fastpm/fof.h>
#include "pmpfft.h"
#include "pm2lpt.h"
#include "pmghosts.h"
#include "vpm.h"
#include <fastpm/io.h>
#include <fastpm/string.h>
#include <bigfile-mpi.h>
//#define FASTPM_FOF_DEBUG
struct FastPMFOFFinderPrivate {
int ThisTask;
int NTask;
double * boxsize;
MPI_Comm comm;
};
/* creating a kdtree struct
* for store with np particles starting from start.
* */
struct KDTreeNodeBuffer {
void * mem;
void * base;
char * ptr;
char * end;
struct KDTreeNodeBuffer * prev;
};
static void *
_kdtree_buffered_malloc(void * userdata, size_t size)
{
struct KDTreeNodeBuffer ** pbuffer = (struct KDTreeNodeBuffer**) userdata;
struct KDTreeNodeBuffer * buffer = *pbuffer;
if(buffer->base == NULL || buffer->ptr + size >= buffer->end) {
struct KDTreeNodeBuffer * newbuffer = malloc(sizeof(newbuffer[0]));
newbuffer->mem = buffer->mem;
size_t newsize = 1024 * 1024 * 4; /* 4 MB for each block */
if(newsize < size) {
newsize = size;
}
newbuffer->base = fastpm_memory_alloc(buffer->mem, "KDTreeBase", newsize, FASTPM_MEMORY_STACK);
newbuffer->ptr = newbuffer->base;
newbuffer->end = newbuffer->base + newsize;
newbuffer->prev = buffer;
*pbuffer = newbuffer;
buffer = newbuffer;
}
void * r = buffer->ptr;
buffer->ptr += size;
return r;
}
static void
_kdtree_buffered_free(void * userdata, size_t size, void * ptr)
{
/* do nothing; */
}
static
KDNode *
_create_kdtree (KDTree * tree, int thresh,
FastPMStore ** stores, int nstore,
double boxsize[])
{
/* if boxsize is NULL the tree will be non-periodic. */
/* the allocator; started empty. */
struct KDTreeNodeBuffer ** pbuffer = malloc(sizeof(void*));
struct KDTreeNodeBuffer * headbuffer = malloc(sizeof(headbuffer[0]));
*pbuffer = headbuffer;
headbuffer->mem = stores[0]->mem;
headbuffer->base = NULL;
headbuffer->prev = NULL;
int s;
ptrdiff_t i;
tree->userdata = pbuffer;
tree->input.dims[0] = 0;
for(s = 0; s < nstore; s ++) {
tree->input.dims[0] += stores[s]->np;
}
tree->input.dims[1] = 3;
if(tree->input.dims[0] < stores[0]->np_upper) {
/* if the first store is big enough, use it for the tree */
tree->input.buffer = (void*) &stores[0]->x[0][0];
} else {
/* otherwise, allocate a big buffer and make a copy */
tree->input.buffer = _kdtree_buffered_malloc(pbuffer,
tree->input.dims[0] * sizeof(stores[0]->x[0]));
memcpy(tree->input.buffer, &stores[0]->x[0][0], stores[0]->np * sizeof(stores[0]->x[0]));
}
i = stores[0]->np;
/* copy the other positions to the base pointer. */
for(s = 1; s < nstore; s ++) {
memcpy(((char*) tree->input.buffer) + i * sizeof(stores[0]->x[0]),
&stores[s]->x[0][0],
stores[s]->np * sizeof(stores[0]->x[0]));
i = i + stores[s]->np;
}
tree->input.strides[0] = sizeof(stores[0]->x[0]);
tree->input.strides[1] = sizeof(stores[0]->x[0][0]);
tree->input.elsize = sizeof(stores[0]->x[0][0]);
tree->input.cast = NULL;
tree->ind = _kdtree_buffered_malloc(pbuffer, tree->input.dims[0] * sizeof(tree->ind[0]));
for(i = 0; i < tree->input.dims[0]; i ++) {
tree->ind[i] = i;
}
tree->ind_size = tree->input.dims[0];
tree->malloc = _kdtree_buffered_malloc;
tree->free = _kdtree_buffered_free;
tree->thresh = thresh;
tree->boxsize = boxsize;
KDNode * root = kd_build(tree);
fastpm_info("Creating KDTree with %td nodes for %td particles\n", tree->size, tree->ind_size);
return root;
}
void
_free_kdtree (KDTree * tree, KDNode * root)
{
kd_free(root);
struct KDTreeNodeBuffer * buffer, *q, **pbuffer = tree->userdata;
for(buffer = *pbuffer; buffer; buffer = q) {
if(buffer->base)
fastpm_memory_free(buffer->mem, buffer->base);
q = buffer->prev;
free(buffer);
}
free(pbuffer);
}
void
fastpm_fof_init(FastPMFOFFinder * finder, FastPMStore * store, PM * pm)
{
finder->priv = malloc(sizeof(FastPMFOFFinderPrivate));
finder->p = store;
finder->pm = pm;
finder->event_handlers = NULL;
if (finder->periodic)
finder->priv->boxsize = pm_boxsize(pm);
else
finder->priv->boxsize = NULL;
finder->priv->comm = pm_comm(pm);
MPI_Comm comm = finder->priv->comm;
MPI_Comm_rank(comm, &finder->priv->ThisTask);
MPI_Comm_size(comm, &finder->priv->NTask);
}
static void
_fof_local_find(FastPMFOFFinder * finder,
FastPMStore * p,
PMGhostData * pgd,
ptrdiff_t * head, double linkinglength)
{
/* local find of p and the the ghosts */
KDTree tree;
FastPMStore * stores[2] = {p, pgd->p};
KDNode * root = _create_kdtree(&tree, finder->kdtree_thresh, stores, 2, finder->priv->boxsize);
kd_fof(root, linkinglength, head);
_free_kdtree(&tree, root);
}
static int
_merge(uint64_t * src, ptrdiff_t isrc, uint64_t * dest, ptrdiff_t idest, ptrdiff_t * head)
{
int merge = 0;
ptrdiff_t j = head[idest];
if(src[isrc] < dest[j]) {
merge = 1;
}
if(merge) {
dest[j] = src[isrc];
}
return merge;
}
struct reduce_fof_data {
ptrdiff_t * head;
size_t nmerged;
};
static void
FastPMReduceFOF(FastPMStore * src, ptrdiff_t isrc, FastPMStore * dest, ptrdiff_t idest, int ci, void * userdata)
{
struct reduce_fof_data * data = userdata;
data->nmerged += _merge(src->minid, isrc, dest->minid, idest, data->head);
}
static void
_fof_global_merge(
FastPMFOFFinder * finder,
FastPMStore * p,
PMGhostData * pgd,
uint64_t * minid,
ptrdiff_t * head
)
{
ptrdiff_t i;
MPI_Comm comm = finder->priv->comm;
size_t npmax = p->np;
MPI_Allreduce(MPI_IN_PLACE, &npmax, 1, MPI_LONG, MPI_MAX, comm);
/* initialize minid, used as a global tag of groups as we merge */
for(i = 0; i < p->np; i ++) {
/* assign unique ID to each particle; could use a better scheme with true offsets */
minid[i] = i + finder->priv->ThisTask * npmax;
#ifdef FASTPM_FOF_DEBUG
/* for debugging, overwrite the previous unique ID with the true ID of particles */
minid[i] = p->id[i];
#endif
}
/* send minid */
p->minid = minid; /* only send up to p->np */
pm_ghosts_send(pgd, COLUMN_MINID);
p->minid = NULL;
/* copy over to minid for storage; FIXME: allow overriding */
for(i = 0; i < pgd->p->np; i ++) {
minid[i + p->np] = pgd->p->minid[i];
}
/* reduce the minid of the head items according to the local connection. */
while(1) {
size_t nmerge = 0;
for(i = 0; i < p->np + pgd->p->np; i ++) {
nmerge += _merge(minid, i, minid, i, head);
}
if(nmerge == 0) break;
}
#ifdef FASTPM_FOF_DEBUG
{
FILE * fp = fopen(fastpm_strdup_printf("dump-pos-%d.f8", finder->priv->ThisTask), "w");
fwrite(p->x, p->np, sizeof(double) * 3, fp);
fwrite(pgd->p->x, pgd->p->np, sizeof(double) * 3, fp);
fclose(fp);
}
{
FILE * fp = fopen(fastpm_strdup_printf("dump-id-%d.f8", finder->priv->ThisTask), "w");
fwrite(p->id, p->np, sizeof(int64_t), fp);
fwrite(pgd->p->id, pgd->p->np, sizeof(int64_t) * 3, fp);
fclose(fp);
}
#endif
int iter = 0;
while(1) {
/* prepare the communication buffer, every ghost has
* the minid and task of the current head. such that
* they will connect to the other ranks correctly */
for(i = 0; i < pgd->p->np; i ++) {
pgd->p->minid[i] = minid[head[i + p->np]];
}
/* at this point all items on ghosts have local minid and task, ready to reduce */
struct reduce_fof_data data = {
.head = head,
.nmerged = 0,
};
/* merge ghosts into the p, reducing the MINID on p */
p->minid = minid; /* only update up to p->np */
pm_ghosts_reduce(pgd, COLUMN_MINID, FastPMReduceFOF, &data);
p->minid = NULL;
size_t nmerged = data.nmerged;
/* at this point all items on p->fof with head[i] = i have present minid and task */
MPI_Allreduce(MPI_IN_PLACE, &nmerged, 1, MPI_LONG, MPI_SUM, comm);
MPI_Barrier(comm);
fastpm_info("FOF reduction iteration %d : merged %td crosslinks\n", iter, nmerged);
if(nmerged == 0) break;
for(i = 0; i < p->np + pgd->p->np; i ++) {
if(minid[i] < minid[head[i]]) {
fastpm_raise(-1, "p->fof invariance is broken i = %td np = %td\n", i, p->np);
}
}
iter++;
}
/* previous loop only updated head[i]; now make sure every particles has the correct minid. */
for(i = 0; i < p->np + pgd->p->np; i ++) {
minid[i] = minid[head[i]];
}
#ifdef FASTPM_FOF_DEBUG
{
for(i = 0; i < p->np + pgd->p->np ; i ++) {
uint64_t id = i <p->np?p->id[i]:pgd->p->id[i - p->np];
if(minid[i] == 88) {
fastpm_ilog(INFO, "%d MINID == %ld ID = %ld headminid == %ld i = %td / %td head=%td", finder->priv->ThisTask,
minid[i], id, minid[head[i]], i, p->np, head[i]);
}
if(id == 88 || id == 96 || id == 152 || id == 160) {
fastpm_ilog(INFO, "%d MINID == %ld ID = %ld headminid == %ld i = %td / %td head=%td", finder->priv->ThisTask,
minid[i], id, minid[head[i]], i, p->np, head[i]);
}
}
}
#endif
}
/* set head[i] to hid*/
static size_t
_assign_halo_attr(FastPMFOFFinder * finder, PMGhostData * pgd, ptrdiff_t * head, size_t np, size_t np_ghosts, int nmin)
{
ptrdiff_t * offset = fastpm_memory_alloc(finder->p->mem, "FOFOffset", sizeof(offset[0]) * (np + np_ghosts), FASTPM_MEMORY_STACK);
uint8_t * has_remote = fastpm_memory_alloc(finder->p->mem, "FOFHasRemote", sizeof(has_remote[0]) * (np + np_ghosts), FASTPM_MEMORY_STACK);
uint8_t * has_local = fastpm_memory_alloc(finder->p->mem, "FOFHasLocal", sizeof(has_local[0]) * (np + np_ghosts), FASTPM_MEMORY_STACK);
ptrdiff_t i;
for(i = 0; i < np + np_ghosts; i ++) {
offset[i] = 0;
has_remote[i] = 0;
has_local[i] = 0;
}
/* set offset to number of particles in the halo */
for(i = 0; i < np + np_ghosts; i ++) {
offset[head[i]] ++;
}
for(i = 0; i < np; i ++) {
has_local[head[i]] = 1;
}
/* if the group is connected to a remote component */
/* if the particle has a ghost, then */
pm_ghosts_has_ghosts(pgd, has_remote);
/* if connected to a particle that has ghost */
for(i = 0; i < np; i ++) {
if(has_remote[i]) has_remote[head[i]] = 1;
}
/* if connected to a ghost */
for(i = np; i < np + np_ghosts; i ++) {
has_remote[head[i]] = 1;
}
size_t it = 0;
/* assign attr index for groups at least contain 1 local particle */
for(i = 0; i < np + np_ghosts; i ++) {
if(has_local[i] && (has_remote[i] || offset[i] >= nmin)) {
offset[i] = it;
it ++;
} else {
offset[i] = -1;
}
}
size_t nhalos = it;
/* update head [i] to offset[head[i]], which stores the index in the halo store for this particle. */
for(i = 0; i < np + np_ghosts; i ++) {
head[i] = offset[head[i]];
/* this will not happen if nmin == 1 */
if(head[i] != -1 && head[i] > nhalos) {
fastpm_raise(-1, "head[i] (%td) > nhalos (%td) This shall not happen.\n", head[i], nhalos);
}
}
fastpm_memory_free(finder->p->mem, has_local);
fastpm_memory_free(finder->p->mem, has_remote);
fastpm_memory_free(finder->p->mem, offset);
return it;
}
static double
periodic_add(double x, double wx, double y, double wy, double L)
{
if(wx > 0) {
while(y - x > L / 2) y -= L;
while(y - x < -L / 2) y += L;
return wx * x + wy * y;
} else {
return wy * y;
}
}
/*
* apply mask to a halo storage.
* relable head, and halo->id
* */
static void
fastpm_fof_subsample(FastPMFOFFinder * finder, FastPMStore * halos, FastPMParticleMaskType * mask, ptrdiff_t * head)
{
/* mapping goes from the old head[i] value to the new head[i] value */
ptrdiff_t * mapping = fastpm_memory_alloc(finder->p->mem, "FOFMapping", sizeof(mapping[0]) * halos->np, FASTPM_MEMORY_STACK);
ptrdiff_t i;
for(i = 0; i < halos->np; i ++) {
mapping[i] = -1;
halos->id[i] = i;
}
/* remove non-contributing halo segments */
fastpm_store_subsample(halos, mask, halos);
for(i = 0; i < halos->np; i ++) {
mapping[halos->id[i]] = i;
halos->id[i] = i;
}
/* adjust head[i] */
for(i = 0; i < finder->p->np; i ++) {
if(head[i] >= 0) {
head[i] = mapping[head[i]];
}
}
fastpm_memory_free(finder->p->mem, mapping);
}
static void
fastpm_fof_apply_length_cut(FastPMFOFFinder * finder, FastPMStore * halos, ptrdiff_t * head)
{
MPI_Comm comm = finder->priv->comm;
FastPMParticleMaskType * mask = fastpm_memory_alloc(finder->p->mem, "LengthMask", sizeof(mask[0]) * halos->np, FASTPM_MEMORY_STACK);
ptrdiff_t i;
for(i = 0; i < halos->np; i ++) {
/* remove halos that are shorter than nmin */
if(halos->length[i] < finder->nmin) {
mask[i] = 0;
} else {
mask[i] = 1;
}
}
fastpm_fof_subsample(finder, halos, mask, head);
fastpm_memory_free(finder->p->mem, mask);
fastpm_info("After length cut we have %td halos (%td including ghost halos).\n",
fastpm_store_get_mask_sum(halos, comm),
fastpm_store_get_np_total(halos, comm));
}
/* first every undecided halo; then the real halo with particles */
static int
FastPMLocalSortByMinID(const int i1,
const int i2,
FastPMStore * p)
{
int v1 = (p->minid[i1] < p->minid[i2]);
int v2 = (p->minid[i1] > p->minid[i2]);
return v2 - v1;
}
static int
FastPMTargetMinID(FastPMStore * store, ptrdiff_t i, void * userdata)
{
FastPMFOFFinder * finder = userdata;
const uint32_t GOLDEN32 = 2654435761ul;
/* const uint64_t GOLDEN64 = 11400714819323198549; */
/* may over flow, but should be okay here as the periodicity is ggt NTask */
int key = (store->minid[i] * GOLDEN32) % (unsigned) finder->priv->NTask;
return key;
}
static int
FastPMTargetTask(FastPMStore * store, ptrdiff_t i, void * userdata)
{
return store->task[i];
}
/* for debugging, move particles to a spatially unrelated rank */
static int
FastPMTargetFOF(FastPMStore * store, ptrdiff_t i, void * userdata)
{
#ifdef FASTPM_FOF_DEBUG
PM * pm = userdata;
int NTask;
MPI_Comm_size(pm_comm(pm), &NTask);
const uint32_t GOLDEN32 = 2654435761ul;
/* const uint64_t GOLDEN64 = 11400714819323198549; */
/* may over flow, but should be okay here as the periodicity is ggt NTask */
int key = (store->id[i] * GOLDEN32) % (unsigned) NTask;
return key;
#else
return FastPMTargetPM(store, i, userdata);
#endif
}
/*
* This function group halos by halos->minid[i].
*
* All halos with the same minid will have the same attribute values afterwards, except
* a few book keeping items named in this function (see comments inside)
*
* */
static void
fastpm_fof_reduce_halo_attrs(FastPMFOFFinder * finder, FastPMStore * halos,
void (* add_func) (FastPMFOFFinder * finder, FastPMStore * halo1, ptrdiff_t i1, FastPMStore * halo2, ptrdiff_t i2 ),
void (* reduce_func)(FastPMFOFFinder * finder, FastPMStore * halo1, ptrdiff_t i1)
)
{
ptrdiff_t i;
ptrdiff_t first = -1;
uint64_t lastminid = 0;
/* ind is the array to use to replicate items */
int * ind = fastpm_memory_alloc(finder->p->mem, "HaloPermutation", sizeof(ind[0]) * halos->np, FASTPM_MEMORY_STACK);
/* the following items will have mask[i] == 1, but we will mark some to 0 if
* they are not the principle (first) halos segment with this minid */
for(i = 0; i < halos->np + 1; i++) {
/* we use i == halos->np to terminate the last segment */
if(first == -1 || i == halos->np || lastminid != halos->minid[i]) {
if (first >= 0) {
/* a segment ended */
ptrdiff_t j;
for(j = first; j < i; j ++) {
ind[j] = first;
}
}
if (i < halos->np) {
/* a segment started */
halos->mask[i] = 1;
lastminid = halos->minid[i];
}
/* starting a segment of the same halos */
first = i;
} else {
/* inside segment, simply add the ith halo to the first of the segment */
halos->mask[i] = 0;
add_func(finder, halos, first, halos, i);
}
}
/* use permute to replicate the first halo attr to the rest:
*
* we do not want to replicate
* - fof, as fof.task is the original mpi rank of the halo
* - id, as it is the original location of the halo on the original mpi rank.
* - mask, whether it is primary or not
*
* we need to replicate because otherwise when we return the head array on the
* original ranks will be violated.
* */
FastPMStore save[1];
/* FIXME: add a method for this! */
memcpy(save->columns, halos->columns, sizeof(save->columns));
halos->minid = NULL;
halos->task = NULL;
halos->id = NULL;
halos->mask = NULL;
fastpm_store_permute(halos, ind);
memcpy(halos->columns, save->columns, sizeof(save->columns));
for(i = 0; i < halos->np; i++) {
reduce_func(finder, halos, i);
}
fastpm_memory_free(finder->p->mem, ind);
}
static void
fastpm_fof_compute_halo_attrs(FastPMFOFFinder * finder, FastPMStore * halos,
ptrdiff_t * head,
void (*convert_func)(FastPMFOFFinder * finder, FastPMStore * p, ptrdiff_t i, FastPMStore * halos),
void (*add_func)(FastPMFOFFinder * finder, FastPMStore * halos, ptrdiff_t i1, FastPMStore * halos2, ptrdiff_t i2),
void (*reduce_func)(FastPMFOFFinder * finder, FastPMStore * halos, ptrdiff_t i)
)
{
MPI_Comm comm = finder->priv->comm;
FastPMStore h1[1];
fastpm_store_init(h1, "FOF", 1, halos->attributes, FASTPM_MEMORY_HEAP);
ptrdiff_t i;
for(i = 0; i < finder->p->np; i++) {
ptrdiff_t hid = head[i];
if(hid < 0) continue;
if(hid >= halos->np) {
fastpm_raise(-1, "halo of a particle out of bounds (%td > %td)\n", hid, halos->np);
}
/* initialize h1 with existing halo attributes for this particle */
fastpm_store_take(halos, hid, h1, 0);
convert_func(finder, finder->p, i, h1);
add_func(finder, halos, hid, h1, 0);
}
fastpm_store_destroy(h1);
/* decompose halos by minid (gather); if all halo segments of the same minid are on the same rank, we can combine
* these into a single entry, then replicate for each particle to look up;
* halo segments that have no local particles are never exchanged to another rank. */
if(0 != fastpm_store_decompose(halos,
(fastpm_store_target_func) FastPMTargetMinID, finder, comm)) {
fastpm_raise(-1, "out of space sending halos by MinID.\n");
}
/* now head[i] is no longer the halo attribute of particle i. */
/* to combine, first local sort by minid; those without local particles are moved to the beginning
* so we can easily skip them. */
fastpm_store_sort(halos, FastPMLocalSortByMinID);
/* reduce and update properties */
fastpm_fof_reduce_halo_attrs(finder, halos, add_func, reduce_func);
/* decompose halos by task (return) */
if (0 != fastpm_store_decompose(halos,
(fastpm_store_target_func) FastPMTargetTask, finder, comm)) {
fastpm_raise(-1, "out of space for gathering halos this shall never happen.\n");
}
/* local sort by id (restore the order) */
fastpm_store_sort(halos, FastPMLocalSortByID);
/* now head[i] is again the halo attribute of particle i. */
}
/*
* compute the attrs of the local halo segments based on local particles.
* head : the hid of each particle;
* fofsave : the minid of each particle (unique label of each halo)
*
* if a halo has no local particles, halos->mask[i] is set to 0.
* if a halo has any local particles, and halos->mask[i] is set to 1.
* */
static void
fastpm_fof_remove_empty_halos(FastPMFOFFinder * finder, FastPMStore * halos, uint64_t * minid, ptrdiff_t * head)
{
/* */
ptrdiff_t i;
/* set minid and task of the halo; all of the halo particles of the same minid needs to be reduced */
for(i = 0; i < finder->p->np; i++) {
/* set the minid of the halo; need to take care of the ghosts too.
* even though we do not add them to the attributes */
ptrdiff_t hid = head[i];
if(hid < 0) continue;
if(halos->mask[hid] == 0) {
/* halo will be reduced by minid */
halos->minid[hid] = minid[i];
halos->mask[hid] = 1;
} else {
if(halos->minid[hid] != minid[i]) {
fastpm_raise(-1, "Consistency check failed after FOF global merge.\n");
}
}
}
/* halo will be returned to this task;
* we save ThisTask here.*/
for(i = 0; i < halos->np; i ++) {
halos->task[i] = finder->priv->ThisTask;
}
fastpm_fof_subsample(finder, halos, halos->mask, head);
}
static void
_add_basic_halo_attrs(FastPMFOFFinder * finder, FastPMStore * halos, ptrdiff_t hid, FastPMStore * h1, ptrdiff_t i)
{
double * boxsize = finder->priv->boxsize;
if(halos->aemit)
halos->aemit[hid] += h1->aemit[i];
int d;
for(d = 0; d < 3; d++) {
if(halos->v)
halos->v[hid][d] += h1->v[i][d];
if(halos->dx1)
halos->dx1[hid][d] += h1->dx1[i][d];
if(halos->dx2)
halos->dx2[hid][d] += h1->dx2[i][d];
}
if(halos->x) {
for(d = 0; d < 3; d++) {
if(boxsize) {
halos->x[hid][d] = periodic_add(
halos->x[hid][d] / halos->length[hid], halos->length[hid],
h1->x[i][d] / h1->length[i], h1->length[i], boxsize[d]);
} else {
halos->x[hid][d] += h1->x[i][d];
}
}
}
if(halos->q) {
for(d = 0; d < 3; d ++) {
if (boxsize) {
halos->q[hid][d] = periodic_add(
halos->q[hid][d] / halos->length[hid], halos->length[hid],
h1->q[i][d] / h1->length[i], h1->length[i], boxsize[d]);
} else {
halos->q[hid][d] += h1->q[i][d];
}
}
}
/* do this after the loop because x depends on the old length. */
halos->length[hid] += h1->length[i];
}
/* convert a particle to the first halo in the halo store */
static void
_convert_basic_halo_attrs(FastPMFOFFinder * finder, FastPMStore * p, ptrdiff_t i, FastPMStore * halos)
{
int hid = 0;
int d;
double q[3];
if(halos->q && fastpm_store_has_q(p)) {
fastpm_store_get_q_from_id(p, p->id[i], q);
}
halos->length[hid] = 1;
for(d = 0; d < 3; d++) {
if(halos->x)
halos->x[hid][d] = p->x[i][d];
if(halos->v)
halos->v[hid][d] = p->v[i][d];
if(halos->dx1)
halos->dx1[hid][d] = p->dx1[i][d];
if(halos->dx2)
halos->dx2[hid][d] = p->dx2[i][d];
if(halos->q && fastpm_store_has_q(p)) {
halos->q[hid][d] = q[d];
}
}
if(halos->aemit)
halos->aemit[hid] = p->aemit[i];
}
static void
_reduce_basic_halo_attrs(FastPMFOFFinder * finder, FastPMStore * halos, ptrdiff_t i)
{
int d;
double n = halos->length[i];
for(d = 0; d < 3; d++) {
if(halos->x)
halos->x[i][d] /= n;
if(halos->v)
halos->v[i][d] /= n;
if(halos->dx1)
halos->dx1[i][d] /= n;
if(halos->dx2)
halos->dx2[i][d] /= n;
if(halos->q)
halos->q[i][d] /= n;
}
if(halos->aemit)
halos->aemit[i] /= n;
}
static void
_add_extended_halo_attrs(FastPMFOFFinder * finder, FastPMStore * h1, ptrdiff_t i1, FastPMStore * h2, ptrdiff_t i2)
{
int d;
if(h1->rvdisp) {
for(d = 0; d < 9; d ++) {
h1->rvdisp[i1][d] += h2->rvdisp[i2][d];
}
}
if(h1->vdisp) {
for(d = 0; d < 6; d ++) {
h1->vdisp[i1][d] += h2->vdisp[i2][d];
}
}
if(h1->rdisp) {
for(d = 0; d < 6; d ++) {
h1->rdisp[i1][d] += h2->rdisp[i2][d];
}
}
}
static void
_convert_extended_halo_attrs(FastPMFOFFinder * finder, FastPMStore * p, ptrdiff_t i, FastPMStore * halos)
{
int hid = 0;
int d;
double rrel[3];
for(d = 0; d < 3; d ++) {
rrel[d] = p->x[i][d] - halos->x[hid][d];
if(finder->priv->boxsize) {
double L = finder->priv->boxsize[d];
while(rrel[d] > L / 2) rrel[d] -= L;
while(rrel[d] < -L / 2) rrel[d] += L;
}
}
if(halos->vdisp) {
/* FIXME: add hubble expansion term based on aemit and hubble function? needs to modify Finder object */
double vrel[3];
for(d = 0; d < 3; d ++) {
vrel[d] = p->v[i][d] - halos->v[hid][d];
}
for(d = 0; d < 3; d ++) {
halos->vdisp[hid][d] = vrel[d] * vrel[d];
halos->vdisp[hid][d + 3] = vrel[d] * vrel[(d + 1) % 3];
}
}
if(halos->rvdisp) {
/* FIXME: add hubble expansion term based on aemit and hubble function? needs to modify Finder object */
double vrel[3];
for(d = 0; d < 3; d ++) {
vrel[d] = p->v[i][d] - halos->v[hid][d];
}
for(d = 0; d < 3; d ++) {
halos->rvdisp[hid][d] = rrel[d] * vrel[d];
halos->rvdisp[hid][d + 3] = rrel[d] * vrel[(d + 1) % 3];
halos->rvdisp[hid][d + 6] = rrel[d] * vrel[(d + 2) % 3];
}
}
if(halos->rdisp) {
for(d = 0; d < 3; d ++) {
halos->rdisp[hid][d] = rrel[d] * rrel[d];
halos->rdisp[hid][d + 3] = rrel[d] * rrel[(d + 1) % 3];
}
}
}
static void
_reduce_extended_halo_attrs(FastPMFOFFinder * finder, FastPMStore * halos, ptrdiff_t hid)
{
double n = halos->length[hid];
int d;
if(halos->rvdisp) {
for(d = 0; d < 9; d ++) {
halos->rvdisp[hid][d] /= n;
}
}
if(halos->vdisp) {
for(d = 0; d < 6; d ++) {
halos->vdisp[hid][d] /= n;
}
}
if(halos->rdisp) {
for(d = 0; d < 3; d ++) {
halos->rdisp[hid][d] /= n;
}
}
}
/* This function creates the storage object for halo segments that are local on this
* rank. We store mnay attributes. We only allow a flucutation of 2 around avg_halos.
* this should be OK, since we will only redistribute by the MinID, which are supposed
* to be very uniform.
* */
static void
fastpm_fof_create_local_halos(FastPMFOFFinder * finder, FastPMStore * halos, size_t nhalos)
{
MPI_Comm comm = finder->priv->comm;
FastPMColumnTags attributes = finder->p->attributes;
attributes |= COLUMN_MASK;
attributes |= COLUMN_LENGTH | COLUMN_MINID | COLUMN_TASK;
attributes |= COLUMN_RDISP | COLUMN_VDISP | COLUMN_RVDISP;
attributes |= COLUMN_ACC; /* ACC used as the first particle position offset */
attributes &= ~COLUMN_POTENTIAL;
attributes &= ~COLUMN_DENSITY;
attributes &= ~COLUMN_TIDAL;
/* store initial position only for periodic case. non-periodic suggests light cone and
* we cannot infer q from ID sensibly. (crashes there) */
if(finder->priv->boxsize) {
attributes |= COLUMN_Q;
} else {
attributes &= ~COLUMN_Q;
}
double avg_halos;
double max_halos;
/* + 1 to ensure avg_halos > 0 */
MPIU_stats(comm, nhalos + 1, "->", &avg_halos, &max_halos);
fastpm_info("Allocating %d halos per rank for final catalog.\n", (size_t) max_halos * 2);
/* give it enough space for rebalancing. */
fastpm_store_init(halos, NULL, (size_t) (max_halos * 2),
attributes,
FASTPM_MEMORY_HEAP);
halos->np = nhalos;
halos->meta = finder->p->meta;
ptrdiff_t i;
for(i = 0; i < halos->np; i++) {
halos->id[i] = i;
halos->mask[i] = 0; /* unselect the halos ; will turn this only if any particle is used */
/* everthing should have been set to zero already by fastpm_store_init */
}
}
void
fastpm_fof_execute(FastPMFOFFinder * finder, FastPMStore * halos)
{
/* initial decompose -- reduce number of ghosts */
FastPMStore * p = finder->p;
PM * pm = finder->pm;
MPI_Comm comm = finder->priv->comm;
/* only do wrapping for periodic data */
if(finder->priv->boxsize)
fastpm_store_wrap(p, finder->priv->boxsize);
double npmax, npmin, npstd, npmean;
MPIU_stats(comm, p->np, "<->s", &npmin, &npmean, &npmax, &npstd);
fastpm_info("load balance before fof decompose : min = %g max = %g mean = %g std = %g\n",
npmin, npmax, npmean, npstd
);
#if 1
/* still route particles to the pm pencils as if they are periodic. */
/* should still work (albeit use crazy memory) if we skip this. */
if(0 != fastpm_store_decompose(p,
(fastpm_store_target_func) FastPMTargetFOF, pm, comm)
) {
fastpm_raise(-1, "out of storage space decomposing for FOF\n");
}
#endif
MPIU_stats(comm, p->np, "<->s", &npmin, &npmean, &npmax, &npstd);
fastpm_info("load balance after fof decompose : min = %g max = %g mean = %g std = %g\n",
npmin, npmax, npmean, npstd
);
/* create ghosts mesh size is usually > ll so we are OK here. */
double below[3], above[3];
int d;
for(d = 0; d < 3; d ++) {
/* bigger padding reduces number of iterations */
below[d] = -finder->linkinglength * 1;
above[d] = finder->linkinglength * 1;
}
PMGhostData * pgd = pm_ghosts_create_full(pm, p,
COLUMN_POS | COLUMN_ID | COLUMN_MINID,
below, above
);
pm_ghosts_send(pgd, COLUMN_POS);
pm_ghosts_send(pgd, COLUMN_ID);
size_t np_and_ghosts = p->np + pgd->p->np;
#ifdef FASTPM_FOF_DEBUG
fastpm_ilog(INFO, "Rank %d has %td particles including ghost\n", finder->priv->ThisTask, np_and_ghosts);
#endif
ptrdiff_t * head = fastpm_memory_alloc(p->mem, "FOFHead",
sizeof(head[0]) * np_and_ghosts, FASTPM_MEMORY_STACK);
FastPMStore savebuff[1];
fastpm_store_init(savebuff, p->name, np_and_ghosts, COLUMN_MINID, FASTPM_MEMORY_STACK);
_fof_local_find(finder, p, pgd, head, finder->linkinglength);
_fof_global_merge (finder, p, pgd, savebuff->minid, head);
/* assign halo attr entries. This will keep only candidates that can possibly reach to nmin */
size_t nsegments = _assign_halo_attr(finder, pgd, head, p->np, pgd->p->np, finder->nmin);
fastpm_info("Found %td halos segments >= %d particles; or cross linked. \n", nsegments, finder->nmin);
pm_ghosts_free(pgd);
/* create local halos and modify head to index the local halos */
fastpm_fof_create_local_halos(finder, halos, nsegments);
/* remove halos without any local particles */
fastpm_fof_remove_empty_halos(finder, halos, savebuff->minid, head);
fastpm_store_destroy(savebuff);
/* reduce the primary halo attrs */
fastpm_fof_compute_halo_attrs(finder, halos, head, _convert_basic_halo_attrs, _add_basic_halo_attrs, _reduce_basic_halo_attrs);
#ifdef FASTPM_FOF_DEBUG
{
int i;
for(i = 0; i < halos->np; i ++) {
fastpm_ilog(INFO, "Task = %d, Halo[%d] = %d mask=%d MINID=%ld\n", finder->priv->ThisTask, i, halos->length[i], halos->mask[i], halos->minid[i]);
}
}
#endif
/* apply length cut */
fastpm_fof_apply_length_cut(finder, halos, head);
/* reduce the primary halo attrs */
fastpm_fof_compute_halo_attrs(finder, halos, head, _convert_extended_halo_attrs, _add_extended_halo_attrs, _reduce_extended_halo_attrs);
/* the event is called with full halos, only those where mask==1 are primary
* the others are ghosts with the correct properties but shall not show up in the
* catalog.
* */
FastPMHaloEvent event[1];
event->halos = halos;
event->p = finder->p;
event->ihalo = head;
fastpm_emit_event(finder->event_handlers, FASTPM_EVENT_HALO,
FASTPM_EVENT_STAGE_AFTER, (FastPMEvent*) event, finder);
fastpm_memory_free(finder->p->mem, head);
fastpm_store_subsample(halos, halos->mask, halos);
fastpm_info("After event: %td halos.\n", fastpm_store_get_np_total(halos, comm));
}
void
fastpm_fof_destroy(FastPMFOFFinder * finder)
{
fastpm_destroy_event_handlers(&finder->event_handlers);
free(finder->priv);
}
| {
"alphanum_fraction": 0.5818208911,
"avg_line_length": 30.2297297297,
"ext": "c",
"hexsha": "ef5feb8e6ed9b5ebe1f746bfd31c2fba779b815d",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2021-04-14T23:24:19.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-04-14T23:24:19.000Z",
"max_forks_repo_head_hexsha": "f38f6e69c603fb699436b645fe7b4eb418ee82c2",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "sbird/FastPMRunner",
"max_forks_repo_path": "fastpm/libfastpm/fof.c",
"max_issues_count": 4,
"max_issues_repo_head_hexsha": "f38f6e69c603fb699436b645fe7b4eb418ee82c2",
"max_issues_repo_issues_event_max_datetime": "2022-01-24T05:51:04.000Z",
"max_issues_repo_issues_event_min_datetime": "2021-04-19T23:01:33.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "sbird/FastPMRunner",
"max_issues_repo_path": "fastpm/libfastpm/fof.c",
"max_line_length": 156,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "f38f6e69c603fb699436b645fe7b4eb418ee82c2",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "sbird/FastPMRunner",
"max_stars_repo_path": "fastpm/libfastpm/fof.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 10178,
"size": 33555
} |
#pragma once
#include <gsl/gsl>
#include <string>
#include <memory>
#include <vector>
#include <string_view>
#include "aas/aas_math.h"
namespace aas {
struct MeshVertex {
static constexpr size_t sMaxBoneAttachments = 6;
DX::XMFLOAT4 pos;
DX::XMFLOAT4 normal;
DX::XMFLOAT2 uv;
uint16_t padding;
uint16_t attachmentCount;
uint16_t attachmentBone[sMaxBoneAttachments];
float attachmentWeight[sMaxBoneAttachments];
bool IsAttachedTo(int bone_idx) const {
for (int i = 0; i < attachmentCount; i++) {
if (attachmentBone[i] == bone_idx) {
return true;
}
}
return false;
}
};
struct MeshFace {
static constexpr size_t sVertexCount = 3;
int16_t material_idx;
int16_t vertices[sVertexCount];
};
struct MeshBone {
int16_t flags;
int16_t parent_id;
char name[48];
Matrix3x4 full_world_inverse;
};
class Mesh {
public:
Mesh(std::string filename, std::vector<uint8_t> data);
const std::vector<std::string_view> &GetMaterials() const {
return materials_;
}
std::string_view GetMaterial(int materialIdx) const {
return materials_[materialIdx];
}
gsl::span<MeshBone> GetBones() const {
return bones_;
}
const MeshBone &GetBone(int boneIdx) const {
Expects(boneIdx >= 0 && boneIdx < bones_.size());
return bones_[boneIdx];
}
gsl::span<MeshVertex> GetVertices() const {
return vertices_;
}
const MeshVertex &GetVertex(int vertexIdx) const {
return vertices_[vertexIdx];
}
const size_t GetVertexCount() const {
return vertices_.size();
}
MeshVertex &GetVertex(int vertexIdx) {
return vertices_[vertexIdx];
}
gsl::span<MeshFace> GetFaces() const {
return faces_;
}
const MeshFace &GetFace(int faceIdx) const {
return faces_[faceIdx];
}
void RenormalizeClothVertices(int clothBoneId);
const std::string &GetFilename() const {
return filename_;
}
private:
std::string filename_;
std::vector<uint8_t> data_;
std::vector<std::string_view> materials_;
// These are views into the data buffer
gsl::span<MeshBone> bones_;
gsl::span<MeshVertex> vertices_;
gsl::span<MeshFace> faces_;
};
std::unique_ptr<Mesh> LoadMeshFile(std::string_view filename);
}
| {
"alphanum_fraction": 0.6970654628,
"avg_line_length": 19.7767857143,
"ext": "h",
"hexsha": "d2bda3e13db6dfa40fddc10e954432aca8250570",
"lang": "C",
"max_forks_count": 25,
"max_forks_repo_forks_event_max_datetime": "2021-11-15T23:14:51.000Z",
"max_forks_repo_forks_event_min_datetime": "2016-02-04T21:19:53.000Z",
"max_forks_repo_head_hexsha": "f0e552289822fea908f16daa379fa568b1bd286d",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "edoipi/TemplePlus",
"max_forks_repo_path": "Infrastructure/src/aas/aas_mesh.h",
"max_issues_count": 457,
"max_issues_repo_head_hexsha": "f0e552289822fea908f16daa379fa568b1bd286d",
"max_issues_repo_issues_event_max_datetime": "2022-03-31T02:19:10.000Z",
"max_issues_repo_issues_event_min_datetime": "2015-05-01T22:07:45.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "edoipi/TemplePlus",
"max_issues_repo_path": "Infrastructure/src/aas/aas_mesh.h",
"max_line_length": 63,
"max_stars_count": 69,
"max_stars_repo_head_hexsha": "f0e552289822fea908f16daa379fa568b1bd286d",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "edoipi/TemplePlus",
"max_stars_repo_path": "Infrastructure/src/aas/aas_mesh.h",
"max_stars_repo_stars_event_max_datetime": "2022-02-15T06:13:04.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-05-05T14:09:25.000Z",
"num_tokens": 622,
"size": 2215
} |
#if !defined(fvSupport_h)
#define fvSupport_h
#include <petsc.h>
#define MAX_FVM_RHS_FUNCTION_FIELDS 4
typedef PetscErrorCode (*FVMRHSFluxFunction)(PetscInt dim, const PetscFVFaceGeom *fg, const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar fieldL[], const PetscScalar fieldR[],
const PetscScalar gradL[], const PetscScalar gradR[], const PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar auxL[], const PetscScalar auxR[],
const PetscScalar gradAuxL[], const PetscScalar gradAuxR[], PetscScalar flux[], void *ctx);
typedef PetscErrorCode (*FVMRHSPointFunction)(PetscInt dim, const PetscFVCellGeom *cg, const PetscInt uOff[], const PetscScalar u[], const PetscInt aOff[], const PetscScalar a[], PetscScalar f[], void *ctx);
typedef PetscErrorCode (*FVAuxFieldUpdateFunction)(PetscReal time, PetscInt dim, const PetscFVCellGeom *cellGeom, const PetscScalar *conservedValues, PetscScalar *auxField, void *ctx);
/**
* struct to describe how to compute RHS finite volume flux source terms
*/
struct _FVMRHSFluxFunctionDescription {
FVMRHSFluxFunction function;
void *context;
PetscInt field;
PetscInt inputFields[MAX_FVM_RHS_FUNCTION_FIELDS];
PetscInt numberInputFields;
PetscInt auxFields[MAX_FVM_RHS_FUNCTION_FIELDS];
PetscInt numberAuxFields;
};
typedef struct _FVMRHSFluxFunctionDescription FVMRHSFluxFunctionDescription;
/**
* struct to describe how to compute RHS finite volume point source terms
*/
struct _FVMRHSPointFunctionDescription {
FVMRHSPointFunction function;
void *context;
PetscInt fields[MAX_FVM_RHS_FUNCTION_FIELDS];
PetscInt numberFields;
PetscInt inputFields[MAX_FVM_RHS_FUNCTION_FIELDS];
PetscInt numberInputFields;
PetscInt auxFields[MAX_FVM_RHS_FUNCTION_FIELDS];
PetscInt numberAuxFields;
};
typedef struct _FVMRHSPointFunctionDescription FVMRHSPointFunctionDescription;
/**
DMPlexTSComputeRHSFunctionFVM - Form the local forcing F from the local input X using flux and pointfunctions specified by the user
Input Parameters:
+ dm - The mesh
. t - The time
. locX - Local solution
- user - The user context
Output Parameter:
. F - Global output vector
Level: developer
.seealso: DMPlexComputeJacobianActionFEM()
**/
PETSC_EXTERN PetscErrorCode ABLATE_DMPlexComputeRHSFunctionFVM(FVMRHSFluxFunctionDescription *fluxFunctionDescriptions, PetscInt numberFluxFunctionDescription,
FVMRHSPointFunctionDescription *pointFunctionDescriptions, PetscInt numberPointFunctionDescription, DM dm, PetscReal time, Vec locX, Vec F);
/**
* Populate the boundary with gradient information
* @param dm
* @param auxDM
* @param time
* @param locXVec
* @param locAuxField
* @param numberUpdateFunctions
* @param updateFunctions
* @param data
* @return
*/
/**
* Takes all local vector
* @return
*/
PETSC_EXTERN PetscErrorCode ABLATE_DMPlexComputeFluxResidual_Internal(FVMRHSFluxFunctionDescription functionDescription[], PetscInt numberFunctionDescription, DM, IS, PetscReal, Vec, Vec, PetscReal, Vec);
/**
Form the local forcing F from the local input X using pointwise functions specified by the user
Input Parameters:
+ dm - The mesh
. t - The time
. locX - Local solution
Output Parameter:
. F - local output vector
**/
PETSC_EXTERN PetscErrorCode ABLATE_DMPlexComputePointResidual_Internal(FVMRHSPointFunctionDescription *functionDescription, PetscInt numberFunctionDescription, DM, IS, PetscReal, Vec, Vec, PetscReal, Vec);
/**
* reproduces the petsc call with grad fixes for multiple fields
* @param dm
* @param fvm
* @param locX
* @param grad
* @return
*/
PETSC_EXTERN PetscErrorCode DMPlexReconstructGradientsFVM_MulfiField(DM dm, PetscFV fvm, Vec locX, Vec grad);
/**
* reproduces the petsc call with grad fixes for multiple fields
* @param dm
* @param fvm
* @param locX
* @param grad
* @return
*/
PETSC_EXTERN PetscErrorCode DMPlexGetDataFVM_MulfiField(DM dm, PetscFV fv, Vec *cellgeom, Vec *facegeom, DM *gradDM);
/**
* Function to update all cells. This should be merged into other update calls
* @param dm
* @param auxDM
* @param time
* @param locXVec
* @param locAuxField
* @param numberUpdateFunctions
* @param updateFunctions
* @param ctx
* @return
*/
PETSC_EXTERN PetscErrorCode FVFlowUpdateAuxFieldsFV(DM dm, DM auxDM, PetscReal time, Vec locXVec, Vec locAuxField, PetscInt numberUpdateFunctions, FVAuxFieldUpdateFunction *updateFunctions, void **ctx);
#endif | {
"alphanum_fraction": 0.7517376195,
"avg_line_length": 33.3623188406,
"ext": "h",
"hexsha": "4565e02bca7cf4b58b2b67e4770a464bb5cd7898",
"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": "27df14008f0d0c595bc25334a2f5a4ef7ccbe4bf",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "mschulwitz/ablate",
"max_forks_repo_path": "ablateCore/flow/fvSupport.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "27df14008f0d0c595bc25334a2f5a4ef7ccbe4bf",
"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": "mschulwitz/ablate",
"max_issues_repo_path": "ablateCore/flow/fvSupport.h",
"max_line_length": 207,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "27df14008f0d0c595bc25334a2f5a4ef7ccbe4bf",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "mschulwitz/ablate",
"max_stars_repo_path": "ablateCore/flow/fvSupport.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1153,
"size": 4604
} |
#pragma once
#include "GradUtil.h"
#ifndef _NOGSL
#include <gsl/gsl_vector.h>
#include <gsl/gsl_blas.h>
#else
#include "CustomSolver.h"
#endif
#include "BooleanDAG.h"
class ActualEvaluators;
class SmoothEvaluators;
class Predicate {
public:
virtual string print() = 0;
virtual double evaluate(ActualEvaluators* eval) = 0;
virtual double evaluate(gsl_vector* grad, ActualEvaluators* eval) = 0;
virtual double evaluate(SmoothEvaluators* eval) = 0;
virtual double evaluate(gsl_vector* grad, SmoothEvaluators* eval) = 0;
virtual double grad_norm(ActualEvaluators* eval) = 0;
virtual const gsl_vector* grad(ActualEvaluators* eval) = 0;
virtual bool isPure() = 0;
virtual void makeImpure() = 0;
virtual bool isBasic() = 0;
virtual bool isDiff() = 0;
};
class BasicPredicate: public Predicate { // TODO: override equal
bool pure;
public:
int nid;
BooleanDAG* dag;
Predicate* oldPred;
BasicPredicate(BooleanDAG* _dag, int _nid): dag(_dag), nid(_nid), oldPred(NULL) { pure = true;}
BasicPredicate(BooleanDAG* _dag, int _nid, Predicate* _oldPred): dag(_dag), nid(_nid), oldPred(_oldPred) { pure = true;}
virtual void makeImpure() {
pure = false;
}
virtual bool isPure() {
return pure;
}
virtual bool isBasic() { return true; }
virtual bool isDiff() { return false; }
virtual string print() {
stringstream s;
//s << (*dag)[nid]->lprint();
s << nid;
if (oldPred != NULL) {
s << "(" << oldPred->print() << ")";
}
return s.str();
}
virtual double evaluate(ActualEvaluators* eval);
virtual double evaluate(gsl_vector* grad, ActualEvaluators* eval);
virtual double evaluate(SmoothEvaluators* eval);
virtual double evaluate(gsl_vector* grad, SmoothEvaluators* eval);
virtual double grad_norm(ActualEvaluators* eval);
virtual const gsl_vector* grad(ActualEvaluators* eval);
};
class DiffPredicate: public Predicate {
bool pure;
public:
Predicate* p1;
Predicate* p2;
gsl_vector* tmp_p1; // TODO: Not sure where is the best place to create these tmp vectors for gradient calculation
gsl_vector* tmp_p2;
DiffPredicate(Predicate* _p1, Predicate* _p2, int ncontrols): p1(_p1), p2(_p2) {
tmp_p1 = gsl_vector_alloc(ncontrols);
tmp_p2 = gsl_vector_alloc(ncontrols);
pure = true;
}
~DiffPredicate() {
gsl_vector_free(tmp_p1);
gsl_vector_free(tmp_p2);
}
virtual void makeImpure() {
pure = false;
}
virtual bool isPure() {
return pure;
}
virtual bool isBasic() { return false; }
virtual bool isDiff() { return true; }
virtual string print() {
stringstream s;
s << p1->print() << " - " << p2->print() << endl;
return s.str();
}
virtual double evaluate(ActualEvaluators* eval);
virtual double evaluate(gsl_vector* grad, ActualEvaluators* eval);
virtual double evaluate(SmoothEvaluators* eval);
virtual double evaluate(gsl_vector* grad, SmoothEvaluators* eval);
virtual double grad_norm(ActualEvaluators* eval);
virtual const gsl_vector* grad(ActualEvaluators* eval);
}; | {
"alphanum_fraction": 0.654500464,
"avg_line_length": 30.7904761905,
"ext": "h",
"hexsha": "f2912debdc5203629ef6771c11a81c8ada9e8771",
"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/BoolAbstraction/Predicate.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/BoolAbstraction/Predicate.h",
"max_line_length": 125,
"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/BoolAbstraction/Predicate.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": 857,
"size": 3233
} |
#pragma once
#include <gsl\gsl>
#include <winrt\base.h>
#include <d3d11.h>
#include "DrawableGameComponent.h"
#include "PointSpriteMaterial.h"
namespace Rendering
{
class PointSpriteDemo final : public Library::DrawableGameComponent
{
public:
PointSpriteDemo(Library::Game& game, const std::shared_ptr<Library::Camera>& camera);
PointSpriteDemo(const PointSpriteDemo&) = delete;
PointSpriteDemo(PointSpriteDemo&&) = default;
PointSpriteDemo& operator=(const PointSpriteDemo&) = default;
PointSpriteDemo& operator=(PointSpriteDemo&&) = default;
~PointSpriteDemo();
virtual void Initialize() override;
virtual void Draw(const Library::GameTime& gameTime) override;
private:
void InitializeRandomPoints();
PointSpriteMaterial mMaterial;
winrt::com_ptr<ID3D11Buffer> mVertexBuffer;
std::size_t mVertexCount{ 0 };
bool mUpdateMaterial{ true };
};
} | {
"alphanum_fraction": 0.7604994325,
"avg_line_length": 27.53125,
"ext": "h",
"hexsha": "0723238b1e9eb441f5038d8443042c04c6c86c27",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl",
"max_forks_repo_path": "source/10.1_Point_Sprites/PointSpriteDemo.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl",
"max_issues_repo_path": "source/10.1_Point_Sprites/PointSpriteDemo.h",
"max_line_length": 87,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl",
"max_stars_repo_path": "source/10.1_Point_Sprites/PointSpriteDemo.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 220,
"size": 881
} |
/**
* Copyright 2019 José Manuel Abuín Mosquera <josemanuel.abuin@usc.es>
*
* This file is part of Matrix Market Suite.
*
* Matrix Market Suite 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.
*
* Matrix Market Suite 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 Matrix Market Suite. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stdio.h>
#include <stdlib.h>
#include <mpi.h>
#include <unistd.h>
#include <cblas.h>
#include "DMxV-MPI.h"
void usageDMxVMPI(){
fprintf(stderr, "\n");
fprintf(stderr, "Usage: MM-Suite DMxV [options] <input-matrix> <input-vector>\n");
fprintf(stderr, "\nInput/output options:\n\n");
fprintf(stderr, " -o STR Output file name. Default: stdout\n");
fprintf(stderr, " -r Input format is row per line. Default: False\n");
fprintf(stderr, "\nParameters options:\n\n");
fprintf(stderr, " -a DOUBLE Alpha. Default: 1.0\n");
fprintf(stderr, " -b DOUBLE Beta. Default: 0.0\n");
fprintf(stderr, "\nPerformance options:\n\n");
fprintf(stderr, " -t INT Number of threads to use in OpenBLAS. Default: 1\n");
fprintf(stderr, "\n");
}
int DMxVMPI(int argc, char *argv[], int numProcs, int myid) {
int ret_code = 1;
int option;
unsigned long *II;
unsigned long *J;
double *values;
unsigned long M;
unsigned long local_M;
unsigned long N;
unsigned long long nz;
double *vectorValues;
unsigned long M_Vector;
unsigned long N_Vector;
unsigned long long nz_vector;
char *outputFileName = NULL;
char *inputMatrixFile = NULL;
char *inputVectorFile = NULL;
char *outputVectorFile = NULL;
int inputFormatRow = 0;
double alpha = 1.0;
double beta = 0.0;
int numThreads = 1;
int i, j;
while ((option = getopt(argc, argv,"ro:a:b:t:")) >= 0) {
switch (option) {
case 'o' :
//free(outputFileName);
outputFileName = (char *) malloc(sizeof(char)*strlen(optarg)+1);
strcpy(outputFileName,optarg);
break;
case 'r':
inputFormatRow = 1;
break;
case 'b':
beta = atof(optarg);
break;
case 'a':
alpha = atof(optarg);
break;
case 't':
numThreads = atoi(optarg);
break;
default: break;
}
}
if ((optind + 3 != argc) && (optind + 2 != argc)) {
if (myid == 0) {
//fprintf(stderr,"[%s] Argc: %d, optind: %d\n",__func__, argc, optind);
usageDMxVMPI();
}
return 0;
}
openblas_set_num_threads(numThreads);
if(optind + 3 == argc) { //We have an output vector
outputVectorFile = (char *)malloc(sizeof(char)*strlen(argv[optind+2])+1);
strcpy(outputVectorFile,argv[optind+2]);
}
if(outputFileName == NULL) {
outputFileName = (char *) malloc(sizeof(char)*6);
sprintf(outputFileName,"stdout");
}
inputMatrixFile = (char *)malloc(sizeof(char)*strlen(argv[optind])+1);
inputVectorFile = (char *)malloc(sizeof(char)*strlen(argv[optind+1])+1);
strcpy(inputMatrixFile,argv[optind]);
strcpy(inputVectorFile,argv[optind+1]);
//Read matrix
if(inputFormatRow) {
if(!readDenseCoordinateMatrixMPIRowLine(inputMatrixFile,&II,&J,&values,&M,&local_M,&N,&nz,myid, numProcs)){
fprintf(stderr, "[%s] Can not read Matrix\n",__func__);
return 0;
}
}
else{
if(!readDenseCoordinateMatrixMPI(inputMatrixFile,&II,&J,&values,&M,&local_M,&N,&nz,myid, numProcs)){
fprintf(stderr, "[%s] Can not read Matrix\n",__func__);
return 0;
}
}
//Read input vector
if(!readDenseVector(inputVectorFile, &vectorValues,&M_Vector,&N_Vector,&nz_vector)){
fprintf(stderr, "[%s] Can not read Vector\n",__func__);
return 0;
}
/*
void cblas_dgemv(const enum CBLAS_ORDER order,
const enum CBLAS_TRANSPOSE TransA, const int M, const int N,
const double alpha, const double *A, const int lda,
const double *X, const int incX, const double beta,
double *Y, const int incY);
*/
double *partial_result=(double *) calloc(local_M,sizeof(double));
double* y = (double*)calloc(N,sizeof(double));
if(y == NULL){
fprintf(stderr,"[%s] Error reserving memory for final result vector in processor %d\n",__func__,myid);
return 0;
}
//Read output vector if any
if(outputVectorFile != NULL) {
if(!readDenseVector(outputVectorFile, &y,&M_Vector,&N_Vector,&nz_vector)){
fprintf(stderr, "[%s] Can not read Vector %s\n",__func__, outputVectorFile);
return 0;
}
for( i = (local_M * myid), j = 0; i< (local_M * myid + local_M) && j< local_M; i++, j++) {
partial_result[j] = y [i];
}
}
double t_real = realtime();
//y := alpha * A * x + beta * y
//cblas_dgemv(CblasRowMajor,CblasNoTrans,local_M,N,1.0,values,N,vectorValues,1,0.0,partial_result,1);
cblas_dgemv(CblasRowMajor,CblasNoTrans,local_M,N,alpha,values,N,vectorValues,1,beta,partial_result,1);
MPI_Allgather (partial_result,local_M,MPI_DOUBLE,y,local_M,MPI_DOUBLE,MPI_COMM_WORLD);
MPI_Barrier(MPI_COMM_WORLD);
fprintf(stderr, "\n[%s] Time spent in DMxV: %.6f sec\n", __func__, realtime() - t_real);
if (myid == 0){
writeDenseVector(outputFileName, y,M_Vector,N_Vector,nz_vector);
}
return ret_code;
}
| {
"alphanum_fraction": 0.6394263994,
"avg_line_length": 26.9209302326,
"ext": "c",
"hexsha": "9e3f67cd317ccf44127abaca8690660b7041cb17",
"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": "0bf3a81214f094dbddec868d3d133986b31f4b01",
"max_forks_repo_licenses": [
"BSD-2-Clause"
],
"max_forks_repo_name": "vkeller/math-454",
"max_forks_repo_path": "projects/CG/GENMAT/matrix-market-suite/src/MPI/operations/DMxV-MPI.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "0bf3a81214f094dbddec868d3d133986b31f4b01",
"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": "vkeller/math-454",
"max_issues_repo_path": "projects/CG/GENMAT/matrix-market-suite/src/MPI/operations/DMxV-MPI.c",
"max_line_length": 109,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "0bf3a81214f094dbddec868d3d133986b31f4b01",
"max_stars_repo_licenses": [
"BSD-2-Clause"
],
"max_stars_repo_name": "vkeller/math-454",
"max_stars_repo_path": "projects/CG/GENMAT/matrix-market-suite/src/MPI/operations/DMxV-MPI.c",
"max_stars_repo_stars_event_max_datetime": "2021-05-19T13:31:49.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-05-19T13:31:49.000Z",
"num_tokens": 1630,
"size": 5788
} |
//
// global.h
// Agile_RRT
//
// Created by Timothy M. Caldwell.
// Copyright (c) 2015 Timothy M. Caldwell. Refer to license.txt
//
#ifndef __Agile_RRT__global__
#define __Agile_RRT__global__
#include <fstream>
//#include <string>
//#include <sstream>
#include <iostream>
#include <iomanip>
#include <stdlib.h>
#include <math.h>
#include <random>
//boost libraries
#include <boost/numeric/odeint.hpp>
//gsl libraries
#include <gsl/gsl_spline.h>
#include <gsl/gsl_integration.h>
#include <gsl/gsl_errno.h>
//Eigen libraries
#include <eigen3/Eigen/Dense>
#include <eigen3/Eigen/Core>
#include <eigen3/Eigen/Geometry>
//namespaces
using namespace std;
namespace odeint = boost::numeric::odeint;
extern const int NI; // Constant; Number of inputs to the dynamic system
extern const int NS; // Constant; Number of states to the dynamic system
extern const double kLARGENUM; // Constant; A sufficiently large number
// Constants; For integration using odeint
extern const int kMAX_NUM_INTEGRATION_STEPS;
extern const double kINTEGRATION_DT_START;
//integrate state types
extern const int kFREEDYNAMICS_TYPE;
extern const int kFEEDFORWARD_TYPE;
extern const int kTRACKPOINT_TYPE;
extern const int kTRACKTRAJECTORY_TYPE;
extern const int kLINEARSTEERINGPROJECTION_TYPE;
extern const int kLINEARSTEERINGPROJECTIONWCOST_TYPE;
//integrate linear state and ricatti types
extern const int kLTI_TYPE;
extern const int kLTV_TYPE;
//STMSlot2 types
extern const int kLTI_OPENLOOP_TYPE;
extern const int kLTI_CLOSEDLOOP_TYPE;
extern const int kLTV_OPENLOOP_TYPE;
extern const int kLTV_CLOSEDLOOP_TYPE;
//control type for linear state equation
extern const int kFREE_CONTROLTYPE;
extern const int kFEEDFORWARD_CONTROLTYPE;
extern const int kMINENERGY_OPENLOOP_CONTROLTYPE;
extern const int kMINENERGY_CLOSEDLOOP_CONTROLTYPE;
//Gramian types
extern const int kWW_GRAMIANTYPE;
extern const int kWWK_GRAMIANTYPE;
extern const int kSSK_GRAMIANTYPE;
typedef vector<double> ode_state_type; // odeint integrator state_type
///////////////////////////////
//Currently implemented as global. Needs to be updated for NS and NI
///////////////////////////////
// Eigen Matrix types of size NS or NI by NS or NI
typedef Eigen::Matrix< double , 8 , 8 > NSxNS_type;
typedef Eigen::Matrix< double , 8 , 1 > NSxNI_type;
typedef Eigen::Matrix< double , 1 , 1 > NIxNI_type;
typedef Eigen::Matrix< double , 1 , 8 > NIxNS_type;
typedef Eigen::Matrix< double , 8 , 1 > NSx1_type;
typedef Eigen::Matrix< double , 1 , 1 > NIx1_type;
struct constraints_struct {
Eigen::Matrix<double, 8, 2> xbounds; // list of upper and lower bounds for each state
Eigen::Matrix<double, 1, 2> ubounds; // list of upper and lower bounds for each input
// list of circle obstacles of radius obs_radii[.] at point (obs_Xs[.], obs_Ys[.])
vector< double > obs_radii;
vector< double > obs_Xs;
vector< double > obs_Ys;
};
// list of upper and lower bounds for each state and input. Should be the same as those set in constraints_struct
struct sampling_bounds_struct {
Eigen::Matrix<double, 8, 2> xbounds;
Eigen::Matrix<double, 1, 2> ubounds;
};
// stepper type used by odeint for integration
//typedef odeint::controlled_runge_kutta< odeint::runge_kutta_dopri5<ode_state_type> > stepper_type; // Alternative stepper choice
typedef odeint::controlled_runge_kutta< odeint::runge_kutta_cash_karp54<ode_state_type> > stepper_type;
// Printing parameters
extern const int kPRINT_PRECISION; // Printing precision number
extern const double kPRINT_CHOP_BOUND; // Lower bound for chopping (i.e. if abs(x)<kPRINT_CHOP_BOUND, then 0 is returned)
// prints a vec to stream in a form easily readable by Mathematica.
extern void PrintVec(const vector<double> & vec, ostream * stream = &(std::cout));
extern void PrintVec(const vector<double> & vec, const string & name, ostream * stream);
#endif // __Agile_RRT__global__
| {
"alphanum_fraction": 0.735286814,
"avg_line_length": 33.5583333333,
"ext": "h",
"hexsha": "f63a90237b9475746c531f56fe696aa66a2220c6",
"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": "d0b8fe4464c86dc3b9843d7110eaeef4f2589993",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "timocaldwell/agile_rrt",
"max_forks_repo_path": "global.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "d0b8fe4464c86dc3b9843d7110eaeef4f2589993",
"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": "timocaldwell/agile_rrt",
"max_issues_repo_path": "global.h",
"max_line_length": 132,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "d0b8fe4464c86dc3b9843d7110eaeef4f2589993",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "timocaldwell/agile_rrt",
"max_stars_repo_path": "global.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1037,
"size": 4027
} |
#ifndef __INC_ESTIMATE_THREADED__
#define __INC_ESTIMATE_THREADED__
#include <unistd.h>
#include <pthread.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_vector.h>
/* common data block for most options to be passed around */
struct optstruct;
struct modelstruct;
//! used to pass the args into estimate_thread_function
struct estimate_thetas_params{
// these are direct copies of the respective data structures
struct optstruct* options;
struct modelstruct* the_model;
// things needed specifically for the estimation
gsl_rng* random_number;
gsl_matrix* h_matrix;
int max_tries;
int success_count;
double lhood_current;
double my_best; // want to check on the local best values
} estimate_thetas_params;
#define USEMUTEX
#include "../modelstruct.h"
#include "../optstruct.h"
void estimate_thetas_threaded(modelstruct* the_model, optstruct* options);
// this won't work unless it has access to the nasty globals in estimate_threaded.c
void* estimate_thread_function(void* args);
int get_number_cpus(void);
void setup_params(struct estimate_thetas_params *params, modelstruct* the_model, optstruct* options, int nthreads, int max_tries);
void fprintPt(FILE *f, pthread_t pt);
// see the source for defs of the number of threads etc etc
#endif
| {
"alphanum_fraction": 0.7842227378,
"avg_line_length": 25.86,
"ext": "h",
"hexsha": "1c5893ad9e256e980465c9d2d0699d0a24663203",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2021-01-30T16:43:33.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-01-30T16:43:33.000Z",
"max_forks_repo_head_hexsha": "7d926ad04a791c7694defd88db41c13f7ee4e6aa",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "MADAI/MADAIEmulator",
"max_forks_repo_path": "src/libEmu/estimate_threaded.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "7d926ad04a791c7694defd88db41c13f7ee4e6aa",
"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": "MADAI/MADAIEmulator",
"max_issues_repo_path": "src/libEmu/estimate_threaded.h",
"max_line_length": 130,
"max_stars_count": 2,
"max_stars_repo_head_hexsha": "1c11f69c535acef8159ef0e780cca343785ea004",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "jackdawjackdaw/emulator",
"max_stars_repo_path": "src/libEmu/estimate_threaded.h",
"max_stars_repo_stars_event_max_datetime": "2017-06-02T00:34:49.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-04-02T17:37:42.000Z",
"num_tokens": 303,
"size": 1293
} |
/* Author: G. Jungman */
/* Convenience header */
#ifndef __GSL_SPECFUNC_H__
#define __GSL_SPECFUNC_H__
#if !defined( GSL_FUN )
# if !defined( GSL_DLL )
# define GSL_FUN extern
# elif defined( BUILD_GSL_DLL )
# define GSL_FUN extern __declspec(dllexport)
# else
# define GSL_FUN extern __declspec(dllimport)
# endif
#endif
#include <gsl/gsl_sf.h>
#endif /* __GSL_SPECFUNC_H__ */
| {
"alphanum_fraction": 0.6666666667,
"avg_line_length": 20.2857142857,
"ext": "h",
"hexsha": "7a7205db14cb83be512b60ca6f6c37911a16b14f",
"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": "099b66cb1285d19955e953f916ec6c12c68f2242",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "berkus/music-cs",
"max_forks_repo_path": "deps/include/gsl/gsl_specfunc.h",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "099b66cb1285d19955e953f916ec6c12c68f2242",
"max_issues_repo_issues_event_max_datetime": "2021-01-13T16:28:48.000Z",
"max_issues_repo_issues_event_min_datetime": "2021-01-11T01:08:01.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "berkus/music-cs",
"max_issues_repo_path": "deps/include/gsl/gsl_specfunc.h",
"max_line_length": 49,
"max_stars_count": 2,
"max_stars_repo_head_hexsha": "099b66cb1285d19955e953f916ec6c12c68f2242",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "berkus/music-cs",
"max_stars_repo_path": "deps/include/gsl/gsl_specfunc.h",
"max_stars_repo_stars_event_max_datetime": "2021-01-09T16:18:47.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-01-09T05:48:44.000Z",
"num_tokens": 118,
"size": 426
} |
#include <stdio.h>
#include <gsl/gsl_multifit.h>
#include <gsl/gsl_randist.h>
int
dofit(const gsl_multifit_robust_type *T,
const gsl_matrix *X, const gsl_vector *y,
gsl_vector *c, gsl_matrix *cov)
{
int s;
gsl_multifit_robust_workspace * work
= gsl_multifit_robust_alloc (T, X->size1, X->size2);
s = gsl_multifit_robust (X, y, c, cov, work);
gsl_multifit_robust_free (work);
return s;
}
int
main (int argc, char **argv)
{
int i;
size_t n;
const size_t p = 2; /* linear fit */
gsl_matrix *X, *cov;
gsl_vector *x, *y, *c, *c_ols;
const double a = 1.45; /* slope */
const double b = 3.88; /* intercept */
gsl_rng *r;
if (argc != 2)
{
fprintf (stderr,"usage: robfit n\n");
exit (-1);
}
n = atoi (argv[1]);
X = gsl_matrix_alloc (n, p);
x = gsl_vector_alloc (n);
y = gsl_vector_alloc (n);
c = gsl_vector_alloc (p);
c_ols = gsl_vector_alloc (p);
cov = gsl_matrix_alloc (p, p);
r = gsl_rng_alloc(gsl_rng_default);
/* generate linear dataset */
for (i = 0; i < n - 3; i++)
{
double dx = 10.0 / (n - 1.0);
double ei = gsl_rng_uniform(r);
double xi = -5.0 + i * dx;
double yi = a * xi + b;
gsl_vector_set (x, i, xi);
gsl_vector_set (y, i, yi + ei);
}
/* add a few outliers */
gsl_vector_set(x, n - 3, 4.7);
gsl_vector_set(y, n - 3, -8.3);
gsl_vector_set(x, n - 2, 3.5);
gsl_vector_set(y, n - 2, -6.7);
gsl_vector_set(x, n - 1, 4.1);
gsl_vector_set(y, n - 1, -6.0);
/* construct design matrix X for linear fit */
for (i = 0; i < n; ++i)
{
double xi = gsl_vector_get(x, i);
gsl_matrix_set (X, i, 0, 1.0);
gsl_matrix_set (X, i, 1, xi);
}
/* perform robust and OLS fit */
dofit(gsl_multifit_robust_ols, X, y, c_ols, cov);
dofit(gsl_multifit_robust_bisquare, X, y, c, cov);
/* output data and model */
for (i = 0; i < n; ++i)
{
double xi = gsl_vector_get(x, i);
double yi = gsl_vector_get(y, i);
gsl_vector_view v = gsl_matrix_row(X, i);
double y_ols, y_rob, y_err;
gsl_multifit_robust_est(&v.vector, c, cov, &y_rob, &y_err);
gsl_multifit_robust_est(&v.vector, c_ols, cov, &y_ols, &y_err);
printf("%g %g %g %g\n", xi, yi, y_rob, y_ols);
}
#define C(i) (gsl_vector_get(c,(i)))
#define COV(i,j) (gsl_matrix_get(cov,(i),(j)))
{
printf ("# best fit: Y = %g + %g X\n",
C(0), C(1));
printf ("# covariance matrix:\n");
printf ("# [ %+.5e, %+.5e\n",
COV(0,0), COV(0,1));
printf ("# %+.5e, %+.5e\n",
COV(1,0), COV(1,1));
}
gsl_matrix_free (X);
gsl_vector_free (x);
gsl_vector_free (y);
gsl_vector_free (c);
gsl_vector_free (c_ols);
gsl_matrix_free (cov);
gsl_rng_free(r);
return 0;
}
| {
"alphanum_fraction": 0.5694891033,
"avg_line_length": 22.756097561,
"ext": "c",
"hexsha": "ce9a3859805f54e91b36e8c17a8ec8ac3458a0d2",
"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/doc/examples/robfit.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/doc/examples/robfit.c",
"max_line_length": 69,
"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/doc/examples/robfit.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": 1018,
"size": 2799
} |
/* sum/demo.c
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Gerard Jungman, Brian Gough
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include <stdio.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_sum.h>
#define N 20
int
main (void)
{
double t[N];
double sum_accel, err;
double sum = 0;
int n;
gsl_sum_levin_u_workspace * w = gsl_sum_levin_u_alloc (N);
const double zeta_2 = M_PI * M_PI / 6.0;
/* terms for zeta(2) = \sum_{n=1}^{\infty} 1/n^2 */
for (n = 0; n < N; n++)
{
double np1 = n + 1.0;
t[n] = 1.0 / (np1 * np1);
sum += t[n] ;
}
gsl_sum_levin_u_accel (t, N, w, &sum_accel, &err);
printf("term-by-term sum = % .16f using %d terms\n", sum, N) ;
printf("term-by-term sum = % .16f using %d terms\n",
w->sum_plain, w->terms_used) ;
printf("exact value = % .16f\n", zeta_2) ;
printf("accelerated sum = % .16f using %d terms\n",
sum_accel, w->terms_used) ;
printf("estimated error = % .16f\n", err) ;
printf("actual error = % .16f\n", sum_accel - zeta_2) ;
gsl_sum_levin_u_free (w);
return 0;
}
| {
"alphanum_fraction": 0.6425792107,
"avg_line_length": 27.6769230769,
"ext": "c",
"hexsha": "1a1b4ba0a630f8635166ad404c8558a934d27711",
"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/sum/demo.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "zzpwahaha/Chimera-Control-Trim",
"max_issues_repo_path": "Chimera/3rd_Party/GSL_MSVC/sum/demo.c",
"max_line_length": 81,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "zzpwahaha/Chimera-Control-Trim",
"max_stars_repo_path": "Chimera/3rd_Party/GSL_MSVC/sum/demo.c",
"max_stars_repo_stars_event_max_datetime": "2021-06-14T11:51:37.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-06-14T11:51:37.000Z",
"num_tokens": 573,
"size": 1799
} |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
#pragma once
#include <memory>
#include <future>
#include <array>
#include <gsl\gsl>
#include <boost\optional.hpp>
#include "Data\Data.h"
#include "MageSettings.h"
#include "Device\Device.h"
#include <SensorSample.h>
#include <Plat/CameraDevice/CameraSettings.h>
namespace mage
{
class PoseHistory;
/* Entry point of the MAGESlam library */
class MAGESlam
{
struct Impl;
public:
struct CameraConfiguration
{
CameraIdentity CameraIdentity;
Size Size{};
PixelFormat Format;
Matrix Extrinsics;
CameraConfiguration(mage::CameraIdentity cameraIdentity, const mage::Size& size, PixelFormat format, const Matrix& extrinsics)
: CameraIdentity{ cameraIdentity },
Format{ format },
Size{ size },
Extrinsics{ extrinsics }
{
};
};
struct FrameFormat
{
const mage::FrameId FrameId;
std::shared_ptr<const calibration::CameraModel> CameraModel;
std::chrono::system_clock::time_point Timestamp;
mira::CameraSettings CameraSettings;
FrameFormat(
const mage::FrameId& frameId,
std::shared_ptr<const calibration::CameraModel> cameraModel,
const std::chrono::system_clock::time_point& timestamp,
const mira::CameraSettings& cameraSettings)
: FrameId{ frameId },
CameraModel{ cameraModel },
Timestamp{ timestamp },
CameraSettings{ cameraSettings }
{}
};
struct Tracking
{
/*
The Matrix is a row-major column-vector view matrix. right handed
R, R, R, Tx
R, R, R, Ty
R, R, R, Tz
0, 0, 0, 1
*/
Matrix Pose;
TrackingState State;
Tracking(const Matrix& mat, TrackingState state)
: Pose{ mat }, State{ state }
{}
Tracking()
: Pose{ }, State{ TrackingState::SKIPPED }
{}
bool IsPoseGood() const
{
return State == TrackingState::TRACKING;
}
bool IsPoseSkipped() const
{
return State == TrackingState::SKIPPED;
}
};
struct TrackedFrame
{
Tracking Tracking;
std::shared_ptr<const calibration::CameraModel> CameraModel;
Depth Depth;
TrackedFrame(const MAGESlam::Tracking& tracking, std::shared_ptr<const calibration::CameraModel> cameraModel, const mage::Depth& depth)
: Tracking{ tracking }, CameraModel{ cameraModel }, Depth{ depth }
{}
TrackedFrame() = default;
};
class FossilizedMap
{
public:
~FossilizedMap();
/*
Get the most up-to-date pose for the specified frame ID
*/
std::vector<boost::optional<MAGESlam::TrackedFrame>> GetTrackingResultsForFrames(const gsl::span<const FrameId> frameIds) const;
bool TryGetVolumeOfInterest(AxisAlignedVolume& volumeOfInterest) const;
private:
FossilizedMap(std::unique_ptr<const PoseHistory> history, std::vector<Position> mapPoints, const MageSlamSettings& settings);
friend class MAGESlam;
struct Impl;
std::unique_ptr<Impl> m_impl;
};
explicit MAGESlam(const MageSlamSettings&, gsl::span<const CameraConfiguration> cameras, const device::IMUCharacterization& imu);
MAGESlam(const MAGESlam&) = delete;
MAGESlam& operator =(const MAGESlam&) = delete;
struct Frame
{
FrameFormat Format;
gsl::span<const uint8_t> Bytes;
Frame(const FrameFormat& format, gsl::span<const uint8_t> bytes)
: Format(format),
Bytes(bytes)
{}
};
/*
Processes an image frame and returns a future Pose and the state of the
tracker while it was generating it.
*/
std::future<Tracking> ProcessFrame(const Frame& frame);
/*
Processes an stereo image pair and returns a future Pose for each frame and the state of the
tracker while it was generating it.
*/
std::pair<std::future<Tracking>, std::future<Tracking>> ProcessStereoFrames(const Frame& one, const Frame& two);
/*
Get the most up-to-date pose for the specified frame ID
*/
std::vector<boost::optional<MAGESlam::TrackedFrame>> GetTrackingResultsForFrames(const gsl::span<const FrameId> frameIds) const;
// adds a sensor sample to the sample queue for sensor fusion
void AddSensorSample(const SensorSample& sample);
// get normalized vector in mage's world coordinate frame describing the fuser's gravity estimate
// returns whether the gravity estimate is valid.
bool GetGravityDirection(Direction& gravDir) const;
// gets the scale to apply to mage to bring it to meters as estimated by
// the stereo tracking code
float GetStereoMageMeterEstimate() const;
// gets the scale to apply to mage to bring it to meters as estimated by the fuser
// returns whether the scale is valid
bool GetScaleFromIMU(float& scaleMAGEtoMeters) const;
bool TryGetVolumeOfInterest(AxisAlignedVolume& volumeOfInterest) const;
// Destroys the current instance of MAGESlam and converts it to a fossilized map
// that can be used for offline queries of frame poses
static std::unique_ptr<FossilizedMap> Fossilize(std::unique_ptr<MAGESlam> slam);
~MAGESlam();
private:
std::unique_ptr<Impl> m_impl;
};
}
| {
"alphanum_fraction": 0.5838519489,
"avg_line_length": 32.3068783069,
"ext": "h",
"hexsha": "497507c79117dfcd7b5add99ed715dcd9f054a05",
"lang": "C",
"max_forks_count": 16,
"max_forks_repo_forks_event_max_datetime": "2022-03-31T15:36:49.000Z",
"max_forks_repo_forks_event_min_datetime": "2020-05-07T03:09:13.000Z",
"max_forks_repo_head_hexsha": "ba79a4e6315689c072c29749de18d70279a4c5e4",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "syntheticmagus/mageslam",
"max_forks_repo_path": "Core/MAGESLAM/Source/MageSlam.h",
"max_issues_count": 3,
"max_issues_repo_head_hexsha": "ba79a4e6315689c072c29749de18d70279a4c5e4",
"max_issues_repo_issues_event_max_datetime": "2020-10-08T07:43:32.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-06-01T00:34:01.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "syntheticmagus/mageslam",
"max_issues_repo_path": "Core/MAGESLAM/Source/MageSlam.h",
"max_line_length": 147,
"max_stars_count": 70,
"max_stars_repo_head_hexsha": "ba79a4e6315689c072c29749de18d70279a4c5e4",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "syntheticmagus/mageslam",
"max_stars_repo_path": "Core/MAGESLAM/Source/MageSlam.h",
"max_stars_repo_stars_event_max_datetime": "2022-02-11T01:04:54.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-05-07T03:09:09.000Z",
"num_tokens": 1257,
"size": 6106
} |
#include <assert.h>
#include <math.h>
#include <stdlib.h>
#include <gsl/gsl_complex.h>
#include <gsl/gsl_complex_math.h>
#include <gsl/gsl_poly.h>
#include "userFunc.h"
#define G 6.67384e-8 /* 2010 CODATA value in CGS units */
#define C 2.99792458e10 /* Exact value in CGS units */
#define ALPHAMIN 1.0e-3 /* Minimum alpha allowed for numerical reasons */
#define YR (365.25*24.0*3600.0) /* 1 yr in sec */
#define MYR (1.0e6*YR) /* 1 Myr in seconds */
#define MSUN 1.9886e33 /* Solar mass in g */
/**************************************************************************/
/* This defines userFunc routines for the Krumholz & Kruijssen CMZ */
/* disk model including feedback */
/**************************************************************************/
/* Define the parameters to be used here */
typedef struct {
double eta;
double sigmath;
double shapefac;
double zetad;
double alphacoef;
double epsff0;
long tctr;
double p_per_sn;
double e_per_sn;
double star_rad_var;
double col_min;
double sigma_max;
double col_floor;
double en_wind;
void *wksp; /* This a placeholder for the extra memory stored at
the end of the parameters for temporary workspace
and to store the SF history. The size of storage
here will be (nbin_SB99+5)*grd->nr; we implement
pointers to this data via macro, below */
} paramType;
#define MSRC_TMP(p) ((double *) &(((paramType *) (p))->wksp))
#define PDOT(p,g) ((double *) &(((paramType *) (p))->wksp) + (g)->nr)
#define EDOT(p,g) ((double *) &(((paramType *) (p))->wksp) + 2*(g)->nr)
#define MDOT(p,g) ((double *) &(((paramType *) (p))->wksp) + 3*(g)->nr)
#define SIGMASTAR(p,g) ((double *) &(((paramType *) (p))->wksp) + 4*(g)->nr)
/* Declare some utility functions to compute the SFR, mass loss rate,
and momentum and energy injection rate per unit area */
void injection_rate(double *mstar, double p_per_sn, double e_per_sn,
double *pdot_tot, double *edot_tot, double *mdot_tot);
void sfrwind(const grid *grd, const double *col, const double *pres,
void *params, double *sigma_SFR, double *sigma_wind);
/* Data from starburst99 */
const int nbin_SB99 = 1000; /* Number of output times */
const double dt_SB99 = 0.05; /* Output time interval in Myr */
/* Supernova rate, expressed as log SNe / year / 10^6 Msun of stars, for stellar populations of different ages */
const double snr_SB99[1000] =
{ -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -3.64, -3.33, -3.32, -3.31, -3.31, -3.28, -3.30, -3.27, -3.29, -3.28, -3.28, -3.25, -3.25, -3.27, -3.26, -3.24, -3.27, -3.24, -3.26, -3.24, -3.26, -3.26, -3.26, -3.25, -3.25, -3.25, -3.25, -3.25, -3.25, -3.22, -3.22, -3.24, -3.24, -3.22, -3.22, -3.24, -3.26, -3.26, -3.26, -3.26, -3.26, -3.26, -3.26, -3.26, -3.26, -3.26, -3.24, -3.26, -3.26, -3.26, -3.26, -3.26, -3.26, -3.26, -3.26, -3.26, -3.26, -3.26, -3.26, -3.26, -3.26, -3.26, -3.26, -3.26, -3.26, -3.26, -3.26, -3.26, -3.27, -3.27, -3.27, -3.27, -3.27, -3.27, -3.27, -3.27, -3.27, -3.27, -3.27, -3.28, -3.28, -3.28, -3.28, -3.28, -3.28, -3.28, -3.28, -3.28, -3.28, -3.28, -3.28, -3.28, -3.28, -3.29, -3.29, -3.29, -3.29, -3.29, -3.29, -3.29, -3.29, -3.29, -3.29, -3.29, -3.29, -3.29, -3.29, -3.29, -3.30, -3.30, -3.30, -3.33, -3.33, -3.33, -3.34, -3.34, -3.34, -3.34, -3.35, -3.35, -3.35, -3.35, -3.35, -3.35, -3.36, -3.36, -3.36, -3.36, -3.36, -3.37, -3.37, -3.37, -3.37, -3.37, -3.37, -3.38, -3.38, -3.38, -3.38, -3.38, -3.38, -3.39, -3.39, -3.39, -3.39, -3.39, -3.39, -3.40, -3.40, -3.40, -3.40, -3.40, -3.40, -3.40, -3.41, -3.41, -3.41, -3.41, -3.41, -3.41, -3.42, -3.42, -3.42, -3.42, -3.42, -3.42, -3.42, -3.42, -3.43, -3.43, -3.43, -3.43, -3.43, -3.43, -3.43, -3.44, -3.44, -3.44, -3.44, -3.44, -3.44, -3.44, -3.44, -3.45, -3.45, -3.45, -3.45, -3.45, -3.45, -3.45, -3.45, -3.45, -3.45, -3.46, -3.46, -3.46, -3.46, -3.46, -3.46, -3.46, -3.46, -3.47, -3.47, -3.47, -3.47, -3.47, -3.47, -3.47, -3.47, -3.47, -3.48, -3.48, -3.48, -3.48, -3.48, -3.48, -3.48, -3.48, -3.48, -3.48, -3.49, -3.49, -3.49, -3.49, -3.49, -3.49, -3.49, -3.49, -3.49, -3.49, -3.50, -3.50, -3.50, -3.50, -3.50, -3.50, -3.50, -3.50, -3.50, -3.50, -3.51, -3.51, -3.51, -3.51, -3.51, -3.51, -3.51, -3.51, -3.51, -3.51, -3.51, -3.52, -3.52, -3.52, -3.52, -3.52, -3.52, -3.52, -3.52, -3.52, -3.52, -3.52, -3.53, -3.53, -3.53, -3.53, -3.53, -3.53, -3.53, -3.53, -3.53, -3.53, -3.53, -3.54, -3.54, -3.54, -3.54, -3.54, -3.54, -3.54, -3.54, -3.54, -3.54, -3.54, -3.54, -3.54, -3.55, -3.55, -3.55, -3.55, -3.55, -3.55, -3.55, -3.55, -3.55, -3.55, -3.55, -3.55, -3.55, -3.55, -3.55, -3.56, -3.56, -3.56, -3.56, -3.56, -3.56, -3.56, -3.56, -3.56, -3.56, -3.56, -3.56, -3.56, -3.57, -3.57, -3.57, -3.57, -3.57, -3.57, -3.57, -3.57, -3.57, -3.57, -3.57, -3.57, -3.57, -3.57, -3.58, -3.58, -3.58, -3.58, -3.58, -3.58, -3.58, -3.58, -3.58, -3.58, -3.58, -3.58, -3.58, -3.58, -3.58, -3.59, -3.59, -3.59, -3.59, -3.59, -3.59, -3.59, -3.59, -3.59, -3.59, -3.59, -3.59, -3.59, -3.59, -3.59, -3.60, -3.60, -3.60, -3.60, -3.60, -3.60, -3.60, -3.60, -3.60, -3.60, -3.60, -3.60, -3.60, -3.60, -3.60, -3.61, -3.61, -3.61, -3.61, -3.61, -3.61, -3.61, -3.61, -3.61, -3.61, -3.61, -3.61, -3.61, -3.61, -3.61, -3.61, -3.61, -3.62, -3.62, -3.62, -3.62, -3.62, -3.62, -3.62, -3.62, -3.62, -3.62, -3.62, -3.62, -3.62, -3.62, -3.62, -3.62, -3.63, -3.63, -3.63, -3.63, -3.63, -3.63, -3.63, -3.63, -3.63, -3.63, -3.63, -3.63, -3.63, -3.63, -3.63, -3.63, -3.63, -3.63, -3.64, -3.64, -3.64, -3.64, -3.64, -3.64, -3.64, -3.64, -3.64, -3.64, -3.64, -3.64, -3.64, -3.64, -3.64, -3.64, -3.64, -3.64, -3.65, -3.65, -3.65, -3.65, -3.65, -3.65, -3.65, -3.65, -3.65, -3.65, -3.65, -3.65, -3.65, -3.65, -3.65, -3.65, -3.65, -3.65, -3.65, -3.66, -3.66, -3.66, -3.66, -3.66, -3.66, -3.66, -3.66, -3.66, -3.66, -3.66, -3.66, -3.66, -3.66, -3.66, -3.66, -3.66, -3.66, -3.66, -3.67, -3.67, -3.67, -3.67, -3.67, -3.67, -3.67, -3.67, -3.67, -3.67, -3.67, -3.67, -3.67, -3.67, -3.67, -3.67, -3.67, -3.67, -3.67, -3.67, -3.68, -3.68, -3.68, -3.68, -3.68, -3.68, -3.68, -3.68, -3.68, -3.68, -3.68, -3.68, -3.68, -3.68, -3.68, -3.68, -3.68, -3.68, -3.68, -3.68, -3.68, -3.69, -3.69, -3.69, -3.69, -3.69, -3.69, -3.69, -3.69, -3.69, -3.69, -3.69, -3.69, -3.69, -3.69, -3.69, -3.69, -3.69, -3.69, -3.69, -3.69, -3.69, -3.70, -3.68, -3.67, -3.67, -3.67, -3.67, -3.67, -3.67, -3.68, -3.68, -3.68, -3.68, -3.68, -3.68, -3.68, -3.68, -3.68, -3.68, -3.68, -3.68, -3.68, -3.68, -3.68, -3.68, -3.68, -3.68, -3.68, -3.68, -3.68, -3.68, -3.68, -3.68, -3.68, -3.68, -3.68, -3.68, -3.68, -3.68, -3.68, -3.68, -3.68, -3.69, -3.69, -3.69, -3.69, -3.69, -3.69, -3.69, -3.69, -3.69, -3.69, -3.69, -3.69, -3.69, -3.69, -3.69, -3.69, -3.69, -3.69, -3.69, -3.69, -3.69, -3.69, -3.69, -3.69, -3.69, -3.69, -3.69, -3.69, -3.69, -3.69, -3.69, -3.69, -3.69, -3.69, -3.69, -3.70, -3.70, -3.70, -3.70, -3.70, -3.70, -3.70, -3.70, -3.70, -3.70, -3.70, -3.70, -3.70, -3.70, -3.70, -3.70, -3.70, -3.70, -3.70, -3.70, -3.70, -3.70, -3.70, -3.70, -3.70, -3.70, -3.70, -3.70, -3.70, -3.70, -3.70, -3.70, -3.70, -3.70, -3.70, -3.71, -3.71, -3.71, -3.71, -3.71, -3.71, -3.71, -3.71, -3.71, -3.71, -3.71, -3.71, -3.71, -3.71, -3.71, -3.71, -3.71, -3.71, -3.71, -3.71, -3.71, -3.71, -3.71, -3.71, -3.71, -3.71, -3.71, -3.71, -3.71, -3.71, -3.71, -3.71, -3.71, -3.71, -3.71, -3.71, -3.71, -3.71, -3.71, -3.72, -3.72, -3.72, -3.72, -3.72, -3.72, -3.72, -3.74, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00 };
/* Luminosity of stellar populations of different ages, expressed as log of the luminosity in erg/s per 10^6 Msun worth of stars */
const double lum_SB99[1000] =
{ 42.496, 42.497, 42.498, 42.500, 42.501, 42.503, 42.505, 42.506, 42.508, 42.510, 42.512, 42.513, 42.515, 42.517, 42.519, 42.520, 42.522, 42.524, 42.526, 42.528, 42.530, 42.531, 42.533, 42.535, 42.537, 42.539, 42.541, 42.543, 42.545, 42.547, 42.549, 42.551, 42.553, 42.556, 42.558, 42.560, 42.562, 42.564, 42.567, 42.569, 42.572, 42.574, 42.576, 42.579, 42.582, 42.584, 42.587, 42.590, 42.593, 42.595, 42.598, 42.601, 42.603, 42.606, 42.609, 42.611, 42.614, 42.618, 42.619, 42.619, 42.616, 42.612, 42.607, 42.602, 42.593, 42.579, 42.566, 42.554, 42.541, 42.529, 42.517, 42.505, 42.493, 42.482, 42.471, 42.460, 42.450, 42.440, 42.431, 42.422, 42.413, 42.405, 42.396, 42.388, 42.380, 42.372, 42.364, 42.357, 42.349, 42.341, 42.334, 42.326, 42.319, 42.312, 42.304, 42.297, 42.289, 42.282, 42.274, 42.266, 42.258, 42.250, 42.243, 42.236, 42.228, 42.221, 42.214, 42.207, 42.200, 42.193, 42.187, 42.180, 42.174, 42.167, 42.161, 42.155, 42.149, 42.143, 42.136, 42.130, 42.124, 42.118, 42.113, 42.107, 42.101, 42.095, 42.089, 42.084, 42.078, 42.072, 42.067, 42.061, 42.055, 42.050, 42.044, 42.038, 42.033, 42.027, 42.021, 42.015, 42.010, 42.004, 41.999, 41.994, 41.988, 41.983, 41.978, 41.973, 41.967, 41.962, 41.957, 41.952, 41.947, 41.943, 41.937, 41.932, 41.927, 41.922, 41.917, 41.913, 41.908, 41.903, 41.898, 41.894, 41.889, 41.884, 41.879, 41.874, 41.870, 41.865, 41.860, 41.855, 41.851, 41.846, 41.841, 41.837, 41.833, 41.829, 41.824, 41.821, 41.817, 41.813, 41.809, 41.805, 41.801, 41.797, 41.794, 41.790, 41.786, 41.783, 41.779, 41.776, 41.772, 41.768, 41.765, 41.762, 41.758, 41.755, 41.751, 41.748, 41.745, 41.742, 41.738, 41.735, 41.732, 41.729, 41.726, 41.723, 41.719, 41.716, 41.713, 41.710, 41.707, 41.704, 41.701, 41.698, 41.695, 41.693, 41.690, 41.687, 41.684, 41.681, 41.679, 41.676, 41.673, 41.671, 41.667, 41.665, 41.662, 41.659, 41.656, 41.654, 41.651, 41.648, 41.645, 41.642, 41.639, 41.636, 41.634, 41.631, 41.628, 41.625, 41.622, 41.620, 41.617, 41.614, 41.611, 41.608, 41.606, 41.603, 41.599, 41.597, 41.594, 41.591, 41.588, 41.586, 41.583, 41.580, 41.578, 41.575, 41.572, 41.569, 41.566, 41.564, 41.561, 41.559, 41.556, 41.553, 41.551, 41.548, 41.545, 41.543, 41.540, 41.538, 41.535, 41.533, 41.530, 41.528, 41.525, 41.523, 41.521, 41.518, 41.516, 41.513, 41.511, 41.509, 41.506, 41.504, 41.502, 41.499, 41.497, 41.495, 41.492, 41.490, 41.488, 41.486, 41.484, 41.482, 41.480, 41.478, 41.475, 41.473, 41.471, 41.469, 41.467, 41.464, 41.462, 41.460, 41.458, 41.456, 41.454, 41.452, 41.450, 41.448, 41.445, 41.444, 41.442, 41.440, 41.438, 41.436, 41.434, 41.432, 41.430, 41.428, 41.426, 41.425, 41.423, 41.421, 41.419, 41.417, 41.416, 41.414, 41.412, 41.410, 41.409, 41.407, 41.406, 41.404, 41.402, 41.401, 41.399, 41.397, 41.396, 41.394, 41.392, 41.391, 41.390, 41.388, 41.387, 41.385, 41.384, 41.382, 41.381, 41.379, 41.378, 41.376, 41.375, 41.374, 41.373, 41.371, 41.370, 41.368, 41.367, 41.365, 41.364, 41.363, 41.361, 41.360, 41.359, 41.357, 41.356, 41.355, 41.353, 41.352, 41.351, 41.349, 41.348, 41.347, 41.346, 41.344, 41.343, 41.342, 41.340, 41.339, 41.338, 41.336, 41.335, 41.334, 41.332, 41.331, 41.330, 41.329, 41.328, 41.326, 41.325, 41.324, 41.323, 41.322, 41.320, 41.319, 41.318, 41.317, 41.315, 41.314, 41.313, 41.312, 41.311, 41.309, 41.308, 41.307, 41.306, 41.305, 41.304, 41.303, 41.302, 41.301, 41.300, 41.298, 41.297, 41.296, 41.295, 41.294, 41.292, 41.291, 41.290, 41.289, 41.288, 41.287, 41.286, 41.285, 41.284, 41.283, 41.282, 41.281, 41.279, 41.279, 41.277, 41.277, 41.276, 41.274, 41.273, 41.272, 41.271, 41.270, 41.269, 41.268, 41.267, 41.266, 41.265, 41.264, 41.263, 41.262, 41.261, 41.259, 41.259, 41.258, 41.257, 41.256, 41.254, 41.253, 41.252, 41.252, 41.251, 41.249, 41.248, 41.247, 41.246, 41.245, 41.244, 41.243, 41.242, 41.241, 41.240, 41.239, 41.238, 41.238, 41.236, 41.235, 41.234, 41.233, 41.232, 41.232, 41.231, 41.230, 41.230, 41.229, 41.227, 41.227, 41.225, 41.225, 41.224, 41.223, 41.222, 41.221, 41.220, 41.219, 41.218, 41.218, 41.217, 41.216, 41.215, 41.214, 41.213, 41.212, 41.211, 41.211, 41.209, 41.208, 41.208, 41.207, 41.206, 41.205, 41.204, 41.203, 41.203, 41.202, 41.201, 41.200, 41.199, 41.198, 41.198, 41.197, 41.196, 41.195, 41.194, 41.193, 41.192, 41.191, 41.191, 41.190, 41.189, 41.188, 41.187, 41.187, 41.186, 41.185, 41.184, 41.184, 41.183, 41.182, 41.181, 41.180, 41.180, 41.179, 41.178, 41.177, 41.176, 41.175, 41.175, 41.174, 41.173, 41.172, 41.171, 41.171, 41.170, 41.169, 41.168, 41.167, 41.166, 41.165, 41.165, 41.164, 41.163, 41.162, 41.162, 41.161, 41.160, 41.159, 41.159, 41.158, 41.157, 41.156, 41.156, 41.155, 41.154, 41.153, 41.152, 41.151, 41.150, 41.150, 41.149, 41.148, 41.147, 41.146, 41.146, 41.145, 41.144, 41.143, 41.143, 41.141, 41.141, 41.140, 41.139, 41.139, 41.138, 41.137, 41.136, 41.136, 41.135, 41.134, 41.134, 41.133, 41.118, 41.131, 41.130, 41.130, 41.129, 41.128, 41.128, 41.127, 41.126, 41.125, 41.125, 41.124, 41.123, 41.122, 41.121, 41.120, 41.119, 41.119, 41.118, 41.117, 41.116, 41.115, 41.114, 41.113, 41.113, 41.112, 41.111, 41.111, 41.110, 41.109, 41.108, 41.107, 41.107, 41.106, 41.105, 41.104, 41.104, 41.103, 41.102, 41.101, 41.100, 41.099, 41.099, 41.098, 41.097, 41.096, 41.095, 41.095, 41.094, 41.093, 41.093, 41.092, 41.091, 41.090, 41.089, 41.088, 41.088, 41.087, 41.086, 41.085, 41.085, 41.084, 41.084, 41.083, 41.082, 41.082, 41.081, 41.080, 41.079, 41.079, 41.078, 41.077, 41.076, 41.076, 41.075, 41.074, 41.073, 41.073, 41.072, 41.071, 41.070, 41.070, 41.069, 41.068, 41.068, 41.067, 41.066, 41.065, 41.065, 41.064, 41.063, 41.063, 41.062, 41.061, 41.060, 41.060, 41.059, 41.058, 41.058, 41.057, 41.056, 41.055, 41.055, 41.054, 41.053, 41.053, 41.052, 41.051, 41.050, 41.050, 41.049, 41.048, 41.048, 41.047, 41.046, 41.045, 41.045, 41.044, 41.043, 41.043, 41.042, 41.041, 41.041, 41.040, 41.040, 41.039, 41.038, 41.037, 41.036, 41.036, 41.035, 41.035, 41.034, 41.033, 41.033, 41.032, 41.031, 41.030, 41.030, 41.029, 41.028, 41.028, 41.027, 41.027, 41.026, 41.025, 41.024, 41.024, 41.023, 41.023, 41.022, 41.021, 41.020, 41.020, 41.019, 41.018, 41.017, 41.017, 41.016, 41.016, 41.015, 41.014, 41.014, 41.013, 41.012, 41.012, 41.011, 41.010, 41.010, 41.009, 41.008, 41.008, 41.007, 41.007, 41.006, 41.005, 41.005, 41.004, 41.003, 41.003, 41.002, 41.001, 41.000, 41.000, 40.999, 40.999, 40.998, 40.998, 40.997, 40.997, 40.996, 40.996, 40.995, 40.994, 40.994, 40.993, 40.993, 40.992, 40.992, 40.991, 40.990, 40.990, 40.989, 40.988, 40.988, 40.987, 40.986, 40.985, 40.985, 40.984, 40.984, 40.983, 40.983, 40.982, 40.981, 40.981, 40.980, 40.979, 40.979, 40.978, 40.978, 40.977, 40.976, 40.976, 40.975, 40.975, 40.974, 40.973, 40.973, 40.972, 40.971, 40.971, 40.970, 40.970, 40.969, 40.969, 40.968, 40.967, 40.967, 40.966, 40.966, 40.965, 40.964, 40.964, 40.963, 40.962, 40.962, 40.962, 40.961, 40.960, 40.942, 40.959, 40.958, 40.958, 40.957, 40.957, 40.956, 40.955, 40.955, 40.954, 40.954, 40.953, 40.953, 40.952, 40.951, 40.951, 40.950, 40.949, 40.949, 40.948, 40.948, 40.947, 40.946, 40.946, 40.945, 40.945, 40.944, 40.943, 40.943, 40.942, 40.942, 40.941, 40.941, 40.940, 40.939, 40.939, 40.938, 40.938, 40.937, 40.937, 40.936, 40.935, 40.935, 40.934, 40.934, 40.933, 40.933, 40.932, 40.931, 40.931, 40.930, 40.929, 40.929, 40.928, 40.928, 40.928, 40.927, 40.926, 40.926, 40.925, 40.925, 40.924, 40.923, 40.923, 40.922, 40.922, 40.921, 40.921, 40.920, 40.920, 40.919, 40.919, 40.918, 40.918, 40.917, 40.916, 40.916, 40.915, 40.915, 40.914, 40.914, 40.913, 40.912, 40.912, 40.911, 40.911, 40.911, 40.910, 40.909, 40.909, 40.908, 40.907, 40.907, 40.906, 40.906, 40.905, 40.905, 40.904, 40.904, 40.903, 40.902, 40.902, 40.901, 40.901, 40.900, 40.899, 40.899, 40.899, 40.898, 40.898, 40.897, 40.897, 40.897, 40.896, 40.895, 40.895, 40.894, 40.894, 40.893, 40.893, 40.892, 40.892, 40.891, 40.891, 40.890, 40.890, 40.889, 40.889, 40.888, 40.888, 40.887, 40.887, 40.886, 40.886, 40.885, 40.884, 40.884, 40.883, 40.883, 40.882, 40.881, 40.881, 40.880, 40.880, 40.879, 40.879, 40.878, 40.877 };
/* Wind momentum flux, expressed as log of the momentum in dyne per 10^6 Msun worth of stars */
const double pdot_wind_SB99[1000] =
{ 31.689, 31.695, 31.700, 31.705, 31.709, 31.714, 31.718, 31.723, 31.728, 31.732, 31.737, 31.741, 31.746, 31.750, 31.755, 31.759, 31.764, 31.768, 31.773, 31.778, 31.782, 31.787, 31.792, 31.796, 31.801, 31.805, 31.809, 31.814, 31.818, 31.822, 31.826, 31.829, 31.833, 31.836, 31.838, 31.841, 31.842, 31.843, 31.844, 31.843, 31.842, 31.839, 31.835, 31.830, 31.822, 31.812, 31.803, 31.821, 31.844, 31.868, 31.893, 31.929, 31.982, 32.001, 32.016, 32.012, 32.033, 32.064, 32.168, 32.222, 32.272, 32.308, 32.325, 32.339, 32.340, 32.336, 32.332, 32.329, 32.329, 32.295, 32.251, 32.214, 32.183, 32.160, 32.140, 32.118, 32.088, 32.011, 31.980, 31.946, 31.916, 31.885, 31.868, 31.842, 31.808, 31.805, 31.747, 31.751, 31.724, 31.707, 31.702, 31.673, 31.674, 31.630, 31.612, 31.595, 31.552, 31.545, 31.543, 31.526, 31.508, 31.494, 31.476, 31.421, 31.395, 31.389, 31.375, 31.373, 31.385, 31.157, 31.352, 31.337, 31.317, 31.352, 31.273, 31.245, 31.226, 31.185, 31.173, 31.125, 31.050, 31.063, 31.102, 31.113, 31.140, 31.160, 31.155, 31.046, 31.019, 31.004, 30.984, 30.981, 30.978, 30.979, 30.964, 30.954, 30.947, 30.937, 30.894, 30.895, 30.893, 30.896, 30.895, 30.895, 30.897, 30.898, 30.896, 30.895, 30.900, 30.903, 30.905, 30.905, 30.907, 30.909, 30.910, 30.914, 30.916, 30.911, 30.907, 30.892, 30.878, 30.859, 30.839, 30.818, 30.799, 30.777, 30.759, 30.739, 30.720, 30.699, 30.681, 30.664, 30.642, 30.624, 30.608, 30.585, 30.570, 30.549, 30.533, 30.514, 30.499, 30.478, 30.461, 30.444, 30.431, 30.414, 30.396, 30.383, 30.362, 30.351, 30.336, 30.315, 30.304, 30.285, 30.277, 30.260, 30.242, 30.235, 30.213, 30.203, 30.191, 30.179, 30.160, 30.149, 30.138, 30.124, 30.113, 30.094, 30.082, 30.073, 30.063, 30.043, 30.033, 30.023, 30.012, 29.999, 29.983, 29.972, 29.962, 29.951, 29.941, 29.930, 29.913, 29.903, 29.891, 29.878, 29.871, 29.861, 29.854, 29.846, 29.841, 29.821, 29.813, 29.798, 29.786, 29.775, 29.758, 29.745, 29.722, 29.700, 29.689, 29.650, 29.644, 29.604, 29.584, 29.571, 29.557, 29.544, 29.532, 29.520, 29.509, 29.500, 29.491, 29.482, 29.474, 29.464, 29.456, 29.447, 29.437, 29.429, 29.422, 29.415, 29.408, 29.401, 29.394, 29.387, 29.380, 29.373, 29.366, 29.360, 29.353, 29.346, 29.340, 29.333, 29.326, 29.320, 29.313, 29.307, 29.300, 29.293, 29.287, 29.281, 29.274, 29.268, 29.261, 29.255, 29.249, 29.242, 29.236, 29.230, 29.224, 29.217, 29.211, 29.205, 29.198, 29.192, 29.186, 29.180, 29.174, 29.168, 29.162, 29.156, 29.150, 29.144, 29.138, 29.131, 29.125, 29.119, 29.113, 29.107, 29.101, 29.096, 29.090, 29.084, 29.078, 29.072, 29.066, 29.061, 29.055, 29.049, 29.044, 29.038, 29.032, 29.026, 29.021, 29.015, 29.009, 29.004, 28.999, 28.993, 28.988, 28.982, 28.977, 28.972, 28.966, 28.961, 28.956, 28.951, 28.945, 28.941, 28.936, 28.930, 28.925, 28.920, 28.915, 28.910, 28.905, 28.900, 28.895, 28.889, 28.884, 28.879, 28.874, 28.868, 28.863, 28.858, 28.853, 28.848, 28.842, 28.837, 28.832, 28.827, 28.822, 28.817, 28.812, 28.807, 28.802, 28.797, 28.792, 28.787, 28.782, 28.777, 28.772, 28.768, 28.764, 28.758, 28.753, 28.749, 28.744, 28.739, 28.735, 28.730, 28.726, 28.721, 28.716, 28.712, 28.708, 28.703, 28.699, 28.694, 28.690, 28.685, 28.680, 28.677, 28.672, 28.667, 28.663, 28.659, 28.655, 28.651, 28.647, 28.642, 28.638, 28.634, 28.630, 28.626, 28.622, 28.618, 28.614, 28.609, 28.606, 28.602, 28.598, 28.594, 28.590, 28.587, 28.582, 28.578, 28.575, 28.571, 28.567, 28.563, 28.560, 28.556, 28.552, 28.548, 28.545, 28.541, 28.537, 28.534, 28.530, 28.527, 28.524, 28.519, 28.516, 28.513, 28.509, 28.506, 28.502, 28.499, 28.495, 28.491, 28.488, 28.484, 28.481, 28.478, 28.475, 28.472, 28.469, 28.465, 28.461, 28.458, 28.455, 28.447, 28.448, 28.445, 28.442, 28.439, 28.435, 28.433, 28.429, 28.426, 28.422, 28.419, 28.416, 28.413, 28.407, 28.406, 28.404, 28.400, 28.397, 28.395, 28.392, 28.386, 28.383, 28.385, 28.377, 28.374, 28.374, 28.369, 28.365, 28.366, 28.362, 28.360, 28.354, 28.355, 28.350, 28.347, 28.341, 28.342, 28.339, 28.339, 28.334, 28.331, 28.328, 28.326, 28.324, 28.321, 28.318, 28.315, 28.312, 28.310, 28.307, 28.305, 28.410, 28.373, 28.447, 28.424, 28.464, 28.443, 28.488, 28.484, 28.489, 28.487, 28.488, 28.486, 28.492, 28.488, 28.493, 28.491, 28.488, 28.485, 28.482, 28.486, 28.480, 28.482, 28.483, 28.478, 28.476, 28.478, 28.476, 28.475, 28.476, 28.469, 28.471, 28.466, 28.466, 28.470, 28.468, 28.462, 28.460, 28.462, 28.459, 28.456, 28.453, 28.454, 28.455, 28.453, 28.449, 28.448, 28.444, 28.444, 28.440, 28.441, 28.437, 28.435, 28.433, 28.436, 28.434, 28.431, 28.429, 28.426, 28.425, 28.423, 28.421, 28.417, 28.416, 28.415, 28.412, 28.409, 28.408, 28.405, 28.405, 28.401, 28.400, 28.397, 28.394, 28.394, 28.390, 28.388, 28.384, 28.383, 28.380, 28.376, 28.375, 28.372, 28.371, 28.371, 28.368, 28.366, 28.363, 28.363, 28.361, 28.359, 28.358, 28.358, 28.353, 28.354, 28.352, 28.351, 28.350, 28.350, 28.136, 28.349, 28.348, 28.346, 28.346, 28.346, 28.345, 28.343, 28.340, 28.340, 28.340, 28.339, 28.339, 28.336, 28.334, 28.333, 28.332, 28.331, 28.329, 28.329, 28.328, 28.328, 28.325, 28.323, 28.324, 28.321, 28.319, 28.318, 28.318, 28.317, 28.316, 28.315, 28.314, 28.312, 28.311, 28.310, 28.310, 28.307, 28.306, 28.305, 28.304, 28.303, 28.301, 28.301, 28.300, 28.299, 28.298, 28.297, 28.298, 28.294, 28.293, 28.294, 28.293, 28.291, 28.291, 28.289, 28.289, 28.288, 28.286, 28.285, 28.283, 28.284, 28.283, 28.283, 28.282, 28.280, 28.279, 28.277, 28.278, 28.276, 28.274, 28.273, 28.273, 28.273, 28.273, 28.270, 28.269, 28.269, 28.267, 28.266, 28.265, 28.266, 28.265, 28.263, 28.261, 28.261, 28.261, 28.259, 28.259, 28.258, 28.256, 28.256, 28.254, 28.254, 28.251, 28.253, 28.252, 28.252, 28.250, 28.249, 28.246, 28.248, 28.245, 28.245, 28.244, 28.244, 28.240, 28.239, 28.239, 28.238, 28.239, 28.238, 28.237, 28.234, 28.235, 28.234, 28.235, 28.235, 28.233, 28.229, 28.230, 28.226, 28.229, 28.229, 28.226, 28.225, 28.224, 28.225, 28.224, 28.223, 28.223, 28.220, 28.219, 28.218, 28.220, 28.218, 28.217, 28.216, 28.213, 28.213, 28.214, 28.212, 28.214, 28.209, 28.214, 28.208, 28.210, 28.205, 28.205, 28.206, 28.208, 28.203, 28.203, 28.202, 28.202, 28.201, 28.201, 28.201, 28.200, 28.198, 28.194, 28.193, 28.193, 28.199, 28.196, 28.196, 28.195, 28.193, 28.195, 28.189, 28.189, 28.188, 28.188, 28.186, 28.189, 28.186, 28.188, 28.187, 28.188, 28.181, 28.181, 28.181, 28.178, 28.178, 28.178, 28.176, 28.176, 28.176, 28.174, 28.175, 28.174, 28.173, 28.173, 28.172, 28.170, 28.170, 28.172, 28.171, 28.168, 28.168, 28.169, 28.167, 28.168, 28.167, 28.167, 28.164, 28.166, 28.162, 28.165, 28.165, 28.158, 28.157, 28.157, 28.155, 28.159, 28.156, 28.155, 28.156, 28.160, 28.151, 28.155, 28.149, 28.149, 28.155, 28.148, 28.148, 28.152, 28.145, 28.150, 28.150, 28.146, 28.146, 28.144, 28.143, 28.143, 28.142, 28.143, 28.142, 28.142, 28.142, 28.142, 28.136, 28.141, 28.139, 28.138, 28.135, 28.135, 28.138, 28.135, 28.129, 27.728, 28.133, 28.132, 28.132, 28.129, 28.131, 28.131, 28.129, 28.123, 28.122, 28.124, 28.121, 28.119, 28.123, 28.118, 28.125, 28.125, 28.116, 28.119, 28.119, 28.113, 28.114, 28.114, 28.114, 28.115, 28.112, 28.113, 28.110, 28.113, 28.108, 28.114, 28.106, 28.106, 28.112, 28.110, 28.112, 28.111, 28.111, 28.109, 28.102, 28.102, 28.098, 28.108, 28.109, 28.100, 28.107, 28.102, 28.106, 28.105, 28.105, 28.096, 28.095, 28.091, 28.095, 28.092, 28.092, 28.092, 28.098, 28.089, 28.091, 28.098, 28.098, 28.090, 28.090, 28.086, 28.086, 28.096, 28.087, 28.092, 28.092, 28.092, 28.092, 28.088, 28.087, 28.084, 28.082, 28.084, 28.088, 28.088, 28.088, 28.088, 28.088, 28.076, 28.087, 28.087, 28.079, 28.087, 28.073, 28.078, 28.083, 28.083, 28.073, 28.081, 28.072, 28.080, 28.071, 28.073, 28.073, 28.072, 28.076, 28.080, 28.072, 28.066, 28.073, 28.078, 28.078, 28.071, 28.071, 28.071, 28.066, 28.066, 28.065, 28.056, 28.069, 28.053, 28.051, 28.061, 28.049, 28.049, 28.049, 28.051, 28.048, 28.048, 28.041, 28.041, 28.041, 28.040, 28.040, 28.041, 28.039, 28.039, 28.026, 28.035, 28.026, 28.026, 28.025, 28.025, 28.032, 28.023, 28.031, 28.021, 28.021, 28.021, 28.020, 28.017, 28.015, 28.017, 28.016 };
/* Wind energy flux, expressed as log of the power in erg/s per 10^6 Msun worth of stars */
const double edot_wind_SB99[1000] =
{ 39.937, 39.941, 39.944, 39.948, 39.951, 39.953, 39.957, 39.960, 39.963, 39.966, 39.969, 39.972, 39.975, 39.977, 39.980, 39.983, 39.986, 39.989, 39.991, 39.994, 39.997, 39.999, 40.002, 40.004, 40.006, 40.008, 40.010, 40.012, 40.013, 40.014, 40.015, 40.016, 40.016, 40.016, 40.015, 40.014, 40.012, 40.009, 40.006, 40.001, 39.995, 39.988, 39.980, 39.970, 39.958, 39.943, 39.929, 39.937, 39.949, 39.960, 39.971, 39.991, 40.022, 40.026, 40.026, 40.012, 40.012, 40.011, 40.116, 40.169, 40.215, 40.250, 40.273, 40.298, 40.303, 40.295, 40.288, 40.278, 40.272, 40.243, 40.208, 40.179, 40.154, 40.132, 40.113, 40.087, 40.055, 39.949, 39.898, 39.849, 39.803, 39.750, 39.722, 39.691, 39.649, 39.644, 39.587, 39.595, 39.564, 39.545, 39.541, 39.510, 39.512, 39.453, 39.429, 39.418, 39.393, 39.385, 39.379, 39.350, 39.323, 39.296, 39.260, 39.211, 39.181, 39.169, 39.145, 39.138, 39.146, 38.963, 39.105, 39.091, 39.070, 39.126, 39.017, 38.986, 38.962, 38.918, 38.901, 38.856, 38.788, 38.790, 38.812, 38.819, 38.833, 38.843, 38.837, 38.762, 38.743, 38.723, 38.701, 38.690, 38.684, 38.683, 38.670, 38.663, 38.656, 38.650, 38.629, 38.629, 38.627, 38.629, 38.629, 38.630, 38.633, 38.635, 38.635, 38.635, 38.639, 38.642, 38.645, 38.646, 38.649, 38.650, 38.655, 38.659, 38.662, 38.659, 38.653, 38.638, 38.621, 38.602, 38.580, 38.557, 38.537, 38.514, 38.494, 38.473, 38.453, 38.432, 38.413, 38.396, 38.374, 38.356, 38.341, 38.320, 38.306, 38.285, 38.271, 38.253, 38.239, 38.219, 38.204, 38.188, 38.175, 38.160, 38.142, 38.130, 38.111, 38.101, 38.087, 38.068, 38.058, 38.041, 38.033, 38.017, 38.001, 37.994, 37.975, 37.965, 37.954, 37.942, 37.926, 37.915, 37.905, 37.892, 37.883, 37.865, 37.854, 37.845, 37.835, 37.818, 37.808, 37.798, 37.789, 37.776, 37.762, 37.751, 37.741, 37.731, 37.721, 37.711, 37.695, 37.685, 37.673, 37.660, 37.653, 37.643, 37.635, 37.627, 37.620, 37.601, 37.593, 37.578, 37.566, 37.555, 37.537, 37.525, 37.503, 37.482, 37.471, 37.436, 37.429, 37.393, 37.373, 37.360, 37.347, 37.334, 37.322, 37.310, 37.299, 37.289, 37.279, 37.270, 37.261, 37.251, 37.242, 37.233, 37.223, 37.214, 37.206, 37.198, 37.191, 37.183, 37.175, 37.167, 37.160, 37.152, 37.145, 37.137, 37.129, 37.122, 37.114, 37.107, 37.099, 37.091, 37.084, 37.077, 37.069, 37.061, 37.054, 37.047, 37.039, 37.032, 37.024, 37.017, 37.009, 37.002, 36.995, 36.987, 36.980, 36.973, 36.965, 36.957, 36.950, 36.943, 36.936, 36.928, 36.921, 36.914, 36.906, 36.899, 36.891, 36.884, 36.877, 36.869, 36.862, 36.855, 36.847, 36.839, 36.832, 36.825, 36.817, 36.810, 36.803, 36.796, 36.789, 36.782, 36.775, 36.769, 36.762, 36.755, 36.748, 36.741, 36.735, 36.728, 36.720, 36.715, 36.708, 36.701, 36.695, 36.688, 36.682, 36.675, 36.668, 36.663, 36.656, 36.650, 36.643, 36.637, 36.631, 36.624, 36.618, 36.612, 36.606, 36.599, 36.593, 36.587, 36.581, 36.575, 36.569, 36.563, 36.557, 36.550, 36.545, 36.539, 36.533, 36.527, 36.520, 36.515, 36.509, 36.503, 36.497, 36.491, 36.486, 36.480, 36.474, 36.468, 36.463, 36.456, 36.451, 36.445, 36.440, 36.434, 36.429, 36.423, 36.417, 36.412, 36.406, 36.400, 36.395, 36.390, 36.383, 36.378, 36.373, 36.368, 36.362, 36.357, 36.352, 36.346, 36.341, 36.336, 36.330, 36.325, 36.320, 36.314, 36.309, 36.304, 36.299, 36.294, 36.288, 36.283, 36.278, 36.273, 36.268, 36.263, 36.258, 36.253, 36.248, 36.242, 36.238, 36.233, 36.228, 36.223, 36.219, 36.213, 36.208, 36.203, 36.199, 36.194, 36.189, 36.184, 36.180, 36.175, 36.170, 36.165, 36.160, 36.155, 36.151, 36.146, 36.142, 36.136, 36.133, 36.126, 36.122, 36.118, 36.113, 36.109, 36.104, 36.099, 36.095, 36.090, 36.085, 36.080, 36.076, 36.072, 36.067, 36.063, 36.059, 36.054, 36.049, 36.045, 36.039, 36.036, 36.030, 36.027, 36.022, 36.019, 36.013, 36.009, 36.005, 36.000, 35.996, 35.991, 35.987, 35.982, 35.979, 35.973, 35.969, 35.965, 35.960, 35.957, 35.952, 35.948, 35.944, 35.940, 35.936, 35.930, 35.926, 35.922, 35.917, 35.914, 35.909, 35.905, 35.901, 35.897, 35.893, 35.890, 35.884, 35.879, 35.875, 35.870, 35.867, 35.863, 35.859, 35.855, 35.851, 35.846, 35.842, 35.838, 35.834, 35.830, 35.824, 35.822, 35.978, 35.924, 36.029, 35.997, 36.053, 36.025, 36.084, 36.079, 36.087, 36.083, 36.086, 36.083, 36.091, 36.086, 36.094, 36.091, 36.087, 36.084, 36.080, 36.087, 36.079, 36.082, 36.084, 36.076, 36.075, 36.078, 36.076, 36.075, 36.076, 36.067, 36.069, 36.062, 36.062, 36.068, 36.064, 36.057, 36.053, 36.056, 36.052, 36.048, 36.043, 36.045, 36.047, 36.043, 36.039, 36.038, 36.031, 36.032, 36.028, 36.029, 36.023, 36.020, 36.019, 36.022, 36.020, 36.016, 36.015, 36.010, 36.009, 36.007, 36.004, 35.999, 35.997, 35.997, 35.992, 35.989, 35.988, 35.985, 35.985, 35.980, 35.978, 35.975, 35.971, 35.970, 35.965, 35.962, 35.958, 35.957, 35.953, 35.948, 35.947, 35.944, 35.943, 35.942, 35.940, 35.937, 35.933, 35.934, 35.932, 35.930, 35.928, 35.929, 35.923, 35.924, 35.922, 35.921, 35.921, 35.921, 35.395, 35.919, 35.917, 35.916, 35.914, 35.913, 35.912, 35.911, 35.907, 35.907, 35.906, 35.905, 35.906, 35.902, 35.900, 35.898, 35.897, 35.896, 35.893, 35.894, 35.892, 35.892, 35.888, 35.886, 35.887, 35.885, 35.880, 35.880, 35.879, 35.879, 35.878, 35.877, 35.874, 35.873, 35.872, 35.870, 35.871, 35.868, 35.866, 35.866, 35.864, 35.862, 35.860, 35.860, 35.859, 35.858, 35.858, 35.856, 35.857, 35.852, 35.852, 35.852, 35.852, 35.848, 35.850, 35.847, 35.847, 35.846, 35.842, 35.842, 35.839, 35.841, 35.839, 35.840, 35.839, 35.837, 35.836, 35.834, 35.835, 35.831, 35.831, 35.829, 35.830, 35.830, 35.829, 35.825, 35.825, 35.824, 35.822, 35.821, 35.821, 35.822, 35.821, 35.819, 35.817, 35.816, 35.815, 35.814, 35.813, 35.813, 35.810, 35.811, 35.808, 35.808, 35.805, 35.807, 35.806, 35.806, 35.803, 35.803, 35.800, 35.802, 35.799, 35.798, 35.798, 35.798, 35.792, 35.791, 35.791, 35.791, 35.792, 35.790, 35.790, 35.786, 35.788, 35.787, 35.789, 35.788, 35.786, 35.781, 35.781, 35.777, 35.781, 35.781, 35.777, 35.777, 35.775, 35.777, 35.776, 35.774, 35.775, 35.772, 35.770, 35.769, 35.772, 35.769, 35.769, 35.768, 35.764, 35.763, 35.766, 35.763, 35.766, 35.759, 35.766, 35.758, 35.762, 35.755, 35.755, 35.757, 35.760, 35.753, 35.753, 35.753, 35.753, 35.752, 35.752, 35.752, 35.752, 35.748, 35.743, 35.742, 35.742, 35.751, 35.747, 35.747, 35.747, 35.744, 35.747, 35.739, 35.739, 35.738, 35.738, 35.736, 35.740, 35.735, 35.739, 35.739, 35.740, 35.730, 35.731, 35.731, 35.727, 35.727, 35.727, 35.725, 35.725, 35.725, 35.723, 35.724, 35.723, 35.723, 35.723, 35.721, 35.719, 35.719, 35.722, 35.721, 35.717, 35.717, 35.719, 35.717, 35.719, 35.717, 35.717, 35.714, 35.717, 35.712, 35.717, 35.716, 35.705, 35.705, 35.705, 35.703, 35.710, 35.705, 35.705, 35.706, 35.712, 35.700, 35.706, 35.697, 35.697, 35.706, 35.697, 35.697, 35.703, 35.694, 35.701, 35.700, 35.696, 35.696, 35.693, 35.693, 35.693, 35.692, 35.693, 35.692, 35.692, 35.692, 35.692, 35.684, 35.692, 35.689, 35.688, 35.683, 35.683, 35.688, 35.685, 35.677, 34.086, 35.682, 35.683, 35.682, 35.679, 35.682, 35.682, 35.679, 35.671, 35.671, 35.674, 35.670, 35.668, 35.675, 35.667, 35.678, 35.679, 35.666, 35.670, 35.671, 35.663, 35.665, 35.666, 35.666, 35.667, 35.663, 35.666, 35.662, 35.667, 35.660, 35.669, 35.658, 35.659, 35.668, 35.664, 35.667, 35.668, 35.668, 35.665, 35.656, 35.656, 35.651, 35.665, 35.667, 35.655, 35.666, 35.658, 35.664, 35.664, 35.664, 35.650, 35.651, 35.644, 35.651, 35.647, 35.647, 35.647, 35.657, 35.644, 35.647, 35.657, 35.658, 35.647, 35.647, 35.642, 35.642, 35.657, 35.645, 35.652, 35.652, 35.653, 35.653, 35.648, 35.646, 35.642, 35.640, 35.643, 35.649, 35.649, 35.649, 35.650, 35.650, 35.634, 35.650, 35.650, 35.639, 35.651, 35.631, 35.638, 35.645, 35.645, 35.632, 35.644, 35.631, 35.643, 35.631, 35.634, 35.634, 35.633, 35.639, 35.644, 35.634, 35.626, 35.636, 35.644, 35.644, 35.635, 35.635, 35.635, 35.627, 35.628, 35.628, 35.614, 35.633, 35.610, 35.607, 35.623, 35.606, 35.606, 35.606, 35.609, 35.606, 35.606, 35.596, 35.596, 35.596, 35.596, 35.595, 35.597, 35.595, 35.594, 35.577, 35.589, 35.577, 35.577, 35.576, 35.576, 35.587, 35.575, 35.586, 35.573, 35.573, 35.573, 35.572, 35.570, 35.567, 35.571, 35.570 };
/* Cumulative mass lost, expressed as log of the mass in Msun per 10^6
Msun of stars */
const double mass_return_SB99[1000] =
{ 1.743, 2.225, 2.451, 2.600, 2.713, 2.803, 2.879, 2.944, 3.001, 3.053, 3.099, 3.142, 3.181, 3.218, 3.252, 3.284, 3.314, 3.343, 3.370, 3.396, 3.421, 3.445, 3.468, 3.491, 3.512, 3.533, 3.553, 3.572, 3.591, 3.610, 3.628, 3.645, 3.662, 3.679, 3.695, 3.711, 3.727, 3.742, 3.756, 3.771, 3.785, 3.799, 3.812, 3.825, 3.837, 3.849, 3.860, 3.872, 3.885, 3.898, 3.913, 3.928, 3.946, 3.965, 3.985, 4.004, 4.024, 4.053, 4.088, 4.123, 4.159, 4.196, 4.230, 4.261, 4.296, 4.333, 4.366, 4.396, 4.425, 4.450, 4.472, 4.491, 4.508, 4.523, 4.537, 4.551, 4.563, 4.575, 4.586, 4.596, 4.606, 4.616, 4.626, 4.635, 4.645, 4.654, 4.663, 4.672, 4.682, 4.691, 4.700, 4.709, 4.718, 4.726, 4.734, 4.742, 4.749, 4.756, 4.763, 4.770, 4.777, 4.783, 4.789, 4.795, 4.800, 4.806, 4.812, 4.817, 4.822, 4.828, 4.833, 4.837, 4.842, 4.846, 4.850, 4.854, 4.858, 4.862, 4.866, 4.870, 4.873, 4.877, 4.880, 4.884, 4.887, 4.891, 4.894, 4.897, 4.900, 4.904, 4.907, 4.910, 4.913, 4.917, 4.920, 4.923, 4.926, 4.929, 4.932, 4.935, 4.938, 4.941, 4.943, 4.946, 4.949, 4.951, 4.954, 4.956, 4.959, 4.961, 4.964, 4.966, 4.968, 4.971, 4.973, 4.975, 4.978, 4.980, 4.982, 4.984, 4.986, 4.988, 4.990, 4.992, 4.995, 4.996, 4.998, 5.000, 5.002, 5.004, 5.006, 5.008, 5.010, 5.011, 5.013, 5.014, 5.016, 5.017, 5.019, 5.020, 5.022, 5.023, 5.025, 5.026, 5.027, 5.028, 5.030, 5.031, 5.032, 5.033, 5.035, 5.036, 5.037, 5.038, 5.039, 5.040, 5.041, 5.043, 5.044, 5.045, 5.046, 5.047, 5.048, 5.049, 5.050, 5.051, 5.052, 5.053, 5.054, 5.055, 5.056, 5.057, 5.058, 5.059, 5.060, 5.061, 5.062, 5.062, 5.063, 5.064, 5.065, 5.066, 5.067, 5.068, 5.069, 5.070, 5.071, 5.072, 5.072, 5.073, 5.074, 5.075, 5.076, 5.077, 5.078, 5.079, 5.079, 5.080, 5.081, 5.082, 5.083, 5.084, 5.085, 5.085, 5.086, 5.087, 5.088, 5.089, 5.090, 5.090, 5.091, 5.092, 5.093, 5.094, 5.094, 5.095, 5.096, 5.097, 5.098, 5.098, 5.099, 5.100, 5.101, 5.101, 5.102, 5.103, 5.104, 5.104, 5.105, 5.106, 5.107, 5.107, 5.108, 5.109, 5.109, 5.110, 5.111, 5.111, 5.112, 5.113, 5.114, 5.114, 5.115, 5.116, 5.116, 5.117, 5.117, 5.118, 5.119, 5.119, 5.120, 5.121, 5.121, 5.122, 5.122, 5.123, 5.124, 5.124, 5.125, 5.125, 5.126, 5.127, 5.127, 5.128, 5.128, 5.129, 5.130, 5.130, 5.131, 5.131, 5.132, 5.132, 5.133, 5.133, 5.134, 5.135, 5.135, 5.136, 5.136, 5.137, 5.137, 5.138, 5.138, 5.139, 5.139, 5.140, 5.140, 5.141, 5.141, 5.142, 5.142, 5.143, 5.143, 5.144, 5.144, 5.145, 5.145, 5.146, 5.146, 5.147, 5.147, 5.148, 5.148, 5.149, 5.149, 5.150, 5.150, 5.151, 5.151, 5.152, 5.152, 5.152, 5.153, 5.153, 5.154, 5.154, 5.155, 5.155, 5.156, 5.156, 5.156, 5.157, 5.157, 5.158, 5.158, 5.159, 5.159, 5.160, 5.160, 5.160, 5.161, 5.161, 5.162, 5.162, 5.162, 5.163, 5.163, 5.164, 5.164, 5.164, 5.165, 5.165, 5.166, 5.166, 5.166, 5.167, 5.167, 5.168, 5.168, 5.168, 5.169, 5.169, 5.170, 5.170, 5.170, 5.171, 5.171, 5.171, 5.172, 5.172, 5.172, 5.173, 5.173, 5.174, 5.174, 5.174, 5.175, 5.175, 5.175, 5.176, 5.176, 5.176, 5.177, 5.177, 5.177, 5.178, 5.178, 5.179, 5.179, 5.179, 5.180, 5.180, 5.180, 5.181, 5.181, 5.181, 5.182, 5.182, 5.182, 5.183, 5.183, 5.183, 5.184, 5.184, 5.184, 5.184, 5.185, 5.185, 5.185, 5.186, 5.186, 5.186, 5.187, 5.187, 5.187, 5.188, 5.188, 5.188, 5.189, 5.189, 5.189, 5.189, 5.190, 5.190, 5.190, 5.191, 5.191, 5.191, 5.192, 5.192, 5.192, 5.192, 5.193, 5.193, 5.193, 5.194, 5.194, 5.194, 5.194, 5.195, 5.195, 5.195, 5.196, 5.196, 5.196, 5.196, 5.197, 5.197, 5.197, 5.198, 5.198, 5.198, 5.198, 5.199, 5.199, 5.199, 5.199, 5.200, 5.200, 5.200, 5.201, 5.201, 5.201, 5.201, 5.202, 5.202, 5.202, 5.202, 5.203, 5.203, 5.203, 5.203, 5.204, 5.204, 5.204, 5.204, 5.205, 5.205, 5.205, 5.205, 5.206, 5.206, 5.206, 5.206, 5.207, 5.207, 5.207, 5.207, 5.208, 5.208, 5.208, 5.208, 5.209, 5.209, 5.209, 5.209, 5.210, 5.210, 5.210, 5.210, 5.211, 5.211, 5.211, 5.211, 5.212, 5.212, 5.212, 5.212, 5.213, 5.213, 5.213, 5.213, 5.213, 5.214, 5.214, 5.214, 5.214, 5.215, 5.215, 5.215, 5.215, 5.215, 5.216, 5.216, 5.216, 5.216, 5.217, 5.217, 5.217, 5.217, 5.217, 5.218, 5.218, 5.218, 5.218, 5.219, 5.219, 5.219, 5.219, 5.219, 5.220, 5.220, 5.220, 5.220, 5.220, 5.221, 5.221, 5.221, 5.221, 5.222, 5.222, 5.222, 5.222, 5.222, 5.223, 5.223, 5.223, 5.223, 5.223, 5.224, 5.224, 5.224, 5.224, 5.224, 5.225, 5.225, 5.225, 5.225, 5.225, 5.226, 5.226, 5.226, 5.226, 5.226, 5.227, 5.227, 5.227, 5.227, 5.227, 5.228, 5.228, 5.228, 5.228, 5.228, 5.229, 5.229, 5.229, 5.229, 5.229, 5.230, 5.230, 5.230, 5.230, 5.230, 5.231, 5.231, 5.231, 5.231, 5.231, 5.232, 5.232, 5.232, 5.232, 5.232, 5.233, 5.233, 5.233, 5.233, 5.233, 5.234, 5.234, 5.234, 5.234, 5.234, 5.234, 5.235, 5.235, 5.235, 5.235, 5.235, 5.236, 5.236, 5.236, 5.236, 5.236, 5.237, 5.237, 5.237, 5.237, 5.237, 5.237, 5.238, 5.238, 5.238, 5.238, 5.238, 5.239, 5.239, 5.239, 5.239, 5.239, 5.239, 5.240, 5.240, 5.240, 5.240, 5.240, 5.241, 5.241, 5.241, 5.241, 5.241, 5.241, 5.242, 5.242, 5.242, 5.242, 5.242, 5.242, 5.243, 5.243, 5.243, 5.243, 5.243, 5.243, 5.244, 5.244, 5.244, 5.244, 5.244, 5.245, 5.245, 5.245, 5.245, 5.245, 5.245, 5.246, 5.246, 5.246, 5.246, 5.246, 5.246, 5.247, 5.247, 5.247, 5.247, 5.247, 5.247, 5.248, 5.248, 5.248, 5.248, 5.248, 5.248, 5.248, 5.249, 5.249, 5.249, 5.249, 5.249, 5.249, 5.250, 5.250, 5.250, 5.250, 5.250, 5.250, 5.251, 5.251, 5.251, 5.251, 5.251, 5.251, 5.252, 5.252, 5.252, 5.252, 5.252, 5.252, 5.252, 5.253, 5.253, 5.253, 5.253, 5.253, 5.253, 5.254, 5.254, 5.254, 5.254, 5.254, 5.254, 5.254, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255 };
/* H ionizing luminosity corresponding to constant star formation at 1
Msun/yr, expressed in photons / sec (derived from a slug
calculation at an age of 50 Myr */
const double qH0perSFR = 1.57e53;
/* H ionizing luminosity, expressed as log_10 photons per second per 10^6 Msun worth of stars */
const double qH0_SB99[1000] =
{ 52.615, 52.615, 52.613, 52.613, 52.613, 52.613, 52.613, 52.614, 52.614, 52.615, 52.615, 52.616, 52.615, 52.614, 52.615, 52.614, 52.614, 52.614, 52.613, 52.612, 52.608, 52.600, 52.603, 52.605, 52.608, 52.609, 52.611, 52.612, 52.615, 52.612, 52.610, 52.596, 52.596, 52.600, 52.601, 52.600, 52.600, 52.600, 52.599, 52.591, 52.586, 52.579, 52.565, 52.550, 52.545, 52.537, 52.525, 52.509, 52.492, 52.467, 52.451, 52.433, 52.407, 52.390, 52.363, 52.341, 52.295, 52.270, 52.303, 52.342, 52.366, 52.385, 52.393, 52.403, 52.401, 52.385, 52.363, 52.351, 52.335, 52.317, 52.303, 52.289, 52.270, 52.247, 52.219, 52.199, 52.186, 52.141, 52.104, 52.089, 52.070, 52.047, 52.037, 52.019, 51.997, 51.984, 51.968, 51.943, 51.923, 51.903, 51.890, 51.865, 51.850, 51.815, 51.769, 51.750, 51.744, 51.720, 51.702, 51.676, 51.672, 51.657, 51.602, 51.570, 51.540, 51.524, 51.496, 51.470, 51.446, 51.422, 51.397, 51.376, 51.359, 51.349, 51.323, 51.285, 51.267, 51.245, 51.226, 51.203, 51.177, 51.150, 51.134, 51.118, 51.095, 51.078, 51.052, 51.031, 51.013, 50.990, 50.970, 50.951, 50.932, 50.911, 50.892, 50.874, 50.856, 50.837, 50.820, 50.800, 50.783, 50.767, 50.745, 50.727, 50.708, 50.690, 50.673, 50.655, 50.640, 50.622, 50.600, 50.583, 50.565, 50.556, 50.541, 50.520, 50.505, 50.491, 50.478, 50.457, 50.442, 50.428, 50.412, 50.395, 50.383, 50.366, 50.354, 50.340, 50.323, 50.312, 50.298, 50.282, 50.272, 50.257, 50.248, 50.237, 50.219, 50.208, 50.198, 50.186, 50.172, 50.160, 50.154, 50.140, 50.128, 50.112, 50.102, 50.087, 50.077, 50.063, 50.054, 50.038, 50.031, 50.019, 50.010, 49.999, 49.993, 49.978, 49.972, 49.956, 49.946, 49.938, 49.926, 49.918, 49.908, 49.899, 49.888, 49.875, 49.869, 49.855, 49.847, 49.835, 49.828, 49.816, 49.804, 49.797, 49.785, 49.770, 49.768, 49.755, 49.748, 49.736, 49.727, 49.721, 49.713, 49.701, 49.694, 49.684, 49.677, 49.666, 49.655, 49.649, 49.638, 49.630, 49.624, 49.613, 49.602, 49.596, 49.587, 49.576, 49.567, 49.560, 49.549, 49.541, 49.531, 49.524, 49.515, 49.510, 49.499, 49.490, 49.479, 49.477, 49.464, 49.453, 49.450, 49.443, 49.431, 49.427, 49.419, 49.411, 49.404, 49.402, 49.391, 49.383, 49.373, 49.370, 49.361, 49.353, 49.344, 49.341, 49.330, 49.322, 49.313, 49.310, 49.302, 49.290, 49.283, 49.280, 49.271, 49.259, 49.253, 49.245, 49.240, 49.233, 49.222, 49.220, 49.209, 49.200, 49.197, 49.188, 49.180, 49.177, 49.166, 49.158, 49.153, 49.149, 49.146, 49.138, 49.132, 49.125, 49.120, 49.114, 49.106, 49.100, 49.097, 49.090, 49.082, 49.077, 49.068, 49.063, 49.055, 49.052, 49.044, 49.039, 49.031, 49.025, 49.024, 49.012, 49.006, 49.002, 48.998, 48.988, 48.985, 48.978, 48.972, 48.967, 48.955, 48.950, 48.949, 48.941, 48.936, 48.929, 48.922, 48.916, 48.912, 48.908, 48.902, 48.896, 48.887, 48.882, 48.880, 48.874, 48.869, 48.860, 48.855, 48.849, 48.846, 48.846, 48.837, 48.837, 48.830, 48.823, 48.821, 48.814, 48.811, 48.804, 48.800, 48.795, 48.789, 48.787, 48.783, 48.778, 48.776, 48.762, 48.766, 48.758, 48.752, 48.749, 48.747, 48.736, 48.735, 48.731, 48.726, 48.720, 48.715, 48.714, 48.709, 48.705, 48.697, 48.695, 48.691, 48.682, 48.681, 48.675, 48.670, 48.664, 48.660, 48.655, 48.649, 48.645, 48.643, 48.638, 48.633, 48.629, 48.624, 48.618, 48.613, 48.607, 48.603, 48.603, 48.597, 48.591, 48.587, 48.583, 48.579, 48.576, 48.569, 48.567, 48.564, 48.557, 48.554, 48.549, 48.544, 48.541, 48.539, 48.533, 48.530, 48.526, 48.525, 48.523, 48.519, 48.513, 48.508, 48.504, 48.499, 48.495, 48.495, 48.491, 48.487, 48.482, 48.481, 48.473, 48.472, 48.464, 48.461, 48.465, 48.458, 48.454, 48.452, 48.445, 48.441, 48.437, 48.432, 48.427, 48.426, 48.419, 48.417, 48.419, 48.415, 48.409, 48.403, 48.399, 48.391, 48.389, 48.384, 48.386, 48.382, 48.377, 48.370, 48.367, 48.364, 48.361, 48.357, 48.353, 48.352, 48.342, 48.343, 48.337, 48.333, 48.329, 48.322, 48.323, 48.315, 48.313, 48.309, 48.305, 48.303, 48.298, 48.293, 48.289, 48.284, 48.284, 48.281, 48.280, 48.277, 48.273, 48.267, 48.270, 48.263, 48.260, 48.256, 48.250, 48.246, 48.244, 48.241, 48.239, 48.236, 48.238, 48.231, 48.229, 48.221, 48.219, 48.216, 48.212, 48.210, 48.206, 48.201, 48.197, 48.198, 48.194, 48.188, 48.190, 48.184, 48.178, 48.175, 48.174, 48.170, 48.164, 48.161, 48.155, 48.157, 48.156, 48.148, 48.151, 48.141, 48.136, 48.133, 48.129, 48.126, 48.122, 48.120, 48.113, 48.113, 48.109, 48.106, 48.103, 48.098, 48.095, 48.091, 48.087, 48.084, 48.076, 48.073, 48.071, 48.068, 48.065, 48.060, 48.056, 48.059, 48.050, 48.047, 48.042, 48.039, 48.033, 48.030, 48.024, 48.024, 48.020, 48.017, 48.011, 48.008, 48.005, 48.003, 48.001, 47.999, 47.993, 47.991, 47.988, 47.989, 47.985, 47.981, 47.978, 47.976, 47.972, 47.968, 47.966, 47.960, 47.954, 47.952, 47.949, 47.944, 47.948, 47.941, 47.938, 47.934, 47.932, 47.928, 47.924, 47.917, 47.914, 47.912, 47.912, 47.906, 47.903, 47.902, 47.898, 47.894, 47.891, 47.888, 47.886, 47.884, 47.878, 47.876, 47.869, 47.867, 47.864, 47.861, 47.857, 47.854, 47.853, 47.847, 47.844, 47.845, 47.841, 47.842, 47.831, 47.827, 47.822, 47.819, 47.812, 47.812, 47.809, 47.806, 47.801, 47.799, 47.797, 47.794, 47.788, 47.786, 47.783, 47.778, 47.774, 47.771, 47.768, 47.761, 47.762, 47.759, 47.753, 47.751, 47.751, 47.746, 47.744, 47.740, 47.734, 47.731, 47.729, 47.723, 47.722, 47.715, 47.712, 47.710, 47.704, 47.707, 47.701, 47.703, 47.695, 47.689, 47.685, 47.685, 47.679, 47.678, 47.680, 47.670, 47.671, 47.668, 47.665, 47.663, 47.662, 47.660, 47.656, 47.651, 47.652, 47.650, 47.647, 47.643, 47.637, 47.636, 47.632, 47.634, 47.626, 47.624, 47.619, 47.618, 47.611, 47.614, 47.613, 47.614, 47.600, 47.602, 47.597, 47.594, 47.592, 47.589, 47.586, 47.588, 47.576, 47.577, 47.572, 47.572, 47.568, 47.566, 47.571, 47.557, 47.556, 47.552, 47.551, 47.546, 47.551, 47.544, 47.540, 47.533, 47.527, 47.528, 47.525, 47.523, 47.516, 47.514, 47.508, 47.508, 47.508, 47.503, 47.500, 47.495, 47.499, 47.495, 47.490, 47.494, 47.486, 47.477, 47.474, 47.470, 47.468, 47.465, 47.462, 47.457, 47.452, 47.449, 47.450, 47.444, 47.444, 47.442, 47.437, 47.437, 47.434, 47.428, 47.426, 47.424, 47.415, 47.416, 47.411, 47.408, 47.402, 47.403, 47.399, 47.389, 47.391, 47.388, 47.377, 47.380, 47.380, 47.377, 47.373, 47.370, 47.367, 47.364, 47.361, 47.359, 47.356, 47.351, 47.344, 47.344, 47.340, 47.338, 47.332, 47.333, 47.331, 47.320, 47.320, 47.319, 47.317, 47.308, 47.306, 47.306, 47.302, 47.295, 47.298, 47.294, 47.292, 47.294, 47.292, 47.284, 47.286, 47.283, 47.280, 47.273, 47.275, 47.280, 47.271, 47.272, 47.264, 47.263, 47.265, 47.263, 47.264, 47.258, 47.253, 47.248, 47.250, 47.242, 47.239, 47.237, 47.230, 47.232, 47.229, 47.222, 47.223, 47.218, 47.225, 47.216, 47.213, 47.210, 47.208, 47.205, 47.199, 47.201, 47.195, 47.193, 47.193, 47.198, 47.188, 47.181, 47.181, 47.178, 47.174, 47.171, 47.171, 47.169, 47.166, 47.168, 47.171, 47.169, 47.154, 47.149, 47.146, 47.143, 47.140, 47.133, 47.134, 47.131, 47.136, 47.122, 47.127, 47.125, 47.120, 47.113, 47.111, 47.111, 47.106, 47.103, 47.107, 47.104, 47.100, 47.100, 47.093, 47.090, 47.087, 47.086, 47.090, 47.081, 47.074, 47.072, 47.075, 47.072, 47.078, 47.065, 47.057, 47.067, 47.065, 47.056, 47.049, 47.044, 47.041, 47.039, 47.039, 47.036, 47.034, 47.028, 47.026, 47.025, 47.022, 47.016, 47.016, 47.016, 47.010, 47.009, 47.006, 47.004, 47.002, 46.997, 46.987, 46.982, 46.979, 46.977, 46.977, 46.974, 46.972, 46.974, 46.972, 46.965, 46.963, 46.964, 46.961, 46.960, 46.952, 46.952, 46.945, 46.943, 46.939, 46.938, 46.935, 46.933, 46.934, 46.929, 46.923, 46.922, 46.923, 46.918, 46.916, 46.913, 46.911, 46.911, 46.905, 46.903, 46.898, 46.894, 46.891, 46.888, 46.887, 46.885, 46.883, 46.876, 46.872, 46.872, 46.866, 46.864, 46.862, 46.860, 46.858, 46.854, 46.850, 46.845, 46.843, 46.840, 46.836, 46.829, 46.827, 46.826, 46.829, 46.825, 46.826, 46.824, 46.824, 46.822, 46.819, 46.831, 46.828, 46.814, 46.812, 46.808, 46.807, 46.807, 46.799, 46.800, 46.800, 46.799, 46.800, 46.795, 46.793, 46.787, 46.786, 46.788, 46.786, 46.792, 46.781, 46.777, 46.775, 46.773, 46.770, 46.772, 46.764, 46.758, 46.760, 46.758, 46.756, 46.749, 46.756, 46.750, 46.772, 46.760, 46.745 };
void
userEOS(const double t, const double dt, const grid *grd,
const double *col, const double *pres, const double *eInt,
void *params,
double *gamma, double *delta) {
fprintf(stderr,
"Warning: userEOS function called but not implemented!\n");
return;
}
void
userAlpha(const double t, const double dt, const grid *grd,
const double *col, const double *pres, const double *eInt,
const double *gamma, const double *delta,
void *params,
double *alpha) {
gsl_poly_complex_workspace *wksp;
double coef[6], sol[10];
double omega, kappa, T1, sigma, kcrit, J, Q, d, tfast, tgrowth;
unsigned long i, j;
const int m=2;
gsl_complex nu2, nu;
double alphacoef = ((paramType *) params)->alphacoef;
/* Allocate workspace */
wksp = gsl_poly_complex_workspace_alloc(6);
/* Store the coefficiencts of the dispersion relation polynomial
that don't change */
coef[2] = -8.0;
coef[3] = coef[4] = 0.0;
/* Loop over cells */
for (i=0; i<grd->nr; i++) {
/* Handle negative column densities, which may arise if the time
step overshoots. We just need to make sure the code doesn't
barf here, as the negative column densities will be fixed by
the iterative solver. */
if (col[i] <= 0.0) {
alpha[i] = ALPHAMIN;
continue;
}
/* The various quantities needed for the stability analysis */
sigma = sqrt(pres[i]/col[i]);
omega = grd->vphi_g[i+1]/grd->r_g[i+1];
kappa = sqrt(2.0*(1.0+grd->beta_g[i+1]))*omega;
T1 = -(2.0*m*omega/(kappa*grd->r_g[i+1])) *
(2.0*m*omega/(kappa*grd->r_g[i+1])) * (grd->beta_g[i+1]-1);
kcrit = kappa*kappa / (2.0*M_PI*G*col[i]);
Q = kappa*sigma / (M_PI*G*col[i]);
if (Q < 0)
printf("Q < 0! kappa = %f, sigma = %f, col = %f\n", kappa, sigma, col[i]);
J = sqrt(T1)/kcrit;
/* Coefficients of the disperison relation polynomial */
coef[0] = -Q*Q*Q*Q;
coef[1] = 6.0*Q*Q;
coef[5] = 16.0*J*J;
/* Find roots, giving minima and maxima of D; note that we test
to make sure that the leading coefficient isn't too small,
which makes the problem ill-conditioned as causes the solver
to hang. If we detect this happening, we just drop the leading
coefficient and solve a 4th order polynomial instead of a 5th. */
if (coef[5] > 1e-30) {
gsl_poly_complex_solve(coef, 6, wksp, sol);
} else {
gsl_poly_complex_solve(coef, 5, wksp, sol);
}
/* For each root, compute the growth time of the instability */
tfast = 1.0e30;
for (j=0; j<5; j++) {
/* Skip roots with negative real part, or imaginary part that is
greater than roundoff */
if ((sol[2*j] < 0) || (fabs(sol[2*j+1]) > 1.0e-6)) continue;
/* Compute D */
d = (Q*Q/(4.0*sol[2*j]*sol[2*j]) - 1.0/sol[2*j]) *
(Q*Q/(4.0*sol[2*j]*sol[2*j]) - 1.0/sol[2*j] -
4.0*J*J*sol[2*j]*sol[2*j]);
/* Ignore stable roots */
if (d > 0) continue;
/* Get frequency and growth time */
GSL_SET_COMPLEX(&nu2,
1.0 + 0.5*(Q*Q/(4.0*sol[2*j]*sol[2*j]) - 1.0/sol[2*j]),
0.5 * sqrt(-d));
nu = gsl_complex_sqrt(nu2);
tgrowth = 1.0 / (GSL_IMAG(nu)*kappa) / (2.0*M_PI/omega);
/* Store minimum growth time */
if (tgrowth < tfast) tfast = tgrowth;
}
/* Now check for gravitational instability */
if (Q < 1) {
GSL_SET_COMPLEX(&nu, 0.0, sqrt(1.0/(Q*Q)-1.0));
tgrowth = 1.0 / (GSL_IMAG(nu)*kappa) / (2.0*M_PI/omega);
if (tgrowth < tfast) tfast = tgrowth;
}
/* Compute alpha based on the fastest growing mode timescale */
alpha[i] = alphacoef * exp(-tfast+1.0);
if (alpha[i] > 1.0) alpha[i] = 1.0;
if (alpha[i] < ALPHAMIN) alpha[i] = ALPHAMIN;
}
/* Free workspace */
gsl_poly_complex_workspace_free(wksp);
}
void
userMassSrc(const double t, const double dt, const grid *grd,
const double *col, const double *pres, const double *eInt,
const double *gamma, const double *delta,
void *params,
double *massSrc) {
/* Estimate Mdot, including effects of star formation and mass ejection */
long i;
double *sigma_sfr, *sigma_wind;
double col_floor = ((paramType *) params)->col_floor;
/* Allocate memory to hold results */
sigma_sfr = calloc(grd->nr, sizeof(double));
sigma_wind = calloc(grd->nr, sizeof(double));
/* Get SFR and wind mass flux */
sfrwind(grd, col, pres, params, sigma_sfr, sigma_wind);
/* Compute mass source term */
for (i=0; i<grd->nr; i++) massSrc[i] = -sigma_sfr[i] - sigma_wind[i];
/* Apply absolute floor */
if (col_floor > 0) {
for (i=0; i<grd->nr; i++) {
massSrc[i] += col_floor / (grd->r_g[i+1]/grd->vphi_g[i+1]) *
exp(col_floor/col[i]) / (1.0 + exp(SQR(col[i]/col_floor)));
}
}
/* Free memory */
free(sigma_sfr);
free(sigma_wind);
}
void
userIntEnSrc(const double t, const double dt, const grid *grd,
const double *col, const double *pres, const double *eInt,
const double *gamma, const double *delta,
void *params, double *intEnSrc) {
/* Cooling rate = eta Sigma sigma^2 Omega = eta P vphi/r; heating
rate from star formation = pdot * sigma / area */
long i;
double eta = ((paramType *) params)->eta;
double sigmath = ((paramType *) params)->sigmath;
double shapefac = ((paramType *) params)->shapefac;
double zetad = ((paramType *) params)->zetad;
double sigma_max = ((paramType *) params)->sigma_max;
double col_min = ((paramType *) params)->col_min;
double *pdot = PDOT(params, grd);
double sigma2, sigmaNT, rhostar, a, b, c, h;
for (i=0; i<grd->nr; i++) {
/* Gas velocity dispersion */
sigma2 = pres[i]/col[i];
if (sigma2 > SQR(sigmath)) {
sigmaNT = sqrt(sigma2 - SQR(sigmath));
/* Stellar density */
rhostar = shapefac * SQR(grd->vphi_g[i+1]) *
(1.0+2.0*grd->beta_g[i+1]) /
(4.0*M_PI*G*SQR(grd->r_g[i+1]));
/* Get scale height from OML model */
if (rhostar > 0.0) {
a = 2.0*M_PI*zetad*G*rhostar*col[i];
b = M_PI/2.0*G*SQR(col[i]);
c = -pres[i];
h = (-b + sqrt(b*b-4.0*a*c))/(2.0*a);
} else {
h = pres[i] / (M_PI/2.0*G*SQR(col[i]));
}
/* Cooling rate = eta Sigma sigmaNT^2 / (h/sigmaNT) */
intEnSrc[i] = -eta * col[i] * SQR(sigmaNT) / (h/sigmaNT);
} else {
intEnSrc[i] = 0.0;
}
/* Heating rate = pdot/area * sigma */
intEnSrc[i] += pdot[i] * sqrt(sigma2) * exp(-col_min/col[i]);
/* Extra cooling in hot cells */
intEnSrc[i] -= col[i] * SQR(sigmaNT) /
(grd->r_g[i+1]/grd->vphi_g[i+1]) *
exp(sigmaNT/sigma_max) / (1.0 + exp(SQR(sigma_max/sigmaNT)));
}
}
void
userIBC(const double t, const double dt, const grid *grd,
const double *col, const double *pres, const double *eInt,
const double *gamma, const double *delta,
const pres_bc_type ibc_pres, const enth_bc_type ibc_enth,
void *params,
double *ibc_pres_val, double *ibc_enth_val) {
fprintf(stderr,
"Warning: userIBC function called but not implemented!\n");
return;
}
void
userOBC(const double t, const double dt, const grid *grd,
const double *col, const double *pres, const double *eInt,
const double *gamma, const double *delta,
const pres_bc_type obc_pres, const enth_bc_type obc_enth,
void *params,
double *obc_pres_val, double *obc_enth_val) {
fprintf(stderr,
"Warning: userOBC function called but not implemented!\n");
return;
}
void
userPreTimestep(const double t, const double dt,
const grid *grd, double *col, double *pres,
double *eInt, double *mBnd, double *eBnd,
double *mSrc, double *eSrc,
void *params, const unsigned long nUserOut,
double *userOut) {
/* We do two things before a time step: (1) record the stellar mass
at the start of the time step so we can back out the mass lost
during it; (2) compute and store the current momentum and energy
injection rate from the stellar population */
long i, j;
double p_per_sn = ((paramType *) params)->p_per_sn;
double e_per_sn = ((paramType *) params)->e_per_sn;
double star_rad_var = ((paramType *) params)->star_rad_var;
double *msrc_tmp = MSRC_TMP(params);
double *pdot = PDOT(params, grd);
double *edot = EDOT(params, grd);
double *mdot = MDOT(params, grd);
double *pdot_tmp, *pdot_tmp1, *edot_tmp, *edot_tmp1,
*mdot_tmp, *mdot_tmp1;
double pdot_tot, norm;
double *Sigmastar = SIGMASTAR(params, grd);
/* Record cumulative mass source term up to this point */
for (i=0; i<grd->nr; i++) msrc_tmp[i] = mSrc[i];
/* Compute pdot and edot from star formation */
pdot_tmp = calloc(grd->nr, sizeof(double));
edot_tmp = calloc(grd->nr, sizeof(double));
mdot_tmp = calloc(grd->nr, sizeof(double));
pdot_tmp1 = calloc(grd->nr, sizeof(double));
edot_tmp1 = calloc(grd->nr, sizeof(double));
mdot_tmp1 = calloc(grd->nr, sizeof(double));
for (i=0; i<grd->nr; i++)
injection_rate(Sigmastar+i*nbin_SB99, p_per_sn, e_per_sn,
pdot_tmp+i, edot_tmp+i, mdot_tmp+i);
/* Initialize to 0 */
for (i=0; i<grd->nr; i++) pdot[i] = edot[i] = mdot[i] = 0.0;
/* Loop over cells to do convolution, being careful to ensure that
the area-integrated momentum and energy added stays constant */
for (j=0; j<grd->nr; j++) {
pdot_tot = 0.0;
for (i=0; i<grd->nr; i++) {
pdot_tmp1[i] = exp(-SQR(grd->r_g[i+1]-grd->r_g[j+1]) /
(2.0*SQR(star_rad_var*grd->r_g[j+1])))
* pdot_tmp[j];
pdot_tot += pdot_tmp1[i] * grd->area[i];
edot_tmp1[i] = exp(-SQR(grd->r_g[i+1]-grd->r_g[j+1]) /
(2.0*SQR(star_rad_var*grd->r_g[j+1])))
* edot_tmp[j];
mdot_tmp1[i] = exp(-SQR(grd->r_g[i+1]-grd->r_g[j+1]) /
(2.0*SQR(star_rad_var*grd->r_g[j+1])))
* mdot_tmp[j];
}
norm = pdot_tmp[j]*grd->area[j] / (pdot_tot + SMALL);
for (i=0; i<grd->nr; i++) {
pdot[i] += norm * pdot_tmp1[i];
edot[i] += norm * edot_tmp1[i];
mdot[i] += norm * mdot_tmp1[i];
}
}
/* Free memory */
free(pdot_tmp);
free(pdot_tmp1);
free(edot_tmp);
free(edot_tmp1);
free(mdot_tmp);
free(mdot_tmp1);
}
void
userPostTimestep(const double t, const double dt,
const grid *grd, double *col, double *pres,
double *eInt, double *mBnd, double *eBnd,
double *mSrc, double *eSrc,
void *params, const unsigned long nUserOut,
double *userOut) {
long i, j;
long *tctr = &(((paramType *) params)->tctr);
double *msrc_tmp = MSRC_TMP(params);
double *Sigmastar = SIGMASTAR(params, grd);
double *pdot = PDOT(params, grd);
double *edot = EDOT(params, grd);
double *mdot = MDOT(params, grd);
double *Sigmastar_tot = userOut;
double *Sigmawind_tot = userOut + grd->nr;
double *pdot_save = userOut + 2*grd->nr;
double *edot_save = userOut + 3*grd->nr;
double *sigma_sfr = userOut + 4*grd->nr;
double *sigma_wind = userOut + 5*grd->nr;
double *sigma_sfr_obs = userOut + 6*grd->nr;
double *mdot_save = userOut + 7*grd->nr;
double d2qdtdA;
/* Safety check */
assert(nUserOut == 8);
/* Shift bins of star formation history if needed */
while (t/(dt_SB99*MYR) >= *tctr+1) {
for (i=0; i<grd->nr; i++) {
for (j=nbin_SB99-1; j>0; j--) {
Sigmastar[j+i*nbin_SB99] = Sigmastar[j-1+i*nbin_SB99];
}
Sigmastar[i*nbin_SB99] = 0.0;
}
(*tctr)++;
}
/* Figure out the current SFR and mass loss rate; we will use these
to partition the change in mass between new stars and wind */
sfrwind(grd, col, pres, params, sigma_sfr, sigma_wind);
/* Record stars formed during this timestep in the youngest bin;
also add to source terms we're tracking */
for (i=0; i<grd->nr; i++) {
Sigmastar[i*nbin_SB99] += (-mSrc[i] + msrc_tmp[i]) *
sigma_sfr[i] / (sigma_sfr[i] + sigma_wind[i] + SMALL);
}
/* Save cumulative surface densities of stars formed and wind mass
lost, and instantaneous momentum injection rate */
for (i=0; i<grd->nr; i++) {
Sigmastar_tot[i] += (-mSrc[i] + msrc_tmp[i]) *
sigma_sfr[i] / (sigma_sfr[i] + sigma_wind[i] + SMALL);
Sigmawind_tot[i] += (-mSrc[i] + msrc_tmp[i]) *
sigma_wind[i] / (sigma_sfr[i] + sigma_wind[i] + SMALL);
pdot_save[i] = pdot[i];
edot_save[i] = edot[i];
mdot_save[i] = mdot[i];
}
/* Save "observed" SFR at this time, i.e., SFR that would be
inferred from Halpha or similar ionization-based tracer */
for (i=0; i<grd->nr; i++) {
d2qdtdA = 0.0;
for (j=0; j<nbin_SB99; j++)
d2qdtdA += pow(10.0, qH0_SB99[j]) *
(Sigmastar[i*nbin_SB99+j] / (1.0e6*MSUN));
sigma_sfr_obs[i] = d2qdtdA / (qH0perSFR/(MSUN/YR));
}
}
/* This is an auxiliary routine to compute the momentum and energy
input per unit area from a stellar population */
void injection_rate(double *Sigmastar, double p_per_sn,
double e_per_sn, double *pdot_tot,
double *edot_tot, double *mdot_tot) {
long i;
double snr = 0.0;
double pdot_sn = 0.0, pdot_wind = 0.0, pdot_rad = 0.0;
double edot_sn = 0.0, edot_wind = 0.0;
/* Figure out the total SN rate and momentum injection */
for (i=0; i<nbin_SB99; i++) {
if ((snr_SB99[i] > -29.0) && (Sigmastar[i] > 0.0)) {
snr += pow(10.0, snr_SB99[i]) * Sigmastar[i]/(1.0e6*MSUN)/YR;
}
}
pdot_sn = snr*p_per_sn;
edot_sn = snr*e_per_sn;
/* Get wind momentum and energy input rate */
for (i=0; i<nbin_SB99; i++) {
pdot_wind += pow(10.0, pdot_wind_SB99[i]) *
(Sigmastar[i] / (1.0e6*MSUN));
edot_wind += pow(10.0, edot_wind_SB99[i]) *
(Sigmastar[i] / (1.0e6*MSUN));
}
/* Get radiation momentum flux */
for (i=0; i<nbin_SB99; i++)
pdot_rad += pow(10.0, lum_SB99[i]) * (Sigmastar[i] / (1.0e6*MSUN)) / C;
/* Set momentum and energy total values */
*pdot_tot = pdot_rad + pdot_sn + pdot_wind;
*edot_tot = edot_sn + edot_wind;
/* Get mass injection rate */
*mdot_tot = pow(10.0, mass_return_SB99[0]) / (dt_SB99*MYR) *
(Sigmastar[0] / 1.0e6);
for (i=1; i<nbin_SB99; i++)
*mdot_tot += (pow(10.0, mass_return_SB99[i]) -
pow(10.0, mass_return_SB99[i-1])) / (dt_SB99*MYR) *
(Sigmastar[i] / 1.0e6);
}
/* This routine takes the current state of the simulation as input and
computes the star formation rate and wind mass loss rate in every cell */
void sfrwind(const grid *grd, const double *col, const double *pres,
void *params, double *sigma_SFR, double *sigma_wind) {
long i;
double shapefac = ((paramType *) params)->shapefac;
double zetad = ((paramType *) params)->zetad;
double epsff0 = ((paramType *) params)->epsff0;
double sigmath = ((paramType *) params)->sigmath;
double col_min = ((paramType *) params)->col_min;
double en_wind = ((paramType *) params)->en_wind;
double *pdot = PDOT(params, grd);
double *edot = EDOT(params, grd);
double *mdot = MDOT(params, grd);
double rhostar, a, b, c, h;
double rhog, tff, alphavir, epsff;
double pdotEdd, xcrit, sigma2, mach2, r, sigma_surf2, zeta, vwind;
/* Loop over cells */
for (i=0; i<grd->nr; i++) {
/* Stellar density */
rhostar = shapefac * SQR(grd->vphi_g[i+1]) *
(1.0+2.0*grd->beta_g[i+1]) /
(4.0*M_PI*G*SQR(grd->r_g[i+1]));
/* Get scale height from OML model */
if (rhostar > 0.0) {
a = 2.0*M_PI*zetad*G*rhostar*col[i];
b = M_PI/2.0*G*SQR(col[i]);
c = -pres[i];
h = (-b + sqrt(b*b-4.0*a*c))/(2.0*a);
} else {
h = pres[i] / (M_PI/2.0*G*SQR(col[i]));
}
/* Gas density and free-fall time */
rhog = col[i]/(2*h);
tff = sqrt(3*M_PI/(32*G*rhog));
/* Virial ratio */
alphavir = pres[i]/(M_PI/2.0*G*col[i]*col[i]*h);
/*alphavir = tff/(h/sqrt(pres[i]/col[i]));*/
/* epsff */
epsff = exp(alphavir*log(epsff0));
/*epsff = exp(sqrt(alphavir)*log(epsff0));*/
/* SFR */
sigma_SFR[i] = epsff * col[i] / tff;
/* Compute wind using either momentum or energy prescription */
if (en_wind <= 0.0) {
/* Momentum case */
/* Eddington momentum injection rate */
/*pdotEdd = 2.0*M_PI*G*col[i]*(col[i]+rhostar*h);*/
pdotEdd = 2.0*M_PI*G*col[i]*(col[i]+rhostar*grd->r_g[i+1]/shapefac);
/* xcrit */
xcrit = log(pdot[i]/pdotEdd);
/* Dispersion of surface densities */
sigma2 = pres[i]/col[i];
mach2 = sigma2 / SQR(sigmath);
r = 0.5 * (3.0-2.5)/(2.0-2.5) * (1.0-pow(mach2, 2.0-2.5)) /
(1.0-pow(mach2, 3.0-2.5));
sigma_surf2 = log(1.0 + r*mach2/4.0);
/* zeta */
zeta = 0.5*(1.0-erf((-2.0*xcrit+sigma_surf2) / sqrt(8.0*sigma_surf2)));
/* Wind mass flux per unit area, which we take to be zeta *
Sigma_gas / t_dyn, where t_dyn = h / sigma */
sigma_wind[i] = zeta * col[i] * sqrt(sigma2)/h * exp(-col_min/col[i]);
} else {
/* Energy case */
/* Thermal velocity of hot gas, assuming complete thermalization */
vwind = sqrt(2.0*edot[i]/(mdot[i]+SMALL));
/* Wind mass launch rate, using Martin 2005 entrainment model */
sigma_wind[i] = sqrt(3.0*mdot[i]*rhog*vwind);
/*if ((i==285) && (sigma_wind[i] > 1e-16))
printf("sigma_sfr = %e, sigma_wind = %e\n", sigma_wind[i], sigma_SFR[i]);*/
}
}
}
void
userCheckRead(
FILE *fp, grid *grd, const unsigned long nOut,
double *tOut, double *colOut,
double *presOut, double *eIntOut, double *mBndOut,
double *eBndOut, double *mSrcOut, double *eSrcOut,
const unsigned long nUserOut, double *userOut,
void *params
) {
long *tctr = &(((paramType *) params)->tctr);
double *Sigmastar = SIGMASTAR(params, grd);
/* Read counter and the age-dependent stellar surface densities */
fread(tctr, sizeof(long), 1, fp);
fread(Sigmastar, nbin_SB99*grd->nr, sizeof(double), fp);
}
void
userCheckWrite(
FILE *fp,
const grid *grd, const unsigned long nOut,
const double *tOut, const double *colOut,
const double *presOut, const double *eIntOut,
const double *mBndOut, const double *eBndOut,
const double *mSrcOut, const double *eSrcOut,
const unsigned long nUserOut, const double *userOut,
const void *params
) {
long *tctr = &(((paramType *) params)->tctr);
double *Sigmastar = SIGMASTAR(params, grd);
/* Write the counter and the age-dependent stellar surface densities */
fwrite(tctr, sizeof(long), 1, fp);
fwrite(Sigmastar, nbin_SB99*grd->nr, sizeof(double), fp);
}
| {
"alphanum_fraction": 0.5923157466,
"avg_line_length": 107.6118935837,
"ext": "c",
"hexsha": "41f43d72dec906e21d51bf4e0a63fd8c4c971bd6",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2021-11-20T02:11:17.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-11-19T04:41:37.000Z",
"max_forks_repo_head_hexsha": "646b3136c39da7152c82a032f8151555ec1e3d44",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "franciscaconcha/amuse-vader",
"max_forks_repo_path": "src/amuse/community/vader/src/prob/userFunc_cmzdisk2.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "646b3136c39da7152c82a032f8151555ec1e3d44",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "franciscaconcha/amuse-vader",
"max_issues_repo_path": "src/amuse/community/vader/src/prob/userFunc_cmzdisk2.c",
"max_line_length": 8006,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "646b3136c39da7152c82a032f8151555ec1e3d44",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "franciscaconcha/amuse-vader",
"max_stars_repo_path": "src/amuse/community/vader/src/prob/userFunc_cmzdisk2.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 37948,
"size": 68764
} |
#ifndef QDM_THETA_H
#define QDM_THETA_H 1
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_vector.h>
int
qdm_theta_optimize(
gsl_vector *result,
gsl_vector *emperical_quantiles,
gsl_matrix *ix
);
void
qdm_theta_matrix_constrain(
gsl_matrix *theta,
double min
);
#endif /* QDM_THETA_H */
| {
"alphanum_fraction": 0.7305194805,
"avg_line_length": 14.6666666667,
"ext": "h",
"hexsha": "6c23626d3c35daa28ee23cbf5d6694894fea18cf",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "2ee95bec6c8be64f69e231c78f2be5fce3509c67",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "calebcase/qdm",
"max_forks_repo_path": "include/qdm/theta.h",
"max_issues_count": 3,
"max_issues_repo_head_hexsha": "2ee95bec6c8be64f69e231c78f2be5fce3509c67",
"max_issues_repo_issues_event_max_datetime": "2020-03-22T20:22:53.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-03-06T18:09:06.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "calebcase/qdm",
"max_issues_repo_path": "include/qdm/theta.h",
"max_line_length": 36,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "2ee95bec6c8be64f69e231c78f2be5fce3509c67",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "calebcase/qdm",
"max_stars_repo_path": "include/qdm/theta.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 93,
"size": 308
} |
/***********************************************************************
* mexeigPartial.c : C mex file for the routine DSYEVX in LAPACK
*
* mex -O -largeArrayDims -lmwlapack -lmwblas mexeigPartial.c
*
* [V,D,nv] = mexeigPartial(A, vl, vu, options);
*
* options.jobz = 1 (default), compute both eigenvectors and eigenvalues;
* = 2, compute only eigenvalues.
* options.range = 1 (default), compute all;
* = 2, compute eigenvalues between [vl, vu].
* = 3, compute vl-th to vu-th eigenvalues.
* options.abstol = tolerance (default = 1e-8)
***********************************************************************/
#include <math.h>
#include <mex.h>
#include <matrix.h>
#include <blas.h>
#include <lapack.h>
#include <string.h> /* needed for memcpy() */
#if !defined(_WIN32)
#define dsyevd dsyevd_
#define dsyevx dsyevx_
#define dgesdd dgesdd_
#endif
/**********************************************************
*
***********************************************************/
void mexFunction(
int nlhs, mxArray *plhs[],
int nrhs, const mxArray *prhs[] )
{ double *A, *AA, *nV, *V, *D, VL, VU, abstol, *work, *work2, *tmp;
ptrdiff_t m, n, IL, IU, lwork, *iwork, *ifail, info, options;
char *jobz="V";
char *uplo="U";
char *range="A";
/* CHECK FOR PROPER NUMBER OF ARGUMENTS */
if (nrhs > 4){
mexErrMsgTxt("mexeigPartial: requires at most 4 input arguments."); }
if (nlhs > 3){
mexErrMsgTxt("mexeigPartial: requires at most 3 output argument."); }
/* CHECK THE DIMENSIONS */
m = mxGetM(prhs[0]);
n = mxGetN(prhs[0]);
if (m != n) {
mexErrMsgTxt("mexeigPartial: matrix must be square."); }
if (mxIsSparse(prhs[0])) {
mexErrMsgTxt("mexeigPartial: sparse matrix not allowed."); }
A = mxGetPr(prhs[0]);
options = 1;
abstol = 1e-8;
/*Get fields from options */
tmp = mxGetPr(mxGetField(prhs[3], 0, "abstol")); abstol = *tmp;
tmp = mxGetPr(mxGetField(prhs[3], 0, "jobz")); options = (ptrdiff_t)*tmp;
tmp = mxGetPr(mxGetField(prhs[3], 0, "range")); options = (ptrdiff_t)*tmp;
if (options==1) {
range="A"; }
else if (options==2) {
range="V"; VL = *mxGetPr(prhs[1]); VU = *mxGetPr(prhs[2]); }
else if (options == 3) {
range="I";
IL = (ptrdiff_t)*mxGetPr(prhs[1]);
IU = (ptrdiff_t)*mxGetPr(prhs[2]);
}
/***** create return argument *****/
plhs[0] = mxCreateDoubleMatrix(n,n,mxREAL);
V = mxGetPr(plhs[0]);
plhs[1] = mxCreateDoubleMatrix(n,1,mxREAL);
D = mxGetPr(plhs[1]);
plhs[2] = mxCreateDoubleMatrix(1,1,mxREAL);
nV = mxGetPr(plhs[2]);
/***** Do the computations in a subroutine *****/
lwork = 8*n;
work = mxCalloc(lwork,sizeof(double));
iwork = mxCalloc(5*n, sizeof(ptrdiff_t));
ifail = mxCalloc(n, sizeof(ptrdiff_t));
AA = mxCalloc(n*n,sizeof(double));
memcpy(AA,mxGetPr(prhs[0]),(n*n)*sizeof(double));
dsyevx(jobz, range, uplo, &n, AA, &n, &VL, &VU, &IL, &IU,
&abstol, &m, D, V, &n, work, &lwork, iwork, ifail, &info);
*nV = m;
return;
}
/**********************************************************/
| {
"alphanum_fraction": 0.5155015198,
"avg_line_length": 33.2323232323,
"ext": "c",
"hexsha": "2660b3e24e3a6da451f961b44344bcdb0d4c08c0",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2020-02-06T15:17:55.000Z",
"max_forks_repo_forks_event_min_datetime": "2020-02-06T15:17:55.000Z",
"max_forks_repo_head_hexsha": "7ba674da284ae7727b3385ef0f2036509da0c98d",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "napinoco/BBCPOP",
"max_forks_repo_path": "solver/BP/mexfun_TohK/mexeigPartialK.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "7ba674da284ae7727b3385ef0f2036509da0c98d",
"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": "napinoco/BBCPOP",
"max_issues_repo_path": "solver/BP/mexfun_TohK/mexeigPartialK.c",
"max_line_length": 80,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "7ba674da284ae7727b3385ef0f2036509da0c98d",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "napinoco/BBCPOP",
"max_stars_repo_path": "solver/BP/mexfun_TohK/mexeigPartialK.c",
"max_stars_repo_stars_event_max_datetime": "2020-02-06T15:17:56.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-02-06T15:17:56.000Z",
"num_tokens": 1039,
"size": 3290
} |
/**
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <gsl/gsl_interp.h>
#include <gsl/gsl_multifit_nlin.h>
#include "aXe_grism.h"
#include "aXe_utils.h"
//#include "spce_PET.h"
#include "inout_aper.h"
//#include "trace_conf.h"
#include "aper_conf.h"
//#include "spc_sex.h"
//#include "disp_conf.h"
//#include "spc_wl_calib.h"
//#include "spce_binning.h"
#include "spc_spc.h"
//#include "spce_output.h"
//#include "spc_FITScards.h"
#include "fringe_conf.h"
#include "trfit_utils.h"
#include "ipixcorr_utils.h"
#define AXE_IMAGE_PATH "AXE_IMAGE_PATH"
#define AXE_OUTPUT_PATH "AXE_OUTPUT_PATH"
#define AXE_CONFIG_PATH "AXE_CONFIG_PATH"
int
main (int argc, char *argv[])
{
char *opt;
char ipc_aper_file[MAXCHAR];
char ipc_aper_file_path[MAXCHAR];
char aper_file[MAXCHAR];
char aper_file_path[MAXCHAR];
char conf_file[MAXCHAR];
char conf_file_path[MAXCHAR];
char grism_file[MAXCHAR];
char grism_file_path[MAXCHAR];
char bck_image[MAXCHAR];
char bck_image_path[MAXCHAR];
char IPC_file[MAXCHAR];
char IPC_file_path[MAXCHAR];
char ipc_file[MAXCHAR];
char ipc_file_path[MAXCHAR];
char SPC_file[MAXCHAR];
char SPC_file_path[MAXCHAR];
char IPC_func[MAXCHAR];
char IPC_func_path[MAXCHAR];
aperture_conf *conf;
object **oblist;
observation *obs=NULL, *bck;
//Initialize obs struct memebers
obs->grism = NULL;
obs->pixerrs = NULL;
obs->dq = NULL;
interpolator *ipcorr;
interpolator *nlincorr;
int index;
//int i;
full_spectr *SPC;
fitsfile *SPC_ptr;
fitsfile *IPC_ptr;
FITScards *cards;
int f_status=0;
int aperID=0, beamID=0;
//objindex;
int spec_OAF=0;
int point_like=0;
beam act_beam;
beam *beam_ptr;
double max_ext=0.0;
//double adcgain;
double exptime=NAN;
gsl_matrix *data_matrix;
int ipixc=0;
int nlinc=0;
int icorr=0;
int num=0;
if ((argc < 3) || (opt = get_online_option ("help", argc, argv)))
{
fprintf (stdout,
"aXe_FRINGECORR Version %s:\n",RELEASE);
exit (1);
}
fprintf (stdout, "aXe_INTPIXCORR: Starting...\n");
// reset the parameter index
index = 0;
// read in the grism image name
strcpy(grism_file, argv[++index]);
build_path (AXE_IMAGE_PATH, grism_file, grism_file_path);
// read in the configuration file name
strcpy(conf_file, argv[++index]);
build_path (AXE_CONFIG_PATH, conf_file, conf_file_path);
// load the configuration file
conf = get_aperture_descriptor(conf_file_path);
// determine the science extension number
get_extension_numbers(grism_file_path, conf,conf->optkey1,conf->optval1);
// get or set up the input OAF name
if ((opt = get_online_option("in_OAF", argc, argv)))
{
// copy the parameter value if given
strcpy(aper_file, opt);
// mark that there is a special OAF file
spec_OAF=1;
}
else
{
// copy the grism name and construct the name
// if not given as parameter
strcpy(aper_file, grism_file);
replace_file_extension (grism_file, aper_file, ".fits",
".OAF", conf->science_numext);
}
build_path(AXE_OUTPUT_PATH, aper_file, aper_file_path);
// build the name of the modified
// OAF file
replace_file_extension (grism_file, ipc_aper_file, ".fits",
"_ipc.OAF", conf->science_numext);
build_path(AXE_OUTPUT_PATH, ipc_aper_file, ipc_aper_file_path);
// get or set up the output SPC name
if ((opt = get_online_option("out_SPC", argc, argv)))
{
// copy the parameter value if given
strcpy(IPC_file, opt);
}
else
{
// copy the grism name and construct the name
// if not given as parameter
strcpy(IPC_file, grism_file);
replace_file_extension(grism_file, IPC_file, ".fits",
"_ipc.SPC.fits", conf->science_numext);
}
build_path(AXE_OUTPUT_PATH, IPC_file, IPC_file_path);
// get or set up the output SPC name
if ((opt = get_online_option("in_SPC", argc, argv)))
{
// copy the parameter value if given
strcpy(SPC_file, opt);
}
else
{
// copy the grism name and construct the name
// if not given as parameter
strcpy(SPC_file, grism_file);
replace_file_extension(grism_file, SPC_file, ".fits",
".SPC.fits", conf->science_numext);
}
build_path(AXE_OUTPUT_PATH, SPC_file, SPC_file_path);
// form the background image name
replace_file_extension(grism_file, bck_image, ".fits",
".BCK.fits", conf->science_numext);
build_path (AXE_OUTPUT_PATH, bck_image, bck_image_path);
// check whether an intra pixel sensitivity correction
// shall be applied
if ((opt = get_online_option("ipixcorr", argc, argv)))
ipixc = 1;
// check whether an intra pixel sensitivity correction
// shall be applied
if ((opt = get_online_option("nlincorr", argc, argv)))
nlinc = 1;
// check whether something is
// done at all
if (ipixc || nlinc)
{
// Build the intrapixel correction file name
sprintf(IPC_func,"%s",conf->IPIXfunc);
// overwrite it with the parameter if given
if ((opt = get_online_option ("IPIXFUNCTION", argc, argv)))
strcpy(IPC_func,opt);
if (!strcmp(IPC_file,"None"))
// check whether the correction function is given;
// complain if not given!
aXe_message (aXe_M_FATAL, __FILE__, __LINE__,
"aXe_INTPIXCORR: Correction function must be given!!\n");
else
// compose the full pathname
build_path (AXE_CONFIG_PATH, IPC_func, IPC_func_path);
// get the maximum extension number
if ((opt = get_online_option ("max_ext", argc, argv)))
max_ext = atof(opt);
// check whether either max_ext is defined
// OR a special OAF file is given
if (!max_ext && !spec_OAF)
aXe_message (aXe_M_FATAL, __FILE__, __LINE__,
"aXe_INTPIXCORR: Either maximum extension\n"
"OR a special OAF file must be given!\n");
}
// print on screen what's done
fprintf (stdout, "aXe_INTPIXCORR: Grism file name: %s\n",
grism_file_path);
fprintf (stdout, "aXe_INTPIXCORR: Configuration file name: %s\n",
conf_file_path);
fprintf (stdout, "aXe_INTPIXCORR: Correction function: %s\n",
IPC_func_path);
fprintf (stdout, "aXe_INTPIXCORR: Input OAF file name: %s\n",
aper_file_path);
fprintf (stdout, "aXe_INTPIXCORR: Input SPC file name: %s\n",
SPC_file_path);
fprintf (stdout, "aXe_INTPIXCORR: Output SPC file name: %s\n",
IPC_file_path);
fprintf (stdout, "aXe_INTPIXCORR: Maximal extension for point objects: %f\n",
max_ext);
if (ipixc)
fprintf (stdout, "aXe_INTPIXCORR: Intra-pixel sensitivity correction is aplied!\n");
if (nlinc)
fprintf (stdout, "aXe_INTPIXCORR: Non-linearity correction is aplied!\n");
// check whether something is
// done at all
if (ipixc || nlinc)
{
// check whether the intra pixel
// sensitivity is applied
if (ipixc)
{
// determine the exposure time
if (isnan(exptime))
exptime = (double)get_float_from_keyword(grism_file_path, 1,
conf->exptimekey);
if (isnan(exptime))
exptime = 1.0;
// load the image data
obs = load_image_t(grism_file_path, conf->science_numext,
conf->errors_numext, conf->dq_numext,
conf->dqmask, exptime, conf->rdnoise);
// load the background data
bck = load_image_t(bck_image_path, conf->science_numext,
conf->errors_numext, conf->dq_numext,
conf->dqmask, exptime, conf->rdnoise);
// subtract the background from
// the image data
data_matrix = bcksub_observation(obs, bck);
}
// load the aperture list
fprintf (stdout, "aXe_INTPIXCORR: Loading object aperture list...");fflush(stdout);
oblist = file_to_object_list_seq (aper_file_path, obs);
fprintf (stdout,"%d objects loaded.\n",object_list_size(oblist));fflush(stdout);
// open the input SPC file
SPC_ptr = get_SPC_opened(SPC_file_path, 0);
// open the output SPC file
IPC_ptr = create_SPC_opened (IPC_file_path,1);
cards = get_FITS_cards_opened(SPC_ptr);
put_FITS_cards_opened(IPC_ptr, cards);
free_FITScards(cards);
if (ipixc)
// create an interpolator reading in the fits file
ipcorr = create_interp_ftable(IPC_func_path,2,"X","FX",IPCORR_INTERP_TYPE);
else
ipcorr = NULL;
if (nlinc)
// for the NICMOS nonlinearity correction
// create an interpolator for the non-linear correction
//nlincorr = create_nlincor();
nlincorr = create_interp_ftable(IPC_func_path,2,"LAMBDA","BPAR",NLINCORR_INTERP_TYPE);
else
nlincorr = NULL;
while ((aperID!=-1) || (beamID!=-1))
{
// load the next extension from the SPC table
SPC = get_ALL_from_next_in_SPC(SPC_ptr, &aperID, &beamID);
// break the loop if the end was reached
if ((aperID==-1) && (beamID==-1))
break;
// if the full spectrum is NULL,
// go to the next beam
if (!SPC)
continue;
// select the actual beam from the beam list
act_beam = find_beam_in_object_list(oblist, aperID, beamID);
beam_ptr = find_beamptr_in_object_list(oblist, aperID, beamID);
// determine whether the object is pointlike
point_like = is_pointlike(act_beam, spec_OAF, max_ext);
// if the obejct is indeed
// a pointlike one
if (point_like)
{
// check whether the intra-pixel sensititvity correction
// shall be applied
if (ipixc)
{
// form the name of the file which contain
// the data
replace_file_extension(grism_file, ipc_file, ".fits",
".IPC.dat", aperID);
build_path(AXE_OUTPUT_PATH, ipc_file, ipc_file_path);
icorr = fitting_ipc_corr(act_beam, conf_file_path, ipcorr,
SPC, obs, data_matrix, ipc_file_path, beam_ptr);
if (icorr)
fprintf(stdout, "aXe_INTPIXCORR: Corrected BEAM %d%c\n", SPC->aperID, BEAM(SPC->beamID));
else
fprintf(stdout, "aXe_INTPIXCORR: phase accuracy in BEAM %d%c too low\n", SPC->aperID, BEAM(SPC->beamID));
}
// check whether the non-linearity correction
// shall be applied
if (nlinc)
{
/*
if (!strcmp(conf->gainkey,"None"))
adcgain=1.0;
else
adcgain = (double)get_float_from_keyword(grism_file_path, 1, conf->gainkey);
*/
// apply the NICMOS non-linearity correction
fprintf(stdout, "aXe_INTPIXCORR: Non-linearity correting BEAM %d%c...\n", SPC->aperID, BEAM(SPC->beamID));
// the gain mostly used in NICMOS
// is hardcoded here!!!!!
nlin_corr_beam(nlincorr, 6.5, SPC);
}
}
else
{
fprintf(stdout, "aXe_INTPIXCORR: Skipping BEAM %d%c...\n", SPC->aperID, BEAM(SPC->beamID));
}
add_spectra_to_SPC_opened (IPC_ptr, SPC->fgr_spec, SPC->bck_spec,
SPC->obj_spec, SPC->aperID, SPC->beamID);
/* Copy header from OPET extension into this SPC extension */
cards = get_FITS_cards_opened(SPC_ptr);
put_FITS_cards_opened(IPC_ptr,cards);
free_FITScards(cards);
free_full_spectr(SPC);
}
refurbish_object_list(oblist, 1, -100, 0);
fprintf (stdout, "aXe_INTPIXCORR: Writing aperture file %s ... ", ipc_aper_file);fflush(stdout);
num = object_list_to_file (oblist, ipc_aper_file_path, 0);
fprintf (stdout, "%d beams written.\n", num);
// free the object list
if (oblist!=NULL)
free_oblist (oblist);
if (ipcorr)
// free the interpolator
free_interp(ipcorr);
if (nlincorr)
// free the interpolator
free_interp(nlincorr);
fits_close_file (SPC_ptr, &f_status);
if (f_status)
{
ffrprt (stderr, f_status);
aXe_message (aXe_M_FATAL, __FILE__, __LINE__,
"aXe_INTPIXCORR: " "Error closing SPC: %s\n",
SPC_file_path);
}
fits_close_file (IPC_ptr, &f_status);
if (f_status)
{
ffrprt (stderr, f_status);
aXe_message (aXe_M_FATAL, __FILE__, __LINE__,
"aXe_INTPIXCORR: " "Error closing SPC: %s\n",
IPC_file_path);
}
}
// say goodbye
fprintf (stdout, "aXe_INTPIXCORR: Done...\n");
exit (0);
}
| {
"alphanum_fraction": 0.6649595242,
"avg_line_length": 27.6392694064,
"ext": "c",
"hexsha": "8f3bf4d18b53abf598a9c8ba13b5b30bf8ba170b",
"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/aXe_INTPIXCORR.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/aXe_INTPIXCORR.c",
"max_line_length": 111,
"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/aXe_INTPIXCORR.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 3571,
"size": 12106
} |
// Copyright (c) 2005 - 2010 Marc de Kamps
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
// * Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software
// without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY
// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
// USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// If you use this software in work leading to a scientific publication, you should cite
// the 'currently valid reference', which can be found at http://miind.sourceforge.net
#ifndef _CODE_LIBS_NUMTOOLSLIB_NODE_GSLOBJECTS_INCLUDE_GUARD
#define _CODE_LIBS_NUMTOOLSLIB_NODE_GSLOBJECTS_INCLUDE_GUARD
#include <boost/shared_ptr.hpp>
#include <gsl/gsl_odeiv.h>
#include <gsl/gsl_errno.h>
#include "Precision.h"
using boost::shared_ptr;
namespace NumtoolsLib {
typedef unsigned int Number;
typedef int (*Function) (double t, const double y[], double dydt[], void * params);
typedef int (*Derivative) (double t, const double y[], double * dfdy, double dfdt[], void * params);
//! auxilliary struct to clean up some of the code of AbstractDVIntegrator
struct GSLObjects{
const gsl_odeiv_step_type* _p_step_algorithm; //!< pointer to function, so no ownership issues
gsl_odeiv_step* _p_step;
gsl_odeiv_control* _p_controller;
gsl_odeiv_evolve* _p_evolver;
gsl_odeiv_system _system;
GSLObjects
(
const gsl_odeiv_step_type*, //<! choice for solver type
Number, //<! state size
const Precision& //<! absolute and relative precision conform GSL documentation
);
~GSLObjects();
};
}
#endif // include guard
| {
"alphanum_fraction": 0.7588276836,
"avg_line_length": 47.2,
"ext": "h",
"hexsha": "c3ce5ea720f182da6e718a73fea846e036bb0c6f",
"lang": "C",
"max_forks_count": 9,
"max_forks_repo_forks_event_max_datetime": "2022-03-08T12:18:18.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-09-14T20:52:07.000Z",
"max_forks_repo_head_hexsha": "4b321c62c2bd27eb0d5d8336a16a9e840ba63856",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "dekamps/miind",
"max_forks_repo_path": "libs/NumtoolsLib/GSLObjects.h",
"max_issues_count": 41,
"max_issues_repo_head_hexsha": "4b321c62c2bd27eb0d5d8336a16a9e840ba63856",
"max_issues_repo_issues_event_max_datetime": "2022-03-21T16:20:37.000Z",
"max_issues_repo_issues_event_min_datetime": "2015-08-25T07:50:55.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "dekamps/miind",
"max_issues_repo_path": "libs/NumtoolsLib/GSLObjects.h",
"max_line_length": 163,
"max_stars_count": 13,
"max_stars_repo_head_hexsha": "4b321c62c2bd27eb0d5d8336a16a9e840ba63856",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "dekamps/miind",
"max_stars_repo_path": "libs/NumtoolsLib/GSLObjects.h",
"max_stars_repo_stars_event_max_datetime": "2022-03-22T20:26:47.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-09-15T17:28:25.000Z",
"num_tokens": 648,
"size": 2832
} |
/* linalg/cholesky_band.c
*
* Copyright (C) 2018, 2019, 2020 Patrick Alken
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include <config.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_linalg.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_blas.h>
#include <gsl/gsl_cblas.h>
static double cholesky_band_norm1(const gsl_matrix * A);
static int cholesky_band_Ainv(CBLAS_TRANSPOSE_t TransA, gsl_vector * x, void * params);
/*
gsl_linalg_cholesky_band_decomp()
Cholesky decomposition of a square symmetric positive definite banded
matrix
Inputs: A - matrix in banded format, N-by-ndiag where N is the size of
the matrix and ndiag is the number of nonzero diagonals.
Notes:
1) The main diagonal of the Cholesky factor is stored in the first column
of A; the first subdiagonal in the second column and so on.
2) If ndiag > 1, the 1-norm of A is stored in A(N,ndiag) on output
3) At each diagonal element, the matrix is factored as
A(j:end,j:end) = [ A11 A21^T ] = [ alpha 0 ] [ alpha v^T ]
[ A21 A22 ] [ v L ] [ 0 L^T ]
where:
alpha = sqrt(A(j,j))
v = A(j+1:end, j) / alpha
A22 = L L^T + v v^T
So we start at A(1,1) and work right. Pseudo-code is:
loop j = 1, ..., N
alpha = sqrt(A(j,j))
A(j+1:end, j) := A(j+1:end, j) / alpha (DSCAL)
A(j+1:end, j+1:end) -= v v^T (DSYR)
Due to the banded structure, v has at most p non-zero elements, where
p is the lower bandwidth
*/
int
gsl_linalg_cholesky_band_decomp(gsl_matrix * A)
{
const size_t N = A->size1; /* size of matrix */
const size_t ndiag = A->size2; /* number of diagonals in band, including main diagonal */
if (ndiag > N)
{
GSL_ERROR ("invalid matrix dimensions", GSL_EBADLEN);
}
else
{
const size_t p = ndiag - 1; /* lower bandwidth */
const int kld = (int) GSL_MAX(1, p);
size_t j;
if (ndiag > 1)
{
/*
* calculate 1-norm of A and store in lower right of matrix, which is not accessed
* by rest of routine. gsl_linalg_cholesky_band_rcond() will use this later. If
* A is diagonal, there is no empty slot to store the 1-norm, so the rcond routine
* will have to reconstruct it from the Cholesky factor.
*/
double Anorm = cholesky_band_norm1(A);
gsl_matrix_set(A, N - 1, p, Anorm);
}
for (j = 0; j < N; ++j)
{
double ajj = gsl_matrix_get(A, j, 0);
size_t lenv;
if (ajj <= 0.0)
{
GSL_ERROR("matrix is not positive definite", GSL_EDOM);
}
ajj = sqrt(ajj);
gsl_matrix_set(A, j, 0, ajj);
/* number of elements in v, which will normally be p, unless we
* are in lower right corner of matrix */
lenv = GSL_MIN(p, N - j - 1);
if (lenv > 0)
{
gsl_vector_view v = gsl_matrix_subrow(A, j, 1, lenv);
gsl_matrix_view m = gsl_matrix_submatrix(A, j + 1, 0, lenv, lenv);
gsl_blas_dscal(1.0 / ajj, &v.vector);
m.matrix.tda = kld;
gsl_blas_dsyr(CblasUpper, -1.0, &v.vector, &m.matrix);
}
}
return GSL_SUCCESS;
}
}
int
gsl_linalg_cholesky_band_solve (const gsl_matrix * LLT,
const gsl_vector * b,
gsl_vector * x)
{
if (LLT->size1 != b->size)
{
GSL_ERROR ("matrix size must match b size", GSL_EBADLEN);
}
else if (LLT->size1 != 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_band_svx(LLT, x);
return status;
}
}
int
gsl_linalg_cholesky_band_svx (const gsl_matrix * LLT, gsl_vector * x)
{
if (LLT->size1 != x->size)
{
GSL_ERROR ("matrix size must match solution size", GSL_EBADLEN);
}
else
{
/* solve for c using forward-substitution, L c = b */
cblas_dtbsv(CblasColMajor, CblasLower, CblasNoTrans, CblasNonUnit,
(int) LLT->size1, (int) (LLT->size2 - 1), LLT->data, LLT->tda,
x->data, x->stride);
/* perform back-substitution, L^T x = c */
cblas_dtbsv(CblasColMajor, CblasLower, CblasTrans, CblasNonUnit,
(int) LLT->size1, (int) (LLT->size2 - 1), LLT->data, LLT->tda,
x->data, x->stride);
return GSL_SUCCESS;
}
}
int
gsl_linalg_cholesky_band_solvem (const gsl_matrix * LLT,
const gsl_matrix * B,
gsl_matrix * X)
{
if (LLT->size1 != B->size1)
{
GSL_ERROR ("LLT size1 must match B size1", GSL_EBADLEN);
}
else if (LLT->size1 != X->size1)
{
GSL_ERROR ("LLT size1 must match solution size1", GSL_EBADLEN);
}
else if (B->size2 != X->size2)
{
GSL_ERROR ("B size2 must match X size2", GSL_EBADLEN);
}
else
{
int status;
/* copy X <- B */
gsl_matrix_memcpy (X, B);
status = gsl_linalg_cholesky_band_svxm(LLT, X);
return status;
}
}
int
gsl_linalg_cholesky_band_svxm (const gsl_matrix * LLT, gsl_matrix * X)
{
if (LLT->size1 != X->size1)
{
GSL_ERROR ("LLT size1 must match solution size1", GSL_EBADLEN);
}
else
{
int status;
const size_t nrhs = X->size2;
size_t j;
for (j = 0; j < nrhs; ++j)
{
gsl_vector_view xj = gsl_matrix_column(X, j);
status = gsl_linalg_cholesky_band_svx (LLT, &xj.vector);
if (status)
return status;
}
return GSL_SUCCESS;
}
}
int
gsl_linalg_cholesky_band_invert (const gsl_matrix * LLT, gsl_matrix * Ainv)
{
if (Ainv->size1 != Ainv->size2)
{
GSL_ERROR("Ainv must be square", GSL_ENOTSQR);
}
else if (LLT->size1 != Ainv->size1)
{
GSL_ERROR("cholesky matrix has different dimensions from Ainv", GSL_EBADLEN);
}
else
{
int status;
/* unpack Cholesky factor into lower triangle of Ainv */
status = gsl_linalg_cholesky_band_unpack(LLT, Ainv);
if (status)
return status;
/* call the standard Cholesky inversion routine */
status = gsl_linalg_cholesky_invert(Ainv);
if (status)
return status;
return GSL_SUCCESS;
}
}
int
gsl_linalg_cholesky_band_unpack (const gsl_matrix * LLT, gsl_matrix * L)
{
const size_t N = LLT->size1;
if (N != L->size1)
{
GSL_ERROR("L matrix does not match LLT dimensions", GSL_EBADLEN);
}
else if (L->size1 != L->size2)
{
GSL_ERROR("L matrix is not square", GSL_ENOTSQR);
}
else
{
const size_t p = LLT->size2 - 1; /* lower bandwidth */
size_t i;
for (i = 0; i < p + 1; ++i)
{
gsl_vector_const_view v = gsl_matrix_const_subcolumn(LLT, i, 0, N - i);
gsl_vector_view w = gsl_matrix_subdiagonal(L, i);
gsl_vector_memcpy(&w.vector, &v.vector);
}
/* zero out remaining subdiagonals */
for (i = p + 1; i < N; ++i)
{
gsl_vector_view w = gsl_matrix_subdiagonal(L, i);
gsl_vector_set_zero(&w.vector);
}
return GSL_SUCCESS;
}
}
int
gsl_linalg_cholesky_band_rcond (const gsl_matrix * LLT, double * rcond, gsl_vector * work)
{
const size_t N = LLT->size1;
if (work->size != 3 * N)
{
GSL_ERROR ("work vector must have length 3*N", GSL_EBADLEN);
}
else
{
int status;
const size_t ndiag = LLT->size2;
double Anorm; /* ||A||_1 */
double Ainvnorm; /* ||A^{-1}||_1 */
if (ndiag == 1)
{
/* diagonal matrix, compute 1-norm since it has not been stored */
gsl_vector_const_view v = gsl_matrix_const_column(LLT, 0);
Anorm = gsl_vector_max(&v.vector);
Anorm = Anorm * Anorm;
}
else
{
/* 1-norm is stored in A(N, ndiag) by gsl_linalg_cholesky_band_decomp() */
Anorm = gsl_matrix_get(LLT, N - 1, ndiag - 1);
}
*rcond = 0.0;
/* return if matrix is singular */
if (Anorm == 0.0)
return GSL_SUCCESS;
status = gsl_linalg_invnorm1(N, cholesky_band_Ainv, (void *) LLT, &Ainvnorm, work);
if (status)
return status;
if (Ainvnorm != 0.0)
*rcond = (1.0 / Anorm) / Ainvnorm;
return GSL_SUCCESS;
}
}
/*
gsl_linalg_cholesky_band_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_band_scale(const gsl_matrix * A, gsl_vector * S)
{
const size_t N = A->size1; /* size of matrix */
const size_t ndiag = A->size2; /* number of diagonals in band, including main diagonal */
if (ndiag > N)
{
GSL_ERROR ("invalid matrix dimensions", GSL_EBADLEN);
}
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, 0);
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_band_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 in banded format
on output, diag(S) * A * diag(S) in banded format
S - (input) scale factors
*/
int
gsl_linalg_cholesky_band_scale_apply(gsl_matrix * A, const gsl_vector * S)
{
const size_t N = A->size1; /* size of matrix */
const size_t ndiag = A->size2; /* number of diagonals in band, including main diagonal */
if (ndiag > N)
{
GSL_ERROR ("invalid matrix dimensions", GSL_EBADLEN);
}
else if (N != S->size)
{
GSL_ERROR("S must have length N", GSL_EBADLEN);
}
else
{
size_t i, j;
for (j = 0; j < N; ++j)
{
double sj = gsl_vector_get(S, j);
for (i = j; i < GSL_MIN(N, j + ndiag); ++i)
{
double si = gsl_vector_get(S, i);
double * ptr = gsl_matrix_ptr(A, j, i - j);
*ptr *= sj * si;
}
}
return GSL_SUCCESS;
}
}
/* compute 1-norm of symmetric banded matrix */
static double
cholesky_band_norm1(const gsl_matrix * A)
{
const size_t N = A->size1;
const size_t ndiag = A->size2; /* number of diagonals in band, including main diagonal */
double value;
if (ndiag == 1)
{
/* diagonal matrix */
gsl_vector_const_view v = gsl_matrix_const_column(A, 0);
CBLAS_INDEX_t idx = gsl_blas_idamax(&v.vector);
value = gsl_vector_get(&v.vector, idx);
}
else
{
size_t j;
value = 0.0;
for (j = 0; j < N; ++j)
{
size_t ncol = GSL_MIN(ndiag, N - j); /* number of elements in column j below and including main diagonal */
gsl_vector_const_view v = gsl_matrix_const_subrow(A, j, 0, ncol);
double sum = gsl_blas_dasum(&v.vector);
size_t k, l;
/* sum now contains the absolute sum of elements below and including main diagonal for column j; we
* have to add the symmetric elements above the diagonal */
k = j;
l = 1;
while (k > 0 && l < ndiag)
{
double Akl = gsl_matrix_get(A, --k, l++);
sum += fabs(Akl);
}
value = GSL_MAX(value, sum);
}
}
return value;
}
/* x := A^{-1} x = A^{-t} x, A = L L^T */
static int
cholesky_band_Ainv(CBLAS_TRANSPOSE_t TransA, gsl_vector * x, void * params)
{
gsl_matrix * LLT = (gsl_matrix * ) params;
(void) TransA; /* unused parameter warning */
/* compute x := L^{-1} x */
cblas_dtbsv(CblasColMajor, CblasLower, CblasNoTrans, CblasNonUnit,
(int) LLT->size1, (int) (LLT->size2 - 1), LLT->data, LLT->tda,
x->data, x->stride);
/* compute x := L^{-T} x */
cblas_dtbsv(CblasColMajor, CblasLower, CblasTrans, CblasNonUnit,
(int) LLT->size1, (int) (LLT->size2 - 1), LLT->data, LLT->tda,
x->data, x->stride);
return GSL_SUCCESS;
}
| {
"alphanum_fraction": 0.5845346344,
"avg_line_length": 26.6804733728,
"ext": "c",
"hexsha": "2c0b0e26e3c0f5002dfcb4bce4822d212eb3cace",
"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/cholesky_band.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "zzpwahaha/Chimera-Control-Trim",
"max_issues_repo_path": "Chimera/3rd_Party/GSL_MSVC/linalg/cholesky_band.c",
"max_line_length": 117,
"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/cholesky_band.c",
"max_stars_repo_stars_event_max_datetime": "2021-06-14T11:51:37.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-06-14T11:51:37.000Z",
"num_tokens": 4003,
"size": 13527
} |
#pragma once
#include <gsl/span>
#include <cstddef>
#include <type_traits>
namespace imageview {
namespace detail {
template <class T, typename Enable = void>
class HasColorTypeTypedef : public std::false_type {};
template <class T>
class HasColorTypeTypedef<T, std::void_t<typename T::color_type>> : public std::true_type {};
template <class T, typename Enable = void>
class HasKBytesPerPixelConstant : public std::false_type {};
template <class T>
class HasKBytesPerPixelConstant<T, std::enable_if_t<std::is_integral_v<decltype(T::kBytesPerPixel)> &&
std::is_const_v<decltype(T::kBytesPerPixel)>>>
: public std::true_type {};
template <class T, class Enable = void>
class HasRead : public std::false_type {};
template <class T>
class HasRead<T, std::enable_if_t<std::is_same_v<typename T::color_type,
decltype(std::declval<const T&>().read(
std::declval<gsl::span<const std::byte, T::kBytesPerPixel>>()))>>>
: public std::true_type {};
template <class T, class Enable = void>
class HasWrite : public std::false_type {};
template <class T>
class HasWrite<T, std::enable_if_t<std::is_same_v<void, decltype(std::declval<const T&>().write(
std::declval<const typename T::color_type&>(),
std::declval<gsl::span<std::byte, T::kBytesPerPixel>>()))>>>
: public std::true_type {};
} // namespace detail
template <class T>
class IsPixelFormat : public std::conjunction<
// Has a member typedef 'color_type'.
detail::HasColorTypeTypedef<T>,
// Has an integral static member constant 'kBytesPerPixel'.
detail::HasKBytesPerPixelConstant<T>,
// Has a member function read() with the signature equivalent to
// color_type read(gsl::span<const std::byte, kBytesPerPixel>) const;
detail::HasRead<T>,
// Has a member function write() with the signature equivalent to
// void write(const color_type&, gsl::span<std::byte, kBytesPerPixel>) const;
detail::HasWrite<T>> {};
} // namespace imageview
| {
"alphanum_fraction": 0.5721881391,
"avg_line_length": 41.4406779661,
"ext": "h",
"hexsha": "8cc9f9c323cfb3b106ba176aca6f7ca695a51aa6",
"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": "817e92ac1dcbffc7fb0ebb11afe4ee9836f37df0",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "alexanderbelous/imageview",
"max_forks_repo_path": "include/imageview/IsPixelFormat.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "817e92ac1dcbffc7fb0ebb11afe4ee9836f37df0",
"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": "alexanderbelous/imageview",
"max_issues_repo_path": "include/imageview/IsPixelFormat.h",
"max_line_length": 120,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "817e92ac1dcbffc7fb0ebb11afe4ee9836f37df0",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "alexanderbelous/imageview",
"max_stars_repo_path": "include/imageview/IsPixelFormat.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 497,
"size": 2445
} |
#ifndef KGS_EIGENVALUE_H
#define KGS_EIGENVALUE_H
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_linalg.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_multimin.h>
class Eigenvalue {
protected:
const int m, n; ///< Dimensions of matrix
public:
Eigenvalue(gsl_matrix* matrix1, gsl_matrix* matrix2, gsl_matrix* matrix3);
gsl_matrix * const Jacobianmatrix; //TODO: Make private
gsl_matrix * const Hessiancartesian; //TODO: Make private
gsl_matrix * const Hessiantorsionangle; //TODO: Make private
gsl_matrix * const Massmatrix;
gsl_vector_complex * const eigenvaluealpha;
gsl_vector * const eigenvaluebeta;
gsl_matrix_complex * const eigenvector;
gsl_matrix* times(gsl_matrix* matrix1, gsl_matrix* matrix2) const;
virtual ~Eigenvalue();
gsl_matrix* getHessiantorsionangle() const;
void setSingularvalue() const;
gsl_vector* getSingularvalue() const;
gsl_vector * const singularvalue;
};
#endif //KGS_EIGENVALUE_H
| {
"alphanum_fraction": 0.6807116105,
"avg_line_length": 26.7,
"ext": "h",
"hexsha": "ddd47d6af22ccf8e3f8569fc6f751e3ec4cd2e94",
"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/Eigenvalue.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "117c4a3d39ec6285eccc1d3b8e5de9a21db21ec9",
"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": "XiyuChenFAU/kgs_vibration_entropy",
"max_issues_repo_path": "src/math/Eigenvalue.h",
"max_line_length": 82,
"max_stars_count": null,
"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/Eigenvalue.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 268,
"size": 1068
} |
/*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*
** **
** 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 <mpi.h>
#include <StGermain/libStGermain/src/StGermain.h>
#include <petsc.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
const Type StGermain_Type = "StGermain";
#include "StGermain_Tools.h"
StgData* StgInit( int argc, char* argv[] ) {
StgData* data = (StgData*) malloc(sizeof(StgData));
*data = (StgData){.comm = NULL, .rank=-1, .nProcs=-1, .dictionary=NULL, .argcCpy=0, .argvCpy=NULL };
//lets copy all this data for safety
data->argcCpy = argc;
data->argvCpy = (char**) malloc((argc+1)*sizeof(char*));
int ii;
for(ii = 0; ii<argc; ii++){
data->argvCpy[ii] = (char*)malloc(strlen(argv[ii])+1);
strcpy(data->argvCpy[ii],argv[ii]);
}
data->argvCpy[argc] = NULL; //add sentinel
int is_inited;
MPI_Initialized( &is_inited );
if(!is_inited)
MPI_Init( &argc, &argv );
MPI_Comm_dup( MPI_COMM_WORLD, &data->comm );
MPI_Comm_size( data->comm, &data->nProcs );
MPI_Comm_rank( data->comm, &data->rank );
StGermain_Init( &(data->argcCpy), &(data->argvCpy) );
return data;
}
int StgFinalise(StgData* data){
/* Close off everything */
// StGermain_Finalise(); // avoid this finalise, as py interpreter has its own ideas about when it will destroy objects.
PetscFinalize();
// MPI_Finalize();
/* free up these guys created earlier */
int ii;
for(ii = 0; ii<data->argcCpy; ii++)
free(data->argvCpy[ii]);
free(data->argvCpy);
free(data);
return 0; /* success */
}
void StgAbort(StgData* data){
MPI_Abort( data->comm, EXIT_FAILURE );
}
| {
"alphanum_fraction": 0.5183061315,
"avg_line_length": 33.8358208955,
"ext": "c",
"hexsha": "9934c14e62e570307acb8ec110a765d276ee86b4",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "76991c475ac565e092e99a364370fbae15bb40ac",
"max_forks_repo_licenses": [
"CC-BY-4.0"
],
"max_forks_repo_name": "rbeucher/underworld2",
"max_forks_repo_path": "underworld/libUnderworld/libUnderworldPy/StGermain_Tools.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "76991c475ac565e092e99a364370fbae15bb40ac",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"CC-BY-4.0"
],
"max_issues_repo_name": "rbeucher/underworld2",
"max_issues_repo_path": "underworld/libUnderworld/libUnderworldPy/StGermain_Tools.c",
"max_line_length": 124,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "76991c475ac565e092e99a364370fbae15bb40ac",
"max_stars_repo_licenses": [
"CC-BY-4.0"
],
"max_stars_repo_name": "rbeucher/underworld2",
"max_stars_repo_path": "underworld/libUnderworld/libUnderworldPy/StGermain_Tools.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 721,
"size": 2267
} |
/**
* \author Sylvain Marsat, University of Maryland - NASA GSFC
*
* \brief C code for the implementation of the Fourier domain response for LISA-like detectors.
*
*/
#define _XOPEN_SOURCE 500
#ifdef __GNUC__
#define UNUSED __attribute__ ((unused))
#else
#define UNUSED
#endif
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <complex.h>
#include <time.h>
#include <unistd.h>
#include <getopt.h>
#include <stdbool.h>
#include <string.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_bspline.h>
#include <gsl/gsl_blas.h>
#include <gsl/gsl_min.h>
#include <gsl/gsl_spline.h>
#include <gsl/gsl_complex.h>
#include "constants.h"
#include "struct.h"
#include "EOBNRv2HMROMstruct.h"
#include "LISAgeometry.h"
#include "LISAFDresponse.h"
/***************************************/
/********* Core functions **************/
/* Core function processing a signal (in the form of a list of modes) through the Fourier-domain LISA response, for given values of the inclination, position in the sky and polarization angle - here simplified version for just the y_21 observable */
/* Older version of th FD response: two stages, first for the orbital delay (Bessel phase) and second for the constellation delay/modulation */
int LISASimFDResponse21(
LISAconstellation *variant, /* Provides specifics on the variant of LISA */
struct tagListmodesCAmpPhaseFrequencySeries **list, /* Input/Output: list of modes in Frequency-domain amplitude and phase form as produced by the ROM, and output after FD response processing */
const double inclination, /* Inclination of the source */
const double lambda, /* First angle for the position in the sky */
const double beta, /* Second angle for the position in the sky */
const double psi) /* Polarization angle */
{
/* Computing the complicated trigonometric coefficients */
//clock_t begsetcoeffs = clock();
SetCoeffsG(lambda, beta, psi);
//clock_t endsetcoeffs = clock();
//printf("Set Coeffs time: %g s\n", (double)(endsetcoeffs - begsetcoeffs) / CLOCKS_PER_SEC);
/* Main loop over the modes - goes through all the modes present */
ListmodesCAmpPhaseFrequencySeries* listelement = *list;
while(listelement) {
/* Definitions: l,m, frequency series and length */
int l = listelement->l;
int m = listelement->m;
CAmpPhaseFrequencySeries* freqseries = listelement->freqseries;
gsl_vector* freq = freqseries->freq;
gsl_vector* amp_real = freqseries->amp_real;
gsl_vector* amp_imag = freqseries->amp_imag;
gsl_vector* phase = freqseries->phase;
int len = (int) freq->size;
double f, tf, bphi;
double complex camp;
/* Computing the Ylm combined factors for plus and cross for this mode */
/* Capital Phi is set to 0 by convention */
double complex Yfactorplus;
double complex Yfactorcross;
if (!(l%2)) {
Yfactorplus = 1/2 * (SpinWeightedSphericalHarmonic(inclination, 0., -2, l, m) + conj(SpinWeightedSphericalHarmonic(inclination, 0., -2, l, -m)));
Yfactorcross = I/2 * (SpinWeightedSphericalHarmonic(inclination, 0., -2, l, m) - conj(SpinWeightedSphericalHarmonic(inclination, 0., -2, l, -m)));
}
else {
Yfactorplus = 1/2 * (SpinWeightedSphericalHarmonic(inclination, 0., -2, l, m) - conj(SpinWeightedSphericalHarmonic(inclination, 0., -2, l, -m)));
Yfactorcross = I/2 * (SpinWeightedSphericalHarmonic(inclination, 0., -2, l, m) + conj(SpinWeightedSphericalHarmonic(inclination, 0., -2, l, -m)));
}
/* First step of the processing: orbital delay */
/* Initializing spline for the phase */
gsl_spline* spline_phi = gsl_spline_alloc(gsl_interp_cspline, len);
gsl_interp_accel* accel_phi = gsl_interp_accel_alloc();
gsl_spline_init(spline_phi, gsl_vector_const_ptr(freq, 0), gsl_vector_const_ptr(phase, 0), len);
/* Vector keeping track of the Bessel Phase correction - to be used in the next step */
gsl_vector* besselphi = gsl_vector_alloc(len);
/* Loop over the frequencies - computing the correction due to the orbital delay */
for(int j=0; j<len; j++) {
f = gsl_vector_get(freq, j);
tf = gsl_spline_eval_deriv(spline_phi, f, accel_phi)/(2*PI);
bphi = -2*PI*f*variant->OrbitR/C_SI*cos(beta) * cos( variant->OrbitOmega*tf + variant->OrbitPhi0 - lambda );
camp = gsl_vector_get(amp_real, j) * cexp(I*bphi); /* Amplitude is real before applying this first delay */
gsl_vector_set(amp_real, j, creal(camp));
gsl_vector_set(amp_imag, j, cimag(camp));
gsl_vector_set(besselphi, j, bphi);
}
/* Second step of the processing: constellation delay/modulation */
/* Initializing spline for the bessel phase */
gsl_spline* spline_besselphi = gsl_spline_alloc(gsl_interp_cspline, len);
gsl_interp_accel* accel_besselphi = gsl_interp_accel_alloc();
gsl_spline_init(spline_besselphi, gsl_vector_const_ptr(freq, 0), gsl_vector_const_ptr(besselphi, 0), len);
/* Loop over the frequencies - computing the correction due to the orbital delay */
for(int j=0; j<len; j++) {
f = gsl_vector_get(freq, j);
tf = (gsl_spline_eval_deriv(spline_phi, f, accel_phi) + gsl_spline_eval_deriv(spline_besselphi, f, accel_besselphi))/(2*PI);
camp = G21mode(variant, f, tf, Yfactorplus, Yfactorcross) * (gsl_vector_get(amp_real, j) + I * gsl_vector_get(amp_imag, j));
/**/
gsl_vector_set(amp_real, j, creal(camp));
gsl_vector_set(amp_imag, j, cimag(camp));
}
listelement = listelement->next;
/* Clean up */
gsl_spline_free(spline_phi);
gsl_interp_accel_free(accel_phi);
gsl_vector_free(besselphi);
gsl_spline_free(spline_besselphi);
gsl_interp_accel_free(accel_besselphi);
}
return SUCCESS;
}
//WARNING: tRef is ignored for now in the response - i.e. set to 0
/* Core function processing a signal (in the form of a list of modes) through the Fourier-domain LISA response, for given values of the inclination, position in the sky and polarization angle */
int LISASimFDResponsey12(
LISAconstellation *variant, /* Provides specifics on the variant of LISA */
struct tagListmodesCAmpPhaseFrequencySeries **list, /* Input: list of modes in Frequency-domain amplitude and phase form as produced by the ROM */
struct tagListmodesCAmpPhaseFrequencySeries **listy12, /* Output: list of contribution of each mode in Frequency-domain amplitude and phase form, in the y12 observable */
const double torb, /* Reference orbital time - tf as read from the hlm gives t-tinj, this arg allows to pass tinj to the response */
const double lambda, /* First angle for the position in the sky */
const double beta, /* Second angle for the position in the sky */
const double inclination, /* Inclination of the source */
const double psi, /* Polarization angle */
const int tagfrozenLISA, /* Tag to treat LISA as frozen at its torb configuration */
const ResponseApproxtag responseapprox) /* Tag to select possible low-f approximation level in FD response */
{
/* Computing the complicated trigonometric coefficients */
//clock_t begsetcoeffs = clock();
SetCoeffsG(lambda, beta, psi);
//clock_t endsetcoeffs = clock();
//printf("Set Coeffs time: %g s\n", (double)(endsetcoeffs - begsetcoeffs) / CLOCKS_PER_SEC);
/* Main loop over the modes - goes through all the modes present, stopping when encountering NULL */
ListmodesCAmpPhaseFrequencySeries* listelement = *list;
while(listelement) {
/* Definitions: l,m, frequency series and length */
int l = listelement->l;
int m = listelement->m;
CAmpPhaseFrequencySeries* freqseries = listelement->freqseries;
gsl_vector* freq = freqseries->freq;
gsl_vector* amp_real = freqseries->amp_real;
gsl_vector* amp_imag = freqseries->amp_imag;
gsl_vector* phase = freqseries->phase;
int len = (int) freq->size;
double f, tf, tforb;
double complex g12mode = 0.;
double complex g21mode = 0.;
double complex g23mode = 0.;
double complex g32mode = 0.;
double complex g31mode = 0.;
double complex g13mode = 0.;
double complex camp_y;
/* Computing the Ylm combined factors for plus and cross for this mode */
/* Capital Phi is set to 0 by convention */
double complex Yfactorplus;
double complex Yfactorcross;
if (!(l%2)) {
Yfactorplus = 1./2 * (SpinWeightedSphericalHarmonic(inclination, 0., -2, l, m) + conj(SpinWeightedSphericalHarmonic(inclination, 0., -2, l, -m)));
Yfactorcross = I/2 * (SpinWeightedSphericalHarmonic(inclination, 0., -2, l, m) - conj(SpinWeightedSphericalHarmonic(inclination, 0., -2, l, -m)));
}
else {
Yfactorplus = 1./2 * (SpinWeightedSphericalHarmonic(inclination, 0., -2, l, m) - conj(SpinWeightedSphericalHarmonic(inclination, 0., -2, l, -m)));
Yfactorcross = I/2 * (SpinWeightedSphericalHarmonic(inclination, 0., -2, l, m) + conj(SpinWeightedSphericalHarmonic(inclination, 0., -2, l, -m)));
}
/* Initializing spline for the phase */
gsl_spline* spline_phi = gsl_spline_alloc(gsl_interp_cspline, len);
gsl_interp_accel* accel_phi = gsl_interp_accel_alloc();
gsl_spline_init(spline_phi, gsl_vector_const_ptr(freq, 0), gsl_vector_const_ptr(phase, 0), len);
/* Orbital delay, constellation delay/modulation */
/* Initializing frequency series structure for this mode, for each of the TDI observables */
CAmpPhaseFrequencySeries *modefreqseries = NULL;
CAmpPhaseFrequencySeries_Init(&modefreqseries, len);
gsl_vector* freq_y = modefreqseries->freq;
gsl_vector* amp_real_y = modefreqseries->amp_real;
gsl_vector* amp_imag_y = modefreqseries->amp_imag;
gsl_vector* phase_y = modefreqseries->phase;
/* Loop over the frequencies - computing the correction due to the constellation delay/modulation */
//clock_t tbegcontesllation = clock();
//double timingcumulativeGABmode = 0;
for(int j=0; j<len; j++) {
f = gsl_vector_get(freq, j);
tf = (gsl_spline_eval_deriv(spline_phi, f, accel_phi))/(2*PI);
/* tf read from hlm is t-tinj - here convert to orbital time */
if(!(tagfrozenLISA)) {
tforb = tf + torb;
} else {
tforb = torb;
}
//clock_t tbegGAB = clock();
EvaluateGABmode(variant, &g12mode, &g21mode, &g23mode, &g32mode, &g31mode, &g13mode, f, tforb, Yfactorplus, Yfactorcross, 1, responseapprox); /* does include the R-delay term */
//clock_t tendGAB = clock();
//timingcumulativeGABmode += (double) (tendGAB-tbegGAB) /CLOCKS_PER_SEC;
/**/
camp_y = (gsl_vector_get(amp_real, j) + I * gsl_vector_get(amp_imag, j)) * g12mode;
/**/
gsl_vector_set(amp_real_y, j, creal(camp_y));
gsl_vector_set(amp_imag_y, j, cimag(camp_y));
}
//clock_t tendcontesllation = clock();
//printf("Set constellation time: %g s\n", (double)(tendcontesllation - tbegcontesllation) / CLOCKS_PER_SEC);
//printf("GAB cumulated time: %g s\n", timingcumulativeGABmode);
/* Copying the vectors of frequencies and phases */
gsl_vector_memcpy(freq_y, freq);
gsl_vector_memcpy(phase_y, phase);
/* Append the modes to the ouput list-of-modes structures */
*listy12 = ListmodesCAmpPhaseFrequencySeries_AddModeNoCopy(*listy12, modefreqseries, l, m);
/* Going to the next mode in the list */
listelement = listelement->next;
/* Clean up */
gsl_spline_free(spline_phi);
gsl_interp_accel_free(accel_phi);
}
return SUCCESS;
}
//WARNING: tRef is ignored for now in the response - i.e. set to 0
/* Core function processing a signal (in the form of a list of modes) through the Fourier-domain LISA response, for given values of the inclination, position in the sky and polarization angle */
int LISASimFDResponseTDI3Chan(
int tagtRefatLISA, /* 0 to measure Tref from SSB arrival, 1 at LISA guiding center */
LISAconstellation *variant, /* Provides specifics on the variant of LISA */
struct tagListmodesCAmpPhaseFrequencySeries **list, /* Input: list of modes in Frequency-domain amplitude and phase form as produced by the ROM */
struct tagListmodesCAmpPhaseFrequencySeries **listTDI1, /* Output: list of contribution of each mode in Frequency-domain amplitude and phase form, in the TDI channel 1 */
struct tagListmodesCAmpPhaseFrequencySeries **listTDI2, /* Output: list of contribution of each mode in Frequency-domain amplitude and phase form, in the TDI channel 2 */
struct tagListmodesCAmpPhaseFrequencySeries **listTDI3, /* Output: list of contribution of each mode in Frequency-domain amplitude and phase form, in the TDI channel 3 */
const double torb, /* Reference orbital time - tf as read from the hlm gives t-tinj, this arg allows to pass tinj to the response */
const double lambda, /* First angle for the position in the sky */
const double beta, /* Second angle for the position in the sky */
const double inclination, /* Inclination of the source */
const double psi, /* Polarization angle */
const double m1, /* m1 in solar masses - used for resampling */
const double m2, /* m2 in solar masses - used for resampling */
const double maxf, /* Maximal frequency to consider - used to ignore hard-to-resolve response at f>1Hz - NOTE: for now, no recomputation of the boundary, so when not resampling can lose a bit of support between the last frequency point covered and maxf */
const TDItag tditag, /* Selector for the set of TDI observables */
const int tagfrozenLISA, /* Tag to treat LISA as frozen at its torb configuration */
const ResponseApproxtag responseapprox) /* Tag to select possible low-f approximation level in FD response */
{
/* Computing the complicated trigonometric coefficients */
//clock_t begsetcoeffs = clock();
SetCoeffsG(lambda, beta, psi);
//clock_t endsetcoeffs = clock();
//printf("Set Coeffs time: %g s\n", (double)(endsetcoeffs - begsetcoeffs) / CLOCKS_PER_SEC);
/* Chirp mass for resampling */
double mchirp = Mchirpofm1m2(m1, m2);
/* Main loop over the modes - goes through all the modes present, stopping when encountering NULL */
ListmodesCAmpPhaseFrequencySeries* listelement = *list;
while(listelement) {
/* Definitions: l,m, frequency series and length */
int l = listelement->l;
int m = listelement->m;
CAmpPhaseFrequencySeries* freqseries = listelement->freqseries;
gsl_vector* freq = freqseries->freq;
gsl_vector* amp_real = freqseries->amp_real;
gsl_vector* amp_imag = freqseries->amp_imag;
gsl_vector* phase = freqseries->phase;
int len = (int) freq->size;
//
//printf("len: %d\n", len);
//
//if(l==2&&m==1) printf("no resampling 21\n");
// if(l==2&&m==1) {for(int i=0; i<len; i++) printf("%d, %g, %g, %g, %g\n", i, gsl_vector_get(freq, i), gsl_vector_get(amp_real, i), gsl_vector_get(amp_imag, i), gsl_vector_get(phase, i));};
double f, tf, tforb;
double complex g21mode = 0.;
double complex g12mode = 0.;
double complex g32mode = 0.;
double complex g23mode = 0.;
double complex g13mode = 0.;
double complex g31mode = 0.;
double complex camp;
double complex camp1;
double complex camp2;
double complex camp3;
double complex factor1 = 0.;
double complex factor2 = 0.;
double complex factor3 = 0.;
/* Computing the Ylm combined factors for plus and cross for this mode */
/* Capital Phi is set to 0 by convention */
double complex Yfactorplus;
double complex Yfactorcross;
if (!(l%2)) {
Yfactorplus = 1./2 * (SpinWeightedSphericalHarmonic(inclination, 0., -2, l, m) + conj(SpinWeightedSphericalHarmonic(inclination, 0., -2, l, -m)));
Yfactorcross = I/2 * (SpinWeightedSphericalHarmonic(inclination, 0., -2, l, m) - conj(SpinWeightedSphericalHarmonic(inclination, 0., -2, l, -m)));
}
else {
Yfactorplus = 1./2 * (SpinWeightedSphericalHarmonic(inclination, 0., -2, l, m) - conj(SpinWeightedSphericalHarmonic(inclination, 0., -2, l, -m)));
Yfactorcross = I/2 * (SpinWeightedSphericalHarmonic(inclination, 0., -2, l, m) + conj(SpinWeightedSphericalHarmonic(inclination, 0., -2, l, -m)));
}
/* Initializing spline for the phase - will be used to compute tf */
gsl_spline* spline_phi = gsl_spline_alloc(gsl_interp_cspline, len);
gsl_interp_accel* accel_phi = gsl_interp_accel_alloc();
gsl_spline_init(spline_phi, gsl_vector_const_ptr(freq, 0), gsl_vector_const_ptr(phase, 0), len);
/* Resampling at high f to achieve a deltaf of at most 0.002 Hz */
/* Resample linearly at this deltaf when this threshold is reached */
/* NOTE: Assumes input frequencies are logarithmic (except maybe first interval) to evaluate when to resample */
gsl_vector* freqrhigh = NULL;
SetMaxdeltafResampledFrequencies(&freqrhigh, freq, maxf, 0.002); /* Use 0.002Hz as a default maximal deltaf */
/* Resampling at low f to achieve a deltat of at most 2 weeks */
/* Resample linearly in time until this threshold is reached */
/* NOTE: uses Newtonian estimates - also requires the chirp mass as extra information */
/* It would also be possible to use t(f) (more accurate), but we would also need to interpolate f(t) */
/* Accuracy in time of this resampling is not critical, estimate should be enough */
gsl_vector* freqr = NULL;
SetMaxdeltatResampledFrequencies(&freqr, freqrhigh, 1./24, mchirp, m); /* Use half a month as a default maximal deltaft */
/* Evaluate resampled waveform */
CAmpPhaseFrequencySeries* freqseriesr = NULL;
CAmpPhaseFrequencySeries_Resample(&freqseriesr, freqseries, freqr);
gsl_vector* freq_resample = freqseriesr->freq;
gsl_vector* amp_real_resample = freqseriesr->amp_real;
gsl_vector* amp_imag_resample = freqseriesr->amp_imag;
gsl_vector* phase_resample = freqseriesr->phase;
int len_resample = (int) freq_resample->size;
// /* Determine frequencies to use */
// /* Because we will need the interpolation on the Re/Im amplitude to resolve the structure of the L-response at high fequencies, we add points beyond 0.01 Hz, with a linear sampling */
// /* WARNING : It seemed 600 points between 0.1 and 3 Hz (deltaf=0.005) should give interpolation errors below 1e-4 - considering a simple sin(2 pi f L) */
// /* But first test with TDIA show the sampling should be reduced 10-fold - possibly large increase in cost */
// /* We use here deltaf=0.0005 until the cause is better understood */
// /* NOTE: the structure in the response due to the R-delay gives much larger interpolation errors - here we assume the R-delay term is now treated as a phase */
// int resampled = 0; /* Keeps track of wether or not we resampled and allocated new resources we need to free */
// double maxfsignal = gsl_vector_get(freq, len-1);
// double fHigh = fmin(maxf, maxfsignal);
// /* BEWARE : as Mathematica tests show, this is way too pessimistic - normally deltaf=0.002Hz sould work */
// /* To be investigated */
// double fHigh_log_samp = 0.002;
// double deltaflineartarget = 0.00002; //1e-5 better, but slower
// int ifmax = len-1; /* last index to be covered in original sampling overall */
// while((gsl_vector_get(freq, ifmax)>fHigh) && ifmax>0) ifmax--;
// int imaxlogsampling = ifmax; /* last index to be covered with original sampling */
// while((gsl_vector_get(freq, imaxlogsampling)>fHigh_log_samp) && imaxlogsampling>0) imaxlogsampling--;
// gsl_vector* freq_resample = NULL; /* */
// gsl_vector* amp_real_resample = NULL;
// gsl_vector* amp_imag_resample = NULL;
// gsl_vector* phase_resample = NULL;
// int len_resample;
//
// if((fHigh>fHigh_log_samp) && ((fHigh - gsl_vector_get(freq, imaxlogsampling))/deltaflineartarget)>ifmax-imaxlogsampling) { /* condition to check if the linear sampling will add points - if not, do nothing */
//
// resampled = 1;
// /* Number of pts in resampled part */
// int nbfreqlinear = ceil((fHigh - gsl_vector_get(freq, imaxlogsampling))/deltaflineartarget);
// double deltaflinear = (fHigh - gsl_vector_get(freq, imaxlogsampling))/(nbfreqlinear + 1);
// /* Initialize new vectors */
// len_resample = imaxlogsampling + 1 + nbfreqlinear;
// freq_resample = gsl_vector_alloc(len_resample);
// amp_real_resample = gsl_vector_alloc(len_resample);
// amp_imag_resample = gsl_vector_alloc(len_resample);
// phase_resample = gsl_vector_alloc(len_resample);
// /* Build interpolation for original amp_real, amp_imag and phase */
// /* NOTE: we could use spline_phi here, written this way for clarity */
// gsl_spline* spline_amp_real = gsl_spline_alloc(gsl_interp_cspline, len);
// gsl_spline* spline_amp_imag = gsl_spline_alloc(gsl_interp_cspline, len);
// gsl_spline* spline_phase = gsl_spline_alloc(gsl_interp_cspline, len);
// gsl_interp_accel* accel_amp_real = gsl_interp_accel_alloc();
// gsl_interp_accel* accel_amp_imag = gsl_interp_accel_alloc();
// gsl_interp_accel* accel_phase = gsl_interp_accel_alloc();
// gsl_spline_init(spline_amp_real, gsl_vector_const_ptr(freq, 0), gsl_vector_const_ptr(amp_real, 0), len);
// gsl_spline_init(spline_amp_imag, gsl_vector_const_ptr(freq, 0), gsl_vector_const_ptr(amp_imag, 0), len);
// gsl_spline_init(spline_phase, gsl_vector_const_ptr(freq, 0), gsl_vector_const_ptr(phase, 0), len);
// /* Set resampled frequencies and values */
// for(int j=0; j<=imaxlogsampling; j++) {
// gsl_vector_set(freq_resample, j, gsl_vector_get(freq, j));
// gsl_vector_set(amp_real_resample, j, gsl_vector_get(amp_real, j));
// gsl_vector_set(amp_imag_resample, j, gsl_vector_get(amp_imag, j));
// gsl_vector_set(phase_resample, j, gsl_vector_get(phase, j));
// }
// double fimax = gsl_vector_get(freq, imaxlogsampling);
// for(int j=imaxlogsampling+1; j<len_resample; j++) {
// f = fimax + (j-imaxlogsampling) * deltaflinear;
// gsl_vector_set(freq_resample, j, f);
// gsl_vector_set(amp_real_resample, j, gsl_spline_eval(spline_amp_real, f, accel_amp_real));
// gsl_vector_set(amp_imag_resample, j, gsl_spline_eval(spline_amp_imag, f, accel_amp_imag));
// gsl_vector_set(phase_resample, j, gsl_spline_eval(spline_phase, f, accel_phase));
// }
// /* Free interpolation functions */
// gsl_spline_free(spline_amp_real);
// gsl_spline_free(spline_amp_imag);
// gsl_spline_free(spline_phase);
// gsl_interp_accel_free(accel_amp_real);
// gsl_interp_accel_free(accel_amp_imag);
// gsl_interp_accel_free(accel_phase);
// }
// else { /* If no resampling, use the values we had as input */
// resampled = 0;
// len_resample = imaxlogsampling + 1; /* If maxf < maxfsignal, we will cut the signal above maxf by simply adjusting the range of indices included (NOTE: without recomputing the exact boundary, so some support is lost due to discretization) */
// freq_resample = freq;
// amp_real_resample = amp_real;
// amp_imag_resample = amp_imag;
// phase_resample = phase;
// }
/* Initializing frequency series structure for this mode, for each of the TDI observables */
CAmpPhaseFrequencySeries *modefreqseries1 = NULL;
CAmpPhaseFrequencySeries *modefreqseries2 = NULL;
CAmpPhaseFrequencySeries *modefreqseries3 = NULL;
CAmpPhaseFrequencySeries_Init(&modefreqseries1, len_resample);
CAmpPhaseFrequencySeries_Init(&modefreqseries2, len_resample);
CAmpPhaseFrequencySeries_Init(&modefreqseries3, len_resample);
gsl_vector* freq1 = modefreqseries1->freq;
gsl_vector* amp_real1 = modefreqseries1->amp_real;
gsl_vector* amp_imag1 = modefreqseries1->amp_imag;
gsl_vector* phase1 = modefreqseries1->phase;
gsl_vector* freq2 = modefreqseries2->freq;
gsl_vector* amp_real2 = modefreqseries2->amp_real;
gsl_vector* amp_imag2 = modefreqseries2->amp_imag;
gsl_vector* phase2 = modefreqseries2->phase;
gsl_vector* freq3 = modefreqseries3->freq;
gsl_vector* amp_real3 = modefreqseries3->amp_real;
gsl_vector* amp_imag3 = modefreqseries3->amp_imag;
gsl_vector* phase3 = modefreqseries3->phase;
/* Loop over the frequencies */
//clock_t tbegcontesllation = clock();
//double timingcumulativeGABmode = 0;
for(int j=0; j<len_resample; j++) {
f = gsl_vector_get(freq_resample, j);
tf = (gsl_spline_eval_deriv(spline_phi, f, accel_phi))/(2*PI);
/* tf read from hlm is t-tinj - here convert to orbital time using torb - ignore tf if orbit is frozen */
if(!(tagfrozenLISA)) {
tforb = tf + torb;
} else {
tforb = torb;
}
//clock_t tbegGAB = clock();
EvaluateGABmode(variant, &g12mode, &g21mode, &g23mode, &g32mode, &g31mode, &g13mode, f, tforb, Yfactorplus, Yfactorcross, 0, responseapprox); /* does not include the R-delay term */
//clock_t tendGAB = clock();
//timingcumulativeGABmode += (double) (tendGAB-tbegGAB) /CLOCKS_PER_SEC;
/**/
EvaluateTDIfactor3Chan(variant, &factor1, &factor2, &factor3, g12mode, g21mode, g23mode, g32mode, g31mode, g13mode, f, tditag, responseapprox);
double complex amphtilde = gsl_vector_get(amp_real_resample, j) + I * gsl_vector_get(amp_imag_resample, j);
camp1 = factor1 * amphtilde;
camp2 = factor2 * amphtilde;
camp3 = factor3 * amphtilde;
/* Phase term due to the R-delay, including correction to first order */
double phase=variant->OrbitOmega*tforb + variant->OrbitPhi0 - lambda;
double OrbitRoC=variant->OrbitR/C_SI;
//double phaseRdelay = -2*PI*R_SI/C_SI*f*cos(beta)*cos(Omega_SI*tf - lambda) * (1 + R_SI/C_SI*cos(beta)*Omega_SI*sin(Omega_SI*tf - lambda));
double phaseRdelay;
if(tagtRefatLISA==0){//delay so that tinj=torb refers to arrival time at SSB
phaseRdelay = -2*PI*OrbitRoC*f*cos(beta)*cos(phase) * (1 + cos(beta)*OrbitRoC*variant->OrbitOmega*sin(phase));
} else {
//In this version we delay so that tinj=torb is relative to LISAcenter arrival time, so there is no orbital delay when tf = tinj
//If the original delay realized td=t+d(t), now we want td=t+d(t)-d(t0), that we we change d(t) -> d(t) + d(t0)
//Then with the approximation d(td)=d(t)(1-ddot(t)),
double phase0 = variant->OrbitOmega*torb + variant->OrbitPhi0 - lambda;
phaseRdelay = -2*PI*OrbitRoC*f*cos(beta)*( cos(phase)-cos(phase0) ) * (1 + cos(beta)*OrbitRoC*variant->OrbitOmega*sin(phase));
}
if(responseapprox==lowf) { /* In the full low-f approximation, ignore this delay term */
phaseRdelay = 0.;
}
double phasewithRdelay = gsl_vector_get(phase_resample, j) + phaseRdelay;
/**/
gsl_vector_set(amp_real1, j, creal(camp1));
gsl_vector_set(amp_imag1, j, cimag(camp1));
gsl_vector_set(amp_real2, j, creal(camp2));
gsl_vector_set(amp_imag2, j, cimag(camp2));
gsl_vector_set(amp_real3, j, creal(camp3));
gsl_vector_set(amp_imag3, j, cimag(camp3));
gsl_vector_set(phase1, j, phasewithRdelay);
gsl_vector_set(phase2, j, phasewithRdelay);
gsl_vector_set(phase3, j, phasewithRdelay);
}
//clock_t tendconstellation = clock();
//printf("Set constellation time: %g s\n", (double)(tendconstellation - tbegconstellation) / CLOCKS_PER_SEC);
//printf("GAB cumulated time: %g s\n", timingcumulativeGABmode);
/* Copying the vectors of frequencies - we have to allow for the case where it has been shortened */
gsl_vector_view freq_resample_subview = gsl_vector_subvector(freq_resample, 0, len_resample);
gsl_vector_memcpy(freq1, &freq_resample_subview.vector);
gsl_vector_memcpy(freq2, &freq_resample_subview.vector);
gsl_vector_memcpy(freq3, &freq_resample_subview.vector);
/* Append the modes to the ouput list-of-modes structures */
*listTDI1 = ListmodesCAmpPhaseFrequencySeries_AddModeNoCopy(*listTDI1, modefreqseries1, l, m);
*listTDI2 = ListmodesCAmpPhaseFrequencySeries_AddModeNoCopy(*listTDI2, modefreqseries2, l, m);
*listTDI3 = ListmodesCAmpPhaseFrequencySeries_AddModeNoCopy(*listTDI3, modefreqseries3, l, m);
/* Going to the next mode in the list */
listelement = listelement->next;
/* Clean up */
gsl_spline_free(spline_phi);
gsl_interp_accel_free(accel_phi);
gsl_vector_free(freqrhigh);
gsl_vector_free(freqr);
CAmpPhaseFrequencySeries_Cleanup(freqseriesr);
// /* If we used resampling, then we need to free the additional resources that were allocated */
// if(resampled) {
// gsl_vector_free(freq_resample);
// gsl_vector_free(amp_real_resample);
// gsl_vector_free(amp_imag_resample);
// gsl_vector_free(phase_resample);
// }
}
return SUCCESS;
}
| {
"alphanum_fraction": 0.6801262041,
"avg_line_length": 55.2745825603,
"ext": "c",
"hexsha": "9789e6ff9f8c6d9de507d2c57e6dc7bb6ad8a2fe",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2020-07-20T02:56:30.000Z",
"max_forks_repo_forks_event_min_datetime": "2018-09-20T14:19:13.000Z",
"max_forks_repo_head_hexsha": "4ffb02977d19786ab8c1a767cc495a799d9575ae",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "titodalcanton/flare",
"max_forks_repo_path": "LISAsim/LISAFDresponse.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "4ffb02977d19786ab8c1a767cc495a799d9575ae",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "titodalcanton/flare",
"max_issues_repo_path": "LISAsim/LISAFDresponse.c",
"max_line_length": 295,
"max_stars_count": 3,
"max_stars_repo_head_hexsha": "4ffb02977d19786ab8c1a767cc495a799d9575ae",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "titodalcanton/flare",
"max_stars_repo_path": "LISAsim/LISAFDresponse.c",
"max_stars_repo_stars_event_max_datetime": "2020-07-20T02:56:25.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-05-26T15:21:13.000Z",
"num_tokens": 7992,
"size": 29793
} |
// @file im2col_conv.c
//
// \date Created on: Sep 30, 2017
// \author Gopalakrishna Hegde
//
// Description:
//
//
//
#include <stdbool.h>
#include <cblas.h>
#include "common_types.h"
//From Berkeley Vision's Caffe
//Refer to Caffe's license : https://github.com/BVLC/caffe/blob/master/LICENSE
static inline bool is_a_ge_zero_and_a_lt_b(int a, int b) {
return (unsigned int)a < (unsigned int)(b);
}
void Im2Col(const float *data_im, const int channels,
const int height, const int width, const int kernel_h, const int kernel_w,
const int pad_h, const int pad_w,
const int stride_h, const int stride_w,
float *data_col) {
const int output_h = (height + 2 * pad_h -
((kernel_h - 1) + 1)) / stride_h + 1;
const int output_w = (width + 2 * pad_w -
((kernel_w - 1) + 1)) / stride_w + 1;
const int channel_size = height * width;
for (int channel = channels; channel--; data_im += channel_size) {
for (int kernel_row = 0; kernel_row < kernel_h; kernel_row++) {
for (int kernel_col = 0; kernel_col < kernel_w; kernel_col++) {
int input_row = -pad_h + kernel_row;
for (int output_rows = output_h; output_rows; output_rows--) {
if (!is_a_ge_zero_and_a_lt_b(input_row, height)) {
for (int output_cols = output_w; output_cols; output_cols--) {
*(data_col++) = 0;
}
} else {
int input_col = -pad_w + kernel_col;
for (int output_col = output_w; output_col; output_col--) {
if (is_a_ge_zero_and_a_lt_b(input_col, width)) {
*(data_col++) = data_im[input_row * width + input_col];
} else {
*(data_col++) = 0;
}
input_col += stride_w;
}
}
input_row += stride_h;
}
}
}
}
}
void Im2ColConvLayer(const float *input, const float *weight,
const float *bias, float *scratchpad, const TensorDim in_dim,
const TensorDim out_dim, const int ker_size, const int group,
const int pad, const int stride, const int bias_en, float *output) {
int C = in_dim.c;
int H = in_dim.h;
int W = in_dim.w;
int in_ch_per_group = C / group;
int out_ch_per_group = out_dim.c / group;
float alpha = 1;
float beta = 0;
for (int b = 0; b < in_dim.n; b++) {
int in_offset = b * C * H * W;
Im2Col(input + in_offset, C, H, W, ker_size, ker_size, pad, pad, stride,
stride, scratchpad);
for (int g = 0; g < group; g++) {
int weight_offset = g * ker_size * ker_size * in_ch_per_group * out_ch_per_group;
int data_offset = g * (ker_size * ker_size * in_ch_per_group) *
(out_dim.h * out_dim.w);
int out_offset = (b * out_dim.c + g * out_ch_per_group) *
out_dim.h * out_dim.w;
int m = out_ch_per_group;
int k = in_ch_per_group * ker_size * ker_size;
int n = out_dim.h * out_dim.w;
cblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans,
m, n, k, alpha, weight + weight_offset,
k, scratchpad + data_offset, n, beta, output + out_offset, n);
}
}
}
| {
"alphanum_fraction": 0.6010841837,
"avg_line_length": 33.7204301075,
"ext": "c",
"hexsha": "7793eec86c6383602fcdb18bead8ad5dc4a33446",
"lang": "C",
"max_forks_count": 23,
"max_forks_repo_forks_event_max_datetime": "2021-12-21T14:16:14.000Z",
"max_forks_repo_forks_event_min_datetime": "2017-10-24T05:17:21.000Z",
"max_forks_repo_head_hexsha": "c5f612d35888e224aa610408a7fc9f08f232147c",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "chayitw/convolution-flavors",
"max_forks_repo_path": "src/im2col_conv.c",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "c5f612d35888e224aa610408a7fc9f08f232147c",
"max_issues_repo_issues_event_max_datetime": "2021-10-16T02:49:23.000Z",
"max_issues_repo_issues_event_min_datetime": "2021-10-16T02:49:23.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "chayitw/convolution-flavors",
"max_issues_repo_path": "src/im2col_conv.c",
"max_line_length": 87,
"max_stars_count": 54,
"max_stars_repo_head_hexsha": "c5f612d35888e224aa610408a7fc9f08f232147c",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "gplhegde/convolution-flavors",
"max_stars_repo_path": "src/im2col_conv.c",
"max_stars_repo_stars_event_max_datetime": "2022-01-12T06:38:50.000Z",
"max_stars_repo_stars_event_min_datetime": "2017-10-03T18:10:24.000Z",
"num_tokens": 890,
"size": 3136
} |
//
// Created by pedram pakseresht on 2/18/21.
//
// #include <petsc.h>
#include <printf.h>
#include <stdlib.h>
void setNumber(double *zxy);
typedef struct{
double x;
double z;
int g[3];
}Pstruct;
void printStruct(Pstruct str) {
printf("print struct %f %f %d %d %d \n", str.x, str.z, str.g[0], str.g[1], str.g[2]);
// printf("print x %lf \n", str.z );
// printf("print x %lf \n", str.g[1] );
};
void setValues(){
}
int main( int argc, char *argv[] )
{
Pstruct a;
a.x = 7.0;
a.z = 8.0;
a.g[0] = 1;
a.g[1] = 2;
a.g[2] = 3;
Pstruct b;
b.x = 5.0;
b.z = 4.0;
b.g[0] = 3;
b.g[1] = 1;
b.g[2] = 2;
printStruct(a);
printStruct(b);
// printf("x of b is %lf \n",b.x);
//printf("size of struc %lu \n", sizeof(Pstruct));
//printf("size of int %lu", sizeof(int [4]));
}
| {
"alphanum_fraction": 0.5046296296,
"avg_line_length": 12.8955223881,
"ext": "c",
"hexsha": "27ae140c9932b0dd16c4a85576e8f8378a9e182e",
"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": "c7bb7cf4a4ec706170efd7c06bf8589e30ece47b",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "pakserep/ablateClient",
"max_forks_repo_path": "structExp.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "c7bb7cf4a4ec706170efd7c06bf8589e30ece47b",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "pakserep/ablateClient",
"max_issues_repo_path": "structExp.c",
"max_line_length": 89,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "c7bb7cf4a4ec706170efd7c06bf8589e30ece47b",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "pakserep/ablateClient",
"max_stars_repo_path": "structExp.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 325,
"size": 864
} |
/*
Excited States software: KGS
Contributors: See CONTRIBUTORS.txt
Contact: kgs-contact@simtk.org
Copyright (C) 2009-2017 Stanford University
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
This entire text, including the above copyright notice and this permission notice
shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS, CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
IN THE SOFTWARE.
*/
//
// Created by Dominik Budday on 15.03.16.
//
#ifndef KGS_FASTCLASHAVOIDINGMOVE_H
#define KGS_FASTCLASHAVOIDINGMOVE_H
#include <vector>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_matrix.h>
#include "metrics/Metric.h"
#include "metrics/RMSD.h"
#include "moves/Move.h"
#include "core/Configuration.h"
class FastClashAvoidingMove : public Move
{
public:
FastClashAvoidingMove( double maxRotation,
int trialSteps,
const std::string& atomTypes,
bool projectConstraints
);
protected:
Configuration* performMove(Configuration* current, gsl_vector* gradient);
private:
Configuration* projectOnClashNullspace(Configuration *conf,
gsl_vector *gradient,
std::set<std::pair<Atom *, Atom *> > &collisions);
gsl_matrix* computeClashAvoidingJacobian( Configuration* conf,
std::map<int,int>& dofMap,
std::set< std::pair<Atom*,Atom*> >& collisions);
/** Return a map that associates cycle-dofs and constrained dofs with a general dofs. */
std::map<int,int> collectConstrainedDofMap(Configuration* conf, std::set< std::pair<Atom*,Atom*> >& allCollisions);
const int m_trialSteps;
const bool m_projectConstraints;
const std::string m_collisionCheckAtomTypes;
};
#endif //KGS_FASTCLASHAVOIDINGMOVE_H
| {
"alphanum_fraction": 0.7129491018,
"avg_line_length": 35.6266666667,
"ext": "h",
"hexsha": "3785896c3500cc00420feadbf6f21653742ebe1b",
"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/moves/FastClashAvoidingMove.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/moves/FastClashAvoidingMove.h",
"max_line_length": 117,
"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/moves/FastClashAvoidingMove.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": 581,
"size": 2672
} |
#pragma once
#include "halley_gl.h"
#include <gsl/gsl>
namespace Halley
{
class GLBuffer
{
public:
GLBuffer();
~GLBuffer();
void bind();
void bindToTarget(GLuint index);
void init(GLenum target, GLenum usage = GL_STREAM_DRAW);
void setData(gsl::span<const gsl::byte> data);
size_t getSize() const;
private:
GLenum target = 0;
GLenum usage = 0;
GLuint name = 0;
size_t capacity = 0;
size_t size = 0;
};
}
| {
"alphanum_fraction": 0.6568848758,
"avg_line_length": 15.8214285714,
"ext": "h",
"hexsha": "7fdcaefdc7d3b20c4604dd3c3c092f4fba72524f",
"lang": "C",
"max_forks_count": 193,
"max_forks_repo_forks_event_max_datetime": "2022-03-22T12:59:58.000Z",
"max_forks_repo_forks_event_min_datetime": "2017-10-23T06:08:41.000Z",
"max_forks_repo_head_hexsha": "fc4f153956cc34d7fa02b76850e22183b8e30e25",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "sunhay/halley",
"max_forks_repo_path": "src/plugins/opengl/src/gl_buffer.h",
"max_issues_count": 53,
"max_issues_repo_head_hexsha": "fc4f153956cc34d7fa02b76850e22183b8e30e25",
"max_issues_repo_issues_event_max_datetime": "2022-01-10T13:52:37.000Z",
"max_issues_repo_issues_event_min_datetime": "2016-10-09T16:25:04.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "sunhay/halley",
"max_issues_repo_path": "src/plugins/opengl/src/gl_buffer.h",
"max_line_length": 58,
"max_stars_count": 3262,
"max_stars_repo_head_hexsha": "fc4f153956cc34d7fa02b76850e22183b8e30e25",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "sunhay/halley",
"max_stars_repo_path": "src/plugins/opengl/src/gl_buffer.h",
"max_stars_repo_stars_event_max_datetime": "2022-03-31T17:47:08.000Z",
"max_stars_repo_stars_event_min_datetime": "2016-04-10T15:24:10.000Z",
"num_tokens": 132,
"size": 443
} |
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include <gsl/gsl_integration.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_roots.h>
#include <gsl/gsl_spline.h>
#include <gsl/gsl_sf_bessel.h>
#include <gsl/gsl_sf_legendre.h>
#include "fftlog.h"
#include "ccl.h"
#include "ccl_params.h"
/*--------ROUTINE: taper_cl ------
TASK:n Apply cosine tapering to Cls to reduce aliasing
INPUT: number of ell bins for Cl, ell vector, C_ell vector, limits for tapering
e.g., ell_limits=[low_ell_limit_lower,low_ell_limit_upper,high_ell_limit_lower,high_ell_limit_upper]
*/
static int taper_cl(int n_ell,double *ell,double *cl, double *ell_limits)
{
for(int i=0;i<n_ell;i++) {
if(ell[i]<ell_limits[0] || ell[i]>ell_limits[3]) {
cl[i]=0;//ell outside desirable range
continue;
}
if(ell[i]>=ell_limits[1] && ell[i]<=ell_limits[2])
continue;//ell within good ell range
if(ell[i]<ell_limits[1])//tapering low ell
cl[i]*=cos((ell[i]-ell_limits[1])/(ell_limits[1]-ell_limits[0])*M_PI/2.);
if(ell[i]>ell_limits[2])//tapering high ell
cl[i]*=cos((ell[i]-ell_limits[2])/(ell_limits[3]-ell_limits[2])*M_PI/2.);
}
return 0;
}
/*--------ROUTINE: ccl_tracer_corr_fftlog ------
TASK: For a given tracer, get the correlation function
Following function takes a function to calculate angular cl as well.
By default above function will call it using ccl_angular_cl
INPUT: type of tracer, number of theta values to evaluate = NL, theta vector
*/
static void ccl_tracer_corr_fftlog(ccl_cosmology *cosmo,
int n_ell,double *ell,double *cls,
int n_theta,double *theta,double *wtheta,
int corr_type,int do_taper_cl,double *taper_cl_limits,
int *status)
{
int i;
double *l_arr,*cl_arr,*th_arr,*wth_arr;
l_arr=ccl_log_spacing(ccl_splines->ELL_MIN_CORR,ccl_splines->ELL_MAX_CORR,ccl_splines->N_ELL_CORR);
if(l_arr==NULL) {
*status=CCL_ERROR_LINSPACE;
ccl_cosmology_set_status_message(cosmo, "ccl_correlation.c: ccl_tracer_corr_fftlog ran out of memory\n");
return;
}
cl_arr=malloc(ccl_splines->N_ELL_CORR*sizeof(double));
if(cl_arr==NULL) {
free(l_arr);
*status=CCL_ERROR_MEMORY;
ccl_cosmology_set_status_message(cosmo, "ccl_correlation.c: ccl_tracer_corr_fftlog ran out of memory\n");
return;
}
//Interpolate input Cl into array needed for FFTLog
SplPar *cl_spl=ccl_spline_init(n_ell,ell,cls,cls[0],0);
if(cl_spl==NULL) {
free(l_arr);
free(cl_arr);
*status=CCL_ERROR_MEMORY;
ccl_cosmology_set_status_message(cosmo, "ccl_correlation.c: ccl_tracer_corr_fftlog ran out of memory\n");
return;
}
double cl_tilt,l_edge,cl_edge;
l_edge=ell[n_ell-1];
if((cls[n_ell-1]*cls[n_ell-2]<0) || (cls[n_ell-2]==0)) {
cl_tilt=0;
cl_edge=0;
}
else {
cl_tilt=log(cls[n_ell-1]/cls[n_ell-2])/log(ell[n_ell-1]/ell[n_ell-2]);
cl_edge=cls[n_ell-1];
}
for(i=0;i<ccl_splines->N_ELL_CORR;i++) {
if(l_arr[i]>=l_edge)
cl_arr[i]=cl_edge*pow(l_arr[i]/l_edge,cl_tilt);
else
cl_arr[i]=ccl_spline_eval(l_arr[i],cl_spl);
}
ccl_spline_free(cl_spl);
if (do_taper_cl)
taper_cl(ccl_splines->N_ELL_CORR,l_arr,cl_arr,taper_cl_limits);
th_arr=malloc(sizeof(double)*ccl_splines->N_ELL_CORR);
if(th_arr==NULL) {
free(l_arr);
free(cl_arr);
*status=CCL_ERROR_MEMORY;
ccl_cosmology_set_status_message(cosmo, "ccl_correlation.c: ccl_tracer_corr_fftlog ran out of memory\n");
return;
}
wth_arr=(double *)malloc(sizeof(double)*ccl_splines->N_ELL_CORR);
if(wth_arr==NULL) {
free(l_arr); free(cl_arr); free(th_arr);
*status=CCL_ERROR_MEMORY;
ccl_cosmology_set_status_message(cosmo, "ccl_correlation.c: ccl_tracer_corr_fftlog ran out of memory\n");
return;
}
for(i=0;i<ccl_splines->N_ELL_CORR;i++)
th_arr[i]=0;
//Although set here to 0, theta is modified by FFTlog to obtain the correlation at ~1/l
int i_bessel=0;
if(corr_type==CCL_CORR_GG) i_bessel=0;
if(corr_type==CCL_CORR_GL) i_bessel=2;
if(corr_type==CCL_CORR_LP) i_bessel=0;
if(corr_type==CCL_CORR_LM) i_bessel=4;
fftlog_ComputeXi2D(i_bessel,ccl_splines->N_ELL_CORR,l_arr,cl_arr,th_arr,wth_arr);
// Interpolate to output values of theta
SplPar *wth_spl=ccl_spline_init(ccl_splines->N_ELL_CORR,th_arr,wth_arr,wth_arr[0],0);
for(i=0;i<n_theta;i++)
wtheta[i]=ccl_spline_eval(theta[i]*M_PI/180.,wth_spl);
ccl_spline_free(wth_spl);
free(l_arr); free(cl_arr);
free(th_arr); free(wth_arr);
return;
}
typedef struct {
int nell;
double ell0;
double ellf;
double cl0;
double clf;
int extrapol_0;
int extrapol_f;
double tilt0;
double tiltf;
SplPar *cl_spl;
int i_bessel;
double th;
} corr_int_par;
static double corr_bessel_integrand(double l,void *params)
{
double cl,jbes;
corr_int_par *p=(corr_int_par *)params;
double x=l*p->th;
if(l<p->ell0) {
if(p->extrapol_0)
cl=p->cl0*pow(l/p->ell0,p->tilt0);
else
cl=0;
}
else if(l>p->ellf) {
if(p->extrapol_f)
cl=p->clf*pow(l/p->ellf,p->tiltf);
else
cl=0;
}
else
cl=ccl_spline_eval(l,p->cl_spl);
jbes=gsl_sf_bessel_Jn(p->i_bessel,x);
return l*jbes*cl;
}
static void ccl_tracer_corr_bessel(ccl_cosmology *cosmo,
int n_ell,double *ell,double *cls,
int n_theta,double *theta,double *wtheta,
int corr_type,int *status)
{
corr_int_par *cp=malloc(sizeof(corr_int_par));
if(cp==NULL) {
*status=CCL_ERROR_MEMORY;
ccl_cosmology_set_status_message(cosmo, "ccl_correlation.c: ccl_tracer_corr_bessel ran out of memory\n");
return;
}
cp->nell=n_ell;
cp->ell0=ell[0];
cp->ellf=ell[n_ell-1];
cp->cl0=cls[0];
cp->clf=cls[n_ell-1];
cp->cl_spl=ccl_spline_init(n_ell,ell,cls,cls[0],0);
if(cp->cl_spl==NULL) {
free(cp);
*status=CCL_ERROR_MEMORY;
ccl_cosmology_set_status_message(cosmo, "ccl_correlation.c: ccl_tracer_corr_bessel ran out of memory\n");
return;
}
switch(corr_type) {
case CCL_CORR_GG :
cp->i_bessel=0;
break;
case CCL_CORR_GL :
cp->i_bessel=2;
break;
case CCL_CORR_LP :
cp->i_bessel=0;
break;
case CCL_CORR_LM :
cp->i_bessel=4;
break;
}
if(cls[0]*cls[1]<=0)
cp->extrapol_0=0;
else {
cp->extrapol_0=1;
cp->tilt0=log10(cls[1]/cls[0])/log10(ell[1]/ell[0]);
}
if(cls[n_ell-2]*cls[n_ell-1]<=0)
cp->extrapol_f=0;
else {
cp->extrapol_f=1;
cp->tiltf=log10(cls[n_ell-1]/cls[n_ell-2])/log10(ell[n_ell-1]/ell[n_ell-2]);
}
int ith, gslstatus;
double result,eresult;
gsl_function F;
gsl_integration_workspace *w=gsl_integration_workspace_alloc(ccl_gsl->N_ITERATION);
for(ith=0;ith<n_theta;ith++) {
cp->th=theta[ith]*M_PI/180;
F.function=&corr_bessel_integrand;
F.params=cp;
//TODO: Split into intervals between first bessel zeros before integrating
//This will help both speed and accuracy of the integral.
gslstatus = gsl_integration_qag(&F, 0, ccl_splines->ELL_MAX_CORR, 0,
ccl_gsl->INTEGRATION_EPSREL, ccl_gsl->N_ITERATION,
ccl_gsl->INTEGRATION_GAUSS_KRONROD_POINTS,
w, &result, &eresult);
if(gslstatus != GSL_SUCCESS) {
ccl_raise_gsl_warning(gslstatus, "ccl_correlation.c: ccl_tracer_corr_bessel():");
*status |= gslstatus;
}
wtheta[ith]=result/(2*M_PI);
}
gsl_integration_workspace_free(w);
ccl_spline_free(cp->cl_spl);
free(cp);
}
/*--------ROUTINE: ccl_compute_legendre_polynomial ------
TASK: Compute input factor for ccl_tracer_corr_legendre
INPUT: tracer 1, tracer 2, i_bessel, theta array, n_theta, L_max, output Pl_theta
*/
static void ccl_compute_legendre_polynomial(int corr_type,double theta,int ell_max,double *Pl_theta)
{
int i,j;
double k=0;
double cth=cos(theta*M_PI/180);
//Initialize Pl_theta
for (j=0;j<=ell_max;j++)
Pl_theta[j]=0.;
if(corr_type==CCL_CORR_GG) {
gsl_sf_legendre_Pl_array(ell_max,cth,Pl_theta);
for (j=0;j<=ell_max;j++)
Pl_theta[j]*=(2*j+1);
}
else if(corr_type==CCL_CORR_GL) {
for (j=2;j<=ell_max;j++) {//https://arxiv.org/pdf/1007.4809.pdf
Pl_theta[j]=gsl_sf_legendre_Plm(j,2,cth);
Pl_theta[j]*=(2*j+1.)/((j+0.)*(j+1.));
}
}
}
/*--------ROUTINE: ccl_tracer_corr_legendre ------
TASK: Compute correlation function via Legendre polynomials
INPUT: cosmology, number of theta bins, theta array, tracer 1, tracer 2, i_bessel, boolean
for tapering, vector of tapering limits, correlation vector, angular_cl function.
*/
static void ccl_tracer_corr_legendre(ccl_cosmology *cosmo,
int n_ell,double *ell,double *cls,
int n_theta,double *theta,double *wtheta,
int corr_type,int do_taper_cl,double *taper_cl_limits,
int *status)
{
int i;
double *l_arr,*cl_arr,*Pl_theta;
SplPar *cl_spl;
if(corr_type==CCL_CORR_LM || corr_type==CCL_CORR_LP){
*status=CCL_ERROR_NOT_IMPLEMENTED;
ccl_cosmology_set_status_message(cosmo, "ccl_correlation.c: CCL does not support full-sky xi+- calcuations.\nhttps://arxiv.org/abs/1702.05301 indicates flat-sky to be sufficient.\n");
}
if(*status==0) {
l_arr=malloc(((int)(ccl_splines->ELL_MAX_CORR)+1)*sizeof(double));
if(l_arr==NULL) {
*status=CCL_ERROR_MEMORY;
ccl_cosmology_set_status_message(cosmo, "ccl_correlation.c: ccl_tracer_corr_legendre ran out of memory\n");
}
}
if(*status==0) {
cl_arr=malloc(((int)(ccl_splines->ELL_MAX_CORR)+1)*sizeof(double));
if(cl_arr==NULL) {
*status=CCL_ERROR_MEMORY;
ccl_cosmology_set_status_message(cosmo, "ccl_correlation.c: ccl_tracer_corr_legendre ran out of memory\n");
}
}
if(*status==0) {
//Interpolate input Cl into
cl_spl=ccl_spline_init(n_ell,ell,cls,cls[0],0);
if(cl_spl==NULL) {
*status=CCL_ERROR_MEMORY;
ccl_cosmology_set_status_message(cosmo, "ccl_correlation.c: ccl_tracer_corr_legendre ran out of memory\n");
}
}
if(*status==0) {
double cl_tilt,l_edge,cl_edge;
l_edge=ell[n_ell-1];
if((cls[n_ell-1]*cls[n_ell-2]<0) || (cls[n_ell-2]==0)) {
cl_tilt=0;
cl_edge=0;
}
else {
cl_tilt=log(cls[n_ell-1]/cls[n_ell-2])/log(ell[n_ell-1]/ell[n_ell-2]);
cl_edge=cls[n_ell-1];
}
for(i=0;i<=(int)(ccl_splines->ELL_MAX_CORR);i++) {
double l=(double)i;
l_arr[i]=l;
if(l>=l_edge)
cl_arr[i]=cl_edge*pow(l/l_edge,cl_tilt);
else
cl_arr[i]=ccl_spline_eval(l,cl_spl);
}
ccl_spline_free(cl_spl);
if (do_taper_cl)
*status=taper_cl((int)(ccl_splines->ELL_MAX_CORR)+1,l_arr,cl_arr,taper_cl_limits);
}
if(*status==0) {
Pl_theta=malloc(sizeof(double)*((int)(ccl_splines->ELL_MAX_CORR)+1));
if(Pl_theta==NULL) {
*status=CCL_ERROR_MEMORY;
ccl_cosmology_set_status_message(cosmo, "ccl_correlation.c: ccl_tracer_corr_legendre ran out of memory\n");
}
}
if(*status==0) {
for (int i=0;i<n_theta;i++) {
wtheta[i]=0;
ccl_compute_legendre_polynomial(corr_type,theta[i],(int)(ccl_splines->ELL_MAX_CORR),Pl_theta);
for(int i_L=1;i_L<(int)(ccl_splines->ELL_MAX_CORR);i_L+=1)
wtheta[i]+=cl_arr[i_L]*Pl_theta[i_L];
wtheta[i]/=(M_PI*4);
}
}
free(Pl_theta);
free(l_arr);
free(cl_arr);
}
/*--------ROUTINE: ccl_tracer_corr ------
TASK: For a given tracer, get the correlation function. Do so by running
ccl_angular_cls. If you already have Cls calculated, go to the next
function to pass them directly.
INPUT: cosmology, number of theta values to evaluate = NL, theta vector,
tracer 1, tracer 2, i_bessel, key for tapering, limits of tapering
correlation function.
*/
void ccl_correlation(ccl_cosmology *cosmo,
int n_ell,double *ell,double *cls,
int n_theta,double *theta,double *wtheta,
int corr_type,int do_taper_cl,double *taper_cl_limits,int flag_method,
int *status)
{
switch(flag_method) {
case CCL_CORR_FFTLOG :
ccl_tracer_corr_fftlog(cosmo,n_ell,ell,cls,n_theta,theta,wtheta,corr_type,
do_taper_cl,taper_cl_limits,status);
break;
case CCL_CORR_LGNDRE :
ccl_tracer_corr_legendre(cosmo,n_ell,ell,cls,n_theta,theta,wtheta,corr_type,
do_taper_cl,taper_cl_limits,status);
break;
case CCL_CORR_BESSEL :
ccl_tracer_corr_bessel(cosmo,n_ell,ell,cls,n_theta,theta,wtheta,corr_type,status);
break;
default :
*status=CCL_ERROR_INCONSISTENT;
ccl_cosmology_set_status_message(cosmo, "ccl_correlation.c: ccl_correlation. Unknown algorithm\n");
}
ccl_check_status(cosmo,status);
}
/*--------ROUTINE: ccl_correlation_3d ------
TASK: Calculate the 3d-correlation function. Do so by using FFTLog.
INPUT: cosmology, scale factor a,
number of r values, r values,
key for tapering, limits of tapering
Correlation function result will be in array xi
*/
void ccl_correlation_3d(ccl_cosmology *cosmo, double a,
int n_r,double *r,double *xi,
int do_taper_pk,double *taper_pk_limits,
int *status)
{
int i,N_ARR;
double *k_arr,*pk_arr,*r_arr,*xi_arr;
//number of data points for k and pk array
N_ARR=(int)(ccl_splines->N_K_3DCOR*log10(ccl_splines->K_MAX/ccl_splines->K_MIN));
k_arr=ccl_log_spacing(ccl_splines->K_MIN,ccl_splines->K_MAX,N_ARR);
if(k_arr==NULL) {
*status=CCL_ERROR_MEMORY;
ccl_cosmology_set_status_message(cosmo, "ccl_correlation.c: ccl_correlation_3d ran out of memory\n");
return;
}
pk_arr=malloc(N_ARR*sizeof(double));
if(pk_arr==NULL) {
free(k_arr);
*status=CCL_ERROR_MEMORY;
ccl_cosmology_set_status_message(cosmo, "ccl_correlation.c: ccl_correlation_3d ran out of memory\n");
return;
}
for (i=0; i<N_ARR; i++)
pk_arr[i] = ccl_nonlin_matter_power(cosmo, k_arr[i], a, status);
if (do_taper_pk)
taper_cl(N_ARR,k_arr,pk_arr,taper_pk_limits);
r_arr=malloc(sizeof(double)*N_ARR);
if(r_arr==NULL) {
free(k_arr);
free(pk_arr);
*status=CCL_ERROR_MEMORY;
ccl_cosmology_set_status_message(cosmo, "ccl_correlation.c: ccl_correlation_3d ran out of memory\n");
return;
}
xi_arr=malloc(sizeof(double)*N_ARR);
if(xi_arr==NULL) {
free(k_arr); free(pk_arr); free(r_arr);
*status=CCL_ERROR_MEMORY;
ccl_cosmology_set_status_message(cosmo, "ccl_correlation.c: ccl_correlation_3d ran out of memory\n");
return;
}
for(i=0;i<N_ARR;i++)
r_arr[i]=0;
pk2xi(N_ARR,k_arr,pk_arr,r_arr,xi_arr);
// Interpolate to output values of r
SplPar *xi_spl=ccl_spline_init(N_ARR,r_arr,xi_arr,xi_arr[0],0);
for(i=0;i<n_r;i++)
xi[i]=ccl_spline_eval(r[i],xi_spl);
ccl_spline_free(xi_spl);
free(k_arr); free(pk_arr);
free(r_arr); free(xi_arr);
ccl_check_status(cosmo,status);
return;
}
| {
"alphanum_fraction": 0.6846980864,
"avg_line_length": 29.9979716024,
"ext": "c",
"hexsha": "1c035d945e9da4381fd339d1b7cdec032c2f788f",
"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": "b3bd184b516212b51bdf7ceacab70b2b7afeffb3",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "vrastil/CCL",
"max_forks_repo_path": "src/ccl_correlation.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "b3bd184b516212b51bdf7ceacab70b2b7afeffb3",
"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": "vrastil/CCL",
"max_issues_repo_path": "src/ccl_correlation.c",
"max_line_length": 187,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "b3bd184b516212b51bdf7ceacab70b2b7afeffb3",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "vrastil/CCL",
"max_stars_repo_path": "src/ccl_correlation.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 4826,
"size": 14789
} |
#ifndef GENERIC_API_NAMESPACE
#error "Wrong usage of this header"
#endif
#ifndef GENERIC_API_ROUTINES_NAMESPACE
#error "Wrong usage of this header"
#endif
#define ROUTINES_NAMESPACE namespace GENERIC_API_ROUTINES_NAMESPACE
#define BLAS_NAMESPACE namespace GENERIC_API_NAMESPACE
#ifndef GENERIC_API_DEFINE
namespace cl
{
namespace routines
{
ROUTINES_NAMESPACE
{
template<MathDomain md>
static void Add(MemoryBuffer&, const MemoryBuffer&, const MemoryBuffer&, const double)
{
throw NotImplementedException();
}
template<MathDomain md>
static void AddEqual(MemoryBuffer&, const MemoryBuffer&, const double)
{
throw NotImplementedException();
}
template<MathDomain md>
static void AddEqualMatrix(MemoryTile&, const MemoryTile&, const MatrixOperation, const MatrixOperation, const double, const double)
{
throw NotImplementedException();
}
template<MathDomain md>
static void Scale(MemoryBuffer&, const double)
{
throw NotImplementedException();
}
template<MathDomain md>
static void ScaleColumns(MemoryTile&, const MemoryBuffer&)
{
throw NotImplementedException();
}
template<MathDomain md>
static void ElementwiseProduct(MemoryBuffer&, const MemoryBuffer&, const MemoryBuffer&, const double)
{
throw NotImplementedException();
}
template<MathDomain md>
static void SubMultiply(MemoryTile&, const MemoryTile&, const MemoryTile&, const unsigned, const unsigned, const unsigned, const MatrixOperation, const MatrixOperation, const double, const double)
{
throw NotImplementedException();
}
template<MathDomain md>
static void BatchedMultiply(MemoryCube&, const MemoryCube&, const MemoryCube&, const unsigned, const unsigned, const MatrixOperation, const MatrixOperation, const double, const double)
{
throw NotImplementedException();
}
template<MathDomain md>
static void Dot(MemoryBuffer&, const MemoryTile&, const MemoryBuffer&, const MatrixOperation, const double, const double)
{
throw NotImplementedException();
}
template<MathDomain md>
static void KroneckerProduct(MemoryTile&, const MemoryBuffer&, const MemoryBuffer&, const double)
{
throw NotImplementedException();
}
template<MathDomain md>
static void Solve(const MemoryTile&, MemoryTile&, const MatrixOperation, const LinearSystemSolverType)
{
throw NotImplementedException();
}
template<MathDomain md>
static void ArgAbsMin(int&, const MemoryBuffer&)
{
throw NotImplementedException();
}
template<MathDomain md>
static void ColumnWiseArgAbsMin(MemoryBuffer&, const MemoryTile&)
{
throw NotImplementedException();
}
template<MathDomain md>
static void ArgAbsMax(int&, const MemoryBuffer&)
{
throw NotImplementedException();
}
template<MathDomain md>
static void ColumnWiseArgAbsMax(MemoryBuffer&, const MemoryTile&)
{
throw NotImplementedException();
}
// norm = ||x||_2
template<MathDomain md>
static void EuclideanNorm(double&, const MemoryBuffer&)
{
throw NotImplementedException();
}
}
} // namespace routines
} // namespace cl
#else
#include <cmath>
#include <complex>
BLAS_NAMESPACE
{
#include <cblas.h>
#include <lapacke.h>
}
namespace cl
{
namespace routines
{
ROUTINES_NAMESPACE
{
static constexpr GENERIC_API_NAMESPACE::CBLAS_ORDER columnMajorLayout = { GENERIC_API_NAMESPACE::CBLAS_ORDER::CblasColMajor };
static constexpr std::array<GENERIC_API_NAMESPACE::CBLAS_TRANSPOSE, 2> operationsEnum = { GENERIC_API_NAMESPACE::CBLAS_TRANSPOSE::CblasNoTrans, GENERIC_API_NAMESPACE::CBLAS_TRANSPOSE::CblasTrans };
template<MathDomain md>
static void Add(MemoryBuffer & z, const MemoryBuffer& x, const MemoryBuffer& y, const double alpha);
template<>
inline void Add<MathDomain::Float>(MemoryBuffer & z, const MemoryBuffer& x, const MemoryBuffer& y, const double alpha)
{
Copy<MathDomain::Float>(z, y);
GENERIC_API_NAMESPACE::cblas_saxpy(static_cast<int>(z.size), static_cast<float>(alpha), reinterpret_cast<float*>(x.pointer), 1, reinterpret_cast<float*>(z.pointer), 1);
}
template<>
inline void Add<MathDomain::Double>(MemoryBuffer & z, const MemoryBuffer& x, const MemoryBuffer& y, const double alpha)
{
Copy<MathDomain::Double>(z, y);
GENERIC_API_NAMESPACE::cblas_daxpy(static_cast<int>(z.size), alpha, reinterpret_cast<double*>(x.pointer), 1, reinterpret_cast<double*>(z.pointer), 1);
}
template<MathDomain md>
static void AddEqual(MemoryBuffer & z, const MemoryBuffer& x, const double alpha);
template<>
inline void AddEqual<MathDomain::Float>(MemoryBuffer & z, const MemoryBuffer& x, const double alpha)
{
GENERIC_API_NAMESPACE::cblas_saxpy(static_cast<int>(z.size), static_cast<float>(alpha), reinterpret_cast<float*>(x.pointer), 1, reinterpret_cast<float*>(z.pointer), 1);
}
template<>
inline void AddEqual<MathDomain::Double>(MemoryBuffer & z, const MemoryBuffer& x, const double alpha)
{
GENERIC_API_NAMESPACE::cblas_daxpy(static_cast<int>(z.size), alpha, reinterpret_cast<double*>(x.pointer), 1, reinterpret_cast<double*>(z.pointer), 1);
}
template<MathDomain md>
static void AddEqualMatrix(MemoryTile & A, const MemoryTile& B, const MatrixOperation aOperation, const MatrixOperation bOperation, const double alpha, const double beta);
template<>
inline void AddEqualMatrix<MathDomain::Float>(MemoryTile & A, const MemoryTile& B, const MatrixOperation aOperation, const MatrixOperation bOperation, const double alpha, const double beta)
{
if (aOperation != MatrixOperation::None)
throw NotImplementedException();
if (bOperation != MatrixOperation::None)
throw NotImplementedException();
GENERIC_API_NAMESPACE::cblas_sgeadd(columnMajorLayout, static_cast<int>(A.nRows), static_cast<int>(A.nCols), static_cast<float>(beta), reinterpret_cast<float*>(B.pointer), static_cast<int>(B.leadingDimension), static_cast<float>(alpha), reinterpret_cast<float*>(A.pointer), static_cast<int>(A.leadingDimension));
}
template<>
inline void AddEqualMatrix<MathDomain::Double>(MemoryTile & A, const MemoryTile& B, const MatrixOperation aOperation, const MatrixOperation bOperation, const double alpha, const double beta)
{
if (aOperation != MatrixOperation::None)
throw NotImplementedException();
if (bOperation != MatrixOperation::None)
throw NotImplementedException();
GENERIC_API_NAMESPACE::cblas_dgeadd(columnMajorLayout, static_cast<int>(A.nRows), static_cast<int>(A.nCols), beta, reinterpret_cast<double*>(B.pointer), static_cast<int>(B.leadingDimension), alpha, reinterpret_cast<double*>(A.pointer), static_cast<int>(A.leadingDimension));
}
template<MathDomain md>
static void Scale(MemoryBuffer & z, const double alpha);
template<>
inline void Scale<MathDomain::Float>(MemoryBuffer & z, const double alpha)
{
GENERIC_API_NAMESPACE::cblas_sscal(static_cast<int>(z.size), static_cast<float>(alpha), reinterpret_cast<float*>(z.pointer), 1);
}
template<>
inline void Scale<MathDomain::Double>(MemoryBuffer & z, const double alpha)
{
GENERIC_API_NAMESPACE::cblas_dscal(static_cast<int>(z.size), alpha, reinterpret_cast<double*>(z.pointer), 1);
}
template<MathDomain md>
static void ScaleColumns(MemoryTile & z, const MemoryBuffer& alpha);
template<>
inline void ScaleColumns<MathDomain::Float>(MemoryTile & z, const MemoryBuffer& alpha)
{
for (size_t i = 0; i < z.nCols; ++i)
GENERIC_API_NAMESPACE::cblas_sscal(static_cast<int>(z.nRows), *reinterpret_cast<float*>(alpha.pointer + i * alpha.ElementarySize()), reinterpret_cast<float*>(z.pointer + i * z.nRows * z.ElementarySize()), 1);
}
template<>
inline void ScaleColumns<MathDomain::Double>(MemoryTile & z, const MemoryBuffer& alpha)
{
for (size_t i = 0; i < z.nCols; ++i)
GENERIC_API_NAMESPACE::cblas_dscal(static_cast<int>(z.nRows), *reinterpret_cast<double*>(alpha.pointer + i * alpha.ElementarySize()), reinterpret_cast<double*>(z.pointer + i * z.nRows * z.ElementarySize()), 1);
}
template<MathDomain md>
static void SubMultiply(MemoryTile & A, const MemoryTile& B, const MemoryTile& C, const unsigned nRowsB, const unsigned nColsB, const unsigned nColsC, const MatrixOperation bOperation, const MatrixOperation cOperation, const double alpha, const double beta);
template<>
inline void SubMultiply<MathDomain::Float>(MemoryTile & A, const MemoryTile& B, const MemoryTile& C, const unsigned nRowsB, const unsigned nColsB, const unsigned nColsC, const MatrixOperation bOperation, const MatrixOperation cOperation, const double alpha, const double beta)
{
GENERIC_API_NAMESPACE::cblas_sgemm(columnMajorLayout, operationsEnum[static_cast<unsigned>(bOperation)], operationsEnum[static_cast<unsigned>(cOperation)], static_cast<int>(nRowsB), static_cast<int>(nColsC), static_cast<int>(nColsB), static_cast<float>(alpha), reinterpret_cast<float*>(B.pointer), static_cast<int>(B.leadingDimension), reinterpret_cast<float*>(C.pointer), static_cast<int>(C.leadingDimension), static_cast<float>(beta), reinterpret_cast<float*>(A.pointer), static_cast<int>(A.leadingDimension));
}
template<>
inline void SubMultiply<MathDomain::Double>(MemoryTile & A, const MemoryTile& B, const MemoryTile& C, const unsigned nRowsB, const unsigned nColsB, const unsigned nColsC, const MatrixOperation bOperation, const MatrixOperation cOperation, const double alpha, const double beta)
{
GENERIC_API_NAMESPACE::cblas_dgemm(columnMajorLayout, operationsEnum[static_cast<unsigned>(bOperation)], operationsEnum[static_cast<unsigned>(cOperation)], static_cast<int>(nRowsB), static_cast<int>(nColsC), static_cast<int>(nColsB), alpha, reinterpret_cast<double*>(B.pointer), static_cast<int>(B.leadingDimension), reinterpret_cast<double*>(C.pointer), static_cast<int>(C.leadingDimension), beta, reinterpret_cast<double*>(A.pointer), static_cast<int>(A.leadingDimension));
}
template<MathDomain md>
static void Dot(MemoryBuffer & y, const MemoryTile& A, const MemoryBuffer& x, const MatrixOperation aOperation, const double alpha = 1.0, const double beta = 0.0);
template<>
inline void Dot<MathDomain::Float>(MemoryBuffer & y, const MemoryTile& A, const MemoryBuffer& x, const MatrixOperation aOperation, const double alpha, const double beta)
{
GENERIC_API_NAMESPACE::cblas_sgemv(columnMajorLayout, operationsEnum[static_cast<unsigned>(aOperation)], static_cast<int>(A.nRows), static_cast<int>(A.nCols), static_cast<float>(alpha), reinterpret_cast<float*>(A.pointer), static_cast<int>(A.leadingDimension), reinterpret_cast<float*>(x.pointer), 1, static_cast<float>(beta), reinterpret_cast<float*>(y.pointer), 1);
}
template<>
inline void Dot<MathDomain::Double>(MemoryBuffer & y, const MemoryTile& A, const MemoryBuffer& x, const MatrixOperation aOperation, const double alpha, const double beta)
{
GENERIC_API_NAMESPACE::cblas_dgemv(columnMajorLayout, operationsEnum[static_cast<unsigned>(aOperation)], static_cast<int>(A.nRows), static_cast<int>(A.nCols), alpha, reinterpret_cast<double*>(A.pointer), static_cast<int>(A.leadingDimension), reinterpret_cast<double*>(x.pointer), 1, beta, reinterpret_cast<double*>(y.pointer), 1);
}
template<MathDomain md>
static void KroneckerProduct(MemoryTile & A, const MemoryBuffer& x, const MemoryBuffer& y, const double alpha);
template<>
inline void KroneckerProduct<MathDomain::Float>(MemoryTile & A, const MemoryBuffer& x, const MemoryBuffer& y, const double alpha)
{
GENERIC_API_NAMESPACE::cblas_sger(columnMajorLayout, static_cast<int>(x.size), static_cast<int>(y.size), static_cast<float>(alpha), reinterpret_cast<float*>(x.pointer), 1, reinterpret_cast<float*>(y.pointer), 1, reinterpret_cast<float*>(A.pointer), static_cast<int>(A.nRows));
}
template<>
inline void KroneckerProduct<MathDomain::Double>(MemoryTile & A, const MemoryBuffer& x, const MemoryBuffer& y, const double alpha)
{
GENERIC_API_NAMESPACE::cblas_dger(columnMajorLayout, static_cast<int>(x.size), static_cast<int>(y.size), alpha, reinterpret_cast<double*>(x.pointer), 1, reinterpret_cast<double*>(y.pointer), 1, reinterpret_cast<double*>(A.pointer), static_cast<int>(A.nRows));
}
template<MathDomain md>
static void Solve(const MemoryTile& A, MemoryTile& B, const MatrixOperation aOperation, const LinearSystemSolverType solver);
template<>
inline void Solve<MathDomain::Float>(const MemoryTile& A, MemoryTile& B, const MatrixOperation aOperation, const LinearSystemSolverType solver)
{
// Need to copy A, as it will be overwritten by its factorization
MemoryTile aCopy(A);
Alloc(aCopy);
Copy<MathDomain::Float>(aCopy, A);
const auto nra = static_cast<int>(A.nRows);
const auto lda = static_cast<int>(A.leadingDimension);
const auto ncb = static_cast<int>(B.nCols);
const auto ldb = static_cast<int>(B.leadingDimension);
// Initializes auxliary value for solver
int info = 0;
switch (solver)
{
case LinearSystemSolverType::Lu:
{
// allocate memory for pivoting
MemoryBuffer pivot(0, A.nRows, A.memorySpace, MathDomain::Int);
Alloc(pivot);
// Factorize A (and overwrite it with L)
info = GENERIC_API_NAMESPACE::LAPACKE_sgetrf(static_cast<int>(columnMajorLayout), nra, nra, reinterpret_cast<float*>(aCopy.pointer), lda, reinterpret_cast<int*>(pivot.pointer));
if (info != 0)
throw OpenBlasException(__func__);
// Solve factorized system
info = GENERIC_API_NAMESPACE::LAPACKE_sgetrs(static_cast<int>(columnMajorLayout), openBlasOperation[static_cast<unsigned>(aOperation)], nra, ncb, reinterpret_cast<float*>(aCopy.pointer), lda, reinterpret_cast<int*>(pivot.pointer), reinterpret_cast<float*>(B.pointer), ldb);
if (info != 0)
throw OpenBlasException(__func__);
// free memory
Free(pivot);
break;
}
case LinearSystemSolverType::Qr:
{
// allocate memory for tau
MemoryBuffer tau(0, A.nRows, A.memorySpace, MathDomain::Float);
Alloc(tau);
// A = Q * R
/* int matrix_layout, lapack_int m, lapack_int n,
float* a, lapack_int lda, float* tau */
info = GENERIC_API_NAMESPACE::LAPACKE_sgeqrf(static_cast<int>(columnMajorLayout), nra, nra, reinterpret_cast<float*>(aCopy.pointer), lda, reinterpret_cast<float*>(tau.pointer));
if (info != 0)
throw OpenBlasException(__func__);
// B = Q^T * B
/*
* int matrix_layout, char side, char trans,
lapack_int m, lapack_int n, lapack_int k,
const float* a, lapack_int lda, const float* tau,
float* c, lapack_int ldc */
info = GENERIC_API_NAMESPACE::LAPACKE_sormqr(static_cast<int>(columnMajorLayout), 'L', 'T', nra, nra, ncb, reinterpret_cast<float*>(aCopy.pointer), lda, reinterpret_cast<float*>(tau.pointer), reinterpret_cast<float*>(B.pointer), ldb);
if (info != 0)
throw OpenBlasException(__func__);
// Solve (x = R \ (Q^T * B))
GENERIC_API_NAMESPACE::cblas_strsm(columnMajorLayout, GENERIC_API_NAMESPACE::CBLAS_SIDE::CblasLeft, GENERIC_API_NAMESPACE::CBLAS_UPLO::CblasUpper, operationsEnum[static_cast<unsigned>(aOperation)], GENERIC_API_NAMESPACE::CBLAS_DIAG::CblasNonUnit, nra, nra, 1.0, reinterpret_cast<float*>(aCopy.pointer), lda, reinterpret_cast<float*>(B.pointer), ldb);
// free memory
Free(tau);
break;
}
default:
throw NotImplementedException();
}
Free(aCopy);
}
template<>
inline void Solve<MathDomain::Double>(const MemoryTile& A, MemoryTile& B, const MatrixOperation aOperation, const LinearSystemSolverType solver)
{
// Need to copy A, as it will be overwritten by its factorization
MemoryTile aCopy(A);
Alloc(aCopy);
Copy<MathDomain::Double>(aCopy, A);
const auto nra = static_cast<int>(A.nRows);
const auto lda = static_cast<int>(A.leadingDimension);
const auto ncb = static_cast<int>(B.nCols);
const auto ldb = static_cast<int>(B.leadingDimension);
// Initializes auxliary value for solver
int info = 0;
switch (solver)
{
case LinearSystemSolverType::Lu:
{
// allocate memory for pivoting
MemoryBuffer pivot(0, A.nRows, A.memorySpace, MathDomain::Int);
Alloc(pivot);
// Factorize A (and overwrite it with L)
info = GENERIC_API_NAMESPACE::LAPACKE_dgetrf(static_cast<int>(columnMajorLayout), nra, nra, reinterpret_cast<double*>(aCopy.pointer), lda, reinterpret_cast<int*>(pivot.pointer));
if (info != 0)
throw OpenBlasException(__func__);
// Solve factorized system
info = GENERIC_API_NAMESPACE::LAPACKE_dgetrs(static_cast<int>(columnMajorLayout), openBlasOperation[static_cast<unsigned>(aOperation)], nra, ncb, reinterpret_cast<double*>(aCopy.pointer), lda, reinterpret_cast<int*>(pivot.pointer), reinterpret_cast<double*>(B.pointer), ldb);
if (info != 0)
throw OpenBlasException(__func__);
// free memory
Free(pivot);
break;
}
case LinearSystemSolverType::Qr:
{
// allocate memory for tau
MemoryBuffer tau(0, A.nRows, A.memorySpace, MathDomain::Double);
Alloc(tau);
// A = Q * R
/* int matrix_layout, lapack_int m, lapack_int n,
double* a, lapack_int lda, double* tau */
info = GENERIC_API_NAMESPACE::LAPACKE_dgeqrf(static_cast<int>(columnMajorLayout), nra, nra, reinterpret_cast<double*>(aCopy.pointer), lda, reinterpret_cast<double*>(tau.pointer));
if (info != 0)
throw OpenBlasException(__func__);
// B = Q^T * B
/*
* int matrix_layout, char side, char trans,
lapack_int m, lapack_int n, lapack_int k,
const double* a, lapack_int lda, const double* tau,
double* c, lapack_int ldc */
info = GENERIC_API_NAMESPACE::LAPACKE_dormqr(static_cast<int>(columnMajorLayout), 'L', 'T', nra, nra, ncb, reinterpret_cast<double*>(aCopy.pointer), lda, reinterpret_cast<double*>(tau.pointer), reinterpret_cast<double*>(B.pointer), ldb);
if (info != 0)
throw OpenBlasException(__func__);
// Solve (x = R \ (Q^T * B))
cblas_dtrsm(columnMajorLayout, GENERIC_API_NAMESPACE::CBLAS_SIDE::CblasLeft, GENERIC_API_NAMESPACE::CBLAS_UPLO::CblasUpper, operationsEnum[static_cast<unsigned>(aOperation)], GENERIC_API_NAMESPACE::CBLAS_DIAG::CblasNonUnit, nra, nra, 1.0, reinterpret_cast<double*>(aCopy.pointer), lda, reinterpret_cast<double*>(B.pointer), ldb);
// free memory
Free(tau);
break;
}
default:
throw NotImplementedException();
}
Free(aCopy);
}
template<MathDomain md>
static void ArgAbsMin(int& argMin, const MemoryBuffer& x);
template<>
inline void ArgAbsMin<MathDomain::Float>(int&, const MemoryBuffer&)
{
// TODO: apparently there's isamax but not isamin??
// argMin = static_cast<int>(cblas_isamin(static_cast<int>(x.size), reinterpret_cast<float*>(x.pointer), 1));
}
template<>
inline void ArgAbsMin<MathDomain::Double>(int&, const MemoryBuffer&)
{
// TODO: apparently there's isamax but not isamin??
// argMin = static_cast<int>(cblas_idamin(static_cast<int>(x.size), reinterpret_cast<double*>(x.pointer), 1));
}
template<MathDomain md>
static void ColumnWiseArgAbsMin(MemoryBuffer & argMin, const MemoryTile& A);
template<>
inline void ColumnWiseArgAbsMin<MathDomain::Float>(MemoryBuffer&, const MemoryTile&)
{
// TODO
// auto* argMinPtr = reinterpret_cast<int*>(argMin.pointer);
// // 1 added for compatibility
// for (size_t j = 0; j < A.nCols; ++j)
// argMinPtr[j] = 1 + static_cast<int>(cblas_isamin(static_cast<int>(A.nRows), reinterpret_cast<float*>(A.pointer + j * A.nRows * A.ElementarySize()), 1));
}
template<>
inline void ColumnWiseArgAbsMin<MathDomain::Double>(MemoryBuffer&, const MemoryTile&)
{
// TODO
// // 1 added for compatibility
// auto* argMinPtr = reinterpret_cast<int*>(argMin.pointer);
// for (size_t j = 0; j < A.nCols; ++j)
// argMinPtr[j] = 1 + static_cast<int>(cblas_idamin(static_cast<int>(A.nRows), reinterpret_cast<double*>(A.pointer + j * A.nRows * A.ElementarySize()), 1));
}
template<MathDomain md>
static void ArgAbsMax(int& argMax, const MemoryBuffer& x);
template<>
inline void ArgAbsMax<MathDomain::Float>(int& argMax, const MemoryBuffer& x)
{
argMax = static_cast<int>(GENERIC_API_NAMESPACE::cblas_isamax(static_cast<int>(x.size), reinterpret_cast<float*>(x.pointer), 1));
}
template<>
inline void ArgAbsMax<MathDomain::Double>(int& argMax, const MemoryBuffer& x)
{
argMax = static_cast<int>(GENERIC_API_NAMESPACE::cblas_idamax(static_cast<int>(x.size), reinterpret_cast<double*>(x.pointer), 1));
}
template<MathDomain md>
static void ColumnWiseArgAbsMax(MemoryBuffer & argMax, const MemoryTile& A);
template<>
inline void ColumnWiseArgAbsMax<MathDomain::Float>(MemoryBuffer & argMax, const MemoryTile& A)
{
// 1 added for compatibility
auto* argMaxPtr = reinterpret_cast<int*>(argMax.pointer);
for (size_t j = 0; j < A.nCols; ++j)
argMaxPtr[j] = 1 + static_cast<int>(GENERIC_API_NAMESPACE::cblas_isamax(static_cast<int>(A.nRows), reinterpret_cast<float*>(A.pointer + j * A.nRows * A.ElementarySize()), 1));
}
template<>
inline void ColumnWiseArgAbsMax<MathDomain::Double>(MemoryBuffer & argMax, const MemoryTile& A)
{
// 1 added for compatibility
auto* argMaxPtr = reinterpret_cast<int*>(argMax.pointer);
for (size_t j = 0; j < A.nCols; ++j)
argMaxPtr[j] = 1 + static_cast<int>(GENERIC_API_NAMESPACE::cblas_idamax(static_cast<int>(A.nRows), reinterpret_cast<double*>(A.pointer + j * A.nRows * A.ElementarySize()), 1));
}
// norm = ||x||_2
template<MathDomain md>
static void EuclideanNorm(double& norm, const MemoryBuffer& z);
template<>
inline void EuclideanNorm<MathDomain::Float>(double& norm, const MemoryBuffer& z)
{
norm = static_cast<double>(GENERIC_API_NAMESPACE::cblas_snrm2(static_cast<int>(z.size), reinterpret_cast<float*>(z.pointer), 1));
}
template<>
inline void EuclideanNorm<MathDomain::Double>(double& norm, const MemoryBuffer& z)
{
norm = GENERIC_API_NAMESPACE::cblas_dnrm2(static_cast<int>(z.size), reinterpret_cast<double*>(z.pointer), 1);
}
}
} // namespace routines
} // namespace cl
#endif
#undef GENERIC_API_DEFINE
#undef GENERIC_API_NAMESPACE
#undef GENERIC_API_ROUTINES_NAMESPACE
#undef ROUTINES_NAMESPACE
#undef BLAS_NAMESPACE
| {
"alphanum_fraction": 0.7197046284,
"avg_line_length": 43.5842911877,
"ext": "h",
"hexsha": "290a8cdda0fbbec94863989ea5a5983a3dcd14de",
"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": "390efb41da88245b2f5909b84213fb5839d505cf",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "pmontalb/CudaLight",
"max_forks_repo_path": "HostRoutines/GenericBlasApiWrappers.h",
"max_issues_count": 2,
"max_issues_repo_head_hexsha": "390efb41da88245b2f5909b84213fb5839d505cf",
"max_issues_repo_issues_event_max_datetime": "2018-03-13T12:57:46.000Z",
"max_issues_repo_issues_event_min_datetime": "2018-03-04T22:26:42.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "pmontalb/CudaLight",
"max_issues_repo_path": "HostRoutines/GenericBlasApiWrappers.h",
"max_line_length": 516,
"max_stars_count": 2,
"max_stars_repo_head_hexsha": "390efb41da88245b2f5909b84213fb5839d505cf",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "pmontalb/CudaLight",
"max_stars_repo_path": "HostRoutines/GenericBlasApiWrappers.h",
"max_stars_repo_stars_event_max_datetime": "2021-11-30T23:34:21.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-03-25T17:54:50.000Z",
"num_tokens": 5849,
"size": 22751
} |
/*
** ECM - eigenvector centrality mapping using full matrix
**
** G.Lohmann, MPI-KYB, Nov 2018
*/
#include <viaio/Vlib.h>
#include <viaio/VImage.h>
#include <viaio/mu.h>
#include <viaio/option.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_cblas.h>
#include <gsl/gsl_blas.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#ifdef _OPENMP
#include <omp.h>
#endif /*_OPENMP*/
#define SQR(x) ((x) * (x))
/* check if matrix is irreducible.
** If it is not, then Perron-Frobenius theorem does not apply
*/
void CheckReducibility(float *A,size_t nvox)
{
size_t i,j,k,n;
float umin = 99999;
n=0;
for (i=0; i<nvox; i++) {
for (j=0; j<i; j++) {
k=j+i*(i+1)/2;
if (A[k] > 0) n++;
if (A[k] > 0 && A[k] < umin) umin = A[k];
}
for (j=i+1; j<nvox; j++) {
k=i+j*(j+1)/2;
if (A[k] > 0) n++;
}
}
if (n < nvox) {
VWarning(" matrix is not irreducible, correction term is applied.");
for (i=0; i<nvox; i++) {
for (j=0; j<i; j++) {
k=j+i*(i+1)/2;
if (A[k] < umin) A[k] = umin*0.5;
}
}
}
}
/* re-implementation of cblas_sspmv, cblas_sspmv causes problems */
void my_sspmv(float *A,float *x,float *y,size_t n)
{
size_t i,j,k,kk;
float tmp1=0,tmp2=0;
kk = k = 0;
for (j=0; j<n; j++) {
y[j] = 0;
tmp1 = x[j];
tmp2 = 0;
k = kk;
for (i=0; i<j; i++) {
y[i] += tmp1 * A[k];
tmp2 += A[k] * x[i];
k++;
}
y[j] += tmp1*A[kk+j] + tmp2;
kk += (j+1);
}
}
void MatrixPowerIteration(float *A,float *ev,size_t nvox,int maxiter)
{
int i,iter;
float sum,d,nx;
fprintf(stderr," power iteration...\n");
float *y = (float *) VCalloc(nvox,sizeof(float));
nx = (double)nvox;
for (i=0; i<nvox; i++) ev[i] = y[i] = 1.0/nx;
for (iter=0; iter < maxiter; iter++) {
/* y = Ax, A symmetric and lower-triangular */
/* cblas_sspmv(CblasRowMajor,CblasLower,(int)n,1.0f,A,ev,1,1.0f,y,1); */
my_sspmv(A,ev,y,nvox);
/* normalize */
sum = 0;
for (i=0; i<nvox; i++) sum += y[i]*y[i];
sum = sqrt(sum);
/* check convergence */
d = 0;
for (i=0; i<nvox; i++) {
y[i] /= sum;
d += SQR(ev[i] - y[i]);
ev[i] = y[i];
}
fprintf(stderr," %5d %f\n",(int)iter,d);
if (iter > 2 && d < 1.0e-6) break;
}
VFree(y);
}
float CorrMetric(float z,int type)
{
switch (type) {
case 1: /* add */
z += 1.0;
break;
case 2: /* pos */
if (z < 0) z = 0;
break;
case 3: /* abs */
z = fabs(z);
break;
case 4: /* neg */
if (z < 0) z = -z;
else z = 0;
break;
default:
VError("illegal type");
}
return z;
}
double ECMcorrelation(const float *arr1,const float *arr2,size_t nt,int type)
{
size_t i;
double sum=0,z=0,kx=(double)nt;
if ((type > 0 && type < 5) || (type==6)) {
sum=0;
for (i=0; i<nt; i++) {
const double u = (double)arr1[i];
const double v = (double)arr2[i];
sum += u*v;
}
z = sum/kx;
}
switch (type) {
case 0: /* RLC positive */
sum=0;
for (i=0; i<nt; i++) {
const double u = (double)arr1[i];
const double v = (double)arr2[i];
sum += u*v + fabs(u*v);
}
z = sum/(2.0*kx);
break;
case 1: /* add */
z += 1.0;
break;
case 2: /* pos */
if (z < 0) z = 0;
break;
case 3: /* abs */
z = fabs(z);
break;
case 4: /* neg */
if (z < 0) z = -z;
else z = 0;
break;
case 5: /* Gaussian of Euclidean distance */
sum=0;
for (i=0; i<nt; i++) {
const double u = (double)arr1[i];
const double v = (double)arr2[i];
const double d = u-v;
sum += d*d;
}
z = sum/kx;
z = exp(-0.5*z*z);
break;
case 7: /* RLC negative */
sum=0;
for (i=0; i<nt; i++) {
const double u = (double)arr1[i];
const double v = (double)arr2[i];
sum += (fabs(u*v) - u*v);
}
z = sum/(2.0*kx);
break;
default:
;
}
return z;
}
void VMatrixECM(gsl_matrix_float *X,float *ev,int type,int maxiter,VImage map)
{
size_t i,j;
size_t nvox = X->size1;
size_t nt = X->size2;
/* compute similarity matrix */
size_t m = (nvox*(nvox+1))/2;
float *A = (float *) calloc(m,sizeof(float));
if (!A) VError(" err allocating correlation matrix (too big)");
memset(A,0,m*sizeof(float));
size_t progress=0;
#pragma omp parallel for shared(progress) private(j) schedule(guided) firstprivate(X,A)
for (i=0; i<nvox; i++) {
if (i%1000 == 0) fprintf(stderr," %d000 of %lu\r",(int)(++progress),nvox);
const float *arr1 = gsl_matrix_float_const_ptr(X,i,0);
for (j=0; j<=i; j++) {
if (i == j) continue;
const float *arr2 = gsl_matrix_float_const_ptr(X,j,0);
const double v = ECMcorrelation(arr1,arr2,nt,type);
const size_t k=j+i*(i+1)/2;
A[k] = v;
}
}
fprintf(stderr,"\n");
/* CheckReducibility(A,nvox); */
/* DMN(map,A,nvox); */
/* power iteration */
MatrixPowerIteration(A,ev,nvox,maxiter);
VFree(A);
}
| {
"alphanum_fraction": 0.5194117647,
"avg_line_length": 19.391634981,
"ext": "c",
"hexsha": "aee001b22e26a05b192b46bf5833fc254bb77274",
"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/nets/vecm/MatrixECM.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/nets/vecm/MatrixECM.c",
"max_line_length": 87,
"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/nets/vecm/MatrixECM.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": 1857,
"size": 5100
} |
#pragma once
#include <vector>
#include <gsl/gsl>
#include <atlcomcli.h>
using gsl::span;
namespace gfx {
/*
Defines the file formats supported by the imaging functions.
*/
enum class ImageFileFormat {
BMP,
JPEG,
TGA,
FNTART,
IMG,
Unknown
};
struct ImageFileInfo {
ImageFileFormat format = ImageFileFormat::Unknown;
int width = 0;
int height = 0;
bool hasAlpha = false;
};
/*
Tries to detect the image format of the given data by
inspecting the header only.
*/
ImageFileInfo DetectImageFormat(span<uint8_t> data);
bool DetectTga(span<uint8_t> data, ImageFileInfo &info);
std::unique_ptr<uint8_t[]> DecodeTga(span<uint8_t> data);
/*
Specifies the pixel format of the uncompressed data
when encoding or decoding a JPEG image.
*/
enum class JpegPixelFormat {
RGB,
BGR,
RGBX,
BGRX,
XBGR,
XRGB
};
/*
Encodes a JPEG image in memory and returns the compressed data.
pitch is the size in pixels of a line of the uncompressed data.
quality is an integer between 1 and 100.
*/
std::vector<uint8_t> EncodeJpeg(const uint8_t* imageData,
JpegPixelFormat imageDataFormat,
int width,
int height,
int quality,
int pitch);
struct DecodedImage {
std::unique_ptr<uint8_t[]> data;
ImageFileInfo info;
};
DecodedImage DecodeFontArt(const span<uint8_t> data);
DecodedImage DecodeImage(const span<uint8_t> data);
DecodedImage DecodeCombinedImage(const std::string &filename, span<uint8_t> data);
HCURSOR LoadImageToCursor(const span<uint8_t> data, uint32_t hotspotX, uint32_t hotspotY);
}
| {
"alphanum_fraction": 0.6583526682,
"avg_line_length": 21.55,
"ext": "h",
"hexsha": "2c0f0f7a4f56242302f9ec102ce0001ba096c400",
"lang": "C",
"max_forks_count": 25,
"max_forks_repo_forks_event_max_datetime": "2021-11-15T23:14:51.000Z",
"max_forks_repo_forks_event_min_datetime": "2016-02-04T21:19:53.000Z",
"max_forks_repo_head_hexsha": "f0e552289822fea908f16daa379fa568b1bd286d",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "edoipi/TemplePlus",
"max_forks_repo_path": "Infrastructure/include/infrastructure/images.h",
"max_issues_count": 457,
"max_issues_repo_head_hexsha": "f0e552289822fea908f16daa379fa568b1bd286d",
"max_issues_repo_issues_event_max_datetime": "2022-03-31T02:19:10.000Z",
"max_issues_repo_issues_event_min_datetime": "2015-05-01T22:07:45.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "edoipi/TemplePlus",
"max_issues_repo_path": "Infrastructure/include/infrastructure/images.h",
"max_line_length": 91,
"max_stars_count": 69,
"max_stars_repo_head_hexsha": "f0e552289822fea908f16daa379fa568b1bd286d",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "edoipi/TemplePlus",
"max_stars_repo_path": "Infrastructure/include/infrastructure/images.h",
"max_stars_repo_stars_event_max_datetime": "2022-02-15T06:13:04.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-05-05T14:09:25.000Z",
"num_tokens": 443,
"size": 1724
} |
//
// C++ Interface: %{MODULE}
//
// Description:
//
//
// Author: %{AUTHOR} <%{EMAIL}>, (C) %{YEAR}
//
// Copyright: See COPYING file that comes with this distribution
//
//
#ifndef STK_BasicVector_h
#define STK_BasicVector_h
#include "common.h"
#include "Error.h"
#include <cstddef>
#include <cstdlib>
#include <stdexcept>
#include <iostream>
#ifdef HAVE_ATLAS
extern "C"{
#ifdef USE_MKL
#include "mkl.h"
#else
#include <cblas.h>
#include <atlas/clapack.h>
#endif
}
#endif
namespace STK
{
template<typename _ElemT> class BasicVector;
template<typename _ElemT> class Matrix;
// we need to declare the friend << operator here
template<typename _ElemT>
std::ostream & operator << (std::ostream & out, BasicVector<_ElemT> & m);
/** **************************************************************************
** **************************************************************************
* @brief Provides a matrix abstraction class
*
* This class provides a way to work with matrices in STK.
* It encapsulates basic operations and memory optimizations.
*
*/
template<typename _ElemT>
class BasicVector
{
public:
BasicVector(): mpData(NULL)
#ifdef STK_MEMALIGN_MANUAL
,mpFreeData(NULL)
#endif
, mLength(0)
{}
/**
* @brief Copy constructor
* @param rV
*/
BasicVector(const BasicVector<_ElemT>& rV);
BasicVector(const size_t s);
BasicVector(const _ElemT* pData, const size_t s);
~BasicVector();
void
Init(size_t length);
/**
* @brief Dealocates the window from memory and resets the dimensions to (0)
*/
void
Destroy();
/**
* @brief Returns @c true if vector is initialized
*/
const bool
IsInitialized() const
{ return mpData != NULL; }
/**
* @brief Sets all elements to 0
*/
void
Clear();
const size_t
Length() const
{ return mLength; }
/**
* @brief Returns size of matrix in memory (in bytes)
*/
const size_t
MSize() const
{
return (mLength + (((16 / sizeof(_ElemT)) - mLength%(16 / sizeof(_ElemT)))
% (16 / sizeof(_ElemT)))) * sizeof(_ElemT);
}
/**
* @brief Gives access to the vector memory area
* @return pointer to the first field
*/
_ElemT*
pData() const
{ return mpData; }
/**
* @brief Gives access to the vector memory area
* @return pointer to the first field
*/
const _ElemT* const
cpData() const
{ return mpData; }
/**
* @brief Gives access to a specified vector element without range check
* @return pointer to the first field of the row
*/
_ElemT&
operator [] (size_t i) const
{ return *(mpData + i);}
//########################################################################
//########################################################################
BasicVector<_ElemT>&
AddCVMul(const _ElemT c, const BasicVector<_ElemT>& rV);
BasicVector<_ElemT>&
AddCVMul(const _ElemT c, const _ElemT* pV);
BasicVector<_ElemT>&
AddCVVDotMul(const _ElemT c, const _ElemT* pA, const size_t nA,
const _ElemT* pB, const size_t nB);
/// this = this + c * rM * rV
BasicVector<_ElemT>&
AddCMVMul(const _ElemT c, const Matrix<_ElemT>& rM,
const BasicVector<_ElemT>& rV);
/// this = this + c * rM * pV
BasicVector<_ElemT>&
AddCMVMul(const _ElemT c, const Matrix<_ElemT>& rM,
const _ElemT* pV);
/// this = this + c * rM * rV
BasicVector<_ElemT>&
AddCMtVMul(const _ElemT c, const Matrix<_ElemT>& rM,
const BasicVector<_ElemT>& rV);
/// this = this + c * rM * rV
BasicVector<_ElemT>&
AddCMtVMul(const _ElemT c, const Matrix<_ElemT>& rM,
const _ElemT* pV);
/// Adds a diagonal after Matrix-Matrix Multiplication
BasicVector<_ElemT>&
AddDiagCMMMul(const _ElemT c, const Matrix<_ElemT>& rMa,
const Matrix<_ElemT>& rMb);
_ElemT
Dot(const BasicVector<_ElemT>& rV);
_ElemT
Dot(const _ElemT* pV);
/// Performs a row stack of the matrix rMa
BasicVector<_ElemT>&
MatrixRowStack(const Matrix<_ElemT>& rMa);
/// Returns sum of the elements
_ElemT
Sum() const;
/// Returns sum of the elements
BasicVector<_ElemT>&
AddRowSum(const Matrix<_ElemT>& rM);
/// Returns sum of the elements
BasicVector<_ElemT>&
AddColSum(const Matrix<_ElemT>& rM);
/// Returns log(sum(exp())) without exp overflow
_ElemT
LogSumExp() const;
//########################################################################
//########################################################################
friend std::ostream &
operator << <> (
std::ostream& rOut,
BasicVector<_ElemT>& rV);
//operator _ElemT* ()
//{
// return mpData;
//}
//##########################################################################
//##########################################################################
//protected:
public:
/// data memory area
_ElemT* mpData;
#ifdef STK_MEMALIGN_MANUAL
/// data to be freed (in case of manual memalignment use, see common.h)
_ElemT* mpFreeData;
#endif
size_t mLength; ///< Number of elements
}; // class BasicVector
}; // namespace STK
//*****************************************************************************
//*****************************************************************************
// we need to include the implementation
#include "BasicVector.tcc"
//*****************************************************************************
//*****************************************************************************
/******************************************************************************
******************************************************************************
* The following section contains specialized template definitions
* whose implementation is in BasicVector.cc
*/
namespace STK
{
template<>
BasicVector<float>&
BasicVector<float>::
AddCVMul(const float c, const BasicVector<float>& rV);
template<>
BasicVector<double>&
BasicVector<double>::
AddCVMul(const double c, const BasicVector<double>& rV);
template<>
BasicVector<float>&
BasicVector<float>::
AddCVMul(const float c, const float* pV);
template<>
BasicVector<double>&
BasicVector<double>::
AddCVMul(const double c, const double* pV);
template<>
BasicVector<float>&
BasicVector<float>::
AddCMVMul(const float c, const Matrix<float>& rV, const BasicVector<float>& rV2);
template<>
BasicVector<double>&
BasicVector<double>::
AddCMVMul(const double c, const Matrix<double>& rV, const BasicVector<double>& rV2);
template<>
BasicVector<float>&
BasicVector<float>::
AddCMtVMul(const float c, const Matrix<float>& rV, const BasicVector<float>& rV2);
template<>
BasicVector<double>&
BasicVector<double>::
AddCMtVMul(const double c, const Matrix<double>& rV, const BasicVector<double>& rV2);
template<>
BasicVector<float>&
BasicVector<float>::
AddCMtVMul(const float c, const Matrix<float>& rV, const float* pV);
template<>
BasicVector<double>&
BasicVector<double>::
AddCMtVMul(const double c, const Matrix<double>& rV, const double* pV);
template<>
float
BasicVector<float>::
Dot(const float* pV);
template<>
double
BasicVector<double>::
Dot(const double* pV);
} // namespace STK
#endif // #ifndef STK_BasicVector_h
| {
"alphanum_fraction": 0.4838596491,
"avg_line_length": 27.0569620253,
"ext": "h",
"hexsha": "25cdfc4937829ec2557ec849c3cbce4ce2611d8a",
"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": "0381dcb95d9482c36a24d95af16155da9c12f43d",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "troylee/nnet-asr",
"max_forks_repo_path": "src/STKLib/trunk/src/STKLib/BasicVector.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "0381dcb95d9482c36a24d95af16155da9c12f43d",
"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": "troylee/nnet-asr",
"max_issues_repo_path": "src/STKLib/trunk/src/STKLib/BasicVector.h",
"max_line_length": 90,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "0381dcb95d9482c36a24d95af16155da9c12f43d",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "troylee/nnet-asr",
"max_stars_repo_path": "src/STKLib/trunk/src/STKLib/BasicVector.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1944,
"size": 8550
} |
/**
*
* @file core_stsmlq_sytra1.c
*
* PLASMA core_blas kernel
* PLASMA is a software package provided by Univ. of Tennessee,
* Univ. of California Berkeley and Univ. of Colorado Denver
*
* @version 2.6.0
* @author Hatem Ltaief
* @author Mathieu Faverge
* @author Azzam Haidar
* @date 2010-11-15
* @generated s Tue Jan 7 11:44:48 2014
*
**/
#include <lapacke.h>
#include "common.h"
#undef COMPLEX
#define REAL
/***************************************************************************//**
*
* @ingroup CORE_float
*
* CORE_stsmlq_sytra1: see CORE_stsmlq
*
* This kernel applies a Right transformation on | A1' A2 |
* and does not handle the transpose of A1.
* Needs therefore to make the explicit transpose of A1 before
* and after the application of the block of reflectors
* Can be further optimized by changing accordingly the underneath
* kernel ztsrfb!
*
*******************************************************************************
*
* @param[in] side
* @arg PlasmaLeft : apply Q or Q**T from the Left;
* @arg PlasmaRight : apply Q or Q**T from the Right.
*
* @param[in] trans
* @arg PlasmaNoTrans : No transpose, apply Q;
* @arg PlasmaTrans : ConjTranspose, apply Q**T.
*
* @param[in] m1
* The number of rows of the tile A1. m1 >= 0.
*
* @param[in] n1
* The number of columns of the tile A1. n1 >= 0.
*
* @param[in] m2
* The number of rows of the tile A2. m2 >= 0.
* m2 = m1 if side == PlasmaRight.
*
* @param[in] n2
* The number of columns of the tile A2. n2 >= 0.
* n2 = n1 if side == PlasmaLeft.
*
* @param[in] k
* The number of elementary reflectors whose product defines
* the matrix Q.
*
* @param[in] ib
* The inner-blocking size. ib >= 0.
*
* @param[in,out] A1
* On entry, the m1-by-n1 tile A1.
* On exit, A1 is overwritten by the application of Q.
*
* @param[in] lda1
* The leading dimension of the array A1. lda1 >= max(1,m1).
*
* @param[in,out] A2
* On entry, the m2-by-n2 tile A2.
* On exit, A2 is overwritten by the application of Q.
*
* @param[in] lda2
* The leading dimension of the tile A2. lda2 >= max(1,m2).
*
* @param[in] V
* The i-th row must contain the vector which defines the
* elementary reflector H(i), for i = 1,2,...,k, as returned by
* CORE_STSLQT in the first k rows of its array argument V.
*!
* @param[in] ldv
* The leading dimension of the array V. ldv >= max(1,K).
*
* @param[in] T
* The IB-by-n1 triangular factor T of the block reflector.
* T is upper triangular by block (economic storage);
* The rest of the array is not referenced.
*
* @param[in] ldt
* The leading dimension of the array T. ldt >= IB.
*
* @param[out] WORK
* Workspace array of size
* LDWORK-by-m1 if side == PlasmaLeft
* LDWORK-by-IB if side == PlasmaRight
*
* @param[in] ldwork
* The leading dimension of the array WORK.
* LDWORK >= max(1,IB) if side == PlasmaLeft
* LDWORK >= max(1,n1) if side == PlasmaRight
*
*******************************************************************************
*
* @return
* \retval PLASMA_SUCCESS successful exit
* \retval <0 if -i, the i-th argument had an illegal value
*
******************************************************************************/
#if defined(PLASMA_HAVE_WEAK)
#pragma weak CORE_stsmlq_sytra1 = PCORE_stsmlq_sytra1
#define CORE_stsmlq_sytra1 PCORE_stsmlq_sytra1
#define CORE_stsmlq PCORE_stsmlq
int CORE_stsmlq(PLASMA_enum side, PLASMA_enum trans,
int m1, int n1, int m2, int n2, int K, int IB,
float *A1, int lda1,
float *A2, int lda2,
const float *V, int ldv,
const float *T, int ldt,
float *WORK, int LDWORK);
#endif
int CORE_stsmlq_sytra1( PLASMA_enum side, PLASMA_enum trans,
int m1, int n1, int m2, int n2,
int k, int ib,
float *A1, int lda1,
float *A2, int lda2,
const float *V, int ldv,
const float *T, int ldt,
float *WORK, int ldwork)
{
int i, j;
if ( (m1 != n1) ) {
coreblas_error(3, "Illegal value of M1, N1");
return -3;
}
/* in-place transposition of A1 */
for (j = 0; j < n1; j++){
A1[j + j*lda1] = (A1[j + j*lda1]);
for (i = j+1; i < m1; i++){
*WORK = *(A1 + i + j*lda1);
*(A1 + i + j*lda1) = (*(A1 + j + i*lda1));
*(A1 + j + i*lda1) = (*WORK);
}
}
CORE_stsmlq(side, trans, m1, n1, m2, n2, k, ib,
A1, lda1, A2, lda2,
V, ldv, T, ldt,
WORK, ldwork);
/* in-place transposition of A1 */
for (j = 0; j < n1; j++){
A1[j + j*lda1] = (A1[j + j*lda1]);
for (i = j+1; i < m1; i++){
*WORK = *(A1 + i + j*lda1);
*(A1 + i + j*lda1) = (*(A1 + j + i*lda1));
*(A1 + j + i*lda1) = (*WORK);
}
}
return PLASMA_SUCCESS;
}
| {
"alphanum_fraction": 0.5096009036,
"avg_line_length": 31.2470588235,
"ext": "c",
"hexsha": "4e38895e073f29df549e4c5caf990ead9b02b193",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "zhuangsc/Plasma-ompss1",
"max_forks_repo_path": "core_blas/core_stsmlq_sytra1.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "zhuangsc/Plasma-ompss1",
"max_issues_repo_path": "core_blas/core_stsmlq_sytra1.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/core_stsmlq_sytra1.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1548,
"size": 5312
} |
/**
* @file batch_zdotu_sub.c
*
* Part of API test for Batched BLAS routines.
*
* @author Samuel D. Relton
* @author Pedro V. Lara
* @author Mawussi Zounon
* @date
*
* @precisions normal z -> c d s
*
**/
#include <cblas.h>
#include "bblas.h"
#define COMPLEX
void batch_zdotu_sub(
const int *n,
BBLAS_Complex64_t const * const *x,
const int *incx,
BBLAS_Complex64_t const * const *y,
const int *incy,
BBLAS_Complex64_t *dotu,
const int batch_count, const enum BBLAS_OPTS batch_opts,
int* info)
{
/* Local variables */
int first_index = 0;
char func_name[15] = "batch_zdotu";
/*initialize the result */
for (int batch_iter = 0; batch_iter < batch_count; batch_iter++)
{
dotu[batch_iter] = (BBLAS_Complex64_t)0.0;
}
/* Check input arguments */
if (batch_count < 0)
{
xerbla_batch(func_name, BBLAS_ERR_BATCH_COUNT, -1);
}
if (batch_opts == BBLAS_FIXED)
{
/* Call fixed size code */
batchf_zdotu_sub(
n[first_index],
x,
incx[first_index],
y,
incy[first_index],
dotu,
batch_count, info);
}
else if (batch_opts == BBLAS_VARIABLE)
{
/* Call variable size code */
batchv_zdotu_sub(
n,
x,
incx,
y,
incy,
dotu,
batch_count, info);
}
else
{
xerbla_batch(func_name, BBLAS_ERR_BATCH_OPTS, -1);
}
}
#undef COMPLEX
| {
"alphanum_fraction": 0.595980596,
"avg_line_length": 18.7402597403,
"ext": "c",
"hexsha": "52c2b9161a61afa3a7adb78c1848c5923d4a4d25",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "117f3538b3ab43ade0ad53950ecac25c1a192bc7",
"max_forks_repo_licenses": [
"BSD-2-Clause"
],
"max_forks_repo_name": "sdrelton/bblas_api_test",
"max_forks_repo_path": "src/batch_zdotu.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "117f3538b3ab43ade0ad53950ecac25c1a192bc7",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-2-Clause"
],
"max_issues_repo_name": "sdrelton/bblas_api_test",
"max_issues_repo_path": "src/batch_zdotu.c",
"max_line_length": 65,
"max_stars_count": 3,
"max_stars_repo_head_hexsha": "3df5d3379b73d4716d4850aaa9f04e808d2c850a",
"max_stars_repo_licenses": [
"BSD-2-Clause"
],
"max_stars_repo_name": "mawussi/BBLAS-group",
"max_stars_repo_path": "src/batch_zdotu.c",
"max_stars_repo_stars_event_max_datetime": "2016-08-31T22:24:49.000Z",
"max_stars_repo_stars_event_min_datetime": "2016-08-04T11:59:07.000Z",
"num_tokens": 439,
"size": 1443
} |
#pragma once
#include "random_utils.h"
#include "schedule.h"
#include "schedule_params.h"
#include "stochastic_tunneling.h"
#include "temperature.h"
#include "utils.h"
#include <gsl/gsl-lite.hpp>
namespace angonoka::stun {
/**
How many stochastic tunneling iterations to go through
during each update.
*/
enum class BatchSize : std::int_fast32_t;
/**
A single optimization job, meant to be launched in a thread pool.
Optimizer starts many OptimizerJobs in parallel,
pruning unseccessful jobs as needed.
*/
class OptimizerJob {
public:
/**
OptimizerJob options.
@var params Schedule parameters
@var random Random utils.
*/
struct Options {
gsl::not_null<const ScheduleParams*> params;
gsl::not_null<RandomUtils*> random;
};
/**
Constructor.
@param params Scheduling parameters
@param random_utils Random number generator utilities
@param batch_size Number of iterations per update
*/
OptimizerJob(
const ScheduleParams& params,
RandomUtils& random_utils,
BatchSize batch_size);
OptimizerJob(const Options& options, BatchSize batch_size);
/**
Run stochastic tunneling optimization batch.
Does batch_size number of iterations.
*/
void update() noexcept;
/**
The best schedule so far.
@return A schedule.
*/
[[nodiscard]] Schedule schedule() const;
/**
The best makespan so far.
@return Makespan.
*/
[[nodiscard]] float normalized_makespan() const;
/**
Reset the optimization to initial state.
*/
void reset();
/**
Get current options.
@return Options.
*/
[[nodiscard]] Options options() const;
/**
Set options.
@param options Options.
*/
void options(const Options& options);
OptimizerJob(const OptimizerJob& other);
OptimizerJob(OptimizerJob&& other) noexcept;
OptimizerJob& operator=(const OptimizerJob& other);
OptimizerJob& operator=(OptimizerJob&& other) noexcept;
~OptimizerJob() noexcept;
private:
static constexpr auto beta_scale = 1e-4F;
static constexpr auto stun_window = 10000;
static constexpr auto gamma = .5F;
static constexpr auto restart_period = 1 << 20;
static constexpr auto initial_beta = 1.0F;
int16 batch_size;
Mutator mutator;
Makespan makespan;
Temperature temperature;
StochasticTunneling stun;
};
} // namespace angonoka::stun
| {
"alphanum_fraction": 0.649609375,
"avg_line_length": 23.2727272727,
"ext": "h",
"hexsha": "76efedc98a27329ff3ddc0e55cc6bae36160dbdf",
"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/stun/optimizer_job.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/stun/optimizer_job.h",
"max_line_length": 69,
"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/stun/optimizer_job.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": 566,
"size": 2560
} |
/* CLM (Music V) implementation */
#include <mus-config.h>
#if USE_SND
#include "snd.h"
#endif
#include <stddef.h>
#include <math.h>
#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
#if (defined(HAVE_LIBC_H) && (!defined(HAVE_UNISTD_H)))
#include <libc.h>
#else
#ifndef _MSC_VER
#include <unistd.h>
#endif
#endif
#include "_sndlib.h"
#include "clm.h"
#include "clm-strings.h"
#define clm_malloc(Num, What) malloc(Num)
#define clm_calloc(Num, Size, What) calloc(Num, Size)
#define clm_realloc(Old, NewSize) realloc(Old, NewSize)
#define clm_free(Ptr) free(Ptr)
#if HAVE_GSL
#include <gsl/gsl_complex.h>
#include <gsl/gsl_complex_math.h>
#endif
#if HAVE_FFTW3
#include <fftw3.h>
#endif
#if HAVE_COMPLEX_TRIG
#include <complex.h>
#endif
#ifndef TWO_PI
#define TWO_PI (2.0 * M_PI)
#endif
#if defined(__GNUC__) && (__GNUC__ >= 3)
#define MUS_EXPECT __builtin_expect
#else
#define MUS_EXPECT(_expr, _value) (_expr)
#endif
#define MUS_LIKELY(_expr) MUS_EXPECT((_expr), 1)
#define MUS_UNLIKELY(_expr) MUS_EXPECT((_expr), 0)
#if (!HAVE_MEMMOVE)
static void *memmove (char *dest, const char *source, unsigned int length)
{ /* from libit */
char *d0 = dest;
if (source < dest)
/* Moving from low mem to hi mem; start at end. */
for (source += length, dest += length; length; --length)
*--dest = *--source;
else
if (source != dest)
{
/* Moving from hi mem to low mem; start at beginning. */
for (; length; --length)
*dest++ = *source++;
}
return((void *)d0);
}
#endif
enum {MUS_OSCIL, MUS_NCOS, MUS_DELAY, MUS_COMB, MUS_NOTCH, MUS_ALL_PASS,
MUS_TABLE_LOOKUP, MUS_SQUARE_WAVE, MUS_SAWTOOTH_WAVE, MUS_TRIANGLE_WAVE, MUS_PULSE_TRAIN,
MUS_RAND, MUS_RAND_INTERP, MUS_ASYMMETRIC_FM, MUS_ONE_ZERO, MUS_ONE_POLE, MUS_TWO_ZERO, MUS_TWO_POLE, MUS_FORMANT,
MUS_SRC, MUS_GRANULATE, MUS_WAVE_TRAIN,
MUS_FILTER, MUS_FIR_FILTER, MUS_IIR_FILTER, MUS_CONVOLVE, MUS_ENV, MUS_LOCSIG,
MUS_FRAME, MUS_READIN, MUS_FILE_TO_SAMPLE, MUS_FILE_TO_FRAME,
MUS_SAMPLE_TO_FILE, MUS_FRAME_TO_FILE, MUS_MIXER, MUS_PHASE_VOCODER,
MUS_MOVING_AVERAGE, MUS_NSIN, MUS_SSB_AM, MUS_POLYSHAPE, MUS_FILTERED_COMB,
MUS_MOVE_SOUND, MUS_NRXYSIN, MUS_NRXYCOS, MUS_POLYWAVE, MUS_FIRMANT,
MUS_INITIAL_GEN_TAG};
static const char *interp_name[] = {"step", "linear", "sinusoidal", "all-pass", "lagrange", "bezier", "hermite"};
static const char *interp_type_to_string(int type)
{
if (mus_interp_type_p(type))
return(interp_name[type]);
return("unknown");
}
static int mus_class_tag = MUS_INITIAL_GEN_TAG;
int mus_make_class_tag(void) {return(mus_class_tag++);}
static mus_float_t sampling_rate = MUS_DEFAULT_SAMPLING_RATE;
static mus_float_t w_rate = (TWO_PI / MUS_DEFAULT_SAMPLING_RATE);
static mus_float_t float_equal_fudge_factor = 0.0000001;
mus_float_t mus_float_equal_fudge_factor(void) {return(float_equal_fudge_factor);}
mus_float_t mus_set_float_equal_fudge_factor(mus_float_t val)
{
mus_float_t prev;
prev = float_equal_fudge_factor;
float_equal_fudge_factor = val;
return(prev);
}
static int array_print_length = MUS_DEFAULT_ARRAY_PRINT_LENGTH;
int mus_array_print_length(void) {return(array_print_length);}
int mus_set_array_print_length(int val)
{
int prev;
prev = array_print_length;
if (val >= 0) array_print_length = val;
return(prev);
}
static mus_long_t clm_file_buffer_size = MUS_DEFAULT_FILE_BUFFER_SIZE;
mus_long_t mus_file_buffer_size(void) {return(clm_file_buffer_size);}
mus_long_t mus_set_file_buffer_size(mus_long_t size)
{
/* this is set in with-sound, among other places */
mus_long_t prev;
prev = clm_file_buffer_size;
clm_file_buffer_size = size;
return(prev);
}
mus_float_t mus_radians_to_hz(mus_float_t rads) {return(rads / w_rate);}
mus_float_t mus_hz_to_radians(mus_float_t hz) {return(hz * w_rate);}
mus_float_t mus_degrees_to_radians(mus_float_t degree) {return(degree * TWO_PI / 360.0);}
mus_float_t mus_radians_to_degrees(mus_float_t rads) {return(rads * 360.0 / TWO_PI);}
mus_float_t mus_db_to_linear(mus_float_t x) {return(pow(10.0, x / 20.0));}
mus_float_t mus_linear_to_db(mus_float_t x) {if (x > 0.0) return(20.0 * log10(x)); return(-100.0);}
mus_float_t mus_srate(void) {return(sampling_rate);}
mus_float_t mus_set_srate(mus_float_t val)
{
mus_float_t prev;
prev = sampling_rate;
if (val > 0.0)
{
sampling_rate = val;
w_rate = (TWO_PI / sampling_rate);
}
return(prev);
}
mus_long_t mus_seconds_to_samples(mus_float_t secs) {return((mus_long_t)(secs * sampling_rate));}
mus_float_t mus_samples_to_seconds(mus_long_t samps) {return((mus_float_t)((double)samps / (double)sampling_rate));}
#define DESCRIBE_BUFFER_SIZE 2048
#define STR_SIZE 128
static char *float_array_to_string(mus_float_t *arr, int len, int loc)
{
#define MAX_NUM_SIZE 32
char *base, *str;
int i, lim, k, size = 256;
if (arr == NULL)
{
str = (char *)clm_calloc(4, sizeof(char), "float_array_to_string");
sprintf(str, "nil");
return(str);
}
lim = (array_print_length + 4) * MAX_NUM_SIZE; /* 4 for possible bounds below */
if (lim > size) size = lim;
if (loc < 0) loc = 0;
base = (char *)clm_calloc(size, sizeof(char), "float_array_to_string");
str = (char *)clm_calloc(STR_SIZE, sizeof(char), "float_array_to_string");
if (len > 0)
{
sprintf(base, "[");
lim = len;
if (lim > array_print_length) lim = array_print_length;
k = loc;
if (k >= len) k = 0;
for (i = 0; i < lim - 1; i++)
{
mus_snprintf(str, STR_SIZE, "%.3f ", arr[k]);
strcat(base, str);
if ((int)(strlen(base) + MAX_NUM_SIZE) > size)
{
base = (char *)clm_realloc(base, size * 2 * sizeof(char));
base[size] = 0;
size *= 2;
}
k++;
if (k >= len) k = 0;
}
mus_snprintf(str, STR_SIZE, "%.3f%s", arr[k], (len > lim) ? "..." : "]");
strcat(base, str);
}
else sprintf(base, "[]");
if (len > lim)
{
/* print ranges */
int min_loc = 0, max_loc = 0;
mus_float_t min_val, max_val;
min_val = arr[0];
max_val = arr[0];
for (i = 1; i < len; i++)
{
if (arr[i] < min_val) {min_val = arr[i]; min_loc = i;}
if (arr[i] > max_val) {max_val = arr[i]; max_loc = i;}
}
mus_snprintf(str, STR_SIZE, "(%d: %.3f, %d: %.3f)]", min_loc, min_val, max_loc, max_val);
strcat(base, str);
}
clm_free(str);
return(base);
}
static char *clm_array_to_string(mus_any **gens, int num_gens, const char *name, const char *indent)
{
char *descr = NULL;
if ((gens) && (num_gens > 0))
{
int i, len = 0;
char **descrs;
descrs = (char **)clm_calloc(num_gens, sizeof(char *), "clm_array_to_string");
for (i = 0; i < num_gens; i++)
{
if (gens[i])
{
char *str = NULL;
descrs[i] = mus_format("\n%s[%d]: %s", indent, i, str = mus_describe(gens[i]));
if (str) clm_free(str);
}
else descrs[i] = mus_format("\n%s[%d]: nil", indent, i);
len += strlen(descrs[i]);
}
len += (64 + strlen(name));
descr = (char *)clm_calloc(len, sizeof(char), "clm_array_to_string");
mus_snprintf(descr, len, "%s[%d]:", name, num_gens);
for (i = 0; i < num_gens; i++)
{
strcat(descr, descrs[i]);
clm_free(descrs[i]);
}
clm_free(descrs);
}
else
{
descr = (char *)clm_calloc(128, sizeof(char), "clm_array_to_string");
mus_snprintf(descr, 128, "%s: nil", name);
}
return(descr);
}
static char *int_array_to_string(int *arr, int num_ints, const char *name)
{
#define MAX_INT_SIZE 32
char *descr = NULL;
if ((arr) && (num_ints > 0))
{
int i, len;
char *intstr;
len = num_ints * MAX_INT_SIZE + 64;
descr = (char *)clm_calloc(len, sizeof(char), "clm_int_array_to_string");
intstr = (char *)clm_calloc(MAX_INT_SIZE, sizeof(char), "clm_int_array_to_string");
mus_snprintf(descr, len, "%s[%d]: (", name, num_ints);
for (i = 0; i < num_ints - 1; i++)
{
mus_snprintf(intstr, MAX_INT_SIZE, "%d ", arr[i]);
strcat(descr, intstr);
}
mus_snprintf(intstr, MAX_INT_SIZE, "%d)", arr[num_ints - 1]);
strcat(descr, intstr);
clm_free(intstr);
}
else
{
descr = (char *)clm_calloc(128, sizeof(char), "clm_int_array_to_string");
mus_snprintf(descr, 128, "%s: nil", name);
}
return(descr);
}
/* ---------------- generic functions ---------------- */
static bool check_gen(mus_any *ptr, const char *name)
{
if (ptr == NULL)
{
mus_error(MUS_NO_GEN, "null generator passed to %s", name);
return(false);
}
return(true);
}
const char *mus_name(mus_any *ptr)
{
if (ptr == NULL)
return("null");
return(ptr->core->name);
}
const char *mus_set_name(mus_any *ptr, const char *new_name)
{
/* an experiment -- to change the name, we need to make a local copy of the mus_any_class struct */
/* eventually we could use this to specialize built-in methods and so on */
if (check_gen(ptr, S_mus_name))
{
if (ptr->core->original_class)
{
if (ptr->core->name) free(ptr->core->name);
ptr->core->name = mus_strdup(new_name);
}
else
{
mus_any_class *tmp;
tmp = ptr->core;
ptr->core = (mus_any_class *)clm_calloc(1, sizeof(mus_any_class), "mus_set_name");
memcpy((void *)(ptr->core), (void *)tmp, sizeof(mus_any_class));
ptr->core->name = mus_strdup(new_name);
ptr->core->original_class = (void *)tmp;
}
}
return(new_name);
}
/* add_method: in clm2xen always include mus_xen wrapper as environ (as currently for vct-func cases)
* this is currently handled through closure and set_closure (locally) -- needs gen struct field for the pointer
* add-method of degenerator could just prepend -- wouldn't assoc ignore the later case?
* add_method(ptr, name, func) then copies if original as above, resets ptr to xen_func
* also adds func to gen property list
* func itself takes ptr, gets mus_xen via environ, finds func in property list and calls
* to refer to (hidden) gen fields, we'd need a way to tell it to use the original_class ptr's funcs
* call-next-method? this would need the current ptr, the current class ptr etc
*/
int mus_free(mus_any *gen)
{
if ((check_gen(gen, "mus-free")) &&
(gen->core->release))
{
int release_result = 0;
mus_any_class *local_class = NULL;
if (gen->core->original_class)
local_class = (mus_any_class *)(gen->core);
release_result = ((*(gen->core->release))(gen));
if (local_class)
clm_free(local_class);
return(release_result);
}
return(mus_error(MUS_NO_FREE, "can't free %s", mus_name(gen)));
}
char *mus_describe(mus_any *gen)
{
if (gen == NULL)
return(mus_strdup((char *)"null"));
if ((gen->core) && (gen->core->describe))
return((*(gen->core->describe))(gen));
else mus_error(MUS_NO_DESCRIBE, "can't describe %s", mus_name(gen));
return(NULL);
}
bool mus_equalp(mus_any *p1, mus_any *p2)
{
if ((p1) && (p2))
{
if ((p1->core)->equalp)
return((*((p1->core)->equalp))(p1, p2));
else return(p1 == p2);
}
return(true); /* (eq nil nil) */
}
void mus_reset(mus_any *gen)
{
if ((check_gen(gen, S_mus_reset)) &&
(gen->core->reset))
(*(gen->core->reset))(gen);
else mus_error(MUS_NO_RESET, "can't reset %s", mus_name(gen));
}
mus_float_t mus_frequency(mus_any *gen)
{
if ((check_gen(gen, S_mus_frequency)) &&
(gen->core->frequency))
return((*(gen->core->frequency))(gen));
return((mus_float_t)mus_error(MUS_NO_FREQUENCY, "can't get %s's frequency", mus_name(gen)));
}
mus_float_t mus_set_frequency(mus_any *gen, mus_float_t val)
{
if ((check_gen(gen, S_setB S_mus_frequency)) &&
(gen->core->set_frequency))
return((*(gen->core->set_frequency))(gen, val));
return((mus_float_t)mus_error(MUS_NO_FREQUENCY, "can't set %s's frequency", mus_name(gen)));
}
mus_float_t mus_phase(mus_any *gen)
{
if ((check_gen(gen, S_mus_phase)) &&
(gen->core->phase))
return((*(gen->core->phase))(gen));
return((mus_float_t)mus_error(MUS_NO_PHASE, "can't get %s's phase", mus_name(gen)));
}
mus_float_t mus_set_phase(mus_any *gen, mus_float_t val)
{
if ((check_gen(gen, S_setB S_mus_phase)) &&
(gen->core->set_phase))
return((*(gen->core->set_phase))(gen, val));
return((mus_float_t)mus_error(MUS_NO_PHASE, "can't set %s's phase", mus_name(gen)));
}
int mus_safety(mus_any *gen)
{
if ((check_gen(gen, S_mus_safety)) &&
(gen->core->safety))
return((*(gen->core->safety))(gen));
return(mus_error(MUS_NO_SAFETY, "can't get %s's safety", mus_name(gen)));
}
int mus_set_safety(mus_any *gen, int val)
{
if ((check_gen(gen, S_setB S_mus_safety)) &&
(gen->core->set_safety))
return((*(gen->core->set_safety))(gen, val));
return(mus_error(MUS_NO_SAFETY, "can't set %s's safety", mus_name(gen)));
}
mus_float_t mus_scaler(mus_any *gen)
{
if ((check_gen(gen, S_mus_scaler)) &&
(gen->core->scaler))
return((*(gen->core->scaler))(gen));
return((mus_float_t)mus_error(MUS_NO_SCALER, "can't get %s's scaler", mus_name(gen)));
}
mus_float_t mus_set_scaler(mus_any *gen, mus_float_t val)
{
if ((check_gen(gen, S_setB S_mus_scaler)) &&
(gen->core->set_scaler))
return((*(gen->core->set_scaler))(gen, val));
return((mus_float_t)mus_error(MUS_NO_SCALER, "can't set %s's scaler", mus_name(gen)));
}
mus_float_t mus_feedforward(mus_any *gen) /* shares "scaler" */
{
if ((check_gen(gen, S_mus_feedforward)) &&
(gen->core->scaler))
return((*(gen->core->scaler))(gen));
return((mus_float_t)mus_error(MUS_NO_SCALER, "can't get %s's feedforward", mus_name(gen)));
}
mus_float_t mus_set_feedforward(mus_any *gen, mus_float_t val)
{
if ((check_gen(gen, S_setB S_mus_feedforward)) &&
(gen->core->set_scaler))
return((*(gen->core->set_scaler))(gen, val));
return((mus_float_t)mus_error(MUS_NO_SCALER, "can't set %s's feedforward", mus_name(gen)));
}
mus_float_t mus_offset(mus_any *gen)
{
if ((check_gen(gen, S_mus_offset)) &&
(gen->core->offset))
return((*(gen->core->offset))(gen));
return((mus_float_t)mus_error(MUS_NO_OFFSET, "can't get %s's offset", mus_name(gen)));
}
mus_float_t mus_set_offset(mus_any *gen, mus_float_t val)
{
if ((check_gen(gen, S_setB S_mus_offset)) &&
(gen->core->set_offset))
return((*(gen->core->set_offset))(gen, val));
return((mus_float_t)mus_error(MUS_NO_OFFSET, "can't set %s's offset", mus_name(gen)));
}
mus_float_t mus_width(mus_any *gen)
{
if ((check_gen(gen, S_mus_width)) &&
(gen->core->width))
return((*(gen->core->width))(gen));
return((mus_float_t)mus_error(MUS_NO_WIDTH, "can't get %s's width", mus_name(gen)));
}
mus_float_t mus_set_width(mus_any *gen, mus_float_t val)
{
if ((check_gen(gen, S_setB S_mus_width)) &&
(gen->core->set_width))
return((*(gen->core->set_width))(gen, val));
return((mus_float_t)mus_error(MUS_NO_WIDTH, "can't set %s's width", mus_name(gen)));
}
mus_float_t mus_increment(mus_any *gen)
{
if ((check_gen(gen, S_mus_increment)) &&
(gen->core->increment))
return((*(gen->core->increment))(gen));
return((mus_float_t)mus_error(MUS_NO_INCREMENT, "can't get %s's increment", mus_name(gen)));
}
mus_float_t mus_set_increment(mus_any *gen, mus_float_t val)
{
if ((check_gen(gen, S_setB S_mus_increment)) &&
(gen->core->set_increment))
return((*(gen->core->set_increment))(gen, val));
return((mus_float_t)mus_error(MUS_NO_INCREMENT, "can't set %s's increment", mus_name(gen)));
}
mus_float_t mus_feedback(mus_any *gen) /* shares "increment" */
{
if ((check_gen(gen, S_mus_feedback)) &&
(gen->core->increment))
return((*(gen->core->increment))(gen));
return((mus_float_t)mus_error(MUS_NO_INCREMENT, "can't get %s's feedback", mus_name(gen)));
}
mus_float_t mus_set_feedback(mus_any *gen, mus_float_t val)
{
if ((check_gen(gen, S_setB S_mus_feedback)) &&
(gen->core->set_increment))
return((*(gen->core->set_increment))(gen, val));
return((mus_float_t)mus_error(MUS_NO_INCREMENT, "can't set %s's feedback", mus_name(gen)));
}
void *mus_environ(mus_any *gen)
{
if (check_gen(gen, "mus-environ"))
return((*(gen->core->closure))(gen));
return(NULL);
}
void *mus_set_environ(mus_any *gen, void *e)
{
if (check_gen(gen, S_setB "mus-environ"))
return((*(gen->core->set_closure))(gen, e));
return(NULL);
}
mus_float_t mus_run(mus_any *gen, mus_float_t arg1, mus_float_t arg2)
{
if ((check_gen(gen, "mus-run")) &&
(gen->core->run))
return((*(gen->core->run))(gen, arg1, arg2));
return((mus_float_t)mus_error(MUS_NO_RUN, "can't run %s", mus_name(gen)));
}
mus_long_t mus_length(mus_any *gen)
{
if ((check_gen(gen, S_mus_length)) &&
(gen->core->length))
return((*(gen->core->length))(gen));
return(mus_error(MUS_NO_LENGTH, "can't get %s's length", mus_name(gen)));
}
mus_long_t mus_set_length(mus_any *gen, mus_long_t len)
{
if ((check_gen(gen, S_setB S_mus_length)) &&
(gen->core->set_length))
return((*(gen->core->set_length))(gen, len));
return(mus_error(MUS_NO_LENGTH, "can't set %s's length", mus_name(gen)));
}
mus_long_t mus_order(mus_any *gen) /* shares "length", no set */
{
if ((check_gen(gen, S_mus_order)) &&
(gen->core->length))
return((*(gen->core->length))(gen));
return(mus_error(MUS_NO_LENGTH, "can't get %s's order", mus_name(gen)));
}
int mus_channels(mus_any *gen)
{
if ((check_gen(gen, S_mus_channels)) &&
(gen->core->channels))
return((*(gen->core->channels))(gen));
return(mus_error(MUS_NO_CHANNELS, "can't get %s's channels", mus_name(gen)));
}
int mus_interp_type(mus_any *gen) /* shares "channels", no set */
{
if ((check_gen(gen, S_mus_interp_type)) &&
(gen->core->channels))
return((*(gen->core->channels))(gen));
return(mus_error(MUS_NO_CHANNELS, "can't get %s's interp type", mus_name(gen)));
}
int mus_position(mus_any *gen) /* shares "channels", no set, only used in C (snd-env.c) */
{
if ((check_gen(gen, "mus-position")) &&
(gen->core->channels))
return((*(gen->core->channels))(gen));
return(mus_error(MUS_NO_CHANNELS, "can't get %s's position", mus_name(gen)));
}
int mus_channel(mus_any *gen)
{
if ((check_gen(gen, S_mus_channel)) &&
(gen->core->channel))
return(((*gen->core->channel))(gen));
return(mus_error(MUS_NO_CHANNEL, "can't get %s's channel", mus_name(gen)));
}
mus_long_t mus_hop(mus_any *gen)
{
if ((check_gen(gen, S_mus_hop)) &&
(gen->core->hop))
return((*(gen->core->hop))(gen));
return(mus_error(MUS_NO_HOP, "can't get %s's hop value", mus_name(gen)));
}
mus_long_t mus_set_hop(mus_any *gen, mus_long_t len)
{
if ((check_gen(gen, S_setB S_mus_hop)) &&
(gen->core->set_hop))
return((*(gen->core->set_hop))(gen, len));
return(mus_error(MUS_NO_HOP, "can't set %s's hop value", mus_name(gen)));
}
mus_long_t mus_ramp(mus_any *gen)
{
if ((check_gen(gen, S_mus_ramp)) &&
(gen->core->ramp))
return((*(gen->core->ramp))(gen));
return(mus_error(MUS_NO_RAMP, "can't get %s's ramp value", mus_name(gen)));
}
mus_long_t mus_set_ramp(mus_any *gen, mus_long_t len)
{
if ((check_gen(gen, S_setB S_mus_ramp)) &&
(gen->core->set_ramp))
return((*(gen->core->set_ramp))(gen, len));
return(mus_error(MUS_NO_RAMP, "can't set %s's ramp value", mus_name(gen)));
}
mus_float_t *mus_data(mus_any *gen)
{
if ((check_gen(gen, S_mus_data)) &&
(gen->core->data))
return((*(gen->core->data))(gen));
mus_error(MUS_NO_DATA, "can't get %s's data", mus_name(gen));
return(NULL);
}
/* every case that implements the data or set data functions needs to include
* a var-allocated flag, since all such memory has to be handled via vcts
*/
mus_float_t *mus_set_data(mus_any *gen, mus_float_t *new_data)
{
if (check_gen(gen, S_setB S_mus_data))
{
if (gen->core->set_data)
{
(*(gen->core->set_data))(gen, new_data);
return(new_data);
}
else mus_error(MUS_NO_DATA, "can't set %s's data", mus_name(gen));
}
return(new_data);
}
mus_float_t *mus_xcoeffs(mus_any *gen)
{
if ((check_gen(gen, S_mus_xcoeffs)) &&
(gen->core->xcoeffs))
return((*(gen->core->xcoeffs))(gen));
mus_error(MUS_NO_XCOEFFS, "can't get %s's xcoeffs", mus_name(gen));
return(NULL);
}
mus_float_t *mus_ycoeffs(mus_any *gen)
{
if ((check_gen(gen, S_mus_ycoeffs)) &&
(gen->core->ycoeffs))
return((*(gen->core->ycoeffs))(gen));
mus_error(MUS_NO_YCOEFFS, "can't get %s's ycoeffs", mus_name(gen));
return(NULL);
}
mus_float_t mus_xcoeff(mus_any *gen, int index)
{
if ((check_gen(gen, S_mus_xcoeff)) &&
(gen->core->xcoeff))
return((*(gen->core->xcoeff))(gen, index));
return(mus_error(MUS_NO_XCOEFF, "can't get %s's xcoeff[%d] value", mus_name(gen), index));
}
mus_float_t mus_set_xcoeff(mus_any *gen, int index, mus_float_t val)
{
if ((check_gen(gen, S_setB S_mus_xcoeff)) &&
(gen->core->set_xcoeff))
return((*(gen->core->set_xcoeff))(gen, index, val));
return(mus_error(MUS_NO_XCOEFF, "can't set %s's xcoeff[%d] value", mus_name(gen), index));
}
mus_float_t mus_ycoeff(mus_any *gen, int index)
{
if ((check_gen(gen, S_mus_ycoeff)) &&
(gen->core->ycoeff))
return((*(gen->core->ycoeff))(gen, index));
return(mus_error(MUS_NO_YCOEFF, "can't get %s's ycoeff[%d] value", mus_name(gen), index));
}
mus_float_t mus_set_ycoeff(mus_any *gen, int index, mus_float_t val)
{
if ((check_gen(gen, S_setB S_mus_ycoeff)) &&
(gen->core->set_ycoeff))
return((*(gen->core->set_ycoeff))(gen, index, val));
return(mus_error(MUS_NO_YCOEFF, "can't set %s's ycoeff[%d] value", mus_name(gen), index));
}
mus_long_t mus_location(mus_any *gen)
{
if ((check_gen(gen, S_mus_location)) &&
(gen->core->location))
return(((*gen->core->location))(gen));
return((mus_long_t)mus_error(MUS_NO_LOCATION, "can't get %s's location", mus_name(gen)));
}
/* ---------------- AM etc ---------------- */
mus_float_t mus_ring_modulate(mus_float_t sig1, mus_float_t sig2)
{
return(sig1 * sig2);
}
mus_float_t mus_amplitude_modulate(mus_float_t carrier, mus_float_t sig1, mus_float_t sig2)
{
return(sig1 * (carrier + sig2));
}
mus_float_t mus_contrast_enhancement(mus_float_t sig, mus_float_t index)
{
return(sin((sig * M_PI_2) + (index * sin(sig * TWO_PI))));
}
void mus_clear_array(mus_float_t *arr, mus_long_t size)
{
memset((void *)arr, 0, size * sizeof(mus_float_t));
}
bool mus_arrays_are_equal(mus_float_t *arr1, mus_float_t *arr2, mus_float_t fudge, mus_long_t len)
{
mus_long_t i;
if (fudge == 0.0)
{
for (i = 0; i < len; i++)
if (arr1[i] != arr2[i])
return(false);
}
else
{
for (i = 0; i < len; i++)
if (fabs(arr1[i] - arr2[i]) > fudge)
return(false);
}
return(true);
}
static bool clm_arrays_are_equal(mus_float_t *arr1, mus_float_t *arr2, mus_long_t len)
{
return(mus_arrays_are_equal(arr1, arr2, float_equal_fudge_factor, len));
}
mus_float_t mus_dot_product(mus_float_t *data1, mus_float_t *data2, mus_long_t size)
{
mus_long_t i;
mus_float_t sum = 0.0;
for (i = 0; i < size; i++)
sum += (data1[i] * data2[i]);
return(sum);
}
#if HAVE_COMPLEX_TRIG
#if HAVE_FORTH
#include "xen.h"
#endif
complex double mus_edot_product(complex double freq, complex double *data, mus_long_t size)
{
mus_long_t i;
complex double sum = 0.0;
for (i = 0; i < size; i++)
sum += (cexp(i * freq) * data[i]);
return(sum);
}
#endif
mus_float_t mus_polynomial(mus_float_t *coeffs, mus_float_t x, int ncoeffs)
{
double sum;
int i;
if (ncoeffs <= 0) return(0.0);
if (ncoeffs == 1) return(coeffs[0]); /* just a constant term */
sum = coeffs[ncoeffs - 1];
for (i = ncoeffs - 2; i >= 0; i--)
sum = (sum * x) + coeffs[i];
return((mus_float_t)sum);
}
void mus_multiply_arrays(mus_float_t *data, mus_float_t *window, mus_long_t len)
{
mus_long_t i;
for (i = 0; i < len; i++)
data[i] *= window[i];
}
void mus_rectangular_to_polar(mus_float_t *rl, mus_float_t *im, mus_long_t size)
{
mus_long_t i;
for (i = 0; i < size; i++)
{
mus_float_t temp; /* apparently floating underflows (denormals?) in sqrt are bringing us to a halt */
temp = rl[i] * rl[i] + im[i] * im[i];
im[i] = -atan2(im[i], rl[i]); /* "-" here so that clockwise is positive? is this backwards? */
if (temp < .00000001)
rl[i] = 0.0;
else rl[i] = sqrt(temp);
}
}
void mus_rectangular_to_magnitudes(mus_float_t *rl, mus_float_t *im, mus_long_t size)
{
mus_long_t i;
for (i = 0; i < size; i++)
{
mus_float_t temp; /* apparently floating underflows in sqrt are bringing us to a halt */
temp = rl[i] * rl[i] + im[i] * im[i];
if (temp < .00000001)
rl[i] = 0.0;
else rl[i] = sqrt(temp);
}
}
void mus_polar_to_rectangular(mus_float_t *rl, mus_float_t *im, mus_long_t size)
{
mus_long_t i;
for (i = 0; i < size; i++)
{
mus_float_t temp;
temp = rl[i] * sin(-im[i]); /* minus to match sense of rectangular->polar above */
rl[i] *= cos(-im[i]);
im[i] = temp;
}
}
static mus_float_t *array_normalize(mus_float_t *table, mus_long_t table_size)
{
mus_float_t amp = 0.0;
mus_long_t i;
for (i = 0; i < table_size; i++)
if (amp < (fabs(table[i])))
amp = fabs(table[i]);
if ((amp > 0.0) &&
(amp != 1.0))
for (i = 0; i < table_size; i++)
table[i] /= amp;
return(table);
}
/* ---------------- interpolation ---------------- */
mus_float_t mus_array_interp(mus_float_t *wave, mus_float_t phase, mus_long_t size)
{
/* changed 26-Sep-00 to be closer to mus.lisp */
mus_long_t int_part;
mus_float_t frac_part;
if ((phase < 0.0) || (phase > size))
{
/* 28-Mar-01 changed to fmod; I was hoping to avoid this... */
phase = fmod((double)phase, (double)size);
if (phase < 0.0) phase += size;
}
int_part = (mus_long_t)floor(phase);
frac_part = phase - int_part;
if (int_part == size) int_part = 0;
if (frac_part == 0.0)
return(wave[int_part]);
else
{
mus_long_t inx;
inx = int_part + 1;
if (inx >= size) inx = 0;
return(wave[int_part] + (frac_part * (wave[inx] - wave[int_part])));
}
}
static mus_float_t mus_array_all_pass_interp(mus_float_t *wave, mus_float_t phase, mus_long_t size, mus_float_t yn1)
{
/* this is intended for delay lines where you have a stream of values; in table-lookup it can be a mess */
mus_long_t int_part, inx;
mus_float_t frac_part;
if ((phase < 0.0) || (phase > size))
{
phase = fmod((double)phase, (double)size);
if (phase < 0.0) phase += size;
}
int_part = (mus_long_t)floor(phase);
frac_part = phase - int_part;
if (int_part == size) int_part = 0;
inx = int_part + 1;
if (inx >= size) inx -= size;
#if 1
/* from DAFX */
if (frac_part == 0.0)
return(wave[inx] - yn1);
return(wave[int_part] * frac_part + (1.0 - frac_part) * (wave[inx] - yn1));
#else
/* from Perry Cook */
if (frac_part == 0.0)
return(wave[int_part] + wave[inx] - yn1);
else return(wave[int_part] + ((1.0 - frac_part) / (1 + frac_part)) * (wave[inx] - yn1));
#endif
}
static mus_float_t mus_array_lagrange_interp(mus_float_t *wave, mus_float_t x, mus_long_t size)
{
/* Abramovitz and Stegun 25.2.11 -- everyone badmouths this poor formula */
/* x assumed to be in the middle, between second and third vals */
mus_long_t x0, xp1, xm1;
mus_float_t p, pp;
if ((x < 0.0) || (x > size))
{
x = fmod((double)x, (double)size);
if (x < 0.0) x += size;
}
x0 = (mus_long_t)floor(x);
p = x - x0;
if (x0 >= size) x0 -= size;
if (p == 0.0) return(wave[x0]);
xp1 = x0 + 1;
if (xp1 >= size) xp1 -= size;
xm1 = x0 - 1;
if (xm1 < 0) xm1 += size;
pp = p * p;
return((wave[xm1] * 0.5 * (pp - p)) +
(wave[x0] * (1.0 - pp)) +
(wave[xp1] * 0.5 * (p + pp)));
}
static mus_float_t mus_array_hermite_interp(mus_float_t *wave, mus_float_t x, mus_long_t size)
{
/* from James McCartney */
mus_long_t x0, x1, x2, x3;
mus_float_t p, c0, c1, c2, c3, y0, y1, y2, y3;
if ((x < 0.0) || (x > size))
{
x = fmod((double)x, (double)size);
if (x < 0.0) x += size;
}
x1 = (mus_long_t)floor(x);
p = x - x1;
if (x1 == size) x1 = 0;
if (p == 0.0) return(wave[x1]);
x2 = x1 + 1;
if (x2 == size) x2 = 0;
x3 = x2 + 1;
if (x3 == size) x3 = 0;
x0 = x1 - 1;
if (x0 < 0) x0 = size - 1;
y0 = wave[x0];
y1 = wave[x1];
y2 = wave[x2];
y3 = wave[x3];
c0 = y1;
c1 = 0.5 * (y2 - y0);
c3 = 1.5 * (y1 - y2) + 0.5 * (y3 - y0);
c2 = y0 - y1 + c1 - c3;
return(((c3 * p + c2) * p + c1) * p + c0);
}
static mus_float_t mus_array_bezier_interp(mus_float_t *wave, mus_float_t x, mus_long_t size)
{
mus_long_t x0, x1, x2, x3;
mus_float_t p, y0, y1, y2, y3, ay, by, cy;
if ((x < 0.0) || (x > size))
{
x = fmod((double)x, (double)size);
if (x < 0.0) x += size;
}
x1 = (mus_long_t)floor(x);
p = ((x - x1) + 1.0) / 3.0;
if (x1 == size) x1 = 0;
x2 = x1 + 1;
if (x2 == size) x2 = 0;
x3 = x2 + 1;
if (x3 == size) x3 = 0;
x0 = x1 - 1;
if (x0 < 0) x0 = size - 1;
y0 = wave[x0];
y1 = wave[x1];
y2 = wave[x2];
y3 = wave[x3];
cy = 3 * (y1 - y0);
by = 3 * (y2 - y1) - cy;
ay = y3 - y0 - cy - by;
return(y0 + p * (cy + (p * (by + (p * ay)))));
}
bool mus_interp_type_p(int val)
{
/* this is C++'s fault. */
switch (val)
{
case MUS_INTERP_NONE:
case MUS_INTERP_LINEAR:
case MUS_INTERP_SINUSOIDAL:
case MUS_INTERP_LAGRANGE:
case MUS_INTERP_HERMITE:
case MUS_INTERP_ALL_PASS:
case MUS_INTERP_BEZIER:
return(true);
break;
}
return(false);
}
mus_float_t mus_interpolate(mus_interp_t type, mus_float_t x, mus_float_t *table, mus_long_t table_size, mus_float_t y)
{
switch (type)
{
case MUS_INTERP_NONE:
{
mus_long_t x0;
x0 = ((mus_long_t)x) % table_size;
if (x0 < 0) x0 += table_size;
return(table[x0]);
}
break;
case MUS_INTERP_LAGRANGE:
return(mus_array_lagrange_interp(table, x, table_size));
break;
case MUS_INTERP_HERMITE:
return(mus_array_hermite_interp(table, x, table_size));
break;
case MUS_INTERP_LINEAR:
return(mus_array_interp(table, x, table_size));
break;
case MUS_INTERP_ALL_PASS:
return(mus_array_all_pass_interp(table, x, table_size, y));
break;
case MUS_INTERP_BEZIER:
return(mus_array_bezier_interp(table, x, table_size));
break;
default:
mus_error(MUS_ARG_OUT_OF_RANGE, "unknown interpolation type: %d", type);
break;
}
return(0.0);
}
/* ---------------- oscil ---------------- */
typedef struct {
mus_any_class *core;
double phase, freq;
} osc;
mus_float_t mus_oscil(mus_any *ptr, mus_float_t fm, mus_float_t pm)
{
osc *gen = (osc *)ptr;
mus_float_t result;
result = sin(gen->phase + pm);
gen->phase += (gen->freq + fm);
return(result);
}
mus_float_t mus_oscil_unmodulated(mus_any *ptr)
{
osc *gen = (osc *)ptr;
mus_float_t result;
result = sin(gen->phase);
gen->phase += gen->freq;
return(result);
}
mus_float_t mus_oscil_fm(mus_any *ptr, mus_float_t fm)
{
osc *gen = (osc *)ptr;
mus_float_t result;
result = sin(gen->phase);
gen->phase += (gen->freq + fm);
return(result);
}
mus_float_t mus_oscil_pm(mus_any *ptr, mus_float_t pm)
{
mus_float_t result;
osc *gen = (osc *)ptr;
result = sin(gen->phase + pm);
gen->phase += gen->freq;
return(result);
}
bool mus_oscil_p(mus_any *ptr)
{
return((ptr) &&
(ptr->core->type == MUS_OSCIL));
}
static int free_oscil(mus_any *ptr) {if (ptr) clm_free(ptr); return(0);}
static mus_float_t oscil_freq(mus_any *ptr) {return(mus_radians_to_hz(((osc *)ptr)->freq));}
static mus_float_t oscil_set_freq(mus_any *ptr, mus_float_t val) {((osc *)ptr)->freq = mus_hz_to_radians(val); return(val);}
static mus_float_t oscil_increment(mus_any *ptr) {return(((osc *)ptr)->freq);}
static mus_float_t oscil_set_increment(mus_any *ptr, mus_float_t val) {((osc *)ptr)->freq = val; return(val);}
static mus_float_t oscil_phase(mus_any *ptr) {return(fmod(((osc *)ptr)->phase, TWO_PI));}
static mus_float_t oscil_set_phase(mus_any *ptr, mus_float_t val) {((osc *)ptr)->phase = val; return(val);}
static mus_long_t oscil_cosines(mus_any *ptr) {return(1);}
static void oscil_reset(mus_any *ptr) {((osc *)ptr)->phase = 0.0;}
static mus_float_t fallback_scaler(mus_any *ptr) {return(1.0);}
static bool oscil_equalp(mus_any *p1, mus_any *p2)
{
return((p1 == p2) ||
((mus_oscil_p((mus_any *)p1)) &&
(mus_oscil_p((mus_any *)p2)) &&
((((osc *)p1)->freq) == (((osc *)p2)->freq)) &&
((((osc *)p1)->phase) == (((osc *)p2)->phase))));
}
static char *describe_oscil(mus_any *ptr)
{
char *describe_buffer;
describe_buffer = (char *)clm_malloc(DESCRIBE_BUFFER_SIZE, "describe buffer");
mus_snprintf(describe_buffer, DESCRIBE_BUFFER_SIZE, "%s freq: %.3fHz, phase: %.3f",
mus_name(ptr),
mus_frequency(ptr),
mus_phase(ptr));
return(describe_buffer);
}
static mus_any_class OSCIL_CLASS = {
MUS_OSCIL,
(char *)S_oscil, /* the "(char *)" business is for g++'s benefit */
&free_oscil,
&describe_oscil,
&oscil_equalp,
0, 0,
&oscil_cosines, 0,
&oscil_freq,
&oscil_set_freq,
&oscil_phase,
&oscil_set_phase,
&fallback_scaler, 0,
&oscil_increment,
&oscil_set_increment,
&mus_oscil,
MUS_NOT_SPECIAL,
NULL,
0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0,
&oscil_reset,
0, 0, 0
};
mus_any *mus_make_oscil(mus_float_t freq, mus_float_t phase)
{
osc *gen;
gen = (osc *)clm_calloc(1, sizeof(osc), S_make_oscil);
gen->core = &OSCIL_CLASS;
gen->freq = mus_hz_to_radians(freq);
gen->phase = phase;
return((mus_any *)gen);
}
/* decided against feedback-oscil (as in cellon) because it's not clear how to handle the index,
* and there are many options for the filtering -- since this part of the signal path
* is not hidden, there's no reason to bring it out explicitly (as in filtered-comb)
*/
/* ---------------- ncos ---------------- */
typedef struct {
mus_any_class *core;
int n;
double scaler, cos5, phase, freq;
} cosp;
#define DIVISOR_NEAR_ZERO(Den) MUS_UNLIKELY(fabs(Den) < 1.0e-14)
mus_float_t mus_ncos(mus_any *ptr, mus_float_t fm)
{
/* changed 25-Apr-04: use less stupid formula */
/* (/ (- (/ (sin (* (+ n 0.5) angle)) (* 2 (sin (* 0.5 angle)))) 0.5) n) */
double val, den;
cosp *gen = (cosp *)ptr;
den = sin(gen->phase * 0.5);
if (DIVISOR_NEAR_ZERO(den)) /* see note -- this was den == 0.0 1-Aug-07 */
/* perhaps use DBL_EPSILON (1.0e-9 I think) */
val = 1.0;
else
{
val = (gen->scaler * (((sin(gen->phase * gen->cos5)) / (2.0 * den)) - 0.5));
if (val > 1.0) val = 1.0;
/* I think this can't happen now that we check den above, but just in case... */
/* this check is actually incomplete, since we can be much below the correct value also, but the den check should fix those cases too */
}
gen->phase += (gen->freq + fm);
return((mus_float_t)val);
}
/* I think we could add ncos_pm via:
*
* mus_float_t mus_ncos_pm(mus_any *ptr, mus_float_t fm, mus_float_t pm)
* {
* cosp *gen = (cosp *)ptr;
* mus_float_t result;
* gen->phase += pm;
* result = mus_ncos(ptr, fm);
* gen->phase -= pm;
* return(result);
* }
*
* and the same trick could add pm to anything:
*
* mus_float_t mus_run_with_pm(mus_any *ptr, mus_float_t fm, mus_float_t pm)
* {
* mus_float_t result;
* mus_set_phase(ptr, mus_phase(ptr) + pm);
* result = mus_run(ptr, fm, 0.0);
* mus_set_phase (ptr, mus_phase(ptr) - pm);
* return(result);
* }
*
* fm could also be handled here so the 4 cases become gen, mus_run_with_fm|pm|fm_and_pm(gen)
* but... this could just as well happen at the extension language level, except that run doesn't expand macros?
* The problem with differentiating the pm and using the fm arg is that we'd need a closure.
*/
#if 0
/* if the current phase is close to 0.0, there were numerical troubles here:
:(/ (cos (* 1.5 pi 1.0000000000000007)) (cos (* 0.5 pi 1.0000000000000007)))
-3.21167411694788
:(/ (cos (* 1.5 pi 1.0000000000000004)) (cos (* 0.5 pi 1.0000000000000004)))
-2.63292557243357
:(/ (cos (* 1.5 pi 1.0000000000000002)) (cos (* 0.5 pi 1.0000000000000002)))
-1.84007079646018
:(/ (cos (* 1.5 pi 1.0000000000000001)) (cos (* 0.5 pi 1.0000000000000001)))
-3.0
:(/ (cos (* 1.5 pi 1.0000000000000008)) (cos (* 0.5 pi 1.0000000000000008)))
-3.34939116712516
;; 16 bits in is probably too much for doubles
;; these numbers can be hit in normal cases:
(define (ncos-with-inversions n x)
;; Andrews Askey Roy 261
(let* ((num (cos (* x (+ 0.5 n))))
(den (cos (* x 0.5)))
(val (/ num den))) ; Chebyshev polynomial of the 3rd kind! (4th uses sin = our current formula)
(/ (- (if (even? n) val (- val))
0.5)
(+ 1 (* n 2)))))
(with-sound (:scaled-to 1.0)
(do ((i 0 (1+ i))
(x 0.0 (+ x .01)))
((= i 200)) ; glitch at 100 (= 1)
(outa i (ncos-with-inversions 1 (* pi x)) *output*)))
*/
#endif
bool mus_ncos_p(mus_any *ptr)
{
return((ptr) &&
(ptr->core->type == MUS_NCOS));
}
static int free_ncos(mus_any *ptr) {if (ptr) clm_free(ptr); return(0);}
static void ncos_reset(mus_any *ptr) {((cosp *)ptr)->phase = 0.0;}
static mus_float_t ncos_freq(mus_any *ptr) {return(mus_radians_to_hz(((cosp *)ptr)->freq));}
static mus_float_t ncos_set_freq(mus_any *ptr, mus_float_t val) {((cosp *)ptr)->freq = mus_hz_to_radians(val); return(val);}
static mus_float_t ncos_increment(mus_any *ptr) {return(((cosp *)ptr)->freq);}
static mus_float_t ncos_set_increment(mus_any *ptr, mus_float_t val) {((cosp *)ptr)->freq = val; return(val);}
static mus_float_t ncos_phase(mus_any *ptr) {return(fmod(((cosp *)ptr)->phase, TWO_PI));}
static mus_float_t ncos_set_phase(mus_any *ptr, mus_float_t val) {((cosp *)ptr)->phase = val; return(val);}
static mus_float_t ncos_scaler(mus_any *ptr) {return(((cosp *)ptr)->scaler);}
static mus_float_t ncos_set_scaler(mus_any *ptr, mus_float_t val) {((cosp *)ptr)->scaler = val; return(val);}
static mus_long_t ncos_n(mus_any *ptr) {return(((cosp *)ptr)->n);}
static mus_long_t ncos_set_n(mus_any *ptr, mus_long_t val)
{
cosp *gen = (cosp *)ptr;
if (val > 0)
{
gen->n = (int)val;
gen->cos5 = val + 0.5;
gen->scaler = 1.0 / (mus_float_t)val;
}
return(val);
}
static mus_float_t run_ncos(mus_any *ptr, mus_float_t fm, mus_float_t unused) {return(mus_ncos(ptr, fm));}
static bool ncos_equalp(mus_any *p1, mus_any *p2)
{
return((p1 == p2) ||
((mus_ncos_p((mus_any *)p1)) && (mus_ncos_p((mus_any *)p2)) &&
((((cosp *)p1)->freq) == (((cosp *)p2)->freq)) &&
((((cosp *)p1)->phase) == (((cosp *)p2)->phase)) &&
((((cosp *)p1)->n) == (((cosp *)p2)->n)) &&
((((cosp *)p1)->scaler) == (((cosp *)p2)->scaler))));
}
static char *describe_ncos(mus_any *ptr)
{
char *describe_buffer;
describe_buffer = (char *)clm_malloc(DESCRIBE_BUFFER_SIZE, "describe buffer");
mus_snprintf(describe_buffer, DESCRIBE_BUFFER_SIZE, "%s freq: %.3fHz, phase: %.3f, n: %d",
mus_name(ptr),
mus_frequency(ptr),
mus_phase(ptr),
(int)mus_order(ptr));
return(describe_buffer);
}
static mus_any_class NCOS_CLASS = {
MUS_NCOS,
(char *)S_ncos,
&free_ncos,
&describe_ncos,
&ncos_equalp,
0, 0, /* data */
&ncos_n,
&ncos_set_n,
&ncos_freq,
&ncos_set_freq,
&ncos_phase,
&ncos_set_phase,
&ncos_scaler,
&ncos_set_scaler,
&ncos_increment,
&ncos_set_increment,
&run_ncos,
MUS_NOT_SPECIAL,
NULL,
0,
0, 0, 0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0,
&ncos_reset,
0, 0, 0
};
mus_any *mus_make_ncos(mus_float_t freq, int n)
{
cosp *gen;
gen = (cosp *)clm_calloc(1, sizeof(cosp), S_make_ncos);
gen->core = &NCOS_CLASS;
if (n == 0) n = 1;
gen->scaler = 1.0 / (mus_float_t)n;
gen->n = n;
gen->cos5 = n + 0.5;
gen->freq = mus_hz_to_radians(freq);
gen->phase = 0.0;
return((mus_any *)gen);
}
/* ---------------- nsin ---------------- */
static bool nsin_equalp(mus_any *p1, mus_any *p2)
{
return((p1 == p2) ||
((mus_nsin_p((mus_any *)p1)) && (mus_nsin_p((mus_any *)p2)) &&
((((cosp *)p1)->freq) == (((cosp *)p2)->freq)) &&
((((cosp *)p1)->phase) == (((cosp *)p2)->phase)) &&
((((cosp *)p1)->n) == (((cosp *)p2)->n)) &&
((((cosp *)p1)->scaler) == (((cosp *)p2)->scaler))));
}
static char *describe_nsin(mus_any *ptr)
{
char *describe_buffer;
describe_buffer = (char *)clm_malloc(DESCRIBE_BUFFER_SIZE, "describe buffer");
mus_snprintf(describe_buffer, DESCRIBE_BUFFER_SIZE, "%s freq: %.3fHz, phase: %.3f, n: %d",
mus_name(ptr),
mus_frequency(ptr),
mus_phase(ptr),
(int)mus_order(ptr));
return(describe_buffer);
}
bool mus_nsin_p(mus_any *ptr)
{
return((ptr) &&
(ptr->core->type == MUS_NSIN));
}
#if 0
/* its simplest to get the maxes by running an example and recording the maxamp, but it also
* works for small "n" to use the derivative of the sum-of-sines as a Chebyshev polynomial in cos x,
* find its roots, and plug acos(root) into the original, recording the max:
*
(define (smax coeffs)
(let* ((n (vct-length coeffs))
(dcos (make-vct n 1.0)))
(do ((i 0 (1+ i)))
((= i n))
(vct-set! dcos i (* (+ i 1) (vct-ref coeffs i))))
(let ((partials '()))
(do ((i 0 (1+ i)))
((= i n))
(set! partials (append (list (vct-ref dcos i) (+ i 1)) partials)))
(let ((Tn (partials->polynomial (reverse partials))))
(let ((roots (poly-roots Tn)))
(let ((mx (* -2 n)))
(for-each
(lambda (root)
(let ((acr (acos root))
(sum 0.0))
(do ((i 0 (1+ i)))
((= i n))
(set! sum (+ sum (* (vct-ref coeffs i) (sin (* (+ i 1) acr))))))
(if (> (abs sum) mx)
(set! mx (abs sum)))))
roots)
mx))))))
(smax (make-vct n 1.0))
* but that's too much effort for an initialization function.
* much faster is this search (it usually hits an answer in 2 or 3 tries):
*
(define (find-nsin-max n)
(define (ns x n)
(let* ((a2 (/ x 2))
(den (sin a2)))
(if (= den 0.0)
0.0
(/ (* (sin (* n a2)) (sin (* (1+ n) a2))) den))))
(define (find-mid-max n lo hi)
(let ((mid (/ (+ lo hi) 2)))
(let ((ylo (ns lo n))
(yhi (ns hi n)))
(if (< (abs (- ylo yhi)) 1e-100)
(list (ns mid n)
(rationalize (/ mid pi) 0.0))
(if (> ylo yhi)
(find-mid-max n lo mid)
(find-mid-max n mid hi))))))
(find-mid-max n 0.0 (/ pi (+ n .5))))
*
* the 'mid' point has a surprisingly simple relation to pi:
*
* (find-max 100000000000000)
* 7.24518620297426541161857919764185053934850053037407235e13
*
* (find-max 1000000000000000000000000)
* 7.24518620297422918568756794921595308358209723004380140e23 1/1333333333333333333333334 = .75e-24 -> (3*pi)/(4*n)
*
* (find-max 10000000000000000000000000000000000)
* 7.24518620297422918568756432662285195872681453497436666955413707681801083640192066844820049586929551886747925783e33
*
* which is approximately (/ (* 8 (expt (sin (* pi 3/8)) 2)) (* 3 pi)):
* 7.245186202974229185687564326622851596467504
*
* (to get that expression, plug in 3pi/4n, treat (n+1)/n as essentially 1 as n gets very large,
* treat (sin x) as about x when x is very small, and simplify)
* so if n>10, we could use (ns (/ (* 3 pi) (* 4 n)) n) without major error
* It's possible to differentiate the nsin formula:
*
* -(cos(x/2)sin(nx/2)sin((n+1)x/2))/(2sin^2(x/2)) + ncos(nx/2)sin((n+1)x/2)/(2sin(x/2)) + (n+1)sin(nx/2)cos((n+1)x/2)/(2sin(x/2))
*
* and find the 1st 0 when n is very large -- it is very close to 3pi/(4*n)
*/
#endif
static mus_float_t nsin_ns(mus_float_t x, int n)
{
mus_float_t a2, den;
a2 = x / 2;
den = sin(a2);
if (den == 0.0)
return(0.0);
return(sin(n * a2) * sin((n + 1) * a2) / den);
}
static mus_float_t find_nsin_scaler(int n, mus_float_t lo, mus_float_t hi)
{
mus_float_t mid, ylo, yhi;
mid = (lo + hi) / 2;
ylo = nsin_ns(lo, n);
yhi = nsin_ns(hi, n);
if (fabs(ylo - yhi) < 1e-12)
return(nsin_ns(mid, n));
if (ylo > yhi)
return(find_nsin_scaler(n, lo, mid));
return(find_nsin_scaler(n, mid, hi));
}
static mus_float_t nsin_scaler(int n)
{
return(1.0 / find_nsin_scaler(n, 0.0, M_PI / (n + 0.5)));
}
static mus_long_t nsin_set_n(mus_any *ptr, mus_long_t val)
{
cosp *gen = (cosp *)ptr;
gen->n = (int)val;
gen->cos5 = val + 1.0;
gen->scaler = nsin_scaler((int)val);
return(val);
}
mus_float_t mus_nsin(mus_any *ptr, mus_float_t fm)
{
/* (let* ((a2 (* angle 0.5))
(den (sin a2)))
(if (= den 0.0)
0.0
(/ (* (sin (* n a2)) (sin (* (1+ n) a2))) den)))
*/
double val, den, a2;
cosp *gen = (cosp *)ptr;
a2 = gen->phase * 0.5;
den = sin(a2);
if (DIVISOR_NEAR_ZERO(den)) /* see note under ncos */
val = 0.0;
else val = gen->scaler * sin(gen->n * a2) * sin(a2 * gen->cos5) / den;
gen->phase += (gen->freq + fm);
return((mus_float_t)val);
}
static mus_float_t run_nsin(mus_any *ptr, mus_float_t fm, mus_float_t unused) {return(mus_nsin(ptr, fm));}
static mus_any_class NSIN_CLASS = {
MUS_NSIN,
(char *)S_nsin,
&free_ncos,
&describe_nsin,
&nsin_equalp,
0, 0, /* data */
&ncos_n,
&nsin_set_n,
&ncos_freq,
&ncos_set_freq,
&ncos_phase,
&ncos_set_phase,
&ncos_scaler,
&ncos_set_scaler,
&ncos_increment,
&ncos_set_increment,
&run_nsin,
MUS_NOT_SPECIAL,
NULL,
0,
0, 0, 0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0,
&ncos_reset,
0, 0, 0
};
mus_any *mus_make_nsin(mus_float_t freq, int n)
{
cosp *gen;
gen = (cosp *)mus_make_ncos(freq, n);
gen->core = &NSIN_CLASS;
gen->scaler = nsin_scaler(n);
gen->cos5 = gen->n + 1.0;
return((mus_any *)gen);
}
/* ---------------- asymmetric-fm ---------------- */
/* changed from sin(sin) to cos(sin) and added amplitude normalization 6-Sep-07 */
typedef struct {
mus_any_class *core;
mus_float_t r;
double freq, phase;
mus_float_t ratio;
double cosr, sinr;
mus_float_t one;
} asyfm;
static int free_asymmetric_fm(mus_any *ptr) {if (ptr) clm_free(ptr); return(0);}
static void asyfm_reset(mus_any *ptr) {((asyfm *)ptr)->phase = 0.0;}
static mus_float_t asyfm_freq(mus_any *ptr) {return(mus_radians_to_hz(((asyfm *)ptr)->freq));}
static mus_float_t asyfm_set_freq(mus_any *ptr, mus_float_t val) {((asyfm *)ptr)->freq = mus_hz_to_radians(val); return(val);}
static mus_float_t asyfm_increment(mus_any *ptr) {return(((asyfm *)ptr)->freq);}
static mus_float_t asyfm_set_increment(mus_any *ptr, mus_float_t val) {((asyfm *)ptr)->freq = val; return(val);}
static mus_float_t asyfm_phase(mus_any *ptr) {return(fmod(((asyfm *)ptr)->phase, TWO_PI));}
static mus_float_t asyfm_set_phase(mus_any *ptr, mus_float_t val) {((asyfm *)ptr)->phase = val; return(val);}
static mus_float_t asyfm_ratio(mus_any *ptr) {return(((asyfm *)ptr)->ratio);}
static mus_float_t asyfm_r(mus_any *ptr) {return(((asyfm *)ptr)->r);}
static mus_float_t asyfm_set_r(mus_any *ptr, mus_float_t val)
{
asyfm *gen = (asyfm *)ptr;
if (val != 0.0)
{
gen->r = val;
gen->cosr = 0.5 * (val - (1.0 / val));
gen->sinr = 0.5 * (val + (1.0 / val));
if ((val > 1.0) ||
((val < 0.0) && (val > -1.0)))
gen->one = -1.0;
else gen->one = 1.0;
}
return(val);
}
static bool asyfm_equalp(mus_any *p1, mus_any *p2)
{
return((p1 == p2) ||
(((p1->core)->type == (p2->core)->type) &&
((((asyfm *)p1)->freq) == (((asyfm *)p2)->freq)) &&
((((asyfm *)p1)->phase) == (((asyfm *)p2)->phase)) &&
((((asyfm *)p1)->ratio) == (((asyfm *)p2)->ratio)) &&
((((asyfm *)p1)->r) == (((asyfm *)p2)->r))));
}
static char *describe_asyfm(mus_any *ptr)
{
char *describe_buffer;
describe_buffer = (char *)clm_malloc(DESCRIBE_BUFFER_SIZE, "describe buffer");
mus_snprintf(describe_buffer, DESCRIBE_BUFFER_SIZE, "%s freq: %.3fHz, phase: %.3f, ratio: %.3f, r: %.3f",
mus_name(ptr),
mus_frequency(ptr),
mus_phase(ptr),
((asyfm *)ptr)->ratio,
asyfm_r(ptr));
return(describe_buffer);
}
bool mus_asymmetric_fm_p(mus_any *ptr)
{
return((ptr) &&
(ptr->core->type == MUS_ASYMMETRIC_FM));
}
mus_float_t mus_asymmetric_fm(mus_any *ptr, mus_float_t index, mus_float_t fm)
{
asyfm *gen = (asyfm *)ptr;
mus_float_t result;
double mth;
mth = gen->ratio * gen->phase;
result = exp(index * gen->cosr * (gen->one + cos(mth))) * cos(gen->phase + index * gen->sinr * sin(mth));
/* second index factor added 4-Mar-02 and (+/-)1.0 + cos to normalize amps 6-Sep-07 */
gen->phase += (gen->freq + fm);
return(result);
}
mus_float_t mus_asymmetric_fm_unmodulated(mus_any *ptr, mus_float_t index)
{
asyfm *gen = (asyfm *)ptr;
mus_float_t result, mth;
mth = gen->ratio * gen->phase;
result = exp(index * gen->cosr * (gen->one + cos(mth))) * cos(gen->phase + index * gen->sinr * sin(mth));
/* second index factor added 4-Mar-02 */
gen->phase += gen->freq;
return(result);
}
mus_float_t mus_asymmetric_fm_no_input(mus_any *ptr)
{
asyfm *gen = (asyfm *)ptr;
mus_float_t result;
result = sin(gen->phase);
gen->phase += gen->freq;
return(result);
}
static mus_any_class ASYMMETRIC_FM_CLASS = {
MUS_ASYMMETRIC_FM,
(char *)S_asymmetric_fm,
&free_asymmetric_fm,
&describe_asyfm,
&asyfm_equalp,
0, 0, 0, 0,
&asyfm_freq,
&asyfm_set_freq,
&asyfm_phase,
&asyfm_set_phase,
&asyfm_r,
&asyfm_set_r,
&asyfm_increment,
&asyfm_set_increment,
&mus_asymmetric_fm,
MUS_NOT_SPECIAL,
NULL, 0,
&asyfm_ratio,
0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0,
&asyfm_reset,
0, 0, 0
};
mus_any *mus_make_asymmetric_fm(mus_float_t freq, mus_float_t phase, mus_float_t r, mus_float_t ratio) /* r default 1.0, ratio 1.0 */
{
asyfm *gen = NULL;
if (r == 0.0)
mus_error(MUS_ARG_OUT_OF_RANGE, "r can't be 0.0");
else
{
gen = (asyfm *)clm_calloc(1, sizeof(asyfm), S_make_asymmetric_fm);
gen->core = &ASYMMETRIC_FM_CLASS;
gen->freq = mus_hz_to_radians(freq);
gen->phase = phase;
gen->r = r;
gen->ratio = ratio;
gen->cosr = 0.5 * (r - (1.0 / r)); /* 0.5 factor for I/2 */
gen->sinr = 0.5 * (r + (1.0 / r));
if ((r > 1.0) ||
((r < 0.0) && (r > -1.0)))
gen->one = -1.0;
else gen->one = 1.0;
}
return((mus_any *)gen);
}
/*---------------- nrxysin (sine-summation) and nrxycos ---------------- */
/* the generator uses x and y (frequencies), but it's very common to start up with 0 freqs
* and let the fm arg set the frequency, so it seems like we want to give the ratio between
* the frequencies at make time, rather than two (possibly dummy) frequencies).
* xy-ratio negative to build (via r) backwards.
*/
#define MAX_R 0.999999
#define MIN_R -0.999999
typedef struct {
mus_any_class *core;
double freq, phase;
int n;
double norm, r, r_to_n_plus_1, r_squared_plus_1, y_over_x;
} nrxy;
static int free_nrxy(mus_any *ptr) {if (ptr) clm_free(ptr); return(0);}
static void nrxy_reset(mus_any *ptr) {((nrxy *)ptr)->phase = 0.0;}
static mus_float_t nrxy_freq(mus_any *ptr) {return(mus_radians_to_hz(((nrxy *)ptr)->freq));}
static mus_float_t nrxy_set_freq(mus_any *ptr, mus_float_t val) {((nrxy *)ptr)->freq = mus_hz_to_radians(val); return(val);}
static mus_float_t nrxy_increment(mus_any *ptr) {return(((nrxy *)ptr)->freq);}
static mus_float_t nrxy_set_increment(mus_any *ptr, mus_float_t val) {((nrxy *)ptr)->freq = val; return(val);}
static mus_float_t nrxy_phase(mus_any *ptr) {return(fmod(((nrxy *)ptr)->phase, TWO_PI));}
static mus_float_t nrxy_set_phase(mus_any *ptr, mus_float_t val) {((nrxy *)ptr)->phase = val; return(val);}
static mus_long_t nrxy_n(mus_any *ptr) {return((mus_long_t)(((nrxy *)ptr)->n));}
static mus_float_t nrxy_y_over_x(mus_any *ptr) {return(((nrxy *)ptr)->y_over_x);}
static mus_float_t nrxy_set_y_over_x(mus_any *ptr, mus_float_t val) {((nrxy *)ptr)->y_over_x = val; return(val);}
static mus_float_t nrxy_r(mus_any *ptr) {return(((nrxy *)ptr)->r);}
static mus_float_t nrxy_set_r(mus_any *ptr, mus_float_t r)
{
nrxy *gen = (nrxy *)ptr;
int n;
n = gen->n;
if (r > MAX_R) r = MAX_R;
if (r < MIN_R) r = MIN_R;
gen->r = r;
gen->r_to_n_plus_1 = pow(r, n + 1);
gen->r_squared_plus_1 = 1.0 + r * r;
if (n == 0)
gen->norm = 1.0;
else gen->norm = (pow(fabs(r), n + 1) - 1.0) / (fabs(r) - 1.0);
/* fabs here because if r<0.0, we line up at (2k-1)*pi rather than 2k*pi, but
* otherwise the waveform is identical
*/
return(r);
}
static bool nrxy_equalp(mus_any *p1, mus_any *p2)
{
nrxy *g1 = (nrxy *)p1;
nrxy *g2 = (nrxy *)p2;
return((p1 == p2) ||
(((g1->core)->type == (g2->core)->type) &&
(g1->freq == g2->freq) &&
(g1->phase == g2->phase) &&
(g1->n == g2->n) &&
(g1->r == g2->r) &&
(g1->y_over_x == g2->y_over_x)));
}
bool mus_nrxysin_p(mus_any *ptr)
{
return((ptr) &&
(ptr->core->type == MUS_NRXYSIN));
}
static char *describe_nrxysin(mus_any *ptr)
{
nrxy *gen = (nrxy *)ptr;
char *describe_buffer;
describe_buffer = (char *)clm_malloc(DESCRIBE_BUFFER_SIZE, "describe buffer");
mus_snprintf(describe_buffer, DESCRIBE_BUFFER_SIZE, "%s frequency: %.3f, ratio: %.3f, phase: %.3f, n: %d, r: %.3f",
mus_name(ptr),
mus_frequency(ptr),
gen->y_over_x,
mus_phase(ptr),
gen->n,
nrxy_r(ptr));
return(describe_buffer);
}
mus_float_t mus_nrxysin(mus_any *ptr, mus_float_t fm)
{
/* Jolley 475 but 0..n rather than 0..n-1 */
/* see also Durell and Robson "Advanced Trigonometry" p 175 */
nrxy *gen = (nrxy *)ptr;
double x, y, r, divisor;
int n;
x = gen->phase;
y = x * gen->y_over_x;
n = gen->n;
r = gen->r;
gen->phase += (gen->freq + fm);
divisor = gen->norm * (gen->r_squared_plus_1 - (2 * r * cos(y)));
if (DIVISOR_NEAR_ZERO(divisor))
return(0.0);
return((sin(x) -
r * sin(x - y) -
gen->r_to_n_plus_1 * (sin (x + (n + 1) * y) -
r * sin(x + n * y))) /
divisor);
}
static mus_float_t run_nrxysin(mus_any *ptr, mus_float_t fm, mus_float_t unused) {return(mus_nrxysin(ptr, fm));}
static mus_any_class NRXYSIN_CLASS = {
MUS_NRXYSIN,
(char *)S_nrxysin,
&free_nrxy,
&describe_nrxysin,
&nrxy_equalp,
0, 0,
&nrxy_n, 0,
&nrxy_freq,
&nrxy_set_freq,
&nrxy_phase,
&nrxy_set_phase,
&nrxy_r,
&nrxy_set_r,
&nrxy_increment,
&nrxy_set_increment,
&run_nrxysin,
MUS_NOT_SPECIAL,
NULL, 0,
&nrxy_y_over_x,
&nrxy_set_y_over_x,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0,
&nrxy_reset,
0, 0, 0
};
mus_any *mus_make_nrxysin(mus_float_t frequency, mus_float_t y_over_x, int n, mus_float_t r)
{
nrxy *gen;
gen = (nrxy *)clm_calloc(1, sizeof(nrxy), S_make_nrxysin);
gen->core = &NRXYSIN_CLASS;
gen->freq = mus_hz_to_radians(frequency);
gen->y_over_x = y_over_x;
gen->phase = 0.0;
gen->n = n;
nrxy_set_r((mus_any *)gen, r);
return((mus_any *)gen);
}
bool mus_nrxycos_p(mus_any *ptr)
{
return((ptr) &&
(ptr->core->type == MUS_NRXYCOS));
}
static char *describe_nrxycos(mus_any *ptr)
{
nrxy *gen = (nrxy *)ptr;
char *describe_buffer;
describe_buffer = (char *)clm_malloc(DESCRIBE_BUFFER_SIZE, "describe buffer");
mus_snprintf(describe_buffer, DESCRIBE_BUFFER_SIZE, "%s frequency: %.3f, ratio: %.3f, phase: %.3f, n: %d, r: %.3f",
mus_name(ptr),
mus_frequency(ptr),
gen->y_over_x,
mus_phase(ptr),
gen->n,
nrxy_r(ptr));
return(describe_buffer);
}
mus_float_t mus_nrxycos(mus_any *ptr, mus_float_t fm)
{
nrxy *gen = (nrxy *)ptr;
double x, y, r, divisor;
int n;
x = gen->phase;
y = x * gen->y_over_x;
n = gen->n;
r = gen->r;
gen->phase += (gen->freq + fm);
divisor = gen->norm * (gen->r_squared_plus_1 - (2 * r * cos(y)));
if (DIVISOR_NEAR_ZERO(divisor))
return(1.0);
/* this can happen if --with-doubles and r>0.9999999 or thereabouts;
* it also happens in x86-64 linux with r=.999999 (with floats), divisor ca 1.0e-12
* in this case, using --with-doubles fixes it
*/
return((cos(x) -
r * cos(x - y) -
gen->r_to_n_plus_1 * (cos(x + (n + 1) * y) -
r * cos(x + n * y))) /
divisor);
}
static mus_float_t run_nrxycos(mus_any *ptr, mus_float_t fm, mus_float_t unused) {return(mus_nrxycos(ptr, fm));}
static mus_any_class NRXYCOS_CLASS = {
MUS_NRXYCOS,
(char *)S_nrxycos,
&free_nrxy,
&describe_nrxycos,
&nrxy_equalp,
0, 0,
&nrxy_n, 0,
&nrxy_freq,
&nrxy_set_freq,
&nrxy_phase,
&nrxy_set_phase,
&nrxy_r,
&nrxy_set_r,
&nrxy_increment,
&nrxy_set_increment,
&run_nrxycos,
MUS_NOT_SPECIAL,
NULL, 0,
&nrxy_y_over_x,
&nrxy_set_y_over_x,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0,
&nrxy_reset,
0, 0, 0
};
mus_any *mus_make_nrxycos(mus_float_t frequency, mus_float_t y_over_x, int n, mus_float_t r)
{
nrxy *gen;
gen = (nrxy *)mus_make_nrxysin(frequency, y_over_x, n, r);
gen->core = &NRXYCOS_CLASS;
return((mus_any *)gen);
}
/* ---------------- table lookup ---------------- */
typedef struct {
mus_any_class *core;
double freq, internal_mag, phase;
mus_float_t *table;
mus_long_t table_size;
mus_interp_t type;
bool table_allocated;
mus_float_t yn1;
} tbl;
mus_float_t *mus_partials_to_wave(mus_float_t *partial_data, int partials, mus_float_t *table, mus_long_t table_size, bool normalize)
{
int partial, k;
mus_clear_array(table, table_size);
for (partial = 0, k = 1; partial < partials; partial++, k += 2)
{
double amp;
amp = partial_data[k];
if (amp != 0.0)
{
mus_long_t i;
double freq, angle;
freq = (partial_data[partial * 2] * TWO_PI) / (double)table_size;
for (i = 0, angle = 0.0; i < table_size; i++, angle += freq)
table[i] += amp * sin(angle);
}
}
if (normalize)
return(array_normalize(table, table_size));
return(table);
}
mus_float_t *mus_phase_partials_to_wave(mus_float_t *partial_data, int partials, mus_float_t *table, mus_long_t table_size, bool normalize)
{
int partial, k, n;
mus_clear_array(table, table_size);
for (partial = 0, k = 1, n = 2; partial < partials; partial++, k += 3, n += 3)
{
double amp;
amp = partial_data[k];
if (amp != 0.0)
{
mus_long_t i;
double freq, angle;
freq = (partial_data[partial * 3] * TWO_PI) / (double)table_size;
for (i = 0, angle = partial_data[n]; i < table_size; i++, angle += freq)
table[i] += amp * sin(angle);
}
}
if (normalize)
return(array_normalize(table, table_size));
return(table);
}
mus_float_t mus_table_lookup(mus_any *ptr, mus_float_t fm)
{
tbl *gen = (tbl *)ptr;
gen->yn1 = mus_interpolate(gen->type, gen->phase, gen->table, gen->table_size, gen->yn1);
gen->phase += (gen->freq + (fm * gen->internal_mag));
if ((gen->phase >= gen->table_size) ||
(gen->phase < 0.0))
{
gen->phase = fmod(gen->phase, (double)(gen->table_size));
if (gen->phase < 0.0)
gen->phase += gen->table_size;
}
return(gen->yn1);
}
mus_float_t mus_table_lookup_unmodulated(mus_any *ptr)
{
tbl *gen = (tbl *)ptr;
gen->yn1 = mus_interpolate(gen->type, gen->phase, gen->table, gen->table_size, gen->yn1);
gen->phase += gen->freq;
if ((gen->phase >= gen->table_size) ||
(gen->phase < 0.0))
{
gen->phase = fmod(gen->phase, (double)(gen->table_size));
if (gen->phase < 0.0)
gen->phase += gen->table_size;
}
return(gen->yn1);
}
static mus_float_t run_table_lookup(mus_any *ptr, mus_float_t fm, mus_float_t unused) {return(mus_table_lookup(ptr, fm));}
bool mus_table_lookup_p(mus_any *ptr)
{
return((ptr) &&
(ptr->core->type == MUS_TABLE_LOOKUP));
}
static mus_long_t table_lookup_length(mus_any *ptr) {return(((tbl *)ptr)->table_size);}
static mus_float_t *table_lookup_data(mus_any *ptr) {return(((tbl *)ptr)->table);}
static mus_float_t table_lookup_freq(mus_any *ptr) {return((((tbl *)ptr)->freq * sampling_rate) / (mus_float_t)(((tbl *)ptr)->table_size));}
static mus_float_t table_lookup_set_freq(mus_any *ptr, mus_float_t val) {((tbl *)ptr)->freq = (val * ((tbl *)ptr)->table_size) / sampling_rate; return(val);}
static mus_float_t table_lookup_increment(mus_any *ptr) {return(((tbl *)ptr)->freq);}
static mus_float_t table_lookup_set_increment(mus_any *ptr, mus_float_t val) {((tbl *)ptr)->freq = val; return(val);}
static mus_float_t table_lookup_phase(mus_any *ptr) {return(fmod(((TWO_PI * ((tbl *)ptr)->phase) / ((tbl *)ptr)->table_size), TWO_PI));}
static mus_float_t table_lookup_set_phase(mus_any *ptr, mus_float_t val) {((tbl *)ptr)->phase = (val * ((tbl *)ptr)->table_size) / TWO_PI; return(val);}
static int table_lookup_interp_type(mus_any *ptr) {return((int)(((tbl *)ptr)->type));} /* ints here and elsewhere to fit mus_channels method = interp-type */
static void table_lookup_reset(mus_any *ptr) {((tbl *)ptr)->phase = 0.0;}
static char *describe_table_lookup(mus_any *ptr)
{
char *describe_buffer;
describe_buffer = (char *)clm_malloc(DESCRIBE_BUFFER_SIZE, "describe buffer");
mus_snprintf(describe_buffer, DESCRIBE_BUFFER_SIZE, "%s freq: %.3fHz, phase: %.3f, length: %d, interp: %s",
mus_name(ptr),
mus_frequency(ptr),
mus_phase(ptr),
(int)mus_length(ptr),
interp_type_to_string(table_lookup_interp_type(ptr)));
return(describe_buffer);
}
static bool table_lookup_equalp(mus_any *p1, mus_any *p2)
{
tbl *t1 = (tbl *)p1;
tbl *t2 = (tbl *)p2;
if (p1 == p2) return(true);
return((t1) && (t2) &&
(t1->core->type == t2->core->type) &&
(t1->table_size == t2->table_size) &&
(t1->freq == t2->freq) &&
(t1->phase == t2->phase) &&
(t1->type == t2->type) &&
(t1->internal_mag == t2->internal_mag) &&
(clm_arrays_are_equal(t1->table, t2->table, t1->table_size)));
}
static int free_table_lookup(mus_any *ptr)
{
tbl *gen = (tbl *)ptr;
if (gen)
{
if ((gen->table) && (gen->table_allocated)) clm_free(gen->table);
clm_free(gen);
}
return(0);
}
static mus_float_t *table_set_data(mus_any *ptr, mus_float_t *val)
{
tbl *gen = (tbl *)ptr;
if (gen->table_allocated) {clm_free(gen->table); gen->table_allocated = false;}
gen->table = val;
return(val);
}
static mus_any_class TABLE_LOOKUP_CLASS = {
MUS_TABLE_LOOKUP,
(char *)S_table_lookup,
&free_table_lookup,
&describe_table_lookup,
&table_lookup_equalp,
&table_lookup_data,
&table_set_data,
&table_lookup_length,
0,
&table_lookup_freq,
&table_lookup_set_freq,
&table_lookup_phase,
&table_lookup_set_phase,
&fallback_scaler, 0,
&table_lookup_increment,
&table_lookup_set_increment,
&run_table_lookup,
MUS_NOT_SPECIAL,
NULL,
&table_lookup_interp_type,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0,
&table_lookup_reset,
0, 0, 0
};
mus_any *mus_make_table_lookup(mus_float_t freq, mus_float_t phase, mus_float_t *table, mus_long_t table_size, mus_interp_t type)
{
tbl *gen;
gen = (tbl *)clm_calloc(1, sizeof(tbl), S_make_table_lookup);
gen->core = &TABLE_LOOKUP_CLASS;
gen->table_size = table_size;
gen->internal_mag = (mus_float_t)table_size / TWO_PI;
gen->freq = (freq * table_size) / sampling_rate;
gen->phase = (fmod(phase, TWO_PI) * table_size) / TWO_PI;
gen->type = type;
gen->yn1 = 0.0;
if (table)
{
gen->table = table;
gen->table_allocated = false;
}
else
{
gen->table = (mus_float_t *)clm_calloc(table_size, sizeof(mus_float_t), "table lookup table");
gen->table_allocated = true;
}
return((mus_any *)gen);
}
/* ---------------- polywave ---------------- */
mus_float_t *mus_partials_to_polynomial(int npartials, mus_float_t *partials, mus_polynomial_t kind)
{
/* coeffs returned in partials */
int i;
mus_long_t *T0, *T1, *Tn;
double *Cc1;
T0 = (mus_long_t *)clm_calloc(npartials + 1, sizeof(mus_long_t), "partials_to_polynomial t0");
T1 = (mus_long_t *)clm_calloc(npartials + 1, sizeof(mus_long_t), "partials_to_polynomial t1");
Tn = (mus_long_t *)clm_calloc(npartials + 1, sizeof(mus_long_t), "partials_to_polynomial tn");
Cc1 = (double *)clm_calloc(npartials + 1, sizeof(double), "partials_to_polynomial cc1");
if (kind == MUS_CHEBYSHEV_FIRST_KIND)
T0[0] = 1;
else T0[0] = 0;
T1[1] = 1;
Cc1[0] = partials[0]; /* DC requested? */
for (i = 1; i < npartials; i++)
{
int k;
double amp;
amp = partials[i];
if (amp != 0.0)
{
if (kind == MUS_CHEBYSHEV_FIRST_KIND)
for (k = 0; k <= i; k++)
Cc1[k] += (amp * T1[k]);
else
for (k = 1; k <= i; k++)
Cc1[k - 1] += (amp * T1[k]);
}
for (k = i + 1; k > 0; k--)
Tn[k] = (2 * T1[k - 1]) - T0[k];
Tn[0] = -T0[0];
for (k = i + 1; k >= 0; k--)
{
T0[k] = T1[k];
T1[k] = Tn[k];
}
}
for (i = 0; i < npartials; i++)
partials[i] = Cc1[i];
clm_free(T0);
clm_free(T1);
clm_free(Tn);
clm_free(Cc1);
return(partials);
}
mus_float_t *mus_normalize_partials(int num_partials, mus_float_t *partials)
{
int i;
double sum = 0.0;
for (i = 0; i < num_partials; i++)
sum += fabs(partials[2 * i + 1]);
if ((sum != 0.0) &&
(sum != 1.0))
{
sum = 1.0 / sum;
for (i = 0; i < num_partials; i++)
partials[2 * i + 1] *= sum;
}
return(partials);
}
typedef struct {
mus_any_class *core;
double phase, freq;
mus_float_t *coeffs;
int n, cheby_choice;
mus_float_t index;
} pw;
static int free_pw(mus_any *pt)
{
pw *ptr = (pw *)pt;
if (ptr)
clm_free(ptr);
return(0);
}
static void pw_reset(mus_any *ptr)
{
pw *gen = (pw *)ptr;
gen->phase = 0.0;
}
static bool pw_equalp(mus_any *p1, mus_any *p2)
{
pw *w1 = (pw *)p1;
pw *w2 = (pw *)p2;
if (p1 == p2) return(true);
return((w1) && (w2) &&
(w1->core->type == w2->core->type) &&
(w1->freq == w2->freq) &&
(w1->phase == w2->phase) &&
(w1->n == w2->n) &&
(w1->index == w2->index) &&
(w1->cheby_choice == w2->cheby_choice) &&
(clm_arrays_are_equal(w1->coeffs, w2->coeffs, w1->n)));
}
static mus_float_t pw_freq(mus_any *ptr) {return(mus_radians_to_hz(((pw *)ptr)->freq));}
static mus_float_t pw_set_freq(mus_any *ptr, mus_float_t val) {((pw *)ptr)->freq = mus_hz_to_radians(val); return(val);}
static mus_float_t pw_increment(mus_any *ptr) {return(((pw *)ptr)->freq);}
static mus_float_t pw_set_increment(mus_any *ptr, mus_float_t val) {((pw *)ptr)->freq = val; return(val);}
static mus_float_t pw_phase(mus_any *ptr) {return(fmod(((pw *)ptr)->phase, TWO_PI));}
static mus_float_t pw_set_phase(mus_any *ptr, mus_float_t val) {((pw *)ptr)->phase = val; return(val);}
static mus_long_t pw_n(mus_any *ptr) {return(((pw *)ptr)->n);}
static mus_long_t pw_set_n(mus_any *ptr, mus_long_t val) {((pw *)ptr)->n = (int)val; return(val);}
static mus_float_t *pw_data(mus_any *ptr) {return(((pw *)ptr)->coeffs);}
static mus_float_t *pw_set_data(mus_any *ptr, mus_float_t *val) {((pw *)ptr)->coeffs = val; return(val);}
static mus_float_t pw_index(mus_any *ptr) {return(((pw *)ptr)->index);}
static mus_float_t pw_set_index(mus_any *ptr, mus_float_t val) {((pw *)ptr)->index = val; return(val);}
static int pw_choice(mus_any *ptr) {return(((pw *)ptr)->cheby_choice);}
mus_float_t mus_chebyshev_tu_sum(mus_float_t x, int n, mus_float_t *tn, mus_float_t *un)
{
/* the Clenshaw algorithm */
double x2, tb, tb1 = 0.0, tb2, cx, ub, ub1 = 0.0, ub2;
mus_float_t *tp, *up;
cx = cos(x);
x2 = 2.0 * cx;
tp = (mus_float_t *)(tn + n - 1);
up = (mus_float_t *)(un + n - 1);
tb = (*tp--);
ub = (*up--);
while (up != un)
{
tb2 = tb1;
tb1 = tb;
tb = x2 * tb1 - tb2 + (*tp--);
ub2 = ub1;
ub1 = ub;
ub = x2 * ub1 - ub2 + (*up--);
}
tb2 = tb1;
tb1 = tb;
tb = x2 * tb1 - tb2 + tn[0];
return((mus_float_t)((tb - tb1 * cx) + (sin(x) * ub)));
}
mus_float_t mus_chebyshev_t_sum(mus_float_t x, int n, mus_float_t *tn)
{
int i;
double x2, b, b1 = 0.0, b2 = 0.0, cx;
cx = cos(x);
x2 = 2.0 * cx;
/* Tn calc */
b = tn[n - 1];
for (i = n - 2; i >= 0; i--)
{
b2 = b1;
b1 = b;
b = x2 * b1 - b2 + tn[i];
}
return((mus_float_t)(b - b1 * cx));
}
#if 0
/* here is the trick to do odd Tn without doing the intervening evens: */
(define (mus-chebyshev-odd-t-sum x n t2n)
(let* ((b1 0.0)
(b2 0.0)
(cx1 (cos x))
(cx (- (* 2 cx1 cx1) 1))
(x2 (* 2.0 cx))
(b (vct-ref t2n (- n 1))))
(do ((i (- n 2) (1- i)))
((< i 0))
(set! b2 b1)
(set! b1 b)
(set! b (- (+ (* b1 x2) (vct-ref t2n i)) b2)))
(* cx1 (- b b1))))
(with-sound ()
(let ((t2n (vct 0.5 0.25 0.25))
(x 0.0)
(dx (hz->radians 10.0)))
(do ((i 0 (1+ i)))
((= i 22050))
(outa i (mus-chebyshev-odd-t-sum x 3 t2n))
(set! x (+ x dx)))))
#endif
mus_float_t mus_chebyshev_u_sum(mus_float_t x, int n, mus_float_t *un)
{
int i;
double x2, b, b1 = 0.0, b2 = 0.0, cx;
cx = cos(x);
x2 = 2.0 * cx;
/* Un calc */
b = un[n - 1];
for (i = n - 2; i > 0; i--)
{
b2 = b1;
b1 = b;
b = x2 * b1 - b2 + un[i];
}
return((mus_float_t)(sin(x) * b));
}
static mus_float_t mus_chebyshev_t_sum_with_index(mus_float_t x, mus_float_t index, int n, mus_float_t *tn)
{
int i;
double x2, b, b1 = 0.0, b2 = 0.0, cx;
cx = index * cos(x);
x2 = 2.0 * cx;
/* Tn calc */
b = tn[n - 1];
for (i = n - 2; i >= 0; i--)
{
b2 = b1;
b1 = b;
b = x2 * b1 - b2 + tn[i];
}
return((mus_float_t)(b - b1 * cx));
}
static mus_float_t mus_chebyshev_u_sum_with_index(mus_float_t x, mus_float_t index, int n, mus_float_t *un)
{
int i;
double x2, b, b1 = 0.0, b2 = 0.0, cx;
cx = index * cos(x);
x2 = 2.0 * cx;
/* Un calc */
b = un[n - 1];
for (i = n - 2; i > 0; i--)
{
b2 = b1;
b1 = b;
b = x2 * b1 - b2 + un[i];
}
return((mus_float_t)(sin(x) * b));
}
mus_float_t mus_polywave(mus_any *ptr, mus_float_t fm)
{
/* changed to use recursion, rather than polynomial in x, 25-May-08
* this algorithm taken from Mason and Handscomb, "Chebyshev Polynomials" p27
*/
pw *gen = (pw *)ptr;
mus_float_t result;
if (gen->cheby_choice != MUS_CHEBYSHEV_SECOND_KIND)
result = mus_chebyshev_t_sum_with_index(gen->phase, gen->index, gen->n, gen->coeffs);
else result = mus_chebyshev_u_sum_with_index(gen->phase, gen->index, gen->n, gen->coeffs);
gen->phase += (gen->freq + fm);
return(result);
}
mus_float_t mus_polywave_unmodulated(mus_any *ptr)
{
return(mus_polywave(ptr, 0.0));
}
static mus_float_t run_polywave(mus_any *ptr, mus_float_t fm, mus_float_t ignored) {return(mus_polywave(ptr, fm));}
static char *describe_polywave(mus_any *ptr)
{
pw *gen = (pw *)ptr;
char *str;
char *describe_buffer;
str = float_array_to_string(gen->coeffs, gen->n, 0);
describe_buffer = (char *)clm_malloc(DESCRIBE_BUFFER_SIZE, "describe buffer");
mus_snprintf(describe_buffer, DESCRIBE_BUFFER_SIZE, "%s freq: %.3fHz, phase: %.3f, coeffs[%d]: %s",
mus_name(ptr),
mus_frequency(ptr),
mus_phase(ptr),
gen->n,
str);
if (str) clm_free(str);
return(describe_buffer);
}
static mus_any_class POLYWAVE_CLASS = {
MUS_POLYWAVE,
(char *)S_polywave,
&free_pw,
&describe_polywave,
&pw_equalp,
&pw_data,
&pw_set_data,
&pw_n,
&pw_set_n,
&pw_freq,
&pw_set_freq,
&pw_phase,
&pw_set_phase,
&pw_index,
&pw_set_index,
&pw_increment,
&pw_set_increment,
&run_polywave,
MUS_NOT_SPECIAL,
NULL, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0,
&pw_choice,
0, 0, 0, 0, 0,
&pw_reset,
0, 0, 0
};
mus_any *mus_make_polywave(mus_float_t frequency, mus_float_t *coeffs, int n, int cheby_choice)
{
pw *gen;
gen = (pw *)clm_calloc(1, sizeof(pw), S_make_polywave);
gen->core = &POLYWAVE_CLASS;
gen->phase = 0.0; /* cos used in cheby funcs above */
gen->freq = mus_hz_to_radians(frequency);
gen->coeffs = coeffs;
gen->n = n;
gen->index = 1.0;
gen->cheby_choice = cheby_choice;
return((mus_any *)gen);
}
bool mus_polywave_p(mus_any *ptr)
{
return((ptr) &&
(ptr->core->type == MUS_POLYWAVE));
}
/* ---------------- polyshape ---------------- */
static char *describe_polyshape(mus_any *ptr)
{
pw *gen = (pw *)ptr;
char *str;
char *describe_buffer;
describe_buffer = (char *)clm_malloc(DESCRIBE_BUFFER_SIZE, "describe buffer");
str = float_array_to_string(gen->coeffs, gen->n, 0);
mus_snprintf(describe_buffer, DESCRIBE_BUFFER_SIZE, "%s freq: %.3fHz, phase: %.3f, coeffs[%d]: %s",
mus_name(ptr),
mus_frequency(ptr),
mus_phase(ptr),
gen->n,
str);
clm_free(str);
return(describe_buffer);
}
mus_float_t mus_polyshape(mus_any *ptr, mus_float_t index, mus_float_t fm)
{
pw *gen = (pw *)ptr;
mus_float_t result;
gen->index = index;
result = mus_polynomial(gen->coeffs,
index * cos(gen->phase),
gen->n);
if (gen->cheby_choice == MUS_CHEBYSHEV_SECOND_KIND)
result *= sin(gen->phase);
gen->phase += (gen->freq + fm);
return(result);
}
mus_float_t mus_polyshape_unmodulated(mus_any *ptr, mus_float_t index)
{
pw *gen = (pw *)ptr;
mus_float_t result;
gen->index = index;
result = mus_polynomial(gen->coeffs,
index * cos(gen->phase),
gen->n);
if (gen->cheby_choice == MUS_CHEBYSHEV_SECOND_KIND)
result *= sin(gen->phase);
gen->phase += gen->freq;
return(result);
}
static mus_any_class POLYSHAPE_CLASS = {
MUS_POLYSHAPE,
(char *)S_polyshape,
&free_pw,
&describe_polyshape,
&pw_equalp,
&pw_data,
&pw_set_data,
&pw_n,
&pw_set_n,
&pw_freq,
&pw_set_freq,
&pw_phase,
&pw_set_phase,
&pw_index, &pw_set_index,
&pw_increment,
&pw_set_increment,
&mus_polyshape,
MUS_NOT_SPECIAL,
NULL, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0,
&pw_reset,
0, 0, 0
};
mus_any *mus_make_polyshape(mus_float_t frequency, mus_float_t phase, mus_float_t *coeffs, int size, int cheby_choice)
{
mus_any *gen;
gen = mus_make_polywave(frequency, coeffs, size, cheby_choice);
gen->core = &POLYSHAPE_CLASS;
pw_set_phase(gen, phase);
return(gen);
}
bool mus_polyshape_p(mus_any *ptr)
{
return((ptr) &&
(ptr->core->type == MUS_POLYSHAPE));
}
/* ---------------- wave-train ---------------- */
typedef struct {
mus_any_class *core;
double freq, phase;
mus_float_t *wave; /* passed in from caller */
mus_long_t wave_size;
mus_float_t *out_data;
mus_long_t out_data_size;
mus_interp_t interp_type; /* "type" field exists in core -- avoid confusion */
mus_float_t next_wave_time;
mus_long_t out_pos;
bool first_time;
mus_float_t yn1;
} wt;
static mus_float_t wt_freq(mus_any *ptr) {return(((wt *)ptr)->freq);}
static mus_float_t wt_set_freq(mus_any *ptr, mus_float_t val) {((wt *)ptr)->freq = val; return(val);}
static mus_float_t wt_phase(mus_any *ptr) {return(fmod(((TWO_PI * ((wt *)ptr)->phase) / ((mus_float_t)((wt *)ptr)->wave_size)), TWO_PI));}
static mus_float_t wt_set_phase(mus_any *ptr, mus_float_t val) {((wt *)ptr)->phase = (fmod(val, TWO_PI) * ((wt *)ptr)->wave_size) / TWO_PI; return(val);}
static mus_long_t wt_length(mus_any *ptr) {return(((wt *)ptr)->wave_size);}
static mus_long_t wt_set_length(mus_any *ptr, mus_long_t val) {if (val > 0) ((wt *)ptr)->wave_size = val; return(((wt *)ptr)->wave_size);}
static int wt_interp_type(mus_any *ptr) {return((int)(((wt *)ptr)->interp_type));}
static mus_float_t *wt_data(mus_any *ptr) {return(((wt *)ptr)->wave);}
static mus_float_t *wt_set_data(mus_any *ptr, mus_float_t *data) {((wt *)ptr)->wave = data; return(data);}
static bool wt_equalp(mus_any *p1, mus_any *p2)
{
wt *w1 = (wt *)p1;
wt *w2 = (wt *)p2;
if (p1 == p2) return(true);
return((w1) && (w2) &&
(w1->core->type == w2->core->type) &&
(w1->freq == w2->freq) &&
(w1->phase == w2->phase) &&
(w1->interp_type == w2->interp_type) &&
(w1->wave_size == w2->wave_size) &&
(w1->out_data_size == w2->out_data_size) &&
(w1->out_pos == w2->out_pos) &&
(clm_arrays_are_equal(w1->wave, w2->wave, w1->wave_size)) &&
(clm_arrays_are_equal(w1->out_data, w2->out_data, w1->out_data_size)));
}
static char *describe_wt(mus_any *ptr)
{
char *describe_buffer;
describe_buffer = (char *)clm_malloc(DESCRIBE_BUFFER_SIZE, "describe buffer");
mus_snprintf(describe_buffer, DESCRIBE_BUFFER_SIZE, "%s freq: %.3fHz, phase: %.3f, size: " MUS_LD ", interp: %s",
mus_name(ptr),
mus_frequency(ptr),
mus_phase(ptr),
mus_length(ptr),
interp_type_to_string(wt_interp_type(ptr)));
return(describe_buffer);
}
static mus_float_t mus_wave_train_any(mus_any *ptr, mus_float_t fm)
{
wt *gen = (wt *)ptr;
mus_float_t result = 0.0;
if (gen->out_pos < gen->out_data_size)
result = gen->out_data[gen->out_pos];
gen->out_pos++;
if (gen->out_pos >= gen->next_wave_time)
{
mus_long_t i;
if (gen->out_pos < gen->out_data_size)
{
mus_long_t good_samps;
good_samps = gen->out_data_size - gen->out_pos;
memmove((void *)(gen->out_data), (void *)(gen->out_data + gen->out_pos), good_samps * sizeof(mus_float_t));
memset((void *)(gen->out_data + good_samps), 0, gen->out_pos * sizeof(mus_float_t));
}
else mus_clear_array(gen->out_data, gen->out_data_size);
for (i = 0; i < gen->wave_size; i++)
{
gen->yn1 = mus_interpolate(gen->interp_type, gen->phase + i, gen->wave, gen->wave_size, gen->yn1);
gen->out_data[i] += gen->yn1;
}
if (gen->first_time)
{
gen->first_time = false;
gen->out_pos = (mus_long_t)(gen->phase); /* initial phase, but as an integer in terms of wave table size (gad...) */
if (gen->out_pos >= gen->wave_size)
gen->out_pos = gen->out_pos % gen->wave_size;
result = gen->out_data[gen->out_pos++];
gen->next_wave_time = ((mus_float_t)sampling_rate / (gen->freq + fm));
}
else
{
gen->next_wave_time += (((mus_float_t)sampling_rate / (gen->freq + fm)) - gen->out_pos);
gen->out_pos = 0;
}
}
return(result);
}
mus_float_t mus_wave_train(mus_any *ptr, mus_float_t fm) {return(mus_wave_train_any(ptr, fm / w_rate));}
mus_float_t mus_wave_train_unmodulated(mus_any *ptr) {return(mus_wave_train(ptr, 0.0));}
static mus_float_t run_wave_train(mus_any *ptr, mus_float_t fm, mus_float_t unused) {return(mus_wave_train_any(ptr, fm / w_rate));}
static int free_wt(mus_any *p)
{
wt *ptr = (wt *)p;
if (ptr)
{
if (ptr->out_data)
{
clm_free(ptr->out_data);
ptr->out_data = NULL;
}
clm_free(ptr);
}
return(0);
}
static void wt_reset(mus_any *ptr)
{
wt *gen = (wt *)ptr;
gen->phase = 0.0;
mus_clear_array(gen->out_data, gen->out_data_size);
gen->out_pos = gen->out_data_size;
gen->next_wave_time = 0.0;
gen->first_time = true;
}
static mus_any_class WAVE_TRAIN_CLASS = {
MUS_WAVE_TRAIN,
(char *)S_wave_train,
&free_wt,
&describe_wt,
&wt_equalp,
&wt_data,
&wt_set_data,
&wt_length,
&wt_set_length,
&wt_freq,
&wt_set_freq,
&wt_phase,
&wt_set_phase,
&fallback_scaler, 0,
0, 0,
&run_wave_train,
MUS_NOT_SPECIAL,
NULL,
&wt_interp_type,
0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0,
&wt_reset,
0, 0, 0
};
mus_any *mus_make_wave_train(mus_float_t freq, mus_float_t phase, mus_float_t *wave, mus_long_t wave_size, mus_interp_t type)
{
wt *gen;
gen = (wt *)clm_calloc(1, sizeof(wt), S_make_wave_train);
gen->core = &WAVE_TRAIN_CLASS;
gen->freq = freq;
gen->phase = (wave_size * fmod(phase, TWO_PI)) / TWO_PI;
gen->wave = wave;
gen->wave_size = wave_size;
gen->interp_type = type;
gen->out_data_size = wave_size + 2;
gen->out_data = (mus_float_t *)clm_calloc(gen->out_data_size, sizeof(mus_float_t), "wave train out data");
gen->out_pos = gen->out_data_size;
gen->next_wave_time = 0.0;
gen->first_time = true;
gen->yn1 = 0.0;
return((mus_any *)gen);
}
bool mus_wave_train_p(mus_any *ptr)
{
return((ptr) &&
(ptr->core->type == MUS_WAVE_TRAIN));
}
/* ---------------- delay, comb, notch, all-pass, moving-average ---------------- */
typedef struct {
mus_any_class *core;
int loc, size;
bool zdly, line_allocated;
mus_float_t *line;
int zloc, zsize;
mus_float_t xscl, yscl, yn1;
mus_interp_t type;
mus_any *filt;
} dly;
mus_float_t mus_delay_tick(mus_any *ptr, mus_float_t input)
{
dly *gen = (dly *)ptr;
gen->line[gen->loc] = input;
gen->loc++;
if (gen->zdly)
{
if (gen->loc >= gen->zsize) gen->loc = 0;
gen->zloc++;
if (gen->zloc >= gen->zsize) gen->zloc = 0;
}
else
{
if (gen->loc >= gen->size) gen->loc = 0;
}
return(input);
}
mus_float_t mus_delay_tick_noz(mus_any *ptr, mus_float_t input)
{
dly *gen = (dly *)ptr;
gen->line[gen->loc] = input;
gen->loc++;
if (gen->loc >= gen->size)
gen->loc = 0;
return(input);
}
mus_float_t mus_delay(mus_any *ptr, mus_float_t input, mus_float_t pm)
{
mus_float_t result;
dly *gen = (dly *)ptr;
if ((gen->size == 0) && (pm < 1.0))
return(pm * gen->line[0] + (1.0 - pm) * input);
result = mus_tap(ptr, pm);
mus_delay_tick(ptr, input);
return(result);
}
mus_float_t mus_delay_unmodulated(mus_any *ptr, mus_float_t input)
{
dly *gen = (dly *)ptr;
mus_float_t result;
if (gen->zdly)
{
if (gen->size == 0) return(input); /* no point in tick in this case */
result = gen->line[gen->zloc];
}
else result = gen->line[gen->loc];
mus_delay_tick(ptr, input);
return(result);
}
mus_float_t mus_delay_unmodulated_noz(mus_any *ptr, mus_float_t input)
{
dly *gen = (dly *)ptr;
mus_float_t result;
result = gen->line[gen->loc];
gen->line[gen->loc] = input;
gen->loc++;
if (gen->loc >= gen->size)
gen->loc = 0;
return(result);
}
mus_float_t mus_tap(mus_any *ptr, mus_float_t loc)
{
dly *gen = (dly *)ptr;
int taploc;
if (gen->zdly)
{
gen->yn1 = mus_interpolate(gen->type, gen->zloc - loc, gen->line, gen->zsize, gen->yn1);
return(gen->yn1);
}
else
{
if (gen->size == 0) return(gen->line[0]);
if ((int)loc == 0) return(gen->line[gen->loc]);
taploc = (int)(gen->loc - (int)loc) % gen->size;
if (taploc < 0) taploc += gen->size;
return(gen->line[taploc]);
}
}
mus_float_t mus_tap_unmodulated(mus_any *ptr)
{
dly *gen = (dly *)ptr;
return(gen->line[gen->loc]);
}
static int free_delay(mus_any *gen)
{
dly *ptr = (dly *)gen;
if (ptr)
{
if ((ptr->line) && (ptr->line_allocated)) clm_free(ptr->line);
clm_free(ptr);
}
return(0);
}
static char *describe_delay(mus_any *ptr)
{
char *str = NULL;
dly *gen = (dly *)ptr;
char *describe_buffer;
describe_buffer = (char *)clm_malloc(DESCRIBE_BUFFER_SIZE, "describe buffer");
if (gen->zdly)
mus_snprintf(describe_buffer, DESCRIBE_BUFFER_SIZE, "%s line[%d,%d, %s]: %s",
mus_name(ptr),
gen->size,
gen->zsize,
interp_type_to_string(gen->type),
str = float_array_to_string(gen->line, gen->size, gen->zloc));
else mus_snprintf(describe_buffer, DESCRIBE_BUFFER_SIZE, "%s line[%d, %s]: %s",
mus_name(ptr),
gen->size,
interp_type_to_string(gen->type),
str = float_array_to_string(gen->line, gen->size, gen->loc));
if (str) clm_free(str);
return(describe_buffer);
}
static bool delay_equalp(mus_any *p1, mus_any *p2)
{
dly *d1 = (dly *)p1;
dly *d2 = (dly *)p2;
if (p1 == p2) return(true);
return((d1) && (d2) &&
(d1->core->type == d2->core->type) &&
(d1->size == d2->size) &&
(d1->loc == d2->loc) &&
(d1->zdly == d2->zdly) &&
(d1->zloc == d2->zloc) &&
(d1->zsize == d2->zsize) &&
(d1->xscl == d2->xscl) &&
(d1->yscl == d2->yscl) &&
(d1->yn1 == d2->yn1) &&
(d1->type == d2->type) &&
(clm_arrays_are_equal(d1->line, d2->line, d1->size)));
}
static mus_long_t delay_length(mus_any *ptr)
{
dly *d = (dly *)ptr;
if (d->size > 0) /* this is possible (not sure it's a good idea...) */
return(d->size);
return(d->zsize); /* maybe always use this? */
}
static mus_float_t delay_scaler(mus_any *ptr) {return(((dly *)ptr)->xscl);}
static mus_float_t delay_set_scaler(mus_any *ptr, mus_float_t val) {((dly *)ptr)->xscl = val; return(val);}
static mus_float_t delay_fb(mus_any *ptr) {return(((dly *)ptr)->yscl);}
static mus_float_t delay_set_fb(mus_any *ptr, mus_float_t val) {((dly *)ptr)->yscl = val; return(val);}
static int delay_interp_type(mus_any *ptr) {return((int)(((dly *)ptr)->type));}
static int delay_zdly(mus_any *ptr) {return((int)(((dly *)ptr)->zdly));}
static mus_long_t delay_loc(mus_any *ptr){return((mus_long_t)(((dly *)ptr)->loc));}
static mus_float_t *delay_data(mus_any *ptr) {return(((dly *)ptr)->line);}
static mus_float_t *delay_set_data(mus_any *ptr, mus_float_t *val)
{
dly *gen = (dly *)ptr;
if (gen->line_allocated) {clm_free(gen->line); gen->line_allocated = false;}
gen->line = val;
return(val);
}
static mus_long_t delay_set_length(mus_any *ptr, mus_long_t val)
{
dly *gen = (dly *)ptr;
if (val > 0)
{
int old_size;
old_size = gen->size;
gen->size = (int)val;
if (gen->size < old_size)
{
if (gen->loc > gen->size) gen->loc = 0;
gen->zdly = false; /* otherwise too many ways to screw up */
}
}
return((mus_long_t)(gen->size));
}
bool mus_delay_line_p(mus_any *gen)
{
return((gen) &&
(gen->core->extended_type == MUS_DELAY_LINE));
}
static void delay_reset(mus_any *ptr)
{
dly *gen = (dly *)ptr;
gen->loc = 0;
gen->zloc = 0;
gen->yn1 = 0.0;
mus_clear_array(gen->line, gen->zsize);
}
static mus_any_class DELAY_CLASS = {
MUS_DELAY,
(char *)S_delay,
&free_delay,
&describe_delay,
&delay_equalp,
&delay_data,
&delay_set_data,
&delay_length,
&delay_set_length,
0, 0, 0, 0, /* freq phase */
&delay_scaler,
&delay_set_scaler,
&delay_fb,
&delay_set_fb,
&mus_delay,
MUS_DELAY_LINE,
NULL,
&delay_interp_type,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0,
&delay_loc,
0, 0,
0, 0, 0, 0, 0,
&delay_reset,
0, &delay_zdly, 0
};
mus_any *mus_make_delay(int size, mus_float_t *preloaded_line, int line_size, mus_interp_t type)
{
/* if preloaded_line null, allocated locally */
/* if size == line_size, normal (non-interpolating) delay */
dly *gen;
gen = (dly *)clm_calloc(1, sizeof(dly), S_make_delay);
gen->core = &DELAY_CLASS;
gen->loc = 0;
gen->size = size;
gen->zsize = line_size;
gen->zdly = ((line_size != size) || (type != MUS_INTERP_NONE));
gen->type = type;
if (preloaded_line)
{
gen->line = preloaded_line;
gen->line_allocated = false;
}
else
{
gen->line = (mus_float_t *)clm_calloc(line_size, sizeof(mus_float_t), "delay line");
gen->line_allocated = true;
}
gen->zloc = line_size - size;
return((mus_any *)gen);
}
bool mus_delay_p(mus_any *ptr)
{
return((ptr) &&
(ptr->core->type == MUS_DELAY));
}
mus_float_t mus_comb(mus_any *ptr, mus_float_t input, mus_float_t pm)
{
dly *gen = (dly *)ptr;
if (gen->zdly)
return(mus_delay(ptr, input + (gen->yscl * mus_tap(ptr, pm)), pm));
/* mus.lisp has 0 in place of the final pm -- the question is whether the delay
should interpolate as well as the tap. There is a subtle difference in
output (the pm case is low-passed by the interpolation ("average"),
but I don't know if there's a standard here, or what people expect.
We're doing the outer-level interpolation in notch and all-pass.
Should mus.lisp be changed?
*/
else return(mus_delay(ptr, input + (gen->line[gen->loc] * gen->yscl), 0.0));
}
mus_float_t mus_comb_unmodulated(mus_any *ptr, mus_float_t input)
{
dly *gen = (dly *)ptr;
return(mus_delay_unmodulated(ptr, input + (gen->line[gen->loc] * gen->yscl)));
}
mus_float_t mus_comb_unmodulated_noz(mus_any *ptr, mus_float_t input)
{
dly *gen = (dly *)ptr;
mus_float_t result;
result = gen->line[gen->loc];
gen->line[gen->loc] = input + (gen->line[gen->loc] * gen->yscl);
gen->loc++;
if (gen->loc >= gen->size)
gen->loc = 0;
return(result);
}
static char *describe_comb(mus_any *ptr)
{
char *str = NULL;
dly *gen = (dly *)ptr;
char *describe_buffer;
describe_buffer = (char *)clm_malloc(DESCRIBE_BUFFER_SIZE, "describe buffer");
if (gen->zdly)
mus_snprintf(describe_buffer, DESCRIBE_BUFFER_SIZE, "%s scaler: %.3f, line[%d,%d, %s]: %s",
mus_name(ptr),
gen->yscl,
gen->size,
gen->zsize,
interp_type_to_string(gen->type),
str = float_array_to_string(gen->line, gen->size, gen->zloc));
else mus_snprintf(describe_buffer, DESCRIBE_BUFFER_SIZE, "%s scaler: %.3f, line[%d, %s]: %s",
mus_name(ptr),
gen->yscl,
gen->size,
interp_type_to_string(gen->type),
str = float_array_to_string(gen->line, gen->size, gen->loc));
if (str) clm_free(str);
return(describe_buffer);
}
static mus_any_class COMB_CLASS = {
MUS_COMB,
(char *)S_comb,
&free_delay,
&describe_comb,
&delay_equalp,
&delay_data,
&delay_set_data,
&delay_length,
&delay_set_length,
0, 0, 0, 0, /* freq phase */
&delay_scaler,
&delay_set_scaler,
&delay_fb,
&delay_set_fb,
&mus_comb,
MUS_DELAY_LINE,
NULL,
&delay_interp_type,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0,
&delay_loc,
0, 0,
0, 0, 0, 0, 0,
&delay_reset,
0, &delay_zdly, 0
};
mus_any *mus_make_comb(mus_float_t scaler, int size, mus_float_t *line, int line_size, mus_interp_t type)
{
dly *gen;
gen = (dly *)mus_make_delay(size, line, line_size, type);
if (gen)
{
gen->core = &COMB_CLASS;
gen->yscl = scaler;
return((mus_any *)gen);
}
return(NULL);
}
bool mus_comb_p(mus_any *ptr)
{
return((ptr) &&
(ptr->core->type == MUS_COMB));
}
static char *describe_notch(mus_any *ptr)
{
char *str = NULL;
dly *gen = (dly *)ptr;
char *describe_buffer;
describe_buffer = (char *)clm_malloc(DESCRIBE_BUFFER_SIZE, "describe buffer");
if (gen->zdly)
mus_snprintf(describe_buffer, DESCRIBE_BUFFER_SIZE, "%s scaler: %.3f, line[%d,%d, %s]: %s",
mus_name(ptr),
gen->xscl,
gen->size,
gen->zsize,
interp_type_to_string(gen->type),
str = float_array_to_string(gen->line, gen->size, gen->zloc));
else mus_snprintf(describe_buffer, DESCRIBE_BUFFER_SIZE, "%s scaler: %.3f, line[%d, %s]: %s",
mus_name(ptr),
gen->xscl,
gen->size,
interp_type_to_string(gen->type),
str = float_array_to_string(gen->line, gen->size, gen->loc));
if (str) clm_free(str);
return(describe_buffer);
}
static mus_any_class NOTCH_CLASS = {
MUS_NOTCH,
(char *)S_notch,
&free_delay,
&describe_notch,
&delay_equalp,
&delay_data,
&delay_set_data,
&delay_length,
&delay_set_length,
0, 0, 0, 0, /* freq phase */
&delay_scaler,
&delay_set_scaler,
0, 0,
&mus_notch,
MUS_DELAY_LINE,
NULL,
&delay_interp_type,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0,
&delay_loc,
0, 0,
0, 0, 0, 0, 0,
&delay_reset,
0, &delay_zdly, 0
};
mus_float_t mus_notch(mus_any *ptr, mus_float_t input, mus_float_t pm)
{
dly *gen = (dly *)ptr;
return((input * gen->xscl) + mus_delay(ptr, input, pm));
}
mus_float_t mus_notch_unmodulated(mus_any *ptr, mus_float_t input)
{
return((input * ((dly *)ptr)->xscl) + mus_delay_unmodulated(ptr, input));
}
mus_float_t mus_notch_unmodulated_noz(mus_any *ptr, mus_float_t input)
{
dly *gen = (dly *)ptr;
mus_float_t result;
result = gen->line[gen->loc] + (input * gen->xscl);
gen->line[gen->loc] = input;
gen->loc++;
if (gen->loc >= gen->size)
gen->loc = 0;
return(result);
}
bool mus_notch_p(mus_any *ptr)
{
return((ptr) &&
(ptr->core->type == MUS_NOTCH));
}
mus_any *mus_make_notch(mus_float_t scaler, int size, mus_float_t *line, int line_size, mus_interp_t type)
{
dly *gen;
gen = (dly *)mus_make_delay(size, line, line_size, type);
if (gen)
{
gen->core = &NOTCH_CLASS;
gen->xscl = scaler;
return((mus_any *)gen);
}
return(NULL);
}
mus_float_t mus_all_pass(mus_any *ptr, mus_float_t input, mus_float_t pm)
{
mus_float_t din;
dly *gen = (dly *)ptr;
if (gen->zdly)
din = input + (gen->yscl * mus_tap(ptr, pm));
else din = input + (gen->yscl * gen->line[gen->loc]);
return(mus_delay(ptr, din, pm) + (gen->xscl * din));
}
mus_float_t mus_all_pass_unmodulated(mus_any *ptr, mus_float_t input)
{
mus_float_t din;
dly *gen = (dly *)ptr;
din = input + (gen->yscl * gen->line[gen->loc]);
return(mus_delay_unmodulated(ptr, din) + (gen->xscl * din));
}
mus_float_t mus_all_pass_unmodulated_noz(mus_any *ptr, mus_float_t input)
{
mus_float_t result, din;
dly *gen = (dly *)ptr;
din = input + (gen->yscl * gen->line[gen->loc]);
result = gen->line[gen->loc] + (gen->xscl * din);
gen->line[gen->loc] = din;
gen->loc++;
if (gen->loc >= gen->size)
gen->loc = 0;
return(result);
}
bool mus_all_pass_p(mus_any *ptr)
{
return((ptr) &&
(ptr->core->type == MUS_ALL_PASS));
}
static char *describe_all_pass(mus_any *ptr)
{
char *str = NULL;
dly *gen = (dly *)ptr;
char *describe_buffer;
describe_buffer = (char *)clm_malloc(DESCRIBE_BUFFER_SIZE, "describe buffer");
if (gen->zdly)
mus_snprintf(describe_buffer, DESCRIBE_BUFFER_SIZE, "%s feedback: %.3f, feedforward: %.3f, line[%d,%d, %s]:%s",
mus_name(ptr),
gen->yscl,
gen->xscl,
gen->size,
gen->zsize,
interp_type_to_string(gen->type),
str = float_array_to_string(gen->line, gen->size, gen->zloc));
else mus_snprintf(describe_buffer, DESCRIBE_BUFFER_SIZE, "%s feedback: %.3f, feedforward: %.3f, line[%d, %s]:%s",
mus_name(ptr),
gen->yscl,
gen->xscl,
gen->size,
interp_type_to_string(gen->type),
str = float_array_to_string(gen->line, gen->size, gen->loc));
if (str) clm_free(str);
return(describe_buffer);
}
static mus_any_class ALL_PASS_CLASS = {
MUS_ALL_PASS,
(char *)S_all_pass,
&free_delay,
&describe_all_pass,
&delay_equalp,
&delay_data,
&delay_set_data,
&delay_length,
&delay_set_length,
0, 0, 0, 0, /* freq phase */
&delay_scaler,
&delay_set_scaler,
&delay_fb,
&delay_set_fb,
&mus_all_pass,
MUS_DELAY_LINE,
NULL,
&delay_interp_type,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0,
&delay_loc,
0, 0,
0, 0, 0, 0, 0,
&delay_reset,
0, &delay_zdly, 0
};
mus_any *mus_make_all_pass(mus_float_t backward, mus_float_t forward, int size, mus_float_t *line, int line_size, mus_interp_t type)
{
dly *gen;
gen = (dly *)mus_make_delay(size, line, line_size, type);
if (gen)
{
gen->core = &ALL_PASS_CLASS;
gen->xscl = forward;
gen->yscl = backward;
return((mus_any *)gen);
}
return(NULL);
}
bool mus_moving_average_p(mus_any *ptr)
{
return((ptr) &&
(ptr->core->type == MUS_MOVING_AVERAGE));
}
mus_float_t mus_moving_average(mus_any *ptr, mus_float_t input)
{
dly *gen = (dly *)ptr;
mus_float_t output;
output = mus_delay_unmodulated_noz(ptr, input);
gen->xscl += (input - output);
return(gen->xscl * gen->yscl); /* xscl=sum, yscl=1/n */
}
static mus_float_t run_mus_moving_average(mus_any *ptr, mus_float_t input, mus_float_t unused) {return(mus_moving_average(ptr, input));}
static void moving_average_reset(mus_any *ptr)
{
dly *gen = (dly *)ptr;
delay_reset(ptr);
gen->xscl = 0.0;
}
static char *describe_moving_average(mus_any *ptr)
{
char *str = NULL;
dly *gen = (dly *)ptr;
char *describe_buffer;
describe_buffer = (char *)clm_malloc(DESCRIBE_BUFFER_SIZE, "describe buffer");
mus_snprintf(describe_buffer, DESCRIBE_BUFFER_SIZE, "%s %.3f, line[%d]:%s",
mus_name(ptr),
gen->xscl * gen->yscl,
gen->size,
str = float_array_to_string(gen->line, gen->size, gen->loc));
if (str) clm_free(str);
return(describe_buffer);
}
static mus_any_class MOVING_AVERAGE_CLASS = {
MUS_MOVING_AVERAGE,
(char *)S_moving_average,
&free_delay,
&describe_moving_average,
&delay_equalp,
&delay_data,
&delay_set_data,
&delay_length,
&delay_set_length,
0, 0, 0, 0, /* freq phase */
&delay_scaler,
&delay_set_scaler,
&delay_fb,
&delay_set_fb,
&run_mus_moving_average,
MUS_DELAY_LINE,
NULL, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0,
&delay_loc,
0, 0,
0, 0, 0, 0, 0,
&moving_average_reset,
0, &delay_zdly, 0
};
mus_any *mus_make_moving_average(int size, mus_float_t *line)
{
dly *gen;
gen = (dly *)mus_make_delay(size, line, size, MUS_INTERP_NONE);
if (gen)
{
int i;
gen->core = &MOVING_AVERAGE_CLASS;
gen->xscl = 0.0;
for (i = 0; i < size; i++)
gen->xscl += gen->line[i];
gen->yscl = 1.0 / (mus_float_t)size;
return((mus_any *)gen);
}
return(NULL);
}
/* ---------------------------------------- filtered-comb ---------------------------------------- */
static void filtered_comb_reset(mus_any *ptr)
{
dly *fc = (dly *)ptr;
delay_reset(ptr);
mus_reset(fc->filt);
}
static bool filtered_comb_equalp(mus_any *p1, mus_any *p2)
{
return((delay_equalp(p1, p2)) &&
(mus_equalp(((dly *)p1)->filt,
((dly *)p2)->filt)));
}
static char *describe_filtered_comb(mus_any *ptr)
{
char *comb_str, *filter_str, *res;
int len;
comb_str = describe_comb(ptr);
filter_str = mus_describe(((dly *)ptr)->filt);
len = strlen(comb_str) + strlen(filter_str) + 64;
res = (char *)clm_calloc(len, sizeof(char), "describe_filtered_comb");
mus_snprintf(res, len, "%s, filter: [%s]", comb_str, filter_str);
if (comb_str) clm_free(comb_str);
if (filter_str) clm_free(filter_str);
return(res);
}
bool mus_filtered_comb_p(mus_any *ptr)
{
return((ptr) &&
(ptr->core->type == MUS_FILTERED_COMB));
}
mus_float_t mus_filtered_comb(mus_any *ptr, mus_float_t input, mus_float_t pm)
{
dly *fc = (dly *)ptr;
if (fc->zdly)
return(mus_delay(ptr,
input + (fc->yscl *
mus_run(fc->filt,
mus_tap(ptr, pm),
0.0)),
pm));
else return(mus_delay(ptr,
input + (fc->yscl *
mus_run(fc->filt,
fc->line[fc->loc],
0.0)),
0.0));
}
mus_float_t mus_filtered_comb_unmodulated(mus_any *ptr, mus_float_t input)
{
dly *fc = (dly *)ptr;
return(mus_delay_unmodulated(ptr,
input + (fc->yscl *
mus_run(fc->filt,
fc->line[fc->loc],
0.0))));
}
static mus_any_class FILTERED_COMB_CLASS = {
MUS_FILTERED_COMB,
(char *)S_filtered_comb,
&free_delay,
&describe_filtered_comb,
&filtered_comb_equalp,
&delay_data,
&delay_set_data,
&delay_length,
&delay_set_length,
0, 0, 0, 0, /* freq phase */
&delay_scaler,
&delay_set_scaler,
&delay_fb,
&delay_set_fb,
&mus_filtered_comb,
MUS_DELAY_LINE,
NULL,
&delay_interp_type,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0,
&delay_loc,
0, 0,
0, 0, 0, 0, 0,
&filtered_comb_reset,
0, 0, 0
};
mus_any *mus_make_filtered_comb(mus_float_t scaler, int size, mus_float_t *line, int line_size, mus_interp_t type, mus_any *filt)
{
if (filt)
{
dly *fc;
fc = (dly *)mus_make_comb(scaler, size, line, line_size, type);
if (fc)
{
fc->core = &FILTERED_COMB_CLASS;
fc->filt = filt;
return((mus_any *)fc);
}
else return(NULL);
}
return(mus_make_comb(scaler, size, line, line_size, type));
}
/* ---------------- sawtooth et al ---------------- */
typedef struct {
mus_any_class *core;
mus_float_t current_value;
double freq, phase, base, width;
} sw;
static int free_sw(mus_any *ptr)
{
if (ptr) clm_free(ptr);
return(0);
}
mus_float_t mus_sawtooth_wave(mus_any *ptr, mus_float_t fm)
{
sw *gen = (sw *)ptr;
mus_float_t result;
result = gen->current_value;
gen->phase += (gen->freq + fm);
if ((gen->phase >= TWO_PI) || (gen->phase < 0.0))
{
gen->phase = fmod(gen->phase, TWO_PI);
if (gen->phase < 0.0) gen->phase += TWO_PI;
}
gen->current_value = gen->base * (gen->phase - M_PI);
return(result);
}
static mus_float_t run_sawtooth_wave(mus_any *ptr, mus_float_t fm, mus_float_t unused) {return(mus_sawtooth_wave(ptr, fm));}
bool mus_sawtooth_wave_p(mus_any *ptr)
{
return((ptr) &&
(ptr->core->type == MUS_SAWTOOTH_WAVE));
}
static mus_float_t sw_freq(mus_any *ptr) {return(mus_radians_to_hz(((sw *)ptr)->freq));}
static mus_float_t sw_set_freq(mus_any *ptr, mus_float_t val) {((sw *)ptr)->freq = mus_hz_to_radians(val); return(val);}
static mus_float_t sw_increment(mus_any *ptr) {return(((sw *)ptr)->freq);}
static mus_float_t sw_set_increment(mus_any *ptr, mus_float_t val) {((sw *)ptr)->freq = val; return(val);}
static mus_float_t sw_phase(mus_any *ptr) {return(fmod(((sw *)ptr)->phase, TWO_PI));}
static mus_float_t sw_set_phase(mus_any *ptr, mus_float_t val) {((sw *)ptr)->phase = val; return(val);}
static mus_float_t sw_width(mus_any *ptr) {return((((sw *)ptr)->width) / ( 2 * M_PI));}
static mus_float_t sw_set_width(mus_any *ptr, mus_float_t val) {((sw *)ptr)->width = (2 * M_PI * val); return(val);}
static mus_float_t sawtooth_scaler(mus_any *ptr) {return(((sw *)ptr)->base * M_PI);}
static mus_float_t sawtooth_set_scaler(mus_any *ptr, mus_float_t val) {((sw *)ptr)->base = val / M_PI; return(val);}
static bool sw_equalp(mus_any *p1, mus_any *p2)
{
sw *s1, *s2;
s1 = (sw *)p1;
s2 = (sw *)p2;
return((p1 == p2) ||
((s1) && (s2) &&
(s1->core->type == s2->core->type) &&
(s1->freq == s2->freq) &&
(s1->phase == s2->phase) &&
(s1->base == s2->base) &&
(s1->current_value == s2->current_value)));
}
static char *describe_sw(mus_any *ptr)
{
char *describe_buffer;
describe_buffer = (char *)clm_malloc(DESCRIBE_BUFFER_SIZE, "describe buffer");
mus_snprintf(describe_buffer, DESCRIBE_BUFFER_SIZE, "%s freq: %.3fHz, phase: %.3f, amp: %.3f",
mus_name(ptr),
mus_frequency(ptr),
mus_phase(ptr),
mus_scaler(ptr));
return(describe_buffer);
}
static void sawtooth_reset(mus_any *ptr)
{
sw *gen = (sw *)ptr;
gen->phase = M_PI;
gen->current_value = 0.0;
}
static mus_any_class SAWTOOTH_WAVE_CLASS = {
MUS_SAWTOOTH_WAVE,
(char *)S_sawtooth_wave,
&free_sw,
&describe_sw,
&sw_equalp,
0, 0, 0, 0,
&sw_freq,
&sw_set_freq,
&sw_phase,
&sw_set_phase,
&sawtooth_scaler,
&sawtooth_set_scaler,
&sw_increment,
&sw_set_increment,
&run_sawtooth_wave,
MUS_NOT_SPECIAL,
NULL, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0,
&sawtooth_reset,
0, 0, 0
};
mus_any *mus_make_sawtooth_wave(mus_float_t freq, mus_float_t amp, mus_float_t phase) /* M_PI as initial phase, normally */
{
sw *gen;
gen = (sw *)clm_calloc(1, sizeof(sw), S_make_sawtooth_wave);
gen->core = &SAWTOOTH_WAVE_CLASS;
gen->freq = mus_hz_to_radians(freq);
gen->base = (amp / M_PI);
gen->phase = phase;
gen->current_value = gen->base * (gen->phase - M_PI);
return((mus_any *)gen);
}
mus_float_t mus_square_wave(mus_any *ptr, mus_float_t fm)
{
sw *gen = (sw *)ptr;
mus_float_t result;
result = gen->current_value;
gen->phase += (gen->freq + fm);
if ((gen->phase >= TWO_PI) || (gen->phase < 0.0))
{
gen->phase = fmod(gen->phase, TWO_PI);
if (gen->phase < 0.0) gen->phase += TWO_PI;
}
if (gen->phase < gen->width)
gen->current_value = gen->base;
else gen->current_value = 0.0;
return(result);
}
bool mus_square_wave_p(mus_any *ptr)
{
return((ptr) &&
(ptr->core->type == MUS_SQUARE_WAVE));
}
static mus_float_t run_square_wave(mus_any *ptr, mus_float_t fm, mus_float_t unused) {return(mus_square_wave(ptr, fm));}
static mus_float_t square_wave_scaler(mus_any *ptr) {return(((sw *)ptr)->base);}
static mus_float_t square_wave_set_scaler(mus_any *ptr, mus_float_t val) {((sw *)ptr)->base = val; return(val);}
static void square_wave_reset(mus_any *ptr)
{
sw *gen = (sw *)ptr;
gen->phase = 0.0;
gen->current_value = gen->base;
}
static mus_any_class SQUARE_WAVE_CLASS = {
MUS_SQUARE_WAVE,
(char *)S_square_wave,
&free_sw,
&describe_sw,
&sw_equalp,
0, 0, 0, 0,
&sw_freq,
&sw_set_freq,
&sw_phase,
&sw_set_phase,
&square_wave_scaler,
&square_wave_set_scaler,
&sw_increment,
&sw_set_increment,
&run_square_wave,
MUS_NOT_SPECIAL,
NULL, 0,
0, 0,
&sw_width, &sw_set_width,
0, 0,
0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0,
&square_wave_reset,
0, 0, 0
};
mus_any *mus_make_square_wave(mus_float_t freq, mus_float_t amp, mus_float_t phase)
{
sw *gen;
gen = (sw *)clm_calloc(1, sizeof(sw), S_make_square_wave);
gen->core = &SQUARE_WAVE_CLASS;
gen->freq = mus_hz_to_radians(freq);
gen->base = amp;
gen->phase = phase;
gen->width = M_PI;
if (gen->phase < gen->width)
gen->current_value = gen->base;
else gen->current_value = 0.0;
return((mus_any *)gen);
}
mus_float_t mus_triangle_wave(mus_any *ptr, mus_float_t fm)
{
sw *gen = (sw *)ptr;
mus_float_t result;
result = gen->current_value;
gen->phase += (gen->freq + fm);
if ((gen->phase >= TWO_PI) || (gen->phase < 0.0))
{
gen->phase = fmod(gen->phase, TWO_PI);
if (gen->phase < 0.0) gen->phase += TWO_PI;
}
if (gen->phase < (M_PI / 2.0))
gen->current_value = gen->base * gen->phase;
else
if (gen->phase < (M_PI * 1.5))
gen->current_value = gen->base * (M_PI - gen->phase);
else gen->current_value = gen->base * (gen->phase - TWO_PI);
return(result);
}
bool mus_triangle_wave_p(mus_any *ptr)
{
return((ptr) &&
(ptr->core->type == MUS_TRIANGLE_WAVE));
}
static mus_float_t run_triangle_wave(mus_any *ptr, mus_float_t fm, mus_float_t unused) {return(mus_triangle_wave(ptr, fm));}
static mus_float_t triangle_wave_scaler(mus_any *ptr) {return(((sw *)ptr)->base * M_PI_2);}
static mus_float_t triangle_wave_set_scaler(mus_any *ptr, mus_float_t val) {((sw *)ptr)->base = (val * 2.0 / M_PI); return(val);}
static void triangle_wave_reset(mus_any *ptr)
{
sw *gen = (sw *)ptr;
gen->phase = 0.0;
gen->current_value = 0.0;
}
static mus_any_class TRIANGLE_WAVE_CLASS = {
MUS_TRIANGLE_WAVE,
(char *)S_triangle_wave,
&free_sw,
&describe_sw,
&sw_equalp,
0, 0, 0, 0,
&sw_freq,
&sw_set_freq,
&sw_phase,
&sw_set_phase,
&triangle_wave_scaler,
&triangle_wave_set_scaler,
&sw_increment,
&sw_set_increment,
&run_triangle_wave,
MUS_NOT_SPECIAL,
NULL, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0,
&triangle_wave_reset,
0, 0, 0
};
mus_any *mus_make_triangle_wave(mus_float_t freq, mus_float_t amp, mus_float_t phase)
{
sw *gen;
gen = (sw *)clm_calloc(1, sizeof(sw), S_make_triangle_wave);
gen->core = &TRIANGLE_WAVE_CLASS;
gen->freq = mus_hz_to_radians(freq);
gen->base = (2.0 * amp / M_PI);
gen->phase = phase;
if (gen->phase < M_PI_2)
gen->current_value = gen->base * gen->phase;
else
if (gen->phase < (M_PI * 1.5))
gen->current_value = gen->base * (M_PI - gen->phase);
else gen->current_value = gen->base * (gen->phase - TWO_PI);
return((mus_any *)gen);
}
mus_float_t mus_pulse_train(mus_any *ptr, mus_float_t fm)
{
sw *gen = (sw *)ptr;
if ((gen->phase >= TWO_PI) || (gen->phase < 0.0))
{
gen->phase = fmod(gen->phase, TWO_PI);
if (gen->phase < 0.0) gen->phase += TWO_PI;
gen->current_value = gen->base;
}
else gen->current_value = 0.0;
gen->phase += (gen->freq + fm);
return(gen->current_value);
}
bool mus_pulse_train_p(mus_any *ptr)
{
return((ptr) &&
(ptr->core->type == MUS_PULSE_TRAIN));
}
static mus_float_t run_pulse_train(mus_any *ptr, mus_float_t fm, mus_float_t unused) {return(mus_pulse_train(ptr, fm));}
static mus_float_t pulse_train_scaler(mus_any *ptr) {return(((sw *)ptr)->base);}
static mus_float_t pulse_train_set_scaler(mus_any *ptr, mus_float_t val) {((sw *)ptr)->base = val; return(val);}
static void pulse_train_reset(mus_any *ptr)
{
sw *gen = (sw *)ptr;
gen->phase = TWO_PI;
gen->current_value = 0.0;
}
static mus_any_class PULSE_TRAIN_CLASS = {
MUS_PULSE_TRAIN,
(char *)S_pulse_train,
&free_sw,
&describe_sw,
&sw_equalp,
0, 0, 0, 0,
&sw_freq,
&sw_set_freq,
&sw_phase,
&sw_set_phase,
&pulse_train_scaler,
&pulse_train_set_scaler,
&sw_increment,
&sw_set_increment,
&run_pulse_train,
MUS_NOT_SPECIAL,
NULL, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0,
&pulse_train_reset,
0, 0, 0
};
mus_any *mus_make_pulse_train(mus_float_t freq, mus_float_t amp, mus_float_t phase) /* TWO_PI initial phase, normally */
{
sw *gen;
gen = (sw *)clm_calloc(1, sizeof(sw), S_make_pulse_train);
gen->core = &PULSE_TRAIN_CLASS;
gen->freq = mus_hz_to_radians(freq);
gen->base = amp;
gen->phase = phase;
gen->current_value = 0.0;
return((mus_any *)gen);
}
/* ---------------- rand, rand_interp ---------------- */
typedef struct {
mus_any_class *core;
double freq, phase, base, incr;
mus_float_t output;
mus_float_t *distribution;
int distribution_size;
} noi;
/* rand taken from the ANSI C standard (essentially the same as the Cmix form used earlier) */
static unsigned long randx = 1;
#define INVERSE_MAX_RAND 0.0000610351563
#define INVERSE_MAX_RAND2 0.000030517579
void mus_set_rand_seed(unsigned long val) {randx = val;}
unsigned long mus_rand_seed(void) {return(randx);}
static mus_float_t next_random(void)
{
randx = randx * 1103515245 + 12345;
return((mus_float_t)((unsigned int)(randx >> 16) & 32767));
}
mus_float_t mus_random(mus_float_t amp) /* -amp to amp as mus_float_t */
{
return(amp * (next_random() * INVERSE_MAX_RAND - 1.0));
}
mus_float_t mus_random_no_input(void) /* -1.0 to 1.0 as mus_float_t */
{
return(next_random() * INVERSE_MAX_RAND - 1.0);
}
mus_float_t mus_frandom(mus_float_t amp) /* 0.0 to amp as mus_float_t */
{
return(amp * next_random() * INVERSE_MAX_RAND2);
}
mus_float_t mus_frandom_no_input(void) /* 0.0 to 1.0 as mus_float_t */
{
return(next_random() * INVERSE_MAX_RAND2);
}
int mus_irandom(int amp)
{
return((int)(amp * next_random() * INVERSE_MAX_RAND2));
}
static mus_float_t random_any(noi *gen) /* -amp to amp possibly through distribution */
{
if (gen->distribution)
return(gen->base * mus_array_interp(gen->distribution,
next_random() * INVERSE_MAX_RAND2 * gen->distribution_size,
gen->distribution_size));
return(gen->base * (next_random() * INVERSE_MAX_RAND - 1.0));
}
mus_float_t mus_rand(mus_any *ptr, mus_float_t fm)
{
noi *gen = (noi *)ptr;
if ((gen->phase >= TWO_PI) || (gen->phase < 0.0))
{
gen->phase = fmod(gen->phase, TWO_PI);
if (gen->phase < 0.0) gen->phase += TWO_PI;
gen->output = random_any(gen);
}
gen->phase += (gen->freq + fm);
return(gen->output);
}
mus_float_t mus_rand_interp(mus_any *ptr, mus_float_t fm)
{
/* fm can change the increment step during a ramp */
noi *gen = (noi *)ptr;
gen->output += gen->incr;
if (gen->output > gen->base)
gen->output = gen->base;
else
{
if (gen->output < -gen->base)
gen->output = -gen->base;
}
if ((gen->phase >= TWO_PI) || (gen->phase < 0.0))
{
gen->phase = fmod(gen->phase, TWO_PI);
if (gen->phase < 0.0) gen->phase += TWO_PI;
gen->incr = (random_any(gen) - gen->output) / (ceil(TWO_PI / (gen->freq + fm)));
}
gen->phase += (gen->freq + fm);
return(gen->output);
}
static mus_float_t run_rand(mus_any *ptr, mus_float_t fm, mus_float_t unused) {return(mus_rand(ptr, fm));}
static mus_float_t run_rand_interp(mus_any *ptr, mus_float_t fm, mus_float_t unused) {return(mus_rand_interp(ptr, fm));}
bool mus_rand_p(mus_any *ptr)
{
return((ptr) &&
(ptr->core->type == MUS_RAND));
}
bool mus_rand_interp_p(mus_any *ptr)
{
return((ptr) &&
(ptr->core->type == MUS_RAND_INTERP));
}
static int free_noi(mus_any *ptr) {if (ptr) clm_free(ptr); return(0);}
static mus_float_t noi_freq(mus_any *ptr) {return(mus_radians_to_hz(((noi *)ptr)->freq));}
static mus_float_t noi_set_freq(mus_any *ptr, mus_float_t val) {((noi *)ptr)->freq = mus_hz_to_radians(val); return(val);}
static mus_float_t noi_increment(mus_any *ptr) {return(((noi *)ptr)->freq);}
static mus_float_t noi_set_increment(mus_any *ptr, mus_float_t val) {((noi *)ptr)->freq = val; return(val);}
static mus_float_t noi_phase(mus_any *ptr) {return(fmod(((noi *)ptr)->phase, TWO_PI));}
static mus_float_t noi_set_phase(mus_any *ptr, mus_float_t val) {((noi *)ptr)->phase = val; return(val);}
static mus_float_t noi_scaler(mus_any *ptr) {return(((noi *)ptr)->base);}
static mus_float_t noi_set_scaler(mus_any *ptr, mus_float_t val) {((noi *)ptr)->base = val; return(val);}
static mus_float_t *noi_data(mus_any *ptr) {return(((noi *)ptr)->distribution);}
static mus_long_t noi_length(mus_any *ptr) {return(((noi *)ptr)->distribution_size);}
static void noi_reset(mus_any *ptr)
{
noi *gen = (noi *)ptr;
gen->phase = 0.0;
gen->output = 0.0;
}
static bool noi_equalp(mus_any *p1, mus_any *p2)
{
noi *g1 = (noi *)p1;
noi *g2 = (noi *)p2;
return((p1 == p2) ||
((g1) && (g2) &&
(g1->core->type == g2->core->type) &&
(g1->freq == g2->freq) &&
(g1->phase == g2->phase) &&
(g1->output == g2->output) &&
(g1->incr == g2->incr) &&
(g1->base == g2->base) &&
(g1->distribution_size == g2->distribution_size) &&
(g1->distribution == g2->distribution)));
}
static char *describe_noi(mus_any *ptr)
{
noi *gen = (noi *)ptr;
char *describe_buffer;
describe_buffer = (char *)clm_malloc(DESCRIBE_BUFFER_SIZE, "describe buffer");
if (mus_rand_p(ptr))
mus_snprintf(describe_buffer, DESCRIBE_BUFFER_SIZE, "%s freq: %.3fHz, phase: %.3f, amp: %.3f%s",
mus_name(ptr),
mus_frequency(ptr),
mus_phase(ptr),
mus_scaler(ptr),
(gen->distribution) ? ", with distribution envelope" : "");
else
mus_snprintf(describe_buffer, DESCRIBE_BUFFER_SIZE, "%s freq: %.3fHz, phase: %.3f, amp: %.3f, incr: %.3f, curval: %.3f%s",
mus_name(ptr),
mus_frequency(ptr),
mus_phase(ptr),
mus_scaler(ptr),
gen->incr,
gen->output,
(gen->distribution) ? ", with distribution envelope" : "");
return(describe_buffer);
}
static mus_any_class RAND_INTERP_CLASS = {
MUS_RAND_INTERP,
(char *)S_rand_interp,
&free_noi,
&describe_noi,
&noi_equalp,
&noi_data, 0,
&noi_length, 0,
&noi_freq,
&noi_set_freq,
&noi_phase,
&noi_set_phase,
&noi_scaler,
&noi_set_scaler,
&noi_increment, /* (phase increment) */
&noi_set_increment,
&run_rand_interp,
MUS_NOT_SPECIAL,
NULL, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0,
&noi_reset,
0, 0, 0
};
static mus_any_class RAND_CLASS = {
MUS_RAND,
(char *)S_rand,
&free_noi,
&describe_noi,
&noi_equalp,
&noi_data, 0,
&noi_length, 0,
&noi_freq,
&noi_set_freq,
&noi_phase,
&noi_set_phase,
&noi_scaler,
&noi_set_scaler,
&noi_increment, /* (phase increment) */
&noi_set_increment,
&run_rand,
MUS_NOT_SPECIAL,
NULL, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0,
&noi_reset,
0, 0, 0
};
mus_any *mus_make_rand(mus_float_t freq, mus_float_t base)
{
noi *gen;
gen = (noi *)clm_calloc(1, sizeof(noi), S_make_rand);
gen->core = &RAND_CLASS;
gen->freq = mus_hz_to_radians(freq);
gen->base = base;
gen->incr = 0.0;
gen->output = random_any(gen); /* this was always starting at 0.0 (changed 23-Dec-06) */
return((mus_any *)gen);
}
mus_any *mus_make_rand_interp(mus_float_t freq, mus_float_t base)
{
noi *gen;
gen = (noi *)clm_calloc(1, sizeof(noi), S_make_rand_interp);
gen->core = &RAND_INTERP_CLASS;
gen->freq = mus_hz_to_radians(freq);
gen->base = base;
gen->incr = mus_random(base) * freq / sampling_rate;
gen->output = 0.0;
return((mus_any *)gen);
}
mus_any *mus_make_rand_with_distribution(mus_float_t freq, mus_float_t base, mus_float_t *distribution, int distribution_size)
{
noi *gen;
gen = (noi *)mus_make_rand(freq, base);
gen->distribution = distribution;
gen->distribution_size = distribution_size;
gen->output = random_any(gen);
return((mus_any *)gen);
}
mus_any *mus_make_rand_interp_with_distribution(mus_float_t freq, mus_float_t base, mus_float_t *distribution, int distribution_size)
{
noi *gen;
gen = (noi *)mus_make_rand_interp(freq, base);
gen->distribution = distribution;
gen->distribution_size = distribution_size;
return((mus_any *)gen);
}
/* ---------------- simple filters ---------------- */
typedef struct {
mus_any_class *core;
mus_float_t xs[3];
mus_float_t ys[3];
mus_float_t x1, x2, y1, y2;
} smpflt;
static int free_smpflt(mus_any *ptr)
{
if (ptr) clm_free(ptr);
return(0);
}
static bool smpflt_equalp(mus_any *p1, mus_any *p2)
{
smpflt *g1 = (smpflt *)p1;
smpflt *g2 = (smpflt *)p2;
return((p1 == p2) ||
((g1->core->type == g2->core->type) &&
(g1->xs[0] == g2->xs[0]) &&
(g1->xs[1] == g2->xs[1]) &&
(g1->xs[2] == g2->xs[2]) &&
(g1->ys[1] == g2->ys[1]) &&
(g1->ys[2] == g2->ys[2]) &&
(g1->x1 == g2->x1) &&
(g1->x2 == g2->x2) &&
(g1->y1 == g2->y1) &&
(g1->y2 == g2->y2)));
}
static char *describe_smpflt(mus_any *ptr)
{
smpflt *gen = (smpflt *)ptr;
char *describe_buffer;
describe_buffer = (char *)clm_malloc(DESCRIBE_BUFFER_SIZE, "describe buffer");
switch (gen->core->type)
{
case MUS_ONE_ZERO:
mus_snprintf(describe_buffer, DESCRIBE_BUFFER_SIZE, "%s a0: %.3f, a1: %.3f, x1: %.3f",
mus_name(ptr),
gen->xs[0], gen->xs[1], gen->x1);
break;
case MUS_ONE_POLE:
mus_snprintf(describe_buffer, DESCRIBE_BUFFER_SIZE, "%s a0: %.3f, b1: %.3f, y1: %.3f",
mus_name(ptr),
gen->xs[0], gen->ys[1], gen->y1);
break;
case MUS_TWO_ZERO:
mus_snprintf(describe_buffer, DESCRIBE_BUFFER_SIZE, "%s a0: %.3f, a1: %.3f, a2: %.3f, x1: %.3f, x2: %.3f",
mus_name(ptr),
gen->xs[0], gen->xs[1], gen->xs[2], gen->x1, gen->x2);
break;
case MUS_TWO_POLE:
mus_snprintf(describe_buffer, DESCRIBE_BUFFER_SIZE, "%s a0: %.3f, b1: %.3f, b2: %.3f, y1: %.3f, y2: %.3f",
mus_name(ptr),
gen->xs[0], gen->ys[1], gen->ys[2], gen->y1, gen->y2);
break;
}
return(describe_buffer);
}
mus_float_t mus_one_zero(mus_any *ptr, mus_float_t input)
{
smpflt *gen = (smpflt *)ptr;
mus_float_t result;
result = (gen->xs[0] * input) + (gen->xs[1] * gen->x1);
gen->x1 = input;
return(result);
}
static mus_float_t run_one_zero(mus_any *ptr, mus_float_t input, mus_float_t unused) {return(mus_one_zero(ptr, input));}
static mus_long_t one_length(mus_any *ptr) {return(1);}
static mus_long_t two_length(mus_any *ptr) {return(2);}
static mus_float_t smp_xcoeff(mus_any *ptr, int index) {return(((smpflt *)ptr)->xs[index]);}
static mus_float_t smp_set_xcoeff(mus_any *ptr, int index, mus_float_t val) {((smpflt *)ptr)->xs[index] = val; return(val);}
static mus_float_t smp_ycoeff(mus_any *ptr, int index) {return(((smpflt *)ptr)->ys[index]);}
static mus_float_t smp_set_ycoeff(mus_any *ptr, int index, mus_float_t val) {((smpflt *)ptr)->ys[index] = val; return(val);}
static mus_float_t *smp_xcoeffs(mus_any *ptr) {return(((smpflt *)ptr)->xs);}
static mus_float_t *smp_ycoeffs(mus_any *ptr) {return(((smpflt *)ptr)->ys);}
static void smpflt_reset(mus_any *ptr)
{
smpflt *gen = (smpflt *)ptr;
gen->x1 = 0.0;
gen->x2 = 0.0;
gen->y1 = 0.0;
gen->y2 = 0.0;
}
static mus_any_class ONE_ZERO_CLASS = {
MUS_ONE_ZERO,
(char *)S_one_zero,
&free_smpflt,
&describe_smpflt,
&smpflt_equalp,
0, 0,
&one_length, 0,
0, 0, 0, 0,
0, 0,
0, 0,
&run_one_zero,
MUS_SIMPLE_FILTER,
NULL, 0,
0, 0,
0, 0,
&smp_xcoeff, &smp_set_xcoeff,
0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0,
0, 0,
&smp_xcoeffs, &smp_ycoeffs, 0,
&smpflt_reset,
0, 0, 0
};
mus_any *mus_make_one_zero(mus_float_t a0, mus_float_t a1)
{
smpflt *gen;
gen = (smpflt *)clm_calloc(1, sizeof(smpflt), S_make_one_zero);
gen->core = &ONE_ZERO_CLASS;
gen->xs[0] = a0;
gen->xs[1] = a1;
return((mus_any *)gen);
}
bool mus_one_zero_p(mus_any *ptr)
{
return((ptr) &&
(ptr->core->type == MUS_ONE_ZERO));
}
mus_float_t mus_one_pole(mus_any *ptr, mus_float_t input)
{
smpflt *gen = (smpflt *)ptr;
gen->y1 = (gen->xs[0] * input) - (gen->ys[1] * gen->y1);
return(gen->y1);
}
static mus_float_t run_one_pole(mus_any *ptr, mus_float_t input, mus_float_t unused) {return(mus_one_pole(ptr, input));}
static mus_any_class ONE_POLE_CLASS = {
MUS_ONE_POLE,
(char *)S_one_pole,
&free_smpflt,
&describe_smpflt,
&smpflt_equalp,
0, 0,
&one_length, 0,
0, 0, 0, 0,
0, 0, 0, 0,
&run_one_pole,
MUS_SIMPLE_FILTER,
NULL, 0,
0, 0, 0, 0,
&smp_xcoeff, &smp_set_xcoeff,
0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0,
&smp_ycoeff, &smp_set_ycoeff,
&smp_xcoeffs, &smp_ycoeffs, 0,
&smpflt_reset,
0, 0, 0
};
mus_any *mus_make_one_pole(mus_float_t a0, mus_float_t b1)
{
smpflt *gen;
gen = (smpflt *)clm_calloc(1, sizeof(smpflt), S_make_one_pole);
gen->core = &ONE_POLE_CLASS;
gen->xs[0] = a0;
gen->ys[1] = b1;
return((mus_any *)gen);
}
bool mus_one_pole_p(mus_any *ptr)
{
return((ptr) &&
(ptr->core->type == MUS_ONE_POLE));
}
mus_float_t mus_two_zero(mus_any *ptr, mus_float_t input)
{
smpflt *gen = (smpflt *)ptr;
mus_float_t result;
result = (gen->xs[0] * input) + (gen->xs[1] * gen->x1) + (gen->xs[2] * gen->x2);
gen->x2 = gen->x1;
gen->x1 = input;
return(result);
}
static mus_float_t run_two_zero(mus_any *ptr, mus_float_t input, mus_float_t unused) {return(mus_two_zero(ptr, input));}
static mus_float_t two_zero_radius(mus_any *ptr)
{
smpflt *gen = (smpflt *)ptr;
return(sqrt(gen->xs[2]));
}
static mus_float_t two_zero_set_radius(mus_any *ptr, mus_float_t new_radius)
{
smpflt *gen = (smpflt *)ptr;
gen->xs[1] = -2.0 * new_radius * cos(mus_hz_to_radians(mus_frequency(ptr)));
gen->xs[2] = new_radius * new_radius;
return(new_radius);
}
static mus_float_t two_zero_frequency(mus_any *ptr)
{
smpflt *gen = (smpflt *)ptr;
return(mus_radians_to_hz(acos(gen->xs[1] / (-2.0 * two_zero_radius(ptr)))));
}
static mus_float_t two_zero_set_frequency(mus_any *ptr, mus_float_t new_freq)
{
smpflt *gen = (smpflt *)ptr;
gen->xs[1] = -2.0 * mus_scaler(ptr) * cos(mus_hz_to_radians(new_freq));
return(new_freq);
}
static mus_any_class TWO_ZERO_CLASS = {
MUS_TWO_ZERO,
(char *)S_two_zero,
&free_smpflt,
&describe_smpflt,
&smpflt_equalp,
0, 0,
&two_length, 0,
&two_zero_frequency, &two_zero_set_frequency,
0, 0,
&two_zero_radius, &two_zero_set_radius,
0, 0,
&run_two_zero,
MUS_SIMPLE_FILTER,
NULL, 0,
0, 0, 0, 0,
&smp_xcoeff, &smp_set_xcoeff,
0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0,
0, 0,
&smp_xcoeffs, &smp_ycoeffs, 0,
&smpflt_reset,
0, 0, 0
};
mus_any *mus_make_two_zero(mus_float_t a0, mus_float_t a1, mus_float_t a2)
{
smpflt *gen;
gen = (smpflt *)clm_calloc(1, sizeof(smpflt), S_make_two_zero);
gen->core = &TWO_ZERO_CLASS;
gen->xs[0] = a0;
gen->xs[1] = a1;
gen->xs[2] = a2;
return((mus_any *)gen);
}
bool mus_two_zero_p(mus_any *ptr)
{
return((ptr) &&
(ptr->core->type == MUS_TWO_ZERO));
}
mus_any *mus_make_two_zero_from_frequency_and_radius(mus_float_t frequency, mus_float_t radius)
{
return(mus_make_two_zero(1.0, -2.0 * radius * cos(mus_hz_to_radians(frequency)), radius * radius));
}
mus_float_t mus_two_pole(mus_any *ptr, mus_float_t input)
{
smpflt *gen = (smpflt *)ptr;
mus_float_t result;
result = (gen->xs[0] * input) - (gen->ys[1] * gen->y1) - (gen->ys[2] * gen->y2);
gen->y2 = gen->y1;
gen->y1 = result;
return(result);
}
static mus_float_t run_two_pole(mus_any *ptr, mus_float_t input, mus_float_t unused) {return(mus_two_pole(ptr, input));}
static mus_float_t two_pole_radius(mus_any *ptr)
{
smpflt *gen = (smpflt *)ptr;
return(sqrt(gen->ys[2]));
}
static mus_float_t two_pole_set_radius(mus_any *ptr, mus_float_t new_radius)
{
smpflt *gen = (smpflt *)ptr;
gen->ys[1] = -2.0 * new_radius * cos(mus_hz_to_radians(mus_frequency(ptr)));
gen->ys[2] = new_radius * new_radius;
return(new_radius);
}
static mus_float_t two_pole_frequency(mus_any *ptr)
{
smpflt *gen = (smpflt *)ptr;
return(mus_radians_to_hz(acos(gen->ys[1] / (-2.0 * two_pole_radius(ptr)))));
}
static mus_float_t two_pole_set_frequency(mus_any *ptr, mus_float_t new_freq)
{
smpflt *gen = (smpflt *)ptr;
gen->ys[1] = -2.0 * mus_scaler(ptr) * cos(mus_hz_to_radians(new_freq));
return(new_freq);
}
static mus_any_class TWO_POLE_CLASS = {
MUS_TWO_POLE,
(char *)S_two_pole,
&free_smpflt,
&describe_smpflt,
&smpflt_equalp,
0, 0,
&two_length, 0,
&two_pole_frequency, &two_pole_set_frequency,
0, 0,
&two_pole_radius, &two_pole_set_radius,
0, 0,
&run_two_pole,
MUS_SIMPLE_FILTER,
NULL, 0,
0, 0, 0, 0,
&smp_xcoeff, &smp_set_xcoeff,
0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0,
&smp_ycoeff, &smp_set_ycoeff,
&smp_xcoeffs, &smp_ycoeffs, 0,
&smpflt_reset,
0, 0, 0
};
mus_any *mus_make_two_pole(mus_float_t a0, mus_float_t b1, mus_float_t b2)
{
if (fabs(b1) >= 2.0)
mus_error(MUS_UNSTABLE_TWO_POLE_ERROR, S_make_two_pole ": b1 = %.3f", b1);
else
{
if (fabs(b2) >= 1.0)
mus_error(MUS_UNSTABLE_TWO_POLE_ERROR, S_make_two_pole ": b2 = %.3f", b2);
else
{
if ( ((b1 * b1) - (b2 * 4.0) >= 0.0) &&
( ((b1 + b2) >= 1.0) ||
((b2 - b1) >= 1.0)))
mus_error(MUS_UNSTABLE_TWO_POLE_ERROR, S_make_two_pole ": b1 = %.3f, b2 = %.3f", b1, b2);
else
{
smpflt *gen;
gen = (smpflt *)clm_calloc(1, sizeof(smpflt), S_make_two_pole);
gen->core = &TWO_POLE_CLASS;
gen->xs[0] = a0;
gen->ys[1] = b1;
gen->ys[2] = b2;
return((mus_any *)gen);
}
}
}
return(NULL);
}
bool mus_two_pole_p(mus_any *ptr)
{
return((ptr) &&
(ptr->core->type == MUS_TWO_POLE));
}
mus_any *mus_make_two_pole_from_frequency_and_radius(mus_float_t frequency, mus_float_t radius)
{
return(mus_make_two_pole(1.0, -2.0 * radius * cos(mus_hz_to_radians(frequency)), radius * radius));
}
/* ---------------- formant ---------------- */
typedef struct {
mus_any_class *core;
mus_float_t frequency, radius;
mus_float_t x1, x2, y1, y2;
mus_float_t rr, gain, fdbk;
} frm;
static int free_frm(mus_any *ptr)
{
if (ptr) clm_free(ptr);
return(0);
}
bool mus_formant_p(mus_any *ptr)
{
return((ptr) &&
(ptr->core->type == MUS_FORMANT));
}
static void frm_reset(mus_any *ptr)
{
frm *gen = (frm *)ptr;
gen->x1 = 0.0;
gen->x2 = 0.0;
gen->y1 = 0.0;
gen->y2 = 0.0;
}
static bool frm_equalp(mus_any *p1, mus_any *p2)
{
frm *g1 = (frm *)p1;
frm *g2 = (frm *)p2;
return((p1 == p2) ||
((g1->core->type == g2->core->type) &&
(g1->radius == g2->radius) &&
(g1->frequency == g2->frequency) &&
(g1->x1 == g2->x1) &&
(g1->x2 == g2->x2) &&
(g1->y1 == g2->y1) &&
(g1->y2 == g2->y2)));
}
static char *describe_formant(mus_any *ptr)
{
frm *gen = (frm *)ptr;
char *describe_buffer;
describe_buffer = (char *)clm_malloc(DESCRIBE_BUFFER_SIZE, "describe buffer");
mus_snprintf(describe_buffer, DESCRIBE_BUFFER_SIZE, "%s frequency: %.3f, radius: %.3f",
mus_name(ptr),
mus_radians_to_hz(gen->frequency),
gen->radius);
return(describe_buffer);
}
mus_float_t mus_formant(mus_any *ptr, mus_float_t input)
{
frm *gen = (frm *)ptr;
mus_float_t x0, y0;
x0 = gen->gain * input;
y0 = x0 - gen->x2 + (gen->fdbk * gen->y1) - (gen->rr * gen->y2);
gen->y2 = gen->y1;
gen->y1 = y0;
gen->x2 = gen->x1;
gen->x1 = x0;
return(y0);
}
static mus_float_t run_formant(mus_any *ptr, mus_float_t input, mus_float_t unused) {return(mus_formant(ptr, input));}
mus_float_t mus_formant_bank(mus_float_t *amps, mus_any **formants, mus_float_t inval, int size)
{
int i;
mus_float_t sum = 0.0;
for (i = 0; i < size; i++)
sum += (amps[i] * mus_formant(formants[i], inval));
return(sum);
}
static void mus_set_formant_radius_and_frequency_in_radians(mus_any *ptr, mus_float_t radius, mus_float_t freq_in_radians)
{
frm *gen = (frm *)ptr;
gen->radius = radius;
gen->frequency = freq_in_radians;
gen->rr = radius * radius;
gen->gain = (1.0 - gen->rr) * 0.5;
gen->fdbk = 2.0 * radius * cos(freq_in_radians);
}
void mus_set_formant_radius_and_frequency(mus_any *ptr, mus_float_t radius, mus_float_t freq_in_hz)
{
mus_set_formant_radius_and_frequency_in_radians(ptr, radius, mus_hz_to_radians(freq_in_hz));
}
static mus_float_t formant_frequency(mus_any *ptr) {return(mus_radians_to_hz(((frm *)ptr)->frequency));}
static mus_float_t formant_set_frequency(mus_any *ptr, mus_float_t freq_in_hz)
{
frm *gen = (frm *)ptr;
mus_float_t fw;
fw = mus_hz_to_radians(freq_in_hz);
gen->frequency = fw;
gen->fdbk = 2.0 * gen->radius * cos(fw);
return(freq_in_hz);
}
mus_float_t mus_formant_with_frequency(mus_any *ptr, mus_float_t input, mus_float_t freq_in_radians)
{
frm *gen = (frm *)ptr;
gen->frequency = freq_in_radians;
gen->fdbk = 2.0 * gen->radius * cos(freq_in_radians);
return(mus_formant(ptr, input));
}
static mus_float_t formant_radius(mus_any *ptr) {return(((frm *)ptr)->radius);}
static mus_float_t formant_set_radius(mus_any *ptr, mus_float_t val)
{
mus_set_formant_radius_and_frequency_in_radians(ptr, val, ((frm *)ptr)->frequency);
return(val);
}
static mus_any_class FORMANT_CLASS = {
MUS_FORMANT,
(char *)S_formant,
&free_frm,
&describe_formant,
&frm_equalp,
0, 0,
&two_length, 0,
&formant_frequency, &formant_set_frequency,
0, 0,
&formant_radius, &formant_set_radius,
0, 0,
&run_formant,
MUS_SIMPLE_FILTER,
NULL, 0,
0, 0, 0, 0,
0, 0,
0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0,
&frm_reset,
0, 0, 0
};
mus_any *mus_make_formant(mus_float_t frequency, mus_float_t radius)
{
frm *gen;
gen = (frm *)clm_calloc(1, sizeof(frm), S_make_formant);
gen->core = &FORMANT_CLASS;
mus_set_formant_radius_and_frequency((mus_any *)gen, radius, frequency);
return((mus_any *)gen);
}
/* ---------------- firmant ---------------- */
static char *describe_firmant(mus_any *ptr)
{
frm *gen = (frm *)ptr;
char *describe_buffer;
describe_buffer = (char *)clm_malloc(DESCRIBE_BUFFER_SIZE, "describe buffer");
mus_snprintf(describe_buffer, DESCRIBE_BUFFER_SIZE, "%s frequency: %.3f, radius: %.3f",
mus_name(ptr),
mus_radians_to_hz(gen->frequency),
gen->radius);
return(describe_buffer);
}
static mus_float_t firmant_frequency(mus_any *ptr) {return(mus_radians_to_hz(((frm *)ptr)->frequency));}
static mus_float_t firmant_set_frequency(mus_any *ptr, mus_float_t freq_in_hz)
{
frm *gen = (frm *)ptr;
mus_float_t fw;
fw = mus_hz_to_radians(freq_in_hz);
gen->frequency = fw;
gen->fdbk = 2.0 * sin(gen->frequency * 0.5);
return(freq_in_hz);
}
static mus_float_t firmant_radius(mus_any *ptr) {return(((frm *)ptr)->radius);}
static mus_float_t firmant_set_radius(mus_any *ptr, mus_float_t radius)
{
frm *gen = (frm *)ptr;
gen->radius = radius;
gen->gain = 1.0 - radius * radius;
return(radius);
}
bool mus_firmant_p(mus_any *ptr)
{
return((ptr) &&
(ptr->core->type == MUS_FIRMANT));
}
mus_float_t mus_firmant(mus_any *ptr, mus_float_t input)
{
frm *gen = (frm *)ptr;
mus_float_t xn1, yn1;
xn1 = gen->gain * input + gen->radius * (gen->x1 - gen->fdbk * gen->y1);
yn1 = gen->radius * (gen->fdbk * xn1 + gen->y1);
gen->x1 = xn1;
gen->y1 = yn1;
return(yn1);
}
mus_float_t mus_firmant_with_frequency(mus_any *ptr, mus_float_t input, mus_float_t freq_in_radians)
{
frm *gen = (frm *)ptr;
gen->frequency = freq_in_radians;
gen->fdbk = 2.0 * sin(gen->frequency * 0.5);
return(mus_firmant(ptr, input));
}
static mus_float_t run_firmant(mus_any *ptr, mus_float_t input, mus_float_t unused) {return(mus_firmant(ptr, input));}
static mus_any_class FIRMANT_CLASS = {
MUS_FIRMANT,
(char *)S_firmant,
&free_frm,
&describe_firmant,
&frm_equalp,
0, 0,
&two_length, 0,
&firmant_frequency, &firmant_set_frequency,
0, 0,
&firmant_radius, &firmant_set_radius,
0, 0,
&run_firmant,
MUS_SIMPLE_FILTER,
NULL, 0,
0, 0, 0, 0,
0, 0,
0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0,
&frm_reset,
0, 0, 0
};
mus_any *mus_make_firmant(mus_float_t frequency, mus_float_t radius)
{
frm *gen;
gen = (frm *)clm_calloc(1, sizeof(frm), S_make_firmant);
gen->core = &FIRMANT_CLASS;
gen->frequency = mus_hz_to_radians(frequency);
gen->radius = radius;
gen->fdbk = 2.0 * sin(gen->frequency * 0.5);
gen->gain = 1.0 - radius * radius;
return((mus_any *)gen);
}
/* ---------------- filter ---------------- */
typedef struct {
mus_any_class *core;
int order, allocated_size;
bool state_allocated;
mus_float_t *x, *y, *state;
} flt;
/* handling symmetric coeffs to reduce multiplies was actually slower than the normal form */
mus_float_t mus_filter(mus_any *ptr, mus_float_t input)
{
flt *gen = (flt *)ptr;
mus_float_t xout = 0.0;
mus_float_t *xp, *yp, *dp, *d, *dprev;
if (!(gen->y)) return(mus_fir_filter(ptr, input));
if (!(gen->x)) return(mus_iir_filter(ptr, input));
xp = (mus_float_t *)(gen->x + gen->order - 1);
yp = (mus_float_t *)(gen->y + gen->order - 1);
dp = (mus_float_t *)(gen->state + gen->order - 1);
d = gen->state;
d[0] = input;
while (dp > d)
{
xout += (*dp) * (*xp--);
d[0] -= (*dp) * (*yp--);
dprev = dp--;
(*dprev) = (*dp);
}
return(xout + (d[0] * (*xp)));
}
mus_float_t mus_fir_filter(mus_any *ptr, mus_float_t input)
{
mus_float_t xout = 0.0;
flt *gen = (flt *)ptr;
mus_float_t *ap, *dp, *d, *dprev;
ap = (mus_float_t *)(gen->x + gen->order - 1);
dp = (mus_float_t *)(gen->state + gen->order - 1);
d = gen->state;
(*d) = input;
while (dp > d)
{
xout += (*dp) * (*ap--);
dprev = dp--;
(*dprev) = (*dp);
}
return(xout + (input * (*ap)));
}
mus_float_t mus_iir_filter(mus_any *ptr, mus_float_t input)
{
flt *gen = (flt *)ptr;
mus_float_t *ap, *dp, *d, *dprev;
ap = (mus_float_t *)(gen->y + gen->order - 1);
dp = (mus_float_t *)(gen->state + gen->order - 1);
d = gen->state;
(*d) = input;
while (dp > d)
{
(*d) -= (*dp) * (*ap--);
dprev = dp--;
(*dprev) = (*dp);
}
return(*d);
}
static mus_float_t run_filter(mus_any *ptr, mus_float_t input, mus_float_t unused) {return(mus_filter(ptr, input));}
static mus_float_t run_fir_filter(mus_any *ptr, mus_float_t input, mus_float_t unused) {return(mus_fir_filter(ptr, input));}
static mus_float_t run_iir_filter(mus_any *ptr, mus_float_t input, mus_float_t unused) {return(mus_iir_filter(ptr, input));}
bool mus_filter_p(mus_any *ptr)
{
return((ptr) &&
((ptr->core->type == MUS_FILTER) ||
(ptr->core->type == MUS_FIR_FILTER) ||
(ptr->core->type == MUS_IIR_FILTER)));
}
bool mus_fir_filter_p(mus_any *ptr)
{
return((ptr) &&
(ptr->core->type == MUS_FIR_FILTER));
}
bool mus_iir_filter_p(mus_any *ptr)
{
return((ptr) &&
(ptr->core->type == MUS_IIR_FILTER));
}
static mus_float_t *filter_data(mus_any *ptr) {return(((flt *)ptr)->state);}
static mus_long_t filter_length(mus_any *ptr) {return(((flt *)ptr)->order);}
static mus_float_t *filter_xcoeffs(mus_any *ptr) {return(((flt *)ptr)->x);}
static mus_float_t *filter_ycoeffs(mus_any *ptr) {return(((flt *)ptr)->y);}
mus_float_t *mus_filter_set_xcoeffs(mus_any *ptr, mus_float_t *new_data)
{
/* needed by Snd if filter order increased during play */
flt *gen = (flt *)ptr;
mus_float_t *old_data;
old_data = gen->x;
gen->x = new_data;
return(old_data);
}
mus_float_t *mus_filter_set_ycoeffs(mus_any *ptr, mus_float_t *new_data)
{
flt *gen = (flt *)ptr;
mus_float_t *old_data;
old_data = gen->y;
gen->y = new_data;
return(old_data);
}
static mus_long_t filter_set_length(mus_any *ptr, mus_long_t val)
{
/* just resets order if order < allocated size */
flt *gen = (flt *)ptr;
if ((val > 0) && (val <= gen->allocated_size))
gen->order = (int)val;
return((mus_long_t)(gen->order));
}
int mus_filter_set_order(mus_any *ptr, int order)
{
/* resets order and fixes state array if needed (coeffs arrays should be handled separately by set_x|ycoeffs above) */
/* returns either old order or -1 if state array can't be reallocated */
flt *gen = (flt *)ptr;
int old_order;
if ((order > gen->allocated_size) &&
(!(gen->state_allocated)))
return(-1);
old_order = gen->order;
gen->order = order;
if (order > gen->allocated_size)
{
int i;
gen->allocated_size = order;
gen->state = (mus_float_t *)clm_realloc(gen->state, order * sizeof(mus_float_t));
for (i = old_order; i < order; i++)
gen->state[i] = 0.0; /* try to minimize click */
}
return(old_order);
}
static mus_float_t filter_xcoeff(mus_any *ptr, int index)
{
flt *gen = (flt *)ptr;
if (!(gen->x)) return((mus_float_t)mus_error(MUS_NO_XCOEFFS, "no xcoeffs"));
if ((index >= 0) && (index < gen->order))
return(gen->x[index]);
return((mus_float_t)mus_error(MUS_ARG_OUT_OF_RANGE, S_mus_xcoeff ": invalid index %d, order = %d?", index, gen->order));
}
static mus_float_t filter_set_xcoeff(mus_any *ptr, int index, mus_float_t val)
{
flt *gen = (flt *)ptr;
if (!(gen->x)) return((mus_float_t)mus_error(MUS_NO_XCOEFFS, "no xcoeffs"));
if ((index >= 0) && (index < gen->order))
{
gen->x[index] = val;
return(val);
}
return((mus_float_t)mus_error(MUS_ARG_OUT_OF_RANGE, S_setB S_mus_xcoeff ": invalid index %d, order = %d?", index, gen->order));
}
static mus_float_t filter_ycoeff(mus_any *ptr, int index)
{
flt *gen = (flt *)ptr;
if (!(gen->y)) return((mus_float_t)mus_error(MUS_NO_YCOEFFS, "no ycoeffs"));
if ((index >= 0) && (index < gen->order))
return(gen->y[index]);
return((mus_float_t)mus_error(MUS_ARG_OUT_OF_RANGE, S_mus_ycoeff ": invalid index %d, order = %d?", index, gen->order));
}
static mus_float_t filter_set_ycoeff(mus_any *ptr, int index, mus_float_t val)
{
flt *gen = (flt *)ptr;
if (!(gen->y)) return((mus_float_t)mus_error(MUS_NO_YCOEFFS, "no ycoeffs"));
if ((index >= 0) && (index < gen->order))
{
gen->y[index] = val;
return(val);
}
return((mus_float_t)mus_error(MUS_ARG_OUT_OF_RANGE, S_setB S_mus_ycoeff ": invalid index %d, order = %d?", index, gen->order));
}
static int free_filter(mus_any *ptr)
{
flt *gen = (flt *)ptr;
if (gen)
{
if ((gen->state) && (gen->state_allocated)) clm_free(gen->state);
clm_free(gen);
}
return(0);
}
static bool filter_equalp(mus_any *p1, mus_any *p2)
{
flt *f1, *f2;
f1 = (flt *)p1;
f2 = (flt *)p2;
if (p1 == p2) return(true);
return(((p1->core)->type == (p2->core)->type) &&
((mus_filter_p(p1)) || (mus_fir_filter_p(p1)) || (mus_iir_filter_p(p1))) &&
(f1->order == f2->order) &&
((!(f1->x)) || (!(f2->x)) || (clm_arrays_are_equal(f1->x, f2->x, f1->order))) &&
((!(f1->y)) || (!(f2->y)) || (clm_arrays_are_equal(f1->y, f2->y, f1->order))) &&
(clm_arrays_are_equal(f1->state, f2->state, f1->order)));
}
static char *describe_filter(mus_any *ptr)
{
flt *gen = (flt *)ptr;
char *xstr = NULL, *ystr = NULL;
char *describe_buffer;
describe_buffer = (char *)clm_malloc(DESCRIBE_BUFFER_SIZE, "describe buffer");
xstr = float_array_to_string(gen->x, gen->order, 0);
ystr = float_array_to_string(gen->y, gen->order, 0);
mus_snprintf(describe_buffer, DESCRIBE_BUFFER_SIZE, "%s order: %d, xs: %s, ys: %s",
mus_name(ptr),
gen->order,
xstr, ystr);
if (xstr) clm_free(xstr);
if (ystr) clm_free(ystr);
return(describe_buffer);
}
static char *describe_fir_filter(mus_any *ptr)
{
flt *gen = (flt *)ptr;
char *xstr = NULL;
char *describe_buffer;
describe_buffer = (char *)clm_malloc(DESCRIBE_BUFFER_SIZE, "describe buffer");
xstr = float_array_to_string(gen->x, gen->order, 0);
mus_snprintf(describe_buffer, DESCRIBE_BUFFER_SIZE, "%s order: %d, xs: %s",
mus_name(ptr),
gen->order,
xstr);
if (xstr) clm_free(xstr);
return(describe_buffer);
}
static char *describe_iir_filter(mus_any *ptr)
{
flt *gen = (flt *)ptr;
char *ystr = NULL;
char *describe_buffer;
describe_buffer = (char *)clm_malloc(DESCRIBE_BUFFER_SIZE, "describe buffer");
ystr = float_array_to_string(gen->y, gen->order, 0);
mus_snprintf(describe_buffer, DESCRIBE_BUFFER_SIZE, "%s order: %d, ys: %s",
mus_name(ptr),
gen->order,
ystr);
if (ystr) clm_free(ystr);
return(describe_buffer);
}
static void filter_reset(mus_any *ptr)
{
flt *gen = (flt *)ptr;
mus_clear_array(gen->state, gen->allocated_size);
}
static mus_any_class FILTER_CLASS = {
MUS_FILTER,
(char *)S_filter,
&free_filter,
&describe_filter,
&filter_equalp,
&filter_data, 0,
&filter_length,
&filter_set_length,
0, 0, 0, 0,
0, 0,
0, 0,
&run_filter,
MUS_FULL_FILTER,
NULL, 0,
0, 0, 0, 0,
&filter_xcoeff, &filter_set_xcoeff,
0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0,
&filter_ycoeff, &filter_set_ycoeff,
&filter_xcoeffs, &filter_ycoeffs,
0,
&filter_reset,
0, 0, 0
};
static mus_any_class FIR_FILTER_CLASS = {
MUS_FIR_FILTER,
(char *)S_fir_filter,
&free_filter,
&describe_fir_filter,
&filter_equalp,
&filter_data, 0,
&filter_length,
&filter_set_length,
0, 0, 0, 0,
0, 0,
0, 0,
&run_fir_filter,
MUS_FULL_FILTER,
NULL, 0,
0, 0, 0, 0,
&filter_xcoeff, &filter_set_xcoeff,
0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0,
0, 0,
&filter_xcoeffs, 0, 0,
&filter_reset,
0, 0, 0
};
static mus_any_class IIR_FILTER_CLASS = {
MUS_IIR_FILTER,
(char *)S_iir_filter,
&free_filter,
&describe_iir_filter,
&filter_equalp,
&filter_data, 0,
&filter_length,
&filter_set_length,
0, 0, 0, 0,
0, 0,
0, 0,
&run_iir_filter,
MUS_FULL_FILTER,
NULL, 0,
0, 0, 0, 0,
0, 0,
0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0,
&filter_ycoeff, &filter_set_ycoeff,
0, &filter_ycoeffs, 0,
&filter_reset,
0, 0, 0
};
static mus_any *make_filter(mus_any_class *cls, const char *name, int order, mus_float_t *xcoeffs, mus_float_t *ycoeffs, mus_float_t *state) /* if state null, allocated locally */
{
if (order <= 0)
mus_error(MUS_ARG_OUT_OF_RANGE, "%s order = %d?", name, order);
else
{
flt *gen;
gen = (flt *)clm_calloc(1, sizeof(flt), name);
if (state)
gen->state = state;
else
{
gen->state = (mus_float_t *)clm_calloc(order, sizeof(mus_float_t), "filter state space");
gen->state_allocated = true;
}
gen->core = cls;
gen->order = order;
gen->allocated_size = order;
gen->x = xcoeffs;
gen->y = ycoeffs;
return((mus_any *)gen);
}
return(NULL);
}
mus_any *mus_make_filter(int order, mus_float_t *xcoeffs, mus_float_t *ycoeffs, mus_float_t *state)
{
return(make_filter(&FILTER_CLASS, S_make_filter, order, xcoeffs, ycoeffs, state));
}
mus_any *mus_make_fir_filter(int order, mus_float_t *xcoeffs, mus_float_t *state)
{
return(make_filter(&FIR_FILTER_CLASS, S_make_fir_filter, order, xcoeffs, NULL, state));
}
mus_any *mus_make_iir_filter(int order, mus_float_t *ycoeffs, mus_float_t *state)
{
return(make_filter(&IIR_FILTER_CLASS, S_make_iir_filter, order, NULL, ycoeffs, state));
}
mus_float_t *mus_make_fir_coeffs(int order, mus_float_t *envl, mus_float_t *aa)
{
/* envl = evenly sampled freq response, has order samples */
int n, i, j, jj;
mus_float_t scl;
mus_float_t *a;
n = order;
if (n <= 0) return(aa);
if (aa)
a = aa;
else a = (mus_float_t *)clm_calloc(order, sizeof(mus_float_t), "coeff space");
if (!a) return(NULL);
if (!(POWER_OF_2_P(order)))
{
int m;
mus_float_t am, q, xt = 0.0, xt0, qj, x;
m = (n + 1) / 2;
am = 0.5 * (n + 1);
scl = 2.0 / (mus_float_t)n;
q = TWO_PI / (mus_float_t)n;
xt0 = envl[0] * 0.5;
for (j = 0, jj = n - 1; j < m; j++, jj--)
{
xt = xt0;
qj = q * (am - j - 1);
for (i = 1, x = qj; i < m; i++, x += qj)
xt += (envl[i] * cos(x));
a[j] = xt * scl;
a[jj] = a[j];
}
}
else /* use fft if it's easy to match -- there must be a way to handle odd orders here */
{
mus_float_t *rl, *im;
mus_long_t fsize;
int lim;
mus_float_t offset;
fsize = 2 * order; /* checked power of 2 above */
rl = (mus_float_t *)clm_calloc(fsize, sizeof(mus_float_t), "mus_make_fir_coeffs");
im = (mus_float_t *)clm_calloc(fsize, sizeof(mus_float_t), "mus_make_fir_coeffs");
lim = order / 2;
memcpy((void *)rl, (void *)envl, lim * sizeof(mus_float_t));
mus_fft(rl, im, fsize, 1);
scl = 4.0 / fsize;
offset = -2.0 * envl[0] / fsize;
for (i = 0; i < fsize; i++)
rl[i] = rl[i] * scl + offset;
for (i = 1, j = lim - 1, jj = lim; i < order; i += 2, j--, jj++)
{
a[j] = rl[i];
a[jj] = rl[i];
}
clm_free(rl);
clm_free(im);
}
return(a);
}
/* ---------------- env ---------------- */
typedef struct {
mus_any_class *core;
double rate, current_value, base, offset, scaler, power, init_y, init_power, original_scaler, original_offset;
mus_long_t loc, end;
mus_env_t style;
int index, size;
bool data_allocated;
mus_float_t *original_data;
double *rates;
mus_long_t *locs;
} seg;
/* I used to use exp directly, but:
(define (texp1 start end num)
(let* ((ls (log start))
(le (log end))
(cf (exp (/ (- le ls) (1- num))))
(max-diff 0.0)
(xstart start))
(do ((i 0 (1+ i)))
((= i num)
max-diff)
(let ((val1 (* start (exp (* (/ i (1- num)) (- le ls)))))
(val2 xstart))
(set! xstart (* xstart cf))
(set! max-diff (max max-diff (abs (- val1 val2))))))))
returns:
:(texp1 1.0 3.0 1000000)
2.65991229042584e-10
:(texp1 1.0 10.0 100000000)
2.24604939091932e-8
:(texp1 10.0 1000.0 100000000)
4.11786902532185e-6
:(texp1 1.0 1.1 100000000)
1.28246036013024e-9
:(texp1 10.0 1000.0 1000000000)
4.39423240550241e-5
so the repeated multiply version is more than accurate enough
*/
bool mus_env_p(mus_any *ptr)
{
return((ptr) &&
(ptr->core->type == MUS_ENV));
}
mus_env_t mus_env_type(mus_any *ptr)
{
return(((seg *)ptr)->style);
}
mus_float_t mus_env(mus_any *ptr)
{
seg *gen = (seg *)ptr;
mus_float_t val;
val = gen->current_value;
if (gen->loc >= gen->locs[gen->index])
{
gen->index++;
gen->rate = gen->rates[gen->index];
}
if (gen->style == MUS_ENV_LINEAR)
gen->current_value += gen->rate;
else
{
if (gen->style == MUS_ENV_EXPONENTIAL)
{
gen->power *= gen->rate;
gen->current_value = gen->offset + (gen->scaler * gen->power);
}
else gen->current_value = gen->rate;
}
gen->loc++;
return(val);
}
mus_float_t mus_env_linear(mus_any *ptr)
{
seg *gen = (seg *)ptr;
mus_float_t val;
val = gen->current_value;
if (gen->loc >= gen->locs[gen->index])
{
gen->index++;
gen->rate = gen->rates[gen->index];
}
gen->current_value += gen->rate;
gen->loc++;
return(val);
}
mus_float_t mus_env_exponential(mus_any *ptr)
{
seg *gen = (seg *)ptr;
mus_float_t val;
val = gen->current_value;
if (gen->loc >= gen->locs[gen->index])
{
gen->index++;
gen->rate = gen->rates[gen->index];
}
gen->power *= gen->rate;
gen->current_value = gen->offset + (gen->scaler * gen->power);
gen->loc++;
return(val);
}
static mus_float_t run_env(mus_any *ptr, mus_float_t unused1, mus_float_t unused2)
{
return(mus_env(ptr));
}
static void dmagify_env(seg *e, mus_float_t *data, int pts, mus_long_t dur, double scaler)
{
int i, j;
double xscl = 1.0, cur_loc = 0.0, y1 = 0.0;
e->size = pts;
if ((pts > 1) &&
(data[pts * 2 - 2] != data[0]))
xscl = (double)(dur - 1) / (double)(data[pts * 2 - 2] - data[0]); /* was dur, 7-Apr-02 */
e->rates = (double *)clm_calloc(pts, sizeof(double), "env rates");
e->locs = (mus_long_t *)clm_calloc(pts + 1, sizeof(mus_long_t), "env locs");
for (j = 0, i = 2; i < pts * 2; i += 2, j++)
{
mus_long_t samps;
double cur_dx, x0, y0, x1;
x0 = data[i - 2];
x1 = data[i];
y0 = data[i - 1];
y1 = data[i + 1];
cur_dx = xscl * (x1 - x0);
if (cur_dx < 1.0) cur_dx = 1.0;
cur_loc += cur_dx;
if (e->style == MUS_ENV_STEP)
e->locs[j] = (mus_long_t)cur_loc; /* this is the change boundary (confusing...) */
else e->locs[j] = (mus_long_t)(cur_loc + 0.5);
if (j == 0)
samps = e->locs[0];
else samps = e->locs[j] - e->locs[j - 1];
switch (e->style)
{
case MUS_ENV_LINEAR:
if ((y0 == y1) || (samps == 0))
e->rates[j] = 0.0;
else e->rates[j] = scaler * (y1 - y0) / (double)samps;
break;
case MUS_ENV_EXPONENTIAL:
if ((y0 == y1) || (samps == 0))
e->rates[j] = 1.0;
else e->rates[j] = exp((y1 - y0) / (double)samps);
break;
case MUS_ENV_STEP:
e->rates[j] = e->offset + (scaler * y0);
break;
}
}
if ((pts > 1) &&
(e->locs[pts - 2] != e->end))
e->locs[pts - 2] = e->end;
if (pts > 1)
{
switch (e->style)
{
case MUS_ENV_STEP:
e->rates[pts - 1] = e->offset + (scaler * y1); /* stick at last value, which in this case is the value (not an increment) */
break;
case MUS_ENV_LINEAR:
e->rates[pts - 1] = 0.0;
break;
case MUS_ENV_EXPONENTIAL:
e->rates[pts - 1] = 1.0;
break;
}
}
e->locs[pts - 1] = 1000000000;
e->locs[pts] = 1000000000; /* guard cell at end to make bounds check simpler */
}
static mus_float_t *fixup_exp_env(seg *e, mus_float_t *data, int pts, double offset, double scaler, double base)
{
double min_y, max_y, val = 0.0, tmp = 0.0, b1;
int len, i;
bool flat;
mus_float_t *result = NULL;
if ((base <= 0.0) ||
(base == 1.0))
return(NULL);
min_y = offset + scaler * data[1];
max_y = min_y;
len = pts * 2;
/* fill "result" with x and (offset+scaler*y) */
result = (mus_float_t *)clm_calloc(len, sizeof(mus_float_t), "env data");
result[0] = data[0];
result[1] = min_y;
for (i = 2; i < len; i += 2)
{
tmp = offset + scaler * data[i + 1];
result[i] = data[i];
result[i + 1] = tmp;
if (tmp < min_y) min_y = tmp;
if (tmp > max_y) max_y = tmp;
}
b1 = base - 1.0;
flat = (min_y == max_y);
if (!flat)
val = 1.0 / (max_y - min_y);
/* now logify result */
for (i = 1; i < len; i += 2)
{
if (flat)
tmp = 1.0;
else tmp = val * (result[i] - min_y);
result[i] = log(1.0 + (tmp * b1));
}
e->scaler = (max_y - min_y) / b1;
e->offset = min_y;
return(result);
}
static bool env_equalp(mus_any *p1, mus_any *p2)
{
seg *e1 = (seg *)p1;
seg *e2 = (seg *)p2;
if (p1 == p2) return(true);
return((e1) && (e2) &&
(e1->core->type == e2->core->type) &&
(e1->loc == e2->loc) &&
(e1->end == e2->end) &&
(e1->style == e2->style) &&
(e1->index == e2->index) &&
(e1->size == e2->size) &&
(e1->rate == e2->rate) &&
(e1->base == e2->base) &&
(e1->power == e2->power) &&
(e1->current_value == e2->current_value) &&
(e1->scaler == e2->scaler) &&
(e1->offset == e2->offset) &&
(e1->init_y == e2->init_y) &&
(e1->init_power == e2->init_power) &&
(clm_arrays_are_equal(e1->original_data, e2->original_data, e1->size * 2)));
}
static char *describe_env(mus_any *ptr)
{
char *str = NULL;
seg *e = (seg *)ptr;
char *describe_buffer;
describe_buffer = (char *)clm_malloc(DESCRIBE_BUFFER_SIZE, "describe buffer");
mus_snprintf(describe_buffer, DESCRIBE_BUFFER_SIZE, "%s %s, pass: " MUS_LD " (dur: " MUS_LD "), index: %d, scaler: %.4f, offset: %.4f, data: %s",
mus_name(ptr),
((e->style == MUS_ENV_LINEAR) ? "linear" : ((e->style == MUS_ENV_EXPONENTIAL) ? "exponential" : "step")),
e->loc,
e->end + 1,
e->index,
e->original_scaler,
e->original_offset,
str = float_array_to_string(e->original_data, e->size * 2, 0));
if (str) clm_free(str);
return(describe_buffer);
}
static int free_env_gen(mus_any *pt)
{
seg *ptr = (seg *)pt;
if (ptr)
{
if (ptr->locs) {clm_free(ptr->locs); ptr->locs = NULL;}
if (ptr->rates) {clm_free(ptr->rates); ptr->rates = NULL;}
if ((ptr->original_data) && (ptr->data_allocated)) {clm_free(ptr->original_data); ptr->original_data = NULL;}
clm_free(ptr);
}
return(0);
}
static mus_float_t *env_data(mus_any *ptr) {return(((seg *)ptr)->original_data);} /* mus-data */
static mus_float_t env_scaler(mus_any *ptr) {return(((seg *)ptr)->original_scaler);} /* "mus_float_t" for mus-scaler */
static mus_float_t env_offset(mus_any *ptr) {return(((seg *)ptr)->original_offset);}
int mus_env_breakpoints(mus_any *ptr) {return(((seg *)ptr)->size);}
static mus_long_t env_length(mus_any *ptr) {return((((seg *)ptr)->end + 1));} /* this needs to match the :length arg to make-env (changed to +1, 20-Feb-08) */
static mus_float_t env_current_value(mus_any *ptr) {return(((seg *)ptr)->current_value);}
mus_long_t *mus_env_passes(mus_any *gen) {return(((seg *)gen)->locs);}
double *mus_env_rates(mus_any *gen) {return(((seg *)gen)->rates);}
static int env_position(mus_any *ptr) {return(((seg *)ptr)->index);}
double mus_env_offset(mus_any *gen) {return(((seg *)gen)->offset);}
double mus_env_scaler(mus_any *gen) {return(((seg *)gen)->scaler);}
double mus_env_initial_power(mus_any *gen) {return(((seg *)gen)->init_power);}
static mus_long_t seg_pass(mus_any *ptr) {return(((seg *)ptr)->loc);}
static void env_set_location(mus_any *ptr, mus_long_t val);
static mus_long_t seg_set_pass(mus_any *ptr, mus_long_t val) {env_set_location(ptr, val); return(val);}
static mus_float_t env_increment(mus_any *rd)
{
if (((seg *)rd)->style == MUS_ENV_STEP)
return(0.0);
return(((seg *)rd)->base);
}
static void env_reset(mus_any *ptr)
{
seg *gen = (seg *)ptr;
gen->current_value = gen->init_y;
gen->loc = 0;
gen->index = 0;
gen->rate = gen->rates[0];
gen->power = gen->init_power;
}
static void rebuild_env(seg *e, mus_float_t scl, mus_float_t off, mus_long_t end)
{
seg *new_e;
new_e = (seg *)mus_make_env(e->original_data, e->size, scl, off, e->base, 0.0, end, e->original_data);
if (e->locs) clm_free(e->locs);
if (e->rates) clm_free(e->rates);
e->locs = new_e->locs;
e->rates = new_e->rates;
e->init_y = new_e->init_y;
e->init_power = new_e->init_power;
env_reset((mus_any *)e);
clm_free(new_e);
}
static mus_float_t env_set_scaler(mus_any *ptr, mus_float_t val)
{
seg *e;
e = (seg *)ptr;
rebuild_env(e, val, e->original_offset, e->end);
e->original_scaler = val;
return(val);
}
static mus_float_t env_set_offset(mus_any *ptr, mus_float_t val)
{
seg *e;
e = (seg *)ptr;
rebuild_env(e, e->original_scaler, val, e->end);
e->original_offset = val;
return(val);
}
static mus_long_t env_set_length(mus_any *ptr, mus_long_t val)
{
seg *e;
e = (seg *)ptr;
rebuild_env(e, e->original_scaler, e->original_offset, val - 1);
e->end = val - 1;
return(val);
}
static mus_any_class ENV_CLASS = {
MUS_ENV,
(char *)S_env,
&free_env_gen,
&describe_env,
&env_equalp,
&env_data, /* mus-data -> original breakpoints */
0,
&env_length, &env_set_length,
0, 0,
&env_current_value, 0, /* mus-phase?? -- used in snd-sig.c, but this needs a better access point */
&env_scaler, &env_set_scaler,
&env_increment,
0,
&run_env,
MUS_NOT_SPECIAL,
NULL,
&env_position,
&env_offset, &env_set_offset,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0,
&seg_pass, &seg_set_pass,
0,
0, 0, 0, 0, 0,
&env_reset,
0, 0, 0
};
mus_any *mus_make_env(mus_float_t *brkpts, int npts, double scaler, double offset, double base, double duration, mus_long_t end, mus_float_t *odata)
{
int i;
mus_long_t dur_in_samples;
mus_float_t *edata;
seg *e = NULL;
for (i = 2; i < npts * 2; i += 2)
if (brkpts[i - 2] >= brkpts[i])
{
char *temp = NULL;
mus_error(MUS_BAD_ENVELOPE, S_make_env ": env at breakpoint %d: x axis value: %f <= previous x value: %f (env: %s)",
i / 2, brkpts[i], brkpts[i - 2],
temp = float_array_to_string(brkpts, npts * 2, 0)); /* minor memleak here */
if (temp) clm_free(temp);
return(NULL);
}
e = (seg *)clm_calloc(1, sizeof(seg), S_make_env);
e->core = &ENV_CLASS;
if (duration != 0.0)
dur_in_samples = (mus_long_t)(duration * sampling_rate);
else dur_in_samples = (end + 1);
e->init_y = offset + scaler * brkpts[1];
e->current_value = e->init_y;
e->rate = 0.0;
e->offset = offset;
e->scaler = scaler;
e->original_offset = offset;
e->original_scaler = scaler;
e->base = base;
e->end = (dur_in_samples - 1);
e->loc = 0;
e->index = 0;
if (odata)
e->original_data = odata;
else
{
e->original_data = (mus_float_t *)clm_calloc(npts * 2, sizeof(mus_float_t), "env original data");
e->data_allocated = true;
}
if (e->original_data != brkpts)
memcpy((void *)(e->original_data), (void *)brkpts, npts * 2 * sizeof(mus_float_t));
if (base == 0.0)
{
e->style = MUS_ENV_STEP;
dmagify_env(e, brkpts, npts, dur_in_samples, scaler);
}
else
{
if (base == 1.0)
{
e->style = MUS_ENV_LINEAR;
dmagify_env(e, brkpts, npts, dur_in_samples, scaler);
}
else
{
e->style = MUS_ENV_EXPONENTIAL;
edata = fixup_exp_env(e, brkpts, npts, offset, scaler, base);
if (edata == NULL)
{
if ((e->original_data) && (e->data_allocated)) clm_free(e->original_data);
clm_free(e);
return(NULL);
}
dmagify_env(e, edata, npts, dur_in_samples, 1.0);
e->power = exp(edata[1]);
e->init_power = e->power;
e->offset -= e->scaler;
clm_free(edata);
}
}
e->rate = e->rates[0];
return((mus_any *)e);
}
static void env_set_location(mus_any *ptr, mus_long_t val)
{
seg *gen = (seg *)ptr;
mus_long_t ctr = 0;
if (gen->loc == val) return;
if (gen->loc > val)
mus_reset(ptr);
else ctr = gen->loc;
gen->loc = val;
while ((gen->index < (gen->size - 1)) && /* this was gen->size */
(ctr < val))
{
mus_long_t samps;
if (val > gen->locs[gen->index])
samps = gen->locs[gen->index] - ctr;
else samps = val - ctr;
switch (gen->style)
{
case MUS_ENV_LINEAR:
gen->current_value += (samps * gen->rate);
break;
case MUS_ENV_STEP:
gen->current_value = gen->rate;
break;
case MUS_ENV_EXPONENTIAL:
gen->power *= exp(samps * log(gen->rate));
gen->current_value = gen->offset + (gen->scaler * gen->power);
break;
}
ctr += samps;
if (ctr < val)
{
gen->index++;
if (gen->index < gen->size)
gen->rate = gen->rates[gen->index];
}
}
}
double mus_env_interp(double x, mus_any *ptr)
{
/* the accuracy depends on the duration here -- more samples = more accurate */
seg *gen = (seg *)ptr;
env_set_location(ptr, (mus_long_t)((x * (gen->end + 1)) / (gen->original_data[gen->size * 2 - 2])));
return(gen->current_value);
}
mus_float_t mus_env_any(mus_any *e, mus_float_t (*connect_points)(mus_float_t val))
{
/* "env_any" is supposed to mimic "out-any" */
seg *gen = (seg *)e;
mus_float_t *pts;
int pt, size;
mus_float_t y0, y1, new_val, val;
double scaler, offset;
scaler = gen->original_scaler;
offset = gen->original_offset;
size = gen->size;
if (size <= 1)
return(offset + scaler * connect_points(0.0));
pts = gen->original_data;
pt = gen->index;
if (pt >= (size - 1)) pt = size - 2;
if (pts[pt * 2 + 1] <= pts[pt * 2 + 3])
{
y0 = pts[pt * 2 + 1];
y1 = pts[pt * 2 + 3];
}
else
{
y1 = pts[pt * 2 + 1];
y0 = pts[pt * 2 + 3];
}
val = (mus_env(e) - offset) / scaler;
new_val = connect_points( (val - y0) / (y1 - y0));
return(offset + scaler * (y0 + new_val * (y1 - y0)));
}
/* ---------------- frame ---------------- */
/* frame = vector, mixer = (square) matrix, but "vector" is in use already, and "matrix" sounds too techy */
/* someday frames and vcts should be combined, and mixers/sound-data
*/
typedef struct {
mus_any_class *core;
int chans;
mus_float_t *vals;
bool data_allocated;
} mus_frame;
static int free_frame(mus_any *pt)
{
mus_frame *ptr = (mus_frame *)pt;
if (ptr)
{
if ((ptr->vals) && (ptr->data_allocated)) clm_free(ptr->vals);
clm_free(ptr);
}
return(0);
}
static char *describe_frame(mus_any *ptr)
{
mus_frame *gen = (mus_frame *)ptr;
char *str = NULL;
char *describe_buffer;
describe_buffer = (char *)clm_malloc(DESCRIBE_BUFFER_SIZE, "describe buffer");
mus_snprintf(describe_buffer, DESCRIBE_BUFFER_SIZE, "%s[%d]: %s",
mus_name(ptr),
gen->chans,
str = float_array_to_string(gen->vals, gen->chans, 0));
if (str) clm_free(str);
return(describe_buffer);
}
bool mus_frame_p(mus_any *ptr)
{
return((ptr) &&
(ptr->core->type == MUS_FRAME));
}
static bool equalp_frame(mus_any *p1, mus_any *p2)
{
mus_frame *g1, *g2;
if (p1 == p2) return(true);
g1 = (mus_frame *)p1;
g2 = (mus_frame *)p2;
return(((g1->core)->type == (g2->core)->type) &&
(g1->chans == g2->chans) &&
(clm_arrays_are_equal(g1->vals, g2->vals, g1->chans)));
}
static mus_float_t run_frame(mus_any *ptr, mus_float_t arg1, mus_float_t arg2) {return(mus_frame_ref(ptr, (int)arg1));}
static mus_float_t *frame_data(mus_any *ptr) {return(((mus_frame *)ptr)->vals);}
static mus_long_t frame_length(mus_any *ptr) {return(((mus_frame *)ptr)->chans);}
static int frame_channels(mus_any *ptr) {return(((mus_frame *)ptr)->chans);}
static void frame_reset(mus_any *ptr)
{
mus_frame *gen = (mus_frame *)ptr;
mus_clear_array(gen->vals, gen->chans);
}
static mus_any_class FRAME_CLASS = {
MUS_FRAME,
(char *)S_frame,
&free_frame,
&describe_frame,
&equalp_frame,
&frame_data, 0,
&frame_length, 0,
0, 0, 0, 0,
0, 0,
0, 0,
&run_frame,
MUS_NOT_SPECIAL,
NULL,
&frame_channels,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0,
&frame_reset,
0, 0, 0
};
mus_any *mus_make_empty_frame(int chans)
{
mus_frame *nf;
if (chans <= 0) return(NULL);
nf = (mus_frame *)clm_calloc(1, sizeof(mus_frame), S_make_frame);
nf->core = &FRAME_CLASS;
nf->chans = chans;
nf->vals = (mus_float_t *)clm_calloc(chans, sizeof(mus_float_t), "frame data");
nf->data_allocated = true;
return((mus_any *)nf);
}
mus_any *mus_make_frame_with_data(int chans, mus_float_t *data)
{
/* for CLM */
mus_frame *nf;
if (chans <= 0) return(NULL);
nf = (mus_frame *)clm_calloc(1, sizeof(mus_frame), S_make_frame);
nf->core = &FRAME_CLASS;
nf->chans = chans;
nf->vals = data;
nf->data_allocated = false;
return((mus_any *)nf);
}
mus_any *mus_make_frame(int chans, ...)
{
if (chans <= 0)
mus_error(MUS_ARG_OUT_OF_RANGE, S_make_frame ": chans: %d", chans);
else
{
mus_frame *nf = NULL;
nf = (mus_frame *)mus_make_empty_frame(chans);
if (nf)
{
int i;
va_list ap;
va_start(ap, chans);
for (i = 0; i < chans; i++)
nf->vals[i] = (mus_float_t)(va_arg(ap, double)); /* float not safe here apparently */
va_end(ap);
return((mus_any *)nf);
}
}
return(NULL);
}
mus_any *mus_frame_add(mus_any *uf1, mus_any *uf2, mus_any *ures)
{
int chans, i;
mus_frame *f1 = (mus_frame *)uf1;
mus_frame *f2 = (mus_frame *)uf2;
mus_frame *res = (mus_frame *)ures;
chans = f1->chans;
if (f2->chans < chans) chans = f2->chans;
if (res)
{
if (res->chans < chans) chans = res->chans;
}
else res = (mus_frame *)mus_make_empty_frame(chans);
for (i = 0; i < chans; i++)
res->vals[i] = f1->vals[i] + f2->vals[i];
return((mus_any *)res);
}
mus_any *mus_frame_multiply(mus_any *uf1, mus_any *uf2, mus_any *ures)
{
int chans, i;
mus_frame *f1 = (mus_frame *)uf1;
mus_frame *f2 = (mus_frame *)uf2;
mus_frame *res = (mus_frame *)ures;
chans = f1->chans;
if (f2->chans < chans) chans = f2->chans;
if (res)
{
if (res->chans < chans)
chans = res->chans;
}
else res = (mus_frame *)mus_make_empty_frame(chans);
for (i = 0; i < chans; i++)
res->vals[i] = f1->vals[i] * f2->vals[i];
return((mus_any *)res);
}
mus_any *mus_frame_scale(mus_any *uf1, mus_float_t scl, mus_any *ures)
{
int chans, i;
mus_frame *f1 = (mus_frame *)uf1;
mus_frame *res = (mus_frame *)ures;
chans = f1->chans;
if (res)
{
if (res->chans < chans)
chans = res->chans;
}
else res = (mus_frame *)mus_make_empty_frame(chans);
for (i = 0; i < chans; i++)
res->vals[i] = f1->vals[i] * scl;
return((mus_any *)res);
}
mus_any *mus_frame_offset(mus_any *uf1, mus_float_t offset, mus_any *ures)
{
int chans, i;
mus_frame *f1 = (mus_frame *)uf1;
mus_frame *res = (mus_frame *)ures;
chans = f1->chans;
if (res)
{
if (res->chans < chans) chans = res->chans;
}
else res = (mus_frame *)mus_make_empty_frame(chans);
for (i = 0; i < chans; i++)
res->vals[i] = f1->vals[i] + offset;
return((mus_any *)res);
}
mus_float_t mus_frame_ref(mus_any *uf, int chan)
{
mus_frame *f = (mus_frame *)uf;
if ((chan >= 0) && (chan < f->chans))
return(f->vals[chan]);
return((mus_float_t)mus_error(MUS_ARG_OUT_OF_RANGE,
S_frame_ref ": invalid chan: %d (frame has %d chan%s)",
chan, f->chans, (f->chans == 1) ? "" : "s"));
}
mus_float_t mus_frame_set(mus_any *uf, int chan, mus_float_t val)
{
mus_frame *f = (mus_frame *)uf;
if ((chan >= 0) && (chan < f->chans))
f->vals[chan] = val;
else mus_error(MUS_ARG_OUT_OF_RANGE,
S_frame_set ": invalid chan: %d (frame has %d chan%s)",
chan, f->chans, (f->chans == 1) ? "" : "s");
return(val);
}
mus_any *mus_frame_copy(mus_any *uf)
{
mus_frame *f = (mus_frame *)uf;
mus_frame *nf;
nf = (mus_frame *)mus_make_empty_frame(f->chans);
memcpy((void *)(nf->vals), (void *)(f->vals), f->chans * sizeof(mus_float_t));
return((mus_any *)nf);
}
mus_float_t mus_frame_fill(mus_any *uf, mus_float_t val)
{
int i;
mus_frame *f = (mus_frame *)uf;
for (i = 0; i < f->chans; i++)
f->vals[i] = val;
return(val);
}
/* ---------------- mixer ---------------- */
typedef struct {
mus_any_class *core;
int chans;
mus_float_t **vals;
bool data_allocated;
} mus_mixer;
static int free_mixer(mus_any *pt)
{
mus_mixer *ptr = (mus_mixer *)pt;
if (ptr)
{
if (ptr->vals)
{
int i;
if (ptr->data_allocated)
for (i = 0; i < ptr->chans; i++)
clm_free(ptr->vals[i]);
clm_free(ptr->vals);
}
clm_free(ptr);
}
return(0);
}
static void mixer_reset(mus_any *ptr)
{
int i;
mus_mixer *gen = (mus_mixer *)ptr;
for (i = 0; i < gen->chans; i++)
mus_clear_array(gen->vals[i], gen->chans);
}
static char *describe_mixer(mus_any *ptr)
{
mus_mixer *gen = (mus_mixer *)ptr;
char *str;
int i, j, lim, bufsize;
char *describe_buffer;
lim = mus_array_print_length();
if (gen->chans < lim) lim = gen->chans;
bufsize = lim * lim * 16;
if (bufsize < DESCRIBE_BUFFER_SIZE) bufsize = DESCRIBE_BUFFER_SIZE;
if (bufsize > 65536) bufsize = 65536;
describe_buffer = (char *)clm_malloc(bufsize, "describe buffer");
if (gen->chans == 1)
mus_snprintf(describe_buffer, bufsize, "%s chans: 1, [%.3f]", mus_name(ptr), gen->vals[0][0]);
else
{
mus_snprintf(describe_buffer, bufsize, "%s chans: %d, [\n ", mus_name(ptr), gen->chans);
str = (char *)clm_calloc(64, sizeof(char), "describe_mixer");
for (i = 0; i < lim; i++)
for (j = 0; j < lim; j++)
{
mus_snprintf(str, 64, "%.3f%s%s%s",
gen->vals[i][j],
((j == (lim - 1)) && (lim < gen->chans)) ? "..." : "",
(j == (lim - 1)) ? "\n" : "",
((i == (lim - 1)) && (j == (lim - 1))) ? "]" : " ");
if ((int)(strlen(describe_buffer) + strlen(str)) < (bufsize - 1))
strcat(describe_buffer, str);
else break;
}
clm_free(str);
}
return(describe_buffer);
}
bool mus_mixer_p(mus_any *ptr) {return((ptr) && (ptr->core->type == MUS_MIXER));}
static bool equalp_mixer(mus_any *p1, mus_any *p2)
{
int i;
mus_mixer *g1, *g2;
if (p1 == p2) return(true);
if ((p1 == NULL) || (p2 == NULL)) return(false); /* is this needed? */
g1 = (mus_mixer *)p1;
g2 = (mus_mixer *)p2;
if (((g1->core)->type != (g2->core)->type) ||
(g1->chans != g2->chans))
return(false);
for (i = 0; i < g1->chans; i++)
if (!(clm_arrays_are_equal(g1->vals[i], g2->vals[i], g1->chans)))
return(false);
return(true);
}
static mus_float_t run_mixer(mus_any *ptr, mus_float_t arg1, mus_float_t arg2) {return(mus_mixer_ref(ptr, (int)arg1, (int)arg2));}
static mus_long_t mixer_length(mus_any *ptr) {return(((mus_mixer *)ptr)->chans);}
static mus_float_t *mixer_data(mus_any *ptr) {return((mus_float_t *)(((mus_mixer *)ptr)->vals));}
static int mixer_channels(mus_any *ptr) {return(((mus_mixer *)ptr)->chans);}
static mus_any_class MIXER_CLASS = {
MUS_MIXER,
(char *)S_mixer,
&free_mixer,
&describe_mixer,
&equalp_mixer,
&mixer_data, 0,
&mixer_length,
0,
0, 0, 0, 0,
0, 0,
0, 0,
&run_mixer,
MUS_NOT_SPECIAL,
NULL,
&mixer_channels,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0,
&mixer_reset,
0, 0, 0
};
mus_any *mus_make_mixer_with_data(int chans, mus_float_t *data)
{
/* for CLM */
mus_mixer *nf;
int i;
if (chans <= 0) return(NULL);
nf = (mus_mixer *)clm_calloc(1, sizeof(mus_mixer), S_make_mixer);
nf->core = &MIXER_CLASS;
nf->chans = chans;
nf->vals = (mus_float_t **)clm_calloc(chans, sizeof(mus_float_t *), "mixer data");
for (i = 0; i < chans; i++)
nf->vals[i] = (mus_float_t *)(data + (i * chans));
nf->data_allocated = false;
return((mus_any *)nf);
}
mus_any *mus_make_empty_mixer(int chans)
{
mus_mixer *nf = NULL;
int i;
nf = (mus_mixer *)clm_calloc(1, sizeof(mus_mixer), S_make_mixer);
nf->core = &MIXER_CLASS;
nf->chans = chans;
nf->vals = (mus_float_t **)clm_calloc(chans, sizeof(mus_float_t *), "mixer data");
for (i = 0; i < chans; i++)
nf->vals[i] = (mus_float_t *)clm_calloc(chans, sizeof(mus_float_t), "mixer data");
nf->data_allocated = true;
return((mus_any *)nf);
}
mus_any *mus_make_scalar_mixer(int chans, mus_float_t scalar)
{
mus_mixer *mx = NULL;
if (chans <= 0)
mus_error(MUS_ARG_OUT_OF_RANGE, S_make_scalar_mixer ": chans: %d", chans);
else
{
int i;
mx = (mus_mixer *)mus_make_empty_mixer(chans);
if (mx) for (i = 0; i < chans; i++) mx->vals[i][i] = scalar;
}
return((mus_any *)mx);
}
mus_any *mus_make_identity_mixer(int chans)
{
return(mus_make_scalar_mixer(chans, 1.0));
}
mus_any *mus_make_mixer(int chans, ...)
{
mus_mixer *mx = NULL;
if (chans <= 0)
mus_error(MUS_ARG_OUT_OF_RANGE, S_make_mixer ": chans: %d", chans);
else
{
mx = (mus_mixer *)mus_make_empty_mixer(chans);
if (mx)
{
int i, j;
va_list ap;
va_start(ap, chans);
for (i = 0; i < chans; i++)
for (j = 0; j < chans; j++)
mx->vals[i][j] = (mus_float_t)(va_arg(ap, double));
va_end(ap);
}
}
return((mus_any *)mx);
}
mus_any *mus_mixer_copy(mus_any *uf)
{
int i, j;
mus_mixer *f = (mus_mixer *)uf;
mus_mixer *nf;
nf = (mus_mixer *)mus_make_empty_mixer(f->chans);
for (i = 0; i < f->chans; i++)
for (j = 0; j < f->chans; j++)
nf->vals[i][j] = f->vals[i][j];
return((mus_any *)nf);
}
mus_float_t mus_mixer_fill(mus_any *uf, mus_float_t val)
{
int i, j;
mus_mixer *f = (mus_mixer *)uf;
for (i = 0; i < f->chans; i++)
for (j = 0; j < f->chans; j++)
f->vals[i][j] = val;
return(val);
}
mus_float_t mus_mixer_ref(mus_any *uf, int in, int out)
{
mus_mixer *f = (mus_mixer *)uf;
if ((in >= 0) && (in < f->chans) &&
(out >= 0) && (out < f->chans))
return(f->vals[in][out]);
mus_error(MUS_ARG_OUT_OF_RANGE,
S_mixer_ref ": invalid chan: %d (mixer has %d chan%s)",
((in < 0) || (in >= f->chans)) ? in : out,
f->chans,
(f->chans == 1) ? "" : "s");
return(0.0);
}
mus_float_t mus_mixer_set(mus_any *uf, int in, int out, mus_float_t val)
{
mus_mixer *f = (mus_mixer *)uf;
if ((in >= 0) && (in < f->chans) &&
(out >= 0) && (out < f->chans))
f->vals[in][out] = val;
else mus_error(MUS_ARG_OUT_OF_RANGE,
S_mixer_set ": invalid chan: %d (mixer has %d chan%s)",
((in < 0) || (in >= f->chans)) ? in : out,
f->chans,
(f->chans == 1) ? "" : "s");
return(val);
}
static mus_any *frame_to_frame_right(mus_any *arg1, mus_any *arg2, mus_any *arg_out)
{
/* (frame->frame frame mixer frame) = frame * mixer -> frame -- this is the original form */
mus_mixer *mix = (mus_mixer *)arg2;
mus_frame *frame = (mus_frame *)arg1;
mus_frame *out = (mus_frame *)arg_out;
int i, in_chans, out_chans;
in_chans = frame->chans;
if (in_chans > mix->chans)
in_chans = mix->chans;
out_chans = mix->chans;
if (out)
{
if (out->chans < out_chans)
out_chans = out->chans;
}
else out = (mus_frame *)mus_make_empty_frame(out_chans);
for (i = 0; i < out_chans; i++)
{
int j;
out->vals[i] = 0.0;
for (j = 0; j < in_chans; j++)
out->vals[i] += (frame->vals[j] * mix->vals[j][i]);
}
return((mus_any *)out); /* not arg_out since out may be allocated above, and clm2xen.c expects this to be legit */
}
mus_any *mus_frame_to_frame_mono(mus_any *frame, mus_any *mix, mus_any *out)
{
/* assume every possible problem has already been checked somewhere */
((mus_frame *)out)->vals[0] = ((mus_frame *)frame)->vals[0] * ((mus_mixer *)mix)->vals[0][0];
return(out);
}
mus_any *mus_frame_to_frame_stereo(mus_any *frame, mus_any *mix, mus_any *out)
{
((mus_frame *)out)->vals[0] = ((mus_frame *)frame)->vals[0] * ((mus_mixer *)mix)->vals[0][0] +
((mus_frame *)frame)->vals[1] * ((mus_mixer *)mix)->vals[1][0];
((mus_frame *)out)->vals[1] = ((mus_frame *)frame)->vals[0] * ((mus_mixer *)mix)->vals[0][1] +
((mus_frame *)frame)->vals[1] * ((mus_mixer *)mix)->vals[1][1];
return(out);
}
mus_any *mus_frame_to_frame_mono_to_stereo(mus_any *frame, mus_any *mix, mus_any *out)
{
((mus_frame *)out)->vals[0] = ((mus_frame *)frame)->vals[0] * ((mus_mixer *)mix)->vals[0][0];
((mus_frame *)out)->vals[1] = ((mus_frame *)frame)->vals[0] * ((mus_mixer *)mix)->vals[0][1];
return(out);
}
static mus_any *frame_to_frame_left(mus_any *arg1, mus_any *arg2, mus_any *arg_out)
{
/* (frame->frame mixer frame frame) = mixer * frame -> frame */
mus_mixer *mix = (mus_mixer *)arg1;
mus_frame *frame = (mus_frame *)arg2;
mus_frame *out = (mus_frame *)arg_out;
int i, in_chans, out_chans;
in_chans = frame->chans;
if (in_chans > mix->chans)
in_chans = mix->chans;
out_chans = mix->chans;
if (out)
{
if (out->chans < out_chans)
out_chans = out->chans;
}
else out = (mus_frame *)mus_make_empty_frame(out_chans);
for (i = 0; i < out_chans; i++)
{
int j;
out->vals[i] = 0.0;
for (j = 0; j < in_chans; j++)
out->vals[i] += (mix->vals[i][j] * frame->vals[j]);
}
return((mus_any *)out);
}
mus_any *mus_frame_to_frame(mus_any *arg1, mus_any *arg2, mus_any *arg_out)
{
if (mus_mixer_p(arg2))
return(frame_to_frame_right(arg1, arg2, arg_out));
return(frame_to_frame_left(arg1, arg2, arg_out));
}
mus_any *mus_sample_to_frame(mus_any *f, mus_float_t in, mus_any *uout)
{
int i, chans;
mus_frame *out = (mus_frame *)uout;
if (mus_frame_p(f))
{
mus_frame *fr;
fr = (mus_frame *)f;
chans = fr->chans;
if (out)
{
if (out->chans < chans)
chans = out->chans;
}
else out = (mus_frame *)mus_make_empty_frame(chans);
for (i = 0; i < chans; i++)
out->vals[i] = (in * fr->vals[i]);
/* was += here and below? */
}
else
{
if (mus_mixer_p(f))
{
mus_mixer *mx;
mx = (mus_mixer *)f;
chans = mx->chans;
if (out)
{
if (out->chans < chans)
chans = out->chans;
}
else out = (mus_frame *)mus_make_empty_frame(chans);
for (i = 0; i < chans; i++)
out->vals[i] = (in * mx->vals[0][i]);
}
else mus_error(MUS_ARG_OUT_OF_RANGE, S_sample_to_frame ": gen not frame or mixer");
}
return((mus_any *)out);
}
mus_float_t mus_frame_to_sample(mus_any *f, mus_any *uin)
{
int i, chans;
mus_frame *in = (mus_frame *)uin;
mus_float_t val = 0.0;
if (mus_frame_p(f))
{
mus_frame *fr;
fr = (mus_frame *)f;
chans = in->chans;
if (fr->chans < chans)
chans = fr->chans;
for (i = 0; i < chans; i++)
val += (in->vals[i] * fr->vals[i]);
}
else
{
if (mus_mixer_p(f))
{
mus_mixer *mx;
mx = (mus_mixer *)f;
chans = in->chans;
if (mx->chans < chans)
chans = mx->chans;
for (i = 0; i < chans; i++)
val += (in->vals[i] * mx->vals[i][0]);
}
else mus_error(MUS_ARG_OUT_OF_RANGE, S_frame_to_sample ": gen not frame or mixer");
}
return(val);
}
mus_any *mus_mixer_add(mus_any *uf1, mus_any *uf2, mus_any *ures)
{
int i, j, chans;
mus_mixer *f1 = (mus_mixer *)uf1;
mus_mixer *f2 = (mus_mixer *)uf2;
mus_mixer *res = (mus_mixer *)ures;
chans = f1->chans;
if (f2->chans < chans)
chans = f2->chans;
if (res)
{
if (res->chans < chans)
chans = res->chans;
}
else res = (mus_mixer *)mus_make_empty_mixer(chans);
for (i = 0; i < chans; i++)
for (j = 0; j < chans; j++)
res->vals[i][j] = f1->vals[i][j] + f2->vals[i][j];
return((mus_any *)res);
}
mus_any *mus_mixer_multiply(mus_any *uf1, mus_any *uf2, mus_any *ures)
{
int i, j, k, chans;
mus_mixer *f1 = (mus_mixer *)uf1;
mus_mixer *f2 = (mus_mixer *)uf2;
mus_mixer *res = (mus_mixer *)ures;
chans = f1->chans;
if (f2->chans < chans)
chans = f2->chans;
if (res)
{
if (res->chans < chans)
chans = res->chans;
}
else res = (mus_mixer *)mus_make_empty_mixer(chans);
for (i = 0; i < chans; i++)
for (j = 0; j < chans; j++)
{
res->vals[i][j] = 0.0;
for (k = 0; k < chans; k++)
res->vals[i][j] += (f1->vals[i][k] * f2->vals[k][j]);
}
return((mus_any *)res);
}
mus_any *mus_mixer_scale(mus_any *uf1, mus_float_t scaler, mus_any *ures)
{
int i, j, chans;
mus_mixer *f1 = (mus_mixer *)uf1;
mus_mixer *res = (mus_mixer *)ures;
chans = f1->chans;
if (res)
{
if (res->chans < chans)
chans = res->chans;
}
else res = (mus_mixer *)mus_make_empty_mixer(chans);
for (i = 0; i < chans; i++)
for (j = 0; j < chans; j++)
res->vals[i][j] = f1->vals[i][j] * scaler;
return((mus_any *)res);
}
mus_any *mus_mixer_offset(mus_any *uf1, mus_float_t offset, mus_any *ures)
{
int i, j, chans;
mus_mixer *f1 = (mus_mixer *)uf1;
mus_mixer *res = (mus_mixer *)ures;
chans = f1->chans;
if (res)
{
if (res->chans < chans)
chans = res->chans;
}
else res = (mus_mixer *)mus_make_empty_mixer(chans);
for (i = 0; i < chans; i++)
for (j = 0; j < chans; j++)
res->vals[i][j] = f1->vals[i][j] + offset;
return((mus_any *)res);
}
/* ---------------- input/output ---------------- */
static mus_float_t mus_read_sample(mus_any *fd, mus_long_t frame, int chan)
{
if ((check_gen(fd, "mus-read-sample")) &&
((fd->core)->read_sample))
return(((*(fd->core)->read_sample))(fd, frame, chan));
return((mus_float_t)mus_error(MUS_NO_SAMPLE_INPUT,
"can't find %s's sample input function",
mus_name(fd)));
}
static mus_float_t mus_write_sample(mus_any *fd, mus_long_t frame, int chan, mus_float_t samp)
{
if ((check_gen(fd, "mus-write-sample")) &&
((fd->core)->write_sample))
return(((*(fd->core)->write_sample))(fd, frame, chan, samp));
return((mus_float_t)mus_error(MUS_NO_SAMPLE_OUTPUT,
"can't find %s's sample output function",
mus_name(fd)));
}
char *mus_file_name(mus_any *gen)
{
if ((check_gen(gen, S_mus_file_name)) &&
(gen->core->file_name))
return((*(gen->core->file_name))(gen));
else mus_error(MUS_NO_FILE_NAME, "can't get %s's file name", mus_name(gen));
return(NULL);
}
bool mus_input_p(mus_any *gen)
{
return((gen) &&
(gen->core->extended_type == MUS_INPUT));
}
bool mus_output_p(mus_any *gen)
{
return((gen) &&
(gen->core->extended_type == MUS_OUTPUT));
}
/* ---------------- file->sample ---------------- */
typedef struct {
mus_any_class *core;
int chan;
int dir;
mus_long_t loc;
char *file_name;
int chans;
mus_sample_t **ibufs;
mus_long_t data_start, data_end, file_end;
mus_long_t file_buffer_size;
int safety;
} rdin;
static char *describe_file_to_sample(mus_any *ptr)
{
rdin *gen = (rdin *)ptr;
char *describe_buffer;
describe_buffer = (char *)clm_malloc(DESCRIBE_BUFFER_SIZE, "describe buffer");
mus_snprintf(describe_buffer, DESCRIBE_BUFFER_SIZE, "%s %s",
mus_name(ptr),
gen->file_name);
return(describe_buffer);
}
static bool rdin_equalp(mus_any *p1, mus_any *p2)
{
rdin *r1 = (rdin *)p1;
rdin *r2 = (rdin *)p2;
return((p1 == p2) ||
((r1) && (r2) &&
(r1->core->type == r2->core->type) &&
(r1->chan == r2->chan) &&
(r1->loc == r2->loc) &&
(r1->dir == r2->dir) &&
(r1->file_name) &&
(r2->file_name) &&
(strcmp(r1->file_name, r2->file_name) == 0)));
}
static int free_file_to_sample(mus_any *p)
{
rdin *ptr = (rdin *)p;
if (ptr)
{
if (ptr->core->end) ((*ptr->core->end))(p);
clm_free(ptr->file_name);
clm_free(ptr);
}
return(0);
}
static mus_long_t file_to_sample_length(mus_any *ptr) {return((((rdin *)ptr)->file_end));}
static int file_to_sample_channels(mus_any *ptr) {return((int)(((rdin *)ptr)->chans));}
static int file_to_sample_safety(mus_any *ptr) {return(((rdin *)ptr)->safety);}
static int file_to_sample_set_safety(mus_any *ptr, int val) {((rdin *)ptr)->safety = val; return(val);}
static mus_float_t file_to_sample_increment(mus_any *rd) {return((mus_float_t)(((rdin *)rd)->dir));}
static mus_float_t file_to_sample_set_increment(mus_any *rd, mus_float_t val) {((rdin *)rd)->dir = (int)val; return(val);}
static char *file_to_sample_file_name(mus_any *ptr) {return(((rdin *)ptr)->file_name);}
static void no_reset(mus_any *ptr) {}
static int file_to_sample_end(mus_any *ptr);
static mus_float_t run_file_to_sample(mus_any *ptr, mus_float_t arg1, mus_float_t arg2) {return(mus_in_any_from_file(ptr, (int)arg1, (int)arg2));} /* mus_read_sample here? */
static mus_any_class FILE_TO_SAMPLE_CLASS = {
MUS_FILE_TO_SAMPLE,
(char *)S_file_to_sample,
&free_file_to_sample,
&describe_file_to_sample,
&rdin_equalp,
0, 0,
&file_to_sample_length, 0,
0, 0, 0, 0,
0, 0,
&file_to_sample_increment,
&file_to_sample_set_increment,
&run_file_to_sample,
MUS_INPUT,
NULL,
&file_to_sample_channels,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
&mus_in_any_from_file,
0,
&file_to_sample_file_name,
&file_to_sample_end,
0, /* location */
0, /* set_location */
0, /* channel */
0, 0, 0, 0, 0,
&no_reset,
0,
&file_to_sample_safety,
&file_to_sample_set_safety
};
mus_float_t mus_in_any_from_file(mus_any *ptr, mus_long_t samp, int chan)
{
/* check in-core buffer bounds,
* if needed read new buffer (taking into account dir)
* return mus_float_t at samp (frame)
*/
rdin *gen = (rdin *)ptr;
mus_float_t result = 0.0;
if ((chan >= gen->chans) ||
(samp < 0))
return(0.0);
if ((samp <= gen->data_end) &&
(samp >= gen->data_start))
{
result = (mus_float_t)MUS_SAMPLE_TO_FLOAT(gen->ibufs[chan][samp - gen->data_start]);
}
else
{
if ((samp >= 0) &&
(samp < gen->file_end))
{
/* got to read it from the file */
int fd;
mus_long_t newloc;
/* read in first buffer start either at samp (dir > 0) or samp-bufsize (dir < 0) */
if (gen->dir >= 0)
newloc = samp;
else newloc = (mus_long_t)(samp - (gen->file_buffer_size * .75));
/* The .75 in the backwards read is trying to avoid reading the full buffer on
* nearly every sample when we're oscillating around the
* nominal buffer start/end (in src driven by an oscil for example)
*/
if (newloc < 0) newloc = 0;
gen->data_start = newloc;
gen->data_end = newloc + gen->file_buffer_size - 1;
fd = mus_sound_open_input(gen->file_name);
if (fd == -1)
return((mus_float_t)mus_error(MUS_CANT_OPEN_FILE,
"open(%s) -> %s",
gen->file_name, STRERROR(errno)));
else
{
int i;
if (gen->ibufs == NULL)
{
gen->ibufs = (mus_sample_t **)clm_malloc(gen->chans * sizeof(mus_sample_t *), "input buffers");
for (i = 0; i < gen->chans; i++)
gen->ibufs[i] = (mus_sample_t *)clm_calloc(gen->file_buffer_size, sizeof(mus_sample_t), "input buffer");
}
mus_file_seek_frame(fd, gen->data_start);
if ((gen->data_start + gen->file_buffer_size) >= gen->file_end)
mus_file_read_chans(fd, 0, gen->file_end - gen->data_start - 1, gen->chans, gen->ibufs, gen->ibufs);
else mus_file_read_chans(fd, 0, gen->file_buffer_size - 1, gen->chans, gen->ibufs, gen->ibufs);
/* we have to check file_end here because chunked files can have trailing chunks containing
* comments or whatever. io.c (mus_file_read_*) merely calls read, and translates bytes --
* if it gets fewer than requested, it zeros from the point where the incoming file data stopped,
* but that can be far beyond the actual end of the sample data! It is at this level that
* we know how much data is actually supposed to be in the file.
*
* Also, file_end is the number of frames, so we should not read samp # file_end (see above).
*/
mus_sound_close_input(fd);
if (gen->data_end > gen->file_end) gen->data_end = gen->file_end;
}
result = (mus_float_t)MUS_SAMPLE_TO_FLOAT(gen->ibufs[chan][samp - gen->data_start]);
}
}
return(result);
}
static int file_to_sample_end(mus_any *ptr)
{
rdin *gen = (rdin *)ptr;
if (gen)
{
if (gen->ibufs)
{
int i;
for (i = 0; i < gen->chans; i++)
if (gen->ibufs[i])
clm_free(gen->ibufs[i]);
clm_free(gen->ibufs);
gen->ibufs = NULL;
}
}
return(0);
}
bool mus_file_to_sample_p(mus_any *ptr)
{
return((ptr) &&
(ptr->core->type == MUS_FILE_TO_SAMPLE));
}
mus_any *mus_make_file_to_sample_with_buffer_size(const char *filename, mus_long_t buffer_size)
{
rdin *gen;
if (filename == NULL)
mus_error(MUS_NO_FILE_NAME_PROVIDED, S_make_file_to_sample " requires a file name");
else
{
gen = (rdin *)clm_calloc(1, sizeof(rdin), S_make_file_to_sample);
gen->core = &FILE_TO_SAMPLE_CLASS;
gen->file_buffer_size = buffer_size;
gen->file_name = (char *)clm_calloc(strlen(filename) + 1, sizeof(char), S_file_to_sample " filename");
strcpy(gen->file_name, filename);
gen->data_end = -1; /* force initial read */
gen->chans = mus_sound_chans(gen->file_name);
if (gen->chans <= 0)
mus_error(MUS_NO_CHANNELS, "%s chans: %d", filename, gen->chans);
gen->file_end = mus_sound_frames(gen->file_name);
if (gen->file_end < 0)
mus_error(MUS_NO_LENGTH, "%s frames: " MUS_LD, filename, gen->file_end);
return((mus_any *)gen);
}
return(NULL);
}
mus_any *mus_make_file_to_sample(const char *filename)
{
return(mus_make_file_to_sample_with_buffer_size(filename, clm_file_buffer_size));
}
mus_float_t mus_file_to_sample(mus_any *ptr, mus_long_t samp, int chan)
{
return(mus_in_any_from_file(ptr, samp, chan));
}
/* ---------------- readin ---------------- */
/* readin reads only the desired channel and increments the location by the direction
* it inherits from and specializes the file_to_sample class
*/
static char *describe_readin(mus_any *ptr)
{
rdin *gen = (rdin *)ptr;
char *describe_buffer;
describe_buffer = (char *)clm_malloc(DESCRIBE_BUFFER_SIZE, "describe buffer");
mus_snprintf(describe_buffer, DESCRIBE_BUFFER_SIZE, "%s %s[chan %d], loc: " MUS_LD ", dir: %d",
mus_name(ptr),
gen->file_name, gen->chan, gen->loc, gen->dir);
return(describe_buffer);
}
static int free_readin(mus_any *p)
{
rdin *ptr = (rdin *)p;
if (ptr)
{
if (ptr->core->end) ((*ptr->core->end))(p);
clm_free(ptr->file_name);
clm_free(ptr);
}
return(0);
}
static mus_float_t run_readin(mus_any *ptr, mus_float_t unused1, mus_float_t unused2) {return(mus_readin(ptr));}
static mus_float_t rd_increment(mus_any *ptr) {return((mus_float_t)(((rdin *)ptr)->dir));}
static mus_float_t rd_set_increment(mus_any *ptr, mus_float_t val) {((rdin *)ptr)->dir = (int)val; return(val);}
static mus_long_t rd_location(mus_any *rd) {return(((rdin *)rd)->loc);}
static mus_long_t rd_set_location(mus_any *rd, mus_long_t loc) {((rdin *)rd)->loc = loc; return(loc);}
static int rd_channel(mus_any *rd) {return(((rdin *)rd)->chan);}
static mus_any_class READIN_CLASS = {
MUS_READIN,
(char *)S_readin,
&free_readin,
&describe_readin,
&rdin_equalp,
0, 0,
&file_to_sample_length, 0,
0, 0, 0, 0,
&fallback_scaler, 0,
&rd_increment,
&rd_set_increment,
&run_readin,
MUS_INPUT,
NULL,
&file_to_sample_channels,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
&mus_in_any_from_file,
0,
&file_to_sample_file_name,
&file_to_sample_end,
&rd_location,
&rd_set_location,
&rd_channel,
0, 0, 0, 0, 0,
&no_reset,
0, 0, 0
};
bool mus_readin_p(mus_any *ptr)
{
return((ptr) &&
(ptr->core->type == MUS_READIN));
}
mus_any *mus_make_readin_with_buffer_size(const char *filename, int chan, mus_long_t start, int direction, mus_long_t buffer_size)
{
rdin *gen;
gen = (rdin *)mus_make_file_to_sample(filename);
if (gen)
{
gen->core = &READIN_CLASS;
gen->loc = start;
gen->dir = direction;
gen->chan = chan;
gen->file_buffer_size = buffer_size;
gen->ibufs = (mus_sample_t **)clm_calloc(gen->chans, sizeof(mus_sample_t *), "readin buffers");
gen->ibufs[chan] = (mus_sample_t *)clm_calloc(gen->file_buffer_size, sizeof(mus_sample_t), "readin buffer");
return((mus_any *)gen);
}
return(NULL);
}
mus_float_t mus_readin(mus_any *ptr)
{
mus_float_t res;
rdin *rd = (rdin *)ptr;
res = mus_in_any_from_file(ptr, rd->loc, rd->chan);
rd->loc += rd->dir;
return(res);
}
mus_long_t mus_set_location(mus_any *gen, mus_long_t loc)
{
if ((check_gen(gen, S_setB S_mus_location)) &&
(gen->core->set_location))
return((*(gen->core->set_location))(gen, loc));
return((mus_long_t)mus_error(MUS_NO_LOCATION, "can't set %s's location", mus_name(gen)));
}
/* ---------------- in-any ---------------- */
mus_float_t mus_in_any(mus_long_t samp, int chan, mus_any *IO)
{
if (IO) return(mus_read_sample(IO, samp, chan));
return(0.0);
}
/* ---------------- file->frame ---------------- */
/* also built on file->sample */
static char *describe_file_to_frame(mus_any *ptr)
{
rdin *gen = (rdin *)ptr;
char *describe_buffer;
describe_buffer = (char *)clm_malloc(DESCRIBE_BUFFER_SIZE, "describe buffer");
mus_snprintf(describe_buffer, DESCRIBE_BUFFER_SIZE, "%s %s",
mus_name(ptr),
gen->file_name);
return(describe_buffer);
}
static mus_float_t run_file_to_frame(mus_any *ptr, mus_float_t arg1, mus_float_t arg2)
{
mus_error(MUS_NO_RUN, "no run method for file->frame");
return(0.0);
}
static mus_any_class FILE_TO_FRAME_CLASS = {
MUS_FILE_TO_FRAME,
(char *)S_file_to_frame,
&free_file_to_sample,
&describe_file_to_frame,
&rdin_equalp,
0, 0,
&file_to_sample_length, 0,
0, 0, 0, 0,
&fallback_scaler, 0,
&file_to_sample_increment, /* allow backward reads */
&file_to_sample_set_increment,
&run_file_to_frame,
MUS_INPUT,
NULL,
&file_to_sample_channels,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
&mus_in_any_from_file,
0,
&file_to_sample_file_name,
&file_to_sample_end,
0, /* location */
0, /* set_location */
0, /* channel */
0, 0, 0, 0, 0,
&no_reset,
0, 0, 0
};
mus_any *mus_make_file_to_frame_with_buffer_size(const char *filename, mus_long_t buffer_size)
{
rdin *gen;
gen = (rdin *)mus_make_file_to_sample_with_buffer_size(filename, buffer_size);
if (gen)
{
gen->core = &FILE_TO_FRAME_CLASS;
return((mus_any *)gen);
}
return(NULL);
}
mus_any *mus_make_file_to_frame(const char *filename)
{
return(mus_make_file_to_frame_with_buffer_size(filename, clm_file_buffer_size));
}
bool mus_file_to_frame_p(mus_any *ptr)
{
return((ptr) &&
(ptr->core->type == MUS_FILE_TO_FRAME));
}
mus_any *mus_file_to_frame(mus_any *ptr, mus_long_t samp, mus_any *uf)
{
mus_frame *f;
rdin *gen = (rdin *)ptr;
int i;
if (uf == NULL)
f = (mus_frame *)mus_make_empty_frame(gen->chans);
else f = (mus_frame *)uf;
for (i = 0; i < gen->chans; i++)
f->vals[i] = mus_in_any_from_file(ptr, samp, i);
return((mus_any *)f);
}
/* ---------------- sample->file ---------------- */
/* in all output functions, the assumption is that we're adding to whatever already exists */
/* also, the "end" methods need to flush the output buffer */
typedef struct {
mus_any_class *core;
int chan;
mus_long_t loc;
char *file_name;
int chans;
mus_sample_t **obufs;
mus_long_t data_start, data_end;
mus_long_t out_end;
int output_data_format;
int output_header_type;
int safety;
} rdout;
static char *describe_sample_to_file(mus_any *ptr)
{
rdout *gen = (rdout *)ptr;
char *describe_buffer;
describe_buffer = (char *)clm_malloc(DESCRIBE_BUFFER_SIZE, "describe buffer");
mus_snprintf(describe_buffer, DESCRIBE_BUFFER_SIZE, "%s %s",
mus_name(ptr),
gen->file_name);
return(describe_buffer);
}
static bool sample_to_file_equalp(mus_any *p1, mus_any *p2) {return(p1 == p2);}
static int free_sample_to_file(mus_any *p)
{
rdout *ptr = (rdout *)p;
if (ptr)
{
if (ptr->core->end) ((*ptr->core->end))(p);
clm_free(ptr->file_name);
clm_free(ptr);
}
return(0);
}
static int sample_to_file_channels(mus_any *ptr) {return((int)(((rdout *)ptr)->chans));}
static mus_long_t bufferlen(mus_any *ptr) {return(clm_file_buffer_size);}
static mus_long_t set_bufferlen(mus_any *ptr, mus_long_t len) {clm_file_buffer_size = len; return(len);}
static char *sample_to_file_file_name(mus_any *ptr) {return(((rdout *)ptr)->file_name);}
static int sample_to_file_safety(mus_any *ptr) {return(((rdout *)ptr)->safety);}
static int sample_to_file_set_safety(mus_any *ptr, int val) {((rdout *)ptr)->safety = val; return(val);}
static int sample_to_file_end(mus_any *ptr);
static mus_float_t run_sample_to_file(mus_any *ptr, mus_float_t arg1, mus_float_t arg2) {mus_error(MUS_NO_RUN, "no run method for sample->file"); return(0.0);}
static mus_any_class SAMPLE_TO_FILE_CLASS = {
MUS_SAMPLE_TO_FILE,
(char *)S_sample_to_file,
&free_sample_to_file,
&describe_sample_to_file,
&sample_to_file_equalp,
0, 0,
&bufferlen, &set_bufferlen, /* does this have any effect on the current gen? */
0, 0, 0, 0,
&fallback_scaler, 0,
0, 0,
&run_sample_to_file,
MUS_OUTPUT,
NULL,
&sample_to_file_channels,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0,
&mus_out_any_to_file,
&sample_to_file_file_name,
&sample_to_file_end,
0, 0, 0,
0, 0, 0, 0, 0,
&no_reset,
0,
&sample_to_file_safety,
&sample_to_file_set_safety
};
static int *data_format_zero = NULL;
int mus_data_format_zero(int format)
{
return(data_format_zero[format]);
}
static void flush_buffers(rdout *gen)
{
int fd;
if ((gen->obufs == NULL) ||
(mus_file_probe(gen->file_name) == 0) ||
(gen->chans == 0))
return; /* can happen if output abandoned, then later mus_free called via GC sweep */
fd = mus_sound_open_input(gen->file_name);
if (fd == -1)
{
/* no output yet, so open the output file and write the current samples (no need to add to existing samples in this case) */
fd = mus_sound_open_output(gen->file_name,
(int)sampling_rate,
gen->chans,
gen->output_data_format,
gen->output_header_type,
NULL);
if (fd == -1)
mus_error(MUS_CANT_OPEN_FILE,
"open(%s) -> %s",
gen->file_name, STRERROR(errno));
else
{
mus_file_write(fd, 0, gen->out_end, gen->chans, gen->obufs);
mus_sound_close_output(fd, (gen->out_end + 1) * gen->chans * mus_bytes_per_sample(mus_sound_data_format(gen->file_name)));
}
}
else
{
/* get existing samples, add new output, write back to output */
mus_sample_t **addbufs;
int i, j, data_format;
mus_long_t current_file_frames, frames_to_add;
data_format = mus_sound_data_format(gen->file_name);
current_file_frames = mus_sound_frames(gen->file_name);
addbufs = (mus_sample_t **)clm_calloc(gen->chans, sizeof(mus_sample_t *), "output buffers");
{
bool allocation_failed = false;
for (i = 0; i < gen->chans; i++)
{
/* clm_file_buffer_size may be too large, but it's very hard to tell that
* in advance. In Linux, malloc returns a non-null pointer even when
* there's no memory available, so you have to touch the memory to force
* the OS to deal with it, then the next allocation returns null.
* So, here we go...
*/
addbufs[i] = (mus_sample_t *)calloc(clm_file_buffer_size, sizeof(mus_sample_t));
if (addbufs[i])
addbufs[i][0] = MUS_SAMPLE_0;
else
{
allocation_failed = true;
break;
}
}
if (allocation_failed)
{
mus_long_t old_file_buffer_size = 0;
/* first clean up the mess we made */
for (i = 0; i < gen->chans; i++)
if (addbufs[i])
{
free(addbufs[i]);
addbufs[i] = NULL;
}
clm_free(addbufs);
/* it would take a lot of screwing around to find the biggest clm_file_buffer_size we could handle,
* and it might fail on the next call (if more chans), so we'll throw an error. We could get
* say 1024 samps per chan, then run through a loop outputting the current buffer, but geez...
*/
/* but... if we hit this in with-sound, mus_error calls (eventually) s7_error which sees the
* dynamic-wind and tries to call mus-close, which tries to flush the buffers and we have
* an infinite loop. So, we need to clean up right now.
*/
mus_sound_close_input(fd);
old_file_buffer_size = clm_file_buffer_size;
clm_file_buffer_size = MUS_DEFAULT_FILE_BUFFER_SIZE;
mus_error(MUS_MEMORY_ALLOCATION_FAILED, S_mus_file_buffer_size " (" MUS_LD ") is too large: we can't allocate the output buffers!", old_file_buffer_size);
return;
}
}
mus_file_seek_frame(fd, gen->data_start);
frames_to_add = gen->out_end - gen->data_start;
/* if the caller reset clm_file_buffer_size during a run, frames_to_add might be greater than the assumed buffer size,
* so we need to complain and fix up the limits. In CLM, the size is set in sound.lisp, begin-with-sound.
* In Snd via mus_set_file_buffer_size in clm2xen.c. The initial default is set in mus_initialize
* called in CLM by clm-initialize-links via in cmus.c, and in Snd in clm2xen.c when the module is setup.
*/
if (frames_to_add >= clm_file_buffer_size)
{
mus_print("clm-file-buffer-size changed? " MUS_LD " <= " MUS_LD " (start: " MUS_LD ", end: " MUS_LD ", " MUS_LD ")",
clm_file_buffer_size, frames_to_add, gen->data_start, gen->data_end, gen->out_end);
frames_to_add = clm_file_buffer_size - 1;
/* this means we drop samples -- the other choice (short of throwing an error) would
* be to read/allocate the bigger size.
*/
}
mus_file_read(fd, 0, frames_to_add, gen->chans, addbufs);
mus_sound_close_input(fd);
fd = mus_sound_reopen_output(gen->file_name, gen->chans, data_format,
mus_sound_header_type(gen->file_name),
mus_sound_data_location(gen->file_name));
if ((current_file_frames < gen->data_start) &&
(data_format_zero[data_format] != 0))
{
/* we're about to create a gap in the output file. mus_file_seek_frame calls lseek which (man lseek):
*
* "The lseek function allows the file offset to be set beyond the end of
* the existing end-of-file of the file (but this does not change the size
* of the file). If data is later written at this point, subsequent reads
* of the data in the gap return bytes of zeros (until data is actually
* written into the gap)."
*
* but 0 bytes in a file are not interpreted as sound samples of 0 in several data formats.
* for example, mus-mulaw 0 => -.98, whereas sound sample 0 is a byte of 255.
* see the table at the end of this file (data_format_zero) for the other cases.
*
* So, we need to write explicit data-format 0 values in those cases where machine 0's
* won't be data format 0. data_format_zero[format] != 0 signals we have such a
* case, and returns the nominal zero value. For unsigned shorts, we also need to
* take endianess into account.
*
* Since addbufs is empty here, and is of type mus_sample_t, I'll take the slightly
* slower but simpler path of calling mus_file_write to handle all the translations.
*/
mus_long_t filler, current_samps;
filler = gen->data_start - current_file_frames;
mus_file_seek_frame(fd, current_file_frames);
while (filler > 0)
{
if (filler > clm_file_buffer_size)
current_samps = clm_file_buffer_size;
else current_samps = filler;
mus_file_write(fd, 0, current_samps - 1, gen->chans, addbufs);
filler -= current_samps;
}
}
/* fill/write output buffers with current data added to saved data (if any) */
for (j = 0; j < gen->chans; j++)
for (i = 0; i <= frames_to_add; i++)
addbufs[j][i] += gen->obufs[j][i];
mus_file_seek_frame(fd, gen->data_start);
mus_file_write(fd, 0, frames_to_add, gen->chans, addbufs);
if (current_file_frames <= gen->out_end) current_file_frames = gen->out_end + 1;
mus_sound_close_output(fd, current_file_frames * gen->chans * mus_bytes_per_sample(data_format));
for (i = 0; i < gen->chans; i++)
free(addbufs[i]); /* used calloc above to make sure we can check for unsuccessful allocation */
clm_free(addbufs);
}
}
mus_any *mus_sample_to_file_add(mus_any *out1, mus_any *out2)
{
mus_long_t min_frames;
rdout *dest = (rdout *)out1;
rdout *in_coming = (rdout *)out2;
int chn, min_chans;
min_chans = dest->chans;
if (in_coming->chans < min_chans) min_chans = in_coming->chans;
min_frames = in_coming->out_end;
for (chn = 0; chn < min_chans; chn++)
{
mus_long_t i;
for (i = 0; i < min_frames; i++)
dest->obufs[chn][i] += in_coming->obufs[chn][i];
memset((void *)(in_coming->obufs[chn]), 0, min_frames * sizeof(mus_sample_t));
}
if (min_frames > dest->out_end)
dest->out_end = min_frames;
in_coming->out_end = 0;
in_coming->data_start = 0;
return((mus_any*)dest);
}
mus_float_t mus_out_any_to_file(mus_any *ptr, mus_long_t samp, int chan, mus_float_t val)
{
rdout *gen = (rdout *)ptr;
if (!ptr) return(val);
if ((chan >= gen->chans) ||
(!(gen->obufs)) ||
(samp < 0))
return(val);
if (gen->safety == 1)
{
gen->obufs[chan][samp] += MUS_FLOAT_TO_SAMPLE(val);
if (samp > gen->out_end)
gen->out_end = samp;
return(val);
}
if ((samp <= gen->data_end) &&
(samp >= gen->data_start))
gen->obufs[chan][samp - gen->data_start] += MUS_FLOAT_TO_SAMPLE(val);
else
{
int j;
flush_buffers(gen);
for (j = 0; j < gen->chans; j++)
memset((void *)(gen->obufs[j]), 0, clm_file_buffer_size * sizeof(mus_sample_t));
gen->data_start = samp;
gen->data_end = samp + clm_file_buffer_size - 1;
gen->obufs[chan][samp - gen->data_start] += MUS_FLOAT_TO_SAMPLE(val);
gen->out_end = samp; /* this resets the current notion of where in the buffer the new data ends */
}
if (samp > gen->out_end)
gen->out_end = samp;
return(val);
}
static int sample_to_file_end(mus_any *ptr)
{
rdout *gen = (rdout *)ptr;
if ((gen) && (gen->obufs))
{
int i;
if (gen->chans > 0)
{
flush_buffers(gen); /* this forces the error handling stuff, unlike in free reader case */
for (i = 0; i < gen->chans; i++)
if (gen->obufs[i])
clm_free(gen->obufs[i]);
}
clm_free(gen->obufs);
gen->obufs = NULL;
}
return(0);
}
bool mus_sample_to_file_p(mus_any *ptr)
{
return((ptr) &&
(ptr->core->type == MUS_SAMPLE_TO_FILE));
}
static mus_any *mus_make_sample_to_file_with_comment_1(const char *filename, int out_chans, int out_format, int out_type, const char *comment, bool reopen)
{
int fd;
if (filename == NULL)
mus_error(MUS_NO_FILE_NAME_PROVIDED, S_make_sample_to_file " requires a file name");
else
{
if (reopen)
fd = mus_sound_reopen_output(filename, out_chans, out_format, out_type, mus_sound_data_location(filename));
else fd = mus_sound_open_output(filename, (int)sampling_rate, out_chans, out_format, out_type, comment);
if (fd == -1)
mus_error(MUS_CANT_OPEN_FILE,
"open(%s) -> %s",
filename, STRERROR(errno));
else
{
rdout *gen;
int i;
gen = (rdout *)clm_calloc(1, sizeof(rdout), "output");
gen->core = &SAMPLE_TO_FILE_CLASS;
gen->file_name = (char *)clm_calloc(strlen(filename) + 1, sizeof(char), "output filename");
strcpy(gen->file_name, filename);
gen->data_start = 0;
gen->data_end = clm_file_buffer_size - 1;
gen->out_end = 0;
gen->chans = out_chans;
gen->output_data_format = out_format;
gen->output_header_type = out_type;
gen->obufs = (mus_sample_t **)clm_calloc(gen->chans, sizeof(mus_sample_t *), "output buffers");
for (i = 0; i < gen->chans; i++)
gen->obufs[i] = (mus_sample_t *)clm_calloc(clm_file_buffer_size, sizeof(mus_sample_t), "output buffer");
/* clear previous, if any */
if (mus_file_close(fd) != 0)
mus_error(MUS_CANT_CLOSE_FILE,
"close(%d, %s) -> %s",
fd, gen->file_name, STRERROR(errno));
return((mus_any *)gen);
}
}
return(NULL);
}
mus_any *mus_continue_sample_to_file(const char *filename)
{
return(mus_make_sample_to_file_with_comment_1(filename,
mus_sound_chans(filename),
mus_sound_data_format(filename),
mus_sound_header_type(filename),
NULL,
true));
}
mus_any *mus_make_sample_to_file_with_comment(const char *filename, int out_chans, int out_format, int out_type, const char *comment)
{
return(mus_make_sample_to_file_with_comment_1(filename, out_chans, out_format, out_type, comment, false));
}
mus_float_t mus_sample_to_file(mus_any *ptr, mus_long_t samp, int chan, mus_float_t val)
{
return(mus_write_sample(ptr, samp, chan, val)); /* write_sample -> write_sample in class struct -> mus_out_any_to_file for example */
}
int mus_close_file(mus_any *ptr)
{
rdout *gen = (rdout *)ptr;
if ((mus_output_p(ptr)) && (gen->obufs)) sample_to_file_end(ptr);
return(0);
}
/* ---------------- out-any ---------------- */
mus_float_t mus_out_any(mus_long_t samp, mus_float_t val, int chan, mus_any *IO)
{
if ((IO) && (samp >= 0))
return(mus_write_sample(IO, samp, chan, val));
return(val);
}
/* ---------------- frame->file ---------------- */
static char *describe_frame_to_file(mus_any *ptr)
{
rdout *gen = (rdout *)ptr;
char *describe_buffer;
describe_buffer = (char *)clm_malloc(DESCRIBE_BUFFER_SIZE, "describe buffer");
mus_snprintf(describe_buffer, DESCRIBE_BUFFER_SIZE, "%s %s",
mus_name(ptr),
gen->file_name);
return(describe_buffer);
}
static mus_float_t run_frame_to_file(mus_any *ptr, mus_float_t arg1, mus_float_t arg2)
{
mus_error(MUS_NO_RUN, "no run method for frame->file");
return(0.0);
}
static mus_any_class FRAME_TO_FILE_CLASS = {
MUS_FRAME_TO_FILE,
(char *)S_frame_to_file,
&free_sample_to_file,
&describe_frame_to_file,
&sample_to_file_equalp,
0, 0,
&bufferlen, &set_bufferlen,
0, 0, 0, 0,
&fallback_scaler, 0,
0, 0,
&run_frame_to_file,
MUS_OUTPUT,
NULL,
&sample_to_file_channels,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0,
&mus_out_any_to_file,
&sample_to_file_file_name,
&sample_to_file_end,
0, 0, 0,
0, 0, 0, 0, 0,
&no_reset,
0,
&sample_to_file_safety,
&sample_to_file_set_safety
};
mus_any *mus_make_frame_to_file_with_comment(const char *filename, int chans, int out_format, int out_type, const char *comment)
{
rdout *gen = NULL;
gen = (rdout *)mus_make_sample_to_file_with_comment(filename, chans, out_format, out_type, comment);
if (gen) gen->core = &FRAME_TO_FILE_CLASS;
return((mus_any *)gen);
}
bool mus_frame_to_file_p(mus_any *ptr)
{
return((ptr) &&
(ptr->core->type == MUS_FRAME_TO_FILE));
}
mus_any *mus_frame_to_file(mus_any *ptr, mus_long_t samp, mus_any *udata)
{
rdout *gen = (rdout *)ptr;
mus_frame *data = (mus_frame *)udata;
if (data)
{
if (data->chans == 1)
mus_out_any_to_file(ptr, samp, 0, data->vals[0]);
else
{
if ((data->chans == 2) &&
(gen->chans == 2))
{
mus_out_any_to_file(ptr, samp, 0, data->vals[0]);
mus_out_any_to_file(ptr, samp, 1, data->vals[1]);
}
else
{
int i, chans;
chans = data->chans;
if (gen->chans < chans)
chans = gen->chans;
for (i = 0; i < chans; i++)
mus_out_any_to_file(ptr, samp, i, data->vals[i]);
}
}
}
return(udata);
}
mus_any *mus_continue_frame_to_file(const char *filename)
{
rdout *gen = NULL;
gen = (rdout *)mus_continue_sample_to_file(filename);
if (gen) gen->core = &FRAME_TO_FILE_CLASS;
return((mus_any *)gen);
}
/* ---------------- locsig ---------------- */
typedef struct {
mus_any_class *core;
mus_any *outn_writer;
mus_any *revn_writer;
mus_frame *outf, *revf;
mus_float_t *outn;
mus_float_t *revn;
int chans, rev_chans;
mus_interp_t type;
mus_float_t reverb;
void *closure;
int safety;
} locs;
static bool locsig_equalp(mus_any *p1, mus_any *p2)
{
locs *g1 = (locs *)p1;
locs *g2 = (locs *)p2;
if (p1 == p2) return(true);
return((g1) && (g2) &&
(g1->core->type == g2->core->type) &&
(g1->chans == g2->chans) &&
(clm_arrays_are_equal(g1->outn, g2->outn, g1->chans)) &&
(((bool)(g1->revn != NULL)) == ((bool)(g2->revn != NULL))) &&
((!(g1->revn)) || (clm_arrays_are_equal(g1->revn, g2->revn, g1->rev_chans))));
}
static char *describe_locsig(mus_any *ptr)
{
char *str;
int i, lim = 16;
locs *gen = (locs *)ptr;
char *describe_buffer;
describe_buffer = (char *)clm_malloc(DESCRIBE_BUFFER_SIZE, "describe buffer");
mus_snprintf(describe_buffer, DESCRIBE_BUFFER_SIZE, "%s chans %d, outn: [",
mus_name(ptr),
gen->chans);
str = (char *)clm_calloc(STR_SIZE, sizeof(char), "describe_locsig");
if (gen->outn)
{
if (gen->chans - 1 < lim) lim = gen->chans - 1;
for (i = 0; i < lim; i++)
{
mus_snprintf(str, STR_SIZE, "%.3f ", gen->outn[i]);
if ((strlen(describe_buffer) + strlen(str)) < (DESCRIBE_BUFFER_SIZE - 16))
strcat(describe_buffer, str);
else break;
}
if (gen->chans - 1 > lim) strcat(describe_buffer, "...");
mus_snprintf(str, STR_SIZE, "%.3f]", gen->outn[gen->chans - 1]);
strcat(describe_buffer, str);
}
else
{
strcat(describe_buffer, "nil!]");
}
if ((gen->rev_chans > 0) && (gen->revn))
{
strcat(describe_buffer, ", revn: [");
lim = 16;
if (gen->rev_chans - 1 < lim) lim = gen->rev_chans - 1;
for (i = 0; i < lim; i++)
{
mus_snprintf(str, STR_SIZE, "%.3f ", gen->revn[i]);
if ((strlen(describe_buffer) + strlen(str)) < (DESCRIBE_BUFFER_SIZE - 16))
strcat(describe_buffer, str);
else break;
}
if (gen->rev_chans - 1 > lim) strcat(describe_buffer, "...");
mus_snprintf(str, STR_SIZE, "%.3f]", gen->revn[gen->rev_chans - 1]);
strcat(describe_buffer, str);
}
mus_snprintf(str, STR_SIZE, ", interp: %s", interp_type_to_string(gen->type));
strcat(describe_buffer, str);
clm_free(str);
return(describe_buffer);
}
static int free_locsig(mus_any *p)
{
locs *ptr = (locs *)p;
if (ptr)
{
if (ptr->outn)
{
clm_free(ptr->outn);
ptr->outn = NULL;
}
if (ptr->revn)
{
clm_free(ptr->revn);
ptr->revn = NULL;
}
mus_free((mus_any *)(ptr->outf));
ptr->outf = NULL;
if (ptr->revf)
{
mus_free((mus_any *)(ptr->revf));
ptr->revf = NULL;
}
ptr->outn_writer = NULL;
ptr->revn_writer = NULL;
ptr->chans = 0;
ptr->rev_chans = 0;
clm_free(ptr);
}
return(0);
}
static int locsig_safety(mus_any *ptr) {return(((locs *)ptr)->safety);}
static int locsig_set_safety(mus_any *ptr, int val) {((locs *)ptr)->safety = val; return(val);}
static mus_long_t locsig_length(mus_any *ptr) {return(((locs *)ptr)->chans);}
static int locsig_channels(mus_any *ptr) {return(((locs *)ptr)->chans);}
static mus_float_t *locsig_data(mus_any *ptr) {return(((locs *)ptr)->outn);}
static mus_float_t *locsig_xcoeffs(mus_any *ptr) {return(((locs *)ptr)->revn);}
mus_any *mus_locsig_outf(mus_any *ptr) {return((mus_any *)(((locs *)ptr)->outf));} /* clm2xen.c */
mus_any *mus_locsig_revf(mus_any *ptr) {return((mus_any *)(((locs *)ptr)->revf));}
void *mus_locsig_closure(mus_any *ptr) {return(((locs *)ptr)->closure);} /* run.c */
static void *locsig_set_closure(mus_any *ptr, void *e) {((locs *)ptr)->closure = e; return(e);}
static void locsig_reset(mus_any *ptr)
{
locs *gen = (locs *)ptr;
if (gen->outn) mus_clear_array(gen->outn, gen->chans);
if (gen->revn) mus_clear_array(gen->revn, gen->rev_chans);
}
static mus_float_t locsig_xcoeff(mus_any *ptr, int index)
{
locs *gen = (locs *)ptr;
if (gen->revn)
return(gen->revn[index]);
return(0.0);
}
static mus_float_t locsig_set_xcoeff(mus_any *ptr, int index, mus_float_t val)
{
locs *gen = (locs *)ptr;
if (gen->revn)
gen->revn[index] = val;
return(val);
}
static mus_any *locsig_warned = NULL;
/* these locsig error messages are a pain -- using the output pointer in the wan hope that
* subsequent runs will use a different output generator.
*/
mus_float_t mus_locsig_ref(mus_any *ptr, int chan)
{
locs *gen = (locs *)ptr;
if ((ptr) && (mus_locsig_p(ptr)))
{
if ((chan >= 0) &&
(chan < gen->chans))
return(gen->outn[chan]);
else
{
if (locsig_warned != gen->outn_writer)
{
mus_error(MUS_NO_SUCH_CHANNEL,
S_locsig_ref " chan %d >= %d",
chan, gen->chans);
locsig_warned = gen->outn_writer;
}
}
}
return(0.0);
}
mus_float_t mus_locsig_set(mus_any *ptr, int chan, mus_float_t val)
{
locs *gen = (locs *)ptr;
if ((ptr) && (mus_locsig_p(ptr)))
{
if ((chan >= 0) &&
(chan < gen->chans))
gen->outn[chan] = val;
else
{
if (locsig_warned != gen->outn_writer)
{
mus_error(MUS_NO_SUCH_CHANNEL,
S_locsig_set " chan %d >= %d",
chan, gen->chans);
locsig_warned = gen->outn_writer;
}
}
}
return(val);
}
mus_float_t mus_locsig_reverb_ref(mus_any *ptr, int chan)
{
locs *gen = (locs *)ptr;
if ((ptr) && (mus_locsig_p(ptr)))
{
if ((chan >= 0) &&
(chan < gen->rev_chans))
return(gen->revn[chan]);
else
{
if (locsig_warned != gen->outn_writer)
{
mus_error(MUS_NO_SUCH_CHANNEL,
S_locsig_reverb_ref " chan %d, but this locsig has %d reverb chans",
chan, gen->rev_chans);
locsig_warned = gen->outn_writer;
}
}
}
return(0.0);
}
mus_float_t mus_locsig_reverb_set(mus_any *ptr, int chan, mus_float_t val)
{
locs *gen = (locs *)ptr;
if ((ptr) && (mus_locsig_p(ptr)))
{
if ((chan >= 0) &&
(chan < gen->rev_chans))
gen->revn[chan] = val;
else
{
if (locsig_warned != gen->outn_writer)
{
mus_error(MUS_NO_SUCH_CHANNEL,
S_locsig_reverb_set " chan %d >= %d",
chan, gen->rev_chans);
locsig_warned = gen->outn_writer;
}
}
}
return(val);
}
static mus_float_t run_locsig(mus_any *ptr, mus_float_t arg1, mus_float_t arg2)
{
mus_locsig(ptr, (mus_long_t)arg1, arg2);
return(arg2);
}
static mus_any_class LOCSIG_CLASS = {
MUS_LOCSIG,
(char *)S_locsig,
&free_locsig,
&describe_locsig,
&locsig_equalp,
&locsig_data, 0,
&locsig_length,
0,
0, 0, 0, 0,
0, 0,
0, 0,
&run_locsig,
MUS_OUTPUT,
&mus_locsig_closure,
&locsig_channels,
0, 0, 0, 0,
&locsig_xcoeff, &locsig_set_xcoeff,
0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0,
0, 0,
&locsig_xcoeffs, 0, 0,
&locsig_reset,
&locsig_set_closure, /* the method name is set_environ (clm2xen.c) */
&locsig_safety, &locsig_set_safety
};
bool mus_locsig_p(mus_any *ptr)
{
return((ptr) &&
(ptr->core->type == MUS_LOCSIG));
}
static void mus_locsig_fill(mus_float_t *arr, int chans, mus_float_t degree, mus_float_t scaler, mus_interp_t type)
{
if (chans == 1)
arr[0] = scaler;
else
{
mus_float_t deg, pos, frac, degs_per_chan, ldeg, c, s;
int left, right;
/* this used to check for degree < 0.0 first, but as Michael Klingbeil noticed, that
* means that in the stereo case, the location can jump to 90 => click. It was also
* possible for a negative degree to leak through, causing a segfault in the Scheme
* version if "run" was in use.
*/
if (chans == 2)
{
/* there's no notion of a circle of speakers here, so we don't have to equate, for example, -90 and 270 */
if (degree > 90.0)
deg = 90.0;
else
{
if (degree < 0.0)
deg = 0.0;
else deg = degree;
}
degs_per_chan = 90.0;
}
else
{
deg = fmod(degree, 360.0);
if (deg < 0.0)
{
/* -0.0 is causing trouble when mus_float_t == float */
if (deg < -0.0000001)
deg += 360.0; /* C's fmod can return negative results when modulus is positive */
else deg = 0.0;
}
degs_per_chan = 360.0 / chans;
}
pos = deg / degs_per_chan;
left = (int)floor(pos);
right = left + 1;
if (right >= chans) right = 0;
frac = pos - left;
if (type == MUS_INTERP_LINEAR)
{
arr[left] = scaler * (1.0 - frac);
arr[right] = scaler * frac;
}
else
{
ldeg = M_PI_2 * (0.5 - frac);
scaler *= sqrt(2.0) / 2.0;
c = cos(ldeg);
s = sin(ldeg);
arr[left] = scaler * (c + s);
arr[right] = scaler * (c - s);
}
}
}
mus_any *mus_make_locsig(mus_float_t degree, mus_float_t distance, mus_float_t reverb,
int chans, mus_any *output, /* direct signal output */
int rev_chans, mus_any *revput, /* reverb output */
mus_interp_t type)
{
locs *gen;
mus_float_t dist;
if (chans <= 0)
{
mus_error(MUS_ARG_OUT_OF_RANGE, "chans: %d", chans);
return(NULL);
}
gen = (locs *)clm_calloc(1, sizeof(locs), S_make_locsig);
gen->core = &LOCSIG_CLASS;
gen->outf = (mus_frame *)mus_make_empty_frame(chans);
gen->type = type;
gen->reverb = reverb;
if (distance > 1.0)
dist = 1.0 / distance;
else dist = 1.0;
if (mus_output_p(output))
gen->outn_writer = output;
gen->chans = chans;
gen->outn = (mus_float_t *)clm_calloc(gen->chans, sizeof(mus_float_t), "locsig frame");
mus_locsig_fill(gen->outn, gen->chans, degree, dist, type);
if (mus_output_p(revput))
gen->revn_writer = revput;
gen->rev_chans = rev_chans;
if (gen->rev_chans > 0)
{
gen->revn = (mus_float_t *)clm_calloc(gen->rev_chans, sizeof(mus_float_t), "locsig reverb frame");
gen->revf = (mus_frame *)mus_make_empty_frame(gen->rev_chans);
mus_locsig_fill(gen->revn, gen->rev_chans, degree, (reverb * sqrt(dist)), type);
}
if ((gen->outn_writer) &&
(((rdout *)output)->safety == 1))
gen->safety = 1;
return((mus_any *)gen);
}
mus_float_t mus_locsig(mus_any *ptr, mus_long_t loc, mus_float_t val)
{
locs *gen = (locs *)ptr;
int i;
if (gen->safety == 1)
{
/* assume (since it's locsig) that we're eventually headed for sample->file, and
* (since safety == 1) that everything is ready to go, and the output frames are
* of no interest.
*/
if (gen->outn_writer)
{
rdout *writer = (rdout *)(gen->outn_writer);
for (i = 0; i < gen->chans; i++)
writer->obufs[i][loc] += MUS_FLOAT_TO_SAMPLE(val * gen->outn[i]);
if (loc > writer->out_end)
writer->out_end = loc;
}
if (gen->revn_writer)
{
rdout *writer = (rdout *)(gen->revn_writer);
for (i = 0; i < gen->rev_chans; i++)
writer->obufs[i][loc] += MUS_FLOAT_TO_SAMPLE(val * gen->revn[i]);
if (loc > writer->out_end)
writer->out_end = loc;
}
}
else
{
rdout *writer = (rdout *)(gen->outn_writer);
for (i = 0; i < gen->chans; i++)
{
(gen->outf)->vals[i] = val * gen->outn[i];
if (writer)
mus_out_any_to_file((mus_any *)writer, loc, i, gen->outf->vals[i]);
}
writer = (rdout *)(gen->revn_writer);
for (i = 0; i < gen->rev_chans; i++)
{
(gen->revf)->vals[i] = val * gen->revn[i];
if (writer)
mus_out_any_to_file((mus_any *)writer, loc, i, gen->revf->vals[i]);
}
}
return(val);
}
int mus_locsig_channels(mus_any *ptr)
{
return(((locs *)ptr)->chans);
}
int mus_locsig_reverb_channels(mus_any *ptr)
{
return(((locs *)ptr)->rev_chans);
}
int mus_locsig_safety(mus_any *ptr)
{
return(((locs *)ptr)->safety);
}
void mus_locsig_mono_no_reverb(mus_any *ptr, mus_long_t loc, mus_float_t val)
{
locs *gen = (locs *)ptr;
mus_out_any_to_file(gen->outn_writer, loc, 0, val * gen->outn[0]);
}
void mus_locsig_mono(mus_any *ptr, mus_long_t loc, mus_float_t val)
{
locs *gen = (locs *)ptr;
mus_out_any_to_file(gen->outn_writer, loc, 0, val * gen->outn[0]);
mus_out_any_to_file(gen->revn_writer, loc, 0, val * gen->revn[0]);
}
void mus_locsig_stereo_no_reverb(mus_any *ptr, mus_long_t loc, mus_float_t val)
{
locs *gen = (locs *)ptr;
mus_out_any_to_file(gen->outn_writer, loc, 0, val * gen->outn[0]);
mus_out_any_to_file(gen->outn_writer, loc, 1, val * gen->outn[1]);
}
void mus_locsig_stereo(mus_any *ptr, mus_long_t loc, mus_float_t val) /* but mono rev */
{
locs *gen = (locs *)ptr;
mus_out_any_to_file(gen->outn_writer, loc, 0, val * gen->outn[0]);
mus_out_any_to_file(gen->outn_writer, loc, 1, val * gen->outn[1]);
mus_out_any_to_file(gen->revn_writer, loc, 0, val * gen->revn[0]);
}
void mus_locsig_safe_mono_no_reverb(mus_any *ptr, mus_long_t loc, mus_float_t val)
{
locs *gen = (locs *)ptr;
rdout *writer = (rdout *)(gen->outn_writer);
writer->obufs[0][loc] += MUS_FLOAT_TO_SAMPLE(val * gen->outn[0]);
if (loc > writer->out_end)
writer->out_end = loc;
}
void mus_locsig_safe_mono(mus_any *ptr, mus_long_t loc, mus_float_t val)
{
locs *gen = (locs *)ptr;
rdout *writer = (rdout *)(gen->outn_writer);
writer->obufs[0][loc] += MUS_FLOAT_TO_SAMPLE(val * gen->outn[0]);
writer = (rdout *)(gen->revn_writer);
writer->obufs[0][loc] += MUS_FLOAT_TO_SAMPLE(val * gen->revn[0]);
if (loc > writer->out_end)
writer->out_end = loc;
}
void mus_locsig_safe_stereo_no_reverb(mus_any *ptr, mus_long_t loc, mus_float_t val)
{
locs *gen = (locs *)ptr;
rdout *writer = (rdout *)(gen->outn_writer);
writer->obufs[0][loc] += MUS_FLOAT_TO_SAMPLE(val * gen->outn[0]);
writer->obufs[1][loc] += MUS_FLOAT_TO_SAMPLE(val * gen->outn[1]);
if (loc > writer->out_end)
writer->out_end = loc;
}
void mus_locsig_safe_stereo(mus_any *ptr, mus_long_t loc, mus_float_t val)
{
locs *gen = (locs *)ptr;
rdout *writer = (rdout *)(gen->outn_writer);
writer->obufs[0][loc] += MUS_FLOAT_TO_SAMPLE(val * gen->outn[0]);
writer->obufs[1][loc] += MUS_FLOAT_TO_SAMPLE(val * gen->outn[1]);
writer = (rdout *)(gen->revn_writer);
writer->obufs[0][loc] += MUS_FLOAT_TO_SAMPLE(val * gen->revn[0]);
if (loc > writer->out_end)
writer->out_end = loc;
}
void mus_move_locsig(mus_any *ptr, mus_float_t degree, mus_float_t distance)
{
locs *gen = (locs *)ptr;
mus_float_t dist;
mus_reset(ptr); /* clear old state, if any */
if (distance > 1.0)
dist = 1.0 / distance;
else dist = 1.0;
if (gen->rev_chans > 0)
mus_locsig_fill(gen->revn, gen->rev_chans, degree, (gen->reverb * sqrt(dist)), gen->type);
mus_locsig_fill(gen->outn, gen->chans, degree, dist, gen->type);
}
/* ---------------- move-sound ---------------- */
/* TODO: move-sound rb: update dlocsig.rb (787, l788)
*/
typedef struct {
mus_any_class *core;
mus_any *outn_writer;
mus_any *revn_writer;
mus_frame *outf, *revf;
int out_channels, rev_channels;
mus_long_t start, end;
mus_any *doppler_delay, *doppler_env, *rev_env;
mus_any **out_delays, **out_envs, **rev_envs;
int *out_map;
bool free_arrays, free_gens;
void *closure;
} dloc;
static bool move_sound_equalp(mus_any *p1, mus_any *p2) {return(p1 == p2);}
static int move_sound_channels(mus_any *ptr) {return(((dloc *)ptr)->out_channels);}
static mus_long_t move_sound_length(mus_any *ptr) {return(((dloc *)ptr)->out_channels);} /* need both because return types differ */
static void move_sound_reset(mus_any *ptr) {}
mus_any *mus_move_sound_outf(mus_any *ptr) {return((mus_any *)(((dloc *)ptr)->outf));}
mus_any *mus_move_sound_revf(mus_any *ptr) {return((mus_any *)(((dloc *)ptr)->revf));}
void *mus_move_sound_closure(mus_any *ptr) {return(((dloc *)ptr)->closure);}
static void *move_sound_set_closure(mus_any *ptr, void *e) {((dloc *)ptr)->closure = e; return(e);}
static char *describe_move_sound(mus_any *ptr)
{
dloc *gen = (dloc *)ptr;
char *dopdly = NULL, *dopenv = NULL, *revenv = NULL;
char *outdlys = NULL, *outenvs = NULL, *revenvs = NULL;
char *outmap = NULL;
char *starts = NULL;
char *str1 = NULL, *str2 = NULL, *str3 = NULL;
char *allstr = NULL;
int len;
starts = mus_format("%s start: " MUS_LD ", end: " MUS_LD ", out chans %d, rev chans: %d",
mus_name(ptr),
gen->start,
gen->end,
gen->out_channels,
gen->rev_channels);
dopdly = mus_format("doppler %s", str1 = mus_describe(gen->doppler_delay));
dopenv = mus_format("doppler %s", str2 = mus_describe(gen->doppler_env));
revenv = mus_format("global reverb %s", str3 = mus_describe(gen->rev_env));
outdlys = clm_array_to_string(gen->out_delays, gen->out_channels, "out_delays", " ");
outenvs = clm_array_to_string(gen->out_envs, gen->out_channels, "out_envs", " ");
revenvs = clm_array_to_string(gen->rev_envs, gen->rev_channels, "rev_envs", " ");
outmap = int_array_to_string(gen->out_map, gen->out_channels, "out_map");
len = 64 + strlen(starts) + strlen(dopdly) + strlen(dopenv) + strlen(revenv) +
strlen(outdlys) + strlen(outenvs) + strlen(revenvs) + strlen(outmap);
allstr = (char *)clm_calloc(len, sizeof(char), "describe_move_sound");
mus_snprintf(allstr, len, "%s\n %s\n %s\n %s\n %s\n %s\n %s\n %s\n free: arrays: %s, gens: %s\n",
starts, dopdly, dopenv, revenv, outdlys, outenvs, revenvs, outmap,
(gen->free_arrays) ? "true" : "false",
(gen->free_gens) ? "true" : "false");
if (str1) clm_free(str1);
if (str2) clm_free(str2);
if (str3) clm_free(str3);
clm_free(starts);
clm_free(dopdly);
clm_free(dopenv);
clm_free(revenv);
clm_free(outdlys);
clm_free(outenvs);
clm_free(revenvs);
clm_free(outmap);
return(allstr);
}
static int free_move_sound(mus_any *p)
{
dloc *ptr = (dloc *)p;
if (ptr)
{
if (ptr->free_gens)
{
int i;
/* free everything except outer arrays and IO stuff */
if (ptr->doppler_delay) mus_free(ptr->doppler_delay);
if (ptr->doppler_env) mus_free(ptr->doppler_env);
if (ptr->rev_env) mus_free(ptr->rev_env);
if (ptr->out_delays)
for (i = 0; i < ptr->out_channels; i++)
if (ptr->out_delays[i]) mus_free(ptr->out_delays[i]);
if (ptr->out_envs)
for (i = 0; i < ptr->out_channels; i++)
if (ptr->out_envs[i]) mus_free(ptr->out_envs[i]);
if (ptr->rev_envs)
for (i = 0; i < ptr->rev_channels; i++)
if (ptr->rev_envs[i]) mus_free(ptr->rev_envs[i]);
}
if (ptr->free_arrays)
{
/* free outer arrays */
if (ptr->out_envs) {clm_free(ptr->out_envs); ptr->out_envs = NULL;}
if (ptr->rev_envs) {clm_free(ptr->rev_envs); ptr->rev_envs = NULL;}
if (ptr->out_delays) {clm_free(ptr->out_delays); ptr->out_delays = NULL;}
if (ptr->out_map) clm_free(ptr->out_map);
}
/* we created these in make_move_sound, so it should always be safe to free them */
if (ptr->outf) mus_free((mus_any *)(ptr->outf));
if (ptr->revf) mus_free((mus_any *)(ptr->revf));
clm_free(ptr);
}
return(0);
}
bool mus_move_sound_p(mus_any *ptr)
{
return((ptr) &&
(ptr->core->type == MUS_MOVE_SOUND));
}
mus_float_t mus_move_sound(mus_any *ptr, mus_long_t loc, mus_float_t uval)
{
dloc *gen = (dloc *)ptr;
mus_float_t val;
int chan;
if (loc > gen->end) val = 0.0; else val = uval;
/* initial silence */
if (loc < gen->start)
{
mus_delay_unmodulated(gen->doppler_delay, val);
/* original calls out_any here with 0.0 -- a no-op */
return(val);
}
/* doppler */
if (gen->doppler_delay)
val = mus_delay(gen->doppler_delay, val, mus_env(gen->doppler_env));
/* direct signal */
for (chan = 0; chan < gen->out_channels; chan++)
{
mus_float_t sample;
sample = val * mus_env(gen->out_envs[chan]);
if (gen->out_delays[chan])
sample = mus_delay_unmodulated(gen->out_delays[chan], sample);
gen->outf->vals[gen->out_map[chan]] = sample;
}
/* reverb */
if (gen->revn_writer)
{
val *= mus_env(gen->rev_env);
if (gen->rev_envs)
{
if (gen->rev_channels == 1)
gen->revf->vals[0] = val * mus_env(gen->rev_envs[0]);
else
{
for (chan = 0; chan < gen->rev_channels; chan++)
gen->revf->vals[gen->out_map[chan]] = val * mus_env(gen->rev_envs[chan]);
}
}
else gen->revf->vals[0] = val;
mus_frame_to_file(gen->revn_writer, loc, (mus_any *)(gen->revf));
}
/* file output */
if (gen->outn_writer)
mus_frame_to_file(gen->outn_writer, loc, (mus_any *)(gen->outf));
return(uval);
}
static mus_float_t run_move_sound(mus_any *ptr, mus_float_t arg1, mus_float_t arg2)
{
mus_move_sound(ptr, (mus_long_t)arg1, arg2);
return(arg2);
}
static mus_any_class MOVE_SOUND_CLASS = {
MUS_MOVE_SOUND,
(char *)S_move_sound,
&free_move_sound,
&describe_move_sound,
&move_sound_equalp,
0, 0,
&move_sound_length,
0,
0, 0, 0, 0,
0, 0,
0, 0,
&run_move_sound,
MUS_OUTPUT,
&mus_move_sound_closure,
&move_sound_channels,
0, 0, 0, 0,
0, 0,
0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0,
0, 0,
0, 0, 0,
&move_sound_reset,
&move_sound_set_closure,
0, 0
};
mus_any *mus_make_move_sound(mus_long_t start, mus_long_t end, int out_channels, int rev_channels,
mus_any *doppler_delay, mus_any *doppler_env, mus_any *rev_env,
mus_any **out_delays, mus_any **out_envs, mus_any **rev_envs,
int *out_map, mus_any *output, mus_any *revput, bool free_arrays, bool free_gens)
{
/* most of these args come to us in a list at the lisp/xen level ("dlocs" struct is actually a list)
* so the make-move-sound function in lisp/xen is (make-move-sound dloc-list output revout)
* where the trailing args mimic locsig.
*/
dloc *gen;
if (out_channels <= 0)
{
mus_error(MUS_ARG_OUT_OF_RANGE, "move-sound: out chans: %d", out_channels);
return(NULL);
}
gen = (dloc *)clm_calloc(1, sizeof(dloc), S_make_move_sound);
gen->core = &MOVE_SOUND_CLASS;
gen->start = start;
gen->end = end;
gen->out_channels = out_channels;
gen->rev_channels = rev_channels;
gen->doppler_delay = doppler_delay;
gen->doppler_env = doppler_env;
gen->rev_env = rev_env;
gen->out_delays = out_delays;
gen->out_envs = out_envs;
gen->rev_envs = rev_envs;
gen->out_map = out_map;
/* default is to free only what we make ourselves */
gen->free_gens = free_gens;
gen->free_arrays = free_arrays;
gen->outf = (mus_frame *)mus_make_empty_frame(out_channels);
if (mus_output_p(output))
gen->outn_writer = output;
if (rev_channels > 0)
{
if (mus_output_p(revput))
gen->revn_writer = revput;
gen->revf = (mus_frame *)mus_make_empty_frame(rev_channels);
}
return((mus_any *)gen);
}
/* ---------------- src ---------------- */
/* sampling rate conversion */
/* taken from sweep_srate.c of Perry Cook. To quote Perry:
*
* 'The conversion is performed by sinc interpolation.
* J. O. Smith and P. Gossett, "A Flexible Sampling-Rate Conversion Method,"
* Proc. of the IEEE Conference on Acoustics, Speech, and Signal Processing, San Diego, CA, March, 1984.
* There are essentially two cases, one where the conversion factor
* is less than one, and the sinc table is used as is yielding a sound
* which is band limited to the 1/2 the new sampling rate (we don't
* want to create bandwidth where there was none). The other case
* is where the conversion factor is greater than one and we 'warp'
* the sinc table to make the final cutoff equal to the original sampling
* rate /2. Warping the sinc table is based on the similarity theorem
* of the time and frequency domain, stretching the time domain (sinc
* table) causes shrinking in the frequency domain.'
*
* we also scale the amplitude if interpolating to take into account the broadened sinc
* this means that isolated pulses get scaled by 1/src, but that's a dumb special case
*/
typedef struct {
mus_any_class *core;
mus_float_t (*feeder)(void *arg, int direction);
mus_float_t x;
mus_float_t incr, width_1;
int width, lim;
int len;
mus_float_t *data, *sinc_table;
void *closure;
} sr;
/* I wonder if it would be more accurate and not too much slower to use
* the Chebyshev expansion of sinc here, or even the power series:
* 1 - x^2/3! + x^4/5! etc (i.e. x divides sin(x))
*/
#define SRC_SINC_DENSITY 1000
#define SRC_SINC_WIDTH 10
static mus_float_t **sinc_tables = NULL;
static int *sinc_widths = NULL;
static int sincs = 0;
void mus_clear_sinc_tables(void)
{
if (sincs)
{
int i;
for (i = 0; i < sincs; i++)
if (sinc_tables[i])
clm_free(sinc_tables[i]);
clm_free(sinc_tables);
sinc_tables = NULL;
clm_free(sinc_widths);
sinc_widths = NULL;
sincs = 0;
}
}
static mus_float_t *init_sinc_table(int width)
{
int i, size, padded_size, loc;
mus_float_t sinc_freq, win_freq, sinc_phase, win_phase;
for (i = 0; i < sincs; i++)
if (sinc_widths[i] == width)
return(sinc_tables[i]);
if (sincs == 0)
{
sinc_tables = (mus_float_t **)clm_calloc(8, sizeof(mus_float_t *), "sinc tables");
sinc_widths = (int *)clm_calloc(8, sizeof(int), "sinc tables");
sincs = 8;
loc = 0;
}
else
{
loc = -1;
for (i = 0; i < sincs; i++)
if (sinc_widths[i] == 0)
{
loc = i;
break;
}
if (loc == -1)
{
sinc_tables = (mus_float_t **)clm_realloc(sinc_tables, (sincs + 8) * sizeof(mus_float_t *));
sinc_widths = (int *)clm_realloc(sinc_widths, (sincs + 8) * sizeof(int));
for (i = sincs; i < (sincs + 8); i++)
{
sinc_widths[i] = 0;
sinc_tables[i] = NULL;
}
loc = sincs;
sincs += 8;
}
}
sinc_widths[loc] = width;
size = width * SRC_SINC_DENSITY;
padded_size = size + 4;
sinc_freq = M_PI / (mus_float_t)SRC_SINC_DENSITY;
win_freq = M_PI / (mus_float_t)size;
sinc_tables[loc] = (mus_float_t *)clm_calloc(padded_size, sizeof(mus_float_t), "sinc table");
sinc_tables[loc][0] = 1.0;
for (i = 1, sinc_phase = sinc_freq, win_phase = win_freq; i < padded_size; i++, sinc_phase += sinc_freq, win_phase += win_freq)
sinc_tables[loc][i] = sin(sinc_phase) * (0.5 + 0.5 * cos(win_phase)) / sinc_phase;
return(sinc_tables[loc]);
}
bool mus_src_p(mus_any *ptr)
{
return((ptr) &&
(ptr->core->type == MUS_SRC));
}
static int free_src_gen(mus_any *srptr)
{
sr *srp = (sr *)srptr;
if (srp)
{
if (srp->data) clm_free(srp->data);
clm_free(srp);
}
return(0);
}
static bool src_equalp(mus_any *p1, mus_any *p2) {return(p1 == p2);}
static char *describe_src(mus_any *ptr)
{
sr *gen = (sr *)ptr;
char *describe_buffer;
describe_buffer = (char *)clm_malloc(DESCRIBE_BUFFER_SIZE, "describe buffer");
mus_snprintf(describe_buffer, DESCRIBE_BUFFER_SIZE, "%s width: %d, x: %.3f, incr: %.3f, sinc table len: %d",
mus_name(ptr),
gen->width, gen->x, gen->incr, gen->len);
return(describe_buffer);
}
static mus_long_t src_length(mus_any *ptr) {return(((sr *)ptr)->width);}
static mus_float_t run_src_gen(mus_any *srptr, mus_float_t sr_change, mus_float_t unused) {return(mus_src(srptr, sr_change, NULL));}
static void *src_closure(mus_any *rd) {return(((sr *)rd)->closure);}
static void *src_set_closure(mus_any *rd, void *e) {((sr *)rd)->closure = e; return(e);}
static mus_float_t src_increment(mus_any *rd) {return(((sr *)rd)->incr);}
static mus_float_t src_set_increment(mus_any *rd, mus_float_t val) {((sr *)rd)->incr = val; return(val);}
static mus_float_t *src_sinc_table(mus_any *rd) {return(((sr *)rd)->sinc_table);}
static void src_reset(mus_any *ptr)
{
sr *gen = (sr *)ptr;
mus_clear_array(gen->data, gen->lim + 1);
gen->x = 0.0;
/* center the data if possible */
if (gen->feeder)
{
int i, dir = 1;
if (gen->incr < 0.0) dir = -1;
for (i = gen->width - 1; i < gen->lim; i++)
gen->data[i] = (*(gen->feeder))(gen->closure, dir);
}
}
static mus_any_class SRC_CLASS = {
MUS_SRC,
(char *)S_src,
&free_src_gen,
&describe_src,
&src_equalp,
&src_sinc_table, 0,
&src_length, /* sinc width actually */
0,
0, 0, 0, 0,
&fallback_scaler, 0,
&src_increment,
&src_set_increment,
&run_src_gen,
MUS_NOT_SPECIAL,
&src_closure,
0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0,
&src_reset,
&src_set_closure,
0, 0
};
mus_any *mus_make_src(mus_float_t (*input)(void *arg, int direction), mus_float_t srate, int width, void *closure)
{
if (fabs(srate) > MUS_MAX_CLM_SRC)
mus_error(MUS_ARG_OUT_OF_RANGE, S_make_src " srate arg invalid: %f", srate);
else
{
if ((width < 0) || (width > MUS_MAX_CLM_SINC_WIDTH))
mus_error(MUS_ARG_OUT_OF_RANGE, S_make_src " width arg invalid: %d", width);
else
{
sr *srp;
int wid;
srp = (sr *)clm_calloc(1, sizeof(sr), S_make_src);
if (width <= 0) width = SRC_SINC_WIDTH;
if (width < (int)(fabs(srate) * 2))
wid = (int)(ceil(fabs(srate)) * 2);
else wid = width;
srp->core = &SRC_CLASS;
srp->x = 0.0;
srp->feeder = input;
srp->closure = closure;
srp->incr = srate;
srp->width = wid;
srp->lim = 2 * wid;
srp->len = wid * SRC_SINC_DENSITY;
srp->data = (mus_float_t *)clm_calloc(srp->lim + 1, sizeof(mus_float_t), "src table");
srp->sinc_table = init_sinc_table(wid);
if (input)
{
int i, dir = 1;
if (srate < 0.0) dir = -1;
for (i = wid - 1; i < srp->lim; i++)
srp->data[i] = (*input)(closure, dir);
/* was i = 0 here but we want the incoming data centered */
}
srp->width_1 = 1.0 - wid;
return((mus_any *)srp);
}
}
return(NULL);
}
mus_float_t mus_src(mus_any *srptr, mus_float_t sr_change, mus_float_t (*input)(void *arg, int direction))
{
sr *srp = (sr *)srptr;
mus_float_t sum = 0.0, x, zf, srx, factor;
int fsx, lim, i, k, loc;
int xi, xs;
bool int_ok = false;
lim = srp->lim;
if (sr_change > MUS_MAX_CLM_SRC)
sr_change = MUS_MAX_CLM_SRC;
else
{
if (sr_change < -MUS_MAX_CLM_SRC)
sr_change = -MUS_MAX_CLM_SRC;
}
srx = srp->incr + sr_change;
if (srp->x >= 1.0)
{
mus_float_t (*sr_input)(void *arg, int direction) = input;
if (sr_input == NULL) sr_input = srp->feeder;
fsx = (int)(srp->x);
srp->x -= fsx;
/* realign data, reset srp->x */
if (fsx > lim)
{
int dir = 1;
if (srx < 0.0) dir = -1;
/* if sr_change is so extreme that the new index falls outside the data table, we need to
* read forward until we reach the new data bounds
*/
for (i = lim; i < fsx; i++)
(*sr_input)(srp->closure, dir);
fsx = lim;
}
loc = lim - fsx;
if (loc > 0)
memmove((void *)(srp->data), (void *)(srp->data + fsx), sizeof(mus_float_t) * loc);
for (i = loc; i < lim; i++)
srp->data[i] = (*sr_input)(srp->closure, (srx >= 0.0) ? 1 : -1);
}
/* if (srx == 0.0) srx = 0.01; */ /* can't decide about this ... */
if (srx < 0.0) srx = -srx;
/* tedious timing tests indicate that precalculating this block in the sr_change=0 case saves no time at all */
if (srx > 1.0)
{
factor = 1.0 / srx;
/* this is not exact since we're sampling the sinc and so on, but it's close over a wide range */
zf = factor * (mus_float_t)SRC_SINC_DENSITY;
xi = (int)zf;
int_ok = ((zf - xi) < .001);
}
else
{
factor = 1.0;
zf = (mus_float_t)SRC_SINC_DENSITY;
xi = SRC_SINC_DENSITY;
int_ok = true;
}
if (int_ok)
{
xs = (int)(zf * (srp->width_1 - srp->x));
i = 0;
if (xs < 0)
for (; (i < lim) && (xs < 0); i++, xs += xi)
sum += (srp->data[i] * srp->sinc_table[-xs]); /* fma? */
for (; i < lim; i++, xs += xi)
sum += (srp->data[i] * srp->sinc_table[xs]);
}
else
{
/* this form twice as slow because of float->int conversions */
for (i = 0, x = zf * (srp->width_1 - srp->x); i < lim; i++, x += zf)
{
/* we're moving backwards in the data array, so the sr->x field has to mimic that (hence the '1.0 - srp->x') */
if (x < 0) k = (int)(-x); else k = (int)x;
sum += (srp->data[i] * srp->sinc_table[k]);
/* rather than do a bounds check here, we just padded the sinc_table above with 2 extra 0's */
}
}
srp->x += srx;
return(sum * factor);
}
/* it was a cold, rainy day... */
mus_float_t mus_src_20(mus_any *srptr, mus_float_t (*input)(void *arg, int direction))
{
sr *srp = (sr *)srptr;
mus_float_t sum;
int lim, i, loc;
int xi, xs;
lim = srp->lim;
if (srp->x > 0.0)
{
/* realign data, reset srp->x */
mus_float_t (*sr_input)(void *arg, int direction) = input;
if (sr_input == NULL) sr_input = srp->feeder;
loc = lim - 2;
memmove((void *)(srp->data), (void *)(srp->data + 2), sizeof(mus_float_t) * loc);
for (i = loc; i < lim; i++)
srp->data[i] = (*sr_input)(srp->closure, 1);
}
else srp->x = 2.0;
xi = (int)(SRC_SINC_DENSITY / 2);
xs = xi * (1 - srp->width);
xi *= 2;
sum = srp->data[srp->width - 1];
for (i = 0; (i < lim) && (xs < 0); i += 2, xs += xi)
sum += (srp->data[i] * srp->sinc_table[-xs]);
for (; i < lim; i += 2, xs += xi)
sum += (srp->data[i] * srp->sinc_table[xs]);
return(sum * 0.5);
}
mus_float_t mus_src_05(mus_any *srptr, mus_float_t (*input)(void *arg, int direction))
{
sr *srp = (sr *)srptr;
mus_float_t sum;
int lim, i, loc;
int xs;
lim = srp->lim;
if (srp->x >= 1.0)
{
mus_float_t (*sr_input)(void *arg, int direction) = input;
if (sr_input == NULL) sr_input = srp->feeder;
loc = lim - 1;
memmove((void *)(srp->data), (void *)(srp->data + 1), sizeof(mus_float_t) * loc);
for (i = loc; i < lim; i++)
srp->data[i] = (*sr_input)(srp->closure, 1);
srp->x = 0.0;
}
if (srp->x == 0.0)
{
srp->x = 0.5;
return(srp->data[srp->width - 1]);
}
xs = (int)(SRC_SINC_DENSITY * (srp->width_1 - 0.5));
for (i = 0, sum = 0.0; (i < lim) && (xs < 0); i++, xs += SRC_SINC_DENSITY)
sum += (srp->data[i] * srp->sinc_table[-xs]);
for (; i < lim; i++, xs += SRC_SINC_DENSITY)
sum += (srp->data[i] * srp->sinc_table[xs]);
srp->x += 0.5;
return(sum);
}
/* ---------------- granulate ---------------- */
typedef struct {
mus_any_class *core;
mus_float_t (*rd)(void *arg, int direction);
int s20;
int s50;
int rmp;
mus_float_t amp;
int cur_out;
int input_hop;
int ctr;
int output_hop;
mus_float_t *out_data; /* output buffer */
int out_data_len;
mus_float_t *in_data; /* input buffer */
int in_data_len;
void *closure;
int (*edit)(void *closure);
mus_float_t *grain; /* grain data */
int grain_len;
bool first_samp;
unsigned long randx; /* gen-local random number seed */
} grn_info;
bool mus_granulate_p(mus_any *ptr)
{
return((ptr) &&
(ptr->core->type == MUS_GRANULATE));
}
static bool granulate_equalp(mus_any *p1, mus_any *p2) {return(p1 == p2);}
static char *describe_granulate(mus_any *ptr)
{
grn_info *gen = (grn_info *)ptr;
char *describe_buffer;
describe_buffer = (char *)clm_malloc(DESCRIBE_BUFFER_SIZE, "describe buffer");
mus_snprintf(describe_buffer, DESCRIBE_BUFFER_SIZE, "%s expansion: %.3f (%d/%d), scaler: %.3f, length: %.3f secs (%d samps), ramp: %.3f",
mus_name(ptr),
(mus_float_t)(gen->output_hop) / (mus_float_t)(gen->input_hop),
gen->input_hop, gen->output_hop,
gen->amp,
(mus_float_t)(gen->grain_len) / (mus_float_t)sampling_rate, gen->grain_len,
(mus_float_t)(gen->rmp) / (mus_float_t)sampling_rate);
return(describe_buffer);
}
static int free_granulate(mus_any *ptr)
{
grn_info *gen = (grn_info *)ptr;
if (gen)
{
if (gen->out_data) clm_free(gen->out_data);
if (gen->in_data) clm_free(gen->in_data);
if (gen->grain) clm_free(gen->grain);
clm_free(gen);
}
return(0);
}
static mus_long_t grn_length(mus_any *ptr) {return(((grn_info *)ptr)->grain_len);}
static mus_long_t grn_set_length(mus_any *ptr, mus_long_t val)
{
grn_info *gen = ((grn_info *)ptr);
if ((val > 0) && (val < gen->out_data_len))
gen->grain_len = (int)val; /* larger -> segfault */
return(gen->grain_len);
}
static mus_float_t grn_scaler(mus_any *ptr) {return(((grn_info *)ptr)->amp);}
static mus_float_t grn_set_scaler(mus_any *ptr, mus_float_t val) {((grn_info *)ptr)->amp = val; return(val);}
static mus_float_t grn_frequency(mus_any *ptr) {return(((mus_float_t)((grn_info *)ptr)->output_hop) / (mus_float_t)sampling_rate);}
static mus_float_t grn_set_frequency(mus_any *ptr, mus_float_t val) {((grn_info *)ptr)->output_hop = (int)((mus_float_t)sampling_rate * val); return(val);}
static void *grn_closure(mus_any *rd) {return(((grn_info *)rd)->closure);}
static void *grn_set_closure(mus_any *rd, void *e) {((grn_info *)rd)->closure = e; return(e);}
static mus_float_t grn_increment(mus_any *ptr)
{
grn_info *gen = ((grn_info *)ptr);
return(((mus_float_t)(gen->output_hop)) / ((mus_float_t)(gen->input_hop)));
}
static mus_float_t grn_set_increment(mus_any *ptr, mus_float_t val)
{
grn_info *gen = ((grn_info *)ptr);
if (val != 0.0)
gen->input_hop = (int)(gen->output_hop / val);
return(val);
}
static mus_long_t grn_hop(mus_any *ptr) {return(((grn_info *)ptr)->output_hop);}
static mus_long_t grn_set_hop(mus_any *ptr, mus_long_t val) {((grn_info *)ptr)->output_hop = (int)val; return(val);}
static mus_long_t grn_ramp(mus_any *ptr) {return(((grn_info *)ptr)->rmp);}
static mus_long_t grn_set_ramp(mus_any *ptr, mus_long_t val)
{
grn_info *gen = (grn_info *)ptr;
if (val < (gen->grain_len * .5))
gen->rmp = (int)val;
return(val);
}
static mus_float_t *granulate_data(mus_any *ptr) {return(((grn_info *)ptr)->grain);}
int mus_granulate_grain_max_length(mus_any *ptr) {return(((grn_info *)ptr)->in_data_len);}
static mus_long_t grn_location(mus_any *ptr) {return((mus_long_t)(((grn_info *)ptr)->randx));}
static mus_long_t grn_set_location(mus_any *ptr, mus_long_t val) {((grn_info *)ptr)->randx = (unsigned long)val; return(val);}
static mus_float_t run_granulate(mus_any *ptr, mus_float_t unused1, mus_float_t unused2) {return(mus_granulate(ptr, NULL));}
static void grn_reset(mus_any *ptr)
{
grn_info *gen = (grn_info *)ptr;
gen->cur_out = 0;
gen->ctr = 0;
mus_clear_array(gen->out_data, gen->out_data_len);
mus_clear_array(gen->in_data, gen->in_data_len);
mus_clear_array(gen->grain, gen->in_data_len);
gen->first_samp = true;
}
static int grn_irandom(grn_info *spd, int amp)
{
/* gen-local next_random */
spd->randx = spd->randx * 1103515245 + 12345;
return((int)(amp * INVERSE_MAX_RAND2 * ((mus_float_t)((unsigned int)(spd->randx >> 16) & 32767))));
}
static mus_any_class GRANULATE_CLASS = {
MUS_GRANULATE,
(char *)S_granulate,
&free_granulate,
&describe_granulate,
&granulate_equalp,
&granulate_data, 0,
&grn_length, /* segment-length */
&grn_set_length,
&grn_frequency, /* spd-out */
&grn_set_frequency,
0, 0,
&grn_scaler, /* segment-scaler */
&grn_set_scaler,
&grn_increment,
&grn_set_increment,
&run_granulate,
MUS_NOT_SPECIAL,
&grn_closure,
0,
0, 0, 0, 0, 0, 0,
&grn_hop, &grn_set_hop,
&grn_ramp, &grn_set_ramp,
0, 0, 0, 0,
&grn_location, &grn_set_location, /* local randx */
0, 0, 0, 0, 0, 0,
&grn_reset,
&grn_set_closure,
0, 0
};
mus_any *mus_make_granulate(mus_float_t (*input)(void *arg, int direction),
mus_float_t expansion, mus_float_t length, mus_float_t scaler,
mus_float_t hop, mus_float_t ramp, mus_float_t jitter, int max_size,
int (*edit)(void *closure),
void *closure)
{
grn_info *spd;
int outlen;
outlen = (int)(sampling_rate * (hop + length));
if (max_size > outlen) outlen = max_size;
if (expansion <= 0.0)
{
mus_error(MUS_ARG_OUT_OF_RANGE, S_make_granulate " expansion must be > 0.0: %f", expansion);
return(NULL);
}
if (outlen <= 0)
{
mus_error(MUS_NO_LENGTH, S_make_granulate " size is %d (hop: %f, segment-length: %f)?", outlen, hop, length);
return(NULL);
}
if ((hop * sampling_rate) < expansion)
{
mus_error(MUS_ARG_OUT_OF_RANGE, S_make_granulate " expansion (%f) must be < hop * srate (%f)", expansion, hop * sampling_rate);
return(NULL);
}
spd = (grn_info *)clm_calloc(1, sizeof(grn_info), S_make_granulate);
spd->core = &GRANULATE_CLASS;
spd->cur_out = 0;
spd->ctr = 0;
spd->grain_len = (int)(ceil(length * sampling_rate));
spd->rmp = (int)(ramp * spd->grain_len);
spd->amp = scaler;
spd->output_hop = (int)(hop * sampling_rate);
spd->input_hop = (int)((mus_float_t)(spd->output_hop) / expansion);
spd->s20 = 2 * (int)(jitter * sampling_rate * hop); /* was *.05 here and *.02 below */
/* added "2 *" 21-Mar-05 and replaced irandom with (grn)mus_irandom below */
spd->s50 = (int)(jitter * sampling_rate * hop * 0.4);
spd->out_data_len = outlen;
spd->out_data = (mus_float_t *)clm_calloc(spd->out_data_len, sizeof(mus_float_t), "granulate out data");
spd->in_data_len = outlen + spd->s20 + 1;
spd->in_data = (mus_float_t *)clm_calloc(spd->in_data_len, sizeof(mus_float_t), "granulate in data");
spd->rd = input;
spd->closure = closure;
spd->edit = edit;
spd->grain = (mus_float_t *)clm_calloc(spd->in_data_len, sizeof(mus_float_t), "granulate grain");
spd->first_samp = true;
spd->randx = mus_rand_seed(); /* caller can override this via the mus_location method */
next_random();
return((mus_any *)spd);
}
void mus_granulate_set_edit_function(mus_any *ptr, int (*edit)(void *closure))
{
grn_info *gen = (grn_info *)ptr;
if (!(gen->grain))
gen->grain = (mus_float_t *)clm_calloc(gen->in_data_len, sizeof(mus_float_t), "granulate grain");
gen->edit = edit;
}
mus_float_t mus_granulate_with_editor(mus_any *ptr, mus_float_t (*input)(void *arg, int direction), int (*edit)(void *closure))
{
/* in_data_len is the max grain size (:maxsize arg), not the current grain size
* out_data_len is the size of the output buffer
* grain_len is the current grain size
* cur_out is the out_data buffer location where we need to add in the next grain
* ctr is where we are now in out_data
*/
grn_info *spd = (grn_info *)ptr;
mus_float_t result = 0.0;
if (spd->ctr < spd->out_data_len)
result = spd->out_data[spd->ctr]; /* else return 0.0 */
spd->ctr++;
if (spd->ctr >= spd->cur_out) /* time for next grain */
{
int i;
/* set up edit/input functions and possible outside-accessible grain array */
mus_float_t (*spd_input)(void *arg, int direction) = input;
int (*spd_edit)(void *closure) = edit;
if (spd_input == NULL) spd_input = spd->rd;
if (spd_edit == NULL) spd_edit = spd->edit;
if (spd->first_samp)
{
/* fill up in_data, out_data is already cleared */
for (i = 0; i < spd->in_data_len; i++)
spd->in_data[i] = (*spd_input)(spd->closure, 1);
}
else
{
/* align output buffer to flush the data we've already output, and zero out new trailing portion */
if (spd->cur_out >= spd->out_data_len)
{
/* entire buffer has been output, and in fact we've been sending 0's for awhile to fill out hop */
mus_clear_array(spd->out_data, spd->out_data_len); /* so zero the entire thing (it's all old) */
}
else
{
/* move yet-un-output data to 0, zero trailers */
int good_samps;
good_samps = (spd->out_data_len - spd->cur_out);
memmove((void *)(spd->out_data), (void *)(spd->out_data + spd->cur_out), good_samps * sizeof(mus_float_t));
memset((void *)(spd->out_data + good_samps), 0, spd->cur_out * sizeof(mus_float_t)); /* must be cur_out trailing samples to 0 */
}
/* align input buffer */
if (spd->input_hop > spd->in_data_len)
{
/* need to flush enough samples to accommodate the fact that the hop is bigger than our data buffer */
for (i = spd->in_data_len; i < spd->input_hop; i++) (*spd_input)(spd->closure, 1);
/* then get a full input buffer */
for (i = 0; i < spd->in_data_len; i++)
spd->in_data[i] = (*spd_input)(spd->closure, 1);
}
else
{
/* align input buffer with current input hop location */
int good_samps;
good_samps = (spd->in_data_len - spd->input_hop);
memmove((void *)(spd->in_data), (void *)(spd->in_data + spd->input_hop), good_samps * sizeof(mus_float_t));
for (i = good_samps; i < spd->in_data_len; i++)
spd->in_data[i] = (*spd_input)(spd->closure, 1);
}
}
/* create current grain */
{
int lim, steady_end, curstart, j;
lim = spd->grain_len;
curstart = grn_irandom(spd, spd->s20); /* start location in input buffer */
if ((curstart + spd->grain_len) > spd->in_data_len)
lim = (spd->in_data_len - curstart);
if (lim > spd->grain_len)
lim = spd->grain_len;
mus_clear_array(spd->grain, spd->grain_len);
if (spd->rmp > 0)
{
mus_float_t amp = 0.0, incr;
steady_end = (spd->grain_len - spd->rmp);
incr = (mus_float_t)(spd->amp) / (mus_float_t)(spd->rmp);
for (i = 0, j = curstart; i < lim; i++, j++)
{
spd->grain[i] = (amp * spd->in_data[j]);
if (i < spd->rmp)
amp += incr;
else
if (i >= steady_end) /* was >, but that truncates the envelope */
amp -= incr;
}
}
else
{
/* ramp is 0.0, so just scale the input buffer by the current amp */
if (spd->amp == 1.0)
memcpy((void *)(spd->grain), (void *)(spd->in_data + curstart), lim * sizeof(mus_float_t));
else
{
for (i = 0, j = curstart; i < lim; i++, j++)
spd->grain[i] = (spd->amp * spd->in_data[j]);
}
}
}
/* add new grain into output buffer */
{
int new_len;
if (spd_edit)
{
new_len = (*spd_edit)(spd->closure);
if (new_len <= 0)
new_len = spd->grain_len;
else
{
if (new_len > spd->out_data_len)
new_len = spd->out_data_len;
}
}
else new_len = spd->grain_len;
if (new_len > spd->out_data_len) /* can be off-by-one here if hop is just barely greater then 0.0 (user is screwing around...) */
new_len = spd->out_data_len;
for (i = 0; i < new_len; i++)
spd->out_data[i] += spd->grain[i];
}
/* set location of next grain calculation */
spd->ctr = 0;
spd->cur_out = spd->output_hop + grn_irandom(spd, 2 * spd->s50) - (spd->s50 >> 1);
/* this form suggested by Marc Lehmann */
/* "2 *" added 21-Mar-05 and irandom replaced with mus_irandom, grn_irandom 28-Feb-06 */
/* use of gen-local random sequence suggested by Kjetil Matheussen (to keep multi-channel grns in sync) */
if (spd->cur_out < 0) spd->cur_out = 0;
if (spd->first_samp)
{
spd->first_samp = false;
spd->ctr = 1;
return(spd->out_data[0]);
}
}
return(result);
}
mus_float_t mus_granulate(mus_any *ptr, mus_float_t (*input)(void *arg, int direction))
{
return(mus_granulate_with_editor(ptr, input, NULL));
}
/* ---------------- Fourier transform ---------------- */
/* fft of mus_float_t data in zero-based arrays
*/
static void mus_big_fft(mus_float_t *rl, mus_float_t *im, mus_long_t n, int is);
#if HAVE_FFTW3 && HAVE_COMPLEX_TRIG && (!__cplusplus)
static fftw_complex *c_in_data = NULL, *c_out_data = NULL;
static fftw_plan c_r_plan, c_i_plan;
static int last_c_fft_size = 0;
static void mus_fftw_with_imag(mus_float_t *rl, mus_float_t *im, int n, int dir)
{
int i;
if (n != last_c_fft_size)
{
if (c_in_data)
{
fftw_free(c_in_data);
fftw_free(c_out_data);
fftw_destroy_plan(c_r_plan);
fftw_destroy_plan(c_i_plan);
}
c_in_data = (fftw_complex *)fftw_malloc(n * sizeof(fftw_complex));
c_out_data = (fftw_complex *)fftw_malloc(n * sizeof(fftw_complex));
c_r_plan = fftw_plan_dft_1d(n, c_in_data, c_out_data, FFTW_FORWARD, FFTW_ESTIMATE);
c_i_plan = fftw_plan_dft_1d(n, c_in_data, c_out_data, FFTW_BACKWARD, FFTW_ESTIMATE);
last_c_fft_size = n;
}
for (i = 0; i < n; i++)
c_in_data[i] = rl[i] + _Complex_I * im[i];
if (dir == -1)
fftw_execute(c_r_plan);
else fftw_execute(c_i_plan);
for (i = 0; i < n; i++)
{
rl[i] = creal(c_out_data[i]);
im[i] = cimag(c_out_data[i]);
}
}
void mus_fft(mus_float_t *rl, mus_float_t *im, mus_long_t n, int is)
{
/* simple timing tests indicate fftw is slightly less than 4 times faster than mus_fft in this context */
if (n < (1 << 30))
mus_fftw_with_imag(rl, im, n, is);
else mus_big_fft(rl, im, n, is);
}
#else
static void mus_scramble(mus_float_t *rl, mus_float_t *im, int n)
{
/* bit reversal */
int i, m, j;
mus_float_t vr, vi;
j = 0;
for (i = 0; i < n; i++)
{
if (j > i)
{
vr = rl[j];
vi = im[j];
rl[j] = rl[i];
im[j] = im[i];
rl[i] = vr;
im[i] = vi;
}
m = n >> 1;
while ((m >= 2) && (j >= m))
{
j -= m;
m = m >> 1;
}
j += m;
}
}
void mus_fft(mus_float_t *rl, mus_float_t *im, mus_long_t n, int is)
{
/* standard fft: real part in rl, imaginary in im,
* rl and im are zero-based.
* see fxt/simplfft/fft.c (Joerg Arndt)
*/
int m, j, mh, ldm, lg, i, i2, j2, imh;
double ur, ui, u, vr, vi, angle, c, s;
if (n >= (1 << 30))
{
mus_big_fft(rl, im, n, is);
return;
}
imh = (int)(log(n + 1) / log(2.0));
mus_scramble(rl, im, n);
m = 2;
ldm = 1;
mh = n >> 1;
angle = (M_PI * is);
for (lg = 0; lg < imh; lg++)
{
c = cos(angle);
s = sin(angle);
ur = 1.0;
ui = 0.0;
for (i2 = 0; i2 < ldm; i2++)
{
i = i2;
j = i2 + ldm;
for (j2 = 0; j2 < mh; j2++)
{
vr = ur * rl[j] - ui * im[j];
vi = ur * im[j] + ui * rl[j];
rl[j] = rl[i] - vr;
im[j] = im[i] - vi;
rl[i] += vr;
im[i] += vi;
i += m;
j += m;
}
u = ur;
ur = (ur * c) - (ui * s);
ui = (ui * c) + (u * s);
}
mh >>= 1;
ldm = m;
angle *= 0.5;
m <<= 1;
}
}
#endif
static void mus_big_fft(mus_float_t *rl, mus_float_t *im, mus_long_t n, int is)
{
mus_long_t m, j, mh, ldm, i, i2, j2;
int imh, lg;
double ur, ui, u, vr, vi, angle, c, s;
imh = (int)(log(n + 1) / log(2.0));
j = 0;
for (i = 0; i < n; i++)
{
if (j > i)
{
vr = rl[j];
vi = im[j];
rl[j] = rl[i];
im[j] = im[i];
rl[i] = vr;
im[i] = vi;
}
m = n >> 1;
while ((m >= 2) && (j >= m))
{
j -= m;
m = m >> 1;
}
j += m;
}
m = 2;
ldm = 1;
mh = n >> 1;
angle = (M_PI * is);
for (lg = 0; lg < imh; lg++)
{
c = cos(angle);
s = sin(angle);
ur = 1.0;
ui = 0.0;
for (i2 = 0; i2 < ldm; i2++)
{
i = i2;
j = i2 + ldm;
for (j2 = 0; j2 < mh; j2++)
{
vr = ur * rl[j] - ui * im[j];
vi = ur * im[j] + ui * rl[j];
rl[j] = rl[i] - vr;
im[j] = im[i] - vi;
rl[i] += vr;
im[i] += vi;
i += m;
j += m;
}
u = ur;
ur = (ur * c) - (ui * s);
ui = (ui * c) + (u * s);
}
mh >>= 1;
ldm = m;
angle *= 0.5;
m <<= 1;
}
}
#if HAVE_GSL
#include <gsl/gsl_sf_bessel.h>
double mus_bessi0(mus_float_t x)
{
gsl_sf_result res;
gsl_sf_bessel_I0_e(x, &res);
return(res.val);
}
#else
double mus_bessi0(mus_float_t x)
{
if (x == 0.0) return(1.0);
if (fabs(x) <= 15.0)
{
mus_float_t z, denominator, numerator;
z = x * x;
numerator = (z * (z * (z * (z * (z * (z * (z * (z * (z * (z * (z * (z * (z * (z *
0.210580722890567e-22 + 0.380715242345326e-19) +
0.479440257548300e-16) + 0.435125971262668e-13) +
0.300931127112960e-10) + 0.160224679395361e-7) +
0.654858370096785e-5) + 0.202591084143397e-2) +
0.463076284721000e0) + 0.754337328948189e2) +
0.830792541809429e4) + 0.571661130563785e6) +
0.216415572361227e8) + 0.356644482244025e9) +
0.144048298227235e10);
denominator = (z * (z * (z - 0.307646912682801e4) +
0.347626332405882e7) - 0.144048298227235e10);
return(-numerator / denominator);
}
return(1.0);
}
#endif
#if HAVE_COMPLEX_TRIG || HAVE_GSL
static mus_float_t ultraspherical(int n, mus_float_t x, mus_float_t lambda)
{
/* this is also the algorithm used in gsl gegenbauer.c -- slow but not as bad as using the binomials! */
mus_float_t fn1, fn2 = 1.0, fn = 1.0;
int k;
if (n == 0) return(1.0);
if (lambda == 0.0)
fn1 = 2.0 * x;
else fn1 = 2.0 * x * lambda;
if (n == 1) return(fn1);
for (k = 2; k <= n; k++)
{
fn = ((2.0 * x * (k + lambda - 1.0) * fn1) - ((k + (2.0 * lambda) - 2.0) * fn2)) / (mus_float_t)k;
fn2 = fn1;
fn1 = fn;
}
return(fn);
}
#endif
bool mus_fft_window_p(int val)
{
switch (val)
{
case MUS_RECTANGULAR_WINDOW: case MUS_HANN_WINDOW: case MUS_WELCH_WINDOW: case MUS_PARZEN_WINDOW:
case MUS_BARTLETT_WINDOW: case MUS_HAMMING_WINDOW: case MUS_BLACKMAN2_WINDOW: case MUS_BLACKMAN3_WINDOW:
case MUS_BLACKMAN4_WINDOW: case MUS_EXPONENTIAL_WINDOW: case MUS_RIEMANN_WINDOW: case MUS_KAISER_WINDOW:
case MUS_CAUCHY_WINDOW: case MUS_POISSON_WINDOW: case MUS_GAUSSIAN_WINDOW: case MUS_TUKEY_WINDOW:
case MUS_DOLPH_CHEBYSHEV_WINDOW: case MUS_HANN_POISSON_WINDOW: case MUS_CONNES_WINDOW:
case MUS_SAMARAKI_WINDOW: case MUS_ULTRASPHERICAL_WINDOW: case MUS_BARTLETT_HANN_WINDOW:
case MUS_BOHMAN_WINDOW: case MUS_FLAT_TOP_WINDOW: case MUS_BLACKMAN5_WINDOW: case MUS_BLACKMAN6_WINDOW:
case MUS_BLACKMAN7_WINDOW: case MUS_BLACKMAN8_WINDOW: case MUS_BLACKMAN9_WINDOW: case MUS_BLACKMAN10_WINDOW:
case MUS_RV2_WINDOW: case MUS_RV3_WINDOW: case MUS_RV4_WINDOW: case MUS_MLT_SINE_WINDOW:
case MUS_PAPOULIS_WINDOW: case MUS_DPSS_WINDOW: case MUS_SINC_WINDOW:
return(true);
break;
}
return(false);
}
#if HAVE_GSL_EIGEN_NONSYMMV_WORKSPACE
#include <gsl/gsl_math.h>
#include <gsl/gsl_eigen.h>
#endif
static mus_float_t sqr(mus_float_t x) {return(x * x);}
mus_float_t *mus_make_fft_window_with_window(mus_fft_window_t type, mus_long_t size, mus_float_t beta, mus_float_t mu, mus_float_t *window)
{
/* mostly taken from
* Fredric J. Harris, "On the Use of Windows for Harmonic Analysis with the
* Discrete Fourier Transform," Proceedings of the IEEE, Vol. 66, No. 1,
* January 1978.
*
* Albert H. Nuttall, "Some Windows with Very Good Sidelobe Behaviour",
* IEEE Transactions of Acoustics, Speech, and Signal Processing, Vol. ASSP-29,
* No. 1, February 1981, pp 84-91
*/
mus_long_t i, j, midn, midp1;
double freq, rate, angle = 0.0, cx;
if (window == NULL) return(NULL);
midn = size >> 1;
midp1 = (size + 1) / 2;
freq = TWO_PI / (double)size;
rate = 1.0 / (double)midn;
switch (type)
{
case MUS_RECTANGULAR_WINDOW:
for (i = 0; i < size; i++)
window[i] = 1.0;
break;
case MUS_WELCH_WINDOW:
for (i = 0, j = size - 1; i <= midn; i++, j--)
{
window[i] = 1.0 - sqr((mus_float_t)(i - midn) / (mus_float_t)midp1);
window[j] = window[i];
}
break;
case MUS_CONNES_WINDOW:
for (i = 0, j = size - 1; i <= midn; i++, j--)
{
window[i] = sqr(1.0 - sqr((mus_float_t)(i - midn) / (mus_float_t)midp1));
window[j] = window[i];
}
break;
case MUS_PARZEN_WINDOW:
for (i = 0, j = size - 1; i <= midn; i++, j--)
{
window[i] = 1.0 - fabs((mus_float_t)(i - midn) / (mus_float_t)midp1);
window[j] = window[i];
}
break;
case MUS_BARTLETT_WINDOW:
for (i = 0, j = size - 1, angle = 0.0; i <= midn; i++, j--, angle += rate)
{
window[i] = angle;
window[j] = angle;
}
break;
case MUS_BARTLETT_HANN_WINDOW:
{
double ramp;
rate *= 0.5;
/* this definition taken from mathworks docs: they use size - 1 throughout -- this makes very little
* difference unless you're using a small window. I decided to be consistent with all the other
* windows, and besides, this way actually peaks at 1.0 (which matlab misses)
*/
for (i = 0, j = size - 1, angle = -M_PI, ramp = 0.5; i <= midn; i++, j--, angle += freq, ramp -= rate)
{
window[i] = 0.62 - 0.48 * ramp + 0.38 * cos(angle);
window[j] = window[i];
}
}
break;
case MUS_BOHMAN_WINDOW:
{
double ramp;
/* definition from diracdelta docs and "DSP Handbook" -- used in bispectrum ("minimum bispectrum bias supremum") */
for (i = 0, j = size - 1, angle = M_PI, ramp = 0.0; i <= midn; i++, j--, angle -= freq, ramp += rate)
{
window[i] = ramp * cos(angle) + (sin(angle) / M_PI);
window[j] = window[i];
}
}
break;
case MUS_HANN_WINDOW:
for (i = 0, j = size - 1, angle = 0.0; i <= midn; i++, j--, angle += freq)
{
window[i] = 0.5 - 0.5 * cos(angle);
window[j] = window[i];
}
break;
/* Rife-Vincent windows are an elaboration of this (Hann = RV1) */
case MUS_RV2_WINDOW:
for (i = 0, j = size - 1, angle = 0.0; i <= midn; i++, j--, angle += freq)
{
window[i] = .375 - 0.5 * cos(angle) + .125 * cos(2 * angle);
window[j] = window[i];
}
break;
case MUS_RV3_WINDOW:
for (i = 0, j = size - 1, angle = 0.0; i <= midn; i++, j--, angle += freq)
{
window[i] = (10.0 / 32.0) -
(15.0 / 32.0) * cos(angle) +
(6.0 / 32.0) * cos(2 * angle) -
(1.0 / 32.0) * cos(3 * angle);
window[j] = window[i];
}
break;
case MUS_RV4_WINDOW:
for (i = 0, j = size - 1, angle = 0.0; i <= midn; i++, j--, angle += freq)
{
window[i] = (35.0 / 128.0) -
(56.0 / 128.0) * cos(angle) +
(28.0 / 128.0) * cos(2 * angle) -
(8.0 / 128.0) * cos(3 * angle) +
(1.0 / 128.0) * cos(4 * angle);
window[j] = window[i];
}
break;
case MUS_HAMMING_WINDOW:
for (i = 0, j = size - 1, angle = 0.0; i <= midn; i++, j--, angle += freq)
{
window[i] = 0.54 - 0.46 * cos(angle);
window[j] = window[i];
}
break;
/* Blackman 1 is the same as Hamming */
case MUS_BLACKMAN2_WINDOW: /* using Chebyshev polynomial equivalents here (this is also given as .42 .5 .08) */
for (i = 0, j = size - 1, angle = 0.0; i <= midn; i++, j--, angle += freq)
{ /* (+ 0.42323 (* -0.49755 (cos a)) (* 0.07922 (cos (* a 2)))) */
/* "A Family...": .42438 .49341 .078279 */
cx = cos(angle);
window[i] = .34401 + (cx * (-.49755 + (cx * .15844)));
window[j] = window[i];
}
break;
case MUS_BLACKMAN3_WINDOW:
for (i = 0, j = size - 1, angle = 0.0; i <= midn; i++, j--, angle += freq)
{ /* (+ 0.35875 (* -0.48829 (cos a)) (* 0.14128 (cos (* a 2))) (* -0.01168 (cos (* a 3)))) */
/* (+ 0.36336 (* 0.48918 (cos a)) (* 0.13660 (cos (* a 2))) (* 0.01064 (cos (* a 3)))) is "Nuttall" window? */
/* "A Family...": .36358 .489177 .136599 .0106411 */
cx = cos(angle);
window[i] = .21747 + (cx * (-.45325 + (cx * (.28256 - (cx * .04672)))));
window[j] = window[i];
}
break;
case MUS_BLACKMAN4_WINDOW:
for (i = 0, j = size - 1, angle = 0.0; i <= midn; i++, j--, angle += freq)
{ /* (+ 0.287333 (* -0.44716 (cos a)) (* 0.20844 (cos (* a 2))) (* -0.05190 (cos (* a 3))) (* 0.005149 (cos (* a 4)))) */
/* "A Family...": .32321 .471492 .175534 .0284969 .001261357 */
cx = cos(angle);
window[i] = .084037 + (cx * (-.29145 + (cx * (.375696 + (cx * (-.20762 + (cx * .041194)))))));
window[j] = window[i];
}
break;
/* "A Family of Cosine-Sum Windows..." Albrecht */
case MUS_BLACKMAN5_WINDOW:
for (i = 0, j = size - 1, angle = 0.0; i <= midn; i++, j--, angle += freq)
{
/* .293557 -.451935 .201416 -.047926 .00502619 -.000137555 */
/* partials->polynomial -> -0.196389809 -0.308844775 0.3626224697 -0.188952908 0.0402095206 -0.002200880, then fixup constant */
cx = cos(angle);
window[i] = 0.097167 +
(cx * (-.3088448 +
(cx * (.3626224 +
(cx * (-.1889530 +
(cx * (.04020952 +
(cx * -.0022008)))))))));
window[j] = window[i];
}
break;
case MUS_BLACKMAN6_WINDOW:
for (i = 0, j = size - 1, angle = 0.0; i <= midn; i++, j--, angle += freq)
{
/* .2712203 -.4334446 .2180041 -.0657853 .010761867 -.0007700127 .00001368088 */
/* partials->polynomial -> -0.207255900 -0.239938736 0.3501594961
* -0.247740954 0.0854382589 -0.012320203 0.0004377882
*/
cx = cos(angle);
window[i] = 0.063964353 +
(cx * (-0.239938736 +
(cx * (0.3501594961 +
(cx * (-0.247740954 +
(cx * (0.0854382589 +
(cx * (-0.012320203 +
(cx * 0.0004377882)))))))))));
window[j] = window[i];
}
break;
case MUS_BLACKMAN7_WINDOW:
for (i = 0, j = size - 1, angle = 0.0; i <= midn; i++, j--, angle += freq)
{
/* .2533176 -.4163269 .2288396 -.08157508 .017735924 -.0020967027 .00010677413 -.0000012807 */
/* partials->polynomial -> -0.211210445 -0.182076216 0.3177137375 -0.284437984
* 0.1367622316 -0.033403806 0.0034167722 -0.000081965
*/
cx = cos(angle);
window[i] = 0.04210723 +
(cx * (-0.18207621 +
(cx * (0.3177137375 +
(cx * (-0.284437984 +
(cx * (0.1367622316 +
(cx * (-0.033403806 +
(cx * (0.0034167722 +
(cx * -0.000081965)))))))))))));
window[j] = window[i];
}
break;
case MUS_BLACKMAN8_WINDOW:
for (i = 0, j = size - 1, angle = 0.0; i <= midn; i++, j--, angle += freq)
{
/* .2384331 -.4005545 .2358242 -.09527918 .025373955 -.0041524329 .00036856041 -.00001384355 .0000001161808 */
/* partials->polynomial -> -0.210818693 -0.135382235 0.2752871215 -0.298843294 0.1853193194
* -0.064888448 0.0117641902 -0.000885987 0.0000148711
*/
cx = cos(angle);
window[i] = 0.027614462 +
(cx * (-0.135382235 +
(cx * (0.2752871215 +
(cx * (-0.298843294 +
(cx * (0.1853193194 +
(cx * (-0.064888448 +
(cx * (0.0117641902 +
(cx * (-0.000885987 +
(cx * 0.0000148711)))))))))))))));
window[j] = window[i];
}
break;
case MUS_BLACKMAN9_WINDOW:
for (i = 0, j = size - 1, angle = 0.0; i <= midn; i++, j--, angle += freq)
{
/* .2257345 -.3860122 .2401294 -.1070542 .03325916 -.00687337 .0008751673 -.0000600859 .000001710716 -.00000001027272 */
/* partials->polynomial -> -0.207743675 -0.098795950 0.2298837751 -0.294112951 0.2243389785
* -0.103248745 0.0275674108 -0.003839580 0.0002189716 -0.000002630
*/
cx = cos(angle);
window[i] = 0.01799071953 +
(cx * (-0.098795950 +
(cx * (0.2298837751 +
(cx * (-0.294112951 +
(cx * (0.2243389785 +
(cx * (-0.103248745 +
(cx * (0.0275674108 +
(cx * (-0.003839580 +
(cx * (0.0002189716 +
(cx * -0.000002630)))))))))))))))));
window[j] = window[i];
}
break;
case MUS_BLACKMAN10_WINDOW:
for (i = 0, j = size - 1, angle = 0.0; i <= midn; i++, j--, angle += freq)
{
/* .2151527 -.3731348 .2424243 -.1166907 .04077422 -.01000904 .0016398069 -.0001651660 .000008884663 -.000000193817 .00000000084824 */
/* partials->polynomial -> -0.203281015 -0.071953468 0.1878870875 -0.275808066
* 0.2489042133 -0.141729787 0.0502002984 -0.010458985 0.0011361511 -0.000049617 0.0000004343
*/
cx = cos(angle);
window[i] = 0.0118717384 +
(cx * (-0.071953468 +
(cx * (0.1878870875 +
(cx * (-0.275808066 +
(cx * (0.2489042133 +
(cx * (-0.141729787 +
(cx * (0.0502002984 +
(cx * (-0.010458985 +
(cx * (0.0011361511 +
(cx * (-0.000049617 +
(cx * 0.0000004343)))))))))))))))))));
window[j] = window[i];
}
break;
case MUS_FLAT_TOP_WINDOW:
/* this definition taken from mathworks docs -- see above */
for (i = 0, j = size - 1, angle = 0.0; i <= midn; i++, j--, angle += freq)
{
window[i] = 0.2156 - 0.4160 * cos(angle) + 0.2781 * cos(2 * angle) - 0.0836 * cos(3 * angle) + 0.0069 * cos(4 * angle);
window[j] = window[i];
}
break;
case MUS_EXPONENTIAL_WINDOW:
{
double expn, expsum = 1.0;
expn = log(2) / (double)midn + 1.0;
for (i = 0, j = size - 1; i <= midn; i++, j--)
{
window[i] = expsum - 1.0;
window[j] = window[i];
expsum *= expn;
}
}
break;
case MUS_KAISER_WINDOW:
{
double I0beta;
I0beta = mus_bessi0(beta); /* Harris multiplies beta by pi */
for (i = 0, j = size - 1, angle = 1.0; i <= midn; i++, j--, angle -= rate)
{
window[i] = mus_bessi0(beta * sqrt(1.0 - sqr(angle))) / I0beta;
window[j] = window[i];
}
}
break;
case MUS_CAUCHY_WINDOW:
for (i = 0, j = size - 1, angle = 1.0; i <= midn; i++, j--, angle -= rate)
{
window[i] = 1.0 / (1.0 + sqr(beta * angle));
window[j] = window[i];
}
break;
case MUS_POISSON_WINDOW:
for (i = 0, j = size - 1, angle = 1.0; i <= midn; i++, j--, angle -= rate)
{
window[i] = exp((-beta) * angle);
window[j] = window[i];
}
break;
case MUS_HANN_POISSON_WINDOW:
/* Hann * Poisson -- from JOS */
{
double angle1;
for (i = 0, j = size - 1, angle = 1.0, angle1 = 0.0; i <= midn; i++, j--, angle -= rate, angle1 += freq)
{
window[i] = exp((-beta) * angle) * (0.5 - 0.5 * cos(angle1));
window[j] = window[i];
}
}
break;
case MUS_RIEMANN_WINDOW:
{
double sr1;
sr1 = TWO_PI / (double)size;
for (i = 0, j = size - 1; i <= midn; i++, j--)
{
if (i == midn)
window[i] = 1.0;
else
{
cx = sr1 * (midn - i);
window[i] = sin(cx) / cx;
}
window[j] = window[i];
}
}
break;
case MUS_GAUSSIAN_WINDOW:
for (i = 0, j = size - 1, angle = 1.0; i <= midn; i++, j--, angle -= rate)
{
window[i] = exp(-.5 * sqr(beta * angle));
window[j] = window[i];
}
break;
case MUS_TUKEY_WINDOW:
cx = midn * (1.0 - beta);
for (i = 0, j = size - 1; i <= midn; i++, j--)
{
if (i >= cx)
window[i] = 1.0;
else window[i] = .5 * (1.0 - cos(M_PI * i / cx));
window[j] = window[i];
}
break;
case MUS_MLT_SINE_WINDOW:
{
double scl;
scl = M_PI / (double)size;
for (i = 0, j = size - 1; i <= midn; i++, j--)
{
window[i] = sin((i + 0.5) * scl);
window[j] = window[i];
}
}
break;
case MUS_PAPOULIS_WINDOW:
{
int n2;
n2 = size / 2;
for (i = -n2; i < n2; i++)
{
double ratio, pratio;
ratio = (double)i / (double)n2;
pratio = M_PI * ratio;
window[i + n2] = (fabs(sin(pratio)) / M_PI) + (cos(pratio) * (1.0 - fabs(ratio)));
}
}
break;
case MUS_SINC_WINDOW:
{
double scl;
scl = 2 * M_PI / (size - 1);
for (i = -midn, j = 0; i < midn; i++, j++)
{
if (i == 0)
window[j] = 1.0;
else window[j] = sin(i * scl) / (i * scl);
}
}
break;
case MUS_DPSS_WINDOW:
#if HAVE_GSL_EIGEN_NONSYMMV_WORKSPACE
{
/* from Verma, Bilbao, Meng, "The Digital Prolate Spheroidal Window"
* output checked using Julius Smith's dpssw.m, although my "beta" is different
*/
double *data;
double cw, n1, pk = 0.0;
cw = cos(2 * M_PI * beta);
n1 = (size - 1) * 0.5;
if ((mus_long_t)(size * size * sizeof(double)) > mus_max_malloc())
{
mus_error(MUS_ARG_OUT_OF_RANGE, "dpss window requires size^2 * 8 bytes, but that exceeds the current mus-max-malloc amount");
return(window);
}
data = (double *)calloc(size * size, sizeof(double));
for (i = 0; i < size; i++)
{
double n2;
n2 = n1 - i;
data[i * size + i] = cw * n2 * n2;
if (i < (size - 1))
data[i * (size + 1) + 1] = 0.5 * (i + 1) * (size - 1 - i);
if (i > 0)
data[i * (size + 1) - 1] = 0.5 * i * (size - i);
}
{
gsl_vector_complex_view evec_i;
gsl_matrix_view m = gsl_matrix_view_array(data, size, size);
gsl_vector_complex *eval = gsl_vector_complex_alloc(size);
gsl_matrix_complex *evec = gsl_matrix_complex_alloc(size, size);
gsl_eigen_nonsymmv_workspace *w = gsl_eigen_nonsymmv_alloc(size);
gsl_eigen_nonsymmv(&m.matrix, eval, evec, w);
gsl_eigen_nonsymmv_free(w);
gsl_eigen_nonsymmv_sort(eval, evec, GSL_EIGEN_SORT_ABS_DESC);
evec_i = gsl_matrix_complex_column(evec, 0);
for (j = 0; j < size; j++)
window[j] = GSL_REAL(gsl_vector_complex_get(&evec_i.vector, j));
gsl_vector_complex_free(eval);
gsl_matrix_complex_free(evec);
}
for (i = 0; i < size; i++)
if (fabs(window[i]) > fabs(pk))
pk = window[i];
if (pk != 0.0)
for (i = 0; i < size; i++)
window[i] /= pk;
free(data);
}
#else
mus_error(MUS_NO_SUCH_FFT_WINDOW, "DPSS window needs GSL");
#endif
break;
case MUS_ULTRASPHERICAL_WINDOW:
case MUS_SAMARAKI_WINDOW:
case MUS_DOLPH_CHEBYSHEV_WINDOW:
/* "Design of Ultraspherical Window Functions with Prescribed Spectral Characteristics", Bergen and Antoniou, EURASIP JASP 2004 */
if (type == MUS_ULTRASPHERICAL_WINDOW)
{
if (mu == 0.0)
type = MUS_DOLPH_CHEBYSHEV_WINDOW;
else
{
if (mu == 1.0)
type = MUS_SAMARAKI_WINDOW;
}
}
#if HAVE_COMPLEX_TRIG
{
mus_float_t *rl, *im;
mus_float_t pk = 0.0;
double alpha;
freq = M_PI / (mus_float_t)size;
if (beta < 0.2) beta = 0.2;
alpha = creal(ccosh(cacosh(pow(10.0, beta)) / (mus_float_t)size));
rl = (mus_float_t *)clm_calloc(size, sizeof(mus_float_t), "ifft window buffer");
im = (mus_float_t *)clm_calloc(size, sizeof(mus_float_t), "ifft window buffer");
for (i = 0, angle = 0.0; i < size; i++, angle += freq)
{
switch (type)
{
case MUS_DOLPH_CHEBYSHEV_WINDOW:
rl[i] = creal(ccos(cacos(alpha * cos(angle)) * size)); /* here is Tn (Chebyshev polynomial 1st kind) */
break;
case MUS_SAMARAKI_WINDOW:
/* Samaraki window uses Un instead */
rl[i] = creal(csin(cacos(alpha * cos(angle)) * (size + 1.0)) / csin(cacos(alpha * cos(angle))));
break;
case MUS_ULTRASPHERICAL_WINDOW:
/* Cn here */
rl[i] = ultraspherical(size, alpha * cos(angle), mu);
break;
default:
break;
}
}
mus_fft(rl, im, size, -1); /* can be 1 here */
pk = 0.0;
for (i = 0; i < size; i++)
if (pk < rl[i])
pk = rl[i];
if ((pk != 0.0) && (pk != 1.0))
{
for (i = 0, j = size / 2; i < size; i++)
{
window[i] = rl[j++] / pk;
if (j == size) j = 0;
}
}
else
{
memcpy((void *)window, (void *)rl, size * sizeof(mus_float_t));
}
clm_free(rl);
clm_free(im);
}
#else
#if HAVE_GSL
{
mus_float_t *rl, *im;
mus_float_t pk;
double alpha;
freq = M_PI / (mus_float_t)size;
if (beta < 0.2) beta = 0.2;
alpha = GSL_REAL(gsl_complex_cosh(
gsl_complex_mul_real(
gsl_complex_arccosh_real(pow(10.0, beta)),
(double)(1.0 / (mus_float_t)size))));
rl = (mus_float_t *)clm_calloc(size, sizeof(mus_float_t), "ifft window buffer");
im = (mus_float_t *)clm_calloc(size, sizeof(mus_float_t), "ifft window buffer");
for (i = 0, angle = 0.0; i < size; i++, angle += freq)
{
switch (type)
{
case MUS_DOLPH_CHEBYSHEV_WINDOW:
rl[i] = GSL_REAL(gsl_complex_cos(
gsl_complex_mul_real(
gsl_complex_arccos_real(alpha * cos(angle)),
(double)size)));
break;
case MUS_SAMARAKI_WINDOW:
rl[i] = GSL_REAL(gsl_complex_div(
gsl_complex_sin(
gsl_complex_mul_real(
gsl_complex_arccos_real(alpha * cos(angle)),
(double)(size + 1.0))),
gsl_complex_sin(
gsl_complex_arccos_real(alpha * cos(angle)))));
break;
case MUS_ULTRASPHERICAL_WINDOW:
rl[i] = ultraspherical(size, alpha * cos(angle), mu);
break;
default:
break;
}
}
mus_fft(rl, im, size, -1); /* can be 1 here */
pk = 0.0;
for (i = 0; i < size; i++)
if (pk < rl[i])
pk = rl[i];
if ((pk != 0.0) && (pk != 1.0))
{
for (i = 0, j = size / 2; i < size; i++)
{
window[i] = rl[j++] / pk;
if (j == size) j = 0;
}
}
else
{
memcpy((void *)window, (void *)rl, size * sizeof(mus_float_t));
}
clm_free(rl);
clm_free(im);
}
#else
mus_error(MUS_NO_SUCH_FFT_WINDOW, "Dolph-Chebyshev, Samaraki, and Ultraspherical windows need complex trig support");
#endif
#endif
break;
default:
mus_error(MUS_NO_SUCH_FFT_WINDOW, "unknown fft data window: %d", (int)type);
break;
}
return(window);
}
mus_float_t *mus_make_fft_window(mus_fft_window_t type, mus_long_t size, mus_float_t beta)
{
return(mus_make_fft_window_with_window(type, size, beta, 0.0, (mus_float_t *)clm_calloc(size, sizeof(mus_float_t), S_make_fft_window)));
}
static const char *fft_window_names[MUS_NUM_FFT_WINDOWS] =
{"Rectangular", "Hann", "Welch", "Parzen", "Bartlett", "Hamming", "Blackman2", "Blackman3", "Blackman4",
"Exponential", "Riemann", "Kaiser", "Cauchy", "Poisson", "Gaussian", "Tukey", "Dolph-Chebyshev", "Hann-Poisson", "Connes",
"Samaraki", "Ultraspherical", "Bartlett-Hann", "Bohman", "Flat-top",
"Blackman5", "Blackman6", "Blackman7", "Blackman8", "Blackman9", "Blackman10",
"Rife-Vincent2", "Rife-Vincent3", "Rife-Vincent4", "MLT Sine", "Papoulis", "DPSS (Slepian)", "Sinc"
};
const char *mus_fft_window_name(mus_fft_window_t win)
{
if (mus_fft_window_p((int)win))
return(fft_window_names[(int)win]);
return("unknown");
}
const char **mus_fft_window_names(void)
{
return(fft_window_names);
}
mus_float_t *mus_spectrum(mus_float_t *rdat, mus_float_t *idat, mus_float_t *window, mus_long_t n, mus_spectrum_t type)
{
mus_long_t i;
mus_float_t maxa, lowest;
double val, todb;
if (window) mus_multiply_arrays(rdat, window, n);
mus_clear_array(idat, n);
mus_fft(rdat, idat, n, 1);
lowest = 0.000001;
maxa = 0.0;
n = n * 0.5;
for (i = 0; i < n; i++)
{
#if (__linux__ && __PPC__)
if (rdat[i] < lowest) rdat[i] = 0.0;
if (idat[i] < lowest) idat[i] = 0.0;
#endif
val = rdat[i] * rdat[i] + idat[i] * idat[i];
if (val < lowest)
rdat[i] = 0.001;
else
{
rdat[i] = sqrt(val);
if (rdat[i] > maxa) maxa = rdat[i];
}
}
if (maxa > 0.0)
{
maxa = 1.0 / maxa;
if (type == MUS_SPECTRUM_IN_DB)
{
todb = 20.0 / log(10.0);
for (i = 0; i < n; i++)
rdat[i] = todb * log(rdat[i] * maxa);
}
else
{
if (type == MUS_SPECTRUM_NORMALIZED)
for (i = 0; i < n; i++)
rdat[i] *= maxa;
}
}
return(rdat);
}
mus_float_t *mus_autocorrelate(mus_float_t *data, mus_long_t n)
{
mus_float_t *im;
mus_float_t fscl;
mus_long_t i, n2;
n2 = n / 2;
fscl = 1.0 / (mus_float_t)n;
im = (mus_float_t *)clm_calloc(n, sizeof(mus_float_t), "mus_autocorrelate imaginary data");
mus_fft(data, im, n, 1);
for (i = 0; i < n; i++)
data[i] = data[i] * data[i] + im[i] * im[i];
memset((void *)im, 0, n * sizeof(mus_float_t));
mus_fft(data, im, n, -1);
for (i = 0; i <= n2; i++)
data[i] *= fscl;
for (i = n2 + 1; i < n; i++)
data[i] = 0.0;
clm_free(im);
return(data);
}
mus_float_t *mus_correlate(mus_float_t *data1, mus_float_t *data2, mus_long_t n)
{
mus_float_t *im1, *im2;
mus_long_t i;
mus_float_t fscl;
im1 = (mus_float_t *)clm_calloc(n, sizeof(mus_float_t), "mus_correlate imaginary data");
im2 = (mus_float_t *)clm_calloc(n, sizeof(mus_float_t), "mus_correlate imaginary data");
mus_fft(data1, im1, n, 1);
mus_fft(data2, im2, n, 1);
for (i = 0; i < n; i++)
{
mus_float_t tmp1, tmp2, tmp3, tmp4;
tmp1 = data1[i] * data2[i];
tmp2 = im1[i] * im2[i];
tmp3 = data1[i] * im2[i];
tmp4 = data2[i] * im1[i];
data1[i] = tmp1 + tmp2;
im1[i] = tmp3 - tmp4;
}
mus_fft(data1, im1, n, -1);
fscl = 1.0 / (mus_float_t)n;
for (i = 0; i < n; i++)
data1[i] *= fscl;
clm_free(im1);
clm_free(im2);
return(data1);
}
mus_float_t *mus_cepstrum(mus_float_t *data, mus_long_t n)
{
mus_float_t *rl, *im;
mus_float_t fscl = 0.0, lowest;
mus_long_t i;
lowest = 0.00000001;
fscl = 2.0 / (mus_float_t)n;
rl = (mus_float_t *)clm_malloc(n * sizeof(mus_float_t), "mus_cepstrum real data");
im = (mus_float_t *)clm_calloc(n, sizeof(mus_float_t), "mus_cepstrum imaginary data");
memcpy((void *)rl, (void *)data, n * sizeof(mus_float_t));
mus_fft(rl, im, n, 1);
for (i = 0; i < n; i++)
{
rl[i] = rl[i] * rl[i] + im[i] * im[i];
if (rl[i] < lowest)
rl[i] = -10.0;
else rl[i] = log(sqrt(rl[i]));
}
memset((void *)im, 0, n * sizeof(mus_float_t));
mus_fft(rl, im, n, -1);
for (i = 0; i < n; i++)
if (fabs(rl[i]) > fscl)
fscl = fabs(rl[i]);
if (fscl > 0.0)
for (i = 0; i < n; i++)
data[i] = rl[i] / fscl;
free(rl);
free(im);
return(data);
}
/* ---------------- convolve ---------------- */
mus_float_t *mus_convolution(mus_float_t *rl1, mus_float_t *rl2, mus_long_t n)
{
/* convolves two real arrays. */
/* rl1 and rl2 are assumed to be set up correctly for the convolution */
/* (that is, rl1 (the "signal") is zero-padded by length of */
/* (non-zero part of) rl2 and rl2 is stored in wrap-around order) */
/* We treat rl2 as the imaginary part of the first fft, then do */
/* the split, scaling, and (complex) spectral multiply in one step. */
/* result in rl1 */
mus_long_t j, n2;
mus_float_t invn;
mus_fft(rl1, rl2, n, 1);
n2 = n >> 1;
invn = 0.25 / (mus_float_t)n;
rl1[0] = ((rl1[0] * rl2[0]) / (mus_float_t)n);
rl2[0] = 0.0;
for (j = 1; j <= n2; j++)
{
mus_long_t nn2;
mus_float_t rem, rep, aim, aip;
nn2 = n - j;
rep = (rl1[j] + rl1[nn2]);
rem = (rl1[j] - rl1[nn2]);
aip = (rl2[j] + rl2[nn2]);
aim = (rl2[j] - rl2[nn2]);
rl1[j] = invn * (rep * aip + aim * rem);
rl1[nn2] = rl1[j];
rl2[j] = invn * (aim * aip - rep * rem);
rl2[nn2] = -rl2[j];
}
mus_fft(rl1, rl2, n, -1);
return(rl1);
}
typedef struct {
mus_any_class *core;
mus_float_t (*feeder)(void *arg, int direction);
mus_long_t fftsize, fftsize2, ctr, filtersize;
mus_float_t *rl1, *rl2, *buf, *filter;
void *closure;
} conv;
static bool convolve_equalp(mus_any *p1, mus_any *p2) {return(p1 == p2);}
static char *describe_convolve(mus_any *ptr)
{
conv *gen = (conv *)ptr;
char *describe_buffer;
describe_buffer = (char *)clm_malloc(DESCRIBE_BUFFER_SIZE, "describe buffer");
mus_snprintf(describe_buffer, DESCRIBE_BUFFER_SIZE, "%s size: " MUS_LD,
mus_name(ptr),
gen->fftsize);
return(describe_buffer);
}
static int free_convolve(mus_any *ptr)
{
conv *gen = (conv *)ptr;
if (gen)
{
if (gen->rl1) clm_free(gen->rl1);
if (gen->rl2) clm_free(gen->rl2);
if (gen->buf) clm_free(gen->buf);
clm_free(gen);
}
return(0);
}
static mus_long_t conv_length(mus_any *ptr) {return(((conv *)ptr)->fftsize);}
static mus_float_t run_convolve(mus_any *ptr, mus_float_t unused1, mus_float_t unused2) {return(mus_convolve(ptr, NULL));}
static void *conv_closure(mus_any *rd) {return(((conv *)rd)->closure);}
static void *conv_set_closure(mus_any *rd, void *e) {((conv *)rd)->closure = e; return(e);}
static void convolve_reset(mus_any *ptr)
{
conv *gen = (conv *)ptr;
gen->ctr = gen->fftsize2;
mus_clear_array(gen->rl1, gen->fftsize);
mus_clear_array(gen->rl2, gen->fftsize);
mus_clear_array(gen->buf, gen->fftsize);
}
static mus_any_class CONVOLVE_CLASS = {
MUS_CONVOLVE,
(char *)S_convolve,
&free_convolve,
&describe_convolve,
&convolve_equalp,
0, 0,
&conv_length,
0,
0, 0, 0, 0,
0, 0,
0, 0,
&run_convolve,
MUS_NOT_SPECIAL,
&conv_closure,
0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0,
&convolve_reset,
&conv_set_closure,
0, 0
};
mus_float_t mus_convolve(mus_any *ptr, mus_float_t (*input)(void *arg, int direction))
{
conv *gen = (conv *)ptr;
mus_float_t result;
if (gen->ctr >= gen->fftsize2)
{
mus_long_t i, j;
mus_float_t (*conv_input)(void *arg, int direction) = input;
if (conv_input == NULL) conv_input = gen->feeder;
for (i = 0, j = gen->fftsize2; i < gen->fftsize2; i++, j++)
{
gen->buf[i] = gen->buf[j];
gen->buf[j] = 0.0;
gen->rl1[i] = (*conv_input)(gen->closure, 1);
gen->rl1[j] = 0.0;
gen->rl2[i] = 0.0;
gen->rl2[j] = 0.0;
}
memcpy((void *)(gen->rl2), (void *)(gen->filter), gen->filtersize * sizeof(mus_float_t));
mus_convolution(gen->rl1, gen->rl2, gen->fftsize);
for (i = 0, j = gen->fftsize2; i < gen->fftsize2; i++, j++)
{
gen->buf[i] += gen->rl1[i];
gen->buf[j] = gen->rl1[j];
}
gen->ctr = 0;
}
result = gen->buf[gen->ctr];
gen->ctr++;
return(result);
}
bool mus_convolve_p(mus_any *ptr)
{
return((ptr) &&
(ptr->core->type == MUS_CONVOLVE));
}
mus_any *mus_make_convolve(mus_float_t (*input)(void *arg, int direction), mus_float_t *filter, mus_long_t fftsize, mus_long_t filtersize, void *closure)
{
conv *gen = NULL;
gen = (conv *)clm_calloc(1, sizeof(conv), S_make_convolve);
gen->core = &CONVOLVE_CLASS;
gen->feeder = input;
gen->closure = closure;
gen->filter = filter;
if (filter)
{
mus_long_t i;
bool all_zero = true;
for (i = 0; i < filtersize; i++)
if (fabs(filter[i]) != 0.0) /* I'm getting -0.000 != 0.000 */
{
all_zero = false;
break;
}
if (all_zero)
mus_print("make_convolve: filter contains only 0.0.");
}
gen->filtersize = filtersize;
gen->fftsize = fftsize;
gen->fftsize2 = gen->fftsize / 2;
gen->ctr = gen->fftsize2;
gen->rl1 = (mus_float_t *)clm_calloc(fftsize, sizeof(mus_float_t), "convolve fft data");
gen->rl2 = (mus_float_t *)clm_calloc(fftsize, sizeof(mus_float_t), "convolve fft data");
gen->buf = (mus_float_t *)clm_calloc(fftsize, sizeof(mus_float_t), "convolve fft data");
return((mus_any *)gen);
}
void mus_convolve_files(const char *file1, const char *file2, mus_float_t maxamp, const char *output_file)
{
mus_long_t file1_len, file2_len, outlen, totallen;
int file1_chans, file2_chans, output_chans;
mus_float_t *data1, *data2;
const char *errmsg = NULL;
mus_float_t maxval = 0.0;
mus_long_t i, fftlen;
file1_len = mus_sound_frames(file1);
file2_len = mus_sound_frames(file2);
if ((file1_len <= 0) || (file2_len <= 0)) return;
file1_chans = mus_sound_chans(file1);
if (file1_chans <= 0) mus_error(MUS_NO_CHANNELS, "%s chans: %d", file1, file1_chans);
file2_chans = mus_sound_chans(file2);
if (file2_chans <= 0) mus_error(MUS_NO_CHANNELS, "%s chans: %d", file2, file2_chans);
output_chans = file1_chans;
if (file2_chans > output_chans) output_chans = file2_chans;
fftlen = (mus_long_t)(pow(2.0, (int)ceil(log(file1_len + file2_len + 1) / log(2.0))));
outlen = file1_len + file2_len + 1;
totallen = outlen * output_chans;
data1 = (mus_float_t *)clm_calloc(fftlen, sizeof(mus_float_t), "convolve_files data");
data2 = (mus_float_t *)clm_calloc(fftlen, sizeof(mus_float_t), "convolve_files data");
if (output_chans == 1)
{
mus_sample_t *samps;
samps = (mus_sample_t *)clm_calloc(fftlen, sizeof(mus_sample_t), "convolve_files data");
mus_file_to_array(file1, 0, 0, file1_len, samps);
for (i = 0; i < file1_len; i++) data1[i] = MUS_SAMPLE_TO_DOUBLE(samps[i]);
mus_file_to_array(file2, 0, 0, file2_len, samps);
for (i = 0; i < file2_len; i++) data2[i] = MUS_SAMPLE_TO_DOUBLE(samps[i]);
mus_convolution(data1, data2, fftlen);
for (i = 0; i < outlen; i++)
if (maxval < fabs(data1[i]))
maxval = fabs(data1[i]);
if (maxval > 0.0)
{
maxval = maxamp / maxval;
for (i = 0; i < outlen; i++) data1[i] *= maxval;
}
for (i = 0; i < outlen; i++) samps[i] = MUS_DOUBLE_TO_SAMPLE(data1[i]);
errmsg = mus_array_to_file_with_error(output_file, samps, outlen, mus_sound_srate(file1), 1);
clm_free(samps);
}
else
{
mus_sample_t *samps;
mus_float_t *outdat = NULL;
int c1 = 0, c2 = 0, chan;
samps = (mus_sample_t *)clm_calloc(totallen, sizeof(mus_sample_t), "convolve_files data");
outdat = (mus_float_t *)clm_calloc(totallen, sizeof(mus_float_t), "convolve_files data");
for (chan = 0; chan < output_chans; chan++)
{
mus_long_t j, k;
mus_file_to_array(file1, c1, 0, file1_len, samps);
for (k = 0; k < file1_len; k++) data1[k] = MUS_SAMPLE_TO_DOUBLE(samps[k]);
mus_file_to_array(file2, c2, 0, file2_len, samps);
for (k = 0; k < file2_len; k++) data2[k] = MUS_SAMPLE_TO_DOUBLE(samps[k]);
mus_convolution(data1, data2, fftlen);
for (j = chan, k = 0; j < totallen; j += output_chans, k++) outdat[j] = data1[k];
c1++;
if (c1 >= file1_chans) c1 = 0;
c2++;
if (c2 >= file2_chans) c2 = 0;
mus_clear_array(data1, fftlen);
mus_clear_array(data2, fftlen);
}
for (i = 0; i < totallen; i++)
if (maxval < fabs(outdat[i]))
maxval = fabs(outdat[i]);
if (maxval > 0.0)
{
maxval = maxamp / maxval;
for (i = 0; i < totallen; i++) outdat[i] *= maxval;
}
for (i = 0; i < totallen; i++)
samps[i] = MUS_DOUBLE_TO_SAMPLE(outdat[i]);
errmsg = mus_array_to_file_with_error(output_file, samps, totallen, mus_sound_srate(file1), output_chans);
clm_free(samps);
clm_free(outdat);
}
clm_free(data1);
clm_free(data2);
if (errmsg)
mus_error(MUS_CANT_OPEN_FILE, "%s", errmsg);
}
/* ---------------- phase-vocoder ---------------- */
typedef struct {
mus_any_class *core;
mus_float_t pitch;
mus_float_t (*input)(void *arg, int direction);
void *closure;
bool (*analyze)(void *arg, mus_float_t (*input)(void *arg1, int direction));
int (*edit)(void *arg);
mus_float_t (*synthesize)(void *arg);
int outctr, interp, filptr, N, D;
mus_float_t *win, *ampinc, *amps, *freqs, *phases, *phaseinc, *lastphase, *in_data;
} pv_info;
bool mus_phase_vocoder_p(mus_any *ptr)
{
return((ptr) &&
(ptr->core->type == MUS_PHASE_VOCODER));
}
static bool phase_vocoder_equalp(mus_any *p1, mus_any *p2) {return(p1 == p2);}
static char *describe_phase_vocoder(mus_any *ptr)
{
char *arr = NULL;
pv_info *gen = (pv_info *)ptr;
char *describe_buffer;
describe_buffer = (char *)clm_malloc(DESCRIBE_BUFFER_SIZE, "describe buffer");
mus_snprintf(describe_buffer, DESCRIBE_BUFFER_SIZE, "%s outctr: %d, interp: %d, filptr: %d, N: %d, D: %d, in_data: %s",
mus_name(ptr),
gen->outctr, gen->interp, gen->filptr, gen->N, gen->D,
arr = float_array_to_string(gen->in_data, gen->N, 0));
if (arr) clm_free(arr);
return(describe_buffer);
}
static int free_phase_vocoder(mus_any *ptr)
{
pv_info *gen = (pv_info *)ptr;
if (gen)
{
if (gen->in_data) clm_free(gen->in_data);
if (gen->amps) clm_free(gen->amps);
if (gen->freqs) clm_free(gen->freqs);
if (gen->phases) clm_free(gen->phases);
if (gen->win) clm_free(gen->win);
if (gen->phaseinc) clm_free(gen->phaseinc);
if (gen->lastphase) clm_free(gen->lastphase);
if (gen->ampinc) clm_free(gen->ampinc);
clm_free(gen);
}
return(0);
}
static mus_long_t pv_length(mus_any *ptr) {return(((pv_info *)ptr)->N);}
static mus_long_t pv_hop(mus_any *ptr) {return(((pv_info *)ptr)->D);}
static mus_long_t pv_set_hop(mus_any *ptr, mus_long_t val) {((pv_info *)ptr)->D = (int)val; return(val);}
static mus_float_t pv_frequency(mus_any *ptr) {return(((pv_info *)ptr)->pitch);}
static mus_float_t pv_set_frequency(mus_any *ptr, mus_float_t val) {((pv_info *)ptr)->pitch = val; return(val);}
static void *pv_closure(mus_any *rd) {return(((pv_info *)rd)->closure);}
static void *pv_set_closure(mus_any *rd, void *e) {((pv_info *)rd)->closure = e; return(e);}
mus_float_t *mus_phase_vocoder_amp_increments(mus_any *ptr) {return(((pv_info *)ptr)->ampinc);}
mus_float_t *mus_phase_vocoder_amps(mus_any *ptr) {return(((pv_info *)ptr)->amps);}
mus_float_t *mus_phase_vocoder_freqs(mus_any *ptr) {return(((pv_info *)ptr)->freqs);}
mus_float_t *mus_phase_vocoder_phases(mus_any *ptr) {return(((pv_info *)ptr)->phases);}
mus_float_t *mus_phase_vocoder_phase_increments(mus_any *ptr) {return(((pv_info *)ptr)->phaseinc);}
static mus_long_t pv_outctr(mus_any *ptr) {return((mus_long_t)(((pv_info *)ptr)->outctr));} /* mus_location wrapper */
static mus_long_t pv_set_outctr(mus_any *ptr, mus_long_t val) {((pv_info *)ptr)->outctr = (int)val; return(val);}
static mus_float_t run_phase_vocoder(mus_any *ptr, mus_float_t unused1, mus_float_t unused2) {return(mus_phase_vocoder(ptr, NULL));}
static mus_float_t pv_increment(mus_any *rd) {return((mus_float_t)(((pv_info *)rd)->interp));}
static mus_float_t pv_set_increment(mus_any *rd, mus_float_t val) {((pv_info *)rd)->interp = (int)val; return(val);}
static void pv_reset(mus_any *ptr)
{
pv_info *gen = (pv_info *)ptr;
if (gen->in_data) clm_free(gen->in_data);
gen->in_data = NULL;
gen->outctr = gen->interp;
gen->filptr = 0;
mus_clear_array(gen->ampinc, gen->N);
mus_clear_array(gen->freqs, gen->N);
mus_clear_array(gen->amps, gen->N / 2);
mus_clear_array(gen->phases, gen->N / 2);
mus_clear_array(gen->lastphase, gen->N / 2);
mus_clear_array(gen->phaseinc, gen->N / 2);
}
static mus_any_class PHASE_VOCODER_CLASS = {
MUS_PHASE_VOCODER,
(char *)S_phase_vocoder,
&free_phase_vocoder,
&describe_phase_vocoder,
&phase_vocoder_equalp,
0, 0,
&pv_length, 0,
&pv_frequency,
&pv_set_frequency,
0, 0,
0, 0,
&pv_increment,
&pv_set_increment,
&run_phase_vocoder,
MUS_NOT_SPECIAL,
&pv_closure,
0,
0, 0, 0, 0, 0, 0,
&pv_hop, &pv_set_hop,
0, 0,
0, 0, 0, 0,
&pv_outctr, &pv_set_outctr,
0, 0, 0, 0, 0, 0,
&pv_reset,
&pv_set_closure,
0, 0
};
mus_any *mus_make_phase_vocoder(mus_float_t (*input)(void *arg, int direction),
int fftsize, int overlap, int interp,
mus_float_t pitch,
bool (*analyze)(void *arg, mus_float_t (*input)(void *arg1, int direction)),
int (*edit)(void *arg),
mus_float_t (*synthesize)(void *arg),
void *closure)
{
/* order of args is trying to match src, granulate etc
* the inclusion of pitch and interp provides built-in time/pitch scaling which is 99% of phase-vocoder use
*/
pv_info *pv;
int N2, D, i;
mus_float_t scl;
N2 = (int)(fftsize / 2);
if (N2 == 0) return(NULL);
D = fftsize / overlap;
if (D == 0) return(NULL);
pv = (pv_info *)clm_calloc(1, sizeof(pv_info), S_make_phase_vocoder);
pv->core = &PHASE_VOCODER_CLASS;
pv->N = fftsize;
pv->D = D;
pv->interp = interp;
pv->outctr = interp;
pv->filptr = 0;
pv->pitch = pitch;
pv->ampinc = (mus_float_t *)clm_calloc(fftsize, sizeof(mus_float_t), "pvoc ampinc");
pv->freqs = (mus_float_t *)clm_calloc(fftsize, sizeof(mus_float_t), "pvoc freqs");
pv->amps = (mus_float_t *)clm_calloc(N2, sizeof(mus_float_t), "pvoc amps");
pv->phases = (mus_float_t *)clm_calloc(N2, sizeof(mus_float_t), "pvoc phases");
pv->lastphase = (mus_float_t *)clm_calloc(N2, sizeof(mus_float_t), "pvoc lastphase");
pv->phaseinc = (mus_float_t *)clm_calloc(N2, sizeof(mus_float_t), "pvoc phaseinc");
pv->in_data = NULL;
pv->input = input;
pv->closure = closure;
pv->analyze = analyze;
pv->edit = edit;
pv->synthesize = synthesize;
pv->win = mus_make_fft_window(MUS_HAMMING_WINDOW, fftsize, 0.0);
scl = 2.0 / (0.54 * (mus_float_t)fftsize);
if (pv->win) /* clm2xen traps errors for later reporting (to clean up local allocation),
* so calloc might return NULL in all the cases here
*/
for (i = 0; i < fftsize; i++)
pv->win[i] *= scl;
return((mus_any *)pv);
}
mus_float_t mus_phase_vocoder_with_editors(mus_any *ptr,
mus_float_t (*input)(void *arg, int direction),
bool (*analyze)(void *arg, mus_float_t (*input)(void *arg1, int direction)),
int (*edit)(void *arg),
mus_float_t (*synthesize)(void *arg))
{
pv_info *pv = (pv_info *)ptr;
int N2, i;
mus_float_t (*pv_synthesize)(void *arg) = synthesize;
mus_float_t sum = 0.0;
if (pv_synthesize == NULL) pv_synthesize = pv->synthesize;
N2 = pv->N / 2;
if (pv->outctr >= pv->interp)
{
mus_float_t scl;
mus_float_t (*pv_input)(void *arg, int direction) = input;
bool (*pv_analyze)(void *arg, mus_float_t (*input)(void *arg1, int direction)) = analyze;
int (*pv_edit)(void *arg) = edit;
if (pv_input == NULL)
{
pv_input = pv->input;
if (pv_input == NULL)
mus_error(MUS_NO_SAMPLE_INPUT, "%s has no input function!", mus_describe(ptr));
}
if (pv_analyze == NULL) pv_analyze = pv->analyze;
if (pv_edit == NULL) pv_edit = pv->edit;
pv->outctr = 0;
if ((pv_analyze == NULL) ||
((*pv_analyze)(pv->closure, pv_input)))
{
int j, buf;
mus_clear_array(pv->freqs, pv->N);
if (pv->in_data == NULL)
{
pv->in_data = (mus_float_t *)clm_calloc(pv->N, sizeof(mus_float_t), "pvoc indata");
for (i = 0; i < pv->N; i++) pv->in_data[i] = (*pv_input)(pv->closure, 1);
}
else
{
for (i = 0, j = pv->D; j < pv->N; i++, j++) pv->in_data[i] = pv->in_data[j];
for (i = pv->N - pv->D; i < pv->N; i++) pv->in_data[i] = (*pv_input)(pv->closure, 1);
}
buf = pv->filptr % pv->N;
for (i = 0; i < pv->N; i++)
{
pv->ampinc[buf++] = pv->win[i] * pv->in_data[i];
if (buf >= pv->N) buf = 0;
}
pv->filptr += pv->D;
mus_fft(pv->ampinc, pv->freqs, pv->N, 1);
mus_rectangular_to_polar(pv->ampinc, pv->freqs, N2);
}
if ((pv_edit == NULL) ||
((*pv_edit)(pv->closure)))
{
mus_float_t pscl, kscl, ks;
pscl = 1.0 / (mus_float_t)(pv->D);
kscl = TWO_PI / (mus_float_t)(pv->N);
for (i = 0, ks = 0.0; i < N2; i++, ks += kscl)
{
mus_float_t diff;
diff = pv->freqs[i] - pv->lastphase[i];
pv->lastphase[i] = pv->freqs[i];
while (diff > M_PI) diff -= TWO_PI;
while (diff < -M_PI) diff += TWO_PI;
pv->freqs[i] = pv->pitch * (diff * pscl + ks);
}
}
scl = 1.0 / (mus_float_t)(pv->interp);
for (i = 0; i < N2; i++)
{
pv->ampinc[i] = scl * (pv->ampinc[i] - pv->amps[i]);
pv->freqs[i] = scl * (pv->freqs[i] - pv->phaseinc[i]);
}
}
pv->outctr++;
if (pv_synthesize)
return((*pv_synthesize)(pv->closure));
for (i = 0; i < N2; i++)
{
pv->amps[i] += pv->ampinc[i];
pv->phaseinc[i] += pv->freqs[i];
pv->phases[i] += pv->phaseinc[i];
sum += (pv->amps[i] * sin(pv->phases[i]));
}
return(sum);
}
mus_float_t mus_phase_vocoder(mus_any *ptr, mus_float_t (*input)(void *arg, int direction))
{
return(mus_phase_vocoder_with_editors(ptr, input, NULL, NULL, NULL));
}
/* ---------------- single sideband "suppressed carrier" amplitude modulation (ssb-am) ---------------- */
typedef struct {
mus_any_class *core;
bool shift_up;
mus_float_t *coeffs;
mus_any *sin_osc, *cos_osc, *hilbert, *dly;
} ssbam;
bool mus_ssb_am_p(mus_any *ptr)
{
return((ptr) &&
(ptr->core->type == MUS_SSB_AM));
}
static mus_float_t run_hilbert(flt *gen, mus_float_t insig)
{
mus_float_t xout = 0.0, d1 = 0.0, d2 = 0.0;
mus_float_t *ap, *dp, *dend;
ap = gen->x;
dp = gen->state;
dend = (mus_float_t *)(gen->state + gen->order);
dp[0] = insig;
while (dp < dend)
{
xout += (*dp) * (*ap++);
d2 = d1;
d1 = (*dp);
(*dp++) = d2;
if (dp == dend) break;
d2 = d1;
d1 = (*dp);
(*dp++) = d2;
ap++; /* every odd-numbered entry in the coeffs array is 0 in this filter */
}
return(xout);
#if 0
int i, len;
mus_float_t val = 0.0;
len = g->order;
g->state[0] = insig;
for (i = 0; i < len; i += 2) val += (g->x[i] * g->state[i]);
for (i = len - 1; i >= 1; i--) g->state[i] = g->state[i - 1];
return(val);
#endif
}
mus_float_t mus_ssb_am_unmodulated(mus_any *ptr, mus_float_t insig)
{
ssbam *gen = (ssbam *)ptr;
return((mus_oscil_unmodulated(gen->cos_osc) * mus_delay_unmodulated(gen->dly, insig)) +
(mus_oscil_unmodulated(gen->sin_osc) * run_hilbert((flt *)(gen->hilbert), insig)));
}
mus_float_t mus_ssb_am(mus_any *ptr, mus_float_t insig, mus_float_t fm)
{
ssbam *gen = (ssbam *)ptr;
return((mus_oscil_fm(gen->cos_osc, fm) * mus_delay_unmodulated(gen->dly, insig)) +
(mus_oscil_fm(gen->sin_osc, fm) * run_hilbert((flt *)(gen->hilbert), insig)));
}
static int free_ssb_am(mus_any *ptr)
{
if (ptr)
{
ssbam *gen = (ssbam *)ptr;
mus_free(gen->dly);
mus_free(gen->hilbert);
mus_free(gen->cos_osc);
mus_free(gen->sin_osc);
if (gen->coeffs) {clm_free(gen->coeffs); gen->coeffs = NULL;}
clm_free(ptr);
}
return(0);
}
static mus_float_t ssb_am_freq(mus_any *ptr)
{
return(mus_radians_to_hz(((osc *)((ssbam *)ptr)->sin_osc)->freq));
}
static mus_float_t ssb_am_set_freq(mus_any *ptr, mus_float_t val)
{
ssbam *gen = (ssbam *)ptr;
mus_float_t rads;
rads = mus_hz_to_radians(val);
((osc *)(gen->sin_osc))->freq = rads;
((osc *)(gen->cos_osc))->freq = rads;
return(val);
}
static mus_float_t ssb_am_increment(mus_any *ptr)
{
return(((osc *)((ssbam *)ptr)->sin_osc)->freq);
}
static mus_float_t ssb_am_set_increment(mus_any *ptr, mus_float_t val)
{
ssbam *gen = (ssbam *)ptr;
((osc *)(gen->sin_osc))->freq = val;
((osc *)(gen->cos_osc))->freq = val;
return(val);
}
static mus_float_t ssb_am_phase(mus_any *ptr)
{
return(fmod(((osc *)((ssbam *)ptr)->cos_osc)->phase - 0.5 * M_PI, TWO_PI));
}
static mus_float_t ssb_am_set_phase(mus_any *ptr, mus_float_t val)
{
ssbam *gen = (ssbam *)ptr;
if (gen->shift_up)
((osc *)(gen->sin_osc))->phase = val + M_PI;
else ((osc *)(gen->sin_osc))->phase = val;
((osc *)(gen->cos_osc))->phase = val + 0.5 * M_PI;
return(val);
}
static mus_long_t ssb_am_order(mus_any *ptr) {return(mus_order(((ssbam *)ptr)->dly));}
static int ssb_am_interp_type(mus_any *ptr) {return(delay_interp_type(((ssbam *)ptr)->dly));}
static mus_float_t *ssb_am_data(mus_any *ptr) {return(filter_data(((ssbam *)ptr)->hilbert));}
static mus_float_t ssb_am_run(mus_any *ptr, mus_float_t insig, mus_float_t fm) {return(mus_ssb_am(ptr, insig, fm));}
static mus_float_t *ssb_am_xcoeffs(mus_any *ptr) {return(mus_xcoeffs(((ssbam *)ptr)->hilbert));}
static mus_float_t ssb_am_xcoeff(mus_any *ptr, int index) {return(mus_xcoeff(((ssbam *)ptr)->hilbert, index));}
static mus_float_t ssb_am_set_xcoeff(mus_any *ptr, int index, mus_float_t val) {return(mus_set_xcoeff(((ssbam *)ptr)->hilbert, index, val));}
static bool ssb_am_equalp(mus_any *p1, mus_any *p2)
{
return((p1 == p2) ||
((mus_ssb_am_p((mus_any *)p1)) &&
(mus_ssb_am_p((mus_any *)p2)) &&
(((ssbam *)p1)->shift_up == ((ssbam *)p2)->shift_up) &&
(mus_equalp(((ssbam *)p1)->sin_osc, ((ssbam *)p2)->sin_osc)) &&
(mus_equalp(((ssbam *)p1)->cos_osc, ((ssbam *)p2)->cos_osc)) &&
(mus_equalp(((ssbam *)p1)->dly, ((ssbam *)p2)->dly)) &&
(mus_equalp(((ssbam *)p1)->hilbert, ((ssbam *)p2)->hilbert))));
}
static char *describe_ssb_am(mus_any *ptr)
{
ssbam *gen = (ssbam *)ptr;
char *describe_buffer;
describe_buffer = (char *)clm_malloc(DESCRIBE_BUFFER_SIZE, "describe buffer");
mus_snprintf(describe_buffer, DESCRIBE_BUFFER_SIZE, "%s shift: %s, sin/cos: %f Hz (%f radians), order: %d",
mus_name(ptr),
(gen->shift_up) ? "up" : "down",
mus_frequency(ptr),
mus_phase(ptr),
(int)mus_order(ptr));
return(describe_buffer);
}
static void ssb_reset(mus_any *ptr)
{
ssbam *gen = (ssbam *)ptr;
ssb_am_set_phase(ptr, 0.0);
mus_reset(gen->dly);
mus_reset(gen->hilbert);
}
static mus_any_class SSB_AM_CLASS = {
MUS_SSB_AM,
(char *)S_ssb_am,
&free_ssb_am,
&describe_ssb_am,
&ssb_am_equalp,
&ssb_am_data, 0,
&ssb_am_order, 0,
&ssb_am_freq,
&ssb_am_set_freq,
&ssb_am_phase,
&ssb_am_set_phase,
&fallback_scaler, 0,
&ssb_am_increment,
&ssb_am_set_increment,
&ssb_am_run,
MUS_NOT_SPECIAL,
NULL,
&ssb_am_interp_type,
0, 0, 0, 0,
&ssb_am_xcoeff, &ssb_am_set_xcoeff,
0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0,
0, 0,
&ssb_am_xcoeffs, 0, 0,
&ssb_reset,
0, 0, 0
};
mus_any *mus_make_ssb_am(mus_float_t freq, int order)
{
ssbam *gen;
int i, k, len;
if ((order & 1) == 0) order++; /* if order is even, the first Hilbert coeff is 0.0 */
gen = (ssbam *)clm_calloc(1, sizeof(ssbam), S_make_ssb_am);
gen->core = &SSB_AM_CLASS;
if (freq > 0)
gen->shift_up = true;
else gen->shift_up = false;
gen->sin_osc = mus_make_oscil(fabs(freq), (gen->shift_up) ? M_PI : 0.0);
gen->cos_osc = mus_make_oscil(fabs(freq), M_PI * 0.5);
gen->dly = mus_make_delay(order, NULL, order, MUS_INTERP_NONE);
len = order * 2 + 1;
gen->coeffs = (mus_float_t *)clm_calloc(len, sizeof(mus_float_t), "make-ssb-am");
for (i = -order, k = 0; i <= order; i++, k++)
{
mus_float_t denom, num;
denom = i * M_PI;
num = 1.0 - cos(denom);
if (i == 0)
gen->coeffs[k] = 0.0;
else gen->coeffs[k] = (num / denom) * (0.54 + (0.46 * cos(denom / order)));
}
gen->hilbert = mus_make_fir_filter(len, gen->coeffs, NULL);
return((mus_any *)gen);
}
/* ---------------- mix files ---------------- */
/* a mixing "instrument" along the lines of the mix function in clm */
/* this is a very commonly used function, so it's worth picking out the special cases for optimization */
#define IDENTITY_MIX 0
#define IDENTITY_MONO_MIX 1
#define SCALED_MONO_MIX 2
#define SCALED_MIX 3
#define ENVELOPED_MONO_MIX 4
#define ENVELOPED_MIX 5
#define ALL_MIX 6
static int mix_type(int out_chans, int in_chans, mus_any *umx, mus_any ***envs)
{
mus_mixer *mx = (mus_mixer *)umx;
if (envs)
{
if ((in_chans == 1) && (out_chans == 1))
return(ENVELOPED_MONO_MIX);
else
{
if (mx)
return(ALL_MIX);
return(ENVELOPED_MIX);
}
}
if (mx)
{
int i, j;
if ((in_chans == 1) && (out_chans == 1))
{
if (mx->vals[0][0] == 1.0)
return(IDENTITY_MONO_MIX);
return(SCALED_MONO_MIX);
}
for (i = 0; i < mx->chans; i++)
for (j = 0; j < mx->chans; j++)
if (((i == j) && (mx->vals[i][i] != 1.0)) ||
((i != j) && (mx->vals[i][j] != 0.0)))
return(SCALED_MIX);
}
if ((in_chans == 1) && (out_chans == 1))
return(IDENTITY_MONO_MIX);
return(IDENTITY_MIX);
}
void mus_mix_with_reader_and_writer(mus_any *outf, mus_any *inf, mus_long_t out_start, mus_long_t out_frames, mus_long_t in_start, mus_any *umx, mus_any ***envs)
{
int in_chans, out_chans, mix_chans, mixtype;
mus_mixer *mx = (mus_mixer *)umx;
mus_long_t inc, outc, offi;
mus_frame *frin, *frthru = NULL;
out_chans = mus_channels(outf);
if (out_chans <= 0)
mus_error(MUS_NO_CHANNELS, "%s chans: %d", mus_describe(outf), out_chans);
in_chans = mus_channels(inf);
if (in_chans <= 0)
mus_error(MUS_NO_CHANNELS, "%s chans: %d", mus_describe(inf), in_chans);
if (out_chans > in_chans)
mix_chans = out_chans;
else mix_chans = in_chans;
mixtype = mix_type(out_chans, in_chans, umx, envs);
frin = (mus_frame *)mus_make_empty_frame(mix_chans);
frthru = (mus_frame *)mus_make_empty_frame(mix_chans);
switch (mixtype)
{
case ENVELOPED_MONO_MIX:
case ENVELOPED_MIX:
if (umx == NULL)
mx = (mus_mixer *)mus_make_identity_mixer(mix_chans); /* fall through */
case ALL_MIX:
/* the general case -- possible envs/scalers on every mixer cell */
for (offi = 0, inc = in_start, outc = out_start; offi < out_frames; offi++, inc++, outc++)
{
int j, k;
for (j = 0; j < in_chans; j++)
for (k = 0; k < out_chans; k++)
if (envs[j][k])
mx->vals[j][k] = mus_env(envs[j][k]);
mus_frame_to_file(outf,
outc,
mus_frame_to_frame(mus_file_to_frame(inf, inc, (mus_any *)frin),
(mus_any *)mx,
(mus_any *)frthru));
}
if (umx == NULL) mus_free((mus_any *)mx);
break;
case IDENTITY_MIX:
case IDENTITY_MONO_MIX:
for (offi = 0, inc = in_start, outc = out_start; offi < out_frames; offi++, inc++, outc++)
mus_frame_to_file(outf, outc, mus_file_to_frame(inf, inc, (mus_any *)frin));
break;
case SCALED_MONO_MIX:
case SCALED_MIX:
for (offi = 0, inc = in_start, outc = out_start; offi < out_frames; offi++, inc++, outc++)
mus_frame_to_file(outf,
outc,
mus_frame_to_frame(mus_file_to_frame(inf, inc, (mus_any *)frin),
(mus_any *)mx,
(mus_any *)frthru));
break;
}
mus_free((mus_any *)frin);
mus_free((mus_any *)frthru);
}
void mus_mix(const char *outfile, const char *infile, mus_long_t out_start, mus_long_t out_frames, mus_long_t in_start, mus_any *umx, mus_any ***envs)
{
int in_chans, out_chans, min_chans, mixtype;
out_chans = mus_sound_chans(outfile);
if (out_chans <= 0)
mus_error(MUS_NO_CHANNELS, "%s chans: %d", outfile, out_chans);
in_chans = mus_sound_chans(infile);
if (in_chans <= 0)
mus_error(MUS_NO_CHANNELS, "%s chans: %d", infile, in_chans);
if (out_chans > in_chans)
min_chans = in_chans; else min_chans = out_chans;
mixtype = mix_type(out_chans, in_chans, umx, envs);
if (mixtype == ALL_MIX)
{
mus_any *inf, *outf;
/* the general case -- possible envs/scalers on every mixer cell */
outf = mus_continue_sample_to_file(outfile);
inf = mus_make_file_to_frame(infile);
mus_mix_with_reader_and_writer(outf, inf, out_start, out_frames, in_start, umx, envs);
mus_free((mus_any *)inf);
mus_free((mus_any *)outf);
}
else
{
mus_mixer *mx = (mus_mixer *)umx;
mus_long_t j = 0;
int i, m, ofd, ifd;
mus_float_t scaler;
mus_any *e;
mus_sample_t **obufs, **ibufs;
mus_long_t offk, curoutframes;
/* highly optimizable cases */
obufs = (mus_sample_t **)clm_malloc(out_chans * sizeof(mus_sample_t *), "mix output");
for (i = 0; i < out_chans; i++)
obufs[i] = (mus_sample_t *)clm_calloc(clm_file_buffer_size, sizeof(mus_sample_t), "mix output buffers");
ibufs = (mus_sample_t **)clm_malloc(in_chans * sizeof(mus_sample_t *), "mix input");
for (i = 0; i < in_chans; i++)
ibufs[i] = (mus_sample_t *)clm_calloc(clm_file_buffer_size, sizeof(mus_sample_t), "mix input buffers");
ifd = mus_sound_open_input(infile);
mus_file_seek_frame(ifd, in_start);
mus_file_read(ifd, 0, clm_file_buffer_size - 1, in_chans, ibufs);
ofd = mus_sound_reopen_output(outfile,
out_chans,
mus_sound_data_format(outfile),
mus_sound_header_type(outfile),
mus_sound_data_location(outfile));
curoutframes = mus_sound_frames(outfile);
mus_file_seek_frame(ofd, out_start);
mus_file_read(ofd, 0, clm_file_buffer_size - 1, out_chans, obufs);
mus_file_seek_frame(ofd, out_start);
switch (mixtype)
{
case IDENTITY_MONO_MIX:
for (offk = 0, j = 0; offk < out_frames; offk++, j++)
{
if (j == clm_file_buffer_size)
{
mus_file_write(ofd, 0, j - 1, out_chans, obufs);
j = 0;
mus_file_seek_frame(ofd, out_start + offk);
mus_file_read(ofd, 0, clm_file_buffer_size - 1, out_chans, obufs);
mus_file_seek_frame(ofd, out_start + offk);
mus_file_read(ifd, 0, clm_file_buffer_size - 1, in_chans, ibufs);
}
obufs[0][j] += ibufs[0][j];
}
break;
case IDENTITY_MIX:
for (offk = 0, j = 0; offk < out_frames; offk++, j++)
{
if (j == clm_file_buffer_size)
{
mus_file_write(ofd, 0, j - 1, out_chans, obufs);
j = 0;
mus_file_seek_frame(ofd, out_start + offk);
mus_file_read(ofd, 0, clm_file_buffer_size - 1, out_chans, obufs);
mus_file_seek_frame(ofd, out_start + offk);
mus_file_read(ifd, 0, clm_file_buffer_size - 1, in_chans, ibufs);
}
for (i = 0; i < min_chans; i++)
obufs[i][j] += ibufs[i][j];
}
break;
case SCALED_MONO_MIX:
scaler = mx->vals[0][0];
for (offk = 0, j = 0; offk < out_frames; offk++, j++)
{
if (j == clm_file_buffer_size)
{
mus_file_write(ofd, 0, j - 1, out_chans, obufs);
j = 0;
mus_file_seek_frame(ofd, out_start + offk);
mus_file_read(ofd, 0, clm_file_buffer_size - 1, out_chans, obufs);
mus_file_seek_frame(ofd, out_start + offk);
mus_file_read(ifd, 0, clm_file_buffer_size - 1, in_chans, ibufs);
}
obufs[0][j] += (mus_sample_t)(scaler * ibufs[0][j]);
}
break;
case SCALED_MIX:
for (offk = 0, j = 0; offk < out_frames; offk++, j++)
{
if (j == clm_file_buffer_size)
{
mus_file_write(ofd, 0, j - 1, out_chans, obufs);
j = 0;
mus_file_seek_frame(ofd, out_start + offk);
mus_file_read(ofd, 0, clm_file_buffer_size- 1 , out_chans, obufs);
mus_file_seek_frame(ofd, out_start + offk);
mus_file_read(ifd, 0, clm_file_buffer_size - 1, in_chans, ibufs);
}
for (i = 0; i < min_chans; i++)
for (m = 0; m < in_chans; m++)
obufs[i][j] += (mus_sample_t)(ibufs[m][j] * mx->vals[m][i]);
}
break;
case ENVELOPED_MONO_MIX:
e = envs[0][0];
for (offk = 0, j = 0; offk < out_frames; offk++, j++)
{
if (j == clm_file_buffer_size)
{
mus_file_write(ofd, 0, j - 1, out_chans, obufs);
j = 0;
mus_file_seek_frame(ofd, out_start + offk);
mus_file_read(ofd, 0, clm_file_buffer_size - 1, out_chans, obufs);
mus_file_seek_frame(ofd, out_start + offk);
mus_file_read(ifd, 0, clm_file_buffer_size - 1, in_chans, ibufs);
}
obufs[0][j] += (mus_sample_t)(mus_env(e) * ibufs[0][j]);
}
break;
case ENVELOPED_MIX:
e = envs[0][0];
for (offk = 0, j = 0; offk < out_frames; offk++, j++)
{
if (j == clm_file_buffer_size)
{
mus_file_write(ofd, 0, j - 1, out_chans, obufs);
j = 0;
mus_file_seek_frame(ofd, out_start + offk);
mus_file_read(ofd, 0, clm_file_buffer_size - 1, out_chans, obufs);
mus_file_seek_frame(ofd, out_start + offk);
mus_file_read(ifd, 0, clm_file_buffer_size - 1, in_chans, ibufs);
}
scaler = mus_env(e);
for (i = 0; i < min_chans; i++)
obufs[i][j] += (mus_sample_t)(scaler * ibufs[i][j]);
}
break;
}
if (j > 0)
mus_file_write(ofd, 0, j - 1, out_chans, obufs);
if (curoutframes < (out_frames + out_start))
curoutframes = out_frames + out_start;
mus_sound_close_output(ofd,
curoutframes * out_chans * mus_bytes_per_sample(mus_sound_data_format(outfile)));
mus_sound_close_input(ifd);
for (i = 0; i < in_chans; i++) clm_free(ibufs[i]);
clm_free(ibufs);
for (i = 0; i < out_chans; i++) clm_free(obufs[i]);
clm_free(obufs);
}
}
/* ---------------- mus-apply ---------------- */
mus_float_t mus_apply(mus_any *gen, mus_float_t f1, mus_float_t f2)
{
/* what about non-gen funcs such as polynomial, ring_modulate etc? */
if ((gen) && (MUS_RUN_P(gen)))
return(MUS_RUN(gen, f1, f2));
return(0.0);
}
/* ---------------- init clm ---------------- */
void mus_initialize(void)
{
#define MULAW_ZERO 255
#define ALAW_ZERO 213
#define UBYTE_ZERO 128
mus_class_tag = MUS_INITIAL_GEN_TAG;
sampling_rate = MUS_DEFAULT_SAMPLING_RATE;
w_rate = (TWO_PI / MUS_DEFAULT_SAMPLING_RATE);
array_print_length = MUS_DEFAULT_ARRAY_PRINT_LENGTH;
clm_file_buffer_size = MUS_DEFAULT_FILE_BUFFER_SIZE;
#if HAVE_FFTW3 && HAVE_COMPLEX_TRIG && (!__cplusplus)
last_c_fft_size = 0;
/* is there a problem if the caller built fftw with --enable-threads?
* How to tell via configure that we need to initialize the thread stuff in libfftw?
*/
#endif
sincs = 0;
locsig_warned = NULL;
data_format_zero = (int *)clm_calloc(MUS_NUM_DATA_FORMATS, sizeof(int), "init mus module");
data_format_zero[MUS_MULAW] = MULAW_ZERO;
data_format_zero[MUS_ALAW] = ALAW_ZERO;
data_format_zero[MUS_UBYTE] = UBYTE_ZERO;
#if MUS_LITTLE_ENDIAN
data_format_zero[MUS_UBSHORT] = 0x80;
data_format_zero[MUS_ULSHORT] = 0x8000;
#else
data_format_zero[MUS_UBSHORT] = 0x8000;
data_format_zero[MUS_ULSHORT] = 0x80;
#endif
}
| {
"alphanum_fraction": 0.6185898624,
"avg_line_length": 26.5791721419,
"ext": "c",
"hexsha": "9200416591404076af21ee15db4121429a9e8933",
"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": "b633660e5945a6a6b095cd9aa3178deab56b354f",
"max_forks_repo_licenses": [
"Ruby"
],
"max_forks_repo_name": "OS2World/MM-SOUND-Snd",
"max_forks_repo_path": "sources/clm.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "b633660e5945a6a6b095cd9aa3178deab56b354f",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"Ruby"
],
"max_issues_repo_name": "OS2World/MM-SOUND-Snd",
"max_issues_repo_path": "sources/clm.c",
"max_line_length": 179,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "b633660e5945a6a6b095cd9aa3178deab56b354f",
"max_stars_repo_licenses": [
"Ruby"
],
"max_stars_repo_name": "OS2World/MM-SOUND-Snd",
"max_stars_repo_path": "sources/clm.c",
"max_stars_repo_stars_event_max_datetime": "2018-08-27T17:57:08.000Z",
"max_stars_repo_stars_event_min_datetime": "2018-08-27T17:57:08.000Z",
"num_tokens": 111357,
"size": 323628
} |
/* rng/rand.c
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000 James Theiler, Brian Gough
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <config.h>
#include <stdlib.h>
#include <gsl/gsl_rng.h>
/* This is the old BSD rand() generator. The sequence is
x_{n+1} = (a x_n + c) mod m
with a = 1103515245, c = 12345 and m = 2^31 = 2147483648. The seed
specifies the initial value, x_1.
The theoretical value of x_{10001} is 1910041713.
The period of this generator is 2^31.
The rand() generator is not very good -- the low bits of successive
numbers are correlated. */
static inline unsigned long int rand_get (void *vstate);
static double rand_get_double (void *vstate);
static void rand_set (void *state, unsigned long int s);
typedef struct
{
unsigned long int x;
}
rand_state_t;
static inline unsigned long int
rand_get (void *vstate)
{
rand_state_t *state = (rand_state_t *) vstate;
/* The following line relies on unsigned 32-bit arithmetic */
state->x = (1103515245 * state->x + 12345) & 0x7fffffffUL;
return state->x;
}
static double
rand_get_double (void *vstate)
{
return rand_get (vstate) / 2147483648.0 ;
}
static void
rand_set (void *vstate, unsigned long int s)
{
rand_state_t *state = (rand_state_t *) vstate;
state->x = s;
return;
}
static const gsl_rng_type rand_type =
{"rand", /* name */
0x7fffffffUL, /* RAND_MAX */
0, /* RAND_MIN */
sizeof (rand_state_t),
&rand_set,
&rand_get,
&rand_get_double};
const gsl_rng_type *gsl_rng_rand = &rand_type;
| {
"alphanum_fraction": 0.7062556664,
"avg_line_length": 25.6511627907,
"ext": "c",
"hexsha": "315cb4e97b37594bbb6552c0bb8f378f5560438a",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2015-10-02T01:32:59.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-10-02T01:32:59.000Z",
"max_forks_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "ICML14MoMCompare/spectral-learn",
"max_forks_repo_path": "code/em/treba/gsl-1.0/rng/rand.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "ICML14MoMCompare/spectral-learn",
"max_issues_repo_path": "code/em/treba/gsl-1.0/rng/rand.c",
"max_line_length": 72,
"max_stars_count": 14,
"max_stars_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "ICML14MoMCompare/spectral-learn",
"max_stars_repo_path": "code/em/treba/gsl-1.0/rng/rand.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": 621,
"size": 2206
} |
/* numerical stuff */
#include <math.h>
#include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>
#include "numerical.h"
#include <gsl/gsl_sf.h>
//#include "nrutil.h"
/* Numerical Recipes Stuff */
#define GOLD 1.618034
#define GLIMIT 100.0
#define TINY 1.0e-20
#define MAX(a,b) ((a) > (b) ? (a) : (b))
#define MIN(a,b) ((a) < (b) ? (a) : (b))
#define SIGN(a,b) ((b) > 0.0 ? fabs(a) : -fabs(a))
#define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d);
#define FUNC(x) ((*func)(x))
#define FUNC2(x,p) ((*func)(x,p))
#define MIN_P_VALUE 1.0e-200
#define EPS 1.0e-5
#define JMAX 50
/* this is from numerical recipes; brackets a minimum with ax, bx, cx */
void mnbrak(double *ax,double *bx,double *cx,double *fa,double *fb,double *fc,double (*func)()){
double ulim,u,r,q,fu,dum;
*fa=(*func)(*ax);
*fb=(*func)(*bx);
if(*fb > *fa){
SHFT(dum,*ax,*bx,dum)
SHFT(dum,*fb,*fa,dum)
}
*cx = *bx + GOLD * (*bx-*ax);
*fc=(*func)(*cx);
while(*fb > *fc){
r=(*bx-*ax)*(*fb-*fc);
q=(*bx-*cx)*(*fb-*fa);
u = *bx-((*bx-*cx)*q-(*bx-*ax)*r) /
(2.*SIGN(MAX(fabs(q-r),TINY),q-r));
ulim = *bx + GLIMIT * (*cx-*bx);
if((*bx-u) * (u-*cx) > 0.0){
fu=(*func)(u);
if(fu < *fc){
*ax = *bx;
*bx = u;
*fa = *fb;
*fb = fu;
return;
}
else if(fu > *fb){
*cx=u;
*fc=fu;
return;
}
u = *cx + GOLD * (*cx-*bx);
fu = (*func)(u);
}
else if((*cx-u)*(u-ulim) > 0.0){
fu=(*func)(u);
if(fu < *fc){
SHFT(*bx,*cx,u,*cx + GOLD * (*cx - *bx));
SHFT(*fb,*fc,fu,(*func)(u));
}
}
else if((u-ulim)*(ulim-*cx) >= 0.0){
u=ulim;
fu=(*func)(u);
}
else{
u = *cx+GOLD*(*cx-*bx);
fu=(*func)(u);
}
SHFT(*ax,*bx,*cx,u)
SHFT(*fa,*fb,*fc,fu)
}
return;
}
/* this is from numerical recipes; brackets a minimum with ax, bx, cx */
void mnbrak2(double *ax,double *bx,double *cx,double *fa,double *fb,double *fc,double (*func)(double, void * ), double beta, void * p){
double ulim,u,r,q,fu,dum;
*fa=(*func)(*ax, p);
*fb=(*func)(*bx, p);
if(*fb > *fa){
SHFT(dum,*ax,*bx,dum)
SHFT(dum,*fb,*fa,dum)
}
*cx = *bx + GOLD * (*bx-*ax);
*fc=(*func)(*cx, p);
while(*fb > *fc){
r=(*bx-*ax)*(*fb-*fc);
q=(*bx-*cx)*(*fb-*fa);
u = *bx-((*bx-*cx)*q-(*bx-*ax)*r) /
(2.*SIGN(MAX(fabs(q-r),TINY),q-r));
ulim = *bx + GLIMIT * (*cx-*bx);
if((*bx-u) * (u-*cx) > 0.0){
fu=(*func)(u, p);
if(fu < *fc){
*ax = *bx;
*bx = u;
*fa = *fb;
*fb = fu;
return;
}
else if(fu > *fb){
*cx=u;
*fc=fu;
return;
}
u = *cx + GOLD * (*cx-*bx);
fu = (*func)(u, p);
}
else if((*cx-u)*(u-ulim) > 0.0){
fu=(*func)(u, p);
if(fu < *fc){
SHFT(*bx,*cx,u,*cx + GOLD * (*cx - *bx));
SHFT(*fb,*fc,fu,(*func)(u, p));
}
}
else if((u-ulim)*(ulim-*cx) >= 0.0){
u=ulim;
fu=(*func)(u, p);
}
else{
u = *cx+GOLD*(*cx-*bx);
fu=(*func)(u, p);
}
SHFT(*ax,*bx,*cx,u)
SHFT(*fa,*fb,*fc,fu)
}
return;
}
/* Numerical Integration Routines */
#define FUNC(x) ((*func)(x))
double d_trapzd(double (*func)(double), double a, double b, int n)
{
double x,tnm,sum,del;
static double s;
int it,j;
if (n == 1) {
return (s=0.5*(b-a)*(FUNC(a)+FUNC(b)));
} else {
for (it=1,j=1;j<n-1;j++) it <<= 1;
tnm=it;
del=(b-a)/tnm;
x=a+0.5*del;
for (sum=0.0,j=1;j<=it;j++,x+=del) sum += FUNC(x);
s=0.5*(s+(b-a)*sum/tnm);
return s;
}
}
/* specific version for GSL function */
double d_trapzd2(double (*func)(double, void *), double a, double b, int n, void * p)
{
double x,tnm,sum,del;
static double s;
int it,j;
if (n == 1) {
return (s=0.5*(b-a)*(FUNC2(a,p)+FUNC2(b,p)));
} else {
for (it=1,j=1;j<n-1;j++) it <<= 1;
tnm=it;
del=(b-a)/tnm;
x=a+0.5*del;
for (sum=0.0,j=1;j<=it;j++,x+=del) sum += FUNC2(x,p);
s=0.5*(s+(b-a)*sum/tnm);
return s;
}
}
double d_qtrap(double (*func)(double), double a, double b)
{
double trapzd(double (*func)(double), double a, double b, int n);
void nrerror(char error_text[]);
double s,olds;
int j;
olds = -1.0e30;
for (j=1;j<=JMAX;j++) {
s=d_trapzd(func,a,b,j);
if (fabs(s-olds) < EPS*fabs(olds)) return s;
olds=s;
}
nrerror("Too many steps in routine qtrap");
return 0.0;
}
/* specific version for GSL function */
double d_qtrap2(double (*func)(double, void *), double a, double b, void * p){
double s,olds;
int j;
olds = -1.0e30;
for (j=1;j<=JMAX;j++) {
s=d_trapzd2(func,a,b,j,p);
if (fabs(s-olds) < EPS*fabs(olds)) return s;
olds=s;
}
nrerror("Too many steps in routine qtrap");
return 0.0;
}
double d_qsimp(double (*func)(double), double a, double b)
{
double trapzd(double (*func)(double), double a, double b, int n);
void nrerror(char error_text[]);
int j;
double s,st,ost,os;
ost = os = -1.0e30;
for (j=1;j<=JMAX;j++) {
st=d_trapzd(func,a,b,j);
s=(4.0*st-ost)/3.0;
if (fabs(s-os) < EPS*fabs(os)) return s;
os=s;
ost=st;
}
nrerror("Too many steps in routine qsimp");
return 0.0;
}
#define JMAXP (JMAX+1)
#define K 5
double d_qromb(double (*func)(double), double a, double b)
{
void polint(double xa[], double ya[], int n, double x, double *y, double *dy);
double trapzd(double (*func)(double), double a, double b, int n);
void nrerror(char error_text[]);
double ss,dss;
double s[JMAXP+1],h[JMAXP+1];
int j;
h[1]=1.0;
for (j=1;j<=JMAX;j++) {
s[j]=d_trapzd(func,a,b,j);
if (j >= K) {
d_polint(&h[j-K],&s[j-K],K,0.0,&ss,&dss);
if (fabs(dss) < EPS*fabs(ss)) return ss;
}
s[j+1]=s[j];
h[j+1]=0.25*h[j];
}
nrerror("Too many steps in routine qromb");
return 0.0;
}
double d_qromb2(double (*func)(double, void *), double a, double b, void * p){
double ss,dss;
double s[JMAXP+1],h[JMAXP+1];
int j;
h[1]=1.0;
for (j=1;j<=JMAX;j++) {
s[j]=midpnt2(func,a,b,j,p);
if (j >= K) {
d_polint(&h[j-K],&s[j-K],K,0.0,&ss,&dss);
if (fabs(dss) < EPS*fabs(ss)) return ss;
}
s[j+1]=s[j];
h[j+1]=0.25*h[j];
}
nrerror("Too many steps in routine qromb");
return 0.0;
}
#undef JMAXP
#undef K
#define NRANSI
#include "nrutil.h"
void d_polint(double xa[], double ya[], int n, double x, double *y, double *dy)
{
int i,m,ns=1;
double den,dif,dift,ho,hp,w;
double *c,*d;
dif=fabs(x-xa[1]);
c=dvector(1,n);
d=dvector(1,n);
for (i=1;i<=n;i++) {
if ( (dift=fabs(x-xa[i])) < dif) {
ns=i;
dif=dift;
}
c[i]=ya[i];
d[i]=ya[i];
}
*y=ya[ns--];
for (m=1;m<n;m++) {
for (i=1;i<=n-m;i++) {
ho=xa[i]-x;
hp=xa[i+m]-x;
w=c[i+1]-d[i];
if ( (den=ho-hp) == 0.0) nrerror("Error in routine polint");
den=w/den;
d[i]=hp*den;
c[i]=ho*den;
}
*y += (*dy=(2*ns < (n-m) ? c[ns+1] : d[ns--]));
}
free_dvector(d,1,n);
free_dvector(c,1,n);
}
#undef NRANSI
/* from chp. 4 of numerical recipes */
double midpnt(double (*func)(double), double a, double b, int n){
double x,tnm,sum,del,ddel;
static double s;
int it,j;
if (n == 1) {
return (s=(b-a)*FUNC(0.5*(a+b)));
} else {
for(it=1,j=1;j<n-1;j++) it *= 3;
tnm=it;
del=(b-a)/(3.0*tnm);
ddel=del+del;
x=a+0.5*del;
sum=0.0;
for (j=1;j<=it;j++) {
sum += FUNC(x);
x += ddel;
sum += FUNC(x);
x += del;
}
s=(s+(b-a)*sum/tnm)/3.0;
return s;
}
}
/* from chp. 4 of numerical recipes, specific for GSL functions */
double midpnt2(double (*func)(double, void *), double a, double b, int n, void * p){
double x,tnm,sum,del,ddel;
static double s;
int it,j;
if (n == 1) {
return (s=(b-a)*FUNC2(0.5*(a+b),p));
} else {
for(it=1,j=1;j<n-1;j++) it *= 3;
tnm=it;
del=(b-a)/(3.0*tnm);
ddel=del+del;
x=a+0.5*del;
sum=0.0;
for (j=1;j<=it;j++) {
sum += FUNC2(x,p);
x += ddel;
sum += FUNC2(x,p);
x += del;
}
s=(s+(b-a)*sum/tnm)/3.0;
return s;
}
}
/* factorials */
double xchoosey(int n, int k){
if(n<k) return(0);
if(n == k || k == 0) return(1);
return(gsl_sf_choose(n,k));
}
double multinom(int x, int n, ...) {
int i, y;
va_list ap;
double ret_val=0.0;
va_start(ap, n);
for (i=0; i<n; i++) {
y = va_arg(ap, int);
if (x < y) return 0.0;
ret_val *= xchoosey(x, y);
x -= y;
if (x < 0) return 0.0;
}
va_end(ap);
return exp(ret_val);
}
//from Chuck Langley
/* +++++++++++ chl 19JAN2010 ++++++++++++++++++++++++++++++++++++++++++ */
double FsXctTst(int m11, int m12, int m21, int m22) {
double onetail, twotail;
double ep[(m11+m12+m21+m22 + 1)];
double cov[(m11+m12+m21+m22 + 1)];
int nt11,nt12,nt21,nt22 ;
int i ;
if( ((m11+m21)<1) || ((m12+m22)<1) ) return(-99.0);
nt11 = 0 ;
do
{
nt12 = m11 + m12 - nt11 ;
nt21 = m11 + m21 - nt11 ;
nt22 = m11 + m12 + m21 + m22 - nt11 - nt12 - nt21 ;
ep[nt11] = 0.0 ;
cov[nt11] = 0.0 ;
if ((nt12 < 0) || (nt21 < 0) || (nt22 < 0))
nt11++ ;
else
{
ep[nt11] = ExactProb(nt11,nt12,nt21,nt22) ;
cov[nt11] = nt11*nt22 - nt12*nt21 ;
/* fprintf(stderr,"\nep[%2d] = %e\tcov[%2d] = %e", nt11,ep[nt11],nt11,cov[nt11]) ; */
nt11++ ;
}
} while (nt11 <= (MIN( (m11 + m12),(m11 + m21))) ) ;
if(cov[m11] <= 0.0){
onetail = 0.0 ;
for(i=0;i<=m11;i++) onetail += ep[i] ;
twotail = onetail ;
i = nt11 - 1 ;
if(ep[i] <= (ep[m11] + 0.0001))
{
do
{
twotail += ep[i] ;
i-- ;
} while ((ep[i] <= (ep[m11] + 0.0001)) && (i > m11)) ;
}
}
else
{
onetail = 0.0 ;
for(i=m11;i<nt11;i++) onetail += ep[i] ;
twotail = onetail ;
i = 0 ;
if(ep[0] <= (ep[m11] + 0.0001))
{
do
{
twotail += ep[i] ;
i++ ;
} while ((ep[i] <= (ep[m11] + 0.0001)) && (i < m11)) ;
}
}
if(cov[m11] == 0.0) onetail = 99 ;
/* fprintf(stderr,"\n onetail = %e \t twotail = %e ", *onetail, *twotail) ; */
if(twotail < MIN_P_VALUE) printf("\nFsXctTst(%d,%d,%d,%d) = %lf", m11, m12, m21, m22, twotail);
return(twotail) ;
}
double ExactProb(int nn11, int nn12, int nn21, int nn22){
double xp = 0.0;
xp = logfact(nn11+nn12) ;
xp += logfact(nn11+nn21) ;
xp += logfact(nn12+nn22) ;
xp += logfact(nn21+nn22) ;
xp -= logfact(nn11+nn12+nn21+nn22) ;
xp -= logfact(nn11) ;
xp -= logfact(nn12) ;
xp -= logfact(nn21) ;
xp -= logfact(nn22) ;
return(exp(xp)) ;
}
double logfact(int num){
double sumlog = 0.0 ;
if((num == 0) || (num == 1)) return(0.0) ;
else
{
do
{
sumlog += log(((double)num)) ;
num-- ;
} while (num > 1) ;
return(sumlog) ;
}
return(-99.99) ;
}
/* #define ITMAX 200 */
/* #define NRANSI */
/* void powellMin(double p[], double **xi, int n, double ftol, int *iter, double *fret, */
/* double (*func)(double [])) */
/* { */
/* void linmin(double p[], double xi[], int n, double *fret, */
/* float (*func)(double [])); */
/* int i,ibig,j; */
/* float del,fp,fptt,t,*pt,*ptt,*xit; */
/* pt=vector(1,n); */
/* ptt=vector(1,n); */
/* xit=vector(1,n); */
/* *fret=(*func)(p); */
/* for (j=1;j<=n;j++) pt[j]=p[j]; */
/* for (*iter=1;;++(*iter)) { */
/* fp=(*fret); */
/* ibig=0; */
/* del=0.0; */
/* for (i=1;i<=n;i++) { */
/* for (j=1;j<=n;j++) xit[j]=xi[j][i]; */
/* fptt=(*fret); */
/* linmin(p,xit,n,fret,func); */
/* if (fabs(fptt-(*fret)) > del) { */
/* del=fabs(fptt-(*fret)); */
/* ibig=i; */
/* } */
/* } */
/* if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) { */
/* free_vector(xit,1,n); */
/* free_vector(ptt,1,n); */
/* free_vector(pt,1,n); */
/* return; */
/* } */
/* if (*iter == ITMAX) nrerror("powell exceeding maximum iterations."); */
/* for (j=1;j<=n;j++) { */
/* ptt[j]=2.0*p[j]-pt[j]; */
/* xit[j]=p[j]-pt[j]; */
/* pt[j]=p[j]; */
/* } */
/* fptt=(*func)(ptt); */
/* if (fptt < fp) { */
/* t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt); */
/* if (t < 0.0) { */
/* linmin(p,xit,n,fret,func); */
/* for (j=1;j<=n;j++) { */
/* xi[j][ibig]=xi[j][n]; */
/* xi[j][n]=xit[j]; */
/* } */
/* } */
/* } */
/* } */
/* } */
/* #undef ITMAX */
/* #undef NRANSI */
/* #define NRANSI */
/* #define TOL 2.0e-4 */
/* int ncom; */
/* double *pcom,*xicom,(*nrfunc)(double []); */
/* void linmin(double p[], double xi[], int n, double *fret, double (*func)(double [])) */
/* { */
/* float brent(double ax, double bx, double cx, */
/* double (*f)(double), double tol, double *xmin); */
/* double f1dim(double x); */
/* void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, */
/* double *fc, double (*func)(double)); */
/* int j; */
/* double xx,xmin,fx,fb,fa,bx,ax; */
/* ncom=n; */
/* pcom=vector(1,n); */
/* xicom=vector(1,n); */
/* nrfunc=func; */
/* for (j=1;j<=n;j++) { */
/* pcom[j]=p[j]; */
/* xicom[j]=xi[j]; */
/* } */
/* ax=0.0; */
/* xx=1.0; */
/* mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim); */
/* *fret=brent(ax,xx,bx,f1dim,TOL,&xmin); */
/* for (j=1;j<=n;j++) { */
/* xi[j] *= xmin; */
/* p[j] += xi[j]; */
/* } */
/* free_vector(xicom,1,n); */
/* free_vector(pcom,1,n); */
/* } */
/* #undef TOL */
/* #undef NRANSI */
/* #define NRANSI */
/* #define ITMAX 100 */
/* #define CGOLD 0.3819660 */
/* #define ZEPS 1.0e-10 */
/* #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d); */
/* double brent(double ax, double bx, double cx, double (*f)(double), double tol, */
/* double *xmin) */
/* { */
/* int iter; */
/* double a,b,d,etemp,fu,fv,fw,fx,p,q,r,tol1,tol2,u,v,w,x,xm; */
/* double e=0.0; */
/* a=(ax < cx ? ax : cx); */
/* b=(ax > cx ? ax : cx); */
/* x=w=v=bx; */
/* fw=fv=fx=(*f)(x); */
/* for (iter=1;iter<=ITMAX;iter++) { */
/* xm=0.5*(a+b); */
/* tol2=2.0*(tol1=tol*fabs(x)+ZEPS); */
/* if (fabs(x-xm) <= (tol2-0.5*(b-a))) { */
/* *xmin=x; */
/* return fx; */
/* } */
/* if (fabs(e) > tol1) { */
/* r=(x-w)*(fx-fv); */
/* q=(x-v)*(fx-fw); */
/* p=(x-v)*q-(x-w)*r; */
/* q=2.0*(q-r); */
/* if (q > 0.0) p = -p; */
/* q=fabs(q); */
/* etemp=e; */
/* e=d; */
/* if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x)) */
/* d=CGOLD*(e=(x >= xm ? a-x : b-x)); */
/* else { */
/* d=p/q; */
/* u=x+d; */
/* if (u-a < tol2 || b-u < tol2) */
/* d=SIGN(tol1,xm-x); */
/* } */
/* } else { */
/* d=CGOLD*(e=(x >= xm ? a-x : b-x)); */
/* } */
/* u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d)); */
/* fu=(*f)(u); */
/* if (fu <= fx) { */
/* if (u >= x) a=x; else b=x; */
/* SHFT(v,w,x,u) */
/* SHFT(fv,fw,fx,fu) */
/* } else { */
/* if (u < x) a=u; else b=u; */
/* if (fu <= fw || w == x) { */
/* v=w; */
/* w=u; */
/* fv=fw; */
/* fw=fu; */
/* } else if (fu <= fv || v == x || v == w) { */
/* v=u; */
/* fv=fu; */
/* } */
/* } */
/* } */
/* nrerror("Too many iterations in brent"); */
/* *xmin=x; */
/* return fx; */
/* } */
/* #undef ITMAX */
/* #undef CGOLD */
/* #undef ZEPS */
/* #undef SHFT */
/* #undef NRANSI */
/* #define NRANSI */
/* extern int ncom; */
/* extern double *pcom,*xicom,(*nrfunc)(double []); */
/* double f1dim(double x) */
/* { */
/* int j; */
/* double f,*xt; */
/* xt=vector(1,ncom); */
/* for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j]; */
/* f=(*nrfunc)(xt); */
/* free_vector(xt,1,ncom); */
/* return f; */
/* } */
/* #undef NRANSI */
| {
"alphanum_fraction": 0.4845292956,
"avg_line_length": 21.8561151079,
"ext": "c",
"hexsha": "897b05fa2cd9b733d3b1c0bc6c4f530ac8a8ee4c",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2018-09-15T10:37:33.000Z",
"max_forks_repo_forks_event_min_datetime": "2018-09-15T10:37:33.000Z",
"max_forks_repo_head_hexsha": "59765d9ed9e683731eb8213986c00875b9ceeab0",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "andrewkern/pgLib",
"max_forks_repo_path": "numerical.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "59765d9ed9e683731eb8213986c00875b9ceeab0",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "andrewkern/pgLib",
"max_issues_repo_path": "numerical.c",
"max_line_length": 135,
"max_stars_count": 3,
"max_stars_repo_head_hexsha": "59765d9ed9e683731eb8213986c00875b9ceeab0",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "andrewkern/pgLib",
"max_stars_repo_path": "numerical.c",
"max_stars_repo_stars_event_max_datetime": "2018-09-16T05:43:01.000Z",
"max_stars_repo_stars_event_min_datetime": "2018-09-15T10:37:29.000Z",
"num_tokens": 6323,
"size": 15190
} |
// randomizer.h
// (C) 2013-2020 Nicholas G Davies
#ifndef RANDOMIZER_H
#define RANDOMIZER_H
#include <vector>
#include <limits>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
#include <cmath>
#include <stdexcept>
#include <string>
#include <iostream>
class Randomizer
{
public:
Randomizer(unsigned long int seed = 0);
~Randomizer();
void Reset();
double Uniform(double min = 0.0, double max = 1.0);
double RoundedUniform(double min = 0.0, double max = 1.0, double shoulder = 0.01);
double Normal(double mean = 0.0, double sd = 1.0);
double Normal(double mean, double sd, double clamp);
double Cauchy(double x0 = 0.0, double gamma = 1.0);
double LogNormal(double zeta = 0.0, double sd = 1.0);
double Exponential(double rate = 1.0);
double Gamma(double shape, double scale);
double Beta(double alpha, double beta);
unsigned int Discrete(unsigned int size);
int Discrete(int min, int max);
// int Discrete(std::vector<unsigned int>& cumulative_weights);
// int Discrete(std::vector<double>& cumulative_weights);
void Multinomial(unsigned int N, std::vector<double>& p, std::vector<unsigned int>& n);
bool Bernoulli(double p);
unsigned int Binomial(unsigned int n, double p);
unsigned int BetaBinomial(unsigned int n, double p, double a_plus_b);
int Poisson(double mean);
int Geometric(double p);
int Round(double x);
template <typename T>
void Shuffle(std::vector<T>& vec);
inline gsl_rng* GSL_RNG() { return r; }
private:
unsigned long int seed;
gsl_rng* r;
};
Randomizer::Randomizer(unsigned long int s)
: seed(s), r(gsl_rng_alloc(gsl_rng_mt19937))
{
Reset();
}
Randomizer::~Randomizer()
{
gsl_rng_free(r);
}
void Randomizer::Reset()
{
gsl_rng_set(r, seed);
}
double Randomizer::Uniform(double min, double max)
{
return min + gsl_rng_uniform(r) * (max - min);
}
double Randomizer::RoundedUniform(double min, double max, double shoulder)
{
if (min >= max)
return min;
double z = Uniform();
double sd = shoulder * (max - min) / ((1 - shoulder) * 2.50662827463);
if (z < shoulder / 2)
return min - abs(Normal(0, sd));
else if (z < shoulder)
return max + abs(Normal(0, sd));
else
return Uniform(min, max);
}
double Randomizer::Normal(double mean, double sd)
{
return mean + gsl_ran_gaussian_ziggurat(r, sd);
}
double Randomizer::Normal(double mean, double sd, double clamp)
{
double n;
do n = Normal(mean, sd); while (std::fabs(n - mean) > clamp);
return n;
}
double Randomizer::LogNormal(double zeta, double sd)
{
return gsl_ran_lognormal(r, zeta, sd);
}
double Randomizer::Cauchy(double x0, double gamma)
{
return x0 + gsl_ran_cauchy(r, gamma);
}
double Randomizer::Exponential(double rate)
{
return gsl_ran_exponential(r, 1. / rate);
}
double Randomizer::Gamma(double shape, double scale)
{
return gsl_ran_gamma(r, shape, scale);
}
double Randomizer::Beta(double alpha, double beta)
{
return gsl_ran_beta(r, alpha, beta);
}
unsigned int Randomizer::Discrete(unsigned int size)
{
// TODO improve...
if (size > gsl_rng_max(r))
throw std::runtime_error("Generator cannot produce integers larger than " + std::to_string(gsl_rng_max(r)));
return gsl_rng_get(r) % size;
}
int Randomizer::Discrete(int min, int max)
{
return min + gsl_rng_uniform_int(r, max - min + 1);
}
// ///
// int Randomizer::Discrete(std::vector<unsigned int>& cumulative_weights)
// {
// if (cumulative_weights.back() == 0)
// return Discrete(cumulative_weights.size());
// return std::distance(cumulative_weights.begin(),
// std::lower_bound(cumulative_weights.begin(),
// cumulative_weights.end(),
// Discrete(cumulative_weights.back())));
// }
// ///
// int Randomizer::Discrete(std::vector<double>& cumulative_weights)
// {
// if (cumulative_weights.back() == 0)
// return Discrete(cumulative_weights.size());
// return std::distance(cumulative_weights.begin(),
// std::lower_bound(cumulative_weights.begin(),
// cumulative_weights.end(),
// Uniform(0.0, cumulative_weights.back())));
// }
void Randomizer::Multinomial(unsigned int N, std::vector<double>& p, std::vector<unsigned int>& n)
{
gsl_ran_multinomial(r, p.size(), N, &p[0], &n[0]);
}
bool Randomizer::Bernoulli(double p)
{
if (p <= 0) return false;
if (p >= 1) return true;
return gsl_rng_uniform(r) < p;
}
unsigned int Randomizer::Binomial(unsigned int n, double p)
{
if (p <= 0) return 0;
if (p >= 1) return n;
return gsl_ran_binomial(r, p, n);
}
unsigned int Randomizer::BetaBinomial(unsigned int n, double p, double a_plus_b)
{
if (a_plus_b > 0)
p = gsl_ran_beta(r, a_plus_b * p, a_plus_b * (1 - p));
return gsl_ran_binomial(r, p, n);
}
int Randomizer::Poisson(double mean)
{
if (mean <= 0) return 0;
return gsl_ran_poisson(r, mean);
}
int Randomizer::Geometric(double p)
{
if (p <= 0) return 0;
return gsl_ran_geometric(r, p);
}
int Randomizer::Round(double x)
{
int sign = x < 0 ? -1 : 1;
double intpart, fracpart;
fracpart = std::modf(std::fabs(x), &intpart);
return sign * (intpart + Bernoulli(fracpart));
}
template <typename T>
void Randomizer::Shuffle(std::vector<T>& vec)
{
gsl_ran_shuffle(r, &vec[0], vec.size(), sizeof(vec[0]));
}
#endif | {
"alphanum_fraction": 0.6488160291,
"avg_line_length": 25.6542056075,
"ext": "h",
"hexsha": "a874a8ed7b0a7e54db9d385369607abfa01165cc",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2021-07-15T00:11:25.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-07-15T00:11:25.000Z",
"max_forks_repo_head_hexsha": "149997f77dddfe48906e15c1e4c0dcda976c0a6f",
"max_forks_repo_licenses": [
"CC0-1.0"
],
"max_forks_repo_name": "yangclaraliu/covid_europe_vac_app",
"max_forks_repo_path": "deprecated_4_speed/covidm_for_fitting/randomizer/randomizer.h",
"max_issues_count": 3,
"max_issues_repo_head_hexsha": "149997f77dddfe48906e15c1e4c0dcda976c0a6f",
"max_issues_repo_issues_event_max_datetime": "2020-10-31T10:56:44.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-10-31T08:41:20.000Z",
"max_issues_repo_licenses": [
"CC0-1.0"
],
"max_issues_repo_name": "yangclaraliu/covid_europe_vac_app",
"max_issues_repo_path": "deprecated_4_speed/covidm_for_fitting/randomizer/randomizer.h",
"max_line_length": 116,
"max_stars_count": 6,
"max_stars_repo_head_hexsha": "1119331676dcf397242610a4b1da08582c3e7faf",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "nicholasdavies/covid-tiers",
"max_stars_repo_path": "fitting/covidm_for_fitting/randomizer/randomizer.h",
"max_stars_repo_stars_event_max_datetime": "2021-11-22T07:33:58.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-10-31T22:18:20.000Z",
"num_tokens": 1495,
"size": 5490
} |
/* 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: current_tdel.c
*
* Description: Stationary current as a function of T/D
*
* Version: 1.0
* Created: 10/05/2014 19:52:35
* Revision: none
* License: BSD
*
* Author: Giuseppe Argentieri (ga), giuseppe.argentieri@ts.infn.it
* Organization: Università degli Studi di Trieste
*
*
*/
#include <gsl/gsl_ieee_utils.h>
#include <stdlib.h>
#include <stdio.h>
#include "funcs.h"
#include "initial.h"
/*
* FUNCTION
* Name: current_red_T
* Description: Given the physical parameters and the ratio x = T/Delta,
* determine the generators matrix in Redfield case
* and the stationary current.
*
*/
double current_red_T ( double x, void* params )
{
struct f_params* pars = (struct f_params*) params ;
/* Calculate beta and set into pars */
double Temp = x*D ;
pars->beta = 1.0/Temp ;
/* Calculate the stationary current */
gsl_vector* stat_state = gsl_vector_calloc (4) ;
gsl_matrix* red_m = gsl_matrix_calloc ( 4, 4 ) ;
red_mat ( red_m, pars ) ;
stationary ( red_m, stat_state ) ;
double curr = -VECTOR(stat_state,3)*OMEGA/pars->omega_1 ;
gsl_matrix_free (red_m) ;
return curr ;
} /* ----- end of function current_red_T ----- */
/*
* FUNCTION
* Name: current_cp_T
* Description:
*
*/
double current_cp_T ( double x, void* params )
{
struct f_params* pars = (struct f_params*) params ;
/* Calculate beta and set into pars */
double Temp = x*D ;
pars->beta = 1.0/Temp ;
/* Calculate the stationary current */
gsl_vector* stat_state = gsl_vector_calloc (4) ;
gsl_matrix* cp_m = gsl_matrix_calloc ( 4, 4 ) ;
cp_mat ( cp_m, pars ) ;
stationary ( cp_m, stat_state ) ;
double curr = -VECTOR(stat_state,3)*OMEGA/pars->omega_1 ;
gsl_matrix_free (cp_m) ;
return curr ;
} /* ----- end of function current_cp_T ----- */
/*
* FUNCTION
* Name: write_red_curr_T
* Description:
*
*/
int write_red_curr_T ( void* params )
{
FILE* f = fopen ( "RED-STAT-CURR-T.dat" , "w" ) ;
double x = 0.00 ;
int i ;
for ( i = 0 ; i < 1000 ; i++ )
{
x += 0.001 ;
fprintf ( f, "%.3f %.9f\n", x, current_red_T (x, params) ) ;
}
for ( i = 0 ; i < 900 ; i++ )
{
x += 0.01 ;
fprintf ( f, "%.2f %.9f\n", x, current_red_T (x, params) ) ;
}
for ( i = 0 ; i < 900 ; i++ )
{
x += 0.1 ;
fprintf ( f, "%.1f %.9f\n", x, current_red_T (x, params) ) ;
}
fclose (f) ;
return 0;
} /* ----- end of function write_red_curr_T ----- */
/*
* FUNCTION
* Name: write_cp_curr_T
* Description:
*
*/
int write_cp_curr_T ( void* params )
{
FILE* f = fopen ( "CP-STAT-CURR-T.dat" , "w" ) ;
double x = 0.00 ;
int i ;
for ( i = 0 ; i < 1000 ; i++ )
{
x += 0.001 ;
fprintf ( f, "%.3f %.9f\n", x, current_cp_T (x, params) ) ;
}
for ( i = 0 ; i < 900 ; i++ )
{
x += 0.01 ;
fprintf ( f, "%.2f %.9f\n", x, current_cp_T (x, params) ) ;
}
for ( i = 0 ; i < 900 ; i++ )
{
x += 0.1 ;
fprintf ( f, "%.1f %.9f\n", x, current_cp_T (x, params) ) ;
}
fclose (f) ;
return 0;
} /* ----- end of function write_cp_curr_T ----- */
/*
* FUNCTION
* Name: main
* Description:
*
*/
int main ( int argc, char *argv[] )
{
double omega_1 = gsl_hypot(OMEGA,D) ; /* omega' */
struct f_params params;
params.omega_c = omega_c ;
params.beta = 1 ; /* it will be changed after... */
params.Omega = OMEGA ;
params.omega_1 = omega_1 ;
params.alpha = alpha ;
int status1 = write_red_curr_T ( ¶ms ) ;
int status2 = write_cp_curr_T ( ¶ms ) ;
return status1+status2 ;
} /* ---------- end of function main ---------- */
| {
"alphanum_fraction": 0.6202383278,
"avg_line_length": 24.4928229665,
"ext": "c",
"hexsha": "b35de8408d298ef7ba95298909067078aaa3a24e",
"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": "current_tdel.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": "current_tdel.c",
"max_line_length": 79,
"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": "current_tdel.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1492,
"size": 5119
} |
#include <cblas.h>
#ifdef LAPACKE_FOLDER
#include <lapacke/lapacke.h>
#else
#include <lapacke.h>
#endif
#include "math.h"
#include "minimal_opencv.h"
#include "stdbool.h"
#include "stdio.h"
#include "string.h"
#include <limits.h>
#include <stdarg.h>
#include "linmath.h"
#ifdef _WIN32
#define SURVIVE_LOCAL_ONLY
#include <malloc.h>
#define alloca _alloca
#else
#define SURVIVE_LOCAL_ONLY __attribute__((visibility("hidden")))
#endif
SURVIVE_LOCAL_ONLY int cvRound(float f) { return roundf(f); }
#define CV_Error(code, msg) assert(0 && msg); // cv::error( code, msg, CV_Func, __FILE__, __LINE__ )
const int DECOMP_SVD = 1;
const int DECOMP_LU = 2;
void print_mat(const CvMat *M);
static size_t mat_size_bytes(const CvMat *mat) { return (size_t)CV_ELEM_SIZE(mat->type) * mat->cols * mat->rows; }
SURVIVE_LOCAL_ONLY void cvCopy(const CvMat *srcarr, CvMat *dstarr, const CvMat *mask) {
assert(mask == 0 && "This isn't implemented yet");
assert(srcarr->rows == dstarr->rows);
assert(srcarr->cols == dstarr->cols);
assert(dstarr->type == srcarr->type);
memcpy(CV_RAW_PTR(dstarr), CV_RAW_PTR(srcarr), mat_size_bytes(srcarr));
}
#ifdef USE_FLOAT
#define cblas_gemm cblas_sgemm
#define cblas_symm cblas_ssymm
#define LAPACKE_getrs LAPACKE_sgetrs
#define LAPACKE_getrf LAPACKE_sgetrf
#define LAPACKE_getri LAPACKE_sgetri
#define LAPACKE_gelss LAPACKE_sgelss
#define LAPACKE_gesvd LAPACKE_sgesvd
#else
#define cblas_gemm cblas_dgemm
#define cblas_symm cblas_dsymm
#define LAPACKE_getrs LAPACKE_dgetrs
#define LAPACKE_getrf LAPACKE_dgetrf
#define LAPACKE_getri LAPACKE_dgetri
#define LAPACKE_gelss LAPACKE_dgelss
#define LAPACKE_gesvd LAPACKE_dgesvd
#endif
// dst = alpha * src1 * src2 + beta * src3 or dst = alpha * src2 * src1 + beta * src3 where src1 is symm
SURVIVE_LOCAL_ONLY void cvSYMM(const CvMat *src1, const CvMat *src2, double alpha, const CvMat *src3, double beta,
CvMat *dst, bool src1First) {
int rows1 = src1->rows;
int cols1 = src1->cols;
int rows2 = src2->rows;
int cols2 = src2->cols;
if (src3) {
int rows3 = src3->rows;
int cols3 = src3->cols;
assert(rows3 == dst->rows);
assert(cols3 == dst->cols);
}
// assert(src3 == 0 || beta != 0);
assert(cols1 == rows2);
assert(rows1 == dst->rows);
assert(cols2 == dst->cols);
lapack_int lda = src1->cols;
lapack_int ldb = src2->cols;
if (src3)
cvCopy(src3, dst, 0);
else
beta = 0;
assert(CV_RAW_PTR(dst) != CV_RAW_PTR(src1));
assert(CV_RAW_PTR(dst) != CV_RAW_PTR(src2));
/*
void cblas_dsymm(OPENBLAS_CONST enum CBLAS_ORDER Order,
OPENBLAS_CONST enum CBLAS_SIDE Side,
OPENBLAS_CONST enum CBLAS_UPLO Uplo,
OPENBLAS_CONST blasint M,
OPENBLAS_CONST blasint N,
OPENBLAS_CONST double alpha,
OPENBLAS_CONST double *A,
OPENBLAS_CONST blasint lda,
OPENBLAS_CONST double *B,
OPENBLAS_CONST blasint ldb,
OPENBLAS_CONST double beta,
double *C,
OPENBLAS_CONST blasint ldc);
*/
cblas_symm(CblasRowMajor, src1First ? CblasLeft : CblasRight, CblasUpper, dst->rows, dst->cols, alpha,
CV_RAW_PTR(src1), lda, CV_RAW_PTR(src2), ldb, beta, CV_RAW_PTR(dst), dst->cols);
}
// Special case dst = alpha * src2 * src1 * src2' + beta * src3
void mulBABt(const CvMat *src1, const CvMat *src2, double alpha, const CvMat *src3, double beta, CvMat *dst) {
size_t dims = src2->rows;
assert(src2->cols == src2->rows);
CREATE_STACK_MAT(tmp, dims, dims);
// This has been profiled; and weirdly enough the SYMM version is slower for a 19x19 matrix. Guessing access order
// or some other cache thing matters more than the additional 2x multiplications.
//#define USE_SYM
#ifdef USE_SYM
cvSYMM(src1, src2, 1, 0, 0, &tmp, false);
cvGEMM(&tmp, src2, alpha, src3, beta, dst, CV_GEMM_B_T);
#else
cvGEMM(src1, src2, 1, 0, 0, &tmp, CV_GEMM_B_T);
cvGEMM(src2, &tmp, alpha, src3, beta, dst, 0);
#endif
}
// dst = alpha * src1 * src2 + beta * src3
SURVIVE_LOCAL_ONLY void cvGEMM(const CvMat *src1, const CvMat *src2, double alpha, const CvMat *src3, double beta,
CvMat *dst, int tABC) {
int rows1 = (tABC & CV_GEMM_A_T) ? src1->cols : src1->rows;
int cols1 = (tABC & CV_GEMM_A_T) ? src1->rows : src1->cols;
int rows2 = (tABC & CV_GEMM_B_T) ? src2->cols : src2->rows;
int cols2 = (tABC & CV_GEMM_B_T) ? src2->rows : src2->cols;
if (src3) {
int rows3 = (tABC & CV_GEMM_C_T) ? src3->cols : src3->rows;
int cols3 = (tABC & CV_GEMM_C_T) ? src3->rows : src3->cols;
assert(rows3 == dst->rows);
assert(cols3 == dst->cols);
}
// assert(src3 == 0 || beta != 0);
assert(cols1 == rows2);
assert(rows1 == dst->rows);
assert(cols2 == dst->cols);
lapack_int lda = src1->cols;
lapack_int ldb = src2->cols;
if (src3)
cvCopy(src3, dst, 0);
else
beta = 0;
assert(CV_RAW_PTR(dst) != CV_RAW_PTR(src1));
assert(CV_RAW_PTR(dst) != CV_RAW_PTR(src2));
cblas_gemm(CblasRowMajor, (tABC & CV_GEMM_A_T) ? CblasTrans : CblasNoTrans,
(tABC & CV_GEMM_B_T) ? CblasTrans : CblasNoTrans, dst->rows, dst->cols, cols1, alpha, CV_RAW_PTR(src1),
lda, CV_RAW_PTR(src2), ldb, beta, CV_RAW_PTR(dst), dst->cols);
}
// dst = scale * src ^ t * src iff order == 1
// dst = scale * src * src ^ t iff order == 0
SURVIVE_LOCAL_ONLY void cvMulTransposed(const CvMat *src, CvMat *dst, int order, const CvMat *delta, double scale) {
lapack_int rows = src->rows;
lapack_int cols = src->cols;
lapack_int drows = order == 0 ? dst->rows : dst->cols;
assert(drows == dst->cols);
assert(order == 1 ? (dst->cols == src->cols) : (dst->cols == src->rows));
assert(delta == 0 && "This isn't implemented yet");
double beta = 0;
bool isAT = order == 1;
bool isBT = !isAT;
lapack_int dstCols = dst->cols;
cblas_gemm(CblasRowMajor, isAT ? CblasTrans : CblasNoTrans, isBT ? CblasTrans : CblasNoTrans, dst->rows, dst->cols,
order == 1 ? src->rows : src->cols, scale, CV_RAW_PTR(src), src->cols, CV_RAW_PTR(src), src->cols, beta,
CV_RAW_PTR(dst), dstCols);
}
SURVIVE_LOCAL_ONLY void *cvAlloc(size_t size) { return malloc(size); }
static void icvCheckHuge(CvMat *arr) {
if ((int64_t)arr->step * arr->rows > INT_MAX)
arr->type &= ~CV_MAT_CONT_FLAG;
}
static CvMat *cvInitMatHeader(CvMat *arr, int rows, int cols, int type) {
type = CV_MAT_TYPE(type);
assert(!(rows < 0 || cols < 0));
int min_step = CV_ELEM_SIZE(type);
assert(!(min_step <= 0));
min_step *= cols;
arr->step = min_step;
arr->type = CV_MAT_MAGIC_VAL | type | CV_MAT_CONT_FLAG;
arr->rows = rows;
arr->cols = cols;
arr->data.ptr = 0;
arr->refcount = 0;
arr->hdr_refcount = 1;
icvCheckHuge(arr);
return arr;
}
SURVIVE_LOCAL_ONLY CvMat *cvCreateMatHeader(int rows, int cols, int type) {
return cvInitMatHeader((CvMat *)cvAlloc(sizeof(CvMat)), rows, cols, type);
}
/* the alignment of all the allocated buffers */
#define CV_MALLOC_ALIGN 16
/* IEEE754 constants and macros */
#define CV_TOGGLE_FLT(x) ((x) ^ ((int)(x) < 0 ? 0x7fffffff : 0))
#define CV_TOGGLE_DBL(x) ((x) ^ ((int64)(x) < 0 ? CV_BIG_INT(0x7fffffffffffffff) : 0))
#define CV_DbgAssert assert
static inline void *cvAlignPtr(const void *ptr, int align) {
CV_DbgAssert((align & (align - 1)) == 0);
return (void *)(((size_t)ptr + align - 1) & ~(size_t)(align - 1));
}
SURVIVE_LOCAL_ONLY void cvCreateData(CvMat *arr) {
if (CV_IS_MAT_HDR_Z(arr)) {
size_t step, total_size;
CvMat *mat = (CvMat *)arr;
step = mat->step;
if (mat->rows == 0 || mat->cols == 0)
return;
if (mat->data.ptr != 0)
CV_Error(CV_StsError, "Data is already allocated");
if (step == 0)
step = CV_ELEM_SIZE(mat->type) * mat->cols;
int64_t _total_size = (int64_t)step * mat->rows + sizeof(int) + CV_MALLOC_ALIGN;
total_size = (size_t)_total_size;
if (_total_size != (int64_t)total_size)
CV_Error(CV_StsNoMem, "Too big buffer is allocated");
mat->refcount = (int *)cvAlloc((size_t)total_size);
mat->data.ptr = (uchar *)cvAlignPtr(mat->refcount + 1, CV_MALLOC_ALIGN);
*mat->refcount = 1;
} else if (CV_IS_MATND_HDR(arr)) {
assert("There is no support for ND types");
} else
CV_Error(CV_StsBadArg, "unrecognized or unsupported array type");
}
#define CV_CREATE_MAT_HEADER_ALLOCA(stack_mat, rows, cols, type) \
CvMat *stack_mat = cvInitMatHeader(alloca(sizeof(CvMat)), rows, cols, type);
#define CV_CREATE_MAT_ALLOCA(stack_mat, height, width, type) \
CV_CREATE_MAT_HEADER_ALLOCA(stack_mat, height, width, type); \
stack_mat->data.ptr = alloca(mat_size_bytes(stack_mat));
SURVIVE_LOCAL_ONLY CvMat *cvCreateMat(int height, int width, int type) {
CvMat *arr = cvCreateMatHeader(height, width, type);
cvCreateData(arr);
return arr;
}
#define CREATE_CV_STACK_MAT(name, rows, cols, type) \
FLT *_##name = alloca(rows * cols * sizeof(FLT)); \
CvMat name = cvMat(rows, cols, SURVIVE_CV_F, _##name);
SURVIVE_LOCAL_ONLY double cvInvert(const CvMat *srcarr, CvMat *dstarr, int method) {
lapack_int inf;
lapack_int rows = srcarr->rows;
lapack_int cols = srcarr->cols;
lapack_int lda = srcarr->cols;
cvCopy(srcarr, dstarr, 0);
FLT *a = CV_RAW_PTR(dstarr);
#ifdef DEBUG_PRINT
printf("a: \n");
print_mat(srcarr);
#endif
if (method == DECOMP_LU) {
lapack_int *ipiv = alloca(sizeof(lapack_int) * MIN(srcarr->rows, srcarr->cols));
inf = LAPACKE_getrf(LAPACK_ROW_MAJOR, rows, cols, a, lda, ipiv);
assert(inf == 0);
inf = LAPACKE_getri(LAPACK_ROW_MAJOR, rows, a, lda, ipiv);
assert(inf >= 0);
if (inf > 0) {
printf("Warning: Singular matrix: \n");
// print_mat(srcarr);
}
//free(ipiv);
} else if (method == DECOMP_SVD) {
// TODO: There is no way this needs this many allocations,
// but in my defense I was very tired when I wrote this code
CREATE_CV_STACK_MAT(w, 1, MIN(dstarr->rows, dstarr->cols), dstarr->type);
CREATE_CV_STACK_MAT(u, dstarr->cols, dstarr->cols, dstarr->type);
CREATE_CV_STACK_MAT(v, dstarr->rows, dstarr->rows, dstarr->type);
CREATE_CV_STACK_MAT(um, w.cols, w.cols, w.type);
cvSVD(dstarr, &w, &u, &v, 0);
cvSetZero(&um);
for (int i = 0; i < w.cols; i++) {
cvmSet(&um, i, i, 1. / (_w)[i]);
}
CvMat *tmp = cvCreateMat(dstarr->cols, dstarr->rows, dstarr->type);
cvGEMM(&v, &um, 1, 0, 0, tmp, CV_GEMM_A_T);
cvGEMM(tmp, &u, 1, 0, 0, dstarr, CV_GEMM_B_T);
cvReleaseMat(&tmp);
} else {
assert(0 && "Bad argument");
return -1;
}
return 0;
}
#define CV_CLONE_MAT_ALLOCA(stack_mat, mat) \
CV_CREATE_MAT_ALLOCA(stack_mat, mat->rows, mat->cols, mat->type) \
cvCopy(mat, stack_mat, 0);
SURVIVE_LOCAL_ONLY CvMat *cvCloneMat(const CvMat *mat) {
CvMat *rtn = cvCreateMat(mat->rows, mat->cols, mat->type);
cvCopy(mat, rtn, 0);
return rtn;
}
SURVIVE_LOCAL_ONLY int cvSolve(const CvMat *Aarr, const CvMat *xarr, CvMat *Barr, int method) {
lapack_int inf;
lapack_int arows = Aarr->rows;
lapack_int acols = Aarr->cols;
lapack_int xcols = xarr->cols;
lapack_int xrows = xarr->rows;
lapack_int lda = acols; // Aarr->step / sizeof(double);
lapack_int type = CV_MAT_TYPE(Aarr->type);
if (method == DECOMP_LU) {
assert(Aarr->cols == Barr->rows);
assert(xarr->rows == Aarr->rows);
assert(Barr->cols == xarr->cols);
assert(type == CV_MAT_TYPE(Barr->type) && (type == CV_32F || type == CV_64F));
cvCopy(xarr, Barr, 0);
FLT *a_ws = alloca(mat_size_bytes(Aarr));
memcpy(a_ws, CV_RAW_PTR(Aarr), mat_size_bytes(Aarr));
lapack_int brows = Barr->rows;
lapack_int bcols = Barr->cols;
lapack_int ldb = bcols; // Barr->step / sizeof(double);
lapack_int *ipiv = alloca(sizeof(lapack_int) * MIN(Aarr->rows, Aarr->cols));
inf = LAPACKE_getrf(LAPACK_ROW_MAJOR, arows, acols, (a_ws), lda, ipiv);
assert(inf >= 0);
if (inf > 0) {
printf("Warning: Singular matrix: \n");
// print_mat(a_ws);
}
#ifdef DEBUG_PRINT
printf("Solve A * x = B:\n");
// print_mat(a_ws);
print_mat(Barr);
#endif
inf = LAPACKE_getrs(LAPACK_ROW_MAJOR, CblasNoTrans, arows, bcols, (a_ws), lda, ipiv, CV_RAW_PTR(Barr), ldb);
assert(inf == 0);
//free(ipiv);
// cvReleaseMat(&a_ws);
} else if (method == DECOMP_SVD) {
#ifdef DEBUG_PRINT
printf("Solve |b - A * x|:\n");
print_mat(Aarr);
print_mat(xarr);
#endif
bool xLargerThanB = xarr->rows > acols;
CvMat *xCpy = 0;
if (xLargerThanB) {
CV_CLONE_MAT_ALLOCA(xCpyStack, xarr);
xCpy = xCpyStack;
} else {
xCpy = Barr;
memcpy(CV_RAW_PTR(Barr), CV_RAW_PTR(xarr), mat_size_bytes(xarr));
}
// CvMat *aCpy = cvCloneMat(Aarr);
FLT *aCpy = alloca(mat_size_bytes(Aarr));
memcpy(aCpy, CV_RAW_PTR(Aarr), mat_size_bytes(Aarr));
FLT *S = alloca(sizeof(FLT) * MIN(arows, acols));
// FLT *S = malloc(sizeof(FLT) * MIN(arows, acols));
FLT rcond = -1;
lapack_int *rank = alloca(sizeof(lapack_int) * MIN(arows, acols));
// lapack_int *rank = malloc(sizeof(lapack_int) * MIN(arows, acols));
lapack_int inf = LAPACKE_gelss(LAPACK_ROW_MAJOR, arows, acols, xcols, (aCpy), acols, CV_RAW_PTR(xCpy), xcols, S,
rcond, rank);
assert(Barr->rows == acols);
assert(Barr->cols == xCpy->cols);
if (xLargerThanB) {
xCpy->rows = acols;
cvCopy(xCpy, Barr, 0);
// cvReleaseMat(&xCpy);
}
// cvReleaseMat(&aCpy);
#ifdef DEBUG_PRINT
print_mat(Barr);
#endif
assert(inf == 0);
}
return 0;
}
SURVIVE_LOCAL_ONLY void cvTranspose(const CvMat *M, CvMat *dst) {
bool inPlace = M == dst || CV_RAW_PTR(M) == CV_RAW_PTR(dst);
FLT *src = CV_RAW_PTR(M);
if (inPlace) {
src = alloca(mat_size_bytes(M));
memcpy(src, CV_RAW_PTR(M), mat_size_bytes(M));
} else {
assert(M->rows == dst->cols);
assert(M->cols == dst->rows);
}
for (unsigned i = 0; i < M->rows; i++) {
for (unsigned j = 0; j < M->cols; j++) {
CV_RAW_PTR(dst)[j * M->rows + i] = src[i * M->cols + j];
}
}
}
SURVIVE_LOCAL_ONLY void cvSVD(CvMat *aarr, CvMat *warr, CvMat *uarr, CvMat *varr, int flags) {
char jobu = 'A';
char jobvt = 'A';
lapack_int inf;
if ((flags & CV_SVD_MODIFY_A) == 0) {
aarr = cvCloneMat(aarr);
}
if (uarr == 0)
jobu = 'N';
if (varr == 0)
jobvt = 'N';
FLT *pw, *pu, *pv;
lapack_int arows = aarr->rows, acols = aarr->cols;
pw = warr ? CV_RAW_PTR(warr) : (FLT *)alloca(sizeof(FLT) * arows * acols);
pu = uarr ? CV_RAW_PTR(uarr) : (FLT *)alloca(sizeof(FLT) * arows * arows);
pv = varr ? CV_RAW_PTR(varr) : (FLT *)alloca(sizeof(FLT) * acols * acols);
lapack_int ulda = uarr ? uarr->cols : acols;
lapack_int plda = varr ? varr->cols : acols;
FLT *superb = alloca(sizeof(FLT) * MIN(arows, acols));
inf = LAPACKE_gesvd(LAPACK_ROW_MAJOR, jobu, jobvt, arows, acols, CV_RAW_PTR(aarr), acols, pw, pu, ulda, pv, plda,
superb);
// free(superb);
switch (inf) {
case -6:
assert(false && "matrix has NaNs");
break;
case 0:
break;
default:
assert(inf == 0);
}
if (uarr && (flags & CV_SVD_U_T)) {
cvTranspose(uarr, uarr);
}
if (varr && (flags & CV_SVD_V_T) == 0) {
cvTranspose(varr, varr);
}
if ((flags & CV_SVD_MODIFY_A) == 0) {
cvReleaseMat(&aarr);
}
}
SURVIVE_LOCAL_ONLY void cvSetZero(CvMat *arr) {
for (int i = 0; i < arr->rows; i++)
for (int j = 0; j < arr->cols; j++)
CV_RAW_PTR(arr)[i * arr->cols + j] = 0;
}
SURVIVE_LOCAL_ONLY void cvSetIdentity(CvMat *arr) {
for (int i = 0; i < arr->rows; i++)
for (int j = 0; j < arr->cols; j++)
CV_RAW_PTR(arr)[i * arr->cols + j] = i == j;
}
SURVIVE_LOCAL_ONLY void cvReleaseMat(CvMat **mat) {
assert(*(*mat)->refcount == 1);
free((*mat)->refcount);
free(*mat);
*mat = 0;
}
SURVIVE_LOCAL_ONLY double cvDet(const CvMat *M) {
assert(M->rows == M->cols);
assert(M->rows <= 3 && "cvDet unimplemented for matrices >3");
FLT *m = CV_RAW_PTR(M);
switch (M->rows) {
case 1:
return m[0];
case 2: {
return m[0] * m[3] - m[1] * m[2];
}
case 3: {
FLT m00 = m[0], m01 = m[1], m02 = m[2], m10 = m[3], m11 = m[4], m12 = m[5], m20 = m[6], m21 = m[7], m22 = m[8];
return m00 * (m11 * m22 - m12 * m21) - m01 * (m10 * m22 - m12 * m20) + m02 * (m10 * m21 - m11 * m20);
}
default:
abort();
}
}
| {
"alphanum_fraction": 0.6511296812,
"avg_line_length": 29.4262295082,
"ext": "c",
"hexsha": "fcabb47d269a8e7fd67cc3c9d5b898bd8f731ab0",
"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": "b966a6c0942889f7a4d6a34dd21488bb9a06ffc6",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "tiiuae/libsurvive",
"max_forks_repo_path": "redist/minimal_opencv.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "b966a6c0942889f7a4d6a34dd21488bb9a06ffc6",
"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": "tiiuae/libsurvive",
"max_issues_repo_path": "redist/minimal_opencv.c",
"max_line_length": 120,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "b966a6c0942889f7a4d6a34dd21488bb9a06ffc6",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "tiiuae/libsurvive",
"max_stars_repo_path": "redist/minimal_opencv.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 5517,
"size": 16155
} |
/*
* 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.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.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 <math.h>
#include <cblas.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include "PHY/TOOLS/defs.h"
#include "defs.h"
// NEW code with lookup table for sin/cos based on delay profile (TO BE TESTED)
double **cos_lut=NULL,**sin_lut=NULL;
//#if 1
int init_freq_channel(channel_desc_t *desc,uint16_t nb_rb,int16_t n_samples)
{
double delta_f,freq; // 90 kHz spacing
double delay;
int16_t f;
uint8_t l;
if ((n_samples&1)==0) {
fprintf(stderr, "freq_channel_init: n_samples has to be odd\n");
return(-1);
}
cos_lut = (double **)malloc(n_samples*sizeof(double*));
sin_lut = (double **)malloc(n_samples*sizeof(double*));
delta_f = nb_rb*180000/(n_samples-1);
for (f=-(n_samples>>1); f<=(n_samples>>1); f++) {
freq=delta_f*(double)f*1e-6;// due to the fact that delays is in mus
cos_lut[f+(n_samples>>1)] = (double *)malloc((int)desc->nb_taps*sizeof(double));
sin_lut[f+(n_samples>>1)] = (double *)malloc((int)desc->nb_taps*sizeof(double));
for (l=0; l<(int)desc->nb_taps; l++) {
if (desc->nb_taps==1)
delay = desc->delays[l];
else
delay = desc->delays[l]+NB_SAMPLES_CHANNEL_OFFSET/desc->sampling_rate;
cos_lut[f+(n_samples>>1)][l] = cos(2*M_PI*freq*delay);
sin_lut[f+(n_samples>>1)][l] = sin(2*M_PI*freq*delay);
//printf("values cos:%d, sin:%d\n", cos_lut[f][l], sin_lut[f][l]);
}
}
return(0);
}
int freq_channel(channel_desc_t *desc,uint16_t nb_rb,int16_t n_samples)
{
int16_t f,f2,d;
uint8_t aarx,aatx,l;
double *clut,*slut;
static int freq_channel_init=0;
static int n_samples_max=0;
// do some error checking
// n_samples has to be a odd number because we assume the spectrum is symmetric around the DC and includes the DC
if ((n_samples&1)==0) {
fprintf(stderr, "freq_channel: n_samples has to be odd\n");
return(-1);
}
// printf("no of taps:%d,",(int)desc->nb_taps);
if (freq_channel_init == 0) {
// we are initializing the lut for the largets possible n_samples=12*nb_rb+1
// if called with n_samples<12*nb_rb+1, we decimate the lut
n_samples_max=12*nb_rb+1;
if (init_freq_channel(desc,nb_rb,n_samples_max)==0)
freq_channel_init=1;
else
return(-1);
}
d=(n_samples_max-1)/(n_samples-1);
//printf("no_samples=%d, n_samples_max=%d, d=%d\n",n_samples,n_samples_max,d);
start_meas(&desc->interp_freq);
for (f=-n_samples_max/2,f2=-n_samples/2; f<n_samples_max/2; f+=d,f2++) {
clut = cos_lut[n_samples_max/2+f];
slut = sin_lut[n_samples_max/2+f];
for (aarx=0; aarx<desc->nb_rx; aarx++) {
for (aatx=0; aatx<desc->nb_tx; aatx++) {
desc->chF[aarx+(aatx*desc->nb_rx)][n_samples/2+f2].x=0.0;
desc->chF[aarx+(aatx*desc->nb_rx)][n_samples/2+f2].y=0.0;
for (l=0; l<(int)desc->nb_taps; l++) {
desc->chF[aarx+(aatx*desc->nb_rx)][n_samples/2+f2].x+=(desc->a[l][aarx+(aatx*desc->nb_rx)].x*clut[l]+
desc->a[l][aarx+(aatx*desc->nb_rx)].y*slut[l]);
desc->chF[aarx+(aatx*desc->nb_rx)][n_samples/2+f2].y+=(-desc->a[l][aarx+(aatx*desc->nb_rx)].x*slut[l]+
desc->a[l][aarx+(aatx*desc->nb_rx)].y*clut[l]);
}
}
}
}
stop_meas(&desc->interp_freq);
return(0);
}
double compute_pbch_sinr(channel_desc_t *desc,
channel_desc_t *desc_i1,
channel_desc_t *desc_i2,
double snr_dB,double snr_i1_dB,
double snr_i2_dB,
uint16_t nb_rb)
{
double avg_sinr,snr=pow(10.0,.1*snr_dB),snr_i1=pow(10.0,.1*snr_i1_dB),snr_i2=pow(10.0,.1*snr_i2_dB);
uint16_t f;
uint8_t aarx,aatx;
double S;
struct complex S_i1;
struct complex S_i2;
avg_sinr=0.0;
// printf("nb_rb %d\n",nb_rb);
for (f=(nb_rb-6); f<(nb_rb+6); f++) {
S = 0.0;
S_i1.x =0.0;
S_i1.y =0.0;
S_i2.x =0.0;
S_i2.y =0.0;
for (aarx=0; aarx<desc->nb_rx; aarx++) {
for (aatx=0; aatx<desc->nb_tx; aatx++) {
S += (desc->chF[aarx+(aatx*desc->nb_rx)][f].x*desc->chF[aarx+(aatx*desc->nb_rx)][f].x +
desc->chF[aarx+(aatx*desc->nb_rx)][f].y*desc->chF[aarx+(aatx*desc->nb_rx)][f].y);
// printf("%d %d chF[%d] => (%f,%f)\n",aarx,aatx,f,desc->chF[aarx+(aatx*desc->nb_rx)][f].x,desc->chF[aarx+(aatx*desc->nb_rx)][f].y);
if (desc_i1) {
S_i1.x += (desc->chF[aarx+(aatx*desc->nb_rx)][f].x*desc_i1->chF[aarx+(aatx*desc->nb_rx)][f].x +
desc->chF[aarx+(aatx*desc->nb_rx)][f].y*desc_i1->chF[aarx+(aatx*desc->nb_rx)][f].y);
S_i1.y += (desc->chF[aarx+(aatx*desc->nb_rx)][f].x*desc_i1->chF[aarx+(aatx*desc->nb_rx)][f].y -
desc->chF[aarx+(aatx*desc->nb_rx)][f].y*desc_i1->chF[aarx+(aatx*desc->nb_rx)][f].x);
}
if (desc_i2) {
S_i2.x += (desc->chF[aarx+(aatx*desc->nb_rx)][f].x*desc_i2->chF[aarx+(aatx*desc->nb_rx)][f].x +
desc->chF[aarx+(aatx*desc->nb_rx)][f].y*desc_i2->chF[aarx+(aatx*desc->nb_rx)][f].y);
S_i2.y += (desc->chF[aarx+(aatx*desc->nb_rx)][f].x*desc_i2->chF[aarx+(aatx*desc->nb_rx)][f].y -
desc->chF[aarx+(aatx*desc->nb_rx)][f].y*desc_i2->chF[aarx+(aatx*desc->nb_rx)][f].x);
}
}
}
// printf("snr %f f %d : S %f, S_i1 %f, S_i2 %f\n",snr,f-nb_rb,S,snr_i1*sqrt(S_i1.x*S_i1.x + S_i1.y*S_i1.y),snr_i2*sqrt(S_i2.x*S_i2.x + S_i2.y*S_i2.y));
avg_sinr += (snr*S/(desc->nb_tx+snr_i1*sqrt(S_i1.x*S_i1.x + S_i1.y*S_i1.y)+snr_i2*sqrt(S_i2.x*S_i2.x + S_i2.y*S_i2.y)));
}
// printf("avg_sinr %f (%f,%f,%f)\n",avg_sinr/12.0,snr,snr_i1,snr_i2);
return(10*log10(avg_sinr/12.0));
}
double compute_sinr(channel_desc_t *desc,
channel_desc_t *desc_i1,
channel_desc_t *desc_i2,
double snr_dB,double snr_i1_dB,
double snr_i2_dB,
uint16_t nb_rb)
{
double avg_sinr,snr=pow(10.0,.1*snr_dB),snr_i1=pow(10.0,.1*snr_i1_dB),snr_i2=pow(10.0,.1*snr_i2_dB);
uint16_t f;
uint8_t aarx,aatx;
double S;
struct complex S_i1;
struct complex S_i2;
DevAssert( nb_rb > 0 );
avg_sinr=0.0;
// printf("nb_rb %d\n",nb_rb);
for (f=0; f<2*nb_rb; f++) {
S = 0.0;
S_i1.x =0.0;
S_i1.y =0.0;
S_i2.x =0.0;
S_i2.y =0.0;
for (aarx=0; aarx<desc->nb_rx; aarx++) {
for (aatx=0; aatx<desc->nb_tx; aatx++) {
S += (desc->chF[aarx+(aatx*desc->nb_rx)][f].x*desc->chF[aarx+(aatx*desc->nb_rx)][f].x +
desc->chF[aarx+(aatx*desc->nb_rx)][f].y*desc->chF[aarx+(aatx*desc->nb_rx)][f].y);
if (desc_i1) {
S_i1.x += (desc->chF[aarx+(aatx*desc->nb_rx)][f].x*desc_i1->chF[aarx+(aatx*desc->nb_rx)][f].x +
desc->chF[aarx+(aatx*desc->nb_rx)][f].y*desc_i1->chF[aarx+(aatx*desc->nb_rx)][f].y);
S_i1.y += (desc->chF[aarx+(aatx*desc->nb_rx)][f].x*desc_i1->chF[aarx+(aatx*desc->nb_rx)][f].y -
desc->chF[aarx+(aatx*desc->nb_rx)][f].y*desc_i1->chF[aarx+(aatx*desc->nb_rx)][f].x);
}
if (desc_i2) {
S_i2.x += (desc->chF[aarx+(aatx*desc->nb_rx)][f].x*desc_i2->chF[aarx+(aatx*desc->nb_rx)][f].x +
desc->chF[aarx+(aatx*desc->nb_rx)][f].y*desc_i2->chF[aarx+(aatx*desc->nb_rx)][f].y);
S_i2.y += (desc->chF[aarx+(aatx*desc->nb_rx)][f].x*desc_i2->chF[aarx+(aatx*desc->nb_rx)][f].y -
desc->chF[aarx+(aatx*desc->nb_rx)][f].y*desc_i2->chF[aarx+(aatx*desc->nb_rx)][f].x);
}
}
}
// printf("f %d : S %f, S_i1 %f, S_i2 %f\n",f-nb_rb,snr*S,snr_i1*sqrt(S_i1.x*S_i1.x + S_i1.y*S_i1.y),snr_i2*sqrt(S_i2.x*S_i2.x + S_i2.y*S_i2.y));
avg_sinr += (snr*S/(desc->nb_tx+snr_i1*sqrt(S_i1.x*S_i1.x + S_i1.y*S_i1.y)+snr_i2*sqrt(S_i2.x*S_i2.x + S_i2.y*S_i2.y)));
}
// printf("avg_sinr %f (%f,%f,%f)\n",avg_sinr/12.0,snr,snr_i1,snr_i2);
return(10*log10(avg_sinr/(nb_rb*2)));
}
int pbch_polynomial_degree=6;
double pbch_awgn_polynomial[7]= {-7.2926e-05, -2.8749e-03, -4.5064e-02, -3.5301e-01, -1.4655e+00, -3.6282e+00, -6.6907e+00};
void load_pbch_desc(FILE *pbch_file_fd)
{
int i, ret;
char dummy[25];
ret = fscanf(pbch_file_fd,"%d",&pbch_polynomial_degree);
if (ret < 0) {
printf("fscanf failed: %s\n", strerror(errno));
exit(EXIT_FAILURE);
}
if (pbch_polynomial_degree>6) {
printf("Illegal degree for pbch interpolation polynomial %d\n",pbch_polynomial_degree);
exit(-1);
}
printf("PBCH polynomial : ");
for (i=0; i<=pbch_polynomial_degree; i++) {
ret = fscanf(pbch_file_fd,"%s",dummy);
if (ret < 0) {
printf("fscanf failed: %s\n", strerror(errno));
exit(EXIT_FAILURE);
}
pbch_awgn_polynomial[i] = strtod(dummy,NULL);
printf("%f ",pbch_awgn_polynomial[i]);
}
printf("\n");
}
double pbch_bler(double sinr)
{
int i;
double log10_bler=pbch_awgn_polynomial[pbch_polynomial_degree];
double sinrpow=sinr;
double bler=0.0;
// printf("log10bler %f\n",log10_bler);
if (sinr<-10.0)
bler= 1.0;
else if (sinr>=0.0)
bler=0.0;
else {
for (i=1; i<=pbch_polynomial_degree; i++) {
// printf("sinrpow %f\n",sinrpow);
log10_bler += (pbch_awgn_polynomial[pbch_polynomial_degree-i]*sinrpow);
sinrpow *= sinr;
// printf("log10bler %f\n",log10_bler);
}
bler = pow(10.0,log10_bler);
}
//printf ("sinr %f bler %f\n",sinr,bler);
return(bler);
}
| {
"alphanum_fraction": 0.5977055087,
"avg_line_length": 32.7546583851,
"ext": "c",
"hexsha": "88b3ce6406bfbf72272d75f155f69edefb1704b4",
"lang": "C",
"max_forks_count": 5,
"max_forks_repo_forks_event_max_datetime": "2022-01-05T03:52:29.000Z",
"max_forks_repo_forks_event_min_datetime": "2019-02-14T16:06:26.000Z",
"max_forks_repo_head_hexsha": "45212d3b2fd22fdeec8e0062844eaff8de3039a0",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "shahab1992/OAI",
"max_forks_repo_path": "openair1/SIMULATION/TOOLS/abstraction.c",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "45212d3b2fd22fdeec8e0062844eaff8de3039a0",
"max_issues_repo_issues_event_max_datetime": "2021-05-28T14:49:39.000Z",
"max_issues_repo_issues_event_min_datetime": "2021-05-28T09:06:21.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "shahab1992/OAI",
"max_issues_repo_path": "openair1/SIMULATION/TOOLS/abstraction.c",
"max_line_length": 159,
"max_stars_count": 2,
"max_stars_repo_head_hexsha": "45212d3b2fd22fdeec8e0062844eaff8de3039a0",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "t0930198/OAI_nb_IoT",
"max_stars_repo_path": "openair1/SIMULATION/TOOLS/abstraction.c",
"max_stars_repo_stars_event_max_datetime": "2019-04-07T13:56:25.000Z",
"max_stars_repo_stars_event_min_datetime": "2018-01-08T06:59:34.000Z",
"num_tokens": 3885,
"size": 10547
} |
/*
Copyright [2017-2019] [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 __NUPM_DAX_DATA_H__
#define __NUPM_DAX_DATA_H__
#include <libpmem.h>
#include <city.h> /* CityHash */
#include <common/pointer_cast.h>
#include <common/string_view.h>
#include <common/types.h>
#include <common/utils.h>
#include <boost/icl/split_interval_map.hpp>
#include <gsl/span>
#include <algorithm>
#include <list>
#include <stdexcept>
namespace
{
std::uint64_t make_uuid(const common::string_view name_)
{
if ( 255 < name_.size() )
{
throw std::invalid_argument("invalid file name (too long)");
}
auto region_id = ::CityHash64(name_.begin(), name_.size());
if (region_id == 0) throw std::invalid_argument("invalid region_id (and extreme bad luck!)");
return region_id;
}
}
namespace nupm
{
static std::uint32_t constexpr DM_REGION_MAGIC = 0xC0070000;
static unsigned constexpr DM_REGION_NAME_MAX_LEN = 1024;
static std::uint32_t constexpr DM_REGION_VERSION = 3;
static unsigned constexpr dm_region_log_grain_size = DM_REGION_LOG_GRAIN_SIZE; // log2 granularity (CMake default is 25, i.e. 32 MiB)
class DM_undo_log {
static constexpr unsigned MAX_LOG_COUNT = 4;
static constexpr unsigned MAX_LOG_SIZE = 272;
struct log_entry_t {
byte log[MAX_LOG_SIZE];
void * ptr;
size_t length; /* zero indicates log freed */
};
void log(void *ptr, size_t length)
{
assert(length > 0);
assert(ptr);
if (length > MAX_LOG_SIZE)
throw std::invalid_argument("log length exceeds max. space");
for (unsigned i = 0; i < MAX_LOG_COUNT; i++) {
if (_log[i].length == 0) {
_log[i].length = length;
_log[i].ptr = ptr;
pmem_memcpy_nodrain(_log[i].log, ptr, length);
// TODO
//memcpy(_log[i].log, ptr, length);
//mem_flush(&_log[i], sizeof(log_entry_t));
return;
}
}
throw API_exception("undo log full");
}
public:
template <typename T>
void log(T *ptr)
{
static_assert(sizeof *ptr <= MAX_LOG_SIZE, "object too big to log");
log(ptr, sizeof *ptr);
}
void clear_log()
{
for (unsigned i = 0; i < MAX_LOG_COUNT; i++) _log[i].length = 0;
}
void check_and_undo()
{
for (unsigned i = 0; i < MAX_LOG_COUNT; i++) {
if (_log[i].length > 0) {
PLOG("undo log being applied (ptr=%p, len=%lu).", _log[i].ptr,
_log[i].length);
// TODO
pmem_memcpy_persist(_log[i].ptr, _log[i].log, _log[i].length);
//memcpy(_log[i].ptr, _log[i].log, _log[i].length);
// mem_flush_nodrain(_log[i].ptr, _log[i].length);
_log[i].length = 0;
}
}
}
private:
log_entry_t _log[MAX_LOG_COUNT];
} __attribute__((packed));
class DM_region {
public:
/* "grain" is the unit of suballocation within a region. It is a fixed power
* of 2 common to all regions in the devdax namespace.
*/
using grain_offset_t = uint32_t;
grain_offset_t offset_grain;
grain_offset_t length_grain;
uint64_t region_id;
/* File name. Saved and returned.
* Internal logic uses region_id (file name hash) to reduce code changes.
*/
char file_name[256];
public:
/* re-zeroing constructor */
DM_region() : offset_grain(0), length_grain(0), region_id(0) { assert(check_aligned(this, 8)); }
void initialize(size_t space_size, std::size_t grain_size)
{
offset_grain = 0;
length_grain = boost::numeric_cast<uint32_t>(space_size / grain_size);
region_id = 0; /* zero indicates free */
}
friend class DM_region_header;
} __attribute__((packed));
/* Note: "region" has at least two meanings:
* 1. The space starting with, and described by, DM_region_header. ndctl calls this a namespace.
e 2. The space described by DM_region
*/
class DM_region_header {
private:
static constexpr uint16_t DEFAULT_MAX_REGIONS = 1024;
using string_view = common::string_view;
uint32_t _magic; // 4
uint32_t _version; // 8
uint64_t _device_size; // 16
uint32_t _region_count; // 20
uint16_t _log_grain_size; // 22
uint16_t _resvd; // 24
uint8_t _padding[40]; // 64
DM_undo_log _undo_log;
/*
* Following this data, there is
* 1. region_table_base, immediately following (this + 1)
* 2. arena_base, at ptr_cast<byte>(this) + grain_size. Code assumes
* (but does not verify) that DM_region_header plus all DM_region
* descriptors fit within a single grain.
*
* grain 0:
* "region_header"
* "region_table"
* grains 1 and following:
* "arena"
*/
public:
auto grain_size() const { return std::size_t(1) << _log_grain_size; }
/* Rebuilding constructor */
DM_region_header(size_t device_size)
: _magic(DM_REGION_MAGIC)
, _version(DM_REGION_VERSION)
, _device_size(device_size)
, _region_count( (::pmem_flush(this, sizeof(DM_region_header)), DEFAULT_MAX_REGIONS) )
, _log_grain_size(dm_region_log_grain_size)
, _resvd()
, _undo_log()
{
(void)_resvd; // unused
(void)_padding; // unused
DM_region *region_p = region_table_base();
/* initialize first region with all capacity with size of space, and size of grain */
region_p->initialize(device_size - grain_size(), grain_size());
_undo_log.clear_log();
region_p++;
for (uint16_t r = 1; r < _region_count; r++) {
new (region_p) DM_region();
_undo_log.clear_log();
region_p++;
}
major_flush();
}
void check_undo_logs()
{
_undo_log.check_and_undo();
}
void debug_dump()
{
PINF("DM_region_header:");
PINF(
" magic [0x%8x]\n version [%u]\n device_size [%lu]\n region_count [%u]",
_magic, _version, _device_size, _region_count);
PINF(" base [%p]", common::p_fmt(this));
const auto regions = region_table_span();
for (auto const & reg : regions ) {
if (reg.region_id > 0) {
PINF(" - USED: %lu (%lx-%lx)", reg.region_id,
grain_to_bytes(reg.offset_grain),
grain_to_bytes(reg.offset_grain + reg.length_grain) - 1);
assert(reg.length_grain > 0);
}
else if (reg.length_grain > 0) {
PINF(" - FREE: %lu (%lx-%lx)", reg.region_id,
grain_to_bytes(reg.offset_grain),
grain_to_bytes(reg.offset_grain + reg.length_grain) - 1);
}
}
}
void *get_region(string_view name_, size_t *out_size)
{
auto region_id = make_uuid(name_);
const auto regions = region_table_span();
for (auto const & reg : regions ) {
if (reg.region_id == region_id) {
#if 0
PLOG("%s: found matching region (%lx)", __func__, region_id);
#endif
if (out_size) *out_size = grain_to_bytes(reg.length_grain);
return arena_base() + grain_to_bytes(reg.offset_grain);
}
}
return nullptr; /* not found */
}
void erase_region(string_view name_)
{
auto region_id = make_uuid(name_);
const auto regions = region_table_span();
for (auto & reg : regions ) {
if (reg.region_id == region_id) {
reg.region_id = 0; /* power-fail atomic */
pmem_flush(®.region_id, sizeof(reg.region_id));
return;
}
}
throw std::runtime_error("region not found");
}
void *allocate_region(string_view name_, DM_region::grain_offset_t size_in_grain)
{
auto region_id = make_uuid(name_);
const auto regions = region_table_span();
for (auto & reg : regions ) {
if (reg.region_id == region_id)
throw std::bad_alloc();
}
bool found = false;
for (DM_region & reg : regions)
{
/* If we have found a sufficiently large free region */
if (reg.region_id == 0 && reg.length_grain >= size_in_grain) {
if (reg.length_grain == size_in_grain) {
/* exact match */
void *rp = arena_base() + grain_to_bytes(reg.offset_grain);
/* write file name to region */
pmem_memcpy_persist(reg.file_name, name_.begin(), name_.size());
pmem_memcpy_persist(®.file_name[name_.size()], "\0", 1);
// claim region
tx_atomic_write(®, region_id);
return rp;
}
else {
/* cut out */
const uint32_t new_offset = reg.offset_grain;
const auto changed_length = reg.length_grain - size_in_grain;
const auto changed_offset = reg.offset_grain + size_in_grain;
/* reg_n is the new region for unallocated space */
auto reg_n = std::find_if(regions.begin(), regions.end(), [] (const DM_region &r) { return r.region_id == 0 && r.length_grain == 0; });
if ( reg_n != regions.end() )
{
void *rp = arena_base() + grain_to_bytes(new_offset);
/* write file name to region */
pmem_memcpy_persist(reg.file_name, name_.begin(), name_.size());
pmem_memcpy_persist(®.file_name[name_.size()], "\0", 1);
// claim region
tx_atomic_write(&*reg_n, boost::numeric_cast<uint16_t>(changed_offset), boost::numeric_cast<uint16_t>(changed_length), ®,
new_offset, size_in_grain, region_id);
return rp;
}
}
}
}
if (!found)
throw General_exception("no more regions (size in grain=%u)", size_in_grain);
throw General_exception("no spare slots");
}
size_t get_max_available() const
{
auto regions = region_table_span();
auto max_grain_element =
std::max_element(
regions.begin()
, regions.end()
, [] (const DM_region &a, const DM_region &b) -> bool { return a.length_grain < b.length_grain; }
);
return grain_to_bytes( max_grain_element == regions.end() ? 0 : max_grain_element->length_grain);
}
inline size_t grain_to_bytes(unsigned grain) const { return size_t(grain) << _log_grain_size; }
inline void major_flush()
{
pmem_flush(this, sizeof(DM_region_header) + (sizeof(DM_region) * _region_count));
}
bool check_magic() const
{
return (_magic == DM_REGION_MAGIC) && (_version == DM_REGION_VERSION);
}
std::list<std::string> names_list()
{
std::list<std::string> nl;
auto regions = region_table_span();
for ( const auto &r : regions )
{
if ( 0 != r.region_id )
{
nl.push_back(std::string(r.file_name));
}
}
return nl;
}
private:
void tx_atomic_write(DM_region *dst, uint64_t region_id)
{
#pragma GCC diagnostic push
#if 9 <= __GNUC__
#pragma GCC diagnostic ignored "-Waddress-of-packed-member"
#endif
_undo_log.log(&dst->region_id);
#pragma GCC diagnostic pop
dst->region_id = region_id;
pmem_flush(&dst->region_id, sizeof(region_id));
_undo_log.clear_log();
}
void tx_atomic_write(DM_region *dst0, // offset0, size0, offset1, size1 all expressed in grains
uint32_t offset0,
uint32_t size0,
DM_region *dst1,
uint32_t offset1,
uint32_t size1,
uint64_t region_id1)
{
_undo_log.log(dst0);
_undo_log.log(dst1);
dst0->offset_grain = offset0;
dst0->length_grain = size0;
pmem_flush(dst0, sizeof(DM_region));
dst1->region_id = region_id1;
dst1->offset_grain = offset1;
dst1->length_grain = size1;
pmem_flush(dst1, sizeof(DM_region));
_undo_log.clear_log();
}
inline unsigned char *arena_base()
{
return common::pointer_cast<unsigned char>(this) + grain_size();
}
/* region descriptors immediately follow the DM_region_header. */
inline DM_region *region_table_base() { return common::pointer_cast<DM_region>(this + 1); }
inline const DM_region *region_table_base() const { return common::pointer_cast<const DM_region>(this + 1); }
gsl::span<DM_region> region_table_span() { return gsl::span<DM_region>(region_table_base(), _region_count); }
gsl::span<const DM_region> region_table_span() const { return gsl::span<const DM_region>(region_table_base(), _region_count); }
inline DM_region *region(size_t idx)
{
if (idx >= _region_count) return nullptr;
DM_region *p = static_cast<DM_region *>(region_table_base());
return &p[idx];
}
void reset_header(size_t device_size)
{
_magic = DM_REGION_MAGIC;
_version = DM_REGION_VERSION;
_device_size = device_size;
pmem_flush(this, sizeof(DM_region_header));
}
} __attribute__((packed));
} // namespace nupm
#endif //__NUPM_DAX_DATA_H__
| {
"alphanum_fraction": 0.6418436997,
"avg_line_length": 30.8250591017,
"ext": "h",
"hexsha": "63c868ab27529482edc980f1e473eec4c830b4ae",
"lang": "C",
"max_forks_count": 13,
"max_forks_repo_forks_event_max_datetime": "2022-01-26T01:56:42.000Z",
"max_forks_repo_forks_event_min_datetime": "2019-11-02T06:30:36.000Z",
"max_forks_repo_head_hexsha": "f47aab12754c91ebd75b0e1881c8a7cc7aa81278",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "omriarad/mcas",
"max_forks_repo_path": "src/lib/libnupm/src/dax_data.h",
"max_issues_count": 66,
"max_issues_repo_head_hexsha": "f47aab12754c91ebd75b0e1881c8a7cc7aa81278",
"max_issues_repo_issues_event_max_datetime": "2022-03-07T20:34:52.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-09-03T23:40:48.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "omriarad/mcas",
"max_issues_repo_path": "src/lib/libnupm/src/dax_data.h",
"max_line_length": 145,
"max_stars_count": 60,
"max_stars_repo_head_hexsha": "f47aab12754c91ebd75b0e1881c8a7cc7aa81278",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "omriarad/mcas",
"max_stars_repo_path": "src/lib/libnupm/src/dax_data.h",
"max_stars_repo_stars_event_max_datetime": "2022-03-08T10:35:15.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-04-28T08:15:07.000Z",
"num_tokens": 3447,
"size": 13039
} |
/*
* Evan Lezar
* An implementation of a dense eigensolver that uses the ARPACK Fortran backend.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <omp.h>
#include <cblas.h>
// #include <acml.h>
// Include the interfaces to the Fortran routines.
#include "interface.h"
#define ARPACK_CALL 0
#define SHIFT 1
#define SGETRF_S 2
#define SGEMV 9
//!
//! A data structure used to pass the eigenproblem configuration to Fortran and
//! back to C again.
struct data_struct {
float* A; //! A pointer to the matrix representing the eigenproblem.
double sgemv_time; //! The total time required to calculate the matrix-vector products.
int sgemv_calls; //! The number of times the matrix-vector product was called.
int LDA; //! The leading dimension of the matrix.
};
typedef struct data_struct data_struct;
//!
//! A utility function to print the structure representing the eigenproblem.
void print_data ( const char* desc, data_struct DATA )
{
printf ( "%s: A = %p LDA = %d\n", desc, DATA.A, DATA.LDA );
}
//!
//! Calculate the matrix-vector product y <- Ax for the eigensystem defined by DATA. This
//! routine is called from the Fortran backend whenever ARPACK requires a matrix-vector
//! product to be calculated.
//! \param[in] N The dimension of the eigensystem.
//! \param[in,out] DATA The structure representing the eigenproblem.
//! \param[in] x The vector that must be multiplied by A.
//! \param[out] y The vector that must store the result.
void sgemv_wrapper ( int N, data_struct* DATA, float* x, float* y )
{
checkpoint t0 = tic();
// read the relevant data from the struct
float* A = DATA->A;
int LDA = DATA->LDA;
// calculate y <-- Ax
cblas_sgemv ( CblasColMajor, CblasNoTrans, N, N, 1.0, A, LDA, x, 1, 0.0, y, 1);
DATA->sgemv_time += toc ( t0 );
DATA->sgemv_calls += 1;
}
//!
//! Initialise the struct representing the eigensystem.
void init_data ( data_struct* DATA, float* A, int LDMAT )
{
DATA->A = A;
DATA->LDA = LDMAT;
DATA->sgemv_calls = 0;
DATA->sgemv_time = 0.0;
}
//!
//! Solve the actual eigensystem. This takes the eigensystem defined in the structure DATA and allocates
//! the required temporary workspaces before calling the Fortran backend.
void calculate_eigen_values ( int N, void* DATA, int NEV, float* eigenvalues, float* eigenvectors, char* which )
{
int use_N_ev = 2*NEV;
if ( use_N_ev > ( N/2 - 1 ) )
use_N_ev = N/2 - 1;
// select the number of Arnoldi vectors to generate
int NCV = 2*use_N_ev + 1;
if ( NCV > N )
NCV = N;
// allocate temporary storage for the vectors
float* temp_ev = (float*)malloc ( NCV*2*sizeof(float) );
float* temp_vectors = (float*) malloc (N*NCV*sizeof(float));
float* temp_residuals = (float*)malloc ( (NCV )*sizeof(float));
// solve the eigenvalue problem using ARPACK
arpack_ssev(N, (void*)DATA, use_N_ev, NCV, temp_ev, temp_vectors, temp_residuals, which );
// Copy the resultant eigenvalues to the previously allocated space.
memcpy(eigenvalues, temp_ev, NEV*2*sizeof(float));
memcpy(eigenvectors, temp_vectors, NEV*N*sizeof(float));
// free the temporary storage
free ( temp_ev );
free ( temp_vectors );
free ( temp_residuals );
}
//!
//! Solve the standard eigensystem Ax = lx.eigen
//! \param[in] N The number of columns in the matrix A
//! \param[in] A The matrix representing the eigensystem to be solved.
//! \param[in] NEV The number of eigenvalues to calculate.
//! \param[out] eigenvalues A vector of the NEV eigenvalues. Note that the eigenvectors are complex.
//! \param[out] eigenvectors An NxNEV matrix with the eigenvectors as columns.
//! \param[out] timing_data_10 A 10-vector representing the timing data for various phases of the process.
//! \param[out] int_data_10 A 10-vector containing some run information.
//! \return A non-zero error code if an error occured.
int dense_seev ( int N, float* A, int LDMAT, int NEV, float* eigenvalues, float* eigenvectors, double* timing_data_10, int* int_data_10 )
{
checkpoint t0;
int result = 0;
// Initialise the data structure that is passed to the ARPACK routines.
data_struct DATA;
init_data( &DATA, A, LDMAT );
t0 = tic();
// Call a C wrapper function that allows for the calculation of the NEV largest eigenvalues.
calculate_eigen_values ( N, &DATA, NEV, eigenvalues, eigenvectors, "LM" );
timing_data_10[ARPACK_CALL] = toc( t0 );
timing_data_10[SGEMV] = DATA.sgemv_time;
int_data_10[SGEMV] = DATA.sgemv_calls;
return result;
}
| {
"alphanum_fraction": 0.6879723602,
"avg_line_length": 35.8992248062,
"ext": "c",
"hexsha": "c12f20beb3f726b52625835eb9451f3fa9d63f8f",
"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": "f9c4edb20c2f1556fea4404679bd8c2d7039af18",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "elezar/gpu-arpack",
"max_forks_repo_path": "src/dense_cpu.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "f9c4edb20c2f1556fea4404679bd8c2d7039af18",
"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": "elezar/gpu-arpack",
"max_issues_repo_path": "src/dense_cpu.c",
"max_line_length": 137,
"max_stars_count": 3,
"max_stars_repo_head_hexsha": "f9c4edb20c2f1556fea4404679bd8c2d7039af18",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "elezar/gpu-arpack",
"max_stars_repo_path": "src/dense_cpu.c",
"max_stars_repo_stars_event_max_datetime": "2021-01-14T14:14:16.000Z",
"max_stars_repo_stars_event_min_datetime": "2016-08-15T14:35:42.000Z",
"num_tokens": 1266,
"size": 4631
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.