示例#1
0
def plot_compare_coeffs(directory1, directory2):
    fgrid1 = axml.load(os.path.join(directory1, "TestHitranXsec.f_grid.xml"))
    y1 = axml.load(os.path.join(directory1, "TestHitranXsec.y.xml"))

    fgrid2 = axml.load(os.path.join(directory2, "TestHitranXsec.f_grid.xml"))
    y2 = axml.load(os.path.join(directory2, "TestHitranXsec.y.xml"))

    fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(10, 6))

    fig.suptitle(
        "Species specific coefficients $C_s$ vs. averaged coefficients $C_a$")
    plot_spectrum(ax1, fgrid1, y1, label="$C_s$", rasterized=True)
    ax1.plot(fgrid2, y2, label="$C_a$", rasterized=True)
    ax1.xaxis.set_ticklabels([])
    ax1.set_xlabel("")

    if numpy.max(y1) < 100:
        unit = "radiance"
        ax1.set_ylabel("Spectral radiance $[\\frac{W}{sr⋅m^2⋅Hz}]$")
    else:
        unit = "bt"
        ax1.set_ylabel("Brightness temperature $[B_T]$")

    ax2.set_ylabel(
        "Relative change $\\frac{y_{C_a} - y_{C_s}}{y_{C_s}} [\\%]$")
    ax1.legend()

    axtop = plot_spectrum(ax2, fgrid1, (y2 - y1) / y1 * 100, rasterized=True)
    axtop.xaxis.set_ticklabels([])
    axtop.set_xlabel("")

    fig.savefig(os.path.join("y_coeff_compare." + unit + ".pdf"), dpi=300)
示例#2
0
    def test_equality(self):
        """Check the equality of two GriddedField objects."""
        # Create two different objects with same content.
        a = xml.load(self.ref_dir + 'GriddedField3.xml')
        b = xml.load(self.ref_dir + 'GriddedField3.xml')

        assert a == b
示例#3
0
def plot_xsec(inputdir):
    fgrid_s = axml.load(
        os.path.join(inputdir, "TestHitranXsec-simple.f_grid.xml"))
    xsec = axml.load(
        os.path.join(inputdir,
                     "TestHitranXsec-simple.abs_xsec_per_species.xml"))
    species_names = axml.load(
        os.path.join(inputdir, "TestHitranXsec-simple.abs_species.xml"))

    fig, ax = plt.subplots()

    for species, name in zip(xsec, species_names):
        for band in range(species.shape[1]):
            ax.plot(
                fgrid_s,
                species[:, band],
                label=f"{name[0].split('-')[0]} {band}",
                linewidth=0.75,
            )

    ax.xaxis.set_major_formatter(THzFormatter())
    ax.set_xlabel("THz")

    fig.legend()
    fig.savefig("xsec.pdf", dpi=300)
示例#4
0
def main():
    # Load the (simulated) measurement.
    measurement = xml.load("input/measurement.xml")
    f_grid = measurement.grids[0]
    y_measurement = measurement.data

    # Load the a priori atmospheric state.
    atm_fields = xml.load("input/x_apriori.xml")
    z = atm_fields.get("z", keep_dims=False)
    x_apriori = atm_fields.get("abs_species-H2O", keep_dims=False)

    # Load the covariance matrices.
    S_xa = xml.load("input/S_xa.xml")
    S_y = 2.5e-3 * np.eye(f_grid.size)  # in [K^2]

    # Run the forward model (ARTS).
    # y, K = forward_model(f_grid, atm_fields)

    # Plot the y measurement alongside the simulated y for the a priori.

    # Plot the Jacobians.

    # Plot the covariance matrices.

    # Plot the OEM result next to the true atmospheric state and the a priori.
    # x_oem = retrieve(y_measurement, K, x_apriori, y, S_xa, S_y)

    # Plot the averaging kernels and the measurement response.
    # A = averaging_kernel_matrix(K, S_xa, S_y)

    plt.show()
