def calc_dict(reddenings):

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

    for EBmV in reddenings:

        spectrum = S.ArraySpectrum(np.array(wl), np.array(flx), 'angstrom',
                                   'flam')
        spectrum = spectrum * S.Extinction(EBmV, 'mwavg')

        #calculate colours
        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)

        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
Exemplo n.º 2
0
 def chi2(self, bands, mags, magerrs, fit='flux'):
     """
   Calculate the total chi-square for self.spec given a list of bands 
   (pysynphot SpectralElement instances) and magnitudes and errors.
   """
     if fit == 'mag':
         mags = np.array(mags)
         magerrs = np.array(magerrs)
         mags_spec = [
             S.Observation(self.rspec, b).effstim('abmag') for b in bands
         ]
         mags_spec = np.array(mags_spec)
         # chi2 = ((mags_spec - mags)**2 / mags_spec)
         chi2 = (((mags_spec - mags) / magerrs)**2).sum()
         if self.verbose:
             print mags_spec, self.beta, self.A, chi2
     elif fit == 'flux':
         fluxes = np.array([pu.ABmag2uJy(m)
                            for m in mags])  # in micro-Jansky
         sn = [pu.magerr2sn(m) for m in magerrs]
         fluxerrs = fluxes / sn  # to get flux errors from S/N
         # Now sample the reference spectrum at the central wavelengths
         self.rspec.convert('muJy')  # convert to micro-Jansky
         # flux_spec = [self.rspec.sample(b.pivot()) for b in bands]
         flux_spec = [
             S.Observation(self.rspec, b).effstim('muJy') for b in bands
         ]
         flux_spec = np.array(flux_spec)  # convert to micro-Jansky
         chi2 = (((flux_spec - fluxes) / fluxerrs)**2).sum()
         self.rspec.convert('flam')  # go back to flam
     return chi2
def get_magnitudes(Teff, FeH=0.0, logg=4.5, Vmag=10, magScale='vegamag'):
    # Load the Filters
    bp_j = S.ObsBandpass('j')
    bp_h = S.ObsBandpass('h')
    bp_k = S.ObsBandpass('k')
    bp_v = S.ObsBandpass('johnson,v')

    # Stellar spectrum normalized to V=10 mags (default Phoenix models)
    sp = S.Icat(
        'phoenix', Teff, FeH,
        logg)  #pynrc.stellar_spectrum(stellarType, Vmag, 'vegamag', bp_v)

    sp_norm = sp.renorm(Vmag, magScale, bp_v)
    sp_norm.name = sp.name
    sp = sp_norm

    # Observe in J, H, and K
    obs_j = S.Observation(sp, bp_j, binset=sp.wave)
    obs_h = S.Observation(sp, bp_h, binset=sp.wave)
    obs_k = S.Observation(sp, bp_k, binset=sp.wave)

    # Magnitudes in each filter
    mag_j = obs_j.effstim(magScale)
    mag_h = obs_h.effstim(magScale)
    mag_k = obs_k.effstim(magScale)

    return mag_j, mag_h, mag_k
Exemplo n.º 4
0
def synphotSNR(filtname,
               mag,
               etime=1200,
               nexp=4,
               aperture=0.4,
               pixscale=0.128):
    import pysynphot as syn
    from numpy import pi, sqrt
    bandpass = syn.ObsBandpass('wfc3,ir,%s,aper#%.1f' % (filtname, aperture))
    sn1a = syn.FileSpectrum('sn1a_flux_max.dat').redshift(1.5).renorm(
        mag, 'abmag', bandpass)
    sourcecps = syn.Observation(sn1a, bandpass).countrate()
    srccounts = sourcecps * etime

    skybandpass = syn.ObsBandpass('wfc3,ir,%s' % filtname)
    earthshine = syn.FileSpectrum('earthshine_average.dat')
    earthcps_arcsec2 = syn.Observation(earthshine, skybandpass,
                                       force='extrap').countrate()
    V = syn.ObsBandpass('landolt,V')
    zodiacal = syn.FileSpectrum('zodiacal_high.dat').renorm(22.7, 'vegamag', V)
    zodcps_arcsec2 = syn.Observation(zodiacal, skybandpass,
                                     force='extrap').countrate()

    aparea_arcsec2 = pi * aperture**2
    aparea_pix = aparea_arcsec2 / pixscale**2
    npix = (aparea_arcsec2 / pixscale**2)
    sharpness = 3.3 / npix

    skycounts = (earthcps_arcsec2 + zodcps_arcsec2) * aparea_arcsec2 * etime
    skycounts_pix = skycounts / npix

    # TODO : get thermal noise, dark current and readnoise from SYNPHOT
    darkcps_arcsec2 = 3.05
    darkcounts = darkcps_arcsec2 * aparea_arcsec2 * etime
    darkcounts_pix = darkcounts / npix

    thermcps_arcsec2 = 8.15
    thermcounts = thermcps_arcsec2 * aparea_arcsec2 * etime
    thermcounts_pix = thermcounts / npix

    rdnoise_pix = 12.5  # read noise per pixel (per exposure)
    rdnoiseTot = rdnoise_pix * aparea_pix  # 161.61

    bgcounts_pix = skycounts_pix + darkcounts_pix + thermcounts_pix

    noise = sqrt(srccounts + npix * bgcounts_pix +
                 npix * nexp * rdnoise_pix**2)

    SNR = srccounts / noise

    onoise = sqrt(srccounts + (bgcounts_pix + rdnoise_pix**2) / sharpness)
    oSNR = srccounts / onoise

    return SNR, oSNR
