lsst.afw  14.0-59-g0c7cc230b
multiMatch.py
Go to the documentation of this file.
1 from __future__ import absolute_import, division, print_function
2 
3 import collections
4 
5 from builtins import zip
6 from builtins import range
7 from builtins import object
8 import numpy
9 
10 import lsst.afw.geom
11 from .schemaMapper import SchemaMapper
12 from .aggregates import CoordKey
13 from .source import SourceRecord
14 
15 
16 class MultiMatch(object):
17 
18  def __init__(self, schema, dataIdFormat, coordField="coord", idField="id", radius=None,
19  RecordClass=SourceRecord):
20  """Initialize a multi-catalog match.
21 
22  Arguments:
23  schema -------- schema shared by all catalogs to be included in the match.
24  dataIdFormat -- dict of name: type for all data ID keys (e.g. {"visit":int, "ccd":int}).
25  coordField ---- prefix for _ra and _dec fields that contain the coordinates to use for the match.
26  idField ------- name of the field in schema that contains unique object IDs.
27  radius -------- lsst.afw.geom.Angle; maximum separation for a match. Defaults to 0.5 arcseconds.
28  RecordClass --- type of record (a subclass of lsst.afw.table.BaseRecord) to expect in catalogs
29  to be matched.
30  """
31  if radius is None:
32  radius = 0.5*lsst.afw.geom.arcseconds
33  elif not isinstance(radius, lsst.afw.geom.Angle):
34  raise ValueError("'radius' argument must be an Angle")
35  self.radius = radius
36  self.mapper = SchemaMapper(schema)
37  self.mapper.addMinimalSchema(schema, True)
38  self.coordKey = CoordKey(schema[coordField])
39  self.idKey = schema.find(idField).key
40  self.dataIdKeys = {}
41  outSchema = self.mapper.editOutputSchema()
42  self.objectKey = outSchema.addField(
43  "object", type=numpy.int64, doc="Unique ID for joined sources")
44  for name, dataType in dataIdFormat.items():
45  self.dataIdKeys[name] = outSchema.addField(
46  name, type=dataType, doc="'%s' data ID component")
47  # self.result will be a catalog containing the union of all matched records, with an 'object' ID
48  # column that can be used to group matches. Sources that have ambiguous matches may appear
49  # multiple times.
50  self.result = None
51  # self.reference will be a subset of self.result, with exactly one record for each group of matches
52  # (we'll use the one from the first catalog matched into this group)
53  # We'll use this to match against each subsequent catalog.
54  self.reference = None
55  # A set of ambiguous objects that we may want to ultimately remove from
56  # the final merged catalog.
57  self.ambiguous = set()
58  # Table used to allocate new records for the ouput catalog.
59  self.table = RecordClass.Table.make(self.mapper.getOutputSchema())
60  # Counter used to assign the next object ID
61  self.nextObjId = 1
62 
63  def makeRecord(self, inputRecord, dataId, objId):
64  """Create a new result record from the given input record, using the given data ID and object ID
65  to fill in additional columns."""
66  outputRecord = self.table.copyRecord(inputRecord, self.mapper)
67  for name, key in self.dataIdKeys.items():
68  outputRecord.set(key, dataId[name])
69  outputRecord.set(self.objectKey, objId)
70  return outputRecord
71 
72  def add(self, catalog, dataId):
73  """Add a new catalog to the match, corresponding to the given data ID.
74  """
75  if self.result is None:
76  self.result = self.table.Catalog(self.table)
77  for record in catalog:
78  self.result.append(self.makeRecord(
79  record, dataId, objId=self.nextObjId))
80  self.nextObjId += 1
81  self.reference = self.result.copy(deep=False)
82  return
83  catalog.sort(self.idKey) # pre-sort for speedy by-id access later.
84  # Will remove from this set as objects are matched.
85  unmatchedIds = {record.get(self.idKey) for record in catalog}
86  # Temporary dict mapping new source ID to a set of associated objects.
87  newToObj = {}
88  matches = lsst.afw.table.matchRaDec(self.reference, catalog, self.radius)
89  matchedRefIds = set()
90  matchedCatIds = set()
91  for refRecord, newRecord, distance in matches:
92  objId = refRecord.get(self.objectKey)
93  if objId in matchedRefIds:
94  # We've already matched this object against another new source,
95  # mark it as ambiguous.
96  self.ambiguous.add(objId)
97  matchedRefIds.add(objId)
98  if newRecord.get(self.idKey) in matchedCatIds:
99  # We've already matched this new source to one or more other objects
100  # Mark all involved objects as ambiguous
101  self.ambiguous.add(objId)
102  self.ambiguous |= newToObj.get(newRecord.get(self.idKey), set())
103  matchedCatIds.add(newRecord.get(self.idKey))
104  unmatchedIds.discard(newRecord.get(self.idKey))
105  # Populate the newToObj dict (setdefault trick is an idiom for
106  # appending to a dict-of-sets)
107  newToObj.setdefault(newRecord.get(self.idKey), set()).add(objId)
108  # Add a new result record for this match.
109  self.result.append(self.makeRecord(newRecord, dataId, objId))
110  # Add any unmatched sources from the new catalog as new objects to both
111  # the joined result catalog and the reference catalog.
112  for objId in unmatchedIds:
113  newRecord = catalog.find(objId, self.idKey)
114  resultRecord = self.makeRecord(newRecord, dataId, self.nextObjId)
115  self.nextObjId += 1
116  self.result.append(resultRecord)
117  self.reference.append(resultRecord)
118 
119  def finish(self, removeAmbiguous=True):
120  """Return the final match catalog, after sorting it by object, copying it to ensure contiguousness,
121  and optionally removing ambiguous matches.
122 
123  After calling finish(), the in-progress state of the matcher is returned to the state it was
124  just after construction, with the exception of the object ID counter (which is not reset).
125  """
126  if removeAmbiguous:
127  result = self.table.Catalog(self.table)
128  for record in self.result:
129  if record.get(self.objectKey) not in self.ambiguous:
130  result.append(record)
131  else:
132  result = self.result
133  result.sort(self.objectKey)
134  result = result.copy(deep=True)
135  self.result = None
136  self.reference = None
137  self.ambiguous = set()
138  return result
139 
140 
141 class GroupView(collections.Mapping):
142  """A mapping (i.e. dict-like object) that provides convenient operations on the concatenated
143  catalogs returned by a MultiMatch object.
144 
145  A GroupView provides access to a catalog of grouped objects, in which the grouping is indicated by
146  a field for which all records in a group have the same value. Once constructed, it allows operations
147  similar to those supported by SQL "GROUP BY", such as filtering and aggregate calculation.
148  """
149 
150  @classmethod
151  def build(cls, catalog, groupField="object"):
152  """!Construct a GroupView from a concatenated catalog.
153 
154  @param[in] cls (Class; omit this argument, but Doxygen wants it mentioned)
155  @param[in] catalog Input catalog, containing records grouped by a field in which all records
156  in the same group have the same value. Must be sorted by the group field.
157  @param[in] groupField Name or Key for the field that indicates groups.
158  """
159  groupKey = catalog.schema.find(groupField).key
160  ids, indices = numpy.unique(catalog.get(groupKey), return_index=True)
161  groups = numpy.zeros(len(ids), dtype=object)
162  ends = list(indices[1:]) + [len(catalog)]
163  for n, (i1, i2) in enumerate(zip(indices, ends)):
164  # casts are a work-around for DM-8557
165  groups[n] = catalog[int(i1):int(i2)]
166  assert (groups[n].get(groupKey) == ids[n]).all()
167  return cls(catalog.schema, ids, groups)
168 
169  def __init__(self, schema, ids, groups):
170  """Direct constructor; most users should call build() instead.
171 
172  This constructor takes the constituent arrays of the object directly, to allow multiple
173  methods for construction.
174  """
175  self.schema = schema
176  self.ids = ids
177  self.groups = groups
178  self.count = sum(len(cat) for cat in self.groups)
179 
180  def __len__(self):
181  """Return the number of groups"""
182  return len(self.ids)
183 
184  def __iter__(self):
185  """Iterate over group field values"""
186  return self.ids
187 
188  def __getitem__(self, key):
189  """Return the catalog subset that corresponds to an group field value"""
190  index = numpy.searchsorted(self.ids, key)
191  if self.ids[index] != key:
192  raise KeyError("Group with ID {0} not found".format(key))
193  return self.groups[index]
194 
195  def where(self, predicate):
196  """Return a new GroupView that contains only groups for which the given predicate function
197  returns True.
198 
199  The predicate function is called once for each group, and passed a single argument: the subset
200  catalog for that group.
201  """
202  mask = numpy.zeros(len(self), dtype=bool)
203  for i in range(len(self)):
204  mask[i] = predicate(self.groups[i])
205  return type(self)(self.schema, self.ids[mask], self.groups[mask])
206 
207  def aggregate(self, function, field=None, dtype=float):
208  """!Run an aggregate function on each group, returning an array with one element for each group.
209 
210  @param[in] function Callable object that computes the aggregate value. If field is None,
211  called with the entire subset catalog as an argument. If field is not
212  None, called with an array view into that field.
213  @param[in] field A string name or Key object that indicates a single field the aggregate
214  is computed over.
215  @param[in] dtype Data type for the output array.
216  """
217  result = numpy.zeros(len(self), dtype=dtype)
218  if field is not None:
219  key = self.schema.find(field).key
220 
221  def f(cat):
222  return function(cat.get(key))
223  else:
224  f = function
225  for i in range(len(self)):
226  result[i] = f(self.groups[i])
227  return result
228 
229  def apply(self, function, field=None, dtype=float):
230  """!Run a non-aggregate function on each group, returning an array with one element for each record.
231 
232  @param[in] function Callable object that computes the aggregate value. If field is None,
233  called with the entire subset catalog as an argument. If field is not
234  None, called with an array view into that field.
235  @param[in] field A string name or Key object that indicates a single field the aggregate
236  is computed over.
237  @param[in] dtype Data type for the output array.
238  """
239  result = numpy.zeros(self.count, dtype=dtype)
240  if field is not None:
241  key = self.schema.find(field).key
242 
243  def f(cat):
244  return function(cat.get(key))
245  else:
246  f = function
247  last = 0
248  for i in range(len(self)):
249  next = last + len(self.groups[i])
250  result[last:next] = f(self.groups[i])
251  last = next
252  return result
bool all(CoordinateExpr< N > const &expr)
Return true if all elements are true.
def __init__(self, schema, dataIdFormat, coordField="coord", idField="id", radius=None, RecordClass=SourceRecord)
Definition: multiMatch.py:19
def build(cls, catalog, groupField="object")
Construct a GroupView from a concatenated catalog.
Definition: multiMatch.py:151
def apply(self, function, field=None, dtype=float)
Run a non-aggregate function on each group, returning an array with one element for each record...
Definition: multiMatch.py:229
def makeRecord(self, inputRecord, dataId, objId)
Definition: multiMatch.py:63
def __init__(self, schema, ids, groups)
Definition: multiMatch.py:169
A class representing an angle.
Definition: Angle.h:102
std::vector< Match< typename Cat::Record, typename Cat::Record > > matchRaDec(Cat const &cat, Angle radius, bool symmetric)
Compute all tuples (s1,s2,d) where s1 != s2, s1 and s2 both belong to cat, and d, the distance betwee...
def finish(self, removeAmbiguous=True)
Definition: multiMatch.py:119
def aggregate(self, function, field=None, dtype=float)
Run an aggregate function on each group, returning an array with one element for each group...
Definition: multiMatch.py:207
def add(self, catalog, dataId)
Definition: multiMatch.py:72