# Calculates weighted distance to nearest center (WDNC)
# by Angela Bohn and Norbert Walchhofer

# Arguments
# vnetwork: a square adjacency matrix. Network must be strongly connected

# Value
# A vector of length n, where n is the number of nodes contained in vnetwork

wdnc <- function(vnetwork){
  ewcmatrix <- cluster<- c()
  network <- vnetwork
  network[network>0] <- 1
  n <- dim(network)[1]
  W <- network
  Sigma <- network
  wd <- colSums(vnetwork, na.rm=TRUE)
  i <- 2
  while(min(Sigma)==0){
    Y <- vnetwork %*% W
    X <- network %*% W
    TM <- X
    TM[TM>0] <- 1
    TM <- TM-Sigma
    TM[TM<0] <- 0
    X <- TM * X
    diag(Y) <- 0
    Z <- (Y/X)/i
    Z[Z == "Inf" | Z == "-Inf"] <- 0
    wd <- rbind(wd,colSums(Z, na.rm=TRUE))
    Sigma <- Sigma + TM
    W <- W %*% network
    i <- i + 1
  }
  wd <- wd/(max(vnetwork)*(n-1))
  ewcmatrix <- rbind(ewcmatrix,wd)
  ewcmatrix[which(ewcmatrix=="Inf")] <- 0
  for (i in 1:n){
    cluster <- c(cluster,which(ewcmatrix[,i]==max(ewcmatrix[,i]))[1])
  }
  names(cluster) <- NULL
  cluster
}

#Example:
#vnetwork <- cbind(c(0,1),c(1,0))
#wdnc(vnetwork)