示例#1
0
    def drawLabels(self, labels=None, frame=None):
        """Draw the list labels at the corners of each panel.  If labels is None, use the ones
        specified by Mosaic.append()"""

        if frame is None:
            return

        if not labels:
            labels = self.labels

        if not labels:
            return

        if len(labels) != self.nImage:
            raise RuntimeError, ("You provided %d labels for %d panels" % (len(labels), self.nImage))

        with ds9.Buffering():
            for i in range(len(labels)):
                if labels[i]:
                    label, ctype = labels[i], None
                    try:
                        label, ctype = label
                    except:
                        pass

                    if not label:
                        continue

                    ds9.dot(str(label), self.getBBox(i).getMinX(), self.getBBox(i).getMinY(),
                            frame=frame, ctype=ctype)
示例#2
0
def showKernelSpatialCells(maskedIm, kernelCellSet, showChi2=False, symb="o",
                           ctype=None, ctypeUnused=None, ctypeBad=None, size=3,
                           frame=None, title="Spatial Cells"):
    """Show the SpatialCells.  If symb is something that ds9.dot
    understands (e.g. "o"), the top nMaxPerCell candidates will be
    indicated with that symbol, using ctype and size"""

    ds9.mtv(maskedIm, frame=frame, title=title)
    with ds9.Buffering():
        origin = [-maskedIm.getX0(), -maskedIm.getY0()]
        for cell in kernelCellSet.getCellList():
            displayUtils.drawBBox(cell.getBBox(), origin=origin, frame=frame)

            goodies = ctypeBad is None
            for cand in cell.begin(goodies):
                xc, yc = cand.getXCenter() + origin[0], cand.getYCenter() + origin[1]
                if cand.getStatus() == afwMath.SpatialCellCandidate.BAD:
                    color = ctypeBad
                elif cand.getStatus() == afwMath.SpatialCellCandidate.GOOD:
                    color = ctype
                elif cand.getStatus() == afwMath.SpatialCellCandidate.UNKNOWN:
                    color = ctypeUnused
                else:
                    continue

                if color:
                    ds9.dot(symb, xc, yc, frame=frame, ctype=color, size=size)

                    if showChi2:
                        rchi2 = cand.getChi2()
                        if rchi2 > 1e100:
                            rchi2 = np.nan
                        ds9.dot("%d %.1f" % (cand.getId(), rchi2),
                                xc - size, yc - size - 4, frame=frame, ctype=color, size=size)
