|
| 1 | +""" |
| 2 | +Alias system to convert PyGMT parameters to GMT options. |
| 3 | +""" |
| 4 | +import inspect |
| 5 | +from collections import defaultdict |
| 6 | +from typing import NamedTuple |
| 7 | + |
| 8 | +from pygmt.helpers import is_nonstr_iter |
| 9 | + |
| 10 | + |
| 11 | +class Alias(NamedTuple): |
| 12 | + """ |
| 13 | + Alias system for mapping a PyGMT parameter to its equivalent GMT option string. |
| 14 | +
|
| 15 | + Attributes |
| 16 | + ---------- |
| 17 | + name : str |
| 18 | + PyGMT parameter name. |
| 19 | + flag : str |
| 20 | + GMT single-letter option flag. |
| 21 | + modifier : str |
| 22 | + GMT option modifier. Can be None. |
| 23 | + separator : str |
| 24 | + Separator to join the iterable argument into a string. |
| 25 | + """ |
| 26 | + |
| 27 | + name: str |
| 28 | + flag: str |
| 29 | + modifier: str |
| 30 | + separator: str |
| 31 | + |
| 32 | + |
| 33 | +def convert_aliases(): |
| 34 | + """ |
| 35 | + Convert PyGMT parameters to GMT options. |
| 36 | +
|
| 37 | + The caller function must have the special variable ``_aliases`` defined. |
| 38 | +
|
| 39 | + Examples |
| 40 | + -------- |
| 41 | + >>> def module_func(**kwargs): |
| 42 | + ... _aliases = [ |
| 43 | + ... Alias("par1", "A", "", ""), |
| 44 | + ... Alias("par2", "B", "", "/"), |
| 45 | + ... Alias("par3", "C", "", ","), |
| 46 | + ... Alias("pard1", "D", "", ""), |
| 47 | + ... Alias("pard2", "D", "+a", ""), |
| 48 | + ... Alias("pard3", "D", "+b", ","), |
| 49 | + ... Alias("pard4", "D", "+c", "/"), |
| 50 | + ... ] |
| 51 | + ... options = convert_aliases() |
| 52 | + ... print(options) |
| 53 | + >>> |
| 54 | + >>> module_func( |
| 55 | + ... par1="value1", |
| 56 | + ... par2=[1, 2, 3, 4], |
| 57 | + ... par3=[0, 1], |
| 58 | + ... pard1="value2", |
| 59 | + ... pard2="value3", |
| 60 | + ... pard3=[1, 2, 3, 4], |
| 61 | + ... pard4=[1, 2, 3, 4], |
| 62 | + ... ) |
| 63 | + {'A': 'value1', 'B': '1/2/3/4', 'C': '0,1', 'D': 'value2+avalue3+b1,2,3,4+c1/2/3/4'} |
| 64 | + """ |
| 65 | + # Get the local namespace of the caller function |
| 66 | + p_locals = inspect.currentframe().f_back.f_locals |
| 67 | + params = p_locals.pop("kwargs", {}) | p_locals |
| 68 | + |
| 69 | + # Define a dict to store GMT option flags and arguments |
| 70 | + kwdict = defaultdict(str) # default value is an empty string |
| 71 | + for alias in p_locals.get("_aliases"): |
| 72 | + value = params.get(alias.name) |
| 73 | + if is_nonstr_iter(value): |
| 74 | + if alias.separator != "": |
| 75 | + value = alias.separator.join(str(item) for item in value) |
| 76 | + else: |
| 77 | + value = "" |
| 78 | + elif value in (None, False): # None or False are skipped |
| 79 | + continue |
| 80 | + elif value is True: # Convert True to an empty string |
| 81 | + value = "" |
| 82 | + kwdict[alias.flag] += f"{alias.modifier}{value}" |
| 83 | + return dict(kwdict) |
0 commit comments