radis.tools.slit moduleΒΆ

Routine ListingΒΆ

This module contains…

a function to convolve with a slit function, that can resample and correct for slit dilation:

This function is called directly by the Spectrum method apply_slit()

predefined slit functions generators (triangular, gaussian, etc… see SLIT_SHAPES) and experimental slit function importer:

functions to manipulate slit functions (plot, get_FWHM, get_effective_FWHM, recenter_slit, crop_slit):


SLIT_SHAPES = ['triangular', 'trapezoidal', 'gaussian'][source]ΒΆ

list of predefined slit shapes

Type:

list

convolve_with_slit(w, I, w_slit, I_slit, mode='valid', k=1, bplot=False, verbose=True, assert_evenly_spaced=True, wunit='', waveunit=None)[source]ΒΆ

Convolves spectrum (w,I) with instrumental slit function (w_slit, I_slit)

Returns a convolved spectrum on a valid range.

Check Notes section below for more details about its implementation.

This function is called directly from a Spectrum object with the apply_slit() method.

Warning

By default, convoluted spectra are thinner than non convoluted spectra, as spectra are cropped to remove boundary effects. See mode= to change this behaviour.

Parameters:
  • w, I (array) – theoretical spectrum (wavespace unit (nm / cm-1))

  • w_slit, I_slit (array) – instrumental slit function (wavespace unit (nm / cm-1)) It is recommended to truncate the input slit function to its minimum spectral extension (see Notes).

    Warning

    Both wavespaces have to be the same!

  • mode ('valid', 'same') – 'same': returns output of same length as initial spectra, but boundary effects are still visible.

    'valid': returns output of length len(spectra) - len(slit) + 1, assuming len(I_slit) < len(I), for which lines outside of the calculated range have no impact.

    Default 'valid'.

Other Parameters:
  • k (int) – order of spline interpolation. 3: cubic, 1: linear. Default 1.

  • bplot (boolean) – if True, plots the convolve slit function (for debugging)

  • verbose (boolean) – more blabla

  • assert_evenly_spaced (boolean, or 'resample') – for the convolution to be accurate, w should be evenly spaced. If assert_evenly_spaced=True, then we check this is the case, and raise an error if arrays is not evenly spaced. If 'resample', then we resample w and I if needed. Recommended, but it takes some time.

  • wunit ('nm', 'cm-1') – just for printing messages. However, w and w_slit should be in the same wavespace.

Returns:

w_conv, I_conv – convoluted quantity. w_conv is defined on a valid range (sides are cut) if mode='valid'

Return type:

arrays

Notes

The discrete convolution operation is defined as

\[(I * I_{slit})[n] = \sum_{m = -\infty}^{\infty} I[m] I_{slit}[n - m]\]

