コード例 #1
0
 def setup_class(self):
     # Create a TimeSeriesSource with a flat spectrum at all times.
     phase = np.linspace(0., 100., 10)
     wave = np.linspace(1000., 10000., 100)
     flux = np.ones((len(phase), len(wave)), dtype=np.float)
     source = sncosmo.TimeSeriesSource(phase, wave, flux)
     self.model = sncosmo.Model(source=source)
コード例 #2
0
ファイル: problem.py プロジェクト: dannygoldstein/bolomc
    def __init__(
            self,
            sedw,
            rv,
            ebv,  # "True parameter values."
            z,
            mwebv,  # "True parameter values."
            dust_type=sncosmo.OD94Dust,
            template=hsiao):

        self.template = template
        p = self.template._phase
        l = self.template._wave
        flux = self.template.flux(p, l)

        try:
            sedw.__call__
        except AttributeError:
            wflux = sedw * flux
        else:
            self.wsurf = np.asarray([[sedw(pp, ll) for ll in l] for pp in p])
            wflux = self.wsurf * flux
        self.source = sncosmo.TimeSeriesSource(p, l, wflux)

        self.rv = rv
        self.ebv = ebv
        self.z = z
        self.dust_type = dust_type
        self.mwebv = mwebv
コード例 #3
0
ファイル: test_models.py プロジェクト: wmwv/sncosmo
def flatsource():
    """Create and return a TimeSeriesSource with a flat spectrum == 1.0 at
    all times."""
    phase = np.linspace(0., 100., 10)
    wave = np.linspace(800., 20000., 100)
    flux = np.ones((len(phase), len(wave)), dtype=np.float)
    return sncosmo.TimeSeriesSource(phase, wave, flux)
コード例 #4
0
 def to_sn_model(self):
     try:
         source = sncosmo.TimeSeriesSource(self.warped_phase,self.warped_wave,self.warped_flux)
     except:
         print("Could not create sncosmo model, have you created warped data yet?")
     self.sn_model = sncosmo.Model(source)
     return(self.sn_model)
コード例 #5
0
ファイル: models.py プロジェクト: srodney/sntd
def _param_to_source(source,
                     wave,
                     color_curve=None,
                     band1=None,
                     band2=None,
                     ref_color=False):
    band = None
    for b in np.unique(source.lc['band']):
        temp = sncosmo.get_bandpass(b)
        if temp.minwave() <= min(wave) and temp.maxwave() >= max(wave):
            band = sncosmo.get_bandpass(b)
    if band is None:
        raise RuntimeError(
            "Hmm, your data do not contain the band you want to fit.")
    finalPhase = source._phase
    if color_curve is not None and not ref_color:
        zp1 = source.lc['zp'][source.lc['band'] == band1][0]
        zp2 = source.lc['zp'][source.lc['band'] == band2][0]
        flux1 = sncosmo.Model(source._ts_sources[band1]).bandflux(
            band1, source._phase, zp1,
            source.lc['zpsys'][source.lc['band'] == band1][0])

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

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

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

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

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

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

    out = sncosmo.TimeSeriesSource(np.array(finalPhase),
                                   np.array(finalWave),
                                   np.array(finalFlux),
                                   zero_before=False)
    return (out)
コード例 #6
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'
コード例 #7
0
def model_(phase=0, wave=0, cos_theta=0, flux=0, viewingangle_dependece=True):
    '''phase, wave, cos_theta and flux are 1D arrays with the same length'''
    if viewingangle_dependece:
        source = AngularTimeSeriesSource(phase, wave, cos_theta, flux)
    else:
        source = sncosmo.TimeSeriesSource(phase, wave, flux)
    dust = sncosmo.CCM89Dust()
    return sncosmo.Model(source=source,
                         effects=[dust, dust],
                         effect_names=['host', 'MW'],
                         effect_frames=['rest', 'obs'])
コード例 #8
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
コード例 #9
0
ファイル: cc_extrap.py プロジェクト: Zeklandia/snsed
def createSNSED(filename,rescale=False):
    """
    Creates an sncosmo.Source object from a timeseries source (flux in photons/s/cm^2 as in sncosmo,assumes the file
    is in ergs though)

    :param filename: Name of file containing the timerseries source
    :type filename: str
    :param rescale: If you want to rescale the flux so that it is in photons at the end instead of ergs (divides by ergs/AA
    :type rescale: Boolean, optional
    :returns: ncosmo.Source object
    """
    phase,wave,flux=sncosmo.read_griddata_ascii(filename)
    if rescale:
        for i in range( len(phase) ) :
            flux[i]=flux[i]/sncosmo.constants.HC_ERG_AA
    return(sncosmo.TimeSeriesSource(phase,wave,flux,zero_before=True,name=os.path.basename(filename)))
    #return(snSource(phase,wave,flux,name=os.path.basename(filename)))
