Esempio n. 1
0
    def model_for_fit(self):

        #print 'there man, to fit'
        dust = sncosmo.OD94Dust()
        self.fit_model = 'salt2-extended'
        self.fit_version = '1.0'

        source = sncosmo.get_source(self.fit_model, version=self.fit_version)

        self.SN_fit_model = sncosmo.Model(source=source,
                                          effects=[dust, dust],
                                          effect_names=['host', 'mw'],
                                          effect_frames=['rest', 'obs'])

        self.SN_fit_model.set(z=self.z)
        self.SN_fit_model.set_source_peakabsmag(self.peakAbsMagBesselB,
                                                'bessellB',
                                                'vega',
                                                cosmo=cosmology.WMAP9)

        self.lsstmwebv = EBVbase()
        self.ebvofMW = self.lsstmwebv.calculateEbv(
            equatorialCoordinates=np.array([[np.radians(self.radeg)],
                                            [np.radians(self.decdeg)]]))[0]

        self.SN_fit_model.set(mwebv=self.ebvofMW)
        self.SN_fit_model.set(mwebv=0.)
Esempio n. 2
0
def Plot_LC(lc,sn):

     dust = sncosmo.OD94Dust()
     fitted_model=sncosmo.Model(source='salt2-extended', effects=[dust, dust],
                                effect_names=['host', 'mw'],
                                effect_frames=['rest', 'obs'])
     fitted_model.set(z=sn['z'])
     fitted_model.set(t0=sn['salt2.T0'])
     fitted_model.set(x0=sn['salt2.X0'])
     fitted_model.set(x1=sn['salt2.X1'])
     fitted_model.set(c=sn['salt2.Color']) 
     
     errors={}
     errors['t0']=np.sqrt(sn['salt2.CovT0T0'])
     errors['x0']=np.sqrt(sn['salt2.CovX0X0'])
     errors['x1']=np.sqrt(sn['salt2.CovX1X1'])
     errors['c']=np.sqrt(sn['salt2.CovColorColor'])
     
     print 'Phases : first',(lc['time'][0]-sn['salt2.T0'])/(1.+sn['z']),'last',(lc['time'][-1]-sn['salt2.T0'])/(1.+sn['z'])
     """
     res, fitted_modelb = sncosmo.fit_lc(lc, fitted_model,['t0', 'x0', 'x1', 'c'],bounds={'z':(sn['z']-0.001, sn['z']+0.001)})
     
     print 'ooo',res.errors
     print 'bbb',errors
     """
     sncosmo.plot_lc(lc, model=fitted_model,pulls=True)
Esempio n. 3
0
    def __init__(self,
                 model='salt2-extended',
                 version='1.0',
                 z=0.1,
                 telescope=None,
                 Plot=False,
                 bands='ugrizy'):

        self.Plot = Plot
        #transmission=telescope.throughputs
        self.z = z
        #bands=[b[-1:] for b in np.unique(select['band'])]
        self.model = model
        self.version = version

        #print 'hello',bands,telescope.airmass
        """
        for filtre in bands:
            if telescope.airmass > 0:
                band=sncosmo.Bandpass(transmission.atmosphere[filtre].wavelen,transmission.atmosphere[filtre].sb, name='LSST::'+filtre,wave_unit=u.nm)
            else:
                band=sncosmo.Bandpass(transmission.system[filtre].wavelen,transmission.system[filtre].sb, name='LSST::'+filtre,wave_unit=u.nm) 
            sncosmo.registry.register(band, force=True)
        """
        source = sncosmo.get_source(model, version=version)
        dust = sncosmo.OD94Dust()

        self.SN_fit_model = sncosmo.Model(source=source)
        self.SN_fit_model.set(z=self.z)
Esempio n. 4
0
    def extinction(self, eb_v, dust_law, r_v=3.1):
        """ Given eb-v and r-v return the dust extinction in a particular BAND 
         It can use:
         Cardelli dust law (CCM),
         ODonneal (OD94)
         Fitzpatrick (F99)
        
        KEEP IN MIND:
        _minwave = 909.09
        _maxwave = 33333.33
         """
        if dust_law == 'OD94':
            dust = sncosmo.OD94Dust()
        elif dust_law == 'CCM':
            dust = sncosmo.CCM89Dust()
        elif dust_law == 'F99':
            dust = sncosmo.F99Dust()
        else:
            print('Add this dust law! I dont know it')

        dust.parameters = [eb_v, r_v]
        w = self.wave
        t = self.transmission
        ext = dust.propagate(w, t)
        correction_extinction = np.trapz((ext)[1:-1], w[1:-1]) / np.trapz(
            (t)[1:-1], w[1:-1])
        return correction_extinction
Esempio n. 5
0
    def Fit(self):

        #print self.table_for_fit
        t=self.table_for_fit
        select=t[np.where(np.logical_and(t['flux']/t['fluxerr']>5.,t['flux']>0.))]
        idx=select['band']!='LSST::u'
        select=select[idx]

        if self.z > 0.35:
           idx=select['band']!='LSST::g'
           select=select[idx] 


        for filtre in bands:
            band=sncosmo.Bandpass(self.transmission.atmosphere[filtre].wavelen, self.transmission.atmosphere[filtre].sb, name='LSST::'+filtre,wave_unit=u.nm)
            sncosmo.registry.register(band, force=True)
        
        source=sncosmo.get_source(self.model,version=self.version)
        dust = sncosmo.OD94Dust()
        """
        SN_fit_model=sncosmo.Model(source=source,effects=[dust, dust],
                              effect_names=['host', 'mw'],
                              effect_frames=['rest', 'obs'])
        """
        SN_fit_model=sncosmo.Model(source=source)
        SN_fit_model.set(z=self.z)
        SN_fit_model.set_source_peakabsmag(self.peakAbsMagBesselB, 'bessellB', 'vega',cosmo=self.astropy_cosmo)
        """
        lsstmwebv = EBVbase()
        ebvofMW = lsstmwebv.calculateEbv(
            equatorialCoordinates=np.array([[np.radians(self.radeg)], [np.radians(self.decdeg)]]))[0]
        
        SN_fit_model.set(mwebv=ebvofMW)
        """

        z_sim=self.z
        self.sigma_c=0.
        try:
            res, fitted_model = sncosmo.fit_lc(select, SN_fit_model,['t0', 'x0', 'x1', 'c'],bounds={'z':(z_sim-0.1, z_sim+0.1)})

            self.sigma_c=res['errors']['c']
            """
            print z_sim,self.sigma_c
            if z_sim>=0.409 and z_sim<0.411:
                sncosmo.plot_lc(select, model=fitted_model,color='k',pulls=True,errors=res.errors) 
                
                plt.show()
            """
        except (RuntimeError, TypeError, NameError):
                print 'crashed'
                for sel in select:
                    print sel
                print self.z
                self.Plot_bands(select)
                plt.show()
                print 'crashed'
