forked from igraph/rigraph
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstructural.properties.R
More file actions
2884 lines (2615 loc) · 108 KB
/
Copy pathstructural.properties.R
File metadata and controls
2884 lines (2615 loc) · 108 KB
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
# 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.
#'
#' \code{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.
#'
#' \code{farthest_vertices} returns two vertex ids, the vertices which are
#' connected by the diameter path.
#'
#' @aliases diameter get.diameter farthest.nodes farthest_vertices get_diameter
#' @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 \code{weight} edge attribute, then this is
#' used by default.
#' @return A numeric constant for \code{diameter}, a numeric vector for
#' \code{get_diameter}. \code{farthest_vertices} returns a list with two
#' entries: \itemize{
#' \item \code{vertices} The two vertices that are the farthest.
#' \item \code{distance} Their distance.
#' }
#' @author Gabor Csardi \email{csardi.gabor@@gmail.com}
#' @seealso \code{\link{distances}}
#' @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) {
if (!is_igraph(graph)) {
stop("Not a graph object")
}
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", PACKAGE="igraph") )
.Call("R_igraph_diameter", graph, as.logical(directed),
as.logical(unconnected), weights,
PACKAGE="igraph")
}
#' @export
get_diameter <- function(graph, directed=TRUE, unconnected=TRUE,
weights=NULL) {
if (!is_igraph(graph)) {
stop("Not a graph object")
}
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", PACKAGE="igraph") )
res <- .Call("R_igraph_get_diameter", graph, as.logical(directed),
as.logical(unconnected), weights,
PACKAGE="igraph") + 1L
if (igraph_opt("return.vs.es")) {
res <- create_vs(graph, res)
}
res
}
#' @export
farthest_vertices <- function(graph, directed=TRUE, unconnected=TRUE,
weights=NULL) {
if (!is_igraph(graph)) {
stop("Not a graph object")
}
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", PACKAGE="igraph") )
res <- .Call("R_igraph_farthest_points", graph, as.logical(directed),
as.logical(unconnected), weights,
PACKAGE="igraph")
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
mean_distance <- function(graph, directed=TRUE, unconnected=TRUE) {
if (!is_igraph(graph)) {
stop("Not a graph object")
}
on.exit( .Call("R_igraph_finalizer", PACKAGE="igraph") )
.Call("R_igraph_average_path_length", graph, as.logical(directed),
as.logical(unconnected),
PACKAGE="igraph")
}
#' Degree and degree distribution of the vertices
#'
#' The degree of a vertex is its most basic structural property, the number of
#' its adjacent edges.
#'
#'
#' @aliases degree degree.distribution degree_distribution
#' @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
#' \code{TRUE} then the result is divided by \eqn{n-1}, where \eqn{n} is the
#' number of vertices in the graph.
#' @param \dots Additional arguments to pass to \code{degree}, eg. \code{mode}
#' is useful but also \code{v} and \code{loops} make sense.
#' @return For \code{degree} a numeric vector of the same length as argument
#' \code{v}.
#'
#' For \code{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.
#' @author Gabor Csardi \email{csardi.gabor@@gmail.com}
#' @keywords graphs
#' @export
#' @examples
#'
#' g <- make_ring(10)
#' degree(g)
#' g2 <- sample_gnp(1000, 10/1000)
#' degree_distribution(g2)
#'
degree <- function(graph, v=V(graph),
mode=c("all", "out", "in", "total"), loops=TRUE,
normalized=FALSE){
if (!is_igraph(graph)) {
stop("Not a graph object")
}
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", PACKAGE="igraph") )
res <- .Call("R_igraph_degree", graph, v-1,
as.numeric(mode), as.logical(loops), PACKAGE="igraph")
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
#' @param cumulative Logical; whether the cumulative degree distribution is to
#' be calculated.
#' @export
#' @importFrom graphics hist
degree_distribution <- function(graph, cumulative=FALSE, ...) {
if (!is_igraph(graph)) {
stop("Not a graph object")
}
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
#'
#' \code{distances} calculates the length of all the shortest paths from
#' or to the vertices in the network. \code{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.
#'
#' \code{distances} calculates the lengths of pairwise shortest paths from
#' a set of vertices (\code{from}) to another set of vertices (\code{to}). It
#' uses different algorithms, depending on the \code{argorithm} argument and
#' the \code{weight} edge attribute of the graph. The implemented algorithms
#' are breadth-first search (\sQuote{\code{unweighted}}), this only works for
#' unweighted graphs; the Dijkstra algorithm (\sQuote{\code{dijkstra}}), this
#' works for graphs with non-negative edge weights; the Bellman-Ford algorithm
#' (\sQuote{\code{bellman-ford}}), and Johnson's algorithm
#' (\sQuote{\code{"johnson"}}). The latter two algorithms work with arbitrary
#' edge weights, but (naturally) only for graphs that don't have a negative
#' cycle.
#'
#' 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{\code{automatic}} as the
#' \code{algorithm} argument. (This is also the default.)
#'
#' \code{shortest_paths} calculates a single shortest path (i.e. the path
#' itself, not just its length) between the source vertex given in \code{from},
#' to the target vertices given in \code{to}. \code{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.
#'
#' \code{all_shortest_paths} calculates \emph{all} shortest paths between
#' pairs of vertices. More precisely, between the \code{from} vertex to the
#' vertices given in \code{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.
#'
#' \code{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). This function does not consider edge weights currently and
#' uses a breadth-first search.
#'
#' \code{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.
#'
#' @aliases shortest.paths get.shortest.paths get.all.shortest.paths distances
#' mean_distance distance_table average.path.length path.length.hist
#' all_shortest_paths shortest_paths
#' @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
#' \code{distances} every vertex must be included here at most once. (This
#' is not required for \code{shortest_paths}.
#' @param mode Character constant, gives whether the shortest paths to or from
#' the given vertices should be calculated for directed graphs. If \code{out}
#' then the shortest paths \emph{from} the vertex, if \code{in} then \emph{to}
#' it will be considered. If \code{all}, the default, then the corresponding
#' undirected graph will be used, ie. not directed paths are searched. This
#' argument is ignored for undirected graphs.
#' @param weights Possibly a numeric vector giving edge weights. If this is
#' \code{NULL} and the graph has a \code{weight} edge attribute, then the
#' attribute is used. If this is \code{NA} then no weights are used (even if
#' the graph has a \code{weight} attribute).
#' @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.
#' @return For \code{distances} a numeric matrix with \code{length(to)}
#' columns and \code{length(v)} rows. The shortest path length from a vertex to
#' itself is always zero. For unreachable vertices \code{Inf} is included.
#'
#' For \code{shortest_paths} a named list with four entries is returned:
#' \item{vpath}{This itself is a list, of length \code{length(to)}; list
#' element \code{i} contains the vertex ids on the path from vertex \code{from}
#' to vertex \code{to[i]} (or the other way for directed graphs depending on
#' the \code{mode} argument). The vector also contains \code{from} and \code{i}
#' as the first and last elements. If \code{from} is the same as \code{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 \code{output} argument, then it will be
#' \code{NULL}.} \item{epath}{This is a list similar to \code{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 \code{NULL} if it is not requested
#' in the \code{output} argument.} \item{predecessors}{Numeric vector, the
#' predecessor of each vertex in the \code{to} argument, or \code{NULL} if it
#' was not requested.} \item{inbound_edges}{Numeric vector, the inbound edge
#' for each vertex, or \code{NULL}, if it was not requested.}
#'
#' For \code{all_shortest_paths} a list is returned, each list element
#' contains a shortest path from \code{from} to a vertex in \code{to}. The
#' shortest paths to the same vertex are collected into consecutive elements of
#' the list.
#'
#' For \code{mean_distance} a single number is returned.
#'
#' \code{distance_table} returns a named list with two entries: \code{res} is
#' a numeric vector, the histogram of distances, \code{unconnected} is a
#' numeric scalar, the number of pairs for which the first vertex is not
#' reachable from the second. 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). \emph{Introduction to Graph Theory.} Upper
#' Saddle River, N.J.: Prentice Hall.
#' @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(nc=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")) {
if (!is_igraph(graph)) {
stop("Not a graph object")
}
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)
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
warning("Unweighted algorithm chosen, weights ignored")
}
on.exit( .Call("R_igraph_finalizer", PACKAGE="igraph") )
res <- .Call("R_igraph_shortest_paths", graph, v-1, to-1,
as.numeric(mode), weights, as.numeric(algorithm),
PACKAGE="igraph")
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 \code{i} in the tree is the
#' vertex from which vertex \code{i} was reached. The predecessor of the start
#' vertex (in the \code{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 \code{to} are reached.
#' @param inbound.edges Logical scalar, whether to return the inbound edge for
#' each vertex. The inbound edge of vertex \code{i} in the tree is the edge via
#' which vertex \code{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 \code{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) {
if (!is_igraph(graph)) {
stop("Not a graph object")
}
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)
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)
}
}
to <- as.igraph.vs(graph, to)-1
on.exit( .Call("R_igraph_finalizer", PACKAGE="igraph") )
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),
PACKAGE="igraph")
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
}
if (!is.null(res$inbound_edges)) {
res$inbound_edges <- res$inbound_edges + 1
}
if (igraph_opt("return.vs.es")) {
if (!is.null(res$vpath)) {
res$vpath <- lapply(res$vpath, create_vs, graph = graph)
}
if (!is.null(res$epath)) {
res$epath <- lapply(res$epath, create_es, graph = graph)
}
if (!is.null(res$predecessors)) {
res$predecessors <- create_vs(res$predecessors, graph = graph,
na_ok = TRUE)
}
if (!is.null(res$inbound_edges)) {
res$inbound_edges <- create_es(res$inbound_edges, graph = graph,
na_ok = TRUE)
}
}
res
}
#' @export
#' @rdname distances
all_shortest_paths <- function(graph, from,
to=V(graph),
mode=c("out", "all", "in"),
weights=NULL) {
if (!is_igraph(graph)) {
stop("Not a graph object")
}
mode <- igraph.match.arg(mode)
mode <- switch(mode, "out"=1, "in"=2, "all"=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)
}
}
on.exit( .Call("R_igraph_finalizer", PACKAGE="igraph") )
if (is.null(weights)) {
res <- .Call("R_igraph_get_all_shortest_paths", graph,
as.igraph.vs(graph, from)-1, as.igraph.vs(graph, to)-1,
as.numeric(mode), PACKAGE="igraph")
} else {
res <- .Call("R_igraph_get_all_shortest_paths_dijkstra", graph,
as.igraph.vs(graph, from)-1, as.igraph.vs(graph, to)-1,
weights, as.numeric(mode), PACKAGE="igraph")
}
if (igraph_opt("return.vs.es")) {
res$res <- lapply(res$res, create_vs, graph = graph)
}
res
}
#' In- or out- component of a vertex
#'
#' Finds all vertices reachable from a given vertex, or the opposite: all
#' vertices from which a given vertex is reachable via a directed path.
#'
#' A breadh-first search is conducted starting from vertex \code{v}.
#'
#' @aliases subcomponent
#' @param graph The graph to analyze.
#' @param v The vertex to start the search from.
#' @param mode Character string, either \dQuote{in}, \dQuote{out} or
#' \dQuote{all}. If \dQuote{in} all vertices from which \code{v} is reachable
#' are listed. If \dQuote{out} all vertices reachable from \code{v} are
#' returned. If \dQuote{all} returns the union of these. It is ignored for
#' undirected graphs.
#' @return Numeric vector, the ids of the vertices in the same component as
#' \code{v}.
#' @author Gabor Csardi \email{csardi.gabor@@gmail.com}
#' @seealso \code{\link{components}}
#' @export
#' @keywords graphs
#' @examples
#'
#' g <- sample_gnp(100, 1/200)
#' subcomponent(g, 1, "in")
#' subcomponent(g, 1, "out")
#' subcomponent(g, 1, "all")
subcomponent <- function(graph, v, mode=c("all", "out", "in")) {
if (!is_igraph(graph)) {
stop("Not a graph object")
}
mode <- igraph.match.arg(mode)
mode <- switch(mode, "out"=1, "in"=2, "all"=3)
on.exit( .Call("R_igraph_finalizer", PACKAGE="igraph") )
res <- .Call("R_igraph_subcomponent", graph, as.igraph.vs(graph, v)-1,
as.numeric(mode),
PACKAGE="igraph") + 1L
if (igraph_opt("return.vs.es")) res <- create_vs(graph, res)
res
}
#' Subgraph of a graph
#'
#' \code{subgraph} creates a subgraph of a graph, containing only the specified
#' vertices and all the edges among them.
#'
#' \code{induced_subgraph} calculates the induced subgraph of a set of vertices
#' in a graph. This means that exactly the specified vertices and all the edges
#' between them will be kept in the result graph.
#'
#' \code{subgraph.edges} calculates the subgraph of a graph. For this function
#' one can specify the vertices and edges to keep. This function will be
#' renamed to \code{subgraph} in the next major version of igraph.
#'
#' The \code{subgraph} function does the same as \code{induced.graph} currently
#' (assuming \sQuote{\code{auto}} as the \code{impl} argument), but it is
#' deprecated and will be removed in the next major version of igraph.
#'
#' @aliases subgraph induced.subgraph subgraph.edges induced_subgraph
#' @param graph The original graph.
#' @param v Numeric vector, the vertices of the original graph which will
#' form the subgraph.
#' @return A new graph object.
#' @author Gabor Csardi \email{csardi.gabor@@gmail.com}
#' @export
#' @keywords graphs
#' @examples
#'
#' g <- make_ring(10)
#' g2 <- induced_subgraph(g, 1:7)
#' g3 <- subgraph.edges(g, 1:5, 1:5)
#'
subgraph <- function(graph, v) {
if (!is_igraph(graph)) {
stop("Not a graph object")
}
on.exit( .Call("R_igraph_finalizer", PACKAGE="igraph") )
.Call("R_igraph_subgraph", graph, as.igraph.vs(graph, v)-1,
PACKAGE="igraph")
}
#' @rdname subgraph
#' @param vids Numeric vector, the vertices of the original graph which will
#' form the subgraph.
#' @param impl Character scalar, to choose between two implementation of the
#' subgraph calculation. \sQuote{\code{copy_and_delete}} copies the graph
#' first, and then deletes the vertices and edges that are not included in the
#' result graph. \sQuote{\code{create_from_scratch}} searches for all vertices
#' and edges that must be kept and then uses them to create the graph from
#' scratch. \sQuote{\code{auto}} chooses between the two implementations
#' automatically, using heuristics based on the size of the original and the
#' result graph.
#' @export
induced_subgraph <- function(graph, vids, impl=c("auto", "copy_and_delete", "create_from_scratch")) {
# Argument checks
if (!is_igraph(graph)) { stop("Not a graph object") }
vids <- as.igraph.vs(graph, vids)
impl <- switch(igraph.match.arg(impl), "auto"=0, "copy_and_delete"=1, "create_from_scratch"=2)
on.exit( .Call("R_igraph_finalizer", PACKAGE="igraph") )
# Function call
res <- .Call("R_igraph_induced_subgraph", graph, vids-1, impl,
PACKAGE="igraph")
res
}
#' @rdname subgraph
#' @param eids The edge ids of the edges that will be kept in the result graph.
#' @param delete.vertices Logical scalar, whether to remove vertices that do
#' not have any adjacent edges in \code{eids}.
#' @export
subgraph.edges <- function(graph, eids, delete.vertices=TRUE) {
# Argument checks
if (!is_igraph(graph)) { stop("Not a graph object") }
eids <- as.igraph.es(graph, eids)
delete.vertices <- as.logical(delete.vertices)
on.exit( .Call("R_igraph_finalizer", PACKAGE="igraph") )
# Function call
res <- .Call("R_igraph_subgraph_edges", graph, eids-1, delete.vertices,
PACKAGE="igraph")
res
}
#' @rdname betweenness
#' @param vids The vertices for which the vertex betweenness estimation will be
#' calculated.
#' @param cutoff The maximum path length to consider when calculating the
#' betweenness. If zero or negative then there is no such limit.
#' @export
estimate_betweenness <- function(graph, vids=V(graph), directed=TRUE, cutoff, weights=NULL, nobigint=TRUE) {
# Argument checks
if (!is_igraph(graph)) { stop("Not a graph object") }
vids <- as.igraph.vs(graph, vids)
directed <- as.logical(directed)
cutoff <- as.numeric(cutoff)
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
}
nobigint <- as.logical(nobigint)
on.exit( .Call("R_igraph_finalizer", PACKAGE="igraph") )
# Function call
res <- .Call("R_igraph_betweenness_estimate", graph, vids-1, directed, cutoff, weights, nobigint,
PACKAGE="igraph")
if (igraph_opt("add.vertex.names") && is_named(graph)) {
names(res) <- vertex_attr(graph, "name", vids)
}
res
}
#' Vertex and edge betweenness centrality
#'
#' The vertex and edge betweenness are (roughly) defined by the number of
#' geodesics (shortest paths) going through a vertex or an edge.
#'
#' The vertex betweenness of vertex \eqn{v}{\code{v}} is defined by
#'
#' \deqn{\sum_{i\ne j, i\ne v, j\ne v} g_{ivj}/g_{ij}}{sum( g_ivj / g_ij,
#' i!=j,i!=v,j!=v)}
#'
#' The edge betweenness of edge \eqn{e}{\code{e}} is defined by
#'
#' \deqn{\sum_{i\ne j} g{iej}/g_{ij}.}{sum( g_iej / g_ij, i!=j).}
#'
#' \code{betweenness} calculates vertex betweenness, \code{edge_betweenness}
#' calculates edge betweenness.
#'
#' \code{estimate_betweenness} only considers paths of length \code{cutoff} or
#' smaller, this can be run for larger graphs, as the running time is not
#' quadratic (if \code{cutoff} is small). If \code{cutoff} is zero or negative
#' then the function calculates the exact betweenness scores.
#'
#' \code{estimate_edge_betweenness} is similar, but for edges.
#'
#' For calculating the betweenness a similar algorithm to the one proposed by
#' Brandes (see References) is used.
#'
#' @aliases betweenness edge.betweenness betweenness.estimate
#' edge.betweenness.estimate edge_betweenness estimate_betweenness
#' estimate_edge_betweenness
#' @param graph The graph to analyze.
#' @param v The vertices for which the vertex betweenness will be calculated.
#' @param directed Logical, whether directed paths should be considered while
#' determining the shortest paths.
#' @param weights Optional positive weight vector for calculating weighted
#' betweenness. If the graph has a \code{weight} edge attribute, then this is
#' used by default. Weights are used to calculate weighted shortest paths,
#' so they are interpreted as distances.
#' @param nobigint Logical scalar, whether to use big integers during the
#' calculation. This is only required for lattice-like graphs that have very
#' many shortest paths between a pair of vertices. If \code{TRUE} (the
#' default), then big integers are not used.
#' @param normalized Logical scalar, whether to normalize the betweenness
#' scores. If \code{TRUE}, then the results are normalized according to
#' \deqn{B^n=\frac{2B}{n^2-3n+2}}{Bnorm=2*B/(n*n-3*n+2)}, where
#' \eqn{B^n}{Bnorm} is the normalized, \eqn{B} the raw betweenness, and \eqn{n}
#' is the number of vertices in the graph.
#' @return A numeric vector with the betweenness score for each vertex in
#' \code{v} for \code{betweenness}.
#'
#' A numeric vector with the edge betweenness score for each edge in \code{e}
#' for \code{edge_betweenness}.
#'
#' \code{estimate_betweenness} returns the estimated betweenness scores for
#' vertices in \code{vids}, \code{estimate_edge_betweenness} the estimated edge
#' betweenness score for \emph{all} edges; both in a numeric vector.
#' @note \code{edge_betweenness} might give false values for graphs with
#' multiple edges.
#' @author Gabor Csardi \email{csardi.gabor@@gmail.com}
#' @seealso \code{\link{closeness}}, \code{\link{degree}}
#' @references Freeman, L.C. (1979). Centrality in Social Networks I:
#' Conceptual Clarification. \emph{Social Networks}, 1, 215-239.
#'
#' Ulrik Brandes, A Faster Algorithm for Betweenness Centrality. \emph{Journal
#' of Mathematical Sociology} 25(2):163-177, 2001.
#' @export
#' @keywords graphs
#' @examples
#'
#' g <- sample_gnp(10, 3/10)
#' betweenness(g)
#' edge_betweenness(g)
#'
betweenness <- function(graph, v=V(graph), directed=TRUE, weights=NULL,
nobigint=TRUE, normalized=FALSE) {
if (!is_igraph(graph)) {
stop("Not a graph object")
}
v <- as.igraph.vs(graph, v)
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", PACKAGE="igraph") )
res <- .Call("R_igraph_betweenness", graph, v-1,
as.logical(directed), weights, as.logical(nobigint),
PACKAGE="igraph")
if (normalized) {
vc <- vcount(graph)
if (is_directed(graph) && directed) {
res <- res / ( vc*vc-3*vc+2)
} else {
res <- 2*res / ( vc*vc-3*vc+2)
}
}
if (igraph_opt("add.vertex.names") && is_named(graph)) {
names(res) <- V(graph)$name[v]
}
res
}
#' Transitivity of a graph
#'
#' Transitivity measures the probability that the adjacent vertices of a vertex
#' are connected. This is sometimes also called the clustering coefficient.
#'
#' Note that there are essentially two classes of transitivity measures, one is
#' a vertex-level, the other a graph level property.
#'
#' There are several generalizations of transitivity to weighted graphs, here
#' we use the definition by A. Barrat, this is a local vertex-level quantity,
#' its formula is
#'
#' \deqn{C_i^w=\frac{1}{s_i(k_i-1)}\sum_{j,h}\frac{w_{ij}+w_{ih}}{2}a_{ij}a_{ih}a_{jh}}{
#' weighted C_i = 1/s_i 1/(k_i-1) sum( (w_ij+w_ih)/2 a_ij a_ih a_jh, j, h)}
#'
#' \eqn{s_i}{s_i} is the strength of vertex \eqn{i}{i}, see
#' \code{\link{strength}}, \eqn{a_{ij}}{a_ij} are elements of the
#' adjacency matrix, \eqn{k_i}{k_i} is the vertex degree, \eqn{w_{ij}}{w_ij}
#' are the weights.
#'
#' This formula gives back the normal not-weighted local transitivity if all
#' the edge weights are the same.
#'
#' The \code{barrat} type of transitivity does not work for graphs with
#' multiple and/or loop edges. If you want to calculate it for a directed
#' graph, call \code{\link{as.undirected}} with the \code{collapse} mode first.
#'
#' @param graph The graph to analyze.
#' @param type The type of the transitivity to calculate. Possible values:
#' \describe{ \item{"global"}{The global transitivity of an undirected
#' graph (directed graphs are considered as undirected ones as well). This is
#' simply the ratio of the triangles and the connected triples in the graph.
#' For directed graph the direction of the edges is ignored. }
#' \item{"local"}{The local transitivity of an undirected graph, this is
#' calculated for each vertex given in the \code{vids} argument. The local
#' transitivity of a vertex is the ratio of the triangles connected to the
#' vertex and the triples centered on the vertex. For directed graph the
#' direction of the edges is ignored. } \item{"undirected"}{This is the
#' same as \code{global}.} \item{"globalundirected"}{This is the same as
#' \code{global}.} \item{"localundirected"}{This is the same as
#' \code{local}.} \item{"barrat"}{The weighted transitivity as defined A.
#' Barrat. See details below.} \item{"weighted"}{The same as
#' \code{barrat}.} }
#' @param vids The vertex ids for the local transitivity will be calculated.
#' This will be ignored for global transitivity types. The default value is
#' \code{NULL}, in this case all vertices are considered. It is slightly faster
#' to supply \code{NULL} here than \code{V(graph)}.
#' @param weights Optional weights for weighted transitivity. It is ignored for
#' other transitivity measures. If it is \code{NULL} (the default) and the
#' graph has a \code{weight} edge attribute, then it is used automatically.
#' @param isolates Character scalar, defines how to treat vertices with degree
#' zero and one. If it is \sQuote{\code{NaN}} then they local transitivity is
#' reported as \code{NaN} and they are not included in the averaging, for the
#' transitivity types that calculate an average. If there are no vertices with
#' degree two or higher, then the averaging will still result \code{NaN}. If it
#' is \sQuote{\code{zero}}, then we report 0 transitivity for them, and they
#' are included in the averaging, if an average is calculated.
#' @return For \sQuote{\code{global}} a single number, or \code{NaN} if there
#' are no connected triples in the graph.
#'
#' For \sQuote{\code{local}} a vector of transitivity scores, one for each
#' vertex in \sQuote{\code{vids}}.
#' @author Gabor Csardi \email{csardi.gabor@@gmail.com}
#' @references Wasserman, S., and Faust, K. (1994). \emph{Social Network
#' Analysis: Methods and Applications.} Cambridge: Cambridge University Press.
#'
#' Alain Barrat, Marc Barthelemy, Romualdo Pastor-Satorras, Alessandro
#' Vespignani: The architecture of complex weighted networks, Proc. Natl. Acad.
#' Sci. USA 101, 3747 (2004)
#' @export
#' @keywords graphs
#' @examples
#'
#' g <- make_ring(10)
#' transitivity(g)
#' g2 <- sample_gnp(1000, 10/1000)
#' transitivity(g2) # this is about 10/1000
#'
#' # Weighted version, the figure from the Barrat paper
#' gw <- graph_from_literal(A-B:C:D:E, B-C:D, C-D)
#' E(gw)$weight <- 1
#' E(gw)[ V(gw)[name == "A"] %--% V(gw)[name == "E" ] ]$weight <- 5
#' transitivity(gw, vids="A", type="local")
#' transitivity(gw, vids="A", type="weighted")
#'
#' # Weighted reduces to "local" if weights are the same
#' gw2 <- sample_gnp(1000, 10/1000)
#' E(gw2)$weight <- 1
#' t1 <- transitivity(gw2, type="local")
#' t2 <- transitivity(gw2, type="weighted")
#' all(is.na(t1) == is.na(t2))
#' all(na.omit(t1 == t2))
#'
transitivity <- function(graph, type=c("undirected", "global", "globalundirected",
"localundirected", "local", "average",
"localaverage", "localaverageundirected",
"barrat", "weighted"),
vids=NULL, weights=NULL, isolates=c("NaN", "zero")) {
if (!is_igraph(graph)) {
stop("Not a graph object")
}
type <- igraph.match.arg(type)
type <- switch(type, "undirected"=0, "global"=0, "globalundirected"=0,
"localundirected"=1, "local"=1, "average"=2,
"localaverage"=2, "localaverageundirected"=2, "barrat"=3,
"weighted"=3)
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
}
isolates <- igraph.match.arg(isolates)
isolates <- as.double(switch(isolates, "nan"=0, "zero"=1))
on.exit( .Call("R_igraph_finalizer", PACKAGE="igraph") )
if (type==0) {
.Call("R_igraph_transitivity_undirected", graph, isolates,
PACKAGE="igraph")
} else if (type==1) {
if (is.null(vids)) {
.Call("R_igraph_transitivity_local_undirected_all", graph, isolates,
PACKAGE="igraph")
} else {
vids <- as.igraph.vs(graph, vids)-1
.Call("R_igraph_transitivity_local_undirected", graph, vids,
isolates, PACKAGE="igraph")
}
} else if (type==2) {
.Call("R_igraph_transitivity_avglocal_undirected", graph, isolates,
PACKAGE="igraph")
} else if (type==3) {
if (is.null(vids)) { vids <- V(graph) }
vids <- as.igraph.vs(graph, vids)-1
if (is.null(weights)) {
.Call("R_igraph_transitivity_local_undirected", graph, vids,
isolates, PACKAGE="igraph")
} else {
.Call("R_igraph_transitivity_barrat", graph, vids, weights,
isolates, PACKAGE="igraph")
}
}
}
## Generated by stimulus now
## laplacian_matrix <- function(graph, normalized=FALSE) {
## if (!is_igraph(graph)) {