Exemple #1
0
def magnitude_in_band(band: str, spectrum):
    """ """
    bandpassfiles = load_info_json("bandpassfiles")
    zpbandfluxnames = load_info_json("zpbandfluxnames")
    additional_bands = load_info_json("additional_bands")

    # for bandpassfile in bandpassfiles:
    #     full_path_file = os.path.join(CURRENT_FILE_DIR, bandpassfile)
    #     bandpassfiles.update(bandpassfile: full_path_file)

    for bandname in additional_bands.keys():
        fname = additional_bands[bandname]
        b = np.loadtxt(os.path.join(CURRENT_FILE_DIR, fname))
        if "Swift" in fname:
            bandpass = sncosmo.Bandpass(b[:, 0], b[:, 1] / 50, name=bandname)
        else:
            bandpass = sncosmo.Bandpass(b[:, 0], b[:, 1], name=bandname)
        sncosmo.registry.register(bandpass, force=True)

    bp = sncosmo_spectral_v13.read_bandpass(
        os.path.join(CURRENT_FILE_DIR, bandpassfiles[band]))
    ab = sncosmo.get_magsystem("ab")
    zp_flux = ab.zpbandflux(zpbandfluxnames[band])
    bandflux = spectrum.bandflux(bp) / zp_flux
    mag = -2.5 * np.log10(bandflux)

    return mag
    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 #3
0
def _getPartialBandMag(model,phase,wave,band,zpsys,wavestep):
    """
    (Private)
     Helper function that calculates the bandmag from a sub-band section of flux using sncosmo.Bandmag
    """
    interpFunc=scint.interp1d(band.wave,band.trans)
    waves=arange(band.wave[0],wave[-1]+1,wavestep)
    transInterp=interpFunc(waves)
    sncosmo.registry.register(sncosmo.Bandpass(waves,transInterp,name='tempBand'),force=True)

    return(model.bandmag('tempBand',zpsys,phase)) #magnitude in the overlap of the band
Exemple #4
0
def getMagSncosmo(filename,band,model,theta=0.0,redshift=0.0):
    #u = np.genfromtxt(opts.name)

    D_cm = 10*3.0857e16*100 # 10 pc in cm

    with open(filename) as f:
        content = f.readlines()
    for ii in range(3):
        if ii == 0:
            Nobs=int(content[0])
        elif ii == 1:
            Nwave=int(content[1])
        elif ii == 2:
            Ntime=int(content[2].split()[0])
            ti = float(content[2].split()[1])
            tf = float(content[2].split()[2])

    dlogt = (np.log(tf)-np.log(ti)) / float(Ntime)

    tt = []
    for i in range(Ntime):
        tt.append(np.exp(np.log(ti) + i * dlogt))
    tt = np.array(tt)

    a = np.genfromtxt(filename, skip_header=3)

    dMpc = 10e-6

    mall = []
    costhetas = np.linspace(0,1,Nobs)
    thetas = np.rad2deg(np.arccos(costhetas))
    j = np.argmin(np.abs(thetas-theta))

    w = a[Nwave*j:Nwave*(j+1),0]

    fl = np.ones((Ntime,len(w)))
    Lbol = np.ones(Ntime)
    for i in range(0,Ntime):
        I = a[Nwave*j:Nwave*(j+1),1+i*3] * (1./dMpc)**2
        fl[i] = I
        Lbol[i] = np.trapz(I*(4*np.pi*D_cm**2),x=w)
    source = sncosmo.TimeSeriesSource(tt,w,fl)

    bp = sncosmo.Bandpass(band[:,0], band[:,1])
    m = source.bandmag(bp,"ab",tt)
    mag_d = m - 5. * np.log10(dMpc*1e6/10.)

    ii = np.where(~np.isnan(mag_d) & np.isfinite(mag_d))[0]
    f1 = interp.interp1d(tt[ii], mag_d[ii])
    f = extrap1d(f1,4)
    mag_d = f(tt)

    return tt, mag_d, Lbol
 def register_ZTF_bands(ZTF_analysis_data = 'melissa/Data/ZTF/Filters/'):
     band_file_G = 'Filter_G.csv'
     band_file_I = 'Filter_I.csv'
     band_file_R = 'Filter_R.csv'
 
     filt2 = pd.read_csv(ZTF_analysis_data/band_file_G)
     wl_G = filt2['lambda']
     transmission_G = filt2['transmission']
     filt2 = pd.read_csv(ZTF_analysis_data/band_file_I)
     wl_I = filt2['lambda']
     transmission_I = filt2['transmission']
     filt2 = pd.read_csv(ZTF_analysis_data/band_file_R)
     wl_V = filt2['lambda']
     transmission_V = filt2['transmission']
 
     band_G = sncosmo.Bandpass(wl_G,transmission_G,wave_unit=u.AA,name='GZTF')    
     sncosmo.registry.register(band_G, force=True)
     band_I = sncosmo.Bandpass(wl_I,transmission_I,wave_unit=u.AA,name='IZTF')    
     sncosmo.registry.register(band_I, force=True)
     band_R = sncosmo.Bandpass(wl_R,transmission_R,wave_unit=u.AA,name='RZTF')    
     sncosmo.registry.register(band_R, force=True)
def read_and_register(path, name=None):
    """Read and register non-built-in bandpasses into the sncosmo registry
    
    Args:
        path: path to filter definition
        name: name of bandpass. If None, uses the filename.
    """
    if name is None:
        name = os.path.basename(path).split('.')[0]
    wave, trans = np.loadtxt(path, unpack=True)
    band = sncosmo.Bandpass(wave=wave, trans=trans, name=name)
    sncosmo.registry.register(band)
def load_ztf_bands(bandpass_dir=''):
    bands = {
        'ztfg': 'ztfg_eff.txt',
        'ztfr': 'ztfr_eff.txt',
        'ztfi': 'ztfi_eff.txt',
    }

    for bandname in bands.keys():
        fname = bands[bandname]
        b = np.loadtxt(os.path.join(bandpass_dir, fname))
        band = sncosmo.Bandpass(b[:, 0], b[:, 1], name=bandname)
        sncosmo.registry.register(band, force=True)
Exemple #8
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 bolometric_bandpass(sncosmo_source_or_model):
    """
    create a sncosmo.Bandpass instance that has transmission of 1
    for the whole spectral range od the model or the source given
    :param sncosmo_source_or_model:
    :return:
    """

    transmission = [1, 1]
    src_wavelength = [
        sncosmo_source_or_model.minwave(),
        sncosmo_source_or_model.maxwave()
    ]
    src_bandpass = sncosmo.Bandpass(src_wavelength,
                                    transmission,
                                    name='complete band')
    return src_bandpass