lsst.afw  16.0-10-gd1b3a1c94
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 lsst::geom::AffineTransform makeChebyshevRangeTransform(lsst::geom::Box2D const bbox) {
49  lsst::geom::Extent2D(-(2.0 * bbox.getCenterX()) / bbox.getWidth(),
50  -(2.0 * bbox.getCenterY()) / bbox.getHeight()));
51 }
52 
53 } // namespace
54 
56  ndarray::Array<double const, 2, 2> const& coefficients)
57  : BoundedField(bbox),
58  _toChebyshevRange(makeChebyshevRangeTransform(lsst::geom::Box2D(bbox))),
59  _coefficients(coefficients) {}
60 
62  : BoundedField(bbox), _toChebyshevRange(makeChebyshevRangeTransform(lsst::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  lsst::geom::AffineTransform const& toChebyshevRange,
96  Packer const& packer, 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  lsst::geom::Point2D sxy = toChebyshevRange(lsst::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(lsst::geom::Box2I const& bbox,
117  lsst::geom::AffineTransform const& toChebyshevRange,
118  Packer const& packer, 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[lsst::geom::AffineTransform::XX] * x +
123  toChebyshevRange[lsst::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[lsst::geom::AffineTransform::YY] * y +
133  toChebyshevRange[lsst::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 } // namespace
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  ndarray::asEigenArray(matrix).colwise() *= ndarray::asEigenArray(w);
179  ndarray::Array<double, 1, 1> wz = ndarray::copy(z);
180  ndarray::asEigenArray(wz) *= ndarray::asEigenArray(w);
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
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>() - 1))
216  .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>() - 1))
222  .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 } // namespace
276 
278  lsst::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), orderX(s["order_x"]), bbox(s["bbox"]), coefficients(s["coefficients"]) {}
324 };
325 
326 class ChebyshevBoundedFieldFactory : public table::io::PersistableFactory {
327 public:
328  explicit ChebyshevBoundedFieldFactory(std::string const& name)
329  : afw::table::io::PersistableFactory(name) {}
330 
331  virtual std::shared_ptr<table::io::Persistable> read(InputArchive const& archive,
332  CatalogVector const& catalogs) const {
333  LSST_ARCHIVE_ASSERT(catalogs.size() == 1u);
334  LSST_ARCHIVE_ASSERT(catalogs.front().size() == 1u);
335  table::BaseRecord const& record = catalogs.front().front();
336  PersistenceHelper const keys(record.getSchema());
337  lsst::geom::Box2I bbox(record.get(keys.bbox));
338  int nx = record.get(keys.orderX) + 1;
339  int ny = keys.coefficients.getSize() / nx;
340  LSST_ARCHIVE_ASSERT(nx * ny == keys.coefficients.getSize());
341  ndarray::Array<double, 2, 2> coefficients = ndarray::allocate(ny, nx);
342  ndarray::flatten<1>(coefficients) = record.get(keys.coefficients);
343  return std::make_shared<ChebyshevBoundedField>(bbox, coefficients);
344  }
345 };
346 
347 std::string getChebyshevBoundedFieldPersistenceName() { return "ChebyshevBoundedField"; }
348 
349 ChebyshevBoundedFieldFactory registration(getChebyshevBoundedFieldPersistenceName());
350 
351 } // namespace
352 
354  return getChebyshevBoundedFieldPersistenceName();
355 }
356 
357 std::string ChebyshevBoundedField::getPythonModule() const { return "lsst.afw.math"; }
358 
360  PersistenceHelper const keys(_coefficients.getSize<1>(), _coefficients.getSize<0>());
361  table::BaseCatalog catalog = handle.makeCatalog(keys.schema);
362  std::shared_ptr<table::BaseRecord> record = catalog.addNew();
363  record->set(keys.orderX, _coefficients.getSize<1>() - 1);
364  record->set(keys.bbox, getBBox());
365  (*record)[keys.coefficients].deep() = ndarray::flatten<1>(_coefficients);
366  handle.saveCatalog(catalog);
367 }
368 
369 // ------------------ operators -----------------------------------------------------------------------------
370 
372  return std::make_shared<ChebyshevBoundedField>(getBBox(), ndarray::copy(getCoefficients() * scale));
373 }
374 
376  auto rhsCasted = dynamic_cast<ChebyshevBoundedField const*>(&rhs);
377  if (!rhsCasted) return false;
378 
379  return (getBBox() == rhsCasted->getBBox()) &&
380  (_coefficients.getShape() == rhsCasted->_coefficients.getShape()) &&
381  all(equal(_coefficients, rhsCasted->_coefficients));
382 }
383 
384 std::string ChebyshevBoundedField::toString() const {
386  os << "ChebyshevBoundedField (" << _coefficients.getShape() << " coefficients in y,x)";
387  return os.str();
388 }
389 
390 // ------------------ explicit instantiation ----------------------------------------------------------------
391 
392 #ifndef DOXYGEN
393 
394 #define INSTANTIATE(T) \
395  template std::shared_ptr<ChebyshevBoundedField> ChebyshevBoundedField::fit(image::Image<T> const& image, \
396  Control const& ctrl)
397 
398 INSTANTIATE(float);
399 INSTANTIATE(double);
400 
401 #endif
402 } // namespace math
403 } // namespace afw
404 } // namespace lsst
ChebyshevBoundedField(lsst::geom::Box2I const &bbox, ndarray::Array< double const, 2, 2 > const &coefficients)
Initialize the field from its bounding box an coefficients.
double getCenterY() const
static LinearTransform makeScaling(double s)
def keys(self)
virtual double integrate() const
Compute the integral of this function over its bounding-box.
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.
double getHeight() const
BoxKey< lsst::geom::Box2I > Box2IKey
Definition: aggregates.h:187
#define LSST_ARCHIVE_ASSERT(EXPR)
An assertion macro used to validate the structure of an InputArchive.
Definition: Persistable.h:48
virtual double evaluate(lsst::geom::Point2D const &position) const
Evaluate the field at the given point.
def scale(algorithm, min, max=None, frame=None)
Definition: ds9.py:113
A control object used when fitting ChebyshevBoundedField to data (see ChebyshevBoundedField::fit) ...
Solver for linear least-squares problems.
Definition: LeastSquares.h:67
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
double getWidth() const
double z
Definition: Match.cc:44
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.
STL class.
double getCenterX() const
ndarray::Array< double const, 2, 2 > coefficients
int computeSize() const
Return the number of nonzero coefficients in the Chebyshev function defined by this object...
bool all(CoordinateExpr< N > const &expr)
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.
lsst::geom::Box2I getBBox(ImageOrigin origin=PARENT) const
Definition: ImageBase.h:448
int getHeight() const
int getArea() const
#define INSTANTIATE(FROMSYS, TOSYS)
Definition: Detector.cc:156
lsst::geom::Box2I getBBox() const
Return the bounding box that defines the region where the field is valid.
Definition: BoundedField.h:112
int getBeginY() const
T str(T... args)
std::shared_ptr< ChebyshevBoundedField > relocate(lsst::geom::Box2I const &bbox) const
Return a new ChebyshevBoundedField with domain set to the given bounding box.
double x
std::unique_ptr< SchemaItem< U > > result
Definition: Schema.cc:194
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 getWidth() const
ndarray::Array< double const, 2, 2 > getCoefficients() const
Return the coefficient matrix.
A BoundedField based on 2-d Chebyshev polynomials of the first kind.
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...
void saveCatalog(BaseCatalog const &catalog)
Save a catalog in the archive.
table::Key< int > orderX
std::ostream * os
Definition: Schema.cc:737
A class to represent a 2-dimensional array of pixels.
Definition: Image.h:67
int y
Definition: SpanSet.cc:44
A helper class ChebyshevBoundedField, for mapping trapezoidal matrices to 1-d arrays.
int getBeginX() const
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
static std::shared_ptr< ChebyshevBoundedField > fit(lsst::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.
int orderX
"maximum Chebyshev function order in x" ;