Exemplo n.º 1
0
    def testApplyIGM(self):

        """Test application of IGM from Lookup Tables to SED objects"""

        #Test that a warning comes up if input redshift is out of range and that no changes occurs to SED
        testSed = Sed()
        testSed.readSED_flambda(os.environ['SIMS_SED_LIBRARY_DIR'] + '/galaxySED/Inst.80E09.25Z.spec.gz')
        testFlambda = []
        for fVal in testSed.flambda:
            testFlambda.append(fVal)
        testIGM = ApplyIGM()
        testIGM.initializeIGM()
        with warnings.catch_warnings(record=True) as wa:
            testIGM.applyIGM(1.1, testSed)
            self.assertEqual(len(wa), 1)
            self.assertTrue('IGM Lookup tables' in str(wa[-1].message))
        np.testing.assert_equal(testFlambda, testSed.flambda)

        #Test that lookup table is read in correctly
        testTable15 = np.genfromtxt(str(os.environ['SIMS_SED_LIBRARY_DIR'] + '/igm/' +
                                        'MeanLookupTable_zSource1.5.tbl'))
        np.testing.assert_equal(testTable15, testIGM.meanLookups['1.5'])

        #Test output by making sure that an incoming sed with flambda = 1.0 everywhere will return the
        #transmission values of the lookup table as its flambda output
        testSed.setSED(testSed.wavelen, flambda = np.ones(len(testSed.wavelen)))
        testIGM.applyIGM(1.5, testSed)
        testTable15Above300 = testTable15[np.where(testTable15[:,0] >= 300.0)]
        testSed.resampleSED(wavelen_match = testTable15Above300[:,0])
        np.testing.assert_allclose(testTable15Above300[:,1], testSed.flambda, 1e-4)
Exemplo n.º 2
0
    def testApplyIGM(self):
        """Test application of IGM from Lookup Tables to SED objects"""

        #Test that a warning comes up if input redshift is out of range and that no changes occurs to SED
        testSed = Sed()
        testSed.readSED_flambda(os.environ['SIMS_SED_LIBRARY_DIR'] +
                                '/galaxySED/Inst.80E09.25Z.spec.gz')
        testFlambda = []
        for fVal in testSed.flambda:
            testFlambda.append(fVal)
        testIGM = ApplyIGM()
        testIGM.initializeIGM()
        with warnings.catch_warnings(record=True) as wa:
            testIGM.applyIGM(1.1, testSed)
            self.assertEqual(len(wa), 1)
            self.assertTrue('IGM Lookup tables' in str(wa[-1].message))
        np.testing.assert_equal(testFlambda, testSed.flambda)

        #Test that lookup table is read in correctly
        testTable15 = np.genfromtxt(
            str(os.environ['SIMS_SED_LIBRARY_DIR'] + '/igm/' +
                'MeanLookupTable_zSource1.5.tbl'))
        np.testing.assert_equal(testTable15, testIGM.meanLookups['1.5'])

        #Test output by making sure that an incoming sed with flambda = 1.0 everywhere will return the
        #transmission values of the lookup table as its flambda output
        testSed.setSED(testSed.wavelen, flambda=np.ones(len(testSed.wavelen)))
        testIGM.applyIGM(1.5, testSed)
        testTable15Above300 = testTable15[np.where(testTable15[:, 0] >= 300.0)]
        testSed.resampleSED(wavelen_match=testTable15Above300[:, 0])
        np.testing.assert_allclose(testTable15Above300[:, 1], testSed.flambda,
                                   1e-4)
Exemplo n.º 3
0
    def calcMagNorm(self,
                    objectMags,
                    sedObj,
                    bandpassDict,
                    mag_error=None,
                    redshift=None,
                    filtRange=None):
        """
        This will find the magNorm value that gives the closest match to the magnitudes of the object
        using the matched SED. Uses scipy.optimize.leastsq to find the values of fluxNorm that minimizes
        the function: ((flux_obs - (fluxNorm*flux_model))/flux_error)**2.

        @param [in] objectMags are the magnitude values for the object with extinction matching that of
        the SED object. In the normal case using the selectSED routines above it will be dereddened mags.

        @param [in] sedObj is an Sed class instance that is set with the wavelength and flux of the
        matched SED

        @param [in] bandpassDict is a BandpassDict class instance with the Bandpasses set to those
        for the magnitudes given for the catalog object

        @param [in] mag_error are provided error values for magnitudes in objectMags. If none provided
        then this defaults to 1.0. This should be an array of the same length as objectMags.

        @param [in] redshift is the redshift of the object if the magnitude is observed

        @param [in] filtRange is a selected range of filters specified by their indices in the bandpassList
        to match up against. Used when missing data in some magnitude bands.

        @param [out] bestMagNorm is the magnitude normalization for the given magnitudes and SED
        """

        import scipy.optimize as opt

        sedTest = Sed()
        sedTest.setSED(sedObj.wavelen, flambda=sedObj.flambda)
        if redshift is not None:
            sedTest.redshiftSED(redshift)
        imSimBand = Bandpass()
        imSimBand.imsimBandpass()
        zp = -2.5 * np.log10(3631)  #Note using default AB zeropoint
        flux_obs = np.power(10, (objectMags + zp) / (-2.5))
        sedTest.resampleSED(wavelen_match=bandpassDict.values()[0].wavelen)
        sedTest.flambdaTofnu()
        flux_model = sedTest.manyFluxCalc(bandpassDict.phiArray,
                                          bandpassDict.wavelenStep)
        if filtRange is not None:
            flux_obs = flux_obs[filtRange]
            flux_model = flux_model[filtRange]
        if mag_error is None:
            flux_error = np.ones(len(flux_obs))
        else:
            flux_error = np.abs(flux_obs * (np.log(10) / (-2.5)) * mag_error)
        bestFluxNorm = opt.leastsq(
            lambda x: ((flux_obs - (x * flux_model)) / flux_error), 1.0)[0][0]
        sedTest.multiplyFluxNorm(bestFluxNorm)
        bestMagNorm = sedTest.calcMag(imSimBand)
        return bestMagNorm
Exemplo n.º 4
0
    def testAlternateBandpassesStars(self):
        """
        This will test our ability to do photometry using non-LSST bandpasses.

        It will first calculate the magnitudes using the getters in cartoonPhotometryStars.

        It will then load the alternate bandpass files 'by hand' and re-calculate the magnitudes
        and make sure that the magnitude values agree.  This is guarding against the possibility
        that some default value did not change and the code actually ended up loading the
        LSST bandpasses.
        """

        obs_metadata_pointed = ObservationMetaData(
            mjd=2013.23, boundType="circle", unrefractedRA=200.0, unrefractedDec=-30.0, boundLength=1.0
        )

        bandpassDir = os.path.join(lsst.utils.getPackageDir("sims_photUtils"), "tests", "cartoonSedTestData")

        cartoon_dict = BandpassDict.loadTotalBandpassesFromFiles(
            ["u", "g", "r", "i", "z"], bandpassDir=bandpassDir, bandpassRoot="test_bandpass_"
        )

        testBandPasses = {}
        keys = ["u", "g", "r", "i", "z"]

        bplist = []

        for kk in keys:
            testBandPasses[kk] = Bandpass()
            testBandPasses[kk].readThroughput(os.path.join(bandpassDir, "test_bandpass_%s.dat" % kk))
            bplist.append(testBandPasses[kk])

        sedObj = Sed()
        phiArray, waveLenStep = sedObj.setupPhiArray(bplist)

        sedFileName = os.path.join(lsst.utils.getPackageDir("sims_sed_library"), "starSED", "kurucz")
        sedFileName = os.path.join(sedFileName, "km20_5750.fits_g40_5790.gz")
        ss = Sed()
        ss.readSED_flambda(sedFileName)

        controlBandpass = Bandpass()
        controlBandpass.imsimBandpass()
        ff = ss.calcFluxNorm(22.0, controlBandpass)
        ss.multiplyFluxNorm(ff)

        testMags = cartoon_dict.magListForSed(ss)

        ss.resampleSED(wavelen_match=bplist[0].wavelen)
        ss.flambdaTofnu()
        mags = -2.5 * numpy.log10(numpy.sum(phiArray * ss.fnu, axis=1) * waveLenStep) - ss.zp
        self.assertTrue(len(mags) == len(testMags))
        self.assertTrue(len(mags) > 0)
        for j in range(len(mags)):
            self.assertAlmostEqual(mags[j], testMags[j], 10)
