text:
/*******************************************************************************
*
*       This file is part of the General Hidden Markov Model Library,
*       GHMM version __VERSION__, see http://ghmm.org
*
*       Filename: ghmm/ghmm/randvar.c
*       Authors:  Bernhard Knab, Benjamin Rich, Janne Grunau
*
*       Copyright (C) 1998-2004 Alexander Schliep
*       Copyright (C) 1998-2001 ZAIK/ZPR, Universitaet zu Koeln
*       Copyright (C) 2002-2004 Max-Planck-Institut fuer Molekulare Genetik,
*                               Berlin
*
*       Contact: schliep@ghmm.org
*
*       This library is free software; you can redistribute it and/or
*       modify it under the terms of the GNU Library General Public
*       License as published by the Free Software Foundation; either
*       version 2 of the License, or (at your option) any later version.
*
*       This library is distributed in the hope that it will be useful,
*       but WITHOUT ANY WARRANTY; without even the implied warranty of
*       MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
*       Library General Public License for more details.
*
*       You should have received a copy of the GNU Library General Public
*       License along with this library; if not, write to the Free
*       Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*
*       This file is version $Revision: 2310 $
*                       from $Date: 2013-06-14 10:36:57 -0400 (Fri, 14 Jun 2013) $
*             last change by $Author: ejb177 $.
*
*******************************************************************************/

#ifdef HAVE_CONFIG_H
#  include "../config.h"
#endif

#include <math.h>
#include <float.h>
#include <string.h>
#ifdef HAVE_LIBPTHREAD
# include <pthread.h>
#endif /* HAVE_LIBPTHREAD */

#include "ghmm.h"
#include "mes.h"
#include "mprintf.h"
#include "randvar.h"
#include "rng.h"

#ifdef DO_WITH_GSL

# include <gsl/gsl_math.h>
# include <gsl/gsl_sf_erf.h>
# include <gsl/gsl_randist.h>

#include <gsl/gsl_vector.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_blas.h>

#endif /* DO_WITH_GSL */

#if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L)
#else
static double ighmm_erf (double x);
static double ighmm_erfc (double x);
#endif /* check for ISO C99 */

/* A list of already calculated values of the density function of a
   N(0,1)-distribution, with x in [0.00, 19.99] */
#define PDFLEN 2000
#define X_STEP_PDF 0.01         /* step size */
#define X_FAKT_PDF 100          /* equivalent to step size */
static double pdf_stdnormal[PDFLEN];
static int pdf_stdnormal_exists = 0;

/* A list of already calulated values PHI of the Gauss distribution is
   read in, x in [-9.999, 0] */
#define X_STEP_PHI 0.001        /* step size */
#define X_FAKT_PHI 1000         /* equivalent to step size */
static double x_PHI_1 = -1.0;

#ifndef M_SQRT1_2
#define M_SQRT1_2  0.70710678118654752440084436210
#endif

/*============================================================================*/
/* needed by ighmm_gtail_pmue_interpol */

double ighmm_rand_get_xfaktphi ()
{
  return X_FAKT_PHI;
}

double ighmm_rand_get_xstepphi ()
{
  return X_STEP_PHI;
}

double ighmm_rand_get_philen ()
{
#ifdef DO_WITH_GSL
  return 0 /*PHI_len*/;
#else
  return ighmm_rand_get_xPHIless1 () / X_STEP_PHI;
#endif
}

/*============================================================================*/
double ighmm_rand_get_PHI (double x)
{
#if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L)
  return (erf (x * M_SQRT1_2) + 1.0) / 2.0;
#else
  return (ighmm_erf (x * M_SQRT1_2) + 1.0) / 2.0;
#endif
}                               /* randvar_get_PHI */

/*============================================================================*/
/* When is PHI[x,0,1] == 1? */
double ighmm_rand_get_xPHIless1 ()
{
# define CUR_PROC "ighmm_rand_get_xPHIless1"

  if (x_PHI_1 == -1) {
    double low, up, half;
    low = 0;
    up = 100;
    while (up - low > 0.001) {
      half = (low + up) / 2.0;
      if (ighmm_rand_get_PHI (half) < 1.0)
        low = half;
      else
        up = half;
    }
    x_PHI_1 = low;
  }
  return (x_PHI_1);

# undef CUR_PROC
}

/*============================================================================*/
double ighmm_rand_get_1overa (double x, double mean, double u)
{
  /* Calulates 1/a(x, mean, u), with a = the integral from x til \infty over
     the Gauss density function */
# define CUR_PROC "ighmm_rand_get_1overa"

  double erfc_value;

  if (u <= 0.0) {
    GHMM_LOG(LCONVERTED, "u <= 0.0 not allowed\n");
    goto STOP;
  }

#if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L)
  erfc_value = erfc ((x - mean) / sqrt (u * 2));
#else
  erfc_value = ighmm_erfc ((x - mean) / sqrt (u * 2));
#endif

  if (erfc_value <= DBL_MIN) {
    ighmm_mes (MES_WIN, "a ~= 0.0 critical! (mue = %.2f, u =%.2f)\n", mean, u);
    return (erfc_value);
  }
  else
    return (2.0 / erfc_value);

STOP:
  return (-1.0);
# undef CUR_PROC
}                               /* ighmm_rand_get_1overa */

/*============================================================================*/
/* REMARK:
   The calulation of this density function was testet, by calculating the
   following integral sum for arbitrary mue and u:
     for (x = 0, x < ..., x += step(=0.01/0.001/0.0001))
       isum += step * ighmm_rand_normal_density_pos(x, mue, u);
   In each case, the sum "converged" evidently towards 1!
   (BK, 14.6.99)
   CHANGE:
   Truncate at -EPS_NDT (const.h), so that x = 0 doesn't lead to a problem.
   (BK, 15.3.2000)
*/
double ighmm_rand_normal_density_pos (double x, double mean, double u)
{
# define CUR_PROC "ighmm_rand_normal_density_pos"
  return ighmm_rand_normal_density_trunc (x, mean, u, -GHMM_EPS_NDT);
# undef CUR_PROC
}                               /* double ighmm_rand_normal_density_pos */

/*============================================================================*/
double ighmm_rand_normal_density_trunc(double x, double mean, double u,
                                       double a)
{
# define CUR_PROC "ighmm_rand_normal_density_trunc"
#ifndef DO_WITH_GSL
  double c;
#endif /* DO_WITH_GSL */

  if (u <= 0.0) {
    GHMM_LOG(LERROR, "u <= 0.0 not allowed");
    goto STOP;
  }
  if (x < a)
    return 0.0;

#ifdef DO_WITH_GSL
  /* move mean to the right position */
  return gsl_ran_gaussian_tail_pdf(x - mean, a - mean, sqrt(u));
#else
  if ((c = ighmm_rand_get_1overa(a, mean, u)) == -1) {
    GHMM_LOG_QUEUED(LERROR);
    goto STOP;
  };
  return c * ighmm_rand_normal_density(x, mean, u);
#endif /* DO_WITH_GSL */

STOP:
  return -1.0;
# undef CUR_PROC
}                               /* double ighmm_rand_normal_density_trunc */

/*============================================================================*/
double ighmm_rand_normal_density (double x, double mean, double u)
{
# define CUR_PROC "ighmm_rand_normal_density"
#ifndef DO_WITH_GSL
  double expo;
#endif
  if (u <= 0.0) {
    GHMM_LOG(LCONVERTED, "u <= 0.0 not allowed\n");
    goto STOP;
  }
  /* The denominator is possibly < EPS??? Check that ? */
#ifdef DO_WITH_GSL
  /* double gsl_ran_gaussian_pdf (double x, double sigma) */
  return gsl_ran_gaussian_pdf (x - mean, sqrt (u));
#else
  expo = exp (-1 * m_sqr (mean - x) / (2 * u));
  return (1 / (sqrt (2 * PI * u)) * expo);
#endif

STOP:
  return (-1.0);
# undef CUR_PROC
}                               /* double ighmm_rand_normal_density */

/*============================================================================*/
/* covariance matrix is linearized */
double ighmm_rand_binormal_density(const double *x, double *mean, double *cov)
{
# define CUR_PROC "ighmm_rand_binormal_density"
  double rho;
#ifndef DO_WITH_GSL
  double numerator,part1,part2,part3;
#endif
  if (cov[0] <= 0.0 || cov[2 + 1] <= 0.0) {
    GHMM_LOG(LCONVERTED, "variance <= 0.0 not allowed\n");
    goto STOP;
  }
  rho = cov[1] / ( sqrt (cov[0]) * sqrt (cov[2 + 1]) );
  /* The denominator is possibly < EPS??? Check that ? */
#ifdef DO_WITH_GSL
  /* double gsl_ran_bivariate_gaussian_pdf (double x, double y, double sigma_x,
                                            double sigma_y, double rho) */
  return gsl_ran_bivariate_gaussian_pdf (x[0], x[1], sqrt (cov[0]),
                                         sqrt (cov[2 + 1]), rho);
#else
  part1 = (x[0] - mean[0]) / sqrt (cov[0]);
  part2 = (x[1] - mean[1]) / sqrt (cov[2 + 1]);
  part3 = m_sqr (part1) - 2 * part1 * part2 + m_sqr (part2);
  numerator = exp ( -1 * (part3) / ( 2 * (1 - m_sqr(rho)) ) );
  return (numerator / ( 2 * PI * sqrt(1 - m_sqr(rho)) ));
#endif

STOP:
  return (-1.0);
# undef CUR_PROC
}                               /* double ighmm_rand_binormal_density */

/*============================================================================*/
/* matrices are linearized */
double ighmm_rand_multivariate_normal_density(int length, const double *x, double *mean, double *sigmainv, double det)
{
# define CUR_PROC "ighmm_rand_multivariate_normal_density"
  /* multivariate normal density function    */
  /*
   *       length     dimension of the random vetor
   *       x          point at which to evaluate the pdf
   *       mean       vector of means of size n
   *       sigmainv   inverse variance matrix of dimension n x n
   *       det        determinant of covariance matrix
   */

#ifdef DO_WITH_GSL
  int i, j;
  double ax,ay;
  gsl_vector *ym, *xm, *gmean;
  gsl_matrix *inv = gsl_matrix_alloc(length, length);

  for (i=0; i<length; ++i) {
    for (j=0; j<length; ++j) {
      gsl_matrix_set(inv, i, j, sigmainv[i*length+j]);
    }
  }

  xm = gsl_vector_alloc(length);
  gmean = gsl_vector_alloc(length);
  /*gsl_vector_memcpy(xm, x);*/
  for (i=0; i<length; ++i) {
    gsl_vector_set(xm, i, x[i]);
    gsl_vector_set(gmean, i, mean[i]);
  }

  gsl_vector_sub(xm, gmean);
  ym = gsl_vector_alloc(length);
  gsl_blas_dsymv(CblasUpper, 1.0, inv, xm, 0.0, ym);
  gsl_matrix_free(inv);
  gsl_blas_ddot(xm, ym, &ay);
  gsl_vector_free(xm);
  gsl_vector_free(ym);
  ay = exp(-0.5*ay) / sqrt(pow((2*M_PI), length) * det);

  return ay;
#else
  /* do without GSL */
  int i, j;
  double ay, tempv;

  ay = 0;
  for (i=0; i<length; ++i) {
    tempv = 0;
    for (j=0; j<length; ++j) {
      tempv += (x[j]-mean[j])*sigmainv[j*length+i];
    }
    ay += tempv*(x[i]-mean[i]);
  }
  ay = exp(-0.5*ay) / sqrt(pow((2*PI), length) * det);

  return ay;
#endif
# undef CUR_PROC
}                               /* double ighmm_rand_multivariate_normal_density */

/*============================================================================*/
double ighmm_rand_uniform_density (double x, double max, double min)
{
# define CUR_PROC "ighmm_rand_uniform_density"
  double prob;
  if (max <= min) {
    GHMM_LOG(LCONVERTED, "max <= min not allowed \n");
    goto STOP;
  }
  prob = 1.0/(max-min);

  if ( (x <= max) && (x>=min) ){
    return prob;
  }else{
    return 0.0;
  }
STOP:
  return (-1.0);
# undef CUR_PROC
}                               /* double ighmm_rand_uniform_density */

/*============================================================================*/
/* special ghmm_cmodel pdf need it: smo->density==normal_approx: */
/* generates a table of of aequidistant samples of gaussian pdf */

static int randvar_init_pdf_stdnormal ()
{
# define CUR_PROC "randvar_init_pdf_stdnormal"
  int i;
  double x = 0.00;
  for (i = 0; i < PDFLEN; i++) {
    pdf_stdnormal[i] = 1 / (sqrt (2 * PI)) * exp (-1 * x * x / 2);
    x += (double) X_STEP_PDF;
  }
  pdf_stdnormal_exists = 1;
  /* printf("pdf_stdnormal_exists = %d\n", pdf_stdnormal_exists); */
  return (0);
# undef CUR_PROC
}                               /* randvar_init_pdf_stdnormal */

double ighmm_rand_normal_density_approx (double x, double mean, double u)
{
# define CUR_PROC "ighmm_rand_normal_density_approx"
#ifdef HAVE_LIBPTHREAD
  static pthread_mutex_t lock;
#endif /* HAVE_LIBPTHREAD */
  int i;
  double y, z, pdf_x;
  if (u <= 0.0) {
    GHMM_LOG(LCONVERTED, "u <= 0.0 not allowed\n");
    goto STOP;
  }
  if (!pdf_stdnormal_exists) {
#ifdef HAVE_LIBPTHREAD
    pthread_mutex_lock (&lock); /* Put on a lock, because the clustering is parallel   */
#endif /* HAVE_LIBPTHREAD */
    randvar_init_pdf_stdnormal ();
#ifdef HAVE_LIBPTHREAD
    pthread_mutex_unlock (&lock);       /* Take the lock off */
#endif /* HAVE_LIBPTHREAD */
  }
  y = 1 / sqrt (u);
  z = fabs ((x - mean) * y);
  i = (int) (z * X_FAKT_PDF);
  /* linear interpolation: */
  if (i >= PDFLEN - 1) {
    i = PDFLEN - 1;
    pdf_x = y * pdf_stdnormal[i];
  }
  else
    pdf_x = y * (pdf_stdnormal[i] +
                 (z - i * X_STEP_PDF) *
                 (pdf_stdnormal[i + 1] - pdf_stdnormal[i]) / X_STEP_PDF);
  return (pdf_x);
STOP:
  return (-1.0);
# undef CUR_PROC
}                               /* double ighmm_rand_normal_density_approx */
double ighmm_rand_dirichlet(int seed, int len, double *alpha, double *theta){
  if (seed != 0) {
    GHMM_RNG_SET(RNG, seed);
  }
#ifdef DO_WITH_GSL
   gsl_ran_dirichlet(RNG, len, alpha, theta);
#else
  printf("not implemted without gsl. Compile with gsl to use dirichlet");
#endif
}

