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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341

;;; graph.lisp  because its easier to write than to learn such a library
;; Copyright (C) Eric Schulte and Thomas Dye 20122013
;; 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  + +
;;  abc g  a  (a b) (a b)  3
;;  1 1  b  (b d) (b c) (b d)  1
;;  def  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 (makeinstance 'graph)
;; :nodes '(a b c d e f g)
;; :edgeswvalues '(((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))
;;
;; * (nodeedges *graph* 'b)
;; ((B C) (B D) (A B))
;;
;; * (edgevalue *graph* '(d e))
;; 2
;;
;; Nodes and edges may be removed using `deletenode` and
;; `deleteedge`, or using setf methods on any of the accessors above.
;;
;; * (deleteedge *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.
;;
;; * (shortestpath *graph* 'b 'e)
;; ((B C) (C E))
;;
;; * (connectedcomponents *graph*)
;; ((G) (B D C E) (F))
;;
;; * (setf (nodes *graph*) '(B D C E))
;; (B C D E)
;;
;; * (mincut *graph*)
;; ((B C) (E D))
;; 2
;;
;; Additionally digraphs represent graphs with directed edges.
;; Starting with the original graph above we get the following.
;;
;; * (stronglyconnectedcomponents *graph*)
;; ((G) (D F E C B A))
;;
;; * (stronglyconnectedcomponents (digraphof *graph*))
;; ((G) (A) (B) (D) (C) (E) (F))
;;
;; * (deleteedge *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))
;;
;; * (stronglyconnectedcomponents (digraphof *graph*))
;; ((G) (A) (B) (D E C) (F))
;;; Code:
(uiop/package:definepackage :graph/graph
(:nicknames :graph)
(:use :commonlisp :alexandria :metabangbind
:namedreadtables :currycomposereadermacros)
(:export
:graph
:digraph
:copy
:digraphof
:graphof
:populate
:graphequal
;; Serialization
:toplist
:fromplist
:toadjacencymatrix
:tovaluematrix
:fromvaluematrix
;; Simple Graph Methods
:edges
:edgeswvalues
:nodes
:nodeswvalues
:hasnodep
:hasedgep
:subgraph
:addnode
:addedge
:nodeedges
:degree
:indegree
:outdegree
:deletenode
:edgevalue
:deleteedge
:reverseedges
;; Complex Graph Methods
:mergenodes
:mergeedges
:edgeneighbors
:neighbors
:precedents
:connectedcomponent
:connectedp
:connectedcomponents
:topologicalsort
:levels
;; Cycles and strongly connected components
:stronglyconnectedcomponents
:basiccycles
:cycles
:minimumspanningtree
:connectedgroupsofsize
:closedp
:clusteringcoefficient
:cliques
;; Shortest Path
:shortestpath
;; Max Flow
:residual
:addpaths
:maxflow
;; Min Cut
:mincut
;; Random Graph generation
:preferentialattachmentpopulate
:erdosrenyipopulate
:erdosrenyigraph
:erdosrenyidigraph
:edgargilbertpopulate
:edgargilbertgraph
:edgargilbertdigraph
;; Centrality
:farness
:closeness
:betweenness
:katzcentrality
;; Degeneracy
:degeneracy
:kcores))
(inpackage :graph)
(inreadtable :currycomposereadermacros)
;;; Special hashes keyed for edges
(defun edgeequalp (edge1 edge2)
(setequal edge1 edge2))
(defun sxhashedge (edge)
(sxhash (sort (copytree edge) (if (numberp (car edge)) #'< #'string<))))
#+sbcl
(sbext:definehashtabletest edgeequalp sxhashedge)
#+clisp
(ext:definehashtabletest edgeequalp edgeequalp sxhashedge)
(defun diredgeequalp (edge1 edge2)
(treeequal edge1 edge2))
#+sbcl
(sbext:definehashtabletest diredgeequalp sxhash)
#+clisp
(ext:definehashtabletest diredgeequalp diredgeequalp sxhash)
(defun makeedgehashtable ()
#+sbcl
(makehashtable :test 'edgeequalp)
#+clisp
(makehashtable :test 'edgeequalp)
#+ccl
(makehashtable :test 'edgeequalp :hashfunction 'sxhashedge)
#(or sbcl clisp ccl)
(error "unsupport lisp distribution"))
(defun makediedgehashtable ()
#+sbcl
(makehashtable :test 'diredgeequalp)
#+clisp
(makehashtable :test 'diredgeequalp)
#+ccl
(makehashtable :test 'diredgeequalp :hashfunction 'sxhash)
#(or sbcl clisp ccl)
(error "unsupport lisp distribution"))
;;; Graph objects and basic methods
(defclass graph ()
((nodeh :initarg :nodeh :accessor nodeh :initform (makehashtable))
(edgeh :initarg :edgeh :accessor edgeh :initform (makeedgehashtable))
(edgeeq :initarg :edgeeq :accessor edgeeq :initform 'edgeequalp))
(: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.,
`mergenodes', `mergeedges', `maxflow' and `mincut')."))
(defclass digraph (graph)
((edgeh :initarg :edgeh :accessor edgeh :initform (makediedgehashtable))
(edgeeq :initarg :edgeeq :accessor edgeeq :initform 'diredgeequalp))
(:documentation "A `graph' with directed edges."))
(defun copyhash (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 ((copy
#+sbcl (makehashtable :test (or test (hashtabletest hash)))
#+clisp (makehashtable :test (or test (hashtabletest hash)))
#+ccl (makehashtable
:test (or test (hashtabletest hash))
:hashfunction (case (or test (hashtabletest hash))
(edgeequalp 'sxhashedge)
((diredgeequalp equalp) 'sxhash)))
#(or sbcl clisp ccl) (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 nodehashequal (hash1 hash2)
"Test node hashes HASH1 and HASH2 for equality."
(setequal (hashtablealist hash1)
(hashtablealist hash2)
:test (lambda (a b)
(and (equalp (car a) (car b))
(setequal (cdr a) (cdr b) :test 'treeequal)))))
(defun edgehashequal (hash1 hash2)
"Test edge hashes HASH1 and HASH2 for equality."
(setequal (hashtablealist hash1)
(hashtablealist hash2)
:test 'equalp))
(defgeneric copy (graph)
(:documentation "Return a copy of GRAPH."))
(defmethod copy ((graph graph))
(makeinstance (typeof graph)
:nodeh (copyhash (nodeh graph))
:edgeh (copyhash (edgeh graph))
:edgeeq (edgeeq graph)))
(defgeneric digraphof (graph)
(:documentation "Copy GRAPH into a `digraph' and return."))
(defmethod digraphof ((graph graph))
(makeinstance 'digraph
:nodeh (copyhash (nodeh graph))
:edgeh (copyhash (edgeh graph))
:edgeeq (edgeeq graph)))
(defgeneric graphof (digraph)
(:documentation "Copy DIGRAPH into a `graph' and return."))
(defmethod graphof ((digraph digraph))
(makeinstance 'graph
:nodeh (copyhash (nodeh digraph))
:edgeh (copyhash (edgeh digraph) 'equalp)
:edgeeq (edgeeq digraph)))
(defgeneric populate (graph &key nodes edges edgeswvalues)
(:documentation
"Populate the nodes and edges of GRAPH based on keyword arguments."))
(defmethod populate ((graph graph) &key nodes edges edgeswvalues)
(mapc {addnode graph} nodes)
(mapc {addedge graph} edges)
(setf (edgeswvalues graph) edgeswvalues)
graph)
(defgeneric graphequal (graph1 graph2)
(:documentation "Compare GRAPH1 and GRAPH2 for equality."))
(defmethod graphequal ((graph1 graph) (graph2 graph))
(every (lambdabind ((test key)) ;; TODO: digraph's need a stricter graphequal
(apply test (append (mapcar key (list graph1 graph2)))))
'((eq typeof)
(equal edgeeq)
(edgehashequal edgeh)
(nodehashequal nodeh))))
;;; Serialize graphs
(defgeneric toplist (graph &key nodefn edgefn)
(:documentation "Serialize GRAPH as a plist.
Keyword arguments NODEFN and EDGEFN 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 toplist ((graph graph) &key nodefn edgefn)
(let ((counts (makehashtable)) (counter 1))
(list :nodes (mapcar (lambda (node)
(append (list :name node)
(when nodefn (funcall nodefn 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 edgefn (funcall edgefn edge))))
(mapcar {mapcar {gethash _ counts}} (edges graph))
(mapcar {edgevalue graph} (edges graph))))))
(defgeneric fromplist (graph plist)
(:documentation "Populate GRAPH with the contents of PLIST."))
(defmethod fromplist ((graph graph) plist)
(let ((nodes (map 'vector {getf _ :name} (getf plist :nodes))))
(populate graph
:nodes (coerce nodes 'list)
:edgeswvalues (mapcar (lambda (el)
(cons (mapcar {aref nodes} (getf el :edge))
(getf el :value)))
(getf plist :edges)))))
(defgeneric tovaluematrix (graph)
(:documentation "Return the value matrix of GRAPH."))
(defmethod tovaluematrix ((graph graph))
(let ((nodeindexhash (makehashtable))
(counter 1))
(mapc (lambda (node) (setf (gethash node nodeindexhash) (incf counter)))
(nodes graph))
(let ((matrix (makearray (list (1+ counter) (1+ counter))
:initialelement nil)))
(mapc (lambdabind (((a b) . value))
(setf (aref matrix
(gethash a nodeindexhash)
(gethash b nodeindexhash))
(or value t)))
(edgeswvalues graph))
matrix)))
(defgeneric fromvaluematrix (graph matrix)
(:documentation "Populate GRAPH from the value matrix MATRIX."))
(defmethod fromvaluematrix ((graph graph) matrix)
(bind (((as bs) (arraydimensions matrix)))
(assert (= as bs) (matrix) "Value matrix ~S must be square." matrix)
(loop :for a :below as :do
(loop :for b :below bs :do
(when (aref matrix a b)
(addedge 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 :hashkey :of (edgeh graph) :collect key))
(defgeneric (setf edges) (new graph)
(:documentation "Set the edges in GRAPH to NEW."))
(defmethod (setf edges) (new (graph graph))
(mapc {deleteedge graph} (setdifference (edges graph) new
:test (edgeeq graph)))
(mapc {addedge graph} (setdifference new (edges graph)
:test (edgeeq graph)))
(edges graph))
(defgeneric edgeswvalues (graph)
(:documentation "Return an alist of edges of GRAPH with their values."))
(defmethod edgeswvalues ((graph graph) &aux alist)
(maphash (lambda (edge value) (push (cons edge value) alist)) (edgeh graph))
alist)
(defgeneric (setf edgeswvalues) (new graph)
(:documentation "Set the edges of graph to edges and values in NEW."))
(defmethod (setf edgeswvalues) (new (graph graph))
(mapc (lambdabind ((edge . value)) (addedge 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 :hashkey :of (nodeh graph) :collect key))
(defgeneric (setf nodes) (new graph)
(:documentation "Set the nodes in GRAPH to NEW."))
(defmethod (setf nodes) (new (graph graph))
(mapc {deletenode graph} (setdifference (nodes graph) new))
(mapc {addnode graph} (setdifference new (nodes graph)))
(nodes graph))
(defgeneric nodeswvalues (graph)
(:documentation "Return an alist of nodes of GRAPH with their values."))
(defmethod nodeswvalues ((graph graph) &aux alist)
(maphash (lambda (node value) (push (cons node value) alist)) (nodeh graph))
alist)
(defgeneric hasnodep (graph node)
(:documentation "Return `true' if GRAPH has node NODE."))
(defmethod hasnodep ((graph graph) node)
(multiplevaluebind (value included) (gethash node (nodeh graph))
(declare (ignorable value)) included))
(defgeneric hasedgep (graph edge)
(:documentation "Return `true' if GRAPH has edge EDGE."))
(defmethod hasedgep ((graph graph) edge)
(multiplevaluebind (value included) (gethash edge (edgeh 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 addnode (graph node)
(:documentation "Add NODE to GRAPH."))
(defmethod addnode ((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 typeannotations 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"
(typeof node) node)
(unless (hasnodep graph node)
(setf (gethash node (nodeh graph)) nil)
node))
(defgeneric addedge (graph edge &optional value)
(:documentation "Add EDGE to GRAPH with optional VALUE. The nodes of
EDGE are also added to GRAPH."))
(defmethod addedge ((graph graph) edge &optional value)
(mapc (lambda (node)
(addnode graph node)
(pushnew (case (typeof graph)
(graph (removeduplicates edge))
(digraph edge))
(gethash node (nodeh graph))
:test (edgeeq graph)))
edge)
(setf (gethash edge (edgeh graph)) value)
edge)
(defgeneric nodeedges (graph node)
(:documentation "Return the value of NODE in GRAPH."))
(defmethod nodeedges ((graph graph) node)
(multiplevaluebind (edges included) (gethash node (nodeh graph))
(assert included (node graph) "~S doesn't include ~S" graph node)
(copytree edges)))
(defgeneric degree (graph node)
(:documentation "Return the degree of NODE in GRAPH."))
(defmethod degree ((graph graph) node)
(length (nodeedges graph node)))
(defgeneric indegree (digraph node)
(:documentation "The number of edges directed to NODE in GRAPH."))
(defmethod indegree ((digraph digraph) node)
(length (removeifnot [{member node} #'cdr] (nodeedges digraph node))))
(defgeneric outdegree (digraph node)
(:documentation "The number of edges directed from NODE in DIGRAPH."))
(defmethod outdegree ((digraph digraph) node)
(length (removeifnot [{equal node} #'car] (nodeedges 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 node 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 (setf nodeedges) (new graph node) ;; TODO: segfaults in clisp
(:documentation "Set the edges of NODE in GRAPH to NEW.
Delete and return the old edges of NODE in GRAPH."))
(defmethod (setf nodeedges) (new (graph graph) node)
(prog1 (mapc {deleteedge graph} (gethash node (nodeh graph)))
(mapc {addedge graph} new)))
(defgeneric deletenode (graph node)
(:documentation "Delete NODE from GRAPH.
Delete and return the old edges of NODE in GRAPH."))
(defmethod deletenode ((graph graph) node)
(prog1 (mapcar (lambda (edge) (cons edge (deleteedge graph edge)))
(nodeedges graph node))
(remhash node (nodeh graph))))
(defgeneric edgevalue (graph edge)
(:documentation "Return the value of EDGE in GRAPH."))
(defmethod edgevalue ((graph graph) edge)
(multiplevaluebind (value included) (gethash edge (edgeh graph))
(assert included (edge graph) "~S doesn't include ~S" graph edge)
value))
(defgeneric (setf edgevalue) (new graph edge)
(:documentation "Set the value of EDGE in GRAPH to NEW."))
(defmethod (setf edgevalue) (new (graph graph) edge)
(setf (gethash edge (edgeh graph)) new))
(defgeneric deleteedge (graph edge)
(:documentation "Delete EDGE from GRAPH.
Return the old value of EDGE."))
(defmethod deleteedge ((graph graph) edge)
(prog1 (edgevalue graph edge)
(mapc (lambda (node) (setf (gethash node (nodeh graph))
(remove edge (gethash node (nodeh graph))
:test (edgeeq graph))))
edge)
(remhash edge (edgeh graph))))
(defgeneric reverseedges (graph)
(:documentation "Return a copy of GRAPH with all edges reversed."))
(defmethod reverseedges ((graph graph))
(populate (makeinstance (typeof graph))
:nodes (nodes graph)
:edgeswvalues (mapcar (lambdabind ((edge . value)) (cons (reverse edge) value))
(edgeswvalues graph))))
;;; Complex graph methods
(defgeneric mergenodes (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 mergenodes ((graph graph) node1 node2 &key (new node1))
;; replace all removed edges with NEW instead of NODE1 or NODE2
(mapcar
(lambdabind ((edge . value))
(let ((e (mapcar (lambda (n) (if (member n (list node1 node2)) new n)) edge)))
(if (hasedgep graph e)
(when (and (edgevalue graph e) value)
(setf (edgevalue graph e) (+ (edgevalue graph e) value)))
(addedge graph e value))))
;; drop edges between only node1 and node2
(removeifnot [{setdifference _ (list node1 node2)} #'car]
;; delete both nodes keeping their edges and values
(prog1 (append (deletenode graph node1)
(deletenode graph node2))
;; add the new node
(addnode graph new))))
graph)
(defgeneric mergeedges (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 mergeedges ((graph graph) edge1 edge2 &key value)
(addedge graph (removeduplicates (append edge1 edge2))
(or value
(when (and (edgevalue graph edge1) (edgevalue graph edge2))
(+ (edgevalue graph edge1) (edgevalue graph edge2)))))
(append (deleteedge graph edge1)
(deleteedge graph edge2)))
(defgeneric edgeneighbors (graph edge)
(:documentation "Return all edges which share a node with EDGE in GRAPH."))
(defmethod edgeneighbors ((graph graph) edge)
(mapcan {nodeedges graph} edge))
(defgeneric neighbors (graph node)
(:documentation "Return all nodes which share an edge with NODE in GRAPH."))
(defmethod neighbors ((graph graph) node)
(apply {concatenate 'list} (nodeedges graph node)))
(defmethod neighbors ((digraph digraph) node)
(mapcan [#'cdr {member node}] (nodeedges 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] (nodeedges digraph node)))
(defgeneric connectedcomponent (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 connectedcomponent (node neighborfn)
;; Helper function for `connectedcomponent'.
(let ((from (list node)) (seen (list node)))
(loop :until (null from) :do
(let ((next (removeduplicates (mapcan neighborfn from))))
(setf from (setdifference next seen))
(setf seen (union next seen))))
(reverse seen)))
(defmethod connectedcomponent ((graph graph) node &key type)
(declare (ignorable type))
(connectedcomponent node {neighbors graph}))
(defmethod connectedcomponent ((digraph digraph) node &key type)
(ecase (or type :strong)
(:strong (connectedcomponent node {neighbors digraph}))
(:weak (connectedcomponent node {neighbors (graphof digraph)}))
(:unilateral
(let ((weakly (connectedcomponent node {neighbors (graphof digraph)}))
(strongly (connectedcomponent 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
(removeifnot
[{member node} {connectedcomponent (reverseedges digraph)}]
(setdifference weakly strongly)))))))
(defgeneric connectedp (graph &key type)
(:documentation "Return true if the graph is connected.
TYPE keyword argument is passed to `connectedcomponents'."))
(defmethod connectedp ((graph graph) &key type)
(declare (ignorable type))
(let ((nodes (nodes graph)))
(subsetp (nodes graph) (connectedcomponent graph (car nodes)))))
(defmethod connectedp ((digraph digraph) &key type)
(every [{subsetp (nodes digraph)}
(lambda (n) (connectedcomponent digraph n :type type))]
(nodes digraph)))
(defgeneric connectedcomponents (graph &key type)
(:documentation "Return a list of the connected components of GRAPH.
Keyword TYPE is passed to `connectedcomponent' and only has effect
for directed graphs. Returns strongly connected components of a
directed graph by default."))
(defmethod connectedcomponents ((graph graph) &key type)
(flet ((cchelper ()
(let ((nodes (sort (nodes graph) #'< :key {degree graph})) ccs)
(loop :until (null nodes) :do
(let ((cc (connectedcomponent graph (car nodes) :type type)))
(setf nodes (setdifference nodes cc))
(push cc ccs)))
ccs)))
(cond
((and type (eq (typeof graph) 'graph))
(warn "type parameter has no effect for undirected graphs")
(cchelper))
((eq type :unilateral)
(warn "unilateral connected component partition may not be well defined")
(cchelper))
((or (eq type :strong)
(and (null type)
(eq (typeof graph) 'digraph)))
(stronglyconnectedcomponents graph))
(t (cchelper)))))
(defgeneric topologicalsort (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 topologicalsort (digraph)
(assert (null (basiccycles digraph)) (digraph)
"~S has a cycle so no topological sort is possible" digraph)
(let ((index (makehashtable))
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 (makehashtable)))
(dolist (x (topologicalsort digraph))
(let ((maxval 0)
(incoming (precedents digraph x)))
(if incoming
(progn
(dolist (y incoming)
(when (> (gethash y longest) maxval)
(setf maxval (gethash y longest))))
(setf (gethash x longest) (+ 1 maxval)))
(setf (gethash x longest) maxval))))
(values (if alist (nreverse (hashtablealist longest))
longest)
(+ 1 (reduce #'max (hashtablevalues longest))))))
;;; Cycles and strongly connected components
(defgeneric stronglyconnectedcomponents (graph)
(:documentation
"Return the nodes of GRAPH partitioned into strongly connected components.
Uses Tarjan's algorithm."))
(defmethod stronglyconnectedcomponents ((graph graph))
(let ((index (makehashtable))
(lowlink (makehashtable))
(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 basiccycles (graph)
(:documentation "Return all basic cycles in the GRAPH."))
(defmethod basiccycles ((graph graph))
(let (cycles seen)
(labels ((follow (node path usededges)
(push node seen)
(dolist (edge (nodeedges graph node))
(unless (member edge usededges :test (edgeeq graph))
(dolist (neighbor (case (typeof 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 usededges)))))))))
(dolist (node (nodes graph))
(unless (member node seen)
(follow node (list node) nil))))
(removeduplicates cycles :test 'setequal)))
(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 :initialvalue nil))))
(let ((basiccycles (basiccycles graph)) cycles)
(loop :for cycle = (pop basiccycles) :while cycle :do
(push cycle cycles)
(mapc (lambda (c) (push (combine c cycle) cycles))
(removeifnot {intersection cycle} basiccycles)))
cycles)))
(defgeneric minimumspanningtree (graph &optional tree)
(:documentation "Return a minimum spanning tree of GRAPH.
Prim's algorithm is used. Optional argument TREE may be used to
specify an initial tree, otherwise a random node is used."))
(defmethod minimumspanningtree
((graph graph) &optional (tree
(populate (makeinstance 'graph)
:nodes (list (randomelt (nodes graph))))))
(assert (connectedp graph) (graph) "~S is not connected" graph)
(let ((copy (copy graph))
(totalnodes (length (nodes graph))))
(loop :until (= (length (nodes tree)) totalnodes) :do
(let ((e (car (sort
(removeifnot
{intersection (setdifference (nodes copy) (nodes tree))}
(mapcan {nodeedges copy} (nodes tree)))
#'< :key {edgevalue copy}))))
(when e
(addedge tree e (edgevalue graph e))
(deleteedge copy e))))
tree))
(defgeneric connectedgroupsofsize (graph size)
(:documentation "Return all connected node groups of SIZE in GRAPH."))
(defmethod connectedgroupsofsize ((graph graph) size)
;; Note: this function doesn't work with hyper graphs
(assert (> size 1) (size) "can't group less than two items")
(let ((connectedgroups (edges graph)))
(loop :for i :from 2 :below size :do
(setf connectedgroups
(mapcan (lambda (group)
(mapcar {union group}
(removeif {subsetp _ group}
(mapcan {nodeedges graph}
group))))
connectedgroups)))
(removeduplicates connectedgroups :test 'setequal)))
(defgeneric closedp (graph nodes)
(:documentation "Return true if NODES are fully connected in GRAPH."))
(defmethod closedp ((graph graph) nodes)
(block nil ;; Note: this function doesn't work with hyper graphs
(mapcombinations (lambda (pair) (unless (hasedgep graph pair) (return nil)))
nodes :length 2)))
(defgeneric clusteringcoefficient (graph)
(:documentation "Fraction of connected triples which are closed."))
(defmethod clusteringcoefficient ((graph graph))
(let ((triples (connectedgroupsofsize graph 3)))
(/ (length (removeifnot {closedp graph} triples)) (length triples))))
(defgeneric cliques (graph)
(:documentation "Return the maximal cliques of GRAPH.
The BronKerbosh algorithm is used."))
(defmethod cliques ((graph graph) &aux cliques)
(labels ((bronkerbosch (r p x)
(if (and (null x) (null p))
(push r cliques)
(loop :for v :in p :collect ;; TODO: use `degeneracy' ordering
(let ((n (neighbors graph v)))
(bronkerbosch (union (list v) r)
(intersection (setdifference p r) n)
(intersection x n)))
:do (setf p (remove v p)
x (union (list v) x))))))
(bronkerbosch nil (nodes graph) nil))
cliques)
;;; Shortest Path
(defgeneric shortestpath (graph a b)
(:documentation "Return the shortest path in GRAPH from A to B.
GRAPH must be a directed graph. Dijkstra's algorithm is used."))
;; TODO: needs to work for undirected edges
(defmethod shortestpath ((graph graph) a b &aux seen)
(block nil ;; (car next) is leading node, (cdr next) is edge path
(let ((next (list (list a))))
(loop :until (null next) :do
(setf next
(mapcan
(lambdabind ((from . rest))
(mapcan
(lambda (edge)
(if (case (typeof graph)
(graph (member b edge))
(digraph (member b (cdr (member from edge)))))
(return (reverse (cons edge rest)))
(unless (member edge seen :test (edgeeq graph))
(push edge seen)
(mapcar
(lambda (n) (cons n (cons edge rest)))
(case (typeof graph)
(graph (remove from edge))
(digraph (cdr (member from edge))))))))
(nodeedges graph from)))
next))))))
;;; Max Flow
;;  Must be a "network" (digraph in which each edge has a positive weight)
;;  FordFulkerson is used
(defgeneric residual (graph flow)
(:documentation "Return the residual graph of GRAPH with FLOW.
Each edge in the residual has a value equal to the original capacity
minus the current flow, or equal to the negative of the current flow."))
(defmethod residual ((graph graph) flow)
(flet ((flowvalue (edge) (or (cdr (assoc edge flow :test (edgeeq graph))) 0)))
(let ((residual (makeinstance (typeof graph))))
(mapc (lambda (edge)
(let ((left ( (edgevalue graph edge) (flowvalue edge))))
(when (not (zerop left))
(addedge residual edge left)))
(when (not (zerop (flowvalue edge)))
(addedge residual (reverse edge) (flowvalue edge))))
(edges graph))
residual)))
(defgeneric addpaths (graph path1 path2)
(:documentation
"Return the combination of paths PATH1 and PATH2 through GRAPH.
Each element of PATH has the form (cons edge value)."))
(defmethod addpaths ((graph graph) path1 path2)
(let ((comb (copytree path1)))
(mapc (lambdabind ((edge . value))
(if (assoc edge comb :test (edgeeq graph))
(setf (cdr (assoc edge comb :test (edgeeq graph)))
(+ (cdr (assoc edge comb :test (edgeeq graph))) value))
(push (cons edge value) comb)))
path2)
comb))
(defmethod addpaths ((digraph digraph) path1 path2)
"Return the combination of paths PATH1 and PATH2 through DIGRAPH.
Each element of path has the form (cons edge value)."
(let ((comb (copytree path1)))
(mapc (lambdabind ((edge . value))
(cond
((assoc edge comb :test (edgeeq digraph))
(setf (cdr (assoc edge comb :test (edgeeq digraph)))
(+ (cdr (assoc edge comb :test (edgeeq digraph))) value)))
((assoc (reverse edge) comb :test (edgeeq digraph))
(setf (cdr (assoc (reverse edge) comb :test (edgeeq digraph)))
( (cdr (assoc edge comb :test (edgeeq digraph))) value)))
(t (push (cons edge value) comb))))
path2)
comb))
(defgeneric maxflow (graph from to)
(:documentation "Return the maximum flow from FROM and TO in GRAPH.
GRAPHS must be a network with numeric values of all edges.
The FordFulkerson algorithm is used."))
(defmethod maxflow ((digraph digraph) from to)
(flet ((trimpath (path)
(when path
(let ((flow (apply #'min (mapcar #'cdr path))))
(mapcar (lambda (el) (cons (car el) flow)) path))))
(flowvalueinto (flow node)
(reduce #'+ (removeifnot (lambda (el) (equal (lastcar (car el)) node))
flow)
:key #'cdr)))
(let ((from from) (to to) augment residual flow)
(loop :do
(setf residual (residual digraph flow))
;; "augmenting path" is path through residual network in which each
;; edge has positive capacity
(setf augment (trimpath
(mapcar (lambda (edge)
(cons edge (edgevalue residual edge)))
(shortestpath residual from to))))
:while augment :do
;; if ∃ an augmenting path, add it to the flow and repeat
(setf flow (addpaths digraph flow augment)))
(values flow (flowvalueinto flow to)))))
;;; Min Cut
;;
;; Stoer, M. and Wagner, Frank. 1997. A Simple MinCut Algorithm.
;; Journal of the ACM
;;
;; Theorem: Let s,t ∈ (nodes G), let G' be the result of merging s and
;; t in G. Then (mincut G) is equal to the minimum of the
;; min cut of s and t in G and (mincut G').
;;
(defun weighcut (graph cut)
(reduce #'+ (mapcar {edgevalue graph}
(removeifnot (lambda (edge)
(and (intersection edge (first cut))
(intersection edge (second cut))))
(edges graph)))))
(defgeneric mincut (graph)
(:documentation
"Return both the global mincut of GRAPH and the weight of the cut."))
(defmethod mincut ((graph graph))
(let ((g (copy graph))
(mergednodes (mapcar (lambda (n) (list n n)) (nodes graph)))
cutsofphase)
(flet ((connectionweight (group node)
;; return the weight of edges between GROUP and NODE
(reduce #'+ (mapcar {edgevalue g}
(removeifnot {intersection group}
(nodeedges g node)))))
(mymerge (a b)
;; merge in the graph
(mergenodes g a b)
;; update our merged nodes alist
(setf (cdr (assoc a mergednodes))
(append (cdr (assoc a mergednodes))
(cdr (assoc b mergednodes))))
(setq mergednodes
(removeif (lambda (it) (eql (car it) b)) mergednodes))))
(loop :while (> (length (nodes g)) 1) :do
(let* ((a (list (randomelt (nodes g))))
(rest (remove (car a) (nodes g))))
(loop :while rest :do
;; grow A by adding the node most tightly connected to A
(let ((new (car (sort rest #'> :key {connectionweight a}))))
(setf rest (remove new rest))
(push new a)))
;; store the cutofphase
(push (cons (connectionweight (cdr a) (car a))
(cdr (assoc (car a) mergednodes)))
cutsofphase)
;; merge two last added nodes
(mymerge (first a) (second a))))
;; return the minimum cutofphase
(let* ((half (cdar (sort cutsofphase #'< :key #'car)))
(cut (list half (setdifference (nodes graph) half))))
(values (sort cut #'< :key #'length) (weighcut graph cut))))))
;;; Random graphs generation
(defgeneric preferentialattachmentpopulate (graph nodes &key edgevals)
(:documentation ;; TODO: add optional argument for desired average degree
"Add NODES to GRAPH using preferential attachment, return the new edges.
Optionally assign edge values from those listed in EDGEVALS."))
(defmethod preferentialattachmentpopulate ((graph graph) nodes &key edgevals)
(let ((degreesum 0) (connections (makearray (* 2 (length nodes)))))
(flet ((saveedge (from to)
(incf degreesum 2)
(setf (aref connections ( degreesum 2)) from)
(setf (aref connections ( degreesum 1)) to)
(addedge graph (list from to) (when edgevals (pop edgevals)))))
(assert (not (= 1 (length nodes))) (nodes)
"Can't preferentially attach a single node.")
(when (null (nodes graph))
(saveedge (pop nodes) (pop nodes)))
(mapc (lambda (n) (saveedge n (aref connections (random degreesum)))) nodes)
(edgeswvalues graph))))
(defgeneric erdosrenyipopulate (graph m)
(:documentation
"Populate GRAPH with M edges in an Erdős–Rényi random graph model."))
(defmethod erdosrenyipopulate ((graph graph) m)
(let* ((nodes (coerce (nodes graph) 'vector))
(num (length nodes)))
(loop :until (= m 0) :do
;; NOTE: this naive approach will slow down drastically for
;; large nearly complete graphs
(let ((a (aref nodes (random num)))
(b (aref nodes (random num))))
(unless (or (= a b) (hasedgep graph (list a b)))
(addedge graph (list a b))
(decf m)))))
graph)
(defun erdosrenyigraph (n m)
"Return an Erdős–Rényi graph with N nodes and M edges."
(assert (and (not (< m 0)) (< m (/ (* n (1 n)) 2))) (n m)
"an ~Snode graph can not have ~S edges" n m)
(erdosrenyipopulate (populate (makeinstance 'graph)
:nodes (loop :for i :below n :collect i))
m))
(defun erdosrenyidigraph (n m)
"Return an Erdős–Rényi digraph with N nodes and M edges."
(assert (and (not (< m 0)) (< m (* n (1 n)))) (n m)
"an ~Snode digraph can not have ~S edges" n m)
(erdosrenyipopulate (populate (makeinstance 'digraph)
:nodes (loop :for i :below n :collect i))
m))
(defgeneric edgargilbertpopulate (graph p)
(:documentation
"Populate GRAPH including every possible edge with probability P."))
(defmethod edgargilbertpopulate ((graph graph) p)
(setf (edges graph) nil)
(mapcombinations (lambda (pair) ;; Note: needs refinement for hypergraphs
(when (< (random 1.0) p) (addedge graph pair)))
(nodes graph) :length 2)
graph)
(defmethod edgargilbertpopulate ((digraph digraph) p)
(setf (edges digraph) nil)
(mapc (lambda (from) ;; Note: needs refinement for hypergraphs
(mapc (lambda (to)
(when (< (random 1.0) p) (addedge digraph (list from to))))
(remove from (nodes digraph))))
(nodes digraph))
digraph)
(defun edgargilbertgraph (n p)
(edgargilbertpopulate (populate (makeinstance 'graph)
:nodes (loop :for i :below n :collect i))
p))
(defun edgargilbertdigraph (n p)
(edgargilbertpopulate (populate (makeinstance 'digraph)
:nodes (loop :for i :below n :collect i))
p))
;;; Centrality
(defgeneric farness (graph node)
(:documentation
"Sum of the distance from NODE to every other node in connected GRAPH."))
(defmethod farness ((graph graph) node)
(assert (connectedp graph) (graph)
"~S must be connected to calculate farness." graph)
(reduce #'+ (mapcar [#'length {shortestpath graph node}]
(remove node (nodes graph)))))
(defgeneric closeness (graph node)
(:documentation "Inverse of the `farness' for NODE in GRAPH."))
(defmethod closeness ((graph graph) node)
(/ 1 ) (farness graph node))
(defgeneric betweenness (graph node)
(:documentation
"Fraction of shortest paths through GRAPH which pass through NODE.
Fraction of node pairs (s,t) s.t. s and t ≠ NODE and the shortest path
between s and t in GRAPH passes through NODE."))
(defmethod betweenness ((graph graph) node)
(flet ((allpairs (lst)
(case (typeof graph)
(graph (mapcan (lambda (n) (mapcar {list n} (cdr (member n lst)))) lst))
(digraph (mapcan (lambda (n) (mapcar {list n} (remove n lst))) lst)))))
(let ((num 0) (denom 0))
(mapc (lambdabind ((a b))
(when (member node (apply #'append (shortestpath graph a b)))
(incf num))
(incf denom))
(allpairs (remove node (nodes graph))))
(/ num denom))))
(defgeneric katzcentrality (graph node &key attenuation)
(:documentation "Combined measure of number and nearness of nodes to NODE."))
(defmethod katzcentrality ((graph graph) node &key (attenuation 0.8))
(let ((cc (connectedcomponent graph node)))
(reduce #'+ (mapcar [{expt attenuation} #'length {shortestpath graph node}]
(remove node cc)))))
;;; Degeneracy
;;
;; From the Wikipedia article on "Degeneracy (graph theory)".
;;
(defgeneric degeneracy (graph)
(:documentation "Return the degeneracy and kcores of GRAPH.
Also return the node ordering with optimal coloring number as an
alist. The `car' of each element of the alist identifies kcores and
the `cdr' holds the nodes in the ordering."))
(defmethod degeneracy ((graph graph))
(let ((copy (copy graph))
(nodedegree (makehashtable))
(maxdegree 0) (numnodes 0) (k 0) (i 0)
bydegree output)
;; initialize
(mapc (lambda (n)
(let ((degree (degree copy n)))
(incf numnodes)
(setf (gethash n nodedegree) degree)
(setf maxdegree (max maxdegree degree))))
(nodes copy))
(setf bydegree (makearray (1+ maxdegree) :initialelement nil))
(maphash (lambda (node degree) (push node (aref bydegree degree)))
nodedegree)
;; reduction
(dotimes (n numnodes (values k output))
(setf i 0)
(loop :until (aref bydegree i) :do (incf i))
;; create alist element for the new core
(when (< k (setf k (max k i))) (push (list k) output))
;; drop a node and demote all neighbors
(let ((node (pop (aref bydegree i))))
(push node (cdr (assoc k output)))
(mapc (lambda (node)
(setf (aref bydegree (gethash node nodedegree))
(remove node (aref bydegree (gethash node nodedegree))))
(decf (gethash node nodedegree))
(push node (aref bydegree (gethash node nodedegree))))
(prog1 (removeduplicates (remove node (neighbors copy node)))
(deletenode copy node)))))))
(defgeneric kcores (graph)
(:documentation "Return the kcores of GRAPH."))
(defmethod kcores ((graph graph))
(multiplevaluebind (k cores) (degeneracy graph)
(declare (ignorable k)) cores))
