2021-10-08 18:16:04 +02:00
|
|
|
import random as rand
|
|
|
|
|
|
|
|
|
|
|
|
def read_graph_from_file(path, separator=",", read_first_line=False, is_directed=False, has_weight=False):
|
|
|
|
edges = dict()
|
|
|
|
with open(path, 'r') as file:
|
|
|
|
read_line = read_first_line
|
|
|
|
line = file.readline()
|
|
|
|
while line != '':
|
|
|
|
if read_line:
|
|
|
|
if line[0] != "#":
|
2021-10-17 11:21:09 +02:00
|
|
|
split = line.strip('\n').split(separator)
|
2021-10-08 18:16:04 +02:00
|
|
|
node1 = int(split[0])
|
|
|
|
node2 = int(split[1])
|
|
|
|
if not is_directed:
|
2021-10-17 11:21:09 +02:00
|
|
|
if node1 < node2:
|
|
|
|
node1, node2 = node2, node1
|
2021-10-08 18:16:04 +02:00
|
|
|
if not has_weight:
|
|
|
|
edges[(node1, node2)] = 1
|
|
|
|
else:
|
2021-10-17 11:21:09 +02:00
|
|
|
edges[(node1, node2)] = int(split[2])
|
2021-10-08 18:16:04 +02:00
|
|
|
else:
|
|
|
|
read_line = True
|
|
|
|
line = file.readline()
|
|
|
|
return edges
|
|
|
|
|
|
|
|
|
|
|
|
def add_weight_to_file(graph, path, extension, separator=",", weight_scale=(1, 100)):
|
2021-10-17 11:21:09 +02:00
|
|
|
with open(path + "_with_weight" + extension, 'w') as file:
|
2021-10-08 18:16:04 +02:00
|
|
|
for key in graph.keys():
|
|
|
|
file.write(str(key[0]) + separator + str(key[1]) + separator + str(rand.randint(weight_scale[0],
|
|
|
|
weight_scale[1])) + "\n")
|