PanCAKE package

Module contents

pancake.analysis module

pancake.analysis.companion_snrs(subtracted_hdu_file, filt, mask, companion_xy, mask_radius=7)[source]

Function to, perhaps crudely, estimate the SNR of a planet in a pyKLIP subtracted image.

Parameters
  • subtracted_hdu_file (str) – Filepath for the subtracted image.

  • filt (str) – JWST filter string

  • mask (str) – JWST coronagraphic mask string

  • companion_xy (iterator of tuples) – zip() tuples, with each containing the companion x and y pixel locations.

Returns

companion_snrs – List of companion SNR’s corresponding the order provided in companion_xy

Return type

list

pancake.analysis.compute_contrast(subtracted_hdu_file, filt, mask, offaxis_psf_stamp, offaxis_flux, raw_input_dataset, raw_input_psflib, primary_vegamag=0, pixel_scale=0.063, annuli=1, subsections=1, numbasis=25, movement=1, subtraction='ADI', companion_xy=None, verbose=True, outputdir='./RESULTS/', plot_klip_throughput=False, low_pass=False)[source]

Function to compute contrast curves from a pyKLIP subtracted image file. Contrast curves will be corrected for both the coronagraphic and KLIP throughput, in addition to being converted to relative, and absolute magnitude sensitivity limits.

Parameters
  • subtracted_hdu_file (str) – Filename for a subtracted image file as produced by pyklip.parallelized.klip_dataset()

  • filt (str) – JWST filter string

  • mask (str) – JWST coronagraphic mask string

  • offaxis_psf_stamp (2D ndarray) – Stamp image of an offaxis (i.e. not underneath the coronagraph) PSF

  • offaxis_flux (float) – Peak flux of the offaxis PSF

  • raw_input_dataset (pyKLIP Dataset) – The input target dataset that was used to generate the subtracted_hdu_file. Used many times over for planet injection.

  • raw_input_psflib (pyKLIP PSFLibrary) – The input PSF library dataset that was used to generate the subtracted_hdu_file, if any. Used many times over for planet injection.

  • primary_vegamag (float) – Vega magnitude of the primary source of the target scene in the specified filter.

  • pixel_scale (float) – Pixel scale for this observation.

  • annuli (int) – pyKLIP argument - Annuli to use for KLIP. Can be a number, or a list of 2-element tuples (a, b) specifying the pixel boundaries (a <= r < b) for each annulus

  • subsections (int) – pyKLIP argument - Sections to break each annuli into. Can be a number [integer], or a list of 2-element tuples (a, b) specifying the positon angle boundaries (a <= PA < b) for each section [radians]

  • numbasis (int) – number of KL basis vectors to use (can be a scalar or list like). Length of b If numbasis is [None] the number of KL modes to be used is automatically picked based on the eigenvalues.

  • movement (int) – pyKLIP argument - minimum amount of movement (in pixels) of an astrophysical source to consider using that image for a refernece PSF

  • subtraction (str) – pyKLIP compatible subtraction string, available options are ‘ADI’, ‘RDI’, or ‘ADI+RDI’

  • companion_xy (iterator of tuples) – zip() tuples, with each containing any companion x and y pixel locations.

  • verbose (bool) – Optional argument to turn on (True) or off (False) printed terminal updates.

  • outputdir (str) – Directory to save any temporary or results files.

  • plot_klip_throughput (bool) – Optional argument to plot (True) the calculated KLIP throughput for each image. Primarily for debugging.

Returns

all_contrasts – Dictionary output of the contrast, relative magnitude sensitivity, absolute magnitude sensitivity and separation. Alternative formats of the separation, the contrast prior to throughput corrections, and the estimated KLIP throughput, are also provided.

Return type

dict

pancake.analysis.contrast_curve(pancake_results, target, references=None, subtraction='ADI', filters='all', masks='all', target_rolls='default', target_primary_source='default', reference_primary_sources='default', reference_rolls='default', klip_annuli=1, klip_subsections=1, klip_numbasis=25, klip_movement=1, get_companion_snrs=True, clean_saved_files=False, outputdir='./RESULTS/', save_prefix='default', verbose=True, plot_contrast=True, plot_klip_throughput=False, low_pass_filter=False, save_contrasts=True, regis_err='saved')[source]

Overarching function to compute contrast curves from output PanCAKE results.

Parameters
  • pancake_results (HDUList) – Simulated results as returned by pancake.sequence.Sequence().run()

  • target (str) – The provided string name for the target scene in the observation sequence.

  • references (str / list of strings / NoneType) – The provided string name(s) for the reference scene(s) in the observations sequence, if any.

  • subtraction (str) – pyKLIP compatible subtraction string, available options are ‘ADI’, ‘RDI’, or ‘ADI+RDI’

  • filters (str) – JWST filter string, or ‘all’ to use all available filters.

  • masks (str) – JWST mask string, or ‘all’ to use all available masks

  • target_rolls (list of ints / floats) – Which target PA roll images to use. Alternatively, ‘default’ to use all of them for ADI modes, or roll=0 for RDI.

  • target_primary_source (str) – Desired primary source to use for the target scene, or ‘default’ to assume primary source.

  • reference_primary_sources (str / list of strings) – Desired primary source(s) to use for the reference scene(s), or ‘default’ to assume primary source(s).

  • reference_rolls (list of ints / floats) – Which reference PA roll images to use. Alternatively, ‘default’ to use all of them for ADI modes, or roll=0 for RDI.

  • klip_annuli (int) – pyKLIP argument - Annuli to use for KLIP. Can be a number, or a list of 2-element tuples (a, b) specifying the pixel boundaries (a <= r < b) for each annulus

  • klip_subsections (int) – pyKLIP argument - Sections to break each annuli into. Can be a number [integer], or a list of 2-element tuples (a, b) specifying the positon angle boundaries (a <= PA < b) for each section [radians]

  • klip_numbasis (int) – number of KL basis vectors to use (can be a scalar or list like). Length of b If numbasis is [None] the number of KL modes to be used is automatically picked based on the eigenvalues.

  • klip_movement (int) – pyKLIP argument - minimum amount of movement (in pixels) of an astrophysical source to consider using that image for a refernece PSF

  • get_companions_snrs (bool) – True to calculate SNR’s of any companions in subtracted images, False to not.

  • clean_saved_files (bool) – True to delete any subtracted files generated by pyKLIP

  • outputdir (str) – Output directory to save subtracted files to.

  • save_prefix (str) – Prefix of filenames to be saved, ‘default is “{}-{}-{}-{}-nb{}a{}s{}m{}”.format(target, filt, mask, subtraction, klip_nb_str, klip_annuli, klip_subsections, klip_movement)

  • verbose (bool) – Toggle for printing various messages throughout the computation

  • plot_contrast (bool) – Toggle for plotting of contrast curves

  • plot_klip_throughput (bool) – Toggle for plotting of calculated klip_throughout, may interrupt code execution

  • save_contrasts (bool) – Toggle for saving computed contrasts to a file.

  • regis_err (str) – Error when registering the unsubtracted images to a common center

Returns

contrast_curve_dict – Dictionary output of all requested contrasts, relative magnitude sensitivities, absolute magnitude sensitivities and separations. Alternative formats of the separation, the contrast prior to throughput corrections, and the estimated KLIP throughput, are also provided.

Return type

dict

pancake.analysis.enable_runtime_warnings(state)[source]

Function to toggle on/off RuntimeWarning’s. Many of these do not impact the functionality of the code and therefore can be safely ignored for the vast majority of user cases. As a result, this function is immediately called a few lines above.

Parameters

state (bool) – Whether the RuntimeWarning’s should be enabled (True), or disabled ( False).

pancake.analysis.extract_simulated_images(pancake_results, observations, primary_sources, all_rolls, references=None, extract_offaxis=False, filename_prefix='image', low_pass=False, regis_err='saved')[source]

Function to extract a subset of simulated images from the output of a PanCAKE simulation into a more flexible format.

Parameters
  • pancake_results (HDUList) – Simulated results as returned by pancake.sequence.Sequence().run()

  • observations (list of strings) – List of observation strings that correspond to extension names in the pancake_results HDUList

  • primary_sources (list of strings) – List of the primary source(s) as obtained by identify_primary_sources

  • all_rolls (list of ints / floats) – Which PA roll images to be extracted

  • references (str / list of strings / NoneType) – The provided string name(s) for the reference scene(s) in the observations sequence, if any. Can not be used in conjunction with retrieving simulated target images.

  • extract_offaxis (bool) – Boolean choice of whether to extract offaxis images or not

  • filename_prefix (str) – Simple prefix string used to assign a unique name to each simulated image.

  • regis_err (str) – Error when registering the unsubtracted images to a common center

