Hide keyboard shortcuts

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

1# See COPYRIGHT file at the top of the source tree. 

2# 

3# This file is part of fgcmcal. 

4# 

5# Developed for the LSST Data Management System. 

6# This product includes software developed by the LSST Project 

7# (https://www.lsst.org). 

8# See the COPYRIGHT file at the top-level directory of this distribution 

9# for details of code ownership. 

10# 

11# This program is free software: you can redistribute it and/or modify 

12# it under the terms of the GNU General Public License as published by 

13# the Free Software Foundation, either version 3 of the License, or 

14# (at your option) any later version. 

15# 

16# This program is distributed in the hope that it will be useful, 

17# but WITHOUT ANY WARRANTY; without even the implied warranty of 

18# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 

19# GNU General Public License for more details. 

20# 

21# You should have received a copy of the GNU General Public License 

22# along with this program. If not, see <https://www.gnu.org/licenses/>. 

23"""Load reference catalog objects for input to FGCM. 

24 

25This task will load multi-band reference objects and apply color terms (if 

26configured). This wrapper around LoadReferenceObjects task also allows loading 

27by healpix pixel (the native pixelization of fgcm), and is self-contained so 

28the task can be called by third-party code. 

29""" 

30 

31import numpy as np 

32import healpy as hp 

33from astropy import units 

34 

35import lsst.pex.config as pexConfig 

36import lsst.pipe.base as pipeBase 

37from lsst.meas.algorithms import LoadIndexedReferenceObjectsTask, ReferenceSourceSelectorTask 

38from lsst.meas.algorithms import getRefFluxField 

39from lsst.pipe.tasks.colorterms import ColortermLibrary 

40from lsst.afw.image import abMagErrFromFluxErr 

41import lsst.geom 

42 

43__all__ = ['FgcmLoadReferenceCatalogConfig', 'FgcmLoadReferenceCatalogTask'] 

44 

45 

46class FgcmLoadReferenceCatalogConfig(pexConfig.Config): 

47 """Config for FgcmLoadReferenceCatalogTask""" 

48 

49 refObjLoader = pexConfig.ConfigurableField( 

50 target=LoadIndexedReferenceObjectsTask, 

51 doc="Reference object loader for photometry", 

52 ) 

53 refFilterMap = pexConfig.DictField( 

54 doc="Mapping from camera 'filterName' to reference filter name.", 

55 keytype=str, 

56 itemtype=str, 

57 default={}, 

58 ) 

59 applyColorTerms = pexConfig.Field( 

60 doc=("Apply photometric color terms to reference stars?" 

61 "Requires that colorterms be set to a ColorTermLibrary"), 

62 dtype=bool, 

63 default=True 

64 ) 

65 colorterms = pexConfig.ConfigField( 

66 doc="Library of photometric reference catalog name to color term dict.", 

67 dtype=ColortermLibrary, 

68 ) 

69 referenceSelector = pexConfig.ConfigurableField( 

70 target=ReferenceSourceSelectorTask, 

71 doc="Selection of reference sources", 

72 ) 

73 

74 def validate(self): 

75 super().validate() 

76 if not self.refFilterMap: 

77 msg = 'Must set refFilterMap' 

78 raise pexConfig.FieldValidationError(FgcmLoadReferenceCatalogConfig.refFilterMap, self, msg) 

79 if self.applyColorTerms and len(self.colorterms.data) == 0: 

80 msg = "applyColorTerms=True requires the `colorterms` field be set to a ColortermLibrary." 

81 raise pexConfig.FieldValidationError(FgcmLoadReferenceCatalogConfig.colorterms, self, msg) 

82 

83 

84class FgcmLoadReferenceCatalogTask(pipeBase.Task): 

85 """ 

86 Load multi-band reference objects from a reference catalog. 

87 

88 Paramters 

89 --------- 

90 butler: `lsst.daf.persistence.Butler` 

91 Data butler for reading catalogs 

92 """ 

93 ConfigClass = FgcmLoadReferenceCatalogConfig 

94 _DefaultName = 'fgcmLoadReferenceCatalog' 

95 

96 def __init__(self, butler, *args, **kwargs): 

97 """Construct an FgcmLoadReferenceCatalogTask 

98 

99 Parameters 

100 ---------- 

101 butler: `lsst.daf.persistence.Buter` 

102 Data butler for reading catalogs. 

103 """ 

104 pipeBase.Task.__init__(self, *args, **kwargs) 

105 self.butler = butler 

106 self.makeSubtask('refObjLoader', butler=butler) 

107 self.makeSubtask('referenceSelector') 

108 self._fluxFilters = None 

109 self._fluxFields = None 

110 self._referenceFilter = None 

111 

112 def getFgcmReferenceStarsHealpix(self, nside, pixel, filterList, nest=False): 

