예제 #1
0
파일: testMethods.py 프로젝트: brianv0/afw
    def testAssertCoordsNearlyEqual(self):
        """Test assertCoordsNearlyEqual"""
        for raDecDeg in ((45, 45), (-70, 89), (130, -89.5)):
            raDecDeg = [val * afwGeom.degrees for val in raDecDeg]
            coord0 = afwCoord.IcrsCoord(*raDecDeg)
            self.assertCoordsNearlyEqual(coord0,
                                         coord0,
                                         maxDiff=1e-7 * afwGeom.arcseconds)

            for offAng in (0, 45, 90):
                offAng = offAng * afwGeom.degrees
                for offDist in (0.001, 0.1):
                    offDist = offDist * afwGeom.arcseconds
                    coord1 = coord0.toGalactic()
                    coord1.offset(offAng, offDist)
                    self.assertCoordsNearlyEqual(coord0,
                                                 coord1,
                                                 maxDiff=offDist * 1.00001)
                    with self.assertRaises(AssertionError):
                        self.assertCoordsNearlyEqual(coord0,
                                                     coord1,
                                                     maxDiff=offDist * 0.99999)

            # test wraparound in RA
            coord2 = afwCoord.IcrsCoord(raDecDeg[0] + 360 * afwGeom.degrees,
                                        raDecDeg[1])
            self.assertCoordsNearlyEqual(coord0,
                                         coord2,
                                         maxDiff=1e-7 * afwGeom.arcseconds)
예제 #2
0
    def testTicket2441(self):
        """Test ticket 2441: warpExposure sometimes mishandles zero-extent dest exposures"""
        fromWcs = makeWcs(
            pixelScale=afwGeom.Angle(1.0e-8, afwGeom.degrees),
            projection="TAN",
            crPixPos=(0, 0),
            crValCoord=afwCoord.IcrsCoord(afwGeom.Point2D(359, 0),
                                          afwGeom.degrees),
        )
        fromExp = afwImage.ExposureF(afwImage.MaskedImageF(10, 10), fromWcs)

        toWcs = makeWcs(
            pixelScale=afwGeom.Angle(0.00011, afwGeom.degrees),
            projection="CEA",
            crPixPos=(410000.0, 11441.0),
            crValCoord=afwCoord.IcrsCoord(afwGeom.Point2D(45, 0),
                                          afwGeom.degrees),
            doFlipX=True,
        )
        toExp = afwImage.ExposureF(afwImage.MaskedImageF(0, 0), toWcs)

        warpControl = afwMath.WarpingControl("lanczos3")
        # if a bug described in ticket #2441 is present, this will raise an
        # exception:
        numGoodPix = afwMath.warpExposure(toExp, fromExp, warpControl)
        self.assertEqual(numGoodPix, 0)
예제 #3
0
    def testSmallSrc(self):
        """Verify that a source image that is too small will not raise an exception

        This tests another bug that was fixed in ticket #2441
        """
        fromWcs = makeWcs(
            pixelScale=afwGeom.Angle(1.0e-8, afwGeom.degrees),
            projection="TAN",
            crPixPos=(0, 0),
            crValCoord=afwCoord.IcrsCoord(afwGeom.Point2D(359, 0),
                                          afwGeom.degrees),
        )
        fromExp = afwImage.ExposureF(afwImage.MaskedImageF(1, 1), fromWcs)

        toWcs = makeWcs(
            pixelScale=afwGeom.Angle(1.1e-8, afwGeom.degrees),
            projection="TAN",
            crPixPos=(0, 0),
            crValCoord=afwCoord.IcrsCoord(afwGeom.Point2D(358, 0),
                                          afwGeom.degrees),
        )
        toExp = afwImage.ExposureF(afwImage.MaskedImageF(10, 10), toWcs)

        warpControl = afwMath.WarpingControl("lanczos3")
        # if a bug described in ticket #2441 is present, this will raise an
        # exception:
        numGoodPix = afwMath.warpExposure(toExp, fromExp, warpControl)
        self.assertEqual(numGoodPix, 0)
        imArr, maskArr, varArr = toExp.getMaskedImage().getArrays()
        self.assertTrue(np.all(np.isnan(imArr)))
        self.assertTrue(np.all(np.isinf(varArr)))
        noDataBitMask = afwImage.Mask.getPlaneBitMask("NO_DATA")
        self.assertTrue(np.all(maskArr == noDataBitMask))
