-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgenerate_graph.py
64 lines (54 loc) · 1.76 KB
/
generate_graph.py
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
#!/usr/bin/env python
from itertools import combinations, groupby
import json
import random
import networkx as nx
def gnp_random_connected_graph(n, p):
"""
Generates a random undirected graph, similarly to an Erdős-Rényi
graph, but enforcing that the resulting graph is conneted
"""
edges = combinations(range(n), 2)
G = nx.Graph()
G.add_nodes_from(range(n))
if p <= 0:
return G
if p >= 1:
return nx.complete_graph(n, create_using=G)
for _, node_edges in groupby(edges, key=lambda x: x[0]):
node_edges = list(node_edges)
random_edge = random.choice(node_edges)
G.add_edge(*random_edge)
for e in node_edges:
if random.random() < p:
G.add_edge(*e)
return G
NUM_NODES = 50
VEHICLES = ["Light", "Colorful", "Passenger", "Truck", "IllegalRacer", "Police", "Tractor"]
VERTICES = ["Basic", "Recolor", "BusStop", "PoliceVert", "GasStation", "Field", "Warehouse", "Factory", "ConstructionSite"]
G = gnp_random_connected_graph(NUM_NODES, 0.00001)
data = {
"vertices" : {},
"vehicles" : {}
}
vertices = data["vertices"]
vehicles = data["vehicles"]
for node in G.nodes:
nodeName = "v" + str(node);
vertices[nodeName] = {
"type" : random.choice(VERTICES),
"incident" : {}
}
for edge in G.edges:
nodeFrom = "v" + str(edge[0])
nodeTo = "v" + str(edge[1])
vertices[nodeFrom]["incident"][nodeTo] = {
"length" : random.uniform(0.3, 1.5)
}
for i in range(1, random.randint(NUM_NODES // 10, NUM_NODES // 2)):
vehicles[str(i)] = {
"type" : random.choice(VEHICLES),
"initial" : "v" + str(random.randint(0, NUM_NODES - 1))
}
with open('graph.json', 'w') as outfile:
json.dump(data, outfile)