Example #1
0
 def __init__(self, data, name='BazinSource', version=None, tstep=1, colorCurve=None):
     super(sncosmo.Source, self).__init__()  # init for the super class
     self.name = name
     self.version = version
     self._model = {}
     self.lc = _removeDupes(data)
     wave = []
     for b in np.unique(data['band']):
         wave = np.append(wave, sncosmo.get_bandpass(b).wave)
     wave = np.sort(np.unique(wave))
     wave = np.append([.99*wave[0]], wave)
     wave = np.append(wave, [1.01*wave[-1]])
     self._wave = wave
     # self._phase=np.arange(-(np.max(data['time'])-np.min(data['time'])),np.max(data['time'])-np.min(data['time']),tstep)
     self._phase = np.arange(-300, 300, 1)
     self._parameters = np.array([1., 0., 30., 15.])
     self._tstep = tstep
     if colorCurve is not None:
         color = [x for x in colorCurve.colnames if x != 'time'][0]
         curve = interp1d(
             colorCurve['time'], colorCurve[color], fill_value=0., bounds_error=False)
         self._ts_sources = dict([])
         i = 0
         for b in [color[0:color.find('-')], color[color.find('-')+1:]]:
             self._ts_sources[b] = _param_to_source(self, sncosmo.get_bandpass(b).wave, curve,
                                                    color[0:color.find('-')], color[color.find('-')+1:], ref_color=i == 0)
             i += 1
     else:
         self._ts_sources = {b: _param_to_source(
             self, sncosmo.get_bandpass(b).wave) for b in np.unique(self.lc['band'])}
Example #2
0
def load_filters(FILTER_PREFIX='tophat_'):
    '''
    Load UBVRI tophat filters defined in Pereira (2013) into the sncosmo
    registry.  Also returns a dictionary of zero-point values in Vega system
    flux for each filter.  Flux is given in [photons/s/cm^2].

    Example usage:

        ZP_CACHE = loader.load_filters()
        U_band_zp = ZP_CACHE['U']
    '''
    # dictionary for zero point fluxes of filters
    ZP_CACHE = {'prefix': FILTER_PREFIX}

    for f in 'UBVRI':
        filter_name = FILTER_PREFIX+f
        file_name = dirname+'/data/filters/'+filter_name+'.dat'
        
        try:
            snc.get_bandpass(filter_name)
        except:
            data = np.genfromtxt(file_name)
            bandpass = snc.Bandpass( data[:,0], data[:,1] )
            snc.registry.register(bandpass, filter_name)

        zpsys = snc.get_magsystem('ab')
        zp_phot = zpsys.zpbandflux(filter_name)

        ZP_CACHE[f] = zp_phot

    return ZP_CACHE
Example #3
0
def calc_model_chisq(data, result, model):
    """Calculate the chi-squared for a given data table and model

    Chi-squared is calculated using parameter values from ``model``. Degrees
    of freedom are calculated using the number of varied parameters specified
    is the ``result`` object.

    Args:
        data    (Table): An sncosmo input table
        model   (Model): An sncosmo Model
        result (Result): sncosmo fitting result

    Returns:
        The un-normalized chi-squared
        The number of data points used in the calculation
    """

    data = deepcopy(data)

    # Drop any data that is not withing the model's range
    min_band_wave = np.array(
        [sncosmo.get_bandpass(b).minwave() for b in data['band']])
    max_band_wave = np.array(
        [sncosmo.get_bandpass(b).maxwave() for b in data['band']])
    data = data[(data['time'] >= model.mintime())
                & (data['time'] <= model.maxtime()) &
                (min_band_wave >= model.minwave()) &
                (max_band_wave <= model.maxwave())]

    if len(data) == 0:
        raise ValueError('No data within model range')

    return sncosmo.chisq(data, model), len(data) - len(result.vparam_names)
Example #4
0
    def _flux(self, phase, wave):

        band = [x for x in np.unique(self.lc['band']) if sncosmo.get_bandpass(
            x).wave[0] <= wave[0] and sncosmo.get_bandpass(x).wave[-1] >= wave[-1]][0]

        src = self._ts_sources[band]

        return(src._flux(phase, wave)*(self._param_flux(phase)[:, None]))
Example #5
0
def _param_to_source(source,
                     wave,
                     color_curve=None,
                     band1=None,
                     band2=None,
                     ref_color=False):
    band = None
    for b in np.unique(source.lc['band']):
        temp = sncosmo.get_bandpass(b)
        if temp.minwave() <= min(wave) and temp.maxwave() >= max(wave):
            band = sncosmo.get_bandpass(b)
    if band is None:
        raise RuntimeError(
            "Hmm, your data do not contain the band you want to fit.")
    finalPhase = source._phase
    if color_curve is not None and not ref_color:
        zp1 = source.lc['zp'][source.lc['band'] == band1][0]
        zp2 = source.lc['zp'][source.lc['band'] == band2][0]
        flux1 = sncosmo.Model(source._ts_sources[band1]).bandflux(
            band1, source._phase, zp1,
            source.lc['zpsys'][source.lc['band'] == band1][0])

        temp_flux = flux1 / 10**(-.4 * (color_curve(source._phase) -
                                        (zp1 - zp2)))

    else:
        temp_flux = np.ones(len(finalPhase))
    try:
        zpnorm = 10.**(
            0.4 * source.lc['zp'][source.lc['band'] == band.name.lower()][0])
        band.name = band.name.lower()
    except:
        zpnorm = 10.**(
            0.4 * source.lc['zp'][source.lc['band'] == band.name.upper()][0])
        band.name = band.name.upper()

    wave, dwave = integration_grid(band.minwave(), band.maxwave(),
                                   MODEL_BANDFLUX_SPACING)

    ms = sncosmo.get_magsystem(source.lc['zpsys'][0])
    zpnorm = zpnorm / ms.zpbandflux(band)
    flux = temp_flux * HC_ERG_AA / (dwave * np.sum(wave * band(wave)) * zpnorm)
    finalWave = np.arange(wave[0] - dwave * 10, wave[-1] + dwave * 10, dwave)
    finalFlux = np.zeros((len(finalPhase), len(finalWave)))

    for i in range(len(finalPhase)):
        #if finalPhase[i]>= np.min(timeArr) and finalPhase[i] <= np.max(timeArr):
        for j in range(len(finalWave)):
            if finalWave[j] >= wave[0] and finalWave[j] <= wave[-1]:
                finalFlux[i][j] = flux[i]

    #offset=np.zeros(len(finalPhase))

    out = sncosmo.TimeSeriesSource(np.array(finalPhase),
                                   np.array(finalWave),
                                   np.array(finalFlux),
                                   zero_before=False)
    return (out)
Example #6
0
    def test_combined_lenses_equal_product_of_lenses(self) -> None:
        """Test ``lsst_lenses`` filter is the product of all three lenses"""

        l1 = sncosmo.get_bandpass('lsst_lens1')
        l2 = sncosmo.get_bandpass('lsst_lens2')
        l3 = sncosmo.get_bandpass('lsst_lens3')
        l_product = l1.trans * l2.trans * l3.trans

        l_total = sncosmo.get_bandpass('lsst_lenses')
        self.assertListEqual(l_product.tolist(), l_total.trans.tolist())
Example #7
0
    def test_combined_mirrors_equal_product_of_mirrors(self) -> None:
        """Test ``lsst_mirrors`` filter is the product of all three mirrors"""

        m1 = sncosmo.get_bandpass('lsst_m1')
        m2 = sncosmo.get_bandpass('lsst_m2')
        m3 = sncosmo.get_bandpass('lsst_m3')
        m_product = m1.trans * m2.trans * m3.trans

        m_total = sncosmo.get_bandpass('lsst_mirrors')
        self.assertListEqual(m_product.tolist(), m_total.trans.tolist())
Example #8
0
def test_register():
    disp = np.array([4000., 4200., 4400., 4600., 4800., 5000.])
    trans = np.array([0., 1., 1., 1., 1., 0.])

    # create a band, register it, make sure we can get it back.
    band = sncosmo.Bandpass(disp, trans, name='tophatg')
    sncosmo.register(band)
    assert sncosmo.get_bandpass('tophatg') is band

    # test deprecated path to registry
    band = sncosmo.Bandpass(disp, trans, name='tophatg2')
    sncosmo.registry.register(band)
    assert sncosmo.get_bandpass('tophatg2') is band