Exemplo n.º 5
0
    def calcMagNorm(self, objectMags, sedObj, bandpassDict, mag_error = None,
                    redshift = None, filtRange = None):

        """
        This will find the magNorm value that gives the closest match to the magnitudes of the object
        using the matched SED. Uses scipy.optimize.leastsq to find the values of fluxNorm that minimizes
        the function: ((flux_obs - (fluxNorm*flux_model))/flux_error)**2.

        @param [in] objectMags are the magnitude values for the object with extinction matching that of
        the SED object. In the normal case using the selectSED routines above it will be dereddened mags.

        @param [in] sedObj is an Sed class instance that is set with the wavelength and flux of the
        matched SED

        @param [in] bandpassDict is a BandpassDict class instance with the Bandpasses set to those
        for the magnitudes given for the catalog object

        @param [in] mag_error are provided error values for magnitudes in objectMags. If none provided
        then this defaults to 1.0. This should be an array of the same length as objectMags.

        @param [in] redshift is the redshift of the object if the magnitude is observed

        @param [in] filtRange is a selected range of filters specified by their indices in the bandpassList
        to match up against. Used when missing data in some magnitude bands.

        @param [out] bestMagNorm is the magnitude normalization for the given magnitudes and SED
        """

        import scipy.optimize as opt

        sedTest = Sed()
        sedTest.setSED(sedObj.wavelen, flambda = sedObj.flambda)
        if redshift is not None:
            sedTest.redshiftSED(redshift)
        imSimBand = Bandpass()
        imSimBand.imsimBandpass()
        zp = -2.5*np.log10(3631)  #Note using default AB zeropoint
        flux_obs = np.power(10,(objectMags + zp)/(-2.5))
        sedTest.resampleSED(wavelen_match=bandpassDict.values()[0].wavelen)
        sedTest.flambdaTofnu()
        flux_model = sedTest.manyFluxCalc(bandpassDict.phiArray, bandpassDict.wavelenStep)
        if filtRange is not None:
            flux_obs = flux_obs[filtRange]
            flux_model = flux_model[filtRange]
        if mag_error is None:
            flux_error = np.ones(len(flux_obs))
        else:
            flux_error = np.abs(flux_obs*(np.log(10)/(-2.5))*mag_error)
        bestFluxNorm = opt.leastsq(lambda x: ((flux_obs - (x*flux_model))/flux_error), 1.0)[0][0]
        sedTest.multiplyFluxNorm(bestFluxNorm)
        bestMagNorm = sedTest.calcMag(imSimBand)
        return bestMagNorm
Exemplo n.º 6
0
    def testAlternateBandpassesStars(self):
        """
        This will test our ability to do photometry using non-LSST bandpasses.

        It will first calculate the magnitudes using the getters in cartoonPhotometryStars.

        It will then load the alternate bandpass files 'by hand' and re-calculate the magnitudes
        and make sure that the magnitude values agree.  This is guarding against the possibility
        that some default value did not change and the code actually ended up loading the
        LSST bandpasses.
        """

        bandpassDir = os.path.join(lsst.utils.getPackageDir('sims_photUtils'), 'tests', 'cartoonSedTestData')

        cartoon_dict = BandpassDict.loadTotalBandpassesFromFiles(['u', 'g', 'r', 'i', 'z'],
                                                                 bandpassDir=bandpassDir,
                                                                 bandpassRoot='test_bandpass_')

        testBandPasses = {}
        keys = ['u', 'g', 'r', 'i', 'z']

        bplist = []

        for kk in keys:
            testBandPasses[kk] = Bandpass()
            testBandPasses[kk].readThroughput(os.path.join(bandpassDir, "test_bandpass_%s.dat" % kk))
            bplist.append(testBandPasses[kk])

        sedObj = Sed()
        phiArray, waveLenStep = sedObj.setupPhiArray(bplist)

        sedFileName = os.path.join(lsst.utils.getPackageDir('sims_photUtils'),
                                   'tests/cartoonSedTestData/starSed/')
        sedFileName = os.path.join(sedFileName, 'kurucz', 'km20_5750.fits_g40_5790.gz')
        ss = Sed()
        ss.readSED_flambda(sedFileName)

        controlBandpass = Bandpass()
        controlBandpass.imsimBandpass()
        ff = ss.calcFluxNorm(22.0, controlBandpass)
        ss.multiplyFluxNorm(ff)

        testMags = cartoon_dict.magListForSed(ss)

        ss.resampleSED(wavelen_match = bplist[0].wavelen)
        ss.flambdaTofnu()
        mags = -2.5*np.log10(np.sum(phiArray*ss.fnu, axis=1)*waveLenStep) - ss.zp
        self.assertEqual(len(mags), len(testMags))
        self.assertGreater(len(mags), 0)
        for j in range(len(mags)):
            self.assertAlmostEqual(mags[j], testMags[j], 10)
