lsst.afw  15.0-25-gacd707fca
LinearCombinationKernel.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 #include <numeric>
25 #include <sstream>
26 #include <stdexcept>
27 #include <typeinfo>
28 
29 #include "boost/format.hpp"
30 
31 #include "lsst/pex/exceptions.h"
33 #include "lsst/afw/math/Kernel.h"
35 #include "lsst/afw/geom.h"
36 
38 
39 namespace lsst {
40 namespace afw {
41 namespace math {
42 
44  : Kernel(),
45  _kernelList(),
46  _kernelImagePtrList(),
47  _kernelSumList(),
48  _kernelParams(),
49  _isDeltaFunctionBasis(false) {}
50 
52  std::vector<double> const &kernelParameters)
53  : Kernel(kernelList[0]->getWidth(), kernelList[0]->getHeight(), kernelList.size()),
54  _kernelList(),
55  _kernelImagePtrList(),
56  _kernelSumList(),
57  _kernelParams(kernelParameters),
58  _isDeltaFunctionBasis(false) {
59  if (kernelList.size() != kernelParameters.size()) {
61  os << "kernelList.size() = " << kernelList.size() << " != " << kernelParameters.size() << " = "
62  << "kernelParameters.size()";
64  }
65  checkKernelList(kernelList);
66  _setKernelList(kernelList);
67 }
68 
70  Kernel::SpatialFunction const &spatialFunction)
71  : Kernel(kernelList[0]->getWidth(), kernelList[0]->getHeight(), kernelList.size(), spatialFunction),
72  _kernelList(),
73  _kernelImagePtrList(),
74  _kernelSumList(),
75  _kernelParams(std::vector<double>(kernelList.size())),
76  _isDeltaFunctionBasis(false) {
77  checkKernelList(kernelList);
78  _setKernelList(kernelList);
79 }
80 
82  KernelList const &kernelList, std::vector<Kernel::SpatialFunctionPtr> const &spatialFunctionList)
83  : Kernel(kernelList[0]->getWidth(), kernelList[0]->getHeight(), spatialFunctionList),
84  _kernelList(),
85  _kernelImagePtrList(),
86  _kernelSumList(),
87  _kernelParams(std::vector<double>(kernelList.size())),
88  _isDeltaFunctionBasis(false) {
89  if (kernelList.size() != spatialFunctionList.size()) {
91  os << "kernelList.size() = " << kernelList.size() << " != " << spatialFunctionList.size() << " = "
92  << "spatialFunctionList.size()";
94  }
95  checkKernelList(kernelList);
96  _setKernelList(kernelList);
97 }
98 
101  if (this->isSpatiallyVarying()) {
102  retPtr.reset(new LinearCombinationKernel(this->_kernelList, this->_spatialFunctionList));
103  } else {
104  retPtr.reset(new LinearCombinationKernel(this->_kernelList, this->_kernelParams));
105  }
106  retPtr->setCtr(this->getCtr());
107  return retPtr;
108 }
109 
111  KernelList kernelList;
112  kernelList.reserve(getKernelList().size());
113  for (const std::shared_ptr<Kernel> &kIter : getKernelList()) {
114  kernelList.push_back(kIter->resized(width, height));
115  }
116 
118  if (isSpatiallyVarying()) {
119  retPtr = std::make_shared<LinearCombinationKernel>(kernelList, _spatialFunctionList);
120  } else {
121  retPtr = std::make_shared<LinearCombinationKernel>(kernelList, _kernelParams);
122  }
123 
124  return retPtr;
125 }
126 
128  if (kernelList.size() < 1) {
129  throw LSST_EXCEPT(pexExcept::InvalidParameterError, "kernelList has no elements");
130  }
131 
132  geom::Extent2I const dim0 = kernelList[0]->getDimensions();
133  geom::Point2I const ctr0 = kernelList[0]->getCtr();
134 
135  for (unsigned int ii = 0; ii < kernelList.size(); ++ii) {
136  if (kernelList[ii]->getDimensions() != dim0) {
138  (boost::format("kernel %d has different size than kernel 0") % ii).str());
139  }
140  if (kernelList[ii]->getCtr() != ctr0) {
142  (boost::format("kernel %d has different center than kernel 0") % ii).str());
143  }
144  if (kernelList[ii]->isSpatiallyVarying()) {
146  (boost::format("kernel %d is spatially varying") % ii).str());
147  }
148  }
149 }
150 
151 KernelList const &LinearCombinationKernel::getKernelList() const { return _kernelList; }
152 
154 
156 
158  if (!this->isSpatiallyVarying()) {
159  return std::shared_ptr<Kernel>();
160  }
161  Kernel::SpatialFunctionPtr const firstSpFuncPtr = this->_spatialFunctionList[0];
162  if (!firstSpFuncPtr->isLinearCombination()) {
163  return std::shared_ptr<Kernel>();
164  }
165 
166  typedef image::Image<Kernel::Pixel> KernelImage;
167  typedef std::shared_ptr<KernelImage> KernelImagePtr;
168  typedef std::vector<KernelImagePtr> KernelImageList;
169 
170  // create kernel images for new refactored basis kernels
171  int const nSpatialParameters = this->getNSpatialParameters();
172  KernelImageList newKernelImagePtrList;
173  newKernelImagePtrList.reserve(nSpatialParameters);
174  for (int i = 0; i < nSpatialParameters; ++i) {
175  KernelImagePtr kernelImagePtr(new KernelImage(this->getDimensions()));
176  newKernelImagePtrList.push_back(kernelImagePtr);
177  }
178  KernelImage kernelImage(this->getDimensions());
180  this->_spatialFunctionList.begin();
181  KernelList::const_iterator kIter = _kernelList.begin();
182  KernelList::const_iterator const kEnd = _kernelList.end();
183  auto & firstSpFunc = *firstSpFuncPtr;
184  auto & firstType = typeid(firstSpFunc); // noncopyable object of static storage duration
185  for (; kIter != kEnd; ++kIter, ++spFuncPtrIter) {
186  auto & spFunc = **spFuncPtrIter;
187  if (typeid(spFunc) != firstType) {
188  return std::shared_ptr<Kernel>();
189  }
190 
191  (**kIter).computeImage(kernelImage, false);
192  for (int i = 0; i < nSpatialParameters; ++i) {
193  double spParam = (*spFuncPtrIter)->getParameter(i);
194  newKernelImagePtrList[i]->scaledPlus(spParam, kernelImage);
195  }
196  }
197 
198  // create new kernel; the basis kernels are fixed kernels computed above
199  // and the corresponding spatial model is the same function as the original kernel,
200  // but with all coefficients zero except coeff_i = 1.0
201  KernelList newKernelList;
202  newKernelList.reserve(nSpatialParameters);
203  KernelImageList::iterator newKImPtrIter = newKernelImagePtrList.begin();
204  KernelImageList::iterator const newKImPtrEnd = newKernelImagePtrList.end();
205  for (; newKImPtrIter != newKImPtrEnd; ++newKImPtrIter) {
206  newKernelList.push_back(std::shared_ptr<Kernel>(new FixedKernel(**newKImPtrIter)));
207  }
208  std::vector<SpatialFunctionPtr> newSpFunctionPtrList;
209  for (int i = 0; i < nSpatialParameters; ++i) {
210  std::vector<double> newSpParameters(nSpatialParameters, 0.0);
211  newSpParameters[i] = 1.0;
212  SpatialFunctionPtr newSpFunctionPtr = firstSpFuncPtr->clone();
213  newSpFunctionPtr->setParameters(newSpParameters);
214  newSpFunctionPtrList.push_back(newSpFunctionPtr);
215  }
217  new LinearCombinationKernel(newKernelList, newSpFunctionPtrList));
218  refactoredKernel->setCtr(this->getCtr());
219  return refactoredKernel;
220 }
221 
224  os << prefix << "LinearCombinationKernel:" << std::endl;
225  os << prefix << "..Kernels:" << std::endl;
226  for (KernelList::const_iterator i = _kernelList.begin(); i != _kernelList.end(); ++i) {
227  os << (*i)->toString(prefix + "\t");
228  }
229  os << "..parameters: [ ";
230  for (std::vector<double>::const_iterator i = _kernelParams.begin(); i != _kernelParams.end(); ++i) {
231  if (i != _kernelParams.begin()) os << ", ";
232  os << *i;
233  }
234  os << " ]" << std::endl;
235  os << Kernel::toString(prefix + "\t");
236  return os.str();
237 }
238 
239 //
240 // Protected Member Functions
241 //
243  image = 0.0;
244  double imSum = 0.0;
245  std::vector<std::shared_ptr<image::Image<Pixel>>>::const_iterator kImPtrIter =
246  _kernelImagePtrList.begin();
247  std::vector<double>::const_iterator kSumIter = _kernelSumList.begin();
248  std::vector<double>::const_iterator kParIter = _kernelParams.begin();
249  for (; kImPtrIter != _kernelImagePtrList.end(); ++kImPtrIter, ++kSumIter, ++kParIter) {
250  image.scaledPlus(*kParIter, **kImPtrIter);
251  imSum += (*kSumIter) * (*kParIter);
252  }
253 
254  if (doNormalize) {
255  if (imSum == 0) {
256  throw LSST_EXCEPT(pexExcept::OverflowError, "Cannot normalize; kernel sum is 0");
257  }
258  image /= imSum;
259  imSum = 1;
260  }
261 
262  return imSum;
263 }
264 
265 void LinearCombinationKernel::setKernelParameter(unsigned int ind, double value) const {
266  this->_kernelParams[ind] = value;
267 }
268 
269 //
270 // Private Member Functions
271 //
272 void LinearCombinationKernel::_setKernelList(KernelList const &kernelList) {
273  _kernelSumList.clear();
274  _kernelImagePtrList.clear();
275  _kernelList.clear();
276  _isDeltaFunctionBasis = true;
277  for (KernelList::const_iterator kIter = kernelList.begin(), kEnd = kernelList.end(); kIter != kEnd;
278  ++kIter) {
279  std::shared_ptr<Kernel> basisKernelPtr = (*kIter)->clone();
280  if (dynamic_cast<DeltaFunctionKernel const *>(&(*basisKernelPtr)) == 0) {
281  _isDeltaFunctionBasis = false;
282  }
283  _kernelList.push_back(basisKernelPtr);
285  _kernelSumList.push_back(basisKernelPtr->computeImage(*kernelImagePtr, false));
286  _kernelImagePtrList.push_back(kernelImagePtr);
287  }
288 }
289 
290 // ------ Persistence ---------------------------------------------------------------------------------------
291 
292 namespace {
293 
294 struct LinearCombinationKernelPersistenceHelper : public Kernel::PersistenceHelper {
295  table::Key<table::Array<double>> amplitudes;
296  table::Key<table::Array<int>> components;
297 
298  LinearCombinationKernelPersistenceHelper(int nComponents, bool isSpatiallyVarying)
299  : Kernel::PersistenceHelper(isSpatiallyVarying ? nComponents : 0),
300  components(schema.addField<table::Array<int>>("components", "archive IDs of component kernel",
301  nComponents)) {
302  if (!isSpatiallyVarying) {
303  amplitudes = schema.addField<table::Array<double>>("amplitudes", "amplitudes component kernel",
304  nComponents);
305  }
306  }
307 
308  LinearCombinationKernelPersistenceHelper(table::Schema const &schema_)
309  : Kernel::PersistenceHelper(schema_), components(schema["components"]) {
310  if (!spatialFunctions.isValid()) {
311  amplitudes = schema["amplitudes"];
312  LSST_ARCHIVE_ASSERT(amplitudes.getSize() == components.getSize());
313  } else {
314  LSST_ARCHIVE_ASSERT(spatialFunctions.getSize() == components.getSize());
315  }
316  }
317 };
318 
319 } // anonymous
320 
322 public:
324  CatalogVector const &catalogs) const {
325  LSST_ARCHIVE_ASSERT(catalogs.size() == 1u);
326  LSST_ARCHIVE_ASSERT(catalogs.front().size() == 1u);
327  LinearCombinationKernelPersistenceHelper const keys(catalogs.front().getSchema());
328  afw::table::BaseRecord const &record = catalogs.front().front();
329  geom::Extent2I dimensions(record.get(keys.dimensions));
330  std::vector<std::shared_ptr<Kernel>> componentList(keys.components.getSize());
331  for (std::size_t i = 0; i < componentList.size(); ++i) {
332  componentList[i] = archive.get<Kernel>(record[keys.components[i]]);
333  }
335  if (keys.spatialFunctions.isValid()) {
336  std::vector<SpatialFunctionPtr> spatialFunctionList = keys.readSpatialFunctions(archive, record);
337  result.reset(new LinearCombinationKernel(componentList, spatialFunctionList));
338  } else {
339  std::vector<double> kernelParameters(keys.amplitudes.getSize());
340  for (std::size_t i = 0; i < kernelParameters.size(); ++i) {
341  kernelParameters[i] = record[keys.amplitudes[i]];
342  }
343  result.reset(new LinearCombinationKernel(componentList, kernelParameters));
344  }
345  LSST_ARCHIVE_ASSERT(result->getDimensions() == dimensions);
346  result->setCtr(record.get(keys.center));
347  return result;
348  }
349 
350  explicit Factory(std::string const &name) : afw::table::io::PersistableFactory(name) {}
351 };
352 
353 namespace {
354 
355 std::string getLinearCombinationKernelPersistenceName() { return "LinearCombinationKernel"; }
356 
357 LinearCombinationKernel::Factory registration(getLinearCombinationKernelPersistenceName());
358 
359 } // anonymous
360 
362  return getLinearCombinationKernelPersistenceName();
363 }
364 
366  bool isVarying = isSpatiallyVarying();
367  LinearCombinationKernelPersistenceHelper const keys(getNBasisKernels(), isVarying);
368  std::shared_ptr<afw::table::BaseRecord> record = keys.write(handle, *this);
369  if (isVarying) {
370  for (int n = 0; n < keys.components.getSize(); ++n) {
371  record->set(keys.components[n], handle.put(_kernelList[n]));
372  record->set(keys.spatialFunctions[n], handle.put(_spatialFunctionList[n]));
373  }
374  } else {
375  for (int n = 0; n < keys.components.getSize(); ++n) {
376  record->set(keys.components[n], handle.put(_kernelList[n]));
377  record->set(keys.amplitudes[n], _kernelParams[n]);
378  }
379  }
380 }
381 }
382 }
383 } // namespace math
table::Key< table::Array< int > > components
int getHeight() const
Return the Kernel&#39;s height.
Definition: Kernel.h:245
def keys(self)
int put(Persistable const *obj, bool permissive=false)
Save an object to the archive and return a unique ID that can be used to retrieve it from an InputArc...
void checkKernelList(const KernelList &kernelList) const
Check that all kernels have the same size and center and that none are spatially varying.
An object passed to Persistable::write to allow it to persist itself.
T front(T... args)
afw::table::Schema schema
Definition: GaussianPsf.cc:43
#define LSST_ARCHIVE_ASSERT(EXPR)
An assertion macro used to validate the structure of an InputArchive.
Definition: Persistable.h:48
A base class for factory classes used to reconstruct objects from records.
Definition: Persistable.h:217
virtual double doComputeImage(lsst::afw::image::Image< Pixel > &image, bool doNormalize) const
Low-level version of computeImage.
T endl(T... args)
virtual void setKernelParameter(unsigned int ind, double value) const
Set one kernel parameter.
lsst::afw::geom::Point2I getCtr() const
Return index of kernel&#39;s center.
Definition: Kernel.h:250
STL namespace.
T end(T... args)
table::Key< table::Array< double > > amplitudes
A Function taking two arguments.
Definition: Function.h:277
LinearCombinationKernel()
Construct an empty LinearCombinationKernel of size 0x0.
int getNBasisKernels() const
Get the number of basis kernels.
Definition: Kernel.h:843
virtual void write(OutputArchiveHandle &handle) const
Write the object to one or more catalogs.
STL class.
T push_back(T... args)
afw::table::PointKey< int > dimensions
Definition: GaussianPsf.cc:44
bool isSpatiallyVarying() const
Return true iff the kernel is spatially varying (has a spatial function)
Definition: Kernel.h:384
A base class for image defects.
virtual std::vector< double > getKernelParameters() const
Return the current kernel parameters.
T str(T... args)
T reset(T... args)
virtual std::shared_ptr< afw::table::io::Persistable > read(InputArchive const &archive, CatalogVector const &catalogs) const
Construct a new object from the given InputArchive and vector of catalogs.
void scaledPlus(double const c, Image< PixelT > const &rhs)
Add Image c*rhs to lhs.
Definition: Image.cc:502
T clear(T... args)
std::unique_ptr< SchemaItem< U > > result
Definition: Schema.cc:194
int getWidth() const
Return the Kernel&#39;s width.
Definition: Kernel.h:240
T size(T... args)
#define LSST_EXCEPT(type,...)
A vector of catalogs used by Persistable.
Definition: CatalogVector.h:29
std::vector< double > getKernelSumList() const
Get the sum of the pixels of each fixed basis kernel.
Base class for all records.
Definition: BaseRecord.h:31
T begin(T... args)
std::vector< SpatialFunctionPtr > _spatialFunctionList
Definition: Kernel.h:500
Kernel()
Construct a null Kernel of size 0,0.
Definition: Kernel.cc:53
int getNSpatialParameters() const
Return the number of spatial parameters (0 if not spatially varying)
Definition: Kernel.h:282
std::string prefix
Definition: SchemaMapper.cc:79
virtual KernelList const & getKernelList() const
Get the fixed basis kernels.
virtual std::shared_ptr< Kernel > clone() const
Return a pointer to a deep copy of this kernel.
A multi-catalog archive object used to load table::io::Persistable objects.
Definition: InputArchive.h:31
virtual std::shared_ptr< Kernel > resized(int width, int height) const
Return a pointer to a clone with specified kernel dimensions.
std::ostream * os
Definition: Schema.cc:736
std::shared_ptr< Kernel > refactor() const
Refactor the kernel as a linear combination of N bases where N is the number of parameters for the sp...
Kernels are used for convolution with MaskedImages and (eventually) Images.
Definition: Kernel.h:123
geom::Extent2I const getDimensions() const
Return the Kernel&#39;s dimensions (width, height)
Definition: Kernel.h:228
virtual std::string getPersistenceName() const
Return the unique name used to persist this object and look up its factory.
A class to represent a 2-dimensional array of pixels.
Definition: Image.h:69
virtual std::string toString(std::string const &prefix="") const
Return a string representation of the kernel.
Definition: Kernel.cc:197
A kernel created from an Image.
Definition: Kernel.h:524
std::shared_ptr< Persistable > get(int id) const
Load the Persistable with the given ID and return it.
T reserve(T... args)
virtual std::string toString(std::string const &prefix="") const
Return a string representation of the kernel.