Example #9
0
    def Get_SED_Restframe(self, Sed_time):

        a = 1. / (1. + self.z)
        bandpass_besselb = Bandpass(
            wavelen=sncosmo.get_bandpass('bessellB').wave,
            sb=sncosmo.get_bandpass('bessellB').trans)
        print 'before', Sed_time.wavelen, Sed_time.flambda
        #print 'there we go',Sed_time.wavelen,Sed_time.flambda
        SED_rest = Sed(wavelen=Sed_time.wavelen * a * 10.,
                       flambda=Sed_time.flambda * np.power(self.lumidist, 2.) /
                       a / 10. / HC_ERG_AA)
        print 'hello', Sed_time.wavelen * a * 10, Sed_time.flambda * np.power(
            self.lumidist, 2.) / a / 10. / HC_ERG_AA
        print 'heelp', SED_rest.wavelen, SED_rest.flambda

        SED_new = Sed(wavelen=SED_rest.wavelen / a,
                      flambda=a * SED_rest.flambda /
                      np.power(self.lumidist, 2.))
        #print 'ici',SED_new.wavelen,SED_new.flambda
        #estimate the flux in the B band bessellb

        flux_B_rest = SED_rest.calcFlux(bandpass=bandpass_besselb)
        flux_B_new = SED_new.calcFlux(bandpass=bandpass_besselb)
        #now the magnitudes (apparent and absolute)

        vega_SED = Sed()

        vega_SED.readSED_flambda('vega.txt')
        flux_vega = vega_SED.calcFlux(bandpass=bandpass_besselb)

        mag_B_rest = -2.5 * np.log10(flux_B_rest / flux_vega)
        mag_B_new = -2.5 * np.log10(flux_B_new / 3631.)

        print 'hello', len(vega_SED.wavelen), len(vega_SED.flambda), len(
            bandpass_besselb.sb), flux_vega, flux_B_rest

        bwave = bandpass_besselb.wavelen
        btrans = bandpass_besselb.sb
        vega_wave = vega_SED.wavelen
        vega_flambda = vega_SED.flambda

        mask = ((vega_wave > bwave[0]) & (vega_wave < bwave[-1]))
        d = vega_wave[mask]
        f = vega_flambda[mask]

        trans = np.interp(d, bwave, btrans)
        binw = np.gradient(d)
        ftot = np.sum(f * trans * binw)

        print 'vega flux', flux_vega, ftot
        return SED_rest, mag_B_rest, mag_B_new
Example #10
0
def mksedplot(z=1.8, color='k'):
    """ make a set of plots showing the SN Ia SED (Hsiao template)
    at various redshifts, with bandpasses overlaid.
    """
    snIa = sncosmo.Model(source='hsiao')
    snIa.set(z=z, t0=0)
    snwave = np.arange(6000., 20000., 10.)
    snflux = snIa.flux(0, snwave)
    snwave = snwave / 10000.
    snflux = 0.5 * snflux / snflux.max()

    pl.plot(snwave, snflux, color=color, ls='-')

    f105w = sncosmo.get_bandpass('f105w')
    f098m = sncosmo.get_bandpass('f098m')
    f127m = sncosmo.get_bandpass('f127m')
    f139m = sncosmo.get_bandpass('f139m')
    f153m = sncosmo.get_bandpass('f153m')

    wf127m = f127m.wave / 10000.
    wf139m = f139m.wave / 10000.
    wf153m = f153m.wave / 10000.

    pl.plot(wf127m, f127m.trans, color='darkmagenta', ls='-')
    pl.plot(wf139m, f139m.trans, color='teal', ls='-')
    pl.plot(wf153m, f153m.trans, color='darkorange', ls='-')

    intf127m = scint.interp1d(wf127m,
                              f127m.trans,
                              bounds_error=False,
                              fill_value=0)
    overlap = np.min([snflux, intf127m(snwave)], axis=0)
    pl.fill_between(snwave,
                    np.zeros(len(snwave)),
                    overlap,
                    color='darkmagenta')

    intf139m = scint.interp1d(wf139m,
                              f139m.trans,
                              bounds_error=False,
                              fill_value=0)
    overlap = np.min([snflux, intf139m(snwave)], axis=0)
    pl.fill_between(snwave, np.zeros(len(snwave)), overlap, color='teal')

    intf153m = scint.interp1d(wf153m,
                              f153m.trans,
                              bounds_error=False,
                              fill_value=0)
    overlap = np.min([snflux, intf153m(snwave)], axis=0)
    pl.fill_between(snwave, np.zeros(len(snwave)), overlap, color='darkorange')
Example #11
0
def _getWave(sedfile,bandDict,colors):
    phase,wave,flux=sncosmo.read_griddata_ascii(sedfile)
    for color in colors:
        wave1=sncosmo.get_bandpass(bandDict[color[0]]).wave
        wave2=sncosmo.get_bandpass(bandDict[color[-1]]).wave
        if wave1[0]>=wave[0] and wave1[-1]<=wave[-1]:
            if wave2[0]>=wave[0] and wave2[-1]<=wave[-1]:
                if wave2[0]>=_IRleftBound:
                    wave=wave[wave<wave2[0]]
            else:
                wave=wave[wave<wave2[0]]
        else:
            wave=wave[wave>wave1[-1]]
    return(wave)
Example #12
0
File: ml.py Project: jpierel14/sntd
    def __init__(self, times, dmags, bands, magformat='multiply', **kwargs):
        """
        Parameters
            ----------
            times: 1D or 2D :class:`~list` or :class:`~numpy.array`
                A list of the time arrays for your microlensing, with nrows=len(bands), ncols=len(dmags)
            dmags: 1D or 2D :class:`~list` or :class:`~numpy.array`
                same as times, but for microlensing magnification
            bands: :class:`~list` or :class:`~numpy.array`
                list of bands defining microlensing
        magformat : str
            Format of the magnification column.  May be ``multiply`` or ``add,``
            where ``multiply`` means the magnification column provides a
            multiplicative magnification factor, mu, so the effect is applied to
            the source as flux * mu, and ``add`` means the magnification column
            provides an additive magnitude, DeltaM=-2.5*log10(mu).
        """
        if not isinstance(bands, (list, tuple, np.ndarray)):
            bands = [bands]
        if len(bands) != len(times):
            times = [times]*len(bands)
        if len(bands) != len(dmags):
            dmags = [dmags]*len(bands)
        self.bandNorms = [getBandNorm(b) for b in bands]
        self._magformat = magformat
        self._parameters = np.array([])

        ml_list = [MicrolensingData(data={'phase': times[i], 'magnification':dmags[i]}, magformat=magformat).magnification_interpolator() for i in
                   range(len(bands))]

        self.bandwaves = [[sncosmo.get_bandpass(band).wave[0],
                           sncosmo.get_bandpass(band).wave[-1]] for band in bands]
        self.bandtimes = [[t[0], t[-1]] for t in times]
        self.wave = np.arange(np.max([self._minwave, np.min(self.bandwaves)]), np.min([self._maxwave, np.max(self.bandwaves)])+.01,
                              sncosmo.constants.MODEL_BANDFLUX_SPACING)
        self.phase = np.arange(np.min(times), np.max(times)+.01, .1)

        all_mu = np.ones((len(self.phase), len(self.wave)))
        for i in range(len(bands)):
            indsp = np.where(np.logical_and(
                self.phase >= self.bandtimes[i][0], self.phase <= self.bandtimes[i][1]))[0]
            indsw = np.where(np.logical_and(
                self.wave >= self.bandwaves[i][0], self.wave <= self.bandwaves[i][1]))[0]
            for ind in indsp:
                all_mu[ind, indsw] = ml_list[i](
                    self.phase[ind])*np.ones(len(indsw))  # /self.bandNorms[i]

        self.mu = interp2d(self.phase, self.wave, np.array(
            all_mu).T, fill_value=1, bounds_error=True)
Example #13
0
def plot_bandpass_set(setname):
    """Plot the given set of bandpasses."""

    rc("font", family="serif")

    bandpass_meta = sncosmo.spectral._BANDPASSES.get_loaders_metadata()

    fig = plt.figure(figsize=(9, 3))
    ax = plt.axes()

    nbands = 0
    for m in bandpass_meta:
        if m['filterset'] != setname:
            continue
        b = sncosmo.get_bandpass(m['name'])
        ax.plot(b.wave, b.trans, label=m['name'])
        nbands += 1

    ax.set_xlabel("Wavelength ($\\AA$)")
    ax.set_ylabel("Transmission")

    ncol = 1 + (nbands - 1) // 9  # 9 labels per column
    ax.legend(loc='upper right', frameon=False, fontsize='small', ncol=ncol)

    # Looks like each legend column takes up about 0.125 of the figure.
    # Make room for the legend.
    xmin, xmax = ax.get_xlim()
    xmax += ncol * 0.125 * (xmax - xmin)
    ax.set_xlim(xmin, xmax)
    plt.tight_layout()
    plt.show()
