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
|
#' Apply a function to nodes in the order of a breath first search
#'
#' These functions allow you to map over the nodes in a graph, by first
#' performing a breath first search on the graph and then mapping over each
#' node in the order they are visited. The mapping function will have access to
#' the result and search statistics for all the nodes between itself and the
#' root in the search. To map over the nodes in the reverse direction use
#' [map_bfs_back()].
#'
#' @details
#' The function provided to `.f` will be called with the following arguments in
#' addition to those supplied through `...`:
#'
#' * `graph`: The full `tbl_graph` object
#' * `node`: The index of the node currently mapped over
#' * `rank`: The rank of the node in the search
#' * `parent`: The index of the node that led to the current node
#' * `before`: The index of the node that was visited before the current node
#' * `after`: The index of the node that was visited after the current node.
#' * `dist`: The distance of the current node from the root
#' * `path`: A table containing `node`, `rank`, `parent`, `before`, `after`,
#' `dist`, and `result` columns giving the values for each node leading to the
#' current node. The `result` column will contain the result of the mapping
#' of each node in a list.
#'
#' Instead of spelling out all of these in the function it is possible to simply
#' name the ones needed and use `...` to catch the rest.
#'
#' @param root The node to start the search from
#'
#' @param mode How should edges be followed? `'out'` only follows outbound
#' edges, `'in'` only follows inbound edges, and `'all'` follows all edges. This
#' parameter is ignored for undirected graphs.
#'
#' @param unreachable Should the search jump to an unvisited node if the search
#' is completed without visiting all nodes.
#'
#' @param .f A function to map over all nodes. See Details
#'
#' @param ... Additional parameters to pass to `.f`
#'
#' @return `map_bfs()` returns a list of the same length as the number of nodes
#' in the graph, in the order matching the node order in the graph (that is, not
#' in the order they are called). `map_bfs_*()` tries to coerce its result into
#' a vector of the classes `logical` (`map_bfs_lgl`), `character`
#' (`map_bfs_chr`), `integer` (`map_bfs_int`), or `double` (`map_bfs_dbl`).
#' These functions will throw an error if they are unsuccesful, so they are type
#' safe.
#'
#' @family node map functions
#'
#' @export
#'
#' @examples
#' # Accumulate values along a search
#' create_tree(40, children = 3, directed = TRUE) %>%
#' mutate(value = round(runif(40)*100)) %>%
#' mutate(value_acc = map_bfs_dbl(node_is_root(), .f = function(node, path, ...) {
#' sum(.N()$value[c(node, path$node)])
#' }))
map_bfs <- function(root, mode = 'out', unreachable = FALSE, .f, ...) {
expect_nodes()
graph <- .G()
root <- as_node_ind(root, graph)
dot_params <- list(...)
search_df <- bfs_df(graph, root, mode, unreachable)
paths <- get_paths(as.integer(search_df$parent))
call_nodes(graph, .f, search_df, paths, dot_params)[focus_ind(graph, 'nodes')]
}
#' @rdname map_bfs
#' @export
map_bfs_lgl <- function(root, mode = 'out', unreachable = FALSE, .f, ...) {
res <- map_bfs(root = root, mode = mode, unreachable = unreachable, .f = .f, ...)
as_vector(res, .type = logical(1))
}
#' @rdname map_bfs
#' @export
map_bfs_chr <- function(root, mode = 'out', unreachable = FALSE, .f, ...) {
res <- map_bfs(root = root, mode = mode, unreachable = unreachable, .f = .f, ...)
as_vector(res, .type = character(1))
}
#' @rdname map_bfs
#' @export
map_bfs_int <- function(root, mode = 'out', unreachable = FALSE, .f, ...) {
res <- map_bfs(root = root, mode = mode, unreachable = unreachable, .f = .f, ...)
as_vector(res, .type = integer(1))
}
#' @rdname map_bfs
#' @export
map_bfs_dbl <- function(root, mode = 'out', unreachable = FALSE, .f, ...) {
res <- map_bfs(root = root, mode = mode, unreachable = unreachable, .f = .f, ...)
as_vector(res, .type = double(1))
}
#' Apply a function to nodes in the reverse order of a breath first search
#'
#' These functions allow you to map over the nodes in a graph, by first
#' performing a breath first search on the graph and then mapping over each
#' node in the reverse order they are visited. The mapping function will have
#' access to the result and search statistics for all the nodes following itself
#' in the search. To map over the nodes in the original direction use
#' [map_bfs()].
#'
#' @details
#' The function provided to `.f` will be called with the following arguments in
#' addition to those supplied through `...`:
#'
#' * `graph`: The full `tbl_graph` object
#' * `node`: The index of the node currently mapped over
#' * `rank`: The rank of the node in the search
#' * `parent`: The index of the node that led to the current node
#' * `before`: The index of the node that was visited before the current node
#' * `after`: The index of the node that was visited after the current node.
#' * `dist`: The distance of the current node from the root
#' * `path`: A table containing `node`, `rank`, `parent`, `before`, `after`,
#' `dist`, and `result` columns giving the values for each node reached from
#' the current node. The `result` column will contain the result of the mapping
#' of each node in a list.
#'
#' Instead of spelling out all of these in the function it is possible to simply
#' name the ones needed and use `...` to catch the rest.
#'
#' @inheritParams map_bfs
#'
#' @return `map_bfs_back()` returns a list of the same length as the number of
#' nodes in the graph, in the order matching the node order in the graph (that
#' is, not in the order they are called). `map_bfs_back_*()` tries to coerce
#' its result into a vector of the classes `logical` (`map_bfs_back_lgl`),
#' `character` (`map_bfs_back_chr`), `integer` (`map_bfs_back_int`), or `double`
#' (`map_bfs_back_dbl`). These functions will throw an error if they are
#' unsuccesful, so they are type safe.
#'
#' @family node map functions
#'
#' @export
#'
#' @examples
#' # Collect values from children
#' create_tree(40, children = 3, directed = TRUE) %>%
#' mutate(value = round(runif(40)*100)) %>%
#' mutate(child_acc = map_bfs_back_dbl(node_is_root(), .f = function(node, path, ...) {
#' if (nrow(path) == 0) .N()$value[node]
#' else {
#' sum(unlist(path$result[path$parent == node]))
#' }
#' }))
map_bfs_back <- function(root, mode = 'out', unreachable = FALSE, .f, ...) {
expect_nodes()
graph <- .G()
root <- as_node_ind(root, graph)
dot_params <- list(...)
search_df <- bfs_df(graph, root, mode, unreachable)
offspring <- get_offspring(as.integer(search_df$parent), order(search_df$rank))
call_nodes(graph, .f, search_df, offspring, dot_params, reverse = TRUE)[focus_ind(graph, 'nodes')]
}
#' @rdname map_bfs_back
#' @export
map_bfs_back_lgl <- function(root, mode = 'out', unreachable = FALSE, .f, ...) {
res <- map_bfs_back(root = root, mode = mode, unreachable = unreachable, .f = .f, ...)
as_vector(res, .type = logical(1))
}
#' @rdname map_bfs_back
#' @export
map_bfs_back_chr <- function(root, mode = 'out', unreachable = FALSE, .f, ...) {
res <- map_bfs_back(root = root, mode = mode, unreachable = unreachable, .f = .f, ...)
as_vector(res, .type = character(1))
}
#' @rdname map_bfs_back
#' @export
map_bfs_back_int <- function(root, mode = 'out', unreachable = FALSE, .f, ...) {
res <- map_bfs_back(root = root, mode = mode, unreachable = unreachable, .f = .f, ...)
as_vector(res, .type = integer(1))
}
#' @rdname map_bfs_back
#' @export
map_bfs_back_dbl <- function(root, mode = 'out', unreachable = FALSE, .f, ...) {
res <- map_bfs_back(root = root, mode = mode, unreachable = unreachable, .f = .f, ...)
as_vector(res, .type = double(1))
}
#' Apply a function to nodes in the order of a depth first search
#'
#' These functions allow you to map over the nodes in a graph, by first
#' performing a depth first search on the graph and then mapping over each
#' node in the order they are visited. The mapping function will have access to
#' the result and search statistics for all the nodes between itself and the
#' root in the search. To map over the nodes in the reverse direction use
#' [map_dfs_back()].
#'
#' @details
#' The function provided to `.f` will be called with the following arguments in
#' addition to those supplied through `...`:
#'
#' * `graph`: The full `tbl_graph` object
#' * `node`: The index of the node currently mapped over
#' * `rank`: The rank of the node in the search
#' * `rank_out`: The rank of the completion of the nodes subtree
#' * `parent`: The index of the node that led to the current node
#' * `dist`: The distance of the current node from the root
#' * `path`: A table containing `node`, `rank`, `rank_out`, `parent`, dist`, and
#' `result` columns giving the values for each node leading to the
#' current node. The `result` column will contain the result of the mapping
#' of each node in a list.
#'
#' Instead of spelling out all of these in the function it is possible to simply
#' name the ones needed and use `...` to catch the rest.
#'
#' @inheritParams map_bfs
#'
#' @return `map_dfs()` returns a list of the same length as the number of nodes
#' in the graph, in the order matching the node order in the graph (that is, not
#' in the order they are called). `map_dfs_*()` tries to coerce its result into
#' a vector of the classes `logical` (`map_dfs_lgl`), `character`
#' (`map_dfs_chr`), `integer` (`map_dfs_int`), or `double` (`map_dfs_dbl`).
#' These functions will throw an error if they are unsuccesful, so they are type
#' safe.
#'
#' @family node map functions
#'
#' @export
#'
#' @examples
#' # Add a random integer to the last value along a search
#' create_tree(40, children = 3, directed = TRUE) %>%
#' mutate(child_acc = map_dfs_int(node_is_root(), .f = function(node, path, ...) {
#' last_val <- if (nrow(path) == 0) 0L else tail(unlist(path$result), 1)
#' last_val + sample(1:10, 1)
#' }))
map_dfs <- function(root, mode = 'out', unreachable = FALSE, .f, ...) {
expect_nodes()
graph <- .G()
root <- as_node_ind(root, graph)
dot_params <- list(...)
search_df <- dfs_df(graph, root, mode, unreachable)
paths <- get_paths(as.integer(search_df$parent))
call_nodes(graph, .f, search_df, paths, dot_params)[focus_ind(graph, 'nodes')]
}
#' @rdname map_dfs
#' @export
map_dfs_lgl <- function(root, mode = 'out', unreachable = FALSE, .f, ...) {
res <- map_dfs(root = root, mode = mode, unreachable = unreachable, .f = .f, ...)
as_vector(res, .type = logical(1))
}
#' @rdname map_dfs
#' @export
map_dfs_chr <- function(root, mode = 'out', unreachable = FALSE, .f, ...) {
res <- map_dfs(root = root, mode = mode, unreachable = unreachable, .f = .f, ...)
as_vector(res, .type = character(1))
}
#' @rdname map_dfs
#' @export
map_dfs_int <- function(root, mode = 'out', unreachable = FALSE, .f, ...) {
res <- map_dfs(root = root, mode = mode, unreachable = unreachable, .f = .f, ...)
as_vector(res, .type = integer(1))
}
#' @rdname map_dfs
#' @export
map_dfs_dbl <- function(root, mode = 'out', unreachable = FALSE, .f, ...) {
res <- map_dfs(root = root, mode = mode, unreachable = unreachable, .f = .f, ...)
as_vector(res, .type = double(1))
}
#' Apply a function to nodes in the reverse order of a depth first search
#'
#' These functions allow you to map over the nodes in a graph, by first
#' performing a depth first search on the graph and then mapping over each
#' node in the reverse order they are visited. The mapping function will have
#' access to the result and search statistics for all the nodes following itself
#' in the search. To map over the nodes in the original direction use
#' [map_dfs()].
#'
#' @details
#' The function provided to `.f` will be called with the following arguments in
#' addition to those supplied through `...`:
#'
#' * `graph`: The full `tbl_graph` object
#' * `node`: The index of the node currently mapped over
#' * `rank`: The rank of the node in the search
#' * `rank_out`: The rank of the completion of the nodes subtree
#' * `parent`: The index of the node that led to the current node
#' * `dist`: The distance of the current node from the root
#' * `path`: A table containing `node`, `rank`, `rank_out`, `parent`, dist`, and
#' `result` columns giving the values for each node reached from
#' the current node. The `result` column will contain the result of the mapping
#' of each node in a list.
#'
#' Instead of spelling out all of these in the function it is possible to simply
#' name the ones needed and use `...` to catch the rest.
#'
#' @inheritParams map_bfs
#'
#' @return `map_dfs_back()` returns a list of the same length as the number of
#' nodes in the graph, in the order matching the node order in the graph (that
#' is, not in the order they are called). `map_dfs_back_*()` tries to coerce
#' its result into a vector of the classes `logical` (`map_dfs_back_lgl`),
#' `character` (`map_dfs_back_chr`), `integer` (`map_dfs_back_int`), or `double`
#' (`map_dfs_back_dbl`). These functions will throw an error if they are
#' unsuccesful, so they are type safe.
#'
#' @family node map functions
#'
#' @export
#'
#' @examples
#' # Collect values from the 2 closest layers of children in a dfs search
#' create_tree(40, children = 3, directed = TRUE) %>%
#' mutate(value = round(runif(40)*100)) %>%
#' mutate(child_acc = map_dfs_back(node_is_root(), .f = function(node, path, dist, ...) {
#' if (nrow(path) == 0) .N()$value[node]
#' else {
#' unlist(path$result[path$dist - dist <= 2])
#' }
#' }))
map_dfs_back <- function(root, mode = 'out', unreachable = FALSE, .f, ...) {
expect_nodes()
graph <- .G()
root <- as_node_ind(root, graph)
dot_params <- list(...)
search_df <- dfs_df(graph, root, mode, unreachable)
offspring <- get_offspring(as.integer(search_df$parent), order(search_df$rank))
call_nodes(graph, .f, search_df, offspring, dot_params, reverse = TRUE)[focus_ind(graph, 'nodes')]
}
#' @rdname map_dfs_back
#' @export
map_dfs_back_lgl <- function(root, mode = 'out', unreachable = FALSE, .f, ...) {
res <- map_dfs_back(root = root, mode = mode, unreachable = unreachable, .f = .f, ...)
as_vector(res, .type = logical(1))
}
#' @rdname map_dfs_back
#' @export
map_dfs_back_chr <- function(root, mode = 'out', unreachable = FALSE, .f, ...) {
res <- map_dfs_back(root = root, mode = mode, unreachable = unreachable, .f = .f, ...)
as_vector(res, .type = character(1))
}
#' @rdname map_dfs_back
#' @export
map_dfs_back_int <- function(root, mode = 'out', unreachable = FALSE, .f, ...) {
res <- map_dfs_back(root = root, mode = mode, unreachable = unreachable, .f = .f, ...)
as_vector(res, .type = integer(1))
}
#' @rdname map_dfs_back
#' @export
map_dfs_back_dbl <- function(root, mode = 'out', unreachable = FALSE, .f, ...) {
res <- map_dfs_back(root = root, mode = mode, unreachable = unreachable, .f = .f, ...)
as_vector(res, .type = double(1))
}
#' Map a function over a graph representing the neighborhood of each node
#'
#' This function extracts the neighborhood of each node as a graph and maps over
#' each of these neighborhood graphs. Conceptually it is similar to
#' [igraph::local_scan()], but it borrows the type safe versions available in
#' [map_bfs()] and [map_dfs()].
#'
#' @details
#' The function provided to `.f` will be called with the following arguments in
#' addition to those supplied through `...`:
#'
#' * `neighborhood`: The neighborhood graph of the node
#' * `graph`: The full `tbl_graph` object
#' * `node`: The index of the node currently mapped over
#'
#' The `neighborhood` graph will contain an extra node attribute called
#' `.central_node`, which will be `TRUE` for the node that the neighborhood is
#' expanded from and `FALSE` for everything else.
#'
#' @inheritParams igraph::ego
#' @inheritParams map_bfs
#'
#' @return `map_local()` returns a list of the same length as the number of
#' nodes in the graph, in the order matching the node order in the graph.
#' `map_local_*()` tries to coerce its result into a vector of the classes
#' `logical` (`map_local_lgl`), `character` (`map_local_chr`), `integer`
#' (`map_local_int`), or `double` (`map_local_dbl`). These functions will throw
#' an error if they are unsuccesful, so they are type safe.
#'
#' @importFrom igraph gorder make_ego_graph V<-
#' @export
#'
#' @examples
#' # Smooth out values over a neighborhood
#' create_notable('meredith') %>%
#' mutate(value = rpois(graph_order(), 5)) %>%
#' mutate(value_smooth = map_local_dbl(order = 2, .f = function(neighborhood, ...) {
#' mean(as_tibble(neighborhood, active = 'nodes')$value)
#' }))
map_local <- function(order = 1, mode = 'all', mindist = 0, .f, ...) {
expect_nodes()
graph <- .G()
V(graph)$.central_node <- FALSE
res <- lapply(focus_ind(graph, 'nodes'), function(i) {
V(graph)$.central_node[i] <- TRUE
ego_graph <- make_ego_graph(graph, order = order, nodes = i, mode = mode, mindist = mindist)[[1]]
.f(neighborhood = as_tbl_graph(ego_graph), graph = graph, node = i, ...)
})
}
#' @rdname map_local
#' @export
map_local_lgl <- function(order = 1, mode = 'all', mindist = 0, .f, ...) {
res <- map_local(order = order, mode = mode, mindist = mindist, .f = .f, ...)
as_vector(res, .type = logical(1))
}
#' @rdname map_local
#' @export
map_local_chr <- function(order = 1, mode = 'all', mindist = 0, .f, ...) {
res <- map_local(order = order, mode = mode, mindist = mindist, .f = .f, ...)
as_vector(res, .type = character(1))
}
#' @rdname map_local
#' @export
map_local_int <- function(order = 1, mode = 'all', mindist = 0, .f, ...) {
res <- map_local(order = order, mode = mode, mindist = mindist, .f = .f, ...)
as_vector(res, .type = integer(1))
}
#' @rdname map_local
#' @export
map_local_dbl <- function(order = 1, mode = 'all', mindist = 0, .f, ...) {
res <- map_local(order = order, mode = mode, mindist = mindist, .f = .f, ...)
as_vector(res, .type = double(1))
}
# Helpers -----------------------------------------------------------------
#' @importFrom igraph bfs
#' @importFrom tibble tibble
bfs_df <- function(graph, root, mode, unreachable) {
search <- bfs(graph = graph, root = root, mode = mode, unreachable = unreachable,
order = TRUE, rank = TRUE, father = TRUE, pred = TRUE,
succ = TRUE, dist = TRUE)
nodes <- seq_along(search$order)
tibble(
node = nodes,
rank = as.integer(search$rank),
parent = as.integer(search$father),
before = as.integer(search$pred),
after = as.integer(search$succ),
dist = as.integer(search$dist),
result = rep(list(NULL), length(nodes))
)
}
#' @importFrom igraph dfs
#' @importFrom tibble tibble
dfs_df <- function(graph, root, mode, unreachable) {
search <- dfs(graph = graph, root = root, mode = mode, unreachable = unreachable,
order = TRUE, order.out = TRUE, father = TRUE, dist = TRUE)
nodes <- seq_along(search$order)
tibble(
node = nodes,
rank = match(nodes, as.integer(search$order)),
rank_out = match(nodes, as.integer(search$order.out)),
parent = as.integer(search$father),
dist = as.integer(search$dist),
result = rep(list(NULL), length(nodes))
)
}
call_nodes <- function(graph, .f, search, connections, dot_params, reverse = FALSE) {
not_results <- which(names(search) != 'result')
call_order <- order(search$rank)
if (reverse) call_order <- rev(call_order)
for (i in call_order) {
if (is.na(i)) break
conn <- connections[[i]]
search$result[[i]] <- do.call(
.f,
c(list(graph = graph),
as.list(search[i, not_results]),
list(path = search[conn, , drop = FALSE]),
dot_params)
)
}
search$result
}
get_offspring <- function(parent, order) {
offspring <- rep(list(integer(0)), length(parent))
direct_offspring <- split(seq_along(parent), parent)
offspring[as.integer(names(direct_offspring))] <- direct_offspring
offspring <- collect_offspring(offspring, as.integer(rev(order)))
lapply(offspring, function(x) x[order(match(x, order))])
}
# Avoid importing full purrr for as_vector fun
can_simplify <- function(x, type = NULL) {
is_atomic <- vapply(x, is.atomic, logical(1))
if (!all(is_atomic))
return(FALSE)
mode <- unique(vapply(x, typeof, character(1)))
if (length(mode) > 1 && !all(c("double", "integer") %in%
mode)) {
return(FALSE)
}
is.null(type) || can_coerce(x, type)
}
can_coerce <- function(x, type) {
actual <- typeof(x[[1]])
if (is_mold(type)) {
lengths <- unique(lengths(x))
if (length(lengths) > 1 || !(lengths == length(type))) {
return(FALSE)
}
else {
type <- typeof(type)
}
}
if (actual == "integer" && type %in% c("integer", "double",
"numeric")) {
return(TRUE)
}
if (actual %in% c("integer", "double") && type == "numeric") {
return(TRUE)
}
actual == type
}
is_mold <- function (type) {
modes <- c("numeric", "logical", "integer", "double", "complex",
"character", "raw")
length(type) > 1 || (!type %in% modes)
}
as_vector <- function(.x, .type = NULL){
null_elem <- sapply(.x, is.null)
if (any(null_elem)) {
na <- rep(NA, length(.type))
class(na) <- class(.type)
.x[null_elem] <- na
}
if (can_simplify(.x, .type)) {
unlist(.x)
}
else {
type <- deparse(substitute(.type))
cli::cli_abort("Cannot coerce values to {.cls {type}}")
}
}
|