Пример #1
0
def test_call_module():
    "Run a command to see if call_module works"
    data_fname = os.path.join(TEST_DATA_DIR, "points.txt")
    out_fname = "test_call_module.txt"
    with clib.Session() as lib:
        with GMTTempFile() as out_fname:
            lib.call_module("info",
                            "{} -C ->{}".format(data_fname, out_fname.name))
            assert os.path.exists(out_fname.name)
            output = out_fname.read().strip()
            assert output == "11.5309 61.7074 -2.9289 7.8648 0.1412 0.9338"
Пример #2
0
def test_filter1d_file_output(data):
    """
    Test that filter1d returns a file output when it is specified.
    """
    with GMTTempFile(suffix=".txt") as tmpfile:
        result = filter1d(data=data,
                          filter_type="g5",
                          outfile=tmpfile.name,
                          output_type="file")
        assert result is None  # return value is None
        assert os.path.exists(path=tmpfile.name)  # check that outfile exists
Пример #3
0
def test_figure_savefig_filename_with_spaces():
    """
    Check if savefig (or psconvert) supports filenames with spaces.
    """
    fig = Figure()
    fig.basemap(region=[0, 1, 0, 1], projection="X1c/1c", frame=True)
    with GMTTempFile(prefix="pygmt-filename with spaces",
                     suffix=".png") as imgfile:
        fig.savefig(fname=imgfile.name)
        assert r"\040" not in os.path.abspath(imgfile.name)
        assert os.path.exists(imgfile.name)
Пример #4
0
def test_grdvolume_outgrid(grid):
    """
    Test the expected output of grdvolume with an output file set.
    """
    with GMTTempFile(suffix=".csv") as tmpfile:
        result = grdvolume(grid=grid,
                           contour=[200, 400, 50],
                           output_type="file",
                           outfile=tmpfile.name)
        assert result is None  # return value is None
        assert os.path.exists(path=tmpfile.name)  # check that outfile exists
Пример #5
0
def test_sphinterpolate_outgrid(mars):
    """
    Test sphinterpolate with a set outgrid.
    """
    with GMTTempFile(suffix=".nc") as tmpfile:
        result = sphinterpolate(data=mars,
                                outgrid=tmpfile.name,
                                spacing=1,
                                region="g")
        assert result is None  # return value is None
        assert os.path.exists(path=tmpfile.name)  # check that outgrid exists
Пример #6
0
def test_sph2grd_outgrid():
    """
    Test sph2grd with a set outgrid.
    """
    with GMTTempFile(suffix=".nc") as tmpfile:
        result = sph2grd(data="@EGM96_to_36.txt",
                         outgrid=tmpfile.name,
                         spacing=1,
                         region="g")
        assert result is None  # return value is None
        assert os.path.exists(path=tmpfile.name)  # check that outgrid exists
Пример #7
0
def test_grdsample_file_out(grid):
    """
    grdsample with an outgrid set and the spacing is changed.
    """
    with GMTTempFile(suffix=".nc") as tmpfile:
        result = grdsample(grid=grid, outgrid=tmpfile.name, spacing=[1, 0.5])
        assert result is None  # return value is None
        assert os.path.exists(path=tmpfile.name)  # check that outgrid exists
        result = grdinfo(tmpfile.name, per_column=True).strip().split()
        assert float(result[6]) == 1  # x-increment
        assert float(result[7]) == 0.5  # y-increment
Пример #8
0
def test_grdfilter_dataarray_in_file_out(grid):
    """
    grdfilter an input DataArray, and output to a grid file.
    """
    with GMTTempFile(suffix=".nc") as tmpfile:
        result = grdfilter(grid, outgrid=tmpfile.name, filter="g600", distance="4")
        assert result is None  # grdfilter returns None if output to a file
        result = grdinfo(tmpfile.name, per_column=True)
        assert (
            result == "-180 180 -90 90 -6147.49072266 5164.06005859 1 1 360 180 1 1\n"
        )
