34 """Make a double Gaussian PSF
36 @param[in] fwhm FWHM of double Gaussian smoothing kernel
37 @return measAlg.DoubleGaussianPsf
39 ksize = 4*int(fwhm) + 1
43 """Calculate effective gain
45 @param[in] maskedImage afw.image.MaskedImage to process
46 @return (median gain, mean gain) in e-/ADU
48 im = afwImage.ImageF(maskedImage.getImage(),
True)
49 var = maskedImage.getVariance()
53 return medgain, meangain
56 """Make a transposed copy of a masked image
58 @param[in] maskedImage afw.image.MaskedImage to process
59 @return transposed masked image
61 transposed = maskedImage.Factory(
afwGeom.Extent2I(maskedImage.getHeight(), maskedImage.getWidth()))
62 transposed.getImage().getArray()[:] = maskedImage.getImage().getArray().T
63 transposed.getMask().getArray()[:] = maskedImage.getMask().getArray().T
64 transposed.getVariance().getArray()[:] = maskedImage.getVariance().getArray().T
68 """Interpolate over defects specified in a defect list
70 @param[in,out] maskedImage masked image to process
71 @param[in] defectList defect list
72 @param[in] fwhm FWHM of double Gaussian smoothing kernel
73 @param[in] fallbackValue fallback value if an interpolated value cannot be determined;
74 if None then use clipped mean image value
77 if fallbackValue
is None:
79 if 'INTRP' not in maskedImage.getMask().getMaskPlaneDict().keys():
80 maskedImage.getMask.addMaskPlane(
'INTRP')
84 """Compute a defect list from a footprint list, optionally growing the footprints
86 @param[in] fpList footprint list
87 @param[in] growFootprints amount by which to grow footprints of detected regions
88 @return meas.algorithms.DefectListT
90 defectList = measAlg.DefectListT()
92 if growFootprints > 0:
100 defectList.push_back(defect)
104 """Make a transposed copy of a defect list
106 @param[in] defectList defect list
107 @return meas.algorithms.DefectListT with transposed defects
109 retDefectList = measAlg.DefectListT()
110 for defect
in defectList:
111 bbox = defect.getBBox()
118 """Set mask plane based on a defect list
120 @param[in,out] maskedImage afw.image.MaskedImage to process; mask plane is updated
121 @param[in] defectList meas.algorithms.DefectListT
122 @param[in] maskName mask plane name
125 mask = maskedImage.getMask()
126 bitmask = mask.getPlaneBitMask(maskName)
127 for defect
in defectList:
128 bbox = defect.getBBox()
132 """Compute a defect list from a specified mask plane
134 @param[in] maskedImage masked image to process
135 @param[in] maskName mask plane name, or list of names
136 @param[in] growFootprints amount by which to grow footprints of detected regions
137 @return meas.algrithms.DefectListT of regions in mask
139 mask = maskedImage.getMask()
140 workmask = afwImage.MaskU(mask,
True)
141 workmask &= mask.getPlaneBitMask(maskName)
143 maskimg = afwImage.ImageU(workmask.getBBox())
146 fpList = ds.getFootprints()
150 """Mask pixels based on threshold detection
152 @param[in,out] maskedImage afw.image.MaskedImage to process; the mask is altered
153 @param[in] threshold detection threshold
154 @param[in] growFootprints amount by which to grow footprints of detected regions
155 @param[in] maskName mask plane name
156 @return meas.algorihtms.DefectListT of regions set in the mask.
162 if growFootprints > 0:
165 fpList = fs.getFootprints()
167 mask = maskedImage.getMask()
168 bitmask = mask.getPlaneBitMask(maskName)
174 """Interpolate over defects identified by a particular mask plane
176 @param[in,out] maskedImage afw.image.MaskedImage to process
177 @param[in] fwhm FWHM of double Gaussian smoothing kernel
178 @param[in] growFootprints amount by which to grow footprints of detected regions
179 @param[in] maskName mask plane name
180 @param[in] fallbackValue value of last resort for interpolation
185 def saturationCorrection(maskedImage, saturation, fwhm, growFootprints=1, interpolate=True, maskName='SAT',
187 """Mark saturated pixels and optionally interpolate over them
189 @param[in,out] maskedImage afw.image.MaskedImage to process
190 @param[in] saturation saturation level (used as a detection threshold)
191 @param[in] fwhm FWHM of double Gaussian smoothing kernel
192 @param[in] growFootprints amount by which to grow footprints of detected regions
193 @param[in] interpolate interpolate over saturated pixels?
194 @param[in] maskName mask plane name
195 @param[in] fallbackValue value of last resort for interpolation
198 maskedImage = maskedImage,
199 threshold = saturation,
200 growFootprints = growFootprints,
207 """Apply bias correction in place
209 @param[in,out] maskedImage masked image to correct
210 @param[in] biasMaskedImage bias, as a masked image
212 if maskedImage.getBBox(afwImage.LOCAL) != biasMaskedImage.getBBox(afwImage.LOCAL):
213 raise RuntimeError(
"maskedImage bbox %s != biasMaskedImage bbox %s" % \
214 (maskedImage.getBBox(afwImage.LOCAL), biasMaskedImage.getBBox(afwImage.LOCAL)))
215 maskedImage -= biasMaskedImage
218 """Apply dark correction in place
220 maskedImage -= dark * expScaling / darkScaling
222 @param[in,out] maskedImage afw.image.MaskedImage to correct
223 @param[in] darkMaskedImage dark afw.image.MaskedImage
224 @param[in] expScale exposure scale
225 @param[in] darkScale dark scale
227 if maskedImage.getBBox(afwImage.LOCAL) != darkMaskedImage.getBBox(afwImage.LOCAL):
228 raise RuntimeError(
"maskedImage bbox %s != darkMaskedImage bbox %s" % \
229 (maskedImage.getBBox(afwImage.LOCAL), darkMaskedImage.getBBox(afwImage.LOCAL)))
231 scale = expScale / darkScale
232 maskedImage.scaledMinus(scale, darkMaskedImage)
235 """Set the variance plane based on the image plane
237 @param[in,out] maskedImage afw.image.MaskedImage; image plane is read and variance plane is written
238 @param[in] gain amplifier gain (e-/ADU)
239 @param[in] readNoise amplifier read noise (ADU/pixel)
241 var = maskedImage.getVariance()
242 var <<= maskedImage.getImage()
247 """Apply flat correction in place
249 @param[in,out] maskedImage afw.image.MaskedImage to correct
250 @param[in] flatMaskedImage flat field afw.image.MaskedImage
251 @param[in] scalingType how to compute flat scale; one of 'MEAN', 'MEDIAN' or 'USER'
252 @param[in] userScale scale to use if scalingType is 'USER', else ignored
254 if maskedImage.getBBox(afwImage.LOCAL) != flatMaskedImage.getBBox(afwImage.LOCAL):
255 raise RuntimeError(
"maskedImage bbox %s != flatMaskedImage bbox %s" % \
256 (maskedImage.getBBox(afwImage.LOCAL), flatMaskedImage.getBBox(afwImage.LOCAL)))
261 if scalingType ==
'MEAN':
263 elif scalingType ==
'MEDIAN':
265 elif scalingType ==
'USER':
266 flatScale = userScale
270 maskedImage.scaledDivides(1.0/flatScale, flatMaskedImage)
273 """Apply illumination correction in place
275 @param[in,out] maskedImage afw.image.MaskedImage to correct
276 @param[in] illumMaskedImage illumination correction masked image
277 @param[in] illumScale scale value for illumination correction
279 if maskedImage.getBBox(afwImage.LOCAL) != illumMaskedImage.getBBox(afwImage.LOCAL):
280 raise RuntimeError(
"maskedImage bbox %s != illumMaskedImage bbox %s" % \
281 (maskedImage.getBBox(afwImage.LOCAL), illumMaskedImage.getBBox(afwImage.LOCAL)))
283 maskedImage.scaledDivides(1./illumScale, illumMaskedImage)
285 def overscanCorrection(ampMaskedImage, overscanImage, fitType='MEDIAN', order=1, collapseRej=3.0,
287 """Apply overscan correction in place
289 @param[in,out] ampMaskedImage masked image to correct
290 @param[in] overscanImage overscan data as an afw.image.Image or afw.image.MaskedImage.
291 If a masked image is passed in the mask plane will be used
292 to constrain the fit of the bias level.
293 @param[in] fitType type of fit for overscan correction; one of:
296 - 'POLY' (ordinary polynomial)
297 - 'CHEB' (Chebyshev polynomial)
298 - 'LEG' (Legendre polynomial)
299 - 'NATURAL_SPLINE', 'CUBIC_SPLINE', 'AKIMA_SPLINE' (splines)
300 @param[in] order polynomial order or spline knots (ignored unless fitType
301 indicates a polynomial or spline)
302 @param[in] collapseRej Rejection threshold (sigma) for collapsing dimension of overscan
303 @param[in] statControl Statistics control object
305 ampImage = ampMaskedImage.getImage()
306 if statControl
is None:
308 if fitType ==
'MEAN':
310 elif fitType ==
'MEDIAN':
312 elif fitType
in (
'POLY',
'CHEB',
'LEG',
'NATURAL_SPLINE',
'CUBIC_SPLINE',
'AKIMA_SPLINE'):
313 if hasattr(overscanImage,
"getImage"):
314 biasArray = overscanImage.getImage().getArray()
315 biasArray = numpy.ma.masked_where(overscanImage.getMask().getArray() & statControl.getAndMask(),
318 biasArray = overscanImage.getArray()
320 shortInd = numpy.argmin(biasArray.shape)
323 biasArray = numpy.transpose(biasArray)
326 percentiles = numpy.percentile(biasArray, [25.0, 50.0, 75.0], axis=1)
327 medianBiasArr = percentiles[1]
328 stdevBiasArr = 0.74*(percentiles[2] - percentiles[0])
329 diff = numpy.abs(biasArray - medianBiasArr[:,numpy.newaxis])
330 biasMaskedArr = numpy.ma.masked_where(diff > collapseRej*stdevBiasArr[:,numpy.newaxis], biasArray)
331 collapsed = numpy.mean(biasMaskedArr, axis=1)
332 del biasArray, percentiles, stdevBiasArr, diff, biasMaskedArr
335 collapsed = numpy.transpose(collapsed)
338 indices = 2.0*numpy.arange(num)/float(num) - 1.0
340 if fitType
in (
'POLY',
'CHEB',
'LEG'):
342 poly = numpy.polynomial
343 fitter, evaler = {
"POLY": (poly.polynomial.polyfit, poly.polynomial.polyval),
344 "CHEB": (poly.chebyshev.chebfit, poly.chebyshev.chebval),
345 "LEG": (poly.legendre.legfit, poly.legendre.legval),
348 coeffs = fitter(indices, collapsed, order)
349 fitBiasArr = evaler(indices, coeffs)
350 elif 'SPLINE' in fitType:
359 collapsedMask = collapsed.mask
361 if collapsedMask == numpy.ma.nomask:
362 collapsedMask = numpy.array(len(collapsed)*[numpy.ma.nomask])
366 numPerBin, binEdges = numpy.histogram(indices, bins=numBins,
367 weights=1-collapsedMask.astype(int))
370 values = numpy.histogram(indices, bins=numBins, weights=collapsed)[0]/numPerBin
371 binCenters = numpy.histogram(indices, bins=numBins, weights=indices)[0]/numPerBin
373 values.astype(float)[numPerBin > 0],
375 fitBiasArr = numpy.array([interp.interpolate(i)
for i
in indices])
379 import matplotlib.pyplot
as plot
380 figure = plot.figure(1)
382 axes = figure.add_axes((0.1, 0.1, 0.8, 0.8))
383 axes.plot(indices, collapsed,
'k+')
384 axes.plot(indices, fitBiasArr,
'r-')
386 prompt =
"Press Enter or c to continue [chp]... "
388 ans = raw_input(prompt).lower()
389 if ans
in (
"",
"c",):
392 import pdb; pdb.set_trace()
394 print "h[elp] c[ontinue] p[db]"
397 offImage = ampImage.Factory(ampImage.getDimensions())
398 offArray = offImage.getArray()
400 offArray[:,:] = fitBiasArr[:,numpy.newaxis]
402 offArray[:,:] = fitBiasArr[numpy.newaxis,:]
410 mask = ampMaskedImage.getMask()
411 maskArray = mask.getArray()
if shortInd == 1
else mask.getArray().transpose()
412 suspect = mask.getPlaneBitMask(
"SUSPECT")
414 if collapsed.mask == numpy.ma.nomask:
418 for low
in xrange(num):
419 if not collapsed.mask[low]:
422 maskArray[:low,:] |= suspect
423 for high
in xrange(1, num):
424 if not collapsed.mask[-high]:
427 maskArray[-high:,:] |= suspect
431 (
"overscanCorrection", fitType)
Interpolate::Style stringToInterpStyle(std::string const &style)
Conversion function to switch a string to an Interpolate::Style.
boost::shared_ptr< Footprint > growFootprint(Footprint const &foot, int nGrow, bool left, bool right, bool up, bool down)
Grow a Footprint in at least one of the cardinal directions, returning a new Footprint.
boost::shared_ptr< Interpolate > makeInterpolate(std::vector< double > const &x, std::vector< double > const &y, Interpolate::Style const style=Interpolate::AKIMA_SPLINE)
A Threshold is used to pass a threshold value to detection algorithms.
An integer coordinate rectangle.
def maskPixelsFromDefectList
void interpolateOverDefects(MaskedImageT &image, lsst::afw::detection::Psf const &psf, std::vector< Defect::Ptr > &badList, double fallbackValue=0.0, bool useFallbackValueAtEdge=false)
Process a set of known bad pixels in an image.
Represent a Psf as a circularly symmetrical double Gaussian.
def interpolateDefectList
Pass parameters to a Statistics objectA class to pass parameters which control how the stats are calc...
def illuminationCorrection
def getDefectListFromMask
std::vector< lsst::afw::geom::Box2I > footprintToBBoxList(Footprint const &foot)
MaskT setMaskFromFootprint(lsst::afw::image::Mask< MaskT > *mask, Footprint const &footprint, MaskT const bitmask)
OR bitmask into all the Mask's pixels that are in the Footprint.
Statistics makeStatistics(afwImage::Mask< afwImage::MaskPixel > const &msk, int const flags, StatisticsControl const &sctrl)
Specialization to handle Masks.
MaskT setMaskFromFootprintList(lsst::afw::image::Mask< MaskT > *mask, boost::shared_ptr< std::vector< boost::shared_ptr< Footprint >> const > const &footprints, MaskT const bitmask)
OR bitmask into all the Mask's pixels which are in the set of Footprints.
Encapsulate information about a bad portion of a detector.
def defectListFromFootprintList