Esempio n. 1
0
def cost_function(fit_values, plot=None):
    ''' Return error on Spectrum s vs experimental spectrum '''
    
    s = generate_spectrum(fit_values)
    
    # Delete unecessary variables (for a faster resampling)
    for var in [k for k in s._q.keys() if k not in [fit_variable, 'wavespace']]:
        del s._q[var]
        
    if plot is not None:
        plt.figure(plot).clear()
        plot_diff(s_exp, s, var=fit_variable, nfig=plot, title=print_fit_values(fit_values))
        
    s.resample(w_exp, energy_threshold=2e-2)
    
    return get_residual(s, s_exp, fit_variable, ignore_nan=True, norm='L2')
Esempio n. 2
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
Esempio n. 3
0
def test_direct_overpopulation_vs_recombined_bands(verbose=True,
                                                   plot=False,
                                                   warnings=True,
                                                   rtol=0.05,
                                                   *args,
                                                   **kwargs):
    """ Compare a non-equilibrium spectrum calculated directly with overpopulations, 
    or by recombining pre-calculated vibrational bands. 

    The later allows for almost instantaneous changes of the overpopulation factors, 
    (mostly useful in fitting algorithms), but is only valid for optically thin emission spectra

    Expected output:

    when x_CO2 = 1e-3, radiance in both cases match
    when x_CO2 = 1, they dont

    """

    #    Notes
    #    -----
    #
    #    On the old NeQ package the test used [HITEMP-2010]_
    #
    #    Starting from RADIS 1.0.1, the test is run on [HITRAN-2016]_, which
    #    is not valid for these temperatures but can be more conveniently
    #    downloaded automatically and thus executed everytime with [Travis]_
    #

    # Note: only with iso1 at the moment

    if plot:  # Make sure matplotlib is interactive so that test are not stuck in pytest
        plt.ion()

    try:

        # Generate factory
        iso = 1
        sf = SpectrumFactory(
            wavelength_min=4220,
            wavelength_max=4280,
            mole_fraction=1e-3,
            path_length=10,
            cutoff=1e-25,
            molecule="CO2",
            isotope=iso,
            db_use_cached=True,
            wstep=0.01,
            broadening_max_width=5,
            medium="air",
            verbose=verbose,
        )
        sf.warnings["MissingSelfBroadeningWarning"] = "ignore"
        sf.warnings["NegativeEnergiesWarning"] = "ignore"
        sf.load_databank("CDSD-HITEMP-PCN")
        #        sf.fetch_databank()   # uses HITRAN: not really valid at this temperature, but runs on all machines without install

        # Generate bands to recombine
        parfunc = sf.parsum_calc["CO2"][iso]["X"]
        Tref = 1500
        # , return_lines=False)
        s_bands = sf.non_eq_bands(Tvib=Tref, Trot=Tref)
        lvlist = LevelsList(parfunc, s_bands, sf.params.levelsfmt)

        # Compare ab initio and recombined from bands at M = 1e-3
        s_recombined = lvlist.non_eq_spectrum(Tvib=Tref,
                                              Trot=Tref,
                                              overpopulation={"(4,1,3)": 3})
        sref = sf.non_eq_spectrum(Tvib=Tref,
                                  Trot=Tref,
                                  overpopulation={"(4,1,3)": 1})

        if verbose:
            printm(
                "Testing x_CO2 = 1e-3: ab initio ~ recombined bands (<{0:.1f}%):\t"
                .format(rtol * 100))

        if plot:
            plot_diff(
                sref,
                s_recombined,
                var="radiance_noslit",
                label1="ab initio",
                label2="recombined bands",
                title="x_CO2 = 1e-3",
            )

        assert np.allclose(s_recombined.get_radiance_noslit(),
                           sref.get_radiance_noslit(),
                           rtol=rtol)

        # Rescale and try again for x_CO2 = 1
        s_recombined.rescale_mole_fraction(1)
        sref.rescale_mole_fraction(1)

        if plot:
            plot_diff(
                sref,
                s_recombined,
                var="radiance_noslit",
                label1="ab initio",
                label2="recombined bands",
                title="x_CO2 = 1",
            )

        if verbose:
            printm(
                "Testing x_CO2 = 1: ab initio ~ recombined bands (<{0:.1f}%):\t{1}"
                .format(
                    rtol * 100,
                    np.allclose(
                        s_recombined.get_radiance_noslit(),
                        sref.get_radiance_noslit(),
                        rtol=rtol,
                    ),
                ))

        with pytest.raises(AssertionError):
            assert np.allclose(
                s_recombined.get_radiance_noslit(),
                sref.get_radiance_noslit(),
                rtol=rtol,
            )

        return True

    except DatabankNotFound as err:
        assert IgnoreMissingDatabase(err, __file__, warnings)
Esempio n. 4
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)