'Read edgelist of directed Graph

I am trying to apply different clustering methods to my networkx Graph, which is quite big (2631 edges and 2179 nodes). For that to work I would like to build/learn embeddings, which I am currently doing via the Node2Vec algorithm.

The problem however is that I didn't yet manage to figure out how to read my edgelist while considering the direction of the edges. Without any weights tho, as I do not have or need those. I tried out different approaches, my current code is inpired by this entry.

nx.write_edgelist(G, "test.edgelist")

G_edges = nx.read_edgelist("test.edgelist")

Moreover, I tried several of those approaches as well.

Oddly enough, these Code (e.g. Example 1) chunks do not run through, but without throwing an error. It just never finishes. Additionally, I am able to run several other chucks of code in the meantime. These then occasionally throw errors claiming: ERROR! Session/line number was not unique in database. History logging moved to new session 57.

Do you know any other approach or addition to the read_edgelist variable to store the direction of the edges as well?

Any help is greatly appreciated, please let me know when you have any questions or there are misunderstandings at my side.

Thanks a lot



Solution 1:[1]

import numpy as np
import matplotlib.pyplot as plt
import networkx as nx


# make dummy directed graph
adj_matrix = np.array([[0,1,1], [0,1,1], [0,1,1]])

G = nx.from_numpy_matrix(adj_matrix, create_using=nx.DiGraph)
# store positions for later use:
pos = nx.spring_layout(G)

# write edgelist. Directionality is implied by ordering of the nodes in the edge
# i.e. 0 1 means an edge from 0 to 1
# and 1 0 means an edge from 1 to 0
nx.write_edgelist(G, 'test.txt')

# to make use of the directional information you need to create a graph 
# that supports directed edges
H = nx.read_edgelist('test.txt', create_using=nx.DiGraph)
H = nx.relabel_nodes(H, {a:int(a) for a in H.nodes()})


# the default nx.Graph class will lose edge direction:
I = nx.read_edgelist('test.txt')
I = nx.relabel_nodes(I, {a:int(a) for a in I.nodes()})
    

fig, axes = plt.subplots(ncols=3)

for ax, graph, title in zip(axes, [G, H, I], ['original', 'nx.DiGraph', 'nx.Graph']):
    nx.draw_networkx(graph, pos=pos, ax=ax)
    ax.set_title(title)

enter image description here

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1