lsst.ip.isr  16.0-15-g1417920+1
crosstalk.py
Go to the documentation of this file.
1 #
2 # LSST Data Management System
3 # Copyright 2008-2017 AURA/LSST.
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 <https://www.lsstcorp.org/LegalNotices/>.
21 #
22 """
23 Apply intra-CCD crosstalk corrections
24 """
25 
26 import lsst.afw.math
27 import lsst.afw.table
28 import lsst.afw.detection
29 from lsst.pex.config import Config, Field
30 from lsst.pipe.base import Task
31 
32 __all__ = ["CrosstalkConfig", "CrosstalkTask", "subtractCrosstalk", "writeCrosstalkCoeffs"]
33 
34 
35 class CrosstalkConfig(Config):
36  """Configuration for intra-CCD crosstalk removal"""
37  minPixelToMask = Field(
38  dtype=float,
39  doc="Set crosstalk mask plane for pixels over this value",
40  default=45000
41  )
42  crosstalkMaskPlane = Field(
43  dtype=str,
44  doc="Name for crosstalk mask plane",
45  default="CROSSTALK"
46  )
47 
48 
49 class CrosstalkTask(Task):
50  """Apply intra-CCD crosstalk correction"""
51  ConfigClass = CrosstalkConfig
52 
53  def prepCrosstalk(self, dataRef):
54  """Placeholder for crosstalk preparation method, e.g., for inter-CCD crosstalk.
55 
56  Parameters
57  ----------
58  dataRef : `daf.persistence.butlerSubset.ButlerDataRef`
59  Butler reference of the detector data to be processed.
60 
61  See also
62  --------
63  lsst.obs.decam.crosstalk.DecamCrosstalkTask.prepCrosstalk
64  """
65  return
66 
67  def run(self, exposure, crosstalkSources=None):
68  """Apply intra-CCD crosstalk correction
69 
70  Parameters
71  ----------
72  exposure : `lsst.afw.image.Exposure`
73  Exposure for which to remove crosstalk.
74  crosstalkSources : `defaultdict`, optional
75  Image data and crosstalk coefficients from other CCDs/amps that are
76  sources of crosstalk in exposure.
77  The default for intra-CCD crosstalk here is None.
78  """
79  detector = exposure.getDetector()
80  if not detector.hasCrosstalk():
81  self.log.warn("Crosstalk correction skipped: no crosstalk coefficients for detector")
82  return
83  self.log.info("Applying crosstalk correction")
84  subtractCrosstalk(exposure, minPixelToMask=self.config.minPixelToMask,
85  crosstalkStr=self.config.crosstalkMaskPlane)
86 
87 
88 # Flips required to get the corner to the lower-left
89 # (an arbitrary choice; flips are relative, so the choice of reference here is not important)
90 X_FLIP = {lsst.afw.table.LL: False, lsst.afw.table.LR: True,
91  lsst.afw.table.UL: False, lsst.afw.table.UR: True}
92 Y_FLIP = {lsst.afw.table.LL: False, lsst.afw.table.LR: False,
93  lsst.afw.table.UL: True, lsst.afw.table.UR: True}
94 
95 
97  def run(self, exposure, crosstalkSources=None):
98  self.log.info("Not performing any crosstalk correction")
99 
100 
101 def extractAmp(image, amp, corner, isTrimmed=False):
102  """Return an image of the amp
103 
104  The returned image will have the amp's readout corner in the
105  nominated `corner`.
106 
107  Parameters
108  ----------
109  image : `lsst.afw.image.Image` or `lsst.afw.image.MaskedImage`
110  Image containing the amplifier of interest.
111  amp : `lsst.afw.table.AmpInfoRecord`
112  Amplifier information.
113  corner : `lsst.afw.table.ReadoutCorner` or `None`
114  Corner in which to put the amp's readout corner, or `None` for
115  no flipping.
116  isTrimmed : `bool`
117  The image is already trimmed.
118  This should no longer be needed once DM-15409 is resolved.
119 
120  Returns
121  -------
122  output : `lsst.afw.image.Image`
123  Image of the amplifier in the standard configuration.
124  """
125  output = image[amp.getBBox() if isTrimmed else amp.getRawDataBBox()]
126  ampCorner = amp.getReadoutCorner()
127  # Flipping is necessary only if the desired configuration doesn't match what we currently have
128  xFlip = X_FLIP[corner] ^ X_FLIP[ampCorner]
129  yFlip = Y_FLIP[corner] ^ Y_FLIP[ampCorner]
130  return lsst.afw.math.flipImage(output, xFlip, yFlip)
131 
132 
133 def calculateBackground(mi, badPixels=["BAD"]):
134  """Calculate median background in image
135 
136  Getting a great background model isn't important for crosstalk correction,
137  since the crosstalk is at a low level. The median should be sufficient.
138 
139  Parameters
140  ----------
141  mi : `lsst.afw.image.MaskedImage`
142  MaskedImage for which to measure background.
143  badPixels : `list` of `str`
144  Mask planes to ignore.
145 
146  Returns
147  -------
148  bg : `float`
149  Median background level.
150  """
151  mask = mi.getMask()
153  stats.setAndMask(mask.getPlaneBitMask(badPixels))
154  return lsst.afw.math.makeStatistics(mi, lsst.afw.math.MEDIAN, stats).getValue()
155 
156 
157 def subtractCrosstalk(exposure, badPixels=["BAD"], minPixelToMask=45000, crosstalkStr="CROSSTALK"):
158  """Subtract the intra-CCD crosstalk from an exposure
159 
160  We set the mask plane indicated by ``crosstalkStr`` in a target amplifier
161  for pixels in a source amplifier that exceed `minPixelToMask`. Note that
162  the correction is applied to all pixels in the amplifier, but only those
163  that have a substantial crosstalk are masked with ``crosstalkStr``.
164 
165  The uncorrected image is used as a template for correction. This is good
166  enough if the crosstalk is small (e.g., coefficients < ~ 1e-3), but if it's
167  larger you may want to iterate.
168 
169  Parameters
170  ----------
171  exposure : `lsst.afw.image.Exposure`
172  Exposure for which to subtract crosstalk.
173  badPixels : `list` of `str`
174  Mask planes to ignore.
175  minPixelToMask : `float`
176  Minimum pixel value in source amplifier for which to set
177  ``crosstalkStr`` mask plane in target amplifier.
178  crosstalkStr : `str`
179  Mask plane name for pixels greatly modified by crosstalk.
180  """
181  mi = exposure.getMaskedImage()
182  mask = mi.getMask()
183 
184  ccd = exposure.getDetector()
185  numAmps = len(ccd)
186  coeffs = ccd.getCrosstalk()
187  assert coeffs.shape == (numAmps, numAmps)
188 
189  # Set the crosstalkStr bit for the bright pixels (those which will have significant crosstalk correction)
190  crosstalkPlane = mask.addMaskPlane(crosstalkStr)
191  footprints = lsst.afw.detection.FootprintSet(mi, lsst.afw.detection.Threshold(minPixelToMask))
192  footprints.setMask(mask, crosstalkStr)
193  crosstalk = mask.getPlaneBitMask(crosstalkStr)
194 
195  backgrounds = [calculateBackground(mi[amp.getBBox()], badPixels) for amp in ccd]
196 
197  subtrahend = mi.Factory(mi.getBBox())
198  subtrahend.set((0, 0, 0))
199  for ii, iAmp in enumerate(ccd):
200  iImage = subtrahend[iAmp.getRawDataBBox()]
201  for jj, jAmp in enumerate(ccd):
202  if ii == jj:
203  assert coeffs[ii, jj] == 0.0
204  if coeffs[ii, jj] == 0.0:
205  continue
206 
207  jImage = extractAmp(mi, jAmp, iAmp.getReadoutCorner())
208  jImage.getMask().getArray()[:] &= crosstalk # Remove all other masks
209  jImage -= backgrounds[jj]
210 
211  iImage.scaledPlus(coeffs[ii, jj], jImage)
212 
213  # Set crosstalkStr bit only for those pixels that have been significantly modified (i.e., those
214  # masked as such in 'subtrahend'), not necessarily those that are bright originally.
215  mask.clearMaskPlane(crosstalkPlane)
216  mi -= subtrahend # also sets crosstalkStr bit for bright pixels
217 
218 
219 def writeCrosstalkCoeffs(outputFileName, coeff, det=None, crosstalkName="Unknown", indent=2):
220  """Write a yaml file containing the crosstalk coefficients
221 
222  The coeff array is indexed by [i, j] where i and j are amplifiers
223  corresponding to the amplifiers in det
224 
225  Parameters
226  ----------
227  outputFileName : `str`
228  Name of output yaml file
229  coeff : `numpy.array(namp, namp)`
230  numpy array of coefficients
231  det : `lsst.afw.cameraGeom.Detector`
232  Used to provide the list of amplifier names;
233  if None use ['0', '1', ...]
234  ccdType : `str`
235  Name of CCD, used to index the yaml file
236  If all CCDs are identical could be the type (e.g. ITL)
237  indent : `int`
238  Indent width to use when writing the yaml file
239  """
240 
241  if det is None:
242  ampNames = [str(i) for i in range(coeff.shape[0])]
243  else:
244  ampNames = [a.getName() for a in det]
245 
246  assert coeff.shape == (len(ampNames), len(ampNames))
247 
248  dIndent = indent
249  indent = 0
250  with open(outputFileName, "w") as fd:
251  print(indent*" " + "crosstalk :", file=fd)
252  indent += dIndent
253  print(indent*" " + "%s :" % crosstalkName, file=fd)
254  indent += dIndent
255 
256  for i, ampNameI in enumerate(ampNames):
257  print(indent*" " + "%s : {" % ampNameI, file=fd)
258  indent += dIndent
259  print(indent*" ", file=fd, end='')
260 
261  for j, ampNameJ in enumerate(ampNames):
262  print("%s : %11.4e, " % (ampNameJ, coeff[i, j]), file=fd,
263  end='\n' + indent*" " if j%4 == 3 else '')
264  print("}", file=fd)
265 
266  indent -= dIndent
def subtractCrosstalk(exposure, badPixels=["BAD"], minPixelToMask=45000, crosstalkStr="CROSSTALK")
Definition: crosstalk.py:157
std::shared_ptr< ImageT > flipImage(ImageT const &inImage, bool flipLR, bool flipTB)
def run(self, exposure, crosstalkSources=None)
Definition: crosstalk.py:97
Statistics makeStatistics(lsst::afw::math::MaskedVector< EntryT > const &mv, std::vector< WeightPixel > const &vweights, int const flags, StatisticsControl const &sctrl=StatisticsControl())
def calculateBackground(mi, badPixels=["BAD"])
Definition: crosstalk.py:133
def run(self, exposure, crosstalkSources=None)
Definition: crosstalk.py:67
def extractAmp(image, amp, corner, isTrimmed=False)
Definition: crosstalk.py:101
def prepCrosstalk(self, dataRef)
Definition: crosstalk.py:53
def writeCrosstalkCoeffs(outputFileName, coeff, det=None, crosstalkName="Unknown", indent=2)
Definition: crosstalk.py:219