Skip to content

Commit a1924e8

Browse files
authored
Refractor build_arg_string to also deal with infile and outfile (#1837)
1 parent 4cfe813 commit a1924e8

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

44 files changed

+111
-111
lines changed

pygmt/helpers/utils.py

Lines changed: 33 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -119,12 +119,12 @@ def dummy_context(arg):
119119
yield arg
120120

121121

122-
def build_arg_string(kwargs):
122+
def build_arg_string(kwdict, infile=None, outfile=None):
123123
r"""
124-
Transform keyword arguments into a GMT argument string.
124+
Convert a dict and optional input/output files into a GMT argument string.
125125
126-
Make sure all arguments have been previously converted to a string
127-
representation using the ``kwargs_to_strings`` decorator. The only
126+
Make sure all values in ``kwdict`` have been previously converted to a
127+
string representation using the ``kwargs_to_strings`` decorator. The only
128128
exceptions are True, False and None.
129129
130130
Any lists or tuples left will be interpreted as multiple entries for the
@@ -138,14 +138,19 @@ def build_arg_string(kwargs):
138138
139139
Parameters
140140
----------
141-
kwargs : dict
142-
Parsed keyword arguments.
141+
kwdict : dict
142+
A dict containing parsed keyword arguments.
143+
infile : str or pathlib.Path
144+
The input file.
145+
outfile : str or pathlib.Path
146+
The output file.
143147
144148
Returns
145149
-------
146150
args : str
147151
The space-delimited argument string with '-' inserted before each
148-
keyword. The arguments are sorted alphabetically.
152+
keyword. The arguments are sorted alphabetically, with optional input
153+
file at the begining and optioanl output file at the end.
149154
150155
Examples
151156
--------
@@ -191,29 +196,42 @@ def build_arg_string(kwargs):
191196
... )
192197
... )
193198
-BWSne+tBlank\040Space -Baf -F+t"Empty\040\040Spaces" -l'Void\040Space'
199+
>>> print(
200+
... build_arg_string(
201+
... dict(A="0", B=True, C="rainbow"),
202+
... infile="input.txt",
203+
... outfile="output.txt",
204+
... )
205+
... )
206+
input.txt -A0 -B -Crainbow ->output.txt
194207
"""
195208
gmt_args = []
196209

197-
for key in kwargs:
210+
for key in kwdict:
198211
if len(key) > 2: # raise an exception for unrecognized options
199212
raise GMTInvalidInput(f"Unrecognized parameter '{key}'.")
200-
if kwargs[key] is None or kwargs[key] is False:
213+
if kwdict[key] is None or kwdict[key] is False:
201214
pass # Exclude arguments that are None and False
202-
elif is_nonstr_iter(kwargs[key]):
203-
for value in kwargs[key]:
215+
elif is_nonstr_iter(kwdict[key]):
216+
for value in kwdict[key]:
204217
_value = str(value).replace(" ", r"\040")
205218
gmt_args.append(rf"-{key}{_value}")
206-
elif kwargs[key] is True:
219+
elif kwdict[key] is True:
207220
gmt_args.append(f"-{key}")
208221
else:
209222
if key != "J": # non-projection parameters
210-
_value = str(kwargs[key]).replace(" ", r"\040")
223+
_value = str(kwdict[key]).replace(" ", r"\040")
211224
else:
212225
# special handling if key == "J" (projection)
213226
# remove any spaces in PROJ4 string
214-
_value = str(kwargs[key]).replace(" ", "")
227+
_value = str(kwdict[key]).replace(" ", "")
215228
gmt_args.append(rf"-{key}{_value}")
216-
return " ".join(sorted(gmt_args))
229+
gmt_args = sorted(gmt_args)
230+
if infile:
231+
gmt_args = [str(infile)] + gmt_args
232+
if outfile:
233+
gmt_args.append("->" + str(outfile))
234+
return " ".join(gmt_args)
217235

218236

219237
def is_nonstr_iter(value):

pygmt/src/blockm.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -51,8 +51,10 @@ def _blockm(block_method, data, x, y, z, outfile, **kwargs):
5151
with table_context as infile:
5252
if outfile is None:
5353
outfile = tmpfile.name
54-
arg_str = " ".join([infile, build_arg_string(kwargs), "->" + outfile])
55-
lib.call_module(module=block_method, args=arg_str)
54+
lib.call_module(
55+
module=block_method,
56+
args=build_arg_string(kwargs, infile=infile, outfile=outfile),
57+
)
5658

5759
# Read temporary csv output to a pandas table
5860
if outfile == tmpfile.name: # if user did not set outfile, return pd.DataFrame

pygmt/src/contour.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -132,5 +132,4 @@ def contour(self, data=None, x=None, y=None, z=None, **kwargs):
132132
check_kind="vector", data=data, x=x, y=y, z=z, required_z=True
133133
)
134134
with file_context as fname:
135-
arg_str = " ".join([fname, build_arg_string(kwargs)])
136-
lib.call_module("contour", arg_str)
135+
lib.call_module("contour", build_arg_string(kwargs, infile=fname))