/*============================================================================*/
double ighmm_rand_std_normal (int seed)
{
# define CUR_PROC "ighmm_rand_std_normal"
  if (seed != 0) {
    GHMM_RNG_SET (RNG, seed);
  }

#ifdef DO_WITH_GSL
    return (gsl_ran_gaussian (RNG, 1.0));
#else
    /* Use the polar Box-Mueller transform */
    /*
       double x, y, r2;

       do {
       x = 2.0 * GHMM_RNG_UNIFORM(RNG) - 1.0;
       y = 2.0 * GHMM_RNG_UNIFORM(RNG) - 1.0;
       r2 = (x * x) + (y * y);
       } while (r2 >= 1.0);

       return x * sqrt((-2.0 * log(r2)) / r2);
     */

    double r2, theta;

    r2 = -2.0 * log (GHMM_RNG_UNIFORM (RNG));   /* r2 ~ chi-square(2) */
    theta = 2.0 * PI * GHMM_RNG_UNIFORM (RNG);  /* theta ~ uniform(0, 2 \pi) */
    return sqrt (r2) * cos (theta);
#endif

# undef CUR_PROC
}                               /* ighmm_rand_std_normal */

/*============================================================================*/
double ighmm_rand_normal(double mue, double u, int seed)
{
# define CUR_PROC "ighmm_rand_normal"
  if (seed != 0) {
    GHMM_RNG_SET(RNG, seed);
  }

#ifdef DO_WITH_GSL
    return gsl_ran_gaussian(RNG, sqrt (u)) + mue;
#else
    double x;
    x = sqrt(u) * ighmm_rand_std_normal(seed) + mue;
    return x;
#endif

# undef CUR_PROC
}                               /* ighmm_rand_normal */

/*============================================================================*/
int ighmm_rand_multivariate_normal (int dim, double *x, double *mue, double *sigmacd, int seed)
{
# define CUR_PROC "ighmm_rand_multivariate_normal"
  /* generate random vector of multivariate normal
   *
   *     dim     number of dimensions
   *     x       space to store resulting vector in
   *     mue     vector of means
   *     sigmacd linearized cholesky decomposition of cov matrix
   *     seed    RNG seed
   *
   *     see Barr & Slezak, A Comparison of Multivariate Normal Generators */
  int i, j;
#ifdef DO_WITH_GSL
  gsl_vector *y = gsl_vector_alloc(dim);
  gsl_vector *xgsl = gsl_vector_alloc(dim);
  gsl_matrix *cd = gsl_matrix_alloc(dim, dim);
#endif
  if (seed != 0) {
    GHMM_RNG_SET (RNG, seed);
    /* do something here */
    return 0;
  }
  else {
#ifdef DO_WITH_GSL
    /* cholesky decomposition matrix */
    for (i=0;i<dim;i++) {
      for (j=0;j<dim;j++) {
        gsl_matrix_set(cd, i, j, sigmacd[i*dim+j]);
      }
    }
    /* generate a random vector N(O,I) */
    for (i=0;i<dim;i++) {
      gsl_vector_set(y, i, ighmm_rand_std_normal(seed));
    }
    /* multiply cd with y */
    gsl_blas_dgemv(CblasNoTrans, 1.0, cd, y, 0.0, xgsl);
    for (i=0;i<dim;i++) {
      x[i] = gsl_vector_get(xgsl, i) + mue[i];
    }
    gsl_vector_free(y);
    gsl_vector_free(xgsl);
    gsl_matrix_free(cd);
#else
    /* multivariate random numbers without gsl */
    double randuni;
    for (i=0;i<dim;i++) {
      randuni = ighmm_rand_std_normal(seed);
      for (j=0;j<dim;j++) {
        if (i==0)
          x[j] = mue[j];
        x[j] += randuni * sigmacd[j*dim+i];
      }
    }
#endif
    return 0;
  }
# undef CUR_PROC
}                               /* ighmm_rand_multivariate_normal */

/*============================================================================*/
#ifndef DO_WITH_GSL
# define C0 2.515517
# define C1 0.802853
# define C2 0.010328
# define D1 1.432788
# define D2 0.189269
# define D3 0.001308
#endif

double ighmm_rand_normal_right (double a, double mue, double u, int seed)
{
# define CUR_PROC "ighmm_rand_normal_right"
  double x = -1;
  double sigma;
#ifdef DO_WITH_GSL
  double s;
#else
  double U, Us, Us1, Feps, t, T;
#endif

  if (u <= 0.0) {
    GHMM_LOG(LCONVERTED, "u <= 0.0 not allowed\n");
    goto STOP;
  }
  sigma = sqrt(u);

  if (seed != 0) {
    GHMM_RNG_SET (RNG, seed);
  }

#ifdef DO_WITH_GSL
  /* move boundary to lower values in order to achieve maximum at mue
     gsl_ran_gaussian_tail(generator, lower_boundary, sigma)
   */
  return mue + gsl_ran_gaussian_tail(RNG, a - mue, sqrt (u));

#else /* DO_WITH_GSL */

  /* Inverse transformation with restricted sampling by Fishman */
  U = GHMM_RNG_UNIFORM(RNG);
  Feps = ighmm_rand_get_PHI((a-mue) / sigma);

  Us = Feps + (1-Feps) * U;
  Us1 = 1-Us;
  t = m_min (Us, Us1);

  t = sqrt (-log (t * t));

  T =
    sigma * (t - (C0 + t * (C1 + t * C2))
                 / (1 + t * (D1 + t * (D2 + t * D3))));

  if (Us < Us1)
    x = mue - T;
  else
    x = mue + T;
#endif /* DO_WITH_GSL */

STOP:
  return x;
# undef CUR_PROC
}                               /* randvar_normal_pos */

/*============================================================================*/
double ighmm_rand_uniform_int (int seed, int K)
{
# define CUR_PROC "ighmm_rand_uniform_int"
  if (seed != 0) {
    GHMM_RNG_SET (RNG, seed);
  }

#ifdef DO_WITH_GSL
    /* more direct solution than old version ! */
    return (double) gsl_rng_uniform_int (RNG, K);
#else
    return (double) ((int) (((double) K) * GHMM_RNG_UNIFORM (RNG)));
#endif

# undef CUR_PROC
}                               /* ighmm_rand_uniform_int */

/*===========================================================================*/
double ighmm_rand_uniform_cont (int seed, double max, double min)
{
# define CUR_PROC "ighmm_rand_uniform_cont"
  if (max <= min) {
    GHMM_LOG(LCONVERTED, "max <= min not allowed\n");
    goto STOP;
  }
  if (seed != 0) {
    GHMM_RNG_SET (RNG, seed);
  }

#ifdef DO_WITH_GSL
    return (double)(((double)gsl_rng_uniform (RNG)*(max-min)) + min);
#else
    return (double)((GHMM_RNG_UNIFORM (RNG))*(max-min) + min );
#endif

STOP:
  return (-1.0);
# undef CUR_PROC
}                               /* ighmm_rand_uniform_cont */

/*============================================================================*/
/* cumalative distribution function of N(mean, u) */
double ighmm_rand_normal_cdf (double x, double mean, double u)
{
# define CUR_PROC "ighmm_rand_normal_cdf"
  if (u <= 0.0) {
    GHMM_LOG(LCONVERTED, "u <= 0.0 not allowed\n");
    goto STOP;
  }
#if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L)
  /* PHI(x)=erf(x/sqrt(2))/2+0.5 */
  return (erf ((x - mean) / sqrt (u * 2.0)) + 1.0) / 2.0;
#else
  return (ighmm_erf ((x - mean) / sqrt (u * 2.0)) + 1.0) / 2.0;
#endif /* Check for ISO C99 */
STOP:
  return (-1.0);
# undef CUR_PROC
}                               /* double ighmm_rand_normal_cdf */

/*============================================================================*/
/* cumalative distribution function of a-truncated N(mean, u) */
double ighmm_rand_normal_right_cdf (double x, double mean, double u, double a)
{
# define CUR_PROC "ighmm_rand_normal_right_cdf"

  if (x <= a)
    return (0.0);
  if (u <= a) {
    GHMM_LOG(LCONVERTED, "u <= a not allowed\n");
    goto STOP;
  }
#if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L)
  /*
     Function: int erfc (double x, gsl_sf_result * result)
     These routines compute the complementary error function
     erfc(x) = 1 - erf(x) = 2/\sqrt(\pi) \int_x^\infty \exp(-t^2).
   */
  return 1.0 + (erf ((x - mean) / sqrt (u * 2)) -
                1.0) / erfc ((a - mean) / sqrt (u * 2));
#else
  return 1.0 + (ighmm_erf ((x - mean) / sqrt (u * 2)) -
                1.0) / ighmm_erfc ((a - mean) / sqrt (u * 2));
#endif /* Check for ISO C99 */
STOP:
  return (-1.0);
# undef CUR_PROC
}                               /* double ighmm_rand_normal_cdf */

/*============================================================================*/
/* cumalative distribution function of a uniform distribution in the range [min,max] */
double ighmm_rand_uniform_cdf (double x, double max, double min)
{
# define CUR_PROC "ighmm_rand_uniform_cdf"
  if (max <= min) {
    GHMM_LOG(LCONVERTED, "max <= min not allowed\n");
    goto STOP;
  }
  if (x < min) {
    return 0.0;
  }
  if (x >= max) {
    return 1.0;
  }
  return (x-min)/(max-min);
STOP:
  return (-1.0);
# undef CUR_PROC
}                               /* ighmm_rand_uniform_cdf */

#if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L)
#else

/* THIS WILL BE OBSOLETE WHEN WE USE ISO C99 */

/*===========================================================================
 *
 * The following functions for the error function and the complementory
 * error function are taken from
 * http://www.mathematik.uni-bielefeld.de/~sillke/ALGORITHMS/special-functions/erf.c
 * and have following different copyright.

 * ====================================================
 * Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved.
 *
 * Developed at SunPro, a Sun Microsystems, Inc. business.
 * Permission to use, copy, modify, and distribute this
 * software is freely granted, provided that this notice
 * is preserved.
 * ====================================================
 */

/*
 * ====================================================
 *
 * Reference:
 *
 * W. J. Cody,
 *   Rational Chebychev approximations for the
 *   error function.
 *   Mathematics of Computations 23 (1969) 631-637
 *
 * W. J. Cody,
 *   Performance evaluations of programs for the
 *   error and complementary error function.
 *   Transactions of the ACM on Mathematical Software,
 *   16:1 (March 1990) 38-46
 *
 * W. J. Cody,
 *   SPECFUN - A portable special function package,
 *   In: New Computing environments;
 *   Microcomputers in Large-Scale Scientific Computing,
 *   A. Wouk, SIAM, 1987, 1-12
 *
 * W. J. Cody,
 *   http://www.netlib.org/specfun/erf.
 *
 * For calculations with complex arguments see:
 *
 * Walter Gautschi
 *   "Efficient computation of the complex error function"
 *   SIAM J. Numer. Anal.
 *   7:1 (1970), 187-198
 *
 * J.A.C. Weideman
 *   "Computation of the complex error function"
 *   SIAM J. Numer. Anal.
 *   31:5 (1994), 1497-1518
 *
 * ====================================================
 */

