lsst.afw  13.0-39-g3deb52d
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Groups Pages
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 
37 namespace pexExcept = lsst::pex::exceptions;
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()) {
60  std::ostringstream os;
61  os << "kernelList.size() = " << kernelList.size() << " != " << kernelParameters.size() << " = "
62  << "kernelParameters.size()";
63  throw LSST_EXCEPT(pexExcept::InvalidParameterError, os.str());
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()) {
90  std::ostringstream os;
91  os << "kernelList.size() = " << kernelList.size() << " != " << spatialFunctionList.size() << " = "
92  << "spatialFunctionList.size()";
93  throw LSST_EXCEPT(pexExcept::InvalidParameterError, os.str());
94  }
95  checkKernelList(kernelList);
96  _setKernelList(kernelList);
97 }
98 
99 std::shared_ptr<Kernel> LinearCombinationKernel::clone() const {
100  std::shared_ptr<Kernel> retPtr;
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  if (kernelList.size() < 1) {
112  throw LSST_EXCEPT(pexExcept::InvalidParameterError, "kernelList has no elements");
113  }
114 
115  geom::Extent2I const dim0 = kernelList[0]->getDimensions();
116  geom::Point2I const ctr0 = kernelList[0]->getCtr();
117 
118  for (unsigned int ii = 0; ii < kernelList.size(); ++ii) {
119  if (kernelList[ii]->getDimensions() != dim0) {
120  throw LSST_EXCEPT(pexExcept::InvalidParameterError,
121  (boost::format("kernel %d has different size than kernel 0") % ii).str());
122  }
123  if (kernelList[ii]->getCtr() != ctr0) {
124  throw LSST_EXCEPT(pexExcept::InvalidParameterError,
125  (boost::format("kernel %d has different center than kernel 0") % ii).str());
126  }
127  if (kernelList[ii]->isSpatiallyVarying()) {
128  throw LSST_EXCEPT(pexExcept::InvalidParameterError,
129  (boost::format("kernel %d is spatially varying") % ii).str());
130  }
131  }
132 }
133 
134 KernelList const &LinearCombinationKernel::getKernelList() const { return _kernelList; }
135 
136 std::vector<double> LinearCombinationKernel::getKernelSumList() const { return _kernelSumList; }
137 
138 std::vector<double> LinearCombinationKernel::getKernelParameters() const { return _kernelParams; }
139 
140 std::shared_ptr<Kernel> LinearCombinationKernel::refactor() const {
141  if (!this->isSpatiallyVarying()) {
142  return std::shared_ptr<Kernel>();
143  }
144  Kernel::SpatialFunctionPtr const firstSpFuncPtr = this->_spatialFunctionList[0];
145  if (!firstSpFuncPtr->isLinearCombination()) {
146  return std::shared_ptr<Kernel>();
147  }
148 
149  typedef image::Image<Kernel::Pixel> KernelImage;
150  typedef std::shared_ptr<KernelImage> KernelImagePtr;
151  typedef std::vector<KernelImagePtr> KernelImageList;
152 
153  // create kernel images for new refactored basis kernels
154  int const nSpatialParameters = this->getNSpatialParameters();
155  KernelImageList newKernelImagePtrList;
156  newKernelImagePtrList.reserve(nSpatialParameters);
157  for (int i = 0; i < nSpatialParameters; ++i) {
158  KernelImagePtr kernelImagePtr(new KernelImage(this->getDimensions()));
159  newKernelImagePtrList.push_back(kernelImagePtr);
160  }
161  KernelImage kernelImage(this->getDimensions());
162  std::vector<Kernel::SpatialFunctionPtr>::const_iterator spFuncPtrIter =
163  this->_spatialFunctionList.begin();
164  KernelList::const_iterator kIter = _kernelList.begin();
165  KernelList::const_iterator const kEnd = _kernelList.end();
166  for (; kIter != kEnd; ++kIter, ++spFuncPtrIter) {
167  if (typeid(**spFuncPtrIter) != typeid(*firstSpFuncPtr)) {
168  return std::shared_ptr<Kernel>();
169  }
170 
171  (**kIter).computeImage(kernelImage, false);
172  for (int i = 0; i < nSpatialParameters; ++i) {
173  double spParam = (*spFuncPtrIter)->getParameter(i);
174  newKernelImagePtrList[i]->scaledPlus(spParam, kernelImage);
175  }
176  }
177 
178  // create new kernel; the basis kernels are fixed kernels computed above
179  // and the corresponding spatial model is the same function as the original kernel,
180  // but with all coefficients zero except coeff_i = 1.0
181  KernelList newKernelList;
182  newKernelList.reserve(nSpatialParameters);
183  KernelImageList::iterator newKImPtrIter = newKernelImagePtrList.begin();
184  KernelImageList::iterator const newKImPtrEnd = newKernelImagePtrList.end();
185  for (; newKImPtrIter != newKImPtrEnd; ++newKImPtrIter) {
186  newKernelList.push_back(std::shared_ptr<Kernel>(new FixedKernel(**newKImPtrIter)));
187  }
188  std::vector<SpatialFunctionPtr> newSpFunctionPtrList;
189  for (int i = 0; i < nSpatialParameters; ++i) {
190  std::vector<double> newSpParameters(nSpatialParameters, 0.0);
191  newSpParameters[i] = 1.0;
192  SpatialFunctionPtr newSpFunctionPtr = firstSpFuncPtr->clone();
193  newSpFunctionPtr->setParameters(newSpParameters);
194  newSpFunctionPtrList.push_back(newSpFunctionPtr);
195  }
196  std::shared_ptr<LinearCombinationKernel> refactoredKernel(
197  new LinearCombinationKernel(newKernelList, newSpFunctionPtrList));
198  refactoredKernel->setCtr(this->getCtr());
199  return refactoredKernel;
200 }
201 
202 std::string LinearCombinationKernel::toString(std::string const &prefix) const {
203  std::ostringstream os;
204  os << prefix << "LinearCombinationKernel:" << std::endl;
205  os << prefix << "..Kernels:" << std::endl;
206  for (KernelList::const_iterator i = _kernelList.begin(); i != _kernelList.end(); ++i) {
207  os << (*i)->toString(prefix + "\t");
208  }
209  os << "..parameters: [ ";
210  for (std::vector<double>::const_iterator i = _kernelParams.begin(); i != _kernelParams.end(); ++i) {
211  if (i != _kernelParams.begin()) os << ", ";
212  os << *i;
213  }
214  os << " ]" << std::endl;
215  os << Kernel::toString(prefix + "\t");
216  return os.str();
217 }
218 
219 //
220 // Protected Member Functions
221 //
223  image = 0.0;
224  double imSum = 0.0;
225  std::vector<std::shared_ptr<image::Image<Pixel>>>::const_iterator kImPtrIter =
226  _kernelImagePtrList.begin();
227  std::vector<double>::const_iterator kSumIter = _kernelSumList.begin();
228  std::vector<double>::const_iterator kParIter = _kernelParams.begin();
229  for (; kImPtrIter != _kernelImagePtrList.end(); ++kImPtrIter, ++kSumIter, ++kParIter) {
230  image.scaledPlus(*kParIter, **kImPtrIter);
231  imSum += (*kSumIter) * (*kParIter);
232  }
233 
234  if (doNormalize) {
235  if (imSum == 0) {
236  throw LSST_EXCEPT(pexExcept::OverflowError, "Cannot normalize; kernel sum is 0");
237  }
238  image /= imSum;
239  imSum = 1;
240  }
241 
242  return imSum;
243 }
244 
245 void LinearCombinationKernel::setKernelParameter(unsigned int ind, double value) const {
246  this->_kernelParams[ind] = value;
247 }
248 
249 //
250 // Private Member Functions
251 //
252 void LinearCombinationKernel::_setKernelList(KernelList const &kernelList) {
253  _kernelSumList.clear();
254  _kernelImagePtrList.clear();
255  _kernelList.clear();
256  _isDeltaFunctionBasis = true;
257  for (KernelList::const_iterator kIter = kernelList.begin(), kEnd = kernelList.end(); kIter != kEnd;
258  ++kIter) {
259  std::shared_ptr<Kernel> basisKernelPtr = (*kIter)->clone();
260  if (dynamic_cast<DeltaFunctionKernel const *>(&(*basisKernelPtr)) == 0) {
261  _isDeltaFunctionBasis = false;
262  }
263  _kernelList.push_back(basisKernelPtr);
264  std::shared_ptr<image::Image<Pixel>> kernelImagePtr(new image::Image<Pixel>(this->getDimensions()));
265  _kernelSumList.push_back(basisKernelPtr->computeImage(*kernelImagePtr, false));
266  _kernelImagePtrList.push_back(kernelImagePtr);
267  }
268 }
269 
270 // ------ Persistence ---------------------------------------------------------------------------------------
271 
272 namespace {
273 
274 struct LinearCombinationKernelPersistenceHelper : public Kernel::PersistenceHelper {
275  table::Key<table::Array<double>> amplitudes;
276  table::Key<table::Array<int>> components;
277 
278  LinearCombinationKernelPersistenceHelper(int nComponents, bool isSpatiallyVarying)
279  : Kernel::PersistenceHelper(isSpatiallyVarying ? nComponents : 0),
280  components(schema.addField<table::Array<int>>("components", "archive IDs of component kernel",
281  nComponents)) {
282  if (!isSpatiallyVarying) {
283  amplitudes = schema.addField<table::Array<double>>("amplitudes", "amplitudes component kernel",
284  nComponents);
285  }
286  }
287 
288  LinearCombinationKernelPersistenceHelper(table::Schema const &schema_)
289  : Kernel::PersistenceHelper(schema_), components(schema["components"]) {
290  if (!spatialFunctions.isValid()) {
291  amplitudes = schema["amplitudes"];
292  LSST_ARCHIVE_ASSERT(amplitudes.getSize() == components.getSize());
293  } else {
294  LSST_ARCHIVE_ASSERT(spatialFunctions.getSize() == components.getSize());
295  }
296  }
297 };
298 
299 } // anonymous
300 
302 public:
303  virtual std::shared_ptr<afw::table::io::Persistable> read(InputArchive const &archive,
304  CatalogVector const &catalogs) const {
305  LSST_ARCHIVE_ASSERT(catalogs.size() == 1u);
306  LSST_ARCHIVE_ASSERT(catalogs.front().size() == 1u);
307  LinearCombinationKernelPersistenceHelper const keys(catalogs.front().getSchema());
308  afw::table::BaseRecord const &record = catalogs.front().front();
309  geom::Extent2I dimensions(record.get(keys.dimensions));
310  std::vector<std::shared_ptr<Kernel>> componentList(keys.components.getSize());
311  for (std::size_t i = 0; i < componentList.size(); ++i) {
312  componentList[i] = archive.get<Kernel>(record[keys.components[i]]);
313  }
314  std::shared_ptr<LinearCombinationKernel> result;
315  if (keys.spatialFunctions.isValid()) {
316  std::vector<SpatialFunctionPtr> spatialFunctionList = keys.readSpatialFunctions(archive, record);
317  result.reset(new LinearCombinationKernel(componentList, spatialFunctionList));
318  } else {
319  std::vector<double> kernelParameters(keys.amplitudes.getSize());
320  for (std::size_t i = 0; i < kernelParameters.size(); ++i) {
321  kernelParameters[i] = record[keys.amplitudes[i]];
322  }
323  result.reset(new LinearCombinationKernel(componentList, kernelParameters));
324  }
325  LSST_ARCHIVE_ASSERT(result->getDimensions() == dimensions);
326  result->setCtr(record.get(keys.center));
327  return result;
328  }
329 
330  explicit Factory(std::string const &name) : afw::table::io::PersistableFactory(name) {}
331 };
332 
333 namespace {
334 
335 std::string getLinearCombinationKernelPersistenceName() { return "LinearCombinationKernel"; }
336 
337 LinearCombinationKernel::Factory registration(getLinearCombinationKernelPersistenceName());
338 
339 } // anonymous
340 
342  return getLinearCombinationKernelPersistenceName();
343 }
344 
346  bool isVarying = isSpatiallyVarying();
347  LinearCombinationKernelPersistenceHelper const keys(getNBasisKernels(), isVarying);
348  std::shared_ptr<afw::table::BaseRecord> record = keys.write(handle, *this);
349  if (isVarying) {
350  for (int n = 0; n < keys.components.getSize(); ++n) {
351  record->set(keys.components[n], handle.put(_kernelList[n]));
352  record->set(keys.spatialFunctions[n], handle.put(_spatialFunctionList[n]));
353  }
354  } else {
355  for (int n = 0; n < keys.components.getSize(); ++n) {
356  record->set(keys.components[n], handle.put(_kernelList[n]));
357  record->set(keys.amplitudes[n], _kernelParams[n]);
358  }
359  }
360 }
361 }
362 }
363 } // namespace math
std::vector< double > getKernelSumList() const
Get the sum of the pixels of each fixed basis kernel.
table::Key< table::Array< int > > components
std::shared_ptr< Persistable > get(int id) const
Load the Persistable with the given ID and return it.
afw::table::PointKey< int > dimensions
Definition: GaussianPsf.cc:44
geom::Extent2I const getDimensions() const
Return the Kernel&#39;s dimensions (width, height)
Definition: Kernel.h:210
virtual std::shared_ptr< Kernel > clone() const
Return a pointer to a deep copy of this kernel.
PersistableFactory(std::string const &name)
Constructor for the factory.
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.
int put(Persistable const *obj, bool permissive=false)
Save a nested Persistable to the same archive.
An object passed to Persistable::write to allow it to persist itself.
#define LSST_ARCHIVE_ASSERT(EXPR)
An assertion macro used to validate the structure of an InputArchive.
Definition: Persistable.h:47
A base class for factory classes used to reconstruct objects from records.
Definition: Persistable.h:214
virtual std::string toString(std::string const &prefix="") const
Return a string representation of the kernel.
Definition: Kernel.cc:197
int getNSpatialParameters() const
Return the number of spatial parameters (0 if not spatially varying)
Definition: Kernel.h:264
std::shared_ptr< lsst::afw::math::Function2< double > > SpatialFunctionPtr
Definition: Kernel.h:129
table::Key< table::Array< double > > amplitudes
A Function taking two arguments.
Definition: Function.h:266
LinearCombinationKernel()
Construct an empty LinearCombinationKernel of size 0x0.
void checkKernelList(const KernelList &kernelList) const
Check that all kernels have the same size and center and that none are spatially varying.
virtual std::vector< double > getKernelParameters() const
Return the current kernel parameters.
virtual std::string toString(std::string const &prefix="") const
Return a string representation of the kernel.
int getNBasisKernels() const
Get the number of basis kernels.
Definition: Kernel.h:800
virtual void setKernelParameter(unsigned int ind, double value) const
Set one kernel parameter.
table::Key< std::string > name
Definition: ApCorrMap.cc:71
void scaledPlus(double const c, Image< PixelT > const &rhs)
Add Image c*rhs to lhs.
Definition: Image.cc:475
lsst::afw::geom::Point2I getCtr() const
Return index of kernel&#39;s center.
Definition: Kernel.h:232
virtual KernelList const & getKernelList() const
Get the fixed basis kernels.
A vector of catalogs used by Persistable.
Definition: CatalogVector.h:29
Base class for all records.
Definition: BaseRecord.h:29
std::vector< std::shared_ptr< Kernel > > KernelList
Definition: Kernel.h:500
std::vector< SpatialFunctionPtr > _spatialFunctionList
Definition: Kernel.h:482
afw::table::Key< afw::table::Array< ImagePixelT > > image
virtual double doComputeImage(lsst::afw::image::Image< Pixel > &image, bool doNormalize) const
Low-level version of computeImage.
virtual std::string getPersistenceName() const
Return the unique name used to persist this object and look up its factory.
A multi-catalog archive object used to load table::io::Persistable objects.
Definition: InputArchive.h:31
py::object result
Definition: schema.cc:290
Kernels are used for convolution with MaskedImages and (eventually) Images.
Definition: Kernel.h:123
A class to represent a 2-dimensional array of pixels.
Definition: Image.h:486
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...
afw::table::Schema schema
Definition: GaussianPsf.cc:43
virtual void write(OutputArchiveHandle &handle) const
Write the object to one or more catalogs.
A kernel created from an Image.
Definition: Kernel.h:509
bool isSpatiallyVarying() const
Return true iff the kernel is spatially varying (has a spatial function)
Definition: Kernel.h:366