blib/lib/Graph/Dijkstra.pm

filter: Statementstmt 88.8% 16 / 18 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 6 / 6 Podpod n/a totaltotal 91.6% 22 / 24 CC 1 SCAR 0.5
CC
1
Cov
89%
BEGIN
1.3
BEGIN
1.0
BEGIN
1.0
CRAP 1.0
↑ Summary
1 package Graph::Dijkstra;
2
3 1 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 1 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
5
6 1 ▶use Carp qw(croak carp);
Subroutine BEGIN: called CC=1 SCAR=0.0
7
8 1 ▶use English qw(-no_match_vars);
Subroutine BEGIN: called CC=1 SCAR=0.0
9 $OUTPUT_AUTOFLUSH=1;
10
11
12 1 ▶use vars qw($VERSION);
Subroutine BEGIN: called CC=1 SCAR=0.0
13 $VERSION = '0.70';
14
15 my $VERBOSE = 0;
16 my $verboseOutfile = *STDOUT;
17
18 0 ▶use Readonly;
Subroutine BEGIN: called CC=1 SCAR=2.6
19
20 Readonly my $EMPTY_STRING => q{};
21 Readonly my %IS_GRAPHML_WEIGHT_ATTR => map { ($_ => 1) } qw(weight value cost distance height);
22 Readonly my %IS_GRAPHML_LABEL_ATTR => map { ($_ => 1) } qw(label name description nlabel);
23 Readonly my $PINF => 1e9999; # positive infinity
24 Readonly my %GRAPH_ATTRIBUTES => (label=>$EMPTY_STRING, creator=>$EMPTY_STRING, edgedefault=>'undirected');
25 Readonly my %NODE_ATTRIBUTES => (label=>$EMPTY_STRING);
26 Readonly my %EDGE_ATTRIBUTES => (id=>$EMPTY_STRING, label=>$EMPTY_STRING, directed=>'undirected', weight=>0);
27
28 ## no critic (PostfixControls)
29
30 #############################################################################
31 #used Modules #
32 #############################################################################
33
34
35 use Benchmark qw(:hireswallclock);
36 use Array::Heap::ModifiablePriorityQueue;
37 use Scalar::Util qw(looks_like_number);
38 use HTML::Entities qw(encode_entities);
39 use utf8;
40
41 #############################################################################
42 #Class Methods #
43 #############################################################################
44
45 sub verbose {
46 VERBOSE(@_);
47 }
48
49 sub VERBOSE {
50 my ($either, $verbose, $vOutfile) = @_;
51 return $VERBOSE if !defined($verbose);
52 $VERBOSE = $verbose;
53 print {$verboseOutfile} 'verbose output ', (($VERBOSE) ? 'set' : 'unset'), "\n";
54 if (defined($vOutfile) and (ref($vOutfile) eq 'GLOB' or ref($vOutfile) eq 'IO')) {
55 $verboseOutfile = $vOutfile;
56 print {$verboseOutfile} "verbose output redirected\n";
57 }
58 }
59
60 sub stringifyAttribs {
61 my ($either, $attribHref) = @_;
62
63 return if ref($attribHref) ne 'HASH';
64
65 my $val = '';
66 foreach my $attrib (sort keys %$attribHref) {
67 $val .= ', ' if $val;
68 my $printval = (looks_like_number($attribHref->{$attrib})) ? "$attribHref->{$attrib}" : "'".encode_entities($attribHref->{$attrib})."'";
69 $val .= "$attrib=>$printval";
70 }
71 return "( $val )";
72 }
73
74 sub hashifyAttribs {
75 my ($either, $attribStr) = @_;
76
77 my %keyvals = ();
78
79 if ($attribStr =~ /^\(\s*(.+)\s*\)$/) {
80 $attribStr = $1;
81 }
82 while ($attribStr =~ /([a-z]+) => ([+-]? [0-9]+ (?: \. [0-9]+ )?+|(?:(?:\')(?:[^\\\']*(?:\\.[^\\\']*)*)(?:\')))/igx) {
83 my $id = $1;
84 my $val = $2;
85 $val = substr($val,1,-1) if substr($val,0,1) eq "'";
86 $keyvals{$id} = $val;
87 }
88 return \%keyvals;
89 }
90
91
92 sub _initialize {
93 my ($self, $options) = @_;
94 $self->{edges} = ();
95 $self->{nodes} = ();
96
97 foreach my $attrib (keys %GRAPH_ATTRIBUTES) {
98 $self->{$attrib} = $GRAPH_ATTRIBUTES{$attrib};
99 }
100
101 if (ref($options) eq 'HASH') {
102 foreach my $attrib (keys %$options) {
103 if (exists($GRAPH_ATTRIBUTES{$attrib})) {
104 $self->{$attrib} = $options->{$attrib};
105 }
106 else {
107 carp "new: unrecognized graph attribute '$attrib'";
108 }
109 }
110 }
111 return $self;
112 }
113
114 sub new {
115 my ($class, $options) = @_;
116
117 my $self = {};
118 bless $self, $class;
119
120 return $self->_initialize($options);
121
122 #return $self;
123 }
124
125
126 #############################################################################
127 #Graph Method(s) #
128 #############################################################################
129
130 sub graph {
131 my ($self, $options) = @_;
132 if (defined($options) and ref($options) eq 'HASH') { #SET method call
133 foreach my $attrib (keys %$options) {
134 if (exists($GRAPH_ATTRIBUTES{$attrib})) {
135 utf8::upgrade($options->{$attrib});
136 $self->{$attrib} = $options->{$attrib};
137 }
138 else {
139 carp "graph: unrecognized graph attribute '$attrib'";
140 }
141 }
142 return $self;
143 }
144 #GET method call
145
146 return( {map { ($_ => $self->{$_} ) } (keys %GRAPH_ATTRIBUTES)} );
147 }
148
149 #############################################################################
150 #Node Methods #
151 #############################################################################
152
153 sub node {
154 my ($self, $nodeParam) = @_;
155
156 croak "node: missing nodeID / options parameter" if !defined($nodeParam);
157
158 if (ref($nodeParam) eq $EMPTY_STRING) { #GET method call
159 #my $nodeID = $nodeParam;
160
161 if (exists($self->{nodes}{$nodeParam})) {
162 my %node = map { ($_ => $self->{nodes}{$nodeParam}{$_} ) } (keys %NODE_ATTRIBUTES);
163 $node{id} = $nodeParam;
164 return( \%node );
165 }
166 return;
167 }
168
169 if (ref($nodeParam) eq 'HASH') { #SET method call
170
171 croak "node: missing \"id\" attribute in attributes hash" if !exists($nodeParam->{id});
172 my $nodeID = $nodeParam->{id};
173 croak "node: nodeID is not a SCALAR value" if ref($nodeID) ne $EMPTY_STRING;
174
175 if (!exists($self->{nodes}{$nodeID})) { #set default node attribute values for new node
176 foreach my $attrib (keys %NODE_ATTRIBUTES) {
177 $self->{nodes}{$nodeID}{$attrib} = $NODE_ATTRIBUTES{$attrib};
178 }
179 }
180
181 foreach my $attrib (keys %$nodeParam) { #update node attribute values from parameter values
182 if ( exists($NODE_ATTRIBUTES{$attrib}) ) {
183 utf8::upgrade($nodeParam->{$attrib});
184 $self->{nodes}{$nodeID}{$attrib} = $nodeParam->{$attrib};
185 }
186 elsif ($attrib ne 'id') {
187 carp "node: unrecognized node attribute '$attrib'";
188 }
189 }
190
191 return $self;
192 }
193 croak "node: invalid parameter: must be either a nodeID (simple scalar) or an attributes hash (reference)";
194 }
195
196 sub nodeExists {
197 my ($self, $nodeID) = @_;
198
199 croak "nodeExists: missing nodeID parameter" if !defined($nodeID);
200
201 return (exists($self->{nodes}{$nodeID})) ? 1 : 0;
202 }
203
204
205 sub nodeList {
206 my $self = shift;
207
208 my @nodeList = ();
209 foreach my $node (keys %{$self->{nodes}}) {
210 push(@nodeList, { id=>$node, map {($_ => $self->{nodes}{$node}{$_})} (keys %NODE_ATTRIBUTES) } );
211 }
212 return @nodeList;
213 }
214
215
216 sub nodeIDsList {
217 my $self = shift;
218
219 my @nodeList = ();
220 foreach my $node (keys %{$self->{nodes}}) {
221 push(@nodeList, $node);
222 }
223 return @nodeList;
224 }
225
226
227 sub removeNode {
228 my ($self, $nodeID) = @_;
229
230 croak "removeNode: missing nodeID parameter" if !defined($nodeID);
231
232 if (exists($self->{nodes}{$nodeID})) {
233
234 if (exists($self->{edges}{$nodeID})) { #delete edges where nodeID is source
235 delete($self->{edges}{$nodeID});
236 }
237
238 foreach my $sourceID (keys %{$self->{edges}}) { #delete edges where nodeID is target
239 if (exists($self->{edges}{$sourceID}{$nodeID})) {
240 delete($self->{edges}{$sourceID}{$nodeID});
241 }
242 }
243
244 delete($self->{nodes}{$nodeID});
245 return $self;
246 }
247 return;
248 }
249
250 #############################################################################
251 #Edge Methods #
252 #############################################################################
253
254
255 sub edge {
256 my ($self, $edgeHref) = @_;
257
258 croak "edge: missing parameter hash reference" if !defined($edgeHref) or ref($edgeHref) ne 'HASH';
259 croak "edge: parameter hash missing sourceID" if !exists($edgeHref->{sourceID});
260 croak "edge: parameter hash missing targetID" if !exists($edgeHref->{targetID});
261
262 my $sourceID = $edgeHref->{sourceID};
263 my $targetID = $edgeHref->{targetID};
264
265 #checks that apply to both set & get calls
266
267 if ($sourceID eq $targetID) {
268 carp 'edge: source and target node IDs must be different: ' . $self->stringifyAttribs( $edgeHref );
269 return;
270 }
271
272 if (!exists($self->{nodes}{$sourceID})) {
273 carp "edge: sourceID $sourceID does not exist.";
274 return;
275 }
276
277 if (!exists($self->{nodes}{$targetID})) {
278 carp "edge: targetID $targetID does not exist.";
279 return;
280 }
281
282
283 if (scalar(keys %$edgeHref) == 2) { #get method call, must be just sourceID, targetID
284
285 if (exists($self->{edges}{$sourceID}{$targetID})) {
286 return( {sourceID=>$sourceID, targetID=>$targetID, map { ($_ => $self->{edges}{$sourceID}{$targetID}{$_} ) } (keys %EDGE_ATTRIBUTES) } );
287 }
288
289 if (exists($self->{nodes}{$sourceID}) and exists($self->{nodes}{$targetID})) {
290 return( {sourceID=>$sourceID, targetID=>$targetID, weight=>0} );
291 }
292
293 if (!exists($self->{nodes}{$sourceID})) {
294 carp "edge: sourceID $sourceID does not exist";
295 return;
296 }
297
298 carp "edge: targetID $targetID does not exist";
299 return;
300 }
301
302 #set method call
303
304 #directed value check
305 if (exists($edgeHref->{directed}) and ($edgeHref->{directed} ne 'directed' and $edgeHref->{directed} ne 'undirected')) {
306 carp "edge: unrecognized 'directed' attribute value '$edgeHref->{directed}'.";
307 return;
308 }
309
310 #weight value check
311 if (exists( $edgeHref->{weight} ) and (!looks_like_number($edgeHref->{weight}) or $edgeHref->{weight} <= 0)) {
312 carp "edge: invalid edge weight (cost) $edgeHref->{weight}.";
313 return;
314 }
315
316 if (exists($self->{edges}{$sourceID}{$targetID})) { #update existing edge
317
318 if (exists($edgeHref->{directed}) and $edgeHref->{directed} ne $self->{edges}{$sourceID}{$targetID}{directed}) {
319 carp "edge: cannot change directed value for existing edge $sourceID $targetID '$self->{edges}{$sourceID}{$targetID}{directed}'. To change edge directed value, remove and re-add.";
320 return;
321 }
322 my $edgeDirected = $self->{edges}{$sourceID}{$targetID}{directed};
323
324 foreach my $attrib (keys %$edgeHref) { #update node attribute values from parameter values
325
326 if ( exists($EDGE_ATTRIBUTES{$attrib}) ) {
327
328 utf8::upgrade($edgeHref->{$attrib}) if !looks_like_number($edgeHref->{$attrib});
329
330 $self->{edges}{$sourceID}{$targetID}{$attrib} = $edgeHref->{$attrib};
331 $self->{edges}{$targetID}{$sourceID}{$attrib} = $edgeHref->{$attrib} if $edgeDirected eq 'undirected';
332 }
333 elsif ($attrib ne 'sourceID' and $attrib ne 'targetID') {
334 carp "edge: unrecognized attribute '$attrib' not set";
335 }
336 }
337 return $self;
338 }
339
340 #create new edge
341
342 $edgeHref->{directed} = $self->{edgedefault} if !exists($edgeHref->{directed});
343
344 if ($edgeHref->{directed} eq 'undirected' and exists($self->{edges}{$targetID}{$sourceID}) and $self->{edges}{$targetID}{$sourceID}{directed} eq 'directed') {
345 carp "edge: $targetID $sourceID directed arc (edge) exists. Undirected edge $sourceID $targetID not created. Remove then add.";
346 return;
347 }
348
349 #set default attribute values
350 foreach my $attrib (keys %EDGE_ATTRIBUTES) {
351 $self->{edges}{$sourceID}{$targetID}{$attrib} = $EDGE_ATTRIBUTES{$attrib};
352 $self->{edges}{$targetID}{$sourceID}{$attrib} = $EDGE_ATTRIBUTES{$attrib} if $edgeHref->{directed} eq 'undirected';
353 }
354
355 foreach my $attrib (keys %$edgeHref) { #set edge attribute values from parameter values
356
357 next if ($attrib eq 'sourceID' or $attrib eq 'targetID');
358
359 if ( exists($EDGE_ATTRIBUTES{$attrib}) ) {
360 utf8::upgrade($edgeHref->{$attrib}) if !looks_like_number($attrib);
361 $self->{edges}{$sourceID}{$targetID}{$attrib} = $edgeHref->{$attrib};
362 $self->{edges}{$targetID}{$sourceID}{$attrib} = $edgeHref->{$attrib} if $edgeHref->{directed} eq 'undirected';
363 }
364 else {
365 carp "edge: unrecognized attribute '$attrib' not set";
366 }
367 }
368
369 return($self);
370
371 }
372
373 sub _getEdgeAttrib {
374 my ($self, $sourceID, $targetID, $attrib) = @_;
375
376 if (exists($self->{edges}{$sourceID}{$targetID}{$attrib})) {
377 return $self->{edges}{$sourceID}{$targetID}{$attrib};
378 }
379 croak "_getEdgeAttrib: does not exist '$sourceID' '$targetID' '$attrib'";
380
381 }
382
383 sub _hasEdges {
384 my ($self, $sourceID) = @_;
385 return exists($self->{edges}{$sourceID});
386 }
387
388 sub removeEdge {
389 my ($self, $edgeHref) = @_;
390
391 croak "removeEdge: missing parameter hash reference" if !defined($edgeHref);
392 croak "removeEdge: parameter hash missing sourceID" if !exists($edgeHref->{sourceID});
393 croak "removeEdge: parameter hash missing targetID" if !exists($edgeHref->{targetID});
394
395 my $sourceID = $edgeHref->{sourceID};
396 my $targetID = $edgeHref->{targetID};
397
398 if (exists($self->{edges}{$sourceID}{$targetID})) {
399
400 my $directed = $self->{edges}{$sourceID}{$targetID}{directed};
401
402 delete($self->{edges}{$sourceID}{$targetID});
403
404 if ($directed eq 'undirected') { #remove $targetID $sourceID for undirected edges
405
406 delete($self->{edges}{$targetID}{$sourceID});
407
408 }
409 }
410 else {
411 carp "removeEdge: no edge found for sourceID $sourceID and targetID $targetID";
412 }
413
414 return $self;
415 }
416
417
418
419 sub edgeExists {
420 my ($self, $edgeHref) = @_;
421
422 croak "edgeExists: missing parameter hash reference" if !defined($edgeHref);
423 croak "edgeExists: parameter hash missing sourceID" if !exists($edgeHref->{sourceID});
424 croak "edgeExists: parameter hash missing targetID" if !exists($edgeHref->{targetID});
425
426 my $sourceID = $edgeHref->{sourceID};
427 my $targetID = $edgeHref->{targetID};
428
429 return exists($self->{edges}{$sourceID}{$targetID});
430 }
431
432
433 sub adjacent {
434 my ($self, $edgeHref) = @_;
435
436 croak "adjacent: missing parameter hash reference" if !defined($edgeHref);
437 croak "adjacent: parameter hash missing sourceID" if !exists($edgeHref->{sourceID});
438 croak "adjacent: parameter hash missing targetID" if !exists($edgeHref->{targetID});
439
440 my $sourceID = $edgeHref->{sourceID};
441 my $targetID = $edgeHref->{targetID};
442
443 return exists($self->{edges}{$sourceID}{$targetID});
444 }
445
446
447 sub adjacentNodes {
448 my ($self, $sourceID) = @_;
449
450 if (!defined($sourceID)) {
451 croak "adjacentNodes: missing node ID parameter";
452 }
453
454 my @neighbors = ();
455 if (exists($self->{edges}{$sourceID})) {
456 foreach my $targetID (keys %{$self->{edges}{$sourceID}}) {
457 push(@neighbors, $targetID);
458 }
459 croak "adjacentNodes: internal logic error" if scalar(@neighbors) == 0;
460 }
461 # else {
462 # print {$verboseOutfile} "adjacentNodes: node $sourceID has no outbound edges\n" if $VERBOSE;
463 # }
464 return @neighbors;
465 }
466
467
468
469 #############################################################################
470 #Dijkstra Computation Methods #
471 #############################################################################
472
473 #Computes Jordan center by creating all pairs shortest path matrix
474
475 sub vertexCenter {
476 my ($self, $solutionMatrix) = @_;
477
478 %$solutionMatrix = ();
479
480 my @connectedNodeList = ();
481 my $nodesEdgeCount = 0;
482
483 my $totalNodes = 0;
484 foreach my $nodeID ( $self->nodeIDsList() ) {
485 $totalNodes++;
486 $nodesEdgeCount++ if $self->_hasEdges($nodeID);
487 push(@connectedNodeList, $nodeID);
488 }
489 my $nodeCount = scalar(@connectedNodeList);
490 print {$verboseOutfile} "vertexCenter: graph contains $totalNodes nodes, $nodesEdgeCount nodes have one or more outbound edges\n" if $VERBOSE;
491
492 foreach my $fromNodeID (@connectedNodeList) {
493
494 $solutionMatrix->{rowMax}{$fromNodeID} = $PINF;
495
496 foreach my $toNodeID (@connectedNodeList) {
497 $solutionMatrix->{row}{$fromNodeID}{$toNodeID} = $PINF;
498 }
499 $solutionMatrix->{row}{$fromNodeID}{$fromNodeID} = 0;
500 }
501 my $hasDirectedEdges = 0;
502 foreach my $nodeID (@connectedNodeList) {
503 foreach my $targetID ($self->adjacentNodes($nodeID)) {
504 if ($self->_getEdgeAttrib($nodeID, $targetID, 'directed') eq 'directed') {
505 $hasDirectedEdges = 1;
506 last;
507 }
508 }
509 last if $hasDirectedEdges;
510 }
511 my $matrixComputations = ($totalNodes * $totalNodes) - $totalNodes;
512 if ($nodesEdgeCount < $totalNodes) {
513 my $nodesNoEdges = $totalNodes - $nodesEdgeCount;
514 $matrixComputations -= $nodesNoEdges * ($totalNodes - 1);
515 }
516 $matrixComputations = $matrixComputations / 2 if !$hasDirectedEdges;
517 print {$verboseOutfile} "vertexCenter: graph has directed edges. Computing shortest path for A -> C and C -> A separately.\n" if $hasDirectedEdges and $VERBOSE;
518 print {$verboseOutfile} "vertexCenter: graph has no directed edges. Shortest path for A -> C and C -> A are same.\n" if !$hasDirectedEdges and $VERBOSE;
519 print {$verboseOutfile} "vertexCenter: performing $matrixComputations shortest path computations.\n" if $VERBOSE;
520
521 #should add code to limit computations at reasonable number
522
523 my $cycle = 0;
524 my $t0 = Benchmark->new;
525
526 foreach my $origin (@connectedNodeList) {
527
528 next if !$self->_hasEdges($origin); #skip origin nodes that have no outbound edges, all paths are infinite
529 #print '.';
530 foreach my $destination (@connectedNodeList) {
531
532 next if $solutionMatrix->{row}{$origin}{$destination} < $PINF or $origin eq $destination;
533 #print "shortest path $origin -> $destination...";
534
535 my $pq = Array::Heap::ModifiablePriorityQueue->new();
536
537 my %solution = ();
538 my %unvisited = ();
539 foreach my $node (@connectedNodeList) {
540 next if $node ne $destination and !$self->_hasEdges($node); #solution cannot include intermediate nodes with no outbound edges
541 $solution{$node}{weight} = $PINF;
542 $pq->add($node, $PINF);
543 }
544
545 $solution{$origin}{weight} = 0;
546 $pq->add($origin,0); #modify weight of origin node
547
548
549 #my $foundSolution = 0;
550 while ($pq->size()) {
551 $cycle++;
552
553 my $visitNode = $pq->get();
554
555 $solutionMatrix->{row}{$origin}{$visitNode} = $solution{$visitNode}{weight};
556 $solutionMatrix->{row}{$visitNode}{$origin} = $solution{$visitNode}{weight} if !$hasDirectedEdges;
557
558 last if ($visitNode eq $destination);
559
560 foreach my $adjacentNode ($self->adjacentNodes($visitNode)) {
561 next if !defined($pq->weight($adjacentNode));
562
563 my $thisWeight = $solution{$visitNode}{weight} + $self->{edges}{$visitNode}{$adjacentNode}{weight};
564 if ($thisWeight < $solution{$adjacentNode}{weight}) {
565 $solution{$adjacentNode}{weight} = $thisWeight;
566 # $solution{$adjacentNode}{prevnode} = $visitNode;
567 $pq->add($adjacentNode, $thisWeight);
568 }
569 }
570 }
571
572 undef($pq);
573 }
574 }
575 #print "\n cycles=$cycle\n";
576 if ($VERBOSE) {
577 my $t1 = Benchmark->new;
578 #if ($cycle >= 1000) {
579 # print "\n";
580 #}
581 my $td = timediff($t1, $t0);
582 print {$verboseOutfile} "computing shortest path matrix took: ",timestr($td),"\n";
583 }
584 my $graphMinMax = $PINF;
585 my $centerNode = '';
586 foreach my $origin (@connectedNodeList) {
587 my $rowMax = 0;
588 foreach my $destination (@connectedNodeList) {
589 next if $origin eq $destination;
590 if ($solutionMatrix->{row}{$origin}{$destination} > $rowMax) {
591 $rowMax = $solutionMatrix->{row}{$origin}{$destination};
592 }
593 }
594 $solutionMatrix->{rowMax}{$origin} = $rowMax;
595 if ($rowMax < $graphMinMax) {
596 $graphMinMax = $rowMax;
597 }
598 }
599 $solutionMatrix->{centerNodeSet} = [];
600 if ($graphMinMax < $PINF) {
601 foreach my $origin (@connectedNodeList) {
602 if ($solutionMatrix->{rowMax}{$origin} == $graphMinMax) {
603 push(@{$solutionMatrix->{centerNodeSet}}, $origin);
604 }
605 }
606 }
607 else {
608 carp "vertexCenter: Graph contains disconnected sub-graph / non-reachable node pairs. Center node set undefined.";
609 $graphMinMax = 0;
610 }
611 #print "centernodeset ", join(',', @{$solutionMatrix->{centerNodeSet}}), "\n";
612 return($graphMinMax);
613 }
614
615 sub farthestNode { ## no critic (ProhibitExcessComplexity)
616 my ($self, $solutionHref) = @_;
617
618 if (!exists($solutionHref->{originID})) {
619 croak "farthestNode: originID attribute not set in solution hash reference parameter";
620 }
621 my $originID = $solutionHref->{originID};
622
623 if (!exists($self->{nodes}{$originID})) {
624 carp "farthestNode: originID not found: $originID";
625 return 0;
626 }
627 elsif (!$self->_hasEdges($originID)) {
628 carp "farthestNode: origin node $originID has no edges";
629 return 0;
630 }
631 my $pq = Array::Heap::ModifiablePriorityQueue->new();
632
633 my %solution = (); #initialize the solution hash
634 my %unvisited = ();
635 foreach my $node ($self->nodeIDsList()) {
636 $solution{$node}{weight} = $PINF;
637 $solution{$node}{prevnode} = $EMPTY_STRING;
638 $pq->add($node, $PINF);
639 }
640
641 $solution{$originID}{weight} = 0;
642 $pq->add($originID,0); #modify weight of origin node
643
644 my $cycle = 0;
645 my $t0 = Benchmark->new;
646
647 while ($pq->size()) {
648 $cycle++;
649 #print '.' if $VERBOSE and ($cycle % 1000 == 0);
650
651 my $visitNode = $pq->get();
652 next if !$self->_hasEdges($visitNode);
653
654 foreach my $adjacentNode ($self->adjacentNodes($visitNode)) {
655 next if !defined($pq->weight($adjacentNode));
656
657 my $thisWeight = $solution{$visitNode}{weight} + $self->_getEdgeAttrib($visitNode, $adjacentNode, 'weight' );
658 if ($thisWeight < $solution{$adjacentNode}{weight}) {
659 $solution{$adjacentNode}{weight} = $thisWeight;
660 $solution{$adjacentNode}{prevnode} = $visitNode;
661 $pq->add($adjacentNode, $thisWeight);
662 }
663 }
664 }
665 if ($VERBOSE) {
666 my $t1 = Benchmark->new;
667 #if ($cycle >= 1000) {
668 # print "\n";
669 #}
670 my $td = timediff($t1, $t0);
671 print {$verboseOutfile} "dijkstra's algorithm took: ",timestr($td),"\n";
672 }
673
674 my $farthestWeight = 0;
675 foreach my $node (sort keys %solution) {
676
677 if ($solution{$node}{weight} < $PINF and $solution{$node}{weight} > $farthestWeight) {
678 $farthestWeight = $solution{$node}{weight};
679 #$farthestnode = $node;
680 }
681 }
682
683 croak "farthestNode: path weight to farthest node is 0" if $farthestWeight == 0;
684
685
686 my $solutioncnt = 0;
687 %{$solutionHref} = (
688 desc => 'farthest',
689 originID => $originID,
690 weight => $farthestWeight,
691 );
692
693 foreach my $farthestnode (sort keys %solution) {
694 if ($solution{$farthestnode}{weight} == $farthestWeight) {
695
696 $solutioncnt++;
697
698 print {$verboseOutfile} "\nfarthestNode: (solution $solutioncnt) farthest node from origin $originID is $farthestnode at weight (cost) $farthestWeight\n" if $VERBOSE;
699
700 my $fromNode = $solution{$farthestnode}{prevnode};
701 my @path = ( $farthestnode, $fromNode );
702
703 my %loopCheck = ();
704 while ($solution{$fromNode}{prevnode} ne $EMPTY_STRING) {
705 $fromNode = $solution{$fromNode}{prevnode};
706 if (exists($loopCheck{$fromNode})) {
707 print STDERR "farthestNode: path loop at $fromNode\n";
708 print STDERR 'farthestNode: path = ', join(',',@path), "\n";
709 die 'farthestNode: internal error: destination to origin path logic error';
710 }
711 $loopCheck{$fromNode} = 1;
712 push(@path,$fromNode);
713 }
714
715 @path = reverse(@path);
716
717 my $nexttolast = $#path - 1;
718
719 $solutionHref->{path}{$solutioncnt}{destinationID} = $farthestnode;
720 $solutionHref->{path}{$solutioncnt}{edges} = [];
721
722 foreach my $i (0 .. $nexttolast) {
723
724 push(@{$solutionHref->{path}{$solutioncnt}{edges}}, {sourceID => $path[$i], targetID => $path[$i+1], weight => $self->edge( { sourceID=>$path[$i], targetID=>$path[$i+1] } )->{weight} } );
725
726 }
727 }
728 }
729
730 $solutionHref->{count} = $solutioncnt;
731
732 return($farthestWeight);
733 }
734
735 sub shortestPath { ## no critic (ProhibitExcessComplexity)
736 my ($self, $solutionHref) = @_;
737
738 if (!exists($solutionHref->{originID})) {
739 croak "farthestNode: originID attribute not set in solution hash reference parameter";
740 }
741 my $originID = $solutionHref->{originID};
742
743 if (!exists($solutionHref->{destinationID})) {
744 croak "farthestNode: destinationID attribute not set in solution hash reference parameter";
745 }
746 my $destinationID = $solutionHref->{destinationID};
747
748 if (!exists($self->{nodes}{$originID})) {
749 carp "shortestPath: originID not found: $originID";
750 return 0;
751 }
752
753 if (!$self->_hasEdges($originID)) {
754 carp "shortestPath: origin node $originID has no edges";
755 return 0;
756 }
757 if (!exists($self->{nodes}{$destinationID})) {
758 carp "shortestPath: destinationID not found: $destinationID";
759 return 0;
760 }
761
762 my $pq = Array::Heap::ModifiablePriorityQueue->new();
763
764 my %solution = (); #initialize the solution hash
765 my %unvisited = ();
766 foreach my $node ($self->nodeIDsList()) {
767 $solution{$node}{weight} = $PINF;
768 $solution{$node}{prevnode} = $EMPTY_STRING;
769 $pq->add($node, $PINF);
770 }
771
772 $solution{$originID}{weight} = 0;
773 $pq->add($originID,0); #modify weight of origin node
774
775 my $cycle = 0;
776 my $t0 = Benchmark->new;
777
778 my $foundSolution = 0;
779 while ($pq->size()) {
780 $cycle++;
781 #print '.' if $VERBOSE and ($cycle % 1000 == 0);
782
783 my $visitNode = $pq->get();
784
785 if ($visitNode eq $destinationID) {
786 $foundSolution = 1 if $solution{$visitNode}{weight} < $PINF;
787 last;
788 }
789 next if !$self->_hasEdges($visitNode);
790
791 foreach my $adjacentNode ($self->adjacentNodes($visitNode)) {
792 next if !defined($pq->weight($adjacentNode));
793
794 my $thisWeight = $solution{$visitNode}{weight} + $self->_getEdgeAttrib($visitNode, $adjacentNode, 'weight' );
795 if ($thisWeight < $solution{$adjacentNode}{weight}) {
796 $solution{$adjacentNode}{weight} = $thisWeight;
797 $solution{$adjacentNode}{prevnode} = $visitNode;
798 $pq->add($adjacentNode, $thisWeight);
799 }
800 }
801 }
802 if ($VERBOSE) {
803 my $t1 = Benchmark->new;
804 #if ($cycle >= 1000) {
805 # print "\n";
806 #}
807 my $td = timediff($t1, $t0);
808 print "dijkstra's algorithm took: ",timestr($td),"\n";
809 }
810
811 my $pathWeight = 0;
812 if ($foundSolution) {
813 $pathWeight = $solution{$destinationID}{weight};
814 print {$verboseOutfile} "shortestPath: originID $originID -> destinationID $destinationID pathWeight (cost) = $pathWeight\n" if $VERBOSE;
815
816 my $solutioncnt = 0;
817 %{$solutionHref} = (
818 desc => 'path',
819 originID => $originID,
820 destinationID => $destinationID,
821 weight => $pathWeight,
822 );
823
824 my $fromNode = $solution{$destinationID}{prevnode};
825 my @path = ( $destinationID, $fromNode );
826
827 my %loopCheck = ();
828 while ($solution{$fromNode}{prevnode} ne $EMPTY_STRING) {
829 $fromNode = $solution{$fromNode}{prevnode};
830 if (exists($loopCheck{$fromNode})) {
831 print "shortestPath: path loop at $fromNode\n";
832 print "shortestPath: path = ", join(',',@path), "\n";
833 die "shortestPath internal error: destination to origin path logic error";
834 }
835 $loopCheck{$fromNode} = 1;
836 push(@path,$fromNode);
837 }
838
839 @path = reverse(@path);
840
841 my $nexttolast = $#path - 1;
842 foreach my $i (0 .. $nexttolast) {
843 push(@{$solutionHref->{edges}}, {sourceID => $path[$i], targetID => $path[$i+1], weight => $self->edge( { sourceID=>$path[$i], targetID=>$path[$i+1] } )->{weight} } );
844 }
845 }
846 return($pathWeight);
847 }
848
849 #############################################################################
850 #Floyd Warshall alternative method #
851 #############################################################################
852
853 sub vertexCenterFloydWarshall {
854 my ($self, $solutionMatrix) = @_;
855
856 %$solutionMatrix = ();
857
858 my @nodeList = ();
859 my $nodesEdgeCount = 0;
860
861 my $totalNodes = 0;
862 foreach my $nodeID ( $self->nodeIDsList() ) {
863 $totalNodes++;
864 $nodesEdgeCount++ if $self->_hasEdges($nodeID);
865 push(@nodeList, $nodeID);
866 }
867 my $nodeCount = scalar(@nodeList);
868 print {$verboseOutfile} "vertexCenterFloydWarshall: graph contains $totalNodes nodes, $nodesEdgeCount nodes have one or more outbound edges\n" if $VERBOSE;
869
870 #should add code to limit computations at reasonable number
871
872 my $t0 = Benchmark->new;
873
874 foreach my $fromNodeID (@nodeList) {
875
876 $solutionMatrix->{rowMax}{$fromNodeID} = $PINF;
877
878 foreach my $toNodeID (@nodeList) {
879 $solutionMatrix->{row}{$fromNodeID}{$toNodeID} = $PINF;
880 }
881 $solutionMatrix->{row}{$fromNodeID}{$fromNodeID} = 0;
882 }
883
884 foreach my $fromNodeID (@nodeList) {
885 next if !$self->_hasEdges($fromNodeID);
886 foreach my $toNodeID ($self->adjacentNodes($fromNodeID)) {
887 $solutionMatrix->{row}{$fromNodeID}{$toNodeID} = $self->_getEdgeAttrib($fromNodeID, $toNodeID, 'weight');
888 $solutionMatrix->{row}{$toNodeID}{$fromNodeID} = $solutionMatrix->{row}{$fromNodeID}{$toNodeID} if $self->_getEdgeAttrib($fromNodeID, $toNodeID, 'directed') eq 'undirected';
889 }
890 }
891 foreach my $k (@nodeList) {
892 next if !$self->_hasEdges($k);
893 foreach my $i (@nodeList) {
894 next if !$self->_hasEdges($i);
895 foreach my $j (@nodeList) {
896 next if $i eq $j;
897 if ($solutionMatrix->{row}{$i}{$j} > ($solutionMatrix->{row}{$i}{$k} + $solutionMatrix->{row}{$k}{$j})) {
898 $solutionMatrix->{row}{$i}{$j} = $solutionMatrix->{row}{$i}{$k} + $solutionMatrix->{row}{$k}{$j};
899 }
900 }
901 }
902 }
903
904 if ($VERBOSE) {
905 my $t1 = Benchmark->new;
906 #if ($cycle >= 1000) {
907 # print "\n";
908 #}
909 my $td = timediff($t1, $t0);
910 print {$verboseOutfile} "vertexCenterFloydWarshall: computing shortest path matrix took: ",timestr($td),"\n";
911 }
912 my $graphMinMax = $PINF;
913 my $centerNode = '';
914 foreach my $origin (@nodeList) {
915 my $rowMax = 0;
916 foreach my $destination (@nodeList) {
917 next if $origin eq $destination;
918 if ($solutionMatrix->{row}{$origin}{$destination} > $rowMax) {
919 $rowMax = $solutionMatrix->{row}{$origin}{$destination};
920 }
921 }
922 $solutionMatrix->{rowMax}{$origin} = $rowMax;
923 if ($rowMax < $graphMinMax) {
924 $graphMinMax = $rowMax;
925 }
926 }
927 $solutionMatrix->{centerNodeSet} = [];
928 if ($graphMinMax < $PINF) {
929 foreach my $origin (@nodeList) {
930 if ($solutionMatrix->{rowMax}{$origin} == $graphMinMax) {
931 push(@{$solutionMatrix->{centerNodeSet}}, $origin);
932 }
933 }
934 }
935 else {
936 carp "vertexCenterFloydWarshall: Graph contains disconnected sub-graph / non-reachable node pairs. Center node set undefined.";
937 $graphMinMax = 0;
938 }
939 return($graphMinMax);
940
941 }
942
943 #############################################################################
944 #input / output file methods #
945 #############################################################################
946
947 { #CSV file format methods
948
949 use Text::CSV_XS;
950
951 sub getRowHref {
952 my $row = shift;
953 my $attribStr = $EMPTY_STRING;
954 foreach my $i (1 .. $#$row) {
955 $attribStr .= ', ' if $attribStr;
956 $attribStr .= $row->[$i];
957 }
958 return Graph::Dijkstra->hashifyAttribs( "($attribStr)" );
959 }
960
961 sub inputGraphfromCSV {
962 my ($self, $filename) = @_;
963
964 if (!ref($self)) {
965 $self = Graph::Dijkstra->new();
966 }
967
968 my $nodecount = 0;
969 my $edgecount = 0;
970
971 open(my $infile, '<:encoding(UTF-8)', $filename) or croak "could not open '$filename'";
972
973 print {$verboseOutfile} "inputGraphfromCSV: opened '$filename' for input\n" if $VERBOSE;
974
975 my $csv = Text::CSV_XS->new ({ binary => 1, auto_diag => 1 });
976 while (my $row = $csv->getline ($infile)) {
977 if (lc($row->[0]) eq 'graph') {
978 $self->graph( getRowHref( $row ) ) if $#$row;
979 }
980 elsif (lc($row->[0]) eq 'node') {
981 $self->node( getRowHref( $row ) );
982 $nodecount++;
983 }
984 elsif (lc($row->[0]) eq 'edge') {
985 $self->edge( getRowHref( $row ) );
986 $edgecount++;
987 }
988 }
989 close($infile);
990
991 carp "inputGraphfromCSV: no nodes read from '$filename'" if !$nodecount;
992 carp "inputGraphfromCSV: no edges read from '$filename'" if !$edgecount;
993
994 print {$verboseOutfile} "inputGraphfromCSV: found $nodecount nodes and $edgecount edges\n" if $VERBOSE;
995 return $self;
996 }
997
998 sub makeRow {
999 my $href = shift;
1000 my @rowdata = ();
1001 foreach my $attrib (sort keys %$href) {
1002 next if $href->{$attrib} eq $EMPTY_STRING;
1003 my $printVal = (looks_like_number($href->{$attrib})) ? $href->{$attrib} : "'$href->{$attrib}'";
1004 push(@rowdata, "$attrib=>$printVal");
1005 }
1006 return @rowdata;
1007 }
1008
1009 sub outputGraphtoCSV {
1010 my ($self, $filename) = @_;
1011
1012 open(my $outfile, '>:encoding(UTF-8)', $filename) or croak "could not open '$filename'";
1013
1014 print {$verboseOutfile} "outputGraphtoCSV: opened '$filename' for output\n" if $VERBOSE;
1015
1016 my $csv = Text::CSV_XS->new ({ binary => 1, auto_diag => 1 });
1017
1018 my $nodecount = 0;
1019 my $edgecount = 0;
1020 my $graphHref = $self->graph();
1021
1022 $csv->say( $outfile, ['comment', 'generated by Graph::Dijkstra on ' . localtime] );
1023 $csv->say( $outfile, ['graph', makeRow( $self->graph() ) ] );
1024
1025 my $graphDirected = $self->{edgedefault};
1026
1027 my %edges = ();
1028 foreach my $nodeID ($self->nodeIDsList()) {
1029
1030 $csv->say($outfile, ['node', makeRow( $self->node($nodeID) ) ]);
1031
1032 $nodecount++;
1033 # if ($self->_hasEdges($nodeID)) {
1034 foreach my $targetID ($self->adjacentNodes($nodeID)) {
1035 my $edgeDirected = $self->_getEdgeAttrib($nodeID, $targetID, 'directed');
1036 if ( ($edgeDirected eq 'undirected' and !exists($edges{$targetID}{$nodeID})) or $edgeDirected eq 'directed') {
1037 $edges{$nodeID}{$targetID}{weight} = $self->_getEdgeAttrib($nodeID, $targetID, 'weight');
1038 }
1039 }
1040 # }
1041 }
1042 foreach my $sourceID (keys %edges) {
1043 foreach my $targetID (keys %{$edges{$sourceID}}) {
1044
1045 $csv->say($outfile, ['edge', makeRow( $self->edge( {sourceID=>$sourceID, targetID=>$targetID} ) ) ]);
1046
1047 $edgecount++;
1048 }
1049 }
1050 close($outfile);
1051 print {$verboseOutfile} "outputGraphtoCSV: wrote $nodecount nodes and $edgecount edges to '$filename'\n" if $VERBOSE;
1052
1053 return $self;
1054 }
1055
1056 sub outputAPSPmatrixtoCSV {
1057 my ($either, $solutionMatrix, $filename, $labelSort) = @_;
1058
1059 $labelSort = '' if !defined($labelSort);
1060
1061 open(my $outfile, '>:encoding(UTF-8)', $filename) or croak "could not open '$filename'";
1062
1063 print {$verboseOutfile} "outputAPSPmatrixtoCSV: opened '$filename' for output\n" if $VERBOSE;
1064
1065 my $csv = Text::CSV_XS->new ({ binary => 1, auto_diag => 1 });
1066
1067 my @nodeList = (lc($labelSort) eq 'numeric') ? (sort {$a <=> $b} keys %{$solutionMatrix->{row}}) : (sort keys %{$solutionMatrix->{row}});
1068
1069 $csv->say($outfile, ['From/To', @nodeList ]);
1070 my $rowcount = 1;
1071
1072 foreach my $nodeID (@nodeList) {
1073 my @row = ();
1074 foreach my $destinationID (@nodeList) {
1075 push(@row, $solutionMatrix->{row}{$nodeID}{$destinationID});
1076 }
1077 $csv->say($outfile, [$nodeID, @row]);
1078 $rowcount++;
1079 }
1080 close($outfile);
1081 print {$verboseOutfile} "outputAPSPmatrixtoCSV: wrote $rowcount rows to '$filename'\n" if $VERBOSE;
1082 return $either;
1083
1084 }
1085
1086 } #CSV file format I/O methods
1087
1088 #############################################################################
1089 #JSON Graph Specification file format methods #
1090 #############################################################################
1091 {
1092
1093 use JSON;
1094
1095 sub inputGraphfromJSON {
1096 my ($self, $filename, $options) = @_;
1097
1098 if (!ref($self)) {
1099 $self = Graph::Dijkstra->new();
1100 }
1101
1102 my $json_text = $EMPTY_STRING;
1103 open(my $infile, '<:encoding(UTF-8)', $filename) or croak "could not open '$filename'";
1104
1105 print {$verboseOutfile} "inputGraphfromJSON: opened '$filename' for input\n" if $VERBOSE;
1106
1107 while (my $line = <$infile>) {
1108 $json_text .= $line;
1109 }
1110 close($infile);
1111
1112 my $graphHref = from_json( $json_text, {utf8 => 1} ) or croak "inputGraphfromJSON: invalid json text";
1113
1114 if (ref($graphHref) ne 'HASH') {
1115 croak "inputGraphfromJSON: invalid JSON text";
1116 }
1117
1118 if (exists($graphHref->{graphs})) {
1119 croak "inputGraphfromJSON: JSON \"multi graph\" type not supported";
1120 }
1121 if (!exists($graphHref->{graph}{edges})) {
1122 croak "inputGraphfromJSON: not a JSON graph specification or graph has no edges";
1123 }
1124 my $edgeWeightKey = (defined($options) and ref($options) eq 'HASH' and exists($options->{edgeWeightKey})) ? $options->{edgeWeightKey} : 'value';
1125
1126 my $graphDirected = 'undirected';
1127 if (exists($graphHref->{graph}{directed}) and $graphHref->{graph}{directed} ) {
1128 $graphDirected = 'directed';
1129 }
1130 print {$verboseOutfile} "inputGraphfromJSON: graph edge default is '$graphDirected'.\n" if $VERBOSE;
1131
1132 $self->graph( {label=>$graphHref->{graph}{label} } ) if exists($graphHref->{graph}{label});
1133 $self->graph( {creator=>$graphHref->{graph}{metadata}{creator} } ) if exists($graphHref->{graph}{metadata}{creator});
1134
1135 my $nodecount = 0;
1136 my $edgecount = 0;
1137 my $dupedgecount = 0;
1138
1139 foreach my $nodeHref (@{$graphHref->{graph}{nodes}}) {
1140 $nodecount++;
1141 $self->node( {id=>$nodeHref->{id}, label=>$nodeHref->{label} } );
1142 }
1143 foreach my $edgeHref (@{$graphHref->{graph}{edges}}) {
1144
1145 my $edgeDirected = $graphDirected;
1146 if (exists($edgeHref->{directed})) {
1147 $edgeDirected = ($edgeHref->{directed}) ? 'directed' : 'undirected';
1148 }
1149 my $edgeLabel = $edgeHref->{label} || $EMPTY_STRING;
1150 my $edgeID = $edgeHref->{metadata}{id} || $EMPTY_STRING;
1151 my $weight = $edgeHref->{metadata}{$edgeWeightKey} || 1;
1152
1153 $edgecount++;
1154 $dupedgecount++ if $self->edgeExists( { sourceID=>$edgeHref->{source}, targetID=>$edgeHref->{target} } );
1155 $self->edge( { sourceID=>$edgeHref->{source}, targetID=>$edgeHref->{target}, weight=>$weight, label=>$edgeLabel, directed=>$edgeDirected, id=>$edgeID } );
1156 }
1157
1158 carp "inputGraphfromJSON: no nodes read from '$filename'" if !$nodecount;
1159 carp "inputGraphfromJSON: no edges read from '$filename'" if !$edgecount;
1160
1161 print {$verboseOutfile} "inputGraphfromJSON: found $nodecount nodes and $edgecount edges\n" if $VERBOSE;
1162 print {$verboseOutfile} "inputGraphfromJSON: found $dupedgecount duplicate edges\n" if $dupedgecount and $VERBOSE;
1163
1164 return $self;
1165 }
1166
1167
1168 sub outputGraphtoJSON {
1169 my ($self, $filename, $options) = @_;
1170
1171 my $nodecount = 0;
1172 my $edgecount = 0;
1173
1174 my %graph = ();
1175 my $graphDirected = $self->{edgedefault};
1176
1177 $graph{graph}{directed} = ($graphDirected eq 'directed') ? JSON::true : JSON::false;
1178 @{$graph{graph}{nodes}} = ();
1179 @{$graph{graph}{edges}} = ();
1180
1181 $graph{graph}{metadata}{comment} = 'generated by Graph::Dijkstra on ' . localtime;
1182 $graph{graph}{label} = $self->{label} if $self->{label};
1183 $graph{graph}{metadata}{creator} = $self->{creator} if $self->{creator};
1184
1185 my $edgeWeightKey = (defined($options) and ref($options) eq 'HASH' and exists($options->{edgeWeightKey})) ? $options->{edgeWeightKey} : 'value';
1186
1187 my %edges = ();
1188 foreach my $nodeID ($self->nodeIDsList()) {
1189
1190 push(@{$graph{graph}{nodes}}, { id => $nodeID, label => $self->{nodes}{$nodeID}{label} } );
1191
1192 $nodecount++;
1193 # if ($self->_hasEdges($nodeID)) {
1194 foreach my $targetID ($self->adjacentNodes($nodeID)) {
1195
1196 my $edgeDirected = $self->_getEdgeAttrib($nodeID, $targetID, 'directed');
1197 if ( ($edgeDirected eq 'undirected' and !exists($edges{$targetID}{$nodeID})) or $edgeDirected eq 'directed') {
1198
1199 $edges{$nodeID}{$targetID} = 1;
1200 my %edgeData = ( source => $nodeID, target => $targetID, metadata => {$edgeWeightKey => $self->_getEdgeAttrib($nodeID, $targetID, 'weight') } );
1201
1202 $edgeData{label} = $self->{edges}{$nodeID}{$targetID}{label} if $self->{edges}{$nodeID}{$targetID}{label};
1203
1204 if ($edgeDirected ne $graphDirected) {
1205 $edgeData{directed} = ($edgeDirected eq 'directed') ? JSON::true : JSON::false;
1206 }
1207
1208 push( @{$graph{graph}{edges}}, \%edgeData );
1209 $edgecount++;
1210 }
1211 }
1212 # }
1213 }
1214
1215 my $json_text = to_json(\%graph, {utf8 => 1, pretty => 1});
1216
1217 open(my $outfile, '>:encoding(UTF-8)', $filename) or croak "could not open '$filename'";
1218
1219 print {$verboseOutfile} "outputGraphtoJSON: opened '$filename' for output\n" if $VERBOSE;
1220 print {$outfile} $json_text;
1221 close($outfile);
1222 print {$verboseOutfile} "outputGraphtoJSON: wrote $nodecount nodes and $edgecount edges to '$filename'\n" if $VERBOSE;
1223
1224 return $self;
1225 }
1226
1227 } #JSON Graph Specification file format methods
1228
1229 #############################################################################
1230 #GML file format methods #
1231 #############################################################################
1232 {
1233
1234 use Regexp::Common;
1235
1236 sub inputGraphfromGML { ## no critic (ProhibitExcessComplexity)
1237 my ($self, $filename) = @_;
1238
1239 if (!ref($self)) {
1240 $self = Graph::Dijkstra->new();
1241 }
1242 my $buffer = $EMPTY_STRING;
1243 my $linecount = 0;
1244 open(my $infile, '<:encoding(UTF-8)', $filename) or croak "could not open '$filename'";
1245
1246 print {$verboseOutfile} "inputGraphfromGML: opened '$filename' for input\n" if $VERBOSE;
1247
1248 while (my $line = <$infile>) {
1249 next if substr($line,0,1) eq '#';
1250 $buffer .= $line;
1251 $linecount++;
1252 }
1253 close($infile);
1254 print {$verboseOutfile} "inputGraphfromGML: read $linecount lines\n" if $VERBOSE;
1255
1256 if ($buffer !~ /graph\s+\[.+?(?:node|edge)\s+\[/ixs) {
1257 croak "file does not appear to be GML format";
1258 }
1259
1260 my $graphDirected = 'undirected';
1261
1262 if ($buffer =~ /graph\s+\[\s+directed\s+(\d)/ixs) {
1263 $graphDirected = ($1) ? 'directed' : 'undirected';
1264 }
1265
1266 print {$verboseOutfile} "inputGraphfromGML: graph edge default = '$graphDirected'\n" if $VERBOSE;
1267 $self->graph( { edgedefault=>$graphDirected } );
1268
1269 if ($buffer =~ /^\s*creator\s+\"([^\"]+)\"/i) {
1270 my $creator = $1;
1271 $self->graph( {creator=>$creator} );
1272 print {$verboseOutfile} "inputGraphfromGML: graph attribute creator set: $creator\n" if $VERBOSE;
1273
1274 }
1275
1276 my $has_graphics_elements = ($buffer =~ /graphics\s+\[/) ? 1 : 0;
1277 print {$verboseOutfile} "GML file contain graphics elements\n" if ($VERBOSE and $has_graphics_elements);
1278
1279 my $balancedRE = $RE{balanced}{-parens=>'[]'};
1280
1281
1282 my $nodecount = 0;
1283 my $edgecount = 0;
1284 my $dupedgecount = 0;
1285
1286 while ($buffer =~ /(node|edge)\s+$balancedRE/gixso) {
1287 my $type = lc($1);
1288 my $attribs = $2;
1289 #my $bufferPos = $-[0];
1290
1291 $attribs = substr($attribs, 1, -1);
1292
1293 $attribs =~ s/graphics\s+$balancedRE//xio if $has_graphics_elements and $type eq 'node';
1294
1295 my %keyvals = ();
1296 while ($attribs =~/(id|label|source|target|value)\s+(?|([0-9\.]+)|\"([^\"]+)\")/gixs) {
1297 my $attrib = lc($1);
1298 my $attribValue = $2;
1299 if ($type eq 'edge' and $attrib eq 'value' and !looks_like_number($attribValue)) {
1300 carp "non-numeric edge value '$attribValue'. Skipped.";
1301 next;
1302 }
1303 $keyvals{$attrib} = $attribValue;
1304 }
1305
1306 if ($type eq 'node') {
1307 $nodecount++;
1308 if (exists($keyvals{id})) {
1309 $self->{nodes}{$keyvals{id}}{label} = $keyvals{label} || $EMPTY_STRING;
1310 }
1311 else {
1312 croak "inputGraphfromGML: node: missing id problem -- matched attribs: '$attribs'";
1313 }
1314 }
1315 else {
1316 $edgecount++;
1317 my $edgeLabel = $keyvals{label} || $EMPTY_STRING;
1318 if (exists($keyvals{source}) and exists($keyvals{target}) and exists($keyvals{value}) and $keyvals{value} > 0) {
1319 $dupedgecount++ if $self->edgeExists( { sourceID=>$keyvals{source}, targetID=>$keyvals{target} } );
1320 $self->edge( { sourceID=>$keyvals{source}, targetID=>$keyvals{target}, weight=>$keyvals{value}, label=>$edgeLabel, directed=>$graphDirected } );
1321 }
1322 else {
1323 croak "inputGraphfromGML: edge: missing source, target, value, or value <= 0 problem -- matched attribs '$attribs'";
1324 }
1325 }
1326 }
1327
1328 carp "inputGraphfromGML: no nodes read from '$filename'" if !$nodecount;
1329 carp "inputGraphfromGML: no edges read from '$filename'" if !$edgecount;
1330
1331 print {$verboseOutfile} "inputGraphfromGML: found $nodecount nodes and $edgecount edges\n" if $VERBOSE;
1332 print {$verboseOutfile} "inputGraphfromGML: found $dupedgecount duplicate edges\n" if $dupedgecount and $VERBOSE;
1333
1334 return $self;
1335 }
1336
1337
1338 sub outputGraphtoGML {
1339 my ($self, $filename) = @_;
1340
1341 open(my $outfile, '>:encoding(UTF-8)', $filename) or croak "could not open '$filename' for output";
1342
1343 print {$verboseOutfile} "outputGraphtoGML: opened '$filename' for output\n" if $VERBOSE;
1344
1345 print {$outfile} "Creator \"$self->{creator}\"\n" if $self->{creator};
1346 my $graphDirected = ($self->{edgedefault} eq 'directed') ? 1 : 0;
1347 my $comment = '"Generated by Graph::Dijkstra on ' . localtime . '"';
1348 print {$outfile} "Graph [\nComment $comment\n\tDirected ", (($self->{edgedefault} eq 'directed') ? 1 : 0), "\n";
1349 $graphDirected = $self->{edgedefault};
1350
1351 my $nodecount = 0;
1352 my $edgecount = 0;
1353
1354 my %edges = ();
1355 foreach my $nodeID ($self->nodeIDsList()) {
1356 my $nodeIDprint = (looks_like_number($nodeID)) ? $nodeID : '"' . encode_entities($nodeID) . '"';
1357 my $nodeLabel = encode_entities($self->{nodes}{$nodeID}{label});
1358 print {$outfile} "\tnode [\n\t\tid $nodeIDprint\n\t\tlabel \"$nodeLabel\"\n\t]\n";
1359 $nodecount++;
1360 # if ($self->_hasEdges($nodeID)) {
1361 foreach my $targetID ($self->adjacentNodes($nodeID)) {
1362 croak "outputGraphtoGML: internal graph includes both directed and undirected edges. Not supported by GML format." if $self->_getEdgeAttrib($nodeID, $targetID, 'directed') ne $graphDirected;
1363 if ( ($graphDirected eq 'undirected' and !exists($edges{$targetID}{$nodeID})) or $graphDirected eq 'directed') {
1364 $edges{$nodeID}{$targetID}{weight} = $self->_getEdgeAttrib($nodeID, $targetID, 'weight');
1365 $edges{$nodeID}{$targetID}{label} = $self->_getEdgeAttrib($nodeID, $targetID, 'label');
1366 }
1367 }
1368 # }
1369 }
1370 foreach my $sourceID (keys %edges) {
1371 foreach my $targetID (keys %{$edges{$sourceID}}) {
1372 my $sourceIDprint = (looks_like_number($sourceID)) ? $sourceID : '"' . encode_entities($sourceID) . '"';
1373 my $targetIDprint = (looks_like_number($targetID)) ? $targetID : '"' . encode_entities($targetID) . '"';
1374 my $edgeLabelprint = ($edges{$sourceID}{$targetID}{label}) ? "\t\tlabel \"" . encode_entities($edges{$sourceID}{$targetID}{label}) . "\"\n" : $EMPTY_STRING;
1375 print {$outfile} "\tedge [\n\t\tsource $sourceIDprint\n\t\ttarget $targetIDprint\n$edgeLabelprint\t\tvalue $edges{$sourceID}{$targetID}{weight}\n\t]\n";
1376 $edgecount++;
1377 }
1378 }
1379 print {$outfile} "]\n";
1380 close($outfile);
1381 print {$verboseOutfile} "outputGraphtoGML: wrote $nodecount nodes and $edgecount edges to '$filename'\n" if $VERBOSE;
1382
1383 return $self;
1384 }
1385
1386 } #GML file format methods
1387
1388 #############################################################################
1389 #XML file format methods: GraphML and GEXF #
1390 #############################################################################
1391 {
1392
1393 use XML::LibXML;
1394
1395
1396 sub inputGraphfromGraphML { ## no critic (ProhibitExcessComplexity)
1397 my ($self, $filename, $options) = @_;
1398
1399 if (!ref($self)) {
1400 $self = Graph::Dijkstra->new();
1401 }
1402
1403 my $dom = XML::LibXML->load_xml(location => $filename);
1404
1405 print {$verboseOutfile} "inputGraphfromGraphML: input '$filename'\n" if $VERBOSE;
1406
1407 my $topNode = $dom->nonBlankChildNodes()->[0];
1408
1409 croak "inputGraphfromGraphML: not a GraphML format XML file" if lc($topNode->nodeName()) ne 'graphml';
1410
1411 my $nsURI = $topNode->getAttribute('xmlns') || '';
1412
1413 croak "inputGraphfromGraphML: not a GraphML format XML file" if (lc($nsURI) ne 'http://graphml.graphdrawing.org/xmlns');
1414
1415 my $xpc = XML::LibXML::XPathContext->new($dom);
1416 $xpc->registerNs('gml', $nsURI);
1417
1418 my $labelKey = $options->{nodeKeyLabelID} || $EMPTY_STRING;
1419 my $weightKey = $options->{edgeKeyValueID} || $EMPTY_STRING;
1420 my $edgeLabelKey = 'label';
1421
1422 my $defaultWeight = 1;
1423
1424 my $nodecount = 0;
1425 my $dupnodecount = 0;
1426 my $edgecount = 0;
1427 my $badedgecount = 0;
1428 my $dupedgecount = 0;
1429 my $graphDirected = $EMPTY_STRING;
1430
1431 if (my $graphNode = $xpc->findnodes('/gml:graphml/gml:graph')->[0] ) {
1432 $graphDirected = lc($graphNode->getAttribute('edgedefault'));
1433 print {$verboseOutfile} "inputGraphfromGraphML: graph edge default is '$graphDirected'.\n" if $VERBOSE;
1434 }
1435 else {
1436 croak "inputGraphfromGraphML: GraphML file has no <graph> element";
1437 }
1438
1439 if (my $graphNode = $xpc->findnodes('/gml:graphml/gml:graph[2]')->[0] ) {
1440 croak "inputGraphfromGraphML: file contains more than one graph. Not supported.";
1441 }
1442
1443 if (my $graphNode = $xpc->findnodes('/gml:graphml/gml:graph/gml:node/gml:graph')->[0] ) {
1444 croak "inputGraphfromGraphML: file contains one or more embedded graphs. Not supported.";
1445 }
1446
1447 if ($weightKey) {
1448 if (my $keyWeightNode = $xpc->findnodes("/gml:graphml/gml:key[\@for=\"edge\" and \@id=\"$weightKey\"]")->[0]) {
1449 print {$verboseOutfile} "inputGraphfromGraphML: found edgeKeyValueID '$weightKey' in GraphML key elements list\n" if $VERBOSE;
1450 if (my $defaultNode = $xpc->findnodes('.//gml:default[1]',$keyWeightNode)->[0]) {
1451 $defaultWeight = $defaultNode->textContent();
1452 }
1453 }
1454 else {
1455 carp "inputGraphfromGraphML: edgeKeyValueID '$weightKey' not found in GraphML key elements list";
1456 $weightKey = $EMPTY_STRING;
1457 }
1458 }
1459
1460 if (!$weightKey) {
1461 foreach my $keyEdge ($xpc->findnodes('/gml:graphml/gml:key[@for="edge"]') ) {
1462 my $attrName = $keyEdge->getAttribute('attr.name');
1463 if ($IS_GRAPHML_WEIGHT_ATTR{ lc($attrName) } ) {
1464 $weightKey = $keyEdge->getAttribute('id');
1465 print {$verboseOutfile} "inputGraphfromGraphML: found key attribute for edge attr.name='$attrName' id='$weightKey'\n" if $VERBOSE;
1466 if (my $defaultNode = $xpc->findnodes('.//gml:default[1]',$keyEdge)->[0]) {
1467 $defaultWeight = $defaultNode->textContent();
1468 }
1469 last;
1470 }
1471 }
1472
1473 if (!$weightKey) {
1474 croak "inputGraphfromGraphML: graph does not contain key attribute for edge weight/value/cost/distance '<key id=\"somevalue\" for=\"edge\" attr.name=\"weight|value|cost|distance\" />'. Not supported.";
1475 }
1476 }
1477
1478 if ($edgeLabelKey) {
1479 if (my $keyEdgeLabelNode = $xpc->findnodes("/gml:graphml/gml:key[\@for=\"edge\" and \@id=\"$edgeLabelKey\"]")->[0]) {
1480 print {$verboseOutfile} "inputGraphfromGraphML: found edgeKeyLabelID '$edgeLabelKey' in GraphML key elements list\n" if $VERBOSE;
1481 }
1482 else {
1483 # carp "inputGraphfromGraphML: edgeKeyLabelID '$edgeLabelKey' not found in GraphML key elements list";
1484 $edgeLabelKey = $EMPTY_STRING;
1485 }
1486 }
1487 my $edgeLabelXPATH = ($edgeLabelKey) ? ".//gml:data[\@key=\"$edgeLabelKey\"]" : $EMPTY_STRING;
1488
1489 my $labelXPATH = $EMPTY_STRING;
1490
1491 if ($labelKey) {
1492 if (my $keyNodeLabelNode = $xpc->findnodes("/gml:graphml/gml:key[\@for=\"node\" and \@id=\"$labelKey\"]")->[0]) {
1493 print {$verboseOutfile} "inputGraphfromGraphML: found nodeKeyLabelID '$labelKey' in GraphML key elements list\n" if $VERBOSE;
1494 }
1495 else {
1496 carp "inputGraphfromGraphML: nodeLabelValueID '$labelKey' not found in GraphML key elements list";
1497 $labelKey = $EMPTY_STRING;
1498 }
1499 }
1500
1501 if (!$labelKey) {
1502 foreach my $keyNode ($xpc->findnodes('/gml:graphml/gml:key[@for="node" and @attr.type="string"]')) {
1503 my $attrName = $keyNode->getAttribute('attr.name') || $EMPTY_STRING;
1504 if ($IS_GRAPHML_LABEL_ATTR{lc($attrName)}) {
1505 $labelKey = $keyNode->getAttribute('id');
1506 print {$verboseOutfile} "inputGraphfromGraphML: found key attribute for node 'label' attr.name='$attrName' id='$labelKey'\n" if $VERBOSE;
1507 last;
1508 }
1509 }
1510 }
1511
1512 if (!$labelKey) {
1513 carp "inputGraphfromGraphML: key node name / label / description attribute not found in graphml";
1514 }
1515 else {
1516 $labelXPATH = ".//gml:data[\@key=\"$labelKey\"]";
1517 }
1518
1519 if (my $keyGraphCreator = $xpc->findnodes("/gml:graphml/gml:key[\@for=\"graph\" and \@id=\"creator\"]")->[0]) {
1520 if (my $dataGraphCreator = $xpc->findnodes("/gml:graphml/gml:graph/gml:data[\@key=\"creator\"]")->[0]) {
1521 if (my $creator = $dataGraphCreator->textContent()) {
1522 $self->graph( {creator=>$creator} );
1523 }
1524 }
1525 }
1526 if (my $keyGraphLabel = $xpc->findnodes("/gml:graphml/gml:key[\@for=\"graph\" and \@id=\"graphlabel\"]")->[0]) {
1527 if (my $dataGraphLabel = $xpc->findnodes("/gml:graphml/gml:graph/gml:data[\@key=\"graphlabel\"]")->[0]) {
1528 if (my $label = $dataGraphLabel->textContent()) {
1529 $self->graph( {label=>$label} );
1530 }
1531 }
1532 }
1533
1534 foreach my $nodeElement ($xpc->findnodes('/gml:graphml/gml:graph/gml:node')) {
1535
1536 my $node = $nodeElement->nodeName();
1537 my $id = $nodeElement->getAttribute('id');
1538 my $label = $EMPTY_STRING;
1539 if ($labelXPATH and my $dataNameNode = $xpc->findnodes($labelXPATH,$nodeElement)->[0]) {
1540 $label = $dataNameNode->textContent();
1541 }
1542 $dupnodecount++ if $self->nodeExists($id);
1543 $self->node( {id=>$id,label=>$label } );
1544 $nodecount++;
1545 }
1546
1547 my $weightXPATH = ".//gml:data[\@key=\"$weightKey\"]";
1548
1549 foreach my $edgeElement ($xpc->findnodes('/gml:graphml/gml:graph/gml:edge')) {
1550
1551 my $edge = $edgeElement->nodeName();
1552 my $source = $edgeElement->getAttribute('source');
1553 my $target = $edgeElement->getAttribute('target');
1554 my $edgeID = ($edgeElement->hasAttribute('id')) ? $edgeElement->getAttribute('id') : $EMPTY_STRING;
1555 my $edgeDirected = ($edgeElement->hasAttribute('directed')) ? $edgeElement->getAttribute('directed') : $graphDirected;
1556 my $edgeLabel = '';
1557 if ($edgeLabelXPATH and my $dataEdgeLabelNode = $xpc->findnodes($edgeLabelXPATH,$edgeElement)->[0]) {
1558 $edgeLabel = $dataEdgeLabelNode->textContent();
1559 }
1560 my $weight = $defaultWeight;
1561 if (my $dataWeightNode = $xpc->findnodes($weightXPATH,$edgeElement)->[0]) {
1562 $weight = $dataWeightNode->textContent();
1563 }
1564 if ($weight) {
1565 $dupedgecount++ if $self->edgeExists( { sourceID=>$source, targetID=>$target } );
1566 my %edgeAttribs = (sourceID=>$source, targetID=>$target, weight=>$weight, directed=>$edgeDirected);
1567 $edgeAttribs{id} = $edgeID if $edgeID;
1568 $edgeAttribs{label} = $edgeLabel if $edgeLabel;
1569
1570 if (defined($self->edge( \%edgeAttribs ) )) {
1571 $edgecount++;
1572 }
1573 else {
1574 $badedgecount++;
1575 }
1576 }
1577 else {
1578 carp "inputGraphfromGraphML: edge $source $target has no weight. Not created."
1579 }
1580
1581 }
1582
1583 carp "inputGraphfromGraphML: no nodes read from '$filename'" if !$nodecount;
1584 carp "inputGraphfromGraphML: no edges read from '$filename'" if !$edgecount;
1585
1586 print {$verboseOutfile} "inputGraphfromGraphML: found $nodecount nodes and $edgecount edges\n" if $VERBOSE;
1587 print {$verboseOutfile} "inputGraphfromGraphML: found $dupnodecount duplicate nodes\n" if $dupnodecount and $VERBOSE;
1588 print {$verboseOutfile} "inputGraphfromGraphML: found $dupedgecount duplicate edges\n" if $dupedgecount and $VERBOSE;
1589 print {$verboseOutfile} "inputGraphfromGraphML: $badedgecount edges rejected (bad)\n" if $badedgecount and $VERBOSE;
1590
1591 return $self;
1592 }
1593
1594
1595 sub outputGraphtoGraphML {
1596 my ($self, $filename, $options) = @_;
1597
1598 my $nsURI = "http://graphml.graphdrawing.org/xmlns";
1599
1600 my $doc = XML::LibXML::Document->new('1.0','UTF-8');
1601 my $graphML = $doc->createElementNS( $EMPTY_STRING, 'graphml' );
1602 $doc->setDocumentElement( $graphML );
1603
1604 $graphML->setNamespace( $nsURI , $EMPTY_STRING, 1 );
1605
1606 {
1607 my $now_string = localtime;
1608 $graphML->appendChild($doc->createComment("Generated by Graph::Dijkstra on $now_string"));
1609 }
1610
1611 $graphML->setAttribute('xmlns:xsi','http://www.w3.org/2001/XMLSchema-instance');
1612 $graphML->setAttribute('xsi:schemaLocation','http://graphml.graphdrawing.org/xmlns http://graphml.graphdrawing.org/xmlns/1.0/graphml.xsd');
1613
1614
1615
1616 my $keyEdgeWeightID = $options->{keyEdgeWeightID} || 'weight';
1617 my $keyEdgeWeightAttrName = $options->{keyEdgeWeightAttrName} || 'weight';
1618 my $keyNodeLabelID = $options->{keyNodeLabelID} || 'name';
1619 my $keyNodeLabelAttrName = $options->{keyNodeLabelAttrName} || 'name';
1620 my $keyEdgeLabelID = $options->{keyEdgeLabelID} || 'label';
1621 my $keyEdgeLabelAttrName = $options->{keyEdgeLabelAttrName} || 'label';
1622
1623 my $keyNode = $graphML->addNewChild( $nsURI, 'key' );
1624
1625 $keyNode->setAttribute('for','node');
1626 $keyNode->setAttribute('id', $keyNodeLabelID );
1627 $keyNode->setAttribute('attr.name', $keyNodeLabelAttrName );
1628 $keyNode->setAttribute('attr.type', 'string' );
1629
1630 my $keyEdge = $graphML->addNewChild( $nsURI, 'key' );
1631 $keyEdge->setAttribute('for','edge');
1632 $keyEdge->setAttribute('id', $keyEdgeWeightID );
1633 $keyEdge->setAttribute('attr.name', $keyEdgeWeightAttrName );
1634 $keyEdge->setAttribute('attr.type', 'double' );
1635
1636 $keyEdge = $graphML->addNewChild( $nsURI, 'key' );
1637 $keyEdge->setAttribute('for','edge');
1638 $keyEdge->setAttribute('id', $keyEdgeLabelID );
1639 $keyEdge->setAttribute('attr.name', $keyEdgeLabelAttrName );
1640 $keyEdge->setAttribute('attr.type', 'string' );
1641
1642 if ($self->{creator}) {
1643 my $keyGraph = $graphML->addNewChild( $nsURI, 'key' );
1644 $keyGraph->setAttribute('for','graph');
1645 $keyGraph->setAttribute('id','creator');
1646 $keyGraph->setAttribute('attr.name','creator');
1647 $keyGraph->setAttribute('attr.type','string');
1648 }
1649 if ($self->{label}) {
1650 my $keyGraph = $graphML->addNewChild( $nsURI, 'key' );
1651 $keyGraph->setAttribute('for','graph');
1652 $keyGraph->setAttribute('id','graphlabel');
1653 $keyGraph->setAttribute('attr.name','label');
1654 $keyGraph->setAttribute('attr.type','string');
1655 }
1656
1657 my $graph = $graphML->addNewChild( $nsURI, 'graph' );
1658 $graph->setAttribute('id','G');
1659 $graph->setAttribute('edgedefault', $self->{edgedefault} );
1660 if ($self->{creator}) {
1661 my $dataNode = $graph->addNewChild( $nsURI, 'data');
1662 $dataNode->setAttribute('key', 'creator');
1663 $dataNode->appendTextNode( $self->{creator} );
1664 }
1665 if ($self->{label}) {
1666 my $dataNode = $graph->addNewChild( $nsURI, 'data');
1667 $dataNode->setAttribute('key', 'label');
1668 $dataNode->appendTextNode( $self->{label} );
1669 }
1670
1671 my $nodecount = 0;
1672 my $edgecount = 0;
1673
1674 my %edges = ();
1675 foreach my $nodeID ($self->nodeIDsList()) {
1676
1677 my $nodeNode = $graph->addNewChild( $nsURI, 'node' );
1678 $nodeNode->setAttribute('id', $nodeID);
1679 my $dataNode = $nodeNode->addNewChild( $nsURI, 'data');
1680 $dataNode->setAttribute('key', $keyNodeLabelID);
1681 $dataNode->appendTextNode( $self->{nodes}{$nodeID}{label} );
1682
1683 $nodecount++;
1684 # if ($self->_hasEdges($nodeID)) {
1685 foreach my $targetID ($self->adjacentNodes($nodeID)) {
1686 my $directed = $self->_getEdgeAttrib($nodeID, $targetID, 'directed');
1687 if ( ($directed eq 'undirected' and !exists($edges{$targetID}{$nodeID})) or $directed eq 'directed') {
1688 $edges{$nodeID}{$targetID}{weight} = $self->_getEdgeAttrib($nodeID, $targetID, 'weight');
1689 $edges{$nodeID}{$targetID}{id} = $self->_getEdgeAttrib($nodeID, $targetID, 'id');
1690 $edges{$nodeID}{$targetID}{directed} = $directed;
1691 $edges{$nodeID}{$targetID}{label} = $self->_getEdgeAttrib($nodeID, $targetID, 'label');
1692 }
1693 }
1694 # }
1695 }
1696 foreach my $sourceID (keys %edges) {
1697 foreach my $targetID (keys %{$edges{$sourceID}}) {
1698
1699 $edgecount++;
1700 my $edgeNode = $graph->addNewChild( $nsURI, 'edge');
1701 $edgeNode->setAttribute('id', ($edges{$sourceID}{$targetID}{id} ne $EMPTY_STRING) ? $edges{$sourceID}{$targetID}{id} : $edgecount);
1702 $edgeNode->setAttribute('source', $sourceID );
1703 $edgeNode->setAttribute('target', $targetID );
1704 $edgeNode->setAttribute('directed', $edges{$sourceID}{$targetID}{directed} ) if $edges{$sourceID}{$targetID}{directed} ne $self->{edgedefault};
1705 my $dataNode = $edgeNode->addNewChild( $nsURI, 'data');
1706 $dataNode->setAttribute('key', $keyEdgeWeightID );
1707 $dataNode->appendTextNode( $edges{$sourceID}{$targetID}{weight} );
1708
1709 if ( $edges{$sourceID}{$targetID}{label} ) {
1710 $dataNode = $edgeNode->addNewChild( $nsURI, 'data');
1711 $dataNode->setAttribute('key', $keyEdgeLabelID );
1712 $dataNode->appendTextNode( $edges{$sourceID}{$targetID}{label} );
1713 }
1714 }
1715 }
1716
1717 my $state = $doc->toFile($filename,2);
1718 croak "could not output internal grap to '$filename'" if !$state;
1719
1720 print {$verboseOutfile} "outputGraphtoGraphML: wrote $nodecount nodes and $edgecount edges to '$filename'\n" if $VERBOSE;
1721 return $self;
1722 }
1723
1724
1725 sub inputGraphfromGEXF { ## no critic (ProhibitExcessComplexity)
1726 my ($self, $filename) = @_;
1727
1728 if (!ref($self)) {
1729 $self = Graph::Dijkstra->new();
1730 }
1731
1732 my $dom = XML::LibXML->load_xml(location => $filename);
1733
1734 print {$verboseOutfile} "inputGraphfromGEXF: input '$filename'\n" if $VERBOSE;
1735
1736 my $topNode = $dom->nonBlankChildNodes()->[0];
1737
1738 croak "inputGraphfromGEXF: not a GEXF format XML file" if lc($topNode->nodeName()) ne 'gexf';
1739
1740 my $nsURI = $topNode->getAttribute('xmlns') || '';
1741
1742 croak "inputGraphfromGEXF: not a GEXF draft specification 1.1 or 1.2 format XML file" if ( $nsURI !~ /^http:\/\/www.gexf.net\/1\.[1-2]draft$/i );
1743
1744 my $gexfVersion = $topNode->getAttribute('version') || ''; #don't do anything with the GEXF version string
1745
1746 my $xpc = XML::LibXML::XPathContext->new($dom);
1747 $xpc->registerNs('gexf', $nsURI);
1748
1749 my $nodecount = 0;
1750 my $edgecount = 0;
1751 my $dupedgecount = 0;
1752 my $defaultWeight = 1;
1753 my $graphDirected = 'undirected';
1754 my $attvalueWeightCount = 0;
1755 my $weightXPATH = ".//gexf:attvalues/gexf:attvalue[\@for=\"weight\"]";
1756
1757 if (my $graphNode = $xpc->findnodes('/gexf:gexf/gexf:graph')->[0] ) {
1758 $graphDirected = ($graphNode->hasAttribute('defaultedgetype')) ? lc($graphNode->getAttribute('defaultedgetype')) : 'undirected';
1759 croak "inputGraphfromGEXF: graph defaultedgetype is 'mutual'. Not supported." if $graphDirected eq 'mutual';
1760 $self->graph( {edgedefault=>$graphDirected} );
1761 print {$verboseOutfile} "inputGraphfromGEXF: graph edgedefault is '$graphDirected'.\n" if $VERBOSE;
1762 my $mode = $graphNode->getAttribute('mode') || $EMPTY_STRING;
1763 carp "inputGraphfromGEXF: graph mode is 'dynamic'. Ignored." if lc($mode) eq 'dynamic';
1764 }
1765 else {
1766 croak "inputGraphfromGEXF: GEXF file has no <graph> element";
1767 }
1768
1769 if (my $graphNode = $xpc->findnodes('/gexf:gexf/gexf:graph[2]')->[0] ) {
1770 croak "inputGraphfromGEXF: file contains more than one graph. Not supported.";
1771 }
1772
1773 if (my $heirarchyNode = $xpc->findnodes('/gexf:gexf/gexf:graph/gexf:nodes/gexf:node/gexf:nodes')->[0] ) {
1774 croak "inputGraphfromGEXF: file contains heirarchical nodes. Not supported.";
1775 }
1776 if (my $parentsNode = $xpc->findnodes('/gexf:gexf/gexf:graph/gexf:nodes/gexf:node/gexf:parents')->[0] ) {
1777 croak "inputGraphfromGEXF: file contains parent nodes. Not supported.";
1778 }
1779
1780 if (my $metaNode = $xpc->findnodes('/gexf:gexf/gexf:meta/gexf:creator')->[0] ) {
1781 if (my $creator = $metaNode->textContent()) {
1782 $self->graph( { creator=>$creator } );
1783 print {$verboseOutfile} "inputGraphfromGEXF: set graph attribute creator: $creator\n" if $VERBOSE;
1784 }
1785 }
1786
1787 if (my $metaNode = $xpc->findnodes('/gexf:gexf/gexf:meta/gexf:description')->[0] ) {
1788 if (my $label = $metaNode->textContent()) {
1789 $self->graph( { label=>$label } );
1790 print {$verboseOutfile} "inputGraphfromGEXF: set graph attribute label (from meta attribute description): $label\n" if $VERBOSE;
1791 }
1792 }
1793
1794
1795 foreach my $nodeElement ($xpc->findnodes('/gexf:gexf/gexf:graph/gexf:nodes/gexf:node')) {
1796
1797 #my $node = $nodeElement->nodeName();
1798 my $id = $nodeElement->getAttribute('id');
1799 my $label = $nodeElement->getAttribute('label') || $EMPTY_STRING;
1800 $self->node( {id=>$id, label=>$label} );
1801 $nodecount++;
1802 }
1803
1804 foreach my $edgeElement ($xpc->findnodes('/gexf:gexf/gexf:graph/gexf:edges/gexf:edge')) {
1805
1806 #my $edge = $edgeElement->nodeName();
1807 my $source = $edgeElement->getAttribute('source'); #source, target, and id are required attributes
1808 my $target = $edgeElement->getAttribute('target');
1809 my $edgeID = $edgeElement->getAttribute('id');
1810 my $weight = $defaultWeight;
1811 if ($edgeElement->hasAttribute('weight')) {
1812 $weight = $edgeElement->getAttribute('weight');
1813 }
1814 elsif ($edgeElement->hasChildNodes() and my $dataWeightNode = $xpc->findnodes($weightXPATH,$edgeElement)->[0]) {
1815 $weight = $dataWeightNode->getAttribute('value');
1816 $attvalueWeightCount++;
1817 }
1818 my $label = ($edgeElement->hasAttribute('label')) ? $edgeElement->getAttribute('label') : $EMPTY_STRING;
1819 my $edgeDirected = ($edgeElement->hasAttribute('type')) ? $edgeElement->getAttribute('type') : $graphDirected;
1820 if ($weight) {
1821 $dupedgecount++ if $self->edgeExists( { sourceID=>$source, targetID=>$target } );
1822 $self->edge( { sourceID=>$source, targetID=>$target, weight=>$weight, directed=>$edgeDirected, label=>$label, id=>$edgeID } );
1823 $edgecount++;
1824 }
1825 else {
1826 carp "inputGraphfromGEXF: edge $source $target has no weight. Not created."
1827 }
1828
1829 }
1830
1831 carp "inputGraphfromGEXF: no nodes read from '$filename'" if !$nodecount;
1832 carp "inputGraphfromGEXF: no edges read from '$filename'" if !$edgecount;
1833
1834 print {$verboseOutfile} "inputGraphfromGEXF: found $nodecount nodes and $edgecount edges\n" if $VERBOSE;
1835 print {$verboseOutfile} "inputGraphfromGEXF: found $dupedgecount duplicate edges\n" if $dupedgecount and $VERBOSE;
1836 print {$verboseOutfile} "inputGraphfromGEXF: input edge weight from attvalue element for $attvalueWeightCount edges\n" if $attvalueWeightCount and $VERBOSE;
1837
1838 return $self;
1839 }
1840
1841
1842 sub outputGraphtoGEXF {
1843 my ($self, $filename) = @_;
1844
1845 my $nsURI = 'http://www.gexf.net/1.2draft';
1846
1847 my $doc = XML::LibXML::Document->new('1.0','UTF-8');
1848 my $GEXF = $doc->createElementNS( $EMPTY_STRING, 'gexf' );
1849 $doc->setDocumentElement( $GEXF );
1850
1851 $GEXF->setNamespace( $nsURI , $EMPTY_STRING, 1 );
1852
1853 $GEXF->setAttribute('xmlns:xsi','http://www.w3.org/2001/XMLSchema-instance');
1854 $GEXF->setAttribute('xsi:schemaLocation','http://www.gexf.net/1.2draft http://www.gexf.net/1.2draft/gexf.xsd');
1855 $GEXF->setAttribute('version','1.2');
1856
1857 {
1858 my $now_string = localtime;
1859 $GEXF->appendChild($doc->createComment("Generated by Graph::Dijkstra on $now_string"));
1860 }
1861 {
1862 my (undef, undef, undef, $mday, $month, $year, undef, undef, undef) = localtime;
1863 my $ISODATE = sprintf "%4d-%02d-%02d", $year+1900, $month+1, $mday;
1864 my $meta = $GEXF->addNewChild( $nsURI, 'meta');
1865 $meta->setAttribute('lastmodifieddate', $ISODATE);
1866 if ($self->{creator}) {
1867 my $creatorNode = $meta->addNewChild( $nsURI, 'creator');
1868 $creatorNode->appendTextNode( $self->{creator} );
1869 }
1870 if ($self->{label}) {
1871 my $descriptionNode = $meta->addNewChild( $nsURI, 'description');
1872 $descriptionNode->appendTextNode( $self->{label} );
1873 }
1874 }
1875
1876 my $graph = $GEXF->addNewChild( $nsURI, 'graph' );
1877 $graph->setAttribute('mode','static');
1878 $graph->setAttribute('defaultedgetype', $self->{edgedefault} );
1879 my $nodesElement = $graph->addNewChild( $nsURI, 'nodes' );
1880
1881 my $nodecount = 0;
1882 my $edgecount = 0;
1883
1884 my %edges = ();
1885 foreach my $nodeID ($self->nodeIDsList()) {
1886
1887 my $nodeNode = $nodesElement->addNewChild( $nsURI, 'node' );
1888 $nodeNode->setAttribute('id', $nodeID);
1889 $nodeNode->setAttribute('label', $self->{nodes}{$nodeID}{label} );
1890
1891 $nodecount++;
1892 # if ($self->_hasEdges($nodeID)) {
1893 foreach my $targetID ($self->adjacentNodes($nodeID)) {
1894 my $directed = $self->_getEdgeAttrib($nodeID, $targetID, 'directed');
1895 if ( ($directed eq 'undirected' and !exists($edges{$targetID}{$nodeID})) or $directed eq 'directed') {
1896 $edges{$nodeID}{$targetID}{weight} = $self->_getEdgeAttrib($nodeID, $targetID, 'weight');
1897 $edges{$nodeID}{$targetID}{id} = $self->_getEdgeAttrib($nodeID, $targetID, 'id');
1898 $edges{$nodeID}{$targetID}{directed} = $directed;
1899 $edges{$nodeID}{$targetID}{label} = $self->_getEdgeAttrib($nodeID, $targetID, 'label');
1900 }
1901 }
1902 # }
1903 }
1904
1905 my $edgesElement = $graph->addNewChild( $nsURI, 'edges' );
1906
1907 foreach my $sourceID (keys %edges) {
1908 foreach my $targetID (keys %{$edges{$sourceID}}) {
1909
1910 $edgecount++;
1911 my $edgeNode = $edgesElement->addNewChild( $nsURI, 'edge');
1912 $edgeNode->setAttribute('id', ($edges{$sourceID}{$targetID}{id} ne '') ? $edges{$sourceID}{$targetID}{id} : $edgecount);
1913 $edgeNode->setAttribute('source', $sourceID );
1914 $edgeNode->setAttribute('target', $targetID );
1915 $edgeNode->setAttribute('weight', $edges{$sourceID}{$targetID}{weight} );
1916 $edgeNode->setAttribute('directed', $edges{$sourceID}{$targetID}{directed} ) if $edges{$sourceID}{$targetID}{directed} ne $self->{edgedefault};
1917 $edgeNode->setAttribute('label', $edges{$sourceID}{$targetID}{label} ) if $edges{$sourceID}{$targetID}{label};
1918
1919 }
1920 }
1921 my $state = $doc->toFile($filename,2);
1922 croak "could not output internal grap to '$filename'" if !$state;
1923
1924 print {$verboseOutfile} "outputGraphtoGEXF: wrote $nodecount nodes and $edgecount edges to '$filename'\n" if $VERBOSE;
1925 return $self;
1926 }
1927
1928 sub validateGraphMLxml {
1929 my ($either, $filename) = @_;
1930
1931 Readonly my $GraphML_URL => 'http://graphml.graphdrawing.org/xmlns/1.1/graphml.xsd';
1932
1933 my $GraphMLschema;
1934
1935 eval {
1936 $GraphMLschema = XML::LibXML::Schema->new( location => $GraphML_URL );
1937 print {$verboseOutfile} "validateGraphMLxml: loaded GraphML schema\n" if $VERBOSE;
1938 };
1939 if ($@) {
1940 print {$verboseOutfile} "\n$@\n" if $VERBOSE;
1941 carp "validateGraphMLxml: GraphML xml schema URL not accessible: $GraphML_URL";
1942 return(0,'GraphML xml schema URL not accessible');
1943 }
1944
1945 my $dom = XML::LibXML->load_xml(location => $filename);
1946 print {$verboseOutfile} "validateGraphMLxml: loaded '$filename'\n" if $VERBOSE;
1947
1948 eval { $GraphMLschema->validate( $dom ); };
1949
1950 if ($@) {
1951 print {$verboseOutfile} "validateGraphMLxml: validate failed\n$@\n" if $VERBOSE;
1952 return(0,$@);
1953 }
1954 else {
1955 print {$verboseOutfile} "validateGraphMLxml: validated\n" if $VERBOSE;
1956 return(1,$EMPTY_STRING);
1957 }
1958
1959 }
1960
1961 sub validateGEXFxml {
1962 my ($either, $filename) = @_;
1963
1964 Readonly my $GEXF_URL => 'http://www.gexf.net/1.2draft/gexf.xsd';
1965 my $GEXFschema;
1966
1967 eval {
1968 $GEXFschema = XML::LibXML::Schema->new( location => $GEXF_URL );
1969 print {$verboseOutfile} "validateGEXFxml: loaded GEXF schema\n" if $VERBOSE;
1970 };
1971 if ($@) {
1972 print {$verboseOutfile} "\n$@\n" if $VERBOSE;
1973 carp "validateGEXFxml: GEXF xml schema URL not accessible: $GEXF_URL";
1974 return(0,'GEXF xml schema URL not accessible');
1975 }
1976
1977 my $dom = XML::LibXML->load_xml(location => $filename);
1978 print {$verboseOutfile} "validateGEXFxml: loaded '$filename'\n" if $VERBOSE;
1979
1980 eval { $GEXFschema->validate( $dom ); };
1981
1982 if ($@) {
1983 print {$verboseOutfile} "validateGEXFxml: validate failed\n$@\n" if $VERBOSE;
1984 return(0,$@);
1985 }
1986 else {
1987 print {$verboseOutfile} "validateGEXFxml: validated\n" if $VERBOSE;
1988 return(1,$EMPTY_STRING);
1989 }
1990
1991 }
1992
1993
1994 } #XML file format methods
1995
1996 #############################################################################
1997 #NET (Pajek) file format methods #
1998 #############################################################################
1999 {
2000 sub inputGraphfromNET {
2001 my ($self, $filename) = @_;
2002
2003 use Regexp::Common qw /delimited/;
2004
2005 if (!ref($self)) {
2006 $self = Graph::Dijkstra->new();
2007 }
2008
2009 open(my $infile, '<:encoding(UTF-8)', $filename) or croak "inputGraphfromNET: could not open '$filename' for input";
2010
2011 print {$verboseOutfile} "inputGraphfromNET: opened '$filename' for input\n" if $VERBOSE;
2012
2013 my $nodes = 0;
2014 while (my $line = <$infile>) {
2015 if ($line =~ /^\*vertices\s+(\d+)/ix) {
2016 $nodes = $1;
2017 last;
2018 }
2019 }
2020 croak "inputGraphfromNET: vertices element not found" if !$nodes;
2021 print {$verboseOutfile} "inputGraphfromNET: vertices = $nodes\n" if $VERBOSE;
2022
2023 my $nodecount = 0;
2024 my $edgecount = 0;
2025 my $dupedgecount = 0;
2026
2027 my $quotedRE = $RE{delimited}{-delim=>'"'};
2028 #print "quotedRE = '$quotedRE'\n";
2029
2030 my $nextSection = '';
2031 foreach my $i (1 .. $nodes) {
2032 my $line = '';
2033 while(1) {
2034 $line = <$infile>;
2035 croak "inputGraphfromNET: unexpected EOF in vertices section" if !defined($line);
2036 chomp $line;
2037 last if substr($line,0,1) ne '%';
2038 }
2039
2040 if (substr($line,0,1) eq '*') {
2041 $nextSection = lc($line);
2042 last;
2043 }
2044
2045 if ($line =~ /^\s*(\d+)\s+($quotedRE)/ix) {
2046 my $id = $1;
2047 my $label = $2;
2048 $label = substr($label,1,-1); #strip quotes
2049 $self->node( {id=>$id, label=>$label} );
2050 $nodecount++;
2051 }
2052 }
2053 if ($nextSection and $nodecount == 0) {
2054 print {$verboseOutfile} "inputGraphfromNET: empty vertices section (no node labels). Generating node ID values 1 .. $nodes\n" if $VERBOSE;
2055 foreach my $i (1 .. $nodes) {
2056 $self->node( {id=>$i, label=>$EMPTY_STRING} );
2057 $nodecount++;
2058 }
2059 }
2060 elsif ($nodes != $nodecount) {
2061 die "inputGraphfromNET: internal logic error: # vertices ($nodes) != # read nodes ($nodecount)";
2062 }
2063
2064 if ($nextSection =~ /^(\*\w+)/) {
2065 $nextSection = $1;
2066 }
2067 elsif ($nextSection) {
2068 die "inputGraphfromNET: internal logic error. Did not recognize next section '$nextSection' in NET (pajek) file.";
2069 }
2070
2071 croak "inputGraphfromNET: input file contains *arclist section. Not supported." if $nextSection eq '*arclist';
2072 croak "inputGraphfromNET: input file contains *edgelist section. Not supported." if $nextSection eq '*edgelist';
2073
2074 print {$verboseOutfile} "inputGraphfromNET: next section is '$nextSection'\n" if $nextSection and $VERBOSE;
2075
2076 while (1) {
2077
2078 if ($nextSection ne '*arcs' and $nextSection ne '*edges') {
2079 $nextSection = '';
2080 while (my $line = <$infile>) {
2081 if ($line =~ /^(\*(?:edges|arcs))/i) {
2082 $nextSection = lc($1);
2083 last;
2084 }
2085 }
2086 last if !$nextSection;
2087 }
2088
2089 my $edgeDirected = ($nextSection eq '*edges') ? 'undirected' : 'directed';
2090 $nextSection = '';
2091
2092 while (my $line = <$infile>) {
2093 chomp $line;
2094 next if !$line;
2095 next if substr($line,0,1) eq '%';
2096 if ($line =~ /^(\*\w+)/) {
2097 $nextSection = lc($1);
2098 last;
2099 }
2100 if ($line =~ /^\s+(\d+)\s+(\d+)\s+([0-9\.]+)/s) {
2101 my $sourceID = $1;
2102 my $targetID = $2;
2103 my $weight = $3;
2104 $dupedgecount++ if $self->edgeExists( { sourceID=>$sourceID, targetID=>$targetID } );
2105 $self->edge( { sourceID=>$sourceID, targetID=>$targetID, weight=>$weight, directed=>$edgeDirected } );
2106 $edgecount++;
2107 }
2108 else {
2109 chomp $line;
2110 carp "inputGraphfromNET: unrecognized input line (maybe edge with no weight?) =>$line<=";
2111 last;
2112 }
2113 }
2114 last if !$nextSection;
2115 }
2116 close($infile);
2117
2118 carp "inputGraphfromNET: no nodes read from '$filename'" if !$nodecount;
2119 carp "inputGraphfromNET: no edges read from '$filename'" if !$edgecount;
2120
2121 print {$verboseOutfile} "inputGraphfromNET: found $nodecount nodes and $edgecount edges\n" if $VERBOSE;
2122 print {$verboseOutfile} "inputGraphfromNET: found $dupedgecount duplicate edges\n" if $dupedgecount and $VERBOSE;
2123
2124 return $self;
2125 }
2126
2127 sub outputGraphtoNET {
2128 my ($self, $filename) = @_;
2129
2130 open(my $outfile, '>:encoding(UTF-8)', $filename) or croak "outputGraphtoNET: could not open '$filename' for output";
2131
2132 print {$verboseOutfile} "outputGraphtoNET: opened '$filename' for output\n" if $VERBOSE;
2133
2134 my %edges = ();
2135 my $nodecount = 0;
2136 my $edgecount = 0;
2137 my $useConsecutiveNumericIDs = 1;
2138 my $hasNonBlankLabels = 0;
2139 my $highestNumericID = 0;
2140 my $lowestNumericID = $PINF;
2141
2142 my @nodeList = $self->nodeList();
2143
2144 foreach my $nodeHref (@nodeList) {
2145 $nodecount++;
2146 my $nodeID = $nodeHref->{id};
2147 my $label = $nodeHref->{label};
2148 if ($useConsecutiveNumericIDs) {
2149 if ($nodeID =~ /^\d+$/) {
2150 $highestNumericID = $nodeID if $nodeID > $highestNumericID;
2151 $lowestNumericID = $nodeID if $nodeID < $lowestNumericID;
2152 }
2153 else {
2154 $useConsecutiveNumericIDs = 0;
2155 }
2156 }
2157
2158 $hasNonBlankLabels = 1 if (!$hasNonBlankLabels and $label ne $EMPTY_STRING);
2159 }
2160 print {$verboseOutfile} "outputGraphtoNET: internal graph has non-blank labels.\n" if $VERBOSE and $hasNonBlankLabels;
2161
2162 if ($useConsecutiveNumericIDs) {
2163 if ($highestNumericID != $nodecount or $lowestNumericID != 1) {
2164 $useConsecutiveNumericIDs = 0;
2165 }
2166 }
2167
2168
2169 {
2170 my $now_string = localtime;
2171 print {$outfile} "% Generated by Graph::Dijkstra on $now_string\n";
2172 }
2173
2174 print {$outfile} "*Vertices $nodecount\n";
2175
2176 my $hasArcs = 0;
2177 my $hasEdges = 0;
2178
2179 if ($useConsecutiveNumericIDs) {
2180
2181 print {$verboseOutfile} "outputGraphtoNET: internal graph has consecutive numeric IDs.\n" if $VERBOSE;
2182 $nodecount = 0;
2183 foreach my $nodeHref (sort { $a->{id} <=> $b->{id} } @nodeList) {
2184
2185 $nodecount++;
2186
2187 my $nodeID = $nodeHref->{id};
2188 my $label = $nodeHref->{label};
2189 croak "outputGraphtoNET: node IDs are not consecutive numeric integers starting at 1" if ($nodeID != $nodecount);
2190
2191 if ($hasNonBlankLabels) {
2192 printf {$outfile} "%7d \"%s\"\n", $nodeID, $label;
2193 }
2194
2195 # if ($self->_hasEdges($nodeID)) {
2196 foreach my $targetID ($self->adjacentNodes($nodeID)) {
2197 my $edgeDirected = $self->_getEdgeAttrib($nodeID, $targetID, 'directed');
2198 if ( ($edgeDirected eq 'undirected' and !exists($edges{$targetID}{$nodeID}) ) or $edgeDirected eq 'directed') {
2199 $edges{$nodeID}{$targetID}{weight} = $self->_getEdgeAttrib($nodeID, $targetID, 'weight');
2200 $edges{$nodeID}{$targetID}{directed} = $edgeDirected;
2201 if ($edgeDirected eq 'directed') {
2202 $hasArcs++;
2203 }
2204 else {
2205 $hasEdges++;
2206 }
2207 }
2208 }
2209 # }
2210 }
2211 }
2212 else {
2213 if ($VERBOSE) {
2214 print {$verboseOutfile} "outputGraphtoNET: internal graph node ID values are not consecutive integer values starting at 1.\n";
2215 print {$verboseOutfile} "outputGraphtoNET: internal graph node ID values not perserved in output\n";
2216 print {$verboseOutfile} "outputGraphtoNET: generating consecutive integer ID values in output\n";
2217 }
2218
2219 my %nodeIDtoNumericID = ();
2220 foreach my $i (0 .. $#nodeList) {
2221 $nodeIDtoNumericID{ $nodeList[$i]->{id} } = $i+1;
2222 }
2223
2224 foreach my $nodeID (sort {$nodeIDtoNumericID{$a} <=> $nodeIDtoNumericID{$b}} keys %nodeIDtoNumericID) {
2225 if ($hasNonBlankLabels) {
2226 printf {$outfile} "%7d \"%s\"\n", $nodeIDtoNumericID{$nodeID}, $self->{nodes}{$nodeID}{label};
2227 }
2228
2229 # if ($self->_hasEdges($nodeID)) {
2230 my $numericNodeID = $nodeIDtoNumericID{$nodeID};
2231 foreach my $targetID ($self->adjacentNodes($nodeID)) {
2232 my $edgeDirected = $self->_getEdgeAttrib($nodeID, $targetID, 'directed');
2233 my $numericTargetID = $nodeIDtoNumericID{$targetID};
2234 if ( ($edgeDirected eq 'undirected' and !exists($edges{$numericTargetID}{$numericNodeID})) or $edgeDirected eq 'directed') {
2235 $edges{$numericNodeID}{$numericTargetID}{weight} = $self->_getEdgeAttrib($nodeID, $targetID, 'weight');
2236 $edges{$numericNodeID}{$numericTargetID}{directed} = $edgeDirected;
2237 if ($edgeDirected eq 'directed') {
2238 $hasArcs++;
2239 }
2240 else {
2241 $hasEdges++;
2242 }
2243 }
2244 }
2245 # }
2246 }
2247 }
2248
2249 if ($hasEdges) {
2250 print {$outfile} "*Edges\n";
2251 foreach my $sourceID (sort {$a <=> $b} keys %edges) {
2252 foreach my $targetID (sort {$a <=> $b} keys %{$edges{$sourceID}} ) {
2253 next if $edges{$sourceID}{$targetID}{directed} eq 'directed';
2254 printf {$outfile} "%7d %7d %10s\n", $sourceID, $targetID, "$edges{$sourceID}{$targetID}{weight}";
2255 $edgecount++;
2256 }
2257 }
2258 }
2259 if ($hasArcs) {
2260 print {$outfile} "*Arcs\n";
2261 foreach my $sourceID (sort {$a <=> $b} keys %edges) {
2262 foreach my $targetID (sort {$a <=> $b} keys %{$edges{$sourceID}} ) {
2263 next if $edges{$sourceID}{$targetID}{directed} eq 'undirected';
2264 printf {$outfile} "%7d %7d %10s\n", $sourceID, $targetID, "$edges{$sourceID}{$targetID}{weight}";
2265 $edgecount++;
2266 }
2267 }
2268 }
2269 close($outfile);
2270
2271 print {$verboseOutfile} "outputGraphtoNET: wrote $nodecount nodes and $edgecount edges to '$filename'\n" if $VERBOSE;
2272 return $self;
2273 }
2274
2275
2276 } #NET (Pagek) file format methods
2277
2278 1;
2279
2280 __END__
↑ Summary