Пример #9
0
def grdlandmask(**kwargs):
    r"""
    Create a grid file with set values for land and water.

    Read the selected shoreline database and create a grid to specify which
    nodes in the specified grid are over land or over water. The nodes defined
    by the selected region and lattice spacing
    will be set according to one of two criteria: (1) land vs water, or
    (2) the more detailed (hierarchical) ocean vs land vs lake
    vs island vs pond.

    Full option list at :gmt-docs:`grdlandmask.html`

    {aliases}

    Parameters
    ----------
    outgrid : str or None
        The name of the output netCDF file with extension .nc to store the grid
        in.
    {I}
    {R}
    {r}

    Returns
    -------
    ret: xarray.DataArray or None
        Return type depends on whether the ``outgrid`` parameter is set:

        - :class:`xarray.DataArray` if ``outgrid`` is not set
        - None if ``outgrid`` is set (grid output will be stored in file set by
          ``outgrid``)
    """
    if "I" not in kwargs.keys() or "R" not in kwargs.keys():
        raise GMTInvalidInput("Both 'region' and 'spacing' must be specified.")

    with GMTTempFile(suffix=".nc") as tmpfile:
        with Session() as lib:
            if "G" not in kwargs.keys(
            ):  # if outgrid is unset, output to tempfile
                kwargs.update({"G": tmpfile.name})
            outgrid = kwargs["G"]
            arg_str = build_arg_string(kwargs)
            lib.call_module("grdlandmask", arg_str)

        if outgrid == tmpfile.name:  # if user did not set outgrid, return DataArray
            with xr.open_dataarray(outgrid) as dataarray:
                result = dataarray.load()
                _ = result.gmt  # load GMTDataArray accessor information
        else:
            result = None  # if user sets an outgrid, return None

        return result
Пример #10
0
def test_grdcut_file_in_file_out():
    """
    grdcut an input grid file, and output to a grid file.
    """
    with GMTTempFile(suffix=".nc") as tmpfile:
        result = grdcut("@earth_relief_01d",
                        outgrid=tmpfile.name,
                        region="0/180/0/90")
        assert result is None  # return value is None
        assert os.path.exists(path=tmpfile.name)  # check that outgrid exists
        result = grdinfo(tmpfile.name, per_column=True)
        assert result == "0 180 0 90 -8182 5651.5 1 1 180 90 1 1\n"
Пример #11
0
def test_grdlandmask_outgrid(expected_grid):
    """
    Creates a grid land mask with an outgrid argument.
    """
    with GMTTempFile(suffix=".nc") as tmpfile:
        result = grdlandmask(outgrid=tmpfile.name,
                             spacing=1,
                             region=[125, 130, 30, 35])
        assert result is None  # return value is None
        assert os.path.exists(path=tmpfile.name)  # check that outgrid exists
        temp_grid = load_dataarray(tmpfile.name)
        xr.testing.assert_allclose(a=temp_grid, b=expected_grid)
Пример #12
0
def test_grdcut_file_in_file_out(expected_grid):
    """
    grdcut an input grid file, and output to a grid file.
    """
    with GMTTempFile(suffix=".nc") as tmpfile:
        result = grdcut("@earth_relief_01d",
                        outgrid=tmpfile.name,
                        region=[-3, 1, 2, 5])
        assert result is None  # return value is None
        assert os.path.exists(path=tmpfile.name)  # check that outgrid exists
        temp_grid = load_dataarray(tmpfile.name)
        xr.testing.assert_allclose(a=temp_grid, b=expected_grid)
Пример #13
0
def test_equalize_grid_outgrid_file(grid, expected_grid, region):
    """
    Test grdhisteq.equalize_grid with a set outgrid.
    """
    with GMTTempFile(suffix=".nc") as tmpfile:
        result = grdhisteq.equalize_grid(grid=grid,
                                         divisions=2,
                                         region=region,
                                         outgrid=tmpfile.name)
        assert result is None  # return value is None
        assert os.path.exists(path=tmpfile.name)  # check that outgrid exists
        temp_grid = load_dataarray(tmpfile.name)
        xr.testing.assert_allclose(a=temp_grid, b=expected_grid)
Пример #14
0
def test_grd2xyz_outfile_incorrect_output_type(grid):
    """
    Test that grd2xyz raises a warning when an outfile filename is set but the
    output_type is not set to 'file'.
    """
    with pytest.warns(RuntimeWarning):
        with GMTTempFile(suffix=".xyz") as tmpfile:
            result = grd2xyz(grid=grid,
                             outfile=tmpfile.name,
                             output_type="numpy")
            assert result is None  # return value is None
            assert os.path.exists(
                path=tmpfile.name)  # check that outfile exists
