def magnitude_in_filter(filter, star, ext, AKs, atm, vega):
    """
    Using pysynphot objects and functions.

    filter = NIRC2Filter object (wave in angstrom)
    star = TabularSourceSpectrum object (wave in angstrom, flux in FLAMs)
    ext = CustomRedLaw object
    atm = EarthAtmosphere object (wave in angstrom)
    vega = Vega object (wave in angstrom, flux in FLAMs)
    """
    bandpass = filter

    if atm != None:
        bandpass *= atm

    vega_in_filter = obs.Observation(vega, bandpass, binset=filter.wave)
    vega_flux = vega_in_filter.binflux.sum()
    vega_mag = 0.03

    if ext != None and AKs > 0:
        bandpass *= extinction.reddening(AKs)

    star_in_filter = obs.Observation(star, bandpass, binset=filter.wave)
    star_flux = star_in_filter.binflux.sum()
    star_mag = -2.5 * math.log10(star_flux / vega_flux) + vega_mag

    return star_mag
Beispiel #2
0
def rebin_spec(spec, wavnew, waveunits='um'):
    from pysynphot import spectrum, observation
    # Gives same error answer: Err = np.array([np.sqrt(sum(spec[2].value[idx_include(wavnew,[((wavnew[0] if n==0 else
    #  wavnew[n-1]+wavnew[n])/2,wavnew[-1] if n==len(wavnew) else (wavnew[n]+wavnew[n+1])/2)])]**2)) for n in range(
    # len(wavnew)-1)])*spec[2].unit if spec[2] is not '' else ''
    if len(spec) == 2:
        spec += ['']
    try:
        Flx, Err, filt = spectrum.ArraySourceSpectrum(
            wave=spec[0].value,
            flux=spec[1].value), spectrum.ArraySourceSpectrum(
                wave=spec[0].value, flux=spec[2].value
            ) if spec[2] else '', spectrum.ArraySpectralElement(
                spec[0].value, np.ones(len(spec[0])), waveunits=waveunits)
    except:
        spec, wavnew = [i * q.Unit('') for i in spec], wavnew * q.Unit('')
        Flx, Err, filt = spectrum.ArraySourceSpectrum(
            wave=spec[0].value,
            flux=spec[1].value), spectrum.ArraySourceSpectrum(
                wave=spec[0].value, flux=spec[2].value
            ) if spec[2] else '', spectrum.ArraySpectralElement(
                spec[0].value, np.ones(len(spec[0])), waveunits=waveunits)
    return [
        wavnew,
        observation.Observation(Flx, filt, binset=wavnew.value,
                                force='taper').binflux * spec[1].unit,
        observation.Observation(Err, filt, binset=wavnew.value,
                                force='taper').binflux *
        spec[2].unit if spec[2] else np.ones(len(wavnew)) * spec[1].unit
    ]
Beispiel #3
0
def rebin_spec(wave, specin, wavnew):
    spec = spectrum.ArraySourceSpectrum(wave=wave, flux=specin)
    f = np.ones(len(wave))
    filt = spectrum.ArraySpectralElement(wave, f, waveunits='angstrom')
    obs = observation.Observation(spec, filt, binset=wavnew, force='taper')

    return obs.binflux
Beispiel #4
0
def spectra_rebin(wave,flux,rebin_wave):

    spect=spectrum.ArraySourceSpectrum(wave=wave.values,flux=flux.values)
    f = np.ones(len(wave))
    filt=spectrum.ArraySpectralElement(wave.values,f,waveunits='microns')
    obs=observation.Observation(spect,filt,binset=rebin_wave,force='taper')

    return obs.binflux
def rebin(new_wav, old_wav, flux):

    f_ = np.ones(len(old_wav))
    spec_ = pysynspec.ArraySourceSpectrum(wave=old_wav, flux=flux)
    filt = pysynspec.ArraySpectralElement(old_wav, f_, waveunits='angstrom')
    obs = observation.Observation(spec_, filt, binset=new_wav, force='taper')
    newflux = obs.binflux
    return newflux
Beispiel #6
0
def spec_res_downgrade(l_in, spec_in, l_out):
    templ_spec = spectrum.ArraySourceSpectrum(wave=l_in, flux=spec_in)
    white_filter = spectrum.ArraySpectralElement(l_out,\
    np.ones(len(l_out)), waveunits='angstrom')
    convolved_spec = observation.Observation(templ_spec,\
    white_filter, binset=l_out, force='taper').binflux

    return convolved_spec
Beispiel #7
0
def rebin_spec(wave, specin, wavnew):
    '''(inwave (ndarray),influx (ndarray),outwave(ndarray)-> outflux
    Correctly rebins spectra
    '''
    spec = spectrum.ArraySourceSpectrum(wave=wave, flux=specin)
    f = nu.ones(len(wave))
    filt = spectrum.ArraySpectralElement(wave, f, waveunits='angstrom')
    obs = observation.Observation(spec, filt, binset=wavnew, force='taper')

    return obs.binflux
Beispiel #8
0
def get_filter_info(name, vega=None):
    filt = pysynphot.ObsBandpass(name)

    vega_obs = observation.Observation(vega, filt, binset=filt.wave)

    # Vega_flux in Flam units.
    vega_flux = vega_obs.effstim('flam')
    vega_mag = 0.03

    return filt, vega_flux, vega_mag
def get_filter_info(name, earth=earth, vega=vega):
    filter = FilterNIRC2(name)

    earth2 = earth.resample(filter.wave)
    filter *= earth2

    vega_obs = obs.Observation(vega, filter, binset=filter.wave)
    vega_flux = vega_obs.binflux.sum()
    vega_mag = 0.03

    return filter, vega_flux, vega_mag
Beispiel #10
0
def rebin_spec(wavelength, flux, waveout, keepneg=False):
    spec = spectrum.ArraySourceSpectrum(wave=wavelength,
                                        flux=flux,
                                        keepneg=keepneg)
    f = np.ones(len(flux))
    filt = spectrum.ArraySpectralElement(wavelength.to(wavelength.unit).value,
                                         f,
                                         waveunits=str(wavelength.unit))
    obs = observation.Observation(spec, filt, binset=waveout, force='taper')

    return obs.binflux
def get_filter_info(name, vega=vega):
    filter = ObsBandpass(name)

    vega_obs = obs.Observation(vega, filter, binset=filter.wave, force='taper')
    vega_flux = vega_obs.binflux.sum()
    vega_mag = 0.03

    filter.flux0 = vega_flux
    filter.mag0 = vega_mag

    return filter
def mag_in_filter(star, filter, extinction, flux0, mag0):
    """
    Assumes that extinction is already resampled to same wavelengths
    as filter.
    """
    star_in_filter = obs.Observation(star,
                                     filter * extinction,
                                     binset=filter.wave)
    star_flux = star_in_filter.binflux.sum()
    star_mag = -2.5 * math.log10(star_flux / flux0) + mag0

    return star_mag
Beispiel #13
0
def rebin_spec(wave, specin, wavnew):
    '''	
	Given wavelength, a spectrum, and new wavelength array, this
    function resamples the spectrum to match new array.
	'''
    import numpy as np
    from pysynphot import observation
    from pysynphot import spectrum

    spec = spectrum.ArraySourceSpectrum(wave=wave, flux=specin, keepneg=True)
    f = np.ones(len(wave))
    filt = spectrum.ArraySpectralElement(wave, f, waveunits='angstrom')
    obs = observation.Observation(spec, filt, binset=wavnew, force='taper')
    return obs.binflux
Beispiel #14
0
def rebin_spec(wave, specin, wavnew):
    """
    Rebin spectra to bins used in wavnew.
    Ref: http://www.astrobetter.com/blog/2013/08/12/python-tip-re-sampling-spectra-with-pysynphot/
    """
    from pysynphot import observation
    from pysynphot import spectrum as pysynphot_spec
    import numpy as np

    spec = pysynphot_spec.ArraySourceSpectrum(wave=wave, flux=specin)
    f = np.ones(len(wave))
    filt = pysynphot_spec.ArraySpectralElement(wave, f, waveunits='angstrom')
    obs = observation.Observation(spec, filt, binset=wavnew, force='taper')

    return obs.binflux
def get_filter_info(name, vega=vega):
    if name.startswith('nirc2'):
        tmp = name.split(',')
        filterName = tmp[-1]
        filter = nirc2syn.filters[filterName]
        flux0 = nirc2syn.filter_flux0[filterName]
        mag0 = nirc2syn.filter_mag0[filterName]
    else:
        filter = ObsBandpass(name)

    vega_obs = obs.Observation(vega, filter, binset=filter.wave, force='taper')
    vega_flux = vega_obs.binflux.sum()
    vega_mag = 0.03

    filter.flux0 = vega_flux
    filter.mag0 = vega_mag

    return filter