/* double erf(double x)
 * double erfc(double x)
 *			     x
 *		      2      |\
 *     erf(x)  =  ---------  | exp(-t*t)dt
 *	 	   sqrt(pi) \|
 *			     0
 *
 *     erfc(x) =  1-erf(x)
 *  Note that
 *		erf(-x) = -erf(x)
 *		erfc(-x) = 2 - erfc(x)
 *
 * Method:
 *	1. For |x| in [0, 0.84375]
 *	    erf(x)  = x + x*R(x^2)
 *          erfc(x) = 1 - erf(x)           if x in [-.84375,0.25]
 *                  = 0.5 + ((0.5-x)-x*R)  if x in [0.25,0.84375]
 *	   where R = P/Q where P is an odd poly of degree 8 and
 *	   Q is an odd poly of degree 10.
 *						 -57.90
 *			| R - (erf(x)-x)/x | <= 2
 *
 *
 *	   Remark. The formula is derived by noting
 *          erf(x) = (2/sqrt(pi))*(x - x^3/3 + x^5/10 - x^7/42 + ....)
 *	   and that
 *          2/sqrt(pi) = 1.128379167095512573896158903121545171688
 *	   is close to one. The interval is chosen because the fix
 *	   point of erf(x) is near 0.6174 (i.e., erf(x)=x when x is
 *	   near 0.6174), and by some experiment, 0.84375 is chosen to
 * 	   guarantee the error is less than one ulp for erf.
 *
 *      2. For |x| in [0.84375,1.25], let s = |x| - 1, and
 *         c = 0.84506291151 rounded to single (24 bits)
 *         	erf(x)  = sign(x) * (c  + P1(s)/Q1(s))
 *         	erfc(x) = (1-c)  - P1(s)/Q1(s) if x > 0
 *			  1+(c+P1(s)/Q1(s))    if x < 0
 *         	|P1/Q1 - (erf(|x|)-c)| <= 2**-59.06
 *	   Remark: here we use the taylor series expansion at x=1.
 *		erf(1+s) = erf(1) + s*Poly(s)
 *			 = 0.845.. + P1(s)/Q1(s)
 *	   That is, we use rational approximation to approximate
 *			erf(1+s) - (c = (single)0.84506291151)
 *	   Note that |P1/Q1|< 0.078 for x in [0.84375,1.25]
 *	   where
 *		P1(s) = degree 6 poly in s
 *		Q1(s) = degree 6 poly in s
 *
 *      3. For x in [1.25,1/0.35(~2.857143)],
 *         	erfc(x) = (1/x)*exp(-x*x-0.5625+R1/S1)
 *         	erf(x)  = 1 - erfc(x)
 *	   where
 *		R1(z) = degree 7 poly in z, (z=1/x^2)
 *		S1(z) = degree 8 poly in z
 *
 *      4. For x in [1/0.35,28]
 *         	erfc(x) = (1/x)*exp(-x*x-0.5625+R2/S2) if x > 0
 *			= 2.0 - (1/x)*exp(-x*x-0.5625+R2/S2) if -6<x<0
 *			= 2.0 - tiny		(if x <= -6)
 *         	erf(x)  = sign(x)*(1.0 - erfc(x)) if x < 6, else
 *         	erf(x)  = sign(x)*(1.0 - tiny)
 *	   where
 *		R2(z) = degree 6 poly in z, (z=1/x^2)
 *		S2(z) = degree 7 poly in z
 *
 *      Note1:
 *	   To compute exp(-x*x-0.5625+R/S), let s be a single
 *	   precision number and s := x; then
 *		-x*x = -s*s + (s-x)*(s+x)
 *	        exp(-x*x-0.5626+R/S) =
 *			exp(-s*s-0.5625)*exp((s-x)*(s+x)+R/S);
 *      Note2:
 *	   Here 4 and 5 make use of the asymptotic series
 *			  exp(-x*x)
 *		erfc(x) ~ ---------- * ( 1 + Poly(1/x^2) )
 *			  x*sqrt(pi)
 *	   We use rational approximation to approximate
 *      	g(s)=f(1/x^2) = log(erfc(x)*x) - x*x + 0.5625
 *	   Here is the error bound for R1/S1 and R2/S2
 *      	|R1/S1 - f(x)|  < 2**(-62.57)
 *      	|R2/S2 - f(x)|  < 2**(-61.52)
 *
 *      5. For inf > x >= 28
 *         	erf(x)  = sign(x) *(1 - tiny)  (raise inexact)
 *         	erfc(x) = tiny*tiny (raise underflow) if x > 0
 *			= 2 - tiny if x<0
 *
 *      7. Special case:
 *         	erf(0)  = 0, erf(inf)  = 1, erf(-inf) = -1,
 *         	erfc(0) = 1, erfc(inf) = 0, erfc(-inf) = 2,
 *	   	erfc/erf(NaN) is NaN
 */

static const double

tiny =  1e-300,
half =  5.00000000000000000000e-01, /* 0x3FE00000, 0x00000000 */
one  =  1.00000000000000000000e+00, /* 0x3FF00000, 0x00000000 */
two  =  2.00000000000000000000e+00, /* 0x40000000, 0x00000000 */

erx  =  8.45062911510467529297e-01, /* 0x3FEB0AC1, 0x60000000 */
/*
 * Coefficients for approximation to  erf on [0,0.84375]
 */
efx  =  1.28379167095512586316e-01, /* 0x3FC06EBA, 0x8214DB69 */
efx8 =  1.02703333676410069053e+00, /* 0x3FF06EBA, 0x8214DB69 */
pp0  =  1.28379167095512558561e-01, /* 0x3FC06EBA, 0x8214DB68 */
pp1  = -3.25042107247001499370e-01, /* 0xBFD4CD7D, 0x691CB913 */
pp2  = -2.84817495755985104766e-02, /* 0xBF9D2A51, 0xDBD7194F */
pp3  = -5.77027029648944159157e-03, /* 0xBF77A291, 0x236668E4 */
pp4  = -2.37630166566501626084e-05, /* 0xBEF8EAD6, 0x120016AC */
qq1  =  3.97917223959155352819e-01, /* 0x3FD97779, 0xCDDADC09 */
qq2  =  6.50222499887672944485e-02, /* 0x3FB0A54C, 0x5536CEBA */
qq3  =  5.08130628187576562776e-03, /* 0x3F74D022, 0xC4D36B0F */
qq4  =  1.32494738004321644526e-04, /* 0x3F215DC9, 0x221C1A10 */
qq5  = -3.96022827877536812320e-06, /* 0xBED09C43, 0x42A26120 */
/*
 * Coefficients for approximation to  erf  in [0.84375,1.25]
 */
pa0  = -2.36211856075265944077e-03, /* 0xBF6359B8, 0xBEF77538 */
pa1  =  4.14856118683748331666e-01, /* 0x3FDA8D00, 0xAD92B34D */
pa2  = -3.72207876035701323847e-01, /* 0xBFD7D240, 0xFBB8C3F1 */
pa3  =  3.18346619901161753674e-01, /* 0x3FD45FCA, 0x805120E4 */
pa4  = -1.10894694282396677476e-01, /* 0xBFBC6398, 0x3D3E28EC */
pa5  =  3.54783043256182359371e-02, /* 0x3FA22A36, 0x599795EB */
pa6  = -2.16637559486879084300e-03, /* 0xBF61BF38, 0x0A96073F */
qa1  =  1.06420880400844228286e-01, /* 0x3FBB3E66, 0x18EEE323 */
qa2  =  5.40397917702171048937e-01, /* 0x3FE14AF0, 0x92EB6F33 */
qa3  =  7.18286544141962662868e-02, /* 0x3FB2635C, 0xD99FE9A7 */
qa4  =  1.26171219808761642112e-01, /* 0x3FC02660, 0xE763351F */
qa5  =  1.36370839120290507362e-02, /* 0x3F8BEDC2, 0x6B51DD1C */
qa6  =  1.19844998467991074170e-02, /* 0x3F888B54, 0x5735151D */
/*
 * Coefficients for approximation to  erfc in [1.25,1/0.35]
 */
ra0  = -9.86494403484714822705e-03, /* 0xBF843412, 0x600D6435 */
ra1  = -6.93858572707181764372e-01, /* 0xBFE63416, 0xE4BA7360 */
ra2  = -1.05586262253232909814e+01, /* 0xC0251E04, 0x41B0E726 */
ra3  = -6.23753324503260060396e+01, /* 0xC04F300A, 0xE4CBA38D */
ra4  = -1.62396669462573470355e+02, /* 0xC0644CB1, 0x84282266 */
ra5  = -1.84605092906711035994e+02, /* 0xC067135C, 0xEBCCABB2 */
ra6  = -8.12874355063065934246e+01, /* 0xC0545265, 0x57E4D2F2 */
ra7  = -9.81432934416914548592e+00, /* 0xC023A0EF, 0xC69AC25C */
sa1  =  1.96512716674392571292e+01, /* 0x4033A6B9, 0xBD707687 */
sa2  =  1.37657754143519042600e+02, /* 0x4061350C, 0x526AE721 */
sa3  =  4.34565877475229228821e+02, /* 0x407B290D, 0xD58A1A71 */
sa4  =  6.45387271733267880336e+02, /* 0x40842B19, 0x21EC2868 */
sa5  =  4.29008140027567833386e+02, /* 0x407AD021, 0x57700314 */
sa6  =  1.08635005541779435134e+02, /* 0x405B28A3, 0xEE48AE2C */
sa7  =  6.57024977031928170135e+00, /* 0x401A47EF, 0x8E484A93 */
sa8  = -6.04244152148580987438e-02, /* 0xBFAEEFF2, 0xEE749A62 */
/*
 * Coefficients for approximation to  erfc in [1/.35,28]
 */
rb0  = -9.86494292470009928597e-03, /* 0xBF843412, 0x39E86F4A */
rb1  = -7.99283237680523006574e-01, /* 0xBFE993BA, 0x70C285DE */
rb2  = -1.77579549177547519889e+01, /* 0xC031C209, 0x555F995A */
rb3  = -1.60636384855821916062e+02, /* 0xC064145D, 0x43C5ED98 */
rb4  = -6.37566443368389627722e+02, /* 0xC083EC88, 0x1375F228 */
rb5  = -1.02509513161107724954e+03, /* 0xC0900461, 0x6A2E5992 */
rb6  = -4.83519191608651397019e+02, /* 0xC07E384E, 0x9BDC383F */
sb1  =  3.03380607434824582924e+01, /* 0x403E568B, 0x261D5190 */
sb2  =  3.25792512996573918826e+02, /* 0x40745CAE, 0x221B9F0A */
sb3  =  1.53672958608443695994e+03, /* 0x409802EB, 0x189D5118 */
sb4  =  3.19985821950859553908e+03, /* 0x40A8FFB7, 0x688C246A */
sb5  =  2.55305040643316442583e+03, /* 0x40A3F219, 0xCEDF3BE6 */
sb6  =  4.74528541206955367215e+02, /* 0x407DA874, 0xE79FE763 */
sb7  = -2.24409524465858183362e+01; /* 0xC03670E2, 0x42712D62 */

static double ighmm_erf (double x) {
  double R,S,P,Q,s,y,z,r;
  double ax = fabs(x);
#ifdef HAVE_IEEE754
  if (!isfinite(x)) {
    if (isnan(x)) return x;     /* erf(nan)=nan */
    return (x==ax) ? 1 : -1;	/* erf(+-inf)=+-1 */
  }
#endif
  if (ax < 0.84375) {		/* |x|<0.84375 */
    if (ax < 3.7252903e-9) { 	/* |x|<2**-28 */
      if (ax < tiny)
	return 0.125*(8.0*x+efx8*x);  /*avoid underflow */
      return x + efx*x;
    }
    z = x*x;
    r = pp0+z*(pp1+z*(pp2+z*(pp3+z*pp4)));
    s = one+z*(qq1+z*(qq2+z*(qq3+z*(qq4+z*qq5))));
    y = r/s;
    return x + x*y;
  }
  if (ax < 1.25) {			/* 0.84375 <= |x| < 1.25 */
    s = ax-one;
    P = pa0+s*(pa1+s*(pa2+s*(pa3+s*(pa4+s*(pa5+s*pa6)))));
    Q = one+s*(qa1+s*(qa2+s*(qa3+s*(qa4+s*(qa5+s*qa6)))));
    if (x>=0) return erx + P/Q;
    else return -erx - P/Q;
  }
  if (ax >= 6.0) {		/* inf>|x|>=6 */
    if (x>=0) return one-tiny;
    else return tiny-one;
  }
  s = one/(x*x);
  if (ax < 2.857142857) {	/* |x| < 1/0.35 */
    R=ra0+s*(ra1+s*(ra2+s*(ra3+s*(ra4+s*(ra5+s*(ra6+s*ra7))))));
    S=one+s*(sa1+s*(sa2+s*(sa3+s*(sa4+s*(sa5+s*(sa6+s*(sa7+s*sa8)))))));
  }
  else {		/* |x| >= 1/0.35 */
    R=rb0+s*(rb1+s*(rb2+s*(rb3+s*(rb4+s*(rb5+s*rb6)))));
    S=one+s*(sb1+s*(sb2+s*(sb3+s*(sb4+s*(sb5+s*(sb6+s*sb7))))));
  }
  z  = (double)(float) ax;
  r  = exp(-z*z-0.5625)*exp((z-ax)*(z+ax)+R/S);
  if (x>=0) return one-r/ax;
  else return  r/ax-one;
}

static double ighmm_erfc (double x) {
  double R,S,P,Q,s,y,z,r;
  double ax = fabs(x);
#ifdef HAVE_IEEE754
  if (!isfinite(x)) {
    if (isnan(x)) return x;     /* erfc(nan)=nan */
    return (x==ax) ? 0 : 2;	/* erfc(+-inf)=0,2 */
  }
#endif
  if (ax < 0.84375) {		/* |x|<0.84375 */
    if (ax < 13.8777878e-18)  	/* |x|<2**-56 */
      return one-x;
    z = x*x;
    r = pp0+z*(pp1+z*(pp2+z*(pp3+z*pp4)));
    s = one+z*(qq1+z*(qq2+z*(qq3+z*(qq4+z*qq5))));
    y = r/s;
    if (ax < 0.25) {  		/* x<1/4 */
      return one-(x+x*y);
    }
    else {
      r = x*y;
      r += (x-half);
      return half - r ;
    }
  }
  if (ax < 1.25) {			/* 0.84375 <= |x| < 1.25 */
    s = fabs(x)-one;
    P = pa0+s*(pa1+s*(pa2+s*(pa3+s*(pa4+s*(pa5+s*pa6)))));
    Q = one+s*(qa1+s*(qa2+s*(qa3+s*(qa4+s*(qa5+s*qa6)))));
    if (x>=0) {
      z  = one-erx; return z - P/Q;
    }
    else {
      z = erx+P/Q; return one+z;
    }
  }
  if (ax < 28.0) {		/* |x|<28 */
    s = one/(x*x);
    if (ax < 2.857142857) {	/* |x| < 1/.35 ~ 2.857143*/
      R=ra0+s*(ra1+s*(ra2+s*(ra3+s*(ra4+s*(ra5+s*(ra6+s*ra7))))));
      S=one+s*(sa1+s*(sa2+s*(sa3+s*(sa4+s*(sa5+s*(sa6+s*(sa7+s*sa8)))))));
    }
    else {			/* |x| >= 1/.35 ~ 2.857143 */
      if (x < -6.0) return two-tiny;/* x < -6 */
      R=rb0+s*(rb1+s*(rb2+s*(rb3+s*(rb4+s*(rb5+s*rb6)))));
      S=one+s*(sb1+s*(sb2+s*(sb3+s*(sb4+s*(sb5+s*(sb6+s*sb7))))));
    }
    z  = (double)(float) ax;
    r  = exp(-z*z-0.5625)*exp((z-ax)*(z+ax)+R/S);
    if (x>0) return r/ax;
    else return two-r/ax;
  }
  else {
    if(x>0) return tiny*tiny;
    else return two-tiny;
  }
}
#endif /* check for ISO C99 */