Пример #15
0
def test_grdsample_file_out(grid, expected_grid, region, spacing):
    """
    Test grdsample with an outgrid set and the spacing is changed.
    """
    with GMTTempFile(suffix=".nc") as tmpfile:
        result = grdsample(grid=grid,
                           outgrid=tmpfile.name,
                           spacing=spacing,
                           region=region)
        assert result is None  # return value is None
        assert os.path.exists(path=tmpfile.name)  # check that outgrid exists
        temp_grid = load_dataarray(tmpfile.name)
        xr.testing.assert_allclose(a=temp_grid, b=expected_grid)
Пример #16
0
def test_grdtrack_input_csvfile_and_dataarray(dataarray, expected_array):
    """
    Run grdtrack by passing in a csvfile and xarray.DataArray as inputs.
    """
    with GMTTempFile() as tmpfile:
        output = grdtrack(points=POINTS_DATA,
                          grid=dataarray,
                          outfile=tmpfile.name)
        assert output is None  # check that output is None since outfile is set
        assert os.path.exists(
            path=tmpfile.name)  # check that outfile exists at path
        output = np.loadtxt(tmpfile.name)
        npt.assert_allclose(np.array(output), expected_array)
Пример #17
0
def sph2grd(data, **kwargs):
    r"""
    Create spherical grid files in tension of data.

    Reads a spherical harmonics coefficient table with records of L, M,
    C[L,M], S[L,M] and evaluates the spherical harmonic model on the
    specified grid.

    Full option list at :gmt-docs:`sph2grd.html`

    {aliases}

    Parameters
    ----------
    data : str or {table-like}
        Pass in data with L, M, C[L,M], S[L,M] values by
        providing a file name to an ASCII data table, a 2D
        {table-classes}.
    outgrid : str or None
        The name of the output netCDF file with extension .nc to store the grid
        in.
    {I}
    {R}
    {V}
    {b}
    {h}
    {i}
    {r}
    {x}

    Returns
    -------
    ret: xarray.DataArray or None
        Return type depends on whether the ``outgrid`` parameter is set:

        - :class:`xarray.DataArray` if ``outgrid`` is not set
        - None if ``outgrid`` is set (grid output will be stored in file set by
          ``outgrid``)
    """
    with GMTTempFile(suffix=".nc") as tmpfile:
        with Session() as lib:
            file_context = lib.virtualfile_from_data(check_kind="vector",
                                                     data=data)
            with file_context as infile:
                if "G" not in kwargs:  # if outgrid is unset, output to tempfile
                    kwargs.update({"G": tmpfile.name})
                outgrid = kwargs["G"]
                arg_str = " ".join([infile, build_arg_string(kwargs)])
                lib.call_module("sph2grd", arg_str)

        return load_dataarray(outgrid) if outgrid == tmpfile.name else None
Пример #18
0
def test_grdgradient_outgrid(grid, expected_grid):
    """
    Test the azimuth and direction parameters for grdgradient with a set
    outgrid.
    """
    with GMTTempFile(suffix=".nc") as tmpfile:
        result = grdgradient(grid=grid,
                             outgrid=tmpfile.name,
                             azimuth=10,
                             region=[-53, -49, -20, -17])
        assert result is None  # return value is None
        assert os.path.exists(path=tmpfile.name)  # check that outgrid exists
        temp_grid = load_dataarray(tmpfile.name)
        xr.testing.assert_allclose(a=temp_grid, b=expected_grid)
Пример #19
0
def test_filter1d_outfile_incorrect_output_type(data):
    """
    Test that filter1d raises a warning when an outfile filename is set but the
    output_type is not set to 'file'.
    """
    with pytest.warns(RuntimeWarning):
        with GMTTempFile(suffix=".txt") as tmpfile:
            result = filter1d(data=data,
                              filter_type="g5",
                              outfile=tmpfile.name,
                              output_type="numpy")
            assert result is None  # return value is None
            assert os.path.exists(
                path=tmpfile.name)  # check that outfile exists