Beispiel #16
0
def ABtoVega(instrument, bandpass):

    bp = ObsBandpass(str(instrument) + ',wfc1,'\
    + str(bandpass) + ',mjd#57754')
    spec_bb = BlackBody(10000)
    spec_bb_norm = spec_bb.renorm(1, 'counts', bp)
    obs = observation.Observation(spec_bb_norm, bp)

    # Get photometric calibration information.
    photflam = obs.effstim('flam')
    photplam = bp.pivot()

    zp_vega = obs.effstim('vegamag')
    zp_st = obs.effstim('stmag')
    zp_ab = obs.effstim('abmag')

    difference = zp_vega - zp_ab

    return difference
Beispiel #17
0
def test_binning_methods():
    """
    Compare the pysynphot binflux.sum() routine on filter integrations at different resolutions.
    Shows bug in routine: integrated flux depends on the filter resolution! 

    Fix: manually integrate the binned filter function. Shows that this method performs
    much better, getting nearly the same output flux for different filter resolutions,
    as we would expect
    """
    # We'll test an integration of the vega spectrum through the WFC3-IR F127M filter
    vega = synthetic.Vega()
    filt = pysynphot.ObsBandpass('wfc3,ir,f127m')

    # Convert to ArraySpectralElement for resampling.
    filt = spectrum.ArraySpectralElement(filt.wave,
                                         filt.throughput,
                                         waveunits=filt.waveunits)

    # Two rebinning schemes: one coarse and the other fine
    idx = np.where(filt.throughput > 0.001)[0]
    new_wave = np.linspace(filt.wave[idx[0]],
                           filt.wave[idx[-1]],
                           1500,
                           dtype=float)
    filt_fine = filt.resample(new_wave)

    wave_bin = vega.wave
    filt_bin = synthetic.rebin_spec(filt.wave, filt.throughput, wave_bin)
    filt_coarse = pysynphot.ArrayBandpass(wave_bin, filt_bin)

    # Do the filter integration in 2 methods: one with pysynphot binflux,
    # the other with manual integration
    vega_obs_fine = obs.Observation(vega,
                                    filt_fine,
                                    binset=filt_fine.wave,
                                    force='taper')
    vega_obs_coarse = obs.Observation(vega,
                                      filt_coarse,
                                      binset=filt_coarse.wave,
                                      force='taper')

    fine_binflux = vega_obs_fine.binflux.sum()
    coarse_binflux = vega_obs_coarse.binflux.sum()

    diff_f = np.diff(vega_obs_fine.binwave)
    diff_f = np.append(diff_f, diff_f[-1])
    fine_manual = np.sum(vega_obs_fine.binflux * diff_f)

    diff_c = np.diff(vega_obs_coarse.binwave)
    diff_c = np.append(diff_c, diff_c[-1])
    coarse_manual = np.sum(vega_obs_coarse.binflux * diff_c)

    print('**************************************')
    print('Integrated flux with binflux:')
    print('fine binning: {0}'.format(fine_binflux))
    print('coarse binning: {0}'.format(coarse_binflux))
    print('And with manual integration:')
    print('fine binning: {0}'.format(fine_manual))
    print('coarse binning: {0}'.format(coarse_manual))
    print('**************************************')

    pdb.set_trace()
    return
