-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathPGraph.py
More file actions
3201 lines (2559 loc) · 106 KB
/
Copy pathPGraph.py
File metadata and controls
3201 lines (2559 loc) · 106 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import annotations
from abc import ABC, abstractmethod
import sys
import warnings
import numpy as np
import matplotlib.pyplot as plt
import copy
from collections.abc import Iterable, Iterator
import tempfile
import subprocess
import webbrowser
from typing import Any, Callable, ClassVar
from numpy.typing import ArrayLike, NDArray
from spatialmath.base.graphics import axes_logic
class _BaseGraph(ABC):
#: concrete vertex type for this graph kind, provided by :class:`UGraph`
#: and :class:`DGraph` -- lets :meth:`add_vertex` and :meth:`vertex_copy`
#: be defined once here rather than duplicated per subclass.
_vertex_cls: ClassVar[type[BaseVertex]]
def __init__(
self,
metric: Callable[[NDArray], float] | str | None = None,
heuristic: Callable[[NDArray], float] | str | None = None,
verbose: bool = False,
dim: int | None = None,
):
"""
Abstract base class for graphs
:param metric: distance metric, defaults to "L2"
:type metric: callable or str, optional
:param heuristic: heuristic distance metric for A*, defaults to the
same as ``metric``
:type heuristic: callable or str, optional
:param verbose: print diagnostic information as vertices/edges are
added, defaults to False
:param dim: required length of every vertex's ``coord``, defaults to
None (unconstrained -- vertices may have coordinates of any
length, or none at all)
:type dim: int, optional
:raises ValueError: ``dim`` is given but is not a positive integer
This is the common base class of :class:`UGraph` and :class:`DGraph`
and should not be instantiated directly.
:seealso: :class:`UGraph` :class:`DGraph` :meth:`add_vertex`
"""
if dim is not None and dim <= 0:
raise ValueError(f"dim must be a positive integer, got {dim!r}")
# we use a list and a dict, the list respects the order of adding
self._vertexlist: list[BaseVertex] = []
self._vertexdict: dict[str, BaseVertex] = {}
self._edgelist: set[Edge] = set()
self._verbose = verbose
self._dim = dim
self._ncomponents = 0
self._connectivitychange = False
if metric is None:
self.metric = "L2"
else:
self.metric = metric
if heuristic is None:
self.heuristic = self.metric
else:
self.heuristic = heuristic
def __str__(self) -> str:
"""
Human-readable summary of the graph
:return: one-line summary of vertex/edge/component counts
: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)
>>> str(g)
:seealso: :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.
return str(self)
@classmethod
def Dict(cls, d: dict, reverse: bool = False) -> _BaseGraph:
"""
Create graph from parent/child dictionary
:param d: dictionary that maps from ``BaseVertex`` subclass to ``BaseVertex`` subclass
:type d: dict
:param reverse: reverse link direction, defaults to False
:return: graph
:rtype: UGraph or DGraph
Behaves like a constructor for a ``DGraph`` or ``UGraph`` from a
dictionary that maps vertices to parents. From this information it
can create a tree graph.
By default parent vertices are linked their children. If ``reverse`` is
True then children are linked to their parents.
.. runblock:: pycon
>>> from pgraph import UGraph
>>> d = {'b': 'a', 'c': 'a', 'd': 'b'}
>>> g = UGraph.Dict(d)
>>> print(g)
:seealso: :meth:`Adjacency`
"""
g = cls()
for vertex, parent in d.items():
if isinstance(vertex, str):
vertex_name = vertex
else:
vertex_name = vertex.name
if vertex_name in g:
vertex = g[vertex_name]
else:
vertex = g.add_vertex(name=vertex_name)
if isinstance(parent, str):
parent_name = parent
else:
parent_name = parent.name
if parent_name in g:
parent = g[parent_name]
else:
parent = g.add_vertex(name=parent_name)
if reverse:
g.add_edge(vertex, parent)
else:
g.add_edge(parent, vertex)
return g
@classmethod
def Adjacency(
cls,
A: NDArray,
coords: NDArray | None = None,
names: list[str] | None = None,
) -> _BaseGraph:
"""
Create graph from adjacency matrix
:param A: adjacency matrix
:type A: ndarray(N,N)
:param coords: coordinates of vertices, defaults to None
:type coords: ndarray(N,M), optional
:param names: names of vertices, defaults to None
:type names: list(N) of str, optional
:return: graph
:rtype: UGraph or DGraph
Create a directed or undirected graph where non-zero elements ``A[i,j]``
correspond to edges from vertex ``i`` to vertex ``j``.
.. warning:: For undirected graph ``A`` should be symmetric but this
is not checked. Only the upper triangular part is used.
.. runblock:: pycon
>>> from pgraph import UGraph
>>> import numpy as np
>>> A = np.array([[0, 1, 0], [1, 0, 1], [0, 1, 0]])
>>> g = UGraph.Adjacency(A)
>>> print(g)
:seealso: :meth:`Dict` :meth:`adjacency`
"""
if A.shape[0] != A.shape[1]:
raise ValueError("Adjacency matrix must be square")
if names is not None and len(names) != A.shape[0]:
raise ValueError("length of names must match dimension of adjacency matrix")
if coords is not None and coords.shape[0] != A.shape[0]:
raise ValueError("coords must have same number of rows as adjacency matrix")
g = cls()
name = None
coord = None
for i in range(A.shape[0]):
if names is not None:
name = names[i]
if coords is not None:
coord = coords[i, :]
g.add_vertex(name=name, coord=coord)
if isinstance(g, UGraph):
# undirected graph
for i in range(A.shape[0]):
for j in range(i + 1, A.shape[1]):
if A[i, j] > 0:
g[i].connect(g[j], cost=A[i, j])
else:
# directed graph
for i in range(A.shape[0]):
for j in range(A.shape[1]):
if A[i, j] > 0:
if i == j:
raise ValueError("loops in graph not supported")
g[i].connect(g[j], cost=A[i, j])
return g
def copy(self) -> _BaseGraph:
"""
Deepcopy of graph
:return: deep copy
:rtype: _BaseGraph
.. runblock:: pycon
>>> from pgraph import UGraph
>>> g = UGraph()
>>> v1 = g.add_vertex(coord=[0,0], name='v1')
>>> g2 = g.copy()
>>> g2 is g
>>> g2[0] is g[0]
"""
return copy.deepcopy(self)
def add_vertex(
self, coord: ArrayLike | BaseVertex | None = None, name: str | None = None
) -> BaseVertex:
"""
Add a vertex to the graph
:param coord: coordinate for an embedded graph, or an existing vertex
of this graph's own kind (``UVertex`` for :class:`UGraph`,
``DVertex`` for :class:`DGraph`) to add as-is, defaults to None
:type coord: array-like or BaseVertex subclass, optional
:param name: name of vertex, defaults to "#i"
:type name: str, optional
:raises TypeError: ``coord`` is a ``BaseVertex`` of the wrong kind
:raises ValueError: the graph was constructed with ``dim``, and
``coord`` is given but its length doesn't match
:return: the added vertex
:rtype: BaseVertex subclass
- ``g.add_vertex()`` creates a new vertex with optional ``coord`` and
``name``.
- ``g.add_vertex(v)`` takes an instance or subclass of this graph's
own vertex kind and adds it to the graph.
If the vertex has no name and ``name`` is None give it a default name
``#N`` where ``N`` is a consecutive integer.
The vertex is placed into a dictionary with a key equal to its name.
This single implementation, shared by :class:`UGraph` and
:class:`DGraph`, is parameterized by each subclass's
:attr:`_vertex_cls` rather than duplicated per subclass -- see
:doc:`policy` for why that matters.
.. runblock:: pycon
>>> from pgraph import UGraph, UVertex
>>> g = UGraph()
>>> v1 = g.add_vertex(coord=[0,0])
>>> print(v1.name)
>>> v2 = g.add_vertex(UVertex(coord=[1,1], name='v2'))
>>> print(v2.name)
If the graph was constructed with a required ``dim`` (see
:meth:`_BaseGraph.__init__`), every embedded vertex must have a
coordinate of exactly that length -- adding one of the wrong length
raises ``ValueError``:
.. runblock:: pycon
>>> from pgraph import UGraph
>>> g = UGraph(dim=6)
>>> v1 = g.add_vertex(coord=[0, 0, 0, 0, 0, 0], name='pose1')
>>> print(v1)
:seealso: :meth:`vertex_copy`
"""
if isinstance(coord, self._vertex_cls):
vertex = coord
elif isinstance(coord, BaseVertex):
raise TypeError(
f"expecting {self._vertex_cls.__name__} or coordinate data, "
f"got {type(coord).__name__}"
)
else:
vertex = self._vertex_cls(coord, name=name)
if (
self._dim is not None
and vertex.coord is not None
and len(vertex.coord) != self._dim
):
raise ValueError(
f"vertex coord has length {len(vertex.coord)}, "
f"but this graph requires dim={self._dim}"
)
if name is None:
name = vertex.name
if name is None:
name = f"#{len(self._vertexlist)}"
vertex.name = name
self._vertexlist.append(vertex)
self._vertexdict[vertex.name] = vertex
if self._verbose:
print(f"New vertex {vertex.name}: {vertex.coord}")
vertex._graph = self
self._connectivitychange = True
return vertex
@classmethod
def vertex_copy(cls, vertex: BaseVertex) -> BaseVertex:
"""
Copy a vertex for use in a new graph of this kind
:param vertex: vertex to copy
:type vertex: BaseVertex subclass
:return: new, unconnected vertex with the same coordinate and name
:rtype: BaseVertex subclass
A vertex can only belong to a single graph, so this method is used to
create a new vertex with the same name and coordinates for inclusion
in a new graph -- of ``cls``'s own vertex kind, per :attr:`_vertex_cls`.
.. runblock:: pycon
>>> from pgraph import UGraph, DGraph
>>> g = UGraph()
>>> v = g.add_vertex(coord=[1,2], name='v1')
>>> newv = DGraph.vertex_copy(v)
>>> print(newv)
:seealso: :meth:`BaseVertex.copy`
"""
return cls._vertex_cls(coord=vertex.coord, name=vertex.name)
def _resolve_vertex(self, v: BaseVertex | str, label: str) -> BaseVertex:
"""
Resolve a vertex given by reference or name (private method)
:param v: vertex, or the name of a vertex in this graph
:type v: BaseVertex subclass or str
:param label: parameter name to use in the error message, e.g. "start"
:raises TypeError: ``v`` is neither a ``BaseVertex`` nor a string
:return: the resolved vertex
:rtype: BaseVertex subclass
Used by :meth:`add_edge`, :meth:`path_BFS`, :meth:`path_UCS` and
:meth:`path_Astar` for their vertex-or-name parameters -- previously
each method duplicated this check inline, which had let a
copy-paste mistake (checking the wrong parameter's type in the
error-raising branch) slip into all three path-finding methods
unnoticed.
"""
if isinstance(v, str):
return self[v]
elif isinstance(v, BaseVertex):
return v
else:
raise TypeError(f"{label} must be BaseVertex subclass or string name")
def _require_cost(self, edge: Edge) -> float:
"""
Get an edge's cost, raising clearly if it hasn't been set (private method)
:param edge: the edge
:raises ValueError: ``edge.cost`` is None
:return: the edge's cost
:rtype: float
``Edge.cost`` is None when it could not be auto-computed (the edge
was created outside a graph, or without vertex coordinates) and no
explicit cost was given. Every method that does arithmetic with edge
costs -- :meth:`distance`, :meth:`path_BFS`, :meth:`path_UCS`,
:meth:`path_Astar` -- calls this rather than reading ``edge.cost``
directly, so a missing cost fails clearly at the point of use
instead of with a bare ``TypeError`` deep inside a search loop.
If you want an edge that is present but deliberately unusable for
path planning or distance calculations, set its cost to
``float("inf")`` explicitly -- ``None`` means "not set", not
"infinite".
:seealso: :meth:`Edge`
"""
if edge.cost is None:
raise ValueError(
f"{edge} has no cost -- set an explicit cost, or "
"float('inf') to mark it unusable for path planning"
)
return edge.cost
def add_edge(self, v1: BaseVertex | str, v2: BaseVertex | str, **kwargs: Any) -> Edge:
"""
Add an edge to the graph (base class method)
:param v1: first vertex (start if a directed graph)
:type v1: BaseVertex subclass or str
:param v2: second vertex (end if a directed graph)
:type v2: BaseVertex subclass or str
:param kwargs: optional arguments to pass to ``BaseVertex.connect``
:return: edge
:rtype: Edge
Create an edge between a vertex pair and adds it to the graph.
This is a graph centric way of creating an edge. The
alternative is the ``connect`` method of a vertex.
.. 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')
>>> e = g.add_edge(v1, v2)
>>> print(e)
>>> e2 = g.add_edge('v2', 'v3', cost=99)
>>> print(e2)
:seealso: :meth:`Edge.connect` :meth:`BaseVertex.connect`
"""
v1 = self._resolve_vertex(v1, "v1")
v2 = self._resolve_vertex(v2, "v2")
if self._verbose:
print(f"New edge from {v1.name} to {v2.name}")
return v1.connect(v2, **kwargs)
def remove_edge(self, edge: Edge) -> None:
"""
Remove an edge from the graph
:param edge: edge to remove
:raises ValueError: ``edge`` does not belong to this graph
The edge is removed from this graph's own edge collection and from
the edge lists of its connected vertices, and ``edge.v1``/``edge.v2``
are cleared to ``None``.
.. warning:: The connectivity of the network may be changed.
.. note:: A directed edge is tracked only by its source vertex's
edge list, not its target's (see :attr:`BaseVertex.edges`), so
membership is checked per endpoint rather than assumed for both
-- removing a directed edge from an undirected-only
implementation would otherwise raise ``ValueError`` on the
target side.
.. 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')
>>> e = g.add_edge(v1, v2)
>>> g.remove_edge(e)
>>> print(g)
:seealso: :meth:`remove_vertex` :meth:`Edge.remove`
"""
if edge not in self._edgelist:
raise ValueError("edge does not belong to this graph")
assert edge.v1 is not None and edge.v2 is not None
if edge in edge.v1._edgelist:
edge.v1._edgelist.remove(edge)
if edge in edge.v2._edgelist:
edge.v2._edgelist.remove(edge)
edge.v1._connectivitychange = True
edge.v2._connectivitychange = True
self._connectivitychange = True
edge.v1 = None
edge.v2 = None
self._edgelist.remove(edge)
def remove_vertex(self, vertex: BaseVertex) -> None:
"""
Remove a vertex, and all its edges, from the graph
:param vertex: vertex to remove
:raises ValueError: ``vertex`` does not belong to this graph
Every edge touching ``vertex`` -- incoming or outgoing -- is removed
via :meth:`remove_edge`, then the vertex itself is removed.
.. warning:: The connectivity of the network may be changed.
.. note:: This scans the graph's own edge set for edges touching
``vertex``, rather than iterating ``vertex.edges()`` --
for a ``DGraph`` vertex that only ever reports outgoing edges
(see :attr:`BaseVertex.edges`), so incoming edges would
otherwise be missed and left dangling.
.. 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)
>>> g.remove_vertex(v2)
>>> print(g)
:seealso: :meth:`remove_edge` :meth:`BaseVertex.remove`
"""
if vertex._graph is not self:
raise ValueError("vertex does not belong to this graph")
assert vertex.name is not None
for edge in [e for e in self._edgelist if e.v1 is vertex or e.v2 is vertex]:
self.remove_edge(edge)
self._vertexlist.remove(vertex)
del self._vertexdict[vertex.name]
def remove(self, x: Edge | BaseVertex) -> None:
"""
Remove element from graph (deprecated)
:param x: element to remove from graph
:type x: Edge or BaseVertex subclass
:raises TypeError: unknown type
.. deprecated:: use :meth:`remove_edge` or :meth:`remove_vertex`
instead -- this dispatched on ``type(x)`` to two operations with
very different blast radii (detach one edge, vs. cascade-remove
everything touching a vertex) hidden behind one ambiguous name.
:seealso: :meth:`remove_edge` :meth:`remove_vertex`
"""
warnings.warn(
"remove() is deprecated, use remove_edge() or remove_vertex() instead",
DeprecationWarning,
stacklevel=2,
)
if isinstance(x, Edge):
self.remove_edge(x)
elif isinstance(x, BaseVertex):
self.remove_vertex(x)
else:
raise TypeError("expecting Edge or BaseVertex")
def show(self) -> None:
"""
Print a summary of all vertices and edges to stdout
.. 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)
>>> g.show()
:seealso: :meth:`__str__`
"""
print("vertices:")
for v in self._vertexlist:
print(" " + str(v))
print("edges:")
for e in self._edgelist:
print(" " + str(e))
@property
def n(self) -> int:
"""
Number of vertices
:return: Number of vertices
:rtype: int
.. runblock:: pycon
>>> from pgraph import UGraph
>>> g = UGraph()
>>> g.add_vertex(name='v1')
>>> g.add_vertex(name='v2')
>>> print(g.n)
"""
return len(self._vertexdict)
@property
def ne(self) -> int:
"""
Number of edges
:return: Number of vertices
:rtype: int
.. runblock:: pycon
>>> from pgraph import UGraph
>>> g = UGraph()
>>> v1 = g.add_vertex(name='v1')
>>> v2 = g.add_vertex(name='v2')
>>> g.add_edge(v1, v2)
>>> print(g.ne)
"""
return len(self._edgelist)
@abstractmethod
def _graphcolor(self) -> int | None:
"""
Color the graph (subclass method)
Concrete graph coloring algorithm, provided by :meth:`UGraph._graphcolor`
and :meth:`DGraph._graphcolor`.
"""
@property
def nc(self) -> int:
"""
Number of components
:return: Number of components
:rtype: int
.. note::
- Components are labeled from 0 to ``g.nc-1``.
- A graph coloring algorithm is run if the graph connectivity
has changed.
.. note:: A lazy approach is used, and if a connectivity changing
operation has been performed since the last call, the graph
coloring algorithm is run which is potentially expensive for
a large graph.
.. runblock:: pycon
>>> from pgraph import UGraph
>>> g = UGraph()
>>> v1 = g.add_vertex(name='v1')
>>> v2 = g.add_vertex(name='v2')
>>> v3 = g.add_vertex(name='v3')
>>> g.add_edge(v1, v2)
>>> print(g.nc)
"""
n = self._graphcolor()
if n is not None:
self._ncomponents = n
return self._ncomponents
def _metricfunc(self, metric: Callable[[NDArray], float] | str) -> Callable[[NDArray], float]:
"""
Resolve a metric name or callable to a callable (private method)
:param metric: distance metric, a callable or one of "L1", "L2", "SE2"
:raises ValueError: ``metric`` is a string other than "L1"/"L2"/"SE2",
or is neither callable nor a string
:return: the resolved distance metric callable
:rtype: callable
The returned callable takes a single coordinate-difference vector
(shape ``(n,)``) and returns a scalar distance -- never a list or
array of multiple vectors. That vector is always the difference
between one vertex's ``coord`` and either another vertex's ``coord``
or an arbitrary point supplied by the caller (see :meth:`closest` and
:meth:`BaseVertex.distance`).
If ``metric`` is already a callable matching this signature, it is
returned unchanged. Otherwise it must be one of the built-in names
"L1", "L2", "SE2" (see :meth:`metric` for their definitions).
:seealso: :meth:`metric` :meth:`heuristic`
"""
def L1(v):
return np.linalg.norm(v, 1)
def L2(v):
return np.linalg.norm(v)
def SE2(v):
if len(v) != 3:
raise ValueError(
f"SE2 metric requires a 3-element (x, y, theta) vector, got length {len(v)}"
)
# wrap angle to range [-pi, pi)
v[2] = (v[2] + np.pi) % (2 * np.pi) - np.pi
return np.linalg.norm(v)
if callable(metric):
return metric
elif isinstance(metric, str):
if metric == "L1":
return L1
elif metric == "L2":
return L2
elif metric == "SE2":
return SE2
else:
raise ValueError(f"unknown metric {metric!r}")
else:
raise ValueError("unknown metric")
@property
def metric(self) -> Callable[[NDArray], float]:
"""
Get the distance metric for graph
:return: distance metric
:rtype: callable
This is a function of a single coordinate-difference vector (shape
``(n,)``), returning a scalar distance.
"""
return self._metric
@metric.setter
def metric(self, metric: Callable[[NDArray], float] | str) -> None:
r"""
Set the distance metric for graph
:param metric: distance metric
:type metric: callable or str
This is a function that takes a single coordinate-difference vector
(shape ``(n,)``, not a list/array of multiple vectors) and returns a
scalar distance. It can be a user defined function or a string:
- 'L1' is the norm :math:`L_1 = \Sigma_i | v_i |`
- 'L2' is the norm :math:`L_2 = \sqrt{ \Sigma_i v_i^2}`
- 'SE2' is a mixed norm for vectors :math:`(x, y, \theta)` and
is :math:`\sqrt{x^2 + y^2 + \bar{\theta}^2}` where :math:`\bar{\theta}`
is :math:`\theta` wrapped to the interval :math:`[-\pi, \pi)`.
Requires every coordinate involved -- vertex ``coord`` and any
point passed to :meth:`closest`/:meth:`BaseVertex.distance` -- to be
exactly 3 elements; raises :exc:`ValueError` otherwise.
The metric is used by :meth:`closest` and :meth:`distance`
.. runblock:: pycon
>>> from pgraph import UGraph
>>> import numpy as np
>>> g = UGraph()
>>> g.metric = 'L1'
>>> print(g.metric(np.r_[3, -4]))
"""
self._metric = self._metricfunc(metric)
@property
def heuristic(self) -> Callable[[NDArray], float]:
"""
Get the heuristic distance metric for graph
:return: heuristic distance metric
:rtype: callable
This is a function of a single coordinate-difference vector (shape
``(n,)``), returning a scalar distance.
"""
return self._heuristic
@heuristic.setter
def heuristic(self, heuristic: Callable[[NDArray], float] | str) -> None:
r"""
Set the heuristic distance metric for graph
:param metric: heuristic distance metric
:type metric: callable or str
This is a function that takes a single coordinate-difference vector
(shape ``(n,)``, not a list/array of multiple vectors) and returns a
scalar distance. It can be a user defined function or a string:
- 'L1' is the norm :math:`L_1 = \Sigma_i | v_i |`
- 'L2' is the norm :math:`L_2 = \sqrt{ \Sigma_i v_i^2}`
- 'SE2' is a mixed norm for vectors :math:`(x, y, \theta)` and
is :math:`\sqrt{x^2 + y^2 + \bar{\theta}^2}` where :math:`\bar{\theta}`
is :math:`\theta` wrapped to the interval :math:`[-\pi, \pi)`.
Requires every coordinate involved -- vertex ``coord`` and any
point passed to :meth:`closest`/:meth:`BaseVertex.distance` -- to be
exactly 3 elements; raises :exc:`ValueError` otherwise.
The heuristic distance is only used by the A* planner :meth:`path_Astar`.
.. runblock:: pycon
>>> from pgraph import UGraph
>>> import numpy as np
>>> g = UGraph()
>>> g.heuristic = 'L2'
>>> print(g.heuristic(np.r_[3, 4]))
"""
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 | BaseVertex) -> BaseVertex:
"""
Get vertex (base class method)
:param i: vertex description
:type i: int or str
:return: the referenced vertex
:rtype: BaseVertex subclass
Retrieve a vertex by index or name:
-``g[i]`` is the i'th vertex in the graph. This reflects the order of
addition to the graph.
-``g[s]`` is vertex named ``s``
-``g[v]`` is ``v`` where ``v`` is a ``BaseVertex`` subclass
This method also supports iteration over the vertices in a graph::
for v in g:
print(v)
will iterate over all the vertices.
"""
if isinstance(i, int):
return self._vertexlist[i]
elif isinstance(i, str):
return self._vertexdict[i]
elif isinstance(i, BaseVertex):
return i
def __iter__(self) -> Iterator[BaseVertex]:
"""
Iterate over the vertices of the graph
:return: iterator over vertices, in order of addition
:rtype: iterator of BaseVertex subclass
.. 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')
>>> for v in g:
... print(v)
:seealso: :meth:`__getitem__`
"""
return iter(self._vertexlist)
def __contains__(self, item: BaseVertex | str) -> bool:
"""
Test if vertex in graph
:param item: vertex or name of vertex
:type item: BaseVertex subclass or str
:return: true if vertex exists in the graph
:rtype: bool
- ``'name' in graph`` is true if a vertex named ``'name'`` exists in the
graph.
- ``v in graph`` is true if the vertex reference ``v`` exists in the
graph.
"""
if isinstance(item, str):
return item in self._vertexdict
elif isinstance(item, BaseVertex):
return item in self._vertexdict.values()
def closest(self, coord: ArrayLike) -> tuple[BaseVertex | None, float]:
"""
BaseVertex closest to point
:param coord: coordinates of a point
:type coord: ndarray(n)
:return: closest vertex and its distance, or ``(None, inf)`` if no
vertex in the graph has a coordinate
:rtype: BaseVertex subclass or None, float
Returns the vertex closest to the given point. Distance is computed
according to the graph's metric. Vertices without a coordinate
(``coord`` is None) are skipped -- they have no position to compare.
.. runblock:: pycon
>>> from pgraph import UGraph
>>> g = UGraph()
>>> v1 = g.add_vertex(coord=[0,0], name='v1')
>>> v2 = g.add_vertex(coord=[10,10], name='v2')
>>> vertex, d = g.closest([1, 1])
>>> print(vertex, d)
:seealso: :meth:`metric`
"""
min_dist = np.inf
min_which: BaseVertex | None = None
for vertex in self:
if vertex.coord is None:
continue
d = self.metric(vertex.coord - coord)
if d < min_dist:
min_dist = d
min_which = vertex
return min_which, min_dist
def edges(self) -> set[Edge]:
"""
Get all edges in graph (base class method)
:return: All edges in the graph
:rtype: set of Edge references
We can iterate over all edges in the graph by::
for e in g.edges():
print(e)
.. note:: Unlike :meth:`BaseVertex.edges`, which returns a ``list`` in
connection order, this returns a ``set`` with no defined
iteration order.
.. 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)
>>> print(g.edges())
:seealso: :meth:`BaseVertex.edges`
"""
return self._edgelist
def plot(
self,
colorcomponents: bool = True,
force2d: bool = False,
vopt: dict = {},
eopt: dict = {},
text: dict | bool = {},
block: bool = False,
grid: bool = True,
ax: Any = None,
) -> None:
"""