Пример #1
0
def get_synthetic_mag_bb(T, mag_in, filt_in="sdss,r", system_in="vegamag", filt_out="sdss,g", system_out="vegamag"):
    '''
    Provided a black body temperature, it normalizes the emission to one input magnitude
    in a given photometric system, and produces another synthetic magnitude in the output
    band and photometric system.
    
    Parameters
    ----------
    T : float
        Black body temperature
    mag_in: float
        magnitude that the black body spectrum will be normalized to
    filt_in: string
        Name of the band where the input magnitude is in.
    system_in: photometric system for the input mangitude (agmag, vegamag, stmag...)
    filt_out: string
        Name of the band where the out magnitude will be computed.
    system_out: photometric system for the output mangitude (agmag, vegamag, stmag...)
    
    Returns
    -------
    mag : float
        The synthetic magnitude of the black body spectrum for that photometric band and system.
    
    
    Examples
    --------
    >>> phot_utils.get_filter_mag_bb(6000, 19, "V", "vegamag", "sdss,g", "abmag")
    >>> 19.311307758370692
    '''
    
    sp = ps.BlackBody(T)
    sp.convert('flam')
        
    if (filt_in in banddic.keys()):
        bp_in = ps.FileBandpass(banddic[filt_out])
    else:
        bp_in = ps.ObsBandpass(filt_out)
        
    if (filt_out in banddic.keys()):
        bp_out = ps.FileBandpass(banddic[filt_out])
    else:
        bp_out = ps.ObsBandpass(filt_out)
          
    sp_norm = sp.renorm(mag_in, system_in, bp_in)

    obs = ps.Observation(sp_norm, bp_out, binset=sp_norm.wave)
    mag = obs.effstim(system_out)
    return mag 
Пример #2
0
 def __init__(self):
     # Transmission / reflectivity of different elements to calculate throughput
     _e_diff = 0.90  # transmission
     _e_lens = 0.99 * 0.99 * 0.99 * 0.99
     _e_mirr = 0.96 * 0.96
     _e_atmosphere = 0.5  # fudgefactor for atmosphere, assume 50%
     _tot_throughput = _e_diff * _e_lens * _e_mirr * _e_atmosphere
     Telescope.__init__(
         self,
         name='ARC 3.5m',  #Name of the telescope
         diameter=350.,  #cm
         fnum=8.0,  #
         flength=28.,  #m
         gain=2.0,  #e/ADU
         pix_size=15.,  #microns
         fov=8.,  #arcmin, not really needed
         num_pix=4096.,  #pixels on x-axis of detector
         plt_scale=0.11,  #arcsec/pix
         dark_noise=0.,  #electrons
         read_noise=3.7,  #e^2
         altitude=2788.,  #m
         central_obstruction=0.09,  # from 0 to 1
         QE=S.FileBandpass(self.qe_file),
         Throughput=S.UniformTransmission(_tot_throughput),
         diffuser_angle=0.34,
         diffuser_dist_from_detector=200.)  # from 0 to 1
Пример #3
0
def test_johnson_v_tabular_spectra():
    bp = pysyn.FileBandpass("data/test_bp_johnson_v.fits",
                            thrucol="THROUGHPUT")
    sp = pysyn.FileSpectrum("data/test_sp_vega.fits")
    obs = pysyn.Observation(sp, bp)
    obs *= 1e20
    result(obs, 411896149580, 0, 8893)
Пример #4
0
 def setUp(self):
     self.bp = S.FileBandpass('crnonhstcomp$johnson_v_004_syn.fits')
     self.r_avgwave=5490.5552003639823
     self.r_efficiency=0.15678915809503616
     self.r_equivwidth=857.34999515116215
     self.r_rectwidth=857.34999515116215
     self.r_rmswidth=357.13065617707804
Пример #5
0
def test_hst_analytic_binset():
    bp = pysyn.FileBandpass("data/test_bp_acs_hrc_f555w.fits",
                            thrucol="THROUGHPUT")
    spec = FlatSpectrum(10000, fluxunits='flam')
    binset = np.asarray([1000, 2000, 5000, 11000])
    obs = pysyn.Observation(spec, bp, binset=binset)
    result(obs, 2439, 0, 17023)
Пример #6
0
def test_hst_tabular_spectra():
    bp = pysyn.FileBandpass("data/test_bp_acs_hrc_f555w.fits",
                            thrucol="THROUGHPUT")
    sp = pysyn.FileSpectrum("data/test_sp_vega.fits")
    obs = pysyn.Observation(sp, bp)
    obs *= 1e20
    result(obs, 112231834769, 0, 15866)
Пример #7
0
 def testthru(self):
     iraf.calcband(obsmode=self.obsmode, output=self.cbname)
     ref = S.FileBandpass(self.cbname)
     rthru = ref.throughput
     rwave = ref.wave
     tthru = self.bp(rwave)
     self.savepysyn(rwave, tthru, self.cbname)
     self.arraysigtest(tthru, rthru)
Пример #8
0
def test_hst_tabular_spectra_binset():
    bp = pysyn.FileBandpass("data/test_bp_acs_hrc_f555w.fits",
                            thrucol="THROUGHPUT")
    sp = pysyn.FileSpectrum("data/test_sp_vega.fits")

    binset = np.asarray([1000, 2000, 5000, 11000])
    obs = pysyn.Observation(sp, bp, binset=binset)
    obs *= 1e20
    result(obs, 112231834769, 0, 15866)
Пример #9
0
def get_fl(system='kic1255', renormBand='Kmag'):
    """ Get the fluxes"""
    if system == 'kic1255':
        ## From Rappapor et al. 2012
        sp = S.Icat('phoenix', 4400, 0.0, 4.63)
        Jmag = 14.021
        Kmag = 13.319

    elif system == 'k2-22':
        ## From Sanchis-Ojeda 2016
        sp = S.Icat('phoenix', 3830, 0.0, 4.65)
        Jmag = 12.726
        Kmag = 11.924

    else:
        print 'No Valid System specified'

    ## Get the 2MASS bandpasses
    tmassdir = os.path.join(os.environ['TEL_DATA'], '2mass')
    bpK = S.FileBandpass(os.path.join(tmassdir, '2mass_k_ang.txt'))
    bpJ = S.FileBandpass(os.path.join(tmassdir, '2mass_j_ang.txt'))

    # Get the IRAC bandpasses
    iracdir = os.path.join(os.environ['TEL_DATA'], 'irac')
    irac45 = S.FileBandpass(os.path.join(iracdir, 'irac_45_ang.txt'))
    irac36 = S.FileBandpass(os.path.join(iracdir, 'irac_36_ang.txt'))
    iracnames = ['IRAC 3.6um', 'IRAC 4.5um']

    # Renormalize spectrum
    if renormBand == 'Kmag':
        renormBandpass = bpK
        renormMag = Kmag
    else:
        renormBandpass = bpJ
        renormMag = Jmag

    sp_norm = sp.renorm(renormMag, 'vegamag', renormBandpass)

    for iracInd, iracBP in enumerate([irac36, irac45]):
        obs = S.Observation(sp_norm, iracBP)
        ## Get the flux at the wavelegnth
        stim = obs.effstim('uJy')
        print "Flux for " + iracnames[iracInd] + " is " + str(stim) + " uJy"
Пример #10
0
def calculate_nires_s2n_qso(src_type, redshift, obs_wave, exp_time, coadds,
                            dither, dither_repeat, seeing, num_reads):
    ## fixed instrument parameters
    slit_width = 0.55  #arcsec
    slit_lenth = 18.0  #arcsec
    dark_current = 0.01  #e-/s
    pix_size = 0.123  #arcsec/pix
    collect_area = 76 * 1e4  # 76 m^2 = 76e4 cm^2
    obs_wave_angstrom = obs_wave * 1e4  #convert to angstrom
    del_lmbd = obs_wave_angstrom / 2700  # unit: A
    spatial_cov = 0.55 * seeing
    num_pix_slt = 18 * 0.55 / pix_size**2
    num_pix_src = 0.55 * seeing

    # throughput wave unit in A
    tpt_tab = S.FileBandpass(datadir + "nires_throughput_18_edit.dat")
    #convert input wavelength cm to A then interp
    tpt_val_interp = np.interp(obs_wave_angstrom, tpt_tab.wave,
                               tpt_tab.throughput)
    print(tpt_val_interp)

    #sky value unit is phot/s/arcsec^2/cm^2/A
    ## mauna kea IR sky bkg
    IR_sky = ascii.read(datadir + "IRsky_am10_pw10.dat")
    sky_wave = IR_sky[0][:] / 1000  # um
    sky_bkg = 1000 * IR_sky[1][:]  #photon/s/arcsec^2/cm/cm^2
    sky_bkg_interp = np.interp(obs_wave_angstrom, sky_wave, sky_bkg)

    src_sp = {"qso": qso_sp, "sy1": sy1_sp, "sy2": sy2_sp}

    ## convolve source spectra and sky and plot, estimate source s2n
    ## source signal flux at given obs. wavelength
    sig_src_obs = np.interp(obs_wave_angstrom, src_sp[src_type].wave,
                            src_sp[src_type].flux)  #unit: phot/s/cm^2/A
    sig_src = sig_src_obs * collect_area * tpt_val_interp * del_lmbd * spatial_cov  # source signal in e-/s

    if num_reads == 2:
        read_noise = 15  #CDS
    elif num_reads == 16:
        read_noise = 5  #MCDS

    sig_src_int = sig_src * exp_time  #source flux integrated over time, single frame
    noise_int = (sig_src * exp_time + num_pix_slt * dark_current * exp_time +
                 (num_pix_slt - num_pix_src) * sky_bkg_interp * exp_time +
                 num_pix_slt * read_noise**2 * exp_time)**(
                     1 / 2)  #noise, single frame

    s2n = sig_src_int / noise_int  # s/n, single frame

    return s2n
Пример #11
0
def get_synthetic_mag_file(filename, filt_out, system_out, filt_in=None, mag_in=None, system_in=None, ebv=0, force=None):
    '''
    Scales the input spectrum (read from the filename file) to the magnitude 
    provided in the filter_in band, and obtains the synthetic photometry in the filter_out band.
    If no scaling magnitude is provided, the original spectrum is used to compute the synthetic mangitude.
    
    Parameters
    ----------
    filename : string
            The name of the file which contains the spectrum.
    filt_out : string
            The name of the filter the system will compute the output of.
    system_out : string
            The system in which the output magntiudes are measured. "abmag" or "vegamag" or "stmag"
    filt_in : string
            The name of the filter we want to scale the spectrum.
    mag_in : float
            The mangtude of the object in the filter_in band.
    system_in : string
            The system in which the input magntiude is measured. "abmag" or "vegamag" or "stmag"
    ebv : float, default: 0
            The reddening to be applied to the model spectrum.    
    force : string, default: None
            Whether the magnitude should be extrapolated in case the filter and the spectrum wavelengths do not
            completely overlap. You may use force=[extrap|taper] to force this Observation anyway.
            
    Returns
    -------
    
    mag_out : float
                The synthetic photometry magnitude of the input spectrum once 
                scaled to its mag_in value in filter_out band.
    '''
    sp = ps.FileSpectrum(filename)
    sp_ext = sp * ps.Extinction(ebv, 'mwavg')
    
    if not( filt_in is None or mag_in is None or system_in is None):
        sp_norm = sp_ext.renorm(mag_in, system_in, ps.ObsBandpass(filt_in))
    else:
        sp_norm = sp_ext
        
    try:
        obs = ps.Observation(sp_norm, ps.ObsBandpass(filt_out), binset=sp_norm.wave, force=force)
    except ValueError:
        bp = ps.FileBandpass(banddic[filt_out])
        obs = ps.Observation(sp_norm, bp, binset=sp.wave)
        
    mag_out = obs.effstim(system_out)
    
    return mag_out
Пример #12
0
    def _get_bandpass(self, *args):
        """
        Parse a self.bandpass of the form <photsys>,<filter> and use the keys to look up a bandpass file
        in self.photsystems.  Use pysynphot to load the bandpass and return it.

        Returns
        -------
        bp: pysynphot.SpectralElement
            Bandpass throughput data as returned by pysynphot.FileBandpass() and converted to pandeia
            wavelength units
        """
        keys = get_key_list(self.bandpass, separator=',')  # should be [photsys, filter]
        bp_filename = get_dict_from_keys(self.bandpasses, keys)['filename']
        bp_path = os.path.join(default_refdata_directory, "normalization", "bandpass", bp_filename)
        bp = psyn.FileBandpass(bp_path)
        bp.convert(pandeia_waveunits)
        return bp
Пример #13
0
 def __init__(self):
     Telescope.__init__(
         self,
         name='PSU 0.6m',  #Name of the telescope
         diameter=61.,  #cm
         fnum=6.5,  #
         flength=3.965,  #m
         gain=1.0,  #e/ADU
         pix_size=13.5,  #microns
         fov=24.,  #arcmin, not really needed
         num_pix=2048.,  #pixels on x-axis of detector
         plt_scale=0.703,  #arcsec/pix
         dark_noise=22.8,  #electrons
         read_noise=18.,  #e^2
         altitude=359.,  #m
         central_obstruction=0.47,  # from 0 to 1
         QE=S.FileBandpass(
             self.qe_file),  # Lets just use the same as for ARCTIC for now
         Throughput=S.UniformTransmission(_tot_throughput),
         diffuser_angle=0.34,
         diffuser_dist_from_detector=53.)  # from 0 to 1
