Code to generate 3D random geometric graph in r

牧云@^-^@ 提交于 2019-12-12 03:09:54

问题


Hi all i want to generate 3D geometric random graph in r. In igraph there is no function of generating the graph in 3D. In 3D geometric random graph i found the euclidean distance between of the uniformly distributed points in 3D space and considered an edge if the distance is less than or equal to some threshold. Tried the following.

 ##Code to generate random geometric graph in 3D
    ##To generate geometric random graph in 3D I have placed points in 3D space in uniform distribution the number of points placed in 3D space would be equal to N= total number of nodes.

    ##function to calculate euclidean distance of the random points placed in 3D
    get.dist = function(x)
    {
      sqrt(x[1]^2 + x[2]^2)
    }

    ##Generate matrix with total number of possible edges N(N-1)/2 
    get.pairs = function(N)
    {
      M = matrix(0, nrow = N * (N - 1)/2, ncol = 2)
      x = 1:N
      k = 1

      for (i in head(x, -1))
      {
        for (j in (i + 1):(length(x)))
        {
          M[k, ] = c(i, j)
          k = k +1
        }
      }
      M
    }
    ##Create a graph object and associate calculated euclidien distance to   each pair of edge
    create.graph = function(N = 100, d = 0.3)
    {
      ##random points in 3D with uniform distribution
      rnd.points = matrix(runif(3 * N), ncol = 3)
      perms = get.pairs(N)

       ###Caculate the difference between the points to calculate euclidien   distance between each pair
      Edges = apply(perms, 1, FUN = function(x){
        vec.diff = rnd.points[x[1], ] - rnd.points[x[2], ]
        get.dist(vec.diff)
      })

      res = cbind(Edges, perms)
      colnames(res) = c('E', 'V1', 'V2')
      list(M = res, N = N, d = d, pts = rnd.points)  
    }

Now I have achieved M with all the associated distance value.

##Create graph with provided number of nodes and threshold
cg <- create.graph(10,0.5)
mat <- cg$M

Now I will fetch only those from matrix mat's column E which are less than or equal to provided threshold which is here 0.5. And that would be my final graph object.

nd[nd[, 'E'] <= 0.5,]

Is it a proper way of generation of geometric graph in 3D.?

来源:https://stackoverflow.com/questions/37549154/code-to-generate-3d-random-geometric-graph-in-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!