-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgenerate_devices.py
More file actions
434 lines (328 loc) · 15 KB
/
Copy pathgenerate_devices.py
File metadata and controls
434 lines (328 loc) · 15 KB
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
import json, math, random
from scripts import config
def generate_devices():
# ============================================================
# Configuration
# ============================================================
with open(config.ROAD_NODES_FILE, "r") as f: road_nodes = json.load(f)["road_nodes"]
with open(config.DEMAND_POINTS_FILE, "r") as f: demand_points = json.load(f)["demand_points"]
UNCOVERED_WEIGHT = 1000
DISTANCE_WEIGHT = 1.0
# ============================================================
# Distance
# ============================================================
def calculate_distance_m(lat1, lon1, lat2, lon2):
R = 6371000
phi1 = math.radians(lat1)
phi2 = math.radians(lat2)
dphi = math.radians(lat2 - lat1)
dlambda = math.radians(lon2 - lon1)
a = (
math.sin(dphi / 2) ** 2 +
math.cos(phi1) *
math.cos(phi2) *
math.sin(dlambda / 2) ** 2
)
return 2 * R * math.atan2( math.sqrt(a), math.sqrt(1 - a))
# ============================================================
# Helper
# ============================================================
def min_distance_to_selected(candidate, selected_nodes):
if not selected_nodes:
return float("inf")
return min(calculate_distance_m(candidate["latitude"], candidate["longitude"], other["latitude"], other["longitude"]) for other in selected_nodes)
# ============================================================
# Precompute Coverage For Every Road Node
# ============================================================
print("Precomputing node coverage...")
node_coverage = {}
for node in road_nodes:
covered_indices = []
for i, demand in enumerate(demand_points):
dist = calculate_distance_m(node["latitude"], node["longitude"], demand["latitude"], demand["longitude"])
if dist <= config.RU_RANGE_M:
covered_indices.append(i)
node_coverage[node["id"]] = covered_indices
# ============================================================
# Balanced Regional Coverage Placement
# ============================================================
selected_nodes = []
used_node_ids = set()
covered = set()
# ============================================================
# Stage 1 - Prioritise Full Coverage
# ============================================================
print("Stage 1: Achieving full coverage...")
while True:
best_candidate = None
best_score = -1
for node in road_nodes:
if node["id"] in used_node_ids:
continue
candidate_cover = node_coverage[node["id"]]
# Count NEW uncovered demand points
uncovered_points = [idx for idx in candidate_cover if idx not in covered]
uncovered_count = len(uncovered_points)
# Skip useless candidates
if uncovered_count == 0:
continue
# Spread score
if not selected_nodes:
spread_score = config.RU_RANGE_M
else:
spread_score = min(calculate_distance_m(node["latitude"], node["longitude"], other["latitude"], other["longitude"]) for other in selected_nodes)
# Combined score
score = (UNCOVERED_WEIGHT * uncovered_count + DISTANCE_WEIGHT * spread_score)
if score > best_score:
best_score = score
best_candidate = node
# No useful candidate
if best_candidate is None:
break
# Add RU
selected_nodes.append(best_candidate)
used_node_ids.add(best_candidate["id"])
# Update coverage
for idx in node_coverage[best_candidate["id"]]:
covered.add(idx)
covered_count = len(covered)
coverage_percent = (covered_count / len(demand_points)) * 100
print(f"Coverage RU {len(selected_nodes)} | Coverage: {coverage_percent:.2f}%")
# Stop when fully covered
if covered_count == len(demand_points):
print("Full coverage achieved.")
break
# ============================================================
# Stage 2 - Add Extra RUs While Maximising Spread
# ============================================================
print("Stage 2: Adding extra spread-out RUs...")
while len(selected_nodes) < config.NUM_RUS:
best_candidate = None
best_distance = -1
for node in road_nodes:
if node["id"] in used_node_ids:
continue
# Maximise minimum distance to existing RUs
nearest_distance = min(calculate_distance_m( node["latitude"], node["longitude"], other["latitude"], other["longitude"]) for other in selected_nodes)
if nearest_distance > best_distance:
best_distance = nearest_distance
best_candidate = node
if best_candidate is None:
break
selected_nodes.append(best_candidate)
used_node_ids.add(best_candidate["id"])
print(f"Extra RU {len(selected_nodes)}/{config.NUM_RUS} | Spread distance: {best_distance:.2f}m")
# ============================================================
# Final Coverage Statistics
# ============================================================
final_covered = set()
for node in selected_nodes:
final_covered.update(node_coverage[node["id"]])
covered_count = len(final_covered)
coverage_percent = (covered_count / len(demand_points)) * 100
print("================================================")
print(f"Final RU Count: {len(selected_nodes)}")
print(f"Covered demand points: {covered_count}/{len(demand_points)}")
print(f"Coverage: {coverage_percent:.2f}%")
print("================================================")
# ============================================================
# Build RU Objects
# ============================================================
radio_units = []
for i, node in enumerate(selected_nodes, start=1):
radio_units.append({
"ru_name": f"RU{i}",
"service": "RadioUnit",
"latitude": node["latitude"],
"longitude": node["longitude"],
"capacity_bandwidth": config.RU_CAPACITY,
"range_m": config.RU_RANGE_M
})
# ============================================================
# DU Placement
# ============================================================
print("\n================================================")
print("Placing Distributed Units...")
print("================================================")
du_selected_nodes = []
du_used_ids = set()
# Candidate locations are RU locations
du_candidates = selected_nodes.copy()
# ============================================================
# Place First DU
# ============================================================
first_du = random.choice(du_candidates)
du_selected_nodes.append(first_du)
du_used_ids.add(first_du["id"])
print("Placed DU1")
# ============================================================
# Place Remaining DUs
# ============================================================
while len(du_selected_nodes) < config.NUM_DUS:
best_candidate = None
best_distance = -1
for candidate in du_candidates:
if candidate["id"] in du_used_ids:
continue
# Maximise minimum distance to existing DUs
nearest_distance = min(calculate_distance_m(candidate["latitude"], candidate["longitude"], existing["latitude"], existing["longitude"]) for existing in du_selected_nodes)
if nearest_distance > best_distance:
best_distance = nearest_distance
best_candidate = candidate
if best_candidate is None:
break
du_selected_nodes.append(best_candidate)
du_used_ids.add(best_candidate["id"])
print(f"Placed DU{len(du_selected_nodes)} | Nearest distance: {best_distance:.2f}m")
# ============================================================
# Build DU Objects
# ============================================================
distributed_units = []
for i, node in enumerate(du_selected_nodes, start=1):
distributed_units.append({
"du_name": f"DU{i}",
"latitude": node["latitude"],
"longitude": node["longitude"],
"service": "DistributedUnit",
"capacity_bandwidth": config.DU_CAPACITY,
"capacity_ports": config.DU_PORTS
})
# ============================================================
# CU Configuration
# ============================================================
print("\n================================================")
print("Placing Centralised Unit...")
print("================================================")
# Compute geographic center of all RUs
center_lat = sum(ru["latitude"] for ru in radio_units) / len(radio_units)
center_lon = sum(ru["longitude"] for ru in radio_units) / len(radio_units)
# Find closest road node to center
best_cu_node = min(road_nodes, key=lambda node: calculate_distance_m(center_lat, center_lon, node["latitude"], node["longitude"]))
print(f"Placed CU1 at ({best_cu_node['latitude']}, {best_cu_node['longitude']})")
# ============================================================
# Build CU Object
# ============================================================
centralised_units = [{
"cu_name": "CU1",
"latitude": best_cu_node["latitude"],
"longitude": best_cu_node["longitude"],
"service": "CentralisedUnit",
"capacity_bandwidth": config.CU_CAPACITY,
"capacity_ports": config.CU_PORTS
}]
# ============================================================
# Export
# ============================================================
with open(config.RU_OUTPUT_FILE, "w") as f:
json.dump({"radio_units": radio_units}, f, indent=4)
print(f"Generated {len(radio_units)} Radio Units")
print(f"Saved to: {config.RU_OUTPUT_FILE}")
with open(config.DU_OUTPUT_FILE, "w") as f:
json.dump({"distributed_units": distributed_units}, f, indent=4)
print(f"Generated {len(distributed_units)} Distributed Units")
print(f"Saved to: {config.DU_OUTPUT_FILE}")
with open(config.CU_OUTPUT_FILE, "w") as f:
json.dump({"centralised_units": centralised_units}, f, indent=4)
print(f"Generated {len(centralised_units)} Centralised Unit")
print(f"Saved to: {config.CU_OUTPUT_FILE}")
# ============================================================
# Existing / New Split Configuration
# ============================================================
existing_center = random.choice(road_nodes)
existing_center_lat = existing_center["latitude"]
existing_center_lon = existing_center["longitude"]
print("\n================================================")
print("Generating Existing/New Infrastructure Split...")
print("================================================")
# ============================================================
# Select Existing RUs
# ============================================================
ru_candidates_existing = []
for ru in radio_units:
dist = calculate_distance_m(
existing_center_lat,
existing_center_lon,
ru["latitude"],
ru["longitude"]
)
if dist <= config.EXISTING_REGION_RADIUS_M:
ru_candidates_existing.append(ru)
# ------------------------------------------------------------
# Fallback if insufficient candidates
# ------------------------------------------------------------
if len(ru_candidates_existing) < config.NUM_EXISTING_RUS:
ru_candidates_existing = sorted(
radio_units,
key=lambda ru:
calculate_distance_m(
existing_center_lat,
existing_center_lon,
ru["latitude"],
ru["longitude"]
)
)
radio_units_existing = ru_candidates_existing[:config.NUM_EXISTING_RUS]
existing_ru_names = {
ru["ru_name"]
for ru in radio_units_existing
}
radio_units_new = [
ru for ru in radio_units
if ru["ru_name"] not in existing_ru_names
]
# ============================================================
# Select Existing DUs
# ============================================================
du_candidates_existing = []
for du in distributed_units:
dist = calculate_distance_m(
existing_center_lat,
existing_center_lon,
du["latitude"],
du["longitude"]
)
if dist <= config.EXISTING_REGION_RADIUS_M:
du_candidates_existing.append(du)
# ------------------------------------------------------------
# Fallback if insufficient candidates
# ------------------------------------------------------------
if len(du_candidates_existing) < config.NUM_EXISTING_DUS:
du_candidates_existing = sorted(
distributed_units,
key=lambda du:
calculate_distance_m(
existing_center_lat,
existing_center_lon,
du["latitude"],
du["longitude"]
)
)
distributed_units_existing = du_candidates_existing[:config.NUM_EXISTING_DUS]
existing_du_names = {
du["du_name"]
for du in distributed_units_existing
}
distributed_units_new = [
du for du in distributed_units
if du["du_name"] not in existing_du_names
]
# ============================================================
# Export Existing/New RUs
# ============================================================
with open(config.RU_EXISTING_FILE, "w") as f:
json.dump({"radio_units_existing": radio_units_existing}, f, indent=4)
with open(config.RU_NEW_FILE, "w") as f:
json.dump({"radio_units_new": radio_units_new}, f, indent=4)
print(f"Generated {len(radio_units_existing)} Existing RUs")
print(f"Generated {len(radio_units_new)} New RUs")
# ============================================================
# Export Existing/New DUs
# ============================================================
with open(config.DU_EXISTING_FILE, "w") as f:
json.dump({"distributed_units_existing": distributed_units_existing}, f, indent=4)
with open(config.DU_NEW_FILE, "w") as f:
json.dump({"distributed_units_new": distributed_units_new}, f, indent=4)
print(f"Generated {len(distributed_units_existing)} Existing DUs")
print(f"Generated {len(distributed_units_new)} New DUs")
if __name__ == "__main__":
generate_devices()