From 6cc6254e52809478ccc349521e2b6af33d773382 Mon Sep 17 00:00:00 2001 From: Peter Corke Date: Tue, 24 Nov 2026 06:20:29 +1000 Subject: [PATCH] feat(base): add parse_fmt to turn a MATLAB-style format string into options Parse strings such as 'r--', 'go' or 'C2:' into color, marker and linestyle keys, with only the parts the string sets, so the result can be merged over defaults. Follows the rules of Matplotlib's plot(): a marker with no linestyle means no line. Tested against Matplotlib's own parser. Co-Authored-By: Claude Sonnet 5.5 --- docs/source/func_2d_graphics.rst | 2 +- spatialmath/base/__init__.py | 2 + spatialmath/base/graphics.py | 112 +++++++++++++++++ tests/base/test_parse_fmt.py | 205 +++++++++++++++++++++++++++++++ 4 files changed, 320 insertions(+), 1 deletion(-) create mode 100644 tests/base/test_parse_fmt.py diff --git a/docs/source/func_2d_graphics.rst b/docs/source/func_2d_graphics.rst index ecc20d73..467d0e1e 100644 --- a/docs/source/func_2d_graphics.rst +++ b/docs/source/func_2d_graphics.rst @@ -4,4 +4,4 @@ 2d graphical primitives which build on Matplotlib. .. automodule:: spatialmath.base.graphics - :members: plot_point, plot_text, plot_homline, plot_box, plot_arrow, plot_circle, plot_ellipse, plot_polygon, plotvol2 + :members: parse_fmt, plot_point, plot_text, plot_homline, plot_box, plot_arrow, plot_circle, plot_ellipse, plot_polygon, plotvol2 diff --git a/spatialmath/base/__init__.py b/spatialmath/base/__init__.py index 02489283..b1a0f6f4 100644 --- a/spatialmath/base/__init__.py +++ b/spatialmath/base/__init__.py @@ -24,6 +24,7 @@ _LAZY_ATTRS = { "Animate": "animate", "Animate2": "animate", + "parse_fmt": "graphics", "plot_text": "graphics", "plot_point": "graphics", "plot_homline": "graphics", @@ -374,6 +375,7 @@ def __getattr__(name): "plotvol2", "plotvol3", "plot_point", + "parse_fmt", "plot_text", "plot_box", "plot_polygon", diff --git a/spatialmath/base/graphics.py b/spatialmath/base/graphics.py index 06e6ce85..00098e8a 100644 --- a/spatialmath/base/graphics.py +++ b/spatialmath/base/graphics.py @@ -1,4 +1,5 @@ import math +import re from itertools import product import warnings import numpy as np @@ -22,6 +23,117 @@ """ +_FMT_LINESTYLES2 = ("--", "-.") +_FMT_LINESTYLES1 = ("-", ":") +_FMT_MARKERS = ".,ov^<>1234sp*hH+xDd|_PX8" +_FMT_COLORS = "bgrcmykw" + + +def parse_fmt(fmt: str | tuple[str] | list[str] | None) -> dict[str, str]: + """ + Parse a MATLAB-style format string into Matplotlib options + + :param fmt: a format string such as ``"r--"``, ``"ko"`` or ``"C2:"``, or a + tuple or list whose first element is one, or None + :type fmt: str, tuple or list of str, or None + :raises ValueError: if the string is not a valid format string + :return: the options the string sets, as ``color``, ``marker`` and + ``linestyle`` keys + :rtype: dict + + The string is a color, a marker and a line style in any order, and each is + optional: + + - color: one of ``b g r c m y k w``, a cycle color such as ``C0``, or the whole + string can be any Matplotlib color, such as ``"red"``, ``"0.5"`` or ``"#ff8000"`` + - marker: one of ``. , o v ^ < > 1 2 3 4 8 s p P * h H + x X D d | _`` + - line style: one of ``-``, ``--``, ``-.`` or ``:`` + + The result holds only what the string sets, so it can be merged over a dict of + defaults without wiping them out:: + + >>> parse_fmt("r--") + {'color': 'r', 'linestyle': '--'} + >>> parse_fmt("--") + {'linestyle': '--'} + >>> parse_fmt("") + {} + + As in Matplotlib, a marker with no line style means markers only, so + ``linestyle`` is ``"None"``:: + + >>> parse_fmt("go") + {'color': 'g', 'marker': 'o', 'linestyle': 'None'} + + This is the same parsing that ``plot`` applies to its ``fmt`` argument, except + that a color, marker or line style that is not in the string is left out, and + is not set to a default. + + .. note:: The characters accepted are the same as those of ``plot``, but not + the unusual ones: a space, ``"None"``, or the numbers that Matplotlib + accepts as markers. + """ + if fmt is None: + return {} + if isinstance(fmt, (tuple, list)): + if len(fmt) == 0: + return {} + fmt = fmt[0] + if not isinstance(fmt, str): + raise ValueError(f"format must be a string, got {type(fmt).__name__}") + + res: dict[str, str] = {} + if fmt == "": + return res + + # the whole string is a color, such as "red" or "#ff8000"; "0" and "1" are + # a gray level to colors.is_color_like, but are a marker ("1" is a tri_down) + if fmt not in ("0", "1") and colors.is_color_like(fmt): + return {"color": fmt} + + def bad(why: str) -> ValueError: + return ValueError(f"{fmt!r} is not a valid format string ({why})") + + i = 0 + while i < len(fmt): + c = fmt[i] + if fmt[i : i + 2] in _FMT_LINESTYLES2: + if "linestyle" in res: + raise bad("two linestyle symbols") + res["linestyle"] = fmt[i : i + 2] + i += 2 + elif c in _FMT_LINESTYLES1: + if "linestyle" in res: + raise bad("two linestyle symbols") + res["linestyle"] = c + i += 1 + elif c in _FMT_MARKERS: + if "marker" in res: + raise bad("two marker symbols") + res["marker"] = c + i += 1 + elif c in _FMT_COLORS: + if "color" in res: + raise bad("two color symbols") + res["color"] = c + i += 1 + elif c == "C": + m = re.match(r"C\d+", fmt[i:]) + if m is None: + raise bad("'C' must be followed by a number") + if "color" in res: + raise bad("two color symbols") + res["color"] = m[0] + i += len(m[0]) + else: + raise bad(f"unrecognized character {c!r}") + + # as for plot(): a marker without a line style means no line + if "marker" in res and "linestyle" not in res: + res["linestyle"] = "None" + return res + + try: import matplotlib.pyplot as plt from matplotlib.patches import Circle diff --git a/tests/base/test_parse_fmt.py b/tests/base/test_parse_fmt.py new file mode 100644 index 00000000..c000517e --- /dev/null +++ b/tests/base/test_parse_fmt.py @@ -0,0 +1,205 @@ +"""Tests of parse_fmt, which is checked against what Matplotlib's plot() makes of +the same string.""" + +import itertools +import re + +import matplotlib as mpl +import matplotlib.colors as mcolors +import matplotlib.pyplot as plt +import pytest +from matplotlib.axes import _base + +from spatialmath.base import parse_fmt + +COLORS = ["b", "g", "r", "c", "m", "y", "k", "w", "C0", "C3", "C12"] +MARKERS = list(".,ov^<>1234sp*hH+xDd|_PX8") +LINESTYLES = ["-", "--", "-.", ":"] + + +def matplotlib_says(fmt): + """What plot() makes of fmt: (linestyle, marker, color or None).""" + linestyle, marker, color = _base._process_plot_format(fmt) + # a string that is only a color comes back with no marker or linestyle at all + if marker is None: + marker = "None" + if linestyle is None: + linestyle = mpl.rcParams["lines.linestyle"] + return linestyle, marker, color + + +def n_colors(fmt): + """Number of color symbols in fmt, a letter or a cycle color like C2.""" + return len(re.findall(r"C\d+|[bgrcmykw]", fmt)) + + +def same_as_matplotlib(fmt): + """Check parse_fmt against Matplotlib, filling in what plot() fills in.""" + ours = parse_fmt(fmt) + linestyle, marker, color = matplotlib_says(fmt) + + # plot() takes a missing marker as none, and a missing linestyle as the rc + # default, unless there is a marker, when it is none + assert ours.get("marker", "None") == marker, fmt + assert ours.get("linestyle", mpl.rcParams["lines.linestyle"]) == linestyle, fmt + if color is None: + assert "color" not in ours, fmt + else: + assert mcolors.to_rgba(ours["color"]) == mcolors.to_rgba(color), fmt + assert set(ours) <= {"color", "marker", "linestyle"} + + +def test_every_single_symbol(): + for sym in COLORS + MARKERS + LINESTYLES: + same_as_matplotlib(sym) + + +def test_every_pair_in_either_order(): + symbols = COLORS + MARKERS + LINESTYLES + n = 0 + for a, b in itertools.product(symbols, repeat=2): + fmt = a + b + if n_colors(fmt) > 1: + continue # see test_two_colors_are_refused + try: + matplotlib_says(fmt) + except ValueError: + with pytest.raises(ValueError): + parse_fmt(fmt) + else: + same_as_matplotlib(fmt) + n += 1 + assert n > 800 + + +def test_every_color_marker_linestyle_in_every_order(): + n = 0 + for color, marker, ls in itertools.product(COLORS, MARKERS, LINESTYLES): + for order in itertools.permutations([color, marker, ls]): + fmt = "".join(order) + if n_colors(fmt) > 1: + continue + try: + matplotlib_says(fmt) + except ValueError: + # such as a marker "1" after "C", which is the cycle color "C1" + with pytest.raises(ValueError): + parse_fmt(fmt) + else: + same_as_matplotlib(fmt) + n += 1 + assert n > 5000 + + +@pytest.mark.parametrize( + "fmt", + ["red", "0.5", "0.0", "#ff8000", "#f80", "tab:blue", "C4", "xkcd:sky blue", "gray"], +) +def test_whole_string_colors(fmt): + same_as_matplotlib(fmt) + assert parse_fmt(fmt) == {"color": fmt} + + +def test_one_is_a_marker_not_a_gray_level(): + # "1" is a tri_down marker, not the gray level 1 + same_as_matplotlib("1") + assert parse_fmt("1") == {"marker": "1", "linestyle": "None"} + + +def test_zero_is_refused(): + # "0" could be black, but Matplotlib refuses it for consistency with "1" + with pytest.raises(ValueError): + matplotlib_says("0") + with pytest.raises(ValueError): + parse_fmt("0") + + +def test_dashed_line_with_dot_marker(): + same_as_matplotlib("--.") + assert parse_fmt("--.") == {"linestyle": "--", "marker": "."} + + +@pytest.mark.parametrize("fmt", ["rg", "rr", "bC0", "C0C1", "C1r", "kC12--"]) +def test_two_colors_are_refused(fmt): + # Matplotlib refuses two letter colors, but takes the last of a cycle color + # and a letter; we refuse them all + with pytest.raises(ValueError, match="two color symbols"): + parse_fmt(fmt) + + +@pytest.mark.parametrize( + "fmt", + ["roo", "r?", "ro--?", "C", "Cx", "xyz", "r--:", "-:", "--:", "ab"], +) +def test_invalid_strings_raise_as_matplotlib_does(fmt): + with pytest.raises(ValueError): + matplotlib_says(fmt) + with pytest.raises(ValueError, match="not a valid format string"): + parse_fmt(fmt) + + +def test_empty_and_none(): + assert parse_fmt("") == {} + assert parse_fmt(None) == {} + assert parse_fmt(()) == {} + assert parse_fmt([]) == {} + + +def test_tuple_or_list_takes_the_first(): + # as the *fmt argument of the plot functions arrives + assert parse_fmt(("r--",)) == {"color": "r", "linestyle": "--"} + assert parse_fmt(["r--", "ignored"]) == {"color": "r", "linestyle": "--"} + + +def test_not_a_string(): + with pytest.raises(ValueError, match="must be a string"): + parse_fmt(3) + + +def test_only_what_the_string_sets(): + assert parse_fmt("--") == {"linestyle": "--"} + assert parse_fmt("r") == {"color": "r"} + assert parse_fmt("r--") == {"color": "r", "linestyle": "--"} + assert parse_fmt("-.b") == {"color": "b", "linestyle": "-."} + assert parse_fmt("C2:") == {"color": "C2", "linestyle": ":"} + + +def test_marker_alone_means_no_line(): + assert parse_fmt("o") == {"marker": "o", "linestyle": "None"} + assert parse_fmt("rx") == {"color": "r", "marker": "x", "linestyle": "None"} + assert parse_fmt("ro--") == {"color": "r", "marker": "o", "linestyle": "--"} + + +def test_the_dot_is_a_marker_not_part_of_dash_dot(): + assert parse_fmt("-.") == {"linestyle": "-."} + assert parse_fmt(".-") == {"marker": ".", "linestyle": "-"} + + +def test_merges_over_defaults_without_wiping_them(): + defaults = {"color": "red", "linewidth": 2} + assert defaults | parse_fmt("--") == { + "color": "red", + "linewidth": 2, + "linestyle": "--", + } + assert defaults | parse_fmt("b--") == { + "color": "b", + "linewidth": 2, + "linestyle": "--", + } + + +def test_result_is_accepted_by_plot(): + fig, ax = plt.subplots() + try: + for fmt in ["r--", "go", "C2:", "--", "red", "k.-", "+"]: + (line,) = ax.plot([0, 1], [0, 1], **parse_fmt(fmt)) + (ref,) = ax.plot([0, 1], [0, 1], fmt) + assert line.get_linestyle() == ref.get_linestyle(), fmt + assert line.get_marker() == ref.get_marker(), fmt + if fmt not in ("--", "+"): # no color: the color cycle differs + assert mcolors.to_rgba(line.get_color()) == mcolors.to_rgba( + ref.get_color() + ), fmt + finally: + plt.close(fig)