def test_backgrounds(thisday=100): """ Test backgrounds output from github example.""" # Column Names column_names = ['wavelenght', 'total_background', 'zodical_background', 'nonzodical_background', 'stray_light_background', 'thermal_background'] # Read truth files data_file = join(TEST_DIR, 'background.txt') truth = ascii.read(data_file, names=column_names) # Run background calculation bkg = background(261.6833333, -73.33222222, 2.15, thresh=1.1) calendar = bkg.bkg_data['calendar'] thisday_index = np.where(thisday == calendar)[0][0] data = [] for i, wavelength in enumerate(bkg.bkg_data['wave_array']): data.append([wavelength, bkg.bkg_data['total_bg'][thisday_index][i], bkg.bkg_data['zodi_bg'][thisday_index][i], bkg.bkg_data['nonzodi_bg'][i], bkg.bkg_data['stray_light_bg'][thisday_index][i], bkg.bkg_data['thermal_bg'][i]]) # Build background output table test_data = Table(rows=data, names=column_names) # Compare values of tables. assert truth.values_equal(test_data)
def niriss_background_scaling(param_dict, detector, module): """Determine the scaling factor needed to translate the pre-existing NIRISS WFSS background image to the requested signal level, which is one of "low", "medium", or "high", as with the ETC. Parameters ---------- param_dict : dict Dictionary of observation information from an input yaml file detector : str Name of detector, e.g. "NRCA1" module : str Name of module, e.g. "A" Returns ------- ratio : float Ratio of the background value at the pivot wavelength that corresponds to the requested level, ratioed to that for the "medium" level, which is what was used to create the NIRISS WFSS background images. """ # Generate background spectra for all days background = jbt.background(param_dict['Telescope']['ra'], param_dict['Telescope']['dec'], 4.) # Determine which optical element wheel contains the filter we want # to use for background estimation if param_dict['Readout']['pupil'][0].upper() == 'F': usefilt = 'pupil' else: usefilt = 'filter' # Get basic flux calibration information vegazp, photflam, photfnu, pivot_wavelength = fluxcal_info( param_dict, usefilt, detector, module) # Extract the spectrum value across all days at the pivot wavelength wave_diff = np.abs(background.bkg_data['wave_array'] - pivot_wavelength) bkgd_wave = np.where(wave_diff == np.min(wave_diff))[0][0] bkgd_at_pivot = background.bkg_data['total_bg'][:, bkgd_wave] # Now sort and determine the low/medium/high levels low, medium, high = find_low_med_high(bkgd_at_pivot) # Find the value based on the level in the yaml file background_level = param_dict['simSignals']['bkgdrate'].lower() if background_level == "low": level_value = low elif background_level == "medium": level_value = medium elif background_level == "high": level_value = high else: raise ValueError(( "ERROR: Unrecognized background value: {}. Must be low, medium, or high" .format(params_dict['simSignals']['bkgdrate']))) return level_value
def day_of_year_background_spectrum(ra, dec, observation_date): """Call jwst_backgrounds in order to produce an estimate of background versus wavelength for a particular pointing on a particular day of year. Parameters ---------- ra : float Right Ascention of pointing dec : float Declination of pointing observation_date : str Requested day of year of the observation i.e. '2021-10-31' Returns ------- background_waves : numpy.ndarray 1D array with the wavelength values in microns associated with ``background_signals`` background_sigmals : numpy.ndarray 1D array containing background values in MJy/str """ # Generate background spectra for all days background = jbt.background(ra, dec, 4.) # Confirm that the target is observable of the requested day of year obsdate = datetime.datetime.strptime(observation_date, '%Y-%m-%d') obs_dayofyear = obsdate.timetuple().tm_yday if obs_dayofyear not in background.bkg_data['calendar']: raise ValueError(( "ERROR: The requested RA, Dec is not observable on {}. Either " "specify a different day, or set simSignals:use_dateobs_for_background " "to False.".format(observation_date))) # Extraxct the spectrum for the requested day match = obs_dayofyear == background.bkg_data['calendar'] background_waves = background.bkg_data['wave_array'] background_signals = background.bkg_data['total_bg'][match, :][0] return background_waves, background_signals
def test_day_of_year_background_spectrum(): """Make sure the function returns a spectrum of wavelength and flux values. """ ra = 57.2 dec = -27.6 observation_date = '2020-12-10' waves, signals = backgrounds.day_of_year_background_spectrum( ra, dec, observation_date) assert isinstance(waves, np.ndarray) assert isinstance(signals, np.ndarray) assert len(waves.shape) == 1 assert len(signals.shape) == 1 background = jbt.background(ra, dec, 4.) obsdate = datetime.datetime.strptime(observation_date, '%Y-%m-%d') obs_dayofyear = obsdate.timetuple().tm_yday assert obs_dayofyear in background.bkg_data['calendar']
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()
F = FLARE.filters.add_filters(filters) PSF = SynthObs.Morph.webbPSFs( filters, 4.) # creates a dictionary of instances of the webbPSF class wavelengths = np.array([F[f].pivwv() / 1E4 for f in F['filters']]) # --- hopefully this is the same as the benchmark background ra = 261.6833333 dec = -73.3322222 day = 170 # calculate background bg = jbt.background(ra, dec, wavelengths) # identify index of day day_i = np.argwhere(bg.bkg_data['calendar'] == day)[0][0] # --- telescope area - precise? area = 25. * 100**2 # cm2 pixel_s = 0.031 pixel_l = 0.063 source_flux_original = 100 # nJy t_exp = 9974.46 # s
def low_medium_high_background_value(ra, dec, background_level, filter_waves, filter_throughput, siaf_info): """Calculate the integrated background flux density for a given filter, using the filter's throughput curve and the user-input background level (e.g. "medium") Parameters ---------- ra : float Right ascention of the pointing. Units are degrees dec : float Declineation of the pointing. Units are degrees background_level : str "low", "medium", or "high", just as with the ETC filter_waves : numpy.ndarray 1d array of wavelengths in microns to be used along with ``filter_throughput`` filter_throughput : numpy.ndarray 1d array of filter throughput values to convolve with the background spectrum. Normalized units. 1.0 = 100% transmission. siaf_info : pysiaf.Siaf Siaf information for the detector/aperture in use Returns ------- value : float Background value corresponding to ``background_level``, integrated over the filter bandpass. Background units are e-/sec/pixel. """ # Get background information bg = jbt.background(ra, dec, 4.) back_wave = bg.bkg_data['wave_array'] bsigs = np.zeros(len(bg.bkg_data['total_bg'][:, 0])) for i in range(len(bg.bkg_data['total_bg'][:, 0])): back_sig = bg.bkg_data['total_bg'][i, :] # Interpolate background to match filter wavelength grid bkgd_interp = np.interp(filter_waves, back_wave, back_sig) # Combine filt_bkgd = bkgd_interp * filter_throughput # Convert from MJy/sr to e-/sec/pixel pixelarea = siaf_info.XSciScale * u.arcsec * siaf_info.YSciScale * u.arcsec photon_total = PRIMARY_MIRROR_AREA * (filt_bkgd * u.MJy / u.sr) * ( 1. / PLANCK) * 1.e-20 * pixelarea.to( u.sr) / (filter_waves * u.micron) bsigs[i] = np.trapz(photon_total.value, x=filter_waves) # Now sort and determine the low/medium/high levels low, medium, high = find_low_med_high(bsigs) # Find the value based on the level in the yaml file background_level = background_level.lower() if background_level == "low": value = low elif background_level == "medium": value = medium elif background_level == "high": value = high else: raise ValueError(( "ERROR: Unrecognized background value: {}. Must be low, mediumn, or high" .format(background_level))) return value
def low_med_high_background_spectrum(param_dict, detector, module): """Call jwst_backgrounds in order to produce an estimate of background versus wavelength for a particular pointing that corresponds to one of "low", "medium", or "high", as with the ETC. Parameters ---------- param_dict : dict Dictionary of observation information from an input yaml file detector : str Name of detector, e.g. "NRCA1" module : str Name of module, e.g. "A" Returns ------- background_waves : numpy.ndarray 1D array with the wavelength values in microns associated with ``background_signals`` background_spec : numpy.ndarray 1D array containing background values in MJy/str """ # Generate background spectra for all days background = jbt.background(param_dict['Telescope']['ra'], param_dict['Telescope']['dec'], 4.) # Get basic flux calibration information vegazp, photflam, photfnu, pivot_wavelength = fluxcal_info( param_dict['Reffiles']['flux_cal'], param_dict['Inst']['instrument'], param_dict['Readout']['filter'], param_dict['Readout']['pupil'], detector, module) # Extract the spectrum value across all days at the pivot wavelength wave_diff = np.abs(background.bkg_data['wave_array'] - pivot_wavelength) bkgd_wave = np.where(wave_diff == np.min(wave_diff))[0][0] bkgd_at_pivot = background.bkg_data['total_bg'][:, bkgd_wave] # Now sort and determine the low/medium/high levels low, medium, high = find_low_med_high(bkgd_at_pivot) # Find the value based on the level in the yaml file background_level = param_dict['simSignals']['bkgdrate'].lower() if background_level == "low": level_value = low elif background_level == "medium": level_value = medium elif background_level == "high": level_value = high else: raise ValueError(( "ERROR: Unrecognized background value: {}. Must be low, mediumn, or high" .format(param_dict['simSignals']['bkgdrate']))) # Find the day with the background at the pivot wavelength that # is closest to the value associated with the requested level diff = np.abs(bkgd_at_pivot - level_value) mindiff = np.where(diff == np.min(diff))[0][0] background_spec = background.bkg_data['total_bg'][mindiff, :] return background.bkg_data['wave_array'], background_spec
from jwst_backgrounds import jbt pointings = [{'ra':53.1625,'dec':27.7914,'name':'HUDF'}, {'ra':83.8187,'dec':-5.3872,'name':'Trapezium'}, {'ra':266.41683,'dec':-29.00781,'name':'Galactic Center'}] wavelength = 4.4 #micron for pointing in pointings: bg = jbt.background(pointing['ra'],pointing['dec'],wavelength) print(pointing['name'], bg.bathtub['total_thiswave'][0], 'MJy/sr') jbt.get_background(223.555, -54.395, 2.15, thresh=1.1, plot_background=True, plot_bathtub=True, write_bathtub=True)
detailed_output = False F = FLARE.filters.add_filters(filters) # wavelengths = np.array([F[f].pivwv()/1E4 for f in F['filters']]) wavelengths = np.arange(0.5, 5.5, 0.01) from jwst_backgrounds import jbt # --- hopefully this is the same as the benchmark background (it is not) ra = 261.6833333 dec = -73.3322222 day = 170 bg = jbt.background(ra,dec, wavelengths) # calculate background day_i = np.argwhere(bg.bkg_data['calendar'] == day)[0][0] # identify index of day # --- telescope area - precise? area = 25.4*100**2 # cm2 pixel_s = 0.031 pixel_l = 0.063 t_exp = 9974.46 # s pandeia = {'JWST.NIRCAM.F070W': 1126.0721474889592, 'JWST.NIRCAM.F090W': 1786.7394403286296, 'JWST.NIRCAM.F115W': 1958.3717674718248, 'JWST.NIRCAM.F150W': 2094.999837765901, 'JWST.NIRCAM.F200W': 2061.5719837568827, 'JWST.NIRCAM.F140M': 981.5902707204624, 'JWST.NIRCAM.F162M': 942.9066381746721, 'JWST.NIRCAM.F182M': 1185.001923425075, 'JWST.NIRCAM.F210M': 834.308953687194, 'JWST.NIRCAM.F277W': 5783.452503476042, 'JWST.NIRCAM.F356W': 5598.499153909868, 'JWST.NIRCAM.F444W': 10433.88191793632, 'JWST.NIRCAM.F250M': 1812.3164234617484, 'JWST.NIRCAM.F300M': 2043.4940798266255, 'JWST.NIRCAM.F360M': 2468.310748196025, 'JWST.NIRCAM.F410M': 3277.565422796658, 'JWST.NIRCAM.F430M': 1862.4507469018095, 'JWST.NIRCAM.F460M': 2187.9391545638887, 'JWST.NIRCAM.F480M': 3220.657767138416} background = {}