Exemplo n.º 5
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
Exemplo n.º 6
0
    def get_adu_per_sec(self, vegamag, BandPass):
        """
        Get the photon count in phot/s for a star with a Vega magnitude of *vegamag* in a given pysynphot.BandPass

        These are the total photon counts the telescope/imager will see.

        INPUT:
            vegamag  - Vega magnitude in a given bandpass
            BandPass - pysynphot.BandPass class

        OUTPUT:
            photons per second

        NOTES:
            Accounts for QE
        """
        # Convolve QE, BandPass, and Throughput
        CombinedBP = self.QE * self.Throughput * BandPass
        # Use Vega magnitudes
        VegaSpectrum = S.Vega.renorm(vegamag, 'vegamag', CombinedBP)
        # Define observation
        obs = S.Observation(VegaSpectrum,
                            CombinedBP,
                            binset=VegaSpectrum.GetWaveSet())
        # pysynphot is automatically set up to calculate for Hubble, we just need to scale the area
        hubble_area = S.refs.PRIMARY_AREA
        electrons_per_sec = (
            obs.countrate() / hubble_area
        ) * self.area  # electrons per second, as we are using QE information
        # convert to adu_per_sec
        adu_per_sec = electrons_per_sec / self.gain
        return adu_per_sec
Exemplo n.º 7
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)
Exemplo n.º 8
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)
Exemplo n.º 9
0
def compute_zodi(ra, dec, jd, FILTER='F140W', verbose=False):
    """
    Get the predicted Zodiacal surface brightness and then fold it through the Synphot WFC3 filters
    """
    import pysynphot as S

    thermal = {
        'F160W': 0.134,
        'F140W': 0.069,
        'F105W': 0.051,
        'F110W': 0.05,
        'F125W': 0.052,
        'F128N': 0.051,
        'F130N': 0.051,
        'F132N': 0.051,
        'F164N': 0.0651,
        'G141': 0.1,
        'G102': 0.04,
        'F098M': 0.05
    }

    lat, lng = helio_lat_lng(ra, dec, jd)
    SB = get_zodi_SB(lat, lng)
    if verbose:
        print 'Lat, Lng: %f, %f, SB=%.2f' % (lat, lng,
                                             SB + 2.5 * np.log10(0.128254**2))

    zod = S.FileSpectrum('%s/zodiacal_model_001.fits' % (datapath()))
    nz = zod.renorm(SB, S.units.VegaMag, S.ObsBandpass("V"))
    bp = S.ObsBandpass('wfc3,ir,%s' % (FILTER.lower()))
    obs = S.Observation(nz, bp)

    return obs.countrate() + thermal[FILTER]
Exemplo n.º 10
0
def fit_UVslope(filternames,
                mags,
                magerrs,
                z,
                beta0=-2.0,
                normband=filters['f850lp'],
                normmag=25.0,
                verbose=False,
                fit='flux'):
    """
   Fit a UV slope (beta) to the observed rest-frame UV magnitudes.
   bands - a list of strings as filter names (e.g., f160w)
   mags, magerrs - lists of magnitude and magnitude errors
   """
    x = UVSlope(1500., beta0, z)
    mag = S.Observation(x.rspec, normband).effstim('abmag')
    A0 = 10.**(normmag - mag)
    bands = [filters[b] for b in filternames]

    def func((beta, A)):
        y = UVSlope(1500., beta, z, A, verbose=verbose)
        return y.chi2(bands, mags, magerrs, fit=fit)

    # print beta0, A0, func((beta0, A0))
    output = scipy.optimize.fmin(func, np.array([beta0, A0]), maxiter=1000)
    return output