Returns

extracted – Dictionary containing all requested images, their roll angles, center points, assigned filenames, and if requested, a 20x20 pixel offaxis PSF stamp image and its peak flux.

Return type

dict

pancake.analysis.get_companion_mask(companion_xy, mask_dataset, mask_psflib, offaxis_psf_stamp, center=[0, 0], filt='f444w', mask='mask335r', annuli=1, subsections=1, numbasis=25, movement=1, subtraction='ADI', outputdir='./RESULTS/')[source]

Function to create a mask that can be applied to an image in order to “block” any pixels that correspond to the emitted flux of a companion object.

In essence, the function uses an offaxis PSF to inject companions into the image, on top of where they already exist, except at a very high flux.

This image can then be processed via KLIP to identify the pixels in the resultant subtracted image which are most impacted by the presence of the companion object, and assign them to be masked. This offers significant improvements over a simplistic circular mask due to the lobes of the JWST PSF, particularly for the NIRCam filters, whilst still being relatively quick to compute.

Parameters
  • companion_xy (iterator of tuples) – zip() tuples, with each containing any companion x and y pixel locations.

  • mask_dataset (pyKLIP Dataset) – Dataset to use to estimate the a companion mask

  • mask_psflib (pyKLIP PSFLibrary) – Dataset to use for RDI subtractions

  • offaxis_psf_stamp (2D ndarray) – Stamp image of an offaxis (i.e. not underneath the coronagraph) PSF

  • center (list) – List of x and y centers

  • filt (str) – JWST filter string

  • mask (str) – JWST coronagraphic mask string

  • annuli (int) – pyKLIP argument - Annuli to use for KLIP. Can be a number, or a list of 2-element tuples (a, b) specifying the pixel boundaries (a <= r < b) for each annulus

  • subsections (int) – pyKLIP argument - Sections to break each annuli into. Can be a number [integer], or a list of 2-element tuples (a, b) specifying the positon angle boundaries (a <= PA < b) for each section [radians]

  • numbasis (int) – number of KL basis vectors to use (can be a scalar or list like). Length of b If numbasis is [None] the number of KL modes to be used is automatically picked based on the eigenvalues.

  • movement (int) – pyKLIP argument - minimum amount of movement (in pixels) of an astrophysical source to consider using that image for a refernece PSF

  • subtraction (str) – pyKLIP compatible subtraction string, available options are ‘ADI’, ‘RDI’, or ‘ADI+RDI’

  • outputdir (str) – Directory to output pyKLIP generated results to.

Returns

comp_mask – True/False array of pixels to mask to exclude companion

Return type

2D ndarray

pancake.analysis.get_source_properties(template_obs, primary_source)[source]

Small function to grab a variety of source properties for a template observation HDUList

Parameters
  • template_obs (HDUList) – FITS data for a template observation file

  • primary_source (str) – String descriptor of the primary source in the observation.

Returns

source_props – Dictionary of source properties as extracted from the input template_obs file.

Return type

dict

pancake.analysis.identify_primary_sources(pancake_results, target, references=None, target_primary_source='default', reference_primary_sources='default')[source]

Function to identify, or assume, the primary sources (i.e. central ‘stars’) of output PanCAKE simulation results.

Parameters
  • pancake_results (HDUList) – Simulated results as returned by pancake.sequence.Sequence().run()

  • target (str) – The provided string name for the target scene in the observation sequence.

  • references (str / list of strings / NoneType) – The provided string name(s) for the reference scene(s) in the observations sequence, if any.

  • target_primary_source (str) – Desired primary source to use for the target scene, or ‘default’ to assume primary source.

  • reference_primary_sources (str / list of strings) – Desired primary source(s) to use for the reference scene(s), or ‘default’ to assume primary source(s).

Returns

primary_sources – List of the primary source(s), where the source in the ‘0’ index always corresponds to the target scene.

Return type

list of strings

pancake.analysis.mask_companions(image_array, companion_xy, mask_radius=7)[source]

Function apply NaN masks to a number of images at the location of known companion objects.

Parameters
  • image_array (3D ndarray) – Numpy array of input images

  • companion_xy (iterator of tuples) – zip() tuples, with each containing the companion x and y pixel locations.

  • mask_radius (float) – The desired mask radius in pixels.

Returns

masked_images – Numpy array of output, companion masked images.

Return type

3D ndarray

pancake.analysis.mask_pa(image, pa_ranges=[])[source]
pancake.analysis.meas_contrast_basic(dat, iwa, owa, resolution, center=None, low_pass_filter=True)[source]

Duplicate of the meas_contrast() function within pyKLIP, except calculating a standard 5 sigma limit instead of small sample statistics corrections.

Parameters
  • dat (2D ndarray) – 2D image - already flux calibrated

  • iwa (float) – inner working angle

  • owa (float) – outer working angle

  • resolution (float) – size of noise resolution element in pixels (for speckle noise ~ FWHM or lambda/D) but it can be 1 pixel if limited by pixel-to-pixel noise.

  • center (list) – location of star (x,y). If None, defaults the image size // 2.

  • low_pass_filter (bool/float) – if True, run a low pass filter. Can also be a float which specifices the width of the Gaussian filter (sigma). If False, no Gaussian filter is run

Returns

(seps, contrast) – separations in pixels and corresponding 5 sigma FPF

Return type

tuple

pancake.analysis.process_simulations(pancake_results, target, target_obs, filt, mask, primary_sources, references=None, reference_obs=None, target_rolls='default', reference_rolls='default', subtraction='ADI', low_pass=False, regis_err='saved')[source]

Function to process a set of desired simulated images from PanCAKE and convert them into pyKLIP datasets to enable easier stellar PSF subtraction and contrast curve estimation.

Parameters
  • pancake_results (HDUList) – Simulated results as returned by pancake.sequence.Sequence().run()

  • target (string) – The provided string name for the target scene in the observation sequence

  • target_obs (list of stings) – List of target observation strings that correspond to extension names in the pancake_results HDUList

  • filt (string) – JWST filter string

  • mask (string) – JWST coronagraphic mask string

  • primary_sources (list of strings) – List of the primary source(s) as obtained by identify_primary_sources

  • references (list of strings) – The provided string name(s) for the reference scene(s) in the observations sequence, if any.

  • reference_obs (list of strings) – List of target observation strings that correspond to extension names in the pancake_results HDUList, if any.

  • target_rolls (list of ints / floats) – Which target PA roll images to use. Alternatively, ‘default’ to use all of them for ADI modes, or roll=0 for RDI.

  • reference_rolls (list of ints / floats) – Which reference PA roll images to use. Alternatively, ‘default’ to use all of them for ADI modes, or roll=0 for RDI.

  • subtraction (str) – pyKLIP compatible subtraction string, available options are ‘ADI’, ‘RDI’, or ‘ADI+RDI’

  • regis_err (str) – Error when registering the unsubtracted images to a common center

Returns

processed_output – Dictionary output containing pyKLIP datasets for the target and PSF library (if necessary), in addition to some information on the offaxis simulation for normalisation / planet injection purposes.

Return type

dict

pancake.analysis.transmission_corrected(input_stamp, input_dx, input_dy, filt, mask, mode='multiply')[source]

Function to apply a 2-dimensional JWST coronagraphic transmission map to an input image.

Parameters
  • input_stamp (2D ndarray) – Input image, should have dimensions equal to or smaller than the array for the coronagraphic transmission map.

  • input_dx (2D ndarray) – Array of X pixel offsets for each element in the array relative to the central pixel of the simulation.

  • input_dy (2D ndarray) – Array of Y pixel offsets for each element in the array relative to the central pixel of the simulation.

  • filt (str) – JWST filter string, used to obtain offsets for the NIRCam bar masks.

  • mask (str) – JWST coronagraphic mask string, used to identify which transmission map to apply.

  • mode (str) – Whether to ‘multiply’ or ‘divide’ the input stamp by the transmission map.

Returns

output_stamp – Equivalent to the input_stamp following the application of the transmission map.

Return type

2D ndarray

pancake.config module

class pancake.config.EngineConfiguration(**kwargs)[source]

Bases: object

A class to consolidate the options for customizing calculations made with the Pandiea engine.

Users aren’t expected to interact with this class directly. Use the engine.options object instead.

Could add type checking in the @property.setter methods.

property cache

Caching can currently be done one of three ways: - LRU RAM cache (‘ram’) - On-disk cache (‘disk’) - No caching (‘none’)

property current_config

A space to store a pandeia configuration dictionary for inspection at runtime.

property current_options

Stores all configuration options in a dictionary, and returns that dictionary.

property effects

