-
-
Notifications
You must be signed in to change notification settings - Fork 207
Expand file tree
/
Copy pathcentrality.R
More file actions
2197 lines (2109 loc) · 71.9 KB
/
centrality.R
File metadata and controls
2197 lines (2109 loc) · 71.9 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
#' Find subgraph centrality scores of network positions
#'
#' @description
#' `r lifecycle::badge("deprecated")`
#'
#' `subgraph.centrality()` was renamed to [subgraph_centrality()] to create a more
#' consistent API.
#' @inheritParams subgraph_centrality
#' @keywords internal
#' @export
subgraph.centrality <- function(graph, diag = FALSE) {
# nocov start
lifecycle::deprecate_soft(
"2.0.0",
"subgraph.centrality()",
"subgraph_centrality()"
)
subgraph_centrality(graph = graph, diag = diag)
} # nocov end
#' The Page Rank algorithm
#'
#' @description
#' `r lifecycle::badge("deprecated")`
#'
#' `page.rank()` was renamed to [page_rank()] to create a more
#' consistent API.
#' @inheritParams page_rank
#' @keywords internal
#' @export
page.rank <- function(
graph,
algo = c("prpack", "arpack"),
vids = V(graph),
directed = TRUE,
damping = 0.85,
personalized = NULL,
weights = NULL,
options = NULL
) {
# nocov start
lifecycle::deprecate_soft("2.0.0", "page.rank()", "page_rank()")
page_rank(
graph = graph,
algo = algo,
vids = vids,
directed = directed,
damping = damping,
personalized = personalized,
weights = weights,
options = options
)
} # nocov end
#' Kleinberg's hub and authority centrality scores.
#'
#' @description
#' `r lifecycle::badge("deprecated")`
#'
#' `hub.score()` was renamed to [hub_score()] to create a more
#' consistent API.
#' @inheritParams hub_score
#' @keywords internal
#' @export
hub.score <- function(
graph,
scale = TRUE,
weights = NULL,
options = arpack_defaults()
) {
# nocov start
lifecycle::deprecate_warn("2.0.0", "hub.score()", "hits_scores()")
hub_score(graph = graph, scale = scale, weights = weights, options = options)
} # nocov end
#' Kleinberg's hub and authority centrality scores.
#'
#' @description
#' `r lifecycle::badge("deprecated")`
#'
#' `authority.score()` was renamed to [authority_score()] to create a more
#' consistent API.
#' @inheritParams authority_score
#' @keywords internal
#' @export
authority.score <- function(
graph,
scale = TRUE,
weights = NULL,
options = arpack_defaults()
) {
# nocov start
lifecycle::deprecate_warn("2.0.0", "authority.score()", "hits_scores()")
authority_score(
graph = graph,
scale = scale,
weights = weights,
options = options
)
} # nocov end
#' Strength or weighted vertex degree
#'
#' @description
#' `r lifecycle::badge("deprecated")`
#'
#' `graph.strength()` was renamed to [strength()] to create a more
#' consistent API.
#' @inheritParams strength
#' @keywords internal
#' @export
graph.strength <- function(
graph,
vids = V(graph),
mode = c("all", "out", "in", "total"),
loops = TRUE,
weights = NULL
) {
# nocov start
lifecycle::deprecate_soft("2.0.0", "graph.strength()", "strength()")
strength(
graph = graph,
vids = vids,
mode = mode,
loops = loops,
weights = weights
)
} # nocov end
#' Eigenvalues and eigenvectors of the adjacency matrix of a graph
#'
#' @description
#' `r lifecycle::badge("deprecated")`
#'
#' `graph.eigen()` was renamed to [spectrum()] to create a more
#' consistent API.
#' @inheritParams spectrum
#' @keywords internal
#' @export
graph.eigen <- function(
graph,
algorithm = c(
"arpack",
"auto",
"lapack",
"comp_auto",
"comp_lapack",
"comp_arpack"
),
which = list(),
options = arpack_defaults()
) {
# nocov start
lifecycle::deprecate_soft("2.0.0", "graph.eigen()", "spectrum()")
spectrum(
graph = graph,
algorithm = algorithm,
which = which,
options = options
)
} # nocov end
#' Graph diversity
#'
#' @description
#' `r lifecycle::badge("deprecated")`
#'
#' `graph.diversity()` was renamed to [diversity()] to create a more
#' consistent API.
#' @inheritParams diversity
#' @keywords internal
#' @export
graph.diversity <- function(graph, weights = NULL, vids = V(graph)) {
# nocov start
lifecycle::deprecate_soft("2.0.0", "graph.diversity()", "diversity()")
diversity(graph = graph, weights = weights, vids = vids)
} # nocov end
#' Find Eigenvector Centrality Scores of Network Positions
#'
#' @description
#' `r lifecycle::badge("deprecated")`
#'
#' `evcent()` was renamed to [eigen_centrality()] to create a more
#' consistent API.
#' @inheritParams eigen_centrality
#' @keywords internal
#' @export
evcent <- function(
graph,
directed = FALSE,
scale = TRUE,
weights = NULL,
options = arpack_defaults()
) {
# nocov start
lifecycle::deprecate_soft("2.0.0", "evcent()", "eigen_centrality()")
eigen_centrality(
graph = graph,
directed = directed,
scale = scale,
weights = weights,
options = options
)
} # nocov end
#' Vertex and edge betweenness centrality
#'
#' @description
#' `r lifecycle::badge("deprecated")`
#'
#' `edge.betweenness()` was renamed to [edge_betweenness()] to create a more
#' consistent API.
#' @inheritParams edge_betweenness
#' @keywords internal
#' @export
edge.betweenness <- function(
graph,
e = E(graph),
directed = TRUE,
weights = NULL,
cutoff = -1
) {
# nocov start
lifecycle::deprecate_soft("2.0.0", "edge.betweenness()", "edge_betweenness()")
edge_betweenness(
graph = graph,
e = e,
directed = directed,
weights = weights,
cutoff = cutoff
)
} # nocov end
#' Find Bonacich Power Centrality Scores of Network Positions
#'
#' @description
#' `r lifecycle::badge("deprecated")`
#'
#' `bonpow()` was renamed to [power_centrality()] to create a more
#' consistent API.
#' @inheritParams power_centrality
#' @keywords internal
#' @export
bonpow <- function(
graph,
nodes = V(graph),
loops = FALSE,
exponent = 1,
rescale = FALSE,
tol = 1e-7,
sparse = TRUE
) {
# nocov start
lifecycle::deprecate_soft("2.0.0", "bonpow()", "power_centrality()")
power_centrality(
graph = graph,
nodes = nodes,
loops = loops,
exponent = exponent,
rescale = rescale,
tol = tol,
sparse = sparse
)
} # nocov end
#' Find Bonacich alpha centrality scores of network positions
#'
#' @description
#' `r lifecycle::badge("deprecated")`
#'
#' `alpha.centrality()` was renamed to [alpha_centrality()] to create a more
#' consistent API.
#' @inheritParams alpha_centrality
#' @keywords internal
#' @export
alpha.centrality <- function(
graph,
nodes = V(graph),
alpha = 1,
loops = FALSE,
exo = 1,
weights = NULL,
tol = 1e-7,
sparse = TRUE
) {
# nocov start
lifecycle::deprecate_soft("2.0.0", "alpha.centrality()", "alpha_centrality()")
alpha_centrality(
graph = graph,
nodes = nodes,
alpha = alpha,
loops = loops,
exo = exo,
weights = weights,
tol = tol,
sparse = sparse
)
} # nocov end
# IGraph R package
# Copyright (C) 2005-2012 Gabor Csardi <[email protected]>
# 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
#
###################################################################
#' Deprecated version of `betweenness()`
#'
#' @description
#' `r lifecycle::badge("deprecated")`
#'
#' Use [betweenness()] with the `cutoff` argument instead.
#' @param vids The vertices for which the vertex betweenness estimation will be
#' calculated.
#' @inheritParams betweenness
#' @keywords internal
#' @export
estimate_betweenness <- function(
graph,
vids = V(graph),
directed = TRUE,
cutoff,
weights = NULL
) {
lifecycle::deprecate_soft(
"1.6.0",
"estimate_betweenness()",
"betweenness()",
details = "with the cutoff argument."
)
betweenness(
graph,
v = vids,
directed = directed,
cutoff = cutoff,
weights = weights
)
}
#' @export
betweenness.estimate <- estimate_betweenness
#' 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 `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 `e` is defined by
#'
#' \deqn{\sum_{i\ne j} g_{iej}/g_{ij}.}{sum( g_iej / g_ij, i!=j).}
#'
#' `betweenness()` calculates vertex betweenness, `edge_betweenness()`
#' calculates edge betweenness.
#'
#' Here \eqn{g_{ij}}{g_ij} is the total number of shortest paths between vertices
#' \eqn{i} and \eqn{j} while \eqn{g_{ivj}} is the number of those shortest paths
#' which pass though vertex \eqn{v}.
#'
#' Both functions allow you to consider only paths of length `cutoff` or
#' smaller; this can be run for larger graphs, as the running time is not
#' quadratic (if `cutoff` is small). If `cutoff` is negative (the default),
#' then the function calculates the exact betweenness scores. Since igraph 1.6.0,
#' a `cutoff` value of zero is treated literally, i.e. paths of length larger
#' than zero are ignored.
#'
#' For calculating the betweenness a similar algorithm to the one proposed by
#' Brandes (see References) is used.
#'
#' @aliases betweenness.estimate
#' @aliases edge.betweenness.estimate
#' @param graph The graph to analyze.
#' @param vids 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 `weight` edge attribute, then this is
#' used by default. Weights are used to calculate weighted shortest paths,
#' so they are interpreted as distances.
#' @param normalized Logical scalar, whether to normalize the betweenness
#' scores. If `TRUE`, then the results are normalized by the number of ordered
#' or unordered vertex pairs in directed and undirected graphs, respectively.
#' In an undirected graph,
#' \deqn{B^n=\frac{2B}{(n-1)(n-2)},}{Bnorm=2 B / ((n-1)(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. Note that the same
#' normalization factor is used even when setting a `cutoff` on the considered
#' shortest path lengths, even though the number of vertex pairs reachable
#' from each other may be less than \eqn{(n-1)(n-2)/2}.
#' @param cutoff The maximum shortest path length to consider when calculating
#' betweenness. If negative, then there is no such limit.
#' @return A numeric vector with the betweenness score for each vertex in
#' `vids` for `betweenness()`.
#'
#' A numeric vector with the edge betweenness score for each edge in `e`
#' for `edge_betweenness()`.
#'
#' @note `edge_betweenness()` might give false values for graphs with
#' multiple edges.
#' @author Gabor Csardi \email{csardi.gabor@@gmail.com}
#' @seealso [closeness()], [degree()], [harmonic_centrality()]
#' @references Freeman, L.C. (1979). Centrality in Social Networks I:
#' Conceptual Clarification. *Social Networks*, 1, 215-239.
#' \doi{10.1016/0378-8733(78)90021-7}
#'
#' Ulrik Brandes, A Faster Algorithm for Betweenness Centrality. *Journal
#' of Mathematical Sociology* 25(2):163-177, 2001.
#' \doi{10.1080/0022250X.2001.9990249}
#' @family centrality
#' @export
#' @keywords graphs
#' @examples
#'
#' g <- sample_gnp(10, 3 / 10)
#' betweenness(g)
#' edge_betweenness(g)
#'
betweenness <- function(
graph,
vids = V(graph),
directed = TRUE,
weights = NULL,
normalized = FALSE,
cutoff = -1
) {
res <- betweenness_cutoff_impl(
graph = graph,
vids = vids,
directed = directed,
weights = weights,
cutoff = cutoff
)
if (normalized) {
vc <- as.numeric(vcount(graph))
if (is_directed(graph) && directed) {
res <- res / (vc * vc - 3 * vc + 2)
} else {
res <- 2 * res / (vc * vc - 3 * vc + 2)
}
}
res
}
#' @rdname betweenness
#' @param e The edges for which the edge betweenness will be calculated.
#' @export
edge_betweenness <- function(
graph,
e = E(graph),
directed = TRUE,
weights = NULL,
cutoff = -1
) {
e <- as_igraph_es(graph, e)
res <- edge_betweenness_cutoff_impl(
graph = graph,
directed = directed,
weights = weights,
cutoff = cutoff
)
res[as.numeric(e)]
}
#' Deprecated version of `edge_betweenness()`
#'
#' @description
#' `r lifecycle::badge("deprecated")`
#'
#' Use [edge_betweenness()] with the `cutoff` argument instead.
#' @inheritParams edge_betweenness
#' @keywords internal
#' @export
estimate_edge_betweenness <- function(
graph,
e = E(graph),
directed = TRUE,
cutoff,
weights = NULL
) {
lifecycle::deprecate_soft(
"1.6.0",
"estimate_edge_betweenness()",
"edge_betweenness()",
details = "with the cutoff argument."
)
edge_betweenness(
graph,
e,
directed = directed,
cutoff = cutoff,
weights = weights
)
}
#' @export
edge.betweenness.estimate <- estimate_edge_betweenness
#' Closeness centrality of vertices
#'
#' Closeness centrality measures how many steps are required to access every other
#' vertex from a given vertex.
#'
#' The closeness centrality of a vertex is defined as the inverse of the
#' sum of distances to all the other vertices in the graph:
#'
#' \deqn{\frac{1}{\sum_{i\ne v} d_{vi}}}{1/sum( d(v,i), i != v)}
#'
#' If there is no (directed) path between vertex `v` and `i`, then
#' `i` is omitted from the calculation. If no other vertices are reachable
#' from `v`, then its closeness is returned as NaN.
#'
# " You may use the \code{cutoff} argument to consider only paths of length
#' `cutoff` or smaller. This can be run for larger graphs, as the running
#' time is not quadratic (if `cutoff` is small). If `cutoff` is
#' negative (which is the default), then the function calculates the exact
#' closeness scores. Since igraph 1.6.0, a `cutoff` value of zero is treated
#' literally, i.e. path with a length greater than zero are ignored.
#'
#' Closeness centrality is meaningful only for connected graphs. In disconnected
#' graphs, consider using the harmonic centrality with
#' [harmonic_centrality()]
#'
#' @aliases closeness.estimate
#' @param graph The graph to analyze.
#' @param vids The vertices for which closeness will be calculated.
#' @param mode Character string, defined the types of the paths used for
#' measuring the distance in directed graphs. \dQuote{in} measures the paths
#' *to* a vertex, \dQuote{out} measures paths *from* a vertex,
#' *all* uses undirected paths. This argument is ignored for undirected
#' graphs.
#' @param normalized Logical scalar, whether to calculate the normalized
#' closeness, i.e. the inverse average distance to all reachable vertices.
#' The non-normalized closeness is the inverse of the sum of distances to
#' all reachable vertices.
#' @param weights Optional positive weight vector for calculating weighted
#' closeness. If the graph has a `weight` edge attribute, then this is
#' used by default. Weights are used for calculating weighted shortest
#' paths, so they are interpreted as distances.
#' @param cutoff The maximum path length to consider when calculating the
#' closeness. If zero or negative then there is no such limit.
#' @return Numeric vector with the closeness values of all the vertices in
#' `v`.
#' @author Gabor Csardi \email{csardi.gabor@@gmail.com}
#' @references Freeman, L.C. (1979). Centrality in Social Networks I:
#' Conceptual Clarification. *Social Networks*, 1, 215-239.
#' @family centrality
#' @export
#' @keywords graphs
#' @examples
#'
#' g <- make_ring(10)
#' g2 <- make_star(10)
#' closeness(g)
#' closeness(g2, mode = "in")
#' closeness(g2, mode = "out")
#' closeness(g2, mode = "all")
#'
closeness <- function(
graph,
vids = V(graph),
mode = c("out", "in", "all", "total"),
weights = NULL,
normalized = FALSE,
cutoff = -1
) {
# Argument checks
ensure_igraph(graph)
vids <- as_igraph_vs(graph, vids)
mode <- switch(
igraph.match.arg(mode),
"out" = 1,
"in" = 2,
"all" = 3,
"total" = 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
}
normalized <- as.logical(normalized)
cutoff <- as.numeric(cutoff)
on.exit(.Call(R_igraph_finalizer))
# Function call
res <- .Call(
R_igraph_closeness_cutoff,
graph,
vids - 1,
mode,
weights,
normalized,
cutoff
)$res
if (igraph_opt("add.vertex.names") && is_named(graph)) {
names(res) <- V(graph)$name[vids]
}
res
}
#' Deprecated version of `closeness()`
#'
#' @description
#' `r lifecycle::badge("deprecated")`
#'
#' Use [closeness()] with the `cutoff` argument instead.
#' @inheritParams closeness
#' @keywords internal
#' @export
estimate_closeness <- function(
graph,
vids = V(graph),
mode = c("out", "in", "all", "total"),
cutoff,
weights = NULL,
normalized = FALSE
) {
lifecycle::deprecate_soft(
"1.6.0",
"estimate_closeness()",
"closeness()",
details = "with the cutoff argument."
)
closeness(
graph,
vids,
mode = mode,
weights = weights,
normalized = normalized,
cutoff = cutoff
)
}
#' @export
closeness.estimate <- estimate_closeness
#' @rdname arpack
#' @family arpack
#' @export
arpack_defaults <- function() {
list(
bmat = "I",
n = 0,
which = "XX",
nev = 1,
tol = 0.0,
ncv = 3,
ldv = 0,
ishift = 1,
maxiter = 3000,
nb = 1,
mode = 1,
start = 0,
sigma = 0.0,
sigmai = 0.0
)
}
#' ARPACK eigenvector calculation
#'
#' Interface to the ARPACK library for calculating eigenvectors of sparse
#' matrices
#'
#' @details
#' ARPACK is a library for solving large scale eigenvalue problems. The
#' package is designed to compute a few eigenvalues and corresponding
#' eigenvectors of a general \eqn{n} by \eqn{n} matrix \eqn{A}. It is most
#' appropriate for large sparse or structured matrices \eqn{A} where structured
#' means that a matrix-vector product `w <- Av` requires order \eqn{n}
#' rather than the usual order \eqn{n^2} floating point operations.
#'
#' This function is an interface to ARPACK. igraph does not contain all ARPACK
#' routines, only the ones dealing with symmetric and non-symmetric eigenvalue
#' problems using double precision real numbers.
#'
#' The eigenvalue calculation in ARPACK (in the simplest case) involves the
#' calculation of the \eqn{Av} product where \eqn{A} is the matrix we work with
#' and \eqn{v} is an arbitrary vector. The function supplied in the `fun`
#' argument is expected to perform this product. If the product can be done
#' efficiently, e.g. if the matrix is sparse, then `arpack()` is usually
#' able to calculate the eigenvalues very quickly.
#'
#' @details
#' The `options` argument specifies what kind of calculation to perform.
#' It is a list with the following members, they correspond directly to ARPACK
#' parameters. On input it has the following fields:
#' \describe{
#' \item{bmat}{
#' Character constant, possible values:
#' \sQuote{`I`}, standard eigenvalue problem, \eqn{Ax=\lambda x}{A*x=lambda*x}; and
#' \sQuote{`G`}, generalized eigenvalue problem, \eqn{Ax=\lambda B x}{A*x=lambda B*x}.
#' Currently only \sQuote{`I`} is supported.
#' }
#' \item{n}{
#' Numeric scalar. The dimension of the eigenproblem.
#' You only need to set this if you call [arpack()] directly.
#' (I.e. not needed for [eigen_centrality()], [page_rank()], etc.)
#' }
#' \item{which}{
#' Specify which eigenvalues/vectors to compute,
#' character constant with exactly two characters.
#' Possible values for symmetric input matrices:
#' \describe{
#' \item{"LA"}{
#' Compute `nev` largest (algebraic) eigenvalues.
#' }
#' \item{"SA"}{
#' Compute `nev` smallest (algebraic) eigenvalues.
#' }
#' \item{"LM"}{
#' Compute `nev` largest (in magnitude) eigenvalues.
#' }
#' \item{"SM"}{
#' Compute `nev` smallest (in magnitude) eigenvalues.
#' }
#' \item{"BE"}{
#' Compute `nev` eigenvalues, half from each end of the spectrum.
#' When `nev` is odd, compute one more from the high end than from the low end.
#' }
#' }
#' Possible values for non-symmetric input matrices:
#' \describe{
#' \item{"LM"}{
#' Compute `nev` eigenvalues of largest magnitude.
#' }
#' \item{"SM"}{
#' Compute `nev` eigenvalues of smallest magnitude.
#' }
#' \item{"LR"}{
#' Compute `nev` eigenvalues of largest real part.
#' }
#' \item{"SR"}{
#' Compute `nev` eigenvalues of smallest real part.
#' }
#' \item{"LI"}{
#' Compute `nev` eigenvalues of largest imaginary part.
#' }
#' \item{"SI"}{
#' Compute `nev` eigenvalues of smallest imaginary part.
#' }
#' }
#' This parameter is sometimes overwritten by the various functions,
#' e.g. [page_rank()] always sets \sQuote{`LM`}.
#' }
#' \item{nev}{
#' Numeric scalar. The number of eigenvalues to be computed.
#' }
#' \item{tol}{
#' Numeric scalar. Stopping criterion:
#' the relative accuracy of the Ritz value is considered acceptable
#' if its error is less than `tol` times its estimated value.
#' If this is set to zero then machine precision is used.
#' }
#' \item{ncv}{
#' Number of Lanczos vectors to be generated.
#' }
#' \item{ldv}{
#' Numberic scalar. It should be set to zero in the current implementation.
#' }
#' \item{ishift}{
#' Either zero or one.
#' If zero then the shifts are provided by the user via reverse communication.
#' If one then exact shifts with respect to the reduced tridiagonal matrix \eqn{T}.
#' Please always set this to one.
#' }
#' \item{maxiter}{
#' Maximum number of Arnoldi update iterations allowed.
#' }
#' \item{nb}{
#' Blocksize to be used in the recurrence. Please always leave this on the default value, one.
#' }
#' \item{mode}{
#' The type of the eigenproblem to be solved. Possible values if the input matrix is symmetric:
#' \describe{
#' \item{1}{
#' \eqn{Ax=\lambda x}{A*x=lambda*x}, \eqn{A} is symmetric.
#' }
#' \item{2}{
#' \eqn{Ax=\lambda Mx}{A*x=lambda*M*x}, \eqn{A} is symmetric, \eqn{M} is symmetric positive definite.
#' }
#' \item{3}{
#' \eqn{Kx=\lambda Mx}{K*x=lambda*M*x}, \eqn{K} is symmetric, \eqn{M} is symmetric positive semi-definite.
#' }
#' \item{4}{
#' \eqn{Kx=\lambda KGx}{K*x=lambda*KG*x}, \eqn{K} is symmetric positive semi-definite, \eqn{KG} is symmetric indefinite.
#' }
#' \item{5}{
#' \eqn{Ax=\lambda Mx}{A*x=lambda*M*x}, \eqn{A} is symmetric, \eqn{M} is symmetric positive semi-definite. (Cayley transformed mode.)
#' }
#' }
#' Please note that only `mode==1` was tested and other values might not work properly.
#' Possible values if the input matrix is not symmetric:
#' \describe{
#' \item{1}{
#' \eqn{Ax=\lambda x}{A*x=lambda*x}.
#' }
#' \item{2}{
#' \eqn{Ax=\lambda Mx}{A*x=lambda*M*x}, \eqn{M} is symmetric positive definite.
#' }
#' \item{3}{
#' \eqn{Ax=\lambda Mx}{A*x=lambda*M*x}, \eqn{M} is symmetric semi-definite.
#' }
#' \item{4}{
#' \eqn{Ax=\lambda Mx}{A*x=lambda*M*x}, \eqn{M} is symmetric semi-definite.
#' }
#' }
#' Please note that only `mode==1` was tested and other values might not work properly.
#' }
#' \item{start}{
#' Not used currently. Later it be used to set a starting vector.
#' }
#' \item{sigma}{
#' Not used currently.
#' }
#' \item{sigmai}{
#' Not use currently.
#' }
#' }
#'
#' @details:
#' On output the following additional fields are added:
#'
#' \describe{
#' \item{info}{
#' Error flag of ARPACK. Possible values:
#' \describe{
#' \item{0}{
#' Normal exit.
#' }
#' \item{1}{
#' Maximum number of iterations taken.
#' }
#' \item{3}{
#' No shifts could be applied during a cycle
#' of the implicitly restarted Arnoldi iteration.
#' One possibility is to increase the size of `ncv` relative to `nev`.
#' }
#' }
#' ARPACK can return more error conditions than these,
#' but they are converted to regular igraph errors.
#' }
#' \item{iter}{
#' Number of Arnoldi iterations taken.
#' }
#' \item{nconv}{
#' Number of \dQuote{converged} Ritz values.
#' This represents the number of Ritz values that satisfy the convergence critetion.
#' }
#' \item{numop}{
#' Total number of matrix-vector multiplications.
#' }
#' \item{numopb}{
#' Not used currently.
#' }
#' \item{numreo}{
#' Total number of steps of re-orthogonalization.
#' }
#' }
#'
#' Please see the ARPACK documentation for additional details.
#'
#' @aliases arpack arpack-options arpack.unpack.complex
#' @aliases arpack_defaults
#' @param func The function to perform the matrix-vector multiplication. ARPACK
#' requires to perform these by the user. The function gets the vector \eqn{x}
#' as the first argument, and it should return \eqn{Ax}, where \eqn{A} is the
#' \dQuote{input matrix}. (The input matrix is never given explicitly.) The
#' second argument is `extra`.
#' @param extra Extra argument to supply to `func`.
#' @param sym Logical scalar, whether the input matrix is symmetric. Always
#' supply `TRUE` here if it is, since it can speed up the computation.
#' @param options Options to ARPACK, a named list to overwrite some of the
#' default option values. See details below.
#' @param env The environment in which `func` will be evaluated.
#' @param complex Whether to convert the eigenvectors returned by ARPACK into R
#' complex vectors. By default this is not done for symmetric problems (these
#' only have real eigenvectors/values), but only non-symmetric ones. If you
#' have a non-symmetric problem, but you're sure that the results will be real,
#' then supply `FALSE` here.
#' @return A named list with the following members:
#' \describe{
#' \item{values}{
#' Numeric vector, the desired eigenvalues.
#' }
#' \item{vectors}{
#' Numeric matrix, the desired eigenvectors as columns.
#' If `complex=TRUE` (the default for non-symmetric problems), then the matrix is complex.
#' }
#' \item{options}{
#' A named list with the supplied `options`
#' and some information about the performed calculation,
#' including an ARPACK exit code.
#' See the details above.
#' }
#' }
#' @author Rich Lehoucq, Kristi Maschhoff, Danny Sorensen, Chao Yang for
#' ARPACK, Gabor Csardi \email{csardi.gabor@@gmail.com} for the R interface.
#' @seealso [eigen_centrality()], [page_rank()],
#' [hub_score()], [cluster_leading_eigen()] are some of the
#' functions in igraph that use ARPACK.
#' @references D.C. Sorensen, Implicit Application of Polynomial Filters in a
#' k-Step Arnoldi Method. *SIAM J. Matr. Anal. Apps.*, 13 (1992), pp
#' 357-385.
#'
#' R.B. Lehoucq, Analysis and Implementation of an Implicitly Restarted Arnoldi
#' Iteration. *Rice University Technical Report* TR95-13, Department of
#' Computational and Applied Mathematics.
#'
#' B.N. Parlett & Y. Saad, Complex Shift and Invert Strategies for Real
#' Matrices. *Linear Algebra and its Applications*, vol 88/89, pp 575-595,
#' (1987).
#' @keywords graphs
#' @examples
#'
#' # Identity matrix
#' f <- function(x, extra = NULL) x
#' arpack(f, options = list(n = 10, nev = 2, ncv = 4), sym = TRUE)
#'
#' # Graph laplacian of a star graph (undirected), n>=2
#' # Note that this is a linear operation
#' f <- function(x, extra = NULL) {
#' y <- x
#' y[1] <- (length(x) - 1) * x[1] - sum(x[-1])
#' for (i in 2:length(x)) {
#' y[i] <- x[i] - x[1]
#' }
#' y
#' }
#'
#' arpack(f, options = list(n = 10, nev = 1, ncv = 3), sym = TRUE)
#'
#' # double check
#' eigen(laplacian_matrix(make_star(10, mode = "undirected")))
#'
#' ## First three eigenvalues of the adjacency matrix of a graph
#' ## We need the 'Matrix' package for this
#' @examplesIf rlang::is_installed("Matrix")
#' library("Matrix")
#' set.seed(42)
#' g <- sample_gnp(1000, 5 / 1000)
#' M <- as_adjacency_matrix(g, sparse = TRUE)
#' f2 <- function(x, extra = NULL) {
#' cat(".")
#' as.vector(M %*% x)
#' }
#' baev <- arpack(
#' f2,
#' sym = TRUE,
#' options = list(
#' n = vcount(g),
#' nev = 3,
#' ncv = 8,
#' which = "LM",
#' maxiter = 2000
#' )
#' )
#' @family arpack
#' @export
arpack <- function(
func,
extra = NULL,
sym = FALSE,
options = arpack_defaults(),
env = parent.frame(),
complex = !sym
) {
if (is.function(options)) {
lifecycle::deprecate_soft(
"1.6.0",
"arpack(options = 'must be a list')",
details = c(
"`arpack_defaults()` is now a function, use `options = arpack_defaults()` instead of `options = arpack_defaults`."
)
)
options <- options()