lsst.afw  14.0-25-g0e8fc950e+3
catalogMatches.py
Go to the documentation of this file.
1 #
2 # LSST Data Management System
3 # Copyright 2008-2016 AURA/LSST.
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 <https://www.lsstcorp.org/LegalNotices/>.
21 #
22 from __future__ import absolute_import, division, print_function
23 
24 __all__ = ["makeMergedSchema", "copyIntoCatalog",
25  "matchesToCatalog", "matchesFromCatalog"]
26 
27 import os.path
28 
29 from builtins import zip
30 from builtins import range
31 import numpy as np
32 
33 from .schema import Schema
34 from .schemaMapper import SchemaMapper
35 from .base import BaseCatalog
36 from .simple import SimpleCatalog, SimpleTable
37 from .source import SourceCatalog, SourceTable
38 from .match import ReferenceMatch
39 
40 from lsst.utils import getPackageDir
41 
42 
43 def makeMapper(sourceSchema, targetSchema, sourcePrefix=None, targetPrefix=None):
44  """Create a SchemaMapper between the input source and target schemas
45 
46  \param[in] sourceSchema input source schema that fields will be mapped from
47  \param[in] targetSchema target schema that fields will be mapped to
48  \param[in] sourcePrefix if set, only those keys with that prefix will be mapped
49  \param[in] targetPrefix if set, prepend it to the mapped (target) key name
50 
51  \return SchemaMapper between source and target schemas
52  """
53  m = SchemaMapper(sourceSchema, targetSchema)
54  for key, field in sourceSchema:
55  keyName = field.getName()
56  if sourcePrefix is not None:
57  if not keyName.startswith(sourcePrefix):
58  continue
59  else:
60  keyName = field.getName().replace(sourcePrefix, "", 1)
61  m.addMapping(key, (targetPrefix or "") + keyName)
62  return m
63 
64 
65 def makeMergedSchema(sourceSchema, targetSchema, sourcePrefix=None, targetPrefix=None):
66  """Return a schema that is a deep copy of a mapping between source and target schemas
67  \param[in] sourceSchema input source schema that fields will be mapped from
68  \param[in] targetSchema target schema that fields will be mapped to
69  \param[in] sourcePrefix if set, only those keys with that prefix will be mapped
70  \param[in] targetPrefix if set, prepend it to the mapped (target) key name
71 
72  \return schema schema that is the result of the mapping between source and target schemas
73  """
74  return makeMapper(sourceSchema, targetSchema, sourcePrefix, targetPrefix).getOutputSchema()
75 
76 
77 def copyIntoCatalog(catalog, target, sourceSchema=None, sourcePrefix=None, targetPrefix=None):
78  """Copy entries from one Catalog into another
79 
80  \param[in] catalog source catalog to be copied from
81  \param[in/out] target target catalog to be copied to (edited in place)
82  \param[in] souceSchema schema of source catalog (optional)
83  \param[in] sourcePrefix if set, only those keys with that prefix will be copied
84  \param[in] targetPrefix if set, prepend it to the copied (target) key name
85  """
86  if sourceSchema is None:
87  sourceSchema = catalog.schema
88 
89  targetSchema = target.schema
90  target.reserve(len(catalog))
91  for i in range(len(target), len(catalog)):
92  target.addNew()
93 
94  if len(catalog) != len(target):
95  raise RuntimeError("Length mismatch: %d vs %d" %
96  (len(catalog), len(target)))
97 
98  m = makeMapper(sourceSchema, targetSchema, sourcePrefix, targetPrefix)
99  for rFrom, rTo in zip(catalog, target):
100  rTo.assign(rFrom, m)
101 
102 
103 def matchesToCatalog(matches, matchMeta):
104  """Denormalise matches into a Catalog of "unpacked matches"
105 
106  \param[in] matches unpacked matches, i.e. a list of Match objects whose schema
107  has "first" and "second" attributes which, resepectively, contain the
108  reference and source catalog entries, and a "distance" field (the
109  measured distance between the reference and source objects)
110  \param[in] matchMeta metadata for matches (must have .add attribute)
111 
112  \return lsst.afw.table.BaseCatalog of matches (with ref_ and src_ prefix identifiers
113  for referece and source entries, respectively)
114  """
115  if len(matches) == 0:
116  raise RuntimeError("No matches provided.")
117 
118  refSchema = matches[0].first.getSchema()
119  srcSchema = matches[0].second.getSchema()
120 
121  mergedSchema = makeMergedSchema(refSchema, Schema(), targetPrefix="ref_")
122  mergedSchema = makeMergedSchema(
123  srcSchema, mergedSchema, targetPrefix="src_")
124  distKey = mergedSchema.addField(
125  "distance", type=np.float64, doc="Distance between ref and src")
126 
127  mergedCatalog = BaseCatalog(mergedSchema)
128  copyIntoCatalog([m.first for m in matches], mergedCatalog,
129  sourceSchema=refSchema, targetPrefix="ref_")
130  copyIntoCatalog([m.second for m in matches], mergedCatalog,
131  sourceSchema=srcSchema, targetPrefix="src_")
132  for m, r in zip(matches, mergedCatalog):
133  r.set(distKey, m.distance)
134 
135  # obtain reference catalog name if one is setup
136  try:
137  catalogName = os.path.basename(getPackageDir("astrometry_net_data"))
138  except:
139  catalogName = "NOT_SET"
140  matchMeta.add("REFCAT", catalogName)
141  mergedCatalog.getTable().setMetadata(matchMeta)
142 
143  return mergedCatalog
144 
145 
146 def matchesFromCatalog(catalog, sourceSlotConfig=None):
147  """Generate a list of ReferenceMatches from a Catalog of "unpacked matches"
148 
149  \param[in] catalog catalog of matches. Must have schema where reference entries are
150  prefixed with "ref_" and source entries are prefixed with "src_"
151  \param[in] sourceSlotConfig an lsst.meas.base.baseMeasurement.SourceSlotConfig configuration
152  for source slots (optional)
153 
154  \returns lsst.afw.table.ReferenceMatch of matches
155  """
156  refSchema = makeMergedSchema(
157  catalog.schema, SimpleTable.makeMinimalSchema(), sourcePrefix="ref_")
158  refCatalog = SimpleCatalog(refSchema)
159  copyIntoCatalog(catalog, refCatalog, sourcePrefix="ref_")
160 
161  srcSchema = makeMergedSchema(
162  catalog.schema, SourceTable.makeMinimalSchema(), sourcePrefix="src_")
163  srcCatalog = SourceCatalog(srcSchema)
164  copyIntoCatalog(catalog, srcCatalog, sourcePrefix="src_")
165 
166  if sourceSlotConfig is not None:
167  sourceSlotConfig.setupSchema(srcCatalog.schema)
168 
169  matches = []
170  distKey = catalog.schema.find("distance").key
171  for ref, src, cat in zip(refCatalog, srcCatalog, catalog):
172  matches.append(ReferenceMatch(ref, src, cat[distKey]))
173 
174  return matches
CatalogT< BaseRecord > BaseCatalog
Definition: fwd.h:71
def matchesFromCatalog(catalog, sourceSlotConfig=None)
def makeMergedSchema(sourceSchema, targetSchema, sourcePrefix=None, targetPrefix=None)
def matchesToCatalog(matches, matchMeta)
def makeMapper(sourceSchema, targetSchema, sourcePrefix=None, targetPrefix=None)
def copyIntoCatalog(catalog, target, sourceSchema=None, sourcePrefix=None, targetPrefix=None)
Match< SimpleRecord, SourceRecord > ReferenceMatch
Definition: fwd.h:104
SortedCatalogT< SimpleRecord > SimpleCatalog
Definition: fwd.h:79