added basic save/load
This commit is contained in:
@ -1,9 +1,11 @@
|
||||
from __future__ import annotations
|
||||
from math import inf
|
||||
from typing import Iterator, Optional
|
||||
|
||||
from src.graph.node import Node
|
||||
from src.graph.edge import Edge
|
||||
|
||||
|
||||
class Graph:
|
||||
def __init__(self):
|
||||
self.edges: list[Edge] = []
|
||||
@ -47,7 +49,7 @@ class Graph:
|
||||
|
||||
def get_edge_nodes(self, edge: Edge) -> tuple[Node, Node]:
|
||||
return self.nodes[edge.start], self.nodes[edge.end]
|
||||
|
||||
|
||||
def get_edge_center(self, edge_index: int) -> tuple[float, float]:
|
||||
edge = self.edges[edge_index]
|
||||
start_n = self.nodes[edge.start]
|
||||
@ -94,4 +96,32 @@ class Graph:
|
||||
node_sequences[end] = node_sequences[start].copy()
|
||||
node_sequences[end].append(end)
|
||||
|
||||
return node_sequences[target_index]
|
||||
return node_sequences[target_index]
|
||||
|
||||
def save(self, path: str) -> None:
|
||||
with open(path, "w") as f:
|
||||
for node in self.nodes:
|
||||
f.write(f"n {node.x} {node.z} {node.name}\n")
|
||||
f.write("\n")
|
||||
for edge in self.edges:
|
||||
f.write(f"e {edge.start} {edge.end} {edge.length}\n")
|
||||
|
||||
@staticmethod
|
||||
def load(path: str) -> Graph:
|
||||
graph = Graph()
|
||||
with open(path, "r") as f:
|
||||
lines = f.read().splitlines()
|
||||
for line in lines:
|
||||
if len(line.strip()) == 0:
|
||||
continue
|
||||
|
||||
entry_type, values = line.split(" ", 1)
|
||||
if entry_type == "n":
|
||||
x, z, name = values.split(" ", 2)
|
||||
x, z = int(x), int(z)
|
||||
graph.add_node(x, z, name)
|
||||
elif entry_type == "e":
|
||||
start, end, length = values.split(" ", 2)
|
||||
start, end, length = int(start), int(end), float(length)
|
||||
graph.add_edge(start, end, length)
|
||||
return graph
|
||||
|
Reference in New Issue
Block a user