Example03 / 11
有向网络的入度与出度
一个玩具基因调控网络:边 X -> Y 表示转录因子 X 调控基因 Y。 有向图的邻接矩阵一般不对称;入度 = 被多少个调控者调控,出度 = 调控多少个靶基因。 输出:邻接矩阵不对称;出度最大的“主调控因子”是 TF1(出度 4)。 注意 TF3 -> g3 与 g3 -> TF3 构成一个长度为 2 的反馈环(feedback loop),只有有向表示才能区分它。
Output输出图

Output文字输出
节点顺序: ['TF1', 'TF2', 'TF3', 'g1', 'g2', 'g3', 'g4']
[[0 1 1 1 0 0 1]
[0 0 0 1 1 0 0]
[0 0 0 0 1 1 0]
[0 0 0 0 0 0 0]
[0 0 0 0 0 0 0]
[0 0 1 0 0 0 0]
[0 0 0 0 0 0 0]]
对称吗? False
入度: {'TF1': 0, 'TF2': 1, 'TF3': 2, 'g1': 2, 'g2': 2, 'g3': 1, 'g4': 1}
出度: {'TF1': 4, 'TF2': 2, 'TF3': 2, 'g1': 0, 'g2': 0, 'g3': 1, 'g4': 0}
主调控因子: TF1(出度 4)
长度为 2 的反馈环: [['TF3', 'g3']]Code代码
# 一个玩具基因调控网络:边 X -> Y 表示转录因子 X 调控基因 Y。
# 有向图的邻接矩阵一般不对称;入度 = 被多少个调控者调控,出度 = 调控多少个靶基因。
# 输出:邻接矩阵不对称;出度最大的“主调控因子”是 TF1(出度 4)。
# 注意 TF3 -> g3 与 g3 -> TF3 构成一个长度为 2 的反馈环(feedback loop),只有有向表示才能区分它。
import networkx as nx
import numpy as np
reg = [("TF1", "TF2"), ("TF1", "TF3"), ("TF1", "g1"), ("TF2", "g1"), ("TF2", "g2"),
("TF3", "g2"), ("TF3", "g3"), ("TF1", "g4"), ("g3", "TF3")]
D = nx.DiGraph(reg)
order = sorted(D.nodes())
A = nx.to_numpy_array(D, nodelist=order, dtype=int)
print("节点顺序:", order)
print(A)
print("对称吗?", np.array_equal(A, A.T))
in_deg = dict(D.in_degree())
out_deg = dict(D.out_degree())
master = max(out_deg, key=out_deg.get)
print("入度:", in_deg)
print("出度:", out_deg)
print("主调控因子: %s(出度 %d)" % (master, out_deg[master]))
print("长度为 2 的反馈环:", [c for c in nx.simple_cycles(D) if len(c) == 2])
# 作图:有向网络,节点大小 ∝ 出度,反馈环的两条边标红
import matplotlib.pyplot as plt
fig, ax = plt.subplots(figsize=(6.4, 4.2))
pos = {"TF1": (0, 2), "TF2": (-1, 1), "TF3": (1, 1), "g1": (-1.5, 0), "g2": (-0.5, 0), "g3": (0.5, 0), "g4": (1.5, 0)}
loop = {("TF3", "g3"), ("g3", "TF3")}
nx.draw_networkx_edges(D, pos, ax=ax, edgelist=[e for e in D.edges() if e not in loop], edge_color="0.55",
arrows=True, arrowsize=14, node_size=900)
nx.draw_networkx_edges(D, pos, ax=ax, edgelist=list(loop), edge_color="#d6604d", width=2, arrows=True,
arrowsize=14, node_size=900, connectionstyle="arc3,rad=0.2")
nx.draw_networkx_nodes(D, pos, ax=ax, node_size=[300 + 150 * out_deg[n] for n in D],
node_color=["#f4a582" if n.startswith("TF") else "#92c5de" for n in D])
nx.draw_networkx_labels(D, pos, ax=ax, font_size=8)
ax.set_title("Master regulator %s (out-degree %d); red = feedback loop" % (master, out_deg[master]), fontsize=10)
ax.axis("off"); plt.tight_layout(); plt.show()Run在浏览器中运行
首次加载 Python 环境约需 20–40 秒;可以修改参数后重新运行。