def showcurve(sn, hml):

    
    source=sncosmo.get_source('s11-2005hm') 
    model=sncosmo.Model(source=source)
    z0 = float(redshifts[sn])
    model.set(z=z0)
    
    numofrows = len(hml[:,1])
    
    #adding flux, fluxerr, mag and magerror columns
    flux = [str(float(hml[i][1])*10**((-27-21.49)/2.5)) for i in range(numofrows)]
    hml=np.column_stack((hml,flux))
    fluxerr = [str(float(hml[i][2])*10**((-27-21.49)/2.5)) for i in range(numofrows)]
    hml=np.column_stack((hml,fluxerr))
    #adding zpsys and filter columns
    ab = ['ab' for i in range(numofrows)]
    hml=np.column_stack((hml,ab))  
    band = ['ptf48r' for i in range(numofrows)]
    hml=np.column_stack((hml,band))
    ''''
    'counts to flux eq',     hml_dat[8][1]*10**((-27-21.49)/2.5)
    'flux to mag eq',     -2.5 *np.log10(flux)-21.49
    'counts to mag eq',     -2.5 *np.log10(hml_dat[8][1]) +27
    '''
    #plt.errorbar([float(i) for i in hml[:,0]], [float(i) for i in hml[:,1]], yerr = [float(i) for i in hml[:,2]], color = 'blue', fmt = 'o')
    #plt.scatter(hml[:,0], hml[:,4], color = 'green')
    
    #plt.show()
    hml_dat=astropy.table.Table(data=hml, names=('mjd', 'counts', 'dcounts', 'zp', 'flux', 'fluxerr', 'zpsys', 'filter'), dtype=('float','float','float','float','float','float','str', 'str'))
    #print hml_dat
    
    mjdlimits = {'09': (55197-365, 55197),'10': (55197, 55562), '11': (55562, 55927), '12': (55927, 56293)}
    res, fitted_model=sncosmo.fit_lc(hml_dat, model, ['t0','amplitude'], nburn=10000, nsamples=50000, bounds={'t0':mjdlimits[sn[:2]]})
    #res, fitted_model=sncosmo.fit_lc(hml_dat, model, ['t0','amplitude'], nburn=10000, nsamples=50000, bounds={'t0':(55830,55960)})
    
   # sncosmo.plot_lc(hml_dat, model=fitted_model, model_label=source.name, errors=res.errors, color='blue', figtext=str(sn+'\n'+'Model name: s11-2005hm'+ '\n'+'Reduced Chi Squared: ')+ str(res.chisq/res.ndof), xfigsize=18)
  #  plt.show()
    
    
    
    hml2 = []
    #print hml
    #print res.parameters[1]
    j = 0; k= 0
    start = float(res.parameters[1])
    peaktime = modellimit(z0)
    for row in hml:
        datestamp = row[0]
        if peaktime + (40.0)*(1+z0) > float(datestamp)-start > peaktime - (20.0)*(1+z0) :
            hml2.append(row)
        if peaktime + (40.0)*(1+z0) > float(datestamp)-start > peaktime:
            j+=1
        if peaktime > float(datestamp)-start> peaktime-(20.0)*(1+z0):
            k+=1  
            
    if j > 0 and k > 0:
        hml2= np.array(hml2)

        ## print 'after', len(hml2)
        hml_dat2=astropy.table.Table(data=hml2, names=('mjd', 'counts', 'dcounts', 'zp', 'flux', 'fluxerr', 'zpsys', 'filter'), dtype=('float','float','float','float','float','float','str', 'str'))
        
        res2, fitted_model2=sncosmo.fit_lc(hml_dat2, model, ['t0','amplitude'], nburn=10000, nsamples=50000, bounds={'t0':mjdlimits[sn[:2]]})

        #plot model
        redchisqaured = res2.chisq/res2.ndof

        #sncosmo.plot_lc(hml_dat2, model=fitted_model2, model_label=source.name, zp = 27.00, errors=res2.errors, color='blue', figtext=str(sn+'\n'+'Model name: s11-2005hm'+ '\n'+'Reduced Chi Squared: ')+ str(res2.chisq/res2.ndof), xfigsize=18)
       # plt.show()
        
        ##print 'Done:', hml2[:,0][0], 'z:',float(res2.parameters[0]), 'Reduced chi^2:', res2.chisq/res2.ndof #'Data points:', len(hml[:,1]),' Type'+types[hml[:,0][0]]+'Model name: '+ source.name,'\n' #'Dof:', res.ndof
        return  redchisqaured, res2.parameters, z0, hml2 #, res.errors['amplitude']]
    else:
        print sn, 'didn\'t make the cut'
    def model_IIP_nugent(self):
        """
        """
        sncosmo.get_source('nugent-sn2p', version='1.2')
        p, w, f = sncosmo.read_griddata_ascii(
            os.path.join(sncosmo.builtins.get_cache_dir(),
                         'sncosmo/models/nugent/sn2p_flux.v1.2.dat')
        )
        mask = (p < 130)

        return sncosmo.Model(source=sncosmo.TimeSeriesSource(p[mask], w, f[mask]),
                             effects=[sncosmo.CCM89Dust()],
                             effect_names=['host'],
                             effect_frames=['rest'])
    def model_Ia_hsiao(self):
        """
        """
        sncosmo.get_source('hsiao', version='3.0')
        p, w, f = sncosmo.read_griddata_fits(
            os.path.join(sncosmo.builtins.get_cache_dir(),
                         'sncosmo/models/hsiao/Hsiao_SED_V3.fits')
        )

        return sncosmo.Model(
            source=sncosmo.StretchSource(p, w, f, name='hsiao-stretch'),
            effects=[sncosmo.CCM89Dust()],
            effect_names=['host'],
            effect_frames=['rest']
        )
def finalfitcurve(x, source_name, hml):
    try:
        source = sncosmo.get_source(source_name)
        model = sncosmo.Model(source=source)

        #fit to model
        z0 = float(spec_z(x[:-7]))
        hml_dat = astropy.table.Table(
            data=hml,
            names=('ptfname', 'time', 'magnitude', 'mag_err', 'flux',
                   'flux_err', 'zp_new', 'zp', 'ra', 'dec', 'zpsys', 'filter'),
            dtype=('str', 'float', 'float', 'float', 'float', 'float', 'float',
                   'float', 'float', 'float', 'str', 'str'))
        res, fitted_model = sncosmo.fit_lc(hml_dat,
                                           model, ['z', 't0', 'amplitude'],
                                           bounds={'z': (z0, z0 + 0.0001)},
                                           nburn=10000,
                                           nsamples=50000)
        #The following excludes data with not enough distribution..
        ##Ensuring at least 2 data points on either side of peak.
        limit = modellimit(source_name, x[:-7], res.parameters[1])
        j = 0
        k = 0
        for i in hml[:, 1]:
            if float(i) > float(limit[2]):
                j += 1
            else:
                k += 1
        if j >= 2 and k >= 2:
            return np.array([
                float(res.chisq / res.ndof), hml[:, 0][0], source_name
            ]), hml  #returns reduced chi squared, sn name and model name.

    except ValueError:
        print 'error'
Exemple #5
0
def load_dm15(name=None, version=None):
    # hack to get hsiao template arrays
    hsiao = sncosmo.get_source('hsiao')
    phase = hsiao._phase
    wave = hsiao._wave
    flux = hsiao.flux(phase, wave)
    return DM15Source(phase, wave, flux, name=name, version=version)
def showcurve(sn, source_name):
    try:
        hml=np.load('/home/fcm1g13/Documents/Supernova/CorecollapseLC/ccdata/' + sn)    
    
        source=sncosmo.get_source(source_name) 
        model=sncosmo.Model(source=source) 
    # print len(hml[:,1]), 'data points'
    
        # Adding zpsys and filter columns. zp system used is ab and filter used is ptf48r
        ab = np.zeros(len(hml[:, 1]), dtype='|S2')
        band = np.zeros(len(hml[:, 1]), dtype='|S6')
        for i in range(len(ab)):
            ab[i] = 'ab'
            band[i] = 'ptf48r'
        hml = np.column_stack((hml, ab, band))

        hml_dat=astropy.table.Table(data=hml, names=('ptfname', 'time', 'magnitude', 'mag_err', 'flux', 'flux_err', 'zp_new', 'zp', 'ra', 'dec', 'zpsys', 'filter'), dtype=('str','float','float','float','float','float','float','float','float','float','str', 'str'))
        
        ###fitting model
        res, fitted_model=sncosmo.fit_lc(hml_dat, model, ['z','t0','amplitude'], bounds={'z':(0.005,0.35)}, nburn=10000, nsamples=50000)
            #print 'peak', float(res.parameters[1])
        print res                              
        sncosmo.plot_lc(hml_dat, model=fitted_model, errors=res.errors, color='blue', figtext=str(hml[:,0][0]+' Type'+types[hml[:,0][0]]+'\n'+'Model name: '+ source.name), xfigsize=10)
        #plt.clfig()
        plt.show()

        #print #'### Parameters ###'
        #print 'SN',str(hml[:,0][0]), 'z:',float(res.parameters[0])# float(res.errors['z']), float(res.parameters[1]), float(res.errors['t0']),float(res.parameters[2]), float(res.errors['x0']),  float(res.parameters[3]), float(res.errors['x1']), float(res.parameters[4]), float(res.errors['c']), float(hml[:,8][0]), float(hml[:,9][0])
        print 'Done:', hml[:,0][0], 'z:',float(res.parameters[0]), 'Reduced chi^2:', res.chisq/res.ndof,#'Data points:', len(hml[:,1]),' Type'+types[hml[:,0][0]]+'Model name: '+ source.name,'\n' #'Dof:', res.ndof

    except ValueError:
        sn, source_name, 'cannot be plotted'