Esempio n. 6
0
def mkcirclepoints(z=2.0,
                   avrange=[0.0, 2.0],
                   colorselect=[0, 1],
                   source='hsiao',
                   **plotargs):
    import numpy as np
    from matplotlib import pyplot as pl
    from mpltools import color
    from matplotlib import cm
    import sncosmo
    from sncosmohst import hstbandpasses, ccsnmodels

    # load the O'Donnell 1994 dust model
    dust = sncosmo.OD94Dust()
    sn = sncosmo.Model(source='hsiao',
                       effects=[dust],
                       effect_names=['host'],
                       effect_frames=['rest'])

    avsteps = np.arange(avrange[0], avrange[1], 0.05)
    color.cycle_cmap(length=len(avsteps), cmap=cm.jet)

    f127m, f139m, f153m = [], [], []
    f125w, f140w, f160w = [], [], []
    for av in avsteps:
        sn.set(z=z, t0=0, hostr_v=3.1, hostebv=av / 3.1)
        f127m.append(sn.bandmag('wfc3f127m', 'ab', 0.))
        f139m.append(sn.bandmag('wfc3f139m', 'ab', 0.))
        f153m.append(sn.bandmag('wfc3f153m', 'ab', 0.))
        f125w.append(sn.bandmag('wfc3f125w', 'ab', 0.))
        f140w.append(sn.bandmag('wfc3f140w', 'ab', 0.))
        f160w.append(sn.bandmag('wfc3f160w', 'ab', 0.))
    med = np.array([f127m, f139m, f153m])
    broad = np.array([f125w, f140w, f160w])
    color = med - broad
    pl.plot(color[colorselect[0]], color[colorselect[1]], **plotargs)

    colorlabel = ['F127M-F125W', 'F139M-F140W', 'F153M-F160W']
    ax = pl.gca()
    ax.set_xlabel(colorlabel[colorselect[0]])
    ax.set_ylabel(colorlabel[colorselect[1]])

    labelcolors = ['darkmagenta', 'teal', 'darkorange']

    colorlabel = ['F127M-F125W', 'F139M-F140W', 'F153M-F160W']
    ax = pl.gca()
    ax.set_xlabel(colorlabel[colorselect[0]],
                  color=labelcolors[colorselect[0]])
    ax.set_ylabel(colorlabel[colorselect[1]],
                  color=labelcolors[colorselect[1]])
Esempio n. 7
0
    def equivalentSNCosmoModel(self):
        """
        returns an SNCosmo Model which is equivalent to SNObject
        """
        snState = self.SNstate
        dust = sncosmo.OD94Dust()
        sncosmoModel = sncosmo.Model(source=snState['ModelSource'],
                                     effects=[dust, dust],
                                     effect_names=['host', 'mw'],
                                     effect_frames=['rest', 'obs'])

        sncosmoParams = self.sncosmoParamDict(snState, sncosmoModel)
        sncosmoParams['mwebv'] = snState['MWE(B-V)']
        sncosmoModel.set(**sncosmoParams)
        return sncosmoModel
Esempio n. 8
0
    def fromSNState(cls, snState):
        """
        creates an instance of SNObject with a state described by snstate.

        Parameters
        ----------
        snState: Dictionary summarizing the state of SNObject

        Returns
        -------
        Instance of SNObject class with attributes set by snstate

        Example
        -------

        """
        # Separate into SNCosmo parameters and SNObject parameters
        dust = sncosmo.OD94Dust()
        sncosmoModel = sncosmo.Model(source=snState['ModelSource'],
                                     effects=[dust, dust],
                                     effect_names=['host', 'mw'],
                                     effect_frames=['rest', 'obs'])

        sncosmoParams = cls.sncosmoParamDict(snState, sncosmoModel)

        # Now create the class
        cls = SNObject(source=snState['ModelSource'])

        # Set the SNObject coordinate properties
        # Have to be careful to not convert `None` type objects to degrees
        setdec, setra = False, False
        if snState['_ra'] is not None:
            ra = np.degrees(snState['_ra'])
            setra = True
        if snState['_dec'] is not None:
            dec = np.degrees(snState['_dec'])
            setdec = True
        if setdec and setra:
            cls.setCoords(ra, dec)

        # Set the SNcosmo parameters
        cls.set(**sncosmoParams)

        # Set the ebvofMW by hand
        cls.ebvofMW = snState['MWE(B-V)']

        return cls
Esempio n. 9
0
def Plot_LC_sncosmo(table, telescope):
    print('What will be plotted', table)
    prefix = 'LSST::'
    print(table.dtype)
    for band in 'ugrizy':
        name_filter = prefix + band
        if telescope.airmass > 0:
            bandpass = sncosmo.Bandpass(telescope.atmosphere[band].wavelen,
                                        telescope.atmosphere[band].sb,
                                        name=name_filter,
                                        wave_unit=u.nm)
        else:
            bandpass = sncosmo.Bandpass(telescope.system[band].wavelen,
                                        telescope.system[band].sb,
                                        name=name_filter,
                                        wave_unit=u.nm)
            # print('registering',name_filter)
        sncosmo.registry.register(bandpass, force=True)

    source = sncosmo.get_source('salt2-extended', version='1.0')
    dust = sncosmo.OD94Dust()
    model = sncosmo.Model(source=source)
    print('metadata', table.meta)
    model.set(z=table.meta['z'],
              c=table.meta['Color'],
              t0=table.meta['DayMax'],
              x1=table.meta['X1'])
    z = table.meta['z']
    tab = table[['flux', 'fluxerr', 'band', 'zp', 'zpsys', 'time']]
    res, fitted_model = sncosmo.fit_lc(tab,
                                       model, ['t0', 'x0', 'x1', 'c'],
                                       bounds={'z': (z - 0.001, z + 0.001)})
    print(res)
    print('jjj', fitted_model)
    sncosmo.plot_lc(data=tab, model=fitted_model, errors=res['errors'])
    plt.draw()
    plt.pause(20.)
    plt.close()
Esempio n. 10
0
    def __init__(self,
                 model='salt2-extended',
                 version=1.0,
                 telescope=None,
                 display=False,
                 bands='ugrizy'):

        self.display = display
        self.bands = bands

        # get the bands for sncosmo registration - with and without airmass

        for band in bands:
            if telescope.airmass > 0:
                band = sncosmo.Bandpass(telescope.atmosphere[band].wavelen,
                                        telescope.atmosphere[band].sb,
                                        name='LSST::' + band,
                                        wave_unit=u.nm)
            else:
                band = sncosmo.Bandpass(telescope.system[band].wavelen,
                                        telescope.system[band].sb,
                                        name='LSST::' + band,
                                        wave_unit=u.nm)
            sncosmo.registry.register(band, force=True)

        # get the source
        source = sncosmo.get_source(model, version=str(version))
        # get the dust
        dust = sncosmo.OD94Dust()

        # sn_fit_model instance
        self.SN_fit_model = sncosmo.Model(source=source)

        # name parameters
        self.parNames = dict(
            zip(['z', 't0', 'x0', 'x1', 'c'],
                ['z', 't0', 'x0', 'x1', 'color']))
Esempio n. 11
0
    def __init__(self, ra=None, dec=None, source='salt2-extended'):
        """
        Instantiate object

        Parameters
        ----------
        ra : float
            ra of the SN in degrees
        dec : float
            dec of the SN in degrees

        source : instance of `sncosmo.SALT2Source`, optional, defaults to using salt2-extended 
            source class to define the model
        """

        dust = sncosmo.OD94Dust()
        sncosmo.Model.__init__(self, source=source, effects=[dust, dust],
                               effect_names=['host', 'mw'],
                               effect_frames=['rest', 'obs'])

        # Current implementation of Model has a default value of mwebv = 0.
        # ie. no extinction, but this is not part of the API, so should not
        # depend on it, set explicitly in order to unextincted SED from
        # SNCosmo. We will use catsim extinction from `lsst.sims.photUtils`.

        self.ModelSource = source
        self.set(mwebv=0.)

        # self._ra, self._dec is initialized as None for cases where ra, dec
        # is not provided
        self._ra = None
        self._dec = None

        # ra, dec is input in degrees
        # If provided, set _ra, _dec in radians
        self._hascoords = True
        if dec is None:
            self._hascoords = False
        if ra is None:
            self._hascoords = False

        # Satisfied that coordinates provided are floats
        if self._hascoords:
            self.setCoords(ra, dec)

        # For values of ra, dec, the E(B-V) is calculated directly
        # from DustMaps
        self.lsstmwebv = EBVbase()
        self.ebvofMW = None
        if self._hascoords:
            self.mwEBVfromMaps()


        # Behavior of model outside temporal range :
        # if 'zero' then all fluxes outside the temporal range of the model
        # are set to 0.
        self._modelOutSideTemporalRange = 'zero'
        
        # SED will be rectified to 0. for negative values of SED if this
        # attribute is set to True
        self.rectifySED = True
        return
Esempio n. 12
0
def mksedplot(z=1.8, Av=0, color='k'):
    """ make a set of plots showing the SN Ia SED (Hsiao template)
    at various redshifts, with bandpasses overlaid.
    :return:
    """
    import numpy as np
    import sncosmo
    from sncosmohst import hstbandpasses, ccsnmodels
    from matplotlib import pyplot as pl
    from matplotlib import ticker
    from pytools import plotsetup
    from scipy import interpolate as scint

    # load the O'Donnell 1994 dust model
    dust = sncosmo.OD94Dust()
    snIa = sncosmo.Model(source='hsiao',
                         effects=[dust],
                         effect_names=['host'],
                         effect_frames=['rest'])
    snIa.set(z=z, t0=0, hostr_v=3.1, hostebv=Av / 3.1)
    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('wfc3f105w')
    f098m = sncosmo.get_bandpass('wfc3f098m')
    f127m = sncosmo.get_bandpass('wfc3f127m')
    f139m = sncosmo.get_bandpass('wfc3f139m')
    f153m = sncosmo.get_bandpass('wfc3f153m')

    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')
Esempio n. 13
0
def mkExtinctionDemoFigSmall(z=2.0):
    """ make a set of plots showing the SN Ia SED (Hsiao template)
    at three extinction values, with bandpasses overlaid.
    :return:
    """
    import numpy as np
    import sncosmo
    # from sncosmost import hstbandpasses, ccsnmodels
    from matplotlib import rc
    rc('text', usetex=True)
    rc('text.latex', preamble='\usepackage[usenames]{xcolor}')
    from matplotlib import pyplot as pl
    from matplotlib import ticker
    from pytools import plotsetup
    from scipy import interpolate as scint

    fig = plotsetup.fullpaperfig(1, [8, 3])

    # load the O'Donnell 1994 dust model
    dust = sncosmo.OD94Dust()
    snIa = sncosmo.Model(source='hsiao',
                         effects=[dust],
                         effect_names=['host'],
                         effect_frames=['rest'])

    ax1 = pl.gca()

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

    f125w = sncosmo.get_bandpass('f125w')
    f140w = sncosmo.get_bandpass('f140w')
    f160w = sncosmo.get_bandpass('f160w')

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

    wf125w = f125w.wave / 10000.
    wf140w = f140w.wave / 10000.
    wf160w = f160w.wave / 10000.

    # ax2 = ax1.twinx()
    ax2 = ax1
    ax2.plot(wf127m, f127m.trans, color='darkmagenta', ls='-', lw=2)
    ax2.plot(wf153m, f153m.trans, color='darkorange', ls='-', lw=2)

    ax2.plot(wf125w, f125w.trans, color='darkmagenta', ls='--', lw=2)
    ax2.plot(wf160w, f160w.trans, color='darkorange', ls='--', lw=2)

    intf127m = scint.interp1d(wf127m,
                              f127m.trans,
                              bounds_error=False,
                              fill_value=0)
    intf153m = scint.interp1d(wf153m,
                              f153m.trans,
                              bounds_error=False,
                              fill_value=0)

    colorlist1, colorlist2 = [], []
    for Av, ls, alpha in zip([2, 1, 0], [':', '--', '-'], [0.1, 0.3, 0.5]):
        snIa.set(z=z, t0=0, hostr_v=3.1, hostebv=Av / 3.1)
        colorlist1.append(
            snIa.bandmag('f127m', 'ab', 0) - snIa.bandmag('f125w', 'ab', 0))
        colorlist2.append(
            snIa.bandmag('f153m', 'ab', 0) - snIa.bandmag('f160w', 'ab', 0))

        snwave = np.arange(6000., 20000., 10.)
        snflux = snIa.flux(0, snwave)
        snwave = snwave / 10000.
        snflux = 0.12 * snflux / snflux[400]
        ax1.plot(snwave, snflux, color='k', ls=ls, lw=1, label='%.1f' % Av)
        overlap127 = np.min([snflux, intf127m(snwave)], axis=0)
        ax2.fill_between(snwave,
                         np.zeros(len(snwave)),
                         overlap127,
                         color='darkmagenta',
                         alpha=alpha)
        overlap153 = np.min([snflux, intf153m(snwave)], axis=0)
        pl.fill_between(snwave,
                        np.zeros(len(snwave)),
                        overlap153,
                        color='darkorange',
                        alpha=alpha)

    ax1.legend(loc='upper left',
               bbox_to_anchor=(0.0, 0.9),
               frameon=False,
               fontsize=11)
    ax1.text(0.08,
             0.88,
             'A$_V$',
             transform=ax1.transAxes,
             ha='left',
             va='bottom',
             fontsize=11)
    ax1.text(0.13,
             0.88,
             '$\Delta$m$_{127}$',
             color='darkmagenta',
             transform=ax1.transAxes,
             ha='left',
             va='bottom',
             fontsize=11)
    ax1.text(0.23,
             0.88,
             '$\Delta$m$_{153}$',
             color='darkorange',
             transform=ax1.transAxes,
             ha='left',
             va='bottom',
             fontsize=11)

    ax1.text(0.14,
             0.78,
             '%.3f' % colorlist1[0],
             color='darkmagenta',
             transform=ax1.transAxes,
             ha='left',
             va='bottom',
             fontsize=11)
    ax1.text(0.23,
             0.78,
             '%.3f' % colorlist2[0],
             color='darkorange',
             transform=ax1.transAxes,
             ha='left',
             va='bottom',
             fontsize=11)

    ax1.text(0.14,
             0.68,
             '%.3f' % colorlist1[1],
             color='darkmagenta',
             transform=ax1.transAxes,
             ha='left',
             va='bottom',
             fontsize=11)
    ax1.text(0.23,
             0.68,
             '%.3f' % colorlist2[1],
             color='darkorange',
             transform=ax1.transAxes,
             ha='left',
             va='bottom',
             fontsize=11)

    ax1.text(0.14,
             0.58,
             '%.3f' % colorlist1[2],
             color='darkmagenta',
             transform=ax1.transAxes,
             ha='left',
             va='bottom',
             fontsize=11)
    ax1.text(0.23,
             0.58,
             '%.3f' % colorlist2[2],
             color='darkorange',
             transform=ax1.transAxes,
             ha='left',
             va='bottom',
             fontsize=11)

    #           title=+
    #                 '\\textcolor{DarlMagenta}{W}' +
    #                 '\\textcolor{F153M-F160W')#, handlelength=0.5, numpoints=3)
    # ax1.text( 0.15,0.95,,ha='left',va='bottom')

    ax1.yaxis.set_major_locator(ticker.MultipleLocator(0.1))
    ax1.yaxis.set_minor_locator(ticker.MultipleLocator(0.05))
    ax1.xaxis.set_major_locator(ticker.MultipleLocator(0.2))
    ax1.xaxis.set_minor_locator(ticker.MultipleLocator(0.1))
    ax1.set_xlabel('wavelength ($\mu$m)')
    ax1.set_ylabel('SN Flux or Filter Transmission\n (arbitrary units)')

    ax1.set_xlim(0.6, 2.0)
    ax1.set_ylim(0.0, 0.7)
    ax1.set_yticklabels([])

    ax1.text(1.27,
             0.6,
             'F127M,F125W',
             color='darkmagenta',
             fontsize=9,
             ha='center',
             va='center')
    ax1.text(1.53,
             0.6,
             'F153M,F160W',
             color='darkorange',
             fontsize=9,
             ha='center',
             va='center')

    fig.subplots_adjust(left=0.12, right=0.95, bottom=0.18, top=0.92)
