Exemplo n.º 1
0
    def testFootprintToBBoxList(self):
        """Test footprintToBBoxList"""
        region = afwGeom.Box2I(afwGeom.Point2I(0, 0), afwGeom.Extent2I(12, 10))
        foot = afwDetect.Footprint(0, region)
        for y, x0, x1 in [
            (3, 3, 5),
            (3, 7, 7),
            (4, 2, 3),
            (4, 5, 7),
            (5, 2, 3),
            (5, 5, 8),
            (6, 3, 5),
        ]:
            foot.addSpan(y, x0, x1)

        idImage = afwImage.ImageU(region.getDimensions())
        idImage.set(0)

        foot.insertIntoImage(idImage, 1)
        if display:
            ds9.mtv(idImage)

        idImageFromBBox = idImage.Factory(idImage, True)
        idImageFromBBox.set(0)
        bboxes = afwDetect.footprintToBBoxList(foot)
        for bbox in bboxes:
            x0, y0, x1, y1 = bbox.getMinX(), bbox.getMinY(), bbox.getMaxX(
            ), bbox.getMaxY()

            for y in range(y0, y1 + 1):
                for x in range(x0, x1 + 1):
                    idImageFromBBox.set(x, y, 1)

            if display:
                x0 -= 0.5
                y0 -= 0.5
                x1 += 0.5
                y1 += 0.5

                ds9.line([(x0, y0), (x1, y0), (x1, y1), (x0, y1), (x0, y0)],
                         ctype=ds9.RED)

        idImageFromBBox -= idImage  # should be blank
        stats = afwMath.makeStatistics(idImageFromBBox, afwMath.MAX)

        self.assertEqual(stats.getValue(), 0)
Exemplo n.º 2
0
    def testFootprintToBBoxList(self):
        """Test footprintToBBoxList"""
        region = lsst.geom.Box2I(lsst.geom.Point2I(0, 0),
                                 lsst.geom.Extent2I(12, 10))
        foot = afwDetect.Footprint(afwGeom.SpanSet(), region)
        spanList = [
            afwGeom.Span(*span)
            for span in ((3, 3, 5), (3, 7, 7), (4, 2, 3), (4, 5, 7), (5, 2, 3),
                         (5, 5, 8), (6, 3, 5))
        ]
        foot.spans = afwGeom.SpanSet(spanList)

        idImage = afwImage.ImageU(region.getDimensions())
        idImage.set(0)

        foot.spans.setImage(idImage, 1)
        if display:
            disp = afwDisplay.Display(frame=1)
            disp.mtv(idImage, title=self._testMethodName + " image")

        idImageFromBBox = idImage.Factory(idImage, True)
        idImageFromBBox.set(0)
        bboxes = afwDetect.footprintToBBoxList(foot)
        for bbox in bboxes:
            x0, y0, x1, y1 = bbox.getMinX(), bbox.getMinY(), \
                bbox.getMaxX(), bbox.getMaxY()

            for y in range(y0, y1 + 1):
                for x in range(x0, x1 + 1):
                    idImageFromBBox[x, y, afwImage.LOCAL] = 1

            if display:
                x0 -= 0.5
                y0 -= 0.5
                x1 += 0.5
                y1 += 0.5

                disp.line([(x0, y0), (x1, y0), (x1, y1), (x0, y1), (x0, y0)],
                          ctype=afwDisplay.RED)

        idImageFromBBox -= idImage  # should be blank
        stats = afwMath.makeStatistics(idImageFromBBox, afwMath.MAX)

        self.assertEqual(stats.getValue(), 0)
Exemplo n.º 3
0
def defectListFromFootprintList(fpList):
    """Compute a defect list from a footprint list, optionally growing the footprints.

    Parameters
    ----------
    fpList : `list` of `lsst.afw.detection.Footprint`
        Footprint list to process.

    Returns
    -------
    defectList : `list` of `lsst.afw.meas.algorithms.Defect`
        List of defects.
    """
    defectList = []
    for fp in fpList:
        for bbox in afwDetection.footprintToBBoxList(fp):
            defect = measAlg.Defect(bbox)
            defectList.append(defect)
    return defectList
Exemplo n.º 4
0
def defectListFromFootprintList(fpList, growFootprints=1):
    """Compute a defect list from a footprint list, optionally growing the footprints

    @param[in] fpList  footprint list
    @param[in] growFootprints  amount by which to grow footprints of detected regions
    @return meas.algorithms.DefectListT
    """
    defectList = measAlg.DefectListT()
    for fp in fpList:
        if growFootprints > 0:
            # if "True", growing requires a convolution
            # if "False", its faster
            fpGrow = afwDetection.growFootprint(fp, growFootprints, False)
        else:
            fpGrow = fp
        for bbox in afwDetection.footprintToBBoxList(fpGrow):
            defect = measAlg.Defect(bbox)
            defectList.push_back(defect)
    return defectList
Exemplo n.º 5
0
def defectListFromFootprintList(fpList, growFootprints=1):
    """Compute a defect list from a footprint list, optionally growing the footprints

    @param[in] fpList  footprint list
    @param[in] growFootprints  amount by which to grow footprints of detected regions
    @return meas.algorithms.DefectListT
    """
    defectList = measAlg.DefectListT()
    for fp in fpList:
        if growFootprints > 0:
            # if "True", growing requires a convolution
            # if "False", its faster
            fpGrow = afwDetection.growFootprint(fp, growFootprints, False)
        else:
            fpGrow = fp
        for bbox in afwDetection.footprintToBBoxList(fpGrow):
            defect = measAlg.Defect(bbox)
            defectList.push_back(defect)
    return defectList
Exemplo n.º 6
0
def defectListFromFootprintList(fpList, growFootprints=1):
    """Compute a defect list from a footprint list, optionally growing the footprints

    @param[in] fpList  footprint list
    @param[in] growFootprints  amount by which to grow footprints of detected regions
    @return a list of defects (meas.algorithms.Defect)
    """
    defectList = []
    for fp in fpList:
        if growFootprints > 0:
            # if "True", growing requires a convolution
            # if "False", its faster
            tempSpans = fp.spans.dilated(growFootprints,
                                         afwGeom.Stencil.MANHATTAN)
            fpGrow = afwDetection.Footprint(tempSpans, fp.getRegion())
        else:
            fpGrow = fp
        for bbox in afwDetection.footprintToBBoxList(fpGrow):
            defect = measAlg.Defect(bbox)
            defectList.append(defect)
    return defectList
Exemplo n.º 7
0
    def testFootprintToBBoxList(self):
        """Test footprintToBBoxList"""
        region = afwGeom.Box2I(afwGeom.Point2I(0,0), afwGeom.Extent2I(12,10))
        foot = afwDetect.Footprint(0, region)
        for y, x0, x1 in [(3, 3, 5), (3, 7, 7),
                          (4, 2, 3), (4, 5, 7),
                          (5, 2, 3), (5, 5, 8),
                          (6, 3, 5),
                          ]:
            foot.addSpan(y, x0, x1)

        idImage = afwImage.ImageU(region.getDimensions())
        idImage.set(0)

        foot.insertIntoImage(idImage, 1)
        if display:
            ds9.mtv(idImage)

        idImageFromBBox = idImage.Factory(idImage, True)
        idImageFromBBox.set(0)
        bboxes = afwDetect.footprintToBBoxList(foot)
        for bbox in bboxes:
            x0, y0, x1, y1 = bbox.getMinX(), bbox.getMinY(), bbox.getMaxX(), bbox.getMaxY()

            for y in range(y0, y1 + 1):
                for x in range(x0, x1 + 1):
                    idImageFromBBox.set(x, y, 1)

            if display:
                x0 -= 0.5
                y0 -= 0.5
                x1 += 0.5
                y1 += 0.5

                ds9.line([(x0, y0), (x1, y0), (x1, y1), (x0, y1), (x0, y0)], ctype=ds9.RED)

        idImageFromBBox -= idImage      # should be blank
        stats = afwMath.makeStatistics(idImageFromBBox, afwMath.MAX)

        self.assertEqual(stats.getValue(), 0)
Exemplo n.º 8
0
im = mi.getImage()
arr = im.getArray()
deadidx = numpy.where(arr == 0.)
hotidx = numpy.where(arr > 1.1)
arr[deadidx] = 2.
arr[hotidx] = 3.
im2 = ai.makeImageFromArray(arr)
thresh = afwDetection.Threshold(1.1)
fs = afwDetection.FootprintSet(im2, thresh)
x0 = []
y0 = []
width = []
height = []
for f in fs.getFootprints():
    for bbox in afwDetection.footprintToBBoxList(f):
        bbox = cameraGeom.rotateBBoxBy90(bbox, 3, im.getBBox().getDimensions())
        x0.append(bbox.getMinX())
        y0.append(bbox.getMinY())
        width.append(bbox.getWidth())
        height.append(bbox.getHeight())

head = fits.Header()
cmap = {'A': (0, 0), 'B': (0, 1)}
if ha is not None:
    head.update('SERIAL', int('%i%i%i%i%i%i' %
                              (rx, ry, sx, sy, cmap[ha][0], cmap[ha][1])), 'Serial of the sensor')
    head.update('NAME', 'R:%i,%i S:%i,%i,%c'%(rx, ry, sx, sy, ha), 'Name of sensor for this defect map')
else:
    head.update('SERIAL', int('%i%i%i%i'%(rx, ry, sx, sy)), 'Serial of the sensor')
    head.update('NAME', 'R:%i,%i S:%i,%i'%(rx, ry, sx, sy), 'Name of sensor for this defect map')
Exemplo n.º 9
0
def makeBBList(mask, ccd):

    # Create a bounding box corresponding to the useful part of the CCD
    # (exclude overscan regions)
    bb = geom.Box2I(geom.Point2I(32, 0), geom.Point2I(2079, 4611))
    # Read mask file provided by Elixir team
    im = afwImage.ImageF('%s.fits[' % mask + str(ccd + 1) + ']',
                         bbox=bb,
                         origin=afwImage.ImageOrigin.PARENT)
    # Pixel values in mask files are 1 for background and 0 for bad pixels
    # - Need to inverse this
    im *= -1.
    im += 1.
    im *= 10.

    level = 2
    s = afwDetect.FootprintSet(im, afwDetect.Threshold(level, polarity=True))

    keys = ['x', 'y', 'w', 'h']
    defect = {k: [] for k in keys}
    defectE = {k: [] for k in keys}

    for f in s.getFootprints():
        fpl = afwDetect.footprintToBBoxList(f)
        for i in fpl:
            i.shift(geom.Extent2I(-32, 0))

            x0 = i.getBeginX()
            y0 = i.getBeginY()
            w0 = i.getWidth()
            h0 = i.getHeight()
            defect['x'].append(x0)
            defect['y'].append(y0)
            defect['w'].append(w0)
            defect['h'].append(h0)

            if (x0 % 2 == 0):
                x1 = x0
                if (w0 % 2 == 0):
                    w1 = w0
                else:
                    w1 = w0 + 1
            else:
                x1 = max(x0 - 1, 0)
                if (w0 % 2 == 0):
                    w1 = min(w0 + 2, 2048)
                else:
                    w1 = min(w0 + 1, 2048)
            if (y0 % 2 == 0):
                y1 = y0
                if (h0 % 2 == 0):
                    h1 = h0
                else:
                    h1 = min(h0 + 1, 4612)
            else:
                y1 = max(y0 - 1, 0)
                if (h0 % 2 == 0):
                    h1 = min(h0 + 2, 4612)
                else:
                    h1 = min(h0 + 1, 4612)

            defectE['x'].append(x1)
            defectE['y'].append(y1)
            defectE['w'].append(w1)
            defectE['h'].append(h1)

    return defect, defectE
