lsst.afw  14.0-25-g0e8fc950e+5
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  statisticsProperty["NCLIPPED"] = NCLIPPED;
639  statisticsProperty["NMASKED"] = NMASKED;
640  }
641  return statisticsProperty[property];
642 }
643 
644 template <typename ImageT, typename MaskT, typename VarianceT>
645 Statistics::Statistics(ImageT const &img, MaskT const &msk, VarianceT const &var, int const flags,
646  StatisticsControl const &sctrl)
647  : _flags(flags),
648  _mean(NaN, NaN),
649  _variance(NaN, NaN),
650  _min(NaN),
651  _max(NaN),
652  _sum(NaN),
653  _meanclip(NaN, NaN),
654  _varianceclip(NaN, NaN),
655  _median(NaN, NaN),
656  _nClipped(0),
657  _nMasked(0),
658  _iqrange(NaN),
659  _sctrl(sctrl),
660  _weightsAreMultiplicative(false) {
661  doStatistics(img, msk, var, var, _flags, _sctrl);
662 }
663 
664 namespace {
665 template <typename T>
666 bool isEmpty(T const &t) {
667  return t.empty();
668 }
669 
670 template <typename T>
671 bool isEmpty(image::Image<T> const &im) {
672  return (im.getWidth() == 0 && im.getHeight() == 0);
673 }
674 
675 // Asserts that image dimensions are equal
676 template <typename ImageT1, typename ImageT2>
677 void checkDimensions(ImageT1 const &image1, ImageT2 const &image2) {
678  if (image1.getDimensions() != image2.getDimensions()) {
680  (boost::format("Image sizes don't match: %s vs %s") % image1.getDimensions() %
681  image2.getDimensions())
682  .str());
683  }
684 }
685 
686 // Overloads for MaskImposter (which doesn't have a size)
687 template <typename ImageT, typename PixelT>
688 void checkDimensions(ImageT const &image1, MaskImposter<PixelT> const &image2) {}
689 template <typename ImageT, typename PixelT>
690 void checkDimensions(MaskImposter<PixelT> const &image1, ImageT const &image2) {}
691 }
692 
693 template <typename ImageT, typename MaskT, typename VarianceT, typename WeightT>
694 Statistics::Statistics(ImageT const &img, MaskT const &msk, VarianceT const &var, WeightT const &weights,
695  int const flags, StatisticsControl const &sctrl)
696  : _flags(flags),
697  _mean(NaN, NaN),
698  _variance(NaN, NaN),
699  _min(NaN),
700  _max(NaN),
701  _sum(NaN),
702  _meanclip(NaN, NaN),
703  _varianceclip(NaN, NaN),
704  _median(NaN, NaN),
705  _nClipped(0),
706  _nMasked(0),
707  _iqrange(NaN),
708  _sctrl(sctrl),
709  _weightsAreMultiplicative(true) {
710  if (!isEmpty(weights)) {
711  if (_sctrl.getWeightedIsSet() && !_sctrl.getWeighted()) {
713  "You must use the weights if you provide them");
714  }
715 
716  _sctrl.setWeighted(true);
717  }
718  doStatistics(img, msk, var, weights, _flags, _sctrl);
719 }
720 
721 template <typename ImageT, typename MaskT, typename VarianceT, typename WeightT>
722 void Statistics::doStatistics(ImageT const &img, MaskT const &msk, VarianceT const &var,
723  WeightT const &weights, int const flags, StatisticsControl const &sctrl) {
724  int const num = img.getWidth() * img.getHeight();
725  _n = num;
726  if (_n == 0) {
727  throw LSST_EXCEPT(pexExceptions::InvalidParameterError, "Image contains no pixels");
728  }
729  checkDimensions(img, msk);
730  checkDimensions(img, var);
731  if (sctrl.getWeighted()) {
732  checkDimensions(img, weights);
733  }
734 
735  // Check that an int's large enough to hold the number of pixels
736  assert(img.getWidth() * static_cast<double>(img.getHeight()) < std::numeric_limits<int>::max());
737 
738  // get the standard statistics
739  StandardReturn standard =
740  getStandard(img, msk, var, weights, flags, _weightsAreMultiplicative, _sctrl.getAndMask(),
741  _sctrl.getCalcErrorFromInputVariance(), _sctrl.getNanSafe(), _sctrl.getWeighted(),
742  _sctrl._maskPropagationThresholds);
743 
744  _n = std::get<0>(standard);
745  _sum = std::get<1>(standard);
746  _mean = std::get<2>(standard);
747  _variance = std::get<3>(standard);
748  _min = std::get<4>(standard);
749  _max = std::get<5>(standard);
750  _allPixelOrMask = std::get<6>(standard);
751 
752  // ==========================================================
753  // now only calculate it if it's specifically requested - these all cost more!
754 
755  if (flags & NMASKED) {
756  _nMasked = num - _n;
757  }
758 
759  // copy the image for any routines that will use median or quantiles
760  if (flags & (MEDIAN | IQRANGE | MEANCLIP | STDEVCLIP | VARIANCECLIP)) {
761  // make a vector copy of the image to get the median and quartiles (will move values)
763  if (_sctrl.getNanSafe()) {
764  imgcp = makeVectorCopy<ChkFin>(img, msk, var, _sctrl.getAndMask());
765  } else {
766  imgcp = makeVectorCopy<AlwaysT>(img, msk, var, _sctrl.getAndMask());
767  }
768 
769  // if we *only* want the median, just use percentile(), otherwise use medianAndQuartiles()
770  if ((flags & (MEDIAN)) && !(flags & (IQRANGE | MEANCLIP | STDEVCLIP | VARIANCECLIP))) {
771  _median = Value(percentile(*imgcp, 0.5), NaN);
772  } else {
773  MedianQuartileReturn mq = medianAndQuartiles(*imgcp);
774  _median = Value(std::get<0>(mq), NaN);
775  _iqrange = std::get<2>(mq) - std::get<1>(mq);
776  }
777 
778  if (flags & (MEANCLIP | STDEVCLIP | VARIANCECLIP)) {
779  for (int i_i = 0; i_i < _sctrl.getNumIter(); ++i_i) {
780  double const center = ((i_i > 0) ? _meanclip : _median).first;
781  double const hwidth = (i_i > 0 && _n > 1)
782  ? _sctrl.getNumSigmaClip() * std::sqrt(_varianceclip.first)
783  : _sctrl.getNumSigmaClip() * IQ_TO_STDEV * _iqrange;
784  std::pair<double, double> const clipinfo(center, hwidth);
785 
786  StandardReturn clipped = getStandard(
787  img, msk, var, weights, flags, clipinfo, _weightsAreMultiplicative,
788  _sctrl.getAndMask(), _sctrl.getCalcErrorFromInputVariance(), _sctrl.getNanSafe(),
789  _sctrl.getWeighted(), _sctrl._maskPropagationThresholds);
790 
791  int const nClip = std::get<0>(clipped); // number after clipping
792  _nClipped = _n - nClip; // number clipped
793  _meanclip = std::get<2>(clipped); // clipped mean
794  double const varClip = std::get<3>(clipped).first; // clipped variance
795 
796  _varianceclip = Value(varClip, varianceError(varClip, nClip));
797  // ... ignore other values
798  }
799  }
800  }
801 }
802 
804  // if iProp == NOTHING try to return their heart's delight, as specified in the constructor
805  Property const prop = static_cast<Property>(((iProp == NOTHING) ? _flags : iProp) & ~ERRORS);
806 
807  if (!(prop & _flags)) { // we didn't calculate it
809  (boost::format("You didn't ask me to calculate %d") % prop).str());
810  }
811 
812  Value ret(NaN, NaN);
813  switch (prop) {
814  case NPOINT:
815  ret.first = static_cast<double>(_n);
816  if (_flags & ERRORS) {
817  ret.second = 0;
818  }
819  break;
820 
821  case NCLIPPED:
822  ret.first = static_cast<double>(_nClipped);
823  if (_flags & ERRORS) {
824  ret.second = 0;
825  }
826  break;
827 
828  case NMASKED:
829  ret.first = static_cast<double>(_nMasked);
830  if (_flags & ERRORS) {
831  ret.second = 0;
832  }
833  break;
834 
835  case SUM:
836  ret.first = static_cast<double>(_sum);
837  if (_flags & ERRORS) {
838  ret.second = 0;
839  }
840  break;
841 
842  // == means ==
843  case MEAN:
844  ret.first = _mean.first;
845  if (_flags & ERRORS) {
846  ret.second = ::sqrt(_mean.second);
847  }
848  break;
849  case MEANCLIP:
850  ret.first = _meanclip.first;
851  if (_flags & ERRORS) {
852  ret.second = ::sqrt(_meanclip.second);
853  }
854  break;
855 
856  // == stdevs & variances ==
857  case VARIANCE:
858  ret.first = _variance.first;
859  if (_flags & ERRORS) {
860  ret.second = ::sqrt(_variance.second);
861  }
862  break;
863  case STDEV:
864  ret.first = sqrt(_variance.first);
865  if (_flags & ERRORS) {
866  ret.second = 0.5 * ::sqrt(_variance.second) / ret.first;
867  }
868  break;
869  case VARIANCECLIP:
870  ret.first = _varianceclip.first;
871  if (_flags & ERRORS) {
872  ret.second = ret.second;
873  }
874  break;
875  case STDEVCLIP:
876  ret.first = sqrt(_varianceclip.first);
877  if (_flags & ERRORS) {
878  ret.second = 0.5 * ::sqrt(_varianceclip.second) / ret.first;
879  }
880  break;
881 
882  case MEANSQUARE:
883  ret.first = (_n - 1) / static_cast<double>(_n) * _variance.first + ::pow(_mean.first, 2);
884  if (_flags & ERRORS) {
885  ret.second = ::sqrt(2 * ::pow(ret.first / _n, 2)); // assumes Gaussian
886  }
887  break;
888 
889  // == other stats ==
890  case MIN:
891  ret.first = _min;
892  if (_flags & ERRORS) {
893  ret.second = 0;
894  }
895  break;
896  case MAX:
897  ret.first = _max;
898  if (_flags & ERRORS) {
899  ret.second = 0;
900  }
901  break;
902  case MEDIAN:
903  ret.first = _median.first;
904  if (_flags & ERRORS) {
905  ret.second = sqrt(geom::HALFPI * _variance.first / _n); // assumes Gaussian
906  }
907  break;
908  case IQRANGE:
909  ret.first = _iqrange;
910  if (_flags & ERRORS) {
911  ret.second = NaN; // we're not estimating this properly
912  }
913  break;
914 
915  // no-op to satisfy the compiler
916  case ERRORS:
917  break;
918  // default: redundant as 'ret' is initialized to NaN, NaN
919  default: // we must have set prop to _flags
920  assert(iProp == 0);
922  "getValue() may only be called without a parameter"
923  " if you asked for only one statistic");
924  }
925  return ret;
926 }
927 
928 double Statistics::getValue(Property const prop) const { return getResult(prop).first; }
929 
930 double Statistics::getError(Property const prop) const { return getResult(prop).second; }
931 
941 template <>
943  image::Mask<image::MaskPixel> const &var, int const flags,
944  StatisticsControl const &sctrl)
945  : _flags(flags),
946  _mean(NaN, NaN),
947  _variance(NaN, NaN),
948  _min(NaN),
949  _max(NaN),
950  _meanclip(NaN, NaN),
951  _varianceclip(NaN, NaN),
952  _median(NaN, NaN),
953  _nClipped(0),
954  _iqrange(NaN),
955  _sctrl(sctrl) {
956  if ((flags & ~(NPOINT | SUM)) != 0x0) {
958  "Statistics<Mask> only supports NPOINT and SUM");
959  }
960 
961  typedef image::Mask<image::MaskPixel> Mask;
962 
963  _n = msk.getWidth() * msk.getHeight();
964  if (_n == 0) {
965  throw LSST_EXCEPT(pexExceptions::InvalidParameterError, "Image contains no pixels");
966  }
967 
968  // Check that an int's large enough to hold the number of pixels
969  assert(msk.getWidth() * static_cast<double>(msk.getHeight()) < std::numeric_limits<int>::max());
970 
971  image::MaskPixel sum = 0x0;
972  for (int y = 0; y != msk.getHeight(); ++y) {
973  for (Mask::x_iterator ptr = msk.row_begin(y), end = msk.row_end(y); ptr != end; ++ptr) {
974  sum |= (*ptr)[0];
975  }
976  }
977  _sum = sum;
978 }
979 
980 /*
981  * Although short, the definition can't be in the header as it must
982  * follow the specialization definition
983  * (g++ complained when this was in the header.)
984  */
986  StatisticsControl const &sctrl) {
987  return Statistics(msk, msk, msk, flags, sctrl);
988 }
989 
990 /*
991  * Explicit instantiations
992  *
993  * explicit Statistics(MaskedImage const& img, int const flags,
994  * StatisticsControl const& sctrl=StatisticsControl());
995  */
997 //
998 #define STAT Statistics
999 
1000 typedef image::VariancePixel VPixel;
1001 
1002 #define INSTANTIATE_MASKEDIMAGE_STATISTICS(TYPE) \
1003  template STAT::Statistics(image::Image<TYPE> const &img, image::Mask<image::MaskPixel> const &msk, \
1004  image::Image<VPixel> const &var, int const flags, \
1005  StatisticsControl const &sctrl); \
1006  template STAT::Statistics(image::Image<TYPE> const &img, image::Mask<image::MaskPixel> const &msk, \
1007  image::Image<VPixel> const &var, image::Image<VPixel> const &weights, \
1008  int const flags, StatisticsControl const &sctrl); \
1009  template STAT::Statistics(image::Image<TYPE> const &img, image::Mask<image::MaskPixel> const &msk, \
1010  image::Image<VPixel> const &var, ImageImposter<VPixel> const &weights, \
1011  int const flags, StatisticsControl const &sctrl)
1012 
1013 #define INSTANTIATE_MASKEDIMAGE_STATISTICS_NO_MASK(TYPE) \
1014  template STAT::Statistics(image::Image<TYPE> const &img, MaskImposter<image::MaskPixel> const &msk, \
1015  image::Image<VPixel> const &var, int const flags, \
1016  StatisticsControl const &sctrl); \
1017  template STAT::Statistics(image::Image<TYPE> const &img, MaskImposter<image::MaskPixel> const &msk, \
1018  image::Image<VPixel> const &var, image::Image<VPixel> const &weights, \
1019  int const flags, StatisticsControl const &sctrl)
1020 
1021 #define INSTANTIATE_MASKEDIMAGE_STATISTICS_NO_VAR(TYPE) \
1022  template STAT::Statistics(image::Image<TYPE> const &img, image::Mask<image::MaskPixel> const &msk, \
1023  MaskImposter<VPixel> const &var, int const flags, \
1024  StatisticsControl const &sctrl); \
1025  template STAT::Statistics(image::Image<TYPE> const &img, image::Mask<image::MaskPixel> const &msk, \
1026  MaskImposter<VPixel> const &var, image::Image<VPixel> const &weights, \
1027  int const flags, StatisticsControl const &sctrl); \
1028  template STAT::Statistics(image::Image<TYPE> const &img, image::Mask<image::MaskPixel> const &msk, \
1029  MaskImposter<VPixel> const &var, ImageImposter<VPixel> const &weights, \
1030  int const flags, StatisticsControl const &sctrl)
1031 
1032 #define INSTANTIATE_REGULARIMAGE_STATISTICS(TYPE) \
1033  template STAT::Statistics(image::Image<TYPE> const &img, MaskImposter<image::MaskPixel> const &msk, \
1034  MaskImposter<VPixel> const &var, int const flags, \
1035  StatisticsControl const &sctrl)
1036 
1037 #define INSTANTIATE_VECTOR_STATISTICS(TYPE) \
1038  template STAT::Statistics(ImageImposter<TYPE> const &img, MaskImposter<image::MaskPixel> const &msk, \
1039  MaskImposter<VPixel> const &var, int const flags, \
1040  StatisticsControl const &sctrl); \
1041  template STAT::Statistics(ImageImposter<TYPE> const &img, MaskImposter<image::MaskPixel> const &msk, \
1042  MaskImposter<VPixel> const &var, ImageImposter<VPixel> const &weights, \
1043  int const flags, StatisticsControl const &sctrl)
1044 
1045 #define INSTANTIATE_IMAGE_STATISTICS(T) \
1046  INSTANTIATE_MASKEDIMAGE_STATISTICS(T); \
1047  INSTANTIATE_MASKEDIMAGE_STATISTICS_NO_VAR(T); \
1048  INSTANTIATE_MASKEDIMAGE_STATISTICS_NO_MASK(T); \
1049  INSTANTIATE_REGULARIMAGE_STATISTICS(T); \
1050  INSTANTIATE_VECTOR_STATISTICS(T)
1051 
1052 INSTANTIATE_IMAGE_STATISTICS(double);
1053 INSTANTIATE_IMAGE_STATISTICS(float);
1054 INSTANTIATE_IMAGE_STATISTICS(int);
1055 INSTANTIATE_IMAGE_STATISTICS(std::uint16_t);
1056 INSTANTIATE_IMAGE_STATISTICS(std::uint64_t);
1057 
1059 }
1060 }
1061 } // end math
Value getResult(Property const prop=NOTHING) const
Return the value and error in the specified statistic (e.g.
Definition: Statistics.cc:803
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:930
int getHeight() const
Return the number of rows in the image.
Definition: ImageBase.h:299
number of clipped points
Definition: Statistics.h:81
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:140
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:215
number of masked points
Definition: Statistics.h:82
Statistics(ImageT const &img, MaskT const &msk, VarianceT const &var, int const flags, StatisticsControl const &sctrl=StatisticsControl())
Constructor for Statistics object.
Definition: Statistics.cc:645
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:218
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:93
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:333
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:153
double getValue(Property const prop=NOTHING) const
Return the value of the desired property (if specified in the constructor)
Definition: Statistics.cc:928
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:348