113 """ 

114 Get a reference catalog that overlaps a healpix pixel, using multiple 

115 filters. In addition, apply colorterms if available. 

116 

117 Return format is a numpy recarray for use with fgcm. 

118 

119 Parameters 

120 ---------- 

121 nside: `int` 

122 Healpix nside of pixel to load 

123 pixel: `int` 

124 Healpix pixel of pixel to load 

125 filterList: `list` 

126 list of `str` of camera filter names. 

127 nest: `bool`, optional 

128 Is the pixel in nest format? Default is False. 

129 

130 Returns 

131 ------- 

132 fgcmRefCat: `np.recarray` 

133 Numpy recarray with the following fields: 

134 ra: `np.float64` 

135 Right ascension, degrees 

136 dec: `np.float64` 

137 Declination, degrees 

138 refMag: (`np.float32`, len(filterList)) 

139 Reference magnitude for filterList bands 

140 Will be 99 for non-detections. 

141 refMagErr: (`np.float32`, len(filterList)) 

142 Reference magnitude error for filterList bands 

143 Will be 99 for non-detections. 

144 """ 

145 

146 # Determine the size of the sky circle to load 

147 theta, phi = hp.pix2ang(nside, pixel, nest=nest) 

148 center = lsst.geom.SpherePoint(phi * lsst.geom.radians, (np.pi/2. - theta) * lsst.geom.radians) 

149 

150 corners = hp.boundaries(nside, pixel, step=1, nest=nest) 

151 theta_phi = hp.vec2ang(np.transpose(corners)) 

152 

153 radius = 0.0 * lsst.geom.radians 

154 for ctheta, cphi in zip(*theta_phi): 

155 rad = center.separation(lsst.geom.SpherePoint(cphi * lsst.geom.radians, 

156 (np.pi/2. - ctheta) * lsst.geom.radians)) 

157 if (rad > radius): 

158 radius = rad 

159 

160 # Load the fgcm-format reference catalog 

161 fgcmRefCat = self.getFgcmReferenceStarsSkyCircle(center.getRa().asDegrees(), 

162 center.getDec().asDegrees(), 

163 radius.asDegrees(), 

164 filterList) 

165 catPix = hp.ang2pix(nside, np.radians(90.0 - fgcmRefCat['dec']), 

166 np.radians(fgcmRefCat['ra']), nest=nest) 

167 

168 inPix, = np.where(catPix == pixel) 

169 

170 return fgcmRefCat[inPix] 

171 

172 def getFgcmReferenceStarsSkyCircle(self, ra, dec, radius, filterList): 

173 """ 

174 Get a reference catalog that overlaps a circular sky region, using 

175 multiple filters. In addition, apply colorterms if available. 

176 

177 Return format is a numpy recarray for use with fgcm. 

178 

179 Parameters 

180 ---------- 

181 ra: `float` 

182 ICRS right ascension, degrees. 

183 dec: `float` 

184 ICRS declination, degrees. 

185 radius: `float` 

186 Radius to search, degrees. 

187 filterList: `list` 

188 list of `str` of camera filter names. 

189 

190 Returns 

191 ------- 

192 fgcmRefCat: `np.recarray` 

193 Numpy recarray with the following fields: 

194 ra: `np.float64` 

195 Right ascension, degrees 

196 dec: `np.float64` 

197 Declination, degrees 

198 refMag: (`np.float32`, len(filterList)) 

199 Reference magnitude for filterList bands 

200 Will be 99 for non-detections. 

201 refMagErr: (`np.float32`, len(filterList)) 

202 Reference magnitude error for filterList bands 

203 Will be 99 for non-detections. 

204 """ 

205 

206 center = lsst.geom.SpherePoint(ra * lsst.geom.degrees, dec * lsst.geom.degrees) 

207 

208 # Check if we haev previously cached values for the fluxFields 

209 if self._fluxFilters is None or self._fluxFilters != filterList: 

210 self._determine_flux_fields(center, filterList) 

211 

212 skyCircle = self.refObjLoader.loadSkyCircle(center, 

213 radius * lsst.geom.degrees, 

214 self._referenceFilter) 

215 

216 if not skyCircle.refCat.isContiguous(): 

217 refCat = skyCircle.refCat.copy(deep=True) 

218 else: 

219 refCat = skyCircle.refCat 

220 

221 # Select on raw (uncorrected) catalog, where the errors should make more sense 

222 goodSources = self.referenceSelector.selectSources(refCat) 

223 selected = goodSources.selected 

224 

225 fgcmRefCat = np.zeros(np.sum(selected), dtype=[('ra', 'f8'), 

226 ('dec', 'f8'), 

227 ('refMag', 'f4', len(filterList)), 

228 ('refMagErr', 'f4', len(filterList))]) 

229 if fgcmRefCat.size == 0: 

230 # Return an empty catalog if we don't have any selected sources 

231 return fgcmRefCat 

232 

233 # The ra/dec native Angle format is radians 

234 # We determine the conversion from the native units (typically 

235 # radians) to degrees for the first observation. This allows us 

236 # to treate ra/dec as numpy arrays rather than Angles, which would 

237 # be approximately 600x slower. 

238 

