Exemple #1
0
    def testAddTrimmedAmp(self):
        """Test that building a Ccd from trimmed Amps leads to a trimmed Ccd"""

        dataSec = afwGeom.BoxI(afwGeom.PointI(1, 0), afwGeom.ExtentI(10, 20))
        biasSec = afwGeom.BoxI(afwGeom.PointI(0, 0), afwGeom.ExtentI(1, 1))
        allPixelsInAmp = afwGeom.BoxI(afwGeom.PointI(0, 0), afwGeom.ExtentI(11, 21))
        eParams = cameraGeom.ElectronicParams(1.0, 1.0, 65000)

        ccd = cameraGeom.Ccd(cameraGeom.Id(0))
        self.assertFalse(ccd.isTrimmed())

        for i in range(2):
            amp = cameraGeom.Amp(cameraGeom.Id(i, "", i, 0),
                                 allPixelsInAmp, biasSec, dataSec, eParams)
            amp.setTrimmed(True)

            if i%2 == 0:                # check both APIs
                ccd.addAmp(afwGeom.PointI(i, 0), amp)
            else:
                ccd.addAmp(amp)
            self.assertTrue(ccd.isTrimmed())

        # should fail to add non-trimmed Amp to a trimmed Ccd
        i += 1
        amp = cameraGeom.Amp(cameraGeom.Id(i, "", i, 0),
                             allPixelsInAmp, biasSec, dataSec, eParams)
        self.assertFalse(amp.isTrimmed())

        utilsTests.assertRaisesLsstCpp(self, pexExcept.InvalidParameterException, ccd.addAmp, amp)

        # should fail to add trimmed Amp to a non-trimmed Ccd
        ccd.setTrimmed(False)
        amp.setTrimmed(True)
        utilsTests.assertRaisesLsstCpp(self, pexExcept.InvalidParameterException, ccd.addAmp, amp)