Exemplo n.º 11
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)
Exemplo n.º 12
0
def apply_filter(stars, colour):
    """
    Generates a binary filter based on the colour selected and passes the stars 
    spectrum through this filter, being normalised to its actual magnitude as observed
    outputs an oberservation from this spectrum for use in other programs
    """

    nwavels = 3501
    wavels = np.linspace(3500, 7000, nwavels)

    if colour == "red":
        throughput = custom_bandpass(wavels, [5750, 6500])  # 750nm range
    elif colour == "green":
        throughput = custom_bandpass(wavels, [4750, 6000])  # 1250nm range
    elif colour == "blue":
        throughput = custom_bandpass(wavels, [4000, 5250])  # 1250nm range

    band_bin = S.ArrayBandpass(wavels, throughput)

    for star in stars:
        star_obj = star[0]
        mag = star[3]

        filtered_spec = star_obj.renorm(mag, 'vegamag', band_bin)
        observation = S.Observation(filtered_spec, band_bin, binset=wavels)

        star.append(filtered_spec)
        star.append(observation)

    return stars
Exemplo n.º 13
0
def compute_photometry(catalog, photmode):
    """ Compute magnitudes for sources from catalog based on observations photmode

    Parameters
    -----------
    catalog : object
        Astropy Table with 'source_sum' column for the measured flux for each source

    photmode : String
        Specification of the observation filter configuration used for the exposure
        as reported by the 'PHOTMODE' keyword from the PRIMARY header.

    Returns
    --------
    phot_cat : object
        Astropy Table object of input source catalog with added column for
        VEGAMAG photometry (in magnitudes).
    """
    # Determine VEGAMAG zero-point using pysynphot for this photmode
    photmode = photmode.replace(' ', ',')
    vega = S.FileSpectrum(VEGASPEC)
    bp = S.ObsBandpass(photmode)
    vegauvis = S.Observation(vega, bp)
    vegazpt = 2.5 * np.log10(vegauvis.countrate())

    # Use zero-point to convert flux values from catalog into magnitudes
    source_phot = vegazpt - 2.5 * np.log10(catalog['source_sum'])
    source_phot.name = 'vegamag'
    # Now add this new column to the catalog table
    catalog.add_column(source_phot)

    return catalog
Exemplo n.º 14
0
def show_uvslope_fit(filternames, mags, magerrs, z, beta, A):
    x = UVSlope(1500., beta, z, A=A)
    plt.figure()
    bands = [filters[b] for b in filternames]
    waves = np.array([b.pivot() for b in bands])
    plt.errorbar(waves,
                 mags,
                 yerr=magerrs,
                 ls='none',
                 fmt='x',
                 mew=2,
                 ms=12,
                 capsize=10,
                 elinewidth=2)
    x.rspec.convert('fnu')  # in erg cm^-2 s^-1 Hz^-1
    rspec = x.rspec * (1. / 1.e-29)  # in micro-Jansky
    plt.plot(rspec.wave,
             23.9 - 2.5 * np.log10(rspec.flux),
             lw=1.5,
             label=r'$\beta=%.2f$' % beta)
    plt.scatter(waves,
                [S.Observation(x.rspec, b).effstim('abmag') for b in bands],
                marker='s',
                facecolor='none',
                edgecolor='red',
                linewidths=2,
                s=30**2)
    plt.xscale('log')
    plt.xlim(0.9 * waves.min(), 1.1 * waves.max())
    plt.ylim(np.min(mags) - 1.0, np.max(mags) + 1.0)
    plt.xticks(waves, filternames)
    plt.legend(loc=0)
    plt.gca().invert_yaxis()
    plt.show()