示例#5
0
def test_load_arts_xml_data(xmlfile):
    """Try to load all XML files in ARTS_DATA_PATH.

    Search for XML files in ARTS_DATA_PATH. If files are found, try to load
    them. It is just checked, if xml.load runs without exception.
    """
    xml.load(xmlfile)
    pass
示例#6
0
def plot_y(directory):
    fgrid = axml.load(os.path.join(directory, "TestHitranXsec.f_grid.xml"))
    y = axml.load(os.path.join(directory, "TestHitranXsec.y.xml"))

    fgrid_nocfc = axml.load(
        os.path.join(directory, "TestHitranXsec-nocfc.f_grid.xml"))
    y_nocfc = axml.load(os.path.join(directory, "TestHitranXsec-nocfc.y.xml"))

    if numpy.max(y) < 100:
        unit = "radiance"
        ylabel = "Spectral radiance $[\\frac{W}{sr⋅m^2⋅Hz}]$"
        int_nocfc = integrate(y_nocfc, fgrid_nocfc)
        int_cfc = integrate(y, fgrid)
        nocfc_extra_label = f" Total: {int_nocfc:.2f} " + "$\\frac{W}{sr⋅m^2}$"
        cfc_extra_label = f" Total: {int_cfc:.2f} " + "$\\frac{W}{sr⋅m^2}$"
    else:
        unit = "bt"
        ylabel = "Brightness temperature $[B_T]$"
        nocfc_extra_label = ""
        cfc_extra_label = ""

    fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(10, 6))
    plt.subplots_adjust(hspace=0)

    fig.suptitle("Fascod profile without CFCs vs. with CFCs")
    ax1a = plot_spectrum(ax1,
                         fgrid_nocfc,
                         y_nocfc,
                         label="$y$" + nocfc_extra_label,
                         rasterized=True)
    ax1.plot(fgrid, y, label="$y_{cfc}$" + cfc_extra_label, rasterized=True)
    ax1.set_ylabel(ylabel)
    ax1.xaxis.set_ticks([])
    ax1.set_xlabel("")
    ax1.spines["right"].set_visible(False)
    ax1.spines["bottom"].set_visible(False)
    ax1a.spines["right"].set_visible(False)
    ax1a.spines["bottom"].set_visible(False)

    ax2.set_ylabel("Relative change $\\frac{y_{cfc} - y}{y} [\\%]$")
    ax1.legend()

    next(ax2._get_lines.prop_cycler)["color"]
    next(ax2._get_lines.prop_cycler)["color"]
    axtop = plot_spectrum(ax2,
                          fgrid, (y - y_nocfc) / y_nocfc * 100,
                          rasterized=True)
    axtop.xaxis.set_ticks([])
    axtop.set_xlabel("")
    ax2.spines["right"].set_visible(False)
    ax2.spines["top"].set_visible(False)
    axtop.spines["right"].set_visible(False)
    axtop.spines["top"].set_visible(False)

    # fig.tight_layout()
    fig.savefig(os.path.join(directory, "y." + unit + ".pdf"), dpi=300)
示例#7
0
    def test_nonequality(self):
        """Check the non-equality of two GriddedField objects."""
        # Create two different objects with same content.
        a = xml.load(self.ref_dir + 'GriddedField3.xml')
        b = xml.load(self.ref_dir + 'GriddedField3.xml')

        a.name = 'foo'
        b.name = 'bar'

        assert a != b
示例#8
0
def plot_xsec(inputfile):
    xsecs = axml.load(inputfile + ".xml")

    fig, ax = plt.subplots()

    ax2 = ax.twiny()
    ax.callbacks.connect(
        "xlim_changed", functools.partial(convert_ax_to_wavenumber, ax2=ax2)
    )

    for xsec in xsecs:
        for fmin, fmax, xsecdata in zip(xsec.fmin, xsec.fmax, xsec.xsec):
            ax.plot(
                numpy.linspace(fmin, fmax, len(xsecdata), endpoint=True),
                xsecdata,
                label=f"{xsec.species} " f"{f2w(fmin):.0f}-{f2w(fmax):.0f}",
                rasterized=True,
            )

    ax.xaxis.set_major_formatter(ticker.FuncFormatter(hz2thz))
    ax.yaxis.set_major_formatter(ticker.FormatStrFormatter("%.1g"))
    ax.set_xlabel("Frequency [THz]")
    ax.set_ylabel("Cross section [m$^2$]")
    ax2.set_xlabel("Wavenumber [cm$^{-1}$]")
    ax.legend()
    fig.savefig(inputfile + ".pdf", dpi=300)
