Skip to main content
 首页 » 编程设计

用只出现一次的唯一节点映射一系列化学 react 的 Python 程序

2024年10月17日9tuyile006

我用 Python 编写了一个程序来绘制化学图谱,其中的一个示例是以下格式的文本: react 物 > 产物。

H2 > H2 
H2 > H2 
H2 > H2* 
H2 > H2* 
H2 > H + H 
H2 > H2^ 
H2 > H* + H 
H2 > H + H 
H2^ > H2^ 
H2^ > H^ + H 
H2^ > H + H 
H3^ > H3^ 
H3^ > H^ + H2 
H3^ > H + H2 
H > H 
H > H* 
H > H^ 
H^ > H^ 
H^ > H 
H + H2^ > H2 + H^ 
H2 + H2^ > H + H3^ 
CF4 > CF4 
CF4 > F- + CF3 

我希望我的程序在 map 上为化学中的每个物种创建节点,并绘制 react 物和产物之间的路径,其中一个物种在 map 上只出现一次, map 上有线条来表示 react 中每个 react 物的 react react 中的每个产物。

我写了下面的代码,但是这段代码只是简单地获取每个 react 并将其绘制在 map 上,它没有连接它们,我不确定如何最好地继续连接 react 中的常见物种。

import os 
import sys 
import numpy as np 
import networkx as nx 
import matplotlib.pyplot as plt 
import copy 
 
try: 
data = sys.argv[1] 
except IndexError: 
    print('Insert filename') 
    sys.exit(1) 
 
def parse_line(line): 
    new=line.split('>') 
    reactants=new[0].split('+') 
    products=new[1].split('+') 
    return reactants,products 
 
 
 
all_edges=[] 
edge_labels={} 
all_reactants=[] 
all_products=[] 
 
with open(data) as fi: 
    for line in fi.readlines(): 
        line = line.strip() 
        if not line or line[0] in '#%!': 
        # skip blank and comment lines 
            continue 
        reactants,products = parse_line(line) 
 
        for i in np.arange(len(reactants)): 
            other_reactants=copy.copy(reactants) 
            other_reactants.remove(reactants[i]) 
            other_reactants=', '.join(other_reactants) 
            for j in np.arange(len(products)): 
                edge=(reactants[i],products[j]) 
                all_edges.append(edge) 
                edge_labels[edge]=other_reactants 
 
 
 
gr=nx.DiGraph() 
 
gr.add_edges_from(all_edges) 
 
pos=nx.random_layout(gr) 
 
nx.draw_networkx_nodes(gr,pos,node_size=2000,node_shape='o',node_color='0.75',alpha=10) 
nx.draw_networkx_edges(gr,pos, width=0.05,edge_color='b') 
 
nx.draw_networkx_labels(gr, pos,font_size=12, font_color='k', font_weight='normal', alpha=1.0, ax=None) 
nx.draw_networkx_edge_labels(gr,pos,edge_labels=edge_labels, label_pos=0.01, ax=None, rotate=False) 
plt.show() 

谁能告诉我进行此操作的最佳方法,我需要一个函数来识别所有反应中 react 物和产物中的常见物种,并为每个独特的物种创建一个节点,并从每个 react 物创建一条线到每个 react 的每个产物。

任何帮助将不胜感激

非常感谢

请您参考如下方法:

您似乎遇到的问题之一是您没有从 react 的“qstrings”中解析出 react 物/产物周围的空白。这意味着例如'H2' 和 'H2' 被视为不同的物种,因此在您的图中得到不同的节点。

你可能想用类似的东西来处理这个:

reactants = [s.strip() for s in new[0].split('+')] 
products = [s.strip() for s in new[1].split('+')] 

在您的parse_line 函数中。