| 1 | package YAGL; | ||
| 2 | |||
| 3 | 20 | ▶ | use strict; |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 4 | 20 | ▶ | use warnings; |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 5 | 20 | ▶ | no warnings 'recursion'; |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 6 | 20 | ▶ | use feature qw/ say state current_sub /; |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 7 | 0 | ▶ | use Text::CSV; |
|
Subroutine
BEGIN: called CC=1 SCAR=2.6
| |||
| 8 | use Hash::PriorityQueue; | ||
| 9 | use Storable; | ||
| 10 | use List::Util qw/ uniq /; | ||
| 11 | |||
| 12 | use constant DEBUG => undef; | ||
| 13 | |||
| 14 | our $VERSION = '0.1'; | ||
| 15 | |||
| 16 | =pod | ||
| 17 | |||
| 18 | =encoding UTF-8 | ||
| 19 | |||
| 20 | =head1 NAME | ||
| 21 | |||
| 22 | YAGL - Yet Another Graph Library | ||
| 23 | |||
| 24 | =head1 VERSION | ||
| 25 | |||
| 26 | version 0.1 | ||
| 27 | |||
| 28 | =head1 SYNOPSIS | ||
| 29 | |||
| 30 | use YAGL; | ||
| 31 | |||
| 32 | my $g = YAGL->new; | ||
| 33 | |||
| 34 | # Populate the graph with 124 vertices, with randomly allocated | ||
| 35 | # weighted edges between some of the vertices. The 'p' argument is | ||
| 36 | # the probability that a given node A will *not* be connected to | ||
| 37 | # another randomly selected node B. | ||
| 38 | |||
| 39 | $g->generate_random_vertices( | ||
| 40 | { n => 124, p => 0.1, max_weight => 100_000 } ); | ||
| 41 | |||
| 42 | # Add vertices to the graph. | ||
| 43 | |||
| 44 | $g->add_vertex('abc123'); | ||
| 45 | $g->add_vertex('xyz789'); | ||
| 46 | $g->add_vertex('I_AM_A_TEST'); | ||
| 47 | |||
| 48 | # Add edges to the graph. You can store arbitrary attributes on | ||
| 49 | # edges in hashrefs. | ||
| 50 | |||
| 51 | $g->add_edge( 'abc123', 'xyz789', { weight => 1_000_000 } ); | ||
| 52 | $g->add_edge( 'I_AM_A_TEST', 'abc123', { weight => 12345 } ); | ||
| 53 | |||
| 54 | # Write the graph out to a CSV file. This file can be read back | ||
| 55 | # in later with the 'read_csv' method. The CSV format is limited, | ||
| 56 | # it can only store the following columns: | ||
| 57 | # node,neighbor,weight,is_directed | ||
| 58 | |||
| 59 | $g->write_csv('foo.csv'); | ||
| 60 | |||
| 61 | # Pick a start and end vertex at random from the graph. | ||
| 62 | |||
| 63 | my @vertices = $g->get_vertices; | ||
| 64 | |||
| 65 | my $i = int rand @vertices; | ||
| 66 | my $j = int rand @vertices; | ||
| 67 | my $start = $vertices[$i]; | ||
| 68 | my $end = $vertices[$j]; | ||
| 69 | |||
| 70 | # Using breadth-first search, find a path between the start and | ||
| 71 | # end vertices, if any such path exists. Otherwise, this method | ||
| 72 | # returns undef. | ||
| 73 | |||
| 74 | my @path; | ||
| 75 | @path = $g->find_path_between( $start, $end ); | ||
| 76 | |||
| 77 | # Get a string representation of the graph in the graphviz | ||
| 78 | # language for passing along to graphviz tools like `dot`. | ||
| 79 | |||
| 80 | my $dot_string = $g->to_graphviz; | ||
| 81 | |||
| 82 | # Color the vertices | ||
| 83 | |||
| 84 | $g->color_vertices; | ||
| 85 | |||
| 86 | # Find a Hamiltonian cycle in the graph, if any exist: | ||
| 87 | |||
| 88 | $g->hamiltonian_walks(closed => 1, n_solutions => 1); | ||
| 89 | |||
| 90 | =head1 DESCRIPTION | ||
| 91 | |||
| 92 | This library implements a | ||
| 93 | L<graph|https://en.wikipedia.org/wiki/Graph_(discrete_mathematics)> | ||
| 94 | data structure, and a number of common algorithms on graphs. It can | ||
| 95 | be used for both directed and undirected graphs. Features include: | ||
| 96 | |||
| 97 | =over | ||
| 98 | |||
| 99 | =item * Generating random graphs. | ||
| 100 | |||
| 101 | =item * Serializing graphs to and from CSV files. | ||
| 102 | |||
| 103 | =item * Vertices and edges can have arbitrary attributes associated | ||
| 104 | with them (stored in hashrefs). | ||
| 105 | |||
| 106 | =item * Breadth-first search (BFS) to find the shortest path between | ||
| 107 | two nodes. | ||
| 108 | |||
| 109 | =item * Depth-first search (DFS). | ||
| 110 | |||
| 111 | =item * Find minimum spanning trees of weighted graphs. | ||
| 112 | |||
| 113 | =item * List the connected components. | ||
| 114 | |||
| 115 | =item * Dijkstra's algorithm for finding the shortest path through a | ||
| 116 | weighted graph. | ||
| 117 | |||
| 118 | =item * A general method for exhaustive search with backtracking. | ||
| 119 | |||
| 120 | =item * Finding Hamiltonian walks (open and closed) using exhaustive | ||
| 121 | search with backtracking. | ||
| 122 | |||
| 123 | =item * Vertex coloring. | ||
| 124 | |||
| 125 | =back | ||
| 126 | |||
| 127 | For a possibly interesting example, see the file | ||
| 128 | C<examples/ladders.pl>, which is an approximate port to Perl of the | ||
| 129 | C<LADDERS> program from the book I<The Stanford GraphBase> by Donald | ||
| 130 | E. Knuth. It uses Dijkstra's algorithm to build a "word ladder" of | ||
| 131 | the form: | ||
| 132 | |||
| 133 | WORDS - WOODS - GOODS - GOADS - GRADS - GRADE - GRAPE - GRAPH | ||
| 134 | |||
| 135 | Finally, note that this library is still in development. There are | ||
| 136 | some important algorithms that are not yet implemented. Also, some | ||
| 137 | algorithms that are implemented for undirected graphs are not yet | ||
| 138 | implemented for directed graphs. Test coverage is OK, but can still | ||
| 139 | be improved. | ||
| 140 | |||
| 141 | =head1 METHODS | ||
| 142 | |||
| 143 | =head2 INITIALIZATION AND RANDOMIZATION | ||
| 144 | |||
| 145 | =over | ||
| 146 | |||
| 147 | =item C<new> | ||
| 148 | |||
| 149 | Initialize a new undirected graph: | ||
| 150 | |||
| 151 | my $g = YAGL->new; | ||
| 152 | |||
| 153 | To make a directed graph, set the C<is_directed> argument: | ||
| 154 | |||
| 155 | my $g = YAGL->new(is_directed => 1); | ||
| 156 | |||
| 157 | Note that a YAGL object must be set as directed or undirected when | ||
| 158 | it's created, and it can't be changed later. | ||
| 159 | |||
| 160 | =cut | ||
| 161 | |||
| 162 | sub new { | ||
| 163 | my ($self, @args) = @_; | ||
| 164 | my $graph = {}; | ||
| 165 | |||
| 166 | my %args = @args; | ||
| 167 | $graph->{_INTERNAL}->{is_directed} = $args{is_directed}; | ||
| 168 | |||
| 169 | $graph->{_INTERNAL}->{edge_attrs} = {}; | ||
| 170 | $graph->{_INTERNAL}->{vertex_attrs} = {}; | ||
| 171 | |||
| 172 | bless $graph, $self; | ||
| 173 | return $graph; | ||
| 174 | } | ||
| 175 | |||
| 176 | =item C<generate_random_vertices> | ||
| 177 | |||
| 178 | Generate C<n> vertices with random names, and distribute edges | ||
| 179 | randomly among them with a 1-C<p> probability of connection. Further, | ||
| 180 | assign random weights to each edge up to the value of C<max_weight>. | ||
| 181 | |||
| 182 | Note that this needs to be called on a graph object that already | ||
| 183 | exists. Also, it is usually best to call this on a brand new, empty | ||
| 184 | graph, since it will overwrite or update existing vertices and edges | ||
| 185 | if the random vertex name generator comes up with a name that is | ||
| 186 | already in use. This is unlikely in practice since the random names | ||
| 187 | are alphanumeric gibberish like "cu991". | ||
| 188 | |||
| 189 | Example: | ||
| 190 | |||
| 191 | my $g = YAGL->new; | ||
| 192 | $g->generate_random_vertices({n => 48, p => 0.1, max_weight => 1000}); | ||
| 193 | |||
| 194 | Arguments: | ||
| 195 | |||
| 196 | =over | ||
| 197 | |||
| 198 | =item C<n> | ||
| 199 | |||
| 200 | Number of vertices. | ||
| 201 | |||
| 202 | =item C<p> | ||
| 203 | |||
| 204 | Probability that a given vertex I<A> will B<not> be connected to | ||
| 205 | another randomly selected vertex I<B>. In other words, the | ||
| 206 | probability that I<A> will be connected to I<B> is 1-C<p>. | ||
| 207 | |||
| 208 | =item C<max_weight> | ||
| 209 | |||
| 210 | All edges are given a random integer weight less than or equal to this | ||
| 211 | number. | ||
| 212 | |||
| 213 | =back | ||
| 214 | |||
| 215 | =cut | ||
| 216 | |||
| 217 | sub generate_random_vertices { | ||
| 218 | ## HashRef -> State! | ||
| 219 | my ($self, $args) = @_; | ||
| 220 | |||
| 221 | my $n = $args->{n}; | ||
| 222 | |||
| 223 | # As we loop through the nodes, for each node A, this is the | ||
| 224 | # probability that another randomly selected node B is NOT | ||
| 225 | # connected to A. In other words, this is the probability that | ||
| 226 | # there is NOT an edge A-B. | ||
| 227 | my $p = $args->{p}; | ||
| 228 | my $max_weight = $args->{max_weight}; | ||
| 229 | |||
| 230 | my %seen; | ||
| 231 | |||
| 232 | for my $node (1 .. $n) { | ||
| 233 | my $name = $self->_make_vertex_name; | ||
| 234 | redo if $seen{$name}; | ||
| 235 | $seen{$name}++; | ||
| 236 | } | ||
| 237 | |||
| 238 | my @nodes = keys %seen; | ||
| 239 | |||
| 240 | my @pairs; | ||
| 241 | |||
| 242 | for my $node (@nodes) { | ||
| 243 | my $maybe_neighbor = $nodes[rand $#nodes]; | ||
| 244 | next if $maybe_neighbor eq $node; | ||
| 245 | my $connection_prob = rand 1; | ||
| 246 | my $dist = int rand $max_weight; | ||
| 247 | if ($connection_prob > $p) { | ||
| 248 | push @pairs, [$node, $maybe_neighbor, $dist]; | ||
| 249 | unless ($self->is_directed) { | ||
| 250 | push @pairs, [$maybe_neighbor, $node, $dist]; | ||
| 251 | } | ||
| 252 | } | ||
| 253 | redo if rand 1 > 0.8; # Sometimes, add more neighbors to this node. | ||
| 254 | } | ||
| 255 | |||
| 256 | for my $pair (@pairs) { | ||
| 257 | $self->add_edge($pair->[0], $pair->[1], {weight => $pair->[2]}); | ||
| 258 | } | ||
| 259 | } | ||
| 260 | |||
| 261 | =back | ||
| 262 | |||
| 263 | =head2 SERIALIZATION | ||
| 264 | |||
| 265 | =over | ||
| 266 | |||
| 267 | =item write_csv | ||
| 268 | |||
| 269 | Write a CSV representation of this graph out to a (named) file. | ||
| 270 | |||
| 271 | =cut | ||
| 272 | |||
| 273 | sub write_csv { | ||
| 274 | ## Filename -> State! IO! | ||
| 275 | my ($self, $f) = @_; | ||
| 276 | |||
| 277 | open my $fh, '>:encoding(utf8)', $f or die "Can't open file '$f': $!\n"; | ||
| 278 | |||
| 279 | say $fh qq[node,neighbor,weight,is_directed]; | ||
| 280 | |||
| 281 | my @vertices = $self->get_vertices; | ||
| 282 | |||
| 283 | for my $vertex (@vertices) { | ||
| 284 | my $neighbors = $self->get_neighbors($vertex); | ||
| 285 | for my $neighbor (@$neighbors) { | ||
| 286 | next unless defined $neighbor; | ||
| 287 | my $weight | ||
| 288 | = $self->get_edge_attribute($vertex, $neighbor, 'weight') || 0; | ||
| 289 | my @cols = ($vertex, $neighbor, $weight); | ||
| 290 | $self->is_directed ? push @cols, '1' : push @cols, '0'; | ||
| 291 | my $line = join ',', @cols; | ||
| 292 | say $fh $line; | ||
| 293 | } | ||
| 294 | } | ||
| 295 | close $fh; | ||
| 296 | } | ||
| 297 | |||
| 298 | =item read_lst | ||
| 299 | |||
| 300 | Read in a *.lst file that represents a graph (from L<https://hog.grinvin.org>). | ||
| 301 | |||
| 302 | =cut | ||
| 303 | |||
| 304 | sub read_lst { | ||
| 305 | my ($self, $lst_file) = @_; | ||
| 306 | |||
| 307 | my $csv_file = qq[$lst_file.csv]; | ||
| 308 | open my $output_fh, '>', $csv_file | ||
| 309 | or die "Can't open file '$csv_file': $!\n"; | ||
| 310 | |||
| 311 | open my $input_fh, '<', $lst_file | ||
| 312 | or die "Can't open file '$lst_file': $!\n"; | ||
| 313 | |||
| 314 | say $output_fh qq[node,neighbor,weight,is_directed]; | ||
| 315 | while (my $line = <$input_fh>) { | ||
| 316 | next unless $line =~ /[A-Z0-9]: [A-Z0-9]+/; # Skip empty lines. | ||
| 317 | my ($node, $neighbors) = split /:/, $line; | ||
| 318 | chomp($node) if defined $node; | ||
| 319 | chomp($neighbors) if defined $neighbors; | ||
| 320 | my @neighbors = grep { $_ ne '' } split / /, $neighbors; | ||
| 321 | |||
| 322 | for my $n (@neighbors) { | ||
| 323 | say $output_fh qq["$node","$n",0,0]; | ||
| 324 | } | ||
| 325 | } | ||
| 326 | close $input_fh; | ||
| 327 | close $output_fh; | ||
| 328 | |||
| 329 | $self->read_csv($csv_file); | ||
| 330 | } | ||
| 331 | |||
| 332 | =item read_hcp | ||
| 333 | |||
| 334 | Read in a *.hcp file that represents a graph (from L<https://sites.flinders.edu.au/flinders-hamiltonian-cycle-project/fhcp-challenge-set>). | ||
| 335 | |||
| 336 | =cut | ||
| 337 | |||
| 338 | sub read_hcp { | ||
| 339 | my ($self, $hcp_file) = @_; | ||
| 340 | |||
| 341 | my $csv_file = qq[$hcp_file.csv]; | ||
| 342 | open my $output_fh, '>', $csv_file; | ||
| 343 | open my $input_fh, '<', $hcp_file | ||
| 344 | or die "Can't open file '$hcp_file': $!\n"; | ||
| 345 | say $output_fh qq[node,neighbor,weight,is_directed]; | ||
| 346 | |||
| 347 | LINE: while (my $line = <$input_fh>) { | ||
| 348 | next LINE unless $line =~ /^([0-9]+) ([0-9]+)/; | ||
| 349 | my ($e1, $e2) = ($1, $2); | ||
| 350 | say $output_fh qq["$e1","$e2",0,0]; | ||
| 351 | say $output_fh qq["$e2","$e1",0,0]; | ||
| 352 | } | ||
| 353 | close $input_fh; | ||
| 354 | close $output_fh; | ||
| 355 | |||
| 356 | $self->read_csv($csv_file); | ||
| 357 | } | ||
| 358 | |||
| 359 | =item read_csv | ||
| 360 | |||
| 361 | Read in a CSV file that represents a graph. | ||
| 362 | |||
| 363 | =cut | ||
| 364 | |||
| 365 | sub read_csv { | ||
| 366 | ## Filename -> State! IO! | ||
| 367 | my ($self, $f) = @_; | ||
| 368 | |||
| 369 | my $csv = Text::CSV->new({binary => 1}); | ||
| 370 | |||
| 371 | open my $fh, "<:encoding(utf8)", $f or die "Can't open file '$f': $!\n"; | ||
| 372 | |||
| 373 | my %seen; | ||
| 374 | LINE: while (my $line = $csv->getline($fh)) { | ||
| 375 | my @cols = @$line; | ||
| 376 | my $vertex = $cols[0]; | ||
| 377 | my $neighbor = $cols[1]; | ||
| 378 | my $weight = $cols[2]; | ||
| 379 | my $is_directed = $cols[3]; | ||
| 380 | |||
| 381 | next LINE if $vertex eq 'node'; | ||
| 382 | if ($self->is_directed) { | ||
| 383 | if ($seen{$neighbor . $vertex}) { | ||
| 384 | next LINE; | ||
| 385 | } | ||
| 386 | } | ||
| 387 | |||
| 388 | die qq[Directed graph cannot read in serialized undirected graph\n] | ||
| 389 | if ($self->is_directed && !$is_directed); | ||
| 390 | |||
| 391 | die qq[Undirected graph cannot read in serialized directed graph\n] | ||
| 392 | if (!$self->is_directed && $is_directed); | ||
| 393 | $self->add_edge($vertex, $neighbor, {weight => $weight}); | ||
| 394 | $seen{$neighbor . $vertex}++; | ||
| 395 | } | ||
| 396 | } | ||
| 397 | |||
| 398 | =item to_graphviz | ||
| 399 | |||
| 400 | Generate a Graphviz representation of this graph (really, a string). | ||
| 401 | |||
| 402 | =cut | ||
| 403 | |||
| 404 | sub to_graphviz { | ||
| 405 | ## ArrayRef -> String | ||
| 406 | my ( $self, $path ) = @_; | ||
| 407 | |||
| 408 | my @buffer; | ||
| 409 | my %seen; | ||
| 410 | |||
| 411 | push @buffer, qq[graph { \n]; | ||
| 412 | |||
| 413 | VERTEX: for my $vertex ( $self->get_vertices ) { | ||
| 414 | next VERTEX unless defined $vertex; | ||
| 415 | if (defined $path && _memberp($vertex, $path)) { | ||
| 416 | push @buffer, qq{$vertex [style=filled fillcolor=red] \n}; | ||
| 417 | } | ||
| 418 | |||
| 419 | my $neighbors = $self->get_neighbors($vertex); | ||
| 420 | |||
| 421 | # "graph" is a keyword in `dot` and must be quoted. | ||
| 422 | $vertex = qq["graph"] if $vertex =~ /graph/; | ||
| 423 | |||
| 424 | NEIGHBOR: for my $neighbor (@$neighbors) { | ||
| 425 | next NEIGHBOR unless defined $neighbor; | ||
| 426 | next NEIGHBOR if $seen{$vertex . ';' . $neighbor}; | ||
| 427 | next NEIGHBOR if $seen{$neighbor . ';' . $vertex}; | ||
| 428 | |||
| 429 | # "graph" is a keyword in `dot` and must be quoted. | ||
| 430 | $neighbor = qq["graph"] if $neighbor =~ /graph/; | ||
| 431 | |||
| 432 | # We create a line in the *.dot file for every | ||
| 433 | # vertex-neighbor pair. This is necessary to add the edge | ||
| 434 | # labels (in this case, weights). | ||
| 435 | if (defined $path && _memberp($neighbor, $path)) { | ||
| 436 | push @buffer, qq{$neighbor [style=filled fillcolor=red] \n}; | ||
| 437 | } | ||
| 438 | |||
| 439 | push @buffer, $vertex; | ||
| 440 | push @buffer, qq[ -- ]; | ||
| 441 | push @buffer, qq[ { ]; | ||
| 442 | |||
| 443 | my $edge_weight | ||
| 444 | = $self->get_edge_attribute($vertex, $neighbor, 'weight'); | ||
| 445 | my $edge_color | ||
| 446 | = $self->get_edge_attribute($vertex, $neighbor, 'color'); | ||
| 447 | my $penwidth = $edge_color ? "penwidth=5" : ''; | ||
| 448 | my $vertex_color = $self->get_vertex_color($neighbor); | ||
| 449 | my $fillcolor = $vertex_color ? qq[fillcolor=$vertex_color] : ''; | ||
| 450 | my $label_edge_weight = $edge_weight ? qq{[label=$edge_weight]} : ''; | ||
| 451 | my $vertex_label = qq[label=$neighbor]; | ||
| 452 | my $color_edge_color = $edge_color ? qq[color=$edge_color] : ''; | ||
| 453 | unless ($seen{$vertex . ';' . $neighbor}) { | ||
| 454 | push @buffer, qq{$neighbor [$fillcolor $vertex_label $color_edge_color $penwidth]}; | ||
| 455 | } | ||
| 456 | $seen{$neighbor . ';' . $vertex}++ unless $self->is_directed; | ||
| 457 | $seen{$vertex . ';' . $neighbor}++; | ||
| 458 | push @buffer, qq[ } $label_edge_weight\n]; | ||
| 459 | } | ||
| 460 | } | ||
| 461 | push @buffer, qq[ } ]; | ||
| 462 | return join ' ', @buffer; | ||
| 463 | } | ||
| 464 | |||
| 465 | =item draw | ||
| 466 | |||
| 467 | Given a file name, dumps a representation of the graph (as GraphViz) | ||
| 468 | and uses C<dot> to build an image of the graph. All of this happens | ||
| 469 | in C<$TMPDIR>. This assumes you have a copy of C<dot> on your system. | ||
| 470 | |||
| 471 | $g->draw('24-ham-00'); | ||
| 472 | # To view the file, open $TMPDIR/24-ham-00.jpg | ||
| 473 | |||
| 474 | =cut | ||
| 475 | |||
| 476 | sub draw { | ||
| 477 | ## String -> State! IO! | ||
| 478 | my ($self, $basename, $path) = @_; | ||
| 479 | |||
| 480 | die qq[draw() must be passed a filename argument!] unless $basename; | ||
| 481 | |||
| 482 | my $tmpdir = $ENV{Temp} || $ENV{TMPDIR} || '/tmp'; | ||
| 483 | my $filename = qq[$tmpdir/$basename.dot]; | ||
| 484 | my $viz = $path ? $self->to_graphviz($path) : $self->to_graphviz; | ||
| 485 | open my $fh, '>', $filename or die $!; | ||
| 486 | say $fh $viz; | ||
| 487 | close $fh; | ||
| 488 | system qq[dot -O -Tjpg $filename]; | ||
| 489 | } | ||
| 490 | |||
| 491 | =back | ||
| 492 | |||
| 493 | =head2 BOOLEAN METHODS | ||
| 494 | |||
| 495 | =over | ||
| 496 | |||
| 497 | =item is_empty | ||
| 498 | |||
| 499 | Returns true if the graph is empty - that is, if it has no vertices. | ||
| 500 | |||
| 501 | =cut | ||
| 502 | |||
| 503 | sub is_empty { | ||
| 504 | ## -> Boolean | ||
| 505 | my $self = shift; | ||
| 506 | my @vertices = $self->get_vertices; | ||
| 507 | |||
| 508 | if (scalar @vertices >= 1) { | ||
| 509 | return; | ||
| 510 | } | ||
| 511 | else { | ||
| 512 | return 1; | ||
| 513 | } | ||
| 514 | } | ||
| 515 | |||
| 516 | =item is_complete | ||
| 517 | |||
| 518 | Return true if this is a complete graph. A complete graph is one | ||
| 519 | wherein each vertex is connected to every other vertex. | ||
| 520 | |||
| 521 | =cut | ||
| 522 | |||
| 523 | sub is_complete { | ||
| 524 | my $self = shift; | ||
| 525 | |||
| 526 | my @vertices = $self->get_vertices; | ||
| 527 | my $v = pop @vertices; | ||
| 528 | |||
| 529 | my $neighbors = $self->get_neighbors($v); | ||
| 530 | |||
| 531 | @vertices = sort { ($a || '') cmp($b || '') } @vertices; | ||
| 532 | my @neighbors = sort { ($a || '') cmp($b || '') } @$neighbors; | ||
| 533 | |||
| 534 | return 1 if _array_eq(\@vertices, \@neighbors); | ||
| 535 | |||
| 536 | return; | ||
| 537 | } | ||
| 538 | |||
| 539 | =item is_tree | ||
| 540 | |||
| 541 | Return true if this graph is a tree. A graph is a tree if its number | ||
| 542 | of edges is one fewer than its number of vertices. This definition is | ||
| 543 | taken from Even's book I<Graph Algorithms>. | ||
| 544 | |||
| 545 | =cut | ||
| 546 | |||
| 547 | sub is_tree { | ||
| 548 | my ($self) = @_; | ||
| 549 | |||
| 550 | return unless $self->is_connected; | ||
| 551 | |||
| 552 | my @e = $self->get_edges; | ||
| 553 | my @v = $self->get_vertices; | ||
| 554 | |||
| 555 | my $e = @e; | ||
| 556 | my $v = @v; | ||
| 557 | |||
| 558 | return unless $e == $v - 1; | ||
| 559 | } | ||
| 560 | |||
| 561 | =item is_connected | ||
| 562 | |||
| 563 | Return true if for each vertex A in this graph, there is a path | ||
| 564 | between A and every other vertex in the graph. | ||
| 565 | |||
| 566 | =cut | ||
| 567 | |||
| 568 | sub is_connected { | ||
| 569 | my ($self) = @_; | ||
| 570 | |||
| 571 | die qq[is_connected() - not implemented for directed graphs] | ||
| 572 | if $self->is_directed; | ||
| 573 | |||
| 574 | my @vertices = $self->get_vertices; | ||
| 575 | |||
| 576 | my $start = pop @vertices; | ||
| 577 | |||
| 578 | for my $v (@vertices) { | ||
| 579 | return unless $self->find_path_between($start, $v); | ||
| 580 | } | ||
| 581 | return 1; | ||
| 582 | } | ||
| 583 | |||
| 584 | =item has_cycle | ||
| 585 | |||
| 586 | Return true if there is a cycle in this graph; in other words, if this | ||
| 587 | graph is not a tree. | ||
| 588 | |||
| 589 | =cut | ||
| 590 | |||
| 591 | sub has_cycle { | ||
| 592 | my ($self) = @_; | ||
| 593 | return $self->is_tree ? undef : 1; | ||
| 594 | } | ||
| 595 | |||
| 596 | =item is_colored | ||
| 597 | |||
| 598 | Return true if this graph has already been colored using the | ||
| 599 | C<color_vertices> method. | ||
| 600 | |||
| 601 | =cut | ||
| 602 | |||
| 603 | sub is_colored { | ||
| 604 | ## -> Number | ||
| 605 | my ($self) = @_; | ||
| 606 | my @vertices = $self->get_vertices; | ||
| 607 | my @colors = grep { $self->get_vertex_color($_) } @vertices; | ||
| 608 | |||
| 609 | return scalar @vertices == scalar @colors; | ||
| 610 | } | ||
| 611 | |||
| 612 | =item is_directed | ||
| 613 | |||
| 614 | Return true if this is a directed graph. Graphs can only be marked as | ||
| 615 | directed during object initialization, by setting the C<is_directed> | ||
| 616 | argument to C<new>. | ||
| 617 | |||
| 618 | =cut | ||
| 619 | |||
| 620 | sub is_directed { | ||
| 621 | my ($self) = @_; | ||
| 622 | return $self->{_INTERNAL}->{is_directed}; | ||
| 623 | } | ||
| 624 | |||
| 625 | =item C<is_bipartite> | ||
| 626 | |||
| 627 | Returns true if the graph G is bipartite. False otherwise. | ||
| 628 | |||
| 629 | Note that this method operates on a copy of the graph, to avoid | ||
| 630 | overwriting any existing vertex colorings. | ||
| 631 | |||
| 632 | =back | ||
| 633 | |||
| 634 | =cut | ||
| 635 | |||
| 636 | sub is_bipartite { | ||
| 637 | ## -> Boolean State! | ||
| 638 | my ($self) = @_; | ||
| 639 | $self->color_vertices; | ||
| 640 | my $n = $self->chromatic_number; | ||
| 641 | |||
| 642 | return unless $n == 2; | ||
| 643 | return 1; | ||
| 644 | } | ||
| 645 | |||
| 646 | =head2 METHODS ON VERTICES | ||
| 647 | |||
| 648 | =over | ||
| 649 | |||
| 650 | =item add_vertex | ||
| 651 | |||
| 652 | Add a vertex V to this graph, if it does not already exist. Return | ||
| 653 | C<undef> if V already exists. | ||
| 654 | |||
| 655 | $g->add_vertex('s'); | ||
| 656 | |||
| 657 | =cut | ||
| 658 | |||
| 659 | sub add_vertex { | ||
| 660 | ## String -> State! | ||
| 661 | my ($self, $vertex) = @_; | ||
| 662 | return if $self->has_vertex($vertex); | ||
| 663 | $self->{$vertex} = []; | ||
| 664 | } | ||
| 665 | |||
| 666 | =item add_vertices | ||
| 667 | |||
| 668 | Add multiple vertices to this graph. Takes an array as its argument. | ||
| 669 | |||
| 670 | my @to_add = qw/a b c d e f/; | ||
| 671 | $g->add_vertices(@to_add); | ||
| 672 | |||
| 673 | =cut | ||
| 674 | |||
| 675 | sub add_vertices { | ||
| 676 | my ($self, @vertices) = @_; | ||
| 677 | $self->add_vertex($_) for @vertices; | ||
| 678 | } | ||
| 679 | |||
| 680 | =item get_neighbors | ||
| 681 | |||
| 682 | Given a vertex in the graph, get its neighbors - that is, the other | ||
| 683 | vertices to which it is connected. | ||
| 684 | |||
| 685 | $g->get_neighbors('s'); | ||
| 686 | |||
| 687 | =cut | ||
| 688 | |||
| 689 | sub get_neighbors { | ||
| 690 | ## String -> ArrayRef | ||
| 691 | my ($self, $vertex) = @_; | ||
| 692 | |||
| 693 | return unless $self->has_vertex($vertex); | ||
| 694 | |||
| 695 | if (exists $self->{$vertex}) { | ||
| 696 | return $self->{$vertex} if defined $self->{$vertex}; | ||
| 697 | } | ||
| 698 | else { | ||
| 699 | return; | ||
| 700 | } | ||
| 701 | } | ||
| 702 | |||
| 703 | =item has_vertex | ||
| 704 | |||
| 705 | Return true if the vertex in question is a part of the graph. | ||
| 706 | |||
| 707 | $g->has_vertex('a'); | ||
| 708 | |||
| 709 | =cut | ||
| 710 | |||
| 711 | sub has_vertex { | ||
| 712 | ## String -> Boolean | ||
| 713 | my ($self, $vertex) = @_; | ||
| 714 | return unless defined $vertex; | ||
| 715 | if (exists $self->{$vertex} && defined $self->{$vertex}) { | ||
| 716 | return 1; | ||
| 717 | } | ||
| 718 | return; | ||
| 719 | } | ||
| 720 | |||
| 721 | =item remove_vertex | ||
| 722 | |||
| 723 | Remove the named vertex from the graph, if it exists. | ||
| 724 | |||
| 725 | $g->remove_vertex('s'); | ||
| 726 | |||
| 727 | Note that removing a vertex will also delete all edges (and edge | ||
| 728 | attributes) between the given vertex and its former neighbors. | ||
| 729 | |||
| 730 | =cut | ||
| 731 | |||
| 732 | sub remove_vertex { | ||
| 733 | ## String -> State! | ||
| 734 | my ($self, $vertex) = @_; | ||
| 735 | |||
| 736 | my $neighbors = $self->get_neighbors($vertex); | ||
| 737 | |||
| 738 | # Our general strategy for deleting things is to set the vertex's | ||
| 739 | # position in the array of arrays graph representation to undef. | ||
| 740 | # | ||
| 741 | # In this pass, we delete all edges between each of this vertex's | ||
| 742 | # neighbor and the vertex. Note the order of the arguments: | ||
| 743 | # | ||
| 744 | # - Because we are deleting *this* vertex (and *not* the | ||
| 745 | # neighbor), we have the neighbor (which is not being deleted) set | ||
| 746 | # its connection to this vertex to undef (i.e., deleted). | ||
| 747 | # | ||
| 748 | # - Then, we delete any edge attributes that exist between the two | ||
| 749 | # vertices (since there is no edge there anymore). | ||
| 750 | for my $neighbor (@$neighbors) { | ||
| 751 | $self->_remove_neighbor($neighbor, $vertex); | ||
| 752 | $self->delete_edge_attributes($vertex, $neighbor); | ||
| 753 | } | ||
| 754 | |||
| 755 | # Then, we delete the "root" reference to the vertex by setting it | ||
| 756 | # to undef. | ||
| 757 | if (exists $self->{$vertex}) { | ||
| 758 | delete $self->{$vertex}; | ||
| 759 | } | ||
| 760 | } | ||
| 761 | |||
| 762 | =item get_vertices | ||
| 763 | |||
| 764 | Return a list of the vertices in the graph. | ||
| 765 | |||
| 766 | my @v = $g->get_vertices; | ||
| 767 | |||
| 768 | =cut | ||
| 769 | |||
| 770 | sub get_vertices { | ||
| 771 | ## -> Array | ||
| 772 | my $self = shift; | ||
| 773 | my @vertices; | ||
| 774 | for my $vertex (keys %$self) { | ||
| 775 | next unless defined $vertex; | ||
| 776 | next if $vertex eq '_INTERNAL'; | ||
| 777 | push @vertices, $vertex; | ||
| 778 | } | ||
| 779 | |||
| 780 | # TODO(rml): Remove this call to C<sort>. It has a large | ||
| 781 | # performance cost for large graphs. On a recent "word ladder" | ||
| 782 | # run with the 5757-vertex WORDS graph from the Stanford | ||
| 783 | # Graphbase, of 522s of runtime, this call to C<sort> cost 30s | ||
| 784 | # (30/522 = ~6%). | ||
| 785 | |||
| 786 | # AFAICT there is no good reason for the sorting; it was done to | ||
| 787 | # get some tests to pass -- likely the graph cloning equality | ||
| 788 | # tests, if memory serves. Therefore the action item is to remove | ||
| 789 | # this call to C<sort>, see what breaks in the tests, and fix it. | ||
| 790 | |||
| 791 | @vertices = sort @vertices; | ||
| 792 | return @vertices; | ||
| 793 | } | ||
| 794 | |||
| 795 | =item get_degree | ||
| 796 | |||
| 797 | Given a vertex V, return the degree of that vertex -- that is, the | ||
| 798 | number of edges between V and other vertices (its neighbors). | ||
| 799 | |||
| 800 | =cut | ||
| 801 | |||
| 802 | sub get_degree { | ||
| 803 | my ($self, $vertex) = @_; | ||
| 804 | if ($self->has_vertex($vertex)) { | ||
| 805 | my $neighbors = $self->get_neighbors($vertex); | ||
| 806 | return scalar @$neighbors; | ||
| 807 | } | ||
| 808 | return; | ||
| 809 | } | ||
| 810 | |||
| 811 | =item set_vertex_attribute | ||
| 812 | |||
| 813 | Given a vertex V, store a hashref of attributes about that vertex. | ||
| 814 | |||
| 815 | =cut | ||
| 816 | |||
| 817 | sub set_vertex_attribute { | ||
| 818 | ## String HashRef -> State! | ||
| 819 | my ($self, $vertex, $new_attrs) = @_; | ||
| 820 | return unless $self->has_vertex($vertex); | ||
| 821 | |||
| 822 | # Attributes hashref already exists, so we add to it. NOTE: | ||
| 823 | # this is a hash so the update is destructive. | ||
| 824 | for (my ($k, $v) = each %$new_attrs) { | ||
| 825 | next unless defined $k; | ||
| 826 | next if $k eq ''; | ||
| 827 | $self->{_INTERNAL}->{vertex_attrs}->{$vertex}->{$k} = $v; | ||
| 828 | } | ||
| 829 | } | ||
| 830 | |||
| 831 | =item get_vertex_attribute | ||
| 832 | |||
| 833 | Given a vertex V and an attribute string, retrieve the value of that attribute. | ||
| 834 | |||
| 835 | my $weight = $g->get_vertex_attribute('s', 'weight'); | ||
| 836 | # 123 | ||
| 837 | |||
| 838 | =cut | ||
| 839 | |||
| 840 | sub get_vertex_attribute { | ||
| 841 | ## String String -> Value OR undef | ||
| 842 | my ($self, $vertex, $attribute) = @_; | ||
| 843 | return unless $self->has_vertex($vertex); | ||
| 844 | return $self->{_INTERNAL}->{vertex_attrs}->{$vertex}->{$attribute}; | ||
| 845 | } | ||
| 846 | |||
| 847 | =item get_vertex_attributes | ||
| 848 | |||
| 849 | Given a vertex V, return all of the vertex's attributes, whatever they | ||
| 850 | are. Reads from the object's internal hashref, so beware: these | ||
| 851 | values could be anything. | ||
| 852 | |||
| 853 | my $attrs = $g->get_vertex_attributes('s'); | ||
| 854 | |||
| 855 | =cut | ||
| 856 | |||
| 857 | sub get_vertex_attributes { | ||
| 858 | ## String -> HashRef OR undef | ||
| 859 | my ($self, $vertex) = @_; | ||
| 860 | return unless $self->has_vertex($vertex); | ||
| 861 | return $self->{_INTERNAL}->{vertex_attrs}->{$vertex}; | ||
| 862 | } | ||
| 863 | |||
| 864 | =item delete_vertex_attributes | ||
| 865 | |||
| 866 | Given a vertex V, delete all of its attributes (if any). | ||
| 867 | |||
| 868 | $g->delete_vertex_attributes('s'); | ||
| 869 | |||
| 870 | =cut | ||
| 871 | |||
| 872 | sub delete_vertex_attributes { | ||
| 873 | ## String -> Undefined OR State! | ||
| 874 | my ($self, $vertex) = @_; | ||
| 875 | return unless $self->has_vertex($vertex); | ||
| 876 | delete $self->{_INTERNAL}->{vertex_attrs}->{$vertex}; | ||
| 877 | } | ||
| 878 | |||
| 879 | =item set_vertex_color | ||
| 880 | |||
| 881 | Given a vertex V and some color C, sets a 'color' attribute on | ||
| 882 | V. Shorthand for using C<set_vertex_attribute>. | ||
| 883 | |||
| 884 | $g->set_vertex_color('s', 'red'); | ||
| 885 | |||
| 886 | =cut | ||
| 887 | |||
| 888 | sub set_vertex_color { | ||
| 889 | ## String String -> Undefined OR State! | ||
| 890 | my ($self, $vertex, $color) = @_; | ||
| 891 | $self->set_vertex_attribute($vertex, {color => $color}); | ||
| 892 | } | ||
| 893 | |||
| 894 | =item get_vertex_color | ||
| 895 | |||
| 896 | Given a vertex V, get its color (if any). Shorthand for calling | ||
| 897 | C<get_vertex_attribute>. | ||
| 898 | |||
| 899 | $g->get_vertex_color('s'); | ||
| 900 | |||
| 901 | =back | ||
| 902 | |||
| 903 | =cut | ||
| 904 | |||
| 905 | sub get_vertex_color { | ||
| 906 | ## String -> String OR Undefined | ||
| 907 | my ($self, $vertex) = @_; | ||
| 908 | $self->get_vertex_attribute($vertex, 'color'); | ||
| 909 | } | ||
| 910 | |||
| 911 | =head2 METHODS ON EDGES | ||
| 912 | |||
| 913 | =over | ||
| 914 | |||
| 915 | =item get_edge | ||
| 916 | |||
| 917 | Get the edge between two vertices, A and B. Return C<undef> if no | ||
| 918 | such edge exists. If the edge does exist, return an array reference | ||
| 919 | containing A, B, and a (possibly empty) hash reference of edge | ||
| 920 | attributes. | ||
| 921 | |||
| 922 | my $edge = $g->get_edge('s', 'a'); | ||
| 923 | |||
| 924 | =cut | ||
| 925 | |||
| 926 | sub get_edge { | ||
| 927 | ## String String -> ArrayRef | ||
| 928 | my ($self, $a, $b) = @_; | ||
| 929 | |||
| 930 | return unless $self->edge_between($a, $b); | ||
| 931 | |||
| 932 | my $attrs = $self->get_edge_attributes($a, $b); | ||
| 933 | |||
| 934 | return [$a, $b, $attrs]; | ||
| 935 | } | ||
| 936 | |||
| 937 | =item get_edges | ||
| 938 | |||
| 939 | Get a list containing all of the edges in the graph. Specifically, | ||
| 940 | this will be a list of array references, with the contents of each | ||
| 941 | array reference as described in the documentation for C<get_edge()>. | ||
| 942 | |||
| 943 | my @edges = $g->get_edges; | ||
| 944 | |||
| 945 | =cut | ||
| 946 | |||
| 947 | sub get_edges { | ||
| 948 | ## -> Array | ||
| 949 | my ($self) = @_; | ||
| 950 | |||
| 951 | my @vertices = $self->get_vertices; | ||
| 952 | my @answer; | ||
| 953 | my %seen; | ||
| 954 | |||
| 955 | for my $vertex (@vertices) { | ||
| 956 | my $neighbors = $self->get_neighbors($vertex); | ||
| 957 | |||
| 958 | for my $neighbor (@$neighbors) { | ||
| 959 | next unless defined $neighbor; | ||
| 960 | next if $seen{$vertex . $neighbor}; | ||
| 961 | push @answer, $self->get_edge($vertex, $neighbor); | ||
| 962 | $seen{$vertex . $neighbor}++; | ||
| 963 | $seen{$neighbor . $vertex}++; | ||
| 964 | } | ||
| 965 | } | ||
| 966 | |||
| 967 | @answer = sort { $a->[0] lt $b->[0] } @answer; | ||
| 968 | return @answer; | ||
| 969 | } | ||
| 970 | |||
| 971 | =item edge_between | ||
| 972 | |||
| 973 | Given two vertices A and B, return something truthy if there exists an | ||
| 974 | edge between A and B. Otherwise, return C<undef>. | ||
| 975 | |||
| 976 | if ($g->edge_between('s', 'a')) { | ||
| 977 | say 'Yes'; | ||
| 978 | } | ||
| 979 | |||
| 980 | =cut | ||
| 981 | |||
| 982 | sub edge_between { | ||
| 983 | ## String String -> Boolean | ||
| 984 | my ($self, $a, $b) = @_; | ||
| 985 | |||
| 986 | return unless (defined $a && defined $b); | ||
| 987 | return 1 if $a eq $b; | ||
| 988 | |||
| 989 | my $neighbors = $self->get_neighbors($a); | ||
| 990 | if (_memberp($b, $neighbors)) { | ||
| 991 | return 1; | ||
| 992 | } | ||
| 993 | else { return; } | ||
| 994 | } | ||
| 995 | |||
| 996 | =item get_edge_attributes | ||
| 997 | |||
| 998 | Given two vertices A and B that have an edge between them, return | ||
| 999 | whatever attributes are stored for that edge. Note that this can be | ||
| 1000 | any arbitrary Perl data structure that could be stored in a hash | ||
| 1001 | reference. | ||
| 1002 | |||
| 1003 | =cut | ||
| 1004 | |||
| 1005 | sub get_edge_attributes { | ||
| 1006 | ## String String -> HashRef OR undef | ||
| 1007 | my ($self, $start, $end) = @_; | ||
| 1008 | |||
| 1009 | my $pairkey = $start . $end; | ||
| 1010 | return $self->{_INTERNAL}->{edge_attrs}->{$pairkey}; | ||
| 1011 | } | ||
| 1012 | |||
| 1013 | =item get_edge_attribute | ||
| 1014 | |||
| 1015 | Given two vertices A and B that have an edge between them, and a | ||
| 1016 | specific (text) attribute T, return whatever values are associated | ||
| 1017 | with T for that edge. For example, a (numeric) weight. | ||
| 1018 | |||
| 1019 | my $edge_weight = $g->get_edge_attribute('s', 'a', 'weight'); | ||
| 1020 | |||
| 1021 | =cut | ||
| 1022 | |||
| 1023 | sub get_edge_attribute { | ||
| 1024 | ## String String String -> Value OR undef | ||
| 1025 | my ($self, $start, $end, $attribute) = @_; | ||
| 1026 | return unless defined $start && defined $end; | ||
| 1027 | |||
| 1028 | my $pairkey = $start . $end; | ||
| 1029 | return $self->{_INTERNAL}->{edge_attrs}->{$pairkey}->{$attribute}; | ||
| 1030 | } | ||
| 1031 | |||
| 1032 | =item get_edge_weight | ||
| 1033 | |||
| 1034 | Shortcut for the following call to C<get_edge_attribute()>. | ||
| 1035 | |||
| 1036 | my $edge_weight = $g->get_edge_attribute('s', 'a', 'weight'); | ||
| 1037 | |||
| 1038 | =cut | ||
| 1039 | |||
| 1040 | sub get_edge_weight { | ||
| 1041 | ## String String -> Value OR undef | ||
| 1042 | my ($self, $start, $end, $attribute) = @_; | ||
| 1043 | |||
| 1044 | return $self->get_edge_attribute($start, $end, 'weight'); | ||
| 1045 | } | ||
| 1046 | |||
| 1047 | =item set_edge_attribute | ||
| 1048 | |||
| 1049 | Given two vertices A and B that have an edge between them, store a | ||
| 1050 | specific attribute key-value pair (a hash reference) that you want to | ||
| 1051 | associate with that edge. | ||
| 1052 | |||
| 1053 | my $edge_weight = $g->set_edge_attribute('s', 'a', { weight => 123 }); | ||
| 1054 | |||
| 1055 | =cut | ||
| 1056 | |||
| 1057 | sub set_edge_attribute { | ||
| 1058 | ## String String HashRef -> State! | ||
| 1059 | my ($self, $start, $end, $new_attrs) = @_; | ||
| 1060 | |||
| 1061 | my $pairkey1 = $start . $end; | ||
| 1062 | my $pairkey2 = $end . $start; | ||
| 1063 | |||
| 1064 | # Attributes hashref already exists, so we add to it. NOTE: | ||
| 1065 | # this is a hash so the update is destructive. | ||
| 1066 | for (my ($k, $v) = each %$new_attrs) { | ||
| 1067 | next unless defined $k; | ||
| 1068 | next if $k eq ''; | ||
| 1069 | $self->{_INTERNAL}->{edge_attrs}->{$pairkey1}->{$k} = $v; | ||
| 1070 | $self->{_INTERNAL}->{edge_attrs}->{$pairkey2}->{$k} = $v; | ||
| 1071 | } | ||
| 1072 | } | ||
| 1073 | |||
| 1074 | =item delete_edge_attributes | ||
| 1075 | |||
| 1076 | Given two vertices A and B that have an edge between them, delete all | ||
| 1077 | of the attributes (weight, color, etc.) associated with that edge. | ||
| 1078 | |||
| 1079 | $g->delete_edge_attributes('s', 'a'); | ||
| 1080 | |||
| 1081 | =cut | ||
| 1082 | |||
| 1083 | sub delete_edge_attributes { | ||
| 1084 | ## String String -> Undefined OR State! | ||
| 1085 | my ($self, $start, $end) = @_; | ||
| 1086 | return unless defined $start && defined $end; | ||
| 1087 | |||
| 1088 | my $pairkey1 = $start . $end; | ||
| 1089 | my $pairkey2 = $end . $start; | ||
| 1090 | return | ||
| 1091 | unless (exists $self->{_INTERNAL}->{edge_attrs}->{$pairkey1} | ||
| 1092 | && exists $self->{_INTERNAL}->{edge_attrs}->{$pairkey2}); | ||
| 1093 | delete $self->{_INTERNAL}->{edge_attrs}->{$pairkey1}; | ||
| 1094 | delete $self->{_INTERNAL}->{edge_attrs}->{$pairkey2}; | ||
| 1095 | } | ||
| 1096 | |||
| 1097 | =item add_edge | ||
| 1098 | |||
| 1099 | Given two vertices A and B, add an edge between them, as well as a | ||
| 1100 | hash reference containing any attributes that should be associated | ||
| 1101 | with that edge. Note that if either of the vertices do not yet exist, | ||
| 1102 | they will be created. | ||
| 1103 | |||
| 1104 | $g->add_edge('s', 'a', { name => 'my great edge'}); | ||
| 1105 | |||
| 1106 | =cut | ||
| 1107 | |||
| 1108 | sub add_edge { | ||
| 1109 | ## String String -> State! | ||
| 1110 | my ($self, $v1, $v2, $attrs) = @_; | ||
| 1111 | $self->_add_neighbor($v1, [$v2], $attrs); | ||
| 1112 | $self->_add_neighbor($v2, [$v1], $attrs) unless $self->is_directed; | ||
| 1113 | } | ||
| 1114 | |||
| 1115 | =item add_edges | ||
| 1116 | |||
| 1117 | Given a list of array references that describe vertices in the format | ||
| 1118 | |||
| 1119 | [['a', 'b', { weight => 123 }], ... ] | ||
| 1120 | |||
| 1121 | add all of the edges listed, as well as the attributes that should be | ||
| 1122 | associated with each edge. Note that if either of the vertices do not | ||
| 1123 | yet exist, they will be created. | ||
| 1124 | |||
| 1125 | $g->add_edge('s', 'a', { name => 'my great edge'}); | ||
| 1126 | |||
| 1127 | =cut | ||
| 1128 | |||
| 1129 | sub add_edges { | ||
| 1130 | my ( $self, @edges ) = @_; | ||
| 1131 | for my $elem (@edges) { | ||
| 1132 | my ( $a, $b, $attrs ) = @$elem; | ||
| 1133 | $self->add_edge( $a, $b, $attrs ); | ||
| 1134 | } | ||
| 1135 | } | ||
| 1136 | |||
| 1137 | =item remove_edge | ||
| 1138 | |||
| 1139 | Given two vertices A and B, remove the edge (if any) between them, as | ||
| 1140 | well as any associated attributes. | ||
| 1141 | |||
| 1142 | $g->remove_edge('s', 'a'); | ||
| 1143 | |||
| 1144 | =back | ||
| 1145 | |||
| 1146 | =cut | ||
| 1147 | |||
| 1148 | sub remove_edge { | ||
| 1149 | ## String String -> Boolean State! OR Undef | ||
| 1150 | my ($self, $a, $b) = @_; | ||
| 1151 | |||
| 1152 | return unless $self->edge_between($a, $b); | ||
| 1153 | |||
| 1154 | # We delete A from B's list of neighbors, and delete B from A's | ||
| 1155 | # list of neighbors. Then, we delete any edge attributes, since | ||
| 1156 | # said edge no longer exists. | ||
| 1157 | |||
| 1158 | $self->_remove_neighbor($a, $b); | ||
| 1159 | $self->_remove_neighbor($b, $a); | ||
| 1160 | $self->delete_edge_attributes($a, $b); | ||
| 1161 | |||
| 1162 | return 1; | ||
| 1163 | } | ||
| 1164 | |||
| 1165 | =head2 SEARCH | ||
| 1166 | |||
| 1167 | =over | ||
| 1168 | |||
| 1169 | =item dijkstra | ||
| 1170 | |||
| 1171 | Given two vertices START and END on a graph with weighted edges, find | ||
| 1172 | the shortest path between them using Dijkstra's algorithm. | ||
| 1173 | |||
| 1174 | $g->dijkstra($a, $b); | ||
| 1175 | |||
| 1176 | =cut | ||
| 1177 | |||
| 1178 | sub dijkstra { | ||
| 1179 | ## String String -> Array | ||
| 1180 | my ($self, $start, $end) = @_; | ||
| 1181 | |||
| 1182 | return () unless defined $start && defined $end; | ||
| 1183 | |||
| 1184 | my @path; | ||
| 1185 | my @queue; | ||
| 1186 | my %seen; | ||
| 1187 | my $heap = Hash::PriorityQueue->new; | ||
| 1188 | my $st = {}; | ||
| 1189 | |||
| 1190 | $st->{$start}->{distance} = 0; | ||
| 1191 | $st->{$start}->{prev} = undef; | ||
| 1192 | |||
| 1193 | for my $vertex ($self->get_vertices) { | ||
| 1194 | next if $vertex eq $start; | ||
| 1195 | $st->{$vertex}->{distance} = 1_000_000; | ||
| 1196 | $st->{$vertex}->{prev} = undef; | ||
| 1197 | } | ||
| 1198 | |||
| 1199 | $heap->insert($start, $st->{$start}->{distance}); | ||
| 1200 | |||
| 1201 | while (my $v = $heap->pop()) { | ||
| 1202 | my $neighbors = $self->get_neighbors($v); | ||
| 1203 | |||
| 1204 | for my $neighbor (@$neighbors) { | ||
| 1205 | next if $seen{$neighbor}; | ||
| 1206 | $seen{$neighbor}++; | ||
| 1207 | |||
| 1208 | # In this block, we are setting up the information we will | ||
| 1209 | # need to answer the question "Have we found a new | ||
| 1210 | # shortest path (by distance)?" | ||
| 1211 | my $distance_to_self = $st->{$v}->{distance}; | ||
| 1212 | my $old_distance_to_neighbor = $st->{$neighbor}->{distance}; | ||
| 1213 | my $neighbor_edge_weight | ||
| 1214 | = $self->get_edge_attribute($v, $neighbor, 'weight'); | ||
| 1215 | my $new_distance_to_neighbor | ||
| 1216 | = $distance_to_self + $neighbor_edge_weight; | ||
| 1217 | |||
| 1218 | # This is the core of Dijkstra's algorithm: Have we | ||
| 1219 | # discovered a path whose distance to the neighbor is | ||
| 1220 | # shorter than the previously discovered path's distance? | ||
| 1221 | # If yes, we update the spanning tree with this new path | ||
| 1222 | # information. | ||
| 1223 | if ($new_distance_to_neighbor < $old_distance_to_neighbor) { | ||
| 1224 | $st->{$neighbor}->{distance} = $new_distance_to_neighbor; | ||
| 1225 | $st->{$neighbor}->{prev} = $v; | ||
| 1226 | } | ||
| 1227 | |||
| 1228 | if ($neighbor eq $end) { | ||
| 1229 | @path = $self->_st_walk($st, $start, $end); | ||
| 1230 | return @path; | ||
| 1231 | } | ||
| 1232 | else { | ||
| 1233 | $heap->insert($neighbor, $st->{$neighbor}->{distance}); | ||
| 1234 | } | ||
| 1235 | } | ||
| 1236 | |||
| 1237 | $seen{$v}++; | ||
| 1238 | } | ||
| 1239 | return (); | ||
| 1240 | } | ||
| 1241 | |||
| 1242 | =item has_walk | ||
| 1243 | |||
| 1244 | Given a list of vertices, determine whether they constitute a walk. | ||
| 1245 | Given an optional argument, will determine if it is a closed walk. | ||
| 1246 | |||
| 1247 | $walk = qw/a f d b c e l m j k i h g/; | ||
| 1248 | $g->has_walk($walk, {closed => 1}); | ||
| 1249 | |||
| 1250 | =cut | ||
| 1251 | |||
| 1252 | sub has_walk { | ||
| 1253 | ## ArrayRef HashRef -> Boolean | ||
| 1254 | my ($self, $walk, $args) = @_; | ||
| 1255 | |||
| 1256 | my $len = @$walk - 1; | ||
| 1257 | |||
| 1258 | my $closed; | ||
| 1259 | $closed = $args->{closed} if $args; | ||
| 1260 | |||
| 1261 | # Short-circuit on whether it's a closed walk. | ||
| 1262 | if ($closed) { | ||
| 1263 | return unless $self->edge_between($walk->[0], $walk->[$len]); | ||
| 1264 | } | ||
| 1265 | |||
| 1266 | for (my $i = 0; $i <= $len; $i++) { | ||
| 1267 | my $j = $i + 1; | ||
| 1268 | last if $j > $len; | ||
| 1269 | return unless $self->edge_between($walk->[$i], $walk->[$i + 1]); | ||
| 1270 | } | ||
| 1271 | |||
| 1272 | return 1; | ||
| 1273 | } | ||
| 1274 | |||
| 1275 | =item paths_between | ||
| 1276 | |||
| 1277 | Given two vertices I<START> and I<END>, return a list of all the paths | ||
| 1278 | between them. | ||
| 1279 | |||
| 1280 | Note that this method is implemented using exhaustive search, so it | ||
| 1281 | will grind to a halt for larger graphs. | ||
| 1282 | |||
| 1283 | =cut | ||
| 1284 | |||
| 1285 | sub paths_between { | ||
| 1286 | my ($self, $start, $end) = @_; | ||
| 1287 | |||
| 1288 | return () unless defined $start && defined $end; | ||
| 1289 | |||
| 1290 | # We will get this done with exhaustive search. We will return true | ||
| 1291 | # when the last element in the path is equal to the current element | ||
| 1292 | # being inspected; this means that the path ends at the current | ||
| 1293 | # element. | ||
| 1294 | |||
| 1295 | my @paths; | ||
| 1296 | |||
| 1297 | my $lambda = sub { | ||
| 1298 | my ($current, $path) = @_; | ||
| 1299 | if ($current eq $end) { | ||
| 1300 | push @paths, [@$path]; | ||
| 1301 | return; | ||
| 1302 | } | ||
| 1303 | }; | ||
| 1304 | |||
| 1305 | $self->exhaustive_search($start, $lambda); | ||
| 1306 | @paths = sort { @$a <=> @$b } @paths; | ||
| 1307 | return @paths; | ||
| 1308 | } | ||
| 1309 | |||
| 1310 | =item find_path_between | ||
| 1311 | |||
| 1312 | Given two vertices START and END in an unweighted graph, find the | ||
| 1313 | shortest path between them using breadth-first search. | ||
| 1314 | |||
| 1315 | =cut | ||
| 1316 | |||
| 1317 | sub find_path_between { | ||
| 1318 | ## String String -> Array | ||
| 1319 | my ($self, $start, $end) = @_; | ||
| 1320 | |||
| 1321 | return () unless defined $start && defined $end; | ||
| 1322 | |||
| 1323 | my @path; # Path so far | ||
| 1324 | my @queue; # Vertices still to visit. | ||
| 1325 | my %seen; # Vertices already seen. | ||
| 1326 | my $found; # Whether we have found the wanted vertex. | ||
| 1327 | my $st = {}; # Spanning tree, used to find paths. | ||
| 1328 | |||
| 1329 | if ($start eq $end) { | ||
| 1330 | push @path, $start; | ||
| 1331 | return @path; | ||
| 1332 | } | ||
| 1333 | |||
| 1334 | push @queue, $start; | ||
| 1335 | $seen{$start}++; | ||
| 1336 | |||
| 1337 | while (@queue) { | ||
| 1338 | |||
| 1339 | my $v = shift @queue; | ||
| 1340 | |||
| 1341 | my $neighbors = $self->get_neighbors($v); | ||
| 1342 | |||
| 1343 | for my $neighbor (@$neighbors) { | ||
| 1344 | next unless defined $neighbor; | ||
| 1345 | next if $seen{$neighbor}; | ||
| 1346 | $st->{$neighbor}->{prev} = $v; | ||
| 1347 | if ($neighbor eq $end) { | ||
| 1348 | $found++; | ||
| 1349 | @path = $self->_st_walk($st, $start, $end); | ||
| 1350 | return @path; | ||
| 1351 | } | ||
| 1352 | else { | ||
| 1353 | push @queue, $neighbor; | ||
| 1354 | } | ||
| 1355 | $seen{$neighbor}++; | ||
| 1356 | } | ||
| 1357 | } | ||
| 1358 | return $found ? @path : (); | ||
| 1359 | } | ||
| 1360 | |||
| 1361 | =item mst | ||
| 1362 | |||
| 1363 | The F<mst> method finds the minimum spanning tree of the current graph | ||
| 1364 | object. As such, it takes no arguments; instead, it searches for the | ||
| 1365 | lowest-weight edge in the graph, chooses a vertex from one end of that | ||
| 1366 | edge as the starting vertex, and builds the spanning tree from there. | ||
| 1367 | |||
| 1368 | =cut | ||
| 1369 | |||
| 1370 | sub mst { | ||
| 1371 | ## -> YAGL OR Undef | ||
| 1372 | my ($self) = @_; | ||
| 1373 | |||
| 1374 | return unless $self->is_connected; | ||
| 1375 | |||
| 1376 | my @queue; | ||
| 1377 | my %seen; | ||
| 1378 | my $heap = Hash::PriorityQueue->new; | ||
| 1379 | |||
| 1380 | my @vertices = $self->get_vertices; | ||
| 1381 | my @edges = $self->get_edges; | ||
| 1382 | |||
| 1383 | # TODO(rml): This method should throw an error if the edge does | ||
| 1384 | # not have a weight attribute. Or perhaps it should assume a | ||
| 1385 | # weight of 0 if none is found? Since that's what our CSV format | ||
| 1386 | # does. | ||
| 1387 | |||
| 1388 | @edges = sort { $a->[2]->{weight} <=> $b->[2]->{weight} } @edges; | ||
| 1389 | my $start = $edges[0]->[1]; | ||
| 1390 | |||
| 1391 | my $mst = YAGL->new; | ||
| 1392 | |||
| 1393 | $mst->add_vertex($start); | ||
| 1394 | $mst->set_vertex_attribute($start, {distance => 0}); | ||
| 1395 | |||
| 1396 | for my $vertex (@vertices) { | ||
| 1397 | next if $vertex eq $start; | ||
| 1398 | $mst->add_vertex($vertex); | ||
| 1399 | $mst->set_vertex_attribute($vertex, {distance => 1_000_000}); | ||
| 1400 | } | ||
| 1401 | |||
| 1402 | $heap->insert($start, $mst->get_vertex_attribute($start, 'distance')); | ||
| 1403 | |||
| 1404 | while (my $v = $heap->pop()) { | ||
| 1405 | my $neighbors = $self->get_neighbors($v); | ||
| 1406 | |||
| 1407 | for my $neighbor (@$neighbors) { | ||
| 1408 | next if $seen{$neighbor}; | ||
| 1409 | $seen{$neighbor}++; | ||
| 1410 | |||
| 1411 | # In this block, we are setting up the information we will | ||
| 1412 | # need to answer the question "Have we found a new | ||
| 1413 | # shortest path (by distance)?" | ||
| 1414 | my $distance_to_self = $mst->get_vertex_attribute($v, 'distance'); | ||
| 1415 | my $old_distance_to_neighbor | ||
| 1416 | = $mst->get_vertex_attribute($neighbor, 'distance'); | ||
| 1417 | my $neighbor_edge_weight | ||
| 1418 | = $self->get_edge_attribute($v, $neighbor, 'weight'); | ||
| 1419 | my $new_distance_to_neighbor | ||
| 1420 | = $distance_to_self + $neighbor_edge_weight; | ||
| 1421 | |||
| 1422 | # This is the core of Jarnik-Prim (as well as Dijkstra's) | ||
| 1423 | # algorithm: Have we discovered a path whose distance to | ||
| 1424 | # the neighbor is shorter than the previously discovered | ||
| 1425 | # path's distance? If yes, we update the spanning tree | ||
| 1426 | # with this new path information. | ||
| 1427 | if ($new_distance_to_neighbor < $old_distance_to_neighbor) { | ||
| 1428 | $mst->set_vertex_attribute($neighbor, | ||
| 1429 | {distance => $new_distance_to_neighbor}); | ||
| 1430 | $mst->add_edge($v, $neighbor, | ||
| 1431 | {weight => $neighbor_edge_weight}); | ||
| 1432 | } | ||
| 1433 | |||
| 1434 | if ( $mst->is_connected | ||
| 1435 | && scalar $mst->get_vertices == scalar @vertices | ||
| 1436 | && $mst->is_tree) | ||
| 1437 | { | ||
| 1438 | return $mst; | ||
| 1439 | } | ||
| 1440 | else { | ||
| 1441 | $heap->insert($neighbor, | ||
| 1442 | $mst->get_vertex_attribute($neighbor, 'distance')); | ||
| 1443 | } | ||
| 1444 | } | ||
| 1445 | $seen{$v}++; | ||
| 1446 | } | ||
| 1447 | return; | ||
| 1448 | } | ||
| 1449 | |||
| 1450 | =item dfs | ||
| 1451 | |||
| 1452 | The F<dfs> method performs depth-first-search on the graph beginning | ||
| 1453 | at the vertex START; for each vertex visited by the search, invoke | ||
| 1454 | C<$sub>. | ||
| 1455 | |||
| 1456 | =cut | ||
| 1457 | |||
| 1458 | sub dfs { | ||
| 1459 | ## String Function -> Array State! | ||
| 1460 | my ($self, $start, $sub) = @_; | ||
| 1461 | return () unless defined $start; | ||
| 1462 | |||
| 1463 | my $dfs = sub { | ||
| 1464 | my ($self, $current, $sub, $seen) = @_; | ||
| 1465 | |||
| 1466 | $seen->{$current}++; | ||
| 1467 | $sub->($current); | ||
| 1468 | my $neighbors = $self->get_neighbors($current); | ||
| 1469 | for my $neighbor (@$neighbors) { | ||
| 1470 | next unless defined $neighbor; | ||
| 1471 | unless ($seen->{$neighbor}) { | ||
| 1472 | $self->set_edge_attribute($current, $neighbor, | ||
| 1473 | {color => 'red'}); | ||
| 1474 | __SUB__->($self, $neighbor, $sub, $seen); | ||
| 1475 | } | ||
| 1476 | } | ||
| 1477 | }; | ||
| 1478 | my $seen = {}; | ||
| 1479 | $dfs->($self, $start, $sub, $seen); | ||
| 1480 | |||
| 1481 | # Deal with any unconnected vertices. | ||
| 1482 | my @unseen = grep { !exists $seen->{$_} } $self->get_vertices; | ||
| 1483 | |||
| 1484 | for my $u (@unseen) { | ||
| 1485 | next if $seen->{$u}; | ||
| 1486 | $dfs->($self, $u, $sub, $seen); | ||
| 1487 | } | ||
| 1488 | } | ||
| 1489 | |||
| 1490 | =item connected_components | ||
| 1491 | |||
| 1492 | The F<connected_components> method returns the connected components of | ||
| 1493 | the graph, as a list of lists. | ||
| 1494 | |||
| 1495 | If there are no connected components, it will return an empty list: | ||
| 1496 | |||
| 1497 | [] | ||
| 1498 | |||
| 1499 | If there is only one connected component, it will return a list with | ||
| 1500 | one element: a list of the vertices of the connected component: | ||
| 1501 | |||
| 1502 | [['a', 'b', 'c', 'd']] | ||
| 1503 | |||
| 1504 | If there are I<n> connected components, it will return a list with | ||
| 1505 | I<n> elements: | ||
| 1506 | |||
| 1507 | [['a', 'b'], ['c', 'd'], ['e', 'f', 'g']] | ||
| 1508 | |||
| 1509 | =cut | ||
| 1510 | |||
| 1511 | # TODO(rml): Design a better output format. This should probably be | ||
| 1512 | # returning YAGL objects so the caller can do graph operations on them | ||
| 1513 | # if they want to. | ||
| 1514 | |||
| 1515 | sub connected_components { | ||
| 1516 | my ($self) = @_; | ||
| 1517 | |||
| 1518 | my @components; | ||
| 1519 | |||
| 1520 | my $lambda = sub { | ||
| 1521 | my ($current) = @_; | ||
| 1522 | |||
| 1523 | my $delim = 'XXX'; | ||
| 1524 | push @components, $delim unless @components; | ||
| 1525 | if ($components[$#components] eq $delim) { | ||
| 1526 | push @components, $current; | ||
| 1527 | } | ||
| 1528 | elsif ($self->find_path_between($current, $components[$#components])) | ||
| 1529 | { | ||
| 1530 | push @components, $current; | ||
| 1531 | } | ||
| 1532 | else { | ||
| 1533 | push @components, $delim; | ||
| 1534 | push @components, $current; | ||
| 1535 | } | ||
| 1536 | }; | ||
| 1537 | |||
| 1538 | my @vertices = sort { $self->get_degree($a) <=> $self->get_degree($b) } | ||
| 1539 | $self->get_vertices; | ||
| 1540 | my $start = $vertices[0]; | ||
| 1541 | $self->dfs($start, $lambda); | ||
| 1542 | |||
| 1543 | my @p1 = grep { $_ ne '' } split /XXX/, join ' ', @components; | ||
| 1544 | my @answer; | ||
| 1545 | for my $piece (@p1) { | ||
| 1546 | my @parts = grep { $_ ne '' } split / +/, $piece; | ||
| 1547 | push @answer, \@parts; | ||
| 1548 | } | ||
| 1549 | |||
| 1550 | return @answer; | ||
| 1551 | } | ||
| 1552 | |||
| 1553 | =item exhaustive_search | ||
| 1554 | |||
| 1555 | The F<exhaustive_search> method performs an exhaustive search of all | ||
| 1556 | trees in the graph. The way this works is very close to the algorithm | ||
| 1557 | for depth-first-search, except that F<exhaustive_search> unmarks the | ||
| 1558 | vertices it has visited after the recursive self-call; this is | ||
| 1559 | described in more detail on p.623 of Sedgewick's I<Algorithms>, 2nd | ||
| 1560 | ed. | ||
| 1561 | |||
| 1562 | It takes two arguments: the name of the starting vertex, and an | ||
| 1563 | optional subroutine argument. | ||
| 1564 | |||
| 1565 | $g->exhaustive_search('a', sub { say $_[0] }); | ||
| 1566 | |||
| 1567 | =cut | ||
| 1568 | |||
| 1569 | sub exhaustive_search { | ||
| 1570 | my ($self, $start, $sub) = @_; | ||
| 1571 | |||
| 1572 | return () unless defined $start; | ||
| 1573 | |||
| 1574 | my $search = sub { | ||
| 1575 | my ($self, $current, $sub, $seen, $path) = @_; | ||
| 1576 | $seen->{$current}++; | ||
| 1577 | state $backtracked; | ||
| 1578 | |||
| 1579 | my $len = @$path - 1; | ||
| 1580 | my $last; | ||
| 1581 | $last = $path->[$len] if $path->[$len]; | ||
| 1582 | |||
| 1583 | if (DEBUG) { | ||
| 1584 | say | ||
| 1585 | qq[exhaustive_search(): choice point is '$last', adding '$current'] | ||
| 1586 | if $last && $backtracked; | ||
| 1587 | say qq[exhaustive_search(): adding '$current'] | ||
| 1588 | unless $backtracked; | ||
| 1589 | } | ||
| 1590 | push @$path, $current; | ||
| 1591 | |||
| 1592 | say qq[exhaustive_search(): PATH -> @$path] if DEBUG; | ||
| 1593 | |||
| 1594 | # The subroutine operates on the current vertex $current as | ||
| 1595 | # well as looking at the "path so far". That way, the | ||
| 1596 | # subroutine can be used as a predicate to determine a search | ||
| 1597 | # cutoff property as described on p.28 of Knuth's v04f05. | ||
| 1598 | |||
| 1599 | # TODO(rml): The behavior described above still doesn't quite | ||
| 1600 | # work as expected yet. The branch below shows how the | ||
| 1601 | # subroutine can "signal into" this method that it wants to | ||
| 1602 | # cutoff/prune the current branch of the search tree and try | ||
| 1603 | # something else. However, the subroutine is still getting | ||
| 1604 | # called more than once (e.g. 15 times out of 8000), for | ||
| 1605 | # reasons I don't understand. Why 15 and not just 1? | ||
| 1606 | |||
| 1607 | if ($sub) { | ||
| 1608 | my $rv = $sub->($current, $path); | ||
| 1609 | unless (defined $rv) { | ||
| 1610 | |||
| 1611 | # This cutoff optimization brings the number of subroutine | ||
| 1612 | # calls from ~8000 to ~16 in Test 5 of | ||
| 1613 | # 28-house-of-graphs-lst-file-format.t, a savings of about | ||
| 1614 | # 99.8 percent! | ||
| 1615 | say | ||
| 1616 | qq[exhaustive_search(): cutoff(@$path) -> FAIL, bailing...] | ||
| 1617 | if DEBUG; | ||
| 1618 | return; | ||
| 1619 | } | ||
| 1620 | } | ||
| 1621 | |||
| 1622 | my $neighbors = $self->get_neighbors($current); | ||
| 1623 | for my $neighbor (@$neighbors) { | ||
| 1624 | next unless defined $neighbor; | ||
| 1625 | unless ($seen->{$neighbor}) { | ||
| 1626 | __SUB__->($self, $neighbor, $sub, $seen, $path); | ||
| 1627 | if (DEBUG) { | ||
| 1628 | say | ||
| 1629 | qq[exhaustive_search(): backtracking from '$neighbor']; | ||
| 1630 | } | ||
| 1631 | delete $seen->{$neighbor}; | ||
| 1632 | pop @$path; | ||
| 1633 | $backtracked = 1 if DEBUG; | ||
| 1634 | } | ||
| 1635 | } | ||
| 1636 | }; | ||
| 1637 | my $seen = {}; | ||
| 1638 | my $path = []; | ||
| 1639 | $search->($self, $start, $sub, $seen, $path); | ||
| 1640 | } | ||
| 1641 | |||
| 1642 | =item hamiltonian_walks | ||
| 1643 | |||
| 1644 | The C<hamiltonian_walks> method does an exhaustive search to find all | ||
| 1645 | of the open or closed Hamiltonian walks on the graph, if they exist. | ||
| 1646 | It takes an optional C<closed> argument to determine which type to | ||
| 1647 | look for. | ||
| 1648 | |||
| 1649 | $g->hamiltonian_walks(closed => 1); | ||
| 1650 | $g->hamiltonian_walks; # Finds open walks by default. | ||
| 1651 | |||
| 1652 | =cut | ||
| 1653 | |||
| 1654 | sub hamiltonian_walks { | ||
| 1655 | ## Array -> Array State! | ||
| 1656 | my ($self, @args) = @_; | ||
| 1657 | |||
| 1658 | my %args = @args; | ||
| 1659 | my $closed = $args{closed}; | ||
| 1660 | |||
| 1661 | my $allow_reversals = $args{allow_reversals}; | ||
| 1662 | |||
| 1663 | my $n_solutions; | ||
| 1664 | if (exists $args{n_solutions}) { | ||
| 1665 | $n_solutions = $args{n_solutions}; | ||
| 1666 | } # 1,..,_n_ OR undef | ||
| 1667 | $n_solutions = 1_000_000 | ||
| 1668 | unless defined $n_solutions; # undef = all solutions | ||
| 1669 | |||
| 1670 | my @vertices = $self->get_vertices; | ||
| 1671 | my $n_vertices = @vertices; | ||
| 1672 | my $start; | ||
| 1673 | |||
| 1674 | # We can easily disqualify a graph as not having a closed Hamiltonian | ||
| 1675 | # walk if it has any vertex with a degree of less than two (that | ||
| 1676 | # is, if it has any leaves or entirely disconnected vertices). | ||
| 1677 | if ($closed) { | ||
| 1678 | for my $v (@vertices) { | ||
| 1679 | return if $self->get_degree($v) < 2; | ||
| 1680 | } | ||
| 1681 | } | ||
| 1682 | |||
| 1683 | # If the graph is a tree, we need to select a leaf node. | ||
| 1684 | my $is_tree = $self->is_tree; | ||
| 1685 | |||
| 1686 | # However, if we're looking for a closed walk in a tree, none | ||
| 1687 | # exists. | ||
| 1688 | return if $is_tree && $closed; | ||
| 1689 | |||
| 1690 | if ($is_tree) { | ||
| 1691 | LOOP: for my $v (@vertices) { | ||
| 1692 | if ($self->get_degree($v) == 1) { | ||
| 1693 | $start = $v; | ||
| 1694 | last LOOP; | ||
| 1695 | } | ||
| 1696 | } | ||
| 1697 | } | ||
| 1698 | else { | ||
| 1699 | $start = $vertices[0]; | ||
| 1700 | } | ||
| 1701 | |||
| 1702 | my @hams; | ||
| 1703 | |||
| 1704 | my $lambda = sub { | ||
| 1705 | ## String ArrayRef -> State! | ||
| 1706 | my ($current, $path) = @_; | ||
| 1707 | |||
| 1708 | state $calls = 0; | ||
| 1709 | state %seen; | ||
| 1710 | $calls++; | ||
| 1711 | say qq[hamiltonian_walks(): calls -> $calls] if DEBUG; | ||
| 1712 | |||
| 1713 | # Bail out early if we've already found the desired number of | ||
| 1714 | # solutions. | ||
| 1715 | |||
| 1716 | if (@hams == $n_solutions) { | ||
| 1717 | if (DEBUG) { | ||
| 1718 | say | ||
| 1719 | qq[hamiltonian_walks(): found $n_solutions solutions after $calls calls]; | ||
| 1720 | } | ||
| 1721 | return; | ||
| 1722 | } | ||
| 1723 | |||
| 1724 | if (@$path == $n_vertices) { | ||
| 1725 | if ($self->has_walk($path, {closed => $closed})) { | ||
| 1726 | say qq[hamiltonian_paths(): found a path -> @$path] if DEBUG; | ||
| 1727 | if ($allow_reversals) { | ||
| 1728 | push @hams, [@$path]; | ||
| 1729 | } | ||
| 1730 | else { | ||
| 1731 | my @p = @$path; | ||
| 1732 | my $p1 = join '-', @p[1 .. $#p]; | ||
| 1733 | my $p2 = join '-', reverse @p[1 .. $#p]; | ||
| 1734 | unless (exists $seen{$p1} || exists $seen{$p2}) { | ||
| 1735 | push @hams, [@$path]; | ||
| 1736 | } | ||
| 1737 | $seen{$p1}++; | ||
| 1738 | $seen{$p2}++; | ||
| 1739 | } | ||
| 1740 | } | ||
| 1741 | } | ||
| 1742 | }; | ||
| 1743 | |||
| 1744 | $self->exhaustive_search($start, $lambda); | ||
| 1745 | return @hams; | ||
| 1746 | } | ||
| 1747 | |||
| 1748 | =item is_planar | ||
| 1749 | |||
| 1750 | The C<is_planar> method tests whether a graph is planar. | ||
| 1751 | |||
| 1752 | =back | ||
| 1753 | |||
| 1754 | =cut | ||
| 1755 | |||
| 1756 | # TODO(rml): Add a citation for this algorithm, I think it might be | ||
| 1757 | # from I<Graph Algorithms> by S. Even. | ||
| 1758 | |||
| 1759 | sub is_planar { | ||
| 1760 | my ($self) = @_; | ||
| 1761 | |||
| 1762 | my $edge_count = $self->get_edges; | ||
| 1763 | my $vertex_count = $self->get_vertices; | ||
| 1764 | |||
| 1765 | if ($edge_count > (3 * $vertex_count)) { | ||
| 1766 | return; | ||
| 1767 | } | ||
| 1768 | } | ||
| 1769 | |||
| 1770 | =head2 CLONING (OBJECT COPYING) AND EQUALITY CHECKS | ||
| 1771 | |||
| 1772 | =over | ||
| 1773 | |||
| 1774 | =cut | ||
| 1775 | |||
| 1776 | =item clone | ||
| 1777 | |||
| 1778 | Given a graph object, the C<clone> method makes a fresh copy of that object. | ||
| 1779 | |||
| 1780 | =cut | ||
| 1781 | |||
| 1782 | sub clone { | ||
| 1783 | my ($self) = @_; | ||
| 1784 | my $copy = Storable::dclone($self); | ||
| 1785 | return $copy; | ||
| 1786 | } | ||
| 1787 | |||
| 1788 | =back | ||
| 1789 | |||
| 1790 | =head2 INTERNAL HELPER METHODS | ||
| 1791 | |||
| 1792 | =over | ||
| 1793 | |||
| 1794 | =item _array_eq | ||
| 1795 | |||
| 1796 | Given two array references, are their contents equal? NB. Only works on flat, non-nested arrays. | ||
| 1797 | |||
| 1798 | =cut | ||
| 1799 | |||
| 1800 | sub _array_eq { | ||
| 1801 | my ( $xs, $ys ) = @_; | ||
| 1802 | my $x = scalar @$xs; | ||
| 1803 | my $y = scalar @$ys; | ||
| 1804 | return unless $x == $y; | ||
| 1805 | for ( my $i = 0 ; $i < @$xs ; $i++ ) { | ||
| 1806 | my ( $this, $that ) = ( $xs->[$i], $ys->[$i] ); | ||
| 1807 | return unless $this eq $that; | ||
| 1808 | } | ||
| 1809 | return 1; | ||
| 1810 | } | ||
| 1811 | |||
| 1812 | =item _memberp | ||
| 1813 | |||
| 1814 | Given a string element and an array, return true if the element is in the array. | ||
| 1815 | |||
| 1816 | =cut | ||
| 1817 | |||
| 1818 | sub _memberp { | ||
| 1819 | my ( $item, $array_ref ) = @_; | ||
| 1820 | for my $element (@$array_ref) { | ||
| 1821 | if ($element eq $item) { | ||
| 1822 | return 1; | ||
| 1823 | } | ||
| 1824 | } | ||
| 1825 | return; | ||
| 1826 | } | ||
| 1827 | |||
| 1828 | =item _add_neighbor | ||
| 1829 | |||
| 1830 | The C<_add_neighbor> method is the internal helper used to add an edge | ||
| 1831 | (and any edge attributes) between two vertices. | ||
| 1832 | |||
| 1833 | =cut | ||
| 1834 | |||
| 1835 | sub _add_neighbor { | ||
| 1836 | ## String ArrayRef HashRef -> State! | ||
| 1837 | my ($self, $vertex, $new_neighbor, $edge_attrs) = @_; | ||
| 1838 | |||
| 1839 | unless (ref($new_neighbor) eq 'ARRAY') { | ||
| 1840 | my ($package, $filename, $line) = caller(); | ||
| 1841 | die <<"EOF"; | ||
| 1842 | on line $line of file $filename: | ||
| 1843 | $package\:\:_add_neighbor('$vertex', '$new_neighbor', '$edge_attrs'): | ||
| 1844 | expected arrayref, got '$new_neighbor' | ||
| 1845 | EOF | ||
| 1846 | } | ||
| 1847 | |||
| 1848 | if ($self->has_vertex($vertex)) { | ||
| 1849 | my $neighbors = $self->get_neighbors($vertex); | ||
| 1850 | for my $value (@$new_neighbor) { | ||
| 1851 | unless (_memberp($value, $neighbors)) { | ||
| 1852 | push @$neighbors, $value; | ||
| 1853 | } | ||
| 1854 | } | ||
| 1855 | $self->{$vertex} = $neighbors; | ||
| 1856 | } | ||
| 1857 | else { | ||
| 1858 | $self->{$vertex} = $new_neighbor; | ||
| 1859 | } | ||
| 1860 | $self->set_edge_attribute($vertex, $new_neighbor->[0], $edge_attrs); | ||
| 1861 | } | ||
| 1862 | |||
| 1863 | =item _remove_neighbor | ||
| 1864 | |||
| 1865 | The C<_remove_neighbor> method is an internal helper used for deleting | ||
| 1866 | an edge between two vertices. | ||
| 1867 | |||
| 1868 | =cut | ||
| 1869 | |||
| 1870 | sub _remove_neighbor { | ||
| 1871 | ## String String -> State! OR Undef | ||
| 1872 | my ($self, $vertex, $neighbor) = @_; | ||
| 1873 | |||
| 1874 | return unless $self->edge_between($vertex, $neighbor); | ||
| 1875 | |||
| 1876 | # Graphs are represented as a hash of arrays that look like the | ||
| 1877 | # following: | ||
| 1878 | # | ||
| 1879 | # my $example = { | ||
| 1880 | # 's' => [ 'a', 'd' ], | ||
| 1881 | # 'a' => [ 's', 'b', 'd' ], | ||
| 1882 | # 'b' => [ 'a', 'c', 'e' ], | ||
| 1883 | # 'c' => [ 'b' ], | ||
| 1884 | # 'd' => [ 's', 'a', 'e' ], | ||
| 1885 | # 'e' => [ 'b', 'd', 'f' ], | ||
| 1886 | # }; | ||
| 1887 | # | ||
| 1888 | # To delete a specific neighbor, we have to walk this vertex's | ||
| 1889 | # list of neighbors (skipping any already deleted neighbors) and | ||
| 1890 | # set the neighbor's value to undef. | ||
| 1891 | |||
| 1892 | return unless $self->has_vertex($vertex); | ||
| 1893 | my $neighbors = $self->get_neighbors($vertex); | ||
| 1894 | |||
| 1895 | for (my $i = 0; $i <= @$neighbors; $i++) { | ||
| 1896 | my $this = $self->{$vertex}->[$i]; | ||
| 1897 | next unless defined $this; | ||
| 1898 | if ($this eq $neighbor) { | ||
| 1899 | |||
| 1900 | # https://perlmaven.com/how-to-eliminate-a-value-in-the-middle-of-an-array-in-perl | ||
| 1901 | splice @{$self->{$vertex}}, $i, 1; | ||
| 1902 | } | ||
| 1903 | } | ||
| 1904 | } | ||
| 1905 | |||
| 1906 | =item _st_walk | ||
| 1907 | |||
| 1908 | The C<_st_walk> method is used internally for building walks (paths) | ||
| 1909 | along spanning trees, such as are built inside C<find_path_between> | ||
| 1910 | and C<dijkstra>. | ||
| 1911 | |||
| 1912 | =cut | ||
| 1913 | |||
| 1914 | sub _st_walk { | ||
| 1915 | ## String String HashRef -> Array | ||
| 1916 | my ($self, $st, $start, $end) = @_; | ||
| 1917 | |||
| 1918 | my @path; | ||
| 1919 | |||
| 1920 | if (exists $st->{$start}->{distance}) { | ||
| 1921 | push @path, {vertex => $end, distance => $st->{$end}->{distance}}; | ||
| 1922 | my $prev = $st->{$end}->{prev}; | ||
| 1923 | |||
| 1924 | while (1) { | ||
| 1925 | if ($prev eq $start) { | ||
| 1926 | |||
| 1927 | push @path, | ||
| 1928 | {vertex => $prev, distance => $st->{$prev}->{distance}}; | ||
| 1929 | last; | ||
| 1930 | } | ||
| 1931 | push @path, | ||
| 1932 | {vertex => $prev, distance => $st->{$prev}->{distance}}; | ||
| 1933 | $prev = $st->{$prev}->{prev}; | ||
| 1934 | next; | ||
| 1935 | } | ||
| 1936 | } | ||
| 1937 | else { | ||
| 1938 | push @path, $end; | ||
| 1939 | my $prev = $st->{$end}->{prev}; | ||
| 1940 | while (1) { | ||
| 1941 | if ($prev eq $start) { | ||
| 1942 | push @path, $start; | ||
| 1943 | last; | ||
| 1944 | } | ||
| 1945 | push @path, $prev; | ||
| 1946 | $prev = $st->{$prev}->{prev}; | ||
| 1947 | next; | ||
| 1948 | } | ||
| 1949 | } | ||
| 1950 | return reverse @path; | ||
| 1951 | } | ||
| 1952 | |||
| 1953 | =item _edge_attrs | ||
| 1954 | |||
| 1955 | The C<_edge_attrs> method is an internal helper that returns all of | ||
| 1956 | the graph's edge attributes. | ||
| 1957 | |||
| 1958 | =cut | ||
| 1959 | |||
| 1960 | sub _edge_attrs { | ||
| 1961 | my ($self) = @_; | ||
| 1962 | return $self->{_INTERNAL}->{edge_attrs}; | ||
| 1963 | } | ||
| 1964 | |||
| 1965 | =item _vertex_attrs | ||
| 1966 | |||
| 1967 | The C<_vertex_attrs> method is an internal helper that returns all of | ||
| 1968 | the graph's vertex attributes. | ||
| 1969 | |||
| 1970 | =cut | ||
| 1971 | |||
| 1972 | sub _vertex_attrs { | ||
| 1973 | my ($self) = @_; | ||
| 1974 | return $self->{_INTERNAL}->{vertex_attrs}; | ||
| 1975 | } | ||
| 1976 | |||
| 1977 | =item _make_vertex_name | ||
| 1978 | |||
| 1979 | The C<_make_vertex_name> method is used to generate random vertex | ||
| 1980 | names, such as when generating random graphs. | ||
| 1981 | |||
| 1982 | =back | ||
| 1983 | |||
| 1984 | =cut | ||
| 1985 | |||
| 1986 | sub _make_vertex_name { | ||
| 1987 | ## -> String | ||
| 1988 | my $n = int rand 10000; | ||
| 1989 | my $chars = qq[a b c d e f g h i j k l m n o p q r s t u v w x y z]; | ||
| 1990 | my @chars = split / /, $chars; | ||
| 1991 | |||
| 1992 | my $i = rand scalar @chars; | ||
| 1993 | my $c1 = $chars[$i]; | ||
| 1994 | my $c2 = $chars[rand scalar @chars]; | ||
| 1995 | |||
| 1996 | return qq[$c1$c2$n]; | ||
| 1997 | } | ||
| 1998 | |||
| 1999 | =head2 COLORING | ||
| 2000 | |||
| 2001 | =over | ||
| 2002 | |||
| 2003 | =item get_color_degree | ||
| 2004 | |||
| 2005 | The C<get_color_degree> method returns the "color degree" of a vertex: | ||
| 2006 | that is, how many colors its neighbors have. | ||
| 2007 | |||
| 2008 | =cut | ||
| 2009 | |||
| 2010 | sub get_color_degree { | ||
| 2011 | ## String -> Integer | ||
| 2012 | my ($self, $vertex) = @_; | ||
| 2013 | my $count = 0; | ||
| 2014 | my @colors; | ||
| 2015 | my $neighbors = $self->get_neighbors($vertex); | ||
| 2016 | for my $neighbor (@$neighbors) { | ||
| 2017 | my $color = $self->get_vertex_color($neighbor); | ||
| 2018 | if ($color) { | ||
| 2019 | $count++; | ||
| 2020 | push @colors, $color; | ||
| 2021 | } | ||
| 2022 | } | ||
| 2023 | return ($count, @colors); | ||
| 2024 | } | ||
| 2025 | |||
| 2026 | =item color_vertices | ||
| 2027 | |||
| 2028 | The C<color_vertices> method colors the vertices of the graph using | ||
| 2029 | the algorithm due to Brelaz, as described in Skiena, I<Implementing | ||
| 2030 | Discrete Mathematics>. Specifically: | ||
| 2031 | |||
| 2032 | =over | ||
| 2033 | |||
| 2034 | =item 1. Number the colors from 1 to k. | ||
| 2035 | |||
| 2036 | =item 2. Color the vertex of largest degree with color 1. | ||
| 2037 | |||
| 2038 | =item 3. Then repeatedly select the vertex with highest I<color | ||
| 2039 | degree>, where the color degree is the number of adjacent vertices | ||
| 2040 | which have already been colored, and color it with the smallest | ||
| 2041 | possible color. | ||
| 2042 | |||
| 2043 | =back | ||
| 2044 | |||
| 2045 | =cut | ||
| 2046 | |||
| 2047 | sub color_vertices { | ||
| 2048 | ## -> State! | ||
| 2049 | my ($self) = @_; | ||
| 2050 | |||
| 2051 | if ($self->is_directed) { | ||
| 2052 | my ($package, $filename, $line) = caller(); | ||
| 2053 | die <<"EOF"; | ||
| 2054 | on line $line of file $filename: | ||
| 2055 | $package\:\:_color_vertices(): | ||
| 2056 | is not implemented for directed graphs! | ||
| 2057 | EOF | ||
| 2058 | } | ||
| 2059 | |||
| 2060 | # Ordered by indices | ||
| 2061 | my @colors = qw/ white brown black indigo orange yellow blue green red/; | ||
| 2062 | my @vertices_by_degree | ||
| 2063 | = sort { $self->get_degree($a) > $self->get_degree($b) } | ||
| 2064 | $self->get_vertices; | ||
| 2065 | |||
| 2066 | my $v = pop @vertices_by_degree; | ||
| 2067 | $self->set_vertex_color($v, $colors[0]); | ||
| 2068 | |||
| 2069 | my @vertices_by_color_degree | ||
| 2070 | = sort { $self->get_color_degree($a) > $self->get_color_degree($b) } | ||
| 2071 | $self->get_vertices; | ||
| 2072 | |||
| 2073 | while (my $v = pop @vertices_by_color_degree) { | ||
| 2074 | my ($count, @adjacent_colors) = $self->get_color_degree($v); | ||
| 2075 | for my $color (@colors) { | ||
| 2076 | $self->set_vertex_color($v, $color) | ||
| 2077 | unless _memberp($color, \@adjacent_colors); | ||
| 2078 | } | ||
| 2079 | @vertices_by_color_degree | ||
| 2080 | = sort { $self->get_color_degree($a) > $self->get_color_degree($b) } | ||
| 2081 | @vertices_by_color_degree; | ||
| 2082 | } | ||
| 2083 | } | ||
| 2084 | |||
| 2085 | =item uncolor_vertices | ||
| 2086 | |||
| 2087 | The C<uncolor_vertices> method "uncolors" every vertex in the graph by | ||
| 2088 | setting its color attribute to C<undef>. | ||
| 2089 | |||
| 2090 | =cut | ||
| 2091 | |||
| 2092 | sub uncolor_vertices { | ||
| 2093 | my ($self) = @_; | ||
| 2094 | for my $vertex ($self->get_vertices) { | ||
| 2095 | $self->set_vertex_color($vertex, undef); | ||
| 2096 | } | ||
| 2097 | } | ||
| 2098 | |||
| 2099 | =item vertex_colors | ||
| 2100 | |||
| 2101 | The C<vertex_colors> method returns a list containing each vertex and its color. | ||
| 2102 | |||
| 2103 | =cut | ||
| 2104 | |||
| 2105 | sub vertex_colors { | ||
| 2106 | ## -> Array[Hashref] | ||
| 2107 | my ($self) = @_; | ||
| 2108 | my @colors; | ||
| 2109 | for my $vertex ($self->get_vertices) { | ||
| 2110 | push @colors, [$vertex, {color => $self->get_vertex_color($vertex)}]; | ||
| 2111 | } | ||
| 2112 | return @colors; | ||
| 2113 | } | ||
| 2114 | |||
| 2115 | =item chromatic_number | ||
| 2116 | |||
| 2117 | The C<chromatic_number> method does not actually return the chromatic | ||
| 2118 | number. It returns the number of colors that were used to color the | ||
| 2119 | vertices of the graph using the C<color_vertices> method. | ||
| 2120 | |||
| 2121 | =cut | ||
| 2122 | |||
| 2123 | sub chromatic_number { | ||
| 2124 | ## -> Integer OR Undef | ||
| 2125 | my ($self) = @_; | ||
| 2126 | my $n = 0; | ||
| 2127 | my @colors = $self->vertex_colors; | ||
| 2128 | return unless @colors; | ||
| 2129 | |||
| 2130 | my %colors; | ||
| 2131 | for my $elem (@colors) { | ||
| 2132 | my $color = $elem->[1]->{color}; | ||
| 2133 | $colors{$color}++; | ||
| 2134 | } | ||
| 2135 | my @keys = keys %colors; | ||
| 2136 | if (@keys) { | ||
| 2137 | $n = scalar @keys; | ||
| 2138 | } | ||
| 2139 | return $n; | ||
| 2140 | } | ||
| 2141 | |||
| 2142 | =item set_cover | ||
| 2143 | |||
| 2144 | =cut | ||
| 2145 | |||
| 2146 | sub set_cover { | ||
| 2147 | my ($self, @args) = @_; | ||
| 2148 | |||
| 2149 | my $is_bipartite = $self->is_bipartite; | ||
| 2150 | die qq[set_cover: Graph is not bipartite!] unless $is_bipartite; | ||
| 2151 | |||
| 2152 | my @vertices = $self->get_vertices; | ||
| 2153 | my @green = grep { $self->get_vertex_color($_) eq 'green'; } @vertices; | ||
| 2154 | my @red = grep { $self->get_vertex_color($_) eq 'red'; } @vertices; | ||
| 2155 | my @options; | ||
| 2156 | my @items; | ||
| 2157 | |||
| 2158 | for my $g (@green) { | ||
| 2159 | if (length($g) >= 2) { | ||
| 2160 | @options = @green; | ||
| 2161 | @items = @red; | ||
| 2162 | } | ||
| 2163 | } | ||
| 2164 | |||
| 2165 | for my $r (@red) { | ||
| 2166 | if (length($r) >= 2) { | ||
| 2167 | @options = @red; | ||
| 2168 | @items = @green; | ||
| 2169 | } | ||
| 2170 | } | ||
| 2171 | |||
| 2172 | my %args = @args; | ||
| 2173 | my $n_solutions; | ||
| 2174 | if (exists $args{n_solutions}) { | ||
| 2175 | $n_solutions = $args{n_solutions}; | ||
| 2176 | } | ||
| 2177 | $n_solutions = 1 unless defined $n_solutions; | ||
| 2178 | |||
| 2179 | my $is_exact; | ||
| 2180 | if (exists $args{is_exact}) { | ||
| 2181 | $is_exact = $args{is_exact}; | ||
| 2182 | } | ||
| 2183 | |||
| 2184 | my @covers; | ||
| 2185 | my $found; | ||
| 2186 | my %found; | ||
| 2187 | my %seen; | ||
| 2188 | |||
| 2189 | my $lambda = sub { | ||
| 2190 | my ($current, $path) = @_; | ||
| 2191 | |||
| 2192 | my @path_options = grep { _memberp($_, \@options) } @$path; | ||
| 2193 | my $path_options = join ';', sort @path_options; | ||
| 2194 | |||
| 2195 | if (_covers_all_items(\@path_options, \@items)) { | ||
| 2196 | if ($is_exact) { | ||
| 2197 | unless (_disjoint(@path_options)) { | ||
| 2198 | return; | ||
| 2199 | } | ||
| 2200 | } | ||
| 2201 | unless (exists $found{$path_options}) { | ||
| 2202 | push @covers, [@path_options]; | ||
| 2203 | $found++; | ||
| 2204 | $found{$path_options}++; | ||
| 2205 | say qq[set_cover: Found a cover -> @path_options] if DEBUG; | ||
| 2206 | return if @covers == $n_solutions; | ||
| 2207 | return 1; | ||
| 2208 | } | ||
| 2209 | } | ||
| 2210 | return 1; | ||
| 2211 | }; | ||
| 2212 | |||
| 2213 | # TODO(rml): Apply some of the problem reductions from [Syslo83] | ||
| 2214 | # here, so we can avoid doing so much work in the search. Note | ||
| 2215 | # that in what follows, the "rows" per Syslo et al are what | ||
| 2216 | # [Knuth2020] calls the columns, aka the "items" to be | ||
| 2217 | # covered. The reductions are: | ||
| 2218 | |||
| 2219 | # Rule 1R. Zero rows: If there is an item for which there is no | ||
| 2220 | # cover, then no solution exists. | ||
| 2221 | |||
| 2222 | # Rule 1C. Zero columns: If there is an option whose elements do | ||
| 2223 | # not cover any item, remove the option. | ||
| 2224 | |||
| 2225 | # Rule 2. Essential columns: If there is an option one of whose | ||
| 2226 | # elements is the *only* cover for one of the items, then push | ||
| 2227 | # this option onto the list of COVERS immediately. | ||
| 2228 | |||
| 2229 | # Now we will perform the reductions. | ||
| 2230 | |||
| 2231 | # Rule 1R. Zero rows: if there is an item for which there is no | ||
| 2232 | # option whose elements cover that item, then no solution exists. | ||
| 2233 | |||
| 2234 | my @option_elems = uniq sort { $a cmp $b } split //, join '', @options; | ||
| 2235 | @option_elems = sort { $a cmp $b } @option_elems; | ||
| 2236 | |||
| 2237 | my @wanted; | ||
| 2238 | |||
| 2239 | for my $item (@items) { | ||
| 2240 | unless (_memberp($item, \@option_elems)) { | ||
| 2241 | goto END; | ||
| 2242 | } | ||
| 2243 | } | ||
| 2244 | |||
| 2245 | # Rule 1C. Zero columns: If there is an option whose elements do | ||
| 2246 | # not cover any item, remove the option. Interestingly, we do not | ||
| 2247 | # need to implement this - it kind of happens automatically for us | ||
| 2248 | # during the graph coloring bipartiteness check, since the options | ||
| 2249 | # in question will not be part of the main connected component of | ||
| 2250 | # the graph. | ||
| 2251 | |||
| 2252 | # Now that the reductions have been performed, we will actually | ||
| 2253 | # run the exhaustive search. | ||
| 2254 | |||
| 2255 | my $other = $self->complement; | ||
| 2256 | |||
| 2257 | for my $item (@items) { | ||
| 2258 | $other->remove_vertex($item); | ||
| 2259 | } | ||
| 2260 | |||
| 2261 | for my $o (@options) { | ||
| 2262 | $other->exhaustive_search($o, $lambda); | ||
| 2263 | } | ||
| 2264 | @covers = sort { @$a <=> @$b } @covers; | ||
| 2265 | for (0 .. $n_solutions - 1) { | ||
| 2266 | if ($covers[$_]) { | ||
| 2267 | push @wanted, $covers[$_]; | ||
| 2268 | } | ||
| 2269 | } | ||
| 2270 | |||
| 2271 | END: | ||
| 2272 | return @wanted; | ||
| 2273 | } | ||
| 2274 | |||
| 2275 | =item _covers_all_items | ||
| 2276 | |||
| 2277 | =cut | ||
| 2278 | |||
| 2279 | sub _covers_all_items { | ||
| 2280 | ## ArrayRef : ArrayRef -> Boolean | ||
| 2281 | my ($the_options, $the_items) = @_; | ||
| 2282 | do { | ||
| 2283 | say qq[_covers_all_items:]; | ||
| 2284 | say | ||
| 2285 | qq[ checking if options '@$the_options' cover items '@$the_items']; | ||
| 2286 | } if DEBUG; | ||
| 2287 | |||
| 2288 | my @option_elems; | ||
| 2289 | my @item_elems; | ||
| 2290 | |||
| 2291 | @option_elems = uniq sort { $a cmp $b } split //, join '', @$the_options; | ||
| 2292 | @option_elems = sort { $a cmp $b } @option_elems; | ||
| 2293 | say qq[ option_elems: (@option_elems)] if DEBUG; | ||
| 2294 | |||
| 2295 | @item_elems = sort { $a cmp $b } @$the_items; | ||
| 2296 | |||
| 2297 | for (my $i = 0; $i < @item_elems; $i++) { | ||
| 2298 | unless (_memberp($item_elems[$i], \@option_elems)) { | ||
| 2299 | say qq[ NO] if DEBUG; | ||
| 2300 | return; | ||
| 2301 | } | ||
| 2302 | } | ||
| 2303 | say qq[ YES] if DEBUG; | ||
| 2304 | return 1; | ||
| 2305 | } | ||
| 2306 | |||
| 2307 | =item del | ||
| 2308 | |||
| 2309 | =cut | ||
| 2310 | |||
| 2311 | sub _del { | ||
| 2312 | ## ArrayRef Scalar -> State! | ||
| 2313 | my ($xs, $item) = @_; | ||
| 2314 | for (my $i = 0; $i < @$xs; $i++) { | ||
| 2315 | if ($xs->[$i] eq $item) { | ||
| 2316 | ## splice ARRAY,OFFSET,LENGTH,LIST | ||
| 2317 | splice(@$xs, $i, 1); # delete element at index $i | ||
| 2318 | } | ||
| 2319 | } | ||
| 2320 | } | ||
| 2321 | |||
| 2322 | =item _disjoint | ||
| 2323 | |||
| 2324 | =cut | ||
| 2325 | |||
| 2326 | sub _disjoint { | ||
| 2327 | ## Array -> Boolean | ||
| 2328 | my (@options) = @_; | ||
| 2329 | |||
| 2330 | # The set of options is disjoint if, when joined, split, and sorted, | ||
| 2331 | # the resulting array contains no duplicate elements. | ||
| 2332 | say qq[_disjoint:] if DEBUG; | ||
| 2333 | |||
| 2334 | my @elems = split //, join '', @options; | ||
| 2335 | say qq[ elems: (@elems)] if DEBUG; | ||
| 2336 | |||
| 2337 | my @uniq = uniq @elems; | ||
| 2338 | say qq[ uniq: (@uniq)] if DEBUG; | ||
| 2339 | |||
| 2340 | unless (@uniq == @elems) { | ||
| 2341 | say qq[ _disjoint(@options) == FALSE] if DEBUG; | ||
| 2342 | return; | ||
| 2343 | } | ||
| 2344 | |||
| 2345 | say qq[ _disjoint(@options) == TRUE] if DEBUG; | ||
| 2346 | return 1; | ||
| 2347 | } | ||
| 2348 | |||
| 2349 | =item get_anti_neighbors | ||
| 2350 | |||
| 2351 | =cut | ||
| 2352 | |||
| 2353 | sub _get_anti_neighbors { | ||
| 2354 | my ($self, $vertex) = @_; | ||
| 2355 | my %seen; | ||
| 2356 | $seen{$vertex}++; | ||
| 2357 | my $neighbors = $self->get_neighbors($vertex); | ||
| 2358 | for my $neighbor (@$neighbors) { | ||
| 2359 | $seen{$neighbor}++; | ||
| 2360 | } | ||
| 2361 | my @antineighbors; | ||
| 2362 | my @vertices = $self->get_vertices; | ||
| 2363 | for my $v (@vertices) { | ||
| 2364 | push @antineighbors, $v unless $seen{$v}; | ||
| 2365 | } | ||
| 2366 | return @antineighbors; | ||
| 2367 | } | ||
| 2368 | |||
| 2369 | =item complement | ||
| 2370 | |||
| 2371 | =back | ||
| 2372 | |||
| 2373 | =cut | ||
| 2374 | |||
| 2375 | sub complement { | ||
| 2376 | my ($self) = @_; | ||
| 2377 | my @vertices = $self->get_vertices; | ||
| 2378 | my $h = YAGL->new(is_directed => $self->is_directed); | ||
| 2379 | for my $v (@vertices) { | ||
| 2380 | my @antineighbors = $self->_get_anti_neighbors($v); | ||
| 2381 | for my $a (@antineighbors) { | ||
| 2382 | $h->add_edge($v, $a); | ||
| 2383 | my $v_attrs = $self->get_vertex_attributes($v); | ||
| 2384 | $h->set_vertex_attribute($v, $v_attrs); | ||
| 2385 | my $a_attrs = $self->get_vertex_attributes($a); | ||
| 2386 | $h->set_vertex_attribute($a, $a_attrs); | ||
| 2387 | } | ||
| 2388 | } | ||
| 2389 | return $h; | ||
| 2390 | } | ||
| 2391 | |||
| 2392 | |||
| 2393 | 1; | ||
| 2394 | |||
| 2395 | =pod | ||
| 2396 | |||
| 2397 | =head1 REFERENCES | ||
| 2398 | |||
| 2399 | =over | ||
| 2400 | |||
| 2401 | =item Even, Shimon. I<Graph Algorithms>. | ||
| 2402 | |||
| 2403 | =item Skiena, Steven. I<Implementing Discrete Mathematics>. | ||
| 2404 | |||
| 2405 | =item Sedgewick, Robert. I<Algorithms, 2nd ed.> | ||
| 2406 | |||
| 2407 | =back | ||
| 2408 | |||
| 2409 | =head1 SEE ALSO | ||
| 2410 | |||
| 2411 | =over | ||
| 2412 | |||
| 2413 | =item * L<Graph> by Jarkko Hietaniemi | ||
| 2414 | |||
| 2415 | =item * L<Graph::Fast> by Lars Stoltenow | ||
| 2416 | |||
| 2417 | =item * L<Boost::Graph> by David Burdick | ||
| 2418 | |||
| 2419 | =back | ||
| 2420 | |||
| 2421 | =head1 BUGS | ||
| 2422 | |||
| 2423 | Undoubtedly! Please file any issues at L<https://github.com/rmloveland/YAGL>. | ||
| 2424 | |||
| 2425 | =head1 AUTHOR | ||
| 2426 | |||
| 2427 | Richard Loveland <r@rmloveland.com> | ||
| 2428 | |||
| 2429 | =head1 COPYRIGHT AND LICENSE | ||
| 2430 | |||
| 2431 | This software is copyright (c) 2019, 2020, 2021, 2022, 2023, 2024 by Rich Loveland | ||
| 2432 | |||
| 2433 | This is free software; you can redistribute it and/or modify it under | ||
| 2434 | the same terms as the Perl 5 programming language system itself. | ||
| 2435 | |||
| 2436 | =cut | ||