예제 #4
0
    def testEquality(self):
        # (In)equality is determined by value, not identity. See DM-2347, -2465.
        c1 = afwCoord.IcrsCoord(self.ra, self.dec)
        self.assertTrue(c1 == c1)
        self.assertFalse(c1 != c1)

        c2 = afwCoord.IcrsCoord(self.ra.replace('1', '2'), self.dec)
        self.assertFalse(c2 == c1)
        self.assertTrue(c2 != c1)

        c3 = afwCoord.IcrsCoord(self.ra, self.dec)
        self.assertTrue(c3 == c1)
        self.assertFalse(c3 != c1)
예제 #5
0
    def testEquality(self):
        # (In)equality is determined by value, not identity. See DM-2347, -2465.
        # These asserts are testing the functionality of `==` and `!=` and should not be changed
        c1 = afwCoord.IcrsCoord(self.ra, self.dec)
        self.assertTrue(c1 == c1)
        self.assertFalse(c1 != c1)

        c2 = afwCoord.IcrsCoord(self.ra.replace('1', '2'), self.dec)
        self.assertTrue(c2 != c1)
        self.assertFalse(c2 == c1)

        c3 = afwCoord.IcrsCoord(self.ra, self.dec)
        self.assertEqual(c3, c1)
        self.assertFalse(c3 != c1)
예제 #6
0
    def setUp(self):
        self.crval = afwCoord.IcrsCoord(afwGeom.PointD(44., 45.))
        self.crpix = afwGeom.Point2D(15000, 4000)

        arcsecPerPixel = 1 / 3600.0
        CD11 = arcsecPerPixel
        CD12 = 0
        CD21 = 0
        CD22 = arcsecPerPixel

        self.wcs = afwImage.makeWcs(self.crval, self.crpix, CD11, CD12, CD21,
                                    CD22)

        refSchema = afwTable.SimpleTable.makeMinimalSchema()
        self.refCentroidKey = afwTable.Point2DKey.addFields(
            refSchema, "centroid", "centroid", "pixels")
        self.refCoordKey = afwTable.CoordKey(refSchema["coord"])
        self.refCat = afwTable.SimpleCatalog(refSchema)

        # an alias is required to make src.getCentroid() work;
        # simply defining a field named "slot_Centroid" doesn't suffice
        srcSchema = afwTable.SourceTable.makeMinimalSchema()
        self.srcCentroidKey = afwTable.Point2DKey.addFields(
            srcSchema, "base_SdssCentroid", "centroid", "pixels")
        srcAliases = srcSchema.getAliasMap()
        srcAliases.set("slot_Centroid", "base_SdssCentroid")
        self.srcCoordKey = afwTable.CoordKey(srcSchema["coord"])
        self.sourceCat = afwTable.SourceCatalog(srcSchema)
