pynrc.NIRCam

class pynrc.NIRCam(filter=None, pupil_mask=None, image_mask=None, ND_acq=False, detector=None, apname=None, autogen_coeffs=True, calc_psf_offset=True, **kwargs)[source]

Bases: NIRCam_ext

NIRCam base instrument class

Creates a NIRCam instrument class that holds all the information pertinent to an observation using a given observation. This class extends the NIRCam subclass webbpsf_ext.NIRCam_ext, to generate PSF coefficients to calculate an arbitrary PSF based on wavelength, field position, and WFE drift.

In addition to PSF generation, includes ability to estimate detector saturation limits, sensitivities, and perform ramp optimizations.

__init__(filter=None, pupil_mask=None, image_mask=None, ND_acq=False, detector=None, apname=None, autogen_coeffs=True, calc_psf_offset=True, **kwargs)[source]

Init Function

Parameters:
  • filter (str) – Name of input filter.

  • pupil_mask (str, None) – Pupil elements such as grisms or lyot stops (default: None).

  • image_mask (str, None) – Specify which coronagraphic occulter (default: None).

  • ND_acq (bool) – Add in neutral density attenuation in throughput and PSF creation? Used primarily for sensitivity and saturation calculations. Not recommended for simulations (TBI).

  • detector (int or str) – NRC[A-B][1-5] or 481-490

  • apname (str) – Pass specific SIAF aperture name, which will update pupil mask, image mask, and detector subarray information.

  • apername (str) – Alternate spelling of apname.

  • autogen_coeffs (bool) – Automatically generate base PSF coefficients. Equivalent to performing self.gen_psf_coeff(). Default: True WFE drift and field-dependent coefficients should be run manually via gen_wfedrift_coeff, gen_wfefield_coeff, and gen_wfemask_coeff.

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.

  • Keywords (PSF)

  • ============

  • 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 recalculation 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)

Methods

__init__([filter, pupil_mask, image_mask, ...])

Init Function

bg_zodi([zfact])

Zodiacal background flux.

bg_zodi_image([zfact, frame])

Zodiacal light image

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

display()

Display the currently configured optical system on screen

drift_opd(wfe_drift[, opd])

A quick method to drift the pupil OPD.

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_psf_coeff([bar_offset])

Generate PSF coefficients

gen_psfs_over_fov([sptype, wfe_drift, ...])

Create PSF grid over full field of view

gen_save_name([wfe_drift])

Generate save name for polynomial coefficient output file.

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_apname()

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.

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([sp, full_size, ngroup, ...])

Saturation levels

sensitivity([nsig, units, sp, verbose])

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

update_detectors([verbose])

Update detector operation parameters

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_MAX

LONG_WAVELENGTH_MIN

ND_acq

Use Coronagraphic ND acquisition square?

SHORT_WAVELENGTH_MAX

SHORT_WAVELENGTH_MIN

aperturename

SIAF aperture name for detector pixel to sky coords transformations

bandpass

Return bandpass throughput

channel

coron_substrate

Include coronagraphic substrate material?

det_info

Dictionary housing detector info parameters and keywords.

detector

Detector selected for simulated PSF

detector_list

Detectors on which the simulated PSF could lie

detector_position

The pixel position in (X, Y) on the detector, relative to the currently-selected SIAF aperture subarray.

fastaxis

Fast readout direction in sci coords

filter

Currently selected filter name (e.g. F200W).

filter_list

List of available filter names for this instrument

fov_pix

image_mask

Currently selected image plane mask, or None for direct imaging

is_coron

Observation with coronagraphic mask (incl Lyot stop)?

is_dark

is_grism

is_lyot

Is a Lyot mask in the pupil wheel?

module

multiaccum

multiaccum object

multiaccum_times

Exposure timings in dictionary

name

ndeg

npsf

Number of wavelengths/PSFs to fit

options

A dictionary capable of storing other arbitrary options, for extensibility.

oversample

pixelscale

Detector pixel scale, in arcsec/pixel

psf_info

PSF parameters

pupil

Filename or fits.HDUList for JWST pupil mask.

pupil_mask

Currently selected Lyot pupil mask, or None for direct imaging

pupilopd

Filename or fits.HDUList for JWST pupil OPD.

quick

Perform quicker coeff calculation over limited bandwidth?

save_dir

Coefficient save directory

save_name

Coefficient file name

scaid

SCA ID (481, 482, .

siaf_ap

SIAF Aperture object

siaf_ap_names

Give all possible SIAF aperture names

slowaxis

Slow readout direction in sci coords

telescope

use_fov_pix_plus1

If fov_pix is even, then set use_fov_pix_plus1 to True.

wave_fit

Wavelength range to fit

well_level

Detector well level in units of electrons

include_ote_field_dependence

Should calculations include the Science Instrument internal WFE?

image_mask_list

List of available image_masks

pupil_mask_list

List of available pupil_masks

property ND_acq

Use Coronagraphic ND acquisition square?

property aperturename

SIAF aperture name for detector pixel to sky coords transformations

property bandpass

Return bandpass throughput

bg_zodi(zfact=None, **kwargs)[source]

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)[source]

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_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:

  1. 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.

  2. 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)[source]

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)[source]

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)[source]

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_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_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)[source]

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_save_name(wfe_drift=0)

Generate save name for polynomial coefficient output file.

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()[source]

Get SIAF aperture based on instrument settings

get_subarray_name(apname=None)[source]

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

multiaccum object

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

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.plot function.

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)[source]

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)[source]

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)[source]

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(sp=None, full_size=True, ngroup=2, image=None, charge_migration=True, **kwargs)[source]

Saturation levels

Create image showing level of saturation for each pixel.

Parameters:
  • sp (webbpsf_ext.synphot_ext.Spectrum) – A synphot spectral object (normalized).

  • full_size (bool) – Expand (or contract) to size of detector array? If False, use fov_pix size.

  • 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.

  • image (ndarray) – Rather than generating an image on the fly, pass a pre-computed slope image. Overrides sp and full_size

  • charge_migration (bool) – Include charge migration effects?

Keyword Arguments:
  • 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.

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, **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, unless forwardSNR=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)[source]

Simulate DMS Level 1b data model

simulate_ramps(sp=None, im_slope=None, cframe='sci', nint=None, do_dark=False, rand_seed=None, **kwargs)[source]

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 generator simulate_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 as im_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 as im_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

update_detectors(verbose=False, **kwargs)[source]

Update detector operation parameters

Creates detector object based on detector attribute. 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_from_SIAF(apname, image_mask=None, pupil_mask=None, **kwargs)[source]

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)[source]

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