Пример #14
0
def get_synthetic_mag_spec(wave, flux, filt="sdss,g", system="abmag"):
    '''
    Provided a spectrum for a source, it computes its synthetic magnitude in the required
    band and photometric system.
    
    Parameters
    ----------
    wave : 1-D array containing the wavelength of the spectrum (in Angstrom).
    flux: 1-D array containing the flux (in erg/s/cm**2/A)
    filt: photometric band the synthetic mangitude needs to be computed.
    system: photometric system for the output mangitude (agmag, vegamag, stmag...)
    
    Returns
    -------
    mag : float
        The synthetic magnitude of the input spectrum for that photometric band and system.
    
    
    Examples
    --------
    >>> import pysynphot as ps
    >>> vega = ps.Vega
    >>> get_synthetic_phot(vega.wave, vega.flux, filt="V", system="vegamag")
    >>> 0.0
    '''
    
    sp = ps.ArraySpectrum(wave, flux, fluxunits="flam")
    
    #If the band is a custom one that we have added to the dictionary of filters,
    # we just create a new passband from the file. Otherwise, it selects it automatically.
    if (filt in banddic.keys()): 
        filt_file = banddic.get(filt, filt)
        bp = ps.FileBandpass(filt_file)
    else:
        bp = ps.ObsBandpass(filt)

    obs = ps.Observation(sp, bp, force='extrap', binset=wave)
    mag = obs.effstim(system)
    return mag 
Пример #15
0
### -Version 1.2bv: rewrite the calculation as function calc_zeroflux -- 09/23/2008
### -Version 1.3: calculate zeropoint fluxes directly by converting ABmag to micro-Jansky -- 09/28/08
### -Version 1.3.1: changed bandpass into a dictionary, and will be referenced by bandpass name

import os
import numpy as np
import pysynphot as S
import matplotlib.pyplot as plt
#from pyraf import iraf
#from iraf import stsdas,hst_calib,ttools,synphot

rootdir = os.getenv('mypytools')
filters = {}

filters['ukpno'] = S.FileBandpass(
    rootdir + '/sedtools/bandpass/CANDELS_FILTERS/MOSAIC/U_kpno_mosaic.bp'
)  # "Mosaic U band in TFIT catalog
filters['uctio'] = S.FileBandpass(
    rootdir + '/sedtools/bandpass/CANDELS_FILTERS/CTIO/U_ctio.bp')
