TahaRasouli commited on
Commit
48cc956
·
verified ·
1 Parent(s): bca6fdd

Create graphGen7.py

Browse files
Files changed (1) hide show
  1. graphGen7.py +319 -0
graphGen7.py ADDED
@@ -0,0 +1,319 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import numpy as np
3
+ import networkx as nx
4
+ import matplotlib.pyplot as plt
5
+ import random
6
+ import time
7
+
8
+
9
+ class NetworkGenerator:
10
+ def __init__(self,
11
+ width=10,
12
+ height=10,
13
+ variant="F",
14
+ topology="highly_connected",
15
+ node_drop_fraction=0.1,
16
+ bottleneck_cluster_count=None,
17
+ bottleneck_edges_per_link=1):
18
+
19
+ self.variant = variant.upper() # "F" = Fixed Density, "R" = Random/Custom Density
20
+ self.topology = topology.lower()
21
+ self.width = int(width)
22
+ self.height = int(height)
23
+ self.node_drop_fraction = float(node_drop_fraction)
24
+
25
+ # Standard config
26
+ self.node_factor = 0.4
27
+
28
+ # Bottleneck settings
29
+ if bottleneck_cluster_count is None:
30
+ area = self.width * self.height
31
+ self.bottleneck_cluster_count = max(2, int(area / 18))
32
+ else:
33
+ self.bottleneck_cluster_count = int(bottleneck_cluster_count)
34
+
35
+ self.bottleneck_edges_per_link = int(bottleneck_edges_per_link)
36
+
37
+ self.graph = None
38
+ self.active_positions = None
39
+
40
+ def generate(self):
41
+ """Generate a connected network representing rooms in a building."""
42
+ max_attempts = 20
43
+
44
+ for attempt in range(max_attempts):
45
+ self._build_node_mask()
46
+ self._initialize_graph()
47
+ self._add_nodes()
48
+
49
+ nodes = list(self.graph.nodes())
50
+ if len(nodes) < 2:
51
+ continue
52
+
53
+ # Topology-specific edge construction
54
+ if self.topology == "bottlenecks":
55
+ self._build_bottleneck_clusters(nodes)
56
+ else:
57
+ self._connect_all_nodes_by_nearby_growth(nodes)
58
+ self._add_edges()
59
+
60
+ # Cleanup - STRICT MODE
61
+ self._remove_intersections()
62
+ self._enforce_edge_budget()
63
+
64
+ if not nx.is_connected(self.graph):
65
+ self._force_connect_components()
66
+
67
+ # Final Safety Check
68
+ self._remove_intersections()
69
+
70
+ if nx.is_connected(self.graph):
71
+ return self.graph
72
+
73
+ raise RuntimeError("Failed to generate a valid network. Try reducing Void Fraction.")
74
+
75
+ # --- INTERNAL HELPERS ---
76
+ def _effective_node_drop_fraction(self):
77
+ base = self.node_drop_fraction
78
+ if self.topology == "highly_connected": return max(0.0, base * 0.8)
79
+ if self.topology == "linear": return min(0.95, base * 1.2)
80
+ return base
81
+
82
+ def _build_node_mask(self):
83
+ all_positions = [(x, y) for x in range(self.width + 1) for y in range(self.height + 1)]
84
+ drop_frac = self._effective_node_drop_fraction()
85
+ drop = int(drop_frac * len(all_positions))
86
+
87
+ deactivated = set(random.sample(all_positions, drop)) if drop > 0 else set()
88
+ self.active_positions = set(all_positions) - deactivated
89
+
90
+ def _initialize_graph(self):
91
+ self.graph = nx.Graph()
92
+ # Seed near center
93
+ margin_x = max(1, self.width // 4)
94
+ margin_y = max(1, self.height // 4)
95
+
96
+ low_x, high_x = margin_x, self.width - margin_x
97
+ low_y, high_y = margin_y, self.height - margin_y
98
+
99
+ middle_active = [
100
+ (x, y) for (x, y) in self.active_positions
101
+ if low_x <= x <= high_x and low_y <= y <= high_y
102
+ ]
103
+
104
+ if middle_active:
105
+ seed = random.choice(middle_active)
106
+ elif self.active_positions:
107
+ seed = random.choice(list(self.active_positions))
108
+ else:
109
+ return
110
+
111
+ self.graph.add_node(tuple(seed))
112
+
113
+ def _compute_nodes(self):
114
+ total_possible = (self.width + 1) * (self.height + 1)
115
+ # Variant "F" (Fixed) uses stable logic. Variant "R" (Custom) adds randomization.
116
+ base = self.node_factor if self.variant == "F" else random.uniform(0.3, 0.6)
117
+ scale = {"highly_connected": 1.2, "bottlenecks": 0.85, "linear": 0.75}.get(self.topology, 1.0)
118
+
119
+ target = int(base * scale * total_possible)
120
+ return min(target, len(self.active_positions))
121
+
122
+ def _add_nodes(self):
123
+ total_nodes = self._compute_nodes()
124
+ attempts = 0
125
+ while len(self.graph.nodes()) < total_nodes and attempts < (total_nodes * 20):
126
+ attempts += 1
127
+ x = random.randint(0, self.width)
128
+ y = random.randint(0, self.height)
129
+
130
+ if (x, y) in self.active_positions and (x, y) not in self.graph:
131
+ self.graph.add_node((x, y))
132
+
133
+ def _connect_all_nodes_by_nearby_growth(self, nodes):
134
+ connected = set()
135
+ remaining = set(nodes)
136
+ if not remaining: return
137
+
138
+ current = random.choice(nodes)
139
+ connected.add(current)
140
+ remaining.remove(current)
141
+
142
+ while remaining:
143
+ candidates = []
144
+ for n in remaining:
145
+ for c in connected:
146
+ if abs(n[0]-c[0]) <= 2 and abs(n[1]-c[1]) <= 2:
147
+ candidates.append(n)
148
+ break
149
+
150
+ if not candidates:
151
+ n = min(remaining, key=lambda r: min(abs(r[0]-c[0]) + abs(r[1]-c[1]) for c in connected))
152
+ candidates.append(n)
153
+
154
+ candidate = random.choice(candidates)
155
+
156
+ neighbors = [c for c in connected if abs(c[0]-candidate[0])<=3 and abs(c[1]-candidate[1])<=3]
157
+ neighbors.sort(key=lambda c: abs(c[0]-candidate[0]) + abs(c[1]-candidate[1]))
158
+
159
+ n = neighbors[0] if neighbors else random.choice(list(connected))
160
+
161
+ self.graph.add_edge(n, candidate)
162
+ connected.add(candidate)
163
+ remaining.remove(candidate)
164
+
165
+ def _compute_edge_count(self):
166
+ n = len(self.graph.nodes())
167
+ if self.topology == "highly_connected": return int(3.5 * n)
168
+ if self.topology == "bottlenecks": return int(1.8 * n)
169
+ return int(random.uniform(1.2, 2.0) * n)
170
+
171
+ def _add_edges(self):
172
+ nodes = list(self.graph.nodes())
173
+ if self.topology == "highly_connected":
174
+ self._add_cluster_dense(nodes, self._compute_edge_count())
175
+ elif self.topology == "linear":
176
+ self._make_linear(nodes)
177
+
178
+ def _make_linear(self, nodes):
179
+ nodes_sorted = sorted(nodes, key=lambda x: (x[0], x[1]))
180
+ if not nodes_sorted: return
181
+ prev = nodes_sorted[0]
182
+ for nxt in nodes_sorted[1:]:
183
+ if not self._would_create_intersection(prev, nxt):
184
+ self.graph.add_edge(prev, nxt)
185
+ prev = nxt
186
+
187
+ def _add_cluster_dense(self, nodes, max_edges):
188
+ edges_added = 0
189
+ nodes = list(nodes)
190
+ random.shuffle(nodes)
191
+
192
+ for i in range(len(nodes)):
193
+ for j in range(i + 1, len(nodes)):
194
+ if edges_added >= max_edges: return
195
+
196
+ n1, n2 = nodes[i], nodes[j]
197
+ dist = max(abs(n1[0]-n2[0]), abs(n1[1]-n2[1]))
198
+
199
+ if dist <= 4:
200
+ if not self._would_create_intersection(n1, n2):
201
+ self.graph.add_edge(n1, n2)
202
+ edges_added += 1
203
+
204
+ # --- BOTTLENECK LOGIC ---
205
+ def _build_bottleneck_clusters(self, nodes):
206
+ self.graph.remove_edges_from(list(self.graph.edges()))
207
+ clusters, centers = self._spatial_cluster_nodes(nodes, k=self.bottleneck_cluster_count)
208
+
209
+ for cluster in clusters:
210
+ if len(cluster) < 2: continue
211
+ self._connect_cluster_by_nearby_growth(cluster)
212
+ self._add_cluster_dense(list(cluster), max_edges=max(1, int(3.5 * len(cluster))))
213
+
214
+ order = sorted(range(len(clusters)), key=lambda i: (centers[i][0], centers[i][1]))
215
+ for a_idx, b_idx in zip(order[:-1], order[1:]):
216
+ self._add_bottleneck_links(clusters[a_idx], clusters[b_idx], self.bottleneck_edges_per_link)
217
+
218
+ if not nx.is_connected(self.graph):
219
+ self._force_connect_components()
220
+
221
+ def _force_connect_components(self):
222
+ components = list(nx.connected_components(self.graph))
223
+ while len(components) > 1:
224
+ c1 = list(components[0])
225
+ c2 = list(components[1])
226
+
227
+ best_pair = None
228
+ min_dist = float('inf')
229
+
230
+ for u in c1:
231
+ for v in c2:
232
+ d = (u[0]-v[0])**2 + (u[1]-v[1])**2
233
+ if d < min_dist:
234
+ if not self._would_create_intersection(u, v):
235
+ min_dist = d
236
+ best_pair = (u, v)
237
+
238
+ if best_pair:
239
+ self.graph.add_edge(best_pair[0], best_pair[1])
240
+ else:
241
+ pass
242
+
243
+ prev_len = len(components)
244
+ components = list(nx.connected_components(self.graph))
245
+ if len(components) == prev_len: break
246
+
247
+ def _spatial_cluster_nodes(self, nodes, k):
248
+ nodes = list(nodes)
249
+ if k >= len(nodes): return [[n] for n in nodes], nodes[:]
250
+ centers = random.sample(nodes, k)
251
+ clusters = [[] for _ in range(k)]
252
+ for n in nodes:
253
+ best_i = min(range(k), key=lambda i: max(abs(n[0]-centers[i][0]), abs(n[1]-centers[i][1])))
254
+ clusters[best_i].append(n)
255
+ return clusters, centers
256
+
257
+ def _connect_cluster_by_nearby_growth(self, cluster_nodes):
258
+ self._connect_all_nodes_by_nearby_growth(cluster_nodes)
259
+
260
+ def _add_bottleneck_links(self, cluster_a, cluster_b, m):
261
+ pairs = []
262
+ for u in cluster_a:
263
+ for v in cluster_b:
264
+ dist = max(abs(u[0]-v[0]), abs(u[1]-v[1]))
265
+ pairs.append((dist, u, v))
266
+ pairs.sort(key=lambda t: t[0])
267
+
268
+ added = 0
269
+ for _, u, v in pairs:
270
+ if added >= m: break
271
+ if not self.graph.has_edge(u, v) and not self._would_create_intersection(u, v):
272
+ self.graph.add_edge(u, v)
273
+ added += 1
274
+
275
+ # --- GEOMETRY & CLEANUP ---
276
+ def _remove_intersections(self):
277
+ pass_no = 0
278
+ while pass_no < 8:
279
+ pass_no += 1
280
+ edges = list(self.graph.edges())
281
+ intersections = []
282
+
283
+ for i in range(len(edges)):
284
+ for j in range(i+1, len(edges)):
285
+ e1 = edges[i]
286
+ e2 = edges[j]
287
+ if self._segments_intersect(e1[0], e1[1], e2[0], e2[1]):
288
+ intersections.append((e1, e2))
289
+
290
+ if not intersections: break
291
+
292
+ for e1, e2 in intersections:
293
+ if not self.graph.has_edge(*e1) or not self.graph.has_edge(*e2): continue
294
+ l1 = (e1[0][0]-e1[1][0])**2 + (e1[0][1]-e1[1][1])**2
295
+ l2 = (e2[0][0]-e2[1][0])**2 + (e2[0][1]-e2[1][1])**2
296
+ rem = e1 if l1 > l2 else e2
297
+ self.graph.remove_edge(*rem)
298
+
299
+ def _enforce_edge_budget(self):
300
+ budget = self._compute_edge_count()
301
+ while len(self.graph.edges()) > budget:
302
+ edges = list(self.graph.edges())
303
+ rem = random.choice(edges)
304
+ self.graph.remove_edge(*rem)
305
+ if not nx.is_connected(self.graph):
306
+ self.graph.add_edge(*rem)
307
+ break
308
+
309
+ def _segments_intersect(self, a, b, c, d):
310
+ if a == c or a == d or b == c or b == d: return False
311
+ def ccw(A,B,C): return (C[1]-A[1]) * (B[0]-A[0]) > (B[1]-A[1]) * (C[0]-A[0])
312
+ return ccw(a,c,d) != ccw(b,c,d) and ccw(a,b,c) != ccw(a,b,d)
313
+
314
+ def _would_create_intersection(self, u, v):
315
+ for a, b in self.graph.edges():
316
+ if u == a or u == b or v == a or v == b: continue
317
+ if self._segments_intersect(u, v, a, b): return True
318
+ return False
319
+