NIRCam Tools¶
Functions Summary

Read filter bandpass. 

Generate PSF coefficients 

PSF Coefficient Mod for WFE Drift 

Generate PSF from coefficient 

Sensitivity Estimates 

Saturation limits 

Noise per pixel 

Select wavelength channel 

Grism information 

Create coronagraphic mask image 

Create mask image for a given detector 

Build a transmission image of a coronagraphic mask spanning the 20” coronagraphic FoV. 

Bar mask offset locations 

NIRCam CONFIG2 (0x4011) Register 

Detector class from header 
Documentation

pynrc.nrc_utils.
read_filter
(filter, pupil=None, mask=None, module=None, ND_acq=False, ice_scale=None, nvr_scale=None, grism_order=1, **kwargs)[source]¶ Read filter bandpass.
Read in filter throughput curve from file generated by STScI. Includes: OTE, NRC mirrors, dichroic, filter curve, and detector QE.
To Do: Account for pupil size reduction for DHS and grism observations.
 Parameters
filter (str) – Name of a filter.
pupil (str, None) – NIRCam pupil elements such as grisms or lyot stops.
mask (str, None) – Specify the coronagraphic occulter (spots or bar).
module (str) – Module ‘A’ or ‘B’.
ND_acq (bool) – ND acquisition square in coronagraphic mask.
ice_scale (float) – Add in additional OTE H2O absorption. This is a scale factor relative to 0.0131 um thickness.
nvr_scale (float) – Add in additional NIRCam nonvolatile residue. This is a scale factor relative to 0.280 um thickness. If set to None, then assumes a scale factor of 1.0 as is contained in the NIRCam filter curves. Setting nvr_scale=0 will remove these contributions.
grism_order (int) – Option to use 2nd order grism throughputs instead. Useful if someone wanted to overlay the 2nd order contributions onto a wide field observation.
 Returns
pysynphot.obsbandpass
– A Pysynphot bandpass object.

pynrc.nrc_utils.
psf_coeff
(filter_or_bp, pupil=None, mask=None, module='A', fov_pix=11, oversample=None, npsf=None, ndeg=None, tel_pupil=None, offset_r=None, offset_theta=None, jitter=None, jitter_sigma=0.007, opd=None, wfe_drift=None, drift_file=None, include_si_wfe=False, detector=None, detector_position=None, bar_offset=None, force=False, save=True, save_name=None, return_save_name=False, quick=False, **kwargs)[source]¶ Generate PSF coefficients
Creates a set of coefficients that will generate a simulated PSF at any arbitrary wavelength. This function first uses
WebbPSF
to simulate a number of evenly spaced PSFs throughout some specified bandpass. An nthdegree polynomial is then fit to each oversampled pixel using a linearleast square fitting routine. The final set of coefficients for each pixel is returned as an image cube. The returned set of coefficient can be used to produce a set of PSFs by:>>> psfs = pynrc.nrc_utils.jl_poly(waves, coeffs)
where ‘waves’ can be a scalar, nparray, list, or tuple. All wavelengths are in microns.
Distortions should be applied after creation of an image scene. For NIRCam, this involves first rotating the focal plane and then applying the distortions (see webbpsf.distortion).
>>> psf_rotated = distortion.apply_rotation(psf, crop=True) # apply rotation >>> psf_distorted = distortion.apply_distortion(psf_rotated) # apply siaf distortion
 Parameters