filters['uvimos'] = S.FileBandpass(rootdir + '/sedtools/bandpass/U_vimos.bp')
filters['f435w'] = S.ObsBandpass('acs,wfc2,f435w')
filters['f475w'] = S.ObsBandpass('acs,wfc2,f475w')
filters['f555w'] = S.ObsBandpass('acs,wfc2,f555w')
filters['f606w'] = S.ObsBandpass('acs,wfc2,f606w')
filters['f625w'] = S.ObsBandpass('acs,wfc2,f625w')
filters['f775w'] = S.ObsBandpass('acs,wfc2,f775w')
filters['f814w'] = S.ObsBandpass('acs,wfc2,f814w')
filters['f850lp'] = S.ObsBandpass('acs,wfc2,f850lp')
filters['f098m'] = S.ObsBandpass('wfc3,ir,f098m')
filters['f105w'] = S.ObsBandpass('wfc3,ir,f105w')
filters['f110w'] = S.ObsBandpass('wfc3,ir,f110w')
Пример #16
0
"""

tempdir = '/Users/khuang/Dropbox/codes/mypytools/sedtools/galtemplates'
## Coleman, Wu & Weedman (1980) local galaxy templates
Sbc = tempdir + '/Gsbc.spec'
Scd = tempdir + '/Gscd.spec'
ES0 = tempdir + '/Geso.spec'
Imm = tempdir + '/Gimm.spec'
## LBG template with const. SFH & age = 200 Myr, solar Z, Salpeter IMF
LBG = tempdir + '/lbgtemp_z3_Zsolar_constSFH_200Myr.sed'

localTemplates = {'Sbc':Sbc, 'Scd':Scd, 'ES0':ES0, 'Imm':Imm, 'LBG':LBG}

## Subaru filters
bpdir = '/Users/khuang/Dropbox/codes/mypytools/sedtools/bandpass/CANDELS_FILTERS'
iSubaru = S.FileBandpass(bpdir + '/SuprimeCAM/i_subaru.dat')
iSubaru.name = 'iSubaru'
jSubaru = S.FileBandpass(bpdir + '/MOIRCS/J_MOIRCS.dat')
jSubaru.name = 'jSubaru'
hSubaru = S.FileBandpass(bpdir + '/MOIRCS/H_MOIRCS.dat')
hSubaru.name = 'hSubaru'
kSubaru = S.FileBandpass(bpdir + '/MOIRCS/K_MOIRCS.dat')
kSubaru.name = 'kSubaru'
subFilters = [iSubaru, jSubaru, hSubaru, kSubaru]
IRAC1 = S.FileBandpass(bpdir + '/IRAC/irac_ch1.dat')
IRAC1.name = "IRAC1"
IRAC2 = S.FileBandpass(bpdir + '/IRAC/irac_ch2.dat')
IRAC2.name = "IRAC2"
iracFilters = [iSubaru, IRAC1, IRAC2]

def calcTempMagnitudes(templates=localTemplates, zarray=np.arange(0.02,3.02,0.02)):
Пример #17
0
def calc_reddened_colours(temp):

    magsystem = 'vegamag'

    #read in transmission tables describing the VPHAS+ filter curves
    fpaths = glob.glob(
        '/mirror2/scratch/hbarker/Macquarie/CS_synthetic_colours/vphas_atmosphere_included_filters/*.dat'
    )
    for fpath in fpaths:
        bandpass = S.FileBandpass(fpath)
        with open(fpath, 'r') as f:
            tab = [line.strip().split() for line in f]
        #if 'u_SDSS' in fpath:
        #	u_bp = bandpass
        #elif 'g_SDSS' in fpath:
        #	g_bp = bandpass

        #use the filtercurved emailed by Janet Drew that contain the known u
        # and g band red leak
        if 'u-transmission' in fpath:
            bandpass = S.FileBandpass(fpath)
            u_bp = bandpass
        elif 'g-transmission' in fpath:
            bandpass = S.FileBandpass(fpath)
            g_bp = bandpass

        elif 'r_SDSS' in fpath:
            r_bp = bandpass
        elif 'i_SDSS' in fpath:
            i_bp = bandpass

    #read in PN model spectra from the TMAP models
    tmap_paths = glob.glob(
        '/mirror2/scratch/hbarker/Macquarie/CS_synthetic_colours/TubingenModels/'
        + str(temp) + 'kK_7.0_solar/*.txt')
    if len(tmap_paths) == 0:
        print 'File does not exist'
        print '/mirror2/scratch/hbarker/Macquarie/CS_synthetic_colours/TubingenModels/' + str(
            temp) + 'kK_7.0_solar/*.txt'
        sys.exit()
    fpath = tmap_paths[0]

    #read the spectrum into a table
    colnames = ['lambda', 'F_lambda']
    wl = []
    flx = []
    with open(fpath, 'r') as f:
        for line in f:
            line = line.split()
            wl.append(float(line[0]))  #A
            #convert flux from erg/cm**2/s/cm to erg/s/cm**2/A
            flx_cgs = float(line[1]) * 1e-8
            flx.append(flx_cgs)

    #E(B-V) values to calculate
    reddenings = np.arange(0, 31, 1)  #0, 0.1, 0.2, ...., 2.9, 3.0
    reddenings = [round(line / 10., 3) for line in reddenings]

    EBmV_dict = {}  # { 0.0 : [u-g, g-r, r-i], ... }
    for EBmV in reddenings:

        #construct spectrum for pysynphot
        spectrum = S.ArraySpectrum(np.array(wl), np.array(flx), 'angstrom',
                                   'flam')

        #convert from flam to photons, as colours need to be calculatated in photon counts
        spectrum.convert('counts')

        #redden the spectrum using cardelli1989 and Rv=3.1
        spectrum = spectrum * S.Extinction(EBmV, 'mwavg')

        obs_u = S.Observation(spectrum, u_bp)
        obs_g = S.Observation(spectrum, g_bp)
        obs_r = S.Observation(spectrum, r_bp)
        obs_i = S.Observation(spectrum, i_bp)

        #calculate colours
        u_min_g = obs_u.effstim(magsystem) - obs_g.effstim(magsystem)
        g_min_r = obs_g.effstim(magsystem) - obs_r.effstim(magsystem)
        r_min_i = obs_r.effstim(magsystem) - obs_i.effstim(magsystem)

        #Add EBmV and colours to the dictionary
        colours = [u_min_g, g_min_r, r_min_i]
        EBmV_dict[EBmV] = colours

    return EBmV_dict
Пример #18
0
ind = (w_full > 2000) & (w_full < 40000)
ww = w_full[ind]

ff = load_flux_full(5900, 3.5)[ind] * 2e-28
#redden spectrum
#red = ff/deredden(ww,1.5,mags=False)

sp = S.ArraySpectrum(wave=ww, flux=ff, waveunits='angstrom', fluxunits='flam', name='T5900K')

#sdss_u=S.FileBandpass("/home/ian/.builds/stsci_python-2.12/pysynphot/cdbs/comp/nonhst/sdss_u_005_syn.fits")
#sdss_g=S.FileBandpass("/home/ian/.builds/stsci_python-2.12/pysynphot/cdbs/comp/nonhst/sdss_g_005_syn.fits")
#sdss_r=S.FileBandpass("/home/ian/.builds/stsci_python-2.12/pysynphot/cdbs/comp/nonhst/sdss_r_005_syn.fits")
#sdss_i=S.FileBandpass("/home/ian/.builds/stsci_python-2.12/pysynphot/cdbs/comp/nonhst/sdss_i_005_syn.fits")
#sdss_z=S.FileBandpass("/home/ian/.builds/stsci_python-2.12/pysynphot/cdbs/comp/nonhst/sdss_z_005_syn.fits")

U = S.FileBandpass("/home/ian/.builds/stsci_python-2.12/pysynphot/cdbs/comp/nonhst/landolt_u_004_syn.fits")
B = S.FileBandpass("/home/ian/.builds/stsci_python-2.12/pysynphot/cdbs/comp/nonhst/landolt_b_004_syn.fits")
V = S.FileBandpass("/home/ian/.builds/stsci_python-2.12/pysynphot/cdbs/comp/nonhst/landolt_v_004_syn.fits")
R = S.FileBandpass("/home/ian/.builds/stsci_python-2.12/pysynphot/cdbs/comp/nonhst/landolt_r_004_syn.fits")
I = S.FileBandpass("/home/ian/.builds/stsci_python-2.12/pysynphot/cdbs/comp/nonhst/landolt_i_004_syn.fits")

#H = S.FileBandpass("/home/ian/.builds/stsci_python-2.12/pysynphot/cdbs/comp/nonhst/bessell_h_004_syn.fits")
#J = S.FileBandpass("/home/ian/.builds/stsci_python-2.12/pysynphot/cdbs/comp/nonhst/bessell_j_003_syn.fits")
#K = S.FileBandpass("/home/ian/.builds/stsci_python-2.12/pysynphot/cdbs/comp/nonhst/bessell_k_003_syn.fits")

#obs = S.Observation(sp,sdss_u)
#print("Filter = {name}\tAB = {AB:.3f}\tVega = {Vega:.3f}".format(name="i",AB=obs.effstim("abmag"),Vega=obs.effstim(
# "vegamag")))

pfilts = [U, B, V, R, I]
Пример #19
0
def get_pbmodel(pbnames, model, pbfile=None, mag_type=None, mag_zero=0.):
    """
    Converts passband names ``pbnames`` into passband models based on the
    mapping of name to ``pysynphot`` ``obsmode`` strings in ``pbfile``.

    Parameters
    ----------
    pbnames : array-like
        List of passband names to get throughput models for Each name is
        resolved by first looking in ``pbfile`` (if provided) If an entry is
        found, that entry is treated as an ``obsmode`` for pysynphot. If the
        entry cannot be treated as an ``obsmode,`` we attempt to treat as an
        ASCII file. If neither is possible, an error is raised.
    model : :py:class:`WDmodel.WDmodel.WDmodel` instance
        The DA White Dwarf SED model generator
        All the passbands are interpolated onto the wavelengths of the SED
        model.
    pbfile : str, optional
        Filename containing mapping between ``pbnames`` and ``pysynphot``
        ``obsmode`` string, as well as the standard that has 0 magnitude in the
        system (either ''Vega'' or ''AB''). The ``obsmode`` may also be the
        fullpath to a file that is readable by ``pysynphot``
    mag_type : str, optional
        One of ''vegamag'' or ''abmag''
        Used to specify the standard that has mag_zero magnitude in the passband.
        If ``magsys`` is specified in ``pbfile,`` that overrides this option.
        Must be the same for all passbands listed in ``pbname`` that do not
        have ``magsys`` specified in ``pbfile``
        If ``pbnames`` require multiple ``mag_type``, concatentate the output.
    mag_zero : float, optional
        Magnitude of the standard in the passband
        If ``magzero`` is specified in ``pbfile,`` that overrides this option.
        Must be the same for all passbands listed in ``pbname`` that do not
        have ``magzero`` specified in ``pbfile``
        If ``pbnames`` require multiple ``mag_zero``, concatentate the output.

    Returns
    -------
    out : dict
        Output passband model dictionary. Has passband name ``pb`` from ``pbnames`` as key.

    Raises
    ------
    RuntimeError
        If a bandpass cannot be loaded

    Notes
    -----
        Each item of ``out`` is a tuple with
            * ``pb`` : (:py:class:`numpy.recarray`)
              The passband transmission with zero throughput entries trimmed.
              Has ``dtype=[('wave', '<f8'), ('throughput', '<f8')]``
            * ``transmission`` : (array-like)
              The non-zero passband transmission interpolated onto overlapping model wavelengths
            * ``ind`` : (array-like)
              Indices of model wavelength that overlap with this passband
            * ``zp`` : (float)
              mag_type zeropoint of this passband
            * ``avgwave`` : (float)
              Passband average/reference wavelength

        ``pbfile`` must be readable by :py:func:`WDmodel.io.read_pbmap` and
        must return a :py:class:`numpy.recarray`
        with``dtype=[('pb', 'str'),('obsmode', 'str')]``

        If there is no entry in ``pbfile`` for a passband, then we attempt to
        use the passband name ``pb`` as ``obsmode`` string as is.

        Trims the bandpass to entries with non-zero transmission and determines
        the ``VEGAMAG/ABMAG`` zeropoint for the passband - i.e. ``zp`` that
        gives ``mag_Vega/AB=mag_zero`` in all passbands.

    See Also
    --------
    :py:func:`WDmodel.io.read_pbmap`
    :py:func:`WDmodel.passband.chop_syn_spec_pb`
    """

    # figure out the mapping from passband to observation mode
    if pbfile is None:
        pbfile = 'WDmodel_pb_obsmode_map.txt'
        pbfile = io.get_pkgfile(pbfile)
    pbdata  = io.read_pbmap(pbfile)
    pbmap   = dict(list(zip(pbdata.pb, pbdata.obsmode)))
    sysmap  = dict(list(zip(pbdata.pb, pbdata.magsys)))
    zeromap = dict(list(zip(pbdata.pb, pbdata.magzero)))

    # setup the photometric system by defining the standard and corresponding magnitude system
    if mag_type not in ('vegamag', 'abmag', None):
        message = 'Magnitude system must be one of abmag or vegamag'
        raise RuntimeError(message)

    try:
        mag_zero = float(mag_zero)
    except ValueError as e:
        message = 'Zero magnitude must be a floating point number'
        raise RuntimeError(message)

    # define the standards
    vega = S.Vega
    vega.convert('flam')
    ab   = S.FlatSpectrum(0., waveunits='angstrom', fluxunits='abmag')
    ab.convert('flam')

    # defile the magnitude sysem
    if mag_type == 'vegamag':
        mag_type= 'vegamag'
    else:
        mag_type = 'abmag'

    out = OrderedDict()

    for pb in pbnames:

        standard = None

        # load each passband
        obsmode = pbmap.get(pb, pb)
        magsys  = sysmap.get(pb, mag_type)
        synphot_mag = zeromap.get(pb, mag_zero)

        if magsys == 'vegamag':
            standard = vega
        elif magsys == 'abmag':
            standard = ab
        else:
            message = 'Unknown standard system {} for passband {}'.format(magsys, pb)
            raise RuntimeError(message)

        loadedpb = False
        # treat the passband as a obsmode string
        try:
            bp = S.ObsBandpass(obsmode)
            loadedpb = True
        except ValueError:
            message = 'Could not load pb {} as an obsmode string {}'.format(pb, obsmode)
            warnings.warn(message, RuntimeWarning)
            loadedpb = False

        # if that fails, try to load the passband interpreting obsmode as a file
        if not loadedpb:
            try:
                bandpassfile = io.get_filepath(obsmode)
                bp = S.FileBandpass(bandpassfile)
                loadedpb = True
            except Exception as e:
                message = 'Could not load passband {} from obsmode or file {}'.format(pb, obsmode)
                warnings.warn(message, RuntimeWarning)
                loadedpb = False

        if not loadedpb:
            message = 'Could not load passband {}. Giving up.'.format(pb)
            raise RuntimeError(message)

        avgwave = bp.avgwave()
        if standard.wave.min() > model._wave.min():
            message = 'Standard does not extend past the blue edge of the model'
            warnings.warn(message, RuntimeWarning)

        if standard.wave.max() < model._wave.max():
            message = 'Standard does not extend past the red edge of the model'
            warnings.warn(message, RuntimeWarning)

        # interpolate the standard onto the model wavelengths
        sinterp = interp1d(standard.wave, standard.flux, fill_value='extrapolate')
        standard_flux = sinterp(model._wave)
        standard = np.rec.fromarrays([model._wave, standard_flux], names='wave,flux')

        # cut the passband to non-zero values and interpolate onto overlapping standard wavelengths
        outpb, outzp = chop_syn_spec_pb(standard, synphot_mag, bp, model)

        # interpolate the passband onto the standard's  wavelengths
        transmission, ind = interp_passband(model._wave, outpb, model)

        # save everything we need for this passband
        out[pb] = (outpb, transmission, ind, outzp, avgwave)
    return out
Пример #20
0
def test_johnson_v_analytic():
    bp = pysyn.FileBandpass("data/test_bp_johnson_v.fits",
                            thrucol="THROUGHPUT")
    spec = FlatSpectrum(10000, fluxunits='flam')
    obs = pysyn.Observation(spec, bp)
    result(obs, 10000, 0, 10047)
Пример #21
0
def photometry(filters_path,
               filters_list,
               specs_path,
               specs_list,
               telescope_area,
               results_path,
               confidence=0.6,
               plot=False,
               save=False):
    """

    :param filters_path: add the path to your filters response files -- e.g '/home/user/Documents/Filters'
    :param filters_list: add the path and name of your filters' list
    -- e.g '/home/user/Documents/filters_list.txt'
    Inside this list you should have all the filters' response files that you are going to use
    -- e.g.:
    uSDSS.txt
    gSDSS.txt
    rSDSS,txt
    iSDSS.txt
    zSDSS.txt
    You can create it in your command line by doing the following command:
    $ ls /home/user/Documents/Filters >> /home/user/Documents/filters_list.txt
    :param specs_path: add the path to your spectra files -- e.g '/home/user/Documents/Specs'
    :param specs_list: similar to the filters_list
    :param telescope_area: the default parameter is 4400 which is the J-PAS T80 M1 effective area in cm^2.
    Set it as you wish given your telescope.
    :param results_path: add the path where you would like to save your results. It is only obligatory if you set
    plot=True
    :param confidence: the confidence that you would like to add in order to calculate a simulated photometry.
    This is important for the photometry of the borders of the spectra. This will limit the calculation of the
    photometry in terms of the wavelength range. If the filter occupies less than X% of your spectrum wavelength range,
    it will generate an error value (-999), but if it occupies more than X% it will do the convolution the filter with
    the spectrum. The default value is 60% (0.6), but you can change this at your will.
    :param plot: if you want to plot the results and save them, please set 'plot=True'. If not, please set 'plot=False'.
    The default is false.
    :param save: if you want to save the results, please set 'save=True'. If not, please set 'save=False'.
    The default is False.
    is false.
    :return: The returned parameters are:
    1) photometry: your simulated photometry. This is your main result.
    2) lambda_eff: effective wavelengths of your filters.
    3) photometry_flam: the simulated photometry in terms of flux_lambda
    4) photometry_fnu: the simulated photometry in terms of flux_fnu
    5) filter_name: the name of the filters you used in each round. This is not very important, you can ignore this.
    """

    # Setting the telescope area; the default parameter is the T80 M1 effective area in cm^2 ---------------------------
    if telescope_area == None:
        s.setref(area=4400)
    else:
        s.setref(area=telescope_area)

    # Reading your files -----------------------------------------------------------------------------------------------
    filters_list = np.loadtxt(filters_list, dtype=str)
    specs_list = np.loadtxt(specs_list, dtype=str)

    # Simulating photometry for your spectra using the selected survey filters -----------------------------------------
    count = 0
    for each_spectrum in specs_list:
        print each_spectrum
        filter_name = []
        photometry = []
        photometry_flam = []
        lambda_eff = []
        for filters in filters_list:
            # saving an array with the filters names -------------------------------------------------------------------
            filter_name_i = filters.split('.')[0]
            filter_name.append(filter_name_i)

            # convolution ----------------------------------------------------------------------------------------------
            filter_bandpass = s.FileBandpass(
                os.path.join(filters_path, filters))
            spectrum = s.FileSpectrum(os.path.join(
                specs_path, each_spectrum))  # the entire spectrum
            index = np.where(
                spectrum.flux >
                0)  # selecting only the positive part of the spectrum
            spectrum2 = s.ArraySpectrum(wave=spectrum.wave[index],
                                        flux=spectrum.flux[index],
                                        fluxunits=spectrum.fluxunits,
                                        waveunits=spectrum.waveunits)
            binset = filter_bandpass.wave  # this is very very important! don't change this unless
            # you are absolutely sure of what you are doing!
            ## convolved photometry ------------------------------------------------------------------------------------
            photometry_i = s.Observation(spectrum2,
                                         filter_bandpass,
                                         binset=binset,
                                         force='extrap')

            ## effective wavelength ------------------------------------------------------------------------------------
            lambda_eff_i = photometry_i.efflam()
            lambda_eff.append(lambda_eff_i)

            ## checking if the simulated photometry is "virtual" and letting those away --------------------------------
            if filter_bandpass.wave.min() < spectrum2.wave.min():
                if filter_bandpass.wave.max() - spectrum2.wave.min(
                ) > confidence * (filter_bandpass.wave.max() -
                                  filter_bandpass.wave.min()):
                    photometry.append(photometry_i.effstim('abmag'))
                    photometry_flam_i = photometry_i.effstim('flam')
                    photometry_flam.append(photometry_flam_i)

                else:
                    new_photometry_i = -999
                    photometry.append(new_photometry_i)
                    photometry_flam.append(new_photometry_i)

            elif filter_bandpass.wave.max() > spectrum2.wave.max():
                if spectrum2.wave.max() - filter_bandpass.wave.min(
                ) > confidence * (filter_bandpass.wave.max() -
                                  filter_bandpass.wave.min()):
                    photometry.append(photometry_i.effstim('abmag'))
                    photometry_flam_i = photometry_i.effstim('flam')
                    photometry_flam.append(photometry_flam_i)

                else:
                    new_photometry_i = -999
                    photometry.append(new_photometry_i)
                    photometry_flam.append(new_photometry_i)

            else:
                photometry.append(photometry_i.effstim('abmag'))
                photometry_flam_i = photometry_i.effstim('flam')
                photometry_flam.append(photometry_flam_i)

        count = count + 1

        # putting the iterated items into arrays -----------------------------------------------------------------------
        filter_name = np.array(filter_name)  # name of each filter
        photometry = np.array(photometry)  # in magnitudes
        lambda_eff = np.array(
            lambda_eff)  # effective wavelengths of the filters
        photometry_flam = np.array(photometry_flam)  # in flux of lambda
        photometry_fnu = 10**(-0.4 * (photometry + 48.60))  # in flux of nu

        if (plot == False) * (save == False):
            continue

        elif (plot == False) * (save == True):
            # saving the newley calculated photometry ------------------------------------------------------------------
            galaxy_simulation_abmag = np.vstack((filter_name, photometry))
            galaxy_simulation_abmag = pd.DataFrame(galaxy_simulation_abmag)
            galaxy_simulation_abmag.to_csv(os.path.join(
                results_path,
                str(count) + '_abmag.csv'),
                                           sep=',',
                                           header=None,
                                           index=False)
            galaxy_simulation_fnu = np.vstack((filter_name, photometry_fnu))
            galaxy_simulation_fnu = pd.DataFrame(galaxy_simulation_fnu)
            galaxy_simulation_fnu.to_csv(os.path.join(results_path,
                                                      str(count) + '_fnu.csv'),
                                         sep=',',
                                         header=None,
                                         index=False)

        elif (plot == True) * (save == False):
            # plots ----------------------------------------------------------------------------------------------------
            plt.plot(spectrum2.wave, spectrum2.flux, '-')
            plt.plot(lambda_eff[[photometry_flam != -999]],
                     photometry_flam[[photometry_flam != -999]], 'o')
            plt.title(r"%s" % each_spectrum, size='15')
            plt.savefig(os.path.join(results_path,
                                     'object_' + str(count) + '.png'),
                        dpi=100)
            plt.show()

        elif (plot == True) * (save == True):
            # plots ----------------------------------------------------------------------------------------------------
            plt.plot(spectrum2.wave, spectrum2.flux, '-')
            plt.plot(lambda_eff[[photometry_flam != -999]],
                     photometry_flam[[photometry_flam != -999]], 'o')
            plt.title(r"%s" % each_spectrum, size='15')
            plt.savefig(os.path.join(results_path,
                                     'object_' + str(count) + '.png'),
                        dpi=100)
            plt.show()

            # saving the newley calculated photometry ------------------------------------------------------------------
            galaxy_simulation_abmag = np.vstack((filter_name, photometry))
            galaxy_simulation_abmag = pd.DataFrame(galaxy_simulation_abmag)
            galaxy_simulation_abmag.to_csv(os.path.join(
                results_path, 'object_' + str(count) + '_abmag.csv'),
                                           sep=',',
                                           header=None,
                                           index=False)
            galaxy_simulation_fnu = np.vstack((filter_name, photometry_fnu))
            galaxy_simulation_fnu = pd.DataFrame(galaxy_simulation_fnu)
            galaxy_simulation_fnu.to_csv(os.path.join(
                results_path, 'object_' + str(count) + '_fnu.csv'),
                                         sep=',',
                                         header=None,
                                         index=False)

    return photometry, lambda_eff, photometry_flam, photometry_fnu, filter_name
Пример #22
0
    'f850lp':
    S.ObsBandpass('acs,wfc2,f850lp'),
    'f098m':
    S.ObsBandpass('wfc3,ir,f098m'),
    'f105w':
    S.ObsBandpass('wfc3,ir,f105w'),
    'f110w':
    S.ObsBandpass('wfc3,ir,f110w'),
    'f125w':
    S.ObsBandpass('wfc3,ir,f125w'),
    'f140w':
    S.ObsBandpass('wfc3,ir,f140w'),
    'f160w':
    S.ObsBandpass('wfc3,ir,f160w'),
    'uvimos':
    S.FileBandpass(
        '/Users/khuang/Dropbox/codes/mypytools/sedtools/bandpass/U_vimos.bp'),
    'uctio':
    S.FileBandpass(
        '/Users/khuang/Dropbox/codes/mypytools/sedtools/bandpass/CANDELS_FILTERS/CTIO/U_ctio.bp'
    )
}


class starlib(object):
    """
	A class that reads in a catalog of (normalized) magnitudes calculated from stellar
	spectra library. Then calculates the colors in the specified bands (must be present
	in the catalog) and make plots.
	"""
    def __init__(self, catalog):
        """
