corgisim package

Subpackages

Submodules

corgisim.convolution module

corgisim.inputs module

class corgisim.inputs.Input(**kwargs)

Bases: object

A class that holds all the information necessary for a simulation.

Input can be created without arguments (default values will be used), with individual arguments or with dictionnaries for host star, proper keywords and emccd keywords

Attribute Access:
  • All attributes are made read-only after initialization.

  • Accessing an attribute (e.g., input.source_x_offset) will retrieve the corresponding internal value (e.g., _source_x_offset).

Raises:

AttributeError: If an attempt is made to modify any attribute after initialization.

corgisim.inputs.create_variation_input(old_input, **kwargs)

This function creates a new input which is identical to the old input except for the specified keywords. This allows for easily creating variations of a simulation input without modifying the original object.

Args:
**kwargs: Keyword arguments representing the attributes to be

overwritten in the new Input object.

Returns:
corgisim.inputs.Input: A new Input object with the specified

variations.

Raises:
NameError: If an unknown keyword argument is provided that is not a

valid attribute of the Input class.

corgisim.inputs.load_cpgs_data(filepath, return_input=False)

Creates a scene and optics based on the content of a CPGS file.

This function parses the CPGS file to extract simulation parameters for target and, if present, reference stars, along with visit-specific details.

Args:

filepath (str): Path to the input CPGS XML file. return_input (bool, optional): If True, an Input object populated with CPGS data

will be returned instead of the scene, optics, and detector objects. Defaults to False.

Returns:
tuple or corgisim.inputs.Input:
If “return_input” is False (default):
A tuple containing:
If “return_input” is True:
Raises:
  • FileNotFoundError: If the specified filepath does not exist.

  • xml.etree.ElementTree.ParseError: If the file at filepath is not a valid XML file.

  • Exception: For unsupported target IDs or other parsing issues within the CPGS structure.

  • NotImplementedError: If a specific configuration (e.g., polarization, filter, coronagraph mask) from the CPGS file is not yet implemented in the simulation.

corgisim.instrument module

class corgisim.instrument.CorgiDetector(emccd_keywords, photon_counting=True)

Bases: object

define_EMCCD(emccd_keywords=None)

Create and configure an EMCCD detector object with optional CTI simulation.

This method initializes an EMCCD detector object using the provided parameters. Optionally, if CTI (Charge Transfer Inefficiency) simulation is required, it updates the detector object using a trap model.

Args:
  • # default values match requirements, except QE, which is year 0 curve (already accounted for in counts)

  • em_gain (float, optional): EM gain, default 1000.

  • full_well_image (float, optional): image full well; 50K is requirement, 60K is CBE

  • full_well_serial (float, optional): full well for serial register; 90K is requirement, 100K is CBE

  • dark_rate (float, optional): Dark current rate, e-/pix/s; 1.0 is requirement, 0.00042/0.00056 is CBE for 0/5 years

  • cic_noise (float, optional): Clock-induced charge noise, e-/pix/frame; Defaults to 0.01.

  • read_noise (float, optional): Read noise, e-/pix/frame; 125 is requirement, 100 is CBE

  • bias (int, optional): Bias level (in digital numbers). Defaults to 0.

  • qe (float): Quantum efficiency, set to 1 here, because already counted in counts

  • cr_rate (int, optional): Cosmic ray event rate, hits/cm^2/s (0 for none, 5 for L2)

  • pixel_pitch (float, optional): Pixel pitch (in meters). Defaults to 13e-6.

  • e_per_dn (float, optional): post-multiplied electrons per data unit

  • numel_gain_register (int, optional): Number of elements in the gain register. Defaults to 604.

  • nbits (int, optional): Number of bits in the analog-to-digital converter. Defaults to 14.

  • use_traps (bool, optional): Flag indicating whether to simulate CTI effects using trap models. Defaults to False.

  • date4traps (float, optional): Decimal year of observation; only applicable if use_traps is True. Defaults to 2028.0.

Returns:
  • emccd (EMCCDDetectBase): A configured EMCCD detector object. If use_traps is True, the detector’s CTI is updated using the corresponding trap model.

generate_detector_image(simulated_scene, exptime, full_frame=False, loc_x=512, loc_y=512)

Function that generates a detector image from the input image, using emccd_detect.

The input_image probably has to be in electrons.

Arguments:
  • simulated_scene: a corgisim.scene.SimulatedScen object that contains the noise-free scene from CorgiOptics

  • full_frame: if generated full_frame image in detetor

  • loc_x (int): The horizontal coordinate (in pixels) of the center where the sub_frame will be inserted, needed when full_frame=True, and image from CorgiOptics has size is smaller than 1024×1024

  • loc_y (int): The vertical coordinate (in pixels) of the center where the sub_frame will be inserted, needed when full_frame=True, and image from CorgiOptics has size is smaller than 1024×1024

  • exptime: exptime in second

Returns:
  • A corgisim.scene.SimulatedImage object that contains the detector image in the

place_scene_on_detector(sub_frame, loc_x, loc_y)

Place the simulated scene onto the detector centered at a specified point.

This method inserts a sub-frame (the simulated scene) into a larger 1024x1024 detector array, where the (loc_x, loc_y) coordinates represent the center of the sub_frame in the detector’s coordinate system. The rest of the detector frame is padded with zeros. The resulting image is used later to generate an astropy HDU with associated metadata via the emccd_detect function.

Note:

