lsst.afw  15.0-24-g02ed2a30c+2
Match.cc
Go to the documentation of this file.
1 // -*- lsst-c++ -*-
2 
3 /*
4  * LSST Data Management System
5  * Copyright 2008, 2009, 2010, 2016 LSST Corporation.
6  *
7  * This product includes software developed by the
8  * LSST Project (http://www.lsst.org/).
9  *
10  * This program is free software: you can redistribute it and/or modify
11  * it under the terms of the GNU General Public License as published by
12  * the Free Software Foundation, either version 3 of the License, or
13  * (at your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18  * GNU General Public License for more details.
19  *
20  * You should have received a copy of the LSST License Statement and
21  * the GNU General Public License along with this program. If not,
22  * see <http://www.lsstcorp.org/LegalNotices/>.
23  */
24 
25 #include <algorithm>
26 #include <cmath>
27 #include <memory>
28 
29 #include "lsst/pex/exceptions.h"
30 #include "lsst/log/Log.h"
31 #include "lsst/afw/table/Match.h"
32 #include "lsst/afw/geom/Angle.h"
33 
34 namespace lsst {
35 namespace afw {
36 namespace table {
37 namespace {
38 
39 template <typename RecordT>
40 struct RecordPos {
41  double dec;
42  double x;
43  double y;
44  double z;
45  // JFB removed extra pointer here; this may have performance implications, but hopefully not
46  // significant ones. BaseCatalog iterators yield temporary BaseRecord shared_ptrs, so storing
47  // their address was no longer an option.
49 };
50 
51 template <typename Record1, typename Record2>
52 bool operator<(RecordPos<Record1> const &s1, RecordPos<Record2> const &s2) {
53  return (s1.dec < s2.dec);
54 }
55 
56 struct CmpRecordPtr {
57  bool operator()(std::shared_ptr<SourceRecord> const s1, std::shared_ptr<SourceRecord> const s2) {
58  return s1->getY() < s2->getY();
59  }
60 };
61 
72 template <typename Cat>
73 size_t makeRecordPositions(Cat const &cat, RecordPos<typename Cat::Record> *positions) {
74  size_t n = 0;
75  Key<Angle> raKey = Cat::Table::getCoordKey().getRa();
76  Key<Angle> decKey = Cat::Table::getCoordKey().getDec();
77  for (typename Cat::const_iterator i(cat.begin()), e(cat.end()); i != e; ++i) {
78  geom::Angle ra = i->get(raKey);
79  geom::Angle dec = i->get(decKey);
80  if (std::isnan(ra.asRadians()) || std::isnan(dec.asRadians())) {
81  continue;
82  }
83  double cosDec = std::cos(dec);
84  positions[n].dec = dec.asRadians();
85  positions[n].x = std::cos(ra) * cosDec;
86  positions[n].y = std::sin(ra) * cosDec;
87  positions[n].z = std::sin(dec);
88  positions[n].src = i;
89  ++n;
90  }
91  std::sort(positions, positions + n);
92  if (n < cat.size()) {
93  LOGLS_WARN("afw.table.matchRaDec", "At least one source had ra or dec equal to NaN");
94  }
95  return n;
96 }
97 
98 template size_t makeRecordPositions(SimpleCatalog const &, RecordPos<SimpleRecord> *);
99 template size_t makeRecordPositions(SourceCatalog const &, RecordPos<SourceRecord> *);
100 
101 template <typename Cat1, typename Cat2>
102 bool doSelfMatchIfSame(std::vector<Match<typename Cat1::Record, typename Cat2::Record> > &result,
103  Cat1 const &cat1, Cat2 const &cat2, Angle radius) {
104  // types are different, so the catalogs are never the same.
105  return false;
106 }
107 
108 template <typename Cat>
109 bool doSelfMatchIfSame(std::vector<Match<typename Cat::Record, typename Cat::Record> > &result,
110  Cat const &cat1, Cat const &cat2, Angle radius) {
111  if (&cat1 == &cat2) {
112  result = matchRaDec(cat1, radius);
113  return true;
114  }
115  return false;
116 }
117 
126 double toUnitSphereDistanceSquared(afw::geom::Angle theta) noexcept {
127  return 2. * (1. - std::cos(theta.asRadians()));
128  // == 4.0 * pow(std::sin(0.5 * theta.asRadians()), 2.0)
129 }
130 
139 Angle fromUnitSphereDistanceSquared(double d2) noexcept {
140  // acos(1 - 0.5*d2) doesn't require sqrt but isn't as precise for small d2
141  return 2.0*std::asin(0.5*std::sqrt(d2))*afw::geom::radians;
142 }
143 
144 } // anonymous
145 
146 template <typename Cat1, typename Cat2>
148  Cat2 const &cat2, Angle radius,
149  bool closest) {
150  MatchControl mc;
151  mc.findOnlyClosest = closest;
152 
153  return matchRaDec(cat1, cat2, radius, mc);
154 }
155 
156 template <typename Cat1, typename Cat2>
158  Cat2 const &cat2, Angle radius,
159  MatchControl const &mc) {
161  std::vector<MatchT> matches;
162 
163  if (doSelfMatchIfSame(matches, cat1, cat2, radius)) return matches;
164 
165  if (radius < 0.0 || (radius > (45. * geom::degrees))) {
166  throw LSST_EXCEPT(pex::exceptions::RangeError, "match radius out of range (0 to 45 degrees)");
167  }
168  if (cat1.size() == 0 || cat2.size() == 0) {
169  return matches;
170  }
171  // setup match parameters
172  double const d2Limit = toUnitSphereDistanceSquared(radius);
173 
174  // Build position lists
175  size_t len1 = cat1.size();
176  size_t len2 = cat2.size();
177 
178  typedef RecordPos<typename Cat1::Record> Pos1;
179  typedef RecordPos<typename Cat2::Record> Pos2;
180  std::unique_ptr<Pos1[]> pos1(new Pos1[len1]);
181  std::unique_ptr<Pos2[]> pos2(new Pos2[len2]);
182  len1 = makeRecordPositions(cat1, pos1.get());
183  len2 = makeRecordPositions(cat2, pos2.get());
185 
186  for (size_t i = 0, start = 0; i < len1; ++i) {
187  double minDec = pos1[i].dec - radius.asRadians();
188  while (start < len2 && pos2[start].dec < minDec) {
189  ++start;
190  }
191  if (start == len2) {
192  break;
193  }
194  double maxDec = pos1[i].dec + radius.asRadians();
195  size_t closestIndex = -1; // Index of closest match (if any)
196  double d2Include = d2Limit; // Squared distance for inclusion of match
197  bool found = false; // Found anything?
198  size_t nMatches = 0; // Number of matches
199  for (size_t j = start; j < len2 && pos2[j].dec <= maxDec; ++j) {
200  double dx = pos1[i].x - pos2[j].x;
201  double dy = pos1[i].y - pos2[j].y;
202  double dz = pos1[i].z - pos2[j].z;
203  double d2 = dx * dx + dy * dy + dz * dz;
204  if (d2 < d2Include) {
205  if (mc.findOnlyClosest) {
206  d2Include = d2;
207  closestIndex = j;
208  found = true;
209  } else {
210  matches.push_back(MatchT(pos1[i].src, pos2[j].src, fromUnitSphereDistanceSquared(d2)));
211  }
212  ++nMatches;
213  }
214  }
215  if (mc.includeMismatches && nMatches == 0) {
216  matches.push_back(MatchT(pos1[i].src, nullRecord, NAN));
217  }
218  if (mc.findOnlyClosest && found) {
219  matches.push_back(
220  MatchT(pos1[i].src, pos2[closestIndex].src, fromUnitSphereDistanceSquared(d2Include)));
221  }
222  }
223  return matches;
224 }
225 
226 #define LSST_MATCH_RADEC(RTYPE, C1, C2) \
227  template RTYPE matchRaDec(C1 const &, C2 const &, Angle, bool); \
228  template RTYPE matchRaDec(C1 const &, C2 const &, Angle, MatchControl const &)
229 
233 
234 #undef LSST_MATCH_RADEC
235 
236 template <typename Cat>
238  bool symmetric) {
239  MatchControl mc;
240  mc.symmetricMatch = symmetric;
241 
242  return matchRaDec(cat, radius, mc);
243 }
244 
245 template <typename Cat>
247  MatchControl const &mc) {
249  std::vector<MatchT> matches;
250 
251  if (radius < 0.0 || radius > (45.0 * geom::degrees)) {
252  throw LSST_EXCEPT(pex::exceptions::RangeError, "match radius out of range (0 to 45 degrees)");
253  }
254  if (cat.size() == 0) {
255  return matches;
256  }
257  // setup match parameters
258  double const d2Limit = toUnitSphereDistanceSquared(radius);
259 
260  // Build position list
261  size_t len = cat.size();
262  typedef RecordPos<typename Cat::Record> Pos;
263  std::unique_ptr<Pos[]> pos(new Pos[len]);
264  len = makeRecordPositions(cat, pos.get());
265 
266  for (size_t i = 0; i < len; ++i) {
267  double maxDec = pos[i].dec + radius.asRadians();
268  for (size_t j = i + 1; j < len && pos[j].dec <= maxDec; ++j) {
269  double dx = pos[i].x - pos[j].x;
270  double dy = pos[i].y - pos[j].y;
271  double dz = pos[i].z - pos[j].z;
272  double d2 = dx * dx + dy * dy + dz * dz;
273  if (d2 < d2Limit) {
274  Angle d = fromUnitSphereDistanceSquared(d2);
275  matches.push_back(MatchT(pos[i].src, pos[j].src, d));
276  if (mc.symmetricMatch) {
277  matches.push_back(MatchT(pos[j].src, pos[i].src, d));
278  }
279  }
280  }
281  }
282  return matches;
283 }
284 
285 #define LSST_MATCH_RADEC(RTYPE, C) \
286  template RTYPE matchRaDec(C const &, Angle, bool); \
287  template RTYPE matchRaDec(C const &, Angle, MatchControl const &)
288 
291 
292 #undef LSST_MATCH_RADEC
293 
294 SourceMatchVector matchXy(SourceCatalog const &cat1, SourceCatalog const &cat2, double radius, bool closest) {
295  MatchControl mc;
296  mc.findOnlyClosest = closest;
297 
298  return matchXy(cat1, cat2, radius, mc);
299 }
300 
301 SourceMatchVector matchXy(SourceCatalog const &cat1, SourceCatalog const &cat2, double radius,
302  MatchControl const &mc) {
303  if (&cat1 == &cat2) {
304  return matchXy(cat1, radius);
305  }
306  // setup match parameters
307  double const r2 = radius * radius;
308 
309  // copy and sort array of pointers on y
310  size_t len1 = cat1.size();
311  size_t len2 = cat2.size();
315  size_t n = 0;
316  for (SourceCatalog::const_iterator i(cat1.begin()), e(cat1.end()); i != e; ++i) {
317  if (std::isnan(i->getX()) || std::isnan(i->getY())) {
318  continue;
319  }
320  pos1[n] = i;
321  ++n;
322  }
323  len1 = n;
324  n = 0;
325  for (SourceCatalog::const_iterator i(cat2.begin()), e(cat2.end()); i != e; ++i) {
326  if (std::isnan(i->getX()) || std::isnan(i->getY())) {
327  continue;
328  }
329  pos2[n] = i;
330  ++n;
331  }
332  len2 = n;
333 
334  std::sort(pos1.get(), pos1.get() + len1, CmpRecordPtr());
335  std::sort(pos2.get(), pos2.get() + len2, CmpRecordPtr());
336 
337  SourceMatchVector matches;
338  for (size_t i = 0, start = 0; i < len1; ++i) {
339  double y = pos1[i]->getY();
340  double minY = y - radius;
341  while (start < len2 && pos2[start]->getY() < minY) {
342  ++start;
343  }
344  if (start == len2) {
345  break;
346  }
347  double x = pos1[i]->getX();
348  double maxY = y + radius;
349  double y2;
350  size_t closestIndex = -1; // Index of closest match (if any)
351  double r2Include = r2; // Squared radius for inclusion of match
352  bool found = false; // Found anything?
353  size_t nMatches = 0; // Number of matches
354  for (size_t j = start; j < len2 && (y2 = pos2[j]->getY()) <= maxY; ++j) {
355  double dx = x - pos2[j]->getX();
356  double dy = y - y2;
357  double d2 = dx * dx + dy * dy;
358  if (d2 < r2Include) {
359  if (mc.findOnlyClosest) {
360  r2Include = d2;
361  closestIndex = j;
362  found = true;
363  } else {
364  matches.push_back(SourceMatch(pos1[i], pos2[j], std::sqrt(d2)));
365  }
366  ++nMatches;
367  }
368  }
369  if (mc.includeMismatches && nMatches == 0) {
370  matches.push_back(SourceMatch(pos1[i], nullRecord, NAN));
371  }
372  if (mc.findOnlyClosest && found) {
373  matches.push_back(SourceMatch(pos1[i], pos2[closestIndex], std::sqrt(r2Include)));
374  }
375  }
376  return matches;
377 }
378 
379 SourceMatchVector matchXy(SourceCatalog const &cat, double radius, bool symmetric) {
380  MatchControl mc;
381  mc.symmetricMatch = symmetric;
382 
383  return matchXy(cat, radius, mc);
384 }
385 
386 SourceMatchVector matchXy(SourceCatalog const &cat, double radius, MatchControl const &mc) {
387  // setup match parameters
388  double const r2 = radius * radius;
389 
390  // copy and sort array of pointers on y
391  size_t len = cat.size();
393  size_t n = 0;
394  for (SourceCatalog::const_iterator i(cat.begin()), e(cat.end()); i != e; ++i) {
395  if (std::isnan(i->getX()) || std::isnan(i->getY())) {
396  continue;
397  }
398  pos[n] = i;
399  ++n;
400  }
401  len = n;
402 
403  std::sort(pos.get(), pos.get() + len, CmpRecordPtr());
404 
405  SourceMatchVector matches;
406  for (size_t i = 0; i < len; ++i) {
407  double x = pos[i]->getX();
408  double y = pos[i]->getY();
409  double maxY = y + radius;
410  double y2;
411  for (size_t j = i + 1; j < len && (y2 = pos[j]->getY()) <= maxY; ++j) {
412  double dx = x - pos[j]->getX();
413  double dy = y - y2;
414  double d2 = dx * dx + dy * dy;
415  if (d2 < r2) {
416  double d = std::sqrt(d2);
417  matches.push_back(SourceMatch(pos[i], pos[j], d));
418  if (mc.symmetricMatch) {
419  matches.push_back(SourceMatch(pos[j], pos[i], d));
420  }
421  }
422  }
423  }
424  return matches;
425 }
426 
427 template <typename Record1, typename Record2>
429  Schema schema;
430  Key<RecordId> outKey1 = schema.addField<RecordId>("first", "ID for first source record in match.");
431  Key<RecordId> outKey2 = schema.addField<RecordId>("second", "ID for second source record in match.");
432  Key<double> keyD = schema.addField<double>("distance", "Distance between matches sources.");
433  BaseCatalog result(schema);
434  result.getTable()->preallocate(matches.size());
435  result.reserve(matches.size());
436  typedef typename std::vector<Match<Record1, Record2> >::const_iterator Iter;
437  for (Iter i = matches.begin(); i != matches.end(); ++i) {
438  std::shared_ptr<BaseRecord> record = result.addNew();
439  record->set(outKey1, i->first->getId());
440  record->set(outKey2, i->second->getId());
441  record->set(keyD, i->distance);
442  }
443  return result;
444 }
445 
446 template BaseCatalog packMatches(SimpleMatchVector const &);
448 template BaseCatalog packMatches(SourceMatchVector const &);
449 
450 template <typename Cat1, typename Cat2>
452  Cat1 const &first,
453  Cat2 const &second) {
454  LOG_LOGGER tableLog = LOG_GET("afw.table");
455  Key<RecordId> inKey1 = matches.getSchema()["first"];
456  Key<RecordId> inKey2 = matches.getSchema()["second"];
457  Key<double> keyD = matches.getSchema()["distance"];
458  if (!first.isSorted() || !second.isSorted())
460  "Catalogs passed to unpackMatches must be sorted.");
463  result.resize(matches.size());
464  typename std::vector<MatchT>::iterator j = result.begin();
465  for (BaseCatalog::const_iterator i = matches.begin(); i != matches.end(); ++i, ++j) {
466  typename Cat1::const_iterator k1 = first.find(i->get(inKey1));
467  typename Cat2::const_iterator k2 = second.find(i->get(inKey2));
468  if (k1 != first.end()) {
469  j->first = k1;
470  } else {
471  LOGLS_WARN(tableLog, "Persisted match record with ID " << i->get(inKey1)
472  << " not found in catalog 1.");
473  }
474  if (k2 != second.end()) {
475  j->second = k2;
476  } else {
477  LOGLS_WARN(tableLog, "Persisted match record with ID " << i->get(inKey2)
478  << " not found in catalog 2.");
479  }
480  j->distance = i->get(keyD);
481  }
482  return result;
483 }
484 
485 template SimpleMatchVector unpackMatches(BaseCatalog const &, SimpleCatalog const &, SimpleCatalog const &);
487  SourceCatalog const &);
488 template SourceMatchVector unpackMatches(BaseCatalog const &, SourceCatalog const &, SourceCatalog const &);
489 }
490 }
491 } // namespace lsst::afw::table
#define LOGLS_WARN(logger, message)
Defines the fields and offsets for a table.
Definition: Schema.h:47
bool findOnlyClosest
"Return only the closest match if more than one is found " "(default: true)" ;
Definition: Match.h:50
double dec
Definition: Match.cc:41
lsst::afw::geom::Angle Angle
Definition: misc.h:33
afw::table::Schema schema
Definition: GaussianPsf.cc:43
AngleUnit constexpr radians
constant with units of radians
Definition: Angle.h:87
AngleUnit constexpr degrees
constant with units of degrees
Definition: Angle.h:88
Schema getSchema() const
Return the schema associated with the catalog&#39;s table.
Definition: Catalog.h:117
double z
Definition: Match.cc:44
T resize(T... args)
std::vector< Match< typename Cat1::Record, typename Cat2::Record > > unpackMatches(BaseCatalog const &matches, Cat1 const &cat1, Cat2 const &cat2)
Reconstruct a MatchVector from a BaseCatalog representation of the matches and a pair of catalogs...
Definition: Match.cc:451
std::vector< Match< typename Cat1::Record, typename Cat2::Record > > matchRaDec(Cat1 const &cat1, Cat2 const &cat2, Angle radius, MatchControl const &mc=MatchControl())
Compute all tuples (s1,s2,d) where s1 belings to cat1, s2 belongs to cat2 and d, the distance between...
Definition: Match.cc:157
T sin(T... args)
Pass parameters to algorithms that match list of sources.
Definition: Match.h:45
T push_back(T... args)
A class representing an angle.
Definition: Angle.h:102
A base class for image defects.
Custom catalog class for record/table subclasses that are guaranteed to have an ID, and should generally be sorted by that ID.
Definition: fwd.h:63
std::shared_ptr< RecordT > src
Definition: Match.cc:48
iterator end()
Iterator access.
Definition: Catalog.h:397
Lightweight representation of a geometric match between two records.
Definition: fwd.h:101
std::vector< SimpleMatch > SimpleMatchVector
Definition: fwd.h:107
Iterator class for CatalogT.
Definition: Catalog.h:38
T cos(T... args)
double x
Definition: Match.cc:42
std::unique_ptr< SchemaItem< U > > result
Definition: Schema.cc:194
BaseCatalog packMatches(std::vector< Match< Record1, Record2 > > const &matches)
Return a table representation of a MatchVector that can be used to persist it.
Definition: Match.cc:428
double y
Definition: Match.cc:43
T asin(T... args)
T get(T... args)
#define LSST_EXCEPT(type,...)
STL class.
STL class.
A class used as a handle to a particular field in a table.
Definition: fwd.h:45
T begin(T... args)
#define LSST_MATCH_RADEC(RTYPE, C1, C2)
Definition: Match.cc:285
SortedCatalogT< SourceRecord > SourceCatalog
Definition: fwd.h:85
constexpr double asRadians() const noexcept
Return an Angle&#39;s value in radians.
Definition: Angle.h:141
T isnan(T... args)
SourceMatchVector matchXy(SourceCatalog const &cat1, SourceCatalog const &cat2, double radius, MatchControl const &mc=MatchControl())
Compute all tuples (s1,s2,d) where s1 belings to cat1, s2 belongs to cat2 and d, the distance between...
Definition: Match.cc:301
size_type size() const
Return the number of elements in the catalog.
Definition: Catalog.h:408
T sort(T... args)
T sqrt(T... args)
bool includeMismatches
"Include failed matches (i.e. one &#39;match&#39; is NULL) " "(default: false)" ;
Definition: Match.h:56
iterator begin()
Iterator access.
Definition: Catalog.h:396
#define LOG_GET(logger)
SortedCatalogT< SimpleRecord > SimpleCatalog
Definition: fwd.h:79
Match< SourceRecord, SourceRecord > SourceMatch
Definition: fwd.h:105
Key< T > addField(Field< T > const &field, bool doReplace=false)
Add a new field to the Schema, and return the associated Key.
Definition: Schema.cc:666
bool symmetricMatch
"Produce symmetric matches (default: true):\n" "i.e. if (s1, s2, d) is reported, then so is (s2...
Definition: Match.h:53
std::vector< SourceMatch > SourceMatchVector
Definition: fwd.h:109