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 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804
|
package Graph;
use strict;
use warnings;
BEGIN { warnings->unimport('recursion') if $ENV{GRAPH_ALLOW_RECURSION} }
sub __carp_confess { require Carp; Carp::confess(@_) }
BEGIN {
if (0) { # SET THIS TO ZERO FOR TESTING AND RELEASES!
$SIG{__DIE__ } = \&__carp_confess;
$SIG{__WARN__} = \&__carp_confess;
}
}
use Graph::AdjacencyMap qw(:flags :fields);
our $VERSION = '0.9726';
require 5.006; # Weak references are absolutely required.
my @GRAPH_PROPS_COPIED = qw(
undirected refvertexed countvertexed multivertexed __stringified
hyperedged countedged multiedged
);
my $_empty_array = [];
sub _empty_array () { $_empty_array }
my $can_deep_copy_Storable;
sub _can_deep_copy_Storable () {
return $can_deep_copy_Storable if defined $can_deep_copy_Storable;
return $can_deep_copy_Storable = 0 if $] < 5.010; # no :load tag Safe 5.8
eval {
require Storable;
require B::Deparse;
Storable->VERSION(2.05);
B::Deparse->VERSION(0.61);
};
$can_deep_copy_Storable = !$@;
}
sub _F () { 0 } # Flags.
sub _G () { 1 } # Generation.
sub _V () { 2 } # Vertices.
sub _E () { 3 } # Edges.
sub _A () { 4 } # Attributes.
sub _U () { 5 } # Union-Find.
my $Inf;
BEGIN {
if ($] >= 5.022) {
$Inf = eval '+"Inf"'; # uncoverable statement
} else {
local $SIG{FPE}; # uncoverable statement
eval { $Inf = exp(999) } || # uncoverable statement
eval { $Inf = 9**9**9 } || # uncoverable statement
eval { $Inf = 1e+999 } || # uncoverable statement
{ $Inf = 1e+99 }; # uncoverable statement
# Close enough for most practical purposes.
}
}
sub Infinity () { $Inf }
# Graphs are blessed array references.
# - The first element contains the flags.
# - The second element is the vertices.
# - The third element is the edges.
# - The fourth element is the attributes of the whole graph.
# The defined flags for Graph are:
# - unionfind
# The vertices are contained in a "simplemap"
# (if no attributes) or in a "map".
# The edges are always in a "map".
# The defined flags for maps are:
# - _COUNT for countedness: more than one instance
# expects one for vertices and two for edges
# - _UNORD for unordered coordinates (a set): if _UNORD is not set
# the coordinates are assumed to be meaningfully ordered
# Vertices and edges assume none of these flags.
use Graph::Attribute array => _A, map => 'graph';
sub stringify {
my ($u, $h) = (&is_undirected, &is_hyperedged);
my $e = $u ? '=' : '-';
my @edges = map join($e,
$u ? sort { "$a" cmp "$b" } @$_ :
$h ? map '['.join(",", sort { "$a" cmp "$b" } @$_).']', @$_ :
@$_), &_edges05;
my @s = sort @edges;
push @s, sort { "$a" cmp "$b" } &isolated_vertices;
join(",", @s);
}
sub eq {
"$_[0]" eq "$_[1]"
}
sub boolify {
1; # Important for empty graphs: they stringify to "", which is false.
}
sub ne {
"$_[0]" ne "$_[1]"
}
use overload
'""' => \&stringify,
'bool' => \&boolify,
'eq' => \&eq,
'ne' => \≠
sub _opt {
my ($opt, $flags, %flags) = @_;
while (my ($flag, $FLAG) = each %flags) {
$$flags |= $FLAG if delete $opt->{$flag};
$$flags &= ~$FLAG if delete $opt->{"non$flag"};
}
}
sub _opt_get {
my ($opt, $key, $var) = @_;
return if !exists $opt->{$key};
$$var = delete $opt->{$key};
}
sub _opt_unknown {
my ($opt) = @_;
return unless my @opt = keys %$opt;
__carp_confess sprintf
"@{[(caller(1))[3]]}: Unknown option%s: @{[map qq['$_'], sort @opt]}",
@opt > 1 ? 's' : '';
}
sub _opt_from_existing {
my ($g) = @_;
my %existing;
$existing{$_}++ for grep $g->$_, @GRAPH_PROPS_COPIED;
$existing{unionfind}++ if $g->has_union_find;
%existing;
}
sub _opt_to_vflags {
my ($vflags, $opt) = (0, @_);
_opt($opt, \$vflags,
countvertexed => _COUNT,
multivertexed => _MULTI,
refvertexed => _REF,
refvertexed_stringified => _REFSTR ,
__stringified => _STR,
);
$vflags;
}
sub _opt_to_eflags {
my ($eflags, $opt) = (0, @_);
$opt->{undirected} = !delete $opt->{directed} if exists $opt->{directed};
_opt($opt, \$eflags,
countedged => _COUNT,
multiedged => _MULTI,
undirected => _UNORD,
);
($eflags, delete $opt->{hyperedged});
}
sub new {
my ($class, @args) = @_;
my $gflags = 0;
my %opt = _get_options( \@args );
%opt = (_opt_from_existing($class), %opt) # allow overrides
if ref $class && $class->isa('Graph');
my $vflags = _opt_to_vflags(\%opt);
my ($eflags, $is_hyper) = _opt_to_eflags(\%opt);
_opt(\%opt, \$gflags,
unionfind => _UNIONFIND,
);
my @V;
if ($opt{vertices}) {
__carp_confess "Graph: vertices should be an array ref"
if ref $opt{vertices} ne 'ARRAY';
@V = @{ delete $opt{vertices} };
}
my @E;
if ($opt{edges}) {
__carp_confess "Graph: edges should be an array ref of array refs"
if ref $opt{edges} ne 'ARRAY';
@E = @{ delete $opt{edges} };
}
_opt_unknown(\%opt);
__carp_confess "Graph: both countvertexed and multivertexed"
if ($vflags & _COUNT) && ($vflags & _MULTI);
__carp_confess "Graph: both countedged and multiedged"
if ($eflags & _COUNT) && ($eflags & _MULTI);
my $g = bless [ ], ref $class || $class;
$g->[ _F ] = $gflags;
$g->[ _G ] = 0;
$g->[ _V ] = _make_v($vflags);
$g->[ _E ] = _make_e($is_hyper, $eflags);
$g->add_vertices(@V) if @V;
__carp_confess "Graph: edges should be array refs"
if grep ref $_ ne 'ARRAY', @E;
$g->add_edges(@E);
$g->[ _U ] = do { require Graph::UnionFind; Graph::UnionFind->new }
if $gflags & _UNIONFIND;
return $g;
}
sub _make_v {
my ($vflags) = @_;
$vflags ? _am_heavy($vflags, 1) : _am_light($vflags, 1);
}
sub _make_e {
my ($is_hyper, $eflags) = @_;
($is_hyper or $eflags & ~_UNORD) ?
_am_heavy($eflags, $is_hyper ? 0 : 2) :
_am_light($eflags, 2);
}
sub _am_light {
require Graph::AdjacencyMap::Light;
Graph::AdjacencyMap::Light->_new(@_);
}
sub _am_heavy {
Graph::AdjacencyMap->_new(@_);
}
sub countvertexed { $_[0]->[ _V ]->_is_COUNT }
sub multivertexed { $_[0]->[ _V ]->_is_MULTI }
sub refvertexed { $_[0]->[ _V ]->_is_REF }
sub refvertexed_stringified { $_[0]->[ _V ]->_is_REFSTR }
sub __stringified { $_[0]->[ _V ]->_is_STR }
sub countedged { $_[0]->[ _E ]->_is_COUNT }
sub multiedged { $_[0]->[ _E ]->_is_MULTI }
sub hyperedged { !$_[0]->[ _E ]->[ _arity ] }
sub undirected { $_[0]->[ _E ]->_is_UNORD }
sub directed { ! $_[0]->[ _E ]->_is_UNORD }
*is_directed = \&directed;
*is_undirected = \&undirected;
*is_countvertexed = \&countvertexed;
*is_multivertexed = \&multivertexed;
*is_refvertexed = \&refvertexed;
*is_refvertexed_stringified = \&refvertexed_stringified;
*is_countedged = \&countedged;
*is_multiedged = \&multiedged;
*is_hyperedged = \&hyperedged;
sub has_union_find { $_[0]->[ _U ] }
sub add_vertex {
__carp_confess "Graph::add_vertex: use add_vertices for more than one vertex" if @_ != 2;
__carp_confess "Graph::add_vertex: undef vertex" if grep !defined, @_;
goto &add_vertices;
}
sub has_vertex {
my $g = $_[0];
my $V = $g->[ _V ];
return defined $V->has_path($_[1]) if ($V->[ _f ] & _REF);
exists $V->[ _pi ]->{ $_[1] };
}
sub _vertices05 {
my $g = $_[0];
$g->[ _V ]->paths;
}
sub vertices {
my $g = $_[0];
my @v = &_vertices05;
return @v if !(&is_multivertexed || &is_countvertexed);
return map +(($_) x $g->get_vertex_count($_)), @v if wantarray;
my $V = 0;
$V += $g->get_vertex_count($_) for @v;
return $V;
}
*unique_vertices = \&_vertices05;
sub has_vertices {
my $g = shift;
scalar $g->[ _V ]->has_any_paths;
}
sub add_edge {
&expect_hyperedged, &expect_undirected if @_ != 3;
$_[0]->add_edges([ @_[1..$#_] ]);
}
sub _vertex_ids_ensure {
push @_, 1;
goto &_vertex_ids_maybe_ensure;
}
sub _vertex_ids_ensure_multi {
my $id = pop;
my @i = &_vertex_ids_ensure;
push @_, $id;
@i ? (@i, $id) : ();
}
sub _vertex_ids {
push @_, 0;
goto &_vertex_ids_maybe_ensure;
}
sub _vertex_ids_multi {
my $id = pop;
my @i = &_vertex_ids;
push @_, $id;
@i ? (@i, $id) : ();
}
sub _vertex_ids_maybe_ensure {
my $ensure = pop;
my ($g, @args) = @_;
__carp_confess "Graph: given undefined vertex" if grep !defined, @args;
my $V = $g->[ _V ];
my $deep = &is_hyperedged && &is_directed;
return $V->get_ids_by_paths(\@args, $ensure, $deep) if ($V->[ _f ] & _REF) or $deep;
my $pi = $V->[ _pi ];
my @non_exist = grep !exists $pi->{ $_ }, @args;
return if !$ensure and @non_exist;
$V->get_ids_by_paths(\@non_exist, 1) if @non_exist;
@$pi{ @args };
}
sub has_edge {
my $g = $_[0];
my $E = $g->[ _E ];
my ($Ef, $Ea) = @$E[ _f, _arity ];
return 0 if $Ea and @_ != $Ea + 1;
my $directed = &is_directed;
my $deep = &is_hyperedged && $directed;
return 0 if (my @i = &_vertex_ids) != @_ - 1;
return defined $E->has_path($directed ? \@i : [ map [ sort @$_ ], @i ]) if $deep;
@i = sort @i if !$directed;
exists $E->[ _pi ]{ "@i" };
}
sub any_edge {
my ($g, @args) = @_;
my $E = $g->[ _E ];
my $V = $g->[ _V ];
return 0 if (my @i = $V->get_ids_by_paths(\@args)) != @args;
$E->has_successor(@i);
}
sub _edges05 {
my $g = $_[0];
my @e = $g->[ _E ]->paths;
return @e if !wantarray;
$g->[ _V ]->get_paths_by_ids(\@e, &is_hyperedged && &is_directed);
}
*unique_edges = \&_edges05;
sub edges {
my $g = $_[0];
my @e = &_edges05;
return @e if !(&is_multiedged || &is_countedged);
return map +(($_) x $g->get_edge_count(@$_)), @e if wantarray;
my $E = 0;
$E += $g->get_edge_count(@$_) for @e;
return $E;
}
sub has_edges {
scalar $_[0]->[ _E ]->has_any_paths;
}
###
# by_id
#
sub add_vertex_by_id {
&expect_multivertexed;
my ($g, $v, $id) = @_;
my $V = $g->[ _V ];
return $g if $V->has_path_by_multi_id( my @args = ($v, $id) );
my ($i) = $V->set_path_by_multi_id( @args );
$g->[ _U ]->add($i) if &has_union_find;
$g->[ _G ]++;
return $g;
}
sub add_vertex_get_id {
&expect_multivertexed;
my ($g, $v) = @_;
my ($i, $multi_id) = $g->[ _V ]->set_path_by_multi_id( $v, _GEN_ID );
$g->[ _U ]->add($i) if &has_union_find;
$g->[ _G ]++;
return $multi_id;
}
sub has_vertex_by_id {
&expect_multivertexed;
my ($g, $v, $id) = @_;
$g->[ _V ]->has_path_by_multi_id( $v, $id );
}
sub delete_vertex_by_id {
&expect_multivertexed;
&expect_non_unionfind;
my ($g, $v, $id) = @_;
return $g unless &has_vertex_by_id;
# TODO: what to about the edges at this vertex?
# If the multiness of this vertex goes to zero, delete the edges?
$g->[ _V ]->del_path_by_multi_id( $v, $id );
$g->[ _G ]++;
return $g;
}
sub get_multivertex_ids {
&expect_multivertexed;
my $g = shift;
$g->[ _V ]->get_multi_ids( @_ );
}
sub add_edge_by_id {
&expect_multiedged;
my $g = $_[0];
my @i = &_vertex_ids_ensure_multi;
my $id = pop @i;
@i = sort @i if &is_undirected;
$g->[ _E ]->set_path_by_multi_id( \@i, $id );
$g->[ _G ]++;
$g->[ _U ]->union(\@i) if &has_union_find;
return $g;
}
sub add_edge_get_id {
&expect_multiedged;
my $g = $_[0];
my @i = &_vertex_ids_ensure;
@i = sort @i if &is_undirected;
my (undef, $id) = $g->[ _E ]->set_path_by_multi_id( \@i, _GEN_ID );
$g->[ _G ]++;
$g->[ _U ]->union(\@i) if &has_union_find;
return $id;
}
sub has_edge_by_id {
&expect_multiedged;
my $g = $_[0];
my @i = &_vertex_ids_multi;
return 0 if @i < @_ - 2;
my $id = pop @i;
@i = sort @i if &is_undirected;
$g->[ _E ]->has_path_by_multi_id( \@i, $id );
}
sub delete_edge_by_id {
&expect_multiedged;
&expect_non_unionfind;
my $g = $_[0];
my $E = $g->[ _E ];
my @i = &_vertex_ids_multi;
return if @i < @_ - 2;
my $id = pop @i;
@i = sort @i if &is_undirected;
return unless $E->has_path_by_multi_id( my @args = (\@i, $id) );
$E->del_path_by_multi_id( @args );
$g->[ _G ]++;
return $g;
}
sub get_multiedge_ids {
&expect_multiedged;
return unless @_-1 == (my @i = &_vertex_ids);
$_[0]->[ _E ]->get_multi_ids( \@i );
}
###
# Neighbourhood.
#
sub _edges_at {
goto &_edges_from if &is_undirected;
require Set::Object;
Set::Object->new(&_edges_from, &_edges_to)->${ wantarray ? \'members' : \'size' };
}
sub _edges_from {
my ($g, @args) = @_;
my ($V, $E) = @$g[ _V, _E ];
return if (my @i = $V->get_ids_by_paths(\@args, &is_hyperedged && &is_directed)) != @args;
$E->paths_from(@i);
}
sub _edges_to {
goto &_edges_from if &is_undirected;
my ($g, @args) = @_;
my ($V, $E) = @$g[ _V, _E ];
return if (my @i = $V->get_ids_by_paths(\@args, &is_hyperedged && &is_directed)) != @args;
$E->paths_to(@i);
}
sub edges_at {
goto &_edges_at if !wantarray;
$_[0]->[ _V ]->get_paths_by_ids([ &_edges_at ], &is_hyperedged && &is_directed);
}
sub edges_from {
goto &_edges_from if !wantarray;
$_[0]->[ _V ]->get_paths_by_ids([ &_edges_from ], &is_hyperedged && &is_directed);
}
sub edges_to {
goto &edges_from if &is_undirected;
goto &_edges_to if !wantarray;
$_[0]->[ _V ]->get_paths_by_ids([ &_edges_to ], &is_hyperedged && &is_directed);
}
sub successors {
my ($g, @args) = @_;
my ($V, $E) = @$g[ _V, _E ];
return if (my @i = $V->get_ids_by_paths(\@args)) != @args;
my @v = $E->successors(@i);
return @v if !wantarray;
map @$_, $V->get_paths_by_ids([ \@v ]);
}
sub predecessors {
goto &successors if &is_undirected;
my ($g, @args) = @_;
my ($V, $E) = @$g[ _V, _E ];
return if (my @i = $V->get_ids_by_paths(\@args)) != @args;
my @v = $E->predecessors(@i);
return @v if !wantarray;
map @$_, $V->get_paths_by_ids([ \@v ]);
}
sub _cessors_by_radius {
my ($radius, $method, $self_only_if_loop) = splice @_, -3, 3;
my ($g, @v) = @_;
require Set::Object;
my ($init, $next) = map Set::Object->new(@v), 1..2;
my $self = Set::Object->new(grep $g->has_edge($_, $_), @v) if $self_only_if_loop;
my ($got, $found) = map Set::Object->new, 1..2;
while (!defined $radius or $radius-- > 0) {
$found->insert($g->$method($next->members));
$next = $found->difference($got);
last if $next->is_null; # Leave if no new found.
$got->insert($next->members);
$found->clear;
}
$got->remove($init->difference($self)->members) if $self_only_if_loop;
$got->${ wantarray ? \'members' : \'size' };
}
sub all_successors {
&expect_directed;
push @_, undef, 'successors', 0;
goto &_cessors_by_radius;
}
sub successors_by_radius {
&expect_directed;
push @_, 'successors', 0;
goto &_cessors_by_radius;
}
sub all_predecessors {
&expect_directed;
push @_, undef, 'predecessors', 0;
goto &_cessors_by_radius;
}
sub predecessors_by_radius {
&expect_directed;
push @_, 'predecessors', 0;
goto &_cessors_by_radius;
}
sub neighbours_by_radius {
push @_, 'neighbours', 1;
goto &_cessors_by_radius;
}
*neighbors_by_radius = \&neighbours_by_radius;
sub neighbours {
require Set::Object;
my $s = Set::Object->new(&successors);
$s->insert(&predecessors) if &is_directed;
$s->${ wantarray ? \'members' : \'size' };
}
*neighbors = \&neighbours;
sub all_neighbours {
push @_, undef, 'neighbours', 1;
goto &_cessors_by_radius;
}
*all_neighbors = \&all_neighbours;
sub all_reachable {
&directed ? goto &all_successors : goto &all_neighbors;
}
sub reachable_by_radius {
&directed ? goto &successors_by_radius : goto &neighbors_by_radius;
}
sub delete_edge {
&expect_non_unionfind;
my $g = $_[0];
return $g if (my @i = &_vertex_ids) != @_ - 1;
@i = sort @i if &is_undirected;
return $g unless @i and $g->[ _E ]->del_path( \@i );
$g->[ _G ]++;
return $g;
}
sub delete_vertex {
&expect_non_unionfind;
my $g = $_[0];
return $g if @_ != 2;
my $V = $g->[ _V ];
return $g unless defined $V->has_path($_[1]);
# TODO: _edges_at is excruciatingly slow (rt.cpan.org 92427)
my $E = $g->[ _E ];
$E->del_path( $_ ) for &_edges_at;
$V->del_path($_[1]);
$g->[ _G ]++;
return $g;
}
sub get_vertex_count {
my $g = shift;
$g->[ _V ]->_get_path_count( @_ );
}
sub get_edge_count {
my $g = $_[0];
return 0 if (my @i = &_vertex_ids) != @_ - 1;
@i = sort @i if &is_undirected;
$g->[ _E ]->_get_path_count( \@i );
}
sub delete_vertices {
&expect_non_unionfind;
my $g = shift;
while (@_) {
my $v = shift @_;
$g->delete_vertex($v);
}
return $g;
}
sub delete_edges {
&expect_non_unionfind;
my $g = shift;
while (@_) {
my ($u, $v) = splice @_, 0, 2;
$g->delete_edge($u, $v);
}
return $g;
}
###
# Degrees.
#
sub in_degree {
my $g = $_[0];
return undef unless @_ > 1 && &has_vertex;
my $in = 0;
$in += $g->get_edge_count( @$_ ) for &edges_to;
$in++ if &is_undirected and &is_self_loop_vertex;
return $in;
}
sub out_degree {
my $g = $_[0];
return undef unless @_ > 1 && &has_vertex;
my $out = 0;
$out += $g->get_edge_count( @$_ ) for &edges_from;
$out++ if &is_undirected and &is_self_loop_vertex;
return $out;
}
sub _total_degree {
return undef unless @_ > 1 && &has_vertex;
&is_undirected ? &in_degree : &in_degree - &out_degree;
}
sub degree {
goto &_total_degree if @_ > 1;
return 0 if &is_directed;
my $g = $_[0];
my $total = 0;
$total += $g->_total_degree( $_ ) for &_vertices05;
return $total;
}
*vertex_degree = \°ree;
sub is_sink_vertex {
return 0 unless @_ > 1;
&successors == 0 && &predecessors > 0;
}
sub is_source_vertex {
return 0 unless @_ > 1;
&predecessors == 0 && &successors > 0;
}
sub is_successorless_vertex {
return 0 unless @_ > 1;
&successors == 0;
}
sub is_predecessorless_vertex {
return 0 unless @_ > 1;
&predecessors == 0;
}
sub is_successorful_vertex {
return 0 unless @_ > 1;
&successors > 0;
}
sub is_predecessorful_vertex {
return 0 unless @_ > 1;
&predecessors > 0;
}
sub is_isolated_vertex {
return 0 unless @_ > 1;
&predecessors == 0 && &successors == 0;
}
sub is_interior_vertex {
return 0 unless @_ > 1;
my $s = &successors;
$s-- if my $isl = &is_self_loop_vertex;
return 0 if $s == 0;
return $s > 0 if &is_undirected;
my $p = &predecessors;
$p-- if $isl;
$p > 0;
}
sub is_exterior_vertex {
return 0 unless @_ > 1;
&predecessors == 0 || &successors == 0;
}
sub is_self_loop_vertex {
return 0 unless @_ > 1;
return 1 if grep $_ eq $_[1], &successors; # @todo: multiedges
return 0;
}
for my $p (qw(
is_sink_vertex
is_source_vertex
is_successorless_vertex
is_predecessorless_vertex
is_successorful_vertex
is_predecessorful_vertex
is_isolated_vertex
is_interior_vertex
is_exterior_vertex
is_self_loop_vertex
)) {
no strict 'refs';
(my $m = $p) =~ s/^is_(.*)ex$/${1}ices/;
*$m = sub { my $g = $_[0]; grep $g->$p($_), &_vertices05 };
}
###
# Paths and cycles.
#
sub add_path {
my $g = shift;
my $u = shift;
my @edges;
while (@_) {
my $v = shift;
push @edges, [ $u, $v ];
$u = $v;
}
$g->add_edges(@edges);
return $g;
}
sub delete_path {
&expect_non_unionfind;
my $g = shift;
my $u = shift;
while (@_) {
my $v = shift;
$g->delete_edge($u, $v);
$u = $v;
}
return $g;
}
sub has_path {
my $g = shift;
my $u = shift;
while (@_) {
my $v = shift;
return 0 unless $g->has_edge($u, $v);
$u = $v;
}
return $g;
}
sub add_cycle {
push @_, $_[1];
goto &add_path;
}
sub delete_cycle {
&expect_non_unionfind;
push @_, $_[1];
goto &delete_path;
}
sub has_cycle {
return 0 if @_ == 1;
push @_, $_[1];
goto &has_path;
}
*has_this_cycle = \&has_cycle;
sub has_a_cycle {
my $g = shift;
require Graph::Traversal::DFS;
my $t = Graph::Traversal::DFS->new($g, has_a_cycle => 1, @_);
$t->dfs;
return $t->get_state('has_a_cycle');
}
sub find_a_cycle {
require Graph::Traversal::DFS;
my @r = ( back_edge => \&Graph::Traversal::find_a_cycle);
push @r,
down_edge => \&Graph::Traversal::find_a_cycle
if &is_undirected;
my $g = shift;
my $t = Graph::Traversal::DFS->new($g, @r, @_);
$t->dfs;
$t->has_state('a_cycle') ? @{ $t->get_state('a_cycle') } : ();
}
###
# Attributes.
my @generic_methods = (
[ 'set_attribute', \&_set_attribute ],
[ 'set_attributes', \&_set_attributes ],
[ 'has_attributes', \&_has_attributes ],
[ 'has_attribute', \&_has_attribute ],
[ 'get_attributes', \&_get_attributes ],
[ 'get_attribute', \&_get_attribute ],
[ 'get_attribute_names', \&_get_attribute_names ],
[ 'get_attribute_values', \&_get_attribute_values ],
[ 'delete_attributes', \&_delete_attributes ],
[ 'delete_attribute', \&_delete_attribute ],
);
my %entity2offset = (vertex => _V, edge => _E);
my %entity2args = (edge => '_vertex_ids');
for my $entity (qw(vertex edge)) {
no strict 'refs';
my $expect_non = \&{ "expect_non_multi${entity}" };
my $expect_yes = \&{ "expect_multi${entity}" };
my $args_non = \&{ $entity2args{$entity} } if $entity2args{$entity};
my $args_yes = \&{ $entity2args{$entity}.'_multi' } if $entity2args{$entity};
my $offset = $entity2offset{$entity};
for my $t (@generic_methods) {
my ($raw, $func) = @$t;
my ($first, $rest) = ($raw =~ /^(\w+?)_(.+)/);
my $m = join '_', $first, $entity, $rest;
my $is_vertex = $entity eq 'vertex';
*$m = sub {
&$expect_non; push @_, 0, $entity, $offset, $args_non, $is_vertex; goto &$func;
};
*{$m.'_by_id'} = sub {
&$expect_yes; push @_, 1, $entity, $offset, $args_yes, $is_vertex; goto &$func;
};
}
}
sub _munge_args {
my ($is_vertex, $is_multi, $is_undirected, @args) = @_;
return \@args if !$is_vertex and !$is_undirected and !$is_multi;
return [ sort @args ] if !$is_vertex and !$is_multi;
return @args if $is_vertex;
my $id = pop @args;
($is_undirected ? [ sort @args ] : \@args, $id);
}
sub _set_attribute {
my ($is_multi, $entity, $offset, $args, $is_vertex) = splice @_, -5, 5;
my $value = pop;
my $attr = pop;
no strict 'refs';
&{ 'add_' . $entity . ($is_multi ? '_by_id' : '') } unless &{ 'has_' . $entity . ($is_multi ? '_by_id' : '') };
my @args = ($entity eq 'edge') ? &$args : @_[1..$#_];
@args = _munge_args($is_vertex, $is_multi, &is_undirected, @args);
$_[0]->[ $offset ]->_set_path_attr( @args, $attr, $value );
}
sub _set_attributes {
my ($is_multi, $entity, $offset, $args, $is_vertex) = splice @_, -5, 5;
my $attr = pop;
no strict 'refs';
&{ 'add_' . $entity . ($is_multi ? '_by_id' : '') } unless &{ 'has_' . $entity . ($is_multi ? '_by_id' : '') };
my @args = ($entity eq 'edge') ? &$args : @_[1..$#_];
@args = _munge_args($is_vertex, $is_multi, &is_undirected, @args);
$_[0]->[ $offset ]->_set_path_attrs( @args, $attr );
}
sub _has_attributes {
my ($is_multi, $entity, $offset, $args, $is_vertex) = splice @_, -5, 5;
no strict 'refs';
return 0 unless &{ 'has_' . $entity . ($is_multi ? '_by_id' : '') };
my @args = ($entity eq 'edge') ? &$args : @_[1..$#_];
@args = _munge_args($is_vertex, $is_multi, &is_undirected, @args);
$_[0]->[ $offset ]->_has_path_attrs( @args );
}
sub _has_attribute {
my ($is_multi, $entity, $offset, $args, $is_vertex) = splice @_, -5, 5;
my $attr = pop;
no strict 'refs';
return 0 unless &{ 'has_' . $entity . ($is_multi ? '_by_id' : '') };
my @args = ($entity eq 'edge') ? &$args : @_[1..$#_];
@args = _munge_args($is_vertex, $is_multi, &is_undirected, @args);
$_[0]->[ $offset ]->_has_path_attr( @args, $attr );
}
sub _get_attributes {
my ($is_multi, $entity, $offset, $args, $is_vertex) = splice @_, -5, 5;
no strict 'refs';
return undef unless &{ 'has_' . $entity . ($is_multi ? '_by_id' : '') };
my @args = ($entity eq 'edge') ? &$args : @_[1..$#_];
@args = _munge_args($is_vertex, $is_multi, &is_undirected, @args);
scalar $_[0]->[ $offset ]->_get_path_attrs( @args );
}
sub _get_attribute {
my ($is_multi, $entity, $offset, $args, $is_vertex) = splice @_, -5, 5;
no strict 'refs';
my $attr = pop;
return undef unless &{ 'has_' . $entity . ($is_multi ? '_by_id' : '') };
my @args = ($entity eq 'edge') ? &$args : @_[1..$#_];
@args = _munge_args($is_vertex, $is_multi, &is_undirected, @args);
scalar $_[0]->[ $offset ]->_get_path_attr( @args, $attr );
}
sub _get_attribute_names {
my ($is_multi, $entity, $offset, $args, $is_vertex) = splice @_, -5, 5;
no strict 'refs';
return unless &{ 'has_' . $entity . ($is_multi ? '_by_id' : '') };
my @args = ($entity eq 'edge') ? &$args : @_[1..$#_];
@args = _munge_args($is_vertex, $is_multi, &is_undirected, @args);
$_[0]->[ $offset ]->_get_path_attr_names( @args );
}
sub _get_attribute_values {
my ($is_multi, $entity, $offset, $args, $is_vertex) = splice @_, -5, 5;
no strict 'refs';
return unless &{ 'has_' . $entity . ($is_multi ? '_by_id' : '') };
my @args = ($entity eq 'edge') ? &$args : @_[1..$#_];
@args = _munge_args($is_vertex, $is_multi, &is_undirected, @args);
$_[0]->[ $offset ]->_get_path_attr_values( @args );
}
sub _delete_attributes {
my ($is_multi, $entity, $offset, $args, $is_vertex) = splice @_, -5, 5;
no strict 'refs';
return undef unless &{ 'has_' . $entity . ($is_multi ? '_by_id' : '') };
my @args = ($entity eq 'edge') ? &$args : @_[1..$#_];
@args = _munge_args($is_vertex, $is_multi, &is_undirected, @args);
$_[0]->[ $offset ]->_del_path_attrs( @args );
}
sub _delete_attribute {
my ($is_multi, $entity, $offset, $args, $is_vertex) = splice @_, -5, 5;
my $attr = pop;
no strict 'refs';
return undef unless &{ 'has_' . $entity . ($is_multi ? '_by_id' : '') };
my @args = ($entity eq 'edge') ? &$args : @_[1..$#_];
@args = _munge_args($is_vertex, $is_multi, &is_undirected, @args);
$_[0]->[ $offset ]->_del_path_attr( @args, $attr );
}
sub add_vertices {
my ($g, @v) = @_;
if (&is_multivertexed) {
$g->add_vertex_by_id($_, _GEN_ID) for @v;
return $g;
}
my @i = $g->[ _V ]->set_paths(@v);
$g->[ _G ]++;
return $g if !&has_union_find;
$g->[ _U ]->add(@i);
$g;
}
sub add_edges {
my ($g, @args) = @_;
my @edges;
while (defined(my $u = shift @args)) {
push @edges, ref $u eq 'ARRAY' ? $u : @args ? [ $u, shift @args ]
: __carp_confess "Graph::add_edges: missing end vertex";
}
if (&is_multiedged) {
$g->add_edge_by_id(@$_, _GEN_ID) for @edges;
return $g;
}
my $uf = &has_union_find;
my $deep = &is_hyperedged && &is_directed;
my @paths = $g->[ _V ]->get_ids_by_paths(\@edges, 1, 1 + ($deep ? 1 : 0));
@paths = map [ sort @$_ ], @paths if &is_undirected;
$g->[ _E ]->set_paths( @paths );
$uf->union(@paths) if $uf;
$g->[ _G ]++;
return $g;
}
sub rename_vertex {
my $g = shift;
$g->[ _V ]->rename_path(@_);
return $g;
}
sub rename_vertices {
my ($g, $code) = @_;
my %seen;
$g->rename_vertex($_, $code->($_))
for grep !$seen{$_}++, $g->[ _V ]->paths;
return $g;
}
sub as_hashes {
my ($g) = @_;
my (%v, %e, @e);
my ($is_hyper, $is_directed)= (&is_hyperedged, &is_directed);
if (&is_multivertexed) {
for my $v ($g->unique_vertices) {
$v{$v} = {
map +($_ => $g->get_vertex_attributes_by_id($v, $_) || {}),
$g->get_multivertex_ids($v)
};
}
} else {
%v = map +($_ => $g->get_vertex_attributes($_) || {}), $g->unique_vertices;
}
my $multi_e = &is_multiedged;
for my $e ($g->edges) {
my $edge_attr = {
$multi_e
? map +($_ => $g->get_edge_attributes_by_id(@$e, $_) || {}),
$g->get_multiedge_ids(@$e)
: %{ $g->get_edge_attributes(@$e)||{} }
};
if ($is_hyper) {
my %h = (attributes => $edge_attr);
if ($is_directed) {
@h{qw(predecessors successors)} = @$e;
} else {
$h{vertices} = $e;
}
push @e, \%h;
} else {
$e{ $e->[0] }{ $e->[1] } = $edge_attr;
$e{ $e->[1] }{ $e->[0] } = $edge_attr if !$is_directed;
}
}
( \%v, $is_hyper ? \@e : \%e );
}
sub ingest {
my ($g, $g2) = @_;
for my $v ($g2->vertices) {
if (&is_multivertexed) {
$g->set_vertex_attributes_by_id($v, $_, $g2->get_vertex_attributes_by_id($v, $_))
for $g2->get_multivertex_ids($v);
} else {
$g->set_vertex_attributes($v, $g2->get_vertex_attributes($v));
}
if (&is_multiedged) {
for my $e ($g2->edges_from($v)) {
$g->set_edge_attributes_by_id(@$e, $_, $g2->get_edge_attributes_by_id(@$e, $_))
for $g2->get_multiedge_ids(@$e);
}
} else {
$g->set_edge_attributes(@$_, $g2->get_edge_attributes(@$_))
for $g2->edges_from($v);
}
}
$g;
}
###
# More constructors.
#
sub copy {
my ($g, @args) = @_;
my %opt = _get_options( \@args );
no strict 'refs';
my $c = (ref $g)->new(map +($_ => &$_ ? 1 : 0), @GRAPH_PROPS_COPIED);
$c->add_vertices(&isolated_vertices);
$c->add_edges(&_edges05);
return $c;
}
*copy_graph = \©
sub _deep_copy_best {
_can_deep_copy_Storable()
? _deep_copy_Storable(@_) : _deep_copy_DataDumper(@_);
}
sub _deep_copy_Storable {
my $g = shift;
require Safe; # For deep_copy().
my $safe = Safe->new;
$safe->permit(qw/:load/);
local $Storable::Deparse = 1;
local $Storable::Eval = sub { $safe->reval($_[0]) };
return Storable::thaw(Storable::freeze($g));
}
sub _deep_copy_DataDumper {
my $g = shift;
require Data::Dumper;
my $d = Data::Dumper->new([$g]);
use vars qw($VAR1);
$d->Purity(1)->Terse(1)->Deepcopy(1);
$d->Deparse(1) if $] >= 5.008;
eval $d->Dump;
}
sub deep_copy {
local $. = $.;
my $g2 = _deep_copy_best(@_);
$g2->[ _V ]->reindex if grep ref, &_vertices05;
$g2;
}
*deep_copy_graph = \&deep_copy;
sub transpose_edge {
my $g = $_[0];
return $g if !&is_directed;
return undef unless &has_edge;
my $c = &get_edge_count;
my $a = &get_edge_attributes;
my @e = reverse @_[1..$#_];
&delete_edge unless $g->has_edge( @e );
$g->add_edges(map \@e, 1..$c);
$g->set_edge_attributes(@e, $a) if $a;
return $g;
}
sub transpose_graph {
my $t = ©
return $t if !&directed;
$t->transpose_edge(@$_) for &_edges05;
return $t;
}
*transpose = \&transpose_graph;
sub complete_graph {
my $directed = &is_directed;
my $c = &new;
my @v = &_vertices05;
my @edges;
for (my $i = $#v; $i >= 0; $i-- ) {
push @edges, map +([$v[$i], $v[$_]], $directed ? [$v[$_], $v[$i]] : ()),
0..$i - 1;
}
$c->add_edges(@edges);
return $c;
}
*complement = \&complement_graph;
sub complement_graph {
my $c = &complete_graph;
$c->delete_edge(@$_) for &edges;
return $c;
}
*complete = \&complete_graph;
sub subgraph {
my ($g, $src, $dst) = @_;
__carp_confess "Graph::subgraph: need src and dst array references"
unless ref $src eq 'ARRAY' && (!defined($dst) or ref $dst eq 'ARRAY');
require Set::Object;
my $s = $g->new;
my @u = grep $g->has_vertex($_), @$src;
my $v = Set::Object->new($dst ? grep $g->has_vertex($_), @$dst : @u);
$s->add_vertices(@u, $dst ? $v->members : ());
my $directed = &is_directed;
if ($directed) {
$s->add_edges(grep $v->contains($_->[1]), $g->edges_from(@u));
} else {
my $valid = $dst ? $v + Set::Object->new(@u) : $v;
$s->add_edges(
grep +($v->contains($_->[0]) || $v->contains($_->[1])) &&
($valid->contains($_->[0]) && $valid->contains($_->[1])),
$g->edges_from(@u)
);
}
return $s;
}
###
# Transitivity.
#
sub is_transitive {
my $g = shift;
require Graph::TransitiveClosure;
Graph::TransitiveClosure::is_transitive($g);
}
###
# Weighted vertices.
#
my $defattr = 'weight';
sub _defattr {
return $defattr;
}
sub add_weighted_vertex {
&expect_non_multivertexed;
push @_, $defattr, pop;
goto &set_vertex_attribute;
}
sub add_weighted_vertices {
&expect_non_multivertexed;
my $g = shift;
while (@_) {
my ($v, $w) = splice @_, 0, 2;
$g->set_vertex_attribute($v, $defattr, $w);
}
}
sub get_vertex_weight {
&expect_non_multivertexed;
push @_, $defattr;
goto &get_vertex_attribute;
}
sub has_vertex_weight {
&expect_non_multivertexed;
push @_, $defattr;
goto &has_vertex_attribute;
}
sub set_vertex_weight {
&expect_non_multivertexed;
push @_, $defattr, pop;
goto &set_vertex_attribute;
}
sub delete_vertex_weight {
&expect_non_multivertexed;
push @_, $defattr;
goto &delete_vertex_attribute;
}
sub add_weighted_vertex_by_id {
&expect_multivertexed;
push @_, $defattr, pop;
goto &set_vertex_attribute_by_id;
}
sub add_weighted_vertices_by_id {
&expect_multivertexed;
my $g = shift;
my $id = pop;
while (@_) {
my ($v, $w) = splice @_, 0, 2;
$g->add_vertex_by_id($v, $id);
$g->set_vertex_attribute_by_id($v, $id, $defattr, $w);
}
}
sub get_vertex_weight_by_id {
&expect_multivertexed;
push @_, $defattr;
goto &get_vertex_attribute_by_id;
}
sub has_vertex_weight_by_id {
&expect_multivertexed;
push @_, $defattr;
goto &has_vertex_attribute_by_id;
}
sub set_vertex_weight_by_id {
&expect_multivertexed;
push @_, $defattr, pop;
goto &set_vertex_attribute_by_id;
}
sub delete_vertex_weight_by_id {
&expect_multivertexed;
push @_, $defattr;
goto &delete_vertex_attribute_by_id;
}
###
# Weighted edges.
#
sub add_weighted_edge {
&expect_non_multiedged;
push @_, $defattr, pop;
goto &set_edge_attribute;
}
sub add_weighted_edges {
&expect_non_multiedged;
my $g = shift;
while (@_) {
my ($u, $v, $w) = splice @_, 0, 3;
$g->set_edge_attribute($u, $v, $defattr, $w);
}
}
sub add_weighted_edges_by_id {
&expect_multiedged;
my $g = shift;
my $id = pop;
while (@_) {
my ($u, $v, $w) = splice @_, 0, 3;
$g->set_edge_attribute_by_id($u, $v, $id, $defattr, $w);
}
}
sub add_weighted_path {
&expect_non_multiedged;
my $g = shift;
my $u = shift;
while (@_) {
my ($w, $v) = splice @_, 0, 2;
$g->set_edge_attribute($u, $v, $defattr, $w);
$u = $v;
}
}
sub get_edge_weight {
&expect_non_multiedged;
push @_, $defattr;
goto &get_edge_attribute;
}
sub has_edge_weight {
&expect_non_multiedged;
push @_, $defattr;
goto &has_edge_attribute;
}
sub set_edge_weight {
&expect_non_multiedged;
push @_, $defattr, pop;
goto &set_edge_attribute;
}
sub delete_edge_weight {
&expect_non_multiedged;
push @_, $defattr;
goto &delete_edge_attribute;
}
sub add_weighted_edge_by_id {
&expect_multiedged;
push @_, $defattr, pop;
goto &set_edge_attribute_by_id;
}
sub add_weighted_path_by_id {
&expect_multiedged;
my $g = shift;
my $id = pop;
my $u = shift;
while (@_) {
my ($w, $v) = splice @_, 0, 2;
$g->set_edge_attribute_by_id($u, $v, $id, $defattr, $w);
$u = $v;
}
}
sub get_edge_weight_by_id {
&expect_multiedged;
push @_, $defattr;
goto &get_edge_attribute_by_id;
}
sub has_edge_weight_by_id {
&expect_multiedged;
push @_, $defattr;
goto &has_edge_attribute_by_id;
}
sub set_edge_weight_by_id {
&expect_multiedged;
push @_, $defattr, pop;
goto &set_edge_attribute_by_id;
}
sub delete_edge_weight_by_id {
&expect_multiedged;
push @_, $defattr;
goto &delete_edge_attribute_by_id;
}
###
# Error helpers.
#
my %expected;
@expected{qw(directed undirected acyclic)} = qw(undirected directed cyclic);
sub _expected {
my $exp = shift;
my $got = @_ ? shift : $expected{$exp};
$got = defined $got ? ", got $got" : "";
if (my @caller2 = caller(2)) {
die "$caller2[3]: expected $exp graph$got, at $caller2[1] line $caller2[2].\n";
} else {
my @caller1 = caller(1); # uncoverable statement
die "$caller1[3]: expected $exp graph$got, at $caller1[1] line $caller1[2].\n"; # uncoverable statement
}
}
sub expect_no_args {
my $g = shift;
return unless @_;
my @caller1 = caller(1); # uncoverable statement
die "$caller1[3]: expected no arguments, got " . scalar @_ . ", at $caller1[1] line $caller1[2]\n"; # uncoverable statement
}
sub expect_undirected {
_expected('undirected') unless &is_undirected;
}
sub expect_directed {
_expected('directed') unless &is_directed;
}
sub expect_acyclic {
_expected('acyclic') unless &is_acyclic;
}
sub expect_dag {
my @got;
push @got, 'undirected' unless &is_directed;
push @got, 'cyclic' unless &is_acyclic;
_expected('directed acyclic', "@got") if @got;
}
sub expect_hyperedged {
_expected('hyperedged') unless &is_hyperedged;
}
sub expect_multivertexed {
_expected('multivertexed') unless &is_multivertexed;
}
*expect_multivertex = \&expect_multivertexed;
sub expect_non_multivertexed {
_expected('non-multivertexed') if &is_multivertexed;
}
*expect_non_multivertex = \&expect_non_multivertexed;
sub expect_non_multiedged {
_expected('non-multiedged') if &is_multiedged;
}
*expect_non_multiedge = \&expect_non_multiedged;
sub expect_multiedged {
_expected('multiedged') unless &is_multiedged;
}
*expect_multiedge = \&expect_multiedged;
sub expect_non_unionfind {
_expected('non-unionfind') if &has_union_find;
}
sub _get_options {
my @caller = caller(1);
unless (@_ == 1 && ref $_[0] eq 'ARRAY') {
die "$caller[3]: internal error: should be called with only one array ref argument, at $caller[1] line $caller[2].\n";
}
my @opt = @{ $_[0] };
unless (@opt % 2 == 0) {
die "$caller[3]: expected an options hash, got a non-even number of arguments, at $caller[1] line $caller[2].\n"; # uncoverable statement
}
return @opt;
}
###
# Random constructors and accessors.
#
sub __fisher_yates_shuffle (@) {
# From perlfaq4, but modified to be non-modifying.
my @a = @_;
my $i = @a;
while ($i--) {
my $j = int rand ($i+1);
@a[$i,$j] = @a[$j,$i];
}
return @a;
}
BEGIN {
sub _shuffle(@);
# Workaround for the Perl bug [perl #32383] where -d:Dprof and
# List::Util::shuffle do not like each other: if any debugging
# (-d) flags are on, fall back to our own Fisher-Yates shuffle.
# The bug was fixed by perl changes #26054 and #26062, which
# went to Perl 5.9.3. If someone tests this with a pre-5.9.3
# bleadperl that calls itself 5.9.3 but doesn't yet have the
# patches, oh, well.
*_shuffle = $^P && $] < 5.009003 ?
\&__fisher_yates_shuffle : do { require List::Util; \&List::Util::shuffle };
}
sub random_graph {
my $class = (@_ % 2) == 0 ? 'Graph' : shift;
my %opt = _get_options( \@_ );
__carp_confess "Graph::random_graph: argument 'vertices' missing or undef"
unless defined $opt{vertices};
srand delete $opt{random_seed} if exists $opt{random_seed};
my $random_edge = delete $opt{random_edge} if exists $opt{random_edge};
my @V;
if (my $ref = ref $opt{vertices}) {
__carp_confess "Graph::random_graph: argument 'vertices' illegal"
if $ref ne 'ARRAY';
@V = @{ $opt{vertices} };
} else {
@V = 0..($opt{vertices} - 1);
}
delete $opt{vertices};
my $V = @V;
my $C = $V * ($V - 1) / 2;
my $E;
__carp_confess "Graph::random_graph: both arguments 'edges' and 'edges_fill' specified"
if exists $opt{edges} && exists $opt{edges_fill};
$E = exists $opt{edges_fill} ? $opt{edges_fill} * $C : $opt{edges};
delete $opt{edges};
delete $opt{edges_fill};
my $g = $class->new(%opt);
$g->add_vertices(@V);
return $g if $V < 2;
$C *= 2 if my $is_directed = $g->directed;
$E = $C / 2 unless defined $E;
$E = int($E + 0.5);
my $p = $E / $C;
$random_edge = sub { $p } unless defined $random_edge;
# print "V = $V, E = $E, C = $C, p = $p\n";
__carp_confess "Graph::random_graph: needs to be countedged or multiedged ($E > $C)"
if $p > 1.0 && !($g->countedged || $g->multiedged);
# Shuffle the vertex lists so that the pairs at
# the beginning of the lists are not more likely.
my (%v1_v2, @edges);
my @V1 = _shuffle @V;
my @V2 = _shuffle @V;
LOOP:
while ($E) {
for my $v1 (@V1) {
for my $v2 (@V2) {
next if $v1 eq $v2; # TODO: allow self-loops?
my $q = $random_edge->($g, $v1, $v2, $p);
if ($q && ($q == 1 || rand() <= $q) &&
!exists $v1_v2{$v1}{$v2} &&
($is_directed ? 1 : !exists $v1_v2{$v2}{$v1})) {
$v1_v2{$v1}{$v2} = undef;
push @edges, [ $v1, $v2 ];
$E--;
last LOOP unless $E;
}
}
}
}
$g->add_edges(@edges);
}
sub random_vertex {
my @V = &_vertices05;
@V[rand @V];
}
sub random_edge {
my @E = &_edges05;
@E[rand @E];
}
sub random_successor {
my @S = &successors;
@S[rand @S];
}
sub random_predecessor {
my @P = &predecessors;
@P[rand @P];
}
###
# Algorithms.
#
my $MST_comparator = sub { ($_[0] || 0) <=> ($_[1] || 0) };
sub _MST_attr {
my $attr = shift;
my $attribute =
exists $attr->{attribute} ?
$attr->{attribute} : $defattr;
my $comparator =
exists $attr->{comparator} ?
$attr->{comparator} : $MST_comparator;
return ($attribute, $comparator);
}
sub _MST_edges {
my ($g, $attr) = @_;
my ($attribute, $comparator) = _MST_attr($attr);
map $_->[1],
sort { $comparator->($a->[0], $b->[0], $a->[1], $b->[1]) }
map [ $g->get_edge_attribute(@$_, $attribute), $_ ],
&_edges05;
}
sub MST_Kruskal {
&expect_undirected;
my ($g, %attr) = @_;
require Graph::UnionFind;
my $MST = Graph->new(directed => 0);
my $UF = Graph::UnionFind->new;
$UF->add(&_vertices05);
my @edges;
for my $e ($g->_MST_edges(\%attr)) {
my ($u, $v) = @$e; # TODO: hyperedges
next if $UF->same( @$e );
$UF->union([$u, $v]);
push @edges, [ $u, $v ];
}
$MST->add_edges(@edges);
return $MST;
}
sub _MST_add {
my ($g, $h, $HF, $r, $attr, $unseen) = @_;
$HF->add( Graph::MSTHeapElem->new( $r, $_, $g->get_edge_attribute( $r, $_, $attr ) ) )
for grep exists $unseen->{ $_ }, $g->successors( $r );
}
sub _next_alphabetic { shift; (sort keys %{ $_[0] })[0] }
sub _next_numeric { shift; (sort { $a <=> $b } keys %{ $_[0] })[0] }
sub _next_random { shift; (values %{ $_[0] })[ rand keys %{ $_[0] } ] }
sub _root_opt {
my ($g, @args) = @_;
my %opt = @args == 1 ? ( first_root => $args[0] ) : _get_options( \@args );
my %unseen;
my @unseen = $g->_vertices05;
@unseen{ @unseen } = @unseen;
@unseen = _shuffle @unseen;
my $r;
if (exists $opt{ start }) {
$opt{ first_root } = delete $opt{ start };
$opt{ next_root } = undef;
}
if (exists $opt{ first_root }) {
if (ref $opt{ first_root } eq 'CODE') {
$r = $opt{ first_root }->( $g, \%unseen );
} else {
$r = $opt{ first_root };
}
} else {
$r = shift @unseen;
}
my $next =
exists $opt{ next_root } ?
$opt{ next_root } :
$opt{ next_alphabetic } ?
\&_next_alphabetic :
$opt{ next_numeric } ?
\&_next_numeric :
\&_next_random;
my $code = ref $next eq 'CODE';
my $attr = exists $opt{ attribute } ? $opt{ attribute } : $defattr;
return ( \%opt, \%unseen, \@unseen, $r, $next, $code, $attr );
}
sub _heap_walk {
my ($g, $h, $add, $etc, $opt, $unseenh, $unseena, $r, $next, $code, $attr) = @_;
require Heap::Fibonacci;
my $HF = Heap::Fibonacci->new;
while (defined $r) {
# print "r = $r\n";
$add->($g, $h, $HF, $r, $attr, $unseenh, $etc);
delete $unseenh->{ $r };
while (defined $HF->top) {
my $t = $HF->extract_top;
# use Data::Dumper; print "t = ", Dumper($t);
if (defined $t) {
my ($u, $v, $w) = $t->val;
# print "extracted top: $u $v $w\n";
if (exists $unseenh->{ $v }) {
$h->set_edge_attribute($u, $v, $attr, $w);
delete $unseenh->{ $v };
$add->($g, $h, $HF, $v, $attr, $unseenh, $etc);
}
}
}
return $h unless defined $next;
$r = $code ? $next->( $g, $unseenh ) : shift @$unseena;
last unless defined $r;
}
return $h;
}
sub MST_Prim {
&expect_undirected;
require Graph::MSTHeapElem;
$_[0]->_heap_walk(Graph->new(directed => 0), \&_MST_add, undef, &_root_opt);
}
*MST_Dijkstra = \&MST_Prim;
*minimum_spanning_tree = \&MST_Prim;
###
# Cycle detection.
#
*is_cyclic = \&has_a_cycle;
sub is_acyclic {
!&is_cyclic;
}
sub is_dag {
&is_directed && &is_acyclic ? 1 : 0;
}
*is_directed_acyclic_graph = \&is_dag;
###
# Simple DFS uses.
#
sub topological_sort {
my $g = shift;
my %opt = _get_options( \@_ );
my $eic = delete $opt{ empty_if_cyclic };
my $hac;
if ($eic) {
$hac = $g->has_a_cycle;
} else {
$g->expect_dag;
}
require Graph::Traversal::DFS;
my $t = Graph::Traversal::DFS->new($g, %opt);
my @s = $t->dfs;
$hac ? () : reverse @s;
}
*toposort = \&topological_sort;
sub _undirected_copy_compute {
Graph->new(directed => 0, vertices => [&isolated_vertices], edges => [&_edges05]);
}
sub undirected_copy {
&expect_directed;
return _check_cache($_[0], 'undirected_copy', [], \&_undirected_copy_compute);
}
*undirected_copy_graph = \&undirected_copy;
sub directed_copy {
&expect_undirected;
my @edges = &_edges05;
Graph->new(directed => 1, vertices => [&isolated_vertices],
edges => [@edges, map [reverse @$_], @edges]);
}
*directed_copy_graph = \&directed_copy;
###
# Cache or not.
#
my %_cache_type =
(
'connectivity' => ['_ccc'],
'strong_connectivity' => ['_scc'],
'biconnectivity' => ['_bcc'],
'SPT_Dijkstra' => ['_spt_di', 'SPT_Dijkstra_root'],
'SPT_Bellman_Ford' => ['_spt_bf', 'SPT_Bellman_Ford_root'],
'undirected_copy' => ['_undirected'],
'transitive_closure_matrix' => ['_tcm'],
);
for my $t (keys %_cache_type) {
no strict 'refs';
my @attr = @{ $_cache_type{$t} };
*{$t."_clear_cache"} = sub { $_[0]->delete_graph_attribute($_) for @attr };
}
sub _check_cache {
my ($g, $type, $extra_vals, $code, @args) = @_;
my $c = $_cache_type{$type};
__carp_confess "Graph: unknown cache type '$type'" if !defined $c;
my ($main_key, @extra_keys) = @$c;
__carp_confess "Graph: wrong number of extra values (@extra_keys) vs (@$extra_vals)" if @extra_keys != @$extra_vals;
my $a = $g->get_graph_attribute($main_key);
__carp_confess "$c attribute set to unexpected value $a"
if defined $a and ref $a ne 'ARRAY';
unless (defined $a && $a->[ 0 ] == $g->[ _G ]) {
$g->set_graph_attribute($main_key, $a = [ $g->[ _G ], $code->( $g, @args ) ]);
}
my $i = -1;
my $extra_invalid = grep {
my $v = $a->[ 1 ]->get_graph_attribute($_);
$i++; # here so still incremented even if short-cut
!defined $v or $v ne $extra_vals->[$i];
} @extra_keys;
if ($extra_invalid) {
$g->set_graph_attribute($main_key, $a = [ $g->[ _G ], $code->( $g, @args ) ]);
}
return $a->[ 1 ];
}
###
# Connected components.
#
sub _connected_components_compute {
my $g = $_[0];
my %v2c;
my @c;
return [ [], {} ] unless my @v = $g->unique_vertices;
if (my $UF = &has_union_find) {
my $V = $g->[ _V ];
my @ids = $V->get_ids_by_paths(\@v, 0);
my ($counter, %cc2counter) = 0;
my @cc = $UF->find(@ids);
for (my $i = 0; $i <= $#v; $i++) {
my $cc = $cc[$i];
__carp_confess "connected_component union-find did not have vertex '$v[$i]', please report"
if !defined $cc;
$cc2counter{$cc} = $counter++ if !exists $cc2counter{$cc};
my $ci = $cc2counter{$cc};
$v2c{ $v[$i] } = $ci;
push @{ $c[$ci] }, $v[$i];
}
} else {
require Graph::Traversal::DFS;
my %r; @r{ @v } = @v;
@c = [];
my $t = Graph::Traversal::DFS->new(
$g,
first_root => sub { (each %r)[1] },
next_root => sub { push @c, [] if keys %r; (each %r)[1]; },
pre => sub {
my ($v, $t) = @_;
$v2c{ $v } = $#c;
push @{ $c[-1] }, $v;
delete $r{ $v };
},
@_[1..$#_]
);
$t->dfs;
}
return [ \@c, \%v2c ];
}
sub _connected_components {
my $ccc = _check_cache($_[0], 'connectivity', [],
\&_connected_components_compute);
return @{ $ccc };
}
sub connected_component_by_vertex {
&expect_undirected;
(&_connected_components)[1]->{ $_[1] };
}
sub connected_component_by_index {
&expect_undirected;
my $value = (&_connected_components)[0]->[$_[1]];
$value ? @{ $value || _empty_array } : ();
}
sub connected_components {
&expect_undirected;
@{ (&_connected_components)[0] };
}
sub same_connected_components {
&expect_undirected;
my ($g, @args) = @_;
my @components;
if (my $UF = &has_union_find) {
my @ids = &_vertex_ids;
return 0 if @ids != @args;
@components = $UF->find(@ids);
} else {
@components = @{ (&_connected_components)[1] }{ @args };
}
return 0 if grep !defined, @components;
require List::Util;
List::Util::uniq( @components ) == 1;
}
sub _super_component { join("+", sort @_) }
sub connected_graph {
&expect_undirected;
my ($g, %opt) = @_;
my $cg = Graph->new(undirected => 1);
if ($g->has_union_find && $g->vertices == 1) {
# TODO: super_component?
$cg->add_vertices($g->vertices);
} else {
my $sc_cb = $opt{super_component} || \&_super_component;
$cg->set_vertex_attribute(scalar $sc_cb->(@$_), 'subvertices', $_)
for $g->connected_components;
}
return $cg;
}
sub is_connected {
&expect_undirected;
return @{ (&_connected_components)[0] } == 1;
}
sub is_weakly_connected {
&expect_directed;
splice @_, 0, 1, &undirected_copy;
goto &is_connected;
}
*weakly_connected = \&is_weakly_connected;
sub weakly_connected_components {
&expect_directed;
splice @_, 0, 1, &undirected_copy;
goto &connected_components;
}
sub weakly_connected_component_by_vertex {
&expect_directed;
splice @_, 0, 1, &undirected_copy;
goto &connected_component_by_vertex;
}
sub weakly_connected_component_by_index {
&expect_directed;
splice @_, 0, 1, &undirected_copy;
goto &connected_component_by_index;
}
sub same_weakly_connected_components {
&expect_directed;
splice @_, 0, 1, &undirected_copy;
goto &same_connected_components;
}
sub weakly_connected_graph {
&expect_directed;
splice @_, 0, 1, &undirected_copy;
goto &connected_graph;
}
sub _strongly_connected_components_compute {
my $g = $_[0];
require Graph::Traversal::DFS;
require List::Util;
my $t = Graph::Traversal::DFS->new($g);
my @d = reverse $t->dfs;
my @c;
my %v2c;
my $u = Graph::Traversal::DFS->new(
$g->transpose_graph,
next_root => sub {
my ($t, $u) = @_;
return if !defined(my $root = List::Util::first(
sub { exists $u->{$_} }, @d
));
push @c, [];
return $root;
},
pre => sub {
my ($v, $t) = @_;
push @{ $c[-1] }, $v;
$v2c{$v} = $#c;
},
next_alphabetic => 1,
);
$u->dfs;
return [ \@c, \%v2c ];
}
sub _strongly_connected_components_v2c {
&_strongly_connected_components->[1];
}
sub _strongly_connected_components_arrays {
@{ &_strongly_connected_components->[0] };
}
sub _strongly_connected_components {
_check_cache($_[0], 'strong_connectivity', [],
\&_strongly_connected_components_compute);
}
sub strongly_connected_components {
&expect_directed;
goto &_strongly_connected_components_arrays;
}
sub strongly_connected_component_by_vertex {
&expect_directed;
&_strongly_connected_components_v2c->{$_[1]};
}
sub strongly_connected_component_by_index {
&expect_directed;
my $i = $_[1];
return if !defined(my $c = &_strongly_connected_components->[0][ $i ]);
@$c;
}
sub same_strongly_connected_components {
&expect_directed;
my ($g, @args) = @_;
require Set::Object;
Set::Object->new(@{ &_strongly_connected_components_v2c }{@args})->size <= 1;
}
sub is_strongly_connected {
&strongly_connected_components == 1;
}
*strongly_connected = \&is_strongly_connected;
sub strongly_connected_graph {
&expect_directed;
my ($g, %attr) = @_;
my $sc_cb = \&_super_component;
_opt_get(\%attr, super_component => \$sc_cb);
_opt_unknown(\%attr);
my ($c, $v2c) = @{ &_strongly_connected_components };
my $s = Graph->new;
my @s = map $sc_cb->(@$_), @$c;
$s->set_vertex_attribute($s[$_], 'subvertices', $c->[$_]) for 0..$#$c;
require List::Util;
$s->add_edges(map [@s[ @$v2c{ @$_ } ]], grep List::Util::uniq( @$v2c{ @$_ } ) > 1, &_edges05);
return $s;
}
###
# Biconnectivity.
#
sub _biconnectivity_out {
my ($state, $u, $v) = @_;
my @BC;
while (@{$state->{stack}}) {
push @BC, my $e = pop @{$state->{stack}};
last if $e->[0] eq $u && $e->[1] eq $v;
}
push @{$state->{BC}}, \@BC if @BC;
}
sub _biconnectivity_dfs {
my ($g, $u, $state) = @_;
$state->{low}{$u} = $state->{num}{$u} = $state->{dfs}++;
for my $v ($g->successors($u)) {
if (!exists $state->{num}{$v}) {
push @{$state->{stack}}, [$u, $v];
$state->{pred}{$v} = $u;
$state->{succ}{$u}{$v}++;
_biconnectivity_dfs($g, $v, $state);
$state->{low}{$u} = List::Util::min(@{ $state->{low} }{$u, $v});
_biconnectivity_out($state, $u, $v)
if $state->{low}{$v} >= $state->{num}{$u};
} elsif (defined $state->{pred}{$u} &&
$state->{pred}{$u} ne $v &&
$state->{num}{$v} < $state->{num}{$u}) {
push @{$state->{stack}}, [$u, $v];
$state->{low}{$u} = List::Util::min($state->{low}{$u}, $state->{num}{$v});
}
}
}
sub _biconnectivity_compute {
require List::Util;
my ($g) = @_;
my %state = (BC=>[], dfs=>0);
my @u = $g->vertices;
for my $u (@u) {
next if exists $state{num}->{$u};
_biconnectivity_dfs($g, $u, \%state);
push @{$state{BC}}, delete $state{stack} if @{ $state{stack} || _empty_array };
}
# Mark the components each vertex belongs to.
my ($bci, %v2bc, %bc2v) = 0;
for my $bc (@{$state{BC}}) {
$v2bc{$_}{$bci} = undef for map @$_, @$bc;
$bci++;
}
# Any isolated vertices get each their own component.
$v2bc{$_}{$bci++} = undef for grep !exists $v2bc{$_}, @u;
# build vector now we know how big to make it
my ($Z, %v2bc_vec, @ap) = "\0" x (($bci + 7) / 8);
@v2bc_vec{@u} = ($Z) x @u;
for my $v (@u) {
my @components = keys %{ $v2bc{$v} };
vec($v2bc_vec{$v}, $_, 1) = 1 for @components;
$bc2v{$_}{$v}{$_} = undef for @components;
# Articulation points / cut vertices are the vertices
# which belong to more than one component.
push @ap, $v if @components > 1;
}
# Bridges / cut edges are the components of two vertices.
my @br = grep @$_ == 2, map [keys %$_], values %bc2v;
# Create the subgraph components.
my @sg = map [ List::Util::uniq( map @$_, @$_ ) ], @{$state{BC}};
return [ \@ap, \@sg, \@br, \%v2bc, \%v2bc_vec, $Z ];
}
sub biconnectivity {
&expect_undirected;
@{ _check_cache($_[0], 'biconnectivity', [],
\&_biconnectivity_compute, @_[1..$#_]) || _empty_array };
}
sub is_biconnected {
&edges >= 2 ? @{ (&biconnectivity)[0] } == 0 : undef ;
}
sub is_edge_connected {
&edges >= 2 ? @{ (&biconnectivity)[2] } == 0 : undef;
}
sub is_edge_separable {
&edges >= 2 ? @{ (&biconnectivity)[2] } > 0 : undef;
}
sub articulation_points {
@{ (&biconnectivity)[0] };
}
*cut_vertices = \&articulation_points;
sub biconnected_components {
@{ (&biconnectivity)[1] };
}
sub biconnected_component_by_index {
my ($i) = splice @_, 1, 1;
(&biconnectivity)[1]->[ $i ];
}
sub biconnected_component_by_vertex {
my ($v) = splice @_, 1, 1;
my $v2bc = (&biconnectivity)[3];
splice @_, 1, 0, $v;
return defined $v2bc->{ $v } ? keys %{ $v2bc->{ $v } } : ();
}
sub same_biconnected_components {
my ($v2bc, $Z) = (&biconnectivity)[4,5];
return 0 if grep !defined, my @vecs = @$v2bc{ @_[1..$#_] };
my $accumulator = $vecs[0];
$accumulator &= $_ for @vecs[1..$#vecs]; # accumulate 0s -> all in same
$accumulator ne $Z;
}
sub biconnected_graph {
my ($g, %opt) = @_;
my $bc = (&biconnectivity)[1];
my $bcg = Graph->new(directed => 0);
my $sc_cb = $opt{super_component} || \&_super_component;
my @s = map $sc_cb->(@$_), @$bc;
$bcg->set_vertex_attribute($s[$_], 'subvertices', $bc->[$_]) for 0..$#$bc;
my @edges;
for my $i (0..$#$bc) {
my @u = @{ $bc->[ $i ] };
for my $j (0..$i-1) {
my %j; @j{ @{ $bc->[ $j ] } } = ();
next if !grep exists $j{ $_ }, @u;
push @edges, [ @s[$i, $j] ];
}
}
$bcg->add_edges(@edges);
return $bcg;
}
sub bridges {
@{ (&biconnectivity)[2] || _empty_array };
}
###
# SPT.
#
sub _SPT_add {
my ($g, $h, $HF, $r, $attr, $unseen, $etc) = @_;
my $etc_r = $etc->{ $r } || 0;
for my $s ( grep exists $unseen->{ $_ }, $g->successors( $r ) ) {
my $t = $g->get_edge_attribute( $r, $s, $attr );
$t = 1 unless defined $t;
__carp_confess "Graph::SPT_Dijkstra: edge $r-$s is negative ($t)"
if $t < 0;
if (!defined($etc->{ $s }) || ($etc_r + $t) < $etc->{ $s }) {
my $etc_s = $etc->{ $s } || 0;
$etc->{ $s } = $etc_r + $t;
# print "$r - $s : setting $s to $etc->{ $s } ($etc_r, $etc_s)\n";
$h->set_vertex_attributes($s, { $attr=>$etc->{ $s }, 'p', $r });
$HF->add( Graph::SPTHeapElem->new($r, $s, $etc->{ $s }) );
}
}
}
sub _SPT_Dijkstra_compute {
require Graph::SPTHeapElem;
my $sptg = $_[0]->_heap_walk($_[0]->new, \&_SPT_add, {}, @_[1..$#_]);
$sptg->set_graph_attribute('SPT_Dijkstra_root', $_[4]);
$sptg;
}
sub SPT_Dijkstra {
my $g = $_[0];
my @args = &_root_opt;
_check_cache($g, 'SPT_Dijkstra', [$args[3]],
\&_SPT_Dijkstra_compute, @args);
}
*SSSP_Dijkstra = \&SPT_Dijkstra;
*single_source_shortest_paths = \&SPT_Dijkstra;
sub SP_Dijkstra {
my ($g, $u, $v) = @_;
my $sptg = $g->SPT_Dijkstra(first_root => $u);
my @path = ($v);
require Set::Object;
my $seen = Set::Object->new;
my $V = $g->vertices;
my $p;
while (defined($p = $sptg->get_vertex_attribute($v, 'p'))) {
last if $seen->contains($p);
push @path, $p;
$v = $p;
$seen->insert($p);
last if $seen->size == $V || $u eq $v;
}
return if !@path or $path[-1] ne $u;
return reverse @path;
}
sub __SPT_Bellman_Ford {
my ($g, $u, $v, $attr, $d, $p, $c0, $c1) = @_;
return unless $c0->{ $u };
my $w = $g->get_edge_attribute($u, $v, $attr);
$w = 1 unless defined $w;
if (defined $d->{ $v }) {
if (defined $d->{ $u }) {
if ($d->{ $v } > $d->{ $u } + $w) {
$d->{ $v } = $d->{ $u } + $w;
$p->{ $v } = $u;
$c1->{ $v }++;
}
} # else !defined $d->{ $u } && defined $d->{ $v }
} else {
if (defined $d->{ $u }) {
# defined $d->{ $u } && !defined $d->{ $v }
$d->{ $v } = $d->{ $u } + $w;
$p->{ $v } = $u;
$c1->{ $v }++;
} # else !defined $d->{ $u } && !defined $d->{ $v }
}
}
sub _SPT_Bellman_Ford {
my ($g, $opt, $unseenh, $unseena, $r, $next, $code, $attr) = @_;
my %d;
return unless defined $r;
$d{ $r } = 0;
my %p;
my $V = $g->vertices;
my %c0; # Changed during the last iteration?
$c0{ $r }++;
for (my $i = 0; $i < $V; $i++) {
my %c1;
for my $e ($g->edges) {
my ($u, $v) = @$e;
__SPT_Bellman_Ford($g, $u, $v, $attr, \%d, \%p, \%c0, \%c1);
__SPT_Bellman_Ford($g, $v, $u, $attr, \%d, \%p, \%c0, \%c1)
if $g->undirected;
}
%c0 = %c1 unless $i == $V - 1;
}
for my $e ($g->edges) {
my ($u, $v) = @$e;
if (defined $d{ $u } && defined $d{ $v }) {
my $d = $g->get_edge_attribute($u, $v, $attr);
__carp_confess "Graph::SPT_Bellman_Ford: negative cycle exists"
if defined $d && $d{ $v } > $d{ $u } + $d;
}
}
return (\%p, \%d);
}
sub _SPT_Bellman_Ford_compute {
my ($g, @args) = @_;
my ($p, $d) = $g->_SPT_Bellman_Ford(@args);
my $h = $g->new;
for my $v (keys %$p) {
my $u = $p->{ $v };
$h->set_edge_attribute( $u, $v, $args[6],
$g->get_edge_attribute($u, $v, $args[6]));
$h->set_vertex_attributes( $v, { $args[6], $d->{ $v }, p => $u } );
}
$h->set_graph_attribute('SPT_Bellman_Ford_root', $args[3]);
$h;
}
sub SPT_Bellman_Ford {
my @args = &_root_opt;
_check_cache($_[0], 'SPT_Bellman_Ford', [$args[3]],
\&_SPT_Bellman_Ford_compute, @args);
}
*SSSP_Bellman_Ford = \&SPT_Bellman_Ford;
sub SP_Bellman_Ford {
my ($g, $u, $v) = @_;
my $sptg = $g->SPT_Bellman_Ford(first_root => $u);
my @path = ($v);
require Set::Object;
my $seen = Set::Object->new;
my $V = $g->vertices;
my $p;
while (defined($p = $sptg->get_vertex_attribute($v, 'p'))) {
last if $seen->contains($p);
push @path, $p;
$v = $p;
$seen->insert($p);
last if $seen->size == $V;
}
# @path = () if @path && "$path[-1]" ne "$u";
return reverse @path;
}
###
# Transitive Closure.
#
sub TransitiveClosure_Floyd_Warshall {
my $self = shift;
require Graph::TransitiveClosure;
Graph::TransitiveClosure->new($self, @_);
}
*transitive_closure = \&TransitiveClosure_Floyd_Warshall;
sub APSP_Floyd_Warshall {
my $self = shift;
require Graph::TransitiveClosure;
Graph::TransitiveClosure->new($self, path => 1, @_);
}
*all_pairs_shortest_paths = \&APSP_Floyd_Warshall;
sub _transitive_closure_matrix_compute {
&APSP_Floyd_Warshall->transitive_closure_matrix;
}
sub transitive_closure_matrix {
_check_cache($_[0], 'transitive_closure_matrix', [],
\&_transitive_closure_matrix_compute, @_[1..$#_]);
}
sub path_length {
shift->transitive_closure_matrix->path_length(@_);
}
sub path_successor {
shift->transitive_closure_matrix->path_successor(@_);
}
sub path_vertices {
shift->transitive_closure_matrix->path_vertices(@_);
}
sub all_paths {
shift->transitive_closure_matrix->all_paths(@_);
}
sub is_reachable {
shift->transitive_closure_matrix->is_reachable(@_);
}
sub for_shortest_paths {
my $g = shift;
my $c = shift;
my $t = $g->transitive_closure_matrix;
my @v = $g->vertices;
my $n = 0;
for my $u (@v) {
$c->($t, $u, $_, ++$n) for grep $t->is_reachable($u, $_), @v;
}
return $n;
}
sub _minmax_path {
my $g = shift;
my $min;
my $max;
my $minp;
my $maxp;
$g->for_shortest_paths(sub {
my ($t, $u, $v, $n) = @_;
my $l = $t->path_length($u, $v);
return unless defined $l;
my $p;
if ($u ne $v && (!defined $max || $l > $max)) {
$max = $l;
$maxp = $p = [ $t->path_vertices($u, $v) ];
}
if ($u ne $v && (!defined $min || $l < $min)) {
$min = $l;
$minp = $p || [ $t->path_vertices($u, $v) ];
}
});
return ($min, $max, $minp, $maxp);
}
sub diameter {
my $g = shift;
my ($min, $max, $minp, $maxp) = $g->_minmax_path(@_);
return defined $maxp ? (wantarray ? @$maxp : $max) : undef;
}
*graph_diameter = \&diameter;
sub longest_path {
my ($g, $u, $v) = @_;
my $t = $g->transitive_closure_matrix;
if (defined $u) {
return wantarray ? $t->path_vertices($u, $v) : $t->path_length($u, $v)
if defined $v;
my $max;
my @max;
for my $v (grep $u ne $_, $g->vertices) {
my $l = $t->path_length($u, $v);
next if !(defined $l && (!defined $max || $l > $max));
$max = $l;
@max = $t->path_vertices($u, $v);
}
return wantarray ? @max : $max;
}
if (defined $v) {
my $max;
my @max;
for my $u (grep $_ ne $v, $g->vertices) {
my $l = $t->path_length($u, $v);
next if !(defined $l && (!defined $max || $l > $max));
$max = $l;
@max = $t->path_vertices($u, $v);
}
return wantarray ? @max : @max - 1;
}
my ($min, $max, $minp, $maxp) = $g->_minmax_path(@_);
return defined $maxp ? (wantarray ? @$maxp : $max) : undef;
}
sub vertex_eccentricity {
&expect_undirected;
my ($g, $u) = @_;
return Infinity() if !&is_connected;
my $max;
for my $v (grep $u ne $_, $g->vertices) {
my $l = $g->path_length($u, $v);
next if !(defined $l && (!defined $max || $l > $max));
$max = $l;
}
return defined $max ? $max : Infinity();
}
sub shortest_path {
&expect_undirected;
my ($g, $u, $v) = @_;
my $t = $g->transitive_closure_matrix;
if (defined $u) {
return wantarray ? $t->path_vertices($u, $v) : $t->path_length($u, $v)
if defined $v;
my $min;
my @min;
for my $v (grep $u ne $_, $g->vertices) {
my $l = $t->path_length($u, $v);
next if !(defined $l && (!defined $min || $l < $min));
$min = $l;
@min = $t->path_vertices($u, $v);
}
# print "min/1 = @min\n";
return wantarray ? @min : $min;
}
if (defined $v) {
my $min;
my @min;
for my $u (grep $_ ne $v, $g->vertices) {
my $l = $t->path_length($u, $v);
next if !(defined $l && (!defined $min || $l < $min));
$min = $l;
@min = $t->path_vertices($u, $v);
}
# print "min/2 = @min\n";
return wantarray ? @min : $min;
}
my ($min, $max, $minp, $maxp) = $g->_minmax_path(@_);
return if !defined $minp;
wantarray ? @$minp : $min;
}
sub radius {
&expect_undirected;
my $g = shift;
my ($center, $radius) = (undef, Infinity());
for my $v ($g->vertices) {
my $x = $g->vertex_eccentricity($v);
($center, $radius) = ($v, $x) if defined $x && $x < $radius;
}
return $radius;
}
sub center_vertices {
&expect_undirected;
my ($g, $delta) = @_;
$delta = 0 unless defined $delta;
$delta = abs($delta);
my @c;
my $Inf = Infinity();
my $r = $g->radius;
if (defined $r && $r != $Inf) {
for my $v ($g->vertices) {
my $e = $g->vertex_eccentricity($v);
next unless defined $e && $e != $Inf;
push @c, $v if abs($e - $r) <= $delta;
}
}
return @c;
}
*centre_vertices = \¢er_vertices;
sub average_path_length {
my $g = shift;
my @A = @_;
my $d = 0;
my $m = 0;
$g->for_shortest_paths(sub {
my ($t, $u, $v, $n) = @_;
return unless my $l = $t->path_length($u, $v);
return if defined $A[0] && $u ne $A[0];
return if defined $A[1] && $v ne $A[1];
$d += $l;
$m++;
});
return $m ? $d / $m : undef;
}
###
# Simple tests.
#
sub is_multi_graph {
return 0 unless &is_multiedged || &is_countedged;
my $g = $_[0];
my $multiedges = 0;
for my $e (&_edges05) {
my ($u, @v) = @$e;
return 0 if grep $u eq $_, @v;
$multiedges++ if $g->get_edge_count(@$e) > 1;
}
return $multiedges;
}
sub is_simple_graph {
return 1 unless &is_multiedged || &is_countedged;
my $g = $_[0];
return 0 if grep $g->get_edge_count(@$_) > 1, &_edges05;
return 1;
}
sub is_pseudo_graph {
my $m = &is_countedged || &is_multiedged;
my $g = $_[0];
for my $e (&_edges05) {
my ($u, @v) = @$e;
return 1 if grep $u eq $_, @v;
return 1 if $m && $g->get_edge_count($u, @v) > 1;
}
return 0;
}
###
# Rough isomorphism guess.
#
my %_factorial = (0 => 1, 1 => 1);
sub __factorial {
my $n = shift;
for (my $i = 2; $i <= $n; $i++) {
next if exists $_factorial{$i};
$_factorial{$i} = $i * $_factorial{$i - 1};
}
$_factorial{$n};
}
sub _factorial {
my $n = int(shift);
__carp_confess "factorial of a negative number" if $n < 0;
__factorial($n) unless exists $_factorial{$n};
return $_factorial{$n};
}
sub could_be_isomorphic {
my ($g0, $g1) = @_;
return 0 unless &vertices == $g1->vertices;
return 0 unless &_edges05 == $g1->_edges05;
my %d0;
$d0{ $g0->in_degree($_) }{ $g0->out_degree($_) }++ for &vertices;
my %d1;
$d1{ $g1->in_degree($_) }{ $g1->out_degree($_) }++ for $g1->vertices;
return 0 unless keys %d0 == keys %d1;
for my $da (keys %d0) {
return 0
unless exists $d1{$da} &&
keys %{ $d0{$da} } == keys %{ $d1{$da} };
return 0
if grep !(exists $d1{$da}{$_} && $d0{$da}{$_} == $d1{$da}{$_}),
keys %{ $d0{$da} };
}
for my $da (keys %d0) {
return 0 if grep $d1{$da}{$_} != $d0{$da}{$_}, keys %{ $d0{$da} };
delete $d1{$da};
}
return 0 unless keys %d1 == 0;
my $f = 1;
for my $da (keys %d0) {
$f *= _factorial(abs($d0{$da}{$_})) for keys %{ $d0{$da} };
}
return $f;
}
###
# Analysis functions.
sub subgraph_by_radius {
$_[0]->subgraph([ @_[1..$#_-1], &reachable_by_radius ]);
}
sub clustering_coefficient {
my ($g) = @_;
return unless my @v = $g->vertices;
require Set::Object;
my %clustering;
my $gamma = 0;
for my $n (@v) {
my $gamma_v = 0;
my @neigh = $g->successors($n);
my $c = Set::Object->new;
for my $u (@neigh) {
for my $v (grep +(!$c->contains("$u-$_") && $g->has_edge($u, $_)), @neigh) {
$gamma_v++;
$c->insert("$u-$v");
$c->insert("$v-$u");
}
}
if (@neigh > 1) {
$clustering{$n} = $gamma_v/(@neigh * (@neigh - 1) / 2);
$gamma += $gamma_v/(@neigh * (@neigh - 1) / 2);
} else {
$clustering{$n} = 0;
}
}
$gamma /= @v;
return wantarray ? ($gamma, %clustering) : $gamma;
}
sub betweenness {
my $g = shift;
my @V = $g->vertices();
my %Cb; # C_b{w} = 0
@Cb{@V} = ();
for my $s (@V) {
my @S; # stack (unshift, shift)
my %P; # P{w} = empty list
$P{$_} = [] for @V;
my %sigma; # \sigma{t} = 0
$sigma{$_} = 0 for @V;
$sigma{$s} = 1;
my %d; # d{t} = -1;
$d{$_} = -1 for @V;
$d{$s} = 0;
my @Q; # queue (push, shift)
push @Q, $s;
while (@Q) {
my $v = shift @Q;
unshift @S, $v;
for my $w ($g->successors($v)) {
# w found for first time
if ($d{$w} < 0) {
push @Q, $w;
$d{$w} = $d{$v} + 1;
}
# Shortest path to w via v
if ($d{$w} == $d{$v} + 1) {
$sigma{$w} += $sigma{$v};
push @{ $P{$w} }, $v;
}
}
}
my %delta;
$delta{$_} = 0 for @V;
while (@S) {
my $w = shift @S;
$delta{$_} += $sigma{$_}/$sigma{$w} * (1 + $delta{$w})
for @{ $P{$w} };
$Cb{$w} += $delta{$w} if $w ne $s;
}
}
return %Cb;
}
1;
|