Beispiel #1
0
def spectrums(molecule, ids, path):
    print(f"\n***** Plotting Spectrums *****\n")
    environment = {"p": 1, "T": 296, "l": 1000}
    nu1, coef = absorptionCoefficient_Voigt(
        (ids, ),
        molecule,
        OmegaStep=0.01,
        HITRAN_units=False,
        GammaL="gamma_self",
        Environment=environment,
    )
    nu2, absorp = absorptionSpectrum(nu1, coef, Environment=environment)
    nu3, transm = transmittanceSpectrum(nu1, coef, Environment=environment)
    nu4, radian = radianceSpectrum(nu1, coef, Environment=environment)
    plt.figure()
    plt.subplot(2, 2, 1)
    plt.plot(nu1, coef, "r")
    plt.title(f"{molecule} Absorption Coefficient")
    plt.subplot(2, 2, 2)
    plt.plot(nu2, absorp, "g")
    plt.title(f"{molecule} Absorption Spectrum")
    plt.subplot(2, 2, 3)
    plt.plot(nu3, transm, "b")
    plt.title(f"{molecule} Transmittance Spectrum")
    plt.subplot(2, 2, 4)
    plt.plot(nu4, radian, "y")
    plt.title(f"{molecule} Radiance Spectrum")
    plt.tight_layout()
    plt.savefig(f"{path}/spectrums.png")
    plt.clf()
Beispiel #2
0
def hires(molecule, ids, path):
    print(f"\n***** Plotting HiRes *****\n")
    environment = {"p": 1, "T": 296, "l": 1000}
    nu1, coef = absorptionCoefficient_Voigt(
        (ids, ),
        molecule,
        OmegaStep=0.01,
        HITRAN_units=False,
        GammaL="gamma_self",
        Environment=environment,
    )
    nu2, transm = transmittanceSpectrum(nu1, coef, Environment=environment)
    nu3, conv, _, _, _ = convolveSpectrum(
        nu2,
        transm,
        SlitFunction=SLIT_MICHELSON,
        Resolution=1.0,
        AF_wing=20.0,
    )
    plt.figure()
    plt.plot(nu2, transm, "red", nu3, conv, "blue")
    plt.legend(["HI-RES", "Michelson"])
    plt.tight_layout()
    plt.savefig(f"{path}/hires.png")
    plt.clf()
Beispiel #3
0
def absorptions(molecule, ids, path):
    print(f"\n***** Plotting Absorption Coefficients *****\n")
    plt.figure()
    colors = ["r", "g", "b", "y"]
    for i, temperature in enumerate([296]):
        nu, coef = absorptionCoefficient_Voigt(
            (ids, ),
            molecule,
            OmegaStep=0.01,
            HITRAN_units=False,
            GammaL="gamma_self",
            Environment={
                "p": 1,
                "T": temperature
            },
        )
        plt.subplot(2, 2, i + 1)
        plt.plot(nu, coef, colors[i])
        plt.title(f"{molecule} Absorption (p=1atm, T={temperature}K)")
        plt.xlabel("Wavenumber")
        plt.ylabel("Absorption Coefficient")

    plt.tight_layout()
    plt.savefig(f"{path}/absorption_coefficients.png")
    plt.clf()
Beispiel #4
0
def transform_data(molecules, nu_min, nu_max):
    for molecule, spec in molecules.items():
        print(f"\n***** Converting Molecule {molecule} Data to CSV *****\n")
        dataset = pandas.DataFrame(columns=COLUMNS)
        environment = {"T": 296, "p": 1, "l": 1}
        wave_number, absorption_coefficient = absorptionCoefficient_Voigt(
            Components=(spec, ),
            SourceTables=molecule,
            OmegaRange=(nu_min, nu_max),
            OmegaStep=0.1,
            HITRAN_units=False,
            Environment=environment,
        )
        _, absorption_spectrum = absorptionSpectrum(wave_number,
                                                    absorption_coefficient,
                                                    Environment=environment)
        _, transmittance_spectrum = transmittanceSpectrum(
            wave_number, absorption_coefficient, Environment=environment)
        dataset["wave_number"] = wave_number
        dataset["mass"] = molecularMass(spec[0], spec[1])
        dataset["name"] = molecule
        dataset["absorption_coefficient"] = absorption_coefficient
        dataset["absorption_spectrum"] = absorption_spectrum
        dataset["transmittance_spectrum"] = transmittance_spectrum
        dataset.to_csv(f"{CSV}/{molecule}.csv")