This function is an intermediate step in the simulation pipeline and is generally not modified by end users.

Args:
  • sub_frame (numpy.ndarray): A 2D array representing the simulated scene to be placed on the detector.

  • loc_x (int): The horizontal coordinate (in pixels) of the center where the sub_frame will be inserted.

  • loc_y (int): The vertical coordinate (in pixels) of the center where the sub_frame will be inserted.

Returns:
  • numpy.ndarray: A 1024x1024 2D array (detector frame) with the sub_frame placed at the specified center location and the remaining areas padded with zeros.

Raises:
  • ValueError: If the sub_frame, when placed at the specified location, exceeds the bounds of the 1024x1024 detector array or if negative indices result.

class corgisim.instrument.CorgiOptics(cgi_mode=None, bandpass=None, diam=236.3114, optics_keywords=None, roll_angle=0, satspot_keywords=None, stellar_diam_and_jitter_keywords=None, oversampling_factor=7, return_oversample=False, **kwargs)

Bases: object

A class that defines the current configuration of the CGI optics, including the telescope and the coronagraph.

It should include basically everything about the instrument configuration.

Will likely be fairly similar to Jorge’s corgisims_core class.

It will need to know the telescope roll angle.

add_satspot(satspot_keywords)

Add satellite spots to deformable mirror (DM) settings. This function modifies the deformable mirror settings stored in self.optics_keywords[‘dm1_v’] by injecting satellite spots according to the provided satspot_keywords.

Parameters:

satspot_keywordsdict

Dictionary specifying the parameters needed to define and inject satellite spots (sep_lamD, angle_deg, contrast, wavelength_m).

Returns:

dm1_cos_added2D ndarray

Updated DM1 voltage map with satellite spots added.

construct_image_array(grid_dim_out_tem, images_tem, obs)

Function that constucts an appropriately sized array depending on the coronagraph mode and whether the wollaston is used

Inputs:

grid_dim_out_tem: temporary size of the fields output by proper images_tem: temporary images that still need to be integrated

over the pixel size (binned down)

obs: observed stellar spectrum within the defined bandpass

Outputs:

image: array containing the image at the final resolution

construct_jittered_image_from_fields(fields)

This function uses the onaxis electric field and the library of offset electric fields and their weights to determine the intensity that incorporates the effects of jitter and/or finite stellar diameter. Inputs:

fields: onaxis electric fields as returned by proper

Outputs:

images_temp: Temporary images

convolve_2D_scene(scene, on_the_fly=False)

Function that simulates a 2D scene with the current configuration of CGI.

It should take the image data from the HDU from scene.background_scene and convolve it with a set of off-axis PSFs (also known as PRFs in some circles), and return an updated scene object with the background_scene attribute populated with an astropy HDU that contains the simulated scene and associated metadata in the header.

The off-axis PSFs should be either generated on the fly, or read in from a set of pre-generated PSFs. The convolution should be flux conserving.

TODO: Figure out the default output units. Current candidate is photoelectrons/s. TODO: If the input is a scene.Simulation_Scene instead, then just pull the Scene from the attribute

and put the output of this function into the twoD_image attribute

Arguments:
  • scene: A corgisim.scene.Scene object that contains the scene to be simulated.

  • on_the_fly: A boolean that defines whether the PSFs should be generated on the fly.

Returns:
  • corgisim.scene.Simulated_Scene: A scene object with the background_scene attribute populated with an astropy

    HDU that contains the simulated scene.

generate_full_aberration_psf(optics_keywords, is_offaxis_source=False)

Calls proper.prop_run_multi() with polaxis set to -2, 2, -1, and 1 in order to obtain fields with polarization aberrations describing -45->Y, 45->Y, -45->X, and 45->X, incoherently average those four fields to obtain an intensity image containing the full polarization aberration information

Arguments:

optics_keywords: A dictionary with the keywords that are used to set up the proper model is_offaxis_source: An optional Boolean specifying whether the PSF calculation is for an offaxis source or not

Returns:

images_tem: 3D datacube containing the PSFs sampled at various wavelengths in the pass band

get_e_field(resizing=True)

Function that only returns the e fields Set resizing = False to return the electric fields as they are output by proper.prop_run_multi.

Returns:
  • fields: an array that contains the field

get_host_star_psf(input_scene, sim_scene=None, on_the_fly=False)

Function that provides an on-axis PSF for the current configuration of CGI.

It should take the host star properties from scene.host_star_properties and return a Simulated_scene object with the host_star_image attribute populated with an astropy HDU that contains a noiseless on-axis PSF, and associated metadata in the header. This on-axis PSF should be either generated on the fly, or picked from a pregenerated library (e.g. OS11 or something cached locally).

#Todo Figure out the default output units. Current candidate is photoelectrons/s. #Todo: If the input is a scene.Simulation_Scene instead, then just pull the Scene from the attribute

and put the output of this function into the host_star_image attribute.

Arguments: input_scene: A corgisim.scene.Scene object that contains the scene to be simulated. on_the_fly: A boolean that defines whether the PSF should be generated on the fly.

Returns: corgisim.scene.Simulated_Scene: A scene object with the host_star_image attribute populated with an astropy

HDU that contains a noiseless on-axis PSF.

inject_point_sources(input_scene, sim_scene=None, on_the_fly=False)

Function that injects point sources into the scene.

It should take the input scene and inject the point sources defined scene.point_source_list, which should give the location and brightness.

