pynrc.obs_hci
- class pynrc.obs_hci(sp_sci, distance, sp_ref=None, wfe_ref_drift=5, wfe_roll_drift=2, wind_mode='WINDOW', xpix=320, ypix=320, disk_params=None, autogen_coeffs=True, sgd_type=None, slew_std=0, fsm_std=0, **kwargs)[source]
Bases:
nrc_hciNIRCam coronagraphic observations
Subclass of the
nrc_hciinstrument class used to observe stars (plus exoplanets and disks) with either a coronagraph or direct imaging.The main concept is to generate a science target of the primary source along with a simulated disk structure. Planets are further added to the astronomical scene. A separate reference source is also defined for PSF subtraction, which contains a specified WFE. A variety of methods exist to generate slope images and analyze the PSF-subtracted results via images and contrast curves.
- __init__(sp_sci, distance, sp_ref=None, wfe_ref_drift=5, wfe_roll_drift=2, wind_mode='WINDOW', xpix=320, ypix=320, disk_params=None, autogen_coeffs=True, sgd_type=None, slew_std=0, fsm_std=0, **kwargs)[source]
Init function for obs_hci class
- Parameters:
sp_sci (
webbpsf_ext.synphot_ext.Spectrum) – A synphot spectrum of science target (e.g., central star). Should already be normalized to the apparent flux.sp_ref (
webbpsf_ext.synphot_ext.Spectrumor None) – A synphot spectrum of reference target. Should already be normalized to the apparent flux.distance (float) – Distance in parsecs to the science target. This is used for flux normalization of the planets and disk.
wfe_ref_drift (float) – WFE drift in nm RMS between the science and reference targets. Expected values are between ~3-10 nm.
wfe_roll_drift (float) – WFE drift in nm RMS between science roll angles. Default=0.
wind_mode (str) – ‘FULL’, ‘STRIPE’, or ‘WINDOW’
xpix (int) – Size of the detector readout along the x-axis. The detector is assumed to be in window mode unless the user explicitly sets wind_mode=’FULL’.
ypix (int) – Size of the detector readout along the y-axis. The detector is assumed to be in window mode unless the user explicitly sets wind_mode=’FULL’.
disk_params (dict) –
Arguments describing disk model information for a given FITS file:
‘file’ : Path to model file or an HDUList.
‘pixscale’ : Pixel scale for model image (arcsec/pixel).
‘dist’ : Assumed model distance in parsecs.
‘wavelength’ : Wavelength of observation in microns.
‘units’ : String of assumed flux units (ie., MJy/arcsec^2 or muJy/pixel)
‘cen_star’ : True/False. Is a star already placed in the central pixel?
autogen_coeffs (bool) – Automatically generate base PSF coefficients. Equivalent to performing self.gen_psf_coeff(). gen_wfedrift_coeff, and gen_wfemask_coeff. Default: True.
use_ap_info (bool) – For subarray observations, the mask reference points are not actually in the center of the array. Set this to True to shift the sources to actual aperture reference location. Otherwise, default will place in center of array.
sgd_type (str or None) – Small grid dither pattern. Valid types are ‘9circle’, ‘5box’, ‘5diamond’, ‘3bar’, or ‘5bar’. If ‘auto’, then defaults are ‘5diamond’ for round masks, ‘5bar’ for bar masks, and ‘5diamond’ for direct imaging. If None, then no FSM pointings, but there will be a single slew.
fsm_std (float) – One-sigma accuracy per axis of fine steering mirror positions. This provides randomness to each position relative to the nominal central position. Ignored for central position. *Values should be in units of mas*
slew_std (float) – One-sigma accuracy per axis of the initial slew. This is applied to all positions and gives a baseline offset relative to the desired mask center. *Values should be in units of mas*
Methods
__init__(sp_sci, distance[, sp_ref, ...])Init function for obs_hci class
add_planet([name, model, atmo, mass, age, ...])Insert a planet into observation.
attenuate_with_mask(image_oversampled[, cmask])Image attenuation from coronagraph mask features
bg_zodi([zfact])Zodiacal background flux.
bg_zodi_image([zfact, frame])Zodiacal light image
calc_contrast([hdu_diff, roll_angle, nsig, ...])Create contrast curve.
calc_datacube(wavelengths[, progressbar, ...])Calculate a spectral datacube of PSFs
calc_datacube_fast(wavelengths[, ...])Calculate a spectral datacube of PSFs: Simplified, much MUCH faster version.
calc_psf([sp, return_oversample, ...])Compute a PSF
calc_psf_from_coeff([sp, return_oversample, ...])Create PSF image from polynomial coefficients
calc_psf_offset_from_center([use_coeff, ...])Calculate the offset necessary to shift PSF to array center
calc_psfs_grid([sp, wfe_drift, osamp, ...])PSF grid across an instrument FoV
calc_psfs_sgd(xoff_asec, yoff_asec[, use_coeff])Calculate small grid dither PSFs
Remove planet info
display()Display the currently configured optical system on screen
drift_opd(wfe_drift[, opd])A quick method to drift the pupil OPD.
gen_disk_hdulist([file, pixscale, dist, ...])Create a correctly scaled disk model image.
gen_disk_image([PA_offset, xyoff_asec, ...])Create image of just disk.
gen_disk_psfs([wfe_drift, force, use_coeff, ...])Save instances of NIRCam PSFs that are incrementally offset from coronagraph center to convolve with a disk image.
gen_mask_image([npix, pixelscale, ...])Return an image representation of the focal plane mask attenuation.
gen_mask_transmission_map(coord_vals, ...[, ...])Return mask transmission for a set of coordinates
gen_offset_psf(offset_r, offset_theta[, sp, ...])Create a PSF offset from center of mask
gen_planets_image([PA_offset, xyoff_asec, ...])Create image of just planets.
gen_pointing_offsets([sgd_type, slew_std, ...])Create a series of x and y position offsets for a SGD pattern.
gen_psf_coeff([bar_offset])Generate PSF coefficients
gen_psfs_over_fov([sptype, wfe_drift, ...])Create PSF grid over full field of view
gen_ref_det([verbose])Function to generate and update Reference Detector class.
gen_roll_image([PA1, PA2, ...])Make roll-subtracted image.
gen_save_name([wfe_drift])Generate save name for polynomial coefficient output file.
gen_slope_image([PA, xyoff_asec, ...])Create slope image of observation
gen_wfedrift_coeff([force, save])Fit WFE drift coefficients
gen_wfefield_coeff([force, save])Fit WFE field-dependent coefficients
gen_wfemask_coeff([large_grid, force, save])Fit WFE changes in mask position
get_bar_offset([narrow, filter, ignore_options])Obtain the value of the bar offset that would be passed through to PSF calculations for bar/wedge coronagraphic masks.
get_opd_file_full_path([opdfilename])Return full path to the named OPD file.
get_opd_info([opd, pupil, HDUL_to_OTELM])Parse out OPD information for a given OPD, which can be a file name, tuple (file,slice), HDUList, or OTE Linear Model.
get_optical_system([fft_oversample, ...])Return an OpticalSystem instance corresponding to the instrument as currently configured.
Get SIAF aperture based on instrument settings
get_subarray_name([apname])Get JWST NIRCam subarray name
get_wfe([kind, wavelength, plot])Extract and return one component plane of the optical model for this instrument
interpolate_was_opd(array, newdim)Interpolates an input 2D array to any given size.
load_wss_opd(filename[, output_path, ...])Load an OPD produced by the JWST WSS into this instrument instance, specified by filename
load_wss_opd_by_date([date, choice, ...])Load an OPD produced by the JWST WSS into this instrument instance, specified by filename.
planet_flux([fluxunit])Return planet fluxes
planet_spec(**kwargs)Exoplanet spectrum
plot_bandpass([ax, color, title, return_ax])Plot the instrument bandpass on a selected axis.
psf_grid([num_psfs, all_detectors, save, ...])Create a PSF library in the form of a grid of PSFs across the detector based on the specified instrument, filter, and detector.
ramp_optimize(sp[, sp_bright, is_extended, ...])Optimize ramp settings.
recenter_psf(psf[, sampling, shift_func, interp])Recenter PSF to array center
sat_limits([sp, bp_lim, units, well_frac, ...])Saturation limits.
saturation_levels([ngroup, do_ref, image, ...])Saturation levels
sensitivity([nsig, units, sp, verbose, do_ref])Sensitivity limits.
set_position_from_aperture_name(aperture_name)Set the simulated center point of the array based on a named SIAF aperture.
simulate_level1b(target_name, ra, dec, ...)Simulate DMS Level 1b data model
simulate_ramps([sp, im_slope, cframe, nint, ...])Simulate Ramp Data
star_flux([fluxunit, do_ref, sp])Stellar flux
update_detectors([verbose, do_ref])Update detector operation parameters
update_detectors_ref([verbose])An easy-to-identify shortcut to gen_ref_det, because I keep forgetting to run it to independently of update_detectors.
update_from_SIAF(apname[, image_mask, ...])Update detector properties based on SIAF aperture
update_psf_coeff([filter, pupil_mask, ...])Update properties and create new set of PSF coefficients
visualize_wfe_budget([slew_delta_time, ...])Display a visual WFE budget showing the various terms that sum into the overall WFE for a given instrument
Attributes
LONG_WAVELENGTH_MAXLONG_WAVELENGTH_MINUse Coronagraphic ND acquisition square?
SHORT_WAVELENGTH_MAXSHORT_WAVELENGTH_MINSIAF aperture name for detector pixel to sky coords transformations
Return bandpass throughput
Offset position along bar mask (arcsec).
channelInclude coronagraphic substrate material?
Dictionary housing detector info parameters and keywords.
Detector selected for simulated PSF
Detectors on which the simulated PSF could lie
The pixel position in (X, Y) on the detector, relative to the currently-selected SIAF aperture subarray.
disk_paramsFast readout direction in sci coords
Currently selected filter name (e.g. F200W).
List of available filter names for this instrument
fov_pixCurrently selected image plane mask, or None for direct imaging
Observation with coronagraphic mask (incl Lyot stop)?
is_darkis_grismIs a Lyot mask in the pupil wheel?
modulemultiaccumobjectExposure timings in dictionary
namendegNumber of wavelengths/PSFs to fit
A dictionary capable of storing other arbitrary options, for extensibility.
oversampleDetector pixel scale, in arcsec/pixel
Planet info (if any exists)
PSF parameters
Filename or fits.HDUList for JWST pupil mask.
Currently selected Lyot pupil mask, or None for direct imaging
Filename or fits.HDUList for JWST pupil OPD.
Perform quicker coeff calculation over limited bandwidth?
Coefficient save directory
Coefficient file name
SCA ID (481, 482, .
SIAF Aperture object
Give all possible SIAF aperture names
Slow readout direction in sci coords
telescopeIf fov_pix is even, then set use_fov_pix_plus1 to True.
Wavelength range to fit
Detector well level in units of electrons
WFE drift (nm) of ref obs relative to sci obs
WFE drift (nm) of Roll2 obs relative to Roll1 obs
Should calculations include the Science Instrument internal WFE?
List of available image_masks
List of available pupil_masks
- property ND_acq
Use Coronagraphic ND acquisition square?
- add_planet(name=None, model='SB12', atmo='hy3s', mass=10, age=100, entropy=10, xy=None, rtheta=None, runits='AU', Av=0, renorm_args=None, sptype=None, accr=False, mmdot=None, mdot=None, accr_rin=2, truncated=False, **kwargs)[source]
Insert a planet into observation.
Add exoplanet information that will be used to generate a point source image using a spectrum from Spiegel & Burrows (2012). Use self.delete_planets() to delete them.
Coordinate convention is for +N up and +E to left.
- Parameters:
model (str) – Exoplanet model to use (‘sb12’, ‘bex’, ‘cond’) or stellar spectrum model (‘bosz’, ‘ck04models’, ‘phoenix’).
atmo (str) – A string consisting of one of four atmosphere types: [‘hy1s’, ‘hy3s’, ‘cf1s’, ‘cf3s’]. Only relevant for SB12.
mass (int) – Number 1 to 15 Jupiter masses for SB12. BEX and COND spans much lower masses (sub-Saturn, depending on age).
age (float) – Age in millions of years (1-1000).
entropy (float) – Initial entropy (8.0-13.0) in increments of 0.25
sptype (str) – Instead of using a exoplanet spectrum, specify a stellar type.
renorm_args (tuple) – Renormalization arguments in case you want very specific luminosity in some bandpass. Includes (value, units, bandpass).
Av (float) – Extinction magnitude (assumes Rv=4.0) of the exoplanet due to being embedded in a disk.
xy (tuple, None) – (X,Y) position in sky coordinates of companion (N up, E left).
rtheta (tuple, None) – Radius and position angle relative to stellar position. Alternative to xy keyword.
runits (str) – What are the spatial units? Valid values are ‘AU’, ‘asec’, or ‘pix’.
accr (bool) – Include accretion? default: False
mmdot (float) – From Zhu et al. (2015), the Mjup^2/yr value. If set to None then calculated from age and mass.
mdot (float) – Or use mdot (Mjup/yr) instead of mmdot.
accr_rin (float) – Inner radius of accretion disk (units of RJup; default: 2)
truncated (bool) – Full disk or truncated (ie., MRI; default: False)?
- property aperturename
SIAF aperture name for detector pixel to sky coords transformations
- attenuate_with_mask(image_oversampled, cmask=None)
Image attenuation from coronagraph mask features
Multiply image data by coronagraphic mask. Excludes region already affected by observed occulting mask. Involves mainly ND Squares and opaque COM holder. Appropriately accounts for COM substrate wavelength-dep throughput.
WARNING: If self.ND_acq=True, then bandpass already includes ND throughput, so be careful not to double count.
- property bandpass
Return bandpass throughput
- property bar_offset
Offset position along bar mask (arcsec).
- bg_zodi(zfact=None, **kwargs)
Zodiacal background flux.
There are options to call jwst_backgrounds to obtain better predictions of the background. Specify keywords ra, dec, and thisday to use jwst_backgrounds.
Returned values are in units of e-/sec/pixel
- Parameters:
zfact (float) – Factor to scale Zodiacal spectrum (default 2.5)
- Keyword Arguments:
ra (float) – Right ascension in decimal degrees
dec (float) – Declination in decimal degrees
thisday (int) – Calendar day to use for background calculation. If not given, will use the average of visible calendar days.
Notes
Representative values for zfact:
0.0 - No zodiacal emission
1.0 - Minimum zodiacal emission from JWST-CALC-003894
1.2 - Required NIRCam performance
2.5 - Average (default)
5.0 - High
10.0 - Maximum
- bg_zodi_image(zfact=None, frame='sci', **kwargs)
Zodiacal light image
Returns an image of background Zodiacal light emission in e-/sec in specified coordinate frame.
- Parameters:
zfact (float) – Factor to scale Zodiacal spectrum (default 2.5)
frame (str) – Return in ‘sci’ or ‘det’ coordinates?
- Keyword Arguments:
ra (float) – Right ascension in decimal degrees
dec (float) – Declination in decimal degrees
thisday (int) – Calendar day to use for background calculation. If not given, will use the average of visible calendar days.
Notes
Representative values for zfact:
0.0 - No zodiacal emission
1.0 - Minimum zodiacal emission from JWST-CALC-003894
1.2 - Required NIRCam performance
2.5 - Average (default)
5.0 - High
10.0 - Maximum
- calc_contrast(hdu_diff=None, roll_angle=10, nsig=1, exclude_disk=True, exclude_planets=True, no_ref=False, wfe_drift0=0, wfe_ref_drift=None, wfe_roll_drift=None, func_std=<function std>, **kwargs)[source]
Create contrast curve.
Generate n-sigma contrast curve for the current observation settings. Make sure that MULTIACCUM parameters are set for both the main class (
self.update_detectors()) as well as the reference target class (self.update_detectors_ref()).- Parameters:
hdu_diff (HDUList) – Option to pass an already pre-made differenced image.
roll_angle (float) – Telescope roll angle (deg) between two observations. If set to 0 or None, then only one roll will be performed. If value is >0, then two rolls are performed, each using the specified MULTIACCUM settings (doubling the effective exposure time).
nsig (float) – n-sigma contrast curve.
exclude_disk (bool) – Ignore disk when generating image?
exclude_planets (bool) – Ignore planets when generating image?
no_ref (bool) – Exclude reference observation. Subtraction is then Roll1-Roll2.
func_std (func) – The function to use for calculating the radial standard deviation.
- Keyword Arguments:
zfact (float) – Zodiacal background factor (default=2.5)
psf_corr_over (ndarray) – PSF correction factor for oversampled PSF. Used to better match simulated PSFs to observed PSFs.
diffusion_sigma (float) – Apply pixel diffusion to PSF. Value is in units of detector pixels.
kipc (ndarray) – Kernel for IPC. If not provided, then IPC is not applied.
kppc (ndarray) – Kernel for PPC. If not provided, then PPC is not applied.
exclude_noise (bool) – Don’t add random Gaussian noise (detector+photon)?
ideal_Poisson (bool) – If set to True, use total signal for noise estimate, otherwise MULTIACCUM equation is used.
use_cmask (bool) – Include coronagraphic mask elements to attenuate background, disk, companions?
opt_diff (bool) – Optimal reference differencing (scaling only on the inner regions)
smooth (bool) – Smooth the result by convolving with a Gaussian that has stddev=1 Default: True.
small_numbers (bool) – Account for small number statistics? Default: True.
- Returns:
tuple – Three arrays in a tuple: the radius in arcsec, n-sigma contrast, and n-sigma magnitude sensitivity limit (vega mag).
- calc_datacube(wavelengths, progressbar=False, outfile=None, overwrite=True, *args, **kwargs)
Calculate a spectral datacube of PSFs
- Parameters:
wavelengths (iterable of floats) – List or ndarray or tuple of floating point wavelengths in meters, such as you would supply in a call to calc_psf via the “monochromatic” option
progressbar (bool) – Optionally display a progress bar indicator for status while iterating over wavelengths. Note, this requires the optional dependency package ‘tqdm’, which is not included as a requirement.
outfile (string) – Filename to write. If None, then result is returned as an HDUList
overwrite (bool) – overwrite output FITS file if it already exists?
Additional parameters are passed through to calc_datacube
- calc_datacube_fast(wavelengths, compare_methods=False, outfile=None, add_distortion=True, *args, **kwargs)
Calculate a spectral datacube of PSFs: Simplified, much MUCH faster version.
This is adapted from poppy.Instrument.calc_datacube, optimized and simplified for a substantial gain in speed at minimal reduction in accuracy for some use cases.
ASSUMPTIONS:
- Assumes the wavefront error (OPD) and amplitude are independent of wavelength, such
that we can do the expensive propagation from sky through the optics to the exit pupil of NIRSpec only once, save that, and reuse the same exit pupil wavefront many times changing only the wavelength for just the last DFT step to the detector.
- Assumes we do not need the binned-to-detector-resolution nor distorted versions;
we just want the oversampled PSF datacube at many wavelengths as fast as possible. (If the binned output is also desired, it can be computed post facto. TODO: A future revision of this function may also add here an option for computing those derived versions as well.)
Testing for NIRSpec IFU indicates this achieves ~150x speedup, and the differences in computed oversampled PSF are typically ~1/100th or less relative to the local PSF values in any given pixel.
A consequence of the above assumption 1 is that this method is not well applicable for cases that have image plane masks, nor for NIRCam in general. It does seem to be reasonably applicable for NIRSpec IFU calculations within the current limited fidelity of stpsf for that mode, IF we also neglect the image plane stop around the IFU FOV.
- Parameters:
wavelengths (iterable of floats) – List or ndarray or tuple of floating point wavelengths in meters, such as you would supply in a call to calc_psf via the “monochromatic” option
add_distortion (bool) – Same as for regular calc_psf.
compare_methods (bool) – If true, compute the PSF BOTH WAYS, and return both for comparisons. This is of course much slower. Default is False. This is retained for test and debug usage for assessing cases in which this method is OK or not.
- Returns:
a PSF datacube, normally (with compare_methods=False)
A list of two PSF datacubes and two exit wavefront objects, if compare_methods is True
- calc_psf(sp=None, return_oversample=True, return_hdul=True, wfe_drift=None, coord_vals=None, coord_frame='tel', use_bg_psf=False, **kwargs)
Compute a PSF
Slight modification of inherent STPSF calc_psf function. If add_distortion, fov_pixels, and oversample are not specified, then we automatically use the associated attributes. Also, add ability to directly specify wfe_drift and coordinate offset values in the same fashion as calc_psf_from_coeff.
Notes
Additional PSF computation options (pupil shifts, source positions, jitter, …) may be set by configuring the .options dictionary attribute of this class.
Calculations with bar masks: Calling with coord_vals=None will generate a PSF at the nominal mask position based on the filter or NARROW as called out from self.siaf_ap. If coord_vals is set to a tuple of (x,y) values, then the PSF will be generated at those locations relative to the center of the mask (or more specifically, center of self.aperturname).
- Parameters:
source (synphot.spectrum.SourceSpectrum or dict)
nlambda (int) – How many wavelengths to model for broadband? The default depends on how wide the filter is: (5,3,1) for types (W,M,N) respectively
monochromatic (float, optional) – Setting this to a wavelength value (in meters) will compute a monochromatic PSF at that wavelength, overriding filter and nlambda settings.
fov_arcsec (float) – field of view in arcsec. Default=5
fov_pixels (int) – field of view in pixels. This is an alternative to fov_arcsec.
outfile (string) – Filename to write. If None, then result is returned as an HDUList
oversample, detector_oversample, fft_oversample (int) – How much to oversample. Default=4. By default the same factor is used for final output pixels and intermediate optical planes, but you may optionally use different factors if so desired.
overwrite (bool) – overwrite output FITS file if it already exists?
display (bool) – Whether to display the PSF when done or not.
save_intermediates, return_intermediates (bool) – Options for saving to disk or returning to the calling function the intermediate optical planes during the propagation. This is useful if you want to e.g. examine the intensity in the Lyot plane for a coronagraphic propagation.
normalize (string) – Desired normalization for output PSFs. See doc string for OpticalSystem.calc_psf. Default is to normalize the entrance pupil to have integrated total intensity = 1.
add_distortion (bool) – If True, will add 2 new extensions to the PSF HDUlist object. The 2nd extension will be a distorted version of the over-sampled PSF and the 3rd extension will be a distorted version of the detector-sampled PSF.
crop_psf (bool) – If True, when the PSF is rotated to match the detector’s rotation in the focal plane, the PSF will be cropped so the shape of the distorted PSF will match it’s undistorted counterpart. This will only be used for NIRCam, NIRISS, and FGS PSFs.
- Keyword Arguments:
sp (
webbpsf_ext.synphot_ext.Spectrum) – Source input spectrum. If not specified, the default is flat in phot lam. (equal number of photons per spectral bin).coord_vals (tuple or None) – Coordinates (in arcsec or pixels) to calculate field-dependent PSF. If multiple values, then this should be an array ([xvals], [yvals]).
coord_frame (str) –
Type of input coordinates relative to self.siaf_ap aperture:
’tel’: arcsecs V2,V3
’sci’: pixels, in DMS axes orientation; aperture-dependent
’det’: pixels, in raw detector read out axes orientation
’idl’: arcsecs relative to aperture reference location.
return_hdul (bool) – Return PSFs in an HDUList rather than set of arrays. Default: True.
return_oversample (bool) – Returns the oversampled version of the PSF instead of detector-sampled PSF. Only valid for reaturn_hdul=False, otherwise full HDUList returned. Default: True.
- calc_psf_from_coeff(sp=None, return_oversample=True, return_hdul=True, wfe_drift=None, coord_vals=None, coord_frame='tel', use_bg_psf=False, **kwargs)
Create PSF image from polynomial coefficients
Create a PSF image from instrument settings. The image is noiseless and doesn’t take into account any non-linearity or saturation effects, but is convolved with the instrument throughput. Pixel values are in counts/sec. The result is effectively an idealized slope image (no background).
Returns a single image or list of images if sp is a list of spectra. By default, it returns only the oversampled PSF, but setting return_oversample=False will instead return detector-sampled images.
- Parameters:
sp (
webbpsf_ext.synphot_ext.Spectrum) – If not specified, the default is flat in phot lam (equal number of photons per spectral bin). The default is normalized to produce 1 count/sec within that bandpass, assuming the telescope collecting area and instrument bandpass. Coronagraphic PSFs will further decrease this due to the smaller pupil size and coronagraphic spot.return_oversample (bool) – Returns the oversampled version of the PSF instead of detector-sampled PSF. Default: True.
wfe_drift (float or None) – Wavefront error drift amplitude in nm.
coord_vals (tuple or None) – Coordinates (in arcsec or pixels) to calculate field-dependent PSF. If multiple values, then this should be an array ([xvals], [yvals]).
coord_frame (str) –
Type of input coordinates relative to self.siaf_ap aperture.
‘tel’: arcsecs V2,V3
‘sci’: pixels, in DMS axes orientation; aperture-dependent
‘det’: pixels, in raw detector read out axes orientation
‘idl’: arcsecs relative to aperture reference location.
return_hdul (bool) – Return PSFs in an HDUList rather than set of arrays (default: True).
coron_rescale (bool) – Rescale total flux of off-axis coronagraphic PSF to better match analytic prediction when source overlaps coronagraphic occulting mask. Primarily used for planetary companion and disk PSFs. Default: True.
- calc_psf_offset_from_center(use_coeff=True, halfwidth=None)
Calculate the offset necessary to shift PSF to array center
Returns values in detector-sampled pixels.
The array center is the middle of a pixel for odd images, and at pixel boundaries for even images.
- calc_psfs_grid(sp=None, wfe_drift=0, osamp=1, npsf_per_full_fov=15, xsci_vals=None, ysci_vals=None, return_coords=None, use_coeff=True, **kwargs)
PSF grid across an instrument FoV
Create a grid of PSFs across instrument aperture FoV. By default, imaging observations will be for full detector FoV with regularly spaced grid. Coronagraphic observations will cover nominal coronagraphic mask region (usually 10s of arcsec) and will have logarithmically spaced values where appropriate.
- Keyword Arguments:
sp (
webbpsf_ext.synphot_ext.Spectrum) – If not specified, the default is flat in phot lam (equal number of photons per wavelength bin). The default is normalized to produce 1 count/sec within that bandpass, assuming the telescope collecting area and instrument bandpass. Coronagraphic PSFs will further decrease this due to the smaller pupil size and suppression of coronagraphic mask. If set, then the resulting PSF image will be scaled to generate the total observed number of photons from the spectrum (ie., not scaled by unit response).wfe_drift (float) – Desired WFE drift value relative to default OPD.
osamp (int) – Sampling of output PSF relative to detector sampling.
npsf_per_full_fov (int) – Number of PSFs across one dimension of the instrument’s field of view. If a coronagraphic observation, then this is for the nominal coronagrahic field of view (20”x20”).
xsci_vals (None or ndarray) – Option to pass a custom grid values along x-axis in ‘sci’ coords.
ysci_vals (None or ndarray) – Option to pass a custom grid values along y-axis in ‘sci’ coords.
return_coords (None or str) – Option to also return coordinate values in desired frame (‘det’, ‘sci’, ‘tel’, ‘idl’). Output is then xvals, yvals, hdul_psfs.
use_coeff (bool) – If True, uses calc_psf_from_coeff, other STPSF’s built-in calc_psf.
coron_rescale (bool) – Rescale off-axis coronagraphic PSF to better match analytic prediction when source overlaps coronagraphic occulting mask. Only valid for use_coeff=True.
- calc_psfs_sgd(xoff_asec, yoff_asec, use_coeff=True, **kwargs)
Calculate small grid dither PSFs
Convenience function to calculation a series of SGD PSFs. This is essentially a wrapper around the calc_psf_from_coeff and calc_psf functions. Only valid for coronagraphic observations.
- Parameters:
xoff_asec (float or array-like) – Offsets in x-direction (in ‘idl’ coordinates).
yoff_asec (float or array-like) – Offsets in y-direction (in ‘idl’ coordinates).
use_coeff (bool) – If True, uses calc_psf_from_coeff, other STPSF’s built-in calc_psf.
- property coron_substrate
Include coronagraphic substrate material?
- property det_info
Dictionary housing detector info parameters and keywords.
- property detector
Detector selected for simulated PSF
Used in calculation of field-dependent aberrations. Must be selected from detectors in the detector_list attribute.
- property detector_list
Detectors on which the simulated PSF could lie
- property detector_position
The pixel position in (X, Y) on the detector, relative to the currently-selected SIAF aperture subarray. By default the SIAF aperture will correspond to the full-frame detector, so (X,Y) will in that case be absolute (X,Y) pixels on the detector. But if you select a subarray aperture name from the SIAF, then the (X,Y) are interpreted as (X,Y) within that subarray.
Please note, this is X,Y order - not a Pythonic y,x axes ordering.
- display()
Display the currently configured optical system on screen
- drift_opd(wfe_drift, opd=None)
A quick method to drift the pupil OPD. This function applies some WFE drift to input OPD file by breaking up the wfe_drift attribute into thermal, frill, and IEC components. If we want more realistic time evolution, then we should use the procedure in dev_utils/WebbPSF_OTE_LM.ipynb to create a time series of OPD maps, which can then be passed directly to create unique PSFs.
- This outputs an OTE Linear Model. In order to update instrument class:
>>> opd_dict = inst.drift_opd() >>> inst.pupilopd = opd_dict['opd'] >>> inst.pupil = opd_dict['opd']
- property fastaxis
Fast readout direction in sci coords
- property filter
Currently selected filter name (e.g. F200W)
- filter_list = None
List of available filter names for this instrument
- gen_disk_hdulist(file=None, pixscale=None, dist=None, wavelength=None, units=None, cen_star=None, shape_out=None, **kwargs)[source]
Create a correctly scaled disk model image.
Rescale disk model flux to current pixel scale and distance. If instrument bandpass is different from disk model, scales flux assuming a grey scattering model.
Result (in photons/sec) is saved in self.disk_hdulist attribute.
- gen_disk_image(PA_offset=0, xyoff_asec=(0, 0), use_cmask=True, return_oversample=False, diffusion_sigma=None, psf_corr_over=None, apply_distortions=None, xypix=None, shift_method=None, interp=None, use_ap_info=None, **kwargs)[source]
Create image of just disk.
Generate a (noiseless) convolved image of the disk at some PA offset. The PA offset value will rotate the image CCW. Image units of e-/sec.
Coordinate convention is for N up and E to left.
For now, we don’t perform any changes to the WFE.
- Parameters:
PA_offset (float) – Rotate entire scene by some position angle. Positive values are counter-clockwise from +Y direction. This should be -1 times telescope V3 PA.
xyoff_asec (tuple) – Offsets (dx,dy) specified in arcsec. These are meant to be for minor shifts, use as SGD. Bar offsets are accounted for automatically.
use_cmask (bool) – Use the coronagraphic mask image to attenuate disk regions getting obscurred by a corongraphic mask feature
return_oversample (bool) – Return either the detector pixel-sampled or oversampled image.
diffusion_sigma (float) – Apply pixel diffusion to the PSF convolved with disk image. Value is in units of detector pixels.
psf_corr_over (ndarray) – Oversampled PSF correction factor to apply to disk PSF to better match empirical data.
- gen_disk_psfs(wfe_drift=0, force=False, use_coeff=True, recenter=True, diffusion_sigma=None, psf_corr_over=None, **kwargs)[source]
Save instances of NIRCam PSFs that are incrementally offset from coronagraph center to convolve with a disk image.
- gen_mask_image(npix=None, pixelscale=None, bar_offset=None, nd_squares=True)
Return an image representation of the focal plane mask attenuation. Output is in ‘sci’ coords orientation. If no image mask is present, then returns an array of all 1s. Mask is centered in image, while actual subarray readout has a slight offset.
- Parameters:
npix (int) – Number of pixels in output image. If not set, then is automatically determined based on mask FoV and pixelscale
pixelscale (float) – Size of output pixels in units of arcsec. If not specified, then selects oversample pixel scale.
- gen_mask_transmission_map(coord_vals, coord_frame, siaf_ap=None, return_more=False)
Return mask transmission for a set of coordinates
Similar to self.gen_mask_image, but instead of returning a full image, can query the transmission at a set of coordinates. This is useful for calculating the transmission at the location of a source or for plotting the transmission across the mask. Returns the intensity transmission (ie., photon loss), wich is the amplitude transmission squared (as supplied by the STPSF BandLimitedCoron class and nrc_mask_trans function).
- Parameters:
coord_vals (tuple or None) – Coordinates (in arcsec or pixels) to calculate field-dependent PSF. If multiple values, then this should be an array ([xvals], [yvals]).
coord_frame (str) –
Type of input coordinates relative to self.siaf_ap aperture.
‘tel’: arcsecs V2,V3
‘sci’: pixels, in DMS axes orientation; aperture-dependent
‘det’: pixels, in raw detector read out axes orientation
‘idl’: arcsecs relative to aperture reference location.
siaf_ap (pysiaf.SiafAperture) – SIAF aperture object. If not specified, then uses self.siaf_ap.
return_more (bool) – If True, then return additional information about the mask transmission, specifically the x and y coordinates relative to the center of the mask in arcsec.
- gen_offset_psf(offset_r, offset_theta, sp=None, return_oversample=False, wfe_drift=None, use_coeff=True, coron_rescale=True, use_cmask=False, recenter=True, diffusion_sigma=None, psf_corr_over=None, **kwargs)
Create a PSF offset from center of mask
NOTE: The resulting PSF is still in the center of the output image, but the PSF morphology matches that of the off-axis location.
Generate some off-axis PSF at a given (r,theta) offset from center of mask. The offset_r and offset_theta parameters are assumed to be in ‘idl’ frame. This function is mainly for coronagraphic observations where the off-axis PSF varies w.r.t. position. The PSF is centered in the resulting image. The offset values are assumed to be in ‘idl’ coordinate frame relative to the mask center.
WARNING: Bar offsets are added in calc_psf functions, so don’t double count.
- Parameters:
offset_r (float) – Radial offset of the target from center in arcsec.
offset_theta (float) – Position angle for that offset, in degrees CCW (+Y).
- Keyword Arguments:
sp (None,
webbpsf_ext.synphot_ext.Spectrum) – If not specified, the default is flat in phot lam (equal number of photons per spectral bin).return_oversample (bool) – Return either the pixel-sampled or oversampled PSF.
use_coeff (bool) – If True, uses calc_psf_from_coeff, other STPSF’s built-in calc_psf.
coron_rescale (bool) – Rescale total flux of off-axis coronagraphic PSF to better match analytic prediction when source overlaps coronagraphic occulting mask. Primarily used for planetary companion and disk PSFs. Default: True.
recenter (bool) – Recenter the PSF to the center of the image where offsets are caused by small (sub-pixel) tip/tilt values or dispersion from Lyot wedges. Default: True.
diffusion_sigma (float) – Apply pixel diffusion to the disk image. This is a Gaussian convolution with a sigma value in pixels.
psf_corr_over (ndarray) – Oversampled PSF correction factor. If not None, then apply this correction factor to the oversampled PSF. The correction factor should be the same size as the oversampled PSF.
- gen_planets_image(PA_offset=0, xyoff_asec=(0, 0), use_cmask=True, sp=None, wfe_drift=None, use_coeff=True, return_oversample=False, shift_method=None, interp=None, quiet=True, use_ap_info=None, **kwargs)[source]
Create image of just planets.
Use info stored in self.planets to create a noiseless slope image of just the exoplanets (no star).
Coordinate convention is for +N up and +E to left.
- Parameters:
PA_offset (float) – Rotate entire scene by some position angle. Positive values are counter-clockwise from +Y direction. This should be -1 times telescope V3 PA.
xyoff_asec (tuple) – Offsets (dx,dy) specified in arcsec. These are meant to be for minor shifts, such as SGD. Bar offsets are accounted for automatically.
use_cmask (bool) – Use the coronagraphic mask image to determine if any planet is getting obscurred by a corongraphic mask feature. Default: True.
sp (
webbpsf_ext.synphot_ext.Spectrum) – Specify the spectrum of the planet to be used. If None, then uses info stored in self.planets.wfe_drift (float) – WFE drift value (in nm RMS). Not usually a concern for companion PSFs, so default is 0.
use_coeff (bool) – If True, uses calc_psf_from_coeff, otherwise use STPSF’s built-in calc_psf for stellar sources.
return_oversample (bool) – Return either the detector pixel-sampled or oversampled image.
shift_method (str) – Function to use for shifting image. Options are: - ‘fourier’ : Shift in Fourier space - ‘fshift’ : Shift using interpolation - ‘opencv’ : Shift using OpenCV warpAffine
interp (str) – Interpolation method to use for shifting using ‘fshift’ or ‘opencv. Default is ‘cubic’. For ‘opencv’, valid options are ‘linear’, ‘cubic’, and ‘lanczos’. for ‘fshift’, valid options are ‘linear’, ‘cubic’, and ‘quintic’.
- Keyword Arguments:
coron_rescale (bool) – Rescale total flux of off-axis coronagraphic PSF to better match analytic prediction when source overlaps coronagraphic occulting mask. Primarily used for planetary companion and disk PSFs. Default: True.
diffusion_sigma (float) – Apply pixel diffusion to PSFs. This is the standard deviation of the Gaussian kernel used for diffusion in terms of detector pixels. Default: None.
psf_corr_over (ndarray) – Oversampled PSF correction factor. This is used to better match STPSF PSFs to observed PSFs. Default: None.
- gen_pointing_offsets(sgd_type=None, slew_std=None, fsm_std=None, rand_seed=None, verbose=False)[source]
Create a series of x and y position offsets for a SGD pattern. This includes the central position as the first in the series. By default, will also add random position errors using the slew_std and fsm_std keywords. Returned values are in arcsec.
This initializes a set of target acquisition offsets for each roll position and reference observation.
- Parameters:
sgd_type (str or None) – Small grid dither pattern. Valid types are ‘9circle’, ‘5box’, ‘5diamond’, ‘3bar’, ‘5bar’, ‘5miri’, and ‘9miri’ where the first four refer to NIRCam coronagraphic dither positions and the last two are for MIRI coronagraphy. If ‘auto’, then defaults are ‘5diamond’ for round masks, ‘5bar’ for bar masks, and ‘5diamond’ for direct imaging. If None, then no FSM pointings, but there will be a single slew.
fsm_std (float) – One-sigma accuracy per axis of fine steering mirror positions. This provides randomness to each position relative to the nominal central position. Ignored for central position. Values should be in units of mas.
slew_std (float) – One-sigma accuracy per axis of the initial slew. This is applied to all positions and gives a baseline offset relative to the desired mask center. Values should be in units of mas.
- gen_psf_coeff(bar_offset=0, **kwargs)
Generate PSF coefficients
Creates a set of coefficients that will generate simulated PSFs for any arbitrary wavelength. This function first simulates a number of evenly- spaced PSFs throughout the specified bandpass (or the full channel). An nth-degree polynomial is then fit to each oversampled pixel using a linear-least squares fitting routine. The final set of coefficients for each pixel is returned as an image cube. The returned set of coefficient are then used to produce PSF via calc_psf_from_coeff.
Useful for quickly generated imaging and dispersed PSFs for multiple spectral types.
- Parameters:
bar_offset (float) – For wedge masks, option to set the PSF position across the bar. In this framework, we generally set the default to 0, then use the gen_wfemask_coeff function to determine how the PSF changes along the wedge axis as well as perpendicular to the wedge. This allows for more arbitrary PSFs within the mask, including small grid dithers as well as variable PSFs for extended objects. Default: 0.
- Keyword Arguments:
wfe_drift (float) – Wavefront error drift amplitude in nm.
force (bool) – Forces a recalculation of PSF even if saved PSF exists. (default: False)
save (bool) – Save the resulting PSF coefficients to a file? (default: True)
nproc (bool or None) – Manual setting of number of processor cores to break up PSF calculation. If set to None, this is determined based on the requested PSF size, number of available memory, and hardware processor cores. The automatic calculation endeavors to leave a number of resources available to the user so as to not crash the user’s machine.
return_results (bool) – By default, results are saved as object the attributes psf_coeff and psf_coeff_header. If return_results=True, results are instead returned as function outputs and will not be saved to the attributes. This is mostly used for successive coeff simulations to determine varying WFE drift or focal plane dependencies.
return_extras (bool) – Additionally returns a dictionary of monochromatic PSFs images and their corresponding wavelengths for debugging purposes. Can be used with or without return_results. If return_results=False, then only this dictionary is returned, otherwise if return_results=True then returns everything as a 3-element tuple (psf_coeff, psf_coeff_header, extras_dict).
- gen_psfs_over_fov(sptype='G0V', wfe_drift=0, osamp=1, npsf_per_full_fov=15, return_coords=None, use_coeff=True, **kwargs)
Create PSF grid over full field of view
Wrapper around calc_psfs_grid that returns normalized PSFs across the field of view.
Create a grid of PSFs across instrument aperture FoV. By default, imaging observations will be for full detector FoV with regularly spaced grid. Coronagraphic observations will cover nominal coronagraphic mask region (usually 10s of arcsec) and will have logarithmically spaced values where appropriate.
- Parameters:
sptype (str) – Spectral type, such as ‘A0V’ or ‘K2III’.
wfe_drift (float) – Desired WFE drift value relative to default OPD.
osamp (int) – Sampling of output PSF relative to detector sampling.
npsf_per_full_fov (int) – Number of PSFs across one dimension of the instrument’s field of view. If a coronagraphic observation, then this is for the nominal coronagrahic field of view.
return_coords (None or str) – Option to also return coordinate values in desired frame (‘det’, ‘sci’, ‘tel’, ‘idl’). Output is then xvals, yvals, hdul_psfs.
use_coeff (bool) – If True, uses calc_psf_from_coeff, other STPSF’s built-in calc_psf.
- Keyword Arguments:
xsci_vals (None or ndarray) – Option to pass a custom grid values along x-axis in ‘sci’ coords. If coronagraph, this instead corresponds to coronagraphic mask axis, which has a slight rotation in MIRI.
ysci_vals (None or ndarray) – Option to pass a custom grid values along y-axis in ‘sci’ coords. If coronagraph, this instead corresponds to coronagraphic mask axis, which has a slight rotation in MIRI.
- gen_ref_det(verbose=False, **kwargs)[source]
Function to generate and update Reference Detector class. Used to keep track of detector and multiaccum config, which can differ between sci and ref observations.
- gen_roll_image(PA1=-5, PA2=5, return_oversample=False, no_ref=False, opt_diff=False, ref_scale_all=False, wfe_drift0=0, wfe_ref_drift=None, wfe_roll_drift=None, xyoff_roll1=None, xyoff_roll2=None, xyoff_ref=None, interp=None, do_sat=False, sat_val=0.95, use_ap_info=None, **kwargs)[source]
Make roll-subtracted image.
Create a final roll-subtracted slope image based on current observation settings. Coordinate convention is for N up and E to left.
Procedure:
Create Roll 1 and Roll 2 slope images (star+exoplanets+disk)
Create Reference Star slope image
Add noise to all images
Scale ref image
Subtract ref image from both rolls
De-rotate Roll 1 and Roll 2 to common coordinates
Average Roll 1 and Roll 2
Returns an HDUList of final image (N rotated upwards).
- Parameters:
PA1 (float) – Position angle of first telescope roll position. This is counter-clockwise (West to East).
PA2 (float, None) – Position angle of second roll position. If set equal to PA1 (or to None), then only one roll will be performed. Otherwise, two rolls are performed, each using the specified MULTIACCUM settings (doubling the effective exposure time).
no_ref (bool) – Exclude reference observation. Subtraction is then Roll1-Roll2.
opt_diff (bool) – Optimal reference differencing (scaling only on the inner regions)
ref_scale_all (bool) – Normally we just use the science and reference PSFs to calculate scaling. However, if there is an unresolved companion or disk emission close to the star, then we won’t get the correct scale factor for optimal reference subtraction. Instead, this option inludes disk and companions for calculating the reference scale factor.
wfe_drift0 (float) – Initial RMS WFE drift value of First PSF. Roll2 and Ref observations will be incremented from this. Default is 0.
wfe_ref_drift (float) – WFE drift between sci and ref observations (nm RMS).
wfe_roll_drift (float) – WFE drift between Roll1 and Roll2 observations (nm RMS).
return_oversample (bool) – Return either the detector pixel-sampled or oversampled image.
xyoff_roll1 (tuple or None) – Explicitly set pointing offset for Roll 1 (arcsec)
xyoff_roll2 (tuple or None) – Explicitly set pointing offset for Roll 2 (arcsec)
xyoff_ref (tuple or None) – Explicitly set pointing offset for Reference (arcsec)
do_sat (bool) – Determine saturated regions and NaN them.
sat_val (float) – Fraction of full well to consider as saturated within two groups.
- Keyword Arguments:
exclude_disk (bool) – Do not include disk in final image (for radial contrast), but still add Poisson noise from disk.
exclude_planets (bool) – Do not include planets in final image (for radial contrast), but still add Poisson noise from disk.
exclude_noise (bool) – Don’t add random Gaussian noise (detector+photon)
use_coeff (bool) – If True, uses calc_psf_from_coeff, other STPSF’s built-in calc_psf for stellar sources.
psf_corr_over (ndarray) – PSF correction factor for oversampled PSF. Used to better match simulated PSFs to observed PSFs.
diffusion_sigma (float) – Apply pixel diffusion to PSF. Value is in units of detector pixels.
kipc (ndarray) – Kernel for IPC. If not provided, then IPC is not applied.
kppc (ndarray) – Kernel for PPC. If not provided, then PPC is not applied.
ideal_Poisson (bool) – If set to True, use total signal for noise estimate, otherwise MULTIACCUM equation is used.
use_cmask (bool) – Use the coronagraphic mask image to attenuate planets or disk obscurred by a corongraphic mask feature. Default is True.
zfact (float) – Zodiacal background factor (default=2.5)
ra (float) – Right ascension in decimal degrees
dec (float) – Declination in decimal degrees
thisday (int) – Calendar day to use for background calculation. If not given, will use the average of visible calendar days.
shift_func (func) – Function to use for shifting image. Typical options are fshift and fourier_imshift.
interp (str) – Interpolation used for fshift, either ‘linear’ or ‘cubic’.
- gen_save_name(wfe_drift=0)
Generate save name for polynomial coefficient output file.
- gen_slope_image(PA=0, xyoff_asec=(0, 0), return_oversample=False, exclude_disk=False, exclude_planets=False, exclude_noise=False, zfact=None, do_ref=False, do_roll2=False, im_star=None, sat_val=0.9, wfe_drift0=0, wfe_ref_drift=None, wfe_roll_drift=None, shift_method=None, interp=None, apply_distortions=None, diffusion_sigma=None, kipc=None, kppc=None, psf_corr_over=None, use_ap_info=None, **kwargs)[source]
Create slope image of observation
Beware that stellar position (centered on a pixel) will likely not fall in the exact center of the slope image (between pixel borders) because images are generally even while psf_fovs may be odd.
- Parameters:
PA (float) – Position angle of roll position (counter-clockwise, from West to East). Scene will rotate in opposite direction. This should be similar to V3 PA.
xyoff_asec (None or tuple) – Positional offset of scene from reference location in ‘idl’ coords. Shift occurs after PA rotation. Default is (0,0), but set to None to get the default dither position from self.pointing_info.
do_ref (bool) – Slope image for reference star observation using self.wfe_ref_drift.
do_roll2 (bool) – Slope image for observation during Roll2 using self.wfe_roll_drift. Will compound with do_ref if both are set.
exclude_disk (bool) – Do not include disk in final image (for radial contrast), but still add Poisson noise from disk.
exclude_planets (bool) – Do not include planets in final image (for radial contrast), but still add Poisson noise from disk.
exclude_noise (bool) – Don’t add random Gaussian noise (detector+photon)
zfact (float) – Zodiacal background factor (default=2.5)
im_star (ndarray or None) – Pass a precomputed slope image of the stellar source already positioned at it’s correct location.
sat_val (float) – Fraction of full well to consider as saturated. Used to determine number of unsaturated groups for linear fit, which feeds into estimated effective noise equation. For pixels that saturatea in a single group, the noise is assumed to be that for a single frame. Final image does not flag saturated pixels!
wfe_drift0 (float) – Initial RMS WFE drift value of First PSF. Roll2 and Ref observations will be incremented from this. Default is 0.
wfe_ref_drift (float) – WFE drift between sci and ref observations (nm RMS).
wfe_roll_drift (float) – WFE drift between Roll1 and Roll2 observations (nm RMS).
return_oversample (bool) – Return either the detector pixel-sampled or oversampled image.
shift_method (str) – Function to use for shifting image. Options are: - ‘fourier’ : Shift in Fourier space - ‘fshift’ : Shift using interpolation - ‘opencv’ : Shift using OpenCV warpAffine
interp (str) – Interpolation method to use for shifting using ‘fshift’ or ‘opencv. Default is ‘cubic’. For ‘opencv’, valid options are ‘linear’, ‘cubic’, and ‘lanczos’. for ‘fshift’, valid options are ‘linear’, ‘cubic’, and ‘quintic’.
- Keyword Arguments:
use_cmask (bool) – Use the coronagraphic mask image to attenuate planet or disk that is obscurred by a corongraphic mask feature. (Default=True)
ra (float) – Right ascension in decimal degrees
dec (float) – Declination in decimal degrees
thisday (int) – Calendar day to use for background calculation. If not given, will use the average of visible calendar days.
ideal_Poisson (bool) – If set to True, use total signal for noise estimate, otherwise MULTIACCUM equation is used.
use_coeff (bool) – If True, uses calc_psf_from_coeff, other STPSF’s built-in calc_psf for stellar sources.
- gen_wfedrift_coeff(force=False, save=True, **kwargs)
Fit WFE drift coefficients
This function finds a relationship between PSF coefficients in the presence of WFE drift. For a series of WFE drift values, we generate corresponding PSF coefficients and fit a polynomial relationship to the residual values. This allows us to quickly modify a nominal set of PSF image coefficients to generate a new PSF where the WFE has drifted by some amplitude.
It’s Legendre’s all the way down…
- Parameters:
force (bool) – Forces a recalculation of coefficients even if saved file exists. (default: False)
save (bool) – Save the resulting PSF coefficients to a file? (default: True)
- Keyword Arguments:
wfe_list (array-like) – A list of wavefront error drift values (nm) to calculate and fit. Default is [0,1,2,5,10,20,40], which covers the most-likely scenarios (1-5nm) while also covering a range of extreme drift values (10-40nm).
return_results (bool) – By default, results are saved in self._psf_coeff_mod dictionary. If return_results=True, results are instead returned as function outputs and will not be saved to the dictionary attributes.
return_raw (bool) – Normally, we return the relation between PSF coefficients as a function of position. Instead this returns (as function outputs) the raw values prior to fitting. Final results will not be saved to the dictionary attributes.
- gen_wfefield_coeff(force=False, save=True, **kwargs)
Fit WFE field-dependent coefficients
Find a relationship between field position and PSF coefficients for non-coronagraphic observations and when include_si_wfe is enabled.
- Parameters:
force (bool) – Forces a recalculation of coefficients even if saved file exists. (default: False)
save (bool) – Save the resulting PSF coefficients to a file? (default: True)
- Keyword Arguments:
return_results (bool) – By default, results are saved in self._psf_coeff_mod dictionary. If return_results=True, results are instead returned as function outputs and will not be saved to the dictionary attributes.
return_raw (bool) – Normally, we return the relation between PSF coefficients as a function of position. Instead this returns (as function outputs) the raw values prior to fitting. Final results will not be saved to the dictionary attributes.
- gen_wfemask_coeff(large_grid=True, force=False, save=True, **kwargs)
Fit WFE changes in mask position
For coronagraphic masks, slight changes in the PSF location relative to the image plane mask can substantially alter the PSF speckle pattern. This function generates a number of PSF coefficients at a variety of positions, then fits polynomials to the residuals to track how the PSF changes across the mask’s field of view. Special care is taken near the 10-20mas region in order to provide accurate sampling of the SGD offsets.
- Parameters:
large_grid (bool) – Use a large number (high-density) of grid points to create coefficients. If True, then a higher fidelity PSF variations across the FoV, but could take hours to generate on the first pass. Setting to False allows for quicker coefficient creation with a smaller memory footprint, useful for testing and debugging.
force (bool) – Forces a recalculation of coefficients even if saved file exists. (default: False)
save (bool) – Save the resulting PSF coefficients to a file? (default: True)
- Keyword Arguments:
return_results (bool) – By default, results are saved in self._psf_coeff_mod dictionary. If return_results=True, results are instead returned as function outputs and will not be saved to the dictionary attributes.
return_raw (bool) – Normally, we return the relation between PSF coefficients as a function of position. Instead this returns (as function outputs) the raw values prior to fitting. Final results will not be saved to the dictionary attributes.
- get_bar_offset(narrow=None, filter=None, ignore_options=False)
Obtain the value of the bar offset that would be passed through to PSF calculations for bar/wedge coronagraphic masks. By default, this uses the filter information. Secondary is the aperture name (e.g., _F250M or _NARROW). If the bar offset is explicitly set in self.options[‘bar_offset’], then that value is returned unless ignore_options=True.
- Parameters:
narrow (bool or None) – If True, then use the narrow bar offset position. If False, then use the filter-dependent bar offset position. If None, then try to determine based on apeture name. Default: None
filter (str or None) – If not None, then use this filter to determine the bar offset position. The narrow keyword or aperture name in self.siaf_ap takes priority.
ignore_options (bool) – If True, then ignore any values in self.options[‘bar_offset’]. Otherwise, if ‘bar_offset’ is not None, it returns already that configured value in self.options.
- get_opd_file_full_path(opdfilename=None)
Return full path to the named OPD file.
- The OPD may be:
a local or absolute path,
or relative implicitly within an SI directory, e.g. $STPSF_PATH/NIRCam/OPD
or relative implicitly within $STPSF_PATH
This function handles filling in the implicit path in the latter cases.
- get_opd_info(opd=None, pupil=None, HDUL_to_OTELM=True)
Parse out OPD information for a given OPD, which can be a file name, tuple (file,slice), HDUList, or OTE Linear Model. Returns dictionary of some relevant information for logging purposes. The dictionary returns the OPD as an OTE LM by default.
- This outputs an OTE Linear Model. In order to update instrument class:
>>> opd_dict = inst.get_opd_info() >>> opd_new = opd_dict['pupilopd'] >>> inst.pupilopd = opd_new >>> inst.pupil = opd_new
- get_optical_system(fft_oversample=2, detector_oversample=None, fov_arcsec=2, fov_pixels=None, options=None)
Return an OpticalSystem instance corresponding to the instrument as currently configured.
When creating such an OpticalSystem, you must specify the parameters needed to define the desired sampling, specifically the oversampling and field of view.
- Parameters:
fft_oversample (int) – Oversampling factor for intermediate plane calculations. Default is 2
detector_oversample (int, optional) – By default the detector oversampling is equal to the intermediate calculation oversampling. If you wish to use a different value for the detector, set this parameter. Note that if you just want images at detector pixel resolution you will achieve higher fidelity by still using some oversampling (i.e. not setting oversample_detector=1) and instead rebinning down the oversampled data.
fov_pixels (float) – Field of view in pixels. Overrides fov_arcsec if both set.
fov_arcsec (float) – Field of view, in arcseconds. Default is 2
- Returns:
osys (poppy.OpticalSystem) – an optical system instance representing the desired configuration.
- get_siaf_apname()
Get SIAF aperture based on instrument settings
- get_subarray_name(apname=None)
Get JWST NIRCam subarray name
- get_wfe(kind='si', wavelength=2e-06, plot=False)
Extract and return one component plane of the optical model for this instrument
This is a utility function for convenience, making it easier to access and plot various OPD maps. It doesn’t do anything unique which can’t be done otherwise, and in particular this isn’t used at all as part of the optical propagation calculations.
Note, all WFE terms are returned in OTE entrance pupil orientation (i.e. as if you were in front of the OTE and looking at it), regardless of pupil flips and orientations in the optical propagation.
- Parameters:
kind (string) – A type of WFE. Must be one of “SI”, “OTE”, “OTE_field_dep”, or other values TBD. Case insensitive.
plot (bool) – Make a quick plot of this WFE. Not very flexible or scriptable but useful for some interactive checks
- property image_mask
Currently selected image plane mask, or None for direct imaging
- image_mask_list
List of available image_masks
- include_ote_field_dependence
Should calculations include the Science Instrument internal WFE?
- interpolate_was_opd(array, newdim)
Interpolates an input 2D array to any given size.
- Parameters:
array (float) – input array to interpolate
newdim (int) – new size of the 2D square array (newdim x newdim)
- Returns:
newopd (new array interpolated to (newdim x newdim))
- property is_coron
Observation with coronagraphic mask (incl Lyot stop)?
- property is_lyot
Is a Lyot mask in the pupil wheel?
- load_wss_opd(filename, output_path=None, backout_si_wfe=True, verbose=True, plot=False, save_ote_wfe=False)
Load an OPD produced by the JWST WSS into this instrument instance, specified by filename
- This includes:
If necessary, downloading that OPD from MAST. Downloaded files are cached in $STPSF_PATH/MAST_JWST_WSS_OPDs
calling import_wss_opd to load the OPD from the FITS file and perform some necessary format conversions
- Subtract off the instrument WFE for the field point used in wavefront sensing, to get an
OTE-only wavefront. STPSF will separately add back in the SI WFE for the appropriate field point, as usual.
- Subtract off the modeled field dependence term in the OTE WFE for the sensing field point, to get
an estimate of the OTE wavefront nominally at the master chief ray location (between the NIRCams). STPSF will automatically add back on top of this the OTE field dependent WFE for the appropriate field point. as usual.
Scale the OPD to match the same size of the user provide pupil file
- Parameters:
filename (str) – Name of OPD file to load
output_path (str) – Downloaded OPD are saved in this location. This option is convinient for STScI users using /grp/stpsf/stpsf-data/. Default is $STPSF_PATH/MAST_JWST_WSS_OPDs
backout_si_wfe (bool) – Subtract model for science instrument WFE at the sensing field point? Generally this should be true which is the default.
plot (bool) – Generate informative plots showing WFE, including the backout steps. Only works if backout_si_wfe is True.
save_ote_wfe (bool) – Save OTE-only WFE model? This is not needed for calculations in STPSF, but can be used to export OTE WFE models for use with other software. The file will be saved in the STPSF_DATA_PATH directory and a message will be printed on screen with the filename. Note that the exported OPD file will give the OTE estimated total WFE at the selected Instrument’s field point, not the OTE global at master chief ray, since it is the OTE WFE at the selected field point which is most of use for some other tool.
- load_wss_opd_by_date(date=None, choice='closest', verbose=True, plot=False, **kwargs)
Load an OPD produced by the JWST WSS into this instrument instance, specified by filename.
This does a MAST query by date to identify the relevant OPD file, then calls load_wss_opd.
- Parameters:
date (string) – Date time in UTC as ISO-format string, a la 2021-12-25T07:20:00 Note, if date is left unspecified as None, the most recent available measurement will be retrieved.
choice (string) – Method to choose which OPD file to use, e.g. ‘before’, ‘after’
Further keyword parameters may be passed via **kwargs to load_wss_opd
- property multiaccum
multiaccumobject
- property multiaccum_times
Exposure timings in dictionary
t_frame : Time of a single frame. t_group : Time of a single group (read frames + drop frames). t_int : Photon collection time for a single ramp/integration. t_int_tot1: Total time for all frames (reset+read+drop) in a first ramp. t_int_tot2: Total time for all frames (reset+read+drop) in a subsequent ramp. t_exp : Total photon collection time for all ramps. t_acq : Total acquisition time to complete exposure with all overheads.
- property npsf
Number of wavelengths/PSFs to fit
- options = {}
A dictionary capable of storing other arbitrary options, for extensibility. The following are all optional, and may or may not be meaningful depending on which instrument is selected.
This is a superset of the options provided in
poppy.Instrument.options.- Parameters:
source_offset_r (float) – Radial offset of the target from the center, in arcseconds
source_offset_theta (float) – Position angle for that offset, in degrees CCW.
pupil_shift_x, pupil_shift_y (float) – Relative shift of the intermediate (coronagraphic) pupil in X and Y relative to the telescope entrance pupil, expressed as a decimal between -1.0-1.0 Note that shifting an array too much will wrap around to the other side unphysically, but for reasonable values of shift this is a non-issue. This option only has an effect for optical models that have something at an intermediate pupil plane between the telescope aperture and the detector.
pupil_rotation (float) – Relative rotation of the intermediate (coronagraphic) pupil relative to the telescope entrance pupil, expressed in degrees counterclockwise. This option only has an effect for optical models that have something at an intermediate pupil plane between the telescope aperture and the detector.
rebin (bool) – For output files, write an additional FITS extension including a version of the output array rebinned down to the actual detector pixel scale?
jitter (string “gaussian” or None) – Type of jitter model to apply. Currently only convolution with a Gaussian kernel of specified width jitter_sigma is implemented. (default: None)
jitter_sigma (float) – Width of the jitter kernel in arcseconds (default: 0.006 arcsec, 1 sigma per axis)
parity (string “even” or “odd”) – You may wish to ensure that the output PSF grid has either an odd or even number of pixels. Setting this option will force that to be the case by increasing npix by one if necessary. Note that this applies to the number detector pixels, rather than the subsampled pixels if oversample > 1.
force_coron (bool) – Set this to force full coronagraphic optical propagation when it might not otherwise take place (e.g. calculate the non-coronagraphic images via explicit propagation to all optical surfaces, FFTing to intermediate pupil and image planes whether or not they contain any actual optics, rather than taking the straight-to-MFT shortcut)
no_sam (bool) – Set this to prevent the SemiAnalyticMethod coronagraph mode from being used when possible, and instead do the brute-force FFT calculations. This is usually not what you want to do, but is available for comparison tests. The SAM code will in general be much faster than the FFT method, particularly for high oversampling.
- pixelscale = 0.025
Detector pixel scale, in arcsec/pixel
- planet_spec(**kwargs)[source]
Exoplanet spectrum
Return the planet spectrum from Spiegel & Burrows (2012) normalized to distance of current target. Output is a
webbpsf_ext.synphot_ext.Spectrum.See spectra.companion_spec() function for more details.
- property planets
Planet info (if any exists)
- plot_bandpass(ax=None, color=None, title=None, return_ax=False, **kwargs)
Plot the instrument bandpass on a selected axis. Can pass various keywords to
matplotlib.plotfunction.- Parameters:
ax (matplotlib.axes, optional) – Axes on which to plot bandpass.
color – Color of bandpass curve.
title (str) – Update plot title.
- Returns:
matplotlib.axes – Updated axes
- psf_grid(num_psfs=16, all_detectors=True, save=False, outdir=None, outfile=None, overwrite=True, verbose=True, use_detsampled_psf=False, single_psf_centered=True, **kwargs)
Create a PSF library in the form of a grid of PSFs across the detector based on the specified instrument, filter, and detector. The output GriddedPSFModel object will contain a 3D array with axes [i, y, x] where i is the PSF position on the detector grid and (y,x) is the 2D PSF.
- Parameters:
num_psfs (int) – The total number of fiducial PSFs to be created and saved in the files. This number must be a square number. Default is 16. E.g. num_psfs = 16 will create a 4x4 grid of fiducial PSFs.
all_detectors (bool) – If True, run all detectors for the instrument. If False, run for the detector set in the instance. Default is True
save (bool) – True/False boolean if you want to save your file. Default is False.
outdir (str) – If “save” keyword is set to True, your file will be saved in the specified directory. Default of None will save it in the current directory
outfile (str) – If “save” keyword is set to True, your file will be saved as {outfile}_det.fits. Default of None will save it as instr_det_filt_fovp#_samp#_npsf#.fits
overwrite (bool) – True/False boolean to overwrite the output file if it already exists. Default is True.
verbose (bool) – True/False boolean to print status updates. Default is True.
use_detsampled_psf (bool) – If True, the grid of PSFs returned will be detector sampled (made by binning down the oversampled PSF). If False, the PSFs will be oversampled by the factor defined by the oversample/detector_oversample/fft_oversample keywords. Default is False. This is rarely needed - if uncertain, leave this alone.
single_psf_centered (bool) – If num_psfs is set to 1, this defines where that psf is located. If True it will be the center of the detector, if False it will be the location defined in the STPSF attribute detector_position (reminder - detector_position is (x,y)). Default is True This is also rarely needed.
**kwargs – Any extra arguments to pass the STPSF calc_psf() method call.
- Returns:
gridmodel (photutils GriddedPSFModel object or list of objects) – Returns a GriddedPSFModel object or a list of objects if more than one configuration is specified (1 per instrument, detector, and filter) User also has the option to save the grid as a fits.HDUlist object.
Examples
nir = stpsf.NIRCam() nir.filter = “F090W” list_of_grids = nir.psf_grid(all_detectors=True, num_psfs=4)
wfi = stpsf.WFI() wfi.filter = “Z087” wfi.detector = “WFI02” grid = wfi.psf_grid(all_detectors=False, oversample=5, fov_pixels=101)
- property psf_info
PSF parameters
- pupil = None
Filename or fits.HDUList for JWST pupil mask. Usually there is no need to change this.
- property pupil_mask
Currently selected Lyot pupil mask, or None for direct imaging
- pupil_mask_list
List of available pupil_masks
- pupilopd = None
Filename or fits.HDUList for JWST pupil OPD.
This can be either a full absolute filename, or a relative name in which case it is assumed to be within the instrument’s data/OPDs/ directory, or an actual fits.HDUList object corresponding to such a file. If the file contains a datacube, you may set this to a tuple (filename, slice) to select a given slice, or else the first slice will be used.
- property quick
Perform quicker coeff calculation over limited bandwidth?
- ramp_optimize(sp, sp_bright=None, is_extended=False, patterns=None, snr_goal=None, snr_frac=0.02, tacq_max=None, tacq_frac=0.1, well_frac_max=0.8, nint_min=1, nint_max=5000, ng_min=2, ng_max=None, return_full_table=False, even_nints=False, verbose=False, **kwargs)
Optimize ramp settings.
Find the optimal ramp settings to observe a spectrum based on input constraints. This function quickly runs through each detector readout pattern and calculates the acquisition time and SNR for all possible settings of NINT and NGROUP that fulfill the SNR requirement (and other constraints).
The final output table is then filtered, removing those exposure settings that have the same exact acquisition times but worse SNR. Further “obvious” comparisons are done that exclude settings where there is another setting that has both better SNR and less acquisition time. The best results are then sorted by an efficiency metric (SNR / sqrt(acq_time)). To skip filtering of results, set return_full_table=True.
The result is an AstroPy Table.
- Parameters:
sp (
webbpsf_ext.synphot_ext.Spectrum) – A synphot spectral object to calculate SNR.sp_bright (
webbpsf_ext.synphot_ext.Spectrum, None) – Same as sp, but optionally used to calculate the saturation limit (treated as brightest source in field). If a coronagraphic mask observation, then this source is assumed to be occulted and sp is fully unocculted.is_extended (bool) – Treat sp source as extended object, then in units/arcsec^2
snr_goal (float) – Minimum required SNR for source. For grism, this is the average SNR for all wavelength.
snr_frac (float) – Give fractional buffer room rather than strict SNR cut-off.
tacq_max (float) – Maximum amount of acquisition time in seconds to consider.
tacq_frac (float) – Fractional amount of time to consider exceeding tacq_max.
patterns (numpy array) – Subset of MULTIACCUM patterns to check, otherwise check all.
nint_min/max (int) – Min/max number of desired integrations.
ng_min/max (int) – Min/max number of desired groups in a ramp.
well_frac_max (float) – Maximum level that the pixel well is allowed to be filled. Fractions greater than 1 imply hard saturation, but the reported SNR will not be aware of any saturation that may occur to sp.
even_nints (bool) – Return only the even NINTS
return_full_table (bool) – Don’t filter or sort the final results (ingores event_ints).
verbose (bool) – Prints out top 10 results.
- Keyword Arguments:
zfact (float) – Factor to scale Zodiacal spectrum (default 2.5)
ra (float) – Right ascension in decimal degrees
dec (float) – Declination in decimal degrees
thisday (int) – Calendar day to use for background calculation. If not given, will use the average of visible calendar days.
ideal_Poisson (bool) – Use total signal for noise estimate? Otherwise MULTIACCUM equation is used. Default = True
rad_EE (int) – Extraction aperture radius (in pixels) for imaging mode.
dw_bin (float) – Delta wavelength to calculate spectral sensitivities for grisms and DHS.
ap_spec (float, int) – Instead of dw_bin, specify the spectral extraction aperture in pixels. Takes priority over dw_bin. Value will get rounded up to nearest int.
Note
The keyword arguments ra, dec, thisday are not recommended for use given the amount of time it takes to query the web server. Instead, use
bg_zodi()to match a zfact estimate.- Returns:
astropy table – A sorted and filtered table of ramp options.
- recenter_psf(psf, sampling=1, shift_func=<function fourier_imshift>, interp='cubic', **kwargs)
Recenter PSF to array center
- sat_limits(sp=None, bp_lim=None, units='vegamag', well_frac=0.8, ngroup=None, trim_psf=33, verbose=False, **kwargs)
Saturation limits.
Generate the limiting magnitude (80% saturation) with the current instrument parameters (filter and ramp settings) assuming some spectrum. If no spectrum is defined, then a G2V star is assumed.
The user can also define a separate bandpass in which to determine the limiting magnitude that will cause the current NIRCam bandpass to saturate.
- Parameters:
sp (
webbpsf_ext.synphot_ext.Spectrum) – Spectrum to determine saturation limit.bp_lim (
webbpsf_ext.synphot_ext.Bandpass) – Bandpass to report limiting magnitude.units (str) – Output units (defaults to vegamag).
well_frac (float) – Fraction of full well to consider ‘saturated’.
ngroup (int, None) – Option to specify the number of groups to determine integration time. If not set, then the default is to use those specified in the Detectors class. Can set ngroup=0 for the so-called Zero Frame in the event there are multiple reads per group.
trim_psf (int, None) – Option to crop the PSF coefficient around the brightest pixel. For PSFs with large fov_pix values, this option helps speed up the saturation limit calculation. Afterall, we’re usually only interested in the brightest pixel when calculating saturation limits. Set to None to use the ‘fov_pix’ value. Default = 33 (detector pixels).
verbose (bool) – Print result details.
Example
>>> nrc = pynrc.NIRCam('F430M') # Initiate NIRCam observation >>> sp_A0V = pynrc.stellar_spectrum('A0V') # Define stellar spectral type >>> bp_k = pynrc.bp_2mass('k') # synphot K-Band bandpass >>> mag_lim = nrc.sat_limits(sp_A0V, bp_k, verbose=True)
Returns K-Band Limiting Magnitude for F430M assuming A0V source.
- saturation_levels(ngroup=2, do_ref=False, image=None, charge_migration=True, **kwargs)[source]
Saturation levels
Create image showing level of saturation for each pixel. Saturation at different number of groups is possible with ngroup keyword. Returns an array the same shape as det_info [ypix,xpix] properties.
- Parameters:
ngroup (int) – How many group times to determine saturation level? If this number is higher than the total groups in ramp, then a warning is produced. The default is ngroup=2, A value of 0 corresponds to the so-called “zero-frame,” which is the very first frame that is read-out and saved separately. This is the equivalent to ngroup=1 for RAPID and BRIGHT1 observations.
do_ref (bool) – Get saturation levels for reference source instead of science
image (ndarray) – Rather than generating an image on the fly, pass a pre-computed slope image.
charge_migration (bool) – Include charge migration effects?
- Keyword Arguments:
exclude_disk (bool) – Do not include disk in final image (for radial contrast), but still add Poisson noise from disk.
exclude_planets (bool) – Do not include planets in final image (for radial contrast), but still add Poisson noise from disk.
use_cmask (bool) – Use the coronagraphic mask image to attenuate planet or disk that is obscurred by a corongraphic mask feature.
satmax (float) – Saturation value to limit charge migration. Default is 1.5.
niter (int) – Number of iterations for charge migration. Default is 5.
corners (bool) – Include corner pixels in charge migration? Default is True.
zfact (float) – Zodiacal background factor (default=2.5)
ra (float) – Right ascension in decimal degrees
dec (float) – Declination in decimal degrees
thisday (int) – Calendar day to use for background calculation. If not given, will use the average of visible calendar days.
- property save_dir
Coefficient save directory
- property save_name
Coefficient file name
- property scaid
SCA ID (481, 482, … 489, 490)
- sensitivity(nsig=10, units=None, sp=None, verbose=False, do_ref=False, **kwargs)[source]
Sensitivity limits.
Convenience function for returning the point source (and surface brightness) sensitivity for the given instrument setup. See sensitivities function for more details.
- Parameters:
nsig (int, float) – Desired nsigma sensitivity (default 10).
units (str) – Output units (defaults to uJy for grisms, nJy for imaging).
sp (
webbpsf_ext.synphot_ext.Spectrum) – Input spectrum to use for determining sensitivity. Only the spectral shape matters, unlessforwardSNR=True.verbose (bool) – Print result details.
- Keyword Arguments:
forwardSNR (bool) – Find the SNR of the input spectrum instead of sensitivity.
zfact (float) – Factor to scale Zodiacal spectrum (default 2.5)
ideal_Poisson (bool) – If set to True, use total signal for noise estimate, otherwise MULTIACCUM equation is used.
rad_EE (float) – Extraction aperture radius (in pixels) for imaging mode.
dw_bin (float) – Delta wavelength for spectral sensitivities (grisms & DHS).
ap_spec (int, float) – Instead of dw_bin, specify the spectral extraction aperture in pixels. Takes priority over dw_bin. Value will get rounded up to nearest int.
- set_position_from_aperture_name(aperture_name)
Set the simulated center point of the array based on a named SIAF aperture. This will adjust the detector and detector position attributes.
- property siaf_ap
SIAF Aperture object
- property siaf_ap_names
Give all possible SIAF aperture names
- simulate_level1b(target_name, ra, dec, date_obs, time_obs, sp=None, im_slope=None, cframe='sci', nint=None, do_dark=False, save_dir=None, return_model=False, return_hdul=False, **kwargs)
Simulate DMS Level 1b data model
- simulate_ramps(sp=None, im_slope=None, cframe='sci', nint=None, do_dark=False, rand_seed=None, **kwargs)
Simulate Ramp Data
Create a series of ramp data based on the current NIRCam settings. This method calls the
gen_ramp()function, which in turn calls the detector noise generatorsimulate_detector_ramp().- Parameters:
im_slope (numpy array, None) – Pass the slope image directly. If not set, then a slope image will be created from the input spectrum keyword. This should include zodiacal light emission, but not dark current. Make sure this array is in detector coordinates.
sp (
webbpsf_ext.synphot_ext.Spectrum, None) – A synphot spectral object. If not specified, then it is assumed that we’re looking at blank sky.cframe (str) – Output coordinate frame, ‘sci’ or ‘det’.
nint (None or int) – Options to specify arbitrary number of integrations.
do_dark (bool) – Make a dark ramp (ie., pupil_mask=’FLAT’), no external flux.
- Keyword Arguments:
zfact (float) – Factor to scale Zodiacal spectrum (default 2.5)
ra (float) – Right ascension in decimal degrees
dec (float) – Declination in decimal degrees
thisday (int) – Calendar day to use for background calculation. If not given, will use the average of visible calendar days.
return_full_ramp (bool) – By default, we average groups and drop frames as specified in the det input. If this keyword is set to True, then return all raw frames within the ramp. The last set of nd2 frames will be omitted.
out_ADU (bool) – If True, divide by gain and convert to 16-bit UINT.
super_bias (ndarray or None) – Option to include a custom super bias image. If set to None, then grabs from
cal_obj. Should be the same shape asim_slope.super_dark (ndarray or None) – Option to include a custom super dark image. If set to None, then grabs from
cal_obj. Should be the same shape asim_slope.include_dark (bool) – Add dark current?
include_bias (bool) – Add detector bias?
include_ktc (bool) – Add kTC noise?
include_rn (bool) – Add readout noise per frame?
include_cpink (bool) – Add correlated 1/f noise to all amplifiers?
include_upink (bool) – Add uncorrelated 1/f noise to each amplifier?
include_acn (bool) – Add alternating column noise?
apply_ipc (bool) – Include interpixel capacitance?
apply_ppc (bool) – Apply post-pixel coupling to linear analog signal?
include_refoffsets (bool) – Include reference offsts between amplifiers and odd/even columns?
include_refinst (bool) – Include reference/active pixel instabilities?
include_colnoise (bool) – Add in column noise per integration?
col_noise (ndarray or None) – Option to explicitly specifiy column noise distribution in order to shift by one for subsequent integrations
amp_crosstalk (bool) – Crosstalk between amplifiers?
add_crs (bool) – Add cosmic ray events? See Robberto et al 2010 (JWST-STScI-001928).
cr_model (str) – Cosmic ray model to use: ‘SUNMAX’, ‘SUNMIN’, or ‘FLARES’.
cr_scale (float) – Scale factor for probabilities.
apply_nonlinearity (bool) – Apply non-linearity?
random_nonlin (bool) – Add randomness to the linearity coefficients?
apply_flats (bool) – Apply sub-pixel QE variations (crosshatching)?
latents (None or ndarray) – (TODO) Apply persistence from previous integration.
- property slowaxis
Slow readout direction in sci coords
- star_flux(fluxunit='counts', do_ref=False, sp=None)[source]
Stellar flux
Return the stellar flux in synphot-supported units, such as vegamag, counts, or Jy.
- Parameters:
fluxunits (str) – Desired output units, such as counts, vegamag, Jy, etc. Must be a synphot supported unit string.
sp (
webbpsf_ext.synphot_ext.Spectrum) – Normalized synphot spectrum.
- update_detectors(verbose=False, do_ref=False, **kwargs)[source]
Update detector operation parameters
Creates detector object based on
detectorattribute. This function should be called any time a filter, pupil, mask, or module is modified by the user.If the user wishes to change any properties of the multiaccum ramp or detector readout mode, pass those arguments through this function rather than creating a whole new NIRCam() instance. For example:
>>> nrc = pynrc.NIRCam('F430M', ngroup=10, nint=5) >>> nrc.update_detectors(ngroup=2, nint=10, wind_mode='STRIPE', ypix=64)
A dictionary of the keyword settings can be referenced in
det_info. This dictionary cannot be modified directly.- Parameters:
verbose (bool) – Print out ramp and detector settings.
- Keyword Arguments:
wind_mode (str) – Window mode type ‘FULL’, ‘STRIPE’, ‘WINDOW’.
xpix (int) – Size of window in x-pixels for frame time calculation.
ypix (int) – Size of window in y-pixels for frame time calculation.
x0 (int) – Lower-left x-coord position of detector window.
y0 (int) – Lower-left y-coord position of detector window.
read_mode (str) – NIRCam Ramp Readout mode such as ‘RAPID’, ‘BRIGHT1’, etc.
nint (int) – Number of integrations (ramps).
ngroup (int) – Number of groups in a integration.
nf (int) – Number of frames per group.
nd1 (int) – Number of drop frame after reset (before first group read).
nd2 (int) – Number of drop frames within a group (ie., groupgap).
nd3 (int) – Number of drop frames after final read frame in ramp.
nr1 (int) – Number of reset frames within first ramp.
nr2 (int) – Number of reset frames for subsequent ramps.
- update_detectors_ref(verbose=False, **kwargs)[source]
An easy-to-identify shortcut to gen_ref_det, because I keep forgetting to run it to independently of update_detectors.
- Keyword Arguments:
wind_mode (str) – Window mode type ‘FULL’, ‘STRIPE’, ‘WINDOW’.
xpix (int) – Size of window in x-pixels for frame time calculation.
ypix (int) – Size of window in y-pixels for frame time calculation.
x0 (int) – Lower-left x-coord position of detector window.
y0 (int) – Lower-left y-coord position of detector window.
read_mode (str) – NIRCam Ramp Readout mode such as ‘RAPID’, ‘BRIGHT1’, etc.
nint (int) – Number of integrations (ramps).
ngroup (int) – Number of groups in a integration.
nf (int) – Number of frames per group.
nd1 (int) – Number of drop frame after reset (before first group read).
nd2 (int) – Number of drop frames within a group (ie., groupgap).
nd3 (int) – Number of drop frames after final read frame in ramp.
nr1 (int) – Number of reset frames within first ramp.
nr2 (int) – Number of reset frames for subsequent ramps.
- update_from_SIAF(apname, image_mask=None, pupil_mask=None, **kwargs)
Update detector properties based on SIAF aperture
- update_psf_coeff(filter=None, pupil_mask=None, image_mask=None, detector=None, fov_pix=None, oversample=None, include_ote_field_dependence=None, include_si_wfe=None, include_distortions=None, pupil=None, pupilopd=None, offset_r=None, offset_theta=None, bar_offset=None, jitter=None, jitter_sigma=None, npsf=None, ndeg=None, nproc=None, quick=None, save=None, force=False, use_legendre=None, **kwargs)
Update properties and create new set of PSF coefficients
- Parameters:
filter (str) – Name of NIRCam filter.
pupil_mask (str, None) – NIRCam pupil elements such as grisms or lyot stops (default: None).
image_mask (str, None) – Specify which coronagraphic occulter (default: None).
detector (str) – Name of detector (e.g., “NRCA5”)
fov_pix (int) – Size of the PSF FoV in pixels (real SW or LW pixels). The defaults depend on the type of observation. Odd number place the PSF on the center of the pixel, whereas an even number centers it on the “crosshairs.”
oversample (int) – Factor to oversample during STPSF calculations. Default 2 for coronagraphy and 4 otherwise.
include_si_wfe (bool) – Include SI WFE measurements? Default=True.
include_ote_field_dependence (bool) – Include OTE field-dependent WFE measurements? Default=True.
include_distortions (bool) – If True, will include a distorted version of the PSF.
pupil (str) – File name or HDUList specifying telescope entrance pupil. Can also be an OTE_Linear_Model.
pupilopd (tuple or HDUList) – Tuple (file, index) or filename or HDUList specifying OPD. Can also be an OTE_Linear_Model.
wfe_drift (float) – Wavefront error drift amplitude in nm.
offset_r (float) – Radial offset from the center in arcsec.
offset_theta (float) – Position angle for radial offset, in degrees CCW.
bar_offset (float) – For wedge masks, option to set the PSF position across the bar.
jitter (str or None) – Currently either ‘gaussian’ or None.
jitter_sigma (float) – If
jitter = 'gaussian', then this is the size of the blurring effect.npsf (int) – Number of wavelengths/PSFs to fit.
ndeg (int) – Degree of polynomial fit.
nproc (int) – Manual setting of number of processor cores to break up PSF calculation. If set to None, this is determined based on the requested PSF size, number of available memory, and hardware processor cores. The automatic calculation endeavors to leave a number of resources available to the user so as to not crash the user’s machine.
save (bool) – Save the resulting PSF coefficients to a file? (default: True)
force (bool) – Forces a recalcuation of PSF even if saved PSF exists. (default: False)
quick (bool) – Only perform a fit over the filter bandpass with a lower default polynomial degree fit. (default: True)
use_legendre (bool) – Fit with Legendre polynomials, an orthonormal basis set. (default: True)
- property use_fov_pix_plus1
If fov_pix is even, then set use_fov_pix_plus1 to True. This will create PSF coefficients with an odd number of pixels that are then cropped to fov_pix so we don’t have to generate the same data twice.
- visualize_wfe_budget(slew_delta_time=<Quantity 14. d>, slew_case='EOL', ptt_only=False, verbose=True)
Display a visual WFE budget showing the various terms that sum into the overall WFE for a given instrument
Compares a STPSF instrument instance with the JWST optical budget for that instrument
- Parameters:
inst (stpsf.JWInstrument) – A JWST instrument instance
slew_delta_time (astropy.Quantity time) – Time duration for thermal slew model
slew_case (basestring) – ‘BOL’ or ‘EOL’ for beginning of life or end of life thermal slew model. EOL is about 3x higher amplitude
ptt_only (bool) – When decomposing wavefront into controllable modes, use a PTT-only basis? The default is to use all controllable pose modes. (This is mostly a leftover debug option at this point, not likely useful in general)
verbose (bool) – Be more verbose
- property wave_fit
Wavelength range to fit
- property well_level
Detector well level in units of electrons
- property wfe_ref_drift
WFE drift (nm) of ref obs relative to sci obs
- property wfe_roll_drift
WFE drift (nm) of Roll2 obs relative to Roll1 obs