Skip to content
Merged
Show file tree
Hide file tree
Changes from 19 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
182 changes: 181 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 dataclasses
import warnings
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 @@ -131,3 +133,181 @@ def _to_string(
# "prefix" and "mapping" are ignored. We can enable them when needed.
_value = sequence_join(value, separator=separator, size=size, ndim=ndim, name=name)
return f"{prefix}{_value}"


@dataclasses.dataclass
class Alias:
"""
Class for aliasing a PyGMT parameter to a GMT option or a modifier.

Attributes
----------
value
The value of the alias.
name
The name of the parameter to be used in the error message.
prefix
The string to add as a prefix to the returned value.
mapping
A mapping dictionary to map PyGMT's long-form arguments to GMT's short-form.
separator
The separator to use if the value is a sequence.
size
Expected size of the 1-D sequence. It can be either an integer or a sequence of
integers. If an integer, it is the expected size of the 1-D sequence. If it is a
sequence, it is the allowed size of the 1-D sequence.
ndim
The expected maximum number of dimensions of the sequence.

Examples
--------
>>> par = Alias((3.0, 3.0), prefix="+o", separator="/")
>>> par._value
'+o3.0/3.0'

>>> par = Alias("mean", mapping={"mean": "a", "mad": "d", "full": "g"})
>>> par._value
'a'

>>> par = Alias(["xaf", "yaf", "WSen"])
>>> par._value
['xaf', 'yaf', 'WSen']
"""

value: Any
name: str | None = None
prefix: str = ""
mapping: Mapping | None = None
separator: Literal["/", ","] | None = None
size: int | Sequence[int] | None = None
ndim: int = 1

@property
def _value(self) -> str | list[str] | None:
"""
The value of the alias as a string, a sequence of strings or None.
"""
return _to_string(
value=self.value,
name=self.name,
prefix=self.prefix,
mapping=self.mapping,
separator=self.separator,
size=self.size,
ndim=self.ndim,
)


class AliasSystem:
"""
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.

The class provides the ``kwdict`` attribute, which is a dictionary mapping each GMT
option flag to its current value. The value can be a string or a list of strings.
This keyword dictionary can then be passed to the ``build_arg_list`` function.

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
... ):
... alias = 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=","),
... ).update(kwargs)
... return build_arg_list(alias.kwdict)
>>> 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 and create the keyword dictionary that stores the
current parameter values.
"""
# Storing the aliases as a dictionary for easy access.
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'}


# Storing option-value as a keyword dictionary.
self.kwdict = {}

# The value of each key in aliasdict 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.
for option, aliases in self.aliasdict.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:
self.kwdict[option] = "".join(values)
elif aliases._value is not None: # A single Alias object and not None.
self.kwdict[option] = aliases._value

def update(self, kwargs: Mapping[str, Any]):
"""
Update the kwdict 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():
# Long-form parameters exist.
if 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 short_param in self.kwdict:
msg = (
f"Short-form parameter {short_param!r} conflicts with "
"long-form parameters and is not recommended. "
f"{_msg_long}"
)
raise GMTInvalidInput(msg)

# Long-form parameters are not specified.
msg = (
f"Short-form parameter {short_param!r} is not recommended. "
f"{_msg_long}"
)
warnings.warn(msg, category=SyntaxWarning, stacklevel=2)

# Update the kwdict with the short-form parameter anyway.
self.kwdict[short_param] = value
return self
17 changes: 11 additions & 6 deletions pygmt/src/basemap.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,15 @@
basemap - Plot base maps and frames.
"""

from pygmt.alias import Alias, AliasSystem
Copy link
Member Author

Choose a reason for hiding this comment

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

Changes in basemap.py is only meant for proof of concept. I plan to revert the changes in basemap.py and open separate PRs for it.

from pygmt.clib import Session
from pygmt.helpers import build_arg_list, fmt_docstring, kwargs_to_strings, use_alias


@fmt_docstring
@use_alias(
R="region",
J="projection",
Jz="zscale",
JZ="zsize",
B="frame",
L="map_scale",
F="box",
Td="rose",
Expand All @@ -23,8 +21,8 @@
p="perspective",
t="transparency",
)
@kwargs_to_strings(R="sequence", c="sequence_comma", p="sequence")
def basemap(self, **kwargs):
@kwargs_to_strings(c="sequence_comma", p="sequence")
def basemap(self, region=None, projection=None, frame=None, **kwargs):
r"""
Plot base maps and frames.

Expand Down Expand Up @@ -83,5 +81,12 @@ def basemap(self, **kwargs):
{transparency}
"""
self._activate_figure()

alias = AliasSystem(
R=Alias(region, name="region", separator="/", size=[4, 6]),
J=Alias(projection, name="projection"),
B=Alias(frame, name="frame"),
).update(kwargs)
Copy link
Member Author

Choose a reason for hiding this comment

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

Actually, I'm still debating if we should change these lines to:

Suggested change
alias = AliasSystem(
R=Alias(region, name="region", separator="/", size=[4, 6]),
J=Alias(projection, name="projection"),
B=Alias(frame, name="frame"),
).update(kwargs)
kwdict = AliasSystem(
R=Alias(region, name="region", separator="/", size=[4, 6]),
J=Alias(projection, name="projection"),
B=Alias(frame, name="frame"),
).update(kwargs).kwdict

since only alias.kwdict is used below.

Copy link
Member

@weiji14 weiji14 Jul 24, 2025

Choose a reason for hiding this comment

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

I did wonder if we could turn the AliasSystem class into a subclass of collections.UserDict or collections.OrderedDict (or maybe collections.ChainMap?), since it is essentially just holding a dictonary with a custom update method. But then you'll need to reconcile self.aliasdict with self.kwdict.

Copy link
Member Author

Choose a reason for hiding this comment

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

I did wonder if we could turn the AliasSystem class into a subclass of collections.UserDict or collections.OrderedDict (or maybe collections.ChainMap?), since it is essentially just holding a dictonary with a custom update method.

Then we will have codes like

alias = AliasSystem(A=Alias(...), B=Alias(...), ...)
build_arg_list(alias)

or rename alias to kwdict, but both may be confusing.

Copy link
Member

Choose a reason for hiding this comment

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

or rename alias to kwdict, but both may be confusing.

how about aliasdict = AliasSystem(...)?

Copy link
Member Author

@seisman seisman Jul 25, 2025

Choose a reason for hiding this comment

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

aliasdict looks good.

I just tried UserDict and it looks good. Here is a minimal example:

from collections import UserDict
from collections.abc import Sequence
from pygmt.alias import Alias

class AliasSystem(UserDict):

    def __init__(self, **kwargs):
        self.aliasdict = kwargs

        kwdict = {}
        for option, aliases in kwargs.items():
            if isinstance(aliases, Sequence):
                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:
                kwdict[option] = aliases._value
        super().__init__(kwdict)

    def update(self, kwargs):
        print("Updating dict")
        # Add more checks later.
        for short_param, value in kwargs.items():
            self[short_param] = value
        return self

aliasdict = AliasSystem(
    A=Alias("label"),
    B=Alias((0, 10), separator="/"),
    C=[Alias("text"), Alias("TL", prefix="+j")]
).update({"C": "abc"})
print(aliasdict)

The script output is:

Updating dict
Updating dict
{'A': 'label', 'B': '0/10', 'C': 'abc'}

As you can see, it prints Updating dict twice. One is by the super().__init__ call, another by the AliasSystem().update call. Since update is a built-in method of dict/UserDict, overriding it is not a good idea. I guess we need to change the method name from update() to something like merge()/check()?

Copy link
Member Author

Choose a reason for hiding this comment

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

I've updated the AliasSystem class using UserDict in 99845c2.


with Session() as lib:
lib.call_module(module="basemap", args=build_arg_list(kwargs))
lib.call_module(module="basemap", args=build_arg_list(alias.kwdict))
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.
"""
alias = 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="/"),
],
).update(kwargs)
return build_arg_list(alias.kwdict)


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