Exemplo n.º 10
0
def findMatchingFootprints(eIm, eHDUList, wcs, ra, dec, rmags, baRatio, objId, option, a_disk, b_disk, a_bulge, b_bulge, diskFluxNorm, bulgeFluxNorm, pa_d, raEdge, decEdge, dxMin, dyMin, matchArcsec, plotno, ePath):
   # Get the set of footprints from the FITS image, setting the 
   # threshold by either count value or STDEV.  footprintsP is the list
   # of positive footprints for that particular FITS file, con-
   # sisting of a set of pixels.  getFootprints() returns the
   # footprints of detected objects.
   # Don't set the detection limit too bright, or sources will
   #  sometimes be missed. 
   detSetP = afwDetection.makeFootprintSet(
       eIm, afwDetection.createThreshold(2., 'value'))
       #eIm, afwDetection.createThreshold(28., 'stdev'))
   footprintsP = detSetP.getFootprints()
   nf = len(footprintsP)
   b1 = 1.999*1 - 0.327
   b4 = 1.999*4 - 0.327
   detxs = []; detys = []; nCts = []; estSizePix = []
   detMinx = []; detMaxx = []; detMiny = []; detMaxy = []
   detMaxRad2 = []
   n = 0; boxSize = 2
   minCtsBrightThresh = 1000
   #print 'Considering %i positive footprints.' % len(footprintsP)
   for fp in footprintsP:
      if n % 10000 == 0: print '%i of %i positive footprints analyzed.' % (n, nf)
      # Return "a list of BBoxs whose union contains exactly the pixels in
      # foot, neither more or less."
      # This looks at each boundary box in the list of boundary boxes (bboxes)
      # and gets the minimum and maximum x and y values of the list of coordinates,
      # and calculates the x and y lengths of the boundary box (dx, dy).
      # Lots of times they're only 1 pixel in length.  fAllFPP is a file
      # containing the center x,y coordinates of each footprint, as well as dx and dy.
      # minx, maxx, miny, and maxy will be the very minimum and maximum values of
      # all the footprints for all the boundary boxes in the list.  Create a
      # rectangular footprint:
      bboxes = afwDetection.footprintToBBoxList(fp)
      minx = 1e100; maxx = -1e100; miny = 1e100; maxy = -1e100
      for bbox in bboxes:
         x0, y0 = bbox.getMinX(), bbox.getMinY()
         x1, y1 = bbox.getMaxX(), bbox.getMaxY()
         dx = x1 - x0; dy = y1 - y0
         minx = min([minx, x0, x1]); maxx = max([maxx, x0, x1])
         miny = min([miny, y0, y1]); maxy = max([maxy, y0, y1])

      oldminx = minx; oldmaxx = maxx
      oldminy = miny; oldmaxy = maxy
      # The footprint regions are sometimes skewed, so center them
      #  as best we can by finding the maximum pixel and then weighting
      #  around that.
      # eIm.get(x,y) returns the number of counts (t0) in that pixel.
      # DS9 uses 1-based coords, so add 1
      highPixx = -1; highPixy = -1; highPixVal = -1.e100
      for x in range(minx, maxx+1):
         for y in range(miny, maxy+1):
            t0 = eIm.get(x, y)
            if t0 > highPixVal:
               highPixx = x; highPixy = y; highPixVal = t0
      # Now we know the max pixel.  Work in an aperture around it.  Use the
      #  footprints to set the maximum extent of the aperture.
      # Check to make sure the distance of the pixel in question is equal
      # to or less that the maximum radius of the aperture.
      # ctsWtSumx(or y) is the weighted center coordinate of the object 
      # in the  x (or y) direction.
      # detxs is a list of ctsWtSumx for each footprint.
      # Only keep the eImages that are above a minimum brightness threshold
      # and above a minimum x or y width in terms of pixels.
      tCts = 0; ctsWtSumx = 0; ctsWtSumy = 0; nPix = 0
      t0 = (maxx - highPixx)**2
      t1 = (minx - highPixx)**2
      maxx2 = max(t0, t1)
      t0 = (maxy - highPixy)**2
      t1 = (miny - highPixy)**2
      maxy2 = max(t0, t1)
      maxRad2 = maxx2 + maxy2
      dx = abs(maxx - minx)
      dy = abs(maxy - miny)
      if dx >= dxMin or dy >= dyMin:
         for x in range(minx, maxx+1):
            for y in range(miny, maxy+1):
               r2 = (x-highPixx)**2 + (y-highPixy)**2
               if r2 > maxRad2: continue
               t0 = eIm.get(x, y)
               tCts += t0
               ctsWtSumx += x * t0; ctsWtSumy += y * t0
               nPix += 1
         if tCts > minCtsBrightThresh:
            ctsWtSumx /= float(tCts); ctsWtSumy /= float(tCts)
            # Now iterate it again over a smaller region to improve
            # your chances of hitting the center.
            minx = int(ctsWtSumx - dx/5.); maxx = int(ctsWtSumx + dx/5.)
            miny = int(ctsWtSumy - dy/5.); maxy = int(ctsWtSumy + dy/5.)
            if maxx > 3999: maxx = 3999
            if minx < 1: minx = 0
            if maxy > 4071: maxy = 4071
            if miny < 1: miny = 0

            highPixx = -1; highPixy = -1; highPixVal = -1.e100
            for x in range(minx, maxx+1):
               for y in range(miny, maxy+1):
                  t0 = eIm.get(x, y)
                  if t0 > highPixVal:
                     highPixx = x; highPixy = y; highPixVal = t0

            tCts = 0; ctsWtSumx = 0; ctsWtSumy = 0; nPix = 0
            t0 = (maxx - highPixx)**2
            t1 = (minx - highPixx)**2
            maxx2 = max(t0, t1)
            t0 = (maxy - highPixy)**2
            t1 = (miny - highPixy)**2
            maxy2 = max(t0, t1)
            maxRad2 = maxx2 + maxy2
            for x in range(minx, maxx+1):
               for y in range(miny, maxy+1):
                  r2 = (x-highPixx)**2 + (y-highPixy)**2
                  if r2 > maxRad2: continue
                  t0 = eIm.get(x, y)
                  tCts += t0
                  ctsWtSumx += x * t0; ctsWtSumy += y * t0
                  nPix += 1
            ctsWtSumx /= float(tCts); ctsWtSumy /= float(tCts)
            minx = oldminx
            maxx = oldmaxx
            miny = oldminy
            maxy = oldmaxy
            t0 = (maxx - ctsWtSumx)**2
            t1 = (minx - ctsWtSumx)**2
            maxx2 = max(t0, t1)
            t0 = (maxy - ctsWtSumy)**2
            t1 = (miny - ctsWtSumy)**2
            maxy2 = max(t0, t1)
            maxRad2 = maxx2 + maxy2

            detxs.append(ctsWtSumx); detys.append(ctsWtSumy)
            nCts.append(tCts); estSizePix.append(nPix)
            detMinx.append(int(ctsWtSumx-dx/2.)); detMaxx.append(int(ctsWtSumx+dx/2.))
            detMiny.append(int(ctsWtSumy-dy/2.)); detMaxy.append(int(ctsWtSumy+dy/2.)) 
            detMaxRad2.append(maxRad2)
      n += 1

   # At this point you have data for bright enough, wide enough footprints.
   detxs = numpy.array(detxs); detys = numpy.array(detys)
   nCts = numpy.array(nCts); estSizePix = numpy.array(estSizePix)
   detMinx = numpy.array(detMinx); detMaxx = numpy.array(detMaxx)
   detMiny = numpy.array(detMiny); detMaxy = numpy.array(detMaxy)

   #brightRAs = numpy.zeros(len(detxs))
   #brightDecs = numpy.zeros(len(detxs))
   brightRAs = wcs.pixelToSky(detxs, detys).getPosition()[0]
   brightDecs = wcs.pixelToSky(detxs, detys).getPosition()[1]
        

   # for each value of your original coordinates of interest,
   # create a list (t0) of the square of the distance between each bright
   # coordinate and the galaxy coordinates.  t1 is the index of the minimum distance
   # squared, so t0[t1] is the minimum distance squared. The match to your
   # coordinates is brightRAs[t1] and BrightDecs[t1].
   #matchDistArcsec = numpy.zeros(len(ra))id
   psi = []
   psiFit = []
   psiCatRaDec = []
   psiCatXY = []
   psiImageRaDec = []
   psiImageXY = []
   pa_d = []
   aFit = []
   bFit = []
   baRatioFit = []
   idx = []
   tidx = []
   distArcsec = []
   gal_code = ['Lowba_bulge_Only', 'Lowba_disk_Only', 'Lowba_bulge_and_Disk']
   #gal_code = ['Bulge_Only', 'Disk_Only', 'Bulge_and_Disk']
   for i in range(len(ra)):
      # Assuming distance is small, keep it linear
      t0 = (brightRAs - ra[i])**2 + (brightDecs - dec[i])**2
      t1 = numpy.argmin(t0)
      diffArcsec = numpy.sqrt(t0[t1]) * 3600.
      if diffArcsec <= matchArcsec:
         idx.append(i)
         tidx.append(t1)
         distArcsec.append(diffArcsec)
           
   ra = ra[idx]
   dec = dec[idx]
   raEdge = raEdge[idx]
   decEdge = decEdge[idx]
   raCat = raEdge - ra
   decCat = decEdge - dec
   psiCatRaDec.append(positionAngle(raCat, decCat))

   xyCtrCat = wcs.skyToPixel(ra, dec)
   xCtrCat, yCtrCat = xyCtrCat
   xyPixPos = wcs.skyToPixel(raEdge, decEdge)
   xPixPos, yPixPos = xyPixPos

   xCat = xPixPos - xCtrCat
   yCat = yPixPos - yCtrCat
   psiCatXY.append(positionAngle(xCat, yCat))

   distArcsec = numpy.array(distArcsec)
   brightRAs = brightRAs[tidx]
   brightDecs = brightDecs[tidx]
   ra = ra[idx]
   dec = dec[idx]
   raEdge = raEdge[idx]
   decEdge = decEdge[idx]
   detMinx = detMinx[tidx]
   detMaxx = detMaxx[tidx]
   detMiny = detMiny[tidx]
   detMaxy = detMaxy[tidx]
   xwidth = abs(detMaxx - detMinx)
   ywidth = abs(detMaxy - detMiny)
   detxs = detxs[tidx]
   detys = detys[tidx]
   pa_d = pa_d[idx]
   Rad2Max = max((xwidth/2.)**2, (ywidth/2.)**2)
   nbins = int(max(xwidth/2., ywidth/2.))
   rmags = rmags[idx]
   baRatio = baRatio[idx]
   option = option[idx]
   objId = objId[idx]
   a_disk = a_disk[idx]
   b_disk = b_disk[idx]
   a_bulge = a_bulge[idx]          #for m in range(nbins[i]):
   b_bulge = b_bulge[idx]
   diskFluxNorm = diskFluxNorm[idx]
   bulgeFluxNorm = bulgeFluxNorm[idx]

   # Now you've got the object and its radius.  To calculate the flux as a
   # function of radius, I(r), break the radius squared into multiple segments
   # and bin the number of counts.  Then divide the total number of counts
   # in each bin by the area, if you want. 
   print 'len(detxs), len(objId), len(rmags), len(a_disk), len(detMinx), len(detMaxy): '
   print len(detxs), len(objId), len(rmags), len(a_disk), len(detMinx), len(detMaxy)
   for i in range(len(detxs)): 
      if i != -1:
         print 'Galaxy ID:  ', objId[i]
         print 'rmags:   ', rmags[i]
         print 'a_disk:  ', a_disk[i]
         print 'b_disk:  ', b_disk[i]
         print 'a_bulge: ', a_bulge[i]
         print 'b_bulge: ', b_bulge[i]
         print 'diskFluxNorm:  ', diskFluxNorm[i]
         print 'bulgeFluxNorm:  ', bulgeFluxNorm[i]
         print 'detMinx:  ', detMinx[i]
         print 'detMaxx:  ', detMaxx[i]
         print 'detMiny:  ', detMiny[i]
         print 'detMaxy:  ', detMaxy[i]
         print 'pa_d: ', pa_d[i]
         print 'detxs:  ', detxs[i]
         print 'detys:  ', detys[i]
         print 'ra (cat): ', ra[i]
         print 'dec (cat): ', dec[i]
         print 'raEdge, decEdge: ', raEdge[i], decEdge[i]
         print 'psiCatXY: xPixPos, xCtrCat, yPixPos, yCtrCat'
         print xPixPos[i], xCtrCat[i], yPixPos[i], yCtrCat[i]
         tCts = numpy.zeros(nbins[i])
         I_R = numpy.zeros(nbins[i])
         nPix = numpy.zeros(nbins[i])
         mew = numpy.zeros(nbins[i])
         rErr = numpy.zeros(nbins[i])
         Err_Up = numpy.zeros(nbins[i])
         Err_Dn = numpy.zeros(nbins[i])
         a2Bin = numpy.zeros(nbins[i])
         aBin = numpy.zeros(nbins[i])
         AveABin = numpy.zeros(nbins[i])
         xBdry = []
         yBdry = []
         ellipticity = b_disk[i]/a_disk[i]

         # Create an image plot for each footprint.
         C = numpy.zeros(((detMaxy[i]-detMiny[i]+1), (detMaxx[i]-detMinx[i]+1)), numpy.int)
         for y in range (detMiny[i], detMaxy[i], 1):
            for x in range(detMinx[i], detMaxx[i], 1):
               C[y-detMiny[i], x-detMinx[i]] = eIm.get(x,y)

         # Find the boundaries of an eimage using the pixel count threshold
         # as the discriminator.  Break the eimage into anglar bins (say, 
         # 50,so the distant outliers are less likely to be included)and
         # select the minimum value in each bin.  The original purpose was
         # to get data points for fitting ellipses to galactic disks.

         n = 50
         deltaAng = 2.*math.pi/float(n)
         xBdry = []
         yBdry = []          
         theta = []          
         radDist2 = []
         xVal = []
         yVal = []
         angleDeg = []
         for j in range(n):
            radDist2.append([])
            xVal.append([])
            yVal.append([])
            angleDeg.append([])

         # This section is devoted to finding psi, the angle of 
         # the ellipse's rotation CCW with respect to the positive
         # x-axis
         countMin = 12
         count = 0
         for x in range(detMinx[i] + 1, detMaxx[i]-1, 1):
            xp = float(x - detMinx[i])
            for y in range(detMiny[i], detMaxy[i], 1):
               yp = float(y - detMiny[i])
               if C[yp, xp] < countMin:
                  if C[yp, xp-1] < countMin or C[yp, xp+1] < countMin:
                     y0 = float(y) - detys[i]
                     x0 = float(x) - detxs[i]
                     Angle = xyPosAngle(x0, y0)
                     m = int(Angle/deltaAng)
                     radDist2[m].append(x0**2 + y0**2)
                     xVal[m].append(xp)
                     yVal[m].append(yp)
                     angleDeg[m].append(Angle*180./math.pi)

         for j in range(n):
            if len(radDist2[j]) >= 1.:
               t1 = numpy.argmin(radDist2[j])
               xBdry.append(xVal[j][t1])
               yBdry.append(yVal[j][t1])
               theta.append(angleDeg[j][t1])
                
         z, a, b, psiAve = fitellipse([xBdry, yBdry])
         aFit.append(a)
         bFit.append(b)
         if a >= b and a != None and b !=None:
            baRatioFit.append(b/a)
         elif b > a and a != None and b !=None:
            baRatioFit.append(a/b)
         else:
            baRatioFit.append(None)
         if psiAve != None:
            psiFit.append(float(psiAve)*180./math.pi)
         else:
            psiFit.append(None)
         print 'psiFit:  ', psiFit[i]
         if a and b and psiAve and z != None:
            xEllipse, yEllipse = ellipse(aFit[-1], bFit[-1], psiAve, detxs[i]-detMinx[i], detys[i]-detMiny[i])
            daMax2 = a*a/float(nbins[i])
         else:
            print 'a, b, psiAve, or z = None for i = ', i, a, b, psiAve, z
            psiImageXY.append(None)
            psiImageRaDec.append(None)
            print 'psiImageXY, psiImageRaDec: ', psiImageXY[i], psiImageRaDec[i]
            continue
         xMajor = aFit[-1]*math.cos(psiAve) + detxs[i]-detMinx[i]
         yMajor = aFit[-1]*math.sin(psiAve) + detys[i]-detMiny[i]
         print 'xMajor, yMajor = ', xMajor, yMajor

         x0 = xMajor - detxs[i]
         y0 = yMajor - detys[i]
         psiImageXY.append(positionAngle(x0, y0))
          
         ra3 = wcs.pixelToSky(xMajor, yMajor).getPosition()[0]
         dec3 = wcs.pixelToSky(xMajor, yMajor).getPosition()[1]
         print 'ra3, brightRAs[i], dec3, brightDecs[i] = ', ra3, brightRAs[i], brightDecs[i], dec3
         xyMajor3 = wcs.skyToPixel(ra3, dec3)
         xMajor3, yMajor3 = xyMajor3
         print "xMajor3, yMajor3 = ", xMajor3, yMajor3
         xyMajor2 = wcs.skyToPixel(raEdge[i], decEdge[i])
         xMajor2, yMajor2 = xyMajor2
         print 'brightRAs[i], brightDecs[i]:'
         print brightRAs[i], brightDecs[i]
         ra0 = ra3 - brightRAs[i]
         dec0 = dec3 - brightDecs[i]
         psiImageRaDec.append(positionAngle(ra0, dec0))
             
         t0 = 0.
         for m in range(nbins[i]):
            t0 += daMax2
            a2Bin[m] = t0
            aBin[m] = math.sqrt(t0)

         AveABin[0] = 10.**(math.log10(aBin[0])/2.)
         for m in range(nbins[i]-1):
            Ave = (math.log10(aBin[m+1]) + math.log10(aBin[m]))/2.
            AveABin[m+1] = 10.**Ave

         xbin = []
         ybin = []
         for x in range(detMinx[i], detMaxx[i]+1):
            for y in range(detMiny[i], detMaxy[i]+1):
               xprime = x - detxs[i]
               yprime = y - detys[i]
               aXY2 = (xprime*math.cos(psiAve) + yprime*math.sin(psiAve
                       ))**2 + (xprime*math.sin(psiAve) 
                       - yprime*math.cos(psiAve)/(b/a))**2
               if aXY2 > a*a: continue
               nval = min(int(aXY2/daMax2), nbins[i]-1)
               tCts[nval] += eIm.get(x,y)
               nPix[nval] += 1
               if nval <= 4:
                  xbin.append(x - detMinx[i])
                  ybin.append(y - detMiny[i])
         sumCts = 0
         sumPix = 0
         for m in range(nbins[i]):
            sumCts += tCts[m]
            sumPix += nPix[m]
            #mew, the mean, is in counts/pixel
            mew[m] = tCts[m]/nPix[m]
         for m in range(nbins[i]): 
            # I(R) in units of counts per square arcsec: 
            if mew[m] == 0:
               I_R[m] = numpy.nan
            else:
               I_R[m] = mew[m]/.04
               rErr[m] = math.sqrt(tCts[m])/nPix[m]/.04
         I_Reff = max(I_R)/math.e
         for m in range(nbins[i]):
            if I_R[m] < I_Reff:
               R_eff = 10**(math.log10(AveABin[m]) - (math.log10(I_R[m]) - math.log10(I_Reff))/(math.log10(I_R[m]) - math.log10(I_R[m-1]))*(math.log10(AveABin[m]) - math.log10(AveABin[m-1]))) 
               break 
         print 'xwidth, ywidth (in pixels) = ', abs(detMaxx[i] - detMinx[i]), abs(detMaxy[i] - detMiny[i])
         print 'Total Counts = %i, Total Pixels = %i' % (sumCts, sumPix)
         print 'log_Radius(") log_Intensity   n = 1 and 4      n = 1        n = 4    Pixels   Counts  Mean   Sigma'
         #Prepare Sersic n=1 and n = 4 model profiles for comparison
         In1 = numpy.zeros(nbins[i])
         In4 = numpy.zeros(nbins[i])
         InBoth = numpy.zeros(nbins[i])
         for m in range(nbins[i]):
           In1[m] = I_Reff*math.exp(-b1*((AveABin[m]/R_eff) - 1))
           In4[m] = I_Reff*math.exp(-b4*(((AveABin[m]/R_eff)**0.25) - 1))
           InBoth[m] = (diskFluxNorm[i]*In1[m] + bulgeFluxNorm[i]*In4[m])/(diskFluxNorm[i] + bulgeFluxNorm[i])
         for m in range(nbins[i]):
            # Convert pixels to arcsec (0.2 arcsec/pixel, roughly)
            AveABin[m] = math.log10(AveABin[m]*.2)
            if I_R[m] != None:
               Err_Up[m] = math.log10(I_R[m] + rErr[m]) - math.log10(I_R[m])
               if I_R[m] > rErr[m]:
                  Err_Dn[m] = math.log10(I_R[m]) - math.log10(I_R[m] - rErr[m])
               else:
                  Err_Dn[m] = 5
               I_R[m] = math.log10(I_R[m])
            if In1[m] != 0.: 
               In1[m] = math.log10(In1[m])
            else:
               In1[m] = numpy.nan
            if In4[m] != 0.: 
               In4[m] = math.log10(In4[m]) 
            else:
               In4[m] = numpy.nan
            if InBoth[m] != 0.: 
               InBoth[m] = math.log10(InBoth[m])
            else:
               InBoth[m] = numpy.nan
            if m > 8 and I_R[m] is 'nan' and I_R[m-1] is 'nan' and I_R[m-2] is 'nan' and I_R[m-3] is 'nan':
               nbins[i] = nbins[:(nbins[i]-m+1)]
         for m in range(nbins[i]):
            print '%11.2f %11.2f %11.2f %11.2f %11.2f  %11.2f  %11.2f %11.2f %11.2f' % (AveABin[m], I_R[m], InBoth[m], In1[m], In4[m], nPix[m], tCts[m], mew[m], rErr[m])
         fig = plt.figure()
         fig.suptitle('Galaxy %s, (ra,dec)=(%5.2f, %5.2f), %d pixels \n%d counts; Gal_ID %s R_eff = %5.2f arcsecs, PA = %5.2f deg.\n%s' %(gal_code[option[i]], brightRAs[i], brightDecs[i], sumPix, sumCts, objId[i], R_eff*.2, pa_d[i], ePath), fontsize=9)
         ax = fig.add_subplot(121)
         im = plt.imshow(C, aspect ='equal', origin='lower', cmap = plt.cm.gray, interpolation = 'nearest')
         cir = Circle((detxs[i]-detMinx[i],detys[i]-detMiny[i]), radius = .25, ec='r', fc = 'r')
         cir2 = Circle((xMajor, yMajor), radius = .25, ec='g', fc = 'g')
         print 'semi-major axis direction at (', xMajor, ', ', yMajor, ')'
         ax.add_patch(cir)
         ax.add_patch(cir2)
         line5, = ax.plot(xBdry, yBdry, 'r.')
         line6, = ax.plot(xEllipse, yEllipse, 'm.')
         line7, = ax.plot(xbin, ybin, 'y.')
         xcolname = 'log [Radius (arcsec)]'
         ycolname = 'Intensity (Log_10[Counts/Area])'
         ax2 = fig.add_subplot(122)
         plt.xlabel(xcolname, fontsize=10)
         plt.ylabel(ycolname, fontsize=10)
         line1 = ax2.errorbar(AveABin, I_R, yerr=[Err_Dn, Err_Up], fmt = 'bo', ms = 2)
         line2, = ax2.plot(AveABin, In1, 'm--')
         line3, = ax2.plot(AveABin, In4, 'g-.')
         line4, = ax2.plot(AveABin, InBoth, 'r-')
         props = font_manager.FontProperties(size=12)
         leg = ax2.legend([line1[0], line2, line3, line4], ['eImage', 'n=1', 'n=4', 'n=1+4'], loc='upper right', prop=props)
         plt.text(0.1, 0.1, 'r = %5.2f\nb/a = %5.3f' % (rmags[i], baRatio[i]), transform = ax2.transAxes)
         plt.savefig('%s/Sers70cM12%sh.png' % (gal_code[option[i]], objId[i]), format = 'png')
         plotno += 1
         plt.clf()
   print 'Length of the following variables:'
   print len(detxs), len(detys), len(xPixPos), len(yPixPos), len(psiImageXY), len(psiImageRaDec), len(psiCatXY), len(psiCatRaDec), len(psiFit), len(a_disk), len(b_disk), len(aFit), len(bFit)
   print 'objId    ra2-raEdge  dec2-decEdge   detxs   detys  xPixPos   yPixPos    a_disk b_disk   a     b b/a catalog  b/a fit'
   for i in range(len(detxs)):
      if aFit[i] and bFit[i] and a_disk[i] and b_disk[i] and psiFit[i] != None:
         print '%8i  %7.2e %7.2e %7.2f %7.2f %7.2f %7.2f %7.2f %7.2f %7.2f %7.2f %7.2f %7.2f' % (objId[i], 
                ra2[i]-raEdge[i], dec2[i]-decEdge[i], detxs[i], 
                detys[i], xPixPos[i], yPixPos[i], a_disk[i], b_disk[i], aFit[i], bFit[i],
                b_disk[i]/a_disk[i], bFit[i]/aFit[i])
   print 'objId   pa_d psiCatRD psiImRD   psiCatXY  psiImXY  psiFit  b/a cat  b/a fit'
   for i in range(len(detxs)):
      if aFit[i] and bFit[i] and a_disk[i] and b_disk[i] and psiFit[i] != None:
         print '%8i  %7.2f %7.2f %7.2f %7.2f %7.2f %7.2f %7.2f  %7.2f' % (objId[i], pa_d[i], psiCatRaDec[i], psiImageRaDec[i], psiCatXY[i], psiImageXY[i], psiFit[i], b_disk[i]/a_disk[i], bFit[i]/aFit[i])
   return plotno
