-
Notifications
You must be signed in to change notification settings - Fork 15
/
graph.lisp
1490 lines (1295 loc) · 56.5 KB
/
graph.lisp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
;;; graph.lisp --- because its easier to write than to learn such a library
;; Copyright (C) Eric Schulte and Thomas Dye 2012-2013
;; Licensed under the Gnu Public License Version 3 or later
;;; Commentary
;; Graphs are composed of two hash tables, nodes and edges. The node
;; hash is keyed by node and holds the edges containing that node,
;; while the edge hash is keyed by edge containing any optional edge
;; value.
;;
;; Nodes Edges
;; ------- -------
;; +----Graph G-----+ key | value key | value
;; | 3 2 | -----+--------- -------+----------
;; | a---b---c g | a | (a b) (a b) | 3
;; | 1| |1 | b | (b d) (b c) (b d) | 1
;; | d---e---f | c | (b c) (c e) (b c) | 2
;; | 2 3 | d | (b d) (d e) (c e) | 1
;; +----------------+ e | (d e) (c e) (d e) | 2
;; f | (e f) (e f) | 3
;; g |
;;
;; Graphs are CLOS objects which are constructed with the usual `make
;; instance` and are populated with the `populate` function.
;;
;; (defvar *graph* (populate (make-instance 'graph)
;; :nodes '(a b c d e f g)
;; :edges-w-values '(((a b) . 3)
;; ((b d) . 1)
;; ((b c) . 2)
;; ((c e) . 1)
;; ((d e) . 2)
;; ((e f) . 3))))
;;
;; Standard accessors are provided.
;;
;; * (nodes *graph*)
;; (A B C D E F G)
;;
;; * (edges *graph*)
;; ((A B) (B D) (B C) (C E) (D E) (E F))
;;
;; * (node-edges *graph* 'b)
;; ((B C) (B D) (A B))
;;
;; * (edge-value *graph* '(d e))
;; 2
;;
;; Nodes and edges may be removed using `delete-node` and
;; `delete-edge`, or using setf methods on any of the accessors above.
;;
;; * (delete-edge *graph* '(e f))
;; 3
;;
;; * (edges *graph*)
;; ((A B) (B D) (B C) (C E) (D E))
;;
;; * (setf (nodes *graph*) (remove 'a (nodes *graph*)))
;; (B C D E F G)
;;
;; * (edges *graph*)
;; ((B D) (B C) (C E) (D E))
;;
;; Some more sophisticated graph algorithms are implemented. A couple
;; are shown below, see the dictionary for a complete list.
;;
;; * (shortest-path *graph* 'b 'e)
;; ((B C) (C E))
;;
;; * (connected-components *graph*)
;; ((G) (B D C E) (F))
;;
;; * (setf (nodes *graph*) '(B D C E))
;; (B C D E)
;;
;; * (min-cut *graph*)
;; ((B C) (E D))
;; 2
;;
;; Additionally digraphs represent graphs with directed edges.
;; Starting with the original graph above we get the following.
;;
;; * (strongly-connected-components *graph*)
;; ((G) (D F E C B A))
;;
;; * (strongly-connected-components (digraph-of *graph*))
;; ((G) (A) (B) (D) (C) (E) (F))
;;
;; * (delete-edge *graph* '(d e))
;; 2
;;
;; * (push '(e d) (edges *graph*))
;; ((A B) (B D) (B C) (C E) (E D) (E F))
;;
;; * (push '(d c) (edges *graph*))
;; ((A B) (B D) (B C) (C E) (E D) (E F) (D C))
;;
;; * (strongly-connected-components (digraph-of *graph*))
;; ((G) (A) (B) (D E C) (F))
;;; Code:
(uiop/package:define-package :graph/graph
(:nicknames :graph)
(:use :common-lisp :alexandria :metabang-bind
:named-readtables :curry-compose-reader-macros)
(:import-from :damn-fast-priority-queue
:make-queue :enqueue :dequeue)
(:export
:graph
:digraph
:copy
:digraph-of
:graph-of
:populate
:graph-equal
;; Serialization
:to-plist
:from-plist
:to-adjacency-matrix
:to-value-matrix
:from-value-matrix
;; Simple Graph Methods
:edges
:edges-w-values
:nodes
:nodes-w-values
:has-node-p
:has-edge-p
:subgraph
:add-node
:add-edge
:node-edges
:degree
:indegree
:outdegree
:adjacent-to
:adjacent-from
:delete-node
:edge-value
:delete-edge
:reverse-edges
;; Complex Graph Methods
:merge-nodes
:merge-edges
:edge-neighbors
:neighbors
:precedents
:connected-component
:connectedp
:connected-components
:topological-sort
:levels
;; Cycles and strongly connected components
:strongly-connected-components
:basic-cycles
:cycles
:minimum-spanning-tree
:connected-groups-of-size
:closedp
:clustering-coefficient
:cliques
;; All paths
:all-paths
;; Shortest Path
:shortest-path
;; Max Flow
:residual
:add-paths
:max-flow
;; Min Cut
:min-cut
;; Random Graph generation
:preferential-attachment-populate
:erdos-renyi-populate
:erdos-renyi-graph
:erdos-renyi-digraph
:edgar-gilbert-populate
:edgar-gilbert-graph
:edgar-gilbert-digraph
;; Centrality
:farness
:closeness
:betweenness
:katz-centrality
;; Degeneracy
:degeneracy
:k-cores
;; Digraph node classification predicates
:transmitterp
:receiverp
:isolatep
:carrierp
:ordinaryp
;; Digraph node classes
:transmitters
:receivers
:isolates
:ordinaries
:carriers))
(in-package :graph)
(in-readtable :curry-compose-reader-macros)
(declaim (optimize (speed 3)))
;;; Special hashes keyed for edges
(defun edge-equalp (edge1 edge2)
(set-equal edge1 edge2))
(defun sxhash-edge (edge)
(sxhash (sort (copy-tree edge)
(if (numberp (car edge))
(lambda (a b)
(or (< (imagpart a) (imagpart b))
(and (= (imagpart a) (imagpart b))
(< (realpart a) (realpart b)))))
#'string<))))
#+sbcl
(sb-ext:define-hash-table-test edge-equalp sxhash-edge)
#+clisp
(ext:define-hash-table-test edge-equalp edge-equalp sxhash-edge)
(defun dir-edge-equalp (edge1 edge2)
(tree-equal edge1 edge2))
#+sbcl
(sb-ext:define-hash-table-test dir-edge-equalp sxhash)
#+clisp
(ext:define-hash-table-test dir-edge-equalp dir-edge-equalp sxhash)
(defun make-edge-hash-table ()
#+sbcl
(make-hash-table :test 'edge-equalp)
#+clisp
(make-hash-table :test 'edge-equalp)
#+(or ccl lispworks)
(make-hash-table :test 'edge-equalp :hash-function 'sxhash-edge)
#+allegro
(make-hash-table :test 'edge-equalp)
#+ecl
(make-hash-table :test 'edge-equalp :hash-function 'sxhash-edge)
#-(or sbcl clisp ccl allegro lispworks ecl)
(error "unsupport lisp distribution"))
(defun make-diedge-hash-table ()
#+sbcl
(make-hash-table :test 'dir-edge-equalp)
#+clisp
(make-hash-table :test 'dir-edge-equalp)
#+(or ccl lispworks)
(make-hash-table :test 'dir-edge-equalp :hash-function 'sxhash)
#+allegro
(make-hash-table :test 'dir-edge-equalp)
#+ecl
(make-hash-table :test 'dir-edge-equalp :hash-function 'sxhash)
#-(or sbcl clisp ccl allegro lispworks ecl)
(error "unsupport lisp distribution"))
;;; Graph objects and basic methods
(defclass graph ()
((node-h :initarg :node-h :accessor node-h :initform (make-hash-table))
(edge-h :initarg :edge-h :accessor edge-h :initform (make-edge-hash-table))
(edge-eq :initarg :edge-eq :accessor edge-eq :initform 'edge-equalp))
(:documentation "A graph consisting of `nodes' connected by `edges'.
Nodes must be numbers symbols or keywords. Edges may be assigned
arbitrary values, although some functions assume numeric values (e.g.,
`merge-nodes', `merge-edges', `max-flow' and `min-cut')."))
(defclass digraph (graph)
((edge-h :initarg :edge-h :accessor edge-h :initform (make-diedge-hash-table))
(edge-eq :initarg :edge-eq :accessor edge-eq :initform 'dir-edge-equalp))
(:documentation "A `graph' with directed edges."))
(defun copy-hash (hash &optional test comb)
"Return a copy of HASH.
Optional argument TEST specifies a new equality test to use for the
copy. Second optional argument COMB specifies a function to use to
combine the values of elements of HASH which collide in the copy due
to a new equality test specified with TEST."
(let ((comb (when comb (fdefinition comb)))
(copy
#+sbcl (make-hash-table :test (or test (hash-table-test hash)))
#+clisp (make-hash-table :test (or test (hash-table-test hash)))
#+(or ccl lispworks)
(make-hash-table
:test (or test (hash-table-test hash))
:hash-function (case (or test (hash-table-test hash))
(edge-equalp 'sxhash-edge)
((dir-edge-equalp equalp) 'sxhash)))
#+ecl
(make-hash-table
:test (or test (hash-table-test hash))
:hash-function (let ((test (or test (hash-table-test hash))))
(cond ((eql test #'edge-equalp) 'sxhash-edge)
((member test (list #'dir-edge-equalp #'equalp))
'sxhash))))
#-(or sbcl clisp ccl lispworks ecl)
(error "unsupported lisp distribution")))
(maphash (lambda (k v) (setf (gethash k copy)
(if (and (gethash k copy) comb)
(funcall comb (gethash k copy) v)
v)))
hash)
copy))
(defun node-hash-equal (hash1 hash2)
"Test node hashes HASH1 and HASH2 for equality."
(set-equal (hash-table-alist hash1)
(hash-table-alist hash2)
:test (lambda (a b)
(and (equalp (car a) (car b))
(set-equal (cdr a) (cdr b) :test 'tree-equal)))))
(defun edge-hash-equal (hash1 hash2)
"Test edge hashes HASH1 and HASH2 for equality."
(set-equal (hash-table-alist hash1)
(hash-table-alist hash2)
:test 'equalp))
(defgeneric copy (graph)
(:documentation "Return a copy of GRAPH."))
(defmethod copy ((graph graph))
(make-instance (type-of graph)
:node-h (copy-hash (node-h graph))
:edge-h (copy-hash (edge-h graph))
:edge-eq (edge-eq graph)))
(defgeneric digraph-of (graph)
(:documentation "Copy GRAPH into a `digraph' and return."))
(defmethod digraph-of ((graph graph))
(make-instance 'digraph
:node-h (copy-hash (node-h graph))
:edge-h (copy-hash (edge-h graph))
:edge-eq (edge-eq graph)))
(defgeneric graph-of (digraph)
(:documentation "Copy DIGRAPH into a `graph' and return."))
(defmethod graph-of ((digraph digraph))
(make-instance 'graph
:node-h (copy-hash (node-h digraph))
:edge-h (copy-hash (edge-h digraph) 'equalp)
:edge-eq (edge-eq digraph)))
(defgeneric populate (graph &key nodes edges edges-w-values)
(:documentation
"Populate the nodes and edges of GRAPH based on keyword arguments."))
(defmethod populate ((graph graph) &key nodes edges edges-w-values)
(mapc {add-node graph} nodes)
(mapc {add-edge graph} edges)
(setf (edges-w-values graph) edges-w-values)
graph)
(defgeneric graph-equal (graph1 graph2)
(:documentation "Compare GRAPH1 and GRAPH2 for equality."))
(defmethod graph-equal ((graph1 graph) (graph2 graph))
(every (lambda-bind ((test key))
;; TODO: digraph's need a stricter graph-equal
(declare (type function test) (type function key))
(apply test (append (mapcar key (list graph1 graph2)))))
(list (list #'eq #'type-of)
(list #'equal #'edge-eq)
(list #'edge-hash-equal #'edge-h)
(list #'node-hash-equal #'node-h))))
;;; Serialize graphs
(defgeneric to-plist (graph &key node-fn edge-fn)
(:documentation "Serialize GRAPH as a plist.
Keyword arguments NODE-FN and EDGE-FN will be called on a node or edge
and should return a plist of data to associate with the given node or
edge in the results."))
(defmethod to-plist ((graph graph) &key node-fn edge-fn)
(let ((node-fn (when node-fn (fdefinition node-fn)))
(edge-fn (when edge-fn (fdefinition edge-fn)))
(counts (make-hash-table)) (counter -1))
(declare (type fixnum counter))
(list :nodes (mapcar (lambda (node)
(append (list :name node)
(when node-fn (funcall node-fn node))))
(mapc (lambda (n) (setf (gethash n counts)
(incf counter)))
(nodes graph)))
:edges (map 'list (lambda (edge value)
(append (list :edge edge :value value)
(when edge-fn (funcall edge-fn edge))))
(mapcar {mapcar {gethash _ counts}} (edges graph))
(mapcar {edge-value graph} (edges graph))))))
(defgeneric from-plist (graph plist)
(:documentation "Populate GRAPH with the contents of PLIST."))
(defmethod from-plist ((graph graph) plist)
(let ((nodes (map 'vector {getf _ :name} (getf plist :nodes))))
(populate graph
:nodes (coerce nodes 'list)
:edges-w-values (mapcar (lambda (el)
(cons (mapcar {aref nodes} (getf el :edge))
(getf el :value)))
(getf plist :edges)))))
(defgeneric to-value-matrix (graph)
(:documentation "Return the value matrix of GRAPH."))
(defmethod to-value-matrix ((graph graph))
(let ((node-index-hash (make-hash-table))
(counter -1))
(declare (type fixnum counter))
(mapc (lambda (node) (setf (gethash node node-index-hash) (incf counter)))
(nodes graph))
(let ((matrix (make-array (list (1+ counter) (1+ counter))
:initial-element nil)))
(mapc (lambda-bind (((a b) . value))
(setf (aref matrix
(gethash a node-index-hash)
(gethash b node-index-hash))
(or value t)))
(edges-w-values graph))
matrix)))
(defgeneric from-value-matrix (graph matrix)
(:documentation "Populate GRAPH from the value matrix MATRIX."))
(defmethod from-value-matrix ((graph graph) matrix)
(declare (type simple-array matrix))
(bind (((as bs) (array-dimensions matrix)))
(declare (type fixnum as) (type fixnum bs))
(assert (= as bs) (matrix) "Value matrix ~S must be square." matrix)
(do ((a 0 (1+ a))) ((= a as))
(declare (type fixnum a))
(do ((b 0 (1+ b))) ((= b bs))
(declare (type fixnum b))
(when (aref matrix a b)
(add-edge graph (list a b)
(if (eq t (aref matrix a b)) nil (aref matrix a b)))))))
graph)
;;; Simple graph methods
(defgeneric edges (graph)
(:documentation "Return a list of the edges in GRAPH."))
(defmethod edges ((graph graph))
(loop :for key :being :each :hash-key :of (edge-h graph) :collect key))
(defgeneric (setf edges) (new graph)
(:documentation "Set the edges in GRAPH to NEW."))
(defmethod (setf edges) (new (graph graph))
(mapc {delete-edge graph} (set-difference (edges graph) new
:test (edge-eq graph)))
(mapc {add-edge graph} (set-difference new (edges graph)
:test (edge-eq graph)))
(edges graph))
(defgeneric edges-w-values (graph)
(:documentation "Return an alist of edges of GRAPH with their values."))
(defmethod edges-w-values ((graph graph) &aux alist)
(maphash (lambda (edge value) (push (cons edge value) alist)) (edge-h graph))
alist)
(defgeneric (setf edges-w-values) (new graph)
(:documentation "Set the edges of graph to edges and values in NEW."))
(defmethod (setf edges-w-values) (new (graph graph))
(mapc (lambda-bind ((edge . value)) (add-edge graph edge value)) new))
(defgeneric nodes (graph)
(:documentation "Return a list of the nodes in GRAPH."))
(defmethod nodes ((graph graph))
(loop :for key :being :each :hash-key :of (node-h graph) :collect key))
(defgeneric (setf nodes) (new graph)
(:documentation "Set the nodes in GRAPH to NEW."))
(defmethod (setf nodes) (new (graph graph))
(mapc {delete-node graph} (set-difference (nodes graph) new))
(mapc {add-node graph} (set-difference new (nodes graph)))
(nodes graph))
(defgeneric nodes-w-values (graph)
(:documentation "Return an alist of nodes of GRAPH with their values."))
(defmethod nodes-w-values ((graph graph) &aux alist)
(maphash (lambda (node value) (push (cons node value) alist)) (node-h graph))
alist)
(defgeneric has-node-p (graph node)
(:documentation "Return `true' if GRAPH has node NODE."))
(defmethod has-node-p ((graph graph) node)
(multiple-value-bind (value included) (gethash node (node-h graph))
(declare (ignorable value)) included))
(defgeneric has-edge-p (graph edge)
(:documentation "Return `true' if GRAPH has edge EDGE."))
(defmethod has-edge-p ((graph graph) edge)
(multiple-value-bind (value included) (gethash edge (edge-h graph))
(declare (ignorable value)) included))
(defgeneric subgraph (graph nodes)
(:documentation "Return the subgraph of GRAPH restricted to NODES."))
(defmethod subgraph ((graph graph) nodes)
(let ((g (copy graph))) (setf (nodes g) nodes) g))
(defgeneric add-node (graph node)
(:documentation "Add NODE to GRAPH."))
(defmethod add-node ((graph graph) node)
;; NOTE: This limitation on the types of node simplifies the
;; equality tests, and the use of nodes as hash keys
;; throughout the remainder of this library. In fact the
;; addition of type-annotations around node quality operations
;; may improve performance. The desire for more complex node
;; structures, may often be met by maintaining a hash table
;; outside of the graph which maps graph nodes to the more
;; complex object related to the node.
(assert (or (numberp node) (symbolp node)) (node)
"Nodes must be numbers, symbols or keywords, not ~S.~%Invalid node:~S"
(type-of node) node)
(unless (has-node-p graph node)
(setf (gethash node (node-h graph)) nil)
node))
(defgeneric add-edge (graph edge &optional value)
(:documentation "Add EDGE to GRAPH with optional VALUE. The nodes of
EDGE are also added to GRAPH."))
(defmethod add-edge ((graph graph) edge &optional value)
(mapc (lambda (node)
(add-node graph node)
(pushnew (case (type-of graph)
(graph (remove-duplicates edge))
(digraph edge))
(gethash node (node-h graph))
:test (edge-eq graph)))
edge)
(setf (gethash edge (edge-h graph)) value)
edge)
(defgeneric node-edges (graph node)
(:documentation "Return the value of NODE in GRAPH."))
(defmethod node-edges ((graph graph) node)
(multiple-value-bind (edges included) (gethash node (node-h graph))
(assert included (node graph) "~S doesn't include ~S" graph node)
(copy-tree edges)))
(defgeneric degree (graph node)
(:documentation "Return the degree of NODE in GRAPH."))
(defmethod degree ((graph graph) node)
(length (node-edges graph node)))
(defgeneric indegree (digraph node)
(:documentation "The number of edges directed to NODE in GRAPH."))
(defmethod indegree ((digraph digraph) node)
(length (remove-if-not [{member node} #'cdr] (node-edges digraph node))))
(defgeneric outdegree (digraph node)
(:documentation "The number of edges directed from NODE in DIGRAPH."))
(defmethod outdegree ((digraph digraph) node)
(length (remove-if-not [{equal node} #'car] (node-edges digraph node))))
(defgeneric adjacent-from (digraph node)
(:documentation "List nodes adjacent from NODE in DIGRAPH."))
(defmethod adjacent-from ((digraph digraph) node)
(mapcar #'(lambda (x) (nth 1 x))
(remove-if-not [{equal node} #'car] (node-edges digraph node))))
(defgeneric adjacent-to (digraph node)
(:documentation "List nodes adjacent to NODE in DIGRAPH."))
(defmethod adjacent-to ((digraph digraph) node)
(mapcar #'(lambda (x) (nth 0 x))
(remove-if-not [{member node} #'cdr] (node-edges digraph node))))
(defgeneric transmitterp (digraph node)
(:documentation "Returns t if node is a transmitter, i.e., has
indegree of 0 and positive outdegree."))
(defmethod transmitterp ((digraph digraph) node)
(and (eq (indegree digraph node) 0) (> (outdegree digraph node) 0)))
(defgeneric receiverp (digraph node)
(:documentation "Returns t if node is a receiver, i.e., has
outdegree of 0 and positive indegree."))
(defmethod receiverp ((digraph digraph) node)
(and (eq (outdegree digraph node) 0) (> (indegree digraph node) 0)))
(defgeneric isolatep (digraph node)
(:documentation "Returns t if node is an isolate, i.e., both
indegree and outdegree are 0."))
(defmethod isolatep ((digraph digraph) node)
(and (eq (indegree digraph node) 0) (eq (outdegree digraph node) 0)))
(defgeneric carrierp (digraph node)
(:documentation "Returns t if node is a carrier, i.e.,
both indegree and outdegree are 1."))
(defmethod carrierp ((digraph digraph) node)
(and (eq (indegree digraph node) 1) (eq (outdegree digraph node) 1)))
(defgeneric ordinaryp (digraph node)
(:documentation "Returns t if node is ordinary, i.e., is not a
transmitter, receiver, isolate, or carrier."))
(defmethod ordinaryp ((digraph digraph) node)
(not (or (transmitterp digraph node)
(receiverp digraph node)
(isolatep digraph node)
(carrierp digraph node))))
(defgeneric transmitters (digraph)
(:documentation "Return a list of the transmitters in digraph."))
(defmethod transmitters ((digraph digraph))
(let ((r))
(dolist (n (nodes digraph) r)
(when (transmitterp digraph n) (push n r)))))
(defgeneric receivers (digraph)
(:documentation "Return a list of the receivers in digraph."))
(defmethod receivers ((digraph digraph))
(let ((r))
(dolist (n (nodes digraph) r)
(when (receiverp digraph n) (push n r)))))
(defgeneric isolates (digraph)
(:documentation "Return a list of the isolated nodes in digraph."))
(defmethod isolates ((digraph digraph))
(let ((r))
(dolist (n (nodes digraph) r)
(when (isolatep digraph n) (push n r)))))
(defgeneric ordinaries (digraph)
(:documentation "Return a list of the ordinary nodes in digraph."))
(defmethod ordinaries ((digraph digraph))
(let ((r))
(dolist (n (nodes digraph) r)
(when (ordinaryp digraph n) (push n r)))))
(defgeneric carriers (digraph)
(:documentation "Return a list of the carrier nodes in digraph."))
(defmethod carriers ((digraph digraph))
(let ((r))
(dolist (n (nodes digraph) r)
(when (carrierp digraph n) (push n r)))))
(defgeneric (setf node-edges) (new graph node) ;; TODO: seg-faults in clisp
(:documentation "Set the edges of NODE in GRAPH to NEW.
Delete and return the old edges of NODE in GRAPH."))
(defmethod (setf node-edges) (new (graph graph) node)
(prog1 (mapc {delete-edge graph} (gethash node (node-h graph)))
(mapc {add-edge graph} new)))
(defgeneric delete-node (graph node)
(:documentation "Delete NODE from GRAPH.
Delete and return the old edges of NODE in GRAPH."))
(defmethod delete-node ((graph graph) node)
(prog1 (mapcar (lambda (edge) (cons edge (delete-edge graph edge)))
(node-edges graph node))
(remhash node (node-h graph))))
(defgeneric edge-value (graph edge)
(:documentation "Return the value of EDGE in GRAPH."))
(defmethod edge-value ((graph graph) edge)
(multiple-value-bind (value included) (gethash edge (edge-h graph))
(assert included (edge graph) "~S doesn't include ~S" graph edge)
value))
(defgeneric (setf edge-value) (new graph edge)
(:documentation "Set the value of EDGE in GRAPH to NEW."))
(defmethod (setf edge-value) (new (graph graph) edge)
(setf (gethash edge (edge-h graph)) new))
(defgeneric delete-edge (graph edge)
(:documentation "Delete EDGE from GRAPH.
Return the old value of EDGE."))
(defmethod delete-edge ((graph graph) edge)
(prog1 (edge-value graph edge)
(mapc (lambda (node) (setf (gethash node (node-h graph))
(remove edge (gethash node (node-h graph))
:test (edge-eq graph))))
edge)
(remhash edge (edge-h graph))))
(defgeneric reverse-edges (graph)
(:documentation "Return a copy of GRAPH with all edges reversed."))
(defmethod reverse-edges ((graph graph))
(populate (make-instance (type-of graph))
:nodes (nodes graph)
:edges-w-values (mapcar (lambda-bind ((edge . value)) (cons (reverse edge) value))
(edges-w-values graph))))
;;; Complex graph methods
(defgeneric merge-nodes (graph node1 node2 &key new)
(:documentation "Combine NODE1 and NODE2 in GRAPH into the node NEW.
All edges of NODE1 and NODE2 in GRAPH will be combined into a new node
of value NEW. Edges between only NODE1 and NODE2 will be removed."))
(defmethod merge-nodes ((graph graph) node1 node2 &key (new node1))
;; replace all removed edges with NEW instead of NODE1 or NODE2
(mapcar
(lambda-bind ((edge . value))
(let ((e (mapcar (lambda (n) (if (member n (list node1 node2)) new n)) edge)))
(if (has-edge-p graph e)
(when (and (edge-value graph e) value)
(setf (edge-value graph e) (+ (edge-value graph e) value)))
(add-edge graph e value))))
;; drop edges between only node1 and node2
(remove-if-not [{set-difference _ (list node1 node2)} #'car]
;; delete both nodes keeping their edges and values
(prog1 (append (delete-node graph node1)
(delete-node graph node2))
;; add the new node
(add-node graph new))))
graph)
(defgeneric merge-edges (graph edge1 edge2 &key value)
(:documentation "Combine EDGE1 and EDGE2 in GRAPH into a new EDGE.
Optionally provide a value for the new edge, the values of EDGE1 and
EDGE2 will be combined."))
(defmethod merge-edges ((graph graph) edge1 edge2 &key value)
(add-edge graph (remove-duplicates (append edge1 edge2))
(or value
(when (and (edge-value graph edge1) (edge-value graph edge2))
(+ (edge-value graph edge1) (edge-value graph edge2)))))
(append (delete-edge graph edge1)
(delete-edge graph edge2)))
(defgeneric edge-neighbors (graph edge)
(:documentation "Return all edges which share a node with EDGE in GRAPH."))
(defmethod edge-neighbors ((graph graph) edge)
(mapcan {node-edges graph} edge))
(defgeneric neighbors (graph node)
(:documentation "Return all nodes which share an edge with NODE in GRAPH."))
(defmethod neighbors ((graph graph) node)
(remove node (apply {concatenate 'list} (node-edges graph node))))
(defmethod neighbors ((digraph digraph) node)
(mapcan [#'cdr {member node}] (node-edges digraph node)))
(defgeneric precedents (digraph node)
(:documentation "Return all nodes preceding NODE in an edge of DIGRAPH."))
(defmethod precedents ((digraph digraph) node)
(mapcan [#'cdr {member node} #'reverse] (node-edges digraph node)))
(defgeneric connected-component (graph node &key type)
(:documentation "Return the connected component of NODE in GRAPH.
The TYPE keyword argument only has an effect for directed graphs in
which it may be set to one of the following with :STRONG being the
default value.
:STRONG ..... connections only traverse edges along the direction of
the edge
:WEAK ....... connections may traverse edges in any direction
regardless of the edge direction
:UNILATERAL . two nodes a and b connected iff a is strongly connected
to b or b is strongly connected to a"))
(defun connected-component- (node neighbor-fn)
;; Helper function for `connected-component'.
(let ((from (list node)) (seen (list node)))
(loop :until (null from) :do
(let ((next (remove-duplicates (mapcan neighbor-fn from))))
(setf from (set-difference next seen))
(setf seen (union next seen))))
(reverse seen)))
(defmethod connected-component ((graph graph) node &key type)
(declare (ignorable type))
(connected-component- node {neighbors graph}))
(defmethod connected-component ((digraph digraph) node &key type)
(ecase (or type :strong)
(:strong (connected-component- node {neighbors digraph}))
(:weak (connected-component- node {neighbors (graph-of digraph)}))
(:unilateral
(let ((weakly (connected-component- node {neighbors (graph-of digraph)}))
(strongly (connected-component- node {neighbors digraph})))
;; keep weakly connected components which are strongly
;; connected to NODE in digraph or to which NODE is strongly
;; connected in the directional compliment of digraph
(union strongly
(remove-if-not
[{member node} {connected-component (reverse-edges digraph)}]
(set-difference weakly strongly)))))))
(defgeneric connectedp (graph &key type)
(:documentation "Return true if the graph is connected.
TYPE keyword argument is passed to `connected-components'."))
(defmethod connectedp ((graph graph) &key type)
(declare (ignorable type))
(let ((nodes (nodes graph)))
(subsetp (nodes graph) (connected-component graph (car nodes)))))
(defmethod connectedp ((digraph digraph) &key type)
(every [{subsetp (nodes digraph)}
(lambda (n) (connected-component digraph n :type type))]
(nodes digraph)))
(defgeneric connected-components (graph &key type)
(:documentation "Return a list of the connected components of GRAPH.
Keyword TYPE is passed to `connected-component' and only has effect
for directed graphs. Returns strongly connected components of a
directed graph by default."))
(defmethod connected-components ((graph graph) &key type)
(flet ((cc-helper ()
(let ((nodes (sort (nodes graph) #'< :key {degree graph})) ccs)
(loop :until (null nodes) :do
(let ((cc (connected-component graph (car nodes) :type type)))
(setf nodes (set-difference nodes cc))
(push cc ccs)))
ccs)))
(cond
((and type (eq (type-of graph) 'graph))
(warn "type parameter has no effect for undirected graphs")
(cc-helper))
((eq type :unilateral)
(warn "unilateral connected component partition may not be well defined")
(cc-helper))
((or (eq type :strong)
(and (null type)
(eq (type-of graph) 'digraph)))
(strongly-connected-components graph))
(t (cc-helper)))))
(defgeneric topological-sort (digraph)
(:documentation
"Returns a topologically ordered list of the nodes in DIGRAPH, such
that, for each edge in DIGRAPH, the start of the edge appears in the
list before the end of the edge."))
(defmethod topological-sort (digraph)
(assert (null (basic-cycles digraph)) (digraph)
"~S has a cycle so no topological sort is possible" digraph)
(let ((index (make-hash-table))
stack)
(labels ((visit (node)
(mapc (lambda (neighbor)
(unless (gethash neighbor index)
(visit neighbor)))
(neighbors digraph node))
;; mark this node
(setf (gethash node index) 1)
(push node stack)))
(mapc (lambda (node) (unless (gethash node index) (visit node)))
(nodes digraph)))
stack))
(defgeneric levels (digraph &key alist)
(:documentation "Assign a positive integer to each node in DIGRAPH,
called its level, where, for each directed edge (a b) the
corresponding integers satisfy a < b. Returns either a hash table
where the nodes are keys and the levels are values, or an association
list of nodes and their levels, along with the number of levels in
DIGRAPH."))
(defmethod levels (digraph &key alist)
(let ((longest (make-hash-table)))
(dolist (x (topological-sort digraph))
(let ((max-val 0)
(incoming (precedents digraph x)))
(if incoming
(progn
(dolist (y incoming)
(when (> (gethash y longest) max-val)
(setf max-val (gethash y longest))))
(setf (gethash x longest) (+ 1 max-val)))
(setf (gethash x longest) max-val))))
(values (if alist (nreverse (hash-table-alist longest))
longest)
(+ 1 (reduce #'max (hash-table-values longest))))))
;;; Cycles and strongly connected components
(defgeneric strongly-connected-components (graph)
(:documentation
"Return the nodes of GRAPH partitioned into strongly connected components.
Uses Tarjan's algorithm."))
(defmethod strongly-connected-components ((graph graph))
(let ((index (make-hash-table))
(lowlink (make-hash-table))
(counter 0) stack sccs)
(labels ((tarjan (node)
;; mark this node
(setf (gethash node index) counter)
(setf (gethash node lowlink) counter)
(incf counter)
(push node stack)
;; consider successors
(mapc (lambda (neighbor)
(cond
((not (gethash neighbor index))
(tarjan neighbor)
(setf (gethash node lowlink)
(min (gethash node lowlink)
(gethash neighbor lowlink))))
((member neighbor stack)
(setf (gethash node lowlink)
(min (gethash node lowlink)
(gethash neighbor index))))))
(neighbors graph node))
;; is NODE the root of a strongly connected component
(when (= (gethash node index) (gethash node lowlink))
(push (loop :for v = (pop stack) :collect v :until (eq v node))
sccs))))
(mapc (lambda (node) (unless (gethash node index) (tarjan node)))
(nodes graph)))
sccs))
(defgeneric basic-cycles (graph)
(:documentation "Return all basic cycles in the GRAPH."))
(defmethod basic-cycles ((graph graph))
(let (cycles seen)
(labels ((follow (node path used-edges)
(push node seen)
(dolist (edge (node-edges graph node))
(unless (member edge used-edges :test (edge-eq graph))
(dolist (neighbor (case (type-of graph)
(graph (remove node edge))
(digraph (cdr (member node edge)))))
(cond ((member neighbor path)
(push (subseq path 0 (1+ (position neighbor path)))
cycles))
(t (follow neighbor
(cons neighbor path)
(cons edge used-edges)))))))))
(dolist (node (nodes graph))
(unless (member node seen)
(follow node (list node) nil))))
(remove-duplicates cycles :test 'set-equal)))
(defgeneric cycles (graph)
(:documentation "Return all cycles of GRAPH (both basic and compound)."))
(defmethod cycles ((graph graph))
(flet ((combine (c1 c2)
(let (done)
(reduce (lambda (acc el)
(append
(if (and (not done) (member el c1))
(progn
(setf done t)
(append (member el c1)
(reverse (member el (reverse c1)))))
(list el))
acc))
c2 :initial-value nil))))
(let ((basic-cycles (basic-cycles graph)) cycles)
(loop :for cycle = (pop basic-cycles) :while cycle :do
(push cycle cycles)
(mapc (lambda (c) (push (combine c cycle) cycles))
(remove-if-not {intersection cycle} basic-cycles)))
cycles)))
(defgeneric minimum-spanning-tree (graph &optional tree)
(:documentation "Return a minimum spanning tree of GRAPH.