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()
def setUp(self): self.sp = S.BlackBody(5000) self.bp = S.ObsBandpass('Johnson,V') self.oldref = S.refs.getref() S.setref(comptable='$PYSYN_CDBS/mtab/t260548pm_tmc.fits') self.tda = dict(spectrum=str(self.sp), bp=str(self.bp)) self.tda.update(refs.getref())
def setUp(self): graphtab = 'mtab$u921351jm_tmg.fits' comptab = 'mtab$v8h1925fm_tmc.fits' thermtab = 'mtab$tae17277m_tmt.fits' S.setref(graphtable=graphtab, comptable=comptab, thermtable=thermtab)
def setUp(self): self.spectrum = "((earthshine.fits*0.5)%2brn(spec(Zodi.fits),band(V),22.7,vegamag)%2b(el1215a.fits*0.5)%2b(el1302a.fits*0.5)%2b(el1356a.fits*0.5)%2b(el2471a.fits*0.5))" self.obsmode = "acs,sbc,F140LP" self.refrate = 0.0877036 self.oldref = S.refs.getref() S.setref(comptable='$PYSYN_CDBS/mtab/t260548pm_tmc.fits') self.tda = dict(spectrum=str(self.spectrum), bp=str(self.obsmode)) self.tda.update(refs.getref()) self.setup2()
def setUp(self): self.spectrum = "((earthshine.fits*0.5)%2brn(spec(Zodi.fits),band(V),22.7,vegamag)%2b(el1215a.fits*0.5)%2b(el1302a.fits*0.5)%2b(el1356a.fits*0.5)%2b(el2471a.fits*0.5))" self.obsmode = "acs,sbc,F140LP" self.refrate = 0.0877036 self.oldref = S.refs.getref() S.setref(comptable='$PYSYN_CDBS/mtab/t260548pm_tmc.fits') self.tda = dict(spectrum=str(self.spectrum), bp=str(self.obsmode)) self.tda.update(refs.getref()) self.setup2()
def setUp(self): self.sp=S.BlackBody(5000) self.bp=S.ObsBandpass('Johnson,V') self.oldref = S.refs.getref() S.setref(comptable='$PYSYN_CDBS/mtab/t260548pm_tmc.fits') self.tda=dict(spectrum=str(self.sp), bp=str(self.bp) ) self.tda.update(refs.getref())
def setUp(self): self.spectrum = "spec(earthshine.fits)*0.5+rn(spec(Zodi.fits),band(johnson,v),22.7,vegamag)+(spec(el1215a.fits)+spec(el1302a.fits)+spec(el1356a.fits)+spec(el2471a.fits))" self.obsmode = "cos,fuv,g140l,c1105" # These tests were defined using this graph table self.oldref = refs.getref() S.setref(comptable='$PYSYN_CDBS/mtab/tad1851am_tmc.fits') self.setup2() self.tda = dict(obsmode=self.obsmode, spectrum=self.spectrum) self.tda.update(refs.getref())
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
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)
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)
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)
def setUp(self): self.oldcwd = os.getcwd() os.chdir(os.path.dirname(__file__)) self.oldref = S.refs.getref() S.setref(comptable='$PYSYN_CDBS/mtab/t260548pm_tmc.fits') self.spectrum = "data/qso_template.fits" self.obsmode = "cos,fuv,g140l,c1230,PSA" self.syncmd = "rn(spec(%s),band(%s),17.0,vegamag)" % (self.spectrum, self.obsmode) self.tda = dict(spectrum=self.spectrum, obsmode=self.obsmode, syncmd=self.syncmd, file=S.__file__)
def setUp(self): self.oldcwd = os.getcwd() os.chdir(os.path.dirname(__file__)) self.oldref = S.refs.getref() S.setref(comptable='$PYSYN_CDBS/mtab/t260548pm_tmc.fits') self.spectrum = "data/qso_template.fits" self.obsmode = "cos,fuv,g140l,c1230,PSA" self.syncmd = "rn(spec(%s),band(%s),17.0,vegamag)" % (self.spectrum, self.obsmode) self.tda = dict(spectrum=self.spectrum, obsmode=self.obsmode, syncmd=self.syncmd, file=S.__file__)
def setUp(self): self.oldcwd = os.getcwd() os.chdir(os.path.dirname(__file__)) self.oldref = S.refs.getref() S.setref(comptable='$PYSYN_CDBS/mtab/t260548pm_tmc.fits') self.spectrum = "data/qso_template.fits" self.obsmode = "cos,fuv,g140l,c1230,PSA" self.bp = S.ObsBandpass(self.obsmode) self.sp = S.FileSpectrum(self.spectrum) self.tst = self.sp.renorm(17.0, 'vegamag', self.bp) self.tda = dict(spectrum=self.spectrum, obsmode=self.obsmode, file=S.__file__)
def setUp(self): self.oldcwd = os.getcwd() os.chdir(os.path.dirname(__file__)) self.oldref = S.refs.getref() S.setref(comptable='$PYSYN_CDBS/mtab/t260548pm_tmc.fits') self.spectrum="data/qso_template.fits" self.obsmode="cos,fuv,g140l,c1230,PSA" self.bp=S.ObsBandpass(self.obsmode) self.sp=S.FileSpectrum(self.spectrum) self.tst=self.sp.renorm(17.0,'vegamag',self.bp) self.tda=dict(spectrum=self.spectrum, obsmode=self.obsmode, file=S.__file__)
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)
def make_cluster_rates(self,masses,instrument,filter,bandpass=None,refs=None): coords = np.load(os.path.join(self.gridpath, 'input.npy')) m, t, g, i = self.get_star_info() temps = np.interp(masses,m,t) gravs = np.interp(masses,m,g) mags = np.interp(masses,m,i) metals = np.full_like(mags, self.metallicity) if os.path.exists(os.path.join(self.gridpath, 'result_{}_{}.npy'.format(instrument.lower(), filter.lower()))): values = np.load(os.path.join(self.gridpath, 'result_{}_{}.npy'.format(instrument.lower(), filter.lower()))) interpolation_function = RegularGridInterpolator(tuple([x for x in coords]), values) try: countrates = interpolation_function(np.array((metals, gravs, temps, mags)).T) except ValueError as v: self.log('error', 'Exception caught when interpolating: {}'.format(v)) min_mag = coords[-1][0] max_mag = coords[-1][-1] interpolation_function = RegularGridInterpolator(tuple([x for x in coords]), values, bounds_error=False, fill_value=0.) mags_min = np.full_like(mags, min_mag) mags_max = np.full_like(mags, max_mag) countrates = interpolation_function(np.array((metals, gravs, temps, mags)).T) countrates_min = interpolation_function(np.array((metals, gravs, temps, mags_min)).T) countrates_min = countrates_min * np.power(10, -(mags-min_mag)/2.512) countrates_max = interpolation_function(np.array((metals, gravs, temps, mags_max)).T) countrates_max = countrates_max * np.power(10, -(mags-max_mag)/2.512) countrates[np.where(mags < mags_min)] = countrates_min[np.where(mags < mags_min)] countrates[np.where(mags > mags_max)] = countrates_max[np.where(mags > mags_max)] else: self.log('warning', 'Could not find result file "result_{}_{}.npy"'.format(instrument.lower(), filter.lower())) import pysynphot as ps countrates = np.array(()) ps.setref(**refs) johnson_i = ps.ObsBandpass('johnson,i') for te, log_g, z, j_i in zip(temps, gravs, metals, mags): spectrum = ps.Icat('phoenix', te, z, log_g) spectrum = spectrum.renorm(j_i, 'vegamag', johnson_i) obs = ps.Observation(spectrum, bandpass, binset=spectrum.wave) countrates = np.append(countrates, obs.countrate()) return countrates
def readPhoenixRealtimeTable(self, table, bp, cached=-1): """ Converts a set of Phoenix sources specified as (id, ra, dec, T, Z, log(g), apparent) into individual stars, observes them, and then produces an output catalogue """ ps.setref(**self.REFS) ids = table['id'] ras = table['ra'] decs = table['dec'] temps = table['teff'] gravs = table['log_g'] metallicities = table['metallicity'] apparents = table['apparent'] norm_bp = '{}'.format(apparents.unit) if norm_bp == '': norm_bp = 'johnson,i' rates = np.zeros_like(ras) for index in range(len(ids)): t, g, Z, a = temps[index], gravs[index], metallicities[ index], apparents[index] sp = ps.Icat('phoenix', t, Z, g) sp = self.normalize(sp, a, norm_bp) obs = ps.Observation(sp, bp, binset=sp.wave) rates[index] = obs.countrate() t = Table() t['ra'] = Column(data=ras) t['dec'] = Column(data=decs) t['flux'] = Column(data=rates) t['type'] = Column(data=np.full_like(ras, "point", dtype="S6")) t['n'] = Column(data=np.full_like(ras, "N/A", dtype="S3")) t['re'] = Column(data=np.full_like(ras, "N/A", dtype="S3")) t['phi'] = Column(data=np.full_like(ras, "N/A", dtype="S3")) t['ratio'] = Column(data=np.full_like(ras, "N/A", dtype="S3")) t['id'] = Column(data=ids) t['notes'] = Column(data=np.full_like(ras, "None", dtype="S6")) return t, cached
def readPandeiaTable(self, table, bp, cached=-1): """ Converts a set of Pandeia phoenix sources specified as (id, ra, dec, key, apparent) into individual stars, observes them, and then produces an output catalogue """ from pandeia.engine.sed import SEDFactory ps.setref(**self.REFS) ids = table['id'] ras = table['ra'] decs = table['dec'] keys = table['key'] apparents = table['apparent'] norm_bp = '{}'.format(apparents.unit) if norm_bp == '': norm_bp = 'johnson,i' rates = np.array((), dtype='float32') for a, key in zip(apparents, keys): config = {'sed_type': 'phoenix', 'key': key} spectrum = SEDFactory(config=config) wave, flux = spectrum.get_spectrum() sp = self.normalize((wave, flux), a, norm_bp) obs = ps.Observation(sp, bp, binset=sp.wave) rates = np.append(rates, obs.countrate()) t = Table() t['ra'] = Column(data=ras) t['dec'] = Column(data=decs) t['flux'] = Column(data=rates) t['type'] = Column(data=np.full_like(ras, "point", dtype="S6")) t['n'] = Column(data=np.full_like(ras, "N/A", dtype="S3")) t['re'] = Column(data=np.full_like(ras, "N/A", dtype="S3")) t['phi'] = Column(data=np.full_like(ras, "N/A", dtype="S3")) t['ratio'] = Column(data=np.full_like(ras, "N/A", dtype="S3")) t['id'] = Column(data=ids) t['notes'] = Column(data=np.full_like(ras, "None", dtype="S6")) return t, cached
def pixel_background(self): if self.background_value == 'none': return 0. from jwst_backgrounds import jbt bg = jbt.background(self.ra, self.dec, self.PHOTPLAM[self.filter]) wave_array = bg.bkg_data['wave_array'] combined_bg_array = bg.bkg_data['total_bg'] if self.background_value == 'avg': flux_array = np.mean(combined_bg_array, axis=0) elif self.background_value == 'med': flux_array = np.median(combined_bg_array, axis=0) elif self.background_value == 'max': flux_array = np.max(combined_bg_array, axis=0) elif self.background_value == 'min': flux_array = np.min(combined_bg_array, axis=0) else: flux_array = combined_bg_array[0] # Convert background flux from MJy/sr to mJy/pixel. # Conversion: * 1e9 for MJy -> mJy # Conversion: * 2.3504e-11 for sr^-2 -> arcsec^-2 # Conversion: * self.SCALE[0] * self.SCALE[1] for arcsec^-2 -> pixel^-2 flux_array_pixels = 1e9 * flux_array * 2.3504e-11 * self.SCALE[ 0] * self.SCALE[1] ps.setref(**self.REFS) sp = ps.ArraySpectrum(wave_array, flux_array_pixels, waveunits='micron', fluxunits='mjy') sp.convert('angstroms') sp.convert('photlam') obs = ps.Observation(sp, self.bandpass, binset=sp.wave) return obs.countrate()
table.drop_duplicates(subset='WAVELENGTH (ANGSTROM)', inplace=True) # create pysynphot spectrum sp = S.ArraySpectrum(table['WAVELENGTH (ANGSTROM)'], table['FLUX (ERG/CM2/S/A)'], fluxunits='flam', waveunits='Angstroms') # Storage dict mags = {} if observation == 'UCAM': # This is the bandpass in the relevant lightpath telescope, instrument = "ntt", "ucam" # Setup the *CAM S.setref(**getref(telescope)) for filt in filters: # Get the lightpath bp = S.ObsBandpass('{},{},{}'.format(telescope, instrument, filt)) # Run the spectrum through the bandpass. Should include atmosphere? obs = S.Observation(sp, bp, force="taper") # Convert to magnitude ADU_flux = obs.countrate() mag = obs.effstim('abmag') mags[filt] = mag print("Band: {}".format(filt))
def tearDown(self): S.setref(comptable=self.oldref['comptable'])
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
def setUpModule(): #Specify a TMC file S.setref(comptable='mtab$t921857im_tmc.fits')
def tearDown(self): S.setref(comptable=self.oldref['comptable'])
""" By C. D. Kilpatrick 2019-05-08 """ # Python 2/3 compatibility from __future__ import print_function import sys,os,astropy,h5py,bisect,warnings,scipy import numpy as np import astropy.constants import astropy.units as u from astropy.table import Table warnings.filterwarnings('ignore') import pysynphot as S S.setref(area = 25.0 * 10000) A_TO_CM = u.angstrom.to(u.centimeter) A_TO_MU = u.angstrom.to(u.micron) MPC_TO_CM = u.megaparsec.to(u.centimeter) C_CGS = astropy.constants.c.cgs.value # Set up IDL and options #idl = pidyl.IDL(os.environ['IDL_DIR']+'/bin/idl') #idl.pro('set_plot','ps') # Global plotting options for IDL #idl_opt = { # 'font': '!6', # 'thick': 4, # 'xthick': 4,
def tearDown(self): os.chdir(self.oldpath) S.setref(comptable=self.oldref['comptable'])
def readBC95Table(self, table, bp, cached=-1): """ Converts a BC95 galaxy grid of sources into the internal source table standard """ # This function is needed because I can't get python not to read '50E8' as a number, or to output it as a correctly formatted string def stringify(num): num = float(num) exponent = int(np.floor(np.log10(num))) value = int(10 * (num / (10**np.floor(np.log10(num))))) return "{}E{}".format(value, exponent - 1) from pandeia.engine.custom_exceptions import PysynphotError self._log("info", "Converting BC95 Catalogue") proflist = {"expdisk": 1, "devauc": 4} ps.setref(**self.REFS) distance_type = "redshift" ids = table['id'] ras = table['ra'] decs = table['dec'] try: zs = table['redshift'] except KeyError: #distances instead zs = table['distance'] distance_type = "pc" models = table['model'] ages = table['age'] profiles = table['profile'] radii = table['radius'] / self.SCALE[ 0] #at some point, may want to figure out multiple scales. ratios = table['axial_ratio'] pas = (table['pa'] + (self.pa * 180. / np.pi)) % 360. vmags = table['apparent_surface_brightness'] norm_bp = '{}'.format(vmags.unit) self._log( "info", "Normalization Bandpass is {} ({})".format(norm_bp, type(norm_bp))) if norm_bp == '' or norm_bp is None or norm_bp == 'None': norm_bp = 'johnson,v' self._log("info", "Normalization Bandpass is {}".format(norm_bp)) rates = np.array(()) indices = np.array(()) notes = np.array((), dtype='object') total = len(models) for i, (z, model, age, profile, radius, ratio, pa, mag) in enumerate( zip(zs, models, ages, profiles, radii, ratios, pas, vmags)): # self._log("info", "{} of {}: {} {} {} {} {} {} {} {}".format(i, total, z, model, age, profile, radius, ratio, pa, mag)) fname = "bc95_{}_{}.fits".format(model, stringify(age)) try: sp = ps.FileSpectrum( os.path.join(os.environ['PYSYN_CDBS'], "grid", "bc95", "templates", fname)) if distance_type == "redshift": sp = sp.redshift(z) sp = self.normalize(sp, mag, norm_bp) obs = ps.Observation(sp, self.bandpass, force='taper', binset=sp.wave) rate = obs.countrate() except PysynphotError as e: self._log( 'warning', 'Source {} of {}: Pysynphot Error {} encountered'.format( i, total, e.message)) rate = 0. rates = np.append(rates, rate) indices = np.append(indices, proflist[profile]) notes = np.append(notes, "BC95_%s_%s_%f" % (model, stringify(age), mag)) t = Table() t['ra'] = Column(data=ras, format='%8.4f') t['dec'] = Column(data=decs, format='% 9.4f') t['flux'] = Column(data=rates, format='%8g') t['type'] = Column(data=np.full_like(ras, 'sersic', dtype='S7'), format='%-7s') t['n'] = Column(data=indices, format='%8g') t['re'] = Column(data=radii, format='%9.5f') t['phi'] = Column(data=pas, format='%9.5f') t['ratio'] = Column(data=ratios, format='%9.5f') t['id'] = Column(data=ids, format='%8d') t['notes'] = Column(data=notes, format='%-25s') return t, cached
import os import sys import numpy as N import pysynphot as S from pysynphot import spparser #For thermal classes only from pysynphot.observationmode import ObservationMode #BUG: find a better way DATADIR = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'data') S.setref(comptable='$PYSYN_CDBS/mtab/tad1851am_tmc.fits', thermtable='$PYSYN_CDBS/mtab/tae17277m_tmt.fits', graphtable='$PYSYN_CDBS/mtab/t2605492m_tmg.fits') class SpecCase(object): class __metaclass__(type): def __new__(mcs, name, bases, dict): cls = type.__new__(mcs, name, bases, dict) cls.location = os.path.abspath( os.path.dirname(sys.modules[cls.__module__].__file__)) return cls @classmethod def setUpClass(cls): """Always overridden by the child cases, but let's put some real values in here to test with"""
def tearDownModule(): S.setref(comptable=orig_ref['comptable'])
def teardown_class(self): """Reset config for both software.""" for cfgname in self.tables: conf.reset(cfgname) S.setref()
def tearDown(self): S.setref(comptable=self.oldref['comptable']) os.chdir(self.oldcwd)
names=['WAVELENGTH (ANGSTROM)', 'FLUX (ERG/CM2/S/A)'] ) # drop duplicate wavelengths. WTF are they here Koester? koester_spectrum.drop_duplicates(subset='WAVELENGTH (ANGSTROM)', inplace=True) # create pysynphot spectrum sp = S.ArraySpectrum( koester_spectrum['WAVELENGTH (ANGSTROM)'], koester_spectrum['FLUX (ERG/CM2/S/A)'], fluxunits='flam', waveunits='Angstroms' ) # Set the lightpath for the hcam observations S.setref(**getref(hcam_tel)) # Get all the hcam magnitudes simulated_mags = {} for f in hcam_filters: bp = S.ObsBandpass("{},{},{}".format('hcam',hcam_tel, f)) obs = S.Observation(sp, bp, force='taper') mag = obs.effstim("abmag") simulated_mags['hcam_{}'.format(f)] = mag # Get the actual colours for colour in SDSS_COLOURS: f1, f2 = colour.split("-") colour_mag = simulated_mags["hcam_{}".format(f1)] - simulated_mags["hcam_{}".format(f2)] row[colour] = colour_mag
def get_col_correction(telescope, instrument, filter, teff, logg, plot=False): S.setref(**getref(telescope)) bp = S.ObsBandpass('{},{},{}'.format(telescope, instrument, filter)) bp_HCAM_GTC = S.ObsBandpass( 'hcam,gtc,{}'.format(filter.split('_')[0] + '_s')) table_fname = get_fname(teff, logg) teff, logg = get_teff_logg(table_fname) table = pd.read_csv(table_fname, delim_whitespace=True, comment='#', names=['WAVELENGTH (ANGSTROM)', 'FLUX (ERG/CM2/S/A)']) # drop duplicate wavelengths. WTF are they here Koester? table.drop_duplicates(subset='WAVELENGTH (ANGSTROM)', inplace=True) # create pysynphot spectrum sp = S.ArraySpectrum(table['WAVELENGTH (ANGSTROM)'], table['FLUX (ERG/CM2/S/A)'], fluxunits='flam', waveunits='Angstrom') obs = S.Observation(sp, bp, force='taper') obs_HCAM_GTC = S.Observation(sp, bp_HCAM_GTC, force='taper') tot_mag = obs.effstim('abmag') col_term = obs_HCAM_GTC.effstim('abmag') - tot_mag if plot: # Plotting stuff limits = (bp.wave.min(), bp.wave.max()) cut_table = table[(table['WAVELENGTH (ANGSTROM)'] < limits[1]) & (table['WAVELENGTH (ANGSTROM)'] > limits[0])] fig, ax = plt.subplots() ax2 = ax.twinx() ax2.plot(bp.wave, bp.throughput, color='red', linestyle='--', label='{}, {} Throughput'.format(instrument, telescope)) ax2.plot(bp_HCAM_GTC.wave, bp_HCAM_GTC.throughput, color='black', linestyle='--', label='HCAM, GTC Throughput') ax.plot(obs.wave, obs.flux, color='red', label='{}, {} stimulation'.format(instrument, telescope)) ax.plot(obs_HCAM_GTC.wave, obs_HCAM_GTC.flux, color='black', label='HCAM, GTC stimulation') ax.step(cut_table['WAVELENGTH (ANGSTROM)'], cut_table['FLUX (ERG/CM2/S/A)'], color='lightgrey', label='Raw Spectrum') ax.set_title( "Teff: {} || log(g): {} || detected magnitude: {:.3f} || Color {:.3f}" .format(teff, logg, tot_mag, col_term)) ax.set_xlabel("Wavelength, Angstroms") ax.set_ylabel("Flux, erg/cm2/s/A") ax.set_xlim(limits) fig.legend() plt.tight_layout() plt.show() return col_term
print("\t{}: Starting log(g) = {}".format(time.ctime(), logg)) for k, teff in enumerate(coords[2]): print("\t\t{}: Starting Teff = {}".format(time.ctime(), teff)) spec = ps.Icat('phoenix', teff, Z, logg) counts = False if sum(spec.flux) > 0: counts = True for l, mag in enumerate(coords[3]): print( "\t\t\t{} of {}: {}: Starting Z = {}, log(g) = {}, Teff = {}, Mabs = {:>4}" .format(n + 1, total, time.ctime(), Z, logg, teff, mag), end='') if counts: spec_norm = spec.renorm(mag, 'vegamag', norm_bandpass) for instrument in instruments: ps.setref(area=area[instrument.lower()], waveset=(500, 260000, 10000., 'log')) for mode in modes[instrument.lower()]: for filter in filters[instrument.lower()][mode]: if counts: obs = ps.Observation( spec_norm, bandpasses[instrument.lower()][filter], binset=spec_norm.wave) result_arrays[instrument.lower()][filter][ i, j, k, l] = obs.countrate() print(".", end='') else: result_arrays[instrument.lower()][filter][ i, j, k, l] = 0. print("x", end='') print("")
def bandpass(self): import pysynphot as ps ps.setref(**self.REFS) obsmode = "wfc3,ir," + self.filter.lower() return ps.ObsBandpass(obsmode)
def setUpModule(): #Answers computed using specified comptable S.setref(comptable='mtab$t9m1635am_tmc.fits')
def tearDown(self): S.setref()
def tearDownModule(): S.setref(comptable=orig_comptable)
def teardown_class(self): """Reset config for both software.""" for cfgname in self.tables: conf.reset(cfgname) S.setref()
import h5py import bisect import matplotlib.pyplot as plt from matplotlib.backends.backend_pdf import PdfPages cdbs = os.getenv('PYSYN_CDBS') if cdbs is None: cdbs = '~/work/synphot/' cdbs = os.path.expanduser(cdbs) os.environ['PYSYN_CDBS'] = cdbs import pysynphot as S import webbpsf as W # define some constants SPEED_OF_LIGHT = astropy.constants.c.cgs.value TELESCOPE_AREA = 25.0 * 10000 # cm^2 -- Area of the telescope has to be in centimeters because pysynphot... S.setref(area=TELESCOPE_AREA) SEC_TO_DAY = u.second.to(u.day) CM_TO_ANGSTROM = u.centimeter.to(u.angstrom) ANGSTROM_TO_CM = u.angstrom.to(u.centimeter) FNU_TO_MJY = (u.erg / (u.centimeter**2) / u.second / u.Hertz).to(u.microjansky) ANGSTROM_TO_MICRON = u.angstrom.to(u.micron) MPC_TO_CM = u.megaparsec.to(u.centimeter) DISTANCE = [50, 120, 200] TMAX = 90 class Kilonova(object): def __init__(self): """ Read Dan's Kilonova spectral model and return the base arrays """
cam_filters = super_filters if filt == 'super' else sdss_filters # Lets store it all in a pandas dataframe. INFO = ['SpecType', 'PicklesName'] SDSS_COLOURS = ['u-g', 'g-r', 'r-i', 'i-z'] CORRECTIONS = ["{}-{}".format(a, b) for a, b in zip(cam_filters, sdss_filters)] COLNAMES = INFO + SDSS_COLOURS + CORRECTIONS table = pd.DataFrame(columns=COLNAMES) # Get the SDSS colours for name, spec in pickles_ms: row = {'SpecType': spec, 'PicklesName': name} # Unset the *CAM thruput stuff S.setref(comptable=None, graphtable=None) # leave the telescope area as it was S.setref(area=None) # reset the telescope area as well # Synthetic spectrum sp = S.FileSpectrum(os.path.join(pickles_path, name + '.fits')) # Apply extinction to that spectrum ext = S.Extinction(ebv, 'gal3') sp = sp * ext # Get all the magnitudes simulated_mags = {} for f in sdss_filters: bp = S.ObsBandpass("{},{}".format('sdss', f)) obs = S.Observation(sp, bp, force='taper') mag = obs.effstim("abmag")
def setUpModule(): #Specify a TMC file S.setref(comptable='mtab$t921857im_tmc.fits')
def tearDownModule(): S.setref(comptable=orig_ref['comptable'])
def tearDown(self): S.setref(comptable=self.oldref['comptable']) os.chdir(self.oldcwd)