Coverage for python/lsst/faro/utils/matcher.py : 5%

Hot-keys on this page
r m x p toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
1from lsst.afw.table import (SchemaMapper, Field,
2 MultiMatch, SimpleRecord,
3 SourceCatalog, updateSourceCoords)
5import numpy as np
6from astropy.table import join, Table
8__all__ = ("matchCatalogs", "ellipticityFromCat", "ellipticity", "makeMatchedPhotom",
9 "mergeCatalogs")
12def matchCatalogs(inputs, photoCalibs, astromCalibs, dataIds, matchRadius, logger=None):
13 schema = inputs[0].schema
14 mapper = SchemaMapper(schema)
15 mapper.addMinimalSchema(schema)
16 mapper.addOutputField(Field[float]('base_PsfFlux_snr',
17 'PSF flux SNR'))
18 mapper.addOutputField(Field[float]('base_PsfFlux_mag',
19 'PSF magnitude'))
20 mapper.addOutputField(Field[float]('base_PsfFlux_magErr',
21 'PSF magnitude uncertainty'))
22 # Needed because addOutputField(... 'slot_ModelFlux_mag') will add a field with that literal name
23 aliasMap = schema.getAliasMap()
24 # Possibly not needed since base_GaussianFlux is the default, but this ought to be safe
25 modelName = aliasMap['slot_ModelFlux'] if 'slot_ModelFlux' in aliasMap.keys() else 'base_GaussianFlux'
26 mapper.addOutputField(Field[float](f'{modelName}_mag',
27 'Model magnitude'))
28 mapper.addOutputField(Field[float](f'{modelName}_magErr',
29 'Model magnitude uncertainty'))
30 mapper.addOutputField(Field[float](f'{modelName}_snr',
31 'Model flux snr'))
32 mapper.addOutputField(Field[float]('e1',
33 'Source Ellipticity 1'))
34 mapper.addOutputField(Field[float]('e2',
35 'Source Ellipticity 1'))
36 mapper.addOutputField(Field[float]('psf_e1',
37 'PSF Ellipticity 1'))
38 mapper.addOutputField(Field[float]('psf_e2',
39 'PSF Ellipticity 1'))
40 mapper.addOutputField(Field[np.int32]('filt',
41 'filter code'))
42 newSchema = mapper.getOutputSchema()
43 newSchema.setAliasMap(schema.getAliasMap())
45 # Create an object that matches multiple catalogs with same schema
46 mmatch = MultiMatch(newSchema,
47 dataIdFormat={'visit': np.int32, 'detector': np.int32},
48 radius=matchRadius,
49 RecordClass=SimpleRecord)
51 # create the new extended source catalog
52 srcVis = SourceCatalog(newSchema)
54 filter_dict = {'u': 1, 'g': 2, 'r': 3, 'i': 4, 'z': 5, 'y': 6,
55 'HSC-U': 1, 'HSC-G': 2, 'HSC-R': 3, 'HSC-I': 4, 'HSC-Z': 5, 'HSC-Y': 6}
57 # Sort by visit, detector, then filter
58 vislist = [v['visit'] for v in dataIds]
59 ccdlist = [v['detector'] for v in dataIds]
60 filtlist = [v['band'] for v in dataIds]
61 tab_vids = Table([vislist, ccdlist, filtlist], names=['vis', 'ccd', 'filt'])
62 sortinds = np.argsort(tab_vids, order=('vis', 'ccd', 'filt'))
64 for ind in sortinds:
65 oldSrc = inputs[ind]
66 photoCalib = photoCalibs[ind]
67 wcs = astromCalibs[ind]
68 dataId = dataIds[ind]
70 if logger:
71 logger.debug(f"{len(oldSrc)} sources in ccd {dataId['detector']} visit {dataId['visit']}")
73 # create temporary catalog
74 tmpCat = SourceCatalog(SourceCatalog(newSchema).table)
75 tmpCat.extend(oldSrc, mapper=mapper)
77 filtnum = filter_dict[dataId['band']]
78 tmpCat['filt'] = np.repeat(filtnum, len(oldSrc))
80 tmpCat['base_PsfFlux_snr'][:] = tmpCat['base_PsfFlux_instFlux'] \
81 / tmpCat['base_PsfFlux_instFluxErr']
83 updateSourceCoords(wcs, tmpCat)
85 photoCalib.instFluxToMagnitude(tmpCat, "base_PsfFlux", "base_PsfFlux")
86 tmpCat['slot_ModelFlux_snr'][:] = (tmpCat['slot_ModelFlux_instFlux']
87 / tmpCat['slot_ModelFlux_instFluxErr'])
88 photoCalib.instFluxToMagnitude(tmpCat, "slot_ModelFlux", "slot_ModelFlux")
90 _, psf_e1, psf_e2 = ellipticityFromCat(oldSrc, slot_shape='slot_PsfShape')
91 _, star_e1, star_e2 = ellipticityFromCat(oldSrc, slot_shape='slot_Shape')
92 tmpCat['e1'][:] = star_e1
93 tmpCat['e2'][:] = star_e2
94 tmpCat['psf_e1'][:] = psf_e1
95 tmpCat['psf_e2'][:] = psf_e2
97 srcVis.extend(tmpCat, False)
98 mmatch.add(catalog=tmpCat, dataId=dataId)
100 # Complete the match, returning a catalog that includes
101 # all matched sources with object IDs that can be used to group them.
102 matchCat = mmatch.finish()
104 # Create a mapping object that allows the matches to be manipulated
105 # as a mapping of object ID to catalog of sources.
107 # I don't think I can persist a group view, so this may need to be called in a subsequent task
108 # allMatches = GroupView.build(matchCat)
110 return srcVis, matchCat
113def ellipticityFromCat(cat, slot_shape='slot_Shape'):
114 """Calculate the ellipticity of the Shapes in a catalog from the 2nd moments.
115 Parameters
116 ----------
117 cat : `lsst.afw.table.BaseCatalog`
118 A catalog with 'slot_Shape' defined and '_xx', '_xy', '_yy'
119 entries for the target of 'slot_Shape'.
120 E.g., 'slot_shape' defined as 'base_SdssShape'
121 And 'base_SdssShape_xx', 'base_SdssShape_xy', 'base_SdssShape_yy' defined.
122 slot_shape : str, optional
123 Specify what slot shape requested. Intended use is to get the PSF shape
124 estimates by specifying 'slot_shape=slot_PsfShape'
125 instead of the default 'slot_shape=slot_Shape'.
126 Returns
127 -------
128 e, e1, e2 : complex, float, float
129 Complex ellipticity, real part, imaginary part
130 """
131 i_xx, i_xy, i_yy = cat.get(slot_shape+'_xx'), cat.get(slot_shape+'_xy'), cat.get(slot_shape+'_yy')
132 return ellipticity(i_xx, i_xy, i_yy)
135def ellipticity(i_xx, i_xy, i_yy):
136 """Calculate ellipticity from second moments.
137 Parameters
138 ----------
139 i_xx : float or `numpy.array`
140 i_xy : float or `numpy.array`
141 i_yy : float or `numpy.array`
142 Returns
143 -------
144 e, e1, e2 : (float, float, float) or (numpy.array, numpy.array, numpy.array)
145 Complex ellipticity, real component, imaginary component
146 """
147 e = (i_xx - i_yy + 2j*i_xy) / (i_xx + i_yy)
148 e1 = np.real(e)
149 e2 = np.imag(e)
150 return e, e1, e2
153def makeMatchedPhotom(dataIds, catalogs, photoCalibs):
154 # inputs: dataIds, catalogs, photoCalibs
156 # Match all input bands:
157 bands = list(set([f['band'] for f in dataIds]))
159 # Should probably add an "assert" that requires bands>1...
161 empty_cat = catalogs[0].copy()
162 empty_cat.clear()
164 cat_dict = {}
165 mags_dict = {}
166 magerrs_dict = {}
167 for band in bands:
168 cat_dict[band] = empty_cat.copy()
169 mags_dict[band] = []
170 magerrs_dict[band] = []
172 for i in range(len(catalogs)):
173 for band in bands:
174 if (dataIds[i]['band'] in band):
175 cat_dict[band].extend(catalogs[i].copy(deep=True))
176 mags = photoCalibs[i].instFluxToMagnitude(catalogs[i], 'base_PsfFlux')
177 mags_dict[band] = np.append(mags_dict[band], mags[:, 0])
178 magerrs_dict[band] = np.append(magerrs_dict[band], mags[:, 1])
180 for band in bands:
181 cat_tmp = cat_dict[band]
182 if cat_tmp:
183 if not cat_tmp.isContiguous():
184 cat_tmp = cat_tmp.copy(deep=True)
185 cat_tmp_final = cat_tmp.asAstropy()
186 cat_tmp_final['base_PsfFlux_mag'] = mags_dict[band]
187 cat_tmp_final['base_PsfFlux_magErr'] = magerrs_dict[band]
188 # Put the bandpass name in the column names:
189 for c in cat_tmp_final.colnames:
190 if c not in 'id':
191 cat_tmp_final[c].name = c+'_'+str(band)
192 # Write the new catalog to the dict of catalogs:
193 cat_dict[band] = cat_tmp_final
195 cat_combined = join(cat_dict[bands[1]], cat_dict[bands[0]], keys='id')
196 if len(bands) > 2:
197 for i in range(2, len(bands)):
198 cat_combined = join(cat_combined, cat_dict[bands[i]], keys='id')
200 qual_cuts = (cat_combined['base_ClassificationExtendedness_value_g'] < 0.5) &\
201 (cat_combined['base_PixelFlags_flag_saturated_g'] == False) &\
202 (cat_combined['base_PixelFlags_flag_cr_g'] == False) &\
203 (cat_combined['base_PixelFlags_flag_bad_g'] == False) &\
204 (cat_combined['base_PixelFlags_flag_edge_g'] == False) &\
205 (cat_combined['base_ClassificationExtendedness_value_r'] < 0.5) &\
206 (cat_combined['base_PixelFlags_flag_saturated_r'] == False) &\
207 (cat_combined['base_PixelFlags_flag_cr_r'] == False) &\
208 (cat_combined['base_PixelFlags_flag_bad_r'] == False) &\
209 (cat_combined['base_PixelFlags_flag_edge_r'] == False) &\
210 (cat_combined['base_ClassificationExtendedness_value_i'] < 0.5) &\
211 (cat_combined['base_PixelFlags_flag_saturated_i'] == False) &\
212 (cat_combined['base_PixelFlags_flag_cr_i'] == False) &\
213 (cat_combined['base_PixelFlags_flag_bad_i'] == False) &\
214 (cat_combined['base_PixelFlags_flag_edge_i'] == False) # noqa: E712
216 # Return the astropy table of matched catalogs:
217 return(cat_combined[qual_cuts])
220def mergeCatalogs(catalogs,
221 photoCalibs=None, astromCalibs=None,
222 models=['slot_PsfFlux'], applyExternalWcs=False):
223 """Merge catalogs and optionally apply photometric and astrometric calibrations.
224 """
226 schema = catalogs[0].schema
227 mapper = SchemaMapper(schema)
228 mapper.addMinimalSchema(schema)
229 aliasMap = schema.getAliasMap()
230 for model in models:
231 modelName = aliasMap[model] if model in aliasMap.keys() else model
232 mapper.addOutputField(Field[float](f'{modelName}_mag',
233 f'{modelName} magnitude'))
234 mapper.addOutputField(Field[float](f'{modelName}_magErr',
235 f'{modelName} magnitude uncertainty'))
236 newSchema = mapper.getOutputSchema()
237 newSchema.setAliasMap(schema.getAliasMap())
239 size = sum([len(cat) for cat in catalogs])
240 catalog = SourceCatalog(newSchema)
241 catalog.reserve(size)
243 for ii in range(0, len(catalogs)):
244 cat = catalogs[ii]
246 # Create temporary catalog. Is this step needed?
247 tempCat = SourceCatalog(SourceCatalog(newSchema).table)
248 tempCat.extend(cat, mapper=mapper)
250 if applyExternalWcs and astromCalibs is not None:
251 wcs = astromCalibs[ii]
252 updateSourceCoords(wcs, tempCat)
254 if photoCalibs is not None:
255 photoCalib = photoCalibs[ii]
256 for model in models:
257 modelName = aliasMap[model] if model in aliasMap.keys() else model
258 photoCalib.instFluxToMagnitude(tempCat, modelName, modelName)
260 catalog.extend(tempCat)
262 return catalog