Sets pandeia effects (background, saturation, IPC). The default is for everything to be turned on.

property noise

Sets noise parameters. The default is for everything to be turned on.

property on_the_fly_PSFs

Avoid Pandeia’s precomputed PSFs and recompute in WebbPSF as needed?

property on_the_fly_oversample

A dictionary of extra options for configuring the PSF calculation ad hoc. Note some options are overridden in get_psf_on_the_fly().

See WebbPSF documentation for more details.

property on_the_fly_webbpsf_opd

Allow overriding the default OPD selection when computing PSFs on the fly.

See the WebbPSF documentation.

property on_the_fly_webbpsf_options

A dictionary of extra options for configuring the PSF calculation ad hoc. Note some options are overridden in get_psf_on_the_fly().

See WebbPSF documentation for more details.

property pandeia_effects

Allows access to the pandeia noise configuration

property pandeia_fixed_seed

By default, the pandeia engine uses a fixed seed. This has undesirable results for many coronagraphy applications. Pandeia-Coronagraphy disables this by default. Restore the fixed seed by toggling this to True.

static pandeia_instrument_config(aperture)[source]
property pandeia_noise

Allows access to the pandeia noise configuration

restore_defaults()[source]

Restore all parameters to their default values.

restore_options()[source]

This restores whatever is stored in self._saved_options. If there’s nothing there, it will have no effect (rather than crashing your program, so there’s that at least). Note that it does not delete the configuration stored in self._saved_options.

save_options()[source]

The configuration object has room for a single backed-up option set. This is useful for storing a default set before running a calculation, so that you can fiddle with the parameters, run the calculation, and then restore everything to what it was before you started fiddling. Note that there is only one such built-in save, so if you want to save a set of parameters you’ve created without overwriting that save, you should call the current_options parameter and store the resulting dictionary somewhere.

set_background(value)[source]

Allows for background counts to be turned on or off in the simulation

set_crs(value)[source]

Allows for cosmic rays to be turned on or off in the simulation

set_darkcurrent(value)[source]

Allows for dark current to be turned on or off in the simulation

set_ffnoise(value)[source]

Allows for flatfield noise to be turned on or off in the simulation

set_ipc(value)[source]

Allows for inter-pixel capacitance to be turned on or off in the simulation

set_readnoise(value)[source]

Allows for readnoise to be turned on or off in the simulation

set_rn_correlation(value)[source]

Allows for readnoise correlation to be turned on or off in the simulation

set_saturation(value)[source]

Allows for detector saturation to be turned on or off in the simulation

property verbose

Print information to terminal

property wave_sampling

Pandeia defaults to ~200 wavelength samples for imaging This is slow and unlikely to significantly improve the accuracy of coronagraphic performance predictions. Setting wave_sampling to 10-20 should be sufficient, and translates to a time savings of about 10. Leaving it at None sets it to Pandeia’s default.

pancake.engine module

The vast majority of functions in this submodule are obsolete owing to generalisation of PanCAKE simulations into Scenes and a Sequence, alongside the incorporation of pyKLIP postprocessing (Nov 2021). Nevertheless, for now I am leaving things as they are to maintain some level of backwards compatability.

Functions that are not used in the current version are marked as ‘Deprecated’ and may not have particularly detailed docstrings.

pancake.engine.calculate_all(raw_config)[source]
Deprecated - Run a pandeia coronagraphy calculation. Output will be
  • a pandeia report showing the target

  • a pandeia report showing the reference source

  • a pandeia report showing the unocculted target (with saturation disabled)

In pandeia 1.3, this can be done as a single calculation, with the results obtained from sub-reports. In pandeia 1.2, the sub-reports are not actually returned properly, so the overall calculation needs to be run 3 times.

Parameters

raw_config (dict) – Dictionary compatible with Pandeia calculations

Returns

output – Various products from the pandeia calculation

Return type

dict

pancake.engine.calculate_batch(calcfiles, nprocesses=None)[source]

Deprecated

pancake.engine.calculate_contrast(raw_config, offset_x=0.5, offset_y=0.5)[source]

Deprecated - Run a pandeia coronagraphy calculation in target-only mode, with the target offset to be unocculted, and with saturation disabled.

pancake.engine.calculate_contrast_curve(raw_config, target=None, reference=None, ta_error=True, iterations=5, keep_options=False)[source]

Deprecated

This is a replacement for the Pandeia calculate_contrast function. It is designed to use the various internal analysis functions to do the following… - Load one of the pandeia_coronagraphy custom templates - Repeat <iterations> times

  • Run through pandeia with the target scene in place of the default scene

  • Run through pandeia with the reference scene in place of the default scene

  • Run through pandeia with the off-axis target

  • Generate an aperture image

  • Run the analysis contrast utility method

It will return - list of target images - list of reference images - off-axis image - list of subtracted images - normalized contrast profile (with reference bins)

Parameters
  • raw_config (string or dict) –

    One of:
    • file name of pandeia JSON file describing an observation

    • pandeia configuration dictionary

    • pandeia instrument configuration from configuration dictionary (i.e. config[‘configuration’][‘instrument’])

  • target (list of dict (or dict), default None) –

    List of Pandeia-style scene dictionaries describing the target. If not present, then the

    target scene from raw_config will be used.

  • reference (list of dict (or dict), default None) –

    List of Pandeia-style scene dictionaries describing the reference source. If not present,

    then the reference scene from raw_config will be used. If a list, only the first element will be used (i.e. the reference source will be assumed to be a single element)

  • ta_error (bool, default False) – Whether to add target acquisition error offsets to the target and reference scenes.

  • iterations (int, default=1) – Number of times to iterate generating TA errors and observing the target and reference source

Returns

  • targets (list of numpy arrays containing <iterations> detector slopes of the target)

  • references (list of numpy arrays containing <iterations> detector slopes of the reference)

  • unocculted (numpy array of the detector slopes of the unocculted source)

  • subtractions (list of numpy arrays containing <iterations> reference-subtracted target images)

  • contrast (list of numpy arrays containing:) – bins: bins used for the normalized contrast profile contrast: normalized contrast profile

pancake.engine.calculate_reference(raw_config)[source]

Deprecated - Run a pandeia coronagraphy calculation in target-only mode, replacing the target scene with the scene stored in the coronagraphy strategy PSF subtraction source.

Parameters

raw_config (dict) – Dictionary compatible with Pandeia calculations

Returns

results – Various products from the pandeia calculation

Return type

dict

pancake.engine.calculate_subtracted(raw_config, target=None, reference=None, ta_error=False, sgd=False, stepsize=0.02)[source]

Deprecated

This is a function to calculate subtracted images with an optional reference image small-grid dither (SGD). It does the following…

  • Create a pandeia configuration file from which to build the target and reference scenes

  • [optional] construct SGD

  • observe target scene

  • for each reference observation
    • observe reference scene

  • centre reference to targets

  • create klip PSF

  • subtract klip PSF from target image

  • return subtracted image

It will return
  • target image

  • list of reference images

  • artificial PSF

  • subtracted image

Parameters
  • raw_config (string or dict) –

    One of:
    • file name of pandeia JSON file describing an observation

    • pandeia configuration dictionary

    • pandeia instrument configuration from configuration dictionary (i.e. config[‘configuration’][‘instrument’])

  • target_scene (list of dict (or dict), default None) –

    List of Pandeia-style scene dictionaries describing the target. If not present, then the

    target scene from raw_config will be used.

  • reference_scene (list of dict (or dict), default None) –

    List of Pandeia-style scene dictionaries describing the reference source. If not present,

    then the reference scene from raw_config will be used. If a list, only the first element will be used (i.e. the reference source will be assumed to be a single element)

  • ta_error (bool, default False) – Whether to add target acquisition error offsets to the target and reference scenes.

  • sgd (bool, default False) – Whether to create a small-grid dither (SGD) for the reference scene.

  • stepsize (float, default 0.02) – Size of the offsets in the SGD (if present), in arcseconds.

Returns

  • target (numpy array containing <iterations> detector slopes of the target)

  • references (list of numpy arrays containing <iterations> detector slopes of the reference)

  • psf (artificial PSF created with klip)

  • subtracted (numpy array containing <iterations> reference-subtracted target images)

pancake.engine.calculate_target(raw_config)[source]

Run a pandeia coronagraphy calculation in target-only mode

Parameters

raw_config (dict) – Dictionary compatible with Pandeia calculations

Returns

results – Various products from the pandeia calculation

Return type

dict

pancake.engine.get_options()[source]

This returns the options object, and is used to let the various Pandeia-based subclasses get the options object currently in use.

pancake.engine.load_calculation(filename)[source]

Deprecated

pancake.engine.perform_calculation(calcfile)[source]

