lsst.afw  18.1.0-12-g0d73a3591
TransformMap.cc
Go to the documentation of this file.
1 /*
2  * LSST Data Management System
3  * Copyright 2014 LSST Corporation.
4  *
5  * This product includes software developed by the
6  * LSST Project (http://www.lsst.org/).
7  *
8  * This program is free software: you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation, either version 3 of the License, or
11  * (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the LSST License Statement and
19  * the GNU General Public License along with this program. If not,
20  * see <http://www.lsstcorp.org/LegalNotices/>.
21  */
22 
23 #include <exception>
24 #include <memory>
25 #include <sstream>
26 #include <type_traits>
27 #include <set>
28 
29 #include "boost/optional.hpp"
30 
31 #include "lsst/pex/exceptions.h"
37 
38 namespace lsst {
39 namespace afw {
40 namespace cameraGeom {
41 
43  CameraSys const & reference,
44  Transforms const & transforms
45 ) {
46  return Builder(reference).connect(transforms).build();
47 }
48 
49 lsst::afw::geom::Point2Endpoint TransformMap::_pointConverter;
50 
51 // All resources owned by value or by smart pointer
52 TransformMap::~TransformMap() noexcept = default;
53 
55  CameraSys const &toSys) const {
56  auto mapping = _getMapping(fromSys, toSys);
57  return _pointConverter.pointFromData(mapping->applyForward(_pointConverter.dataFromPoint(point)));
58 }
59 
61  CameraSys const &fromSys,
62  CameraSys const &toSys) const {
63  auto mapping = _getMapping(fromSys, toSys);
64  return _pointConverter.arrayFromData(mapping->applyForward(_pointConverter.dataFromArray(pointList)));
65 }
66 
67 bool TransformMap::contains(CameraSys const &system) const noexcept { return _frameIds.count(system) > 0; }
68 
70  CameraSys const &toSys) const {
71  return std::make_shared<geom::TransformPoint2ToPoint2>(*_getMapping(fromSys, toSys));
72 }
73 
74 int TransformMap::_getFrame(CameraSys const &system) const {
75  try {
76  return _frameIds.at(system);
77  } catch (std::out_of_range const &e) {
78  std::ostringstream buffer;
79  buffer << "Unsupported coordinate system: " << system;
81  }
82 }
83 
84 std::shared_ptr<ast::Mapping const> TransformMap::_getMapping(CameraSys const &fromSys,
85  CameraSys const &toSys) const {
86  return _transforms->getMapping(_getFrame(fromSys), _getFrame(toSys));
87 }
88 
89 size_t TransformMap::size() const noexcept { return _frameIds.size(); }
90 
92  CameraSysFrameIdMap && frameIds,
93  std::vector<std::pair<int, int>> && canonicalConnections) :
94  _transforms(std::move(transforms)),
95  _frameIds(std::move(frameIds)),
96  _canonicalConnections(std::move(canonicalConnections))
97 {}
98 
99 
100 namespace {
101 
102 struct PersistenceHelper {
103 
104  static PersistenceHelper const & get() {
105  static PersistenceHelper const instance;
106  return instance;
107  }
108 
109  // Schema and keys for the catalog that stores TransformMap._frameIds.
110  // Considered as a graph, this is a list of all of the vertices with the
111  // integers that identify them in the list of edges below.
112  table::Schema sysSchema;
113  table::Key<std::string> sysName;
114  table::Key<std::string> detectorName;
115  table::Key<int> id;
116 
117  // Schema and keys for the catalog that stores
118  // TransformMap._canonicalConnections entries and the associated Transform
119  // extracted from TransformMap._transforms.
120  // Considered as a graph, 'from' and 'to' identify vertices, and
121  // 'transform' identifies an edge.
122  table::Schema connectionSchema;
123  table::Key<int> from;
124  table::Key<int> to;
125  table::Key<int> transform;
126 
127  CameraSys makeCameraSys(table::BaseRecord const & record) const {
128  return CameraSys(record.get(sysName), record.get(detectorName));
129  }
130 
131 private:
132 
133  PersistenceHelper() :
134  sysSchema(),
135  sysName(sysSchema.addField<std::string>("sysName", "Camera coordinate system name", "", 0)),
136  detectorName(sysSchema.addField<std::string>("detectorName",
137  "Camera coordinate system detector name", "", 0)),
138  id(sysSchema.addField<int>("id", "AST ID of the Frame for the CameraSys", "")),
140  from(connectionSchema.addField<int>("from", "AST ID of the Frame this transform maps from.", "")),
141  to(connectionSchema.addField<int>("to", "AST ID of the Frame this transform maps to.", "")),
142  transform(connectionSchema.addField<int>("transform", "Archive ID of the transform.", ""))
143  {}
144 
145  PersistenceHelper(PersistenceHelper const &) = delete;
146  PersistenceHelper(PersistenceHelper &&) = delete;
147 
148  PersistenceHelper & operator=(PersistenceHelper const &) = delete;
149  PersistenceHelper & operator=(PersistenceHelper &&) = delete;
150 
151 };
152 
153 std::string makeFrameName(CameraSys const & sys) {
154  std::string r = "Ident=" + sys.getSysName();
155  if (sys.hasDetectorName()) {
156  r += "_";
157  r += sys.getDetectorName();
158  }
159  return r;
160 }
161 
162 } // namespace
163 
164 
165 std::string TransformMap::getPersistenceName() const {
166  return "TransformMap";
167 }
168 
169 std::string TransformMap::getPythonModule() const {
170  return "lsst.afw.cameraGeom";
171 }
172 
173 void TransformMap::write(OutputArchiveHandle& handle) const {
174  auto const & keys = PersistenceHelper::get();
175 
176  auto sysCat = handle.makeCatalog(keys.sysSchema);
177  for (auto const & sysPair : _frameIds) {
178  auto sysRecord = sysCat.addNew();
179  sysRecord->set(keys.sysName, sysPair.first.getSysName());
180  sysRecord->set(keys.detectorName, sysPair.first.getDetectorName());
181  sysRecord->set(keys.id, sysPair.second);
182  }
183  sysCat.sort(keys.id);
184  handle.saveCatalog(sysCat);
185 
186  auto connectionCat = handle.makeCatalog(keys.connectionSchema);
187  for (auto const & connectionPair : _canonicalConnections) {
188  auto connectionRecord = connectionCat.addNew();
189  connectionRecord->set(keys.from, connectionPair.first);
190  connectionRecord->set(keys.to, connectionPair.second);
192  *_transforms->getMapping(connectionPair.first, connectionPair.second));
193  connectionRecord->set(keys.transform, handle.put(transform));
194  }
195  handle.saveCatalog(connectionCat);
196 }
197 
199 public:
200 
201  Factory() : PersistableFactory("TransformMap") {}
202 
204  CatalogVector const& catalogs) const override {
205  auto const & keys = PersistenceHelper::get();
206 
207  LSST_ARCHIVE_ASSERT(catalogs.size() == 2u);
208  auto const & sysCat = catalogs[0];
209  auto const & connectionCat = catalogs[1];
210  LSST_ARCHIVE_ASSERT(sysCat.getSchema() == keys.sysSchema);
211  LSST_ARCHIVE_ASSERT(connectionCat.getSchema() == keys.connectionSchema);
212  LSST_ARCHIVE_ASSERT(sysCat.size() == connectionCat.size() + 1);
213  LSST_ARCHIVE_ASSERT(sysCat.isSorted(keys.id));
214 
215  CameraSysFrameIdMap frameIdsBySys;
217  for (auto const & sysRecord : sysCat) {
218  auto sys = keys.makeCameraSys(sysRecord);
219  frameIdsBySys.emplace(sys, sysRecord.get(keys.id));
220  framesById.emplace(sysRecord.get(keys.id), ast::Frame(2, makeFrameName(sys)));
221  }
222 
223  auto baseFrameIter = framesById.find(1);
224  LSST_ARCHIVE_ASSERT(baseFrameIter != framesById.end());
225  auto frameSet = std::make_unique<ast::FrameSet>(baseFrameIter->second);
226  std::vector<std::pair<int, int>> canonicalConnections;
227  for (auto const & connectionRecord : connectionCat) {
228  int const fromId = connectionRecord.get(keys.from);
229  int const toId = connectionRecord.get(keys.to);
230  auto const transform = archive.get<geom::TransformPoint2ToPoint2>(
231  connectionRecord.get(keys.transform)
232  );
233  canonicalConnections.emplace_back(fromId, toId);
234  auto toFrameIter = framesById.find(toId);
235  LSST_ARCHIVE_ASSERT(toFrameIter != framesById.end());
236  frameSet->addFrame(fromId, *transform->getMapping(), toFrameIter->second);
237  }
238 
240  std::move(frameIdsBySys),
241  std::move(canonicalConnections)));
242  }
243 
244 };
245 
246 TransformMap::Factory const TransformMap::registration;
247 
248 
249 TransformMap::Builder::Builder(CameraSys const & reference) : _reference(reference) {}
250 
251 TransformMap::Builder::Builder(Builder const &) = default;
253 
256 
257 TransformMap::Builder::~Builder() noexcept = default;
258 
260  CameraSys const & fromSys,
261  CameraSys const & toSys,
263 ) {
264  if (fromSys == toSys) {
265  std::ostringstream buffer;
266  buffer << "Identity connection detected for " << fromSys << ".";
268  }
269  if (!transform->hasForward()) {
270  std::ostringstream buffer;
271  buffer << "Connection from " << fromSys << " to "
272  << toSys << " has no forward transform.";
274  }
275  if (!transform->hasInverse()) {
276  std::ostringstream buffer;
277  buffer << "Connection from " << fromSys << " to "
278  << toSys << " has no inverse transform.";
280  }
281  _connections.push_back(Connection{false, std::move(transform), fromSys, toSys});
282  return *this;
283 }
284 
285 
287  CameraSys const & fromSys,
288  Transforms const & transforms
289 ) {
290  Builder other(_reference); // temporary for strong exception safety
291  for (auto const & item : transforms) {
292  other.connect(fromSys, item.first, item.second);
293  }
294  _connections.insert(_connections.end(), other._connections.begin(), other._connections.end());
295  return *this;
296 }
297 
298 
299 namespace {
300 
301 /*
302  * RAII object that just executes a functor in its destructor.
303  */
304 template <typename Callable>
305 class OnScopeExit {
306 public:
307 
308  explicit OnScopeExit(Callable callable) : _callable(std::move(callable)) {}
309 
310  ~OnScopeExit() noexcept(noexcept(std::declval<Callable>())) { // noexcept iff "_callable()"" is
311  _callable();
312  }
313 
314 private:
315  Callable _callable;
316 };
317 
318 // Factory function for OnScopeExit.
319 template <typename Callable>
320 OnScopeExit<Callable> onScopeExit(Callable callable) {
321  return OnScopeExit<Callable>(std::move(callable));
322 }
323 
324 } // namespace
325 
326 
328 
329  int nFrames = 0; // tracks frameSet->getNFrame() to avoid those (expensive) calls
330  CameraSysFrameIdMap frameIds; // mapping from CameraSys to Frame ID (int)
331  std::vector<std::pair<int, int>> canonicalConnections; // remembers the frame IDs we've connected
332 
333  // Local helper function that looks up the Frame ID for a CameraSys, with
334  // results returned via boost::optional.
335  auto findFrameIdForSys = [&frameIds](CameraSys const & sys) -> boost::optional<int> {
336  auto iter = frameIds.find(sys);
337  if (iter != frameIds.end()) {
338  return boost::optional<int>(iter->second);
339  } else {
340  return boost::none;
341  }
342  };
343 
344  // Local helper function that creates a Frame, updates the nFrames counter,
345  // and adds an entry to the frameIds map. Returns the new Frame.
346  // Should always be called in concert with an update to frameSet.
347  auto addFrameForSys = [&frameIds, &nFrames](CameraSys const & sys) mutable -> ast::Frame {
348  frameIds.emplace(sys, ++nFrames);
349  return ast::Frame(2, makeFrameName(sys));
350  };
351 
352  // FrameSet that manages all transforms; should always be updated in
353  // concert with a call to addFrameForSys.
354  auto frameSet = std::make_unique<ast::FrameSet>(addFrameForSys(_reference));
355 
356  // RAII: make sure all 'processed' fields are reset, no matter how we exit
357  auto guard = onScopeExit(
358  [this]() noexcept {
359  for (auto const & c : _connections) { c.processed = false; }
360  }
361  );
362 
363  std::size_t nProcessedTotal = 0;
364  while (nProcessedTotal != _connections.size()) {
365 
366  // Loop over all connections, only inserting those that are connected
367  // to already-inserted connections.
368  std::size_t nProcessedThisPass = 0;
369  for (auto const & c : _connections) {
370  if (c.processed) continue;
371  auto fromId = findFrameIdForSys(c.fromSys);
372  auto toId = findFrameIdForSys(c.toSys);
373  if (fromId && toId) { // We've already inserted both fromSys and toSys. That's a problem.
374  std::ostringstream buffer;
375  buffer << "Duplicate connection from " << c.fromSys << " to " << c.toSys << ".";
377  } else if (fromId) { // We've already inserted fromSys (only)
378  frameSet->addFrame(*fromId, *c.transform->getMapping(), addFrameForSys(c.toSys));
379  canonicalConnections.emplace_back(*fromId, nFrames);
380  c.processed = true;
381  ++nProcessedThisPass;
382  } else if (toId) { // We've already inserted toSys (only)
383  frameSet->addFrame(*toId, *c.transform->inverted()->getMapping(), addFrameForSys(c.fromSys));
384  canonicalConnections.emplace_back(*toId, nFrames);
385  c.processed = true;
386  ++nProcessedThisPass;
387  }
388  // If we haven't inserted either yet, just continue; hopefully
389  // we'll have inserted one in a future pass.
390  }
391 
392  if (nProcessedThisPass == 0u) { // We're not making progress, so we must have orphans
393  // Use std::set to compile the list of orphaned coordinate systems
394  // for a friendlier (unique, predictably-ordered) error message.
395  std::set<CameraSys> orphaned;
396  for (auto const & c : _connections) {
397  if (!c.processed) {
398  orphaned.insert(c.fromSys);
399  orphaned.insert(c.toSys);
400  }
401  }
402  std::ostringstream buffer;
403  auto o = orphaned.begin();
404  buffer << "Orphaned coordinate system(s) found: " << *o;
405  for (++o; o != orphaned.end(); ++o) {
406  buffer << ", " << *o;
407  }
408  buffer << ".";
410  }
411 
412  nProcessedTotal += nProcessedThisPass;
413  }
414 
415  // We've maintained our own counter for frame IDs for performance and
416  // convenience reasons, but it had better match AST's internal counter.
417  assert(frameSet->getNFrame() == nFrames);
418 
419  // Return the new TransformMap.
420  // We can't use make_shared because TransformMap ctor is private.
422  std::move(frameIds),
423  std::move(canonicalConnections)));
424 }
425 
426 } // namespace cameraGeom
427 
428 namespace table {
429 namespace io {
430 
431 template class PersistableFacade<cameraGeom::TransformMap>;
432 
433 } // namespace io
434 } // namespace table
435 
436 } // namespace afw
437 } // namespace lsst
Camera coordinate system; used as a key in in TransformMap.
Definition: CameraSys.h:83
def keys(self)
#define LSST_ARCHIVE_ASSERT(EXPR)
An assertion macro used to validate the structure of an InputArchive.
Definition: Persistable.h:48
A base class for factory classes used to reconstruct objects from records.
Definition: Persistable.h:228
Point pointFromData(std::vector< double > const &data) const override
Get a single point from raw data.
Definition: Endpoint.cc:138
table::Key< int > to
T end(T... args)
ItemVariant const * other
Definition: Schema.cc:56
lsst::geom::Point2D transform(lsst::geom::Point2D const &point, CameraSys const &fromSys, CameraSys const &toSys) const
Convert a point from one camera coordinate system to another.
Definition: TransformMap.cc:54
table::Schema connectionSchema
table::Key< int > id
Transform< Point2Endpoint, Point2Endpoint > TransformPoint2ToPoint2
Definition: Transform.h:300
STL class.
Helper class used to incrementally construct TransformMap instances.
Definition: TransformMap.h:239
T at(T... args)
Array arrayFromData(ndarray::Array< double, 2, 2 > const &data) const override
Get an array of points from raw data.
Definition: Endpoint.cc:148
TransformMap & operator=(TransformMap const &)=delete
T push_back(T... args)
std::shared_ptr< TransformMap const > build() const
Construct a TransformMap from the connections in the builder.
table::Key< std::string > sysName
A base class for image defects.
table::Key< table::Array< std::uint8_t > > frameSet
T throw_with_nested(T... args)
Builder(CameraSys const &reference)
Construct an empty builder with no transforms and only the given coordinate system.
T str(T... args)
bool contains(CameraSys const &system) const noexcept
Can this transform to and from the specified coordinate system?
Definition: TransformMap.cc:67
T move(T... args)
std::vector< double > dataFromPoint(Point const &point) const override
Definition: Endpoint.cc:115
T count(T... args)
T insert(T... args)
static std::shared_ptr< TransformMap const > make(CameraSys const &reference, Transforms const &transforms)
Construct a TransformMap with all transforms relative to a single reference CameraSys.
Definition: TransformMap.cc:42
T find(T... args)
T size(T... args)
TransformMap(TransformMap const &other)=delete
STL class.
#define LSST_EXCEPT(type,...)
A vector of catalogs used by Persistable.
Definition: CatalogVector.h:29
STL class.
STL class.
T begin(T... args)
std::shared_ptr< Persistable > read(InputArchive const &archive, CatalogVector const &catalogs) const override
Construct a new object from the given InputArchive and vector of catalogs.
table::Key< int > from
size_t size() const noexcept
Get the number of supported coordinate systems.
Definition: TransformMap.cc:89
T emplace(T... args)
Builder & connect(CameraSys const &fromSys, CameraSys const &toSys, std::shared_ptr< geom::TransformPoint2ToPoint2 const > transform)
Add a new coordinate system to the builder.
io::OutputArchiveHandle OutputArchiveHandle
Definition: Persistable.h:108
An endpoint for lsst::geom::Point2D.
Definition: Endpoint.h:261
A multi-catalog archive object used to load table::io::Persistable objects.
Definition: InputArchive.h:31
table::Key< std::string > detectorName
std::shared_ptr< Mapping > getMapping(int from=BASE, int to=CURRENT) const
Transform LSST spatial data, such as lsst::geom::Point2D and lsst::geom::SpherePoint, using an AST mapping.
Definition: Transform.h:67
ndarray::Array< double, 2, 2 > dataFromArray(Array const &arr) const override
Definition: Endpoint.cc:124
std::shared_ptr< Persistable > get(int id) const
Load the Persistable with the given ID and return it.
table::Schema sysSchema
std::shared_ptr< geom::TransformPoint2ToPoint2 > getTransform(CameraSys const &fromSys, CameraSys const &toSys) const
Get a Transform from one camera coordinate system to another.
Definition: TransformMap.cc:69
T emplace_back(T... args)