Exemple #7
0
def test_salt2source_rcov_vs_snfit():
    dirname = os.path.join(os.path.dirname(__file__), "data")

    # read parameters and times
    f = open(os.path.join(dirname, "salt2_rcov_params_times.dat"), 'r')
    meta = read_header(f)
    times = np.loadtxt(f)
    f.close()

    # initialize model and set parameters
    source = sncosmo.get_source("salt2", version="2.4")  # fixed version
    model = sncosmo.Model(source)
    model.set(z=meta['Redshift'],
              t0=meta['DayMax'],
              x0=meta['X0'],
              x1=meta['X1'],
              c=meta['Color'])

    # Test separate bands separately, as thats how they're written to files.
    # (And cross-band covariance is zero.)
    for band in ('SDSSg', 'SDSSr', 'SDSSi'):
        fname = os.path.join(dirname, "salt2_rcov_snfit_{}.dat".format(band))
        ref = np.loadtxt(fname, skiprows=1)

        rcov = model._bandflux_rcov(band, times)
        assert_allclose(ref, rcov, rtol=6.e-5)
Exemple #8
0
def test_salt2source_timeseries_vs_snfit():
    """Test timeseries output from SALT2Source vs pregenerated timeseries
    from snfit (SALT2 software)."""

    source = sncosmo.get_source("salt2", version="2.4")  # fixed version
    model = sncosmo.Model(source)

    dirname = os.path.join(os.path.dirname(__file__), "data")

    for fname in ['salt2_timeseries_1.dat',
                  'salt2_timeseries_2.dat',
                  'salt2_timeseries_3.dat',
                  'salt2_timeseries_4.dat']:
        f = open(os.path.join(dirname, fname), 'r')
        meta = read_header(f)
        time, wave, fluxref = sncosmo.read_griddata_ascii(f)
        f.close()

        # The output from snfit's Salt2Model.SpectrumFlux() has a
        # different definition than sncosmo's model.flux() by a factor
        # of a^2. snfit's definition is the rest-frame flux but at a
        # blue-shifted wavelength.  (There is no correction for photon
        # energy or time dilation. These corrections are made in the
        # integration step.)
        a = 1. / (1. + meta['Redshift'])
        fluxref *= a**2

        model.set(z=meta['Redshift'], t0=meta['DayMax'], x0=meta['X0'],
                  x1=meta['X1'], c=meta['Color'])
        flux = model.flux(time, wave)

        # super good agreement!
        assert_allclose(flux, fluxref, rtol=1e-13)
def fitcurve(x, source_name, hml):
    try:
        source=sncosmo.get_source(source_name) 
        model=sncosmo.Model(source=source) 
        
        #adding zpsys and filter columns
        ab=np.zeros(len(hml[:,1]), dtype='|S2')
        for i in range(len(ab)):
            ab[i]='ab'
        hml=np.column_stack((hml,ab))   
        band=np.zeros(len(hml[:,1]), dtype='|S6')
        for i in range(len(band)):
            band[i]='ptf48r'
        hml=np.column_stack((hml,band))
        #fit to model
        z0 = float(spec_z(x[:-7]))
        hml_dat=astropy.table.Table(data=hml, names=('ptfname', 'time', 'magnitude', 'mag_err', 'flux', 'flux_err', 'zp_new', 'zp', 'ra', 'dec', 'zpsys', 'filter'), dtype=('str','float','float','float','float','float','float','float','float','float','str', 'str'))
        res, fitted_model=sncosmo.fit_lc(hml_dat, model, ['z','t0','amplitude'], bounds={'z':(z0,z0 + 0.0001)}, nburn=10000, nsamples=50000)
        
        #The following excludes data points not in the range of the model and data sets with fewer than 4 data points
        limit = modellimit(source_name, x[:-7], res.parameters[1])
        hml2 = []
        for j in range(len(hml[:,1])):
            datapoint = hml [:,1][j]
            if (res.parameters[1]- limit[0])< float(datapoint) < (res.parameters[1]+limit[1]):
                hml2.append(hml[j]) 
        hml2 = np.array(hml2)
        if len(hml2)>3:
            
            return finalfitcurve(x, source_name, hml2) 
               
        
    except ValueError:
        print 'error'  
Exemple #10
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.)
Exemple #11
0
    def fitting(self, sn_name):
        """Fit the light curve for a SN (data as Astropy table) using the model
        SALT2 z and mwebv are setted, it returns the values of the SALT2 parameters
        and their errors. We plot the fit on the notebook.
        """
        self.read(sn_name)
        self.source = sncosmo.get_source('salt2', version='2.4')
        dust = sncosmo.CCM89Dust()
        self.model = sncosmo.Model(source=self.source,
                                   effects=[dust],
                                   effect_names=['mw'],
                                   effect_frames=['obs'])
        self.model.set(mwebv=self.mwebv)
        self.model.set(z=self.zhl)
        #self.model.set(c=0)

        try:
            res, fitted_model = sncosmo.fit_lc(self.data,
                                               self.model,
                                               ['t0', 'x1', 'c', 'x0'],
                                               phase_range=(-15, 45))
            #res, fitted_model = sncosmo.fit_lc(self.data, self.model, ['t0','x1', 'x0'])
            #return res, fitted_model
        except:
            #except RuntimeError:
            print('Fail:', sn_name)
            res, fitted_model = 'fit fail', np.nan

        return res, fitted_model
Exemple #12
0
def test_sugarsource():
    """Test timeseries output from SUGARSource vs pregenerated timeseries
    from the original files."""

    source = sncosmo.get_source("sugar")
    model = sncosmo.Model(source)

    q1 = [-1, 0, 1, 2]
    q2 = [1, 0, -1, -2]
    q3 = [-1, 1, 0, -2]
    Av = [-0.1, 0, 0.2, 0.5]
    q0 = [10**(-0.4 * 34), 10**(-0.4 * 33), 10**(-0.4 * 38), 10**(-0.4 * 42)]

    time = np.linspace(-5, 30, 10)
    wave = np.linspace(4000, 8000, 10)

    for i in range(len(q1)):

        fluxref = sugar_model(q0=q0[i],
                              q1=q1[i],
                              q2=q2[i],
                              q3=q3[i],
                              Av=Av[i],
                              phase=time,
                              wave=wave)

        model.set(z=0, t0=0, q0=q0[i], q1=q1[i], q2=q2[i], q3=q3[i], Av=Av[i])
        flux = model.flux(time, wave)
        assert_allclose(flux, fluxref, rtol=1e-13)
Exemple #13
0
    def fitting_z(self, sn_name):
        """SALT2 fit using SNCOSMO for the SN without => z free parameter of the
        fit
        """
        self.read(sn_name)
        self.source = sncosmo.get_source('salt2', version='2.4')
        dust = sncosmo.CCM89Dust()
        self.model = sncosmo.Model(source=self.source,
                                   effects=[dust],
                                   effect_names=['mw'],
                                   effect_frames=['obs'])
        self.model.set(mwebv=self.mwebv)
        #self.model.set(c=0)

        try:
            results, fit_model = sncosmo.fit_lc(self.data, self.model,
                                                ['t0', 'x1', 'c', 'x0'])
            #res, fitted_model = sncosmo.fit_lc(self.data, self.model, ['t0','x1', 'x0'])
            #return res, fitted_model
        except:
            #except RuntimeError:
            print('Fail:', sn_name)
            results, fit_model = 'fit fail', np.nan

        return results, fit_model
def lightcurve_Ibc(filter, z, hostebv_Ibc):
    """Given a filter, redshift z at given phase, generates the observed
    magnitude for SNe Type Ibc"""
    zp = zero_point[filter]
    zpsys = zero_point['zpsys']
    model_Ibc = ['s11-2005hl', 's11-2005hm', 's11-2006fo', 'nugent-sn1bc',
                 'nugent-hyper', 's11-2006jo', 'snana-2004fe',
                 'snana-2004gq', 'snana-sdss004012', 'snana-2006fo',
                 'snana-sdss014475', 'snana-2006lc', 'snana-04d1la',
                 'snana-04d4jv', 'snana-2004gv', 'snana-2006ep',
                 'snana-2007y', 'snana-2004ib', 'snana-2005hm',
                 'snana-2006jo', 'snana-2007nc']
    obsflux_Ibc = []
    phase_arrays = []
    for i in model_Ibc:
        model_i = sncosmo.Model(source=sncosmo.get_source(i), effects=[dust],
                                effect_names=['host'], effect_frames=['rest'])
        mabs = -17.56
        model_i.set(z=z)
        phase_array_i = np.linspace(model_i.mintime(), model_i.maxtime(), 100)
        model_i.set_source_peakabsmag(mabs, 'bessellb', 'ab')
        p_core_collapse = {'z': z, 't0': t0, 'hostebv': hostebv_Ibc,
                           'hostr_v': hostr_v}
        model_i.set(**p_core_collapse)
        phase_arrays.append(phase_array_i)
        obsflux_i = model_i.bandflux(filter, phase_array_i, zp, zpsys)
        obsflux_Ibc.append(obsflux_i)
    keys = model_Ibc
    values = []
    for i, item in enumerate(model_Ibc):
        values.append([obsflux_Ibc[i], phase_arrays[i]])
    dict_Ibc = dict(zip(keys, values))
    return (dict_Ibc)