Exemplo n.º 7
0
    def testApplyIGM(self):

        """Test application of IGM from Lookup Tables to SED objects"""

        # Test that a warning comes up if input redshift is out
        # of range and that no changes occurs to SED
        testSed = Sed()
        sedName = os.path.join(getPackageDir('sims_photUtils'),
                               'tests/cartoonSedTestData/galaxySed/')
        testSed.readSED_flambda(os.path.join(sedName,
                                             'Burst.10E08.002Z.spec.gz'))
        testFlambda = []
        for fVal in testSed.flambda:
            testFlambda.append(fVal)
        testIGM = ApplyIGM()
        testIGM.initializeIGM()
        with warnings.catch_warnings(record=True) as wa:
            testIGM.applyIGM(1.1, testSed)
            self.assertEqual(len(wa), 1)
            self.assertIn('IGM Lookup tables', str(wa[-1].message))
        np.testing.assert_equal(testFlambda, testSed.flambda)

        # Test that lookup table is read in correctly
        testTable15 = np.genfromtxt(str(getPackageDir('sims_photUtils') +
                                        '/python/lsst/sims/photUtils/igm_tables/' +
                                        'MeanLookupTable_zSource1.5.tbl.gz'))
        np.testing.assert_equal(testTable15, testIGM.meanLookups['1.5'])

        # Test output by making sure that an incoming sed
        # with flambda = 1.0 everywhere will return the
        # transmission values of the lookup table as its
        # flambda output
        testSed.setSED(testSed.wavelen, flambda=np.ones(len(testSed.wavelen)))
        testIGM.applyIGM(1.5, testSed)
        testTable15Above300 = testTable15[np.where(testTable15[:, 0] >= 300.0)]
        testSed.resampleSED(wavelen_match = testTable15Above300[:, 0])
        np.testing.assert_allclose(testTable15Above300[:, 1],
                                   testSed.flambda, 1e-4)
Exemplo n.º 8
0
    def testApplyIGM(self):

        """Test application of IGM from Lookup Tables to SED objects"""

        # Test that a warning comes up if input redshift is out
        # of range and that no changes occurs to SED
        testSed = Sed()
        sedName = os.path.join(getPackageDir('sims_sed_library'), 'galaxySED')
        testSed.readSED_flambda(os.path.join(sedName,
                                             'Burst.10E08.002Z.spec.gz'))
        testFlambda = []
        for fVal in testSed.flambda:
            testFlambda.append(fVal)
        testIGM = ApplyIGM()
        testIGM.initializeIGM()
        with warnings.catch_warnings(record=True) as wa:
            testIGM.applyIGM(1.1, testSed)
            self.assertEqual(len(wa), 1)
            self.assertIn('IGM Lookup tables', str(wa[-1].message))
        np.testing.assert_equal(testFlambda, testSed.flambda)

        # Test that lookup table is read in correctly
        testTable15 = np.genfromtxt(str(getPackageDir('sims_catUtils') +
                                        '/python/lsst/sims/catUtils/IGM/igm_tables/' +
                                        'MeanLookupTable_zSource1.5.tbl.gz'))
        np.testing.assert_equal(testTable15, testIGM.meanLookups['1.5'])

        # Test output by making sure that an incoming sed
        # with flambda = 1.0 everywhere will return the
        # transmission values of the lookup table as its
        # flambda output
        testSed.setSED(testSed.wavelen, flambda=np.ones(len(testSed.wavelen)))
        testIGM.applyIGM(1.5, testSed)
        testTable15Above300 = testTable15[np.where(testTable15[:, 0] >= 300.0)]
        testSed.resampleSED(wavelen_match = testTable15Above300[:, 0])
        np.testing.assert_allclose(testTable15Above300[:, 1],
                                   testSed.flambda, 1e-4)
