def testFlipI(self): parentExtent = geom.Extent2I(15, 20) x00, y00, x11, y11 = (8, 11, 13, 16) lrx00, lry00, lrx11, lry11 = (1, 11, 6, 16) tbx00, tby00, tbx11, tby11 = (8, 3, 13, 8) box0 = geom.Box2I(geom.Point2I(x00, y00), geom.Point2I(x11, y11)) box1 = geom.Box2I(geom.Point2I(x00, y00), geom.Point2I(x11, y11)) box0.flipLR(parentExtent[0]) box1.flipTB(parentExtent[1]) # test flip RL self.assertEqual(box0.getMinX(), lrx00) self.assertEqual(box0.getMinY(), lry00) self.assertEqual(box0.getMaxX(), lrx11) self.assertEqual(box0.getMaxY(), lry11) # test flip TB self.assertEqual(box1.getMinX(), tbx00) self.assertEqual(box1.getMinY(), tby00) self.assertEqual(box1.getMaxX(), tbx11) self.assertEqual(box1.getMaxY(), tby11)
def testGoodPix(self): """Demonstrate that we can goodPix information in the CoaddPsf.""" bboxSize = afwGeom.Extent2I(2000, 2000) schema = afwTable.ExposureTable.makeMinimalSchema() schema.addField("weight", type="D", doc="Coadd weight") schema.addField("goodpix", type="I", doc="Number of good pixels") mycatalog = afwTable.ExposureCatalog(schema) # Create several records, each with its own peculiar center and numGoodPixels. # Each PSF has the same shape and size, and the position offsets are small # relative to the FWHM, in order to make it easy to predict the resulting # weighted mean position. xwsum = 0 ywsum = 0 wsum = 0 for i, (xOff, yOff, numGoodPix) in enumerate(( (30.0, -20.0, 25), (32.0, -21.0, 10), (28.0, -19.0, 30), )): xwsum -= xOff * numGoodPix ywsum -= yOff * numGoodPix wsum += numGoodPix record = mycatalog.getTable().makeRecord() record.setPsf(measAlg.DoubleGaussianPsf(25, 25, 10, 1.00, 0.0)) offPix = self.crpix + afwGeom.Extent2D(xOff, yOff) wcs = afwGeom.makeSkyWcs(crpix=offPix, crval=self.crval, cdMatrix=self.cdMatrix) record.setWcs(wcs) record['weight'] = 1.0 record['id'] = i record['goodpix'] = numGoodPix record.setBBox(afwGeom.Box2I(afwGeom.Point2I(0, 0), bboxSize)) mycatalog.append(record) mypsf = measAlg.CoaddPsf(mycatalog, self.wcsref, 'weight') predPos = afwGeom.Point2D(xwsum / wsum, ywsum / wsum) self.assertPairsAlmostEqual(predPos, mypsf.getAveragePosition())
def testUndersample(self): """Test how the program handles nx,ny being too small for requested interp style. """ # make an image nx = 64 ny = 64 img = afwImage.ImageF(afwGeom.Extent2I(nx, ny)) # make a background control object bctrl = afwMath.BackgroundControl(10, 10) bctrl.setInterpStyle(afwMath.Interpolate.CUBIC_SPLINE) bctrl.setNxSample(3) bctrl.setNySample(3) if False: # INCREASE_NXNYSAMPLE is no longer supported post #2074 bctrl.setNxSample(2) bctrl.setNySample(2) # see if it adjusts the nx,ny values up to 3x3 bctrl.setUndersampleStyle(afwMath.INCREASE_NXNYSAMPLE) backobj = afwMath.makeBackground(img, bctrl) self.assertEqual(backobj.getBackgroundControl().getNxSample(), 3) self.assertEqual(backobj.getBackgroundControl().getNySample(), 3) # put nx,ny back to 2 and see if it adjusts the interp style down to linear bctrl.setNxSample(2) bctrl.setNySample(2) bctrl.setUndersampleStyle("REDUCE_INTERP_ORDER") backobj = afwMath.makeBackground(img, bctrl) backobj.getImageF() # Need to interpolate background to discover what we actually needed self.assertEqual(backobj.getAsUsedInterpStyle(), afwMath.Interpolate.LINEAR) # put interp style back up to cspline and see if it throws an exception bctrl.setUndersampleStyle("THROW_EXCEPTION") def tst(img, bctrl): backobj = afwMath.makeBackground(img, bctrl) backobj.getImageF("CUBIC_SPLINE") # only now do we see that we have too few points self.assertRaises(lsst.pex.exceptions.InvalidParameterError, tst, img, bctrl)
def testTransform(self): dims = afwGeom.Extent2I(512, 512) bbox = afwGeom.Box2I(afwGeom.Point2I(0, 0), dims) radius = 5 offset = afwGeom.Extent2D(123, 456) crval = afwCoord.Coord(0 * afwGeom.degrees, 0 * afwGeom.degrees) crpix = afwGeom.Point2D(0, 0) cdMatrix = [1.0e-5, 0.0, 0.0, 1.0e-5] source = afwImage.makeWcs(crval, crpix, *cdMatrix) target = afwImage.makeWcs(crval, crpix + offset, *cdMatrix) fpSource = afwDetect.Footprint(afwGeom.Point2I(12, 34), radius, bbox) fpTarget = fpSource.transform(source, target, bbox) self.assertEqual(len(fpSource.getSpans()), len(fpTarget.getSpans())) self.assertEqual(fpSource.getNpix(), fpTarget.getNpix()) self.assertEqual(fpSource.getArea(), fpTarget.getArea()) imSource = afwImage.ImageU(dims) fpSource.insertIntoImage(imSource, 1) imTarget = afwImage.ImageU(dims) fpTarget.insertIntoImage(imTarget, 1) subSource = imSource.Factory(imSource, fpSource.getBBox()) subTarget = imTarget.Factory(imTarget, fpTarget.getBBox()) self.assertTrue(np.all(subSource.getArray() == subTarget.getArray())) # make a bbox smaller than the target footprint bbox2 = afwGeom.Box2I(fpTarget.getBBox()) bbox2.grow(-1) fpTarget2 = fpSource.transform(source, target, bbox2) # this one clips fpTarget3 = fpSource.transform(source, target, bbox2, False) # this one doesn't self.assertTrue(bbox2.contains(fpTarget2.getBBox())) self.assertFalse(bbox2.contains(fpTarget3.getBBox())) self.assertNotEqual(fpTarget.getArea(), fpTarget2.getArea()) self.assertEqual(fpTarget.getArea(), fpTarget3.getArea())
def _bbox_for_coords(self, wcs, center_coord, width, height, units): """Returns a Box2I object representing the bounding box in pixels of the target region. @wcs: WCS object for the target region. @center_coord: ICRS RA and Dec coordinate for the center of the target region. @width: Width of the target region with units indicated by 'units' below. @height: Height of the target region with units indicated by 'units' below. @units: Units for height and width. 'pixel' or 'arcsecond' """ if units == "arcsec": # center_coord center, RA and Dec with width and height in # arcseconds width_half_a = afw_geom.Angle((width / 2.0), afw_geom.arcseconds) height_half_a = afw_geom.Angle((height / 2.0), afw_geom.arcseconds) min_ra = center_coord.getLongitude() - width_half_a min_dec = center_coord.getLatitude() - height_half_a max_ra = center_coord.getLongitude() + width_half_a max_dec = center_coord.getLatitude() + height_half_a ll_coord = afw_geom.SpherePoint(min_ra, min_dec) ll_coord_pix = wcs.skyToPixel(ll_coord) ur_coord = afw_geom.SpherePoint(max_ra, max_dec) ur_coord_pix = wcs.skyToPixel(ur_coord) p2i_min = afw_geom.Point2I(ll_coord_pix) p2i_max = afw_geom.Point2I(ur_coord_pix) bbox = afw_geom.Box2I(p2i_min, p2i_max) elif units == "pixel": # center_coord center, RA and Dec with width and height in pixels ctr_coord_pix = wcs.skyToPixel(center_coord) min_ra_pix = int(ctr_coord_pix.getX() - width // 2) min_dec_pix = int(ctr_coord_pix.getY() - height // 2) p2i = afw_geom.Point2I(min_ra_pix, min_dec_pix) bbox = afw_geom.Box2I(p2i, afw_geom.Extent2I(width, height)) else: raise Exception("invalid units {}".format(units)) return bbox
def testWriteDefect(self): """Write a Footprint as a set of Defects""" region = afwGeom.Box2I(afwGeom.Point2I(0, 0), afwGeom.Extent2I(12, 10)) spanSet = afwGeom.SpanSet([ 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 = afwDetect.Footprint(spanSet, region) openedFile = False if True: fd = open("/dev/null", "w") openedFile = True else: fd = sys.stdout afwDetectUtils.writeFootprintAsDefects(fd, foot) if openedFile: fd.close()
def testNonUnitIntervals(self): """!Test a small ramp image with non-integer increments """ for imageClass in (afwImage.ImageU, afwImage.ImageF, afwImage.ImageD): dim = afwGeom.Extent2I(7, 9) box = afwGeom.Box2I(afwGeom.Point2I(-1, 3), dim) numPix = dim[0] * dim[1] for start in (-5.1, 0, 4.3): if imageClass == afwImage.ImageU and start < 0: continue for stop in (7, 1001.5, 5.4): rampImage = makeRampImage(bbox=box, start=start, stop=stop, imageClass=imageClass) dtype = rampImage.getArray().dtype predArr = np.linspace(start, stop, num=numPix, endpoint=True, dtype=dtype) predArr.shape = (dim[1], dim[0]) self.assertImagesAlmostEqual(rampImage, predArr)
def testWeightedStack(self): """ Test statisticsStack() function when weighting by a variance plane""" sctrl = afwMath.StatisticsControl() sctrl.setWeighted(True) mimgList = [] for val in self.values: mimg = afwImage.MaskedImageF(afwGeom.Extent2I(self.nX, self.nY)) mimg.set(val, 0x0, val) mimgList.append(mimg) mimgStack = afwMath.statisticsStack(mimgList, afwMath.MEAN, sctrl) wvalues = [1.0/q for q in self.values] wmean = float(len(self.values)) / reduce(lambda x, y: x + y, wvalues) self.assertAlmostEqual( mimgStack.getImage().get(self.nX//2, self.nY//2), wmean) # Test in-place stacking afwMath.statisticsStack(mimgStack, mimgList, afwMath.MEAN, sctrl) self.assertAlmostEqual( mimgStack.getImage().get(self.nX//2, self.nY//2), wmean)
def testReadWriteXY0(self): """Test that we read and write (X0, Y0) correctly""" im = afwImage.MaskedImageF(afwGeom.Extent2I(10, 20)) x0, y0 = 1, 2 im.setXY0(x0, y0) tmpFile = "foo.fits" im.writeFits(tmpFile) im2 = im.Factory(tmpFile) self.assertEqual(im2.getX0(), x0) self.assertEqual(im2.getY0(), y0) self.assertEqual(im2.getImage().getX0(), x0) self.assertEqual(im2.getImage().getY0(), y0) self.assertEqual(im2.getMask().getX0(), x0) self.assertEqual(im2.getMask().getY0(), y0) self.assertEqual(im2.getVariance().getX0(), x0) self.assertEqual(im2.getVariance().getY0(), y0) os.remove(tmpFile)
def testMaskedImage(self): """Test image version of copyGoodPixels""" srcBBox = afwGeom.Box2I(afwGeom.Point2I(2, 17), afwGeom.Point2I(100, 101)) destBBox = afwGeom.Box2I(afwGeom.Point2I(13, 4), afwGeom.Point2I(95, 130)) destXY0 = destBBox.getMin() srcImage = self.getRandomMaskedImage(srcBBox) for badMask in (0, 3, MaxMask): destImage = self.getRandomMaskedImage(destBBox, excludeMask=badMask) destBBox = destImage.getBBox() self.basicMaskedImageTest(srcImage, destImage, badMask) for bboxStart in (destXY0, (50, 51)): for bboxDim in ((25, 36), (200, 200)): destViewBox = afwGeom.Box2I(afwGeom.Point2I(*bboxStart), afwGeom.Extent2I(*bboxDim)) destViewBox.clip(destBBox) destView = destImage.Factory(destImage, destViewBox, afwImage.PARENT, False) self.basicMaskedImageTest(srcImage, destView, badMask)
def setUp(self): self.conf = measAstrom.AstrometryConfig() # Load sample input from disk testDir = os.path.dirname(__file__) self.srcCat = afwTable.SourceCatalog.readFits( os.path.join(testDir, "data", "v695833-e0-c000.xy.fits")) self.srcCat["slot_ApFlux_fluxSigma"] = 1 self.srcCat["slot_PsfFlux_fluxSigma"] = 1 # The .xy.fits file has sources in the range ~ [0,2000],[0,4500] # which is bigger than the exposure self.bbox = afwGeom.Box2I(afwGeom.Point2I(0, 0), afwGeom.Extent2I(2048, 4612)) smallExposure = afwImage.ExposureF( os.path.join(testDir, "data", "v695833-e0-c000-a00.sci.fits")) self.exposure = afwImage.ExposureF(self.bbox) self.exposure.setWcs(smallExposure.getWcs()) self.exposure.setFilter(smallExposure.getFilter()) self.exposure.setCalib(smallExposure.getCalib()) # Set up local astrometry_net_data helper.setupAstrometryNetDataDir('photocal', rootDir=testDir)
def testImageStatisticsMask1(self): # Mask value that gets ignored maskPlane = self.policy.getStringArray("badMaskPlanes")[0] maskVal = afwImage.Mask.getPlaneBitMask(maskPlane) numArray = num.ones((20, 19)) mi = afwImage.MaskedImageF(afwGeom.Extent2I(20, 20)) for j in range(mi.getHeight()): for i in range(mi.getWidth()): val = i + 2.3 * j if i == 19: mi.set(i, j, (val, maskVal, 1)) else: mi.set(i, j, (val, 0x0, 1)) numArray[j][i] = val imstat = ipDiffim.ImageStatisticsF(self.policy) imstat.apply(mi) self.assertAlmostEqual(imstat.getMean(), numArray.mean()) # note that these don't agree exactly... self.assertAlmostEqual(imstat.getRms(), numArray.std(), 1) self.assertEqual(imstat.getNpix(), 20 * (20 - 1))
def testExactImages(self): """Confirm that kernel image at each location is correct """ desImage = afwImage.ImageD( afwGeom.Extent2I(self.kernel.getWidth(), self.kernel.getHeight())) for doNormalize in (False, True): region = mathDetail.KernelImagesForRegion(self.kernel, self.bbox, self.xy0, doNormalize) for location in ( region.BOTTOM_LEFT, region.BOTTOM_RIGHT, region.TOP_LEFT, region.TOP_RIGHT, ): pixelIndex = region.getPixelIndex(location) xPos = afwImage.indexToPosition(pixelIndex[0] + self.xy0[0]) yPos = afwImage.indexToPosition(pixelIndex[1] + self.xy0[1]) self.kernel.computeImage(desImage, doNormalize, xPos, yPos) actImage = region.getImage(location) msg = "exact image(%s) incorrect" % (LocNameDict[location], ) self.assertImagesNearlyEqual(actImage, desImage, msg=msg)
def testMEF(self): """Test writing a set of images to an MEF fits file, and then reading them back""" imPath = "data" if os.path.exists("tests"): imPath = os.path.join("tests", imPath) imPath = os.path.join(imPath, "MEF.fits") im = afwImage.ImageF(afwGeom.Extent2I(20, 20)) for hdu in range(1, 5): im.set(100 * hdu) if hdu == 1: mode = "w" else: mode = "a" im.writeFits(imPath, None, mode) for hdu in range(1, 5): im = afwImage.ImageF(imPath, hdu) self.assertEqual(im.get(0, 0), 100 * hdu) os.remove(imPath)
def getCoaddSecondMoments(coaddpsf, point, extent=afwGeom.Extent2I(0, 0)): count = coaddpsf.getComponentCount() coaddWcs = coaddpsf.getCoaddWcs() weight_sum = 0.0 m1_sum = 0.0 m2_sum = 0.0 components = [] for i in range(count): wcs = coaddpsf.getWcs(i) psf = coaddpsf.getPsf(i) bbox = afwGeom.Box2D(coaddpsf.getBBox(i)) point_rel = wcs.skyToPixel(coaddWcs.pixelToSky(afwGeom.Point2D(point))) if bbox.contains(point_rel): weight = coaddpsf.getWeight(i) m0, xbar, ybar, mxx, myy, x0, y0 = getPsfMoments(psf, point) #, extent) m1_sum += mxx * weight m2_sum += myy * weight weight_sum += weight if weight_sum == 0.0: return 0, 0, 0 else: return m1_sum / weight_sum, m2_sum / weight_sum
def testDeepCopySubData(self): """Make sure a deep copy of a subregion of an Exposure has its own data (ticket #2625) """ exp = afwImage.ExposureF(6, 7) mi = exp.getMaskedImage() mi.getImage().set(100) mi.getMask().set(5) mi.getVariance().set(200) bbox = afwGeom.Box2I(afwGeom.Point2I(1, 0), afwGeom.Extent2I(5, 4)) expCopy = exp.Factory(exp, bbox, afwImage.PARENT, True) miCopy = expCopy.getMaskedImage() miCopy.getImage().set(-50) miCopy.getMask().set(2) miCopy.getVariance().set(175) self.assertFloatsAlmostEqual(miCopy.getImage().getArray(), -50) self.assertTrue(np.all(miCopy.getMask().getArray() == 2)) self.assertFloatsAlmostEqual(miCopy.getVariance().getArray(), 175) self.assertFloatsAlmostEqual(mi.getImage().getArray(), 100) self.assertTrue(np.all(mi.getMask().getArray() == 5)) self.assertFloatsAlmostEqual(mi.getVariance().getArray(), 200)
def testSubImage(self): """Test getImage on a subregion of the full background image Using real image data is a cheap way to get a variable background """ mi = self.getCfhtImage() bctrl = afwMath.BackgroundControl(mi.getWidth() // 128, mi.getHeight() // 128) backobj = afwMath.makeBackground(mi.getImage(), bctrl) subBBox = afwGeom.Box2I(afwGeom.Point2I(1000, 3000), afwGeom.Extent2I(100, 100)) bgFullImage = backobj.getImageF() self.assertEqual(bgFullImage.getBBox(), mi.getBBox()) subFullArr = afwImage.ImageF(bgFullImage, subBBox).getArray() bgSubImage = backobj.getImageF(subBBox, bctrl.getInterpStyle()) subArr = bgSubImage.getArray() # the pixels happen to be identical but it is safer not to rely on that; close is good enough self.assertTrue(np.allclose(subArr, subFullArr))
def testBad(self): ti = afwImage.MaskedImageF(afwGeom.Extent2I(100, 100)) ti.getVariance().set(0.1) ti.set(50, 50, (1., 0x0, 1.)) sKernel = self.makeSpatialKernel(2) si = afwImage.MaskedImageF(ti.getDimensions()) afwMath.convolve(si, ti, sKernel, True) bbox = afwGeom.Box2I(afwGeom.Point2I(25, 25), afwGeom.Point2I(75, 75)) si = afwImage.MaskedImageF(si, bbox, origin=afwImage.LOCAL) ti = afwImage.MaskedImageF(ti, bbox, origin=afwImage.LOCAL) kc = ipDiffim.KernelCandidateF(50., 50., ti, si, self.policy) badGaussian = afwMath.GaussianFunction2D(1., 1., 0.) badKernel = afwMath.AnalyticKernel(self.ksize, self.ksize, badGaussian) basisList = [] basisList.append(badKernel) badSpatialKernelFunction = afwMath.PolynomialFunction2D(0) badSpatialKernel = afwMath.LinearCombinationKernel(basisList, badSpatialKernelFunction) badSpatialKernel.setSpatialParameters([[1, ]]) sBg = afwMath.PolynomialFunction2D(1) bgCoeffs = [10., 10., 10.] sBg.setParameters(bgCoeffs) # must be initialized bskv = ipDiffim.BuildSingleKernelVisitorF(self.kList, self.policy) bskv.processCandidate(kc) self.assertEqual(kc.isInitialized(), True) askv = ipDiffim.AssessSpatialKernelVisitorF(badSpatialKernel, sBg, self.policy) askv.processCandidate(kc) self.assertEqual(askv.getNProcessed(), 1) self.assertEqual(askv.getNRejected(), 1) self.assertEqual(kc.getStatus(), afwMath.SpatialCellCandidate.BAD)
def testFilters(self): """Test that the coadd filter is set correctly """ filterPolicyFile = pexPolicy.DefaultPolicyFile("afw", "SdssFilters.paf", "tests") filterPolicy = pexPolicy.Policy.createPolicy( filterPolicyFile, filterPolicyFile.getRepositoryPath(), True) imageUtils.defineFiltersFromPolicy(filterPolicy, reset=True) unkFilter = afwImage.Filter() gFilter = afwImage.Filter("g") rFilter = afwImage.Filter("r") calexpPath = os.path.join(AfwdataDir, SimCalexpSubpath) inExp = afwImage.ExposureF( calexpPath, afwGeom.Box2I(afwGeom.Point2I(0, 0), afwGeom.Extent2I(10, 10)), afwImage.PARENT) coadd = coaddUtils.Coadd( bbox=inExp.getBBox(), wcs=inExp.getWcs(), badMaskPlanes=("NO_DATA", "BAD"), ) inExp.setFilter(gFilter) coadd.addExposure(inExp) self.assertEqualFilters(coadd.getCoadd().getFilter(), gFilter) self.assertEqualFilterSets(coadd.getFilters(), (gFilter, )) coadd.addExposure(inExp) self.assertEqualFilters(coadd.getCoadd().getFilter(), gFilter) self.assertEqualFilterSets(coadd.getFilters(), (gFilter, )) inExp.setFilter(rFilter) coadd.addExposure(inExp) self.assertEqualFilters(coadd.getCoadd().getFilter(), unkFilter) self.assertEqualFilterSets(coadd.getFilters(), (gFilter, rFilter))
def testFixedKernel(self): """Test FixedKernel using a ramp function """ kWidth = 5 kHeight = 6 inArr = numpy.arange(kWidth * kHeight, dtype=float) inArr.shape = [kWidth, kHeight] inImage = afwImage.ImageD(afwGeom.Extent2I(kWidth, kHeight)) for row in range(inImage.getHeight()): for col in range(inImage.getWidth()): inImage.set(col, row, inArr[col, row]) kernel = afwMath.FixedKernel(inImage) self.basicTests(kernel, 0) outImage = afwImage.ImageD(kernel.getDimensions()) kernel.computeImage(outImage, False) outArr = outImage.getArray().transpose() if not numpy.allclose(inArr, outArr): self.fail("%s = %s != %s (not normalized)" % \ (kernel.__class__.__name__, inArr, outArr)) normInArr = inArr / inArr.sum() normOutImage = afwImage.ImageD(kernel.getDimensions()) kernel.computeImage(normOutImage, True) normOutArr = normOutImage.getArray().transpose() if not numpy.allclose(normOutArr, normInArr): self.fail("%s = %s != %s (normalized)" % \ (kernel.__class__.__name__, normInArr, normOutArr)) errStr = self.compareKernels(kernel, kernel.clone()) if errStr: self.fail(errStr) self.verifyCache(kernel, hasCache=False)
def __init__(self, id, patchInnerDimensions, patchBorder, ctrCoord, vertexCoordList, tractOverlap, wcs): """Construct a TractInfo @param[in] id: tract ID @param[in] patchInnerDimensions: dimensions of inner region of patches (x,y pixels) @param[in] patchBorder: overlap between adjacent patches (in pixels, one int) @param[in] ctrCoord: sky coordinate of center of inner region of tract, as an afwCoord.Coord; also used as the CRVAL for the WCS. @param[in] vertexCoordList: list of sky coordinates (afwCoord.Coord) of vertices that define the boundaries of the inner region @param[in] tractOverlap: minimum overlap between adjacent sky tracts; an afwGeom.Angle; this defines the minimum distance the tract extends beyond the inner region in all directions @param[in,out] wcs: an afwImage.Wcs; the reference pixel will be shifted as required so that the lower left-hand pixel (index 0,0) has pixel position 0.0, 0.0 @warning - It is not enforced that ctrCoord is the center of vertexCoordList, but SkyMap relies on it - vertexCoordList will likely become a geom SphericalConvexPolygon someday. """ self._id = id try: assert len(patchInnerDimensions) == 2 self._patchInnerDimensions = afwGeom.Extent2I( *(int(val) for val in patchInnerDimensions)) except: raise TypeError("patchInnerDimensions=%s; must be two ints" % (patchInnerDimensions, )) self._patchBorder = int(patchBorder) self._ctrCoord = ctrCoord self._vertexCoordList = tuple(coord.clone() for coord in vertexCoordList) self._tractOverlap = tractOverlap minBBox = self._minimumBoundingBox(wcs) initialBBox, self._numPatches = self._setupPatches(minBBox, wcs) self._bbox, self._wcs = self._finalOrientation(initialBBox, wcs)
def testExactImages(self): """Confirm that kernel image at each location is correct """ desImage = afwImage.ImageD(afwGeom.Extent2I(self.kernel.getWidth(), self.kernel.getHeight())) for doNormalize in (False, True): region = mathDetail.KernelImagesForRegion(self.kernel, self.bbox, self.xy0, doNormalize) for location in ( region.BOTTOM_LEFT, region.BOTTOM_RIGHT, region.TOP_LEFT, region.TOP_RIGHT, ): pixelIndex = region.getPixelIndex(location) xPos = afwImage.indexToPosition(pixelIndex[0] + self.xy0[0]) yPos = afwImage.indexToPosition(pixelIndex[1] + self.xy0[1]) self.kernel.computeImage(desImage, doNormalize, xPos, yPos) desImArr = desImage.getArray().transpose().copy() actImage = region.getImage(location) actImArr = actImage.getArray().transpose().copy() errStr = imTestUtils.imagesDiffer(actImArr, desImArr) if errStr: self.fail("exact image(%s) incorrect:\n%s" % (LocNameDict[location], errStr))
def testTicket1123(self): """ Ticket #1123 reported that the Statistics stack routine throws an exception when all pixels in a stack are masked. Returning a NaN pixel in the stack is preferred """ ctrl = afwMath.StatisticsControl() ctrl.setAndMask(~0x0) mimg = afwImage.MaskedImageF(afwGeom.Extent2I(10, 10)) mimg.set([self.val, 0x1, self.val]) # test the case with no valid pixels ... both mean and stdev should be # nan stat = afwMath.makeStatistics(mimg, afwMath.MEAN | afwMath.STDEV, ctrl) mean = stat.getValue(afwMath.MEAN) stdev = stat.getValue(afwMath.STDEV) self.assertNotEqual(mean, mean) # NaN does not equal itself self.assertNotEqual(stdev, stdev) # NaN does not equal itself # test the case with one valid pixel ... mean is ok, but stdev should # still be nan mimg.getMask().set(1, 1, 0x0) stat = afwMath.makeStatistics(mimg, afwMath.MEAN | afwMath.STDEV, ctrl) mean = stat.getValue(afwMath.MEAN) stdev = stat.getValue(afwMath.STDEV) self.assertEqual(mean, self.val) self.assertNotEqual(stdev, stdev) # NaN does not equal itself # test the case with two valid pixels ... both mean and stdev are ok mimg.getMask().set(1, 2, 0x0) stat = afwMath.makeStatistics(mimg, afwMath.MEAN | afwMath.STDEV, ctrl) mean = stat.getValue(afwMath.MEAN) stdev = stat.getValue(afwMath.STDEV) self.assertEqual(mean, self.val) self.assertEqual(stdev, 0.0)
def testPcaNaN(self): """Test calculating PCA when the images can contain NaNs""" width, height = 20, 10 values = (100, 200, 300) for i, val in enumerate(values): im = afwImage.ImageF(afwGeom.Extent2I(width, height)) im.set(val) if i == 1: im.set(width // 2, height // 2, np.nan) self.ImageSet.addImage(im, 1.0) self.ImageSet.analyze() eImages = [] for img in self.ImageSet.getEigenImages(): eImages.append(img) if display: mos = displayUtils.Mosaic(background=-10) ds9.mtv(mos.makeMosaic(eImages), frame=1)
def testInvarianceOfPixelToSky(self): for deep in (True, False): llc = afwGeom.Point2I(20, 30) bbox = afwGeom.Box2I(llc, afwGeom.Extent2I(60, 50)) subImg = afwImage.ExposureF(self.parent, bbox, afwImage.LOCAL, deep) xy0 = subImg.getMaskedImage().getXY0() if False: ds9.mtv(self.parent, frame=0) ds9.mtv(subImg, frame=1) for p in self.testPositions: subP = p - afwGeom.Extent2D(llc[0], llc[1]) # pixel in subImg if \ subP[0] < 0 or subP[0] >= bbox.getWidth() or \ subP[1] < 0 or subP[1] >= bbox.getHeight(): continue adParent = self.parent.getWcs().pixelToSky(p) adSub = subImg.getWcs().pixelToSky( subP + afwGeom.Extent2D(xy0[0], xy0[1])) # # Check that we're talking about the same pixel # self.assertEqual( self.parent.getMaskedImage().get(int(p[0]), int(p[1])), subImg.getMaskedImage().get(int(subP[0]), int(subP[1]))) self.assertEqual(adParent[0], adSub[0], "RAs are equal; deep = %s" % deep) self.assertEqual(adParent[1], adSub[1], "DECs are equal; deep = %s" % deep)
def testInvarianceOfCrpix1(self): """Test that crpix is the same for parent and sub-image. Also tests that llc of sub-image saved correctly""" llc = afwGeom.Point2I(20, 30) bbox = afwGeom.Box2I(llc, afwGeom.Extent2I(60, 50)) subImg = afwImage.ExposureF(self.parent, bbox, afwImage.LOCAL) subImgLlc = subImg.getMaskedImage().getXY0() oSubImage = subImg.getWcs().getPixelOrigin() #Useful for debugging if False: print self.parent.getMaskedImage().getXY0() print subImg.getMaskedImage().getXY0() print self.parent.getWcs().getFitsMetadata().toString() print subImg.getWcs().getFitsMetadata().toString() print self.oParent, oSubImage for i in range(2): self.assertEqual(llc[i], subImgLlc[i], "Corner of sub-image not correct") self.assertAlmostEqual(self.oParent[i], oSubImage[i], 6, "Crpix of sub-image not correct")
def testFlatFocalPlane(self): """Test an undistorted focal plane (with rectangular pixels) """ bbox = afwGeom.Box2I(afwGeom.Point2I(0, 0), afwGeom.Extent2I(1000, 1000)) pixelSizeMm = afwGeom.Extent2D(0.02, 0.03) plateScale = 25.0 # arcsec/mm yaw = afwGeom.Angle(20, afwGeom.degrees) # focal-plane position of ref position on detector (mm) fpPosition = afwGeom.Point2D(50, 25) # ref position on detector (pos of lower left corner) refPoint = afwGeom.Point2D(-0.5, -0.5) orientation = cameraGeom.Orientation( fpPosition, refPoint, yaw, ) plateScaleRad = afwGeom.Angle(plateScale, afwGeom.arcseconds).asRadians() focalPlaneToField = afwGeom.makeRadialTransform((0.0, plateScaleRad)) pixelToTanPixel = makePixelToTanPixel( bbox=bbox, orientation=orientation, focalPlaneToField=focalPlaneToField, pixelSizeMm=pixelSizeMm, ) # with no distortion, this should be a unity transform for pointPix in ( afwGeom.Point2D(0, 0), afwGeom.Point2D(1000, 2000), afwGeom.Point2D(-100.5, 27.23), ): pointTanPix = pixelToTanPixel.applyForward(pointPix) self.assertPairsAlmostEqual(pointTanPix, pointPix)
def processRun(wcsList, outputDir, kind, bc, res): """Creates and persists coverage maps for an entire run. """ crpix = afwGeom.Point2D(0.5 * (res + 1), 0.5 * (res + 1)) crval = afwGeom.Point2D(bc.getCenter()[0], bc.getCenter()[1]) scale = bc.getRadius() * 2.0 / res runWcs = afwImage.createWcs(crval, crpix, scale, 0.0, 0.0, scale) covMaps = [] for i in xrange(6): runImg = afwImage.DecoratedImageF(afwGeom.Extent2I(res, res)) if hasattr(runImg, 'setWcs'): runImg.setWcs(runWcs) elif hasattr(runImg, 'setMetadata'): runImg.setMetadata(runWcs.getFitsMetadata()) covMaps.append(runImg) if kind == 'imsim': width, height = 4072, 4000 else: width, height = 2048, 4610 for wcs, filter in wcsList: assert filter >= 0 and filter < 6 apUtils.updateCoverageMap(covMaps[filter].getImage(), runWcs, wcs, width, height, 0) persistCovMaps(covMaps, outputDir)
def testStatsZebra(self): """Add 1 to every other row""" image2 = self.image.Factory(self.image, True) # # Add 1 to every other row, so the variance is 1/4 # self.assertEqual(image2.getHeight() % 2, 0) width = image2.getWidth() for y in range(1, image2.getHeight(), 2): sim = image2.Factory( image2, afwGeom.Box2I(afwGeom.Point2I(0, y), afwGeom.Extent2I(width, 1)), afwImage.LOCAL) sim += 1 if display: ds9.mtv(self.image, frame=0) ds9.mtv(image2, frame=1) stats = afwMath.makeStatistics( image2, afwMath.NPOINT | afwMath.STDEV | afwMath.MEAN | afwMath.ERRORS) mean = stats.getResult(afwMath.MEAN) n = stats.getValue(afwMath.NPOINT) sd = stats.getValue(afwMath.STDEV) self.assertEqual(mean[0], image2.get(0, 0) + 0.5) self.assertEqual(sd, 1 / math.sqrt(4.0) * math.sqrt(n / (n - 1))) self.assertAlmostEqual( mean[1], sd / math.sqrt(image2.getWidth() * image2.getHeight()), 10) meanSquare = afwMath.makeStatistics(image2, afwMath.MEANSQUARE).getValue() self.assertEqual(meanSquare, 0.5 * (image2.get(0, 0)**2 + image2.get(0, 1)**2))
def testImageStatisticsGeneral(self): numArray = num.ones((20, 20)) mi = afwImage.MaskedImageF(afwGeom.Extent2I(20, 20)) for j in range(mi.getHeight()): for i in range(mi.getWidth()): val = i + 2.3 * j mi.set(i, j, (val, 0x0, 1)) numArray[j][i] = val imstat = ipDiffim.ImageStatisticsF(self.policy) imstat.apply(mi) self.assertAlmostEqual(imstat.getMean(), numArray.mean()) # note that these don't agree exactly... self.assertAlmostEqual(imstat.getRms(), numArray.std(), 1) self.assertEqual(imstat.getNpix(), 20 * 20) afwStat = afwMath.makeStatistics(mi.getImage(), afwMath.MEAN | afwMath.STDEV) self.assertAlmostEqual(imstat.getMean(), afwStat.getValue(afwMath.MEAN)) # even though these do self.assertAlmostEqual(imstat.getRms(), afwStat.getValue(afwMath.STDEV))