示例#3
0
    def testLinearRamp(self):
        """Fit a ramp"""

        binsize = 1
        ramp, rampCoeffs, xVec, yVec = self.makeRamp(binsize)
        # Add a (labelled) bad value
        ramp.set(ramp.getWidth()//2, ramp.getHeight()//2, (0, 0x1, np.nan))

        if display:
            ds9.mtv(ramp, title="Input", frame=0)
        # Here's the range that the approximation should be valid (and also the
        # bbox of the image returned by getImage)
        bbox = afwGeom.BoxI(afwGeom.PointI(0, 0),
                            afwGeom.PointI(binsize*ramp.getWidth() - 1,
                                           binsize*ramp.getHeight() - 1))

        order = 3                       # 1 would be enough to fit the ramp
        actrl = afwMath.ApproximateControl(
            afwMath.ApproximateControl.CHEBYSHEV, order)
        approx = afwMath.makeApproximate(xVec, yVec, ramp, bbox, actrl)

        for i, aim in enumerate([approx.getImage(),
                                 approx.getMaskedImage().getImage(),
                                 ]):
            if i == 0 and display:
                ds9.mtv(aim, title="interpolated", frame=1)
                with ds9.Buffering():
                    for x in xVec:
                        for y in yVec:
                            ds9.dot('+', x, y, size=0.4, frame=1)

            for x, y in aim.getBBox().getCorners():
                self.assertEqual(
                    aim.get(x, y), rampCoeffs[0] + rampCoeffs[1]*x + rampCoeffs[1]*y)
示例#4
0
def main(rootDir, visit, ccd, frame=1, title="", scale="zscale", zoom="to fit", trans=60, useEllipse=False):

    # make a butler and specify your dataId
    butler = dafPersist.Butler(rootDir)
    dataId = {'visit': visit, 'ccd':ccd}

    # get the exposure from the butler
    exposure = butler.get('calexp', dataId)

    # put the settings in a dict object and call ds9.mtv()
    settings = {'scale':scale, 'zoom': zoom, 'mask' : 'transparency %d' %(trans)}
    ds9.mtv(exposure, frame=frame, title=title, settings=settings)


    # now get the source catalog and overplot the points

    sources = butler.get('src', dataId)

    with ds9.Buffering():
        for i,source in enumerate(sources):
            color = ds9.RED
            size = 5.0
            
            if useEllipse:
                # show an ellipse symbol
                symbol = "@:{ixx},{ixy},{iyy}".format(ixx=source.getIxx(),
                                                      ixy=source.getIxy(),
                                                      iyy=source.getIyy())
            else:
                # just a simple point (symbols +, x, *, o are all accepted)
                symbol = "o"
                
            ds9.dot(symbol, source.getX(), source.getY(), ctype=color,
                    size=size, frame=frame, silent=True)
示例#5
0
def run(display=False):
    exposure = loadData()
    schema = afwTable.SourceTable.makeMinimalSchema()
    #
    # Create the detection and measurement Tasks
    #
    config = SourceDetectionTask.ConfigClass()
    config.reEstimateBackground = False
    detectionTask = SourceDetectionTask(config=config, schema=schema)

    config = SingleFrameMeasurementTask.ConfigClass()
    # Use the minimum set of plugins required.
    config.plugins.names.clear()
    for plugin in [
            "base_SdssCentroid", "base_SdssShape", "base_CircularApertureFlux",
            "base_PixelFlags"
    ]:
        config.plugins.names.add(plugin)
    config.plugins["base_CircularApertureFlux"].radii = [7.0]
    # Use of the PSF flux is hardcoded in secondMomentStarSelector
    config.slots.psfFlux = "base_CircularApertureFlux_7_0"
    measureTask = SingleFrameMeasurementTask(schema, config=config)
    #
    # Create the measurePsf task
    #
    config = MeasurePsfTask.ConfigClass()

    psfDeterminer = config.psfDeterminer.apply()
    psfDeterminer.config.sizeCellX = 128
    psfDeterminer.config.sizeCellY = 128
    psfDeterminer.config.spatialOrder = 1
    psfDeterminer.config.nEigenComponents = 3

    measurePsfTask = MeasurePsfTask(config=config, schema=schema)
    #
    # Create the output table
    #
    tab = afwTable.SourceTable.make(schema)
    #
    # Process the data
    #
    sources = detectionTask.run(tab, exposure, sigma=2).sources
    measureTask.measure(exposure, sources)

    result = measurePsfTask.run(exposure, sources)
    psf = result.psf
    cellSet = result.cellSet

    if display:  # display on ds9 (see also --debug argparse option)
        frame = 1
        ds9.mtv(exposure, frame=frame)

        with ds9.Buffering():
            for s in sources:
                xy = s.getCentroid()
                ds9.dot('+', *xy, frame=frame)
                if s.get("calib.psf.candidate"):
                    ds9.dot('x', *xy, ctype=ds9.YELLOW, frame=frame)
                if s.get("calib.psf.used"):
                    ds9.dot('o', *xy, size=4, ctype=ds9.RED, frame=frame)
示例#6
0
def main(rootDir, visit, ccd, filter=None,
         frame=1, title="", scale="zscale", zoom="to fit", trans=60,
         useEllipse=False, maskOnly=False):

    if ccd.find(",") < 0:
        ccd = int(ccd)

    pipeVersion = dafPersist.eupsVersions.EupsVersions().versions['hscPipe']
    if StrictVersion(pipeVersion) >= StrictVersion('3.9.0'):
        coaddData = "deepCoadd_calexp"
        coaddCat  = "meas"
    else:
        coaddData = "deepCoadd"
        coaddCat  = "src"

    print "Read in %s image"%coaddData

    # make a butler and specify your dataId
    butler = dafPersist.Butler(rootDir)
    if filter:
        dataId = {'tract': visit, 'patch':ccd, 'filter': filter}
        exposure = butler.get(coaddData, dataId, immediate=True)
        butlerTarget='deepCoadd_'
        sources = butler.get(butlerTarget + coaddCat, dataId)
    else:
        dataId = {'visit': visit, 'ccd':ccd}
        exposure = butler.get("calexp", dataId, immediate=True)
        butlerTarget=""
        sources = butler.get(butlerTarget + 'src', dataId)

    # put the settings in a dict object and call ds9.mtv()
    settings = {'scale':scale, 'zoom': zoom, 'mask' : 'transparency %d' %(trans)}
    ds9.setMaskPlaneColor('FAKE', color=ds9.CYAN)
    if not maskOnly:
        ds9.mtv(exposure, frame=frame, title=title, settings=settings)
    else:
        msk = exposure.getMaskedImage().getMask()
        msk &= msk.getPlaneBitMask('FAKE')
        ds9.mtv(msk, frame=frame, title=title, settings=settings)

    with ds9.Buffering():
        print len(sources)
        x0, y0 = exposure.getXY0()
        print x0, y0
        for i,source in enumerate(sources):
            color = ds9.RED
            size = 5.0

            if useEllipse:
                # show an ellipse symbol
                symbol = "@:{ixx},{ixy},{iyy}".format(ixx=source.getIxx(),
                                                      ixy=source.getIxy(),
                                                      iyy=source.getIyy())
            else:
                # just a simple point (symbols +, x, *, o are all accepted)
                symbol = "o"

            ds9.dot(symbol, source.getX()-x0, source.getY()-y0, ctype=color,
                    size=size, frame=frame, silent=True)
示例#7
0
def showSourceSetSky(sSet, wcs, xy0, frame=0, ctype=ds9.GREEN, symb="+", size=2):
    """Draw the (RA, Dec) positions of a set of Sources. Image has the XY0."""
    with ds9.Buffering():
        for s in sSet:
            (xc, yc) = wcs.skyToPixel(s.getCoord().getRa(), s.getCoord().getDec())
            xc -= xy0[0]
            yc -= xy0[1]
            ds9.dot(symb, xc, yc, frame=frame, ctype=ctype, size=size)
示例#8
0
def display(self, xy0=None, frame=1, ctype=None):
    """Display polygon on existing frame in ds9"""
    import lsst.afw.geom as afwGeom
    import lsst.afw.display.ds9 as ds9
    xy0 = afwGeom.Extent2D(0, 0) if xy0 is None else afwGeom.Extent2D(xy0)
    with ds9.Buffering():
        for p1, p2 in self.getEdges():
            ds9.line((p1 - xy0, p2 - xy0), frame=frame, ctype=ctype)
示例#9
0
def view(cat=None, exp=None, tract=None, patch=None, ID=None, coords=None, filter='I', frame=0, scale="zscale",\
         zoom="to fit", trans=80, draw_ells=True, maxsep=None, shape_model='shape.hsm.moments', pcolor=ds9.GREEN, ccolor=ds9.RED):

    if cat is None:
        assert (tract is not None) and (
            patch is not None), 'if no cat is given, must give tract and patch'
        exp = butler.get("deepCoadd_calexp",
                         tract=tract,
                         patch=patch,
                         filter='HSC-' + filter,
                         immediate=True)
        cat = butler.get("deepCoadd_meas",
                         tract=tract,
                         patch=patch,
                         filter='HSC-' + filter,
                         immediate=True)
    else:
        assert exp is not None, 'if cat is given, must also give exp'
    x0, y0 = exp.getXY0()
    settings = {
        'scale': scale,
        'zoom': zoom,
        'mask': 'transparency %d' % (trans)
    }
    ds9.mtv(exp, frame=frame, settings=settings)

    #########################################################
    # maxsep is used if you only want to draw ellipses around
    # objects within a distance maxsep from a candidate
    #########################################################
    if maxsep is not None:
        if ID is not None:
            obj = cat.find(ID)
            ra0, dec0 = obj.getRa().asDegrees(), obj.getDec().asDegrees()
        else:
            ra0, dec0 = coords
        ra, dec = cat.get('coord.ra') * 180. / np.pi, cat.get(
            'coord.dec') * 180. / np.pi
        seps = angsep(ra0, dec0, ra, dec)
        cut = seps < maxsep
        cat = cat[seps < maxsep].copy(deep=True)

    if draw_ells:
        with ds9.Buffering():
            for i, source in enumerate(cat):
                ellcolor = pcolor if source.get('parent') == 0 else ccolor
                ixx, ixy, iyy = [
                    source.get(shape_model + _x)
                    for _x in ['.xx', '.xy', '.yy']
                ]
                symbol = "@:{ixx},{ixy},{iyy}".format(ixx=ixx,
                                                      ixy=ixy,
                                                      iyy=iyy)
                ds9.dot(symbol,
                        source.getX() - x0,
                        source.getY() - y0,
                        ctype=ellcolor,
                        frame=frame)
示例#10
0
def showPsfResiduals(exposure, sourceSet, magType="psf", scale=10, frame=None):
    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)))
        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)

            subtractPsf(psf, mimIn, x, y, flux)
        except Exception as 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)),
                                             )
        except pexExcept.Exception:
            continue

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

        sim += expIm

    if frame is not None:
        ds9.mtv(im, frame=frame)
        with ds9.Buffering():
            for x, y in cenPos:
                ds9.dot("+", x, y, frame=frame)

    return im