The off-axis PSFs should be either generated on the fly, or read in from a set of pre-generated PSFs.

TODO: Figure out the default output units. Current candidate is photoelectrons/s. TODO: We may want this to generate “far away” point sources whose diffraction spikes still

end up in our scene. We’ll only want to simulate the part of the scene that ends up on the detector. How do we do that with corgisim/proper?

TODO: If the input is a scene.Simulation_Scene instead, then just pull the Scene from the attribute

and put the output of this function into the point_source_image attribute

Arguments:
  • scene: A corgisim.scene.Scene object that contains the scene to be simulated.

  • sim_scene: A corgisim.SimulatedImage object to contains the simulated scene.

  • on_the_fly: A boolean that defines whether the PSFs should be generated on the fly.

Returns:
  • A 2D numpy array that contains the scene with the injected point sources.

setup_bandpass(cgimode, bandpass_name, nd)

Sets up the bandpass for the simulation.

This function initializes a bandpass based on the given parameters, computes wavelength boundaries, and retrieves throughput data.

Args:
  • cgimode (str): The CGI mode to be used.

  • bandpass_name (str): Name of the bandpass filter.

  • nd (int): Neutral density filter index.

Returns:
  • bp (SpectralElement): A spectral element object containing the bandpass data.

corgisim.instrument.skycoord_to_excamcoord(dra, ddec, roll_angle)

Convert sky coordinates to EXCAM coordinates. These are both relative astrometry of a companion relative to host star (or central of the frame)

Args:

dra (float): The right ascension offset in mas. ddec (float): The declination offset in mas. roll_angle (float): The roll angle in degrees.

Returns:

dx (float): The converted EXCAM x-coordinate offset in mas. dy (float): The converted EXCAM y-coordinate offset in mas.

corgisim.jitter module

corgisim.jitter.Determine_offsets_and_areas(outer_radius_of_offset_circle, N_rings_of_offsets, N_offsets_per_ring, starting_offset_ang_by_ring, r_ring0=0.075, dr_rings=0)

This function determines the set of offsets and the area of the region associated with each offset. The region area is normalized to the area of the full circle. Inputs:

outer_radius_of_offset_circle: The outer radius of the circle

containing all of the offsets and their corresponding regions. This radius is equal to the outer radii of the regions in the outermost ring.

N_rings_of_offsets: The number of rings of offsets, not counting

the zeroth ring that consists of the offset at (0,0) and its region.

N_offsets_per_ring: The number of offsets in each ring.

To use different number of offsets in different rings, define N_offsets_per_ring as an array with one entry per ring.

starting_offset_ang_by_ring: The angle (in DEGREES) of the first

offset in the ring. To use a different angle for different rings, define starting_offset_ang_by_ring as an array with one entry per ring.

r_ring0: The radius of the region corresponding to the offset

at the center of the circle (0,0). Defaults to 0.075.

dr_rings: The width for each ring of regions, not including the

central region (whose width is specified by r_ring0). To assign specific widths, define dr_rings as an array with one entry per ring. If left unspecified, the same width will be applied to each ring beyond the 0th. Note that the sum of all the entries in dr_rings plus r_ring0 must equal outer_radius_of_offset_circle.

Outputs:
x_offsets: A dictionary containing the x coordinates for each

offset in each ring

y_offsets: A dictionary containing the y coordinates for each

offset in each ring

A_offsets: A dictionary containing the area of each offset in

each ring

x_outer_dict: A dictionary containing a set of x coordinates for

the outer circle defining each ring (useful for plotting)

yu_outer_dict: A dictionary containing a set of y coordinates for

the upper half of the outer circle defining each ring (useful for plotting)

yl_outer_dict: A dictionary containing a set of y coordinates for

the lower half of the outer circle defining each ring (useful for plotting)

boundary coords_dict: A dictionary containing the coordinates that

specify the boundaries between regions in the same ring

corgisim.jitter.Determine_ring_params(r_ring_inner, dr_ring, regnum_ring, theta_ring_centers_start)

This function returns all of the desired parameters for a ring of regions. These are: the locations of the region centers (the jitter offsets)

the coordinates needed to plot the region outlines (outer ring plus radial boundaries)

Inputs:

r_ring_inner: radius of the inner ring boundary dr_ring: with of the ring regnum_ring: number of regions within the ring theta_ring_centers_start: angle of the center of the first region

IN DEGREES

Outputs:

x_ring_centers: x coordinates of the region centers y_ring_centers: y coordinates of the region centers r_ring_centers: radius of the region centers r_ring_outer: radius of the outer ring defining the regions x_ring_outer: x coordinates for points along the outer circle

defining the regions

yu_ring_outer: y coordinates for points along the upper half of

the circle defining the outer boundary of the regions

yl_ring_outer: y coordinates for points along the lower half of

the circle defining the outer boundar of the regions

boundary_coords: coordinates defining the boundaries between

adjacent regions

corgisim.jitter.Find_ycircle(r, x, xc, yc, half)

This function calculates the y coordinate that corresponds to the specified x coordinate, with half determining whether the “upper” or “lower” half of the circle is being considered. This function is capable of handling vector inputs, and it returns 0 in situations where x does not correspond to a point on the circle.

Inputs:

r: radius of the circle x: x coordinate(s) of the desired point(s) xc: x coordinate of the circle center yc: y coordinate of the circle center half: string specifying which half of the circle to use

