def read(string):
"""
Read a graph from a string in Dot language and return it. Nodes and edges specified in the
input will be added to the current graph.
@type string: string
@param string: Input string in Dot format specifying a graph.
@rtype: graph
@return: Graph
"""
dotG = pydot.graph_from_dot_data(string)
if (dotG.get_type() == "graph"):
G = graph()
elif (dotG.get_type() == "digraph"):
G = digraph()
elif (dotG.get_type() == "hypergraph"):
return read_hypergraph(string)
else:
raise InvalidGraphType
# Read nodes...
# Note: If the nodes aren't explicitly listed, they need to be
for each_node in dotG.get_nodes():
G.add_node(each_node.get_name())
for each_attr_key, each_attr_val in each_node.get_attributes().items():
G.add_node_attribute(each_node.get_name(), (each_attr_key, each_attr_val))
# Read edges...
for each_edge in dotG.get_edges():
# Check if the nodes have been added
if not G.has_node(each_edge.get_source()):
G.add_node(each_edge.get_source())
if not G.has_node(each_edge.get_destination()):
G.add_node(each_edge.get_destination())
# See if there's a weight
if 'weight' in each_edge.get_attributes().keys():
_wt = each_edge.get_attributes()['weight']
else:
_wt = 1
# See if there is a label
if 'label' in each_edge.get_attributes().keys():
_label = each_edge.get_attributes()['label']
else:
_label = ''
G.add_edge((each_edge.get_source(), each_edge.get_destination()), wt = _wt, label = _label)
for each_attr_key, each_attr_val in each_edge.get_attributes().items():
if not each_attr_key in ['weight', 'label']:
G.add_edge_attribute((each_edge.get_source(), each_edge.get_destination()), \
(each_attr_key, each_attr_val))
return G
评论列表
文章目录