예제 #1
0
파일: offsetImage.py 프로젝트: lsst-dm/bp
    def testSetFluxConvervation(self):
        """Test that flux is preserved"""

        outImage = afwMath.offsetImage(self.inImage, 0, 0, self.algorithm)
        self.assertEqual(outImage.get(50, 50), self.background)

        outImage = afwMath.offsetImage(self.inImage, 0.5, 0, self.algorithm)
        self.assertAlmostEqual(outImage.get(50, 50), self.background, 4)

        outImage = afwMath.offsetImage(self.inImage, 0.5, 0.5, self.algorithm)
        self.assertAlmostEqual(outImage.get(50, 50), self.background, 4)
예제 #2
0
    def testSetFluxConvervation(self):
        """Test that flux is preserved"""

        for algorithm in ("lanczos5", "bilinear", "nearest"):
            outImage = afwMath.offsetImage(self.inImage, 0, 0, algorithm)
            self.assertEqual(outImage.get(50, 50), self.background)

            outImage = afwMath.offsetImage(self.inImage, 0.5, 0, algorithm)
            self.assertAlmostEqual(outImage.get(50, 50), self.background, 4)

            outImage = afwMath.offsetImage(self.inImage, 0.5, 0.5, algorithm)
            self.assertAlmostEqual(outImage.get(50, 50), self.background, 4)
예제 #3
0
    def testSetFluxConvervation(self):
        """Test that flux is preserved"""
        
        for algorithm in ("lanczos5", "bilinear", "nearest"):
            outImage = afwMath.offsetImage(self.inImage, 0, 0, algorithm)
            self.assertEqual(outImage.get(50, 50), self.background)

            outImage = afwMath.offsetImage(self.inImage, 0.5, 0, algorithm)
            self.assertAlmostEqual(outImage.get(50, 50), self.background, 4)

            outImage = afwMath.offsetImage(self.inImage, 0.5, 0.5, algorithm)
            self.assertAlmostEqual(outImage.get(50, 50), self.background, 4)
예제 #4
0
    def testSetIntegerOffset(self):
        """Test that we can offset by positive and negative amounts.
        """
        self.inImage[50, 50, afwImage.LOCAL] = 400

        if False and display:
            frame = 0
            disp = afwDisplay.Display(frame=frame)
            disp.mtv(self.inImage, title="Image for Integer Offset Test")
            disp.pan(50, 50)
            disp.dot("+", 50, 50)

        for algorithm in ("lanczos5", "bilinear", "nearest"):
            frame = 1
            for delta in [-0.49, 0.51]:
                for dx, dy in [(2, 3), (-2, 3), (-2, -3), (2, -3)]:
                    outImage = afwMath.offsetImage(self.inImage, dx + delta,
                                                   dy + delta, algorithm)

                    if False and display:
                        frame += 1
                        disp = afwDisplay.Display(frame=frame)
                        disp.mtv(outImage,
                                 title=algorithm +
                                 ": offset image (dx, dy) = (%d, %d)" %
                                 (dx, dy))

                        disp.pan(50, 50)
                        disp.dot("+", 50 + dx + delta - outImage.getX0(),
                                 50 + dy + delta - outImage.getY0())
예제 #5
0
    def testSetIntegerOffset(self):
        """Test that we can offset by positive and negative amounts"""

        self.inImage.set(50, 50, 400)

        if False and display:
            frame = 0
            ds9.mtv(self.inImage, frame=frame)
            ds9.pan(50, 50, frame=frame)
            ds9.dot("+", 50, 50, frame=frame)

        for algorithm in ("lanczos5", "bilinear", "nearest"):
            for delta in [-0.49, 0.51]:
                for dx, dy in [(2, 3), (-2, 3), (-2, -3), (2, -3)]:
                    outImage = afwMath.offsetImage(self.inImage, dx + delta,
                                                   dy + delta, algorithm)

                    if False and display:
                        frame += 1
                        ds9.mtv(outImage, frame=frame)
                        ds9.pan(50, 50, frame=frame)
                        ds9.dot("+",
                                50 + dx + delta - outImage.getX0(),
                                50 + dy + delta - outImage.getY0(),
                                frame=frame)
예제 #6
0
    def testSetIntegerOffset(self):
        """Test that we can offset by positive and negative amounts.
        """
        self.inImage[50, 50, afwImage.LOCAL] = 400

        if False and display:
            frame = 0
            disp = afwDisplay.Display(frame=frame)
            disp.mtv(self.inImage, title="Image for Integer Offset Test")
            disp.pan(50, 50)
            disp.dot("+", 50, 50)

        for algorithm in ("lanczos5", "bilinear", "nearest"):
            frame = 1
            for delta in [-0.49, 0.51]:
                for dx, dy in [(2, 3), (-2, 3), (-2, -3), (2, -3)]:
                    outImage = afwMath.offsetImage(
                        self.inImage, dx + delta, dy + delta, algorithm)

                    if False and display:
                        frame += 1
                        disp = afwDisplay.Display(frame=frame)
                        disp.mtv(outImage, title=algorithm + ": offset image (dx, dy) = (%d, %d)" % (dx, dy))

                        disp.pan(50, 50)
                        disp.dot("+", 50 + dx + delta - outImage.getX0(), 50 + dy + delta - outImage.getY0())
예제 #7
0
def saveSpatialCellSet(psfCellSet, fileName="foo.fits", display=None):
    """Write the contents of a SpatialCellSet to a many-MEF fits file"""

    mode = "w"
    for cell in psfCellSet.getCellList():
        for cand in cell.begin(False):  # include bad candidates
            dx = afwImage.positionToIndex(cand.getXCenter(), True)[1]
            dy = afwImage.positionToIndex(cand.getYCenter(), True)[1]
            im = afwMath.offsetImage(cand.getMaskedImage(), -dx, -dy, "lanczos5")

            md = dafBase.PropertySet()
            md.set("CELL", cell.getLabel())
            md.set("ID", cand.getId())
            md.set("XCENTER", cand.getXCenter())
            md.set("YCENTER", cand.getYCenter())
            md.set("BAD", cand.isBad())
            md.set("AMPL", cand.getAmplitude())
            md.set("FLUX", cand.getSource().getPsfInstFlux())
            md.set("CHI2", cand.getSource().getChi2())

            im.writeFits(fileName, md, mode)
            mode = "a"

            if display:
                display.mtv(im, title="saveSpatialCellSet: image")
예제 #8
0
def saveSpatialCellSet(psfCellSet, fileName="foo.fits", frame=None):
    """Write the contents of a SpatialCellSet to a many-MEF fits file"""
    
    mode = "w"
    for cell in psfCellSet.getCellList():
        for cand in cell.begin(False):  # include bad candidates
            cand = algorithmsLib.cast_PsfCandidateF(cand)

            dx = afwImage.positionToIndex(cand.getXCenter(), True)[1]
            dy = afwImage.positionToIndex(cand.getYCenter(), True)[1]
            im = afwMath.offsetImage(cand.getMaskedImage(), -dx, -dy, "lanczos5")

            md = dafBase.PropertySet()
            md.set("CELL", cell.getLabel())
            md.set("ID", cand.getId())
            md.set("XCENTER", cand.getXCenter())
            md.set("YCENTER", cand.getYCenter())
            md.set("BAD", cand.isBad())
            md.set("AMPL", cand.getAmplitude())
            md.set("FLUX", cand.getSource().getPsfFlux())
            md.set("CHI2", cand.getSource().getChi2())

            im.writeFits(fileName, md, mode)
            mode = "a"

            if frame is not None:
                ds9.mtv(im, frame=frame)
예제 #9
0
    def testOffsetGaussian(self):
        """Insert a Gaussian, offset, and check the residuals.
        """
        size = 50
        refIm = afwImage.ImageF(size, size)
        unshiftedIm = afwImage.ImageF(size, size)

        xc, yc = size / 2.0, size / 2.0

        amp, sigma1 = 1.0, 3

        #
        # Calculate Gaussian directly at (xc, yc)
        #
        self.calcGaussian(refIm, xc, yc, amp, sigma1)

        for dx in (-55.5, -1.500001, -1.5, -1.499999, -1.00001, -1.0, -0.99999,
                   -0.5, 0.0, 0.5, 0.99999, 1.0, 1.00001, 1.499999, 1.5,
                   1.500001, 99.3):
            for dy in (-3.7, -1.500001, -1.5, -1.499999, -1.00001, -1.0,
                       -0.99999, -0.5, 0.0, 0.5, 0.99999, 1.0, 1.00001,
                       1.499999, 1.5, 1.500001, 2.99999):
                dOrigX, dOrigY, dFracX, dFracY = getOrigFracShift(dx, dy)
                self.calcGaussian(unshiftedIm, xc - dFracX, yc - dFracY, amp,
                                  sigma1)

                for algorithm, maxMean, maxLim in (
                    ("lanczos5", 1e-8, 0.0015),
                    ("bilinear", 1e-8, 0.03),
                    ("nearest", 1e-8, 0.2),
                ):
                    im = afwImage.ImageF(size, size)
                    im = afwMath.offsetImage(unshiftedIm, dx, dy, algorithm)

                    if display:
                        afwDisplay.Display(frame=0).mtv(
                            im, title=f"{algorithm}: image")

                    im -= refIm

                    if display:
                        afwDisplay.Display(frame=1).mtv(
                            im, title=f"{algorithm}: diff image ({dx}, {dy})")

                    imArr = im.getArray()
                    imGoodVals = np.ma.array(
                        imArr, copy=False, mask=np.isnan(imArr)).compressed()

                    try:
                        imXY0 = tuple(im.getXY0())
                        self.assertEqual(imXY0, (dOrigX, dOrigY))
                        self.assertLess(abs(imGoodVals.mean()), maxMean * amp)
                        self.assertLess(abs(imGoodVals.max()), maxLim * amp)
                        self.assertLess(abs(imGoodVals.min()), maxLim * amp)
                    except Exception:
                        print(
                            f"failed on algorithm={algorithm}; dx = {dx}; dy = {dy}"
                        )
                        raise
예제 #10
0
파일: psfIO.py 프로젝트: dr-guangtou/hs_hsc
    def setUp(self):
        width, height = 100, 300
        self.mi = afwImage.MaskedImageF(afwGeom.ExtentI(width, height))
        self.mi.set(0)
        self.mi.getVariance().set(10)
        self.mi.getMask().addMaskPlane("DETECTED")

        self.FWHM = 5
        self.ksize = 25                      # size of desired kernel

        self.exposure = afwImage.makeExposure(self.mi)

        psf = roundTripPsf(2, algorithms.DoubleGaussianPsf(self.ksize, self.ksize,
                                                             self.FWHM/(2*sqrt(2*log(2))), 1, 0.1))
        self.exposure.setPsf(psf)

        for x, y in [(20, 20),
                     #(30, 35), (50, 50),
                     (60, 20), (60, 210), (20, 210)]:


            flux = 10000 - 0*x - 10*y

            sigma = 3 + 0.01*(y - self.mi.getHeight()/2)
            psf = roundTripPsf(3, algorithms.DoubleGaussianPsf(self.ksize, self.ksize, sigma, 1, 0.1))
            im = psf.computeImage().convertF()
            im *= flux
            smi = self.mi.getImage().Factory(self.mi.getImage(),
                                             afwGeom.BoxI(afwGeom.PointI(x - self.ksize/2, y - self.ksize/2),
                                                          afwGeom.ExtentI(self.ksize)), 
                                             afwImage.LOCAL)

            if False:                   # Test subtraction with non-centered psfs
                im = afwMath.offsetImage(im, 0.5, 0.5)

            smi += im
            del psf; del im; del smi

        psf = roundTripPsf(4, algorithms.DoubleGaussianPsf(self.ksize, self.ksize,
                                                             self.FWHM/(2*sqrt(2*log(2))), 1, 0.1))

        self.cellSet = afwMath.SpatialCellSet(afwGeom.BoxI(afwGeom.PointI(0, 0), afwGeom.ExtentI(width, height)), 100)
        ds = afwDetection.FootprintSet(self.mi, afwDetection.Threshold(10), "DETECTED")
        #
        # Prepare to measure
        #
        msConfig = algorithms.SourceMeasurementConfig()
        msConfig.load("tests/config/MeasureSources.py")
        schema = afwTable.SourceTable.makeMinimalSchema()
        measureSources = msConfig.makeMeasureSources(schema)
        catalog = afwTable.SourceCatalog(schema)
        msConfig.slots.calibFlux = None
        msConfig.slots.setupTable(catalog.table)
        ds.makeSources(catalog)
        for i, source in enumerate(catalog):
            measureSources.applyWithPeak(source, self.exposure)
            self.cellSet.insertCandidate(algorithms.makePsfCandidate(source, self.exposure))
예제 #11
0
    def testOffsetGaussian(self):
        """Insert a Gaussian, offset, and check the residuals.
        """
        size = 50
        refIm = afwImage.ImageF(size, size)
        unshiftedIm = afwImage.ImageF(size, size)

        xc, yc = size/2.0, size/2.0

        amp, sigma1 = 1.0, 3

        #
        # Calculate Gaussian directly at (xc, yc)
        #
        self.calcGaussian(refIm, xc, yc, amp, sigma1)

        for dx in (-55.5, -1.500001, -1.5, -1.499999, -1.00001, -1.0, -0.99999, -0.5,
                   0.0, 0.5, 0.99999, 1.0, 1.00001, 1.499999, 1.5, 1.500001, 99.3):
            for dy in (-3.7, -1.500001, -1.5, -1.499999, -1.00001, -1.0, -0.99999, -0.5,
                       0.0, 0.5, 0.99999, 1.0, 1.00001, 1.499999, 1.5, 1.500001, 2.99999):
                dOrigX, dOrigY, dFracX, dFracY = getOrigFracShift(dx, dy)
                self.calcGaussian(unshiftedIm, xc - dFracX,
                                  yc - dFracY, amp, sigma1)

                for algorithm, maxMean, maxLim in (
                    ("lanczos5", 1e-8, 0.0015),
                    ("bilinear", 1e-8, 0.03),
                    ("nearest", 1e-8, 0.2),
                ):
                    im = afwImage.ImageF(size, size)
                    im = afwMath.offsetImage(unshiftedIm, dx, dy, algorithm)

                    if display:
                        afwDisplay.Display(frame=0).mtv(im, title=algorithm + ": image")

                    im -= refIm

                    if display:
                        afwDisplay.Display(frame=1).mtv(im, title=algorithm +
                                                        ": diff image (dx, dy) = (%f, %f)" % (dx, dy))

                    imArr = im.getArray()
                    imGoodVals = np.ma.array(
                        imArr, copy=False, mask=np.isnan(imArr)).compressed()

                    try:
                        imXY0 = tuple(im.getXY0())
                        self.assertEqual(imXY0, (dOrigX, dOrigY))
                        self.assertLess(abs(imGoodVals.mean()), maxMean*amp)
                        self.assertLess(abs(imGoodVals.max()), maxLim*amp)
                        self.assertLess(abs(imGoodVals.min()), maxLim*amp)
                    except Exception:
                        print("failed on algorithm=%s; dx = %s; dy = %s" %
                              (algorithm, dx, dy))
                        raise
