blib/lib/Graph/Simple.pm

filter: Statementstmt 99.3% 148 / 149 Branchbran 97.5% 39 / 40 Conditioncond 57.6% 15 / 26 MC/DCmcdc 18.7% 3 / 16 Subroutinesub 100% 26 / 26 Podpod 100% 11 / 11 totaltotal 90.3% 242 / 268 CC 40 SCAR 15.4
CC
40
Cov
94%
breadth_first_search
9.3
prim
7.0
dijkstra
7.0
CRAP 4.6
↑ Summary
1 package Graph::Simple;
2  
3 #ABSTRACT: simple and intuitive interface for manipulating graph
4  
5  
6 1 ▶use Moo;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 1 ▶use Carp 'croak';
Subroutine BEGIN: called CC=1 SCAR=0.0
8  
9 # graphs are represented with adjency lists
10 has _adjencies => (
11 is => 'rw',
12 11 ▶ default => sub { {} },
Subroutine __ANON__: called CC=1 SCAR=0.0
13 1 );
14  
15 # if weights are provided, stored for each edge(u,v)
16 has _weights => (
17 is => 'rw',
18 11 ▶ default => sub { {} },
Subroutine __ANON__: called CC=1 SCAR=0.0
19 1 );
20  
21  
22 has is_weighted => (
23 is => 'ro',
24 4 ▶ default => sub {0},
Subroutine __ANON__: called CC=1 SCAR=0.0
25 1 );
26  
27  
28 has is_directed => (
29 is => 'ro',
30 2 ▶ default => sub {0},
Subroutine __ANON__: called CC=1 SCAR=0.0
31 1 );
32  
33  
34 122 ▶sub vertices {
Subroutine vertices: called CC=1 SCAR=0.0
Pod documented
35 122 my $self = shift;
36 122 return keys %{ $self->_adjencies };
37 }
38  
39  
40 77 ▶sub add_edge {
Subroutine add_edge: called CC=2 SCAR=6.9
Pod documented
41 77 my ( $self, $u, $v, $weight ) = @_;
42  
43 77 $self->_add_edge( $u, $v, $weight );
44  
45 # if the graph is not directed, adding u,v adds v,u
46 77 ▶ $self->_add_edge( $v, $u, $weight ) if !$self->is_directed;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->is_directed 69 8 77
47  
48 77 return "$u,$v";
49 }
50  
51 146 ▶sub _add_edge {
Subroutine _add_edge: called CC=4 SCAR=13.9
52 146 my ( $self, $u, $v, $weight ) = @_;
53 146 ▶ $weight ||= 0;
Condition100%2/2
$weight ||= 0
l!l
9452
MC/DC100%1/1
$weight ||= 0
$weight
Truth table100%2/2
A
A= $weight
Aresult
11
00
54  
55 146 ▶ $self->_adjencies->{$u} ||= [];
Condition100%2/2
$self->_adjencies->{$u} ||= []
l!l
7868
MC/DC100%1/1
$self->_adjencies->{$u} ||= []
$self->_adjencies->{$u}
Truth table100%2/2
A
A= $self->_adjencies->{$u}
Aresult
11
00
56 146 push @{ $self->_adjencies->{$u} }, $v;
57  
58 146 ▶ $self->_weights->{$u}->{$v} = $weight
Branch: 1 branch
BranchTrueFalseTotal
if $self->is_weighted 87 59 146
59 if $self->is_weighted;
60 }
61  
62  
63 2 ▶sub delete_edge {
Subroutine delete_edge: called CC=2 SCAR=6.9
Pod documented
64 2 my ( $self, $u, $v ) = @_;
65  
66 2 $self->_delete_edge( $u, $v );
67 2 ▶ $self->_delete_edge( $v, $u ) if !$self->is_directed;
Branch: 1 branch
BranchTrueFalseTotal
if not $self->is_directed 1 1 2
68 }
69  
70 3 ▶sub _delete_edge {
Subroutine _delete_edge: called CC=3 SCAR=11.0
71 3 my ( $self, $u, $v ) = @_;
72  
73 3 my @neighbors = $self->neighbors($u);
74 3 my @new;
75 3 foreach my $e (@neighbors) {
76 4 ▶ push @new, $e if $e ne $v;
Branch: 1 branch
BranchTrueFalseTotal
if $e ne $v 1 3 4
77 }
78 3 $self->_adjencies->{$u} = \@new;
79 }
80  
81  
82 116 ▶sub neighbors {
Subroutine neighbors: called CC=2 SCAR=6.9
Pod documented
83 116 my ( $self, $v ) = @_;
84  
85 croak "Unknown vertex '$v'"
86 116 ▶ if !grep {/^$v$/} $self->vertices;
Branch: 1 branch
BranchTrueFalseTotal
unless grep {/^$v$/;} $self->vertices 1 115 116
87  
88 115 return @{ $self->_adjencies->{$v} };
89 }
90  
91  
92 70 ▶sub weight {
Subroutine weight: called CC=2 SCAR=6.9
Pod documented
93 70 my ( $self, $u, $v, $w ) = @_;
94 70 ▶ if ( @_ == 3 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_ == 3) { } 69 1 70
95 69 return $self->_weights->{$u}->{$v};
96 }
97 else {
98 1 $self->_weights->{$u}->{$v} = $w;
99 }
100 }
101  
102  
103 2 ▶sub is_adjacent {
Subroutine is_adjacent: called CC=1 SCAR=0.0
Pod documented
104 2 my ( $self, $u, $v ) = @_;
105 2 return grep {/^$v$/} @{ $self->_adjencies->{$u} };
106 }
107  
108  
109 1 ▶sub breadth_first_search {
Subroutine breadth_first_search: called CC=9 SCAR=22.3
Pod documented
110 1 my ( $self, $v, %options ) = @_;
111  
112 1 my @queue = ($v);
113 1 my $parents = {};
114 1 my $states = { $v => 'grey' };
115  
116 8 ▶ my $cb_vertex_discovered = $options{cb_vertex_discovered} || sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
117 1 ▶ };
Condition33%1/3
$options{'cb_vertex_discovered'} || sub { }
l!l&&r!l&&!r
010
MC/DC0%0/2
$options{'cb_vertex_discovered'} || sub { }
$options{'cb_vertex_discovered'} sub { }
Truth table33%1/3
A || B
A= $options{'cb_vertex_discovered'}B= sub { }
ABresult
1X1
011
000
118  
119 8 ▶ my $cb_vertex_processed = $options{cb_vertex_processed} || sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
120 1 ▶ };
Condition33%1/3
$options{'cb_vertex_processed'} || sub { }
l!l&&r!l&&!r
010
MC/DC0%0/2
$options{'cb_vertex_processed'} || sub { }
$options{'cb_vertex_processed'} sub { }
Truth table33%1/3
A || B
A= $options{'cb_vertex_processed'}B= sub { }
ABresult
1X1
011
000
121  
122 4 ▶ my $cb_edge_discovered = $options{cb_edge_discovered} || sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
123 1 ▶ };
Condition33%1/3
$options{'cb_edge_discovered'} || sub { }
l!l&&r!l&&!r
010
MC/DC0%0/2
$options{'cb_edge_discovered'} || sub { }
$options{'cb_edge_discovered'} sub { }
Truth table33%1/3
A || B
A= $options{'cb_edge_discovered'}B= sub { }
ABresult
1X1
011
000
124  
125 1 ▶ while ( my $vertex = shift(@queue) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $vertex = shift @queue) 8 1 9
126 8 $cb_vertex_discovered->($vertex);
127  
128 8 foreach my $n ( $self->neighbors($vertex) ) {
129 22 ▶ my $state = $states->{$n} || 'white';
Condition100%2/2
$states->{$n} || 'white'
l!l
157
MC/DC100%1/1
$states->{$n} || 'white'
$states->{$n}
Truth table100%2/2
A
A= $states->{$n}
Aresult
11
00
130 22 ▶ next if $state eq 'black';
Branch: 1 branch
BranchTrueFalseTotal
if $state eq "black" 11 11 22
131  
132 11 ▶ if ( $state eq 'grey' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($state eq "grey") 4 7 11
133 4 $cb_edge_discovered->( $vertex, $n );
134 4 next;
135 }
136  
137 7 push @queue, $n;
138 7 $states->{$n} = 'grey';
139 7 $parents->{$n} = $vertex;
140 }
141  
142 8 $states->{$vertex} = 'black';
143 8 $cb_vertex_processed->($vertex);
144 }
145  
146 1 return $parents;
147 }
148  
149  
150 3 ▶sub depth_first_search {
Subroutine depth_first_search: called CC=6 SCAR=19.0
Pod documented
151 3 my ( $self, $start, %options ) = @_;
152  
153 # init phase of the DFS traversal
154 3 ▶ my $states ||= {};
Condition50%1/2
my $states ||= {}
l!l
03
MC/DC0%0/1
my $states ||= {}
my $states
Truth table50%1/2
A
A= my $states
Aresult
11
00
155 3 ▶ my $cb_vd = $options{cb_vertex_discovered} || sub { };
Subroutine __ANON__: called CC=1 SCAR=0.2
Condition66%2/3
$options{'cb_vertex_discovered'} || sub { }
l!l&&r!l&&!r
210
MC/DC0%0/2
$options{'cb_vertex_discovered'} || sub { }
$options{'cb_vertex_discovered'} sub { }
Truth table66%2/3
A || B
A= $options{'cb_vertex_discovered'}B= sub { }
ABresult
1X1
011
000
156 3 ▶ my $cb_vp = $options{cb_vertex_processed} || sub { };
Subroutine __ANON__: called CC=1 SCAR=0.2
Condition66%2/3
$options{'cb_vertex_processed'} || sub { }
l!l&&r!l&&!r
120
MC/DC0%0/2
$options{'cb_vertex_processed'} || sub { }
$options{'cb_vertex_processed'} sub { }
Truth table66%2/3
A || B
A= $options{'cb_vertex_processed'}B= sub { }
ABresult
1X1
011
000
157 3 ▶ my $cb_ed = $options{cb_edge_discovered} || sub { };
Subroutine __ANON__: called CC=1 SCAR=1.2
Condition33%1/3
$options{'cb_edge_discovered'} || sub { }
l!l&&r!l&&!r
030
MC/DC0%0/2
$options{'cb_edge_discovered'} || sub { }
$options{'cb_edge_discovered'} sub { }
Truth table33%1/3
A || B
A= $options{'cb_edge_discovered'}B= sub { }
ABresult
1X1
011
000
158 3 foreach my $v ( $self->vertices ) {
159 20 $states->{$v} = 'unknown';
160 }
161  
162 # DFS traversal is recursively done on each new vertex
163 $self->_dfs_visit(
164 3 $start, $states,
165 { cb_vertex_discovered => $cb_vd,
166 cb_vertex_processed => $cb_vp,
167 cb_edge_discovered => $cb_ed,
168 }
169 );
170 }
171  
172 20 ▶sub _dfs_visit {
Subroutine _dfs_visit: called CC=3 SCAR=11.0
173 20 my ( $self, $vertex, $states, $callbacks ) = @_;
174  
175 20 $states->{$vertex} = 'discovered';
176 20 $callbacks->{cb_vertex_discovered}->($vertex);
177  
178 20 foreach my $n ( $self->neighbors($vertex) ) {
179  
180 38 $callbacks->{cb_edge_discovered}->( $vertex, $n );
181 38 my $state = $states->{$n};
182  
183 38 ▶ if ( $state eq 'unknown' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($state eq "unknown") 17 21 38
184 17 $self->_dfs_visit( $n, $states, $callbacks );
185 }
186 }
187  
188 20 $callbacks->{cb_vertex_processed}->($vertex);
189 20 $states->{$vertex} = 'processed';
190 }
191  
192  
193 1 ▶sub prim {
Subroutine prim: called CC=7 SCAR=19.5
Pod documented
194 1 my ( $self, $start ) = @_;
195 1 my $spanning_tree =
196 Graph::Simple->new( is_weighted => 0, is_directed => 0 );
197  
198 1 my %non_tree_vertices = map { $_ => 1 } $self->vertices;
199 1 my %tree_vertices = ( $start => 1 );
200  
201 1 my $current = $start;
202 1 ▶ while ( keys %non_tree_vertices ) {
Branch: 1 branch
BranchTrueFalseTotal
if (keys %non_tree_vertices) 5 1 6
203 5 delete $non_tree_vertices{$current};
204  
205 # select the edge of minimum weight between a tree and a nontree vertex
206 5 my $min_weight;
207 my $new_edge;
208 5 foreach my $u ( keys %tree_vertices ) {
209  
210 15 foreach my $v ( $self->neighbors($u) ) {
211 42 ▶ next if exists $tree_vertices{$v};
Branch: 1 branch
BranchTrueFalseTotal
if exists $tree_vertices{$v} 24 18 42
212  
213 18 my $w = $self->weight( $u, $v );
214  
215 # print " - $u, $v weights $w\n";
216  
217 18 ▶ $min_weight = $w if !defined $min_weight;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $min_weight 5 13 18
218 18 ▶ if ( $w <= $min_weight ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($w <= $min_weight) 11 7 18
219 11 $new_edge = [ $u, $v ];
220 11 $min_weight = $w;
221 }
222 }
223 }
224  
225 # Adding $v to the spanning tree
226 5 my ( $u, $v ) = @$new_edge;
227  
228 # print "Minimum vertex is $u -> $v\n";
229 5 $spanning_tree->add_edge( $u, $v );
230 5 delete $non_tree_vertices{$v};
231 5 $tree_vertices{$v} = 1;
232 }
233  
234 1 return $spanning_tree;
235 }
236  
237  
238 2 ▶sub dijkstra {
Subroutine dijkstra: called CC=7 SCAR=19.5
Pod documented
239 2 my ( $self, $vertex ) = @_;
240 2 my $spanning_tree = Graph::Simple->new;
241  
242 2 my %distances = ( $vertex => 0 );
243 2 my %non_tree_vertices = map { $_ => 1 } $self->vertices;
244 2 my %tree_vertices = ( $vertex => 1 );
245  
246 2 my $current = $vertex;
247 2 ▶ while ( keys %non_tree_vertices ) {
Branch: 1 branch
BranchTrueFalseTotal
if (keys %non_tree_vertices) 14 2 16
248 14 delete $non_tree_vertices{$current};
249  
250 # select the edge of minimum weight between a tree and a nontree vertex
251 14 my $min_dist;
252 my $new_edge;
253 14 foreach my $u ( keys %tree_vertices ) {
254  
255 56 foreach my $v ( $self->neighbors($u) ) {
256 158 ▶ next if exists $tree_vertices{$v};
Branch: 1 branch
BranchTrueFalseTotal
if exists $tree_vertices{$v} 116 42 158
257  
258 42 my $w = $self->weight( $u, $v );
259 42 my $distance = $distances{$u} + $w;
260  
261 42 ▶ $min_dist = $distance if !defined $min_dist;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $min_dist 14 28 42
262 42 ▶ if ( $distance <= $min_dist ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($distance <= $min_dist) 26 16 42
263 26 $new_edge = [ $u, $v ];
264 26 $min_dist = $distance;
265 26 $distances{$v} = $distance;
266 }
267 }
268 }
269  
270 # Adding $v to the spanning tree
271 14 my ( $u, $v ) = @$new_edge;
272 14 $spanning_tree->add_edge( $u, $v );
273 14 delete $non_tree_vertices{$v};
274 14 $tree_vertices{$v} = 1;
275 }
276  
277 2 return { spanning_tree => $spanning_tree, distances => \%distances };
278 }
279  
280  
281 1 ▶sub shortest_path {
Subroutine shortest_path: called CC=4 SCAR=13.9
Pod documented
282 1 my ( $self, $source, $destination ) = @_;
283 1 my $dijkstra = $self->dijkstra($source);
284  
285 1 my $mst = $dijkstra->{spanning_tree};
286  
287 # we build a reverse path, starting from the destination, and backtracking the
288 # source each step with the neighbors of the vertex in the spanning tree
289 1 my @reverse_path;
290 1 my $current = $destination;
291  
292 1 ▶ while ( $current ne $source ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($current ne $source) 2 0 2
293 2 push @reverse_path, $current;
294  
295 2 foreach my $n ( $mst->neighbors($current) ) {
296 2 ▶ if ( $n eq $source ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($n eq $source) { } 1 1 2
297 1 push @reverse_path, $n;
298 1 return reverse @reverse_path;
299 }
300 else {
301 1 $current = $n;
302 }
303 }
304 }
305  
306 0 return reverse @reverse_path;
307 }
308  
309 1 1;
310  
311  
312 =pod
313  
314 =head1 NAME
315  
316 Graph::Simple - simple and intuitive interface for manipulating graph
317  
318 =head1 VERSION
319  
320 version 0.04
321  
322 =head1 DESCRIPTION
323  
324 In computer science, a graph is an abstract data type that is meant to implement
325 the graph and hypergraph concepts from mathematics.
326  
327 A graph data structure consists of a finite (and possibly mutable) set of
328 ordered pairs, called I<edges>, of certain entities called I<vertices>.
329 As in mathematics, an edge (x,y) is said to point or go from x to y.
330  
331 A graph data structure may also associate to each edge some edge value, such as
332 a symbolic label or a numeric attribute (cost, capacity, length, etc.) most
333 oftenly refered to as the I<weight> of the edge.
334  
335 See L<Wikipedia|http://en.wikipedia.org/wiki/Graph_(abstract_data_type)> for
336 more details about the theory.
337  
338 This class provides an easy to use and intuitive API for manipulating graphs in
339 Perl. It's a native Perl implementation based on L<Moo>.
340  
341 =head1 ATTRIBUTES
342  
343 =head2 is_weighted
344  
345 Boolean flag to tell if the graph is weighted
346  
347 =head2 is_directed
348  
349 Boolean flag to tell if the graph is directed
350  
351 =head1 METHODS
352  
353 =head2 vertices
354  
355 Return the array of vertices
356  
357 my @vertices = $g->vertices;
358  
359 =head2 add_edge
360  
361 Adds a new edge to the graph, and add the corresponding vertices.
362 Note that on undirected graphs, adding u,v also adds v,u.
363  
364 $g->add_edge("Foo", "Bar");
365  
366 On weighted graph, it's possible to pass the weight of the edge as a third
367 argument
368  
369 $g->add_edge("Foo", "Bar", 3);
370  
371 =head2 delete_edge
372  
373 $g->delete_edge(x, y)
374  
375 Removes the edge from x to y, if it is there.
376  
377 =head2 neighbors
378  
379 my @neighbors = $g->neighbors('u');
380  
381 Lists all vertices y such that there is an edge from x to y.
382  
383 =head2 weight
384  
385 Accessor to the weight of the edge. If called with two arguments, return the
386 value previously set, with three arguments, set the weight:
387  
388 # reader
389 my $w = $g->weight('u', 'v');
390  
391 # setter
392 $g->weight('u', 'v', 42);
393  
394 =head2 is_adjacent
395  
396 $g->is_adjacent(x, y)
397  
398 Tests whether there is an edge from node x to node y.
399  
400 =head2 breadth_first_search
401  
402 Performs a BFS traversal on the graph, returns the parents hash produced.
403  
404 Callbacks can be given to trigger code when edges or vertices are
405 discovered/processed.
406  
407 $g->breadth_first_search($vertex,
408 cb_vertex_discovered => sub { print "discovered vertex @_" },
409 cb_vertex_processed => sub { print "processed vertex @_" },
410 cb_edge_discovered => sub { print "new edge: @_" });
411  
412 =head2 depth_first_search
413  
414 Performs a DFS traversal on the graph, returns the parents hash produced.
415  
416 Callbacks can be given to trigger code when edges or vertices are
417 discovered/processed.
418  
419 $g->breadth_first_search('Foo',
420 cb_vertex_discovered => sub { print "discovered vertex @_" },
421 cb_vertex_processed => sub { print "processed vertex @_" },
422 cb_edge_discovered => sub { print "new edge: @_" },
423 );
424  
425 =head2 prim
426  
427 Implementation of the Prim algorithm to grow a Minimum Spanning Tree of the
428 graph.
429  
430 Return the tree produced (as a C<Graph::Simple> object).
431  
432 my $mst = $g->prim('Foo');
433  
434 =head2 dijkstra
435  
436 Implementation of the Dijkstra algorithm to find all possible shortest paths from
437 a vertex C<$s> to all other vertices of the graph.
438  
439 The return value of this method is a hashref containing the following entries:
440  
441 =over 4
442  
443 =item spanning_tree
444  
445 A L<Graph::Simple> object representing the minimum spanning tree produced by the
446 Dijkstra traversal.
447  
448 =item distances
449  
450 An hashref containing for each vertices the distance between that vertex and the
451 source vertex.
452  
453 =back
454  
455 my $dijkstra = $g->dijkstra('E');
456  
457 =head2 shortest_path
458  
459 Return the shortest path between two vertices as a list of vertices.
460  
461 my @path = $g->shortest_path('A', 'E');
462 # eg: ( 'A', 'D', 'F', 'E' )
463  
464 Note that internally, this method uses the spanning tree produced by the
465 Dijkstra algorithm to compute the shortest path.
466  
467 =head1 SYNOPSYS
468  
469 my $g = Graph::Simple->new ( is_directed => 1, is_weighted => 1);
470  
471 $g->add_edge( 'Al', 'Bob', 2 );
472 $g->add_edge( 'Al', 'Jim', 3 );
473 $g->add_edge( 'Joe', 'Jim', 3 );
474
475 $g->neighbors('Al');
476  
477 =head1 SEE ALSO
478  
479 This distribution has been written because when I looked on CPAN for an easy to
480 use and lightweight interface for manipulating graphs in Perl, I dind't find
481 something that fitted my expectations.
482  
483 Other distributions exist though:
484  
485 =over 4
486  
487 =item L<Graph>
488  
489 A rather feature-rich implementation but with a complex API.
490  
491 =item L<Graph::Fast>
492  
493 Less features than Graph but presumably faster. Appears to
494 be unmaintained since 2010 though.
495  
496 =item L<Graph::Boost>
497  
498 Perl bindings to the C++ graph library Boost. Certainly the fastest
499 implementation but depends on C++, obviously.
500  
501 =back
502  
503 =head1 AUTHOR
504  
505 Alexis Sukrieh <sukria@sukria.net>
506  
507 =head1 COPYRIGHT AND LICENSE
508  
509 This software is copyright (c) 2013 by Alexis Sukrieh.
510  
511 This is free software; you can redistribute it and/or modify it under
512 the same terms as the Perl 5 programming language system itself.
513  
514 =cut
515  
516  
517 __END__
↑ Summary