def makeTest2(doAddNoise, shiftX=5, shiftY=3):
    gaussian1 = afwMath.GaussianFunction2D(1., 1., 0.)
    kernel1 = afwMath.AnalyticKernel(imSize, imSize, gaussian1)
    image1 = afwImage.ImageD(kernel1.getDimensions())
    kernel1.computeImage(image1, False)
    image1 *= 10000
    image1 = image1.convertF()
    ####
    boxA = afwGeom.Box2I(afwGeom.PointI(imSize // 2, imSize // 2),
                         afwGeom.ExtentI(imSize // 2, imSize // 2))
    boxB = afwGeom.Box2I(
        afwGeom.PointI(imSize // 2 - shiftX, imSize // 2 - shiftY),
        afwGeom.ExtentI(imSize // 2, imSize // 2))
    subregA = afwImage.ImageF(image1, boxA, afwImage.PARENT)
    subregB = afwImage.ImageF(image1, boxB, afwImage.PARENT, True)
    subregA += subregB
    ###
    mask1 = afwImage.MaskU(kernel1.getDimensions())
    var1 = afwImage.ImageF(image1, True)
    mi1 = afwImage.MaskedImageF(image1, mask1, var1)
    if doAddNoise: addNoise(mi1)

    gaussian2 = afwMath.GaussianFunction2D(2., 1.5, 0.5 * num.pi)
    kernel2 = afwMath.AnalyticKernel(imSize, imSize, gaussian2)
    image2 = afwImage.ImageD(kernel2.getDimensions())
    kernel2.computeImage(image2, False)
    image2 *= 10000
    image2 = image2.convertF()
    mask2 = afwImage.MaskU(kernel2.getDimensions())
    var2 = afwImage.ImageF(image2, True)
    mi2 = afwImage.MaskedImageF(image2, mask2, var2)
    if doAddNoise: addNoise(mi2)

    return mi1, mi2
Exemple #3
0
def showPsfResiduals(exposure,
                     sourceSet,
                     magType="psf",
                     scale=10,
                     frame=None,
                     showAmps=False):
    mimIn = exposure.getMaskedImage()
    mimIn = mimIn.Factory(mimIn, True)  # make a copy to subtract from

    psf = exposure.getPsf()
    psfWidth, psfHeight = psf.getLocalKernel().getDimensions()
    #
    # Make the image that we'll paste our residuals into.  N.b. they can overlap the edges
    #
    w, h = int(mimIn.getWidth() / scale), int(mimIn.getHeight() / scale)

    im = mimIn.Factory(w + psfWidth, h + psfHeight)

    cenPos = []
    for s in sourceSet:
        x, y = s.getX(), s.getY()

        sx, sy = int(x / scale + 0.5), int(y / scale + 0.5)

        smim = im.Factory(
            im,
            afwGeom.BoxI(afwGeom.PointI(sx, sy),
                         afwGeom.ExtentI(psfWidth, psfHeight)),
            afwImage.PARENT)
        sim = smim.getImage()

        try:
            if magType == "ap":
                flux = s.getApFlux()
            elif magType == "model":
                flux = s.getModelFlux()
            elif magType == "psf":
                flux = s.getPsfFlux()
            else:
                raise RuntimeError("Unknown flux type %s" % magType)

            algorithmsLib.subtractPsf(psf, mimIn, x, y, flux)
        except Exception, e:
            print e

        try:
            expIm = mimIn.getImage().Factory(
                mimIn.getImage(),
                afwGeom.BoxI(
                    afwGeom.PointI(
                        int(x) - psfWidth // 2,
                        int(y) - psfHeight // 2),
                    afwGeom.ExtentI(psfWidth, psfHeight)), afwImage.PARENT)
        except pexExcept.LsstCppException:
            continue

        cenPos.append([x - expIm.getX0() + sx, y - expIm.getY0() + sy])

        sim += expIm
Exemple #4
0
def subtractXTalk(mi, coeffs, minPixelToMask=45000, crosstalkStr="CROSSTALK"):
    """Subtract the crosstalk from MaskedImage mi given a set of coefficients

The pixels affected by signal over minPixelToMask have the crosstalkStr bit set
    """
    sctrl = afwMath.StatisticsControl()
    sctrl.setAndMask(mi.getMask().getPlaneBitMask("DETECTED"))
    bkgd = afwMath.makeStatistics(mi, afwMath.MEDIAN, sctrl).getValue()
    #
    # These are the pixels that are bright enough to cause crosstalk (more precisely,
    # the ones that we label as causing crosstalk; in reality all pixels cause crosstalk)
    #
    tempStr = "TEMP"                    # mask plane used to record the bright pixels that we need to mask
    mi.getMask().addMaskPlane(tempStr)
    try:
        fs = afwDetect.FootprintSet(mi, afwDetect.Threshold(minPixelToMask), tempStr)

        mi.getMask().addMaskPlane(crosstalkStr)
        afwDisplay.getDisplay().setMaskPlaneColor(crosstalkStr, afwDisplay.MAGENTA)
        fs.setMask(mi.getMask(), crosstalkStr) # the crosstalkStr bit will now be set whenever
                                               # we subtract crosstalk
        crosstalk = mi.getMask().getPlaneBitMask(crosstalkStr)

        width, height = mi.getDimensions()
        for i in range(nAmp):
            bbox = afwGeom.BoxI(afwGeom.PointI(i*(width//nAmp), 0), afwGeom.ExtentI(width//nAmp, height))
            ampI = mi.Factory(mi, bbox)
            for j in range(nAmp):
                if i == j:
                    continue

                bbox = afwGeom.BoxI(afwGeom.PointI(j*(width//nAmp), 0), afwGeom.ExtentI(width//nAmp, height))
                if (i + j)%2 == 1:
                    ampJ = afwMath.flipImage(mi.Factory(mi, bbox), True, False) # no need for a deep copy
                else:
                    ampJ = mi.Factory(mi, bbox, afwImage.LOCAL, True)

                msk = ampJ.getMask()
                if np.all(msk.getArray() & msk.getPlaneBitMask("SAT")):
                    # Bad amplifier; ignore it completely --- its effect will come out in the bias
                    continue
                msk &= crosstalk

                ampJ -= bkgd
                ampJ *= coeffs[j][i]

                ampI -= ampJ
        #
        # Clear the crosstalkStr bit in the original bright pixels, where tempStr is set
        #
        msk = mi.getMask()
        temp = msk.getPlaneBitMask(tempStr)
        xtalk_temp = crosstalk | temp
        np_msk = msk.getArray()
        mask_indicies = np.where(np.bitwise_and(np_msk, xtalk_temp) == xtalk_temp)
        np_msk[mask_indicies] &= getattr(np, np_msk.dtype.name)(~crosstalk)

    finally:
        msk.removeAndClearMaskPlane(tempStr, True) # added in afw #1853
Exemple #5
0
 def testImageSlices(self):
     """Test image slicing, which generate sub-images using Box2I under the covers"""
     exp = afwImage.ExposureF(10, 20)
     mi = exp.getMaskedImage()
     mi[9, 19] = 10
     # N.b. Exposures don't support setting/getting the pixels so can't replicate e.g. Image's slice tests
     sexp = exp[1:4, 6:10]
     self.assertEqual(sexp.getDimensions(), afwGeom.ExtentI(3, 4))
     sexp = exp[..., -3:]
     self.assertEqual(sexp.getDimensions(), afwGeom.ExtentI(exp.getWidth(), 3))
     self.assertEqual(sexp.getMaskedImage().get(sexp.getWidth() - 1, sexp.getHeight() - 1),
                      exp.getMaskedImage().get(exp.getWidth() - 1, exp.getHeight() - 1))
    def run(self, expRef, butler):
        """Make summary plots of full focalplane images.
        """
        sbi = SimButlerImage(butler,
                             type=expRef.butlerSubset.datasetType,
                             visit=expRef.dataId['visit'])

        # Get the per ccd images
        def parse_name_to_dataId(name_str):
            raft, sensor = name_str.split()
            return {'raft': raft[-3:], 'sensor': sensor[-3:]}

        for ccd in butler.get('camera'):
            data_id = parse_name_to_dataId(ccd.getName())
            data_id.update(expRef.dataId)
            try:
                binned_im = sbi.getCcdImage(ccd,
                                            binSize=self.config.sensorBinSize,
                                            as_masked_image=True)[0]
                binned_im = rotateImageBy90(binned_im,
                                            ccd.getOrientation().getNQuarter())
                if self.config.putFullSensors:
                    butler.put(binned_im, 'binned_sensor_fits', **data_id)
            except (TypeError, RuntimeError):
                # butler couldn't put the image or there was no image to put
                continue
            (x, y) = binned_im.getDimensions()
            boxes = {
                'A':
                afwGeom.Box2I(afwGeom.PointI(0, y / 2),
                              afwGeom.ExtentI(x, y / 2)),
                'B':
                afwGeom.Box2I(afwGeom.PointI(0, 0), afwGeom.ExtentI(x, y / 2))
            }
            for half in ('A', 'B'):
                box = boxes[half]
                butler.put(afwImage.MaskedImageF(binned_im, box),
                           'binned_sensor_fits_halves',
                           half=half,
                           **data_id)

        im = cgu.showCamera(butler.get('camera'),
                            imageSource=sbi,
                            binSize=self.config.binSize)
        expRef.put(im, 'focalplane_summary_fits')
        im = flipImage(im, False, True)
        zmap = ZScaleMapping(im, contrast=self.config.contrast)
        rgb = zmap.makeRgbImage(im, im, im)
        file_name = expRef.get('focalplane_summary_png_filename')
        writeRGB(file_name[0], rgb)
Exemple #7
0
    def testLogicalMasksMismatch(self):
        "Test logical operations on Masks of different sizes"
        i1 = afwImage.MaskU(afwGeom.ExtentI(100, 100))
        i1.set(100)
        i2 = afwImage.MaskU(afwGeom.ExtentI(10, 10))
        i2.set(10)

        with self.assertRaises(lsst.pex.exceptions.LengthError):
            i1 |= i2

        with self.assertRaises(lsst.pex.exceptions.LengthError):
            i1 &= i2

        with self.assertRaises(lsst.pex.exceptions.LengthError):
            i1 ^= i2
Exemple #8
0
def makeAmp(i):
    height = 2048
    width = 4096
    allPixels = afwGeom.BoxI(
        afwGeom.PointI(0, 0),
        afwGeom.ExtentI(width + nExtended + nOverclock, height))
    return cameraGeom.Amp(cameraGeom.Id(i), allPixels, None, None, None)
Exemple #9
0
 def _makeBBoxFromList(ylist):
     """Given a list [(x0, y0), (xsize, ysize)], probably from a yaml file,
     return a BoxI
     """
     (x0, y0), (xsize, ysize) = ylist
     return afwGeom.BoxI(afwGeom.PointI(x0, y0),
                         afwGeom.ExtentI(xsize, ysize))
    def testApertureMeasure(self):
        mi = afwImage.MaskedImageF(afwGeom.ExtentI(100, 200))
        mi.set(10)
        #
        # Create our measuring engine
        #

        radii = (1.0, 5.0, 10.0)  # radii to use
        fluxes = [50.0, 810.0, 3170.0]  # corresponding correct fluxes

        control = measAlg.ApertureFluxControl()
        control.radii = radii

        exp = afwImage.makeExposure(mi)
        x0, y0 = 1234, 5678
        exp.setXY0(afwGeom.Point2I(x0, y0))

        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))
        measured = source[control.name]
        for i, f in enumerate(fluxes):
            self.assertEqual(f, measured[i])
Exemple #11
0
    def testCircularApertureMeasure(self):
        mi = afwImage.MaskedImageF(afwGeom.ExtentI(100, 200))
        mi.set(10)
        #
        # Create our measuring engine
        #

        radii = (1.0, 5.0, 10.0)  # radii to use

        control = measBase.ApertureFluxControl()
        control.radii = radii

        exp = afwImage.makeExposure(mi)
        x0, y0 = 1234, 5678
        exp.setXY0(afwGeom.Point2I(x0, y0))

        plugin, cat = makePluginAndCat(measBase.CircularApertureFluxAlgorithm,
                                       "test",
                                       control,
                                       True,
                                       centroid="centroid")
        source = cat.makeRecord()
        source.set("centroid_x", 30 + x0)
        source.set("centroid_y", 50 + y0)
        plugin.measure(source, exp)

        for r in radii:
            currentFlux = source.get(
                "%s_flux" %
                measBase.CircularApertureFluxAlgorithm.makeFieldPrefix(
                    "test", r))
            self.assertAlmostEqual(10.0 * math.pi * r * r / currentFlux,
                                   1.0,
                                   places=4)
Exemple #12
0
    def _getCoaddExpTime(self, coadd):
        """
        Get the total exposure time associated with a coadd patch by adding up
        the exposure times of the individual visits used to build the coadd.
        """
        ccdInputs = coadd.getInfo().getCoaddInputs().ccds

        totalExpTime = 0.0
        expTimeVisits = set()

        for i in range(len(ccdInputs)):
            input = ccdInputs[i]
            ccd = input.get("ccd")
            v = input.get("visit")
            bbox = input.getBBox()
            # It's quicker to not read all the pixels, so just read 1
            calexp = self.butler.get("calexp_sub",
                                     bbox=afwGeom.BoxI(afwGeom.PointI(0, 0),
                                                       afwGeom.ExtentI(1, 1)),
                                     visit=int(v),
                                     ccd=ccd)
            calib = calexp.getCalib()
            exptime = calib.getExptime()
            if v not in expTimeVisits:
                totalExpTime += exptime
                expTimeVisits.add(v)
        return totalExpTime
Exemple #13
0
    def setUp(self):
        self.nx = 64
        self.ny = 64
        self.kwid = 15
        self.sky = 100.0
        self.val = 10000.0
        self.sigma = 4.0
        coordList = [[self.nx / 2, self.ny / 2, self.val, self.sigma]]

        # exposure with gaussian
        bbox = afwGeom.Box2I(afwGeom.Point2I(0, 0),
                             afwGeom.Extent2I(self.nx, self.ny))
        self.expGaussPsf = plantSources(bbox,
                                        self.kwid,
                                        self.sky,
                                        coordList,
                                        addPoissonNoise=False)

        # just plain sky (ie. a constant)
        self.mimg = afwImage.MaskedImageF(afwGeom.ExtentI(self.nx, self.ny))
        self.mimg.set(self.sky, 0x0, self.sky)
        self.expSky = afwImage.makeExposure(self.mimg)

        if display > 1:
            ds9.mtv(self.expGaussPsf)
    def testMeasureCentroid(self):
        """Test that we can use our silly centroid through the usual Tasks"""
        algorithms.AlgorithmRegistry.register("centroid.silly",
                                              testLib.SillyCentroidControl)

        x, y = 10, 20

        im = afwImage.MaskedImageF(afwGeom.ExtentI(512, 512))
        im.set(0)
        arr = im.getImage().getArray()
        arr[y, x] = 1
        exp = afwImage.makeExposure(im)

        schema = afwTable.SourceTable.makeMinimalSchema()

        detConfig = algorithms.SourceDetectionConfig()
        detConfig.thresholdValue = 0.5
        detConfig.thresholdType = "value"
        measConfig = algorithms.SourceMeasurementConfig()
        measConfig.algorithms.names.add("centroid.silly")
        measConfig.slots.centroid = "centroid.silly"
        measConfig.algorithms["centroid.silly"].param = 5
        measConfig.doReplaceWithNoise = False

        det = algorithms.SourceDetectionTask(schema=schema, config=detConfig)
        meas = algorithms.SourceMeasurementTask(schema, config=measConfig)

        table = afwTable.SourceTable.make(schema)
        sources = det.makeSourceCatalog(table, exp, doSmooth=False,
                                        sigma=1.0).sources
        self.assertEqual(len(sources), 1)
        meas.run(exp, sources)
        self.assertEqual(len(sources), 1)
        self.assertEqual(sources[0].getY(), y + 5)
    def __init__(self,
                 xSize=32,
                 ySize=32,
                 ixxMax=30,
                 iyyMax=30,
                 detector=None,
                 xy0=afwGeom.Point2D(0, 0)):
        """Construct a _PsfShapeHistogram

        The maximum seeing FWHM that can be tolerated is [xy]Max/2.35 pixels.
        The 'resolution' of stars vs galaxies/CRs is provided by [xy]Size/[xy]Max.
        A larger (better) resolution may thresh the peaks, but a smaller (worse)
        resolution will allow stars and galaxies/CRs to mix.  The disadvantages of
        a larger (better) resolution can be compensated (some) by using multiple
        histogram peaks.

        @input[in] [xy]Size: the size of the psfImage (in pixels)
        @input[in] ixxMax, iyyMax: the maximum values for I[xy][xy]
        """
        self._xSize, self._ySize = xSize, ySize
        self._xMax, self._yMax = ixxMax, iyyMax
        self._psfImage = afwImage.ImageF(afwGeom.ExtentI(xSize, ySize), 0)
        self._num = 0
        self.detector = detector
        self.xy0 = xy0
Exemple #16
0
    def testCatFluxSigma(self):
        """
        Important note! This test will break if UseNaiveFluxSigma = False
        The alternate method significantly overestimates noise, causing this test to fail.
        It is likely that this test will need to be modified if the noise calculation is updated.
        """
        # Pick arbitrary but unique values for the test case
        source_test_flux = 5.5
        source_test_sigma = 0.23
        source_test_centroid = afwGeom.Point2D(5, 7.3)
        sourceCat = initializeSourceCatalog(schema=self.schema,
                                            name=self.name,
                                            flux=source_test_flux,
                                            sigma=source_test_sigma,
                                            centroid=source_test_centroid)

        fluxName = self.name + "_flux"
        fluxSigmaName = self.name + "_fluxSigma"
        fluxSigmaKey = self.schema.find(fluxSigmaName).key

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

        self.assertAlmostEqual(sourceCat[fluxSigmaKey], source_test_sigma)
Exemple #17
0
def policyToBadRegionList(policyFile):
    """Given a Policy file describing a CCD's bad pixels, return a vector of BadRegion::Ptr"""

    badPixelsPolicy = policy.Policy.createPolicy(policyFile)
    badPixels = algorithmsLib.DefectListT()

    if badPixelsPolicy.exists("Defects"):
        d = badPixelsPolicy.getArray("Defects")
        for reg in d:
            x0 = reg.get("x0")
            width = reg.get("width")
            if not width:
                x1 = reg.get("x1")
                width = x1 - x0 - 1

            y0 = reg.get("y0")
            if reg.exists("height"):
                height = reg.get("height")
            else:
                y1 = reg.get("y1")
                height = y1 - y0 - 1

            bbox = afwGeom.BoxI(afwGeom.PointI(x0, y0),
                                afwGeom.ExtentI(width, height))
            badPixels.push_back(algorithmsLib.Defect(bbox))

    del badPixelsPolicy

    return badPixels
Exemple #18
0
    def setEdgeBits(maskedImage, goodBBox, edgeBitmask):
        """Set the edgeBitmask bits for all of maskedImage outside goodBBox"""
        msk = maskedImage.getMask()

        mx0, my0 = maskedImage.getXY0()
        for x0, y0, w, h in (
            [0, 0, msk.getWidth(),
             goodBBox.getBeginY() - my0],
            [
                0,
                goodBBox.getEndY() - my0,
                msk.getWidth(),
                maskedImage.getHeight() - (goodBBox.getEndY() - my0)
            ],
            [0, 0, goodBBox.getBeginX() - mx0,
             msk.getHeight()],
            [
                goodBBox.getEndX() - mx0, 0,
                maskedImage.getWidth() - (goodBBox.getEndX() - mx0),
                msk.getHeight()
            ],
        ):
            edgeMask = msk.Factory(
                msk, afwGeom.BoxI(afwGeom.PointI(x0, y0),
                                  afwGeom.ExtentI(w, h)), afwImage.LOCAL)
            edgeMask |= edgeBitmask
Exemple #19
0
    def setUp(self):
        config = SingleFrameMeasurementTask.ConfigClass()
        config.slots.apFlux = 'base_CircularApertureFlux_12_0'
        self.schema = afwTable.SourceTable.makeMinimalSchema()

        self.measureSources = SingleFrameMeasurementTask(self.schema,
                                                         config=config)

        bbox = afwGeom.BoxI(afwGeom.PointI(0, 0),
                            afwGeom.ExtentI(self.width, self.height))
        self.cellSet = afwMath.SpatialCellSet(bbox, 100)

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

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

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

            except Exception as e:
                print(e)
                continue
Exemple #20
0
    def setUp(self):
        self.FWHM = 5  # pixels
        self.psf = algorithms.DoubleGaussianPsf(
            29, 29, self.FWHM / (2 * math.sqrt(2 * math.log(2))))

        self.mi = afwImage.MaskedImageF(imageFile)
        self.XY0 = afwGeom.PointI(0, 0)  # origin of the subimage we use

        if imageFile == imageFile0:
            if True:  # use full image, trimmed to data section
                self.XY0 = afwGeom.PointI(32, 2)
                self.mi = self.mi.Factory(
                    self.mi, afwGeom.BoxI(self.XY0, afwGeom.PointI(2079,
                                                                   4609)),
                    afwImage.LOCAL)
                self.mi.setXY0(afwGeom.PointI(0, 0))
                self.nCR = 1076  # number of CRs we should detect
            else:  # use sub-image
                if True:
                    self.XY0 = afwGeom.PointI(824, 140)
                    self.nCR = 10
                else:
                    self.XY0 = afwGeom.PointI(280, 2750)
                    self.nCR = 2
                self.mi = self.mi.Factory(
                    self.mi,
                    afwGeom.BoxI(self.XY0, afwGeom.ExtentI(256, 256),
                                 afwImage.LOCAL))
                self.mi.setXY0(afwGeom.PointI(0, 0))
        else:
            self.nCR = None

        self.mi.getMask().addMaskPlane("DETECTED")
Exemple #21
0
    def testWriteBool(self):
        """Test that we can read and write bools"""
        import lsst.afw.image as afwImage
        import lsst.daf.base as dafBase

        imPath = "data"
        if os.path.exists("tests"):
            imPath = os.path.join("tests", imPath)
        imPath = os.path.join(imPath, "tmp.fits")

        im = afwImage.ImageF(afwGeom.ExtentI(10, 20))
        md = dafBase.PropertySet()
        keys = {
            "BAD": False,
            "GOOD": True,
        }
        for k, v in keys.items():
            md.add(k, v)

        im.writeFits(imPath, md)

        jim = afwImage.DecoratedImageF(imPath)
        os.remove(imPath)

        for k, v in keys.items():
            self.assertEqual(jim.getMetadata().get(k), v)
def create_postage_stamp(butler,
                         out_path,
                         dataid,
                         xpix,
                         ypix,
                         side_length,
                         dataset_type='deepDiff_differenceExp'):
    """Create a singe postage stamp and save it to file

    Args:
        butler     (Butler): A data access butler
        out_path      (str): Output path of fits file
        dataid       (dict): A valid data identifier
        xpix        (float): x pixel coordinate of cutout in degrees
        ypix        (float): y pixel coordinate of cutout in degrees
        side_length (float): Side length of cutout in pixels
        dataset_type  (str): Name of data set to create postage stamp for
    """

    cutout_size = afw_geom.ExtentI(side_length, side_length)
    xy = afw_geom.PointI(xpix, ypix)
    bbox = afw_geom.BoxI(xy - cutout_size // 2, cutout_size)

    try:
        cutout_image = butler.get(datasetType=f'{dataset_type}_sub',
                                  bbox=bbox,
                                  immediate=True,
                                  dataId=dataid)

    except LengthError:
        pass

    else:
        cutout_image.writeFits(str(out_path))
Exemple #23
0
    def testBin(self):
        """Test that we can bin images anisotropically"""

        inImage = afwImage.ImageF(203, 131)
        val = 1
        inImage.set(val)
        binX, binY = 2, 4

        outImage = afwMath.binImage(inImage, binX, binY)

        self.assertEqual(outImage.getWidth(), inImage.getWidth() // binX)
        self.assertEqual(outImage.getHeight(), inImage.getHeight() // binY)

        stats = afwMath.makeStatistics(outImage, afwMath.MAX | afwMath.MIN)
        self.assertEqual(stats.getValue(afwMath.MIN), val)
        self.assertEqual(stats.getValue(afwMath.MAX), val)

        inImage.set(0)
        subImg = inImage.Factory(
            inImage, afwGeom.BoxI(afwGeom.PointI(4, 4), afwGeom.ExtentI(4, 8)),
            afwImage.LOCAL)
        subImg.set(100)
        del subImg
        outImage = afwMath.binImage(inImage, binX, binY)

        if display:
            ds9.mtv(inImage, frame=2, title="unbinned")
            ds9.mtv(outImage, frame=3, title="binned %dx%d" % (binX, binY))
Exemple #24
0
    def testMeasure(self):
        """Test that we can instantiate and play with RotationAngle"""

        scale = 5.0e-5                  # Pixel scale: 0.18 arcsec/pixel
        for angle in (0, 45, 90, 120, 180, 275):
            angle = angle * afwGeom.degrees
            for expFactory in (afwImage.ExposureF, afwImage.ExposureD):
                cdMatrix = numpy.array([[scale * math.cos(angle.asRadians()), 
                                         scale * math.sin(angle.asRadians())],
                                        [scale * -math.sin(angle.asRadians()),
                                         scale * math.cos(angle.asRadians())]])
                
                wcs = afwImage.Wcs(afwGeom.Point2D(0, 0), afwGeom.Point2D(50, 50), cdMatrix)
                exp = expFactory(afwGeom.ExtentI(100, 100), wcs)
                x, y = 10, 20
                exp.getMaskedImage().getImage().set(x, y, 1.0)

                east, north = self.measureRotAngle(exp, x, y)

                eastTrue = angle
                northTrue = angle + 90 * afwGeom.degrees
                while east < 0 * afwGeom.degrees: east = east + 360 * afwGeom.degrees
                while north < 0 * afwGeom.degrees: north = north + 360 * afwGeom.degrees
                while northTrue > 360 * afwGeom.degrees: northTrue = northTrue - 360 * afwGeom.degrees

                self.assertAlmostEqual(east.asRadians(), eastTrue.asRadians())
                self.assertAlmostEqual(north.asRadians(), northTrue.asRadians())
    def testCoordAliases(self):
        with self.assertWarns(FutureWarning):
            self.assertIsInstance(afwGeom.ExtentI(), lsst.geom.ExtentI)
        with self.assertWarns(FutureWarning):
            self.assertIsInstance(afwGeom.Extent2I(), lsst.geom.Extent2I)
        with self.assertWarns(FutureWarning):
            self.assertIsInstance(afwGeom.Extent3I(), lsst.geom.Extent3I)

        with self.assertWarns(FutureWarning):
            self.assertIsInstance(afwGeom.ExtentD(), lsst.geom.ExtentD)
        with self.assertWarns(FutureWarning):
            self.assertIsInstance(afwGeom.Extent2D(), lsst.geom.Extent2D)
        with self.assertWarns(FutureWarning):
            self.assertIsInstance(afwGeom.Extent3D(), lsst.geom.Extent3D)

        with self.assertWarns(FutureWarning):
            self.assertIsInstance(afwGeom.PointI(), lsst.geom.PointI)
        with self.assertWarns(FutureWarning):
            self.assertIsInstance(afwGeom.Point2I(), lsst.geom.Point2I)
        with self.assertWarns(FutureWarning):
            self.assertIsInstance(afwGeom.Point3I(), lsst.geom.Point3I)

        with self.assertWarns(FutureWarning):
            self.assertIsInstance(afwGeom.PointD(), lsst.geom.PointD)
        with self.assertWarns(FutureWarning):
            self.assertIsInstance(afwGeom.Point2D(), lsst.geom.Point2D)
        with self.assertWarns(FutureWarning):
            self.assertIsInstance(afwGeom.Point3D(), lsst.geom.Point3D)
Exemple #26
0
    def setUp(self):
        maskedImage = afwImage.MaskedImageF(inFilePathSmall)
        maskedImageMD = afwImage.readMetadata(inFilePathSmall)

        self.smallExposure = afwImage.ExposureF(inFilePathSmall)
        self.width = maskedImage.getWidth()
        self.height = maskedImage.getHeight()
        self.wcs = afwImage.makeWcs(maskedImageMD)
        self.psf = DummyPsf(2.0)
        self.detector = DetectorWrapper().detector

        self.exposureBlank = afwImage.ExposureF()
        self.exposureMiOnly = afwImage.makeExposure(maskedImage)
        self.exposureMiWcs = afwImage.makeExposure(maskedImage, self.wcs)
        self.exposureCrWcs = afwImage.ExposureF(
            100, 100, self.wcs)  # n.b. the (100, 100, ...) form
        self.exposureCrOnly = afwImage.ExposureF(afwGeom.ExtentI(
            100, 100))  # test with ExtentI(100, 100) too

        afwImage.Filter.reset()
        afwImage.FilterProperty.reset()

        filterPolicy = pexPolicy.Policy()
        filterPolicy.add("lambdaEff", 470.0)
        afwImage.Filter.define(afwImage.FilterProperty("g", filterPolicy))
Exemple #27
0
 def _makeDefaultAmpMap(self):
     """Make the default map from header information to amplifier information
        @return  The HeaderAmpMap object containing the mapping
     """
     hMap = HeaderAmpMap()
     emptyBBox = afwGeom.BoxI()
     mapList = [
         ('EXTNAME', 'setName'),
         ('DETSEC', 'setBBox', None, self._makeBbox),
         ('GAIN', 'setGain', 1.),
         ('RDNOISE', 'setReadNoise', 0.),
         ('SATURATE', 'setSaturation', 2 << 15),
         ('RDCRNR', 'setReadoutCorner', int(afwTable.ReadoutCorner.LL),
          afwTable.ReadoutCorner),
         ('LINCOEFF', 'setLinearityCoeffs', [0., 1.]),
         ('LINTYPE', 'setLinearityType', 'POLY'),
         ('RAWBBOX', 'setRawBBox', None, self._makeBbox),
         ('DATASEC', 'setRawDataBBox', None, self._makeBbox),
         ('FLIPX', 'setRawFlipX', False),
         ('FLIPY', 'setRawFlipY', False),
         ('XYOFF', 'setRawXYOffset', afwGeom.ExtentI(0, 0), self._makeExt),
         ('HOSCAN', 'setRawHorizontalOverscanBBox', emptyBBox,
          self._makeBbox),
         ('VOSCAN', 'setRawVerticalOverscanBBox', emptyBBox,
          self._makeBbox),
         ('PRESCAN', 'setRawPrescanBBox', emptyBBox, self._makeBbox),
     ]
     for tup in mapList:
         hMap.addEntry(*tup)
     return hMap
Exemple #28
0
    def testCopyDetector(self):
        """Test copyDetector() method
        """
        #
        # Make a copy without any modifications
        #
        detector = DetectorWrapper().detector
        ndetector = cameraGeom.copyDetector(detector)

        self.assertEqual(detector.getName(), ndetector.getName())
        self.assertEqual(detector.getBBox(), ndetector.getBBox())
        for amp, namp in zip(detector, ndetector):
            self.assertEqual(amp.getBBox(), namp.getBBox())
            self.assertEqual(amp.getRawXYOffset(), namp.getRawXYOffset())
        #
        # Now make a copy with a hacked-up set of amps
        #
        ampInfoCatalog = detector.getAmpInfoCatalog().copy(deep=True)
        for i, amp in enumerate(ampInfoCatalog, 1):
            amp.setRawXYOffset(i * afwGeom.ExtentI(1, 1))

        ndetector = cameraGeom.copyDetector(detector,
                                            ampInfoCatalog=ampInfoCatalog)

        self.assertEqual(detector.getName(), ndetector.getName())
        self.assertEqual(detector.getBBox(), ndetector.getBBox())
        for i, (amp, namp) in enumerate(zip(detector, ndetector), 1):
            self.assertEqual(amp.getBBox(), namp.getBBox())
            self.assertNotEqual(amp.getRawXYOffset(), namp.getRawXYOffset())
            self.assertEqual(namp.getRawXYOffset()[0], i)
Exemple #29
0
    def setEdgeBits(maskedImage, goodBBox, edgeBitmask):
        """!Set the edgeBitmask bits for all of maskedImage outside goodBBox

        \param[in,out] maskedImage  image on which to set edge bits in the mask
        \param[in] goodBBox  bounding box of good pixels, in LOCAL coordinates
        \param[in] edgeBitmask  bit mask to OR with the existing mask bits in the region outside goodBBox
        """
        msk = maskedImage.getMask()

        mx0, my0 = maskedImage.getXY0()
        for x0, y0, w, h in (
            [0, 0, msk.getWidth(),
             goodBBox.getBeginY() - my0],
            [
                0,
                goodBBox.getEndY() - my0,
                msk.getWidth(),
                maskedImage.getHeight() - (goodBBox.getEndY() - my0)
            ],
            [0, 0, goodBBox.getBeginX() - mx0,
             msk.getHeight()],
            [
                goodBBox.getEndX() - mx0, 0,
                maskedImage.getWidth() - (goodBBox.getEndX() - mx0),
                msk.getHeight()
            ],
        ):
            edgeMask = msk.Factory(
                msk, afwGeom.BoxI(afwGeom.PointI(x0, y0),
                                  afwGeom.ExtentI(w, h)), afwImage.LOCAL)
            edgeMask |= edgeBitmask
Exemple #30
0
    def setEdgeBits(maskedImage, goodBBox, edgeBitmask):
        """Set the edgeBitmask bits for all of maskedImage outside goodBBox

        Parameters
        ----------
        maskedImage : `lsst.afw.image.MaskedImage`
            Image on which to set edge bits in the mask.
        goodBBox : `lsst.afw.geom.Box2I`
            Bounding box of good pixels, in ``LOCAL`` coordinates.
        edgeBitmask : `lsst.afw.image.MaskPixel`
            Bit mask to OR with the existing mask bits in the region
            outside ``goodBBox``.
        """
        msk = maskedImage.getMask()

        mx0, my0 = maskedImage.getXY0()
        for x0, y0, w, h in ([0, 0,
                              msk.getWidth(), goodBBox.getBeginY() - my0],
                             [0, goodBBox.getEndY() - my0, msk.getWidth(),
                              maskedImage.getHeight() - (goodBBox.getEndY() - my0)],
                             [0, 0,
                              goodBBox.getBeginX() - mx0, msk.getHeight()],
                             [goodBBox.getEndX() - mx0, 0,
                              maskedImage.getWidth() - (goodBBox.getEndX() - mx0), msk.getHeight()],
                             ):
            edgeMask = msk.Factory(msk, afwGeom.BoxI(afwGeom.PointI(x0, y0),
                                                     afwGeom.ExtentI(w, h)), afwImage.LOCAL)
            edgeMask |= edgeBitmask