This numerical discrete convolution doesn’t take care of respecting the physical distances. Therefore we have to make sure that the I and I_slit are expressed using the same spectral spacing (e.g. that w and w`_slit have the same step in nm between two adjacent points). The minimal step between values of w is used to determine this reference spacing.

If the slit function covers a spectral interval much larger than its Full Width a Half Maximum (FWHM), it will potentially add non-zero elements in the sum and mix spectral features that are much further away from each other than the FWHM, as it would have been expected. For an experimental slit function, this also means introducing more noise and artificial broadening. It is thus recommended to truncate the input slit function to its minimum useful spectral range.

For instance, if you have an instrumental slit function that looks like so, we recommend to cut it where the vertical lines are drawn.

I_slit  ^
        |     |   _   |
        |     |  / \  |
        |     | /   \ |
       0|_____|/     \|________
      --|-----         --------->
            cut       cut        w_slit

When we apply a slit function, we should consider the contributions of spectral features outside of the initial spectral range (i.e. w[0] - FWHM, w[-1] + FWHM) that would matter to reproduce the entire spectrum. Those points are probably not taken into account during the simulation and it could be interesting to extend the spectral range of w when possible to gauge this contribution.

Since, we don’t have access to this extra points, we truncated the output spectrum to the spectral range we can trust (no missing information). The valid mode operates this truncation by cutting the edge of the spectrum ever a spectral width corresponding to the spectral width of the provided slit function. This is meant to remove incorrect points on the edge. We recommend using this mode. You can however access those removed points using the same mode (at your own risk).

Implementation of convolve_with_slit() is done in 5 steps:

  • Check input slit function: compare input slit spectral range to spectrum spectral range if ranges are comparable, check FWHM and send a warning.

  • Interpolate the slit function on the spectrum grid, resample it if not evenly spaced (in order to match physical distances)

  • Check slit aspect, plot slit if asked for

  • Convolve!

  • Remove boundary effects

crop_slit(w_slit, I_slit, verbose=True)[source]ΒΆ

Removes unnecessary zeros on the side for a faster convolution. (remove as many zeros on the left as on the right).

gaussian_slit(FWHM, wstep, center=0, norm_by='area', bplot=False, wunit='', calc_range=4, scale=1, footerspacing=0, waveunit=None)[source]ΒΆ

Generate normalized slit function

Parameters:
  • FWHM ((nm)) – full-width at half maximum

  • wstep ((nm)) – wavelength step

Other Parameters:
  • center ((nm)) – center wavelength for the wavelength axis of the slit function

  • norm_by ('area', 'max') – normalisation type. 'area' conserves energy. 'max' is what is done in Specair and changes units. Default 'area'

  • bplot (boolean) – plot normalized slit function (for debugging). Default False

  • wunit (β€˜β€™, β€˜nm’, β€˜cm-1’) – used for plot only. Slit function is generated assuming you use the correct wavespace. No conversions are made here.

  • calc_range (float (number of sigma)) – function broadening range expressed in number of standard deviation

  • scale (float) – multiply slit by an arbitrary factor. Default 1.

  • footerspacing (int) – spacing (footer) on left and right. Default 10

Returns:

w, I –

Slit function of shape:

          .-.
         /   \
        /     \
  _ _.-'       `-._ _
  0    [gaussian]   0
  :  :     :     :  :
-c-f -c    0     c  c+f          (c : calc_range)

Return type:

numpy arrays

with c cutoff in number of elements, f spacing on left & right

Notes

slit is generated with an odd number of elements and centered on its maximum. This may result in sightly different FWHM if wstep is too large.

get_FWHM(w, I, return_index=False)[source]ΒΆ

Calculate full width half maximum (FWHM) by comparing amplitudes

Parameters:
  • w, I (arrays)

  • return_index (boolean) – if True, returns indexes for half width boundaries. Default False

Returns:

  • FWHM (float) – full width at half maximum

  • [xmin, xmax] (int)

get_effective_FWHM(w, I)[source]ΒΆ

Calculate full-width-at-half-maximum (FWHM) of a triangular slit of same area and height 1

Parameters:

w, I (arrays)

Returns:

fwhm – effective FWHM

Return type:

float

get_slit_function(slit_function, unit='nm', norm_by='area', shape: ['triangular', 'trapezoidal', 'gaussian'] = 'triangular', center_wavespace=None, return_unit='same', wstep=None, plot=False, resfactor=2, verbose=True, auto_recenter_crop=True, *args, **kwargs)[source]ΒΆ

Import or generate slit function in correct wavespace Give a file path to import, or a float / tuple to generate arbitrary shapes

Warning with units: read about unit and return_unit parameters.

See apply_slit() and convolve_with_slit() for more info

Parameters:
  • slit_function (tuple, or str) –

    If float:

    generate slit function with FWHM of slit_function (in unit)

    If .txt file:

    import experimental slit function (in unit): format must be 2-columns with wavelengths and intensity (doesn’t have to be normalized)

  • unit (β€˜nm’ or β€˜cm-1’) – unit of slit_function FWHM, or unit of imported file

  • norm_by ('area', 'max', or None) – how to normalize. 'area' conserves energy. With 'max' the slit is normalized at peak so that the maximum is one.

    Note

    'max' changes the unit of the spectral array, e.g. from 'mW/cm2/sr/Β΅m' to 'mW/cm2/sr')

    None doesnt normalize. Default 'area'

  • shape ('triangular', 'trapezoidal', 'gaussian') – which shape to use when generating a slit. Default 'triangular'. Should be one of SLIT_SHAPES.

  • center_wavespace (float, or None) – center of slit when generated (in unit). Not used if slit is imported.

  • return_unit ('nm', 'cm-1', or 'same') – if not 'same', slit is converted to the given wavespace. Default 'same'.

  • wstep (float) – which discretization step to use (in return_unit) when generating a slit function. Not used if importing

