R/deterrence.R

# Deterrence functions ---------------------------------------------------------

#' Maximum distance model of deterrence
#'
#' Calculate the cost of distances based on a simple maximum interaction distance.
#'
#' @param dists a vector or matrix of distances
#' @param max maximum distance of interaction
#'
#' @return Deterrences (0 or 1)
#'
#' @importFrom magrittr "%>%"
#' @importFrom magrittr "is_less_than"
#' @importFrom magrittr "multiply_by"
#' @importFrom magrittr "%T>%"
#'
#' @export
#'
#' @author Joe Roe <\email{jwg983@@hum.ku.dk}>
#'
#' @examples
#' distmat <- matrix(runif(n=64),8,8)
#' diag(distmat) <- 0
#' mdm(distmat, 0.1)
mdm <- function(dists, max) {
  dists %>%
    is_less_than(max) %>%
    multiply_by(1)  %T>% # Cast to int
    {if(is.matrix(.)) {
      if(rowSums(.) == 0 || colSums(.) == 0) {
        warning("Some nodes are not connected to the graph. Check max value.")
      }
    }} %>%
    return()
}

#' @title Inverse power function
#'
#' Calculate the cost of distances based on an inverse power law
#'
#' @param dists a vector or matrix of distances
#' @param power the power to be used; default 2
#'
#' @author Daniel Knitter <\email{knitter@@geographie.uni-kiel.de}>
#'
#' @examples
#' distmat <- matrix(runif(n=64),8,8)
#' diag(distmat) <- 0
#' inverse_power(distmat, power = 2)
#'
#' @export
inverse_power <- function(dists, power = 2) {
  dists <- (1/dists)^power
  dists[dists==Inf] <- 0
  return(dists)
}

#' @title Inverse exponential function
#'
#' Calculate the cost of distances based on an inverse exponential function
#'
#' @param dists a vector or matrix of distances
#' @param beta ..
#' @author Daniel Knitter <\email{knitter@@geographie.uni-kiel.de}>
#'
#' @examples
#' distmat <- matrix(runif(n=64),8,8)
#' diag(distmat) <- 0
#' inverse_exponential(distmat, beta = 1)
#'
#' @export
inverse_exponential <- function(dists, beta = .1) {
  dists <- exp(-(beta * dists))
  dists[dists==Inf] <- 0
  return(dists)
}
CRC1266-A2/moin documentation built on May 7, 2019, 8:56 p.m.