def setUp(self):
        if not defDataDir:
            return

        self.configAL = ipDiffim.ImagePsfMatchTask.ConfigClass()
        self.configAL.kernel.name = "AL"
        self.subconfigAL = self.configAL.kernel.active

        self.configDF = ipDiffim.ImagePsfMatchTask.ConfigClass()
        self.configDF.kernel.name = "DF"
        self.subconfigDF = self.configDF.kernel.active

        self.configDFr = ipDiffim.ImagePsfMatchTask.ConfigClass()
        self.configDFr.kernel.name = "DF"
        self.subconfigDFr = self.configDFr.kernel.active

        self.subconfigDF.useRegularization = False
        self.subconfigDFr.useRegularization = True

        self.scienceExposure = afwImage.ExposureF(defSciencePath)
        self.templateExposure = afwImage.ExposureF(defTemplatePath)

        warper = afwMath.Warper.fromConfig(self.subconfigAL.warpingConfig)
        self.templateExposure = warper.warpExposure(self.scienceExposure.getWcs(), self.templateExposure,
                                                    destBBox=self.scienceExposure.getBBox())

        self.scienceMaskedImage = self.scienceExposure.getMaskedImage()
        self.templateMaskedImage = self.templateExposure.getMaskedImage()

        bgConfig = self.subconfigAL.afwBackgroundConfig
        diffimTools.backgroundSubtract(bgConfig, [self.templateMaskedImage,
                                                  self.scienceMaskedImage])
    def testGetCollection(self):
        # NOTE - you need to subtract off background from the image
        # you run detection on.  Here it is the template.
        bgConfig = self.subconfig.afwBackgroundConfig
        diffimTools.backgroundSubtract(bgConfig, [
            self.templateImage,
        ])

        detConfig = self.subconfig.detectionConfig
        maskPlane = detConfig.badMaskPlanes[0]
        maskVal = afwImage.Mask.getPlaneBitMask(maskPlane)

        kcDetect = ipDiffim.KernelCandidateDetectionF(
            pexConfig.makePolicy(detConfig))
        kcDetect.apply(self.templateImage, self.scienceImage)
        fpList1 = kcDetect.getFootprints()

        self.assertNotEqual(len(fpList1), 0)

        for fp in fpList1:
            bbox = fp.getBBox()
            tmi = afwImage.MaskedImageF(self.templateImage,
                                        bbox,
                                        origin=afwImage.LOCAL)
            smi = afwImage.MaskedImageF(self.scienceImage,
                                        bbox,
                                        origin=afwImage.LOCAL)
            tmask = tmi.getMask()
            smask = smi.getMask()

            for j in range(tmask.getHeight()):
                for i in range(tmask.getWidth()):
                    # No masked pixels in either image
                    self.assertEqual(tmask.get(i, j), 0)
                    self.assertEqual(smask.get(i, j), 0)

        # add a masked pixel to the template image and make sure you don't get it
        afwImage.MaskedImageF(self.templateImage,
                              fpList1[0].getBBox(),
                              origin=afwImage.LOCAL).getMask().set(
                                  tmask.getWidth() // 2,
                                  tmask.getHeight() // 2, maskVal)
        kcDetect.apply(self.templateImage, self.scienceImage)
        fpList2 = kcDetect.getFootprints()
        self.assertEqual(len(fpList2), (len(fpList1) - 1))

        # add a masked pixel to the science image and make sure you don't get it
        afwImage.MaskedImageF(self.scienceImage,
                              fpList1[1].getBBox(),
                              origin=afwImage.LOCAL).getMask().set(
                                  smask.getWidth() // 2,
                                  smask.getHeight() // 2, maskVal)
        afwImage.MaskedImageF(self.scienceImage,
                              fpList1[2].getBBox(),
                              origin=afwImage.LOCAL).getMask().set(
                                  smask.getWidth() // 2,
                                  smask.getHeight() // 2, maskVal)
        kcDetect.apply(self.templateImage, self.scienceImage)
        fpList3 = kcDetect.getFootprints()
        self.assertEqual(len(fpList3), (len(fpList1) - 3))
Esempio n. 3
0
    def setUp(self):
        if not defDataDir:
            return

        self.configAL = ipDiffim.ImagePsfMatchTask.ConfigClass()
        self.configAL.kernel.name = "AL"
        self.subconfigAL = self.configAL.kernel.active

        self.configDF = ipDiffim.ImagePsfMatchTask.ConfigClass()
        self.configDF.kernel.name = "DF"
        self.subconfigDF = self.configDF.kernel.active

        self.configDFr = ipDiffim.ImagePsfMatchTask.ConfigClass()
        self.configDFr.kernel.name = "DF"
        self.subconfigDFr = self.configDFr.kernel.active

        self.subconfigDF.useRegularization = False
        self.subconfigDFr.useRegularization = True

        self.scienceExposure = afwImage.ExposureF(defSciencePath)
        self.templateExposure = afwImage.ExposureF(defTemplatePath)

        warper = afwMath.Warper.fromConfig(self.subconfigAL.warpingConfig)
        self.templateExposure = warper.warpExposure(self.scienceExposure.getWcs(), self.templateExposure,
                                                    destBBox=self.scienceExposure.getBBox())

        self.scienceMaskedImage = self.scienceExposure.getMaskedImage()
        self.templateMaskedImage = self.templateExposure.getMaskedImage()
        self.dStats = ipDiffim.ImageStatisticsF()

        bgConfig = self.subconfigAL.afwBackgroundConfig
        diffimTools.backgroundSubtract(bgConfig, [self.templateMaskedImage,
                                                  self.scienceMaskedImage])
    def testGetCollection(self):
        if not self.defDataDir:
            print >> sys.stderr, "Warning: afwdata is not set up; not running KernelCandidateDetection.py"
            return

        # NOTE - you need to subtract off background from the image
        # you run detection on.  Here it is the template.
        bgConfig = self.subconfig.afwBackgroundConfig
        diffimTools.backgroundSubtract(bgConfig, [self.templateImage,])

        detConfig = self.subconfig.detectionConfig
        maskPlane = detConfig.badMaskPlanes[0]
        maskVal   = afwImage.MaskU.getPlaneBitMask(maskPlane)

        kcDetect = ipDiffim.KernelCandidateDetectionF(pexConfig.makePolicy(detConfig))
        kcDetect.apply(self.templateImage, self.scienceImage)
        fpList1 = kcDetect.getFootprints()

        self.assertTrue(len(fpList1) != 0)

        for fp in fpList1:
            bbox = fp.getBBox()
            tmi  = afwImage.MaskedImageF(self.templateImage, bbox, afwImage.LOCAL)
            smi  = afwImage.MaskedImageF(self.scienceImage, bbox, afwImage.LOCAL)
            tmask = tmi.getMask()
            smask = smi.getMask()

            for j in range(tmask.getHeight()):
                for i in range(tmask.getWidth()):
                    # No masked pixels in either image
                    self.assertEqual(tmask.get(i, j), 0)
                    self.assertEqual(smask.get(i, j), 0)

        # add a masked pixel to the template image and make sure you don't get it
        afwImage.MaskedImageF(self.templateImage, fpList1[0].getBBox(), afwImage.LOCAL).getMask().set(
            tmask.getWidth()//2, tmask.getHeight()//2, maskVal)
        kcDetect.apply(self.templateImage, self.scienceImage)
        fpList2 = kcDetect.getFootprints()
        self.assertTrue(len(fpList2) == (len(fpList1)-1))

        # add a masked pixel to the science image and make sure you don't get it
        afwImage.MaskedImageF(self.scienceImage, fpList1[1].getBBox(), afwImage.LOCAL).getMask().set(
            smask.getWidth()//2, smask.getHeight()//2, maskVal)
        afwImage.MaskedImageF(self.scienceImage, fpList1[2].getBBox(), afwImage.LOCAL).getMask().set(
            smask.getWidth()//2, smask.getHeight()//2, maskVal)
        kcDetect.apply(self.templateImage, self.scienceImage)
        fpList3 = kcDetect.getFootprints()
        self.assertTrue(len(fpList3) == (len(fpList1)-3))
    def setUp(self):
        self.config = ipDiffim.ImagePsfMatchTask.ConfigClass()
        self.config.kernel.name = "AL"
        self.subconfig = self.config.kernel.active

        # Some of the tests are sensitive to the centroids returned by
        # "stdev" vs "pixel_stdev"
        self.subconfig.detectionConfig.detThresholdType = "stdev"

        # Impacts some of the test values
        self.subconfig.constantVarianceWeighting = True

        try:
            self.defDataDir = lsst.utils.getPackageDir('afwdata')
        except Exception:
            self.defDataDir = None

        if self.defDataDir:

            defTemplatePath = os.path.join(self.defDataDir, "DC3a-Sim", "sci",
                                           "v5-e0", "v5-e0-c011-a00.sci.fits")
            defSciencePath = os.path.join(self.defDataDir, "DC3a-Sim", "sci",
                                          "v26-e0", "v26-e0-c011-a00.sci.fits")

            self.scienceImage = afwImage.ExposureF(defSciencePath)
            self.templateImage = afwImage.ExposureF(defTemplatePath)

            bgConfig = self.subconfig.afwBackgroundConfig
            bgConfig.useApprox = False
            bgConfig.binSize = 512
            diffimTools.backgroundSubtract(bgConfig, [
                self.templateImage.getMaskedImage(),
                self.scienceImage.getMaskedImage()
            ])

            self.offset = 1500
            self.bbox = afwGeom.Box2I(afwGeom.Point2I(0, self.offset),
                                      afwGeom.Point2I(511, 2046))
            self.subconfig.spatialKernelOrder = 1
            self.subconfig.spatialBgOrder = 0

            # Take a stab at a PSF.  This is needed to get the KernelCandidateList if you don't provide one.
            ksize = 21
            sigma = 2.0
            self.psf = measAlg.DoubleGaussianPsf(ksize, ksize, sigma)
            self.scienceImage.setPsf(self.psf)
Esempio n. 6
0
    def setUp(self):
        self.config    = ipDiffim.ImagePsfMatchTask.ConfigClass()
        self.config.kernel.name = "AL"
        self.subconfig = self.config.kernel.active

        # Some of the tests are sensitive to the centroids returned by
        # "stdev" vs "pixel_stdev"
        self.subconfig.detectionConfig.detThresholdType = "stdev"

        # Impacts some of the test values
        self.subconfig.constantVarianceWeighting = True

        try:
            self.defDataDir = lsst.utils.getPackageDir('afwdata')
        except Exception:
            self.defDataDir = None

        if self.defDataDir:

            defTemplatePath = os.path.join(self.defDataDir, "DC3a-Sim", "sci", "v5-e0",
                                           "v5-e0-c011-a00.sci.fits")
            defSciencePath = os.path.join(self.defDataDir, "DC3a-Sim", "sci", "v26-e0",
                                          "v26-e0-c011-a00.sci.fits")

            self.scienceImage   = afwImage.ExposureF(defSciencePath)
            self.templateImage  = afwImage.ExposureF(defTemplatePath)

            bgConfig = self.subconfig.afwBackgroundConfig
            bgConfig.useApprox = False
            bgConfig.binSize = 512
            diffimTools.backgroundSubtract(bgConfig,
                                           [self.templateImage.getMaskedImage(),
                                            self.scienceImage.getMaskedImage()])

            self.offset   = 1500
            self.bbox     = afwGeom.Box2I(afwGeom.Point2I(0, self.offset),
                                          afwGeom.Point2I(511, 2046))
            self.subconfig.spatialKernelOrder = 1
            self.subconfig.spatialBgOrder = 0

            # Take a stab at a PSF.  This is needed to get the KernelCandidateList if you don't provide one.
            ksize  = 21
            sigma = 2.0
            self.psf = measAlg.DoubleGaussianPsf(ksize, ksize, sigma)
            self.scienceImage.setPsf(self.psf)
    def testGetCollection(self):
        # NOTE - you need to subtract off background from the image
        # you run detection on.  Here it is the template.
        bgConfig = self.subconfig.afwBackgroundConfig
        diffimTools.backgroundSubtract(bgConfig, [self.templateImage, ])

        detConfig = self.subconfig.detectionConfig
        maskPlane = detConfig.badMaskPlanes[0]
        maskVal = afwImage.Mask.getPlaneBitMask(maskPlane)

        kcDetect = ipDiffim.KernelCandidateDetectionF(pexConfig.makePolicy(detConfig))
        kcDetect.apply(self.templateImage, self.scienceImage)
        fpList1 = kcDetect.getFootprints()

        self.assertNotEqual(len(fpList1), 0)

        for fp in fpList1:
            bbox = fp.getBBox()
            tmi = afwImage.MaskedImageF(self.templateImage, bbox, origin=afwImage.LOCAL)
            smi = afwImage.MaskedImageF(self.scienceImage, bbox, origin=afwImage.LOCAL)
            tmask = tmi.getMask()
            smask = smi.getMask()

            for j in range(tmask.getHeight()):
                for i in range(tmask.getWidth()):
                    # No masked pixels in either image
                    self.assertEqual(tmask[i, j, afwImage.LOCAL], 0)
                    self.assertEqual(smask[i, j, afwImage.LOCAL], 0)

        # add a masked pixel to the template image and make sure you don't get it
        tp = afwGeom.Point2I(tmask.getWidth()//2, tmask.getHeight()//2)
        self.templateImage.mask[fpList1[0].getBBox(), afwImage.LOCAL][tp, afwImage.LOCAL] = maskVal
        kcDetect.apply(self.templateImage, self.scienceImage)
        fpList2 = kcDetect.getFootprints()
        self.assertEqual(len(fpList2), (len(fpList1)-1))

        # add a masked pixel to the science image and make sure you don't get it
        sp = afwGeom.Point2I(smask.getWidth()//2, smask.getHeight()//2)
        self.scienceImage.mask[fpList1[1].getBBox(), afwImage.LOCAL][sp, afwImage.LOCAL] = maskVal
        self.scienceImage.mask[fpList1[2].getBBox(), afwImage.LOCAL][sp, afwImage.LOCAL] = maskVal
        kcDetect.apply(self.templateImage, self.scienceImage)
        fpList3 = kcDetect.getFootprints()
        self.assertEqual(len(fpList3), (len(fpList1)-3))
Esempio n. 8
0
def main():
    defDataDir = lsst.utils.getPackageDir('afwdata')

    defSciencePath = os.path.join(defDataDir, "DC3a-Sim", "sci", "v26-e0",
                                  "v26-e0-c011-a10.sci.fits")
    defTemplatePath = os.path.join(defDataDir, "DC3a-Sim", "sci", "v5-e0",
                                   "v5-e0-c011-a10.sci.fits")

    defOutputPath = 'diffExposure.fits'
    defVerbosity = 0
    defFwhm = 3.5
    sigma2fwhm = 2. * np.sqrt(2. * np.log(2.))

    usage = """usage: %%prog [options] [scienceExposure [templateExposure [outputExposure]]]]

Notes:
- image arguments are paths to Expoure fits files
- image arguments must NOT include the final _img.fits
- the result is science image - template image
- the template exposure is convolved, the science exposure is not
- default scienceExposure=%s
- default templateExposure=%s
- default outputExposure=%s
""" % (defSciencePath, defTemplatePath, defOutputPath)

    parser = optparse.OptionParser(usage)
    parser.add_option('-v',
                      '--verbosity',
                      type=int,
                      default=defVerbosity,
                      help='verbosity of Trace messages')
    parser.add_option('-d',
                      '--display',
                      action='store_true',
                      default=False,
                      help='display the images')
    parser.add_option('-b',
                      '--bg',
                      action='store_true',
                      default=False,
                      help='subtract backgrounds using afw')
    parser.add_option('--fwhmS',
                      type=float,
                      help='Science Image Psf Fwhm (pixel)')
    parser.add_option('--fwhmT',
                      type=float,
                      help='Template Image Psf Fwhm (pixel)')

    (options, args) = parser.parse_args()

    def getArg(ind, defValue):
        if ind < len(args):
            return args[ind]
        return defValue

    sciencePath = getArg(0, defSciencePath)
    templatePath = getArg(1, defTemplatePath)
    outputPath = getArg(2, defOutputPath)

    if sciencePath is None or templatePath is None:
        parser.print_help()
        sys.exit(1)

    print('Science exposure: ', sciencePath)
    print('Template exposure:', templatePath)
    print('Output exposure:  ', outputPath)

    templateExposure = afwImage.ExposureF(templatePath)
    scienceExposure = afwImage.ExposureF(sciencePath)

    config = ipDiffim.ImagePsfMatchTask.ConfigClass()
    config.kernel.name = "AL"
    subconfig = config.kernel.active

    fwhmS = defFwhm
    if options.fwhmS:
        if scienceExposure.hasPsf():
            sciPsf = scienceExposure.getPsf()
            fwhm = sciPsf.computeShape(sciPsf.getAveragePosition()
                                       ).getDeterminantRadius() * sigma2fwhm
            print('NOTE: Embedded Psf has FwhmS =', fwhm)
        print('USING: FwhmS =', options.fwhmS)
        fwhmS = options.fwhmS

    fwhmT = defFwhm
    if options.fwhmT:
        if templateExposure.hasPsf():
            templPsf = templateExposure.getPsf()
            fwhm = templPsf.computeShape(templPsf.getAveragePosition()
                                         ).getDeterminantRadius() * sigma2fwhm
            print('NOTE: Embedded Psf has FwhmT =', fwhm)
        print('USING: FwhmT =', options.fwhmT)
        fwhmT = options.fwhmT

    bgSub = False
    if options.bg:
        print('Background subtract =', options.bg)
        bgSub = True

    if options.verbosity > 0:
        print('Verbosity =', options.verbosity)
        logUtils.trace_set_at("lsst.ip.diffim", options.verbosity)

    ####

    if bgSub:
        diffimTools.backgroundSubtract(subconfig.afwBackgroundConfig, [
            templateExposure.getMaskedImage(),
            scienceExposure.getMaskedImage()
        ])
    else:
        if not subconfig.fitForBackground:
            print('NOTE: no background subtraction at all is requested')

    # ImagePsfMatchTask requires a candidateList or that the exposoure have a PSF for detection
    if not scienceExposure.hasPsf():
        sigmaS = fwhmS / sigma2fwhm
        kSize = int(6 * sigmaS)  # minimum kernel size for FWHM
        oddKSize = kSize + 1 if kSize % 2 == 0 else kSize
        scienceExposure.setPsf(SingleGaussianPsf(oddKSize, oddKSize, sigmaS))

    psfmatch = ipDiffim.ImagePsfMatchTask(config)
    results = psfmatch.subtractExposures(templateExposure,
                                         scienceExposure,
                                         templateFwhmPix=fwhmT,
                                         scienceFwhmPix=fwhmS)

    differenceExposure = results.subtractedExposure
    differenceExposure.writeFits(outputPath)

    if False:
        psfMatchingKernel = results.psfMatchingKernel
        backgroundModel = results.backgroundModel
        kernelCellSet = results.kernelCellSet

        diffimTools.writeKernelCellSet(kernelCellSet, psfMatchingKernel,
                                       backgroundModel,
                                       re.sub('.fits', '', outputPath))
Esempio n. 9
0
def main():
    defSciencePath = None
    defTemplatePath = None
    defOutputPath = 'diffImage.fits'
    defVerbosity = 5
    defFwhm = 3.5

    usage = """usage: %%prog [options] [scienceImage [templateImage [outputImage]]]]

Notes:
- image arguments are paths to MaskedImage fits files
- image arguments must NOT include the final _img.fits
- the result is science image - template image
- the template image is convolved, the science image is not
- default scienceMaskedImage=%s
- default templateMaskedImage=%s
- default outputImage=%s
""" % (defSciencePath, defTemplatePath, defOutputPath)

    parser = optparse.OptionParser(usage)
    parser.add_option('-v',
                      '--verbosity',
                      type=int,
                      default=defVerbosity,
                      help='verbosity of Trace messages')
    parser.add_option('-d',
                      '--display',
                      action='store_true',
                      default=False,
                      help='display the images')
    parser.add_option('-b',
                      '--bg',
                      action='store_true',
                      default=False,
                      help='subtract backgrounds')
    parser.add_option('--fwhmS',
                      type=float,
                      help='Science Image Psf Fwhm (pixel)')
    parser.add_option('--fwhmT',
                      type=float,
                      help='Template Image Psf Fwhm (pixel)')
    parser.add_option('-w',
                      '--writeOutput',
                      action='store_true',
                      default=False,
                      help='Write out the subtracted image?')

    (options, args) = parser.parse_args()

    def getArg(ind, defValue):
        if ind < len(args):
            return args[ind]
        return defValue

    sciencePath = getArg(0, defSciencePath)
    templatePath = getArg(1, defTemplatePath)
    outputPath = getArg(2, defOutputPath)

    if sciencePath is None or templatePath is None:
        parser.print_help()
        sys.exit(1)

    print('Science image: ', sciencePath)
    print('Template image:', templatePath)
    print('Output image:  ', outputPath)

    fwhmS = defFwhm
    if options.fwhmS:
        print('FwhmS =', options.fwhmS)
        fwhmS = options.fwhmS

    fwhmT = defFwhm
    if options.fwhmT:
        print('Fwhmt =', options.fwhmT)
        fwhmT = options.fwhmT

    display = False
    if options.display:
        print('Display =', options.display)
        display = True

    bgSub = False
    if options.bg:
        print('Background subtract =', options.bg)
        bgSub = True

    if options.verbosity > 0:
        print('Verbosity =', options.verbosity)
        logUtils.trace_set_at("lsst.ip.diffim", options.verbosity)

    writeOutput = False
    if options.writeOutput:
        print('writeOutput =', options.writeOutput)
        writeOutput = True

    ####

    templateExposure = afwImage.ExposureF(templatePath)
    scienceExposure = afwImage.ExposureF(sciencePath)
    templateMaskedImage = templateExposure.getMaskedImage()
    scienceMaskedImage = scienceExposure.getMaskedImage()

    config = ipDiffim.ImagePsfMatchTask.ConfigClass()
    config.kernel.name = "AL"
    subconfig = config.kernel.active

    if bgSub:
        diffimTools.backgroundSubtract(
            subconfig.afwBackgroundConfig,
            [templateMaskedImage, scienceMaskedImage])
    else:
        if not subconfig.fitForBackground:
            print('NOTE: no background subtraction at all is requested')

    psfmatch = ipDiffim.ImagePsfMatchTask(config)
    candidateList = psfmatch.makeCandidateList(templateExposure,
                                               scienceExposure,
                                               subconfig.kernelSize)
    results = psfmatch.subtractMaskedImages(templateMaskedImage,
                                            scienceMaskedImage,
                                            candidateList,
                                            templateFwhmPix=fwhmT,
                                            scienceFwhmPix=fwhmS)
    differenceMaskedImage = results.subtractedMaskedImage
    if writeOutput:
        differenceMaskedImage.writeFits(outputPath)

    if False:
        spatialKernel = results.psfMatchingKernel
        print(spatialKernel.getSpatialParameters())

    if display:
        afwDisplay.Display().mtv(differenceMaskedImage,
                                 title="Difference Masked Image")
    def setUp(self, CFHT=True):
        lambdaValue = 1.0

        self.config1 = ipDiffim.ImagePsfMatchTask.ConfigClass()
        self.config1.kernel.name = "DF"
        self.subconfig1 = self.config1.kernel.active

        self.config2 = ipDiffim.ImagePsfMatchTask.ConfigClass()
        self.config2.kernel.name = "DF"
        self.subconfig2 = self.config2.kernel.active

        self.config3 = ipDiffim.ImagePsfMatchTask.ConfigClass()
        self.config3.kernel.name = "DF"
        self.subconfig3 = self.config3.kernel.active

        self.config4 = ipDiffim.ImagePsfMatchTask.ConfigClass()
        self.config4.kernel.name = "DF"
        self.subconfig4 = self.config4.kernel.active

        self.subconfig1.useRegularization = False

        self.subconfig2.useRegularization = True
        self.subconfig2.lambdaType = "absolute"
        self.subconfig2.lambdaValue = lambdaValue
        self.subconfig2.regularizationType = "centralDifference"
        self.subconfig2.centralRegularizationStencil = 5

        self.subconfig3.useRegularization = True
        self.subconfig3.lambdaType = "absolute"
        self.subconfig3.lambdaValue = lambdaValue
        self.subconfig3.regularizationType = "centralDifference"
        self.subconfig3.centralRegularizationStencil = 9

        self.subconfig4.useRegularization = True
        self.subconfig4.lambdaType = "absolute"
        self.subconfig4.lambdaValue = lambdaValue
        self.subconfig4.regularizationType = "forwardDifference"
        self.subconfig4.forwardRegularizationOrders = [1, 2]

        self.kList1 = ipDiffim.makeKernelBasisList(self.subconfig1)
        self.bskv1 = ipDiffim.BuildSingleKernelVisitorF(self.kList1, pexConfig.makePolicy(self.subconfig1))

        self.kList2 = ipDiffim.makeKernelBasisList(self.subconfig2)
        self.hMat2 = ipDiffim.makeRegularizationMatrix(pexConfig.makePolicy(self.subconfig2))
        self.bskv2 = ipDiffim.BuildSingleKernelVisitorF(self.kList2,
                                                        pexConfig.makePolicy(self.subconfig2), self.hMat2)

        self.kList3 = ipDiffim.makeKernelBasisList(self.subconfig3)
        self.hMat3 = ipDiffim.makeRegularizationMatrix(pexConfig.makePolicy(self.subconfig3))
        self.bskv3 = ipDiffim.BuildSingleKernelVisitorF(self.kList3,
                                                        pexConfig.makePolicy(self.subconfig3), self.hMat3)

        self.kList4 = ipDiffim.makeKernelBasisList(self.subconfig4)
        self.hMat4 = ipDiffim.makeRegularizationMatrix(pexConfig.makePolicy(self.subconfig4))
        self.bskv4 = ipDiffim.BuildSingleKernelVisitorF(self.kList4,
                                                        pexConfig.makePolicy(self.subconfig4), self.hMat4)

        # known input images
        defDataDir = lsst.utils.getPackageDir('afwdata')
        if CFHT:
            defSciencePath = os.path.join(defDataDir, 'CFHT', 'D4', CFHTTORUN+'.fits')
            defTemplatePath = os.path.join(defDataDir, 'CFHT', 'D4', CFHTTORUN+'_tmpl.fits')

            # no need to remap
            self.scienceExposure = afwImage.ExposureF(defSciencePath)
            self.templateExposure = afwImage.ExposureF(defTemplatePath)
        else:
            defSciencePath = os.path.join(defDataDir, "DC3a-Sim", "sci", "v26-e0",
                                          "v26-e0-c011-a00.sci")
            defTemplatePath = os.path.join(defDataDir, "DC3a-Sim", "sci", "v5-e0",
                                           "v5-e0-c011-a00.sci")

            self.scienceExposure = afwImage.ExposureF(defSciencePath)
            self.templateExposure = afwImage.ExposureF(defTemplatePath)
            warper = afwMath.Warper.fromConfig(self.subconfig1.warpingConfig)
            self.templateExposure = warper.warpExposure(self.scienceExposure.getWcs(), self.templateExposure,
                                                        destBBox=self.scienceExposure.getBBox())

        diffimTools.backgroundSubtract(self.subconfig1.afwBackgroundConfig,
                                       [self.scienceExposure.getMaskedImage(),
                                        self.templateExposure.getMaskedImage()])

        #
        tmi = self.templateExposure.getMaskedImage()
        smi = self.scienceExposure.getMaskedImage()

        detConfig = self.subconfig1.detectionConfig
        detPolicy = pexConfig.makePolicy(detConfig)
        detPolicy.set("detThreshold", 50.)
        detPolicy.set("detOnTemplate", False)
        kcDetect = ipDiffim.KernelCandidateDetectionF(detPolicy)
        kcDetect.apply(tmi, smi)
        self.footprints = kcDetect.getFootprints()
Esempio n. 11
0
    def setUp(self, CFHT=True):
        lambdaValue = 1.0

        self.config1 = ipDiffim.ImagePsfMatchTask.ConfigClass()
        self.config1.kernel.name = "DF"
        self.subconfig1 = self.config1.kernel.active

        self.config2 = ipDiffim.ImagePsfMatchTask.ConfigClass()
        self.config2.kernel.name = "DF"
        self.subconfig2 = self.config2.kernel.active

        self.config3 = ipDiffim.ImagePsfMatchTask.ConfigClass()
        self.config3.kernel.name = "DF"
        self.subconfig3 = self.config3.kernel.active

        self.config4 = ipDiffim.ImagePsfMatchTask.ConfigClass()
        self.config4.kernel.name = "DF"
        self.subconfig4 = self.config4.kernel.active

        self.subconfig1.useRegularization = False

        self.subconfig2.useRegularization = True
        self.subconfig2.lambdaType = "absolute"
        self.subconfig2.lambdaValue = lambdaValue
        self.subconfig2.regularizationType = "centralDifference"
        self.subconfig2.centralRegularizationStencil = 5

        self.subconfig3.useRegularization = True
        self.subconfig3.lambdaType = "absolute"
        self.subconfig3.lambdaValue = lambdaValue
        self.subconfig3.regularizationType = "centralDifference"
        self.subconfig3.centralRegularizationStencil = 9

        self.subconfig4.useRegularization = True
        self.subconfig4.lambdaType = "absolute"
        self.subconfig4.lambdaValue = lambdaValue
        self.subconfig4.regularizationType = "forwardDifference"
        self.subconfig4.forwardRegularizationOrders = [1, 2]

        self.kList1 = ipDiffim.makeKernelBasisList(self.subconfig1)
        self.bskv1 = ipDiffim.BuildSingleKernelVisitorF(
            self.kList1, pexConfig.makePropertySet(self.subconfig1))

        self.kList2 = ipDiffim.makeKernelBasisList(self.subconfig2)
        self.hMat2 = ipDiffim.makeRegularizationMatrix(
            pexConfig.makePropertySet(self.subconfig2))
        self.bskv2 = ipDiffim.BuildSingleKernelVisitorF(
            self.kList2, pexConfig.makePropertySet(self.subconfig2),
            self.hMat2)

        self.kList3 = ipDiffim.makeKernelBasisList(self.subconfig3)
        self.hMat3 = ipDiffim.makeRegularizationMatrix(
            pexConfig.makePropertySet(self.subconfig3))
        self.bskv3 = ipDiffim.BuildSingleKernelVisitorF(
            self.kList3, pexConfig.makePropertySet(self.subconfig3),
            self.hMat3)

        self.kList4 = ipDiffim.makeKernelBasisList(self.subconfig4)
        self.hMat4 = ipDiffim.makeRegularizationMatrix(
            pexConfig.makePropertySet(self.subconfig4))
        self.bskv4 = ipDiffim.BuildSingleKernelVisitorF(
            self.kList4, pexConfig.makePropertySet(self.subconfig4),
            self.hMat4)

        # known input images
        defDataDir = lsst.utils.getPackageDir('afwdata')
        if CFHT:
            defSciencePath = os.path.join(defDataDir, 'CFHT', 'D4',
                                          CFHTTORUN + '.fits')
            defTemplatePath = os.path.join(defDataDir, 'CFHT', 'D4',
                                           CFHTTORUN + '_tmpl.fits')

            # no need to remap
            self.scienceExposure = afwImage.ExposureF(defSciencePath)
            self.templateExposure = afwImage.ExposureF(defTemplatePath)
        else:
            defSciencePath = os.path.join(defDataDir, "DC3a-Sim", "sci",
                                          "v26-e0", "v26-e0-c011-a00.sci")
            defTemplatePath = os.path.join(defDataDir, "DC3a-Sim", "sci",
                                           "v5-e0", "v5-e0-c011-a00.sci")

            self.scienceExposure = afwImage.ExposureF(defSciencePath)
            self.templateExposure = afwImage.ExposureF(defTemplatePath)
            warper = afwMath.Warper.fromConfig(self.subconfig1.warpingConfig)
            self.templateExposure = warper.warpExposure(
                self.scienceExposure.getWcs(),
                self.templateExposure,
                destBBox=self.scienceExposure.getBBox())

        diffimTools.backgroundSubtract(self.subconfig1.afwBackgroundConfig, [
            self.scienceExposure.getMaskedImage(),
            self.templateExposure.getMaskedImage()
        ])

        #
        tmi = self.templateExposure.getMaskedImage()
        smi = self.scienceExposure.getMaskedImage()

        detConfig = self.subconfig1.detectionConfig
        detps = pexConfig.makePropertySet(detConfig)
        detps["detThreshold"] = 50.
        detps["detOnTemplate"] = False
        kcDetect = ipDiffim.KernelCandidateDetectionF(detps)
        kcDetect.apply(tmi, smi)
        self.footprints = kcDetect.getFootprints()
Esempio n. 12
0
templateExposure = afwImage.ExposureF(defTemplatePath)
scienceExposure  = afwImage.ExposureF(defSciencePath)

config    = ipDiffim.ImagePsfMatchTask.ConfigClass()
config.kernel.name = "AL"
subconfig = config.kernel.active


if warp:
    warper = afwMath.Warper.fromConfig(subconfig.warpingConfig)
    templateExposure = warper.warpExposure(scienceExposure.getWcs(), templateExposure,
                                           destBBox = scienceExposure.getBBox())
if subBackground:
    # Do in AFW
    diffimTools.backgroundSubtract(subconfig.afwBackgroundConfig,
                                   [templateExposure.getMaskedImage(),
                                    scienceExposure.getMaskedImage()])
    subconfig.fitForBackground = False
else:
    # Do in IP_DIFFIM
    subconfig.fitForBackground = True
    

frame  = 0
ds9.mtv(templateExposure, frame=frame, title = "Template")
frame += 1
ds9.mtv(scienceExposure, frame=frame, title = "Sci Im")

psfmatch = ipDiffim.ImagePsfMatchTask(config=config)
try:
    results = psfmatch.run(templateExposure.getMaskedImage(),
 def subBackground(self, policy):
     # images in afwdata are not background subtracted
     diffimTools.backgroundSubtract(policy, [self.templateExposure.getMaskedImage(),
                                             self.scienceExposure.getMaskedImage()])
Esempio n. 14
0
def main():
    defDataDir = lsst.utils.getPackageDir('afwdata')
    imageProcDir = lsst.utils.getPackageDir('ip_diffim')

    defSciencePath  = os.path.join(defDataDir, "DC3a-Sim", "sci", "v26-e0", "v26-e0-c011-a10.sci")
    defTemplatePath = os.path.join(defDataDir, "DC3a-Sim", "sci", "v5-e0", "v5-e0-c011-a10.sci")

    defOutputPath   = 'diffExposure.fits'
    defVerbosity    = 5
    defFwhm         = 3.5
    sigma2fwhm      = 2. * num.sqrt(2. * num.log(2.))

    usage = """usage: %%prog [options] [scienceExposure [templateExposure [outputExposure]]]]

Notes:
- image arguments are paths to Expoure fits files
- image arguments must NOT include the final _img.fits
- the result is science image - template image
- the template exposure is convolved, the science exposure is not
- default scienceExposure=%s
- default templateExposure=%s
- default outputExposure=%s 
""" % (defSciencePath, defTemplatePath, defOutputPath)
    
    parser = optparse.OptionParser(usage)
    parser.add_option('-v', '--verbosity', type=int, default=defVerbosity,
                      help='verbosity of Trace messages')
    parser.add_option('-d', '--display', action='store_true', default=False,
                      help='display the images')
    parser.add_option('-b', '--bg', action='store_true', default=False,
                      help='subtract backgrounds using afw')
    parser.add_option('--fwhmS', type=float,
                      help='Science Image Psf Fwhm (pixel)')
    parser.add_option('--fwhmT', type=float,
                      help='Template Image Psf Fwhm (pixel)')

    (options, args) = parser.parse_args()
    
    def getArg(ind, defValue):
        if ind < len(args):
            return args[ind]
        return defValue
    
    sciencePath     = getArg(0, defSciencePath)
    templatePath    = getArg(1, defTemplatePath)
    outputPath      = getArg(2, defOutputPath)
    
    if sciencePath == None or templatePath == None:
        parser.print_help()
        sys.exit(1)

    print 'Science exposure: ', sciencePath
    print 'Template exposure:', templatePath
    print 'Output exposure:  ', outputPath

    templateExposure = afwImage.ExposureF(templatePath)
    scienceExposure  = afwImage.ExposureF(sciencePath)
    
    config = ipDiffim.ImagePsfMatchTask.ConfigClass()
    config.kernel.name = "AL"
    subconfig = config.kernel.active

    fwhmS = defFwhm
    if options.fwhmS:
        if scienceExposure.hasPsf():
            width, height = scienceExposure.getPsf().getKernel().getDimensions()
            psfAttr = measAlg.PsfAttributes(scienceExposure.getPsf(), width//2, height//2)
            s = psfAttr.computeGaussianWidth(psfAttr.ADAPTIVE_MOMENT) # gaussian sigma in pixels
            fwhm = s * sigma2fwhm
            print 'NOTE: Embedded Psf has FwhmS =', fwhm
        print 'USING: FwhmS =', options.fwhmS
        fwhmS = options.fwhmS

    fwhmT = defFwhm
    if options.fwhmT:
        if templateExposure.hasPsf():
            width, height = templateExposure.getPsf().getKernel().getDimensions()
            psfAttr = measAlg.PsfAttributes(templateExposure.getPsf(), width//2, height//2)
            s = psfAttr.computeGaussianWidth(psfAttr.ADAPTIVE_MOMENT) # gaussian sigma in pixels
            fwhm = s * sigma2fwhm
            print 'NOTE: Embedded Psf has FwhmT =', fwhm
        print 'USING: FwhmT =', options.fwhmT
        fwhmT = options.fwhmT

    display = False
    if options.display:
        print 'Display =', options.display
        display = True

    bgSub = False
    if options.bg:
        print 'Background subtract =', options.bg
        bgSub = True

    if options.verbosity > 0:
        print 'Verbosity =', options.verbosity
        Trace.setVerbosity('lsst.ip.diffim', options.verbosity)

    ####
        
    if bgSub:
        diffimTools.backgroundSubtract(subconfig.afwBackgroundConfig,
                                       [templateExposure.getMaskedImage(),
                                        scienceExposure.getMaskedImage()])
    else:
        if subconfig.fitForBackground == False:
            print 'NOTE: no background subtraction at all is requested'

    psfmatch = ipDiffim.ImagePsfMatchTask(config)
    results  = psfmatch.run(templateExposure, scienceExposure, "subtractExposures",
                            templateFwhmPix = fwhmT, scienceFwhmPix = fwhmS)

    differenceExposure = results.subtractedImage
    differenceExposure.writeFits(outputPath)

    if False:
        psfMatchingKernel = results.psfMatchingKernel
        backgroundModel   = results.backgroundModel
        kernelCellSet     = results.kernelCellSet
        
        diffimTools.writeKernelCellSet(kernelCellSet, psfMatchingKernel, backgroundModel,
                                       re.sub('.fits', '', outputPath))
Esempio n. 15
0
def main():
    defDataDir = lsst.utils.getPackageDir('afwdata')
    imageProcDir = lsst.utils.getPackageDir('ip_diffim')

    defSciencePath = os.path.join(defDataDir, "DC3a-Sim", "sci", "v26-e0",
                                  "v26-e0-c011-a10.sci")
    defTemplatePath = os.path.join(defDataDir, "DC3a-Sim", "sci", "v5-e0",
                                   "v5-e0-c011-a10.sci")

    defOutputPath = 'diffExposure.fits'
    defVerbosity = 5
    defFwhm = 3.5
    sigma2fwhm = 2. * num.sqrt(2. * num.log(2.))

    usage = """usage: %%prog [options] [scienceExposure [templateExposure [outputExposure]]]]

Notes:
- image arguments are paths to Expoure fits files
- image arguments must NOT include the final _img.fits
- the result is science image - template image
- the template exposure is convolved, the science exposure is not
- default scienceExposure=%s
- default templateExposure=%s
- default outputExposure=%s 
""" % (defSciencePath, defTemplatePath, defOutputPath)

    parser = optparse.OptionParser(usage)
    parser.add_option('-v',
                      '--verbosity',
                      type=int,
                      default=defVerbosity,
                      help='verbosity of Trace messages')
    parser.add_option('-d',
                      '--display',
                      action='store_true',
                      default=False,
                      help='display the images')
    parser.add_option('-b',
                      '--bg',
                      action='store_true',
                      default=False,
                      help='subtract backgrounds using afw')
    parser.add_option('--fwhmS',
                      type=float,
                      help='Science Image Psf Fwhm (pixel)')
    parser.add_option('--fwhmT',
                      type=float,
                      help='Template Image Psf Fwhm (pixel)')

    (options, args) = parser.parse_args()

    def getArg(ind, defValue):
        if ind < len(args):
            return args[ind]
        return defValue

    sciencePath = getArg(0, defSciencePath)
    templatePath = getArg(1, defTemplatePath)
    outputPath = getArg(2, defOutputPath)

    if sciencePath == None or templatePath == None:
        parser.print_help()
        sys.exit(1)

    print 'Science exposure: ', sciencePath
    print 'Template exposure:', templatePath
    print 'Output exposure:  ', outputPath

    templateExposure = afwImage.ExposureF(templatePath)
    scienceExposure = afwImage.ExposureF(sciencePath)

    config = ipDiffim.ImagePsfMatchTask.ConfigClass()
    config.kernel.name = "AL"
    subconfig = config.kernel.active

    fwhmS = defFwhm
    if options.fwhmS:
        if scienceExposure.hasPsf():
            width, height = scienceExposure.getPsf().getKernel().getDimensions(
            )
            psfAttr = measAlg.PsfAttributes(scienceExposure.getPsf(),
                                            width // 2, height // 2)
            s = psfAttr.computeGaussianWidth(
                psfAttr.ADAPTIVE_MOMENT)  # gaussian sigma in pixels
            fwhm = s * sigma2fwhm
            print 'NOTE: Embedded Psf has FwhmS =', fwhm
        print 'USING: FwhmS =', options.fwhmS
        fwhmS = options.fwhmS

    fwhmT = defFwhm
    if options.fwhmT:
        if templateExposure.hasPsf():
            width, height = templateExposure.getPsf().getKernel(
            ).getDimensions()
            psfAttr = measAlg.PsfAttributes(templateExposure.getPsf(),
                                            width // 2, height // 2)
            s = psfAttr.computeGaussianWidth(
                psfAttr.ADAPTIVE_MOMENT)  # gaussian sigma in pixels
            fwhm = s * sigma2fwhm
            print 'NOTE: Embedded Psf has FwhmT =', fwhm
        print 'USING: FwhmT =', options.fwhmT
        fwhmT = options.fwhmT

    display = False
    if options.display:
        print 'Display =', options.display
        display = True

    bgSub = False
    if options.bg:
        print 'Background subtract =', options.bg
        bgSub = True

    if options.verbosity > 0:
        print 'Verbosity =', options.verbosity
        Trace.setVerbosity('lsst.ip.diffim', options.verbosity)

    ####

    if bgSub:
        diffimTools.backgroundSubtract(subconfig.afwBackgroundConfig, [
            templateExposure.getMaskedImage(),
            scienceExposure.getMaskedImage()
        ])
    else:
        if subconfig.fitForBackground == False:
            print 'NOTE: no background subtraction at all is requested'

    psfmatch = ipDiffim.ImagePsfMatchTask(config)
    results = psfmatch.run(templateExposure,
                           scienceExposure,
                           "subtractExposures",
                           templateFwhmPix=fwhmT,
                           scienceFwhmPix=fwhmS)

    differenceExposure = results.subtractedImage
    differenceExposure.writeFits(outputPath)

    if False:
        psfMatchingKernel = results.psfMatchingKernel
        backgroundModel = results.backgroundModel
        kernelCellSet = results.kernelCellSet

        diffimTools.writeKernelCellSet(kernelCellSet, psfMatchingKernel,
                                       backgroundModel,
                                       re.sub('.fits', '', outputPath))
Esempio n. 16
0
def main():
    imageProcDir = lsst.utils.getPackageDir('ip_diffim')

    defSciencePath  = None
    defTemplatePath = None
    defOutputPath   = 'matchedImage.fits'
    defVerbosity    = 5
    defFwhm         = 3.5
    
    usage = """usage: %%prog [options] [scienceImage [templateImage [outputImage]]]]

Notes:
- image arguments are paths to MaskedImage fits files
- image arguments must NOT include the final _img.fits
- the result is science image matched template image
- the template image is convolved, the science image is not
- default scienceMaskedImage=%s
- default templateMaskedImage=%s
- default outputImage=%s 
""" % (defSciencePath, defTemplatePath, defOutputPath)
    
    parser = optparse.OptionParser(usage)
    parser.add_option('-v', '--verbosity', type=int, default=defVerbosity,
                      help='verbosity of Trace messages')
    parser.add_option('-d', '--display', action='store_true', default=False,
                      help='display the images')
    parser.add_option('-b', '--bg', action='store_true', default=False,
                      help='subtract backgrounds')
    parser.add_option('--fwhmS', type=float,
                      help='Science Image Psf Fwhm (pixel)')
    parser.add_option('--fwhmT', type=float,
                      help='Template Image Psf Fwhm (pixel)')
                      
    (options, args) = parser.parse_args()
    
    def getArg(ind, defValue):
        if ind < len(args):
            return args[ind]
        return defValue
    
    sciencePath     = getArg(0, defSciencePath)
    templatePath    = getArg(1, defTemplatePath)
    outputPath      = getArg(2, defOutputPath)

    if sciencePath == None or templatePath == None:
        parser.print_help()
        sys.exit(1)
    
    print 'Science image: ', sciencePath
    print 'Template image:', templatePath
    print 'Output image:  ', outputPath

    fwhmS = defFwhm
    if options.fwhmS:
        print 'FwhmS =', options.fwhmS
        fwhmS = options.fwhmS

    fwhmT = defFwhm
    if options.fwhmT:
        print 'Fwhmt =', options.fwhmT
        fwhmT = options.fwhmT

    display = False
    if options.display:
        print 'Display =', options.display
        display = True

    bgSub = False
    if options.bg:
        print 'Background subtract =', options.bg
        bgSub = True

    if options.verbosity > 0:
        print 'Verbosity =', options.verbosity
        Trace.setVerbosity('lsst.ip.diffim', options.verbosity)
        
    ####
        
    templateMaskedImage = afwImage.MaskedImageF(templatePath)
    scienceMaskedImage  = afwImage.MaskedImageF(sciencePath)

    config = ipDiffim.ImagePsfMatch.ConfigClass()
    config.kernel.name = "AL"
    subconfig = config.kernel.active

    if bgSub:
        diffimTools.backgroundSubtract(subconfig.afwBackgroundConfig,
                                       [templateMaskedImage, scienceMaskedImage])
    else:
        if subconfig.fitForBackground == False:
            print 'NOTE: no background subtraction at all is requested'

    psfmatch = ipDiffim.ImagePsfMatch(subconfig)
    results  = psfmatch.matchMaskedImages(templateMaskedImage, scienceMaskedImage,
                                          templateFwhmPix = fwhmT, scienceFwhmPix = fwhmS)

    matchMaskedImage = results[0]
    matchMaskedImage.writeFits(outputPath)

    if False:
        spatialKernel = results[1]
        print spatialKernel.getSpatialParameters()
    
    if display:
        ds9.mtv(differenceMaskedImage)
def main():
    defDataDir = lsst.utils.getPackageDir('afwdata')

    defSciencePath = os.path.join(defDataDir, "DC3a-Sim", "sci", "v26-e0", "v26-e0-c011-a10.sci.fits")
    defTemplatePath = os.path.join(defDataDir, "DC3a-Sim", "sci", "v5-e0", "v5-e0-c011-a10.sci.fits")

    defOutputPath = 'diffExposure.fits'
    defVerbosity = 0
    defFwhm = 3.5
    sigma2fwhm = 2. * np.sqrt(2. * np.log(2.))

    usage = """usage: %%prog [options] [scienceExposure [templateExposure [outputExposure]]]]

Notes:
- image arguments are paths to Expoure fits files
- image arguments must NOT include the final _img.fits
- the result is science image - template image
- the template exposure is convolved, the science exposure is not
- default scienceExposure=%s
- default templateExposure=%s
- default outputExposure=%s
""" % (defSciencePath, defTemplatePath, defOutputPath)

    parser = optparse.OptionParser(usage)
    parser.add_option('-v', '--verbosity', type=int, default=defVerbosity,
                      help='verbosity of Trace messages')
    parser.add_option('-d', '--display', action='store_true', default=False,
                      help='display the images')
    parser.add_option('-b', '--bg', action='store_true', default=False,
                      help='subtract backgrounds using afw')
    parser.add_option('--fwhmS', type=float,
                      help='Science Image Psf Fwhm (pixel)')
    parser.add_option('--fwhmT', type=float,
                      help='Template Image Psf Fwhm (pixel)')

    (options, args) = parser.parse_args()

    def getArg(ind, defValue):
        if ind < len(args):
            return args[ind]
        return defValue

    sciencePath = getArg(0, defSciencePath)
    templatePath = getArg(1, defTemplatePath)
    outputPath = getArg(2, defOutputPath)

    if sciencePath is None or templatePath is None:
        parser.print_help()
        sys.exit(1)

    print('Science exposure: ', sciencePath)
    print('Template exposure:', templatePath)
    print('Output exposure:  ', outputPath)

    templateExposure = afwImage.ExposureF(templatePath)
    scienceExposure = afwImage.ExposureF(sciencePath)

    config = ipDiffim.ImagePsfMatchTask.ConfigClass()
    config.kernel.name = "AL"
    subconfig = config.kernel.active

    fwhmS = defFwhm
    if options.fwhmS:
        if scienceExposure.hasPsf():
            fwhm = scienceExposure.getPsf().computeShape().getDeterminantRadius() * sigma2fwhm
            print('NOTE: Embedded Psf has FwhmS =', fwhm)
        print('USING: FwhmS =', options.fwhmS)
        fwhmS = options.fwhmS

    fwhmT = defFwhm
    if options.fwhmT:
        if templateExposure.hasPsf():
            fwhm = templateExposure.getPsf().computeShape().getDeterminantRadius() * sigma2fwhm
            print('NOTE: Embedded Psf has FwhmT =', fwhm)
        print('USING: FwhmT =', options.fwhmT)
        fwhmT = options.fwhmT

    bgSub = False
    if options.bg:
        print('Background subtract =', options.bg)
        bgSub = True

    if options.verbosity > 0:
        print('Verbosity =', options.verbosity)
        logUtils.traceSetAt("ip.diffim", options.verbosity)

    ####

    if bgSub:
        diffimTools.backgroundSubtract(subconfig.afwBackgroundConfig,
                                       [templateExposure.getMaskedImage(),
                                        scienceExposure.getMaskedImage()])
    else:
        if not subconfig.fitForBackground:
            print('NOTE: no background subtraction at all is requested')

    # ImagePsfMatchTask requires a candidateList or that the exposoure have a PSF for detection
    if not scienceExposure.hasPsf():
        sigmaS = fwhmS/sigma2fwhm
        kSize = int(6 * sigmaS)  # minimum kernel size for FWHM
        oddKSize = kSize + 1 if kSize % 2 == 0 else kSize
        scienceExposure.setPsf(SingleGaussianPsf(oddKSize, oddKSize, sigmaS))

    psfmatch = ipDiffim.ImagePsfMatchTask(config)
    results = psfmatch.subtractExposures(templateExposure, scienceExposure,
                                         templateFwhmPix=fwhmT, scienceFwhmPix=fwhmS)

    differenceExposure = results.subtractedExposure
    differenceExposure.writeFits(outputPath)

    if False:
        psfMatchingKernel = results.psfMatchingKernel
        backgroundModel = results.backgroundModel
        kernelCellSet = results.kernelCellSet

        diffimTools.writeKernelCellSet(kernelCellSet, psfMatchingKernel, backgroundModel,
                                       re.sub('.fits', '', outputPath))
Esempio n. 18
0
templateExposure = afwImage.ExposureF(defTemplatePath)
scienceExposure = afwImage.ExposureF(defSciencePath)

config = ipDiffim.ImagePsfMatchTask.ConfigClass()
config.kernel.name = "AL"
subconfig = config.kernel.active

if warp:
    warper = afwMath.Warper.fromConfig(subconfig.warpingConfig)
    templateExposure = warper.warpExposure(scienceExposure.getWcs(),
                                           templateExposure,
                                           destBBox=scienceExposure.getBBox())
if subBackground:
    # Do in AFW
    diffimTools.backgroundSubtract(
        subconfig.afwBackgroundConfig,
        [templateExposure.getMaskedImage(),
         scienceExposure.getMaskedImage()])
    subconfig.fitForBackground = False
else:
    # Do in IP_DIFFIM
    subconfig.fitForBackground = True

frame = 0
ds9.mtv(templateExposure, frame=frame, title="Template")
frame += 1
ds9.mtv(scienceExposure, frame=frame, title="Sci Im")

psfmatch = ipDiffim.ImagePsfMatchTask(config=config)
try:
    results = psfmatch.run(templateExposure.getMaskedImage(),
                           scienceExposure.getMaskedImage(),
def main():
    defSciencePath = None
    defTemplatePath = None
    defOutputPath = 'diffImage.fits'
    defVerbosity = 5
    defFwhm = 3.5

    usage = """usage: %%prog [options] [scienceImage [templateImage [outputImage]]]]

Notes:
- image arguments are paths to MaskedImage fits files
- image arguments must NOT include the final _img.fits
- the result is science image - template image
- the template image is convolved, the science image is not
- default scienceMaskedImage=%s
- default templateMaskedImage=%s
- default outputImage=%s
""" % (defSciencePath, defTemplatePath, defOutputPath)

    parser = optparse.OptionParser(usage)
    parser.add_option('-v', '--verbosity', type=int, default=defVerbosity,
                      help='verbosity of Trace messages')
    parser.add_option('-d', '--display', action='store_true', default=False,
                      help='display the images')
    parser.add_option('-b', '--bg', action='store_true', default=False,
                      help='subtract backgrounds')
    parser.add_option('--fwhmS', type=float,
                      help='Science Image Psf Fwhm (pixel)')
    parser.add_option('--fwhmT', type=float,
                      help='Template Image Psf Fwhm (pixel)')
    parser.add_option('-w', '--writeOutput', action='store_true', default=False,
                      help='Write out the subtracted image?')

    (options, args) = parser.parse_args()

    def getArg(ind, defValue):
        if ind < len(args):
            return args[ind]
        return defValue

    sciencePath = getArg(0, defSciencePath)
    templatePath = getArg(1, defTemplatePath)
    outputPath = getArg(2, defOutputPath)

    if sciencePath is None or templatePath is None:
        parser.print_help()
        sys.exit(1)

    print('Science image: ', sciencePath)
    print('Template image:', templatePath)
    print('Output image:  ', outputPath)

    fwhmS = defFwhm
    if options.fwhmS:
        print('FwhmS =', options.fwhmS)
        fwhmS = options.fwhmS

    fwhmT = defFwhm
    if options.fwhmT:
        print('Fwhmt =', options.fwhmT)
        fwhmT = options.fwhmT

    display = False
    if options.display:
        print('Display =', options.display)
        display = True

    bgSub = False
    if options.bg:
        print('Background subtract =', options.bg)
        bgSub = True

    if options.verbosity > 0:
        print('Verbosity =', options.verbosity)
        logUtils.traceSetAt("ip.diffim", options.verbosity)

    writeOutput = False
    if options.writeOutput:
        print('writeOutput =', options.writeOutput)
        writeOutput = True

    ####

    templateExposure = afwImage.ExposureF(templatePath)
    scienceExposure = afwImage.ExposureF(sciencePath)
    templateMaskedImage = templateExposure.getMaskedImage()
    scienceMaskedImage = scienceExposure.getMaskedImage()

    config = ipDiffim.ImagePsfMatchTask.ConfigClass()
    config.kernel.name = "AL"
    subconfig = config.kernel.active

    if bgSub:
        diffimTools.backgroundSubtract(subconfig.afwBackgroundConfig,
                                       [templateMaskedImage, scienceMaskedImage])
    else:
        if not subconfig.fitForBackground:
            print('NOTE: no background subtraction at all is requested')

    psfmatch = ipDiffim.ImagePsfMatchTask(config)
    candidateList = psfmatch.makeCandidateList(templateExposure, scienceExposure, subconfig.kernelSize)
    results = psfmatch.subtractMaskedImages(templateMaskedImage, scienceMaskedImage, candidateList,
                                            templateFwhmPix=fwhmT, scienceFwhmPix=fwhmS)
    differenceMaskedImage = results.subtractedMaskedImage
    if writeOutput:
        differenceMaskedImage.writeFits(outputPath)

    if False:
        spatialKernel = results.psfMatchingKernel
        print(spatialKernel.getSpatialParameters())

    if display:
        afwDisplay.Display().mtv(differenceMaskedImage, title="Difference Masked Image")