示例#11
0
 def plotPeaks(fps, ctype):
     if fps is None:
         return
     with ds9.Buffering():
         for fp in fps.getFootprints():
             for pp in fp.getPeaks():
                 ds9.dot("+",
                         pp.getFx() - x0,
                         pp.getFy() - y0,
                         ctype=ctype)
    def displayDipoles(self, exposure, sources):
        """!Display debugging information on the detected dipoles

        @param exposure  Image the dipoles were measured on
        @param sources   The set of diaSources that were measured"""

        import lsstDebug
        display = lsstDebug.Info(__name__).display
        displayDiaSources = lsstDebug.Info(__name__).displayDiaSources
        maskTransparency = lsstDebug.Info(__name__).maskTransparency
        if not maskTransparency:
            maskTransparency = 90
        ds9.setMaskTransparency(maskTransparency)
        ds9.mtv(exposure, frame=lsstDebug.frame)

        if display and displayDiaSources:
            with ds9.Buffering():
                for source in sources:
                    cenX, cenY = source.get("ipdiffim_DipolePsfFlux_centroid")
                    if np.isinf(cenX) or np.isinf(cenY):
                        cenX, cenY = source.getCentroid()

                    isdipole = source.get("classification.dipole")
                    if isdipole and np.isfinite(isdipole):
                        # Dipole
                        ctype = "green"
                    else:
                        # Not dipole
                        ctype = "red"

                    ds9.dot("o",
                            cenX,
                            cenY,
                            size=2,
                            ctype=ctype,
                            frame=lsstDebug.frame)

                    negCenX = source.get(
                        "ip_diffim_PsfDipoleFlux_neg_centroid_x")
                    negCenY = source.get(
                        "ip_diffim_PsfDipoleFlux_neg_centroid_y")
                    posCenX = source.get(
                        "ip_diffim_PsfDipoleFlux_pos_centroid_x")
                    posCenY = source.get(
                        "ip_diffim_PsfDipoleFlux_pos_centroid_y")
                    if (np.isinf(negCenX) or np.isinf(negCenY)
                            or np.isinf(posCenX) or np.isinf(posCenY)):
                        continue

                    ds9.line([(negCenX, negCenY), (posCenX, posCenY)],
                             ctype="yellow",
                             frame=lsstDebug.frame)

            lsstDebug.frame += 1
示例#13
0
    def testGrowFootprints3(self):
        """Test that we can grow footprints, correctly merging those that now totally overwritten"""

        self.im = afwImage.MaskedImageF(14, 11)

        self.im.getImage().set(0)
        self.peaks = []
        
        I = 11
        for x, y in [(4, 7), (5, 7), (6, 7), (7, 7), (8, 7),
                     (4, 6),                                     (8, 6),
                     (4, 5),                                     (8, 5),
                     (4, 4),                                     (8, 4),
                     (4, 3),                                     (8, 3),
                     ]:
            self.im.getImage().set(x, y, I)
            I -= 1e-3

        self.im.getImage().set(4, 7, 15)
        self.peaks.append([(4, 7,),])
        
        self.im.getImage().set(6, 5, 30)
        self.peaks[0].append((6, 5,))

        self.fs = afwDetect.FootprintSet(self.im, afwDetect.Threshold(10), "BINNED1")
        #
        # The disappearing Footprint special case only shows up if the outer Footprint is grown
        # _after_ the inner one.  So arrange the order properly
        feet = self.fs.getFootprints()
        feet[0], feet[1] = feet[1], feet[0]

        msk = self.im.getMask()

        grow = 2
        self.fs = afwDetect.FootprintSet(self.fs, grow, False)
        afwDetect.setMaskFromFootprintList(msk, self.fs.getFootprints(),
                                           msk.getPlaneBitMask("DETECTED_NEGATIVE"))

        if display:
            frame = 0

            ds9.mtv(self.im, frame=frame)

            with ds9.Buffering():
                for i, foot in enumerate(self.fs.getFootprints()):
                    for p in foot.getPeaks():
                        ds9.dot("+", p.getIx(), p.getIy(), size=0.4, frame=frame)

                    if i < len(self.peaks):
                        for trueX, trueY in self.peaks[i]:
                            ds9.dot("x", trueX, trueY, size=0.4, ctype=ds9.RED, frame=frame)

        self.assertEqual(len(self.fs.getFootprints()), 1)
        self.assertEqual(len(self.fs.getFootprints()[0].getPeaks()), len(self.peaks[0]))
示例#14
0
def showSourceSet(sSet, xy0=(0, 0), frame=0, ctype=ds9.GREEN, symb="+", size=2):
    """Draw the (XAstrom, YAstrom) positions of a set of Sources.  Image has the given XY0"""

    with ds9.Buffering():
        for s in sSet:
            xc, yc = s.getXAstrom() - xy0[0], s.getYAstrom() - xy0[1]

            if symb == "id":
                ds9.dot(str(splitId(s.getId(), True)["objId"]), xc, yc, frame=frame, ctype=ctype, size=size)
            else:
                ds9.dot(symb, xc, yc, frame=frame, ctype=ctype, size=size)
示例#15
0
    def testText(self):
        """Test drawing text"""
        ds9.erase()

        exp = afwImage.ExposureF(300, 350)
        ds9.mtv(exp, title="parent")  # tells display0 about the image's xy0

        with ds9.Buffering():
            ds9.dot('hello', 200, 200)
            ds9.dot('hello', 200, 210, size=1.25)
            ds9.dot('hello', 200, 220, size=3, fontFamily="times")
            ds9.dot('hello', 200, 230, fontFamily="helvetica bold italic")
示例#16
0
文件: testDs9.py 项目: brianv0/afw
    def testDrawing(self):
        """Test drawing lines and glyphs"""
        ds9.erase()

        exp = afwImage.ExposureF(300, 350)
        ds9.mtv(exp, title="parent")  # tells display0 about the image's xy0

        with ds9.Buffering():
            ds9.dot('o', 200, 220)
            vertices = [(200, 220), (210, 230), (224, 230), (214, 220), (200, 220)]
            ds9.line(vertices, ctype=ds9.CYAN)
            ds9.line(vertices[:-1], symbs="+x+x", size=3)
