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 theapply_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. Ifassert_evenly_spaced=True
, then we check this is the case, and raise an error if arrays is not evenly spaced. If'resample'
, then we resamplew
andI
if needed. Recommended, but it takes some time.wunit (
'nm'
,'cm-1'
) β just for printing messages. However,w
andw_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
andI_slit
are expressed using the same spectral spacing (e.g. thatw
andw`_slit
have the same step in nm between two adjacent points). The minimal step between values ofw
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 ofw
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 thesame
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 FHWM 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
See also
- 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 axs 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()
andconvolve_with_slit()
for more info- Parameters
slit_function (tuple, or str) β
- If float:
generate slit function with FWHM of
slit_function
(inunit
)- 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'
, orNone
) β 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 ofSLIT_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. DefaultTrue
. Seerecenter_slit()
,crop_slit()
- Returns
wslit, Islit β wslit is in
return_unit
. Islit is normalized according tonorm_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 byint(Islit*dΞ½)
instead ofint(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]
See also
- 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
See also
- 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'
, orNone
) β 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 rangew_nm
, and dilate them withslit_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) DefaultNone
. For more details seeconvolve_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 wplot_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
- 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 removescrop_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 ifmode='valid'
crop_left, crop_right (int) β number of points to discard on each side if
mode='crop'
Values are replaced withnan
- 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 axs 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 axs 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.