Consider reading a file in the following linked list (source, dest, weight)
format with graph-tool.
link_list.csv
Alice,Bob,2
Bob,Charlie,5
Charlie,Alice,3
To read this file with grpah-tool, parse it using the csv module as follows.
load_csv_link_list.py
import csv
import graph_tool.all as gt
nodes = set()
rows = []
with open('link_list.csv') as f:
reader = csv.reader(f)
rows = [row for row in reader]
for row in rows:
nodes.add(row[0])
nodes.add(row[1])
nodes = list(nodes)
g = gt.Graph()
g.vp['name'] = g.new_vp('string')
for n in nodes:
v = g.add_vertex()
g.vp['name'][v] = n
# set edges
g.ep['weight'] = g.new_ep('double')
for row in rows:
s = nodes.index(row[0])
t = nodes.index(row[1])
w = float(row[2])
vs = g.vertex(s) # => get vertex object from the index
vt = g.vertex(t)
e = g.add_edge(vs, vt)
g.ep['weight'][e] = w
What we are doing is as follows
--First, read all the contents of the csv file and create a list of nodes nodes
--I want to extract only unique things, so I store them in set
and then convert them to list.
--The node name creates a string vertex_property name
in graph and storesg.vp ['name'] = g.new_vp ('string')
--g.vp
holds the attribute (vertex_property) for the node
--Edge weights are stored by creating a floating point type edge_property weight
This is what the graph looks like.
By the way, the result of visualizing this graph is as follows.
pos = gt.arf_layout(g)
gt.graph_draw(g, pos=pos, vertex_text=g.vp.name, vertex_font_size=10)
Recommended Posts