max_stars_repo_name: ruslankuzmin/julia

max_issues_repo_name: ruslankuzmin/julia

max_forks_repo_name: ruslankuzmin/julia


text:
/* vector/gsl_vector_long_double.h
 *
 * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Gerard Jungman, Brian Gough
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or (at
 * your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 */

#ifndef __GSL_VECTOR_LONG_DOUBLE_H__
#define __GSL_VECTOR_LONG_DOUBLE_H__

#include <stdlib.h>
#include <gsl/gsl_types.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_inline.h>
#include <gsl/gsl_check_range.h>
#include <gsl/gsl_block_long_double.h>

#undef __BEGIN_DECLS
#undef __END_DECLS
#ifdef __cplusplus
# define __BEGIN_DECLS extern "C" {
# define __END_DECLS }
#else
# define __BEGIN_DECLS /* empty */
# define __END_DECLS /* empty */
#endif

__BEGIN_DECLS

typedef struct
{
  size_t size;
  size_t stride;
  long double *data;
  gsl_block_long_double *block;
  int owner;
}
gsl_vector_long_double;

typedef struct
{
  gsl_vector_long_double vector;
} _gsl_vector_long_double_view;

typedef _gsl_vector_long_double_view gsl_vector_long_double_view;

typedef struct
{
  gsl_vector_long_double vector;
} _gsl_vector_long_double_const_view;

typedef const _gsl_vector_long_double_const_view gsl_vector_long_double_const_view;

/* Allocation */

gsl_vector_long_double *gsl_vector_long_double_alloc (const size_t n);
gsl_vector_long_double *gsl_vector_long_double_calloc (const size_t n);

gsl_vector_long_double *gsl_vector_long_double_alloc_from_block (gsl_block_long_double * b,
                                                     const size_t offset,
                                                     const size_t n,
                                                     const size_t stride);

gsl_vector_long_double *gsl_vector_long_double_alloc_from_vector (gsl_vector_long_double * v,
                                                      const size_t offset,
                                                      const size_t n,
                                                      const size_t stride);

void gsl_vector_long_double_free (gsl_vector_long_double * v);

/* Views */

_gsl_vector_long_double_view
gsl_vector_long_double_view_array (long double *v, size_t n);

_gsl_vector_long_double_view
gsl_vector_long_double_view_array_with_stride (long double *base,
                                         size_t stride,
                                         size_t n);

_gsl_vector_long_double_const_view
gsl_vector_long_double_const_view_array (const long double *v, size_t n);

_gsl_vector_long_double_const_view
gsl_vector_long_double_const_view_array_with_stride (const long double *base,
                                               size_t stride,
                                               size_t n);

_gsl_vector_long_double_view
gsl_vector_long_double_subvector (gsl_vector_long_double *v,
                            size_t i,
                            size_t n);

_gsl_vector_long_double_view
gsl_vector_long_double_subvector_with_stride (gsl_vector_long_double *v,
                                        size_t i,
                                        size_t stride,
                                        size_t n);

_gsl_vector_long_double_const_view
gsl_vector_long_double_const_subvector (const gsl_vector_long_double *v,
                                  size_t i,
                                  size_t n);

_gsl_vector_long_double_const_view
gsl_vector_long_double_const_subvector_with_stride (const gsl_vector_long_double *v,
                                              size_t i,
                                              size_t stride,
                                              size_t n);

/* Operations */

void gsl_vector_long_double_set_zero (gsl_vector_long_double * v);
void gsl_vector_long_double_set_all (gsl_vector_long_double * v, long double x);
int gsl_vector_long_double_set_basis (gsl_vector_long_double * v, size_t i);

int gsl_vector_long_double_fread (FILE * stream, gsl_vector_long_double * v);
int gsl_vector_long_double_fwrite (FILE * stream, const gsl_vector_long_double * v);
int gsl_vector_long_double_fscanf (FILE * stream, gsl_vector_long_double * v);
int gsl_vector_long_double_fprintf (FILE * stream, const gsl_vector_long_double * v,
                              const char *format);

int gsl_vector_long_double_memcpy (gsl_vector_long_double * dest, const gsl_vector_long_double * src);

int gsl_vector_long_double_reverse (gsl_vector_long_double * v);

int gsl_vector_long_double_swap (gsl_vector_long_double * v, gsl_vector_long_double * w);
int gsl_vector_long_double_swap_elements (gsl_vector_long_double * v, const size_t i, const size_t j);

long double gsl_vector_long_double_max (const gsl_vector_long_double * v);
long double gsl_vector_long_double_min (const gsl_vector_long_double * v);
void gsl_vector_long_double_minmax (const gsl_vector_long_double * v, long double * min_out, long double * max_out);

size_t gsl_vector_long_double_max_index (const gsl_vector_long_double * v);
size_t gsl_vector_long_double_min_index (const gsl_vector_long_double * v);
void gsl_vector_long_double_minmax_index (const gsl_vector_long_double * v, size_t * imin, size_t * imax);

int gsl_vector_long_double_add (gsl_vector_long_double * a, const gsl_vector_long_double * b);
int gsl_vector_long_double_sub (gsl_vector_long_double * a, const gsl_vector_long_double * b);
int gsl_vector_long_double_mul (gsl_vector_long_double * a, const gsl_vector_long_double * b);
int gsl_vector_long_double_div (gsl_vector_long_double * a, const gsl_vector_long_double * b);
int gsl_vector_long_double_scale (gsl_vector_long_double * a, const long double x);
int gsl_vector_long_double_add_constant (gsl_vector_long_double * a, const long double x);
int gsl_vector_long_double_axpby (const long double alpha, const gsl_vector_long_double * x, const long double beta, gsl_vector_long_double * y);
long double gsl_vector_long_double_sum (const gsl_vector_long_double * a);

int gsl_vector_long_double_equal (const gsl_vector_long_double * u,
                            const gsl_vector_long_double * v);

int gsl_vector_long_double_isnull (const gsl_vector_long_double * v);
int gsl_vector_long_double_ispos (const gsl_vector_long_double * v);
int gsl_vector_long_double_isneg (const gsl_vector_long_double * v);
int gsl_vector_long_double_isnonneg (const gsl_vector_long_double * v);

INLINE_DECL long double gsl_vector_long_double_get (const gsl_vector_long_double * v, const size_t i);
INLINE_DECL void gsl_vector_long_double_set (gsl_vector_long_double * v, const size_t i, long double x);
INLINE_DECL long double * gsl_vector_long_double_ptr (gsl_vector_long_double * v, const size_t i);
INLINE_DECL const long double * gsl_vector_long_double_const_ptr (const gsl_vector_long_double * v, const size_t i);

#ifdef HAVE_INLINE

INLINE_FUN
long double
gsl_vector_long_double_get (const gsl_vector_long_double * v, const size_t i)
{
#if GSL_RANGE_CHECK
  if (GSL_RANGE_COND(i >= v->size))
    {
      GSL_ERROR_VAL ("index out of range", GSL_EINVAL, 0);
    }
#endif
  return v->data[i * v->stride];
}

INLINE_FUN
void
gsl_vector_long_double_set (gsl_vector_long_double * v, const size_t i, long double x)
{
#if GSL_RANGE_CHECK
  if (GSL_RANGE_COND(i >= v->size))
    {
      GSL_ERROR_VOID ("index out of range", GSL_EINVAL);
    }
#endif
  v->data[i * v->stride] = x;
}

INLINE_FUN
long double *
gsl_vector_long_double_ptr (gsl_vector_long_double * v, const size_t i)
{
#if GSL_RANGE_CHECK
  if (GSL_RANGE_COND(i >= v->size))
    {
      GSL_ERROR_NULL ("index out of range", GSL_EINVAL);
    }
#endif
  return (long double *) (v->data + i * v->stride);
}

INLINE_FUN
const long double *
gsl_vector_long_double_const_ptr (const gsl_vector_long_double * v, const size_t i)
{
#if GSL_RANGE_CHECK
  if (GSL_RANGE_COND(i >= v->size))
    {
      GSL_ERROR_NULL ("index out of range", GSL_EINVAL);
    }
#endif
  return (const long double *) (v->data + i * v->stride);
}
#endif /* HAVE_INLINE */

__END_DECLS

#endif /* __GSL_VECTOR_LONG_DOUBLE_H__ */

ext: h

max_stars_repo_name: shakfu/pd-psl

max_issues_repo_name: shakfu/pd-psl

max_forks_repo_name: shakfu/pd-psl


text:
/**
 * @file optimizers.h
 * @author Carl Boettiger <cboettig@gmail.com>
 * @date 22 April 2011
 *
 * @section LICENSE
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or (at
 * your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 */

#include <gsl/gsl_math.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_randist.h>
#include <gsl/gsl_siman.h>

/* set up parameters for this simulated annealing run */
#define N_TRIES 200     	/* how many points do we try before stepping */
#define ITERS_FIXED_T 200	/* how many iterations for each T? */
#define STEP_SIZE .02 		/* max step size in random walk */
#define K 1.0				/* Boltzmann constant */
#define T_INITIAL 0.05		/* initial temperature */
#define MU_T 1.004		    /* damping factor for temperature */
#define T_MIN .008

/* setup parameters for multimin method*/
#define INIT_STEP .2
#define MAX_ITER 10000
#define ERR_TOL 1e-8
#define PRINT 1
#include <gsl/gsl_multimin.h>

double optim_func (const gsl_vector *v, void *params);
double multimin(gsl_vector *x, void * params);
double siman(gsl_vector * x, void * params, gsl_rng * rng);

max_stars_repo_name: cboettig/wrightscape

max_issues_repo_name: cboettig/wrightscape

max_forks_repo_name: cboettig/wrightscape


text:
#ifndef __GSL_MATRIX_H__
#define __GSL_MATRIX_H__

#include <gsl/gsl_matrix_complex_long_double.h>
#include <gsl/gsl_matrix_complex_double.h>
#include <gsl/gsl_matrix_complex_float.h>

#include <gsl/gsl_matrix_long_double.h>
#include <gsl/gsl_matrix_double.h>
#include <gsl/gsl_matrix_float.h>

#include <gsl/gsl_matrix_ulong.h>
#include <gsl/gsl_matrix_long.h>

#include <gsl/gsl_matrix_uint.h>
#include <gsl/gsl_matrix_int.h>

#include <gsl/gsl_matrix_ushort.h>
#include <gsl/gsl_matrix_short.h>

#include <gsl/gsl_matrix_uchar.h>
#include <gsl/gsl_matrix_char.h>

#endif /* __GSL_MATRIX_H__ */

max_stars_repo_name: ielomariala/Hex-Game

max_issues_repo_name: ielomariala/Hex-Game

max_forks_repo_name: ielomariala/Hex-Game


text:
/* Compile with:
export LDLIBS="`pkg-config --libs gsl`"
export CFLAGS="`pkg-config --cflags gsl` -g -Wall -std=gnu11 -O3"
make gsl_erf
*/
#include <gsl/gsl_cdf.h>
#include <stdio.h>

int main(){
    double bottom_tail = gsl_cdf_gaussian_P(-1.96, 1);
    printf("Area between [-1.96, 1.96]: %g\n", 1-2*bottom_tail);
}

ext: c

max_stars_repo_name: catalingheorghe/learning-activities

max_issues_repo_name: catalingheorghe/learning-activities

max_forks_repo_name: catalingheorghe/learning-activities


text:
// TRENTO: Reduced Thickness Event-by-event Nuclear Topology
// Copyright 2015 Jonah E. Bernhard, J. Scott Moreland
// TRENTO3D: Three-dimensional extension of TRENTO by Weiyao Ke
// MIT License

#ifndef ETA_H
#define ETA_H

#include <cmath>
#include <vector>
#include <gsl/gsl_fft_complex.h>

/// GSL fft of complex array, z_i = x_i + j*y_i
/// data are stored in one real array A that A[2i] = x_i and A[2i+1] = y_i
#define REAL(z,i) ((z)[2*(i)])
#define IMAG(z,i) ((z)[2*(i)+1])

double const sqrt2 = std::sqrt(2);
constexpr double TINY = 1e-12;
constexpr int relative_skew_switch = 1;
constexpr int absolute_skew_switch = 2;
/// the mean of the rapidity distribution as function of Ta(x,y),
/// Tb(x,y) and exp(y_beam).
/// For the case both Ta and Tb are tiny small, mean = 0.0 is returned.
/// For the case only Ta(Tb) = 0, it returns +(-)y_beam,
/// For the case y_beam >> 1, mean ~ 0.5*log(Ta/Tb)
double inline mean_function(double ta, double tb, double exp_ybeam){
  if (ta < TINY && tb < TINY) return 0.;
  return 0.5 * std::log((ta*exp_ybeam + tb/exp_ybeam) / std::max(ta/exp_ybeam + tb*exp_ybeam, TINY));
}

/// The coefficient of normalized width of the rapidity distribution
/// Currently, it is simply a constant independent of Ta(x,y) and Tb(x,y)
double inline std_function(double ta, double tb){
  (void)ta;
  (void)tb;
  return 1.;
}

/// The normalized skewness as function of Ta(x,y) and Tb(x,y)

double inline skew_function(double ta, double tb, int type_switch){
  if (type_switch == relative_skew_switch)
    return (ta - tb)/std::max(ta + tb, TINY);
  else if(type_switch == absolute_skew_switch)
      return ta-tb;
  else return 0.;
}

/// A fast pseudorapidity to rapidity transformer using pretabulated values
/// It returns the transfoamtion y(eta) and the jacobian dy/deta(eta)
class fast_eta2y {
private:
  double etamax_;
  double deta_;
  std::size_t neta_;
  std::vector<double> y_;
  std::vector<double> dydeta_;
public:
  fast_eta2y(double J, double etamax, double deta)
      : etamax_(etamax),
        deta_(deta),
        neta_(std::ceil(2.*etamax_/(deta_+1e-15))+1),
        y_(neta_, 0.),
        dydeta_(neta_, 0.) {

    for (std::size_t ieta = 0; ieta < neta_; ++ieta) {
      double eta = -etamax_ + ieta*deta_;
      double Jsh = J*std::sinh(eta);
      double sq = std::sqrt(1. + Jsh*Jsh);
      y_[ieta] = std::log(sq + Jsh);
      dydeta_[ieta] = J*std::cosh(eta)/sq;
    }
  }

  double rapidity(double eta){
    double steps = (eta + etamax_)/deta_;
    double xi = std::fmod(steps, 1.);
    std::size_t index = std::floor(steps);
    return y_[index]*(1. - xi) + y_[index+1]*xi;
  }

  double Jacobian(double eta){
    double steps = (eta + etamax_)/deta_;
    double xi = std::fmod(steps, 1.);
    std::size_t index = std::floor(steps);
    return dydeta_[index]*(1. - xi) + dydeta_[index+1]*xi;
  }

};

/// A class for cumulant generating function inversion
/// This class handles inverse fourier transform the cumulant generating function
/// A direct transformation F^{-1} exp(i*m*k-(std*k)^2/2-skew*(std*k)^3/6) results
/// in an ill-behaved function. Instead, skew is replaced by skew*exp(-(std*k)^2/2).
/// In this way higher order cumulant are included to regulated the function.
/// The reconstruction range is taken to be [-3.33, 3.33]*std, which does not
/// seem to be very large, however, by trail and error, this range elimiates
/// oscillations at large rapidity and leaves the details close to mid-rapidity
/// unchanged. We used GSL FFT library (more specialized library would be FFTW,
/// e.g.), with 256 points. The transformed results are stored and interpolated.
class cumulant_generating{
private:
  size_t const N;
  double * data, * dsdy;
  double eta_max;
  double deta;
  double center;

public:
  cumulant_generating(): N(256), data(new double[2*N]), dsdy(new double[2*N]){};

  /// This function set the mean, std and skew of the profile and use FFT to
  /// transform cumulant generating function at zero mean.
  void calculate_dsdy(double mean, double std, double skew){
    double k1, k2, k3, amp, arg;
    // adaptive eta_max = 3.33*std;
    center = mean;
    eta_max = std*3.33;
    deta = 2.*eta_max/(N-1.);
    double fftmean = eta_max/std;
      for(size_t i=0;i<N;i++){
          k1 = M_PI*(i-N/2.0)/eta_max*std;
      k2 = k1*k1;
      k3 = k2*k1;

          amp = std::exp(-k2/2.0);
          arg = fftmean*k1+skew/6.0*k3*amp;

      REAL(data,i) = amp*std::cos(arg);
          IMAG(data,i) = amp*std::sin(arg);
      }
       gsl_fft_complex_radix2_forward(data, 1, N);

      for(size_t i=0;i<N;i++){
          dsdy[i] = REAL(data,i)*(2.0*static_cast<double>(i%2 == 0)-1.0);
      }
  }

  /// When interpolating the funtion, the mean is put back by simply shifting
  /// the function by y = y - mean + dy/2, the last term is correcting for
  /// interpolating bin edge instead of bin center
  double interp_dsdy(double y){
    y = y-center+deta/2.;
    if (y < -eta_max || y >= eta_max) return 0.0;
    double xy = (y+eta_max)/deta;
    size_t iy = std::floor(xy);
    double ry = xy-iy;
    return dsdy[iy]*(1.-ry) + dsdy[iy+1]*ry;
  }
};
#endif

max_stars_repo_name: K-JW/trento

max_issues_repo_name: K-JW/trento

max_forks_repo_name: K-JW/trento


text:
//
// @author raver119@gmail.com
//

#ifndef LIBND4J_GEMM_H
#define LIBND4J_GEMM_H

#include <cblas.h>
#include <templatemath.h>

namespace nd4j {
     namespace blas {

        template <typename T>
        class GEMM {
        protected:
            static inline int linearIndexC(int rows, int cols, int r, int c);
            static inline int linearIndexF(int rows, int cols, int r, int c);
            static T* transpose(int orderSource, int orderTarget, int rows, int cols, T *source);

        public:
            static void op(int Order, int TransA, int TransB, int M, int N, int K, T alpha, T *A, int lda, T *B, int ldb, T beta, T *C, int ldc);
        };

         template <typename T>
         class GEMV : public nd4j::blas::GEMM<T>{

         public:
             static void op(int TRANS, int M, int N, T alpha, T* A, int lda, T* X, int incx, T beta, T* Y, int incy );
         };
    }
}

#endif //LIBND4J_GEMM_H


text:
/**
  * 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 <cblas.h>
#include "ConjugateGradientSolver.h"
#include <time.h>

/* Include redundant execution header. */
#include "../../../include/ourRMTlib.h"

int ipow(int base, int exp)
{
    int result = 1;
    for (;;)
    {
        if (exp & 1)
            result *= base;
        exp >>= 1;
        if (!exp)
            break;
        base *= base;
    }

    return result;
}

int ConjugateGradientSolver(unsigned long *II, unsigned long *J, double *A, unsigned long M, unsigned long N,
	unsigned long long nz, double *b, unsigned long M_Vector, unsigned long N_Vector, unsigned long long nz_vector,
	double *x, int iterationNumber, int F, int *ret_code) {

	//A*x=b

        double *Ap=(double *) malloc(nz_vector * sizeof(double));
        double *r=(double *) malloc(nz_vector * sizeof(double));
        double *p=(double *) malloc(nz_vector * sizeof(double));

	//double *x=(double *) calloc(nz_vector,sizeof(double));

	//r = b-A*x
	//If we take x=0 the init multiplication is avoided and r=b

	memcpy(r, b, N*sizeof(double));

	//p=r

	memcpy(p, r, N*sizeof(double));

	//rsold = r'*r
	double rsold = cblas_ddot(N,r,1,r,1);
	double rs_0 = cblas_ddot(N,r,1,r,1);

	int stop = 0;

	double alphaCG = 0.0;

	double rsnew = 0.0, rsnew2 = 0.0;
	unsigned long k = 0, selfCG_k=0;

	unsigned long maxIterations = M*2;

	if(iterationNumber != 0 ){
		maxIterations = iterationNumber;
	}

	int flag=0;

	while(!stop){

		//if( ((k+1) % F == 0) ){ //execute CG reliably
		//if(k == pow((double)F, (double)(selfCG_k+1))){
		if(k == ipow(F, (selfCG_k+1))){
				//fprintf(stderr, "F:%d k:%lu selfCG_k:%lu \n",F,k, selfCG_k);

				//Ap=A*p
				cblas_dgemv(CblasRowMajor, CblasNoTrans, M,N , 1.0, A, N, p, 1, 0.0, Ap, 1);

				//r=A*x
				cblas_dgemv(CblasRowMajor, CblasNoTrans, M,N , 1.0, A, N, x, 1, 0.0, r, 1);

				//r=b-r
				cblas_dscal(N, -1, r, 1); //r = -r
				cblas_daxpy(N, 1, b, 1, r, 1); //r = r + b

				//alphaCG=r'*p /(p'*Ap)
				alphaCG = cblas_ddot(N,r,1,p,1)/cblas_ddot(N,p,1,Ap,1);

				//x=x+alphaCG*p
				cblas_daxpy(N,alphaCG,p,1,x,1);

				//r=r-alphaCG*Ap
				cblas_daxpy(N,-alphaCG,Ap,1,r,1);

				//rsnew = r'*r
				rsnew = cblas_ddot(N,r,1,r,1);

				//fprintf(stderr, "k:%ld F_iteration:%ld alphaCG:%.10f error:%.10f\n",k,selfCG_k,alphaCG, sqrt(rsnew));

				// p=r+((-r'*Ap/(p'*Ap))*p)
				cblas_dscal(N, -(cblas_ddot(N,r,1,Ap,1)/cblas_ddot(N,p,1,Ap,1)), p, 1);
				cblas_daxpy(N,1.0,r,1,p,1);

				selfCG_k++;
				flag=0;

		}else{

				//Ap=A*p

				cblas_dgemv(CblasRowMajor, CblasNoTrans, M,N , 1.0, A, N, p, 1, 0.0, Ap, 1);

				//alphaCG=rsold/(p'*Ap)
				alphaCG = rsold/cblas_ddot(N,p,1,Ap,1);

				//x=x+alphaCG*p
				cblas_daxpy(N,alphaCG,p,1,x,1);

				//r=r-alphaCG*Ap
				cblas_daxpy(N,-alphaCG,Ap,1,r,1);

				//rsnew = r'*r
				rsnew = cblas_ddot(N,r,1,r,1);
				//fprintf(stderr, "k:%ld  alphaCG:%.10f error:%.10f\n",k,alphaCG, sqrt(rsnew));

				//p=r+rsnew/rsold*p
				cblas_dscal(N, rsnew/rsold, p, 1);
				cblas_daxpy(N,1.0,r,1,p,1);

				rsold = rsnew;

				if(isnan(alphaCG)){ //checking whether alphaCG is nan!
					fprintf(stderr, "!!! alphaCG:%.10f\n", alphaCG);
					exit(-1);
				}
		}
		k++;

		//if((sqrt(rsnew)<=EPSILON)||(k == maxIterations)){
		if(sqrt(rsnew)/sqrt(rs_0)<=EPSILON){
			stop = 1;
			fprintf(stderr, "STOPPED by CG\n");
		}

	}

	//memcpy(b, x, N*sizeof(double));

        free(Ap);
        free(r);
        free(p);
	//free(x);

	fprintf(stderr, "[%s] Number of total iterations: %lu Number of iterations in SS step:%lu \n",__func__,k, selfCG_k);

    *ret_code=1;
	return 1;
}

max_stars_repo_name: sanemarslan/RMTLib

max_issues_repo_name: sanemarslan/RMTLib

max_forks_repo_name: sanemarslan/RMTLib


text:
//
// Created by be107admin on 9/25/17.
//

#ifndef CIMPLE_GSL_LIBRARY_CIMPLE_EXTENSION_H
#define CIMPLE_GSL_LIBRARY_CIMPLE_EXTENSION_H

#include <gsl/gsl_blas.h>
#include <gurobi_c.h>

////////////////////////////////////////////////////////////////////////////////
// @fn gsl_matrix_from_array()
// @brief Converts an array to a gsl matrix
// @param gsl_matrix *matrix
// @param double *array
////////////////////////////////////////////////////////////////////////////////
void gsl_matrix_from_array(gsl_matrix *matrix,double *array, char* name);

////////////////////////////////////////////////////////////////////////////////
// @fn gsl_vector_from_array()
// @brief Converts an array to a gsl vector
// @param gsl_matrix *matrix
// @param double *array
////////////////////////////////////////////////////////////////////////////////
void gsl_vector_from_array(gsl_vector *vector, double *array, char* name);

////////////////////////////////////////////////////////////////////////////////
// @fn gsl_matrix_print()
// @brief Prints a gsl matrix readable to the output
// @param gsl_matrix *matrix
// @param char *name
////////////////////////////////////////////////////////////////////////////////
void gsl_matrix_print(gsl_matrix *matrix, char *name);

////////////////////////////////////////////////////////////////////////////////
// @fn gsl_vector_print()
// @brief Prints a gsl vector readable to the output
// @param gsl_matrix *matrix
// @param char *name
////////////////////////////////////////////////////////////////////////////////
void gsl_vector_print(gsl_vector *vector, char *name);

gsl_matrix * gsl_matrix_diag_from_vector(gsl_vector * X, double rest);

int gsl_matrix_to_qpterm_gurobi(gsl_matrix *P, GRBmodel *model, size_t N);

int gsl_vector_to_linterm_gurobi(gsl_vector *q, GRBmodel *model, size_t N);

#endif //CIMPLE_GSL_LIBRARY_CIMPLE_EXTENSION_H

max_stars_repo_name: shaesaert/TuLiPXML

max_issues_repo_name: shaesaert/TuLiPXML

max_forks_repo_name: shaesaert/TuLiPXML


text:
#ifndef OPERATOR_H
#define OPERATOR_H

#include <chrono>
#include <iostream>
#include <utility>
#include <vector>
#include <memory>
#include <string>
#include <sstream>

#include <gsl/gsl_matrix.h>
#include <gsl/gsl_spmatrix.h>
#include <gsl/gsl_splinalg.h>

#include "constants.h"

using std::array;
using std::pair;
using std::shared_ptr;
using std::tuple;
using std::vector;
using std::string;

// Smart pointer to matrix
using mat_operator = shared_ptr<gsl_spmatrix>;

// Shorthand for template types
using ComputeStatus = vector<pair<size_t, std::string>>;
using ListCmu = const vector<mat_operator>;
using VecPair = pair<gsl_vector *, gsl_vector *>;
using VecTriplet = tuple<gsl_vector *, gsl_vector *, gsl_vector *>;

// Generate operator L
gsl_matrix *computeL();

// Generate operator C
void computeC();

gsl_spmatrix *computeSingleC(size_t mu);

void findValidCs(vector<bool>& toStore);

void setFilenames(string& raw, string& compressed, size_t mu);

gsl_spmatrix *loadMat(size_t mu);
void storeMat(const gsl_spmatrix *C_mu, size_t mu);

#endif // OPERATOR_H

max_stars_repo_name: ichi-rika/glottal-inverse

max_issues_repo_name: ichi-rika/glottal-inverse

max_forks_repo_name: ichi-rika/glottal-inverse


text:
/**
 *
 * @file core_sgetrf_rectil.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 Piotr Luszczek
 * @date 2009-11-15
 *
 * @generated s Tue Jan  7 11:44:48 2014
 *
 **/

#include <math.h>
#include <cblas.h>
#include <lapacke.h>
#include "common.h"

#define A(m, n) BLKADDR(A, float, m, n)

void
CORE_sgetrf_rectil_init(void);