Пример #23
0
def outTrans(input):
    """Compute out of transit spectra
    
    Computes the out of transit spectra by normalizing flux to specified 
    magnitude and convert to specified Pandeia units of milliJy and microns.  
  
    Parameters 
    ----------
    input : dict
        stellar scene which includes parameters to extract phoenix database or a 
        filename which points to a stellar spectrum 
    
    Return
    ------
    dict 
        contains wave and flux_out_trans
    """

    ref_wave = float(input['ref_wave'])
    mag = float(input['mag'])

    ################# USER ####################################
    if input['type'] == 'user':
        star = np.genfromtxt(
            input['starpath'], dtype=(float, float),
            names='w, f')  #pyfits.getdata(input['starpath'],1)
        #get flux
        flux = star['f']  #star.field(input['logg'])
        #get wavelength and reference wavelength for mag normalization
        wave = star['w']  #star.field('WAVELENGTH')

        #sort if not in ascending order
        sort = np.array([wave, flux]).T
        sort = sort[sort[:, 0].argsort()]
        wave = sort[:, 0]
        flux = sort[:, 1]
        if input['w_unit'] == 'um':
            PANDEIA_WAVEUNITS = 'um'

        elif input['w_unit'] == 'nm':
            PANDEIA_WAVEUNITS = 'nm'

        elif input['w_unit'] == 'cm':
            PANDEIA_WAVEUNITS = 'cm'

        elif input['w_unit'] == 'Angs':
            PANDEIA_WAVEUNITS = 'angstrom'

        elif input['w_unit'] == 'Hz':
            PANDEIA_WAVEUNITS = 'Hz'

        else:
            raise Exception(
                'Units are not correct. Pick um, nm, cm, hz, or Angs')

        #convert to photons/s/nm/m^2 for flux normalization based on
        #http://www.gemini.edu/sciops/instruments/integration-time-calculators/itc-help/source-definition
        if input['f_unit'] == 'Jy':
            PANDEIA_FLUXUNITS = 'jy'
        elif input['f_unit'] == 'FLAM':
            PANDEIA_FLUXUNITS = 'FLAM'
        else:
            raise Exception('Units are not correct. Pick FLAM or Jy')

        sp = psyn.ArraySpectrum(
            wave,
            flux,
            waveunits=PANDEIA_WAVEUNITS,
            fluxunits=PANDEIA_FLUXUNITS
        )  #Convert evrything to nanometer for converstion based on gemini.edu
        sp.convert("nm")
        sp.convert('jy')

    ############ PHOENIX ################################################
    elif input['type'] == 'phoenix':
        #make sure metal is not out of bounds
        if input['metal'] > 0.5: input['metal'] = 0.5
        sp = psyn.Icat("phoenix", input['temp'], input['metal'], input['logg'])
        sp.convert("nm")
        sp.convert("jy")
        wave = sp.wave
        flux = sp.flux
        input['w_unit'] = 'nm'
        input['f_unit'] = 'jy'

    else:
        raise Exception('Wrong input type for stellar spectra')

    ############ NORMALIZATION ################################################
    refdata = os.environ.get("pandeia_refdata")

    all_bps = {
        "H": 'bessell_h_004_syn.fits',
        "J": 'bessell_j_003_syn.fits',
        "K": 'bessell_k_003_syn.fits'
    }

    if (ref_wave <= 1.3) & (ref_wave >= 1.2):
        filt = 'J'
    elif (ref_wave <= 1.7) & (ref_wave >= 1.6):
        filt = 'H'
    elif (ref_wave <= 2.3) & (ref_wave >= 2.1):
        filt = 'K'
    else:
        raise Exception('Only J H and K zeropoints are included')

    bp_path = os.path.join(refdata, "normalization", "bandpass", all_bps[filt])
    bp = psyn.FileBandpass(bp_path)

    sp.convert('angstroms')
    bp.convert('angstroms')

    rn_sp = sp.renorm(mag, 'vegamag', bp)

    rn_sp.convert("microns")
    rn_sp.convert("mjy")

    flux_out_trans = rn_sp.flux
    wave = rn_sp.wave
    return {'flux_out_trans': flux_out_trans, 'wave': wave, 'phoenix': sp}