示例#17
0
def run(display=False):
    exposure = loadData()
    schema = afwTable.SourceTable.makeMinimalSchema()
    #
    # Create the detection task
    #
    config = SourceDetectionTask.ConfigClass()
    config.thresholdPolarity = "both"
    config.background.isNanSafe = True
    config.thresholdValue = 3
    detectionTask = SourceDetectionTask(config=config, schema=schema)
    #
    # And the measurement Task
    #
    config = SingleFrameMeasurementTask.ConfigClass()

    config.algorithms.names = ["base_SdssCentroid", "base_SdssShape", "base_CircularApertureFlux"]
    config.algorithms["base_CircularApertureFlux"].radii = [1, 2, 4, 8, 16] # pixels

    config.slots.instFlux = None
    config.slots.modelFlux = None
    config.slots.psfFlux = None

    algMetadata = dafBase.PropertyList()
    measureTask = SingleFrameMeasurementTask(schema, algMetadata=algMetadata, config=config)
    radii = algMetadata.get("base_CircularApertureFlux_radii")
    #
    # Create the output table
    #
    tab = afwTable.SourceTable.make(schema)
    #
    # Process the data
    #
    result = detectionTask.run(tab, exposure)

    sources = result.sources

    print("Found %d sources (%d +ve, %d -ve)" % (len(sources), result.fpSets.numPos, result.fpSets.numNeg))

    measureTask.run(sources, exposure)
    if display:                         # display on ds9 (see also --debug argparse option)
        frame = 1
        ds9.mtv(exposure, frame=frame)

        with ds9.Buffering():
            for s in sources:
                xy = s.getCentroid()
                ds9.dot('+', *xy, ctype=ds9.CYAN if s.get("flags.negative") else ds9.GREEN, frame=frame)
                ds9.dot(s.getShape(), *xy, ctype=ds9.RED, frame=frame)

                for i in range(s.get("flux.aperture.nProfile")):
                    ds9.dot('o', *xy, size=radii[i], ctype=ds9.YELLOW, frame=frame)
示例#18
0
    def selectStars(self, exposure, sourceCat, matches=None):
        """!Return a list of PSF candidates that represent likely stars

        A list of PSF candidates may be used by a PSF fitter to construct a PSF.

        @param[in] exposure  the exposure containing the sources
        @param[in] sourceCat  catalog of sources that may be stars (an lsst.afw.table.SourceCatalog)
        @param[in] matches  a match vector as produced by meas_astrom; required
                            (defaults to None to match the StarSelector API and improve error handling)

        @return an lsst.pipe.base.Struct containing:
        - starCat  catalog of selected stars (a subset of sourceCat)
        """
        import lsstDebug
        debugInfo = lsstDebug.Info(__name__)
        display = debugInfo.display
        pauseAtEnd = debugInfo.pauseAtEnd  # pause when done

        if matches is None:
            raise RuntimeError("CatalogStarSelectorTask requires matches")

        mi = exposure.getMaskedImage()

        if display:
            frame = 1
            ds9.mtv(mi, frame=frame, title="PSF candidates")

        isGoodSource = CheckSource(sourceCat, self.config.fluxLim,
                                   self.config.fluxMax, self.config.badFlags)

        starCat = SourceCatalog(sourceCat.schema)
        with ds9.Buffering():
            for ref, source, d in matches:
                if not ref.get("resolved"):
                    if not isGoodSource(source):
                        symb, ctype = "+", ds9.RED
                    else:
                        starCat.append(source)
                        symb, ctype = "+", ds9.GREEN

                        if display:
                            ds9.dot(symb,
                                    source.getX() - mi.getX0(),
                                    source.getY() - mi.getY0(),
                                    size=4,
                                    frame=frame,
                                    ctype=ctype)

        if display and pauseAtEnd:
            input("Continue? y[es] p[db] ")

        return Struct(starCat=starCat, )
示例#19
0
def showPeaks(im=None, fs=None, frame=0):
    """Show the image and peaks"""
    if frame is None:
        return

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

    if fs:
        with ds9.Buffering():           # turn on buffering of ds9's slow "region" writes
            for foot in fs.getFootprints():
                for p in foot.getPeaks():
                    ds9.dot("+", p.getIx(), p.getIy(), size=0.4, ctype=ds9.RED, frame=frame)
示例#20
0
def getBackground(image, backgroundConfig, nx=0, ny=0, algorithm=None):
    """
    Make a new Exposure which is exposure - background
    """
    backgroundConfig.validate()

    if not nx:
        nx = image.getWidth() // backgroundConfig.binSize + 1
    if not ny:
        ny = image.getHeight() // backgroundConfig.binSize + 1

    displayBackground = lsstDebug.Info(__name__).displayBackground
    if displayBackground:
        import itertools
        ds9.mtv(image, frame=1)
        xPosts = numpy.rint(
            numpy.linspace(0, image.getWidth() + 1, num=nx, endpoint=True))
        yPosts = numpy.rint(
            numpy.linspace(0, image.getHeight() + 1, num=ny, endpoint=True))
        with ds9.Buffering():
            for (xMin, xMax), (yMin, yMax) in itertools.product(
                    zip(xPosts[:-1], xPosts[1:]), zip(yPosts[:-1],
                                                      yPosts[1:])):
                ds9.line([(xMin, yMin), (xMin, yMax), (xMax, yMax),
                          (xMax, yMin), (xMin, yMin)],
                         frame=1)

    sctrl = afwMath.StatisticsControl()
    sctrl.setAndMask(
        reduce(lambda x, y: x | image.getMask().getPlaneBitMask(y),
               backgroundConfig.ignoredPixelMask, 0x0))
    sctrl.setNanSafe(backgroundConfig.isNanSafe)

    pl = pexLogging.Debug("meas.utils.sourceDetection.getBackground")
    pl.debug(
        3, "Ignoring mask planes: %s" %
        ", ".join(backgroundConfig.ignoredPixelMask))

    if not algorithm:
        algorithm = backgroundConfig.algorithm

    bctrl = afwMath.BackgroundControl(algorithm, nx, ny,
                                      backgroundConfig.undersampleStyle, sctrl,
                                      backgroundConfig.statisticsProperty)

    if backgroundConfig.useApprox:
        actrl = afwMath.ApproximateControl(
            afwMath.ApproximateControl.CHEBYSHEV, backgroundConfig.approxOrder)
        bctrl.setApproximateControl(actrl)

    return afwMath.makeBackground(image, bctrl)