Example #14
0
    def _register_filters(self, force: bool = False):
        """Register filters for this survey / data release with SNCosmo

        Args:
            force: Re-register a band if already registered
        """

        data_arr = np.genfromtxt(self._filter_path, skip_header=1)
        filt_table = Table(data_arr, names=['wave', 'u', 'g', 'r', 'i', 'z'])
        filt_table['wave'] *= 10  # Convert nm to angstroms

        # Bands are already registered in sncosmo under a different name.
        # We register them using the package standardized name
        for new_band_name in self.band_names:
            built_in_name = new_band_name.split('_')[-1]

            # MEGACAMPSF are radius dependant
            if 'MEGACAMPSF' in built_in_name:
                trans = filt_table[built_in_name[-1].lower()]
                new_band = sncosmo.Bandpass(filt_table['wave'], trans)

            else:
                built_in_band = sncosmo.get_bandpass(built_in_name)
                new_band = sncosmo.Bandpass(built_in_band.wave,
                                            built_in_band.trans)

            new_band.name = new_band_name
            sncosmo.register(new_band, force=force)
Example #15
0
def plot_spectrum(wave: np.array,
                  flux: np.array,
                  figsize: Tuple[Numeric, Numeric] = (9, 3),
                  hardware_only=False) -> Tuple[plt.figure, plt.Axes]:
    """Plot a spectrum over the per-filter LSST hardware throughput

    Args:
        wave: Spectrum wavelengths in Angstroms
        flux: Flux of the spectrum in arbitrary units
        figsize: Size of the figure

    Returns:
        The matplotlib figure and axis
    """

    fig, axis = plt.subplots(figsize=figsize)

    axis.set_ylabel('Object Flux')
    axis.set_xlim(min(wave), max(wave))
    axis.set_xlabel(r'Wavelength ($\AA$)')

    twin_ax = axis.twinx()
    twin_ax.set_ylim(0, 1)
    twin_ax.set_ylabel('Bandpass Transmission', rotation=270, labelpad=15)

    prefix = 'lsst_hardware_' if hardware_only else 'lsst_total_'
    for filter_abbrev in 'ugrizy':
        filt = sncosmo.get_bandpass(f'{prefix}{filter_abbrev}')
        twin_ax.fill_between(wave, filt(wave), alpha=.3, label=filter_abbrev)
        twin_ax.plot(wave, filt(wave))

    axis.plot(wave, flux, color='k')
    return fig, axis
Example #16
0
    def test_sncosmo_registered_band_names(self):
        """Test registered bands do have the correct name"""

        self.test_class.register_filters(force=True)
        for band_name in self.test_class.band_names:
            sncosmo_band = sncosmo.get_bandpass(band_name)
            self.assertEqual(band_name, sncosmo_band.name)
Example #17
0
    def bandpass(self):
        """ Object containing the basic information associated to the bandname """
        # - No bandname ?
        if self._derived_properties["bandpass"] is not None:
            return self._derived_properties["bandpass"]

        if self.bandname is None:
            raise AttributeError("No bandname given")

        # - Should this use sncosmo
        try:
            from sncosmo import get_bandpass
            has_sncosmo = True
        except ImportError:
            warnings.warn(
                "sncosmo is not installed. Could not access the bandpass")
            has_sncosmo = False

        if has_sncosmo:
            try:
                self._derived_properties["bandpass"] = get_bandpass(
                    self.bandname)
                use_default_bandpass = False
            except:
                use_default_bandpass = True
        else:
            use_default_bandpass = True

        if use_default_bandpass:
            wave_eff = self.INFO[self.bandname]["lbda"] \
              if self.bandname in self.INFO else np.NaN
            self._derived_properties["bandpass"] = _DefaultBandpass_(
                self.bandname, wave_eff)

        return self._derived_properties["bandpass"]
Example #18
0
def plot_wsurf(pgrid, wgrid, warp, vmin=0, vmax=2, lc=None):

    import seaborn as sns
    import matplotlib.cm as cm
    import matplotlib.pyplot as plt
    """Produce a heatmap of a spectral warping surface. pgrid is the 1D
    array of phase values, wgrid is the 1d array of wavelength values,
    and warp is the 2D array of warping function values evaluated on
    the grid.

    """

    fig, ax = plt.subplots(figsize=(5, 10))
    m = cm.get_cmap('viridis')

    pgrid, wgrid = np.meshgrid(pgrid, wgrid)

    # Plot the surface.
    res = ax.pcolormesh(wgrid, pgrid, warp.T, cmap=m, vmin=vmin, vmax=vmax)

    if lc is not None:
        ax.plot([sncosmo.get_bandpass(band).wave_eff for band in lc['filter']],
                lc['mjd'], 'k+')

    ax.invert_yaxis()
    ax.set_xlabel('wavelength (AA)')
    ax.set_ylabel('phase (days)')

    fig.colorbar(res)
    return fig
Example #19
0
def calculate_lsst_fluxes(spectrum, pwv):
    """Integrate final spectrum after multiplying by rayleigh and H20 absorption

    For more information on the ``data`` argument, see ``get_stellar_spectra``.

    Args:
        spectrum (Series): Spectrum to calculate flux for
        pwv       (float): PWV in mm to calculate flux for

    Returns:
        List of flux values for the LSST ugrizy bands
    """

    transmission = v1_transmission(pwv, spectrum.index, res=5)
    spec_with_trans = spectrum * transmission

    # Integrate spectrum in each bandpass
    fluxes = []
    for band_abbrev in 'ugrizy':
        band = sncosmo.get_bandpass(f'lsst_hardware_{band_abbrev}')
        band_transmission = band(spec_with_trans.index)
        flux = trapz(band_transmission * spec_with_trans,
                     x=spec_with_trans.index)
        fluxes.append(flux)

    return fluxes
Example #20
0
    def integrate_band(self, band_name, flux_source):
        """
		Calculates the filtered integrated magnitude of the flux through a band

		:band_name: (str) the name of the band to use with sncosmo.get_bandpass
		:flux_source: (str) the source of the flux--a key of self.signal

		:returns: (float) the integrated magnitude of flux_source through 
					band_name
		"""
        band = sncosmo.get_bandpass(band_name)

        BandFunction = interp1d(band.wave, band.trans, kind='linear')
        new_bins = np.arange(band.wave[0],band.wave[-1]+self.pars.re_step\
         ,self.pars.re_step).astype(float)
        new_band = BandFunction(new_bins)
        ws = list(self.wvs)
        bs = list(new_bins)
        if bs[0] > ws[0]:
            bi = 0
            wi = ws.index(bs[0])
        else:
            wi = 0
            bi = bs.index(ws[0])
        if bs[-1] > ws[-1]:
            be = bs.index(ws[-1])
            we = ws.index(ws[-1])
        else:
            be = bs.index(bs[-1])
            we = ws.index(bs[-1])
        return np.sum(np.multiply(self.signal[flux_source][wi:we+1]\
         ,new_band[bi:be+1]))*self.pars.re_step
Example #21
0
    def filtcheck(self, bandpass, z, frac=0.75, survey="Euclid", f_index=-1):
        """
        check if the redshifted effective wavelength is redder than the effective
        wavelength of the reddest filter (yes, its a complicated sentence)
        Input is a bandpass (as a string) and redshift
        
        """
        bp_rest = sncosmo.get_bandpass(bandpass)
        if survey == "Euclid":
            effwave = self.effwave_arr
            filtarr = self.filtarr
            
        elif survey == "LSST":
            effwave = self.lsst_effwave_arr
            filtarr = self.lsst_filtarr
            
        if bp_rest.wave_eff*(1+z)  > effwave[f_index]:
            filtfun=filtarr[effwave==effwave[f_index]][0]

            #condition: check what fraction of the redshifted filter is 
            cond = bp_rest.wave*(1+z) < max(filtfun.wave[filtfun.trans > 1e-4])
            
            simp_prod = simps(bp_rest.trans, bp_rest.wave)
            if len(bp_rest.wave[cond])>10:
                simp_prod_cond = simps(bp_rest.trans[cond],bp_rest.wave[cond])
            else:
                simp_prod_cond=0
            if simp_prod_cond/simp_prod > frac:
                return 1
            else:
                print "rest-frame filter is too red for observation"
                return 0
        else:        
            return 1
