Exemplo n.º 1
0
def get_baseline(s, var="radiance", Iunit=None):
    """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 :py:data:`~radis.spectrum.utils.SPECTRAL_QUANTITIES`

    Returns    
    -------
    baseline: Spectrum
        Spectrum object where intenisity is the baseline of s is computed by peakutils
        
    See Also
    --------
    
    :py:func:`~radis.spectrum.operations.sub_baseline`
    """
    import peakutils

    w1, I1 = s.get(var=var, Iunit=Iunit)
    baseline = peakutils.baseline(I1, deg=1, max_it=500)
    baselineSpectrum = Spectrum.from_array(
        w1, baseline, var, unit=Iunit, name=s.get_name() + "_baseline"
    )
    return baselineSpectrum
Exemplo n.º 2
0
def test_rescaling_function(verbose=True, *args, **kwargs):
    """ Test rescaling functions """

    from radis.test.utils import getTestFile

    s = Spectrum.from_txt(
        getTestFile("calc_N2C_spectrum_Trot1200_Tvib3000.txt"),
        quantity="radiance_noslit",
        waveunit="nm",
        unit="mW/cm2/sr/µm",  # Specair units: mW/cm2/sr/µm
        conditions={
            "Tvib": 3000,
            "Trot": 1200,
            "path_length": 1,  # arbitrary
            "medium": "air",
        },
        populations={"molecules": {
            "N2C": 1e13
        }},  # arbitrary
        # (just an example)
    )
    s.update(optically_thin=True)
    s.rescale_path_length(10)

    assert np.isclose(
        s.get_radiance_noslit(Iunit="mW/cm2/sr/nm")[0], 352.57305783248)
Exemplo n.º 3
0
def test_rescaling_function(verbose=True, *args, **kwargs):
    ''' Test rescaling functions '''

    from radis.test.utils import getTestFile

    s = Spectrum.from_txt(
        getTestFile('calc_N2C_spectrum_Trot1200_Tvib3000.txt'),
        quantity='radiance_noslit',
        waveunit='nm',
        unit='mW/cm2/sr/µm',  # Specair units: mW/cm2/sr/µm
        conditions={
            'Tvib': 3000,
            'Trot': 1200,
            'path_length': 1,  # arbitrary
            'medium': 'air',
        },
        populations={'molecules': {
            'N2C': 1e13
        }},  # arbitrary
        # (just an example)
    )
    s.update(optically_thin=True)
    s.rescale_path_length(10)

    assert np.isclose(
        s.get_radiance_noslit(Iunit='mW/cm2/sr/nm')[0], 352.57305783248)
Exemplo n.º 4
0
def get_baseline(s, var='radiance', wunit='nm', medium='air', Iunit=None):
    '''Calculate and returns a baseline 

    Parameters    
    ----------
    s: Spectrum
        Spectrum which needs a baseline

    Returns    
    -------
    baseline: Spectrum
        Spectrum object where intenisity is the baseline of s is computed by peakutils
        
    See Also
    --------
    
    :py:func:`~radis.spectrum.operations.sub_baseline`
    '''
    import peakutils
    w1, I1 = s.get(var=var, Iunit=Iunit, wunit=wunit, medium=medium)
    baseline = peakutils.baseline(I1, deg=1, max_it=500)
    baselineSpectrum = Spectrum.from_array(w1,
                                           baseline,
                                           var,
                                           waveunit=wunit,
                                           unit=Iunit,
                                           conditions={'medium': medium},
                                           name=s.get_name() + '_baseline')
    return baselineSpectrum
