Skip to content

Commit cd536bb

Browse files
committed
New Alias System: Add the AliasSystem class
1 parent f4f3012 commit cd536bb

File tree

1 file changed

+68
-0
lines changed

1 file changed

+68
-0
lines changed

pygmt/alias.py

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
"""
44

55
import dataclasses
6+
from collections import defaultdict
67
from collections.abc import Mapping, Sequence
78
from typing import Any, Literal
89

@@ -195,3 +196,70 @@ def _value(self) -> str | list[str] | None:
195196
size=self.size,
196197
ndim=self.ndim,
197198
)
199+
200+
201+
class AliasSystem:
202+
"""
203+
Alias system for converting long-form PyGMT parameters to GMT short-form options.
204+
205+
This class is initialized with keyword arguments, where each key is a GMT option
206+
flag, and the corresponding value is an ``Alias`` object or a list of ``Alias``
207+
objects.
208+
209+
The class provides the ``kwdict`` attribute, which is a dictionary mapping each GMT
210+
option flag to its current value. The value can be a string or a list of strings.
211+
This keyword dictionary can then be passed to the ``build_arg_list`` function.
212+
213+
Examples
214+
--------
215+
>>> from pygmt.alias import Alias, AliasSystem
216+
>>> from pygmt.helpers import build_arg_list
217+
>>>
218+
>>> def func(
219+
... par0, par1=None, par2=None, frame=False, repeat=None, panel=None, **kwargs
220+
... ):
221+
... alias = AliasSystem(
222+
... A=[
223+
... Alias(par1),
224+
... Alias(par2, prefix="+o", separator="/"),
225+
... ],
226+
... B=Alias(frame),
227+
... D=Alias(repeat),
228+
... c=Alias(panel, separator=","),
229+
... )
230+
... return build_arg_list(alias.kwdict | kwargs)
231+
>>> func(
232+
... "infile",
233+
... par1="mytext",
234+
... par2=(12, 12),
235+
... frame=True,
236+
... repeat=[1, 2, 3],
237+
... panel=(1, 2),
238+
... J="X10c/10c",
239+
... )
240+
['-Amytext+o12/12', '-B', '-D1', '-D2', '-D3', '-JX10c/10c', '-c1,2']
241+
"""
242+
243+
def __init__(self, **kwargs):
244+
"""
245+
Initialize the alias system and create the keyword dictionary that stores the
246+
current parameter values.
247+
"""
248+
# Keyword dictionary with an empty string as default value.
249+
self.kwdict = defaultdict(str)
250+
251+
for option, aliases in kwargs.items():
252+
if not is_nonstr_iter(aliases): # A single alias.
253+
self.kwdict[option] = aliases._value
254+
continue
255+
256+
for alias in aliases: # List of aliases.
257+
match alias._value:
258+
case None:
259+
continue
260+
case str():
261+
self.kwdict[option] += alias._value
262+
case list():
263+
# A repeatable option should have only one alias, so break.
264+
self.kwdict[option] = alias._value
265+
break

0 commit comments

Comments
 (0)