def main():
        filters_bucket, zp_bucket = l.generate_buckets(3300, 9700, N_BUCKETS, inverse_microns=True)

        
        filter_eff_waves = np.array([snc.get_bandpass(zp_bucket['prefix']+f).wave_eff
                                     for f in filters_bucket]
                                    )
        
        sn12cu_excess, phases = load_12cu_excess(filters_bucket, zp_bucket)
        
        
        fig = plt.figure()
        
        for i, phase in enumerate(phases):
                print "Plotting phase {} ...".format(phase)
                
                ax = plt.subplot(2,6,i+1)
                
                plot_contour(i, phase, redden_fm, sn12cu_excess[i], filter_eff_waves,
                             EBV_GUESS, EBV_PAD, RV_GUESS, RV_PAD, STEPS, ax)
                             
        
        fig.subplots_adjust(left=0.04, bottom=0.08, right=0.95, top=0.92, hspace=.06, wspace=.1)
        fig.suptitle('SN2012CU: $E(B-V)$ vs. $R_V$ Contour Plot per Phase', fontsize=TITLE_FONTSIZE)
        plt.show()
Example #23
0
def get_color(bandpass_name):
    if bandpass_name.startswith('ztf'):
        return {
            'ztfg': 'green',
            'ztfi': 'orange',
            'ztfr': 'red'
        }[bandpass_name]
    else:
        bandpass = sncosmo.get_bandpass(bandpass_name)
        wave = bandpass.wave_eff

        if 0 < wave < 3000:
            cmap = cmap_uv
            cmap_limits = (0, 3000)
        elif 3000 <= wave <= 10000:
            cmap = cmap_opt
            cmap_limits = (3000, 10000)
        elif 10000 < wave < 1e5:
            wave = np.log10(wave)
            cmap = cmap_ir
            cmap_limits = (4, 5)
        else:
            raise ValueError('wavelength out of range for color maps')

        rgb = cmap(
            (cmap_limits[1] - wave) / (cmap_limits[1] - cmap_limits[0]))[:3]
        bandcolor = rgb2hex(rgb)

        return bandcolor
def plot_bandpass_set(setname):
    """Plot the given set of bandpasses."""

    rc("font", family="serif")

    bandpass_meta = registry.get_loaders_metadata(Bandpass)

    fig = plt.figure(figsize=(9, 3))
    ax = plt.axes()

    nbands = 0
    for m in bandpass_meta:
        if m['filterset'] != setname:
            continue
        b = get_bandpass(m['name'])
        ax.plot(b.wave, b.trans, label=m['name'])
        nbands += 1

    ax.set_xlabel("Wavelength ($\\AA$)")
    ax.set_ylabel("Transmission")

    ncol = 1 + (nbands-1) // 9  # 9 labels per column
    ax.legend(loc='upper right', frameon=False, fontsize='small',
              ncol=ncol)

    # Looks like each legend column takes up about 0.125 of the figure.
    # Make room for the legend.
    xmin, xmax = ax.get_xlim()
    xmax += ncol * 0.125 * (xmax - xmin)
    ax.set_xlim(xmin, xmax)
    plt.tight_layout()
    plt.show()
Example #25
0
def getlsstbandpassobjs(loadsncosmo=True, loadcatsim=True, plot=True):
    """
    General utility to return a list of the baseline LSST bandpasses loaded
    as catsim bandpass objects, and register them as SNCosmo bandpasses
    accessible through strings like 'LSSTu'.
    args:
        loadsncosmo: Bool, optional, defaults to True
            variable to decide whether to register the LSST bandpasses as
            SNCosmo registered bandpass objects accessible through strings
            like 'LSSTu'
        loadcatsim : Bool, optional, defaults to True
            variable to decide whether to set up catsim bandpass objects
            are return the list of u,g,r,i,z,y bandpasses
    returns:
        if loadcatsim is true, list of catsim bandpass objects corresponding
        to LSST baseline u, g, r, i, z, y filters.
        if loadcatsim is False, return is None

    Examples:

    """
    bandPassList = ['u', 'g', 'r', 'i', 'z', 'y']
    banddir = os.path.join(os.getenv('THROUGHPUTS_DIR'), 'baseline')
    lsstbands = []
    lsstbp = {}

    for band in bandPassList:
        # setup sncosmo bandpasses
        bandfname = banddir + "/total_" + band + '.dat'
        if loadsncosmo:
            # register the LSST bands to the SNCosmo registry
            # Not needed for LSST, but useful to compare independent codes
            # Usually the next two lines can be merged,
            # but there is an astropy bug currently which affects only OSX.
            numpyband = np.loadtxt(bandfname)
            sncosmoband = sncosmo.Bandpass(wave=numpyband[:, 0],
                                           trans=numpyband[:, 1],
                                           wave_unit=Unit('nm'),
                                           name='LSST' + band)
            sncosmo.registry.register(sncosmoband, force=True)
        if loadcatsim:
            # Now load LSST bandpasses for catsim
            lsstbp[band] = Bandpass()
            lsstbp[band].readThroughput(bandfname, wavelen_step=wavelenstep)
            lsstbands.append(lsstbp[band])
    fifilterfigs, filterax = plt.subplots()
    if plot:
        for band in bandPassList:
            b = sncosmo.get_bandpass('LSST' + band)
            filterax.plot(b.wave, b.trans, '-k', lw=2.0)
            filterax.set_xlabel(r'$\lambda$, ($\AA$)')
            filterax.set_ylabel(r'transmission')
            filterax.set_label(r'LSST Filter Transmission Functions')
        plt.show()

    if loadcatsim:
        return lsstbands
    else:
        return None
Example #26
0
    def test_bandflux(self):
        self.source.set(amplitude=1.0)
        f = self.source.bandflux("bessellb", 0.0)

        # Correct answer
        b = sncosmo.get_bandpass("bessellb")
        ans = np.sum(b.trans * b.wave * b.dwave) / sncosmo.models.HC_ERG_AA
        assert_approx_equal(ans, f)
Example #27
0
    def test_bandflux(self):
        self.source.set(amplitude=1.0)
        f = self.source.bandflux("bessellb", 0.)

        # Correct answer
        b = sncosmo.get_bandpass("bessellb")
        ans = np.sum(b.trans * b.wave * b.dwave) / sncosmo.models.HC_ERG_AA
        assert_approx_equal(ans, f)
Example #28
0
 def set_mag_keys(self, key_mag, key_magerr):
     #
     # add lbda def
     #
     super(SDSSCatalogue, self).set_mag_keys(key_mag, key_magerr)
     if key_mag is not None:
         bandpass = get_bandpass("sdss%s" % key_mag[0])
         self.lbda = bandpass.wave_eff
Example #29
0
 def set_mag_keys(self,key_mag,key_magerr):
     #
     # add lbda def
     #
     super(SDSSCatalogue,self).set_mag_keys(key_mag,key_magerr)
     if key_mag is not None:
         bandpass = get_bandpass("sdss%s"%key_mag[0])
         self.lbda = bandpass.wave_eff
Example #30
0
File: ml.py Project: jpierel14/sntd
def getBandNorm(band):
    band = sncosmo.get_bandpass(band)
    wave, dwave = sncosmo.utils.integration_grid(band.minwave(), band.maxwave(),
                                                 sncosmo.constants.MODEL_BANDFLUX_SPACING)
    trans = band(wave)
    f = np.ones((1, len(wave)))

    return np.sum(wave * trans * f, axis=1) * dwave / sncosmo.constants.HC_ERG_AA
Example #31
0
def _unredden(color, bands, ebv, r_v=3.1):
    """
    (Private)
    Helper function that will get a magnitude correction from reddening coefficients using the CCM 1989 (and O'Donnell 1994)parameterization.
    """
    blue = bands[color[0]]
    red = bands[color[-1]]
    if not isinstance(blue, sncosmo.Bandpass):
        blue = sncosmo.get_bandpass(blue)
    if not isinstance(red, sncosmo.Bandpass):
        red = sncosmo.get_bandpass(red)

    blue_wave = array(blue.wave_eff, float)
    blue_a_lambda = _ccm_extinction(blue_wave, ebv, r_v)
    red_wave = array(red.wave_eff, float)
    red_a_lambda = _ccm_extinction(red_wave, ebv, r_v)

    return (blue_a_lambda - red_a_lambda)