Exemplo n.º 5
0
def test_klarenaar_validation_case(verbose=True,
                                   plot=False,
                                   warnings=True,
                                   *args,
                                   **kwargs):
    """ Reproduce the Klarenaar 2018 validation case, as given in the 
    [RADIS-2018]_ article. 
    
    References
    ----------

    Klarenaar et al, "Time evolution of vibrational temperatures in a CO 2 glow 
    discharge measured with infrared absorption spectroscopy", doi 10.1088/1361-6595/aa902e,
    and the references there in.
    
    """

    setup_test_line_databases()

    # %% Data from Dang, adapted by Klarenaar
    s_exp = Spectrum.from_txt(
        getValidationCase(
            join(
                "test_CO2_3Tvib_vs_klarenaar_data",
                "klarenaar_2017_digitized_data.csv",
            )),
        "transmittance_noslit",
        waveunit="cm-1",
        unit="I/I0",
        delimiter=",",
        name="Klarenaar 2017",
    )

    # %% Calculate Klarenaar test case conditions

    sf = SpectrumFactory(
        2284.2,
        2284.6,
        wstep=0.001,  # cm-1
        pressure=20 * 1e-3,  # bar
        db_use_cached=True,
        cutoff=1e-25,
        molecule="CO2",
        isotope="1,2",
        path_length=10,  # cm-1
        # warning! 10% in mass fraction -> less in mole fraction
        mole_fraction=0.1 * 28.97 / 44.07,
        broadening_max_width=1,  # cm-1
        medium="vacuum",
        export_populations="vib",
    )
    sf.warnings["MissingSelfBroadeningWarning"] = "ignore"
    #        sf.load_databank('HITEMP-CO2-DUNHAM')
    sf.load_databank("HITEMP-CO2-TEST")

    # Calculate with Klarenaar fitted values
    T12 = 517
    T3 = 2641
    Trot = 491

    s = sf.non_eq_spectrum((T12, T12, T3),
                           Trot,
                           Ttrans=Trot,
                           vib_distribution="treanor",
                           name="RADIS")

    if plot:
        plot_diff(s, s_exp, "transmittance_noslit")
    #        plt.savefig('test_CO2_3Tvib_vs_klarenaar.png')

    assert get_residual(s, s_exp, "transmittance_noslit",
                        ignore_nan=True) < 0.003

    return True
Exemplo n.º 6
0
def concat_spectra(s1, s2, var=None):
    """ Concatenate two spectra ``s1`` and ``s2`` side by side.
    
    Note: their spectral range should not overlap 
    
    Returns    
    -------
    
    s: Spectrum
        Spectrum object with the same units and waveunits as ``s1``
        
    Parameters    
    ----------
    
    s1, s2: Spectrum objects
        Spectrum you want to concatenate
    var: str
        quantity to manipulate: 'radiance', 'transmittance', ... If ``None``, 
        get the unique spectral quantity of ``s1``, or the unique spectral
        quantity of ``s2``, or raises an error if there is any ambiguity
        
    Notes
    -----
    
    .. warning::
        
        the output Spectrum has the sum of the spectral ranges of s1 and s2. 
        It won't be evenly spaced. This means that you cannot apply a slit without
        side effects. Typically, you want to use this function for convolved 
        quantities only, such as experimental spectra. Else, use
        :func:`~radis.los.slabs.MergeSlabs` with the options 
        ``resample='full', out='transparent'``
        
    See Also
    --------
    
    :func:`~radis.spectrum.operations.add_spectra`, 
    :func:`~radis.los.slabs.MergeSlabs`
    
    """

    # Get variable
    if var is None:
        try:
            var = _get_unique_var(
                s2, var, inplace=False
            )  # unique variable of 2nd spectrum
        except KeyError:
            var = _get_unique_var(
                s1, var, inplace=False
            )  # if doesnt exist, unique variable of 1st spectrum
            # if it fails, let it fail
    # Make sure it is in both Spectra
    if var not in s1.get_vars():
        raise KeyError("Variable {0} not in Spectrum {1}".format(var, s1.get_name()))
    if var not in s2.get_vars():
        raise KeyError("Variable {0} not in Spectrum {1}".format(var, s1.get_name()))

    if var in ["transmittance_noslit", "transmittance"]:
        warn(
            "It does not make much physical sense to sum transmittances. Are "
            + "you sure of what you are doing? See also // (MergeSlabs) and > "
            + "(SerialSlabs)"
        )

    # Use same units
    Iunit1 = s1.units[var]
    wunit1 = s1.get_waveunit()

    # Get the value, on the same wunit)
    w1, I1 = s1.get(var=var, copy=False)  # @dev: faster to just get the stored value.
    # it's copied in hstack() below anyway).
    w2, I2 = s2.get(var=var, Iunit=Iunit1, wunit=wunit1)

    if not (w1.max() < w2.min() or w2.max() > w1.min()):
        raise ValueError(
            "You cannot use concat_spectra for overlapping spectral ranges. "
            + "Got: {0:.2f}-{1:.2f} and {2:.2f}-{3:.2f} {4}. ".format(
                w1.min(), w1.max(), w2.min(), w2.max(), wunit1
            )
            + "Use MergeSlabs instead, with the correct `out=` parameter "
            + "for your case"
        )

    w_tot = hstack((w1, w2))
    I_tot = hstack((I1, I2))

    name = s1.get_name() + "&" + s2.get_name()  # use "&" instead of "+"

    concat = Spectrum.from_array(
        w_tot, I_tot, var, waveunit=wunit1, unit=Iunit1, name=name
    )

    return concat