예제 #7
0
def averageRaDec(ra, dec):
    """Calculate average RA, Dec from input lists using spherical geometry.

    Parameters
    ----------
    ra : list of float
        RA in [radians]
    dec : list of float
        Dec in [radians]

    Returns
    -------
    float, float
       meanRa, meanDec -- Tuple of average RA, Dec [radians]
    """
    assert (len(ra) == len(dec))

    angleRa = [afwGeom.Angle(r, afwGeom.radians) for r in ra]
    angleDec = [afwGeom.Angle(d, afwGeom.radians) for d in dec]
    coords = [
        afwCoord.IcrsCoord(ar, ad) for (ar, ad) in zip(angleRa, angleDec)
    ]

    meanRa, meanDec = afwCoord.averageCoord(coords)

    return meanRa.asRadians(), meanDec.asRadians()
    def joinMatchListWithCatalog(self, matchCat, sourceCat):
        """!Relink an unpersisted match list to sources and reference objects

        A match list is persisted and unpersisted as a catalog of IDs produced by
        afw.table.packMatches(), with match metadata (as returned by the astrometry tasks)
        in the catalog's metadata attribute.  This method converts such a match catalog
        into a match list (an lsst.afw.table.ReferenceMatchVector) with links to source
        records and reference object records.

        @param[in]     matchCat   Unperisted packed match list (an lsst.afw.table.BaseCatalog).
                                  matchCat.table.getMetadata() must contain match metadata,
                                  as returned by the astrometry tasks.
        @param[in,out] sourceCat  Source catalog (an lsst.afw.table.SourceCatalog).
                                  As a side effect, the catalog will be sorted by ID.

        @return the match list (an lsst.afw.table.ReferenceMatchVector)
        """
        matchmeta = matchCat.table.getMetadata()
        version = matchmeta.getInt('SMATCHV')
        if version != 1:
            raise ValueError('SourceMatchVector version number is %i, not 1.' %
                             version)
        filterName = matchmeta.getString('FILTER').strip()
        ctrCoord = afwCoord.IcrsCoord(
            matchmeta.getDouble('RA') * afwGeom.degrees,
            matchmeta.getDouble('DEC') * afwGeom.degrees,
        )
        rad = matchmeta.getDouble('RADIUS') * afwGeom.degrees
        refCat = self.loadSkyCircle(ctrCoord, rad, filterName).refCat
        refCat.sort()
        sourceCat.sort()
        return afwTable.unpackMatches(matchCat, refCat, sourceCat)
예제 #9
0
def makeFakeWcs():
    '''!Make a wcs to put in an exposure
    \return a Wcs object
    '''
    return afwImage.makeWcs(
        afwCoord.IcrsCoord(45.0 * afwGeom.degrees, 45.0 * afwGeom.degrees),
        afwGeom.Point2D(0.0, 0.0), 1.0, 0.0, 0.0, 1.0)
예제 #10
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)
     self.assertRaises(pexExceptions.InvalidParameterError,
                       coaddPsf.computeKernelImage, naiveAvgPos)
     # important test is that this doesn't throw:
     coaddPsf.computeKernelImage()
예제 #11
0
    def testNames(self):
        """Test the names of the Coords (Useful with Point2D form)"""

        # verify that each coordinate type can tell you what its components are called.
        radec1, known1 = afwCoord.Coord(
            self.ra, self.dec).getCoordNames(), ["RA", "Dec"]
        radec3, known3 = afwCoord.Fk5Coord(
            self.ra, self.dec).getCoordNames(), ["RA", "Dec"]
        radec4, known4 = afwCoord.IcrsCoord(
            self.ra, self.dec).getCoordNames(), ["RA", "Dec"]
        lb, known5 = afwCoord.GalacticCoord(
            self.ra, self.dec).getCoordNames(), ["L", "B"]
        lambet, known6 = afwCoord.EclipticCoord(
            self.ra, self.dec).getCoordNames(), ["Lambda", "Beta"]
        observatory = afwCoord.Observatory(0 * afwGeom.degrees,
                                           0 * afwGeom.degrees, 0)
        altaz = afwCoord.TopocentricCoord(self.ra, self.dec, 2000.0,
                                          observatory).getCoordNames()
        known7 = ["Az", "Alt"]

        pairs = [
            [radec1, known1],
            [radec3, known3],
            [radec4, known4],
            [lb, known5],
            [lambet, known6],
            [altaz, known7],
        ]

        for pair, known in (pairs):
            self.assertEqual(pair[0], known[0])
            self.assertEqual(pair[1], known[1])
