LSSTApplications  18.0.0+106,18.0.0+50,19.0.0,19.0.0+1,19.0.0+10,19.0.0+11,19.0.0+13,19.0.0+17,19.0.0+2,19.0.0-1-g20d9b18+6,19.0.0-1-g425ff20,19.0.0-1-g5549ca4,19.0.0-1-g580fafe+6,19.0.0-1-g6fe20d0+1,19.0.0-1-g7011481+9,19.0.0-1-g8c57eb9+6,19.0.0-1-gb5175dc+11,19.0.0-1-gdc0e4a7+9,19.0.0-1-ge272bc4+6,19.0.0-1-ge3aa853,19.0.0-10-g448f008b,19.0.0-12-g6990b2c,19.0.0-2-g0d9f9cd+11,19.0.0-2-g3d9e4fb2+11,19.0.0-2-g5037de4,19.0.0-2-gb96a1c4+3,19.0.0-2-gd955cfd+15,19.0.0-3-g2d13df8,19.0.0-3-g6f3c7dc,19.0.0-4-g725f80e+11,19.0.0-4-ga671dab3b+1,19.0.0-4-gad373c5+3,19.0.0-5-ga2acb9c+2,19.0.0-5-gfe96e6c+2,w.2020.01
LSSTDataManagementBasePackage
isrFunctions.py
Go to the documentation of this file.
1 #
2 # LSST Data Management System
3 # Copyright 2008, 2009, 2010 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 import math
23 import numpy
24 from deprecated.sphinx import deprecated
25 
26 import lsst.geom
27 import lsst.afw.image as afwImage
28 import lsst.afw.detection as afwDetection
29 import lsst.afw.math as afwMath
30 import lsst.meas.algorithms as measAlg
31 import lsst.pex.exceptions as pexExcept
32 import lsst.afw.cameraGeom as camGeom
33 
34 from lsst.afw.geom.wcsUtils import makeDistortedTanWcs
35 from lsst.meas.algorithms.detection import SourceDetectionTask
36 from lsst.pipe.base import Struct
37 
38 from contextlib import contextmanager
39 
40 
41 def createPsf(fwhm):
42  """Make a double Gaussian PSF.
43 
44  Parameters
45  ----------
46  fwhm : scalar
47  FWHM of double Gaussian smoothing kernel.
48 
49  Returns
50  -------
51  psf : `lsst.meas.algorithms.DoubleGaussianPsf`
52  The created smoothing kernel.
53  """
54  ksize = 4*int(fwhm) + 1
55  return measAlg.DoubleGaussianPsf(ksize, ksize, fwhm/(2*math.sqrt(2*math.log(2))))
56 
57 
58 def transposeMaskedImage(maskedImage):
59  """Make a transposed copy of a masked image.
60 
61  Parameters
62  ----------
63  maskedImage : `lsst.afw.image.MaskedImage`
64  Image to process.
65 
66  Returns
67  -------
68  transposed : `lsst.afw.image.MaskedImage`
69  The transposed copy of the input image.
70  """
71  transposed = maskedImage.Factory(lsst.geom.Extent2I(maskedImage.getHeight(), maskedImage.getWidth()))
72  transposed.getImage().getArray()[:] = maskedImage.getImage().getArray().T
73  transposed.getMask().getArray()[:] = maskedImage.getMask().getArray().T
74  transposed.getVariance().getArray()[:] = maskedImage.getVariance().getArray().T
75  return transposed
76 
77 
78 def interpolateDefectList(maskedImage, defectList, fwhm, fallbackValue=None):
79  """Interpolate over defects specified in a defect list.
80 
81  Parameters
82  ----------
83  maskedImage : `lsst.afw.image.MaskedImage`
84  Image to process.
85  defectList : `lsst.meas.algorithms.Defects`
86  List of defects to interpolate over.
87  fwhm : scalar
88  FWHM of double Gaussian smoothing kernel.
89  fallbackValue : scalar, optional
90  Fallback value if an interpolated value cannot be determined.
91  If None, then the clipped mean of the image is used.
92  """
93  psf = createPsf(fwhm)
94  if fallbackValue is None:
95  fallbackValue = afwMath.makeStatistics(maskedImage.getImage(), afwMath.MEANCLIP).getValue()
96  if 'INTRP' not in maskedImage.getMask().getMaskPlaneDict():
97  maskedImage.getMask().addMaskPlane('INTRP')
98  measAlg.interpolateOverDefects(maskedImage, psf, defectList, fallbackValue, True)
99  return maskedImage
100 
101 
102 def makeThresholdMask(maskedImage, threshold, growFootprints=1, maskName='SAT'):
103  """Mask pixels based on threshold detection.
104 
105  Parameters
106  ----------
107  maskedImage : `lsst.afw.image.MaskedImage`
108  Image to process. Only the mask plane is updated.
109  threshold : scalar
110  Detection threshold.
111  growFootprints : scalar, optional
112  Number of pixels to grow footprints of detected regions.
113  maskName : str, optional
114  Mask plane name, or list of names to convert
115 
116  Returns
117  -------
118  defectList : `lsst.meas.algorithms.Defects`
119  Defect list constructed from pixels above the threshold.
120  """
121  # find saturated regions
122  thresh = afwDetection.Threshold(threshold)
123  fs = afwDetection.FootprintSet(maskedImage, thresh)
124 
125  if growFootprints > 0:
126  fs = afwDetection.FootprintSet(fs, rGrow=growFootprints, isotropic=False)
127  fpList = fs.getFootprints()
128 
129  # set mask
130  mask = maskedImage.getMask()
131  bitmask = mask.getPlaneBitMask(maskName)
132  afwDetection.setMaskFromFootprintList(mask, fpList, bitmask)
133 
134  return measAlg.Defects.fromFootprintList(fpList)
135 
136 
137 def interpolateFromMask(maskedImage, fwhm, growSaturatedFootprints=1,
138  maskNameList=['SAT'], fallbackValue=None):
139  """Interpolate over defects identified by a particular set of mask planes.
140 
141  Parameters
142  ----------
143  maskedImage : `lsst.afw.image.MaskedImage`
144  Image to process.
145  fwhm : scalar
146  FWHM of double Gaussian smoothing kernel.
147  growSaturatedFootprints : scalar, optional
148  Number of pixels to grow footprints for saturated pixels.
149  maskNameList : `List` of `str`, optional
150  Mask plane name.
151  fallbackValue : scalar, optional
152  Value of last resort for interpolation.
153  """
154  mask = maskedImage.getMask()
155 
156  if growSaturatedFootprints > 0 and "SAT" in maskNameList:
157  thresh = afwDetection.Threshold(mask.getPlaneBitMask("SAT"), afwDetection.Threshold.BITMASK)
158  fpSet = afwDetection.FootprintSet(mask, thresh)
159  # If we are interpolating over an area larger than the original masked region, we need
160  # to expand the original mask bit to the full area to explain why we interpolated there.
161  fpSet = afwDetection.FootprintSet(fpSet, rGrow=growSaturatedFootprints, isotropic=False)
162  fpSet.setMask(mask, "SAT")
163 
164  thresh = afwDetection.Threshold(mask.getPlaneBitMask(maskNameList), afwDetection.Threshold.BITMASK)
165  fpSet = afwDetection.FootprintSet(mask, thresh)
166  defectList = measAlg.Defects.fromFootprintList(fpSet.getFootprints())
167 
168  interpolateDefectList(maskedImage, defectList, fwhm, fallbackValue=fallbackValue)
169 
170  return maskedImage
171 
172 
173 def saturationCorrection(maskedImage, saturation, fwhm, growFootprints=1, interpolate=True, maskName='SAT',
174  fallbackValue=None):
175  """Mark saturated pixels and optionally interpolate over them
176 
177  Parameters
178  ----------
179  maskedImage : `lsst.afw.image.MaskedImage`
180  Image to process.
181  saturation : scalar
182  Saturation level used as the detection threshold.
183  fwhm : scalar
184  FWHM of double Gaussian smoothing kernel.
185  growFootprints : scalar, optional
186  Number of pixels to grow footprints of detected regions.
187  interpolate : Bool, optional
188  If True, saturated pixels are interpolated over.
189  maskName : str, optional
190  Mask plane name.
191  fallbackValue : scalar, optional
192  Value of last resort for interpolation.
193  """
194  defectList = makeThresholdMask(
195  maskedImage=maskedImage,
196  threshold=saturation,
197  growFootprints=growFootprints,
198  maskName=maskName,
199  )
200  if interpolate:
201  interpolateDefectList(maskedImage, defectList, fwhm, fallbackValue=fallbackValue)
202 
203  return maskedImage
204 
205 
206 def trimToMatchCalibBBox(rawMaskedImage, calibMaskedImage):
207  """Compute number of edge trim pixels to match the calibration data.
208 
209  Use the dimension difference between the raw exposure and the
210  calibration exposure to compute the edge trim pixels. This trim
211  is applied symmetrically, with the same number of pixels masked on
212  each side.
213 
214  Parameters
215  ----------
216  rawMaskedImage : `lsst.afw.image.MaskedImage`
217  Image to trim.
218  calibMaskedImage : `lsst.afw.image.MaskedImage`
219  Calibration image to draw new bounding box from.
220 
221  Returns
222  -------
223  replacementMaskedImage : `lsst.afw.image.MaskedImage`
224  ``rawMaskedImage`` trimmed to the appropriate size
225  Raises
226  ------
227  RuntimeError
228  Rasied if ``rawMaskedImage`` cannot be symmetrically trimmed to
229  match ``calibMaskedImage``.
230  """
231  nx, ny = rawMaskedImage.getBBox().getDimensions() - calibMaskedImage.getBBox().getDimensions()
232  if nx != ny:
233  raise RuntimeError("Raw and calib maskedImages are trimmed differently in X and Y.")
234  if nx % 2 != 0:
235  raise RuntimeError("Calibration maskedImage is trimmed unevenly in X.")
236  if nx < 0:
237  raise RuntimeError("Calibration maskedImage is larger than raw data.")
238 
239  nEdge = nx//2
240  if nEdge > 0:
241  replacementMaskedImage = rawMaskedImage[nEdge:-nEdge, nEdge:-nEdge, afwImage.LOCAL]
242  SourceDetectionTask.setEdgeBits(
243  rawMaskedImage,
244  replacementMaskedImage.getBBox(),
245  rawMaskedImage.getMask().getPlaneBitMask("EDGE")
246  )
247  else:
248  replacementMaskedImage = rawMaskedImage
249 
250  return replacementMaskedImage
251 
252 
253 def biasCorrection(maskedImage, biasMaskedImage, trimToFit=False):
254  """Apply bias correction in place.
255 
256  Parameters
257  ----------
258  maskedImage : `lsst.afw.image.MaskedImage`
259  Image to process. The image is modified by this method.
260  biasMaskedImage : `lsst.afw.image.MaskedImage`
261  Bias image of the same size as ``maskedImage``
262  trimToFit : `Bool`, optional
263  If True, raw data is symmetrically trimmed to match
264  calibration size.
265 
266  Raises
267  ------
268  RuntimeError
269  Raised if ``maskedImage`` and ``biasMaskedImage`` do not have
270  the same size.
271 
272  """
273  if trimToFit:
274  maskedImage = trimToMatchCalibBBox(maskedImage, biasMaskedImage)
275 
276  if maskedImage.getBBox(afwImage.LOCAL) != biasMaskedImage.getBBox(afwImage.LOCAL):
277  raise RuntimeError("maskedImage bbox %s != biasMaskedImage bbox %s" %
278  (maskedImage.getBBox(afwImage.LOCAL), biasMaskedImage.getBBox(afwImage.LOCAL)))
279  maskedImage -= biasMaskedImage
280 
281 
282 def darkCorrection(maskedImage, darkMaskedImage, expScale, darkScale, invert=False, trimToFit=False):
283  """Apply dark correction in place.
284 
285  Parameters
286  ----------
287  maskedImage : `lsst.afw.image.MaskedImage`
288  Image to process. The image is modified by this method.
289  darkMaskedImage : `lsst.afw.image.MaskedImage`
290  Dark image of the same size as ``maskedImage``.
291  expScale : scalar
292  Dark exposure time for ``maskedImage``.
293  darkScale : scalar
294  Dark exposure time for ``darkMaskedImage``.
295  invert : `Bool`, optional
296  If True, re-add the dark to an already corrected image.
297  trimToFit : `Bool`, optional
298  If True, raw data is symmetrically trimmed to match
299  calibration size.
300 
301  Raises
302  ------
303  RuntimeError
304  Raised if ``maskedImage`` and ``darkMaskedImage`` do not have
305  the same size.
306 
307  Notes
308  -----
309  The dark correction is applied by calculating:
310  maskedImage -= dark * expScaling / darkScaling
311  """
312  if trimToFit:
313  maskedImage = trimToMatchCalibBBox(maskedImage, darkMaskedImage)
314 
315  if maskedImage.getBBox(afwImage.LOCAL) != darkMaskedImage.getBBox(afwImage.LOCAL):
316  raise RuntimeError("maskedImage bbox %s != darkMaskedImage bbox %s" %
317  (maskedImage.getBBox(afwImage.LOCAL), darkMaskedImage.getBBox(afwImage.LOCAL)))
318 
319  scale = expScale / darkScale
320  if not invert:
321  maskedImage.scaledMinus(scale, darkMaskedImage)
322  else:
323  maskedImage.scaledPlus(scale, darkMaskedImage)
324 
325 
326 def updateVariance(maskedImage, gain, readNoise):
327  """Set the variance plane based on the image plane.
328 
329  Parameters
330  ----------
331  maskedImage : `lsst.afw.image.MaskedImage`
332  Image to process. The variance plane is modified.
333  gain : scalar
334  The amplifier gain in electrons/ADU.
335  readNoise : scalar
336  The amplifier read nmoise in ADU/pixel.
337  """
338  var = maskedImage.getVariance()
339  var[:] = maskedImage.getImage()
340  var /= gain
341  var += readNoise**2
342 
343 
344 def flatCorrection(maskedImage, flatMaskedImage, scalingType, userScale=1.0, invert=False, trimToFit=False):
345  """Apply flat correction in place.
346 
347  Parameters
348  ----------
349  maskedImage : `lsst.afw.image.MaskedImage`
350  Image to process. The image is modified.
351  flatMaskedImage : `lsst.afw.image.MaskedImage`
352  Flat image of the same size as ``maskedImage``
353  scalingType : str
354  Flat scale computation method. Allowed values are 'MEAN',
355  'MEDIAN', or 'USER'.
356  userScale : scalar, optional
357  Scale to use if ``scalingType``='USER'.
358  invert : `Bool`, optional
359  If True, unflatten an already flattened image.
360  trimToFit : `Bool`, optional
361  If True, raw data is symmetrically trimmed to match
362  calibration size.
363 
364  Raises
365  ------
366  RuntimeError
367  Raised if ``maskedImage`` and ``flatMaskedImage`` do not have
368  the same size or if ``scalingType`` is not an allowed value.
369  """
370  if trimToFit:
371  maskedImage = trimToMatchCalibBBox(maskedImage, flatMaskedImage)
372 
373  if maskedImage.getBBox(afwImage.LOCAL) != flatMaskedImage.getBBox(afwImage.LOCAL):
374  raise RuntimeError("maskedImage bbox %s != flatMaskedImage bbox %s" %
375  (maskedImage.getBBox(afwImage.LOCAL), flatMaskedImage.getBBox(afwImage.LOCAL)))
376 
377  # Figure out scale from the data
378  # Ideally the flats are normalized by the calibration product pipeline, but this allows some flexibility
379  # in the case that the flat is created by some other mechanism.
380  if scalingType in ('MEAN', 'MEDIAN'):
381  scalingType = afwMath.stringToStatisticsProperty(scalingType)
382  flatScale = afwMath.makeStatistics(flatMaskedImage.image, scalingType).getValue()
383  elif scalingType == 'USER':
384  flatScale = userScale
385  else:
386  raise RuntimeError('%s : %s not implemented' % ("flatCorrection", scalingType))
387 
388  if not invert:
389  maskedImage.scaledDivides(1.0/flatScale, flatMaskedImage)
390  else:
391  maskedImage.scaledMultiplies(1.0/flatScale, flatMaskedImage)
392 
393 
394 def illuminationCorrection(maskedImage, illumMaskedImage, illumScale, trimToFit=True):
395  """Apply illumination correction in place.
396 
397  Parameters
398  ----------
399  maskedImage : `lsst.afw.image.MaskedImage`
400  Image to process. The image is modified.
401  illumMaskedImage : `lsst.afw.image.MaskedImage`
402  Illumination correction image of the same size as ``maskedImage``.
403  illumScale : scalar
404  Scale factor for the illumination correction.
405  trimToFit : `Bool`, optional
406  If True, raw data is symmetrically trimmed to match
407  calibration size.
408 
409  Raises
410  ------
411  RuntimeError
412  Raised if ``maskedImage`` and ``illumMaskedImage`` do not have
413  the same size.
414  """
415  if trimToFit:
416  maskedImage = trimToMatchCalibBBox(maskedImage, illumMaskedImage)
417 
418  if maskedImage.getBBox(afwImage.LOCAL) != illumMaskedImage.getBBox(afwImage.LOCAL):
419  raise RuntimeError("maskedImage bbox %s != illumMaskedImage bbox %s" %
420  (maskedImage.getBBox(afwImage.LOCAL), illumMaskedImage.getBBox(afwImage.LOCAL)))
421 
422  maskedImage.scaledDivides(1.0/illumScale, illumMaskedImage)
423 
424 
425 def overscanCorrection(ampMaskedImage, overscanImage, fitType='MEDIAN', order=1, collapseRej=3.0,
426  statControl=None, overscanIsInt=True):
427  """Apply overscan correction in place.
428 
429  Parameters
430  ----------
431  ampMaskedImage : `lsst.afw.image.MaskedImage`
432  Image of amplifier to correct; modified.
433  overscanImage : `lsst.afw.image.Image` or `lsst.afw.image.MaskedImage`
434  Image of overscan; modified.
435  fitType : `str`
436  Type of fit for overscan correction. May be one of:
437 
438  - ``MEAN``: use mean of overscan.
439  - ``MEANCLIP``: use clipped mean of overscan.
440  - ``MEDIAN``: use median of overscan.
441  - ``POLY``: fit with ordinary polynomial.
442  - ``CHEB``: fit with Chebyshev polynomial.
443  - ``LEG``: fit with Legendre polynomial.
444  - ``NATURAL_SPLINE``: fit with natural spline.
445  - ``CUBIC_SPLINE``: fit with cubic spline.
446  - ``AKIMA_SPLINE``: fit with Akima spline.
447 
448  order : `int`
449  Polynomial order or number of spline knots; ignored unless
450  ``fitType`` indicates a polynomial or spline.
451  statControl : `lsst.afw.math.StatisticsControl`
452  Statistics control object. In particular, we pay attention to numSigmaClip
453  overscanIsInt : `bool`
454  Treat the overscan region as consisting of integers, even if it's been
455  converted to float. E.g. handle ties properly.
456 
457  Returns
458  -------
459  result : `lsst.pipe.base.Struct`
460  Result struct with components:
461 
462  - ``imageFit``: Value(s) removed from image (scalar or
463  `lsst.afw.image.Image`)
464  - ``overscanFit``: Value(s) removed from overscan (scalar or
465  `lsst.afw.image.Image`)
466  - ``overscanImage``: Overscan corrected overscan region
467  (`lsst.afw.image.Image`)
468  Raises
469  ------
470  pexExcept.Exception
471  Raised if ``fitType`` is not an allowed value.
472 
473  Notes
474  -----
475  The ``ampMaskedImage`` and ``overscanImage`` are modified, with the fit
476  subtracted. Note that the ``overscanImage`` should not be a subimage of
477  the ``ampMaskedImage``, to avoid being subtracted twice.
478 
479  Debug plots are available for the SPLINE fitTypes by setting the
480  `debug.display` for `name` == "lsst.ip.isr.isrFunctions". These
481  plots show the scatter plot of the overscan data (collapsed along
482  the perpendicular dimension) as a function of position on the CCD
483  (normalized between +/-1).
484  """
485  ampImage = ampMaskedImage.getImage()
486  if statControl is None:
487  statControl = afwMath.StatisticsControl()
488 
489  numSigmaClip = statControl.getNumSigmaClip()
490 
491  if fitType in ('MEAN', 'MEANCLIP'):
492  fitType = afwMath.stringToStatisticsProperty(fitType)
493  offImage = afwMath.makeStatistics(overscanImage, fitType, statControl).getValue()
494  overscanFit = offImage
495  elif fitType in ('MEDIAN',):
496  if overscanIsInt:
497  # we need an image with integer pixels to handle ties properly
498  if hasattr(overscanImage, "image"):
499  imageI = overscanImage.image.convertI()
500  overscanImageI = afwImage.MaskedImageI(imageI, overscanImage.mask, overscanImage.variance)
501  else:
502  overscanImageI = overscanImage.convertI()
503  else:
504  overscanImageI = overscanImage
505 
506  fitType = afwMath.stringToStatisticsProperty(fitType)
507  offImage = afwMath.makeStatistics(overscanImageI, fitType, statControl).getValue()
508  overscanFit = offImage
509 
510  if overscanIsInt:
511  del overscanImageI
512  elif fitType in ('POLY', 'CHEB', 'LEG', 'NATURAL_SPLINE', 'CUBIC_SPLINE', 'AKIMA_SPLINE'):
513  if hasattr(overscanImage, "getImage"):
514  biasArray = overscanImage.getImage().getArray()
515  biasArray = numpy.ma.masked_where(overscanImage.getMask().getArray() & statControl.getAndMask(),
516  biasArray)
517  else:
518  biasArray = overscanImage.getArray()
519  # Fit along the long axis, so collapse along each short row and fit the resulting array
520  shortInd = numpy.argmin(biasArray.shape)
521  if shortInd == 0:
522  # Convert to some 'standard' representation to make things easier
523  biasArray = numpy.transpose(biasArray)
524 
525  # Do a single round of clipping to weed out CR hits and signal leaking into the overscan
526  percentiles = numpy.percentile(biasArray, [25.0, 50.0, 75.0], axis=1)
527  medianBiasArr = percentiles[1]
528  stdevBiasArr = 0.74*(percentiles[2] - percentiles[0]) # robust stdev
529  diff = numpy.abs(biasArray - medianBiasArr[:, numpy.newaxis])
530  biasMaskedArr = numpy.ma.masked_where(diff > numSigmaClip*stdevBiasArr[:, numpy.newaxis], biasArray)
531  collapsed = numpy.mean(biasMaskedArr, axis=1)
532  if collapsed.mask.sum() > 0:
533  collapsed.data[collapsed.mask] = numpy.mean(biasArray.data[collapsed.mask], axis=1)
534  del biasArray, percentiles, stdevBiasArr, diff, biasMaskedArr
535 
536  if shortInd == 0:
537  collapsed = numpy.transpose(collapsed)
538 
539  num = len(collapsed)
540  indices = 2.0*numpy.arange(num)/float(num) - 1.0
541 
542  if fitType in ('POLY', 'CHEB', 'LEG'):
543  # A numpy polynomial
544  poly = numpy.polynomial
545  fitter, evaler = {"POLY": (poly.polynomial.polyfit, poly.polynomial.polyval),
546  "CHEB": (poly.chebyshev.chebfit, poly.chebyshev.chebval),
547  "LEG": (poly.legendre.legfit, poly.legendre.legval),
548  }[fitType]
549 
550  coeffs = fitter(indices, collapsed, order)
551  fitBiasArr = evaler(indices, coeffs)
552  elif 'SPLINE' in fitType:
553  # An afw interpolation
554  numBins = order
555  #
556  # numpy.histogram needs a real array for the mask, but numpy.ma "optimises" the case
557  # no-values-are-masked by replacing the mask array by a scalar, numpy.ma.nomask
558  #
559  # Issue DM-415
560  #
561  collapsedMask = collapsed.mask
562  try:
563  if collapsedMask == numpy.ma.nomask:
564  collapsedMask = numpy.array(len(collapsed)*[numpy.ma.nomask])
565  except ValueError: # If collapsedMask is an array the test fails [needs .all()]
566  pass
567 
568  numPerBin, binEdges = numpy.histogram(indices, bins=numBins,
569  weights=1-collapsedMask.astype(int))
570  # Binning is just a histogram, with weights equal to the values.
571  # Use a similar trick to get the bin centers (this deals with different numbers per bin).
572  with numpy.errstate(invalid="ignore"): # suppress NAN warnings
573  values = numpy.histogram(indices, bins=numBins,
574  weights=collapsed.data*~collapsedMask)[0]/numPerBin
575  binCenters = numpy.histogram(indices, bins=numBins,
576  weights=indices*~collapsedMask)[0]/numPerBin
577  interp = afwMath.makeInterpolate(binCenters.astype(float)[numPerBin > 0],
578  values.astype(float)[numPerBin > 0],
580  fitBiasArr = numpy.array([interp.interpolate(i) for i in indices])
581 
582  import lsstDebug
583  if lsstDebug.Info(__name__).display:
584  import matplotlib.pyplot as plot
585  figure = plot.figure(1)
586  figure.clear()
587  axes = figure.add_axes((0.1, 0.1, 0.8, 0.8))
588  axes.plot(indices[~collapsedMask], collapsed[~collapsedMask], 'k+')
589  if collapsedMask.sum() > 0:
590  axes.plot(indices[collapsedMask], collapsed.data[collapsedMask], 'b+')
591  axes.plot(indices, fitBiasArr, 'r-')
592  plot.xlabel("centered/scaled position along overscan region")
593  plot.ylabel("pixel value/fit value")
594  figure.show()
595  prompt = "Press Enter or c to continue [chp]... "
596  while True:
597  ans = input(prompt).lower()
598  if ans in ("", "c",):
599  break
600  if ans in ("p",):
601  import pdb
602  pdb.set_trace()
603  elif ans in ("h", ):
604  print("h[elp] c[ontinue] p[db]")
605  plot.close()
606 
607  offImage = ampImage.Factory(ampImage.getDimensions())
608  offArray = offImage.getArray()
609  overscanFit = afwImage.ImageF(overscanImage.getDimensions())
610  overscanArray = overscanFit.getArray()
611  if shortInd == 1:
612  offArray[:, :] = fitBiasArr[:, numpy.newaxis]
613  overscanArray[:, :] = fitBiasArr[:, numpy.newaxis]
614  else:
615  offArray[:, :] = fitBiasArr[numpy.newaxis, :]
616  overscanArray[:, :] = fitBiasArr[numpy.newaxis, :]
617 
618  # We don't trust any extrapolation: mask those pixels as SUSPECT
619  # This will occur when the top and or bottom edges of the overscan
620  # contain saturated values. The values will be extrapolated from
621  # the surrounding pixels, but we cannot entirely trust the value of
622  # the extrapolation, and will mark the image mask plane to flag the
623  # image as such.
624  mask = ampMaskedImage.getMask()
625  maskArray = mask.getArray() if shortInd == 1 else mask.getArray().transpose()
626  suspect = mask.getPlaneBitMask("SUSPECT")
627  try:
628  if collapsed.mask == numpy.ma.nomask:
629  # There is no mask, so the whole array is fine
630  pass
631  except ValueError: # If collapsed.mask is an array the test fails [needs .all()]
632  for low in range(num):
633  if not collapsed.mask[low]:
634  break
635  if low > 0:
636  maskArray[:low, :] |= suspect
637  for high in range(1, num):
638  if not collapsed.mask[-high]:
639  break
640  if high > 1:
641  maskArray[-high:, :] |= suspect
642 
643  else:
644  raise pexExcept.Exception('%s : %s an invalid overscan type' % ("overscanCorrection", fitType))
645  ampImage -= offImage
646  overscanImage -= overscanFit
647  return Struct(imageFit=offImage, overscanFit=overscanFit, overscanImage=overscanImage)
648 
649 
650 def brighterFatterCorrection(exposure, kernel, maxIter, threshold, applyGain, gains=None):
651  """Apply brighter fatter correction in place for the image.
652 
653  Parameters
654  ----------
655  exposure : `lsst.afw.image.Exposure`
656  Exposure to have brighter-fatter correction applied. Modified
657  by this method.
658  kernel : `numpy.ndarray`
659  Brighter-fatter kernel to apply.
660  maxIter : scalar
661  Number of correction iterations to run.
662  threshold : scalar
663  Convergence threshold in terms of the sum of absolute
664  deviations between an iteration and the previous one.
665  applyGain : `Bool`
666  If True, then the exposure values are scaled by the gain prior
667  to correction.
668  gains : `dict` [`str`, `float`]
669  A dictionary, keyed by amplifier name, of the gains to use.
670  If gains is None, the nominal gains in the amplifier object are used.
671 
672  Returns
673  -------
674  diff : `float`
675  Final difference between iterations achieved in correction.
676  iteration : `int`
677  Number of iterations used to calculate correction.
678 
679  Notes
680  -----
681  This correction takes a kernel that has been derived from flat
682  field images to redistribute the charge. The gradient of the
683  kernel is the deflection field due to the accumulated charge.
684 
685  Given the original image I(x) and the kernel K(x) we can compute
686  the corrected image Ic(x) using the following equation:
687 
688  Ic(x) = I(x) + 0.5*d/dx(I(x)*d/dx(int( dy*K(x-y)*I(y))))
689 
690  To evaluate the derivative term we expand it as follows:
691 
692  0.5 * ( d/dx(I(x))*d/dx(int(dy*K(x-y)*I(y))) + I(x)*d^2/dx^2(int(dy* K(x-y)*I(y))) )
693 
694  Because we use the measured counts instead of the incident counts
695  we apply the correction iteratively to reconstruct the original
696  counts and the correction. We stop iterating when the summed
697  difference between the current corrected image and the one from
698  the previous iteration is below the threshold. We do not require
699  convergence because the number of iterations is too large a
700  computational cost. How we define the threshold still needs to be
701  evaluated, the current default was shown to work reasonably well
702  on a small set of images. For more information on the method see
703  DocuShare Document-19407.
704 
705  The edges as defined by the kernel are not corrected because they
706  have spurious values due to the convolution.
707  """
708  image = exposure.getMaskedImage().getImage()
709 
710  # The image needs to be units of electrons/holes
711  with gainContext(exposure, image, applyGain, gains):
712 
713  kLx = numpy.shape(kernel)[0]
714  kLy = numpy.shape(kernel)[1]
715  kernelImage = afwImage.ImageD(kLx, kLy)
716  kernelImage.getArray()[:, :] = kernel
717  tempImage = image.clone()
718 
719  nanIndex = numpy.isnan(tempImage.getArray())
720  tempImage.getArray()[nanIndex] = 0.
721 
722  outImage = afwImage.ImageF(image.getDimensions())
723  corr = numpy.zeros_like(image.getArray())
724  prev_image = numpy.zeros_like(image.getArray())
725  convCntrl = afwMath.ConvolutionControl(False, True, 1)
726  fixedKernel = afwMath.FixedKernel(kernelImage)
727 
728  # Define boundary by convolution region. The region that the correction will be
729  # calculated for is one fewer in each dimension because of the second derivative terms.
730  # NOTE: these need to use integer math, as we're using start:end as numpy index ranges.
731  startX = kLx//2
732  endX = -kLx//2
733  startY = kLy//2
734  endY = -kLy//2
735 
736  for iteration in range(maxIter):
737 
738  afwMath.convolve(outImage, tempImage, fixedKernel, convCntrl)
739  tmpArray = tempImage.getArray()
740  outArray = outImage.getArray()
741 
742  with numpy.errstate(invalid="ignore", over="ignore"):
743  # First derivative term
744  gradTmp = numpy.gradient(tmpArray[startY:endY, startX:endX])
745  gradOut = numpy.gradient(outArray[startY:endY, startX:endX])
746  first = (gradTmp[0]*gradOut[0] + gradTmp[1]*gradOut[1])[1:-1, 1:-1]
747 
748  # Second derivative term
749  diffOut20 = numpy.diff(outArray, 2, 0)[startY:endY, startX + 1:endX - 1]
750  diffOut21 = numpy.diff(outArray, 2, 1)[startY + 1:endY - 1, startX:endX]
751  second = tmpArray[startY + 1:endY - 1, startX + 1:endX - 1]*(diffOut20 + diffOut21)
752 
753  corr[startY + 1:endY - 1, startX + 1:endX - 1] = 0.5*(first + second)
754 
755  tmpArray[:, :] = image.getArray()[:, :]
756  tmpArray[nanIndex] = 0.
757  tmpArray[startY:endY, startX:endX] += corr[startY:endY, startX:endX]
758 
759  if iteration > 0:
760  diff = numpy.sum(numpy.abs(prev_image - tmpArray))
761 
762  if diff < threshold:
763  break
764  prev_image[:, :] = tmpArray[:, :]
765 
766  image.getArray()[startY + 1:endY - 1, startX + 1:endX - 1] += \
767  corr[startY + 1:endY - 1, startX + 1:endX - 1]
768 
769  return diff, iteration
770 
771 
772 @contextmanager
773 def gainContext(exp, image, apply, gains=None):
774  """Context manager that applies and removes gain.
775 
776  Parameters
777  ----------
778  exp : `lsst.afw.image.Exposure`
779  Exposure to apply/remove gain.
780  image : `lsst.afw.image.Image`
781  Image to apply/remove gain.
782  apply : `Bool`
783  If True, apply and remove the amplifier gain.
784  gains : `dict` [`str`, `float`]
785  A dictionary, keyed by amplifier name, of the gains to use.
786  If gains is None, the nominal gains in the amplifier object are used.
787 
788  Yields
789  ------
790  exp : `lsst.afw.image.Exposure`
791  Exposure with the gain applied.
792  """
793  # check we have all of them if provided because mixing and matching would
794  # be a real mess
795  if gains and apply is True:
796  ampNames = [amp.getName() for amp in exp.getDetector()]
797  for ampName in ampNames:
798  if ampName not in gains.keys():
799  raise RuntimeError(f"Gains provided to gain context, but no entry found for amp {ampName}")
800 
801  if apply:
802  ccd = exp.getDetector()
803  for amp in ccd:
804  sim = image.Factory(image, amp.getBBox())
805  if gains:
806  gain = gains[amp.getName()]
807  else:
808  gain = amp.getGain()
809  sim *= gain
810 
811  try:
812  yield exp
813  finally:
814  if apply:
815  ccd = exp.getDetector()
816  for amp in ccd:
817  sim = image.Factory(image, amp.getBBox())
818  if gains:
819  gain = gains[amp.getName()]
820  else:
821  gain = amp.getGain()
822  sim /= gain
823 
824 
825 def attachTransmissionCurve(exposure, opticsTransmission=None, filterTransmission=None,
826  sensorTransmission=None, atmosphereTransmission=None):
827  """Attach a TransmissionCurve to an Exposure, given separate curves for
828  different components.
829 
830  Parameters
831  ----------
832  exposure : `lsst.afw.image.Exposure`
833  Exposure object to modify by attaching the product of all given
834  ``TransmissionCurves`` in post-assembly trimmed detector coordinates.
835  Must have a valid ``Detector`` attached that matches the detector
836  associated with sensorTransmission.
837  opticsTransmission : `lsst.afw.image.TransmissionCurve`
838  A ``TransmissionCurve`` that represents the throughput of the optics,
839  to be evaluated in focal-plane coordinates.
840  filterTransmission : `lsst.afw.image.TransmissionCurve`
841  A ``TransmissionCurve`` that represents the throughput of the filter
842  itself, to be evaluated in focal-plane coordinates.
843  sensorTransmission : `lsst.afw.image.TransmissionCurve`
844  A ``TransmissionCurve`` that represents the throughput of the sensor
845  itself, to be evaluated in post-assembly trimmed detector coordinates.
846  atmosphereTransmission : `lsst.afw.image.TransmissionCurve`
847  A ``TransmissionCurve`` that represents the throughput of the
848  atmosphere, assumed to be spatially constant.
849 
850  Returns
851  -------
852  combined : `lsst.afw.image.TransmissionCurve`
853  The TransmissionCurve attached to the exposure.
854 
855  Notes
856  -----
857  All ``TransmissionCurve`` arguments are optional; if none are provided, the
858  attached ``TransmissionCurve`` will have unit transmission everywhere.
859  """
860  combined = afwImage.TransmissionCurve.makeIdentity()
861  if atmosphereTransmission is not None:
862  combined *= atmosphereTransmission
863  if opticsTransmission is not None:
864  combined *= opticsTransmission
865  if filterTransmission is not None:
866  combined *= filterTransmission
867  detector = exposure.getDetector()
868  fpToPix = detector.getTransform(fromSys=camGeom.FOCAL_PLANE,
869  toSys=camGeom.PIXELS)
870  combined = combined.transformedBy(fpToPix)
871  if sensorTransmission is not None:
872  combined *= sensorTransmission
873  exposure.getInfo().setTransmissionCurve(combined)
874  return combined
875 
876 
877 @deprecated(reason="Camera geometry-based SkyWcs are now set when reading raws. To be removed after v19.",
878  category=FutureWarning)
879 def addDistortionModel(exposure, camera):
880  """!Update the WCS in exposure with a distortion model based on camera
881  geometry.
882 
883  Parameters
884  ----------
885  exposure : `lsst.afw.image.Exposure`
886  Exposure to process. Must contain a Detector and WCS. The
887  exposure is modified.
888  camera : `lsst.afw.cameraGeom.Camera`
889  Camera geometry.
890 
891  Raises
892  ------
893  RuntimeError
894  Raised if ``exposure`` is lacking a Detector or WCS, or if
895  ``camera`` is None.
896  Notes
897  -----
898  Add a model for optical distortion based on geometry found in ``camera``
899  and the ``exposure``'s detector. The raw input exposure is assumed
900  have a TAN WCS that has no compensation for optical distortion.
901  Two other possibilities are:
902  - The raw input exposure already has a model for optical distortion,
903  as is the case for raw DECam data.
904  In that case you should set config.doAddDistortionModel False.
905  - The raw input exposure has a model for distortion, but it has known
906  deficiencies severe enough to be worth fixing (e.g. because they
907  cause problems for fitting a better WCS). In that case you should
908  override this method with a version suitable for your raw data.
909 
910  """
911  wcs = exposure.getWcs()
912  if wcs is None:
913  raise RuntimeError("exposure has no WCS")
914  if camera is None:
915  raise RuntimeError("camera is None")
916  detector = exposure.getDetector()
917  if detector is None:
918  raise RuntimeError("exposure has no Detector")
919  pixelToFocalPlane = detector.getTransform(camGeom.PIXELS, camGeom.FOCAL_PLANE)
920  focalPlaneToFieldAngle = camera.getTransformMap().getTransform(camGeom.FOCAL_PLANE,
921  camGeom.FIELD_ANGLE)
922  distortedWcs = makeDistortedTanWcs(wcs, pixelToFocalPlane, focalPlaneToFieldAngle)
923  exposure.setWcs(distortedWcs)
924 
925 
926 def applyGains(exposure, normalizeGains=False):
927  """Scale an exposure by the amplifier gains.
928 
929  Parameters
930  ----------
931  exposure : `lsst.afw.image.Exposure`
932  Exposure to process. The image is modified.
933  normalizeGains : `Bool`, optional
934  If True, then amplifiers are scaled to force the median of
935  each amplifier to equal the median of those medians.
936  """
937  ccd = exposure.getDetector()
938  ccdImage = exposure.getMaskedImage()
939 
940  medians = []
941  for amp in ccd:
942  sim = ccdImage.Factory(ccdImage, amp.getBBox())
943  sim *= amp.getGain()
944 
945  if normalizeGains:
946  medians.append(numpy.median(sim.getImage().getArray()))
947 
948  if normalizeGains:
949  median = numpy.median(numpy.array(medians))
950  for index, amp in enumerate(ccd):
951  sim = ccdImage.Factory(ccdImage, amp.getBBox())
952  if medians[index] != 0.0:
953  sim *= median/medians[index]
954 
955 
957  """Grow the saturation trails by an amount dependent on the width of the trail.
958 
959  Parameters
960  ----------
961  mask : `lsst.afw.image.Mask`
962  Mask which will have the saturated areas grown.
963  """
964 
965  extraGrowDict = {}
966  for i in range(1, 6):
967  extraGrowDict[i] = 0
968  for i in range(6, 8):
969  extraGrowDict[i] = 1
970  for i in range(8, 10):
971  extraGrowDict[i] = 3
972  extraGrowMax = 4
973 
974  if extraGrowMax <= 0:
975  return
976 
977  saturatedBit = mask.getPlaneBitMask("SAT")
978 
979  xmin, ymin = mask.getBBox().getMin()
980  width = mask.getWidth()
981 
982  thresh = afwDetection.Threshold(saturatedBit, afwDetection.Threshold.BITMASK)
983  fpList = afwDetection.FootprintSet(mask, thresh).getFootprints()
984 
985  for fp in fpList:
986  for s in fp.getSpans():
987  x0, x1 = s.getX0(), s.getX1()
988 
989  extraGrow = extraGrowDict.get(x1 - x0 + 1, extraGrowMax)
990  if extraGrow > 0:
991  y = s.getY() - ymin
992  x0 -= xmin + extraGrow
993  x1 -= xmin - extraGrow
994 
995  if x0 < 0:
996  x0 = 0
997  if x1 >= width - 1:
998  x1 = width - 1
999 
1000  mask.array[y, x0:x1+1] |= saturatedBit
1001 
1002 
1003 def setBadRegions(exposure, badStatistic="MEDIAN"):
1004  """Set all BAD areas of the chip to the average of the rest of the exposure
1005 
1006  Parameters
1007  ----------
1008  exposure : `lsst.afw.image.Exposure`
1009  Exposure to mask. The exposure mask is modified.
1010  badStatistic : `str`, optional
1011  Statistic to use to generate the replacement value from the
1012  image data. Allowed values are 'MEDIAN' or 'MEANCLIP'.
1013 
1014  Returns
1015  -------
1016  badPixelCount : scalar
1017  Number of bad pixels masked.
1018  badPixelValue : scalar
1019  Value substituted for bad pixels.
1020 
1021  Raises
1022  ------
1023  RuntimeError
1024  Raised if `badStatistic` is not an allowed value.
1025  """
1026  if badStatistic == "MEDIAN":
1027  statistic = afwMath.MEDIAN
1028  elif badStatistic == "MEANCLIP":
1029  statistic = afwMath.MEANCLIP
1030  else:
1031  raise RuntimeError("Impossible method %s of bad region correction" % badStatistic)
1032 
1033  mi = exposure.getMaskedImage()
1034  mask = mi.getMask()
1035  BAD = mask.getPlaneBitMask("BAD")
1036  INTRP = mask.getPlaneBitMask("INTRP")
1037 
1038  sctrl = afwMath.StatisticsControl()
1039  sctrl.setAndMask(BAD)
1040  value = afwMath.makeStatistics(mi, statistic, sctrl).getValue()
1041 
1042  maskArray = mask.getArray()
1043  imageArray = mi.getImage().getArray()
1044  badPixels = numpy.logical_and((maskArray & BAD) > 0, (maskArray & INTRP) == 0)
1045  imageArray[:] = numpy.where(badPixels, value, imageArray)
1046 
1047  return badPixels.sum(), value
Interpolate::Style stringToInterpStyle(std::string const &style)
Conversion function to switch a string to an Interpolate::Style.
Definition: Interpolate.cc:257
def addDistortionModel(exposure, camera)
Update the WCS in exposure with a distortion model based on camera geometry.
def saturationCorrection(maskedImage, saturation, fwhm, growFootprints=1, interpolate=True, maskName='SAT', fallbackValue=None)
def setBadRegions(exposure, badStatistic="MEDIAN")
Parameters to control convolution.
Definition: ConvolveImage.h:50
def interpolateFromMask(maskedImage, fwhm, growSaturatedFootprints=1, maskNameList=['SAT'], fallbackValue=None)
def interpolateDefectList(maskedImage, defectList, fwhm, fallbackValue=None)
Definition: isrFunctions.py:78
Provides consistent interface for LSST exceptions.
Definition: Exception.h:107
def brighterFatterCorrection(exposure, kernel, maxIter, threshold, applyGain, gains=None)
def transposeMaskedImage(maskedImage)
Definition: isrFunctions.py:58
Fit spatial kernel using approximate fluxes for candidates, and solving a linear system of equations...
def trimToMatchCalibBBox(rawMaskedImage, calibMaskedImage)
Statistics makeStatistics(lsst::afw::math::MaskedVector< EntryT > const &mv, std::vector< WeightPixel > const &vweights, int const flags, StatisticsControl const &sctrl=StatisticsControl())
The makeStatistics() overload to handle lsst::afw::math::MaskedVector<>
Definition: Statistics.h:520
def attachTransmissionCurve(exposure, opticsTransmission=None, filterTransmission=None, sensorTransmission=None, atmosphereTransmission=None)
Property stringToStatisticsProperty(std::string const property)
Conversion function to switch a string to a Property (see Statistics.h)
Definition: Statistics.cc:747
Pass parameters to a Statistics object.
Definition: Statistics.h:93
def flatCorrection(maskedImage, flatMaskedImage, scalingType, userScale=1.0, invert=False, trimToFit=False)
def makeThresholdMask(maskedImage, threshold, growFootprints=1, maskName='SAT')
std::shared_ptr< Interpolate > makeInterpolate(ndarray::Array< double const, 1 > const &x, ndarray::Array< double const, 1 > const &y, Interpolate::Style const style=Interpolate::AKIMA_SPLINE)
Definition: Interpolate.cc:353
def applyGains(exposure, normalizeGains=False)
def darkCorrection(maskedImage, darkMaskedImage, expScale, darkScale, invert=False, trimToFit=False)
def makeDistortedTanWcs(tanWcs, pixelToFocalPlane, focalPlaneToFieldAngle)
def biasCorrection(maskedImage, biasMaskedImage, trimToFit=False)
void convolve(OutImageT &convolvedImage, InImageT const &inImage, KernelT const &kernel, bool doNormalize, bool doCopyEdge=false)
Old, deprecated version of convolve.
Backwards-compatibility support for depersisting the old Calib (FluxMag0/FluxMag0Err) objects...
def gainContext(exp, image, apply, gains=None)
def illuminationCorrection(maskedImage, illumMaskedImage, illumScale, trimToFit=True)
def updateVariance(maskedImage, gain, readNoise)
def overscanCorrection(ampMaskedImage, overscanImage, fitType='MEDIAN', order=1, collapseRej=3.0, statControl=None, overscanIsInt=True)
A kernel created from an Image.
Definition: Kernel.h:518