Other Parameters:
  • resfactor (int) – resolution increase when resampling from nm to cm-1, or the other way round. Default 2.

  • energy_threshold (float) – tolerance fraction. Only used when importing experimental slit as the theoretical slit functions are directly generated in spectrum wavespace Default 1e-3 (0.1%)

  • auto_recenter_crop (bool) – if True, recenter slit and crop zeros on the side when importing an experimental slit. Default True. See recenter_slit(), crop_slit()

Returns:

wslit, Islit – wslit is in return_unit . Islit is normalized according to norm_by

Return type:

array

Examples

>>> wslit, Islit = get_slit_function(1, 'nm', shape='triangular',
center_wavespace=600, wstep=0.01)

Returns a triangular slit function of FWHM = 1 nm, centered on 600 nm, with a step of 0.01 nm

>>> wslit, Islit = get_slit_function(1, 'nm', shape='triangular',
center_wavespace=600, return_unit='cm-1', wstep=0.01)

Returns a triangular slit function expressed in cm-1, with a FWHM = 1 nm (converted in equivalent width in cm-1 at 600 nm), centered on 600 nm, with a step of 0.01 cm-1 (!)

Notes

In norm_by='max' mode, slit is normalized by slit max. In RADIS, this is done in the spectrum wavespace (to avoid errors that would be caused by interpolating the spectrum).

A problem arise if the spectrum wavespace is different from the slit wavespace: typically, slit is in 'nm' but a spectrum calculated by RADIS is stored in 'cm-1': in that case, the convoluted spectrum is divided by int(Islit*dΞ½) instead of int(Islit*dΞ»). The output unit is then [radiance]*[spec_unit] instead of [radiance]*[slit_unit], i.e. typically, [mW/cm2/sr/nm]*[cm-1] instead of [mW/cm2/sr/nm]*[nm]=[mW/cm2/sr]

While this remains true if the units are taken into account, this is not the expected behaviour. For instance, Specair users are used to having a FWHM(nm) factor between spectra convolved with slit normalized by max and slit normalized by area.

The norm_by='max' behaviour adds a correction factor `/int(Islit*dΞ»)/int(Islit*dΞ½)` to maintain an output spectrum in [radiance]*[slit_unit]

import_experimental_slit(slit, norm_by='area', bplot=False, wunit='nm', auto_recenter=True, auto_crop=True, center=None, scale=1, verbose=True, waveunit=None)[source]ΒΆ

Import instrumental slit function and normalize it

Parameters:
  • slit (str or numpy object (wslit, Islit)) – slit function spectrum. If str, the slit is loaded from the corresponding file with:

    w_slit, I_slit = np.loadtxt(slit).T
    
  • norm_by (None, 'area', 'max') – normalisation type. 'area' divides by the area (conserves energy / units are unchanged). 'max' divides by the peak value (similar to what is done in Specair / changes units). None does not normalize the experimental slit function. Default 'area'

  • bplot (boolean) – plot normalized slit function (for debugging). Default False

  • wunit ('nm', 'cm-1') – used for plot only. Slit function is generated assuming you use the correct wavespace. No conversions are made here. Default 'nm'