Exemplo n.º 11
0
im = mi.getImage()
arr = im.getArray()
deadidx = numpy.where(arr == 0.)
hotidx = numpy.where(arr > 1.1)
arr[deadidx] = 2.
arr[hotidx] = 3.
im2 = ai.makeImageFromArray(arr)
thresh = afwDetection.Threshold(1.1)
fs = afwDetection.FootprintSet(im2, thresh)
x0 = []
y0 = []
width = []
height = []
for f in fs.getFootprints():
    for bbox in afwDetection.footprintToBBoxList(f):
        bbox = cameraGeom.rotateBBoxBy90(bbox, 3, im.getBBox().getDimensions())
        x0.append(bbox.getMinX())
        y0.append(bbox.getMinY())
        width.append(bbox.getWidth())
        height.append(bbox.getHeight())

head = pyfits.Header()
cmap = {'A': (0, 0), 'B': (0, 1)}
if ha is not None:
    head.update(
        'SERIAL',
        int('%i%i%i%i%i%i' % (rx, ry, sx, sy, cmap[ha][0], cmap[ha][1])),
        'Serial of the sensor')
    head.update('NAME', 'R:%i,%i S:%i,%i,%c' % (rx, ry, sx, sy, ha),
                'Name of sensor for this defect map')
    if len(footprintsN) > 0:
        raise RuntimeError, '*** Unexpected negative source.'
    else: print '   No negative footprints found, as expected.'

regOut = open(outDir + 'pDet.reg', 'w')
print 'Making positive footprint detections.'
detSetP = afwDetection.makeFootprintSet(useEImForBG, afwDetection.createThreshold(5, "stdev"))
footprintsP = detSetP.getFootprints()
nf = len(footprintsP)
detxs = []; detys = []; nCts = []; estSizePix = []
n = 0; boxSize = 2; circleSize = 20
print 'Considering %i positive footprints.' % len(footprintsP)
fAllFPP = open(outDir + 'fAllFPP.reg', 'w')
for fp in footprintsP:
    if n % 10000 == 0: print '%i of %i done.' % (n, nf)
    bboxes = afwDetection.footprintToBBoxList(fp)
    tCts = 0; ctsWtSumx = 0; ctsWtSumy = 0; nPix = 0
    for bbox in bboxes:
        x0, y0, x1, y1 = bbox.getX0(), bbox.getY0(), bbox.getX1(), bbox.getY1()
        dx = x1 - x0; dy = y1 - y0
        fAllFPP.write('box %5.3f %5.3f %5.3f %5.3f #color=yellow\n' % (
            min([x0,x1])+0.5*dx, min([y0,y1])+0.5*dy, dx, dy))
        for x in range(x0, x1 + 1):
            for y in range(y0, y1 + 1):
                t0 = eIm.get(x, y)
                tCts += t0
                ctsWtSumx += 0.5*(x0 + x1) * t0
                ctsWtSumy += 0.5*(y0 + y1) * t0
                nPix += 1
    ctsWtSumx /= float(tCts); ctsWtSumy /= float(tCts)
    #regOut.write('box %5.5f %5.5f %i %i 0 # color=darkgoldenrod2\n' % (ctsWtSumx, ctsWtSumy, boxSize, boxSize))
