lsst.afw  13.0-109-g62eb66483
Integrate.h
Go to the documentation of this file.
1 // -*- LSST-C++ -*-
2 
3 /*
4  * LSST Data Management System
5  * Copyright 2008, 2009, 2010 LSST Corporation.
6  *
7  * This product includes software developed by the
8  * LSST Project (http://www.lsst.org/).
9  *
10  * This program is free software: you can redistribute it and/or modify
11  * it under the terms of the GNU General Public License as published by
12  * the Free Software Foundation, either version 3 of the License, or
13  * (at your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18  * GNU General Public License for more details.
19  *
20  * You should have received a copy of the LSST License Statement and
21  * the GNU General Public License along with this program. If not,
22  * see <http://www.lsstcorp.org/LegalNotices/>.
23  */
24 
25 #if !defined(LSST_AFW_MATH_INTEGRATE_H)
26 #define LSST_AFW_MATH_INTEGRATE_H 1
27 /*
28  * Compute 1d and 2d integral
29  */
30 
31 #include <functional>
32 #include <vector>
33 #include <queue>
34 #include <map>
35 #include <cmath>
36 #include <algorithm>
37 #include <assert.h>
38 #include <limits>
39 #include <ostream>
40 #include <sstream>
41 #include <complex>
42 #include <stdexcept>
43 
44 #include "lsst/pex/exceptions.h"
45 
47 
48 // == The following is Mike Jarvis original comment ==
49 //
50 // Basic Usage:
51 //
52 // First, define a function object, which should derive from
53 // std::unary_function<double,double>. For example, to integrate a
54 // Gaussian, use something along the lines of this:
55 //
56 // class Gauss :
57 // public std::unary_function<double,double>
58 // {
59 // public :
60 //
61 // Gauss(double _mu, double _sig) :
62 // mu(_mu), sig(_sig), sigsq(_sig*_sig) {}
63 //
64 // double operator()(double x) const
65 // {
66 // const double SQRTTWOPI = 2.50662827463;
67 // return exp(-pow(x-mu,2)/2./sigsq)/SQRTTWOPI/sig;
68 // }
69 //
70 // private :
71 // double mu,sig,sigsq;
72 // };
73 //
74 // Next, make an IntRegion object with the bounds of the integration region.
75 // You need to give it the type to use for the bounds and the value of the
76 // functions (which need to be the same currently - some day I'll allow
77 // complex functions...).
78 //
79 // For example, to integrate something from -1 to 1, use:
80 //
81 // integ::IntRegion<double> reg1(-1.,1.);
82 //
83 // (The integ:: is because everything here is in the integ namespace to
84 // help prevent name conflicts with other header files.)
85 //
86 // If a value is > 1.e10 or < -1.e10, then these values are taken to be
87 // infinity, rather than the actual value.
88 // So to integrate from 0 to infinity:
89 //
90 // integ::IntRegion<double> reg2(0.,1.e100);
91 //
92 // Or, you can use the variable integ::MOCK_INF which might be clearer.
93 //
94 //
95 // Finally, to perform the integral, the line would be:
96 //
97 // double integ1 = int1d(Gauss(0.,1.),reg1,1.e-10,1.e-4);
98 // double integ2 = int1d(Gauss(0.,2.),reg2,1.e-10,1.e-4);
99 //
100 // which should yield 0.68 and 0.5 in our case.
101 //
102 // Those last two numbers indicate the precision required.
103 // 1.e-10 is the required absolute error, and
104 // 1.e-4 is the required relative error.
105 //
106 // If you want, you can omit these and 1.e-15,1.e-6 will be used as the
107 // default precision (which are generally fine for most purposes).
108 //
109 // The absolute error only comes into play for results which are close to
110 // 0 to prevent requiring an error of 0 for integrals which evaluate to 0
111 // or very close to it.
112 //
113 //
114 //
115 // Advanced Usage:
116 //
117 // When an integration fails to converge with the usual GKP algorithm,
118 // it splits the region into 2 (or more) and tries again with each sub-region.
119 // The default is to just bisect the region (or something similarly smart for
120 // infinite regions), but if you know of a good place to split the region,
121 // you can tell it using:
122 //
123 // reg.AddSplit(10.)
124 //
125 // For example, if you know that you have a singularity somewhere in your
126 // region, it would help the program a lot to split there, so you
127 // should add that as a split point. Zeros can also be good choices.
128 //
129 // In addition to the integral being returned from int1d, int2d, or int3d as
130 // the return value, the value is also stored in the region itself.
131 // You can access it using:
132 //
133 // reg.Area();
134 //
135 // There is also an estimate of the error in the value:
136 //
137 // reg.Err();
138 //
139 // (It is intended to be an overestimate of the actual error,
140 // but it doesn't always get it completely right.)
141 //
142 //
143 //
144 // Two- and Three-Dimensional Integrals:
145 //
146 // These are slightly more complicated. The easiest case is when the
147 // bounds of the integral are a rectangle or 3d box. In this case,
148 // you can still use the regular IntRegion. The only new thing then
149 // is the definition of the function. For example, to integrate
150 // int(3x^2 + xy + y , x=0..1, y=0..1):
151 //
152 // struct Integrand :
153 // public std::binary_function<double,double,double>
154 // {
155 // double operator()(double x, double y) const
156 // { return x*(3.*x + y) + y; }
157 // };
158 //
159 // integ::IntRegion<double> reg3(0.,1.);
160 // double integ3 = int2d(Integrand(),reg3,reg3);
161 //
162 // (Which should give 1.75 as the result.)
163 //
164 //
165 //
166 
167 namespace lsst {
168 namespace afw {
169 namespace math {
170 
171 double const MOCK_INF = 1.e10;
172 
173 #ifdef NDEBUG
174 #define integ_dbg1 \
175  if (false) (*_dbgout)
176 #define integ_dbg2 \
177  if (false) (*(reg.getDbgout()))
178 #define integ_dbg3 \
179  if (false) (*(tempreg.getDbgout()))
180 #else
181 #define integ_dbg1 \
182  if (_dbgout) (*_dbgout)
183 #define integ_dbg2 \
184  if (reg.getDbgout()) (*(reg.getDbgout()))
185 #define integ_dbg3 \
186  if (tempreg.getDbgout()) (*(tempreg.getDbgout()))
187 #endif
188 
189 //#define COUNTFEVAL
190 // If defined, then count the number of function evaluations
191 
192 namespace details {
193 template <class T>
194 inline T norm(const T &x) {
195  return x * x;
196 }
197 using std::norm;
198 template <class T>
199 inline T real(const T &x) {
200  return x;
201 }
202 using std::real;
203 #ifdef COUNTFEVAL
204 int nfeval = 0;
205 #endif
206 }
207 
208 template <class T>
209 struct IntRegion {
210 public:
211  IntRegion(T const a, T const b, std::ostream *dbgout = 0)
212  : _a(a), _b(b), _error(0.0), _area(0), _dbgout(dbgout) {}
213 
214  bool operator<(IntRegion<T> const &r2) const { return _error < r2._error; }
215  bool operator>(IntRegion<T> const &r2) const { return _error > r2._error; }
216 
217  void SubDivide(std::vector<IntRegion<T> > *children) {
218  assert(children->size() == 0);
219  if (_splitpoints.size() == 0) {
220  Bisect();
221  }
222  if (_splitpoints.size() > 1) {
223  std::sort(_splitpoints.begin(), _splitpoints.end());
224  }
225 
226 #if 0
227  if (_a > _splitpoints[0] || _b < _splitpoints.back()) {
228  std::cerr << "a, b = " << _a << ', ' << _b << std::endl;
229  std::cerr << "_splitpoints = ";
230  for (size_t i = 0; i<_splitpoints.size(); i++) {
231  std::cerr << _splitpoints[i] << " ";
232  }
233  std::cerr << std::endl;
234  }
235 #endif
236  assert(_splitpoints[0] >= _a);
237  assert(_splitpoints.back() <= _b);
238  children->push_back(IntRegion<T>(_a, _splitpoints[0], _dbgout));
239  for (size_t i = 1; i < _splitpoints.size(); i++) {
240  children->push_back(IntRegion<T>(_splitpoints[i - 1], _splitpoints[i], _dbgout));
241  }
242  children->push_back(IntRegion<T>(_splitpoints.back(), _b, _dbgout));
243  }
244 
245  void Bisect() { _splitpoints.push_back((_a + _b) / 2.0); }
246  void AddSplit(const T x) { _splitpoints.push_back(x); }
247  size_t NSplit() const { return _splitpoints.size(); }
248 
249  T const &Left() const { return _a; }
250  T const &Right() const { return _b; }
251  T const &Err() const { return _error; }
252  T const &Area() const { return _area; }
253  void SetArea(const T &a, const T &e) {
254  _area = a;
255  _error = e;
256  }
257 
258  std::ostream *getDbgout() { return _dbgout; }
259 
260 private:
261  T _a, _b, _error, _area;
262  std::vector<T> _splitpoints;
263  std::ostream *_dbgout;
264 };
265 
266 double const DEFABSERR = 1.e-15;
267 double const DEFRELERR = 1.e-6;
268 
269 namespace details {
270 
271 template <class T>
272 inline T Epsilon() {
273  return std::numeric_limits<T>::epsilon();
274 }
275 template <class T>
276 inline T MinRep() {
278 }
279 
280 #ifdef EXTRA_PREC_H
281 template <>
282 inline Quad Epsilon<Quad>() {
283  return 3.08148791094e-33;
284 }
285 template <>
286 inline Quad MinRep<Quad>() {
287  return 2.2250738585072014e-308;
288 }
289 #endif
290 
291 template <class T>
292 inline T rescale_error(T err, T const &resabs, T const &resasc) {
293  if (resasc != 0.0 && err != 0.0) {
294  T const scale = (200.0 * err / resasc);
295  if (scale < 1.0) {
296  err = resasc * scale * sqrt(scale);
297  } else {
298  err = resasc;
299  }
300  }
301  if (resabs > MinRep<T>() / (50.0 * Epsilon<T>())) {
302  T const min_err = 50.0 * Epsilon<T>() * resabs;
303  if (min_err > err) {
304  err = min_err;
305  }
306  }
307  return err;
308 }
309 
326 template <class UF>
327 inline bool intGKPNA(UF const &func, IntRegion<typename UF::result_type> &reg,
328  typename UF::result_type const epsabs, typename UF::result_type const epsrel,
329  std::map<typename UF::result_type, typename UF::result_type> *fxmap = 0) {
330  typedef typename UF::result_type UfResult;
331  UfResult const a = reg.Left();
332  UfResult const b = reg.Right();
333 
334  UfResult const halfLength = 0.5 * (b - a);
335  UfResult const absHalfLength = fabs(halfLength);
336  UfResult const center = 0.5 * (b + a);
337  UfResult const fCenter = func(center);
338 #ifdef COUNTFEVAL
339  nfeval++;
340 #endif
341 
342  assert(gkp_wb<UfResult>(0).size() == gkp_x<UfResult>(0).size() + 1);
343  UfResult area1 = gkp_wb<UfResult>(0).back() * fCenter;
344  std::vector<UfResult> fv1, fv2;
345  fv1.reserve(2 * gkp_x<UfResult>(0).size() + 1);
346  fv2.reserve(2 * gkp_x<UfResult>(0).size() + 1);
347  for (size_t k = 0; k < gkp_x<UfResult>(0).size(); k++) {
348  UfResult const abscissa = halfLength * gkp_x<UfResult>(0)[k];
349  UfResult const fval1 = func(center - abscissa);
350  UfResult const fval2 = func(center + abscissa);
351  area1 += gkp_wb<UfResult>(0)[k] * (fval1 + fval2);
352  fv1.push_back(fval1);
353  fv2.push_back(fval2);
354  if (fxmap) {
355  (*fxmap)[center - abscissa] = fval1;
356  (*fxmap)[center + abscissa] = fval2;
357  }
358  }
359 #ifdef COUNTFEVAL
360  nfeval += gkp_x<UfResult>(0).size() * 2;
361 #endif
362 
363  integ_dbg2 << "level 0 rule: area = " << area1 << std::endl;
364 
365  UfResult err = 0;
366  bool calcabsasc = true;
367  UfResult resabs = 0.0, resasc = 0.0;
368  for (int level = 1; level < NGKPLEVELS; level++) {
369  assert(gkp_wa<UfResult>(level).size() == fv1.size());
370  assert(gkp_wa<UfResult>(level).size() == fv2.size());
371  assert(gkp_wb<UfResult>(level).size() == gkp_x<UfResult>(level).size() + 1);
372  UfResult area2 = gkp_wb<UfResult>(level).back() * fCenter;
373  // resabs = approximation to integral of abs(f)
374  if (calcabsasc) {
375  resabs = fabs(area2);
376  }
377  for (size_t k = 0; k < fv1.size(); k++) {
378  area2 += gkp_wa<UfResult>(level)[k] * (fv1[k] + fv2[k]);
379  if (calcabsasc) {
380  resabs += gkp_wa<UfResult>(level)[k] * (fabs(fv1[k]) + fabs(fv2[k]));
381  }
382  }
383  for (size_t k = 0; k < gkp_x<UfResult>(level).size(); k++) {
384  UfResult const abscissa = halfLength * gkp_x<UfResult>(level)[k];
385  UfResult const fval1 = func(center - abscissa);
386  UfResult const fval2 = func(center + abscissa);
387  UfResult const fval = fval1 + fval2;
388  area2 += gkp_wb<UfResult>(level)[k] * fval;
389  if (calcabsasc) {
390  resabs += gkp_wb<UfResult>(level)[k] * (fabs(fval1) + fabs(fval2));
391  }
392  fv1.push_back(fval1);
393  fv2.push_back(fval2);
394  if (fxmap) {
395  (*fxmap)[center - abscissa] = fval1;
396  (*fxmap)[center + abscissa] = fval2;
397  }
398  }
399 #ifdef COUNTFEVAL
400  nfeval += gkp_x<UfResult>(level).size() * 2;
401 #endif
402  if (calcabsasc) {
403  UfResult const mean = area1 * UfResult(0.5);
404  // resasc = approximation to the integral of abs(f-mean)
405  resasc = gkp_wb<UfResult>(level).back() * fabs(fCenter - mean);
406  for (size_t k = 0; k < gkp_wa<UfResult>(level).size(); k++) {
407  resasc += gkp_wa<UfResult>(level)[k] * (fabs(fv1[k] - mean) + fabs(fv2[k] - mean));
408  }
409  for (size_t k = 0; k < gkp_x<UfResult>(level).size(); k++) {
410  resasc += gkp_wb<UfResult>(level)[k] * (fabs(fv1[k] - mean) + fabs(fv2[k] - mean));
411  }
412  resasc *= absHalfLength;
413  resabs *= absHalfLength;
414  }
415  area2 *= halfLength;
416  err = rescale_error(fabs(area2 - area1), resabs, resasc);
417  if (err < resasc) {
418  calcabsasc = false;
419  }
420 
421  integ_dbg2 << "at level " << level << " area2 = " << area2;
422  integ_dbg2 << " +- " << err << std::endl;
423 
424  // test for convergence.
425  if (err < epsabs || err < epsrel * fabs(area2)) {
426  reg.SetArea(area2, err);
427  return true;
428  }
429  area1 = area2;
430  }
431 
432  // failed to converge
433  reg.SetArea(area1, err);
434 
435  integ_dbg2 << "Failed to reach tolerance with highest-order GKP rule";
436 
437  return false;
438 }
439 
456 template <class UF>
457 inline void intGKP(UF const &func, IntRegion<typename UF::result_type> &reg,
458  typename UF::result_type const epsabs, typename UF::result_type const epsrel,
459  std::map<typename UF::result_type, typename UF::result_type> *fxmap = 0) {
460  typedef typename UF::result_type UfResult;
461  integ_dbg2 << "Start intGKP\n";
462 
463  assert(epsabs >= 0.0);
464  assert(epsrel > 0.0);
465 
466  // perform the first integration
467  bool done = intGKPNA(func, reg, epsabs, epsrel, fxmap);
468  if (done) return;
469 
470  integ_dbg2 << "In adaptive GKP, failed first pass... subdividing\n";
471  integ_dbg2 << "Intial range = " << reg.Left() << ".." << reg.Right() << std::endl;
472 
473  int roundoffType1 = 0, errorType = 0;
474  UfResult roundoffType2 = 0;
475  size_t iteration = 1;
476 
477  std::priority_queue<IntRegion<UfResult>, std::vector<IntRegion<UfResult> > > allregions;
478  allregions.push(reg);
479  UfResult finalarea = reg.Area();
480  UfResult finalerr = reg.Err();
481  UfResult tolerance = std::max(epsabs, epsrel * fabs(finalarea));
482  assert(finalerr > tolerance);
483 
484  while (!errorType && finalerr > tolerance) {
485  // Bisect the subinterval with the largest error estimate
486  integ_dbg2 << "Current answer = " << finalarea << " +- " << finalerr;
487  integ_dbg2 << " (tol = " << tolerance << ")\n";
488  IntRegion<UfResult> parent = allregions.top();
489  allregions.pop();
490  integ_dbg2 << "Subdividing largest error region ";
491  integ_dbg2 << parent.Left() << ".." << parent.Right() << std::endl;
492  integ_dbg2 << "parent area = " << parent.Area();
493  integ_dbg2 << " +- " << parent.Err() << std::endl;
494  std::vector<IntRegion<UfResult> > children;
495  parent.SubDivide(&children);
496  // For "GKP", there are only two, but for GKPOSC, there is one
497  // for each oscillation in region
498 
499  // Try to do at least 3x better with the children
500  UfResult factor = 3 * children.size() * finalerr / tolerance;
501  UfResult newepsabs = fabs(parent.Err() / factor);
502  UfResult newepsrel = newepsabs / fabs(parent.Area());
503  integ_dbg2 << "New epsabs, rel = " << newepsabs << ", " << newepsrel;
504  integ_dbg2 << " (" << children.size() << " children)\n";
505 
506  UfResult newarea = UfResult(0.0);
507  UfResult newerror = 0.0;
508  for (size_t i = 0; i < children.size(); i++) {
509  IntRegion<UfResult> &child = children[i];
510  integ_dbg2 << "Integrating child " << child.Left();
511  integ_dbg2 << ".." << child.Right() << std::endl;
512  bool hasConverged;
513  hasConverged = intGKPNA(func, child, newepsabs, newepsrel);
514  integ_dbg2 << "child (" << i + 1 << '/' << children.size() << ") ";
515  if (hasConverged) {
516  integ_dbg2 << " converged.";
517  } else {
518  integ_dbg2 << " failed.";
519  }
520  integ_dbg2 << " Area = " << child.Area() << " +- " << child.Err() << std::endl;
521 
522  newarea += child.Area();
523  newerror += child.Err();
524  }
525  integ_dbg2 << "Compare: newerr = " << newerror;
526  integ_dbg2 << " to parent err = " << parent.Err() << std::endl;
527 
528  finalerr += (newerror - parent.Err());
529  finalarea += newarea - parent.Area();
530 
531  UfResult delta = parent.Area() - newarea;
532  if (newerror <= parent.Err() && fabs(delta) <= parent.Err() && newerror >= 0.99 * parent.Err()) {
533  integ_dbg2 << "roundoff type 1: delta/newarea = ";
534  integ_dbg2 << fabs(delta) / fabs(newarea);
535  integ_dbg2 << ", newerror/error = " << newerror / parent.Err() << std::endl;
536  roundoffType1++;
537  }
538  if (iteration >= 10 && newerror > parent.Err() && fabs(delta) <= newerror - parent.Err()) {
539  integ_dbg2 << "roundoff type 2: newerror/error = ";
540  integ_dbg2 << newerror / parent.Err() << std::endl;
541  roundoffType2 += std::min(newerror / parent.Err() - 1.0, UfResult(1.0));
542  }
543 
544  tolerance = std::max(epsabs, epsrel * fabs(finalarea));
545  if (finalerr > tolerance) {
546  if (roundoffType1 >= 200) {
547  errorType = 1; // round off error
548  integ_dbg2 << "GKP: Round off error 1\n";
549  }
550  if (roundoffType2 >= 200.0) {
551  errorType = 2; // round off error
552  integ_dbg2 << "GKP: Round off error 2\n";
553  }
554  if (fabs((parent.Right() - parent.Left()) / (reg.Right() - reg.Left())) < Epsilon<double>()) {
555  errorType = 3; // found singularity
556  integ_dbg2 << "GKP: Probable singularity\n";
557  }
558  }
559  for (size_t i = 0; i < children.size(); i++) {
560  allregions.push(children[i]);
561  }
562  iteration++;
563  }
564 
565  // Recalculate finalarea in case there are any slight rounding errors
566  finalarea = 0.0;
567  finalerr = 0.0;
568  while (!allregions.empty()) {
569  IntRegion<UfResult> const &r = allregions.top();
570  finalarea += r.Area();
571  finalerr += r.Err();
572  allregions.pop();
573  }
574  reg.SetArea(finalarea, finalerr);
575 
576  if (errorType == 1) {
577  std::ostringstream s;
578  s << "Type 1 roundoff's = " << roundoffType1;
579  s << ", Type 2 = " << roundoffType2 << std::endl;
580  s << "Roundoff error 1 prevents tolerance from being achieved ";
581  s << "in intGKP\n";
582  throw LSST_EXCEPT(lsst::pex::exceptions::RuntimeError, s.str());
583  } else if (errorType == 2) {
584  std::ostringstream s;
585  s << "Type 1 roundoff's = " << roundoffType1;
586  s << ", Type 2 = " << roundoffType2 << std::endl;
587  s << "Roundoff error 2 prevents tolerance from being achieved ";
588  s << "in intGKP\n";
589  throw LSST_EXCEPT(lsst::pex::exceptions::RuntimeError, s.str());
590  } else if (errorType == 3) {
591  std::ostringstream s;
592  s << "Bad integrand behavior found in the integration interval ";
593  s << "in intGKP\n";
594  throw LSST_EXCEPT(lsst::pex::exceptions::RuntimeError, s.str());
595  }
596 }
597 
602 template <class UF>
603 struct AuxFunc1 : // f(1/x-1) for int(a..infinity)
604  public std::unary_function<typename UF::argument_type, typename UF::result_type> {
605 public:
606  AuxFunc1(const UF &f) : _f(f) {}
607  typename UF::result_type operator()(typename UF::argument_type x) const {
608  return _f(1.0 / x - 1.0) / (x * x);
609  }
610 
611 private:
612  UF const &_f;
613 };
614 
619 template <class UF>
620 AuxFunc1<UF> inline Aux1(UF uf) {
621  return AuxFunc1<UF>(uf);
622 }
623 
624 template <class UF>
625 struct AuxFunc2 : // f(1/x+1) for int(-infinity..b)
626  public std::unary_function<typename UF::argument_type, typename UF::result_type> {
627 public:
628  AuxFunc2(UF const &f) : _f(f) {}
629  typename UF::result_type operator()(typename UF::argument_type x) const {
630  return _f(1.0 / x + 1.0) / (x * x);
631  }
632 
633 private:
634  UF const &_f;
635 };
636 
641 template <class UF>
642 AuxFunc2<UF> inline Aux2(UF uf) {
643  return AuxFunc2<UF>(uf);
644 }
645 
650 template <class T>
651 struct ConstantReg1 : public std::unary_function<T, IntRegion<T> > {
652  ConstantReg1(T a, T b) : ir(a, b) {}
653  ConstantReg1(IntRegion<T> const &r) : ir(r) {}
654  IntRegion<T> operator()(T) const { return ir; }
656 };
657 
658 template <class T>
659 struct ConstantReg2 : public std::binary_function<T, T, IntRegion<T> > {
660  ConstantReg2(T a, T b) : ir(a, b) {}
661  ConstantReg2(IntRegion<T> const &r) : ir(r) {}
662  IntRegion<T> operator()(T x, T y) const { return ir; }
664 };
665 
666 // pulled from MoreFunctional.h. Needed in class Int2DAuxType and Int3DAuxType
667 template <class BF>
668 class binder2_1 : public std::unary_function<typename BF::second_argument_type, typename BF::result_type> {
669 public:
670  binder2_1(const BF &oper, typename BF::first_argument_type val) : _oper(oper), _value(val) {}
671  typename BF::result_type operator()(const typename BF::second_argument_type &x) const {
672  return _oper(_value, x);
673  }
674 
675 protected:
676  BF _oper;
677  typename BF::first_argument_type _value;
678 };
679 
680 template <class BF, class Tp>
681 inline binder2_1<BF> bind21(const BF &oper, const Tp &x) {
682  typedef typename BF::first_argument_type Arg;
683  return binder2_1<BF>(oper, static_cast<Arg>(x));
684 }
685 
686 template <class BF, class YREG>
687 class Int2DAuxType : public std::unary_function<typename BF::first_argument_type, typename BF::result_type> {
688 public:
689  Int2DAuxType(BF const &func, YREG const &yreg, typename BF::result_type const &abserr,
690  typename BF::result_type const &relerr)
691  : _func(func), _yreg(yreg), _abserr(abserr), _relerr(relerr) {}
692 
693  typename BF::result_type operator()(typename BF::first_argument_type x) const {
694  typename YREG::result_type tempreg = _yreg(x);
695  typename BF::result_type result = int1d(bind21(_func, x), tempreg, _abserr, _relerr);
696  integ_dbg3 << "Evaluated int2dAux at x = " << x;
697  integ_dbg3 << ": f = " << result << " +- " << tempreg.Err() << std::endl;
698  return result;
699  }
700 
701 private:
702  BF const &_func;
703  YREG const &_yreg;
704  typename BF::result_type _abserr, _relerr;
705 };
706 
707 // pulled from MoreFunctional.h. Needed in class Int3DAuxtype
708 template <class TF>
709 class binder3_1 : public std::binary_function<typename TF::secondof3_argument_type,
710  typename TF::thirdof3_argument_type, typename TF::result_type> {
711 public:
712  binder3_1(const TF &oper, typename TF::firstof3_argument_type val) : _oper(oper), _value(val) {}
713  typename TF::result_type operator()(typename TF::secondof3_argument_type const &x1,
714  typename TF::thirdof3_argument_type const &x2) const {
715  return _oper(_value, x1, x2);
716  }
717 
718 protected:
719  TF _oper;
720  typename TF::firstof3_argument_type _value;
721 };
722 
723 template <class TF, class Tp>
724 inline binder3_1<TF> bind31(const TF &oper, const Tp &x) {
725  typedef typename TF::firstof3_argument_type Arg;
726  return binder3_1<TF>(oper, static_cast<Arg>(x));
727 }
728 
729 template <class TF, class YREG, class ZREG>
731  : public std::unary_function<typename TF::firstof3_argument_type, typename TF::result_type> {
732 public:
733  Int3DAuxType(const TF &func, const YREG &yreg, const ZREG &zreg, const typename TF::result_type &abserr,
734  const typename TF::result_type &relerr)
735  : _func(func), _yreg(yreg), _zreg(zreg), _abserr(abserr), _relerr(relerr) {}
736 
737  typename TF::result_type operator()(typename TF::firstof3_argument_type x) const {
738  typename YREG::result_type tempreg = _yreg(x);
739  typename TF::result_type result =
740  int2d(bind31(_func, x), tempreg, bind21(_zreg, x), _abserr, _relerr);
741  integ_dbg3 << "Evaluated int3dAux at x = " << x;
742  integ_dbg3 << ": f = " << result << " +- " << tempreg.Err() << std::endl;
743  return result;
744  }
745 
746 private:
747  const TF &_func;
748  const YREG &_yreg;
749  const ZREG &_zreg;
750  typename TF::result_type _abserr, _relerr;
751 };
752 
753 } // end namespace details
754 
758 template <class UF>
759 inline typename UF::result_type int1d(UF const &func, IntRegion<typename UF::result_type> &reg,
760  typename UF::result_type const &abserr = DEFABSERR,
761  typename UF::result_type const &relerr = DEFRELERR) {
762  typedef typename UF::result_type UfResult;
763  using namespace details;
764 
765  integ_dbg2 << "start int1d: " << reg.Left() << ".." << reg.Right() << std::endl;
766 
767  if ((reg.Left() <= -MOCK_INF && reg.Right() > 0) || (reg.Right() >= MOCK_INF && reg.Left() < 0)) {
768  reg.AddSplit(0);
769  }
770 
771  if (reg.NSplit() > 0) {
772  std::vector<IntRegion<UfResult> > children;
773  reg.SubDivide(&children);
774  integ_dbg2 << "Subdivided into " << children.size() << " children\n";
775  UfResult answer = UfResult();
776  UfResult err = 0;
777  for (size_t i = 0; i < children.size(); i++) {
778  IntRegion<UfResult> &child = children[i];
779  integ_dbg2 << "i = " << i;
780  integ_dbg2 << ": bounds = " << child.Left() << ", " << child.Right() << std::endl;
781  answer += int1d(func, child, abserr, relerr);
782  err += child.Err();
783  integ_dbg2 << "subint = " << child.Area() << " +- " << child.Err() << std::endl;
784  }
785  reg.SetArea(answer, err);
786  return answer;
787 
788  } else {
789  if (reg.Left() <= -MOCK_INF) {
790  integ_dbg2 << "left = -infinity, right = " << reg.Right() << std::endl;
791  assert(reg.Right() <= 0.0);
792  IntRegion<UfResult> modreg(1.0 / (reg.Right() - 1.0), 0.0, reg.getDbgout());
793  intGKP(Aux2<UF>(func), modreg, abserr, relerr);
794  reg.SetArea(modreg.Area(), modreg.Err());
795  } else if (reg.Right() >= MOCK_INF) {
796  integ_dbg2 << "left = " << reg.Left() << ", right = infinity\n";
797  assert(reg.Left() >= 0.0);
798  IntRegion<UfResult> modreg(0.0, 1.0 / (reg.Left() + 1.0), reg.getDbgout());
799  intGKP(Aux1<UF>(func), modreg, abserr, relerr);
800  reg.SetArea(modreg.Area(), modreg.Err());
801  } else {
802  integ_dbg2 << "left = " << reg.Left();
803  integ_dbg2 << ", right = " << reg.Right() << std::endl;
804  intGKP(func, reg, abserr, relerr);
805  }
806  integ_dbg2 << "done int1d answer = " << reg.Area();
807  integ_dbg2 << " +- " << reg.Err() << std::endl;
808  return reg.Area();
809  }
810 }
811 
815 template <class BF, class YREG>
816 inline typename BF::result_type int2d(BF const &func, IntRegion<typename BF::result_type> &reg,
817  YREG const &yreg, typename BF::result_type const &abserr = DEFABSERR,
818  typename BF::result_type const &relerr = DEFRELERR) {
819  using namespace details;
820  integ_dbg2 << "Starting int2d: range = ";
821  integ_dbg2 << reg.Left() << ".." << reg.Right() << std::endl;
822  Int2DAuxType<BF, YREG> faux(func, yreg, abserr * 1.0e-3, relerr * 1.0e-3);
823  typename BF::result_type answer = int1d(faux, reg, abserr, relerr);
824  integ_dbg2 << "done int2d answer = " << answer << " +- " << reg.Err() << std::endl;
825  return answer;
826 }
827 
831 template <class TF, class YREG, class ZREG>
832 inline typename TF::result_type int3d(TF const &func, IntRegion<typename TF::result_type> &reg,
833  YREG const &yreg, ZREG const &zreg,
834  typename TF::result_type const &abserr = DEFABSERR,
835  typename TF::result_type const &relerr = DEFRELERR) {
836  using namespace details;
837  integ_dbg2 << "Starting int3d: range = ";
838  integ_dbg2 << reg.Left() << ".." << reg.Right() << std::endl;
839  Int3DAuxType<TF, YREG, ZREG> faux(func, yreg, zreg, abserr * 1.e-3, relerr * 1.e-3);
840  typename TF::result_type answer = int1d(faux, reg, abserr, relerr);
841  integ_dbg2 << "done int3d answer = " << answer << " +- " << reg.Err() << std::endl;
842  return answer;
843 }
844 
848 template <class BF>
849 inline typename BF::result_type int2d(BF const &func, IntRegion<typename BF::result_type> &reg,
851  typename BF::result_type const &abserr = DEFABSERR,
852  typename BF::result_type const &relerr = DEFRELERR) {
853  using namespace details;
854  return int2d(func, reg, ConstantReg1<typename BF::result_type>(yreg), abserr, relerr);
855 }
856 
860 template <class TF>
861 inline typename TF::result_type int3d(TF const &func, IntRegion<typename TF::result_type> &reg,
864  typename TF::result_type const &abserr = DEFABSERR,
865  typename TF::result_type const &relerr = DEFRELERR) {
866  using namespace details;
867  return int3d(func, reg, ConstantReg1<typename TF::result_type>(yreg),
868  ConstantReg2<typename TF::result_type>(zreg), abserr, relerr);
869 }
870 
871 // =============================================================
879 template <typename UnaryFunctionT>
880 typename UnaryFunctionT::result_type integrate(UnaryFunctionT func,
881  typename UnaryFunctionT::argument_type const a,
882  typename UnaryFunctionT::argument_type const b,
883  double eps = 1.0e-6) {
884  typedef typename UnaryFunctionT::argument_type Arg;
885  IntRegion<Arg> region(a, b);
886 
887  return int1d(func, region, DEFABSERR, eps);
888 }
889 
890 namespace details {
891 
901 template <typename BinaryFunctionT>
902 class FunctionWrapper : public std::unary_function<typename BinaryFunctionT::second_argument_type,
903  typename BinaryFunctionT::result_type> {
904 public:
905  FunctionWrapper(BinaryFunctionT func, typename BinaryFunctionT::first_argument_type const x1,
906  typename BinaryFunctionT::first_argument_type const x2, double const eps = 1.0e-6)
907  : _func(func), _x1(x1), _x2(x2), _eps(eps) {}
908  typename BinaryFunctionT::result_type operator()(
909  typename BinaryFunctionT::second_argument_type const y) const {
910  return integrate(std::bind2nd(_func, y), _x1, _x2, _eps);
911  }
912 
913 private:
914  BinaryFunctionT _func;
915  typename BinaryFunctionT::first_argument_type _x1, _x2;
916  double _eps;
917 };
918 
919 } // end of namespace afw::math::details
920 
921 // =============================================================
928 template <typename BinaryFunctionT>
929 typename BinaryFunctionT::result_type integrate2d(BinaryFunctionT func,
930  typename BinaryFunctionT::first_argument_type const x1,
931  typename BinaryFunctionT::first_argument_type const x2,
932  typename BinaryFunctionT::second_argument_type const y1,
933  typename BinaryFunctionT::second_argument_type const y2,
934  double eps = 1.0e-6) {
935  using namespace details;
936  // note the more stringent eps requirement to ensure the requested limit
937  // can be reached.
938  FunctionWrapper<BinaryFunctionT> fwrap(func, x1, x2, eps);
939  return integrate(fwrap, y1, y2, eps);
940 }
941 }
942 }
943 } // end namespaces lsst/afw/math
944 
945 #endif
IntRegion< T > operator()(T) const
Definition: Integrate.h:654
T const & Right() const
Definition: Integrate.h:250
BF::result_type int2d(BF const &func, IntRegion< typename BF::result_type > &reg, YREG const &yreg, typename BF::result_type const &abserr=DEFABSERR, typename BF::result_type const &relerr=DEFRELERR)
Front end for the 2d integrator.
Definition: Integrate.h:816
bool operator>(IntRegion< T > const &r2) const
Definition: Integrate.h:215
FunctionWrapper(BinaryFunctionT func, typename BinaryFunctionT::first_argument_type const x1, typename BinaryFunctionT::first_argument_type const x2, double const eps=1.0e-6)
Definition: Integrate.h:905
void AddSplit(const T x)
Definition: Integrate.h:246
binder2_1< BF > bind21(const BF &oper, const Tp &x)
Definition: Integrate.h:681
BinaryFunctionT::result_type integrate2d(BinaryFunctionT func, typename BinaryFunctionT::first_argument_type const x1, typename BinaryFunctionT::first_argument_type const x2, typename BinaryFunctionT::second_argument_type const y1, typename BinaryFunctionT::second_argument_type const y2, double eps=1.0e-6)
The 2D integrator.
Definition: Integrate.h:929
def scale(algorithm, min, max=None, frame=None)
Definition: ds9.py:117
#define integ_dbg3
Definition: Integrate.h:185
double const DEFABSERR
Definition: Integrate.h:266
int min
Definition: Coord.cc:160
T norm(const T &x)
Definition: Integrate.h:194
void SetArea(const T &a, const T &e)
Definition: Integrate.h:253
BinaryFunctionT::result_type operator()(typename BinaryFunctionT::second_argument_type const y) const
Definition: Integrate.h:908
void SubDivide(std::vector< IntRegion< T > > *children)
Definition: Integrate.h:217
AuxFunc1< UF > Aux1(UF uf)
Auxiliary function 1.
Definition: Integrate.h:620
TF::result_type operator()(typename TF::secondof3_argument_type const &x1, typename TF::thirdof3_argument_type const &x2) const
Definition: Integrate.h:713
ConstantReg2(IntRegion< T > const &r)
Definition: Integrate.h:661
UF::result_type int1d(UF const &func, IntRegion< typename UF::result_type > &reg, typename UF::result_type const &abserr=DEFABSERR, typename UF::result_type const &relerr=DEFRELERR)
Front end for the 1d integrator.
Definition: Integrate.h:759
T const & Area() const
Definition: Integrate.h:252
A base class for image defects.
Definition: cameraGeom.dox:3
UF::result_type operator()(typename UF::argument_type x) const
Definition: Integrate.h:629
ConstantReg1(IntRegion< T > const &r)
Definition: Integrate.h:653
AuxFunc2< UF > Aux2(UF uf)
Auxiliary function 2.
Definition: Integrate.h:642
Int3DAuxType(const TF &func, const YREG &yreg, const ZREG &zreg, const typename TF::result_type &abserr, const typename TF::result_type &relerr)
Definition: Integrate.h:733
binder3_1< TF > bind31(const TF &oper, const Tp &x)
Definition: Integrate.h:724
int max
Definition: BoundedField.cc:99
IntRegion< T > operator()(T x, T y) const
Definition: Integrate.h:662
double x
TF::firstof3_argument_type _value
Definition: Integrate.h:720
TF::result_type operator()(typename TF::firstof3_argument_type x) const
Definition: Integrate.h:737
BF::first_argument_type _value
Definition: Integrate.h:677
T const & Err() const
Definition: Integrate.h:251
T const & Left() const
Definition: Integrate.h:249
Int2DAuxType(BF const &func, YREG const &yreg, typename BF::result_type const &abserr, typename BF::result_type const &relerr)
Definition: Integrate.h:689
double const MOCK_INF
Definition: Integrate.h:171
BF::result_type operator()(const typename BF::second_argument_type &x) const
Definition: Integrate.h:671
binder3_1(const TF &oper, typename TF::firstof3_argument_type val)
Definition: Integrate.h:712
std::ostream * getDbgout()
Definition: Integrate.h:258
#define integ_dbg2
Definition: Integrate.h:183
UF::result_type operator()(typename UF::argument_type x) const
Definition: Integrate.h:607
double const DEFRELERR
Definition: Integrate.h:267
BF::result_type operator()(typename BF::first_argument_type x) const
Definition: Integrate.h:693
bool intGKPNA(UF const &func, IntRegion< typename UF::result_type > &reg, typename UF::result_type const epsabs, typename UF::result_type const epsrel, std::map< typename UF::result_type, typename UF::result_type > *fxmap=0)
Non-adaptive integration of the function f over the region &#39;reg&#39;.
Definition: Integrate.h:327
size_t NSplit() const
Definition: Integrate.h:247
TF::result_type int3d(TF const &func, IntRegion< typename TF::result_type > &reg, YREG const &yreg, ZREG const &zreg, typename TF::result_type const &abserr=DEFABSERR, typename TF::result_type const &relerr=DEFRELERR)
Front end for the 3d integrator.
Definition: Integrate.h:832
binder2_1(const BF &oper, typename BF::first_argument_type val)
Definition: Integrate.h:670
T rescale_error(T err, T const &resabs, T const &resasc)
Definition: Integrate.h:292
IntRegion(T const a, T const b, std::ostream *dbgout=0)
Definition: Integrate.h:211
T real(const T &x)
Definition: Integrate.h:199
void intGKP(UF const &func, IntRegion< typename UF::result_type > &reg, typename UF::result_type const epsabs, typename UF::result_type const epsrel, std::map< typename UF::result_type, typename UF::result_type > *fxmap=0)
An adaptive integration algorithm which computes the integral of f over the region reg...
Definition: Integrate.h:457
Wrap an integrand in a call to a 1D integrator: romberg()
Definition: Integrate.h:902
UnaryFunctionT::result_type integrate(UnaryFunctionT func, typename UnaryFunctionT::argument_type const a, typename UnaryFunctionT::argument_type const b, double eps=1.0e-6)
The 1D integrator.
Definition: Integrate.h:880
Helpers for constant regions for int2d, int3d:
Definition: Integrate.h:651