Can be ‘u’, ‘U’, ‘t’, or ‘T’ for the upper/top half or

‘l’, ‘L’, ‘b,’ or ‘B’ for the lower/bottom half.

Output:

y: the y coordinate for each point

corgisim.jitter.Plot_ALL_Offsets_And_Region_Outlines(x_offsets, y_offsets, x_outer_dict, yu_outer_dict, yl_outer_dict, boundary_coords_dict, N_rings_of_offsets, N_offsets_per_ring)

This function iteratively uses Plot_Offsets_And_Region_Outlines to plot all of the offsets and their corresponding regions. Inputs:

x_offsets: A dictionary containing the x coordinates for each

offset in each ring

y_offsets: A dictionary containing the y coordinates for each

offset in each ring

x_outer_dict: A dictionary containing a set of x coordinates for

the outer circle defining each ring of regions

yu_outer_dict: A dictionary containing a set of y coordinates for

the upper half of the outer circle defining each ring of regions

yl_outer_dict: A dictionary containing a set of y coordinates for

the lower half of the outer circle defining each ring of regions

boundary_coords_dict: A dictionary containing the coordinates that

specify the boundaries between regions in the same ring

N_rings_of_offsets: The number of rings of offsets, not counting

the zeroth ring that consists of the offset at (0,0) and its region.

N_offsets_per_ring: The number of offsets in each ring.

Output:

A plot of all of the offsets and their corresponding regions

corgisim.jitter.Plot_Offsets_And_Region_Outlines(x_ring_centers, y_ring_centers, x_ring_outer, yu_ring_outer, yl_ring_outer, boundary_coords, regnum_ring, fig, ax)

This function plots a ring of offsets and their region outlines Inputs:

x_ring_centers: x coordinates of the centers of the regions y_ring_centers: y coordinates of the centers of the regions x_ring_outer: x coordinates for points along the outer circle

that defines the regions in the ring

yu_ring_outer: y coordinates for points along the upper half of

the circle that defines the regions in the ring

yl_ring_outer: y coordinates for points along the lower half of

the circle that defines the regions in the ring

boundary_coords: coordinates that define the boundaries between

adjacent regions in the ring

regnum_ring: number of regions in the ring fig: the figure that will contain the result ax: the figure axes

Output:

a plot of the ring of offsets and outlines of their regions

NOTE: This function does not initialize the plot window or show the plot.

It is expected that the plot window will be set up before this function is called (because this will allow all of the rings to be drawn on the same plot).

corgisim.jitter.Polar_in_rad_to_Cartesian_coords(r, theta)

This function converts from polar to Cartesian coordinates. Inputs:

r: radius theta: angle

Outputs:

x: Cartesian coordinate along the horizontal axis y: Cartesian coordinate along the vertical axis

corgisim.jitter.Region_Area(r_inner, r_outer, theta)

This function calculates the area of a region specified by its inner and outer radii and its wedge angle (in DEGREES).

corgisim.jitter.build_delta_e_field_library(stellar_diam_and_jitter_keywords, optics, input_scene)

This function builds a list of offset sources, the area of the region represented by each offset, and the weight for each offset; calculates the electric field for each offset; and saves a library of delta electric fields for use in calculating the effects of jitter or finite stellar diameter.

Inputs:
stellar_diam_and_jitter_keywords: A dictionary containing the necessary information

for the jitter and finite stellar diameter calculations

optics: a CorgiOptics object that defines the configuration of the CGI optics input_scene: a corgisim.scene.Scene object that contains the scene to be simulated

Outputs:
stellar_diam_and_jitter_keywords, updated to include the offsets, the areas of the

regions represented by the offsets, and the delta electric fields in offset_field_data

corgisim.jitter.calculate_weights_for_jitter_and_finite_stellar_diameter(stellar_diam_and_jitter_keywords)

This function calculates the set of weights to use when combining the intensities of the offset sources to add the effects of jitter and the finite stellar diameter

Inputs:
stellar_diam_and_jitter_keywords: A dictionary containing the necessary information

for the jitter and finite stellar diameter calculations

Outputs:

stellar_diam_and_jitter_keywords, updated to include the weights in offset_field_data

corgisim.jitter.load_predefined_jitter_and_stellar_diam_params(quicktest=False, mintest=False, stellar_diam_mas=0)

This function loads a predefined set of parameters for running Determine_offsets_and_areas. Otherwise, the example will match the one given in John Krist’s paper.

Inputs:
quicktest: A Boolean that specifies whether to use the full example

offset distribution (quicktest=False) or a smaller subset that runs more quickly (quicktest=True)

mintest: A Boolean that specifies whether to use a very minimal

subset of the offset distribution. Used instead of quicktest.

Outputs:
stellar_diam_and_jitter_keywords: A dictionary containing all of the

keywords necessary for running the jitter and finite stellar diameter calculations

corgisim.jitter.radial_boundaries(theta_start, theta_num)

This function determines the radial boundaries of the regions along a ring. Inputs:

theta_start: starting angle in degrees theta_num: number of regions in the ring

Outputs:

theta_boundaries: the angles defining the region boundaries

corgisim.jitter.region_centers(theta_start_deg, theta_num)

This function determines the centers of the regions in an annular ring. Inputs:

theta_start: starting angle in degrees theta_num: number of regions in the ring

Outputs:

theta: an array of angles locating the centers

corgisim.jitter.save_offsets_and_areas(x_offsets, y_offsets, A_offsets, N_rings_of_offsets)