def sncosmo_source(source_path):
    """
    create a sncosmo.TimeSeriesSource from a file
    :param source_path: str, path to the file
    :return: sncosmo.TimeSeriesSource
    """

    # read the file
    sed = Table(np.loadtxt(source_path), names=['phase', 'wl', 'flux'])

    # extract phase, wavelength and flux
    phase = np.unique(sed['phase'])
    disp = np.unique(sed['wl'])
    flux = sed['flux'].reshape(len(phase), len(disp))

    # create the TimeSeriesSource
    snc_source = sncosmo.TimeSeriesSource(phase, disp, flux, zero_before=True)

    return snc_source
コード例 #11
0
#   phase0 wls2 flux
# ....
#   phaseN wlsN-1 flux
#   phaseN wlsN flux
## We need to adapt the format to build the sncosmo class TimeSeriesSource

for tmpl in tmpl_host_extinction_corrected[:]:
    tmpl_name = tmpl.replace('.SED', '')
    phase_raw, wls_raw, flux_raw = np.genfromtxt(
        pycoco_dir + 'Templates_HostCorrected/' + tmpl, unpack=True)
    wls = np.unique(wls_raw)
    phase = phase_raw[::len(wls)]
    flux_reshaped = flux_raw.reshape(len(phase), len(wls))
    source = sncosmo.TimeSeriesSource(phase,
                                      wls,
                                      flux_reshaped,
                                      zero_before=True,
                                      name=tmpl_name)
    sncosmo.register(source, name=tmpl_name)
    print(
        tmpl_name,
        '(type %s) registered!' % name2type[tmpl_name.replace('pycoco_', '')])

