lsst.afw  14.0-17-gfc02bf727
Statistics.cc
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 /*
26  * Support statistical operations on images
27  */
28 #include <cassert>
29 #include <cmath>
30 #include <cstdint>
31 #include <iostream>
32 #include <limits>
33 #include <memory>
34 #include <tuple>
35 
36 #include "lsst/pex/exceptions.h"
37 #include "lsst/afw/image/Image.h"
39 #include "lsst/afw/geom/Angle.h"
40 
41 using namespace std;
43 
44 namespace lsst {
45 namespace afw {
46 namespace math {
47 
48 namespace {
49 double const NaN = std::numeric_limits<double>::quiet_NaN();
50 double const MAX_DOUBLE = std::numeric_limits<double>::max();
51 double const IQ_TO_STDEV = 0.741301109252802; // 1 sigma in units of iqrange (assume Gaussian)
52 
54 class AlwaysTrue {
55 public:
56  template <typename T>
57  bool operator()(T) const {
58  return true;
59  }
60  template <typename Ta, typename Tb>
61  bool operator()(Ta, Tb) const {
62  return true;
63  }
64  template <typename Ta, typename Tb, typename Tc>
65  bool operator()(Ta, Tb, Tc) const {
66  return true;
67  }
68 };
69 
71 class AlwaysFalse {
72 public:
73  template <typename T>
74  bool operator()(T) const {
75  return false;
76  }
77  template <typename Ta, typename Tb>
78  bool operator()(Ta, Tb) const {
79  return false;
80  }
81  template <typename Ta, typename Tb, typename Tc>
82  bool operator()(Ta, Tb, Tc) const {
83  return false;
84  }
85 };
86 
88 class CheckFinite {
89 public:
90  template <typename T>
91  bool operator()(T val) const {
92  return std::isfinite(static_cast<float>(val));
93  }
94 };
95 
97 class CheckValueLtMin {
98 public:
99  template <typename Tval, typename Tmin>
100  bool operator()(Tval val, Tmin min) const {
101  return (static_cast<Tmin>(val) < min);
102  }
103 };
104 
106 class CheckValueGtMax {
107 public:
108  template <typename Tval, typename Tmax>
109  bool operator()(Tval val, Tmax max) const {
110  return (static_cast<Tmax>(val) > max);
111  }
112 };
113 
115 class CheckClipRange {
116 public:
117  template <typename Tval, typename Tcen, typename Tmax>
118  bool operator()(Tval val, Tcen center, Tmax cliplimit) const {
119  Tmax tmp = fabs(val - center);
120  return (tmp <= cliplimit);
121  }
122 };
123 
124 // define some abbreviated typenames for the test templates
125 typedef CheckFinite ChkFin;
126 typedef CheckValueLtMin ChkMin;
127 typedef CheckValueGtMax ChkMax;
128 typedef CheckClipRange ChkClip;
129 typedef AlwaysTrue AlwaysT;
130 typedef AlwaysFalse AlwaysF;
131 
135 inline double varianceError(double const variance, int const n) {
136  return 2 * (n - 1) * variance * variance / static_cast<double>(n * n);
137 }
138 
140 typedef std::tuple<int, // n
141  double, // sum
142  Statistics::Value, // mean
143  Statistics::Value, // variance
144  double, // min
145  double, // max
146  image::MaskPixel // allPixelOrMask
147  >
148  StandardReturn;
149 
150 /*
151  * Functions which convert the booleans into calls to the proper templated types, one type per
152  * recursion level
153  */
163 template <typename IsFinite, typename HasValueLtMin, typename HasValueGtMax, typename InClipRange,
164  bool useWeights, typename ImageT, typename MaskT, typename VarianceT, typename WeightT>
165 StandardReturn processPixels(ImageT const &img, MaskT const &msk, VarianceT const &var,
166  WeightT const &weights, int const, int const nCrude, int const stride,
167  double const meanCrude, double const cliplimit,
168  bool const weightsAreMultiplicative, int const andMask,
169  bool const calcErrorFromInputVariance,
170  std::vector<double> const &maskPropagationThresholds) {
171  int n = 0;
172  double sumw = 0.0; // sum(weight) (N.b. weight will be 1.0 if !useWeights)
173  double sumw2 = 0.0; // sum(weight^2)
174  double sumx = 0; // sum(data*weight)
175  double sumx2 = 0; // sum(data*weight^2)
176 #if 1
177  double sumvw2 = 0.0; // sum(variance*weight^2)
178 #endif
179  double min = (nCrude) ? meanCrude : MAX_DOUBLE;
180  double max = (nCrude) ? meanCrude : -MAX_DOUBLE;
181 
182  image::MaskPixel allPixelOrMask = 0x0;
183 
184  std::vector<double> rejectedWeightsByBit(maskPropagationThresholds.size(), 0.0);
185 
186  for (int iY = 0; iY < img.getHeight(); iY += stride) {
187  typename MaskT::x_iterator mptr = msk.row_begin(iY);
188  typename VarianceT::x_iterator vptr = var.row_begin(iY);
189  typename WeightT::x_iterator wptr = weights.row_begin(iY);
190 
191  for (typename ImageT::x_iterator ptr = img.row_begin(iY), end = ptr + img.getWidth(); ptr != end;
192  ++ptr, ++mptr, ++vptr, ++wptr) {
193  if (IsFinite()(*ptr) && !(*mptr & andMask) &&
194  InClipRange()(*ptr, meanCrude, cliplimit)) { // clip
195 
196  double const delta = (*ptr - meanCrude);
197 
198  if (useWeights) {
199  double weight = *wptr;
200  if (weightsAreMultiplicative) {
201  ;
202  } else {
203  if (*wptr <= 0) {
204  continue;
205  }
206  weight = 1 / weight;
207  }
208 
209  sumw += weight;
210  sumw2 += weight * weight;
211  sumx += weight * delta;
212  sumx2 += weight * delta * delta;
213 
214  if (calcErrorFromInputVariance) {
215  double const var = *vptr;
216  sumvw2 += var * weight * weight;
217  }
218  } else {
219  sumx += delta;
220  sumx2 += delta * delta;
221 
222  if (calcErrorFromInputVariance) {
223  double const var = *vptr;
224  sumvw2 += var;
225  }
226  }
227 
228  allPixelOrMask |= *mptr;
229 
230  if (HasValueLtMin()(*ptr, min)) {
231  min = *ptr;
232  }
233  if (HasValueGtMax()(*ptr, max)) {
234  max = *ptr;
235  }
236  n++;
237  } else { // pixel has been clipped, rejected, etc.
238  for (int bit = 0, nBits = maskPropagationThresholds.size(); bit < nBits; ++bit) {
239  image::MaskPixel mask = 1 << bit;
240  if (*mptr & mask) {
241  double weight = 1.0;
242  if (useWeights) {
243  weight = *wptr;
244  if (!weightsAreMultiplicative) {
245  if (*wptr <= 0) {
246  continue;
247  }
248  weight = 1.0 / weight;
249  }
250  }
251  rejectedWeightsByBit[bit] += weight;
252  }
253  }
254  }
255  }
256  }
257  if (n == 0) {
258  min = NaN;
259  max = NaN;
260  }
261 
262  // estimate of population mean and variance.
263  double mean, variance;
264  if (!useWeights) {
265  sumw = sumw2 = n;
266  }
267 
268  for (int bit = 0, nBits = maskPropagationThresholds.size(); bit < nBits; ++bit) {
269  double hypotheticalTotalWeight = sumw + rejectedWeightsByBit[bit];
270  rejectedWeightsByBit[bit] /= hypotheticalTotalWeight;
271  if (rejectedWeightsByBit[bit] > maskPropagationThresholds[bit]) {
272  allPixelOrMask |= (1 << bit);
273  }
274  }
275 
276  // N.b. if sumw == 0 or sumw*sumw == sumw2 (e.g. n == 1) we'll get NaNs
277  // N.b. the estimator of the variance assumes that the sample points all have the same variance;
278  // otherwise, what is it that we're estimating?
279  mean = sumx / sumw;
280  variance = sumx2 / sumw - ::pow(mean, 2); // biased estimator
281  variance *= sumw * sumw / (sumw * sumw - sumw2); // debias
282 
283  double meanVar; // (standard error of mean)^2
284  if (calcErrorFromInputVariance) {
285  meanVar = sumvw2 / (sumw * sumw);
286  } else {
287  meanVar = variance * sumw2 / (sumw * sumw);
288  }
289 
290  double varVar = varianceError(variance, n); // error in variance; incorrect if useWeights is true
291 
292  sumx += sumw * meanCrude;
293  mean += meanCrude;
294 
295  return StandardReturn(n, sumx, Statistics::Value(mean, meanVar), Statistics::Value(variance, varVar), min,
296  max, allPixelOrMask);
297 }
298 
299 template <typename IsFinite, typename HasValueLtMin, typename HasValueGtMax, typename InClipRange,
300  bool useWeights, typename ImageT, typename MaskT, typename VarianceT, typename WeightT>
301 StandardReturn processPixels(ImageT const &img, MaskT const &msk, VarianceT const &var,
302  WeightT const &weights, int const flags, int const nCrude, int const stride,
303  double const meanCrude, double const cliplimit,
304  bool const weightsAreMultiplicative, int const andMask,
305  bool const calcErrorFromInputVariance, bool doGetWeighted,
306  std::vector<double> const &maskPropagationThresholds) {
307  if (doGetWeighted) {
308  return processPixels<IsFinite, HasValueLtMin, HasValueGtMax, InClipRange, true>(
309  img, msk, var, weights, flags, nCrude, 1, meanCrude, cliplimit, weightsAreMultiplicative,
310  andMask, calcErrorFromInputVariance, maskPropagationThresholds);
311  } else {
312  return processPixels<IsFinite, HasValueLtMin, HasValueGtMax, InClipRange, false>(
313  img, msk, var, weights, flags, nCrude, 1, meanCrude, cliplimit, weightsAreMultiplicative,
314  andMask, calcErrorFromInputVariance, maskPropagationThresholds);
315  }
316 }
317 
318 template <typename IsFinite, typename HasValueLtMin, typename HasValueGtMax, typename InClipRange,
319  bool useWeights, typename ImageT, typename MaskT, typename VarianceT, typename WeightT>
320 StandardReturn processPixels(ImageT const &img, MaskT const &msk, VarianceT const &var,
321  WeightT const &weights, int const flags, int const nCrude, int const stride,
322  double const meanCrude, double const cliplimit,
323  bool const weightsAreMultiplicative, int const andMask,
324  bool const calcErrorFromInputVariance, bool doCheckFinite, bool doGetWeighted,
325  std::vector<double> const &maskPropagationThresholds) {
326  if (doCheckFinite) {
327  return processPixels<CheckFinite, HasValueLtMin, HasValueGtMax, InClipRange, useWeights>(
328  img, msk, var, weights, flags, nCrude, 1, meanCrude, cliplimit, weightsAreMultiplicative,
329  andMask, calcErrorFromInputVariance, doGetWeighted, maskPropagationThresholds);
330  } else {
331  return processPixels<AlwaysTrue, HasValueLtMin, HasValueGtMax, InClipRange, useWeights>(
332  img, msk, var, weights, flags, nCrude, 1, meanCrude, cliplimit, weightsAreMultiplicative,
333  andMask, calcErrorFromInputVariance, doGetWeighted, maskPropagationThresholds);
334  }
335 }
336 
354 template <typename ImageT, typename MaskT, typename VarianceT, typename WeightT>
355 StandardReturn getStandard(ImageT const &img, MaskT const &msk, VarianceT const &var, WeightT const &weights,
356  int const flags, bool const weightsAreMultiplicative, int const andMask,
357  bool const calcErrorFromInputVariance, bool doCheckFinite, bool doGetWeighted,
358  std::vector<double> const &maskPropagationThresholds) {
359  // =====================================================
360  // a crude estimate of the mean, used for numerical stability of variance
361  int nCrude = 0;
362  double meanCrude = 0.0;
363 
364  // for small numbers of values, use a small stride
365  int const nPix = img.getWidth() * img.getHeight();
366  int strideCrude;
367  if (nPix < 100) {
368  strideCrude = 2;
369  } else {
370  strideCrude = 10;
371  }
372 
373  double cliplimit = -1; // unused
374  StandardReturn values = processPixels<ChkFin, AlwaysF, AlwaysF, AlwaysT, true>(
375  img, msk, var, weights, flags, nCrude, strideCrude, meanCrude, cliplimit,
376  weightsAreMultiplicative, andMask, calcErrorFromInputVariance, doCheckFinite, doGetWeighted,
377  maskPropagationThresholds);
378  nCrude = std::get<0>(values);
379  double sumCrude = std::get<1>(values);
380 
381  meanCrude = 0.0;
382  if (nCrude > 0) {
383  meanCrude = sumCrude / nCrude;
384  }
385 
386  // =======================================================
387  // Estimate the full precision variance using that crude mean
388  // - get the min and max as well
389 
390  if (flags & (MIN | MAX)) {
391  return processPixels<ChkFin, ChkMin, ChkMax, AlwaysT, true>(
392  img, msk, var, weights, flags, nCrude, 1, meanCrude, cliplimit, weightsAreMultiplicative,
393  andMask, calcErrorFromInputVariance, true, doGetWeighted, maskPropagationThresholds);
394  } else {
395  return processPixels<ChkFin, AlwaysF, AlwaysF, AlwaysT, true>(
396  img, msk, var, weights, flags, nCrude, 1, meanCrude, cliplimit, weightsAreMultiplicative,
397  andMask, calcErrorFromInputVariance, doCheckFinite, doGetWeighted, maskPropagationThresholds);
398  }
399 }
400 
419 template <typename ImageT, typename MaskT, typename VarianceT, typename WeightT>
420 StandardReturn getStandard(ImageT const &img, MaskT const &msk, VarianceT const &var, WeightT const &weights,
421  int const flags, std::pair<double, double> const clipinfo,
422 
423  bool const weightsAreMultiplicative, int const andMask,
424  bool const calcErrorFromInputVariance, bool doCheckFinite, bool doGetWeighted,
425  std::vector<double> const &maskPropagationThresholds) {
426  double const center = clipinfo.first;
427  double const cliplimit = clipinfo.second;
428 
429  if (std::isnan(center) || std::isnan(cliplimit)) {
430  return StandardReturn(0, NaN, Statistics::Value(NaN, NaN), Statistics::Value(NaN, NaN), NaN, NaN,
431  ~0x0);
432  }
433 
434  // =======================================================
435  // Estimate the full precision variance using that crude mean
436  int const stride = 1;
437  int nCrude = 0;
438 
439  if (flags & (MIN | MAX)) {
440  return processPixels<ChkFin, ChkMin, ChkMax, ChkClip, true>(
441  img, msk, var, weights, flags, nCrude, stride, center, cliplimit, weightsAreMultiplicative,
442  andMask, calcErrorFromInputVariance, true, doGetWeighted, maskPropagationThresholds);
443  } else { // fast loop ... just the mean & variance
444  return processPixels<ChkFin, AlwaysF, AlwaysF, ChkClip, true>(
445  img, msk, var, weights, flags, nCrude, stride, center, cliplimit, weightsAreMultiplicative,
446  andMask, calcErrorFromInputVariance, doCheckFinite, doGetWeighted, maskPropagationThresholds);
447  }
448 }
449 
457 template <typename Pixel>
458 double percentile(std::vector<Pixel> &img, double const fraction) {
459  assert(fraction >= 0.0 && fraction <= 1.0);
460 
461  int const n = img.size();
462 
463  if (n > 1) {
464  double const idx = fraction * (n - 1);
465 
466  // interpolate linearly between the adjacent values
467  // For efficiency:
468  // - if we're asked for a fraction > 0.5,
469  // we'll do the second partial sort on shorter (upper) portion
470  // - otherwise, the shorter portion will be the lower one, we'll partial-sort that.
471 
472  int const q1 = static_cast<int>(idx);
473  int const q2 = q1 + 1;
474 
475  typename std::vector<Pixel>::iterator mid1 = img.begin() + q1;
476  typename std::vector<Pixel>::iterator mid2 = img.begin() + q2;
477  if (fraction > 0.5) {
478  std::nth_element(img.begin(), mid1, img.end());
479  std::nth_element(mid1, mid2, img.end());
480  } else {
481  std::nth_element(img.begin(), mid2, img.end());
482  std::nth_element(img.begin(), mid1, mid2);
483  }
484 
485  double val1 = static_cast<double>(*mid1);
486  double val2 = static_cast<double>(*mid2);
487  double w1 = (static_cast<double>(q2) - idx);
488  double w2 = (idx - static_cast<double>(q1));
489  return w1 * val1 + w2 * val2;
490 
491  } else if (n == 1) {
492  return img[0];
493  } else {
494  return NaN;
495  }
496 }
497 
498 typedef std::tuple<double, double, double> MedianQuartileReturn;
499 
505 template <typename Pixel>
506 MedianQuartileReturn medianAndQuartiles(std::vector<Pixel> &img) {
507  int const n = img.size();
508 
509  if (n > 1) {
510  double const idx50 = 0.50 * (n - 1);
511  double const idx25 = 0.25 * (n - 1);
512  double const idx75 = 0.75 * (n - 1);
513 
514  // For efficiency:
515  // - partition at 50th, then partition the two half further to get 25th and 75th
516  // - to get the adjacent points (for interpolation), partition between 25/50, 50/75, 75/end
517  // these should be much smaller partitions
518 
519  int const q50a = static_cast<int>(idx50);
520  int const q50b = q50a + 1;
521  int const q25a = static_cast<int>(idx25);
522  int const q25b = q25a + 1;
523  int const q75a = static_cast<int>(idx75);
524  int const q75b = q75a + 1;
525 
526  typename std::vector<Pixel>::iterator mid50a = img.begin() + q50a;
527  typename std::vector<Pixel>::iterator mid50b = img.begin() + q50b;
528  typename std::vector<Pixel>::iterator mid25a = img.begin() + q25a;
529  typename std::vector<Pixel>::iterator mid25b = img.begin() + q25b;
530  typename std::vector<Pixel>::iterator mid75a = img.begin() + q75a;
531  typename std::vector<Pixel>::iterator mid75b = img.begin() + q75b;
532 
533  // get the 50th percentile, then get the 25th and 75th on the smaller partitions
534  std::nth_element(img.begin(), mid50a, img.end());
535  std::nth_element(mid50a, mid75a, img.end());
536  std::nth_element(img.begin(), mid25a, mid50a);
537 
538  // and the adjacent points for each ... use the smallest segments available.
539  std::nth_element(mid50a, mid50b, mid75a);
540  std::nth_element(mid25a, mid25b, mid50a);
541  std::nth_element(mid75a, mid75b, img.end());
542 
543  // interpolate linearly between the adjacent values
544  double val50a = static_cast<double>(*mid50a);
545  double val50b = static_cast<double>(*mid50b);
546  double w50a = (static_cast<double>(q50b) - idx50);
547  double w50b = (idx50 - static_cast<double>(q50a));
548  double median = w50a * val50a + w50b * val50b;
549 
550  double val25a = static_cast<double>(*mid25a);
551  double val25b = static_cast<double>(*mid25b);
552  double w25a = (static_cast<double>(q25b) - idx25);
553  double w25b = (idx25 - static_cast<double>(q25a));
554  double q1 = w25a * val25a + w25b * val25b;
555 
556  double val75a = static_cast<double>(*mid75a);
557  double val75b = static_cast<double>(*mid75b);
558  double w75a = (static_cast<double>(q75b) - idx75);
559  double w75b = (idx75 - static_cast<double>(q75a));
560  double q3 = w75a * val75a + w75b * val75b;
561 
562  return MedianQuartileReturn(median, q1, q3);
563  } else if (n == 1) {
564  return MedianQuartileReturn(img[0], img[0], img[0]);
565  } else {
566  return MedianQuartileReturn(NaN, NaN, NaN);
567  }
568 }
569 
577 template <typename IsFinite, typename ImageT, typename MaskT, typename VarianceT>
578 std::shared_ptr<std::vector<typename ImageT::Pixel> > makeVectorCopy(ImageT const &img, MaskT const &msk,
579  VarianceT const &, int const andMask) {
580  // Note need to keep track of allPixelOrMask here ... processPixels() does that
581  // and it always gets called
583 
584  for (int i_y = 0; i_y < img.getHeight(); ++i_y) {
585  typename MaskT::x_iterator mptr = msk.row_begin(i_y);
586  for (typename ImageT::x_iterator ptr = img.row_begin(i_y), end = img.row_end(i_y); ptr != end;
587  ++ptr) {
588  if (IsFinite()(*ptr) && !(*mptr & andMask)) {
589  imgcp->push_back(*ptr);
590  }
591  ++mptr;
592  }
593  }
594 
595  return imgcp;
596 }
597 }
598 
599 double StatisticsControl::getMaskPropagationThreshold(int bit) const {
600  int oldSize = _maskPropagationThresholds.size();
601  if (oldSize < bit) {
602  return 1.0;
603  }
604  return _maskPropagationThresholds[bit];
605 }
606 
607 void StatisticsControl::setMaskPropagationThreshold(int bit, double threshold) {
608  int oldSize = _maskPropagationThresholds.size();
609  if (oldSize <= bit) {
610  int newSize = bit + 1;
611  _maskPropagationThresholds.resize(newSize);
612  for (int i = oldSize; i < bit; ++i) {
613  _maskPropagationThresholds[i] = 1.0;
614  }
615  }
616  _maskPropagationThresholds[bit] = threshold;
617 }
618 
620  static std::map<std::string, Property> statisticsProperty;
621  if (statisticsProperty.size() == 0) {
622  statisticsProperty["NOTHING"] = NOTHING;
623  statisticsProperty["ERRORS"] = ERRORS;
624  statisticsProperty["NPOINT"] = NPOINT;
625  statisticsProperty["MEAN"] = MEAN;
626  statisticsProperty["STDEV"] = STDEV;
627  statisticsProperty["VARIANCE"] = VARIANCE;
628  statisticsProperty["MEDIAN"] = MEDIAN;
629  statisticsProperty["IQRANGE"] = IQRANGE;
630  statisticsProperty["MEANCLIP"] = MEANCLIP;
631  statisticsProperty["STDEVCLIP"] = STDEVCLIP;
632  statisticsProperty["VARIANCECLIP"] = VARIANCECLIP;
633  statisticsProperty["MIN"] = MIN;
634  statisticsProperty["MAX"] = MAX;
635  statisticsProperty["SUM"] = SUM;
636  statisticsProperty["MEANSQUARE"] = MEANSQUARE;
637  statisticsProperty["ORMASK"] = ORMASK;
638  }
639  return statisticsProperty[property];
640 }
641 
642 template <typename ImageT, typename MaskT, typename VarianceT>
643 Statistics::Statistics(ImageT const &img, MaskT const &msk, VarianceT const &var, int const flags,
644  StatisticsControl const &sctrl)
645  : _flags(flags),
646  _mean(NaN, NaN),
647  _variance(NaN, NaN),
648  _min(NaN),
649  _max(NaN),
650  _sum(NaN),
651  _meanclip(NaN, NaN),
652  _varianceclip(NaN, NaN),
653  _median(NaN, NaN),
654  _iqrange(NaN),
655  _sctrl(sctrl),
656  _weightsAreMultiplicative(false) {
657  doStatistics(img, msk, var, var, _flags, _sctrl);
658 }
659 
660 namespace {
661 template <typename T>
662 bool isEmpty(T const &t) {
663  return t.empty();
664 }
665 
666 template <typename T>
667 bool isEmpty(image::Image<T> const &im) {
668  return (im.getWidth() == 0 && im.getHeight() == 0);
669 }
670 
671 // Asserts that image dimensions are equal
672 template <typename ImageT1, typename ImageT2>
673 void checkDimensions(ImageT1 const &image1, ImageT2 const &image2) {
674  if (image1.getDimensions() != image2.getDimensions()) {
676  (boost::format("Image sizes don't match: %s vs %s") % image1.getDimensions() %
677  image2.getDimensions())
678  .str());
679  }
680 }
681 
682 // Overloads for MaskImposter (which doesn't have a size)
683 template <typename ImageT, typename PixelT>
684 void checkDimensions(ImageT const &image1, MaskImposter<PixelT> const &image2) {}
685 template <typename ImageT, typename PixelT>
686 void checkDimensions(MaskImposter<PixelT> const &image1, ImageT const &image2) {}
687 }
688 
689 template <typename ImageT, typename MaskT, typename VarianceT, typename WeightT>
690 Statistics::Statistics(ImageT const &img, MaskT const &msk, VarianceT const &var, WeightT const &weights,
691  int const flags, StatisticsControl const &sctrl)
692  : _flags(flags),
693  _mean(NaN, NaN),
694  _variance(NaN, NaN),
695  _min(NaN),
696  _max(NaN),
697  _sum(NaN),
698  _meanclip(NaN, NaN),
699  _varianceclip(NaN, NaN),
700  _median(NaN, NaN),
701  _iqrange(NaN),
702  _sctrl(sctrl),
703  _weightsAreMultiplicative(true) {
704  if (!isEmpty(weights)) {
705  if (_sctrl.getWeightedIsSet() && !_sctrl.getWeighted()) {
707  "You must use the weights if you provide them");
708  }
709 
710  _sctrl.setWeighted(true);
711  }
712  doStatistics(img, msk, var, weights, _flags, _sctrl);
713 }
714 
715 template <typename ImageT, typename MaskT, typename VarianceT, typename WeightT>
716 void Statistics::doStatistics(ImageT const &img, MaskT const &msk, VarianceT const &var,
717  WeightT const &weights, int const flags, StatisticsControl const &sctrl) {
718  _n = img.getWidth() * img.getHeight();
719  if (_n == 0) {
720  throw LSST_EXCEPT(pexExceptions::InvalidParameterError, "Image contains no pixels");
721  }
722  checkDimensions(img, msk);
723  checkDimensions(img, var);
724  if (sctrl.getWeighted()) {
725  checkDimensions(img, weights);
726  }
727 
728  // Check that an int's large enough to hold the number of pixels
729  assert(img.getWidth() * static_cast<double>(img.getHeight()) < std::numeric_limits<int>::max());
730 
731  // get the standard statistics
732  StandardReturn standard =
733  getStandard(img, msk, var, weights, flags, _weightsAreMultiplicative, _sctrl.getAndMask(),
734  _sctrl.getCalcErrorFromInputVariance(), _sctrl.getNanSafe(), _sctrl.getWeighted(),
735  _sctrl._maskPropagationThresholds);
736 
737  _n = std::get<0>(standard);
738  _sum = std::get<1>(standard);
739  _mean = std::get<2>(standard);
740  _variance = std::get<3>(standard);
741  _min = std::get<4>(standard);
742  _max = std::get<5>(standard);
743  _allPixelOrMask = std::get<6>(standard);
744 
745  // ==========================================================
746  // now only calculate it if it's specifically requested - these all cost more!
747 
748  // copy the image for any routines that will use median or quantiles
749  if (flags & (MEDIAN | IQRANGE | MEANCLIP | STDEVCLIP | VARIANCECLIP)) {
750  // make a vector copy of the image to get the median and quartiles (will move values)
752  if (_sctrl.getNanSafe()) {
753  imgcp = makeVectorCopy<ChkFin>(img, msk, var, _sctrl.getAndMask());
754  } else {
755  imgcp = makeVectorCopy<AlwaysT>(img, msk, var, _sctrl.getAndMask());
756  }
757 
758  // if we *only* want the median, just use percentile(), otherwise use medianAndQuartiles()
759  if ((flags & (MEDIAN)) && !(flags & (IQRANGE | MEANCLIP | STDEVCLIP | VARIANCECLIP))) {
760  _median = Value(percentile(*imgcp, 0.5), NaN);
761  } else {
762  MedianQuartileReturn mq = medianAndQuartiles(*imgcp);
763  _median = Value(std::get<0>(mq), NaN);
764  _iqrange = std::get<2>(mq) - std::get<1>(mq);
765  }
766 
767  if (flags & (MEANCLIP | STDEVCLIP | VARIANCECLIP)) {
768  for (int i_i = 0; i_i < _sctrl.getNumIter(); ++i_i) {
769  double const center = ((i_i > 0) ? _meanclip : _median).first;
770  double const hwidth = (i_i > 0 && _n > 1)
771  ? _sctrl.getNumSigmaClip() * std::sqrt(_varianceclip.first)
772  : _sctrl.getNumSigmaClip() * IQ_TO_STDEV * _iqrange;
773  std::pair<double, double> const clipinfo(center, hwidth);
774 
775  StandardReturn clipped = getStandard(
776  img, msk, var, weights, flags, clipinfo, _weightsAreMultiplicative,
777  _sctrl.getAndMask(), _sctrl.getCalcErrorFromInputVariance(), _sctrl.getNanSafe(),
778  _sctrl.getWeighted(), _sctrl._maskPropagationThresholds);
779 
780  int const nClip = std::get<0>(clipped);
781  _meanclip = std::get<2>(clipped); // clipped mean
782  double const varClip = std::get<3>(clipped).first; // clipped variance
783 
784  _varianceclip = Value(varClip, varianceError(varClip, nClip));
785  // ... ignore other values
786  }
787  }
788  }
789 }
790 
792  // if iProp == NOTHING try to return their heart's delight, as specified in the constructor
793  Property const prop = static_cast<Property>(((iProp == NOTHING) ? _flags : iProp) & ~ERRORS);
794 
795  if (!(prop & _flags)) { // we didn't calculate it
797  (boost::format("You didn't ask me to calculate %d") % prop).str());
798  }
799 
800  Value ret(NaN, NaN);
801  switch (prop) {
802  case NPOINT:
803  ret.first = static_cast<double>(_n);
804  if (_flags & ERRORS) {
805  ret.second = 0;
806  }
807  break;
808 
809  case SUM:
810  ret.first = static_cast<double>(_sum);
811  if (_flags & ERRORS) {
812  ret.second = 0;
813  }
814  break;
815 
816  // == means ==
817  case MEAN:
818  ret.first = _mean.first;
819  if (_flags & ERRORS) {
820  ret.second = ::sqrt(_mean.second);
821  }
822  break;
823  case MEANCLIP:
824  ret.first = _meanclip.first;
825  if (_flags & ERRORS) {
826  ret.second = ::sqrt(_meanclip.second);
827  }
828  break;
829 
830  // == stdevs & variances ==
831  case VARIANCE:
832  ret.first = _variance.first;
833  if (_flags & ERRORS) {
834  ret.second = ::sqrt(_variance.second);
835  }
836  break;
837  case STDEV:
838  ret.first = sqrt(_variance.first);
839  if (_flags & ERRORS) {
840  ret.second = 0.5 * ::sqrt(_variance.second) / ret.first;
841  }
842  break;
843  case VARIANCECLIP:
844  ret.first = _varianceclip.first;
845  if (_flags & ERRORS) {
846  ret.second = ret.second;
847  }
848  break;
849  case STDEVCLIP:
850  ret.first = sqrt(_varianceclip.first);
851  if (_flags & ERRORS) {
852  ret.second = 0.5 * ::sqrt(_varianceclip.second) / ret.first;
853  }
854  break;
855 
856  case MEANSQUARE:
857  ret.first = (_n - 1) / static_cast<double>(_n) * _variance.first + ::pow(_mean.first, 2);
858  if (_flags & ERRORS) {
859  ret.second = ::sqrt(2 * ::pow(ret.first / _n, 2)); // assumes Gaussian
860  }
861  break;
862 
863  // == other stats ==
864  case MIN:
865  ret.first = _min;
866  if (_flags & ERRORS) {
867  ret.second = 0;
868  }
869  break;
870  case MAX:
871  ret.first = _max;
872  if (_flags & ERRORS) {
873  ret.second = 0;
874  }
875  break;
876  case MEDIAN:
877  ret.first = _median.first;
878  if (_flags & ERRORS) {
879  ret.second = sqrt(geom::HALFPI * _variance.first / _n); // assumes Gaussian
880  }
881  break;
882  case IQRANGE:
883  ret.first = _iqrange;
884  if (_flags & ERRORS) {
885  ret.second = NaN; // we're not estimating this properly
886  }
887  break;
888 
889  // no-op to satisfy the compiler
890  case ERRORS:
891  break;
892  // default: redundant as 'ret' is initialized to NaN, NaN
893  default: // we must have set prop to _flags
894  assert(iProp == 0);
896  "getValue() may only be called without a parameter"
897  " if you asked for only one statistic");
898  }
899  return ret;
900 }
901 
902 double Statistics::getValue(Property const prop) const { return getResult(prop).first; }
903 
904 double Statistics::getError(Property const prop) const { return getResult(prop).second; }
905 
915 template <>
917  image::Mask<image::MaskPixel> const &var, int const flags,
918  StatisticsControl const &sctrl)
919  : _flags(flags),
920  _mean(NaN, NaN),
921  _variance(NaN, NaN),
922  _min(NaN),
923  _max(NaN),
924  _meanclip(NaN, NaN),
925  _varianceclip(NaN, NaN),
926  _median(NaN, NaN),
927  _iqrange(NaN),
928  _sctrl(sctrl) {
929  if ((flags & ~(NPOINT | SUM)) != 0x0) {
931  "Statistics<Mask> only supports NPOINT and SUM");
932  }
933 
934  typedef image::Mask<image::MaskPixel> Mask;
935 
936  _n = msk.getWidth() * msk.getHeight();
937  if (_n == 0) {
938  throw LSST_EXCEPT(pexExceptions::InvalidParameterError, "Image contains no pixels");
939  }
940 
941  // Check that an int's large enough to hold the number of pixels
942  assert(msk.getWidth() * static_cast<double>(msk.getHeight()) < std::numeric_limits<int>::max());
943 
944  image::MaskPixel sum = 0x0;
945  for (int y = 0; y != msk.getHeight(); ++y) {
946  for (Mask::x_iterator ptr = msk.row_begin(y), end = msk.row_end(y); ptr != end; ++ptr) {
947  sum |= (*ptr)[0];
948  }
949  }
950  _sum = sum;
951 }
952 
953 /*
954  * Although short, the definition can't be in the header as it must
955  * follow the specialization definition
956  * (g++ complained when this was in the header.)
957  */
959  StatisticsControl const &sctrl) {
960  return Statistics(msk, msk, msk, flags, sctrl);
961 }
962 
963 /*
964  * Explicit instantiations
965  *
966  * explicit Statistics(MaskedImage const& img, int const flags,
967  * StatisticsControl const& sctrl=StatisticsControl());
968  */
970 //
971 #define STAT Statistics
972 
973 typedef image::VariancePixel VPixel;
974 
975 #define INSTANTIATE_MASKEDIMAGE_STATISTICS(TYPE) \
976  template STAT::Statistics(image::Image<TYPE> const &img, image::Mask<image::MaskPixel> const &msk, \
977  image::Image<VPixel> const &var, int const flags, \
978  StatisticsControl const &sctrl); \
979  template STAT::Statistics(image::Image<TYPE> const &img, image::Mask<image::MaskPixel> const &msk, \
980  image::Image<VPixel> const &var, image::Image<VPixel> const &weights, \
981  int const flags, StatisticsControl const &sctrl); \
982  template STAT::Statistics(image::Image<TYPE> const &img, image::Mask<image::MaskPixel> const &msk, \
983  image::Image<VPixel> const &var, ImageImposter<VPixel> const &weights, \
984  int const flags, StatisticsControl const &sctrl)
985 
986 #define INSTANTIATE_MASKEDIMAGE_STATISTICS_NO_MASK(TYPE) \
987  template STAT::Statistics(image::Image<TYPE> const &img, MaskImposter<image::MaskPixel> const &msk, \
988  image::Image<VPixel> const &var, int const flags, \
989  StatisticsControl const &sctrl); \
990  template STAT::Statistics(image::Image<TYPE> const &img, MaskImposter<image::MaskPixel> const &msk, \
991  image::Image<VPixel> const &var, image::Image<VPixel> const &weights, \
992  int const flags, StatisticsControl const &sctrl)
993 
994 #define INSTANTIATE_MASKEDIMAGE_STATISTICS_NO_VAR(TYPE) \
995  template STAT::Statistics(image::Image<TYPE> const &img, image::Mask<image::MaskPixel> const &msk, \
996  MaskImposter<VPixel> const &var, int const flags, \
997  StatisticsControl const &sctrl); \
998  template STAT::Statistics(image::Image<TYPE> const &img, image::Mask<image::MaskPixel> const &msk, \
999  MaskImposter<VPixel> const &var, image::Image<VPixel> const &weights, \
1000  int const flags, StatisticsControl const &sctrl); \
1001  template STAT::Statistics(image::Image<TYPE> const &img, image::Mask<image::MaskPixel> const &msk, \
1002  MaskImposter<VPixel> const &var, ImageImposter<VPixel> const &weights, \
1003  int const flags, StatisticsControl const &sctrl)
1004 
1005 #define INSTANTIATE_REGULARIMAGE_STATISTICS(TYPE) \
1006  template STAT::Statistics(image::Image<TYPE> const &img, MaskImposter<image::MaskPixel> const &msk, \
1007  MaskImposter<VPixel> const &var, int const flags, \
1008  StatisticsControl const &sctrl)
1009 
1010 #define INSTANTIATE_VECTOR_STATISTICS(TYPE) \
1011  template STAT::Statistics(ImageImposter<TYPE> const &img, MaskImposter<image::MaskPixel> const &msk, \
1012  MaskImposter<VPixel> const &var, int const flags, \
1013  StatisticsControl const &sctrl); \
1014  template STAT::Statistics(ImageImposter<TYPE> const &img, MaskImposter<image::MaskPixel> const &msk, \
1015  MaskImposter<VPixel> const &var, ImageImposter<VPixel> const &weights, \
1016  int const flags, StatisticsControl const &sctrl)
1017 
1018 #define INSTANTIATE_IMAGE_STATISTICS(T) \
1019  INSTANTIATE_MASKEDIMAGE_STATISTICS(T); \
1020  INSTANTIATE_MASKEDIMAGE_STATISTICS_NO_VAR(T); \
1021  INSTANTIATE_MASKEDIMAGE_STATISTICS_NO_MASK(T); \
1022  INSTANTIATE_REGULARIMAGE_STATISTICS(T); \
1023  INSTANTIATE_VECTOR_STATISTICS(T)
1024 
1025 INSTANTIATE_IMAGE_STATISTICS(double);
1026 INSTANTIATE_IMAGE_STATISTICS(float);
1027 INSTANTIATE_IMAGE_STATISTICS(int);
1028 INSTANTIATE_IMAGE_STATISTICS(std::uint16_t);
1029 INSTANTIATE_IMAGE_STATISTICS(std::uint64_t);
1030 
1032 }
1033 }
1034 } // end math
Value getResult(Property const prop=NOTHING) const
Return the value and error in the specified statistic (e.g.
Definition: Statistics.cc:791
afw::table::Key< afw::table::Array< VariancePixelT > > variance
afw::table::Key< afw::table::Array< MaskPixelT > > mask
get the or-mask of all pixels used.
Definition: Statistics.h:80
estimate sample minimum
Definition: Statistics.h:76
double constexpr HALFPI
Definition: Angle.h:23
double getError(Property const prop=NOTHING) const
Return the error in the desired property (if specified in the constructor)
Definition: Statistics.cc:904
int getHeight() const
Return the number of rows in the image.
Definition: ImageBase.h:299
estimate sample standard deviation
Definition: Statistics.h:68
find mean value of square of pixel values
Definition: Statistics.h:79
STL namespace.
estimate sample maximum
Definition: Statistics.h:77
T end(T... args)
We don&#39;t want anything.
Definition: Statistics.h:64
bool getCalcErrorFromInputVariance() const
Definition: Statistics.h:138
STL class.
Include errors of requested quantities.
Definition: Statistics.h:65
x_iterator row_begin(int y) const
Return an x_iterator to the start of the y&#39;th row.
Definition: ImageBase.h:402
A class to evaluate image statistics.
Definition: Statistics.h:213
Statistics(ImageT const &img, MaskT const &msk, VarianceT const &var, int const flags, StatisticsControl const &sctrl=StatisticsControl())
Constructor for Statistics object.
Definition: Statistics.cc:643
STL class.
T min(T... args)
estimate sample N-sigma clipped stdev (N set in StatisticsControl, default=3)
Definition: Statistics.h:73
std::pair< double, double > Value
The type used to report (value, error) for desired statistics.
Definition: Statistics.h:216
Property stringToStatisticsProperty(std::string const property)
Conversion function to switch a string to a Property (see Statistics.h)
Definition: Statistics.cc:619
estimate sample median
Definition: Statistics.h:70
Pass parameters to a Statistics object.
Definition: Statistics.h:91
estimate sample N-sigma clipped mean (N set in StatisticsControl, default=3)
Definition: Statistics.h:72
A base class for image defects.
int end
Represent a 2-dimensional array of bitmask pixels.
Definition: Mask.h:83
estimate sample N-sigma clipped variance (N set in StatisticsControl, default=3)
Definition: Statistics.h:74
A Mask wrapper to provide an infinite_iterator for Mask::row_begin().
Definition: Statistics.h:329
number of sample points
Definition: Statistics.h:66
T isfinite(T... args)
T fabs(T... args)
T max(T... args)
void setWeighted(bool useWeights)
Definition: Statistics.h:151
double getValue(Property const prop=NOTHING) const
Return the value of the desired property (if specified in the constructor)
Definition: Statistics.cc:902
T size(T... args)
#define LSST_EXCEPT(type,...)
estimate sample inter-quartile range
Definition: Statistics.h:71
T begin(T... args)
T pow(T... args)
estimate sample mean
Definition: Statistics.h:67
int getWidth() const
Return the number of columns in the image.
Definition: ImageBase.h:297
estimate sample variance
Definition: Statistics.h:69
T isnan(T... args)
x_iterator row_end(int y) const
Return an x_iterator to the end of the y&#39;th row.
Definition: ImageBase.h:405
T nth_element(T... args)
T quiet_NaN(T... args)
T sqrt(T... args)
find sum of pixels in the image
Definition: Statistics.h:78
float VariancePixel
default type for MaskedImage variance images
Property
control what is calculated
Definition: Statistics.h:63
A class to represent a 2-dimensional array of pixels.
Definition: Image.h:68
Statistics makeStatistics(lsst::afw::image::Image< Pixel > const &img, lsst::afw::image::Mask< image::MaskPixel > const &msk, int const flags, StatisticsControl const &sctrl=StatisticsControl())
Handle a watered-down front-end to the constructor (no variance)
Definition: Statistics.h:344