Exemplo n.º 15
0
def calcphot(log, wavelengthArray, fluxArray, obsmode):
    """
    *Run calcphot on single spectrum and filter.*

    **Key Arguments:**
        - ``log`` -- logger
        - ``wavelengthArray`` -- the array containing the wavelength range of the spectrum
        - ``fluxArray`` -- the array contain the respective spectrum flux (as function of wavelength)
        - ``obsmode`` -- the observation mode (generally a filter system and filter type, e.g. "sdss,g")

    **Return:**
        - None
    """
    ################ > IMPORTS ################
    ## STANDARD LIB ##
    ## THIRD PARTY ##
    import pysynphot as syn
    ## LOCAL APPLICATION ##

    ################ > VARIABLE SETTINGS ######
    # Read in a spectrum from a file
    sp = syn.ArraySpectrum(
        wave=wavelengthArray, flux=fluxArray, waveunits='angstrom', fluxunits='flam')
    bp = syn.ObsBandpass(obsmode)
    obs = syn.Observation(sp, bp)
    abMag = obs.effstim('abmag')

    return abMag
Exemplo n.º 16
0
 def photflam(self):
     ps.setref(**self.REFS)
     sp = ps.FlatSpectrum(0, fluxunits='stmag')
     sp.convert('angstroms')
     bp = self.bandpass
     obs = ps.Observation(sp, bp, binset=sp.wave)
     return obs.effstim('flam') / obs.countrate()
Exemplo n.º 17
0
 def testextrap(self):
     self.obs = S.Observation(self.sp, self.bp, force='extrap')
     idx = N.where(self.obs.wave == self.refwave)
     test = self.obs.flux.item(idx[0])
     self.assertAlmostEqual(test,
                            self.refval,
                            msg='Expected %f, got %f' % (self.refval, test))
Exemplo n.º 18
0
def test_observation_binset():
    bp = S.ObsBandpass('acs,hrc,f555w')

    spec = S.FlatSpectrum(1)

    obs = S.Observation(spec, bp)

    assert (bp.binset == obs.binwave).all()
Exemplo n.º 19
0
def get_pb_zpt(pb, reference='AB', model_mag=None):
    """
	Determines a passband zeropoint for synthetic photometry, given a reference
	standard and its model magnitude in the passband

	Parameters
	----------
	pb : :py:class:`pysynphot.ArrayBandpass` or :py:class:`pysynphot.obsbandpass.ObsModeBandpass`
		The passband data.
		Must have ``dtype=[('wave', '<f8'), ('throughput', '<f8')]``
	reference : str, optional
		The name of the reference spectrophotometric standard to use to determine the passband zeropoint.
		'AB' or 'Vega' (default: 'AB')
	model_mag : float, optional
		The magnitude of the reference spectrophotometric standard in the passband.
		default = None

	Returns
	-------
	pbzp : float
		passband AB zeropoint

	Raises
	------
	RuntimeError
		If the passband and reference standard do not overlap
	ValueError
		If the reference model_mag is invalid

	See Also
	--------
	:py:func:`source_synphot.passband.synflux`
	:py:func:`source_synphot.passband.synphot`
	"""

    # setup the photometric system by defining the standard and corresponding magnitude system
    if reference.lower() not in ('vega', 'ab'):
        message = 'Do not understand mag system reference standard {}. Must be AB or Vega'.format(
            reference)
        raise RuntimeError(message)
    if reference.lower() == 'ab':
        refspec = S.FlatSpectrum(3631, fluxunits='jy')
        mag_type = 'abmag'
    else:
        refspec = S.Vega
        mag_type = 'vegamag'

    refspec.convert('flam')

    if model_mag is None:
        ob = S.Observation(refspec, pb)
        model_mag = ob.effstim(mag_type)

    synphot_mag = synphot(refspec, pb, zp=0.)
    #print(synphot_mag)
    #print(model_mag)
    outzp = model_mag - synphot_mag
    return outzp
Exemplo n.º 20
0
def counts_syn_no_norm(x, m, b, A, wave):

    spec = spec_norm(m, b, A, wave)
    sp = S.ArraySpectrum(wave, spec, waveunits='angstrom', fluxunits='photlam', name='MySource', keepneg=True)
    counts2 = np.zeros((4))
    for i in range((4)):
        obs = S.Observation(sp, S.ObsBandpass('acs,sbc,%s' % (filter_name[i])))
        counts2[i] = obs.countrate()  # effstim('counts')
    return counts2
