我用 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
函数中。
关于Python程序绘制一系列化学 react ,其唯一节点仅出现一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39002631/