LSSTApplications  17.0+124,17.0+14,17.0+73,18.0.0+37,18.0.0+80,18.0.0-4-g68ffd23+4,18.1.0-1-g0001055+12,18.1.0-1-g03d53ef+5,18.1.0-1-g1349e88+55,18.1.0-1-g2505f39+44,18.1.0-1-g5315e5e+4,18.1.0-1-g5e4b7ea+14,18.1.0-1-g7e8fceb+4,18.1.0-1-g85f8cd4+48,18.1.0-1-g8ff0b9f+4,18.1.0-1-ga2c679d+1,18.1.0-1-gd55f500+35,18.1.0-10-gb58edde+2,18.1.0-11-g0997b02+4,18.1.0-13-gfe4edf0b+12,18.1.0-14-g259bd21+21,18.1.0-19-gdb69f3f+2,18.1.0-2-g5f9922c+24,18.1.0-2-gd3b74e5+11,18.1.0-2-gfbf3545+32,18.1.0-26-g728bddb4+5,18.1.0-27-g6ff7ca9+2,18.1.0-3-g52aa583+25,18.1.0-3-g8ea57af+9,18.1.0-3-gb69f684+42,18.1.0-3-gfcaddf3+6,18.1.0-32-gd8786685a,18.1.0-4-gf3f9b77+6,18.1.0-5-g1dd662b+2,18.1.0-5-g6dbcb01+41,18.1.0-6-gae77429+3,18.1.0-7-g9d75d83+9,18.1.0-7-gae09a6d+30,18.1.0-9-gc381ef5+4,w.2019.45
LSSTDataManagementBasePackage
catalogMatches.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 
22 __all__ = ["makeMergedSchema", "copyIntoCatalog",
23  "matchesToCatalog", "matchesFromCatalog", "copyAliasMapWithPrefix"]
24 
25 import os.path
26 
27 import numpy as np
28 
29 import lsst.pex.exceptions as pexExcept
30 from ._schema import Schema
31 from ._schemaMapper import SchemaMapper
32 from ._base import BaseCatalog
33 from ._table import SimpleTable
34 from ._simple import SimpleCatalog
35 from ._source import SourceCatalog, SourceTable
36 from ._match import ReferenceMatch
37 
38 from lsst.utils import getPackageDir
39 
40 
41 def makeMapper(sourceSchema, targetSchema, sourcePrefix=None, targetPrefix=None):
42  """Create a SchemaMapper between the input source and target schemas.
43 
44  Parameters
45  ----------
46  sourceSchema : :py:class:`lsst.afw.table.Schema`
47  Input source schema that fields will be mapped from.
48  targetSchema : :py:class:`lsst.afw.table.Schema`
49  Target schema that fields will be mapped to.
50  sourcePrefix : `str`, optional
51  If set, only those keys with that prefix will be mapped.
52  targetPrefix : `str`, optional
53  If set, prepend it to the mapped (target) key name.
54 
55  Returns
56  -------
57  SchemaMapper : :py:class:`lsst.afw.table.SchemaMapper`
58  Mapping between source and target schemas.
59  """
60  m = SchemaMapper(sourceSchema, targetSchema)
61  for key, field in sourceSchema:
62  keyName = field.getName()
63  if sourcePrefix is not None:
64  if not keyName.startswith(sourcePrefix):
65  continue
66  else:
67  keyName = field.getName().replace(sourcePrefix, "", 1)
68  m.addMapping(key, (targetPrefix or "") + keyName)
69  return m
70 
71 
72 def makeMergedSchema(sourceSchema, targetSchema, sourcePrefix=None, targetPrefix=None):
73  """Return a schema that is a deep copy of a mapping between source and target schemas.
74 
75  Parameters
76  ----------
77  sourceSchema : :py:class:`lsst.afw.table.Schema`
78  Input source schema that fields will be mapped from.
79  targetSchema : :py:class:`lsst.afw.atable.Schema`
80  Target schema that fields will be mapped to.
81  sourcePrefix : `str`, optional
82  If set, only those keys with that prefix will be mapped.
83  targetPrefix : `str`, optional
84  If set, prepend it to the mapped (target) key name.
85 
86  Returns
87  -------
88  schema : :py:class:`lsst.afw.table.Schema`
89  Schema that is the result of the mapping between source and target schemas.
90  """
91  return makeMapper(sourceSchema, targetSchema, sourcePrefix, targetPrefix).getOutputSchema()
92 
93 
94 def copyIntoCatalog(catalog, target, sourceSchema=None, sourcePrefix=None, targetPrefix=None):
95  """Copy entries from one Catalog into another.
96 
97  Parameters
98  ----------
99  catalog : :py:class:`lsst.afw.table.base.Catalog`
100  Source catalog to be copied from.
101  target : :py:class:`lsst.afw.table.base.Catalog`
102  Target catalog to be copied to (edited in place).
103  sourceSchema : :py:class:`lsst.afw.table.Schema`, optional
104  Schema of source catalog.
105  sourcePrefix : `str`, optional
106  If set, only those keys with that prefix will be copied.
107  targetPrefix : `str`, optional
108  If set, prepend it to the copied (target) key name
109 
110  Returns
111  -------
112  target : :py:class:`lsst.afw.table.base.Catalog`
113  Target catalog that is edited in place.
114  """
115  if sourceSchema is None:
116  sourceSchema = catalog.schema
117 
118  targetSchema = target.schema
119  target.reserve(len(catalog))
120  for i in range(len(target), len(catalog)):
121  target.addNew()
122 
123  if len(catalog) != len(target):
124  raise RuntimeError("Length mismatch: %d vs %d" %
125  (len(catalog), len(target)))
126 
127  m = makeMapper(sourceSchema, targetSchema, sourcePrefix, targetPrefix)
128  for rFrom, rTo in zip(catalog, target):
129  rTo.assign(rFrom, m)
130 
131 
132 def matchesToCatalog(matches, matchMeta):
133  """Denormalise matches into a Catalog of "unpacked matches".
134 
135  Parameters
136  ----------
137  matches : `~lsst.afw.table.match.SimpleMatch`
138  Unpacked matches, i.e. a list of Match objects whose schema
139  has "first" and "second" attributes which, resepectively,
140  contain the reference and source catalog entries, and a
141  "distance" field (the measured distance between the reference
142  and source objects).
143  matchMeta : `~lsst.daf.base.PropertySet`
144  Metadata for matches (must have .add attribute).
145 
146  Returns
147  -------
148  mergedCatalog : :py:class:`lsst.afw.table.BaseCatalog`
149  Catalog of matches (with ref_ and src_ prefix identifiers for
150  referece and source entries, respectively, including alias
151  maps from reference and source catalogs)
152  """
153  if len(matches) == 0:
154  raise RuntimeError("No matches provided.")
155 
156  refSchema = matches[0].first.getSchema()
157  srcSchema = matches[0].second.getSchema()
158 
159  mergedSchema = makeMergedSchema(refSchema, Schema(), targetPrefix="ref_")
160  mergedSchema = makeMergedSchema(
161  srcSchema, mergedSchema, targetPrefix="src_")
162 
163  mergedSchema = copyAliasMapWithPrefix(refSchema, mergedSchema, prefix="ref_")
164  mergedSchema = copyAliasMapWithPrefix(srcSchema, mergedSchema, prefix="src_")
165 
166  distKey = mergedSchema.addField(
167  "distance", type=np.float64, doc="Distance between ref and src")
168 
169  mergedCatalog = BaseCatalog(mergedSchema)
170  copyIntoCatalog([m.first for m in matches], mergedCatalog,
171  sourceSchema=refSchema, targetPrefix="ref_")
172  copyIntoCatalog([m.second for m in matches], mergedCatalog,
173  sourceSchema=srcSchema, targetPrefix="src_")
174  for m, r in zip(matches, mergedCatalog):
175  r.set(distKey, m.distance)
176 
177  # obtain reference catalog name if one is setup
178  try:
179  catalogName = os.path.basename(getPackageDir("astrometry_net_data"))
181  catalogName = "NOT_SET"
182  matchMeta.add("REFCAT", catalogName)
183  mergedCatalog.getTable().setMetadata(matchMeta)
184 
185  return mergedCatalog
186 
187 
188 def matchesFromCatalog(catalog, sourceSlotConfig=None):
189  """Generate a list of ReferenceMatches from a Catalog of "unpacked matches".
190 
191  Parameters
192  ----------
193  catalog : :py:class:`lsst.afw.table.BaseCatalog`
194  Catalog of matches. Must have schema where reference entries
195  are prefixed with "ref_" and source entries are prefixed with
196  "src_".
197  sourceSlotConfig : `lsst.meas.base.baseMeasurement.SourceSlotConfig`, optional
198  Configuration for source slots.
199 
200  Returns
201  -------
202  matches : :py:class:`lsst.afw.table.ReferenceMatch`
203  List of matches.
204  """
205  refSchema = makeMergedSchema(
206  catalog.schema, SimpleTable.makeMinimalSchema(), sourcePrefix="ref_")
207  refCatalog = SimpleCatalog(refSchema)
208  copyIntoCatalog(catalog, refCatalog, sourcePrefix="ref_")
209 
210  srcSchema = makeMergedSchema(
211  catalog.schema, SourceTable.makeMinimalSchema(), sourcePrefix="src_")
212  srcCatalog = SourceCatalog(srcSchema)
213  copyIntoCatalog(catalog, srcCatalog, sourcePrefix="src_")
214 
215  if sourceSlotConfig is not None:
216  sourceSlotConfig.setupSchema(srcCatalog.schema)
217 
218  matches = []
219  distKey = catalog.schema.find("distance").key
220  for ref, src, cat in zip(refCatalog, srcCatalog, catalog):
221  matches.append(ReferenceMatch(ref, src, cat[distKey]))
222 
223  return matches
224 
225 
226 def copyAliasMapWithPrefix(inSchema, outSchema, prefix=""):
227  """Copy an alias map from one schema into another.
228 
229  This copies the alias map of one schema into another, optionally
230  prepending a prefix to both the "from" and "to" names of the alias
231  (the example use case here is for the "match" catalog created by
232  `lsst.meas.astrom.denormalizeMatches` where prefixes "src_" and
233  "ref_" are added to the source and reference field entries,
234  respectively).
235 
236  Parameters
237  ----------
238  inSchema : `lsst.afw.table.Schema`
239  The input schema whose `lsst.afw.table.AliasMap` is to be
240  copied to ``outSchema``.
241  outSchema : `lsst.afw.table.Schema`
242  The output schema into which the `lsst.afw.table.AliasMap`
243  from ``inSchema`` is to be copied (modified in place).
244  prefix : `str`, optional
245  An optional prefix to add to both the "from" and "to" names
246  of the alias (default is an empty string).
247 
248  Returns
249  -------
250  outSchema : `lsst.afw.table.Schema`
251  The output schema with the alias mappings from `inSchema`
252  added.
253  """
254  for k, v in inSchema.getAliasMap().items():
255  outSchema.getAliasMap().set(prefix + k, prefix + v)
256 
257  return outSchema
CatalogT< BaseRecord > BaseCatalog
Definition: fwd.h:71
def matchesFromCatalog(catalog, sourceSlotConfig=None)
def makeMergedSchema(sourceSchema, targetSchema, sourcePrefix=None, targetPrefix=None)
std::vector< SchemaItem< Flag > > * items
def matchesToCatalog(matches, matchMeta)
daf::base::PropertySet * set
Definition: fits.cc:902
std::string getPackageDir(std::string const &packageName)
return the root directory of a setup package
Definition: packaging.cc:33
def makeMapper(sourceSchema, targetSchema, sourcePrefix=None, targetPrefix=None)
Reports attempts to access elements using an invalid key.
Definition: Runtime.h:151
def copyIntoCatalog(catalog, target, sourceSchema=None, sourcePrefix=None, targetPrefix=None)
Match< SimpleRecord, SourceRecord > ReferenceMatch
Definition: fwd.h:104
def copyAliasMapWithPrefix(inSchema, outSchema, prefix="")
SortedCatalogT< SimpleRecord > SimpleCatalog
Definition: fwd.h:79