Example #1
0
    def testFootprintFromCircle(self):
        """Create an elliptical Footprint"""
        ellipse = afwGeom.Ellipse(afwGeomEllipses.Axes(6, 6, 0),
                                  afwGeom.Point2D(9, 15))
        spanSet = afwGeom.SpanSet.fromShape(ellipse)
        foot = afwDetect.Footprint(
            spanSet,
            afwGeom.Box2I(afwGeom.Point2I(0, 0), afwGeom.Extent2I(20, 30)))

        idImage = afwImage.ImageU(
            afwGeom.Extent2I(foot.getRegion().getWidth(),
                             foot.getRegion().getHeight()))
        idImage.set(0)

        foot.spans.setImage(idImage, foot.getId())

        if False:
            ds9.mtv(idImage, frame=2)
Example #2
0
 def cmpExposure(self, e1, e2):
     self.assertEqual(e1.getDetector().getName(),
                      e2.getDetector().getName())
     self.assertEqual(e1.getDetector().getSerial(),
                      e2.getDetector().getSerial())
     self.assertEqual(e1.getFilter().getName(), e2.getFilter().getName())
     xy = afwGeom.Point2D(0, 0)
     self.assertEqual(e1.getWcs().pixelToSky(xy)[0],
                      e2.getWcs().pixelToSky(xy)[0])
     self.assertEqual(e1.getCalib().getExptime(),
                      e2.getCalib().getExptime())
     # check PSF identity
     if not e1.getPsf():
         self.assertFalse(e2.getPsf())
     else:
         psf1 = DummyPsf.swigConvert(e1.getPsf())
         psf2 = DummyPsf.swigConvert(e2.getPsf())
         self.assertEqual(psf1.getValue(), psf2.getValue())
Example #3
0
 def testAssertPairsNearlyEqual(self):
     """Test assertPairsNearlyEqual"""
     for pair0 in ((-5, 4), (-5, 0.001), (0, 0), (49, 0.1)):
         self.assertPairsNearlyEqual(pair0, pair0, maxDiff=1e-7)
         self.assertPairsNearlyEqual(afwGeom.Point2D(*pair0),
                                     afwGeom.Extent2D(*pair0),
                                     maxDiff=1e-7)
         for diff in ((0.001, 0), (-0.01, 0.03)):
             pair1 = [pair0[i] + diff[i] for i in range(2)]
             radialDiff = math.hypot(*diff)
             self.assertPairsNearlyEqual(pair0,
                                         pair1,
                                         maxDiff=radialDiff + 1e-7)
             self.assertRaises(AssertionError,
                               self.assertPairsNearlyEqual,
                               pair0,
                               pair1,
                               maxDiff=radialDiff - 1e-7)
Example #4
0
    def compareTransforms(self, orient, pixelSize=afwGeom.Extent2D(0.12,
                                                                   0.21)):
        """Compare makeFpPixelTransform and makePixelFpTransform to each other
        """
        fwdTransform = orient.makeFpPixelTransform(pixelSize)
        revTransform = orient.makePixelFpTransform(pixelSize)
        for x in (-100.1, 0.0, 230.0):
            for y in (-45.0, 0.0, 25.1):
                pixPos = afwGeom.Point2D(x, y)
                fwdFPPos = fwdTransform.forwardTransform(pixPos)
                fwdPixPos = fwdTransform.reverseTransform(fwdFPPos)
                revPixPos = revTransform.forwardTransform(fwdFPPos)
                revFPPos = revTransform.reverseTransform(pixPos)

                for i in range(2):
                    self.assertAlmostEqual(pixPos[i], fwdPixPos[i])
                    self.assertAlmostEqual(pixPos[i], revPixPos[i])
                    self.assertAlmostEqual(fwdFPPos[i], revFPPos[i])
Example #5
0
    def testTransformList(self):
        """Test transform method, list version
        """
        fromList = []
        for x in (-1.2, 0.0, 25.3):
            for y in (-23.4, 0.0, 2.3):
                fromList.append(afwGeom.Point2D(x, y))

        for fromSys in self.transformMap.getCoordSysList():
            for toSys in self.transformMap.getCoordSysList():
                toList = self.transformMap.transform(fromList, fromSys, toSys)

                self.assertEqual(len(fromList), len(toList))
                for fromPoint, toPoint in zip(fromList, toList):
                    predToPoint = self.transformMap.transform(
                        fromPoint, fromSys, toSys)
                    for i in range(2):
                        self.assertAlmostEqual(predToPoint[i], toPoint[i])
Example #6
0
    def testFactory(self):
        """Test the Factory function makeCoord()"""

        # make a (eg galactic) coord with the constructor, and with the factory
        # and see if they agree.
        for constructor, enum, stringName in self.coordList:
            con = constructor(self.l * afwGeom.degrees,
                              self.b * afwGeom.degrees)
            self.assertEqual(con.getCoordSystem(), enum)
            factories = []
            factories.append(
                afwCoord.makeCoord(enum, self.l * afwGeom.degrees,
                                   self.b * afwGeom.degrees))
            factories.append(
                afwCoord.makeCoord(afwCoord.makeCoordEnum(stringName),
                                   self.l * afwGeom.degrees,
                                   self.b * afwGeom.degrees))
            factories.append(
                afwCoord.makeCoord(enum, afwGeom.Point2D(self.l, self.b),
                                   afwGeom.degrees))

            print("Factory: ")
            for fac in factories:
                self.assertEqual(fac.getCoordSystem(), enum)
                self.assertAlmostEqual(con[0], fac[0])
                self.assertAlmostEqual(con[1], fac[1])
                print(" tried ", fac[0], fac[1], "(expected ", con[0], con[1],
                      ")")

            # can we create an empty coord, and use reset() to fill it?
            c = afwCoord.makeCoord(enum)
            c.reset(1.0 * afwGeom.degrees, 1.0 * afwGeom.degrees, 2000.0)
            self.assertEqual(c.getLongitude().asDegrees(), 1.0)
            self.assertEqual(c.getLatitude().asDegrees(), 1.0)

        # verify that makeCoord throws when given an epoch for an epochless
        # system
        with self.assertRaises(pexEx.Exception):
            afwCoord.makeCoord(afwCoord.GALACTIC, self.l * afwGeom.degrees,
                               self.b * afwGeom.degrees, 2000.0)

        with self.assertRaises(pexEx.Exception):
            afwCoord.makeCoord(afwCoord.ICRS, self.l * afwGeom.degrees,
                               self.b * afwGeom.degrees, 2000.0)
Example #7
0
    def std_raw(self, image, dataId):
        """Standardize a raw dataset by converting it to an Exposure instead of an Image"""
        if isinstance(image, afwImage.DecoratedImageU) or isinstance(image, afwImage.DecoratedImageI) or \
                isinstance(image, afwImage.DecoratedImageF) or isinstance(image, afwImage.DecoratedImageD):
            exposure = afwImage.makeExposure(afwImage.makeMaskedImage(image.getImage()))
        else:
            exposure = image
        md = image.getMetadata()

        if True:
            wcs = afwImage.makeWcs(md, True)

            # The CASU WCSes use ZPN; our stuff wants TAN
            # This won't work near the pole, but should be decent away from it.
            box = afwGeom.BoxD(image.getImage().getBBox())
            refPix = box.getCenter()
            refSky = wcs.pixelToSky(refPix)
            refSkyOffsetX = wcs.pixelToSky(refPix + afwGeom.Extent2D(1.0, 0.0))
            refSkyOffsetY = wcs.pixelToSky(refPix + afwGeom.Extent2D(0.0, 1.0))
            xPixelScale = refSky.angularSeparation(refSkyOffsetX).asDegrees()
            yPixelScale = refSky.angularSeparation(refSkyOffsetY).asDegrees()

            xPixelScale = yPixelScale = wcs.pixelScale().asDegrees()
        else:
            refPix = afwGeom.Point2D(md.get("CRPIX1"), md.get("CRPIX2"))
            refSky = afwCoord.IcrsCoord(md.get("CRVAL1")*afwGeom.degrees,
                                        md.get("CRVAL2")*afwGeom.degrees)
            xPixelScale = yPixelScale = (0.2*afwGeom.arcseconds).asDegrees()

#        import pdb;pdb.set_trace()

        exposure.setMetadata(md)
        #newWcs = afwImage.makeWcs(refSky, refPix, xPixelScale, 0.0, 0.0, yPixelScale)
        #wcs = afwImage.makeWcs(md, True)
        #exposure.setWcs(newWcs)
        exposure.setWcs(wcs)

        """ Set up exposure time """
        pathId = self._transformId(dataId)
        expTime = pathId['expTime']
        exposure.getCalib().setExptime(expTime)

        return self._standardizeExposure(self.exposures['raw'], exposure, dataId,
                                         trimmed=False)
Example #8
0
    def __init__(self, config=None):
        """Construct a EquatSkyMap

        @param[in] config: an instance of self.ConfigClass; if None the default config is used
        """
        BaseSkyMap.__init__(self, config)

        decRange = tuple(
            afwGeom.Angle(dr, afwGeom.degrees) for dr in self.config.decRange)
        midDec = (decRange[0] + decRange[1]) / 2.0
        tractWidthRA = afwGeom.Angle(360.0 / self.config.numTracts,
                                     afwGeom.degrees)
        tractOverlap = afwGeom.Angle(self.config.tractOverlap, afwGeom.degrees)

        for id in range(self.config.numTracts):
            begRA = tractWidthRA * id
            endRA = begRA + tractWidthRA
            vertexCoordList = (
                afwGeom.SpherePoint(begRA, decRange[0]),
                afwGeom.SpherePoint(endRA, decRange[0]),
                afwGeom.SpherePoint(endRA, decRange[1]),
                afwGeom.SpherePoint(begRA, decRange[1]),
            )

            midRA = begRA + tractWidthRA / 2.0
            ctrCoord = afwGeom.SpherePoint(midRA, midDec)

            # CRVal must have Dec=0 for symmetry about the equator
            crValCoord = afwGeom.SpherePoint(midRA, afwGeom.Angle(0.0))

            # make initial WCS; don't worry about crPixPos because TractInfo will shift it as required
            wcs = self._wcsFactory.makeWcs(crPixPos=afwGeom.Point2D(0, 0),
                                           crValCoord=crValCoord)

            self._tractInfoList.append(
                TractInfo(
                    id=id,
                    patchInnerDimensions=self.config.patchInnerDimensions,
                    patchBorder=self.config.patchBorder,
                    ctrCoord=ctrCoord,
                    vertexCoordList=vertexCoordList,
                    tractOverlap=tractOverlap,
                    wcs=wcs,
                ))
Example #9
0
def createImage(
        dataId={"name": "foobar"},  # Data identifier
        center=CENTER,  # Celestial coordinates of center (Coord)
        rotateAxis=ROTATEAXIS,  # Rotation axis (Angle)
        rotateAngle=0 *
    afwGeom.degrees,  # Rotation angle/distance to move (Angle)
        dims=DIMS,  # Image dimensions (Extent2I)
        scale=SCALE  # Pixel scale (Angle)
):
    crpix = afwGeom.Point2D(afwGeom.Extent2D(dims) * 0.5)
    center = center.clone(
    )  # Ensure user doesn't need it, because we're mangling it
    center.rotate(rotateAxis, rotateAngle)
    wcs = afwImage.makeWcs(center, crpix, scale.asDegrees(), 0.0, 0.0,
                           scale.asDegrees())
    return SelectStruct(
        DummyDataRef(dataId), wcs,
        afwGeom.Box2I(afwGeom.Point2I(0, 0),
                      afwGeom.Extent2I(dims[0], dims[1])))
Example #10
0
    def testAssertBoxesNearlyEqual(self):
        """Test assertBoxesNearlyEqual"""
        for min0 in ((0, 0), (-1000.5, 5000.1)):
            min0 = afwGeom.Point2D(*min0)
            for extent0 in ((2.01, 3.01), (5432, 2342)):
                extent0 = afwGeom.Extent2D(*extent0)
                box0 = afwGeom.Box2D(min0, extent0)
                self.assertBoxesNearlyEqual(box0, box0, maxDiff=1e-7)
                for deltaExtent in ((0.001, -0.001), (2, -3)):
                    deltaExtent = afwGeom.Extent2D(*deltaExtent)
                    box1 = afwGeom.Box2D(box0.getMin() + deltaExtent,
                                         box0.getMax())
                    radDiff = math.hypot(*deltaExtent)
                    self.assertBoxesNearlyEqual(box0,
                                                box1,
                                                maxDiff=radDiff * 1.00001)
                    self.assertRaises(AssertionError,
                                      self.assertBoxesNearlyEqual,
                                      box0,
                                      box1,
                                      maxDiff=radDiff * 0.99999)

                    box2 = afwGeom.Box2D(box0.getMin() - deltaExtent,
                                         box0.getMax())
                    self.assertBoxesNearlyEqual(box0,
                                                box2,
                                                maxDiff=radDiff * 1.00001)
                    self.assertRaises(AssertionError,
                                      self.assertBoxesNearlyEqual,
                                      box0,
                                      box2,
                                      maxDiff=radDiff * 0.999999)

                    box3 = afwGeom.Box2D(box0.getMin(),
                                         box0.getMax() + deltaExtent)
                    self.assertBoxesNearlyEqual(box0,
                                                box3,
                                                maxDiff=radDiff * 1.00001)
                    self.assertRaises(AssertionError,
                                      self.assertBoxesNearlyEqual,
                                      box0,
                                      box3,
                                      maxDiff=radDiff * 0.999999)
Example #11
0
 def testTablePersistence(self):
     ellipse = afwGeomEllipses.Ellipse(afwGeomEllipses.Axes(8, 6, 0.25),
                                       afwGeom.Point2D(9, 15))
     fp1 = afwDetect.Footprint(ellipse)
     fp1.addPeak(6, 7, 2)
     fp1.addPeak(8, 9, 3)
     filename = "testFootprintTablePersistence.fits"
     fp1.writeFits(filename)
     fp2 = afwDetect.Footprint.readFits(filename)
     self.assertEqual(fp1.getArea(), fp2.getArea())
     self.assertEqual(list(fp1.getSpans()), list(fp2.getSpans()))
     self.assertEqual(len(fp1.getPeaks()), len(fp2.getPeaks()))
     for peak1, peak2 in zip(fp1.getPeaks(), fp2.getPeaks()):
         self.assertEqual(peak1.getIx(), peak2.getIx())
         self.assertEqual(peak1.getIy(), peak2.getIy())
         self.assertEqual(peak1.getFx(), peak2.getFx())
         self.assertEqual(peak1.getFy(), peak2.getFy())
         self.assertEqual(peak1.getPeakValue(), peak2.getPeakValue())
     os.remove(filename)
Example #12
0
    def testFailureFlagged(self):
        # Check that aperture correction flag is set to True if aperture correction is invalid (negative)
        flagName = self.name + "_flag_apCorr"
        flagKey = self.schema.find(flagName).key
        source_test_flux = 5.2
        source_test_centroid = afwGeom.Point2D(5, 7.1)
        sourceCat = initializeSourceCatalog(schema=self.schema, name=self.name, flux=source_test_flux,
                                            sigma=0, centroid=source_test_centroid)
        fluxName = self.name + "_flux"
        fluxSigmaName = self.name + "_fluxSigma"

        apCorrMap = afwImage.ApCorrMap()
        bbox = afwGeom.Box2I(afwGeom.Point2I(0, 0), afwGeom.ExtentI(10, 10))
        coefficients = -(numpy.ones((1, 1), dtype=float))
        coefficients_sigma = numpy.zeros((1, 1), dtype=float)
        apCorrMap[fluxName] = ChebyshevBoundedField(bbox, coefficients)
        apCorrMap[fluxSigmaName] = ChebyshevBoundedField(bbox, coefficients_sigma)
        self.ap_corr_task.run(sourceCat, apCorrMap)
        self.assertTrue(sourceCat[flagKey])
Example #13
0
 def get_pixel_coords(self, dataId, mag_cut=22.):
     calexp = self.butler.get('calexp', dataId)
     wcs = calexp.getWcs()
     dim = calexp.getDimensions()
     centerPixel = afw_geom.Point2D(dim.getX()/2., dim.getY()/2.)
     centerCoord = wcs.pixelToSky(centerPixel)
     radius = afw_geom.Angle(0.17, afw_geom.degrees)
     ref_cat \
         = self.refTask.loadSkyCircle(centerCoord, radius,
                                      calexp.getFilter().getName()).refCat
     xref, yref = [], []
     mags = -2.5*np.log10(ref_cat['u_flux']/3631.)
     for i, row in enumerate(ref_cat):
         if mags[i] > mag_cut:
             continue
         point = wcs.skyToPixel(row.getCoord())
         xref.append(point.getX())
         yref.append(point.getY())
     return xref, yref, ref_cat
Example #14
0
    def testMakeCameraPoint(self):
        """Test the makeCameraPoint method
        """
        dw = DetectorWrapper()
        for xyMM in ((25.6, -31.07), (0, 0)):
            point = afwGeom.Point2D(*xyMM)
            for sysName in ("csys1", "csys2"):
                for detectorName in ("", dw.name, "a different detector"):
                    cameraSys1 = cameraGeom.CameraSys(sysName, detectorName)
                    cameraPoint1 = dw.detector.makeCameraPoint(point, cameraSys1)

                    self.assertEquals(cameraPoint1.getPoint(), point)
                    self.assertEquals(cameraPoint1.getCameraSys(), cameraSys1)

                cameraSysPrefix = cameraGeom.CameraSysPrefix(sysName)
                cameraPoint2 = dw.detector.makeCameraPoint(point, cameraSysPrefix)
                predCameraSys2 = cameraGeom.CameraSys(sysName, dw.name)
                self.assertEquals(cameraPoint2.getPoint(), point)
                self.assertEquals(cameraPoint2.getCameraSys(), predCameraSys2)