for tmpl in tmpl_host_extinction_NOTcorrected[:]:
    tmpl_name = tmpl.replace('.SED', '')
    phase_raw, wls_raw, flux_raw = np.genfromtxt(
        pycoco_dir + 'Templates_noHostCorr/' + tmpl, unpack=True)
    wls = np.unique(wls_raw)
    phase = phase_raw[::len(wls)]
    flux_reshaped = flux_raw.reshape(len(phase), len(wls))
    source = sncosmo.TimeSeriesSource(phase,
コード例 #12
0
ファイル: perturber_io.py プロジェクト: jpierel14/BYOSED
def kaepora_to_sed(data_folder,
                   perturber_keys,
                   base_sed='hsiao',
                   minWave=0,
                   maxWave=np.inf,
                   minPhase=-np.inf,
                   maxPhase=np.inf,
                   waveStep=10,
                   scale_band='bessellb'):
    waves = {}
    trans = {}
    dwaves = {}
    for b in ['bessellb', 'bessellv', 'bessellr']:
        band = sncosmo.get_bandpass(b)
        wave, dwave = integration_grid(band.minwave(), band.maxwave(),
                                       MODEL_BANDFLUX_SPACING)
        waves[b] = wave
        dwaves[b] = dwave
        trans[b] = band(wave)
    if isinstance(base_sed, str):
        base_sed = sncosmo.Model(base_sed)

    base_sed_wave = base_sed._source._wave

    filelists = []
    for k in perturber_keys:
        filelists.append(glob.glob(os.path.join(data_folder, '*%s*' % k)))

    seds = {}
    phase_pairs = {}
    phase_lists = {}
    scale_factors = {}
    for i in range(len(filelists)):
        filelist = filelists[i]
        temp_key = perturber_keys[i]
        temp_phase = []

        j = 0
        for f in filelist:
            dat = ascii.read(f)

            phase = f[f.find('phase=') + 6:f.find('phase=') + 6 +
                      (f[f.find('phase=') + 6:]).find('_')]

            phase = -1 * float(phase[1:]) if phase[0] == 'm' else float(
                phase[1:])

            temp_phase.append(phase)

            dat = dat[dat['Wavelength'] >= minWave]
            dat = dat[dat['Wavelength'] <= maxWave]

            if i == 0:
                key_phase = np.round(phase, 2)
                phase_pairs[key_phase] = [{
                    'wave':
                    dat['Wavelength'],
                    'flux':
                    dat['Flux'],
                    'interp':
                    interp1d(dat['Wavelength'], dat['Flux'], kind='cubic')
                }]

            else:
                pair_list = np.array(list(phase_pairs.keys()))
                match = pair_list[np.abs(pair_list - phase).argmin()]
                key_phase = np.round(match, 2)
                phase_pairs[key_phase].append({
                    'wave':
                    dat['Wavelength'],
                    'flux':
                    dat['Flux'],
                    'interp':
                    interp1d(dat['Wavelength'], dat['Flux'], kind='cubic')
                })

            if np.min(np.abs(dat['Flux'] - 10)) < .001:
                scale_factors[key_phase] = _get_kaepora_scale(
                    phase_pairs[key_phase][i]['interp'], base_sed, waves,
                    trans, dwaves, key_phase)

        if len(np.unique(temp_phase)) != len(temp_phase):
            print('You have more than one file for at least one phase.')
            sys.exit(1)

        phase_lists[temp_key] = temp_phase

    final_wavelength = np.arange(base_sed_wave[0],
                                 base_sed_wave[-1] + waveStep / 10, waveStep)
    to_save = {}
    for j in range(len(perturber_keys)):

        temp_phase = np.array(phase_lists[perturber_keys[j]])
        bound_inds = np.where(
            np.logical_and(temp_phase >= minPhase, temp_phase <= maxPhase))[0]
        final_phase = np.sort(temp_phase[bound_inds])
        pair_list = np.array(list(phase_pairs.keys()))
        match = np.round(
            np.array([
                pair_list[np.abs(pair_list - phase).argmin()]
                for phase in final_phase
            ]), 2)

        final_flux = []
        for i in range(len(match)):
            scaled_flux = interp1d(phase_pairs[match[i]][j]['wave'],
                                   phase_pairs[match[i]][j]['flux'] *
                                   scale_factors[match[i]],
                                   kind='cubic')
            to_save[final_phase[i]] = scale_factors[match[i]]

            temp = np.zeros(len(final_wavelength))
            for w in range(len(final_wavelength)):
                if final_wavelength[w] < np.min(phase_pairs[
                        match[i]][j]['wave']) or final_wavelength[w] > np.max(
                            phase_pairs[match[i]][j]['wave']):
                    temp[w] = base_sed._source._flux(final_phase[i],
                                                     final_wavelength[w])
                else:
                    temp[w] = scaled_flux(final_wavelength[w])
            final_flux.append(temp)
        seds[perturber_keys[j]] = [
            np.sort(final_phase), final_wavelength,
            sncosmo.TimeSeriesSource(final_phase, final_wavelength,
                                     np.array(final_flux))
        ]

    return (seds)
コード例 #13
0
def getMagSpec(filename,band,model,theta=0.0,redshift=0.0):
    #u = np.genfromtxt(opts.name)

    if "bulla" in filename and "hdf5" in filename:
        with h5py.File(os.path.join(filename), "r") as f:
            data = f['spectra']
            stokes = np.array(data['stokes'])
            t_d = np.array(data['time']) / (60*60*24) # get time in days
            wave = np.array(data['wave'])  # wavelength spec w/ redshift
        dMpc = 1e-5
        Dcm = 10*3.0857e16*100
        I = stokes[:,:,:,0] * (1./dMpc)**2 # get I stokes parameter

        Nobs = stokes.shape[0] # num observing angles
        cos = np.linspace(0,1,Nobs)
        thetas = np.rad2deg(np.arccos(cos))
        idx = np.argmin(np.abs(thetas-theta))

        fl = I[idx]
        source = sncosmo.TimeSeriesSource(t_d,wave,fl)
        bp = sncosmo.Bandpass(band[:,0], band[:,1])
        mag_d = source.bandmag(bp,"ab",t_d)

        L_d = np.trapz(fl*(4*np.pi*D_cm**2),x=wave)
        
        ii = np.where(~np.isnan(mag_d))[0]
        if len(ii) > 1:
            f = interp.interp1d(t_d[ii], mag_d[ii], fill_value='extrapolate')
            mag_d = f(t_d)
        
        ii = np.where(np.isfinite(np.log10(L_d)))[0]
        f = interp.interp1d(t_d[ii], np.log10(L_d[ii]), fill_value='extrapolate')
        L_d = 10**f(t_d)
        
        mag_d = savgol_filter(mag_d,window_length=17,polyorder=3,mode='mirror')
        L_d = savgol_filter(L_d,window_length=17,polyorder=3,mode='mirror')
        
        return t_d, mag_d, L_d

    if "bulla" in filename:
        u2 = np.loadtxt(filename,skiprows=3)
        lines = [line.rstrip('\n') for line in open(filename)]
        lineSplit = lines[2].split(" ")
        nt, t0, tf = int(lineSplit[0]), float(lineSplit[1]), float(lineSplit[2])
        dlogt = (np.log(tf)-np.log(t0)) / float(nt)

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

        ntheta, nwave = int(lines[0]), int(lines[1])
        if not np.isnan(theta) and ntheta > 1:
            costhetas = np.linspace(0,1,ntheta)
            thetas = np.rad2deg(np.arccos(costhetas))
            idx = np.argmin(np.abs(thetas-theta))
            istart, iend = int(idx*nwave), int((idx+1)*nwave)

            u = []
            for ii, t in enumerate(tt):
                if model in ["bulla_blue_cone","bulla_red_ellipse"]:
                    if (t > 6) or (t<1): continue
                for row in u2[istart:iend]:
                    u.append([t,row[0],row[int(ii+1)]])
            u = np.array(u)
        else:
            u = []
            for ii, t in enumerate(tt):
                for row in u2:
                    u.append([t,row[0],row[int(ii+1)]])
            u = np.array(u)
    else:
        u = np.loadtxt(filename,skiprows=1)
    if model == "kilonova_wind_spectra":
        u = u[u[:,2]==0.05] 

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

    if model == "kilonova_wind_spectra":
        u[:,3] /= (4*np.pi*D_cm**2) # F_lam (erg/s/cm2/A at 10pc)
        u[:,0] /= (24*3600) # time in days
    else:
        u[:,2] /= (4*np.pi*D_cm**2) # F_lam (erg/s/cm2/A at 10pc)
        u[:,0] /= (24*3600) # time in days

    t = u[0,0]

    w=[]
    L=[]
    #print(band[:,0])
    S = 0.1089/band[:,0]**2

    S1 = S*band[:,1]

    ZP = np.trapz(S1,x=band[:,0])

    t_d = []
    mag_d = []
    L_d = []

    for enum,i in enumerate(u):
        if i[0]==t:
            if model == "kilonova_wind_spectra":
                w.append(i[1])
                L.append(i[3])
            else:
                w.append(i[1])
                L.append(i[2])
        else:
            w = np.array(w)
            L = np.array(L)
            if not np.isnan(redshift):
                w = w*(1+redshift)

            spec = np.array(list(zip(w,L)))
            spec1 = easyint(spec[:,0],spec[:,1],band[:,0])
            conv = spec1*band[:,1]
            flux = np.trapz(conv,x=band[:,0])
            mag = -2.5*np.log10(flux/ZP)
            Lbol = np.trapz(spec[:,1]*(4*np.pi*D_cm**2),x=spec[:,0])

            if not np.isfinite(mag):
                mag = np.nan
            w=[]
            L=[]
            t=i[0]

            t_d.append(t)
            mag_d.append(mag)
            L_d.append(Lbol)

    t_d = np.array(t_d)
    mag_d = np.array(mag_d)
    L_d = np.array(L_d)

#    if model in ["bulla_1D","bulla_2D","bulla_2Component_lfree","bulla_2Component_lrich","bulla_2Component_lmid","macronovae-rosswog","bulla_2Component_lnsbh","bulla_blue_cone","bulla_red_ellipse","bulla_opacity","bulla_reprocess","KasenLike_2D","RosswogLike_2D"]:
#        #print(mag_d)
#        ii = np.where(~np.isnan(mag_d))[0]
#        f1 = interp.interp1d(t_d[ii], mag_d[ii])
#        f = extrap1d(f1,4)
#        mag_d = f(t_d)
#        #print(mag_d)
#        L_d = np.log10(L_d)
#        ii = np.where((L_d > 0) & (t_d < 10))[0]
#        #print(L_d,ii)
#        f1 = interp.interp1d(t_d[ii], L_d[ii], fill_value='extrapolate')
#        L_d = 10**f1(t_d)
#        #print(L_d)
#        ii = np.where((mag_d > 0.0) & (t_d > 2))[0]
#        if len(ii) > 0:
#            dm_dt = (mag_d[ii[0]] - mag_d[ii[0]-5])/(t_d[ii[0]] - t_d[ii[0]-5])
#            mag_d[ii[0]:] = mag_d[ii[0]] + (t_d[ii[0]:] - t_d[ii[0]])*dm_dt
#

#        mag_d_medfilt = scipy.signal.medfilt(mag_d)
#        L_d_medfilt = scipy.signal.medfilt(np.log10(L_d))

#        mag_d = mag_d_medfilt
#        L_d = 10**L_d_medfilt

    ii = np.where(~np.isnan(mag_d))[0]
    if len(ii) > 1:
        f = interp.interp1d(t_d[ii], mag_d[ii], fill_value='extrapolate')
        mag_d = f(t_d)

    ii = np.where(np.isfinite(np.log10(L_d)))[0]
    f = interp.interp1d(t_d[ii], np.log10(L_d[ii]), fill_value='extrapolate')
    L_d = 10**f(t_d)
    
    mag_d = savgol_filter(mag_d,window_length=17,polyorder=3,mode='mirror')
    L_d = savgol_filter(L_d,window_length=17,polyorder=3,mode='mirror')

    return t_d, mag_d, L_d
コード例 #14
0
    synbands.append(sncosmo.Bandpass(lams, [1., 1.], name='tophat' + name))

names168 = [line.split()[0] for line in open('table.txt')]
dic_meta = cPickle.load(open("CABALLOv2/META.pkl"))
ans = []
for sn in names168:
    meta = dic_meta[sn]
    for nm in meta['spectra']:
        spec = meta['spectra'][nm]
        if abs(spec['salt2.phase']) < 2.5:
            name = "CABALLOv2/" + spec['idr.spec_merged']
            spectra = read_fits.read_fits_spectrum1d(
                name, dispersion_unit='angstrom')


            model0 = sncosmo.TimeSeriesSource(numpy.array([0.,1,2]), spectra.dispersion.value/(1+meta['salt2.Redshift']), \
                numpy.tile(spectra.flux.value,(3,1)))
            dust = sncosmo.F99Dust(r_v=2.5)
            dust.set(ebv=0.01)
            model = sncosmo.Model(source=model0,
                                  effects=[dust],
                                  effect_names=['host'],
                                  effect_frames=['rest'])
            try:

                A = -2.5 * numpy.log10(
                    model.bandflux(synbands, 0.) /
                    model0.bandflux(synbands, 0.))
                ans.append(A[1] / (A[0] - A[1]))
            except:
                pass
コード例 #15
0
                    # Redshift SEDs
                    w *= (1 + z)

                    ph = []
                    fl = np.ones((Ntime, len(w)))

                    for itime in range(0, Ntime):

                        time = ti + step_time * (itime + 0.5
                                                 )  #+ ph_data[0] + tshift
                        I = a[0:Nwave, 1 + itime * 3] * (1. / dMpc)**2

                        ph.append(time)
                        fl[itime] = I

                    source = sncosmo.TimeSeriesSource(ph, w, fl)
                    m = source.bandmag(filters[ifilt], "ab", ph)
                    fmodel = 10**(-m / 2.5)

                    # Compare model to data
                    phdata = ph_data_all[ifilt]
                    mdata = data_all[ifilt]
                    mdataerr = dataerr_all[ifilt]
                    fdata = 10**(-mdata / 2.5)
                    fdataerr = log(10) * fdata * mdataerr

                    for idata in range(0, len(phdata)):
                        #if (phdata[idata] < ep_max):

                        diff = fabs(np.array(ph) - phdata[idata])
                        ind = np.where(diff == min(diff))[0][0]
コード例 #16
0
#                   Light Curves
#--------------------------------------------------------------------------------------------------------------

#   ************************
#   * Premier filtre choisi*
#   ************************

filter_1 = f'sdss::{f1}'
m_1 = np.zeros((nb_obs, Nstep), dtype=list)

for l in range(nb_obs):
    fluxes_l = np.zeros((Nstep, nb_bins), dtype=list)
    for i in index:
        fluxes_l[i] = (intensity[l, i])

    source_l = sn.TimeSeriesSource(ph, wave, fluxes_l)
    m_1[l, :] = list(source_l.bandmag(filter_1, "ab", ph))

m_direct_1 = np.zeros((nb_obs, Nstep), dtype=list)
for l in range(nb_obs):
    fluxes_l_direct = np.zeros((Nstep, nb_bins), dtype=list)
    for i in index:
        fluxes_l_direct[i] = (intensity_direct[l, i])

    source_l_direct = sn.TimeSeriesSource(ph, wave, fluxes_l_direct)
    m_direct_1[l, :] = list(source_l_direct.bandmag(filter_1, "ab", ph))

m_other_1 = np.zeros((nb_obs, Nstep), dtype=list)
for l in range(nb_obs):
    fluxes_l_other = np.zeros((Nstep, nb_bins), dtype=list)
    for i in index:
コード例 #17
0
errimport numpy as np
import scipy as sp
import matplotlib.pyplot as plt
from scipy.interpolate import interp1d
from scipy import stats
import pandas as pd
from pylab import *
import time
import os
import sncosmo
import matplotlib.cm as cm
import pandas as pd
import matplotlib.gridspec as gridspec
import numpy.ma as ma
import extinction
import myfunc as mf

plt.rcdefaults()
plt.rc('lines', linewidth=1.5)
plt.rc('axes', labelsize=19)
plt.rc('xtick', labelsize=19)
plt.rc('ytick', labelsize=19)
plt.rc('text', usetex=True)
plt.rc('font',family='serif')
plt.rc('font', serif='Times')
plt.rc("legend", fontsize=10.5)

home = "/Users/linaissa/documents/ARPE/my_work/opacities_I/simulations/outputs/"

directory = "outputs_nph5/"
コード例 #18
0
disp = np.linspace(1000., 9000., wavelength_points)

# Below, the flux array is made and manipulated across different times and wavelengths. These can be changed, or
# inputted manually, changing the final plots.
x = np.arange(wavelength_points)
flux = []
for i in range(1, time_points + 1):
    flux.append(x * i)
flux = np.array(flux)

for i in range(wavelength_points):
    for z in flux:
        z[i] += i

# Set the created arrays as model
model = sncosmo.TimeSeriesSource(phase, disp, flux)

# Plot the graph of observed luminosity through different filters over time
timearray = np.arange(2455454.88645 - 120., 2455454.88645 + 120, 0.01)

# Registering ptf48r filter
import os
import sys
sys.path.append(os.path.abspath('..'))
import Bandpass

# Plotting relative flux against time
filters = ['ptf48r', 'bessellr', 'bessellv', 'bessellb']
colors = ['black', 'red', 'green', 'blue']
for i in range(len(filters)):
    plt.scatter(timearray,
コード例 #19
0
ファイル: cc_extrap.py プロジェクト: Zeklandia/snsed
def extendCC(colorTable,colorCurveDict,snType,outFileLoc='.',bandDict=_filters,colorExtreme='median',colors=None,zpsys='AB',
             sedlist=None,showplots=None,verbose=True,UVoverwrite=False,IRoverwrite=True,specList=None,specName=None):
    """
    Function used at top level to extend a core-collapse SED.

    :param colorTable: Colortable made by colorCalc.curveToColor
    :type colorTable: astropy.Table
    :param colorCurveDict: Dictionary of color curves, such as made by fitColorCurve
    :type colorCurveDict: dict
    :param snType: SN classification for SED(s)
    :type snType: str
    :param outFileLoc:  Place you want the new SED to be saved, default current directory
    :type outFileLoc: str,optional
    :param bandDict: sncosmo bandpass for each band used in the fitting/table generation
    :type bandDict: dict,optional
    :param colorExtreme: 'blue,'median','red' describes which curve extreme to use
    :type colorExtreme: str,optional
    :param colors: Colors you would like to use for extrapolation
    :type colors: list or None,optional
    :param zpsys: Magnitude system
    :type zpsys: str,optional
    :param sedlist: list of SEDs to extrapolate, if None then uses all SEDs in SNDATA_ROOT
    :type sedlist: list or None,optional
    :param showplots: If you would like to see plots as they're extrapolated
    :type showplots: Boolean,optional
    :param verbose: Printing on?
    :type verbose: Boolean, optional
    :param UVoverwrite: Whether you would like to overwrite existing UV data
    :type UVoverwrite: Boolean,options
    :param IRoverwrite: Whether you would like to overwrite existing IR data
    :type IRoverwrite: Boolean,optional
    :param specList: A list of spectra to use in an average
    :type specList: list, optional
    :param specName: The name of a spectrum to use.
    :type specName: str, optional
    :returns: Saves extrapolated SED to outFileLoc, and returns an sncosmo.Source SED from the extrapolated timeseries.
    """
    colorTable=_standardize(colorTable)

    if not isinstance(colorTable,Table):
        raise RuntimeError('Colors argument must be an astropy table.')

    for band in bandDict:
        if not isinstance(bandDict[band],sncosmo.Bandpass):
            bandDict=_bandCheck(bandDict,band)
    if not colors:
        print("No extrapolation colors defined, assuming: ",colorCurveDict.keys())
        colors=[x for x in colorCurveDict.keys() if 'U-' in x]+[x for x in colorCurveDict.keys() if '-J' in x]+[x for x in colorCurveDict.keys() if '-H' in x]+[x for x in colorCurveDict.keys() if '-K' in x]
    else:
        tempColors=[x for x in colors if 'U-' in x]+[x for x in colors if '-J' in x]+[x for x in colors if '-H' in x]+[x for x in colors if '-K' in x]
        if len(tempColors)>4:
            raise RuntimeError("Only can do 4 colors!")


    bands=append([col[0] for col in colors],[col[-1] for col in colors])
    for band in _filters.keys():
        if band not in bandDict.keys() and band in bands:
            bandDict[band]=sncosmo.get_bandpass(_filters[band])
    if not sedlist:
        sedlist = glob.glob(os.path.join(sndataroot,"snsed","NON1A","*.SED"))
    else:
        sedlist=[sedlist] if not isinstance(sedlist,(tuple,list)) else sedlist
        sedlist=[os.path.join(sndataroot,"snsed","NON1A",sed) for sed in sedlist]
    returnList=[]


    for sedfile in sedlist:

        phase,wave,flux=sncosmo.read_griddata_ascii(sedfile)
        #bbWave,blackbody=getBB(phase,wave,flux)
        #blackbody=sncosmo.Model(source=sncosmo.TimeSeriesSource(phase,bbWave,blackbody))

        origWave=_getWave(sedfile,bandDict,colors)



        #phase,wave,flux=sncosmo.read_griddata_ascii(sedfile)
        bbWave,blackbody=getBB(phase,wave,flux,os.path.basename(sedfile)[:-4])


        blackbody=sncosmo.Model(source=sncosmo.TimeSeriesSource(phase,bbWave,blackbody))
        newsedfile=os.path.join(outFileLoc,os.path.basename(sedfile))
        if verbose:
            print("EXTRAPOLATING %s"%os.path.basename(newsedfile))
        once=False
        boundUV=False
        boundIR=False
        bandsDone=[]

        for color in colors:
            if verbose:
                print('     Running %s extrapolation.'%color)
            if color[0] not in bandDict.keys():
                raise RuntimeError('Band "%s" defined in color "%s", but band is not defined.')
            if color[-1] not in bandDict.keys():
                raise RuntimeError('Band "%s" defined in color "%s", but band is not defined.')


            extremeColors=dict([])

            extremeColors['blue'],extremeColors['median'],extremeColors['red']=_getExtremes(colorCurveDict[color]['time'],colorCurveDict[color][color],colorTable,color)
            if sncosmo.get_bandpass(_filters[color[0]]).wave_eff>_UVrightBound:
                shiftedCurve=_shiftCurve(colorCurveDict[color]['time'],extremeColors,blackbody,color,zpsys)
            else:
                shiftedCurve=extremeColors
            tempMask=colorTable[color].mask

            colorTable[color].mask=tempMask
            if once:
                sedfile=newsedfile
            tempTable=colorTable[~colorTable[color].mask]
            UV,IR=_extrapolatesed(sedfile,newsedfile,color,tempTable,colorCurveDict[color]['time'],shiftedCurve[colorExtreme], bandDict,zpsys,bandsDone,UVoverwrite,IRoverwrite,niter=50)
            if UV:
                boundUV=True
                bandsDone.append(color[0])
            if IR:
                boundIR=True
                bandsDone.append(color[-1])
            once=True

        #_addCCSpec(snType,newsedfile,origWave,specList,specName)
        #phase,wave,flux=sncosmo.read_griddata_ascii(newsedfile)
        #temp=sncosmo.Model(sncosmo.TimeSeriesSource(phase,wave,flux))
        #for col in [('sdss::r','paritel::j'),('sdss::r','paritel::h'),('sdss::r','paritel::ks')]:
        #    print(temp.color(col[0],col[1],'vega',0),blackbody.color(col[0],col[1],'vega',0))

        if showplots:
            plotSED(newsedfile,day=showplots)
            plt.show()
            plt.close()
        if boundUV:
            _boundUVsed(newsedfile)
        if boundIR:
            _boundIRsed(newsedfile)
        if verbose:
            print("     Done with %s.\a\a\a"%os.path.basename(sedfile))
        returnList.append(createSNSED(newsedfile))

    if len(returnList)>1:
        return returnList
    return returnList[0]
コード例 #20
0
for i in index:
    intensity_ref.append(list(np.genfromtxt(fname=file_ref, skip_header=3, max_rows=nb_bins, dtype='float', usecols= (1+ i*3))/(16*100)))    # factor of scale at 40 Mpc


#--------------------------------------------------------------------------------------------------------------
#                   Light Curves
#--------------------------------------------------------------------------------------------------------------

filter = ['sdss::g','sdss::r', 'sdss::i','swope2::h']
#filter = ['sdss::g']
m_ref = []
for (f, band) in enumerate(filter):
    fluxes_ref = np.zeros((Nstep, nb_bins),dtype=list)
    for i in index:
        fluxes_ref[i,:] = intensity_ref[i] # list des intensités I_lambda pour un temps donné
    source_ref = sn.TimeSeriesSource(ph,wave,fluxes_ref)
    m_ref_f      = list(source_ref.bandmag(band,"ab",ph))
    m_ref.append(m_ref_f)



SimulationsData = []
    #for kappaLF in KappaLF:
for gammaLF in GammaLF:
    for kappaLR in KappaLR:
        for gammaLR in GammaLR:
            file_sim   = data_fold2 /f'nph1.0e+05_kappaLF{kappaLF}_gammaLF{gammaLF}_kappaLR{kappaLR}_gammaLR{gammaLR}_spec.txt'
            intensity_sim = []
            for i in index:
                intensity_sim.append(list(np.genfromtxt(fname=file_sim, skip_header=3, max_rows=nb_bins, dtype='float', usecols= (1+ i*3))/(16*100)))    # factor of scale at 40 Mpc
            m_sim = []
コード例 #21
0
import numpy as np
import sncosmo as sn
import matplotlib.pyplot as plt
import glob
import itertools

#********************************************

filenames = sorted(glob.glob('flux_spectra_*.txt'))
# ask nb_bins
nb_bins = 50
fluxes = []
wavelength = np.loadtxt(fname='flux_spectra_1day.txt', skiprows=1)[:, 2]
ph = np.array([1, 2, 4, 7])
filter = 'sdss::g'
for f in filenames:
    data = np.loadtxt(fname=f, skiprows=1)
    intensity = list(data[:, 1])
    fluxes.append(intensity)
source = sn.TimeSeriesSource(ph, wavelength, np.array(fluxes))
m = source.bandmag(filter, "ab", ph)
print(list(m))
コード例 #22
0
filter = ['sdss::g', 'sdss::r', 'sdss::i', 'swope2::h']
#filter = ['sdss::g']
m_old = []
m_new = []
for (f, band) in enumerate(filter):

    m_old_f = np.zeros((nb_obs, Nstep), dtype=list)
    m_new_f = np.zeros((nb_obs, Nstep), dtype=list)

    for l in range(nb_obs):
        fluxes_old_l = np.zeros((Nstep, nb_bins), dtype=list)
        fluxes_new_l = np.zeros((Nstep, nb_bins), dtype=list)
        for i in index:
            fluxes_old_l[i] = (intensity_old[l, i])
            source_old_l = sn.TimeSeriesSource(ph, wave, fluxes_old_l)
            fluxes_new_l[i] = (intensity_new[l, i])
            source_new_l = sn.TimeSeriesSource(ph, wave, fluxes_new_l)
        m_old_f[l, :] = list(source_old_l.bandmag(band, "ab", ph))
        m_new_f[l, :] = list(source_new_l.bandmag(band, "ab", ph))
    m_old.append(m_old_f)
    m_new.append(m_new_f)

#---------------------------------------------------------------------------------------------------------------
#               PLOT
#--------------------------------------------------------------------------------------------------------------

fig = plt.figure()
plt.subplots_adjust(
    wspace=0.15,
    hspace=0.2)  #wspace = écartement horizontal, #vspace=vertical ?
コード例 #23
0
ファイル: lc2.py プロジェクト: lina489/kilonovae
                          usecols=(1 + i * 3)) /
            (16 * 100))  # factor of scale at 40 Mpc

