Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
30 commits
Select commit Hold shift + click to select a range
654261c
New Alias System: Add the Alias class
seisman Jul 10, 2025
7f43055
Fix
seisman Jul 16, 2025
a42c2d8
Merge branch 'main' into AliasSystem/alias
seisman Jul 16, 2025
bc0401e
Merge branch 'main' into AliasSystem/alias
seisman Jul 21, 2025
fae3ab0
Put name after value
seisman Jul 21, 2025
f4f3012
Merge branch 'main' into AliasSystem/alias
seisman Jul 21, 2025
cd536bb
New Alias System: Add the AliasSystem class
seisman Jul 14, 2025
b0f0d14
Improve the alias system to support single-letter option flags
seisman Jul 14, 2025
b244f74
Always pass parameter name
seisman Jul 21, 2025
ddcc7b8
Simplify the alias system
seisman Jul 21, 2025
7ff71d1
Fix static tying
seisman Jul 21, 2025
c1fdfa5
Improve tests
seisman Jul 21, 2025
571d0dd
Improve comments
seisman Jul 22, 2025
d0ebbcb
Merge branch 'main' into AliasSystem/alias
seisman Jul 23, 2025
408199c
Merge branch 'AliasSystem/alias' into AliasSystem/aliassystem
seisman Jul 23, 2025
76f7c6e
Improve error message for recommended long-form parameters
seisman Jul 24, 2025
657f053
Minor fix in tests
seisman Jul 24, 2025
324b973
Simplify the error message handling
seisman Jul 24, 2025
a375e69
Improve tests
seisman Jul 24, 2025
99845c2
Implement AliasSystem as a subclass of UserDict
seisman Jul 25, 2025
5259b1e
Simplify the logic of the AliasSystem.merge() method
seisman Jul 25, 2025
92e0a08
Revert changes in basemap.py
seisman Jul 27, 2025
5a9817d
Merge branch 'main' into AliasSystem/alias
seisman Jul 28, 2025
195acfa
Merge branch 'AliasSystem/alias' into AliasSystem/aliassystem
seisman Jul 28, 2025
4cdef8b
Avoid using dataclass
seisman Jul 28, 2025
e57954d
No need to store properties that won't be used
seisman Jul 28, 2025
4ce43d1
Merge branch 'AliasSystem/alias' into AliasSystem/aliassystem
seisman Jul 28, 2025
209fda1
Merge branch 'AliasSystem/alias' into AliasSystem/aliassystem
seisman Jul 29, 2025
8d2e1be
Merge branch 'main' into AliasSystem/aliassystem
seisman Jul 29, 2025
7e3fb66
Merge remote-tracking branch 'origin/AliasSystem/aliassystem' into Al…
seisman Jul 29, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
121 changes: 120 additions & 1 deletion pygmt/alias.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,12 @@
The PyGMT alias system to convert PyGMT's long-form arguments to GMT's short-form.
"""

import warnings
from collections import UserDict
from collections.abc import Mapping, Sequence
from typing import Any, Literal

from pygmt.exceptions import GMTValueError
from pygmt.exceptions import GMTInvalidInput, GMTValueError
from pygmt.helpers.utils import is_nonstr_iter, sequence_join


Expand Down Expand Up @@ -192,3 +194,120 @@ def __init__(
size=size,
ndim=ndim,
)


class AliasSystem(UserDict):
"""
Alias system for mapping PyGMT's long-form parameters to GMT's short-form options.

This class is initialized with keyword arguments, where each key is a GMT option
flag, and the corresponding value is an ``Alias`` object or a list of ``Alias``
objects.

This class inherits from ``UserDict``, which allows it to behave like a dictionary
and can be passed to the ``build_arg_list`` function. It also provides the ``merge``
method to update the alias dictionary with additional keyword arguments.

Examples
--------
>>> from pygmt.alias import Alias, AliasSystem
>>> from pygmt.helpers import build_arg_list
>>>
>>> def func(
... par0, par1=None, par2=None, frame=False, repeat=None, panel=None, **kwargs
... ):
... aliasdict = AliasSystem(
... A=[
... Alias(par1, name="par1"),
... Alias(par2, name="par2", prefix="+o", separator="/"),
... ],
... B=Alias(frame, name="frame"),
... D=Alias(repeat, name="repeat"),
... c=Alias(panel, name="panel", separator=","),
... ).merge(kwargs)
... return build_arg_list(aliasdict)
>>> func(
... "infile",
... par1="mytext",
... par2=(12, 12),
... frame=True,
... repeat=[1, 2, 3],
... panel=(1, 2),
... J="X10c/10c",
... )
['-Amytext+o12/12', '-B', '-D1', '-D2', '-D3', '-JX10c/10c', '-c1,2']
"""

def __init__(self, **kwargs):
"""
Initialize the alias system as a dictionary with current parameter values.
"""
# Store the aliases in a dictionary, to be used in the merge() method.
self.aliasdict = kwargs
Copy link
Member

@weiji14 weiji14 Jul 25, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should't this be overriding the UserDict's data attribute? https://docs.python.org/3/library/collections.html#collections.UserDict.data

Suggested change
self.aliasdict = kwargs
self.data = kwargs

Then I suppose you can use update as method name? Unless it's still not advised to override that.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

data is the real dictionary that stores the contents of the UserDict class, so changing the UserDict object also affects data.

from collections import UserDict

alias = UserDict(A="label", B="text")
print(alias.data)
print(alias)

alias.data = {"C": True}
print(alias.data)
print(alias)

alias.update({"D": "good"})
print(alias.data)
print(alias)

The output is:

{'A': 'label', 'B': 'text'}
{'A': 'label', 'B': 'text'}
{'C': True}
{'C': True}
{'C': True, 'D': 'good'}
{'C': True, 'D': 'good'}


# The value of each key in kwargs is an Alias object or a sequence of Alias
# objects. If it is a single Alias object, we will use its _value property. If
# it is a sequence of Alias objects, we will concatenate their _value properties
# into a single string.
#
# Note that alias._value is converted by the _to_string method and can only be
# None, string or sequence of strings.
# - None means the parameter is not specified.
# - Sequence of strings means this is a repeatable option, so it can only have
# one long-form parameter.
kwdict = {}
for option, aliases in kwargs.items():
if isinstance(aliases, Sequence): # A sequence of Alias objects.
values = [alias._value for alias in aliases if alias._value is not None]
if values:
kwdict[option] = "".join(values)
elif aliases._value is not None: # A single Alias object and not None.
kwdict[option] = aliases._value
super().__init__(kwdict)

def merge(self, kwargs: Mapping[str, Any]):
"""
Update the dictionary with additional keyword arguments.