示例#9
0
    def test_copy(self):
        """Test copying of GriddedFields."""
        a = xml.load(self.ref_dir + 'GriddedField3.xml')
        b = a.copy()

        # GriddedFields should be equal but not the same object.
        assert a is not b and a == b
示例#10
0
 def test_save_empty_matrix(self):
     """Save empty Matrix to file, read it and compare the results."""
     reference = _create_empty_tensor(2)
     print(reference)
     xml.save(reference, self.f)
     test_data = xml.load(self.f)
     assert np.array_equal(test_data, reference)
示例#11
0
 def test_save_empty_matrix(self):
     """Save empty Matrix to file, read it and compare the results."""
     reference = _create_empty_tensor(2)
     print(reference)
     xml.save(reference, self.f)
     test_data = xml.load(self.f)
     assert np.array_equal(test_data, reference)
示例#12
0
 def _load_griddedfield(self, dim):
     gf = griddedfield.GriddedField(dim)
     gf.grids = [np.arange(2)] * dim
     gf.data = _create_tensor(dim)
     xml.save(gf, self.f)
     test_data = xml.load(self.f)
     assert np.array_equal(gf.data, test_data.data)
def read_planet_data(planets):
    refdata = {}
    for planet, id in planets:
        refdata[planet] = {}
        refdata[planet]['t'] = axml.load(
            os.path.join(sys.argv[1], 't_field.' + planet + '.xml'))
        refdata[planet]['refindex'] = [
            axml.load(ifile) for ifile in sorted(
                glob(
                    os.path.join(sys.argv[1], 'refindexair.' + planet +
                                 '*.xml')))
        ]
        refdata[planet]['p_grid'] = axml.load(
            os.path.join(sys.argv[1], 'p_grid.' + planet + '.xml'))

    return refdata
示例#14
0
 def _load_griddedfield(self, dim):
     gf = griddedfield.GriddedField(dim)
     gf.grids = [np.arange(2)] * dim
     gf.data = _create_tensor(dim)
     xml.save(gf, self.f)
     test_data = xml.load(self.f)
     assert np.array_equal(gf.data, test_data.data)
示例#15
0
    def test_deepcopy(self):
        """Test deepcopying of GriddedField attributes."""
        a = xml.load(self.ref_dir + 'GriddedField3.xml')
        b = a.copy()

        # Grids should not be the same object.
        assert a.grids is not b.grids
示例#16
0
    def test_save_gzip(self):
        """Test writing/reading of gzipped files."""
        f = self.f + '.gz'
        ref = np.arange(10)

        xml.save(ref, f)

        assert np.array_equal(ref, xml.load(f))
示例#17
0
    def test_slicing(self):
        """Test GriddedField slicing."""
        gf3 = xml.load(self.ref_dir + 'GriddedField3.xml')

        # Create new GriddedField which is a sliced subset of the initial one.
        gf_sliced = gf3.extract_slice(slice(1, None), axis=1)

        assert np.allclose(gf3.data[:, 1:, :], gf_sliced.data)
示例#18
0
文件: em.py 项目: obobryshev/typhon
    def fromArtsXML(cls, sat, instr, ch):
        """Read SRF from ArtsXML files.

        Requires that in the TYPHONRC configuration file, the fields
        `srf_backend_f` and `srf_backend_response` in the section
        corresponding to instrument `instr` are defined to point to the
        respective files in ArtsXML format.  Within those definitions,
        {sat:s} will be substituted with the satellite name.  For example,
        in typhonrc, one might have:

        [hirs]
        srf_backend_response = /path/to/{sat}_HIRS.backend_channel_response.xml
        srf_backend_f = /path/to/{sat}_HIRS.f_backend.xml

        so that we can do:

        >>> srf = SRF.fromArtsXML("NOAA15", "hirs", 12)
        >>> R_300 = srf.blackbody_radiance(ureg.Quantity(atleast_1d(250), 'K')) 
        >>> print(R_300)
        [  2.13002925e-13] watt / hertz / meter ** 2 / steradian
        >>> print(R_300.to("cm * mW / m**2 / sr", "radiance")) 
        [ 6.38566704] centimeter * milliwatt / meter ** 2 / steradian

        Arguments:

            sat [str]

                Satellite name, such as 'NOAA15'

            instr [str]

                Instrument name, such as 'hirs'.

            ch [int]

                Channel number (start counting at 1).
        """
        cf = config.conf[instr]
        centres = xml.load(
            cf["srf_backend_f"].format(sat=sat))
        gfs = xml.load(
            cf["srf_backend_response"].format(sat=sat))
        freq = gfs[ch - 1].grids[0] + centres[ch - 1]
        response = gfs[ch - 1].data
        return cls(freq, response)
示例#19
0
    def test_load_tensor(self, n):
        """Load tensor of dimension n and compare data to reference.

        Args:
            n (int): number of dimensions
        """
        reference = _create_tensor(n)
        test_data = xml.load(self.ref_dir + 'tensor{}.xml'.format(n))
        assert np.array_equal(test_data, reference)
示例#20
0
    def test_write_load_griddedfield(self, dim):
        gf = _get_griddedfield_type(dim)()
        gf.grids = [np.arange(2)] * dim
        gf.data = _create_tensor(dim)
        xml.save(gf, self.f)

        test_data = xml.load(self.f)

        assert np.array_equal(gf.data, test_data.data)
示例#21
0
    def _load_tensor(self, n):
        """Load tensor of dimension n and compare data to reference.

        Args:
            n (int): number of dimensions

        """
        reference = _create_tensor(n)
        test_data = xml.load(self.ref_dir + 'tensor{}.xml'.format(n))
        assert np.array_equal(test_data, reference)
示例#22
0
def convert_arts_to_nc(casename, physics_index=1, forcing_index=1):
    if casename.startswith('option'):
        fluxes = axml.load(
            f'in/{casename}_export/fluxes.{casename}.level_input_{casename}.xml')
    else:
        fluxes = axml.load(f'in/{casename}_export/fluxes.{casename}.level_input.xml')
    fluxes = np.array(fluxes).reshape(18, 100, 61, 3)
    fluxes = np.flip(fluxes, 2)

    with Dataset(
            f'out/rld_Efx_ARTS-2-3_rad-irf_r1i1p'
            f'{physics_index}f{forcing_index}_gn.nc', 'a') as ds:
        ds['rld'][:] = -fluxes[:, :, :, 2]
        ds.physics_index = np.int32(physics_index)

    with Dataset(
            f'out/rlu_Efx_ARTS-2-3_rad-irf_r1i1p'
            f'{physics_index}f{forcing_index}_gn.nc', 'a') as ds:
        ds['rlu'][:] = fluxes[:, :, :, 1]
        ds.physics_index = np.int32(physics_index)
示例#23
0
    def _save_empty_tensor(self, n):
        """Save empty tensor of dimension n to file, read it and compare data to
        reference.

        Args:
            n (int): number of dimensions

        """
        reference = _create_empty_tensor(n)
        xml.save(reference, self.f)
        test_data = xml.load(self.f)
        assert np.array_equal(test_data, reference)
示例#24
0
    def test_save_empty_tensor(self, n):
        """Save empty tensor of dimension n to file, read it and compare data
        to reference.

        Args:
            n (int): number of dimensions

        """
        reference = _create_empty_tensor(n)
        xml.save(reference, self.f)
        test_data = xml.load(self.f)
        assert np.array_equal(test_data, reference)
示例#25
0
    def _save_tensor(self, n, format='ascii'):
        """Save tensor of dimension n to file, read it and compare data to
        reference.

        Args:
            n (int): number of dimensions

        """
        reference = _create_tensor(n)
        xml.save(reference, self.f, format=format)
        test_data = xml.load(self.f)
        assert np.array_equal(test_data, reference)
