Example #1
0
    def checkWcs(self, parentExposure, subExposure):
        """Compare WCS at corner points of a sub-exposure and its parent exposure
           By using the function indexToPosition, we should be able to convert the indices
           (of the four corners (of the sub-exposure)) to positions and use the wcs
           to get the same sky coordinates for each.
        """
        subMI = subExposure.getMaskedImage()
        subDim = subMI.getDimensions()

        # Note: pixel positions must be computed relative to XY0 when working
        # with WCS
        mainWcs = parentExposure.getWcs()
        subWcs = subExposure.getWcs()

        for xSubInd in (0, subDim.getX()-1):
            for ySubInd in (0, subDim.getY()-1):
                self.assertSpherePointsAlmostEqual(
                    mainWcs.pixelToSky(
                        afwImage.indexToPosition(xSubInd),
                        afwImage.indexToPosition(ySubInd),
                    ),
                    subWcs.pixelToSky(
                        afwImage.indexToPosition(xSubInd),
                        afwImage.indexToPosition(ySubInd),
                    ))
Example #2
0
    def testExactImages(self):
        """Confirm that kernel image at each location is correct
        """
        desImage = afwImage.ImageD(
            afwGeom.Extent2I(self.kernel.getWidth(), self.kernel.getHeight()))

        for doNormalize in (False, True):
            region = mathDetail.KernelImagesForRegion(self.kernel, self.bbox,
                                                      self.xy0, doNormalize)
            for location in (
                    region.BOTTOM_LEFT,
                    region.BOTTOM_RIGHT,
                    region.TOP_LEFT,
                    region.TOP_RIGHT,
            ):
                pixelIndex = region.getPixelIndex(location)
                xPos = afwImage.indexToPosition(pixelIndex[0] + self.xy0[0])
                yPos = afwImage.indexToPosition(pixelIndex[1] + self.xy0[1])
                self.kernel.computeImage(desImage, doNormalize, xPos, yPos)
                desImArr = desImage.getArray().transpose().copy()

                actImage = region.getImage(location)
                actImArr = actImage.getArray().transpose().copy()
                errStr = imTestUtils.imagesDiffer(actImArr, desImArr)
                if errStr:
                    self.fail("exact image(%s) incorrect:\n%s" %
                              (LocNameDict[location], errStr))
Example #3
0
    def checkWcs(self, parentExposure, subExposure):
        """Compare WCS at corner points of a sub-exposure and its parent exposure
           By using the function indexToPosition, we should be able to convert the indices
           (of the four corners (of the sub-exposure)) to positions and use the wcs
           to get the same sky coordinates for each.
        """
        subMI = subExposure.getMaskedImage()
        subDim = subMI.getDimensions()

        # Note: pixel positions must be computed relative to XY0 when working
        # with WCS
        mainWcs = parentExposure.getWcs()
        subWcs = subExposure.getWcs()

        for xSubInd in (0, subDim.getX()-1):
            for ySubInd in (0, subDim.getY()-1):
                self.assertSpherePointsAlmostEqual(
                    mainWcs.pixelToSky(
                        afwImage.indexToPosition(xSubInd),
                        afwImage.indexToPosition(ySubInd),
                    ),
                    subWcs.pixelToSky(
                        afwImage.indexToPosition(xSubInd),
                        afwImage.indexToPosition(ySubInd),
                    ))
    def getInterpImage(self, bbox):
        """Return an image interpolated in R.A direction covering supplied bounding box

        @param[in] bbox: integer bounding box for image (afwGeom.Box2I)
        """

        npoints = len(self._xList)
        #sort by X coordinate
        if npoints < 1:
            raise RuntimeError("Cannot create scaling image. Found no fluxMag0s to interpolate")

        x, z = zip(*sorted(zip(self._xList, self._scaleList)))

        xvec = afwMath.vectorD(x)
        zvec = afwMath.vectorD(z)
        height = bbox.getHeight()
        width = bbox.getWidth()
        x0, y0 = bbox.getMin()

        interp = afwMath.makeInterpolate(xvec, zvec, self.interpStyle)
        interpValArr = numpy.zeros(width, dtype=numpy.float32)

        for i, xInd in enumerate(range(x0, x0 + width)):
            xPos = afwImage.indexToPosition(xInd)
            interpValArr[i] = interp.interpolate(xPos)

        # assume the maskedImage being scaled is MaskedImageF (which is usually true); see ticket #3070
        interpGrid = numpy.meshgrid(interpValArr, range(0, height))[0].astype(numpy.float32)
        image = afwImage.makeImageFromArray(interpGrid)
        image.setXY0(x0, y0)
        return image
    def getInterpImage(self, bbox):
        """Return an image interpolated in R.A direction covering supplied bounding box

        @param[in] bbox: integer bounding box for image (afwGeom.Box2I)
        """

        npoints = len(self._xList)
        # sort by X coordinate
        if npoints < 1:
            raise RuntimeError(
                "Cannot create scaling image. Found no fluxMag0s to interpolate"
            )

        x, z = list(zip(*sorted(zip(self._xList, self._scaleList))))

        xvec = np.array(x, dtype=float)
        zvec = np.array(z, dtype=float)
        height = bbox.getHeight()
        width = bbox.getWidth()
        x0, y0 = bbox.getMin()

        interp = afwMath.makeInterpolate(xvec, zvec, self.interpStyle)
        interpValArr = np.zeros(width, dtype=np.float32)

        for i, xInd in enumerate(range(x0, x0 + width)):
            xPos = afwImage.indexToPosition(xInd)
            interpValArr[i] = interp.interpolate(xPos)

        # assume the maskedImage being scaled is MaskedImageF (which is usually true); see ticket #3070
        interpGrid = np.meshgrid(interpValArr,
                                 range(0, height))[0].astype(np.float32)
        image = afwImage.makeImageFromArray(interpGrid)
        image.setXY0(x0, y0)
        return image
Example #6
0
    def testExactImages(self):
        """Confirm that kernel image at each location is correct
        """
        desImage = afwImage.ImageD(afwGeom.Extent2I(self.kernel.getWidth(), self.kernel.getHeight()))

        for doNormalize in (False, True):
            region = mathDetail.KernelImagesForRegion(self.kernel, self.bbox, self.xy0, doNormalize)
            for location in (
                region.BOTTOM_LEFT,
                region.BOTTOM_RIGHT,
                region.TOP_LEFT,
                region.TOP_RIGHT,
            ):
                pixelIndex = region.getPixelIndex(location)
                xPos = afwImage.indexToPosition(pixelIndex[0] + self.xy0[0])
                yPos = afwImage.indexToPosition(pixelIndex[1] + self.xy0[1])
                self.kernel.computeImage(desImage, doNormalize, xPos, yPos)

                actImage = region.getImage(location)
                msg = "exact image(%s) incorrect" % (LocNameDict[location],)
                self.assertImagesNearlyEqual(actImage, desImage, msg=msg)
 def testExactImages(self):
     """Confirm that kernel image at each location is correct
     """
     desImage = afwImage.ImageD(afwGeom.Extent2I(self.kernel.getWidth(), self.kernel.getHeight()))
     
     for doNormalize in (False, True):
         region = mathDetail.KernelImagesForRegion(self.kernel, self.bbox, self.xy0, doNormalize)
         for location in (
             region.BOTTOM_LEFT,
             region.BOTTOM_RIGHT,
             region.TOP_LEFT,
             region.TOP_RIGHT,
         ):
             pixelIndex = region.getPixelIndex(location)
             xPos = afwImage.indexToPosition(pixelIndex[0] + self.xy0[0])
             yPos = afwImage.indexToPosition(pixelIndex[1] + self.xy0[1])
             self.kernel.computeImage(desImage, doNormalize, xPos, yPos)
             
             actImage = region.getImage(location)
             msg = "exact image(%s) incorrect" % (LocNameDict[location],)
             self.assertImagesNearlyEqual(actImage, desImage, msg=msg)
 def testExactImages(self):
     """Confirm that kernel image at each location is correct
     """
     desImage = afwImage.ImageD(afwGeom.Extent2I(self.kernel.getWidth(), self.kernel.getHeight()))
     
     for doNormalize in (False, True):
         region = mathDetail.KernelImagesForRegion(self.kernel, self.bbox, self.xy0, doNormalize)
         for location in (
             region.BOTTOM_LEFT,
             region.BOTTOM_RIGHT,
             region.TOP_LEFT,
             region.TOP_RIGHT,
         ):
             pixelIndex = region.getPixelIndex(location)
             xPos = afwImage.indexToPosition(pixelIndex[0] + self.xy0[0])
             yPos = afwImage.indexToPosition(pixelIndex[1] + self.xy0[1])
             self.kernel.computeImage(desImage, doNormalize, xPos, yPos)
             desImArr = desImage.getArray().transpose().copy()
             
             actImage = region.getImage(location)
             actImArr = actImage.getArray().transpose().copy()
             errStr = imTestUtils.imagesDiffer(actImArr, desImArr)
             if errStr:
                 self.fail("exact image(%s) incorrect:\n%s" % (LocNameDict[location], errStr))
    def assess(self, cand, kFn1, bgFn1, kFn2, bgFn2, frame0):
        tmi = cand.getTemplateMaskedImage()
        smi = cand.getScienceMaskedImage()

        im1 = afwImage.ImageD(kFn1.getDimensions())
        kFn1.computeImage(im1, False,
                          afwImage.indexToPosition(int(cand.getXCenter())),
                          afwImage.indexToPosition(int(cand.getYCenter())))
        fk1 = afwMath.FixedKernel(im1)
        bg1 = bgFn1(afwImage.indexToPosition(int(cand.getXCenter())),
                    afwImage.indexToPosition(int(cand.getYCenter())))
        d1 = ipDiffim.convolveAndSubtract(tmi, smi, fk1, bg1)

        ####

        im2 = afwImage.ImageD(kFn2.getDimensions())
        kFn2.computeImage(im2, False,
                          afwImage.indexToPosition(int(cand.getXCenter())),
                          afwImage.indexToPosition(int(cand.getYCenter())))
        fk2 = afwMath.FixedKernel(im2)
        bg2 = bgFn2(afwImage.indexToPosition(int(cand.getXCenter())),
                    afwImage.indexToPosition(int(cand.getYCenter())))
        d2 = ipDiffim.convolveAndSubtract(tmi, smi, fk2, bg2)

        if display:
            disp = afwDisplay.Display(frame=frame0)
            disp.mtv(tmi, title="Template Masked Image")
            disp.dot("Cand %d" % (cand.getId()), 0, 0)

            afwDisplay.Display(frame=frame0 + 1).mtv(
                smi, title="Science Masked Image")
            afwDisplay.Display(frame=frame0 + 2).mtv(im1,
                                                     title="Masked Image: 1")
            afwDisplay.Display(frame=frame0 + 3).mtv(
                d1, title="Difference Image: 1")
            afwDisplay.Display(frame=frame0 + 4).mtv(im2,
                                                     title="Masked Image: 2")
            afwDisplay.Display(frame=frame0 + 5).mtv(
                d2, title="Difference Image: 2")

        logger.debug("Full Spatial Model")
        self.stats(cand.getId(), d1)

        logger.debug("N-1 Spatial Model")
        self.stats(cand.getId(), d2)
    def assess(self, cand, kFn1, bgFn1, kFn2, bgFn2, frame0):
        tmi   = cand.getTemplateMaskedImage()
        smi   = cand.getScienceMaskedImage()
        
        im1   = afwImage.ImageD(kFn1.getDimensions())
        kFn1.computeImage(im1, False,
                          afwImage.indexToPosition(int(cand.getXCenter())),
                          afwImage.indexToPosition(int(cand.getYCenter())))
        fk1   = afwMath.FixedKernel(im1)
        bg1   = bgFn1(afwImage.indexToPosition(int(cand.getXCenter())),
                      afwImage.indexToPosition(int(cand.getYCenter())))
        d1    = ipDiffim.convolveAndSubtract(tmi, smi, fk1, bg1)

        ####
        
        im2   = afwImage.ImageD(kFn2.getDimensions())
        kFn2.computeImage(im2, False,
                          afwImage.indexToPosition(int(cand.getXCenter())),
                          afwImage.indexToPosition(int(cand.getYCenter())))
        fk2   = afwMath.FixedKernel(im2)
        bg2   = bgFn2(afwImage.indexToPosition(int(cand.getXCenter())),
                      afwImage.indexToPosition(int(cand.getYCenter())))
        d2    = ipDiffim.convolveAndSubtract(tmi, smi, fk2, bg2)

        if display:
            ds9.mtv(tmi, frame=frame0+0)
            ds9.dot("Cand %d" % (cand.getId()), 0, 0, frame=frame0+0)
            
            ds9.mtv(smi, frame=frame0+1)
            ds9.mtv(im1, frame=frame0+2)
            ds9.mtv(d1,  frame=frame0+3)
            ds9.mtv(im2, frame=frame0+4)
            ds9.mtv(d2,  frame=frame0+5)

        pexLog.Trace("lsst.ip.diffim.JackknifeResampleKernel", 1,
                     "Full Spatial Model")
        self.stats(cand.getId(), d1)

        pexLog.Trace("lsst.ip.diffim.JackknifeResampleKernel", 1,
                     "N-1 Spatial Model")
        self.stats(cand.getId(), d2)
    def assess(self, cand, kFn1, bgFn1, kFn2, bgFn2, frame0):
        tmi = cand.getTemplateMaskedImage()
        smi = cand.getScienceMaskedImage()

        im1 = afwImage.ImageD(kFn1.getDimensions())
        kFn1.computeImage(im1, False,
                          afwImage.indexToPosition(int(cand.getXCenter())),
                          afwImage.indexToPosition(int(cand.getYCenter())))
        fk1 = afwMath.FixedKernel(im1)
        bg1 = bgFn1(afwImage.indexToPosition(int(cand.getXCenter())),
                    afwImage.indexToPosition(int(cand.getYCenter())))
        d1 = ipDiffim.convolveAndSubtract(tmi, smi, fk1, bg1)

        ####

        im2 = afwImage.ImageD(kFn2.getDimensions())
        kFn2.computeImage(im2, False,
                          afwImage.indexToPosition(int(cand.getXCenter())),
                          afwImage.indexToPosition(int(cand.getYCenter())))
        fk2 = afwMath.FixedKernel(im2)
        bg2 = bgFn2(afwImage.indexToPosition(int(cand.getXCenter())),
                    afwImage.indexToPosition(int(cand.getYCenter())))
        d2 = ipDiffim.convolveAndSubtract(tmi, smi, fk2, bg2)

        if display:
            disp = afwDisplay.Display(frame=frame0)
            disp.mtv(tmi, title="Template Masked Image")
            disp.dot("Cand %d" % (cand.getId()), 0, 0)

            afwDisplay.Display(frame=frame0 + 1).mtv(smi, title="Science Masked Image")
            afwDisplay.Display(frame=frame0 + 2).mtv(im1, title="Masked Image: 1")
            afwDisplay.Display(frame=frame0 + 3).mtv(d1, title="Difference Image: 1")
            afwDisplay.Display(frame=frame0 + 4).mtv(im2, title="Masked Image: 2")
            afwDisplay.Display(frame=frame0 + 5).mtv(d2, title="Difference Image: 2")

        logger.debug("Full Spatial Model")
        self.stats(cand.getId(), d1)

        logger.debug("N-1 Spatial Model")
        self.stats(cand.getId(), d2)
Example #12
0
    def index(self, exposure_or_metadata, data_id, database):
        """Spatially index an |exposure| or |metadata| object.

        Parameters
        ----------

        exposure_or_metadata : lsst.afw.image.Exposure[DFILU] or lsst.daf.base.PropertySet
            An afw |exposure| or corresponding |metadata| object.

        data_id : object
            An object identifying a single exposure (e.g. as used by the
            butler). It must be possible to pickle `data_id`.

        database : sqlite3.Connection or str
            A connection to (or filename of) a SQLite 3 database.

        Returns
        -------

        ``None``, unless the |defer_writes| coniguration parameter is ``True``.
        In that case, an :class:`.ExposureInfo` object containing a pickled
        data-id and an |encoded| |polygon| is returned.
        """
        # Get a pixel index bounding box for the exposure.
        if isinstance(exposure_or_metadata, daf_base.PropertySet):
            md = exposure_or_metadata
            # Map (LTV1, LTV2) to LSST (x0, y0). LSST convention says that
            # (x0, y0) is the location of the sub-image origin (the bottom-left
            # corner) relative to the origin of the parent, whereas LTVi encode
            # the origin of the parent relative to the origin of the subimage.
            pixel_bbox = afw_image.bboxFromMetadata(md)
            wcs = afw_image.makeWcs(md, False)
        else:
            pixel_bbox = exposure_or_metadata.getBBox()
            wcs = exposure_or_metadata.getWcs()
        # Pad the box by a configurable amount and bail if the result is empty.
        pixel_bbox.grow(self.config.pad_pixels)
        if pixel_bbox.isEmpty():
            self.log.warn("skipping exposure indexing for dataId=%s: "
                          "empty bounding box", data_id)
            return
        corners = []
        for c in pixel_bbox.getCorners():
            # Convert the box corners from pixel indexes to pixel positions,
            # and then to sky coordinates.
            c = wcs.pixelToSky(afw_image.indexToPosition(c.getX()),
                               afw_image.indexToPosition(c.getY()))
            c = (c.getLongitude().asRadians(), c.getLatitude().asRadians())
            # Bail if any coordinate is not finite.
            if any(math.isinf(x) or math.isnan(x) for x in c):
                self.log.warn("skipping exposure indexing for dataId=%s: "
                              "NaN or Inf in bounding box sky coordinate(s)"
                              " - bad WCS?", data_id)
                return
            # Convert from sky coordinates to unit vectors.
            corners.append(UnitVector3d(Angle.fromRadians(c[0]),
                                        Angle.fromRadians(c[1])))
        # Create a convex polygon containing the exposure pixels. When sphgeom
        # gains support for non-convex polygons, this could be changed to map
        # exposure.getPolygon() to a spherical equivalent, or to subdivide box
        # edges in pixel space to account for non linear projections. This
        # would have higher accuracy than the current approach of connecting
        # corner sky coordinates with great circles.
        poly = ConvexPolygon(corners)
        # Finally, persist or return the exposure information.
        info = ExposureInfo(pickle.dumps(data_id), poly.encode())
        if self.config.defer_writes:
            return info
        store_exposure_info(database, self.config.allow_replace, info)
Example #13
0
def refConvolve(imMaskVar, xy0, kernel, doNormalize, doCopyEdge):
    """Reference code to convolve a kernel with a masked image.

    Warning: slow (especially for spatially varying kernels).
    
    Inputs:
    - imMaskVar: (image, mask, variance) numpy arrays
    - xy0: xy offset of imMaskVar relative to parent image
    - kernel: lsst::afw::Core.Kernel object
    - doNormalize: normalize the kernel
    - doCopyEdge: if True: copy edge pixels from input image to convolved image;
                if False: set edge pixels to the standard edge pixel (image=nan, var=inf, mask=EDGE)
    """
    # Note: the original version of this function was written when numpy/image conversions were the
    # transpose of what they are today.  Rather than transpose the logic in this function or put
    # transposes throughout the rest of the file, I have transposed only the inputs and outputs.
    #  - Jim Bosch, 3/4/2011
    image, mask, variance = (imMaskVar[0].transpose(), imMaskVar[1].transpose(), imMaskVar[2].transpose())
    
    if doCopyEdge:
        # copy input arrays to output arrays and set EDGE bit of mask; non-edge pixels are overwritten below
        retImage = image.copy()
        retMask = mask.copy()
        retMask += EdgeMaskPixel
        retVariance = variance.copy()
    else:
        # initialize output arrays to all edge pixels; non-edge pixels will be overwritten below
        retImage = numpy.zeros(image.shape, dtype=image.dtype)
        retImage[:, :] = numpy.nan
        retMask = numpy.zeros(mask.shape, dtype=mask.dtype)
        retMask[:, :] = EdgeMaskPixel
        retVariance = numpy.zeros(variance.shape, dtype=image.dtype)
        retVariance[:, :] = numpy.inf
    
    kWidth = kernel.getWidth()
    kHeight = kernel.getHeight()
    numCols = image.shape[0] + 1 - kWidth
    numRows = image.shape[1] + 1 - kHeight
    if numCols < 0 or numRows < 0:
        raise RuntimeError("image must be larger than kernel in both dimensions")
    colRange = range(numCols)


    kImage = afwImage.ImageD(afwGeom.Extent2I(kWidth, kHeight))
    isSpatiallyVarying = kernel.isSpatiallyVarying()
    if not isSpatiallyVarying:
        kernel.computeImage(kImage, doNormalize)
        kImArr = kImage.getArray().transpose()

    retRow = kernel.getCtrY()
    for inRowBeg in range(numRows):
        inRowEnd = inRowBeg + kHeight
        retCol = kernel.getCtrX()
        if isSpatiallyVarying:
            rowPos = afwImage.indexToPosition(retRow) + xy0[1]
        for inColBeg in colRange:
            if isSpatiallyVarying:
                colPos = afwImage.indexToPosition(retCol) + xy0[0]
                kernel.computeImage(kImage, doNormalize, colPos, rowPos)
                kImArr = kImage.getArray().transpose()
            inColEnd = inColBeg + kWidth
            subImage = image[inColBeg:inColEnd, inRowBeg:inRowEnd]
            subVariance = variance[inColBeg:inColEnd, inRowBeg:inRowEnd]
            subMask = mask[inColBeg:inColEnd, inRowBeg:inRowEnd]
            retImage[retCol, retRow] = numpy.add.reduce((kImArr * subImage).flat)
            retVariance[retCol, retRow] = numpy.add.reduce((kImArr * kImArr * subVariance).flat)
            if IgnoreKernelZeroPixels:
                retMask[retCol, retRow] = numpy.bitwise_or.reduce((subMask * (kImArr != 0)).flat)
            else:
                retMask[retCol, retRow] = numpy.bitwise_or.reduce(subMask.flat)
            

            retCol += 1
        retRow += 1
    return (retImage.transpose(), retMask.transpose(), retVariance.transpose())
Example #14
0
def refConvolve(imMaskVar, xy0, kernel, doNormalize, doCopyEdge):
    """Reference code to convolve a kernel with a masked image.

    Warning: slow (especially for spatially varying kernels).

    Inputs:
    - imMaskVar: (image, mask, variance) numpy arrays
    - xy0: xy offset of imMaskVar relative to parent image
    - kernel: lsst::afw::Core.Kernel object
    - doNormalize: normalize the kernel
    - doCopyEdge: if True: copy edge pixels from input image to convolved image;
                if False: set edge pixels to the standard edge pixel (image=nan, var=inf, mask=EDGE)
    """
    # Note: the original version of this function was written when numpy/image conversions were the
    # transpose of what they are today.  Rather than transpose the logic in this function or put
    # transposes throughout the rest of the file, I have transposed only the inputs and outputs.
    #  - Jim Bosch, 3/4/2011
    image, mask, variance = (imMaskVar[0].transpose(),
                             imMaskVar[1].transpose(),
                             imMaskVar[2].transpose())

    if doCopyEdge:
        # copy input arrays to output arrays and set EDGE bit of mask; non-edge
        # pixels are overwritten below
        retImage = image.copy()
        retMask = mask.copy()
        retMask += EdgeMaskPixel
        retVariance = variance.copy()
    else:
        # initialize output arrays to all edge pixels; non-edge pixels will be
        # overwritten below
        retImage = numpy.zeros(image.shape, dtype=image.dtype)
        retImage[:, :] = numpy.nan
        retMask = numpy.zeros(mask.shape, dtype=mask.dtype)
        retMask[:, :] = NoDataMaskPixel
        retVariance = numpy.zeros(variance.shape, dtype=image.dtype)
        retVariance[:, :] = numpy.inf

    kWidth = kernel.getWidth()
    kHeight = kernel.getHeight()
    numCols = image.shape[0] + 1 - kWidth
    numRows = image.shape[1] + 1 - kHeight
    if numCols < 0 or numRows < 0:
        raise RuntimeError(
            "image must be larger than kernel in both dimensions")
    colRange = list(range(numCols))

    kImage = afwImage.ImageD(afwGeom.Extent2I(kWidth, kHeight))
    isSpatiallyVarying = kernel.isSpatiallyVarying()
    if not isSpatiallyVarying:
        kernel.computeImage(kImage, doNormalize)
        kImArr = kImage.getArray().transpose()

    retRow = kernel.getCtrY()
    for inRowBeg in range(numRows):
        inRowEnd = inRowBeg + kHeight
        retCol = kernel.getCtrX()
        if isSpatiallyVarying:
            rowPos = afwImage.indexToPosition(retRow) + xy0[1]
        for inColBeg in colRange:
            if isSpatiallyVarying:
                colPos = afwImage.indexToPosition(retCol) + xy0[0]
                kernel.computeImage(kImage, doNormalize, colPos, rowPos)
                kImArr = kImage.getArray().transpose()
            inColEnd = inColBeg + kWidth
            subImage = image[inColBeg:inColEnd, inRowBeg:inRowEnd]
            subVariance = variance[inColBeg:inColEnd, inRowBeg:inRowEnd]
            subMask = mask[inColBeg:inColEnd, inRowBeg:inRowEnd]
            retImage[retCol, retRow] = numpy.add.reduce(
                (kImArr * subImage).flat)
            retVariance[retCol, retRow] = numpy.add.reduce(
                (kImArr * kImArr * subVariance).flat)
            if IgnoreKernelZeroPixels:
                retMask[retCol, retRow] = numpy.bitwise_or.reduce(
                    (subMask * (kImArr != 0)).flat)
            else:
                retMask[retCol, retRow] = numpy.bitwise_or.reduce(subMask.flat)

            retCol += 1
        retRow += 1
    return [
        numpy.copy(numpy.transpose(arr), order="C")
        for arr in (retImage, retMask, retVariance)
    ]
def makeAutoCorrelation(kernelCellSet, spatialKernel, makePlot=False):
    candList = []
    for cell in kernelCellSet.getCellList():
        for cand in cell.begin(True):  # only look at non-bad candidates
            if cand.getStatus() == afwMath.SpatialCellCandidate.GOOD:
                candList.append(cand.getId())

    r = []
    d1 = []
    d2 = []

    for i in range(len(candList)):
        cand1 = kernelCellSet.getCandidateById(candList[i])
        x1 = cand1.getXCenter()
        y1 = cand1.getYCenter()

        # Original kernel
        kImage1 = afwImage.ImageD(spatialKernel.getDimensions())
        cand1.getKernel(ipDiffim.KernelCandidateF.ORIG).computeImage(kImage1, False)

        # Spatial approximation
        ksImage1 = afwImage.ImageD(spatialKernel.getDimensions())
        spatialKernel.computeImage(ksImage1, False,
                                   afwImage.indexToPosition(int(x1)),
                                   afwImage.indexToPosition(int(y1)))

        # Turn into numarrays for dot product
        ksVector1 = ksImage1.getArray().ravel()
        kVector1 = kImage1.getArray().ravel()

        for j in range(i+1, len(candList)):
            cand2 = kernelCellSet.getCandidateById(candList[j])
            x2 = cand2.getXCenter()
            y2 = cand2.getYCenter()

            # Original kernel
            kImage2 = afwImage.ImageD(spatialKernel.getDimensions())
            cand2.getKernel(ipDiffim.KernelCandidateF.ORIG).computeImage(kImage2, False)

            # Spatial approximation
            ksImage2 = afwImage.ImageD(spatialKernel.getDimensions())
            spatialKernel.computeImage(ksImage2, False,
                                       afwImage.indexToPosition(int(x2)),
                                       afwImage.indexToPosition(int(y2)))

            # Turn into numarrays for dot product
            ksVector2 = ksImage2.getArray().ravel()
            kVector2 = kImage2.getArray().ravel()

            ###

            # Add to cross correlation functions
            r.append(num.sqrt((x1 - x2)**2 + (y1 - y2)**2))
            d1.append(correlationD1(kVector1, ksVector1, kVector2, ksVector2))
            d2.append(correlationD2(kVector1, ksVector1, kVector2, ksVector2))

    r = num.array(r)
    d1 = num.array(d1)
    d2 = num.array(d2)

    if makePlot:
        plotCrossCorrelation(r, d1, d2)

    return r, d1, d2
def makeAutoCorrelation(kernelCellSet, spatialKernel, makePlot=False):
    kImage = afwImage.ImageD(spatialKernel.getDimensions())
    ksImage = afwImage.ImageD(spatialKernel.getDimensions())
    kInfo = []

    candList = []
    for cell in kernelCellSet.getCellList():
        for cand in cell.begin(True):  # only look at non-bad candidates
            if cand.getStatus() == afwMath.SpatialCellCandidate.GOOD:
                candList.append(cand.getId())

    r = []
    d1 = []
    d2 = []

    for i in range(len(candList)):
        cand1 = kernelCellSet.getCandidateById(candList[i])
        x1 = cand1.getXCenter()
        y1 = cand1.getYCenter()

        # Original kernel
        kImage1 = afwImage.ImageD(spatialKernel.getDimensions())
        cand1.getKernel(ipDiffim.KernelCandidateF.ORIG).computeImage(
            kImage1, False)

        # Spatial approximation
        ksImage1 = afwImage.ImageD(spatialKernel.getDimensions())
        spatialKernel.computeImage(ksImage1, False,
                                   afwImage.indexToPosition(int(x1)),
                                   afwImage.indexToPosition(int(y1)))

        # Turn into numarrays for dot product
        ksVector1 = ksImage1.getArray().ravel()
        kVector1 = kImage1.getArray().ravel()

        for j in range(i + 1, len(candList)):
            cand2 = kernelCellSet.getCandidateById(candList[j])
            x2 = cand2.getXCenter()
            y2 = cand2.getYCenter()

            # Original kernel
            kImage2 = afwImage.ImageD(spatialKernel.getDimensions())
            cand2.getKernel(ipDiffim.KernelCandidateF.ORIG).computeImage(
                kImage2, False)

            # Spatial approximation
            ksImage2 = afwImage.ImageD(spatialKernel.getDimensions())
            spatialKernel.computeImage(ksImage2, False,
                                       afwImage.indexToPosition(int(x2)),
                                       afwImage.indexToPosition(int(y2)))

            # Turn into numarrays for dot product
            ksVector2 = ksImage2.getArray().ravel()
            kVector2 = kImage2.getArray().ravel()

            ###

            # Add to cross correlation functions
            r.append(num.sqrt((x1 - x2)**2 + (y1 - y2)**2))
            d1.append(correlationD1(kVector1, ksVector1, kVector2, ksVector2))
            d2.append(correlationD2(kVector1, ksVector1, kVector2, ksVector2))

    r = num.array(r)
    d1 = num.array(d1)
    d2 = num.array(d2)

    if makePlot:
        plotCrossCorrelation(r, d1, d2)

    return r, d1, d2
Example #17
0
    mosaic = mos.makeMosaic()
    frame += 1
    ds9.mtv(mosaic, frame=frame, title="Kernel Bases")
    mos.drawLabels(frame=frame)

    # Spatial model
    mos.reset()
    width = templateExposure.getWidth()
    height = templateExposure.getHeight()
    stamps = []
    stampInfo = []
    for x in (0, width // 2, width):
        for y in (0, height // 2, height):
            im = afwImage.ImageD(spatialKernel.getDimensions())
            ksum = spatialKernel.computeImage(im, False,
                                              afwImage.indexToPosition(x),
                                              afwImage.indexToPosition(y))
            mos.append(im, "x=%d y=%d kSum=%.2f" % (x, y, ksum))

    mosaic = mos.makeMosaic()
    frame += 1
    ds9.mtv(mosaic, frame=frame, title="Spatial Kernels")
    mos.drawLabels(frame=frame)

    # Background
    backgroundIm = afwImage.ImageF(
        afwGeom.Extent2I(templateExposure.getWidth(),
                         templateExposure.getHeight()), 0)
    backgroundIm += spatialBg
    frame += 1
    ds9.mtv(backgroundIm, frame=frame, title="Background model")
Example #18
0
    ds9.mtv(mosaic, frame=frame, title = "Kernel Bases")
    mos.drawLabels(frame=frame)
        

    # Spatial model
    mos.reset()
    width = templateExposure.getWidth()
    height = templateExposure.getHeight()
    stamps = []
    stampInfo = []
    for x in (0, width//2, width):
        for y in (0, height//2, height):
            im   = afwImage.ImageD(spatialKernel.getDimensions())
            ksum = spatialKernel.computeImage(im,
                                              False,
                                              afwImage.indexToPosition(x),
                                              afwImage.indexToPosition(y))
            mos.append(im, "x=%d y=%d kSum=%.2f" % (x, y, ksum))

    mosaic = mos.makeMosaic()
    frame += 1
    ds9.mtv(mosaic, frame=frame, title = "Spatial Kernels")
    mos.drawLabels(frame=frame)
            

    # Background
    backgroundIm  = afwImage.ImageF(afwGeom.Extent2I(templateExposure.getWidth(), templateExposure.getHeight()), 0)
    backgroundIm += spatialBg
    frame += 1
    ds9.mtv(backgroundIm, frame=frame, title = "Background model")