Beispiel #18
0
def etc_uh_roboAO(mag, filt_name, tint, sq_aper_diam=0.3, phot_sys='Vega', spec_res=100, 
                  seeing_limited=False):
    """
    Exposure time calculator for a UH Robo-AO system and a NIR IFU spectrograph.

    phot_sys - 'Vega' (default) or 'AB'
    """
    
    ifu_throughput = 0.35
    #ao_throughput = 0.55
    ao_throughput = 0.76  # New Design
    tel_throughput = 0.85**2

    if seeing_limited:
        sys_throughput = ifu_throughput * tel_throughput
    else:
        sys_throughput = ifu_throughput * ao_throughput * tel_throughput
    
    # TO DO Need to add telescope secondary obscuration to correct the area.
    tel_area = math.pi * (2.22 * 100. / 2.)**2   # cm^2 for UH 2.2m tel
    sec_area = math.pi * (0.613 * 100. / 2.)**2   # cm^2 for UH 2.2m tel hole/secondary obscuration
    tel_area -= sec_area
    
    read_noise = 3.0       # electrons
    dark_current = 0.01    # electrons s^-1

    # Get the filter
    if filt_name == 'Z' or filt_name == 'Y':
        filt = get_ukirt_filter(filt_name)
    else:
        filt = pysynphot.ObsBandpass(filt_name)

    # Calculate the wave set for the IFU. Include Nyquist sampled pixels.
    dlamda = (filt.avgwave() / spec_res) / 2.0
    ifu_wave = np.arange(filt.wave.min(), filt.wave.max()+dlamda, dlamda)

    # Estimate the number of pixels across our spectrum.
    npix_spec = len(ifu_wave)
    
    # Get the Earth transmission spectrum. Sample everything
    # onto this grid.
    earth_trans =  read_mk_sky_transmission()

    # Get the Earth background emission spectrum
    earth_bkg = read_mk_sky_emission_ir()
    earth_bkg.resample(ifu_wave)

    # Convert to Vega if in AB
    if phot_sys != 'Vega':
        mag += Vega_to_AB[filt_name]

    # Assume this star is an A0V star, so just scale a Vega spectrum
    # to the appropriate magnitude. Rescale to match the magnitude.
    # pysynphot.renorm() and pysynphot.setMagnitude are all broken.
    star = pysynphot.Vega.renorm(mag, 'vegamag', filt)  # erg cm^2 s^-1 A^-1

    # Observe the star and background through a filter and resample
    # at the IFU spectral sampling.
    star_obs = observation.Observation(star, filt, binset=ifu_wave)
    bkg_obs = observation.Observation(earth_bkg, filt, binset=ifu_wave, force="extrap")
    vega = pysynphot.FileSpectrum(pysynphot.locations.VegaFile)
    vega_obs = observation.Observation(vega, filt, binset=ifu_wave)

    # Propogate the star flux and background through the
    # atmosphere and telescope. 
    star_obs *= earth_trans                       # erg s^-1 A^-1 cm^-2
    star_obs *= tel_area * sys_throughput         # erg s^-1 A^-1
    vega_obs *= earth_trans                       # erg s^-1 A^-1 cm^-2
    vega_obs *= tel_area * sys_throughput         # erg s^-1 A^-1
    bkg_obs *= tel_area * sys_throughput          # erg s^-1 A^-1 arcsec^-2

    # Convert them into photlam
    star_obs.convert('photlam')            # photon s^-1 A^-1
    vega_obs.convert('photlam')
    bkg_obs.convert('photlam')             # photon s^-1 A^-1 arcsec^-2

    # Pull the arrays out of the Observation objects
    star_counts = star_obs.binflux
    bkg_counts = bkg_obs.binflux
    vega_counts = vega_obs.binflux
    
    # Integrate each spectral channel using the ifu_wave (dlamda defined above).
    star_counts *= dlamda                     # photon s^-1
    bkg_counts *= dlamda                      # photon s^-1 arcsec^-2
    vega_counts *= dlamda                     # photon s^-1 NO? arcsec^-2

    # Integrate over the aperture for the background and make
    # an aperture correction for the star.
    if seeing_limited:
        ee = get_seeing_ee(filt_name, sq_aper_diam)
    else:
        ee = get_roboAO_ee(mag, filt_name, sq_aper_diam)
        
    aper_area = sq_aper_diam**2               # square
    star_counts *= ee                         # photon s^-1
    # TODO... Don't I need to do this for vega as well?
    # vega_counts *= ee  
    bkg_counts *= aper_area                   # photon s^-1 arcsec^-2

    pix_scale = 0.150                      # arcsec per pixel
    if seeing_limited:
        pix_scale = 0.400
        
    npix = (aper_area / pix_scale**2)
    npix *= npix_spec

    vega_mag = 0.03
    star_mag = -2.5 * math.log10(star_counts.sum() / vega_counts.sum()) + vega_mag
    bkg_mag = -2.5 * math.log10(bkg_counts.sum() / vega_counts.sum()) + vega_mag
    
    signal = star_counts * tint               # photon
    bkg = bkg_counts * tint                   # photon
    
    noise_variance = signal.copy()
    noise_variance += bkg
    noise_variance += read_noise**2 * npix
    noise_variance += dark_current * tint * npix
    noise = noise_variance**0.5
    snr_spec = signal / noise
    
    # Calculate average signal-to-noise per spectral channel        
    avg_signal = signal.sum()
    avg_noise = noise.sum()
    avg_snr = avg_signal / avg_noise

    msg = 'filt = {0:s}  signal = {1:13.1f}  bkg = {2:9.1f}  SNR = {3:7.1f}'
    print msg.format(filt_name, avg_signal, bkg.mean(), avg_snr)

    # Inter-OH gives an overal reduction in background of
    # 2.3 mag at H - probably slightly less than this because this was with NIRSPEC
    # 2.0 mag at J

    # Do R=100
    # Do R=30
    
    return avg_snr, star_mag, bkg_mag, ifu_wave, signal, bkg, snr_spec
