lsst.afw  13.0-73-gb2a4e38
 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  auto & firstSpFunc = *firstSpFuncPtr;
167  auto & firstType = typeid(firstSpFunc); // noncopyable object of static storage duration
168  for (; kIter != kEnd; ++kIter, ++spFuncPtrIter) {
169  auto & spFunc = **spFuncPtrIter;
170  if (typeid(spFunc) != firstType) {
171  return std::shared_ptr<Kernel>();
172  }
173 
174  (**kIter).computeImage(kernelImage, false);
175  for (int i = 0; i < nSpatialParameters; ++i) {
176  double spParam = (*spFuncPtrIter)->getParameter(i);
177  newKernelImagePtrList[i]->scaledPlus(spParam, kernelImage);
178  }
179  }
180 
181  // create new kernel; the basis kernels are fixed kernels computed above
182  // and the corresponding spatial model is the same function as the original kernel,
183  // but with all coefficients zero except coeff_i = 1.0
184  KernelList newKernelList;
185  newKernelList.reserve(nSpatialParameters);
186  KernelImageList::iterator newKImPtrIter = newKernelImagePtrList.begin();
187  KernelImageList::iterator const newKImPtrEnd = newKernelImagePtrList.end();
188  for (; newKImPtrIter != newKImPtrEnd; ++newKImPtrIter) {
189  newKernelList.push_back(std::shared_ptr<Kernel>(new FixedKernel(**newKImPtrIter)));
190  }
191  std::vector<SpatialFunctionPtr> newSpFunctionPtrList;
192  for (int i = 0; i < nSpatialParameters; ++i) {
193  std::vector<double> newSpParameters(nSpatialParameters, 0.0);
194  newSpParameters[i] = 1.0;
195  SpatialFunctionPtr newSpFunctionPtr = firstSpFuncPtr->clone();
196  newSpFunctionPtr->setParameters(newSpParameters);
197  newSpFunctionPtrList.push_back(newSpFunctionPtr);
198  }
199  std::shared_ptr<LinearCombinationKernel> refactoredKernel(
200  new LinearCombinationKernel(newKernelList, newSpFunctionPtrList));
201  refactoredKernel->setCtr(this->getCtr());
202  return refactoredKernel;
203 }
204 
205 std::string LinearCombinationKernel::toString(std::string const &prefix) const {
206  std::ostringstream os;
207  os << prefix << "LinearCombinationKernel:" << std::endl;
208  os << prefix << "..Kernels:" << std::endl;
209  for (KernelList::const_iterator i = _kernelList.begin(); i != _kernelList.end(); ++i) {
210  os << (*i)->toString(prefix + "\t");
211  }
212  os << "..parameters: [ ";
213  for (std::vector<double>::const_iterator i = _kernelParams.begin(); i != _kernelParams.end(); ++i) {
214  if (i != _kernelParams.begin()) os << ", ";
215  os << *i;
216  }
217  os << " ]" << std::endl;
218  os << Kernel::toString(prefix + "\t");
219  return os.str();
220 }
221 
222 //
223 // Protected Member Functions
224 //
226  image = 0.0;
227  double imSum = 0.0;
228  std::vector<std::shared_ptr<image::Image<Pixel>>>::const_iterator kImPtrIter =
229  _kernelImagePtrList.begin();
230  std::vector<double>::const_iterator kSumIter = _kernelSumList.begin();
231  std::vector<double>::const_iterator kParIter = _kernelParams.begin();
232  for (; kImPtrIter != _kernelImagePtrList.end(); ++kImPtrIter, ++kSumIter, ++kParIter) {
233  image.scaledPlus(*kParIter, **kImPtrIter);
234  imSum += (*kSumIter) * (*kParIter);
235  }
236 
237  if (doNormalize) {
238  if (imSum == 0) {
239  throw LSST_EXCEPT(pexExcept::OverflowError, "Cannot normalize; kernel sum is 0");
240  }
241  image /= imSum;
242  imSum = 1;
243  }
244 
245  return imSum;
246 }
247 
248 void LinearCombinationKernel::setKernelParameter(unsigned int ind, double value) const {
249  this->_kernelParams[ind] = value;
250 }
251 
252 //
253 // Private Member Functions
254 //
255 void LinearCombinationKernel::_setKernelList(KernelList const &kernelList) {
256  _kernelSumList.clear();
257  _kernelImagePtrList.clear();
258  _kernelList.clear();
259  _isDeltaFunctionBasis = true;
260  for (KernelList::const_iterator kIter = kernelList.begin(), kEnd = kernelList.end(); kIter != kEnd;
261  ++kIter) {
262  std::shared_ptr<Kernel> basisKernelPtr = (*kIter)->clone();
263  if (dynamic_cast<DeltaFunctionKernel const *>(&(*basisKernelPtr)) == 0) {
264  _isDeltaFunctionBasis = false;
265  }
266  _kernelList.push_back(basisKernelPtr);
267  std::shared_ptr<image::Image<Pixel>> kernelImagePtr(new image::Image<Pixel>(this->getDimensions()));
268  _kernelSumList.push_back(basisKernelPtr->computeImage(*kernelImagePtr, false));
269  _kernelImagePtrList.push_back(kernelImagePtr);
270  }
271 }
272 
273 // ------ Persistence ---------------------------------------------------------------------------------------
274 
275 namespace {
276 
277 struct LinearCombinationKernelPersistenceHelper : public Kernel::PersistenceHelper {
278  table::Key<table::Array<double>> amplitudes;
279  table::Key<table::Array<int>> components;
280 
281  LinearCombinationKernelPersistenceHelper(int nComponents, bool isSpatiallyVarying)
282  : Kernel::PersistenceHelper(isSpatiallyVarying ? nComponents : 0),
283  components(schema.addField<table::Array<int>>("components", "archive IDs of component kernel",
284  nComponents)) {
285  if (!isSpatiallyVarying) {
286  amplitudes = schema.addField<table::Array<double>>("amplitudes", "amplitudes component kernel",
287  nComponents);
288  }
289  }
290 
291  LinearCombinationKernelPersistenceHelper(table::Schema const &schema_)
292  : Kernel::PersistenceHelper(schema_), components(schema["components"]) {
293  if (!spatialFunctions.isValid()) {
294  amplitudes = schema["amplitudes"];
295  LSST_ARCHIVE_ASSERT(amplitudes.getSize() == components.getSize());
296  } else {
297  LSST_ARCHIVE_ASSERT(spatialFunctions.getSize() == components.getSize());
298  }
299  }
300 };
301 
302 } // anonymous
303 
305 public:
306  virtual std::shared_ptr<afw::table::io::Persistable> read(InputArchive const &archive,
307  CatalogVector const &catalogs) const {
308  LSST_ARCHIVE_ASSERT(catalogs.size() == 1u);
309  LSST_ARCHIVE_ASSERT(catalogs.front().size() == 1u);
310  LinearCombinationKernelPersistenceHelper const keys(catalogs.front().getSchema());
311  afw::table::BaseRecord const &record = catalogs.front().front();
312  geom::Extent2I dimensions(record.get(keys.dimensions));
313  std::vector<std::shared_ptr<Kernel>> componentList(keys.components.getSize());
314  for (std::size_t i = 0; i < componentList.size(); ++i) {
315  componentList[i] = archive.get<Kernel>(record[keys.components[i]]);
316  }
317  std::shared_ptr<LinearCombinationKernel> result;
318  if (keys.spatialFunctions.isValid()) {
319  std::vector<SpatialFunctionPtr> spatialFunctionList = keys.readSpatialFunctions(archive, record);
320  result.reset(new LinearCombinationKernel(componentList, spatialFunctionList));
321  } else {
322  std::vector<double> kernelParameters(keys.amplitudes.getSize());
323  for (std::size_t i = 0; i < kernelParameters.size(); ++i) {
324  kernelParameters[i] = record[keys.amplitudes[i]];
325  }
326  result.reset(new LinearCombinationKernel(componentList, kernelParameters));
327  }
328  LSST_ARCHIVE_ASSERT(result->getDimensions() == dimensions);
329  result->setCtr(record.get(keys.center));
330  return result;
331  }
332 
333  explicit Factory(std::string const &name) : afw::table::io::PersistableFactory(name) {}
334 };
335 
336 namespace {
337 
338 std::string getLinearCombinationKernelPersistenceName() { return "LinearCombinationKernel"; }
339 
340 LinearCombinationKernel::Factory registration(getLinearCombinationKernelPersistenceName());
341 
342 } // anonymous
343 
345  return getLinearCombinationKernelPersistenceName();
346 }
347 
349  bool isVarying = isSpatiallyVarying();
350  LinearCombinationKernelPersistenceHelper const keys(getNBasisKernels(), isVarying);
351  std::shared_ptr<afw::table::BaseRecord> record = keys.write(handle, *this);
352  if (isVarying) {
353  for (int n = 0; n < keys.components.getSize(); ++n) {
354  record->set(keys.components[n], handle.put(_kernelList[n]));
355  record->set(keys.spatialFunctions[n], handle.put(_spatialFunctionList[n]));
356  }
357  } else {
358  for (int n = 0; n < keys.components.getSize(); ++n) {
359  record->set(keys.components[n], handle.put(_kernelList[n]));
360  record->set(keys.amplitudes[n], _kernelParams[n]);
361  }
362  }
363 }
364 }
365 }
366 } // 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