在具有特定边界结点条件的有向图中寻找簇

我正在使用NetworkX库在Python语言中处理有向图(DiGraph).我的图表由几个 node 组成,这些 node 代表不同主题或类别(编号为1到6)的不同立场(标记为"与"和"反对").其中一些 node 有一个特殊的属性(special_attribute=True),这在我的分析中起着至关重要的作用.

目的

在以下情况下,我需要开发一种算法来识别此图中的集群:

  • 群集是一组强连接的 node .
  • 这些集群中的borderperipheral nodes必须具有special_attribute=True属性.需要注意的是,这些边界 node 可以是多个集群的一部分.

示例图 struct

The graph has nodes like 1-WITH, 1-AGAINST, 2-WITH, etc., with some having the special_attribute attribute set. A small example graph is shown below, with the red nodes having the special attribute example graph

问题

根据集群的边界 node 具有SPECIAL_ATTRIBUTE=True属性的条件,如何用Python语言实现在图中找到所有这类集群的算法?在上面的示例中,集群将是

4-AGAINST, 4-WITH, 6-WITH, 6-AGAINST, 5-WITH, 5-AGAINST, 2-WITH, 2-AGAINST

5-WITH, 5-AGAINST, 2-WITH, 2-AGAINST, 3-WITH,3-AGAINST, 1-WITH,1-AGAINST

Note: The actual graph I am working on has around 40.000 vertices 和 70.000 edges.

用于创建上述图表的要复制粘贴的代码:

digraph = nx.DiGraph()
digraph.add_node('1-WITH')
digraph.add_node('1-AGAINST')
digraph.add_node('2-WITH', specialAttribute=True)
digraph.add_node('2-AGAINST', specialAttribute=True)
digraph.add_node('3-WITH')
digraph.add_node('3-AGAINST')
digraph.add_node('4-WITH')
digraph.add_node('4-AGAINST')
digraph.add_node('5-WITH', specialAttribute=True)
digraph.add_node('5-AGAINST', specialAttribute=True)
digraph.add_node('6-WITH')
digraph.add_node('6-AGAINST')


# Add edges 
digraph.add_edges_from([('1-AGAINST', '1-WITH'),('1-WITH', '2-WITH'),('1-WITH', '3-WITH'), ('2-WITH','4-AGAINST'), ('4-AGAINST', '5-AGAINST'),  ('4-AGAINST', '6-AGAINST'),  ('6-AGAINST', '6-WITH'),
                        ('6-WITH', '5-AGAINST'),  ('6-WITH', '4-WITH'),  ('5-AGAINST', '3-AGAINST'), ('3-AGAINST', '2-WITH'), ('3-AGAINST', '1-AGAINST'), ('3-WITH', '5-WITH'), ('4-WITH','2-AGAINST'),
                        ('2-AGAINST','1-AGAINST'), ('2-AGAINST','3-WITH'), ('5-WITH','4-WITH'), ('5-WITH','6-AGAINST')
])```

推荐答案

这是这样的:"图将被划分成不连通的子图,每个子图有一个簇?"最终目标是在图上执行一个要求很高的优化问题,其中带有specalAttribute的 node 可以被视为观察值,然后这个逻辑将使每个组独立,这减少了计算问题.

  1. 归纳出一个不包含你的"特殊" node 的子图.
  2. 确定未连接的组件.
non_special_nodes = [node for node in digraph if "specialAttribute" not in digraph.nodes[node]]  
subgraph = nx.subgraph(digraph, non_special_nodes)
components = list(nx.connected_components(subgraph.to_undirected()))
print(components)
# [{'1-AGAINST', '1-WITH', '3-AGAINST', '3-WITH'},
#  {'4-AGAINST', '4-WITH', '6-AGAINST', '6-WITH'}]

Python相关问答推荐

返回nxon矩阵的diag元素,而不使用for循环

如何在图片中找到这个化学测试条?OpenCV精明边缘检测不会绘制边界框

具有多个选项的计数_匹配

使用新的类型语法正确注释ParamSecdecorator (3.12)

Django mysql图标不适用于小 case

如何避免Chained when/then分配中的Mypy不兼容类型警告?

从dict的列中分钟

如何在Python数据框架中加速序列的符号化

如果条件不满足,我如何获得掩码的第一个索引并获得None?

优化器的运行顺序影响PyTorch中的预测

我如何根据前一个连续数字改变一串数字?

Pandas Data Wrangling/Dataframe Assignment

如何在PySide/Qt QColumbnView中删除列

Polars将相同的自定义函数应用于组中的多个列,

为什么在FastAPI中创建与数据库的连接时需要使用生成器?

如何将泛型类类型与函数返回类型结合使用?

合并相似列表

pytest、xdist和共享生成的文件依赖项

python3中np. divide(x,y)和x/y有什么区别?'

将像素信息写入文件并读取该文件