static inline void
CORE_sgetrf_rectil_rec(const PLASMA_desc A, int *IPIV, int *info,
                       float *pivot,
                       int thidx,  int thcnt,
                       int column, int width,
                       int ft,     int lt);
static inline void
CORE_sgetrf_rectil_update(const PLASMA_desc A, int *IPIV,
                          int column, int n1,     int n2,
                          int thidx,  int thcnt,
                          int ft,     int lt);

/***************************************************************************//**
 *
 * @ingroup CORE_float
 *
 *  CORE_sgetrf_rectil computes a LU factorization of a general M-by-N
 *  matrix A stored in CCRB layout using partial pivoting with row
 *  interchanges.
 *
 *  The factorization has the form
 *
 *    A = P * L * U
 *
 *  where P is a permutation matrix, L is lower triangular with unit
 *  diagonal elements (lower trapezoidal if m > n), and U is upper
 *  triangular (upper trapezoidal if m < n).
 *
 *  This is the recursive version of the algorithm applied on tile layout.
 *
 *  WARNINGS:
 *     - The function CORE_sgetrf_rectil_init has to be called prior
 *     to any call to this function.
 *     - You cannot call this kernel on different matrices at the same
 *     time.
 *     - The matrix A cannot be more than one tile wide.
 *     - The number of threads calling this function has to be excatly
 *     the number defined by info[2] with each one of them a different
 *     index between 0 included and info[2] excluded.
 *
 *******************************************************************************
 *
 *  @param[in,out] A
 *          PLASMA descriptor of the matrix A to be factorized.
 *          On entry, the M-by-N matrix to be factorized.
 *          On exit, the factors L and U from the factorization
 *          A = P*L*U; the unit diagonal elements of L are not stored.
 *
 *  @param[out] IPIV
 *          The pivot indices; for 0 <= i < min(M,N) stored in Fortran
 *          mode (starting at 1), row i of the matrix was interchanged
 *          with row IPIV(i).
 *          On exit, each value IPIV[i] for 0 <= i < min(M,N) is
 *          increased by A.i, which means A.i < IPIV[i] <= A.i+M.
 *
 *  @param[in,out] info
 *          Array of 3 integers.
 *          - info[0], see returned value
 *          - info[1], is the thread index 0 <= info[0] < info[2]
 *          - info[2], on entry is the number of threads trying to
 *                     participate to the factorization,
 *                     on exit is the real number of threads used to
 *                     perform the factorization.
 *    Info[2] threads, and exactly info[2], have to call this function
 *    to avoid dead lock.
 *
 *******************************************************************************
 *
 * @return
 *          \retval PLASMA_SUCCESS successful exit
 *          \retval -k, the k-th argument had an illegal value
 *          \retval k if U(k,k) is exactly zero. The factorization
 *                  has been completed, but the factor U is exactly
 *                  singular, and division by zero will occur if it is used
 *                  to solve a system of equations.
 *
 */
#if defined(PLASMA_HAVE_WEAK)
#pragma weak CORE_sgetrf_rectil = PCORE_sgetrf_rectil
#define CORE_sgetrf_rectil PCORE_sgetrf_rectil
#endif
int CORE_sgetrf_rectil(const PLASMA_desc A, int *IPIV, int *info)
{
    int ft, lt;
    int thidx = info[1];
    int thcnt = min( info[2], A.mt );
    int minMN = min( A.m, A.n );
    float pivot;

    info[0] = 0;
    info[2] = thcnt;

    if ( A.nt > 1 ) {
        coreblas_error(1, "Illegal value of A.nt");
        info[0] = -1;
        return -1;
    }

    if ( thidx >= thcnt )
      return 0;

    int q = A.mt / thcnt;
    int r = A.mt % thcnt;

    if (thidx < r) {
        q++;
        ft = thidx * q;
        lt = ft + q;
    } else {
        ft = r * (q + 1) + (thidx - r) * q;
        lt = ft + q;
        lt = min( lt, A.mt );
    }

    CORE_sgetrf_rectil_rec( A, IPIV, info, &pivot,
                            thidx, thcnt, 0, minMN, ft, lt);

    if ( A.n > minMN ) {
        CORE_sgetrf_rectil_update( A, IPIV,
                                   0, minMN, A.n-minMN,
                                   thidx, thcnt,
                                   ft, lt);
    }

    return info[0];
}

/*******************************************************************
 *   Additional routines
 */
#define AMAX1BUF_SIZE (48 << 1)

/* 48 threads should be enough for everybody */
static volatile float CORE_samax1buf[AMAX1BUF_SIZE];
static float sfmin;

void
CORE_sgetrf_rectil_init(void)
{
    int i;
    for (i = 0; i < AMAX1BUF_SIZE; ++i) CORE_samax1buf[i] = -1.0;
    sfmin =  LAPACKE_slamch_work('S');
}

static void
CORE_samax1_thread(float localamx,
                   int thidx, int thcnt, int *thwinner,
                   float *diagvalue,
                   float *globalamx,
                   int pividx, int *ipiv)
{
    if (thidx == 0) {
        int i, j = 0;
        float curval = localamx, tmp;
        float curamx = fabsf(localamx);

        /* make sure everybody filled in their value */
        for (i = 1; i < thcnt; ++i) {
            while (CORE_samax1buf[i << 1] == -1.0) { /* wait for thread i to store its value */
            }
        }

        /* better not fuse the loop above and below to make sure data is sync'd */

        for (i = 1; i < thcnt; ++i) {
            tmp = CORE_samax1buf[ (i << 1) + 1];
            if (fabsf(tmp) > curamx) {
                curamx = fabsf(tmp);
                curval = tmp;
                j = i;
            }
        }

        if (0 == j)
            ipiv[0] = pividx;

        /* make sure everybody knows the amax value */
        for (i = 1; i < thcnt; ++i)
            CORE_samax1buf[ (i << 1) + 1] = curval;

        CORE_samax1buf[0] = -j - 2.0; /* set the index of the winning thread */
        CORE_samax1buf[1] = *diagvalue; /* set the index of the winning thread */

        *thwinner = j;
        *globalamx = curval;

        for (i = 1; i < thcnt; ++i)
            CORE_samax1buf[i << 1] = -3.0;

        /* make sure everybody read the max value */
        for (i = 1; i < thcnt; ++i) {
            while (CORE_samax1buf[i << 1] != -1.0) {
            }
        }

        CORE_samax1buf[0] = -1.0;
    } else {
        CORE_samax1buf[(thidx << 1) + 1] = localamx;
        CORE_samax1buf[thidx << 1] = -2.0;  /* announce to thread 0 that local amax was stored */
        while (CORE_samax1buf[0] == -1.0) { /* wait for thread 0 to finish calculating the global amax */
        }
        while (CORE_samax1buf[thidx << 1] != -3.0) { /* wait for thread 0 to store amax */
        }
        *thwinner  = -CORE_samax1buf[0] - 2.0;
        *diagvalue = CORE_samax1buf[1];
        *globalamx = CORE_samax1buf[(thidx << 1) + 1]; /* read the amax from the location adjacent to the one in the above loop */
        CORE_samax1buf[thidx << 1] = -1.0;  /* signal thread 0 that this thread is done reading */

        if (thidx == *thwinner)
            ipiv[0] = pividx;

        while (CORE_samax1buf[0] != -1.0) { /* wait for thread 0 to finish */
        }
    }
}

static void
CORE_sbarrier_thread(int thidx,
                     int thcnt)
{
    int idum1, idum2;
    float ddum1 = 0.;
    float ddum2 = 0.;
    /* it's probably faster to implement a dedicated barrier */
    CORE_samax1_thread( 1.0, thidx, thcnt, &idum1, &ddum1, &ddum2, 0, &idum2 );
}

static inline void
CORE_sgetrf_rectil_update(const PLASMA_desc A, int *IPIV,
                          int column, int n1,     int n2,
                          int thidx,  int thcnt,
                          int ft,     int lt)
{
    int ld, lm, tmpM;
    int ip, j, it, i, ldft;
    float zone  = 1.0;
    float mzone = -1.0;
    float *Atop, *Atop2, *U, *L;
    int offset = A.i;

    ldft = BLKLDD(A, 0);
    Atop  = A(0, 0) + column * ldft;
    Atop2 = Atop    + n1     * ldft;

    if (thidx == 0)
    {
        /* Swap to the right */
        int *lipiv = IPIV+column;
        int idxMax = column+n1;
        for (j = column; j < idxMax; ++j, ++lipiv) {
            ip = (*lipiv) - offset - 1;
            if ( ip != j )
            {
                it = ip / A.mb;
                i  = ip % A.mb;
                ld = BLKLDD(A, it);
                cblas_sswap(n2, Atop2                     + j, ldft,
                            A(it, 0) + (column+n1)*ld + i, ld   );
            }
        }

        /* Trsm on the upper part */
        U = Atop2 + column;
        cblas_strsm( CblasColMajor, CblasLeft, CblasLower,
                     CblasNoTrans, CblasUnit,
                     n1, n2, (zone),
                     Atop  + column, ldft,
                     U,              ldft );

        /* Signal to other threads that they can start update */
        CORE_sbarrier_thread( thidx, thcnt );

        /* First tile */
        L = Atop + column + n1;
        tmpM = min(ldft, A.m) - column - n1;

        /* Apply the GEMM */
        cblas_sgemm( CblasColMajor, CblasNoTrans, CblasNoTrans,
                     tmpM, n2, n1,
                     (mzone), L,      ldft,
                     U,      ldft,
                     (zone),  U + n1, ldft );

    }
    else
    {
        ld = BLKLDD( A, ft );
        L  = A( ft, 0 ) + column * ld;
        lm = ft == A.mt-1 ? A.m - ft * A.mb : A.mb;

        U = Atop2 + column;

        /* Wait for pivoting and triangular solve to be finished
         * before to really start the update */
        CORE_sbarrier_thread( thidx, thcnt );

        /* First tile */
        /* Apply the GEMM */
        cblas_sgemm( CblasColMajor, CblasNoTrans, CblasNoTrans,
                     lm, n2, n1,
                     (mzone), L,         ld,
                                         U,         ldft,
                     (zone),  L + n1*ld, ld );
    }

    /* Update the other blocks */
    for( it = ft+1; it < lt; it++)
    {
        ld = BLKLDD( A, it );
        L  = A( it, 0 ) + column * ld;
        lm = it == A.mt-1 ? A.m - it * A.mb : A.mb;

        /* Apply the GEMM */
        cblas_sgemm( CblasColMajor, CblasNoTrans, CblasNoTrans,
                     lm, n2, n1,
                     (mzone), L,          ld,
                                         U,          ldft,
                     (zone),  L + n1*ld,  ld );
    }
}

