Skip to content
Snippets Groups Projects
Commit 134b85d4 authored by Rhydian Brown's avatar Rhydian Brown
Browse files

init

parents
No related branches found
No related tags found
Loading
venv/
.venv/
graph.py 0 → 100644
import matplotlib.pyplot as plt
import networkx as nx
import pathlib
import sys
class Place:
def __init__(self, name, charging) -> None:
self.name = name
self.charging = charging
class Road:
def __init__(self, first, second, length):
self.first = first
self.second = second
self.length = length
class Map:
def __init__(self, path):
self.places = []
self.roads = {}
self.g = nx.Graph()
p = pathlib.Path(path)
with p.open() as f:
lines = f.readlines()
if len(lines) < 1:
print("failed to read file")
exit(1)
# get the number of places and roads
n_places, n_roads = lines[0].split()
n_places = int(n_places)
n_roads = int(n_roads)
place_data = lines[1:n_places+1]
road_data = lines[n_places+1:]
# build list of places
for data in place_data:
name, charging = data.split()
place = Place(name, int(charging))
self.places.append(place)
# build list of roads
for data in road_data:
first, second, length = (int(x) for x in data.split())
first_place = self.places[first]
second_place = self.places[second]
self.roads[(first_place.name, second_place.name)] = length
# add to graph
self.nodes = {
node.name: node for node in self.places
}
self.g.add_nodes_from(self.nodes.keys())
self.g.add_edges_from(self.roads.keys())
def draw(self):
pos = nx.spring_layout(self.g)
colours = ["green" if node.charging else "gray" for node in self.nodes.values()]
nx.draw_networkx_nodes(self.g, pos, node_size=700, node_color=colours, alpha=0.7)
nx.draw_networkx_edges(self.g, pos, width=1.0, alpha=0.5)
nx.draw_networkx_edge_labels(self.g, pos, edge_labels=self.roads, rotate=False)
node_pos = {}
for node, coords in pos.items():
node_pos[node] = (coords[0], coords[1])
nx.draw_networkx_labels(self.g, node_pos)
plt.axis('off')
plt.show()
if __name__ == "__main__":
if len(sys.argv) < 2:
print(f"usage: {sys.argv[0]} FILE")
exit(1)
p = sys.argv[1]
map = Map(p)
map.draw()
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment