26 #include "ndarray/eigen.h"
58 _toChebyshevRange(makeChebyshevRangeTransform(geom::Box2D(bbox))),
59 _coefficients(coefficients) {}
62 :
BoundedField(bbox), _toChebyshevRange(makeChebyshevRangeTransform(geom::Box2D(bbox))) {}
69 typedef detail::TrapezoidalPacker Packer;
72 void evaluateBasis1d(ndarray::Array<double, 1, 1>
const& t,
double x) {
73 int const n = t.getSize<0>();
80 for (
int i = 2; i <
n; ++i) {
81 t[i] = 2.0*x*t[i-1] - t[i-2];
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);
99 for (
int p = 0; p < nPoints; ++p) {
101 evaluateBasis1d(tx, sxy.getX());
102 evaluateBasis1d(ty, sxy.getY());
103 packer.pack(out[p], tx, ty);
112 ndarray::Array<double, 2, 2> makeMatrix(geom::Box2I
const& bbox,
113 geom::AffineTransform
const& toChebyshevRange, Packer
const& packer,
114 Control
const& ctrl) {
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) {
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) {
130 for (
int j = 0; j < bbox.getWidth(); ++j, ++outIter) {
132 packer.pack(*outIter, tx[j], ty);
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) {
149 Packer
const packer(ctrl);
151 ndarray::Array<double,2,2> matrix = makeMatrix(x, y, result->_toChebyshevRange, packer, ctrl);
155 result->_coefficients = packer.unpack(lstsq.
getSolution());
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) {
169 Packer
const packer(ctrl);
171 ndarray::Array<double,2,2> matrix = makeMatrix(x, y, result->_toChebyshevRange, packer, ctrl);
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>();
180 result->_coefficients = packer.unpack(lstsq.
getSolution());
184 template <
typename T>
186 Control
const& ctrl) {
192 Packer
const packer(ctrl);
193 ndarray::Array<double,2,2> matrix = makeMatrix(bbox, result->_toChebyshevRange, packer, ctrl);
195 ndarray::Array<double,2,2> imgCopy = ndarray::allocate(img.
getArray().getShape());
197 ndarray::Array<double const,1,1> z = ndarray::flatten<1>(imgCopy);
201 result->_coefficients = packer.unpack(lstsq.getSolution());
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>() -
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>() -
221 coefficients.deep() = _coefficients[ndarray::view(0, ctrl.
orderY + 1)(0, ctrl.
orderX + 1)];
224 ndarray::Array<double,1,1> packed = ndarray::allocate(packer.size);
225 packer.pack(packed, coefficients);
226 packer.unpack(coefficients, packed);
232 return std::make_shared<ChebyshevBoundedField>(bbox, _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;
251 return g[0] + x*b_kp1 - b_kp2;
259 struct RecursionArrayImitator {
260 double operator[](
int i)
const {
264 RecursionArrayImitator(ndarray::Array<double const, 2, 2>
const& coefficients_,
double x_)
275 return evaluateFunction1d(RecursionArrayImitator(_coefficients, p.getX()), p.getY(),
276 _coefficients.getSize<0>());
285 return 2.0/(1.0 - double(n*n));
291 for (ndarray::Size j=0; j < _coefficients.getSize<0>(); j++){
292 for (ndarray::Size i=0; i < _coefficients.getSize<1>(); i++){
296 return result * determinant;
305 struct PersistenceHelper {
312 PersistenceHelper(
int nx,
int ny)
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",
318 "upper-right corner of bounding box",
"pixel")),
320 "coefficients",
"Chebyshev function coefficients, ordered by y then x", nx * ny)) {}
322 PersistenceHelper(table::Schema
const& s)
330 class ChebyshevBoundedFieldFactory :
public table::io::PersistableFactory {
332 explicit ChebyshevBoundedFieldFactory(std::string
const&
name)
333 : afw::table::io::PersistableFactory(name) {}
335 virtual std::shared_ptr<table::io::Persistable> read(InputArchive
const& archive,
336 CatalogVector
const& catalogs)
const {
339 table::BaseRecord
const & record = catalogs.front().front();
340 PersistenceHelper
const keys(record.getSchema());
342 geom::Box2I bbox(record.get(keys.bboxMin), record.get(keys.bboxMax),
false);
343 int nx = record.get(keys.orderX) + 1;
344 int ny = keys.coefficients.getSize() / nx;
346 ndarray::Array<double,2,2>
coefficients = ndarray::allocate(ny, nx);
347 ndarray::flatten<1>(
coefficients) = record.get(keys.coefficients);
348 return std::make_shared<ChebyshevBoundedField>(bbox,
coefficients);
352 std::string getChebyshevBoundedFieldPersistenceName() {
return "ChebyshevBoundedField"; }
354 ChebyshevBoundedFieldFactory registration(getChebyshevBoundedFieldPersistenceName());
359 return getChebyshevBoundedFieldPersistenceName();
365 PersistenceHelper
const keys(_coefficients.getSize<1>(), _coefficients.getSize<0>());
367 std::shared_ptr<table::BaseRecord> record = catalog.
addNew();
368 record->set(keys.orderX, _coefficients.getSize<1>() - 1);
369 record->set(keys.bboxMin,
getBBox().getMin());
370 record->set(keys.bboxMax,
getBBox().getMax());
371 (*record)[keys.coefficients].deep() = ndarray::flatten<1>(_coefficients);
383 if (!rhsCasted)
return false;
385 return (
getBBox() == rhsCasted->getBBox()) &&
386 (_coefficients.getShape() == rhsCasted->_coefficients.getShape()) &&
387 all(equal(_coefficients, rhsCasted->_coefficients));
390 std::string ChebyshevBoundedField::toString()
const {
391 std::ostringstream os;
392 os <<
"ChebyshevBoundedField (" << _coefficients.getShape() <<
" coefficients in y,x)";
400 #define INSTANTIATE(T) \
401 template std::shared_ptr<ChebyshevBoundedField> ChebyshevBoundedField::fit(image::Image<T> const& image, \
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.
A custom container class for records, based on std::vector.
#define LSST_ARCHIVE_ASSERT(EXPR)
An assertion macro used to validate the structure of an InputArchive.
table::PointKey< int > bboxMin
double integrateTn(int n)
virtual std::string getPythonModule() const
Return the fully-qualified Python module that should be imported to guarantee that its factory is reg...
virtual void write(OutputArchiveHandle &handle) const
Write the object to one or more catalogs.
Solver for linear least-squares problems.
geom::Box2I getBBox(ImageOrigin origin=PARENT) const
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.
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.
An integer coordinate rectangle.
ndarray::Array< double const, 2, 2 > getCoefficients() const
Return the coefficient matrix.
ChebyshevBoundedFieldControl Control
metadata import lsst afw display as afwDisplay n
Use the normal equations with a symmetric Eigensystem decomposition.
virtual double integrate() const
Compute the integral of this function over its bounding-box.
int orderY
"maximum Chebyshev function order in y" ;
double getCenterX() const
Point< double, 2 > Point2D
double getCenterY() const
table::Key< std::string > name
virtual double evaluate(geom::Point2D const &position) const
Evaluate the field at the given point.
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...
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.
virtual std::shared_ptr< BoundedField > operator*(double const scale) const
Return a scaled BoundedField.
An abstract base class for 2-d functions defined on an integer bounding boxes.
ndarray::Array< double const, 1, 1 > getSolution()
Return the vector solution to the least squares problem.
void saveCatalog(BaseCatalog const &catalog)
Save a catalog in the archive.
A floating-point coordinate rectangle geometry.
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.
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
#define INSTANTIATE(FROMSYS, TOSYS)
std::shared_ptr< RecordT > addNew()
Create a new record, add it to the end of the catalog, and return a pointer to it.
int orderX
"maximum Chebyshev function order in x" ;