-
-
Notifications
You must be signed in to change notification settings - Fork 200
/
structural.properties.R
2878 lines (2709 loc) · 103 KB
/
structural.properties.R
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
#' Shortest (directed or undirected) paths between vertices
#'
#' @description
#' `r lifecycle::badge("deprecated")`
#'
#' `get.shortest.paths()` was renamed to `shortest_paths()` to create a more
#' consistent API.
#' @inheritParams shortest_paths
#' @keywords internal
#' @export
get.shortest.paths <- function(graph, from, to = V(graph), mode = c("out", "all", "in"), weights = NULL, output = c("vpath", "epath", "both"), predecessors = FALSE, inbound.edges = FALSE, algorithm = c("automatic", "unweighted", "dijkstra", "bellman-ford")) { # nocov start
lifecycle::deprecate_soft("2.0.0", "get.shortest.paths()", "shortest_paths()")
shortest_paths(graph = graph, from = from, to = to, mode = mode, weights = weights, output = output, predecessors = predecessors, inbound.edges = inbound.edges, algorithm = algorithm)
} # nocov end
#' Shortest (directed or undirected) paths between vertices
#'
#' @description
#' `r lifecycle::badge("deprecated")`
#'
#' `get.all.shortest.paths()` was renamed to `all_shortest_paths()` to create a more
#' consistent API.
#' @inheritParams all_shortest_paths
#' @keywords internal
#' @export
get.all.shortest.paths <- function(graph, from, to = V(graph), mode = c("out", "all", "in"), weights = NULL) { # nocov start
lifecycle::deprecate_soft("2.0.0", "get.all.shortest.paths()", "all_shortest_paths()")
all_shortest_paths(graph = graph, from = from, to = to, mode = mode, weights = weights)
} # nocov end
#' Diameter of a graph
#'
#' @description
#' `r lifecycle::badge("deprecated")`
#'
#' `get.diameter()` was renamed to `get_diameter()` to create a more
#' consistent API.
#' @inheritParams get_diameter
#' @keywords internal
#' @export
get.diameter <- function(graph, directed = TRUE, unconnected = TRUE, weights = NULL) { # nocov start
lifecycle::deprecate_soft("2.0.0", "get.diameter()", "get_diameter()")
get_diameter(graph = graph, directed = directed, unconnected = unconnected, weights = weights)
} # nocov end
#' Convert a general graph into a forest
#'
#' @description
#' `r lifecycle::badge("deprecated")`
#'
#' `unfold.tree()` was renamed to `unfold_tree()` to create a more
#' consistent API.
#' @inheritParams unfold_tree
#' @keywords internal
#' @export
unfold.tree <- function(graph, mode = c("all", "out", "in", "total"), roots) { # nocov start
lifecycle::deprecate_soft("2.0.0", "unfold.tree()", "unfold_tree()")
unfold_tree(graph = graph, mode = mode, roots = roots)
} # nocov end
#' Topological sorting of vertices in a graph
#'
#' @description
#' `r lifecycle::badge("deprecated")`
#'
#' `topological.sort()` was renamed to `topo_sort()` to create a more
#' consistent API.
#' @inheritParams topo_sort
#' @keywords internal
#' @export
topological.sort <- function(graph, mode = c("out", "all", "in")) { # nocov start
lifecycle::deprecate_soft("2.0.0", "topological.sort()", "topo_sort()")
topo_sort(graph = graph, mode = mode)
} # nocov end
#' Shortest (directed or undirected) paths between vertices
#'
#' @description
#' `r lifecycle::badge("deprecated")`
#'
#' `shortest.paths()` was renamed to `distances()` to create a more
#' consistent API.
#' @inheritParams distances
#' @keywords internal
#' @export
shortest.paths <- function(graph, v = V(graph), to = V(graph), mode = c("all", "out", "in"), weights = NULL, algorithm = c("automatic", "unweighted", "dijkstra", "bellman-ford", "johnson")) { # nocov start
lifecycle::deprecate_soft("2.0.0", "shortest.paths()", "distances()")
algorithm <- igraph.match.arg(algorithm)
mode <- igraph.match.arg(mode)
distances(graph = graph, v = v, to = to, mode = mode, weights = weights, algorithm = algorithm)
} # nocov end
#' Neighborhood of graph vertices
#'
#' @description
#' `r lifecycle::badge("deprecated")`
#'
#' `neighborhood.size()` was renamed to `ego_size()` to create a more
#' consistent API.
#' @inheritParams ego_size
#' @keywords internal
#' @export
neighborhood.size <- function(graph, order = 1, nodes = V(graph), mode = c("all", "out", "in"), mindist = 0) { # nocov start
lifecycle::deprecate_soft("2.0.0", "neighborhood.size()", "ego_size()")
ego_size(graph = graph, order = order, nodes = nodes, mode = mode, mindist = mindist)
} # nocov end
#' Matching
#'
#' @description
#' `r lifecycle::badge("deprecated")`
#'
#' `maximum.bipartite.matching()` was renamed to `max_bipartite_match()` to create a more
#' consistent API.
#' @inheritParams max_bipartite_match
#' @keywords internal
#' @export
maximum.bipartite.matching <- function(graph, types = NULL, weights = NULL, eps = .Machine$double.eps) { # nocov start
lifecycle::deprecate_soft("2.0.0", "maximum.bipartite.matching()", "max_bipartite_match()")
max_bipartite_match(graph = graph, types = types, weights = weights, eps = eps)
} # nocov end
#' Find mutual edges in a directed graph
#'
#' @description
#' `r lifecycle::badge("deprecated")`
#'
#' `is.mutual()` was renamed to `which_mutual()` to create a more
#' consistent API.
#' @inheritParams which_mutual
#' @keywords internal
#' @export
is.mutual <- function(graph, eids = E(graph), loops = TRUE) { # nocov start
lifecycle::deprecate_soft("2.0.0", "is.mutual()", "which_mutual()")
which_mutual(graph = graph, eids = eids, loops = loops)
} # nocov end
#' Find the multiple or loop edges in a graph
#'
#' @description
#' `r lifecycle::badge("deprecated")`
#'
#' `is.multiple()` was renamed to `which_multiple()` to create a more
#' consistent API.
#' @inheritParams which_multiple
#' @keywords internal
#' @export
is.multiple <- function(graph, eids = E(graph)) { # nocov start
lifecycle::deprecate_soft("2.0.0", "is.multiple()", "which_multiple()")
which_multiple(graph = graph, eids = eids)
} # nocov end
#' Matching
#'
#' @description
#' `r lifecycle::badge("deprecated")`
#'
#' `is.maximal.matching()` was renamed to `is_max_matching()` to create a more
#' consistent API.
#' @inheritParams is_max_matching
#' @keywords internal
#' @export
is.maximal.matching <- function(graph, matching, types = NULL) { # nocov start
lifecycle::deprecate_soft("2.0.0", "is.maximal.matching()", "is_max_matching()")
is_max_matching(graph = graph, matching = matching, types = types)
} # nocov end
#' Matching
#'
#' @description
#' `r lifecycle::badge("deprecated")`
#'
#' `is.matching()` was renamed to `is_matching()` to create a more
#' consistent API.
#' @inheritParams is_matching
#' @keywords internal
#' @export
is.matching <- function(graph, matching, types = NULL) { # nocov start
lifecycle::deprecate_soft("2.0.0", "is.matching()", "is_matching()")
is_matching(graph = graph, matching = matching, types = types)
} # nocov end
#' Find the multiple or loop edges in a graph
#'
#' @description
#' `r lifecycle::badge("deprecated")`
#'
#' `is.loop()` was renamed to `which_loop()` to create a more
#' consistent API.
#' @inheritParams which_loop
#' @keywords internal
#' @export
is.loop <- function(graph, eids = E(graph)) { # nocov start
lifecycle::deprecate_soft("2.0.0", "is.loop()", "which_loop()")
which_loop(graph = graph, eids = eids)
} # nocov end
#' Connected components of a graph
#'
#' @description
#' `r lifecycle::badge("deprecated")`
#'
#' `is.connected()` was renamed to `is_connected()` to create a more
#' consistent API.
#' @inheritParams is_connected
#' @keywords internal
#' @export
is.connected <- function(graph, mode = c("weak", "strong")) { # nocov start
lifecycle::deprecate_soft("2.0.0", "is.connected()", "is_connected()")
is_connected(graph = graph, mode = mode)
} # nocov end
#' Subgraph of a graph
#'
#' @description
#' `r lifecycle::badge("deprecated")`
#'
#' `induced.subgraph()` was renamed to `induced_subgraph()` to create a more
#' consistent API.
#' @inheritParams induced_subgraph
#' @keywords internal
#' @export
induced.subgraph <- function(graph, vids, impl = c("auto", "copy_and_delete", "create_from_scratch")) { # nocov start
lifecycle::deprecate_soft("2.0.0", "induced.subgraph()", "induced_subgraph()")
induced_subgraph(graph = graph, vids = vids, impl = impl)
} # nocov end
#' Find the multiple or loop edges in a graph
#'
#' @description
#' `r lifecycle::badge("deprecated")`
#'
#' `has.multiple()` was renamed to `any_multiple()` to create a more
#' consistent API.
#' @inheritParams any_multiple
#' @keywords internal
#' @export
has.multiple <- function(graph) { # nocov start
lifecycle::deprecate_soft("2.0.0", "has.multiple()", "any_multiple()")
any_multiple(graph = graph)
} # nocov end
#' Neighborhood of graph vertices
#'
#' @description
#' `r lifecycle::badge("deprecated")`
#'
#' `graph.neighborhood()` was renamed to `make_ego_graph()` to create a more
#' consistent API.
#' @inheritParams make_ego_graph
#' @keywords internal
#' @export
graph.neighborhood <- function(graph, order = 1, nodes = V(graph), mode = c("all", "out", "in"), mindist = 0) { # nocov start
lifecycle::deprecate_soft("2.0.0", "graph.neighborhood()", "make_ego_graph()")
make_ego_graph(graph = graph, order = order, nodes = nodes, mode = mode, mindist = mindist)
} # nocov end
#' Graph Laplacian
#'
#' @description
#' `r lifecycle::badge("deprecated")`
#'
#' `graph.laplacian()` was renamed to `laplacian_matrix()` to create a more
#' consistent API.
#' @inheritParams laplacian_matrix
#' @keywords internal
#' @export
graph.laplacian <- function(graph, normalized = FALSE, weights = NULL, sparse = igraph_opt("sparsematrices")) { # nocov start
lifecycle::deprecate_soft("2.0.0", "graph.laplacian()", "laplacian_matrix()")
laplacian_matrix(graph = graph, normalized = normalized, weights = weights, sparse = sparse)
} # nocov end
#' Average nearest neighbor degree
#'
#' @description
#' `r lifecycle::badge("deprecated")`
#'
#' `graph.knn()` was renamed to `knn()` to create a more
#' consistent API.
#' @inheritParams knn
#' @keywords internal
#' @export
graph.knn <- function(graph, vids = V(graph), mode = c("all", "out", "in", "total"), neighbor.degree.mode = c("all", "out", "in", "total"), weights = NULL) { # nocov start
lifecycle::deprecate_soft("2.0.0", "graph.knn()", "knn()")
knn(graph = graph, vids = vids, mode = mode, neighbor.degree.mode = neighbor.degree.mode, weights = weights)
} # nocov end
#' Depth-first search
#'
#' @description
#' `r lifecycle::badge("deprecated")`
#'
#' `graph.dfs()` was renamed to `dfs()` to create a more
#' consistent API.
#' @inheritParams dfs
#' @keywords internal
#' @export
graph.dfs <- function(graph, root, mode = c("out", "in", "all", "total"), unreachable = TRUE, order = TRUE, order.out = FALSE, father = FALSE, dist = FALSE, in.callback = NULL, out.callback = NULL, extra = NULL, rho = parent.frame(), neimode) { # nocov start
lifecycle::deprecate_soft("2.0.0", "graph.dfs()", "dfs()")
dfs(graph = graph, root = root, mode = mode, unreachable = unreachable, order = order, order.out = order.out, father = father, dist = dist, in.callback = in.callback, out.callback = out.callback, extra = extra, rho = rho, neimode = neimode)
} # nocov end
#' Graph density
#'
#' @description
#' `r lifecycle::badge("deprecated")`
#'
#' `graph.density()` was renamed to `edge_density()` to create a more
#' consistent API.
#' @inheritParams edge_density
#' @keywords internal
#' @export
graph.density <- function(graph, loops = FALSE) { # nocov start
lifecycle::deprecate_soft("2.0.0", "graph.density()", "edge_density()")
edge_density(graph = graph, loops = loops)
} # nocov end
#' K-core decomposition of graphs
#'
#' @description
#' `r lifecycle::badge("deprecated")`
#'
#' `graph.coreness()` was renamed to `coreness()` to create a more
#' consistent API.
#' @inheritParams coreness
#' @keywords internal
#' @export
graph.coreness <- function(graph, mode = c("all", "out", "in")) { # nocov start
lifecycle::deprecate_soft("2.0.0", "graph.coreness()", "coreness()")
coreness(graph = graph, mode = mode)
} # nocov end
#' Breadth-first search
#'
#' @description
#' `r lifecycle::badge("deprecated")`
#'
#' `graph.bfs()` was renamed to `bfs()` to create a more
#' consistent API.
#' @inheritParams bfs
#' @keywords internal
#' @export
graph.bfs <- function(graph, root, mode = c("out", "in", "all", "total"), unreachable = TRUE, restricted = NULL, order = TRUE, rank = FALSE, father = FALSE, pred = FALSE, succ = FALSE, dist = FALSE, callback = NULL, extra = NULL, rho = parent.frame(), neimode) { # nocov start
lifecycle::deprecate_soft("2.0.0", "graph.bfs()", "bfs()")
bfs(graph = graph, root = root, mode = mode, unreachable = unreachable, restricted = restricted, order = order, rank = rank, father = father, pred = pred, succ = succ, dist = dist, callback = callback, extra = extra, rho = rho, neimode = neimode)
} # nocov end
#' Diameter of a graph
#'
#' @description
#' `r lifecycle::badge("deprecated")`
#'
#' `farthest.nodes()` was renamed to `farthest_vertices()` to create a more
#' consistent API.
#' @inheritParams farthest_vertices
#' @keywords internal
#' @export
farthest.nodes <- function(graph, directed = TRUE, unconnected = TRUE, weights = NULL) { # nocov start
lifecycle::deprecate_soft("2.0.0", "farthest.nodes()", "farthest_vertices()")
farthest_vertices(graph = graph, directed = directed, unconnected = unconnected, weights = weights)
} # nocov end
#' Degree and degree distribution of the vertices
#'
#' @description
#' `r lifecycle::badge("deprecated")`
#'
#' `degree.distribution()` was renamed to `degree_distribution()` to create a more
#' consistent API.
#' @inheritParams degree_distribution
#' @keywords internal
#' @export
degree.distribution <- function(graph, cumulative = FALSE, ...) { # nocov start
lifecycle::deprecate_soft("2.0.0", "degree.distribution()", "degree_distribution()")
degree_distribution(graph = graph, cumulative = cumulative, ...)
} # nocov end
#' Find the multiple or loop edges in a graph
#'
#' @description
#' `r lifecycle::badge("deprecated")`
#'
#' `count.multiple()` was renamed to `count_multiple()` to create a more
#' consistent API.
#' @inheritParams count_multiple
#' @keywords internal
#' @export
count.multiple <- function(graph, eids = E(graph)) { # nocov start
lifecycle::deprecate_soft("2.0.0", "count.multiple()", "count_multiple()")
count_multiple(graph = graph, eids = eids)
} # nocov end
#' Connected components of a graph
#'
#' @description
#' `r lifecycle::badge("deprecated")`
#'
#' `clusters()` was renamed to `components()` to create a more
#' consistent API.
#' @inheritParams components
#' @keywords internal
#' @export
clusters <- function(graph, mode = c("weak", "strong")) { # nocov start
lifecycle::deprecate_soft("2.0.0", "clusters()", "components()")
components(graph = graph, mode = mode)
} # nocov end
#' Shortest (directed or undirected) paths between vertices
#'
#' @description
#' `r lifecycle::badge("deprecated")`
#'
#' `average.path.length()` was renamed to `mean_distance()` to create a more
#' consistent API.
#' @inheritParams mean_distance
#' @keywords internal
#' @export
average.path.length <- function(graph, weights = NULL, directed = TRUE, unconnected = TRUE, details = FALSE) { # nocov start
lifecycle::deprecate_soft("2.0.0", "average.path.length()", "mean_distance()")
mean_distance(graph = graph, weights = weights, directed = directed, unconnected = unconnected, details = details)
} # nocov end
# IGraph R package
# Copyright (C) 2005-2012 Gabor Csardi <csardi.gabor@gmail.com>
# 334 Harvard street, Cambridge, MA 02139 USA
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301 USA
#
###################################################################
###################################################################
# Structural properties
###################################################################
#' Diameter of a graph
#'
#' The diameter of a graph is the length of the longest geodesic.
#'
#' The diameter is calculated by using a breadth-first search like method.
#'
#' `get_diameter()` returns a path with the actual diameter. If there are
#' many shortest paths of the length of the diameter, then it returns the first
#' one found.
#'
#' `farthest_vertices()` returns two vertex ids, the vertices which are
#' connected by the diameter path.
#'
#' @param graph The graph to analyze.
#' @param directed Logical, whether directed or undirected paths are to be
#' considered. This is ignored for undirected graphs.
#' @param unconnected Logical, what to do if the graph is unconnected. If
#' FALSE, the function will return a number that is one larger the largest
#' possible diameter, which is always the number of vertices. If TRUE, the
#' diameters of the connected components will be calculated and the largest one
#' will be returned.
#' @param weights Optional positive weight vector for calculating weighted
#' distances. If the graph has a `weight` edge attribute, then this is
#' used by default.
#' @return A numeric constant for `diameter()`, a numeric vector for
#' `get_diameter()`. `farthest_vertices()` returns a list with two
#' entries: \itemize{
#' \item `vertices` The two vertices that are the farthest.
#' \item `distance` Their distance.
#' }
#' @author Gabor Csardi \email{csardi.gabor@@gmail.com}
#' @seealso [distances()]
#' @family paths
#' @export
#' @keywords graphs
#' @examples
#'
#' g <- make_ring(10)
#' g2 <- delete_edges(g, c(1, 2, 1, 10))
#' diameter(g2, unconnected = TRUE)
#' diameter(g2, unconnected = FALSE)
#'
#' ## Weighted diameter
#' set.seed(1)
#' g <- make_ring(10)
#' E(g)$weight <- sample(seq_len(ecount(g)))
#' diameter(g)
#' get_diameter(g)
#' diameter(g, weights = NA)
#' get_diameter(g, weights = NA)
#'
diameter <- function(graph, directed = TRUE, unconnected = TRUE, weights = NULL) {
ensure_igraph(graph)
if (is.null(weights) && "weight" %in% edge_attr_names(graph)) {
weights <- E(graph)$weight
}
if (!is.null(weights) && any(!is.na(weights))) {
weights <- as.numeric(weights)
} else {
weights <- NULL
}
on.exit(.Call(R_igraph_finalizer))
.Call(
R_igraph_diameter, graph, as.logical(directed),
as.logical(unconnected), weights
)
}
#' @rdname diameter
#' @export
get_diameter <- function(graph, directed = TRUE, unconnected = TRUE,
weights = NULL) {
ensure_igraph(graph)
if (is.null(weights) && "weight" %in% edge_attr_names(graph)) {
weights <- E(graph)$weight
}
if (!is.null(weights) && any(!is.na(weights))) {
weights <- as.numeric(weights)
} else {
weights <- NULL
}
on.exit(.Call(R_igraph_finalizer))
res <- .Call(
R_igraph_get_diameter, graph, as.logical(directed),
as.logical(unconnected), weights
) + 1L
if (igraph_opt("return.vs.es")) {
res <- create_vs(graph, res)
}
res
}
#' @rdname diameter
#' @export
farthest_vertices <- function(graph, directed = TRUE, unconnected = TRUE,
weights = NULL) {
ensure_igraph(graph)
if (is.null(weights) && "weight" %in% edge_attr_names(graph)) {
weights <- E(graph)$weight
}
if (!is.null(weights) && any(!is.na(weights))) {
weights <- as.numeric(weights)
} else {
weights <- NULL
}
on.exit(.Call(R_igraph_finalizer))
res <- .Call(
R_igraph_farthest_points, graph, as.logical(directed),
as.logical(unconnected), weights
)
res <- list(vertices = res[1:2] + 1L, distance = res[3])
if (igraph_opt("return.vs.es")) {
res$vertices <- create_vs(graph, res$vertices)
}
res
}
#' @export
#' @rdname distances
#' @cdocs igraph_average_path_length_dijkstra
mean_distance <- average_path_length_dijkstra_impl
#' Degree and degree distribution of the vertices
#'
#' The degree of a vertex is its most basic structural property, the number of
#' its adjacent edges.
#'
#'
#' @param graph The graph to analyze.
#' @param v The ids of vertices of which the degree will be calculated.
#' @param mode Character string, \dQuote{out} for out-degree, \dQuote{in} for
#' in-degree or \dQuote{total} for the sum of the two. For undirected graphs
#' this argument is ignored. \dQuote{all} is a synonym of \dQuote{total}.
#' @param loops Logical; whether the loop edges are also counted.
#' @param normalized Logical scalar, whether to normalize the degree. If
#' `TRUE` then the result is divided by \eqn{n-1}, where \eqn{n} is the
#' number of vertices in the graph.
#' @inheritParams rlang::args_dots_empty
#' @return For `degree()` a numeric vector of the same length as argument
#' `v`.
#'
#' For `degree_distribution()` a numeric vector of the same length as the
#' maximum degree plus one. The first element is the relative frequency zero
#' degree vertices, the second vertices with degree one, etc.
#'
#' For `max_degree()`, the largest degree in the graph. When no vertices are
#' selected, or when the input is the null graph, zero is returned as this
#' is the smallest possible degree.
#' @author Gabor Csardi \email{csardi.gabor@@gmail.com}
#' @keywords graphs
#' @family structural.properties
#' @export
#' @examples
#'
#' g <- make_ring(10)
#' degree(g)
#' g2 <- sample_gnp(1000, 10 / 1000)
#' max_degree(g2)
#' degree_distribution(g2)
#'
degree <- function(graph, v = V(graph),
mode = c("all", "out", "in", "total"), loops = TRUE,
normalized = FALSE) {
ensure_igraph(graph)
v <- as_igraph_vs(graph, v)
mode <- igraph.match.arg(mode)
mode <- switch(mode,
"out" = 1,
"in" = 2,
"all" = 3,
"total" = 3
)
on.exit(.Call(R_igraph_finalizer))
res <- .Call(
R_igraph_degree, graph, v - 1,
as.numeric(mode), as.logical(loops)
)
if (normalized) {
res <- res / (vcount(graph) - 1)
}
if (igraph_opt("add.vertex.names") && is_named(graph)) {
names(res) <- V(graph)$name[v]
}
res
}
#' @rdname degree
#' @export
#' @cdocs igraph_maxdegree
max_degree <- maxdegree_impl
#' @rdname degree
#' @param cumulative Logical; whether the cumulative degree distribution is to
#' be calculated.
#' @export
#' @importFrom graphics hist
degree_distribution <- function(graph, cumulative = FALSE, ...) {
ensure_igraph(graph)
cs <- degree(graph, ...)
hi <- hist(cs, -1:max(cs), plot = FALSE)$density
if (!cumulative) {
res <- hi
} else {
res <- rev(cumsum(rev(hi)))
}
res
}
#' Shortest (directed or undirected) paths between vertices
#'
#' `distances()` calculates the length of all the shortest paths from
#' or to the vertices in the network. `shortest_paths()` calculates one
#' shortest path (the path itself, and not just its length) from or to the
#' given vertex.
#'
#' The shortest path, or geodesic between two pair of vertices is a path with
#' the minimal number of vertices. The functions documented in this manual page
#' all calculate shortest paths between vertex pairs.
#'
#' `distances()` calculates the lengths of pairwise shortest paths from
#' a set of vertices (`from`) to another set of vertices (`to`). It
#' uses different algorithms, depending on the `algorithm` argument and
#' the `weight` edge attribute of the graph. The implemented algorithms
#' are breadth-first search (\sQuote{`unweighted`}), this only works for
#' unweighted graphs; the Dijkstra algorithm (\sQuote{`dijkstra`}), this
#' works for graphs with non-negative edge weights; the Bellman-Ford algorithm
#' (\sQuote{`bellman-ford`}); Johnson's algorithm
#' (\sQuote{`johnson`}); and a faster version of the Floyd-Warshall algorithm
#' with expected quadratic running time (\sQuote{`floyd-warshall`}). The latter
#' three algorithms work with arbitrary
#' edge weights, but (naturally) only for graphs that don't have a negative
#' cycle. Note that a negative-weight edge in an undirected graph implies
#' such a cycle. Johnson's algorithm performs better than the Bellman-Ford
#' one when many source (and target) vertices are given, with all-pairs
#' shortest path length calculations being the typical use case.
#'
#' igraph can choose automatically between algorithms, and chooses the most
#' efficient one that is appropriate for the supplied weights (if any). For
#' automatic algorithm selection, supply \sQuote{`automatic`} as the
#' `algorithm` argument. (This is also the default.)
#'
#' `shortest_paths()` calculates a single shortest path (i.e. the path
#' itself, not just its length) between the source vertex given in `from`,
#' to the target vertices given in `to`. `shortest_paths()` uses
#' breadth-first search for unweighted graphs and Dijkstra's algorithm for
#' weighted graphs. The latter only works if the edge weights are non-negative.
#'
#' `all_shortest_paths()` calculates *all* shortest paths between
#' pairs of vertices, including several shortest paths of the same length.
#' More precisely, it computerd all shortest path starting at `from`, and
#' ending at any vertex given in `to`. It uses a breadth-first search for
#' unweighted graphs and Dijkstra's algorithm for weighted ones. The latter
#' only supports non-negative edge weights. Caution: in multigraphs, the
#' result size is exponentially large in the number of vertex pairs with
#' multiple edges between them.
#'
#' `mean_distance()` calculates the average path length in a graph, by
#' calculating the shortest paths between all pairs of vertices (both ways for
#' directed graphs). It uses a breadth-first search for unweighted graphs and
#' Dijkstra's algorithm for weighted ones. The latter only supports non-negative
#' edge weights.
#'
#' `distance_table()` calculates a histogram, by calculating the shortest
#' path length between each pair of vertices. For directed graphs both
#' directions are considered, so every pair of vertices appears twice in the
#' histogram.
#'
#' @param graph The graph to work on.
#' @param v Numeric vector, the vertices from which the shortest paths will be
#' calculated.
#' @param to Numeric vector, the vertices to which the shortest paths will be
#' calculated. By default it includes all vertices. Note that for
#' `distances()` every vertex must be included here at most once. (This
#' is not required for `shortest_paths()`.
#' @param mode Character constant, gives whether the shortest paths to or from
#' the given vertices should be calculated for directed graphs. If `out`
#' then the shortest paths *from* the vertex, if `in` then *to*
#' it will be considered. If `all`, the default, then the graph is treated
#' as undirected, i.e. edge directions are not taken into account. This
#' argument is ignored for undirected graphs.
#' @param weights Possibly a numeric vector giving edge weights. If this is
#' `NULL` and the graph has a `weight` edge attribute, then the
#' attribute is used. If this is `NA` then no weights are used (even if
#' the graph has a `weight` attribute). In a weighted graph, the length
#' of a path is the sum of the weights of its constituent edges.
#' @param algorithm Which algorithm to use for the calculation. By default
#' igraph tries to select the fastest suitable algorithm. If there are no
#' weights, then an unweighted breadth-first search is used, otherwise if all
#' weights are positive, then Dijkstra's algorithm is used. If there are
#' negative weights and we do the calculation for more than 100 sources, then
#' Johnson's algorithm is used. Otherwise the Bellman-Ford algorithm is used.
#' You can override igraph's choice by explicitly giving this parameter. Note
#' that the igraph C core might still override your choice in obvious cases,
#' i.e. if there are no edge weights, then the unweighted algorithm will be
#' used, regardless of this argument.
#' @param details Whether to provide additional details in the result.
#' Functions accepting this argument (like `mean_distance()`) return
#' additional information like the number of disconnected vertex pairs in
#' the result when this parameter is set to `TRUE`.
#' @param unconnected What to do if the graph is unconnected (not
#' strongly connected if directed paths are considered). If TRUE, only
#' the lengths of the existing paths are considered and averaged; if
#' FALSE, the length of the missing paths are considered as having infinite
#' length, making the mean distance infinite as well.
#' @return For `distances()` a numeric matrix with `length(to)`
#' columns and `length(v)` rows. The shortest path length from a vertex to
#' itself is always zero. For unreachable vertices `Inf` is included.
#'
#' For `shortest_paths()` a named list with four entries is returned:
#' \item{vpath}{This itself is a list, of length `length(to)`; list
#' element `i` contains the vertex ids on the path from vertex `from`
#' to vertex `to[i]` (or the other way for directed graphs depending on
#' the `mode` argument). The vector also contains `from` and `i`
#' as the first and last elements. If `from` is the same as `i` then
#' it is only included once. If there is no path between two vertices then a
#' numeric vector of length zero is returned as the list element. If this
#' output is not requested in the `output` argument, then it will be
#' `NULL`.} \item{epath}{This is a list similar to `vpath`, but the
#' vectors of the list contain the edge ids along the shortest paths, instead
#' of the vertex ids. This entry is set to `NULL` if it is not requested
#' in the `output` argument.} \item{predecessors}{Numeric vector, the
#' predecessor of each vertex in the `to` argument, or `NULL` if it
#' was not requested.} \item{inbound_edges}{Numeric vector, the inbound edge
#' for each vertex, or `NULL`, if it was not requested.}
#'
#' For `all_shortest_paths()` a list is returned, each list element
#' contains a shortest path from `from` to a vertex in `to`. The
#' shortest paths to the same vertex are collected into consecutive elements
#' of the list.
#'
#' For `mean_distance()` a single number is returned if `details=FALSE`,
#' or a named list with two entries: `res` is the mean distance as a numeric
#' scalar and `unconnected` is the number of unconnected vertex pairs,
#' also as a numeric scalar.
#'
#' `distance_table()` returns a named list with two entries: `res` is
#' a numeric vector, the histogram of distances, `unconnected` is a
#' numeric scalar, the number of pairs for which the first vertex is not
#' reachable from the second. In undirected and directed graphs, unorderde
#' and ordered pairs are considered, respectively. Therefore the sum of the
#' two entries is always \eqn{n(n-1)} for directed graphs and \eqn{n(n-1)/2}
#' for undirected graphs.
#' @author Gabor Csardi \email{csardi.gabor@@gmail.com}
#' @references West, D.B. (1996). *Introduction to Graph Theory.* Upper
#' Saddle River, N.J.: Prentice Hall.
#' @family structural.properties
#' @family paths
#' @export
#' @keywords graphs
#' @examples
#'
#' g <- make_ring(10)
#' distances(g)
#' shortest_paths(g, 5)
#' all_shortest_paths(g, 1, 6:8)
#' mean_distance(g)
#' ## Weighted shortest paths
#' el <- matrix(
#' ncol = 3, byrow = TRUE,
#' c(
#' 1, 2, 0,
#' 1, 3, 2,
#' 1, 4, 1,
#' 2, 3, 0,
#' 2, 5, 5,
#' 2, 6, 2,
#' 3, 2, 1,
#' 3, 4, 1,
#' 3, 7, 1,
#' 4, 3, 0,
#' 4, 7, 2,
#' 5, 6, 2,
#' 5, 8, 8,
#' 6, 3, 2,
#' 6, 7, 1,
#' 6, 9, 1,
#' 6, 10, 3,
#' 8, 6, 1,
#' 8, 9, 1,
#' 9, 10, 4
#' )
#' )
#' g2 <- add_edges(make_empty_graph(10), t(el[, 1:2]), weight = el[, 3])
#' distances(g2, mode = "out")
#'
distances <- function(graph, v = V(graph), to = V(graph),
mode = c("all", "out", "in"),
weights = NULL,
algorithm = c(
"automatic", "unweighted", "dijkstra",
"bellman-ford", "johnson", "floyd-warshall"
)) {
ensure_igraph(graph)
# make sure that the lower-level function in C gets mode == "out"
# unconditionally when the graph is undirected; this is used for
# the selection of Johnson's algorithm in automatic mode
if (!is_directed(graph)) {
mode <- "out"
}
v <- as_igraph_vs(graph, v)
to <- as_igraph_vs(graph, to)
mode <- igraph.match.arg(mode)
mode <- switch(mode,
"out" = 1,
"in" = 2,
"all" = 3
)
algorithm <- igraph.match.arg(algorithm)
algorithm <- switch(algorithm,
"automatic" = 0,
"unweighted" = 1,
"dijkstra" = 2,
"bellman-ford" = 3,
"johnson" = 4,
"floyd-warshall" = 5
)
if (is.null(weights)) {
if ("weight" %in% edge_attr_names(graph)) {
weights <- as.numeric(E(graph)$weight)
}
} else {
if (length(weights) == 1 && is.na(weights)) {
weights <- NULL
} else {
weights <- as.numeric(weights)
}
}
if (!is.null(weights) && algorithm == 1) {
weights <- NULL
cli::cli_warn("Unweighted algorithm chosen, {.arg weights} ignored.")
}
on.exit(.Call(R_igraph_finalizer))
res <- .Call(
R_igraph_shortest_paths, graph, v - 1, to - 1,
as.numeric(mode), weights, as.numeric(algorithm)
)
if (igraph_opt("add.vertex.names") && is_named(graph)) {
rownames(res) <- V(graph)$name[v]
colnames(res) <- V(graph)$name[to]
}
res
}
#' @rdname distances
#' @param from Numeric constant, the vertex from or to the shortest paths will
#' be calculated. Note that right now this is not a vector of vertex ids, but
#' only a single vertex.
#' @param output Character scalar, defines how to report the shortest paths.
#' \dQuote{vpath} means that the vertices along the paths are reported, this
#' form was used prior to igraph version 0.6. \dQuote{epath} means that the
#' edges along the paths are reported. \dQuote{both} means that both forms are
#' returned, in a named list with components \dQuote{vpath} and \dQuote{epath}.
#' @param predecessors Logical scalar, whether to return the predecessor vertex
#' for each vertex. The predecessor of vertex `i` in the tree is the
#' vertex from which vertex `i` was reached. The predecessor of the start
#' vertex (in the `from` argument) is itself by definition. If the
#' predecessor is zero, it means that the given vertex was not reached from the
#' source during the search. Note that the search terminates if all the
#' vertices in `to` are reached.
#' @param inbound.edges Logical scalar, whether to return the inbound edge for
#' each vertex. The inbound edge of vertex `i` in the tree is the edge via
#' which vertex `i` was reached. The start vertex and vertices that were
#' not reached during the search will have zero in the corresponding entry of
#' the vector. Note that the search terminates if all the vertices in `to`
#' are reached.
#' @export
shortest_paths <- function(graph, from, to = V(graph),
mode = c("out", "all", "in"),
weights = NULL,
output = c("vpath", "epath", "both"),
predecessors = FALSE, inbound.edges = FALSE,
algorithm = c("automatic", "unweighted", "dijkstra", "bellman-ford")) {
ensure_igraph(graph)
mode <- igraph.match.arg(mode)
mode <- switch(mode,
"out" = 1,
"in" = 2,
"all" = 3
)
output <- igraph.match.arg(output)
output <- switch(output,
"vpath" = 0,
"epath" = 1,
"both" = 2
)
algorithm <- igraph.match.arg(algorithm)
algorithm <- switch(algorithm,
"automatic" = 0,
"unweighted" = 1,
"dijkstra" = 2,
"bellman-ford" = 3
)
if (is.null(weights)) {
if ("weight" %in% edge_attr_names(graph)) {
weights <- as.numeric(E(graph)$weight)
}
} else {
if (length(weights) == 1 && is.na(weights)) {
weights <- NULL
} else {
weights <- as.numeric(weights)
}
}
if (!is.null(weights) && algorithm == 1) {
weights <- NULL
cli::cli_warn("Unweighted algorithm chosen, {.arg weights} ignored.")
}
to <- as_igraph_vs(graph, to) - 1
on.exit(.Call(R_igraph_finalizer))
res <- .Call(
R_igraph_get_shortest_paths, graph,
as_igraph_vs(graph, from) - 1, to, as.numeric(mode),
as.numeric(length(to)), weights, as.numeric(output),
as.logical(predecessors), as.logical(inbound.edges),
as.numeric(algorithm)
)
if (!is.null(res$vpath)) {
res$vpath <- lapply(res$vpath, function(x) x + 1)
}
if (!is.null(res$epath)) {
res$epath <- lapply(res$epath, function(x) x + 1)
}
if (!is.null(res$predecessors)) {
res$predecessors <- res$predecessors + 1
}