lsst.afw  14.0-58-g91bfccb15
ChebyshevBoundedField.cc
Go to the documentation of this file.
1 // -*- LSST-C++ -*-
2 /*
3  * LSST Data Management System
4  * Copyright 2008-2014 LSST Corporation.
5  *
6  * This product includes software developed by the
7  * LSST Project (http://www.lsst.org/).
8  *
9  * This program is free software: you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License as published by
11  * the Free Software Foundation, either version 3 of the License, or
12  * (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17  * GNU General Public License for more details.
18  *
19  * You should have received a copy of the LSST License Statement and
20  * the GNU General Public License along with this program. If not,
21  * see <http://www.lsstcorp.org/LegalNotices/>.
22  */
23 
24 #include <memory>
25 
26 #include "ndarray/eigen.h"
34 
35 namespace lsst {
36 namespace afw {
37 namespace math {
38 
40 
41 // ------------------ Constructors and helpers ---------------------------------------------------------------
42 
43 namespace {
44 
45 // Compute an affine transform that maps an arbitrary box to [-1,1]x[-1,1]
46 geom::AffineTransform makeChebyshevRangeTransform(afw::geom::Box2D const bbox) {
47  return geom::AffineTransform(
48  geom::LinearTransform::makeScaling(2.0 / bbox.getWidth(), 2.0 / bbox.getHeight()),
49  geom::Extent2D(-(2.0 * bbox.getCenterX()) / bbox.getWidth(),
50  -(2.0 * bbox.getCenterY()) / bbox.getHeight()));
51 }
52 
53 } // anonyomous
54 
56  ndarray::Array<double const, 2, 2> const& coefficients)
57  : BoundedField(bbox),
58  _toChebyshevRange(makeChebyshevRangeTransform(geom::Box2D(bbox))),
59  _coefficients(coefficients) {}
60 
62  : BoundedField(bbox), _toChebyshevRange(makeChebyshevRangeTransform(geom::Box2D(bbox))) {}
63 
67 
68 // ------------------ fit() and helpers ---------------------------------------------------------------------
69 
70 namespace {
71 
73 typedef detail::TrapezoidalPacker Packer;
74 
75 // fill an array with 1-d Chebyshev functions of the 1st kind T(x), evaluated at the given point x
76 void evaluateBasis1d(ndarray::Array<double, 1, 1> const& t, double x) {
77  int const n = t.getSize<0>();
78  if (n > 0) {
79  t[0] = 1.0;
80  }
81  if (n > 1) {
82  t[1] = x;
83  }
84  for (int i = 2; i < n; ++i) {
85  t[i] = 2.0*x*t[i-1] - t[i-2];
86  }
87 }
88 
89 // Create a matrix of 2-d Chebyshev functions evaluated at a set of positions, with
90 // Chebyshev order along columns and evaluation positions along rows. We pack the
91 // 2-d functions using the TrapezoidalPacker class, because we don't want any columns
92 // that correspond to coefficients that should be set to zero.
93 ndarray::Array<double, 2, 2> makeMatrix(ndarray::Array<double const, 1> const& x,
94  ndarray::Array<double const,1> const & y,
95  geom::AffineTransform const& toChebyshevRange, Packer const& packer,
96  Control const& ctrl) {
97  int const nPoints = x.getSize<0>();
98  ndarray::Array<double,1,1> tx = ndarray::allocate(packer.nx);
99  ndarray::Array<double,1,1> ty = ndarray::allocate(packer.ny);
100  ndarray::Array<double,2,2> out = ndarray::allocate(nPoints, packer.size);
101  // Loop over x and y together, computing T_i(x) and T_j(y) arrays for each point,
102  // then packing them together.
103  for (int p = 0; p < nPoints; ++p) {
104  geom::Point2D sxy = toChebyshevRange(geom::Point2D(x[p], y[p]));
105  evaluateBasis1d(tx, sxy.getX());
106  evaluateBasis1d(ty, sxy.getY());
107  packer.pack(out[p], tx, ty); // this sets a row of out to the packed outer product of tx and ty
108  }
109  return out;
110 }
111 
112 // Create a matrix of 2-d Chebyshev functions evaluated on a grid of positions, with
113 // Chebyshev order along columns and evaluation positions along rows. We pack the
114 // 2-d functions using the TrapezoidalPacker class, because we don't want any columns
115 // that correspond to coefficients that should be set to zero.
116 ndarray::Array<double, 2, 2> makeMatrix(geom::Box2I const& bbox,
117  geom::AffineTransform const& toChebyshevRange, Packer const& packer,
118  Control const& ctrl) {
119  // Create a 2-d array that contains T_j(x) for each x value, with x values in rows and j in columns
120  ndarray::Array<double,2,2> tx = ndarray::allocate(bbox.getWidth(), packer.nx);
121  for (int x = bbox.getBeginX(), p = 0; p < bbox.getWidth(); ++p, ++x) {
122  evaluateBasis1d(tx[p], toChebyshevRange[geom::AffineTransform::XX] * x +
123  toChebyshevRange[geom::AffineTransform::X]);
124  }
125 
126  // Loop over y values, and at each point, compute T_i(y), then loop over x and multiply by the T_j(x)
127  // we already computed and stored above.
128  ndarray::Array<double,2,2> out = ndarray::allocate(bbox.getArea(),packer.size);
129  ndarray::Array<double,2,2>::Iterator outIter = out.begin();
130  ndarray::Array<double,1,1> ty = ndarray::allocate(ctrl.orderY + 1);
131  for (int y = bbox.getBeginY(), i = 0; i < bbox.getHeight(); ++i, ++y) {
132  evaluateBasis1d(ty, toChebyshevRange[geom::AffineTransform::YY] * y +
133  toChebyshevRange[geom::AffineTransform::Y]);
134  for (int j = 0; j < bbox.getWidth(); ++j, ++outIter) {
135  // this sets a row of out to the packed outer product of tx and ty
136  packer.pack(*outIter, tx[j], ty);
137  }
138  }
139  return out;
140 }
141 
142 } // anonymous
143 
145  ndarray::Array<double const,1> const & x,
146  ndarray::Array<double const,1> const & y,
147  ndarray::Array<double const,1> const & z,
148  Control const& ctrl) {
149  // Initialize the result object, so we can make use of the AffineTransform it builds
151  // This packer object knows how to map the 2-d Chebyshev functions onto a 1-d array,
152  // using only those that the control says should have nonzero coefficients.
153  Packer const packer(ctrl);
154  // Create a "design matrix" for the linear least squares problem (A in min||Ax-b||)
155  ndarray::Array<double,2,2> matrix = makeMatrix(x, y, result->_toChebyshevRange, packer, ctrl);
156  // Solve the linear least squares problem.
158  // Unpack the solution into a 2-d matrix, with zeros for values we didn't fit.
159  result->_coefficients = packer.unpack(lstsq.getSolution());
160  return result;
161 }
162 
164  ndarray::Array<double const,1> const & x,
165  ndarray::Array<double const,1> const & y,
166  ndarray::Array<double const,1> const & z,
167  ndarray::Array<double const,1> const & w,
168  Control const& ctrl) {
169  // Initialize the result object, so we can make use of the AffineTransform it builds
171  // This packer object knows how to map the 2-d Chebyshev functions onto a 1-d array,
172  // using only those that the control says should have nonzero coefficients.
173  Packer const packer(ctrl);
174  // Create a "design matrix" for the linear least squares problem ('A' in min||Ax-b||)
175  ndarray::Array<double,2,2> matrix = makeMatrix(x, y, result->_toChebyshevRange, packer, ctrl);
176  // We want to do weighted least squares, so we multiply both the data vector 'b' and the
177  // matrix 'A' by the weights.
178  matrix.asEigen<Eigen::ArrayXpr>().colwise() *= w.asEigen<Eigen::ArrayXpr>();
179  ndarray::Array<double,1,1> wz = ndarray::copy(z);
180  wz.asEigen<Eigen::ArrayXpr>() *= w.asEigen<Eigen::ArrayXpr>();
181  // Solve the linear least squares problem.
183  // Unpack the solution into a 2-d matrix, with zeros for values we didn't fit.
184  result->_coefficients = packer.unpack(lstsq.getSolution());
185  return result;
186 }
187 
188 template <typename T>
190  Control const& ctrl) {
191  // Initialize the result object, so we can make use of the AffineTransform it builds
192  geom::Box2I bbox = img.getBBox(image::PARENT);
194  // This packer object knows how to map the 2-d Chebyshev functions onto a 1-d array,
195  // using only those that the control says should have nonzero coefficients.
196  Packer const packer(ctrl);
197  ndarray::Array<double,2,2> matrix = makeMatrix(bbox, result->_toChebyshevRange, packer, ctrl);
198  // Flatten the data image into a 1-d vector.
199  ndarray::Array<double,2,2> imgCopy = ndarray::allocate(img.getArray().getShape());
200  imgCopy.deep() = img.getArray();
201  ndarray::Array<double const,1,1> z = ndarray::flatten<1>(imgCopy);
202  // Solve the linear least squares problem.
204  // Unpack the solution into a 2-d matrix, with zeros for values we didn't fit.
205  result->_coefficients = packer.unpack(lstsq.getSolution());
206  return result;
207 }
208 
209 // ------------------ modifier factories ---------------------------------------------------------------
210 
212  if (static_cast<std::size_t>(ctrl.orderX) >= _coefficients.getSize<1>()) {
214  (boost::format("New x order (%d) exceeds old x order (%d)") % ctrl.orderX %
215  (_coefficients.getSize<1>() -
216  1)).str());
217  }
218  if (static_cast<std::size_t>(ctrl.orderY) >= _coefficients.getSize<0>()) {
220  (boost::format("New y order (%d) exceeds old y order (%d)") % ctrl.orderY %
221  (_coefficients.getSize<0>() -
222  1)).str());
223  }
224  ndarray::Array<double,2,2> coefficients = ndarray::allocate(ctrl.orderY + 1, ctrl.orderX + 1);
225  coefficients.deep() = _coefficients[ndarray::view(0, ctrl.orderY + 1)(0, ctrl.orderX + 1)];
226  if (ctrl.triangular) {
227  Packer packer(ctrl);
228  ndarray::Array<double,1,1> packed = ndarray::allocate(packer.size);
229  packer.pack(packed, coefficients);
230  packer.unpack(coefficients, packed);
231  }
232  return std::make_shared<ChebyshevBoundedField>(getBBox(), coefficients);
233 }
234 
236  return std::make_shared<ChebyshevBoundedField>(bbox, _coefficients);
237 }
238 
239 // ------------------ evaluate() and helpers ---------------------------------------------------------------
240 
241 namespace {
242 
243 // To evaluate a 1-d Chebyshev function without needing to have workspace, we use the
244 // Clenshaw algorith, which is like going through the recurrence relation in reverse.
245 // The CoeffGetter argument g is something that behaves like an array, providing access
246 // to the coefficients.
247 template <typename CoeffGetter>
248 double evaluateFunction1d(CoeffGetter g, double x, int size) {
249  double b_kp2=0.0, b_kp1=0.0;
250  for (int k = (size - 1); k > 0; --k) {
251  double b_k = g[k] + 2*x*b_kp1 - b_kp2;
252  b_kp2 = b_kp1;
253  b_kp1 = b_k;
254  }
255  return g[0] + x*b_kp1 - b_kp2;
256 }
257 
258 // This class imitates a 1-d array, by running evaluateFunction1d on a nested dimension;
259 // this lets us reuse the logic in evaluateFunction1d for both dimensions. Essentially,
260 // we run evaluateFunction1d on a column of coefficients to evaluate T_i(x), then pass
261 // the result of that to evaluateFunction1d with the results as the "coefficients" associated
262 // with the T_j(y) functions.
263 struct RecursionArrayImitator {
264  double operator[](int i) const {
265  return evaluateFunction1d(coefficients[i], x, coefficients.getSize<1>());
266  }
267 
268  RecursionArrayImitator(ndarray::Array<double const, 2, 2> const& coefficients_, double x_)
269  : coefficients(coefficients_), x(x_) {}
270 
271  ndarray::Array<double const,2,2> coefficients;
272  double x;
273 };
274 
275 } // anonymous
276 
277 double ChebyshevBoundedField::evaluate(geom::Point2D const & position) const {
278  geom::Point2D p = _toChebyshevRange(position);
279  return evaluateFunction1d(RecursionArrayImitator(_coefficients, p.getX()), p.getY(),
280  _coefficients.getSize<0>());
281 }
282 
283 // The integral of T_n(x) over [-1,1]:
284 // https://en.wikipedia.org/wiki/Chebyshev_polynomials#Differentiation_and_integration
285 double integrateTn(int n) {
286  if (n % 2 == 1)
287  return 0;
288  else
289  return 2.0/(1.0 - double(n*n));
290 }
291 
293  double result = 0;
294  double determinant = getBBox().getArea() / 4.0;
295  for (ndarray::Size j=0; j < _coefficients.getSize<0>(); j++){
296  for (ndarray::Size i=0; i < _coefficients.getSize<1>(); i++){
297  result += _coefficients[j][i] * integrateTn(i) * integrateTn(j);
298  }
299  }
300  return result * determinant;
301 }
302 
303 double ChebyshevBoundedField::mean() const { return integrate() / getBBox().getArea(); }
304 
305 // ------------------ persistence ---------------------------------------------------------------------------
306 
307 namespace {
308 
309 struct PersistenceHelper {
310  table::Schema schema;
311  table::Key<int> orderX;
313  table::Key< table::Array<double> > coefficients;
314 
315  PersistenceHelper(int nx, int ny)
316  : schema(),
317  orderX(schema.addField<int>("order_x", "maximum Chebyshev function order in x")),
318  bbox(table::Box2IKey::addFields(schema, "bbox", "bounding box", "pixel")),
319  coefficients(schema.addField<table::Array<double> >(
320  "coefficients", "Chebyshev function coefficients, ordered by y then x", nx * ny)) {}
321 
322  PersistenceHelper(table::Schema const& s)
323  : schema(s),
324  orderX(s["order_x"]),
325  bbox(s["bbox"]),
326  coefficients(s["coefficients"]) {}
327 };
328 
329 class ChebyshevBoundedFieldFactory : public table::io::PersistableFactory {
330 public:
331  explicit ChebyshevBoundedFieldFactory(std::string const& name)
332  : afw::table::io::PersistableFactory(name) {}
333 
334  virtual std::shared_ptr<table::io::Persistable> read(InputArchive const& archive,
335  CatalogVector const& catalogs) const {
336  LSST_ARCHIVE_ASSERT(catalogs.size() == 1u);
337  LSST_ARCHIVE_ASSERT(catalogs.front().size() == 1u);
338  table::BaseRecord const & record = catalogs.front().front();
339  PersistenceHelper const keys(record.getSchema());
340  geom::Box2I bbox(record.get(keys.bbox));
341  int nx = record.get(keys.orderX) + 1;
342  int ny = keys.coefficients.getSize() / nx;
343  LSST_ARCHIVE_ASSERT(nx * ny == keys.coefficients.getSize());
344  ndarray::Array<double,2,2> coefficients = ndarray::allocate(ny, nx);
345  ndarray::flatten<1>(coefficients) = record.get(keys.coefficients);
346  return std::make_shared<ChebyshevBoundedField>(bbox, coefficients);
347  }
348 };
349 
350 std::string getChebyshevBoundedFieldPersistenceName() { return "ChebyshevBoundedField"; }
351 
352 ChebyshevBoundedFieldFactory registration(getChebyshevBoundedFieldPersistenceName());
353 
354 } // anonymous
355 
357  return getChebyshevBoundedFieldPersistenceName();
358 }
359 
360 std::string ChebyshevBoundedField::getPythonModule() const { return "lsst.afw.math"; }
361 
363  PersistenceHelper const keys(_coefficients.getSize<1>(), _coefficients.getSize<0>());
364  table::BaseCatalog catalog = handle.makeCatalog(keys.schema);
365  std::shared_ptr<table::BaseRecord> record = catalog.addNew();
366  record->set(keys.orderX, _coefficients.getSize<1>() - 1);
367  record->set(keys.bbox, getBBox());
368  (*record)[keys.coefficients].deep() = ndarray::flatten<1>(_coefficients);
369  handle.saveCatalog(catalog);
370 }
371 
372 // ------------------ operators -----------------------------------------------------------------------------
373 
375  return std::make_shared<ChebyshevBoundedField>(getBBox(), ndarray::copy(getCoefficients()*scale));
376 }
377 
379  auto rhsCasted = dynamic_cast<ChebyshevBoundedField const *>(&rhs);
380  if (!rhsCasted) return false;
381 
382  return (getBBox() == rhsCasted->getBBox()) &&
383  (_coefficients.getShape() == rhsCasted->_coefficients.getShape()) &&
384  all(equal(_coefficients, rhsCasted->_coefficients));
385 }
386 
387 std::string ChebyshevBoundedField::toString() const {
389  os << "ChebyshevBoundedField (" << _coefficients.getShape() << " coefficients in y,x)";
390  return os.str();
391 }
392 
393 // ------------------ explicit instantiation ----------------------------------------------------------------
394 
395 #ifndef DOXYGEN
396 
397 #define INSTANTIATE(T) \
398  template std::shared_ptr<ChebyshevBoundedField> ChebyshevBoundedField::fit(image::Image<T> const& image, \
399  Control const& ctrl)
400 
401 INSTANTIATE(float);
402 INSTANTIATE(double);
403 
404 #endif
405 }
406 }
407 } // namespace lsst::afw::math
virtual double integrate() const
Compute the integral of this function over its bounding-box.
bool all(CoordinateExpr< N > const &expr)
Return true if all elements are true.
table::Key< std::string > name
Definition: ApCorrMap.cc:71
geom::Box2I getBBox(ImageOrigin origin=PARENT) const
Definition: ImageBase.h:448
virtual std::string getPythonModule() const
Return the fully-qualified Python module that should be imported to guarantee that its factory is reg...
An object passed to Persistable::write to allow it to persist itself.
virtual void write(OutputArchiveHandle &handle) const
Write the object to one or more catalogs.
A custom container class for records, based on std::vector.
Definition: Catalog.h:97
#define LSST_ARCHIVE_ASSERT(EXPR)
An assertion macro used to validate the structure of an InputArchive.
Definition: Persistable.h:48
int getArea() const
Definition: Box.h:156
def scale(algorithm, min, max=None, frame=None)
Definition: ds9.py:117
A control object used when fitting ChebyshevBoundedField to data (see ChebyshevBoundedField::fit) ...
virtual double evaluate(geom::Point2D const &position) const
Evaluate the field at the given point.
static LinearTransform makeScaling(double s)
Solver for linear least-squares problems.
Definition: LeastSquares.h:67
std::shared_ptr< ChebyshevBoundedField > relocate(geom::Box2I const &bbox) const
Return a new ChebyshevBoundedField with domain set to the given bounding box.
ndarray::Array< double const, 2, 2 > getCoefficients() const
Return the coefficient matrix.
static LeastSquares fromDesignMatrix(ndarray::Array< T1, 2, C1 > const &design, ndarray::Array< T2, 1, C2 > const &data, Factorization factorization=NORMAL_EIGENSYSTEM)
Initialize from the design matrix and data vector given as ndarrays.
Definition: LeastSquares.h:100
int getHeight() const
Definition: Box.h:155
table::Schema schema
std::shared_ptr< ChebyshevBoundedField > truncate(Control const &ctrl) const
Return a new ChebyshevBoudedField with maximum orders set by the given control object.
An integer coordinate rectangle.
Definition: Box.h:55
BoxKey< geom::Box2I > Box2IKey
Definition: aggregates.h:195
STL class.
geom::Box2I getBBox() const
Return the bounding box that defines the region where the field is valid.
Definition: BoundedField.h:112
int computeSize() const
Return the number of nonzero coefficients in the Chebyshev function defined by this object...
BoundedField(BoundedField const &)=default
Use the normal equations with a symmetric Eigensystem decomposition.
Definition: LeastSquares.h:72
int orderY
"maximum Chebyshev function order in y" ;
A base class for image defects.
double getCenterX() const
Definition: Box.h:369
An affine coordinate transformation consisting of a linear transformation and an offset.
#define INSTANTIATE(FROMSYS, TOSYS)
Definition: Detector.cc:156
double getHeight() const
Definition: Box.h:355
T str(T... args)
double x
int getWidth() const
Definition: Box.h:154
int getBeginX() const
Definition: Box.h:139
BaseCatalog makeCatalog(Schema const &schema)
Return a new, empty catalog with the given schema.
bool triangular
"if true, only include terms where the sum of the x and y order " "is less than or equal to max(order...
#define LSST_EXCEPT(type,...)
int getBeginY() const
Definition: Box.h:140
A BoundedField based on 2-d Chebyshev polynomials of the first kind.
ChebyshevBoundedField(afw::geom::Box2I const &bbox, ndarray::Array< double const, 2, 2 > const &coefficients)
Initialize the field from its bounding box an coefficients.
virtual double mean() const
Compute the mean of this function over its bounding-box.
An abstract base class for 2-d functions defined on an integer bounding boxes.
Definition: BoundedField.h:55
virtual std::shared_ptr< BoundedField > operator*(double const scale) const
Return a scaled BoundedField.
virtual std::string getPersistenceName() const
Return the unique name used to persist this object and look up its factory.
table::Box2IKey bbox
ndarray::Array< double const, 1, 1 > getSolution()
Return the vector solution to the least squares problem.
virtual bool operator==(BoundedField const &rhs) const
BoundedFields (of the same sublcass) are equal if their bounding boxes and parameters are equal...
double getCenterY() const
Definition: Box.h:370
void saveCatalog(BaseCatalog const &catalog)
Save a catalog in the archive.
A floating-point coordinate rectangle geometry.
Definition: Box.h:266
table::Key< int > orderX
ndarray::Array< double const, 2, 2 > coefficients
static std::shared_ptr< ChebyshevBoundedField > fit(afw::geom::Box2I const &bbox, ndarray::Array< double const, 1 > const &x, ndarray::Array< double const, 1 > const &y, ndarray::Array< double const, 1 > const &z, Control const &ctrl)
Fit a Chebyshev approximation to non-gridded data with equal weights.
A class to represent a 2-dimensional array of pixels.
Definition: Image.h:69
A helper class ChebyshevBoundedField, for mapping trapezoidal matrices to 1-d arrays.
std::shared_ptr< RecordT > addNew()
Create a new record, add it to the end of the catalog, and return a pointer to it.
Definition: Catalog.h:472
double getWidth() const
Definition: Box.h:354
int orderX
"maximum Chebyshev function order in x" ;