Exemple #15
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)
def select_model(x):
    # Load file containing data set
    hml = np.load(os.path.abspath('') + '/ccdata/' + x)
    # print len(hml[:,1]), 'data points'             #number of rows and therefore data points

    # Adding zpsys and filter columns. zp system used is ab and filter used is ptf48r
    ab = np.zeros(len(hml[:, 1]), dtype='|S2')
    band = np.zeros(len(hml[:, 1]), dtype='|S6')
    for i in range(len(ab)):
        ab[i] = 'ab'
        band[i] = 'ptf48r'
    hml = np.column_stack((hml, ab, band))

    # Converting into a table using astropy with titles: ptfname, time,
    # magnitude, mag_err, flux, flux_err, zp_new, zp, ra, dec, zpsys and filter
    hml_dat = astropy.table.Table(
        data=hml,
        names=('ptfname', 'time', 'magnitude', 'mag_err', 'flux', 'flux_err',
               'zp_new', 'zp', 'ra', 'dec', 'zpsys', 'filter'),
        dtype=('str', 'float', 'float', 'float', 'float', 'float', 'float',
               'float', 'float', 'float', 'str', 'str'))
    #sn types are Ib, Ib/c, Ic, Ic-BL, IIP
    sn_type = types[hml[:, 0][0]]

    # Selecting only Type II supernovae
    if sn_type[1] == 'I':
        # Selecting model
        source = sncosmo.get_source('s11-2004hx', version='1.0')
        fit_curve(hml_dat, source, hml)

    # Selecting only Type Ic supernovae
    elif sn_type[1] == 'c':
        # Selecting model
        source = sncosmo.get_source('snana-2004fe', version='1.0')
        fit_curve(hml_dat, source, hml)

    # Selecting TypeIb sn only
    elif len(sn_type) == 2 and (sn_type[1] != 'b'):
        # Selecting model
        source = sncosmo.get_source('snana-2006ep', version='1.0')
        fit_curve(hml_dat, source, hml)

    # Selecting TypeIbc sn only
    elif len(sn_type) > 2 and (sn_type[1] != 'b'):
        # Selecting model
        source = sncosmo.get_source('nugent-sn1bc', version='1.1')
        fit_curve(hml_dat, source, hml)
def select_model(x):
    # Load file containing data set
    hml = np.load(os.path.abspath('') + '/ccdata/' + x)
    # print len(hml[:,1]), 'data points'             #number of rows and therefore data points

    # Adding zpsys and filter columns. zp system used is ab and filter used is ptf48r
    ab = np.zeros(len(hml[:, 1]), dtype='|S2')
    band = np.zeros(len(hml[:, 1]), dtype='|S6')
    for i in range(len(ab)):
        ab[i] = 'ab'
        band[i] = 'ptf48r'
    hml = np.column_stack((hml, ab, band))

    # Converting into a table using astropy with titles: ptfname, time,
    # magnitude, mag_err, flux, flux_err, zp_new, zp, ra, dec, zpsys and filter
    hml_dat = astropy.table.Table(data=hml, names=(
            'ptfname', 'time', 'magnitude', 'mag_err', 'flux', 'flux_err', 'zp_new', 'zp', 'ra', 'dec', 'zpsys',
            'filter'),
                                      dtype=(
                                          'str', 'float', 'float', 'float', 'float', 'float', 'float', 'float', 'float',
                                            'float', 'str', 'str'))
    #sn types are Ib, Ib/c, Ic, Ic-BL, IIP
    sn_type = types[hml[:, 0][0]]

    # Selecting only Type II supernovae
    if sn_type[1] == 'I':
        # Selecting model
        source = sncosmo.get_source('s11-2004hx',version='1.0')
        fit_curve(hml_dat, source, hml)

    # Selecting only Type Ic supernovae
    elif sn_type[1]== 'c':
        # Selecting model
        source = sncosmo.get_source('snana-2004fe',version='1.0')
        fit_curve(hml_dat, source, hml)

    # Selecting TypeIb sn only
    elif len(sn_type)== 2 and (sn_type[1]!= 'b'):
        # Selecting model
        source = sncosmo.get_source('snana-2006ep', version='1.0')
        fit_curve(hml_dat, source, hml)

    # Selecting TypeIbc sn only
    elif len(sn_type)> 2 and (sn_type[1]!= 'b'):
        # Selecting model
        source = sncosmo.get_source('nugent-sn1bc', version='1.1')
        fit_curve(hml_dat, source, hml)