This function saves the coordinates of the offset sources and the areas of the regions they represent. Inputs:

x_offsets: A dictionary containing the x coordinates for each

offset in each ring

y_offsets: A dictionary containing the y coordinates for each

offset in each ring

A_offsets: A dictionary containing the area of each region for

each offset in each ring

N_rings_of_offsets: Number of rings of offset sources not

counting the onaxis source (the zeroth ring)

Outputs:

a text file containing the offsets and areas

corgisim.jitter.setup_stellar_diam_and_jitter(optics, stellar_diam_and_jitter_keywords)

This function checks that finite stellar diameter and jitter have been implemented for the selected mode, that the required keys have been provided, and that the provided information is usable.

corgisim.observation module

corgisim.observation.generate_observation_scenario_from_cpgs(filepath, save_as_fits=False, output_dir=None, full_frame=False, loc_x=None, loc_y=None, point_source_info=None)

Generates an observation scenario by loading instrument, scene, and visit information from a CPGS file.

This function attempts to load both target and reference star information. If only target information is available, it proceeds with that.

Args:
  • filepath (str): The path to the CPGS XML file.

  • loc_x (int): The horizontal coordinate (in pixels) of the center where the sub_frame will be inserted, needed when full_frame=True, and image from CorgiOptics has size is smaller than 1024×1024

  • loc_y (int): The vertical coordinate (in pixels) of the center where the sub_frame will be inserted, needed when full_frame=True, and image from CorgiOptics has size is smaller than 1024×1024

  • point_sources_info (list): A list of dictionaries, each representing an off-axis point source in the scene.

Returns:
  • list[corgisim.scene.SimulatedImage]: A list of SimulatedImage objects, representing the complete observation scenario across all visits defined in the CPGS file.

corgisim.observation.generate_observation_sequence(scene, optics, detector, exp_time, n_frames, save_as_fits=False, output_dir=None, full_frame=False, loc_x=None, loc_y=None)

Generates a sequence of simulated observations and places them on a detector.

This function orchestrates the simulation of a given astrophysical scene through the instrument optics and then onto the detector. It first generates the host star’s PSF, then injects any defined off-axis point sources into the simulated scene. Finally, it uses the detector model to create a detector image, optionally generating either a sub-array or a full-frame image for each exposure. Each observation sequence corresponds to a single visit at a specific roll angle.

Args:
scene (corgisim.scene.Scene): The scene object containing information about

the host star and any specified point sources.

optics (corgisim.instrument.CorgiOptics): The optics object defining the

instrument configuration, including the telescope and coronagraph.

detector (corgisim.instrument.CorgiDetector): The detector object defining

the detector characteristics and noise properties.

exp_time (float): The exposure time for each individual frame in seconds. n_frames (int): The total number of frames to generate in this observation sequence. full_frame (bool, optional): If True, a full-frame detector image will be generated.

If False (default), a sub-array image is generated.

loc_x (int, optional): The x-coordinate for the center of the sub-array in pixels

if full_frame is False. If full_frame is True, this specifies the x-coordinate of the full frame’s origin (top-left pixel). Required if full_frame is True.

loc_y (int, optional): The y-coordinate for the center of the sub-array in pixels

if full_frame is False. If full_frame is True, this specifies the y-coordinate of the full frame’s origin (top-left pixel). Required if full_frame is True.

Returns:

list[corgisim.scene.SimulatedImage]: A list of corgisim.scene.SimulatedImage objects, where each object represents a single generated observation frame with its image data and associated FITS header information.

corgisim.outputs module

corgisim.outputs.create_hdu(data, sim_info=None)

Create a simple FITS HDU for intermediate image products (e.g., PSFs).

Parameters:
  • data (numpy.ndarray) – 2D array representing the simulated image or PSF.

  • sim_info (dict, optional) – Key-value metadata added as header comments.

Returns:

hdu – FITS PrimaryHDU with data and metadata in the header.

Return type:

astropy.io.fits.PrimaryHDU

corgisim.outputs.create_hdu_list(data, header_info, sim_info=None)

Create an Astropy HDUList for a simulated L1 FITS product.

  • The primary HDU contains a global header with no image data.

  • The image HDU contains the 2D simulated image and its own header.

Default L1 headers from corgidrp.mocks are applied. Optional metadata can be added as comments to the primary header.

Parameters:
  • data (numpy.ndarray) – 2D array representing the simulated image.

  • header_info (dict) – Header keywords (e.g., ‘EXPTIME’, ‘EMGAIN_C’) to override defaults in the image HDU header.

  • sim_info (dict, optional) – Key-value metadata describing the simulation setup, added as comments in the primary header.

Returns:

hdul – FITS HDUList with: [0] Primary HDU (no data, global header) [1] Image HDU (image data + header)

Return type:

astropy.io.fits.HDUList

corgisim.outputs.isotime_to_yyyymmddThhmmsss(timestr)

Format an ISO time string into a custom format yyyymmddThhmmsss

Parameters:

timestr (str) – ISO time (e.g., ‘2025-04-25T23:18:04.786184+00:00’).

Returns:

Time formatted as ‘yyyymmddThhmmsss’ (e.g., ‘20250425T2318048’).

Return type:

str

corgisim.outputs.save_hdu_to_fits(hdul, outdir=None, overwrite=False, write_as_L1=False, filename=None)

Save an Astropy HDUList to a FITS file.