Пример #20
0
def test_plot3d_scalar_xyz():
    """
    Plot symbols given scalar x, y, z coordinates.
    """
    fig_ref, fig_test = Figure(), Figure()
    with GMTTempFile() as tmpfile:
        np.savetxt(tmpfile.name, np.c_[[-1.5, 0, 1.5], [1.5, 0, -1.5],
                                       [-1.5, 0, 1.5]])
        fig_ref.basemap(R="-2/2/-2/2/-2/2",
                        B=["xaf+lx", "yaf+ly", "zaf+lz"],
                        Jz=2,
                        p="225/30")
        fig_ref.plot3d(data=tmpfile.name, S="c1c", G="red", Jz="", p="", qi=0)
        fig_ref.plot3d(data=tmpfile.name,
                       S="t1c",
                       G="green",
                       Jz="",
                       p="",
                       qi=1)
        fig_ref.plot3d(data=tmpfile.name, S="s1c", G="blue", Jz="", p="", qi=2)

    fig_test.basemap(
        region=[-2, 2, -2, 2, -2, 2],
        frame=["xaf+lx", "yaf+ly", "zaf+lz"],
        zscale=2,
        perspective=[225, 30],
    )
    fig_test.plot3d(x=-1.5,
                    y=1.5,
                    z=-1.5,
                    style="c1c",
                    color="red",
                    zscale=True,
                    perspective=True)
    fig_test.plot3d(x=0,
                    y=0,
                    z=0,
                    style="t1c",
                    color="green",
                    zscale=True,
                    perspective=True)
    fig_test.plot3d(x=1.5,
                    y=-1.5,
                    z=1.5,
                    style="s1c",
                    color="blue",
                    zscale=True,
                    perspective=True)
    return fig_ref, fig_test
Пример #21
0
def which(fname, **kwargs):
    """
    Find the full path to specified files.

    Reports the full paths to the files given through *fname*. We look for
    the file in (1) the current directory, (2) in $GMT_USERDIR (if defined),
    (3) in $GMT_DATADIR (if defined), or (4) in $GMT_CACHEDIR (if defined).

    *fname* can also be a downloadable file (either a full URL, a
    `@file` special file for downloading from the GMT Site Cache, or
    `@earth_relief_*` topography grids). In these cases, use option *download*
    to set the desired behavior. If *download* is not used (or False), the file
    will not be found.

    Full option list at :gmt-docs:`gmtwhich.html`

    {aliases}

    Parameters
    ----------
    fname : str
        The file name that you want to check.
    download : bool or str
        If the file is downloadable and not found, we will try to download the
        it. Use True or 'l' (default) to download to the current directory. Use
        'c' to place in the user cache directory or 'u' user data directory
        instead.
    {V}

    Returns
    -------
    path : str
        The path of the file, depending on the options used.

    Raises
    ------
    FileNotFoundError
        If the file is not found.

    """
    with GMTTempFile() as tmpfile:
        arg_str = " ".join(
            [fname, build_arg_string(kwargs), "->" + tmpfile.name])
        with Session() as lib:
            lib.call_module("which", arg_str)
        path = tmpfile.read().strip()
    if not path:
        raise FileNotFoundError("File '{}' not found.".format(fname))
    return path
Пример #22
0
def test_grdproject_file_out(grid):
    """
    grdproject with an outgrid set.
    """
    with GMTTempFile(suffix=".nc") as tmpfile:
        result = grdproject(grid=grid, projection="M10c", outgrid=tmpfile.name)
        assert result is None  # return value is None
        assert os.path.exists(path=tmpfile.name)  # check that outgrid exists
        result = grdinfo(tmpfile.name, per_column=True).strip().split()
        npt.assert_allclose(float(result[0]), 0)  # x min
        npt.assert_allclose(float(result[1]), 10)  # x max
        npt.assert_allclose(float(result[2]), 0, atol=1.0e-10)  # y min
        npt.assert_allclose(float(result[3]), 9.94585661273)  # y max
        npt.assert_allclose(float(result[4]), -5130.48193359)  # min
        npt.assert_allclose(float(result[5]), -152.585281372)  # max
Пример #23
0
def test_xyz2grd_input_array_file_out(ship_data):
    """
    Run xyz2grd by passing in a numpy array and set an outgrid file.
    """
    with GMTTempFile(suffix=".nc") as tmpfile:
        result = xyz2grd(
            data=np.array(ship_data),
            spacing=5,
            region=[245, 255, 20, 30],
            outgrid=tmpfile.name,
        )
        assert result is None  # return value is None
        assert os.path.exists(path=tmpfile.name)
        result = grdinfo(tmpfile.name, per_column=True).strip()
        assert result == "245 255 20 30 -3651.06079102 -352.379486084 5 5 3 3 0 0"
Пример #24
0
def test_virtualfile_from_vectors_arraylike():
    "Pass array-like vectors to a dataset"
    size = 13
    x = list(range(0, size, 1))
    y = tuple(range(size, size * 2, 1))
    z = range(size * 2, size * 3, 1)
    with clib.Session() as lib:
        with lib.virtualfile_from_vectors(x, y, z) as vfile:
            with GMTTempFile() as outfile:
                lib.call_module("info", "{} ->{}".format(vfile, outfile.name))
                output = outfile.read(keep_tabs=True)
        bounds = "\t".join(
            ["<{:.0f}/{:.0f}>".format(min(i), max(i)) for i in (x, y, z)])
        expected = "<vector memory>: N = {}\t{}\n".format(size, bounds)
        assert output == expected
