Example03 / 07
两个疾病模块的网络分离度 s_AB
定义(Menche 等 2015):s_AB =
Output输出图

Output文字输出
A 与 B(重叠):共享基因 15 个,s = -0.75 A 与 C(远离):共享基因 0 个,s = 1.80
Code代码
# 定义(Menche 等 2015):s_AB = <d_AB> − (<d_AA> + <d_BB>) / 2,
# 其中 <d_AA> 是 A 中每个基因到 A 中其他基因的最短距离的平均,<d_AB> 是 A、B 间对称的“最近距离”平均
# (共有基因的距离为 0)。构造与疾病 A 部分重叠的疾病 B,以及远离 A 的疾病 C,比较 s_AB 与 s_AC。
# 输出解读:s_AB < 0(模块重叠),s_AC > 0(模块分离)。
import networkx as nx
import numpy as np
G = nx.barabasi_albert_graph(1000, 2, seed=14)
deg = dict(G.degree())
rng = np.random.default_rng(3)
def grow(G, start, size, maxdeg=15):
"""从 start(一个节点或节点列表)出发,每步加入与模块连边最多的邻居(不纳入度 > maxdeg 的枢纽)。"""
module = set(start) if isinstance(start, list) else {start}
while len(module) < size:
frontier = {v for u in module for v in G[u] if deg[v] <= maxdeg} - module
score = {v: sum(1 for u in G[v] if u in module) for v in frontier}
best = max(score.values())
module.add(int(rng.choice(sorted(v for v in frontier if score[v] == best))))
return sorted(module)
def mean_within(A, sp):
return np.mean([min(sp[a][b] for b in A if b != a) for a in A])
def mean_between(A, B, sp):
dab = [min(sp[a][b] for b in B) for a in A] # 若 a 也在 B 中,距离为 0
dba = [min(sp[b][a] for a in A) for b in B]
return np.mean(dab + dba)
seeds = [n for n in G if 4 <= deg[n] <= 8]
A = grow(G, seeds[0], 20)
B = grow(G, A[:12], 20) # 以 A 的 12 个基因为起点生长,与 A 部分重叠
spA = {a: nx.single_source_shortest_path_length(G, a) for a in A}
to_A = {n: min(spA[a][n] for a in A) for n in G} # 每个节点到 A 的最近距离
far = max(seeds, key=lambda n: to_A[n]) # 离 A 最远的候选种子
C = grow(G, far, 20)
sp = {s: nx.single_source_shortest_path_length(G, s) for s in set(A) | set(B) | set(C)}
def separation(A, B):
return mean_between(A, B, sp) - (mean_within(A, sp) + mean_within(B, sp)) / 2
for name, X in [("B(重叠)", B), ("C(远离)", C)]:
print(f"A 与 {name}:共享基因 {len(set(A) & set(X))} 个,s = {separation(A, X):.2f}")
import matplotlib.pyplot as plt
fig, ax = plt.subplots(figsize=(6.4, 4.2))
parts = ["<d_AA>", "<d_XX>", "<d_AX>", "s_AX"]
for k, (X, lab, h) in enumerate([(B, "X = B (overlapping)", ""), (C, "X = C (distant)", "//")]):
v = [mean_within(A, sp), mean_within(X, sp), mean_between(A, X, sp), separation(A, X)]
ax.bar(np.arange(4) + (k - 0.5) * 0.38, v, 0.38, hatch=h, color=["C0", "C1"][k], alpha=0.85, label=lab)
ax.axhline(0, color="k", lw=0.8); ax.set_xticks(range(4)); ax.set_xticklabels(parts)
ax.set_ylabel("mean shortest distance (hops)")
ax.set_title("Network separation: s_AB < 0 (overlap), s_AC > 0 (separated)"); ax.legend()
plt.tight_layout(); plt.show()Run在浏览器中运行
首次加载 Python 环境约需 20–40 秒;可以修改参数后重新运行。