示例#1
0
def _test(verbose=True, plot=False, *args, **kwargs):
    """ Generate scalable LevelList at 1500K. Rescale at 2000K and compare with
    spectrum directly calculated at 2000K 
    """

    from radis.lbl import SpectrumFactory

    iso = 1
    sf = SpectrumFactory(
        wavelength_min=4170,
        wavelength_max=4200,
        mole_fraction=1,
        path_length=0.05,
        cutoff=1e-25,
        #                     isotope=[1,2],
        isotope=iso,
        db_use_cached=True,
        wstep=0.01,
        broadening_max_width=10,
        medium="air",
        verbose=verbose,
    )

    sf.load_databank("CDSD")

    parfunc = sf.parsum_calc["CO2"][iso]["X"]

    # %% Fill levels for all bands

    Tref = 1500
    s_bands = sf.non_eq_bands(Tvib=Tref, Trot=Tref)
    lvlist = LevelsList(parfunc, s_bands, sf.params.levelsfmt)

    # %% Test
    Tvib = 2000
    s_resc = lvlist.non_eq_spectrum(Tvib=Tvib, Trot=Tref)
    s0 = sf.non_eq_spectrum(Tvib, Tref)

    return s0.compare_with(s_resc, spectra_only=True, plot=plot)
示例#2
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)
示例#3
0
def test_plot_all_CO2_bandheads(verbose=True, plot=False, *args, **kwargs):
    """In this test we use the :meth:`~radis.lbl.bands.BandFactory.non_eq_bands`
    method to calculate separately all vibrational bands of CO2, and compare
    them with the final Spectrum.

    """

    # Note: only with iso1 at the moment

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

    Tgas = 1000

    sf = SpectrumFactory(
        wavelength_min=4160,
        wavelength_max=4220,
        mole_fraction=1,
        path_length=0.3,
        cutoff=1e-23,
        molecule="CO2",
        isotope=1,
        optimization=None,
        verbose=verbose,
    )
    sf.warnings["MissingSelfBroadeningWarning"] = "ignore"
    sf.warnings["NegativeEnergiesWarning"] = "ignore"
    sf.warnings["HighTemperatureWarning"] = "ignore"
    sf.fetch_databank("hitran")

    s_tot = sf.non_eq_spectrum(Tvib=Tgas, Trot=Tgas)
    s_bands = sf.non_eq_bands(Tvib=Tgas, Trot=Tgas)

    if verbose:
        printm("{0} bands in spectrum".format(len(s_bands)))

    assert len(s_bands) == 6

    # Ensure that recombining gives the same
    s_merged = MergeSlabs(*list(s_bands.values()))
    assert s_tot.compare_with(s_merged, "radiance_noslit", plot=False)

    if verbose:
        printm("Recombining bands give the same Spectrum")

    # %%
    if plot:
        s_tot.apply_slit(1, "nm")
        s_tot.name = "Full spectrum"
        s_tot.plot(wunit="nm", lw=3)
        for band, s in s_bands.items():
            s.plot(wunit="nm", nfig="same")
        plt.legend(loc="upper left")
        plt.ylim(ymax=0.25)

    # %% Compare with equilibrium bands now
    s_bands_eq = sf.eq_bands(Tgas)
    s_merged_eq = MergeSlabs(*list(s_bands_eq.values()))

    assert get_residual(s_tot, s_merged_eq, "radiance_noslit") < 1.5e-5

    return True
示例#4
0
def test_plot_all_CO2_bandheads(verbose=True, plot=False, *args, **kwargs):
    ''' In this test we use the :meth:`~radis.lbl.bands.BandFactory.non_eq_bands`
    method to calculate separately all vibrational bands of CO2, and compare
    them with the final Spectrum. 

    '''

    # Note: only with iso1 at the moment

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

    verbose = True
    Tgas = 1000

    sf = SpectrumFactory(wavelength_min=4160,
                         wavelength_max=4220,
                         mole_fraction=1,
                         path_length=0.3,
                         cutoff=1e-23,
                         molecule='CO2',
                         isotope=1,
                         db_use_cached=True,
                         lvl_use_cached=True,
                         verbose=verbose)
    sf.warnings['MissingSelfBroadeningWarning'] = 'ignore'
    sf.warnings['NegativeEnergiesWarning'] = 'ignore'
    sf.warnings['HighTemperatureWarning'] = 'ignore'
    sf.fetch_databank()

    s_tot = sf.non_eq_spectrum(Tvib=Tgas, Trot=Tgas)
    s_bands = sf.non_eq_bands(Tvib=Tgas, Trot=Tgas)

    if verbose:
        printm('{0} bands in spectrum'.format(len(s_bands)))

    assert len(s_bands) == 6

    # Ensure that recombining gives the same
    s_merged = MergeSlabs(*list(s_bands.values()))
    assert s_tot.compare_with(s_merged, 'radiance_noslit', plot=False)

    if verbose:
        printm('Recombining bands give the same Spectrum')

    # %%
    if plot:
        s_tot.apply_slit(1, 'nm')
        s_tot.name = 'Full spectrum'
        s_tot.plot(wunit='nm', lw=3)
        for band, s in s_bands.items():
            s.plot(wunit='nm', nfig='same')
        plt.legend(loc='upper left')
        plt.ylim(ymax=0.25)

    # %% Compare with equilibrium bands now
    s_bands_eq = sf.eq_bands(Tgas)
    s_merged_eq = MergeSlabs(*list(s_bands_eq.values()))

    assert get_residual(s_tot, s_merged_eq, 'radiance_noslit') < 1e-5

    return True
示例#5
0
def test_all_calc_methods(
    verbose=True, plot=False, warnings=True, rtol=1e-3, *args, **kwargs
):
    """ Test same spectrum for 3 different calculation variants (equilibrium, 
    non-equilibrium, per band and recombine 
    """

    if plot:  # Make sure matplotlib is interactive so that test are not stuck in pytest
        import matplotlib.pyplot as plt

        plt.ion()

    try:

        Tgas = 1500

        iso = 1
        sf = SpectrumFactory(
            wavelength_min=4170,
            wavelength_max=4175,
            mole_fraction=1,
            path_length=0.025,
            cutoff=1e-25,
            molecule="CO2",
            isotope=iso,
            db_use_cached=True,
            lvl_use_cached=True,
            verbose=verbose,
        )
        sf.warnings["MissingSelfBroadeningWarning"] = "ignore"
        sf.warnings["NegativeEnergiesWarning"] = "ignore"
        sf.warnings["HighTemperatureWarning"] = "ignore"
        #        sf.fetch_databank()   # uses HITRAN: not really valid at this temperature, but runs on all machines without install
        sf.load_databank("CDSD-HITEMP-PC")

        s_bands = sf.non_eq_bands(Tvib=Tgas, Trot=Tgas)
        lvl = LevelsList(sf.parsum_calc["CO2"][iso]["X"], s_bands, sf.params.levelsfmt)
        s_bd = lvl.non_eq_spectrum(Tvib=Tgas, Trot=Tgas)

        s_nq = sf.non_eq_spectrum(Tvib=Tgas, Trot=Tgas)
        s_eq = sf.eq_spectrum(Tgas=Tgas)

        #
        if plot:
            fig = plt.figure(fig_prefix + "Compare all calc methods")
            s_bd.plot(nfig=fig.number, color="b", lw=5, label="from bands code")
            s_nq.plot(nfig=fig.number, lw=3, label="non eq code")
            s_eq.plot(nfig=fig.number, lw=2, color="r", label="equilibrum code")
            plt.legend()

        assert np.isclose(s_bd.get_power(), s_nq.get_power(), rtol=rtol)
        assert np.isclose(s_bd.get_power(), s_eq.get_power(), rtol=rtol)

        if verbose:
            printm(
                "Eq == non-eq:\t",
                np.isclose(s_eq.get_power(), s_nq.get_power(), rtol=rtol),
            )
            printm(
                "Bands == Non-eq:\t",
                np.isclose(s_bd.get_power(), s_nq.get_power(), rtol=rtol),
            )

        if verbose:
            printm("Test all methods comparison: OK")

        return True

    except DatabankNotFound as err:
        assert IgnoreMissingDatabase(err, __file__, warnings)
示例#6
0
def test_all_calc_methods_CO2pcN(verbose=True,
                                 plot=False,
                                 warnings=True,
                                 rtol=1e-3,
                                 *args,
                                 **kwargs):
    """Test same spectrum for 3 different calculation variants (equilibrium,
    non-equilibrium, per band and recombine

    Uses CO2 Levels database where the energy partitioning is done as follow:

        2 nonequilibrium modes
        Evib is the minimum of a "p,c,N" group
        Erot = E - Evib

    This corresponds to the levelsfmt = 'cdsd-pcN' in
    :data:`~radis.lbl.loader.KNOWN_LVLFORMAT`
    """

    from radis.misc.config import getDatabankEntries
    from radis.test.utils import (
        define_Evib_as_min_of_polyad,
        discard_lines_with_na_levels,
        setup_test_line_databases,
    )

    if plot:  # Make sure matplotlib is interactive so that test are not stuck in pytest
        import matplotlib.pyplot as plt

        plt.ion()
    #%%
    Tgas = 500

    iso = 1
    sf = SpectrumFactory(
        wavenum_min=2284,
        wavenum_max=2285,
        broadening_max_width=5,  # TODO @EP: crashes with 0.3?
        mole_fraction=1,
        path_length=0.025,
        cutoff=1e-25,
        molecule="CO2",
        isotope=iso,
        db_use_cached=True,
        lvl_use_cached=True,
        verbose=verbose,
    )
    sf.warnings["MissingSelfBroadeningWarning"] = "ignore"
    sf.warnings["NegativeEnergiesWarning"] = "ignore"
    sf.warnings["HighTemperatureWarning"] = "ignore"

    # Preparation:

    setup_test_line_databases()

    # Generate a Levels database with p,c,N energy partitioning
    # ... copy "HITEMP-CO2-HAMIL-TEST" info
    database_kwargs = getDatabankEntries("HITEMP-CO2-HAMIL-TEST")
    # ... adapt it to 'cdsd-pcN' mode
    del database_kwargs["info"]
    database_kwargs["levelsfmt"] = "cdsd-pcN"
    # ... load the new database
    sf.load_databank(**database_kwargs)

    # Now, define Evib:
    Q_calc = sf.parsum_calc["CO2"][1]["X"]
    Q_calc.df = define_Evib_as_min_of_polyad(Q_calc.df, keys=["p", "c", "N"])

    # With this Evib definition, clean the Lines database from where Evib is not defined
    # (because Levels does not exist in the reduced, test Level Database)
    discard_lines_with_na_levels(sf)

    # %%---------------------
    # Ready, let's start the tests:

    s_bands = sf.non_eq_bands(Tvib=Tgas, Trot=Tgas)
    lvl = LevelsList(sf.parsum_calc["CO2"][iso]["X"], s_bands,
                     sf.params.levelsfmt)
    s_bd = lvl.non_eq_spectrum(Tvib=Tgas, Trot=Tgas)

    s_nq = sf.non_eq_spectrum(Tvib=Tgas, Trot=Tgas)
    s_eq = sf.eq_spectrum(Tgas=Tgas)

    #
    if plot:
        fig = plt.figure(fig_prefix + "Compare all calc methods")
        s_bd.plot(nfig=fig.number, color="b", lw=5, label="from bands code")
        s_nq.plot(nfig=fig.number, lw=3, label="non eq code")
        s_eq.plot(nfig=fig.number, lw=2, color="r", label="equilibrum code")
        plt.legend()

    assert np.isclose(s_bd.get_integral("abscoeff"),
                      s_nq.get_integral("abscoeff"),
                      rtol=rtol)
    assert np.isclose(s_bd.get_integral("abscoeff"),
                      s_eq.get_integral("abscoeff"),
                      rtol=rtol)
    assert np.isclose(s_nq.get_integral("abscoeff"),
                      s_eq.get_integral("abscoeff"),
                      rtol=rtol)

    # TODO @EP: assertion fail in emission. This is due to the slight shift
    # in intensity also observed in the Planck test (test_base.py::test_optically_thick_limit_1iso()).
    #    assert np.isclose(s_bd.get_power(), s_nq.get_power(), rtol=rtol)
    #    assert np.isclose(s_bd.get_power(), s_eq.get_power(), rtol=rtol)
    #    assert np.isclose(s_nq.get_power(), s_eq.get_power(), rtol=rtol)

    return True