Exemplo n.º 9
0
    def applyIGM(self, redshift, sedobj):
        """
        Apply IGM extinction to already redshifted sed with redshift  
        between zMin and zMax defined by range of lookup tables
        
        @param [in] redshift is the redshift of the incoming SED object

        @param [in] sedobj is the SED object to which IGM extinction will be applied. This object
        will be modified as a result of this.
        """

        if self.IGMisInitialized == False:
            self.initializeIGM()

        #First make sure redshift is in range of lookup tables.
        if (redshift < self.zMin) or (redshift > self.zMax):
            warnings.warn(
                str("IGM Lookup tables only applicable for " + str(self.zMin) +
                    " < z < " + str(self.zMax) + ". No action taken"))
            return

        #Now read in closest two lookup tables for given redshift
        lowerSed = Sed()
        upperSed = Sed()
        for lower, upper in zip(self.zRange[:-1], self.zRange[1:]):
            if lower <= redshift <= upper:
                lowerSed.setSED(self.meanLookups[str(lower)][:, 0],
                                flambda=self.meanLookups[str(lower)][:, 1])
                upperSed.setSED(self.meanLookups[str(upper)][:, 0],
                                flambda=self.meanLookups[str(upper)][:, 1])
                break

        #Redshift lookup tables to redshift of source, i.e. if source redshift is 1.78 shift lookup
        #table for 1.7 and lookup table for 1.8 to up and down to 1.78, respectively
        zLowerShift = ((1.0 + redshift) / (1.0 + lower)) - 1.0
        zUpperShift = ((1.0 + redshift) / (1.0 + upper)) - 1.0
        lowerSed.redshiftSED(zLowerShift)
        upperSed.redshiftSED(zUpperShift)

        #Resample lower and upper transmission data onto same wavelength grid.
        minWavelen = 300.  #All lookup tables are usable above 300nm
        maxWavelen = np.amin([lowerSed.wavelen[-1], upperSed.wavelen[-1]
                              ]) - 0.01
        lowerSed.resampleSED(wavelen_min=minWavelen,
                             wavelen_max=maxWavelen,
                             wavelen_step=0.01)
        upperSed.resampleSED(wavelen_match=lowerSed.wavelen)

        #Now insert this into a transmission array of 1.0 beyond the limits of current application
        #So that we can get an sed back that extends to the longest wavelengths of the incoming sed
        finalWavelen = np.arange(300., sedobj.wavelen[-1] + 0.01, 0.01)
        finalFlambdaExtended = np.ones(len(finalWavelen))

        #Weighted Average of Transmission from each lookup table to get final transmission
        #table at desired redshift
        dzGrid = self.zDelta  #Step in redshift between transmission lookup table files
        finalSed = Sed()
        finalFlambda = (lowerSed.flambda * (1.0 -
                                            ((redshift - lower) / dzGrid)) +
                        upperSed.flambda * (1.0 -
                                            ((upper - redshift) / dzGrid)))
        finalFlambdaExtended[0:len(finalFlambda)] = finalFlambda
        finalSed.setSED(wavelen=finalWavelen, flambda=finalFlambdaExtended)

        #Resample incoming sed to new grid so that we don't get warnings from multiplySED
        #about matching wavelength grids
        sedobj.resampleSED(wavelen_match=finalSed.wavelen)

        #Now multiply transmission curve by input SED to get final result and make it the new flambda
        #data in the original sed which also is now on a new grid starting at 300 nm
        test = sedobj.multiplySED(finalSed)
        sedobj.flambda = test.flambda