예제 #12
0
 def testTicket2872(self):
     """Test that CoaddPsf.getAveragePosition() is always a position at which
     we can call computeImage().
     """
     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 = self.mycatalog.addNew()
     record1.setPsf(psf1)
     record1.setWcs(wcs)
     record1.setD(self.weightKey, 1.0)
     record1.setBBox(
         afwGeom.Box2I(afwGeom.Point2I(-40, 0), afwGeom.Point2I(40, 100)))
     record2 = self.mycatalog.addNew()
     record2.setPsf(psf2)
     record2.setWcs(wcs)
     record2.setD(self.weightKey, 1.0)
     record2.setBBox(
         afwGeom.Box2I(afwGeom.Point2I(60, 0), afwGeom.Point2I(140, 100)))
     coaddPsf = measAlg.CoaddPsf(self.mycatalog, wcs)
     naiveAvgPos = afwGeom.Point2D(50, 50)
     with self.assertRaises(pexExceptions.InvalidParameterError):
         coaddPsf.computeKernelImage(naiveAvgPos)
     # important test is that this doesn't throw:
     coaddPsf.computeKernelImage()
예제 #13
0
    def run(self, dataRef):
        """Report tracts and patches that are within a given region of a skymap

        @param dataRef: data reference for sky map.
        @return: a pipeBase.Struct with fields:
        - ccdInfoSetDict: a dict of (tractId, patchIndex): set of CcdExposureInfo
        """
        skyMap = dataRef.get(self.config.coaddName + "Coadd_skyMap")

        # make coords in the correct order to form an enclosed space
        raRange = (self.config.raDecRange[0], self.config.raDecRange[2])
        decRange = (self.config.raDecRange[1], self.config.raDecRange[3])
        raDecList = [
            (raRange[0], decRange[0]),
            (raRange[1], decRange[0]),
            (raRange[1], decRange[1]),
            (raRange[0], decRange[1]),
        ]
        coordList = [
            afwCoord.IcrsCoord(afwGeom.Angle(ra, afwGeom.degrees),
                               afwGeom.Angle(dec, afwGeom.degrees))
            for ra, dec in raDecList
        ]
        tractPatchList = skyMap.findTractPatchList(coordList)
        for tractInfo, patchInfoList in tractPatchList:
            for patchInfo in patchInfoList:
                patchIndex = patchInfo.getIndex()
                print("tract=%d patch=%d,%d" %
                      (tractInfo.getId(), patchIndex[0], patchIndex[1]))
예제 #14
0
    def parse_args(self, policyPath, requiredArgs=()):
        """Parse the arguments
        
        @param[in] policyPath: path to main policy dictionary
        @param[in] requiredArgs: list of required arguments, in addition to the standard ones
        
        @return
        - config: a Configuration object
        - opts: command-line options, as from optparse
        - args: command-line arguments, as from optparse
        
        Must be called before calling getReadWrite, getWcs, getWcsBBox, getIdList
        """
        config, opts, args = idListOptions.IdListOptionParser.parse_args(
            self,
            policyPath=policyPath,
            requiredArgs=("size", ) + tuple(requiredArgs))

        pixelScale = opts.scaleAS * _RadPerDeg / 3600.0

        self._skyMap = skymap.SkyMap(
            projection=opts.projection,
            pixelScale=pixelScale,
            overlap=opts.overlapDeg * _RadPerDeg,
        )

        raDec = getattr(opts, "radec", None)
        if raDec != None:
            ctrCoord = afwCoord.IcrsCoord(
                afwGeom.Point2D(opts.radec[0], opts.radec[1]),
                afwCoord.DEGREES)

        dimensions = afwGeom.Extent2I(opts.size[0], opts.size[1])

        tileId = opts.tileid
        if tileId == None:
            if opts.radec == None:
                raise RuntimeError("Must specify tileid or radec")
            tileId = self._skyMap.getSkyTileId(ctrCoord)

        self._skyTileInfo = self._skyMap.getSkyTileInfo(tileId)

        self._coaddWcs = self._skyTileInfo.getWcs()

        # determine bounding box
        if opts.llc != None:
            llcPixInd = afwGeom.Point2I(opts.llc[0], opts.llc[1])
        else:
            if opts.radec == None:
                raise RuntimeError("Must specify llc or radec")
            ctrPixPos = self._coaddWcs.skyToPixel(ctrCoord)
            ctrPixInd = afwGeom.Point2I(ctrPixPos)
            llcPixInd = ctrPixInd - (dimensions / 2)
        self._coaddBBox = afwGeom.Box2I(llcPixInd, dimensions)

        roots = config["roots"]
        self._coaddBasePath = os.path.join(roots["output"], opts.rerun)

        return config, opts, args
