我有具有节点和边缘属性的GXL文件,如下所示:
<?xml version="1.0"?>
<gxl>
<graph id="Network" edgeids="true" edgemode="undirected">
<node id="_103">
<attr name="OTU"><int>103</int></attr>
<attr name="Bacteria"><string>Bif</string></attr>
</node>
:
:
:
<edge from="_103" to="_147">
<attr name="nlr"><float>0.106</float></attr>
</edge>
<edge from="_103" to="_152">
<attr name="nlr"><float>0.343</float></attr>
</edge>
:
:
:我已经与工作示例共享了Googledrive链接:https://drive.google.com/file/d/1HO4B_yLyEOhhRMN6YlmsaHdn2vQ1s1Yw/view?usp=sharing,我使用ElementTree将该文件解析为netwrokx,如下所示:
tree_gxl = ET.parse("CONTROL1.gxl")
root_gxl = tree_gxl.getroot()
node_id = []
edge_attr={}
# Parse nodes
for i, node in enumerate(root_gxl.iter('node')):
node_id += [node.get('id')]
node_id = np.array(node_id)
# Create adjacency matrix
am = np.zeros((len(node_id), len(node_id)))
##Parsing edges
for edge in root_gxl.iter('edge'):
s = np.where(node_id==edge.get('from'))[0][0]
t = np.where(node_id==edge.get('to'))[0][0]
# Undirected Graph
am[s,t] = 1
am[t,s] = 1
# Create the networkx graph
G = nx.from_numpy_matrix(am)我需要执行以下步骤: 1.将边缘属性解析为图G2。解析后,我需要替换边缘属性中的值,如下所示:
(nlr*13.54)-13.54nlr将被每个边缘属性替换。
我该怎么做呢?
发布于 2020-03-05 13:38:03
我对此进行了调查,并会以这样的方式解决:
import xml.etree.ElementTree as ET
import numpy as np
import networkx as nx
import re
G=nx.Graph()
tree_gxl = ET.parse("CONTROL1.gxl")
root_gxl = tree_gxl.getroot()
node_id = []
edge_attr={}
# Parse nodes
for i, node in enumerate(root_gxl.iter('node')):
node_id += [node.get('id')]
node_id = np.array(node_id)
# Create adjacency matrix
am = np.zeros((len(node_id), len(node_id)))
##Parsing edges
for edge in root_gxl.iter('edge'):
s = np.where(node_id==edge.get('from'))[0][0]
t = np.where(node_id==edge.get('to'))[0][0]
# Get the child node of the current edge for the nrl value
for node in edge:
content = ET.tostring(node).decode("utf-8")
# Get the nrl value via regex
r1 = re.findall(r"\d.\d+",content)
# Modify value according to: (nlr*13.54)-13.54
r1 = (float(r1[0])*13.54)-13.54
#Add edge with original node names and nlr value to graph
G.add_edge(node_id[s],node_id[t], nlr=r1)我不太熟悉xml文件的处理,所以我不知道如何正确地检索浮点值。这就是为什么我通过获取边缘的子元素,然后使用正则表达式来匹配浮点值来解决这个问题的原因。
我还注意到,生成的图形没有原始的节点标签,因为您将其保存到一个矩阵中,而命名就会丢失。
因此,我建议使用NetworkX图中的方法来代替:
add_edge(nodex,nodey, attribute=value)您可以将代码的输出和我建议的代码与G.edges.data()进行比较,后者将返回具有各自属性的边缘。
https://stackoverflow.com/questions/60543401
复制相似问题