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

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__ = ("match_catalogs", "ellipticity_from_cat", "ellipticity", "make_matched_photom")
11def match_catalogs(inputs, photoCalibs, astromCalibs, vIds, matchRadius,
12 apply_external_wcs=False, 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 vIds]
59 ccdlist = [v['detector'] for v in vIds]
60 filtlist = [v['band'] for v in vIds]
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 vId = vIds[ind]
70 if logger:
71 logger.debug(f"{len(oldSrc)} sources in ccd {vId['detector']} visit {vId['visit']}")
73 # create temporary catalog
74 tmpCat = SourceCatalog(SourceCatalog(newSchema).table)
75 tmpCat.extend(oldSrc, mapper=mapper)
77 filtnum = filter_dict[vId['band']]
78 tmpCat['filt'] = np.repeat(filtnum, len(oldSrc))
80 tmpCat['base_PsfFlux_snr'][:] = tmpCat['base_PsfFlux_instFlux'] \
81 / tmpCat['base_PsfFlux_instFluxErr']
83 if apply_external_wcs and wcs is not None:
84 updateSourceCoords(wcs, tmpCat)
86 photoCalib.instFluxToMagnitude(tmpCat, "base_PsfFlux", "base_PsfFlux")
87 tmpCat['slot_ModelFlux_snr'][:] = (tmpCat['slot_ModelFlux_instFlux']
88 / tmpCat['slot_ModelFlux_instFluxErr'])
89 photoCalib.instFluxToMagnitude(tmpCat, "slot_ModelFlux", "slot_ModelFlux")
91 _, psf_e1, psf_e2 = ellipticity_from_cat(oldSrc, slot_shape='slot_PsfShape')
92 _, star_e1, star_e2 = ellipticity_from_cat(oldSrc, slot_shape='slot_Shape')
93 tmpCat['e1'][:] = star_e1
94 tmpCat['e2'][:] = star_e2
95 tmpCat['psf_e1'][:] = psf_e1
96 tmpCat['psf_e2'][:] = psf_e2
98 srcVis.extend(tmpCat, False)
99 mmatch.add(catalog=tmpCat, dataId=vId)
101 # Complete the match, returning a catalog that includes
102 # all matched sources with object IDs that can be used to group them.
103 matchCat = mmatch.finish()
105 # Create a mapping object that allows the matches to be manipulated
106 # as a mapping of object ID to catalog of sources.
108 # I don't think I can persist a group view, so this may need to be called in a subsequent task
109 # allMatches = GroupView.build(matchCat)
111 return srcVis, matchCat
114def ellipticity_from_cat(cat, slot_shape='slot_Shape'):
115 """Calculate the ellipticity of the Shapes in a catalog from the 2nd moments.
116 Parameters
117 ----------
118 cat : `lsst.afw.table.BaseCatalog`
119 A catalog with 'slot_Shape' defined and '_xx', '_xy', '_yy'
120 entries for the target of 'slot_Shape'.
121 E.g., 'slot_shape' defined as 'base_SdssShape'
122 And 'base_SdssShape_xx', 'base_SdssShape_xy', 'base_SdssShape_yy' defined.
123 slot_shape : str, optional
124 Specify what slot shape requested. Intended use is to get the PSF shape
125 estimates by specifying 'slot_shape=slot_PsfShape'
126 instead of the default 'slot_shape=slot_Shape'.
127 Returns
128 -------
129 e, e1, e2 : complex, float, float
130 Complex ellipticity, real part, imaginary part
131 """
132 i_xx, i_xy, i_yy = cat.get(slot_shape+'_xx'), cat.get(slot_shape+'_xy'), cat.get(slot_shape+'_yy')
133 return ellipticity(i_xx, i_xy, i_yy)
136def ellipticity(i_xx, i_xy, i_yy):
137 """Calculate ellipticity from second moments.
138 Parameters
139 ----------
140 i_xx : float or `numpy.array`
141 i_xy : float or `numpy.array`
142 i_yy : float or `numpy.array`
143 Returns
144 -------
145 e, e1, e2 : (float, float, float) or (numpy.array, numpy.array, numpy.array)
146 Complex ellipticity, real component, imaginary component
147 """
148 e = (i_xx - i_yy + 2j*i_xy) / (i_xx + i_yy)
149 e1 = np.real(e)
150 e2 = np.imag(e)
151 return e, e1, e2
154def make_matched_photom(vIds, catalogs, photo_calibs):
155 # inputs: vIds, catalogs, photo_calibs
157 # Match all input bands:
158 bands = list(set([f['band'] for f in vIds]))
160 # Should probably add an "assert" that requires bands>1...
162 empty_cat = catalogs[0].copy()
163 empty_cat.clear()
165 cat_dict = {}
166 mags_dict = {}
167 magerrs_dict = {}
168 for band in bands:
169 cat_dict[band] = empty_cat.copy()
170 mags_dict[band] = []
171 magerrs_dict[band] = []
173 for i in range(len(catalogs)):
174 for band in bands:
175 if (vIds[i]['band'] in band):
176 cat_dict[band].extend(catalogs[i].copy(deep=True))
177 mags = photo_calibs[i].instFluxToMagnitude(catalogs[i], 'base_PsfFlux')
178 mags_dict[band] = np.append(mags_dict[band], mags[:, 0])
179 magerrs_dict[band] = np.append(magerrs_dict[band], mags[:, 1])
181 for band in bands:
182 cat_tmp = cat_dict[band]
183 if cat_tmp:
184 if not cat_tmp.isContiguous():
185 cat_tmp = cat_tmp.copy(deep=True)
186 cat_tmp_final = cat_tmp.asAstropy()
187 cat_tmp_final['base_PsfFlux_mag'] = mags_dict[band]
188 cat_tmp_final['base_PsfFlux_magErr'] = magerrs_dict[band]
189 # Put the bandpass name in the column names:
190 for c in cat_tmp_final.colnames:
191 if c not in 'id':
192 cat_tmp_final[c].name = c+'_'+str(band)
193 # Write the new catalog to the dict of catalogs:
194 cat_dict[band] = cat_tmp_final
196 cat_combined = join(cat_dict[bands[1]], cat_dict[bands[0]], keys='id')
197 if len(bands) > 2:
198 for i in range(2, len(bands)):
199 cat_combined = join(cat_combined, cat_dict[bands[i]], keys='id')
201 qual_cuts = (cat_combined['base_ClassificationExtendedness_value_g'] < 0.5) &\
202 (cat_combined['base_PixelFlags_flag_saturated_g'] == False) &\
203 (cat_combined['base_PixelFlags_flag_cr_g'] == False) &\
204 (cat_combined['base_PixelFlags_flag_bad_g'] == False) &\
205 (cat_combined['base_PixelFlags_flag_edge_g'] == False) &\
206 (cat_combined['base_ClassificationExtendedness_value_r'] < 0.5) &\
207 (cat_combined['base_PixelFlags_flag_saturated_r'] == False) &\
208 (cat_combined['base_PixelFlags_flag_cr_r'] == False) &\
209 (cat_combined['base_PixelFlags_flag_bad_r'] == False) &\
210 (cat_combined['base_PixelFlags_flag_edge_r'] == False) &\
211 (cat_combined['base_ClassificationExtendedness_value_i'] < 0.5) &\
212 (cat_combined['base_PixelFlags_flag_saturated_i'] == False) &\
213 (cat_combined['base_PixelFlags_flag_cr_i'] == False) &\
214 (cat_combined['base_PixelFlags_flag_bad_i'] == False) &\
215 (cat_combined['base_PixelFlags_flag_edge_i'] == False) # noqa: E712
217 # Return the astropy table of matched catalogs:
218 return(cat_combined[qual_cuts])