Beispiel #5
0
 def calc_hapi():
     nu, coef = absorptionCoefficient_Voigt(
         SourceTables=molecule,
         Environment={
             "T": T,
             "p": pressure_bar / 1.01315,
         },  # K  # atm
         GammaL="gamma_self",
         WavenumberStep=dnu,
         HITRAN_units=False,
     )
     return nu, coef
    def calc_hapi():
        """ Calc spectrum under HAPI """

        clean_after_run = not exists(HAPIdb) and False

        try:
            db_begin(HAPIdb)
            if not molecule in tableList(
            ):  # only if data not downloaded already
                fetch(
                    molecule,
                    mol_id,
                    iso,
                    wmin - broadening_max_width / 2,
                    wmax + broadening_max_width / 2,
                )
                # HAPI doesnt correct for side effects

            # Calculate with HAPI
            nu, coef = absorptionCoefficient_Voigt(
                SourceTables="CO2",
                Environment={
                    "T": T,
                    "p": p / 1.01325,
                },  # K  # atm
                WavenumberStep=dnu,
                HITRAN_units=False,
                GammaL="gamma_self",
            )
            nu, trans = transmittanceSpectrum(
                nu,
                coef,
                Environment={
                    "l": L,
                },
            )  # cm
            s_hapi = Spectrum.from_array(
                nu,
                trans,
                "transmittance_noslit",
                "cm-1",
                "1",
                conditions={"Tgas": T},
                name="HAPI",
            )

        except:
            raise

        finally:
            if clean_after_run:
                shutil.rmtree(HAPIdb)
        return s_hapi
Beispiel #7
0
def test_broadening_vs_hapi(rtol=1e-2,
                            verbose=True,
                            plot=False,
                            *args,
                            **kwargs):
    """
    Test broadening against HAPI and tabulated data

    We're looking at CO(0->1) line 'R1' at 2150.86 cm-1
    """
    from hapi import absorptionCoefficient_Voigt, db_begin, fetch, tableList

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

    setup_test_line_databases()  # add HITRAN-CO-TEST in ~/.radis if not there

    # Conditions
    T = 3000
    p = 0.0001
    wstep = 0.001
    wmin = 2150  # cm-1
    wmax = 2152  # cm-1
    broadening_max_width = 10  # cm-1

    # %% HITRAN calculation
    # -----------

    # Generate HAPI database locally
    hapi_data_path = join(dirname(__file__),
                          __file__.replace(".py", "_HAPIdata"))

    db_begin(hapi_data_path)
    if not "CO" in tableList():  # only if data not downloaded already
        fetch("CO", 5, 1, wmin - broadening_max_width / 2,
              wmax + broadening_max_width / 2)
        # HAPI doesnt correct for side effects

    # Calculate with HAPI
    nu, coef = absorptionCoefficient_Voigt(
        SourceTables="CO",
        Environment={
            "T": T,
            "p": p / 1.01325,
        },  # K  # atm
        WavenumberStep=wstep,
        HITRAN_units=False,
    )

    s_hapi = Spectrum.from_array(nu,
                                 coef,
                                 "abscoeff",
                                 "cm-1",
                                 "cm-1",
                                 conditions={"Tgas": T},
                                 name="HAPI")

    # %% Calculate with RADIS
    # ----------
    sf = SpectrumFactory(
        wavenum_min=wmin,
        wavenum_max=wmax,
        mole_fraction=1,
        path_length=1,  # doesnt change anything
        wstep=wstep,
        pressure=p,
        broadening_max_width=broadening_max_width,
        isotope=[1],
        warnings={
            "MissingSelfBroadeningWarning": "ignore",
            "NegativeEnergiesWarning": "ignore",
            "HighTemperatureWarning": "ignore",
            "GaussianBroadeningWarning": "ignore",
        },
    )  # 0.2)
    sf.load_databank(path=join(hapi_data_path, "CO.data"),
                     format="hitran",
                     parfuncfmt="hapi")
    #    s = pl.non_eq_spectrum(Tvib=T, Trot=T, Ttrans=T)
    s = sf.eq_spectrum(Tgas=T, name="RADIS")

    if plot:  # plot broadening of line of largest linestrength
        sf.plot_broadening(i=sf.df1.S.idxmax())

    # Plot and compare
    res = abs(get_residual_integral(s, s_hapi, "abscoeff"))
    if plot:
        plot_diff(
            s,
            s_hapi,
            var="abscoeff",
            title="{0} bar, {1} K (residual {2:.2g}%)".format(p, T, res * 100),
            show_points=False,
        )
        plt.xlim((wmin, wmax))
    if verbose:
        printm("residual:", res)
    assert res < rtol
#StartTime = time.time()
hapi.db_begin('TestData')
nu_hapi_Doppler, abs_hapi_Doppler = hapi.absorptionCoefficient_Doppler(
    SourceTables=Molecule,
    OmegaGrid=WaveNumber,
    HITRAN_units=True,
    Environment=Env,
    GammaL='gamma_self',
    OmegaWing=OmegaWingValue,
    OmegaWingHW=0.0,
    LineShift=False)  #, OmegaStep=0.01)
nu_hapi_Voigt, abs_hapi_Voigt = hapi.absorptionCoefficient_Voigt(
    SourceTables=Molecule,
    OmegaGrid=WaveNumber,
    HITRAN_units=True,
    Environment=Env,
    GammaL='gamma_air',
    OmegaWing=OmegaWingValue,
    OmegaWingHW=0.0,
    LineShift=False)  #, OmegaStep=0.01)
#TimeTakenHapi = time.time() - StartTime
#print("The time taken for HAPI is::",TimeTakenHapi)

StartTime = time.time()
Database = ReadData(Molecule, Location="data/")

CrossSectionDoppler = CalcCrossSection(Database,
                                       Temp=TempValue,
                                       P=P_Value,
                                       Broadening="Self",
                                       WN_Grid=WaveNumber,
Beispiel #9
0
def calDas(gasList, nu, profile, mode, iCut=1e-30, etalonCoeff=None,
           unitDict={'c': 'V ratio', 'p': 'hPa', 't': 'K', 'l': 'cm'}, info_out=False):
    """
    Calculate direction absorption spectrum.
    Parameters
    ----------
    gasList: list of dict
        List of parameters for calculation. The dict should have keys for 'gas' (
        gas name str), 'p' (pressure in hPa), 't' (temperature in K), 'l' (path
        length in cm), 'c' (volume mixing ratio).
    nu: array
        Wavelength array in cm-1.
    profile: str
        Choose one from 'Voigt', 'HT', 'Doppler', and 'Lorentz'.
    mode: str
        Choose one from 'Absorbance', 'Transmission', 'Absorb coeff'.
    iCut: float
        Intensity cut threshold.
    etalonCoeff: list of dict
        Results from generateEtalons, containing coefficients for etalon calculation.
    info_out: bool
        True to output line infomation.

    Returns
    -------
    results: list of dict
        Each dict in the list has keys of 'gasParams' (dict given in input),
        'nu' (wavelength array cm^-1), 'coeff' (spectrum coeff).
    """
    results = []
    for idx, gasParams in enumerate(gasList):
        if gasParams['gas'] not in hapi.tableList():
            return str('Cannot find specified gas.')
        nuInTable = hapi.getColumn(gasParams['gas'], 'nu')
        if (np.min(nu) < np.min(nuInTable) - 1) | (
                    np.min(nu) > np.max(nuInTable) + 1) | (
                    np.max(nu) > np.max(nuInTable) + 1) | (
                    np.max(nu) < np.min(nuInTable) - 1):
            return str(
                'Cannot find lines within specified wavenumber range, please download data.')
        Cond = ('AND', ('BETWEEN', 'nu', np.min(nu), np.max(nu)), ('>=', 'sw', iCut))
        hapi.select(gasParams['gas'], Conditions=Cond, DestinationTableName='tmp')
        p, t, l, n = unitHandler(gasParams, unitDict)

        if profile == 'Voigt':
            nu, coeff = hapi.absorptionCoefficient_Voigt(SourceTables='tmp',
                                                         OmegaGrid=nu,
                                                         Environment={'T': t,
                                                                      'p': p})
        elif profile == 'HT':
            nu, coeff = hapi.absorptionCoefficient_HT(SourceTables='tmp',
                                                      OmegaGrid=nu,
                                                      Environment={'T': t, 'p': p},
                                                      IntensityThreshold=iCut)
        elif profile == 'Doppler':
            nu, coeff = hapi.absorptionCoefficient_Doppler(SourceTables='tmp',
                                                           OmegaGrid=nu,
                                                           Environment={'T': t,
                                                                        'p': p},
                                                           IntensityThreshold=iCut)
        elif profile == 'Lorentz':
            nu, coeff = hapi.absorptionCoefficient_Lorentz(SourceTables='tmp',
                                                           OmegaGrid=nu,
                                                           Environment={'T': t,
                                                                        'p': p},
                                                           IntensityThreshold=iCut)
        else:
            raise Exception('No suitable profile.')
        if mode == 'Absorbance':
            coeff = coeff * n * l
        elif mode == 'Transmission':
            coeff = coeff * n * l
            coeff = np.exp(-coeff)
        if info_out:
            hapi.select('tmp', File='tmp.txt')
        hapi.dropTable('tmp')
        result = dict()
        result['gasParams'] = gasParams
        result['nu'] = nu
        result['spectrum'] = coeff
        results.append(result)
    return results
Beispiel #10
0
import hapi as hp
import matplotlib.pyplot as plt

hp.db_begin("data")
#hp.fetch("H2O",1,1,3400,4100)
hp.select('H2O',
          ParameterNames=('nu', 'sw'),
          Conditions=('between', 'nu', 4000, 4100))

nu, coef = hp.absorptionCoefficient_Voigt(((1, 1), ),
                                          'H2O',
                                          OmegaStep=1,
                                          HITRAN_units=False,
                                          GammaL='gamma_self',
                                          Environment={
                                              'p': 1,
                                              'T': 296.
                                          })

plt.plot(nu, coef)
plt.show()