Пример #1
0
 def test_neg_wl_response(self):
     """Check that error is thrown if a negative wavelength is given to getFlux method"""
     
     s = sedFilter.SED(self.testdata[:,0], self.testdata[:,1])
     
     wl = -1.
     self.assertRaises(ValueError, lambda: s.getFlux(wl))
Пример #2
0
 def test_neg_z_response(self):
     """Check that error is thrown if a negative redshift is given to getFlux method"""
     
     s = sedFilter.SED(self.testdata[:,0], self.testdata[:,1])
     
     z = -1.
     self.assertRaises(ValueError, lambda: s.getFlux(self.testdata[5,0], z))
Пример #3
0
 def test_no_negative_fl_on_read(self):
     """Check that error is thrown if a negative flux is read from the data"""
     
     tmpdata = np.copy(self.testdata)
     tmpdata[0,1] = -1.
     
     self.assertRaises(ValueError, lambda: sedFilter.SED(tmpdata[:,0], tmpdata[:,1]))
Пример #4
0
 def test_resolution_wavelength(self):
     """Check the expected wavelength resolution of the SED is returned"""
     
     s = sedFilter.SED(self.testdata[:,0], self.testdata[:,1])
     
     nl = s.returnSedResolution()
     self.assertEqual(len(self.testdata[:,0]), nl)
Пример #5
0
 def test_max_wavelength(self):
     """Check the expected maximum wavelength of the SED is returned"""
     
     s = sedFilter.SED(self.testdata[:,0], self.testdata[:,1])
     
     lmin,lmax = s.returnSedRange()
     self.assertEqual(self.testdata[-1,0], lmax)
Пример #6
0
 def test_interpolation(self):
     """Check interpolation by feeding original wavelength grid back to interpolation function"""
     
     wl = self.testdata[:,0]
     fl = self.testdata[:,1]
     s = sedFilter.SED(wl, fl)
     
     for i in xrange(len(wl)):
         self.assertAlmostEqual(fl[i], s.getFlux(wl[i]))
Пример #7
0
 def test_no_neg_flux_returned(self):
     """Over huge wavelength, redshift domain check no negative fluxes are returned"""
     
     s = sedFilter.SED(self.testdata[:,0], self.testdata[:,1])
     
     lamMax = 10000000000000
     nlam = 10000
     dlam = lamMax/(nlam-1)
     
     dz = 0.5
     ndz = 10
     for i in xrange(ndz):
         z = i*dz
         
         for n in xrange(nlam):
             self.assertGreaterEqual(s.getFlux(n*dlam, z), 0.)
Пример #8
0
    def test_interpolation_again(self):
        """Check interpolation by checking flux values of wls between any two wl in the grid """
        
        wl = self.testdata[:,0]
        fl = self.testdata[:,1]
        s = sedFilter.SED(wl, fl)
        
        for i in xrange(len(wl)-1):
            
            # mid point wl
            wlt = 0.5*(wl[i] + wl[i+1])
            
            # fluxes around mid point
            flBounds = [fl[i], fl[i+1]]
            flMax = max(flBounds)
            flMin = min(flBounds)

            self.assertTrue( s.getFlux(wlt)<=flMax and s.getFlux(wlt)>=flMin )
Пример #9
0
    def generateSpectrum(self, colors):
        """Generate a new SED object given colors supplied
        
        """
        # Generate new set of eigenvalues for supplied colors
        eigenvals_generated = self._gp.predict(colors)

        # check if not all eigenvalues were used in GP
        nGP = eigenvals_generated.shape[1]
        if (nGP < self.eigenspectra.shape[0] and not self._isRetrained):

            if (self._isRetrained):
                raise ValueError("ERROR! cannot have ")
            print nGP, self.eigenspectra.shape[0]

            # find SED with closest colors
            ifit = self._fitColors(colors)

            #eigenvals_generated = eigenvals_generated + self.eigenvalue_coeffs[ifit, nGP+1,:]

            add_on = np.reshape(self.eigenvalue_coeffs[ifit, nGP:],
                                (1, len(self.eigenvalue_coeffs[ifit, nGP:])))
            eigenvals_generated = np.concatenate((eigenvals_generated, add_on),
                                                 axis=1)
            #raise ValueError("Error! not yet implemented")

        # Reconstruct SED and normalise so it sums to 1
        spec_rec = np.dot(eigenvals_generated,
                          self.eigenspectra) + self.meanSpec
        norm = np.sum(spec_rec)
        spec_rec /= norm

        # Protect against zero fluxes
        spec_rec[np.where(spec_rec < 0)] = 0.

        # Recreate SED object
        sed_rec = sedFilter.SED(self._waveLen, spec_rec)

        return sed_rec