Exemplo n.º 13
0
def makeBBList(mask, ccd):

    # Create a bounding box corresponding to the useful part of the CCD (exclude overscan regions)
    bb = afwGeom.Box2I(afwGeom.Point2I(32, 0), afwGeom.Point2I(2079, 4611))
    # Read mask file provided by Elixir team
    im = afwImage.ImageF('%s.fits['%mask + str(ccd+1) + ']', bbox=bb, origin=afwImage.ImageOrigin.PARENT)
    # Pixel values in mask files are 1 for background and 0 for bad pixels - Need to inverse this
    im *= -1.
    im += 1.
    im *= 10.

    level = 2
    s = afwDetect.FootprintSet(im, afwDetect.Threshold(level, polarity=True))

    keys = ['x', 'y', 'w', 'h']
    defect = {k: [] for k in keys}
    defectE = {k: [] for k in keys}

    for f in s.getFootprints():
        fpl = afwDetect.footprintToBBoxList(f)
        for i in fpl:
            i.shift(afwGeom.Extent2I(-32, 0))

            x0 = i.getBeginX()
            y0 = i.getBeginY()
            w0 = i.getWidth()
            h0 = i.getHeight()
            defect['x'].append(x0)
            defect['y'].append(y0)
            defect['w'].append(w0)
            defect['h'].append(h0)

            if (x0 % 2 == 0):
                x1 = x0
                if (w0 % 2 == 0):
                    w1 = w0
                else:
                    w1 = w0 + 1
            else:
                x1 = max(x0 - 1, 0)
                if (w0 % 2 == 0):
                    w1 = min(w0 + 2, 2048)
                else:
                    w1 = min(w0 + 1, 2048)
            if (y0 % 2 == 0):
                y1 = y0
                if (h0 % 2 == 0):
                    h1 = h0
                else:
                    h1 = min(h0 + 1, 4612)
            else:
                y1 = max(y0 - 1, 0)
                if (h0 % 2 == 0):
                    h1 = min(h0 + 2, 4612)
                else:
                    h1 = min(h0 + 1, 4612)

            defectE['x'].append(x1)
            defectE['y'].append(y1)
            defectE['w'].append(w1)
            defectE['h'].append(h1)

    return defect, defectE
