I was using Python and am attempting to convert a networkx
graph into pygsp
graph to plot a signal. However, I cannot understand the documentation on how to do this simple bit of code. I am trying to use the function from_networkx
listed here: here.
Attempt:
I am running the following code within a Google Colab notebook (just some made up example):
import pandas as pd
import numpy as np
import networkx as nx
# Make the networkx graph
G = nx.Graph()
# Add some cars (just do 4 for now)
G.add_nodes_from([
('Ford', {'y': 0}),
('Lexus', {'y': 1}),
('Peugot', {'y': 2}),
('Mitsubushi', {'y': 3}),
('Mazda', {'y': 4}),
])
# Relabel the nodes
remapping = {x[0]: i for i, x in enumerate(G.nodes(data = True))}
remapping
G = nx.relabel_nodes(G, remapping, copy=True)
G.nodes(data = True)
# Add some edges --> A = [(0, 1, 0, 1, 1), (1, 0, 1, 1, 0), (0, 1, 0, 0, 1), (1, 1, 0, 0, 0), (1, 0, 1, 0, 0)] as the adjacency matrix
G.add_edges_from([
(0, 1), (0, 3), (0, 4),
(1, 0), (1, 2), (1, 3),
(2, 1), (2, 4),
(3, 0), (3, 1),
(4, 0), (4, 2)
])
!pip install pygsp
import pygsp
pygsp_graph = pygsp.graphs.Graph.from_networkx(G)
I keep getting errors saying that the module doesn't contain the function from_networkx
. I have tried different combinations, but for some reason cannot figure out how to do this extremely simple task.
The real network I am using also has some edge weights denoted by 'weight' in the networkx edge list, so those should also be able to be converted via the weight
argument of the pygsp from_networkx
function.
According to this, from_networkx
and to_networkx
are only available in the development version which you can install on google colab with !pip install git+https://github.com/epfl-lts2/pygsp
. Once you do that, the code runs normally.
See code below:
import pandas as pd
import numpy as np
import networkx as nx
# Make the networkx graph
G = nx.Graph()
# Add some cars (just do 4 for now)
G.add_nodes_from([
('Ford', {'y': 0}),
('Lexus', {'y': 1}),
('Peugot', {'y': 2}),
('Mitsubushi', {'y': 3}),
('Mazda', {'y': 4}),
])
# Relabel the nodes
remapping = {x[0]: i for i, x in enumerate(G.nodes(data = True))}
remapping
G = nx.relabel_nodes(G, remapping, copy=True)
G.nodes(data = True)
# Add some edges --> A = [(0, 1, 0, 1, 1), (1, 0, 1, 1, 0), (0, 1, 0, 0, 1), (1, 1, 0, 0, 0), (1, 0, 1, 0, 0)] as the adjacency matrix
G.add_edges_from([
(0, 1), (0, 3), (0, 4),
(1, 0), (1, 2), (1, 3),
(2, 1), (2, 4),
(3, 0), (3, 1),
(4, 0), (4, 2)
])
!pip install git+https://github.com/epfl-lts2/pygsp
import pygsp
pygsp_graph = pygsp.graphs.Graph.from_networkx(G)
print(pygsp_graph)
And the output gives:
Graph(n_vertices=5, n_edges=6)