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 testSortedAmps(self): """Test if the Amps are sorted by ID after insertion into a Ccd""" ccd = cameraGeom.Ccd(cameraGeom.Id()) Col = 0 for serial in [0, 1, 2, 3, 4, 5, 6, 7]: gain, readNoise, saturationLevel = 0, 0, 0 width, height = 10, 10 allPixels = afwGeom.Box2I(afwGeom.Point2I(0, 0), afwGeom.Extent2I(width, height)) biasSec = afwGeom.Box2I(afwGeom.Point2I(0, 0), afwGeom.Extent2I(0, height)) dataSec = afwGeom.Box2I(afwGeom.Point2I(0, 0), afwGeom.Extent2I(width, height)) eParams = cameraGeom.ElectronicParams(gain, readNoise, saturationLevel) amp = cameraGeom.Amp(cameraGeom.Id(serial, "", Col, 0), allPixels, biasSec, dataSec, eParams) ccd.addAmp(afwGeom.Point2I(Col, 0), amp); Col += 1 # # Check that Amps are sorted by Id # serials = [] for a in ccd: serials.append(a.getId().getSerial()) self.assertEqual(serials, sorted(serials))
def testCamera(self): """Test if we can build a Camera out of Rafts""" #print >> sys.stderr, "Skipping testCamera"; return cameraInfo = {"ampSerial" : CameraGeomTestCase.ampSerial} camera = cameraGeomUtils.makeCamera(self.geomPolicy, cameraInfo=cameraInfo) if display: cameraGeomUtils.showCamera(camera, ) ds9.incrDefaultFrame() if False: print cameraGeomUtils.describeCamera(camera) self.assertEqual(camera.getAllPixels().getWidth(), cameraInfo["width"]) self.assertEqual(camera.getAllPixels().getHeight(), cameraInfo["height"]) name = "R:1,0" self.assertEqual(camera.findDetector(cameraGeom.Id(name)).getId().getName(), name) self.assertEqual(camera.getSize().getMm()[0], cameraInfo["widthMm"]) self.assertEqual(camera.getSize().getMm()[1], cameraInfo["heightMm"]) # # Test mapping pixel <--> mm # for ix, iy, x, y in [(102, 500, -3.12, 2.02), (152, 525, -2.62, 2.27), (714, 500, 3.12, 2.02), ]: pix = afwGeom.PointD(ix, iy) # wrt raft LLC pos = cameraGeom.FpPoint(x, y) # center of pixel wrt raft center posll = cameraGeom.FpPoint(x, y) # llc of pixel wrt raft center # may need to restructure this since adding FpPoint if False: self.assertEqual(camera.getPixelFromPosition(pos), pix) # there is no unique mapping from a pixel to a focal plane position # ... the pixel could be on any ccd if False: self.assertEqual(camera.getPositionFromPixel(pix).getMm(), posll.getMm()) # Check that we can find an Amp in the bowels of the camera ccdName = "C:1,0" amp = cameraGeomUtils.findAmp(camera, cameraGeom.Id(ccdName), 1, 2) self.assertFalse(amp is None) self.assertEqual(amp.getId().getName(), "ID7") self.assertEqual(amp.getParent().getId().getName(), ccdName)
def testRaft(self): """Test if we can build a Raft out of Ccds""" #print >> sys.stderr, "Skipping testRaft"; return raftId = cameraGeom.Id("Raft") raftInfo = {"ampSerial" : CameraGeomTestCase.ampSerial} raft = cameraGeomUtils.makeRaft(self.geomPolicy, raftId, raftInfo=raftInfo) if display: cameraGeomUtils.showRaft(raft) ds9.incrDefaultFrame() if False: print cameraGeomUtils.describeRaft(raft) self.assertEqual(raft.getAllPixels().getWidth(), raftInfo["width"]) self.assertEqual(raft.getAllPixels().getHeight(), raftInfo["height"]) name = "C:0,2" self.assertEqual(raft.findDetector(cameraGeom.Id(name)).getId().getName(), name) self.assertEqual(raft.getSize().getMm()[0], raftInfo["widthMm"]) self.assertEqual(raft.getSize().getMm()[1], raftInfo["heightMm"]) # # Test mapping pixel <--> mm # ps = raft.getPixelSize() for ix, iy, x, y in [(102, 500, -1.01, 2.02), (306, 100, 1.01, -2.02), (306, 500, 1.01, 2.02), (356, 525, 1.51, 2.27), ]: pix = afwGeom.Point2I(ix, iy) # wrt raft LLC #position of pixel center pos = cameraGeom.FpPoint(x+ps/2., y+ps/2.) # wrt raft center #position of pixel lower left corner which is returned by getPositionFromPixel() posll = cameraGeom.FpPoint(x, y) # wrt raft center rpos = raft.getPixelFromPosition(pos) rpos = afwGeom.PointI(int(rpos.getX()), int(rpos.getY())) # need to rework cameraGeom since FpPoint changes. disable this for now if False: self.assertEqual(rpos, pix) # this test is no longer meaningful as pixel is specific to a detector xy0 if False: self.assertEqual(raft.getPositionFromPixel(afwGeom.Point2D(pix[0], pix[1])).getMm(), posll.getMm())
def makeAmp(i): height = 2048 width = 4096 allPixels = afwGeom.BoxI( afwGeom.PointI(0, 0), afwGeom.ExtentI(width + nExtended + nOverclock, height)) return cameraGeom.Amp(cameraGeom.Id(i), allPixels, None, None, None)
def testLinearity(self): """Test if we can set Linearity parameters""" for ccdNum, threshold in [(-1, 0), (1234, 10),]: ccdId = cameraGeom.Id(ccdNum, "") ccd = cameraGeomUtils.makeCcd(self.geomPolicy, ccdId) for amp in list(ccd)[0:2]: # only two amps in TestCameraGeom.paf lin = amp.getElectronicParams().getLinearity() self.assertEqual(lin.threshold, threshold)
def testSortedCcds(self): """Test if the Ccds are sorted by ID after insertion into a Raft""" raft = cameraGeom.Raft(cameraGeom.Id(), 8, 1) Col = 0 for serial in [7, 0, 1, 3, 2, 6, 5, 4]: ccd = cameraGeom.Ccd(cameraGeom.Id(serial)) raft.addDetector(afwGeom.Point2I(Col, 0), cameraGeom.FpPoint(afwGeom.Point2D(0, 0)), cameraGeom.Orientation(0), ccd) Col += 1 # # Check that CCDs are sorted by Id # serials = [] for ccd in raft: serials.append(ccd.getId().getSerial()) self.assertEqual(serials, sorted(serials))
def run(self, dataRef): calexp_md = dataRef.get("calexp_md") wcs = afwImage.makeWcs(calexp_md) skymap = dataRef.get("deepCoadd_skyMap", immediate=True) # all this, just to get the center pixel coordinate camera = dataRef.get("camera") raft = camGeom.cast_Raft(camera.findDetector(camGeom.Id(0))) detId = camGeom.Id(calexp_md.get("DET-ID")) ccd = camGeom.cast_Ccd(raft.findDetector(detId)) size = ccd.getSize().getPixels(ccd.getPixelSize()) coord = wcs.pixelToSky(size.getX() / 2, size.getY() / 2) tract = skymap.findTract(coord).getId() d = dataRef.dataId print "%-6d %3d %5d" % (d['visit'], d['ccd'], tract) return tract
def testDetectorTime(self): """Test that we can ask a calib for the MidTime at a point in a detector (ticket #1337)""" import lsst.afw.geom as afwGeom import lsst.afw.cameraGeom as cameraGeom det = cameraGeom.Detector(cameraGeom.Id(1)) p = afwGeom.PointI(3, 4) self.calib.getMidTime(det, p)
def testDefectBase(self): """Test DefectBases""" #print >> sys.stderr, "Skipping testDefectBase"; return defectsDict = cameraGeomUtils.makeDefects(self.geomPolicy) for ccdName in ("Defective", "Defective II"): ccd = cameraGeomUtils.makeCcd(self.geomPolicy, cameraGeom.Id(ccdName)) ccdImage = cameraGeomUtils.makeImageFromCcd(ccd) if ccdName == "Defective": # # Insert some defects into the Ccd # for x0, y0, x1, y1 in [ (34, 0, 35, 80 ), (34, 81, 34, 100), (180, 100, 182, 130), ]: bbox = afwGeom.Box2I(afwGeom.Point2I(x0, y0), afwGeom.Point2I(x1, y1)) bad = ccdImage.Factory(ccdImage, bbox, afwImage.LOCAL) bad.set(100) if display: ds9.mtv(ccdImage, title="Defects") cameraGeomUtils.showCcd(ccd, None) defects = [v for (k, v) in defectsDict.items() if k == ccd.getId()] if len(defects) == 0: contine elif len(defects) == 1: defects = defects[0] else: raise RuntimeError, ("Found more than one defect set for CCD %s" % ccd.getId()) ccd.setDefects(defects) if False: print "CCD (%s)" % ccd.getId() for a in ccd: print " ", a.getId(), [str(d.getBBox()) for d in a.getDefects()] if ccdName == "Defective" and display: for d in ccd.getDefects(): displayUtils.drawBBox(d.getBBox(), ctype=ds9.CYAN, borderWidth=1.5) for a in ccd: for d in a.getDefects(): displayUtils.drawBBox(d.getBBox(), ctype=ds9.YELLOW, borderWidth=1.0) ds9.incrDefaultFrame()
def makeCamera(name="DECam"): camera = cameraGeom.Camera(cameraGeom.Id(name), 62, 1) for i in range(62): if i > 31: dewarName = "S%d" % (62 - i + 1) else: dewarName = "S%d" % (i + 1) camera.addDetector(afwGeom.PointI(i, 0), cameraGeom.FpPoint(25.4 * 2.5 * (2.5 - i), 0.0), cameraGeom.Orientation(0), makeRaft(dewarName)) return camera
def testNullDistortionDefaultCcd(self): """Test that we can use a NullDistortion even if the Detector is default-constructed""" ccd = cameraGeom.Ccd(cameraGeom.Id("dummy")) distorter = cameraGeom.NullDistortion() pin = afwGeom.PointD(0, 0) pout = distorter.undistort(pin, ccd) self.assertEqual(pin, pout) ein = geomEllip.Quadrupole(1, 0, 1) eout = distorter.distort(pin, ein, ccd) self.assertEqual(ein, eout)
def _standardizeExposure(self, mapping, item, dataId, filter=True, trimmed=True): item = super(FileMapper, self)._standardizeExposure(mapping, item, dataId, filter=filter, trimmed=trimmed) detector = afwCg.Ccd(afwCg.Id("Dummy")) item.setDetector(detector) return item
def testCopyExposure(self): """Copy an Exposure (maybe changing type)""" exposureU = afwImage.ExposureU(inFilePathSmall) exposureU.setWcs(self.wcs) exposureU.setDetector(cameraGeom.Detector(cameraGeom.Id(666))) exposureU.setFilter(afwImage.Filter("g")) exposureU.getCalib().setExptime(666) exposureU.setPsf(DummyPsf(4.0)) exposureF = exposureU.convertF() self.cmpExposure(exposureF, exposureU) nexp = exposureF.Factory(exposureF, False) self.cmpExposure(exposureF, nexp)
def testSetMembers(self): """ Test that the MaskedImage and the WCS of an Exposure can be set. """ exposure = afwImage.ExposureF() maskedImage = afwImage.MaskedImageF(inFilePathSmall) exposure.setMaskedImage(maskedImage) exposure.setWcs(self.wcs) exposure.setDetector(cameraGeom.Detector(cameraGeom.Id(666))) exposure.setFilter(afwImage.Filter("g")) self.assertEquals(exposure.getDetector().getId().getSerial(), 666) self.assertEquals(exposure.getFilter().getName(), "g") try: exposure.getWcs() except pexExcept.LsstCppException, e: print "caught expected exception (getWcs): %s" % e pass
def testRotatedCcd(self): """Test if we can build a Ccd out of Amps""" #print >> sys.stderr, "Skipping testRotatedCcd"; return ccdId = cameraGeom.Id(1, "Rot. CCD") ccdInfo = {"ampSerial" : CameraGeomTestCase.ampSerial} ccd = cameraGeomUtils.makeCcd(self.geomPolicy, ccdId, ccdInfo=ccdInfo) zero = 0.0*afwGeom.radians ccd.setOrientation(cameraGeom.Orientation(1, zero, zero, zero)) if display: cameraGeomUtils.showCcd(ccd) ds9.incrDefaultFrame() # # Trim the CCD and try again # trimmedImage = trimCcd(ccd) if display: cameraGeomUtils.showCcd(ccd, trimmedImage) ds9.incrDefaultFrame()
def run(self, matchLists, filterName, wcsList, butler): if self.config.applyColorTerms: ct = self.config.colorterms.selectColorTerm(filterName) else: ct = None # Convert matchLists to meas_mosaic specific format mlVisit = dict() for ccdId in matchLists: if matchLists[ccdId] is None: continue visit, ccd = self.decodeCcdExposureId(ccdId) if visit not in mlVisit: mlVisit[visit] = list() matches = [m for m in matchLists[ccdId] if m[0] is not None] keys = self.getKeys(matches[0][1].schema) matches = self.selectMatches(matches, keys) matches = self.selectStars(matches) # Apply color term if ct is not None and len(matches) != 0: refSchema = matches[0][0].schema key_p = refSchema.find(ct.primary).key key_s = refSchema.find(ct.secondary).key key_f = refSchema.find("flux").key refFlux1 = numpy.array([m[0].get(key_p) for m in matches]) refFlux2 = numpy.array([m[0].get(key_s) for m in matches]) refMag1 = -2.5 * numpy.log10(refFlux1) refMag2 = -2.5 * numpy.log10(refFlux2) refMag = ct.transformMags(refMag1, refMag2) refFlux = numpy.power(10.0, -0.4 * refMag) matches = [ self.setCatFlux(m, f, key_f) for m, f in zip(matches, refFlux) if f == f ] for m in matches: if m[0] is not None and m[1] is not None: match = (measMosaic.Source(m[0], wcsList[ccdId]), measMosaic.Source(m[1])) match[1].setExp(visit) match[1].setChip(ccd) mlVisit[visit].append(match) matchList = [] for visit in mlVisit: matchList.append(mlVisit[visit]) rootMat = measMosaic.kdtreeMat(matchList) allMat = rootMat.mergeMat() # Read CCD information ccdSet = {} for ccdId in matchLists: if matchLists[ccdId] is None: continue visit, ccd = self.decodeCcdExposureId(ccdId) if ccd not in ccdSet: ccdDev = cameraGeomUtils.findCcd(butler.mapper.camera, cameraGeom.Id(int(ccd))) ccdSet[ccd] = ccdDev # meas_mosaic specific wcs information wcsDic = {} for ccdId in wcsList: visit, ccd = self.decodeCcdExposureId(ccdId) if visit not in wcsDic and wcsList[ccdId] is not None: wcs = wcsList[ccdId] ccdDev = ccdSet[ccd] offset = afwGeom.Extent2D(ccdDev.getCenter().getPixels( ccdDev.getPixelSize())) wcsDic[visit] = wcs.copyAtShiftedPixelOrigin(offset) # meas_mosaic specific object list matchVec = measMosaic.obsVecFromSourceGroup(allMat, wcsDic, ccdSet) sourceVec = [] # Apply Jocabian correction calculated from wcs for m in matchVec: wcs = wcsList[m.iexp * 200 + m.ichip] m.mag -= 2.5 * math.log10( measMosaic.computeJacobian(wcs, afwGeom.Point2D(m.x, m.y))) fluxFitOrder = self.config.fluxFitOrder absolute = True chebyshev = True commonFluxCorr = False solveCcdScale = True ffpSet = {} for visit in wcsDic: ffp = measMosaic.FluxFitParams(fluxFitOrder, absolute, chebyshev) u_max, v_max = self.getExtent(matchVec) ffp.u_max = (math.floor(u_max / 10.) + 1) * 10 ffp.v_max = (math.floor(v_max / 10.) + 1) * 10 ffpSet[visit] = ffp fexp = {} fchip = {} matchVec, sourceVec, wcsDic, ccdSet, fexp, fchip, ffpSet = measMosaic.fluxFit( absolute, commonFluxCorr, matchVec, len(matchVec), sourceVec, len(sourceVec), wcsDic, ccdSet, fexp, fchip, ffpSet, solveCcdScale) self.writeFcr(butler, list(matchLists.keys()), ccdSet, filterName, fexp, fchip, ffpSet) return (1.0 / fexp[list(fexp.keys())[0]])
def getAmps(ccdData, camera, ampDiskLayout, cursor, kind): """Gets a list of amps belonging to the specified CCD. For each amp, the following data is returned: - amp object (from cameraGeom) - amp WCS - datasec amp corners in the science CCD - datasec amp corners in the raw on-disk amp """ visit, raftNum, sensorNum = ccdData[2:5] if kind == 'imsim': raft = lsstSimRafts[raftNum] s1 = sensorNum // 3 s2 = sensorNum - 3 * s1 ccdNum = int("%s%s%d%d" % (raft[0], raft[2], s1, s2)) ccdName = "R:%s S:%d,%d" % (raft, s1, s2) ccdId = cameraGeom.Id(-1, ccdName) else: ccdName = "CFHT %d" % sensorNum ccdId = cameraGeom.Id(-1, ccdName) ccd = cameraGeomUtils.findCcd(camera, ccdId) cursor.execute(""" SELECT r.amp, r.raDeSys, r.equinox, r.ctype1, r.ctype2, r.crpix1, r.crpix2, r.crval1, r.crval2, r.cd1_1, r.cd1_2, r.cd2_1, r.cd2_2 FROM Raw_Amp_Exposure r, Raw_Amp_To_Science_Ccd_Exposure m WHERE r.rawAmpExposureId = m.rawAmpExposureId AND m.scienceCcdExposureId = %d AND m.snap = 0; """ % ccdData[1]) results = [] amps = {} for row in cursor.fetchall(): amps[row[0]] = row for amp in ccd: ampSerial = amp.getId().getSerial() flipLR, flipTB = ampDiskLayout[ampSerial] chanX, chanY = amp.getId().getIndex() ampCorners = cornersFromBBox(amp.getDiskDataSec()) ampCcdCorners = cornersFromBBox(amp.getDataSec(True)) nQuarter = ccd.getOrientation().getNQuarter() # Deal with flips and rotations performed by CCD assembly. if flipLR: if flipTB: indexes = (2, 3, 0, 1) else: indexes = (1, 0, 3, 2) elif flipTB: indexes = (3, 2, 1, 0) else: indexes = (0, 1, 2, 3) ampCorners = [ampCorners[(i - nQuarter) % 4] for i in indexes] # Construct raw WCS ps = dafBase.PropertySet() ps.setString("RADESYS", amps[ampSerial][1]) ps.setDouble("EQUINOX", amps[ampSerial][2]) ps.setString("CTYPE1", amps[ampSerial][3]) ps.setString("CTYPE2", amps[ampSerial][4]) ps.setString("CUNIT1", "deg") ps.setString("CUNIT2", "deg") ps.setDouble("CRPIX1", amps[ampSerial][5]) ps.setDouble("CRPIX2", amps[ampSerial][6]) ps.setDouble("CRVAL1", amps[ampSerial][7]) ps.setDouble("CRVAL2", amps[ampSerial][8]) ps.setDouble("CD1_1", amps[ampSerial][9]) ps.setDouble("CD1_2", amps[ampSerial][10]) ps.setDouble("CD2_1", amps[ampSerial][11]) ps.setDouble("CD2_2", amps[ampSerial][12]) results.append((amp, afwImage.makeWcs(ps), ampCcdCorners, ampCorners)) return results
def makeRaft(raftName): dewar = cameraGeom.Raft(cameraGeom.Id("DECam"), 1, 1) dewar.addDetector(afwGeom.PointI(0, 0), cameraGeom.FpPoint(0.0, 0.0), cameraGeom.Orientation(0), makeCcd(raftName)) return dewar
def makeCcd(ccdName): ccd = cameraGeom.Ccd(cameraGeom.Id(ccdName), pixelSize) ccd.addAmp(1, 0, makeAmp(1)) return ccd
def testAssembleCcd(self): """Test if we can build a Ccd out of Amps""" compImage = afwImage.ImageU(os.path.join(eups.productDir("afw"), "tests", "test_comp.fits.gz")) compImageTrimmed = afwImage.ImageU(os.path.join(eups.productDir("afw"), "tests", "test_comp_trimmed.fits.gz")) ccdId = cameraGeom.Id(1, "LsstLike") ccdInfo = {"ampSerial" : CameraGeomTestCase.ampSerial} ccd = cameraGeomUtils.makeCcd(self.geomPolicy, ccdId, ccdInfo=ccdInfo) # # Test assembly of images that require preparation for assembly (like # LSST images) # outImage = cameraGeomUtils.makeImageFromCcd(ccd, imageSource=LsstLikeImage(), isTrimmed=False, imageFactory=afwImage.ImageU) self.assertImagesAreEqual(outImage, compImage) if display: cameraGeomUtils.showCcd(ccd, outImage) ds9.incrDefaultFrame() # # Test assembly of images that reside in a pre-assembled state from # the DAQ (like Suprime-Cam images) # ccdId = cameraGeom.Id(1, "ScLike") ccdInfo = {"ampSerial" : CameraGeomTestCase.ampSerial} ccd = cameraGeomUtils.makeCcd(self.geomPolicy, ccdId, ccdInfo=ccdInfo) outImage = cameraGeomUtils.makeImageFromCcd(ccd, imageSource=ScLikeImage(), isTrimmed=False, imageFactory=afwImage.ImageU) self.assertImagesAreEqual(outImage, compImage) if display: cameraGeomUtils.showCcd(ccd, outImage) ds9.incrDefaultFrame() # # Do the same tests for trimmed ccds. # ccdId = cameraGeom.Id(1, "LsstLike") ccdInfo = {"ampSerial" : CameraGeomTestCase.ampSerial} ccd = cameraGeomUtils.makeCcd(self.geomPolicy, ccdId, ccdInfo=ccdInfo) outImage = cameraGeomUtils.makeImageFromCcd(ccd, imageSource=LsstLikeImage(), isTrimmed=True, imageFactory=afwImage.ImageU) ccd.setTrimmed(True) self.assertImagesAreEqual(outImage, compImageTrimmed) if display: cameraGeomUtils.showCcd(ccd, outImage) ds9.incrDefaultFrame() ccdId = cameraGeom.Id(1, "ScLike") ccdInfo = {"ampSerial" : CameraGeomTestCase.ampSerial} ccd = cameraGeomUtils.makeCcd(self.geomPolicy, ccdId, ccdInfo=ccdInfo) outImage = cameraGeomUtils.makeImageFromCcd(ccd, imageSource=ScLikeImage(), isTrimmed=True, imageFactory=afwImage.ImageU) ccd.setTrimmed(True) self.assertImagesAreEqual(outImage, compImageTrimmed) if display: cameraGeomUtils.showCcd(ccd, outImage) ds9.incrDefaultFrame()
def setUp(self): width, height = 110, 301 self.mi = afwImage.MaskedImageF(afwGeom.ExtentI(width, height)) self.mi.set(0) sd = 3 # standard deviation of image self.mi.getVariance().set(sd*sd) self.mi.getMask().addMaskPlane("DETECTED") self.FWHM = 5 self.ksize = 31 # size of desired kernel sigma1 = 1.75 sigma2 = 2*sigma1 self.exposure = afwImage.makeExposure(self.mi) self.exposure.setPsf(measAlg.DoubleGaussianPsf(self.ksize, self.ksize, 1.5*sigma1, 1, 0.1)) crval = afwCoord.makeCoord(afwCoord.ICRS, 0.0*afwGeom.degrees, 0.0*afwGeom.degrees) wcs = afwImage.makeWcs(crval, afwGeom.PointD(0, 0), 1.0, 0, 0, 1.0) self.exposure.setWcs(wcs) ccd = cameraGeom.Ccd(cameraGeom.Id(1)) ccd.addAmp(cameraGeom.Amp(cameraGeom.Id(0), afwGeom.BoxI(afwGeom.PointI(0,0), self.exposure.getDimensions()), afwGeom.BoxI(afwGeom.PointI(0,0), afwGeom.ExtentI(0,0)), afwGeom.BoxI(afwGeom.PointI(0,0), self.exposure.getDimensions()), cameraGeom.ElectronicParams(1.0, 100.0, 65535))) self.exposure.setDetector(ccd) self.exposure.getDetector().setDistortion(None) # # Make a kernel with the exactly correct basis functions. Useful for debugging # basisKernelList = afwMath.KernelList() for sigma in (sigma1, sigma2): basisKernel = afwMath.AnalyticKernel(self.ksize, self.ksize, afwMath.GaussianFunction2D(sigma, sigma)) basisImage = afwImage.ImageD(basisKernel.getDimensions()) basisKernel.computeImage(basisImage, True) basisImage /= np.sum(basisImage.getArray()) if sigma == sigma1: basisImage0 = basisImage else: basisImage -= basisImage0 basisKernelList.append(afwMath.FixedKernel(basisImage)) order = 1 # 1 => up to linear spFunc = afwMath.PolynomialFunction2D(order) exactKernel = afwMath.LinearCombinationKernel(basisKernelList, spFunc) exactKernel.setSpatialParameters([[1.0, 0, 0], [0.0, 0.5*1e-2, 0.2e-2]]) rand = afwMath.Random() # make these tests repeatable by setting seed addNoise = True if addNoise: im = self.mi.getImage() afwMath.randomGaussianImage(im, rand) # N(0, 1) im *= sd # N(0, sd^2) del im xarr, yarr = [], [] for x, y in [(20, 20), (60, 20), (30, 35), (50, 50), (20, 90), (70, 160), (25, 265), (75, 275), (85, 30), (50, 120), (70, 80), (60, 210), (20, 210), ]: xarr.append(x) yarr.append(y) for x, y in zip(xarr, yarr): dx = rand.uniform() - 0.5 # random (centered) offsets dy = rand.uniform() - 0.5 k = exactKernel.getSpatialFunction(1)(x, y) # functional variation of Kernel ... b = (k*sigma1**2/((1 - k)*sigma2**2)) # ... converted double Gaussian's "b" #flux = 80000 - 20*x - 10*(y/float(height))**2 flux = 80000*(1 + 0.1*(rand.uniform() - 0.5)) I0 = flux*(1 + b)/(2*np.pi*(sigma1**2 + b*sigma2**2)) for iy in range(y - self.ksize//2, y + self.ksize//2 + 1): if iy < 0 or iy >= self.mi.getHeight(): continue for ix in range(x - self.ksize//2, x + self.ksize//2 + 1): if ix < 0 or ix >= self.mi.getWidth(): continue I = I0*psfVal(ix, iy, x + dx, y + dy, sigma1, sigma2, b) Isample = rand.poisson(I) if addNoise else I self.mi.getImage().set(ix, iy, self.mi.getImage().get(ix, iy) + Isample) self.mi.getVariance().set(ix, iy, self.mi.getVariance().get(ix, iy) + I) # bbox = afwGeom.BoxI(afwGeom.PointI(0,0), afwGeom.ExtentI(width, height)) self.cellSet = afwMath.SpatialCellSet(bbox, 100) self.footprintSet = afwDetection.FootprintSet(self.mi, afwDetection.Threshold(100), "DETECTED") self.catalog = SpatialModelPsfTestCase.measure(self.footprintSet, self.exposure) for source in self.catalog: try: cand = measAlg.makePsfCandidate(source, self.exposure) self.cellSet.insertCandidate(cand) except Exception, e: print e continue
def testReadWriteFits(self): """Test readFits and writeFits. """ # This should pass without an exception mainExposure = afwImage.ExposureF(inFilePathSmall) mainExposure.setDetector(cameraGeom.Detector(cameraGeom.Id(666))) 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) self.checkWcs(mainExposure, subExposure) # This should throw an exception def getExposure(): afwImage.ExposureF(inFilePathSmallImage) utilsTests.assertRaisesLsstCpp(self, 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) mainExposure.writeFits(outFile) # Check scaling of Calib scale = 2.0 calib = mainExposure.getCalib() calib *= scale self.assertEqual((fluxMag0 * scale, fluxMag0Err * scale), calib.getFluxMag0()) calib /= scale self.assertEqual((fluxMag0, fluxMag0Err), calib.getFluxMag0()) readExposure = type(mainExposure)(outFile) os.remove(outFile) # # 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 testId(self): """Test cameraGeom.Id""" #print >> sys.stderr, "Skipping testId"; return ix, iy = 2, 1 id = cameraGeom.Id(666, "Beasty", ix, iy) self.assertTrue(id.getIndex(), (ix, iy)) self.assertTrue(cameraGeom.Id(1) == cameraGeom.Id(1)) self.assertFalse(cameraGeom.Id(1) == cameraGeom.Id(100)) self.assertTrue(cameraGeom.Id("AA") == cameraGeom.Id("AA")) self.assertFalse(cameraGeom.Id("AA") == cameraGeom.Id("BB")) self.assertTrue(cameraGeom.Id(1, "AA") == cameraGeom.Id(1, "AA")) self.assertFalse(cameraGeom.Id(1, "AA") == cameraGeom.Id(2, "AA")) self.assertFalse(cameraGeom.Id(1, "AA") == cameraGeom.Id(1, "BB")) # self.assertTrue(cameraGeom.Id(1) < cameraGeom.Id(2)) self.assertFalse(cameraGeom.Id(100) < cameraGeom.Id(1)) self.assertTrue(cameraGeom.Id("AA") < cameraGeom.Id("BB")) self.assertTrue(cameraGeom.Id(1, "AA") < cameraGeom.Id(2, "AA")) self.assertTrue(cameraGeom.Id(1, "AA") < cameraGeom.Id(1, "BB"))
def testCcd(self): """Test if we can build a Ccd out of Amps""" #print >> sys.stderr, "Skipping testCcd"; return ccdId = cameraGeom.Id("CCD") ccdInfo = {"ampSerial" : CameraGeomTestCase.ampSerial} ccd = cameraGeomUtils.makeCcd(self.geomPolicy, ccdId, ccdInfo=ccdInfo) if display: cameraGeomUtils.showCcd(ccd) ds9.incrDefaultFrame() trimmedImage = cameraGeomUtils.makeImageFromCcd(ccd, isTrimmed=True) cameraGeomUtils.showCcd(ccd, trimmedImage, isTrimmed=True) ds9.incrDefaultFrame() for i in range(2): self.assertEqual(ccd.getSize().getMm()[i], ccdInfo["pixelSize"]*ccd.getAllPixels(True).getDimensions()[i]) self.assertEqual(ccd.getId().getName(), ccdInfo["name"]) self.assertEqual(ccd.getAllPixels().getWidth(), ccdInfo["width"]) self.assertEqual(ccd.getAllPixels().getHeight(), ccdInfo["height"]) self.assertEqual([a.getId().getSerial() for a in ccd], range(ccdInfo["ampIdMin"], ccdInfo["ampIdMax"] + 1)) id = cameraGeom.Id("ID%d" % ccdInfo["ampIdMax"]) self.assertTrue(ccd.findAmp(id), id) self.assertEqual(ccd.findAmp(afwGeom.Point2I(10, 10)).getId().getSerial(), ccdInfo["ampIdMin"]) self.assertEqual(ccd.getAllPixels().getMin(), ccd.findAmp(afwGeom.Point2I(10, 10)).getAllPixels().getMin()) self.assertEqual(ccd.getAllPixels().getMax(), ccd.findAmp(afwGeom.Point2I(ccdInfo["width"] - 1, ccdInfo["height"] - 1)).getAllPixels().getMax()) ps = ccd.getPixelSize() # # Test mapping pixel <--> mm. Use a pixel at the middle of the top of the CCD # pix = afwGeom.Point2D(99.5, 203.5) # wrt bottom left pos = cameraGeom.FpPoint(0.00, 1.02) # pixel center wrt CCD center posll = cameraGeom.FpPoint(0.00, 1.02) # llc of pixel wrt CCD center # # Map pix into untrimmed coordinates # amp = ccd.findAmp(afwGeom.Point2I(int(pix[0]), int(pix[1]))) corrI = amp.getDataSec(False).getMin() - amp.getDataSec(True).getMin() corr = afwGeom.Extent2D(corrI.getX(), corrI.getY()) pix += corr self.assertEqual(amp.getDiskCoordSys(), cameraGeom.Amp.AMP) self.assertEqual(ccd.getPixelFromPosition(pos) + corr, pix) # # Trim the CCD and try again # trimmedImage = trimCcd(ccd) if display: ds9.mtv(trimmedImage, title='Trimmed') cameraGeomUtils.showCcd(ccd, trimmedImage) ds9.incrDefaultFrame() a = ccd.findAmp(cameraGeom.Id("ID%d" % ccdInfo["ampIdMin"])) self.assertEqual(a.getDataSec(), afwGeom.Box2I(afwGeom.Point2I(0, 0), afwGeom.Extent2I(ccdInfo["ampWidth"], ccdInfo["ampHeight"]))) self.assertEqual(ccd.getSize().getMm()[0], ccdInfo["pixelSize"]*ccdInfo["trimmedWidth"]) self.assertEqual(ccd.getSize().getMm()[1], ccdInfo["pixelSize"]*ccdInfo["trimmedHeight"]) # # Test mapping pixel <--> mm # pix = afwGeom.Point2D(99.5, 203.5) # wrt bottom left pos = cameraGeom.FpPoint(0.00, 1.02) # pixel center wrt CCD center posll = cameraGeom.FpPoint(0.00, 1.02) # llc of pixel wrt CCD center self.assertEqual(ccd.getPixelFromPosition(pos), pix) self.assertEqual(ccd.getPositionFromPixel(pix).getMm(), posll.getMm())