예제 #15
0
 def testTractContains(self):
     """Test that TractInfo.contains works"""
     skyMap = self.getSkyMap()
     for tract in skyMap:
         coord = tract.getCtrCoord()
         self.assertTrue(tract.contains(coord))
         opposite = afwCoord.IcrsCoord(coord.getLongitude() + 12*afwGeom.hours, -1*coord.getLatitude())
         self.assertFalse(tract.contains(opposite))
예제 #16
0
 def compute_coord(row, ra_name, dec_name):
     """!Create a afwCoord object from a np.array row
     @param[in] row  dict like object with ra/dec info in degrees
     @param[in] ra_name  name of RA key
     @param[in] dec_name  name of Dec key
     @param[out] IcrsCoord object constructed from the RA/Dec values
     """
     return afwCoord.IcrsCoord(row[ra_name] * afwGeom.degrees,
                               row[dec_name] * afwGeom.degrees)
예제 #17
0
def makeSimpleImage():
    wcs = makeWcs(
        pixelScale=2 * afwGeom.arcseconds,
        crPixPos=[0, 0],
        crValCoord=afwCoord.IcrsCoord(
            0 * afwGeom.degrees, 0 * afwGeom.degrees),
    )
    im = afwImage.ExposureF(100, 100, wcs)
    im.writeFits("simple.fits")
예제 #18
0
 def testCast(self):
     # strangely, this overload of makeWcs returns a TAN WCS that's not a TanWcs
     wcs = afwImage.makeWcs(afwCoord.IcrsCoord(45.0*afwGeom.degrees, 45.0*afwGeom.degrees),
                            afwGeom.Point2D(0.0, 0.0), 1.0, 0.0, 0.0, 1.0)
     # ...but if you round-trip it through a PropertySet, you get a TanWcs in a Wcs ptr,
     # which is what we want for this test.
     base = afwImage.makeWcs(wcs.getFitsMetadata())
     self.assertEqual(type(base), afwImage.Wcs)
     derived = afwImage.TanWcs.cast(base)
     self.assertEqual(type(derived), afwImage.TanWcs)
예제 #19
0
def getCoordList(minRa, minDec, maxRa, maxDec):
    degList = (
        (minRa, minDec),
        (maxRa, minDec),
        (maxRa, maxDec),
        (minRa, maxDec),
    )
    return tuple(
        afwCoord.IcrsCoord(afwGeom.Point2D(d[0], d[1]), afwGeom.degrees)
        for d in degList)
예제 #20
0
def validate(xs, ys, mapper, wcs):
    dists = []
    for i in range(len(xs)):
        tuple1 = mapper.xyToRaDec(xs[i], ys[i])
        coord1 = afwCoord.IcrsCoord(afwGeom.Point2D(tuple1[0], tuple1[1]),
                                    afwGeom.radians)
        coord2 = wcs.pixelToSky(xs[i], ys[i])
        dist = coord1.angularSeparation(coord2).asArcseconds()
        dists.append(dist)

    print(np.mean(dists), np.std(dists))
예제 #21
0
 def testPrune1(self):
     coords = []
     for ra, dec in [(0.0, 0.0), (0.1, 0.1), (0.0, 90.0), (0.0, -90.0)]:
         coords.append(afwCoord.IcrsCoord(ra * degrees, dec * degrees))
     res = 3
     qs = skypix.QuadSpherePixelization(res, 0.0)
     root, x, y = 1, 1, 1
     skyTileId = qs.id(root, x, y)
     skyTile = utils.PT1SkyTile(res, root, x, y, skyTileId)
     numContained = sum(skyTile.contains(s) for s in coords)
     self.assertEqual(numContained, 2)
예제 #22
0
 def setUp(self):
     ra = 10.0 * afwGeom.degrees
     dec = 1.0 * afwGeom.degrees
     epoch = 2000.0
     self.data = [
         afwCoord.Coord(ra, dec, epoch),
         afwCoord.Fk5Coord(ra, dec, epoch),
         afwCoord.IcrsCoord(ra, dec),
         afwCoord.GalacticCoord(ra, dec),
         afwCoord.EclipticCoord(ra, dec),
         # TopocentricCoord is not currently picklable
     ]
예제 #23
0
    def setUp(self):
        crval = afwCoord.IcrsCoord(afwGeom.PointD(44., 45.))
        crpix = afwGeom.Point2D(15000, 4000)

        arcsecPerPixel = 1 / 3600.0
        CD11 = arcsecPerPixel
        CD12 = 0
        CD21 = 0
        CD22 = arcsecPerPixel

        self.tanWcs = afwImage.makeWcs(crval, crpix, CD11, CD12, CD21, CD22)
        self.loadData()
예제 #24
0
파일: utils.py 프로젝트: lsst/sims_catUtils
def get_Ebv(result):
    ebvMapNorth = EBV.EBVmap()
    datadir = os.environ.get("SIMS_DUSTMAPS_DIR")
    ebvMapNorth.readMapFits(os.path.join(datadir, "DustMaps/SFD_dust_4096_ngp.fits"))
    ebvMapSouth = EBV.EBVmap()
    ebvMapSouth.readMapFits(os.path.join(datadir, "DustMaps/SFD_dust_4096_sgp.fits"))
    # Calculate galactic coordinates:
    gLon = []
    gLat = []
    for i in range(len(result['raJ2000'])):
        gcoord = afwCoord.IcrsCoord(afwGeom.Point2D(result[i]['raJ2000'], result[i]['decJ2000']), afwGeom.radians).toGalactic()
        gLon.append(gcoord.getL().asRadians())
        gLat.append(gcoord.getB().asRadians())
    return EBV.calculateEbv(gLon, gLat, ebvMapNorth, ebvMapSouth, interp = True)
예제 #25
0
def get_hsc_regions(box_coords, butler=None):
    """
    Get hsc regions within a polygonal region (box) of the sky. Here, 
    hsc regions means the tracts and patches within the 'skybox'. 

    Parameters
    ----------
    box_coords : list of tuples
        The four coordinates for the box corners. This is the 
        output of the skybox function. If only one coordinate
        is given, will return a single tract and patch. 
    butler : Butler object, optional
        If None, then a will be created in this function.
        Default is None.

    Returns
    -------
    regions : structured ndarray
        The tracts and patches within the skybox. The columns of 
        the array are 'tract' and 'patch'.

    Note
    ----
    This may give incorrect answers on regions that are larger than a tract, 
    which is ~1.5 degree = 90 arcminute.
    """
    import lsst.afw.coord as afwCoord
    import lsst.afw.geom as afwGeom
    if butler is None:
        import lsst.daf.persistence
        from myPipe import dataDIR
        butler = lsst.daf.persistence.Butler(dataDIR)
    if len(box_coords)==4:
        from toolbox.astro import angsep
        (ra1, dec1), (ra2, dec2) = box_coords[0], box_coords[2]
        if angsep(ra1, dec1, ra2, dec2, sepunits='arcmin') > 90.0:
            print('\n********* WARNING *********')
            print('Region larger than a tract')
            print('***************************\n')
    skymap = butler.get('deepCoadd_skyMap', immediate=True)
    coordList = [afwCoord.IcrsCoord(afwGeom.Angle(ra, afwGeom.degrees),\
                 afwGeom.Angle(dec, afwGeom.degrees)) for ra, dec in box_coords]
    tractPatchList = skymap.findClosestTractPatchList(coordList)
    regions = []
    for tractInfo, patchInfoList in tractPatchList:
        for patchInfo in patchInfoList:
            patchIndex = patchInfo.getIndex()
            regions.append((tractInfo.getId(), str(patchIndex[0])+','+str(patchIndex[1])))
    return np.array(regions, dtype=[('tract', int), ('patch', 'S4')])
