lsst.afw  13.0-73-gb2a4e38
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Groups Pages
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 
64 // ------------------ fit() and helpers ---------------------------------------------------------------------
65 
66 namespace {
67 
68 typedef ChebyshevBoundedField::Control Control;
69 typedef detail::TrapezoidalPacker Packer;
70 
71 // fill an array with 1-d Chebyshev functions of the 1st kind T(x), evaluated at the given point x
72 void evaluateBasis1d(ndarray::Array<double, 1, 1> const& t, double x) {
73  int const n = t.getSize<0>();
74  if (n > 0) {
75  t[0] = 1.0;
76  }
77  if (n > 1) {
78  t[1] = x;
79  }
80  for (int i = 2; i < n; ++i) {
81  t[i] = 2.0*x*t[i-1] - t[i-2];
82  }
83 }
84 
85 // Create a matrix of 2-d Chebyshev functions evaluated at a set of positions, with
86 // Chebyshev order along columns and evaluation positions along rows. We pack the
87 // 2-d functions using the TrapezoidalPacker class, because we don't want any columns
88 // that correspond to coefficients that should be set to zero.
89 ndarray::Array<double, 2, 2> makeMatrix(ndarray::Array<double const, 1> const& x,
90  ndarray::Array<double const,1> const & y,
91  geom::AffineTransform const& toChebyshevRange, Packer const& packer,
92  Control const& ctrl) {
93  int const nPoints = x.getSize<0>();
94  ndarray::Array<double,1,1> tx = ndarray::allocate(packer.nx);
95  ndarray::Array<double,1,1> ty = ndarray::allocate(packer.ny);
96  ndarray::Array<double,2,2> out = ndarray::allocate(nPoints, packer.size);
97  // Loop over x and y together, computing T_i(x) and T_j(y) arrays for each point,
98  // then packing them together.
99  for (int p = 0; p < nPoints; ++p) {
100  geom::Point2D sxy = toChebyshevRange(geom::Point2D(x[p], y[p]));
101  evaluateBasis1d(tx, sxy.getX());
102  evaluateBasis1d(ty, sxy.getY());
103  packer.pack(out[p], tx, ty); // this sets a row of out to the packed outer product of tx and ty
104  }
105  return out;
106 }
107 
108 // Create a matrix of 2-d Chebyshev functions evaluated on a grid of positions, with
109 // Chebyshev order along columns and evaluation positions along rows. We pack the
110 // 2-d functions using the TrapezoidalPacker class, because we don't want any columns
111 // that correspond to coefficients that should be set to zero.
112 ndarray::Array<double, 2, 2> makeMatrix(geom::Box2I const& bbox,
113  geom::AffineTransform const& toChebyshevRange, Packer const& packer,
114  Control const& ctrl) {
115  // Create a 2-d array that contains T_j(x) for each x value, with x values in rows and j in columns
116  ndarray::Array<double,2,2> tx = ndarray::allocate(bbox.getWidth(), packer.nx);
117  for (int x = bbox.getBeginX(), p = 0; p < bbox.getWidth(); ++p, ++x) {
118  evaluateBasis1d(tx[p], toChebyshevRange[geom::AffineTransform::XX] * x +
119  toChebyshevRange[geom::AffineTransform::X]);
120  }
121 
122  // Loop over y values, and at each point, compute T_i(y), then loop over x and multiply by the T_j(x)
123  // we already computed and stored above.
124  ndarray::Array<double,2,2> out = ndarray::allocate(bbox.getArea(),packer.size);
125  ndarray::Array<double,2,2>::Iterator outIter = out.begin();
126  ndarray::Array<double,1,1> ty = ndarray::allocate(ctrl.orderY + 1);
127  for (int y = bbox.getBeginY(), i = 0; i < bbox.getHeight(); ++i, ++y) {
128  evaluateBasis1d(ty, toChebyshevRange[geom::AffineTransform::YY] * y +
129  toChebyshevRange[geom::AffineTransform::Y]);
130  for (int j = 0; j < bbox.getWidth(); ++j, ++outIter) {
131  // this sets a row of out to the packed outer product of tx and ty
132  packer.pack(*outIter, tx[j], ty);
133  }
134  }
135  return out;
136 }
137 
138 } // anonymous
139 
140 std::shared_ptr<ChebyshevBoundedField> ChebyshevBoundedField::fit(afw::geom::Box2I const& bbox,
141  ndarray::Array<double const,1> const & x,
142  ndarray::Array<double const,1> const & y,
143  ndarray::Array<double const,1> const & z,
144  Control const& ctrl) {
145  // Initialize the result object, so we can make use of the AffineTransform it builds
146  std::shared_ptr<ChebyshevBoundedField> result(new ChebyshevBoundedField(bbox));
147  // This packer object knows how to map the 2-d Chebyshev functions onto a 1-d array,
148  // using only those that the control says should have nonzero coefficients.
149  Packer const packer(ctrl);
150  // Create a "design matrix" for the linear least squares problem (A in min||Ax-b||)
151  ndarray::Array<double,2,2> matrix = makeMatrix(x, y, result->_toChebyshevRange, packer, ctrl);
152  // Solve the linear least squares problem.
154  // Unpack the solution into a 2-d matrix, with zeros for values we didn't fit.
155  result->_coefficients = packer.unpack(lstsq.getSolution());
156  return result;
157 }
158 
159 std::shared_ptr<ChebyshevBoundedField> ChebyshevBoundedField::fit(afw::geom::Box2I const& bbox,
160  ndarray::Array<double const,1> const & x,
161  ndarray::Array<double const,1> const & y,
162  ndarray::Array<double const,1> const & z,
163  ndarray::Array<double const,1> const & w,
164  Control const& ctrl) {
165  // Initialize the result object, so we can make use of the AffineTransform it builds
166  std::shared_ptr<ChebyshevBoundedField> result(new ChebyshevBoundedField(bbox));
167  // This packer object knows how to map the 2-d Chebyshev functions onto a 1-d array,
168  // using only those that the control says should have nonzero coefficients.
169  Packer const packer(ctrl);
170  // Create a "design matrix" for the linear least squares problem ('A' in min||Ax-b||)
171  ndarray::Array<double,2,2> matrix = makeMatrix(x, y, result->_toChebyshevRange, packer, ctrl);
172  // We want to do weighted least squares, so we multiply both the data vector 'b' and the
173  // matrix 'A' by the weights.
174  matrix.asEigen<Eigen::ArrayXpr>().colwise() *= w.asEigen<Eigen::ArrayXpr>();
175  ndarray::Array<double,1,1> wz = ndarray::copy(z);
176  wz.asEigen<Eigen::ArrayXpr>() *= w.asEigen<Eigen::ArrayXpr>();
177  // Solve the linear least squares problem.
179  // Unpack the solution into a 2-d matrix, with zeros for values we didn't fit.
180  result->_coefficients = packer.unpack(lstsq.getSolution());
181  return result;
182 }
183 
184 template <typename T>
185 std::shared_ptr<ChebyshevBoundedField> ChebyshevBoundedField::fit(image::Image<T> const& img,
186  Control const& ctrl) {
187  // Initialize the result object, so we can make use of the AffineTransform it builds
188  geom::Box2I bbox = img.getBBox(image::PARENT);
189  std::shared_ptr<ChebyshevBoundedField> result(new ChebyshevBoundedField(bbox));
190  // This packer object knows how to map the 2-d Chebyshev functions onto a 1-d array,
191  // using only those that the control says should have nonzero coefficients.
192  Packer const packer(ctrl);
193  ndarray::Array<double,2,2> matrix = makeMatrix(bbox, result->_toChebyshevRange, packer, ctrl);
194  // Flatten the data image into a 1-d vector.
195  ndarray::Array<double,2,2> imgCopy = ndarray::allocate(img.getArray().getShape());
196  imgCopy.deep() = img.getArray();
197  ndarray::Array<double const,1,1> z = ndarray::flatten<1>(imgCopy);
198  // Solve the linear least squares problem.
200  // Unpack the solution into a 2-d matrix, with zeros for values we didn't fit.
201  result->_coefficients = packer.unpack(lstsq.getSolution());
202  return result;
203 }
204 
205 // ------------------ modifier factories ---------------------------------------------------------------
206 
207 std::shared_ptr<ChebyshevBoundedField> ChebyshevBoundedField::truncate(Control const& ctrl) const {
208  if (static_cast<std::size_t>(ctrl.orderX) >= _coefficients.getSize<1>()) {
209  throw LSST_EXCEPT(pex::exceptions::LengthError,
210  (boost::format("New x order (%d) exceeds old x order (%d)") % ctrl.orderX %
211  (_coefficients.getSize<1>() -
212  1)).str());
213  }
214  if (static_cast<std::size_t>(ctrl.orderY) >= _coefficients.getSize<0>()) {
215  throw LSST_EXCEPT(pex::exceptions::LengthError,
216  (boost::format("New y order (%d) exceeds old y order (%d)") % ctrl.orderY %
217  (_coefficients.getSize<0>() -
218  1)).str());
219  }
220  ndarray::Array<double,2,2> coefficients = ndarray::allocate(ctrl.orderY + 1, ctrl.orderX + 1);
221  coefficients.deep() = _coefficients[ndarray::view(0, ctrl.orderY + 1)(0, ctrl.orderX + 1)];
222  if (ctrl.triangular) {
223  Packer packer(ctrl);
224  ndarray::Array<double,1,1> packed = ndarray::allocate(packer.size);
225  packer.pack(packed, coefficients);
226  packer.unpack(coefficients, packed);
227  }
228  return std::make_shared<ChebyshevBoundedField>(getBBox(), coefficients);
229 }
230 
231 std::shared_ptr<ChebyshevBoundedField> ChebyshevBoundedField::relocate(geom::Box2I const& bbox) const {
232  return std::make_shared<ChebyshevBoundedField>(bbox, _coefficients);
233 }
234 
235 // ------------------ evaluate() and helpers ---------------------------------------------------------------
236 
237 namespace {
238 
239 // To evaluate a 1-d Chebyshev function without needing to have workspace, we use the
240 // Clenshaw algorith, which is like going through the recurrence relation in reverse.
241 // The CoeffGetter argument g is something that behaves like an array, providing access
242 // to the coefficients.
243 template <typename CoeffGetter>
244 double evaluateFunction1d(CoeffGetter g, double x, int size) {
245  double b_kp2=0.0, b_kp1=0.0;
246  for (int k = (size - 1); k > 0; --k) {
247  double b_k = g[k] + 2*x*b_kp1 - b_kp2;
248  b_kp2 = b_kp1;
249  b_kp1 = b_k;
250  }
251  return g[0] + x*b_kp1 - b_kp2;
252 }
253 
254 // This class imitates a 1-d array, by running evaluateFunction1d on a nested dimension;
255 // this lets us reuse the logic in evaluateFunction1d for both dimensions. Essentially,
256 // we run evaluateFunction1d on a column of coefficients to evaluate T_i(x), then pass
257 // the result of that to evaluateFunction1d with the results as the "coefficients" associated
258 // with the T_j(y) functions.
259 struct RecursionArrayImitator {
260  double operator[](int i) const {
261  return evaluateFunction1d(coefficients[i], x, coefficients.getSize<1>());
262  }
263 
264  RecursionArrayImitator(ndarray::Array<double const, 2, 2> const& coefficients_, double x_)
265  : coefficients(coefficients_), x(x_) {}
266 
267  ndarray::Array<double const,2,2> coefficients;
268  double x;
269 };
270 
271 } // anonymous
272 
273 double ChebyshevBoundedField::evaluate(geom::Point2D const & position) const {
274  geom::Point2D p = _toChebyshevRange(position);
275  return evaluateFunction1d(RecursionArrayImitator(_coefficients, p.getX()), p.getY(),
276  _coefficients.getSize<0>());
277 }
278 
279 // The integral of T_n(x) over [-1,1]:
280 // https://en.wikipedia.org/wiki/Chebyshev_polynomials#Differentiation_and_integration
281 double integrateTn(int n) {
282  if (n % 2 == 1)
283  return 0;
284  else
285  return 2.0/(1.0 - double(n*n));
286 }
287 
289  double result = 0;
290  double determinant = getBBox().getArea() / 4.0;
291  for (ndarray::Size j=0; j < _coefficients.getSize<0>(); j++){
292  for (ndarray::Size i=0; i < _coefficients.getSize<1>(); i++){
293  result += _coefficients[j][i] * integrateTn(i) * integrateTn(j);
294  }
295  }
296  return result * determinant;
297 }
298 
299 double ChebyshevBoundedField::mean() const { return integrate() / getBBox().getArea(); }
300 
301 // ------------------ persistence ---------------------------------------------------------------------------
302 
303 namespace {
304 
305 struct PersistenceHelper {
306  table::Schema schema;
307  table::Key<int> orderX;
308  table::PointKey<int> bboxMin;
309  table::PointKey<int> bboxMax;
310  table::Key< table::Array<double> > coefficients;
311 
312  PersistenceHelper(int nx, int ny)
313  : schema(),
314  orderX(schema.addField<int>("order_x", "maximum Chebyshev function order in x")),
315  bboxMin(table::PointKey<int>::addFields(schema, "bbox_min", "lower-left corner of bounding box",
316  "pixel")),
317  bboxMax(table::PointKey<int>::addFields(schema, "bbox_max",
318  "upper-right corner of 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  bboxMin(s["bbox_min"]),
326  bboxMax(s["bbox_max"]),
327  coefficients(s["coefficients"]) {}
328 };
329 
330 class ChebyshevBoundedFieldFactory : public table::io::PersistableFactory {
331 public:
332  virtual std::shared_ptr<table::io::Persistable> read(InputArchive const& archive,
333  CatalogVector const& catalogs) const {
334  LSST_ARCHIVE_ASSERT(catalogs.size() == 1u);
335  LSST_ARCHIVE_ASSERT(catalogs.front().size() == 1u);
336  table::BaseRecord const & record = catalogs.front().front();
337  PersistenceHelper const keys(record.getSchema());
338  // NOTE: needed invert=false in case min=-1, max=0 (empty bbox). See RFC-324 and DM-10200
339  geom::Box2I bbox(record.get(keys.bboxMin), record.get(keys.bboxMax), false);
340  int nx = record.get(keys.orderX) + 1;
341  int ny = keys.coefficients.getSize() / nx;
342  LSST_ARCHIVE_ASSERT(nx * ny == keys.coefficients.getSize());
343  ndarray::Array<double,2,2> coefficients = ndarray::allocate(ny, nx);
344  ndarray::flatten<1>(coefficients) = record.get(keys.coefficients);
345  return std::make_shared<ChebyshevBoundedField>(bbox, coefficients);
346  }
347 
348  ChebyshevBoundedFieldFactory(std::string const & name) : afw::table::io::PersistableFactory(name) {}
349 };
350 
351 std::string getChebyshevBoundedFieldPersistenceName() { return "ChebyshevBoundedField"; }
352 
353 ChebyshevBoundedFieldFactory registration(getChebyshevBoundedFieldPersistenceName());
354 
355 } // anonymous
356 
358  return getChebyshevBoundedFieldPersistenceName();
359 }
360 
361 std::string ChebyshevBoundedField::getPythonModule() const { return "lsst.afw.math"; }
362 
364  PersistenceHelper const keys(_coefficients.getSize<1>(), _coefficients.getSize<0>());
365  table::BaseCatalog catalog = handle.makeCatalog(keys.schema);
366  std::shared_ptr<table::BaseRecord> record = catalog.addNew();
367  record->set(keys.orderX, _coefficients.getSize<1>() - 1);
368  record->set(keys.bboxMin, getBBox().getMin());
369  record->set(keys.bboxMax, getBBox().getMax());
370  (*record)[keys.coefficients].deep() = ndarray::flatten<1>(_coefficients);
371  handle.saveCatalog(catalog);
372 }
373 
374 // ------------------ operators -----------------------------------------------------------------------------
375 
376 PTR(BoundedField) ChebyshevBoundedField::operator*(double const scale) const {
377  return std::make_shared<ChebyshevBoundedField>(getBBox(), ndarray::copy(getCoefficients()*scale));
378 }
379 
381  auto rhsCasted = dynamic_cast<ChebyshevBoundedField const *>(&rhs);
382  if (!rhsCasted) return false;
383 
384  return (getBBox() == rhsCasted->getBBox()) &&
385  (_coefficients.getShape() == rhsCasted->_coefficients.getShape()) &&
386  all(equal(_coefficients, rhsCasted->_coefficients));
387 }
388 
389 std::string ChebyshevBoundedField::toString() const {
390  std::ostringstream os;
391  os << "ChebyshevBoundedField (" << _coefficients.getShape() << " coefficients in y,x)";
392  return os.str();
393 }
394 
395 // ------------------ explicit instantiation ----------------------------------------------------------------
396 
397 #ifndef DOXYGEN
398 
399 #define INSTANTIATE(T) \
400  template std::shared_ptr<ChebyshevBoundedField> ChebyshevBoundedField::fit(image::Image<T> const& image, \
401  Control const& ctrl)
402 
403 INSTANTIATE(float);
404 INSTANTIATE(double);
405 
406 #endif
407 }
408 }
409 } // namespace lsst::afw::math
bool all(CoordinateExpr< N > const &expr)
Return true if all elements are true.
virtual double mean() const
Compute the mean of this function over its bounding-box.
An object passed to Persistable::write to allow it to persist itself.
double getHeight() const
Definition: Box.h:354
A custom container class for records, based on std::vector.
Definition: Catalog.h:96
#define LSST_ARCHIVE_ASSERT(EXPR)
An assertion macro used to validate the structure of an InputArchive.
Definition: Persistable.h:47
table::PointKey< int > bboxMin
virtual std::string getPythonModule() const
Return the fully-qualified Python module that should be imported to guarantee that its factory is reg...
static LinearTransform makeScaling(double s)
virtual void write(OutputArchiveHandle &handle) const
Write the object to one or more catalogs.
Solver for linear least-squares problems.
Definition: LeastSquares.h:67
#define INSTANTIATE(TYPE)
geom::Box2I getBBox(ImageOrigin origin=PARENT) const
Definition: Image.h:456
std::shared_ptr< ChebyshevBoundedField > relocate(geom::Box2I const &bbox) const
Return a new ChebyshevBoundedField with domain set to the given bounding box.
table::PointKey< int > bboxMax
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 computeSize() const
Return the number of nonzero coefficients in the Chebyshev function defined by this object...
virtual bool operator==(BoundedField const &rhs) const
BoundedFields (of the same sublcass) are equal if their bounding boxes and parameters are equal...
geom::Box2I getBBox() const
Return the bounding box that defines the region where the field is valid.
Definition: BoundedField.h:112
An integer coordinate rectangle.
Definition: Box.h:55
Use the normal equations with a symmetric Eigensystem decomposition.
Definition: LeastSquares.h:72
virtual double integrate() const
Compute the integral of this function over its bounding-box.
int orderY
&quot;maximum Chebyshev function order in y&quot; ;
double getCenterX() const
Definition: Box.h:368
Point< double, 2 > Point2D
Definition: Point.h:273
double getCenterY() const
Definition: Box.h:369
An affine coordinate transformation consisting of a linear transformation and an offset.
table::Key< std::string > name
Definition: ApCorrMap.cc:71
virtual double evaluate(geom::Point2D const &position) const
Evaluate the field at the given point.
double x
BaseCatalog makeCatalog(Schema const &schema)
Return a new, empty catalog with the given schema.
bool triangular
&quot;if true, only include terms where the sum of the x and y order &quot; &quot;is less than or equal to max(order...
virtual std::string getPersistenceName() const
Return the unique name used to persist this object and look up its factory.
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.
int getArea() const
Definition: Box.h:156
An abstract base class for 2-d functions defined on an integer bounding boxes.
Definition: BoundedField.h:55
ndarray::Array< double const, 1, 1 > getSolution()
Return the vector solution to the least squares problem.
double getWidth() const
Definition: Box.h:353
void saveCatalog(BaseCatalog const &catalog)
Save a catalog in the archive.
A floating-point coordinate rectangle geometry.
Definition: Box.h:266
py::object result
Definition: schema.cc:290
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:486
std::shared_ptr< ChebyshevBoundedField > truncate(Control const &ctrl) const
Return a new ChebyshevBoudedField with maximum orders set by the given control object.
A helper class ChebyshevBoundedField, for mapping trapezoidal matrices to 1-d arrays.
afw::table::Schema schema
Definition: GaussianPsf.cc:43
table::Key< int > orderX
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:463
int orderX
&quot;maximum Chebyshev function order in x&quot; ;