detSetP = afwDetection.makeFootprintSet(
    useEImForBG, afwDetection.createThreshold(5, "stdev"))
footprintsP = detSetP.getFootprints()
nf = len(footprintsP)
detxs = []
detys = []
nCts = []
estSizePix = []
n = 0
boxSize = 2
circleSize = 20
print 'Considering %i positive footprints.' % len(footprintsP)
fAllFPP = open(outDir + 'fAllFPP.reg', 'w')
for fp in footprintsP:
    if n % 10000 == 0: print '%i of %i done.' % (n, nf)
    bboxes = afwDetection.footprintToBBoxList(fp)
    tCts = 0
    ctsWtSumx = 0
    ctsWtSumy = 0
    nPix = 0
    for bbox in bboxes:
        x0, y0, x1, y1 = bbox.getX0(), bbox.getY0(), bbox.getX1(), bbox.getY1()
        dx = x1 - x0
        dy = y1 - y0
        fAllFPP.write(
            'box %5.3f %5.3f %5.3f %5.3f #color=yellow\n' %
            (min([x0, x1]) + 0.5 * dx, min([y0, y1]) + 0.5 * dy, dx, dy))
        for x in range(x0, x1 + 1):
            for y in range(y0, y1 + 1):
                t0 = eIm.get(x, y)
                tCts += t0