Пример #24
0
 def testthru(self):
     self.bpref = S.FileBandpass(
         (self.fname % 'thru').replace('.fits', '_ref.fits'))
     self.arraytest(self.bpref.throughput, self.bp.throughput)
Пример #25
0
 def testoutputfix(self):
     bp=S.FileBandpass(self.fname)
     idx=N.where(bp.wave == 4)
     num=len(idx[0])
     self.assertFalse(num != 1, "%d occurrences found"%num)
Пример #26
0
def go():
    import os
    import pysynphot as S
    import numpy as np
    import matplotlib.pyplot as plt
    
    import pandeia.engine as etc
    import pandeia.engine.jwst
    import pandeia.engine.calc_utils
    import pandeia.engine.etc3D
    import pandeia.engine.source
    import pandeia.engine.observation
    
    nis = etc.jwst.NIRISS(mode='imaging', config={})
    
    instruments = [etc.jwst.NIRCam, etc.jwst.NIRISS, etc.jwst.MIRI]
        
    modes = [[etc.jwst.NIRISS, 'imaging'], [etc.jwst.NIRCam, 'sw_imaging'], [etc.jwst.NIRCam, 'lw_imaging'], [etc.jwst.MIRI, 'imaging']]

    #modes = [[etc.jwst.NIRCam, 'sw_imaging'], [etc.jwst.NIRCam, 'lw_imaging'], [etc.jwst.MIRI, 'imaging']]

    src = etc.calc_utils.build_default_source()
    #src = etc.source.Source(src_dict)
    src['spectrum']['normalization']['norm_flux'] = 25.0
    src['spectrum']['normalization']['norm_fluxunit'] = 'abmag'
    
    jw = etc.jwst.JWST()
    
    #ote_int = jw.get_ote_eff(wave)
    coll_area = jw.coll_area
    
    ote_file = os.path.join(jw.ref_dir, jw.paths['otefile'])
    ote_bp = S.FileBandpass(ote_file)
    
    filters = {(pandeia.engine.jwst.NIRCam, 'sw_imaging'): ['f070w', 'f090w', 'f115w', 'f150w', 'f200w', 'f150w2', 'f140m', 'f162m', 'f182m', 'f210m', 'f164n', 'f187n', 'f212n'], 
               (pandeia.engine.jwst.NIRCam, 'lw_imaging'): ['f277w', 'f356w', 'f444w', 'f322w2', 'f250m', 'f300m', 'f335m', 'f360m', 'f410m', 'f430m', 'f460m', 'f480m', 'f323n', 'f405n', 'f466n', 'f470n'],
               (pandeia.engine.jwst.NIRISS, 'imaging'): ['f090w', 'f115w', 'f150w', 'f200w', 'f140m', 'f158m', 'f277w', 'f356w', 'f444w', 'f380m', 'f430m', 'f480m'],
               (pandeia.engine.jwst.MIRI, 'imaging'): ['f1065c', 'f1140c', 'f1550c', 'f2300c', 'f560w', 'f770w', 'f1000w', 'f1130w', 'f1280w', 'f1500w', 'f1800w', 'f2100w', 'f2550w']}
    
    fp_info = open('jwst.filters.info','w')
    fp_res = open('jwst.filters.res','w')
    
    # Next number in master FILTER.RES file
    count = 330
    count = 350
    
    today = '030818'
    today = '290419'
    
    for mode in modes:
        ins = mode[0](mode=mode[1])
        ins_str = ins.as_dict()['instrument']['instrument']
        #filters = ins.filters
        for filter in filters[tuple(mode)]:
            label='{0} {1} {2}'.format(mode[0], mode[1], filter)
            
            ins = mode[0](mode=mode[1], config={'instrument':{'filter':filter}})
            
            filter_file = os.path.join(ins.ref_dir, ins.paths[filter])
            filter_bp = S.FileBandpass(filter_file)
            wave = filter_bp.wave
            
            # obs = etc.observation.Observation(instrument=ins)
            # obs.background = 'low'
            # obs.scene.sources[0].spectrum = src['spectrum']
            # det = etc.etc3D.DetectorSignal(observation=obs)
            
            # Manual combine components
            if False:
                ote_int = jw.get_ote_eff(wave)#*coll_area
                filter_eff = ins.get_filter_eff(wave)
                disperser_eff = ins.get_disperser_eff(wave)
                internal_eff = ins.get_internal_eff(wave)
                qe = ins.get_detector_qe(wave)
                #q_yield, fano_factor = ins.get_quantum_yield(wave)
            
                #total_filter = ote_int*filter_eff*internal_eff*qe
            
            total_filter = ins.get_total_eff(wave)
            total_filter *= ins.get_quantum_yield(wave)[0]
                        
            #print(label)
            
            # Resample to R=300
            if filter.endswith('n'):
                R = 1000
            else:
                R = 300
                
            w = np.exp(np.arange(np.log(wave[0]), np.log(wave[-1]), 1./R))
            bp = S.ArrayBandpass(wave*1.e4, total_filter).resample(w*1.e4)

            if total_filter.max() < 0.02:
                continue

            plt.plot(bp.wave, bp.throughput, label=label)
            
            N = len(bp.wave)
            filter_tag = os.path.basename(filter_file).split('.fits')[0]
            filter_label = '{0} lambda_c= {1:.4e}'.format(filter_tag, bp.pivot())
            
            #label_res = '{0:>5d} {1}/{2}/{3}/{4} lambda_c= {5:.4e}'.format(N, ins_str, mode[1], filter, today, bp.pivot())
            #label_info = '{0:>5d} {1}/{2}/{3}/{4} lambda_c= {5:.4e}'.format(count, ins_str, mode[1], filter, today, bp.pivot())
            label_res = '{0:>5d} {1}'.format(N, filter_label)
            label_info = '{0:>5d} {1:>5} {2}'.format(count, N, filter_label)
            
            print(label_info)
            
            fp_res.write(label_res+'\n')
            for i in range(N):
                fp_res.write('{0:<5d} {1:.5e} {2:.5e}\n'.format(i+1, bp.wave[i], bp.throughput[i]))


            fp_info.write(label_info+'\n')
            
            count += 1
            
    fp_info.close()
    fp_res.close()
    
            
            
