如何在python中遍历数组列表,并基于互信息计算合并对
我目前有一个数组列表,表示来自不同样本的细胞计数,每个数组表示不同的分组。我将其结构化为networkx图(出于其他目的),其中节点名称是分组,节点属性是单元计数 最后,我希望能够做到以下几点:如何在python中遍历数组列表,并基于互信息计算合并对,python,networkx,Python,Networkx,我目前有一个数组列表,表示来自不同样本的细胞计数,每个数组表示不同的分组。我将其结构化为networkx图(出于其他目的),其中节点名称是分组,节点属性是单元计数 最后,我希望能够做到以下几点: 计算所有可能的阵列/节点配对的互信息(MI) 对这些配对进行排序,并找到同样高于给定阈值的最大MI值 通过求和值并在删除原始节点的同时创建新节点来合并对的计数 从步骤1开始重复,此时由于两个节点已合并,因此少了一个节点,直到不再有高于阈值的MI 现在我可以起床直到第三步,但我不知道如何有效地重复这个过程
def optimize_MI(G, binsize, threshold):
'''
1. sort edges with highest MI
2. merge nodes with highest MI if MI>threshold
3. Create new node, delete original two
4. Repeat
'''
#find children with no predecessors (backwards)
finest = []
for node in G.nodes():
if len(G.predecessors(node)) == 0:
finest.append(node)
#calculate MI for all pairs and sort
edges = []
for x in finest:
for y in finest:
if G.successors(x) == G.successors(y):
mi = calc_MI(G.node[x]['count'], G.node[y]['count'], binsize)
edge = (x, y, {'MI': mi})
edges.append(edge)
edges_sorted = sorted(edges, key=lambda score: score[2]['MI'])
#make new node
pair = edges_sorted[-1]
if pair[2]['MI'] > threshold:
count = G.node[pair[0]] + G.node[pair[1]])
node_name = pair[0] + ' + ' + pair[1]
G.add_node(node_name, counts=count)
G.remove_nodes_from([pair[0], pair[1]])
G.add_edge(node_name, G.successors(pair[0]))
谢谢你的建议