예제 #26
0
    def bypass_raw(self, datasetType, pythonType, location, dataId):
        ccd = dataId['ccd']
        x, y = ccd % 6, ccd // 6
        xSize, ySize = 2048, 4096

        filename = location.getLocations()[0]
        bbox = afwGeom.Box2I(afwGeom.Point2I(x * xSize, y * ySize),
                             afwGeom.Extent2I(xSize, ySize))
        if False:
            # XXX seems to be some sort of bug here for ccd=11
            # cfitsio returns: READ_ERROR 108 /* error reading from FITS file */
            hdu = 0
            image = afwImage.DecoratedImageF(filename, hdu, bbox)
        else:
            # XXX this can't be at all efficient, but it works
            raw = afwImage.ImageF(filename)
            sub = raw.Factory(raw, bbox, True)
            del raw
            sub.setXY0(afwGeom.Point2I(0, 0))
            image = afwImage.DecoratedImageF(sub)
            del sub

        exp = exposureFromImage(image)
        del image

        md = exp.getMetadata()
        md.add("EXPTIME", 1.0)
        md.add("FILTER", "OPEN")

        # Install a basic (wrong, apart from pixel scale) WCS so the pixel scale can be used
        md.add("RA", "00:00:00.00")
        md.add("DEC", "00:00:00.0")
        coord = afwCoord.IcrsCoord(afwGeom.Point2D(0, 0), afwGeom.radians)
        point = afwGeom.Point2D(0, 0)
        pixScale = (0.9 * afwGeom.arcseconds).asDegrees()
        wcs = afwImage.makeWcs(coord, point, pixScale, 0, 0, pixScale)
        wcsMd = wcs.getFitsMetadata()
        for key in wcsMd.names():
            md.add(key, wcsMd.get(key))
        exp.setWcs(wcs)

        return self._standardizeExposure(self.exposures['raw'],
                                         exp,
                                         dataId,
                                         filter=True,
                                         trimmed=False)
예제 #27
0
    def std_raw(self, image, dataId):
        """Standardize a raw dataset by converting it to an Exposure instead of an Image"""
        if isinstance(image, afwImage.DecoratedImageU) or isinstance(image, afwImage.DecoratedImageI) or \
                isinstance(image, afwImage.DecoratedImageF) or isinstance(image, afwImage.DecoratedImageD):
            exposure = afwImage.makeExposure(afwImage.makeMaskedImage(image.getImage()))
        else:
            exposure = image
        md = image.getMetadata()

        if True:
            wcs = afwImage.makeWcs(md, True)

            # The CASU WCSes use ZPN; our stuff wants TAN
            # This won't work near the pole, but should be decent away from it.
            box = afwGeom.BoxD(image.getImage().getBBox())
            refPix = box.getCenter()
            refSky = wcs.pixelToSky(refPix)
            refSkyOffsetX = wcs.pixelToSky(refPix + afwGeom.Extent2D(1.0, 0.0))
            refSkyOffsetY = wcs.pixelToSky(refPix + afwGeom.Extent2D(0.0, 1.0))
            xPixelScale = refSky.angularSeparation(refSkyOffsetX).asDegrees()
            yPixelScale = refSky.angularSeparation(refSkyOffsetY).asDegrees()

            xPixelScale = yPixelScale = wcs.pixelScale().asDegrees()
        else:
            refPix = afwGeom.Point2D(md.get("CRPIX1"), md.get("CRPIX2"))
            refSky = afwCoord.IcrsCoord(md.get("CRVAL1")*afwGeom.degrees,
                                        md.get("CRVAL2")*afwGeom.degrees)
            xPixelScale = yPixelScale = (0.2*afwGeom.arcseconds).asDegrees()

