首页 > 解决方案 > 如何迭代地定义映射参数以收缩顶点链?

问题描述

我有一个简单的图表g。需要通过删除度数为2的顶点来平滑图,同时保留原始图的布局。在 Mathematica中解决了相同的任务。

library(igraph)
set.seed(1)
# preprocessing
g          <- sample_gnp(40, 1/20)
V(g)$name  <- seq(1:vcount(g))
components <- clusters(g, mode="weak")
biggest_cluster_id <- which.max(components$csize)
vert_ids           <- V(g)[components$membership == biggest_cluster_id]
vert_ids

# input random graph
g    <- induced_subgraph(g, vert_ids)
LO = layout.fruchterman.reingold(g)
plot(g, vertex.color = ifelse(degree(g)==2, "red", "green"), main ="g", layout = LO)

我选择了度数为 2 的顶点链。

subg     <- induced_subgraph(g, degree(g)==2)
subg_ids <- V(subg); subg_ids

我已阅读问答并手动定义函数的mapping参数contract()

# join nodes 3 -> 14, 15 -> 40, 13 -> 31, 29 -> 6
mapping = c(2, 3, 4, 5, 6, 7, 8, 10, 13, 3, 15, 16, 17, 18, 19, 20, 21, 22, 23, 25, 26, 27, 6, 30, 13, 32, 33, 34, 35, 36, 38, 39, 15)

g2 <- simplify(contract(g, mapping=mapping, vertex.attr.comb=toString))
# L2 <- LO[-as.numeric(c(14, 40, 31, 6)),] # not working
plot(g2, vertex.color = ifelse(degree(g2)==2, "red", "green"), main ="g2")

问题。mapping迭代定义参数的可能方法是什么?

在此处输入图像描述

标签: rigraphsubgraph

解决方案


这只是部分答案,因为它没有提供自动计算收缩的方法。但是,我可以对手动映射提供一些见解:

您的顶点有名称,因此这些名称用于参考,而不是从 1 到 n 的内部顶点编号。在映射中,我们需要给出收缩后顶点的新 ID。

原来的ID是

> V(g)
+ 33/33 vertices, named, from 0af52c3:
  [1] 2  3  4  5  6  7  8  10 13 14 15 16 17 18 19 20 21 22 23 25 26 27 29 30 31 32 33 34 35 36 38 39 40

新的 ID 可以给出(存在多种可能性):

mapping <- c(6, 14, 6, 5, 6, 7, 7, 10, 31, 14, 15, 16, 17, 14, 6, 7, 31, 22, 6, 25, 26, 27, 14, 30, 31, 6, 6, 34, 35, 36, 38, 39, 15)

为了更好地概述:

old ID:   2  3 4 5 6 7 8 10 13 14 15 16 17 18 19 20 21 22 23 25 26 27 29 30 31 32 33 34 35 36 38 39 40
new ID:   6 14 6 5 6 7 7 10 31 14 15 16 17 14  6  7 31 22  6 25 26 27 14 30 31  6  6 34 35 36 38 39 15

这导致:

g2 <- simplify(contract(g, mapping=mapping, vertex.attr.comb=toString))
plot(g2, vertex.color = ifelse(degree(g2)==2, "red", "green"), main ="g2")

在此处输入图像描述

要摆脱现有的 degree-0-nodes,您可以执行以下操作:

g3 <- delete.vertices(g2, which(degree(g2) == 0))

或者,甚至更干净,您可以删除无名节点:

g3 <- delete.vertices(g2, which(names(V(g2)) == ""))

在此处输入图像描述

要保留原始布局,您可以执行以下操作:

L3 <- LO[-which(mapping != as.numeric(names(V(g)))),]
plot(g3, layout = L3)

在此处输入图像描述

但是在这种情况下不是很好看...


推荐阅读