Simulation#

class Simulation(scene=None, spectrograph=None, detector=None, telescope=None, extraction={}, meta={})[source]#

Bases: object

Main class to simulate an observation.

This class is the main entry point to the simulation. It combines a scene (point source, background, host), a telescope, a spectrograph and a detector, together with extraction parameters (e.g. nramps), to simulate the observed cube and the extracted spectrum with its variance.

Instances are usually created with one of the class methods Simulation.from_scene, Simulation.from_source or Simulation.from_config rather than directly.

Parameters:
  • scene (Scene, optional) – The scene to observe. Default is None.

  • spectrograph (Spectrograph, optional) – The spectrograph used for the observation. Default is None.

  • detector (Detector, optional) – The detector used for the observation. Default is None.

  • telescope (Telescope, optional) – The telescope used for the observation. Default is None.

  • extraction (dict, optional) – Extraction parameters (e.g. nramps, aperture_radius). aperture (default "1-arcsec") and aperture.position (default "host", i.e. the host position) define the spectrum extraction of a scene without point source, see Simulation.get_aperture, and method (default "default") the extraction method, see Simulation.get_spectrum. Default is {}.

  • meta (dict, optional) – Input configuration, used by Simulation.reset to restore the initial state of each element. Default is {}.

Variables:
  • scene (Scene) – The scene to observe.

  • spectrograph (Spectrograph) – The spectrograph used for the observation.

  • detector (Detector) – The detector used for the observation.

  • telescope (Telescope) – The telescope used for the observation.

  • extraction (dict) – Extraction parameters.

Methods

change_pointsource

Override the considered pointsource.

change_spectrograph_resolution

Change the spectrograph's spectral resolution.

convert_units

Convert flux units.

fetch_snr

Find the exposure configuration reaching a target SNR.

from_config

Initialize the simulation from a nested configuration dictionary.

from_scene

Load the simulation from scene and instrument configurations.

from_scene_and_instconfig

Load the simulation from a scene and an instrument configuration.

from_source

Load the simulation observing a known source (like a star).

get_aperture

Get the aperture used to extract the host spectrum.

get_background_spectrum

Get the (flat) background flux within a given sky area.

get_band_flux

Estimate the mean signal and variance over a spectral domain.

get_band_snr

Compute the signal-to-noise ratio over a spectral domain.

get_band_variance_contribution

Estimate the contributions to the total variance over a band.

get_cube

Get the signal and variance cubes as extracted from the exposure.

get_data_volume

Get the total data volume of the simulation.

get_effective_transmission

Get the effective total transmission of the instrument.

get_input_spectrum

Get the input spectrum of a scene element.

get_lbda

Get the wavelength array.

get_nea

Get the Noise Equivalent Area (NEA).

get_nea_variance

Get the variance estimated from the Noise Equivalent Area.

get_parameter

Get simulation parameter(s).

get_pixel_variance

Get the variance associated with a single detector pixel.

get_projected_scene

Project the scene through the spectrograph and get the flux cube.

get_resolving_power

Get the spectral resolving power \(R\).

get_scene_cubes

Get the cubes of each scene component (noise free).

get_slice

Get images of the cube summed over wavelength ranges.

get_snr

Get the signal-to-noise ratio spectrum.

get_spectrum

Get the extracted spectrum and its variance.

get_times

Get the detector times of the simulation.

get_variance_contribution

Estimate the noise contributions to the total spectrum variance.

reset

Reset simulation elements to their initial configuration.

show_config

Show configuration (resolving power and throughput).

show_cube

Display the cube generated by Simulation.get_projected_scene.

show_nea_fwhm

Show the noise equivalent areas (NEA) and the FWHM.

show_scene

Show images of the observed scene.

show_spectrum

Plot the detected spectrum and its error.

show_variance_sources

Summary figure showing various variance contributions.

update

Update any mutable parameter of the simulation.

update_from_config

Update the simulation from a configuration dictionary.

Attributes

VARIANCE_SOURCES

cube_shape

Shape of the generated 3d-cube (nlbda, ny, nx).

meta

Configuration of all elements (aka.

mutable_parameters

List of the parameter names accepted by Simulation.update.

observing_time

Total observing time [s], i.e. exposure_time * nramps.

variance_sources

List of the variance source names (see Simulation.get_cube).

scene

Scene instance

spectrograph

Spectrograph instance

detector

Detector instance

extraction

Extraction parameters

telescope()

telescope

change_pointsource(pointsource)[source]#

Override the considered pointsource.

Parameters:

pointsource (PointSource) – New pointsource to be used.

Returns:

None

change_spectrograph_resolution(rmin, spotsize=2)[source]#

Change the spectrograph’s spectral resolution.

This updates the spectrograph dispersion configuration (dispersion_scale, dispersion_resolution and spotsize) so that the resulting minimal resolving power scales with rmin. The reference is a dispersion resolution of 2 pixels for rmin=100, such that dispersion_scale = 1.3 * (rmin / 100) * (spotsize / 2).

Parameters:
  • rmin (float) – Requested minimal resolving power.

  • spotsize (float, optional) – Spot size (in pixels) used to compute the dispersion scale. Default is 2.

Returns:

None – Updates the simulation in place (see Simulation.update).

convert_units(units_in, units_out, flux_in=1)[source]#

Convert flux units.

Conversions are only implemented between "adu" (total signal integrated on the detector, over all ramps) and one of:

  • "flambda" (or "erg/s/a/cm2") [erg/s/cm^2/A];

  • "rate" (or "adu/s") [ADU/s];

  • "framerate" (or "adu/frame") [ADU/frame];

  • "fphoton" (or "ph/s") [ph/s].

Parameters:
  • units_in (str) – Input units.

  • units_out (str) – Output units.

  • flux_in (float or array_like, optional) – Input flux. Default is 1 (returns the conversion factor).

Returns:

float or numpy.ndarray – Converted flux (wavelength dependent, shape (nlbda,), for the "flambda" and "fphoton" conversions).

Raises:

NotImplementedError – If the requested conversion is not implemented.

fetch_snr(target_snr, max_group=None, nframe_per_group=None, nframe_per_group_small=4, small_ngroup_range=[32, 8], allow_smaller_ramps=True, too_large=1.0, ndrop=None, guess=None, use_cache=True, lbda_range=[4000, 6800], frame='rest', statistic=<function nanmean>, reset_param=True, maxiter=30, tol=0.5, iterstep=1)[source]#

Find the exposure configuration reaching a target SNR.

The read-out configuration nmd (number of groups, frames per group, dropped frames) and the number of ramps nramps are varied to reach target_snr (see Simulation.get_band_snr):

  • if a single ramp with max_group groups is enough, a single ramp is used and its number of groups is optimised (using nframe_per_group_small frames per group, or even single-frame groups, for bright targets);

  • otherwise, full ramps of max_group groups are used and the number of ramps (at least 2) is optimised. If allow_smaller_ramps, the number of groups is then fine-tuned for that number of ramps.

Parameters:
  • target_snr (float) – Target signal-to-noise ratio.

  • max_group (int or None, optional) – Maximum number of groups per ramp. If None, detector.max_group is used. Default is None.

  • nframe_per_group (int or None, optional) – Number of frames per group for full ramps. If None, the current one is used. Default is None.

  • nframe_per_group_small (int, optional) – Number of frames per group used for single short ramps (bright targets). Default is 4.

  • small_ngroup_range (list of int, optional) – Range of number of groups tested for single short ramps. Default is [32, 8].

  • allow_smaller_ramps (bool, optional) – If N+1 ramps give a too large SNR (see too_large) while N ramps are not enough, reduce the number of groups of the N+1 ramps to reach the target SNR. Default is True.

  • too_large (float, optional) – SNR excess (absolute) above target_snr triggering the reduction of the number of groups. Ignored if allow_smaller_ramps is False. Default is 1.

  • ndrop (int or None, optional) – Number of dropped frames. If None, the current one is used. Default is None.

  • guess (int or None, optional) – Initial guess for the free parameter (number of groups or of ramps). If None, a default guess is used. Default is None.

  • use_cache (bool, optional) – If True, cache the projected scene while iterating (only the read-out configuration changes). The cache is cleared at the end. Default is True.

  • lbda_range (list of float, optional) – (wmin, wmax) test wavelength range [Angstrom]. Default is [4000, 6800].

  • frame (str, optional) – Wavelength frame of lbda_range ("obs" or "rest"). Default is "rest".

  • statistic (callable, optional) – Function applied on the test domain to compute the SNR (see Simulation.get_band_flux). Default is numpy.nanmean.

  • reset_param (bool, optional) – If True, the simulation is set back to its input nmd and nramps. If False, it keeps the configuration reaching the SNR. Default is True.

  • maxiter (int, optional) – Maximum number of iterations. Default is 30.

  • tol (float, optional) – Tolerance on the SNR. Default is 0.5.

  • iterstep (int, optional) – Initial step of the iteration. Default is 1.

Returns:

classmethod from_config(config, slicer=True)[source]#

Initialize the simulation from a nested configuration dictionary.

Parameters:
  • config (dict) – Top level configuration (e.g. as returned by get_config). It must contain the "telescope", "spectrograph", "detector" and "extraction" entries, and may contain a "scene" entry (otherwise the scene is None). It is stored as the reference configuration used by Simulation.reset.

  • slicer (bool, optional) – If True, use a SlicerSpectrograph, otherwise a MLASpectrograph. Default is True.

Returns:

Simulation – The loaded simulation.

classmethod from_scene(redshift=None, snr=20, lbda_range=[4000, 6800], frame='rest', scene='supernova.toml', instrument='lazuli_cbe.toml', slicer=True, **kwargs)[source]#

Load the simulation from scene and instrument configurations.

The exposure configuration (nmd and nramps) is then set to reach the requested SNR on the pointsource, unless snr is None.

Parameters:
  • redshift (float or None, optional) – Redshift of the pointsource. If None, the one from the scene configuration is used. Default is None.

  • snr (float or None, optional) – Targeted average SNR per wavelength bin (see lbda_range and frame), reached using Simulation.fetch_snr. If None, the exposure configuration is not changed. Default is 20.

  • lbda_range (list of float, optional) – (wmin, wmax) wavelength range where the SNR is estimated [Angstrom]. Default is [4000, 6800].

  • frame (str, optional) – Wavelength frame of lbda_range ("obs" or "rest"). Default is "rest".

  • scene (str, dict or list, optional) – Scene configuration (see get_config). Default is "supernova.toml".

  • instrument (str, dict or list, optional) – Instrument configuration (see get_config). Default is "lazuli_cbe.toml".

  • slicer (bool, optional) – If True, use a SlicerSpectrograph, otherwise a MLASpectrograph. Default is True.

  • **kwargs – Goes to Simulation.update to change any default configuration (applied before the SNR optimisation).

Returns:

Simulation – The loaded simulation.

classmethod from_scene_and_instconfig(scene, config, slicer=True)[source]#

Load the simulation from a scene and an instrument configuration.

Parameters:
  • scene (Scene or dict) – The scene to observe, either as a scene object or as a scene configuration dictionary.

  • config (dict or str) – Instrument configuration containing the "telescope", "spectrograph", "detector" and "extraction" entries. If a str, it is loaded with get_config.

  • slicer (bool, optional) – If True, use a SlicerSpectrograph, otherwise a MLASpectrograph. Default is True.

Returns:

Simulation – A simulation with the given scene and configuration.

classmethod from_source(lbda, flux, mag=None, band='bessellb', position=(0, 0), instrument='lazuli_cbe.toml', background='zodi', host=None, snr=None, lbda_range=[4000, 6800], frame='obs', **kwargs)[source]#

Load the simulation observing a known source (like a star).

Parameters:
  • lbda (array_like) – (High resolution) wavelength of the source [Angstrom].

  • flux (array_like) – Flux of the input source [erg/s/cm^2/A].

  • mag (float, optional) – Requested magnitude of the source (rescales the flux amplitude). If None, flux is used as is. Default is None.

  • band (str, optional) – Name of the band used to compute the magnitude (should be known by sncosmo). Default is "bessellb".

  • position (tuple of float, optional) – Location of the point source within the IFU, (x, y) in spaxels. Default is (0, 0).

  • instrument (str, dict or list, optional) – Configuration of the instrument (see get_config). Default is "lazuli_cbe.toml".

  • background (str, dict, list or None, optional) – Configuration of the (spatially flat) scene background. If None, no background is added. Default is "zodi".

  • host (str, dict, list or None, optional) – Configuration of the (spatially structured) host component of the scene. If None, no host is added. Default is None.

  • snr (float or None, optional) – If not None, the simulation is set up (see Simulation.fetch_snr) to reach this average SNR per wavelength bin over lbda_range. Default is None.

  • lbda_range (list of float, optional) – (wmin, wmax) wavelength range used to average the SNR [Angstrom]. Ignored if snr is None. Default is [4000, 6800].

  • frame (str, optional) – Frame of lbda_range ("obs" or "rest"). Ignored if snr is None. Default is "obs".

  • **kwargs – Goes to Simulation.update.

Returns:

Simulation – The loaded simulation.

See also

Simulation.from_scene

load a simulation from a scene configuration.

get_aperture(aperture=None, position=None)[source]#

Get the aperture used to extract the host spectrum.

It is used by Simulation.get_spectrum when the scene has no point source (e.g. a galaxy alone) or with of_host=True, and for the aperture photometry of a point source (method="aperture"), then centered on the point source.

Parameters:
  • aperture (str or None, optional) –

    Aperture definition:

    • "core": the core of the galaxy, extracted as a point source would be, i.e. optimal (PSF-weighted) extraction within the point-source aperture radius (aperture_radius or aperture_radius_insigma);

    • "<n>-arcsec": aperture photometry (plain summation) within a radius of n arcsec, e.g. "1-arcsec";

    • "<n>-kpc": aperture photometry within a radius of n kpc (proper) at the scene redshift, e.g. "2-kpc".

    If None, the aperture extraction parameter is used (default "1-arcsec"). Default is None.

  • position (tuple of float, str or None, optional) – (x, y) aperture center, in spaxels, or "host" for the host position. If None, the aperture.position extraction parameter is used (default "host"). Default is None.

Returns:

  • position (tuple of float) – (x, y) aperture center, in spaxels.

  • radius (float) – Aperture radius, in spaxels.

  • optimal (bool) – True for an optimal (PSF-weighted) extraction ("core"), False for a plain summation.

Raises:
  • ValueError – If aperture cannot be parsed, or if a kpc aperture is requested without redshift.

  • NotImplementedError – If the spaxels are not square (non scalar spx_spatial_scale).

get_background_spectrum(unit='adu', skyarea=None, per_ramp=False, apply_lsf=True)[source]#

Get the (flat) background flux within a given sky area.

Parameters:
  • unit (str, optional) – Unit of the output flux: "adu" (total signal), "flambda" [erg/s/cm^2/A] or "ph", "photon", "photons" [ph/s]. Default is "adu".

  • skyarea (float or None, optional) – Sky area [arcsec^2]. If None, the area of one spaxel is used. Default is None.

  • per_ramp (bool, optional) – If True, the flux is not multiplied by nramps (for single ramp). Default is False.

  • apply_lsf (bool, optional) – If True, apply the line spread function. Default is True.

Returns:

numpy.ndarray – Background flux per wavelength bin, shape (nlbda,).

Raises:

ValueError – If unit is unknown.

get_band_flux(lbda_range, frame='obs', statistic=<function nanmean>, squeeze=True, **kwargs)[source]#

Estimate the mean signal and variance over a spectral domain.

The photometry is computed assuming a top-hat filter and simply considering wavelength bins within the spectral domain (no interpolation nor weighting).

Parameters:
  • lbda_range (tuple of float or list of tuple) – (wmin, wmax) test wavelength range (or list of) [Angstrom].

  • frame (str, optional) – Wavelength frame of lbda_range ("obs" or "rest"). Default is "obs".

  • statistic (callable, optional) – Function applied on the signal and variance of the wavelength bins within the test domain (called with axis=0). Default is numpy.nanmean.

  • squeeze (bool, optional) – If True and a single range is given, return floats rather than arrays. Default is True.

  • **kwargs – Goes to Simulation.get_spectrum (e.g. switch_off).

Returns:

Raises:

ValueError – If frame is neither "obs" nor "rest".

get_band_snr(lbda_range, frame='obs', statistic=<function nanmean>, at_saturation=inf, **kwargs)[source]#

Compute the signal-to-noise ratio over a spectral domain.

The SNR is the band signal over the square root of the band variance, as computed by Simulation.get_band_flux.

Parameters:
Returns:

float or numpy.ndarray – Signal-to-noise ratio (array if several ranges are given).

get_band_variance_contribution(lbda_range, frame='rest', statistic=<function nanmean>)[source]#

Estimate the contributions to the total variance over a band.

Loops over Simulation.variance_sources (detector effects, scene elements and thermal emission), switching each off in turn, to estimate its contribution to the total band variance.

Parameters:
Returns:

dict – Dictionary with keys "snr", "exptime" and "inttime" (per ramp) and "obstime" (total) [s], "signal" [ADU], "variance" [ADU^2], and for each variance source source, its variance contribution (key source, [ADU^2]) and its fraction of the total variance (key frac_<source>).

get_cube(switch_off=[], psf_profile='default', as_oversampled=False, oversampling=None, per_ramp=False, apply_lsf=True, cached=False, **kwargs)[source]#

Get the signal and variance cubes as extracted from the exposure.

Parameters:
  • switch_off (str or list of str, optional) – Name of the variance sources to switch off, any of Simulation.variance_sources ("dark", "roic_glow", "thermal_dark", "ron", "pointsource", "background", "host", "thermal") or "effective_dark" ("dark" and "thermal_dark"). Detector effects are only switched off during the computation. Default is [].

  • psf_profile (str, optional) – PSF profile to use. Default is "default".

  • as_oversampled (bool, optional) – If True, return the oversampled cube. Default is False.

  • oversampling (int or None, optional) – Oversampling factor. Default is None.

  • per_ramp (bool, optional) – If True, the cubes are not multiplied by nramps (for single ramp). Default is False.

  • apply_lsf (bool, optional) – If True, apply the line spread function. Default is True.

  • cached (bool, optional) – If True, use (or store) the cached projected scene and thermal signal (see Simulation.get_projected_scene). Default is False.

  • **kwargs – Goes to Simulation.get_projected_scene.

Returns:

  • cube_signal (numpy.ndarray) – (nlbda, ny, nx) signal cube [ADU].

  • cube_variance (numpy.ndarray) – (nlbda, ny, nx) variance cube [ADU^2].

Raises:

ValueError – If the spectrograph type is neither MLA nor slicer.

Warns:

UserWarning – If an entry of switch_off is unknown.

get_data_volume(units='GB', per_ramp=False, **kwargs)[source]#

Get the total data volume of the simulation.

Parameters:
  • units (str, optional) – Units of the data volume (e.g. "GB", "MB"). Default is "GB".

  • per_ramp (bool, optional) – If True, return the data volume per ramp instead of the total data volume (i.e., not multiplied by the number of ramps). Default is False.

  • **kwargs – Goes to get_data_volume.

Returns:

float – Data volume in the requested units.

get_effective_transmission()[source]#

Get the effective total transmission of the instrument.

Product of the spectroscopic throughput (spectrograph.flambda2photon) and the detector efficiency (detector.photonflux_to_adu), for a single ramp.

Returns:

  • lbda (numpy.ndarray) – Wavelength [Angstrom].

  • throughput (numpy.ndarray) – Effective throughput, i.e. conversion from flux to signal [ADU / (erg/s/cm^2/A)].

get_input_spectrum(which='pointsource')[source]#

Get the input spectrum of a scene element.

This is a shortcut to self.scene.get_element_spectrum.

Parameters:

which (str, optional) –

Which input spectrum to return:

  • individual elements: "pointsource", "background", "host";

  • all elements summed: "stacked".

Default is "pointsource".

Returns:

get_lbda()[source]#

Get the wavelength array.

This is a shortcut to self.spectrograph.lbda.

Returns:

numpy.ndarray – Wavelength of the spectral bins [Angstrom].

get_nea(nea_spatial=None, nea_pixels=None)[source]#

Get the Noise Equivalent Area (NEA).

The NEA is the product of the spatial NEA and the pixel NEA.

Parameters:
  • nea_spatial (float or array_like, optional) – The spatial NEA [spaxel^2]. If None, it is computed. Default is None.

  • nea_pixels (float or array_like, optional) – The pixel NEA [pixel]. If None, it is computed. Default is None.

Returns:

float or numpy.ndarray – The total NEA [pixel].

get_nea_variance(spectrum=None, nea_spatial=None, nea_pixels=None)[source]#

Get the variance estimated from the Noise Equivalent Area.

Parameters:
  • spectrum (array_like or None, optional) – The input spectrum [erg/s/cm^2/A]. If given, its Poisson variance is added (approximation). Default is None.

  • nea_spatial (float or array_like, optional) – The spatial NEA [spaxel^2]. If None, it is computed. Default is None.

  • nea_pixels (float or array_like, optional) – The pixel NEA [pixel]. If None, it is computed. Default is None.

Returns:

float or numpy.ndarray – The estimated variance [ADU^2].

Warns:

UserWarning – If spectrum is given and the configuration differs from the validated one (spatial_scale=0.04, psf_sigma_spectral=0.03).

get_parameter(which=None, default=None, as_dict=True)[source]#

Get simulation parameter(s).

The parameter should be an extraction parameter or an attribute (or meta entry) of one of the elements of the simulation, e.g. gain for Simulation.detector.gain. The element__name format is also accepted: element is first looked for as an attribute of the simulation (e.g. detector__gain), then as a sub-element of the scene, spectrograph or detector (e.g. optics__emissivity for Simulation.spectrograph.optics).

Parameters:
  • which (str, list of str or None, optional) – Parameter name (or list of). If None, all parameters are returned. Default is None.

  • default (object, optional) – Value returned if the parameter is not found. Default is None.

  • as_dict (bool, optional) – If the parameter is not found, return {which: default} rather than default. Default is True.

Returns:

object or dict – Parameter value. If which is a list, a dict {name: value} is returned.

get_pixel_variance(flux=0, **kwargs)[source]#

Get the variance associated with a single detector pixel.

The variance includes all nramps ramps.

Parameters:
Returns:

float or numpy.ndarray – Variance of the pixel [ADU^2].

get_projected_scene(in_photons=True, switch_off=[], psf_profile='default', as_oversampled=False, oversampling=None, apply_lsf=True, cached=False, **kwargs)[source]#

Project the scene through the spectrograph and get the flux cube.

The cube is the noise-free incident flux per spaxel, including the pointsource, host, background and thermal contributions (unless switched off).

Parameters:
  • in_photons (bool, optional) – If True, return the cube in [ph/s], otherwise in [erg/s/cm^2/A]. Default is True.

  • switch_off (list of str, optional) – Components to discard: any of "pointsource", "host", "background" and "thermal". Default is [].

  • psf_profile (str, optional) – PSF profile to use. Default is "default".

  • as_oversampled (bool, optional) – If True, return the oversampled cube. Default is False.

  • oversampling (int or None, optional) – Oversampling factor. If None, 3 is used. Default is None.

  • apply_lsf (bool, optional) – If True, apply the line spread function. Default is True.

  • cached (bool, optional) – If True, return the cube stored by a previous call made with cached=True (if any), otherwise compute and store it. The other arguments are then ignored. Default is False.

  • **kwargs – Goes to the spectrograph generate_pointsource and generate_structured_background methods.

Returns:

numpy.ndarray – (nlbda, ny, nx) cube in [ph/s] or [erg/s/cm^2/A].

Raises:

NotImplementedError – If the host is included and as_oversampled is True.

get_resolving_power()[source]#

Get the spectral resolving power \(R\).

This is a shortcut to get_resolving_power:

\[R = \frac{\lambda}{\Delta\lambda \, \sigma}\]

with \(\Delta\lambda\) the spectral step [Angstrom] and \(\sigma\) the dispersion resolution [pixel].

Returns:

get_scene_cubes(unit='adu', psf_profile='default', as_oversampled=False, oversampling=None, as_dict=True, per_ramp=False, apply_lsf=True, **kwargs)[source]#

Get the cubes of each scene component (noise free).

Parameters:
  • unit (str, optional) – Unit of the output flux: "adu" (or "default"), "flambda" [erg/s/cm^2/A] or "ph", "photon", "photons" [ph/s]. Default is "adu".

  • psf_profile (str, optional) – PSF profile to use. Default is "default".

  • as_oversampled (bool, optional) – If True, return the oversampled pointsource cube. Default is False.

  • oversampling (int or None, optional) – Oversampling factor. Default is None.

  • as_dict (bool, optional) – If True, return a dictionary of cubes. Default is True.

  • per_ramp (bool, optional) – If True, the cubes are not multiplied by nramps (for single ramp). Default is False.

  • apply_lsf (bool, optional) – If True, apply the line spread function. Default is True.

  • **kwargs – Goes to the spectrograph generate_pointsource and generate_structured_background methods.

Returns:

dict or numpy.ndarray – If as_dict, a dictionary with keys "pointsource", "background", "host_cube" and "thermal_cube", each a (nlbda, ny, nx) cube. Otherwise, these four cubes stacked in a (4, nlbda, ny, nx) array.

Raises:
get_slice(lbda_range, frame='obs', switch_off=[], incl_error=False, squeeze=False, psf_profile='default', as_oversampled=False, oversampling=None, apply_lsf=True, cached=False, **kwargs)[source]#

Get images of the cube summed over wavelength ranges.

Parameters:
  • lbda_range (tuple of float or list of tuple) – (lbda_min, lbda_max) for a single slice, or ((lbda_min, lbda_max), (lbda_min, lbda_max), …) for several slices [Angstrom].

  • frame (str, optional) – Wavelength frame of lbda_range ("obs" or "rest"). Default is "obs".

  • switch_off (list of str, optional) – Variance sources to switch off (see Simulation.get_cube). Default is [].

  • incl_error (bool, optional) – If True, the signal is randomly scattered following its (Gaussian) error. Default is False.

  • squeeze (bool, optional) – If True, squeeze the output arrays. Default is False.

  • psf_profile (str, optional) – PSF profile to use. Default is "default".

  • as_oversampled (bool, optional) – If True, use the oversampled cube. Default is False.

  • oversampling (int or None, optional) – Oversampling factor. Default is None.

  • apply_lsf (bool, optional) – If True, apply the line spread function. Default is True.

  • cached (bool, optional) – If True, use cached intermediate products (see Simulation.get_cube). Default is False.

  • **kwargs – Goes to Simulation.get_cube.

Returns:

Raises:

ValueError – If frame is neither "obs" nor "rest".

get_snr(switch_off=[])[source]#

Get the signal-to-noise ratio spectrum.

See Simulation.get_spectrum.

Parameters:

switch_off (list of str, optional) – Variance sources to switch off (see Simulation.get_cube). Default is [].

Returns:

numpy.ndarray – (nlbda,) signal-to-noise ratio per wavelength bin.

get_spectrum(switch_off=[], incl_error=False, of_host=False, method=None, psf_profile='default', apply_lsf=True, cached=False)[source]#

Get the extracted spectrum and its variance.

If the scene has a point source, its spectrum is extracted (unless of_host). Otherwise (e.g. a galaxy alone), the host spectrum is extracted within the aperture defined by the aperture and aperture.position extraction parameters (see Simulation.get_aperture).

The extraction method is either:

  • "optimal": inverse-variance weighted least-square fit of the PSF profile. For a point source, its signal is assumed to be perfectly extracted, while its variance is computed from the variance cube within the point-source extraction aperture (aperture_radius or aperture_radius_insigma). For the host, both the signal and the variance are measured from the cubes, within the aperture.

  • "aperture": aperture photometry, i.e. plain summation of the signal and the variance within the aperture. For a point source, the aperture is centered on it and the signal is the point-source flux within the aperture (no aperture correction, which would not change the signal-to-noise).

  • "default": "optimal" for a point source, and for the host, "optimal" if aperture="core" and "aperture" otherwise.

The signal is measured from the noise-free cube of the extracted element and the variance from the variance cube, with the same weights (but for the optimal point-source signal, see above). Both include all nramps ramps.

Parameters:
  • switch_off (list of str, optional) – Variance sources to switch off (see Simulation.get_cube). Default is [].

  • incl_error (bool, optional) – If True, the signal is randomly scattered following its (Gaussian) error. Default is False.

  • of_host (bool, optional) – If True, extract the host spectrum (even if a point source is present). Default is False.

  • method (str or None, optional) – Extraction method: "default", "optimal" or "aperture" (see above). If None, the method extraction parameter is used (default "default"). Default is None.

  • psf_profile (str, optional) – PSF profile to use. Default is "default".

  • apply_lsf (bool, optional) – If True, apply the line spread function. Default is True.

  • cached (bool, optional) – If True, use cached intermediate products (see Simulation.get_cube). Default is False.

Returns:

Raises:

ValueError – If method is not known.

get_times()[source]#

Get the detector times of the simulation.

Returns:

dict – Times [s], with keys "integration_time", "exposure_time", "tframe", "tgroup" (detector, per ramp) and "total_exptime" (see Simulation.observing_time).

get_variance_contribution(as_dataframe=True)[source]#

Estimate the noise contributions to the total spectrum variance.

Each source of Simulation.variance_sources is switched off in turn to estimate its contribution per wavelength bin.

Parameters:

as_dataframe (bool, optional) – If True, return a pandas.DataFrame, otherwise a dict. Default is True.

Returns:

pandas.DataFrame or dict – Columns "lbda" [Angstrom], "flux" [ADU], "variance" [ADU^2] and one column per variance source (variance contribution [ADU^2]).

reset(which='*')[source]#

Reset simulation elements to their initial configuration.

The initial configuration is the one given as meta when loading the simulation (see Simulation.from_config). Careful, this creates a new element and erases the current one.

Parameters:

which (str, optional) – Element to reset: "*" or "all" for every element, or one of "scene", "telescope", "spectrograph", "detector" or "extraction". Default is "*".

Raises:

ValueError – If which is not a known element.

show_config(axes=None, lbda_units=None, colors=['#194D80', '#A8B7C7'])[source]#

Show configuration (resolving power and throughput).

Parameters:
  • axes (tuple of matplotlib.axes.Axes or None, optional) – (axr, axt) axes for the resolving power and the throughput. If None, a new figure is created. Default is None.

  • lbda_units (str or None, optional) – Units (understood by astropy.units) to convert the wavelength to. If None, Angstrom is used. Default is None.

  • colors (list of str, optional) – Colors used for the plot. Default is ["#194D80", "#A8B7C7"].

Returns:

matplotlib.figure.Figure – Figure.

show_cube(in_photons=True, switch_off=[], spec_prop={}, psf_profile='default', cached=False, **kwargs)[source]#

Display the cube generated by Simulation.get_projected_scene.

The figure has two panels:

  • left: total spectrum (cube summed over spaxels);

  • right: white image (cube summed over wavelengths).

Parameters:
  • in_photons (bool, optional) – If True, the cube is in [ph/s], otherwise in [erg/s/cm^2/A]. Default is True.

  • switch_off (list of str, optional) – Components to discard (see Simulation.get_projected_scene). Default is [].

  • spec_prop (dict, optional) – Spectrum plot options (goes to matplotlib.axes.Axes.plot). Default is {}.

  • psf_profile (str, optional) – PSF profile to use. Default is "default".

  • cached (bool, optional) – If True, use the cached projected scene. Default is False.

  • **kwargs – Goes to matplotlib.axes.Axes.imshow (image panel).

Returns:

matplotlib.figure.Figure – 2-axis figure.

show_nea_fwhm(figsize=(4, 7))[source]#

Show the noise equivalent areas (NEA) and the FWHM.

Parameters:

figsize (tuple of float, optional) – Figure size. Default is (4, 7).

Returns:

matplotlib.figure.Figure – Figure.

show_scene(incl_error=True, fig=None, rest_lbda_range=[4000, 7000], obs_lbda_ranges=[[4000, 6000], [9000, 11000], [14000, 16000]], psf_profile='default', oversampling=None, prop_slice={}, **kwargs)[source]#

Show images of the observed scene.

The top panel shows the image in a rest-frame wavelength range, the bottom panels the images in observed-frame wavelength ranges (see Simulation.get_slice).

Parameters:
  • incl_error (bool, optional) – If True, the images are randomly scattered following their errors. Default is True.

  • fig (matplotlib.figure.Figure or None, optional) – Figure to draw on. If None, a new one is created. Default is None.

  • rest_lbda_range (list of float, optional) – Rest-frame wavelength range [Angstrom]. Default is [4000, 7000].

  • obs_lbda_ranges (list of list of float, optional) – Observed-frame wavelength ranges [Angstrom] (at most 3). Default is [[4000, 6000], [9000, 11_000], [14_000, 16_000]].

  • psf_profile (str, optional) – PSF profile to use. Default is "default".

  • oversampling (int or None, optional) – If given, show oversampled images with this oversampling factor. Default is None.

  • prop_slice (dict, optional) – Goes to Simulation.get_slice. Default is {}.

  • **kwargs – Goes to matplotlib.axes.Axes.imshow.

Returns:

matplotlib.figure.Figure – Figure.

show_spectrum(ax=None, switch_off=[], snr=False, **kwargs)[source]#

Plot the detected spectrum and its error.

Parameters:
Returns:

matplotlib.figure.Figure – Figure.

show_variance_sources(variance_contrib=None, flux_calibrated=True, normalize_variances=True, lbda_nm=False, figsize=(7, 7), gridspec={})[source]#

Summary figure showing various variance contributions.

Parameters:
  • variance_contrib (pandas.DataFrame or None, optional) – Variance contributions, as returned by self.get_variance_contribution(as_dataframe=True) (see Simulation.get_variance_contribution). If None, it is computed. Default is None.

  • flux_calibrated (bool, optional) – If True, show the flux-calibrated spectrum [erg/s/cm^2/A], otherwise in [ADU]. Default is True.

  • normalize_variances (bool, optional) – If True, the variance contributions are normalised by their sum (fractions summing to 1), otherwise by the total variance. Default is True.

  • lbda_nm (bool, optional) – If True, show wavelength in nanometers, otherwise in Angstrom. Default is False.

  • figsize (tuple of float, optional) – Figure size. Default is (7, 7).

  • gridspec (dict, optional) – Goes to gridspec_kw of matplotlib.pyplot.subplots. Default is {}.

Returns:

matplotlib.figure.Figure – Figure.

update(reset_others=False, **kwargs)[source]#

Update any mutable parameter of the simulation.

For convenience, the update method respects the django __ format, such that, e.g. pointsource__phase is understood as pointsource.phase. This way, one can do:

>>> sim.update(pointsource__phase=-1)

You can also specify a short name, like phase. If it matches a single entry of Simulation.mutable_parameters, it is accepted.

>>> sim.update(phase=-1)

For convenience and backward compatibility, you can use target__ in place of pointsource__.

Parameters:
  • reset_others (bool, optional) – If True, the scene, spectrograph and detector parameters that are not given are reset to their default values. Default is False.

  • **kwargs – Parameters to update, as name=value. Parameters set to None are ignored. Parameters not belonging to the scene, the spectrograph or the detector update extraction.

Warns:

UserWarning – If a parameter is not mutable or if a short name is ambiguous (matches several mutable parameters); it is then ignored.

update_from_config(config)[source]#

Update the simulation from a configuration dictionary.

Parameters:

config (dict) – Dictionary of configurations, keyed by element name ("scene", "telescope", "spectrograph", "detector", "extraction"). Each value is passed as keyword arguments to the corresponding element’s update method (or merged into extraction).

Returns:

None

Warns:

UserWarning – If a key of config is not an element name (it is ignored).

VARIANCE_SOURCES = ['dark', 'roic_glow', 'thermal_dark', 'ron', 'pointsource', 'background', 'host', 'thermal']#
cube_shape#

Shape of the generated 3d-cube (nlbda, ny, nx).

meta#

Configuration of all elements (aka. meta), as a dict.

mutable_parameters#

List of the parameter names accepted by Simulation.update.

observing_time#

Total observing time [s], i.e. exposure_time * nramps.

variance_sources#

List of the variance source names (see Simulation.get_cube).

scene#

Scene instance

spectrograph#

Spectrograph instance

detector#

Detector instance

extraction#

Extraction parameters

telescope#

telescope