Skip to content

Commit edf99d2

Browse files
committed
New alias system
1 parent e0c306f commit edf99d2

File tree

3 files changed

+92
-34
lines changed

3 files changed

+92
-34
lines changed

pygmt/alias.py

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
import inspect
2+
from collections import defaultdict
3+
from typing import NamedTuple
4+
5+
from pygmt.helpers import is_nonstr_iter
6+
7+
8+
class Alias(NamedTuple):
9+
name: str
10+
flag: str
11+
modifier: str
12+
separator: str
13+
14+
15+
def sequence_to_str(seq, separator):
16+
return separator.join(str(item) for item in seq)
17+
18+
19+
def convert_aliases():
20+
"""
21+
Convert PyGMT parameters to GMT options.
22+
23+
The caller function must have the special variable ``_aliases`` defined.
24+
"""
25+
# Get the local namespace of the caller function
26+
p_locals = inspect.currentframe().f_back.f_locals
27+
params = p_locals.pop("kwargs", {}) | p_locals
28+
29+
# Define a dict to store GMT option flags and arguments
30+
options = defaultdict(lambda: "")
31+
for alias in p_locals.get("_aliases"):
32+
value = params.get(alias.name)
33+
if value in (None, False): # None or False are skipped
34+
continue
35+
if value is True: # Convert True to an empty string
36+
value = ""
37+
if alias.separator is not None and is_nonstr_iter(value):
38+
value = sequence_to_str(value, alias.separator)
39+
options[alias.flag] += f"{alias.modifier}{value}"
40+
return dict(options)

pygmt/src/info.py

Lines changed: 28 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -2,29 +2,28 @@
22
info - Get information about data tables.
33
"""
44
import numpy as np
5+
from pygmt.alias import Alias, convert_aliases
56
from pygmt.clib import Session
67
from pygmt.helpers import (
78
GMTTempFile,
89
build_arg_string,
910
fmt_docstring,
10-
kwargs_to_strings,
11-
use_alias,
1211
)
1312

1413

1514
@fmt_docstring
16-
@use_alias(
17-
C="per_column",
18-
I="spacing",
19-
T="nearest_multiple",
20-
V="verbose",
21-
a="aspatial",
22-
f="coltypes",
23-
i="incols",
24-
r="registration",
25-
)
26-
@kwargs_to_strings(I="sequence", i="sequence_comma")
27-
def info(data, **kwargs):
15+
def info(
16+
data,
17+
per_column=None,
18+
spacing=None,
19+
nearest_multiple=None,
20+
verbose=None,
21+
aspatial=None,
22+
coltypes=None,
23+
incols=None,
24+
registration=None,
25+
**kwargs,
26+
):
2827
r"""
2928
Get information about data tables.
3029
@@ -43,8 +42,6 @@ def info(data, **kwargs):
4342
4443
Full option list at :gmt-docs:`gmtinfo.html`
4544
46-
{aliases}
47-
4845
Parameters
4946
----------
5047
data : str, {table-like}
@@ -79,17 +76,30 @@ def info(data, **kwargs):
7976
- :class:`numpy.ndarray` if either of the above parameters are used.
8077
- str if none of the above parameters are used.
8178
"""
79+
_aliases = [
80+
Alias("per_column", "C", "", ""),
81+
Alias("spacing", "I", "", "/"),
82+
Alias("nearest_multiple", "T", "", ""),
83+
Alias("verbose", "V", "", ""),
84+
Alias("aspatial", "a", "", ""),
85+
Alias("coltypes", "f", "", ""),
86+
Alias("incols", "i", "", ","),
87+
Alias("registration", "r", "", ""),
88+
]
89+
90+
options = convert_aliases()
91+
8292
with Session() as lib:
8393
file_context = lib.virtualfile_from_data(check_kind="vector", data=data)
8494
with GMTTempFile() as tmpfile:
8595
with file_context as fname:
8696
lib.call_module(
8797
module="info",
88-
args=build_arg_string(kwargs, infile=fname, outfile=tmpfile.name),
98+
args=build_arg_string(options, infile=fname, outfile=tmpfile.name),
8999
)
90100
result = tmpfile.read()
91101

92-
if any(kwargs.get(arg) is not None for arg in ["C", "I", "T"]):
102+
if any(arg is not None for arg in (per_column, spacing, nearest_multiple)):
93103
# Converts certain output types into a numpy array
94104
# instead of a raw string that is less useful.
95105
if result.startswith(("-R", "-T")): # e.g. -R0/1/2/3 or -T0/9/1

pygmt/src/timestamp.py

Lines changed: 24 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -7,8 +7,9 @@
77
from typing import TYPE_CHECKING
88

99
from packaging.version import Version
10+
from pygmt.alias import Alias, convert_aliases
1011
from pygmt.clib import Session, __gmt_version__
11-
from pygmt.helpers import build_arg_string, kwargs_to_strings
12+
from pygmt.helpers import build_arg_string, is_nonstr_iter
1213

1314
if TYPE_CHECKING:
1415
from collections.abc import Sequence
@@ -17,7 +18,6 @@
1718
__doctest_skip__ = ["timestamp"]
1819

1920

20-
@kwargs_to_strings(offset="sequence")
2121
def timestamp(
2222
self,
2323
text: str | None = None,
@@ -82,17 +82,22 @@ def timestamp(
8282
"""
8383
self._preprocess()
8484

85-
# Build the options passed to the "plot" module
86-
kwdict: dict = {"T": True, "U": ""}
87-
if label is not None:
88-
kwdict["U"] += f"{label}"
89-
kwdict["U"] += f"+j{justification}"
90-
91-
if Version(__gmt_version__) <= Version("6.4.0") and "/" not in str(offset):
92-
# Giving a single offset doesn't work in GMT <= 6.4.0.
93-
# See https://github.com/GenericMappingTools/gmt/issues/7107.
94-
offset = f"{offset}/{offset}"
95-
kwdict["U"] += f"+o{offset}"
85+
# Aliases from PyGMT parameters to GMT options
86+
_aliases = [
87+
Alias("label", "U", "", ""),
88+
Alias("justification", "U", "+j", ""),
89+
Alias("offset", "U", "+o", "/"),
90+
Alias("text", "U", "+t", ""),
91+
]
92+
93+
# Giving a single offset doesn't work in GMT <= 6.4.0.
94+
# See https://github.com/GenericMappingTools/gmt/issues/7107.
95+
if (
96+
Version(__gmt_version__) <= Version("6.4.0")
97+
and not is_nonstr_iter(offset)
98+
and "/" not in str(offset)
99+
):
100+
offset = (offset, offset)
96101

97102
# The +t modifier was added in GMT 6.5.0.
98103
# See https://github.com/GenericMappingTools/gmt/pull/7127.
@@ -106,13 +111,16 @@ def timestamp(
106111
if Version(__gmt_version__) <= Version("6.4.0"):
107112
# workaround for GMT<=6.4.0 by overriding the 'timefmt' parameter
108113
timefmt = text[:64]
109-
else:
110-
kwdict["U"] += f"+t{text}"
114+
text = None # reset 'text' to None
115+
116+
# Build the options passed to the "plot" module
117+
options = convert_aliases()
118+
options["T"] = True
111119

112120
with Session() as lib:
113121
lib.call_module(
114122
module="plot",
115123
args=build_arg_string(
116-
kwdict, confdict={"FONT_LOGO": font, "FORMAT_TIME_STAMP": timefmt}
124+
options, confdict={"FONT_LOGO": font, "FORMAT_TIME_STAMP": timefmt}
117125
),
118126
)

0 commit comments

Comments
 (0)