networkX:ego_graph 没有兄弟姐妹?

networkX: ego_graph without sibling?

我有一个有向的无循环 networkX 图。我想创建一个仅包含给定节点 n 的所有直接或直接前辈的子图。例如,如果 n 有 3 个前任,a、b 和 c,我也会为这 3 个节点中的每一个搜索前任。

我目前正在使用 networkX 的 ego_graph 方法,这非常有效,但输出也使兄弟节点无法直接访问我的目标节点,因为它是一个有向图。

def draw(graph_path: Path, target: str, radius: int)
    graph = nx.read_graphml(graphml)
    subgraph = nx.ego_graph(graph, target, undirected=True, radius=radius)
    draw_graph(subgraph, table)

我的 undirected 设置为 False 因为当我设置它 True 时,它只是重新调整我的 target 而已,与 radius 值为.

目标节点名为 CORE - SUPPLY CHAIN [DEV].20220128 AS_IS stock_V1norm.DIM calendar 并且 radius1:

结果是我所期待的。 现在,相同的目标,但 radius2:

结果不是我所期望的,因为我正在获得兄弟姐妹,我只想获得前任节点,例如:

graphML 示例:

<?xml version='1.0' encoding='utf-8'?>
<graphml xmlns="http://graphml.graphdrawing.org/xmlns" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://graphml.graphdrawing.org/xmlns http://graphml.graphdrawing.org/xmlns/1.0/graphml.xsd">
  <key id="d1" for="node" attr.name="kind" attr.type="string" />
  <key id="d0" for="node" attr.name="zone" attr.type="string" />
  <graph edgedefault="directed">
    <node id="gold_core.customers">
      <data key="d0">gold</data>
      <data key="d1">core</data>>
    </node>
    <node id="rt.F0116">
      <data key="d0">silver</data>>
    </node>
    <node id="hy.F4211">
      <data key="d0">silver</data>
    </node>
    <edge 
      source="hy.F4211"
      target="gold_core.customers"
    />

您可以使用 DiGraph.predecessors 方法获取节点的前任。

#!/usr/bin/env python
"""
Find predecessors to a given node.
"""
import matplotlib.pyplot as plt
import networkx as nx

from netgraph import Graph # pip install netgraph

# create a test graph
edges = [
    ('parent a', 'target'),
    ('parent b', 'target'),
    ('parent c', 'target'),
    ('grandparent aa', 'parent a'),
    ('grandparent bb', 'parent b'),
    ('grandparent cc', 'parent c'),
    ('parent a', 'sibling'),
    ('target', 'child')
]

g = nx.from_edgelist(edges, create_using=nx.DiGraph)

# get predecessors
parents = list(g.predecessors('target'))
grandparents = []
for parent in parents:
    for grandparent in list(g.predecessors(parent)):
        grandparents.append(grandparent)
predecessors = parents + grandparents

# give predecessors a red color
node_color = dict()
for node in g:
    if node in predecessors:
        node_color[node] = 'red'
    else:
        node_color[node] = 'white'

# plot
fig, (ax1, ax2) = plt.subplots(1, 2)
Graph(g,
      node_layout='dot',
      arrows=True,
      node_color=node_color,
      node_labels=True,
      node_label_fontdict=dict(size=10),
      node_label_offset=0.1,
      ax=ax1
)

# plot subgraph
subgraph = g.subgraph(predecessors + ['target'])
Graph(subgraph,
      node_layout='dot',
      arrows=True,
      node_labels=True,
      node_label_fontdict=dict(size=10),
      node_label_offset=0.1,
      ax=ax2,
)

plt.show()