Exemplo n.º 10
0
    def testAlternateBandpassesGalaxies(self):
        """
        the same as testAlternateBandpassesStars, but for galaxies
        """

        obs_metadata_pointed = ObservationMetaData(mjd=50000.0,
                                                   boundType='circle',
                                                   pointingRA=0.0, pointingDec=0.0,
                                                   boundLength=10.0)

        dtype = np.dtype([('galid', np.int),
                          ('ra', np.float),
                          ('dec', np.float),
                          ('uTotal', np.float),
                          ('gTotal', np.float),
                          ('rTotal', np.float),
                          ('iTotal', np.float),
                          ('zTotal', np.float),
                          ('uBulge', np.float),
                          ('gBulge', np.float),
                          ('rBulge', np.float),
                          ('iBulge', np.float),
                          ('zBulge', np.float),
                          ('uDisk', np.float),
                          ('gDisk', np.float),
                          ('rDisk', np.float),
                          ('iDisk', np.float),
                          ('zDisk', np.float),
                          ('uAgn', np.float),
                          ('gAgn', np.float),
                          ('rAgn', np.float),
                          ('iAgn', np.float),
                          ('zAgn', np.float),
                          ('bulgeName', str, 200),
                          ('bulgeNorm', np.float),
                          ('bulgeAv', np.float),
                          ('diskName', str, 200),
                          ('diskNorm', np.float),
                          ('diskAv', np.float),
                          ('agnName', str, 200),
                          ('agnNorm', np.float),
                          ('redshift', np.float)])

        test_cat = cartoonGalaxies(self.galaxy, obs_metadata=obs_metadata_pointed)
        with lsst.utils.tests.getTempFilePath('.txt') as catName:
            test_cat.write_catalog(catName)
            catData = np.genfromtxt(catName, dtype=dtype, delimiter=', ')

        self.assertGreater(len(catData), 0)

        cartoonDir = getPackageDir('sims_photUtils')
        cartoonDir = os.path.join(cartoonDir, 'tests', 'cartoonSedTestData')
        sedDir = getPackageDir('sims_sed_library')

        testBandpasses = {}
        keys = ['u', 'g', 'r', 'i', 'z']

        for kk in keys:
            testBandpasses[kk] = Bandpass()
            testBandpasses[kk].readThroughput(os.path.join(cartoonDir, "test_bandpass_%s.dat" % kk))

        imsimBand = Bandpass()
        imsimBand.imsimBandpass()

        specMap = defaultSpecMap

        ct = 0
        for line in catData:
            bulgeMagList = []
            diskMagList = []
            agnMagList = []
            if line['bulgeName'] == 'None':
                for bp in keys:
                    np.testing.assert_equal(line['%sBulge' % bp], np.NaN)
                    bulgeMagList.append(np.NaN)
            else:
                ct += 1
                dummySed = Sed()
                dummySed.readSED_flambda(os.path.join(sedDir, specMap[line['bulgeName']]))
                fnorm = dummySed.calcFluxNorm(line['bulgeNorm'], imsimBand)
                dummySed.multiplyFluxNorm(fnorm)
                a_int, b_int = dummySed.setupCCM_ab()
                dummySed.addDust(a_int, b_int, A_v=line['bulgeAv'])
                dummySed.redshiftSED(line['redshift'], dimming=True)
                dummySed.resampleSED(wavelen_match=testBandpasses['u'].wavelen)
                for bpName in keys:
                    mag = dummySed.calcMag(testBandpasses[bpName])
                    self.assertAlmostEqual(mag, line['%sBulge' % bpName], 10)
                    bulgeMagList.append(mag)

            if line['diskName'] == 'None':
                for bp in keys:
                    np.assert_equal(line['%sDisk' % bp], np.NaN)
                    diskMagList.append(np.NaN)
            else:
                ct += 1
                dummySed = Sed()
                dummySed.readSED_flambda(os.path.join(sedDir, specMap[line['diskName']]))
                fnorm = dummySed.calcFluxNorm(line['diskNorm'], imsimBand)
                dummySed.multiplyFluxNorm(fnorm)
                a_int, b_int = dummySed.setupCCM_ab()
                dummySed.addDust(a_int, b_int, A_v=line['diskAv'])
                dummySed.redshiftSED(line['redshift'], dimming=True)
                dummySed.resampleSED(wavelen_match=testBandpasses['u'].wavelen)
                for bpName in keys:
                    mag = dummySed.calcMag(testBandpasses[bpName])
                    self.assertAlmostEqual(mag, line['%sDisk' % bpName], 10)
                    diskMagList.append(mag)

            if line['agnName'] == 'None':
                for bp in keys:
                    np.testing.assert_true(line['%sAgn' % bp], np.NaN)
                    agnMagList.append(np.NaN)
            else:
                ct += 1
                dummySed = Sed()
                dummySed.readSED_flambda(os.path.join(sedDir, specMap[line['agnName']]))
                fnorm = dummySed.calcFluxNorm(line['agnNorm'], imsimBand)
                dummySed.multiplyFluxNorm(fnorm)
                dummySed.redshiftSED(line['redshift'], dimming=True)
                dummySed.resampleSED(wavelen_match=testBandpasses['u'].wavelen)
                for bpName in keys:
                    mag = dummySed.calcMag(testBandpasses[bpName])
                    self.assertAlmostEqual(mag, line['%sAgn' % bpName], 10)
                    agnMagList.append(mag)

            totalMags = PhotometryGalaxies().sum_magnitudes(bulge=np.array(bulgeMagList),
                                                            disk=np.array(diskMagList),
                                                            agn=np.array(agnMagList))

            for testMag, bpName in zip(totalMags, keys):
                if np.isnan(line['%sTotal' % bpName]):
                    np.testing.assert_equal(testMag, np.NaN)
                else:
                    self.assertAlmostEqual(testMag, line['%sTotal' % bpName], 10)

        self.assertGreater(ct, 0)
