I have a text file with each line indicating an edge on a graph, for example
2 5 1
indicates an edge of weight 1 between nodes 2 and 5. I want to create a sparse adjacency matrix using these tuples. Typically, I'd initialize a sparse matrix as
G = scipy.sparse.lil_matrix((n,n))
where n is the number of nodes in the graph. But in this case, I do not know what 'n' is. Is there a more efficient way to create the matrix than looping over the lines of the file to find the max node index, creating the lil_matrix and then again looping over the file ? My current implementation is this:
n = 0
with open(gfile) as f:
for line in f:
temp = map(int,line.split())
n = np.max([n,temp[0],temp[1]])
G = sp.lil_matrix((n,n))
with open(gfile) as f:
for line in f:
temp = map(int,line.split())
G[temp[0],temp[1]] = temp[2]