Exemplo n.º 21
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)
Exemplo n.º 22
0
 def normalize_abmag(self, normmag, normband):
     if type(normband) in [type(0), type(0.0)]:
         # abmag = self.copy.ABmag_lambda(normband)
         filt = S.Box(normband, 100.)
         # obs = S.Observation(self.copy, filt)
         obs = S.Observation(self.sp, filt)
         abmag = obs.effstim('abmag')
     else:
         # abmag = self.copy.ABmag(normband)
         # obs = S.Observation(self.copy, normband)
         obs = S.Observation(self.sp, normband)
         abmag = obs.effstim('abmag')
     dmag = normmag - abmag
     # self.copy._fluxtable = self.copy._fluxtable * 10.**(-0.4 * dmag)
     self.copy = self.sp * 10.**(-0.4 * dmag)
     self.normband = normband
     self.normmag = normmag
     # self.sp = self.sp * 10.**(-0.4 * dmag) * area_tenpc
     # multiply the flux by 10 pic
     return 10.**(-0.4 * dmag)
Exemplo n.º 23
0
def compute_zpts(instrument, detector, band, mjd):
    bandpass = pyS.ObsBandpass('{:s},{:s},{:s},mjd#{:d}'.format(
        instrument, detector, band, mjd))
    spec_bb = pyS.BlackBody(50000)
    spec_bb_norm = spec_bb.renorm(1, 'counts', bandpass)
    obs = pyS.Observation(spec_bb_norm, bandpass)
    zps = {}
    zps['vega'] = obs.effstim('vegamag')
    zps['st'] = obs.effstim('stmag')
    zps['ab'] = obs.effstim('abmag')
    return zps
Exemplo n.º 24
0
 def setUp(self):
     self.sp = S.BlackBody(4400)
     #Note that this bandpass has a simple 1A-spacing binwave
     self.bp = S.ObsBandpass('acs,hrc,f555w')
     self.refwave = 5500  #Angstroms
     self.obs = S.Observation(self.sp, self.bp)
     self.obs.convert('counts')
     self.tda = dict(thresh=0.001)
     self.tra = dict()
     self.tda['spectrum'] = str(self.sp)
     self.tra['bandpass'] = str(self.bp)
Exemplo n.º 25
0
 def zeropoint(self):
     ps.setref(**self.REFS)
     standard_star_file = GetStipsData(
         os.path.join("standards", "alpha_lyr_stis_008.fits"))
     sp = ps.FileSpectrum(standard_star_file)
     sp.convert('angstroms')
     bp = self.bandpass
     sp = sp.renorm(0.0, "VEGAMAG", bp)
     obs = ps.Observation(sp, bp, binset=sp.wave)
     zeropoint = obs.effstim("OBMAG")
     return zeropoint
Exemplo n.º 26
0
 def setUp(self):
     #Use a defined comptab here: we're examining native arrays
     self.oldref = S.refs.getref()
     S.setref(comptable='$PYSYN_CDBS/mtab/u4c18498m_tmc.fits')
     self.sp = S.BlackBody(4400)
     self.bp = S.ObsBandpass('stis,fuvmama,g140m,c1470,s52x01')
     self.obs = S.Observation(self.sp, self.bp)
     self.refwave = 1450
     self.tda = dict(thresh=0.001)
     self.tra = dict()
     self.tda['spectrum'] = str(self.sp)
     self.tra['bandpass'] = str(self.bp)
Exemplo n.º 27
0
    def setup_class(self):
        """Subclass needs to define ``obsmode`` and ``spectrum``
        class variables for this to work.

        """
        if not HAS_PYSYNPHOT:
            raise ImportError(
                'ASTROLIB PYSYNPHOT must be installed to run these tests')

        # Make sure both software use the same graph and component tables.

        conf.graphtable = self.tables['graphtable']
        conf.comptable = self.tables['comptable']
        conf.thermtable = self.tables['thermtable']

        S.setref(graphtable=self.tables['graphtable'],
                 comptable=self.tables['comptable'],
                 thermtable=self.tables['thermtable'])

        # Construct spectra for both software.

        self.sp = parse_spec(self.spectrum)
        self.bp = band(self.obsmode)

        # Astropy version has no prior knowledge of instrument-specific
        # binset, so it has to be set explicitly.
        if hasattr(self.bp, 'binset'):
            self.obs = Observation(self.sp,
                                   self.bp,
                                   force=self.force,
                                   binset=self.bp.binset)
        else:
            self.obs = Observation(self.sp, self.bp, force=self.force)

        # Astropy version does not assume a default waveset
        # (you either have it or you don't). If there is no
        # waveset, no point comparing obs waveset against ASTROLIB.
        if self.sp.waveset is None or self.bp.waveset is None:
            self._has_obswave = False
        else:
            self._has_obswave = True

        self.spref = old_parse_spec(self.spectrum)
        self.bpref = S.ObsBandpass(self.obsmode)
        self.obsref = S.Observation(self.spref, self.bpref, force=self.force)

        # Ensure we are comparing in the same units
        self.bpref.convert(self.bp._internal_wave_unit.name)
        self.spref.convert(self.sp._internal_wave_unit.name)
        self.spref.convert(self.sp._internal_flux_unit.name)
        self.obsref.convert(self.obs._internal_wave_unit.name)
        self.obsref.convert(self.obs._internal_flux_unit.name)