Exemplo n.º 11
0
    def testAlternateBandpassesGalaxies(self):
        """
        the same as testAlternateBandpassesStars, but for galaxies
        """

        obs_metadata_pointed = ObservationMetaData(mjd=50000.0,
                                                   boundType='circle',
                                                   pointingRA=0.0,
                                                   pointingDec=0.0,
                                                   boundLength=10.0)

        dtype = np.dtype([('galid', np.int), ('ra', np.float),
                          ('dec', np.float), ('uTotal', np.float),
                          ('gTotal', np.float), ('rTotal', np.float),
                          ('iTotal', np.float), ('zTotal', np.float),
                          ('uBulge', np.float), ('gBulge', np.float),
                          ('rBulge', np.float), ('iBulge', np.float),
                          ('zBulge', np.float), ('uDisk', np.float),
                          ('gDisk', np.float), ('rDisk', np.float),
                          ('iDisk', np.float), ('zDisk', np.float),
                          ('uAgn', np.float), ('gAgn', np.float),
                          ('rAgn', np.float), ('iAgn', np.float),
                          ('zAgn', np.float), ('bulgeName', str, 200),
                          ('bulgeNorm', np.float), ('bulgeAv', np.float),
                          ('diskName', str, 200), ('diskNorm', np.float),
                          ('diskAv', np.float), ('agnName', str, 200),
                          ('agnNorm', np.float), ('redshift', np.float)])

        test_cat = cartoonGalaxies(self.galaxy,
                                   obs_metadata=obs_metadata_pointed)
        with lsst.utils.tests.getTempFilePath('.txt') as catName:
            test_cat.write_catalog(catName)
            catData = np.genfromtxt(catName, dtype=dtype, delimiter=', ')

        self.assertGreater(len(catData), 0)

        cartoonDir = getPackageDir('sims_photUtils')
        cartoonDir = os.path.join(cartoonDir, 'tests', 'cartoonSedTestData')
        sedDir = getPackageDir('sims_sed_library')

        testBandpasses = {}
        keys = ['u', 'g', 'r', 'i', 'z']

        for kk in keys:
            testBandpasses[kk] = Bandpass()
            testBandpasses[kk].readThroughput(
                os.path.join(cartoonDir, "test_bandpass_%s.dat" % kk))

        imsimBand = Bandpass()
        imsimBand.imsimBandpass()

        specMap = defaultSpecMap

        ct = 0
        for line in catData:
            bulgeMagList = []
            diskMagList = []
            agnMagList = []
            if line['bulgeName'] == 'None':
                for bp in keys:
                    np.testing.assert_equal(line['%sBulge' % bp], np.NaN)
                    bulgeMagList.append(np.NaN)
            else:
                ct += 1
                dummySed = Sed()
                dummySed.readSED_flambda(
                    os.path.join(sedDir, specMap[line['bulgeName']]))
                fnorm = dummySed.calcFluxNorm(line['bulgeNorm'], imsimBand)
                dummySed.multiplyFluxNorm(fnorm)
                a_int, b_int = dummySed.setupCCM_ab()
                dummySed.addDust(a_int, b_int, A_v=line['bulgeAv'])
                dummySed.redshiftSED(line['redshift'], dimming=True)
                dummySed.resampleSED(wavelen_match=testBandpasses['u'].wavelen)
                for bpName in keys:
                    mag = dummySed.calcMag(testBandpasses[bpName])
                    self.assertAlmostEqual(mag, line['%sBulge' % bpName], 10)
                    bulgeMagList.append(mag)

            if line['diskName'] == 'None':
                for bp in keys:
                    np.assert_equal(line['%sDisk' % bp], np.NaN)
                    diskMagList.append(np.NaN)
            else:
                ct += 1
                dummySed = Sed()
                dummySed.readSED_flambda(
                    os.path.join(sedDir, specMap[line['diskName']]))
                fnorm = dummySed.calcFluxNorm(line['diskNorm'], imsimBand)
                dummySed.multiplyFluxNorm(fnorm)
                a_int, b_int = dummySed.setupCCM_ab()
                dummySed.addDust(a_int, b_int, A_v=line['diskAv'])
                dummySed.redshiftSED(line['redshift'], dimming=True)
                dummySed.resampleSED(wavelen_match=testBandpasses['u'].wavelen)
                for bpName in keys:
                    mag = dummySed.calcMag(testBandpasses[bpName])
                    self.assertAlmostEqual(mag, line['%sDisk' % bpName], 10)
                    diskMagList.append(mag)

            if line['agnName'] == 'None':
                for bp in keys:
                    np.testing.assert_true(line['%sAgn' % bp], np.NaN)
                    agnMagList.append(np.NaN)
            else:
                ct += 1
                dummySed = Sed()
                dummySed.readSED_flambda(
                    os.path.join(sedDir, specMap[line['agnName']]))
                fnorm = dummySed.calcFluxNorm(line['agnNorm'], imsimBand)
                dummySed.multiplyFluxNorm(fnorm)
                dummySed.redshiftSED(line['redshift'], dimming=True)
                dummySed.resampleSED(wavelen_match=testBandpasses['u'].wavelen)
                for bpName in keys:
                    mag = dummySed.calcMag(testBandpasses[bpName])
                    self.assertAlmostEqual(mag, line['%sAgn' % bpName], 10)
                    agnMagList.append(mag)

            totalMags = PhotometryGalaxies().sum_magnitudes(
                bulge=np.array(bulgeMagList),
                disk=np.array(diskMagList),
                agn=np.array(agnMagList))

            for testMag, bpName in zip(totalMags, keys):
                if np.isnan(line['%sTotal' % bpName]):
                    np.testing.assert_equal(testMag, np.NaN)
                else:
                    self.assertAlmostEqual(testMag, line['%sTotal' % bpName],
                                           10)

        self.assertGreater(ct, 0)