#--------------------------------------------------------------------------------------------------------------
#                   Light Curves
#--------------------------------------------------------------------------------------------------------------
filter = 'sdss::u'
#source = np.zeros((nb_obs,Nstep))
m = np.zeros((nb_obs, Nstep), dtype=list)

for l in range(nb_obs):
    fluxes_l = np.zeros((Nstep, nb_bins), dtype=list)
    for i in index:
        fluxes_l[i] = (intensity[l, i])
# print(f'observers number {l}', fluxes_l)
    source_l = sn.TimeSeriesSource(ph, wave, fluxes_l)
    m[l, :] = list(source_l.bandmag(filter, "ab", ph))  # génère une ndarray

#---------------------------------------------------------------------------------------------------------------
#               PLOT
#--------------------------------------------------------------------------------------------------------------

plt.rcParams['figure.figsize'] = [11, 11]  #[largeur, hauteur]
f = plt.figure()
plt.subplots_adjust(
    wspace=0.05,
    hspace=0.05)  #wspace = écartement horizontal, #vspace=vertical ?

X = [list(ph)] * a
dataX = list(np.copy(X))
dataX.append(X)
コード例 #24
0
filter = ['sdss::g', 'sdss::r', 'sdss::i', 'swope2::h']
#filter = ['sdss::g']
m_ref = []
m_sin = []
for (f, band) in enumerate(filter):

    m_ref_f = np.zeros((nb_obs, Nstep), dtype=list)
    m_sin_f = np.zeros((nb_obs, Nstep), dtype=list)

    for l in range(nb_obs):
        fluxes_ref_l = np.zeros((Nstep, nb_bins), dtype=list)
        fluxes_sin_l = np.zeros((Nstep, nb_bins), dtype=list)
        for i in index:
            fluxes_ref_l[i] = (intensity_ref[l, i])
            source_ref_l = sn.TimeSeriesSource(ph, wave, fluxes_ref_l)
            fluxes_sin_l[i] = (intensity_sin[l, i])
            source_sin_l = sn.TimeSeriesSource(ph, wave, fluxes_sin_l)
        m_ref_f[l, :] = list(source_ref_l.bandmag(band, "ab", ph))
        m_sin_f[l, :] = list(source_sin_l.bandmag(band, "ab", ph))
    m_ref.append(m_ref_f)
    m_sin.append(m_sin_f)

