lsst.afw  14.0-23-g38c323faa+3
TransformBoundedField.cc
Go to the documentation of this file.
1 // -*- LSST-C++ -*-
2 /*
3  * LSST Data Management System
4  * Copyright 2017 AURA/LSST.
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 <cstdint>
25 #include <memory>
26 #include <string>
27 
28 #include "ndarray/eigen.h"
29 #include "astshim.h"
36 
37 namespace lsst {
38 namespace afw {
39 namespace math {
40 
42  : BoundedField(bbox), _transform(transform) {
43  if (transform.getToEndpoint().getNAxes() != 1) {
45  "To EndPoint of transform must have 1 axis but has " +
46  std::to_string(transform.getToEndpoint().getNAxes()));
47  }
48 }
49 
50 double TransformBoundedField::evaluate(geom::Point2D const& position) const {
51  return _transform.applyForward(position)[0];
52 }
53 
54 ndarray::Array<double, 1, 1> TransformBoundedField::evaluate(ndarray::Array<double const, 1> const& x,
55  ndarray::Array<double const, 1> const& y) const {
56  if (x.getSize<0>() != y.getSize<0>()) {
58  "x length " + std::to_string(x.getSize<0>()) + "!= y length " +
59  std::to_string(x.getSize<0>()));
60  }
61 
62  // TODO if Mapping.applyForward gains support for x, y (DM-11226) then use that instead of copying data
63  int const nPoints = x.getSize<0>();
64  ndarray::Array<double, 2, 2> xy = ndarray::allocate(ndarray::makeVector(2, nPoints));
65  for (int col = 0; col < nPoints; ++col) {
66  xy[0][col] = x[col];
67  xy[1][col] = y[col];
68  }
69 
70  auto res2D = _transform.getFrameSet()->applyForward(xy);
71 
72  // res2D has shape 1 x N; return a 1-D view with the extra dimension stripped
73  auto resShape = ndarray::makeVector(nPoints);
74  auto resStrides = ndarray::makeVector(1);
75  return ndarray::external(res2D.getData(), resShape, resStrides, res2D);
76 }
77 
78 // ------------------ persistence ---------------------------------------------------------------------------
79 
80 namespace {
81 
82 struct PersistenceHelper {
83  table::Schema schema;
84  table::PointKey<int> bboxMin;
85  table::PointKey<int> bboxMax;
86  // store the FrameSet as string encoded as a variable-length vector of bytes
87  table::Key<table::Array<std::uint8_t>> frameSet;
88 
89  PersistenceHelper()
90  : schema(),
91  bboxMin(table::PointKey<int>::addFields(schema, "bbox_min", "lower-left corner of bounding box",
92  "pixel")),
93  bboxMax(table::PointKey<int>::addFields(schema, "bbox_max",
94  "upper-right corner of bounding box", "pixel")),
95  frameSet(schema.addField<table::Array<std::uint8_t>>(
96  "frameSet", "FrameSet contained in the Transform", "", 0)) {}
97 
98  PersistenceHelper(table::Schema const& s)
99  : schema(s), bboxMin(s["bbox_min"]), bboxMax(s["bbox_max"]), frameSet(s["frameSet"]) {}
100 };
101 
102 class TransformBoundedFieldFactory : public table::io::PersistableFactory {
103 public:
104  explicit TransformBoundedFieldFactory(std::string const& name)
105  : afw::table::io::PersistableFactory(name) {}
106 
107  std::shared_ptr<table::io::Persistable> read(InputArchive const& archive,
108  CatalogVector const& catalogs) const override {
109  LSST_ARCHIVE_ASSERT(catalogs.size() == 1u);
110  LSST_ARCHIVE_ASSERT(catalogs.front().size() == 1u);
111  table::BaseRecord const& record = catalogs.front().front();
112  PersistenceHelper const keys(record.getSchema());
113  // NOTE: needed invert=false in case min=-1, max=0 (empty bbox). See RFC-324 and DM-10200
114  geom::Box2I bbox(record.get(keys.bboxMin), record.get(keys.bboxMax), false);
115  auto frameSetStr = formatters::bytesToString(record.get(keys.frameSet));
116  auto transform =
118  return std::make_shared<TransformBoundedField>(bbox, transform);
119  }
120 };
121 
122 std::string getTransformBoundedFieldPersistenceName() { return "TransformBoundedField"; }
123 
124 TransformBoundedFieldFactory registration(getTransformBoundedFieldPersistenceName());
125 
126 } // namespace
127 
129  return getTransformBoundedFieldPersistenceName();
130 }
131 
132 std::string TransformBoundedField::getPythonModule() const { return "lsst.afw.math"; }
133 
135  PersistenceHelper const keys;
136  table::BaseCatalog catalog = handle.makeCatalog(keys.schema);
137  std::shared_ptr<table::BaseRecord> record = catalog.addNew();
138  record->set(keys.bboxMin, getBBox().getMin());
139  record->set(keys.bboxMax, getBBox().getMax());
140  record->set(keys.frameSet, formatters::stringToBytes(getTransform().writeString()));
141  handle.saveCatalog(catalog);
142 }
143 
145  auto zoomMap = ast::ZoomMap(1, scale);
146  auto newMapping = getTransform().getFrameSet()->then(zoomMap);
147  auto newTransform = Transform(newMapping);
148  return std::make_shared<TransformBoundedField>(getBBox(), newTransform);
149 }
150 
152  auto rhsCasted = dynamic_cast<TransformBoundedField const*>(&rhs);
153  if (!rhsCasted) return false;
154 
155  return getBBox() == rhsCasted->getBBox() &&
156  *(getTransform().getFrameSet()) == *(rhsCasted->getTransform().getFrameSet());
157 }
158 
159 std::string TransformBoundedField::toString() const {
161  os << "TransformBoundedField (containing " << _transform.getFrameSet()->getNFrame() << " frames)";
162  return os.str();
163 }
164 
165 } // namespace math
166 } // namespace afw
167 } // namespace lsst
ToEndpoint getToEndpoint() const
Get the "to" endpoint.
Definition: Transform.h:139
table::PointKey< int > bboxMax
table::Key< std::string > name
Definition: ApCorrMap.cc:71
std::string getPersistenceName() const override
Return the unique name used to persist this object and look up its factory.
An object passed to Persistable::write to allow it to persist itself.
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
std::shared_ptr< const ast::FrameSet > getFrameSet() const
Get the contained frameset.
Definition: Transform.h:134
Transform getTransform() const
Get the contained Transform.
def scale(algorithm, min, max=None, frame=None)
Definition: ds9.py:117
T to_string(T... args)
STL namespace.
TransformBoundedField(geom::Box2I const &bbox, Transform const &transform)
Create a TransformBoundedField from a bounding box and transform.
A BoundedField based on geom::Transform<Poin2Endpoint, GenericEndpoint<1>>.
std::string bytesToString(ndarray::Array< std::uint8_t const, 1, 1 > const &bytes)
Decode a std::string from a vector of uint8 returned by stringToBytes.
Definition: Utils.cc:301
An integer coordinate rectangle.
Definition: Box.h:55
ToPoint applyForward(FromPoint const &point) const
Transform one point in the forward direction ("from" to "to")
STL class.
std::shared_ptr< BoundedField > operator*(double const scale) const override
Return a scaled BoundedField.
geom::Box2I getBBox() const
Return the bounding box that defines the region where the field is valid.
Definition: BoundedField.h:112
table::PointKey< int > bboxMin
bool operator==(BoundedField const &rhs) const override
BoundedFields (of the same sublcass) are equal if their bounding boxes and parameters are equal...
A base class for image defects.
geom::Transform< geom::Point2Endpoint, geom::GenericEndpoint > Transform
table::Key< table::Array< std::uint8_t > > frameSet
T str(T... args)
double x
void write(OutputArchiveHandle &handle) const override
Write the object to one or more catalogs.
BaseCatalog makeCatalog(Schema const &schema)
Return a new, empty catalog with the given schema.
std::string getPythonModule() const override
Return the fully-qualified Python module that should be imported to guarantee that its factory is reg...
#define LSST_EXCEPT(type,...)
static Transform< FromEndpoint, ToEndpoint > readString(std::string &str)
Deserialize a Transform of this type from a string, using the same format as readStream.
An abstract base class for 2-d functions defined on an integer bounding boxes.
Definition: BoundedField.h:55
void saveCatalog(BaseCatalog const &catalog)
Save a catalog in the archive.
ndarray::Array< std::uint8_t, 1, 1 > stringToBytes(std::string const &str)
Encode a std::string as a vector of uint8.
Definition: Utils.cc:290
table::Schema schema
double evaluate(geom::Point2D const &position) const override
Evaluate the field at the given point.
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