Exemplo n.º 12
0
    def applyIGM(self, redshift, sedobj):

        """
        Apply IGM extinction to already redshifted sed with redshift  
        between zMin and zMax defined by range of lookup tables
        
        @param [in] redshift is the redshift of the incoming SED object

        @param [in] sedobj is the SED object to which IGM extinction will be applied. This object
        will be modified as a result of this.
        """

        if self.IGMisInitialized == False:
            self.initializeIGM()

        # First make sure redshift is in range of lookup tables.
        if (redshift < self.zMin) or (redshift > self.zMax):
            warnings.warn(
                str(
                    "IGM Lookup tables only applicable for "
                    + str(self.zMin)
                    + " < z < "
                    + str(self.zMax)
                    + ". No action taken"
                )
            )
            return

        # Now read in closest two lookup tables for given redshift
        lowerSed = Sed()
        upperSed = Sed()
        for lower, upper in zip(self.zRange[:-1], self.zRange[1:]):
            if lower <= redshift <= upper:
                lowerSed.setSED(self.meanLookups[str(lower)][:, 0], flambda=self.meanLookups[str(lower)][:, 1])
                upperSed.setSED(self.meanLookups[str(upper)][:, 0], flambda=self.meanLookups[str(upper)][:, 1])
                break

        # Redshift lookup tables to redshift of source, i.e. if source redshift is 1.78 shift lookup
        # table for 1.7 and lookup table for 1.8 to up and down to 1.78, respectively
        zLowerShift = ((1.0 + redshift) / (1.0 + lower)) - 1.0
        zUpperShift = ((1.0 + redshift) / (1.0 + upper)) - 1.0
        lowerSed.redshiftSED(zLowerShift)
        upperSed.redshiftSED(zUpperShift)

        # Resample lower and upper transmission data onto same wavelength grid.
        minWavelen = 300.0  # All lookup tables are usable above 300nm
        maxWavelen = np.amin([lowerSed.wavelen[-1], upperSed.wavelen[-1]]) - 0.01
        lowerSed.resampleSED(wavelen_min=minWavelen, wavelen_max=maxWavelen, wavelen_step=0.01)
        upperSed.resampleSED(wavelen_match=lowerSed.wavelen)

        # Now insert this into a transmission array of 1.0 beyond the limits of current application
        # So that we can get an sed back that extends to the longest wavelengths of the incoming sed
        finalWavelen = np.arange(300.0, sedobj.wavelen[-1] + 0.01, 0.01)
        finalFlambdaExtended = np.ones(len(finalWavelen))

        # Weighted Average of Transmission from each lookup table to get final transmission
        # table at desired redshift
        dzGrid = self.zDelta  # Step in redshift between transmission lookup table files
        finalSed = Sed()
        finalFlambda = lowerSed.flambda * (1.0 - ((redshift - lower) / dzGrid)) + upperSed.flambda * (
            1.0 - ((upper - redshift) / dzGrid)
        )
        finalFlambdaExtended[0 : len(finalFlambda)] = finalFlambda
        finalSed.setSED(wavelen=finalWavelen, flambda=finalFlambdaExtended)

        # Resample incoming sed to new grid so that we don't get warnings from multiplySED
        # about matching wavelength grids
        sedobj.resampleSED(wavelen_match=finalSed.wavelen)

        # Now multiply transmission curve by input SED to get final result and make it the new flambda
        # data in the original sed which also is now on a new grid starting at 300 nm
        test = sedobj.multiplySED(finalSed)
        sedobj.flambda = test.flambda