filter_or_bp (str,
pysynphot.obsbandpass
) – Either the name of a filter or a Pysynphot bandpass.pupil (str, None) – NIRCam pupil elements such as grisms or lyot stops.
mask (str, None) – Specify the coronagraphic occulter (spots or bar).
module (str) – Module ‘A’ or ‘B’.
fov_pix (int) – Size of the FoV in pixels (real SW or LW pixels)
oversample (int) – Factor to oversample pixels (in one dimension). The resulting coefficients will have x/y dimensions of fov_pix*oversample. Default 2 for coronagraphy and 4 otherwise.
npsf (int) – Number of evenlyspaced (with wavelength) monochromatic PSFs to generate with webbPSF. If not specified, then the default is to produce 20 PSFs/um. The wavelength range is determined by choosing those wavelengths where throughput is >0.001. There’s a minimum of 5 monochromatic PSFs calculated over the bandpass.
ndeg (int) – Polynomial degree for PSF fitting. Default = 10 (7 if quick=True).
offset_r (float) – Radial offset from the center in arcsec.
offset_theta (float) – Position angle for radial offset, in degrees CCW.
bar_offset (float) – Offset along coronagraphic bar (wedge) occulter, in arcseconds. Keeps the resulting PSF at zero tip/tilt, unlike offset_r and offset_theta. Defaults to 0 offset. Use
offset_bar()
for filterdependent offsets.opd (str, tuple, HDUList) – OPD specifications. If a tuple, then it should contain two elements (filename, slice index). Can also specify just the filename, which will default to the first image slice. Can also pass an HDUList where the OPD data is stored at HDUList[0].data.
wfe_drift (float) – Wavefront error drift amplitude in nm.
drift_file (str, None) – Delta OPD file to use for WFE drift.
include_si_wfe (bool) – Include SI WFE measurements? Default=False.
detector (str, None) – Name of detector [NRCA1, …, NRCA5, NRCB1, …, NRCB5].
detector_position (tuple, None) – The pixel position in (X, Y) on the detector (“science” coordinates)
tel_pupil (str, HDUList, None) – Telescope entrance pupil mask. Should either be a filename string or HDUList. If None, then default: jwst_pupil_RevW_npix1024.fits.gz.
jitter (str or None) – Currently either ‘gaussian’ or None.
jitter_sigma (float) – If
jitter = 'gaussian'
, then this is the size of the blurring effect.force (bool) – Forces a recalcuation of PSF even if saved PSF exists. (default: False)
save (bool) – Save the resulting PSF coefficients to a file? (default: True)
save_name (str, None) – Full path name of FITS file to save/load coefficents. If None, then a name is automatically generated.
quick (bool) – Only perform a fit over the filter bandpass with a smaller default polynomial degree fit. Auto filename will have filter name appended.
return_save_name (bool)

pynrc.nrc_utils.
wfed_coeff
(filter, force=False, save=True, save_name=None, **kwargs)[source]¶ PSF Coefficient Mod for WFE Drift
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.
Keyword Arguments match those in
psf_coeff()
. Parameters
filter (str) – Name of a filter.
force (bool) – Forces a recalcuation of coefficients even if saved PSF already exists. (default: False)
save (bool) – Save the resulting WFE drift coefficents to a file? (default: True)
save_name (str, None) – Full path name of save file (.npy) to save/load. If None, then a name is automatically generated, matching the
psf_coeff()
function.
Example
Generate PSF coefficient, WFE drift modifications, then create an undrifted and drifted PSF.
>>> from pynrc import nrc_utils >>> fpix, osamp = (128, 4) >>> coeff = nrc_utils.psf_coeff('F210M', fov_pix=fpix, oversample=osamp) >>> wfe_cf = nrc_utils.wfed_coeff('F210M', fov_pix=fpix, oversample=osamp) >>> psf0 = nrc_utils.gen_image_coeff('F210M', coeff=coeff, fov_pix=fpix, oversample=osamp)
>>> # Drift the coefficients >>> wfe_drift = 5 # nm >>> cf_fit = wfe_cf.reshape([wfe_cf.shape[0], 1]) >>> cf_mod = nrc_utils.jl_poly(np.array([wfe_drift]), cf_fit).reshape(coeff.shape) >>> cf_new = coeff + cf_mod >>> psf5nm = nrc_utils.gen_image_coeff('F210M', coeff=cf_new, fov_pix=fpix, oversample=osamp)

pynrc.nrc_utils.
gen_image_coeff
(filter_or_bp, pupil=None, mask=None, module='A', sp_norm=None, coeff=None, fov_pix=11, oversample=4, return_oversample=False, **kwargs)[source]¶ Generate PSF from coefficient
Create an image (direct, coronagraphic, grism, or DHS) based on a set of instrument parameters and PSF coefficients. The image is noiseless and doesn’t take into account any nonlinearity or saturation effects, but is convolved with the instrument throughput. Pixel values are in counts/sec. The result is effectively an idealized slope image.
If no spectral dispersers (grisms or DHS), then this returns a single image or list of images if sp_norm is a list of spectra.
 Parameters
filter_or_bp (str,
pysynphot.obsbandpass
) – Either the name of a filter or a Pysynphot bandpass.pupil (str, None) – NIRCam pupil elements such as grisms or lyot stops.
mask (str, None) – Specify the coronagraphic occulter (spots or bar).
module (str) – Module ‘A’ or ‘B’.
sp_norm (
pysynphot.spectrum
) – A normalized Pysynphot spectrum to generate image. 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. Coronagraphic PSFs will further decrease this flux.coeff (numpy array) – A cube of polynomial coefficients for generating PSFs. This is generally oversampled with a shape (fov_pix*oversamp, fov_pix*oversamp, deg). If not set, this will be calculated using the psf_coeff() function.
fov_pix (int) – Number of detector pixels in the image coefficient and PSF.
oversample (int) – Factor of oversampling of detector pixels.
return_oversample (bool) – If True, then also returns the oversampled version of the PSF.
 Keyword Arguments
