Skip to content

Commit 39da1cf

Browse files
authored
pygmt.triangulate: Refactor to use codes consistent with other wrappers (#3073)
1 parent 5014591 commit 39da1cf

File tree

2 files changed

+57
-179
lines changed

2 files changed

+57
-179
lines changed

pygmt/src/triangulate.py

+57-170
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@
55

66
import pandas as pd
77
from pygmt.clib import Session
8-
from pygmt.exceptions import GMTInvalidInput
98
from pygmt.helpers import (
109
GMTTempFile,
1110
build_arg_string,
@@ -64,109 +63,7 @@ class triangulate: # noqa: N801
6463
w="wrap",
6564
)
6665
@kwargs_to_strings(I="sequence", R="sequence", i="sequence_comma")
67-
def _triangulate(
68-
data=None, x=None, y=None, z=None, *, output_type, outfile=None, **kwargs
69-
):
70-
"""
71-
Delaunay triangulation or Voronoi partitioning and gridding of Cartesian data.
72-
73-
Must provide ``outfile`` or ``outgrid``.
74-
75-
Full option list at :gmt-docs:`triangulate.html`
76-
77-
{aliases}
78-
79-
Parameters
80-
----------
81-
x/y/z : np.ndarray
82-
Arrays of x and y coordinates and values z of the data points.
83-
data : str, {table-like}
84-
Pass in (x, y, z) or (longitude, latitude, elevation) values by
85-
providing a file name to an ASCII data table, a 2-D
86-
{table-classes}.
87-
{projection}
88-
{region}
89-
{spacing}
90-
{outgrid}
91-
The interpolation is performed in the original coordinates, so if
92-
your triangles are close to the poles you are better off projecting
93-
all data to a local coordinate system before using ``triangulate``
94-
(this is true of all gridding routines) or instead select
95-
:gmt-docs:`sphtriangulate <sphtriangulate.html>`.
96-
outfile : str, bool or None
97-
The name of the output ASCII file to store the results of the
98-
histogram equalization in.
99-
output_type: str
100-
Determine the output type. Use "file", "xarray", "pandas", or
101-
"numpy".
102-
{verbose}
103-
{binary}
104-
{nodata}
105-
{find}
106-
{coltypes}
107-
{header}
108-
{incols}
109-
{registration}
110-
Only valid with ``outgrid``.
111-
{skiprows}
112-
{wrap}
113-
114-
Returns
115-
-------
116-
ret: numpy.ndarray or pandas.DataFrame or xarray.DataArray or None
117-
Return type depends on the ``output_type`` parameter:
118-
119-
- numpy.ndarray if ``output_type`` is "numpy"
120-
- pandas.DataFrame if ``output_type`` is "pandas"
121-
- xarray.DataArray if ``output_type`` is "xarray""
122-
- None if ``output_type`` is "file" (output is stored in
123-
``outgrid`` or ``outfile``)
124-
"""
125-
with Session() as lib:
126-
table_context = lib.virtualfile_from_data(
127-
check_kind="vector", data=data, x=x, y=y, z=z, required_z=False
128-
)
129-
with table_context as infile:
130-
# table output if outgrid is unset, else output to outgrid
131-
if (outgrid := kwargs.get("G")) is None:
132-
kwargs.update({">": outfile})
133-
lib.call_module(
134-
module="triangulate", args=build_arg_string(kwargs, infile=infile)
135-
)
136-
137-
if output_type == "file":
138-
return None
139-
if output_type == "xarray":
140-
return load_dataarray(outgrid)
141-
142-
result = pd.read_csv(outfile, sep="\t", header=None)
143-
if output_type == "numpy":
144-
return result.to_numpy()
145-
return result
146-
147-
@staticmethod
148-
@fmt_docstring
149-
def regular_grid( # noqa: PLR0913
150-
data=None,
151-
x=None,
152-
y=None,
153-
z=None,
154-
outgrid=None,
155-
spacing=None,
156-
projection=None,
157-
region=None,
158-
verbose=None,
159-
binary=None,
160-
nodata=None,
161-
find=None,
162-
coltypes=None,
163-
header=None,
164-
incols=None,
165-
registration=None,
166-
skiprows=None,
167-
wrap=None,
168-
**kwargs,
169-
):
66+
def regular_grid(data=None, x=None, y=None, z=None, **kwargs):
17067
"""
17168
Delaunay triangle based gridding of Cartesian data.
17269
@@ -190,6 +87,8 @@ def regular_grid( # noqa: PLR0913
19087
19188
Full option list at :gmt-docs:`triangulate.html`
19289
90+
{aliases}
91+
19392
Parameters
19493
----------
19594
x/y/z : np.ndarray
@@ -236,58 +135,45 @@ def regular_grid( # noqa: PLR0913
236135
"""
237136
# Return an xarray.DataArray if ``outgrid`` is not set
238137
with GMTTempFile(suffix=".nc") as tmpfile:
239-
if isinstance(outgrid, str):
240-
output_type = "file"
241-
elif outgrid is None:
242-
output_type = "xarray"
243-
outgrid = tmpfile.name
244-
else:
245-
raise GMTInvalidInput(
246-
"'outgrid' should be a proper file name or `None`"
247-
)
248-
249-
return triangulate._triangulate(
250-
data=data,
251-
x=x,
252-
y=y,
253-
z=z,
254-
output_type=output_type,
255-
outgrid=outgrid,
256-
spacing=spacing,
257-
projection=projection,
258-
region=region,
259-
verbose=verbose,
260-
binary=binary,
261-
nodata=nodata,
262-
find=find,
263-
coltypes=coltypes,
264-
header=header,
265-
incols=incols,
266-
registration=registration,
267-
skiprows=skiprows,
268-
wrap=wrap,
269-
**kwargs,
270-
)
138+
with Session() as lib:
139+
with lib.virtualfile_from_data(
140+
check_kind="vector", data=data, x=x, y=y, z=z, required_z=False
141+
) as vintbl:
142+
if (outgrid := kwargs.get("G")) is None:
143+
kwargs["G"] = outgrid = tmpfile.name # output to tmpfile
144+
lib.call_module(
145+
module="triangulate",
146+
args=build_arg_string(kwargs, infile=vintbl),
147+
)
148+
149+
return load_dataarray(outgrid) if outgrid == tmpfile.name else None
271150

272151
@staticmethod
273152
@fmt_docstring
274-
def delaunay_triples( # noqa: PLR0913
153+
@use_alias(
154+
I="spacing",
155+
J="projection",
156+
R="region",
157+
V="verbose",
158+
b="binary",
159+
d="nodata",
160+
e="find",
161+
f="coltypes",
162+
h="header",
163+
i="incols",
164+
r="registration",
165+
s="skiprows",
166+
w="wrap",
167+
)
168+
@kwargs_to_strings(I="sequence", R="sequence", i="sequence_comma")
169+
def delaunay_triples(
275170
data=None,
276171
x=None,
277172
y=None,
278173
z=None,
174+
*,
279175
output_type="pandas",
280176
outfile=None,
281-
projection=None,
282-
verbose=None,
283-
binary=None,
284-
nodata=None,
285-
find=None,
286-
coltypes=None,
287-
header=None,
288-
incols=None,
289-
skiprows=None,
290-
wrap=None,
291177
**kwargs,
292178
):
293179
"""
@@ -306,6 +192,8 @@ def delaunay_triples( # noqa: PLR0913
306192
307193
Full option list at :gmt-docs:`triangulate.html`
308194
195+
{aliases}
196+
309197
Parameters
310198
----------
311199
x/y/z : np.ndarray
@@ -316,7 +204,7 @@ def delaunay_triples( # noqa: PLR0913
316204
{table-classes}.
317205
{projection}
318206
{region}
319-
outfile : str or bool or None
207+
outfile : str or None
320208
The name of the output ASCII file to store the results of the
321209
histogram equalization in.
322210
output_type : str
@@ -355,26 +243,25 @@ def delaunay_triples( # noqa: PLR0913
355243
"""
356244
output_type = validate_output_table_type(output_type, outfile)
357245

358-
# Return a pandas.DataFrame if ``outfile`` is not set
359246
with GMTTempFile(suffix=".txt") as tmpfile:
360-
if output_type != "file":
361-
outfile = tmpfile.name
362-
return triangulate._triangulate(
363-
data=data,
364-
x=x,
365-
y=y,
366-
z=z,
367-
output_type=output_type,
368-
outfile=outfile,
369-
projection=projection,
370-
verbose=verbose,
371-
binary=binary,
372-
nodata=nodata,
373-
find=find,
374-
coltypes=coltypes,
375-
header=header,
376-
incols=incols,
377-
skiprows=skiprows,
378-
wrap=wrap,
379-
**kwargs,
380-
)
247+
with Session() as lib:
248+
with lib.virtualfile_from_data(
249+
check_kind="vector", data=data, x=x, y=y, z=z, required_z=False
250+
) as vintbl:
251+
if outfile is None:
252+
outfile = tmpfile.name
253+
lib.call_module(
254+
module="triangulate",
255+
args=build_arg_string(kwargs, infile=vintbl, outfile=outfile),
256+
)
257+
258+
if outfile == tmpfile.name:
259+
# if user did not set outfile, return pd.DataFrame
260+
result = pd.read_csv(outfile, sep="\t", header=None)
261+
elif outfile != tmpfile.name:
262+
# return None if outfile set, output in outfile
263+
result = None
264+
265+
if output_type == "numpy":
266+
result = result.to_numpy()
267+
return result

pygmt/tests/test_triangulate.py

-9
Original file line numberDiff line numberDiff line change
@@ -157,12 +157,3 @@ def test_regular_grid_with_outgrid_param(dataframe, expected_grid):
157157
assert grid.gmt.registration == 0 # Gridline registration
158158
assert grid.gmt.gtype == 0 # Cartesian type
159159
xr.testing.assert_allclose(a=grid, b=expected_grid)
160-
161-
162-
def test_regular_grid_invalid_format(dataframe):
163-
"""
164-
Test that triangulate.regular_grid fails with outgrid that is not None or a proper
165-
file name.
166-
"""
167-
with pytest.raises(GMTInvalidInput):
168-
triangulate.regular_grid(data=dataframe, outgrid=True)

0 commit comments

Comments
 (0)