예제 #12
0
    def addFakeSources(self, image, fakeImages, sourceType):
        """Add the fake sources to the given image

        Parameters
        ----------
        image : `lsst.afw.image.exposure.exposure.ExposureF`
                    The image into which the fake sources should be added
        fakeImages : `typing.Iterator` [`tuple` ['lsst.afw.image.ImageF`, `lsst.geom.Point2d`]]
                    An iterator of tuples that contains (or generates) images of fake sources,
                    and the locations they are to be inserted at.
        sourceType : `str`
                    The type (star/galaxy) of fake sources input

        Returns
        -------
        image : `lsst.afw.image.exposure.exposure.ExposureF`

        Notes
        -----
        Uses the x, y information in the ``fakeCat`` to position an image of the fake interpolated onto the
        pixel grid of the image. Sets the ``FAKE`` mask plane for the pixels added with the fake source.
        """

        imageBBox = image.getBBox()
        imageMI = image.maskedImage

        for (fakeImage, xy) in fakeImages:
            X0 = xy.getX() - fakeImage.getWidth() / 2 + 0.5
            Y0 = xy.getY() - fakeImage.getHeight() / 2 + 0.5
            self.log.debug("Adding fake source at %d, %d" %
                           (xy.getX(), xy.getY()))
            if sourceType == "galaxy":
                interpFakeImage = afwMath.offsetImage(fakeImage, X0, Y0,
                                                      "lanczos3")
                interpFakeImBBox = interpFakeImage.getBBox()
            else:
                interpFakeImage = fakeImage
                interpFakeImBBox = fakeImage.getBBox()

            interpFakeImBBox.clip(imageBBox)
            imageMIView = imageMI.Factory(imageMI, interpFakeImBBox)

            if interpFakeImBBox.getArea() > 0:
                clippedFakeImage = interpFakeImage.Factory(
                    interpFakeImage, interpFakeImBBox)
                clippedFakeImageMI = afwImage.MaskedImageF(clippedFakeImage)
                clippedFakeImageMI.mask.set(self.bitmask)
                imageMIView += clippedFakeImageMI

        return image
예제 #13
0
파일: offsetImage.py 프로젝트: lsst-dm/bp
    def testOffsetGaussian(self):
        """Insert a Gaussian, offset, and check the residuals"""
        size = 100
        im = afwImage.ImageF(afwGeom.Extent2I(size, size))

        xc, yc = size/2.0, size/2.0

        amp, sigma1 = 1.0, 3
        #
        # Calculate an image with a Gaussian at (xc -dx, yc - dy) and then shift it to (xc, yc)
        #
        dx, dy = 0.5, -0.5
        self.calcGaussian(im, xc - dx, yc - dy, amp, sigma1)
        im2 = afwMath.offsetImage(im, dx, dy, "lanczos5")
        #
        # Calculate Gaussian directly at (xc, yc)
        #
        self.calcGaussian(im, xc, yc, amp, sigma1)
        #
        # See how they differ
        #
        if display:
            ds9.mtv(im, frame=0)

        im -= im2

        if display:
            ds9.mtv(im, frame=1)

        imArr = im.getArray()
        imGoodVals = numpy.ma.array(imArr, copy=False, mask=numpy.isnan(imArr)).compressed()
        imMean = imGoodVals.mean()
        imMax = imGoodVals.max()
        imMin = imGoodVals.min()

        if False:
            print "mean = %g, min = %g, max = %g" % (imMean, imMin, imMax)
            
        self.assertTrue(abs(imMean) < 1e-7)
        self.assertTrue(abs(imMin) < 1.2e-3*amp)
        self.assertTrue(abs(imMax) < 1.2e-3*amp)
예제 #14
0
파일: offsetImage.py 프로젝트: lsst-dm/bp
    def testSetIntegerOffset(self):
        """Test that we can offset by positive and negative amounts"""
        
        self.inImage.set(50, 50, 400)

        if False and display:
            frame = 0
            ds9.mtv(self.inImage, frame=frame)
            ds9.pan(50, 50, frame=frame)
            ds9.dot("+", 50, 50, frame=frame)

        for delta in [-0.49, 0.51]:
            for dx, dy in [(2, 3), (-2, 3), (-2, -3), (2, -3)]:
                outImage = afwMath.offsetImage(self.inImage, dx + delta, dy + delta, self.algorithm)
                
                if False and display:
                    frame += 1
                    ds9.mtv(outImage, frame=frame)
                    ds9.pan(50, 50, frame=frame)
                    ds9.dot("+", 50 + dx + delta - outImage.getX0(), 50 + dy + delta - outImage.getY0(),
                            frame=frame)
예제 #15
0
    def setUp(self):
        width, height = 100, 300
        self.mi = afwImage.MaskedImageF(lsst.geom.ExtentI(width, height))
        self.mi.set(0)
        self.mi.getVariance().set(10)
        self.mi.getMask().addMaskPlane("DETECTED")

        self.FWHM = 5
        self.ksize = 25                      # size of desired kernel

        self.exposure = afwImage.makeExposure(self.mi)

        psf = roundTripPsf(2, algorithms.DoubleGaussianPsf(self.ksize, self.ksize,
                                                           self.FWHM/(2*math.sqrt(2*math.log(2))), 1, 0.1))
        self.exposure.setPsf(psf)

        for x, y in [(20, 20),
                     # (30, 35), (50, 50),
                     (60, 20), (60, 210), (20, 210)]:

            flux = 10000 - 0*x - 10*y

            sigma = 3 + 0.01*(y - self.mi.getHeight()/2)
            psf = roundTripPsf(3, algorithms.DoubleGaussianPsf(self.ksize, self.ksize, sigma, 1, 0.1))
            im = psf.computeImage().convertF()
            im *= flux
            x0y0 = lsst.geom.PointI(x - self.ksize//2, y - self.ksize//2)
            smi = self.mi.getImage().Factory(self.mi.getImage(),
                                             lsst.geom.BoxI(x0y0, lsst.geom.ExtentI(self.ksize)),
                                             afwImage.LOCAL)

            if False:                   # Test subtraction with non-centered psfs
                im = afwMath.offsetImage(im, 0.5, 0.5)

            smi += im
            del psf
            del im
            del smi

        roundTripPsf(4, algorithms.DoubleGaussianPsf(self.ksize, self.ksize,
                                                     self.FWHM/(2*math.sqrt(2*math.log(2))), 1, 0.1))

        self.cellSet = afwMath.SpatialCellSet(lsst.geom.BoxI(lsst.geom.PointI(0, 0),
                                                             lsst.geom.ExtentI(width, height)), 100)
        ds = afwDetection.FootprintSet(self.mi, afwDetection.Threshold(10), "DETECTED")
        #
        # Prepare to measure
        #
        schema = afwTable.SourceTable.makeMinimalSchema()
        sfm_config = measBase.SingleFrameMeasurementConfig()
        sfm_config.plugins = ["base_SdssCentroid", "base_CircularApertureFlux", "base_PsfFlux",
                              "base_SdssShape", "base_GaussianFlux", "base_PixelFlags"]
        sfm_config.slots.centroid = "base_SdssCentroid"
        sfm_config.slots.shape = "base_SdssShape"
        sfm_config.slots.psfFlux = "base_PsfFlux"
        sfm_config.slots.gaussianFlux = None
        sfm_config.slots.apFlux = "base_CircularApertureFlux_3_0"
        sfm_config.slots.modelFlux = "base_GaussianFlux"
        sfm_config.slots.calibFlux = None
        sfm_config.plugins["base_SdssShape"].maxShift = 10.0
        sfm_config.plugins["base_CircularApertureFlux"].radii = [3.0]
        task = measBase.SingleFrameMeasurementTask(schema, config=sfm_config)
        measCat = afwTable.SourceCatalog(schema)
        # detect the sources and run with the measurement task
        ds.makeSources(measCat)
        task.run(measCat, self.exposure)
        for source in measCat:
            self.cellSet.insertCandidate(algorithms.makePsfCandidate(source, self.exposure))
예제 #16
0
파일: psfIO.py 프로젝트: dr-guangtou/hs_hsc
    def setUp(self):
        width, height = 100, 300
        self.mi = afwImage.MaskedImageF(afwGeom.ExtentI(width, height))
        self.mi.set(0)
        self.mi.getVariance().set(10)
        self.mi.getMask().addMaskPlane("DETECTED")

        self.FWHM = 5
        self.ksize = 25  # size of desired kernel

        self.exposure = afwImage.makeExposure(self.mi)

        psf = roundTripPsf(
            2,
            algorithms.DoubleGaussianPsf(self.ksize, self.ksize,
                                         self.FWHM / (2 * sqrt(2 * log(2))), 1,
                                         0.1))
        self.exposure.setPsf(psf)

        for x, y in [
            (20, 20),
                #(30, 35), (50, 50),
            (60, 20),
            (60, 210),
            (20, 210)
        ]:

            flux = 10000 - 0 * x - 10 * y

            sigma = 3 + 0.01 * (y - self.mi.getHeight() / 2)
            psf = roundTripPsf(
                3,
                algorithms.DoubleGaussianPsf(self.ksize, self.ksize, sigma, 1,
                                             0.1))
            im = psf.computeImage().convertF()
            im *= flux
            smi = self.mi.getImage().Factory(
                self.mi.getImage(),
                afwGeom.BoxI(
                    afwGeom.PointI(x - self.ksize / 2, y - self.ksize / 2),
                    afwGeom.ExtentI(self.ksize)), afwImage.LOCAL)

            if False:  # Test subtraction with non-centered psfs
                im = afwMath.offsetImage(im, 0.5, 0.5)

            smi += im
            del psf
            del im
            del smi

        psf = roundTripPsf(
            4,
            algorithms.DoubleGaussianPsf(self.ksize, self.ksize,
                                         self.FWHM / (2 * sqrt(2 * log(2))), 1,
                                         0.1))

        self.cellSet = afwMath.SpatialCellSet(
            afwGeom.BoxI(afwGeom.PointI(0, 0), afwGeom.ExtentI(width, height)),
            100)
        ds = afwDetection.FootprintSet(self.mi, afwDetection.Threshold(10),
                                       "DETECTED")
        #
        # Prepare to measure
        #
        msConfig = algorithms.SourceMeasurementConfig()
        msConfig.load("tests/config/MeasureSources.py")
        schema = afwTable.SourceTable.makeMinimalSchema()
        measureSources = msConfig.makeMeasureSources(schema)
        catalog = afwTable.SourceCatalog(schema)
        msConfig.slots.calibFlux = None
        msConfig.slots.setupTable(catalog.table)
        ds.makeSources(catalog)
        for i, source in enumerate(catalog):
            measureSources.applyWithPeak(source, self.exposure)
            self.cellSet.insertCandidate(
                algorithms.makePsfCandidate(source, self.exposure))
예제 #17
0
    def setUp(self):
        width, height = 100, 300
        self.mi = afwImage.MaskedImageF(afwGeom.ExtentI(width, height))
        self.mi.set(0)
        self.mi.getVariance().set(10)
        self.mi.getMask().addMaskPlane("DETECTED")

        self.FWHM = 5
        self.ksize = 25  # size of desired kernel

        self.exposure = afwImage.makeExposure(self.mi)

        psf = roundTripPsf(
            2,
            algorithms.DoubleGaussianPsf(
                self.ksize, self.ksize,
                self.FWHM / (2 * math.sqrt(2 * math.log(2))), 1, 0.1))
        self.exposure.setPsf(psf)

        for x, y in [
            (20, 20),
                #(30, 35), (50, 50),
            (60, 20),
            (60, 210),
            (20, 210)
        ]:

            flux = 10000 - 0 * x - 10 * y

            sigma = 3 + 0.01 * (y - self.mi.getHeight() / 2)
            psf = roundTripPsf(
                3,
                algorithms.DoubleGaussianPsf(self.ksize, self.ksize, sigma, 1,
                                             0.1))
            im = psf.computeImage().convertF()
            im *= flux
            x0y0 = afwGeom.PointI(x - self.ksize // 2, y - self.ksize // 2)
            smi = self.mi.getImage().Factory(
                self.mi.getImage(),
                afwGeom.BoxI(x0y0, afwGeom.ExtentI(self.ksize)),
                afwImage.LOCAL)

            if False:  # Test subtraction with non-centered psfs
                im = afwMath.offsetImage(im, 0.5, 0.5)

            smi += im
            del psf
            del im
            del smi

        roundTripPsf(
            4,
            algorithms.DoubleGaussianPsf(
                self.ksize, self.ksize,
                self.FWHM / (2 * math.sqrt(2 * math.log(2))), 1, 0.1))

        self.cellSet = afwMath.SpatialCellSet(
            afwGeom.BoxI(afwGeom.PointI(0, 0), afwGeom.ExtentI(width, height)),
            100)
        ds = afwDetection.FootprintSet(self.mi, afwDetection.Threshold(10),
                                       "DETECTED")
        #
        # Prepare to measure
        #
        schema = afwTable.SourceTable.makeMinimalSchema()
        sfm_config = measBase.SingleFrameMeasurementConfig()
        sfm_config.plugins = [
            "base_SdssCentroid", "base_CircularApertureFlux", "base_PsfFlux",
            "base_SdssShape", "base_GaussianFlux", "base_PixelFlags"
        ]
        sfm_config.slots.centroid = "base_SdssCentroid"
        sfm_config.slots.shape = "base_SdssShape"
        sfm_config.slots.psfFlux = "base_PsfFlux"
        sfm_config.slots.instFlux = None
        sfm_config.slots.apFlux = "base_CircularApertureFlux_3_0"
        sfm_config.slots.modelFlux = "base_GaussianFlux"
        sfm_config.slots.calibFlux = None
        sfm_config.plugins["base_SdssShape"].maxShift = 10.0
        sfm_config.plugins["base_CircularApertureFlux"].radii = [3.0]
        task = measBase.SingleFrameMeasurementTask(schema, config=sfm_config)
        measCat = afwTable.SourceCatalog(schema)
        # detect the sources and run with the measurement task
        ds.makeSources(measCat)
        task.run(measCat, self.exposure)
        for source in measCat:
            self.cellSet.insertCandidate(
                algorithms.makePsfCandidate(source, self.exposure))
# add Noise and write image/psf
for filter_name, image in images.items():
    tot_images[filter_name].addNoise(noise)
    tot_images[filter_name].write('%s/image_%s.fits' %
                                  (output_dir, filter_name))

psf_bounds = galsim.BoundsI(0, 41, 0, 41)
psf_image = galsim.ImageF(psf_bounds, scale=scale)
psf.drawImage(image=psf_image)
psf_image.write('%s/psf_image.fits' % output_dir)

# Read in PSF
lsst_psf_image = afwImage.ImageF('%s/psf_image.fits' % output_dir)
bbox = afwGeom.Box2I(afwGeom.Point2I(0, 0), afwGeom.Extent2I(41, 41))
lsst_psf_image = lsst_psf_image[bbox].convertD()
lsst_psf_image = afwMath.offsetImage(lsst_psf_image, -0.5, -0.5)
kernel = afwMath.FixedKernel(lsst_psf_image)
kernelPsf = measAlg.KernelPsf(kernel)

# Exposure setup
wcs = afwImage.makeWcs(
    afwCoord.Coord(0. * afwGeom.degrees, 0. * afwGeom.degrees),
    afwGeom.Point2D(0.0, 0.0), 0.168 * 3600, 0.0, 0.0, 0.168 * 3600)
calib = afwImage.Calib()
calib.setFluxMag0(1e12)

# Config and task setup
measure_config = SingleFrameMeasurementTask.ConfigClass()
measure_config.load(
    '/tigress/rea3/lsst/DM-8059/obs_subaru/config/apertures.py')
measure_config.load('/tigress/rea3/lsst/DM-8059/obs_subaru/config/kron.py')