radis package

Subpackages

Module contents

       *(((((((
        ((((((((((((              ,(((((
        ((((((((((((((((/   *((((((((((*
         ((((((((((((((((( ((((((((((((
             (((((((( (((((((((((((
                *
              @@  *@@       ..  /@@
         @@&  @@  *@@       @@  /@@  @@%
     @@  @@&  @@  *@@  @@&  @@  /@@  @@%  @@
     @@  @@&  @@  *@@  @@&  @@  /@@  @@%  @@
     @@  @@&  @@  *@@  @@&  @@  /@@  @@%  @@  (@
,@   @@  @@&  @@  *@@  @@&  @@  /@@  @@%  @@
@@   @@  @@&  @@  ,.
                           ,%&&&&&&&&&&&&&&&&&&&
 &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
  &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
    &&&&&&&&&&&&&&&&@@@@@@&@@@&&&@@@&&&&&&&&
      &&&&&&&&&&&&&&&@@@@@@&&&&&&&&&&&&&&&
        &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
          &&&&&&&&&&&&&&&&&&&&&&&&&&&.
              &&&&&&&&&&&&&&&&&&&
                      .**.
                       &&&,
                        &&
class LevelsList(parfunc, bands, levelsfmt, sortby='Ei', copy_lines=False, verbose=True)[source]

Bases: object

A class to generate a Spectrum from a list of precalculated bands at a given reference temperature.

Warning

only valid under optically thin conditions!!

E_bands[source]
Qref[source]
Qvib_ref[source]
Trot_ref[source]
Tvib_ref[source]
bands[source]
bands_ref[source]
copy_lines[source]
cum_weight[source]
eq_spectrum(Tgas, overpopulation=None, mole_fraction=None, path_length=None, save_rescaled_bands=False)[source]

See eq_spectrum()

Warning

only valid under optically thin conditions!!

Parameters
  • … same as usually. If None, then the reference value (used to

  • calculate bands) is used

Other Parameters

save_rescaled_bands (boolean) – save updated bands. Take some time as it requires rescaling all bands individually (which is only done on the MergedSlabs usually) Default False

levelsfmt[source]
lvl_index[source]
mole_fraction_ref[source]
non_eq_spectrum(Tvib=None, Trot=None, Ttrans=None, vib_distribution='boltzmann', overpopulation=None, mole_fraction=None, path_length=None, save_rescaled_bands=False)[source]

See non_eq_spectrum()

Warning

only valid under optically thin conditions!!

Parameters
  • … same as usually. If None, then the reference value (used to

  • calculate bands) is used

Other Parameters

save_rescaled_bands (boolean) – save updated bands. Take some time as it requires rescaling all bands individually (which is only done on the MergedSlabs usually) Default False

Notes

Implementation:

Generation of a new spectrum is done by recombination of the precalculated bands with

parfunc[source]
path_length_ref[source]
plot_vib_populations(nfig=None, **kwargs)[source]

Plot current distribution of vibrational levels.

By constructions populations are shown as divided by the state degeneracy, i.e, g = gv * (2J+1) * gi * gs

Parameters
  • nfig (str, int) – name of Figure to plot on

  • kwargs (**dict) – arguments are forwarded to plot()

sorted_bands[source]
verbose[source]
vib_distribution_ref[source]
vib_levels[source]
MergeSlabs(*slabs, **kwargs) Spectrum[source]

Combines several slabs into one. Useful to calculate multi-gas slabs. Linear absorption coefficient is calculated as the sum of all linear absorption coefficients, and the RTE is recalculated to get the total radiance. You can also simply use:

s1//s2

Merged spectrum 1+2 is calculated with Eqn (4.3) of the [RADIS-2018] article, generalized to N slabs :

\[ \begin{align}\begin{aligned}j_{\lambda, 1+2} = j_{\lambda, 1} + j_{\lambda, 2}\\k_{\lambda, 1+2} = k_{\lambda, 1} + k_{\lambda, 2}\end{aligned}\end{align} \]

where

\[j_{\lambda}, k_{\lambda}\]

are the emission coefficient and absorption coefficient of the two slabs 1 and 2. Emission and absorption coefficients are calculated if not given in the initial slabs (if possible).

Parameters

slabs (list of Spectra, each representing a slab) – path_length must be given in Spectrum conditions, and equal for all spectra.

line-of-sight:

slabs
            [0]        \====
light       [1]  ->     )===  observer
            [n]        /====
Other Parameters
  • kwargs input

  • resample ('never', 'intersect', 'full') – what to do when spectra have different wavespaces:

    • If 'never', raises an error

    • If 'intersect', uses the intersection of all ranges, and resample spectra on the most resolved wavespace.

    • If 'full', uses the overlap of all ranges, resample spectra on the most resolved wavespace, and fill missing data with 0 emission and 0 absorption

    Default 'never'

  • out ('transparent', 'nan', 'error') – what to do if resampling is out of bounds:

    • 'transparent': fills with transparent medium.

    • 'nan': fills with nan.

    • 'error': raises an error.

    Default 'nan'

  • optically_thin (boolean) – if True, merge slabs in optically thin mode. Default False

  • verbose (boolean) – if True, print messages and warnings. Default False

  • modify_inputs (False) – if True, slabs are modified directly when they are resampled. This avoids making a copy so is slightly faster. Default False.

Returns

Spectrum – observed at the output. Conditions and units are transported too, unless there is a mismatch then conditions are dropped (and units mismatch raises an error because it doesnt make sense)

Return type

object representing total emission and total transmittance as

Examples

Merge two spectra calculated with different species (physically correct only if broadening coefficients dont change much):

from radis import calc_spectrum, MergeSlabs
s1 = calc_spectrum(...)
s2 = calc_spectrum(...)
s3 = MergeSlabs(s1, s2)

The last line is equivalent to:

s3 = s1//s2

Load a spectrum precalculated on several partial spectral ranges, for a same molecule (i.e, partial spectra are optically thin on the rest of the spectral range):

from radis import load_spec, MergeSlabs
spectra = []
for f in ['spec1.spec', 'spec2.spec', ...]:
    spectra.append(load_spec(f))
s = MergeSlabs(*spectra, resample='full', out='transparent')
s.update()   # Generate missing spectral quantities
s.plot()
Calculate a large spectrum by part

Calculate a large spectrum by part

Calculate a large spectrum by part
PerfectAbsorber(s: Spectrum) Spectrum[source]

Makes a new Spectrum with the same transmittance/absorbance as Spectrum s, but with radiance set to 0. Useful to get contribution of different slabs in line-of-sight calculations (see example).

Parameters

s (Spectrum) – Spectrum object

Returns

s_trSpectrum object, with only the transmittance, absorbance and/or abscoeff part of s, where radiance_noslit , emisscoeff and emissivity_noslit (if they exist) have been set to 0

Return type

Spectrum

Examples

Let’s say you have a total line of sight:

s_los = s1 > s2 > s3

If you now want to get the contribution of s2 to the line-of-sight emission, you can do:

(s2 > PerfectAbsorber(s3)).plot('radiance_noslit')

And the contribution of s1 would be:

(s1 > PerfectAbsorber(s2>s3)).plot('radiance_noslit')

See more examples in Line-of-Sight module

Radiance(s: Spectrum) Spectrum[source]

Returns a new Spectrum with only the radiance component of s

Parameters

s (Spectrum) – Spectrum object

Returns

s_trSpectrum object, with only radiance defined

Return type

Spectrum

Examples

This function is useful to use Spectrum algebra operations:

s = calc_spectrum(...)   # contains emission & absorption arrays
rad = Radiance(s)        # contains radiance array only
rad -= 0.1    # arithmetic operation is applied to Radiance only

Equivalent to:

rad = s.take('radiance')
Radiance_noslit(s: Spectrum) Spectrum[source]

Returns a new Spectrum with only the radiance_noslit component of s

Parameters

s (Spectrum) – Spectrum object

Returns

s_trSpectrum object, with only radiance_noslit defined

Return type

Spectrum

Examples

This function is useful to use Spectrum algebra operations:

s = calc_spectrum(...)   # contains emission & absorption arrays
rad = Radiance_noslit(s) # contains 'radiance_noslit' array only
rad -= 0.1    # arithmetic operation is applied to Radiance_noslit only

Equivalent to:

rad = s.take('radiance_noslit')
SerialSlabs(*slabs: Spectrum, **kwargs: dict) Spectrum[source]

Adds several slabs along the line-of-sight. If adding two slabs only, you can also use:

s1>s2

Serial spectrum 1>2 is calculated with Eqn (4.2) of the [RADIS-2018] article, generalized to N slabs :

\[ \begin{align}\begin{aligned}I_{\lambda, 1>2} = I_{\lambda, 1} \tau_{\lambda, 2} + I_{\lambda, 2}\\\tau_{\lambda, 1+2} = \tau_{\lambda, 1} \cdot \tau_{\lambda, 2}\end{aligned}\end{align} \]

where

\[I_{\lambda}, \tau_{\lambda}\]

are the radiance and transmittance of the two slabs 1 and 2. Radiance and transmittance are calculated if not given in the initial slabs (if possible).

Parameters
  • slabs (list of Spectra, each representing a slab) –

    line-of-sight:

    slabs       [0]     [1]  ............... [n]
                 :       :                    :         \====
    light        *   ->  *        ->          *    ->    )===  observer
                                                        /====
    
  • resample_wavespace ('never', 'intersect', 'full') – what to do when spectra have different wavespaces:

    • If 'never', raises an error

    • If 'intersect', uses the intersection of all ranges, and resample spectra on the most resolved wavespace.

    • If 'full’, uses the overlap of all ranges, resample spectra on the most resolved wavespace, and fill missing data with 0 emission and 0 absorption

    Default 'never'

  • out ('transparent', 'nan', 'error') – what to do if resampling is out of bounds:

    • 'transparent': fills with transparent medium.

    • 'nan': fills with nan.

    • 'error': raises an error.

    Default 'nan'

Other Parameters
  • verbose (bool) – if True, more blabla. Default False

  • modify_inputs (False) – if True, slabs wavelengths/wavenumbers are modified directly when they are resampled. This avoids making a copy so it is slightly faster. Default False.

    Note

    for large number of slabs (in radiative transfer calculations) you surely want to use this option !

Returns

Spectrum – observed at the output (slab[n+1]). Conditions and units are transported too, unless there is a mismatch then conditions are dropped (and units mismatch raises an error because it doesnt make sense)

Return type

object representing total emission and total transmittance as

Examples

Add s1 and s2 along the line of sight: s1 –> s2:

s1 = calc_spectrum(...)
s2 = calc_spectrum(...)
s3 = SerialSlabs(s1, s2)

The last line is equivalent to:

s3 = s1>s2
class SpecDatabase(path='.', filt='.spec', add_info=None, add_date='%Y%m%d', verbose=True, binary=True, nJobs=-2, batch_size='auto', lazy_loading=True, update_register_only=False)[source]

Bases: SpecList

A Spectrum Database class to manage them all.

It basically manages a list of Spectrum JSON files, adding a Pandas dataframe structure on top to serve as an efficient index to visualize the spectra input conditions, and slice through the Dataframe with easy queries

Similar to SpecList, but associated and synchronized with a folder

Parameters
  • path (str) – a folder to initialize the database

  • filt (str) – only consider files ending with filt. Default .spec

  • binary (boolean) – if True, open Spectrum files as binary files. If False and it fails, try as binary file anyway. Default False.

  • lazy_loading (bool``) – If True, load only the data from the summary csv file and the spectra will be loaded when accessed by the get functions. If False, load all the spectrum files. If True and the summary .csv file does not exist, load all spectra

Other Parameters
  • *input for :class:`~joblib.parallel.Parallel` loading of database*

  • nJobs (int) – Number of processors to use to load a database (usefull for big databases). BE CAREFULL, no check is done on processor use prior to the execution ! Default -2: use all but 1 processors. Use 1 for single processor.

  • batch_size (int or 'auto') – The number of atomic tasks to dispatch at once to each worker. When individual evaluations are very fast, dispatching calls to workers can be slower than sequential computation because of the overhead. Batching fast computations together can mitigate this. Default: 'auto'

  • More information in :class:`joblib.parallel.Parallel`

Examples

>>> db = SpecDatabase(r"path/to/database")     # create or loads database

>>> db.update()  # in case something changed
>>> db.see(['Tvib', 'Trot'])   # nice print in console

>>> s = db.get('Tvib==3000')[0]  # get a Spectrum back
>>> db.add(s)  # update database (and raise error because duplicate!)

Note that SpectrumFactory can be configured to automatically look-up and update a database when spectra are calculated.

The function to auto retrieve a Spectrum from database on calculation time is a method of DatabankLoader class

You can see more examples on the Spectrum Database section of the website.

Spectrum Database

Spectrum Database

Spectrum Database
add(spectrum: Spectrum, store_name=None, if_exists_then='increment', **kwargs)[source]

Add Spectrum to database, whether it’s a Spectrum object or a file that stores one. Check it’s not in database already.

Parameters

spectrum (Spectrum object, or path to a .spec file (str)) – if a Spectrum object: stores it in the database (using the store() method), then adds the file to the database folder. if a path to a file (str): first copy the file to the database folder, then loads the copied file to the database.

Other Parameters
  • store_name (str, or None) – name of the file where the spectrum will be stored. If None, name is generated automatically from the Spectrum conditions (see add_info= and if_exists_then=)

  • if_exists_then ('increment', 'replace', 'error', 'ignore') – what to do if file already exists. If 'increment' an incremental digit is added. If 'replace' file is replaced (!). If 'ignore' the Spectrum is not added to the database and no file is created. If 'error' (or anything else) an error is raised. Default 'increment'.

  • **kwargs (**dict) – extra parameters used in the case where spectrum is a file and a .spec object has to be created (useless if spectrum is a file already). kwargs are forwarded to Spectrum.store() method. See the store() method for more information.

    Note

    Other store() parameters can be given as kwargs arguments. See below :

  • compress (0, 1, 2) – if True or 1, save the spectrum in a compressed form

    if 2, removes all quantities that can be regenerated with update(), e.g, transmittance if abscoeff and path length are given, radiance if emisscoeff and abscoeff are given in non-optically thin case, etc. If not given, use the value of SpecDatabase.binary The performances are usually better if compress = 2. See https://github.com/radis/radis/issues/84.

  • add_info (list) – append these parameters and their values if they are in conditions example:

    nameafter = ['Tvib', 'Trot']
    
  • discard (list of str) – parameters to exclude. To save some memory for instance Default ['lines', 'populations']: retrieved Spectrum will loose the line_survey() and plot_populations() methods (but it saves a ton of memory!).

Examples

from radis.tools import SpecDatabase
db = SpecDatabase(r"path/to/database")     # create or loads database
db.add(s, discard=['populations'])

You can see more examples on the Spectrum Database section of the website.

Spectrum Database

Spectrum Database

Spectrum Database
compress_to(new_folder, compress=True, if_exists_then='error')[source]

Saves the Database in a new folder with all Spectrum objects under compressed (binary) format. Read/write is much faster. After the operation, a new database should be initialized in the new_folder to access the new Spectrum.

Parameters
  • new_folder (str) – folder where to store the compressed SpecDatabase. If doesn’t exist, it is created.

  • compress (boolean, or 2) – if True, saves under binary format. Faster and takes less space. If 2, additionaly remove all redundant quantities.

  • if_exists_then ('increment', 'replace', 'error', 'ignore') – what to do if file already exists. If 'increment' an incremental digit is added. If 'replace' file is replaced (!). If 'ignore' the Spectrum is not added to the database and no file is created. If 'error' (or anything else) an error is raised. Default 'error'.

find_duplicates(columns=None)[source]

Find spectra with same conditions. The first duplicated spectrum will be 'False', the following will be 'True' (see .duplicated()).

Parameters

columns (list, or None) – columns to find duplicates on. If None, use all conditions.

Examples

db.find_duplicates(columns={'x_e', 'x_N_II'})

Out[34]:
file
20180710_101.spec    True
20180710_103.spec    True
dtype: bool

You can see more examples in the Spectrum Database section

fit_spectrum(s_exp, residual=None, normalize=False, normalize_how='max', conditions='', **kwconditions)[source]

Returns the Spectrum in the database that has the lowest residual with s_exp.

Parameters

s_exp (Spectrum) – Spectrum to fit (typically: experimental spectrum)

Other Parameters
  • residual (func, or None) – which residual function to use. If None, use get_residual() with option ignore_nan=True and options normalize and normalize_how as defined by the user.

    get_residual should have the form:

    lambda s_exp, s, normalize: func(s_exp, s, normalize=normalize)
    

    where the output is a float. Default None

  • conditions, **kwconditions (str, **dict) – restrain fitting to only Spectrum that match the given conditions in the database. See get() for more information.

  • normalize (bool, or Tuple) – see get_residual()

  • normalize_how (‘max’, ‘area’) – see get_residual()

Returns

s_best – closest Spectrum to s_exp

Return type

Spectrum

Examples

Using a customized residual function (below: to get the transmittance):

from radis import get_residual
db = SpecDatabase('...')
db.fit_spectrum(s_exp, get_residual=lambda s_exp, s: get_residual(s_exp, s, var='transmittance'))

You can see more examples on the Spectrum Database section More advanced tools for interactive fitting of multi-dimensional, multi-slabs spectra can be found in fitroom.

See also

fitroom

interpolate(**kwconditions)[source]

Interpolate existing spectra from the database to generate a new spectrum with conditions kwargs

Examples

db.interpolate(Tgas=300, mole_fraction=0.3)
print_index(file=None)[source]
to_dict()[source]

Returns all Spectra in database under a dictionary, indexed by file.

Returns

out – {path : Spectrum object} dictionary

Return type

dict

Note

SpecList.items().values() is equivalent to SpecList.get()

update(force_reload=False, filt='.spec', update_register_only=False)[source]

Reloads database, updates internal index structure and export it in <database>.csv.

Parameters
  • force_reload (boolean) – if True, reloads files already in database. Default False

  • filt (str) – only consider files ending with filt. Default .spec

Other Parameters

update_register_only (bool) – if True, load files and update csv but do not keep the Spectrum in memory. Default False

Notes

Can be loaded in parallel using joblib by setting the nJobs and batch_size attributes of SpecDatabase. See joblib.parallel.Parallel for information on the arguments

update_conditions()[source]

Reloads conditions of all Spectrum in database.

class Spectrum(quantities, units=None, conditions=None, cond_units=None, populations=None, lines=None, wunit=None, name=None, references={}, check_wavespace=True, **kwargs)[source]

Bases: object

This class holds results calculated with the SpectrumFactory calculation, with other radiative codes, or experimental data. It can be used to plot different quantities a posteriori, or manipulate output units (for instance convert a spectral radiance per wavelength units to a spectral radiance per wavenumber).

See more information on how to generate, edit or combine Spectrum objects on the Spectrum object guide.

Parameters
  • quantities (dict of tuples {'quantity':(w, a)} or dict {'wavelength/wavenumber': w, quantity': a}) – where quantities are spectral quantities (absorbance, radiance, etc.) and wavenum is in \(cm^{-1}\) or \(nm\) (see waveunit) Example:

    # w, k, I are numpy arrays for wavenumbers, absorption coefficient, and radiance.
    from radis import Spectrum
    s = Spectrum({"wavenumber":w, "abscoeff":k, "radiance_noslit":I}, wunit='cm-1',
                 units={"radiance_noslit":"mW/cm2/sr/nm", "abscoeff":"cm-1"})
    

    Or:

    s = Spectrum({"abscoeff":(w,k), "radiance_noslit":(w,I)},
                 wunit="cm-1"
                 units={"radiance_noslit":"mW/cm2/sr/nm", "abscoeff":"cm-1"})
    

    See also: from_array() and from_txt()

  • units (dict) – units for quantities

Other Parameters
  • conditions (dict) – physical conditions and calculation parameters

  • wunit ('nm', 'cm-1', 'nm_vac' or None) – wavelength in air ('nm'), wavenumber ('cm-1'), or wavelength in vacuum ('nm_vac'). If None, 'wavespace' must be defined in conditions. Quantities should be evenly distributed along this space for fast convolution with the slit function

  • cond_units (dict) – units for conditions

Other Parameters
  • name (str, or None) – Give a name to this Spectrum object (automatically used in plots; useful for multislab configurations). Default None

  • populations (dict) – a dictionary of all species, and levels. Should be compatible with other radiative codes such as Specair output. Suggested format: {molecules: {isotopes: {elec state: rovib levels}}} e.g:

    {'CO2':{1: 'X': df}}   # with df a Pandas Dataframe
    
  • lines (pandas Dataframe) – all lines in databank (necessary for using line_survey()). Warning if you want to play with the lines content: The signification of columns in lines may be specific to a database format. Plus, some additional columns may have been added by the calculation (e.g: Ei and S for emission integral and linestrength in SpectrumFactory). Refer to the code to know what they mean (and their units)

  • references (dict) – a dict of doi of references used to compute this object. Automatically returned with the full bibtex entry by cite() It can also be set a posteriori. Example

    s = Spectrum()
    s.references = {"10.1016/j.jqsrt.2010.05.001": "HITEMP-2010 database",
                  "10.1016/j.jqsrt.2018.09.027":["calculation", "post-processing"],  # RADIS main paper. Automatically added
                  "10.1016/j.jqsrt.2020.107476":"DIT algorithm"}
                  )
    s.cite()
    
    Returns :
    Used for DIT algorithm
    ----------------------
    @article{van_den_Bekerom_2021,
        doi = {10.1016/j.jqsrt.2020.107476},
        url = {https://doi.org/10.1016%2Fj.jqsrt.2020.107476},
        year = 2021,
        month = {mar},
        publisher = {Elsevier {BV}},
        volume = {261},
        pages = {107476},
        author = {D.C.M. van den Bekerom and E. Pannier},
        title = {A discrete integral transform for rapid spectral synthesis},
        journal = {Journal of Quantitative Spectroscopy and Radiative Transfer}
    }
    
    Used for HITEMP-2010 database
    -----------------------------
    @article{Rothman_2010,
        doi = {10.1016/j.jqsrt.2010.05.001},
        url = {https://doi.org/10.1016%2Fj.jqsrt.2010.05.001},
        year = 2010,
        month = {oct},
        publisher = {Elsevier {BV}},
        volume = {111},
        number = {15},
        pages = {2139--2150},
        author = {L.S. Rothman and I.E. Gordon and R.J. Barber and H. Dothe and R.R. Gamache and A. Goldman and V.I. Perevalov and S.A. Tashkun and J. Tennyson},
        title = {{HITEMP}, the high-temperature molecular spectroscopic database},
        journal = {Journal of Quantitative Spectroscopy and Radiative Transfer}
    }
    
    Used for calculation, post-processing
    -------------------------------------
    @article{Pannier_2019,
        doi = {10.1016/j.jqsrt.2018.09.027},
        url = {https://doi.org/10.1016%2Fj.jqsrt.2018.09.027},
        year = 2019,
        month = {jan},
        publisher = {Elsevier {BV}},
        volume = {222-223},
        pages = {12--25},
        author = {Erwan Pannier and Christophe O. Laux},
        title = {{RADIS}: A nonequilibrium line-by-line radiative code for {CO}2 and {HITRAN}-like database species},
        journal = {Journal of Quantitative Spectroscopy and Radiative Transfer}
    }
    

    </details>

  • warnings (boolean) – if True, test if inputs are valid, e.g, spectra are evenly distributed in wavelength, and raise a warning if not. Note that this take ~ 3.5 ms for a 20k points spectrum, when the rest of the creation process is only ~ 1.8ms (makes it 3 times longer, and can be a problem if hundreds of spectra are created in a row). Default True

Examples

Manipulate a Spectrum calculated by RADIS:

s = calc_spectrum(2125, 2300, Tgas=2000, databank='CDSD')
s.print_conditions()
s.plot('absorbance')
s.line_survey(overlay='absorbance')
s.plot('radiance_noslit', wunits='cm-1', Iunits='W/m2/sr/cm-1')
s.apply_slit(5)
s.plot('radiance')
w, t = s.get('transmittance_noslit')  # for use in multi-slabs configs

Any tuple of numpy arrays (w, I) can also be converted into a Spectrum object from the Spectrum class directly, or using the calculated_spectrum() function. All the following methods are equivalent:

from radis import Spectrum, calculated_spectrum
s1 = calculated_spectrum(w, I, wunit='nm', Iunit='mW/cm2/sr/nm')
s2 = Spectrum.from_array(w, I, 'radiance_noslit',
                       wunit='nm', unit='mW/cm2/sr/nm')
s3 = Spectrum({'radiance_noslit': (w, I)},
              units={'radiance_noslit':'mW/cm2/sr/nm'},
              wunit='nm')

See more examples in the [Spectrum] page.

Spectrum objects can be stored, retrieved, rescaled, resampled:

from radis import load_spec
s = load_spec('co_calculation.spec')
s.rescale_path_length(0.5)                  # calculate for new path_length
s.rescale_mole_fraction(0.02)   # calculate for new mole fraction
s.resample(w_new)               # resample on new wavespace
s.store('co_calculation2.spec')

Notes

Implementation:

quantities are stored in the self._q dictionary. They are better accessed with the get() method that deals with units and wavespace

Wavebase:

quantites are stored either in wavenum or wavelength base, but this doesnt matter as they are retrieved / plotted with the get() and plot() methods which have units as input arguments

conditions[source]

Stores computation / measurement conditions

Type

dict

c[source]

convenience wrapper to conditions:

s.c["calculation_time"] is s.conditions["calculation_time"]
>> True
Type

dict

populations[source]

Stores molecules, isotopes, electronic states and vibrational or rovibrational populations

Type

dict

References

Spectrum

See the Spectrum object page

apply_slit(slit_function, unit='nm', shape: ['triangular', 'trapezoidal', 'gaussian'] = 'triangular', center_wavespace=None, norm_by='area', mode='valid', plot_slit=False, store=True, slit_dispersion=None, slit_dispersion_threshold=0.01, auto_recenter_crop=True, assert_evenly_spaced=True, verbose=True, inplace=True, *args, **kwargs)[source]

Apply an instrumental slit function to all quantities in Spectrum. Slit function can be generated with usual shapes (see shape=) or imported from an experimental slit function (path to a text file or numpy array of shape n*2). Convoluted spectra are cut on the edge compared to non-convoluted spectra, to remove side effects. See mode= to change this behaviour.

Warning with units: read about 'unit' and 'return_unit' parameters.

Parameters
  • slit_function (float or str or array) –

    If float:

    generate slit function with FWHM of slit function (in nm or cm-1 depending on unit=). A (top, base) tuple of (float, float) is required when asking for a trapezoidal slit function.

    If .txt:

    import experimental slit function from .txt file: format must be 2-columns with wavelengths and intensity (doesn’t have to be normalized)

    If array:

    format must be 2-columns with wavelengths and intensity (doesn’t have to be normalized) It is recommended to truncate the input slit function to its minimum useful spectral extension (see Notes of convolve_with_slit()).

  • unit ('nm' or 'cm-1') – unit of slit_function (FWHM, or imported file)

  • shape ('triangular', 'trapezoidal', 'gaussian', or any of SLIT_SHAPES) –

    which shape to use when generating a slit. Will call,

    respectively, triangular_slit(), trapezoidal_slit(), gaussian_slit(). Default ‘triangular’

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

  • norm_by ('area', 'max') – normalisation type: - 'area' normalizes the slit function to an area

    of 1. It conserves energy, and keeps the same units.

    • 'max' normalizes the slit function to a maximum of 1. The convoluted spectrum units change (they are multiplied by the spectrum waveunit, e.g: a radiance non convoluted in mW/cm2/sr/nm on a wavelength (nm). range will yield a convoluted radiance in mW/cm2/sr. Note that the slit is set to 1 in the Spectrum wavespace (i.e: a Spectrum calculated in cm-1 will have a slit set to 1 in cm-1).

    Default 'area'

  • 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, for which lines outside of the calculated range have no impact. Default 'valid'.

Other Parameters
  • 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.

  • 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()

  • plot_slit (boolean) – if True, plot slit

  • store (boolean) – if True, store slit in the Spectrum object so it can be retrieved with get_slit() and plot with plot_slit(). Default True

  • slit_dispersion (func of (lambda, in 'nm'), or None) – spectrometer reciprocal function : dλ/dx(λ) (in nm) 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

    Warning

    slit dispersion function is assumed to be given in nm if your spectrum is stored in cm-1 the wavenumbers are converted to wavelengths before being forwarded to the dispersion function

    See test_auto_correct_dispersion() for an example of the slit dispersion effect.

    A Python implementation of the slit dispersion:

    >>> def f(lbd):
    >>>    return  w/(2*f)*(tan(Φ)+sqrt((2*d/m/(w*1e-9)*cos(Φ))^2-1))
    

    Theoretical / References:

    >>> dλ/dx ~ d/mf    # at first order
    >>> dλ/dx = w/(2*f)*(tan(Φ)+sqrt((2*d/m/(w)*cos(Φ))^2-1))  # cf
    

    with:

    • Φ: spectrometer angle (°)

    • f: focal length (mm)

    • m: order of dispersion

    • d: grooves spacing (mm) = 1/gr with gr in (gr/mm)

    See Laux 1999 “Experimental study and modeling of infrared air plasma radiation” for more information

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

  • inplace (bool) – if True, adds convolved arrays directly in the Spectrum. If False, returns a new Spectrum with only the convolved arrays. Note: if you want a new Spectrum with both the convolved and non convolved quantities, use

    s.copy().apply_slit()
    
  • *args, **kwargs – are forwarded to slit generation or import function

  • verbose (bool) – print stuff

  • energy_threshold (float) – tolerance fraction when resampling. Default 1e-3 (0.1%) If areas before and after resampling differ by more than that an error is raised.

Returns

Spectrum – Allows chaining. If inplace=False, return a new Spectrum with the new spectral arrays only.

Return type

same Spectrum, with new spectral arrays.

Notes

Units:

the slit function is first converted to the wavespace (wavelength/wavenumber) that the Spectrum is stored in, and applied to the spectral quantities in their native wavespace.

Implementation:

convolve_with_slit() is applied to all quantities in get_vars() that ends with _noslit. Generate a triangular instrumental slit function (or any other shape depending of shape=) with base slit_function_base (Uses the central wavelength of the spectrum for the slit function generation)

We deal with several special cases (which makes the code a little heavy, but the method very versatile):

  • when slit unit and spectrum unit arent the same

  • when spectrum is not evenly spaced

Examples

s.apply_slit(1.2, 'nm')

This applies the instrumental function to all available spectral arrays. To manually apply the slit to a particular spectral array, use take()

s.take('transmittance_noslit').apply_slit(1.2, 'nm')

See convolve_with_slit() for more details on Units and Normalization

The slit is made considering the “center wavelength” which is the mean wavelength of the full spectrum you are applying it to.

Line Survey

Line Survey

Line Survey
GPU Accelerated Spectra

GPU Accelerated Spectra

GPU Accelerated Spectra
Calculate non-LTE spectra of carbon-monoxide

Calculate non-LTE spectra of carbon-monoxide

Calculate non-LTE spectra of carbon-monoxide
Calculate a spectrum from ExoMol

Calculate a spectrum from ExoMol

Calculate a spectrum from ExoMol
c[source]
cite(format='bibentry')[source]

Prints bibliographic references used to compute this spectrum, as stored in the references dictionary. Default references known to RADIS are listed in radis.db.references.doi.

Parameters

format (default 'bibentry'. See more in habanero.content_negotiation())

Examples

from radis import calc_spectrum
s = calc_spectrum(
    1900,
    2300,  # cm-1
    molecule="CO",
    isotope="1,2,3",
    pressure=1.01325,  # bar
    Tvib=2000,  #
    Trot=300,
    mole_fraction=0.1,
    path_length=1,  # cm
    databank="hitran",
)
s.cite()
Returns :
Used for algorithm
------------------
@article{van_den_Bekerom_2021,
    doi = {10.1016/j.jqsrt.2020.107476},
    url = {https://doi.org/10.1016%2Fj.jqsrt.2020.107476},
    year = 2021,
    month = {mar},
    publisher = {Elsevier {BV}},
    volume = {261},
    pages = {107476},
    author = {D.C.M. van den Bekerom and E. Pannier},
    title = {A discrete integral transform for rapid spectral synthesis},
    journal = {Journal of Quantitative Spectroscopy and Radiative Transfer}
}

Used for calculation, rovibrational energies
--------------------------------------------
@article{Pannier_2019,
    doi = {10.1016/j.jqsrt.2018.09.027},
    url = {https://doi.org/10.1016%2Fj.jqsrt.2018.09.027},
    year = 2019,
    month = {jan},
    publisher = {Elsevier {BV}},
    volume = {222-223},
    pages = {12--25},
    author = {Erwan Pannier and Christophe O. Laux},
    title = {{RADIS}: A nonequilibrium line-by-line radiative code for {CO}2 and {HITRAN}-like database species},
    journal = {Journal of Quantitative Spectroscopy and Radiative Transfer}
}

Used for data retrieval
-----------------------
@article{Ginsburg_2019,
    doi = {10.3847/1538-3881/aafc33},
    url = {https://doi.org/10.3847%2F1538-3881%2Faafc33},
    year = 2019,
    month = {feb},
    publisher = {American Astronomical Society},
    volume = {157},
    number = {3},
    pages = {98},
    author = {Adam Ginsburg and Brigitta M. Sip{\H{o}}cz and C. E. Brasseur and Philip S. Cowperthwaite and Matthew W. Craig and Christoph Deil and James Guillochon and Giannina Guzman and Simon Liedtke and Pey Lian Lim and Kelly E. Lockhart and Michael Mommert and Brett M. Morris and Henrik Norman and Madhura Parikh and Magnus V. Persson and Thomas P. Robitaille and Juan-Carlos Segovia and Leo P. Singer and Erik J. Tollerud and Miguel de Val-Borro and Ivan Valtchanov and Julien Woillez and},
    title = {astroquery: An Astronomical Web-querying Package in Python},
    journal = {The Astronomical Journal}
}

Used for line database
----------------------
@article{Gordon_2017,
    doi = {10.1016/j.jqsrt.2017.06.038},
    url = {https://doi.org/10.1016%2Fj.jqsrt.2017.06.038},
    year = 2017,
    month = {dec},
    publisher = {Elsevier {BV}},
    volume = {203},
    pages = {3--69},
    author = {I.E. Gordon and L.S. Rothman and C. Hill and R.V. Kochanov and Y. Tan and P.F. Bernath and M. Birk and V. Boudon and A. Campargue and K.V. Chance and B.J. Drouin and J.-M. Flaud and R.R. Gamache and J.T. Hodges and D. Jacquemart and V.I. Perevalov and A. Perrin and K.P. Shine and M.-A.H. Smith and J. Tennyson and G.C. Toon and H. Tran and V.G. Tyuterev and A. Barbe and A.G. Cs{\'{a}}sz{\'{a}}r and V.M. Devi and T. Furtenbacher and J.J. Harrison and J.-M. Hartmann and A. Jolly and T.J. Johnson and T. Karman and I. Kleiner and A.A. Kyuberis and J. Loos and O.M. Lyulin and S.T. Massie and S.N. Mikhailenko and N. Moazzen-Ahmadi and H.S.P. Müller and O.V. Naumenko and A.V. Nikitin and O.L. Polyansky and M. Rey and M. Rotger and S.W. Sharpe and K. Sung and E. Starikova and S.A. Tashkun and J. Vander Auwera and G. Wagner and J. Wilzewski and P. Wcis{\l}o and S. Yu and E.J. Zak},
    title = {The {HITRAN}2016 molecular spectroscopic database},
    journal = {Journal of Quantitative Spectroscopy and Radiative Transfer}
}

Used for partition function
---------------------------
@article{Gamache_2021,
    doi = {10.1016/j.jqsrt.2021.107713},
    url = {https://doi.org/10.1016%2Fj.jqsrt.2021.107713},
    year = 2021,
    month = {sep},
    publisher = {Elsevier {BV}},
    volume = {271},
    pages = {107713},
    author = {Robert R. Gamache and Bastien Vispoel and Michaël Rey and Andrei Nikitin and Vladimir Tyuterev and Oleg Egorov and Iouli E. Gordon and Vincent Boudon},
    title = {Total internal partition sums for the {HITRAN}2020 database},
    journal = {Journal of Quantitative Spectroscopy and Radiative Transfer}
}
@article{Kochanov_2016,
    doi = {10.1016/j.jqsrt.2016.03.005},
    url = {https://doi.org/10.1016%2Fj.jqsrt.2016.03.005},
    year = 2016,
    month = {jul},
    publisher = {Elsevier {BV}},
    volume = {177},
    pages = {15--30},
    author = {R.V. Kochanov and I.E. Gordon and L.S. Rothman and P. Wcis{\l}o and C. Hill and J.S. Wilzewski},
    title = {{HITRAN} Application Programming Interface ({HAPI}): A comprehensive approach to working with spectroscopic data},
    journal = {Journal of Quantitative Spectroscopy and Radiative Transfer}
}

Used for spectroscopic constants
--------------------------------
@article{Guelachvili_1983,
    doi = {10.1016/0022-2852(83)90203-5},
    url = {https://doi.org/10.1016%2F0022-2852%2883%2990203-5},
    year = 1983,
    month = {mar},
    publisher = {Elsevier {BV}},
    volume = {98},
    number = {1},
    pages = {64--79},
    author = {G. Guelachvili and D. de Villeneuve and R. Farrenq and W. Urban and J. Verges},
    title = {Dunham coefficients for seven isotopic species of {CO}},
    journal = {Journal of Molecular Spectroscopy}
}
Cite all references used

Cite all references used

Cite all references used

See also

RefTracker, doi

compare_with(other, spectra_only=False, plot=True, wunit='default', verbose=True, rtol=1e-05, ignore_nan=False, ignore_outliers=False, normalize=False, **kwargs)[source]

Compare Spectrum with another Spectrum object.

Parameters
  • other (type Spectrum) – another Spectrum to compare with

  • spectra_only (boolean, or str) – if True, only compares spectral quantities (in the same waveunit) and not lines or conditions. If str, compare a particular quantity name. If False, compare everything (including lines and conditions and populations). Default False

  • plot (boolean) – if True, use plot_diff to plot all quantities for the 2 spectra and the difference between them. Default True.

  • wunit ("nm", "cm-1", "default") – in which wavespace to compare (and plot). If "default", natural wavespace of first Spectrum is taken.

  • rtol (float) – relative difference to use for spectral quantities comparison

  • ignore_nan (boolean) – if True, nans are ignored when comparing spectral quantities

  • ignore_outliers (boolean, or float) –

    if not False, outliers are discarded. i.e, output is determined by:

    out = (~np.isclose(I, Ie, rtol=rtol, atol=0)).sum()/len(I) < ignore_outliers
    
  • normalize (bool) – Normalize the spectra to be ploted

Other Parameters

kwargs (dict) – arguments are forwarded to plot_diff()

Returns

equals – return True if spectra are equal (respective to tolerance defined by rtol and other input conditions)

Return type

boolean

Examples

Compare two Spectrum objects, or specifically the transmittance:

s1.compare_with(s2)
s1.compare_with(s2, 'transmittance')

Note that you can also simply use s1 == s2, that uses compare_with() internally:

s1 == s2       # will return True or False
cond_units[source]
conditions[source]

computation conditions, or experimetnal parameters, or any metadata you need to store with the Spectrum object.

Type

dict

copy(copy_lines=True, quantity='all', copy_arrays=True)[source]

Returns a copy of this Spectrum object (performs a smart deepcopy)

Parameters
  • copy_lines (bool) – default True

  • quantity (‘all’, or one of ‘radiance_noslit’, ‘absorbance’, etc.) – if not ‘all’, copy only one quantity. Default 'all'

  • copy_arrays (bool) – if False, returned array’s quantity is a pointer to the original Spectrum. Faster, but warning, changing them will then change the original Spectrum. Default True

Examples

crop(wmin=None, wmax=None, wunit='default', inplace=True)[source]

Crop spectrum to wmin-wmax range in wunit (inplace)

Parameters
  • wmin, wmax (float, or None) – boundaries of spectral range (in wunit)

  • wunit ('nm', 'cm-1', 'nm_vac') – which waveunit to use for wmin, wmax. If default: use the default Spectrum wavespace defined with get_waveunit().

Other Parameters

inplace (bool) – if True, modifies the Spectrum object directly. Else, returns a copy. Default True.

Returns

s – Cropped Spectrum. If inplace=True, Spectrum has been updated directly anyway. Allows chaining

Return type

Spectrum

Examples

Crop to experimental Spectrum, and compare:

from radis import calc_spectrum, load_spec, plot_diff
s = calc_spectrum(...)
s_exp = load_spec('typical_result.spec')
s.crop(s_exp.get_wavelength.min(), s_exp.get_wavelength.max(), 'nm')
plot_diff(s_exp, s)
Load an experimental spectrum

Load an experimental spectrum

Load an experimental spectrum

See also

radis.spectrum.operations.crop()

MergeSlabs()

if used with ``resample=’full’,

out, this, to

file[source]
classmethod from_array(w, I, quantity, wunit=None, Iunit=None, waveunit=None, unit=None, *args, **kwargs)[source]

Construct Spectrum from 2 arrays.

Parameters
  • w, I (array) – waverange and vector

  • quantity (str) – spectral quantity name

  • wunit ('nm', 'cm-1', 'nm_vac') – unit of waverange: wavelength in air ('nm' or 'nm_air'), wavenumber ('cm-1'), or wavelength in vacuum ('nm_vac'). If None, then w must be a dimensionned array.

  • Iunit (str) – spectral quantity unit (arbitrary). Ex: 'mW/cm2/sr/nm' for radiance_noslit If None, then I must be a dimensionned array.

  • *args, **kwargs – see Spectrum doc

Other Parameters
  • conditions (dict) – physical conditions and calculation parameters

  • cond_units (dict) – units for conditions

  • populations (dict) – a dictionary of all species, and levels. Should be compatible with other radiative codes such as Specair output. Suggested format: {molecules: {isotopes: {elec state: rovib levels}}} e.g:

    {'CO2':{1: 'X': df}}   # with df a Pandas Dataframe
    
  • lines (pandas Dataframe) – all lines in databank (necessary for using line_survey()). Warning if you want to play with the lines content: The signification of columns in lines may be specific to a database format. Plus, some additional columns may have been added by the calculation (e.g: Ei and S for emission integral and linestrength in SpectrumFactory). Refer to the code to know what they mean (and their units)

Returns

creates a Spectrum object

Return type

Spectrum

Examples

Create a spectrum:

from radis import Spectrum
s = Spectrum.from_array(w, I, 'radiance_noslit',
                       wunit='nm', unit='mW/cm2/sr/nm')

Dimensionned arrays can also be used directly

import astropy.units as u
w = np.linspace(200, 300) * u.nm
I = np.random.rand(len(w)) * u.mW/u.cm**2/u.sr/u.nm
s = Spectrum.from_array(w, I, 'radiance_noslit')

To create a spectrum with absorption and emission components (e.g: radiance_noslit and transmittance_noslit, or emisscoeff and abscoeff) call the Spectrum class directly. Ex:

from radis import Spectrum
s = Spectrum({'abscoeff': (w, A), 'emisscoeff': (w, E)},
             units={'abscoeff': 'cm-1', 'emisscoeff':'W/cm2/sr/nm'},
             wunit='nm')
classmethod from_hdf5(file, wmin=None, wmax=None, wunit=None, columns=None, engine='pytables')[source]

Generates a Spectrum from an HDF5 file. Uses hdf2spec()

Other Parameters
  • wmin, wmax (float) – range of wmin, wmax to load , using wunit (if None, load everything)

  • columns (list of str) – spectral arrays to load (if None, load everything)

Examples

Spectrum.from_hdf5("rad_hdf.h5", wmin=2100, wmax=2200, columns=['abscoeff', 'emisscoeff'])

See also

to_hdf5()

classmethod from_spec(file)[source]

Generates a Spectrum from a .spec [json] file. Uses load_spec()

classmethod from_specutils(spectrum, var='radiance')[source]

Convert a specutils specutils.spectra.spectrum1d.Spectrum1D to a radis Spectrum object.

Parameters

Examples

Taken from the Specutils website (https://specutils.readthedocs.io/en/stable/#getting-started-with-specutils)

from astropy.io import fits
from astropy import units as u
from specutils import Spectrum1D

f = fits.open('https://data.sdss.org/sas/dr16/sdss/spectro/redux/26/spectra/1323/spec-1323-52797-0012.fits')
# The spectrum is in the second HDU of this file.
specdata = f[1].data

lamb = 10**specdata['loglam'] * u.AA
flux = specdata['flux'] * 10**-17 * u.Unit('erg cm-2 s-1 AA-1')
spec = Spectrum1D(spectral_axis=lamb, flux=flux)

from radis import Spectrum
s = Spectrum.from_specutils(spec)
s.plot(wunit='nm')

See also

to_specutils()

classmethod from_txt(file, quantity, wunit, unit, waveunit=None, *args, **kwargs)[source]

Construct Spectrum from txt file.

Parameters
  • file (str) – file name

  • quantity (str) – spectral quantity name

  • wunit ('nm', 'cm-1', 'nm_vac') – unit of waverange: wavelength in air ('nm'), wavenumber ('cm-1'), or wavelength in vacuum ('nm_vac').

  • unit (str) – spectral quantity unit

  • *args, **kwargs – the following inputs are forwarded to loadtxt: 'delimiter', 'skiprows' The rest if forwarded to Spectrum. see Spectrum doc

Other Parameters
  • delimiter (',', etc.) – see numpy.loadtxt()

  • skiprows (int) – see numpy.loadtxt()

  • argsort (bool) – sorts the arrays in file by wavespace. Convenient way to load a file where points have been manually added at the end. Default False.

  • *Optional Spectrum parameters*

  • conditions (dict) – physical conditions and calculation parameters

  • cond_units (dict) – units for conditions

  • populations (dict) – a dictionary of all species, and levels. Should be compatible with other radiative codes such as Specair output. Suggested format: {molecules: {isotopes: {elec state: rovib levels}}} e.g:

    {'CO2':{1: 'X': df}}   # with df a Pandas Dataframe
    
  • lines (pandas Dataframe) – all lines in databank (necessary for using line_survey()). Warning if you want to play with the lines content: The signification of columns in lines may be specific to a database format. Plus, some additional columns may have been added by the calculation (e.g: Ei and S for emission integral and linestrength in SpectrumFactory). Refer to the code to know what they mean (and their units)

Returns

s – creates a Spectrum object

Return type

Spectrum

Examples

Generate an experimental spectrum from txt. In that example the delimiter key is forwarded to loadtxt():

from radis import Spectrum
s = Spectrum.from_txt('spectrum.csv', 'radiance', wunit='nm',
                          unit='W/cm2/sr/nm', delimiter=',')

To create a spectrum with absorption and emission components (e.g: radiance_noslit and transmittance_noslit, or emisscoeff and abscoeff) call the Spectrum class directly. Ex:

from radis import Spectrum
s = Spectrum({'abscoeff': (w, A), 'emisscoeff': (w, E)},
             units={'abscoeff': 'cm-1', 'emisscoeff':'W/cm2/sr/nm'},
             wunit='nm')

Notes

Internally, the numpy loadtxt() function is used and transposed:

w, I = np.loadtxt(file).T

You can use 'delimiter' and ‘skiprows' as arguments.

generate_perf_profile()[source]

Generate a visual/interactive performance profile diagram using tuna

Examples

s = calc_spectrum(...)
s.generate_perf_profile()

See typical output in https://github.com/radis/radis/pull/325

https://user-images.githubusercontent.com/16088743/128018032-6049be72-1881-46ac-9d7c-1ed89f9c4f42.png

Note

You can also profile with tuna directly:

python -m cProfile -o program.prof your_radis_script.py
tuna your_radis_script.py
get(var: ['radiance'], wunit='default', Iunit='default', copy=True, trim_nan=False, return_units=False)[source]

Retrieve a spectral quantity from a Spectrum object. You can select wavespace unit, intensity unit, or propagation medium.

Parameters
  • var (variable ('absorbance', 'transmittance', 'xsection' etc.)) – Should be a defined quantity among CONVOLUTED_QUANTITIES or NON_CONVOLUTED_QUANTITIES. To get the full list of spectral arrays defined in this Spectrum object use the get_vars() method.

  • wunit ('nm', 'cm', 'nm_vac'.) – wavespace unit: wavelength in air ('nm'), wavenumber ('cm-1'), or wavelength in vacuum ('nm_vac'). if "default", default unit for waveunit is used. See get_waveunit().

  • Iunit (unit for variable var) – if "default", default unit for quantity var is used. See the units attribute. For var="radiance", one can use per wavelength (~ ‘W/m2/sr/nm’) or per wavenumber (~ ‘W/m2/sr/cm-1’) units

    Note

    if using default, the returned unit may be different from Spectrum.units[var]. e.g, for a Spectrum with radiance stored in ‘mW/cm2/sr/nm’, getting it with wunit='cm-1', Iunit='default' will return Iunit in ‘mW/cm2/sr/cm-1’ for consistency. Use return_units to be sure about which units are used.

Other Parameters
  • copy (bool) – if True, returns a copy of the stored quantity (modifying it wont change the Spectrum object). Default True.

  • trim_nan (bool) – if True, removes nan on the sides of the spectral array (and corresponding wavespace). Default False.

  • return_units (bool) – if True, return dimensioned Astropy arrays. Is using return_units = 'as_str', return wunit and Iunit as extra variables, i.e, w, I, wunit, Iunit = s.get(..., return_units='as_str') Default False

Returns

w, I – wavespace, quantity (ex: wavelength, radiance_noslit). For numpy users, note that these are copies (values) of the Spectrum quantity and not a view (reference): if you modify them the Spectrum is not changed

Return type

array-like

Examples

Get transmittance in cm-1:

w, I = s.get('transmittance_noslit', wunit='cm-1')

Get radiance (in wavelength in air):

_, R = s.get('radiance_noslit', wunit='nm', Iunit='W/cm2/sr/nm')

Use with return_units to get dimensioned Astropy Quantities

w, R  = s.get('radiance_noslit', return_units=True)
get_baseline(algorithm='als', **kwargs)[source]

Calculate and returns a baseline

Parameters
  • s (Spectrum) – Spectrum which needs a baseline

  • var (str) – on which spectral quantity to read the baseline. Default 'radiance'. See SPECTRAL_QUANTITIES

  • algorithm (‘als’, ‘polynomial’) – Asymmetric least square or Polynomial fit

  • **kwargs (dict) – additional parameters to send to the algorithm. By default, for ‘polynomial’:

    **kwargs = **{“deg”: 1, “max_it”:500}

    for ‘als’:

    **kwargs = {“asymmetry_param”: 0.05,

    “smoothness_param”: 1e6}

Returns

baseline – Spectrum object where intenisity is the baseline of s

Return type

Spectrum

Examples

See also

get_baseline()

get_conditions()[source]

Get all physical / computational parameters.

get_integral(var, wunit='default', Iunit='default', **kwargs)[source]

Returns integral of variable ‘var’ over waverange.

Parameters
  • var (str) – spectral quantity to integate

  • wunit (str) – over which waverange to integrated. If default, use the default Spectrum wavespace defined with get_waveunit().

  • Iunit (str) – default 'default'

    Warning

    this is the unit of the quantity, not the unit of the integral. Don’t forget to multiply by wunit

Other Parameters

kwargs (**dict) – forwarded to get()

Returns

integral – integral in [Iunit]*[wunit]

Return type

float

get_name()[source]

Return Spectrum name.

If not defined, returns either the file name if Spectrum was loaded from a file, or the 'spectrum{id}' with the Python id object

get_populations(molecule=None, isotope=None, electronic_state=None, show_warning=True)[source]

Return populations that are featured in the spectrum, either as upper or lower levels.

Parameters
  • molecule (str, or None) – if None, only one molecule must be defined. Else, an error is raised

  • isotope (int, or None) – isotope number. if None, only one isotope must be defined. Else, an error is raised

  • electronic_state (str) – if None, only one electronic state must be defined. Else, an error is raised

  • show_warning (bool) – if False, turns off warning about meaning of populations, see Notes and discussion on https://github.com/radis/radis/issues/508.

Returns

  • pandas dataframe of levels, where levels are the index,

  • and ‘Evib’ and ‘nvib’ are featured

Notes

Structure:

{molecule: {isotope: {electronic_state: {'vib': pandas Dataframe,    # (copy of) vib levels
                                         'rovib': pandas Dataframe,  # (copy of) rovib levels
                                         'Ia': float    # isotopic abundance
                                         }}}}

(If Spectrum generated with RADIS, structure should match that of SpectrumFactory.get_populations())

Examples

An example on how different are populations used for partition function and spectrum calculations

#%% CO2 example
# For instance, plot populations of a given vibrational level, v1,v2,v3=(0,1,0)
import radis
s = radis.test_spectrum(molecule="CO2", Tvib=3000, Trot=1000,
                        export_lines=True,
                        export_populations="rovib",
                        isotope=1)
pops = s.get_populations("CO2")["rovib"]

import matplotlib.pyplot as plt
pops.query("v1==0 & v2==1 & v3==0").plot("j", "n",
                                         label="pops. used to compute partition functions")
s.lines.query("v1l==0 & v2l==1 & v3l==0").plot("jl", "nl", ax=plt.gca(), kind="scatter", color="r",
                                               label="pops. of visible absorbing lines")
plt.legend()
plt.xlim((0,70))
See populations of computed levels

See populations of computed levels

See populations of computed levels
get_power(unit='mW/cm2/sr')[source]

Returns integrated radiance (no slit) power density.

Parameters

Iunit (str) – power unit.

Returns

P – radiated power in unit

Return type

float

Examples

s.get_power('W/cm2/sr')
get_quantities(which=None)[source]

Returns all spectral quantities stored in this object (convoluted or non convoluted). Wrapper to get_vars()

get_radiance(Iunit='mW/cm2/sr/nm', copy=True)[source]

Return radiance in whatever unit, and can even convert from ~1/nm to ~1/cm-1 (and the other way round)

Other Parameters

copy (boolean) – if True, returns a copy of the stored waverange (modifying it wont change the Spectrum object). Default True.

get_radiance_noslit(Iunit='mW/cm2/sr/nm', copy=True)[source]

Return radiance (non convoluted) in whatever unit, and can even convert from ~1/nm to ~1/cm-1 (and the other way round)

Other Parameters

copy (boolean) – if True, returns a copy of the stored waverange (modifying it wont change the Spectrum object). Default True.

get_rovib_levels(molecule=None, isotope=None, electronic_state=None, first=None)[source]

Return rovibrational levels calculated in the spectrum (energies, populations)

Parameters
  • molecule (str, or None) – if None, only one molecule must be defined. Else, an error is raised

  • isotope (int, or None) – isotope number. if None, only one isotope must be defined. Else, an error is raised

  • electronic_state (str) – if None, only one electronic state must be defined. Else, an error is raised

  • first (int, or ‘all’ or None) – only show the first N levels. If None or ‘all’, all levels are shown

Returns

out – pandas dataframe of levels, where levels are the index, and ‘Evib’ and ‘nvib’ are featured

Return type

pandas DataFrame

get_slit(wunit='same')[source]

Get slit function that was applied to the Spectrum.

Returns

wslit, Islit – slit function with wslit in Spectrum waveunit. See get_waveunit()

Return type

array

get_vars(which=None)[source]

Returns all spectral quantities stored in this object (convoluted or non convoluted)

get_vib_levels(molecule=None, isotope=None, electronic_state=None, first=None)[source]

Return vibrational levels in the spectrum (energies, populations)

Parameters
  • molecule (str, or None) – if None, only one molecule must be defined. Else, an error is raised

  • isotope (int, or None) – isotope number. if None, only one isotope must be defined. Else, an error is raised

  • electronic_state (str) – if None, only one electronic state must be defined. Else, an error is raised

  • first (int, or ‘all’ or None) – only show the first N levels. If None or ‘all’, all levels are shown

Returns

out – pandas dataframe of levels, where levels are the index, and ‘Evib’ and ‘nvib’ are featured

Return type

pandas DataFrame

get_wavelength(medium='air', which=None, copy=True)[source]

Return wavelength in defined medium.

Parameters

medium ('air', 'vacuum') – returns wavelength as seen in air, or vacuum. Default 'air'. See vacuum2air(), air2vacuum()

Other Parameters

copy (boolean) – if True, returns a copy of the stored waverange (modifying it wont change the Spectrum object). Default True.

Returns

w – (a copy of) spectrum wavelength for convoluted or non convoluted quantities

Return type

array_like

get_wavenumber(which=None, copy=True)[source]

Return wavenumber (if the same for all quantities)

Other Parameters

copy (boolean) – if True, returns a copy of the stored waverange (modifying it wont change the Spectrum object). Default True.

Returns

w – (a copy of) spectrum wavenumber for convoluted or non convoluted quantities

Return type

array_like

get_waveunit()[source]

Returns whether this spectrum is defined in wavelength (nm) or wavenumber (cm-1)

has_nan(ignore_wavespace=True) bool[source]
Parameters

s (Spectrum) – radis Spectrum.

Returns

b – returns whether Spectrum has nan

Return type

bool

Note

print(s) will also show which spectral quantities have ````nan.

is_at_equilibrium(check='warn', verbose=False)[source]

Returns whether this spectrum is at (thermal) equilibrium. Reads the thermal_equilibrium key in Spectrum conditions. It does not imply chemical equilibrium (mole fractions are still arbitrary)

If they are defined, also check that the following assertions are True:

Tvib = Trot = Tgas self_absorption = True overpopulation = None

If they are not, still trust the value in Spectrum conditions, but raise a warning.

Other Parameters
  • check ('warn', 'error', 'ignore') – what to do if Spectrum conditions dont match the given equilibrium state: raise a warning, raise an error, or just ignore and dont even check. Default 'warn'.

  • verbose (bool) – if True, print why is the spectrum is not at equilibrium, if applicable.

is_optically_thin()[source]

Returns whether the spectrum is optically thin, based on the value on the self_absorption key in conditions.

If not given, raises an error

line_survey(overlay=None, wunit='cm-1', Iunit='hitran', medium='air', cutoff=None, plot='S', lineinfo=['int', 'A', 'El'], barwidth='hwhm_voigt', yscale='log', writefile=None, *args, **kwargs)[source]
Plot Line Survey (all linestrengths used for calculation) Output in

Plotly (html)

Parameters
  • overlay (tuple (w, I, [name], [units]), or list or tuples) – plot (w, I) on a secondary axis. Useful to compare linestrength with calculated / measured data:

    LineSurvey(overlay='abscoeff')
    
  • wunit ('nm', 'cm-1') – wavelength / wavenumber units

  • Iunit ('hitran', 'splot') – Linestrength output units:

    • 'hitran': (cm-1/(molecule/cm-2))

    • 'splot' : (cm-1/atm) (Spectraplot units [2]_)

    Note: if not None, cutoff criteria is applied in this unit. Not used if plot is not ‘S’

  • medium ('air', 'vacuum') – show wavelength either in air or vacuum. Default 'air'

  • plot (str) – what to plot. Default 'S' (scaled line intensity). But it can be any key in the lines, such as population ('nu'), or Einstein coefficient ('Aul')

  • lineinfo (list, or 'all') – extra line information to plot. Should be a column name in the databank (s.lines). For instance: 'int', 'selbrd', etc… Default ['int']

Other Parameters
  • writefile (str) – if not None, a valid filename to save the plot under .html format.

    If None, use the fig object returned to show the plot.

    • yscale ('log', 'linear') – Default 'log'

    • barwidth (float or str) –

      if float, width of bars, in wunit, as a fraction of full-range; i.e.

      barwidth=0.01
      

      makes bars span 1% of the full range. if str, uses the column as width. Example

      barwidth = 'hwhm_voigt'
      
      returns
      • fig (a Plotly figure.) – If using a Jupyter Notebook, the plot will appear. Else, use writefile to export to an html file.

      • Plot in Plotly. See Output in [1]_

An example using the SpectrumFactory to generate a spectrum:

from radis import SpectrumFactory
sf = SpectrumFactory(
                     wavenum_min=2380,
                     wavenum_max=2400,
                     mole_fraction=400e-6,
                     path_length=100,  # cm
                     isotope=[1],
                     export_lines=True,    # required for LineSurvey!
                     db_use_cached=True)
sf.load_databank('HITRAN-CO2-TEST')
s = sf.eq_spectrum(Tgas=1500)
s.apply_slit(0.5)
s.line_survey(overlay='radiance_noslit', barwidth=0.01, lineinfo="all")  # or barwidth='hwhm_voigt'

See the output in Examples

Line Survey

Line Survey

Line Survey
See populations of computed levels

See populations of computed levels

See populations of computed levels
1

RADIS Online Documentation (LineSurvey)

2

SpectraPlot

LineSurvey(), the Spectrum page

lines[source]

informations on emitting or absorbing lines that contribute to the spectrum.

See also line_survey()

See populations of computed levels

See populations of computed levels

See populations of computed levels
max(value_only=False)[source]

Maximum of the Spectrum, if only one spectral quantity is available:

s.max()

Returns a dimensioned quantity by default, with the default unit of the spectrum. If value_only=False, a float is returned, without dimensions.

If there are multiple arrays in your Spectrum, use take(), e.g.

s.take('radiance').max()

Examples

Normalize a spectrum (we could also have used normalize() directly)

s /= s.max()

Below is a slightly more advanced use case, convenient to process non-calibrated experimental data.

Imagine we want to remove a baseline that we have identified to originate from a particular species, modelled by spectrum s, but whose intensity (and units) are not the same as that of the experimental spectrum.

We substract exactly the intensity that correspond to the intensity on a given range w1, w2 of the experimental spectrum s_exp, using a combination of take(), normalize(), crop() and max():

s_exp -= s.take('radiance').normalize() * s_exp.crop((w1, w2)), inplace=False).max()
min(value_only=True)[source]

Minimum of the Spectrum, if only one spectral quantity is available

s.min()

Returns a dimensioned quantity by default, with the default unit of the spectrum. If value_only=False, a float is returned, without dimensions.

If there are multiple arrays in your Spectrum, use take(), e.g.

s.take('radiance').min()
name[source]
normalize(normalize_how='max', wrange=(), wunit=None, inplace=False, force=False, verbose=False, return_norm=False)[source]

Normalise the Spectrum, if only one spectral quantity is available.

Parameters
  • normalize_how ('max', 'area', 'mean') – how to normalize. 'max' is the default but may not be suited for very noisy experimental spectra. 'area' will normalize the integral to 1. 'mean' will normalize by the mean amplitude value

  • wrange (tuple) – if not empty, normalize on this range

  • wunit ("nm", "cm-1", "nm_vac") – unit of the normalisation range above. If None, use the spectrum default waveunit.

  • inplace (bool) – if True, changes the Spectrum.

Other Parameters

force (boolean) – By default, normalizing some parametres such as transmittance is forbidden because considered non-physical. Use force=True if you really want to.

Examples

s.normalize("max", (4200, 4800), inplace=True).plot()

If there are multiple arrays in your Spectrum, use take(), e.g.

s.take('radiance').normalize(wrange=(4200, 4800)).plot()
offset(offset: Spectrum, unit: float, inplace: str = True) Spectrum[source]

Offset the spectrum by a wavelength or wavenumber (inplace)

Parameters
  • offset (float) – Constant to add to all quantities in the Spectrum.

  • unit (‘nm’ or ‘cm-1’) – unit for offset

Other Parameters

inplace (bool) – if True, modifies the Spectrum object directly. Else, returns a copy. Default True.

Returns

s – Offset Spectrum. If inplace=True, Spectrum has been updated directly anyway. Allows chaining.

Return type

Spectrum

Examples

::

s.offset(5, ‘nm’)

plot(var: ['radiance'] = None, wunit='default', Iunit='default', show_points=False, nfig=None, yscale='linear', show_medium='vacuum_only', normalize=False, force=False, plot_by_parts=False, show=False, show_ruler=False, **kwargs)[source]

Plot a Spectrum object.

Note

default plotting library and templates can be edited in radis.config [“plot”]

Parameters
  • var (variable (absorbance, transmittance, transmittance_noslit, xsection, etc.)) – For full list see get_vars(). If None, plot the first thing in the Spectrum. Default None.

  • wunit ('default', 'nm', 'cm-1', 'nm_vac',) – wavelength air, wavenumber, or wavelength vacuum. If 'default', Spectrum get_waveunit() is used.

  • Iunit (unit for variable) – if default, default unit for quantity var is used. for radiance, one can use per wavelength (~ W/m2/sr/nm) or per wavenumber (~ W/m2/sr/cm-1) units

Other Parameters
  • show_points (boolean) – show calculated points. Default True.

  • nfig (int, None, or ‘same’) – plot on a particular figure. ‘same’ plots on current figure. For instance:

    s1.plot()
    s2.plot(nfig='same')
    
  • show_medium (bool, 'vacuum_only') – if True and wunit are wavelengths, plot the propagation medium in the xaxis label ([air] or [vacuum]). If 'vacuum_only', plot only if wunit=='nm_vac'. Default 'vacuum_only' (prevents from inadvertently plotting spectra with different propagation medium on the same graph).

  • yscale (‘linear’, ‘log’) – plot yscale

  • normalize (boolean, or tuple.) – option to normalize quantity to 1 (ex: for radiance). Default False

  • plot_by_parts (bool) – if True, look for discontinuities in the wavespace and plot the different parts without connecting lines. Useful for experimental spectra produced by overlapping step-and-glue. Additional parameters read from kwargs : split_threshold and cutwings. See more in split_and_plot_by_parts().

  • force (bool) – plotting on an existing figure is forbidden if labels are not the same. Use force=True to ignore that.

  • show (bool) – show figure. Default False. Will still show the figure in interactive mode, e.g, %matplotlib inline in a Notebook.

  • show_ruler (bool) – if True, add a ruler tool to the Matplotlib toolbar. Convenient to measure distances between peaks, etc.

    Warning

    still experimental in 0.9.30 ! Try it, feedback welcome !

  • **kwargs (**dict) – kwargs forwarded as argument to plot (e.g: lineshape attributes: lw=3, color='r')

Returns

line plot

Return type

line

Examples

Plot an experimental_spectrum() in arbitrary units:

s = experimental_spectrum(..., Iunit='mW/cm2/sr/nm')
s.plot(Iunit='W/cm2/sr/cm-1')

See more examples in the plot Spectral quantities page.

Load an experimental spectrum

Load an experimental spectrum

Load an experimental spectrum
Remove a baseline

Remove a baseline

Remove a baseline
GPU Accelerated Spectra

GPU Accelerated Spectra

GPU Accelerated Spectra
Calculate non-LTE spectra of carbon-monoxide

Calculate non-LTE spectra of carbon-monoxide

Calculate non-LTE spectra of carbon-monoxide
Use different plot themes

Use different plot themes

Use different plot themes
Calculate a large spectrum by part

Calculate a large spectrum by part

Calculate a large spectrum by part
Calculate a spectrum from ExoMol

Calculate a spectrum from ExoMol

Calculate a spectrum from ExoMol
Post-process using Specutils

Post-process using Specutils

Post-process using Specutils
plot_populations(what=None, nunit='', correct_for_abundance=False, **kwargs)[source]

Plots vib populations if given and format is valid.

Parameters
  • what (‘vib’, ‘rovib’, None) – if None plot everything

  • nunit (‘’, ‘cm-3’) – plot either in a fraction of vibrational levels, or a molecule number in in cm-3

  • correct_for_abundance (boolean) – if True, multiplies each population by the isotopic abundance (as it is done during the calculation of emission integral)

  • kwargs (**dict) – are forwarded to the plot

Examples

See populations of computed levels

See populations of computed levels

See populations of computed levels
plot_slit(wunit=None, waveunit=None)[source]

Plot slit function that was applied to the Spectrum.

If dispersion was used (see apply_slit()) the different slits are built again and plotted too (dotted).

Parameters

wunit ('nm', 'cm-1', or None) – plot slit in wavelength or wavenumber. If None, use the unit the slit in which the slit function was given. Default None

Returns

  • fix, ax (matplotlib objects) – figure and ax

  • .. minigallery:: radis.spectrum.spectrum.Spectrum.plot_slit

populations[source]

populations of rovibrational levels used to compute partition functions of the spectrum

See also get_populations(), plot_populations()

print_conditions(**kwargs)[source]

Prints all physical / computational parameters.

Parameters

kwargs (dict) – refer to print_conditions()

Examples

::

s.print_conditions()

You can also simply print the Spectrum object directly:

print(s)
print_perf_profile(number_format='{:.3f}', precision=16)[source]

Prints Profiler output dictionary in a structured manner.

Example

Spectrum.print_perf_profile()

# output >>
    spectrum_calculation      0.189s ████████████████
        check_line_databank              0.000s
        check_non_eq_param               0.042s ███
        fetch_energy_5                   0.015s █
        calc_weight_trans                0.008s
        reinitialize                     0.002s
            copy_database                    0.000s
            memory_usage_warning             0.002s
            reset_population                 0.000s
        calc_noneq_population            0.041s ███
            part_function                    0.035s ██
            population                       0.006s
        scaled_non_eq_linestrength       0.005s
            map_part_func                    0.001s
            corrected_population_se          0.003s
        calc_emission_integral           0.006s
        applied_linestrength_cutoff      0.002s
        calc_lineshift                   0.001s
        calc_hwhm                        0.007s
        generate_wavenumber_arrays       0.001s
        calc_line_broadening             0.074s ██████
            precompute_LDM_lineshapes        0.012s
            LDM_Initialized_vectors          0.000s
            LDM_closest_matching_line        0.001s
            LDM_Distribute_lines             0.001s
            LDM_convolve                     0.060s █████
            others                           0.001s
        calc_other_spectral_quan         0.003s
        generate_spectrum_obj            0.000s
        others                           -0.016s
Other Parameters

precision (int, optional) – total number of blocks. Default 16.

references[source]
resample(w_new, unit='same', out_of_bounds='nan', energy_threshold='default', print_conservation=False, inplace=True, if_conflict_drop=None, **kwargs)[source]

Resample spectrum over a new wavelength/wavenumber range.

Warning

This may result in information loss. Resampling is done with oversampling and spline interpolation. These parameters can be adjusted, and energy conservation ensured with the appropriate parameters.

To minimize information loss, always resample the high-resolution spectrum over the low-resolution spectrum, i.e.

s_highres.resample(s_lowres)

Fills with 'nan' or transparent medium (transmittance 1, radiance 0) when out of bound (see out_of_bounds)

Parameters
  • w_new (array, or Spectrum) – new wavespace to resample the spectrum on. Must be inclosed in the current wavespace (we won’t extrapolate) One can also give a Spectrum directly:

    s1.resample(s2.get_wavenumber())
    s1.resample(s2)            # also valid
    
  • unit ('same', 'nm', 'cm-1', 'nm_vac') – unit of new wavespace. It 'same' it is assumed to be the current waveunit. Default 'same'. The spectrum waveunit is changed to this unit after resampling (i.e: a spectrum calculated and stored in cm-1 but resampled in nm will be stored in nm from now on). If 'nm', wavelength in air. If 'nm_vac', wavelength in vacuum.

  • out_of_bounds ('transparent', 'nan', 'error') – what to do if resampling is out of bounds. 'transparent': fills with transparent medium. ‘nan’: fill with nan. 'error': raises an error. Default 'nan'

  • medium ('air', 'vacuum', or 'default') – in which medium is the new waverange is calculated if it is given in ‘nm’. Ignored if unit=’cm-1’

Other Parameters
  • energy_threshold (float or None or 'default') -- if energy conservation (integrals on the intersecting range) is above this threshold, raise an error. If ``None, dont check for energy conservation. If 'default', look up the value in radis.config [“RESAMPLING_TOLERANCE_THRESHOLD”] Default 'default'

  • print_conservation (boolean) – if True, prints energy conservation. Default False.

  • inplace (boolean) – if True, modifies the Spectrum object directly. Else, returns a copy. Default True.

  • **kwargs (**dict) – all other arguments are sent to radis.misc.signal.resample()

Returns

Spectrum – object has been modified anyway.

Return type

resampled Spectrum object. If using inplace=True, the Spectrum

Examples

Convert a Spectrum in wavenumber to wavelengths:

s_nm = s.resample(s.get_wavelength(), "nm", inplace=False)
resample_even(energy_threshold=0.005, print_conservation=False, inplace=True)[source]

Resample spectrum over the same waverange, but evenly spaced.

Warning

This may result in information loss. Resampling is done with oversampling and spline interpolation. These parameters can be adjusted, and energy conservation ensured with the appropriate parameters.

Parameters
  • energy_threshold (float or None) – if energy conservation (integrals on the intersecting range) is above this threshold, raise an error. If None, dont check for energy conservation Default 5e-3 (0.5%)

  • print_conservation (boolean) – if True, prints energy conservation. Default False.

  • inplace (boolean) – if True, modifies the Spectrum object directly. Else, returns a copy. Default True.

  • **kwargs (**dict) – all other arguments are sent to radis.misc.signal.resample()

Returns

Spectrum – object has been modified anyway.

Return type

resampled Spectrum object. If using inplace=True, the Spectrum

Examples

rescale_mole_fraction(new_mole_fraction, old_mole_fraction=None, inplace=True, ignore_warnings=False, force=False, verbose=True)[source]

Update spectrum with new molar fraction Convoluted values (with slit) are dropped in the process.

Parameters
  • new_mole_fraction (float) – new mole fraction

  • old_mole_fraction (float, or None) – if None, current mole fraction (conditions[‘mole_fraction’]) is used

Other Parameters
  • inplace (boolean) – if True, modifies the Spectrum object directly. Else, returns a copy. Default True.

  • force (boolean) – if False, won’t allow rescaling to 0 (not to loose information). Default False

Returns

s – Cropped Spectrum. If inplace=True, Spectrum has been updated directly anyway. Allows chaining

Return type

Spectrum

Examples

s.rescale_mole_fraction(0.2)

Notes

Implementation:

similar to rescale_path_length() but we have to scale abscoeff & emisscoeff Note that this is valid only for small changes in mole fractions. Then, the change in line broadening becomes significant

rescale_path_length(new_path_length, old_path_length=None, inplace=True, force=False)[source]

Rescale spectrum to new path length. Starts from absorption coefficient and emission coefficient, and solves the RTE again for the new path length Convoluted values (with slit) are dropped in the process.

Parameters
  • new_path_length (float) – new path length

  • old_path_length (float, or None) – if None, current path length (conditions[‘path_length’]) is used

Other Parameters
  • inplace (boolean) – if True, modifies the Spectrum object directly. Else, returns a copy. Default True.

  • force (boolean) – if False, won’t allow rescaling to 0 (not to loose information). Default False

Returns

s – Cropped Spectrum. If inplace=True, Spectrum has been updated directly anyway. Allows chaining

Return type

Spectrum

Examples

for path in [0.1, 10, 100]:
    s.rescale_path_length(10, inplace=False).plot(nfig='same')

Additionally, you can also use astropy units in the input arguments, for example:

# preparing a test spectrum :
import radis
s = radis.test_spectrum()

# rescaling :
import astropy.units as u
s.rescale_path_length(1 * u.km).plot()

Notes

Implementation:

To deal with all the input cases, we first make a list of what has to be recomputed, and what has to be recalculated

save(*args, **kwargs)[source]

Alias to Spectrum.store.

See Spectrum.store for documentation

savetxt(filename, var, wunit='default', Iunit='default')[source]

Export spectral quantity var to filename.

(note that by doing this you will loose additional information, such

as the calculation conditions or the units. You better save a Spectrum object under a .spec file with store() and load it afterwards with load_spec())

Parameters
  • filename (str) – file name

  • var (str) – which spectral variable ot export

Other Parameters

wunit, Iunit, medium (str) – see get() for more information

Notes

Export variable as:

np.savetxt(filename, np.vstack(self.get(var, wunit=wunit, Iunit=Iunit,
                                    medium=medium)).T, header=header)
sort(inplace=True)[source]

Sort the Spectrum by wavelength / wavenumber.

Parameters

inplace (bool, optional) – if True, modifies the Spectrum object directly. The default is True.

Returns

s – sorted Spectrum. If inplace=True, Spectrum has been updated directly anyway. Allows chaining.

Return type

Spectrum

Examples

store(path, discard=['lines', 'populations'], compress=True, add_info=None, add_date=None, if_exists_then='error', verbose=True)[source]

Save a Spectrum object in JSON format. Object can be recovered with load_spec(). If many Spectrum are saved in a same folder you can view their properties with the SpecDatabase structure.

Parameters
  • path (path to folder (database) or file) – if a folder, file is saved to database and name is generated automatically. if a file name, then Spectrum is saved to this file and the later formatting options dont apply

  • file (str) – explicitely give a filename to save

  • compress (boolean) – if False, save under text format, readable with any editor. if True, saves under binary format. Faster and takes less space. If 2, removes all quantities that can be regenerated with s.update(), e.g, transmittance if abscoeff and path length are given, radiance if emisscoeff and abscoeff are given in non-optically thin case, etc. Default True.

  • add_info (list) – append these parameters and their values if they are in conditions example:

    add_info = ['Tvib', 'Trot']
    
  • discard (list of str) – parameters to exclude, for instance to save some memory for instance Default [lines, populations]: retrieved Spectrum looses the line_survey() ability, and plot_populations() (but it saves tons of memory!)

  • if_exists_then ('increment', 'replace', 'error', 'ignore') – what to do if file already exists. If increment an incremental digit is added. If replace file is replaced (yeah). If 'ignore' no file is created. If error (or anything else) an error is raised. Default error

Return type

Returns filename used

Notes

If many spectra are stored in a folder, it may be time to set up a SpecDatabase structure to easily see all Spectrum conditions and get Spectrum that suits specific parameters.

Examples

Store a spectrum in compressed mode, regenerate quantities after loading:

from radis import load_spec
s.store('test.spec', compress=True)   # s is a Spectrum
s2 = load_spec('test.spec')
s2.update()                           # regenerate missing quantities
take(var, copy_lines=False, copy_arrays=True)[source]
Parameters

var (str) – spectral quantity ('absorbance', 'transmittance', 'xsection' etc.)

Other Parameters
  • copy_lines (bool) – if True, export s.lines. Default False

  • copy_arrays (bool) – if False, returned array’s quantity is a pointer to the original Spectrum. Faster, but warning, changing them will then change the original Spectrum. Default True

Returns

s – same Spectrum with only the var spectral quantity

Return type

Spectrum

Examples

Use take to chain other commands

s.take('radiance').normalize().plot()
to_hdf5(file, engine='pytables')[source]

Stores the Spectrum under HDF5 format. Uses spec2hdf()

Examples

s.to_hdf5('spec01.h5')

See also

from_hdf5()

to_json(*args, **kwargs)[source]

Alias to Spectrum.store(compress=False).

See Spectrum. store() for documentation

to_pandas(copy=True)[source]

Convert a Spectrum to a Pandas DataFrame

Returns

pd.DataFrame – units are stored in attributes df.attrs

Return type

pandas DataFrame where columns are spectral arrays, and

Notes

Pandas does not support units yet. pint-pandas is an advanced project but not fully working. See discussion in https://github.com/pandas-dev/pandas/issues/10349

For the moment, we store units as metadata

to_specutils(var=None, wunit='default', Iunit='default')[source]

Convert a radis Spectrum object to specutils specutils.spectra.spectrum1d.Spectrum1D

Parameters
  • var (‘radiance’, ‘radiance_noslit’, etc.) – which spectral array to convert. If None and only one spectral arry is defined, use it.

  • wunit ('nm', 'cm', 'nm_vac'.) – wavespace unit: wavelength in air ('nm'), wavenumber ('cm-1'), or wavelength in vacuum ('nm_vac'). if "default", default unit for waveunit is used. See get_waveunit().

    Note

    specutils handles wavelengths in vacuum only. If using 'nm' wavelengths will be converted to wavelengths in vacuum. We recommend using 'nm_air' or 'nm_vac' to avoid any confusion.

  • Iunit (unit for variable var) – if "default", default unit for quantity var is used. See the units attribute. For var="radiance", one can use per wavelength (~ ‘W/m2/sr/nm’) or per wavenumber (~ ‘W/m2/sr/cm-1’) units

  • .. note::nan, that may have been added on the wings of the spectra if a slit has been applied, are removed using trim_nan parameter of get() . The waverange in the 1DSpectrum object may therefore be cropped.

Examples

spectrum = s.to_specutils()

Add uncertainties by reading a spectrum noise region with SpectralRegion and noise_region_uncertainty()

from specutils import SpectralRegion
from specutils.manipulation import noise_region_uncertainty
noise_region = SpectralRegion(2012 / u.cm, 2009 / u.cm)
spectrum = noise_region_uncertainty(spectrum, noise_region)

Find lines out of the noise using find_lines_threshold()

from specutils.fitting import find_lines_threshold
lines = find_lines_threshold(spectrum)
Post-process using Specutils

Post-process using Specutils

Post-process using Specutils

See also

from_specutils()

trim(inplace=True)[source]

Remove nan common to all arrays on each side of the Spectrum.

Returns a smaller Spectrum (inplace or not).

Returns

s – directly anyway. Allows chaining.

Return type

Spectrum : trimmed Spectrum. If inplace=True, Spectrum has been updated

units[source]

units for spectral quantities.

Type

dict

update(quantity='all', optically_thin='default', verbose=True)[source]

Calculate missing quantities: ex: if path_length and emisscoeff are given, recalculate radiance_noslit.

Parameters
  • spec (Spectrum)

  • quantity (str) – name of the spectral quantity to recompute. If ‘same’, only the quantities in the Spectrum are recomputed. If ‘all’, then all quantities that can be derived are recomputed. Default ‘all’.

  • optically_thin (True, False, or ‘default’) – determines whether to calculate radiance with or without self absorption. If ‘default’, the value is determined from the self_absorption key in Spectrum.conditions. If not given, False is taken. Default ‘default’ Also updates the self_absorption value in conditions (creates it if doesnt exist

Examples

Initialize a spectrum from the absorption coefficient, retrieve the transmittance or the emission coefficient :

s = Spectrum.from_array([1900.  , 1900.01, 1900.02, 1900.03, 1900.04, 1900.05, 1900.06,
                         1900.07, 1900.08, 1900.09],
                        [2.71414065e-06, 2.88341489e-06, 3.06942277e-06, 3.27445689e-06,
                         3.50121831e-06, 3.75290756e-06, 4.03334037e-06, 4.34709612e-06,
                         4.69971017e-06, 5.09792551e-06],
                        'abscoeff',
                        wunit='cm-1',
                        Iunit='cm-1',
                        conditions={'path_length':1, # cm
                                    'thermal_equilibrium':True,
                                    'Tgas':700,  # K
                                    })
s.update('transmittance_noslit')
s.update('emisscoeff')
class SpectrumFactory(wmin=None, wmax=None, wunit=cm - 1, wavenum_min=None, wavenum_max=None, wavelength_min=None, wavelength_max=None, Tref=296, pressure=1.01325, mole_fraction=1, path_length=1, wstep=0.01, molecule=None, isotope='all', medium='air', truncation=50, neighbour_lines=0, pseudo_continuum_threshold=0, self_absorption=True, chunksize=None, optimization='simple', folding_thresh=1e-06, zero_padding=-1, broadening_method='voigt', cutoff=0, parsum_mode='full summation', verbose=True, warnings=True, save_memory=False, export_populations=None, export_lines=False, emulate_gpu=False, **kwargs)[source]

Bases: BandFactory

A class to put together all functions related to loading CDSD / HITRAN databases, calculating the broadenings, and summing over all the lines.

Parameters
  • wmin, wmax (float or Quantity) – a hybrid parameter which can stand for minimum (maximum) wavenumber or minimum (maximum) wavelength depending upon the unit accompanying it. If dimensionless, wunit is considered as the accompanying unit.

  • wunit ('nm', 'cm-1') – the unit accompanying wmin and wmax. Can only be passed with wmin and wmax. Default is "cm-1".

  • wavenum_min, wavenum_max (float(cm^-1) or Quantity) – minimum (maximum) wavenumber to be processed in \(cm^{-1}\). use astropy.units to specify arbitrary inverse-length units.

  • wavelength_min, wavelength_max (float(nm) or Quantity) – minimum (maximum) wavelength to be processed in \(nm\). This wavelength can be in 'air' or 'vacuum' depending on the value of the parameter medium=. use astropy.units to specify arbitrary length units.

  • pressure (float(bar) or Quantity) – partial pressure of gas in bar. Default 1.01325 (1 atm). use astropy.units to specify arbitrary pressure units. For example, 1013.25 * u.mbar.

  • mole_fraction (float [ 0 - 1]) – species mole fraction. Default 1. Note that the rest of the gas is considered to be air for collisional broadening.

  • path_length (float(cm) or Quantity) – path length in cm. Default 1. use astropy.units to specify arbitrary length units.

  • molecule (int, str, or None) – molecule id (HITRAN format) or name. If None, the molecule can be infered from the database files being loaded. See the list of supported molecules in MOLECULES_LIST_EQUILIBRIUM and MOLECULES_LIST_NONEQUILIBRIUM. Default None.

  • isotope (int, list, str of the form '1,2', or 'all') – isotope id (sorted by relative density: (eg: 1: CO2-626, 2: CO2-636 for CO2). See HITRAN documentation for isotope list for all species. If ‘all’, all isotopes in database are used (this may result in larger computation times!). Default 'all'

  • medium ('air', 'vacuum') – propagating medium when giving inputs with 'wavenum_min', 'wavenum_max'. Does not change anything when giving inputs in wavenumber. Default 'air'

Other Parameters
  • Tref (K) – Reference temperature for calculations (linestrength temperature correction). HITRAN database uses 296 Kelvin. Default 296 K

  • self_absorption (boolean) – Compute self absorption. If False, spectra are optically thin. Default True.

  • truncation (float (\(cm^{-1}\))) – Half-width over which to compute the lineshape, i.e. lines are truncated on each side after truncation (\(cm^{-1}\)) from the line center. If None, use no truncation (lineshapes spread on the full spectral range). Default is 300 \(cm^{-1}\)

    Note

    Large values (> 50) can induce a performance drop (computation of lineshape typically scale as \(~truncation ^2\) ). The default 300 was chosen to maintain a good accuracy, and still exhibit the sub-Lorentzian behavior of most lines far (few hundreds \(cm^{-1}\)) from the line center.

  • neighbour_lines (float (\(cm^{-1}\))) – The calculated spectral range is increased (by neighbour_lines cm-1 on each side) to take into account overlaps from out-of-range lines. Default is 0 \(cm^{-1}\).​

  • wstep (float (cm-1) or 'auto') – Resolution of wavenumber grid. Default 0.01 cm-1. If 'auto', it is ensured that there are slightly more points for each linewidth than the value of "GRIDPOINTS_PER_LINEWIDTH_WARN_THRESHOLD" in radis.config (~/radis.json)

    Note

    wstep = ‘auto’ is optimized for performances while ensuring accuracy, but is still experimental in 0.9.30. Feedback welcome!

  • cutoff (float (~ unit of Linestrength: cm-1/(#.cm-2))) – discard linestrengths that are lower that this, to reduce calculation times. 1e-27 is what is generally used to generate databases such as CDSD. If 0, no cutoff. Default 1e-27.

  • parsum_mode (‘full summation’, ‘tabulation’) – how to compute partition functions, at nonequilibrium or when partition function are not already tabulated. 'full summation' : sums over all (potentially millions) of rovibrational levels. 'tabulation' : builds an on-the-fly tabulation of rovibrational levels (500 - 4000x faster and usually accurate within 0.1%). Default full summation'

    Note

    parsum_mode= ‘tabulation’ is new in 0.9.30, and makes nonequilibrium calculations of small spectra extremelly fast. Will become the default after 0.9.31.

  • pseudo_continuum_threshold (float) – if not 0, first calculate a rough approximation of the spectrum, then moves all lines whose linestrength intensity is less than this threshold of the maximum in a semi-continuum. Values above 0.01 can yield significant errors, mostly in highly populated areas. 80% of the lines can typically be moved in a continuum, resulting in 5 times faster spectra. If 0, no semi-continuum is used. Default 0.

  • save_memory (boolean) – if True, removes databases calculated by intermediate functions (for instance, delete the full database once the linestrength cutoff criteria was applied). This saves some memory but requires to reload the database & recalculate the linestrength for each new parameter. Default False.

  • export_populations ('vib', 'rovib', None) – if not None, store populations in Spectrum. Either store vibrational populations (‘vib’) or rovibrational populations (‘rovib’). Default None

  • export_lines (boolean) – if True, saves details of all calculated lines in Spectrum. This is necessary to later use line_survey(), but can take some space. Default False.

  • chunksize (int, or None) – Splits the lines database in several chuncks during calculation, else the multiplication of lines over all spectral range takes too much memory and slows the system down. Chunksize let you change the default chunck size. If None, all lines are processed directly. Usually faster but can create memory problems. Default None

  • optimization ("simple", "min-RMS", None) – If either "simple" or "min-RMS" LDM optimization for lineshape calculation is used: - "min-RMS" : weights optimized by analytical minimization of the RMS-error (See: [Spectral-Synthesis-Algorithm]) - "simple" : weights equal to their relative position in the grid

    If using the LDM optimization, broadening method is automatically set to 'fft'. If None, no lineshape interpolation is performed and the lineshape of all lines is calculated.

    Refer to [Spectral-Synthesis-Algorithm] for more explanation on the LDM method for lineshape interpolation.

    Default "min-RMS"

  • folding_thresh (float) – Folding is a correction procedure thet is applied when the lineshape is calculated with the fft broadening method and the linewidth is comparable to wstep, that prevents sinc(v) modulation of the lineshape. Folding continues until the lineshape intensity is below folding_threshold. Setting to 1 or higher effectively disables folding correction.

    Range: 0.0 < folding_thresh <= 1.0 Default: 1e-6

  • zero_padding (int) – Zero padding is used in conjunction with the fft broadening method to prevent circular convolution at the cost of performance. When set to -1, padding is set equal to the spectrum length, which guarantees a linear convolution.

    Range: 0 <= zero_padding <= len(w), or zero_padding = -1 Default: -1

  • broadening_method ("voigt", "convolve", "fft") – Calculates broadening with a direct voigt approximation (‘voigt’) or by convoluting independantly calculated Doppler and collisional broadening (‘convolve’). First is much faster, 2nd can be used to compare results. This SpectrumFactory parameter can be manually adjusted a posteriori with:

    sf = SpectrumFactory(...)
    sf.params.broadening_method = 'voigt'
    

    Fast fourier transform 'fft' is only available if using the LDM lineshape calculation optimization. Because the LDM convolves all lines at the same time, and thus operates on large arrays, 'fft' becomes more appropriate than convolutions in real space ('voit', 'convolve' )

    By default, use "fft" for any optimization, and "voigt" if optimization is None .

  • warnings (bool, or one of ['warn', 'error', 'ignore'], dict) – If one of ['warn', 'error', 'ignore'], set the default behaviour for all warnings. Can also be a dictionary to set specific warnings only. Example:

    warnings = {'MissingSelfBroadeningWarning':'ignore',
                'NegativeEnergiesWarning':'ignore',
                'HighTemperatureWarning':'ignore'}
    

    See default_warning_status for more information.

  • verbose (boolean, or int) – If False, stays quiet. If True, tells what is going on. If >=2, gives more detailed messages (for instance, details of calculation times). Default True.

Examples

An example using SpectrumFactory, load_databank(), the Spectrum methods, and units

from radis import SpectrumFactory
from astropy import units as u
sf = SpectrumFactory(wavelength_min=4165 * u.nm,
                     wavelength_max=4200 * u.nm,
                     isotope='1,2',
                     truncation=10,  # cm-1
                     optimization=None,
                     medium='vacuum',
                     verbose=1,    # more for more details
                     )
sf.load_databank('HITRAN-CO2-TEST')        # predefined in ~/radis.json
s = sf.eq_spectrum(Tgas=300 * u.K, path_length=1 * u.cm)
s.rescale_path_length(0.01)    # cm
s.plot('radiance_noslit', Iunit='µW/cm2/sr/nm')

Refer to the online Examples for more cases.

GPU Accelerated Spectra

GPU Accelerated Spectra

GPU Accelerated Spectra
Use Custom Abundances

Use Custom Abundances

Use Custom Abundances
Real-time GPU Accelerated Spectra (Interactive)

Real-time GPU Accelerated Spectra (Interactive)

Real-time GPU Accelerated Spectra (Interactive)
Spectrum Database

Spectrum Database

Spectrum Database
Multi-temperature Fit

Multi-temperature Fit

Multi-temperature Fit
1 temperature fit

1 temperature fit

1 temperature fit

Notes

Inheritance diagram of radis.lbl.factory.SpectrumFactory

High-level wrapper to SpectrumFactory:

Main Methods:

For advanced use:

Inputs and parameters can be accessed a posteriori with :

  • input : physical input

  • params : computational parameters

  • misc : miscallenous parameters (don’t change output)

See also

calc_spectrum()

eq_spectrum(Tgas, mole_fraction=None, path_length=None, pressure=None, name=None) Spectrum[source]

Generate a spectrum at equilibrium.

Parameters
  • Tgas (float or Quantity) – Gas temperature (K)

  • mole_fraction (float) – database species mole fraction. If None, Factory mole fraction is used.

  • path_length (float or Quantity) – slab size (cm). If None, the default Factory path_length is used.

  • pressure (float or Quantity) – pressure (bar). If None, the default Factory pressure is used.

  • name (str) – output Spectrum name (useful in batch)

Returns

s

Returns a Spectrum object

Use the get() method to get something among ['radiance', 'radiance_noslit', 'absorbance', etc...]

Or directly the plot() method to plot it. See [1]_ to get an overview of all Spectrum methods

Return type

Spectrum

Examples

::

from radis import SpectrumFactory sf = SpectrumFactory( wavenum_min=2900, wavenum_max=3200, molecule=”OH”, wstep=0.1, ) sf.fetch_databank(“hitemp”)

s1 = sf.eq_spectrum(Tgas=300, path_length=1, pressure=0.1) s2 = sf.eq_spectrum(Tgas=500, path_length=1, pressure=0.1)

References

1

RADIS doc: Spectrum how to?

eq_spectrum_gpu(Tgas, mole_fraction=None, path_length=None, pressure=None, name=None, emulate=False) Spectrum[source]

Generate a spectrum at equilibrium with calculation of lineshapes and broadening done on the GPU.

Note

This method requires CUDA compatible hardware to execute. For more information on how to setup your system to run GPU-accelerated methods using CUDA and Cython, check GPU Spectrum Calculation on RADIS

Parameters
  • Tgas (float or Quantity) – Gas temperature (K)

  • mole_fraction (float) – database species mole fraction. If None, Factory mole fraction is used.

  • path_length (float or Quantity) – slab size (cm). If None, the default Factory path_length is used.

  • pressure (float or Quantity) – pressure (bar). If None, the default Factory pressure is used.

  • name (str) – output Spectrum name (useful in batch)

Other Parameters

emulate (bool) – if True, execute the GPU code on the CPU (useful for development)

Returns

s

Returns a Spectrum object

Use the get() method to get something among ['radiance', 'radiance_noslit', 'absorbance', etc...]

Or directly the plot() method to plot it. See [1]_ to get an overview of all Spectrum methods

Return type

Spectrum

Examples

GPU Accelerated Spectra

GPU Accelerated Spectra

GPU Accelerated Spectra
Real-time GPU Accelerated Spectra (Interactive)

Real-time GPU Accelerated Spectra (Interactive)

Real-time GPU Accelerated Spectra (Interactive)
eq_spectrum_gpu_interactive(var='transmittance', slit_FWHM=0.0, plotkwargs={}, *vargs, **kwargs) Spectrum[source]
Parameters
  • var (TYPE, optional) – DESCRIPTION. The default is “transmittance”.

  • slit_FWHM (TYPE, optional) – DESCRIPTION. The default is 0.0.

  • *vargs (TYPE) – arguments forwarded to eq_spectrum_gpu()

  • **kwargs (dict) – arguments forwarded to eq_spectrum_gpu() In particular, see emulate=.

  • plotkwargs (dict) – arguments forwarded to plot()

Returns

s – DESCRIPTION.

Return type

TYPE

Examples

from radis import SpectrumFactory
from radis.tools.plot_tools import ParamRange

sf = SpectrumFactory(2200, 2400, # cm-1
                  molecule='CO2',
                  isotope='1,2,3',
                  wstep=0.002,
                  )

sf.fetch_databank('hitemp')

s = sf.eq_spectrum_gpu_interactive(Tgas=ParamRange(300.0,2000.0,1200.0), #K
                               pressure=0.2, #bar
                               mole_fraction=0.1,
                               path_length=ParamRange(0,10,2.0), #cm
                               slit_FWHM=ParamRange(0,1,0), #cm
                               emulate=False,  # if True, execute the GPU code on the CPU
                               )
fit_spectrum(s_exp, model, fit_parameters, bounds={}, plot=False, solver_options={'maxiter': 300}, **kwargs) Union[Spectrum, OptimizeResult][source]

Fit an experimental spectrum with an arbitrary model and an arbitrary number of fit parameters.

Parameters
  • s_exp (Spectrum) – experimental spectrum. Should have only spectral array only. Use take(), e.g:

    sf.fit_spectrum(s_exp.take('transmittance'))
    
  • model (func -> Spectrum) – a line-of-sight model returning a Spectrum. Example : Tvib12Tvib3Trot_NonLTEModel()

  • fit_parameters (dict) –

    example:

    {fit_parameter:initial_value}
    
  • bounds (dict, optional) –

    example:

    {fit_parameter:[min, max]}
    
  • fixed_parameters (dict) –

    fixed parameters given to the model. Example:

    fit_spectrum(fixed_parameters={"vib_distribution":"treanor"})
    
Other Parameters
  • plot (bool) – if True, plot spectra as they are computed; and plot the convergence of the residual. Default False

  • solver_options (dict) – parameters forwarded to the solver. More info in minimize Example:

    {"maxiter": (int)  max number of iteration default ``300``,
     }
    
  • kwargs (dict) – forwarded to fit_spectrum()

Returns

  • s_best (Spectrum) – best spectrum

  • res (OptimizeResults) – output of minimize

Examples

See a one-temperature fit example and a non-LTE fit example

Multi-temperature Fit

Multi-temperature Fit

Multi-temperature Fit
1 temperature fit

1 temperature fit

1 temperature fit

More advanced tools for interactive fitting of multi-dimensional, multi-slabs spectra can be found in fitroom.

generate_perf_profile()[source]

Generate a visual/interactive performance profile diagram for the last calculated spectrum, with tuna.

Requires a profiler key with in Spectrum.conditions, and tuna installed.

Note

print_perf_profile() is an ascii-version which does not require tuna.

Examples

sf = SpectrumFactory(...)
sf.eq_spectrum(...)
sf.generate_perf_profile()

See typical output in https://github.com/radis/radis/pull/325

https://user-images.githubusercontent.com/16088743/128018032-6049be72-1881-46ac-9d7c-1ed89f9c4f42.png

Note

You can also profile with tuna directly:

python -m cProfile -o program.prof your_radis_script.py
tuna your_radis_script.py
non_eq_spectrum(Tvib, Trot, Ttrans=None, mole_fraction=None, path_length=None, pressure=None, vib_distribution='boltzmann', rot_distribution='boltzmann', overpopulation=None, name=None) Spectrum[source]

Calculate emission spectrum in non-equilibrium case. Calculates absorption with broadened linestrength and emission with broadened Einstein coefficient.

Parameters
  • Tvib (float) – vibrational temperature [K] can be a tuple of float for the special case of more-than-diatomic molecules (e.g: CO2)

  • Trot (float) – rotational temperature [K]

  • Ttrans (float) – translational temperature [K]. If None, translational temperature is taken as rotational temperature (valid at 1 atm for times above ~ 2ns which is the RT characteristic time)

  • mole_fraction (float) – database species mole fraction. If None, Factory mole fraction is used.

  • path_length (float or Quantity) – slab size (cm). If None, the default Factory path_length is used.

  • pressure (float or Quantity) – pressure (bar). If None, the default Factory pressure is used.

Other Parameters
  • vib_distribution ('boltzmann', 'treanor') – vibrational distribution

  • rot_distribution ('boltzmann') – rotational distribution

  • overpopulation (dict, or None) –

    add overpopulation factors for given levels:

    {level:overpopulation_factor}
    
  • name (str) – output Spectrum name (useful in batch)

Returns

s

Returns a Spectrum object

Use the get() method to get something among ['radiance', 'radiance_noslit', 'absorbance', etc...]

Or directly the plot() method to plot it. See [1]_ to get an overview of all Spectrum methods

Return type

Spectrum

Examples

from radis import SpectrumFactory
sf = SpectrumFactory(
wavenum_min=2000,
wavenum_max=3000,
molecule="CO",
isotope="1,2,3",
wstep="auto"
)
sf.fetch_databank("hitemp", load_columns='noneq')

s1 = sf.non_eq_spectrum(Tvib=2000, Trot=600, path_length=1, pressure=0.1)
s2 = sf.non_eq_spectrum(Tvib=2000, Trot=600, path_length=1, pressure=0.1)

Multi-vibrational temperature. Below we compare non-LTE spectra of CO2 where all vibrational temperatures are equal, or where the bending & symmetric modes are in equilibrium with rotation

from radis import SpectrumFactory
sf = SpectrumFactory(
wavenum_min=2000,
wavenum_max=3000,
molecule="CO2",
isotope="1,2,3",
)
sf.fetch_databank("hitemp", load_columns='noneq')
# nonequilibrium between bending+symmetric and asymmetric modes :
s1 = sf.non_eq_spectrum(Tvib=(600, 600, 2000), Trot=600, path_length=1, pressure=1)
# all vibrational temperatures are equal :
s2 = sf.non_eq_spectrum(Tvib=(2000, 2000, 2000), Trot=600, path_length=1, pressure=1)

References

1

RADIS doc: Spectrum how to?

optically_thin_power(Tgas=None, Tvib=None, Trot=None, Ttrans=None, vib_distribution='boltzmann', rot_distribution='boltzmann', mole_fraction=None, path_length=None, unit='mW/cm2/sr')[source]

Calculate total power emitted in equilibrium or non-equilibrium case in the optically thin approximation: it sums all emission integral over the total spectral range.

Warning

this is a fast implementation that doesnt take into account the contribution of lines outside the given spectral range. It is valid for spectral ranges surrounded by no lines, and spectral ranges much broaded than the typical line broadening (~ 1-10 cm-1 in the infrared)

If what you’re looking for is an accurate simulation on a narrow spectral range you better calculate the spectrum (that does take all of that into account) and integrate it with get_power()

Parameters
  • Tgas (float) – equilibrium temperature [K] If doing a non equilibrium case it should be None. Use Ttrans for translational temperature

  • Tvib (float) – vibrational temperature [K]

  • Trot (float) – rotational temperature [K]

  • Ttrans (float) – translational temperature [K]. If None, translational temperature is taken as rotational temperature (valid at 1 atm for times above ~ 2ns which is the RT characteristic time)

  • mole_fraction (float) – database species mole fraction. If None, Factory mole fraction is used.

  • path_length (float) – slab size (cm). If None, Factory mole fraction is used.

  • unit (str) – output unit. Default 'mW/cm2/sr'

Returns

float – see unit=.

Return type

Returns total power density in mW/cm2/sr (unless different unit is chosen),

predict_time()[source]

predict_time(self) uses the input parameters like Spectral Range, Number of lines, wstep, truncation to predict the estimated calculation time for the Spectrum broadening step(bottleneck step) for the current optimization and broadening_method. The formula for predicting time is based on benchmarks performed on various parameters for different optimization, broadening_method and deriving its time complexity.

Benchmarks: https://anandxkumar.github.io/Benchmark_Visualization_GSoC_2021/

Complexity vs Calculation Time Visualizations LBL>Voigt: LINK, DIT>Voigt: LINK, DIT>FFT: LINK

Returns

float

Return type

Predicted time in seconds.

print_perf_profile(number_format='{:.3f}', precision=16)[source]

Prints Profiler output dictionary in a structured manner for the last calculated spectrum

Examples

sf.print_perf_profile()

# output >>
    spectrum_calculation      0.189s ████████████████
        check_line_databank              0.000s
        check_non_eq_param               0.042s ███
        fetch_energy_5                   0.015s █
        calc_weight_trans                0.008s
        reinitialize                     0.002s
            copy_database                    0.000s
            memory_usage_warning             0.002s
            reset_population                 0.000s
        calc_noneq_population            0.041s ███
            part_function                    0.035s ██
            population                       0.006s
        scaled_non_eq_linestrength       0.005s
            map_part_func                    0.001s
            corrected_population_se          0.003s
        calc_emission_integral           0.006s
        applied_linestrength_cutoff      0.002s
        calc_lineshift                   0.001s
        calc_hwhm                        0.007s
        generate_wavenumber_arrays       0.001s
        calc_line_broadening             0.074s ██████
            precompute_LDM_lineshapes        0.012s
            LDM_Initialized_vectors          0.000s
            LDM_closest_matching_line        0.001s
            LDM_Distribute_lines             0.001s
            LDM_convolve                     0.060s █████
            others                           0.001s
        calc_other_spectral_quan         0.003s
        generate_spectrum_obj            0.000s
        others                           -0.016s
Other Parameters

precision (int, optional) – total number of blocks. Default 16.

Transmittance(s: Spectrum) Spectrum[source]

Returns a new Spectrum with only the transmittance component of s

Parameters

s (Spectrum) – Spectrum object

Returns

s_trSpectrum object, with only the transmittance, absorbance and/or abscoeff part of s, where radiance_noslit , emisscoeff and emissivity_noslit (if they exist) have been set to 0

Return type

Spectrum

Examples

This function is useful to use Spectrum algebra operations:

s = calc_spectrum(...)   # contains emission & absorption arrays
tr = Transmittance(s)    # contains 'radiance_noslit' array only
tr -= 0.1    # arithmetic operation is applied to Transmittance only

Equivalent to:

rad = s.take('transmittance')
Transmittance_noslit(s: Spectrum) Spectrum[source]

Returns a new Spectrum with only the transmittance_noslit component of s

Parameters

s (Spectrum) – Spectrum object

Returns

s_trSpectrum object, with only transmittance_noslit defined

Return type

Spectrum

Examples

This function is useful to use Spectrum algebra operations:

s = calc_spectrum(...)   # contains emission & absorption arrays
tr = Transmittance_noslit(s) # contains 'radiance_noslit' array only
tr -= 0.1    # arithmetic operation is applied to Transmittance_noslit only

Equivalent to:

rad = s.take('transmittance_noslit')
calc_spectrum(wmin=None, wmax=None, wunit=cm - 1, Tgas=None, Tvib=None, Trot=None, pressure=1.01325, molecule=None, isotope='all', mole_fraction=1, path_length=1, databank='hitran', medium='air', wstep=0.01, truncation=50, neighbour_lines=0, cutoff=1e-27, parsum_mode='full summation', optimization='simple', chunksize=None, broadening_method='voigt', overpopulation=None, name=None, save_to='', use_cached=True, mode='cpu', export_lines=False, verbose=True, return_factory=False, **kwargs) Spectrum[source]

Calculate a Spectrum.

Can automatically download databases (HITRAN/HITEMP) or use manually downloaded local databases, under equilibrium or non-equilibrium, with or without overpopulation, using either CPU or GPU.

It is a wrapper to SpectrumFactory class. For advanced used, please refer to the aforementionned class.

Parameters
  • wmin, wmax (float [\(cm^{-1}\)] or Quantity) –

    wavelength/wavenumber range. If no units are given, use \(cm^{-1}\)

    calc_spectrum(2000, 2300, ... )   # cm-1
    calc_spectrum(4000, 4200, wunit='nm', ...)
    

    You can use arbitrary units:

    import astropy.units as u
    calc_spectrum(2.5*u.um, 3.0*u.um, ...)
    
  • wunit ('nm', 'cm-1') – unit for wmin and wmax. Default is "cm-1".

  • Tgas (float [\(K\)]) – Gas temperature. If non equilibrium, is used for \(T_{translational}\). Default 300 K​

  • Tvib, Trot (float [\(K\)]) – Vibrational and rotational temperatures (for non-LTE calculations). If None, they are at equilibrium with Tgas ​.

  • pressure (float [\(bar\)] or Quantity) –

    partial pressure of gas in bar. Default 1.01325 (1 atm)​. Use arbitrary units:

    import astropy.units as u
    calc_spectrum(..., pressure=20*u.mbar)
    
  • molecule (int, str, list or None) – molecule id (HITRAN format) or name. For multiple molecules, use a list. The 'isotope', 'mole_fraction', 'databank' and 'overpopulation' parameters must then be dictionaries. If None, the molecule can be infered from the database files being loaded. See the list of supported molecules in MOLECULES_LIST_EQUILIBRIUM and MOLECULES_LIST_NONEQUILIBRIUM. Default None.​

  • isotope (int, list, str of the form '1,2', or 'all', or dict) – isotope id (sorted by relative density: (eg: 1: CO2-626, 2: CO2-636 for CO2). See [HITRAN-2020] documentation for isotope list for all species. If 'all', all isotopes in database are used (this may result in larger computation times!). Default 'all'.

    For multiple molecules, use a dictionary with molecule names as keys

    isotope={'CO2':'1,2' ,  'CO':'1,2,3' }​
    
  • mole_fraction (float or dict) – database species mole fraction. Default 1.

    For multiple molecules, use a dictionary with molecule names as keys

    mole_fraction={'CO2': 0.8, 'CO':0.2}​
    
  • path_length (float [\(cm\)] or Quantity) –

    slab size. Default 1 cm​. Use arbitrary units:

    import astropy.units as u
    calc_spectrum(..., path_length=1000*u.km)
    
  • databank (str or dict) – can be either: - 'hitran', to fetch the latest HITRAN version

    through fetch_hitran() (download full database with [HAPI]) or fetch_astroquery() (download only the required range). To use one mode or the other, use

    databank=('hitran', 'full')     # download and cache full database, all isotopes
    databank=('hitran', 'range')    # download and cache required range, required isoope
    
    • 'hitemp', to fetch the latest HITEMP version through fetch_hitemp(). Downloads all lines and all isotopes.

    • 'exomol', to fetch the latest ExoMol database through fetch_exomol(). To download a specific database use (more info in fetch_exomol)

      databank=('exomol', 'EBJT')   # 'EBJT' is a specific ExoMol database name
      
    • 'geisa', to fetch the GEISA 2020 database through fetch_geisa(). Downloads all lines and all isotopes.

    • the name of a a valid database file, in which case the format is inferred. For instance, '.par' is recognized as hitran/hitemp format. Accepts wildcards '*' to select multiple files

      databank='PATH/TO/co_*.par'
      
    • the name of a spectral database registered in your ~/radis.json configuration file

      databank='MY_SPECTRAL_DATABASE'
      

    Default 'hitran'. See DatabankLoader for more information on line databases, and DBFORMAT for your ~/radis.json file format.

    For multiple molecules, use a dictionary with molecule names as keys:

    databank='hitran'     # automatic download (or 'hitemp')
    databank='PATH/TO/05_HITEMP2019.par'    # path to a file
    databank='*CO2*.par' #to get all the files that have CO2 in their names (case insensitive)
    databank='HITEMP-2019-CO'   # user-defined database in Configuration file
    databank = {'CO2' : 'PATH/TO/05_HITEMP2019.par', 'CO' : 'hitran'}  # for multiple molecules
    
Other Parameters
  • medium ('air', 'vacuum') – propagating medium when giving inputs with 'wavenum_min', 'wavenum_max'. Does not change anything when giving inputs in wavenumber. Default ``’air’``

  • wstep (float (\(cm^{-1}\)) or 'auto') – Resolution of wavenumber grid. Default 0.01 cm-1. If 'auto', it is ensured that there are slightly more or less than radis.config ['GRIDPOINTS_PER_LINEWIDTH_WARN_THRESHOLD'] points for each linewidth.

    Note

    wstep = ‘auto’ is optimized for performances while ensuring accuracy, but is still experimental in 0.9.30. Feedback welcome!

  • truncation (float (\(cm^{-1}\))) – Half-width over which to compute the lineshape, i.e. lines are truncated on each side after truncation (\(cm^{-1}\)) from the line center. If None, use no truncation (lineshapes spread on the full spectral range). Default is 300 \(cm^{-1}\)

    Note

    Large values (> 50) can induce a performance drop (computation of lineshape typically scale as \(~truncation ^2\) ). The default 300 was chosen to maintain a good accuracy, and still exhibit the sub-Lorentzian behavior of most lines far (few hundreds \(cm^{-1}\)) from the line center.

  • neighbour_lines (float (\(cm^{-1}\))) – The calculated spectral range is increased (by neighbour_lines cm-1 on each side) to take into account overlaps from out-of-range lines. Default is 0 \(cm^{-1}\).​

  • cutoff (float (~ unit of Linestrength: \(cm^{-1}/(molec.cm^{-2})\))) – discard linestrengths that are lower that this, to reduce calculation times. 1e-27 is what is generally used to generate line databases such as CDSD. If 0, no cutoff. Default 1e-27 .

  • parsum_mode (‘full summation’, ‘tabulation’) – how to compute partition functions, at nonequilibrium or when partition function are not already tabulated. 'full summation' : sums over all (potentially millions) of rovibrational levels. 'tabulation' : builds an on-the-fly tabulation of rovibrational levels (500 - 4000x faster and usually accurate within 0.1%). Default 'full summation'

    Note

    parsum_mode= ‘tabulation’ is new in 0.9.30, and makes nonequilibrium calculations of small spectra extremelly fast. Will become the default after 0.9.31.

  • optimization ("simple", "min-RMS", None) – If either "simple" or "min-RMS" LDM optimization for lineshape calculation is used:

    • "min-RMS" : weights optimized by analytical minimization of the RMS-error (See: [Spectral-Synthesis-Algorithm])

    • "simple" : weights equal to their relative position in the grid

    If using the LDM optimization, broadening method is automatically set to 'fft'. If None, no lineshape interpolation is performed and the lineshape of all lines is calculated. Refer to [Spectral-Synthesis-Algorithm] for more explanation on the LDM method for lineshape interpolation. Default "simple".

  • overpopulation (dict) – dictionary of overpopulation compared to the given vibrational temperature. Default None. Example:

    overpopulation = {'CO2' : {'(00`0`0)->(00`0`1)': 2.5,
                               '(00`0`1)->(00`0`2)': 1,
                               '(01`1`0)->(01`1`1)': 1,
                               '(01`1`1)->(01`1`2)': 1 }
                     }​
    
  • export_lines (boolean) – if True, saves details of all calculated lines in Spectrum. This is necessary to later use line_survey(), but can take some space. Default False.

  • name (str) – name of the output Spectrum. If None, a unique ID is generated.

  • save_to (str) – save to a spec file which contains absorption & emission features, all calculation parameters, and can be opened with load_spec(). File can be reloaded and exported to text formats afterwards, see savetxt(). If file already exists, replace.

  • use_cached (boolean) – use cached files for line database and energy database. Default True.​

  • verbose (boolean, or int) – If False, stays quiet. If True, tells what is going on. If >=2, gives more detailed messages (for instance, details of calculation times). Default True.​

  • mode ('cpu', 'gpu', 'emulated_gpu') – if set to 'cpu', computes the spectra purely on the CPU. if set to 'gpu', offloads the calculations of lineshape and broadening steps to the GPU making use of parallel computations to speed up the process. Default 'cpu'. Note that mode='gpu' requires CUDA compatible hardware to execute. For more information on how to setup your system to run GPU-accelerated methods using CUDA and Cython, check GPU Spectrum Calculation on RADIS To try the GPU code without an actual GPU, you can use mode='emulated_gpu'. This will run the GPU equivalent code on the CPU.

  • return_factory (bool) – if True, return the SpectrumFactory that computes the spectrum. Useful to access computational parameters, the line database, or to start batch-computations from a first spectrum calculation. Ex:

    s, sf = calc_spectrum(..., return_factory=True)
    sf.df1  # see the lines calculated
    sf.eq_spectrum(...)  #  new calculation without reloading the database
    
  • **kwargs (other inputs forwarded to SpectrumFactory) – For instance: warnings. See SpectrumFactory documentation for more details on input.

Returns

  • Spectrum – Output spectrum:

    • Use the get() method to retrieve a spectral quantity ('radiance', 'radiance_noslit', 'absorbance', etc…)

    • Or the plot() method to plot it directly.

    • See [1]_ to get an overview of all Spectrum methods

  • :py:class:`~radis.lbl.factory.SpectrumFactory` (if using return_factory=True) – if multiple molecules, a dictionary of factories is returned

References

1

RADIS doc: Spectrum how to?

​.. [2] RADIS GPU support: GPU Calculations on RADIS

Examples

Calculate a CO spectrum from the HITRAN database:

from radis import calc_spectrum
s = calc_spectrum(1900, 2300,         # cm-1
                  molecule='CO',
                  isotope='1,2,3',
                  pressure=1.01325,   # bar
                  Tgas=1000,
                  mole_fraction=0.1,
                  databank='hitran',  # or 'hitemp'
                  )
s.apply_slit(0.5, 'nm')
s.plot('radiance')

This example uses the apply_slit() and plot() methods. See also line_survey():

s.line_survey(overlay='radiance')

Calculate a CO2 spectrum from the CDSD-4000 database:

s = calc_spectrum(2200, 2400,   # cm-1
                  molecule='CO2',
                  isotope='1',
                  databank='/path/to/cdsd/databank/in/npy/format/',
                  pressure=0.1,  # bar
                  Tgas=1000,
                  mole_fraction=0.1,
                  mode='gpu'
                  )

s.plot('absorbance')

This example uses the eq_spectrum_gpu() method to calculate the spectrum on the GPU. The databank points to the CDSD-4000 databank that has been pre-processed and stored in numpy.npy format. ​ Refer to the online Examples for more cases, and to the Spectrum page for details on post-processing methods.

For more details on how to use the GPU method and process the database, refer to the examples linked above and the documentation on GPU support for RADIS. ​ .. minigallery:: radis.calc_spectrum

References

cite: RADIS is built on the shoulders of many state-of-the-art packages and databases. If using RADIS to compute spectra, make sure you cite all of them, for proper reproducibility and acknowledgement of the work ! See How to cite? and the cite() method.

See also

SpectrumFactory

calculated_spectrum(w, I, wunit='nm', Iunit='mW/cm2/sr/nm', conditions=None, cond_units=None, populations=None, name=None) Spectrum[source]

Convert (w, I) into a Spectrum object that has unit conversion, plotting and slit convolution capabilities.

Parameters
  • w (np.array) – wavelength, or wavenumber

  • I (np.array) – intensity (no slit)

  • wunit ('nm', 'cm-1', 'nm_vac') – wavespace unit: wavelength in air ('nm'), wavenumber ('cm-1'), or wavelength in vacuum ('nm_vac'). Default 'nm'.

  • Iunit (str) – intensity unit (can be ‘counts’, ‘mW/cm2/sr/nm’, etc…). Default ‘mW/cm2/sr/nm’ (note that non-convoluted Specair spectra are in ‘mW/cm2/sr/µm’)

Other Parameters
  • conditions (dict) – (optional) calculation conditions to be stored with Spectrum. Default None

  • cond_units (dict) – (optional) calculation conditions units. Default None

  • populations (dict) – populations to be stored in Spectrum. Default None

  • name (str) – (optional) give a name

Examples

# w, I are numpy arrays for wavelength and radiance
from radis import calculated_spectrum
s = calculated_spectrum(w, I, wunit='nm', Iunit='W/cm2/sr/nm')     # creates 'radiance_noslit'
cdsd2df(fname, version='hitemp', cache=True, load_columns=None, verbose=True, drop_non_numeric=True, load_wavenum_min=None, load_wavenum_max=None, engine='pytables')[source]

Convert a CDSD-HITEMP [1]_ or CDSD-4000 [2]_ file to a Pandas dataframe.

Parameters
  • fname (str) – CDSD file name

  • version (str (‘4000’, ‘hitemp’)) – CDSD version

  • cache (boolean, or ‘regen’) – if True, a pandas-readable HDF5 file is generated on first access, and later used. This saves on the datatype cast and conversion and improves performances a lot (but changes in the database are not taken into account). If False, no database is used. If ‘regen’, temp file are reconstructed. Default True.

  • load_columns (list) – columns to load. If None, loads everything

    Note

    this is only relevant if loading from a cache file. To generate the cache file, all columns are loaded anyway.

Other Parameters
  • drop_non_numeric (boolean) – if True, non numeric columns are dropped. This improves performances, but make sure all the columns you need are converted to numeric formats before hand. Default True. Note that if a cache file is loaded it will be left untouched.

  • load_wavenum_min, load_wavenum_max (float) – if not 'None', only load the cached file if it contains data for wavenumbers above/below the specified value. See :py:func`~radis.io.cache_files.load_h5_cache_file`. Default 'None'.

  • engine (‘pytables’, ‘vaex’) – format for Hdf5 cache file. Default pytables

Returns

df – dataframe containing all lines and parameters

Return type

pandas Dataframe

Notes

CDSD-4000 Database can be downloaded from 3

Performances: I had huge performance trouble with this function, because the files are huge (500k lines) and the format is to special (no space between numbers…) to apply optimized methods such as pandas’s. A line by line reading isn’t so bad, using struct to parse each line. However, we waste typing determining what every line is. I ended up using the fromfiles functions from numpy, not considering n (line return) as a special character anymore, and a second call to numpy to cast the correct format. That ended up being twice as fast.

  • initial: 20s / loop

  • with mmap: worse

  • w/o readline().rstrip(’n’): still 20s

  • numpy fromfiles: 17s

  • no more readline, 2x fromfile 9s

Think about using cache mode too:

  • no cache mode 9s

  • cache mode, first time 22s

  • cache mode, then 2s

Moving to HDF5:

On cdsd_02069_02070 (56 Mb)

Reading:

cdsd2df(): 9.29 s
cdsd2df(cache=True [old .txt version]): 2.3s
cdsd2df(cache=True [new h5 version, table]): 910ms
cdsd2df(cache=True [new h5 version, fixed]): 125ms

Storage:

%timeit df.to_hdf("cdsd_02069_02070.h5", "df", format="fixed")  337ms
%timeit df.to_hdf("cdsd_02069_02070.h5", "df", format="table")  1.03s

References

Note that CDSD-HITEMP is used as the line database for CO2 in HITEMP 2010

1

HITEMP 2010, Rothman et al., 2010

2

CDSD-4000 article, Tashkun et al., 2011

3

CDSD-4000 database

See also

hit2df()

config = {'AUTO_UPDATE_DATABASE': False, 'AUTO_UPDATE_SPEC': False, 'DEBUG_MODE': False, 'DEFAULT_DOWNLOAD_PATH': '~/.radisdb', 'GRIDPOINTS_PER_LINEWIDTH_ERROR_THRESHOLD': 1, 'GRIDPOINTS_PER_LINEWIDTH_WARN_THRESHOLD': 3, 'MEMORY_MAPPING_ENGINE': 'auto', 'OLDEST_COMPATIBLE_VERSION': '0.9.1', 'RESAMPLING_TOLERANCE_THRESHOLD': 0.005, 'SPARSE_WAVERANGE': 'auto', 'USE_CYTHON': True, '_HELLO!': 'This is your RADIS configuration file. Any key here will overwrite the values of the radis/default_radis.json file on your local computer (see online version of the latest release: https://github.com/radis/radis/blob/master/radis/default_radis.json). More information on the online docs : https://radis.readthedocs.io/en/latest/lbl/lbl.html#label-lbl-config-file', 'database': {}, 'plot': {'context': 'poster', 'plotlib': 'publib', 'style': 'origin'}, 'spectroscopic_constants': {'CO': 'molecules_data.json', 'CO2': 'molecules_data.json'}}[source]

RADIS configuration parameters

Parameters
  • “DEBUG_MODE” (False) –

    bool: change this at runtime with:

    import radis
    radis.config["DEBUG_MODE"] = True
    

    Use the printdbg() function in radis.misc, typically with:

    if __debug__: printdbg(...)
    

    so that printdbg are removed by the Python preprocessor when running in optimize mode:

    python -O *.py
    
  • “AUTO_UPDATE_SPEC” (False) – bool: experimental feature used to autoupdate .spec files to the latest format, by simply saving them again once they’re loaded and fixed. Warning! Better have a copy of your files before that, or a way to regenerate them.

    Example : Add to the top of your script (once is enough!):

    import radis
    radis.config["AUTO_UPDATE_SPEC"] = True
    

    You can also see: _update_to_latest_format()

“AUTO_UPDATE_DATABASE”: False

bool: experimental feature used to autoupdate .h5 files to the latest format, by simply saving them again once they’re loaded and fixed. Warning! Better have a copy of your files before that, or a way to regenerate them.

Example. Add to the top of your script (once is enough!):

import radis
radis.AUTO_UPDATE_DATABASE = True
“OLDEST_COMPATIBLE_VERSION”: “0.9.1”

str: forces to regenerate cache files that were created in a previous version See also : load_h5_cache_file()

“USE_CYTHON”: True

bool: try to use Cython functions when possible

See more in radis.misc.arrays.add_at()

“GRIDPOINTS_PER_LINEWIDTH_WARN_THRESHOLD”: 3

float: to determine the optimal value of wstep using minimum FWHM value of spectrum. Makes sure there are enough gridpoints per line.

See more in : radis.lbl.broadening.BroadenFactory._check_accuracy()

“GRIDPOINTS_PER_LINEWIDTH_ERROR_THRESHOLD”: 1

float: to determine the minimum feasible value of wstep using minimum FWHM value of spectrum. Makes sure there are enough gridpoints per line.

See more in : radis.lbl.broadening.BroadenFactory._check_accuracy()

“SPARSE_WAVERANGE”: True

bool: if True, allow special optimizations to improve performances for large spectra that are sparse, i.e there are no lines within truncation distance. In that case, spectral calculations can be an order of magnitude faster, and result in less memory use. This optimization may result in a small but unnecessary overhead when there are lines everywhere in the spectral range considered. In such cases, you may deactivate it by setting radis.config['SPARSE_WAVERANGE'] = False Default True

See more in radis.lbl.broadening.BroadenFactory._apply_lineshape_LDM()

“RESAMPLING_TOLERANCE_THRESHOLD” 5e-3

an error if raises if areas do not match by a value above this threshold, during resampling. See resample()

Default 5e-3

Notes

Default values are read from the radis/default_radis.json file.

All values are overriden at runtime by the keys in the user JSON file ~/radis.json (json) (in particular, the list of databases)

See more in the Configuration file documentation.

Type

dict

experimental_spectrum(w, I, wunit='nm', Iunit='count', conditions={}, cond_units=None, name=None) Spectrum[source]

Convert (w, I) into a Spectrum object that has unit conversion and plotting capabilities. Convolution is not available as the spectrum is assumed to have be measured experimentally (hence it is already convolved with the slit function)

Parameters
  • w (np.array) – wavelength, or wavenumber

  • I (np.array) – intensity

  • wunit ('nm', 'cm-1', 'nm_vac') – wavespace unit: wavelength in air ('nm'), wavenumber ('cm-1'), or wavelength in vacuum ('nm_vac'). Default 'nm'.

  • Iunit (str) – intensity unit (can be 'count', ‘mW/cm2/sr/nm’, etc…). Default 'count' (i.e., non calibrated output)

Other Parameters
  • conditions (dict) – (optional) calculation conditions to be stored with Spectrum

  • cond_units (dict) – (optional) calculation conditions units

  • name (str) – (optional) give a name

Examples

Load and plot an experimental spectrum:

from numpy import loadtxt
from radis import experimental_spectrum
w, I = loadtxt('my_file.txt').T    # transpose is often useful, depending on your data.
s = experimental_spectrum(w, I, Iunit='mW/cm2/sr/nm')             # creates 'radiance'
s.plot()
fetch_astroquery(molecule, isotope, wmin, wmax, verbose=True, cache=True, expected_metadata={}, engine='pytables-fixed')[source]

Download a HITRAN line database to a Pandas DataFrame.

Wrapper to the fetch function of Astroquery [1]_ (itself based on [HAPI])

Note

if using, cite [HAPI] and [HITRAN-2020]

Parameters
  • molecule (str, or int) – molecule name or identifier

  • isotope (int) – isotope number

  • wmin, wmax (float (cm-1)) – wavenumber min and max

Other Parameters
  • verbose (boolean) – Default True

  • cache (boolean or 'regen') – if True, tries to find a .h5 cache file in the Astroquery cache_location, that would match the requirements. If not found, downloads it and saves the line dataframe as a .h5 file in the Astroquery. If 'regen', delete existing cache file to regerenate it.

  • expected_metadata (dict) – if cache=True, check that the metadata in the cache file correspond to these attributes. Arguments molecule, isotope, wmin, wmax are already added by default.

References

1

Astroquery

See also

astroquery.hitran.core.Hitran.query_lines_async(), astroquery.query.BaseQuery.cache_location

fetch_exomol(molecule, database=None, local_databases=None, databank_name='EXOMOL-{molecule}', isotope='1', load_wavenum_min=None, load_wavenum_max=None, columns=None, cache=True, verbose=True, clean_cache_files=True, return_local_path=False, return_partition_function=False, engine='default', output='pandas', skip_optional_data=True)[source]

Stream ExoMol file from EXOMOL website. Unzip and build a HDF5 file directly.

Returns a Pandas DataFrame containing all lines.

Parameters
  • molecule (str) – ExoMol molecule

  • database (str) – database name. Ex:: POKAZATEL or BT2 for H2O. See KNOWN_EXOMOL_DATABASE_NAMES. If None and there is only one database available, use it.

  • local_databases (str) – where to create the RADIS HDF5 files. Default "~/.radisdb/exomol". Can be changed in radis.config["DEFAULT_DOWNLOAD_PATH"] or in ~/radis.json config file

  • databank_name (str) – name of the databank in RADIS Configuration file Default "EXOMOL-{molecule}"

  • isotope (str or int) – load only certain isotopes, sorted by terrestrial abundances : '1', '2', etc. Default 1.

    Note

    In RADIS, isotope abundance is included in the line intensity calculation. However, the terrestrial abundances used may not be relevant to non-terrestrial applications. By default, the abundance is given reading HITRAN data. If the molecule does not exist in the HITRAN database, the abundance is read from the radis/radis_default.json configuration file, which can be modified by editing radis.config after import or directly by editing the user ~/radis.json user configuration file (overwrites radis_default.json). In the radis/radis_default.json file, values were calculated with a simple model based on the terrestrial isotopic abundance of each element.

  • load_wavenum_min, load_wavenum_max (float (cm-1)) – load only specific wavenumbers.

  • columns (list of str) – list of columns to load. If None, returns all columns in the file.

Other Parameters
  • cache (bool, or 'regen' or 'force') – if True, use existing HDF5 file. If False or 'regen', rebuild it. If 'force', crash if not cache file found. Default True.

  • verbose (bool)

  • clean_cache_files (bool) – if True clean downloaded cache files after HDF5 are created.

  • return_local_path (bool) – if True, also returns the path of the local database file.

  • return_partition_function (bool) – if True, also returns a PartFuncExoMol object.

  • engine (‘vaex’, ‘feather’) – which memory-mapping library to use. If ‘default’ use the value from ~/radis.json

  • output (‘pandas’, ‘vaex’, ‘jax’) – format of the output DataFrame. If 'jax', returns a dictionary of jax arrays. If 'vaex', output is a vaex.dataframe.DataFrameLocal

    Note

    Vaex DataFrames are memory-mapped. They do not take any space in RAM and are extremelly useful to deal with the largest databases.

  • skip_optional_data (bool) – If False, fetch all fields which are marked as available in the ExoMol definition file. If True, load only the first 4 columns of the states file (“i”, “E”, “g”, “J”). The structure of the columns above 5 depend on the the definitions file (*.def) and the Exomol version. If skip_optional_data=False, two errors may occur:

Returns

  • df (pd.DataFrame) – Line list A HDF5 file is also created in local_databases and referenced in the RADIS config file with name databank_name

  • local_path (str) – path of local database file if return_local_path

Examples

Calculate a spectrum from ExoMol

Calculate a spectrum from ExoMol

Calculate a spectrum from ExoMol
Compare CO xsections from the ExoMol and HITEMP database

Compare CO xsections from the ExoMol and HITEMP database

Compare CO xsections from the ExoMol and HITEMP database

Notes

if using load_only_wavenum_above/below or isotope, the whole database is anyway downloaded and uncompressed to local_databases fast access .HDF5 files (which will take a long time on first call). Only the expected wavenumber range & isotopes are returned. The .HFD5 parsing uses hdf2df()

References

1

Tennyson, J., Yurchenko, S. N., Al-Refaie, A. F., Barton, E. J., Chubb, K. L., Coles, P. A., … Zak, E. (2016). The ExoMol database: molecular line lists for exoplanet and other hot atmospheres. https://doi.org/10.1016/j.jms.2016.05.002

2

Tennyson, J., Yurchenko, S. N., Al-Refaie, A. F., Clark, V. H. J., Chubb, K. L., Conway, E. K., … Yurchenko, O. P. (2020). The 2020 release of the ExoMol database: Molecular line lists for exoplanet and other hot atmospheres. Journal of Quantitative Spectroscopy and Radiative Transfer, 255, 107228. https://doi.org/10.1016/j.jqsrt.2020.107228

fetch_geisa(molecule, local_databases=None, databank_name='GEISA-{molecule}', isotope=None, load_wavenum_min=None, load_wavenum_max=None, columns=None, cache=True, verbose=True, chunksize=100000, clean_cache_files=True, return_local_path=False, engine='default', output='pandas', parallel=True)[source]

Stream GEISA file from GEISA website. Unzip and build a HDF5 file directly.

Returns a Pandas DataFrame containing all lines.

Parameters
  • molecule (all 58 GEISA 2020 molecules. See here https://geisa.aeris-data.fr/interactive-access/?db=2020&info=ftp)

  • local_databases (str) – where to create the RADIS HDF5 files. Default "~/.radisdb/geisa". Can be changed in radis.config["DEFAULT_DOWNLOAD_PATH"] or in ~/radis.json config file

  • databank_name (str) – name of the databank in RADIS Configuration file Default "GEISA-{molecule}"

  • isotope (str, int or None) – load only certain isotopes : '2', '1,2', etc. If None, loads everything. Default None.

  • load_wavenum_min, load_wavenum_max (float (cm-1)) – load only specific wavenumbers.

  • columns (list of str) – list of columns to load. If None, returns all columns in the file.

Other Parameters
  • cache (True, False, 'regen' or 'force') – if True, use existing HDF5 file. If False or 'regen', rebuild it. If 'force', raise an error if cache file cannot be used (useful for debugging). Default True.

  • verbose (bool)

  • chunksize (int) – number of lines to process at a same time. Higher is usually faster but can create Memory problems and keep the user uninformed of the progress.

  • clean_cache_files (bool) – if True clean downloaded cache files after HDF5 are created.

  • return_local_path (bool) – if True, also returns the path of the local database file.

  • engine (‘pytables’, ‘vaex’, ‘default’) – which HDF5 library to use to parse local files. If ‘default’ use the value from ~/radis.json

  • output (‘pandas’, ‘vaex’, ‘jax’) – format of the output DataFrame. If 'jax', returns a dictionary of jax arrays. If 'vaex', output is a vaex.dataframe.DataFrameLocal

    Note

    Vaex DataFrames are memory-mapped. They do not take any space in RAM and are extremelly useful to deal with the largest databases.

  • parallel (bool) – if True, uses joblib.parallel to load database with multiple processes

Returns

  • df (pd.DataFrame) – Line list A HDF5 file is also created in local_databases and referenced in the RADIS config file with name databank_name

  • local_path (str) – path of local database file if return_local_path

Examples

from radis import fetch_geisa
df = fetch_geisa("CO")
print(df.columns)
>>> Index(['wav', 'int', 'airbrd', 'El', 'globu', 'globl', 'locu', 'locl',
    'Tdpgair', 'isoG', 'mol', 'idG', 'id', 'iso', 'A', 'selbrd', 'Pshft',
    'Tdpair', 'ierrA', 'ierrB', 'ierrC', 'ierrF', 'ierrO', 'ierrR', 'ierrN',
    'Tdpgself', 'ierrS', 'Pshfts', 'ierrT', 'Tdppself', 'ierrU'],
    dtype='object')
Compare CO spectrum from the GEISA and HITRAN database

Compare CO spectrum from the GEISA and HITRAN database

Compare CO spectrum from the GEISA and HITRAN database

Notes

if using load_only_wavenum_above/below or isotope, the whole database is anyway downloaded and uncompressed to local_databases fast access .HDF5 files (which will take a long time on first call). Only the expected wavenumber range & isotopes are returned. The .HFD5 parsing uses hdf2df()

fetch_hitemp(molecule, local_databases=None, databank_name='HITEMP-{molecule}', isotope=None, load_wavenum_min=None, load_wavenum_max=None, columns=None, cache=True, verbose=True, chunksize=100000, clean_cache_files=True, return_local_path=False, engine='default', output='pandas', parallel=True)[source]

Stream HITEMP file from HITRAN website. Unzip and build a HDF5 file directly.

Returns a Pandas DataFrame containing all lines.

Parameters
  • molecule ("H2O", "CO2", "N2O", "CO", "CH4", "NO", "NO2", "OH") – HITEMP molecule. See https://hitran.org/hitemp/

  • local_databases (str) – where to create the RADIS HDF5 files. Default "~/.radisdb/hitemp". Can be changed in radis.config["DEFAULT_DOWNLOAD_PATH"] or in ~/radis.json config file

  • databank_name (str) – name of the databank in RADIS Configuration file Default "HITEMP-{molecule}"

  • isotope (str, int or None) – load only certain isotopes : '2', '1,2', etc. If None, loads everything. Default None.

  • load_wavenum_min, load_wavenum_max (float (cm-1)) – load only specific wavenumbers.

  • columns (list of str) – list of columns to load. If None, returns all columns in the file.

Other Parameters
  • cache (True, False, 'regen' or 'force') – if True, use existing HDF5 file. If False or 'regen', rebuild it. If 'force', raise an error if cache file cannot be used (useful for debugging). Default True.

  • verbose (bool)

  • chunksize (int) – number of lines to process at a same time. Higher is usually faster but can create Memory problems and keep the user uninformed of the progress.

  • clean_cache_files (bool) – if True clean downloaded cache files after HDF5 are created.

  • return_local_path (bool) – if True, also returns the path of the local database file.

  • engine (‘pytables’, ‘vaex’, ‘default’) – which HDF5 library to use to parse local files. If ‘default’ use the value from ~/radis.json

  • output (‘pandas’, ‘vaex’, ‘jax’) – format of the output DataFrame. If 'jax', returns a dictionary of jax arrays. If 'vaex', output is a vaex.dataframe.DataFrameLocal

    Note

    Vaex DataFrames are memory-mapped. They do not take any space in RAM and are extremelly useful to deal with the largest databases.

  • parallel (bool) – if True, uses joblib.parallel to load database with multiple processes

Returns

  • df (pd.DataFrame) – Line list A HDF5 file is also created in local_databases and referenced in the RADIS config file with name databank_name

  • local_path (str) – path of local database file if return_local_path

Examples

from radis import fetch_hitemp
df = fetch_hitemp("CO")
print(df.columns)
>>> Index(['id', 'iso', 'wav', 'int', 'A', 'airbrd', 'selbrd', 'El', 'Tdpair',
    'Pshft', 'ierr', 'iref', 'lmix', 'gp', 'gpp', 'Fu', 'branch', 'jl',
    'syml', 'Fl', 'vu', 'vl'],
    dtype='object')
Download the HITEMP database

Download the HITEMP database

Download the HITEMP database
Explore Line Database Parameters

Explore Line Database Parameters

Explore Line Database Parameters
Compare CO xsections from the ExoMol and HITEMP database

Compare CO xsections from the ExoMol and HITEMP database

Compare CO xsections from the ExoMol and HITEMP database
Scale Linestrengths of carbon-monoxide

Scale Linestrengths of carbon-monoxide

Scale Linestrengths of carbon-monoxide

Notes

if using load_only_wavenum_above/below or isotope, the whole database is anyway downloaded and uncompressed to local_databases fast access .HDF5 files (which will take a long time on first call). Only the expected wavenumber range & isotopes are returned. The .HFD5 parsing uses hdf2df()

fetch_hitran(molecule, extra_params=None, local_databases=None, databank_name='HITRAN-{molecule}', isotope=None, load_wavenum_min=None, load_wavenum_max=None, columns=None, cache=True, verbose=True, clean_cache_files=True, return_local_path=False, engine='default', output='pandas', parallel=True, parse_quanta=True)[source]

Download all HITRAN lines from HITRAN website. Unzip and build a HDF5 file directly.

Returns a Pandas DataFrame containing all lines.

Parameters
  • molecule (str) – one specific molecule name, listed in HITRAN molecule metadata. See https://hitran.org/docs/molec-meta/ Example: “H2O”, “CO2”, etc.

  • local_databases (str) – where to create the RADIS HDF5 files. Default "~/.radisdb/hitran". Can be changed in radis.config["DEFAULT_DOWNLOAD_PATH"] or in ~/radis.json config file

  • databank_name (str) – name of the databank in RADIS Configuration file Default "HITRAN-{molecule}"

  • isotope (str) – load only certain isotopes : '2', '1,2', etc. If None, loads everything. Default None.

  • load_wavenum_min, load_wavenum_max (float (cm-1)) – load only specific wavenumbers.

  • columns (list of str) – list of columns to load. If None, returns all columns in the file.

  • extra_params (‘all’ or None) – Downloads all additional columns available in the HAPI database for the molecule including parameters like gamma_co2, n_co2 that are required to calculate spectrum in co2 diluent. For eg:

    from radis.io.hitran import fetch_hitran
    df = fetch_hitran('CO', extra_params='all', cache='regen') # cache='regen' to regenerate new database with additional columns
    
Other Parameters
  • cache (True, False, 'regen' or 'force') – if True, use existing HDF5 file. If False or 'regen', rebuild it. If 'force', raise an error if cache file cannot be used (useful for debugging). Default True.

  • verbose (bool)

  • clean_cache_files (bool) – if True clean downloaded cache files after HDF5 are created.

  • return_local_path (bool) – if True, also returns the path of the local database file.

  • engine (‘pytables’, ‘vaex’, ‘default’) – which HDF5 library to use. If ‘default’ use the value from ~/radis.json

  • output (‘pandas’, ‘vaex’, ‘jax’) – format of the output DataFrame. If 'jax', returns a dictionary of jax arrays. If 'vaex', output is a vaex.dataframe.DataFrameLocal

    Note

    Vaex DataFrames are memory-mapped. They do not take any space in RAM and are extremelly useful to deal with the largest databases.

  • parallel (bool) – if True, uses joblib.parallel to load database with multiple processes

  • parse_quanta (bool) – if True, parse local & global quanta (required to identify lines for non-LTE calculations ; but sometimes lines are not labelled.)

Returns

  • df (pd.DataFrame) – Line list A HDF5 file is also created in local_databases and referenced in the RADIS config file with name databank_name

  • local_path (str) – path of local database file if return_local_path

Examples

from radis.io.hitran import fetch_hitran
df = fetch_hitran("CO")
print(df.columns)
>>> Index(['id', 'iso', 'wav', 'int', 'A', 'airbrd', 'selbrd', 'El', 'Tdpair',
    'Pshft', 'gp', 'gpp', 'branch', 'jl', 'vu', 'vl'],
    dtype='object')
Compare CO spectrum from the GEISA and HITRAN database

Compare CO spectrum from the GEISA and HITRAN database

Compare CO spectrum from the GEISA and HITRAN database

Notes

if using load_only_wavenum_above/below or isotope, the whole database is anyway downloaded and uncompressed to local_databases fast access .HDF5 files (which will take a long time on first call). Only the expected wavenumber range & isotopes are returned. The .HFD5 parsing uses hdf2df()

getMolecule(molecule, isotope=None, electronic_state=None, verbose=True) ElectronicState[source]

Get an ElectronicState object in the RADIS Molecules list, which use the defaults spectroscopic constants.

Parameters
  • molecule (str) – molecule name

  • isotope (int, or None) – isotope number. if None, only one isotope must exist in database. Else, an error is raised

  • electronic_state (str) – if None, only one electronic state must exist in database. Else, an error is raised

  • verbose (boolean) – if True, print which electronic state we got

Returns

ElectronicState

Return type

an ElectronicState object.

Examples

Get rovibrational energies using the default spectroscopic constants:

from radis import getMolecule

# Here we get the energy of the v=6, J=3 level of the 2nd isotope of CO::

CO = getMolecule("CO", 2, "X")
print(CO.Erovib(6, 3))
Calculate Rovibrational Energies

Calculate Rovibrational Energies

Calculate Rovibrational Energies
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_diff(s1: Spectrum, s2: Spectrum, var, wunit='default', Iunit='default', resample=True, diff_window=0)[source]

Get the difference between 2 spectra.

Basically returns w1, I1 - I2 where (w1, I1) and (w2, I2) are the values of s1 and s2 for variable var. (w2, I2) is linearly interpolated if needed.

\[dI = I_1 - I_2\]
Parameters
  • s1, s2 (Spectrum objects) – 2 spectra to compare.

  • var (str) – spectral quantity (ex: 'radiance', 'transmittance'…)

  • wunit ('nm', 'cm-1', 'nm_vac') – waveunit to compare in: wavelength air, wavenumber, wavelength vacuum

  • Iunit (str) – if 'default' use s1 unit for variable var

  • medium (‘air’, ‘vacuum’, default’) – propagating medium to compare in (if in wavelength)

Other Parameters
  • resample (bool) – if not True, wavelength must be equals. Else, resample s2 on s1 if needed.

  • diff_window (int) – If non 0, calculates diff by offsetting s1 by diff_window number of units on either side, and returns the minimum. Compensates for experimental errors on the w axis. Default 0. (look up code for more details…)

Returns

w1, Idiff – difference interpolated on the wavespace range of the first Spectrum

Return type

array

Notes

Uses curve_substract() internally

get_distance(s1: Spectrum, s2: Spectrum, var, wunit='default', Iunit='default', resample=True)[source]

Get a regularized Euclidian distance between two spectra s1 and s2

This regularized Euclidian distance minimizes the effect of a small shift in wavelength between the two spectra

\[D(w_1)[i] = \sqrt{ \sum_j (\hat{I_1}[i] - \hat{I_2}[j] )^2 + (\hat{w_1}[i] - \hat{w_2}[j])^2}\]

Where values are normalized as:

\[\hat{A} = \frac{A}{max(A) - min(A)}\]

If waveranges dont match, s2 is interpolated over s1.

Warning

This is a distance on both the waverange and the intensity axis. It may be used to compensate for a small offset in your experimental spectrum (due to wavelength calibration, for instance) but can lead to wrong fits easily. Plus, it is very cost-intensive! Better use get_residual() for an automatized procedure.

Parameters
  • s1, s2 (Spectrum objects) – Spectrum

  • var (str) – spectral quantity

  • wunit ('nm', 'cm-1', 'nm_vac') – waveunit to compare in: wavelength air, wavenumber, wavelength vacuum

  • Iunit (str) – if 'default' use s1 unit for variable var

  • medium (‘air’, ‘vacuum’, default’) – propagating medium to compare in (if in wavelength)

Notes

Uses curve_distance() internally

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_eq_mole_fraction(initial_mixture, T_K, p_Pa)[source]

Calculates chemical equilibrium mole fraction at temperature T, using the CANTERA equilibrate() function.

The calculation uses the default GRI3.0 mechanism, which was designed to model natural gas combustion, including NO formation and reburn chemistry. See GRI 3.0.

When using, cite the [CANTERA] package.

Parameters
  • initial_mixture (str) –

    Gas composition. Example:

    'N2:0.79, O2:0.21, CO2:363e-6'
    

    Or:

    'CO2:1'
    
  • T_K (float (K)) – temperature (Kelvin) to calculate equilibrium

  • P_Pa (float (Pa)) – temperature (Pascal) to calculate equilibrium

Examples

Calculate equilibrium mixture of CO2 at 2000 K, 1 atm:

get_eq_mole_fraction('CO2:1', 2000, 101325)

>>> {'C': 1.7833953335281855e-19,
    'CO': 0.01495998583472384,
    'CO2': 0.9775311634424326,
    'O': 5.7715610124613225e-05,
    'O2': 0.007451135112719029}

References

[CANTERA]

get_ratio(s1: Spectrum, s2: Spectrum, var, wunit='default', Iunit='default', resample=True)[source]

Get the ratio between two spectra Basically returns w1, I1 / I2 where (w1, I1) and (w2, I2) are the values of s1 and s2 for variable var. (w2, I2) is linearly interpolated if needed.

\[R = I_1 / I_2\]
Parameters
  • s1, s2 (Spectrum objects) – Spectrum

  • var (str) – spectral quantity

  • wunit ('nm', 'cm-1', 'nm_vac') – waveunit to compare in: wavelength air, wavenumber, wavelength vacuum

  • Iunit (str) – if 'default' use s1 unit for variable var

Notes

Uses curve_divide() internally

get_residual(s1: Spectrum, s2: Spectrum, var, norm='L2', ignore_nan=False, diff_window=0, normalize=False, normalize_how='max', wunit='default', Iunit='default') float[source]

Returns L2 norm of s1 and s2

For I1, I2, the values of variable var in s1 and s2, respectively, residual is calculated as:

For L2 norm:

\[res = \frac{\sqrt{\sum_i {(s_1[i]-s_2[i])^2}}}{N}.\]

For L1 norm:

\[res = \frac{\sqrt{\sum_i {|s_1[i]-s_2[i]|}}}{N}.\]
Parameters
  • s1, s2 (Spectrum objects) – if not on the same range, s2 is resampled on s1.

  • var (str) – spectral array

  • norm (‘L2’, ‘L1’) – which norm to use

Other Parameters
  • ignore_nan (boolean) – if True, ignore nan in the difference between s1 and s2 (ex: out of bound) when calculating residual. Default False. Note: get_residual will still fail if there are nan in initial Spectrum.

  • normalize (bool, or tuple) – if True, normalize the two spectra before calculating the residual. If a tuple (ex: (4168, 4180)), normalize on this range only. The unit is that of the first Spectrum by default (use wunit to change). Ex:

    s_exp   # in 'nm'
    s_calc  # in 'cm-1'
    get_residual(s_exp, s_calc, normalize=(4178, 4180))  # interpreted as 'nm'
    
  • normalize_how ('max', 'area', 'mean') – how to normalize. 'max' is the default but may not be suited for very noisy experimental spectra. 'area' will normalize the integral to 1. 'mean' will normalize by the mean amplitude value

  • wunit (str) – used if normalized is a range. If 'default', use first spectrum unit.

  • Iunit (str) – if 'default', use first spectrum unit

Notes

0 values for I1 yield nans except if I2 = I1 = 0

when s1 and s2 dont have the size wavespace range, they are automatically resampled through get_diff on ‘s1’ range

Implementation of L2 norm:

np.sqrt((dI**2).sum())/len(dI)

Implementation of L1 norm:

np.abs(dI).sum()/len(dI)
get_residual_integral()[source]

Returns integral of the difference between two spectra s1 and s2, relatively to the integral of spectrum s1.

Compared to get_residual(), this tends to cancel the effect of the gaussian noise of an experimental spectrum.

res = trapz(I2-I1, w1) / trapz(I1, w1)

Note: when the considered variable is transmittance or transmittance_noslit, the upper integral is used (up to 1) to normalize the integral difference

res = trapz(I2-I1, w1) / trapz(1-I1, w1)
Parameters
  • s1, s2 (Spectrum objects) – Spectrum

  • var (str) – spectral quantity

Other Parameters
  • ignore_nan (boolean) – if True, ignore nan in the difference between s1 and s2 (ex: out of bound) when calculating residual. Default False. Note: get_residual_integral will still fail if there are nan in initial Spectrum.

  • wunit (str) – If 'default', use first spectrum unit.

  • Iunit (str) – if 'default', use first spectrum unit

Notes

For I1, I2, the values of ‘var’ in s1 and s2, respectively, residual is calculated as:

res = trapz(I2-I1, w1) / trapz(I1, w1)

0 values for I1 yield nans except if I2 = I1 = 0

when s1 and s2 dont have the size wavespace range, they are automatically resampled through get_diff on ‘s1’ range

hit2df(fname, cache=True, verbose=True, drop_non_numeric=True, load_wavenum_min=None, load_wavenum_max=None, engine='pytables', parse_quanta=True)[source]

Convert a HITRAN/HITEMP [1]_ file to a Pandas dataframe

Parameters
  • fname (str) – HITRAN-HITEMP file name

  • cache (boolean, or 'regen' or 'force') – if True, a pandas-readable HDF5 file is generated on first access, and later used. This saves on the datatype cast and conversion and improves performances a lot (but changes in the database are not taken into account). If False, no database is used. If 'regen', temp file are reconstructed. Default True.

Other Parameters
  • drop_non_numeric (boolean) – if True, non numeric columns are dropped. This improves performances, but make sure all the columns you need are converted to numeric formats before hand. Default True. Note that if a cache file is loaded it will be left untouched.

  • load_wavenum_min, load_wavenum_max (float) – if not 'None', only load the cached file if it contains data for wavenumbers above/below the specified value. See :py:func`~radis.io.cache_files.load_h5_cache_file`. Default 'None'.

  • engine (‘pytables’, ‘vaex’) – format for Hdf5 cache file. Default pytables

  • parse_quanta (bool) – if True, parse local & global quanta (required to identify lines for non-LTE calculations ; but sometimes lines are not labelled.)

Returns

df – dataframe containing all lines and parameters

Return type

pandas Dataframe

References

1

HITRAN 1996, Rothman et al., 1998

Notes

Performances: see CDSD-HITEMP parser

See also

cdsd2df()

load_spec(file, binary=True) Spectrum[source]

Loads a .spec file into a Spectrum object. Adds file in the Spectrum file attribute.

Parameters
  • file (str) – .spec file to load

  • binary (boolean) – set to True if the file is encoded as binary. Default True. Will autodetect if it fails, but that may take longer.

Returns

Spectrum

Return type

a Spectrum object

Examples

Load an experimental spectrum

Load an experimental spectrum

Load an experimental spectrum
Remove a baseline

Remove a baseline

Remove a baseline
1 temperature fit

1 temperature fit

1 temperature fit
Fit an equilibrium spectrum with Tgas as fit parameter using new fitting modules

Fit an equilibrium spectrum with Tgas as fit parameter using new fitting modules

Fit an equilibrium spectrum with Tgas as fit parameter using new fitting modules
Fit a non-LTE spectrum with multiple fit parameters

Fit a non-LTE spectrum with multiple fit parameters

Fit a non-LTE spectrum with multiple fit parameters

See also

SpecDatabase, store()

planck(lmbda, T, eps=1, unit='mW/cm2/sr/nm')[source]

Planck function for blackbody radiation.

\[\epsilon \frac{2h c^2}{{\lambda}^5} \frac{1}{\operatorname{exp}\left(\frac{h c}{\lambda k T}\right)-1}\]
Parameters
  • λ (np.array (nm)) – wavelength

  • T (float (K)) – equilibrium temperature

  • eps (grey-body emissivity) – default 1

  • unit (output unit) – default ‘mW/sr/cm2/nm’

Returns

np.array – equilibrium radiance

Return type

(mW.sr-1.cm-2/nm)

See also

sPlanck(), planck_wn()

planck_wn(wavenum, T, eps=1, unit='mW/cm2/sr/cm-1')[source]

Planck function for blackbody radiation, wavenumber version.

\[\epsilon 2h c^2 {\nu}^3 \frac{1}{\operatorname{exp}\left(\frac{h c \nu}{k T}\right)-1}\]
Parameters
  • wavenum (np.array (cm-1)) – wavenumber

  • T (float (K)) – equilibrium temperature

  • eps (grey-body emissivity) – default 1

  • unit (str) – output unit. Default ‘mW/sr/cm2/cm-1’

Returns

np.array – equilibrium radiance

Return type

default (mW/sr/cm2/cm-1)

See also

sPlanck(), planck()

plot_diff(s1: Spectrum, s2: Spectrum, var=None, wunit='default', Iunit='default', resample=True, method='diff', diff_window=0, show_points=False, label1=None, label2=None, figsize=None, title=None, nfig=None, normalize=False, yscale='linear', verbose=True, save=False, show=True, show_residual=False, lw_multiplier=1, diff_scale_multiplier=1, discard_centile=0, plot_medium='vacuum_only', legendargs={'loc': 'best'}, show_ruler=False)[source]

Plot two spectra, and the difference between them. method= allows you to plot the absolute difference, ratio, or both.

If waveranges dont match, s2 is interpolated over s1.

Parameters
  • s1, s2 (Spectrum objects)

  • var (str, or None) – spectral quantity to plot (ex: 'abscoeff'). If None, plot the first one in the Spectrum from 'radiance', 'radiance_noslit', 'transmittance', etc.

  • wunit ('default', 'nm', 'cm-1', 'nm_vac') – wavespace unit: wavelength air, wavenumber, wavelength vacuum. If 'default', use first spectrum wunit

  • Iunit (str) – if 'default', use first spectrum unit

  • method ('distance', 'diff', 'ratio', or list of them.) – If 'diff', plot difference of the two spectra. If 'distance', plot Euclidian distance (note that units are meaningless then) If 'ratio', plot ratio of two spectra Default 'diff'.

    Warning

    with 'distance', calculation scales as ~N^2 with N the number of points in a spectrum (against ~N with 'diff'). This can quickly override all memory.

    Can also be a list:

    method=['diff', 'ratio']
    
  • normalize (bool) – Normalize the spectra to be ploted

Other Parameters

plot yscale

yscale: ‘linear’, ‘log diff_window: int

If non 0, calculates diff by offsetting s1 by diff_window number of units on either side, and returns the minimum. Kinda compensates for experimental errors on the w axis. Default 0. (look up code to understand…)

show_points: boolean

if True, make all points appear with ‘o’

label1, label2: str

curve names

figsize

figure size

nfig: int, str

figure number of name

title: str

title

verbose: boolean

if True, plot stuff such as rescale ratio in normalize mode. Default True

save: str

Default is False. By default won’t save anything, type the path of the destination if you want to save it (format in the name).

show: Bool

Default is True. Will show the plots : bad if there are more than 20.

show_residual: bool

if True, calculates and shows on the graph the residual in L2 norm. See get_residual(). diff_window is used in the residual calculation too. normalize has no effect.

diff_scale_multiplier: float

dilate the diff plot scale. Default 1

discard_centile: int

if not 0, discard the firsts and lasts centile when setting the limits of the diff window. Example:

discard_centile=1     #  --> discards the smallest 1% and largest 1%
discard_centile=10    #  --> discards the smallest 10% and largest 10%

Useful to remove spikes in a ratio, for instance. Note that this does not change the values of the residual. It’s just a plot feature. Default 0

plot_medium: bool, 'vacuum_only'

if True and wunit are wavelengths, plot the propagation medium in the xaxis label ([air] or [vacuum]). If 'vacuum_only', plot only if wunit=='nm_vac'. Default 'vacuum_only' (prevents from inadvertently plotting spectra with different propagation medium on the same graph).

legendargs: dict

format arguments forwarded to the legend

show_ruler: bool

if True, add a ruler tool to the Matplotlib toolbar.

Warning

still experimental in 0.9.30 ! Try it, feedback welcome !

Returns

  • fig (figure) – fig

  • [ax0, ax1] (axes) – spectra and difference axis

Examples

Simple use:

from radis import plot_diff
plot_diff(s10, s50)                # s10, s50 are two spectra

Advanced use, plotting the total power in the label, and getting the figure and axes handle to edit them afterwards:

Punit = 'mW/cm2/sr'
fig, axes = plot_diff(s10, s50, 'radiance_noslit', figsize=(18,6),
      label1='brd 10 cm-1, P={0:.2f} {1}'.format(s10.get_power(unit=Punit),Punit),
      label2='brd 50 cm-1, P={0:.2f} {1}'.format(s50.get_power(unit=Punit),Punit)
      )
# modify fig, axes..

See an example in Compare two Spectra, which produces the output below:

https://radis.readthedocs.io/en/latest/_images/cdsd4000_vs_hitemp_3409K.svg

If you wish to plot in a logscale, it can be done in the following way:

fig, [ax0, ax1] = plot_diff(s0, s1, normalize=False, verbose=False)
ylim0 = ax0.get_ybound()
ax0.set_yscale("log")
ax0.set_ybound(ylim0)
Compare CO spectrum from the GEISA and HITRAN database

Compare CO spectrum from the GEISA and HITRAN database

Compare CO spectrum from the GEISA and HITRAN database
Calculate a spectrum from HITEMP

Calculate a spectrum from HITEMP

Calculate a spectrum from HITEMP
Compare CO xsections from the ExoMol and HITEMP database

Compare CO xsections from the ExoMol and HITEMP database

Compare CO xsections from the ExoMol and HITEMP database
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

Slit Function
plot_spec(file, what='radiance', title=True, **kwargs)[source]

Plot a .spec file. Uses the plot() method internally.

Parameters

file (str, or Spectrum object) – .spec file to load, or Spectrum object directly

Other Parameters

kwargs (dict) – arguments forwarded to plot()

Returns

fig – where the Spectrum has been plotted

Return type

matplotlib figure

See also

plot()

sPlanck(wavenum_min=None, wavenum_max=None, wavelength_min=None, wavelength_max=None, T=None, eps=1, wstep=0.01, medium='air', **kwargs)[source]

Return a RADIS Spectrum object with blackbody radiation.

It’s easier to plug in a SerialSlabs() line-of-sight than the Planck radiance calculated by planck(). And you don’t need to worry about units as they are handled internally.

See Spectrum documentation for more information

Parameters
  • wavenum_min / wavenum_max (():math:cm^{-1})) – minimum / maximum wavenumber to be processed in \(cm^{-1}\).

  • wavelength_min / wavelength_max ((\(nm\))) – minimum / maximum wavelength to be processed in \(nm\).

  • T (float (K)) – blackbody temperature

  • eps (float [0-1]) – blackbody emissivity. Default 1

Other Parameters
  • wstep (float (cm-1 or nm)) – wavespace step for calculation

  • **kwargs (other keyword inputs) – all are forwarded to spectrum conditions. For instance you can add a ‘path_length=1’ after all the other arguments

Examples

Generate Earth blackbody:

s = sPlanck(wavelength_min=3000, wavelength_max=50000,
            T=288, eps=1)
s.plot()

Examples using sPlanck :

Blackbody radiation

Blackbody radiation

Blackbody radiation

References

In wavelength:

\[\epsilon \frac{2h c^2}{{\lambda}^5} \frac{1}{\operatorname{exp}\left(\frac{h c}{\lambda k T}\right)-1}\]

In wavenumber:

\[\epsilon 2h c^2 {\nu}^3 \frac{1}{\operatorname{exp}\left(\frac{h c \nu}{k T}\right)-1}\]

See also

planck(), planck_wn()

save(s: Spectrum, path, discard=[], compress=True, add_info=None, add_date=None, if_exists_then='increment', verbose=True, warnings=True)[source]

Save a Spectrum object in JSON format. Object can be recovered with load_spec(). If many Spectrum are saved in a same folder you can view their properties with the SpecDatabase structure.

Parameters
  • s (Spectrum) – to save

  • path (str) – filename to save. No extension needed. If filename already exists then a digit is added. If filename is a directory then a new file is created within this directory.

  • discard (list of str) – parameters to discard. To save some memory.

  • compress (boolean) – if False, save under text format, readable with any editor. if True, saves under binary format. Faster and takes less space. If 2, removes all quantities that can be regenerated with s.update(), e.g, transmittance if abscoeff and path length are given, radiance if emisscoeff and abscoeff are given in non-optically thin case, etc. Default False

  • add_info (list, or None/False) – append these parameters and their values if they are in conditions. e.g:

    add_info = ['Tvib', 'Trot']
    
  • add_date (str, or None/False) – adds date in strftime format to the beginning of the filename. e.g:

    add_date = '%Y%m%d'
    
  • if_exists_then ('increment', 'replace', 'error', 'ignore') – what to do if file already exists. If 'increment' an incremental digit is added. If 'replace' file is replaced (!). If 'ignore' the Spectrum is not added to the database and no file is created. If 'error' (or anything else) an error is raised. Default 'increment'.

Returns

fout – filename used (may be different from given path as new info or incremental identifiers are added)

Return type

str

transmittance_spectrum(w, T, wunit='nm', Tunit='', conditions=None, cond_units=None, name=None) Spectrum[source]

Convert (w, I) into a Spectrum object that has unit conversion, plotting and slit convolution capabilities.

Parameters
  • w (np.array) – wavelength, or wavenumber

  • T (np.array) – transmittance (no slit)

  • wunit ('nm', 'cm-1', 'nm_vac') – wavespace unit: wavelength in air ('nm'), wavenumber ('cm-1'), or wavelength in vacuum ('nm_vac'). Default 'nm'.

  • Iunit (str) – intensity unit. Default "" (adimensionned)

Other Parameters
  • conditions (dict) – (optional) calculation conditions to be stored with Spectrum

  • cond_units (dict) – (optional) calculation conditions units

  • name (str) – (optional) give a name

Examples

# w, T are numpy arrays for wavelength and transmittance
from radis import transmittance_spectrum
s2 = transmittance_spectrum(w, T, wunit='nm')                       # creates 'transmittance_noslit'