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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import networkx as nx
|
| 2 |
+
import random
|
| 3 |
+
from visualizer import get_sorted_nodes
|
| 4 |
+
|
| 5 |
+
def validate_topology(G, topology):
|
| 6 |
+
n = len(G.nodes())
|
| 7 |
+
e = len(G.edges())
|
| 8 |
+
if n < 3: return True, "Graph too small for strict validation."
|
| 9 |
+
|
| 10 |
+
avg_deg = (2.0 * e) / n
|
| 11 |
+
|
| 12 |
+
if topology == "highly_connected":
|
| 13 |
+
if avg_deg < 2.5:
|
| 14 |
+
return False, f"Graph is sparse (Avg Degree: {avg_deg:.1f}) for 'Highly Connected'. Add more target edges."
|
| 15 |
+
|
| 16 |
+
elif topology == "bottlenecks":
|
| 17 |
+
bridges = list(nx.bridges(G))
|
| 18 |
+
if len(bridges) == 0 and avg_deg > 3.0:
|
| 19 |
+
return False, "Graph lacks distinct bottleneck links (bridges) and is too dense. Reduce target edges."
|
| 20 |
+
|
| 21 |
+
elif topology == "linear":
|
| 22 |
+
max_deg = max([d for n, d in G.degree()]) if len(G.nodes()) > 0 else 0
|
| 23 |
+
if max_deg > 4 or avg_deg > 2.5:
|
| 24 |
+
return False, f"Graph contains hub nodes (Max Degree: {max_deg}) or is too dense for 'Linear'. Reduce edges."
|
| 25 |
+
|
| 26 |
+
return True, "Topology matches definition."
|
| 27 |
+
|
| 28 |
+
class NetworkGenerator:
|
| 29 |
+
def __init__(self, width=10, height=10, variant="F", topology="highly_connected",
|
| 30 |
+
node_drop_fraction=0.1, target_edges=0,
|
| 31 |
+
bottleneck_cluster_count=None, bottleneck_edges_per_link=1):
|
| 32 |
+
|
| 33 |
+
self.variant = variant.upper()
|
| 34 |
+
self.topology = topology.lower()
|
| 35 |
+
self.width = int(width)
|
| 36 |
+
self.height = int(height)
|
| 37 |
+
|
| 38 |
+
self.node_drop_fraction = float(node_drop_fraction)
|
| 39 |
+
self.target_edges = int(target_edges)
|
| 40 |
+
self.node_factor = 0.4
|
| 41 |
+
|
| 42 |
+
if bottleneck_cluster_count is None:
|
| 43 |
+
area = self.width * self.height
|
| 44 |
+
self.bottleneck_cluster_count = max(2, int(area / 18))
|
| 45 |
+
else:
|
| 46 |
+
self.bottleneck_cluster_count = int(bottleneck_cluster_count)
|
| 47 |
+
|
| 48 |
+
self.bottleneck_edges_per_link = int(bottleneck_edges_per_link)
|
| 49 |
+
self.graph = None
|
| 50 |
+
self.active_positions = None
|
| 51 |
+
|
| 52 |
+
# def calculate_defaults(self):
|
| 53 |
+
# total_possible = (self.width + 1) * (self.height + 1)
|
| 54 |
+
# scale = {"highly_connected": 1.2, "bottlenecks": 0.85, "linear": 0.75}.get(self.topology, 1.0)
|
| 55 |
+
|
| 56 |
+
# if self.topology == "highly_connected": vf = max(0.0, self.node_drop_fraction * 0.8)
|
| 57 |
+
# elif self.topology == "linear": vf = min(0.95, self.node_drop_fraction * 1.2)
|
| 58 |
+
# else: vf = self.node_drop_fraction
|
| 59 |
+
|
| 60 |
+
# est_nodes = int(self.node_factor * scale * total_possible * (1.0 - vf))
|
| 61 |
+
|
| 62 |
+
# if self.topology == "highly_connected": est_edges = int(3.5 * est_nodes)
|
| 63 |
+
# elif self.topology == "bottlenecks": est_edges = int(1.8 * est_nodes)
|
| 64 |
+
# else: est_edges = int(1.5 * est_nodes)
|
| 65 |
+
|
| 66 |
+
# return est_nodes, est_edges
|
| 67 |
+
|
| 68 |
+
def calculate_defaults(self):
|
| 69 |
+
total_possible = self.width * self.height
|
| 70 |
+
scale = {"highly_connected": 1.2, "bottlenecks": 0.85, "linear": 0.75}.get(self.topology, 1.0)
|
| 71 |
+
|
| 72 |
+
# NEW: Use the unified fraction method we just updated above
|
| 73 |
+
vf = self._effective_node_drop_fraction()
|
| 74 |
+
|
| 75 |
+
est_nodes = int(self.node_factor * scale * total_possible * (1.0 - vf))
|
| 76 |
+
if self.topology == "highly_connected": est_edges = int(3.5 * est_nodes)
|
| 77 |
+
elif self.topology == "bottlenecks": est_edges = int(1.8 * est_nodes)
|
| 78 |
+
else: est_edges = int(1.5 * est_nodes)
|
| 79 |
+
return est_nodes, est_edges
|
| 80 |
+
|
| 81 |
+
def calculate_max_capacity(self):
|
| 82 |
+
"""Estimates max possible edges for planar-like spatial graph."""
|
| 83 |
+
total_possible_nodes = int(self.width * self.height * (1.0 - self.node_drop_fraction))
|
| 84 |
+
if self.topology == "highly_connected":
|
| 85 |
+
return int(total_possible_nodes * 4.5)
|
| 86 |
+
return int(total_possible_nodes * 3.0)
|
| 87 |
+
|
| 88 |
+
def generate(self):
|
| 89 |
+
max_attempts = 15
|
| 90 |
+
for attempt in range(max_attempts):
|
| 91 |
+
self._build_node_mask()
|
| 92 |
+
self._initialize_graph()
|
| 93 |
+
self._add_nodes()
|
| 94 |
+
|
| 95 |
+
nodes = list(self.graph.nodes())
|
| 96 |
+
if len(nodes) < 2: continue
|
| 97 |
+
|
| 98 |
+
if self.topology == "bottlenecks":
|
| 99 |
+
self._build_bottleneck_clusters(nodes)
|
| 100 |
+
else:
|
| 101 |
+
self._connect_all_nodes_by_nearby_growth(nodes)
|
| 102 |
+
self._add_edges()
|
| 103 |
+
|
| 104 |
+
self._remove_intersections()
|
| 105 |
+
|
| 106 |
+
if self.target_edges > 0:
|
| 107 |
+
self._adjust_edges_to_target()
|
| 108 |
+
else:
|
| 109 |
+
self._enforce_edge_budget()
|
| 110 |
+
|
| 111 |
+
if not nx.is_connected(self.graph):
|
| 112 |
+
self._force_connect_components()
|
| 113 |
+
|
| 114 |
+
self._remove_intersections()
|
| 115 |
+
|
| 116 |
+
if nx.is_connected(self.graph):
|
| 117 |
+
return self.graph
|
| 118 |
+
|
| 119 |
+
raise RuntimeError("Failed to generate valid network. Loosen overrides.")
|
| 120 |
+
|
| 121 |
+
# def _effective_node_drop_fraction(self):
|
| 122 |
+
# base = self.node_drop_fraction
|
| 123 |
+
# if self.topology == "highly_connected": return max(0.0, base * 0.8)
|
| 124 |
+
# if self.topology == "linear": return min(0.95, base * 1.2)
|
| 125 |
+
# return base
|
| 126 |
+
|
| 127 |
+
def _effective_node_drop_fraction(self):
|
| 128 |
+
base = self.node_drop_fraction
|
| 129 |
+
|
| 130 |
+
# Fix: app.py passes "R" when the "Custom" variant is selected
|
| 131 |
+
if self.variant == "R":
|
| 132 |
+
return base
|
| 133 |
+
|
| 134 |
+
# Safety net for 'Fixed' ("F") presets
|
| 135 |
+
if self.topology == "highly_connected": return max(0.0, base * 0.8)
|
| 136 |
+
if self.topology == "linear": return min(0.95, base * 1.2)
|
| 137 |
+
return base
|
| 138 |
+
|
| 139 |
+
def _build_node_mask(self):
|
| 140 |
+
all_positions = [(x, y) for x in range(self.width) for y in range(self.height)]
|
| 141 |
+
drop_frac = self._effective_node_drop_fraction()
|
| 142 |
+
drop = int(drop_frac * len(all_positions))
|
| 143 |
+
deactivated = set(random.sample(all_positions, drop)) if drop > 0 else set()
|
| 144 |
+
self.active_positions = set(all_positions) - deactivated
|
| 145 |
+
|
| 146 |
+
def _initialize_graph(self):
|
| 147 |
+
self.graph = nx.Graph()
|
| 148 |
+
margin_x = max(1, self.width // 4)
|
| 149 |
+
margin_y = max(1, self.height // 4)
|
| 150 |
+
low_x, high_x = margin_x, self.width - 1 - margin_x
|
| 151 |
+
low_y, high_y = margin_y, self.height - 1 - margin_y
|
| 152 |
+
|
| 153 |
+
if low_x > high_x: low_x, high_x = 0, self.width - 1
|
| 154 |
+
if low_y > high_y: low_y, high_y = 0, self.height - 1
|
| 155 |
+
|
| 156 |
+
middle_active = [p for p in self.active_positions if low_x <= p[0] <= high_x and low_y <= p[1] <= high_y]
|
| 157 |
+
|
| 158 |
+
if middle_active: seed = random.choice(middle_active)
|
| 159 |
+
elif self.active_positions: seed = random.choice(list(self.active_positions))
|
| 160 |
+
else: return
|
| 161 |
+
self.graph.add_node(tuple(seed))
|
| 162 |
+
|
| 163 |
+
def _add_nodes(self):
|
| 164 |
+
for n in self.active_positions:
|
| 165 |
+
if not self.graph.has_node(n):
|
| 166 |
+
self.graph.add_node(n)
|
| 167 |
+
|
| 168 |
+
def _connect_all_nodes_by_nearby_growth(self, nodes):
|
| 169 |
+
connected = set()
|
| 170 |
+
remaining = set(nodes)
|
| 171 |
+
if not remaining: return
|
| 172 |
+
current = random.choice(nodes)
|
| 173 |
+
connected.add(current)
|
| 174 |
+
remaining.remove(current)
|
| 175 |
+
|
| 176 |
+
while remaining:
|
| 177 |
+
candidates = []
|
| 178 |
+
for n in remaining:
|
| 179 |
+
closest_dist = min([abs(n[0]-c[0]) + abs(n[1]-c[1]) for c in connected])
|
| 180 |
+
if closest_dist <= 4:
|
| 181 |
+
candidates.append(n)
|
| 182 |
+
|
| 183 |
+
if not candidates:
|
| 184 |
+
best_n = min(remaining, key=lambda r: min(abs(r[0]-c[0]) + abs(r[1]-c[1]) for c in connected))
|
| 185 |
+
candidates.append(best_n)
|
| 186 |
+
|
| 187 |
+
candidate = random.choice(candidates)
|
| 188 |
+
neighbors = sorted(list(connected), key=lambda c: abs(c[0]-candidate[0]) + abs(c[1]-candidate[1]))
|
| 189 |
+
for n in neighbors[:3]:
|
| 190 |
+
if not self._would_create_intersection(n, candidate):
|
| 191 |
+
self.graph.add_edge(n, candidate)
|
| 192 |
+
break
|
| 193 |
+
else:
|
| 194 |
+
self.graph.add_edge(neighbors[0], candidate)
|
| 195 |
+
|
| 196 |
+
connected.add(candidate)
|
| 197 |
+
remaining.remove(candidate)
|
| 198 |
+
|
| 199 |
+
def _compute_edge_count(self):
|
| 200 |
+
if self.target_edges > 0: return self.target_edges
|
| 201 |
+
n = len(self.graph.nodes())
|
| 202 |
+
if self.topology == "highly_connected": return int(3.5 * n)
|
| 203 |
+
if self.topology == "bottlenecks": return int(1.8 * n)
|
| 204 |
+
return int(random.uniform(1.2, 2.0) * n)
|
| 205 |
+
|
| 206 |
+
def _add_edges(self):
|
| 207 |
+
nodes = list(self.graph.nodes())
|
| 208 |
+
if self.topology == "highly_connected": self._add_cluster_dense(nodes, self._compute_edge_count())
|
| 209 |
+
elif self.topology == "linear": self._make_linear(nodes)
|
| 210 |
+
|
| 211 |
+
def _make_linear(self, nodes):
|
| 212 |
+
nodes_sorted = sorted(nodes, key=lambda x: (x[0], x[1]))
|
| 213 |
+
if not nodes_sorted: return
|
| 214 |
+
prev = nodes_sorted[0]
|
| 215 |
+
for nxt in nodes_sorted[1:]:
|
| 216 |
+
if not self._would_create_intersection(prev, nxt): self.graph.add_edge(prev, nxt)
|
| 217 |
+
prev = nxt
|
| 218 |
+
|
| 219 |
+
def _add_cluster_dense(self, nodes, max_edges):
|
| 220 |
+
edges_added = 0
|
| 221 |
+
nodes = list(nodes)
|
| 222 |
+
random.shuffle(nodes)
|
| 223 |
+
dist_limit = 10 if self.target_edges > 0 else 4
|
| 224 |
+
|
| 225 |
+
for i in range(len(nodes)):
|
| 226 |
+
for j in range(i + 1, len(nodes)):
|
| 227 |
+
if self.target_edges == 0 and edges_added >= max_edges: return
|
| 228 |
+
n1, n2 = nodes[i], nodes[j]
|
| 229 |
+
dist = max(abs(n1[0]-n2[0]), abs(n1[1]-n2[1]))
|
| 230 |
+
if dist <= dist_limit:
|
| 231 |
+
if not self._would_create_intersection(n1, n2):
|
| 232 |
+
self.graph.add_edge(n1, n2)
|
| 233 |
+
edges_added += 1
|
| 234 |
+
|
| 235 |
+
def _build_bottleneck_clusters(self, nodes):
|
| 236 |
+
self.graph.remove_edges_from(list(self.graph.edges()))
|
| 237 |
+
clusters, centers = self._spatial_cluster_nodes(nodes, k=self.bottleneck_cluster_count)
|
| 238 |
+
for cluster in clusters:
|
| 239 |
+
if len(cluster) < 2: continue
|
| 240 |
+
# FIX: Call main connectivity directly
|
| 241 |
+
self._connect_all_nodes_by_nearby_growth(cluster)
|
| 242 |
+
self._add_cluster_dense(list(cluster), max_edges=max(1, int(3.5 * len(cluster))))
|
| 243 |
+
|
| 244 |
+
order = sorted(range(len(clusters)), key=lambda i: (centers[i][0], centers[i][1]))
|
| 245 |
+
for a_idx, b_idx in zip(order[:-1], order[1:]):
|
| 246 |
+
self._add_bottleneck_links(clusters[a_idx], clusters[b_idx], self.bottleneck_edges_per_link)
|
| 247 |
+
|
| 248 |
+
if not nx.is_connected(self.graph): self._force_connect_components()
|
| 249 |
+
|
| 250 |
+
def _force_connect_components(self):
|
| 251 |
+
components = list(nx.connected_components(self.graph))
|
| 252 |
+
while len(components) > 1:
|
| 253 |
+
c1, c2 = list(components[0]), list(components[1])
|
| 254 |
+
best_pair, min_dist = None, float('inf')
|
| 255 |
+
s1 = c1 if len(c1)<30 else random.sample(c1, 30)
|
| 256 |
+
s2 = c2 if len(c2)<30 else random.sample(c2, 30)
|
| 257 |
+
for u in s1:
|
| 258 |
+
for v in s2:
|
| 259 |
+
d = (u[0]-v[0])**2 + (u[1]-v[1])**2
|
| 260 |
+
if d < min_dist and not self._would_create_intersection(u, v):
|
| 261 |
+
min_dist, best_pair = d, (u, v)
|
| 262 |
+
if best_pair: self.graph.add_edge(best_pair[0], best_pair[1])
|
| 263 |
+
else: break
|
| 264 |
+
prev_len = len(components)
|
| 265 |
+
components = list(nx.connected_components(self.graph))
|
| 266 |
+
if len(components) == prev_len: break
|
| 267 |
+
|
| 268 |
+
def _spatial_cluster_nodes(self, nodes, k):
|
| 269 |
+
nodes = list(nodes)
|
| 270 |
+
if k >= len(nodes): return [[n] for n in nodes], nodes[:]
|
| 271 |
+
centers = random.sample(nodes, k)
|
| 272 |
+
clusters = [[] for _ in range(k)]
|
| 273 |
+
for n in nodes:
|
| 274 |
+
best_i = min(range(k), key=lambda i: max(abs(n[0]-centers[i][0]), abs(n[1]-centers[i][1])))
|
| 275 |
+
clusters[best_i].append(n)
|
| 276 |
+
return clusters, centers
|
| 277 |
+
|
| 278 |
+
def _add_bottleneck_links(self, cluster_a, cluster_b, m):
|
| 279 |
+
pairs = []
|
| 280 |
+
for u in cluster_a:
|
| 281 |
+
for v in cluster_b:
|
| 282 |
+
dist = max(abs(u[0]-v[0]), abs(u[1]-v[1]))
|
| 283 |
+
pairs.append((dist, u, v))
|
| 284 |
+
pairs.sort(key=lambda t: t[0])
|
| 285 |
+
added = 0
|
| 286 |
+
for _, u, v in pairs:
|
| 287 |
+
if added >= m: break
|
| 288 |
+
if not self.graph.has_edge(u, v) and not self._would_create_intersection(u, v):
|
| 289 |
+
self.graph.add_edge(u, v)
|
| 290 |
+
added += 1
|
| 291 |
+
|
| 292 |
+
def _remove_intersections(self):
|
| 293 |
+
pass_no = 0
|
| 294 |
+
while pass_no < 5:
|
| 295 |
+
pass_no += 1
|
| 296 |
+
edges = list(self.graph.edges())
|
| 297 |
+
intersections = []
|
| 298 |
+
check_edges = random.sample(edges, 400) if len(edges) > 600 else edges
|
| 299 |
+
for i in range(len(check_edges)):
|
| 300 |
+
for j in range(i+1, len(check_edges)):
|
| 301 |
+
e1, e2 = check_edges[i], check_edges[j]
|
| 302 |
+
if self._segments_intersect(e1[0], e1[1], e2[0], e2[1]): intersections.append((e1, e2))
|
| 303 |
+
if not intersections: break
|
| 304 |
+
for e1, e2 in intersections:
|
| 305 |
+
if not self.graph.has_edge(*e1) or not self.graph.has_edge(*e2): continue
|
| 306 |
+
l1 = (e1[0][0]-e1[1][0])**2 + (e1[0][1]-e1[1][1])**2
|
| 307 |
+
l2 = (e2[0][0]-e2[1][0])**2 + (e2[0][1]-e2[1][1])**2
|
| 308 |
+
rem = e1 if l1 > l2 else e2
|
| 309 |
+
self.graph.remove_edge(*rem)
|
| 310 |
+
|
| 311 |
+
def _adjust_edges_to_target(self):
|
| 312 |
+
current_edges = list(self.graph.edges())
|
| 313 |
+
curr_count = len(current_edges)
|
| 314 |
+
if curr_count > self.target_edges:
|
| 315 |
+
to_remove = curr_count - self.target_edges
|
| 316 |
+
sorted_edges = sorted(current_edges, key=lambda e: (e[0][0]-e[1][0])**2 + (e[0][1]-e[1][1])**2, reverse=True)
|
| 317 |
+
for e in sorted_edges:
|
| 318 |
+
if len(self.graph.edges()) <= self.target_edges: break
|
| 319 |
+
self.graph.remove_edge(*e)
|
| 320 |
+
if not nx.is_connected(self.graph): self.graph.add_edge(*e)
|
| 321 |
+
elif curr_count < self.target_edges:
|
| 322 |
+
needed = self.target_edges - curr_count
|
| 323 |
+
nodes = list(self.graph.nodes())
|
| 324 |
+
attempts = 0
|
| 325 |
+
while len(self.graph.edges()) < self.target_edges and attempts < (needed * 30):
|
| 326 |
+
attempts += 1
|
| 327 |
+
u = random.choice(nodes)
|
| 328 |
+
candidates = sorted(nodes, key=lambda n: (n[0]-u[0])**2 + (n[1]-u[1])**2)
|
| 329 |
+
if len(candidates) < 2: continue
|
| 330 |
+
v = random.choice(candidates[1:min(len(candidates), 10)])
|
| 331 |
+
if not self.graph.has_edge(u, v) and not self._would_create_intersection(u, v):
|
| 332 |
+
self.graph.add_edge(u, v)
|
| 333 |
+
|
| 334 |
+
def _enforce_edge_budget(self):
|
| 335 |
+
budget = self._compute_edge_count()
|
| 336 |
+
while len(self.graph.edges()) > budget:
|
| 337 |
+
edges = list(self.graph.edges())
|
| 338 |
+
rem = random.choice(edges)
|
| 339 |
+
self.graph.remove_edge(*rem)
|
| 340 |
+
if not nx.is_connected(self.graph):
|
| 341 |
+
self.graph.add_edge(*rem)
|
| 342 |
+
break
|
| 343 |
+
|
| 344 |
+
def _segments_intersect(self, a, b, c, d):
|
| 345 |
+
if a == c or a == d or b == c or b == d: return False
|
| 346 |
+
def ccw(A,B,C): return (C[1]-A[1]) * (B[0]-A[0]) > (B[1]-A[1]) * (C[0]-A[0])
|
| 347 |
+
return ccw(a,c,d) != ccw(b,c,d) and ccw(a,b,c) != ccw(a,b,d)
|
| 348 |
+
|
| 349 |
+
def _would_create_intersection(self, u, v):
|
| 350 |
+
for a, b in self.graph.edges():
|
| 351 |
+
if u == a or u == b or v == a or v == b: continue
|
| 352 |
+
if self._segments_intersect(u, v, a, b): return True
|
| 353 |
+
return False
|
| 354 |
+
|
| 355 |
+
def _get_intersecting_edge(self, u, v):
|
| 356 |
+
for a, b in self.graph.edges():
|
| 357 |
+
if u == a or u == b or v == a or v == b: continue
|
| 358 |
+
if self._segments_intersect(u, v, a, b): return (a, b)
|
| 359 |
+
return None
|
| 360 |
+
|
| 361 |
+
def get_node_id_str(self, node):
|
| 362 |
+
sorted_nodes = get_sorted_nodes(self.graph)
|
| 363 |
+
if node in sorted_nodes:
|
| 364 |
+
return str(sorted_nodes.index(node) + 1)
|
| 365 |
+
return "?"
|
| 366 |
+
|
| 367 |
+
def manual_add_node(self, x, y):
|
| 368 |
+
x, y = int(x), int(y)
|
| 369 |
+
# FIX: Bounds check against Width-1
|
| 370 |
+
if not (0 <= x < self.width and 0 <= y < self.height): return False, "Out of bounds."
|
| 371 |
+
if self.graph.has_node((x, y)): return False, "Already exists."
|
| 372 |
+
self.graph.add_node((x, y))
|
| 373 |
+
nodes = list(self.graph.nodes())
|
| 374 |
+
if len(nodes) > 1:
|
| 375 |
+
closest = min([n for n in nodes if n != (x,y)], key=lambda n: (n[0]-x)**2 + (n[1]-y)**2)
|
| 376 |
+
if not self._would_create_intersection((x,y), closest): self.graph.add_edge((x,y), closest)
|
| 377 |
+
return True, "Node added."
|
| 378 |
+
|
| 379 |
+
def manual_delete_node(self, x, y):
|
| 380 |
+
x, y = int(x), int(y)
|
| 381 |
+
if not self.graph.has_node((x, y)): return False, "Node not found."
|
| 382 |
+
self.graph.remove_node((x, y))
|
| 383 |
+
if len(self.graph.nodes()) > 1 and not nx.is_connected(self.graph):
|
| 384 |
+
self._force_connect_components()
|
| 385 |
+
return True, "Node removed."
|
| 386 |
+
|
| 387 |
+
def manual_toggle_edge(self, u, v):
|
| 388 |
+
if self.graph.has_edge(u, v):
|
| 389 |
+
self.graph.remove_edge(u, v)
|
| 390 |
+
if not nx.is_connected(self.graph):
|
| 391 |
+
self.graph.add_edge(u, v)
|
| 392 |
+
return False, "Cannot remove edge (breaks connectivity)."
|
| 393 |
+
return True, "Edge removed."
|
| 394 |
+
else:
|
| 395 |
+
intersecting_edge = self._get_intersecting_edge(u, v)
|
| 396 |
+
if not intersecting_edge:
|
| 397 |
+
self.graph.add_edge(u, v)
|
| 398 |
+
return True, "Edge added."
|
| 399 |
+
else:
|
| 400 |
+
a, b = intersecting_edge
|
| 401 |
+
id_a = self.get_node_id_str(a)
|
| 402 |
+
id_b = self.get_node_id_str(b)
|
| 403 |
+
return False, f"Intersect with {id_a}-{id_b}."
|