示例#26
0
def main():
    # select frequency
    highlight_frequency = None  # Hz

    # Calculate Jacobians (ARTS)
    jacobian_quantity = "H2O"
    calc_jacobians(jacobian_quantity=jacobian_quantity)

    # read in everything
    freq = xml.load("results/f_grid.xml")
    tau = xml.load("results/optical_thickness.xml")
    bt = xml.load("results/y.xml")
    jac = xml.load("results/jacobian.xml")
    alt = xml.load("results/z_field.xml").ravel()
    jac /= np.gradient(alt / 1000)  # normalize by layer thickness in km

    ty.plots.styles.use()

    if highlight_frequency is None:
        fig, (ax0, ax1) = plt.subplots(ncols=2)
        plot_brightness_temperature(freq, bt, ax=ax0)
        plot_opacity(freq, tau, ax=ax1)
        freq_ind = None
    else:
        fig, ((ax0, ax1), (ax2, ax3)) = plt.subplots(2, 2)
        plot_brightness_temperature(freq,
                                    bt,
                                    where=highlight_frequency,
                                    ax=ax0)
        plot_opacity(freq, tau, where=highlight_frequency, ax=ax1)
        freq_ind = argclosest(freq, highlight_frequency)
        plot_jacobian(alt,
                      jac[freq_ind, :],
                      jacobian_quantity=jacobian_quantity,
                      ax=ax2)
        plot_opacity_profile(alt, tau[:, freq_ind], ax=ax3)
    fig.tight_layout()
    fig.savefig(f"plots/jacobians-{freq_ind}.pdf")
    plt.show()
示例#27
0
    def to_typhon(self):
        if not self.ws:
            raise Exception("Variable needs associated workspace to be read from workspace.")

        name = str(uuid.uuid4())
        xml_file = os.mkfifo(name + ".xml")
        bin_file = os.mkfifo(name + ".xml.bin")

        p = Process(target = self.ws.WriteXML, args=("binary", self, name + ".xml", 0))
        p.start()
        v = xml.load(name + ".xml")
        p.join()
        os.remove(name + ".xml")
        os.remove(name + ".xml.bin")
        return v
示例#28
0
    def test_xml_io(self):
        save(self.covmat, self.f)
        covmat2 = load(self.f)

        def compare_matrices(args):
            b1, b2 = args
            m1 = b1.matrix
            m2 = b2.matrix
            if isinstance(m1, sp.sparse.spmatrix):
                m1 = m1.todense()
                m2 = m2.todense()
                print(m1)
            return np.allclose(m1, m2)

        assert(all(map(compare_matrices, zip(self.covmat.blocks, covmat2.blocks))))
示例#29
0
def combine_xsec(outfile):
    cfcs = []
    for species in (
        ("CFC11", "output_cfc11_full"),
        ("CFC12", "output_cfc12_full"),
        ("HFC134a", "output_hfc134a_full"),
        ("HCFC22", "output_hcfc22_full"),
    ):
        cfcs.extend(axml.load(os.path.join(species[1], species[0] + ".xml")))

    axml.save(cfcs, outfile + ".xml", format="binary")

    avg_coeffs = numpy.sum(numpy.array([x.coeffs for x in cfcs]), axis=0) / len(cfcs)
    for x in cfcs:
        x.coeffs = avg_coeffs

    print(f"Average coeffs: {avg_coeffs}")
    axml.save(cfcs, outfile + ".avg.xml", format="binary")
示例#30
0
    def to_typhon(self):
        """
        Return the value of this variable as a typhon type. This function
        writes the value of the variable to a temporary file and reads it
        into Python using typhon load function. The purpose of this function
        is to access WSV whose groups are not natively supported by the
        C API.

        Returns:
            A typhon object with the same value as the WSV in the associated
            workspace.
        """
        if not self.ws:
            raise Exception("Cannot retrieve the value of a variable without "
                            + " associated Workspace.")
        tmp = tempfile.NamedTemporaryFile()
        self.ws.WriteXML("ascii", self, tmp.name)
        v = load(tmp.name)
        tmp.close()
        return v