grism_order (int) – Grism spectral order (default=1).
npsf (int) – Number of evenlyspaced (with wavelength) monochromatic PSFs to generate with webbPSF. If not specified, then the default is to produce 20 PSFs/um. The wavelength range is determined by choosing those wavelengths where throughput is >0.001.
ndeg (int) – Polynomial degree for PSF fitting. read_filter  ND_acq
ND_acq (bool) – ND acquisition square in coronagraphic mask.

pynrc.nrc_utils.
bg_sensitivity
(filter_or_bp, pupil=None, mask=None, module='A', pix_scale=None, sp=None, units=None, nsig=10, tf=10.737, ngroup=2, nf=1, nd2=0, nint=1, coeff=None, fov_pix=11, oversample=4, quiet=True, forwardSNR=False, offset_r=0, offset_theta=0, return_image=False, image=None, cr_noise=True, dw_bin=None, ap_spec=None, rad_EE=None, **kwargs)[source]¶ Sensitivity Estimates
Estimates the sensitivity for a set of instrument parameters. By default, a flat spectrum is convolved with the specified bandpass. For imaging, this function also returns the surface brightness sensitivity.
The number of photoelectrons are computed for a source at some magnitude as well as the noise from the detector readout and some average zodiacal background flux. Detector readout noise follows an analytical form that matches extensive long dark observations during cryovac testing.
This function returns the nsigma background limit in units of uJy (unless otherwise specified; valid units can be found on the Pysynphot webpage at https://pysynphot.readthedocs.io/).
For imaging, a single value is given assuming aperture photometry with a radius of ~1 FWHM rounded to the next highest integer pixel (or 2.5 pixels, whichever is larger). For spectral observations, this function returns an array of sensitivities at 0.1um intervals with apertures corresponding to 2 spectral pixels and a number of spatial pixels equivalent to 1 FWHM rounded to the next highest integer (minimum of 5 spatial pixels).
 Parameters
Instrument Settings
——————
filter_or_bp (Either the name of the filter or precomputed Pysynphot bandpass.)
pupil (NIRCam pupil elements such as grisms or lyot stops)
mask (Specify the coronagraphic occulter (spots or bar))
module (‘A’ or ‘B’)
pix_scale (Pixel scale in arcsec/pixel)
Spectrum Settings
——————
sp (A pysynphot spectral object to calculate sensitivity) – (default: Flat spectrum in photlam)
nsig (Desired nsigma sensitivity)
units (Output units (defaults to uJy for grisms, nJy for imaging))
forwardSNR (Find the SNR of the input spectrum instead of determining sensitivity.)
Ramp Settings
——————
tf (Time per frame)
ngroup (Number of groups per integration)
nf (Number of averaged frames per group)
nd2 (Number of dropped frames per group)
nint (Number of integrations/ramps to consider)
PSF Information
——————
coeff (A cube of polynomial coefficients for generating PSFs. This is) – generally oversampled with a shape (fov_pix*oversamp, fov_pix*oversamp, deg). If not set, this will be calculated using
psf_coeff()
.fov_pix (Number of detector pixels in the image coefficient and PSF.)
oversample (Factor of oversampling of detector pixels.)
offset_r (Radial offset of the target from center.)
offset_theta (Position angle for that offset, in degrees CCW (+Y).)
Misc.
——————
image (Explicitly pass image data rather than calculating from coeff.)
return_image (Instead of calculating sensitivity, return the image calced from coeff.) – Useful if needing to calculate sensitivities for many different settings.
rad_EE (Extraction aperture radius (in pixels) for imaging mode.)
dw_bin (Delta wavelength to calculate spectral sensitivities (grisms & DHS).)
ap_spec (Instead of dw_bin, specify the spectral extraction aperture in pixels.) – Takes priority over dw_bin. Value will get rounded up to nearest int.
cr_noise (Include noise from cosmic ray hits?)
 Keyword Arguments
 zfact, ra, dec, thisday, [locstr, year, day] (zodi_spec) –
 rn, ktc, idark, and p_excess (pix_noise) –
 npsf and ndeg (psf_coeff) –
 ND_acq (read_filter) –

pynrc.nrc_utils.
sat_limit_webbpsf
(filter_or_bp, pupil=None, mask=None, module='A', pix_scale=None, sp=None, bp_lim=None, int_time=21.47354, full_well=81000.0, well_frac=0.8, coeff=None, fov_pix=11, oversample=4, quiet=True, units='vegamag', offset_r=0, offset_theta=0, **kwargs)[source]¶ Saturation limits
Estimate the saturation limit of a point source for some bandpass. By default, it outputs the max KBand magnitude assuming a G2V star, following the convention on the UA NIRCam webpage. This can be useful if one doesn’t know how bright a source is in the selected NIRCam filter bandpass. However any userdefined bandpass (or userdefined spectrum) can be specifed. These must follow the Pysynphot conventions found here: http://pysynphot.readthedocs.org/en/latest/using_pysynphot.html
This function returns the saturation limit in Vega magnitudes by default, however, any flux unit supported by Pysynphot is possible via the ‘units’ keyword.
 Parameters
Instrument Settings
——————
filter_or_bp (Either the name of the filter or precomputed Pysynphot bandpass.)
pupil (NIRCam pupil elements such as grisms or lyot stops)
mask (Specify the coronagraphic occulter (spots or bar))
module (‘A’ or ‘B’)
Spectrum Settings
——————
sp (A Pysynphot spectrum to calculate saturation (default: G2V star))
bp_lim (A Pysynphot bandpass at which we report the magnitude that will) – saturate the NIRCam band assuming some spectrum sp
units (Output units for saturation limit)
Detector Settings
——————
int_time (Integration time in seconds (default corresponds to 2 full frames))
full_well (Detector full well level in electrons.)
well_frac (Fraction of full well to consider “saturated.” 0.8 by default.)
PSF Information
——————
coeff (A cube of polynomial coefficients for generating PSFs. This is) –
generally oversampled and has the shape:
[fov_pix*oversample, fov_pix*oversample, deg]
If not set, this this will be calculated from fov_pix, oversample, and npsf by generating a number of webbPSF images within the bandpass and fitting a highorder polynomial.
fov_pix (Number of detector pixels in the image coefficient and PSF.)
oversample (Factor of oversampling of detector pixels.)
offset_r (Radial offset of the target from center.)
offset_theta (Position angle for that offset, in degrees CCW (+Y).)
 Keyword Arguments
 npsf and ndeg (psf_coeff) –
 ND_acq (read_filter) –

pynrc.nrc_utils.
pix_noise
(ngroup=2, nf=1, nd2=0, tf=10.737, rn=15.0, ktc=29.0, p_excess=(0, 0), fsrc=0.0, idark=0.003, fzodi=0, fbg=0, ideal_Poisson=False, ff_noise=False, **kwargs)[source]¶ Noise per pixel
Theoretical noise calculation of a generalized MULTIACCUM ramp in terms of e/sec. Includes flat field errors from JWSTCALC003894.
 Parameters
n (int) – Number of groups in integration rampl
m (int) – Number of frames in each groupl
s (int) – Number of dropped frames in each groupl
tf (float) – Frame timel
rn (float) – Read Noise per pixel (e).
ktc (float) – kTC noise (in e). Only valid for single frame (n=1)l
p_excess (arraylike) – An array or list of two elements that holds the parameters describing the excess variance observed in effective noise plots. By default these are both 0. For NIRCam detectors, recommended values are [1.0,5.0] for SW and [1.5,10.0] for LW.
fsrc (float) – Flux of source in e/sec/pix.
idark (float) – Dark current in e/sec/pix.
fzodi (float) – Zodiacal light emission in e/sec/pix.
fbg (float) – Any additional background (telescope emission or scattered light?)
ideal_Poisson (bool) – If set to True, use total signal for noise estimate, otherwise MULTIACCUM equation is used?
ff_noise (bool) – Include flat field errors in calculation? From JWSTCALC003894. Default=False.
Notes
Various parameters can either be single values or numpy arrays. If multiple inputs are arrays, make sure their array sizes match. Variables that need to have the same array shapes (or a single value):
n, m, s, & tf
rn, idark, ktc, fsrc, fzodi, & fbg
Array broadcasting also works.
Example
>>> n = np.arange(50)+1 # An array of different ngroups to test out
>>> # Create 2D Gaussian PSF with FWHM = 3 pix >>> npix = 20 # Number of pixels in x and y direction >>> fwhm = 3.0 >>> x = np.arange(0, npix, 1, dtype=float) >>> y = x[:,np.newaxis] >>> x0 = y0 = npix // 2 # Center position >>> fsrc = np.exp(4*np.log(2.) * ((xx0)**2 + (yy0)**2) / fwhm**2) >>> fsrc /= fsrc.max() >>> fsrc *= 10 # 10 counts/sec in peak pixel >>> fsrc = fsrc.reshape(npix,npix,1) # Necessary for broadcasting
>>> # Represents pixel array w/ slightly different RN/pix >>> rn = 15 + np.random.normal(loc=0, scale=0.5, size=(1,npix,npix)) >>> # Results is a 50x(20x20) showing the noise in e/sec/pix at each group >>> noise = pix_noise(ngroup=n, rn=rn, fsrc=fsrc)

pynrc.nrc_utils.
channel_select
(bp)[source]¶ Select wavelength channel
Based on input bandpass, return the pixel scale, dark current, and excess read noise parameters. These values are typical for either a SW or LW NIRCam detector.
 Parameters
bp (
pysynphot.obsbandpass
) – NIRCam filter bandpass.

pynrc.nrc_utils.
grism_res
(pupil='GRISM', module='A', m=1)[source]¶ Grism information
Based on the pupil input and module, return the spectral dispersion and resolution as a tuple (res, dw).
 Parameters
pupil (str) – ‘GRISM0’ or ‘GRISM90’, otherwise assume res=1000 pix/um
module (str) – ‘A’ or ‘B’
m (int) – Spectral order (1 or 2).

pynrc.nrc_utils.
build_mask
(module='A', pixscale=0.03)[source]¶ Create coronagraphic mask image
Return a truncated image of the full coronagraphic mask layout for a given module.
+V3 is up, and +V2 is to the left.

pynrc.nrc_utils.
build_mask_detid
(detid, oversample=1, ref_mask=None, pupil=None)[source]¶ Create mask image for a given detector
Return a full coronagraphic mask image as seen by a given SCA. +V3 is up, and +V2 is to the left.
 Parameters
detid (str) – Name of detector, ‘A1’, A2’, … ‘A5’ (or ‘ALONG’), etc.
oversample (float) – How much to oversample output mask relative to detector sampling.
ref_mask (str or None) – Reference mask for placement of coronagraphic mask elements. If None, then defaults are chosen for each detector.
pupil (str or None) – Which Lyot pupil stop is being used? If None, then defaults based on ref_mask.

pynrc.nrc_utils.
coron_trans
(name, module='A', pixscale=None, fov=20, nd_squares=True)[source]¶ Build a transmission image of a coronagraphic mask spanning the 20” coronagraphic FoV.
Pulled from WebbPSF

pynrc.nrc_utils.
offset_bar
(filt, mask)[source]¶ Bar mask offset locations
Get the appropriate offset in the xposition to place a source on a bar mask. Each bar is 20” long with edges and centers corresponding to:
SWB: [1.03, 2.10, 3.10] (um) => [10, 0, +10] (asec) LWB: [2.30, 4.60, 6.90] (um) => [+10, 0, 10] (asec)

pynrc.nrc_utils.
config2
(input, intype='int')[source]¶ NIRCam CONFIG2 (0x4011) Register
Return a dictionary of configuration parameters depending on the value of CONFIG2 register (4011).
 Parameters
input (int, str) – Value of CONFIG2, nominally as an int. Binary and Hex values can also be passed as strings.
intype (str) – Input type (int, hex, or bin) for integer, hex, string, or binary string.

pynrc.nrc_utils.
create_detops
(header, DMS=False, read_mode=None, nint=None, ngroup=None, detector=None, wind_mode=None, xpix=None, ypix=None, x0=None, y0=None, nff=None)[source]¶ Detector class from header
Create a detector class based on header settings. Can override settings with a variety of keyword arguments.
 Parameters
header (obj) – Header from NIRCam FITS file
DMS (bool) – Is header format from Data Management Systems? Otherwises, ISIMlike.
 Keyword Arguments
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.
detector (int, str) – NIRCam detector ID (481490) or SCA ID (A1B5).
wind_mode (str) – Window mode type ‘FULL’, ‘STRIPE’, ‘WINDOW’.
xpix (int) – Size of window in xpixels for frame time calculation.
ypix (int) – Size of window in ypixels for frame time calculation.
x0 (int) – Lowerleft xcoord position of detector window.
y0 (int) – Lowerleft ycoord position of detector window.
nff (int) – Number of fast row resets.