Manually decorate pandeia.engine.perform_calculation to circumvent pandeia’s tendency to modify the calcfile during the calculation.

Updates to the saturation computation could go here as well.

Parameters

calcfile (dict) – Dictionary compatible with Pandeia calculations

Returns

results – Various products from the pandeia calculation

Return type

dict

pancake.engine.process_config(raw_config, target_scene, reference_scene)[source]

Deprecated

Process a variable that might be a file name, full JWST configuration dictionary, or instrument configuration dictionary, along with optional target and reference scenes.

pancake.engine.random_seed(self)[source]

Deprecated

The pandeia engine sets a fixed seed of 42. Circumvent that here.

pancake.engine.save_calculation(calcfile, filename)[source]

Deprecated

pancake.engine.save_to_fits(array, filename)[source]

Deprecated

pancake.io module

pancake.io.determine_aperture(filt, nircam_aperture, mode)[source]

Determine aperture (coronagraph) from filter and instrument mode

Parameters
  • filt (str) – JWST filter name

  • nircam_aperture (str) – Direct input for NIRCam aperture, or ‘default’ to automatically assume based on the filter.

  • mode (str) – Observing mode, ‘imaging’ or ‘coronagraphy’

Returns

aperture – Pandeia compatible aperture string

Return type

str

pancake.io.determine_bar_offset(filt)[source]

Returns the bar offset in arcsseconds for the nircam coronagraphs NOTE: As of Pandeia 1.6.1, I’m pretty sure these are slightly wrong.

Parameters

filt (str) – JWST filter name

Returns

offset – Offset value in arcseconds relative to mask center.

Return type

float

pancake.io.determine_detector(filt)[source]

Determine detector from the input filter, only compatible with NIRCam / MIRI.

Parameters

filt (str) – JWST filter name

Returns

detector – Pandeia compatible string

Return type

str

pancake.io.determine_exposure_time(subarray, pattern, groups, integrations)[source]

Determine exposure time (in seconds) for a given readout given the underlying subarray and readout parameters from JWST config files.

Parameters
  • subarray (str) – Subarray string

  • pattern (str) – multiaccum readout pattern

  • groups (int) – Number of groups

  • integrations (int) – Number of integrations

Returns

exposure_time – Exposure time in seconds.

Return type

float

pancake.io.determine_instrument(filt)[source]

Determine instrument from the input filter, only compatible with NIRCam / MIRI.

Parameters

filt (str) – JWST filter name

Returns

instrument – Pandeia compatible NIRCam or MIRI string

Return type

str

pancake.io.determine_pixel_scale(filt)[source]

Determine pixel scale in arcsec/pixel based on filter used.

Parameters

filt (str) – JWST filter name

Returns

pixel_scale – Pixel scale in arcseconds / pixel

Return type

float

pancake.io.determine_subarray(filt, mode, nircam_subarray, miri_subarray)[source]

Determine default subarray for filter and mode

Parameters
  • filt (str) – JWST filter name

  • mode (str) – Observing mode, ‘imaging’ or ‘coronagraphy’

  • nircam_subarray (str) – Manual input for NIRCam subarray, or ‘default’ to automatically determine.

  • miri_subarray (str) – Manual input for MIRI subarray, or ‘default’ to automatically determine.

Returns

Pandeia compatible subarray string

Return type

subarray str

pancake.io.read_bandpass(bandpass)[source]

Read filter bandpass file, must be from 2MASS, WISE, or a pandeia default.

Parameters

bandpass (str) – String representation of the bandpass

Returns

Bandpass – Synphot representation of the bandpass.

Return type

synphot SpectralElement()

pancake.io.read_coronagraph_transmission(mask)[source]

Read 2D coronagraphic transmission from resources folder.

Parameters

mask (str) – String representation of the coronagraphic mask

Returns

transmission – 2D representation of the coronagraphic transmission.

Return type

2D ndarray

pancake.io.sequence_input_checks(exposures, mode, nircam_aperture, nircam_subarray, miri_subarray, telescope, rolls, nircam_sgd, miri_sgd)[source]

Check the inputs to a Sequence call to ensure things match the correct format / types, if not raise an error and report to user.

Parameters
  • exposures (list of tuples) – User defined exposures

  • mode (str) – Observing mode, ‘imaging’ or ‘coronagraphy’

  • nircam_aperture (str) – Direct input for NIRCam aperture, or ‘default’ to automatically assume based on the filter.

  • nircam_subarray (str) – Manual input for NIRCam subarray, or ‘default’ to automatically determine.

  • miri_subarray (str) – Manual input for MIRI subarray, or ‘default’ to automatically determine.

  • telescope (str) – Telescope being used, must be ‘jwst’

  • rolls (list) – Input list of roll PA’s

  • nircam_sgd (str) – NIRCam small grid dither pattern string

  • miri_sgd (str) – MIRI small grid dither pattern string

pancake.opds module

All code in this module is from Jarron Leisenring and the pyNRC / WebbPSF_ext packages, repoduced with permission.

The primary reason for direct duplication is to avoid complicating the installation of PanCAKE.

See following links for potentially more up to date implementations:

https://github.com/JarronL/pynrc/blob/develop/pynrc/opds.py https://github.com/JarronL/webbpsf_ext/blob/main/webbpsf_ext/opds.py

pancake.opds.OPDFile_to_HDUList(file, slice_to_use=0)[source]

Make a picklable HDUList for ingesting into multiproccessor WebbPSF helper function.

class pancake.opds.OTE_WFE_Drift_Model(**kwargs)[source]

Bases: webbpsf.opds.OTE_Linear_Model_WSS

OPD subclass for calculating OPD drift values over time.

calc_rms(arr, segname=None)[source]

Calculate RMS of input images

evolve_dopd(delta_time, slew_angles, case='BOL', return_wfe_amps=True, return_dopd_fin=True, do_thermal=True, do_frill=True, do_iec=True, **kwargs)[source]

Evolve the delta OPD with multiple slews

Input an array of delta_time and slew_angles to return the evolution of a delta_OPD image. Option to return the various WFE components, including OTE backplane (thermal), frill tensioning, and IEC heater switching.

Parameters
  • delta_time (astropy.units quantity object) – An array of times assuming astropy units.

  • slew_angles (ndarray) – The sun pitch angles, in degrees between -5 and +45.

  • case (string) – Either “BOL” for current best estimate at beginning of life, or “EOL” for more conservative prediction at end of life.

  • do_thermal (bool) – Include thermal slew component? Mostly for debugging purposes.

  • do_frill (bool) – Include frill component? Mostly for debugging purposes.

  • do_iec (bool) – Include IEC component? Good to exclude if calling this function repeatedly for evolution of multiple slews, then add IEC later.

  • return_wfe_amps (bool) – Return a dictionary that provides the RMS WFE (nm) of each component at each time step.

  • return_dopd_fin (bool) – Option to exclude calculating final delta OPD in case we only want the final RMS WFE dictionary.

Keyword Arguments
  • amplitude (float) – Full amplitude of IEC arcsine distribution. Values will range from -0.5*amplitude to +0.5*amplitude.

  • period (float) – Period in minutes of IEC oscillations. Usually 3-5 minutes.

gen_delta_opds(delta_time, start_angle=- 5, end_angle=45, do_thermal=True, do_frill=True, do_iec=True, case='BOL', return_wfe_amps=True, return_dopd_fin=True, **kwargs)[source]

Create series of delta OPDs

Generate a series of delta OPDS, the result of which is a combination of thermal, frill, and IEC effects. The thermal and frill values are dependent on time, start/end slew angles, and case (‘BOL’ or ‘EOL’). Delta OPD contributions from the IEC heater switching are treated as random state switches assuming an arcsine distribution.

Parameters
  • delta_time (astropy.units quantity object) – An array of times assuming astropy units.

  • start_angle (float) – The starting sun pitch angle, in degrees between -5 and +45.

  • end_angle (float) – The ending sun pitch angle, in degrees between -5 and +45.

  • case (string) – Either “BOL” for current best estimate at beginning of life, or “EOL” for more conservative prediction at end of life.

  • do_thermal (bool) – Include thermal slew component? Mostly for debugging purposes.

  • do_frill (bool) – Include frill component? Mostly for debugging purposes.

  • do_iec (bool) – Include IEC component? Good to exclude if calling this function repeatedly for evolution of multiple slews, then add IEC later.

  • return_wfe_amps (bool) – Return a dictionary that provides the RMS WFE (nm) of each component at each time step.

  • return_dopd_fin (bool) – Option to exclude calculating final delta OPD in case we only want the final RMS WFE dictionary.

gen_frill_drift(delta_time, start_angle=- 5, end_angle=45, case='BOL')[source]

