lsst.afw  13.0-101-g894215678
FootprintMerge.cc
Go to the documentation of this file.
1 /*
2  * LSST Data Management System
3  * Copyright 2008-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 #include <cstdint>
23 
24 #include "boost/bind.hpp"
25 
29 
30 namespace lsst {
31 namespace afw {
32 namespace detection {
33 
35 public:
36  typedef FootprintMergeList::KeyTuple KeyTuple;
37  typedef FootprintMergeList::FilterMap FilterMap;
38 
39  explicit FootprintMerge(std::shared_ptr<Footprint> footprint,
40  std::shared_ptr<afw::table::SourceTable> sourceTable,
41  std::shared_ptr<PeakTable> peakTable,
42  afw::table::SchemaMapper const &peakSchemaMapper, KeyTuple const &keys)
43  : _footprints(1, footprint), _source(sourceTable->makeRecord()) {
44  std::shared_ptr<Footprint> newFootprint = std::make_shared<Footprint>(*footprint);
45 
46  _source->set(keys.footprint, true);
47  // Replace all the Peaks in the merged Footprint with new ones that include the origin flags
48  newFootprint->getPeaks() = PeakCatalog(peakTable);
49  for (PeakCatalog::iterator iter = footprint->getPeaks().begin(); iter != footprint->getPeaks().end();
50  ++iter) {
51  std::shared_ptr<PeakRecord> newPeak = peakTable->copyRecord(*iter, peakSchemaMapper);
52  newPeak->set(keys.peak, true);
53  newFootprint->getPeaks().push_back(newPeak);
54  }
55  _source->setFootprint(newFootprint);
56  }
57 
58  /*
59  * Does this Footprint overlap the merged Footprint.
60  *
61  * The current implementation just builds an image from the two Footprints and
62  * detects the number of peaks. This is not very efficient and will be changed
63  * within the Footprint class in the future.
64  */
65  bool overlaps(Footprint const &rhs) const {
66  return getMergedFootprint()->getSpans()->overlaps(*(rhs.getSpans()));
67  }
68 
69  /*
70  * Add this Footprint to the merge.
71  *
72  * If minNewPeakDist >= 0, it will add all peaks from the footprint to the merged Footprint
73  * that are greater than minNewPeakDist away from the closest peak in the existing list.
74  * If minNewPeakDist < 0, no peaks will be added from the footprint.
75  *
76  * If maxSamePeakDist >= 0, it will find the closest peak in the existing list for every peak
77  * in the footprint. If the closest peak is less than maxSamePeakDist, the peak will not
78  * be added and the closest peak will be flagged as detected by the filter defined in keys.
79  *
80  * If the footprint does not overlap it will do nothing.
81  */
82  void add(std::shared_ptr<Footprint> footprint, afw::table::SchemaMapper const &peakSchemaMapper,
83  KeyTuple const &keys, float minNewPeakDist = -1., float maxSamePeakDist = -1.) {
84  if (_addSpans(footprint)) {
85  _footprints.push_back(footprint);
86  _source->set(keys.footprint, true);
87  _addPeaks(footprint->getPeaks(), &peakSchemaMapper, &keys, minNewPeakDist, maxSamePeakDist, NULL);
88  }
89  }
90 
91  /*
92  * Merge an already-merged clump of Footprints into this
93  *
94  * If minNewPeakDist >= 0, it will add all peaks from the footprint to the merged Footprint
95  * that are greater than minNewPeakDist away from the closest peak in the existing list.
96  * If minNewPeakDist < 0, no peaks will be added from the footprint.
97  *
98  * If maxSamePeakDist >= 0, it will find the closest peak in the existing list for every peak
99  * in the footprint. If the closest peak is less than maxSamePeakDist, the peak will not
100  * be added to the list and the flags from the closest peak will be set to the OR of the two.
101  *
102  * If the FootprintMerge does not overlap it will do nothing.
103  */
104  void add(FootprintMerge const &other, FilterMap const &keys, float minNewPeakDist = -1.,
105  float maxSamePeakDist = -1.) {
106  if (_addSpans(other.getMergedFootprint())) {
107  _footprints.insert(_footprints.end(), other._footprints.begin(), other._footprints.end());
108  // Set source flags to the OR of the flags of the two inputs
109  for (FilterMap::const_iterator i = keys.begin(); i != keys.end(); ++i) {
110  afw::table::Key<afw::table::Flag> const &flagKey = i->second.footprint;
111  _source->set(flagKey, _source->get(flagKey) || other._source->get(flagKey));
112  }
113  _addPeaks(other.getMergedFootprint()->getPeaks(), NULL, NULL, minNewPeakDist, maxSamePeakDist,
114  &keys);
115  }
116  }
117 
118  // Get the bounding box of the merge
119  afw::geom::Box2I getBBox() const { return getMergedFootprint()->getBBox(); }
120 
121  std::shared_ptr<Footprint> getMergedFootprint() const { return _source->getFootprint(); }
122 
123  std::shared_ptr<afw::table::SourceRecord> getSource() const { return _source; }
124 
125 private:
126  // Implementation helper for add() methods; returns true if the Footprint actually overlapped
127  // and was merged, and false otherwise.
128  bool _addSpans(std::shared_ptr<Footprint> footprint) {
129  if (!getMergedFootprint()->getSpans()->overlaps(*(footprint->getSpans()))) return false;
130  getMergedFootprint()->setSpans(getMergedFootprint()->getSpans()->union_(*(footprint->getSpans())));
131  return true;
132  }
133 
134  /*
135  * Add new peaks to the list of peaks of the merged footprint.
136  * This function handles two different cases:
137  * - The peaks come from a single footprint. In this case, the peakSchemaMapper
138  * and keys should be defined so that it can create a new peak, copy the appropriate
139  * data, and set the peak flag defined in keys.
140  * - The peaks come from another FootprintMerge. In this case, filterMap should
141  * be defined so that the information from the other peaks can be propagated.
142  */
143  void _addPeaks(PeakCatalog const &otherPeaks, afw::table::SchemaMapper const *peakSchemaMapper,
144  KeyTuple const *keys, float minNewPeakDist, float maxSamePeakDist,
145  FilterMap const *filterMap) {
146  if (minNewPeakDist < 0 && maxSamePeakDist < 0) return;
147 
148  assert(peakSchemaMapper || filterMap);
149 
150  PeakCatalog &currentPeaks = getMergedFootprint()->getPeaks();
151  std::shared_ptr<PeakRecord> nearestPeak;
152  // Create new list of peaks
153  PeakCatalog newPeaks(currentPeaks.getTable());
154  float minNewPeakDist2 = minNewPeakDist * minNewPeakDist;
155  float maxSamePeakDist2 = maxSamePeakDist * maxSamePeakDist;
156  for (PeakCatalog::const_iterator otherIter = otherPeaks.begin(); otherIter != otherPeaks.end();
157  ++otherIter) {
158  float minDist2 = std::numeric_limits<float>::infinity();
159 
160  for (PeakCatalog::const_iterator currentIter = currentPeaks.begin();
161  currentIter != currentPeaks.end(); ++currentIter) {
162  float dist2 = otherIter->getI().distanceSquared(currentIter->getI());
163 
164  if (dist2 < minDist2) {
165  minDist2 = dist2;
166  nearestPeak = currentIter;
167  }
168  }
169 
170  if (minDist2 < maxSamePeakDist2 && nearestPeak && maxSamePeakDist > 0) {
171  if (peakSchemaMapper) {
172  nearestPeak->set(keys->peak, true);
173  } else {
174  for (FilterMap::const_iterator i = filterMap->begin(); i != filterMap->end(); ++i) {
175  afw::table::Key<afw::table::Flag> const &flagKey = i->second.peak;
176  nearestPeak->set(flagKey, nearestPeak->get(flagKey) || otherIter->get(flagKey));
177  }
178  }
179  } else if (minDist2 > minNewPeakDist2 && !(minNewPeakDist < 0)) {
180  if (peakSchemaMapper) {
181  std::shared_ptr<PeakRecord> newPeak = newPeaks.addNew();
182  newPeak->assign(*otherIter, *peakSchemaMapper);
183  newPeak->set(keys->peak, true);
184  } else {
185  newPeaks.push_back(otherIter);
186  }
187  }
188  }
189 
190  getMergedFootprint()->getPeaks().insert(getMergedFootprint()->getPeaks().end(), newPeaks.begin(),
191  newPeaks.end(),
192  true // deep-copy
193  );
194  }
195 
196  std::vector<std::shared_ptr<Footprint>> _footprints;
197  std::shared_ptr<afw::table::SourceRecord> _source;
198 };
199 
201  std::vector<std::string> const &filterList,
202  afw::table::Schema const &initialPeakSchema)
203  : _peakSchemaMapper(initialPeakSchema) {
204  _initialize(sourceSchema, filterList);
205 }
206 
208  std::vector<std::string> const &filterList)
209  : _peakSchemaMapper(PeakTable::makeMinimalSchema()) {
210  _initialize(sourceSchema, filterList);
211 }
212 
213 void FootprintMergeList::_initialize(afw::table::Schema &sourceSchema,
214  std::vector<std::string> const &filterList) {
215  _peakSchemaMapper.addMinimalSchema(_peakSchemaMapper.getInputSchema(), true);
216  // Add Flags for the filters
217  for (std::vector<std::string>::const_iterator iter = filterList.begin(); iter != filterList.end();
218  ++iter) {
219  KeyTuple &keys = _filterMap[*iter];
220  keys.footprint = sourceSchema.addField<afw::table::Flag>(
221  "merge_footprint_" + *iter,
222  "Detection footprint overlapped with a detection from filter " + *iter);
223  keys.peak = _peakSchemaMapper.editOutputSchema().addField<afw::table::Flag>(
224  "merge_peak_" + *iter, "Peak detected in filter " + *iter);
225  }
226  _peakTable = PeakTable::make(_peakSchemaMapper.getOutputSchema());
227 }
228 
229 void FootprintMergeList::addCatalog(std::shared_ptr<afw::table::SourceTable> sourceTable,
230  afw::table::SourceCatalog const &inputCat, std::string const &filter,
231  float minNewPeakDist, bool doMerge, float maxSamePeakDist) {
232  FilterMap::const_iterator keyIter = _filterMap.find(filter);
233  if (keyIter == _filterMap.end()) {
234  throw LSST_EXCEPT(pex::exceptions::LogicError,
235  (boost::format("Filter %s not in original list") % filter).str());
236  }
237 
238  // If list is empty don't check for any matches, just add all the objects
239  bool checkForMatches = (_mergeList.size() > 0);
240 
241  for (afw::table::SourceCatalog::const_iterator srcIter = inputCat.begin(); srcIter != inputCat.end();
242  ++srcIter) {
243  // Only consider unblended objects
244  if (srcIter->getParent() != 0) continue;
245 
246  std::shared_ptr<Footprint> foot = srcIter->getFootprint();
247 
248  // Empty pointer to account for the first match in the catalog. If there is more than one
249  // match, subsequent matches will be merged with this one
250  std::shared_ptr<FootprintMerge> first = std::shared_ptr<FootprintMerge>();
251 
252  if (checkForMatches) {
253  FootprintMergeVec::iterator iter = _mergeList.begin();
254  while (iter != _mergeList.end()) {
255  // Grow by one pixel to allow for touching
256  geom::Box2I box((**iter).getBBox());
257  box.grow(geom::Extent2I(1, 1));
258  if (box.overlaps(foot->getBBox()) && (**iter).overlaps(*foot)) {
259  if (!first) {
260  first = *iter;
261  // Add Footprint to existing merge and set flag for this band
262  if (doMerge) {
263  first->add(foot, _peakSchemaMapper, keyIter->second, minNewPeakDist,
264  maxSamePeakDist);
265  }
266  } else {
267  // Add merged Footprint to first
268  if (doMerge) {
269  first->add(**iter, _filterMap, minNewPeakDist, maxSamePeakDist);
270  iter = _mergeList.erase(iter);
271  continue;
272  }
273  }
274  }
275  ++iter;
276  }
277  }
278 
279  if (!first) {
280  _mergeList.push_back(std::make_shared<FootprintMerge>(foot, sourceTable, _peakTable,
281  _peakSchemaMapper, keyIter->second));
282  }
283  }
284 }
285 
287  // Now set the merged footprint as the footprint of the SourceRecord
288  for (FootprintMergeVec::iterator iter = _mergeList.begin(); iter != _mergeList.end(); ++iter) {
289  outputCat.push_back((**iter).getSource());
290  }
291 }
292 }
293 }
294 } // namespace lsst::afw::detection
Defines the fields and offsets for a table.
Definition: Schema.h:46
bool overlaps(Footprint const &rhs) const
std::shared_ptr< afw::table::SourceRecord > getSource() const
void add(std::shared_ptr< Footprint > footprint, afw::table::SchemaMapper const &peakSchemaMapper, KeyTuple const &keys, float minNewPeakDist=-1., float maxSamePeakDist=-1.)
FootprintMerge(std::shared_ptr< Footprint > footprint, std::shared_ptr< afw::table::SourceTable > sourceTable, std::shared_ptr< PeakTable > peakTable, afw::table::SchemaMapper const &peakSchemaMapper, KeyTuple const &keys)
Schema const getInputSchema() const
Return the input schema (copy-on-write).
Definition: SchemaMapper.h:24
FootprintMergeList::FilterMap FilterMap
A mapping between the keys of two Schemas, used to copy data between them.
Definition: SchemaMapper.h:21
std::shared_ptr< Table > getTable() const
Return the table associated with the catalog.
Definition: Catalog.h:113
Table class for Peaks in Footprints.
Definition: Peak.h:86
Schema const getOutputSchema() const
Return the output schema (copy-on-write).
Definition: SchemaMapper.h:27
static std::shared_ptr< PeakTable > make(afw::table::Schema const &schema, bool forceNew=false)
Obtain a table that can be used to create records with given schema.
Definition: Peak.cc:100
Key< T > addField(Field< T > const &field, bool doReplace=false)
Add a new field to the Schema, and return the associated Key.
afw::geom::Box2I getBBox() const
An integer coordinate rectangle.
Definition: Box.h:55
FootprintMergeList::KeyTuple KeyTuple
A base class for image defects.
Definition: cameraGeom.dox:3
afw::table::CatalogT< PeakRecord > PeakCatalog
Definition: Peak.h:223
int end
iterator end()
Iterator access.
Definition: Catalog.h:388
Iterator class for CatalogT.
Definition: Catalog.h:37
void getFinalSources(afw::table::SourceCatalog &outputCat)
Get SourceCatalog with entries that contain the final Footprint and SourceRecord for each entry...
Schema & editOutputSchema()
Return a reference to the output schema that allows it to be modified in place.
Definition: SchemaMapper.h:30
Class to describe the properties of a detected object from an image.
Definition: Footprint.h:62
std::shared_ptr< Footprint > getMergedFootprint() const
void addMinimalSchema(Schema const &minimal, bool doMap=true)
Add the given minimal schema to the output schema.
void addCatalog(std::shared_ptr< afw::table::SourceTable > sourceTable, afw::table::SourceCatalog const &inputCat, std::string const &filter, float minNewPeakDist=-1., bool doMerge=true, float maxSamePeakDist=-1.)
Add objects from a SourceCatalog in the specified filter.
FootprintMergeList(afw::table::Schema &sourceSchema, std::vector< std::string > const &filterList, afw::table::Schema const &initialPeakSchema)
Initialize the merge with a custom initial peak schema.
std::shared_ptr< geom::SpanSet > getSpans() const
Return a shared pointer to the SpanSet.
Definition: Footprint.h:116
void add(FootprintMerge const &other, FilterMap const &keys, float minNewPeakDist=-1., float maxSamePeakDist=-1.)
iterator begin()
Iterator access.
Definition: Catalog.h:387