Exemplo n.º 28
0
def converter(path1,path2,path3,input_filter,input_spectral,input_magnitude,input_photometric,output_filter,output_photometric):
    final_output = None
    os.environ["PYNRC_PATH"] =str(path1)
    os.environ["PYSYN_CDBS"] =str(path2)
    os.environ["WEBBPSF_PATH"] = str(path3)
    import pysynphot as S
    import pynrc
    bp_K = S.ObsBandpass(input_filter)
    bg = pynrc.nrc_utils.stellar_spectrum(input_spectral,input_magnitude,input_photometric,bp_K)
    bp_ncfilter = pynrc.nrc_utils.read_filter(output_filter)
    obs = S.Observation(bg,bp_ncfilter,binset=bg.wave)
    final_output = obs.effstim(output_photometric)
    return final_output
Exemplo n.º 29
0
def findCountRate(instr, filt, Teff=5800., z=0.0, logg=4.44, radius=1., distance=10., vega=False, webbpsf=False, **kwargs):

    if instr=='NIRCam': filt=filt[:5] # Strip the mask string off, e.g. F210M-MASK210R

    # CREATE SPECTRUM OBJECT:
    spec=Spectrum(instr, filt)

    # CREATE FILTER BANDPASS FOR FILTER NAME:
    bandpass=spec.getBandpass()  

    # CREATE SPECTRUM BASED ON Teff, Z, and LOGG:
    star=spec.getSpectrum(Teff=Teff, z=z, logg=logg, vega=vega) # Returns Angstroms, Flam

    # SCALE FOR DISTANCE & CONVERT UNITS TO: photons s^-1 cm^-2 A^-1
    if vega==False:  star*=(radius*2.254e-8/distance)**2 #Distance in units of parsec
    star.convert("photlam") 

    # CREATE OBSERVATION (STAR times BANDPASS):
    obs=S.Observation(star,bandpass, binset=star.wave) 
    #print 'units: ',obs.waveunits, obs.fluxunits

    # ADD QE/GERMANIUM/OTE TRANSMISSION TO OBSERVATION:
    if webbpsf:
        print "Using images created by WebbPSF"
        if instr == 'MIRI': 
            bp_QE   = spec.getMIRI_QE()
            obs     = S.Observation(obs,bp_QE)
            bp_Germ = spec.getMIRI_Germanium()
            obs     = S.Observation(obs,bp_Germ)
            bp_OTE  = spec.getMIRI_OTE_transmission()
            obs     = S.Observation(obs,bp_OTE)
        else: pass # FOR NIRCam, QE/OTE PROFILES ARE INCLUDED IN FILTER TRANSMISSION CURVES
    else: pass     # FOR IMAGES CREATED WITH MATHEMATICA, QE/GERMANIUM/OTE ARE ALREADY INCLUDED

    # INTEGRATE TOTAL NUMBER OF PHOTONS OVER BANDPASS:
    ncounts=np.trapz(obs.flux,obs.wave)*DefaultSettings.JWSTREFS['area']  #multiply by collecting area

    return ncounts, spec
Exemplo n.º 30
0
    def makeobservation(self, observer, outUnit='ABMag'):
        '''Makes an observation of the spectrum through the years.'''

        # Check
        if not (isinstance(observer, psp.spectrum.SpectralElement)
                or hasattr(observer, 'throughput')):
            raise TypeError('observer must be a pysynphot observer')
        outUnit = outUnit.lower()

        # Make Observation measurments
        meas = []
        for spec, _ in self:
            meas.append(psp.Observation(spec, observer).effstim(outUnit))
        return np.array(meas)