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