Esempio n. 14
0
    def __init__(self,
                 parameters,
                 fit=False,
                 model='salt2-extended',
                 version='1.0',
                 telescope=None,
                 ra=6.0979440,
                 dec=-1.1051600,
                 airmass=1.2,
                 X0=None,
                 dL=None):

        #time_begin=time.time()

        self.lc = []
        self.m5 = {
            'u': 23.61,
            'g': 24.83,
            'r': 24.35,
            'i': 23.88,
            'z': 23.30,
            'y': 22.43
        }
        self.radeg = np.rad2deg(ra)
        self.decdeg = np.rad2deg(dec)

        self.model = model
        self.version = version

        self.peakAbsMagBesselB = -19.0906

        if self.model == 'salt2-extended':
            model_min = 300.
            model_max = 180000.
            wave_min = 3000.
            wave_max = 11501.

        if self.model == 'salt2':
            model_min = 3400.
            model_max = 11501.
            wave_min = model_min
            wave_max = model_max

        self.wave = np.arange(wave_min, wave_max, 1.)

        self.sn_type = 'Ia'

        source = sncosmo.get_source(self.model, version=self.version)
        #self.mycosmology=FlatLambdaCDM(H0=70, Om0=0.25)
        #astropy_cosmo=FlatLambdaCDM(H0= self.mycosmology.H0, Om0=self.mycosmology.Om0)

        dust = sncosmo.OD94Dust()

        #self.transmission=Throughputs(through_dir='FAKE_THROUGH',atmos_dir='FAKE_THROUGH',atmos=False,aerosol=False)

        self.transmission = telescope.throughputs
        #self.transmission.Load_Atmosphere(airmass)
        #print 'total elapse time init a',time.time()-time_begin
        self.telescope = telescope
        """
        for band in self.bands:
            themax=np.max(self.transmission.lsst_system[band].sb)
            idx = self.transmission.lsst_system[band].sb >= 0.2*themax
            sel=self.transmission.lsst_system[band].wavelen[idx]
            print band,np.min(sel),np.max(sel)
        """
        """
        self.airmass=airmass
        if self.airmass > 0:
            self.transmission.Load_Atmosphere(airmass)
        """
        #self.lc={}
        #print 'there we go',parameters,len(parameters),parameters.dtype

        self.param = parameters
        """
        SN=sncosmo.Model(source=source,effects=[dust, dust],
                         effect_names=['host', 'mw'],
                         effect_frames=['rest', 'obs'])
        """
        self.SN = sncosmo.Model(source=source)

        self.z = self.param['z']
        if X0 is None:
            self.Cosmology()
            lumidist = self.astropy_cosmo.luminosity_distance(
                self.param['z']).value * 1.e3
            self.dL = lumidist
            #X0_snsim = self.X0_norm_snsim() / lumidist** 2
            X0 = self.X0_norm() / lumidist**2
            #print 'before alpha beta',X0
            alpha = 0.13
            beta = 3.
            X0 *= np.power(
                10.,
                0.4 * (alpha * self.param['X1'] - beta * self.param['Color']))
            self.X0 = X0

        else:
            self.X0 = X0
            self.dL = dL
        #print 'llla',X0,alpha,beta,param['X1'],param['Color'],param['z'],lumidist
        #self.X0=X0
        #print 'hello x0',X0,lumidist
        #SN=sncosmo.Model(source=source)
        self.SN.set(z=self.param['z'])
        self.SN.set(t0=self.param['DayMax'])
        self.SN.set(c=self.param['Color'])
        self.SN.set(x1=self.param['X1'])
        self.SN.set(x0=self.X0)

        #print 'total elapse time init b',time.time()-time_begin

        #self.SED={}
        #print 'sncosmo parameters',self.SN.param_names,self.SN.parameters
        lsstmwebv = EBVbase()

        ebvofMW = lsstmwebv.calculateEbv(equatorialCoordinates=np.array(
            [[np.radians(self.radeg)], [np.radians(self.decdeg)]]))[0]
        #self.SN.set(mwebv=ebvofMW)

        #self.SN.set_source_peakabsmag(self.peakAbsMagBesselB, 'bessellB', 'vega',cosmo=self.astropy_cosmo)
        if self.sn_type == 'Ia':
            self.mbsim = self.SN._source.peakmag('bessellb', 'vega')
Esempio n. 15
0
all_obs = []

for filename in filenames:
    print 'opening', filename
    pkl_file = open(filename, 'rb')
    objs = []
    while 1:
        try:
            objs.append(pkl.load(pkl_file))
        except EOFError:
            break
    all_obs.append(objs)

val = 'error_coadd_through'

dust = sncosmo.OD94Dust()
fitted_model = sncosmo.Model(source='salt2-extended',
                             effects=[dust, dust],
                             effect_names=['host', 'mw'],
                             effect_frames=['rest', 'obs'])

fitted_model_coadd = sncosmo.Model(source='salt2-extended',
                                   effects=[dust, dust],
                                   effect_names=['host', 'mw'],
                                   effect_frames=['rest', 'obs'])
# Read throughputs

transmission = Throughputs()

# Register LSST band pass (system) in sncosmo
bands = ['u', 'g', 'r', 'i', 'z', 'y']
Esempio n. 16
0
matplotlib.use('Agg')
from copy import copy
import sncosmo
import numpy as np
from bolomc import bump
from bolomc import burns
from bolomc.distributions import TruncNorm

lc = sncosmo.read_lc('../data/CSP_Photometry_DR2/SN2005elopt+nir_photo.dat',
                     format='csp')

model = sncosmo.Model(bump.BumpSource(),
                      effect_names=['host', 'mw'],
                      effect_frames=['rest', 'obs'],
                      effects=[sncosmo.OD94Dust(),
                               sncosmo.F99Dust()])