def Gen_SN():
    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, 'bessellb', 'ab',
                                cosmo=FlatLambdaCDM(H0=70, Om0=0.3))  # Fixing my peak absolute magnitude
    # model.set(x1=x_1, c=colour)
    '''
    absmagb =model.source_peakabsmag('bessellb','ab', cosmo=FlatLambdaCDM(H0=70,Om0=0.3))
    absmag_r =model.source_peakabsmag('bessellr','ab', cosmo=FlatLambdaCDM(H0=70,Om0=0.3))


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

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

    data = np.loadtxt('/home/fcm1g13/Documents/Supernova/PTF48R filter/PTF48R.dat')
    wavelength = np.array([row[0] for row in data])
    transmission = np.array([row[1] for row in data])

    band = sncosmo.Bandpass(wavelength, transmission, name='PTF48R')

    wave = np.arange(5580., 7500., 20)
    spec = model.flux([20., 30., 35., 40., 50.], wave)

    adjspec = transmission * spec[1]
    '''
        for point in transmission:
            for flux in spec[1]:
                adjspec.append(point*flux)
        '''
    print len(transmission)
    print len(spec[1])
    print adjspec

    plt.plot(wave, spec[1], color='#27ae60', label='Flux')
    model.bandflux('PTF48R', 30)
    plt.plot(wave, np.array(adjspec), color='#2980b9', label='Observed flux')
    plt.plot(wavelength, transmission * max(spec[1]))
    # plt.plot(wave, spec[2], color = '#27ae60',label = '5 days after peak')
    # plt.plot(wave, spec[3], color = '#c0392b',label = '10 days after peak')
    # plt.plot(wave, spec[4], color = '#8e44ad',label = '20 days after peak')

    plt.title('Model spectrum of Type Ia supernova at peak')
    plt.ylabel('Flux in ergs / s / cm^2 / $\AA$')
    plt.xlabel('Wavelength in $\AA$')
    plt.minorticks_on()
    plt.ylim([0, max(spec[1]) * 1.2])
    plt.legend()
    plt.draw()

    return timearray
def fitcurve(x, source_name):
    # Get data set needed
    hml = np.load('/home/fcm1g13/Documents/Supernova/CorecollapseLC/ccdata/' +
                  x)
    try:
        # Import model
        source = sncosmo.get_source(source_name)
        model = sncosmo.Model(source=source)
        # print len(hml[:,1]), 'data points'

        # Adding zpsys and filter columns. zp system used is ab and filter used is ptf48r
        ab = np.zeros(len(hml[:, 1]), dtype='|S2')
        band = np.zeros(len(hml[:, 1]), dtype='|S6')
        for i in range(len(ab)):
            ab[i] = 'ab'
            band[i] = 'ptf48r'
        hml = np.column_stack((hml, ab, band))

        # Converting into a table using astropy with titles: ptfname, time,
        # magnitude, mag_err, flux, flux_err, zp_new, zp, ra, dec, zpsys and filter
        hml_dat = astropy.table.Table(
            data=hml,
            names=('ptfname', 'time', 'magnitude', 'mag_err', 'flux',
                   'flux_err', 'zp_new', 'zp', 'ra', 'dec', 'zpsys', 'filter'),
            dtype=('str', 'float', 'float', 'float', 'float', 'float', 'float',
                   'float', 'float', 'float', 'str', 'str'))

        # Fitting model: model parameter z bound.
        res, fitted_model = sncosmo.fit_lc(hml_dat,
                                           model, ['z', 't0', 'amplitude'],
                                           bounds={'z': (0.005, 0.35)})

        #The following excludes data with fewer than 4 data points and not enough distribution..
        j = 0
        k = 0
        for i in hml[:, 1]:
            if float(i) > float(res.parameters[1]):
                j += 1
            else:
                k += 1
        # print hml[:,0][0],k,j
        if j >= 2 and k >= 2:
            if len(hml[:, 1]) > 3:
                #sncosmo.plot_lc(hml_dat, model=fitted_model, errors=res.errors, color='blue', figtext=str(hml[:,0][0]+' Type'+types[hml[:,0][0]]+'\n'+'Model name: '+ source.name), xfigsize=10)
                #plt.close()

                return np.array([
                    float(res.chisq / res.ndof), hml[:, 0][0], source_name
                ])  #returns reduced chi squared, sn name and model name.
            else:
                pass
        else:
            pass

    except ValueError:
        pass
    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'
Exemple #21
0
	def luminosity(**kwargs):
		source = sncosmo.get_source("nugent-sn1bc")
		source.set_peakmag(-17.5+kwargs['x0'], 'desg', 'ab') # magnitude at 10pc	
		dust = sncosmo.CCM89Dust()
		model = sncosmo.Model(source=source,effects=[dust], effect_names=['host'], effect_frames=['rest'])
		kwargs2 = dict(kwargs)
		del kwargs2['x0']

		model.set(**kwargs2)
		return model
Exemple #22
0
def test_register_source():
    phase = np.linspace(0., 100., 10)
    wave = np.linspace(800., 20000., 100)
    flux = np.ones((len(phase), len(wave)), dtype=float)
    source = sncosmo.TimeSeriesSource(phase, wave, flux, name='test_source')
    sncosmo.register(source)

    # Retrieving a source makes a copy, so just check that the names are the
    # same.
    assert sncosmo.get_source('test_source').name == 'test_source'
Exemple #23
0
    def luminosity(**kwargs):
        source = sncosmo.get_source("nugent-sn1bc")
        source.set_peakmag(-17.5 + kwargs["x0"], "desg", "ab")  # magnitude at 10pc
        dust = sncosmo.CCM89Dust()
        model = sncosmo.Model(source=source, effects=[dust], effect_names=["host"], effect_frames=["rest"])
        kwargs2 = dict(kwargs)
        del kwargs2["x0"]

        model.set(**kwargs2)
        return model
Exemple #24
0
	def luminosity(**kwargs):
		source = sncosmo.get_source('salt2')
		source.set_peakmag(-19.5-SNIa.alpha*kwargs['x1']+SNIa.beta*kwargs['c']+kwargs['x0'], 'desg', 'ab') # magnitude at 10pc
		dust = sncosmo.CCM89Dust()
		model = sncosmo.Model(source=source,effects=[dust], effect_names=['host'], effect_frames=['rest'])
		kwargs2 = dict(kwargs)
		del kwargs2['x0']

		model.set(**kwargs2)
		return model
Exemple #25
0
    def luminosity(**kwargs):
        source = sncosmo.get_source("salt2")
        source.set_peakmag(
            -19.5 - SNIa.alpha * kwargs["x1"] + SNIa.beta * kwargs["c"] + kwargs["x0"], "desg", "ab"
        )  # magnitude at 10pc
        dust = sncosmo.CCM89Dust()
        model = sncosmo.Model(source=source, effects=[dust], effect_names=["host"], effect_frames=["rest"])
        kwargs2 = dict(kwargs)
        del kwargs2["x0"]

        model.set(**kwargs2)
        return model
Exemple #26
0
def model_limits(sou):
    source = sncosmo.get_source(sou)
    model = sncosmo.Model(source=source)

    timearray = range(-20, 300)
    fluxlc = model.bandflux('ptf48r',timearray)     # Creating a flux array of the light curve
    modelbreak = []
    for i in range(len(fluxlc)-1):
        if fluxlc[i] == fluxlc[i+1]:
            modelbreak.append(timearray[i+1])
    for i in range(len(modelbreak)-1):
        if (modelbreak[i+1]-modelbreak[i]) > 20:
            return sou, modelbreak[i], modelbreak[i+1]
def get_snana_filenames(sntype):
    """
    """
    if not sntype.startswith('SN '):
        sntype = 'SN %s'%sntype

    reg = sncosmo.registry._get_registry(sncosmo.Source)
    source_tuples = [(v['name'], v['version'])
                     for v in reg.get_loaders_metadata()
                     if v['name'].startswith('snana')
                     and v['type'] == sntype]

    filenames = []
    for name, version in source_tuples:
        filepath = os.path.join(sncosmo.builtins.get_cache_dir(),
                                'sncosmo',
                                reg._loaders[(name, version)][1])
        if not os.exists(filepath):
            sncosmo.get_source(name, version=version)
        filenames.append(filepath)

    return filenames
def showcurve(sn, source_name):
    try:
        hml = np.load(
            '/home/fcm1g13/Documents/Supernova/CorecollapseLC/ccdata/' + sn)

        source = sncosmo.get_source(source_name)
        model = sncosmo.Model(source=source)
        # print len(hml[:,1]), 'data points'

        # Adding zpsys and filter columns. zp system used is ab and filter used is ptf48r
        ab = np.zeros(len(hml[:, 1]), dtype='|S2')
        band = np.zeros(len(hml[:, 1]), dtype='|S6')
        for i in range(len(ab)):
            ab[i] = 'ab'
            band[i] = 'ptf48r'
        hml = np.column_stack((hml, ab, band))

        hml_dat = astropy.table.Table(
            data=hml,
            names=('ptfname', 'time', 'magnitude', 'mag_err', 'flux',
                   'flux_err', 'zp_new', 'zp', 'ra', 'dec', 'zpsys', 'filter'),
            dtype=('str', 'float', 'float', 'float', 'float', 'float', 'float',
                   'float', 'float', 'float', 'str', 'str'))

        ###fitting model
        res, fitted_model = sncosmo.fit_lc(hml_dat,
                                           model, ['z', 't0', 'amplitude'],
                                           bounds={'z': (0.005, 0.35)},
                                           nburn=10000,
                                           nsamples=50000)
        #print 'peak', float(res.parameters[1])
        print res
        sncosmo.plot_lc(
            hml_dat,
            model=fitted_model,
            errors=res.errors,
            color='blue',
            figtext=str(hml[:, 0][0] + ' Type' + types[hml[:, 0][0]] + '\n' +
                        'Model name: ' + source.name),
            xfigsize=10)
        #plt.clfig()
        plt.show()

        #print #'### Parameters ###'
        #print 'SN',str(hml[:,0][0]), 'z:',float(res.parameters[0])# float(res.errors['z']), float(res.parameters[1]), float(res.errors['t0']),float(res.parameters[2]), float(res.errors['x0']),  float(res.parameters[3]), float(res.errors['x1']), float(res.parameters[4]), float(res.errors['c']), float(hml[:,8][0]), float(hml[:,9][0])
        print 'Done:', hml[:, 0][0], 'z:', float(
            res.parameters[0]
        ), 'Reduced chi^2:', res.chisq / res.ndof,  #'Data points:', len(hml[:,1]),' Type'+types[hml[:,0][0]]+'Model name: '+ source.name,'\n' #'Dof:', res.ndof

    except ValueError:
        sn, source_name, 'cannot be plotted'
def fitcurve(x, source_name):
    # Get data set needed
    hml=np.load('/home/fcm1g13/Documents/Supernova/CorecollapseLC/ccdata/' + x)    
    try:
        # Import model
        source=sncosmo.get_source(source_name) 
        model=sncosmo.Model(source=source) 
       # print len(hml[:,1]), 'data points'
       
        # Adding zpsys and filter columns. zp system used is ab and filter used is ptf48r
        ab = np.zeros(len(hml[:, 1]), dtype='|S2')
        band = np.zeros(len(hml[:, 1]), dtype='|S6')
        for i in range(len(ab)):
            ab[i] = 'ab'
            band[i] = 'ptf48r'
        hml = np.column_stack((hml, ab, band))

        # Converting into a table using astropy with titles: ptfname, time,
        # magnitude, mag_err, flux, flux_err, zp_new, zp, ra, dec, zpsys and filter
        hml_dat = astropy.table.Table(data=hml, names=(
             'ptfname', 'time', 'magnitude', 'mag_err', 'flux', 'flux_err', 'zp_new', 'zp', 'ra', 'dec', 'zpsys',
               'filter'),
                                      dtype=(
                                          'str', 'float', 'float', 'float', 'float', 'float', 'float', 'float', 'float',
                                            'float', 'str', 'str'))

        # Fitting model: model parameter z bound.
        res, fitted_model = sncosmo.fit_lc(hml_dat, model, ['z', 't0', 'amplitude'], bounds={'z': (0.005, 0.35)})

        #The following excludes data with fewer than 4 data points and not enough distribution..
        j=0; k=0
        for i in hml[:,1]:
            if float(i)>float(res.parameters[1]):
                j+=1
            else:
                k+=1
        # print hml[:,0][0],k,j
        if j>=2 and k>=2:            
            if len(hml[:,1])>3:                                
                #sncosmo.plot_lc(hml_dat, model=fitted_model, errors=res.errors, color='blue', figtext=str(hml[:,0][0]+' Type'+types[hml[:,0][0]]+'\n'+'Model name: '+ source.name), xfigsize=10)
                #plt.close()                
                
                return np.array([float(res.chisq/res.ndof), hml[:,0][0], source_name]) #returns reduced chi squared, sn name and model name. 
            else:
                pass
        else:
            pass
                
    except ValueError:
        pass
Exemple #30
0
    def __init__(self):
        """A version of the Hsiao model with an added stretch parameter

        This source class is equivalent to that of the default Hsiao model,
        except an additional parameter ``x1`` has been included.
        """

        super().__init__()
        self._parent = sncosmo.get_source('hsiao')
        self.name = 'hsiao_x1'
        self.version = '3.0.x1'
        self._wave = self._parent._wave
        self._parameters = np.array([1., 0])

        hsiao_phase = self._parent._phase
        self._phase = hsiao_phase[(hsiao_phase >= -18) & (hsiao_phase <= 85)]
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
Exemple #32
0
def _create_fit_data_iter(priors_hs, priors_bg, kwargs_hs, kwargs_bg):
    """Create an iterable of data used to run light-curve fits

    Args:
        priors_hs  (dict): Priors to use when fitting hsiao
        priors_bg  (dict): Priors to use when fitting sn91bg
        kwargs_hs  (dict): Kwargs to pass ``fit_func`` when fitting salt2
        kwargs_bg  (dict): Kwargs to pass ``fit_func`` when fitting sn91bg

    Returns:
        - An iterable of models, vparams, priors, and kwargs for fitting
        - A table to store output data
    """

    # Set default kwargs and protect against mutation
    priors_hs = deepcopy(priors_hs) or dict()
    priors_bg = deepcopy(priors_bg) or dict()
    kwargs_hs = deepcopy(kwargs_hs) or dict()
    kwargs_bg = deepcopy(kwargs_bg) or dict()

    # Define models for normal and 91bg SNe with host galaxy dust
    dust_kw = dict(effects=[DUST], effect_names=['mw'], effect_frames=['obs'])
    bg_source = sncosmo.get_source('sn91bg', version='hsiao_phase')
    sn91bg = sncosmo.Model(bg_source, **dust_kw)
    hsiao = sncosmo.Model('hsiao_x1', **dust_kw)

    # Determine what parameters to vary for each model
    # Hsiao does not have a c parameter. We don't vary mwebv
    vparams = {'z', 't0', 'amplitude', 'x1', 'c'}
    out_data = create_empty_table(vparams.union({'mwebv'}))
    if 'z' in priors_bg and 'z' in priors_hs:
        vparams -= {'z'}

    hsiao_vparams = set(hsiao.param_names).intersection(vparams)
    sn91bg_vparams = set(sn91bg.param_names).intersection(vparams)

    # Create iterators over the data we need to fit
    model_args = zip(
        (hsiao, sn91bg),  # The models
        (hsiao_vparams, sn91bg_vparams),  # The parameters to vary
        (priors_hs, priors_bg),  # The priors
        (kwargs_hs, kwargs_bg)  # The fitting kwargs
    )

    return model_args, out_data
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)
def showcurve(sn, source_name, hml):
    try:
        source=sncosmo.get_source(source_name) 
        model=sncosmo.Model(source=source) 

        #fit to model
        z0 = float(spec_z(sn[:-7]))
        hml_dat=astropy.table.Table(data=hml, names=('ptfname', 'time', 'magnitude', 'mag_err', 'flux', 'flux_err', 'zp_new', 'zp', 'ra', 'dec', 'zpsys', 'filter'), dtype=('str','float','float','float','float','float','float','float','float','float','str', 'str'))
        res, fitted_model=sncosmo.fit_lc(hml_dat, model, ['z','t0','amplitude'], bounds={'z':(z0, z0+0.001)}, nburn=10000, nsamples=50000)

        #plot model
        sncosmo.plot_lc(hml_dat, model=fitted_model, errors=res.errors, color='blue', figtext=str(hml[:,0][0]+' Type'+types[hml[:,0][0]]+'\n'+'Model name: '+ source.name + '\n'+'Reduced Chi Squared: ')+ str(res.chisq/res.ndof), xfigsize=10)
        plt.show()

        #print 'Parameters:''z:',float(res.parameters[0]), float(res.errors['z']), float(res.parameters[1]), float(res.errors['t0']),float(res.parameters[2]), float(res.errors['x0']),  float(res.parameters[3]), float(res.errors['x1']), float(res.parameters[4]), float(res.errors['c']), float(hml[:,8][0]), float(hml[:,9][0])'
        print 'Done:', hml[:,0][0], 'z:',float(res.parameters[0]), 'Reduced chi^2:', res.chisq/res.ndof,#'Data points:', len(hml[:,1]),' Type'+types[hml[:,0][0]]+'Model name: '+ source.name,'\n' #'Dof:', res.ndof

    except ValueError:
        print sn, source_name, 'cannot be plotted'
def fitcurve(x, source_name, hml):
    try:
        source = sncosmo.get_source(source_name)
        model = sncosmo.Model(source=source)

        #adding zpsys and filter columns
        ab = np.zeros(len(hml[:, 1]), dtype='|S2')
        for i in range(len(ab)):
            ab[i] = 'ab'
        hml = np.column_stack((hml, ab))
        band = np.zeros(len(hml[:, 1]), dtype='|S6')
        for i in range(len(band)):
            band[i] = 'ptf48r'
        hml = np.column_stack((hml, band))
        #fit to model
        z0 = float(spec_z(x[:-7]))
        hml_dat = astropy.table.Table(
            data=hml,
            names=('ptfname', 'time', 'magnitude', 'mag_err', 'flux',
                   'flux_err', 'zp_new', 'zp', 'ra', 'dec', 'zpsys', 'filter'),
            dtype=('str', 'float', 'float', 'float', 'float', 'float', 'float',
                   'float', 'float', 'float', 'str', 'str'))
        res, fitted_model = sncosmo.fit_lc(hml_dat,
                                           model, ['z', 't0', 'amplitude'],
                                           bounds={'z': (z0, z0 + 0.0001)},
                                           nburn=10000,
                                           nsamples=50000)

        #The following excludes data points not in the range of the model and data sets with fewer than 4 data points
        limit = modellimit(source_name, x[:-7], res.parameters[1])
        hml2 = []
        for j in range(len(hml[:, 1])):
            datapoint = hml[:, 1][j]
            if (res.parameters[1] - limit[0]) < float(datapoint) < (
                    res.parameters[1] + limit[1]):
                hml2.append(hml[j])
        hml2 = np.array(hml2)
        if len(hml2) > 3:

            return finalfitcurve(x, source_name, hml2)

    except ValueError:
        print 'error'
Exemple #36
0
def get_model_cc(z, sn_type, all_model):
    """Given a filter and redshift z, generates the observed
    magnitude for SNe Type Ibc or Type II"""
    my_model = choice(all_model)
    if my_model in ['s11-2004hx', 'nugent-sn2l']:
        sn_type = 'IIl'
    elif my_model in ['nugent-sn2n', 'snana-2006ez', 'snana-20069ix']:
        sn_type = 'IIn'
    model = sncosmo.Model(source=sncosmo.get_source(my_model),
                          effects=[dust], effect_names=['host'],
                          effect_frames=['rest'])
    mabs = all_mabs(sn_type)
    model.set(z=z)
    model.set_source_peakabsmag(mabs, 'bessellb', 'vega')
    p = {'z': z, 't0': t0, 'hostebv': uniform(-0.1, 0.65), 'hostr_v': hostr_v}
    model.set(**p)
    p['model_name'] = my_model
    max_phase = max_cc_phase(my_model)
    my_phase = uniform(-2, 3) + max_phase
    return model, p, my_phase
def lightcurve_II(filter, z, hostebv_II):
    """Given a filter and redshift z, generates the observed magnitude for
    SNe Type II"""
    zp = zero_point[filter]
    zpsys = zero_point['zpsys']
    model_II = ['s11-2005lc', 's11-2005gi', 's11-2006jl', 'nugent-sn2p',
                'snana-2004hx', 'snana-2005gi', 'snana-2006gq',
                'snana-2006kn', 'snana-2006jl', 'snana-2006iw',
                'snana-2006kv', 'snana-2006ns', 'snana-2007iz',
                'snana-2007nr', 'snana-2007nr', 'snana-2007kw',
                'snana-2007ky', 'snana-2007lj', 'snana-2007lb',
                'snana-2007ll', 'snana-2007nw', 'snana-2007ld',
                'snana-2007md', 'snana-2007lz', 'snana-2007lx',
                'snana-2007og', 'snana-2007ny', 'snana-2007nv',
                'snana-2007pg', 's11-2004hx', 'nugent-sn2l', 'nugent-sn2n',
                'snana-2006ez', 'snana-2006ix']
    obsflux_II = []
    phase_arrays = []
    for i in model_II:
        model_i = sncosmo.Model(source=sncosmo.get_source(i), effects=[dust],
                                effect_names=['host'],
                                effect_frames=['rest'])
        if i == 's11-2004hx' == 'nugent-sn2l':
            mabs = -17.98
        else:
            mabs = -16.75
        model_i.set(z=z)
        phase_array_i = np.linspace(model_i.mintime(), model_i.maxtime(), 100)
        model_i.set_source_peakabsmag(mabs, 'bessellb', 'ab')
        p_core_collapse = {'z': z, 't0': t0, 'hostebv': hostebv_II,
                           'hostr_v': hostr_v}
        model_i.set(**p_core_collapse)
        phase_arrays.append(phase_array_i)
        obsflux_i = model_i.bandflux(filter, phase_array_i, zp, zpsys)
        obsflux_II.append(obsflux_i)
    keys = model_II
    values = []
    for i, item in enumerate(model_II):
        values.append([obsflux_II[i], phase_arrays[i]])
    dict_II = dict(zip(keys, values))
    return (dict_II)
Exemple #38
0
    def add_sncosmo_params(self, glsne_merged_df):

        source = sncosmo.get_source('salt2-extended')
        model = sncosmo.Model(source=source)

        # Use cosmoDC2 settings
        cosmo = FlatLambdaCDM(H0=71, Om0=0.265, Tcmb0=0, Neff=3.04, m_nu=None, Ob0=0.045)

        x0 = []
        for sn_row_zs, sn_row_mb in zip(glsne_merged_df['zs'].values, glsne_merged_df['MB'].values):
            z = sn_row_zs
            MB = sn_row_mb
            model.set(z=z)
            model.set_source_peakabsmag(MB, 'bessellb', 'ab', cosmo=cosmo)
            x0.append(model.get('x0'))

        glsne_merged_df['x0'] = x0
        glsne_merged_df['x1'] = 1.
        glsne_merged_df['c'] = 0.

        return glsne_merged_df
Exemple #39
0
def get_model_Ia(z, min_phase, max_phase):
    """Given a filter, redshift z at given phase, generates the observed
    magnitude for SNe Type Ia"""

    alpha = 0.12
    beta = 3.
    x1 = normal(0., 1.)
    c = normal(0., 0.1)
    my_phase = uniform(min_phase, max_phase)
    mabs = normal(-19.1 - alpha * x1 + beta * c, scale=0.15)
    salt_name, salt_version = which_salt(z)
    model_Ia = sncosmo.Model(
        source=sncosmo.get_source(salt_name, version=salt_version))
    model_Ia.set(z=z)
    model_Ia.set_source_peakabsmag(mabs, 'bessellb', 'vega')
    p = {'z': z, 't0': t0, 'x1': x1, 'c': c}
    p['x0'] = model_Ia.get('x0')
    model_Ia.set(**p)
    p['salt_name'] = salt_name
    p['salt_version'] = salt_version
    return model_Ia, p, my_phase
Exemple #40
0
def get_model_Ia(z, min_phase, max_phase):
    """Given a filter, redshift z at given phase, generates the observed
    magnitude for SNe Type Ia"""

    alpha = 0.12
    beta = 3.
    x1 = normal(0., 1.)
    c = normal(0., 0.1)
    my_phase = uniform(min_phase, max_phase)
    mabs = normal(-19.1 - alpha*x1 + beta*c, scale=0.15)
    salt_name, salt_version = which_salt(z)
    model_Ia = sncosmo.Model(source=sncosmo.get_source(salt_name,
                                                       version=salt_version))
    model_Ia.set(z=z)
    model_Ia.set_source_peakabsmag(mabs, 'bessellb', 'vega')
    p = {'z': z, 't0': t0, 'x1': x1, 'c': c}
    p['x0'] = model_Ia.get('x0')
    model_Ia.set(**p)
    p['salt_name'] = salt_name
    p['salt_version'] = salt_version
    return model_Ia, p, my_phase
Exemple #41
0
def get_model_cc(z, sn_type, all_model):
    """Given a filter and redshift z, generates the observed
    magnitude for SNe Type Ibc or Type II"""
    my_model = choice(all_model)
    if my_model in ['s11-2004hx', 'nugent-sn2l']:
        sn_type = 'IIl'
    elif my_model in ['nugent-sn2n', 'snana-2006ez', 'snana-20069ix']:
        sn_type = 'IIn'
    model = sncosmo.Model(source=sncosmo.get_source(my_model),
                          effects=[dust],
                          effect_names=['host'],
                          effect_frames=['rest'])
    mabs = all_mabs(sn_type)
    model.set(z=z)
    model.set_source_peakabsmag(mabs, 'bessellb', 'vega')
    p = {'z': z, 't0': t0, 'hostebv': uniform(-0.1, 0.65), 'hostr_v': hostr_v}
    model.set(**p)
    p['model_name'] = my_model
    max_phase = max_cc_phase(my_model)
    my_phase = uniform(-2, 3) + max_phase
    return model, p, my_phase
Exemple #42
0
def fitcurve(x, source_name, hml):
    try:
        source = sncosmo.get_source(source_name)
        model = sncosmo.Model(source=source)
        # print len(hml[:,1]), 'data points'

        # Adding zpsys and filter columns. zp system used is ab and filter used is ptf48r
        ab = np.zeros(len(hml[:, 1]), dtype='|S2')
        band = np.zeros(len(hml[:, 1]), dtype='|S6')
        for i in range(len(ab)):
            ab[i] = 'ab'
            band[i] = 'ptf48r'
        hml = np.column_stack((hml, ab, band))

        # Converting into a table using astropy with titles: ptfname, time,
        # magnitude, mag_err, flux, flux_err, zp_new, zp, ra, dec, zpsys and filter
        hml_dat = astropy.table.Table(
            data=hml,
            names=('ptfname', 'time', 'magnitude', 'mag_err', 'flux',
                   'flux_err', 'zp_new', 'zp', 'ra', 'dec', 'zpsys', 'filter'),
            dtype=('str', 'float', 'float', 'float', 'float', 'float', 'float',
                   'float', 'float', 'float', 'str', 'str'))
        # Fitting model: model parameter z bound.
        res, fitted_model = sncosmo.fit_lc(hml_dat,
                                           model, ['z', 't0', 'amplitude'],
                                           bounds={'z': (0.005, 0.35)})
        #The following excludes data points not in the range of the model and data sets with fewer than 4 data points
        limit = modellimit(source_name, res.parameters[0], res.parameters[1])
        hml2 = []
        for j in range(len(hml[:, 1])):
            datapoint = hml[:, 1][j]
            if (res.parameters[1] - limit[0]) < float(datapoint) < (
                    res.parameters[1] + limit[1]):
                hml2.append(hml[j])
        hml2 = np.array(hml2)
        if len(hml2) > 3:
            return finalfitcurve(x, source_name, hml2)

    except ValueError:
        pass
def modellimit(source_name, x, t0):
    source=sncosmo.get_source(source_name) 
    model=sncosmo.Model(source=source)
    
    #Creating a flux array of the model lightcurve
    timearray= np.arange(t0-120,t0+500, 0.01)
    model.set(z=spec_z(x),t0=t0)
    fluxlc=model.bandflux('ptf48r',timearray) 
    modelbreak = [t0-120.0]
    for i in range(len(fluxlc)-1):
        if fluxlc[i] == fluxlc[i+1]:
            modelbreak.append(timearray[i+1])

    #find the limits of the model by defining where the flux does not change. 
    for i in range(len(modelbreak)-1):
        if abs(modelbreak[i+1]-modelbreak[i]) > 20:
            minimum = t0 - modelbreak[i]
            maximum = modelbreak[i+1] - t0
            
            #return the difference of t0 and the edges of the model and the time of peak flux
            ##this is done as some models use t0 as peak and others use it for start of model
            return minimum, maximum, timearray[list(fluxlc).index(max(fluxlc))]
def modellimit(source_name, x, t0):
    source = sncosmo.get_source(source_name)
    model = sncosmo.Model(source=source)

    #Creating a flux array of the model lightcurve
    timearray = np.arange(t0 - 120, t0 + 500, 0.01)
    model.set(z=spec_z(x), t0=t0)
    fluxlc = model.bandflux('ptf48r', timearray)
    modelbreak = [t0 - 120.0]
    for i in range(len(fluxlc) - 1):
        if fluxlc[i] == fluxlc[i + 1]:
            modelbreak.append(timearray[i + 1])

    #find the limits of the model by defining where the flux does not change.
    for i in range(len(modelbreak) - 1):
        if abs(modelbreak[i + 1] - modelbreak[i]) > 20:
            minimum = t0 - modelbreak[i]
            maximum = modelbreak[i + 1] - t0

            #return the difference of t0 and the edges of the model and the time of peak flux
            ##this is done as some models use t0 as peak and others use it for start of model
            return minimum, maximum, timearray[list(fluxlc).index(max(fluxlc))]
Exemple #45
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()
def showcurve(sn, source_name, hml):
    try:
        source = sncosmo.get_source(source_name)
        model = sncosmo.Model(source=source)

        #fit to model
        z0 = float(spec_z(sn[:-7]))
        hml_dat = astropy.table.Table(
            data=hml,
            names=('ptfname', 'time', 'magnitude', 'mag_err', 'flux',
                   'flux_err', 'zp_new', 'zp', 'ra', 'dec', 'zpsys', 'filter'),
            dtype=('str', 'float', 'float', 'float', 'float', 'float', 'float',
                   'float', 'float', 'float', 'str', 'str'))
        res, fitted_model = sncosmo.fit_lc(hml_dat,
                                           model, ['z', 't0', 'amplitude'],
                                           bounds={'z': (z0, z0 + 0.001)},
                                           nburn=10000,
                                           nsamples=50000)

        #plot model
        sncosmo.plot_lc(
            hml_dat,
            model=fitted_model,
            errors=res.errors,
            color='blue',
            figtext=str(hml[:, 0][0] + ' Type' + types[hml[:, 0][0]] + '\n' +
                        'Model name: ' + source.name + '\n' +
                        'Reduced Chi Squared: ') + str(res.chisq / res.ndof),
            xfigsize=10)
        plt.show()

        #print 'Parameters:''z:',float(res.parameters[0]), float(res.errors['z']), float(res.parameters[1]), float(res.errors['t0']),float(res.parameters[2]), float(res.errors['x0']),  float(res.parameters[3]), float(res.errors['x1']), float(res.parameters[4]), float(res.errors['c']), float(hml[:,8][0]), float(hml[:,9][0])'
        print 'Done:', hml[:, 0][0], 'z:', float(
            res.parameters[0]
        ), 'Reduced chi^2:', res.chisq / res.ndof,  #'Data points:', len(hml[:,1]),' Type'+types[hml[:,0][0]]+'Model name: '+ source.name,'\n' #'Dof:', res.ndof

    except ValueError:
        print sn, source_name, 'cannot be plotted'
def finalfitcurve(x, source_name, hml):
    try:
        source=sncosmo.get_source(source_name) 
        model=sncosmo.Model(source=source) 
        
        #fit to model
        z0 = float(spec_z(x[:-7]))
        hml_dat=astropy.table.Table(data=hml, names=('ptfname', 'time', 'magnitude', 'mag_err', 'flux', 'flux_err', 'zp_new', 'zp', 'ra', 'dec', 'zpsys', 'filter'), dtype=('str','float','float','float','float','float','float','float','float','float','str', 'str'))
        res, fitted_model=sncosmo.fit_lc(hml_dat, model, ['z','t0','amplitude'], bounds={'z':(z0, z0+0.0001)}, nburn=10000, nsamples=50000)
        #The following excludes data with not enough distribution..
        ##Ensuring at least 2 data points on either side of peak.
        limit = modellimit(source_name, x[:-7], res.parameters[1])
        j=0; k=0
        for i in hml[:,1]:
            if float(i)>float(limit[2]):
                j+=1
            else:
                k+=1
        if j>=2 and k>=2:          
            return np.array([float(res.chisq/res.ndof), hml[:,0][0], source_name]), hml #returns reduced chi squared, sn name and model name. 
           
    except ValueError:
        print 'error'
Exemple #48
0
def test_salt2source_rcov_vs_snfit():
    dirname = os.path.join(os.path.dirname(__file__), "data")

    # read parameters and times
    f = open(os.path.join(dirname, "salt2_rcov_params_times.dat"), 'r')
    meta = read_header(f)
    times = np.loadtxt(f)
    f.close()

    # initialize model and set parameters
    source = sncosmo.get_source("salt2", version="2.4")  # fixed version
    model = sncosmo.Model(source)
    model.set(z=meta['Redshift'], t0=meta['DayMax'], x0=meta['X0'],
              x1=meta['X1'], c=meta['Color'])

    # Test separate bands separately, as thats how they're written to files.
    # (And cross-band covariance is zero.)
    for band in ('SDSSg', 'SDSSr', 'SDSSi'):
        fname = os.path.join(dirname, "salt2_rcov_snfit_{}.dat".format(band))
        ref = np.loadtxt(fname, skiprows=1)

        rcov = model._bandflux_rcov(band, times)
        assert_allclose(ref, rcov, rtol=5.e-5)
Exemple #49
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']))
def fitcurve(x, source_name, hml):
    try:
        source=sncosmo.get_source(source_name) 
        model=sncosmo.Model(source=source) 
       # print len(hml[:,1]), 'data points'

        # Adding zpsys and filter columns. zp system used is ab and filter used is ptf48r
        ab = np.zeros(len(hml[:, 1]), dtype='|S2')
        band = np.zeros(len(hml[:, 1]), dtype='|S6')
        for i in range(len(ab)):
            ab[i] = 'ab'
            band[i] = 'ptf48r'
        hml = np.column_stack((hml, ab, band))

        # Converting into a table using astropy with titles: ptfname, time,
        # magnitude, mag_err, flux, flux_err, zp_new, zp, ra, dec, zpsys and filter
        hml_dat = astropy.table.Table(data=hml, names=(
             'ptfname', 'time', 'magnitude', 'mag_err', 'flux', 'flux_err', 'zp_new', 'zp', 'ra', 'dec', 'zpsys',
               'filter'),
                                      dtype=(
                                          'str', 'float', 'float', 'float', 'float', 'float', 'float', 'float', 'float',
                                            'float', 'str', 'str'))
        # Fitting model: model parameter z bound.
        res, fitted_model = sncosmo.fit_lc(hml_dat, model, ['z', 't0', 'amplitude'], bounds={'z': (0.005, 0.35)})
        #The following excludes data points not in the range of the model and data sets with fewer than 4 data points
        limit = modellimit(source_name, res.parameters[0], res.parameters[1])
        hml2 = []
        for j in range(len(hml[:,1])):
            datapoint = hml [:,1][j]
            if (res.parameters[1]- limit[0])< float(datapoint) < (res.parameters[1]+limit[1]):
                hml2.append(hml[j]) 
        hml2 = np.array(hml2)
        if len(hml2)>3:
            return finalfitcurve(x, source_name, hml2)    
    
    except ValueError:
        pass   
Exemple #51
0
    def __init__(self, name=None, version=None):

        self.name = name
        self.version = version
        hsiao = sncosmo.get_source("hsiao", version='3.0')        
        self._phase = hsiao._phase
        self._wave = hsiao._wave
        self._passed_flux = hsiao._passed_flux
        self._param_names = ['amplitude', 's']
        self.param_names_latex = ['A', 's']
        self._parameters = np.array([1., 1.])
        self._model_flux = Spline2d(self._phase, self._wave,
                                    self._passed_flux, kx=2, ky=2)
        self.bumps = copy(self.BUMPS)
        
        for bump in self.bumps:
            bump._fit_kernel(hsiao)
            self._parameters = np.concatenate((self._parameters, [0.]))
            self._param_names.append(bump.name + '_bump_amp')
            self.param_names_latex.append(bump.name + '_A')

        self._parameters = np.concatenate((self.parameters, [0.]))
        self._param_names += ['wave_slope']
        self.param_names_latex.append('m_\lambda')
Exemple #52
0
def sugar_model(q0=0,
                q1=0,
                q2=0,
                q3=0,
                Av=0,
                phase=np.linspace(-5, 30, 10),
                wave=np.linspace(4000, 8000, 10)):
    """
    Give a spectral time series of SUGAR model
    for a given set of parameters.
    """
    source = sncosmo.get_source('sugar')

    mag_sugar = source._model['M0'](phase, wave)

    keys = ['ALPHA1', 'ALPHA2', 'ALPHA3', 'CCM']
    parameters = [q1, q2, q3, Av]
    for i in range(4):
        comp = source._model[keys[i]](phase, wave) * parameters[i]
        mag_sugar += comp
    # Mag AB used in the training of SUGAR.
    mag_sugar += 48.59
    wave_factor = (wave**2 / 299792458. * 1.e-10)
    return (q0 * 10.**(-0.4 * mag_sugar) / wave_factor)
Exemple #53
0
def test_salt2source_timeseries_vs_snfit():
    """Test timeseries output from SALT2Source vs pregenerated timeseries
    from snfit (SALT2 software)."""

    source = sncosmo.get_source("salt2", version="2.4")  # fixed version
    model = sncosmo.Model(source)

    dirname = os.path.join(os.path.dirname(__file__), "data")

    for fname in [
            'salt2_timeseries_1.dat', 'salt2_timeseries_2.dat',
            'salt2_timeseries_3.dat', 'salt2_timeseries_4.dat'
    ]:
        f = open(os.path.join(dirname, fname), 'r')
        meta = read_header(f)
        time, wave, fluxref = sncosmo.read_griddata_ascii(f)
        f.close()

        # The output from snfit's Salt2Model.SpectrumFlux() has a
        # different definition than sncosmo's model.flux() by a factor
        # of a^2. snfit's definition is the rest-frame flux but at a
        # blue-shifted wavelength.  (There is no correction for photon
        # energy or time dilation. These corrections are made in the
        # integration step.)
        a = 1. / (1. + meta['Redshift'])
        fluxref *= a**2

        model.set(z=meta['Redshift'],
                  t0=meta['DayMax'],
                  x0=meta['X0'],
                  x1=meta['X1'],
                  c=meta['Color'])
        flux = model.flux(time, wave)

        # super good agreement!
        assert_allclose(flux, fluxref, rtol=1e-13)
snclist = ['09dh', '09q', '09sk', '09ut', '10aavz', '10acbu', '10bhu', '10bip', '10bzf', '10ciw', '10fmx', '10gvb', '10hfe', '10hie', '10iue', '10lbo', '10osn', '10qqd', '10qts', '10svt', '10tqi', '10tqv', '10xem', '10xik', '10ysd', '10zcn', '11bli', '11bov', '11cmh', '11gcj', '11hyg', '11img', '11ixk', '11jgj', '11klg', '11lbm', '11mnb', '11mwk', '11rka', '12as', '12cde', '12cjy', '12dcp', '12dtf', '12gdy', '12gzk', '12hni', '12jxd', '12ktu', '12lpo']




datadir = '/home/fcm1g13/Documents/Supernova/Ibcsn_pftdata_c/Sullivan_pipeline/data_files/PTF'

tempcompletesnlist = ['09dfk', '09dh', '09dha','09fsr','09q', '09sk', '09ut','10aavz', '10acbu', '10acff', '10acgq', '10bhu', '10bip', '10bzf', '10ciw', '10eqi', '10fbv', '10feq', '10fmx', '10gvb', '10hfe', '10hie', '10inj', '10iue', '10kui', '10lbo', '10osn', '10qif', '10qqd', '10qts', '10svt', '10tqi', '10tqv', '10vnv', '10xem', '10xik', '10xjr', '10ysd', '10zcn','11bli', '11bov', '11cmh', '11gcj', '11hyg', '11ilr', '11img', '11ixk', '11izq', '11jgj', '11kaa', '11klg', '11lbm', '11mnb', '11mwk', '11qcj', '11qiq', '11rka', '12as', '12cde', '12cjy', '12dcp', '12dtf', '12eaw', '12gdy', '12gzk', '12hni', '12jxd', '12ktu', '12lpo', '12mfx']
#tempcompletesnlistwithoutbadones
#snthatdontwork = #REMOVEDSN: '10fia','10wal','11rfh', '12bwq', #'12elh', '12fgw','12gty', '12lvt','11awe','11lmn', '11pnq', '12fes' ,'12grr','12gvr',  '12hvv','12ldy'
#completesnlist = tempcompletesnlistwithoutbadones
completesnlist = tempcompletesnlist
completesnlist = snblist
#completesnlist = ['12hvv']

source=sncosmo.get_source('s11-2005hm') 
model=sncosmo.Model(source=source)

ib = 0; ic = 0; jo = 1
redchib = []; redchic = []
redshiftvb = []; redshiftvc = []
totalred = []
peakabsmagvalueb = []; peakabsmagvaluec = []
for sn in completesnlist[:]:
    x = np.loadtxt(datadir + sn + '.extra_out_PTF48R', dtype= str,skiprows=16,  usecols = (0,1,2,3))# comments='#', delimiter='    ')
    dataset = []
    for i in x:
        if float(i[1]) > 0:
            dataset.append(i)
    hml = np.array(dataset)
    hml = averagedata(hml)
####
for sn in completesnlist[:]:
    redchilist = []

    try:
        types[sn].index("c")
        if sntype[4] == "b":
            source_name_list = b_source_names + c_source_names
        else:
            source_name_list = c_source_names
    except:
        source_name_list = b_source_names
    for source_name in source_name_list:

        source = sncosmo.get_source(source_name)
        model = sncosmo.Model(source=source)

        x = np.loadtxt(
            datadir + sn + ".extra_out_PTF48R", dtype=str, skiprows=16, usecols=(0, 1, 2, 3)
        )  # comments='#', delimiter='    ')
        dataset = []
        for i in x:
            if float(i[1]) > 0:
                dataset.append(i)
        hml = np.array(dataset)
        hml = averagedata(hml)

        try:
            y = showcurve(sn, hml, source_name)
            # print y
snclist = ['09dh', '09q', '09sk', '09ut', '10aavz', '10acbu', '10bhu', '10bip', '10bzf', '10ciw', '10fmx', '10gvb', '10hfe', '10hie', '10iue', '10lbo', '10osn', '10qqd', '10qts', '10svt', '10tqi', '10tqv', '10xem', '10xik', '10ysd', '10zcn', '11bli', '11bov', '11cmh', '11gcj', '11hyg', '11img', '11ixk', '11jgj', '11klg', '11lbm', '11mnb', '11mwk', '11rka', '12as', '12cde', '12cjy', '12dcp', '12dtf', '12gdy', '12gzk', '12hni', '12jxd', '12ktu', '12lpo']




datadir = '/home/fcm1g13/Documents/Supernova/Ibcsn_pftdata_c/Sullivan_pipeline/data_files/PTF'

tempcompletesnlist = ['09dfk', '09dh', '09dha','09fsr','09q', '09sk', '09ut','10aavz', '10acbu', '10acff', '10acgq', '10bhu', '10bip', '10bzf', '10ciw', '10eqi', '10fbv', '10feq', '10fmx', '10gvb', '10hfe', '10hie', '10inj', '10iue', '10kui', '10lbo', '10osn', '10qif', '10qqd', '10qts', '10svt', '10tqi', '10tqv', '10vnv', '10xem', '10xik', '10xjr', '10ysd', '10zcn','11bli', '11bov', '11cmh', '11gcj', '11hyg', '11ilr', '11img', '11ixk', '11izq', '11jgj', '11kaa', '11klg', '11lbm', '11mnb', '11mwk', '11qcj', '11qiq', '11rka', '12as', '12cde', '12cjy', '12dcp', '12dtf', '12eaw', '12gdy', '12gzk', '12hni', '12jxd', '12ktu', '12lpo', '12mfx']
#tempcompletesnlistwithoutbadones
#snthatdontwork = #REMOVEDSN: '10fia','10wal','11rfh', '12bwq', #'12elh', '12fgw','12gty', '12lvt','11awe','11lmn', '11pnq', '12fes' ,'12grr','12gvr',  '12hvv','12ldy'
#completesnlist = tempcompletesnlistwithoutbadones
completesnlist = tempcompletesnlist
completesnlist = snclist
#completesnlist = ['12hvv']

source=sncosmo.get_source('s11-2006fo') 
model=sncosmo.Model(source=source)

ib = 0; ic = 0; jo = 1
redchib = []; redchic = []
redshiftvb = []; redshiftvc = []
totalred = []
peakabsmagvalueb = []; peakabsmagvaluec = []
for sn in completesnlist[:]:
    x = np.loadtxt(datadir + sn + '.extra_out_PTF48R', dtype= str,skiprows=16,  usecols = (0,1,2,3))# comments='#', delimiter='    ')
    dataset = []
    for i in x:
        if float(i[1]) > 0:
            dataset.append(i)
    hml = np.array(dataset)
    hml = averagedata(hml)
Exemple #57
0
def showcurve(sn, hml, source_name):
    try:
        source = sncosmo.get_source(source_name)
        model = sncosmo.Model(source=source)
        z0 = specs[sn]
        if z0 == 'no data':
            #pass
            print sn[:-7], 'cannot be plotted'
        else:
            z0 = float(z0)
            model.set(z=z0)
            #print z0

            #adding zpsys and filter columns
            ab = np.zeros(len(hml[:, 1]), dtype='|S2')
            for i in range(len(ab)):
                ab[i] = 'ab'
            hml = np.column_stack((hml, ab))
            band = np.zeros(len(hml[:, 1]), dtype='|S6')
            for i in range(len(band)):
                band[i] = 'ptf48r'
            hml = np.column_stack((hml, band))

            hml_dat = astropy.table.Table(
                data=hml,
                names=('ptfname', 'time', 'magnitude', 'mag_err', 'flux',
                       'flux_err', 'zp_new', 'zp', 'ra', 'dec', 'zpsys',
                       'filter'),
                dtype=('str', 'float', 'float', 'float', 'float', 'float',
                       'float', 'float', 'float', 'float', 'str', 'str'))
            res, fitted_model = sncosmo.fit_lc(hml_dat,
                                               model, ['t0', 'amplitude'],
                                               nburn=10000,
                                               nsamples=50000)
            ##sncosmo.plot_lc(hml_dat, model=fitted_model, model_label=source.name, errors=res.errors, color='blue', figtext=str(hml[:,0][0]+'\n'+'Model name: nugent-sn1bc'+ '\n'+'Reduced Chi Squared: ')+ str(res.chisq/res.ndof), xfigsize=18)
            ##plt.show()
            zp_new = [hml_dat[i][7] for i in range(len(hml))]

            hml2 = []
            #print hml
            #print res.parameters[1]
            j = 0
            k = 0
            for row in hml:
                datestamp = row[1]
                peaktime = float(res.parameters[1])
                limits = modellimit(z0)
                if peaktime + (40.0) * (1 + z0) > float(
                        datestamp) > peaktime - (15.0) * (1 + z0):
                    hml2.append(row)
                if peaktime + (40.0) * (1 + z0) > float(datestamp) > peaktime:
                    j += 1
                if peaktime > float(datestamp) > peaktime - (15.0) * (1 + z0):
                    k += 1
            if j > 1 and k > 1:
                hml2 = np.array(hml2)

                ##print 'after', len(hml2)
                hml_dat2 = astropy.table.Table(
                    data=hml2,
                    names=('ptfname', 'time', 'magnitude', 'mag_err', 'flux',
                           'flux_err', 'zp_new', 'zp', 'ra', 'dec', 'zpsys',
                           'filter'),
                    dtype=('str', 'float', 'float', 'float', 'float', 'float',
                           'float', 'float', 'float', 'float', 'str', 'str'))
                res2, fitted_model2 = sncosmo.fit_lc(hml_dat2,
                                                     model,
                                                     ['t0', 'amplitude'],
                                                     nburn=10000,
                                                     nsamples=50000)

                #plot model
                redchisqaured = res2.chisq / res2.ndof
                if redchisqaured < 1:
                    pass
                #sncosmo.plot_lc(hml_dat2, model=fitted_model2, model_label=source.name, zp = np.mean(zp_new), errors=res2.errors, color='blue', figtext=str(hml[:,0][0]+'\n'+'Model name: nugent-sn1bc'+ '\n'+'Reduced Chi Squared: ')+ str(res2.chisq/res2.ndof), xfigsize=18)
                #plt.show()

                ##print 'Done:', hml2[:,0][0], 'z:',float(res2.parameters[0]), 'Reduced chi^2:', res2.chisq/res2.ndof #'Data points:', len(hml[:,1]),' Type'+types[hml[:,0][0]]+'Model name: '+ source.name,'\n' #'Dof:', res.ndof
                return res2.parameters, np.mean(
                    zp_new
                ), redchisqaured, z0, hml2  #, res.errors['amplitude']]
            else:
                pass
                #return res.parameters, np.mean(zp_new), res.chisq/res.ndof, z0, hml
    except ValueError:
        #pass
        print sn, 'cannot be plotted'