lsst.pipe.tasks  14.0-39-g03bf09b5
coaddInputRecorder.py
Go to the documentation of this file.
1 #
2 # LSST Data Management System
3 # Copyright 2008, 2009, 2010, 2011, 2012 LSST Corporation.
4 #
5 # This product includes software developed by the
6 # LSST Project (http://www.lsst.org/).
7 #
8 # This program is free software: you can redistribute it and/or modify
9 # it under the terms of the GNU General Public License as published by
10 # the Free Software Foundation, either version 3 of the License, or
11 # (at your option) any later version.
12 #
13 # This program is distributed in the hope that it will be useful,
14 # but WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 # GNU General Public License for more details.
17 #
18 # You should have received a copy of the LSST License Statement and
19 # the GNU General Public License along with this program. If not,
20 # see <http://www.lsstcorp.org/LegalNotices/>.
21 #
22 from __future__ import absolute_import, division, print_function
23 from builtins import object
24 import numpy
25 
26 import lsst.pex.config as pexConfig
27 import lsst.afw.table as afwTable
28 import lsst.afw.image as afwImage
29 import lsst.pipe.base as pipeBase
30 from lsst.meas.algorithms import CoaddPsf, makeCoaddApCorrMap
31 
32 __all__ = ["CoaddInputRecorderTask"]
33 
34 
35 class CoaddInputRecorderConfig(pexConfig.Config):
36  """Config for CoaddInputRecorderTask
37 
38  The inputRecorder section of the various coadd tasks' configs should generally agree,
39  or the schemas created by earlier tasks (like MakeCoaddTempExpTask) will not contain
40  the fields filled by later tasks (like AssembleCoaddTask).
41  """
42  saveEmptyCcds = pexConfig.Field(
43  dtype=bool, default=False, optional=False,
44  doc=("Add records for CCDs we iterated over but did not add a coaddTempExp"
45  " due to a lack of unmasked pixels in the coadd footprint.")
46  )
47  saveErrorCcds = pexConfig.Field(
48  dtype=bool, default=False, optional=False,
49  doc=("Add records for CCDs we iterated over but did not add a coaddTempExp"
50  " due to an exception (often due to the calexp not being found on disk).")
51  )
52  saveVisitGoodPix = pexConfig.Field(
53  dtype=bool, default=True, optional=False,
54  doc=("Save the total number of good pixels in each coaddTempExp (redundant with a sum of"
55  " good pixels in associated CCDs)")
56  )
57  saveCcdWeights = pexConfig.Field(
58  dtype=bool, default=True, optional=False,
59  doc=("Save weights in the CCDs table as well as the visits table?"
60  " (This is necessary for easy construction of CoaddPsf, but otherwise duplicate information.)")
61  )
62 
63 
65  """A helper class for CoaddInputRecorderTask, managing the CoaddInputs object for that a single
66  CoaddTempExp. This will contain single 'visit' record for the CoaddTempExp and a number of 'ccd'
67  records.
68 
69  Should generally be created by calling CoaddInputRecorderTask.makeCoaddTempExp().
70  """
71 
72  def __init__(self, task, visitId, num=0):
73  """Constructor
74 
75  @param task The CoaddInputRecorderTask that is utilising us
76  @param visitId Identifier (integer) for the visit
77  @param num Number of CCDs for this visit that overlap this
78  patch (for reserving memory)
79  """
80  self.task = task
81  self.coaddInputs = self.task.makeCoaddInputs()
82  self.coaddInputs.visits.reserve(1)
83  if num > 0:
84  self.coaddInputs.ccds.reserve(num)
85  self.visitRecord = self.coaddInputs.visits.addNew()
86  self.visitRecord.setId(visitId)
87 
88  def addCalExp(self, calExp, ccdId, nGoodPix):
89  """Add a 'ccd' record for a calexp just added to the CoaddTempExp
90 
91  @param[in] calExp Calibrated exposure just added to the CoaddTempExp, or None in case of
92  failures that should nonetheless be tracked. Should be the original
93  calexp, in that it should contain the original Psf and Wcs, not the
94  warped and/or matched ones.
95  @param[in] ccdId A unique numeric ID for the Exposure.
96  @param[in] nGoodPix Number of good pixels this image will contribute to the CoaddTempExp.
97  If saveEmptyCcds is not set and this value is zero, no record will be
98  added.
99  """
100  if nGoodPix == 0 and not self.task.config.saveEmptyCcds:
101  return
102  record = self.coaddInputs.ccds.addNew()
103  record.setId(ccdId)
104  record.setL(self.task.ccdVisitKey, self.visitRecord.getId())
105  try:
106  record.setI(self.task.ccdCcdKey, calExp.getDetector().getId())
107  except:
108  self.task.log.warn("Error getting detector serial number in visit %d; using -1"
109  % self.visitRecord.getId())
110  record.setI(self.task.ccdCcdKey, -1)
111  record.setI(self.task.ccdGoodPixKey, nGoodPix)
112  if calExp is not None:
113  self._setExposureInfoInRecord(exposure=calExp, record=record)
114  if self.task.config.saveCcdWeights:
115  record.setD(self.task.ccdWeightKey, 1.0) # No weighting or overlap when warping
116  record.set(self.task.ccdFilterKey, calExp.getFilter().getName())
117 
118  def finish(self, coaddTempExp, nGoodPix=None):
119  """Finish creating the CoaddInputs for a CoaddTempExp.
120 
121  @param[in,out] coaddTempExp Exposure object from which to obtain the PSF, WCS, and bounding
122  box for the entry in the 'visits' table. On return, the completed
123  CoaddInputs object will be attached to it.
124  @param[in] nGoodPix Total number of good pixels in the CoaddTempExp; ignored unless
125  saveVisitGoodPix is true.
126  """
127  self._setExposureInfoInRecord(exposure=coaddTempExp, record=self.visitRecord)
128  if self.task.config.saveVisitGoodPix:
129  self.visitRecord.setI(self.task.visitGoodPixKey, nGoodPix)
130  coaddTempExp.getInfo().setCoaddInputs(self.coaddInputs)
131  wcs = coaddTempExp.getWcs()
132  if False:
133  # This causes a test failure, pending fix in issue HSC-802
134  coaddTempExp.setPsf(CoaddPsf(self.coaddInputs.ccds, wcs))
135  apCorrMap = makeCoaddApCorrMap(self.coaddInputs.ccds, coaddTempExp.getBBox(afwImage.PARENT), wcs)
136  coaddTempExp.getInfo().setApCorrMap(apCorrMap)
137 
138  def _setExposureInfoInRecord(self, exposure, record):
139  """Set exposure info and bbox in an ExposureTable record
140 
141  @param[in] exposure exposure whose info is to be recorded
142  @param[in,out] record record of an ExposureTable to set
143  """
144  info = exposure.getInfo()
145  record.setPsf(info.getPsf())
146  record.setWcs(info.getWcs())
147  record.setCalib(info.getCalib())
148  record.setApCorrMap(info.getApCorrMap())
149  record.setValidPolygon(info.getValidPolygon())
150  record.setVisitInfo(info.getVisitInfo())
151  record.setBBox(exposure.getBBox())
152 
153 class CoaddInputRecorderTask(pipeBase.Task):
154  """Subtask that handles filling a CoaddInputs object for a coadd exposure, tracking the CCDs and
155  visits that went into a coadd.
156 
157  The interface here is a little messy, but I think this is at least partly a product of a bit of
158  messiness in the coadd code it's plugged into. I hope #2590 might result in a better design.
159  """
160 
161  ConfigClass = CoaddInputRecorderConfig
162 
163  def __init__(self, *args, **kwargs):
164  pipeBase.Task.__init__(self, *args, **kwargs)
165  self.visitSchema = afwTable.ExposureTable.makeMinimalSchema()
166  if self.config.saveVisitGoodPix:
167  self.visitGoodPixKey = self.visitSchema.addField("goodpix", type=numpy.int32,
168  doc="Number of good pixels in the coaddTempExp")
169  self.visitWeightKey = self.visitSchema.addField("weight", type=float,
170  doc="Weight for this visit in the coadd")
171  self.ccdSchema = afwTable.ExposureTable.makeMinimalSchema()
172  self.ccdCcdKey = self.ccdSchema.addField("ccd", type=numpy.int32, doc="cameraGeom CCD serial number")
173  self.ccdVisitKey = self.ccdSchema.addField("visit", type=numpy.int64,
174  doc="Foreign key for the visits (coaddTempExp) catalog")
175  self.ccdGoodPixKey = self.ccdSchema.addField("goodpix", type=numpy.int32,
176  doc="Number of good pixels in this CCD")
177  if self.config.saveCcdWeights:
178  self.ccdWeightKey = self.ccdSchema.addField("weight", type=float,
179  doc="Weight for this visit in the coadd")
180  self.visitFilterKey = self.visitSchema.addField("filter", type=str, size=32,
181  doc="Filter associated with this visit.")
182  self.ccdFilterKey = self.ccdSchema.addField("filter", type=str, size=32,
183  doc="Filter associated with this visit.")
184 
185  def makeCoaddTempExpRecorder(self, visitId, num=0):
186  """Return a CoaddTempExpInputRecorder instance to help with saving a CoaddTempExp's inputs.
187 
188  The visitId may be any number that is unique for each CoaddTempExp that goes into a coadd,
189  but ideally should be something more meaningful that can be used to reconstruct a data ID.
190  """
191  return CoaddTempExpInputRecorder(self, visitId, num=num)
192 
193  def makeCoaddInputs(self):
194  """Create a CoaddInputs object with schemas defined by the task configuration"""
195  return afwImage.CoaddInputs(self.visitSchema, self.ccdSchema)
196 
197  def addVisitToCoadd(self, coaddInputs, coaddTempExp, weight):
198  """Called by AssembleCoaddTask when adding (a subset of) a coaddTempExp to a coadd. The
199  base class impementation extracts the CoaddInputs from the coaddTempExp and appends
200  them to the given coaddInputs, filling in the weight column(s).
201 
202  Note that the passed coaddTempExp may be a subimage, but that this method will only be
203  called for the first subimage
204 
205  Returns the record for the visit to allow subclasses to fill in additional fields.
206  Warns and returns None if the inputRecorder catalogs for the coaddTempExp are not usable.
207  """
208  tempExpInputs = coaddTempExp.getInfo().getCoaddInputs()
209  if len(tempExpInputs.visits) != 1:
210  self.log.warn("CoaddInputs for coaddTempExp should have exactly one record in visits table "
211  "(found %d). CoaddInputs for this visit will not be saved."
212  % len(tempExpInputs.visits))
213  return None
214  inputVisitRecord = tempExpInputs.visits[0]
215  outputVisitRecord = coaddInputs.visits.addNew()
216  outputVisitRecord.assign(inputVisitRecord)
217  outputVisitRecord.setD(self.visitWeightKey, weight)
218  outputVisitRecord.set(self.visitFilterKey, coaddTempExp.getFilter().getName())
219  for inputCcdRecord in tempExpInputs.ccds:
220  if inputCcdRecord.getL(self.ccdVisitKey) != inputVisitRecord.getId():
221  self.log.warn("CoaddInputs for coaddTempExp with id %d contains CCDs with visit=%d. "
222  "CoaddInputs may be unreliable."
223  % (inputVisitRecord.getId(), inputCcdRecord.getL(self.ccdVisitKey)))
224  outputCcdRecord = coaddInputs.ccds.addNew()
225  outputCcdRecord.assign(inputCcdRecord)
226  if self.config.saveCcdWeights:
227  outputCcdRecord.setD(self.ccdWeightKey, weight)
228  outputCcdRecord.set(self.ccdFilterKey, coaddTempExp.getFilter().getName())
229  return inputVisitRecord
def addVisitToCoadd(self, coaddInputs, coaddTempExp, weight)