Other Parameters:
  • auto_recenter (bool) – if True, recenters the slit on the maximum calculated from the two FWHM limits. To recenter, zeros are added on the shorter side (zero padding) Default True

  • auto_crop (bool) – If True, remove unnecessary zeros on the side for a faster convolution. (remove as many zeros on the left as on the right). Default True

  • center (float, None) – normally the slit instrumental slit function is centered on where it was measured. If not None, center overwrites the center and offsets the slit to the given value. Default None

  • scale (float) – multiply slit by an arbitrary factor. Default 1.

  • verbose (boolean) – Display messages

Returns:

w_slit, I_slit – wavelength and intensity of normalized slit function

Return type:

numpy arrays

normalize_slit(w_slit, I_slit, norm_by='area')[source]ΒΆ

Normalize slit function with different normalization modes. Warning, some change units after convolution!

Parameters:
  • w_slit, I_slit (np.array) – wavelength and slit intensity

  • norm_by ('area', 'max', or None) – how to normalize. 'area' conserves energy. With 'max' the slit is normalized at peak so that the maximum is one.

    Note

    'max' changes the unit of the spectral array, e.g. from 'mW/cm2/sr/Β΅m' to 'mW/cm2/sr')

    None doesnt normalize. Default 'area'

Returns:

w_slit, I_slit – wavelength, and normalized slit intensity

Return type:

np.array

offset_dilate_slit_function(w_slit_nm, I_slit, w_nm, slit_dispersion, threshold=0.01, verbose=True)[source]ΒΆ

Offset the slit wavelengths w_slit_nm to the center of range w_nm, and dilate them with slit_dispersion(w0)

Parameters:
  • w_slit_nm (np.array) – wavelength

    Warning

    slit_dispersion is assumed to be in wavelength. Warning if you’re applying this to an array stored in wavenumbers: don’t forget to convert.

  • I_slit (np.array) – slit intensity

  • w_nm (np.array) – wavelength whose center is used to center the slit function

  • slit_dispersion (func of (lambda), or None) – spectrometer reciprocal function : dΞ»/dx(Ξ») If not None, then the slit_dispersion function is used to correct the slit function for the whole range. Can be important if slit function was measured far from the measured spectrum (e.g: a slit function measured at 632.8 nm will look broader at 350 nm because the spectrometer dispersion is higher at 350 nm. Therefore it should be corrected) Default None. For more details see convolve_with_slit()

Other Parameters:

threshold (float) – if not None, check that slit dispersion is about constant (< threshold change) on the calculated range. Default 0.01 (1%)

Returns:

w_slit, I_slit – dilated wavelength (or wavenumber), slit intensity (renormalized)

Return type:

np.array

plot_slit(w, I=None, wunit='', plot_unit='same', Iunit=None, warnings=True, ls='-', title=None, waveunit=None)[source]ΒΆ

Plot slit, calculate and display FWHM, and calculate effective FWHM. FWHM is calculated from the limits of the range above the half width, while FWHM is the equivalent width of a triangular slit with the same area

Parameters:
  • w, I (arrays or (str, None)) – if str, open file directly

  • waveunit ('nm', 'cm-1' or '') – unit of input w

  • plot_unit ('nm', 'cm-1' or 'same') – change plot unit (and FWHM units)

  • Iunit (str, or None) – give Iunit

  • warnings (boolean) – if True, test if slit is correctly centered and output a warning if it is not. Default True

Returns:

fix, ax – figure and ax

Return type:

matplotlib objects

Examples

Slit Function

Slit Function
recenter_slit(w_slit, I_slit, verbose=True)[source]ΒΆ

Recenters the slit on the maximum calculated from the two FWHM limits. To recenter, zeros are added on the shorter side (zero padding)

remove_boundary(w, I_conv, mode, len_I=None, len_I_slit_interp=None, crop_left=None, crop_right=None)[source]ΒΆ