示例#31
0
def combine_data_for_arts(species, outdir, **_):
    # FIXME: How to handle the active flag?
    # active_species = {k: v for k, v in XSEC_SPECIES_INFO.items()
    #                   if k in species
    #                   and (('active' in v and v[
    #     'active']) or 'active' not in v)}

    combined_xml_file = os.path.join(outdir, "cfc_combined.xml")
    all_species = []
    for s in species:
        cfc_file = os.path.join(outdir, s, "cfc.xml")
        try:
            data = axml.load(cfc_file)
        except FileNotFoundError:
            logger.warning(f"No xml file found for species {s}, ignoring")
        else:
            all_species.append(data)
            logger.info(f"Added {s}")

    axml.save(list(itertools.chain(*all_species)),
              combined_xml_file,
              format="binary")
    logger.info(f"Wrote {combined_xml_file}")
示例#32
0
    def to_typhon(self):
        """
        Return the value of this variable as a typhon type. This function
        writes the value of the variable to a temporary file and reads it
        into Python using typhon load function. The purpose of this function
        is to access WSV whose groups are not natively supported by the
        C API.

        Returns:
            A typhon object with the same value as the WSV in the associated
            workspace.
        """
        from typhon.arts.xml import load

        if not self.ws:
            raise Exception("Cannot retrieve the value of a variable without "
                            + " associated Workspace.")
        with tempfile.TemporaryDirectory() as tmpdir:
            tfile = os.path.join(tmpdir, 'wsv.xml')
            self.ws.WriteXML("binary", self, tfile)
            v = load(tfile)

        return v
示例#33
0
 def test_load_arrayofvector(self):
     """Load reference XML file for ARTS type ArrayOfVector."""
     reference = [np.arange(1), np.arange(1)]
     test_data = xml.load(self.ref_dir + 'arrayofvector.xml')
     assert np.array_equal(test_data, reference)
示例#34
0
 def test_load_comment(self):
     """Load reference XML file storing only a comment."""
     test_data = xml.load(self.ref_dir + 'comment.xml')
     assert test_data is None
示例#35
0
 def test_load_arrayofindex_with_comment(self):
     """Load reference XML file for ARTS type ArrayOfIndex with comment."""
     reference = [1., 2., 3.]
     test_data = xml.load(self.ref_dir + 'arrayofindex-comment.xml')
     assert np.array_equal(test_data, reference)
示例#36
0
 def test_save_index(self):
     """Save Index to file, read it and compare the results."""
     reference = 0
     xml.save(reference, self.f)
     test_data = xml.load(self.f)
     assert test_data == reference
示例#37
0
# -*- coding: utf-8 -*-
"""Evluate the influence of the elevation angle when simulating incoming
longwave radiation.
"""
import numpy as np
import matplotlib.pyplot as plt
import clb
from typhon.arts import xml
from typhon.plots import styles


f = xml.load('../arts/results/angle_integration/f_grid.xml')
y_los = xml.load('../arts/results/angle_integration/y.xml')
los = xml.load('../arts/results/angle_integration/sensor_los.xml')

plt.style.use(styles('typhon'))

lwr_new = clb.math.integrate_angles(f, y_los, los, dtheta=15)

fig, ax = plt.subplots()
for y, a in zip(np.split(y_los, los.size), los):
    ax.plot(f/1e12, y,
            label='${}^\circ$'.format(int(a)),
            linewidth=3,
            linestyle='-')
ax.set_xlim(f.min()/1e12, f.max()/1e12)
ax.set_xlabel('Frequenz [THz]')
ax.set_ylabel(r'Radianz [$W\,m^{-2}\,sr^{-1}\,Hz^{-1}$]')
ax.legend(ncol=2)
fig.savefig('plots/lwr_spectrum_elevation.pdf')
示例#38
0
 def test_save_vector_binary(self):
     """Save Vector to binary file, read it and compare the results."""
     reference = _create_tensor(1)
     xml.save(reference, self.f, format='binary')
     test_data = xml.load(self.f)
     assert np.array_equal(test_data, reference)
