From a5d128588269c3adafa4852a8ae6075183e1befc Mon Sep 17 00:00:00 2001 From: Peter Corke Date: Wed, 14 Oct 2026 08:36:30 +1000 Subject: [PATCH 01/14] perf: closest() and near() use a matrix of coordinates, not a loop (#74) Without a k-d tree both measured the metric of every vertex in a Python loop, and any add_vertex discarded the tree, so a planner that interleaves add_vertex with closest (RTB's LatticePlanner, RRTPlanner) always paid for the loop. The graph now keeps the coordinates of its embedded vertices as a matrix, built on first use and appended to by add_vertex, and applies the built-in metrics to all rows at once. Removing a vertex or assigning a coord drops it. A metric of your own is still applied to each vertex in turn. It is not pickled or copied, and has its own staleness flag. closest at N=1,000: 726 us -> 12 us. Lattice plan of 1,292 vertices: 1.07 s -> 0.06 s. Vertices, edges and paths of the RTB planners are unchanged. A coordinate changed in place (v.coord[0] = x) is not seen, as with build_kdtree(); documented. Co-Authored-By: Claude Sonnet 5.5 --- CHANGELOG.md | 16 +++ src/pgraph/PGraph.py | 135 +++++++++++++++++--- tests/test_point_cache.py | 250 ++++++++++++++++++++++++++++++++++++++ 3 files changed, 385 insertions(+), 16 deletions(-) create mode 100644 tests/test_point_cache.py diff --git a/CHANGELOG.md b/CHANGELOG.md index c39aabea..ba4bb965 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,19 @@ +Unreleased + +Performance + +- `closest()` and `near()` no longer make a Python-level pass over the vertices + when there is no k-d tree. The graph keeps the coordinates as a matrix, built + on first use and appended to by `add_vertex`, and applies the built-in metrics + to all rows at once. A query on a 1,000-vertex graph takes 12 microseconds + rather than 730, and stays that fast while vertices are being added, which is + what the Robotics Toolbox's `LatticePlanner` and `RRTPlanner` do (a lattice of + 1,292 vertices is planned in 0.06 s rather than 1.07 s). Results are the + same. The matrix is a copy of the coordinates, so changing one in place, + `vertex.coord[0] = x`, is not seen by `closest()`, as was already so with + `build_kdtree()`; assigning `vertex.coord` is. A metric of your own is still + applied to each vertex in turn. + 1.0.0 First 1.0 release: six years of production use since the first commit in 2020 diff --git a/src/pgraph/PGraph.py b/src/pgraph/PGraph.py index e0fa4de0..a59b01d4 100644 --- a/src/pgraph/PGraph.py +++ b/src/pgraph/PGraph.py @@ -39,6 +39,42 @@ def __init__(self, tree: Any, index: NDArray, p: float, prepare: Any): self.prepare = prepare # point -> point for the tree, or None if out of range +class _PointCache: + """ + The coordinates of a graph's embedded vertices, as rows of a matrix (private) + + Row ``i`` is the coordinate of ``vertices[i]``, in the order of the graph. + The buffer has spare rows so that adding a vertex is an append, which is + what lets :meth:`Graph.closest` stay fast while a planner interleaves + ``add_vertex`` with queries. + """ + + def __init__(self, points: NDArray, vertices: list[Vertex]): + n, dim = points.shape + self.buf = np.empty((n + n // 2 + 16, dim)) + self.buf[:n] = points + self.n = n + self.vertices = vertices + + @property + def dim(self) -> int: + return self.buf.shape[1] + + @property + def points(self) -> NDArray: + """The ``n`` x dim matrix of coordinates (a view, not a copy)""" + return self.buf[: self.n] + + def append(self, vertex: Vertex, coord: NDArray) -> None: + if self.n == self.buf.shape[0]: + grown = np.empty((2 * self.n, self.dim)) + grown[: self.n] = self.buf + self.buf = grown + self.buf[self.n] = coord + self.n += 1 + self.vertices.append(vertex) + + class SE2Metric: r""" Distance between planar poses, a weighted mixed norm @@ -294,6 +330,10 @@ def __init__( # vertices have changed since it was built self._kdtree: _KDTree | None = None self._spatialchange = False + # the coordinates of the embedded vertices as a matrix, built when + # first needed and kept up to date by add_vertex; None if not built or + # invalidated by a removal or an assignment to a ``coord`` + self._pts: _PointCache | None = None if metric is None: self.metric = "L2" else: @@ -980,7 +1020,7 @@ def subgraph(self, vertices: Iterable[Vertex | str] | NDArray) -> Graph: # pickling and copying #: the graph's own containers, which are saved as a flat description - _STRUCTURE = ("_vertexlist", "_vertexdict", "_edges", "_kdtree") + _STRUCTURE = ("_vertexlist", "_vertexdict", "_edges", "_kdtree", "_pts") #: the references a vertex holds, which are rebuilt rather than saved _VERTEX_LINKS = ("_edgelist", "_inlist", "_graph") @@ -1043,6 +1083,7 @@ def __setstate__(self, state: dict[str, Any]) -> None: state[key] = _METRICS[value[1]] self.__dict__.update(state) self._kdtree = None + self._pts = None self._spatialchange = False self._vertexlist = [] @@ -1186,6 +1227,16 @@ def add_vertex( vertex.__dict__["_graph"] = self self._connectivitychange = True self._spatialchange = True + pts = self._pts + if pts is not None and vertex.coord is not None: + # keep the matrix of coordinates up to date; one that does not + # fit it (another length, not finite) is left for _points to + # judge, by dropping the matrix + coord = vertex.coord + if coord.ndim == 1 and coord.shape[0] == pts.dim and np.isfinite(coord).all(): + pts.append(vertex, coord) + else: + self._pts = None return vertex @classmethod @@ -1471,6 +1522,7 @@ def remove_vertex(self, vertex: Vertex) -> None: vertex._label = None # and so not in a component self._connectivitychange = True self._spatialchange = True + self._pts = None def remove(self, x: Edge | Vertex) -> None: """ @@ -1979,12 +2031,14 @@ def build_kdtree(self) -> None: 3 elements, or no vertex has a coordinate :raises ImportError: scipy is not installed - Finding the nearest vertex to a point is a pass over all the vertices, - which is the cost of a query on a large graph that is queried often. A - k-d tree answers in a time that grows more slowly, at the cost of - building it once. :meth:`closest` and :meth:`near` use the index if it - has been built, and fall back to the pass over the vertices if it has - not or if the graph has changed. + Without an index, finding the nearest vertex to a point measures the + distance to every vertex, which is the cost of a query on a large graph + that is queried often. A k-d tree answers in a time that grows more + slowly, at the cost of building it once, which pays for a graph that is + built and then queried. A graph that is queried while it is growing + does better without it, since adding a vertex discards the index. + :meth:`closest` and :meth:`near` use the index if it has been built, + and measure every vertex if it has not or if the graph has changed. The index is for the built-in metrics ``"L1"``, ``"L2"`` and ``"SE2"`` (with any weight, see :class:`SE2Metric`), and results @@ -2107,6 +2161,36 @@ def _metric_columns(self, diff: NDArray) -> NDArray | None: ) return None + def _points(self) -> _PointCache | None: + """ + The coordinates of the embedded vertices as a matrix, or None (private) + + Built on first use and kept by :meth:`add_vertex`. It is None, so + that the caller makes its pass over the vertices, if no vertex has a + coordinate or the coordinates are not all vectors of the same length, + which that pass reports. A vertex whose coordinate is not finite is + left out, as it is never the closest. + """ + if self._pts is not None: + return self._pts + vertices = [v for v in self._vertexlist if v.coord is not None] + if not vertices: + return None + try: + points = np.array([v.coord for v in vertices], dtype=float) + except (ValueError, TypeError): + return None # not all the same length, or not numbers + if points.ndim != 2 or points.shape[1] == 0: + return None + finite = np.isfinite(points).all(axis=1) + if not finite.all(): + points = points[finite] + vertices = [v for v, ok in zip(vertices, finite) if ok] + if not vertices: + return None + self._pts = _PointCache(points, vertices) + return self._pts + def closest(self, coord: ArrayLike) -> tuple[Vertex | None, float]: """ Vertex closest to point @@ -2121,8 +2205,17 @@ def closest(self, coord: ArrayLike) -> tuple[Vertex | None, float]: according to the graph's metric. Vertices without a coordinate (``coord`` is None) are skipped -- they have no position to compare. - This is a pass over the vertices, unless a spatial index has been - built with :meth:`build_kdtree` and is still valid. + For the built-in metrics the distance to every vertex is found in one + operation on a matrix of the coordinates that the graph keeps, which + adding a vertex only appends to, so this stays fast when vertices are + added between queries, as a planner does. A spatial index built with + :meth:`build_kdtree`, if it is still valid, is faster again for a graph + that is not changing. A metric of your own is applied to each vertex + in turn. + + .. note:: The matrix is a copy, so a coordinate changed in place, + ``vertex.coord[0] = x``, is not seen. Assigning + ``vertex.coord = x`` (or ``+=``) is. .. runblock:: pycon @@ -2143,6 +2236,15 @@ def closest(self, coord: ArrayLike) -> tuple[Vertex | None, float]: if np.isfinite(d): return self._vertexlist[int(index.index[i])], float(d) + pts = self._points() + if pts is not None: + q = np.asarray(coord, dtype=float) + if q.shape == (pts.dim,) and np.isfinite(q).all(): + d = self._metric_columns((pts.points - q).T) + if d is not None: # a built-in metric, applied to all at once + i = int(np.argmin(d)) + return pts.vertices[i], float(d[i]) + min_dist = np.inf min_which: Vertex | None = None @@ -2224,9 +2326,9 @@ def near(self, coord: ArrayLike, radius: float) -> list[tuple[Vertex, float]]: vertices at equal distance are in the order of the graph. For the built-in metrics the distance to every vertex is found in one - operation on :meth:`coordinates`, or by the spatial index if - :meth:`build_kdtree` was called; a metric of your own is applied - to each vertex in turn. + operation on the matrix of coordinates that :meth:`closest` uses, or + by the spatial index if :meth:`build_kdtree` was called; a metric of + your own is applied to each vertex in turn. .. runblock:: pycon @@ -2251,14 +2353,14 @@ def near(self, coord: ArrayLike, radius: float) -> list[tuple[Vertex, float]]: candidates = [self._vertexlist[int(index.index[i])] for i in sorted(hits)] if candidates is None: - C = self.coordinates() + pts = self._points() point = np.asarray(coord, dtype=float) - if C.shape[0] != 0 and point.shape == (C.shape[0],): - d = self._metric_columns(C - point[:, None]) + if pts is not None and point.shape == (pts.dim,): + d = self._metric_columns((pts.points - point).T) if d is not None: hit = np.flatnonzero(d <= radius) hit = hit[np.argsort(d[hit], kind="stable")] - return [(self._vertexlist[i], float(d[i])) for i in hit] + return [(pts.vertices[i], float(d[i])) for i in hit] candidates = [v for v in self._vertexlist if v.coord is not None] found = [] @@ -4498,6 +4600,7 @@ def __setattr__(self, name: str, value: Any) -> None: graph = self.__dict__.get("_graph") if graph is not None: graph._spatialchange = True + graph._pts = None object.__setattr__(self, name, value) def __reduce__(self) -> Any: diff --git a/tests/test_point_cache.py b/tests/test_point_cache.py new file mode 100644 index 00000000..4bc0b55c --- /dev/null +++ b/tests/test_point_cache.py @@ -0,0 +1,250 @@ +""" +The matrix of coordinates that ``closest`` and ``near`` use when there is no +spatial index, and that ``add_vertex`` keeps up to date. + +Expectations are computed here, by hand, from the coordinates that were put +in; never by the code under test. The cache is private, so what is checked +is that answers are the same as the pass over the vertices would give, +through every way the graph can change. +""" + +import copy +import pickle # nosec B403 nosemgrep - only used to round-trip graphs made in this file +import unittest + +import numpy as np + +from pgraph import SE2Metric, UGraph, Vertex + + +def roundtrip(obj): + """Pickle and unpickle: these tests only read what they have just written""" + return pickle.loads(pickle.dumps(obj)) # nosec B301 nosemgrep + + +def oracle(points, q, p=2.0): + """Index and distance of the nearest of ``points`` to ``q``, first on ties""" + best, best_d = None, np.inf + for i, x in enumerate(points): + if x is None: + continue + d = float(np.sum(np.abs(np.asarray(x, float) - np.asarray(q, float)) ** p) ** (1 / p)) + if d < best_d: + best, best_d = i, d + return best, best_d + + +class TestClosestMatrix(unittest.TestCase): + def check(self, g, points, q, p=2.0): + v, d = g.closest(q) + i, d_expected = oracle(points, q, p) + if i is None: + self.assertIsNone(v) + self.assertEqual(d, np.inf) + else: + self.assertIs(v, g[i]) + self.assertAlmostEqual(d, d_expected, places=12) + + def test_matches_oracle(self): + rng = np.random.default_rng(1) + pts = rng.uniform(-5, 5, (100, 2)) + g = UGraph() + for x in pts: + g.add_vertex(coord=x) + for q in rng.uniform(-6, 6, (20, 2)): + self.check(g, pts, q) + + def test_interleaved_add_and_query(self): + """The planners' pattern, over enough vertices to grow the buffer""" + rng = np.random.default_rng(2) + g = UGraph() + pts = [] + for _ in range(300): + x = rng.uniform(-5, 5, 2) + g.add_vertex(coord=x) + pts.append(x) + self.check(g, pts, rng.uniform(-5, 5, 2)) + g.validate() + + def test_l1_and_se2_metrics(self): + rng = np.random.default_rng(3) + pts = rng.uniform(-3, 3, (60, 2)) + g = UGraph(metric="L1") + for x in pts: + g.add_vertex(coord=x) + for q in rng.uniform(-3, 3, (10, 2)): + self.check(g, pts, q, p=1.0) + + # SE2: planar distance plus weighted, wrapped, heading difference + w = 2.0 + poses = np.column_stack([rng.uniform(-3, 3, (40, 2)), rng.uniform(-3, 3, 40)]) + h = UGraph(metric=SE2Metric(weight=w)) + for x in poses: + h.add_vertex(coord=x) + for q in poses[:5] + 0.01: + v, d = h.closest(q) + best = np.inf + for i, x in enumerate(poses): + th = (x[2] - q[2] + np.pi) % (2 * np.pi) - np.pi + best = min(best, np.hypot(np.hypot(x[0] - q[0], x[1] - q[1]), w * th)) + self.assertAlmostEqual(d, best, places=12) + + def test_first_wins_a_tie(self): + g = UGraph() + g.add_vertex(coord=[1, 0], name="a") + g.add_vertex(coord=[-1, 0], name="b") + self.assertEqual(g.closest([0, 0])[0].name, "a") + + def test_vertex_without_coordinate_is_skipped(self): + g = UGraph() + g.add_vertex(name="bare") + self.assertEqual(g.closest([0, 0]), (None, np.inf)) # nothing embedded + g.add_vertex(coord=[3, 4], name="p") + g.add_vertex(name="bare2") + g.add_vertex(coord=[1, 1], name="q") + v, d = g.closest([0, 0]) + self.assertEqual(v.name, "q") + self.assertAlmostEqual(d, np.sqrt(2)) + # built before the unembedded vertex was added, and after + self.assertEqual(g.closest([3, 4])[0].name, "p") + + def test_remove_vertex(self): + pts = [[0, 0], [1, 0], [2, 0]] + g = UGraph() + for i, x in enumerate(pts): + g.add_vertex(coord=x, name=f"v{i}") + self.assertEqual(g.closest([0.1, 0])[0].name, "v0") + g.remove_vertex(g["v0"]) + v, d = g.closest([0.1, 0]) + self.assertEqual(v.name, "v1") + self.assertAlmostEqual(d, 0.9) + g.validate() + + def test_assigning_a_coordinate(self): + g = UGraph() + a = g.add_vertex(coord=[0, 0], name="a") + g.add_vertex(coord=[5, 5], name="b") + self.assertEqual(g.closest([0.1, 0])[0].name, "a") + a.coord = np.array([9.0, 9.0]) + self.assertEqual(g.closest([0.1, 0])[0].name, "b") + a.coord += 1 # also seen + self.assertEqual(g.closest([10, 10])[0].name, "a") + + def test_in_place_change_is_not_seen(self): + """The documented limit, shared with the k-d tree""" + g = UGraph() + a = g.add_vertex(coord=[0.0, 0.0], name="a") + g.add_vertex(coord=[5.0, 5.0], name="b") + g.closest([0, 0]) # build + a.coord[0] = 9.0 + self.assertEqual(g.closest([0.1, 0])[0].name, "a") # the stale answer + + def test_nonfinite_coordinates_are_left_out(self): + g = UGraph() + g.add_vertex(coord=[np.nan, 0], name="nan") + g.add_vertex(coord=[1, 1], name="ok") + self.assertEqual(g.closest([0, 0])[0].name, "ok") # built without it + g.add_vertex(coord=[np.inf, 0], name="inf") # an append that is refused + self.assertEqual(g.closest([0, 0])[0].name, "ok") + h = UGraph() + h.add_vertex(coord=[np.nan, np.nan]) + self.assertEqual(h.closest([0, 0]), (None, np.inf)) + + def test_non_finite_query_and_wrong_length_query(self): + g = UGraph() + g.add_vertex(coord=[0, 0], name="a") + g.add_vertex(coord=[1, 1], name="b") + self.assertEqual(g.closest([0, 0])[0].name, "a") + v, d = g.closest([np.nan, 0]) # as the pass over the vertices does + self.assertIsNone(v) + with self.assertRaises(ValueError): + g.closest([0, 0, 0]) + + def test_a_vertex_of_another_length_is_reported(self): + g = UGraph() + g.add_vertex(coord=[0, 0]) + g.closest([0, 0]) # build + g.add_vertex(coord=[1, 2, 3]) # does not fit; the matrix is dropped + with self.assertRaises(ValueError): + g.closest([0, 0]) + h = UGraph() + h.add_vertex(coord=[0, 0]) + h.add_vertex(coord=[1, 2, 3]) + with self.assertRaises(ValueError): # ragged when first built + h.closest([0, 0]) + + def test_non_numeric_coordinate_falls_back(self): + g = UGraph() + g.add_vertex(coord=["a", "b"]) + with self.assertRaises(TypeError): # from the pass over the vertices + g.closest([0, 0]) + + def test_coordinate_that_is_not_a_vector_is_left_to_the_pass(self): + g = UGraph() + g.add_vertex(coord=np.ones((2, 2))) # a matrix + v, d = g.closest([1, 1]) # broadcast against it, as it always was + self.assertIs(v, g[0]) + self.assertEqual(d, 0.0) + self.assertIsNone(g._pts) + h = UGraph() + h.add_vertex(coord=[]) # no elements + self.assertEqual(h.closest([])[1], 0.0) + self.assertIsNone(h._pts) + + def test_user_metric_is_applied_to_each_vertex(self): + calls = [] + + def metric(v): + calls.append(1) + return float(np.abs(v).max()) + + g = UGraph(metric=metric) + for x in ([0, 0], [3, 1], [1, 3]): + g.add_vertex(coord=x) + v, d = g.closest([2, 0]) + self.assertEqual(d, 1.0) + self.assertGreaterEqual(len(calls), 3) + + def test_near(self): + rng = np.random.default_rng(4) + pts = rng.uniform(-5, 5, (80, 2)) + g = UGraph() + for x in pts: + g.add_vertex(coord=x) + g.add_vertex(name="bare") + q, r = np.array([0.5, -0.5]), 2.5 + got = g.near(q, r) + want = sorted( + [(i, float(np.hypot(*(x - q)))) for i, x in enumerate(pts) if np.hypot(*(x - q)) <= r], + key=lambda t: t[1], + ) + self.assertEqual([g._vertexlist.index(v) for v, _ in got], [i for i, _ in want]) + for (_, d), (_, e) in zip(got, want): + self.assertAlmostEqual(d, e, places=12) + # after a vertex is added, with the matrix already built + g.add_vertex(coord=q + 0.01, name="new") + self.assertEqual(g.near(q, r)[0][0].name, "new") + + def test_pickle_and_copy_do_not_carry_it(self): + g = UGraph() + for x in ([0, 0], [4, 4], [1, 1]): + g.add_vertex(coord=x) + g.closest([0, 0]) + for h in (roundtrip(g), copy.deepcopy(g), g.subgraph([True, True, False])): + self.assertIsNone(h._pts) + self.assertIs(h.closest([4, 4])[0], h[1]) + h.add_vertex(coord=[4.1, 4.1], name="x") + self.assertEqual(h.closest([4.2, 4.2])[0].name, "x") + h.validate() + + def test_vertex_instance_added(self): + g = UGraph() + g.add_vertex(coord=[0, 0]) + g.closest([0, 0]) + g.add_vertex(Vertex(coord=[2, 2], name="inst")) + g.add_vertex(Vertex(name="bare")) + self.assertEqual(g.closest([2.1, 2.1])[0].name, "inst") + + +if __name__ == "__main__": + unittest.main() From 4d383899bde8fdc1dc802f0b5ee993133a13f7a4 Mon Sep 17 00:00:00 2001 From: Peter Corke Date: Thu, 15 Oct 2026 16:25:33 +1000 Subject: [PATCH 02/14] docs(llms): add "when to use it" and recipes, link llms.txt from PyPI Agents choosing between packages need to know what this one is for and what it is not for, and users phrase problems as tasks, not API names. llms_intro.md gains a "When to use it" section (including what it is not for) and a "Recipes" section of task-phrased one-liners, each checked against the current code. pyproject.toml gains a project URL for llms.txt so it is discoverable from the PyPI page. Co-Authored-By: Claude Sonnet 5.5 --- docs/llms_intro.md | 16 ++++++++++++++++ pyproject.toml | 1 + 2 files changed, 17 insertions(+) diff --git a/docs/llms_intro.md b/docs/llms_intro.md index 8969ac8b..61decc8e 100644 --- a/docs/llms_intro.md +++ b/docs/llms_intro.md @@ -1,5 +1,11 @@ pgraph is a pure-Python package of graph classes: directed and undirected graphs of vertices connected by edges, with edge costs and path planning (breadth-first, uniform-cost and A*). Vertices can be *embedded*, given a coordinate in a space of any dimension; edge costs then come from a distance metric (L2, L1, SE2 or your own), and the graph can be queried spatially, plotted and exported. Self-loops and parallel edges are allowed. It requires Python 3.9 or later and depends on NumPy, Matplotlib and spatialmath-python. Install with `pip install pgraph-python`; import it as `pgraph`. +## When to use it + +Reach for pgraph when a program needs a **small, explicit graph with path planning**: vertices with optional coordinates, directed or undirected edges with costs, and breadth-first, uniform-cost or A* search, plus nearest-vertex queries, plotting and export. It suits roadmaps, grid and lattice planners, pose graphs and teaching examples where you want the vertex and edge objects themselves, not just an adjacency structure. `import pgraph` loads only NumPy. + +It is not a large-scale graph analytics package (use `networkx` for centrality, community detection or hundreds of algorithms; `igraph` or `graph-tool` for very large graphs), and it has no weighted-matching or flow algorithms. + ## Quick start ```python @@ -18,6 +24,16 @@ g.plot() g.highlight_path(path) ``` +## Recipes + +- **Shortest path between two named places**: build a `UGraph`, `add_vertex` for each place with its coordinate and `name=`, `add_edge` between neighbours, then `path, length, _ = g.path_Astar("start", "goal")`. +- **Plan on a grid**: add one vertex per cell and an edge to each neighbour, with `cost=` if the cells differ; `path_BFS` gives the fewest steps, `path_Astar` the cheapest. +- **Find the vertex nearest a point**: `v, dist = g.closest(point)`; `g.near(point, radius)` for all within a radius. +- **Check whether two places are connected**: `g.samecomponent(v1, v2)`, or `g.nc` for the number of components. +- **Get the adjacency or Laplacian matrix**: `g.adjacency()`, `g.laplacian()`, as NumPy arrays. +- **Draw the graph and the route**: `g.plot()`, then `g.highlight_path(path)`. +- **Export for GraphViz or Mermaid**: `g.export("graph.dot")` or `g.export("graph.mmd")`. + ## Key points - **Classes.** `UGraph` (undirected) and `DGraph` (directed) share the base class `Graph`, which is concrete: `Graph(directed=True)` is a `DGraph`. There is one `Vertex` class for both and one `Edge` class. `UVertex` and `DVertex` are deprecated aliases of `Vertex`. Constructor arguments are keyword-only: `UGraph(dim=2, metric="L2", heuristic=None, vertex_class=None, edge_class=None, verbose=False)`; `UGraph(2)` is a `TypeError`. diff --git a/pyproject.toml b/pyproject.toml index f67362f6..417c28c1 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -39,6 +39,7 @@ dependencies = ["spatialmath-python", "numpy>=2.0", "matplotlib"] "Homepage" = "https://github.com/petercorke/pgraph-python" "Bug Tracker" = "https://github.com/petercorke/pgraph-python/issues" "Documentation" = "https://petercorke.github.io/pgraph-python" +"llms.txt" = "https://petercorke.github.io/pgraph-python/llms.txt" "GitHub Source" = "https://github.com/petercorke/pgraph-python" "Changelog" = "https://github.com/petercorke/pgraph-python/blob/main/CHANGELOG.md" "Coverage" = "https://codecov.io/gh/petercorke/pgraph-python" From fe10d37ebe75c43a2ae612cdd0455d1b31411a0c Mon Sep 17 00:00:00 2001 From: huxiaoyi-ovo Date: Mon, 19 Oct 2026 12:54:28 +0000 Subject: [PATCH 03/14] fix(plot): default to environment-managed Matplotlib display Align plot() and highlight_path() with the RVC block contract without changing explicit True/False handling. Co-Authored-By: ChatGPT (OpenAI GPT-6) --- src/pgraph/PGraph.py | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/src/pgraph/PGraph.py b/src/pgraph/PGraph.py index e0fa4de0..11fb4eef 100644 --- a/src/pgraph/PGraph.py +++ b/src/pgraph/PGraph.py @@ -2405,7 +2405,7 @@ def plot( vopt: dict | None = None, eopt: dict | None = None, text: dict | bool | None = None, - block: bool | None = False, + block: bool | None = None, grid: bool = True, ax: Any = None, *, @@ -2448,9 +2448,9 @@ def plot( :type grid: bool, optional :param ax: axes to draw in, defaults to the current axes or a new figure :type ax: Axes or Axes3D, optional - :param block: block until figure is dismissed, defaults to False. If - None the figure is not shown at all, which is useful when - adding to the plot or saving it. + :param block: None (default) leaves display to the environment without + calling plt.show; False shows without waiting; True waits until + the window is closed (desktop GUI backends). :type block: bool or None, optional :raises ValueError: the graph is empty, or a vertex has no coordinate or fewer than two coordinate values @@ -2657,15 +2657,16 @@ def plot( plt.show(block=block) def highlight_path( - self, path: list[Vertex], block: bool | None = False, **kwargs: Any + self, path: list[Vertex], block: bool | None = None, **kwargs: Any ) -> None: """ Highlight a path through the graph :param path: sequence of vertices forming a path :type path: list of Vertex subclass - :param block: block until figure is dismissed, defaults to False. If - None the figure is not shown. + :param block: None (default) leaves display to the environment without + calling plt.show; False shows without waiting; True waits until + the window is closed (desktop GUI backends). :type block: bool or None, optional :param kwargs: arguments passed to :meth:`highlight_edge` and :meth:`highlight_vertex` From 749717a53a11c417b78af44768aad854bea7b554 Mon Sep 17 00:00:00 2001 From: huxiaoyi-ovo Date: Mon, 19 Oct 2026 12:54:44 +0000 Subject: [PATCH 04/14] test(plot): verify default and explicit Matplotlib show modes Co-Authored-By: ChatGPT (OpenAI GPT-6) --- tests/test_plot_block.py | 56 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 tests/test_plot_block.py diff --git a/tests/test_plot_block.py b/tests/test_plot_block.py new file mode 100644 index 00000000..a3861dd2 --- /dev/null +++ b/tests/test_plot_block.py @@ -0,0 +1,56 @@ +"""Regression tests for the three-state block= plotting contract.""" + +from unittest.mock import patch + +import matplotlib + +matplotlib.use("Agg") +import matplotlib.pyplot as plt + +from pgraph import UGraph + + +def make_graph() -> tuple[UGraph, list]: + graph = UGraph() + a = graph.add_vertex([0.0, 0.0], name="a") + b = graph.add_vertex([1.0, 1.0], name="b") + graph.add_edge(a, b) + return graph, [a, b] + + +def test_default_plot_and_highlight_do_not_call_show() -> None: + graph, path = make_graph() + try: + with patch.object(plt, "show") as show: + graph.plot() + axes = plt.gca() + before = len(axes.patches) + graph.highlight_path(path) + show.assert_not_called() + assert plt.gca() is axes + assert len(axes.patches) > before + finally: + plt.close("all") + + +def test_explicit_plot_show_modes() -> None: + graph, _ = make_graph() + try: + for block in (False, True): + with patch.object(plt, "show") as show: + graph.plot(block=block) + show.assert_called_once_with(block=block) + finally: + plt.close("all") + + +def test_explicit_highlight_show_modes() -> None: + graph, path = make_graph() + try: + graph.plot() + for block in (False, True): + with patch.object(plt, "show") as show: + graph.highlight_path(path, block=block) + show.assert_called_once_with(block=block) + finally: + plt.close("all") From d720f3e7f9b9741d249cded8bbf11d4387e51f65 Mon Sep 17 00:00:00 2001 From: huxiaoyi-ovo Date: Mon, 19 Oct 2026 12:55:01 +0000 Subject: [PATCH 05/14] docs(plot): show graph and path together in scripts Co-Authored-By: ChatGPT (OpenAI GPT-6) --- README.md | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index d0ff4260..68d10eb2 100644 --- a/README.md +++ b/README.md @@ -60,6 +60,7 @@ This needs Python 3.9 or later. The dependencies, NumPy, Matplotlib and Spatial ```python from pgraph import UGraph +import matplotlib.pyplot as plt import json # load the places and routes @@ -75,8 +76,9 @@ for route in data['routes']: # plan a path from Hughenden to Brisbane p, length, _ = g.path_Astar('Hughenden', 'Brisbane') -g.plot(block=False) # plot it -g.highlight_path(p) # overlay the path +g.plot() # create the graph without displaying it yet +g.highlight_path(p) # overlay the path on the same axes +plt.show() # show the finished figure in a script ``` The data file and the complete example are in the notebook [`examples/roads.ipynb`](https://github.com/petercorke/pgraph-python/blob/main/examples/roads.ipynb). From e6b27f7bfcf709f70a56209c5ede428ca58e101f Mon Sep 17 00:00:00 2001 From: huxiaoyi-ovo Date: Mon, 19 Oct 2026 12:55:14 +0000 Subject: [PATCH 06/14] docs(plot): document block semantics for pgraph users Co-Authored-By: ChatGPT (OpenAI GPT-6) --- docs/llms_intro.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/llms_intro.md b/docs/llms_intro.md index 8969ac8b..53345258 100644 --- a/docs/llms_intro.md +++ b/docs/llms_intro.md @@ -28,7 +28,7 @@ g.highlight_path(path) - **Metrics.** `"L2"` (default), `"L1"`, `"SE2"` for `(x, y, theta)` poses, `SE2Metric(weight)` to weight the angle, or a function of one difference vector. A* uses `heuristic` (default: the metric), which must be in the same units as the edge costs and must not exceed the true cost to go, or the path is not the shortest. - **Spatial queries** on an embedded graph: `closest(point)` returns `(vertex, distance)`, `near(point, radius)`, `within(box)` with `box` a 2 x n array of lower and upper corner, `coordinates()` the `(dim, n)` matrix of coordinates, and `subgraph(vertices)`, which takes vertices, names or a boolean mask and returns a new graph. `build_kdtree()` is an optional index (it needs scipy) that `closest` and `near` then use. - **Components and matrices.** `g.component(c)` is the vertices in component number `c`, `v.label` is the component of a vertex, `g.samecomponent(v1, v2)`. `adjacency()`, `incidence()`, `laplacian()`, `degree()` and `connectivity()` return dense NumPy arrays. -- **Output.** `g.plot()` (arrowheads for a directed graph, arcs for parallel edges, circles for loops), `highlight_path(path)`, and `g.export(file)` for GraphViz dot, Mermaid, GraphML, ELK JSON or an image (images need the GraphViz executables). +- **Output.** `g.plot()` (arrowheads for a directed graph, arcs for parallel edges, circles for loops), `highlight_path(path)`, and `g.export(file)` for GraphViz dot, Mermaid, GraphML, ELK JSON or an image (images need the GraphViz executables). Both plot methods default to `block=None`, which does not call `plt.show()` and lets the environment display the figure (useful for notebook overlays); `block=False` shows without waiting, and `block=True` waits in desktop GUI applications. - **Subclassing.** `class Foo(Vertex)` and `UGraph(vertex_class=Foo, edge_class=Bar)` make the graph build them; a subclass `__init__` must pass `coord` and `name` (vertices) or `v1, v2, cost, data` (edges) to its parent. - **Copying.** `g.copy()` and `pickle` work for a whole graph; a vertex or edge cannot be copied or pickled on its own, and a graph whose metric is a `lambda` cannot be pickled. From a5c1744331ae28cb7db9925901d9e564a4a07852 Mon Sep 17 00:00:00 2001 From: huxiaoyi-ovo Date: Wed, 21 Oct 2026 04:45:37 -0400 Subject: [PATCH 07/14] test(plot): align block contract tests with unittest conventions Co-Authored-By: ChatGPT (OpenAI GPT-6) --- tests/test_plot_block.py | 62 +++++++++++++++++++--------------------- 1 file changed, 29 insertions(+), 33 deletions(-) diff --git a/tests/test_plot_block.py b/tests/test_plot_block.py index a3861dd2..fcef01b6 100644 --- a/tests/test_plot_block.py +++ b/tests/test_plot_block.py @@ -1,5 +1,6 @@ """Regression tests for the three-state block= plotting contract.""" +import unittest from unittest.mock import patch import matplotlib @@ -10,47 +11,42 @@ from pgraph import UGraph -def make_graph() -> tuple[UGraph, list]: - graph = UGraph() - a = graph.add_vertex([0.0, 0.0], name="a") - b = graph.add_vertex([1.0, 1.0], name="b") - graph.add_edge(a, b) - return graph, [a, b] +class TestPlotBlock(unittest.TestCase): + def setUp(self) -> None: + self.graph = UGraph() + a = self.graph.add_vertex([0.0, 0.0], name="a") + b = self.graph.add_vertex([1.0, 1.0], name="b") + self.graph.add_edge(a, b) + self.path = [a, b] + def tearDown(self) -> None: + plt.close("all") -def test_default_plot_and_highlight_do_not_call_show() -> None: - graph, path = make_graph() - try: + def test_default_plot_and_highlight_do_not_call_show(self) -> None: with patch.object(plt, "show") as show: - graph.plot() + self.graph.plot() axes = plt.gca() before = len(axes.patches) - graph.highlight_path(path) + self.graph.highlight_path(self.path) show.assert_not_called() - assert plt.gca() is axes - assert len(axes.patches) > before - finally: - plt.close("all") + self.assertIs(plt.gca(), axes) + self.assertGreater(len(axes.patches), before) + def test_explicit_plot_show_modes(self) -> None: + for block in (False, True): + with self.subTest(block=block): + with patch.object(plt, "show") as show: + self.graph.plot(block=block) + show.assert_called_once_with(block=block) -def test_explicit_plot_show_modes() -> None: - graph, _ = make_graph() - try: + def test_explicit_highlight_show_modes(self) -> None: + self.graph.plot() for block in (False, True): - with patch.object(plt, "show") as show: - graph.plot(block=block) - show.assert_called_once_with(block=block) - finally: - plt.close("all") + with self.subTest(block=block): + with patch.object(plt, "show") as show: + self.graph.highlight_path(self.path, block=block) + show.assert_called_once_with(block=block) -def test_explicit_highlight_show_modes() -> None: - graph, path = make_graph() - try: - graph.plot() - for block in (False, True): - with patch.object(plt, "show") as show: - graph.highlight_path(path, block=block) - show.assert_called_once_with(block=block) - finally: - plt.close("all") +if __name__ == "__main__": + unittest.main() From 4e1c1f9abf554c53c7b29862e0882ecd0f580554 Mon Sep 17 00:00:00 2001 From: Vamsi-2581 <245859299+Vamsi-2581@users.noreply.github.com> Date: Sat, 31 Oct 2026 06:31:38 +0530 Subject: [PATCH 08/14] fix(spatial): handle SE2 angles that round to the period (#86) --- src/pgraph/PGraph.py | 11 +++++++---- tests/test_spatial_index.py | 16 ++++++++++++++++ 2 files changed, 23 insertions(+), 4 deletions(-) diff --git a/src/pgraph/PGraph.py b/src/pgraph/PGraph.py index e0fa4de0..72e1c5ac 100644 --- a/src/pgraph/PGraph.py +++ b/src/pgraph/PGraph.py @@ -2058,14 +2058,17 @@ def prepare(q: NDArray) -> NDArray | None: # noqa: F811 return None # far outside the data: let the caller do it if weight == 0: return xy - return np.r_[xy, np.mod(weight * q[2], period)] + angle = np.mod(weight * q[2], period) + if angle >= period: + angle = 0.0 + return np.r_[xy, angle] if weight == 0: tree = spatial.cKDTree(points[:, :2] - shift, boxsize=[size, size]) else: - data = np.column_stack( - [points[:, :2] - shift, np.mod(weight * points[:, 2], period)] - ) + angle = np.mod(weight * points[:, 2], period) + angle[angle >= period] = 0.0 + data = np.column_stack([points[:, :2] - shift, angle]) tree = spatial.cKDTree(data, boxsize=[size, size, period]) self._kdtree = _KDTree(tree, index, p, prepare) diff --git a/tests/test_spatial_index.py b/tests/test_spatial_index.py index b4d98167..8d2bf281 100644 --- a/tests/test_spatial_index.py +++ b/tests/test_spatial_index.py @@ -168,6 +168,22 @@ def test_a_query_across_the_angle_wrap(self): self.assertEqual(v.name, "a") self.assertAlmostEqual(d, 0.2) + def test_a_negative_angle_that_rounds_to_the_period(self): + for metric in ("SE2", SE2Metric(0.3)): + with self.subTest(metric=metric): + for angle_is_in_graph in (True, False): + with self.subTest(angle_is_in_graph=angle_is_in_graph): + g = UGraph(dim=3, metric=metric) + boundary_angle = -1e-17 if angle_is_in_graph else 0.0 + g.add_vertex([0.0, 0.0, boundary_angle], name="boundary") + g.add_vertex([0.0, 0.0, 0.25], name="other") + g.build_kdtree() + + query_angle = 0.0 if angle_is_in_graph else -1e-17 + query = [0.0, 0.0, query_angle] + self.assertEqual(g.closest(query)[0].name, "boundary") + self.assertEqual(g.near(query, 1e-12)[0][0].name, "boundary") + def test_a_query_far_outside_is_still_right(self): g, P = points_graph(UGraph, dim=3, metric=SE2Metric(1.0)) g.build_kdtree() From 548fb5fa2edfa02978efa0e060fe66fb9aa85706 Mon Sep 17 00:00:00 2001 From: Peter Corke Date: Sat, 31 Oct 2026 11:44:17 +1000 Subject: [PATCH 09/14] fix: repr(g) is the one-line summary, show() lists the vertices The graph had two __repr__ definitions in one class. The first returned str(self) and was shadowed by the second, which printed one line per vertex, so a repr (a notebook cell, a debugger, a log line, an error message) was as long as the graph. A type: ignore[no-redef] hid the redefinition. Keep one __repr__, the same one-line summary as __str__, and have show() print what the long repr did: each vertex with its name, coordinate and component number. plot() and show() now refer to each other in :seealso:. Part of #23. Co-Authored-By: Claude Sonnet 5.5 --- src/pgraph/PGraph.py | 77 ++++++++++++++++++++++++-------------------- tests/test_graph.py | 52 +++++++++++++++++++++++++++--- 2 files changed, 90 insertions(+), 39 deletions(-) diff --git a/src/pgraph/PGraph.py b/src/pgraph/PGraph.py index 72e1c5ac..fc0f008d 100644 --- a/src/pgraph/PGraph.py +++ b/src/pgraph/PGraph.py @@ -323,15 +323,38 @@ def __str__(self) -> str: >>> g.add_edge(v2, v3) >>> str(g) - :seealso: :meth:`show` + :seealso: :meth:`__repr__` :meth:`show` """ s = f"{self.__class__.__name__}: {self.n:,} {'vertex' if self.n==1 else 'vertices'}, {self.ne:,} edge{'s'[:self.ne^1]}, {self.nc:,} component{'s'[:self.nc^1]}" return s def __repr__(self) -> str: - # NOTE: this is shadowed by the __repr__ defined further below in - # this class, which is the one actually used -- kept as-is here to - # avoid changing behaviour as part of a typing-only pass. + """ + Representation of the graph, the same one-line summary as :meth:`__str__` + + :return: one-line summary of vertex/edge/component counts + :rtype: str + + The representation of a graph does not list its vertices, since that + would be as long as the graph, and a ``repr`` is what appears in a + notebook cell, a debugger, a log or an error message. Use + :meth:`show` to list them. + + .. runblock:: pycon + + >>> from pgraph import UGraph + >>> g = UGraph() + >>> v1 = g.add_vertex(coord=[0,0], name='v1') + >>> v2 = g.add_vertex(coord=[1,1], name='v2') + >>> g.add_edge(v1, v2) + >>> repr(g) + + .. versionchanged:: 1.1 + Was one line per vertex, with its name, coordinate and component; + that is now printed by :meth:`show`. + + :seealso: :meth:`__str__` :meth:`show` + """ return str(self) @classmethod @@ -1501,7 +1524,11 @@ def remove(self, x: Edge | Vertex) -> None: def show(self) -> None: """ - Print a summary of all vertices and edges to stdout + Print a listing of all vertices and edges to stdout + + Each vertex is shown with its name, coordinate and component number, + and each edge by its endpoints, cost and data. This is as long as the + graph, unlike :meth:`__str__` and :meth:`__repr__`, which are one line. .. runblock:: pycon @@ -1512,11 +1539,18 @@ def show(self) -> None: >>> g.add_edge(v1, v2) >>> g.show() - :seealso: :meth:`__str__` + .. versionchanged:: 1.1 + Each vertex is shown with its coordinate and component number, + which were what ``repr(g)`` listed before it became one line. + + :seealso: :meth:`__str__` :meth:`plot` """ print("vertices:") for v in self._vertexlist: - print(" " + str(v)) + line = f" {v.name} at {v.coord}" + if v.label is not None: + line += f" component={v.label}" + print(line) print("edges:") for e in self._edges: print(" " + str(e)) @@ -1808,33 +1842,6 @@ def heuristic(self, heuristic: Callable[[NDArray], float] | str) -> None: """ self._heuristic = self._metricfunc(heuristic) - def __repr__(self) -> str: # type: ignore[no-redef] - """ - Detailed representation of the graph, one line per vertex - - :return: one line per vertex showing its name, coordinate and component - :rtype: str - - .. runblock:: pycon - - >>> from pgraph import UGraph - >>> g = UGraph() - >>> v1 = g.add_vertex(coord=[0,0], name='v1') - >>> v2 = g.add_vertex(coord=[1,1], name='v2') - >>> v3 = g.add_vertex(coord=[2,2], name='v3') - >>> g.add_edge(v1, v2) - >>> g.add_edge(v2, v3) - >>> repr(g) - - """ - s = [f"{self.__class__.__name__}:"] - for vertex in self: - ss = f" {vertex.name} at {vertex.coord}" - if vertex.label is not None: - ss += f" component={vertex.label}" - s.append(ss) - return "\n".join(s) - def __getitem__(self, i: int | str | Vertex) -> Vertex: """ Get vertex (base class method) @@ -2528,7 +2535,7 @@ def plot( ... g.add_edge(a, b); >>> g.plot(block=None) - :seealso: :meth:`highlight_path` :meth:`highlight_edge` + :seealso: :meth:`highlight_path` :meth:`highlight_edge` :meth:`show` """ import matplotlib.pyplot as plt from matplotlib.patches import FancyArrowPatch diff --git a/tests/test_graph.py b/tests/test_graph.py index c10df002..a534e39f 100644 --- a/tests/test_graph.py +++ b/tests/test_graph.py @@ -1,4 +1,6 @@ +import contextlib +import io import unittest import numpy as np import numpy.testing as nt @@ -45,11 +47,53 @@ def test_str(self): self.assertEqual(str(g), "DGraph: 2 vertices, 1 edge, 1 component") + # the repr is the one-line summary, not a listing of the vertices + self.assertEqual(repr(g), "DGraph: 2 vertices, 1 edge, 1 component") + + def test_repr_is_one_line_however_big_the_graph(self): + g = UGraph() + for i in range(500): + g.add_vertex([i, i], name=f"v{i}") s = repr(g) - self.assertIsInstance(s, str) - lines = s.split('\n') - self.assertEqual(len(lines), 3) # class-name header + one line per vertex - self.assertEqual(lines[0], "DGraph:") + self.assertNotIn("\n", s) + self.assertEqual(s, str(g)) + self.assertEqual(s, "UGraph: 500 vertices, 0 edges, 500 components") + + def test_show_lists_vertices_and_edges(self): + g = UGraph() + a = g.add_vertex([1, 2], name="a") + b = g.add_vertex([3, 4], name="b") + g.add_vertex([5, 6], name="c") + g.add_edge(a, b, cost=2.5) + + out = io.StringIO() + with contextlib.redirect_stdout(out): + g.show() + lines = out.getvalue().splitlines() + + # a vertex line has the name, the coordinate and the component number, + # which are what the repr used to list; c is a component of its own + self.assertEqual( + lines, + [ + "vertices:", + " a at [1 2] component=0", + " b at [3 4] component=0", + " c at [5 6] component=1", + "edges:", + " Edge{[a] -- [b], cost=2.5}", + ], + ) + + def test_show_a_vertex_without_a_coordinate(self): + g = UGraph() + g.add_vertex(name="x") + + out = io.StringIO() + with contextlib.redirect_stdout(out): + g.show() + + self.assertIn(" x at None", out.getvalue()) def test_str_has_thousands_separators(self): From eb5ff7b9f01c1dca513c0f2197de75104e78affd Mon Sep 17 00:00:00 2001 From: Peter Corke Date: Sat, 31 Oct 2026 11:47:58 +1000 Subject: [PATCH 10/14] refactor: narrow optional edge ends and vertex names with a checked helper Fourteen of the sixteen assert statements in PGraph.py only told mypy that an optional value was set: the ends of an edge (v1 and v2 are None until it is connected) and the name of a vertex (None until it is in a graph). Bandit reports each as B101, and python -O removes them. Add Edge._ends(), which returns both vertices or raises ValueError, and Vertex._require_name(), which returns the name or raises ValueError, in the manner of Graph._require_cost(). They replace the asserts, so the narrowing is still there for mypy and the check is a real one. The two asserts left (the coordinate of a candidate in near(), the graph in Vertex.connect()) are type narrowing too, and are marked # nosec B101. A connected edge behaves as before. An unconnected one, which no graph holds, now raises ValueError from endpoints and next() instead of AssertionError (or, from next(), "should not happen"). Part of #23. Co-Authored-By: Claude Sonnet 5.5 --- src/pgraph/PGraph.py | 117 +++++++++++++++++++++++------------ tests/test_edge_endpoints.py | 37 +++++++++++ tests/test_vertex_init.py | 14 +++++ 3 files changed, 127 insertions(+), 41 deletions(-) diff --git a/src/pgraph/PGraph.py b/src/pgraph/PGraph.py index 72e1c5ac..8d7695fa 100644 --- a/src/pgraph/PGraph.py +++ b/src/pgraph/PGraph.py @@ -1459,14 +1459,14 @@ def remove_vertex(self, vertex: Vertex) -> None: """ if vertex._graph is not self: raise ValueError("vertex does not belong to this graph") - assert vertex.name is not None + name = vertex._require_name() # its own lists name every edge at it, so no need to search the graph for edge in vertex._incident_edges(): self.remove_edge(edge) self._vertexlist.remove(vertex) - del self._vertexdict[vertex.name] + del self._vertexdict[name] vertex._graph = None # it is not in any graph now vertex._label = None # and so not in a component self._connectivitychange = True @@ -2266,7 +2266,8 @@ def near(self, coord: ArrayLike, radius: float) -> list[tuple[Vertex, float]]: found = [] for vertex in candidates: - assert vertex.coord is not None # the candidates all have a position + # type narrowing only: the candidates all have a position + assert vertex.coord is not None # nosec B101 dist = float(self.metric(vertex.coord - coord)) if dist <= radius: found.append((vertex, dist)) @@ -2332,19 +2333,19 @@ def _edge_layout(self) -> tuple[dict[Edge, float], dict[Edge, int]]: groups: dict[frozenset[int], list[Edge]] = {} loops: dict[Vertex, list[Edge]] = {} for e in self._edges: - assert e.v1 is not None and e.v2 is not None - if e.v1 is e.v2: - loops.setdefault(e.v1, []).append(e) + v1, v2 = e._ends() + if v1 is v2: + loops.setdefault(v1, []).append(e) else: - groups.setdefault(frozenset((index[e.v1], index[e.v2])), []).append(e) + groups.setdefault(frozenset((index[v1], index[v2])), []).append(e) rads: dict[Edge, float] = {} for edges in groups.values(): n = len(edges) for k, e in enumerate(edges): - assert e.v1 is not None and e.v2 is not None + v1, v2 = e._ends() offset = (k - (n - 1) / 2) * _ARC_STEP # the same side in space for an edge drawn the other way round - rads[e] = offset if index[e.v1] < index[e.v2] else -offset + rads[e] = offset if index[v1] < index[v2] else -offset loopno = {e: k for edges in loops.values() for k, e in enumerate(edges)} return rads, loopno @@ -2373,8 +2374,7 @@ def _edge_artist( from matplotlib.patches import FancyArrowPatch from matplotlib.transforms import Affine2D, ScaledTranslation from ._plot import _Arrow3D, _Loop3D, _loop_path - v1, v2 = edge.v1, edge.v2 - assert v1 is not None and v2 is not None + v1, v2 = edge._ends() shrink = markersize / 2 + 1 if v1 is v2: radius = _LOOP_RADIUS + _LOOP_GROWTH * loopno @@ -2620,10 +2620,10 @@ def plot( # the edges, each once rads, loopno = self._edge_layout() for e in self._edges: - assert e.v1 is not None + start = e._ends()[0] kwargs = dict(edge_kwargs) if color_components: - kwargs = {**dict(color=color[e.v1.label, :]), **kwargs} + kwargs = {**dict(color=color[start.label, :]), **kwargs} artist = self._edge_artist( ax, e, @@ -2649,10 +2649,8 @@ def plot( ) dx, dy = abs(x1 - x0), abs(y1 - y0) for e in loopno: - assert e.v1 is not None - ax.update_datalim( - [(e.v1.x - dx, e.v1.y - dy), (e.v1.x + dx, e.v1.y + dy)] - ) + v = e._ends()[0] + ax.update_datalim([(v.x - dx, v.y - dy), (v.x + dx, v.y + dy)]) ax.autoscale_view() ax.grid(grid) @@ -3436,11 +3434,11 @@ def incidence(self) -> NDArray: vdict[vertex] = i for j, e in enumerate(edges): - assert e.v1 is not None and e.v2 is not None - I[vdict[e.v1], j] = 1 - I[vdict[e.v2], j] = 1 - if e.v1 is e.v2 and not self.directed: - I[vdict[e.v1], j] = 2 # self-loop, counted at both ends + v1, v2 = e._ends() + I[vdict[v1], j] = 1 + I[vdict[v2], j] = 1 + if v1 is v2 and not self.directed: + I[vdict[v1], j] = 2 # self-loop, counted at both ends return I @@ -3793,8 +3791,7 @@ def path_UCS( parent_names: dict[str, str] = {} for v, p in parent.items(): - assert v.name is not None and p.name is not None - parent_names[v.name] = p.name + parent_names[v._require_name()] = p._require_name() if summary or verbose: print( @@ -3931,8 +3928,7 @@ def path_Astar( parent_names: dict[str, str] = {} for v, p in parent.items(): - assert v.name is not None and p.name is not None - parent_names[v.name] = p.name + parent_names[v._require_name()] = p._require_name() if summary or verbose: print( @@ -3973,9 +3969,9 @@ def _attach(self, edge: Edge) -> None: from either end. A self-loop is therefore held twice by its vertex, which is why it counts 2 towards the degree. """ - assert edge.v1 is not None and edge.v2 is not None - edge.v1._edgelist.append(edge) - edge.v2._edgelist.append(edge) + v1, v2 = edge._ends() + v1._edgelist.append(edge) + v2._edgelist.append(edge) def _detach(self, edge: Edge) -> None: """ @@ -4028,9 +4024,9 @@ def _attach(self, edge: Edge) -> None: The edge goes in the start vertex's list of outgoing edges and in the end vertex's list of incoming ones. """ - assert edge.v1 is not None and edge.v2 is not None - edge.v1._edgelist.append(edge) - edge.v2._inlist.append(edge) + v1, v2 = edge._ends() + v1._edgelist.append(edge) + v2._inlist.append(edge) def _detach(self, edge: Edge) -> None: """ @@ -4203,6 +4199,27 @@ def _set_endpoints(self, v1: Vertex | None, v2: Vertex | None) -> None: self._v1 = v1 self._v2 = v2 + def _ends(self) -> tuple[Vertex, Vertex]: + """ + Both vertices of the edge, raising clearly if it is not connected (private method) + + :raises ValueError: the edge has no vertices + :return: the first and second vertex + :rtype: tuple of Vertex subclass + + ``v1`` and ``v2`` are None for an edge that has not been connected. + Every edge in a graph has both, so the code that works on them takes + them from here, which tells the type checker so, rather than testing + for None at each use. Unlike an ``assert`` this check is not removed + by ``python -O``. + + :seealso: :attr:`v1` :attr:`v2` + """ + v1, v2 = self._v1, self._v2 + if v1 is None or v2 is None: + raise ValueError("the edge is not connected to two vertices") + return v1, v2 + def __reduce__(self) -> Any: """ Refuse to pickle or copy an edge on its own @@ -4334,12 +4351,11 @@ def next(self, vertex: Vertex) -> Vertex: """ - if self.v1 is vertex: - assert self.v2 is not None - return self.v2 - elif self.v2 is vertex: - assert self.v1 is not None - return self.v1 + v1, v2 = self._ends() + if v1 is vertex: + return v2 + elif v2 is vertex: + return v1 else: raise ValueError("should not happen") @@ -4378,8 +4394,7 @@ def endpoints(self) -> list[Vertex]: :seealso: :meth:`vertices` """ - assert self.v1 is not None and self.v2 is not None - return [self.v1, self.v2] + return list(self._ends()) def remove(self) -> None: """ @@ -4804,7 +4819,8 @@ def _bind_edge(self, edge: Edge, dest: Vertex) -> None: endpoints disagree with the vertices' edge lists. """ graph = self._graph - assert graph is not None # connect() has checked + # type narrowing only: connect() has checked + assert graph is not None # nosec B101 if edge.v1 is None and edge.v2 is None: edge._set_endpoints(self, dest) elif not graph._endpoints_match(edge, self, dest): @@ -5141,6 +5157,25 @@ def _incident_edges(self) -> list[Edge]: seen.setdefault(id(e), e) return list(seen.values()) + def _require_name(self) -> str: + """ + The name, raising clearly if the vertex has none (private method) + + :raises ValueError: the vertex has no name + :return: the name + :rtype: str + + A vertex that is not in a graph can have no name, but one in a graph + always has, so the code that works on the vertices of a graph takes + the name from here, which tells the type checker so. Unlike an + ``assert`` this check is not removed by ``python -O``. + + :seealso: :attr:`name` + """ + if self._name is None: + raise ValueError("the vertex has no name") + return self._name + @property def name(self) -> str | None: """ diff --git a/tests/test_edge_endpoints.py b/tests/test_edge_endpoints.py index a31add97..64acfbba 100644 --- a/tests/test_edge_endpoints.py +++ b/tests/test_edge_endpoints.py @@ -120,5 +120,42 @@ def test_repr_shows_the_endpoints_and_an_edge_alone_is_not_copied(self): self.assertEqual((dup.v1.name, dup.v2.name), ("a", "b")) +class TestUnconnected(unittest.TestCase): + """The code that works on both ends of an edge says so if there are none""" + + def test_a_connected_edge_gives_its_ends(self): + g = UGraph() + a = g.add_vertex([0, 0], name="a") + b = g.add_vertex([1, 0], name="b") + e = a.connect(b) + self.assertEqual(e.endpoints, [a, b]) + self.assertIs(e.next(a), b) + self.assertIs(e.next(b), a) + + def test_an_edge_with_no_vertices_raises_clearly(self): + e = Edge() + self.assertIsNone(e.v1) + self.assertIsNone(e.v2) + v = UGraph().add_vertex([0, 0], name="a") + for name, call in ( + ("_ends", e._ends), + ("endpoints", lambda: e.endpoints), + ("next", lambda: e.next(v)), + ): + with self.subTest(name=name): + with self.assertRaises(ValueError) as cm: + call() + self.assertIn("not connected", str(cm.exception)) + + def test_next_of_a_vertex_that_is_not_an_end(self): + g = UGraph() + a = g.add_vertex([0, 0], name="a") + b = g.add_vertex([1, 0], name="b") + c = g.add_vertex([2, 0], name="c") + e = a.connect(b) + with self.assertRaises(ValueError): + e.next(c) + + if __name__ == "__main__": unittest.main() diff --git a/tests/test_vertex_init.py b/tests/test_vertex_init.py index 9a4a3cf7..2fc76b12 100644 --- a/tests/test_vertex_init.py +++ b/tests/test_vertex_init.py @@ -161,5 +161,19 @@ def test_assigning_other_attributes_is_not_a_change(self): self.assertFalse(g._spatialchange) +class TestRequireName(unittest.TestCase): + """The code that works on the vertices of a graph takes their names from here""" + + def test_a_named_vertex_gives_its_name(self): + self.assertEqual(Vertex(name="a")._require_name(), "a") + # a vertex in a graph always has one: the default is "#0", "#1", ... + self.assertEqual(UGraph().add_vertex()._require_name(), "#0") + + def test_a_vertex_with_no_name_raises_clearly(self): + with self.assertRaises(ValueError) as cm: + Vertex()._require_name() + self.assertIn("no name", str(cm.exception)) + + if __name__ == "__main__": unittest.main() From 347b7c80a8b1f42c2c668f2bded409aff58f0a90 Mon Sep 17 00:00:00 2001 From: Peter Corke Date: Sat, 31 Oct 2026 11:49:34 +1000 Subject: [PATCH 11/14] chore: housekeeping leftovers from the Codacy cleanup - Delete posegraph.py, a 2020 prototype in the repository root that nothing uses: it imports the deprecated UVertex, has a stub method and debug prints, and needs itertools.pairwise (Python 3.10) in a package that supports 3.9. The Robotics Toolbox has the real PoseGraph. - examples/create_json.py: pop('dgoal', None) instead of a bare except. - Pin the two remaining third-party GitHub Actions to commit SHAs with the version in a comment, as RTB did in petercorke/robotics-toolbox-python#892: codecov/codecov-action v7.1.1 and dependabot/fetch-metadata v3.1.0. They are the commits that @v7 and @v3 point to today, so what runs is unchanged. GitHub's own actions/* stay on tags, and Dependabot updates a pinned SHA with its comment. - Ignore build/ as well as docs/build and dist/. Part of #23. Co-Authored-By: Claude Sonnet 5.5 --- .github/workflows/ci.yml | 2 +- .github/workflows/dependabot-auto-merge.yml | 2 +- .gitignore | 1 + examples/create_json.py | 5 +- posegraph.py | 105 -------------------- 5 files changed, 4 insertions(+), 111 deletions(-) delete mode 100644 posegraph.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 8af21b81..b71893d0 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -76,7 +76,7 @@ jobs: pytest --cov=pgraph --cov-report=xml:coverage.xml coverage report - name: Upload coverage to Codecov - uses: codecov/codecov-action@v7 + uses: codecov/codecov-action@303a32d7a59b442fa8d48b6a1cc6825c09c847a5 # v7.1.1 with: files: ./coverage.xml verbose: true diff --git a/.github/workflows/dependabot-auto-merge.yml b/.github/workflows/dependabot-auto-merge.yml index 8de7f45f..24f8d0d5 100644 --- a/.github/workflows/dependabot-auto-merge.yml +++ b/.github/workflows/dependabot-auto-merge.yml @@ -13,7 +13,7 @@ jobs: steps: - name: Dependabot metadata id: metadata - uses: dependabot/fetch-metadata@v3 + uses: dependabot/fetch-metadata@25dd0e34f4fe68f24cc83900b1fe3fe149efef98 # v3.1.0 with: github-token: "${{ secrets.GITHUB_TOKEN }}" diff --git a/.gitignore b/.gitignore index 16f919da..ddf82baf 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,4 @@ +build/ docs/build dist/ *.code-workspace diff --git a/examples/create_json.py b/examples/create_json.py index 88e4bef9..d2b0a404 100644 --- a/examples/create_json.py +++ b/examples/create_json.py @@ -15,10 +15,7 @@ del info['y'] del info['dbne'] del info['utmzone'] - try: - del info['dgoal'] - except: - pass + info.pop('dgoal', None) # not every place has one info['utm'] = [info['utm'][0] / 1000, info['utm'][1] / 1000] routes = [] diff --git a/posegraph.py b/posegraph.py deleted file mode 100644 index db908dee..00000000 --- a/posegraph.py +++ /dev/null @@ -1,105 +0,0 @@ -from pgraph import UGraph, UVertex, Edge -import itertools - - -class Frame(UVertex): - def __str__(self): - return f"Frame: {self.name}" - - def __repr__(self): - return self.__str__() - - def neighbours(self): - """ - Neighbours of a vertex - - ``v.neighbours()`` is a list of neighbours of this vertex. - - .. note:: For a directed graph the neighbours are those on edges leaving this vertex - """ - return [e.next(self) for e in self._edgelist] - - -class Transform(Edge): - - def __str__(self): - return f"Transform: {self.v1.name}:{self.v2.name} # [{self.data.strline()}]" - - def set(self, x): - self.data = x - - -class PoseGraph(UGraph): - - def __init__(self): - super().__init__() - self.frames = {} - self.transforms = {} - self.cache = {} - self.dirty = False - - def add_frame(self, name): - f = Frame(name=name) - self.frames[name] = f - self.add_vertex(f) - return f - - def set_transform(self, x, f1, f2): - if isinstance(f1, str): - f1 = self.frames[f1] - if isinstance(f2, str): - f2 = self.frames[f2] - - T = Transform(f1, f2, cost=1, data=x) - f1.connect(f2, edge=T) - return T - - def transform(self, start, end): - # key = (frm, to) - # if key not in self.cache: - # self.cache[key] = self.compute_transform(frm, to) - # return self.cache[key] - vertices, len = self.path_BFS(start, end) - edges = [] - for first, next in itertools.pairwise(vertices): - e = first.edgeto(next) - if e.v1 == next: - edges.append((e, False)) - elif e.v2 == next: - edges.append((e, True)) - - print(vertices) - print(edges) - - def map(self, frm, to): - pass - - -if __name__ == "__main__": - - from spatialmath import SE3 - - pg = PoseGraph() - f1 = pg.add_frame("frame1") - f2 = pg.add_frame("frame2") - f3 = pg.add_frame("frame3") - f4 = pg.add_frame("frame4") - - print(pg) - - x = SE3() - print(x) - - t12 = pg.set_transform(x, f1, f2) - t13 = pg.set_transform(x, "frame1", "frame3") - - print(pg) - - print(f1) - print(t12) - - t12.set(SE3.Trans(1, 2, 3)) - - x = pg.transform(start=f2, end=f3) # keeps a cache of paths - print(x) - # P3 = g.map(p1, from=f1, to=f From 03fdd8b679b286cad5a5964f32ccac3d3dfaeb47 Mon Sep 17 00:00:00 2001 From: Peter Corke Date: Sat, 31 Oct 2026 13:30:26 +1000 Subject: [PATCH 12/14] =?UTF-8?q?feat(edge):=20show=20=E2=86=94=20and=20?= =?UTF-8?q?=E2=86=92=20between=20the=20ends=20of=20an=20edge?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Edge.__str__ (and so repr) used "--" and "->". Use ↔ for an undirected edge and → for a directed one. The DOT exporter is unchanged: GraphViz needs ASCII. The saved outputs in examples/roads.ipynb are updated. Fixes #76 Co-Authored-By: Claude Sonnet 5.5 --- examples/roads.ipynb | 58 ++++++++++++++++++------------------- src/pgraph/PGraph.py | 10 ++++++- tests/test_unified_graph.py | 11 +++++-- 3 files changed, 46 insertions(+), 33 deletions(-) diff --git a/examples/roads.ipynb b/examples/roads.ipynb index 081e72f9..e640e4cb 100644 --- a/examples/roads.ipynb +++ b/examples/roads.ipynb @@ -187,35 +187,35 @@ "name": "stdout", "output_type": "stream", "text": [ - "Edge{[Camooweal] -- [Mount Isa], cost=188}\n", - "Edge{[Mount Isa] -- [Cloncurry], cost=118}\n", - "Edge{[Cloncurry] -- [Hughenden], cost=401}\n", - "Edge{[Cloncurry] -- [Winton], cost=350}\n", - "Edge{[Hughenden] -- [Charters Towers], cost=248}\n", - "Edge{[Charters Towers] -- [Townsville], cost=135}\n", - "Edge{[Townsville] -- [Mackay], cost=388}\n", - "Edge{[Mackay] -- [Rockhampton], cost=334}\n", - "Edge{[Mackay] -- [Emerald], cost=384}\n", - "Edge{[Rockhampton] -- [Brisbane], cost=682}\n", - "Edge{[Rockhampton] -- [Emerald], cost=270}\n", - "Edge{[Brisbane] -- [Roma], cost=482}\n", - "Edge{[Roma] -- [Charleville], cost=266}\n", - "Edge{[Charleville] -- [Blackall], cost=305}\n", - "Edge{[Blackall] -- [Barcaldine], cost=106}\n", - "Edge{[Blackall] -- [Windorah], cost=530}\n", - "Edge{[Barcaldine] -- [Emerald], cost=307}\n", - "Edge{[Barcaldine] -- [Hughenden], cost=500}\n", - "Edge{[Barcaldine] -- [Longreach], cost=106}\n", - "Edge{[Longreach] -- [Windorah], cost=311}\n", - "Edge{[Longreach] -- [Winton], cost=180}\n", - "Edge{[Winton] -- [Hughenden], cost=216}\n", - "Edge{[Winton] -- [Boulia], cost=363}\n", - "Edge{[Winton] -- [Windorah], cost=487}\n", - "Edge{[Boulia] -- [Mount Isa], cost=304}\n", - "Edge{[Boulia] -- [Bedourie], cost=194}\n", - "Edge{[Bedourie] -- [Birdsville], cost=193}\n", - "Edge{[Birdsville] -- [Windorah], cost=380}\n", - "Edge{[Bedourie] -- [Windorah], cost=411}\n" + "Edge{[Camooweal] ↔ [Mount Isa], cost=188}\n", + "Edge{[Mount Isa] ↔ [Cloncurry], cost=118}\n", + "Edge{[Cloncurry] ↔ [Hughenden], cost=401}\n", + "Edge{[Cloncurry] ↔ [Winton], cost=350}\n", + "Edge{[Hughenden] ↔ [Charters Towers], cost=248}\n", + "Edge{[Charters Towers] ↔ [Townsville], cost=135}\n", + "Edge{[Townsville] ↔ [Mackay], cost=388}\n", + "Edge{[Mackay] ↔ [Rockhampton], cost=334}\n", + "Edge{[Mackay] ↔ [Emerald], cost=384}\n", + "Edge{[Rockhampton] ↔ [Brisbane], cost=682}\n", + "Edge{[Rockhampton] ↔ [Emerald], cost=270}\n", + "Edge{[Brisbane] ↔ [Roma], cost=482}\n", + "Edge{[Roma] ↔ [Charleville], cost=266}\n", + "Edge{[Charleville] ↔ [Blackall], cost=305}\n", + "Edge{[Blackall] ↔ [Barcaldine], cost=106}\n", + "Edge{[Blackall] ↔ [Windorah], cost=530}\n", + "Edge{[Barcaldine] ↔ [Emerald], cost=307}\n", + "Edge{[Barcaldine] ↔ [Hughenden], cost=500}\n", + "Edge{[Barcaldine] ↔ [Longreach], cost=106}\n", + "Edge{[Longreach] ↔ [Windorah], cost=311}\n", + "Edge{[Longreach] ↔ [Winton], cost=180}\n", + "Edge{[Winton] ↔ [Hughenden], cost=216}\n", + "Edge{[Winton] ↔ [Boulia], cost=363}\n", + "Edge{[Winton] ↔ [Windorah], cost=487}\n", + "Edge{[Boulia] ↔ [Mount Isa], cost=304}\n", + "Edge{[Boulia] ↔ [Bedourie], cost=194}\n", + "Edge{[Bedourie] ↔ [Birdsville], cost=193}\n", + "Edge{[Birdsville] ↔ [Windorah], cost=380}\n", + "Edge{[Bedourie] ↔ [Windorah], cost=411}\n" ] } ], diff --git a/src/pgraph/PGraph.py b/src/pgraph/PGraph.py index 72e1c5ac..0785d855 100644 --- a/src/pgraph/PGraph.py +++ b/src/pgraph/PGraph.py @@ -4241,6 +4241,9 @@ def __str__(self) -> str: :return: endpoints, cost and optional data :rtype: str + The endpoints are separated by ``→`` if the edge is in a directed graph + and by ``↔`` otherwise. + .. runblock:: pycon >>> from pgraph import Vertex, Edge @@ -4249,10 +4252,15 @@ def __str__(self) -> str: >>> e = Edge(v1, v2, cost=5.0, data="A to B") >>> str(e) + .. versionchanged:: 1.1 + The separator was ``--`` or ``->``. Output redirected to a file or pipe + under a legacy Windows code page (cp1252) can raise + ``UnicodeEncodeError``; set ``PYTHONUTF8=1`` to avoid it. + :seealso: :meth:`__repr__` """ graph = self.v1._graph if self.v1 is not None else None - arrow = "->" if graph is not None and graph.directed else "--" + arrow = "→" if graph is not None and graph.directed else "↔" cost_str = "None" if self.cost is None else f"{self.cost:.4g}" s = f"{self.__class__.__name__}{{{self.v1} {arrow} {self.v2}, cost={cost_str}}}" if self.data is not None: diff --git a/tests/test_unified_graph.py b/tests/test_unified_graph.py index 72016c72..4b2acdf7 100644 --- a/tests/test_unified_graph.py +++ b/tests/test_unified_graph.py @@ -251,14 +251,19 @@ def test_other_names_in_the_module_are_errors(self): class TestEdgeArrow(unittest.TestCase): def test_arrow_follows_the_graph(self): - for flag, arrow in ((False, "--"), (True, "->")): + for flag, expected in ( + (False, "Edge{[a] ↔ [b], cost=3}"), + (True, "Edge{[a] → [b], cost=3}"), + ): g = Graph(directed=flag) a, b = g.add_vertex(name="a"), g.add_vertex(name="b") - self.assertIn(arrow, str(g.add_edge(a, b))) + e = g.add_edge(a, b, cost=3) + self.assertEqual(str(e), expected) + self.assertEqual(repr(e), expected) def test_a_standalone_edge_has_no_arrow_to_show(self): e = Edge(Vertex(name="a"), Vertex(name="b"), cost=1) - self.assertIn("--", str(e)) + self.assertEqual(str(e), "Edge{[a] ↔ [b], cost=1}") if __name__ == "__main__": From bd045d7abebef4746c8cc4e64d02cc30c79db087 Mon Sep 17 00:00:00 2001 From: Peter Corke Date: Sat, 31 Oct 2026 13:48:41 +1000 Subject: [PATCH 13/14] test: show() expects the new edge arrow Co-Authored-By: Claude Sonnet 5.5 --- tests/test_graph.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/test_graph.py b/tests/test_graph.py index a534e39f..f5a716df 100644 --- a/tests/test_graph.py +++ b/tests/test_graph.py @@ -81,7 +81,7 @@ def test_show_lists_vertices_and_edges(self): " b at [3 4] component=0", " c at [5 6] component=1", "edges:", - " Edge{[a] -- [b], cost=2.5}", + " Edge{[a] ↔ [b], cost=2.5}", ], ) From 0c33e9b0c4c7795847b5f7ed45ba041fef20bd98 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Sun, 1 Nov 2026 07:46:36 +0000 Subject: [PATCH 14/14] chore(deps): bump pypa/gh-action-pypi-publish from 1.14.2 to 1.14.3 Bumps [pypa/gh-action-pypi-publish](https://github.com/pypa/gh-action-pypi-publish) from 1.14.2 to 1.14.3. - [Release notes](https://github.com/pypa/gh-action-pypi-publish/releases) - [Commits](https://github.com/pypa/gh-action-pypi-publish/compare/dc37677b2e1c63e2034f94d8a5b11f265b73ba33...7245906fb61fa33a13554f9d5fb856fe61758086) --- updated-dependencies: - dependency-name: pypa/gh-action-pypi-publish dependency-version: 1.14.3 dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- .github/workflows/publish.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index 6d0f1da2..fb1922ac 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -110,6 +110,6 @@ jobs: path: dist # pinned to a commit, as this action can publish to PyPI; dependabot updates it - - uses: pypa/gh-action-pypi-publish@dc37677b2e1c63e2034f94d8a5b11f265b73ba33 # v1.14.2 + - uses: pypa/gh-action-pypi-publish@7245906fb61fa33a13554f9d5fb856fe61758086 # v1.14.3 with: skip-existing: true