Skip to content
Snippets Groups Projects
Commit 3aae5642 authored by Ikenna Oluigbo's avatar Ikenna Oluigbo
Browse files

Build Graph from input data

parent fd580a15
No related branches found
No related tags found
No related merge requests found
import networkx as nx
import matplotlib.pyplot as plt
def parse_graph():
with open('filename.txt', 'r') as file: #Graph edges name/path
f = file.readlines()
edges = []
a = [int(n.split(' ')[0]) for n in f]
b = [int(n.split(' ')[1]) for n in f]
nod = list(set(a + b))
for i in range(len(b)):
edges.append((a[i],b[i]))
return nod, edges
def node_labels():
nod, _ = parse_graph()
d = {}
with open('filename.txt', 'r') as lab: #Graph labels name/path
l = lab.readlines() #Returns a list string
if len(l[0].split(' ')) == 2:
x = [int(w.split(' ')[0]) for w in l]
y = [int(w.split(' ')[-1].rstrip('\n')) for w in l]
for j in range(len(x)):
d[x[j]] = y[j] #For label data with node
elif len(l[0].split(' ')) == 1:
for i, k in enumerate(l, 1): #start counting from 1
d[i] = int(k.rstrip('\n')) #For label data without node
else: print('Edges more than 2 nodes')
labels_dict = {}
for node in nod:
labels_dict[node] = d[node]
return labels_dict
labels_dict = node_labels()
only_labels = list(set(labels_dict.values()))
def extract_subgraph(G, source, destination):
if nx.has_path(G, source, destination):
nodes = nx.shortest_path(G, source, destination)
pattern_graph = G.subgraph(nodes)
nx.draw(pattern_graph, with_labels=True)
plt.show()
else:
print('No Path between {} and {}'.format(source, destination))
def node_neighbors(G):
neighbors = {}
for node in G.nodes:
neighbors[node] = list(G.neighbors(node))
return neighbors
def node_neighbor_labels(G):
neighbor_labels = {}
for node in G.nodes:
nn = list(G.neighbors(node)) #nn = Node Neighbor
nnlabel = [labels_dict[n] for n in nn] #Superimpose labels on node id
neighbor_labels[node] = nnlabel
return neighbor_labels
def build():
nod, edges = parse_graph()
G = nx.Graph()
G.add_nodes_from(nod)
G.add_edges_from(edges)
for e in G.edges:
G.edges[e]['weight'] = 1
return G
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment