Example #1
0
    def testDetectorTime(self):
        """Test that we can ask a calib for the MidTime at a point in a detector (ticket #1337)"""

        import lsst.afw.geom as afwGeom
        import lsst.afw.cameraGeom as cameraGeom

        det = cameraGeom.Detector(cameraGeom.Id(1))

        p = afwGeom.PointI(3, 4)
        self.calib.getMidTime(det, p)
    def makeDetector(self,
                     bbox=None,
                     numAmps=None,
                     rowInds=None,
                     colIndOffsets=None,
                     detName="det_a",
                     detSerial="123",
                     linearityType="LookupTable"):
        """!Make a detector

        @param[in] bbox  bounding box for image
        @param[n] numAmps  x,y number of amplifiers (pair of int)
        @param[in] rowInds  index of lookup table for each amplifier (array of shape numAmps)
        @param[in] colIndOffsets  column index offset for each amplifier (array of shape numAmps)
        @param[in] detName  detector name (a str)
        @param[in] detSerial  detector serial numbe (a str)
        @param[in] linearityType  name of linearity type (a str)

        @return a detector (an lsst.afw.cameraGeom.Detector)
        """
        bbox = bbox if bbox is not None else self.bbox
        numAmps = numAmps if numAmps is not None else self.numAmps
        rowInds = rowInds if rowInds is not None else self.rowInds
        colIndOffsets = colIndOffsets if colIndOffsets is not None else self.colIndOffsets

        schema = afwTable.AmpInfoTable.makeMinimalSchema()
        ampInfoCat = afwTable.AmpInfoCatalog(schema)
        boxArr = BoxGrid(box=bbox, numColRow=numAmps)
        for i in range(numAmps[0]):
            for j in range(numAmps[1]):
                ampInfo = ampInfoCat.addNew()
                ampInfo.setName("amp %d_%d" % (i + 1, j + 1))
                ampInfo.setBBox(boxArr[i, j])
                ampInfo.setLinearityType(linearityType)
                # setLinearityCoeffs is picky about getting a mixed int/float list.
                ampInfo.setLinearityCoeffs(
                    np.array([rowInds[i, j], colIndOffsets[i, j], 0, 0],
                             dtype=float))
        detId = 1
        orientation = cameraGeom.Orientation()
        pixelSize = afwGeom.Extent2D(1, 1)
        transMap = {}
        return cameraGeom.Detector(
            detName,
            detId,
            cameraGeom.SCIENCE,
            detSerial,
            bbox,
            ampInfoCat,
            orientation,
            pixelSize,
            transMap,
        )
Example #3
0
    def testCopyExposure(self):
        """Copy an Exposure (maybe changing type)"""

        exposureU = afwImage.ExposureU(inFilePathSmall)
        exposureU.setWcs(self.wcs)
        exposureU.setDetector(cameraGeom.Detector(cameraGeom.Id(666)))
        exposureU.setFilter(afwImage.Filter("g"))
        exposureU.getCalib().setExptime(666)
        exposureU.setPsf(DummyPsf(4.0))

        exposureF = exposureU.convertF()
        self.cmpExposure(exposureF, exposureU)

        nexp = exposureF.Factory(exposureF, False)
        self.cmpExposure(exposureF, nexp)
Example #4
0
    def makeDetector(self,
                     bbox=None,
                     numAmps=None,
                     sqCoeffs=None,
                     linearityType="Squared"):
        """!Make a detector

        @param[in] bbox  bounding box for image
        @param[n] numAmps  x,y number of amplifiers (pair of int)
        @param[in] sqCoeffs  square coefficient for each amplifier (2D array of float)
        @param[in] detName  detector name (a str)
        @param[in] detID  detector ID (an int)
        @param[in] detSerial  detector serial numbe (a str)
        @param[in] linearityType  name of linearity type (a str)

        @return a detector (an lsst.afw.cameraGeom.Detector)
        """
        bbox = bbox if bbox is not None else self.bbox
        numAmps = numAmps if numAmps is not None else self.numAmps
        sqCoeffs = sqCoeffs if sqCoeffs is not None else self.sqCoeffs
        schema = afwTable.AmpInfoTable.makeMinimalSchema()
        ampInfoCat = afwTable.AmpInfoCatalog(schema)
        boxArr = BoxGrid(box=bbox, numColRow=numAmps)
        for i in range(numAmps[0]):
            for j in range(numAmps[1]):
                ampInfo = ampInfoCat.addNew()
                ampInfo.setName("amp %d_%d" % (i + 1, j + 1))
                ampInfo.setBBox(boxArr[i, j])
                ampInfo.setLinearityType(linearityType)
                ampInfo.setLinearityCoeffs([sqCoeffs[i, j]])
        detName = "det_a"
        detId = 1
        detSerial = "123"
        orientation = cameraGeom.Orientation()
        pixelSize = afwGeom.Extent2D(1, 1)
        transMap = {}
        return cameraGeom.Detector(
            detName,
            detId,
            cameraGeom.SCIENCE,
            detSerial,
            bbox,
            ampInfoCat,
            orientation,
            pixelSize,
            transMap,
        )
