lsst.afw  13.0-100-ge0459d59f+5
ImagePca.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  * Utilities to support PCA analysis of a set of images
27  */
28 #include <algorithm>
29 #include <cmath>
30 #include <cstdint>
31 #include <memory>
32 
33 #include "Eigen/Core"
34 #include "Eigen/SVD"
35 #include "Eigen/Eigenvalues"
36 
39 
40 namespace afwMath = lsst::afw::math;
41 
42 namespace lsst {
43 namespace afw {
44 namespace image {
45 
46 template <typename ImageT>
47 ImagePca<ImageT>::ImagePca(bool constantWeight)
48  : _imageList(),
49  _fluxList(),
50  _dimensions(0, 0),
51  _constantWeight(constantWeight),
52  _eigenValues(std::vector<double>()),
53  _eigenImages(ImageList()) {}
54 
55 template <typename ImageT>
56 void ImagePca<ImageT>::addImage(std::shared_ptr<ImageT> img, double flux) {
57  if (_imageList.empty()) {
58  _dimensions = img->getDimensions();
59  } else {
60  if (getDimensions() != img->getDimensions()) {
61  throw LSST_EXCEPT(lsst::pex::exceptions::LengthError,
62  (boost::format("Dimension mismatch: saw %dx%d; expected %dx%d") %
63  img->getWidth() % img->getHeight() % _dimensions.getX() % _dimensions.getY())
64  .str());
65  }
66  }
67 
68  if (flux == 0.0) {
69  throw LSST_EXCEPT(lsst::pex::exceptions::OutOfRangeError, "Flux may not be zero");
70  }
71 
72  _imageList.push_back(img);
73  _fluxList.push_back(flux);
74 }
75 
76 template <typename ImageT>
78  return _imageList;
79 }
80 
81 template <typename ImageT>
82 std::shared_ptr<ImageT> ImagePca<ImageT>::getMean() const {
83  if (_imageList.empty()) {
84  throw LSST_EXCEPT(lsst::pex::exceptions::LengthError, "You haven't provided any images");
85  }
86 
87  std::shared_ptr<ImageT> mean(new ImageT(getDimensions()));
88  *mean = static_cast<typename ImageT::Pixel>(0);
89 
90  for (typename ImageList::const_iterator ptr = _imageList.begin(), end = _imageList.end(); ptr != end;
91  ++ptr) {
92  *mean += **ptr;
93  }
94  *mean /= _imageList.size();
95 
96  return mean;
97 }
98 
99 namespace {
100 /*
101  * Analyze the images in an ImagePca, calculating the PCA decomposition (== Karhunen-Lo\`eve basis)
102  *
103  * The notation is that in chapter 7 of Gyula Szokoly's thesis at JHU
104  */
105 template <typename T>
106 struct SortEvalueDecreasing
107  : public std::binary_function<std::pair<T, int> const&, std::pair<T, int> const&, bool> {
108  bool operator()(std::pair<T, int> const& a, std::pair<T, int> const& b) {
109  return a.first > b.first; // N.b. sort on greater
110  }
111 };
112 } // namespace
113 
114 template <typename ImageT>
116  int const nImage = _imageList.size();
117 
118  if (nImage == 0) {
119  throw LSST_EXCEPT(lsst::pex::exceptions::LengthError, "No images provided for PCA analysis");
120  }
121  /*
122  * Eigen doesn't like 1x1 matrices, but we don't really need it to handle a single matrix...
123  */
124  if (nImage == 1) {
125  _eigenImages.clear();
126  _eigenImages.push_back(std::shared_ptr<ImageT>(new ImageT(*_imageList[0], true)));
127 
128  _eigenValues.clear();
129  _eigenValues.push_back(1.0);
130 
131  return;
132  }
133  /*
134  * Find the eigenvectors/values of the scalar product matrix, R' (Eq. 7.4)
135  */
136  Eigen::MatrixXd R(nImage, nImage); // residuals' inner products
137 
138  double flux_bar = 0; // mean of flux for all regions
139  for (int i = 0; i != nImage; ++i) {
140  typename GetImage<ImageT>::type const& im_i = *GetImage<ImageT>::getImage(_imageList[i]);
141  double const flux_i = getFlux(i);
142  flux_bar += flux_i;
143 
144  for (int j = i; j != nImage; ++j) {
145  typename GetImage<ImageT>::type const& im_j = *GetImage<ImageT>::getImage(_imageList[j]);
146  double const flux_j = getFlux(j);
147 
148  double dot = innerProduct(im_i, im_j);
149  if (_constantWeight) {
150  dot /= flux_i * flux_j;
151  }
152  R(i, j) = R(j, i) = dot / nImage;
153  }
154  }
155  flux_bar /= nImage;
156  Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> eVecValues(R);
157  Eigen::MatrixXd const& Q = eVecValues.eigenvectors();
158  Eigen::VectorXd const& lambda = eVecValues.eigenvalues();
159  //
160  // We need to sort the eigenValues, and remember the permutation we applied to the eigenImages
161  // We'll use the vector lambdaAndIndex to achieve this
162  //
163  std::vector<std::pair<double, int> > lambdaAndIndex; // pairs (eValue, index)
164  lambdaAndIndex.reserve(nImage);
165 
166  for (int i = 0; i != nImage; ++i) {
167  lambdaAndIndex.push_back(std::make_pair(lambda(i), i));
168  }
169  std::sort(lambdaAndIndex.begin(), lambdaAndIndex.end(), SortEvalueDecreasing<double>());
170  //
171  // Save the (sorted) eigen values
172  //
173  _eigenValues.clear();
174  _eigenValues.reserve(nImage);
175  for (int i = 0; i != nImage; ++i) {
176  _eigenValues.push_back(lambdaAndIndex[i].first);
177  }
178  //
179  // Contruct the first ncomp eigenimages in basis
180  //
181  int ncomp = 100; // number of components to keep
182 
183  _eigenImages.clear();
184  _eigenImages.reserve(ncomp < nImage ? ncomp : nImage);
185 
186  for (int i = 0; i < ncomp; ++i) {
187  if (i >= nImage) {
188  continue;
189  }
190 
191  int const ii = lambdaAndIndex[i].second; // the index after sorting (backwards) by eigenvalue
192 
193  std::shared_ptr<ImageT> eImage(new ImageT(_dimensions));
194  *eImage = static_cast<typename ImageT::Pixel>(0);
195 
196  for (int j = 0; j != nImage; ++j) {
197  int const jj = lambdaAndIndex[j].second; // the index after sorting (backwards) by eigenvalue
198  double const weight = Q(jj, ii) * (_constantWeight ? flux_bar / getFlux(jj) : 1);
199  eImage->scaledPlus(weight, *_imageList[jj]);
200  }
201  _eigenImages.push_back(eImage);
202  }
203 }
204 
205 namespace {
206 /*
207  * Fit a LinearCombinationKernel to an Image, allowing the coefficients of the components to vary
208  *
209  * return std::pair(best-fit kernel, std::pair(amp, chi^2))
210  */
211 template <typename MaskedImageT>
212 std::shared_ptr<typename MaskedImageT::Image> fitEigenImagesToImage(
213  typename ImagePca<MaskedImageT>::ImageList const& eigenImages, // Eigen images
214  int nEigen, // Number of eigen images to use
215  MaskedImageT const& image // The image to be fit
216  ) {
217  typedef typename MaskedImageT::Image ImageT;
218 
219  if (nEigen == 0) {
220  throw LSST_EXCEPT(lsst::pex::exceptions::LengthError, "You must have at least one eigen image");
221  } else if (nEigen > static_cast<int>(eigenImages.size())) {
222  throw LSST_EXCEPT(lsst::pex::exceptions::LengthError,
223  (boost::format("You only have %d eigen images (you asked for %d)") %
224  eigenImages.size() % nEigen)
225  .str());
226  }
227  /*
228  * Solve the linear problem image = sum x_i K_i + epsilon; we solve this for x_i by constructing the
229  * normal equations, A x = b
230  */
231  Eigen::MatrixXd A(nEigen, nEigen);
232  Eigen::VectorXd b(nEigen);
233 
234  for (int i = 0; i != nEigen; ++i) {
235  b(i) = innerProduct(*eigenImages[i]->getImage(), *image.getImage());
236 
237  for (int j = i; j != nEigen; ++j) {
238  A(i, j) = A(j, i) = innerProduct(*eigenImages[i]->getImage(), *eigenImages[j]->getImage());
239  }
240  }
241  Eigen::VectorXd x(nEigen);
242 
243  if (nEigen == 1) {
244  x(0) = b(0) / A(0, 0);
245  } else {
246  x = A.jacobiSvd(Eigen::ComputeThinU | Eigen::ComputeThinV).solve(b);
247  }
248  //
249  // Accumulate the best-fit-image in bestFitImage
250  //
251  std::shared_ptr<ImageT> bestFitImage = std::make_shared<ImageT>(eigenImages[0]->getDimensions());
252 
253  for (int i = 0; i != nEigen; ++i) {
254  bestFitImage->scaledPlus(x[i], *eigenImages[i]->getImage());
255  }
256 
257  return bestFitImage;
258 }
259 
260 template <typename ImageT>
261 double do_updateBadPixels(detail::basic_tag const&, typename ImagePca<ImageT>::ImageList const&,
262  std::vector<double> const&, typename ImagePca<ImageT>::ImageList const&,
263  unsigned long, int const) {
264  return 0.0;
265 }
266 
267 template <typename ImageT>
268 double do_updateBadPixels(detail::MaskedImage_tag const&,
269  typename ImagePca<ImageT>::ImageList const& imageList,
270  std::vector<double> const& fluxes, // fluxes of images
271  typename ImagePca<ImageT>::ImageList const& eigenImages, // Eigen images
272  unsigned long mask,
273  int const ncomp
274  ) {
275  int const nImage = imageList.size();
276  if (nImage == 0) {
277  throw LSST_EXCEPT(lsst::pex::exceptions::LengthError,
278  "Please provide at least one Image for me to update");
279  }
280  geom::Extent2I dimensions = imageList[0]->getDimensions();
281  int const height = dimensions.getY();
282 
283  double maxChange = 0.0; // maximum change to the input images
284 
285  if (ncomp == 0) { // use mean of good pixels
286  typename ImageT::Image mean(dimensions); // desired mean image
287  image::Image<float> weight(mean.getDimensions()); // weight of each pixel
288 
289  for (int i = 0; i != nImage; ++i) {
290  double const flux_i = fluxes[i];
291 
292  for (int y = 0; y != height; ++y) {
293  typename ImageT::const_x_iterator iptr = imageList[i]->row_begin(y);
294  image::Image<float>::x_iterator wptr = weight.row_begin(y);
295  for (typename ImageT::Image::x_iterator mptr = mean.row_begin(y), end = mean.row_end(y);
296  mptr != end; ++mptr, ++iptr, ++wptr) {
297  if (!(iptr.mask() & mask) && iptr.variance() > 0.0) {
298  typename ImageT::Image::Pixel value = iptr.image() / flux_i;
299  float const var = iptr.variance() / (flux_i * flux_i);
300  float const ivar = 1.0 / var;
301 
302  if (std::isfinite(value * ivar)) {
303  *mptr += value * ivar;
304  *wptr += ivar;
305  }
306  }
307  }
308  }
309  }
310  //
311  // Calculate mean
312  //
313  for (int y = 0; y != height; ++y) {
315  for (typename ImageT::Image::x_iterator mptr = mean.row_begin(y), end = mean.row_end(y);
316  mptr != end; ++mptr, ++wptr) {
317  if (*wptr == 0.0) { // oops, no good values
318  ;
319  } else {
320  *mptr /= *wptr;
321  }
322  }
323  }
324  //
325  // Replace bad values by mean
326  //
327  for (int i = 0; i != nImage; ++i) {
328  double const flux_i = fluxes[i];
329 
330  for (int y = 0; y != height; ++y) {
331  typename ImageT::x_iterator iptr = imageList[i]->row_begin(y);
332  for (typename ImageT::Image::x_iterator mptr = mean.row_begin(y), end = mean.row_end(y);
333  mptr != end; ++mptr, ++iptr) {
334  if ((iptr.mask() & mask)) {
335  double const delta = ::fabs(flux_i * (*mptr) - iptr.image());
336  if (delta > maxChange) {
337  maxChange = delta;
338  }
339  iptr.image() = flux_i * (*mptr);
340  }
341  }
342  }
343  }
344  } else {
345  if (ncomp > static_cast<int>(eigenImages.size())) {
346  throw LSST_EXCEPT(lsst::pex::exceptions::LengthError,
347  (boost::format("You only have %d eigen images (you asked for %d)") %
348  eigenImages.size() % ncomp)
349  .str());
350  }
351 
352  for (int i = 0; i != nImage; ++i) {
353  std::shared_ptr<typename ImageT::Image> fitted =
354  fitEigenImagesToImage(eigenImages, ncomp, *imageList[i]);
355 
356  for (int y = 0; y != height; ++y) {
357  typename ImageT::x_iterator iptr = imageList[i]->row_begin(y);
358  for (typename ImageT::Image::const_x_iterator fptr = fitted->row_begin(y),
359  end = fitted->row_end(y);
360  fptr != end; ++fptr, ++iptr) {
361  if (iptr.mask() & mask) {
362  double const delta = fabs(static_cast<double>(*fptr) - iptr.image());
363  if (delta > maxChange) {
364  maxChange = delta;
365  }
366 
367  iptr.image() = *fptr;
368  }
369  }
370  }
371  }
372  }
373 
374  return maxChange;
375 }
376 } // namespace
377 template <typename ImageT>
378 double ImagePca<ImageT>::updateBadPixels(unsigned long mask, int const ncomp) {
379  return do_updateBadPixels<ImageT>(typename ImageT::image_category(), _imageList, _fluxList, _eigenImages,
380  mask, ncomp);
381 }
382 
383 namespace {
384 template <typename T, typename U>
385 struct IsSame {
386  IsSame(T const&, U const&) {}
387  bool operator()() { return false; }
388 };
389 
390 template <typename T>
391 struct IsSame<T, T> {
392  IsSame(T const& im1, T const& im2) : _same(im1.row_begin(0) == im2.row_begin(0)) {}
393  bool operator()() { return _same; }
394 
395 private:
396  bool _same;
397 };
398 
399 // Test if two Images are identical; they need not be of the same type
400 template <typename Image1T, typename Image2T>
401 bool imagesAreIdentical(Image1T const& im1, Image2T const& im2) {
402  return IsSame<Image1T, Image2T>(im1, im2)();
403 }
404 } // namespace
405 template <typename Image1T, typename Image2T>
406 double innerProduct(Image1T const& lhs, Image2T const& rhs, int border) {
407  if (lhs.getWidth() <= 2 * border || lhs.getHeight() <= 2 * border) {
408  throw LSST_EXCEPT(lsst::pex::exceptions::LengthError,
409  (boost::format("All image pixels are in the border of width %d: %dx%d") % border %
410  lhs.getWidth() % lhs.getHeight())
411  .str());
412  }
413 
414  double sum = 0.0;
415  //
416  // Handle I.I specially for efficiency, and to avoid advancing the iterator twice
417  //
418  if (imagesAreIdentical(lhs, rhs)) {
419  for (int y = border; y != lhs.getHeight() - border; ++y) {
420  for (typename Image1T::const_x_iterator lptr = lhs.row_begin(y) + border,
421  lend = lhs.row_end(y) - border;
422  lptr != lend; ++lptr) {
423  typename Image1T::Pixel val = *lptr;
424  if (std::isfinite(val)) {
425  sum += val * val;
426  }
427  }
428  }
429  } else {
430  if (lhs.getDimensions() != rhs.getDimensions()) {
431  throw LSST_EXCEPT(lsst::pex::exceptions::LengthError,
432  (boost::format("Dimension mismatch: %dx%d v. %dx%d") % lhs.getWidth() %
433  lhs.getHeight() % rhs.getWidth() % rhs.getHeight())
434  .str());
435  }
436 
437  for (int y = border; y != lhs.getHeight() - border; ++y) {
438  typename Image2T::const_x_iterator rptr = rhs.row_begin(y) + border;
439  for (typename Image1T::const_x_iterator lptr = lhs.row_begin(y) + border,
440  lend = lhs.row_end(y) - border;
441  lptr != lend; ++lptr, ++rptr) {
442  double const tmp = (*lptr) * (*rptr);
443  if (std::isfinite(tmp)) {
444  sum += tmp;
445  }
446  }
447  }
448  }
449 
450  return sum;
451 }
452 
453 //
454 // Explicit instantiations
455 //
457 #define INSTANTIATE(T) \
458  template class ImagePca<Image<T> >; \
459  template double innerProduct(Image<T> const&, Image<T> const&, int); \
460  template class ImagePca<MaskedImage<T> >;
461 
462 #define INSTANTIATE2(T, U) \
463  template double innerProduct(Image<T> const&, Image<U> const&, int); \
464  template double innerProduct(Image<U> const&, Image<T> const&, int);
465 
466 INSTANTIATE(std::uint16_t)
467 INSTANTIATE(std::uint64_t)
468 INSTANTIATE(int)
469 INSTANTIATE(float)
470 INSTANTIATE(double)
471 
472 INSTANTIATE2(float, double) // the two types must be different
474 } // namespace image
475 } // namespace afw
476 } // namespace lsst
afw::table::Key< afw::table::Array< MaskPixelT > > mask
ImageList getImageList() const
Return the list of images being analyzed.
Definition: ImagePca.cc:77
std::shared_ptr< ImageT > getMean() const
Return the mean of the images in ImagePca&#39;s list.
Definition: ImagePca.cc:82
double innerProduct(Image1T const &lhs, Image2T const &rhs, int const border=0)
Calculate the inner product of two images.
Definition: ImagePca.cc:406
std::vector< std::shared_ptr< ImageT > > ImageList
Definition: ImagePca.h:48
_view_t::x_iterator x_iterator
An iterator for traversing the pixels in a row.
Definition: ImageBase.h:137
STL namespace.
x_iterator row_begin(int y) const
Return an x_iterator to the start of the y&#39;th row.
Definition: ImageBase.h:402
def dot(symb, c, r, frame=None, size=2, ctype=None, origin=afwImage.PARENT, args, kwargs)
Definition: ds9.py:109
afw::table::PointKey< int > dimensions
Definition: GaussianPsf.cc:44
A base class for image defects.
Definition: cameraGeom.dox:3
int end
A traits class for MaskedImage.
Definition: MaskedImage.h:53
#define INSTANTIATE(FROMSYS, TOSYS)
Definition: Detector.cc:139
double x
geom::Extent2I const getDimensions() const
Return the dimension of the images being analyzed.
Definition: ImagePca.h:71
virtual void analyze()
Definition: ImagePca.cc:115
ImagePca(bool constantWeight=true)
ctor
Definition: ImagePca.cc:47
void addImage(std::shared_ptr< ImageT > img, double flux=0.0)
Add an image to the set to be analyzed.
Definition: ImagePca.cc:56
A class to represent a 2-dimensional array of pixels.
Definition: Image.h:68
virtual double updateBadPixels(unsigned long mask, int const ncomp)
Update the bad pixels (i.e.
Definition: ImagePca.cc:378