#        import pdb;pdb.set_trace()

        exposure.setMetadata(md)
        #newWcs = afwImage.makeWcs(refSky, refPix, xPixelScale, 0.0, 0.0, yPixelScale)
        #wcs = afwImage.makeWcs(md, True)
        #exposure.setWcs(newWcs)
        exposure.setWcs(wcs)

        """ Set up exposure time """
        pathId = self._transformId(dataId)
        expTime = pathId['expTime']
        exposure.getCalib().setExptime(expTime)

        return self._standardizeExposure(self.exposures['raw'], exposure, dataId,
                                         trimmed=False)
    def setUp(self):
        '''Create two calibs, one with a valid zero-point and one without. Use these to create two UnitSystem
        objects.
        '''
        self.mag2Flux = lambda m: 10.0**(m / 2.5)
        self.flux2Mag = lambda f: 2.5 * np.log10(f)

        calibNoZero = afwImage.Calib()
        calibWithZero = afwImage.Calib()
        calibWithZero.setFluxMag0(self.mag2Flux(25))

        cdelt = (0.2 * afwGeom.arcseconds).asDegrees()
        position = afwCoord.IcrsCoord(45.0 * afwGeom.degrees,
                                      45.0 * afwGeom.degrees)
        wcs = afwImage.makeWcs(position, afwGeom.Point2D(), cdelt, 0.0, 0.0,
                               cdelt)

        self.unitNoZero = measModel.UnitSystem(wcs, calibNoZero)
        self.unitWithZero = measModel.UnitSystem(wcs, calibWithZero)
예제 #29
0
    def testTicket3093(self):
        """Declination -1 < delta < 0 always prints positive as a string"""

        # from how-to-reproduce code reported on 3093 ticket
        ra   = 26.468676561631767*afwGeom.degrees
        decl = -0.6684668814164008

        # also make sure we didn't break the original functionality
        # Test above/below +/-1
        declIn    = [          decl,     -1.0*decl,     decl - 1.0,   -decl + 1.0]
        declKnown = ["-00:40:06.48", "00:40:06.48", "-01:40:06.48", "01:40:06.48"]

        for i in range(len(declIn)):
            printableCoord = afwCoord.IcrsCoord(ra, declIn[i]*afwGeom.degrees).getDecStr()
        
            # With bug, this prints e.g. '00:40:06.48.  It should be '-00:40:06.48'
            print("Decl 0 to -1 bug:", printableCoord)
        
            self.assertEqual(printableCoord, declKnown[i])
예제 #30
0
    def testAverage(self):
        """Tests for lsst.afw.coord.averageCoord"""
        icrs = afwCoord.IcrsCoord(self.ra, self.dec)
        gal = afwCoord.GalacticCoord(self.l * afwGeom.degrees,
                                     self.b * afwGeom.degrees)

        # Mixed systems, no system provided
        with self.assertRaises(pexEx.InvalidParameterError):
            afwCoord.averageCoord([icrs, gal])

        # Mixed systems, but target system provided
        # Only checking this doesn't fail; will check accuracy later
        afwCoord.averageCoord([icrs, gal], afwCoord.ICRS)
        afwCoord.averageCoord([icrs, gal], afwCoord.FK5)

        # Same system, no target system provided
        result = afwCoord.averageCoord([icrs] * 100)
        self.assertEqual(result, icrs)

        def circle(center, start, precision=1.0e-9):
            """Generate points in a circle; test that average is in the center

            Precision is specified in arcseconds.
            """
            coords = []
            for ii in range(120):
                new = start.clone()
                new.rotate(center, ii * 3 * afwGeom.degrees)
                coords.append(new)
            result = afwCoord.averageCoord(coords)
            distance = result.angularSeparation(center)
            self.assertLess(distance.asArcseconds(), precision)

        for center, start in (
                # RA=0=360 border
            (afwCoord.IcrsCoord(0 * afwGeom.degrees, 0 * afwGeom.degrees),
             afwCoord.IcrsCoord(5 * afwGeom.degrees, 0 * afwGeom.degrees)),
                # North pole
            (afwCoord.IcrsCoord(0 * afwGeom.degrees, 90 * afwGeom.degrees),
             afwCoord.IcrsCoord(0 * afwGeom.degrees, 85 * afwGeom.degrees)),
                # South pole
            (afwCoord.IcrsCoord(0 * afwGeom.degrees, -90 * afwGeom.degrees),
             afwCoord.IcrsCoord(0 * afwGeom.degrees, -85 * afwGeom.degrees)),
        ):
            circle(center, start)