A multigraph is a graph which is permitted to have multiple edges, also called parallel edges, that is, edges that have the same end nodes. Thus, two vertices may be connected by more than one edge.
Multigraphs can further be divided into two categories:
Undirected Multigraphs
Directed Mutligraphs
NetworkX provides classes for both of the above categories.
MultiGraph class for undirected multigraphs.
MultiDiGraph class for directed multigraphs.
In the code below we have created an undirected multigraph and printed the graph degree to see how it behaves.
import networkx as nx
MG = nx.MultiGraph()
MG.add_weighted_edges_from([(1, 2, 0.5), (1, 2, 0.75), (2, 3, 0.5)])
print(dict(MG.degree(weight='weight')))
The output is like this
{1: 1.25, 2: 1.75, 3: 0.5}
Similarly, we will create a directed multigraph and print its indegrees and outdegrees.
import networkx as nx
MG = nx.MultiDiGraph()
MG.add_weighted_edges_from(
[(1, 2, 0.5), (1, 2, 0.3), (2, 1, 0.75), (2, 3, 0.5)])
print(dict(MG.in_degree(weight='weight')))
print(dict(MG.out_degree(weight='weight')))
The output is like this
{1: 0.75, 2: 0.8, 3: 0.5} {1: 0.8, 2: 1.25, 3: 0}
We can also convert a MultiGraph object to a Graph or a MutliDiGraph object to a DiGraph object.
The code below creates the same undirected multigraph we created in a previous example and converts it to an undirected graph.
import networkx as nx
MG = nx.MultiGraph()
MG.add_weighted_edges_from([(1, 2, 0.5), (1, 2, 0.75), (2, 3, 0.5)])
print(dict(MG.degree(weight='weight')))
G = nx.Graph(MG)
print(dict(G.degree(weight='weight')))
The output of the above code is like this
{1: 1.25, 2: 1.75, 3: 0.5} {1: 0.75, 2: 1.25, 3: 0.5}
Comments