Reputation: 47
I have a directed, weighted network stored in a txt file as a list of 3 elements:
node1 node2 weight
node1 node3 weight
...
So for example the triplet:
1 10 50
means that I got an edge between node 1 and node 10 with weight 50.
Can someone please explain in detail how can I import this into graph tool to perform a community detection analysis using the SBM.
Thanks a lot.
Upvotes: 2
Views: 2025
Reputation: 213
graph_tool.load_graph_from_csv(file_name, csv_options={'delimiter': ' ', 'quotechar': '"'})
This will help you load a csv file with delimiter=space. I am still trying to read the documentation as to how to associate a weight to the edges: https://graph-tool.skewed.de/static/doc/graph_tool.html?highlight=load#graph_tool.Graph.load
Upvotes: 1
Reputation: 738
I assume that for a weighted graph you wish to use PropertyMaps (https://graph-tool.skewed.de/static/doc/quickstart.html#sec-property-maps)?
To import the file, you'll want to use file objects (https://docs.python.org/3/tutorial/inputoutput.html).
All together, the code you need is as follows:
#imports the graph-tools library
from graph_tool.all import *
#opens your file in mode "read"
f = open("your_file.txt","r")
#splits each line into a list of integers
lines = [[int(n) for n in x.split()] for x in f.readlines()]
#closes the file
f.close()
#makes the graph
g = Graph()
#adds enough vertices (the "1 + " is for position 0)
g.add_vertex(1 + max([l[0] for l in lines] + [l[1] for l in lines]))
#makes a "property map" to weight the edges
property_map = g.new_edge_property("int")
#for each line
for line in lines:
#make a new edge
g.add_edge(g.vertex(line[0]),g.vertex(line[1]))
#weight it
property_map[g.edge(g.vertex(line[0]),g.vertex(line[1]))] = line[2]
Upvotes: 1