Coverage for python/lsst/fgcmcal/fgcmBuildStarsTable.py : 11%

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"""Build star observations for input to FGCM using sourceTable_visit.
25This task finds all the visits and sourceTable_visits in a repository (or a
26subset based on command line parameters) and extracts all the potential
27calibration stars for input into fgcm. This task additionally uses fgcm to
28match star observations into unique stars, and performs as much cleaning of the
29input catalog as possible.
30"""
32import time
34import numpy as np
35import collections
37import lsst.pex.config as pexConfig
38import lsst.pipe.base as pipeBase
39import lsst.afw.table as afwTable
41from .fgcmBuildStarsBase import FgcmBuildStarsConfigBase, FgcmBuildStarsRunner, FgcmBuildStarsBaseTask
42from .utilities import computeApproxPixelAreaFields
44__all__ = ['FgcmBuildStarsTableConfig', 'FgcmBuildStarsTableTask']
47class FgcmBuildStarsTableConfig(FgcmBuildStarsConfigBase):
48 """Config for FgcmBuildStarsTableTask"""
50 referenceCCD = pexConfig.Field(
51 doc="Reference CCD for checking PSF and background",
52 dtype=int,
53 default=40,
54 )
56 def setDefaults(self):
57 super().setDefaults()
59 # The names here correspond to the post-transformed
60 # sourceTable_visit catalogs, which differ from the raw src
61 # catalogs. Therefore, all field and flag names cannot
62 # be derived from the base config class.
63 self.instFluxField = 'ApFlux_12_0_instFlux'
64 self.localBackgroundFluxField = 'LocalBackground_instFlux'
65 self.apertureInnerInstFluxField = 'ApFlux_12_0_instFlux'
66 self.apertureOuterInstFluxField = 'ApFlux_17_0_instFlux'
67 self.psfCandidateName = 'Calib_psf_candidate'
69 sourceSelector = self.sourceSelector["science"]
71 fluxFlagName = self.instFluxField[0: -len('instFlux')] + 'flag'
73 sourceSelector.flags.bad = ['PixelFlags_edge',
74 'PixelFlags_interpolatedCenter',
75 'PixelFlags_saturatedCenter',
76 'PixelFlags_crCenter',
77 'PixelFlags_bad',
78 'PixelFlags_interpolated',
79 'PixelFlags_saturated',
80 'Centroid_flag',
81 fluxFlagName]
83 if self.doSubtractLocalBackground:
84 localBackgroundFlagName = self.localBackgroundFluxField[0: -len('instFlux')] + 'flag'
85 sourceSelector.flags.bad.append(localBackgroundFlagName)
87 sourceSelector.signalToNoise.fluxField = self.instFluxField
88 sourceSelector.signalToNoise.errField = self.instFluxField + 'Err'
90 sourceSelector.isolated.parentName = 'parentSourceId'
91 sourceSelector.isolated.nChildName = 'Deblend_nChild'
93 sourceSelector.unresolved.name = 'extendedness'
96class FgcmBuildStarsTableTask(FgcmBuildStarsBaseTask):
97 """
98 Build stars for the FGCM global calibration, using sourceTable_visit catalogs.
99 """
100 ConfigClass = FgcmBuildStarsTableConfig
101 RunnerClass = FgcmBuildStarsRunner
102 _DefaultName = "fgcmBuildStarsTable"
104 @classmethod
105 def _makeArgumentParser(cls):
106 """Create an argument parser"""
107 parser = pipeBase.ArgumentParser(name=cls._DefaultName)
108 parser.add_id_argument("--id", "sourceTable_visit", help="Data ID, e.g. --id visit=6789")
110 return parser
112 def findAndGroupDataRefs(self, butler, dataRefs):
113 self.log.info("Grouping dataRefs by %s" % (self.config.visitDataRefName))
115 camera = butler.get('camera')
117 ccdIds = []
118 for detector in camera:
119 ccdIds.append(detector.getId())
120 # Insert our preferred referenceCCD first:
121 # It is fine that this is listed twice, because we only need
122 # the first calexp that is found.
123 ccdIds.insert(0, self.config.referenceCCD)
125 # The visitTable building code expects a dictionary of groupedDataRefs
126 # keyed by visit, the first element as the "primary" calexp dataRef.
127 # We then append the sourceTable_visit dataRef at the end for the
128 # code which does the data reading (fgcmMakeAllStarObservations).
130 groupedDataRefs = collections.defaultdict(list)
131 for dataRef in dataRefs:
132 visit = dataRef.dataId[self.config.visitDataRefName]
134 # Find an existing calexp (we need for psf and metadata)
135 # and make the relevant dataRef
136 for ccdId in ccdIds:
137 try:
138 calexpRef = butler.dataRef('calexp', dataId={self.config.visitDataRefName: visit,
139 self.config.ccdDataRefName: ccdId})
140 except RuntimeError:
141 # Not found
142 continue
143 # It was found. Add and quit out, since we only
144 # need one calexp per visit.
145 groupedDataRefs[visit].append(calexpRef)
146 break
148 # And append this dataRef
149 groupedDataRefs[visit].append(dataRef)
151 return groupedDataRefs
153 def fgcmMakeAllStarObservations(self, groupedDataRefs, visitCat,
154 calibFluxApertureRadius=None,
155 visitCatDataRef=None,
156 starObsDataRef=None,
157 inStarObsCat=None):
158 startTime = time.time()
160 # If both dataRefs are None, then we assume the caller does not
161 # want to store checkpoint files. If both are set, we will
162 # do checkpoint files. And if only one is set, this is potentially
163 # unintentional and we will warn.
164 if (visitCatDataRef is not None and starObsDataRef is None or
165 visitCatDataRef is None and starObsDataRef is not None):
166 self.log.warn("Only one of visitCatDataRef and starObsDataRef are set, so "
167 "no checkpoint files will be persisted.")
169 if self.config.doSubtractLocalBackground and calibFluxApertureRadius is None:
170 raise RuntimeError("Must set calibFluxApertureRadius if doSubtractLocalBackground is True.")
172 # To get the correct output schema, we use similar code as fgcmBuildStarsTask
173 # We are not actually using this mapper, except to grab the outputSchema
174 dataRef = groupedDataRefs[list(groupedDataRefs.keys())[0]][0]
175 sourceSchema = dataRef.get('src_schema', immediate=True).schema
176 sourceMapper = self._makeSourceMapper(sourceSchema)
177 outputSchema = sourceMapper.getOutputSchema()
179 # Construct mapping from ccd number to index
180 camera = dataRef.get('camera')
181 ccdMapping = {}
182 for ccdIndex, detector in enumerate(camera):
183 ccdMapping[detector.getId()] = ccdIndex
185 approxPixelAreaFields = computeApproxPixelAreaFields(camera)
187 if inStarObsCat is not None:
188 fullCatalog = inStarObsCat
189 comp1 = fullCatalog.schema.compare(outputSchema, outputSchema.EQUAL_KEYS)
190 comp2 = fullCatalog.schema.compare(outputSchema, outputSchema.EQUAL_NAMES)
191 if not comp1 or not comp2:
192 raise RuntimeError("Existing fgcmStarObservations file found with mismatched schema.")
193 else:
194 fullCatalog = afwTable.BaseCatalog(outputSchema)
196 visitKey = outputSchema['visit'].asKey()
197 ccdKey = outputSchema['ccd'].asKey()
198 instMagKey = outputSchema['instMag'].asKey()
199 instMagErrKey = outputSchema['instMagErr'].asKey()
201 # Prepare local background if desired
202 if self.config.doSubtractLocalBackground:
203 localBackgroundArea = np.pi*calibFluxApertureRadius**2.
205 # Determine which columns we need from the sourceTable_visit catalogs
206 columns = self._get_sourceTable_visit_columns()
208 k = 2.5/np.log(10.)
210 for counter, visit in enumerate(visitCat):
211 # Check if these sources have already been read and stored in the checkpoint file
212 if visit['sources_read']:
213 continue
215 expTime = visit['exptime']
217 dataRef = groupedDataRefs[visit['visit']][-1]
218 srcTable = dataRef.get()
220 df = srcTable.toDataFrame(columns)
222 goodSrc = self.sourceSelector.selectSources(df)
224 # Need to add a selection based on the local background correction
225 # if necessary
226 if self.config.doSubtractLocalBackground:
227 localBackground = localBackgroundArea*df[self.config.localBackgroundFluxField].values
228 use, = np.where((goodSrc.selected) &
229 ((df[self.config.instFluxField].values - localBackground) > 0.0))
230 else:
231 use, = np.where(goodSrc.selected)
233 tempCat = afwTable.BaseCatalog(fullCatalog.schema)
234 tempCat.resize(use.size)
236 tempCat['ra'][:] = np.deg2rad(df['ra'].values[use])
237 tempCat['dec'][:] = np.deg2rad(df['decl'].values[use])
238 tempCat['x'][:] = df['x'].values[use]
239 tempCat['y'][:] = df['y'].values[use]
240 tempCat[visitKey][:] = df[self.config.visitDataRefName].values[use]
241 tempCat[ccdKey][:] = df[self.config.ccdDataRefName].values[use]
242 tempCat['psf_candidate'] = df['Calib_psf_candidate'].values[use]
244 if self.config.doSubtractLocalBackground:
245 # At the moment we only adjust the flux and not the flux
246 # error by the background because the error on
247 # base_LocalBackground_instFlux is the rms error in the
248 # background annulus, not the error on the mean in the
249 # background estimate (which is much smaller, by sqrt(n)
250 # pixels used to estimate the background, which we do not
251 # have access to in this task). In the default settings,
252 # the annulus is sufficiently large such that these
253 # additional errors are are negligibly small (much less
254 # than a mmag in quadrature).
256 # This is the difference between the mag with local background correction
257 # and the mag without local background correction.
258 tempCat['deltaMagBkg'] = (-2.5*np.log10(df[self.config.instFluxField].values[use] -
259 localBackground[use]) -
260 -2.5*np.log10(df[self.config.instFluxField].values[use]))
261 else:
262 tempCat['deltaMagBkg'][:] = 0.0
264 # Need to loop over ccds here
265 for detector in camera:
266 ccdId = detector.getId()
267 # used index for all observations with a given ccd
268 use2 = (tempCat[ccdKey] == ccdId)
269 tempCat['jacobian'][use2] = approxPixelAreaFields[ccdId].evaluate(tempCat['x'][use2],
270 tempCat['y'][use2])
271 scaledInstFlux = (df[self.config.instFluxField].values[use[use2]] *
272 visit['scaling'][ccdMapping[ccdId]])
273 tempCat[instMagKey][use2] = (-2.5*np.log10(scaledInstFlux) + 2.5*np.log10(expTime))
275 # Compute instMagErr from instFluxErr/instFlux, any scaling
276 # will cancel out.
277 tempCat[instMagErrKey][:] = k*(df[self.config.instFluxField + 'Err'].values[use] /
278 df[self.config.instFluxField].values[use])
280 # Apply the jacobian if configured
281 if self.config.doApplyWcsJacobian:
282 tempCat[instMagKey][:] -= 2.5*np.log10(tempCat['jacobian'][:])
284 fullCatalog.extend(tempCat)
286 # Now do the aperture information
287 with np.warnings.catch_warnings():
288 # Ignore warnings, we will filter infinites and nans below
289 np.warnings.simplefilter("ignore")
291 instMagIn = -2.5*np.log10(df[self.config.apertureInnerInstFluxField].values[use])
292 instMagErrIn = k*(df[self.config.apertureInnerInstFluxField + 'Err'].values[use] /
293 df[self.config.apertureInnerInstFluxField].values[use])
294 instMagOut = -2.5*np.log10(df[self.config.apertureOuterInstFluxField].values[use])
295 instMagErrOut = k*(df[self.config.apertureOuterInstFluxField + 'Err'].values[use] /
296 df[self.config.apertureOuterInstFluxField].values[use])
298 ok = (np.isfinite(instMagIn) & np.isfinite(instMagErrIn) &
299 np.isfinite(instMagOut) & np.isfinite(instMagErrOut))
301 visit['deltaAper'] = np.median(instMagIn[ok] - instMagOut[ok])
302 visit['sources_read'] = True
304 self.log.info(" Found %d good stars in visit %d (deltaAper = %0.3f)",
305 use.size, visit['visit'], visit['deltaAper'])
307 if ((counter % self.config.nVisitsPerCheckpoint) == 0 and
308 starObsDataRef is not None and visitCatDataRef is not None):
309 # We need to persist both the stars and the visit catalog which gets
310 # additional metadata from each visit.
311 starObsDataRef.put(fullCatalog)
312 visitCatDataRef.put(visitCat)
314 self.log.info("Found all good star observations in %.2f s" %
315 (time.time() - startTime))
317 return fullCatalog
319 def _get_sourceTable_visit_columns(self):
320 """
321 Get the sourceTable_visit columns from the config.
323 Returns
324 -------
325 columns : `list`
326 List of columns to read from sourceTable_visit
327 """
328 columns = [self.config.visitDataRefName, self.config.ccdDataRefName,
329 'ra', 'decl', 'x', 'y', self.config.psfCandidateName,
330 self.config.instFluxField, self.config.instFluxField + 'Err',
331 self.config.apertureInnerInstFluxField, self.config.apertureInnerInstFluxField + 'Err',
332 self.config.apertureOuterInstFluxField, self.config.apertureOuterInstFluxField + 'Err']
333 if self.sourceSelector.config.doFlags:
334 columns.extend(self.sourceSelector.config.flags.bad)
335 if self.sourceSelector.config.doUnresolved:
336 columns.append(self.sourceSelector.config.unresolved.name)
337 if self.sourceSelector.config.doIsolated:
338 columns.append(self.sourceSelector.config.isolated.parentName)
339 columns.append(self.sourceSelector.config.isolated.nChildName)
340 if self.config.doSubtractLocalBackground:
341 columns.append(self.config.localBackgroundFluxField)
343 return columns