Пример #25
0
def test_delaunay_triples_outfile(dataframe, expected_dataframe):
    """
    Test triangulate.delaunay_triples with ``outfile``.
    """
    with GMTTempFile(suffix=".txt") as tmpfile:
        with pytest.warns(RuntimeWarning) as record:
            result = triangulate.delaunay_triples(data=dataframe,
                                                  outfile=tmpfile.name)
            assert len(record) == 1  # check that only one warning was raised
        assert result is None  # return value is None
        assert os.path.exists(path=tmpfile.name)
        temp_df = pd.read_csv(filepath_or_buffer=tmpfile.name,
                              sep="\t",
                              header=None)
        pd.testing.assert_frame_equal(left=temp_df, right=expected_dataframe)
Пример #26
0
def test_grdclip_outgrid(grid):
    """
    Test the below and above parameters for grdclip and creates a test outgrid.
    """
    with GMTTempFile(suffix=".nc") as tmpfile:
        result = grdclip(grid=grid,
                         outgrid=tmpfile.name,
                         below=[-1500, -1800],
                         above=[-200, 40])
        assert result is None  # return value is None
        assert os.path.exists(path=tmpfile.name)  # check that outgrid exists
        result = (grdinfo(grid=tmpfile.name, force_scan=0,
                          per_column="n").strip().split())
    assert int(result[4]) == -1800  # minimum value
    assert int(result[5]) == 40  # maximum value
Пример #27
0
def test_xyz2grd_input_array_file_out(ship_data, expected_grid):
    """
    Run xyz2grd by passing in a numpy array and set an outgrid file.
    """
    with GMTTempFile(suffix=".nc") as tmpfile:
        result = xyz2grd(
            data=ship_data,
            spacing=5,
            region=[245, 255, 20, 30],
            outgrid=tmpfile.name,
        )
        assert result is None  # return value is None
        assert os.path.exists(path=tmpfile.name)
        temp_grid = load_dataarray(tmpfile.name)
        xr.testing.assert_allclose(a=temp_grid, b=expected_grid)
Пример #28
0
def test_grdlandmask_outgrid():
    """
    Creates a grid land mask with an outgrid argument.
    """
    with GMTTempFile(suffix=".nc") as tmpfile:
        result = grdlandmask(outgrid=tmpfile.name,
                             spacing=1,
                             region=[-5, 5, -5, 5])
        assert result is None  # return value is None
        assert os.path.exists(path=tmpfile.name)  # check that outgrid exists
        result = (grdinfo(grid=tmpfile.name, force_scan=0,
                          per_column="n").strip().split())
    assert result == [
        "-5", "5", "-5", "5", "0", "1", "1", "1", "11", "11", "0", "1"
    ]
Пример #29
0
def test_virtualfile_from_vectors_arraylike():
    """
    Pass array-like vectors to a dataset.
    """
    size = 13
    x = list(range(0, size, 1))
    y = tuple(range(size, size * 2, 1))
    z = range(size * 2, size * 3, 1)
    with clib.Session() as lib:
        with lib.virtualfile_from_vectors(x, y, z) as vfile:
            with GMTTempFile() as outfile:
                lib.call_module("info", f"{vfile} ->{outfile.name}")
                output = outfile.read(keep_tabs=True)
        bounds = "\t".join([f"<{min(i):.0f}/{max(i):.0f}>" for i in (x, y, z)])
        expected = f"<vector memory>: N = {size}\t{bounds}\n"
        assert output == expected
Пример #30
0
def test_blockmean_input_filename():
    """
    Run blockmean by passing in an ASCII text file as input.
    """
    with GMTTempFile() as tmpfile:
        output = blockmean(
            data="@tut_ship.xyz",
            spacing="5m",
            region=[245, 255, 20, 30],
            outfile=tmpfile.name,
        )
        assert output is None  # check that output is None since outfile is set
        assert os.path.exists(path=tmpfile.name)  # check that outfile exists at path
        output = pd.read_csv(tmpfile.name, sep="\t", header=None)
        assert output.shape == (5849, 3)
        npt.assert_allclose(output.iloc[0], [245.888877, 29.978707, -384.0])