示例#21
0
def main(rootDir,
         visit,
         ccd,
         frame=1,
         title="",
         scale="zscale",
         zoom="to fit",
         trans=60,
         useEllipse=False):

    # butler を開き読み込みたいデータの dataId を指定する
    butler = dafPersist.Butler(rootDir)
    dataId = {'visit': visit, 'ccd': ccd}

    # butler から一次処理済データを読み込む
    exposure = butler.get('calexp', dataId)

    # 読み込みたい天体情報を設定し、ds9.mtv() を読み込む
    settings = {
        'scale': scale,
        'zoom': zoom,
        'mask': 'transparency %d' % (trans)
    }
    ds9.mtv(exposure, frame=frame, title=title, settings=settings)

    # 天体カタログを取得し、データ点を重ねて表示する

    sources = butler.get('src', dataId)

    with ds9.Buffering():
        for i, source in enumerate(sources):
            color = ds9.RED
            size = 5.0

            if useEllipse:
                # 楕円体のシンボルで表示
                symbol = "@:{ixx},{ixy},{iyy}".format(ixx=source.getIxx(),
                                                      ixy=source.getIxy(),
                                                      iyy=source.getIyy())
            else:
                # シンプルなシンボルで表示(例えば、 +, x, *, o が使える)
                symbol = "o"

            ds9.dot(symbol,
                    source.getX(),
                    source.getY(),
                    ctype=color,
                    size=size,
                    frame=frame,
                    silent=True)
示例#22
0
    def checkPeaks(self, dwidth=0, dheight=0, frame=3):
        """Check that we got the peaks right"""
        feet = self.fs.getFootprints()
        #
        # Check that we found all the peaks
        #
        self.assertEqual(sum([len(f.getPeaks()) for f in feet]), sum([len(f.getPeaks()) for f in feet]))

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

            with ds9.Buffering():
                for i, foot in enumerate(feet):
                    for p in foot.getPeaks():
                        ds9.dot("+", p.getIx(), p.getIy(), size=0.4, frame=frame)

                    if i < len(self.peaks):
                        for trueX, trueY, peakVal in self.peaks[i]:
                            ds9.dot("x", trueX, trueY, size=0.4, ctype=ds9.RED, frame=frame)

        for i, foot in enumerate(feet):
            npeak = None
            #
            # Peaks that touch the edge are handled differently, as only the single highest/lowest pixel
            # is treated as a Peak
            #
            if (dwidth != 0 or dheight != 0):
                if (foot.getBBox().getMinX() == 0 or foot.getBBox().getMaxX() == self.im.getWidth()  - 1 or
                    foot.getBBox().getMinY() == 0 or foot.getBBox().getMaxY() == self.im.getHeight() - 1):
                    npeak = 1

            if npeak is None:
                npeak = len(self.peaks[i])

            if npeak != len(foot.getPeaks()):
                print "RHL", foot.repr()
                #print "RHL", [(p.repr().split(":")[0], p.getIx(), p.getIy()) for p in foot.getPeaks()]
                print "RHL", [(p.getId(), p.getIx(), p.getIy()) for p in foot.getPeaks()]
                print "RHL", [p[0:2] for p in self.peaks[i]]

            self.assertEqual(len(foot.getPeaks()), npeak)

            for j, p in enumerate(foot.getPeaks()):
                trueX, trueY, peakVal = self.peaks[i][j]
                if (p.getIx(), p.getIy()) != (trueX, trueY):
                    print "RHL", [(pp.getId(), pp.getIx(), pp.getIy()) for pp in foot.getPeaks()]
                    print "RHL", [pp[0:2] for pp in self.peaks[i]]

                self.assertEqual((p.getIx(), p.getIy()), (trueX, trueY))
示例#23
0
def showPsfSpatialCells(exposure, psfCellSet, nMaxPerCell=-1, showChi2=False, showMoments=False,
                        symb=None, ctype=None, ctypeUnused=None, ctypeBad=None, size=2, frame=None):
    """Show the SpatialCells.  If symb is something that ds9.dot understands (e.g. "o"), the
    top nMaxPerCell candidates will be indicated with that symbol, using ctype and size"""

    with ds9.Buffering():
        origin = [-exposure.getMaskedImage().getX0(), -exposure.getMaskedImage().getY0()]
        for cell in psfCellSet.getCellList():
            displayUtils.drawBBox(cell.getBBox(), origin=origin, frame=frame)

            if nMaxPerCell < 0:
                nMaxPerCell = 0

            i = 0
            goodies = ctypeBad is None
            for cand in cell.begin(goodies):
                if nMaxPerCell > 0:
                    i += 1

                cand = algorithmsLib.cast_PsfCandidateF(cand)

                xc, yc = cand.getXCenter() + origin[0], cand.getYCenter() + origin[1]

                if i > nMaxPerCell:
                    if not ctypeUnused:
                        continue

                color = ctypeBad if cand.isBad() else ctype

                if symb:
                    if i > nMaxPerCell:
                        ct = ctypeUnused
                    else:
                        ct = ctype

                    ds9.dot(symb, xc, yc, frame=frame, ctype=ct, size=size)

                source = cand.getSource()

                if showChi2:
                    rchi2 = cand.getChi2()
                    if rchi2 > 1e100:
                        rchi2 = numpy.nan
                    ds9.dot("%d %.1f" % (splitId(source.getId(), True)["objId"], rchi2),
                            xc - size, yc - size - 4, frame=frame, ctype=color, size=2)

                if showMoments:
                    ds9.dot("%.2f %.2f %.2f" % (source.getIxx(), source.getIxy(), source.getIyy()),
                            xc-size, yc + size + 4, frame=frame, ctype=color, size=size)
    def measureExposure(self, exposure, positions, title="Fringe"):
        """Measure fringe amplitudes for an exposure

        The fringe amplitudes are measured as the statistic within a square
        aperture.  The statistic within a larger aperture are subtracted so
        as to remove the background.

        @param exposure    Exposure to measure
        @param positions   Array of (x,y) for fringe measurement
        @param title       Title for display
        @return Array of fringe measurements
        """
        stats = afwMath.StatisticsControl()
        stats.setNumSigmaClip(self.config.stats.clip)
        stats.setNumIter(self.config.stats.iterations)
        stats.setAndMask(exposure.getMaskedImage().getMask().getPlaneBitMask(
            self.config.stats.badMaskPlanes))

        num = self.config.num
        fringes = numpy.ndarray(num)

        for i in range(num):
            x, y = positions[i]
            small = measure(exposure.getMaskedImage(), x, y, self.config.small,
                            self.config.stats.stat, stats)
            large = measure(exposure.getMaskedImage(), x, y, self.config.large,
                            self.config.stats.stat, stats)
            fringes[i] = small - large

        import lsstDebug
        display = lsstDebug.Info(__name__).display
        if display:
            frame = getFrame()
            ds9.mtv(exposure, frame=frame, title=title)
            if False:
                with ds9.Buffering():
                    for x, y in positions:
                        corners = numpy.array([[-1, -1], [1, -1], [1, 1],
                                               [-1, 1], [-1, -1]]) + [[x, y]]
                        ds9.line(corners * self.config.small,
                                 frame=frame,
                                 ctype="green")
                        ds9.line(corners * self.config.large,
                                 frame=frame,
                                 ctype="blue")

        return fringes
示例#25
0
    def showImage(self, image, sources, title, frame):
        """Display an image

        Images are only displayed if 'display' is turned on.

        @param image: Image to display
        @param sources: Sources to mark on the display
        @param title: Title to give frame
        @param frame: Frame on which to display
        """
        if not display:
            return
        ds9.mtv(image, title=title, frame=frame)
        with ds9.Buffering():
            for s in sources:
                center = s.getCentroid()
                ds9.dot("o", center.getX(), center.getY(), frame=frame)
示例#26
0
def main(rootDir, visit, ccd, filter=None,
         frame=1, title="", scale="zscale", zoom="to fit", trans=60, useEllipse=False):

    if ccd.find(",") < 0:
        ccd = int(ccd)
        
    # make a butler and specify your dataId
    butler = dafPersist.Butler(rootDir)
    if filter:
        dataId = {'tract': visit, 'patch':ccd, 'filter': filter}
        exposure = butler.get("deepCoadd", dataId)
        butlerTarget='deepCoadd_'
    else:
        dataId = {'visit': visit, 'ccd':ccd}
        exposure = butler.get("calexp", dataId)
        butlerTarget=""
    

    # put the settings in a dict object and call ds9.mtv()
    settings = {'scale':scale, 'zoom': zoom, 'mask' : 'transparency %d' %(trans)}
    ds9.mtv(exposure, frame=frame, title=title, settings=settings)


    # now get the source catalog and overplot the points

    sources = butler.get(butlerTarget+'src', dataId)

    with ds9.Buffering():
        print len(sources)
        x0, y0 = exposure.getXY0()
        print x0, y0
        for i,source in enumerate(sources):
            color = ds9.RED
            size = 5.0
            
            if useEllipse:
                # show an ellipse symbol
                symbol = "@:{ixx},{ixy},{iyy}".format(ixx=source.getIxx(),
                                                      ixy=source.getIxy(),
                                                      iyy=source.getIyy())
            else:
                # just a simple point (symbols +, x, *, o are all accepted)
                symbol = "o"
                
            ds9.dot(symbol, source.getX()-x0, source.getY()-y0, ctype=color,
                    size=size, frame=frame, silent=True)