Пример #27
0
 def setUp(self):
     self.opener = S.FileBandpass
     self.fname = '$PYSYN_CDBS/comp/ota/hst_ota_007_syn.fits'
     self.ref = S.FileBandpass(
         os.path.join(os.environ['PYSYN_CDBS'], 'comp', 'ota',
                      'hst_ota_007_syn.fits'))
Пример #28
0
#!/usr/bin/env python
#
import os, sys
import pysynphot as psyn

TOP = '/Users/sontag/dev/pandeia_data/jwst/niriss'
glist = ['gr150r', 'gr150c']
flist = ['f090w', 'f115w', 'f140m', 'f150w', 'f158m', 'f200w']

for grism in glist:
    for filter in flist:
        gname = TOP + '/blaze/' + grism + '_1_blaze.fits'
        gcurve = psyn.FileBandpass(gname)
        gcurve.convert('angstroms')

        fname = TOP + '/filters/' + filter + '.fits'
        fcurve = psyn.FileBandpass(fname)
        fcurve.convert('angstroms')

        outname = '/Users/sontag/NEW/niriss_' + grism + '_' + filter + '.fits'
        combined = fcurve * gcurve
        combined.convert('angstroms')
        print '-' * 75
        print outname
        print 'fcurve (waveunits, wave.max, tp.max)'
        print fcurve.waveunits, fcurve.wave.max(), fcurve.throughput.max()
        print 'gcurve (waveunits, wave.max, tp.max)'
        print gcurve.waveunits, gcurve.wave.max(), gcurve.throughput.max()
        print 'combined (waveunits, wave.max, tp.max)'
        print combined.waveunits, combined.wave.max(), combined.throughput.max(
        )