#---------------------------------------------------------------------------------------------------------------
#               PLOT
#--------------------------------------------------------------------------------------------------------------

fig = plt.figure()
plt.subplots_adjust(
    wspace=0.15,
    hspace=0.2)  #wspace = écartement horizontal, #vspace=vertical ?
コード例 #25
0
#--------------------------------------------------------------------------------------------------------------

filter = ['sdss::g','sdss::r', 'sdss::i','swope2::h']
#filter = ['sdss::g']
m_old = []
m_new = []
for (f, band) in enumerate(filter):

    m_old_f = np.zeros((nb_obs_old, Nstep_old), dtype=list)
    m_new_f = np.zeros((nb_obs_new, Nstep_new), dtype=list)

    for l in range(nb_obs_old):
        fluxes_old_l = np.zeros((Nstep_old, nb_bins_old),dtype=list)
        for i in index_old:
            fluxes_old_l[i] = (intensity_old[l,i])
            source_old_l = sn.TimeSeriesSource(ph_old,wave_old,fluxes_old_l)
        m_old_f[l,:]       = list(source_old_l.bandmag(band,"ab",ph_old))

    for l in range(nb_obs_new):
        fluxes_new_l = np.zeros((Nstep_new, nb_bins_new),dtype=list)
        for i in index_new:
            fluxes_new_l[i] = (intensity_new[l,i])
            source_new_l = sn.TimeSeriesSource(ph_new,wave_new,fluxes_new_l)
        m_new_f[l,:] =  list(source_new_l.bandmag(band,"ab",ph_new))

    m_old.append(m_old_f)
    m_new.append(m_new_f)