Parameters:
  • hdul (astropy.io.fits.HDUList): The HDUList object to be saved.

  • outdir (str, optional): Output directory. Defaults to the current working directory.

  • overwrite (bool): If True, overwrite the file if it already exists. Default is True.

  • write_as_L1 (bool): If True, the file will be named according to the L1 naming convention.

  • filename (str, optional): Name of the output FITS file (without “.fits” extension).

    Required if write_as_L1 is False.

corgisim.outputs.str2bool(value)

Convert string representations of booleans/ints to actual bools.

corgisim.outputs.write_headers_CFAM(band_pass)
corgisim.outputs.write_headers_DPAM(cor_mode, polarization_basis, prism, use_pupil_lens)
corgisim.outputs.write_headers_FPAM(cor_type, band_pass, use_fpm, nd_filter)
corgisim.outputs.write_headers_FSAM(cor_type, band_pass, slit, polaxis, use_field_stop)
corgisim.outputs.write_headers_LSAM(cor_type, use_lyot_stop)
corgisim.outputs.write_headers_SPAM(cor_type)

corgisim.pol module

corgisim.pol.check_stokes_vector_validity(pol_state)

Check if the input stokes vector is of right length and magnitude

Args:

pol_state (float array): Stokes vector describing the polarization state of a source

Raises:

ValueError: If the provided stokes vector is not of length 4 or the polarized intensity magnitude exceeds the total intensity magnitude

corgisim.pol.get_instrument_mueller_matrix(lam_band)

Calculate the average Mueller matrix of the instrument for a given band. The pupil-averaged Mueller matrix of the instrument as a function of wavelength is provided for every 25nm wavelength interval between 450nm and 950nm. This data is interpolated so that a matrix can be obtained for any wavelength in between each 25nm interval. Then, for each wavelength sampled in a given passband, we obtain the interpolated Mueller matrix at that wavelength and average it to obtain the average instrument Mueller matrix for the band.

Args:

lam_band (float array): Array containing the sampled wavelengths for a given band in microns, ordered from shortest to longest.

Returns:

mm_passband (4 by 4 float array): Averaged instrument Mueller matrix for the given passband

corgisim.pol.get_wollaston_mueller_matrix(angle)

Calculate the Mueller matrix response for one of the two orthogonal polarization directions the light is split into, can be treated like a linear polarizer oriented at a certain angle. Used to calculate polarization for point sources

Args:

angle (float): The linear polarization angle of transmission in degrees. Default for the wollaston prisms is 0/90 degrees for the prism oriented at 0 degrees and 45/135 degrees for second prism oriented at 45 degrees.

Returns:

The 4x4 Mueller matrix describing the transformation from light going into the wollaston to one of the two pathes the light is split into

corgisim.sat_spots module

corgisim.sat_spots.add_cos_pattern_dm(dm_volts, num_pairs=2, sep_lamD=7, angle_deg=[0, 90], contrast=1e-06, wavelength_m=5.75e-07, gain_nm_per_V=None)

Add 2D cosine phase pattern(s) to Roman CGI DM solution (in volts). Reference: JPL codes from AJ Riggs and Vanessa Bailey

Parameters:
  • dm_volts: 2D numpy array (original DM in volts)

  • sep_lamD: int, float, or a list of ints/floats. Number of wave cycles across the pupil diameter. Note that the dm gain value is hardcoded assuming sep_lamD=7 and two-pair satellite spots.

  • angle_deg: int, float, or a list of ints/floats. Orientation angle (degrees, 0 = along X-axis)

  • contrast: int, float, or a list of ints/floats. Expected contrast of sattelite spots, assuming amplitude_rad = 2*sqrt(contrast), where amplitude is a phase amplitude in radians

  • wavelength_m: float. Wavelength in meters
    • gain_nm_per_V: (optional) gain to convert the DM solution from a nm unit to volts

Returns:
  • dm_volts_with_pattern: 2D numpy array (in volts), updated DM map with added cosine patterns

corgisim.scene module

class corgisim.scene.Scene(host_star_properties=None, point_source_info=None, twoD_scene_hdu=None, spmethod='bpgs')

Bases: object

A class that defines the an astrophysical scene - Information about the host star (brightness, spectral type, etc.) - A list of point sources (brightness, location, spectra?, etc.) - A 2D background scene that will be convolved with the off-axis PSFs

  • Format needs to be determined. Likely a fits hdu with specific header keywords.

  • Input with North-Up East-Left orientation.

Arguments:
host_star_properties (dict): A dictionary that contains information about the host star, including:
  • “Vmag” (float): The V-band magnitude of the host star.

  • “spectral_type” (str): Spectral type of the host star. Must follow the format: “<Class><Subclass>[<Luminosity Class>]”.

    Valid components include: - Spectral classes: O, B, A, F, G, K, M, L, T, Y - Subclasses: Integer from 0 to 9, optionally with a decimal (e.g., 3.5) - Luminosity classes (optional): I, II, III, IV, V, VI, VII - Example valid spectral types: “G2V”, “M5III”, “A0”, “T7”, “L3.5V”, “B2IV”

  • “magtype” (str): the magnitude type:

    ‘vegamag’ for Vega magnitude system. ‘ABmag’ for AB magnitude system

  • “ref_flag” (boolean):optional, whether the input scene is a reference star (True) or a science target (False). Default is false

  • “stellar_diam_mas” (float): The stellar diameter of the host star in mas.