pygmt/src/grd2cpt.py

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -166,12 +166,10 @@ def grd2cpt(grid, **kwargs):
166166
file_context = lib.virtualfile_from_data(check_kind="raster", data=grid)
167167
with file_context as infile:
168168
if "H" not in kwargs: # if no output is set
169-
arg_str = " ".join([infile, build_arg_string(kwargs)])
169+
arg_str = build_arg_string(kwargs, infile=infile)
170170
if "H" in kwargs: # if output is set
171-
outfile = kwargs.pop("H")
171+
outfile, kwargs["H"] = kwargs["H"], True
172172
if not outfile or not isinstance(outfile, str):
173173
raise GMTInvalidInput("'output' should be a proper file name.")
174-
arg_str = " ".join(
175-
[infile, build_arg_string(kwargs), f"-H > {outfile}"]
176-
)
174+
arg_str = build_arg_string(kwargs, infile=infile, outfile=outfile)
177175
lib.call_module("grd2cpt", arg_str)

pygmt/src/grd2xyz.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -178,8 +178,9 @@ def grd2xyz(grid, output_type="pandas", outfile=None, **kwargs):
178178
with file_context as infile:
179179
if outfile is None:
180180
outfile = tmpfile.name
181-
arg_str = " ".join([infile, build_arg_string(kwargs), "->" + outfile])
182-
lib.call_module("grd2xyz", arg_str)
181+
lib.call_module(
182+
"grd2xyz", build_arg_string(kwargs, infile=infile, outfile=outfile)
183+
)
183184

184185
# Read temporary csv output to a pandas table
185186
if outfile == tmpfile.name: # if user did not set outfile, return pd.DataFrame

pygmt/src/grdclip.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -107,7 +107,6 @@ def grdclip(grid, **kwargs):
107107
if "G" not in kwargs: # if outgrid is unset, output to tempfile
108108
kwargs.update({"G": tmpfile.name})
109109
outgrid = kwargs["G"]
110-
arg_str = " ".join([infile, build_arg_string(kwargs)])
111-
lib.call_module("grdclip", arg_str)
110+
lib.call_module("grdclip", build_arg_string(kwargs, infile=infile))
112111

113112
return load_dataarray(outgrid) if outgrid == tmpfile.name else None

pygmt/src/grdcontour.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -100,5 +100,4 @@ def grdcontour(self, grid, **kwargs):
100100
with Session() as lib:
101101
file_context = lib.virtualfile_from_data(check_kind="raster", data=grid)
102102
with file_context as fname:
103-
arg_str = " ".join([fname, build_arg_string(kwargs)])
104-
lib.call_module("grdcontour", arg_str)
103+
lib.call_module("grdcontour", build_arg_string(kwargs, infile=fname))

pygmt/src/grdcut.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -109,7 +109,6 @@ def grdcut(grid, **kwargs):
109109
if "G" not in kwargs: # if outgrid is unset, output to tempfile
110110
kwargs.update({"G": tmpfile.name})
111111
outgrid = kwargs["G"]
112-
arg_str = " ".join([infile, build_arg_string(kwargs)])
113-
lib.call_module("grdcut", arg_str)
112+
lib.call_module("grdcut", build_arg_string(kwargs, infile=infile))
114113

115114
return load_dataarray(outgrid) if outgrid == tmpfile.name else None

pygmt/src/grdfill.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -72,7 +72,6 @@ def grdfill(grid, **kwargs):
7272
if "G" not in kwargs: # if outgrid is unset, output to tempfile
7373
kwargs.update({"G": tmpfile.name})
7474
outgrid = kwargs["G"]
75-
arg_str = " ".join([infile, build_arg_string(kwargs)])
76-
lib.call_module("grdfill", arg_str)
75+
lib.call_module("grdfill", build_arg_string(kwargs, infile=infile))
7776

7877
return load_dataarray(outgrid) if outgrid == tmpfile.name else None

pygmt/src/grdfilter.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -148,7 +148,6 @@ def grdfilter(grid, **kwargs):
148148
if "G" not in kwargs: # if outgrid is unset, output to tempfile
149149
kwargs.update({"G": tmpfile.name})
150150
outgrid = kwargs["G"]
151-
arg_str = " ".join([infile, build_arg_string(kwargs)])
152-
lib.call_module("grdfilter", arg_str)
151+
lib.call_module("grdfilter", build_arg_string(kwargs, infile=infile))
153152

154153
return load_dataarray(outgrid) if outgrid == tmpfile.name else None

0 commit comments

Comments
 (0)