239 conv = refCat[0]['coord_ra'].asDegrees() / float(refCat[0]['coord_ra']) 

240 fgcmRefCat['ra'] = refCat['coord_ra'][selected] * conv 

241 fgcmRefCat['dec'] = refCat['coord_dec'][selected] * conv 

242 

243 # Default (unset) values are 99.0 

244 fgcmRefCat['refMag'][:, :] = 99.0 

245 fgcmRefCat['refMagErr'][:, :] = 99.0 

246 

247 if self.config.applyColorTerms: 

248 try: 

249 refCatName = self.refObjLoader.ref_dataset_name 

250 except AttributeError: 

251 # NOTE: we need this try:except: block in place until we've 

252 # completely removed a.net support 

253 raise RuntimeError("Cannot perform colorterm corrections with a.net refcats.") 

254 

255 for i, (filterName, fluxField) in enumerate(zip(self._fluxFilters, self._fluxFields)): 

256 if fluxField is None: 

257 continue 

258 

259 self.log.debug("Applying color terms for filtername=%r" % (filterName)) 

260 

261 colorterm = self.config.colorterms.getColorterm( 

262 filterName=filterName, photoCatName=refCatName, doRaise=True) 

263 

264 refMag, refMagErr = colorterm.getCorrectedMagnitudes(refCat, filterName) 

265 

266 # nan_to_num replaces nans with zeros, and this ensures that we select 

267 # magnitudes that both filter out nans and are not very large (corresponding 

268 # to very small fluxes), as "99" is a common sentinel for illegal magnitudes. 

269 

270 good, = np.where((np.nan_to_num(refMag[selected]) < 90.0) & 

271 (np.nan_to_num(refMagErr[selected]) < 90.0) & 

272 (np.nan_to_num(refMagErr[selected]) > 0.0)) 

273 

274 fgcmRefCat['refMag'][good, i] = refMag[selected][good] 

275 fgcmRefCat['refMagErr'][good, i] = refMagErr[selected][good] 

276 

277 else: 

278 # No colorterms 

279 

280 # TODO: need to use Jy here until RFC-549 is completed and refcats return nanojansky 

281 

282 for i, (filterName, fluxField) in enumerate(zip(self._fluxFilters, self._fluxFields)): 

283 # nan_to_num replaces nans with zeros, and this ensures that we select 

284 # fluxes that both filter out nans and are positive. 

285 good, = np.where((np.nan_to_num(refCat[fluxField][selected]) > 0.0) & 

286 (np.nan_to_num(refCat[fluxField+'Err'][selected]) > 0.0)) 

287 refMag = (refCat[fluxField][selected][good] * units.Jy).to_value(units.ABmag) 

288 refMagErr = abMagErrFromFluxErr(refCat[fluxField+'Err'][selected][good], 

289 refCat[fluxField][selected][good]) 

290 fgcmRefCat['refMag'][good, i] = refMag 

291 fgcmRefCat['refMagErr'][good, i] = refMagErr 

292 

293 return fgcmRefCat 

294 

295 def _determine_flux_fields(self, center, filterList): 

296 """ 

297 Determine the flux field names for a reference catalog. 

298 

299 Will set self._fluxFields, self._referenceFilter. 

300 

301 Parameters 

302 ---------- 

303 center: `lsst.geom.SpherePoint` 

304 The center around which to load test sources. 

305 filterList: `list` 

306 list of `str` of camera filter names. 

307 """ 

308 

309 # Record self._fluxFilters for checks on subsequent calls 

310 self._fluxFilters = filterList 

311 

312 # Search for a good filter to use to load the reference catalog 

313 # via the refObjLoader task which requires a valid filterName 

314 foundReferenceFilter = False 

315 for filterName in filterList: 

316 refFilterName = self.config.refFilterMap.get(filterName) 

317 if refFilterName is None: 

318 continue 

319 

320 try: 

321 results = self.refObjLoader.loadSkyCircle(center, 

322 0.05 * lsst.geom.degrees, 

323 refFilterName) 

324 foundReferenceFilter = True 

325 self._referenceFilter = refFilterName 

326 break 

327 except RuntimeError: 

328 # This just means that the filterName wasn't listed 

329 # in the reference catalog. This is okay. 

330 pass 

331 

332 if not foundReferenceFilter: 

333 raise RuntimeError("Could not find any valid flux field(s) %s" % 

334 (", ".join(filterList))) 

335 

336 # Retrieve all the fluxField names 

337 self._fluxFields = [] 

338 for filterName in filterList: 

339 fluxField = None 

340 

341 refFilterName = self.config.refFilterMap.get(filterName) 

342 

343 if refFilterName is not None: 

344 try: 

345 fluxField = getRefFluxField(results.refCat.schema, filterName=refFilterName) 

346 except RuntimeError: 

347 # This flux field isn't available. Set to None 

348 fluxField = None 

349 

350 if fluxField is None: 

351 self.log.warn(f'No reference flux field for camera filter {filterName}') 

352 

353 self._fluxFields.append(fluxField)