Example #32
0
def test_register():
    disp = np.array([4000., 4200., 4400., 4600., 4800., 5000.])
    trans = np.array([0., 1., 1., 1., 1., 0.])
    band = sncosmo.Bandpass(disp, trans, name='tophatg')
    sncosmo.registry.register(band)

    band2 = sncosmo.get_bandpass('tophatg')

    # make sure we can get back the band we put it.
    assert band2 is band
Example #33
0
 def __init__(self, data, name='PierelSource', version=None, tstep=1):
     super(sncosmo.Source, self).__init__()  # init for the super class
     self.name = name
     self.version = version
     self._model = {}
     self.lc = _removeDupes(data)
     wave = []
     for b in np.unique(data['band']):
         wave = np.append(wave, sncosmo.get_bandpass(b).wave)
     wave = np.sort(np.unique(wave))
     wave = np.append([.99*wave[0]], wave)
     wave = np.append(wave, [1.01*wave[-1]])
     self._wave = wave
     # self._phase=np.arange(0,np.max(data['time'])-np.min(data['time']),1)
     # self._phase=np.arange(-(np.max(data['time'])-np.min(data['time'])),np.max(data['time'])-np.min(data['time']),tstep)
     self._phase = np.arange(-800, 800, 1)
     self._parameters = np.array([1., 1., 1., 0.])
     self._tstep = tstep
     self._ts_sources = {b: _param_to_source(self, self._phase, sncosmo.get_bandpass(
         b).wave) for b in np.unique(self.lc['band'])}
Example #34
0
def read_bandpass(fname):
    """Read bandpass from two-column ASCII file containing wavelength and
    transmission in each line.
    """

    bands = sncosmo.get_bandpass(fname)
    d = {'Wavelength': bands.wave, 'Transmission': bands.trans}

    data_filter = pd.DataFrame(data=d)

    return data_filter
Example #35
0
    def test_hardware_equal_product_of_components() -> None:
        """Test ``lsst_hardware`` filter is product of all non-Atm. filters"""

        wave = np.arange(3000, 11000)
        mirrors = sncosmo.get_bandpass('lsst_mirrors')
        lenses = sncosmo.get_bandpass('lsst_lenses')
        detector = sncosmo.get_bandpass('lsst_detector')

        for band in 'ugrizy':
            band_filter = sncosmo.get_bandpass(f'lsst_filter_{band}')
            hardware = sncosmo.get_bandpass(f'lsst_hardware_{band}')
            expected_trans = mirrors(wave) * lenses(wave) * detector(
                wave) * band_filter(wave)

            # We use ``all_close`` to allow for differences due to interpolation
            np.testing.assert_allclose(
                expected_trans,
                hardware(wave),
                atol=1e-10,
                err_msg=f'Incorrect hardware transmission for {band}')
Example #36
0
def mwebv_corr(ra, dec, band):

    mwebv = get_mwebv(ra, dec)

    model_nomw = sncosmo.Model(source='salt2')
    model_mw = sncosmo.Model(source='salt2',
                             effects=[sncosmo.F99Dust()],
                             effect_names=['mw'],
                             effect_frames=['obs'])
    model_mw.set(mwebv=mwebv)
    try:
        bandpass = sncosmo.get_bandpass('ztf' + band)
    except:
        register_ztf_bandpass(band)
        bandpass = sncosmo.get_bandpass('ztf' + band)

    mag_nomw = model_nomw.bandmag(bandpass, 'ab', 0.)
    mag_mw = model_mw.bandmag(bandpass, 'ab', 0.)
    mwebv_corr = mag_mw - mag_nomw

    return mwebv_corr
Example #37
0
def plotexcess(phases, name, loader, EBV, RV, filters, zp, ax, AV=0.0, P=0.0, plotpl=False):
    
    print "Plotting",name,"..."
    
    ref = loader(phases, filters, zp)
    prefix = zp['prefix']
    filter_eff_waves = [snc.get_bandpass(prefix+f).wave_eff for f in filters]

    # get 11fe synthetic photometry at BMAX, get ref sn color excesses at BMAX
    sn11fe = l.interpolate_spectra(phases, l.get_11fe())

    if type(sn11fe) == type(()):  # convert from tuple to list if just one phase
        sn11fe = [sn11fe]
    
    for i, phase, sn11fe_phase in izip(xrange(len(phases)), phases, sn11fe):
        
        # calculate sn11fe band magnitudes
        sn11fe_mags = {f : -2.5*np.log10(sn11fe_phase[1].bandflux(prefix+f)/zp[f])
                       for f in filters}
        
        # calculate V-X colors for sn11fe
        sn11fe_colors = [sn11fe_mags['V']-sn11fe_mags[f] for f in filters]

        # make list of colors of reference supernova for given phase i
        ref_colors = [ref[i][f] for f in filters]

        # get colors excess of reference supernova compared for sn11fe
        phase_excesses = np.array(ref_colors)-np.array(sn11fe_colors)

        # convert effective wavelengths to inverse microns then plot
        eff_waves_inv = (10000./np.array(filter_eff_waves))
        mfc_color = plt.cm.gist_rainbow(abs(phase/24.))        
        plt.plot(eff_waves_inv, phase_excesses, 's', color=mfc_color,
                 ms=8, mec='none', mfc=mfc_color, alpha=0.8)


    x = np.arange(3000,10000,10)
    xinv = 10000./x
    ftz_curve = redden_fm(x, np.zeros(x.shape), EBV, RV, return_excess=True)
    plt.plot(xinv, ftz_curve, 'k--')

    if plotpl:
        # plot PL curve
        gpl_curve = redden_pl(x, np.zeros(x.shape), AV, P, return_excess=True)
        plt.plot(xinv, gpl_curve, 'k-')
    
 
    ax.set_title(name+': Color Excess at B-maximum (with '+prefix[:-1]+' filters)')
    plt.ylabel('$E(V-X)$')
    plt.xlabel('Wavelength ($1 / \mu m$)')
    plt.xlim(1.0, 3.0)
Example #38
0
def mksedplot( z=1.8, color='k' ):
    """ make a set of plots showing the SN Ia SED (Hsiao template)
    at various redshifts, with bandpasses overlaid.
    """
    snIa = sncosmo.Model( source='hsiao' )
    snIa.set( z=z, t0=0 )
    snwave = np.arange( 6000., 20000., 10. )
    snflux = snIa.flux( 0, snwave )
    snwave = snwave / 10000.
    snflux = 0.5 * snflux / snflux.max()

    pl.plot( snwave, snflux, color=color, ls='-')

    f105w = sncosmo.get_bandpass( 'f105w' )
    f098m = sncosmo.get_bandpass( 'f098m' )
    f127m = sncosmo.get_bandpass( 'f127m' )
    f139m = sncosmo.get_bandpass( 'f139m' )
    f153m = sncosmo.get_bandpass( 'f153m' )

    wf127m = f127m.wave / 10000.
    wf139m = f139m.wave / 10000.
    wf153m = f153m.wave / 10000.

    pl.plot( wf127m, f127m.trans, color='darkmagenta', ls='-')
    pl.plot( wf139m, f139m.trans, color='teal', ls='-')
    pl.plot( wf153m, f153m.trans, color='darkorange', ls='-')

    intf127m = scint.interp1d( wf127m, f127m.trans, bounds_error=False, fill_value=0 )
    overlap = np.min( [snflux, intf127m(snwave)], axis=0 )
    pl.fill_between( snwave, np.zeros(len(snwave)), overlap, color='darkmagenta' )

    intf139m = scint.interp1d( wf139m, f139m.trans, bounds_error=False, fill_value=0 )
    overlap = np.min( [snflux, intf139m(snwave)], axis=0 )
    pl.fill_between( snwave, np.zeros(len(snwave)), overlap, color='teal' )

    intf153m = scint.interp1d( wf153m, f153m.trans, bounds_error=False, fill_value=0 )
    overlap = np.min( [snflux, intf153m(snwave)], axis=0 )
    pl.fill_between( snwave, np.zeros(len(snwave)), overlap, color='darkorange' )
    def matchSNANAbandnamesinregistry():
        """
        Will have to build this along as we go, as I don't know the variety
        of naming conventions

        """

        bandPassList = ['u', 'g', 'r', 'i', 'z', 'y']
        for bandpass in bandPassList:
            band = sncosmo.get_bandpass('LSST_' + bandpass)
            band.name = bandpass
            if bandpass == 'y':
                band.name = 'Y'
            sncosmo.registry.register(band)
