Simulation#
- class Simulation(scene=None, spectrograph=None, detector=None, telescope=None, extraction={}, meta={})[source]#
Bases:
objectMain 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_sourceorSimulation.from_configrather 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") andaperture.position(default"host", i.e. the host position) define the spectrum extraction of a scene without point source, seeSimulation.get_aperture, andmethod(default"default") the extraction method, seeSimulation.get_spectrum. Default is{}.meta (
dict, optional) – Input configuration, used bySimulation.resetto 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
Override the considered pointsource.
Change the spectrograph's spectral resolution.
Convert flux units.
Find the exposure configuration reaching a target SNR.
Initialize the simulation from a nested configuration dictionary.
Load the simulation from scene and instrument configurations.
Load the simulation from a scene and an instrument configuration.
Load the simulation observing a known source (like a star).
Get the aperture used to extract the host spectrum.
Get the (flat) background flux within a given sky area.
Estimate the mean signal and variance over a spectral domain.
Compute the signal-to-noise ratio over a spectral domain.
Estimate the contributions to the total variance over a band.
Get the signal and variance cubes as extracted from the exposure.
Get the total data volume of the simulation.
Get the effective total transmission of the instrument.
Get the input spectrum of a scene element.
Get the wavelength array.
Get the Noise Equivalent Area (NEA).
Get the variance estimated from the Noise Equivalent Area.
Get simulation parameter(s).
Get the variance associated with a single detector pixel.
Project the scene through the spectrograph and get the flux cube.
Get the spectral resolving power \(R\).
Get the cubes of each scene component (noise free).
Get images of the cube summed over wavelength ranges.
Get the signal-to-noise ratio spectrum.
Get the extracted spectrum and its variance.
Get the detector times of the simulation.
Estimate the noise contributions to the total spectrum variance.
Reset simulation elements to their initial configuration.
Show configuration (resolving power and throughput).
Display the cube generated by
Simulation.get_projected_scene.Show the noise equivalent areas (NEA) and the FWHM.
Show images of the observed scene.
Plot the detected spectrum and its error.
Summary figure showing various variance contributions.
Update any mutable parameter of the simulation.
Update the simulation from a configuration dictionary.
Attributes
Shape of the generated 3d-cube (nlbda, ny, nx).
Configuration of all elements (aka.
List of the parameter names accepted by
Simulation.update.Total observing time [s], i.e.
exposure_time * nramps.List of the variance source names (see
Simulation.get_cube).Scene instance
Spectrograph instance
Detector instance
Extraction parameters
telescope
- change_pointsource(pointsource)[source]#
Override the considered pointsource.
- Parameters:
pointsource (
PointSource) – New pointsource to be used.- Returns:
- change_spectrograph_resolution(rmin, spotsize=2)[source]#
Change the spectrograph’s spectral resolution.
This updates the spectrograph dispersion configuration (
dispersion_scale,dispersion_resolutionandspotsize) so that the resulting minimal resolving power scales withrmin. The reference is a dispersion resolution of 2 pixels forrmin=100, such thatdispersion_scale = 1.3 * (rmin / 100) * (spotsize / 2).- Parameters:
- Returns:
None– Updates the simulation in place (seeSimulation.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 (
floator array_like, optional) – Input flux. Default is 1 (returns the conversion factor).
- Returns:
floatornumpy.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 rampsnrampsare varied to reachtarget_snr(seeSimulation.get_band_snr):if a single ramp with
max_groupgroups is enough, a single ramp is used and its number of groups is optimised (usingnframe_per_group_smallframes per group, or even single-frame groups, for bright targets);otherwise, full ramps of
max_groupgroups are used and the number of ramps (at least 2) is optimised. Ifallow_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 (
intorNone, optional) – Maximum number of groups per ramp. If None,detector.max_groupis used. Default is None.nframe_per_group (
intorNone, 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 (
listofint, 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 (seetoo_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) abovetarget_snrtriggering the reduction of the number of groups. Ignored ifallow_smaller_rampsis False. Default is 1.ndrop (
intorNone, optional) – Number of dropped frames. If None, the current one is used. Default is None.guess (
intorNone, 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 (
listoffloat, optional) – (wmin, wmax) test wavelength range [Angstrom]. Default is[4000, 6800].frame (
str, optional) – Wavelength frame oflbda_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 isnumpy.nanmean.reset_param (
bool, optional) – If True, the simulation is set back to its inputnmdandnramps. 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:
config (
dict) – Configuration reaching the SNR, with keys"nmd"and"nramps"(to be given toSimulation.update).snr (
float) – Reached SNR.observing_time (
float) – Total observing time of this configuration [s] (seeSimulation.observing_time).
- 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 byget_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 bySimulation.reset.slicer (
bool, optional) – If True, use aSlicerSpectrograph, otherwise aMLASpectrograph. 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 (
nmdandnramps) is then set to reach the requested SNR on the pointsource, unlesssnris None.- Parameters:
redshift (
floatorNone, optional) – Redshift of the pointsource. If None, the one from the scene configuration is used. Default is None.snr (
floatorNone, optional) – Targeted average SNR per wavelength bin (seelbda_rangeandframe), reached usingSimulation.fetch_snr. If None, the exposure configuration is not changed. Default is 20.lbda_range (
listoffloat, optional) – (wmin, wmax) wavelength range where the SNR is estimated [Angstrom]. Default is[4000, 6800].frame (
str, optional) – Wavelength frame oflbda_range("obs"or"rest"). Default is"rest".scene (
str,dictorlist, optional) – Scene configuration (seeget_config). Default is"supernova.toml".instrument (
str,dictorlist, optional) – Instrument configuration (seeget_config). Default is"lazuli_cbe.toml".slicer (
bool, optional) – If True, use aSlicerSpectrograph, otherwise aMLASpectrograph. Default is True.**kwargs – Goes to
Simulation.updateto 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 (
Sceneordict) – The scene to observe, either as a scene object or as a scene configuration dictionary.config (
dictorstr) – Instrument configuration containing the"telescope","spectrograph","detector"and"extraction"entries. If a str, it is loaded withget_config.slicer (
bool, optional) – If True, use aSlicerSpectrograph, otherwise aMLASpectrograph. 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 thefluxamplitude). If None,fluxis used as is. Default is None.band (
str, optional) – Name of the band used to compute the magnitude (should be known bysncosmo). Default is"bessellb".position (
tupleoffloat, optional) – Location of the point source within the IFU,(x, y)in spaxels. Default is(0, 0).instrument (
str,dictorlist, optional) – Configuration of the instrument (seeget_config). Default is"lazuli_cbe.toml".background (
str,dict,listorNone, optional) – Configuration of the (spatially flat) scene background. If None, no background is added. Default is"zodi".host (
str,dict,listorNone, optional) – Configuration of the (spatially structured) host component of the scene. If None, no host is added. Default is None.snr (
floatorNone, optional) – If not None, the simulation is set up (seeSimulation.fetch_snr) to reach this average SNR per wavelength bin overlbda_range. Default is None.lbda_range (
listoffloat, optional) – (wmin, wmax) wavelength range used to average the SNR [Angstrom]. Ignored ifsnris None. Default is[4000, 6800].frame (
str, optional) – Frame oflbda_range("obs"or"rest"). Ignored ifsnris None. Default is"obs".**kwargs – Goes to
Simulation.update.
- Returns:
Simulation– The loaded simulation.
See also
Simulation.from_sceneload 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_spectrumwhen the scene has no point source (e.g. a galaxy alone) or withof_host=True, and for the aperture photometry of a point source (method="aperture"), then centered on the point source.- Parameters:
aperture (
strorNone, 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_radiusoraperture_radius_insigma);"<n>-arcsec": aperture photometry (plain summation) within a radius ofnarcsec, e.g."1-arcsec";"<n>-kpc": aperture photometry within a radius ofnkpc (proper) at the scene redshift, e.g."2-kpc".
If None, the
apertureextraction parameter is used (default"1-arcsec"). Default is None.position (
tupleoffloat,strorNone, optional) –(x, y)aperture center, in spaxels, or"host"for the host position. If None, theaperture.positionextraction parameter is used (default"host"). Default is None.
- Returns:
- Raises:
ValueError – If
aperturecannot 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 (
floatorNone, 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 bynramps(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
unitis 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 (
tupleoffloatorlistoftuple) – (wmin, wmax) test wavelength range (or list of) [Angstrom].frame (
str, optional) – Wavelength frame oflbda_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 isnumpy.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:
signal (
floatornumpy.ndarray) – Signal per band [ADU].variance (
floatornumpy.ndarray) – Variance per band [ADU^2].
- Raises:
ValueError – If
frameis 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:
lbda_range (
tupleoffloatorlistoftuple) – (wmin, wmax) test wavelength range (or list of) [Angstrom].frame (
str, optional) – Wavelength frame oflbda_range("obs"or"rest"). Default is"obs".statistic (callable, optional) – Function applied on the test domain (see
Simulation.get_band_flux). Default isnumpy.nanmean.at_saturation (
float, optional) – Value returned if any detector pixel is saturated. Default isnumpy.inf.**kwargs – Goes to
Simulation.get_band_flux, then toSimulation.get_spectrum(e.g.switch_off).
- Returns:
floatornumpy.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:
lbda_range (
tupleoffloatorlistoftuple) – (wmin, wmax) test wavelength range (or list of) [Angstrom].frame (
str, optional) – Wavelength frame oflbda_range("obs"or"rest"). Default is"rest".statistic (callable, optional) – Function applied on the test domain (see
Simulation.get_band_flux). Default isnumpy.nanmean.
- Returns:
dict– Dictionary with keys"snr","exptime"and"inttime"(per ramp) and"obstime"(total) [s],"signal"[ADU],"variance"[ADU^2], and for each variance sourcesource, its variance contribution (keysource, [ADU^2]) and its fraction of the total variance (keyfrac_<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 (
strorlistofstr, optional) – Name of the variance sources to switch off, any ofSimulation.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 (
intorNone, optional) – Oversampling factor. Default is None.per_ramp (
bool, optional) – If True, the cubes are not multiplied bynramps(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 (seeSimulation.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_offis 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:
lbda (
numpy.ndarray) – Wavelength [Angstrom].flux (
numpy.ndarray) – Input flux [erg/s/cm^2/A].
- 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 (
floator array_like, optional) – The spatial NEA [spaxel^2]. If None, it is computed. Default is None.nea_pixels (
floator array_like, optional) – The pixel NEA [pixel]. If None, it is computed. Default is None.
- Returns:
floatornumpy.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 (
floator array_like, optional) – The spatial NEA [spaxel^2]. If None, it is computed. Default is None.nea_pixels (
floator array_like, optional) – The pixel NEA [pixel]. If None, it is computed. Default is None.
- Returns:
floatornumpy.ndarray– The estimated variance [ADU^2].- Warns:
UserWarning – If
spectrumis 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
metaentry) of one of the elements of the simulation, e.g.gainforSimulation.detector.gain. Theelement__nameformat is also accepted:elementis 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__emissivityforSimulation.spectrograph.optics).- Parameters:
which (
str,listofstrorNone, 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 thandefault. Default is True.
- Returns:
objectordict– Parameter value. Ifwhichis 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
nrampsramps.- Parameters:
flux (
floator array_like, optional) – Incident flux on the pixel [ph/s]. Default is 0.**kwargs – Goes to
estimate_pixel_signal.
- Returns:
floatornumpy.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 (
listofstr, 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 (
intorNone, 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 withcached=True(if any), otherwise compute and store it. The other arguments are then ignored. Default is False.**kwargs – Goes to the spectrograph
generate_pointsourceandgenerate_structured_backgroundmethods.
- 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_oversampledis 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:
lbda (
numpy.ndarray) – Wavelength [Angstrom].resolving_power (
numpy.ndarray) – Resolving power \(R\) (dimensionless).
- 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 (
intorNone, 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 bynramps(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_pointsourceandgenerate_structured_backgroundmethods.
- Returns:
dictornumpy.ndarray– Ifas_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:
ValueError – If
unitis unknown.NotImplementedError – If the scene has a host and
as_oversampledis True.
- 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 (
tupleoffloatorlistoftuple) – (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 oflbda_range("obs"or"rest"). Default is"obs".switch_off (
listofstr, optional) – Variance sources to switch off (seeSimulation.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 (
intorNone, 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 (seeSimulation.get_cube). Default is False.**kwargs – Goes to
Simulation.get_cube.
- Returns:
signal (
numpy.ndarray) – (nslice, ny, nx) signal [ADU].variance (
numpy.ndarray) – (nslice, ny, nx) variance [ADU^2].
- Raises:
ValueError – If
frameis neither"obs"nor"rest".
- get_snr(switch_off=[])[source]#
Get the signal-to-noise ratio spectrum.
- Parameters:
switch_off (
listofstr, optional) – Variance sources to switch off (seeSimulation.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 theapertureandaperture.positionextraction parameters (seeSimulation.get_aperture).The extraction
methodis 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_radiusoraperture_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"ifaperture="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
nrampsramps.- Parameters:
switch_off (
listofstr, optional) – Variance sources to switch off (seeSimulation.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 (
strorNone, optional) – Extraction method:"default","optimal"or"aperture"(see above). If None, themethodextraction 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 (seeSimulation.get_cube). Default is False.
- Returns:
lbda (
numpy.ndarray) – (nlbda,) wavelength [Angstrom].signal (
numpy.ndarray) – (nlbda,) signal [ADU].variance (
numpy.ndarray) – (nlbda,) variance [ADU^2].
- Raises:
ValueError – If
methodis 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"(seeSimulation.observing_time).
- get_variance_contribution(as_dataframe=True)[source]#
Estimate the noise contributions to the total spectrum variance.
Each source of
Simulation.variance_sourcesis switched off in turn to estimate its contribution per wavelength bin.- Parameters:
as_dataframe (
bool, optional) – If True, return apandas.DataFrame, otherwise a dict. Default is True.- Returns:
pandas.DataFrameordict– 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
metawhen loading the simulation (seeSimulation.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
whichis not a known element.
- show_config(axes=None, lbda_units=None, colors=['#194D80', '#A8B7C7'])[source]#
Show configuration (resolving power and throughput).
- Parameters:
axes (
tupleofmatplotlib.axes.AxesorNone, optional) – (axr, axt) axes for the resolving power and the throughput. If None, a new figure is created. Default is None.lbda_units (
strorNone, optional) – Units (understood byastropy.units) to convert the wavelength to. If None, Angstrom is used. Default is None.colors (
listofstr, 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 (
listofstr, optional) – Components to discard (seeSimulation.get_projected_scene). Default is[].spec_prop (
dict, optional) – Spectrum plot options (goes tomatplotlib.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 (
tupleoffloat, 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.FigureorNone, optional) – Figure to draw on. If None, a new one is created. Default is None.rest_lbda_range (
listoffloat, optional) – Rest-frame wavelength range [Angstrom]. Default is[4000, 7000].obs_lbda_ranges (
listoflistoffloat, 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 (
intorNone, optional) – If given, show oversampled images with this oversampling factor. Default is None.prop_slice (
dict, optional) – Goes toSimulation.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:
ax (
matplotlib.axes.AxesorNone, optional) – Axes to plot on. If None, a new figure is created. Default is None.switch_off (
listofstr, optional) – Variance sources to switch off (seeSimulation.get_cube). Default is[].snr (
bool, optional) – If True, add the SNR curve on a twin y-axis. Default is False.**kwargs – Goes to
matplotlib.axes.Axes.plot.
- 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.DataFrameorNone, optional) – Variance contributions, as returned byself.get_variance_contribution(as_dataframe=True)(seeSimulation.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 (
tupleoffloat, optional) – Figure size. Default is (7, 7).gridspec (
dict, optional) – Goes togridspec_kwofmatplotlib.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__phaseis understood aspointsource.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 ofSimulation.mutable_parameters, it is accepted.>>> sim.update(phase=-1)
For convenience and backward compatibility, you can use
target__in place ofpointsource__.- 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 updateextraction.
- 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’supdatemethod (or merged intoextraction).- Returns:
- Warns:
UserWarning – If a key of
configis 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