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