-
Notifications
You must be signed in to change notification settings - Fork 68
/
PGraph.m
1447 lines (1251 loc) · 52.7 KB
/
PGraph.m
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
%PGraph Graph class
%
% g = PGraph() create a 2D, planar embedded, directed graph
% g = PGraph(n) create an n-d, embedded, directed graph
%
% Provides support for graphs that:
% - are directed
% - are embedded in a coordinate system (2D or 3D)
% - have multiple unconnected components
% - have symmetric cost edges (A to B is same cost as B to A)
% - have no loops (edges from A to A)
%
% Graph representation:
% - vertices are represented by integer vertex ids (vid)
% - edges are represented by integer edge ids (eid)
% - each vertex can have arbitrary associated data
% - each edge can have arbitrary associated data
%
% Methods::
%
% Constructing the graph::
% g.add_node(coord) add vertex
% g.add_edge(v1, v2) add edge fbetween vertices
% g.setcost(e, c) set cost for edge
% g.setedata(e, u) set user data for edge
% g.setvdata(v, u) set user data for vertex
%
% Modifying the graph::
% g.clear() remove all vertices and edges from the graph
% g.delete_edge(e) remove edge
% g.delete_node(v) remove vertex
% g.setcoord(v) set coordinate of vertex
%
% Information from graph::
% g.about() summary information about node
% g.component(v) component id for vertex
% g.componentnodes(c) vertices in component
% g.connectivity() number of edges for all vertices
% g.connectivity_in() number of incoming edges for all vertices
% g.connectivity_out() number of outgoing edges for all vertices
% g.coord(v) coordinate of vertex
% g.cost(e) cost of edge
% g.distance_metric(v1,v2) distance between nodes
% g.edata(e) get edge user data
% g.edgedir(v1,v2) direction of edge
% g.edges(v) list of edges for vertex
% g.edges_in(v) list of edges into vertex
% g.edges_out(v) list of edges from vertex
% g.lookup(name) vertex from name
% g.name(v) name of vertex
% g.neighbours(v) neighbours of vertex
% g.neighbours_d(v) neighbours of vertex and edge directions
% g.neighbours_in(v) neighbours with edges in
% g.neighbours_out(v) neighbours with edges out
% g.samecomponent(v1,v2) test if vertices in same component
% g.vdata(v) vertex user data
% g.vertices(e) vertices for edge
%
% Display::
%
% g.char() convert graph to string
% g.display() display summary of graph
% g.highlight_node(v) highlight vertex
% g.highlight_edge(e) highlight edge
% g.highlight_component(c) highlight all nodes in component
% g.highlight_path(p) highlight nodes and edge along path
% g.pick(coord) vertex closest to coord
% g.plot() plot graph
%
%
% Matrix representations::
% g.adjacency() adjacency matrix
% g.degree() degree matrix
% g.incidence() incidence matrix
% g.laplacian() Laplacian matrix
%
% Planning paths through the graph::
% g.Astar(s, g) shortest path from s to g
% g.goal(v) set goal vertex, and plan paths
% g.path(v) list of vertices from v to goal
%
% Graph and world points::
% g.closest(coord) vertex closest to coord
% g.coord(v) coordinate of vertex v
% g.distance(v1, v2) distance between v1 and v2
% g.distances(coord) return sorted distances from coord to all vertices
%
% Object properties (read only)::
% g.n number of vertices
% g.ne number of edges
% g.nc number of components
%
% Example::
% g = PGraph();
% g.add_node([1 2]'); % add node 1
% g.add_node([3 4]'); % add node 1
% g.add_node([1 3]'); % add node 1
% g.add_edge(1, 2); % add edge 1-2
% g.add_edge(2, 3); % add edge 2-3
% g.add_edge(1, 3); % add edge 1-3
% g.plot()
%
% Notes::
% - Support for edge direction is quite simple.
% - The method distance_metric() could be redefined in a subclass.
% Copyright (C) 1993-2019 Peter I. Corke
%
% This file is part of The Spatial Math Toolbox for MATLAB (SMTB).
%
% Permission is hereby granted, free of charge, to any person obtaining a copy
% of this software and associated documentation files (the "Software"), to deal
% in the Software without restriction, including without limitation the rights
% to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
% of the Software, and to permit persons to whom the Software is furnished to do
% so, subject to the following conditions:
%
% The above copyright notice and this permission notice shall be included in all
% copies or substantial portions of the Software.
%
% THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
% IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
% FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
% COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
% IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
% CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
%
% https://github.com/petercorke/spatial-math
% Peter Corke 8/2009.
% TODO:
% be able to delete nodes, must update connectivity
% update to use map.container class
classdef PGraph < matlab.mixin.Copyable
properties (SetAccess=private, GetAccess=public)
vertexlist % vertex coordinates, columnwise, vertex number is the column number
edgelist % 2xNe matrix, each column is vertex index of edge start and end
edgelen % length (cost) of this edge
labels % label of each vertex (1xN)
maxlabel % set of all labels (1xNc)
goaldist % distance from goal, after planning
vertexdata % per vertex data, cell array
edgedata % per edge data, cell array
ndims % number of coordinate dimensions, height of vertices matrix
verbose
measure % distance measure: 'Euclidean', 'SE2'
dweight % distance weighting for SE2 measure
ncvalid
names
end
properties (Dependent)
n % number of nodes/vertices
ne % number of edges
nc % number of components
end
methods
function g = PGraph(ndims, varargin)
%PGraph.PGraph Graph class constructor
%
% G=PGraph(D, OPTIONS) is a graph object embedded in D dimensions.
%
% Options::
% 'distance',M Use the distance metric M for path planning which is either
% 'Euclidean' (default) or 'SE2'.
% 'verbose' Specify verbose operation
%
% Notes::
% - Number of dimensions is not limited to 2 or 3.
% - The distance metric 'SE2' is the sum of the squares of the difference
% in position and angle modulo 2pi.
% - To use a different distance metric create a subclass of PGraph and
% override the method distance_metric().
if nargin < 1
ndims = 2; % planar by default
elseif isa(ndims, 'PGraph')
% do a deep copy
g = ndims.copy();
return
end
g.ndims = ndims;
opt.distance = 'Euclidean';
opt.dweight = 1;
opt = tb_optparse(opt, varargin);
g.clear();
g.verbose = opt.verbose;
g.measure = opt.distance;
g.dweight = opt.dweight;
g.vertexdata = {};
g.edgedata = {};
g.ncvalid = false; % mark connectivity as suspect
g.names = strings(0,0);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%% GRAPH MAINTENANCE
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function v = add_node(g, coord, varargin)
%PGraph.add_node Add a node
%
% V = G.add_node(X, OPTIONS) adds a node/vertex with coordinate X (Dx1) and
% returns the integer node id V.
%
% Options:
% 'name',N Assign a string name N to this vertex
% 'from',V Create a directed edge from vertex V with cost equal to the distance between the vertices.
% 'cost',C If an edge is created use cost C
%
% Notes::
% - Distance is computed according to the metric specified in the
% constructor.
%
% See also PGraph.add_edge, PGraph.data, PGraph.getdata.
if length(coord) ~= g.ndims
error('coordinate length different to graph coordinate dimensions');
end
opt.from = [];
opt.name = [];
opt.cost = NaN;
opt = tb_optparse(opt, varargin);
% append the coordinate as a column in the vertex matrix
g.vertexlist = [g.vertexlist coord(:)];
v = g.n;
if g.verbose
fprintf('add node (%d) = ', v);
fprintf('%f ', coord);
fprintf('\n');
end
% optionally add an edge
if ~isempty(opt.from)
if isnan(opt.cost)
opt.cost = g.distance(v, opt.from);
end
g.add_edge(opt.from, v, opt.cost);
end
if ~isempty(opt.name)
g.names(v) = opt.name;
end
g.ncvalid = false; % mark connectivity as suspect
end
function e = add_edge(g, v1, v2, d)
%PGraph.add_edge Add an edge
%
% E = G.add_edge(V1, V2) adds a directed edge from vertex id V1 to vertex id V2, and
% returns the edge id E. The edge cost is the distance between the vertices.
%
% E = G.add_edge(V1, V2, C) as above but the edge cost is C.
%
% Notes::
% - If V2 is a vector add edges from V1 to all elements of V2
% - Distance is computed according to the metric specified in the
% constructor.
%
% See also PGraph.add_node, PGraph.edgedir.
if g.verbose
fprintf('add edge %d -> %d\n', v1, v2);
end
e = [];
for vv=v2(:)'
g.edgelist = [g.edgelist [v1; vv]];
e = [e numcols(g.edgelist)];
if (nargin < 4) || isempty(d)
d = g.distance(v1, vv);
end
g.edgelen = [g.edgelen d];
end
g.ncvalid = false; % mark connectivity as suspect
end
function delete_node(g, vv)
for v=sort(vv(:)', 2, 'descend')
% remove all its edges
el = g.edges(v);
g.delete_edge(el);
% remove the column from the vertex table
g.vertexlist(:,v) = [];
% now renumber all the edges that might have changed
k = find(g.edgelist > v);
g.edgelist(k) = g.edgelist(k) - 1;
g.ncvalid = false; % mark connectivity as suspect
end
end
function delete_edge(g, e)
g.edgelist(:,e) = [NaN; NaN];
g.ncvalid = false; % mark connectivity as suspect
end
function clear(g)
%PGraph.clear Clear the graph
%
% G.clear() removes all vertices, edges and components.
% set the orientation of the edge and vertex tables
g.labels = zeros(1, 0);
g.edgelist = zeros(2, 0);
g.edgelen = zeros(1, 0);
g.vertexlist = zeros(g.ndims, 0);
g.ncvalid = false; % mark connectivity as suspect
g.maxlabel = 0;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%% GRAPH STRUCTURE
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% which edges contain v
% elist = g.edges(v)
function e = edges(g, v)
%PGraph.edges Find edges given vertex
%
% E = G.edges(V) is a vector containing the id of all edges connected to vertex id V.
%
% See also PGraph.edgedir.
e = [find(g.edgelist(1,:) == v) find(g.edgelist(2,:) == v)];
end
function e = edges_in(g, v)
%PGraph.edges Find edges given vertex
%
% E = G.edges(V) is a vector containing the id of all edges connected to vertex id V.
%
% See also PGraph.edgedir.
e = find(g.edgelist(2,:) == v);
end
function e = edges_out(g, v)
%PGraph.edges Find edges given vertex
%
% E = G.edges(V) is a vector containing the id of all edges connected to vertex id V.
%
% See also PGraph.edgedir.
e = find(g.edgelist(1,:) == v);
end
function dir = edgedir(g, v1, v2)
%PGraph.edgedir Find edge direction
%
% D = G.edgedir(V1, V2) is the direction of the edge from vertex id V1
% to vertex id V2.
%
% If we add an edge from vertex 3 to vertex 4
% g.add_edge(3, 4)
% then
% g.edgedir(3, 4)
% is positive, and
% g.edgedir(4, 3)
% is negative.
%
% See also PGraph.add_node, PGraph.add_edge.
n = g.edges(v1);
if any(ismember( g.edgelist(2, n), v2))
dir = 1;
elseif any(ismember( g.edgelist(1, n), v2))
dir = -1;
else
dir = 0;
end
end
function v = vertices(g, e)
%PGraph.vertices Find vertices given edge
%
% V = G.vertices(E) return the id of the vertices that define edge E.
v = g.edgelist(:,e);
end
function [n,c] = neighbours(g, v)
%PGraph.neighbours Neighbours of a vertex
%
% N = G.neighbours(V) is a vector of ids for all vertices which are
% directly connected neighbours of vertex V.
%
% [N,C] = G.neighbours(V) as above but also returns a vector C whose elements
% are the edge costs of the paths corresponding to the vertex ids in N.
e = g.edges(v);
n = g.edgelist(:,e);
n = n(:)';
n(n==v) = []; % remove references to self
if nargout > 1
c = g.cost(e);
end
end
function [n,c] = neighbours_out(g, v)
%PGraph.neighbours Outgoing neighbours of a vertex
%
% N = G.neighbours(V) is a vector of ids for all vertices which are
% directly connected neighbours of vertex V.
%
% [N,C] = G.neighbours(V) as above but also returns a vector C whose elements
% are the edge costs of the paths corresponding to the vertex ids in N.
e = g.edges_out(v);
n = g.edgelist(:,e);
n = n(:)';
n(n==v) = []; % remove references to self
if nargout > 1
c = g.cost(e);
end
end
function [n,c] = neighbours_in(g, v)
%PGraph.neighbours Incoming neighbours of a vertex
%
% N = G.neighbours(V) is a vector of ids for all vertices which are
% directly connected neighbours of vertex V.
%
% [N,C] = G.neighbours(V) as above but also returns a vector C whose elements
% are the edge costs of the paths corresponding to the vertex ids in N.
e = g.edges_in(v);
n = g.edgelist(:,e);
n = n(:)';
n(n==v) = []; % remove references to self
if nargout > 1
c = g.cost(e);
end
end
function [n,c] = neighbours_d(g, v)
%PGraph.neighbours_d Directed neighbours of a vertex
%
% N = G.neighbours_d(V) is a vector of ids for all vertices which are
% directly connected neighbours of vertex V. Elements are positive
% if there is a link from V to the node (outgoing), and negative if the link
% is from the node to V (incoming).
%
% [N,C] = G.neighbours_d(V) as above but also returns a vector C whose elements
% are the edge costs of the paths corresponding to the vertex ids in N.
e = g.edges(v);
n = [-g.edgelist(1,e) g.edgelist(2,e)];
n(abs(n)==v) = []; % remove references to self
if nargout > 1
c = g.cost(e);
end
end
function c = connectivity(g,nn)
%PGraph.connectivity Node connectivity
%
% C = G.connectivity() is a vector (Nx1) with the number of edges per
% vertex.
%
% The average vertex connectivity is
% mean(g.connectivity())
%
% and the minimum vertex connectivity is
% min(g.connectivity())
if nargin == 1
for k=1:g.n
c(k) = length(g.edges(k));
end
elseif nargin == 2
c = [];
for n=nn
c = [c length(g.edges(n))];
end
end
end
function c = connectivity_in(g,n )
%PGraph.connectivity Graph connectivity
%
% C = G.connectivity() is a vector (Nx1) with the number of incoming edges per
% vertex.
%
% The average vertex connectivity is
% mean(g.connectivity())
%
% and the minimum vertex connectivity is
% min(g.connectivity())
if nargin == 1
for k=1:g.n
c(k) = length(g.edges_in(k));
end
elseif nargin == 2
c = length(g.edges_in(n));
end
end
function c = connectivity_out(g,n )
%PGraph.connectivity Graph connectivity
%
% C = G.connectivity() is a vector (Nx1) with the number of outgoing edges per
% vertex.
%
% The average vertex connectivity is
% mean(g.connectivity())
%
% and the minimum vertex connectivity is
% min(g.connectivity())
if nargin == 1
for k=1:g.n
c(k) = length(g.edges_out(k));
end
elseif nargin == 2
c = length(g.edges_out(n));
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%% NODE PROPERTIES
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function p = coord(g, v)
%PGraph.coord Coordinate of node
%
% X = G.coord(V) is the coordinate vector (Dx1) of vertex id V.
if nargin < 2
p = g.vertexlist;
else
p = g.vertexlist(:,v);
end
end
function p = name(g, v)
%PGraph.coord Name of node
%
% X = G.name(V) is the name (string) of vertex id V.
if nargin < 2
p = [g.names];
else
p = g.names(v);
end
end
function p = lookup(g, name)
p = find( [g.names] == name );
end
function p = setcoord(g, v, c)
%PGraph.coord Coordinate of node
%
% X = G.coord(V) is the coordinate vector (Dx1) of vertex id V.
if nargin < 3
if ~all(size(v) == size(g.vertexlist))
error('SMTB:PGraph:badarg', 'value must be size of vertex table');
end
g.vertexlist = v;
else
g.vertexlist(:,v) = c;
end
end
function u = vdata(g, v)
%PGraph.data Get user data for node
%
% U = G.data(V) gets the user data of vertex V which can be of any
% type such as a number, struct, object or cell array.
%
% See also PGraph.setdata.
u = g.vertexdata{v};
end
function u = setvdata(g, v, u)
%PGraph.setdata Set user data for node
%
% G.setdata(V, U) sets the user data of vertex V to U which can be of any
% type such as a number, struct, object or cell array.
%
% See also PGraph.data.
g.vertexdata{v} = u;
end
function d = distance(g, v1, v2)
%PGraph.distance Distance between vertices
%
% D = G.distance(V1, V2) is the geometric distance between
% the vertices V1 and V2.
%
% See also PGraph.distances.
d = g.distance_metric( g.vertexlist(:,v1), g.vertexlist(:,v2));
end
function [d,k] = distances(g, p)
%PGraph.distances Distances from point to vertices
%
% D = G.distances(X) is a vector (1xN) of geometric distance from the point
% X (Dx1) to every other vertex sorted into increasing order.
%
% [D,W] = G.distances(P) as above but also returns W (1xN) with the
% corresponding vertex id.
%
% Notes::
% - Distance is computed according to the metric specified in the
% constructor.
%
% See also PGraph.closest.
d = g.distance_metric(p(:), g.vertexlist);
[d,k] = sort(d, 'ascend');
end
function [c,dn] = closest(g, p, tol)
%PGraph.closest Find closest vertex
%
% V = G.closest(X) is the vertex geometrically closest to coordinate X.
%
% [V,D] = G.closest(X) as above but also returns the distance D.
%
% See also PGraph.distances.
d = g.distance_metric(p(:), g.vertexlist);
[mn,c] = min(d);
if nargin > 2 && mn > tol
c = []; dn = [];
end
if nargout > 1
dn = mn;
end
end
function about(g, vv)
if nargin < 2
disp('pick a node using the mouse');
vv = g.pick()
end
if ~g.ncvalid
g.graphcolor();
end
for v=vv
fprintf('Node %d #%d@ (', v, g.labels(v)); fprintf('%g ', g.coord(v)); fprintf(')\n');
fprintf(' neighbours: ');
fprintf('%d ', g.neighbours_in(v)); fprintf(' >-o-> ');
fprintf('%d ', g.neighbours_out(v)); fprintf('\n');
fprintf(' edges: ');
fprintf('%d ', g.edges_in(v)); fprintf(' >-o-> ');
fprintf('%d ', g.edges_out(v)); fprintf('\n');
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%% EDGE PROPERTIES
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function d = cost(g, e)
%PGraph.cost Cost of edge
%
% C = G.cost(E) is the cost of edge id E.
d = g.edgelen(e);
end
function d = setcost(g, e, c)
%PGraph.cost Set cost of edge
%
% G.setcost(E, C) set cost of edge id E to C.
g.edgelen(e) = c;
end
function u = edata(g, e)
%PGraph.data Get user data for node
%
% U = G.data(V) gets the user data of vertex V which can be of any
% type such as a number, struct, object or cell array.
%
% See also PGraph.setdata.
u = g.edgedata{e};
end
function u = setedata(g, e, u)
%PGraph.setdata Set user data for node
%
% G.setdata(V, U) sets the user data of vertex V to U which can be of any
% type such as a number, struct, object or cell array.
%
% See also PGraph.data.
g.edgedata{e} = u;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%% GRAPH INFORMATION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function n = get.n(g)
%Pgraph.n Number of vertices
%
% G.n is the number of vertices in the graph.
%
% See also PGraph.ne.
n = numcols(g.vertexlist);
end
function ne = get.ne(g)
%Pgraph.ne Number of edges
%
% G.ne is the number of edges in the graph.
%
% See also PGraph.n.
ne = numcols(g.edgelist);
end
function ne = get.nc(g)
%Pgraph.nc Number of components
%
% G.nc is the number of components in the graph.
%
% See also PGraph.component.
if ~g.ncvalid
g.graphcolor();
end
ne = g.maxlabel;
end
function display(g)
%PGraph.display Display graph
%
% G.display() displays a compact human readable representation of the
% state of the graph including the number of vertices, edges and components.
%
% See also PGraph.char.
loose = strcmp( get(0, 'FormatSpacing'), 'loose');
if loose
disp(' ');
end
disp([inputname(1), ' = '])
disp( char(g) );
end % display()
function s = char(g)
%PGraph.char Convert graph to string
%
% S = G.char() is a compact human readable representation of the
% state of the graph including the number of vertices, edges and components.
s = '';
s = char(s, sprintf(' %d dimensions', g.ndims));
s = char(s, sprintf(' %d vertices', g.n));
s = char(s, sprintf(' %d edges', numcols(g.edgelist)));
s = char(s, sprintf(' %d components', g.nc));
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%% GRAPH COMPONENTS
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function graphcolor(g)
% color the graph
g.labels = repmat(NaN, 1, g.n);
function colorComponent(g, v, l)
g.labels(v) = l;
for n = g.neighbours(v)
if isnan(g.labels(n))
colorComponent(g, n, l);
end
end
end
for label = 1:g.n
% find first vertex with no label
v = find(isnan(g.labels));
if isempty(v)
g.maxlabel = label-1;
break;
end
v = v(1);
colorComponent(g, v, label);
end
g.ncvalid = true;
end
function c = component(g, v)
%PGraph.component Graph component
%
% C = G.component(V) is the id of the graph component that contains vertex
% V.
c = g.labels(v);
end
function v = componentnodes(g, c)
%PGraph.component Graph component
%
% C = G.component(V) are the ids of all vertices in the graph component V.
v = find(g.labels == c);
end
function c = samecomponent(g, v1, v2)
%PGraph.component Graph component
%
% C = G.component(V) is the id of the graph component that contains vertex
% V.
if ~g.ncvalid
% lazy graph coloring
g.graphcolor();
end
c = g.labels(v1) == g.labels(v2);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%% GRAPHICS
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function plot(g, varargin)
%PGraph.plot Plot the graph
%
% G.plot(OPT) plots the graph in the current figure. Nodes
% are shown as colored circles.
%
% Options::
% 'labels' Display vertex id (default false)
% 'edges' Display edges (default true)
% 'edgelabels' Display edge id (default false)
% 'NodeSize',S Size of vertex circle (default 8)
% 'NodeFaceColor',C Node circle color (default blue)
% 'NodeEdgeColor',C Node circle edge color (default blue)
% 'NodeLabelSize',S Node label text sizer (default 16)
% 'NodeLabelColor',C Node label text color (default blue)
% 'EdgeColor',C Edge color (default black)
% 'EdgeLabelSize',S Edge label text size (default black)
% 'EdgeLabelColor',C Edge label text color (default black)
% 'componentcolor' Node color is a function of graph component
% 'only',N Only show these nodes
% show vertices
holdon = ishold;
hold on
% parse options
opt.componentcolor = false;
opt.labels = false;
opt.edges = true;
opt.edgelabels = false;
opt.NodeSize = 8;
opt.NodeFaceColor = 'b';
opt.NodeEdgeColor = 'b';
opt.NodeLabelSize = 16;
opt.NodeLabelColor = 'b';
opt.EdgeColor = 'k';
opt.EdgeLabelSize = 8;
opt.EdgeLabelColor = 'k';
opt.EdgeWidth = 0.5;
opt.dims = g.ndims;
opt.only = [1:g.n];
[opt,args] = tb_optparse(opt, varargin);
% set default color if none specified
if ~isempty(args)
mcolor = args{1};
else
mcolor = 'b';
end
if opt.componentcolor
colororder = get(gca, 'ColorOrder');
% step through each component
for c=1:g.nc
vertices = g.componentnodes(c);
if length(vertices) == 1
% singleton is grey
color = 0.8*[1 1 1];
else
% otherwise use next color from the axis color order
color = colororder(mod(c+1,numrows(colororder)-1)+1,:);
end
% plot the edges
if opt.edges
coords = [];
for v = vertices
p0 = g.coord(v); p0 = p0(1:opt.dims);
for n = g.neighbours(v)
pn = g.coord(n); pn = pn(1:opt.dims);
coords = [coords; p0'; pn'; NaN*ones(1,g.ndims)];
end
end
if ~isempty(coords)
if opt.dims == 3
plot3(coords(1,:), coords(2,:), coords(3,:), 'Color', color, 'LineWidth', opt.EdgeWidth);
else
plot(coords(:,1), coords(:,2), 'Color', color, 'LineWidth', opt.EdgeWidth);
end
end
end
% plot the nodes
args = {'LineStyle', 'None', ...
'Marker', 'o', ...
'MarkerFaceColor', color, ...
'MarkerSize', opt.NodeSize, ...
'MarkerEdgeColor', color };
for v = vertices
if ~ismember(v, opt.only)
continue;
end
p = g.coord(v);
if opt.dims == 3
plot3(p(1), p(2), p(3), args{:});
else
plot(p(1), p(2), args{:});
end
end
if length(vertices) == 1
continue; % no edges to plot
end
end
else
%% user selected colors
% show edges
if opt.edges
for e=g.edgelist
v1 = g.vertexlist(:,e(1));
v2 = g.vertexlist(:,e(2));
if opt.dims == 3
plot3([v1(1) v2(1)], [v1(2) v2(2)], [v1(3) v2(3)], ...
'Color', opt.EdgeColor, 'LineWidth', opt.EdgeWidth);
else
plot([v1(1) v2(1)], [v1(2) v2(2)], ...
'Color', opt.EdgeColor, 'LineWidth', opt.EdgeWidth);
end
end
end
% show the vertices as filled circles
for i=1:g.n
% for each node
if ~ismember(i, opt.only)
continue;
end
args = {'LineStyle', 'None', ...
'Marker', 'o', ...
'MarkerFaceColor', opt.NodeFaceColor, ...
'MarkerSize', opt.NodeSize, ...
'MarkerEdgeColor', opt.NodeEdgeColor };
if opt.dims == 3
plot3(g.vertexlist(1,i), g.vertexlist(2,i), g.vertexlist(3,i), args{:});
else
plot(g.vertexlist(1,i), g.vertexlist(2,i), args{:});
end
end