Exemplo n.º 7
0
def substract_spectra(s1, s2, var=None):
    """Return a new spectrum with ``s2`` substracted from ``s1``. 
    Equivalent to::
        
        s1 - s2
    
    Parameters    
    ----------
    
    s1, s2: Spectrum objects
        Spectrum you want to substract
    var: str
        quantity to manipulate: 'radiance', 'transmittance', ... If ``None``, 
        get the unique spectral quantity of ``s1``, or the unique spectral
        quantity of ``s2``, or raises an error if there is any ambiguity

    Returns    
    -------
    
    s: Spectrum
        Spectrum object with the same units and waveunits as ``s1``
        
    See Also
    --------
    
    :func:`~radis.spectrum.operations.add_spectra`
    
    """

    # Get variable
    if var is None:
        try:
            var = _get_unique_var(
                s2, var, inplace=False
            )  # unique variable of 2nd spectrum
        except KeyError:
            var = _get_unique_var(
                s1, var, inplace=False
            )  # if doesnt exist, unique variable of 1st spectrum
            # if it fails, let it fail
    # Make sure it is in both Spectra
    if var not in s1.get_vars():
        raise KeyError("Variable {0} not in Spectrum {1}".format(var, s1.get_name()))
    if var not in s2.get_vars():
        raise KeyError("Variable {0} not in Spectrum {1}".format(var, s1.get_name()))

    # Use same units
    Iunit1 = s1.units[var]
    wunit1 = s1.get_waveunit()

    # Resample s2 on s1
    s2 = s2.resample(s1, inplace=False)

    # Substract
    w1, I1 = s1.get(var=var, Iunit=Iunit1, wunit=wunit1)
    w2, I2 = s2.get(var=var, Iunit=Iunit1, wunit=wunit1)

    name = s1.get_name() + "-" + s2.get_name()

    sub = Spectrum.from_array(w1, I1 - I2, var, waveunit=wunit1, unit=Iunit1, name=name)
    #    warn("Conditions of the left spectrum were copied in the substraction.", Warning)
    return sub
Exemplo n.º 8
0
def add_spectra(s1, s2, var=None, force=False):
    """Return a new spectrum with ``s2`` added to ``s1``. 
    Equivalent to::
        
        s1 + s2
    
    .. warning::
        we are just algebrically adding the quantities. If you want to merge
        spectra while preserving the radiative transfer equation, see 
        :func:`~radis.los.slabs.MergeSlabs` and :func:`~radis.los.slabs.SerialSlabs`
    
    Parameters    
    ----------
    
    s1, s2: Spectrum objects
        Spectrum you want to substract
    var: str
        quantity to manipulate: 'radiance', 'transmittance', ... If ``None``, 
        get the unique spectral quantity of ``s1``, or the unique spectral
        quantity of ``s2``, or raises an error if there is any ambiguity
        
    Returns    
    -------
    
    s: Spectrum
        Spectrum object with the same units and waveunits as ``s1``
        
    See Also
    --------
    
    :func:`~radis.los.slabs.MergeSlabs`,
    :func:`~radis.spectrum.operations.substract_spectra`
    
    """

    # Get variable
    if var is None:
        try:
            var = _get_unique_var(
                s2, var, inplace=False
            )  # unique variable of 2nd spectrum
        except KeyError:
            var = _get_unique_var(
                s1, var, inplace=False
            )  # if doesnt exist, unique variable of 1st spectrum
            # if it fails, let it fail
    # Make sure it is in both Spectra
    if var not in s1.get_vars():
        raise KeyError("Variable {0} not in Spectrum {1}".format(var, s1.get_name()))
    if var not in s2.get_vars():
        raise KeyError("Variable {0} not in Spectrum {1}".format(var, s1.get_name()))

    if var in ["transmittance_noslit", "transmittance"] and not force:
        raise ValueError(
            "It does not make much physical sense to sum transmittances. Are "
            + "you sure of what you are doing? See also `//` (MergeSlabs), `>` "
            + "(SerialSlabs) and `concat_spectra`. If you're sure, use `force=True`"
        )

    # Get s1 units
    Iunit1 = s1.units[var]
    wunit1 = s1.get_waveunit()

    # Resample s2 on s1
    s2 = s2.resample(s1, inplace=False)

    # Add, change output unit if needed.
    w1, I1 = s1.get(var=var, Iunit=Iunit1, wunit=wunit1)
    w2, I2 = s2.get(var=var, Iunit=Iunit1, wunit=wunit1)

    name = s1.get_name() + "+" + s2.get_name()

    sub = Spectrum.from_array(w1, I1 + I2, var, waveunit=wunit1, unit=Iunit1, name=name)
    #    warn("Conditions of the left spectrum were copied in the substraction.", Warning)
    return sub
Exemplo n.º 9
0
def test_klarenaar_validation_case(verbose=True, plot=False, warnings=True,
                                   *args, **kwargs):
    ''' Reproduce the Klarenaar 2018 validation case, as given in the 
    [RADIS-2018]_ article. 
    
    References
    ----------

    Klarenaar et al, "Time evolution of vibrational temperatures in a CO 2 glow 
    discharge measured with infrared absorption spectroscopy", doi 10.1088/1361-6595/aa902e,
    and the references there in.
    
    '''
    
    setup_test_line_databases()

    try:
        # %% Data from Dang, adapted by Klarenaar
        s_exp = Spectrum.from_txt(getValidationCase(join('test_CO2_3Tvib_vs_klarenaar_data', 
                                                    'klarenaar_2017_digitized_data.csv')),
                                  'transmittance_noslit', waveunit='cm-1', unit='I/I0',
                                  delimiter=',',
                                  name='Klarenaar 2017')

        # %% Calculate Klarenaar test case conditions

        sf = SpectrumFactory(2284.2, 2284.6,
                             wstep=0.001,                # cm-1
                             pressure=20*1e-3,           # bar
                             db_use_cached=True,
                             cutoff=1e-25,
                             molecule='CO2',
                             isotope='1,2',
                             path_length=10,             # cm-1
                             # warning! 10% in mass fraction -> less in mole fraction
                             mole_fraction=0.1*28.97/44.07,
                             broadening_max_width=1,     # cm-1
                             medium='vacuum',
                             export_populations='vib',
                             )
        sf.warnings['MissingSelfBroadeningWarning'] = 'ignore'
#        sf.load_databank('HITEMP-CO2-DUNHAM')
        sf.load_databank('HITEMP-CO2-TEST')

        # Calculate with Klarenaar fitted values
        T12 = 517
        T3 = 2641
        Trot = 491

        s = sf.non_eq_spectrum((T12, T12, T3), Trot, Ttrans=Trot,
                               vib_distribution='treanor',
                               name='RADIS')

        if plot:
            plot_diff(s, s_exp, 'transmittance_noslit')
    #        plt.savefig('test_CO2_3Tvib_vs_klarenaar.png')

        assert get_residual(s, s_exp, 'transmittance_noslit', ignore_nan=True) < 0.003
        
        return True

    except DatabankNotFound as err:
        assert IgnoreMissingDatabase(err, __file__, warnings)
Exemplo n.º 10
0
def substract_spectra(s1, s2, var=None, wunit='nm'):
    '''Return a new spectrum with ``s2`` substracted from ``s1``. 
    Equivalent to::
        
        s1 - s2
    
    Parameters    
    ----------
    
    s1, s2: Spectrum objects
        Spectrum you want to substract
    var: str
        quantity to manipulate: 'radiance', 'transmittance', ... If ``None``, 
        get the unique spectral quantity of ``s1``, or the unique spectral
        quantity of ``s2``, or raises an error if there is any ambiguity
    wunit: str
        'nm'or 'cm-1'
        
    Returns    
    -------
    
    s: Spectrum
        Spectrum object with the same units and waveunits as ``s1``
        
    See Also
    --------
    
    :func:`~radis.spectrum.operations.add_spectra`
    
    '''

    # Get variable
    if var is None:
        try:
            var = _get_unique_var(
                s2, var, inplace=False)  # unique variable of 2nd spectrum
        except KeyError:
            var = _get_unique_var(
                s1, var, inplace=False
            )  # if doesnt exist, unique variable of 1st spectrum
            # if it fails, let it fail
    # Make sure it is in both Spectra
    if var not in s1.get_vars():
        raise KeyError('Variable {0} not in Spectrum {1}'.format(
            var, s1.get_name()))
    if var not in s2.get_vars():
        raise KeyError('Variable {0} not in Spectrum {1}'.format(
            var, s1.get_name()))

    # Use same units
    Iunit = s1.units[var]
    wunit = s1.get_waveunit()
    medium = s1.get_medium()

    # Resample
    if wunit == 'nm':
        s2 = s2.resample(s1.get_wavelength(), 'nm', inplace=False)
    elif wunit == 'cm-1':
        s2 = s2.resample(s1.get_wavenumber(), 'cm-1', inplace=False)
    else:
        raise ValueError('Unexpected wunit: {0}'.format(wunit))

    # Substract
    w1, I1 = s1.get(var=var, Iunit=Iunit, wunit=wunit, medium=medium)
    w2, I2 = s2.get(var=var, Iunit=Iunit, wunit=wunit, medium=medium)

    name = s1.get_name() + '-' + s2.get_name()

    sub = Spectrum.from_array(w1,
                              I1 - I2,
                              var,
                              waveunit=wunit,
                              unit=Iunit,
                              conditions={'medium': medium},
                              name=name)
    #    warn("Conditions of the left spectrum were copied in the substraction.", Warning)
    return sub
Exemplo n.º 11
0
def add_spectra(s1, s2, var=None, wunit='nm', force=False):
    '''Return a new spectrum with ``s2`` added to ``s1``. 
    Equivalent to::
        
        s1 + s2
    
    .. warning::
        we are just algebrically adding the quantities. If you want to merge
        spectra while preserving the radiative transfer equation, see 
        :func:`~radis.los.slabs.MergeSlabs` and :func:`~radis.los.slabs.SerialSlabs`
    
    Parameters    
    ----------
    
    s1, s2: Spectrum objects
        Spectrum you want to substract
    var: str
        quantity to manipulate: 'radiance', 'transmittance', ... If ``None``, 
        get the unique spectral quantity of ``s1``, or the unique spectral
        quantity of ``s2``, or raises an error if there is any ambiguity
    wunit: str
        'nm'or 'cm-1'
        
    Returns    
    -------
    
    s: Spectrum
        Spectrum object with the same units and waveunits as ``s1``
        
    See Also
    --------
    
    :func:`~radis.los.slabs.MergeSlabs`,
    :func:`~radis.spectrum.operations.substract_spectra`
    
    '''

    # Get variable
    if var is None:
        try:
            var = _get_unique_var(
                s2, var, inplace=False)  # unique variable of 2nd spectrum
        except KeyError:
            var = _get_unique_var(
                s1, var, inplace=False
            )  # if doesnt exist, unique variable of 1st spectrum
            # if it fails, let it fail
    # Make sure it is in both Spectra
    if var not in s1.get_vars():
        raise KeyError('Variable {0} not in Spectrum {1}'.format(
            var, s1.get_name()))
    if var not in s2.get_vars():
        raise KeyError('Variable {0} not in Spectrum {1}'.format(
            var, s1.get_name()))

    if var in ['transmittance_noslit', 'transmittance'] and not force:
        raise ValueError('It does not make much physical sense to sum transmittances. Are '+\
                         'you sure of what you are doing? See also `//` (MergeSlabs), `>` '+\
                         "(SerialSlabs) and `concat_spectra`. If you're sure, use `force=True`")

    # Use same units
    Iunit = s1.units[var]
    wunit = s1.get_waveunit()
    medium = s1.get_medium()

    # Resample
    if wunit == 'nm':
        s2 = s2.resample(s1.get_wavelength(), 'nm', inplace=False)
    elif wunit == 'cm-1':
        s2 = s2.resample(s1.get_wavenumber(), 'cm-1', inplace=False)
    else:
        raise ValueError('Unexpected wunit: {0}'.format(wunit))

    # Add
    w1, I1 = s1.get(var=var, Iunit=Iunit, wunit=wunit, medium=medium)
    w2, I2 = s2.get(var=var, Iunit=Iunit, wunit=wunit, medium=medium)

    name = s1.get_name() + '+' + s2.get_name()

    sub = Spectrum.from_array(w1,
                              I1 + I2,
                              var,
                              waveunit=wunit,
                              unit=Iunit,
                              conditions={'medium': medium},
                              name=name)
    #    warn("Conditions of the left spectrum were copied in the substraction.", Warning)
    return sub