示例#27
0
    def process(self, dataRef):
        """Process focus CCD in preparation for focus measurement

        @param dataRef: Data reference for CCD
        @return Struct(sources: source measurements,
                       ccdId: CCD number,
                       filterName: name of filter,
                       dims: exposure dimensions
                       )
        """
        import lsstDebug
        display = lsstDebug.Info(__name__).display

        exp = self.isr.runDataRef(dataRef).exposure

        if display:
            import lsst.afw.display.ds9 as ds9
            ds9.mtv(exp, title="Post-ISR", frame=1)

        self.installPsf.run(exposure=exp)
        bg, exp = measAlg.estimateBackground(exp, self.config.background, subtract=True)

        if display:
            ds9.mtv(exp, title="Post-background", frame=2)

        dmResults = self.detectAndMeasure.run(exp, dataRef.get("expIdInfo"))
        sources = dmResults.sourceCat

        self.starSelector.run(exp, sources, isStarField="hscPipeline_focus_candidate")

        if display:
            ds9.mtv(exp, title="Post-measurement", frame=3)
            with ds9.Buffering():
                for s in sources:
                    ds9.dot("o", s.getX(), s.getY(), frame=3,
                            ctype=ds9.GREEN if s.get("calib.psf.candidate") else ds9.RED)
            import pdb;pdb.set_trace() # pause to allow inspection

        filterName = exp.getFilter().getName()

        if self.config.doWrite:
            dataRef.put(sources, "src")
            dataRef.put(exp, "visitim")

        return Struct(sources=sources, ccdId=dataRef.dataId["ccd"], filterName=filterName,
                      dims=exp.getDimensions())
示例#28
0
def drawCoaddInputs(exposure, frame=None, ctype=None, bin=1):
    """Draw the bounding boxes of input exposures to a coadd on a ds9 frame with the specified ctype,
    assuming ds9.mtv() has already been called on the given exposure on this frame.


    All coordinates are divided by bin, as is right and proper for overlaying on a binned image
    """
    coaddWcs = exposure.getWcs()
    catalog = exposure.getInfo().getCoaddInputs().ccds

    offset = afwGeom.Point2D() - afwGeom.Point2D(exposure.getXY0())
    with ds9.Buffering():
        for record in catalog:
            ccdBox = afwGeom.Box2D(record.getBBox())
            ccdCorners = ccdBox.getCorners()
            coaddCorners = [coaddWcs.skyToPixel(record.getWcs().pixelToSky(point)) + offset
                            for point in ccdCorners]
            ds9.line([(coaddCorners[i].getX() / bin, coaddCorners[i].getY() / bin)
                      for i in range(-1, 4)], frame=frame, ctype=ctype)
示例#29
0
def drawFootprint(foot, borderWidth=0.5, origin=None, XY0=None, frame=None, ctype=None, bin=1,
                  peaks=False, symb="+", size=0.4, ctypePeak=None):
    """Draw an afwDetection::Footprint on a ds9 frame with the specified ctype.  Include an extra borderWidth
pixels If origin is present, it's Added to the Footprint; if XY0 is present is Subtracted from the Footprint

If peaks is True, also show the object's Peaks using the specified symbol and size and ctypePeak

All Footprint coordinates are divided by bin, as is right and proper for overlaying on a binned image
    """

    if XY0:
        if origin:
            raise RuntimeError("You may not specify both origin and XY0")
        origin = (-XY0[0], -XY0[1])

    with ds9.Buffering():
        borderWidth /= bin
        for s in foot.getSpans():
            y, x0, x1 = s.getY(), s.getX0(), s.getX1()

            if origin:
                x0 += origin[0]; x1 += origin[0]
                y += origin[1]

            x0 /= bin; x1 /= bin; y /= bin

            ds9.line([(x0 - borderWidth, y - borderWidth),
                      (x0 - borderWidth, y + borderWidth),
                      (x1 + borderWidth, y + borderWidth),
                      (x1 + borderWidth, y - borderWidth),
                      (x0 - borderWidth, y - borderWidth),
                      ], frame=frame, ctype=ctype)

        if peaks:
            for p in foot.getPeaks():
                x, y = p.getIx(), p.getIy()

                if origin:
                    x += origin[0]; y += origin[1]

                x /= bin; y /= bin

                ds9.dot(symb, x, y, size=size, ctype=ctypePeak, frame=frame)
示例#30
0
    def displaySources(self, exposure, matches, reserved, frame=1):
        """Display sources we'll use for photocal

        Sources that will be actually used will be green.
        Sources reserved from the fit will be red.

        Parameters
        ----------
        exposure : `lsst.afw.image.ExposureF`
            Exposure to display.
        matches : `list` of `lsst.afw.table.RefMatch`
            Matches used for photocal.
        reserved : `numpy.ndarray` of type `bool`
            Boolean array indicating sources that are reserved.
        frame : `int`
            Frame number for display.
        """
        ds9.mtv(exposure, frame=frame, title="photocal")
        with ds9.Buffering():
            for mm, rr in zip(matches, reserved):
                x, y = mm.second.getCentroid()
                ctype = ds9.RED if rr else ds9.GREEN
                ds9.dot("o", x, y, size=4, frame=frame, ctype=ctype)