Skip to content

Instantly share code, notes, and snippets.

@Jaya472
Created December 5, 2023 00:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Jaya472/db0945e9c2016fbd2c206d7ab7254c69 to your computer and use it in GitHub Desktop.
Save Jaya472/db0945e9c2016fbd2c206d7ab7254c69 to your computer and use it in GitHub Desktop.
Create a weighted network using networkx library
import networkx as nx
#for a 14 node network with connections as below. Each tuple represents a connected edge
edge_list = [(1, 2),(1,3),(1,8),(2,3),(2,4),(3,6),(4,5),(4,11),(5,6),(5,7),(6,10),(6,14),(7,8),(8,9),(9,10),(9,12),(9,13),(11,12),(11,13),(12,14),(14,13)]
G = nx.Graph() #to create the graph structure with unidirectional edges
#Use the below DiGraph() for bi-directional edges
# G = nx.DiGraph()
G.add_edges_from([(1, 2, {"weight": 2038}),(1,3, {"weight": 4008}),(1,8, {"weight": 7044}),(2,3, {"weight": 687}),\
(2,4, {"weight": 1153}),(3,6, {"weight":707 }),(4,5, {"weight":9080 }),(4,11, {"weight":1479 }),\
(5,6, {"weight":6001 }),(5,7, {"weight":5049 }),(6,10, {"weight":14016 }),(6,14, {"weight":8309 }),\
(7,8, {"weight": 5045}),(8,9, {"weight":163 }),(9,10, {"weight":1987 }),(9,12, {"weight":8305 }),\
(9,13, {"weight":1221 }),(11,12, {"weight":1081 }),(11,13, {"weight":1676 }),(12,14, {"weight":3031 }),\
(14,13, {"weight":6088 })])
#If using a DiGraph(), accordingly define the edges. E.g. if 1,2 has a distance of 2038 km and 2,1 also has 2308 km distance
#You can get the edge weights as below for use in any other function
edge_weights= list((nx.get_edge_attributes(G, "weight")).values() )
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment