-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparser.py
More file actions
157 lines (140 loc) · 5.86 KB
/
Copy pathparser.py
File metadata and controls
157 lines (140 loc) · 5.86 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
import sys
import os
from typing import Any
from graph_classes import (MapEntries, NodeTypes, ZoneTypes, MetadataKeys,
Node, Edge, Graph)
class Parser:
"""Parsing class, opens file and creates map"""
def _open_file(self, map_file: str) -> list[tuple[str, Any]]:
"""
Method to open chosen file, returns filtered raw data and rejects
invalid entry keys.
Parameters:
map_file(str): the file to be opened.
Returns:
list[tuple[str, Any]]: list of (entry, data) tuples which will then
be parsed.
"""
if not os.path.isfile(map_file):
print(f"Parsing Error: '{map_file}' not valid or not found")
sys.exit(1)
settings = []
try:
with open(map_file, 'r') as file:
for line in file:
line = line.split('#', 1)[0].strip()
if not line:
continue
key, value = line.split(':', 1)
key = key.strip()
if MapEntries(key):
settings.append((key, value))
if settings[0][0] != MapEntries.NB_DRONES.value:
raise Exception("'nb_drones' must be the first valid line")
except Exception as message:
print(f"Parsing Error: '{map_file}': {message}")
sys.exit(1)
return settings
def _create_node(self, key: str, value: str) -> Node:
"""
Creates and returns valid node object from raw key, value data.
Parameters:
key(str): node type.
value(str): node data/metadata which will be parsed and stored.
Returns:
Valid Node object which will be added to the graph.
"""
try:
if not NodeTypes(key):
raise ValueError("Node must be defined as 'start_hub', "
"'end_hub' or 'hub'")
fields = value.split()
node_data: dict[str, Any] = {
"name": fields[0],
"type": NodeTypes(key),
"x": int(fields[1]),
"y": int(fields[2]),
}
metadata = [field.strip('[]') for field in fields[3:]]
for data in metadata:
meta_key, meta_val = data.split('=')
match MetadataKeys(meta_key):
case MetadataKeys.COLOR:
node_data["color"] = meta_val
case MetadataKeys.ZONE:
node_data["zone"] = ZoneTypes(meta_val)
case MetadataKeys.MAX_DRONES:
node_data["max_drones"] = int(meta_val)
case _:
raise ValueError(f"Field '{meta_key}' not accepted as "
f"node metadata")
except Exception as message:
print(f"Parsing Error: Node creation failed ({message})")
sys.exit(1)
return Node(**node_data)
def _create_edge(self, key: str, value: str, graph: Graph) -> Edge:
"""
Creates and returns valid edge object from raw key, value data.
Parameters:
key(str): connection identifier.
value(str): edge data/metadata which will be parsed and stored.
graph(Graph): Graph object, to be able to access the node objects
the edge connects.
Returns:
Valid Edge object which will be added to the graph.
"""
edge_data: dict[str, Any] = {}
try:
if MapEntries(key) != MapEntries.CONNECTION:
raise ValueError("'connection' field not properly formatted")
fields = value.split()
node1, node2 = fields[0].split('-', 1)
edge_data["connection"] = (node1, node2)
edge_costs = {
"normal": 1,
"restricted": 2,
"priority": 1,
"blocked": None,
}
edge_data["cost"] = edge_costs[graph.nodes[node2].zone.value]
if len(fields) > 1:
meta_key, meta_value = fields[1].strip('[]').split('=', 1)
if MetadataKeys(meta_key) == MetadataKeys.MAX_LINK_CAPACITY:
edge_data["max_link_capacity"] = meta_value
except Exception as message:
print(f"Parsing Error: Edge creation failed ({message})")
sys.exit(1)
return Edge(**edge_data)
def create_graph(self, map_file: str) -> Graph:
"""
Main parsing method, will call methods handling every part of the
parsing.
Parameters:
map_file(str): path to the map file to be parsed, returned from the
menu.
Returns:
Graph: Graph object, which will represent the node-graph.
"""
settings: list[tuple[str, str]] = self._open_file(map_file)
graph: Graph = Graph()
try:
graph.nb_drones = int(settings[0][1])
for key, value in settings[1:]:
start = [type for type, info in settings
if type == NodeTypes.START.value]
end = [type for type, info in settings
if type == NodeTypes.END.value]
if len(start) > 1 or len(end) > 1:
raise ValueError("Only one start_hub and "
"end_hub are allowed")
if key in [k.value for k in NodeTypes]:
node = self._create_node(key, value)
graph.add_node(node)
elif key == MapEntries.CONNECTION.value:
edge = self._create_edge(key, value, graph)
graph.add_edge(edge)
graph.validate()
except Exception as message:
print(f"Parsing Error: Graph creation: {message}")
sys.exit(1)
return graph