This method is necessary to allow users to use the single-letter parameters for
option flags that are not aliased.
"""
# Loop over short-form parameters passed via kwargs.
for short_param, value in kwargs.items():
# Check if long-form parameters exist and given.
long_param_exists = short_param in self.aliasdict
long_param_given = short_param in self

# Update the dictionary with the short-form parameter anyway.
self[short_param] = value

# Long-form parameters do not exist.
if not long_param_exists:
continue

# Long-form parameters exist.
aliases = self.aliasdict.get(short_param)
if not isinstance(aliases, Sequence): # Single Alias object.
_msg_long = f"Use long-form parameter {aliases.name!r} instead."
else: # Sequence of Alias objects.
_params = [f"{v.name!r}" for v in aliases if not v.prefix]
_modifiers = [f"{v.name!r} ({v.prefix})" for v in aliases if v.prefix]
_msg_long = (
f"Use long-form parameters {', '.join(_params)}, "
f"with optional parameters {', '.join(_modifiers)} instead."
)

# Long-form parameters are already specified.
if long_param_given:
msg = (
f"Short-form parameter {short_param!r} conflicts with long-form "
f"parameters and is not recommended. {_msg_long}"
)
raise GMTInvalidInput(msg)

# Long-form parameters are not specified.
msg = (
f"Short-form parameter {short_param!r} is not recommended. {_msg_long}"
)
warnings.warn(msg, category=SyntaxWarning, stacklevel=2)
return self
97 changes: 97 additions & 0 deletions pygmt/tests/test_alias_system.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
"""
Tests for the alias system.
"""

import pytest
from pygmt.alias import Alias, AliasSystem
from pygmt.exceptions import GMTInvalidInput
from pygmt.helpers import build_arg_list


def func(
projection=None,
region=None,
frame=None,
label=None,
text=None,
offset=None,
**kwargs,
):
"""
A simple function to test the alias system.
"""
aliasdict = AliasSystem(
J=Alias(projection, name="projection"),
R=Alias(region, name="region", separator="/", size=[4, 6]),
B=Alias(frame, name="frame"),
U=[
Alias(label, name="label"),
Alias(text, name="text", prefix="+t"),
Alias(offset, name="offset", prefix="+o", separator="/"),
],
).merge(kwargs)
return build_arg_list(aliasdict)


def test_alias_system_long_form():
"""
Test that the alias system works with long-form parameters.
"""
# One parameter
assert func(projection="X10c") == ["-JX10c"]
# Multiple parameters.
assert func(projection="H10c", region=[0, 10, 0, 20]) == ["-JH10c", "-R0/10/0/20"]
# Repeatable parameters.
assert func(frame=["WSen", "xaf", "yaf"]) == ["-BWSen", "-Bxaf", "-Byaf"]
# Multiple long-form parameters.
assert func(label="abcd", text="efg", offset=(12, 12)) == ["-Uabcd+tefg+o12/12"]
assert func(
projection="H10c",
region=[0, 10, 0, 20],
label="abcd",
text="efg",
offset=(12, 12),
frame=["WSen", "xaf", "yaf"],
) == ["-BWSen", "-Bxaf", "-Byaf", "-JH10c", "-R0/10/0/20", "-Uabcd+tefg+o12/12"]


def test_alias_system_one_alias_short_form():
"""
Test that the alias system works when short-form parameters coexist.
"""
# Long-form does not exist.
assert func(A="abc") == ["-Aabc"]

# Long-form exists but is not given, and short-form is given.
with pytest.warns(
SyntaxWarning,
match="Short-form parameter 'J' is not recommended. Use long-form parameter 'projection' instead.",
):
assert func(J="X10c") == ["-JX10c"]

# Coexistence of long-form and short-form parameters.
with pytest.raises(
GMTInvalidInput,
match="Short-form parameter 'J' conflicts with long-form parameters and is not recommended. Use long-form parameter 'projection' instead.",
):
func(projection="X10c", J="H10c")


def test_alias_system_multiple_aliases_short_form():
"""
Test that the alias system works with multiple aliases when short-form parameters
are used.
"""
_msg_long = r"Use long-form parameters 'label', with optional parameters 'text' \(\+t\), 'offset' \(\+o\) instead."
# Long-form exists but is not given, and short-form is given.
msg = rf"Short-form parameter 'U' is not recommended. {_msg_long}"
with pytest.warns(SyntaxWarning, match=msg):
assert func(U="abcd+tefg") == ["-Uabcd+tefg"]

# Coexistence of long-form and short-form parameters.
msg = rf"Short-form parameter 'U' conflicts with long-form parameters and is not recommended. {_msg_long}"
with pytest.raises(GMTInvalidInput, match=msg):
func(label="abcd", U="efg")

with pytest.raises(GMTInvalidInput, match=msg):
func(text="efg", U="efg")
Loading