point_sources_info (list): A list of dictionaries, each representing an off-axis point source in the scene. Each dictionary must contain:
  • “Vmag” (float): The apparent V-band magnitude of the source.

  • “magtype” (str): The photometric system used for the magnitude. Must be one of:
    • “vegamag”: Vega magnitude system

    • “ABmag”: AB magnitude system

  • “position_dra” (float): Offset in Right Ascension (dRA) from the host star, in milliarcseconds (mas), in sky coordinates.

  • “position_ddec” (float): Offset in Declination (dDEC) from the host star, in milliarcseconds (mas), in sky coordinates.

  • “Custom_Spectrum” (optional):

    A custom spectrum for the source. If provided, this spectrum will override the default spectrum generated based on Vmag.

  • “pol_state” (float array): optional, vector of length 4 consisting of the I, Q, U and V components of the stokes parameter

    describing how the source light is polarized, default is unpolarized or [1,0,0,0]

Notes:
  • The coordinates should be provided in the same reference frame and orientation as the background scene (typically North-up, East-left).

  • All magnitudes must be consistent with their respective magnitude type.

  • If no custom spectrum is provided, a default flat spectrum will be generated based on the V-band magnitude.

background_scene (HDUList): An astropy HDU that contains a background scene as data and a header full of relevant information, such as:

pixel_scale, etc.

Raises:

ValueError: If the provided spectral type is invalid. ValueError: If the provided stokes vector is not of length 4 or the polarized intensity magnitude exceeds the total intensity magnitude

get_off_axis_source_spectrum(vmag, magtype, spectrum=None)

Generate a list of off-axis source spectra scaled to given V-band magnitudes.

Parameters:
  • vmag (list of float) – Desired V-band magnitudes for the off-axis sources.

  • magtype (list of str) – Magnitude system used for each source.

  • spectrum (list or None, optional) – Custom input spectra. If None, flat spectra will be used and scaled to match vmag. Custom spectra are not yet supported and will raise an error if provided.

Returns:

A list of SourceSpectrum objects scaled to the desired V magnitudes.

Return type:

list of synphot.SourceSpectrum

get_stellar_spectrum(sptype, magnitude, magtype='vegamag', spmethod='bpgs', return_teff=False)

Checks the spmethod and retrieves a stellar spectrum using the method requested. If spmethod is ‘blackbody’ then a blackbody spectrum of the sptype is returned. If spmethod is BPGS, it loads a real stellar spectrum from BPGS atlas text files instead of using a blackbody approximation. If the exact spectral type isn’t available, it defaults to a blackbody and interpolates between neighboring types.

Args:

sptype (str): The spectral type of the star (e.g., “G2V”, “A0IV”). magnitude (float): The magnitude of the star in the specified system. atlas_dir (str or Path): Directory containing the BPGS atlas text files. magtype (str, optional): The magnitude type (‘vegamag’ by default). spmethod (str, optional): The method for generating the spectrum. Current options are ‘bpgs’ and ‘blackbody’. return_teff (bool, optional): If True, also return the effective temperature. Default is False.

Returns:

sp_scale (SourceSpectrum): The scaled stellar spectrum. teff (float, optional): Returned only if return_teff is True. The effective temperature.

Raises:

ValueError: If the spectral type format is invalid. FileNotFoundError: If the atlas directory or required files don’t exist.

property host_star_Vmag

A Method returns host star apparent magnitude Returns:

sptype (float): host star apparent magnitude

property host_star_magtype

A Method returns type of magnitude Returns:

magtype (str): type of magnitude

property host_star_sptype

A Method returns host star spectral type Returns:

sptype (str): specral type

load_bpgs_spectrum(filepath)

Load a BPGS atlas spectrum from a text file.

The BPGS files have the format: # wavelength, f_lambda wavelength_angstroms, flux (erg/s/cm^2/Angstrom)

Args:

filepath (str or Path): Path to the BPGS atlas text file.

Returns:

SourceSpectrum: The loaded spectrum in synphot format.

property point_source_Vmag

List of V-band magnitudes for off-axis point sources.

property point_source_magtype

List of magnitude type for off-axis point sources.

property stellar_diam_mas

Stellar diameter in mas for host star

class corgisim.scene.SimulatedImage(input_scene)

Bases: object

A class that defines a simulated scene.

Arguments:

input_scene: A corgisim.scene.Scene object that contains the information scene to be simulated.

combine_simulated_scenes_list()

Function that takes a list of Simulated_Scene objects and combines them into a single Simulated_Scene object.

Arguments:

scene_list: A list of corgisim.scene.Simulated_Scene objects.

Returns:
corgisim.scene.Simulated_Scene: A scene object with the host_star_image, point_source_image, and background_scene attributes

populated with the sum of the input scenes.

corgisim.scene.is_valid_spectral_type(spectral_type)

Validate if the input stellar spectral type is in a correct format.

Args:

spectral_type (str): The spectral type string (e.g., “G2V”).

Returns:

bool: True if valid, False otherwise.

Raises:

ValueError: If the spectral type is not valid.

corgisim.scene.sort_sptype(typestr)

corgisim.spec module

corgisim.spec.apply_prism(optics, image_cube)

Apply a prism dispersion model to a multiwavelength image cube from Proper.

This function shifts each wavelength slice according to a polynomial dispersion model and a prism clocking angle loaded from a parameter file. The function interpolates the input image cube to a finer wavelength sampling before applying dispersion.

