Skip to content

Commit d2cb8b9

Browse files
weiji14seisman
andauthored
Refactor grdtrack to use virtualfile_from_data and improve i/o to pandas.DataFrame (#1189)
Enables `grdtrack` to work with table-like inputs besides pandas.DataFrame. Also, the `outfile` parameter has become optional, and the output data will be loaded as a pandas.DataFrame when `outfile` is unset. Unit tests have been updated accordingly too. * State that outfile is not required anymore, and fix a lint error * Update expected grdtrack outputs to see if the test xpasses Co-authored-by: Dongdong Tian <[email protected]>
1 parent 2081516 commit d2cb8b9

File tree

2 files changed

+18
-22
lines changed

2 files changed

+18
-22
lines changed

pygmt/src/grdtrack.py

+10-17
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,6 @@
88
GMTTempFile,
99
build_arg_string,
1010
data_kind,
11-
dummy_context,
1211
fmt_docstring,
1312
use_alias,
1413
)
@@ -51,8 +50,7 @@ def grdtrack(points, grid, newcolname=None, outfile=None, **kwargs):
5150
sampled values will be placed.
5251
5352
outfile : str
54-
Required if ``points`` is a file. The file name for the output ASCII
55-
file.
53+
The file name for the output ASCII file.
5654
5755
{V}
5856
{f}
@@ -68,21 +66,13 @@ def grdtrack(points, grid, newcolname=None, outfile=None, **kwargs):
6866
- None if ``outfile`` is set (track output will be stored in file set
6967
by ``outfile``)
7068
"""
69+
if data_kind(points) == "matrix" and newcolname is None:
70+
raise GMTInvalidInput("Please pass in a str to 'newcolname'")
7171

7272
with GMTTempFile(suffix=".csv") as tmpfile:
7373
with Session() as lib:
74-
# Store the pandas.DataFrame points table in virtualfile
75-
if data_kind(points) == "matrix":
76-
if newcolname is None:
77-
raise GMTInvalidInput("Please pass in a str to 'newcolname'")
78-
table_context = lib.virtualfile_from_matrix(points.values)
79-
elif data_kind(points) == "file":
80-
if outfile is None:
81-
raise GMTInvalidInput("Please pass in a str to 'outfile'")
82-
table_context = dummy_context(points)
83-
else:
84-
raise GMTInvalidInput(f"Unrecognized data type {type(points)}")
85-
74+
# Choose how data will be passed into the module
75+
table_context = lib.virtualfile_from_data(check_kind="vector", data=points)
8676
# Store the xarray.DataArray grid in virtualfile
8777
grid_context = lib.virtualfile_from_data(check_kind="raster", data=grid)
8878

@@ -100,8 +90,11 @@ def grdtrack(points, grid, newcolname=None, outfile=None, **kwargs):
10090

10191
# Read temporary csv output to a pandas table
10292
if outfile == tmpfile.name: # if user did not set outfile, return pd.DataFrame
103-
column_names = points.columns.to_list() + [newcolname]
104-
result = pd.read_csv(tmpfile.name, sep="\t", names=column_names)
93+
try:
94+
column_names = points.columns.to_list() + [newcolname]
95+
result = pd.read_csv(tmpfile.name, sep="\t", names=column_names)
96+
except AttributeError: # 'str' object has no attribute 'columns'
97+
result = pd.read_csv(tmpfile.name, sep="\t", header=None, comment=">")
10598
elif outfile != tmpfile.name: # return None if outfile set, output in outfile
10699
result = None
107100

pygmt/tests/test_grdtrack.py

+8-5
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@ def test_grdtrack_input_dataframe_and_dataarray(dataarray):
3636
output = grdtrack(points=dataframe, grid=dataarray, newcolname="bathymetry")
3737
assert isinstance(output, pd.DataFrame)
3838
assert output.columns.to_list() == ["longitude", "latitude", "bathymetry"]
39-
npt.assert_allclose(output.iloc[0], [-110.9536, -42.2489, -2797.394987])
39+
npt.assert_allclose(output.iloc[0], [-110.9536, -42.2489, -2974.656296])
4040

4141
return output
4242

@@ -54,7 +54,7 @@ def test_grdtrack_input_csvfile_and_dataarray(dataarray):
5454
assert os.path.exists(path=TEMP_TRACK) # check that outfile exists at path
5555

5656
track = pd.read_csv(TEMP_TRACK, sep="\t", header=None, comment=">")
57-
npt.assert_allclose(track.iloc[0], [-110.9536, -42.2489, -2797.394987])
57+
npt.assert_allclose(track.iloc[0], [-110.9536, -42.2489, -2974.656296])
5858
finally:
5959
os.remove(path=TEMP_TRACK)
6060

@@ -132,11 +132,14 @@ def test_grdtrack_without_newcolname_setting(dataarray):
132132
grdtrack(points=dataframe, grid=dataarray)
133133

134134

135-
def test_grdtrack_without_outfile_setting(dataarray):
135+
def test_grdtrack_without_outfile_setting():
136136
"""
137137
Run grdtrack by not passing in outfile parameter setting.
138138
"""
139139
csvfile = which("@ridge.txt", download="c")
140+
ncfile = which("@earth_relief_01d", download="a")
140141

141-
with pytest.raises(GMTInvalidInput):
142-
grdtrack(points=csvfile, grid=dataarray)
142+
output = grdtrack(points=csvfile, grid=ncfile)
143+
npt.assert_allclose(output.iloc[0], [-32.2971, 37.4118, -1939.748245])
144+
145+
return output

0 commit comments

Comments
 (0)