Пример #29
0
filterdir = os.getcwd() + '/vphas_atmosphere_included_filters'
#filterdir = os.getcwd()+'/vphas_filters'
filter_fpaths = glob.glob(filterdir + '/*.dat')

for fpath in filter_fpaths:
    #if 'u_SDSS' in fpath:
    #	bandpass = S.FileBandpass(fpath)
    #	u_bp = bandpass
    #elif 'g_SDSS' in fpath:
    #	bandpass = S.FileBandpass(fpath)
    #	g_bp = bandpass

    #use the filtercurved emailed by Janet Drew that contain the known u
    # and g band red leak
    if 'u-transmission' in fpath:
        bandpass = S.FileBandpass(fpath)
        u_bp = bandpass
    elif 'g-transmission' in fpath:
        bandpass = S.FileBandpass(fpath)
        g_bp = bandpass

    elif 'r_SDSS' in fpath:
        bandpass = S.FileBandpass(fpath)
        r_bp = bandpass
    elif 'i_SDSS' in fpath:
        bandpass = S.FileBandpass(fpath)
        i_bp = bandpass
    elif 'J_2MASS' in fpath:
        bandpass = S.FileBandpass(fpath)
        J_bp = bandpass
Пример #30
0
import numpy as np
import FileSED
import pysynphot as S
import matplotlib.pyplot as plt
from pygoods import sextractor
import cosmoclass
import kcorr
# For plotting colors of stars, look at starlib.py

cosmo_def = cosmoclass.cosmoclass(H0=70., omega_m=0.3, omega_l=0.7)
# lbgtemp = 'galtemplates/lbgtemp_z6_0.4Zsolar_constSFH_100Myr.sed'
# Below are HST ACS/WFC3IR filters in CLASH; likely all I'll need for high-z
# stuff?
banddir = '/Users/khuang/Dropbox/codes/mypytools/sedtools/bandpass'
uvimos = S.FileBandpass('%s/U_vimos.bp' % banddir)
uvimos.name = 'UVIMOS'
f435w = S.ObsBandpass('acs,wfc2,f435w')
f475w = S.ObsBandpass('acs,wfc2,f475w')
f555w = S.ObsBandpass('acs,wfc2,f555w')
f606w = S.ObsBandpass('acs,wfc2,f606w')
f625w = S.ObsBandpass('acs,wfc2,f625w')
f775w = S.ObsBandpass('acs,wfc2,f775w')
f814w = S.ObsBandpass('acs,wfc2,f814w')
f850lp = S.ObsBandpass('acs,wfc2,f850lp')
f098m = S.ObsBandpass('wfc3,ir,f098m')
f105w = S.ObsBandpass('wfc3,ir,f105w')
f110w = S.ObsBandpass('wfc3,ir,f110w')
f125w = S.ObsBandpass('wfc3,ir,f125w')
f140w = S.ObsBandpass('wfc3,ir,f140w')
f160w = S.ObsBandpass('wfc3,ir,f160w')