lsst.afw  18.0.0-6-g7484c24d0
multiMatch.py
Go to the documentation of this file.
1 # This file is part of afw.
2 #
3 # Developed for the LSST Data Management System.
4 # This product includes software developed by the LSST Project
5 # (https://www.lsst.org).
6 # See the COPYRIGHT file at the top-level directory of this distribution
7 # for details of code ownership.
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 GNU General Public License
20 # along with this program. If not, see <https://www.gnu.org/licenses/>.
21 import collections.abc
22 
23 import numpy
24 
25 import lsst.geom
26 from .schemaMapper import SchemaMapper
27 from .aggregates import CoordKey
28 from .source import SourceRecord
29 
30 
31 class MultiMatch:
32  """Initialize a multi-catalog match.
33 
34  Parameters
35  ----------
36  schema : `lsst.afw.table.Schema`
37  Schema shared by all catalogs to be included in the match.
38  dataIdFormat : `dict`
39  Set of name: type for all data ID keys (e.g. {"visit":int,
40  "ccd":int}).
41  coordField : `str`, optional
42  Prefix for _ra and _dec fields that contain the
43  coordinates to use for the match.
44  idField : `str`, optional
45  Name of the field in schema that contains unique object
46  IDs.
47  radius : `lsst.geom.Angle`, optional
48  Maximum separation for a match. Defaults to 0.5 arcseconds.
49  RecordClass : `lsst.afw.table.BaseRecord`
50  Type of record to expect in catalogs to be matched.
51  """
52 
53  def __init__(self, schema, dataIdFormat, coordField="coord", idField="id", radius=None,
54  RecordClass=SourceRecord):
55  if radius is None:
56  radius = 0.5*lsst.geom.arcseconds
57  elif not isinstance(radius, lsst.geom.Angle):
58  raise ValueError("'radius' argument must be an Angle")
59  self.radius = radius
60  self.mapper = SchemaMapper(schema)
61  self.mapper.addMinimalSchema(schema, True)
62  self.coordKey = CoordKey(schema[coordField])
63  self.idKey = schema.find(idField).key
64  self.dataIdKeys = {}
65  outSchema = self.mapper.editOutputSchema()
66  outSchema.setAliasMap(self.mapper.getInputSchema().getAliasMap())
67  self.objectKey = outSchema.addField(
68  "object", type=numpy.int64, doc="Unique ID for joined sources")
69  for name, dataType in dataIdFormat.items():
70  self.dataIdKeys[name] = outSchema.addField(
71  name, type=dataType, doc="'%s' data ID component")
72  # self.result will be a catalog containing the union of all matched records, with an 'object' ID
73  # column that can be used to group matches. Sources that have ambiguous matches may appear
74  # multiple times.
75  self.result = None
76  # self.reference will be a subset of self.result, with exactly one record for each group of matches
77  # (we'll use the one from the first catalog matched into this group)
78  # We'll use this to match against each subsequent catalog.
79  self.reference = None
80  # A set of ambiguous objects that we may want to ultimately remove from
81  # the final merged catalog.
82  self.ambiguous = set()
83  # Table used to allocate new records for the ouput catalog.
84  self.table = RecordClass.Table.make(self.mapper.getOutputSchema())
85  # Counter used to assign the next object ID
86  self.nextObjId = 1
87 
88  def makeRecord(self, inputRecord, dataId, objId):
89  """Create a new result record from the given input record, using the
90  given data ID and object ID to fill in additional columns.
91 
92  Parameters
93  ----------
94  inputRecord : `lsst.afw.table.source.sourceRecord`
95  Record to use as the reference for the new result.
96  dataId : `DataId` or `dict`
97  Data id describing the data.
98  objId : `int`
99  Object id of the object to be added.
100 
101  Returns
102  -------
103  outputRecord : `lsst.afw.table.source.sourceRecord`
104  Newly generated record.
105  """
106  outputRecord = self.table.copyRecord(inputRecord, self.mapper)
107  for name, key in self.dataIdKeys.items():
108  outputRecord.set(key, dataId[name])
109  outputRecord.set(self.objectKey, objId)
110  return outputRecord
111 
112  def add(self, catalog, dataId):
113  """Add a new catalog to the match, corresponding to the given data ID.
114  The new catalog is appended to the `self.result` and
115  `self.reference` catalogs.
116 
117  Parameters
118  ----------
119  catalog : `lsst.afw.table.base.Catalog`
120  Catalog to be added to the match result.
121  dataId : `DataId` or `dict`
122  Data id for the catalog to be added.
123  """
124  if self.result is None:
125  self.result = self.table.Catalog(self.table)
126  for record in catalog:
127  self.result.append(self.makeRecord(
128  record, dataId, objId=self.nextObjId))
129  self.nextObjId += 1
130  self.reference = self.result.copy(deep=False)
131  return
132  catalog.sort(self.idKey) # pre-sort for speedy by-id access later.
133  # Will remove from this set as objects are matched.
134  unmatchedIds = {record.get(self.idKey) for record in catalog}
135  # Temporary dict mapping new source ID to a set of associated objects.
136  newToObj = {}
137  matches = lsst.afw.table.matchRaDec(self.reference, catalog, self.radius)
138  matchedRefIds = set()
139  matchedCatIds = set()
140  for refRecord, newRecord, distance in matches:
141  objId = refRecord.get(self.objectKey)
142  if objId in matchedRefIds:
143  # We've already matched this object against another new source,
144  # mark it as ambiguous.
145  self.ambiguous.add(objId)
146  matchedRefIds.add(objId)
147  if newRecord.get(self.idKey) in matchedCatIds:
148  # We've already matched this new source to one or more other objects
149  # Mark all involved objects as ambiguous
150  self.ambiguous.add(objId)
151  self.ambiguous |= newToObj.get(newRecord.get(self.idKey), set())
152  matchedCatIds.add(newRecord.get(self.idKey))
153  unmatchedIds.discard(newRecord.get(self.idKey))
154  # Populate the newToObj dict (setdefault trick is an idiom for
155  # appending to a dict-of-sets)
156  newToObj.setdefault(newRecord.get(self.idKey), set()).add(objId)
157  # Add a new result record for this match.
158  self.result.append(self.makeRecord(newRecord, dataId, objId))
159  # Add any unmatched sources from the new catalog as new objects to both
160  # the joined result catalog and the reference catalog.
161  for objId in unmatchedIds:
162  newRecord = catalog.find(objId, self.idKey)
163  resultRecord = self.makeRecord(newRecord, dataId, self.nextObjId)
164  self.nextObjId += 1
165  self.result.append(resultRecord)
166  self.reference.append(resultRecord)
167 
168  def finish(self, removeAmbiguous=True):
169  """Return the final match catalog, after sorting it by object, copying
170  it to ensure contiguousness, and optionally removing ambiguous
171  matches.
172 
173  After calling finish(), the in-progress state of the matcher
174  is returned to the state it was just after construction, with
175  the exception of the object ID counter (which is not reset).
176 
177  Parameters
178  ----------
179  removeAmbiguous : `bool`, optional
180  Should ambiguous matches be removed from the match
181  catalog? Defaults to True.
182 
183  Returns
184  -------
185  result : `lsst.afw.table.base.Catalog`
186  Final match catalog, sorted by object.
187  """
188  if removeAmbiguous:
189  result = self.table.Catalog(self.table)
190  for record in self.result:
191  if record.get(self.objectKey) not in self.ambiguous:
192  result.append(record)
193  else:
194  result = self.result
195  result.sort(self.objectKey)
196  result = result.copy(deep=True)
197  self.result = None
198  self.reference = None
199  self.ambiguous = set()
200  return result
201 
202 
203 class GroupView(collections.abc.Mapping):
204  """A mapping (i.e. dict-like object) that provides convenient
205  operations on the concatenated catalogs returned by a MultiMatch
206  object.
207 
208  A GroupView provides access to a catalog of grouped objects, in
209  which the grouping is indicated by a field for which all records
210  in a group have the same value. Once constructed, it allows
211  operations similar to those supported by SQL "GROUP BY", such as
212  filtering and aggregate calculation.
213 
214  Parameters
215  ----------
216  schema : `lsst.afw.table.Schema`
217  Catalog schema to use for the grouped object catalog.
218  ids : `List`
219  List of identifying keys for the groups in the catalog.
220  groups : `List`
221  List of catalog subsets associated with each key in ids.
222  """
223 
224  @classmethod
225  def build(cls, catalog, groupField="object"):
226  """Construct a GroupView from a concatenated catalog.
227 
228  Parameters
229  ----------
230  catalog : `lsst.afw.table.base.Catalog`
231  Input catalog, containing records grouped by a field in
232  which all records in the same group have the same value.
233  Must be sorted by the group field.
234  groupField : `str`, optional
235  Name or Key for the field that indicates groups. Defaults
236  to "object".
237 
238  Returns
239  -------
240  groupCatalog : `lsst.afw.table.multiMatch.GroupView`
241  Constructed GroupView from the input concatenated catalog.
242  """
243  groupKey = catalog.schema.find(groupField).key
244  ids, indices = numpy.unique(catalog.get(groupKey), return_index=True)
245  groups = numpy.zeros(len(ids), dtype=object)
246  ends = list(indices[1:]) + [len(catalog)]
247  for n, (i1, i2) in enumerate(zip(indices, ends)):
248  # casts are a work-around for DM-8557
249  groups[n] = catalog[int(i1):int(i2)]
250  assert (groups[n].get(groupKey) == ids[n]).all()
251  return cls(catalog.schema, ids, groups)
252 
253  def __init__(self, schema, ids, groups):
254  self.schema = schema
255  self.ids = ids
256  self.groups = groups
257  self.count = sum(len(cat) for cat in self.groups)
258 
259  def __len__(self):
260  return len(self.ids)
261 
262  def __iter__(self):
263  return self.ids
264 
265  def __getitem__(self, key):
266  index = numpy.searchsorted(self.ids, key)
267  if self.ids[index] != key:
268  raise KeyError("Group with ID {0} not found".format(key))
269  return self.groups[index]
270 
271  def where(self, predicate):
272  """Return a new GroupView that contains only groups for which the
273  given predicate function returns True.
274 
275  The predicate function is called once for each group, and
276  passed a single argument: the subset catalog for that group.
277 
278  Parameters
279  ----------
280  predicate :
281  Function to identify which groups should be included in
282  the output.
283 
284  Returns
285  -------
286  outGroupView : `lsst.afw.table.multiMatch.GroupView`
287  Subset GroupView containing only groups that match the
288  predicate.
289  """
290  mask = numpy.zeros(len(self), dtype=bool)
291  for i in range(len(self)):
292  mask[i] = predicate(self.groups[i])
293  return type(self)(self.schema, self.ids[mask], self.groups[mask])
294 
295  def aggregate(self, function, field=None, dtype=float):
296  """Run an aggregate function on each group, returning an array with
297  one element for each group.
298 
299  Parameters
300  ----------
301  function :
302  Callable object that computes the aggregate value. If
303  `field` is None, called with the entire subset catalog as an
304  argument. If `field` is not None, called with an array view
305  into that field.
306  field : `str`, optional
307  A string name or Key object that indicates a single field the aggregate
308  is computed over.
309  dtype :
310  Data type of the output array.
311 
312  Returns
313  -------
314  result : Array of `dtype`
315  Aggregated values for each group.
316  """
317  result = numpy.zeros(len(self), dtype=dtype)
318  if field is not None:
319  key = self.schema.find(field).key
320 
321  def f(cat):
322  return function(cat.get(key))
323  else:
324  f = function
325  for i in range(len(self)):
326  result[i] = f(self.groups[i])
327  return result
328 
329  def apply(self, function, field=None, dtype=float):
330  """Run a non-aggregate function on each group, returning an array with
331  one element for each record.
332 
333  Parameters
334  ----------
335  function :
336  Callable object that computes the aggregate value. If field is None,
337  called with the entire subset catalog as an argument. If field is not
338  None, called with an array view into that field.
339  field : `str`
340  A string name or Key object that indicates a single field the aggregate
341  is computed over.
342  dtype :
343  Data type for the output array.
344 
345  Returns
346  -------
347  result : `numpy.array` of `dtype`
348  Result of the function calculated on an element-by-element basis.
349  """
350  result = numpy.zeros(self.count, dtype=dtype)
351  if field is not None:
352  key = self.schema.find(field).key
353 
354  def f(cat):
355  return function(cat.get(key))
356  else:
357  f = function
358  last = 0
359  for i in range(len(self)):
360  next = last + len(self.groups[i])
361  result[last:next] = f(self.groups[i])
362  last = next
363  return result
std::vector< SchemaItem< Flag > > * items
def __init__(self, schema, dataIdFormat, coordField="coord", idField="id", radius=None, RecordClass=SourceRecord)
Definition: multiMatch.py:54
def build(cls, catalog, groupField="object")
Definition: multiMatch.py:225
def apply(self, function, field=None, dtype=float)
Definition: multiMatch.py:329
template SourceMatchVector matchRaDec(SourceCatalog const &, lsst::geom::Angle, MatchControl const &)
def makeRecord(self, inputRecord, dataId, objId)
Definition: multiMatch.py:88
def __init__(self, schema, ids, groups)
Definition: multiMatch.py:253
def finish(self, removeAmbiguous=True)
Definition: multiMatch.py:168
table::Key< int > type
Definition: Detector.cc:167
def aggregate(self, function, field=None, dtype=float)
Definition: multiMatch.py:295
daf::base::PropertyList * list
Definition: fits.cc:885
def add(self, catalog, dataId)
Definition: multiMatch.py:112
daf::base::PropertySet * set
Definition: fits.cc:884