lsst.afw  13.0-49-g6f23dda
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Groups Pages
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  # Temporary dict mapping object ID to reference record
84  # Will remove from this dict as objects are matched.
85  objById = {record.get(self.objectKey):
86  record for record in self.reference}
87  # Temporary dict mapping source ID to new catalog record.
88  # Will remove from this dict as objects are matched.
89  newById = {record.get(self.idKey): record for record in catalog}
90  # Temporary dict mapping new source ID to a set of associated objects.
91  newToObj = {}
92  matches = lsst.afw.table.matchRaDec(
93  self.reference, catalog, self.radius)
94  for refRecord, newRecord, distance in matches:
95  objId = refRecord.get(self.objectKey)
96  if objById.pop(objId, None) is None:
97  # We've already matched this object against another new source,
98  # mark it as ambiguous.
99  self.ambiguous.add(objId)
100  if newById.pop(newRecord.get(self.idKey), None) is None:
101  # We've already matched this new source to one or more other objects
102  # Mark all involved objects as ambiguous
103  self.ambiguous.add(objId)
104  self.ambiguous |= newToObj.get(
105  newRecord.get(self.idKey), set())
106  # Populate the newToObj dict (setdefault trick is an idiom for
107  # appending to a dict-of-sets)
108  newToObj.setdefault(newRecord.get(self.idKey), set()).add(objId)
109  # Add a new result record for this match.
110  self.result.append(self.makeRecord(newRecord, dataId, objId))
111  # Add any unmatched sources from the new catalog as new objects to both the joined result catalog
112  # and the reference catalog.
113  for newRecord in newById.values():
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] catalog Input catalog, containing records grouped by a field in which all records
155  in the same group have the same value. Must be sorted by the group field.
156  @param[in] groupField Name or Key for the field that indicates groups.
157  """
158  groupKey = catalog.schema.find(groupField).key
159  ids, indices = numpy.unique(catalog.get(groupKey), return_index=True)
160  groups = numpy.zeros(len(ids), dtype=object)
161  ends = list(indices[1:]) + [len(catalog)]
162  for n, (i1, i2) in enumerate(zip(indices, ends)):
163  # casts are a work-around for DM-8557
164  groups[n] = catalog[int(i1):int(i2)]
165  assert (groups[n].get(groupKey) == ids[n]).all()
166  return cls(catalog.schema, ids, groups)
167 
168  def __init__(self, schema, ids, groups):
169  """Direct constructor; most users should call build() instead.
170 
171  This constructor takes the constituent arrays of the object directly, to allow multiple
172  methods for construction.
173  """
174  self.schema = schema
175  self.ids = ids
176  self.groups = groups
177  self.count = sum(len(cat) for cat in self.groups)
178 
179  def __len__(self):
180  """Return the number of groups"""
181  return len(self.ids)
182 
183  def __iter__(self):
184  """Iterate over group field values"""
185  return self.ids
186 
187  def __getitem__(self, key):
188  """Return the catalog subset that corresponds to an group field value"""
189  index = numpy.searchsorted(self.ids, key)
190  if self.ids[index] != key:
191  raise KeyError("Group with ID {0} not found".format(key))
192  return self.groups[index]
193 
194  def where(self, predicate):
195  """Return a new GroupView that contains only groups for which the given predicate function
196  returns True.
197 
198  The predicate function is called once for each group, and passed a single argument: the subset
199  catalog for that group.
200  """
201  mask = numpy.zeros(len(self), dtype=bool)
202  for i in range(len(self)):
203  mask[i] = predicate(self.groups[i])
204  return type(self)(self.schema, self.ids[mask], self.groups[mask])
205 
206  def aggregate(self, function, field=None, dtype=float):
207  """!Run an aggregate function on each group, returning an array with one element for each group.
208 
209  @param[in] function Callable object that computes the aggregate value. If field is None,
210  called with the entire subset catalog as an argument. If field is not
211  None, called with an array view into that field.
212  @param[in] field A string name or Key object that indicates a single field the aggregate
213  is computed over.
214  @param[in] dtype Data type for the output array.
215  """
216  result = numpy.zeros(len(self), dtype=dtype)
217  if field is not None:
218  key = self.schema.find(field).key
219 
220  def f(cat):
221  return function(cat.get(key))
222  else:
223  f = function
224  for i in range(len(self)):
225  result[i] = f(self.groups[i])
226  return result
227 
228  def apply(self, function, field=None, dtype=float):
229  """!Run a non-aggregate function on each group, returning an array with one element for each record.
230 
231  @param[in] function Callable object that computes the aggregate value. If field is None,
232  called with the entire subset catalog as an argument. If field is not
233  None, called with an array view into that field.
234  @param[in] field A string name or Key object that indicates a single field the aggregate
235  is computed over.
236  @param[in] dtype Data type for the output array.
237  """
238  result = numpy.zeros(self.count, dtype=dtype)
239  if field is not None:
240  key = self.schema.find(field).key
241 
242  def f(cat):
243  return function(cat.get(key))
244  else:
245  f = function
246  last = 0
247  for i in range(len(self)):
248  next = last + len(self.groups[i])
249  result[last:next] = f(self.groups[i])
250  last = next
251  return result
bool all(CoordinateExpr< N > const &expr)
Return true if all elements are true.
def aggregate
Run an aggregate function on each group, returning an array with one element for each group...
Definition: multiMatch.py:206
def build
Construct a GroupView from a concatenated catalog.
Definition: multiMatch.py:151
A class representing an angle.
Definition: Angle.h:103
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 apply
Run a non-aggregate function on each group, returning an array with one element for each record...
Definition: multiMatch.py:228