在r中生成3D随机几何图形的代码

时间:2016-05-31 14:57:57

标签: r graph 3d euclidean-distance

大家好我想在r中生成3D几何随机图。在igraph中,没有在3D中生成图形的功能。在三维几何随机图中,我发现三维空间中均匀分布点之间的欧氏距离,如果距离小于或等于某个阈值则认为是边缘。试过以下。

 ##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)  
    }

现在我已经使用所有相关的距离值获得了M.

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

现在我将仅从矩阵mat的列E中获取小于或等于提供的阈值(在此为0.5)的那些。那将是我的最终图形对象。

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

这是在3D中生成几何图形的正确方法吗?

0 个答案:

没有答案