Example #40
0
    def is_discover(self, band, z, sys, ep, peakmag=-18.4, sig_thresh=0.3, deep='No'):

            """
            INPUTS: Filter (rest frame), Redshift, Magnitude System, Epochs of observation 
            OPTIONS: Absolute Peak magnitude

            Outputs: array of observed magnitudes that are above the detection limit

            """
            
            input_filter = filtcov(z).obs_filt(band, z)[0]
            
            try:
                fcosm = simlc().create_bandpass(input_filter[0])
            except:
                fcosm = sncosmo.get_bandpass(band)
            mod = self.set_params(band, z, peakmag=peakmag)

            
            mag_arr=mod.bandmag(fcosm, sys, ep)

            filt_arr = np.array(self.filters)
            #if the deep fields limit is set use, else use dedicated survey limits from Astier+2014
            if deep == 'Yes':
                limarr = np.array(self.limits)
            elif deep == 'No':
                limarr = np.array(self.deep_limits)
            elif deep == 'Mod':
                limarr = np.array(self.mod_limits)
            elif deep == 'Ast':
                limarr = np.array(self.ast_limits)
            #extract the limiting magnitude for the appropriate filter    
            limmag = limarr[filt_arr == input_filter[0]]
            print limmag, mag_arr

            sig_eval = self.sigma(mag_arr)
            #strict threshold on the estimated error
            ##(Do something more sophisticated??)
            disc_arr = sig_eval[sig_eval <= sig_thresh]#mag_arr[mag_arr < float(limmag[0])]
            
            
            disc_arr = list(disc_arr)
            if not disc_arr:
                print "No Observation above the threshold"
            
                return []
            else:
                print "SN is discovered by Euclid"
                return list(disc_arr)
Example #41
0
    def get_jwst_filt(self, indexx, pl='No'):
        """
        From the filters described above, select a JWST and optionally plot it
        Input: Numerical index for the array

        """
        filt_val=self.flist[indexx]
        band = sncosmo.get_bandpass(filt_val)
        
        
        if pl=='Yes':
            plt.plot(band.wave, band.trans)
            plt.show()
        else:
            return band
Example #42
0
def test_bandpass_bessell():
    """Check that Bessell bandpass definitions are scaled by inverse
    wavelength."""

    band = sncosmo.get_bandpass('bessellb')
    trans = band.trans[[4, 9, 14]]  # transmission at 4000, 4500, 5000

    # copied from file
    orig_wave = np.array([4000., 4500., 5000.])
    orig_trans = np.array([0.920, 0.853, 0.325])

    scaled_trans = orig_trans / orig_wave

    # scaled_trans should be proportional to trans
    factor = scaled_trans[0] / trans[0]
    assert_allclose(scaled_trans, factor * trans)
Example #43
0
def lsq_excess_fit(ref_excess_dict, red_law, EBV, rv_guess, filters, zp):
    prefix = zp['prefix']
    filter_eff_waves = np.array([snc.get_bandpass(prefix+f).wave_eff for f in filters])
    ref_excess = np.array([ref_excess_dict[f] for f in filters])
    
    def lsq_func(Y):
        RV = Y[0]
        ftz_curve = red_law(filter_eff_waves,
                              np.zeros(filter_eff_waves.shape),
                              -EBV, RV,
                              return_excess=True)
        return ftz_curve-ref_excess
    
    Y = np.array([rv_guess])
    valid_phases = {}
    return lsq(lsq_func, Y)
Example #44
0
def which_salt(z):
    salt_name = 'salt2'
    salt_version = '2.4'

    rest_salt_max_wav = 9200
    rest_salt_min_wav = 2000

    salt_max_wav = (1 + z) * rest_salt_max_wav
    salt_min_wav = (1 + z) * rest_salt_min_wav

    for filter in filters:
        band = sncosmo.get_bandpass(filter)
        if (band.wave[0] < salt_min_wav or band.wave[-1] > salt_max_wav):
            salt_name = 'salt2-extended'
            salt_version = '1.0'
            break
    return salt_name, salt_version
def Gen_SN():
    # Use below if on Iridis
    # source = sncosmo.SALT2Source(modeldir="/scratch/cf5g09/Monte_Carlos/salt2-4")

    ##Use below if not on iridis
    source = sncosmo.get_source('salt2', version='2.4')
    model = sncosmo.Model(source=source)
    timearray = range(100)
    mabs = -19.05  # Setting the absolute Magnitude of the Supernova
    model.set(z=0.01, t0=30)  # Setting redshift

    model.set_source_peakabsmag(mabs, 'ptf48r', 'ab',
                                cosmo=FlatLambdaCDM(H0=70, Om0=0.3))  # Fixing my peak absolute magnitude
    # model.set(x1=x_1, c=colour)

    absmag_r = model.source_peakabsmag('ptf48r', 'ab', cosmo=FlatLambdaCDM(H0=70, Om0=0.3))
    print absmag_r

    band = sncosmo.get_bandpass('ptf48r')  # Retrieving the ptf48r bandpass

    maglc = model.bandmag('ptf48r', 'ab', timearray)  # Creating a magnitude array of the lightcurve
    fluxlc = model.bandflux('ptf48r', timearray)  # Creating a flux array of the lightcurve

    model2 = model
    model2.set_source_peakabsmag(mabs, 'bessellr', 'ab',
                                 cosmo=FlatLambdaCDM(H0=70, Om0=0.3))  # Fixing my peak absolute magnitude
    # model.set(x1=x_1, c=colour)

    absmag_r = model2.source_peakabsmag('bessellr', 'ab', cosmo=FlatLambdaCDM(H0=70, Om0=0.3))
    maglc2 = model2.bandmag('bessellr', 'ab', timearray)  # Creating a magnitude array of the lightcurve

    fluxlc2 = model2.bandflux('bessellr', timearray)  # Creating a magnitude array of the lightcurve

    plt.scatter(timearray, fluxlc, color='blue', label='ptf48r')
    plt.scatter(timearray, fluxlc2, color='red', label='bessellr')

    model.bandflux('PTF48R', 30)

    # plt.gca().invert_yaxis()
    plt.title('SNTypeIa peak 30 days')
    plt.legend()
    plt.show()

    # print sn_par

    return maglc, fluxlc, timearray
def lightcurve_Ia(filter, z, x1, c, x0=None):
    """Given a filter and redshift z, generates the observed
    flux for SNe Type Ia"""
    alpha = 0.12
    beta = 3.
    mabs = -19.1 - alpha*x1 + beta*c
    zp = zero_point[filter]
    zpsys = zero_point['zpsys']

    # Checking if bandpass is outside spectral range for SALT2. If yes,
    # use salt2-extended.
    salt_name = 'salt2'
    salt_version = '2.4'

    rest_salt_max_wav = 9200
    rest_salt_min_wav = 2000

    salt_max_wav = (1 + z) * rest_salt_max_wav
    salt_min_wav = (1 + z) * rest_salt_min_wav

    band = sncosmo.get_bandpass(filter)
    if (band.wave[0] < salt_min_wav or band.wave[-1] > salt_max_wav):
        salt_name = 'salt2-extended'
        salt_version = '1.0'

    # Type Ia model
    model_Ia = sncosmo.Model(source=sncosmo.get_source(salt_name,
                                                       version=salt_version))
    if x0 is not None:
        p = {'z': z, 't0': t0, 'x0': x0, 'x1': x1,
             'c': c}
    else:
        p = {'z': z, 't0': t0, 'x1': x1, 'c': c}
        model_Ia.set(z=z)
        model_Ia.set_source_peakabsmag(mabs, 'bessellb', 'vega')
    model_Ia.set(**p)
    phase_array = np.linspace(model_Ia.mintime(), model_Ia.maxtime(), 100)
    obsflux_Ia = model_Ia.bandflux(filter, phase_array, zp=zp, zpsys=zpsys)
    keys = ['phase_array', 'obsflux']
    values = [phase_array, obsflux_Ia]
    dict_Ia = dict(zip(keys, values))
    np.savetxt('test.dat', np.c_[dict_Ia['phase_array'], dict_Ia['obsflux']])
    x0 = model_Ia.get('x0')
    return (dict_Ia, x0, salt_name, salt_version)
