예제 #1
0
    def std_raw(self, item, dataId, filter=True):
        """Standardize a raw dataset by converting it to an
        `~lsst.afw.image.Exposure` instead of an `~lsst.afw.image.Image`."""

        exp = self._standardizeExposure(
            self.exposures['raw'],
            item,
            dataId,
            trimmed=False,
            setVisitInfo=False,  # it's already set, and the metadata's stripped
            filter=False)

        if filter:
            obsInfo = ObservationInfo(exp.getMetadata(),
                                      translator_class=self.translatorClass)
            try:
                filt = afwImage.Filter(obsInfo.physical_filter)
            except LookupError:
                unknownName = "UNKNOWN"

                logger = lsst.log.Log.getLogger("LsstCamMapper")
                logger.warn(
                    'Unknown physical_filter "%s" for %s %s; replacing with "%s"',
                    obsInfo.physical_filter, obsInfo.observation_id,
                    obsInfo.detector_unique_name, unknownName)

                filt = afwImage.Filter(unknownName)

            exp.setFilter(filt)

        return exp
예제 #2
0
파일: color.py 프로젝트: ziggyman/afw_old
    def testUnknownFilter(self):
        """Test that we can define, but not use, an unknown filter"""
        badFilter = "rhl"  # an undefined filter
        # Not defined
        self.assertRaises(pexExcept.NotFoundError,
                          lambda: afwImage.Filter(badFilter))
        # Force definition
        f = afwImage.Filter(badFilter, True)
        self.assertEqual(f.getName(), badFilter)  # name is correctly defined

        self.assertRaises(
            pexExcept.NotFoundError,
            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
        #
        self.assertRaises(
            pexExcept.NotFoundError,
            lambda: afwImage.Filter().getFilterProperty().getLambdaEff())
예제 #3
0
    def testFilters(self):
        """Test that the coadd filter is set correctly
        """
        filterPolicyFile = pexPolicy.DefaultPolicyFile("afw", "SdssFilters.paf", "tests")
        filterPolicy = pexPolicy.Policy.createPolicy(
            filterPolicyFile, filterPolicyFile.getRepositoryPath(), True)
        imageUtils.defineFiltersFromPolicy(filterPolicy, reset=True)

        unkFilter = afwImage.Filter()
        gFilter = afwImage.Filter("g")
        rFilter = afwImage.Filter("r")

        calexpPath = os.path.join(AfwdataDir, SimCalexpSubpath)
        inExp = afwImage.ExposureF(calexpPath, afwGeom.Box2I(afwGeom.Point2I(0, 0), afwGeom.Extent2I(10, 10)),
                                   afwImage.PARENT)
        coadd = coaddUtils.Coadd(
            bbox=inExp.getBBox(),
            wcs=inExp.getWcs(),
            badMaskPlanes=("NO_DATA", "BAD"),
        )

        inExp.setFilter(gFilter)
        coadd.addExposure(inExp)
        self.assertEqualFilters(coadd.getCoadd().getFilter(), gFilter)
        self.assertEqualFilterSets(coadd.getFilters(), (gFilter,))
        coadd.addExposure(inExp)
        self.assertEqualFilters(coadd.getCoadd().getFilter(), gFilter)
        self.assertEqualFilterSets(coadd.getFilters(), (gFilter,))

        inExp.setFilter(rFilter)
        coadd.addExposure(inExp)
        self.assertEqualFilters(coadd.getCoadd().getFilter(), unkFilter)
        self.assertEqualFilterSets(coadd.getFilters(), (gFilter, rFilter))
def saveCalibration(dim, basedir, dtype, dateid, ccdid, ampid, filterid):
    # CFHTLS/%(dtype)/v%(dateid)/c%(ccdid)-a%(ampid).fits
    # -- or --
    # CFHTLS/%(dtype)/v%(dateid)-f%(filterid)/c%(ccdid)-a%(ampid).fits

    if filterid == None:
        outdir = '%s/calib/%s/v%s' % (basedir, dtype, dateid)
        if dtype == 'dark':
            outdir = '%s/calib/%s/v%s-e%d' % (
                basedir, dtype, dateid, int(dim.getMetadata().get('DARKTIME')))
    else:
        outdir = '%s/calib/%s/v%s-f%s' % (basedir, dtype, dateid, filterid)

    if not os.path.isdir(outdir):
        os.makedirs(outdir)

    outfile = '%s/c%s-a%s.fits' % (outdir, ccdid, ampid)
    print '# writing', outfile

    # convert to exposure
    exp = afwImage.ExposureF(afwImage.MaskedImageF(dim.getImage()),
                             afwImage.Wcs())
    exp.setMetadata(dim.getMetadata())
    if filterid == None:
        # For biases
        exp.setFilter(afwImage.Filter("u"))
    else:
        exp.setFilter(afwImage.Filter(filterid))
    exp.getMetadata().set('DC3BPATH', outfile)
    exp.writeFits(outfile)
예제 #5
0
파일: testColor.py 프로젝트: brianv0/afw
    def testReset(self):
        """Test that we can reset filter IDs and properties if needs be"""
        g = afwImage.FilterProperty.lookup("g")

        # Can we add a filter property?
        with self.assertRaises(pexExcept.RuntimeError):
            self.defineFilterProperty("g", self.g_lambdaEff + 10)
        self.defineFilterProperty("g", self.g_lambdaEff + 10,
                                  True)  # should not raise
        self.defineFilterProperty("g", self.g_lambdaEff, True)

        # Can we redefine properties?
        with self.assertRaises(pexExcept.RuntimeError):
            self.defineFilterProperty("g", self.g_lambdaEff +
                                      10)  # changing definition is not allowed

        self.defineFilterProperty(
            "g", self.g_lambdaEff)  # identical redefinition is allowed

        afwImage.Filter.define(
            g,
            afwImage.Filter("g").getId())  # OK if Id's the same
        afwImage.Filter.define(
            g, afwImage.Filter.AUTO)  # AUTO will assign the same ID

        with self.assertRaises(pexExcept.RuntimeError):
            afwImage.Filter.define(g,
                                   afwImage.Filter("g").getId() +
                                   10)  # different ID
예제 #6
0
    def _computeCoaddExposureId(self, dataId, singleFilter):
        """Compute the 64-bit (long) identifier for a coadd.

        Parameters
        ----------
        dataId : `dict`
            Data identifier with tract and patch.
        singleFilter : `bool`
            True means the desired ID is for a single-filter coadd, in which
            case ``dataId`` must contain filter.
        """

        tract = int(dataId['tract'])
        if tract < 0 or tract >= 2**LsstCamMapper._nbit_tract:
            raise RuntimeError('tract not in range [0,%d)' %
                               (2**LsstCamMapper._nbit_tract))
        patchX, patchY = [int(patch) for patch in dataId['patch'].split(',')]
        for p in (patchX, patchY):
            if p < 0 or p >= 2**LsstCamMapper._nbit_patch:
                raise RuntimeError('patch component not in range [0, %d)' %
                                   2**LsstCamMapper._nbit_patch)
        oid = (((tract << LsstCamMapper._nbit_patch) + patchX) <<
               LsstCamMapper._nbit_patch) + patchY
        if singleFilter:
            if afwImage.Filter(
                    dataId['filter']).getId() >= 2**LsstCamMapper._nbit_filter:
                raise RuntimeError(
                    "Filter %s has too high an ID (%d) to fit in %d bits",
                    afwImage.Filter(dataId['filter']),
                    afwImage.Filter(dataId['filter']).getId(),
                    LsstCamMapper._nbit_filter)

            return (oid << LsstCamMapper._nbit_filter) + afwImage.Filter(
                dataId['filter']).getId()
        return oid
예제 #7
0
    def __init__(self, **kwargs):

        #Define the policy file:
        policyFile = Policy.defaultPolicyFile(self.packageName, "GotoMapper.yaml", "policy")
        policy =Policy(policyFile)

        #Change the policy to point to the sim camera description:
        policy["camera"] = "../sim/camera"
        
        #This creates the camera class by calling CameraMapper (i.e., the parent class):
        super(GotoMapper, self).__init__(policy, os.path.dirname(policyFile), **kwargs)

        #Set the filters:
        self.filterIdMap = dict(v=0)
        afwImageUtils.defineFilter(name='R',  lambdaEff=635.9, alias=['R'])
        afwImageUtils.defineFilter(name='G',  lambdaEff=534.9, alias=['G'])
        afwImageUtils.defineFilter(name='B',  lambdaEff=446.6, alias=['B'])
        afwImageUtils.defineFilter(name='L',  lambdaEff=535.5, alias=['L'])
        
        self.filters = {}
        self.filters['R'] = afwImage.Filter('R').getCanonicalName()
        self.filters['G'] = afwImage.Filter('G').getCanonicalName()
        self.filters['B'] = afwImage.Filter('B').getCanonicalName()
        self.filters['L'] = afwImage.Filter('L').getCanonicalName()
        self.defaultFilterName = 'L'
예제 #8
0
파일: color.py 프로젝트: rnikutta/afw
    def testFilterAliases(self):
        """Test that we can provide an alias for a Filter"""
        f0 = afwImage.Filter("z")
        f1 = afwImage.Filter("zprime")
        f2 = afwImage.Filter("z'")

        self.assertEqual(f0.getFilterProperty().getLambdaEff(), f1.getFilterProperty().getLambdaEff())
        self.assertEqual(f0.getFilterProperty().getLambdaEff(), f2.getFilterProperty().getLambdaEff())
예제 #9
0
파일: testColor.py 프로젝트: brianv0/afw
    def testFilterEquality(self):
        """Test a "g" filter comparison"""
        f = afwImage.Filter("g")
        g = afwImage.Filter("g")

        self.assertEqual(f, g)

        f = afwImage.Filter()  # the unknown filter
        self.assertNotEqual(f, f)  # ... doesn't equal itself
예제 #10
0
파일: color.py 프로젝트: ziggyman/afw_old
    def testFilterEquality(self):
        # a "g" filter
        f = afwImage.Filter("g")
        g = afwImage.Filter("g")

        self.assertEqual(f, g)

        f = afwImage.Filter()  # the unknown filter
        self.assertNotEqual(f, f)  # ... doesn't equal itself
예제 #11
0
    def __init__(self, **kwargs):

        # Inject new mappings from importExtData's policy file.
        # This is a bit of a hack; we're pretending these policy entries
        # come from the configuration inside the repository itself, since
        # those always override and extend those from the camera's definitions.
        # Luckily, no one actually uses those per-repository policy entries
        # for anything else, so this should be safe.
        kwargs["repositoryCfg"] = self.makeNewConfig(kwargs["repositoryCfg"])

        HscMapper.__init__(self, **kwargs)

        # add filters
        afwImage.utils.defineFilter(name='MegaCam-uS',
                                    lambdaEff=375,
                                    alias=[
                                        'u1',
                                        'u',
                                    ])
        afwImage.utils.defineFilter(name='MegaCam-u',
                                    lambdaEff=375,
                                    alias=[
                                        'u2',
                                    ])
        afwImage.utils.defineFilter(name='VIRCAM-Y',
                                    lambdaEff=1021,
                                    alias=[
                                        'Y',
                                        'y',
                                    ])
        afwImage.utils.defineFilter(name='VIRCAM-J',
                                    lambdaEff=1254,
                                    alias=[
                                        'J',
                                        'j',
                                    ])
        afwImage.utils.defineFilter(name='VIRCAM-H',
                                    lambdaEff=1646,
                                    alias=[
                                        'H',
                                        'h',
                                    ])
        afwImage.utils.defineFilter(name='VIRCAM-Ks',
                                    lambdaEff=2149,
                                    alias=[
                                        'Ks',
                                        'k',
                                    ])

        for f in [
                'MegaCam-uS', 'MegaCam-u', 'VIRCAM-Y', 'VIRCAM-J', 'VIRCAM-H',
                'VIRCAM-Ks'
        ]:
            self.filters[f] = afwImage.Filter(
                afwImage.Filter(f).getId()).getName()
예제 #12
0
def createFringe(width, height, xFreq, xOffset, yFreq, yOffset):
    """Create a fringe frame.

    Parameters
    ----------
    width, height : `int`
       Size of image.
    xFreq, yFreq : `float`
       Frequency of sinusoids in x and y.
    xOffset, yOffset : `float`
       Phase of sinusoids in x and y.

    Returns
    -------
    exp : `lsst.afw.image.ExposureF`
       Fringe frame.
    """
    image = afwImage.ImageF(width, height)
    array = image.getArray()
    x, y = np.indices(array.shape)
    array[x, y] = np.sin(xFreq*x + xOffset) + np.sin(yFreq*y + yOffset)
    mi = afwImage.makeMaskedImage(image)
    exp = afwImage.makeExposure(mi)
    exp.setFilter(afwImage.Filter('FILTER'))
    return exp
    def setUp(self):
        refCatDir = os.path.join(os.path.dirname(__file__), "data",
                                 "sdssrefcat")

        self.bbox = afwGeom.Box2I(afwGeom.Point2I(0, 0),
                                  afwGeom.Extent2I(3001, 3001))
        self.ctrPix = afwGeom.Point2I(1500, 1500)
        metadata = dafBase.PropertySet()
        metadata.set("RADECSYS", "FK5")
        metadata.set("EQUINOX", 2000.0)
        metadata.set("CTYPE1", "RA---TAN")
        metadata.set("CTYPE2", "DEC--TAN")
        metadata.set("CUNIT1", "deg")
        metadata.set("CUNIT2", "deg")
        metadata.set("CRVAL1", 215.5)
        metadata.set("CRVAL2", 53.0)
        metadata.set("CRPIX1", self.ctrPix[0] + 1)
        metadata.set("CRPIX2", self.ctrPix[1] + 1)
        metadata.set("CD1_1", 5.1e-05)
        metadata.set("CD1_2", 0.0)
        metadata.set("CD2_2", -5.1e-05)
        metadata.set("CD2_1", 0.0)
        self.tanWcs = afwImage.makeWcs(metadata)
        self.exposure = afwImage.ExposureF(self.bbox)
        self.exposure.setWcs(self.tanWcs)
        self.exposure.setFilter(afwImage.Filter("r", True))
        butler = Butler(refCatDir)
        self.refObjLoader = LoadIndexedReferenceObjectsTask(butler=butler)
예제 #14
0
    def setUp(self):
        super().setUp()

        afwImage.Filter.reset()
        afwImage.FilterProperty.reset()
        defineFilter("g", 470.0)

        self.wcs = afwGeom.makeSkyWcs(
            lsst.geom.Point2D(0.0, 0.0),
            lsst.geom.SpherePoint(2.0, 34.0, lsst.geom.degrees),
            np.identity(2),
        )
        self.photoCalib = afwImage.PhotoCalib(1.5)
        self.psf = DummyPsf(2.0)
        self.detector = DetectorWrapper().detector
        self.summaryStats = afwImage.ExposureSummaryStats(ra=100.0)
        self.polygon = afwGeom.Polygon(
            lsst.geom.Box2D(lsst.geom.Point2D(0.0, 0.0),
                            lsst.geom.Point2D(25.0, 20.0)))
        self.coaddInputs = afwImage.CoaddInputs()
        self.apCorrMap = afwImage.ApCorrMap()
        self.transmissionCurve = afwImage.TransmissionCurve.makeIdentity()

        self.exposureInfo = afwImage.ExposureInfo()
        gFilter = afwImage.Filter("g")
        gFilterLabel = afwImage.FilterLabel(band="g")
        self.exposureInfo.setFilter(gFilter)
        self.exposureInfo.setFilterLabel(gFilterLabel)
예제 #15
0
 def testVisitInfoFitsPersistence(self):
     """Test saving an exposure to FITS and reading it back in preserves (some) VisitInfo fields"""
     exposureId = 5
     exposureTime = 12.3
     boresightRotAngle = 45.6 * lsst.geom.degrees
     weather = Weather(1.1, 2.2, 0.3)
     visitInfo = afwImage.VisitInfo(
         exposureId=exposureId,
         exposureTime=exposureTime,
         boresightRotAngle=boresightRotAngle,
         weather=weather,
     )
     photoCalib = afwImage.PhotoCalib(3.4, 5.6)
     exposureInfo = afwImage.ExposureInfo()
     exposureInfo.setVisitInfo(visitInfo)
     exposureInfo.setPhotoCalib(photoCalib)
     exposureInfo.setDetector(self.detector)
     gFilter = afwImage.Filter("g")
     exposureInfo.setFilter(gFilter)
     maskedImage = afwImage.MaskedImageF(inFilePathSmall)
     exposure = afwImage.ExposureF(maskedImage, exposureInfo)
     with lsst.utils.tests.getTempFilePath(".fits") as tmpFile:
         exposure.writeFits(tmpFile)
         rtExposure = afwImage.ExposureF(tmpFile)
     rtVisitInfo = rtExposure.getInfo().getVisitInfo()
     self.assertEqual(rtVisitInfo.getWeather(), weather)
     self.assertEqual(rtExposure.getPhotoCalib(), photoCalib)
     self.assertEqual(rtExposure.getFilter(), gFilter)
예제 #16
0
파일: color.py 프로젝트: rnikutta/afw
    def testReset(self):
        """Test that we can reset filter IDs and properties if needs be"""
        # The properties of a g filter
        g = afwImage.FilterProperty.lookup("g")
        #
        # First FilterProperty
        #
        def tst():
            gprime = self.defineFilterProperty("g", self.g_lambdaEff + 10)

        self.assertRaises(pexExcept.RuntimeError, tst)
        gprime = self.defineFilterProperty("g", self.g_lambdaEff + 10, True) # should not raise
        gprime = self.defineFilterProperty("g", self.g_lambdaEff, True)
        #
        # Can redefine
        #
        def tst():
            self.defineFilterProperty("g", self.g_lambdaEff + 10) # changing definition is not allowed
        self.assertRaises(pexExcept.RuntimeError, tst)

        self.defineFilterProperty("g", self.g_lambdaEff) # identical redefinition is allowed
        #
        # Now Filter
        #
        afwImage.Filter.define(g, afwImage.Filter("g").getId()) # OK if Id's the same
        afwImage.Filter.define(g, afwImage.Filter.AUTO)         # AUTO will assign the same ID

        def tst():
            afwImage.Filter.define(g, afwImage.Filter("g").getId() + 10) # different ID
            
        self.assertRaises(pexExcept.RuntimeError, tst)
예제 #17
0
    def testMultiple(self, pedestal=0.0):
        """Test subtraction of multiple fringe frames

        @param pedestal    Pedestal to add into fringe frame
        """
        xFreqList = [0.1, 0.13, 0.06]
        xOffsetList = [0.0, 0.1, 0.2]
        yFreqList = [0.09, 0.12, 0.07]
        yOffsetList = [0.3, 0.2, 0.1]
        fringeList = [
            createFringe(self.size, self.size, xFreq, xOffset, yFreq,
                         yOffset) for xFreq, xOffset, yFreq, yOffset in zip(
                             xFreqList, xOffsetList, yFreqList, yOffsetList)
        ]

        for fringe in fringeList:
            fMi = fringe.getMaskedImage()
            fMi += pedestal
        # Generate science frame
        scales = [0.33, 0.33, 0.33]
        image = afwImage.ImageF(self.size, self.size)
        image.set(0)
        for s, f in zip(scales, fringeList):
            image.scaledPlus(s, f.getMaskedImage().getImage())
        mi = afwImage.makeMaskedImage(image)
        exp = afwImage.makeExposure(mi)
        exp.setFilter(afwImage.Filter('FILTER'))

        task = FringeTask(name="multiFringe", config=self.config)
        self.checkFringe(task, exp, fringeList, stddevMax=1.0e-2)
예제 #18
0
    def _setFilter(self, mapping, item, dataId):
        """Set the filter object in an Exposure.  If the Exposure had a FILTER
        keyword, this was already processed during load.  But if it didn't,
        use the filter from the registry.
        Parameters
        ----------
        mapping : `lsst.obs.base.Mapping`
            Where to get the filter from.
        item : `lsst.afw.image.Exposure`
            Exposure to set the filter in.
        dataId : `dict`
            Dataset identifier.
        """

        if not (isinstance(item, afwImage.ExposureU) or isinstance(item, afwImage.ExposureI) or
                isinstance(item, afwImage.ExposureF) or isinstance(item, afwImage.ExposureD)):
            return

        if item.getFilter().getId() != afwImage.Filter.UNKNOWN:
            return

        actualId = mapping.need(['filter'], dataId)
        filterName = actualId['filter']
        if self.filters is not None and filterName in self.filters:
            filterName = self.filters[filterName]
        item.setFilter(afwImage.Filter(filterName))
예제 #19
0
파일: color.py 프로젝트: ziggyman/afw_old
    def testLambdaEff(self):
        f = afwImage.Filter("g")
        g_r = 1.2
        c = afwImage.Color(g_r)

        self.assertEqual(c.getLambdaEff(f),
                         1000 * g_r)  # XXX Not a real implementation!
예제 #20
0
def loadData(pixelScale=1.0):
    """Prepare the data we need to run the example"""

    # Load sample input from disk
    mypath = lsst.utils.getPackageDir('afwdata')

    print(
        " mypath = ",
        mypath)  # mssg -- error happens before i can even possibly print this
    #    sys.exit()

    imFile = os.path.join(mypath, "CFHT", "D4",
                          "cal-53535-i-797722_small_1.fits")

    exposure = afwImage.ExposureF(imFile)
    # set the exposure time
    calib = afwImage.Calib()
    calib.setExptime(1.0)
    exposure.setCalib(calib)
    # add a filter
    afwImage.Filter.define(afwImage.FilterProperty(FilterName, 600, True))
    exposure.setFilter(afwImage.Filter(FilterName))
    # and a trivial WCS (needed by MyAstrometryTask)
    pixelScale /= 3600.0  # degrees per pixel
    wcs = afwImage.makeWcs(Coord(PointD(15, 1)), PointD(0, 0), pixelScale, 0.0,
                           0.0, pixelScale)
    exposure.setWcs(wcs)

    return exposure
예제 #21
0
    def testExposureInfoConstructor(self):
        """Test the Exposure(maskedImage, exposureInfo) constructor"""
        exposureInfo = afwImage.ExposureInfo()
        exposureInfo.setWcs(self.wcs)
        exposureInfo.setDetector(self.detector)
        gFilter = afwImage.Filter("g")
        exposureInfo.setFilter(gFilter)
        maskedImage = afwImage.MaskedImageF(inFilePathSmall)
        exposure = afwImage.ExposureF(maskedImage, exposureInfo)

        self.assertTrue(exposure.hasWcs())
        self.assertEqual(exposure.getWcs().getPixelOrigin(),
                         self.wcs.getPixelOrigin())
        self.assertEqual(exposure.getDetector().getName(),
                         self.detector.getName())
        self.assertEqual(exposure.getDetector().getSerial(),
                         self.detector.getSerial())
        self.assertEqual(exposure.getFilter(), gFilter)

        self.assertTrue(exposure.getInfo().hasWcs())
        self.assertEqual(exposure.getInfo().getWcs().getPixelOrigin(),
                         self.wcs.getPixelOrigin())
        self.assertEqual(exposure.getInfo().getDetector().getName(),
                         self.detector.getName())
        self.assertEqual(exposure.getInfo().getDetector().getSerial(),
                         self.detector.getSerial())
        self.assertEqual(exposure.getInfo().getFilter(), gFilter)
예제 #22
0
 def testLambdaMinMax(self):
     """Test additional properties for minimum and maximum wavelength for a filter."""
     filt = afwImage.Filter("g")
     # LambdaMin and LambdaMax are undefined for the test SDSS filter, and should return nan
     self.assertTrue(np.isnan(filt.getFilterProperty().getLambdaMin()))
     self.assertTrue(np.isnan(filt.getFilterProperty().getLambdaMax()))
     lambdaEff = 476.31
     lambdaMin = 405
     lambdaMax = 552
     imageUtils.defineFilter("gNew",
                             lambdaEff,
                             lambdaMin=lambdaMin,
                             lambdaMax=lambdaMax)
     filtNew = afwImage.Filter("gNew")
     self.assertEqual(lambdaMin, filtNew.getFilterProperty().getLambdaMin())
     self.assertEqual(lambdaMax, filtNew.getFilterProperty().getLambdaMax())
예제 #23
0
    def _computeCoaddExposureId(self, dataId, singleFilter):
        """Compute the 64-bit (long) identifier for a coadd.

        Parameters
        ----------
        dataId : `dict`
            Data identifier with tract and patch.
        singleFilter : `bool`
            True means the desired ID is for a single-filter coadd,
            in which case the dataId must contain filter.

        Returns
        -------
        oid : `int`
            Unique integer identifier.
        """
        tract = int(dataId['tract'])
        if tract < 0 or tract >= 2**DecamMapper._nbit_tract:
            raise RuntimeError('tract not in range [0,%d)' %
                               (2**DecamMapper._nbit_tract))
        patchX, patchY = [int(x) for x in dataId['patch'].split(',')]
        for p in (patchX, patchY):
            if p < 0 or p >= 2**DecamMapper._nbit_patch:
                raise RuntimeError('patch component not in range [0, %d)' %
                                   2**DecamMapper._nbit_patch)
        oid = (((tract << DecamMapper._nbit_patch) + patchX) <<
               DecamMapper._nbit_patch) + patchY
        if singleFilter:
            return (oid << DecamMapper._nbit_filter) + afwImage.Filter(
                dataId['filter']).getId()
        return oid
예제 #24
0
    def _computeCoaddExposureId(self, dataId, singleFilter):
        """Compute the 64-bit (long) identifier for a coadd.

        @param dataId (dict)       Data identifier with tract and patch.
        @param singleFilter (bool) True means the desired ID is for a single- 
                                   filter coadd, in which case dataId
                                   must contain filter.
        """

        tract = long(dataId['tract'])
        if tract < 0 or tract >= 2**PfsMapper._nbit_tract:
            raise RuntimeError('tract not in range [0,%d)' %
                               (2**PfsMapper._nbit_tract))
        patchX, patchY = map(int, dataId['patch'].split(','))
        for p in (patchX, patchY):

            if p < 0 or p >= 2**PfsMapper._nbit_patch:
                raise RuntimeError('patch component not in range [0, %d)' %
                                   2**PfsMapper._nbit_patch)
        oid = (((tract << PfsMapper._nbit_patch) + patchX) <<
               PfsMapper._nbit_patch) + patchY
        if singleFilter:
            return (oid << PfsMapper._nbit_filter) + afwImage.Filter(
                dataId['filter']).getId()
        return oid
예제 #25
0
    def setUp(self):

        nSources = 10
        # CFHT Filters from the camera mapper.
        afwImageUtils.resetFilters()
        afwImageUtils.defineFilter('u', lambdaEff=374, alias="u.MP9301")
        afwImageUtils.defineFilter('g', lambdaEff=487, alias="g.MP9401")
        afwImageUtils.defineFilter('r', lambdaEff=628, alias="r.MP9601")
        afwImageUtils.defineFilter('i', lambdaEff=778, alias="i.MP9701")
        afwImageUtils.defineFilter('z', lambdaEff=1170, alias="z.MP9801")

        self.bbox = geom.Box2I(geom.Point2I(0, 0), geom.Extent2I(1024, 1153))
        dataset = measTests.TestDataset(self.bbox)
        for srcIdx in range(nSources):
            dataset.addSource(100000.0, geom.Point2D(100, 100))
        self.inputCatalogNoFlags, _ = make_input_source_catalog(dataset, False)
        self.inputCatalog, self.exposure = \
            make_input_source_catalog(dataset, True)

        detector = DetectorWrapper(id=23,
                                   bbox=self.exposure.getBBox()).detector
        visit = afwImage.VisitInfo(exposureId=4321,
                                   exposureTime=200.,
                                   date=dafBase.DateTime(nsecs=1400000000 *
                                                         10**9))
        self.exposure.setDetector(detector)
        self.exposure.getInfo().setVisitInfo(visit)
        self.exposure.setFilter(afwImage.Filter('g.MP9401'))
        scale = 2
        scaleErr = 1
        self.photoCalib = afwImage.PhotoCalib(scale, scaleErr)
        self.exposure.setPhotoCalib(self.photoCalib)
예제 #26
0
def makeMos(butler, mos, frame0=0, bin=32, nJob=20, visits=[]):
    if not visits:
        visits = [904288, 904320, 904330, 904520, 904534, 904536, 904538, 904670, 904672,
                  904674, 904676, 904678, 904786, 904788, 904790, 904792, 904794, 905034, 905036]

    frame = frame0
    for visit in visits:
        if visit in mos:
            continue

        if visit in bad:
            print("Skipping bad visit %d: %s" % (visit, bad[visit]))
            continue

        global labels
        try:
            md = butler.get("raw_md", visit=visit, ccd=10)
            labels[visit] = afwImage.Filter(md).getName()
        except RuntimeError as e:
            print(e)

        mos[visit] = cgUtils.showCamera(butler.get("camera"),
                                        cgUtils.ButlerImage(butler, visit=visit,
                                                            callback=utils.trimRemoveCrCallback,
                                                            verbose=True),
                                        nJob=nJob, frame=frame, bin=bin,
                                        title=visit, overlay=True, names=False)
        frame += 1
예제 #27
0
파일: testExposure.py 프로젝트: brianv0/afw
 def testVisitInfoFitsPersistence(self):
     """Test saving an exposure to FITS and reading it back in preserves (some) VisitInfo fields"""
     exposureId = 5
     exposureTime = 12.3
     boresightRotAngle = 45.6 * afwGeom.degrees
     weather = afwCoord.Weather(1.1, 2.2, 0.3)
     visitInfo = afwImage.makeVisitInfo(
         exposureId = exposureId,
         exposureTime = exposureTime,
         boresightRotAngle = boresightRotAngle,
         weather = weather,
     )
     # Calib used to have exposure time and exposure date, so check for lack of interference
     calib = afwImage.Calib(3.4)
     exposureInfo = afwImage.ExposureInfo()
     exposureInfo.setVisitInfo(visitInfo)
     exposureInfo.setCalib(calib)
     exposureInfo.setDetector(self.detector)
     gFilter = afwImage.Filter("g")
     exposureInfo.setFilter(gFilter)
     maskedImage = afwImage.MaskedImageF(inFilePathSmall)
     exposure = afwImage.ExposureF(maskedImage, exposureInfo)
     with lsst.utils.tests.getTempFilePath(".fits") as tmpFile:
         exposure.writeFits(tmpFile)
         rtExposure = afwImage.ExposureF(tmpFile)
     rtVisitInfo = rtExposure.getInfo().getVisitInfo()
     self.assertEqual(rtVisitInfo.getWeather(), weather)
     self.assertEqual(rtExposure.getCalib(), calib)
     self.assertEqual(rtExposure.getFilter(), gFilter)
예제 #28
0
    def defineFilter(self,
                     lambdaEff=476.31,
                     lambdaMin=405.,
                     lambdaMax=552.,
                     filterName="gTest"):
        """Construct a `Filter` with sufficient information to calculate DCR.

        Parameters
        ----------
        lambdaEff : `float`, optional
            The effective wavelength of the filter, defaults to LSST g-band value.
        lambdaMin : float, optional
            The minimum wavelength of the filter with greater than 1% transmission,
            defaults to LSST g-band value.
        lambdaMax : `float`, optional
            The maximum wavelength of the filter with greater than 1% transmission,
            defaults to LSST g-band value.
        filterName : `str`, optional
            The simplified name of the filter.

        Returns
        -------
        filterInfo : `lsst.afw.image.Filter`
            The filter definition.
        """
        afwImageUtils.defineFilter(filterName,
                                   lambdaEff,
                                   lambdaMin=lambdaMin,
                                   lambdaMax=lambdaMax)
        return afwImage.Filter(filterName)
예제 #29
0
    def testCoordinateTransformDcrCalculation(self):
        """Check the DCR calculation using astropy coordinate transformations.

        Astmospheric refraction causes sources to appear closer to zenith than
        they really are. An alternate calculation of the shift due to DCR is to
        transform the pixel coordinates to altitude and azimuth, add the DCR
        amplitude to the altitude, and transform back to pixel coordinates.
        """
        afwImageUtils.defineFilter("gTest", self.lambdaEff,
                                   lambdaMin=self.lambdaMin, lambdaMax=self.lambdaMax)
        filterInfo = afwImage.Filter("gTest")
        pixelScale = 0.2*arcseconds
        doFlip = [False, True]

        for testIter in range(self.nRandIter):
            rotAngle = 360.*self.rng.rand()*degrees
            azimuth = 360.*self.rng.rand()*degrees
            elevation = (45. + self.rng.rand()*40.)*degrees  # Restrict to 45 < elevation < 85 degrees
            visitInfo = self.makeDummyVisitInfo(azimuth, elevation)
            for flip in doFlip:
                # Repeat the calculation for both WCS orientations
                wcs = self.makeDummyWcs(rotAngle, pixelScale, crval=visitInfo.getBoresightRaDec(), flipX=flip)
                dcrShifts = calculateDcr(visitInfo, wcs, filterInfo, self.dcrNumSubfilters)
                refShifts = calculateAstropyDcr(visitInfo, wcs, filterInfo, self.dcrNumSubfilters)
                for refShift, dcrShift in zip(refShifts, dcrShifts):
                    # Use a fairly loose tolerance, since 1% of a pixel is good enough agreement.
                    self.assertFloatsAlmostEqual(refShift[1], dcrShift[1], rtol=1e-2, atol=1e-2)
                    self.assertFloatsAlmostEqual(refShift[0], dcrShift[0], rtol=1e-2, atol=1e-2)
예제 #30
0
    def __init__(self, inputPolicy=None, **kwargs):

        #Define the policy file:
        policyFile = Policy.defaultPolicyFile(self.packageName,
                                              "GotoMapper.yaml", "policy")
        policy = Policy(policyFile)

        #This creates the camera class by calling CameraMapper (i.e., the parent class):
        super(GotoMapper, self).__init__(policy, os.path.dirname(policyFile),
                                         **kwargs)

        # Ensure each dataset type of interest knows about the full range of keys available from the registry
        keys = {
            'visit': int,
            'ccd': int,
            'filter': str,
            'dataType': str,
            'expTime': float,
            'dateObs': str,
            'taiObs': str,
            'mjd': int,
            'field': str,
            'survey': str
        }
        for name in (
                "raw",
                "postISRCCD",
                "calexp",
                "src",
                "icSrc",
                "srcMatch",
        ):
            self.mappings[name].keyDict.update(keys)

        #Set the filters:
        self.filterIdMap = dict(v=0)
        afwImageUtils.defineFilter(name='R', lambdaEff=635.9, alias=['R'])
        afwImageUtils.defineFilter(name='G', lambdaEff=534.9, alias=['G'])
        afwImageUtils.defineFilter(name='B', lambdaEff=446.6, alias=['B'])
        afwImageUtils.defineFilter(name='L', lambdaEff=535.5, alias=['L'])

        self.filters = {}
        self.filters['R'] = afwImage.Filter('R').getCanonicalName()
        self.filters['G'] = afwImage.Filter('G').getCanonicalName()
        self.filters['B'] = afwImage.Filter('B').getCanonicalName()
        self.filters['L'] = afwImage.Filter('L').getCanonicalName()
        self.defaultFilterName = 'L'