-
-
Notifications
You must be signed in to change notification settings - Fork 200
/
iterators.R
1862 lines (1723 loc) · 55.7 KB
/
iterators.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
# 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
#
###################################################################
###################################################################
# Constructors
###################################################################
update_es_ref <- update_vs_ref <- function(graph) {
env <- get_es_ref(graph)
if (!is.null(env)) assign("me", graph, envir = env)
}
get_es_ref <- get_vs_ref <- function(graph) {
if (is_igraph(graph) && !warn_version(graph)) {
.Call(R_igraph_copy_env, graph)
} else {
NULL
}
}
get_es_graph <- get_vs_graph <- function(seq) {
at <- attr(seq, "env")
if (inherits(at, "weakref")) {
weak_ref_key(at)$me
} else if (inherits(at, "environment")) {
get("graph", envir = at)
} else {
NULL
}
}
has_es_graph <- has_vs_graph <- function(seq) {
!is.null(weak_ref_key(attr(seq, "env")))
}
get_es_graph_id <- get_vs_graph_id <- function(seq) {
new_g <- attr(seq, "graph")
if (!is.null(new_g)) {
new_g
} else if (!is.null(attr(seq, "env"))) {
get("graph", envir = attr(seq, "env"))
} else {
NULL
}
}
#' Decide if two graphs are identical
#'
#' Two graphs are considered identical by this function if and only if
#' they are represented in exactly the same way in the internal R
#' representation. This means that the two graphs must have the same
#' list of vertices and edges, in exactly the same order, with same
#' directedness, and the two graphs must also have identical graph, vertex and
#' edge attributes.
#'
#' This is similar to `identical` in the `base` package,
#' but it ignores the mutable piece of igraph objects; those might be
#' different even if the two graphs are identical.
#'
#' Attribute comparison can be turned off with the `attrs` parameter if
#' the attributes of the two graphs are allowed to be different.
#'
#' @param g1,g2 The two graphs
#' @param attrs Whether to compare the attributes of the graphs
#' @return Logical scalar
#' @export
identical_graphs <- function(g1, g2, attrs = TRUE) {
stopifnot(is_igraph(g1), is_igraph(g2))
.Call(R_igraph_identical_graphs, g1, g2, as.logical(attrs))
}
add_vses_graph_ref <- function(vses, graph) {
ref <- get_vs_ref(graph)
if (!is.null(ref)) {
attr(vses, "env") <- make_weak_ref(ref, NULL)
attr(vses, "graph") <- get_graph_id(graph)
} else {
ne <- new.env()
assign("graph", graph, envir = ne)
attr(vses, "env") <- ne
}
vses
}
#' Get the id of a graph
#'
#' Graph ids are used to check that a vertex or edge sequence
#' belongs to a graph. If you create a new graph by changing the
#' structure of a graph, the new graph will have a new id.
#' Changing the attributes will not change the id.
#'
#' @param x A graph or a vertex sequence or an edge sequence.
#' @param ... Not used currently.
#' @return The id of the graph, a character scalar. For
#' vertex and edge sequences the id of the graph they were created from.
#'
#' @export
#' @examples
#' g <- make_ring(10)
#' graph_id(g)
#' graph_id(V(g))
#' graph_id(E(g))
#'
#' g2 <- g + 1
#' graph_id(g2)
graph_id <- function(x, ...) {
UseMethod("graph_id")
}
#' @method graph_id igraph
#' @export
graph_id.igraph <- function(x, ...) {
get_graph_id(x)
}
#' @method graph_id igraph.vs
#' @export
graph_id.igraph.vs <- function(x, ...) {
get_vs_graph_id(x) %||% NA_character_
}
#' @method graph_id igraph.es
#' @export
graph_id.igraph.es <- function(x, ...) {
get_es_graph_id(x) %||% NA_character_
}
is_complete_iterator <- function(x) {
identical(attr(x, "is_all"), TRUE)
}
set_complete_iterator <- function(x, value = TRUE) {
attr(x, "is_all") <- TRUE
x
}
inside_square_error <- function(fn_name, call = rlang::caller_env()) {
cli::cli_abort(c(
"{.fun {fn_name}} must only be used inside index or vertex sequences like {.code E(g)[]} or {.code V(g)[]}.",
i = "See {.help [{.fun [.igraph.es}](igraph::`[.igraph.es`)} or {.help [{.fun [.igraph.vs}](igraph::`[.igraph.vs`)}."
), call = call)
}
#' Helpers within vertex/index sequences
#'
#' Functions to be used only with `[.igraph.es` and `[.igraph.vs`
#'
#' @details
#'
#' See \code{\link[igraph]{[.igraph.vs}} and \code{\link[igraph]{[.igraph.es}}.
#'
#'
#' @keywords internal
#' @rdname inside-square-error
#' @param ... Not used, here for compatibility.
#' @return An error
#' @export
#'
.nei <- function(...) inside_square_error(".nei")
#' @rdname inside-square-error
#' @export
.innei <- function(...) inside_square_error(".innei")
#' @rdname inside-square-error
#' @export
.outnei <- function(...) inside_square_error(".outnei")
#' @rdname inside-square-error
#' @export
.inc <- function(...) inside_square_error(".inc")
#' @rdname inside-square-error
#' @export
.from <- function(...) inside_square_error(".from")
#' @rdname inside-square-error
#' @export
.to <- function(...) inside_square_error(".to")
#' Vertices of a graph
#'
#' Create a vertex sequence (vs) containing all vertices of a graph.
#'
#' @details
#' A vertex sequence is just what the name says it is: a sequence of
#' vertices. Vertex sequences are usually used as igraph function arguments
#' that refer to vertices of a graph.
#'
#' A vertex sequence is tied to the graph it refers to: it really denoted
#' the specific vertices of that graph, and cannot be used together with
#' another graph.
#'
#' At the implementation level, a vertex sequence is simply a vector
#' containing numeric vertex ids, but it has a special class attribute
#' which makes it possible to perform graph specific operations on it, like
#' selecting a subset of the vertices based on graph structure, or vertex
#' attributes.
#'
#' A vertex sequence is most often created by the `V()` function. The
#' result of this includes all vertices in increasing vertex id order. A
#' vertex sequence can be indexed by a numeric vector, just like a regular
#' R vector. See \code{\link{[.igraph.vs}} and additional links to other
#' vertex sequence operations below.
#'
#' @section Indexing vertex sequences:
#' Vertex sequences mostly behave like regular vectors, but there are some
#' additional indexing operations that are specific for them;
#' e.g. selecting vertices based on graph structure, or based on vertex
#' attributes. See \code{\link{[.igraph.vs}} for details.
#'
#' @section Querying or setting attributes:
#' Vertex sequences can be used to query or set attributes for the
#' vertices in the sequence. See [$.igraph.vs()] for details.
#'
#' @param graph The graph
#' @return A vertex sequence containing all vertices, in the order
#' of their numeric vertex ids.
#'
#' @family vertex and edge sequences
#' @export
#' @examples
#' # Vertex ids of an unnamed graph
#' g <- make_ring(10)
#' V(g)
#'
#' # Vertex ids of a named graph
#' g2 <- make_ring(10) %>%
#' set_vertex_attr("name", value = letters[1:10])
#' V(g2)
V <- function(graph) {
ensure_igraph(graph)
update_vs_ref(graph)
res <- seq_len(vcount(graph))
if (is_named(graph)) names(res) <- vertex_attr(graph)$name
class(res) <- "igraph.vs"
res <- set_complete_iterator(res)
add_vses_graph_ref(res, graph)
}
create_vs <- function(graph, idx, na_ok = FALSE) {
if (na_ok) idx <- ifelse(idx < 1 | idx > gorder(graph), NA, idx)
res <- simple_vs_index(V(graph), idx, na_ok = na_ok)
add_vses_graph_ref(res, graph)
}
# Internal function to quickly convert integer vectors to igraph.vs
# for use after C code, when NA and bounds checking is unnecessary.
# Also allows us to construct V(graph) outside the function call in
# lapply() so it's created only once.
unsafe_create_vs <- function(graph, idx, verts = NULL) {
if (is.null(verts)) {
verts <- V(graph)
}
res <- simple_vs_index(verts, idx, na_ok = TRUE)
add_vses_graph_ref(res, graph)
}
# Internal function to quickly convert integer vectors to igraph.es
# for use after C code, when NA and bounds checking is unnecessary
# Also allows us to construct V(graph) outside the function call in
# lapply() so it's created only once.
unsafe_create_es <- function(graph, idx, es = NULL) {
if (is.null(es)) {
es <- E(graph)
}
res <- simple_es_index(es, idx, na_ok = TRUE)
add_vses_graph_ref(res, graph)
}
#' Edges of a graph
#'
#' An edge sequence is a vector containing numeric edge ids, with a special
#' class attribute that allows custom operations: selecting subsets of
#' edges based on attributes, or graph structure, creating the
#' intersection, union of edges, etc.
#'
#' @details
#' Edge sequences are usually used as igraph function arguments that
#' refer to edges of a graph.
#'
#' An edge sequence is tied to the graph it refers to: it really denoted
#' the specific edges of that graph, and cannot be used together with
#' another graph.
#'
#' An edge sequence is most often created by the `E()` function. The
#' result includes edges in increasing edge id order by default (if. none
#' of the `P` and `path` arguments are used). An edge
#' sequence can be indexed by a numeric vector, just like a regular R
#' vector. See links to other edge sequence operations below.
#'
#' @section Indexing edge sequences:
#' Edge sequences mostly behave like regular vectors, but there are some
#' additional indexing operations that are specific for them;
#' e.g. selecting edges based on graph structure, or based on edge
#' attributes. See \code{\link{[.igraph.es}} for details.
#'
#' @section Querying or setting attributes:
#' Edge sequences can be used to query or set attributes for the
#' edges in the sequence. See [$.igraph.es()] for details.
#'
#' @param graph The graph.
#' @param P A list of vertices to select edges via pairs of vertices.
#' The first and second vertices select the first edge, the third
#' and fourth the second, etc.
#' @param path A list of vertices, to select edges along a path.
#' Note that this only works reliable for simple graphs. If the graph
#' has multiple edges, one of them will be chosen arbitrarily to
#' be included in the edge sequence.
#' @param directed Whether to consider edge directions in the `P`
#' argument, for directed graphs.
#' @return An edge sequence of the graph.
#'
#' @export
#' @family vertex and edge sequences
#' @examples
#' # Edges of an unnamed graph
#' g <- make_ring(10)
#' E(g)
#'
#' # Edges of a named graph
#' g2 <- make_ring(10) %>%
#' set_vertex_attr("name", value = letters[1:10])
#' E(g2)
E <- function(graph, P = NULL, path = NULL, directed = TRUE) {
ensure_igraph(graph)
update_es_ref(graph)
if (!is.null(P) && !is.null(path)) {
stop("Cannot give both `P' and `path' at the same time")
}
if (is.null(P) && is.null(path)) {
ec <- ecount(graph)
res <- seq_len(ec)
res <- set_complete_iterator(res)
} else if (!is.null(P)) {
on.exit(.Call(R_igraph_finalizer))
res <- .Call(
R_igraph_es_pairs, graph, as_igraph_vs(graph, P) - 1,
as.logical(directed)
) + 1
} else {
on.exit(.Call(R_igraph_finalizer))
res <- .Call(
R_igraph_es_path, graph, as_igraph_vs(graph, path) - 1,
as.logical(directed)
) + 1
}
if ("name" %in% edge_attr_names(graph)) {
names(res) <- edge_attr(graph)$name[res]
}
if (is_named(graph)) {
el <- ends(graph, es = res)
attr(res, "vnames") <- paste(el[, 1], el[, 2], sep = "|")
}
class(res) <- "igraph.es"
add_vses_graph_ref(res, graph)
}
create_es <- function(graph, idx, na_ok = FALSE) {
if (na_ok) idx <- ifelse(idx < 1 | idx > gsize(graph), NA, idx)
simple_es_index(E(graph), idx)
}
simple_vs_index <- function(x, i, na_ok = FALSE) {
res <- unclass(x)[i]
if (!na_ok && any(is.na(res))) stop("Unknown vertex selected")
class(res) <- "igraph.vs"
res
}
#' Indexing vertex sequences
#'
#' Vertex sequences can be indexed very much like a plain numeric R vector,
#' with some extras.
#'
#' @details
#' Vertex sequences can be indexed using both the single bracket and
#' the double bracket operators, and they both work the same way.
#' The only difference between them is that the double bracket operator
#' marks the result for printing vertex attributes.
#'
#' @section Multiple indices:
#' When using multiple indices within the bracket, all of them
#' are evaluated independently, and then the results are concatenated
#' using the `c()` function (except for the `na_ok` argument,
#' which is special an must be named. E.g. `V(g)[1, 2, .nei(1)]`
#' is equivalent to `c(V(g)[1], V(g)[2], V(g)[.nei(1)])`.
#'
#' @section Index types:
#' Vertex sequences can be indexed with positive numeric vectors,
#' negative numeric vectors, logical vectors, character vectors:
#' \itemize{
#' \item When indexed with positive numeric vectors, the vertices at the
#' given positions in the sequence are selected. This is the same as
#' indexing a regular R atomic vector with positive numeric vectors.
#' \item When indexed with negative numeric vectors, the vertices at the
#' given positions in the sequence are omitted. Again, this is the same
#' as indexing a regular R atomic vector.
#' \item When indexed with a logical vector, the lengths of the vertex
#' sequence and the index must match, and the vertices for which the
#' index is `TRUE` are selected.
#' \item Named graphs can be indexed with character vectors,
#' to select vertices with the given names.
#' }
#'
#' @section Vertex attributes:
#' When indexing vertex sequences, vertex attributes can be referred
#' to simply by using their names. E.g. if a graph has a `name` vertex
#' attribute, then `V(g)[name == "foo"]` is equivalent to
#' `V(g)[V(g)$name == "foo"]`. See more examples below. Note that attribute
#' names mask the names of variables present in the calling environment; if
#' you need to look up a variable and you do not want a similarly named
#' vertex attribute to mask it, use the `.env` pronoun to perform the
#' name lookup in the calling environment. In other words, use
#' `V(g)[.env$name == "foo"]` to make sure that `name` is looked up
#' from the calling environment even if there is a vertex attribute with the
#' same name. Similarly, you can use `.data` to match attribute names only.
#'
#' @section Special functions:
#' There are some special igraph functions that can be used only
#' in expressions indexing vertex sequences: \describe{
#' \item{`.nei`}{takes a vertex sequence as its argument
#' and selects neighbors of these vertices. An optional `mode`
#' argument can be used to select successors (`mode="out"`), or
#' predecessors (`mode="in"`) in directed graphs.}
#' \item{`.inc`}{Takes an edge sequence as an argument, and
#' selects vertices that have at least one incident edge in this
#' edge sequence.}
#' \item{`.from`}{Similar to `.inc`, but only considers the
#' tails of the edges.}
#' \item{`.to`}{Similar to `.inc`, but only considers the
#' heads of the edges.}
#' \item{`.innei`, `.outnei`}{`.innei(v)` is a shorthand for
#' `.nei(v, mode = "in")`, and `.outnei(v)` is a shorthand for
#' `.nei(v, mode = "out")`.
#' }
#' }
#' Note that multiple special functions can be used together, or with
#' regular indices, and then their results are concatenated. See more
#' examples below.
#'
#' @param x A vertex sequence.
#' @param ... Indices, see details below.
#' @param na_ok Whether it is OK to have `NA`s in the vertex
#' sequence.
#' @return Another vertex sequence, referring to the same graph.
#'
#' @method [ igraph.vs
#' @name igraph-vs-indexing
#' @export
#' @family vertex and edge sequences
#' @family vertex and edge sequence operations
#'
#' @examples
#' # -----------------------------------------------------------------
#' # Setting attributes for subsets of vertices
#' largest_comp <- function(graph) {
#' cl <- components(graph)
#' V(graph)[which.max(cl$csize) == cl$membership]
#' }
#' g <- sample_(
#' gnp(100, 2 / 100),
#' with_vertex_(size = 3, label = ""),
#' with_graph_(layout = layout_with_fr)
#' )
#' giant_v <- largest_comp(g)
#' V(g)$color <- "green"
#' V(g)[giant_v]$color <- "red"
#' plot(g)
#'
#' # -----------------------------------------------------------------
#' # nei() special function
#' g <- make_graph(c(1, 2, 2, 3, 2, 4, 4, 2))
#' V(g)[.nei(c(2, 4))]
#' V(g)[.nei(c(2, 4), "in")]
#' V(g)[.nei(c(2, 4), "out")]
#'
#' # -----------------------------------------------------------------
#' # The same with vertex names
#' g <- make_graph(~ A -+ B, B -+ C:D, D -+ B)
#' V(g)[.nei(c("B", "D"))]
#' V(g)[.nei(c("B", "D"), "in")]
#' V(g)[.nei(c("B", "D"), "out")]
#'
#' # -----------------------------------------------------------------
#' # Resolving attributes
#' g <- make_graph(~ A -+ B, B -+ C:D, D -+ B)
#' V(g)$color <- c("red", "red", "green", "green")
#' V(g)[color == "red"]
#'
#' # Indexing with a variable whose name matches the name of an attribute
#' # may fail; use .env to force the name lookup in the parent environment
#' V(g)$x <- 10:13
#' x <- 2
#' V(g)[.env$x]
#'
`[.igraph.vs` <- function(x, ..., na_ok = FALSE) {
args <- rlang::enquos(..., .ignore_empty = "all")
## If indexing has no argument at all, then we still get one,
## but it is "empty", a name that is ""
## Special case, no argument (but we might get an artificial
## empty one
if (length(args) < 1 ||
(length(args) == 1 && inherits(rlang::quo_get_expr(args[[1]]), "name") &&
!nzchar(as.character(rlang::quo_get_expr(args[[1]]))))) {
return(x)
}
## Special case: single numeric argument
first_arg_is_numericish <- inherits(rlang::quo_get_expr(args[[1]]), "numeric") ||
inherits(rlang::quo_get_expr(args[[1]]), "integer")
if (length(args) == 1 && first_arg_is_numericish) {
res <- simple_vs_index(x, rlang::quo_get_expr(args[[1]]), na_ok)
return(add_vses_graph_ref(res, get_vs_graph(x)))
}
## Special case: single symbol argument, no such attribute
if (length(args) == 1 && inherits(rlang::quo_get_expr(args[[1]]), "name")) {
graph <- get_vs_graph(x)
if (!(as.character(rlang::quo_get_expr(args[[1]])) %in% vertex_attr_names(graph))) {
res <- simple_vs_index(x, rlang::eval_tidy(args[[1]]), na_ok)
return(add_vses_graph_ref(res, graph))
}
}
.nei <- function(v, mode = c("all", "in", "out", "total")) {
## TRUE iff the vertex is a neighbor (any type)
## of at least one vertex in v
mode <- igraph.match.arg(mode)
mode <- switch(mode,
"out" = 1,
"in" = 2,
"all" = 3,
"total" = 3
)
if (is.logical(v)) {
v <- which(v)
}
on.exit(.Call(R_igraph_finalizer))
tmp <- .Call(
R_igraph_vs_nei, graph, x, as_igraph_vs(graph, v) - 1,
as.numeric(mode)
)
tmp[as.numeric(x)]
}
nei <- function(...) {
lifecycle::deprecate_stop("2.1.0", "nei()", ".nei()")
}
.innei <- function(v, mode = c("in", "all", "out", "total")) {
.nei(v, mode = mode[1])
}
innei <- function(...) {
lifecycle::deprecate_stop("2.1.0", "innei()", ".innei()")
}
.outnei <- function(v, mode = c("out", "all", "in", "total")) {
.nei(v, mode = mode[1])
}
outnei <- function(...) {
lifecycle::deprecate_stop("2.1.0", "outnei()", ".outnei()")
}
.inc <- function(e) {
## TRUE iff the vertex (in the vs) is incident
## to at least one edge in e
if (is.logical(e)) {
e <- which(e)
}
on.exit(.Call(R_igraph_finalizer))
tmp <- .Call(
R_igraph_vs_adj, graph, x, as_igraph_es(graph, e) - 1,
as.numeric(3)
)
tmp[as.numeric(x)]
}
inc <- function(...) {
lifecycle::deprecate_stop("2.1.0", "inc()", ".inc()")
}
adj <- function(...) {
lifecycle::deprecate_stop("2.1.0", "adj()", ".inc()")
}
.from <- function(e) {
## TRUE iff the vertex is the source of at least one edge in e
if (is.logical(e)) {
e <- which(e)
}
on.exit(.Call(R_igraph_finalizer))
tmp <- .Call(
R_igraph_vs_adj, graph, x, as_igraph_es(graph, e) - 1,
as.numeric(1)
)
tmp[as.numeric(x)]
}
from <- function(...) {
lifecycle::deprecate_stop("2.1.0", "from()", ".from()")
}
.to <- function(e) {
## TRUE iff the vertex is the target of at least one edge in e
if (is.logical(e)) {
e <- which(e)
}
on.exit(.Call(R_igraph_finalizer))
tmp <- .Call(
R_igraph_vs_adj, graph, x, as_igraph_es(graph, e) - 1,
as.numeric(2)
)
tmp[as.numeric(x)]
}
to <- function(...) {
lifecycle::deprecate_stop("2.1.0", "to()", ".to()")
}
graph <- get_vs_graph(x)
if (is.null(graph)) {
res <- lapply(
lapply(args, rlang::eval_tidy),
simple_vs_index,
x = x,
na_ok = na_ok
)
} else {
attrs <- vertex_attr(graph)
xvec <- as.vector(x)
for (i in seq_along(attrs)) attrs[[i]] <- attrs[[i]][xvec]
env <- parent.frame()
# Functions (only visible if called or if no duplicate)
top <- rlang::new_environment(list(
.nei = .nei, nei = nei,
.innei = .innei, innei = innei,
.outnei = .outnei, outnei = outnei,
.inc = .inc, inc = inc, adj = adj,
.from = .from, from = from,
.to = .to, to = to,
.data = list(attrs)
))
# Data objects (visible by default)
bottom <- rlang::new_environment(parent = top, c(
attrs,
.env = env,
.data = list(attrs)
))
data_mask <- rlang::new_data_mask(bottom, top)
res <- lapply(args, rlang::eval_tidy, data = data_mask)
res <- lapply(res, function(ii) {
if (is.null(ii)) {
return(NULL)
}
ii <- simple_vs_index(x, ii, na_ok)
attr(ii, "env") <- attr(x, "env")
attr(ii, "graph") <- attr(x, "graph")
class(ii) <- class(x)
ii
})
}
res <- drop_null(res)
if (length(res)) {
do_call(c, res)
} else {
x[FALSE]
}
}
is_single_index <- function(x) {
isTRUE(attr(x, "single"))
}
set_single_index <- function(x, value = TRUE) {
attr(x, "single") <- value
x
}
#' Select vertices and show their metadata
#'
#' The double bracket operator can be used on vertex sequences, to print
#' the meta-data (vertex attributes) of the vertices in the sequence.
#'
#' @details
#' Technically, when used with vertex sequences, the double bracket
#' operator does exactly the same as the single bracket operator,
#' but the resulting vertex sequence is printed differently: all
#' attributes of the vertices in the sequence are printed as well.
#'
#' See \code{\link{[.igraph.vs}} for more about indexing vertex sequences.
#'
#' @param x A vertex sequence.
#' @param ... Additional arguments, passed to `[`.
#' @return The double bracket operator returns another vertex sequence,
#' with meta-data (attribute) printing turned on. See details below.
#'
#' @method [[ igraph.vs
#' @name igraph-vs-indexing2
#' @family vertex and edge sequences
#' @family vertex and edge sequence operations
#' @export
#' @examples
#' g <- make_ring(10) %>%
#' set_vertex_attr("color", value = "red") %>%
#' set_vertex_attr("name", value = LETTERS[1:10])
#' V(g)
#' V(g)[[]]
#' V(g)[1:5]
#' V(g)[[1:5]]
`[[.igraph.vs` <- function(x, ...) {
res <- x[...]
set_single_index(res)
}
#' Select edges and show their metadata
#'
#' The double bracket operator can be used on edge sequences, to print
#' the meta-data (edge attributes) of the edges in the sequence.
#'
#' @details
#' Technically, when used with edge sequences, the double bracket
#' operator does exactly the same as the single bracket operator,
#' but the resulting edge sequence is printed differently: all
#' attributes of the edges in the sequence are printed as well.
#'
#' See \code{\link{[.igraph.es}} for more about indexing edge sequences.
#'
#' @param x An edge sequence.
#' @param ... Additional arguments, passed to `[`.
#' @return Another edge sequence, with metadata printing turned on.
#' See details below.
#'
#' @method [[ igraph.es
#' @name igraph-es-indexing2
#' @family vertex and edge sequences
#' @family vertex and edge sequence operations
#' @export
#' @examples
#' g <- make_(
#' ring(10),
#' with_vertex_(name = LETTERS[1:10]),
#' with_edge_(weight = 1:10, color = "green")
#' )
#' E(g)
#' E(g)[[]]
#' E(g)[[.inc("A")]]
`[[.igraph.es` <- function(x, ...) {
res <- x[...]
set_single_index(res)
}
simple_es_index <- function(x, i, na_ok = FALSE) {
if (!is.null(attr(x, "vnames"))) {
wh1 <- structure(seq_along(x), names = names(x))[i]
wh2 <- structure(seq_along(x), names = attr(x, "vnames"))[i]
wh <- ifelse(is.na(wh1), wh2, wh1)
res <- unclass(x)[wh]
names(res) <- names(x)[wh]
attr(res, "vnames") <- attr(x, "vnames")[wh]
} else {
res <- unclass(x)[i]
}
if (!na_ok && any(is.na(res))) stop("Unknown edge selected")
attr(res, "env") <- attr(x, "env")
attr(res, "graph") <- attr(x, "graph")
class(res) <- "igraph.es"
res
}
#' Indexing edge sequences
#'
#' Edge sequences can be indexed very much like a plain numeric R vector,
#' with some extras.
#'
#' @section Multiple indices:
#' When using multiple indices within the bracket, all of them
#' are evaluated independently, and then the results are concatenated
#' using the `c()` function. E.g. `E(g)[1, 2, .inc(1)]`
#' is equivalent to `c(E(g)[1], E(g)[2], E(g)[.inc(1)])`.
#'
#' @section Index types:
#' Edge sequences can be indexed with positive numeric vectors,
#' negative numeric vectors, logical vectors, character vectors:
#' \itemize{
#' \item When indexed with positive numeric vectors, the edges at the
#' given positions in the sequence are selected. This is the same as
#' indexing a regular R atomic vector with positive numeric vectors.
#' \item When indexed with negative numeric vectors, the edges at the
#' given positions in the sequence are omitted. Again, this is the same
#' as indexing a regular R atomic vector.
#' \item When indexed with a logical vector, the lengths of the edge
#' sequence and the index must match, and the edges for which the
#' index is `TRUE` are selected.
#' \item Named graphs can be indexed with character vectors,
#' to select edges with the given names. Note that a graph may
#' have edge names and vertex names, and both can be used to select
#' edges. Edge names are simply used as names of the numeric
#' edge id vector. Vertex names effectively only work in graphs without
#' multiple edges, and must be separated with a `|` bar character
#' to select an edges that incident to the two given vertices. See
#' examples below.
#' }
#'
#' @section Edge attributes:
#' When indexing edge sequences, edge attributes can be referred
#' to simply by using their names. E.g. if a graph has a `weight` edge
#' attribute, then `E(G)[weight > 1]` selects all edges with a weight
#' larger than one. See more examples below. Note that attribute names mask the
#' names of variables present in the calling environment; if you need to look up
#' a variable and you do not want a similarly named edge attribute to mask it,
#' use the `.env` pronoun to perform the name lookup in the calling
#' environment. In other words, use `E(g)[.env$weight > 1]` to make sure
#' that `weight` is looked up from the calling environment even if there is
#' an edge attribute with the same name. Similarly, you can use `.data` to
#' match attribute names only.
#'
#' @section Special functions:
#' There are some special igraph functions that can be used
#' only in expressions indexing edge sequences: \describe{
#' \item{`.inc`}{takes a vertex sequence, and selects
#' all edges that have at least one incident vertex in the vertex
#' sequence.}
#' \item{`.from`}{similar to `.inc()`, but only
#' the tails of the edges are considered.}
#' \item{`.to`}{is similar to `.inc()`, but only
#' the heads of the edges are considered.}
#' \item{`\%--\%`}{a special operator that can be
#' used to select all edges between two sets of vertices. It ignores
#' the edge directions in directed graphs.}
#' \item{`\%->\%`}{similar to `\%--\%`,
#' but edges *from* the left hand side argument, pointing
#' *to* the right hand side argument, are selected, in directed
#' graphs.}
#' \item{`\%<-\%`}{similar to `\%--\%`,
#' but edges *to* the left hand side argument, pointing
#' *from* the right hand side argument, are selected, in directed
#' graphs.}
#' }
#' Note that multiple special functions can be used together, or with
#' regular indices, and then their results are concatenated. See more
#' examples below.
#'
#' @aliases %--% %<-% %->%
#' @param x An edge sequence
#' @param ... Indices, see details below.
#' @return Another edge sequence, referring to the same graph.
#'
#' @method [ igraph.es
#' @name igraph-es-indexing
#'
#' @export
#' @family vertex and edge sequences
#' @family vertex and edge sequence operations
#' @examples
#' # -----------------------------------------------------------------
#' # Special operators for indexing based on graph structure
#' g <- sample_pa(100, power = 0.3)
#' E(g)[1:3 %--% 2:6]
#' E(g)[1:5 %->% 1:6]
#' E(g)[1:3 %<-% 2:6]
#'
#' # -----------------------------------------------------------------
#' # The edges along the diameter
#' g <- sample_pa(100, directed = FALSE)
#' d <- get_diameter(g)
#' E(g, path = d)
#'
#' # -----------------------------------------------------------------
#' # Select edges based on attributes
#' g <- sample_gnp(20, 3 / 20) %>%
#' set_edge_attr("weight", value = rnorm(gsize(.)))
#' E(g)[[weight < 0]]
#'
#' # Indexing with a variable whose name matches the name of an attribute
#' # may fail; use .env to force the name lookup in the parent environment
#' E(g)$x <- E(g)$weight
#' x <- 2
#' E(g)[.env$x]
#'
`[.igraph.es` <- function(x, ...) {
args <- rlang::enquos(..., .ignore_empty = "all")
## If indexing has no argument at all, then we still get one,
## but it is "empty", a name that is ""
if (length(args) < 1 ||
(length(args) == 1 && inherits(rlang::quo_get_expr(args[[1]]), "name") &&
!nzchar(as.character(rlang::quo_get_expr(args[[1]]))))) {
return(x)
}
.inc <- function(v) {
## TRUE iff the edge is incident to at least one vertex in v
on.exit(.Call(R_igraph_finalizer))
tmp <- .Call(
R_igraph_es_adj, graph, x, as_igraph_vs(graph, v) - 1,
as.numeric(3)
)
tmp[as.numeric(x)]
}
adj <- function(...) {
lifecycle::deprecate_stop("2.1.0", "adj()", ".inc()")
}
inc <- function(...) {
lifecycle::deprecate_stop("2.1.0", "inc()", ".inc()")
}
.from <- function(v) {
## TRUE iff the edge originates from at least one vertex in v
on.exit(.Call(R_igraph_finalizer))
tmp <- .Call(
R_igraph_es_adj, graph, x, as_igraph_vs(graph, v) - 1,
as.numeric(1)
)
tmp[as.numeric(x)]
}
from <- function(...) {
lifecycle::deprecate_stop("2.1.0", "from()", ".from()")
}
.to <- function(v) {
## TRUE iff the edge points to at least one vertex in v
on.exit(.Call(R_igraph_finalizer))
tmp <- .Call(
R_igraph_es_adj, graph, x, as_igraph_vs(graph, v) - 1,
as.numeric(2)
)
tmp[as.numeric(x)]
}
to <- function(...) {
lifecycle::deprecate_stop("2.1.0", "to()", ".to()")
}
graph <- get_es_graph(x)
if (is.null(graph)) {
res <- lapply(lapply(args, rlang::eval_tidy), simple_es_index, x = x)
} else {
attrs <- edge_attr(graph)
xvec <- as.vector(x)
for (i in seq_along(attrs)) attrs[[i]] <- attrs[[i]][xvec]
env <- parent.frame()
# Functions (only visible if called or if no duplicate)
top <- rlang::new_environment(list(
.inc = .inc, inc = inc, adj = adj,
.from = .from, from = from,
.to = .to, to = to,
`%--%` = `%--%`, `%->%` = `%->%`, `%<-%` = `%<-%`
))
# Data objects (visible by default)
bottom <- rlang::new_environment(parent = top, c(
attrs,
.igraph.from = list(.Call(R_igraph_copy_from, graph)[as.numeric(x)]),
.igraph.to = list(.Call(R_igraph_copy_to, graph)[as.numeric(x)]),
.igraph.graph = list(graph),
.env = env,
.data = list(attrs)
))
data_mask <- rlang::new_data_mask(bottom, top)
res <- lapply(args, rlang::eval_tidy, data = data_mask)
res <- lapply(res, function(ii) {
if (is.null(ii)) {
return(NULL)
}
ii <- simple_es_index(x, ii)
attr(ii, "env") <- attr(x, "env")
attr(ii, "graph") <- attr(x, "graph")
class(ii) <- class(x)
ii
})
}