Example #47
0
def getlsstbandpassobjs(plot=False):
    """
    General utility to return a list of the baseline LSST bandpasses
    and register them as SNCosmo bandpasses accessible through strings 
    like 'LSSTu'.
    
    Parameters
    ----------
    plot : bool, optional, defaults to False
        plot filter functions obtained
    Returns
    -------
    None
    
    Examples
    --------
    >>> getlsstbandpassobjs() 

    """
    bandPassList = ["u", "g", "r", "i", "z", "y"]
    banddir = os.path.join(os.getenv("THROUGHPUTS_DIR"), "baseline")
    lsstbands = []
    lsstbp = {}

    for band in bandPassList:
        # setup sncosmo bandpasses
        bandfname = banddir + "/total_" + band + ".dat"
        loadsncosmo = True
        if loadsncosmo:
            # register the LSST bands to the SNCosmo registry
            # Not needed for LSST, but useful to compare independent codes
            # Usually the next two lines can be merged,
            # but there is an astropy bug currently which affects only OSX.
            numpyband = np.loadtxt(bandfname)
            sncosmoband = sncosmo.Bandpass(
                wave=numpyband[:, 0], trans=numpyband[:, 1], wave_unit=Unit("nm"), name="LSST_" + band
            )
            sncosmo.registry.register(sncosmoband, force=True)
    if plot:
        filterfigs, filterax = plt.subplots()
        for band in bandPassList:
            b = sncosmo.get_bandpass("LSST_" + band)
            filterax.plot(b.wave, b.trans, "-k", lw=2.0)
    return None
Example #48
0
def test_megacampsf_bandpass():
    """Test megacampsf position-dependent bandpasses against snfit"""
    dirname = os.path.join(os.path.dirname(__file__), "data")

    for letter in ('g', 'z'):
        for i in (0, 1):
            fname = os.path.join(
                dirname, 'snfit_filter_{:s}_{:d}.dat'.format(letter, i))

            with open(fname, 'r') as f:
                meta = read_header(f)
                wave, trans_ref = np.loadtxt(f, unpack=True)

            # sncosmo version of bandpass:
            band = sncosmo.get_bandpass('megacampsf::'+letter, meta['radius'])
            trans = band(wave)
            for i in range(len(trans)):
                print(trans_ref[i], trans[i])
            assert_allclose(trans, trans_ref, rtol=1e-5)
Example #49
0
def plot_bandpass_set(setname):
    """Plot the given set of bandpasses."""

    rc("font", family="serif")

    bandpass_meta = sncosmo.bandpasses._BANDPASSES.get_loaders_metadata()

    fig = plt.figure(figsize=(9, 3))
    ax = plt.axes()

    nbands = 0
    for m in bandpass_meta:
        if m['filterset'] != setname:
            continue
        print(m['name'])
        b = sncosmo.get_bandpass(m['name'])

        # add zeros on either side of bandpass transmission
        wave = np.zeros(len(b.wave) + 2)
        wave[0] = b.wave[0]
        wave[1:-1] = b.wave
        wave[-1] = b.wave[-1]
        trans = np.zeros(len(b.trans) + 2)
        trans[1:-1] = b.trans

        ax.plot(wave, trans, label=m['name'])
        nbands += 1

    ax.set_xlabel("Wavelength ($\\AA$)")
    ax.set_ylabel("Transmission")

    ncol = 1 + (nbands-1) // 9  # 9 labels per column
    ax.legend(loc='upper right', frameon=False, fontsize='small',
              ncol=ncol)

    # Looks like each legend column takes up about 0.125 of the figure.
    # Make room for the legend.
    xmin, xmax = ax.get_xlim()
    xmax += ncol * 0.125 * (xmax - xmin)
    ax.set_xlim(xmin, xmax)
    plt.tight_layout()
    plt.show()
def get_12cu_best_ebv_rv(red_law, filters, zp):
        filter_eff_waves = np.array([snc.get_bandpass(zp['prefix']+f).wave_eff
                                     for f in filters])
        
        sn12cu_excess, phases = load_12cu_excess(filters, zp)
        
        
        SN12CU_CHISQ_DATA = []
        for i, phase in enumerate(phases):
                print "Getting phase {} ...".format(phase)
                
                x, y, CDF, \
                best_ebv, best_rv, best_av, \
                ebv_1sig, ebv_2sig, \
                rv_1sig, rv_2sig, \
                av_1sig, av_2sig = plot_contour(i, phase, red_law, sn12cu_excess[i],
                                                filter_eff_waves, EBV_GUESS,
                                                EBV_PAD, RV_GUESS, RV_PAD, STEPS
                                                )
                
                SN12CU_CHISQ_DATA.append({'phase'   : phase,
                                          'x'       : x,
                                          'y'       : y,
                                          'CDF'     : CDF,
                                          'BEST_EBV': best_ebv,
                                          'BEST_RV' : best_rv,
                                          'BEST_AV' : best_av,
                                          'EBV_1SIG': ebv_1sig,
                                          'EBV_2SIG': ebv_2sig,
                                          'RV_1SIG' : rv_1sig,
                                          'RV_2SIG' : rv_2sig,
                                          'AV_1SIG' : av_1sig,
                                          'AV_2SIG' : av_2sig
                                          })
        
        return SN12CU_CHISQ_DATA
def test_hst_bands():
    """  check that the HST and JWST bands are accessible """
    for bandname in ['f606w', 'uvf606w', 'f125w', 'f127m', 'f115w', 'f1130w']:
        sncosmo.get_bandpass(bandname)
 def bandpass(self):
     """ bandpass object (from sncosmo) based on the bandname """
     return get_bandpass(self.bandname)
Example #53
0
 def test_set_source_peakabsmag(self):
     # Both Bandpass and str should work
     band = sncosmo.get_bandpass("desg")
     self.model.set_source_peakabsmag(-19.3, "desg", "ab")
     self.model.set_source_peakabsmag(-19.3, band, "ab")
        if art_var != None:
            pristine_11fe, obs_SN = simulate_11fe(phases_12cu, obs_12cu, no_var = True, art_var = art_var, ebv = -EBV_GUESS, rv = RV_GUESS, del_mu = del_mu)
        else:
            print 'To use artificially reddened 11fe, need to supply art_var.'
    elif select_SN == '12cu':
        obs_SN = obs_12cu
        pristine_11fe = l.nearest_spectra(phases_12cu, l.get_11fe(loadmast=False, loadptf=False))
        #pristine_11fe = l.interpolate_spectra(phases_12cu, l.get_11fe(loadmast=False, loadptf=False))




    ## Setting up tophat filters
    filters_bucket, zp_bucket, LOW_wave, HIGH_wave = l.generate_buckets(lo_wave, hi_wave, N_BUCKETS)  #, inverse_microns=True)
    filters_bucket = np.array(filters_bucket)
    filter_eff_waves = np.array([snc.get_bandpass(zp_bucket['prefix']+f).wave_eff for f in filters_bucket])

    if unfilt == True:
        FEATURES = []
    else:
        FEATURES = [(3425, 3820, 'CaII'), (3900, 4100, 'SiII'), (5640, 5900, 'SiII'),\
                          (6000, 6280, 'SiII'), (8000, 8550, 'CaII')]

    mask = filter_features(FEATURES, filter_eff_waves)
    filters_bucket = filters_bucket[mask]
    filters_bucket = filters_bucket.tolist()
   
    filter_eff_waves = filter_eff_waves[mask]

    del_wave = (HIGH_wave  - LOW_wave)/N_BUCKETS
Example #55
0
    def obs_filt(self, band ,z):
        
        """
        For a given instrument (in this case NIRCam), test which one has the greatest overlap with the redshifted rest-frame filter (i or Y in most cases)

        Input: rest frame filter, redshift of observation

        Output: Filter with greatest overlap, overlap value
        """

        #use the SNCosmo function for extracting the bandpass
        try:
            b = sncosmo.get_bandpass(band)
        except:
            b = simlc().create_bandpass(band)
            
        #obtain the wavelength and transmission values as python readable arrays
        wv = b.wave
        trans = b.trans

        #redshifted wavelength for the rest frame filter 
        wv_red = wv*(1+z)

        #integrate the total flux in the region of the redshifted filter
        tran_int = simps(trans, wv_red)
        
        #define array for filling the filters that have any wavelength overlap

        overlap_array = []
        print "Checking the filter list", self.filters

        for i in self.filters:
            
            #extract the bandpass for LSST
            bp = simlc().create_bandpass(i)
            
            tran_obs = bp.trans

            trans_thresh = 1e-4#max(tran_obs)/1e5

            wv_obs = bp.wave[bp.trans > trans_thresh]
            print wv_red[0], wv_obs[0], wv_red[-1], wv_obs[-1]
            if wv_red[0] > wv_obs[-1]:
                print "The filter being tested is", i
                print "The redshifted filter is very very red"

            elif wv_red[-1] < wv_obs[0]:
                print  "The filter being tested is", i
                print "The redshifted filter is not red enough"

            else:
                print "There is some wavelength overlap with filter", i
                overlap_array.append(i)

        print "The Euclid filters which overlap with the redshifted filter are: ", overlap_array
        
        overlap_percent=[]

        for j in overlap_array:

            bp = simlc().create_bandpass(j)
            
            trans_thresh = max(bp.trans)/1e5
            
            
            wv_obs = bp.wave[bp.trans > trans_thresh]

            cond = (wv_red > wv_obs[0] ) & (wv_red < wv_obs[-1])
            
            overlap_int=simps(trans[cond], wv_red[cond])

            overlap_percent.append([j, overlap_int*100/tran_int])

        #store the overlap percentage
        overlap_percent=np.array(overlap_percent)


        print "The percentages of the overlap are", overlap_percent

        wave_eff_arr =[]
        
        eff_wave_rf = b.wave_eff
        eff_wave_obs = eff_wave_rf *(1+z)

        for k in overlap_percent:

            if len(np.unique(overlap_percent[:,1])) < len(overlap_percent):
                
                bp = simlc().create_bandpass(k[0])
                
                wave_eff_arr.append([k[0], abs(bp.wave_eff-eff_wave_obs)])

        print "The difference between the effective wavelength for the LSST filters and the redshifted rest frame filter is:", wave_eff_arr

   

        #deal with unique and non-unique cases separately.

        if len(wave_eff_arr) > 0:
            print "In case of similar overlapping values, effective wavelengths were used to decide which filter to use"
            
            wave_eff_arr = np.array(wave_eff_arr)

    
            return wave_eff_arr[wave_eff_arr[:,1].astype('float32') == min(wave_eff_arr[:,1].astype('float32'))][0]
        else:
            print "The values for the overlap were all unique"
            return overlap_percent[overlap_percent[:,1].astype('float32')==max(overlap_percent[:,1].astype('float32')) ][0]
Example #56
0
def mk_host_figure( sn='colfax', showpdf=True ):
    """ figure showing galaxy SED fit and pdf(z) for colfaxA
    :return:
    """
    from astropy.io import ascii
    import os
    import numpy as np
    from matplotlib import pyplot as pl, ticker
    from pytools import plotsetup
    import sncosmo

    fig = plotsetup.halfpaperfig( 1, figsize=[5,3])
    ax = fig.add_subplot(1,1,1)

    datadir = "/Users/rodney/Dropbox/MEDBAND/HOSTS/SEDFITS/"

    # read in the observed  SED from the catalog
    # hostphot = ascii.read( os.path.join(datadir,'bushA_ABmag.dat'), format='fixed_width_two_line')
    hostphot = ascii.read( os.path.join(datadir,sn+'A_ABmag.dat'), format='fixed_width_two_line')
    wavedict = {}
    ibest = np.where( [ hostname.endswith('best') for hostname in hostphot['SNHOST_NAME'] ])[0][0]

    for colname in hostphot.colnames :
        if not colname.endswith( 'MAG' ) : continue
        bandname = colname.split('_')[1].lower()
        if bandname.lower() in band2wave.keys() :
            wave = band2wave[bandname]
        else :
            if not bandname.startswith('f') :
                bandname = 'bessell' + bandname
            try :
                band = sncosmo.get_bandpass( bandname )
                wave = band.wave_eff
            except :
                print("no wave_eff for %s"%bandname)
                continue
        wavedict[ colname ] = wave

        mag = hostphot[colname][ibest]
        magerr = hostphot[colname+'ERR'][ibest]
        ax.errorbar( wave, mag, magerr, marker='o', color='k', ls=' ')

    # read in the best-fit SED
    # sedfit = ascii.read( os.path.join(datadir,sn+'A_bestfit_sed.dat'), format='commented_header')
    # ax.plot( sedfit['wavelength'], sedfit['ABmag'] )

    sedfit = ascii.read( os.path.join(datadir,sn+'A_bestfit_sed.dat'), format='commented_header', header_start=-1, data_start=0)
    ax.plot( sedfit['wavelength'], sedfit['ABmag'], color='0.7', zorder=-100 )
    ax.set_xscale('log')

    xlim = [2500,90000]
    if sn=='colfax':
        ylim = [27.9,21.1]
        ax.text( 0.05, 0.92, 'GND12Col Host SED', ha='left', va='top',transform=ax.transAxes )

    elif sn=='bush':
        ylim = [30.05,26.4]
        ax.text( 0.05, 0.92, 'GSD11Bus Host SED', ha='left', va='top',transform=ax.transAxes )

    ax.set_xlim( xlim )
    ax.set_ylim( ylim )

    if showpdf :
        # read in the pdf(z)
        pdfdat = ascii.read( os.path.join(datadir,sn+'A_photoz_pdf.dat'), format='commented_header', header_start=-1, data_start=0)

        ax2 = pl.axes( [0.55,0.07,0.4,0.28] )
        ax2.plot( pdfdat['z'], pdfdat['pdf']/pdfdat['pdf'].max(), color='0.5' )
        ax2.text( 0.1, 0.85, 'P(z)', ha='left', va='top',transform=ax2.transAxes, color='0.5' )

        ax2.set_xlim( 0.01, 2.9 )
        ax2.set_ylim( 0.01, 1.1 )
        ax2.xaxis.set_tick_params( which='both', pad=0)
        ax2.xaxis.set_ticks_position('top')
        ax2.xaxis.set_ticks_position('both')
        ax2.xaxis.set_label_position('top')
        ax2.yaxis.set_ticklabels( [] )
        ax2.xaxis.set_major_locator( ticker.MultipleLocator(1.0) )
        ax2.xaxis.set_minor_locator( ticker.MultipleLocator(0.2) )
        ax2.yaxis.set_major_locator( ticker.MultipleLocator(0.5) )
        ax2.yaxis.set_minor_locator( ticker.MultipleLocator(0.1) )
        ax2.set_xlabel( 'Redshift')#, labelpad=12)

    ax.xaxis.set_ticks_position('top')
    ax.xaxis.set_ticks_position('both')
    ax.xaxis.set_label_position('top')
    ax.xaxis.set_ticklabels( [] )
    ax.set_xlabel( 'Wavelength', labelpad=7)
    ax.set_ylabel( 'AB mag')
    ax.text( 0.0, 1.02, '300 nm', ha='left', va='bottom', fontsize='small', transform=ax.transAxes)
    ax.text( 0.4, 1.02, '1 $\mu$m', ha='center', va='bottom', fontsize='small', transform=ax.transAxes)
    ax.text( 1.0, 1.02, '8 $\mu$m', ha='right', va='bottom', fontsize='small', transform=ax.transAxes)

    fig.subplots_adjust( left=0.12,bottom=0.07,right=0.95, top=0.85)
    pl.draw()
Example #57
0
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import Grid
from sncosmo import registry
from sncosmo import Bandpass, get_bandpass


bandpass_meta = registry.get_loaders_metadata(Bandpass)
filtersets = []
for m in bandpass_meta:
    if m['filterset'] not in filtersets: filtersets.append(m['filterset'])

fig = plt.figure(figsize=(9., 3. * len(filtersets)))
grid = Grid(fig, rect=111, nrows_ncols=(len(filtersets), 1),
            axes_pad=0.25, label_mode='L')

for ax, filterset in zip(grid, filtersets):

    for m in bandpass_meta:
        if m['filterset'] != filterset: continue
        b = get_bandpass(m['name'])
        ax.plot(b.wave, b.trans, label=m['name'])
    ax.set_xlabel('Angstroms')
    ax.set_ylabel('Transmission')
    ax.legend(loc='upper right')

xmin, xmax = ax.get_xlim()
ax.set_xlim(right=(xmax + 1000.))  # make room for legend
plt.tight_layout()
plt.show()