Frill WFE drift scaling

Function to determine the factor to scale the delta OPD associated with frill tensioning. Returns the RMS WFE (nm) depending on time and slew angles.

Parameters
  • delta_time (astropy.units quantity object) – The time since a slew occurred.

  • start_angle (float) – The starting sun pitch angle, in degrees between -5 and +45

  • end_angle (float) – The ending sun pitch angle, in degrees between -5 and +45

  • case (string) – either “BOL” for current best estimate at beginning of life, or “EOL” for more conservative prediction at end of life. The amplitude of the frill drift is roughly 2x lower for BOL (8.6 nm after 2 days) versus EOL (18.4 nm after 2 days).

gen_iec_series(delta_time, amplitude=3.5, period=5.0, interp_kind='linear', random_seed=None)[source]

Create a series of IEC WFE scale factors

Create a series of random IEC heater state changes based on arcsine distribution.

Parameters

delta_time (astropy.units quantity object array) – Time series of atropy units to interpolate IEC amplitudes

Keyword Arguments
  • amplitude (float) – Full amplitude of arcsine distribution. Values will range from -0.5*amplitude to +0.5*amplitude.

  • period (float) – Period in minutes of IEC oscillations. Usually 3-5 minutes.

  • random_seed (int) – Provide a random seed value between 0 and (2**32)-1 to generate reproducible random values.

  • interp_kind (str or int) – Specifies the kind of interpolation as a string (‘linear’, ‘nearest’, ‘zero’, ‘slinear’, ‘quadratic’, ‘cubic’, ‘previous’, ‘next’, where ‘zero’, ‘slinear’, ‘quadratic’ and ‘cubic’ refer to a spline interpolation of zeroth, first, second or third order; ‘previous’ and ‘next’ simply return the previous or next value of the point) or as an integer specifying the order of the spline interpolator to use. Default is ‘linear’.

gen_thermal_drift(delta_time, start_angle=- 5, end_angle=45, case='BOL')[source]

Thermal WFE drift scaling

Function to determine the factor to scale the delta OPD associated with OTE backplane thermal distortion. Returns the RMS WFE (nm) depending on time and slew angles.

Parameters
  • delta_time (astropy.units quantity object) – The time since a slew occurred.

  • start_angle (float) – The starting sun pitch angle, in degrees between -5 and +45

  • end_angle (float) – The ending sun pitch angle, in degrees between -5 and +45

  • case (string) – either “BOL” for current best estimate at beginning of life, or “EOL” for more conservative prediction at end of life. The amplitude of the frill drift is roughly 3x lower for BOL (13 nm after 14 days) versus EOL (43 nm after 14 days).

interp_dopds(delta_time, dopds, dt_new, wfe_dict=None, interp_kind='linear', **kwargs)[source]

Interpolate an array of delta OPDs Perform a linear interpolation on a series of delta OPDS. :param delta_time: An array of times assuming astropy units corresponding to each dopd. :type delta_time: astropy.units quantity object :param dopds: Array of delta OPD images associated with delta_time. :type dopds: ndarray :param dt_new: New array to interpolate onto. :type dt_new: astropy.units quantity object

Keyword Arguments
  • wfe_dict (dict or None) – If specified, then must provide a dictionary where the values for each keywords are the WFE drift components associated with each delta_time. Will then return a dictionary

  • interp_kind (str or int) – Specifies the kind of interpolation as a string (‘linear’, ‘nearest’, ‘zero’, ‘slinear’, ‘quadratic’, ‘cubic’, ‘previous’, ‘next’, where ‘zero’, ‘slinear’, ‘quadratic’ and ‘cubic’ refer to a spline interpolation of zeroth, first, second or third order; ‘previous’ and ‘next’ simply return the previous or next value of the point) or as an integer specifying the order of the spline interpolator to use. Default is ‘linear’.

opds_as_hdul(delta_time, slew_angles, delta_opds=None, wfe_dict=None, case=None, add_main_opd=True, slew_averages=False, return_ind=None, **kwargs)[source]

Convert series of delta OPDS to HDUList

reset(verbose=True)[source]

Reset an OPD to the state it was loaded from disk. i.e. undo all segment moves.

slew_pos_averages(delta_time, slew_angles, opds=None, wfe_dict=None, mn_func=<function mean>, interpolate=False, **kwargs)[source]

Get averages at each slew position Given a series of times and slew angles, calculate the average OPD and WFE RMS error within each slew angle position. Returns a tuple with new arrays of (dt_new, opds_new, wfe_dict_new).

If input both opds and wfe_dict are not specified, then we call the evolve_dopd function and return .

Parameters
  • delta_time (astropy.units quantity object) – An array of times assuming astropy units.

  • slew_angles (ndarray) – The sun pitch angles at each delta_time, in degrees between -5 and +45.

  • opds (ndarray or None) – Cube of OPD images (or delta OPDs) associated with each delta_time. If set to None, then a new set of OPDs are not calculated.

  • wfe_dict (dict or None) – If specified, then must provide a dictionary where the values for each keywords are the WFE drift components associated with each delta_time. New set of WFE dictionary is not calculated if set to None.

  • mn_func (function) – Function to use for taking averages. Default: np.mean()

  • interpolate (bool) – Instead of taking average, use the interpolation function self.interp_dopds().

Keyword Arguments
  • case (string) – Either “BOL” for current best estimate at beginning of life, or “EOL” for more conservative prediction at end of life.

  • do_thermal (bool) – Include thermal slew component? Mostly for debugging purposes.

  • do_frill (bool) – Include frill component? Mostly for debugging purposes.

  • do_iec (bool) – Include IEC component? Good to exclude if calling this function repeatedly for evolution of multiple slews, then add IEC later.

  • amplitude (float) – Full amplitude of IEC arcsine distribution. Values will range from -0.5*amplitude to +0.5*amplitude.

  • period (float) – Period in minutes of IEC oscillations. Usually 3-5 minutes.

  • kind (str or int) – Specifies the kind of interpolation (if specified) as a string. Default: ‘linear’.

slew_scaling(start_angle, end_angle)[source]

WFE scaling due to slew angle

Scale the WSS Hexike components based on slew pitch angles.

Parameters
  • start_angle (float) – The starting sun pitch angle, in degrees between -5 and +45

  • end_angle (float) – The ending sun pitch angle, in degrees between -5 and +45

pancake.opds.plot_im(im, fig, ax, vlim=None, add_cbar=True, return_ax=False, extent=None)[source]

Plot single image on some axes

pancake.opds.plot_opd(hdul, index=1, opd0=None, vlim1=None, vlim2=None)[source]

Plot OPDs images (full and delta)

pancake.pandeia_subclasses module

class pancake.pandeia_subclasses.CoronagraphyConvolvedSceneCube(scene, instrument, **kwargs)[source]

Bases: pandeia.engine.astro_spectrum.ConvolvedSceneCube

This class overrides the ConvolvedSceneCube class, and instead of using SPECTRAL_MAX_SAMPLES it looks for a wavelength size that should be present in the ‘scene’ part of the template

background=None, psf_library=None, webapp=False, empty_scene=False

class pancake.pandeia_subclasses.CoronagraphyDetectorSignal(observation, calc_config=<pandeia.engine.signal.CalculationConfig object>, **kwargs)[source]

Bases: pancake.pandeia_subclasses.CoronagraphyConvolvedSceneCube

Override the DetectorSignal to avoid odd issues with inheritance. Unfortunately this currently means copying the functions entirely (with changes to which class is used)

webapp=False, order=None, empty_scene=False

all_rates(flux, add_extended_background=False)[source]

Calculate rates in e-/s/pixel/micron or e-/s/pixel given a flux cube in mJy

Parameters
  • flux (ConvolvedSceneCube instance) – Convolved source flux cube with flux units in mJy

  • add_extended_background (bool (default=False)) – Toggle for including extended background not contained within the flux cube

Returns

products

Dict of products produced by rate calculation.

’wave_pix’ - Mapping of wavelength to detector pixels ‘ote’ - Source rate at the telescope aperture ‘fp’ - Source rate at the focal plane in e-/s/pixel/micron ‘fp_pix’ - Source rate per pixel ‘fp_pix_no_ipc’ - Source rate per pixel excluding effects if inter-pixel capacitance

Return type

dict

focal_plane_rate(rate, wave)[source]

Takes the output from self.ote_rate() and multiplies it by the components of efficiency within the system and returns the source rate at the focal plane in e-/s/pixel/micron.

get_bg_fp_rate()[source]

