R/sbn_strahler.R

Defines functions sbn_strahler

Documented in sbn_strahler

#' Get node strahler order
#'
#' Calculate the reach (node) Strahler for all nodes in a river network. The function will not work if any of the nodes in the network have more than two adjacent upstream reaches (e.g. some networks generated by the OCNet package).
#'
#' @param g a river network as an igraph object. Must be a downstream directed graph.
#'
#' @return a vector of stream Strahler orders.
#'
#' @importFrom igraph V degree gorder adjacent_vertices
#'
#' @examples
#' g <- sbn_create(10, 0.7)
#' sbn_strahler(g)
#'
#' @export
sbn_strahler <- function(g) {

  if (max(igraph::degree(g, igraph::V(g), mode = "in")) > 2) stop("network must not have vertices with more that two connected upstream verticies")

  res <- rep(0, igraph::gorder(g))
  names(res) <- 1:igraph::gorder(g)

  dg <- igraph::degree(g, mode = "in")
  res[dg == 0] <- 1

  while(any(res == 0)) {
    xx <- unique(unlist(igraph::adjacent_vertices(g,
                                          v = names(res[res > 0]),
                                          mode = "out")))

    xx <- res[xx]
    xx <- as.numeric(names(xx[xx == 0]))

    for (i in xx) {

      zz <- igraph::adjacent_vertices(g, v = i, mode = "in")
      vs <- res[unlist(zz)]
      if (all(vs > 0)) {
        if (length(unique(vs)) == 1 & length(vs) == 2) {
          res[i] <- max(vs) + 1
        } else {res[i] <- max(vs)}
      }
    }
  }
  return(res)
}

Try the SBN package in your browser

Any scripts or data that you put into this service are public.

SBN documentation built on Jan. 18, 2022, 1:08 a.m.