model2 = copy(model)
model2.set(
    UV_bump_amp=1.,  #blue_bump_amp=0.2,
    blue_bump_amp=-0.2,
    i1_bump_amp=0.1,
    i2_bump_amp=-0.2,
    y1_bump_amp=-0.2,
    y2_bump_amp=0.2,
    y3_bump_amp=-0.1,
    j1_bump_amp=-0.2,
    j2_bump_amp=0.2,
    h1_bump_amp=-0.2,
    h2_bump_amp=0.2,
Esempio n. 17
0
    def __init__(self,parameters,fit=False,model='salt2-extended',version='1.0',telescope=None,airmass=-1):

        self.lc=[]
        self.m5={'u':23.61,'g':24.83,'r':24.35,'i':23.88,'z':23.30,'y':22.43}
        self.radeg=np.rad2deg(6.0979440)
        self.decdeg=np.rad2deg(-1.1051600)

        self.params=Table(names=('t0','c','x1','z','ra','dec','status','fit','sn_type','sn_model','sn_version','mbsim','x0','dL'),dtype=('f8','f8','f8','f8','f8','S8','S8','f8','S8','S8','S8','f8','f8','f8'))
       
        self.table_for_fit = Table(names=('time','flux','fluxerr','band','zp','zpsys'), dtype=('f8', 'f8','f8','S7','f4','S4'))
        self.model=model
        self.version=version

        self.peakAbsMagBesselB=-19.0906

        

        if self.model == 'salt2-extended':
            model_min=300.
            model_max=180000.
            wave_min=3000.
            wave_max=11501.

        if self.model=='salt2':
            model_min=3400.
            model_max=11501.
            wave_min=model_min
            wave_max=model_max

        self.wave= np.arange(wave_min,wave_max,1.)
        
        sn_type='Ia'
        source=sncosmo.get_source(self.model,version=self.version)
        #self.mycosmology=FlatLambdaCDM(H0=70, Om0=0.25)
        #astropy_cosmo=FlatLambdaCDM(H0= self.mycosmology.H0, Om0=self.mycosmology.Om0)

        dust = sncosmo.OD94Dust()

        #self.transmission=Throughputs(through_dir='FAKE_THROUGH',atmos_dir='FAKE_THROUGH',atmos=False,aerosol=False)
        
        self.transmission=telescope.throughputs

        """
        for band in self.bands:
            themax=np.max(self.transmission.lsst_system[band].sb)
            idx = self.transmission.lsst_system[band].sb >= 0.2*themax
            sel=self.transmission.lsst_system[band].wavelen[idx]
            print band,np.min(sel),np.max(sel)
        """
        self.airmass=airmass
        if self.airmass > 0:
            self.transmission.Load_Atmosphere(airmass)

        self.lc={}
        #print 'there we go',parameters,len(parameters),parameters.dtype

        self.param=parameters
        """
        SN=sncosmo.Model(source=source,effects=[dust, dust],
                         effect_names=['host', 'mw'],
                         effect_frames=['rest', 'obs'])
        """
        self.SN=sncosmo.Model(source=source)
        
        self.z=self.param['z']
        self.Cosmology()
        lumidist=self.astropy_cosmo.luminosity_distance(self.param['z']).value*1.e3
        X0 = self.X0_norm() / lumidist** 2
        #print 'before alpha beta',X0
        alpha=0.13
        beta=3.
        X0 *= np.power(10., 0.4*(alpha*self.param['X1'] -beta*self.param['Color']))
        #print 'llla',X0,alpha,beta,param['X1'],param['Color'],param['z'],lumidist
        self.X0=X0
        #SN=sncosmo.Model(source=source)
        self.SN.set(z=self.param['z'])
        self.SN.set(t0=self.param['DayMax'])
        self.SN.set(c=self.param['Color'])
        self.SN.set(x1=self.param['X1'])
        self.SN.set(x0=self.X0)
        #self.SED={}
        print 'sncosmo parameters',self.SN.param_names,self.SN.parameters
        #lsstmwebv = EBVbase()
        """
Esempio n. 18
0
    def __init__(self,logobs,parameters,model,version):


        self.mjd_name='mjd'
        self.FWHMeff='seeing'
        peakAbsMagBesselB=-19.0906
        alpha=0.13
        beta=3.
        
        mycosmology=FlatLambdaCDM(H0=70, Om0=0.25)
        self.astropy_cosmo=FlatLambdaCDM(H0= mycosmology.H0, Om0=mycosmology.Om0)
        instrument = instruments.InstrumentModel("STANDARD")
        B = instrument.EffectiveFilterByBand("B")
        magsys = instruments.MagSys('VEGA')
        zp = magsys.ZeroPoint(B)

        print 'zeropoint for b-band',zp
        flux_at_10pc = np.power(10., -0.4 * (peakAbsMagBesselB-zp))
        fs = salt2.load_filters(['STANDARD::B'])
        mc = salt2.ModelComponents('salt2.npz')
        s = salt2.SALT2([0.], ['STANDARD::B'], mc, fs, z=0.)
        raw_model_norm = s()[0]
        # (10pc)^2 in kpc^2
        self.X0_norm = flux_at_10pc * 1.E-4 / raw_model_norm

        table_obs=ascii.read(logobs,fast_reader=False)

        colnames=[]
        sfile=open(logobs,'r')
        for line in sfile.readlines():
            if line.count('#'):
                colnames.append(line[1:].split(':')[0].strip())

        for i,val in enumerate(table_obs.colnames):
            #if val.count('#') >= 1:
            table_obs.rename_column(val, colnames[i])

        self.lc=[]

        print table_obs

        self.params=Table(names=('t0','c','x1','z','ra','dec','status','fit','sn_type','sn_model','sn_version','mbsim','x0','dL'),dtype=('f8','f8','f8','f8','f8','S8','S8','f8','S8','S8','S8','f8','f8','f8'))

        self.transmission=Throughputs()
       
        dust = sncosmo.OD94Dust()

        model=model
        version=version

        if model == 'salt2-extended':
            model_min=300.
            model_max=180000.
            wave_min=3000.
            wave_max=11501.

        if model=='salt2':
            model_min=2000.
            model_max=9200.0
            wave_min=model_min
            wave_max=model_max

        wave= np.arange(wave_min,wave_max,1.)
        
        sn_type='Ia'
        source=sncosmo.get_source(model,version=version)
        ra_field=0.
        dec_field=0.
        
        table_obs.sort(self.mjd_name)
       
        for iv,param in enumerate(parameters):
            #mysn=Simul_Fit_SN(param['DayMax'],param['Color'],param['X1'],param['z'],table_obs,ra=param['ra'],dec=param['dec'])
            table_LC=Table(names=('idSN','filter','expMJD','visitExpTime','FWHMeff','moon_frac','filtSkyBrightness','kAtm','airmass','fiveSigmaDepth','Nexp','e_per_sec','e_per_sec_err'), dtype=('i8','S7','f8', 'f8','f8','f8', 'f8','f8','i8','f8','f8','f8','f8'))


            lumidist=self.astropy_cosmo.luminosity_distance(param['z']).value*1.e3
       
            X0 = self.X0_norm / lumidist** 2
            X0 *= np.power(10., 0.4*(alpha*param['X1'] -beta*param['Color']))

            print 'X0 val',X0

            SN=sncosmo.Model(source=source,effects=[dust, dust],
                              effect_names=['host', 'mw'],
                              effect_frames=['rest', 'obs'])
            SN.set(z=param['z'])
            SN.set(t0=param['DayMax'])
            SN.set(c=param['Color'])
            SN.set(x1=param['X1'])
            SN.set(x0=X0)
            
            #SN.set_source_peakabsmag(peakAbsMagBesselB, 'bessellB', 'vega',cosmo=mycosmology)
            fluxes=10.*SN.flux(table_obs[self.mjd_name],wave)
            wavelength=wave/10. 
            wavelength=np.repeat(wavelength[np.newaxis,:], len(fluxes), 0)
            SED_time = Sed(wavelen=wavelength, flambda=fluxes)
           
            self.params.add_row((param['DayMax'],param['Color'],param['X1'],param['z'],ra_field,dec_field,'unkown',None,sn_type,model,version,SN._source.peakmag('bessellb','vega'),SN.get('x0'),lumidist))
            
            for i in range(len(SED_time.wavelen)):
                obs=table_obs[i]
                sed=Sed(wavelen=SED_time.wavelen[i],flambda=SED_time.flambda[i])
                visittime=obs['exptime']
                filtre=obs['band'][-1]
                photParams = PhotometricParameters(nexp=visittime/15.)
                e_per_sec = sed.calcADU(bandpass=self.transmission.lsst_atmos_aerosol[filtre], photParams=photParams) #number of ADU counts for expTime
                e_per_sec/=visittime/photParams.gain
                
                flux_SN=sed.calcFlux(bandpass=self.transmission.lsst_atmos_aerosol[filtre])

                FWHMeff=obs[self.FWHMeff]
                if flux_SN >0:
                    #print 'hello flux',flux_SN,fluxes[i]
                    mag_SN=-2.5 * np.log10(flux_SN / 3631.0)
                    m5_calc,snr_m5_through=self.Get_m5(filtre,mag_SN,obs['sky'],photParams,FWHMeff)
                    
                    table_LC.add_row((iv,'LSST::'+filtre,obs[self.mjd_name],visittime,FWHMeff,obs['moon_frac'],obs['sky'],obs['kAtm'],obs['airmass'],obs['m5sigmadepth'],obs['Nexp'],e_per_sec,e_per_sec/snr_m5_through))

            self.lc.append(table_LC)
Esempio n. 19
0
    def __init__(self,
                 ra,
                 dec,
                 z,
                 t0,
                 c=0,
                 x1=0,
                 peakAbsMagBesselB=-19.0906,
                 model='salt2-extended',
                 version='1.0',
                 sn_type='Ia',
                 mwdust=True):
        self.radeg = ra
        self.decdeg = dec
        self.z = z
        self.t0 = t0
        self.c = c
        self.x1 = x1
        self.peakAbsMagBesselB = peakAbsMagBesselB
        self.model = model
        self.version = version
        self.sn_type = sn_type
        self.id_SED = ''
        self.cosmology = cosmology.WMAP9
        self.cosmology = FlatLambdaCDM(H0=70, Om0=0.25)
        astropy_cosmo = FlatLambdaCDM(H0=self.cosmology.H0,
                                      Om0=self.cosmology.Om0)
        self.lumidist = astropy_cosmo.luminosity_distance(self.z).value * 1.e6
        #print 'SN Lumidist',self.lumidist,self.cosmology.H0,self.cosmology.Om0

        #print 'sntype',self.sn_type
        dust = sncosmo.OD94Dust()
        self.lsstmwebv = EBVbase()
        self.ebvofMW = self.lsstmwebv.calculateEbv(
            equatorialCoordinates=np.array([[np.radians(self.radeg)],
                                            [np.radians(self.decdeg)]]))[0]

        if self.sn_type == 'Ia':

            if version == '':
                source = sncosmo.get_source(self.model)
            else:
                source = sncosmo.get_source(self.model, version=self.version)

            self.SN = sncosmo.Model(source=source,
                                    effects=[dust, dust],
                                    effect_names=['host', 'mw'],
                                    effect_frames=['rest', 'obs'])

            #self.SN=sncosmo.Model(source=self.source)

            #self.SN=sncosmo.Model(source=self.source)

            #print 'blabla',self.SN.minwave(),self.SN.maxwave()
            lowrange = -30.
            highrange = 50.

            self.SN.set(z=self.z)
            self.SN.set(t0=self.t0)
            self.SN.set(c=self.c)
            self.SN.set(x1=self.x1)

            self.SN.set_source_peakabsmag(self.peakAbsMagBesselB,
                                          'bessellB',
                                          'vega',
                                          cosmo=self.cosmology)

            #self.SN.set(mwebv=self.ebvofMW)
            #self.SN.set(mwebv=0.)

        else:
            self.Fill_nonIa_ID()
            resu = self.Get_nonIa_Template_ID()
            #id_SED='SDSS-018109'
            #id_SED='SDSS-018457'
            """
            if id_SED != None:
                self.id_SED=id_SED
                print 'tagged',self.id_SED
                #self.SED_all_phases=self.Load_SED('NON1A/'+id_SED+'.SED')
                phase, wave, values = read_griddata_ascii('NON1A/'+id_SED+'.SED')
                print 'min max',np.min(wave),np.max(wave)
                self.SED_template = Spline2d(phase, wave, values, kx=2, ky=2)
            """

            self.model = thename = resu[0]
            self.version = resu[1]

            #print 'the choice',resu[0],resu[1]
            """
            thename='snana-2007kw' 
            theversion='1.0'
            """

            if thename != None:

                #print 'Getting the source'
                source = sncosmo.get_source(self.model, self.version)
                #print 'Getting the model'
                self.SN = sncosmo.Model(source=source,
                                        effects=[dust, dust],
                                        effect_names=['host', 'mw'],
                                        effect_frames=['rest', 'obs'])

                #print 'Setting z and T0'
                self.SN.set(z=self.z)
                self.SN.set(t0=self.t0)
                #print 'SN here',self.z,self.t0,thename,theversion
                self.SN.set_source_peakabsmag(-18.,
                                              'bessellB',
                                              'vega',
                                              cosmo=self.cosmology)
        #MW extinction
        if mwdust:
            self.SN.set(mwebv=self.ebvofMW)
            self.SN.set(mwebv=0.)

        self.model_for_fit()
Esempio n. 20
0
            qual = f.split('__')[1].split('.pkl')[0]
            ebv = float(qual.split('_')[1])
            rv = float(qual.split('_')[-1])
            nvparams.append([ebv, rv])
    dicts = []
    for samps, (ebv, rv) in zip(samples, nvparams):
        dicts.append(make_dictionaries(snname, samps, ebv, rv))
    dicts = list(chain(*dicts))
    samples = np.vstack(samples)

    pruned = samples[np.random.choice(range(len(dicts)), replace=False, size=1000)]

    model = sncosmo.Model(bump.BumpSource(),
                          effect_names=['host','mw'],
                          effect_frames=['rest','obs'],
                          effects=[sncosmo.OD94Dust(), sncosmo.F99Dust()])
    mods = [copy(model) for sample in pruned]
    for d, mod in zip(dicts, mods):
        mod.set(**d)

    bolos = [bolometric(mod) for mod in mods]
    stack = bolo.LCStack(mod.source._phase, bolos)
    ax = stack.plot()
    m2 = sncosmo.Model(sncosmo.get_source('hsiao'))
    m2.set(z=mod.get('z'), amplitude=mod.get('amplitude'))
    m3 = copy(mod)
    m3.set(**{p:0 for p in m3._param_names if 'bump' in p})
    ax.plot(m2.source._phase, bolometric(m2), ls='--')
    ax.plot(m3.source._phase, bolometric(m3), ls='-.')
    ax.figure.savefig('combined.pdf')
Esempio n. 21
0
    def __init__(self, sntype, observations=None, z_range=[1.8,2.2],
                 t0_range=[0,0], nsim=100, perfect=True,
                 Om=0.3, H0=70, filterset='hst' ):
        """ Run a monte carlo sim using sncosmo to simulate <nsim> SNe
        of the given <sntype> over the given <z_range>.

        Simulates Type Ia SNe with the SALT2 model, and CC SNe with
        the SNANA CC templates.

        Observations are done at time t=0, unless specified otherwise in
        a user-defined observations table.

        Set perfect=True for noiseless "observations" of the simulated SNe.
        :return:
        """
        from astropy import cosmology
        import sncosmo
        from numpy.random import normal, uniform, choice
        import numpy as np

        self.sntype = sntype
        self.z_range = z_range
        self.nsim = nsim
        self.perfect = perfect

        if observations is None :
            observations = mkobservationsTable( filterset=filterset )
        self.observations = observations

        # Make a list of all the unique sncosmo source models available,
        # and assign a relative probability that any given simulated SN of this
        # type (CC or Ia) belongs to that subclass
        if sntype.lower() in ['cc','ii','ibc'] :
            subClassDict  = SubClassDict_SNANA[sntype.lower()]
            subClassProbs = ccSubClassProbs[sntype.lower()]
            self.SourcenameSet = np.array( subClassDict.keys() )
            self.SubclassSet = np.array([ subClassDict[source] for source in self.SourcenameSet ])
            self.SubclassCount = np.array([ len(np.where(self.SubclassSet==subclass)[0])
                                         for subclass in self.SubclassSet ], dtype=float)
            self.SourceprobSet = np.array([ subClassProbs[subclass]
                                          for subclass in self.SubclassSet ]) / self.SubclassCount
            self.SourceprobSet /= self.SourceprobSet.sum()
        elif sntype.lower()=='ia' :
            # No sub-class divisions for SNIa
            self.SourcenameSet = np.array(['salt2-extended'])
            self.SubclassSet = np.array( ['Ia'] )
            self.SourceprobSet = np.array( [1] )
            self.SubclassCount = np.array( [1] )

        # load the O'Donnell 1994 dust model
        self.dust = sncosmo.OD94Dust()

        # Define an sncosmo SN model for each available source
        modelset = np.array([ sncosmo.Model(source=source, effects=[self.dust],
                                    effect_names=['host'], effect_frames=['rest'])
                                 for source in self.SourcenameSet ])
        # Define a cosmology
        # self.Om = Om
        # self.H0 = H0
        self.cosmo = cosmology.FlatLambdaCDM(Om0=Om, H0=H0)

        # For each simulated SN, draw random Av from distributions
        # as defined in Rodney et al 2014a :
        #   For SN Ia :  P(Av) = exp(-Av/0.33)
        #   For CC SN :  P(Av) = 4 * gauss(0.6) + exp(-Rv/1.7)
        if sntype=='Ia':
            tau,sigma,R0 = 0.33, 0, 0
        else :
            tau,sigma,R0 = 1.7, 0.6, 4
        self.Av = mcsample( pAv, nsim, tau=tau, sigma=sigma, R0=R0 )

        # For each simulated SN, draw a random Rv from a normal
        # distribution centered on 3.1 with width 0.5
        self.Rv = normal( 3.1, 0.5, nsim )
        self.Rv = np.where( self.Rv>0, self.Rv, 0.01 )

        # Convert Av and Rv to E(B-V) :
        # Rv = Av/EBV ==> EBV = Av/Rv
        self.EBV = self.Av / self.Rv

        # TODO : draw the redshifts with a metropolis-hastings sampler to match
        #  a distribution defined based on the expected SN rate

        # Disabled : uniform redshift spacing
        # zlist = np.linspace( z_range[0], z_range[1], nsim )

        # Draw a random redshift from a uniform distribution
        self.z = uniform( low=z_range[0], high=z_range[1], size=nsim )

        lightcurvelist = []
        peakabsmagRlist = []
        modelparamlist = []
        subclasslist = []
        modelindexlist = []
        sourcenamelist = []
        t0list = []
        if sntype=='Ia':
            x0list = []
            x1list = []
            clist = []
        else :
            amplitudelist = []
        for isim in range(self.nsim):
            # Randomly draw an sncosmo model from the available list, according to
            # the predefined probability list, setting the SN sub-class for this
            # simulated SN
            imodel = choice( np.arange(len(modelset)), replace=True, p=self.SourceprobSet )
            model =  modelset[imodel]
            subclass = self.SubclassSet[imodel]

            z = self.z[isim]
            EBV = self.EBV[isim]
            Rv = self.Rv[isim]

            # Set the peak absolute magnitude according to the observed
            # luminosity functions, as defined in Table 3 of Graur:2014a;
            # and set the host extinction according to the 'mid' dust model
            # of Rodney:2014a.
            if subclass == 'Ia' :
                MR = normal( -19.37, 0.47 )
            elif subclass == 'Ib' :
                MR = normal( -17.90, 0.90 )
            elif subclass == 'Ic' :
                MR = normal( -18.30, 0.60 )
            elif subclass == 'IIP' :
                MR = normal( -16.56, 0.80 )
            elif subclass == 'IIL' :
                MR = normal( -17.66, 0.42 )
            elif subclass == 'IIn' :
                MR = normal( -18.25, 1.00 )
            model.set(z=z)
            model.set_source_peakabsmag( MR, 'bessellr', 'vega', cosmo=self.cosmo)

            modelindexlist.append( imodel )
            subclasslist.append( subclass )
            peakabsmagRlist.append( MR )
            sourcenamelist.append( self.SourcenameSet[imodel] )
            if subclass =='Ia' :
                x0 = model.get('x0')
                # TODO : use bifurcated gaussians for more realistic x1,c dist'ns
                x1 = normal(0., 1.)
                c = normal(0., 0.1)
                t0 = uniform( t0_range[0], t0_range[1] )
                modelparams = {'z':z, 't0':t0, 'x0':x0, 'x1':x1, 'c':c, 'hostebv':EBV, 'hostr_v':Rv}
                t0list.append( t0 )
                x0list.append( x0 )
                x1list.append( x1 )
                clist.append( c )
                t0list.append( t0 )
            else :
                amplitude = model.get('amplitude')
                t0 = uniform( t0_range[0], t0_range[1] )
                modelparams = {'z':z, 't0':t0, 'amplitude':amplitude, 'hostebv':EBV, 'hostr_v':Rv }
                amplitudelist.append( amplitude )
                t0list.append( t0 )
            modelparamlist.append( modelparams )

            # Generate one simulated SN:
            snlc = sncosmo.realize_lcs(self.observations, model, [ modelparams ],
                                       thresh=None)#, perfect=perfect )
            lightcurvelist.append( snlc[0] )

        self.lightcurves = lightcurvelist
        self.t0 = np.array( t0list )
        self.modelindex = np.array( modelindexlist )
        self.sourcename = np.array( sourcenamelist )
        self.subclass = np.array( subclasslist )
        self.modelparam = np.array( modelparamlist )
        self.peakabsmagR = np.array( peakabsmagRlist )

        if sntype=='Ia':
            self.x0 = np.array( x0list )
            self.x1 = np.array( x1list )
            self.c  = np.array( clist )
        else :
            self.amplitude = np.array( amplitudelist )

        return
Esempio n. 22
0
def task(filename, i, j, nrv, nebv, kind='mcmc'):

    lc = sncosmo.read_lc(filename, format='csp')

    model = sncosmo.Model(bump.BumpSource(),
                          effect_names=['host', 'mw'],
                          effect_frames=['rest', 'obs'],
                          effects=[sncosmo.OD94Dust(),
                                   sncosmo.F99Dust()])

    rv_prior = burns.get_hostrv_prior(lc.meta['name'], 'gmm', sncosmo.OD94Dust)

    host_ebv, err = burns.get_hostebv(lc.meta['name'])
    ebv_prior = TruncNorm(-np.inf, np.inf, host_ebv, err)

    rv_prior, low, high = burns.get_hostrv_prior(lc.meta['name'],
                                                 'gmm',
                                                 sncosmo.OD94Dust,
                                                 retlims=True)
    host_ebv, err = burns.get_hostebv(lc.meta['name'])

    rv = np.linspace(low if low >= 0 else 0, high, nrv)[i]
    ebvlo = host_ebv - err
    ebvhi = host_ebv + err
    ebv = np.linspace(ebvlo if ebvlo >= 0 else 0, ebvhi, nebv)[j]

    model.set(z=lc.meta['zcmb'])
    model.set(mwebv=burns.get_mwebv(lc.meta['name'])[0])
    model.set(hostebv=ebv)
    model.set(hostr_v=rv)
    model.set(t0=burns.get_t0(lc.meta['name']))

    vparams = filter(lambda x: 'bump' in x, model._param_names)
    vparams += ['t0', 's']
    bounds = {b.name + "_bump_amp": (-1, 2) for b in model.source.bumps}
    #bounds['hostr_v'] = (rv_prior.mean - 0.5, rv_prior.mean + 0.5)
    #bounds['hostebv'] = (0, 0.2)
    bounds['s'] = (0, 3.)

    res, model = sncosmo.fit_lc(lc,
                                model, ['amplitude'] + vparams,
                                bounds=bounds)

    bounds['t0'] = (model.get('t0') - 2, model.get('t0') + 2)

    vparams.append('amplitude')
    bounds['amplitude'] = (0.5 * model.get('amplitude'),
                           2 * model.get('amplitude'))

    qualifier = '_ebv_%.2f_rv_%.2f' % (ebv, rv)

    if kind != 'fit':
        if kind == 'mcmc':
            result = sncosmo.mcmc_lc(lc,
                                     model,
                                     vparams,
                                     bounds=bounds,
                                     nwalkers=500,
                                     nburn=1000,
                                     nsamples=20)
        elif kind == 'nest':
            result = sncosmo.nest_lc(lc,
                                     model,
                                     vparams,
                                     bounds=bounds,
                                     method='multi',
                                     npoints=800)

        samples = result[0].samples.reshape(500, 20, -1)
        vparams = result[0].vparam_names
        plot_arg = np.rollaxis(samples, 2)

        plotting.plot_chains(plot_arg,
                             param_names=vparams,
                             filename='fits/%s_samples%s.pdf' %
                             (lc.meta['name'], qualifier))

        dicts = [
            dict(zip(vparams, samp)) for samp in samples.reshape(500 * 20, -1)
        ]
        thinned = samples.reshape(500, 20, -1)[:, [0, -1]].reshape(1000, -1)

        pickle.dump(
            samples,
            open('fits/%s_samples%s.pkl' % (lc.meta['name'], qualifier), 'wb'))

        models = [copy(result[1]) for i in range(len(thinned))]
        for d, m in zip(dicts, models):
            m.set(**d)

        fig = sncosmo.plot_lc(data=lc,
                              model=models,
                              ci=(50 - 68 / 2., 50., 50 + 68 / 2.),
                              model_label=lc.meta['name'])
        fig.savefig('fits/%s%s.pdf' % (lc.meta['name'], qualifier))

    else:

        fitres, model = sncosmo.fit_lc(lc, model, vparams, bounds=bounds)
        fig = sncosmo.plot_lc(data=lc, model=model)
        fig.savefig('fits/%s_fit%s.pdf' % (lc.meta['name'], qualifier))
Esempio n. 23
0
    def __init__(self,
                 param,
                 simu_param,
                 reference_lc=None,
                 gamma=None,
                 mag_to_flux=None,
                 dustcorr=None,
                 snr_fluxsec='interp',
                 error_model=True):
        super().__init__(param.name,
                         param.sn_parameters,
                         param.gen_parameters,
                         param.cosmology,
                         param.telescope,
                         param.SNID,
                         param.area,
                         param.x0_grid,
                         mjdCol=param.mjdCol,
                         RACol=param.RACol,
                         DecCol=param.DecCol,
                         filterCol=param.filterCol,
                         exptimeCol=param.exptimeCol,
                         nexpCol=param.nexpCol,
                         m5Col=param.m5Col,
                         seasonCol=param.seasonCol,
                         seeingEffCol=param.seeingEffCol,
                         seeingGeomCol=param.seeingGeomCol,
                         airmassCol=param.airmassCol,
                         skyCol=param.skyCol,
                         moonCol=param.moonCol,
                         salt2Dir=param.salt2Dir)
        """ SN class - inherits from SN_Object

        Parameters
        --------------
        param: dict
         parameters requested for the simulation (SN_Object)
        simu_param : dict
         parameters for the simulation:
               name: simulator name (str)
               model: model name for SN (exempla: salt2-extended) (str)
               version: version of the model (str)
        reference_lc : griddata,opt
           reference_light curves (default: None)
        gamma: griddata, opt
           reference gamma values (default: None)
        mag_to_flux: griddata, opt
           reference mag->flux values (default: None)
        snr_fluxsec: str, opt
          type of method to estimate snr and flux in pe.s-1:
          lsstsim: estimated from lsstsims tools
          interp: estimated from interpolation (default)
          all : estimated from the two above-mentioned methods

        """
        model = simu_param['model']
        version = str(simu_param['version'])
        self.model = model
        self.version = version
        self.gamma = gamma
        self.mag_to_flux = mag_to_flux
        self.snr_fluxsec = snr_fluxsec
        self.error_model = error_model

        if model == 'salt2-extended':
            model_min = 300.
            model_max = 180000.
            wave_min = 3000.
            wave_max = 11501.

        if model == 'salt2':
            model_min = 3400.
            model_max = 11501.
            wave_min = model_min
            wave_max = model_max

        self.wave = np.arange(wave_min, wave_max, 1.)

        if not self.error_model:
            source = sncosmo.get_source(model, version=version)
        else:
            SALT2Dir = 'SALT2.Guy10_UV2IR'
            self.SALT2Templates(SALT2Dir=SALT2Dir,
                                blue_cutoff=10. *
                                self.sn_parameters['blue_cutoff'])
            source = sncosmo.SALT2Source(modeldir=SALT2Dir)

        self.dustmap = sncosmo.OD94Dust()

        self.lsstmwebv = EBV.EBVbase()

        self.SN = sncosmo.Model(source=source,
                                effects=[self.dustmap, self.dustmap],
                                effect_names=['host', 'mw'],
                                effect_frames=['rest', 'obs'])

        self.SN.set(z=self.sn_parameters['z'])
        self.SN.set(t0=self.sn_parameters['daymax'] +
                    self.gen_parameters['epsilon_daymax'])
        self.SN.set(c=self.sn_parameters['color'] +
                    self.gen_parameters['epsilon_color'])
        self.SN.set(x1=self.sn_parameters['x1'] +
                    self.gen_parameters['epsilon_x1'])
        # need to correct X0 for alpha and beta
        lumidist = self.cosmology.luminosity_distance(
            self.sn_parameters['z']).value * 1.e3

        self.X0 = self.x0(lumidist)
        self.dL = lumidist
        self.SN.set(x0=self.X0)
        """
        self.SN.set_source_peakabsmag(self.sn_parameters['absmag'],
        self.sn_parameters['band'], self.sn_parameters['magsys'])

        self.X0 = self.SN.get('x0')
        """

        self.defname = dict(
            zip(['healpixID', 'pixRA', 'pixDec'],
                ['observationId', param.RACol, param.DecCol]))

        # names for metadata
        self.names_meta = [
            'RA', 'Dec', 'x0', 'epsilon_x0', 'x1', 'epsilon_x1', 'color',
            'epsilon_color', 'daymax', 'epsilon_daymax', 'z', 'survey_area',
            'healpixID', 'pixRA', 'pixDec', 'season', 'dL', 'ptime',
            'snr_fluxsec_meth', 'status', 'ebvofMW'
        ]

        self.mag_inf = 100.  # mag values to replace infs

        # band registery in sncosmo
        for band in 'grizy':
            throughput = self.telescope.atmosphere[band]
            bandcosmo = sncosmo.Bandpass(throughput.wavelen,
                                         throughput.sb,
                                         name='LSST::' + band,
                                         wave_unit=u.nm)
            sncosmo.registry.register(bandcosmo, force=True)
Esempio n. 24
0
    def __init__(self,
                 x1=-2.0,
                 color=0.2,
                 daymax=0.0,
                 blue_cutoff=380.,
                 redcutoff=800.,
                 mjdCol='observationStartMJD',
                 filterCol='filter',
                 SALT2Dir=''):

        model = 'salt2-extended'
        version = '1.0'

        source = sncosmo.get_source(model, version=version)

        if SALT2Dir != '':
            source = sncosmo.SALT2Source(modeldir=SALT2Dir)

        dustmap = sncosmo.OD94Dust()

        lsstmwebv = EBV.EBVbase()

        self.mjdCol = mjdCol
        self.filterCol = filterCol
        self.x1 = x1
        self.color = color
        self.daymax = daymax
        # SN model
        self.SN = sncosmo.Model(source=source,
                                effects=[dustmap, dustmap],
                                effect_names=['host', 'mw'],
                                effect_frames=['rest', 'obs'])

        # SN parameters
        self.SN.set(t0=daymax)
        self.SN.set(c=color)
        self.SN.set(x1=x1)

        # SN normalisation
        # cosmology
        H0 = 72.0
        Omega_m = 0.3
        Omega_l = 0.70
        w0 = -1.0
        wa = 0.0
        self.cosmo = self.cosmology(H0, Omega_m, Omega_l, w0, wa)

        # x0 normalisation
        self.x0_grid = self.x0(-19.0906)
        self.x0_from_grid = griddata(
            (self.x0_grid['x1'], self.x0_grid['color']),
            self.x0_grid['x0_norm'], (x1, color),
            method='nearest')

        # wavelength for the model
        wave_min = 3000.
        wave_max = 11501.

        self.wave = np.arange(wave_min, wave_max, 1.)

        # telescope
        self.telescope = Telescope(airmass=1.2)

        lambda_min = dict(zip('grizy', [300., 670., 300., 300., 300.]))
        # band registery in sncosmo
        for band in 'grizy':
            throughput = self.telescope.atmosphere[band]
            print(band, lambda_min[band])
            idx = throughput.wavelen <= lambda_min[band]
            # throughput.sb[idx] = 0.

            bandcosmo = sncosmo.Bandpass(throughput.wavelen,
                                         throughput.sb,
                                         name='LSST::' + band,
                                         wave_unit=u.nm)
            sncosmo.registry.register(bandcosmo, force=True)