def testArithmeticImagesMismatch(self): "Test arithmetic operations on Images of different sizes" i1 = afwImage.ImageF(100, 100) i1.set(100) i2 = afwImage.ImageF(10, 10) i2.set(10) def tst1(i1, i2): i1 -= i2 def tst2(i1, i2): i1.scaledMinus(1.0, i2) def tst3(i1, i2): i1 += i2 def tst4(i1, i2): i1.scaledPlus(1.0, i2) def tst5(i1, i2): i1 *= i2 def tst6(i1, i2): i1.scaledMultiplies(1.0, i2) def tst7(i1, i2): i1 /= i2 def tst8(i1, i2): i1.scaledDivides(1.0, i2) tsts12 = [tst1, tst3, tst5, tst7] for tst in tsts12: utilsTests.assertRaisesLsstCpp(self, lsst.pex.exceptions.LengthErrorException, tst, i1, i2) tsts21 = [tst2, tst4, tst6, tst8] for tst in tsts21: utilsTests.assertRaisesLsstCpp(self, lsst.pex.exceptions.LengthErrorException, tst, i2, i1)
def testNoCells(self): """Test that we check for a request to make a SpatialCellSet with no cells""" def tst(): afwMath.SpatialCellSet(afwGeom.Box2I(afwGeom.Point2I(0, 0), afwGeom.Extent2I(500, 500)), 0, 3) utilsTests.assertRaisesLsstCpp(self, pexExcept.LengthErrorException, tst)
def testDeltaFunctionKernel(self): """Test DeltaFunctionKernel """ for kWidth in range(1, 4): for kHeight in range(1, 4): for activeCol in range(kWidth): for activeRow in range(kHeight): kernel = afwMath.DeltaFunctionKernel( kWidth, kHeight, afwGeom.Point2I(activeCol, activeRow)) kImage = afwImage.ImageD(kernel.getDimensions()) kSum = kernel.computeImage(kImage, False) self.assertEqual(kSum, 1.0) kArr = kImage.getArray().transpose() self.assertEqual(kArr[activeCol, activeRow], 1.0) kArr[activeCol, activeRow] = 0.0 self.assertEqual(kArr.sum(), 0.0) errStr = self.compareKernels(kernel, kernel.clone()) if errStr: self.fail(errStr) utilsTests.assertRaisesLsstCpp( self, pexExcept.InvalidParameterException, afwMath.DeltaFunctionKernel, 0, kHeight, afwGeom.Point2I(kWidth, kHeight)) utilsTests.assertRaisesLsstCpp( self, pexExcept.InvalidParameterException, afwMath.DeltaFunctionKernel, kWidth, 0, afwGeom.Point2I(kWidth, kHeight)) kernel = afwMath.DeltaFunctionKernel(5, 6, afwGeom.Point2I(1, 1)) self.basicTests(kernel, 0) self.verifyCache(kernel, hasCache=False)
def testBoundsChecking(self): """Check that pixel indexes are checked in python""" tsts = [] def tst(): self.mask1.get(-1, 0) tsts.append(tst) def tst(): self.mask1.get(0, -1) tsts.append(tst) def tst(): self.mask1.get(self.mask1.getWidth(), 0) tsts.append(tst) def tst(): self.mask1.get(0, self.mask1.getHeight()) tsts.append(tst) for tst in tsts: utilsTests.assertRaisesLsstCpp( self, lsst.pex.exceptions.LengthErrorException, tst)
def testInvalidPlaneOperations(self): """Test mask plane operations invalidated by Mask changes""" testMask3 = self.Mask(self.testMask.getDimensions()) name = "Great Timothy" self.Mask.addMaskPlane(name) testMask3.removeAndClearMaskPlane(name) self.Mask.getMaskPlane(name) # should be fine self.assertRaises(IndexError, lambda : testMask3.getMaskPlaneDict()[name]) def tst(): self.testMask |= testMask3 utilsTests.assertRaisesLsstCpp(self, pexExcept.RuntimeErrorException, tst) self.Mask.addMaskPlane(name) # The dictionary should be back to the same state, so ... tst # ... assertion should not fail self.testMask.removeAndClearMaskPlane(name, True) self.Mask.addMaskPlane("Mario") # takes name's slot self.Mask.addMaskPlane(name) utilsTests.assertRaisesLsstCpp(self, pexExcept.RuntimeErrorException, tst)
def testCalibNegativeFlux(self): """Check that we can control if -ve fluxes raise exceptions""" self.calib.setFluxMag0(1e12) funcs = [ lambda: self.calib.getMagnitude(-10), lambda: self.calib.getMagnitude(-10, 1) ] for func in funcs: tests.assertRaisesLsstCpp(self, pexExcept.DomainErrorException, func) afwImage.Calib.setThrowOnNegativeFlux(False) for func in funcs: mags = func() try: # deal with returning mag or [mag, magErr] mags[0] except TypeError: mags = [mags, None] for m in mags: if m is not None: self.assertTrue(numpy.isnan(m)) afwImage.Calib.setThrowOnNegativeFlux(True) for func in funcs: tests.assertRaisesLsstCpp(self, pexExcept.DomainErrorException, func)
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.ImageD(afwGeom.Extent2I(nx, ny)) # make a background control object bctrl = afwMath.BackgroundControl() bctrl.setInterpStyle(afwMath.Interpolate.CUBIC_SPLINE) 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) self.assertEqual(backobj.getBackgroundControl().getInterpStyle(), afwMath.Interpolate.LINEAR) # put interp style back up to cspline and see if it throws an exception bctrl.setUndersampleStyle("THROW_EXCEPTION") bctrl.setInterpStyle("CUBIC_SPLINE") def tst(im, bc): backobj = afwMath.makeBackground(im, bc) utilsTests.assertRaisesLsstCpp(self, lsst.pex.exceptions.InvalidParameterException, tst, img, bctrl)
def testCalibFromCalibs(self): """Test creating a Calib from an array of Calibs""" exptime = 20 mag0, mag0Sigma = 1.0, 0.01 time0 = dafBase.DateTime.now().get() calibs = afwImage.vectorCalib() ncalib = 3 for i in range(ncalib): calib = afwImage.Calib() calib.setMidTime(dafBase.DateTime(time0 + i)) calib.setExptime(exptime) calib.setFluxMag0(mag0, mag0Sigma) calibs.append(calib) ocalib = afwImage.Calib(calibs) self.assertEqual(ocalib.getExptime(), ncalib*exptime) self.assertAlmostEqual(calibs[ncalib//2].getMidTime().get(), ocalib.getMidTime().get()) # # Check that we can only merge Calibs with the same fluxMag0 values # calibs[0].setFluxMag0(1.001*mag0, mag0Sigma) tests.assertRaisesLsstCpp(self, pexExcept.InvalidParameterException, lambda : afwImage.Calib(calibs))
def testCalibFromCalibs(self): """Test creating a Calib from an array of Calibs""" exptime = 20 mag0, mag0Sigma = 1.0, 0.01 time0 = dafBase.DateTime.now().get() calibs = afwImage.vectorCalib() ncalib = 3 for i in range(ncalib): calib = afwImage.Calib() calib.setMidTime(dafBase.DateTime(time0 + i)) calib.setExptime(exptime) calib.setFluxMag0(mag0, mag0Sigma) calibs.append(calib) ocalib = afwImage.Calib(calibs) self.assertEqual(ocalib.getExptime(), ncalib * exptime) self.assertAlmostEqual(calibs[ncalib // 2].getMidTime().get(), ocalib.getMidTime().get()) # # Check that we can only merge Calibs with the same fluxMag0 values # calibs[0].setFluxMag0(1.001 * mag0, mag0Sigma) tests.assertRaisesLsstCpp(self, pexExcept.InvalidParameterException, lambda: afwImage.Calib(calibs))
def testInvalidPlaneOperations(self): """Test mask plane operations invalidated by Mask changes""" testMask3 = self.Mask(self.testMask.getDimensions()) name = "Great Timothy" self.Mask.addMaskPlane(name) testMask3.removeAndClearMaskPlane(name) self.Mask.getMaskPlane(name) # should be fine self.assertRaises(IndexError, lambda: testMask3.getMaskPlaneDict()[name]) def tst(): self.testMask |= testMask3 utilsTests.assertRaisesLsstCpp(self, pexExcept.RuntimeErrorException, tst) self.Mask.addMaskPlane( name) # The dictionary should be back to the same state, so ... tst # ... assertion should not fail self.testMask.removeAndClearMaskPlane(name, True) self.Mask.addMaskPlane("Mario") # takes name's slot self.Mask.addMaskPlane(name) utilsTests.assertRaisesLsstCpp(self, pexExcept.RuntimeErrorException, tst)
def testInvalidPlaneOperations2(self): """Test mask plane operations invalidated by Mask changes""" testMask3 = self.Mask(self.testMask.getDimensions()) name = "Great Timothy" name2 = "Our Boss" self.Mask.addMaskPlane(name) self.Mask.addMaskPlane(name2) oldDict = testMask3.getMaskPlaneDict() # a description of the Mask's current dictionary for n in (name, name2): self.testMask.removeAndClearMaskPlane(n, True) self.Mask.addMaskPlane(name2) # added in opposite order to the planes in testMask3 self.Mask.addMaskPlane(name) self.assertNotEqual(self.testMask.getMaskPlaneDict()[name], oldDict[name]) def tst(): self.testMask |= testMask3 self.testMask.removeAndClearMaskPlane("BP") utilsTests.assertRaisesLsstCpp(self, pexExcept.RuntimeErrorException, tst) # # OK, that failed as it should. Fixup the dictionaries and try again # self.Mask.addMaskPlane("BP") testMask3.conformMaskPlanes(oldDict) # convert testMask3 from oldDict to current default self.testMask |= testMask3 # shouldn't throw
def testInsertCandidate(self): """Insert candidates into the SpatialCellSet""" self.makeTestCandidateCellSet() def tst(): self.cellSet.insertCandidate(testLib.TestCandidate(501, 501, 100)) # Doesn't fit utilsTests.assertRaisesLsstCpp(self, pexExcept.OutOfRangeException, tst) # # OK, the SpatialCellList is populated # cell0 = self.cellSet.getCellList()[0] self.assertFalse(cell0.empty()) self.assertEqual(cell0[0].getXCenter(), 0.0) self.assertEqual(self.cellSet.getCellList()[1][0].getXCenter(), 305.0) self.assertTrue(self.cellSet.getCellList()[2].empty()) def tst1(): self.cellSet.getCellList()[2][0] self.assertRaises(IndexError, tst1) def tst2(): self.cellSet.getCellList()[2].begin().__deref__() utilsTests.assertRaisesLsstCpp(self, pexExcept.NotFoundException, tst2) self.assertFalse(self.cellSet.getCellList()[5].empty())
def testCalibNegativeFlux(self): """Check that we can control if -ve fluxes raise exceptions""" self.calib.setFluxMag0(1e12) funcs = [lambda : self.calib.getMagnitude(-10), lambda : self.calib.getMagnitude(-10, 1)] for func in funcs: tests.assertRaisesLsstCpp(self, pexExcept.DomainErrorException, func) afwImage.Calib.setThrowOnNegativeFlux(False) for func in funcs: mags = func() try: # deal with returning mag or [mag, magErr] mags[0] except TypeError: mags = [mags, None] for m in mags: if m is not None: self.assertTrue(numpy.isnan(m)) afwImage.Calib.setThrowOnNegativeFlux(True) for func in funcs: tests.assertRaisesLsstCpp(self, pexExcept.DomainErrorException, func)
def testAddTrimmedAmp(self): """Test that building a Ccd from trimmed Amps leads to a trimmed Ccd""" dataSec = afwGeom.BoxI(afwGeom.PointI(1, 0), afwGeom.ExtentI(10, 20)) biasSec = afwGeom.BoxI(afwGeom.PointI(0, 0), afwGeom.ExtentI(1, 1)) allPixelsInAmp = afwGeom.BoxI(afwGeom.PointI(0, 0), afwGeom.ExtentI(11, 21)) eParams = cameraGeom.ElectronicParams(1.0, 1.0, 65000) ccd = cameraGeom.Ccd(cameraGeom.Id(0)) self.assertFalse(ccd.isTrimmed()) for i in range(2): amp = cameraGeom.Amp(cameraGeom.Id(i, "", i, 0), allPixelsInAmp, biasSec, dataSec, eParams) amp.setTrimmed(True) if i%2 == 0: # check both APIs ccd.addAmp(afwGeom.PointI(i, 0), amp) else: ccd.addAmp(amp) self.assertTrue(ccd.isTrimmed()) # should fail to add non-trimmed Amp to a trimmed Ccd i += 1 amp = cameraGeom.Amp(cameraGeom.Id(i, "", i, 0), allPixelsInAmp, biasSec, dataSec, eParams) self.assertFalse(amp.isTrimmed()) utilsTests.assertRaisesLsstCpp(self, pexExcept.InvalidParameterException, ccd.addAmp, amp) # should fail to add trimmed Amp to a non-trimmed Ccd ccd.setTrimmed(False) amp.setTrimmed(True) utilsTests.assertRaisesLsstCpp(self, pexExcept.InvalidParameterException, ccd.addAmp, amp)
def testPhotom(self): """Test the zero-point information""" flux, fluxErr = 1000.0, 10.0 flux0, flux0Err = 1e12, 1e10 self.calib.setFluxMag0(flux0) self.assertEqual(flux0, self.calib.getFluxMag0()[0]) self.assertEqual(0.0, self.calib.getFluxMag0()[1]) self.assertEqual(22.5, self.calib.getMagnitude(flux)) # Error just in flux self.assertAlmostEqual(self.calib.getMagnitude(flux, fluxErr)[1], 2.5/math.log(10)*fluxErr/flux) # Error just in flux0 self.calib.setFluxMag0(flux0, flux0Err) self.assertEqual(flux0Err, self.calib.getFluxMag0()[1]) self.assertAlmostEqual(self.calib.getMagnitude(flux, 0)[1], 2.5/math.log(10)*flux0Err/flux0) self.assertAlmostEqual(flux0, self.calib.getFlux(0)) self.assertAlmostEqual(flux, self.calib.getFlux(22.5)) # I don't know how to test round-trip if fluxMag0 is significant compared to fluxErr self.calib.setFluxMag0(flux0, flux0 / 1e6) for fluxErr in (flux / 1e2, flux / 1e4): mag, magErr = self.calib.getMagnitude(flux, fluxErr) self.assertAlmostEqual(flux, self.calib.getFlux(mag, magErr)[0]) self.assertTrue(abs(fluxErr - self.calib.getFlux(mag, magErr)[1]) < 1.0e-4) # Test context manager; shouldn't raise an exception within the block, should outside with imageUtils.CalibNoThrow(): self.assert_(numpy.isnan(self.calib.getMagnitude(-50.0))) tests.assertRaisesLsstCpp(self, pexExcept.DomainErrorException, self.calib.getMagnitude, -50.0)
def testTicket2872(self): """Test that CoaddPsf.getAveragePosition() is always a position at which we can call computeImage(). """ schema = afwTable.ExposureTable.makeMinimalSchema() weightKey = schema.addField("weight", type=float, doc="photometric weight") catalog = afwTable.ExposureCatalog(schema) cdelt = (0.2*afwGeom.arcseconds).asDegrees() wcs = afwImage.makeWcs( afwCoord.IcrsCoord(afwGeom.Point2D(45.0, 45.0), afwGeom.degrees), afwGeom.Point2D(50, 50), cdelt, 0.0, 0.0, cdelt ) kernel = measAlg.DoubleGaussianPsf(7,7,2.0).getKernel() psf1 = measAlg.KernelPsf(kernel, afwGeom.Point2D(0, 50)) psf2 = measAlg.KernelPsf(kernel, afwGeom.Point2D(100, 50)) record1 = catalog.addNew() record1.setPsf(psf1) record1.setWcs(wcs) record1.setD(weightKey, 1.0); record1.setBBox(afwGeom.Box2I(afwGeom.Point2I(-40, 0), afwGeom.Point2I(40, 100))) record2 = catalog.addNew() record2.setPsf(psf2) record2.setWcs(wcs) record2.setD(weightKey, 1.0); record2.setBBox(afwGeom.Box2I(afwGeom.Point2I(60, 0), afwGeom.Point2I(140, 100))) coaddPsf = measAlg.CoaddPsf(catalog, wcs) naiveAvgPos = afwGeom.Point2D(50, 50) utilsTests.assertRaisesLsstCpp( self, pexExceptions.InvalidParameterException, coaddPsf.computeKernelImage, naiveAvgPos ) # important test is that this doesn't throw: coaddPsf.computeKernelImage()
def testWriteStarsLegacyAPI(self): with utilsTests.getTempFilePath(".png") as fileName: self.writeFileLegacyAPI(fileName) def tst(): self.writeFileLegacyAPI("rgb.unknown") utilsTests.assertRaisesLsstCpp(self, ValueError, tst)
def testDeltaFunctionKernel(self): """Test DeltaFunctionKernel """ for kWidth in range(1, 4): for kHeight in range(1, 4): for activeCol in range(kWidth): for activeRow in range(kHeight): kernel = afwMath.DeltaFunctionKernel(kWidth, kHeight, afwGeom.Point2I(activeCol, activeRow)) kImage = afwImage.ImageD(kernel.getDimensions()) kSum = kernel.computeImage(kImage, False) self.assertEqual(kSum, 1.0) kArr = kImage.getArray().transpose() self.assertEqual(kArr[activeCol, activeRow], 1.0) kArr[activeCol, activeRow] = 0.0 self.assertEqual(kArr.sum(), 0.0) errStr = self.compareKernels(kernel, kernel.clone()) if errStr: self.fail(errStr) utilsTests.assertRaisesLsstCpp(self, pexExcept.InvalidParameterException, afwMath.DeltaFunctionKernel, 0, kHeight, afwGeom.Point2I(kWidth, kHeight)) utilsTests.assertRaisesLsstCpp(self, pexExcept.InvalidParameterException, afwMath.DeltaFunctionKernel, kWidth, 0, afwGeom.Point2I(kWidth, kHeight)) kernel = afwMath.DeltaFunctionKernel(5, 6, afwGeom.Point2I(1, 1)) self.basicTests(kernel, 0) self.verifyCache(kernel, hasCache=False)
def testInvalidPlaneOperations2(self): """Test mask plane operations invalidated by Mask changes""" testMask3 = afwImage.MaskU(self.testMask.getDimensions()) name = "Great Timothy" name2 = "Our Boss" testMask3.addMaskPlane(name) testMask3.addMaskPlane(name2) oldDict = testMask3.getMaskPlaneDict() self.testMask.removeMaskPlane(name) self.testMask.removeMaskPlane(name2) self.testMask.addMaskPlane(name2) # added in opposite order to testMask3 self.testMask.addMaskPlane(name) self.assertNotEqual(self.testMask.getMaskPlaneDict()[name], oldDict[name]) def tst(): self.testMask |= testMask3 utilsTests.assertRaisesLsstCpp(self, pexExcept.RuntimeErrorException, tst) # # OK, that failed as it should. Fixup the dictionaries and try again # testMask3.conformMaskPlanes(oldDict) self.testMask |= testMask3 # shouldn't throw
def testStats3(self): stats = afwMath.makeStatistics(self.image, afwMath.NPOINT) def getMean(): stats.getValue(afwMath.MEAN) utilsTests.assertRaisesLsstCpp(self, lsst.pex.exceptions.InvalidParameterException, getMean)
def testConversion(self): for n in range(10): xmin, xmax, ymin, ymax = numpy.random.uniform(low=-10, high=10, size=4) if xmin > xmax: xmin, xmax = xmax, xmin if ymin > ymax: ymin, ymax = ymax, ymin fpMin = geom.Point2D(xmin, ymin) fpMax = geom.Point2D(xmax, ymax) if any((fpMax - fpMin).lt(3)): continue # avoid empty boxes fpBox = geom.Box2D(fpMin, fpMax) intBoxBig = geom.Box2I(fpBox, geom.Box2I.EXPAND) fpBoxBig = geom.Box2D(intBoxBig) intBoxSmall = geom.Box2I(fpBox, geom.Box2I.SHRINK) fpBoxSmall = geom.Box2D(intBoxSmall) self.assert_(fpBoxBig.contains(fpBox)) self.assert_(fpBox.contains(fpBoxSmall)) self.assert_(intBoxBig.contains(intBoxSmall)) self.assert_(geom.Box2D(intBoxBig)) self.assertEqual(geom.Box2I(fpBoxBig, geom.Box2I.EXPAND), intBoxBig) self.assertEqual(geom.Box2I(fpBoxSmall, geom.Box2I.SHRINK), intBoxSmall) self.assert_(geom.Box2I(geom.Box2D()).isEmpty()) utilsTests.assertRaisesLsstCpp( self, lsst.pex.exceptions.InvalidParameterException, geom.Box2I, geom.Box2D(geom.Point2D(), geom.Point2D(float("inf"), float("inf"))))
def testChebyshevEqualOrder(self): """Check that we enforce the condition orderX == orderY""" utilsTests.assertRaisesLsstCpp( self, pexExcept.InvalidParameterException, lambda: afwMath.ApproximateControl(afwMath.ApproximateControl.CHEBYSHEV, 1, 2), )
def testAllocateLargeImages(self): """Try to allocate a Very large image""" bbox = afwGeom.BoxI(afwGeom.PointI(-1<<30, -1<<30), afwGeom.PointI(1<<30, 1<<30)) def tst(): im = afwImage.ImageF(bbox) utilsTests.assertRaisesLsstCpp(self, lsst.pex.exceptions.LengthErrorException, tst)
def testStats3(self): stats = afwMath.makeStatistics(self.image, afwMath.NPOINT) def getMean(): stats.getValue(afwMath.MEAN) utilsTests.assertRaisesLsstCpp( self, lsst.pex.exceptions.InvalidParameterException, getMean)
def testBadSubimages(self): def tst(): simage1 = afwImage.ImageF( self.image1, afwGeom.Box2I(afwGeom.Point2I(1, -1), afwGeom.Extent2I(10, 5)), afwImage.LOCAL ) utilsTests.assertRaisesLsstCpp(self, lsst.pex.exceptions.LengthErrorException, tst)
def testGetCandidateById(self): """Check that we can lookup candidates by ID""" id = self.cell[1].getId() self.assertEqual(self.cell.getCandidateById(id).getId(), id) def tst(): self.cell.getCandidateById(-1) # non-existent ID self.assertEqual(self.cell.getCandidateById(-1, True), None) utilsTests.assertRaisesLsstCpp(self, pexExcept.NotFoundException, tst)
def testDistortHangs(self): """Test hanging forever on some positions""" elev = 45 import numpy as np for x, y in [ #(7887.9, -15559), # I thought this failed, but it's passing now (np.nan, np.nan), ]: utilsTests.assertRaisesLsstCpp(self, lsst.pex.exceptions.OutOfRangeException, distest.getDistortedPositionIterative, x, y, elev)
def testPlaneRemoval(self): """Test mask plane removal""" planes = afwImage.MaskU_getMaskPlaneDict() self.testMask.clearMaskPlane(planes['BP']) self.testMask.removeMaskPlane("BP") def checkPlaneBP(): self.testMask.getMaskPlane("BP") utilsTests.assertRaisesLsstCpp(self, pexExcept.InvalidParameterException, checkPlaneBP)
def testFitsReadConform2(self): """Check that conforming a mask invalidates the plane dictionary""" hdu, metadata, bbox, conformMasks = 3, None, afwGeom.Box2I(), True testMask = afwImage.MaskU(self.fileName, hdu, metadata, bbox, afwImage.LOCAL, conformMasks) mask = self.mi.getMask() def tst(mask=mask): mask |= testMask utilsTests.assertRaisesLsstCpp(self, pexEx.RuntimeErrorException, tst)
def testFitsReadConform2(self): """Check that conforming a mask invalidates the plane dictionary""" hdu, metadata, bbox, conformMasks = 0, None, afwGeom.Box2I(), True testMask = afwImage.MaskU(afwImage.MaskedImageF_maskFileName(self.baseName), hdu, metadata, bbox, afwImage.LOCAL, conformMasks) mask = self.mi.getMask() def tst(mask=mask): mask |= testMask utilsTests.assertRaisesLsstCpp(self, pexEx.RuntimeErrorException, tst)
def testLogicalMasksMismatch(self): "Test logical operations on Masks of different sizes" i1 = afwImage.MaskU(afwGeom.ExtentI(100, 100)) i1.set(100) i2 = afwImage.MaskU(afwGeom.ExtentI(10, 10)) i2.set(10) def tst(i1, i2): i1 |= i2 utilsTests.assertRaisesLsstCpp(self, lsst.pex.exceptions.LengthErrorException, tst, i1, i2) def tst2(i1, i2): i1 &= i2 utilsTests.assertRaisesLsstCpp(self, lsst.pex.exceptions.LengthErrorException, tst2, i1, i2)
def testGetSet0Images(self): self.assertEqual(self.image1.get0(0, 0), self.val1) self.image1.setXY0(3,4) self.assertEqual(self.image1.get0(3, 4), self.val1) def f1(): return self.image1.get0(0,0) utilsTests.assertRaisesLsstCpp(self, lsst.pex.exceptions.LengthErrorException, f1) self.image1.set(0,0, 42.) self.assertEqual(self.image1.get0(3,4), 42.) self.image1.set0(3,4, self.val1) self.assertEqual(self.image1.get0(3,4), self.val1) self.assertEqual(self.image1.get(0,0), self.val1)
def testRequestMoreThanOneStat(self): """ Make sure we throw an exception if someone requests more than one type of statistics. """ sctrl = afwMath.StatisticsControl() imgList = afwImage.vectorImageF() for val in self.values: img = afwImage.ImageF(afwGeom.Extent2I(self.nX, self.nY), val) imgList.push_back(img) def tst(): imgStackBad = afwMath.statisticsStack(imgList, afwMath.MEAN | afwMath.MEANCLIP, sctrl) utilsTests.assertRaisesLsstCpp(self, pexEx.InvalidParameterException, tst)
def testInvalidPlaneOperations(self): """Test mask plane operations invalidated by Mask changes""" testMask3 = afwImage.MaskU(self.testMask.getDimensions()) name = "Great Timothy" testMask3.addMaskPlane(name) testMask3.removeMaskPlane(name) # invalidates dictionary version def tst(): self.testMask |= testMask3 utilsTests.assertRaisesLsstCpp(self, pexExcept.RuntimeErrorException, tst)
def testInvalidInputs(self): """Test that invalid inputs cause an abort""" utilsTests.assertRaisesLsstCpp( self, pexExcept.InvalidParameterException, lambda: afwMath.makeInterpolate([], [], afwMath.Interpolate.CONSTANT), ) interp = afwMath.makeInterpolate([0], [1], afwMath.Interpolate.CONSTANT) utilsTests.assertRaisesLsstCpp( self, pexExcept.MemoryException, lambda: afwMath.makeInterpolate([0], [1], afwMath.Interpolate.LINEAR) )
def testGetSubExposure(self): """ Test that a subExposure of the original Exposure can be obtained. The MaskedImage class should throw a lsst::pex::exceptions::InvalidParameter if the requested subRegion is not fully contained within the original MaskedImage. """ # # This subExposure is valid # subBBox = afwGeom.Box2I(afwGeom.Point2I(40, 50), afwGeom.Extent2I(10, 10)) subExposure = self.exposureCrWcs.Factory(self.exposureCrWcs, subBBox, afwImage.LOCAL) self.checkWcs(self.exposureCrWcs, subExposure) # this subRegion is not valid and should trigger an exception # from the MaskedImage class and should trigger an exception # from the WCS class for the MaskedImage 871034p_1_MI. subRegion3 = afwGeom.Box2I(afwGeom.Point2I(100, 100), afwGeom.Extent2I(10, 10)) def getSubRegion(): self.exposureCrWcs.Factory(self.exposureCrWcs, subRegion3, afwImage.LOCAL) utilsTests.assertRaisesLsstCpp(self, pexExcept.LengthErrorException, getSubRegion) # this subRegion is not valid and should trigger an exception # from the MaskedImage class only for the MaskedImage small_MI. # small_MI (cols, rows) = (256, 256) subRegion4 = afwGeom.Box2I(afwGeom.Point2I(250, 250), afwGeom.Extent2I(10, 10)) def getSubRegion(): self.exposureCrWcs.Factory(self.exposureCrWcs, subRegion4, afwImage.LOCAL) utilsTests.assertRaisesLsstCpp(self, pexExcept.LengthErrorException, getSubRegion) #check the sub- and parent- exposures are using the same Wcs transformation subBBox = afwGeom.Box2I(afwGeom.Point2I(40, 50), afwGeom.Extent2I(10, 10)) subExposure = self.exposureCrWcs.Factory(self.exposureCrWcs, subBBox, afwImage.LOCAL) parentPos = self.exposureCrWcs.getWcs().pixelToSky(0,0) parentPos = parentPos.getPosition() subExpPos = subExposure.getWcs().pixelToSky(0,0).getPosition() for i in range(2): self.assertAlmostEqual(parentPos[i], subExpPos[i], 9, "Wcs in sub image has changed")
def testGetCandidateById(self): """Check that we can lookup candidates by ID""" self.makeTestCandidateCellSet() # # OK, the SpatialCellList is populated # id = self.cellSet.getCellList()[0][1].getId() self.assertEqual(self.cellSet.getCandidateById(id).getId(), id) def tst(): self.cellSet.getCandidateById(-1) # non-existent ID self.assertEqual(self.cellSet.getCandidateById(-1, True), None) utilsTests.assertRaisesLsstCpp(self, pexExcept.NotFoundException, tst)
def testMask(self): mask = afwImage.MaskU(afwGeom.Extent2I(10, 10)) mask.set(0x0) mask.set(1, 1, 0x10) mask.set(3, 1, 0x08) mask.set(5, 4, 0x08) mask.set(4, 5, 0x02) stats = afwMath.makeStatistics(mask, afwMath.SUM | afwMath.NPOINT) self.assertEqual(mask.getWidth()*mask.getHeight(), stats.getValue(afwMath.NPOINT)) self.assertEqual(0x1a, stats.getValue(afwMath.SUM)) def tst(): stats = afwMath.makeStatistics(mask, afwMath.MEAN) utilsTests.assertRaisesLsstCpp(self, lsst.pex.exceptions.InvalidParameterException, tst)
def testInvalidDgPsf(self): """Test parameters of dgPsfs, both valid and not""" sigma1, sigma2, b = 1, 0, 0 # sigma2 may be 0 iff b == 0 measAlg.DoubleGaussianPsf(self.ksize, self.ksize, sigma1, sigma2, b) def badSigma1(): sigma1 = 0 measAlg.DoubleGaussianPsf(self.ksize, self.ksize, sigma1, sigma2, b) utilsTests.assertRaisesLsstCpp(self, pexExceptions.DomainErrorException, badSigma1) def badSigma2(): sigma2, b = 0, 1 measAlg.DoubleGaussianPsf(self.ksize, self.ksize, sigma1, sigma2, b) utilsTests.assertRaisesLsstCpp(self, pexExceptions.DomainErrorException, badSigma2)
def testInvalidInputs(self): """Test that invalid inputs cause an abort""" utilsTests.assertRaisesLsstCpp( self, pexExcept.InvalidParameterException, lambda : afwMath.makeInterpolate(np.array([], dtype=float), np.array([], dtype=float), afwMath.Interpolate.CONSTANT) ) interp = afwMath.makeInterpolate(np.array([0], dtype=float), np.array([1], dtype=float), afwMath.Interpolate.CONSTANT) utilsTests.assertRaisesLsstCpp( self, pexExcept.OutOfRangeException, lambda : afwMath.makeInterpolate(np.array([0], dtype=float), np.array([1], dtype=float), afwMath.Interpolate.LINEAR) )
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 utilsTests.assertRaisesLsstCpp( self, lsst.pex.exceptions.InvalidParameterException, tst, img, bctrl)
def testBadAreaFailsSpline(self): """Check that a NaN in the stats image doesn't cause spline interpolation to fail (#2734)""" image = afwImage.ImageF(15, 9) for y in range(image.getHeight()): for x in range(image.getWidth()): image.set( x, y, 1 + 2 * y ) # n.b. linear, which is what the interpolation will fall back to # Set the right corner to NaN. This will mean that we have too few points for a spline interpolator binSize = 3 image[-binSize:, -binSize:] = np.nan nx = image.getWidth() // binSize ny = image.getHeight() // binSize sctrl = afwMath.StatisticsControl() bctrl = afwMath.BackgroundControl(nx, ny, sctrl, afwMath.MEANCLIP) bkgd = afwMath.makeBackground(image, bctrl) if display: ds9.mtv(image) ds9.mtv(afwMath.cast_BackgroundMI(bkgd).getStatsImage(), frame=1) # # Should throw if we don't permit REDUCE_INTERP_ORDER # utilsTests.assertRaisesLsstCpp(self, lsst.pex.exceptions.OutOfRangeException, bkgd.getImageF, afwMath.Interpolate.NATURAL_SPLINE) # # The interpolation should fall back to linear for the right part of the image # where the NaNs don't permit spline interpolation (n.b. this happens to be exact) # bkgdImage = bkgd.getImageF(afwMath.Interpolate.NATURAL_SPLINE, afwMath.REDUCE_INTERP_ORDER) if display: ds9.mtv(bkgdImage, frame=2) image -= bkgdImage self.assertEqual( afwMath.makeStatistics(image, afwMath.MEAN).getValue(), 0.0)
def testPlaneRemoval(self): """Test mask plane removal""" def checkPlaneBP(): self.Mask.getMaskPlane("BP") testMask2 = self.Mask(self.testMask.getDimensions()) self.testMask = self.Mask(self.testMask.getDimensions()) self.testMask.removeAndClearMaskPlane("BP") d = testMask2.getMaskPlaneDict() checkPlaneBP() # still present in default mask self.assertTrue( "BP" in testMask2.getMaskPlaneDict()) # should still be in testMask2 self.Mask.removeMaskPlane("BP") # remove from default mask too utilsTests.assertRaisesLsstCpp(self, pexExcept.InvalidParameterException, checkPlaneBP) utilsTests.assertRaisesLsstCpp(self, pexExcept.InvalidParameterException, lambda: self.Mask.removeMaskPlane( "BP")) # Plane is already removed utilsTests.assertRaisesLsstCpp( self, pexExcept.InvalidParameterException, lambda: self.testMask.removeMaskPlane("RHL gets names right")) # self.Mask.clearMaskPlaneDict() p0 = self.Mask.addMaskPlane("P0") p1 = self.Mask.addMaskPlane("P1") p1 = self.Mask.addMaskPlane( "P1") # a no-op -- readding a plane has no effect # # Check that removing default mask planes doesn't affect pre-existing planes # msk = self.Mask() nmask = len(msk.getMaskPlaneDict()) self.Mask.removeMaskPlane("P0") self.Mask.removeMaskPlane("P1") self.assertEqual(len(msk.getMaskPlaneDict()), nmask) del msk # # Check that removeAndClearMaskPlane can clear the default too # self.Mask.addMaskPlane("BP") self.testMask.removeAndClearMaskPlane("BP", True) utilsTests.assertRaisesLsstCpp(self, pexExcept.InvalidParameterException, checkPlaneBP)
def testAddImages(self): """Test adding images to a PCA set""" nImage = 3 for i in range(nImage): im = afwImage.ImageF(afwGeom.Extent2I(21, 21)) val = 1 im.set(val) self.ImageSet.addImage(im, 1.0) vec = self.ImageSet.getImageList() self.assertEqual(len(vec), nImage) self.assertEqual(vec[nImage - 1].get(0, 0), val) def tst(): """Try adding an image with no flux""" self.ImageSet.addImage(im, 0.0) utilsTests.assertRaisesLsstCpp(self, pexExcept.OutOfRangeException, tst)
def testUnknownFilter(self): """Test that we can define, but not use, an unknown filter""" badFilter = "rhl" # an undefined filter # Not defined tests.assertRaisesLsstCpp(self, pexExcept.NotFoundException, lambda: afwImage.Filter(badFilter)) # Force definition f = afwImage.Filter(badFilter, True) self.assertEqual(f.getName(), badFilter) # name is correctly defined tests.assertRaisesLsstCpp( self, pexExcept.NotFoundException, lambda: f.getFilterProperty().getLambdaEff()) # can't use Filter f # # Now define badFilter # lambdaEff = 666.0 self.defineFilterProperty(badFilter, lambdaEff) self.assertEqual(f.getFilterProperty().getLambdaEff(), lambdaEff) # but now we can # # Check that we didn't accidently define the unknown filter # tests.assertRaisesLsstCpp( self, pexExcept.NotFoundException, lambda: afwImage.Filter().getFilterProperty().getLambdaEff())
def testDefaultGet(self): """Test that we can get a single statistic without specifying it""" stats = afwMath.makeStatistics(self.image, afwMath.MEDIAN) self.assertEqual(stats.getValue(), stats.getValue(afwMath.MEDIAN)) self.assertEqual(stats.getResult()[0], stats.getResult(afwMath.MEDIAN)[0]) # stats = afwMath.makeStatistics(self.image, afwMath.MEDIAN | afwMath.ERRORS) self.assertEqual(stats.getValue(), stats.getValue(afwMath.MEDIAN)) self.assertEqual(stats.getResult(), stats.getResult(afwMath.MEDIAN)) self.assertEqual(stats.getError(), stats.getError(afwMath.MEDIAN)) def tst(): stats.getValue() stats = afwMath.makeStatistics(self.image, afwMath.MEDIAN | afwMath.MEAN) utilsTests.assertRaisesLsstCpp( self, lsst.pex.exceptions.InvalidParameterException, tst)
def testCtorFromMetadata(self): """Test building a Filter from metadata""" metadata = dafBase.PropertySet() metadata.add("FILTER", "g") f = afwImage.Filter(metadata) self.assertEqual(f.getName(), "g") # # Check that we can clean up metadata # afwImage.stripFilterKeywords(metadata) self.assertEqual(len(metadata.names()), 0) badFilter = "rhl" # an undefined filter metadata.add("FILTER", badFilter) # Not defined tests.assertRaisesLsstCpp(self, pexExcept.NotFoundException, lambda: afwImage.Filter(metadata)) # Force definition f = afwImage.Filter(metadata, True) self.assertEqual(f.getName(), badFilter) # name is correctly defined
def testLinearRampAsBackground(self): """Fit a ramp""" ramp, rampCoeffs = self.makeRamp()[0:2] if display: ds9.mtv(ramp, title="Input", frame=0) # # Here's the range that the approximation should be valid (and also the # bbox of the image returned by getImage) # bkgd = afwMath.makeBackground(ramp, afwMath.BackgroundControl(10, 10)) orderMax = 3 # 1 would be enough to fit the ramp for order in range(orderMax + 1): actrl = afwMath.ApproximateControl(afwMath.ApproximateControl.CHEBYSHEV, order) approx = bkgd.getApproximate(actrl) # # Get the Image, the MaskedImage, and the Image with a truncated expansion # for i, aim in enumerate([approx.getImage(), approx.getMaskedImage().getImage(), approx.getImage(order - 1 if order > 1 else -1), ]): if display and (i == 0 and order == 1): ds9.mtv(aim, title="Interpolated", frame=1) for x, y in aim.getBBox().getCorners(): val = np.mean(aim.getArray()) if order == 0 else \ rampCoeffs[0] + rampCoeffs[1]*x + rampCoeffs[1]*y self.assertEqual(aim.get(x, y), val) # # Check that we can't "truncate" the expansion to a higher order than we requested # utilsTests.assertRaisesLsstCpp(self, pexExcept.InvalidParameterException, lambda : approx.getImage(orderMax + 1, orderMax + 1))
def testInvalidPlaneOperations2(self): """Test mask plane operations invalidated by Mask changes""" testMask3 = self.Mask(self.testMask.getDimensions()) name = "Great Timothy" name2 = "Our Boss" self.Mask.addMaskPlane(name) self.Mask.addMaskPlane(name2) oldDict = testMask3.getMaskPlaneDict( ) # a description of the Mask's current dictionary for n in (name, name2): self.testMask.removeAndClearMaskPlane(n, True) self.Mask.addMaskPlane( name2) # added in opposite order to the planes in testMask3 self.Mask.addMaskPlane(name) self.assertNotEqual(self.testMask.getMaskPlaneDict()[name], oldDict[name]) def tst(): self.testMask |= testMask3 self.testMask.removeAndClearMaskPlane("BP") utilsTests.assertRaisesLsstCpp(self, pexExcept.RuntimeErrorException, tst) # # OK, that failed as it should. Fixup the dictionaries and try again # self.Mask.addMaskPlane("BP") testMask3.conformMaskPlanes( oldDict) # convert testMask3 from oldDict to current default self.testMask |= testMask3 # shouldn't throw