Crop convoluted array to remove boundary effects

Parameters:
  • w, I_conv (numpy array) – wavelength and intensity of already convoluted quantity (ex: radiance)

  • mode ('valid', 'same', ''crop') – 'same' returns output of same length as initial spectra, but boundary effects are still visible. 'valid' returns output of length len(spectra) - len(slit) + 1, for which lines outside of the calculated range have no impact. 'crop' just removes crop_wings points on the side.

Other Parameters:
  • len_I, len_I_slit_interp (int) – length of initial quantity (ex: radiance_noslit) and length of slit function intensity, before convolution. Needed to determine the valid range if mode='valid'

  • crop_left, crop_right (int) – number of points to discard on each side if mode='crop' Values are replaced with nan

Returns:

w_conv, I_conv – cropped waverange and quantity

Return type:

numpy arrays

Notes

Note

new in 0.9.30 : remove_boundary replaces off-range values with nan but keeps the same array size.

trapezoidal_slit(top, base, wstep, center=0, norm_by='area', bplot=False, wunit='', scale=1, footerspacing=0, waveunit=None)[source]ΒΆ

Build a trapezoidal slit. Remember that FWHM = (top + base) / 2

Parameters:
  • top ((nm)) – top of the trapeze

  • base ((nm)) – base of the trapeze

  • wstep ((nm)) – wavelength step

Other Parameters:
  • center ((nm)) – center wavelength for the wavelength axis of the slit function

  • norm_by ('area', 'max') – normalisation type. 'area' conserves energy. 'max' is what is done in Specair and changes units. Default 'area'

  • bplot (boolean) – plot normalized slit function (for debugging). Default False

  • waveunit (β€˜β€™, β€˜nm’, β€˜cm-1’) – used for plot only. Slit function is generated assuming you use the correct wavespace. No conversions are made here.

  • scale (float) – multiply slit by an arbitrary factor. Default 1.

  • footerspacing (int) – spacing (footer) on left and right. Default 10.

Returns:

w, I –

Slit function of shape:

          _______
         /       \
        / :     : \
  _ _ _/  :     :  \____
  0    :  :     :  :   0
  :   -b  :     :  b   :
-b-f     -t     t     b+f

Return type:

numpy arrays

with t`and `b the half-top and half-base in number of elements, f spacing on left & right. FWHM = (t+b+1)*wstep

Notes

slit is generated with an odd number of elements and centered on its maximum. This may result in sightly different FWHM if wstep is too large. However, slit is corrected so that effective FWHM is preserved.

triangular_slit(FWHM, wstep, center=0, norm_by='area', bplot=False, wunit='', scale=1, footerspacing=0, waveunit=None)[source]ΒΆ

Generate normalized slit function

Parameters:
  • FWHM ((nm)) – full-width at half maximum

  • wstep ((nm)) – wavelength step

  • center ((nm)) – center wavelength for the wavelength axis of the slit function

  • norm_by ('area', 'max') – normalisation type. 'area' conserves energy. 'max' is what is done in Specair and changes units. Default 'area'

  • bplot (boolean) – plot normalized slit function (for debugging). Default False

  • wunit (β€˜β€™, β€˜nm’, β€˜cm-1’) – used for plot only. Slit function is generated assuming you use the correct wavespace. No conversions are made here.

  • scale (float) – multiply slit by an arbitrary factor. Default 1.

  • footerspacing (int) – spacing (footer) on left and right. Default 10.

Returns:

w, I –

Slit function of shape:

        ^
       / \
  _ _ /   \ _ _
 :   :  :  :   :
-a-f -a 0  a  a+f

Return type:

numpy arrays

with FWHM = (a+1/2)*wstep, f spacing on left & right

Notes

slit is generated with an odd number of elements and centered on its maximum. This may result in sightly different FWHM if wstep is too large. However, slit is corrected so that effective FWHM is preserved.