static void
CORE_sgetrf_rectil_rec(const PLASMA_desc A, int *IPIV, int *info,
                       float *pivot,
                       int thidx,  int thcnt,
                       int column, int width,
                       int ft,     int lt)
{
    int ld, jp, n1, n2, lm, tmpM, piv_sf;
    int ip, j, it, i, ldft;
    int max_i, max_it, thwin;
    float zone  = 1.0;
    float mzone = -1.0;
    float tmp1;
    float tmp2 = 0.;
    float pivval;
    float *Atop, *Atop2, *U, *L;
    float             abstmp1;
    int offset = A.i;

    ldft = BLKLDD(A, 0);
    Atop = A(0, 0) + column * ldft;

    if ( width > 1 ) {
        /* Assumption: N = min( M, N ); */
        n1 = width / 2;
        n2 = width - n1;

        Atop2 = Atop + n1 * ldft;

        CORE_sgetrf_rectil_rec( A, IPIV, info, pivot,
                                thidx, thcnt, column, n1, ft, lt );

        if ( *info != 0 )
            return;

        if (thidx == 0)
        {
            /* Swap to the right */
            int *lipiv = IPIV+column;
            int idxMax = column+n1;
            for (j = column; j < idxMax; ++j, ++lipiv) {
                ip = (*lipiv) - offset - 1;
                if ( ip != j )
                {
                    it = ip / A.mb;
                    i  = ip % A.mb;
                    ld = BLKLDD(A, it);
                    cblas_sswap(n2, Atop2                     + j, ldft,
                                    A(it, 0) + (column+n1)*ld + i, ld   );
                }
            }
            /* Trsm on the upper part */
            U = Atop2 + column;
            cblas_strsm( CblasColMajor, CblasLeft, CblasLower,
                         CblasNoTrans, CblasUnit,
                         n1, n2, (zone),
                         Atop  + column, ldft,
                         U,              ldft );

            /* SIgnal to other threads that they can start update */
            CORE_sbarrier_thread( thidx, thcnt );
            pivval = *pivot;
            if ( pivval == 0.0 ) {
                *info = column+n1;
                return;
            } else {
                if ( fabsf(pivval) >= sfmin ) {
                    piv_sf = 1;
                    pivval = 1.0 / pivval;
                } else {
                    piv_sf = 0;
                }
            }

            /* First tile */
            {
                L = Atop + column + n1;
                tmpM = min(ldft, A.m) - column - n1;

                /* Scale last column of L */
                if ( piv_sf ) {
                    cblas_sscal( tmpM, (pivval), L+(n1-1)*ldft, 1 );
                } else {
                    int i;
                    Atop2 = L+(n1-1)*ldft;
                    for( i=0; i < tmpM; i++, Atop2++)
                        *Atop2 = *Atop2 / pivval;
                }

                /* Apply the GEMM */
                cblas_sgemm( CblasColMajor, CblasNoTrans, CblasNoTrans,
                             tmpM, n2, n1,
                             (mzone), L,      ldft,
                                                 U,      ldft,
                             (zone),  U + n1, ldft );

                /* Search Max in first column of U+n1 */
                tmp2    = U[n1];
                max_it  = ft;
                max_i   = cblas_isamax( tmpM, U+n1, 1 ) + n1;
                tmp1    = U[max_i];
                abstmp1 = fabsf(tmp1);
                max_i   += column;
            }
        }
        else
        {
            pivval = *pivot;
            if ( pivval == 0.0 ) {
                *info = column+n1;
                return;
            } else {
                if ( fabsf(pivval) >= sfmin ) {
                    piv_sf = 1;
                    pivval = 1.0 / pivval;
                } else {
                    piv_sf = 0;
                }
            }

            ld = BLKLDD( A, ft );
            L  = A( ft, 0 ) + column * ld;
            lm = ft == A.mt-1 ? A.m - ft * A.mb : A.mb;

            U = Atop2 + column;

            /* First tile */
            /* Scale last column of L */
            if ( piv_sf ) {
                cblas_sscal( lm, (pivval), L+(n1-1)*ld, 1 );
            } else {
                int i;
                Atop2 = L+(n1-1)*ld;
                for( i=0; i < lm; i++, Atop2++)
                    *Atop2 = *Atop2 / pivval;
            }

            /* Wait for pivoting and triangular solve to be finished
             * before to really start the update */
            CORE_sbarrier_thread( thidx, thcnt );

            /* Apply the GEMM */
            cblas_sgemm( CblasColMajor, CblasNoTrans, CblasNoTrans,
                         lm, n2, n1,
                         (mzone), L,         ld,
                                             U,         ldft,
                         (zone),  L + n1*ld, ld );

            /* Search Max in first column of L+n1*ld */
            max_it  = ft;
            max_i   = cblas_isamax( lm, L+n1*ld, 1 );
            tmp1    = L[n1*ld+max_i];
            abstmp1 = fabsf(tmp1);
        }

        /* Update the other blocks */
        for( it = ft+1; it < lt; it++)
        {
            ld = BLKLDD( A, it );
            L  = A( it, 0 ) + column * ld;
            lm = it == A.mt-1 ? A.m - it * A.mb : A.mb;

            /* Scale last column of L */
            if ( piv_sf ) {
                cblas_sscal( lm, (pivval), L+(n1-1)*ld, 1 );
            } else {
                int i;
                Atop2 = L+(n1-1)*ld;
                for( i=0; i < lm; i++, Atop2++)
                    *Atop2 = *Atop2 / pivval;
            }

            /* Apply the GEMM */
            cblas_sgemm( CblasColMajor, CblasNoTrans, CblasNoTrans,
                         lm, n2, n1,
                         (mzone), L,          ld,
                                             U,          ldft,
                         (zone),  L + n1*ld,  ld );

            /* Search the max on the first column of L+n1*ld */
            jp = cblas_isamax( lm, L+n1*ld, 1 );
            if ( fabsf( L[n1*ld+jp] ) > abstmp1 ) {
                tmp1 = L[n1*ld+jp];
                abstmp1 = fabsf(tmp1);
                max_i  = jp;
                max_it = it;
            }
        }

        jp = offset + max_it*A.mb + max_i;
        CORE_samax1_thread( tmp1, thidx, thcnt, &thwin,
                            &tmp2, pivot, jp + 1, IPIV + column + n1 );

        if ( thidx == 0 ) {
            U[n1] = *pivot; /* all threads have the pivot element: no need for synchronization */
        }
        if (thwin == thidx) { /* the thread that owns the best pivot */
            if ( jp-offset != column+n1 ) /* if there is a need to exchange the pivot */
            {
                ld = BLKLDD(A, max_it);
                Atop2 = A( max_it, 0 ) + (column + n1 )* ld + max_i;
                *Atop2 = tmp2;
            }
        }

        CORE_sgetrf_rectil_rec( A, IPIV, info, pivot,
                                thidx, thcnt, column+n1, n2, ft, lt );
        if ( *info != 0 )
            return;

        if ( thidx == 0 )
        {
            /* Swap to the left */
            int *lipiv = IPIV+column+n1;
            int idxMax = column+width;
            for (j = column+n1; j < idxMax; ++j, ++lipiv) {
                ip = (*lipiv) - offset - 1;
                if ( ip != j )
                {
                    it = ip / A.mb;
                    i  = ip % A.mb;
                    ld = BLKLDD(A, it);
                    cblas_sswap(n1, Atop + j,                 ldft,
                                    A(it, 0) + column*ld + i, ld  );
                }
            }
        }

    } else if ( width == 1 ) {

        /* Search maximum for column 0 */
        if ( column == 0 )
        {
            if ( thidx == 0 )
              tmp2 = Atop[column];

            /* First tmp1 */
            ld = BLKLDD(A, ft);
            Atop2   = A( ft, 0 );
            lm      = ft == A.mt-1 ? A.m - ft * A.mb : A.mb;
            max_it  = ft;
            max_i   = cblas_isamax( lm, Atop2, 1 );
            tmp1    = Atop2[max_i];
            abstmp1 = fabsf(tmp1);

            /* Update */
            for( it = ft+1; it < lt; it++)
            {
                Atop2= A( it, 0 );
                lm   = it == A.mt-1 ? A.m - it * A.mb : A.mb;
                jp   = cblas_isamax( lm, Atop2, 1 );
                if (  fabsf(Atop2[jp]) > abstmp1 ) {
                    tmp1 = Atop2[jp];
                    abstmp1 = fabsf(tmp1);
                    max_i  = jp;
                    max_it = it;
                }
            }

            jp = offset + max_it*A.mb + max_i;
            CORE_samax1_thread( tmp1, thidx, thcnt, &thwin,
                                &tmp2, pivot, jp + 1, IPIV + column );

            if ( thidx == 0 ) {
                Atop[0] = *pivot; /* all threads have the pivot element: no need for synchronization */
            }
            if (thwin == thidx) { /* the thread that owns the best pivot */
                if ( jp-offset != 0 ) /* if there is a need to exchange the pivot */
                {
                    Atop2 = A( max_it, 0 ) + max_i;
                    *Atop2 = tmp2;
                }
            }
        }

        CORE_sbarrier_thread( thidx, thcnt );

        /* If it is the last column, we just scale */
        if ( column == (min(A.m, A.n))-1 ) {

            pivval = *pivot;
            if ( pivval != 0.0 ) {
                if ( thidx == 0 ) {
                    if ( fabsf(pivval) >= sfmin ) {
                        pivval = 1.0 / pivval;

                        /*
                         * We guess than we never enter the function with m == A.mt-1
                         * because it means that there is only one thread
                         */
                        lm = ft == A.mt-1 ? A.m - ft * A.mb : A.mb;
                        cblas_sscal( lm - column - 1, (pivval), Atop+column+1, 1 );

                        for( it = ft+1; it < lt; it++)
                        {
                            ld = BLKLDD(A, it);
                            Atop2 = A( it, 0 ) + column * ld;
                            lm = it == A.mt-1 ? A.m - it * A.mb : A.mb;
                            cblas_sscal( lm, (pivval), Atop2, 1 );
                        }
                    } else {
                        /*
                         * We guess than we never enter the function with m == A.mt-1
                         * because it means that there is only one thread
                         */
                        int i;
                        Atop2 = Atop + column + 1;
                        lm = ft == A.mt-1 ? A.m - ft * A.mb : A.mb;

                        for( i=0; i < lm-column-1; i++, Atop2++)
                            *Atop2 = *Atop2 / pivval;

                        for( it = ft+1; it < lt; it++)
                            {
                                ld = BLKLDD(A, it);
                                Atop2 = A( it, 0 ) + column * ld;
                                lm = it == A.mt-1 ? A.m - it * A.mb : A.mb;

                                for( i=0; i < lm; i++, Atop2++)
                                    *Atop2 = *Atop2 / pivval;
                            }
                    }
                }
                else
                {
                    if ( fabsf(pivval) >= sfmin ) {
                        pivval = 1.0 / pivval;

                        for( it = ft; it < lt; it++)
                        {
                            ld = BLKLDD(A, it);
                            Atop2 = A( it, 0 ) + column * ld;
                            lm = it == A.mt-1 ? A.m - it * A.mb : A.mb;
                            cblas_sscal( lm, (pivval), Atop2, 1 );
                        }
                    } else {
                        /*
                         * We guess than we never enter the function with m == A.mt-1
                         * because it means that there is only one thread
                         */
                        int i;
                        for( it = ft; it < lt; it++)
                        {
                            ld = BLKLDD(A, it);
                            Atop2 = A( it, 0 ) + column * ld;
                            lm = it == A.mt-1 ? A.m - it * A.mb : A.mb;

                            for( i=0; i < lm; i++, Atop2++)
                                *Atop2 = *Atop2 / pivval;
                        }
                    }
                }
            }
            else {
                *info = column + 1;
                return;
            }
        }
    }
}


text:
#include <math.h>
#include <gsl/gsl_integration.h>
#include <gsl/gsl_roots.h>
#include <gsl/gsl_sf_hyperg.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_odeiv2.h>

#include <fastpm/libfastpm.h>
#include <fastpm/logging.h>

#define STEF_BOLT 2.85087e-48  // in units: [ h * (10^10Msun/h) * s^-3 * K^-4 ]
#define rho_crit 27.7455       // rho_crit0 in mass/length
#define LIGHT 9.715614e-15     // in units: [ h * (Mpc/h) * s^-1 ]

#define kB 8.617333262145e-5   // boltzman in eV/K

double HubbleDistance = 2997.92458; /* Mpc/h */
double HubbleConstant = 100.0;      /* km/s / Mpc/h */

void
fastpm_cosmology_init(FastPMCosmology * c)
{
    /* prepare the interpolation object for FD tables. */
    if (c->N_ncdm > 0) {
        FastPMFDInterp * FDinterp = malloc(sizeof(FDinterp[0]));
        fastpm_fd_interp_init(FDinterp);
        c->FDinterp = FDinterp;
    }

    // Compute Omega_ncdm(z=0)
    double Omega_ncdm_0;
    if (c->ncdm_matterlike) {
        Omega_ncdm_0 = 0;
        for (int i=0; i<c->N_ncdm; i++) {
            Omega_ncdm_0 += c->m_ncdm[i];
        }
        Omega_ncdm_0 *= 1. / 93.14 / c->h / c->h;
    } else {
        Omega_ncdm_0 = Omega_ncdmTimesHubbleEaSq(1, c);
    }
    c->Omega_ncdm = Omega_ncdm_0;

    // Compute Omega_cdm assuming all ncdm is matter-like at z=0
    c->Omega_cdm = c->Omega_m - Omega_ncdm_0;

    // Set Omega_Lambda at z=0 by closing Friedmann's equation
    c->Omega_Lambda = 1 - c->Omega_m - Omega_r(c) - c->Omega_k;
}

void
fastpm_cosmology_destroy(FastPMCosmology * c)
{
    if (c->FDinterp) {
        fastpm_fd_interp_destroy(c->FDinterp);
        free(c->FDinterp);
    }
}

double Omega_g(FastPMCosmology * c)
{
    /* FIXME: This is really Omega_g0. Might want to redefine all Omegas in the code */
    return 4 * STEF_BOLT * pow(c->T_cmb, 4) / pow(LIGHT, 3) / rho_crit / pow(c->h, 2);
}

double Gamma_nu(FastPMCosmology * c)
{
    /* nu to photon temp ratio today */
    if (c->N_nu == 0) {
        return 0;
    } else {
        return pow(4./11., 1./3.) * pow(c->N_eff / c->N_nu, 1./4.);
    }
}

double Omega_ur(FastPMCosmology * c)
{
    /* Omega_ur0. This is the energy density of all massless nus */
    int N_ur = c->N_nu - c->N_ncdm;    // number of massless nus (different to CLASS defn)
    return 7./8. * N_ur * pow(Gamma_nu(c), 4) * Omega_g(c);
}

double Omega_r(FastPMCosmology * c)
{
    /* Omega_r0. This is the energy density of all radiation-like particles.
       FIXME: really this is Omega_g+ur, not r, because it doesn't have ncdm,r in it
       and we define m with ncdm,m. this doesn't affect rest of code, but maybe redefine.*/
    return Omega_g(c) + Omega_ur(c);
}

static double getFtable(int F_id, double y, FastPMCosmology * c)
{
    /* Not using size as an arg, it's globally defined
       Gets the interpolated value of Ftable[F_id] at y
       F_id: 1 for F, 2 for F', 3 for F'' */
    return fastpm_do_fd_interp(c->FDinterp, F_id, y);
}

static double Fconst(int ncdm_id, FastPMCosmology * c)
{
    /* This is a cosmology dependent constant
       which is the argument divided by a of F, DF, DDF */
    double T_nu = Gamma_nu(c) * c->T_cmb;
    return c->m_ncdm[ncdm_id] / (kB * T_nu);
}

double Omega_ncdm_iTimesHubbleEaSq(double a, int ncdm_id, FastPMCosmology * c)
{
    /* Omega_ncdm_i(a) * E(a)^2 */

    double A = 15. / pow(M_PI, 4) * pow(Gamma_nu(c), 4) * Omega_g(c);
    double Fc = Fconst(ncdm_id, c);
    double F = getFtable(1, Fc*a, c);         //row 1 for F

    return A / (a*a*a*a) * F;
}

double Omega_ncdmTimesHubbleEaSq(double a, FastPMCosmology * c)
{
    // sum over ncdm species
    double res = 0;
    for (int i=0; i<c->N_ncdm; i++) {
        res += Omega_ncdm_iTimesHubbleEaSq(a, i, c);
    }
    return res;
}

double DOmega_ncdmTimesHubbleEaSqDa(double a, FastPMCosmology * c)
{
    double A = 15. / pow(M_PI, 4) * pow(Gamma_nu(c), 4) * Omega_g(c);

    double OncdmESq = Omega_ncdmTimesHubbleEaSq(a,c);

    double FcDF = 0;
    for (int i=0; i<c->N_ncdm; i++) {
        double Fc = Fconst(i, c);
        double DF = getFtable(2, Fc*a, c);
        FcDF += Fc * DF;    //row 2 for F'
    }

    return -4. / a * OncdmESq + A / (a*a*a*a) * FcDF;
}

