网络弹性测试代码出错

时间:2013-05-08 12:17:43

标签: r social-networking igraph

在将下面的代码调整到我自己的网络之前,我尝试运行该教程代码,该代码模拟对指数和无标度网络的故障和攻击。但是,当我运行代码时,我收到一条错误消息:Error: object 'reps' not found 由于我是初学者,我不确定是什么问题。我将不胜感激任何帮助。

以下是代码:

 Tolerance <- function(n=100, m=2, f=seq(0, 0.05, 0.01), reps=1) 
 library(igraph)

  fail <- function(net, r) {
    # Remove r vertices by random
    vids <- sample(V(net), r)
    net <- delete.vertices(net,vids)
    return(net)
  }

  attack <- function(net, r) {
    # Remove top r vertices sorted by degree
    # Return networks
    m <- matrix(0, vcount(net), 2)
    m[,1] <- seq(0, vcount(net)-1, 1)
    m[,2] <- degree(net)
    m <- data.frame(m)
    m.sort <- m[order(m$X2),]
    vids <- tail(m.sort,r)$X1
    net <- delete.vertices(net,vids)
    return(net)
  }

  compSize <- function(net) {
    c <- clusters(net)
    gc <- c$csize[1]/vcount(net)
    cs <- as.vector(table(c$membership))
    if(length(cs) > 1) {
      ic <- mean(cs[2:length(cs)])
    } else {
      ic <- cs[1]
    }
    return(list("gc"=S, "ic"=ic))
  }

  f <- seq(0, 0.05, 0.005)
  mat <- matrix(0.0, length(f), 5)
  mat[,1] <- f

  for(i in 1:reps) {

    e <- ba.game(n, power=0, m=m, directed=F)
    sf <- ba.game(n, power=1, m=m, directed=F)

    mat[1,2] <- diameter(e)
    mat[1,3] <- mat[1,2]
    mat[1,4] <- diameter(sf)
    mat[1,5] <- mat[1,2]

    for(j in 2:length(f)) {

      e <- ba.game(n, power=0, m=m, directed=F)
      sf <- ba.game(n, power=1, m=m, directed=F)

      r <- f[j]*n

      ee <- fail(e, r)
      ea <- attack(e, r)
      sfe <- fail(sf, r)
      sfa <- attack(sf, r)

      mat[j,2] <- diameter(ee)
      mat[j,3] <- diameter(ea)
      mat[j,4] <- diameter(sfe)
      mat[j,5] <- diameter(sfa)
    }
  }

  tdf <- data.frame(mat)
  colnames(tdf) <- c("f", "ee", "ea", "sfe", "sfa")

  return(tdf)
}

TolerancePlot <- function(tdf) {

  # Compute tolerance data.frame first
  # tdf <- Tolerance(...)
  # TolerancePlot(tdf)

  plot(tdf$f, tdf$sfe, ylim=c(0,20), xlab="Fraction removed nodes", ylab="Diameter", 
       type="b", col="blue", pch=0,
       main="Error and Attack Tolerance")
  lines(tdf$f, tdf$sfa, type="b", pch=1, col="red")
  lines(tdf$f, tdf$ee, type="b", pch=15, col="blue")
  lines(tdf$f, tdf$ea, type="b", pch=16, col="red")
  legend(0, 20, legend=c("SF Attack", "SF Error", "E Attack", "E Error"), 
         pch=c(1,0,16,15), col=c("red", "blue"), text.col=c("red", "blue"), bty="n")
}

1 个答案:

答案 0 :(得分:0)

您在代码顶部缺少一个开头{(第一行)

Tolerance <- function(n=100, m=2, f=seq(0, 0.05, 0.01), reps=1) { # <- fixed here
[...]
}

TolerancePlot <- function(tdf) {
[...]
}

然后,运行您的代码:

tdf <- Tolerance()
TolerancePlot(tdf)