Пример #10
0
def get_sed_array(sedDict,
                  minWavelen=2999.,
                  maxWavelen=12000.,
                  nWavelen=10000,
                  filterDict=None,
                  color_file=None):
    """Return array of SEDs on same wavelength grid (optionally along with colors as defined by filterDict)
    
       If computing colors, first orders filters by effective wavelength, then a color is:
       color_{i, i+1} = mag_filter_i - mag_filter_i+1
    
       @param sedDict       dictionary of SEDs
       @param minWavelen    minimum wavelength of wavelength grid
       @param maxWavelen    maximum wavelength of wavelength grid
       @param nWavelen      number of points in wavelength grid
       @param filterDict    dictionary of filters
       @param color_file    file to save SED colors to or read colors from (if exists)
       
    """

    doColors = True
    if (filterDict == None or color_file == None):
        doColors = False

    isFileExist = False
    if doColors:

        # sort based upon effective wavelength
        filter_order = sedFilter.orderFiltersByLamEff(filterDict)

        # check if file exists and need to calculate colors
        isFileExist = os.path.isfile(color_file)
        if (isFileExist):
            print "\nColors already computed,",
        else:
            print "\nComputing colors,",
    print "placing SEDs in array ..."

    # loop over each SED
    nSED = len(sedDict)
    spectra = []
    colors = []
    for ised, (sedname, spec) in enumerate(sedDict.items()):

        print "On SED", ised + 1, "of", nSED, sedname

        # re-grid SEDs onto same wavelengths
        waveLen, fl = spec.getSedData(lamMin=minWavelen,
                                      lamMax=maxWavelen,
                                      nLam=nWavelen)

        # normalise so they sum to 1
        norm = np.sum(fl)
        spectra.append(fl / norm)

        if doColors:
            # calculate or read colors
            cs = []
            if (isFileExist):

                # reading colors
                colors_in_file = np.loadtxt(color_file)
                cs = colors_in_file[ised, :]

            else:

                # calculating colors
                spec = sedFilter.SED(waveLen, fl)  #/norm)
                pcalcs = phot.PhotCalcs(spec, filterDict)

                # in each filter
                for i in range(len(filterDict) - 1):
                    color = pcalcs.computeColor(filter_order[i],
                                                filter_order[i + 1])
                    if (color == float('inf')):
                        color = 99.
                    cs.append(color)

            # store colors for this SED
            colors.append(cs)

    # conver to np arrays for ease
    spectra = np.array(spectra)
    colors = np.array(colors)

    # if had to calculate, save colors to file to re-use
    if (not isFileExist and doColors):
        print "Saving colors to file for future use"
        np.savetxt(color_file, colors)

    if doColors:
        return waveLen, spectra, colors
    else:
        return waveLen, spectra
listOfFilters = 'LSST.filters'
pathToFilters = '../filter_data'

# create a dictionary: keyword is filter name, value is a Filter object
filterDict = sedFilter.createFilterDict(listOfFilters, pathToFilters)

# return the filter names
filterList = sedFilter.orderFiltersByLamEff(filterDict)
print 'Filter list = ', filterList
nFilter = len(filterList)

# load in elliptical SED (1st col: wavelength in A, 2nd col: fluxes in wl units)
seddata = np.loadtxt('../sed_data/El_B2004a.sed')

# turn into SED object
sed = sedFilter.SED(seddata[:, 0], seddata[:, 1])

# instantiate photometry calculations

# need cosmological model
h = 1.
omegamat = 0.3
omegaDE = 0.7
wX = -1.
wXa = 0.
cosmoModel = cosmo.cosmologyCalculator(h, omegamat, omegaDE, wX, wXa)

# need error model

# fractional flux error = 10%
pars = {}
Пример #12
0
import unittest
import os
import numpy as np
import cphotometry as cphot
import sedFilter
import cosmo
import photErrorModel as pem

# Single SED for testing
fname = os.path.join(os.path.dirname(__file__), '../sed_data/El_B2004a.sed')
seddata = np.loadtxt(fname)
TEST_SED = sedFilter.SED(seddata[:, 0], seddata[:, 1])

# List of filters for testing
listOfFilters = 'LSST.filters'
pathToFilters = '../filter_data'
TEST_FILTERDICT = sedFilter.createFilterDict(listOfFilters, pathToFilters)
FILTERLIST = sedFilter.orderFiltersByLamEff(TEST_FILTERDICT)

# List of SEDs for testing
SEDLIST = []
sedfiles = [
    '../sed_data/El_B2004a.sed', '../sed_data/Sbc_B2004a.sed',
    '../sed_data/Scd_B2004a.sed', '../sed_data/Im_B2004a.sed'
]
for name in sedfiles:
    seddata = np.loadtxt(name)
    SEDLIST.append(sedFilter.SED(seddata[:, 0], seddata[:, 1]))

# Cosmological model
COSMOMODEL = cosmo.cosmologyCalculator()
Пример #13
0
# wavelength grid to plot
lamMin = 1000.
lamMax = 10000.
nLam = 1000

# start figure
fig = plt.figure(figsize=(20,20))

ised = 1
for name in sed_names:
    
    # create SED object
    fname = sed_location + name + sed_file_ext
    f = np.loadtxt(fname)
    s = sedFilter.SED(f[:,0], f[:,1])
    
    # return flux data for wavelength grid
    wavelengths, fluxes = s.getSedData(lamMin=lamMin, lamMax=lamMax, nLam=nLam)
    
    # plot
    ax = fig.add_subplot(2,3,ised)
    ax.plot(wavelengths, fluxes, linestyle='solid', color='black', label=name)
    ax.set_xlabel('wavelength (angstroms)', fontsize=24)
    ax.set_ylabel('flux', fontsize=24)
    handles, labels = ax.get_legend_handles_labels()
    ax.legend(labels)
    ax.legend(loc='lower right',prop={'size':12})
    
    ised+=1
Пример #14
0
 def test_flux_units(self):
     """Check flux units are 'wl' (no other option implemented yet)"""
     
     s = sedFilter.SED(self.testdata[:,0], self.testdata[:,1])
     
     self.assertEqual(s.returnFluxUnits(),"wl")
Пример #15
0
 def test_set_em_line(self):
     """Check setEmLine throws error as not implemented yet"""
     
     s = sedFilter.SED(self.testdata[:,0], self.testdata[:,1])
     s.setEmLine(4.)