double D2Omega_ncdmTimesHubbleEaSqDa2(double a, FastPMCosmology * c)
{
    double A = 15. / pow(M_PI, 4) * pow(Gamma_nu(c), 4) * Omega_g(c);

    double OncdmESq = Omega_ncdmTimesHubbleEaSq(a,c);
    double DOncdmESqDa = DOmega_ncdmTimesHubbleEaSqDa(a,c);

    double FcFcDDF = 0;
    for (int i=0; i<c->N_ncdm; i++) {
        double Fc = Fconst(i, c);
        double DDF = getFtable(3, Fc*a, c);
        FcFcDDF += Fc * Fc * DDF;    //row 3 for F''
    }

    return -12. / (a*a) * OncdmESq - 8. / a * DOncdmESqDa + A / (a*a*a*a) * FcFcDDF;
}

double Omega_DE_TimesHubbleEaSq(double a, FastPMCosmology * c)
{
    /* Dark energy parameter as a function of a, times E^2(a).
       Using Chevalier-Linder-Polarski: w(z) = w0 + z/(1+z) wa.
       Omega_DE(z) E^2(z) = Omega_DE(0) * exp( 3 \int_0^z dx (1+w(x)) / (1+x) )
                          = Omega_Lambda * exp[ 3 ( -wa*z/(1+z) + (1+w0+wa)*ln(1+z) )]. */
    double exponent = (a - 1) * c->wa - (1 + c->w0 + c->wa) * log(a);
    return c->Omega_Lambda * exp(3 * exponent);
}

double DOmega_DE_TimesHubbleEaSqDa(double a, FastPMCosmology * c)
{
    return 3 * (c->wa - (1 + c->w0 + c->wa) / a) * Omega_DE_TimesHubbleEaSq(a, c);
}

double D2Omega_DE_TimesHubbleEaSqDa2(double a, FastPMCosmology * c)
{
    double OdeESq = Omega_DE_TimesHubbleEaSq(a, c);
    double DOdeEsqDa = DOmega_DE_TimesHubbleEaSqDa(a, c);
    return DOdeEsqDa*DOdeEsqDa / c->Omega_Lambda + 3 * (1 + c->w0 + c->wa) / (a*a) * OdeESq;
}

double HubbleEa(double a, FastPMCosmology * c)
{
    /* H(a) / H0 */

    double Omega_ncdm_ESq;   // contribution from ncdm
    if (c->ncdm_matterlike) {
        Omega_ncdm_ESq = c->Omega_ncdm / (a*a*a);
    } else {
        Omega_ncdm_ESq = Omega_ncdmTimesHubbleEaSq(a, c);
    }

    return sqrt(Omega_r(c) / (a*a*a*a)
                + c->Omega_cdm / (a*a*a)
                + c->Omega_k / (a*a)
                + Omega_DE_TimesHubbleEaSq(a, c)
                + Omega_ncdm_ESq);
}

double Omega_cdm_a(double a, FastPMCosmology * c)
{
    /* as a func of a
       FIXME: remove the _a and put in 0s for today's value elsewhere */
    double E = HubbleEa(a, c);
    return c->Omega_cdm / (a*a*a) / (E*E);
}

double Omega_m(double a, FastPMCosmology * c){
    /* Total matter component (cdm + ncdm) assuming all ncdm is matter-like (for use in source term) */
    double E = HubbleEa(a, c);
    return c->Omega_m / (a*a*a) / (E*E);
}

double Omega_source(double a, FastPMCosmology * c){
    /* For use in source term of growth ODE and Poisson eqn */
    if (c->ncdm_freestreaming){
        return Omega_cdm_a(a, c);
    } else {
        return Omega_m(a, c);
    }
}

double DHubbleEaDa(double a, FastPMCosmology * c)
{
    /* d E / d a*/
    double E = HubbleEa(a, c);
    double DOdeESqDa = DOmega_DE_TimesHubbleEaSqDa(a, c);

    double DOncdmESqDa;   // contribution from ncdm
    if (c->ncdm_matterlike) {
        DOncdmESqDa = - 3 * c->Omega_ncdm / pow(a,4);
    } else {
        DOncdmESqDa = DOmega_ncdmTimesHubbleEaSqDa(a, c);
    }

    return 0.5 / E * (- 4 * Omega_r(c) / pow(a,5)
                      - 3 * c->Omega_cdm / pow(a,4)
                      - 2 * c->Omega_k / pow(a,3)
                      + DOdeESqDa
                      + DOncdmESqDa);
}

double D2HubbleEaDa2(double a, FastPMCosmology * c)
{
    double E = HubbleEa(a, c);
    double dEda = DHubbleEaDa(a, c);
    double D2OdeESqDa2 = D2Omega_DE_TimesHubbleEaSqDa2(a, c);

    double D2OncdmESqDa2;   // contribution from ncdm
    if (c->ncdm_matterlike) {
        D2OncdmESqDa2 = 12 * c->Omega_ncdm / pow(a,5);
    } else {
        D2OncdmESqDa2 = D2Omega_ncdmTimesHubbleEaSqDa2(a, c);
    }

    return 0.5 / E * (  20 * Omega_r(c) / pow(a,6)
                      + 12 * c->Omega_cdm / pow(a,5)
                      + 6 * c->Omega_k / pow(a,4)
                      + D2OdeESqDa2
                      + D2OncdmESqDa2
                      - 2 * pow(dEda,2) );
}

static double growth_int(double a, void *param)
{
    double * p = (double*) param;
    double Omega_m = p[0];
    double Omega_Lambda = p[1];
    return pow(a / (Omega_m + (1 - Omega_m - Omega_Lambda) * a + Omega_Lambda * a * a * a), 1.5);
}

static double solve_growth_int(double a, FastPMCosmology * c)
{
    /* NOTE that the analytic COLA growthDtemp() is 6 * pow(1 - c.OmegaM, 1.5) times growth() */

    int WORKSIZE = 100000;

    double result, abserr;
    gsl_integration_workspace *workspace;
    gsl_function F;

    workspace = gsl_integration_workspace_alloc(WORKSIZE);

    F.function = &growth_int;
    F.params = (double[]) {c->Omega_m, c->Omega_Lambda};

    gsl_integration_qag(&F, 0, a, 0, 1.0e-9, WORKSIZE, GSL_INTEG_GAUSS41,
            workspace, &result, &abserr);

    gsl_integration_workspace_free(workspace);

    return HubbleEa(a, c) * result;
}

static int growth_ode(double a, const double y[], double dyda[], void *params)
{
    FastPMCosmology* c = (FastPMCosmology * ) params;

    const double E = HubbleEa(a, c);
    const double dEda = DHubbleEaDa(a, c);

    double dydlna[4];
    dydlna[0] = y[1];
    dydlna[1] = - (2. + a / E * dEda) * y[1] + 1.5 * Omega_source(a, c) * y[0];
    dydlna[2] = y[3];
    dydlna[3] = - (2. + a / E * dEda) * y[3] + 1.5 * Omega_source(a, c) * (y[2] - y[0]*y[0]);

    //divide by  a to get dyda
    for (int i=0; i<4; i++){
        dyda[i] = dydlna[i] / a;
    }

    return GSL_SUCCESS;
}

static ode_soln growth_ode_solve(double a, FastPMCosmology * c)
{
    /* This returns an array of {d1, F1, d2, F2} (unnormalised) */
    gsl_odeiv2_system F;
    F.function = &growth_ode;
    F.jacobian = NULL;
    F.dimension = 4;
    F.params = (void*) c;

    gsl_odeiv2_driver * drive
        = gsl_odeiv2_driver_alloc_standard_new(&F,
                                               gsl_odeiv2_step_rkf45,
                                               1e-6,
                                               1e-8,
                                               1e-8,
                                               1,
                                               1);

    // assume matter domination
    double aini = 0.00625;  // FIXME: need to make sure this is less than the starting a. For now using z=159.
    double yini[4];
    yini[0] = aini;
    yini[1] = aini;
    yini[2] = - 3./7. * aini*aini;
    yini[3] = 2 * yini[2];

    int status = gsl_odeiv2_driver_apply(drive, &aini, a, yini);
    if (status != GSL_SUCCESS) {
        fastpm_raise(-1, "Growth ODE unsuccesful at a=%g.", a);
    }

    gsl_odeiv2_driver_free(drive);

    ode_soln soln;
    soln.y0 = yini[0];
    soln.y1 = yini[1];
    soln.y2 = yini[2];
    soln.y3 = yini[3];

    return soln;
}

void fastpm_growth_info_init(FastPMGrowthInfo * growth_info, double a, FastPMCosmology * c) {
    growth_info->a = a;
    growth_info->c = c;

    switch (c->growth_mode) {
        case FASTPM_GROWTH_MODE_LCDM: {
            double d1 = solve_growth_int(a, c);
            double d1_a1 = solve_growth_int(1, c);
            double Om = Omega_m(a, c);

            growth_info->D1 = d1 / d1_a1;
            growth_info->f1 = pow(Om, 5./9.);
            growth_info->D2 = growth_info->D1 * growth_info->D1 * pow(Om/Omega_m(1, c), -1./143.);
            growth_info->f2 = 2 * pow(Om, 6./11.);
        break; }
        case FASTPM_GROWTH_MODE_ODE: {
            ode_soln soln = growth_ode_solve(a, c);
            ode_soln soln_a1 = growth_ode_solve(1, c);

            growth_info->D1 = soln.y0 / soln_a1.y0;
            growth_info->f1 = soln.y1 / soln.y0;    /* f = d log D / d log a. Note soln.y1 is d d1 / d log a */
            growth_info->D2 = soln.y2 / soln_a1.y2;
            growth_info->f2 = soln.y3 / soln.y2;
        break; }
        default:
            fastpm_raise(-1, "Please enter a valid growth mode.\n");
    }
}

double DGrowthFactorDa(FastPMGrowthInfo * growth_info) {
    /* dD/da */
    /* FIXME: Technically the ODE version should agree with LCDM version
              for Lambda+CDM background,
              but to ensure backwards compatibility both versions are here. */
    double a = growth_info->a;
    FastPMCosmology * c = growth_info->c;

    double ans = 0;
    switch (c->growth_mode) {
        case FASTPM_GROWTH_MODE_LCDM: {
            double E = HubbleEa(a, c);
            double EI = solve_growth_int(1.0, c);
            double t1 = DHubbleEaDa(a, c) * growth_info->D1 / E;
            double t2 = E * pow(a * E, -3) / EI;
            ans = t1 + t2;
        break; }
        case FASTPM_GROWTH_MODE_ODE:
            ans = growth_info->f1 * growth_info->D1 / growth_info->a;
        break;
        default:
            fastpm_raise(-1, "Please enter a valid growth mode.\n");
    }
    return ans;
}

double D2GrowthFactorDa2(FastPMGrowthInfo * growth_info) {
    /* d^2 D1 / da^2 */
    /* FIXME: Technically the ODE version should agree with LCDM version
              for Lambda+CDM background,
              but to ensure backwards compatibility both versions are here. */
    double a = growth_info->a;
    FastPMCosmology * c = growth_info->c;

    double ans = 0;
    switch (c->growth_mode) {
        case FASTPM_GROWTH_MODE_LCDM: {
            double d2Eda2 = D2HubbleEaDa2(a, c);
            double dEda = DHubbleEaDa(a, c);
            double E = HubbleEa(a, c);
            double EI = solve_growth_int(1., c);
            double t1 = d2Eda2 * growth_info->D1 / E;
            double t2 = (dEda + 3 / a * E) * pow(a * E, -3) / EI;
            ans = t1 - t2;
        break; }
        case FASTPM_GROWTH_MODE_ODE: {
            double E = HubbleEa(a, c);
            double dEda = DHubbleEaDa(a, c);
            double D1 = growth_info->D1;
            double f1 = growth_info->f1;

            ans -= (3. + a / E * dEda) * f1;
            ans += 1.5 * Omega_source(a, c);
            ans *= D1 / (a*a);
        break; }
        default:
            fastpm_raise(-1, "Please enter a valid growth mode.\n");
    }
    return ans;
}

static double
comoving_distance_int(double a, void * params)
{
    FastPMCosmology * c = (FastPMCosmology * ) params;
    return 1. / (a * a * HubbleEa(a, c));
}

double ComovingDistance(double a, FastPMCosmology * c) {

    /* We tested using ln_a doesn't seem to improve accuracy */
    int WORKSIZE = 100000;

    double result, abserr;
    gsl_integration_workspace *workspace;
    gsl_function F;

    workspace = gsl_integration_workspace_alloc(WORKSIZE);

    F.function = &comoving_distance_int;
    F.params = (void*) c;

    gsl_integration_qag(&F, a, 1., 0, 1.0e-8, WORKSIZE, GSL_INTEG_GAUSS41,
            workspace, &result, &abserr);
            //lowered tol by /10 to avoid error from round off (maybe I need to make my paras more accurate)

    gsl_integration_workspace_free(workspace);

    return result;
}

#ifdef TEST_COSMOLOGY
int main() {
    /* the old COLA growthDtemp is 6 * pow(1 - c.OmegaM, 1.5) times growth */
    double a;
    FastPMCosmology c[1] = {{
        .OmegaM = 0.3,
        .OmegaLambda = 0.7
    }};

    printf("OmegaM D dD/da d2D/da2 D2 E dE/dA d2E/da2 \n");
    for(c->OmegaM = 0.1; c->OmegaM < 0.6; c->OmegaM += 0.1) {
        double f = 6 * pow(1 - c->OmegaM, 1.5);
        c->OmegaLambda = 1 - c->OmegaM;
        c->w0 = -1;
        c->wa = 0;
        double a = 0.8;
        printf("%g %g %g %g %g %g %g %g %g\n",
            c->OmegaM,
            ComovingDistance(a, c),
            GrowthFactor(a, c),
            DGrowthFactorDa(a, c),
            D2GrowthFactorDa2(a, c),

            GrowthFactor2(a, c),
            HubbleEa(a, c),
            DHubbleEaDa(a, c),
            D2HubbleEaDa2(a, c)
            );
    }
}

#endif

max_stars_repo_name: sbird/FastPMRunner

max_issues_repo_name: sbird/FastPMRunner

max_forks_repo_name: sbird/FastPMRunner