示例#39
0
 def test_load_dimension(self):
     """Load reference XML file for GriddedField3 and run check."""
     gf3 = xml.load(self.ref_dir + 'GriddedField3.xml')
     assert gf3.check_dimension()
示例#40
0
def _load_xml(f):
    """Load a given XML file."""
    xml.load(f)
    pass
示例#41
0
 def test_save_arrayofstring(self):
     """Save ArrayOfString to file, read it and compare the results."""
     reference = ['a', 'bb', 'ccc']
     xml.save(reference, self.f)
     test_data = xml.load(self.f)
     assert np.array_equal(test_data, reference)
示例#42
0
 def test_save_arrayofvector(self):
     """Save ArrayOfIndex to file, read it and compare the results."""
     reference = [np.arange(1), np.arange(1)]
     xml.save(reference, self.f)
     test_data = xml.load(self.f)
     assert np.array_equal(test_data, reference)
示例#43
0
 def test_load_index(self):
     """Load reference XML file for ARTS type Index."""
     assert xml.load(self.ref_dir + 'index.xml') == 0
示例#44
0
 def test_load_vector_binary(self):
     """Load reference binary XML file for ARTS type Vector."""
     reference = _create_tensor(1)
     test_data = xml.load(self.ref_dir + 'vector-bin.xml')
     assert np.array_equal(test_data, reference)
示例#45
0
 def test_load_data(self):
     """Load reference XML file for GriddedField3 and check the data."""
     reference = _create_tensor(3)
     gf3 = xml.load(self.ref_dir + 'GriddedField3.xml')
     test_data = gf3.data
     assert np.array_equal(test_data, reference)
示例#46
0
 def test_load_arrayofstring(self):
     """Load reference XML file for ARTS type ArrayOfString."""
     reference = ['a', 'bb', 'ccc']
     test_data = xml.load(self.ref_dir + 'arrayofstring.xml')
     assert np.array_equal(test_data, reference)
示例#47
0
 def test_load_dimension(self):
     """Load reference XML file for GriddedField3 and run check."""
     gf3 = xml.load(self.ref_dir + 'GriddedField3.xml')
     assert gf3.check_dimension()
示例#48
0
 def test_save_arrayofindex_binary(self):
     """Save ArrayOfIndex to binary file, read it and compare the result."""
     reference = [1., 2., 3.]
     xml.save(reference, self.f, format='binary')
     test_data = xml.load(self.f)
     assert np.array_equal(test_data, reference)
示例#49
0
 def test_load_gridnames(self):
     """Load reference XML file for GriddedField3 and check gridnames."""
     reference = ['grid1', 'grid2', 'grid3']
     gf3 = xml.load(self.ref_dir + 'GriddedField3.xml')
     test_data = gf3.gridnames
     assert np.array_equal(test_data, reference)
示例#50
0
 def test_load_matrix(self):
     """Load reference XML file for ARTS type Matrix."""
     reference = _create_tensor(2)
     test_data = xml.load(self.ref_dir + 'matrix.xml')
     assert np.array_equal(test_data, reference)
示例#51
0
 def test_load_grids(self):
     """Load reference XML file for GriddedField3 and check the grids."""
     reference = [np.arange(2)] * 3
     gf3 = xml.load(self.ref_dir + 'GriddedField3.xml')
     test_data = gf3.grids
     assert all(np.allclose(a, b) for a, b in zip(test_data, reference))
示例#52
0
 def test_from_xarray(self):
     a = xml.load(self.ref_dir + 'GriddedField3.xml')
     a.dataname = 'Testdata'
     da = a.to_xarray()
     b = griddedfield.GriddedField.from_xarray(da)
     assert a == b
示例#53
0
 def test_load_arrayofindex_binary(self):
     """Load reference binary XML file for ARTS type ArrayOfIndex."""
     reference = [1., 2., 3.]
     test_data = xml.load(self.ref_dir + 'arrayofindex-bin.xml')
     assert np.array_equal(test_data, reference)