def testApproximate(self): """Test I/O for BackgroundLists with Approximate """ # approx and interp should be very close, but not the same img = self.getParabolaImage(256, 256) # try regular interpolated image (the default) bgCtrl = afwMath.BackgroundControl(6, 6) bgCtrl.setInterpStyle(afwMath.Interpolate.AKIMA_SPLINE) bgCtrl.setUndersampleStyle(afwMath.REDUCE_INTERP_ORDER) bkgd = afwMath.makeBackground(img, bgCtrl) interpImage = bkgd.getImageF() with utilsTests.getTempFilePath("_bgi.fits") as bgiFile, \ utilsTests.getTempFilePath("_bga.fits") as bgaFile: bglInterp = afwMath.BackgroundList() bglInterp.append(bkgd) bglInterp.writeFits(bgiFile) # try an approx background approxStyle = afwMath.ApproximateControl.CHEBYSHEV approxOrder = 2 actrl = afwMath.ApproximateControl(approxStyle, approxOrder) bkgd.getBackgroundControl().setApproximateControl(actrl) approxImage = bkgd.getImageF() bglApprox = afwMath.BackgroundList() bglApprox.append(bkgd) bglApprox.writeFits(bgaFile) # take a difference and make sure the two are very similar interpNp = interpImage.getArray() diff = np.abs(interpNp - approxImage.getArray())/interpNp # the image and interp/approx parameters are chosen so these limits # will be greater than machine precision for float. The two methods # should be measurably different (so we know we're not just getting the # same thing from the getImage() method. But they should be very close # since they're both doing the same sort of thing. tolSame = 1.0e-3 # should be the same to this order tolDiff = 1.0e-4 # should be different here self.assertLess(diff.max(), tolSame) self.assertGreater(diff.max(), tolDiff) # now see if we can reload them from files and get the same images we wrote interpImage2 = afwMath.BackgroundList().readFits(bgiFile).getImage() approxImage2 = afwMath.BackgroundList().readFits(bgaFile).getImage() idiff = interpImage.getArray() - interpImage2.getArray() adiff = approxImage.getArray() - approxImage2.getArray() self.assertEqual(idiff.max(), 0.0) self.assertEqual(adiff.max(), 0.0)
def testFitsHeader(self): """Test that XY0 and crpix are written to the header as expected""" # getPixelOrigin() returns origin in lsst coordinates, so need to add 1 to # compare to values stored in fits headers parentCrpix = self.parent.getWcs().getPixelOrigin() # Make a sub-image x0, y0 = 20, 30 llc = afwGeom.Point2I(x0, y0) bbox = afwGeom.Box2I(llc, afwGeom.Extent2I(60, 50)) deep = False subImg = afwImage.ExposureF(self.parent, bbox, afwImage.LOCAL, deep) with utilsTests.getTempFilePath(".fits") as outFile: subImg.writeFits(outFile) hdr = afwImage.readMetadata(outFile) def checkLtvHeader(hdr, name, value): # Per DM-4133, LTVn headers are required to be floating point self.assertTrue(hdr.exists(name), name + " not saved to FITS header") self.assertIsInstance(hdr.get(name), numbers.Real, name + " is not numeric") self.assertNotIsInstance(hdr.get(name), numbers.Integral, name + " is an int") self.assertEqual(hdr.get(name), value, name + " has wrong value") checkLtvHeader(hdr, "LTV1", -1 * x0) checkLtvHeader(hdr, "LTV2", -1 * y0) self.assertTrue(hdr.exists("CRPIX1"), "CRPIX1 not saved to fits header") self.assertTrue(hdr.exists("CRPIX2"), "CRPIX2 not saved to fits header") fitsCrpix = [hdr.get("CRPIX1"), hdr.get("CRPIX2")] self.assertAlmostEqual(fitsCrpix[0] - hdr.get("LTV1"), parentCrpix[0] + 1, 6, "CRPIX1 saved wrong") self.assertAlmostEqual(fitsCrpix[1] - hdr.get("LTV2"), parentCrpix[1] + 1, 6, "CRPIX2 saved wrong")
def testFitsHeader(self): """Test that XY0 and crpix are written to the header as expected""" #getPixelOrigin() returns origin in lsst coordinates, so need to add 1 to #compare to values stored in fits headers parentCrpix = self.parent.getWcs().getPixelOrigin() #Make a sub-image x0, y0 = 20, 30 llc = afwGeom.Point2I(x0, y0) bbox = afwGeom.Box2I(llc, afwGeom.Extent2I(60, 50)) deep = False subImg = afwImage.ExposureF(self.parent, bbox, afwImage.LOCAL, deep) with utilsTests.getTempFilePath(".fits") as outFile: subImg.writeFits(outFile) hdr = afwImage.readMetadata(outFile) self.assertTrue(hdr.exists("LTV1"), "LTV1 not saved to fits header") self.assertTrue(hdr.exists("LTV2"), "LTV2 not saved to fits header") self.assertEqual(hdr.get("LTV1"), -1 * x0, "LTV1 has wrong value") self.assertEqual(hdr.get("LTV2"), -1 * y0, "LTV1 has wrong value") self.assertTrue(hdr.exists("CRPIX1"), "CRPIX1 not saved to fits header") self.assertTrue(hdr.exists("CRPIX2"), "CRPIX2 not saved to fits header") fitsCrpix = [hdr.get("CRPIX1"), hdr.get("CRPIX2")] self.assertAlmostEqual(fitsCrpix[0] - hdr.get("LTV1"), parentCrpix[0] + 1, 6, "CRPIX1 saved wrong") self.assertAlmostEqual(fitsCrpix[1] - hdr.get("LTV2"), parentCrpix[1] + 1, 6, "CRPIX2 saved wrong")
def testWriteStars(self): """Test writing RGB files to disk""" asinhMap = rgb.AsinhMapping(self.min, self.range, self.Q) rgbImage = asinhMap.makeRgbImage(self.images[R], self.images[G], self.images[B]) with utilsTests.getTempFilePath(".png") as fileName: rgb.writeRGB(fileName, rgbImage)
def testWriteStars(self): """Test writing RGB files to disk""" asinhMap = rgb.AsinhMapping(self.min, self.range, self.Q) rgbImage = asinhMap.makeRgbImage(self.images[R], self.images[G], self.images[B]) with utilsTests.getTempFilePath(".png") as fileName: rgb.writeRGB(fileName, rgbImage) self.assertTrue(os.path.exists(fileName))
def testMakeRGBResize(self): """Test the function that does it all, including rescaling""" rgb.makeRGB(self.images[R], self.images[G], self.images[B], xSize=40, ySize=60) with utilsTests.getTempFilePath(".png") as fileName: rgb.makeRGB(self.images[R], self.images[G], self.images[B], fileName=fileName, rescaleFactor=0.5) self.assertTrue(os.path.exists(fileName))
def testBackgroundListIO(self): """Test I/O for BackgroundLists""" bgCtrl = afwMath.BackgroundControl(10, 10) interpStyle = afwMath.Interpolate.AKIMA_SPLINE undersampleStyle = afwMath.REDUCE_INTERP_ORDER backgroundList = afwMath.BackgroundList() backImage = afwImage.ImageF(self.image.getDimensions()) for i in range(2): bkgd = afwMath.makeBackground(self.image, bgCtrl) if i == 0: backgroundList.append((bkgd, interpStyle, undersampleStyle,)) # no need to call getImage else: backgroundList.append(bkgd) # Relies on having called getImage; deprecated backImage += bkgd.getImageF(interpStyle, undersampleStyle) with utilsTests.getTempFilePath(".fits") as fileName: backgroundList.writeFits(fileName) backgrounds = afwMath.BackgroundList.readFits(fileName) img = backgrounds.getImage() # # Check that the read-back image is identical to that generated from the backgroundList # round-tripped to disk # backImage -= img self.assertEqual(np.min(backImage.getArray()), 0.0) self.assertEqual(np.max(backImage.getArray()), 0.0)
def testFitsHeader(self): """Test that XY0 and crpix are written to the header as expected""" #getPixelOrigin() returns origin in lsst coordinates, so need to add 1 to #compare to values stored in fits headers parentCrpix = self.parent.getWcs().getPixelOrigin() #Make a sub-image x0, y0 = 20, 30 llc = afwGeom.Point2I(x0, y0) bbox = afwGeom.Box2I(llc, afwGeom.Extent2I(60, 50)) deep = False subImg = afwImage.ExposureF(self.parent, bbox, afwImage.LOCAL, deep) with utilsTests.getTempFilePath(".fits") as outFile: subImg.writeFits(outFile) hdr = afwImage.readMetadata(outFile) def checkLtvHeader(hdr, name, value): # Per DM-4133, LTVn headers are required to be floating point self.assertTrue(hdr.exists(name), name + " not saved to FITS header") self.assertIsInstance(hdr.get(name), numbers.Real, name + " is not numeric") self.assertNotIsInstance(hdr.get(name), numbers.Integral, name + " is an int") self.assertEqual(hdr.get(name), value, name + " has wrong value") checkLtvHeader(hdr, "LTV1", -1*x0) checkLtvHeader(hdr, "LTV2", -1*y0) self.assertTrue( hdr.exists("CRPIX1"), "CRPIX1 not saved to fits header") self.assertTrue( hdr.exists("CRPIX2"), "CRPIX2 not saved to fits header") fitsCrpix = [hdr.get("CRPIX1"), hdr.get("CRPIX2")] self.assertAlmostEqual(fitsCrpix[0] - hdr.get("LTV1"), parentCrpix[0]+1, 6, "CRPIX1 saved wrong") self.assertAlmostEqual(fitsCrpix[1] - hdr.get("LTV2"), parentCrpix[1]+1, 6, "CRPIX2 saved wrong")
def testFitsHeader(self): """Test that XY0 and crpix are written to the header as expected""" #getPixelOrigin() returns origin in lsst coordinates, so need to add 1 to #compare to values stored in fits headers parentCrpix = self.parent.getWcs().getPixelOrigin() #Make a sub-image x0, y0 = 20, 30 llc = afwGeom.Point2I(x0, y0) bbox = afwGeom.Box2I(llc, afwGeom.Extent2I(60, 50)) deep = False subImg = afwImage.ExposureF(self.parent, bbox, afwImage.LOCAL, deep) with utilsTests.getTempFilePath(".fits") as outFile: subImg.writeFits(outFile) hdr = afwImage.readMetadata(outFile) self.assertTrue( hdr.exists("LTV1"), "LTV1 not saved to fits header") self.assertTrue( hdr.exists("LTV2"), "LTV2 not saved to fits header") self.assertEqual(hdr.get("LTV1"), -1*x0, "LTV1 has wrong value") self.assertEqual(hdr.get("LTV2"), -1*y0, "LTV1 has wrong value") self.assertTrue( hdr.exists("CRPIX1"), "CRPIX1 not saved to fits header") self.assertTrue( hdr.exists("CRPIX2"), "CRPIX2 not saved to fits header") fitsCrpix = [hdr.get("CRPIX1"), hdr.get("CRPIX2")] self.assertAlmostEqual(fitsCrpix[0] - hdr.get("LTV1"), parentCrpix[0]+1, 6, "CRPIX1 saved wrong") self.assertAlmostEqual(fitsCrpix[1] - hdr.get("LTV2"), parentCrpix[1]+1, 6, "CRPIX2 saved wrong")
def testRoundTrip(self): """Test that saving and retrieving an image doesn't alter the metadata""" llc = afwGeom.Point2I(20, 30) bbox = afwGeom.Box2I(llc, afwGeom.Extent2I(60, 50)) for deep in (False, True): subImg = afwImage.ExposureF(self.parent, bbox, afwImage.LOCAL, deep) with utilsTests.getTempFilePath("_%s.fits" % (deep, )) as outFile: subImg.writeFits(outFile) newImg = afwImage.ExposureF(outFile) subXY0 = subImg.getMaskedImage().getXY0() newXY0 = newImg.getMaskedImage().getXY0() parentCrpix = self.parent.getWcs().getPixelOrigin() subCrpix = subImg.getWcs().getPixelOrigin() newCrpix = newImg.getWcs().getPixelOrigin() if False: print self.parent.getWcs().getFitsMetadata().toString() print subImg.getWcs().getFitsMetadata().toString() print newImg.getWcs().getFitsMetadata().toString() for i in range(2): self.assertEqual(subXY0[i], newXY0[i], "Origin has changed; deep = %s" % deep) self.assertAlmostEqual( subCrpix[i], newCrpix[i], 6, "crpix has changed; deep = %s" % deep)
def testRoundTrip(self): """Test that saving and retrieving an image doesn't alter the metadata""" llc = afwGeom.Point2I(20, 30) bbox = afwGeom.Box2I(llc, afwGeom.Extent2I(60, 50)) for deep in (False, True): subImg = afwImage.ExposureF(self.parent, bbox, afwImage.LOCAL, deep) with utilsTests.getTempFilePath("_%s.fits" % (deep,)) as outFile: subImg.writeFits(outFile) newImg = afwImage.ExposureF(outFile) subXY0 = subImg.getMaskedImage().getXY0() newXY0 = newImg.getMaskedImage().getXY0() self.parent.getWcs().getPixelOrigin() subCrpix = subImg.getWcs().getPixelOrigin() newCrpix = newImg.getWcs().getPixelOrigin() if False: print self.parent.getWcs().getFitsMetadata().toString() print subImg.getWcs().getFitsMetadata().toString() print newImg.getWcs().getFitsMetadata().toString() for i in range(2): self.assertEqual(subXY0[i], newXY0[i], "Origin has changed; deep = %s" % deep) self.assertAlmostEqual(subCrpix[i], newCrpix[i], 6, "crpix has changed; deep = %s" % deep)
def testWriteStarsLegacyAPI(self): with utilsTests.getTempFilePath(".png") as fileName: self.writeFileLegacyAPI(fileName) def tst(): self.writeFileLegacyAPI("rgb.unknown") utilsTests.assertRaisesLsstCpp(self, ValueError, tst)
def testWriteFits(self): if not self.maskFile: print >> sys.stderr, "Warning: afwdata is not set up; not running the FITS I/O tests" return nMaskPlanes0 = self.Mask.getNumPlanesUsed() mask = self.Mask(self.maskFile, 3) self.assertEqual(mask.get(32, 1), 0) self.assertEqual(mask.get(50, 50), 0) self.assertEqual(mask.get(0, 0), (1<<nMaskPlanes0)) # as header had none of the canonical planes with utilsTests.getTempFilePath(".fits") as tmpFile: mask.writeFits(tmpFile) # # Read it back # md = lsst.daf.base.PropertySet() rmask = self.Mask(tmpFile, 0, md) self.assertEqual(mask.get(0, 0), rmask.get(0, 0)) # # Check that we wrote (and read) the metadata successfully # mp_ = "MP_" if True else self.Mask.maskPlanePrefix() # currently private for (k, v) in self.Mask().getMaskPlaneDict().items(): self.assertEqual(md.get(mp_ + k), v)
def testWriteFits(self): """Test writing FITS files""" with utilsTests.getTempFilePath(".fits") as tmpFile: if self.fileForMetadata: imgU = afwImage.DecoratedImageF(self.fileForMetadata) else: print >> sys.stderr, "Warning: afwdata is not set up; not running the FITS metadata I/O tests" imgU = afwImage.DecoratedImageF() self.dimage1.writeFits(tmpFile, imgU.getMetadata()) # # Read it back # rimage = afwImage.DecoratedImageF(tmpFile) self.assertEqual(self.dimage1.getImage().get(0, 0), rimage.getImage().get(0, 0)) # # Check that we wrote (and read) the metadata successfully if self.fileForMetadata: meta = self.trueMetadata for k in meta.keys(): self.assertEqual(rimage.getMetadata().getAsDouble(k), meta[k])
def testWriteReadF64(self): """Test writing then reading an F64 image""" with utilsTests.getTempFilePath(".fits") as tmpFile: im = afwImage.ImageD(afwGeom.Extent2I(100, 100)) im.set(666) im.writeFits(tmpFile) afwImage.ImageD(tmpFile)
def testReadFits(self): """Test reading FITS files""" try: dataDir = lsst.utils.getPackageDir("afwdata") except Exception: print >> sys.stderr, "Warning: afwdata is not set up; not running the FITS I/O tests" return dataDir = os.path.join(dataDir, "data") hdus = {} fileName = os.path.join(dataDir, "small_MI.fits") hdus["img"] = 2 # an S16 fits HDU hdus["msk"] = 3 # an U8 fits HDU hdus["var"] = 4 # an F32 fits HDU imgU = afwImage.DecoratedImageU(fileName, hdus["img"]) # read as unsigned short imgF = afwImage.DecoratedImageF(fileName, hdus["img"]) # read as float self.assertEqual(imgU.getHeight(), 256) self.assertEqual(imgF.getImage().getWidth(), 256) self.assertEqual(imgU.getImage().get(0, 0), imgF.getImage().get(0, 0)) # # Check the metadata # meta = self.trueMetadata for k in meta.keys(): self.assertEqual(imgU.getMetadata().getAsDouble(k), meta[k]) self.assertEqual(imgF.getMetadata().getAsDouble(k), meta[k]) # # Read an F32 image # varU = afwImage.DecoratedImageF(fileName, hdus["var"]) # read as unsigned short varF = afwImage.DecoratedImageF(fileName, hdus["var"]) # read as float self.assertEqual(varU.getHeight(), 256) self.assertEqual(varF.getImage().getWidth(), 256) self.assertEqual(varU.getImage().get(0, 0), varF.getImage().get(0, 0)) # # Read a char image # maskImg = afwImage.DecoratedImageU( fileName, hdus["msk"]).getImage() # read a char file self.assertEqual(maskImg.getHeight(), 256) self.assertEqual(maskImg.getWidth(), 256) self.assertEqual(maskImg.get(0, 0), 1) # # Read a U16 image # with utilsTests.getTempFilePath(".fits") as tmpFile: imgU.writeFits(tmpFile) imgU16 = afwImage.DecoratedImageF( tmpFile) # read as unsigned short
def testReadWriteFits(self): """Test readFits and writeFits. """ # This should pass without an exception mainExposure = afwImage.ExposureF(inFilePathSmall) mainExposure.setDetector(self.detector) subBBox = afwGeom.Box2I(afwGeom.Point2I(10, 10), afwGeom.Extent2I(40, 50)) subExposure = mainExposure.Factory(mainExposure, subBBox, afwImage.LOCAL) self.checkWcs(mainExposure, subExposure) det = subExposure.getDetector() self.assertTrue(det) subExposure = afwImage.ExposureF(inFilePathSmall, subBBox, afwImage.LOCAL) self.checkWcs(mainExposure, subExposure) # This should throw an exception def getExposure(): afwImage.ExposureF(inFilePathSmallImage) self.assertRaises(lsst.afw.fits.FitsError, getExposure) mainExposure.setPsf(self.psf) # Make sure we can write without an exception mainExposure.getCalib().setExptime(10) mainExposure.getCalib().setMidTime(dafBase.DateTime()) midMjd = mainExposure.getCalib().getMidTime().get() fluxMag0, fluxMag0Err = 1e12, 1e10 mainExposure.getCalib().setFluxMag0(fluxMag0, fluxMag0Err) with utilsTests.getTempFilePath(".fits") as tmpFile: mainExposure.writeFits(tmpFile) readExposure = type(mainExposure)(tmpFile) # # Check the round-tripping # self.assertEqual(mainExposure.getFilter().getName(), readExposure.getFilter().getName()) self.assertEqual(mainExposure.getCalib().getExptime(), readExposure.getCalib().getExptime()) self.assertEqual(midMjd, readExposure.getCalib().getMidTime().get()) self.assertEqual((fluxMag0, fluxMag0Err), readExposure.getCalib().getFluxMag0()) psf = readExposure.getPsf() self.assert_(psf is not None) dummyPsf = DummyPsf.swigConvert(psf) self.assert_(dummyPsf is not None) self.assertEqual(dummyPsf.getValue(), self.psf.getValue())
def testArchiveKeys(self): with utilsTests.getTempFilePath(".fits") as tmpFile: exposure1 = afwImage.ExposureF(100, 100, self.wcs) exposure1.setPsf(self.psf) exposure1.writeFits(tmpFile) exposure2 = afwImage.ExposureF(tmpFile) self.assertFalse(exposure2.getMetadata().exists("AR_ID")) self.assertFalse(exposure2.getMetadata().exists("PSF_ID")) self.assertFalse(exposure2.getMetadata().exists("WCS_ID"))
def testMakeRGB(self): """Test the function that does it all""" satValue = 1000.0 with utilsTests.getTempFilePath(".png") as fileName: red = saturate(self.images[R], satValue) green = saturate(self.images[G], satValue) blue = saturate(self.images[B], satValue) rgb.makeRGB(red, green, blue, self.min, self.range, self.Q, fileName=fileName, saturatedBorderWidth=1, saturatedPixelValue=2000)
def testXY0(self): """Test that XY0 values are handled correctly when building an exposure and also when reading the WCS header directly. #2205""" bbox = afwGeom.Box2I(afwGeom.Point2I(1000, 1000), afwGeom.Extent2I(10, 10)) def makeWcs(crPixPos, crValDeg, projection): ps = dafBase.PropertySet() ctypes = [ ("%-5s%3s" % (("RA", "DEC")[i], projection)).replace(" ", "-") for i in range(2) ] for i in range(2): ip1 = i + 1 ps.add("CTYPE%1d" % (ip1, ), ctypes[i]) ps.add("CRPIX%1d" % (ip1, ), crPixPos[i]) ps.add("CRVAL%1d" % (ip1, ), crValDeg[i]) ps.add("RADECSYS", "ICRS") ps.add("EQUINOX", 2000) ps.add("CD1_1", -0.001) ps.add("CD2_1", 0.0) ps.add("CD1_2", 0.0) ps.add("CD2_2", 0.001) return afwImage.makeWcs(ps) wcs = makeWcs( crPixPos=(100.0, 100.0), crValDeg=(10.0, 35.0), projection="STG", # also fails for TAN ) exposure = afwImage.ExposureF(bbox, wcs) pixPos = afwGeom.Box2D(bbox).getMax() if verbose: print "XY0=", exposure.getXY0() print "pixPos=", pixPos skyPos = wcs.pixelToSky(pixPos) with utilsTests.getTempFilePath(".fits") as tmpFile: exposure.writeFits(tmpFile) for useExposure in (False, True): if useExposure: unpExp = afwImage.ExposureF(tmpFile) unpWcs = unpExp.getWcs() else: md = afwImage.readMetadata(tmpFile) unpWcs = afwImage.makeWcs(md, False) unpPixPos = unpWcs.skyToPixel(skyPos) if verbose: print "useExposure=%s; unp pixPos=%s" % (useExposure, unpPixPos) for i in range(2): self.assertAlmostEqual(unpPixPos[i], 1009.5)
def testReadFits(self): """Test reading FITS files""" try: dataDir = lsst.utils.getPackageDir("afwdata") except Exception: print >> sys.stderr, "Warning: afwdata is not set up; not running the FITS I/O tests" return dataDir = os.path.join(dataDir, "data") hdus = {} fileName = os.path.join(dataDir, "small_MI.fits") hdus["img"] = 2 # an S16 fits HDU hdus["msk"] = 3 # an U8 fits HDU hdus["var"] = 4 # an F32 fits HDU imgU = afwImage.DecoratedImageU(fileName, hdus["img"]) # read as unsigned short imgF = afwImage.DecoratedImageF(fileName, hdus["img"]) # read as float self.assertEqual(imgU.getHeight(), 256) self.assertEqual(imgF.getImage().getWidth(), 256) self.assertEqual(imgU.getImage().get(0, 0), imgF.getImage().get(0, 0)) # # Check the metadata # meta = self.trueMetadata for k in meta.keys(): self.assertEqual(imgU.getMetadata().getAsDouble(k), meta[k]) self.assertEqual(imgF.getMetadata().getAsDouble(k), meta[k]) # # Read an F32 image # varU = afwImage.DecoratedImageF(fileName, hdus["var"]) # read as unsigned short varF = afwImage.DecoratedImageF(fileName, hdus["var"]) # read as float self.assertEqual(varU.getHeight(), 256) self.assertEqual(varF.getImage().getWidth(), 256) self.assertEqual(varU.getImage().get(0, 0), varF.getImage().get(0, 0)) # # Read a char image # maskImg = afwImage.DecoratedImageU(fileName, hdus["msk"]).getImage() # read a char file self.assertEqual(maskImg.getHeight(), 256) self.assertEqual(maskImg.getWidth(), 256) self.assertEqual(maskImg.get(0, 0), 1) # # Read a U16 image # with utilsTests.getTempFilePath(".fits") as tmpFile: imgU.writeFits(tmpFile) imgU16 = afwImage.DecoratedImageF(tmpFile) # read as unsigned short
def checkEquinoxHeader(coordSysName, writeEquinox): coordSys = getattr(afwCoord, coordSysName) # We should get the same behaviour with both Wcs and TanWcs: check them both. for dummyWcs in (makeWcs(coordSys=coordSys), afwImage.TanWcs.cast(makeWcs(coordSys=coordSys))): dummyExposure = afwImage.ExposureF() dummyExposure.setWcs(dummyWcs) with utilsTests.getTempFilePath(".fits") as tmpFile: dummyExposure.writeFits(tmpFile) metadata = afwImage.readMetadata(tmpFile) self.assertEqual(metadata.get("RADESYS"), coordSysName) self.assertTrue(("EQUINOX" in metadata.names()) == writeEquinox)
def testTanWcs(self): self.addSipMetadata() wcsIn = lsst.afw.image.makeWcs(self.metadata) with utilsTests.getTempFilePath(".fits") as fileName: wcsOut = self.doFitsRoundTrip(fileName, wcsIn) wcsIn1 = lsst.afw.image.cast_TanWcs(wcsIn) wcsOut1 = lsst.afw.image.cast_TanWcs(wcsOut) self.assert_(wcsIn1 is not None) self.assert_(wcsOut1 is not None) self.assert_(wcsIn1.hasDistortion()) self.assert_(wcsOut1.hasDistortion()) self.assertEqual(wcsIn1, wcsOut1)
def testLongStrings(self): keyWord = 'ZZZ' with utilsTests.getTempFilePath(".fits") as tmpFile: longString = ' '.join(['This is a long string.'] * 8) expOrig = afwImage.ExposureF(100,100) mdOrig = expOrig.getMetadata() mdOrig.set(keyWord, longString) expOrig.writeFits(tmpFile) expNew = afwImage.ExposureF(tmpFile) self.assertEqual(expNew.getMetadata().get(keyWord), longString)
def testTicket2861(self): with utilsTests.getTempFilePath(".fits") as tmpFile: exposure1 = afwImage.ExposureF(100, 100, self.wcs) exposure1.setPsf(self.psf) schema = afwTable.ExposureTable.makeMinimalSchema() coaddInputs = afwImage.CoaddInputs(schema, schema) exposure1.getInfo().setCoaddInputs(coaddInputs) exposure2 = afwImage.ExposureF(exposure1, True) self.assertIsNotNone(exposure2.getInfo().getCoaddInputs()) exposure2.writeFits(tmpFile) exposure3 = afwImage.ExposureF(tmpFile) self.assertIsNotNone(exposure3.getInfo().getCoaddInputs())
def testReadWriteXY0(self): """Test that we read and write (X0, Y0) correctly""" mask = afwImage.MaskU(afwGeom.ExtentI(10, 20)) x0, y0 = 1, 2 mask.setXY0(x0, y0) with utilsTests.getTempFilePath(".fits") as tmpFile: mask.writeFits(tmpFile) mask2 = mask.Factory(tmpFile) self.assertEqual(mask2.getX0(), x0) self.assertEqual(mask2.getY0(), y0)
def testReadWriteXY0(self): """Test that we read and write (X0, Y0) correctly""" im = afwImage.ImageF(afwGeom.Extent2I(10, 20)) x0, y0 = 1, 2 im.setXY0(x0, y0) with utilsTests.getTempFilePath(".fits") as tmpFile: im.writeFits(tmpFile) im2 = im.Factory(tmpFile) self.assertEqual(im2.getX0(), x0) self.assertEqual(im2.getY0(), y0)
def testXY0(self): """Test that XY0 values are handled correctly when building an exposure and also when reading the WCS header directly. #2205""" bbox = afwGeom.Box2I(afwGeom.Point2I(1000, 1000), afwGeom.Extent2I(10, 10)) def makeWcs(crPixPos, crValDeg, projection): ps = dafBase.PropertySet() ctypes = [("%-5s%3s" % (("RA", "DEC")[i], projection)).replace(" ", "-") for i in range(2)] for i in range(2): ip1 = i + 1 ps.add("CTYPE%1d" % (ip1,), ctypes[i]) ps.add("CRPIX%1d" % (ip1,), crPixPos[i]) ps.add("CRVAL%1d" % (ip1,), crValDeg[i]) ps.add("RADECSYS", "ICRS") ps.add("EQUINOX", 2000) ps.add("CD1_1", -0.001) ps.add("CD2_1", 0.0) ps.add("CD1_2", 0.0) ps.add("CD2_2", 0.001) return afwImage.makeWcs(ps) wcs = makeWcs( crPixPos = (100.0, 100.0), crValDeg = (10.0, 35.0), projection = "STG", # also fails for TAN ) exposure = afwImage.ExposureF(bbox, wcs) pixPos = afwGeom.Box2D(bbox).getMax() if verbose: print "XY0=", exposure.getXY0() print "pixPos=", pixPos skyPos = wcs.pixelToSky(pixPos) with utilsTests.getTempFilePath(".fits") as tmpFile: exposure.writeFits(tmpFile) for useExposure in (False, True): if useExposure: unpExp = afwImage.ExposureF(tmpFile) unpWcs = unpExp.getWcs() else: md = afwImage.readMetadata(tmpFile) unpWcs = afwImage.makeWcs(md, False) unpPixPos = unpWcs.skyToPixel(skyPos) if verbose: print "useExposure=%s; unp pixPos=%s" % (useExposure, unpPixPos) for i in range(2): self.assertAlmostEqual(unpPixPos[i], 1009.5)
def test_flare_lc_failure(self): """ Test that the correct exception is thrown when you try to interpolate from an MLT light curve cache that does not exist """ with getTempFilePath('.txt') as cat_name: db = MLT_test_DB(database=self.db_name, driver='sqlite') obs = ObservationMetaData(mjd=67432.1) flare_cat = FlaringCatalog(db, obs_metadata=obs) flare_cat._mlt_lc_file = 'a_nonexistent_cache' with self.assertRaises(RuntimeError) as context: flare_cat.write_catalog(cat_name) self.assertIn('get_mdwarf_flares.sh', context.exception.args[0])
def testWcsWhenNonPersistable(self): """Test that we can round-trip a WCS even when it is not persistable""" import os fileName = os.path.join(os.path.split(__file__)[0], "data", "ZPN.fits") exp = lsst.afw.image.ExposureF(fileName) del fileName self.assertFalse(exp.getWcs().isPersistable(), "Test assumes that ZPN projections are not persistable") with utilsTests.getTempFilePath(".fits") as fileName: exp.writeFits(fileName) exp2 = lsst.afw.image.ExposureF(fileName) self.assertEqual(exp.getWcs(), exp2.getWcs())
def testReadMetadata(self): with utilsTests.getTempFilePath(".fits") as tmpFile: self.exposureCrWcs.getMetadata().set("FRAZZLE", True) # This will write the main metadata (inc. FRAZZLE) to the primary HDU, and the # WCS to subsequent HDUs, along with INHERIT=T. self.exposureCrWcs.writeFits(tmpFile) # This should read the first non-empty HDU (i.e. it skips the primary), but # goes back and reads it if it finds INHERIT=T. That should let us read # frazzle and the Wcs from the PropertySet returned by readMetadata. md = afwImage.readMetadata(tmpFile) wcs = afwImage.makeWcs(md, True) self.assertEqual(wcs.getPixelOrigin(), self.wcs.getPixelOrigin()) self.assertEqual(wcs.getSkyOrigin(), self.wcs.getSkyOrigin()) self.assert_(numpy.all(wcs.getCDMatrix() == self.wcs.getCDMatrix())) frazzle = md.get("FRAZZLE") self.assert_(frazzle is True)
def testWcsWhenNonPersistable(self): """Test that we can round-trip a WCS even when it is not persistable""" import os fileName = os.path.join(os.path.split(__file__)[0], "data", "ZPN.fits") exp = lsst.afw.image.ExposureF(fileName) del fileName self.assertFalse( exp.getWcs().isPersistable(), "Test assumes that ZPN projections are not persistable") with utilsTests.getTempFilePath(".fits") as fileName: exp.writeFits(fileName) exp2 = lsst.afw.image.ExposureF(fileName) self.assertEqual(exp.getWcs(), exp2.getWcs())
def testBoostPersistence(self): """Persist the image using boost""" with utilsTests.getTempFilePath(".boost") as boostFilePath: logicalLocation = dafPers.LogicalLocation(boostFilePath) storage = self.persistence.getPersistStorage("BoostStorage", logicalLocation) storageList = dafPers.StorageList([storage]) self.persistence.persist(self.image, storageList, self.additionalData) # Retrieve it again storage = self.persistence.getRetrieveStorage("BoostStorage", logicalLocation) storageList = dafPers.StorageList([storage]) pers2Ptr = self.persistence.unsafeRetrieve("ImageF", storageList, self.additionalData) image2 = afwImage.ImageF.swigConvert(pers2Ptr) # Check the resulting Image self.checkImages(self.image, image2)
def testIo(self): for Image in (afwImage.ImageU, afwImage.ImageL, afwImage.ImageI, afwImage.ImageF, afwImage.ImageD, ): image = Image(self.cols, self.rows) for x in xrange(0, self.cols): for y in xrange(0, self.rows): image.set(x, y, x + y) with utilsTests.getTempFilePath("_%s.fits" % (Image.__name__,)) as filename: image.writeFits(filename) readImage = Image(filename) self.checkImages(readImage, image)
def testReadMetadata(self): with utilsTests.getTempFilePath(".fits") as tmpFile: self.exposureCrWcs.getMetadata().set("FRAZZLE", True) # This will write the main metadata (inc. FRAZZLE) to the primary HDU, and the # WCS to subsequent HDUs, along with INHERIT=T. self.exposureCrWcs.writeFits(tmpFile) # This should read the first non-empty HDU (i.e. it skips the primary), but # goes back and reads it if it finds INHERIT=T. That should let us read # frazzle and the Wcs from the PropertySet returned by readMetadata. md = afwImage.readMetadata(tmpFile) wcs = afwImage.makeWcs(md, True) self.assertEqual(wcs.getPixelOrigin(), self.wcs.getPixelOrigin()) self.assertEqual(wcs.getSkyOrigin(), self.wcs.getSkyOrigin()) self.assert_( numpy.all(wcs.getCDMatrix() == self.wcs.getCDMatrix())) frazzle = md.get("FRAZZLE") self.assert_(frazzle is True)
def testMEF(self): """Test writing a set of images to an MEF fits file, and then reading them back""" with utilsTests.getTempFilePath(".fits") as tmpFile: 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(tmpFile, None, mode) for hdu in range(1, 5): im = afwImage.ImageF(tmpFile, hdu) self.assertEqual(im.get(0, 0), 100*hdu)
def testBackgroundListIO(self): """Test I/O for BackgroundLists """ bgCtrl = afwMath.BackgroundControl(10, 10) interpStyle = afwMath.Interpolate.AKIMA_SPLINE undersampleStyle = afwMath.REDUCE_INTERP_ORDER approxOrderX = 6 approxOrderY = 6 approxWeighting = True im = self.image.Factory(self.image, self.image.getBBox(afwImage.PARENT)) arr = im.getArray() arr += np.random.normal(size=(im.getHeight(),im.getWidth())) for astyle in afwMath.ApproximateControl.UNKNOWN, afwMath.ApproximateControl.CHEBYSHEV: actrl = afwMath.ApproximateControl(astyle, approxOrderX) bgCtrl.setApproximateControl(actrl) backgroundList = afwMath.BackgroundList() backImage = afwImage.ImageF(im.getDimensions()) for i in range(2): bkgd = afwMath.makeBackground(im, bgCtrl) if i == 0: # no need to call getImage backgroundList.append((bkgd, interpStyle, undersampleStyle, astyle, approxOrderX, approxOrderY, approxWeighting)) else: backgroundList.append(bkgd) # Relies on having called getImage; deprecated backImage += bkgd.getImageF(interpStyle, undersampleStyle) with utilsTests.getTempFilePath(".fits") as fileName: backgroundList.writeFits(fileName) backgrounds = afwMath.BackgroundList.readFits(fileName) img = backgrounds.getImage() # # Check that the read-back image is identical to that generated from the backgroundList # round-tripped to disk # backImage -= img self.assertEqual(np.min(backImage.getArray()), 0.0) self.assertEqual(np.max(backImage.getArray()), 0.0)
def testTablePersistence(self): ellipse = afwGeomEllipses.Ellipse(afwGeomEllipses.Axes(8, 6, 0.25), afwGeom.Point2D(9,15)) fp1 = afwDetect.Footprint(ellipse) fp1.addPeak(6, 7, 2) fp1.addPeak(8, 9, 3) with utilsTests.getTempFilePath(".fits") as tmpFile: fp1.writeFits(tmpFile) fp2 = afwDetect.Footprint.readFits(tmpFile) self.assertEqual(fp1.getArea(), fp2.getArea()) self.assertEqual(list(fp1.getSpans()), list(fp2.getSpans())) # can't use Peak operator== for comparison because it compares IDs, not positions/values self.assertEqual(len(fp1.getPeaks()), len(fp2.getPeaks())) for peak1, peak2 in zip(fp1.getPeaks(), fp2.getPeaks()): self.assertEqual(peak1.getIx(), peak2.getIx()) self.assertEqual(peak1.getIy(), peak2.getIy()) self.assertEqual(peak1.getFx(), peak2.getFx()) self.assertEqual(peak1.getFy(), peak2.getFy()) self.assertEqual(peak1.getPeakValue(), peak2.getPeakValue())
def test_alternate_db(self): with getTempFilePath('.alt_cloud.db') as tmpdb: cloud_dbfile = tmpdb cloud_table = [] cloud_table.append("cloudId INTEGER PRIMARY KEY") cloud_table.append("c_date INTEGER") cloud_table.append("cloud DOUBLE") with sqlite3.connect(cloud_dbfile) as conn: cur = conn.cursor() cur.execute("DROP TABLE IF EXISTS Cloud") cur.execute("CREATE TABLE Cloud({})".format( ",".join(cloud_table))) cur.executemany("INSERT INTO Cloud VALUES(?, ?, ?)", [(1, 9997, 0.5), (2, 10342, 0.125)]) cur.close() cloud1 = CloudData(self.th, tmpdb) cloud1.read_data() self.assertEqual(cloud1.cloud_values.size, 2) self.assertEqual(cloud1.cloud_values[1], 0.125)
def testIo(self): for Image in ( afwImage.ImageU, afwImage.ImageL, afwImage.ImageI, afwImage.ImageF, afwImage.ImageD, ): image = Image(self.cols, self.rows) for x in xrange(0, self.cols): for y in xrange(0, self.rows): image.set(x, y, x + y) with utilsTests.getTempFilePath("_%s.fits" % (Image.__name__, )) as filename: image.writeFits(filename) readImage = Image(filename) self.checkImages(readImage, image)
def testWriteBool(self): """Test that we can read and write bools""" import lsst.afw.image as afwImage import lsst.daf.base as dafBase with utilsTests.getTempFilePath(".fits") as tmpFile: im = afwImage.ImageF(afwGeom.ExtentI(10,20)) md = dafBase.PropertySet() keys = {"BAD" : False, "GOOD" : True, } for k, v in keys.items(): md.add(k, v) im.writeFits(tmpFile, md) jim = afwImage.DecoratedImageF(tmpFile) for k, v in keys.items(): self.assertEqual(jim.getMetadata().get(k), v)
def testWriteFits(self): nMaskPlanes0 = self.Mask.getNumPlanesUsed() mask = self.Mask(self.maskFile, 3) self.assertMasksEqual(mask, self.expect << nMaskPlanes0) with utilsTests.getTempFilePath(".fits") as tmpFile: mask.writeFits(tmpFile) # Read it back md = lsst.daf.base.PropertySet() rmask = self.Mask(tmpFile, 0, md) self.assertMasksEqual(mask, rmask) # Check that we wrote (and read) the metadata successfully mp_ = "MP_" if True else self.Mask.maskPlanePrefix( ) # currently private for (k, v) in self.Mask().getMaskPlaneDict().items(): self.assertEqual(md.get(mp_ + k), v)
def testExposure(self): """Test that we load the Wcs from the binary table instead of headers when possible.""" self.addSipMetadata() wcsIn = lsst.afw.image.makeWcs(self.metadata) dim = lsst.afw.geom.Extent2I(20, 30) expIn = lsst.afw.image.ExposureF(dim) expIn.setWcs(wcsIn) with utilsTests.getTempFilePath(".fits") as fileName: expIn.writeFits(fileName) # Manually mess up the headers, so we'd know if we were loading the Wcs from that; # when there is a WCS in the header and a WCS in the FITS table, we should use the # latter, because the former might just be an approximation. fits = pyfits.open(fileName) fits[1].header.remove("CTYPE1") fits[1].header.remove("CTYPE2") fits.writeto(fileName, clobber=True) # now load it using afw expOut = lsst.afw.image.ExposureF(fileName) wcsOut = expOut.getWcs() self.assertEqual(wcsIn, wcsOut)