def ssp_rebin(logL_ssp, spec_ssp, dlogL_new, Lll=3250.):
    '''
    rebin a GRID of model spectrum to have an identical velocity
    resolution to an input spectrum

    intended to be used on a grid of models with wavelength varying
    along final axis (in 3d array)

    DEPENDS ON pysynphot, which may not be an awesome thing, but
        it definitely preserves spectral integrity, and does not suffer
        from drawbacks of interpolation (failing to average line profiles)
    '''
    dlogL_ssp = np.median(logL_ssp[1:] - logL_ssp[:-1])
    f = dlogL_ssp / dlogL_new

    # print 'zoom factor: {}'.format(f)
    # print 'new array should have length {}'.format(logL_ssp.shape[0]*f)

    # print spec_ssp.shape

    # we want to only sample where we're sure we have data
    CRVAL1_new = logL_ssp[0] - 0.5 * dlogL_ssp + 0.5 * dlogL_new
    CRSTOP_new = logL_ssp[-1] + 0.5 * dlogL_ssp - 0.5 * dlogL_new
    NAXIS1_new = int((CRSTOP_new - CRVAL1_new) / dlogL_new)
    # start at exp(CRVAL1_new) AA, and take samples every exp(dlogL_new) AA
    logL_ssp_new = CRVAL1_new + \
        np.linspace(0., dlogL_new*(NAXIS1_new - 1), NAXIS1_new)
    L_new = np.exp(logL_ssp_new)
    L_ssp = np.exp(logL_ssp)

    # now find the desired new wavelengths

    spec = spectrum.ArraySourceSpectrum(wave=L_ssp, flux=spec_ssp)
    f = np.ones_like(L_ssp)
    filt = spectrum.ArraySpectralElement(wave=L_ssp,
                                         throughput=f,
                                         waveunits='angstrom')
    obs = observation.Observation(spec, filt, binset=L_new, force='taper')
    spec_ssp_new = obs.binflux

    # the following are previous attempts to do this rebinning
    '''
    # first, interpolate to a constant multiple of the desired resolution
    r_interm = int(1./f)
    print r_interm
    dlogL_interm = f * dlogL_new
    print dlogL_interm

    CDELT1_interm = dlogL_interm
    CRVAL1_interm = logL_ssp[0] + 0.5*CDELT1_interm
    CRSTOP_interm = logL_ssp[-1] - 0.5*CDELT1_interm
    NAXIS1_interm = int((CRSTOP_interm - CRVAL1_interm) / CDELT1_interm)
    logL_ssp_interm = CRVAL1_interm + np.linspace(
        0., CDELT1_interm * (NAXIS1_interm - 1), NAXIS1_interm)
    edges_interm = np.column_stack((logL_ssp_interm - 0.5*CDELT1_interm,
                                    logL_ssp_interm + 0.5*CDELT1_interm))

    spec_interp = interp1d(logL_ssp, spec_ssp)
    spec_interm = spec_interp(logL_ssp_interm)
    print spec_interm.shape

    spec_ssp_new = zoom(spec_interm, zoom=[1., 1., 1./r_interm])[1:-1]
    logL_ssp_new = zoom(logL_ssp_interm, zoom=1./r_interm)[1:-1]
    print logL_ssp_new.shape'''
    '''s = np.cumsum(spec_ssp, axis=-1)
    # interpolate cumulative array
    s_interpolator = interp1d(x=logL_ssp, y=s, kind='linear')
    s_interpolated_l = s_interpolator(edges[:, 0])
    s_interpolated_u = s_interpolator(edges[:, 1])
    total_in_bin = np.diff(
        np.row_stack((s_interpolated_l, s_interpolated_u)), n=1, axis=0)
    spec_ssp_new = total_in_bin * (dlogL_new/dlogL_ssp)'''

    return spec_ssp_new, logL_ssp_new
def rebin_spec(wave, specin, wavnew):                                            # wavnew is the new wave grid
	spec = spectrum.ArraySourceSpectrum(wave=wave, flux=specin)                  # configures wave/spectrum for pysynphot
	f = np.ones(len(wave))                                                       # preserve all flux at all wavelengths (no throughput curve)
	filt = spectrum.ArraySpectralElement(wave, f, waveunits='angstrom')          # apply throughput curve 'filter' (not necessary for us?)
	obs = observation.Observation(spec, filt, binset=wavnew, force='taper')
	return obs.binflux