adaptive-cubature (empty) → 0.1.0.0
raw patch · 13 files changed
+2581/−0 lines, 13 filesdep +basesetup-changed
Dependencies added: base
Files
- C/clencurt.h too large to diff
- C/converged.h +73/−0
- C/cubature.h +123/−0
- C/hcubature.c +1099/−0
- C/mintegration.c +28/−0
- C/pcubature.c +424/−0
- C/vwrapper.h +16/−0
- CHANGELOG.md +5/−0
- LICENSE +674/−0
- README.md +31/−0
- Setup.hs +2/−0
- adaptive-cubature.cabal +43/−0
- src/Numerical/Cubature.hs +63/−0
+ C/clencurt.h view
file too large to diff
+ C/converged.h view
@@ -0,0 +1,73 @@+/* Body of convergence test, shared between hcubature.c and+ pcubature.c. We use an #include file because the two routines use+ somewhat different data structures, and define macros ERR(j) and+ VAL(j) to get the error and value estimates, respectively, for+ integrand j. */+{+ unsigned j;+# define SQR(x) ((x) * (x))+ switch (norm) {+ case ERROR_INDIVIDUAL:+ for (j = 0; j < fdim; ++j)+ if (ERR(j) > reqAbsError && ERR(j) > fabs(VAL(j))*reqRelError)+ return 0;+ return 1;+ + case ERROR_PAIRED:+ for (j = 0; j+1 < fdim; j += 2) {+ double maxerr, serr, err, maxval, sval, val;+ /* scale to avoid overflow/underflow */+ maxerr = ERR(j) > ERR(j+1) ? ERR(j) : ERR(j+1);+ maxval = VAL(j) > VAL(j+1) ? VAL(j) : VAL(j+1);+ serr = maxerr > 0 ? 1/maxerr : 1;+ sval = maxval > 0 ? 1/maxval : 1;+ err = sqrt(SQR(ERR(j)*serr) + SQR(ERR(j+1)*serr)) * maxerr;+ val = sqrt(SQR(VAL(j)*sval) + SQR(VAL(j+1)*sval)) * maxval;+ if (err > reqAbsError && err > val*reqRelError)+ return 0;+ }+ if (j < fdim) /* fdim is odd, do last dimension individually */+ if (ERR(j) > reqAbsError && ERR(j) > fabs(VAL(j))*reqRelError)+ return 0;+ return 1;++ case ERROR_L1: {+ double err = 0, val = 0;+ for (j = 0; j < fdim; ++j) {+ err += ERR(j);+ val += fabs(VAL(j));+ }+ return err <= reqAbsError || err <= val*reqRelError;+ }++ case ERROR_LINF: {+ double err = 0, val = 0;+ for (j = 0; j < fdim; ++j) {+ double absval = fabs(VAL(j));+ if (ERR(j) > err) err = ERR(j);+ if (absval > val) val = absval;+ }+ return err <= reqAbsError || err <= val*reqRelError;+ }++ case ERROR_L2: {+ double maxerr = 0, maxval = 0, serr, sval, err = 0, val = 0;+ /* scale values by 1/max to avoid overflow/underflow */+ for (j = 0; j < fdim; ++j) {+ double absval = fabs(VAL(j));+ if (ERR(j) > maxerr) maxerr = ERR(j);+ if (absval > maxval) maxval = absval;+ }+ serr = maxerr > 0 ? 1/maxerr : 1;+ sval = maxval > 0 ? 1/maxval : 1;+ for (j = 0; j < fdim; ++j) {+ err += SQR(ERR(j) * serr);+ val += SQR(fabs(VAL(j)) * sval);+ }+ err = sqrt(err) * maxerr;+ val = sqrt(val) * maxval;+ return err <= reqAbsError || err <= val*reqRelError;+ }+ }+ return 1; /* unreachable */+}
+ C/cubature.h view
@@ -0,0 +1,123 @@+/* Adaptive multidimensional integration of a vector of integrands.+ *+ * Copyright (c) 2005-2013 Steven G. Johnson+ *+ * Portions (see comments) based on HIntLib (also distributed under+ * the GNU GPL, v2 or later), copyright (c) 2002-2005 Rudolf Schuerer.+ * (http://www.cosy.sbg.ac.at/~rschuer/hintlib/)+ *+ * Portions (see comments) based on GNU GSL (also distributed under+ * the GNU GPL, v2 or later), copyright (c) 1996-2000 Brian Gough.+ * (http://www.gnu.org/software/gsl/)+ *+ * This program is free software; you can redistribute it and/or modify+ * it under the terms of the GNU General Public License as published by+ * the Free Software Foundation; either version 2 of the License, or+ * (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU General Public License for more details.+ *+ * You should have received a copy of the GNU General Public License+ * along with this program; if not, write to the Free Software+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA+ *+ */++#ifndef CUBATURE_H+#define CUBATURE_H++#include <stdlib.h> /* for size_t */++#ifdef __cplusplus+extern "C"+{+#endif /* __cplusplus */++/* USAGE: Call hcubature or pcubature with your function as described+ in the README file. */++/* a vector integrand - evaluates the function at the given point x+ (an array of length ndim) and returns the result in fval (an array+ of length fdim). The void* parameter is there in case you have+ to pass any additional data through to your function (it corresponds+ to the fdata parameter you pass to cubature). Return 0 on+ success or nonzero to terminate the integration. */+typedef int (*integrand) (unsigned ndim, const double *x, void *,+ unsigned fdim, double *fval);++/* a vector integrand of a vector of npt points: x[i*ndim + j] is the+ j-th coordinate of the i-th point, and the k-th function evaluation+ for the i-th point is returned in fval[i*fdim + k]. Return 0 on success+ or nonzero to terminate the integration. */+typedef int (*integrand_v) (unsigned ndim, size_t npt,+ const double *x, void *,+ unsigned fdim, double *fval);++/* Different ways of measuring the absolute and relative error when+ we have multiple integrands, given a vector e of error estimates+ in the individual components of a vector v of integrands. These+ are all equivalent when there is only a single integrand. */+typedef enum {+ ERROR_INDIVIDUAL = 0, /* individual relerr criteria in each component */+ ERROR_PAIRED, /* paired L2 norms of errors in each component,+ mainly for integrating vectors of complex numbers */+ ERROR_L2, /* abserr is L_2 norm |e|, and relerr is |e|/|v| */+ ERROR_L1, /* abserr is L_1 norm |e|, and relerr is |e|/|v| */+ ERROR_LINF /* abserr is L_\infty norm |e|, and relerr is |e|/|v| */+} error_norm;++/* Integrate the function f from xmin[dim] to xmax[dim], with at most+ maxEval function evaluations (0 for no limit), until the given+ absolute or relative error is achieved. val returns the integral,+ and err returns the estimate for the absolute error in val; both+ of these are arrays of length fdim, the dimension of the vector+ integrand f(x). The return value of the function is 0 on success+ and non-zero if there was an error. */++/* adapative integration by partitioning the integration domain ("h-adaptive")+ and using the same fixed-degree quadrature in each subdomain, recursively,+ until convergence is achieved. */+int hcubature(unsigned fdim, integrand f, void *fdata,+ unsigned dim, const double *xmin, const double *xmax, + size_t maxEval, double reqAbsError, double reqRelError, + error_norm norm,+ double *val, double *err);++/* as hcubature, but vectorized integrand */+int hcubature_v(unsigned fdim, integrand_v f, void *fdata,+ unsigned dim, const double *xmin, const double *xmax, + size_t maxEval, double reqAbsError, double reqRelError, + error_norm norm,+ double *val, double *err);++/* adaptive integration by increasing the degree of (tensor-product+ Clenshaw-Curtis) quadrature rules ("p-adaptive"), rather than+ subdividing the domain ("h-adaptive"). Possibly better for+ smooth integrands in low dimensions. */+int pcubature_v_buf(unsigned fdim, integrand_v f, void *fdata,+ unsigned dim, const double *xmin, const double *xmax,+ size_t maxEval, + double reqAbsError, double reqRelError,+ error_norm norm,+ unsigned *m,+ double **buf, size_t *nbuf, size_t max_nbuf,+ double *val, double *err);+int pcubature_v(unsigned fdim, integrand_v f, void *fdata,+ unsigned dim, const double *xmin, const double *xmax, + size_t maxEval, double reqAbsError, double reqRelError, + error_norm norm,+ double *val, double *err);+int pcubature(unsigned fdim, integrand f, void *fdata,+ unsigned dim, const double *xmin, const double *xmax, + size_t maxEval, double reqAbsError, double reqRelError, + error_norm norm,+ double *val, double *err);++#ifdef __cplusplus+} /* extern "C" */+#endif /* __cplusplus */++#endif /* CUBATURE_H */
+ C/hcubature.c view
@@ -0,0 +1,1099 @@+/* Adaptive multidimensional integration of a vector of integrands.+ *+ * Copyright (c) 2005-2013 Steven G. Johnson+ *+ * Portions (see comments) based on HIntLib (also distributed under+ * the GNU GPL, v2 or later), copyright (c) 2002-2005 Rudolf Schuerer.+ * (http://www.cosy.sbg.ac.at/~rschuer/hintlib/)+ *+ * Portions (see comments) based on GNU GSL (also distributed under+ * the GNU GPL, v2 or later), copyright (c) 1996-2000 Brian Gough.+ * (http://www.gnu.org/software/gsl/)+ *+ * This program is free software; you can redistribute it and/or modify+ * it under the terms of the GNU General Public License as published by+ * the Free Software Foundation; either version 2 of the License, or+ * (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU General Public License for more details.+ *+ * You should have received a copy of the GNU General Public License+ * along with this program; if not, write to the Free Software+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA+ *+ */++#include <stdio.h>+#include <stdlib.h>+#include <string.h>+#include <math.h>+#include <limits.h>+#include <float.h>++/* Adaptive multidimensional integration on hypercubes (or, really,+ hyper-rectangles) using cubature rules.++ A cubature rule takes a function and a hypercube and evaluates+ the function at a small number of points, returning an estimate+ of the integral as well as an estimate of the error, and also+ a suggested dimension of the hypercube to subdivide.++ Given such a rule, the adaptive integration is simple:++ 1) Evaluate the cubature rule on the hypercube(s).+ Stop if converged.++ 2) Pick the hypercube with the largest estimated error,+ and divide it in two along the suggested dimension.++ 3) Goto (1).++ The basic algorithm is based on the adaptive cubature described in++ A. C. Genz and A. A. Malik, "An adaptive algorithm for numeric+ integration over an N-dimensional rectangular region,"+ J. Comput. Appl. Math. 6 (4), 295-302 (1980).++ and subsequently extended to integrating a vector of integrands in++ J. Berntsen, T. O. Espelid, and A. Genz, "An adaptive algorithm+ for the approximate calculation of multiple integrals,"+ ACM Trans. Math. Soft. 17 (4), 437-451 (1991).++ Note, however, that we do not use any of code from the above authors+ (in part because their code is Fortran 77, but mostly because it is+ under the restrictive ACM copyright license). I did make use of some+ GPL code from Rudolf Schuerer's HIntLib and from the GNU Scientific+ Library as listed in the copyright notice above, on the other hand.++ I am also grateful to Dmitry Turbiner <dturbiner@alum.mit.edu>, who+ implemented an initial prototype of the "vectorized" functionality+ for evaluating multiple points in a single call (as opposed to+ multiple functions in a single call). (Although Dmitry implemented+ a working version, I ended up re-implementing this feature from+ scratch as part of a larger code-cleanup, and in order to have+ a single code path for the vectorized and non-vectorized APIs. I+ subsequently implemented the algorithm by Gladwell to extract+ even more parallelism by evalutating many hypercubes at once.)++ TODO:++ * Putting these routines into the GNU GSL library would be nice.++ * A Python interface would be nice. (Also a Matlab interface,+ a GNU Octave interface, ...)++ * For high-dimensional integrals, it would be nice to implement+ a sparse-grid cubature scheme using Clenshaw-Curtis quadrature.+ Currently, for dimensions > 7 or so, quasi Monte Carlo methods win.++ * Berntsen et. al also describe a "two-level" error estimation scheme+ that they claim makes the algorithm more robust. It might be+ nice to implement this, at least as an option (although I seem+ to remember trying it once and it made the number of evaluations+ substantially worse for my test integrands).++*/++/* USAGE: Call cubature with your function as described in cubature.h.++ To compile a test program, compile cubature.c with+ -DTEST_INTEGRATOR as described at the end. */++#include "cubature.h"++/* error return codes */+#define SUCCESS 0+#define FAILURE 1++/***************************************************************************/+/* Basic datatypes */++typedef struct {+ double val, err;+} esterr;++static double errMax(unsigned fdim, const esterr *ee)+{+ double errmax = 0;+ unsigned k;+ for (k = 0; k < fdim; ++k)+ if (ee[k].err > errmax) errmax = ee[k].err;+ return errmax;+}++typedef struct {+ unsigned dim;+ double *data; /* length 2*dim = center followed by half-widths */+ double vol; /* cache volume = product of widths */+} hypercube;++static double compute_vol(const hypercube *h)+{+ unsigned i;+ double vol = 1;+ for (i = 0; i < h->dim; ++i)+ vol *= 2 * h->data[i + h->dim];+ return vol;+}++static hypercube make_hypercube(unsigned dim, const double *center, const double *halfwidth)+{+ unsigned i;+ hypercube h;+ h.dim = dim;+ h.data = (double *) malloc(sizeof(double) * dim * 2);+ h.vol = 0;+ if (h.data) {+ for (i = 0; i < dim; ++i) {+ h.data[i] = center[i];+ h.data[i + dim] = halfwidth[i];+ }+ h.vol = compute_vol(&h);+ }+ return h;+}++static hypercube make_hypercube_range(unsigned dim, const double *xmin, const double *xmax)+{+ hypercube h = make_hypercube(dim, xmin, xmax);+ unsigned i;+ if (h.data) {+ for (i = 0; i < dim; ++i) {+ h.data[i] = 0.5 * (xmin[i] + xmax[i]);+ h.data[i + dim] = 0.5 * (xmax[i] - xmin[i]);+ }+ h.vol = compute_vol(&h);+ }+ return h;+}++static void destroy_hypercube(hypercube *h)+{+ free(h->data);+ h->dim = 0;+}++typedef struct {+ hypercube h;+ unsigned splitDim;+ unsigned fdim; /* dimensionality of vector integrand */+ esterr *ee; /* array of length fdim */+ double errmax; /* max ee[k].err */+} region;++static region make_region(const hypercube *h, unsigned fdim)+{+ region R;+ R.h = make_hypercube(h->dim, h->data, h->data + h->dim);+ R.splitDim = 0;+ R.fdim = fdim;+ R.ee = R.h.data ? (esterr *) malloc(sizeof(esterr) * fdim) : NULL;+ R.errmax = HUGE_VAL;+ return R;+}++static void destroy_region(region *R)+{+ destroy_hypercube(&R->h);+ free(R->ee);+ R->ee = 0;+}++static int cut_region(region *R, region *R2)+{+ unsigned d = R->splitDim, dim = R->h.dim;+ *R2 = *R;+ R->h.data[d + dim] *= 0.5;+ R->h.vol *= 0.5;+ R2->h = make_hypercube(dim, R->h.data, R->h.data + dim);+ if (!R2->h.data) return FAILURE;+ R->h.data[d] -= R->h.data[d + dim];+ R2->h.data[d] += R->h.data[d + dim];+ R2->ee = (esterr *) malloc(sizeof(esterr) * R2->fdim);+ return R2->ee == NULL;+}++struct rule_s; /* forward declaration */++typedef int (*evalError_func)(struct rule_s *r,+ unsigned fdim, integrand_v f, void *fdata,+ unsigned nR, region *R);+typedef void (*destroy_func)(struct rule_s *r);+++typedef struct rule_s {+ unsigned dim, fdim; /* the dimensionality & number of functions */+ unsigned num_points; /* number of evaluation points */+ unsigned num_regions; /* max number of regions evaluated at once */+ double *pts; /* points to eval: num_regions * num_points * dim */+ double *vals; /* num_regions * num_points * fdim */+ evalError_func evalError;+ destroy_func destroy;+} rule;++static void destroy_rule(rule *r)+{+ if (r) {+ if (r->destroy) r->destroy(r);+ free(r->pts);+ free(r);+ }+}++static int alloc_rule_pts(rule *r, unsigned num_regions)+{+ if (num_regions > r->num_regions) {+ free(r->pts);+ r->pts = r->vals = NULL;+ r->num_regions = 0;+ num_regions *= 2; /* allocate extra so that+ repeatedly calling alloc_rule_pts with+ growing num_regions only needs+ a logarithmic number of allocations */+ r->pts = (double *) malloc(sizeof(double) *+ (num_regions+ * r->num_points * (r->dim + r->fdim)));+ if (r->fdim + r->dim > 0 && !r->pts) return FAILURE;+ r->vals = r->pts + num_regions * r->num_points * r->dim;+ r->num_regions = num_regions;+ }+ return SUCCESS;+}++static rule *make_rule(size_t sz, /* >= sizeof(rule) */+ unsigned dim, unsigned fdim, unsigned num_points,+ evalError_func evalError, destroy_func destroy)+{+ rule *r;++ if (sz < sizeof(rule)) return NULL;+ r = (rule *) malloc(sz);+ if (!r) return NULL;+ r->pts = r->vals = NULL;+ r->num_regions = 0;+ r->dim = dim; r->fdim = fdim; r->num_points = num_points;+ r->evalError = evalError;+ r->destroy = destroy;+ return r;+}++/* note: all regions must have same fdim */+static int eval_regions(unsigned nR, region *R,+ integrand_v f, void *fdata, rule *r)+{+ unsigned iR;+ if (nR == 0) return SUCCESS; /* nothing to evaluate */+ if (r->evalError(r, R->fdim, f, fdata, nR, R)) return FAILURE;+ for (iR = 0; iR < nR; ++iR)+ R[iR].errmax = errMax(R->fdim, R[iR].ee);+ return SUCCESS;+}++/***************************************************************************/+/* Functions to loop over points in a hypercube. */++/* Based on orbitrule.cpp in HIntLib-0.0.10 */++/* ls0 returns the least-significant 0 bit of n (e.g. it returns+ 0 if the LSB is 0, it returns 1 if the 2 LSBs are 01, etcetera). */++static unsigned ls0(unsigned n)+{+#if defined(__GNUC__) && \+ ((__GNUC__ == 3 && __GNUC_MINOR__ >= 4) || __GNUC__ > 3)+ return __builtin_ctz(~n); /* gcc builtin for version >= 3.4 */+#else+ const unsigned bits[256] = {+ 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 4,+ 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 5,+ 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 4,+ 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 6,+ 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 4,+ 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 5,+ 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 4,+ 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 7,+ 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 4,+ 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 5,+ 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 4,+ 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 6,+ 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 4,+ 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 5,+ 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 4,+ 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 8,+ };+ unsigned bit = 0;+ while ((n & 0xff) == 0xff) {+ n >>= 8;+ bit += 8;+ }+ return bit + bits[n & 0xff];+#endif+}++/**+ * Evaluate the integration points for all 2^n points (+/-r,...+/-r)+ *+ * A Gray-code ordering is used to minimize the number of coordinate updates+ * in p, although this doesn't matter as much now that we are saving all pts.+ */+static void evalR_Rfs(double *pts, unsigned dim, double *p, const double *c, const double *r)+{+ unsigned i;+ unsigned signs = 0; /* 0/1 bit = +/- for corresponding element of r[] */++ /* We start with the point where r is ADDed in every coordinate+ (this implies signs=0). */+ for (i = 0; i < dim; ++i)+ p[i] = c[i] + r[i];++ /* Loop through the points in Gray-code ordering */+ for (i = 0;; ++i) {+ unsigned mask, d;++ memcpy(pts, p, sizeof(double) * dim); pts += dim;++ d = ls0(i); /* which coordinate to flip */+ if (d >= dim)+ break;++ /* flip the d-th bit and add/subtract r[d] */+ mask = 1U << d;+ signs ^= mask;+ p[d] = (signs & mask) ? c[d] - r[d] : c[d] + r[d];+ }+}++static void evalRR0_0fs(double *pts, unsigned dim, double *p, const double *c, const double *r)+{+ unsigned i, j;++ for (i = 0; i < dim - 1; ++i) {+ p[i] = c[i] - r[i];+ for (j = i + 1; j < dim; ++j) {+ p[j] = c[j] - r[j];+ memcpy(pts, p, sizeof(double) * dim); pts += dim;+ p[i] = c[i] + r[i];+ memcpy(pts, p, sizeof(double) * dim); pts += dim;+ p[j] = c[j] + r[j];+ memcpy(pts, p, sizeof(double) * dim); pts += dim;+ p[i] = c[i] - r[i];+ memcpy(pts, p, sizeof(double) * dim); pts += dim;++ p[j] = c[j]; /* Done with j -> Restore p[j] */+ }+ p[i] = c[i]; /* Done with i -> Restore p[i] */+ }+}++static void evalR0_0fs4d(double *pts, unsigned dim, double *p, const double *c,+ const double *r1, const double *r2)+{+ unsigned i;++ memcpy(pts, p, sizeof(double) * dim); pts += dim;++ for (i = 0; i < dim; i++) {+ p[i] = c[i] - r1[i];+ memcpy(pts, p, sizeof(double) * dim); pts += dim;++ p[i] = c[i] + r1[i];+ memcpy(pts, p, sizeof(double) * dim); pts += dim;++ p[i] = c[i] - r2[i];+ memcpy(pts, p, sizeof(double) * dim); pts += dim;++ p[i] = c[i] + r2[i];+ memcpy(pts, p, sizeof(double) * dim); pts += dim;++ p[i] = c[i];+ }+}++#define num0_0(dim) (1U)+#define numR0_0fs(dim) (2 * (dim))+#define numRR0_0fs(dim) (2 * (dim) * (dim-1))+#define numR_Rfs(dim) (1U << (dim))++/***************************************************************************/+/* Based on rule75genzmalik.cpp in HIntLib-0.0.10: An embedded+ cubature rule of degree 7 (embedded rule degree 5) due to A. C. Genz+ and A. A. Malik. See:++ A. C. Genz and A. A. Malik, "An imbedded [sic] family of fully+ symmetric numerical integration rules," SIAM+ J. Numer. Anal. 20 (3), 580-588 (1983).+*/++typedef struct {+ rule parent;++ /* temporary arrays of length dim */+ double *widthLambda, *widthLambda2, *p;++ /* dimension-dependent constants */+ double weight1, weight3, weight5;+ double weightE1, weightE3;+ double df_scale;+} rule75genzmalik;++#define real(x) ((double)(x))+#define to_int(n) ((int)(n))++static int isqr(int x)+{+ return x * x;+}++static void destroy_rule75genzmalik(rule *r_)+{+ rule75genzmalik *r = (rule75genzmalik *) r_;+ free(r->p);+}++static int rule75genzmalik_evalError(rule *r_, unsigned fdim, integrand_v f, void *fdata, unsigned nR, region *R)+{+ /* lambda2 = sqrt(9/70), lambda4 = sqrt(9/10), lambda5 = sqrt(9/19) */+ const double lambda2 = 0.3585685828003180919906451539079374954541;+ const double lambda4 = 0.9486832980505137995996680633298155601160;+ const double lambda5 = 0.6882472016116852977216287342936235251269;+ const double weight2 = 980. / 6561.;+ const double weight4 = 200. / 19683.;+ const double weightE2 = 245. / 486.;+ const double weightE4 = 25. / 729.;+ const double ratio = (lambda2 * lambda2) / (lambda4 * lambda4);++ rule75genzmalik *r = (rule75genzmalik *) r_;+ unsigned i, j, iR, dim = r_->dim;+ size_t npts = 0;+ double *diff, *pts, *vals;++ if (alloc_rule_pts(r_, nR)) return FAILURE;+ pts = r_->pts; vals = r_->vals;++ for (iR = 0; iR < nR; ++iR) {+ const double *center = R[iR].h.data;+ const double *halfwidth = R[iR].h.data + dim;++ for (i = 0; i < dim; ++i)+ r->p[i] = center[i];++ for (i = 0; i < dim; ++i)+ r->widthLambda2[i] = halfwidth[i] * lambda2;+ for (i = 0; i < dim; ++i)+ r->widthLambda[i] = halfwidth[i] * lambda4;++ /* Evaluate points in the center, in (lambda2,0,...,0) and+ (lambda3=lambda4, 0,...,0). */+ evalR0_0fs4d(pts + npts*dim, dim, r->p, center,+ r->widthLambda2, r->widthLambda);+ npts += num0_0(dim) + 2 * numR0_0fs(dim);++ /* Calculate points for (lambda4, lambda4, 0, ...,0) */+ evalRR0_0fs(pts + npts*dim, dim, r->p, center, r->widthLambda);+ npts += numRR0_0fs(dim);++ /* Calculate points for (lambda5, lambda5, ..., lambda5) */+ for (i = 0; i < dim; ++i)+ r->widthLambda[i] = halfwidth[i] * lambda5;+ evalR_Rfs(pts + npts*dim, dim, r->p, center, r->widthLambda);+ npts += numR_Rfs(dim);+ }++ /* Evaluate the integrand function(s) at all the points */+ if (f(dim, npts, pts, fdata, fdim, vals))+ return FAILURE;++ /* we are done with the points, and so we can re-use the pts+ array to store the maximum difference diff[i] in each dimension+ for each hypercube */+ diff = pts;+ for (i = 0; i < dim * nR; ++i) diff[i] = 0;++ for (j = 0; j < fdim; ++j) {+ const double *v = vals + j;+# define VALS(i) v[fdim*(i)]+ for (iR = 0; iR < nR; ++iR) {+ double result, res5th;+ double val0, sum2=0, sum3=0, sum4=0, sum5=0;+ unsigned k, k0 = 0;+ /* accumulate j-th function values into j-th integrals+ NOTE: this relies on the ordering of the eval functions+ above, as well as on the internal structure of+ the evalR0_0fs4d function */++ val0 = VALS(0); /* central point */+ k0 += 1;++ for (k = 0; k < dim; ++k) {+ double v0 = VALS(k0 + 4*k);+ double v1 = VALS((k0 + 4*k) + 1);+ double v2 = VALS((k0 + 4*k) + 2);+ double v3 = VALS((k0 + 4*k) + 3);++ sum2 += v0 + v1;+ sum3 += v2 + v3;++ diff[iR * dim + k] +=+ fabs(v0 + v1 - 2*val0 - ratio * (v2 + v3 - 2*val0));+ }+ k0 += 4*k;++ for (k = 0; k < numRR0_0fs(dim); ++k)+ sum4 += VALS(k0 + k);+ k0 += k;++ for (k = 0; k < numR_Rfs(dim); ++k)+ sum5 += VALS(k0 + k);++ /* Calculate fifth and seventh order results */+ result = R[iR].h.vol * (r->weight1 * val0 + weight2 * sum2 + r->weight3 * sum3 + weight4 * sum4 + r->weight5 * sum5);+ res5th = R[iR].h.vol * (r->weightE1 * val0 + weightE2 * sum2 + r->weightE3 * sum3 + weightE4 * sum4);++ R[iR].ee[j].val = result;+ R[iR].ee[j].err = fabs(res5th - result);++ v += r_->num_points * fdim;+ }+# undef VALS+ }+++ /* figure out dimension to split: */+ for (iR = 0; iR < nR; ++iR) {+ double maxdiff = 0, df = 0;+ unsigned dimDiffMax = 0;++ for (j = 0; j < fdim; ++j)+ df += R[iR].ee[j].err;+ df /= R[iR].h.vol * r->df_scale;++ for (i = 0; i < dim; ++i) {+ double delta = diff[iR*dim + i] - maxdiff;+ if (delta > df) {+ maxdiff = diff[iR*dim + i];+ dimDiffMax = i;+ }+ else if (fabs(delta) <= df && R[iR].h.data[dim + i] > R[iR].h.data[dim + dimDiffMax])+ dimDiffMax = i;+ }+ R[iR].splitDim = dimDiffMax;+ }+ return SUCCESS;+}++static rule *make_rule75genzmalik(unsigned dim, unsigned fdim)+{+ rule75genzmalik *r;++ if (dim < 2) return NULL; /* this rule does not support 1d integrals */++ /* Because of the use of a bit-field in evalR_Rfs, we are limited+ to be < 32 dimensions (or however many bits are in unsigned).+ This is not a practical limitation...long before you reach+ 32 dimensions, the Genz-Malik cubature becomes excruciatingly+ slow and is superseded by other methods (e.g. Monte-Carlo). */+ if (dim >= sizeof(unsigned) * 8) return NULL;++ r = (rule75genzmalik *) make_rule(sizeof(rule75genzmalik),+ dim, fdim,+ num0_0(dim) + 2 * numR0_0fs(dim)+ + numRR0_0fs(dim) + numR_Rfs(dim),+ rule75genzmalik_evalError,+ destroy_rule75genzmalik);+ if (!r) return NULL;++ r->weight1 = (real(12824 - 9120 * to_int(dim) + 400 * isqr(to_int(dim)))+ / real(19683));+ r->weight3 = real(1820 - 400 * to_int(dim)) / real(19683);+ r->weight5 = real(6859) / real(19683) / real(1U << dim);+ r->weightE1 = (real(729 - 950 * to_int(dim) + 50 * isqr(to_int(dim)))+ / real(729));+ r->weightE3 = real(265 - 100 * to_int(dim)) / real(1458);++ r->df_scale = pow(10, dim); /* 10^dim */++ r->p = (double *) malloc(sizeof(double) * dim * 3);+ if (!r->p) { destroy_rule((rule *) r); return NULL; }+ r->widthLambda = r->p + dim;+ r->widthLambda2 = r->p + 2 * dim;++ return (rule *) r;+}++/***************************************************************************/+/* 1d 15-point Gaussian quadrature rule, based on qk15.c and qk.c in+ GNU GSL (which in turn is based on QUADPACK). */++static int rule15gauss_evalError(rule *r,+ unsigned fdim, integrand_v f, void *fdata,+ unsigned nR, region *R)+{+ /* Gauss quadrature weights and kronrod quadrature abscissae and+ weights as evaluated with 80 decimal digit arithmetic by+ L. W. Fullerton, Bell Labs, Nov. 1981. */+ const unsigned n = 8;+ const double xgk[8] = { /* abscissae of the 15-point kronrod rule */+ 0.991455371120812639206854697526329,+ 0.949107912342758524526189684047851,+ 0.864864423359769072789712788640926,+ 0.741531185599394439863864773280788,+ 0.586087235467691130294144838258730,+ 0.405845151377397166906606412076961,+ 0.207784955007898467600689403773245,+ 0.000000000000000000000000000000000+ /* xgk[1], xgk[3], ... abscissae of the 7-point gauss rule.+ xgk[0], xgk[2], ... to optimally extend the 7-point gauss rule */+ };+ static const double wg[4] = { /* weights of the 7-point gauss rule */+ 0.129484966168869693270611432679082,+ 0.279705391489276667901467771423780,+ 0.381830050505118944950369775488975,+ 0.417959183673469387755102040816327+ };+ static const double wgk[8] = { /* weights of the 15-point kronrod rule */+ 0.022935322010529224963732008058970,+ 0.063092092629978553290700663189204,+ 0.104790010322250183839876322541518,+ 0.140653259715525918745189590510238,+ 0.169004726639267902826583426598550,+ 0.190350578064785409913256402421014,+ 0.204432940075298892414161999234649,+ 0.209482141084727828012999174891714+ };+ unsigned j, k, iR;+ size_t npts = 0;+ double *pts, *vals;++ if (alloc_rule_pts(r, nR)) return FAILURE;+ pts = r->pts; vals = r->vals;++ for (iR = 0; iR < nR; ++iR) {+ const double center = R[iR].h.data[0];+ const double halfwidth = R[iR].h.data[1];++ pts[npts++] = center;++ for (j = 0; j < (n - 1) / 2; ++j) {+ int j2 = 2*j + 1;+ double w = halfwidth * xgk[j2];+ pts[npts++] = center - w;+ pts[npts++] = center + w;+ }+ for (j = 0; j < n/2; ++j) {+ int j2 = 2*j;+ double w = halfwidth * xgk[j2];+ pts[npts++] = center - w;+ pts[npts++] = center + w;+ }++ R[iR].splitDim = 0; /* no choice but to divide 0th dimension */+ }++ if (f(1, npts, pts, fdata, fdim, vals))+ return FAILURE;++ for (k = 0; k < fdim; ++k) {+ const double *vk = vals + k;+ for (iR = 0; iR < nR; ++iR) {+ const double halfwidth = R[iR].h.data[1];+ double result_gauss = vk[0] * wg[n/2 - 1];+ double result_kronrod = vk[0] * wgk[n - 1];+ double result_abs = fabs(result_kronrod);+ double result_asc, mean, err;++ /* accumulate integrals */+ npts = 1;+ for (j = 0; j < (n - 1) / 2; ++j) {+ int j2 = 2*j + 1;+ double v = vk[fdim*npts] + vk[fdim*npts+fdim];+ result_gauss += wg[j] * v;+ result_kronrod += wgk[j2] * v;+ result_abs += wgk[j2] * (fabs(vk[fdim*npts])+ + fabs(vk[fdim*npts+fdim]));+ npts += 2;+ }+ for (j = 0; j < n/2; ++j) {+ int j2 = 2*j;+ result_kronrod += wgk[j2] * (vk[fdim*npts]+ + vk[fdim*npts+fdim]);+ result_abs += wgk[j2] * (fabs(vk[fdim*npts])+ + fabs(vk[fdim*npts+fdim]));+ npts += 2;+ }++ /* integration result */+ R[iR].ee[k].val = result_kronrod * halfwidth;++ /* error estimate+ (from GSL, probably dates back to QUADPACK+ ... not completely clear to me why we don't just use+ fabs(result_kronrod - result_gauss) * halfwidth */+ mean = result_kronrod * 0.5;+ result_asc = wgk[n - 1] * fabs(vk[0] - mean);+ npts = 1;+ for (j = 0; j < (n - 1) / 2; ++j) {+ int j2 = 2*j + 1;+ result_asc += wgk[j2] * (fabs(vk[fdim*npts]-mean)+ + fabs(vk[fdim*npts+fdim]-mean));+ npts += 2;+ }+ for (j = 0; j < n/2; ++j) {+ int j2 = 2*j;+ result_asc += wgk[j2] * (fabs(vk[fdim*npts]-mean)+ + fabs(vk[fdim*npts+fdim]-mean));+ npts += 2;+ }+ err = fabs(result_kronrod - result_gauss) * halfwidth;+ result_abs *= halfwidth;+ result_asc *= halfwidth;+ if (result_asc != 0 && err != 0) {+ double scale = pow((200 * err / result_asc), 1.5);+ err = (scale < 1) ? result_asc * scale : result_asc;+ }+ if (result_abs > DBL_MIN / (50 * DBL_EPSILON)) {+ double min_err = 50 * DBL_EPSILON * result_abs;+ if (min_err > err) err = min_err;+ }+ R[iR].ee[k].err = err;++ /* increment vk to point to next batch of results */+ vk += 15*fdim;+ }+ }+ return SUCCESS;+}++static rule *make_rule15gauss(unsigned dim, unsigned fdim)+{+ if (dim != 1) return NULL; /* this rule is only for 1d integrals */++ return make_rule(sizeof(rule), dim, fdim, 15,+ rule15gauss_evalError, 0);+}++/***************************************************************************/+/* binary heap implementation (ala _Introduction to Algorithms_ by+ Cormen, Leiserson, and Rivest), for use as a priority queue of+ regions to integrate. */++typedef region heap_item;+#define KEY(hi) ((hi).errmax)++typedef struct {+ size_t n, nalloc;+ heap_item *items;+ unsigned fdim;+ esterr *ee; /* array of length fdim of the total integrand & error */+} heap;++static void heap_resize(heap *h, size_t nalloc)+{+ h->nalloc = nalloc;+ if (nalloc)+ h->items = (heap_item *) realloc(h->items, sizeof(heap_item)*nalloc);+ else {+ /* BSD realloc does not free for a zero-sized reallocation */+ free(h->items);+ h->items = NULL;+ }+}++static heap heap_alloc(size_t nalloc, unsigned fdim)+{+ heap h;+ unsigned i;+ h.n = 0;+ h.nalloc = 0;+ h.items = 0;+ h.fdim = fdim;+ h.ee = (esterr *) malloc(sizeof(esterr) * fdim);+ if (h.ee) {+ for (i = 0; i < fdim; ++i) h.ee[i].val = h.ee[i].err = 0;+ heap_resize(&h, nalloc);+ }+ return h;+}++/* note that heap_free does not deallocate anything referenced by the items */+static void heap_free(heap *h)+{+ h->n = 0;+ heap_resize(h, 0);+ h->fdim = 0;+ free(h->ee);+}++static int heap_push(heap *h, heap_item hi)+{+ int insert;+ unsigned i, fdim = h->fdim;++ for (i = 0; i < fdim; ++i) {+ h->ee[i].val += hi.ee[i].val;+ h->ee[i].err += hi.ee[i].err;+ }+ insert = h->n;+ if (++(h->n) > h->nalloc) {+ heap_resize(h, h->n * 2);+ if (!h->items) return FAILURE;+ }++ while (insert) {+ int parent = (insert - 1) / 2;+ if (KEY(hi) <= KEY(h->items[parent]))+ break;+ h->items[insert] = h->items[parent];+ insert = parent;+ }+ h->items[insert] = hi;+ return SUCCESS;+}++static int heap_push_many(heap *h, size_t ni, heap_item *hi)+{+ size_t i;+ for (i = 0; i < ni; ++i)+ if (heap_push(h, hi[i])) return FAILURE;+ return SUCCESS;+}++static heap_item heap_pop(heap *h)+{+ heap_item ret;+ int i, n, child;++ if (!(h->n)) {+ fprintf(stderr, "attempted to pop an empty heap\n");+ exit(EXIT_FAILURE);+ }++ ret = h->items[0];+ h->items[i = 0] = h->items[n = --(h->n)];+ while ((child = i * 2 + 1) < n) {+ int largest;+ heap_item swap;++ if (KEY(h->items[child]) <= KEY(h->items[i]))+ largest = i;+ else+ largest = child;+ if (++child < n && KEY(h->items[largest]) < KEY(h->items[child]))+ largest = child;+ if (largest == i)+ break;+ swap = h->items[i];+ h->items[i] = h->items[largest];+ h->items[i = largest] = swap;+ }++ {+ unsigned i, fdim = h->fdim;+ for (i = 0; i < fdim; ++i) {+ h->ee[i].val -= ret.ee[i].val;+ h->ee[i].err -= ret.ee[i].err;+ }+ }+ return ret;+}++/***************************************************************************/++static int converged(unsigned fdim, const esterr *ee,+ double reqAbsError, double reqRelError, error_norm norm)+#define ERR(j) ee[j].err+#define VAL(j) ee[j].val+#include "converged.h"++/***************************************************************************/++/* adaptive integration, analogous to adaptintegrator.cpp in HIntLib */++static int rulecubature(rule *r, unsigned fdim,+ integrand_v f, void *fdata,+ const hypercube *h,+ size_t maxEval,+ double reqAbsError, double reqRelError,+ error_norm norm,+ double *val, double *err, int parallel)+{+ size_t numEval = 0;+ heap regions;+ unsigned i, j;+ region *R = NULL; /* array of regions to evaluate */+ size_t nR_alloc = 0;+ esterr *ee = NULL;++ if (fdim <= 1) norm = ERROR_INDIVIDUAL; /* norm is irrelevant */+ if (norm < 0 || norm > ERROR_LINF) return FAILURE; /* invalid norm */++ regions = heap_alloc(1, fdim);+ if (!regions.ee || !regions.items) goto bad;++ ee = (esterr *) malloc(sizeof(esterr) * fdim);+ if (!ee) goto bad;++ nR_alloc = 2;+ R = (region *) malloc(sizeof(region) * nR_alloc);+ if (!R) goto bad;+ R[0] = make_region(h, fdim);+ if (!R[0].ee+ || eval_regions(1, R, f, fdata, r)+ || heap_push(®ions, R[0]))+ goto bad;+ numEval += r->num_points;++ while (numEval < maxEval || !maxEval) {+ if (converged(fdim, regions.ee, reqAbsError, reqRelError, norm))+ break;++ if (parallel) { /* maximize potential parallelism */+ /* adapted from I. Gladwell, "Vectorization of one+ dimensional quadrature codes," pp. 230--238 in+ _Numerical Integration. Recent Developments,+ Software and Applications_, G. Fairweather and+ P. M. Keast, eds., NATO ASI Series C203, Dordrecht+ (1987), as described in J. M. Bull and+ T. L. Freeman, "Parallel Globally Adaptive+ Algorithms for Multi-dimensional Integration,"+ http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.42.6638+ (1994).++ Basically, this evaluates in one shot all regions+ that *must* be evaluated in order to reduce the+ error to the requested bound: the minimum set of+ largest-error regions whose errors push the total+ error over the bound.++ [Note: Bull and Freeman claim that the Gladwell+ approach is intrinsically inefficent because it+ "requires sorting", and propose an alternative+ algorithm that "only" requires three passes over the+ entire set of regions. Apparently, they didn't+ realize that one could use a heap data structure, in+ which case the time to pop K biggest-error regions+ out of N is only O(K log N), much better than the+ O(N) cost of the Bull and Freeman algorithm if K <<+ N, and it is also much simpler.] */+ size_t nR = 0;+ for (j = 0; j < fdim; ++j) ee[j] = regions.ee[j];+ do {+ if (nR + 2 > nR_alloc) {+ nR_alloc = (nR + 2) * 2;+ R = (region *) realloc(R, nR_alloc * sizeof(region));+ if (!R) goto bad;+ }+ R[nR] = heap_pop(®ions);+ for (j = 0; j < fdim; ++j) ee[j].err -= R[nR].ee[j].err;+ if (cut_region(R+nR, R+nR+1)) goto bad;+ numEval += r->num_points * 2;+ nR += 2;+ if (converged(fdim, ee, reqAbsError, reqRelError, norm))+ break; /* other regions have small errs */+ } while (regions.n > 0 && (numEval < maxEval || !maxEval));+ if (eval_regions(nR, R, f, fdata, r)+ || heap_push_many(®ions, nR, R))+ goto bad;+ }+ else { /* minimize number of function evaluations */+ R[0] = heap_pop(®ions); /* get worst region */+ if (cut_region(R, R+1)+ || eval_regions(2, R, f, fdata, r)+ || heap_push_many(®ions, 2, R))+ goto bad;+ numEval += r->num_points * 2;+ }+ }++ /* re-sum integral and errors */+ for (j = 0; j < fdim; ++j) val[j] = err[j] = 0;+ for (i = 0; i < regions.n; ++i) {+ for (j = 0; j < fdim; ++j) {+ val[j] += regions.items[i].ee[j].val;+ err[j] += regions.items[i].ee[j].err;+ }+ destroy_region(®ions.items[i]);+ }++ /* printf("regions.nalloc = %d\n", regions.nalloc); */+ free(ee);+ heap_free(®ions);+ free(R);+ return SUCCESS;++bad:+ free(ee);+ heap_free(®ions);+ free(R);+ return FAILURE;+}++static int cubature(unsigned fdim, integrand_v f, void *fdata,+ unsigned dim, const double *xmin, const double *xmax,+ size_t maxEval, double reqAbsError, double reqRelError,+ error_norm norm,+ double *val, double *err, int parallel)+{+ rule *r;+ hypercube h;+ int status;+ unsigned i;++ if (fdim == 0) /* nothing to do */ return SUCCESS;+ if (dim == 0) { /* trivial integration */+ if (f(0, 1, xmin, fdata, fdim, val)) return FAILURE;+ for (i = 0; i < fdim; ++i) err[i] = 0;+ return SUCCESS;+ }+ r = dim == 1 ? make_rule15gauss(dim, fdim)+ : make_rule75genzmalik(dim, fdim);+ if (!r) {+ for (i = 0; i < fdim; ++i) {+ val[i] = 0;+ err[i] = HUGE_VAL;+ }+ return FAILURE;+ }+ h = make_hypercube_range(dim, xmin, xmax);+ status = !h.data ? FAILURE+ : rulecubature(r, fdim, f, fdata, &h,+ maxEval, reqAbsError, reqRelError, norm,+ val, err, parallel);+ destroy_hypercube(&h);+ destroy_rule(r);+ return status;+}++int hcubature_v(unsigned fdim, integrand_v f, void *fdata,+ unsigned dim, const double *xmin, const double *xmax,+ size_t maxEval, double reqAbsError, double reqRelError,+ error_norm norm,+ double *val, double *err)+{+ return cubature(fdim, f, fdata, dim, xmin, xmax,+ maxEval, reqAbsError, reqRelError, norm, val, err, 1);+}++#include "vwrapper.h"++int hcubature(unsigned fdim, integrand f, void *fdata,+ unsigned dim, const double *xmin, const double *xmax,+ size_t maxEval, double reqAbsError, double reqRelError,+ error_norm norm,+ double *val, double *err)+{+ int ret;+ fv_data d;++ if (fdim == 0) return SUCCESS; /* nothing to do */++ d.f = f; d.fdata = fdata;+ ret = cubature(fdim, fv, &d, dim, xmin, xmax,+ maxEval, reqAbsError, reqRelError, norm, val, err, 0);+ return ret;+}++/***************************************************************************/
+ C/mintegration.c view
@@ -0,0 +1,28 @@+#include "cubature.h"++double mintegration(+ char version,+ int f(unsigned, const double*, void*, unsigned, double*),+ unsigned dim,+ double* xmin,+ double* xmax,+ double relError,+ double* errorEstimate+)+{+ double value;+ switch(version){+ case 'h':+ hcubature(+ 1, f, NULL, dim, xmin, xmax, 0, 0,+ relError, ERROR_INDIVIDUAL, &value, errorEstimate+ );+ break;+ case 'p':+ pcubature(+ 1, f, NULL, dim, xmin, xmax, 0, 0,+ relError, ERROR_INDIVIDUAL, &value, errorEstimate+ );+ }+ return value;+}
+ C/pcubature.c view
@@ -0,0 +1,424 @@+/* Adaptive multidimensional integration of a vector of integrands.+ *+ * Copyright (c) 2005-2013 Steven G. Johnson+ *+ * This program is free software; you can redistribute it and/or modify+ * it under the terms of the GNU General Public License as published by+ * the Free Software Foundation; either version 2 of the License, or+ * (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU General Public License for more details.+ *+ * You should have received a copy of the GNU General Public License+ * along with this program; if not, write to the Free Software+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA+ *+ */++/* p-adaptive cubature (adaptive by increasing the degree of the+ cubature rule rather than subdividing the domain), using products+ of Clenshaw-Curtis rules. This algorithm may be superior to+ Genz-Malik for smooth integrands lacking strongly-localized+ features, in moderate dimensions. */++#include <stdlib.h>+#include <string.h>+#include <math.h>++#include "cubature.h"++/* error return codes */+#define SUCCESS 0+#define FAILURE 1++/* pre-generated Clenshaw-Curtis rules and weights */+#include "clencurt.h"++/* no point in supporting very high dimensional integrals here */+#define MAXDIM (20U)++/***************************************************************************/+/* For adaptive cubature, thanks to the nesting of the C-C rules, we+ can re-use the values from coarser grids for finer grids, and the+ coarser grids are also used for error estimation. ++ A grid is determined by an m[dim] array, where m[i] denotes+ 2^(m[i]+1)+1 points in the i-th dimension.+*/++/* cache of the values for the m[dim] grid. If mi < dim, then we only+ store the values corresponding to the difference between the m grid+ and the grid with m[mi] -> m[mi]-1. (m[mi]-1 == -1 corresponds to+ the trivial grid of one point in the center.) */+typedef struct cacheval_s {+ unsigned m[MAXDIM];+ unsigned mi;+ double *val;+} cacheval;++/* array of ncache cachevals c[i] */+typedef struct valcache_s {+ size_t ncache;+ cacheval *c;+} valcache;++static void free_cachevals(valcache *v)+{+ if (!v) return;+ if (v->c) {+ size_t i;+ for (i = 0; i < v->ncache; ++i)+ free(v->c[i].val);+ free(v->c);+ v->c = NULL;+ }+ v->ncache = 0;+}++/***************************************************************************/++/* recursive loop over all cubature points for the given (m,mi) cache entry:+ add each point to the buffer buf, evaluating all at once whenever the+ buffer is full or when we are done */+static int compute_cacheval(const unsigned *m, unsigned mi, + double *val, size_t *vali,+ unsigned fdim, integrand_v f, void *fdata,+ unsigned dim, unsigned id, double *p,+ const double *xmin, const double *xmax,+ double *buf, size_t nbuf, size_t *ibuf)+{+ if (id == dim) { /* add point to buffer of points */+ memcpy(buf + (*ibuf)++ * dim, p, sizeof(double) * dim);+ if (*ibuf == nbuf) { /* flush buffer */+ if (f(dim, nbuf, buf, fdata, fdim, val + *vali))+ return FAILURE;+ *vali += *ibuf * fdim;+ *ibuf = 0;+ }+ }+ else {+ double c = (xmin[id] + xmax[id]) * 0.5;+ double r = (xmax[id] - xmin[id]) * 0.5;+ const double *x = clencurt_x + + ((id == mi) ? (m[id] ? (1 << (m[id] - 1)) : 0) : 0);+ unsigned i, nx = (id == mi ? (m[id] ? (1 << (m[id] - 1)) : 1)+ : (1 << (m[id])));+ if (id != mi) {+ p[id] = c;+ if (compute_cacheval(m, mi, val, vali, fdim, f, fdata,+ dim, id + 1, p,+ xmin, xmax, buf, nbuf, ibuf))+ return FAILURE;+ }+ for (i = 0; i < nx; ++i) {+ p[id] = c + r * x[i];+ if (compute_cacheval(m, mi, val, vali, fdim, f, fdata,+ dim, id + 1, p,+ xmin, xmax, buf, nbuf, ibuf))+ return FAILURE;+ p[id] = c - r * x[i];+ if (compute_cacheval(m, mi, val, vali, fdim, f, fdata,+ dim, id + 1, p,+ xmin, xmax, buf, nbuf, ibuf))+ return FAILURE;+ }+ }+ return SUCCESS;+}++static size_t num_cacheval(const unsigned *m, unsigned mi, unsigned dim)+{+ unsigned i;+ size_t nval = 1;+ for (i = 0; i < dim; ++i) {+ if (i == mi)+ nval *= m[i] == 0 ? 2 : (1 << (m[i]));+ else+ nval *= (1 << (m[i] + 1)) + 1;+ }+ return nval;+}++static int add_cacheval(valcache *vc,+ const unsigned *m, unsigned mi,+ unsigned fdim, integrand_v f, void *fdata,+ unsigned dim, const double *xmin, const double *xmax,+ double *buf, size_t nbuf)+{+ size_t ic = vc->ncache;+ size_t nval, vali = 0, ibuf = 0;+ double p[MAXDIM];++ vc->c = (cacheval *) realloc(vc->c, sizeof(cacheval) * ++(vc->ncache));+ if (!vc->c) return -1;++ vc->c[ic].mi = mi;+ memcpy(vc->c[ic].m, m, sizeof(unsigned) * dim);+ nval = fdim * num_cacheval(m, mi, dim);+ vc->c[ic].val = (double *) malloc(sizeof(double) * nval);+ if (!vc->c[ic].val) return FAILURE;++ if (compute_cacheval(m, mi, vc->c[ic].val, &vali,+ fdim, f, fdata,+ dim, 0, p, xmin, xmax,+ buf, nbuf, &ibuf))+ return FAILURE;++ if (ibuf > 0) /* flush remaining buffer */+ return f(dim, ibuf, buf, fdata, fdim, vc->c[ic].val + vali);++ return SUCCESS;+}++/***************************************************************************/++/* recursive loop to evaluate the integral contribution from the cache+ entry c, accumulating in val, for the given m[] except with m[md]+ -> m[md] - 1 if md < dim, using the cached values (cm,cmi,cval). id is the+ current loop dimension (from 0 to dim-1). */+static unsigned eval(const unsigned *cm, unsigned cmi, double *cval,+ const unsigned *m, unsigned md,+ unsigned fdim, unsigned dim, unsigned id,+ double weight, double *val)+{+ size_t voff = 0; /* amount caller should offset cval array afterwards */+ if (id == dim) {+ unsigned i;+ for (i = 0; i < fdim; ++i) val[i] += cval[i] * weight;+ voff = fdim;+ }+ else if (m[id] == 0 && id == md) /* using trivial rule for this dim */ {+ voff = eval(cm, cmi, cval, m, md, fdim, dim, id+1, weight*2, val);+ voff += fdim * (1 << cm[id]) * 2+ * num_cacheval(cm + id+1, cmi - (id+1), dim - (id+1));+ }+ else {+ unsigned i;+ unsigned mid = m[id] - (id == md); /* order of C-C rule */+ const double *w = clencurt_w + mid + (1 << mid) - 1+ + (id == cmi ? (cm[id] ? 1 + (1 << (cm[id]-1)) : 1) : 0);+ unsigned cnx = (id == cmi ? (cm[id] ? (1 << (cm[id]-1)) : 1)+ : (1 << (cm[id])));+ unsigned nx = cm[id] <= mid ? cnx : (1 << mid);++ if (id != cmi) {+ voff = eval(cm, cmi, cval, m, md, fdim, dim, id + 1,+ weight * w[0], val);+ ++w;+ }+ for (i = 0; i < nx; ++i) {+ voff += eval(cm, cmi, cval + voff, m, md, fdim, dim, id + 1,+ weight * w[i], val);+ voff += eval(cm, cmi, cval + voff, m, md, fdim, dim, id + 1,+ weight * w[i], val);+ }++ voff += (cnx - nx) * fdim * 2+ * num_cacheval(cm + id+1, cmi - (id+1), dim - (id+1));+ }+ return voff;+}++/* loop over all cache entries that contribute to the integral,+ (with m[md] decremented by 1) */+static void evals(valcache vc, const unsigned *m, unsigned md,+ unsigned fdim, unsigned dim, + double V, double *val)+{+ size_t i;++ memset(val, 0, sizeof(double) * fdim);+ for (i = 0; i < vc.ncache; ++i) {+ if (vc.c[i].mi >= dim ||+ vc.c[i].m[vc.c[i].mi] + (vc.c[i].mi == md) <= m[vc.c[i].mi])+ eval(vc.c[i].m, vc.c[i].mi, vc.c[i].val,+ m, md, fdim, dim, 0, V, val);+ }+}++/* evaluate the integrals for the given m[] using the cached values in vc,+ storing the integrals in val[], the error estimate in err[], and the+ dimension to subdivide next (the largest error contribution) in *mi */+static void eval_integral(valcache vc, const unsigned *m, + unsigned fdim, unsigned dim, double V,+ unsigned *mi, double *val, double *err, double *val1)+{+ double maxerr = 0;+ unsigned i, j;+ + evals(vc, m, dim, fdim, dim, V, val);++ /* error estimates along each dimension by comparing val with+ lower-order rule in that dimension; overall (conservative)+ error estimate from maximum error of lower-order rules. */+ memset(err, 0, sizeof(double) * fdim);+ *mi = 0;+ for (i = 0; i < dim; ++i) {+ double emax = 0;+ evals(vc, m, i, fdim, dim, V, val1);+ for (j = 0; j < fdim; ++j) {+ double e = fabs(val[j] - val1[j]);+ if (e > emax) emax = e;+ if (e > err[j]) err[j] = e;+ }+ if (emax > maxerr) {+ maxerr = emax;+ *mi = i;+ }+ }+ /* printf("eval: %g +/- %g (dim %u)\n", val[0], err[0], *mi); */+}++/***************************************************************************/++static int converged(unsigned fdim, const double *vals, const double *errs,+ double reqAbsError, double reqRelError, error_norm norm)+#define ERR(j) errs[j]+#define VAL(j) vals[j]+#include "converged.h"++/***************************************************************************/+/* Vectorized version with user-supplied buffer to store points and values.+ The buffer *buf should be of length *nbuf * dim on entry (these parameters+ are changed upon return to the final buffer and length that was used).+ The buffer length will be kept <= max(max_nbuf, 1) * dim.++ Also allows the caller to specify an array m[dim] of starting degrees+ for the rule, which upon return will hold the final degrees. The+ number of points in each dimension i is 2^(m[i]+1) + 1. */+ +int pcubature_v_buf(unsigned fdim, integrand_v f, void *fdata,+ unsigned dim, const double *xmin, const double *xmax,+ size_t maxEval,+ double reqAbsError, double reqRelError,+ error_norm norm,+ unsigned *m,+ double **buf, size_t *nbuf, size_t max_nbuf,+ double *val, double *err)+{+ int ret = FAILURE;+ double V = 1;+ size_t numEval = 0, new_nbuf;+ unsigned i;+ valcache vc = {0, NULL};+ double *val1 = NULL;++ if (fdim <= 1) norm = ERROR_INDIVIDUAL; /* norm is irrelevant */+ if (norm < 0 || norm > ERROR_LINF) return FAILURE; /* invalid norm */++ if (fdim == 0) return SUCCESS; /* nothing to do */+ if (dim > MAXDIM) return FAILURE; /* unsupported */+ if (dim == 0) { /* trivial case */+ if (f(0, 1, xmin, fdata, fdim, val)) return FAILURE;+ for (i = 0; i < fdim; ++i) err[i] = 0;+ return SUCCESS;+ }++ for (i = 0; i < fdim; ++i) {+ val[i] = 0;+ err[i] = HUGE_VAL;+ }++ for (i = 0; i < dim; ++i)+ V *= (xmax[i] - xmin[i]) * 0.5; /* scale factor for C-C volume */++ new_nbuf = num_cacheval(m, dim, dim);++ if (max_nbuf < 1) max_nbuf = 1;+ if (new_nbuf > max_nbuf) new_nbuf = max_nbuf;+ if (*nbuf < new_nbuf) {+ free(*buf);+ *buf = (double *) malloc(sizeof(double) + * (*nbuf = new_nbuf) * dim);+ if (!*buf) goto done;+ }++ /* start by evaluating the m=0 cubature rule */+ if (add_cacheval(&vc, m, dim, fdim, f, fdata, dim, xmin, xmax, + *buf, *nbuf) != SUCCESS)+ goto done;++ val1 = (double *) malloc(sizeof(double) * fdim);++ while (1) {+ unsigned mi;++ eval_integral(vc, m, fdim, dim, V, &mi, val, err, val1);+ if (converged(fdim, val, err, reqAbsError, reqRelError, norm)+ || (numEval > maxEval && maxEval)) {+ ret = SUCCESS;+ goto done;+ }+ m[mi] += 1;+ if (m[mi] > clencurt_M) goto done; /* FAILURE */++ new_nbuf = num_cacheval(m, mi, dim);+ if (new_nbuf > *nbuf && *nbuf < max_nbuf) {+ *nbuf = new_nbuf;+ if (*nbuf > max_nbuf) *nbuf = max_nbuf;+ free(*buf);+ *buf = (double *) malloc(sizeof(double) * *nbuf * dim);+ if (!*buf) goto done; /* FAILURE */+ }++ if (add_cacheval(&vc, m, mi, fdim, f, fdata, + dim, xmin, xmax, *buf, *nbuf) != SUCCESS)+ goto done; /* FAILURE */+ numEval += new_nbuf;+ }++done:+ free(val1);+ free_cachevals(&vc);+ return ret;+}++/***************************************************************************/++#define DEFAULT_MAX_NBUF (1U << 20)++int pcubature_v(unsigned fdim, integrand_v f, void *fdata,+ unsigned dim, const double *xmin, const double *xmax,+ size_t maxEval, double reqAbsError, double reqRelError,+ error_norm norm,+ double *val, double *err)+{+ int ret;+ size_t nbuf = 0;+ unsigned m[MAXDIM];+ double *buf = NULL;+ memset(m, 0, sizeof(unsigned) * dim);+ ret = pcubature_v_buf(fdim, f, fdata, dim, xmin, xmax,+ maxEval, reqAbsError, reqRelError, norm,+ m, &buf, &nbuf, DEFAULT_MAX_NBUF, val, err);+ free(buf);+ return ret;+}++#include "vwrapper.h"++int pcubature(unsigned fdim, integrand f, void *fdata,+ unsigned dim, const double *xmin, const double *xmax,+ size_t maxEval, double reqAbsError, double reqRelError,+ error_norm norm,+ double *val, double *err)+{+ int ret;+ size_t nbuf = 0;+ unsigned m[MAXDIM];+ double *buf = NULL;+ fv_data d;++ d.f = f; d.fdata = fdata;+ memset(m, 0, sizeof(unsigned) * dim);+ ret = pcubature_v_buf(+ fdim, fv, &d, dim, xmin, xmax, + maxEval, reqAbsError, reqRelError, norm,+ m, &buf, &nbuf, 16 /* max_nbuf > 0 to amortize function overhead */,+ val, err);+ free(buf);+ return ret;+}
+ C/vwrapper.h view
@@ -0,0 +1,16 @@+/* vectorized wrapper around non-vectorized integrands */+typedef struct fv_data_s { integrand f; void *fdata; } fv_data;+static int fv(unsigned ndim, size_t npt,+ const double *x, void *d_,+ unsigned fdim, double *fval)+{+ fv_data *d = (fv_data *) d_;+ integrand f = d->f;+ void *fdata = d->fdata;+ unsigned i;+ /* printf("npt = %u\n", npt); */+ for (i = 0; i < npt; ++i) + if (f(ndim, x + i*ndim, fdata, fdim, fval + i*fdim))+ return FAILURE;+ return SUCCESS;+}
+ CHANGELOG.md view
@@ -0,0 +1,5 @@+# Changelog for `adaptive-cubature`++## 0.1.0.0 - 2023-09-15++First release.
+ LICENSE view
@@ -0,0 +1,674 @@+ GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/> + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + <one line to give the program's name and a brief idea of what it does.> + Copyright (C) <year> <name of author> + + 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, see <https://www.gnu.org/licenses/>. + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + <program> Copyright (C) <year> <name of author> + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +<https://www.gnu.org/licenses/>. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +<https://www.gnu.org/licenses/why-not-lgpl.html>.
+ README.md view
@@ -0,0 +1,31 @@+# adaptive-cubature++*Adaptive integration of a multivariate function on an axis-aligned hyperrectangle.*++___++This package is powered by the C library [cubature](https://github.com/stevengj/cubature). +Follow the link for details.++### Usage++```haskell+cubature :: Char -- ^ cubature version, 'h' or 'p'+ -> ([Double] -> Double) -- ^ integrand+ -> Int -- ^ dimension (number of variables)+ -> [Double] -- ^ lower limits of integration+ -> [Double] -- ^ upper limits of integration+ -> Double -- ^ desired relative error+ -> IO Result -- ^ output: integral value and error estimate+```++### Example ++```haskell+fExample :: [Double] -> Double+fExample x = exp (-0.5 * (sum $ zipWith (*) x x))++example :: IO Result -- should give 2pi ≈ 6.283185307179586+example = cubature 'h' fExample 2 [-6, -6] [6, 6] 1e-10 +-- Result {_integral = 6.283185282383672, _error = 6.280185128024888e-10}+```
+ Setup.hs view
@@ -0,0 +1,2 @@+import Distribution.Simple+main = defaultMain
+ adaptive-cubature.cabal view
@@ -0,0 +1,43 @@+cabal-version: 2.2+name: adaptive-cubature+version: 0.1.0.0+synopsis: Multidimensional integration+description: Adaptive integration of a multivariate function on a hyperrectangle.+homepage: https://github.com/stla/adaptive-cubature#readme+license: GPL-3.0-only+license-file: LICENSE+author: Stéphane Laurent+maintainer: laurent_step@outlook.fr+copyright: 2023 Stéphane Laurent+category: Numerical+build-type: Simple+extra-source-files: README.md+ CHANGELOG.md++library+ hs-source-dirs: src+ exposed-modules: Numerical.Cubature+ build-depends: base >= 4.7 && < 5+ other-extensions: ForeignFunctionInterface+ include-dirs: C+ C-sources: C/mintegration.c+ , C/hcubature.c+ , C/pcubature.c+ install-includes: C/cubature.h+ , C/converged.h+ , C/clencurt.h+ , C/vwrapper.h+ default-language: Haskell2010+ ghc-options: -Wall+ -Wcompat+ -Widentities+ -Wincomplete-record-updates+ -Wincomplete-uni-patterns+ -Wmissing-export-lists+ -Wmissing-home-modules+ -Wpartial-fields+ -Wredundant-constraints++source-repository head+ type: git+ location: https://github.com/stla/adaptive-cubature
+ src/Numerical/Cubature.hs view
@@ -0,0 +1,63 @@+{-# LANGUAGE ForeignFunctionInterface #-}+module Numerical.Cubature+ (cubature)+ where+import Foreign.C.Types (CUInt(..))+import Foreign.Marshal.Alloc (free, mallocBytes)+import Foreign.Marshal.Array (peekArray, pokeArray)+import Foreign.Ptr (FunPtr, Ptr, freeHaskellFunPtr)+import Foreign.Storable (poke, peek, sizeOf)++type Integrand = CUInt -> Ptr Double -> Ptr () -> CUInt -> Ptr Double -> IO Int++data Result = Result+ { _integral :: Double, _error :: Double } + deriving (Show)++foreign import ccall safe "wrapper" integrandPtr+ :: Integrand -> IO (FunPtr Integrand)++foreign import ccall safe "mintegration" c_cubature+ :: Char+ -> FunPtr Integrand+ -> Int+ -> Ptr Double+ -> Ptr Double+ -> Double+ -> Ptr Double+ -> IO Double++fun2integrand :: ([Double] -> Double) -> Int -> Integrand+fun2integrand f n _ x _ _ fval = do+ list <- peekArray n x+ poke fval (f list)+ return 0++-- | Multivariate integration on an axis-aligned box.+cubature :: Char -- ^ cubature version, 'h' or 'p'+ -> ([Double] -> Double) -- ^ integrand+ -> Int -- ^ dimension (number of variables)+ -> [Double] -- ^ lower limits of integration+ -> [Double] -- ^ upper limits of integration+ -> Double -- ^ desired relative error+ -> IO Result -- ^ output: integral value and error estimate+cubature version f n xmin xmax relError = do+ fPtr <- integrandPtr (fun2integrand f n)+ xminPtr <- mallocBytes (n * sizeOf (0.0 :: Double))+ pokeArray xminPtr xmin+ xmaxPtr <- mallocBytes (n * sizeOf (0.0 :: Double))+ pokeArray xmaxPtr xmax+ errorPtr <- mallocBytes (sizeOf (0.0 :: Double))+ result <- c_cubature version fPtr n xminPtr xmaxPtr relError errorPtr+ errorEstimate <- peek errorPtr+ free errorPtr+ free xmaxPtr+ free xminPtr+ freeHaskellFunPtr fPtr+ return Result { _integral = result, _error = errorEstimate }++-- fExample :: [Double] -> Double+-- fExample list = exp (-0.5 * (sum $ zipWith (*) list list))++-- example :: IO Result+-- example = cubature 'h' fExample 2 [-6,-6] [6,6] 1e-10