Calculate background in e-/s/pixel/micron at the focal plane. Also correct for any excess in predicted background if there are pupil losses in the PSF. (#2529)

get_bg_pix_rate()[source]

Calculate the background on the detector in e-/s/pixel

get_fp_rate()[source]

Return scene flux at the focal plane in e-/s/pixel/micron (excludes background)

get_pix_grid(rate)[source]

Generate the coordinate grid of the detector plane

get_projection_type()[source]
get_saturation_mask(rate=None)[source]

Compute a numpy array indicating pixels with full saturation (2), partial saturation (1) and no saturation (0).

Parameters

rate (None or 2D np.ndarray) – Detector plane rate image used to build saturation map from

Returns

mask – Saturation mask image

Return type

2D np.ndarray

get_wave_pix()[source]

Return the mapping of wavelengths to pixels on the detector plane

image_rate(rate)[source]

Calculate the electron rate for imaging modes by integrating along the wavelength direction of the cube.

Parameters

rate (numpy.ndarray) – Rate of photons interacting with detector as a function of model wavelength set

Returns

products – first element - electron rate per pixel second element - variance of electron rate per pixel

Return type

2-element tuple of numpy.ndarrays

ipc_convolve(rate, kernel)[source]
on_detector(rate_list)[source]

This will take the list of (pixel) rates and use them create a single detector frame. A single image will only have one rate in the list, but the IFUs will have n_slices. There may be other examples, such as different spectral orders for NIRISS. It is not yet clear how many different flavors there are, so this step may get refactored if it gets too complicated. Observing modes that only have one set of rates (imaging and single-slit spectroscopy, for instance) will still go through this, but the operation is trivial.

ote_rate(flux)[source]

Calculate source rate in e-/s/pixel/micron at the telescope entrance aperture given a flux cube in mJy/pixel.

slitless_rate(rate, add_extended_background=True)[source]

Calculate the detector rates for slitless modes. Here we retain all spatial information and build up the detector plane by shifting and coadding the frames from the convolved flux cube. Also need to handle and add background that comes from outside the flux cube, but needs to be accounted for.

Parameters
  • rate (3D numpy.ndarray) – Cube containing the flux rate at the focal plane

  • add_extended_background (bool (default: True)) – Toggle for including extended background not contained within the flux cube

Returns

products – wave_pix: 1D numpy.ndarray containing wavelength to pixel mapping on the detector plane spec_rate: 2D numpy.ndarray of detector count rates

Return type

2 entry tuple

spec_rate(rate)[source]

For slitted spectrographs, calculate the detector signal by integrating along the dispersion direction of the cube (which is masked by a, by assumption, narrow slit). For slitless systems or slits wider than the PSF, the slitless_rate method should be used to preserve spatial information within the slit.

Parameters

rate (numpy.ndarray) – Rate of photons interacting with detector as a function of model wavelength set

Returns

products – first element - map of pixel to wavelength second element - electron rate per pixel third element - variance of electron rate per pixel

Return type

3-element tuple of numpy.ndarrays

spectral_detector_transform()[source]

Create engine API format dict section containing properties of wavelength coordinates at the detector plane.

Returns

t

Return type

dict (engine API compliant keys)

wave_eff(rate)[source]
wcs_info()[source]

Get detector coordinate transform as a dict of WCS keyword/value pairs.

Returns

header – WCS header keys defining coordinate transform in the detector plane

Return type

dict

class pancake.pandeia_subclasses.CoronagraphyPSFLibrary(wavelength_range, path=None, psf_key='all')[source]

Bases: pandeia.engine.psf_library.PSFLibrary, object

Subclass of the Pandeia PSFLibrary class, intended to allow PSFs to be generated on-the-fly via webbpsf rather than using cached PSFs

associate_offset_to_source(sources, instrument, aperture_name)[source]

Added azimuth information for use with webbpsf. Pandeia currently does not calculate the PA and assumes azimuthal symmetry resulting in incorrect calculations when using the bar coronagraph.

static calc_psf(ins, wave, offset, oversample, pix_scale, fov_pixels, trim_fov_pixels=None)[source]

Following the treatment in pandeia_data/dev/make_psf.py to handle off-center PSFs for use as a kernel in later convolutions.

fov_pixels = {'fqpm1065': 81, 'fqpm1140': 81, 'fqpm1550': 81, 'lyot2300': 81, 'mask210r': 101, 'mask210rlw': 101, 'mask210rsw': 101, 'mask335r': 101, 'mask335rlw': 101, 'mask335rsw': 101, 'mask430r': 101, 'mask430rlw': 101, 'mask430rsw': 101, 'masklwb': 351, 'masklwblw': 351, 'masklwbsw': 351, 'maskswb': 351, 'maskswblw': 351, 'maskswbsw': 351}
static get_cached_psf(wave, instrument, aperture_name, oversample=None, source_offset=(0, 0), otf_options=None, full_aperture=None)[source]
get_pix_scale(instrument, aperture_name)[source]

Get PSF pixel scale for given instrument/aperture.

OVERRIDE Pandeia so as to make sure that the pixel scale comes out correctly.

get_psf(wave, instrument, aperture_name, oversample=None, source_offset=(0, 0), otf_options=None, full_aperture=None)[source]

Get PSF given wavelength, instrument, instrument aperture, and optionally source xy offset coordinates. Values are interpolated linearly between the two PSF library entries that bracket the given wavelength.

Parameters
  • wave (float) – Desired wavelength for the PSF

  • instrument (str) – Instrument name

  • aperture_name (str) – Name of the instrument aperture

Returns

psf – Dict containing the PSF and associated information

Return type

dict

get_pupil_throughput(wave, instrument, aperture_name)[source]

Intended for pandeia 1.2 compatibility.

image_mask = {'fqpm1065': 'FQPM1065', 'fqpm1140': 'FQPM1140', 'fqpm1550': 'FQPM1550', 'lyot2300': 'LYOT2300', 'mask210r': 'MASK210R', 'mask210rlw': 'MASK210R', 'mask210rsw': 'MASK210R', 'mask335r': 'MASK335R', 'mask335rlw': 'MASK335R', 'mask335rsw': 'MASK335R', 'mask430r': 'MASK430R', 'mask430rlw': 'MASK430R', 'mask430rsw': 'MASK430R', 'masklwb': 'MASKLWB', 'masklwblw': 'MASKLWB', 'masklwbsw': 'MASKLWB', 'maskswb': 'MASKSWB', 'maskswblw': 'MASKSWB', 'maskswbsw': 'MASKSWB'}
nircam_mode = {'fqpm1065': 'imaging', 'fqpm1140': 'imaging', 'fqpm1550': 'imaging', 'lyot2300': 'imaging', 'mask210r': 'sw_imaging', 'mask210rlw': 'lw_imaging', 'mask210rsw': 'sw_imaging', 'mask335r': 'lw_imaging', 'mask335rlw': 'lw_imaging', 'mask335rsw': 'sw_imaging', 'mask430r': 'lw_imaging', 'mask430rlw': 'lw_imaging', 'mask430rsw': 'sw_imaging', 'masklwb': 'lw_imaging', 'masklwblw': 'lw_imaging', 'masklwbsw': 'sw_imaging', 'maskswb': 'sw_imaging', 'maskswblw': 'lw_imaging', 'maskswbsw': 'sw_imaging'}
static parse_aperture(aperture_name)[source]

Return [image mask, pupil mask, fov_pixels, trim_fov_pixels, pixelscale]

pupil_mask = {'fqpm1065': 'MASKFQPM', 'fqpm1140': 'MASKFQPM', 'fqpm1550': 'MASKFQPM', 'lyot2300': 'MASKLYOT', 'mask210r': 'CIRCLYOT', 'mask210rlw': 'CIRCLYOT', 'mask210rsw': 'CIRCLYOT', 'mask335r': 'CIRCLYOT', 'mask335rlw': 'CIRCLYOT', 'mask335rsw': 'CIRCLYOT', 'mask430r': 'CIRCLYOT', 'mask430rlw': 'CIRCLYOT', 'mask430rsw': 'CIRCLYOT', 'masklwb': 'WEDGELYOT', 'masklwblw': 'WEDGELYOT', 'masklwbsw': 'WEDGELYOT', 'maskswb': 'WEDGELYOT', 'maskswblw': 'WEDGELYOT', 'maskswbsw': 'WEDGELYOT'}
trim_fov_pixels = {'fqpm1065': None, 'fqpm1140': None, 'fqpm1550': None, 'lyot2300': None, 'mask210r': None, 'mask210rlw': None, 'mask210rsw': None, 'mask335r': None, 'mask335rlw': None, 'mask335rsw': None, 'mask430r': None, 'mask430rlw': None, 'mask430rsw': None, 'masklwb': 101, 'masklwblw': 101, 'masklwbsw': 101, 'maskswb': 101, 'maskswblw': 101, 'maskswbsw': 101}
class pancake.pandeia_subclasses.SeparateTargetReferenceCoronagraphy(instrument, webapp=False, config={}, **kwargs)[source]

Bases: pandeia.engine.strategy.Coronagraphy

This class is intended to override the cronography behaviour of requiring that the reference source be included in the same calculation template as the observation source.

pancake.scene module

class pancake.scene.Scene(name=None, **kwargs)[source]

Bases: object

Scene class to mirror the construction of a typical Pandeia ‘Scene’, reinventing the wheel a little bit, but means that users don’t need to import pandeia in their main code and that aspects of data input can be streamlined.

add_source(name, kind='simbad', r=0.0, theta=0.0, verbose=True, **kwargs)[source]

Add a source to the Scene

Parameters
  • name (str) – Name of the source to be added

  • kind (str) – Kind of source to add, options are - ‘simbad’ for SIMBAD query of name string - ‘grid’ to use Pandeia Phoenix with ‘spt’, ‘norm_val’, ‘norm_unit’, ‘norm_bandpass’ passed as kwargs - ‘file’ to use input file, with ‘wave_unit’ and ‘flux_unit’ passed as kwargs

  • r (float) – Radial separation of source from center in arcseconds

  • theta (float) – PA of source, should be N->E counterclockwise

  • verbose (bool) – Print update statements to terminal

offset_scene(x, y)[source]

Offset scene in x, y space in arcseconds

Parameters
  • x (float) – x offset in arcseconds

  • y (float) – y offset in arcseconds

plot_scene(title='', newfig=True)[source]

Plot the scene and its sources spatially.

Parameters
  • title (str) – Title of plot

  • newfig (bool) – Start a new figure, default is True

plot_source_spectra(sources='all', title='', newfig=True, xlim=(0.5, 30), ylim=(0.001, None))[source]

Produce a plot of the spectra of sources within a scene.

Parameters
  • sources (str / list of strings) – List of source names, or ‘all’ to plot all source spectra

  • title (str) – Title of plot

  • newfig (bool) – Start a new figure, default is True

renormalise_source(source, norm_val=5, norm_unit='vegamag', norm_bandpass='2mass_ks')[source]

Renormalise a source already within a scene.

Parameters
  • source (str) – Name of source to renormalise

  • norm_val (float) – Value to renormalise to

  • norm_unit (str) – Unit to perform renormalisation to

  • norm_bandpass (str) – String for the bandpass we are normalising under, 2MASS, WISE or anything in synphot by default.

renormalize_source(*args, **kwargs)[source]
rotate_scene(theta, center=[0.0, 0.0], direction='counter_clockwise')[source]

Rotate scene given an angle in degrees

Parameters
  • theta (float) – Angular distance to rotate

  • center (list) – x and y coordinate to act as rotation center

  • direction (str) – Direction to perform rotation, ‘clockwise’ or ‘counter_clockwise’ default is counter clockwise.

source_magnitude(source, filt)[source]

Calculate the magnitude of particular source in a given filter

Parameters
  • source (str) – Name of source

  • filt (str) – Filter to calculate magnitude in

Returns

magnitude – Magnitude of object in apparent vegamag

Return type

float

pancake.scene.create_SGD(ta_error='none', fsm_error='default', stepsize=0.02, pattern_name=None, sim_num=0, instrument='nircam')[source]

Create small grid dither pointing set. There are two ways to specify dither patterns:

ta_error - add TA error to each point in the SGD?

stepsize - floating point value for a 3x3 grid.

pattern_name - string name of a pattern corresponding to

one of the named dither patterns in APT.

If you specify pattern_name, then stepsize is ignored.

See https://jwst-docs-stage.stsci.edu/display/JTI/NIRCam+Small-Grid+Dithers for information on the available dither patterns and their names.

Parameters
  • ta_error (str / int / float) – Target acquisition error - ‘saved’ to use a saved random seed of offsets - ‘random’ for a random error - int or float for random error with set amplitude in mas - ‘none’ for no error

  • fsm_error (str) – Options of ‘none’ for no error, or ‘default’ for 2e-3 mas

  • stepsize (float) – Manual step size for dither

  • pattern_name (str) – Default small grid dither pattern name

  • sim_num (int) – Specific simulation number / draw from a ‘saved’ ta_error

Returns

sgds – list of x, y offsets for each step in the dither pattern.

Return type

list

pancake.scene.get_fsm_error(error='default')[source]

2mas 1/sigma/axis error from the fine steering mirror

Parameters

error (str / float) – String of ‘default’ for 2e-3, ‘none’ for 0, or input float

Returns

Return type

x,y random error

pancake.scene.get_ta_error(instrument, error='default')[source]

7 mas 1-sigma/axis error

Parameters

error (str / float) – String of ‘default’ for 1e-3, or input float

Returns

Return type

x,y random error

pancake.sequence module

class pancake.sequence.Sequence(**kwargs)[source]

Bases: object

Sequence class used to construct an observational sequence from invidual specified observations of user defined scenes.

add_observation(scene, exposures, mode='coronagraphy', nircam_mask='default', nircam_subarray='default', miri_subarray='default', telescope='jwst', optimise_margin=0.05, optimize_margin=None, max_sat=0.95, rolls=None, nircam_sgd=None, miri_sgd=None, scale_exposures=None, verbose=True, min_groups=4, min_ints=1)[source]

Add observation does the heavy lifting, with a wide variety of input options.

Parameters
  • scene (pancake.Scene() object) – The scene we want to observe

  • exposures (list of tuples) – The exposures we want to perform, possible formats are - [(FILTER, PATTERN, NGROUP, NINT),…] - [(FILTER, ‘optimise’, t_exp),…] with t_exp in seconds

  • mode (str) – Observing mode, ‘coronagraphy’ is working, ‘imaging’ a future development.

  • nircam_mask (str) – The NIRCam coronagraphic mask to use, ‘default’ we use round masks

  • nircam_subarray (str) – NIRCam subarray to use, ‘default’ will use the one assigned to the chosen mask

  • miri_subaray (str) – MIRI subarray to use, ‘default’ will use the one assigned to the chosen mask

  • telescope (str) – Telescope to observe with, only ‘jwst’ is possible at this time.

  • optimise_margin (float) – Fraction of the input t_exp that we can deviate from the overall t_exp for a given exposure

  • optimize_margin (str / None) – For the Americans

  • max_sat (float) – Maximum fraction of saturation to reach when optimising

  • rolls (list of floats) – PA angles to observe scene at

  • nircam_sgd (str / None) – NIRCam small grid dither pattern to use, if any

  • miri_sgd (str / None) – MIRI small grid dither pattern to use, if any

  • scale_exposures (pancake.Scene()) – Scene to scale the provided t_exp in order to reach ~the same number of photons

  • verbose (bool) – Boolean toggle for terminal printing.

run(ta_error='saved', wavefront_evolution=True, on_the_fly_PSFs=False, wave_sampling=3, save_file=False, resume=False, verbose=True, cache='none', cache_path='default', offaxis_nircam=[1, 1], offaxis_miri=[1, 1], debug_verbose=False, initial_wavefront_realisation=4, wavefront_pa_range='median', background='default', roll_ta_error='default')[source]

Perform all simulations for the exposures defined within this sequence.

Parameters
  • ta_error (str / float) – Target acquisition errors - ‘saved’ to use a saved random seed of offsets - ‘random’ for a random error - int or float for random error with set amplitude in mas - ‘none’ for no error

  • wavefront_evolution (bool) – Whether to evolve the wavefront error throughout the observation, requires RA and Dec for at least one source within the scenes being observed.

  • on_the_fly_PSFs (bool) – Whehter to calculate PSF’s on the fly using WebbPSF (more accurate) or use the precomputed library (faster).

  • wave_sampling (int) – If on_the_fly_PSFs == True, sets the number of wavelengths to be sampled in each filter

  • save_file (str) – File name to save simulations to

  • resume (bool) – Toggle to resume an interrupted run under the same save_file path

  • verbose (bool) – Toggle for printing statments to terminal

  • cache (str) – Type of cache to use when generating PSFs, options are - ‘none’ for no caching - ‘ram’ for LRU ram caching - ‘disk’ for hard drive caching

  • cache_path (str) – Directory path to save / load cached PSFs under ‘disk’ caching

  • offaxis_nircam (list) – x, y coordinates in arcseconds for NIRCam offaxis PSF calculations

  • offaxis_miri (list) – x, y coordinates in arcseconds for MIRI offaxis PSF calculations

  • debug_verbose (bool) – Toggle printing of debug statements, toggled off by default as they flood the terminal and do no impact anything.

  • initial_wavefront_realisation (int, 1-10) – 10 possible wavefronts to use to start a simulation, doesn’t greatly impact results

  • wavefront_pa_range (str) – What range of PA’s to aim for when calculating movement of telescope between scenes - options are, ‘median’, ‘minimum’, ‘maximum’

Returns

hdulist – All simulations as a FITS HDUlist dataset

Return type

FITS HDUList()

pancake.sequence.load_run(save_file)[source]

Load a previously performed / incomplete PanCAKE simulation run.

Parameters

save_file (str) – File path for the saved simulation.

Returns

hdul – Extracted file in HDUList format.

Return type

FITS HDUList

pancake.transformations module

pancake.transformations.affine_transform(theta, center)[source]

Compute rotation matrix to apply to x, y, z coordinates

Parameters
  • theta (float) – Rotation in degrees

  • center (list of floats) – Location of x, y rotation center

pancake.transformations.align_fourierLSQ(reference, target, mask=None)[source]

LSQ optimization with Fourier shift alignment

Parameters
  • reference (nd array) – N x K image to be aligned to

  • target (nd array) – N x K image to align to reference

  • mask (nd array, optional) – N x K image indicating pixels to ignore when performing the minimization. The masks acts as a weighting function in performing the fit.

Returns

results – [x, y, beta] values from LSQ optimization, where (x, y) are the misalignment of target from reference and beta is the fraction by which the target intensity must be reduced to match the intensity of the reference.

Return type

list

pancake.transformations.cart_to_polar(xy)[source]

Convert xy separations into offset, theta

Parameters

xy (list of floats) – X and Y separation in arcsec

Returns

  • r (float) – radius offset in arcsec

  • theta (float) – angular position, degrees

pancake.transformations.fourier_imshift(image, xshift, yshift)[source]

Shift an image by use of Fourier shift theorem

Parameters
  • image (nd array) – N x K image

  • xshift (float) – Pixel value by which to shift image in the x direction

  • yshift (float) – Pixel value by which to shift image in the y direction

Returns

offset – Shifted image

Return type

nd array

pancake.transformations.polar_to_cart(r, theta)[source]

Convert from polar to cartesian, assuming theta in degrees

Parameters
  • r (float) – radius offset in arcsec

  • theta (float) – angular position, degrees

Returns

xy – X and Y separation in arcsec

Return type

list of floats

pancake.transformations.rotate(xy, theta, center)[source]

Perform rotation of xy coordinates

Parameters
  • xy (list of floats) – X and Y separation in arcsec

  • theta (float) – angular position, degrees

  • center (list of floats) – Location of x, y rotation center

Returns

Return type

list of floats for new rotated x and y

pancake.transformations.shift_subtract(params, reference, target, mask=None)[source]

Use Fourier Shift theorem for subpixel shifts.

Parameters
  • params (tuple) – xshift, yshift, beta

  • reference (nd array) – See align_fourierLSQ

  • target (nd array) – See align_fourierLSQ

  • mask (nd array, optional) – See align_fourierLSQ

Returns

  • 1D nd array of target-reference residual after

  • applying shift and intensity fraction.

pancake.utilities module

This file contains a number of pancake utilities which may be useful in running pancake.

pancake.utilities.compute_magnitude(spectrum_wave, spectrum_flux, filt, wave_unit='micron', flux_unit='mJy')[source]

Calculate the magnitude of a spectrum in a given filter.

Parameters
  • spectrum_wave (synphot wavelengths) – Wavelengths

  • spectrum_flux (synphot fluxes) – Flux values in mJy

  • filt (str) – Filter / bandpass to use

  • wave_unit (str) – Unit of spectrum wave axis

  • flux_unit (str) – Unit of spectrum flux axis

Returns

magnitude – Vega magnitude in provided filter.

Return type

float

pancake.utilities.convert_spt_to_pandeia(raw_spectral_type)[source]

Function to take a spectral type string, either from Simbad or directly from the user, and return an approximation that Pandeia can use. If the spectral type string cannot be understood, then the spectral type will be assumed as A0V.

Makes use of a lot of if statements, perhaps someone smarter could streamline this at a later date.

Parameters

raw_spectral_type (str) – Spectral type to convert to Pandeia compatability.

Returns

pandeia_spectral_type – Pandeia compatible spectral type

Return type

str

pancake.utilities.determine_pandeia_offset(config)[source]

Uses Pandeia’s PSF library to determine which PSF offset pandeia would use for a particular configuration (for comparison with the offset that pancake would use in on-the-fly PSF generation).

Parameters

config (dict) – Pandeia dictionary for the observation

Returns

- – Dictionary of ‘scene’ and ‘reference’ offsets.

Return type

dict

pancake.utilities.equatorial_to_ecliptic(ra, dec, form=None, verbose=False)[source]

Function to covert equatorial RA and Dec into the ecliptic longitude and latitude.

Parameters
  • ra (float) – Right ascension

  • dec (float) – Declination

  • form (str) – Format of values, ‘degrees’ or anything else for radians.

  • verbose (bool) – Print information to terminal

Returns

  • lamb (float) – Ecliptic longtiude

  • beta (float) – Ecliptic latitude

pancake.utilities.normalise_spectrum(input_wave, input_flux, norm_val=5, norm_unit='vegamag', norm_bandpass='2mass_ks')[source]

Normalise a spectrum to a given bandpass

Parameters
  • input_wave (synphot wavelengths) – Wavelengths

  • input_flux (synphot fluxes) – Flux values in mJy

  • norm_val (float) – Value to normalise to

  • norm_unit (str) – Unit for normalisation value

  • norm_bandpass (str) – Bandpass to normalise in

Returns

  • spectrum.wave (pysynphot spectrum wavelength axis)

  • spectrum.flux (pysynphot spectrum wavelength axis)

pancake.utilities.normalize_spectrum(*args, **kwargs)[source]
pancake.utilities.optimise_readout(obs_dict, t_exp, optimise_margin, min_sat=1e-06, max_sat=1, min_groups=4, min_ints=1)[source]

Function to estimate optimal readout parameters for a given observation based on an input exposure time.

Parameters
  • obs_dict (dict) – Pandeia dictionary for this observation

  • t_exp (float) – Desired exposure time in seconds

  • optimise_margin (float) – Fraction of t_exp “wiggle-room” in estimating optimal readout

  • min_sat (float) – Minimum allowable fraction of saturation

  • max_sat (float) – Maximum allowable fraction of saturation

Returns

  • pattern (str) – Optimal readout pattern

  • groups (int) – Optimal number of groups

  • integrations (int) – Optimal number of integrations

pancake.utilities.optimize_readout(*args, **kwargs)[source]
pancake.utilities.pandeia_spectrum(stellar_type)[source]

Generate a spectrum using the Pandeia Phoenix data files. Returns two arrays containing the wavelength and flux values, unormalised.

Parameters

stellar_type (str) – Spectral type of star

Returns

  • spectrum.wave (pysynphot spectrum wavelength axis)

  • spectrum.flux (pysynphot spectrum wavelength axis)

pancake.utilities.query_simbad(query_string, query_timeout_sec=5.0, default_spt='a0v', verbose=True)[source]

Query simbad for details on a target object, adapted from the JWST Coronagraphic Visibility Tool Will in current state attempt to extract: RA, Dec, Spectral Type and Kmagnitude

Parameters
  • query_string (str) – String to query in SIMBAD, i.e. a stellar name / identifier.

  • query_timeout_sec (float) – Time to allow for query to complete

  • default_spt (str) – Default spectral type to adopt if SIMBAD spectral type cannot be interpreted

  • verbose (bool) – Whether to print information to the terminal

Returns

query_results – Extracted SIMBAD results.

Return type

dict

pancake.utilities.stellar_spectrum(stellar_type, bandpass, magnitude)[source]

Create a spectrum dictionary that assumes a Phoenix model with a key found in pandeia, and set the magnitude to the provided value in the provided bandpass (in ABMAG)

Parameters
  • stellar_type (str) – Spectral type of star

  • bandpass (str) – Bandpass for normalisation

  • magnitude (float) – Vega magnitude in aforementioned bandpass

Returns

spectrum – Spectrum parameters for input into Pandeia

Return type

dict

pancake.utilities.user_spectrum(filename, wave_unit='micron', flux_unit='mJy')[source]

Read in a user spectrum from a specified file.

Parameters
  • filename (str) – Filepath for user spectrum file

  • wave_unit (str) – Unit for wavelength axis (column 1)

  • flux_unit (str) – Unit for flux axis (column 2)

Returns

  • spectrum.wave (pysynphot spectrum wavelength axis)

  • spectrum.flux (pysynphot spectrum wavelength axis)