Example #15
0
 def _growPsf(exp, extraPix=(2, 3)):
     bbox = exp.getBBox()
     center = ((bbox.getBeginX() + bbox.getEndX()) // 2.,
               (bbox.getBeginY() + bbox.getEndY()) // 2.)
     center = afwGeom.Point2D(center[0], center[1])
     kern = exp.getPsf().computeKernelImage(center).convertF()
     kernSize = kern.getDimensions()
     paddedKern = afwImage.ImageF(kernSize[0] + extraPix[0],
                                  kernSize[1] + extraPix[1])
     bboxToPlace = afwGeom.Box2I(
         afwGeom.Point2I(
             (kernSize[0] + extraPix[0] - kern.getWidth()) // 2,
             (kernSize[1] + extraPix[1] - kern.getHeight()) // 2),
         kern.getDimensions())
     paddedKern.assign(kern, bboxToPlace)
     fixedKern = afwMath.FixedKernel(paddedKern.convertD())
     psfNew = measAlg.KernelPsf(fixedKern, center)
     exp.setPsf(psfNew)
     return exp
Example #16
0
    def setUp(self):
        '''Create two calibs, one with a valid zero-point and one without. Use these to create two UnitSystem
        objects.
        '''
        self.mag2Flux = lambda m: 10.0**(m / 2.5)
        self.flux2Mag = lambda f: 2.5 * np.log10(f)

        calibNoZero = afwImage.Calib()
        calibWithZero = afwImage.Calib()
        calibWithZero.setFluxMag0(self.mag2Flux(25))

        scale = 0.2 * afwGeom.arcseconds
        wcs = afwGeom.makeSkyWcs(crpix=afwGeom.Point2D(),
                                 crval=afwGeom.SpherePoint(
                                     45.0, 45.0, afwGeom.degrees),
                                 cdMatrix=afwGeom.makeCdMatrix(scale=scale))

        self.unitNoZero = measModel.UnitSystem(wcs, calibNoZero)
        self.unitWithZero = measModel.UnitSystem(wcs, calibWithZero)
Example #17
0
    def testCatFluxUnchanged(self):
        # Pick arbitrary but unique values for the test case
        source_test_flux = 5.3
        source_test_centroid = afwGeom.Point2D(5, 7.1)
        sourceCat = initializeSourceCatalog(schema=self.schema, name=self.name, flux=source_test_flux,
                                            sigma=0, centroid=source_test_centroid)
        fluxName = self.name + "_flux"
        fluxSigmaName = self.name + "_fluxSigma"
        fluxKey = self.schema.find(fluxName).key

        apCorrMap = afwImage.ApCorrMap()
        bbox = afwGeom.Box2I(afwGeom.Point2I(0, 0), afwGeom.ExtentI(10, 10))
        coefficients = numpy.ones((1, 1), dtype=float)
        coefficients_sigma = numpy.zeros((1, 1), dtype=float)
        apCorrMap[fluxName] = ChebyshevBoundedField(bbox, coefficients)
        apCorrMap[fluxSigmaName] = ChebyshevBoundedField(bbox, coefficients_sigma)
        self.ap_corr_task.run(sourceCat, apCorrMap)

        self.assertEqual(sourceCat[fluxKey], source_test_flux)
 def compare2DFunctions(self,
                        func1,
                        func2,
                        minVal=-10,
                        maxVal=None,
                        nVal=5):
     """Compare two functions(Point2D) -> Point2D over a range of values
     """
     if maxVal is None:
         maxVal = -minVal
     dVal = (maxVal - minVal) / (nVal - 1)
     for xInd in range(nVal):
         x = minVal + (xInd * dVal)
         for yInd in range(nVal):
             y = minVal + (yInd * dVal)
             fromPoint = afwGeom.Point2D(x, y)
             res1 = func1(fromPoint)
             res2 = func2(fromPoint)
             self.assertPairsAlmostEqual(res1, res2)
    def setUp(self):
        '''Create two calibs, one with a valid zero-point and one without. Use these to create two UnitSystem
        objects.
        '''
        self.mag2Flux = lambda m: 10.0**(m / 2.5)
        self.flux2Mag = lambda f: 2.5 * np.log10(f)

        calibNoZero = afwImage.Calib()
        calibWithZero = afwImage.Calib()
        calibWithZero.setFluxMag0(self.mag2Flux(25))

        cdelt = (0.2 * afwGeom.arcseconds).asDegrees()
        position = afwCoord.IcrsCoord(45.0 * afwGeom.degrees,
                                      45.0 * afwGeom.degrees)
        wcs = afwImage.makeWcs(position, afwGeom.Point2D(), cdelt, 0.0, 0.0,
                               cdelt)

        self.unitNoZero = measModel.UnitSystem(wcs, calibNoZero)
        self.unitWithZero = measModel.UnitSystem(wcs, calibWithZero)
Example #20
0
    def _makePsfMaskedImage(self, psfModel, posX, posY, dimensions=None):
        """! Return a MaskedImage of the a PSF Model of specified dimensions
        """
        rawKernel = psfModel.computeKernelImage(afwGeom.Point2D(posX, posY)).convertF()
        if dimensions is None:
            dimensions = rawKernel.getDimensions()
        if rawKernel.getDimensions() == dimensions:
            kernelIm = rawKernel
        else:
            # make image of proper size
            kernelIm = afwImage.ImageF(dimensions)
            bboxToPlace = afwGeom.Box2I(afwGeom.Point2I((dimensions.getX() - rawKernel.getWidth())//2,
                                                        (dimensions.getY() - rawKernel.getHeight())//2),
                                        rawKernel.getDimensions())
            kernelIm.assign(rawKernel, bboxToPlace)

        kernelMask = afwImage.Mask(dimensions, 0x0)
        kernelVar = afwImage.ImageF(dimensions, 1.0)
        return afwImage.MaskedImageF(kernelIm, kernelMask, kernelVar)
Example #21
0
def computeWarpedBBox(destWcs, srcBBox, srcWcs):
    """Compute the bounding box of a warped image

    The bounding box includes all warped pixels and it may be a bit oversize.

    @param destWcs: WCS of warped exposure
    @param srcBBox: parent bounding box of unwarped image
    @param srcWcs: WCS of unwarped image

    @return destBBox: bounding box of warped exposure
    """
    srcPosBox = afwGeom.Box2D(srcBBox)
    destPosBox = afwGeom.Box2D()
    for inX in (srcPosBox.getMinX(), srcPosBox.getMaxX()):
        for inY in (srcPosBox.getMinY(), srcPosBox.getMaxY()):
            destPos = destWcs.skyToPixel(srcWcs.pixelToSky(afwGeom.Point2D(inX, inY)))
            destPosBox.include(destPos)
    destBBox = afwGeom.Box2I(destPosBox, afwGeom.Box2I.EXPAND)
    return destBBox
Example #22
0
 def testTablePersistence(self):
     ellipse = afwGeomEllipses.Ellipse(afwGeomEllipses.Axes(8, 6, 0.25),
                                       afwGeom.Point2D(9, 15))
     fp1 = afwDetect.Footprint(ellipse)
     fp1.addPeak(6, 7, 2)
     fp1.addPeak(8, 9, 3)
     with lsst.utils.tests.getTempFilePath(".fits") as tmpFile:
         fp1.writeFits(tmpFile)
         fp2 = afwDetect.Footprint.readFits(tmpFile)
         self.assertEqual(fp1.getArea(), fp2.getArea())
         self.assertEqual(list(fp1.getSpans()), list(fp2.getSpans()))
         # can't use Peak operator== for comparison because it compares IDs, not positions/values
         self.assertEqual(len(fp1.getPeaks()), len(fp2.getPeaks()))
         for peak1, peak2 in zip(fp1.getPeaks(), fp2.getPeaks()):
             self.assertEqual(peak1.getIx(), peak2.getIx())
             self.assertEqual(peak1.getIy(), peak2.getIy())
             self.assertEqual(peak1.getFx(), peak2.getFx())
             self.assertEqual(peak1.getFy(), peak2.getFy())
             self.assertEqual(peak1.getPeakValue(), peak2.getPeakValue())
    def setUp(self):
        # We create an image that has a ramp (unique values for each pixel),
        # with a single high pixel that allows for centering
        self.width, self.height = 50, 50
        self.xcen, self.ycen = self.width // 2, self.height // 2
        self.image = afwImage.ImageF(afwGeom.ExtentI(self.width, self.height))
        for y in range(self.height):
            for x in range(self.width):
                self.image.set(x, y, self.width * y + x)
        self.image.set(self.xcen, self.ycen, 1234567.89)
        self.exp = afwImage.makeExposure(afwImage.makeMaskedImage(self.image))
        self.exp.getMaskedImage().getVariance().set(1.0)
        scale = 0.2 / 3600
        wcs = afwImage.makeWcs(
            afwCoord.Coord(0 * afwGeom.degrees, 0 * afwGeom.degrees),
            afwGeom.Point2D(self.xcen, self.ycen), scale, 0, 0, scale)
        self.exp.setWcs(wcs)

        if display:
            frame = 1
            ds9.mtv(self.exp, frame=frame, title="Single pixel")

        # We will use a NaiveCentroid (peak over 3x3) to tweak the center (it should not, for forced
        # measurement) and a NaiveFlux to measure the single pixel.  We'll start offset from the high pixel,
        # so that a forced measurement should yield a flux of zero, while a measurement that was allowed to
        # center should yield a flux of unity.
        naiveCentroid = measAlg.NaiveCentroidControl()
        naiveFlux = measAlg.NaiveFluxControl()
        naiveFlux.radius = 0.5
        self.x, self.y = self.xcen - 1, self.ycen - 1

        self.foot = afwDetection.Footprint(afwGeom.Point2I(self.x, self.y), 2)
        peak = afwDetection.Peak(self.x, self.y)
        self.foot.getPeaks().push_back(peak)

        schema = afwTable.SourceTable.makeMinimalSchema()
        msb = measAlg.MeasureSourcesBuilder()
        msb.addAlgorithm(naiveFlux)
        msb.setCentroider(naiveCentroid)
        self.measurer = msb.build(schema)
        self.table = afwTable.SourceTable.make(schema)
        self.table.defineCentroid("centroid.naive")
Example #24
0
    def testMakeTanSipMetadata(self):
        """Test makeTanSipMetadata
        """
        crpix = afwGeom.Point2D(
            self.metadata.get("CRPIX1") - 1,
            self.metadata.get("CRPIX2") - 1)
        crval = afwGeom.SpherePoint(
            self.metadata.get("CRVAL1") * degrees,
            self.metadata.get("CRVAL2") * degrees)
        cdMatrix = getCdMatrixFromMetadata(self.metadata)
        sipA = getSipMatrixFromMetadata(self.metadata, "A")
        sipB = getSipMatrixFromMetadata(self.metadata, "B")
        sipAp = getSipMatrixFromMetadata(self.metadata, "AP")
        sipBp = getSipMatrixFromMetadata(self.metadata, "BP")
        forwardMetadata = makeTanSipMetadata(
            crpix=crpix,
            crval=crval,
            cdMatrix=cdMatrix,
            sipA=sipA,
            sipB=sipB,
        )
        self.assertFalse(forwardMetadata.exists("AP_ORDER"))
        self.assertFalse(forwardMetadata.exists("BP_ORDER"))

        fullMetadata = makeTanSipMetadata(
            crpix=crpix,
            crval=crval,
            cdMatrix=cdMatrix,
            sipA=sipA,
            sipB=sipB,
            sipAp=sipAp,
            sipBp=sipBp,
        )
        for cardName in ("CRPIX1", "CRPIX2", "CRVAL1", "CRVAL2", "CTYPE1",
                         "CTYPE2", "CUNIT1", "CUNIT2", "RADESYS"):
            self.assertTrue(forwardMetadata.exists(cardName))
            self.assertTrue(fullMetadata.exists(cardName))
        for name, matrix in (("A", sipA), ("B", sipB)):
            self.checkSipMetadata(name, matrix, forwardMetadata)
            self.checkSipMetadata(name, matrix, fullMetadata)
        for name, matrix in (("AP", sipAp), ("BP", sipBp)):
            self.checkSipMetadata(name, matrix, fullMetadata)
    def loadData(self, rangePix=3000, numPoints=25):
        """Load catalogs and make the match list

        This is a separate function so data can be reloaded if fitting more than once
        (each time a WCS is fit it may update the source catalog, reference catalog and match list)
        """
        if self.MatchClass == afwTable.ReferenceMatch:
            refSchema = LoadReferenceObjectsTask.makeMinimalSchema(
                filterNameList=["r"], addFluxSigma=True, addIsPhotometric=True)
            self.refCat = afwTable.SimpleCatalog(refSchema)
        elif self.MatchClass == afwTable.SourceMatch:
            refSchema = afwTable.SourceTable.makeMinimalSchema()
            self.refCat = afwTable.SourceCatalog(refSchema)
        else:
            raise RuntimeError("Unsupported MatchClass=%r" % (self.MatchClass,))
        srcSchema = afwTable.SourceTable.makeMinimalSchema()
        SingleFrameMeasurementTask(schema=srcSchema)
        self.srcCoordKey = afwTable.CoordKey(srcSchema["coord"])
        self.srcCentroidKey = afwTable.Point2DKey(srcSchema["slot_Centroid"])
        self.srcCentroidKey_xSigma = srcSchema["slot_Centroid_xSigma"].asKey()
        self.srcCentroidKey_ySigma = srcSchema["slot_Centroid_ySigma"].asKey()
        self.sourceCat = afwTable.SourceCatalog(srcSchema)

        self.matches = []

        for i in np.linspace(0., rangePix, numPoints):
            for j in np.linspace(0., rangePix, numPoints):
                src = self.sourceCat.addNew()
                refObj = self.refCat.addNew()

                src.set(self.srcCentroidKey, afwGeom.Point2D(i, j))
                src.set(self.srcCentroidKey_xSigma, 0.1)
                src.set(self.srcCentroidKey_ySigma, 0.1)

                c = self.tanWcs.pixelToSky(i, j)
                refObj.setCoord(c)

                if False:
                    print("x,y = (%.1f, %.1f) pixels -- RA,Dec = (%.3f, %.3f) deg" %
                          (i, j, c.toFk5().getRa().asDegrees(), c.toFk5().getDec().asDegrees()))

                self.matches.append(self.MatchClass(refObj, src, 0.0))
Example #26
0
    def makeLsstExposure(galData, psfData, pixScale, variance):
        """
        make an LSST exposure object

        Parameters:
            galData (ndarray):  array of galaxy image
            psfData (ndarray):  array of PSF image
            pixScale (float):   pixel scale
            variance (float):   noise variance

        Returns:
            exposure:   LSST exposure object
        """
        if not with_lsst:
            raise ImportError('Do not have lsstpipe!')
        ny, nx = galData.shape
        exposure = afwImg.ExposureF(nx, ny)
        exposure.getMaskedImage().getImage().getArray()[:, :] = galData
        exposure.getMaskedImage().getVariance().getArray()[:, :] = variance
        #Set the PSF
        ngridPsf = psfData.shape[0]
        psfLsst = afwImg.ImageF(ngridPsf, ngridPsf)
        psfLsst.getArray()[:, :] = psfData
        psfLsst = psfLsst.convertD()
        kernel = afwMath.FixedKernel(psfLsst)
        kernelPSF = meaAlg.KernelPsf(kernel)
        exposure.setPsf(kernelPSF)
        #prepare the wcs
        #Rotation
        cdelt = (pixScale * afwGeom.arcseconds)
        CD = afwGeom.makeCdMatrix(cdelt, afwGeom.Angle(0.))  #no rotation
        #wcs
        crval = afwGeom.SpherePoint(afwGeom.Angle(0., afwGeom.degrees),
                                    afwGeom.Angle(0., afwGeom.degrees))
        #crval   =   afwCoord.IcrsCoord(0.*afwGeom.degrees, 0.*afwGeom.degrees) # hscpipe6
        crpix = afwGeom.Point2D(0.0, 0.0)
        dataWcs = afwGeom.makeSkyWcs(crpix, crval, CD)
        exposure.setWcs(dataWcs)
        #prepare the frc
        dataCalib = afwImg.makePhotoCalibFromCalibZeroPoint(63095734448.0194)
        exposure.setPhotoCalib(dataCalib)
        return exposure
Example #27
0
    def setUp(self):
        metadata = dafBase.PropertySet()

        self.crPix = afwGeom.Point2D(15000, 4000)
        dimd = afwGeom.Extent2D(4000, 4000)
        bboxd = afwGeom.Box2D(self.crPix - dimd / 2, dimd)
        self.bbox = afwGeom.Box2I(bboxd)
        metadata.set("RADECSYS", 'ICRS')
        metadata.set("EQUINOX", 2000.0)
        metadata.setDouble("CRVAL1", 215.60)
        metadata.setDouble("CRVAL2", 53.16)
        metadata.setDouble("CRPIX1", self.crPix[0])
        metadata.setDouble("CRPIX2", self.crPix[1])
        metadata.set("CTYPE1", "RA---TAN")
        metadata.set("CTYPE2", "DEC--TAN")
        metadata.setDouble("CD1_1", 5.10808596133527E-05)
        metadata.setDouble("CD1_2", 1.85579539217196E-07)
        metadata.setDouble("CD2_2", -5.10281493481982E-05)
        metadata.setDouble("CD2_1", -8.27440751733828E-07)
        self.tanWcs = afwImage.makeWcs(metadata)
    def initialWcs(self, matches, wcs):
        """Generate a guess Wcs from the astrometric matches

        We create a Wcs anchored at the center of the matches, with the scale
        of the input Wcs.  This is necessary because matching returns only
        matches with no estimated Wcs, and the input Wcs is a wild guess.
        We're using the best of each: positions from the matches, and scale
        from the input Wcs.
        """
        crpix = afwGeom.Extent2D(0, 0)
        crval = lsst.sphgeom.Vector3d(0, 0, 0)
        for mm in matches:
            crpix += afwGeom.Extent2D(mm.second.getCentroid())
            crval += mm.first.getCoord().getVector()
        crpix /= len(matches)
        crval /= len(matches)
        newWcs = afwGeom.makeSkyWcs(crpix=afwGeom.Point2D(crpix),
                                    crval=afwGeom.SpherePoint(crval),
                                    cdMatrix=wcs.getCdMatrix())
        return newWcs
    def testNaiveMeasure(self):
        mi = afwImage.MaskedImageF(afwGeom.ExtentI(100, 200))
        mi.set(10)
        #
        # Create our measuring engine
        #
        exp = afwImage.makeExposure(mi)
        x0, y0 = 1234, 5678
        exp.setXY0(afwGeom.Point2I(x0, y0))

        control = measAlg.NaiveFluxControl()
        control.radius = 10.0
        schema = afwTable.SourceTable.makeMinimalSchema()
        mp = measAlg.MeasureSourcesBuilder().addAlgorithm(control).build(
            schema)
        table = afwTable.SourceTable.make(schema)
        source = table.makeRecord()
        mp.apply(source, exp, afwGeom.Point2D(30 + x0, 50 + y0))
        flux = 3170.0
        self.assertEqual(source.get(control.name), flux)
def makeWcs(ctr_coord,
            ctr_pix=afwGeom.Point2D(2036., 2000.),
            pixel_scale=2 * afwGeom.arcseconds,
            pos_angle=afwGeom.Angle(0.0)):
    """Make a simple TAN WCS

    @param[in] ctr_coord  sky coordinate at ctr_pix
    @param[in] ctr_pix  center pixel; an lsst.afw.geom.Point2D; default matches LSST
    @param[in] pixel_scale  desired scale, as sky/pixel; an lsst.afw.geom.Angle; default matches LSST
    @param[in] pos_angle  orientation of CCD w.r.t. ctr_coord, an lsst.afw.geom.Angle
    """
    pos_angleRad = pos_angle.asRadians()
    pixel_scaleDeg = pixel_scale.asDegrees()
    cdMat = np.array([[math.cos(pos_angleRad),
                       math.sin(pos_angleRad)],
                      [-math.sin(pos_angleRad),
                       math.cos(pos_angleRad)]],
                     dtype=float) * pixel_scaleDeg
    return lsst.afw.image.makeWcs(ctr_coord, ctr_pix, cdMat[0, 0], cdMat[0, 1],
                                  cdMat[1, 0], cdMat[1, 1])