Example #5
0
    def testSetMembers(self):
        """
        Test that the MaskedImage and the WCS of an Exposure can be set.
        """
        exposure = afwImage.ExposureF()

        maskedImage = afwImage.MaskedImageF(inFilePathSmall)
        exposure.setMaskedImage(maskedImage)
        exposure.setWcs(self.wcs)
        exposure.setDetector(cameraGeom.Detector(cameraGeom.Id(666)))
        exposure.setFilter(afwImage.Filter("g"))

        self.assertEquals(exposure.getDetector().getId().getSerial(), 666)
        self.assertEquals(exposure.getFilter().getName(), "g")

        try:
            exposure.getWcs()
        except pexExcept.LsstCppException, e:
            print "caught expected exception (getWcs): %s" % e
            pass
Example #6
0
    def testReadWriteFits(self):
        """Test readFits and writeFits.
        """
        # This should pass without an exception
        mainExposure = afwImage.ExposureF(inFilePathSmall)
        mainExposure.setDetector(cameraGeom.Detector(cameraGeom.Id(666)))

        subBBox = afwGeom.Box2I(afwGeom.Point2I(10, 10),
                                afwGeom.Extent2I(40, 50))
        subExposure = mainExposure.Factory(mainExposure, subBBox,
                                           afwImage.LOCAL)
        self.checkWcs(mainExposure, subExposure)
        det = subExposure.getDetector()
        self.assertTrue(det)

        subExposure = afwImage.ExposureF(inFilePathSmall, subBBox)

        self.checkWcs(mainExposure, subExposure)

        # This should throw an exception
        def getExposure():
            afwImage.ExposureF(inFilePathSmallImage)

        utilsTests.assertRaisesLsstCpp(self, lsst.afw.fits.FitsError,
                                       getExposure)

        mainExposure.setPsf(self.psf)

        # Make sure we can write without an exception
        mainExposure.getCalib().setExptime(10)
        mainExposure.getCalib().setMidTime(dafBase.DateTime())
        midMjd = mainExposure.getCalib().getMidTime().get()
        fluxMag0, fluxMag0Err = 1e12, 1e10
        mainExposure.getCalib().setFluxMag0(fluxMag0, fluxMag0Err)

        mainExposure.writeFits(outFile)

        # Check scaling of Calib
        scale = 2.0
        calib = mainExposure.getCalib()
        calib *= scale
        self.assertEqual((fluxMag0 * scale, fluxMag0Err * scale),
                         calib.getFluxMag0())
        calib /= scale
        self.assertEqual((fluxMag0, fluxMag0Err), calib.getFluxMag0())

        readExposure = type(mainExposure)(outFile)

        os.remove(outFile)
        #
        # Check the round-tripping
        #
        self.assertEqual(mainExposure.getFilter().getName(),
                         readExposure.getFilter().getName())

        self.assertEqual(mainExposure.getCalib().getExptime(),
                         readExposure.getCalib().getExptime())
        self.assertEqual(midMjd, readExposure.getCalib().getMidTime().get())
        self.assertEqual((fluxMag0, fluxMag0Err),
                         readExposure.getCalib().getFluxMag0())

        psf = readExposure.getPsf()
        self.assert_(psf is not None)
        dummyPsf = DummyPsf.swigConvert(psf)
        self.assert_(dummyPsf is not None)
        self.assertEqual(dummyPsf.getValue(), self.psf.getValue())
    def setUp(self):
        width, height = 110, 301

        self.mi = afwImage.MaskedImageF(afwGeom.ExtentI(width, height))
        self.mi.set(0)
        sd = 3                          # standard deviation of image
        self.mi.getVariance().set(sd*sd)
        self.mi.getMask().addMaskPlane("DETECTED")

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

        sigma1 = 1.75
        sigma2 = 2*sigma1

        self.exposure = afwImage.makeExposure(self.mi)
        self.exposure.setPsf(measAlg.DoubleGaussianPsf(self.ksize, self.ksize,
                                                    1.5*sigma1, 1, 0.1))
        self.exposure.setDetector(cameraGeom.Detector(cameraGeom.Id(1), False, 1.0))
        self.exposure.getDetector().setDistortion(None) #cameraGeom.NullDistortion())
        
        #
        # Make a kernel with the exactly correct basis functions.  Useful for debugging
        #
        basisKernelList = afwMath.KernelList()
        for sigma in (sigma1, sigma2):
            basisKernel = afwMath.AnalyticKernel(self.ksize, self.ksize,
                                                 afwMath.GaussianFunction2D(sigma, sigma))
            basisImage = afwImage.ImageD(basisKernel.getDimensions())
            basisKernel.computeImage(basisImage, True)
            basisImage /= numpy.sum(basisImage.getArray())

            if sigma == sigma1:
                basisImage0 = basisImage
            else:
                basisImage -= basisImage0

            basisKernelList.append(afwMath.FixedKernel(basisImage))

        order = 1                                # 1 => up to linear
        spFunc = afwMath.PolynomialFunction2D(order)

        exactKernel = afwMath.LinearCombinationKernel(basisKernelList, spFunc)
        exactKernel.setSpatialParameters([[1.0, 0,          0],
                                          [0.0, 0.5*1e-2, 0.2e-2]])
        self.exactPsf = measAlg.PcaPsf(exactKernel)        

        rand = afwMath.Random()               # make these tests repeatable by setting seed

        addNoise = True

        if addNoise:
            im = self.mi.getImage()
            afwMath.randomGaussianImage(im, rand) # N(0, 1)
            im *= sd                              # N(0, sd^2)
            del im

        xarr, yarr = [], []

        for x, y in [(20, 20), (60, 20), 
                     (30, 35),
                     (50, 50),
                     (20, 90), (70, 160), (25, 265), (75, 275), (85, 30),
                     (50, 120), (70, 80),
                     (60, 210), (20, 210),
                     ]:
            xarr.append(x)
            yarr.append(y)

        for x, y in zip(xarr, yarr):
            dx = rand.uniform() - 0.5   # random (centered) offsets
            dy = rand.uniform() - 0.5

            k = exactKernel.getSpatialFunction(1)(x, y) # functional variation of Kernel ...
            b = (k*sigma1**2/((1 - k)*sigma2**2))       # ... converted double Gaussian's "b"

            #flux = 80000 - 20*x - 10*(y/float(height))**2
            flux = 80000*(1 + 0.1*(rand.uniform() - 0.5))
            I0 = flux*(1 + b)/(2*numpy.pi*(sigma1**2 + b*sigma2**2))
            for iy in range(y - self.ksize//2, y + self.ksize//2 + 1):
                if iy < 0 or iy >= self.mi.getHeight():
                    continue

                for ix in range(x - self.ksize//2, x + self.ksize//2 + 1):
                    if ix < 0 or ix >= self.mi.getWidth():
                        continue

                    I = I0*psfVal(ix, iy, x + dx, y + dy, sigma1, sigma2, b)
                    Isample = rand.poisson(I) if addNoise else I
                    self.mi.getImage().set(ix, iy, self.mi.getImage().get(ix, iy) + Isample)
                    self.mi.getVariance().set(ix, iy, self.mi.getVariance().get(ix, iy) + I)
        # 
        bbox = afwGeom.BoxI(afwGeom.PointI(0,0), afwGeom.ExtentI(width, height))
        self.cellSet = afwMath.SpatialCellSet(bbox, 100)

        self.footprintSet = afwDetection.FootprintSet(self.mi, afwDetection.Threshold(100), "DETECTED")

        self.catalog = SpatialModelPsfTestCase.measure(self.footprintSet, self.exposure)

        for source in self.catalog:
            try:
                cand = measAlg.makePsfCandidate(source, self.exposure)
                self.cellSet.insertCandidate(cand)

            except Exception, e:
                print e
                continue