Args:
optics (object): CorgiOptics configuration object containing:
  • prism_param_fname (str): Path to the prism parameter file

  • lam_um (array_like): Wavelength array in microns for the input image cube

  • wav_step_um (float): Wavelength step size in microns for the interpolated wavelength grid

  • lamref_um (float): Reference wavelength in microns for the observing mode

  • sampling_um (float): Image spatial sampling in microns of the CorgiOptics configuration

  • oversampling_factor (int): Spatial oversampling factor of the CorgiOptics configuration

image_cube (ndarray): Input multi-wavelength intensity cube from Proper simulation,

shape (n_wavelengths, n_y, n_x)

Returns:
tuple:
  • ndarray: Image cube after applying prism dispersion, with finer wavelength sampling,

    shape (n_wavelengths_interp, n_y, n_x)

  • ndarray: Interpolated wavelength array (in microns) for the dispersed_cube

  • float: Horizontal displacement of source at filter center wavelength,

    in units of oversampled model pixels

  • float: Vertical displacement of source at filter center wavelength,

    in units of oversampled model pixels

Notes:

The function performs the following operations: 1. Loads prism parameters including clocking angle and dispersion polynomial coefficients 2. Creates a densely sampled wavelength grid based on optics.wav_step_um 3. Calculates wavelength-dependent dispersion shifts in model pixels 4. Interpolates the input image cube to the finer wavelength grid 5. Applies 2D spatial shifts to each wavelength slice according to the dispersion model 6. Stacks the shifted slices into a cube array

The dispersion direction is determined by the prism clocking angle (theta), with shifts applied in both x and y directions.

Example:
>>> dispersed_cube, wavelengths = apply_prism(optics, image_cube)
corgisim.spec.get_slit_mask(optics, dx_fsam_um=10.0, hires_dim_um=800, binfac=50)

Generate an FSAM slit mask array for spec mode simulations.

This function creates a high-resolution slit mask based on the specified aperture parameters and then bins it down to an intermediate spatial resolution. The function handles slit positioning offsets, and proper scaling based on the coronagraph configuration.

Args:
optics (object): CorgiOptics configuration object containing:
  • cor_type (str): Coronagraph type (‘spc-spec_band3’ or other)

  • lamref_um (float): Reference wavelength of mode in micrometers

  • ref_data_dir (str): Directory path containing reference data files

  • slit (str): Name of the slit to use

  • slit_x_offset_mas (float or None): Slit offset in x-direction in excam coordinates in milliarcseconds

  • slit_y_offset_mas (float or None): Slit offset in y-direction in excam coordinates in milliarcseconds

  • slit_ra_offset_mas (float or None): Slit offset in right ascension in sky coordinates in milliarcseconds

  • slit_dec_offset_mas (float or None): Slit offset in declination in sky coordinates in milliarcseconds

dx_fsam_um (float, optional): FSAM slit array spatial sampling in micrometers. Defaults to 10.0. hires_dim_um (float, optional): High-resolution array dimension in micrometers. Defaults to 800. binfac (int, optional): Binning factor for downsampling. Defaults to 50.

Returns:
tuple:
  • numpy.ndarray: 2D array representing the FSAM slit transmision, with values between 0 and 1

  • float: Spatial sampling of FSAM slit array in meters

Raises:

Exception: If the requested slit is not defined in the reference parameter file ValueError: If the binning factor does not evenly divide the image dimensions

Notes:
  • Uses Roman Space Telescope preflight proper model parameters for scaling

  • Slit parameters are loaded from ‘FSAM_slit_params.json’ reference file

  • The function applies user-specified offsets

Example:
>>> binned_mask, pixel_size = get_slit_mask(self, binfac=25)
>>> print(f"Binned mask shape: {binned_mask.shape}")
corgisim.spec.read_prism_params(prism_param_fname)

Load prism parameters from a NumPy (.npz) file and validate required keys.

This function loads prism dispersion parameters for spectroscopic data simulations, including polynomial coefficients for position vs wavelength mapping and the prism clocking angle.

Args:

prism_param_fname (str or Path): Path to the prism parameter file (.npz format expected)

Returns:
numpy.lib.npyio.NpzFile: Dictionary-like object containing prism parameters with keys:
  • ‘pos_vs_wavlen_polycoeff’ (numpy.ndarray): Polynomial coefficients for position vs wavelength dispersion

  • ‘clocking_angle’ (float): Prism clocking angle in degrees

Additional parameters may be present depending on the file

Raises:

FileNotFoundError: If the prism parameter file does not exist ValueError: If the file is not a valid NumPy archive or is corrupted KeyError: If required prism parameters are missing from the file PermissionError: If the file exists but cannot be read due to permissions

Example:
>>> prism_params = read_prism('prism_data.npz')
>>> coeffs = prism_params['pos_vs_wavlen_polycoeff']
>>> angle = prism_params['clocking_angle']
Notes:

The function expects a NumPy .npz archive file containing at minimum the dispersion polynomial coefficients and clocking angle. Additional parameters in the file will be preserved and accessible.

corgisim.spec.read_slit_params(slit_param_filename)

Load slit aperture reference parameters from a JSON file.

Args:

slit_param_filename (str): The name of the JSON file.

Returns:

dict: A dictionary containing the slit data.

Raises:

FileNotFoundError: If the specified file is not found. json.JSONDecodeError: If the file contains invalid JSON.

Module contents