forked from RhynoW/Leo_Flood_Demo
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathleo_flood_demo_v3i.py
More file actions
1470 lines (1230 loc) · 47.8 KB
/
Copy pathleo_flood_demo_v3i.py
File metadata and controls
1470 lines (1230 loc) · 47.8 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
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
leo_flood_demo_v3i.py
----------------------------------------------------------------
LEO Walker-like Constellation Routing Demo
(v3h, Starlink + Kuiper + Motion + Resilience + Sparse/TinyLEO-like)
整合內容:
- starlink: dense Starlink-like shell
- kuiper : dense Kuiper-like shell + gateway / w_gateway
- sparse : 在 Starlink-like shell 上做 structural sparse
plane_stride=1, sat_stride=2, 只砍 sat index,不砍 plane
並用 BFS 尋找在 sparse 拓樸下可達的 dst
usage_map 在同一個 sparse 拓樸上估計
多模式共用:
- multi_constraint_cost 支援 queue proxy:
* 有 util_map -> 用實際 ρ 算 queue term
* 沒 util_map 但有 usage_map -> 用 usage_map 推 ρ 當 queue proxy
- throughput_experiment_multiflow:
* sparse 模式只選 sparse 拓樸下有路的 flows
* 內部 per-link queue 採簡單 tail-drop 上限 MAX_Q
參考 TinyLEO:在縮減星數的 sparse LEO 網路上仍維持可接受的資料面表現。
----------------------------------------------------------------
"""
import argparse
import heapq
import math
import random
import os
from dataclasses import dataclass, field
from pathlib import Path
from typing import Dict, Tuple, List, Optional, Set
import numpy as np
import matplotlib.pyplot as plt
# ============================================================
# 0. 型別別名與工具函式
# ============================================================
Node = Tuple[int, int]
LinkKey = Tuple[Node, Node]
UtilMap = Dict[LinkKey, float]
UsageMap = Dict[LinkKey, float]
FailedSet = Set[Node]
def link_key(a: Node, b: Node) -> LinkKey:
return (a, b) if a <= b else (b, a)
@dataclass
class StarlinkPreset:
M: int
N: int
altitude_km: float
inclination_deg: float
hotspot_ratio: float
hotspot_rho: float
p_arrival_list: List[float]
@dataclass
class KuiperPreset:
M: int
N: int
altitude_km: float
inclination_deg: float
hotspot_ratio: float
hotspot_rho: float
p_arrival_list: List[float]
gateways: List[Node]
STARLINK_LIKE = StarlinkPreset(
M=24,
N=22,
altitude_km=550.0,
inclination_deg=53.0,
hotspot_ratio=0.30,
hotspot_rho=0.95,
p_arrival_list=[0.02, 0.05, 0.08, 0.10, 0.12],
)
KUIPER_LIKE = KuiperPreset(
M=6,
N=11,
altitude_km=630.0,
inclination_deg=51.9,
hotspot_ratio=0.20,
hotspot_rho=0.90,
p_arrival_list=[0.02, 0.05, 0.08, 0.10],
gateways=[(0, 5), (3, 2)],
)
# ============================================================
# 1. Walker-like 星座建構 + 軌道運動
# ============================================================
class WalkerConstellation:
def __init__(self,
M: int = 6,
N: int = 11,
altitude_km: float = 550.0,
inclination_deg: float = 53.0,
allow_cross_seam: bool = True,
processing_delay_ms: float = 1.5):
self.M = M
self.N = N
self.altitude = altitude_km
self.inclination_deg = inclination_deg
self.inclination = math.radians(inclination_deg)
self.allow_cross_seam = allow_cross_seam
self.Re = 6371.0
self.r = self.Re + altitude_km
mu = 3.986004418e5 # km^3/s^2
self.mean_motion = math.sqrt(mu / (self.r ** 3))
self.SPEED_OF_LIGHT_KMS = 299792.458
self.processing_delay_ms = processing_delay_ms
self.positions: Dict[Node, Tuple[float, float, float]] = {}
self.neighbors: Dict[Node, List[Node]] = {}
self.link_base_delay: Dict[Tuple[Node, Node], float] = {}
self._build_positions()
self._build_topology_and_link_cache()
def get_sat_lat_lon(self, m: int, n: int, t: float = 0.0):
pos_t = self.positions_at_time(t)
x, y, z = pos_t[(m, n)]
lat, lon = eci_to_latlon(x, y, z)
return lat, lon
def _build_positions(self):
for m in range(self.M):
raan = 2 * math.pi * m / self.M
for n in range(self.N):
u = 2 * math.pi * n / self.N
x = self.r * (math.cos(raan) * math.cos(u)
- math.sin(raan) * math.sin(u) * math.cos(self.inclination))
y = self.r * (math.sin(raan) * math.cos(u)
+ math.cos(raan) * math.sin(u) * math.cos(self.inclination))
z = self.r * (math.sin(u) * math.sin(self.inclination))
self.positions[(m, n)] = (x, y, z)
def positions_at_time(self, t: float) -> Dict[Node, Tuple[float, float, float]]:
pos_t: Dict[Node, Tuple[float, float, float]] = {}
for m in range(self.M):
raan = 2 * math.pi * m / self.M
for n in range(self.N):
u0 = 2 * math.pi * n / self.N
u_t = u0 + self.mean_motion * t
x = self.r * (math.cos(raan) * math.cos(u_t)
- math.sin(raan) * math.sin(u_t) * math.cos(self.inclination))
y = self.r * (math.sin(raan) * math.cos(u_t)
+ math.cos(raan) * math.sin(u_t) * math.cos(self.inclination))
z = self.r * (math.sin(u_t) * math.sin(self.inclination))
pos_t[(m, n)] = (x, y, z)
return pos_t
def _build_topology_and_link_cache(self):
for m in range(self.M):
for n in range(self.N):
u: Node = (m, n)
nbrs: List[Node] = []
nbrs.append((m, (n - 1) % self.N))
nbrs.append((m, (n + 1) % self.N))
m_minus = (m - 1) % self.M
m_plus = (m + 1) % self.M
if self.allow_cross_seam:
nbrs.append((m_minus, n))
nbrs.append((m_plus, n))
else:
if not (m == 0 and m_minus == self.M - 1):
nbrs.append((m_minus, n))
if not (m == self.M - 1 and m_plus == 0):
nbrs.append((m_plus, n))
self.neighbors[u] = nbrs
for u, nbrs in self.neighbors.items():
for v in nbrs:
self.link_base_delay[(u, v)] = self._compute_base_delay(u, v)
def _compute_base_delay(self, a: Node, b: Node) -> float:
ax, ay, az = self.positions[a]
bx, by, bz = self.positions[b]
d = math.sqrt((ax - bx) ** 2 + (ay - by) ** 2 + (az - bz) ** 2)
propagation_ms = (d / self.SPEED_OF_LIGHT_KMS) * 1000.0
return propagation_ms + self.processing_delay_ms
def base_delay(self, a: Node, b: Node) -> float:
return self.link_base_delay[(a, b)]
def distance(self, a: Node, b: Node) -> float:
ax, ay, az = self.positions[a]
bx, by, bz = self.positions[b]
return math.sqrt((ax - bx) ** 2 + (ay - by) ** 2 + (az - bz) ** 2)
def all_nodes(self) -> List[Node]:
return list(self.positions.keys())
# ============================================================
# 2. RoutingConfig / queueing
# ============================================================
@dataclass
class RoutingConfig:
w_delay: float = 1.0
w_queue: float = 0.5
w_usage: float = 0.5
w_contact: float = 0.1
# gateway 相關只在 kuiper 用
w_gateway: float = 0.0
gateways: Optional[List[Node]] = field(default=None)
node_to_gw_dist: Optional[Dict[Node, float]] = field(default=None)
delay_norm_factor: float = 10.0
queue_norm_factor: float = 5.0
usage_norm_factor: float = 10.0
contact_norm_factor: float = 10000.0
service_rate_per_ms: float = 1.0
use_queue_proxy_in_multi: bool = True
def queueing_delay(utilization: float, service_rate_per_ms: float = 1.0) -> float:
rho = max(0.0, min(0.98, utilization))
return (rho / (1.0 - rho)) / service_rate_per_ms
def sample_utilization_map(constellation: WalkerConstellation,
rng: random.Random,
hotspot_ratio: float = 0.15,
hotspot_rho: float = 0.90) -> UtilMap:
util: UtilMap = {}
for a in constellation.all_nodes():
for b in constellation.neighbors[a]:
k = link_key(a, b)
if k in util:
continue
if rng.random() < hotspot_ratio:
util[k] = hotspot_rho + rng.uniform(-0.05, 0.05)
else:
util[k] = rng.uniform(0.05, 0.40)
return util
def dynamic_weight(constellation: WalkerConstellation,
a: Node,
b: Node,
util_map: UtilMap,
config: RoutingConfig) -> float:
base = constellation.base_delay(a, b)
rho = util_map[link_key(a, b)]
return base + queueing_delay(rho, service_rate_per_ms=config.service_rate_per_ms)
# ============================================================
# 3. Static / Load-aware Dijkstra(支援 failed)
# ============================================================
def dijkstra_static(constellation: WalkerConstellation,
src: Node,
dst: Node,
failed: Optional[FailedSet] = None):
dist = {n: math.inf for n in constellation.all_nodes()}
prev: Dict[Node, Optional[Node]] = {n: None for n in constellation.all_nodes()}
dist[src] = 0.0
pq: List[Tuple[float, Node]] = [(0.0, src)]
while pq:
d, u = heapq.heappop(pq)
if u == dst:
break
if d > dist[u]:
continue
if failed and u in failed:
continue
for v in constellation.neighbors[u]:
if failed and v in failed:
continue
nd = d + constellation.base_delay(u, v)
if nd < dist[v]:
dist[v] = nd
prev[v] = u
heapq.heappush(pq, (nd, v))
if dist[dst] == math.inf:
return None, math.inf
path: List[Node] = []
cur: Optional[Node] = dst
while cur is not None:
path.append(cur)
cur = prev[cur]
path.reverse()
return path, dist[dst]
def estimate_link_usage(constellation: WalkerConstellation,
sd_pairs: Optional[List[Tuple[Node, Node]]] = None,
trials: int = 100,
seed: int = 123,
failed: Optional[FailedSet] = None) -> UsageMap:
rng = random.Random(seed)
usage: UsageMap = {}
nodes = constellation.all_nodes()
if sd_pairs is None:
sd_pairs = []
for _ in range(trials):
s = rng.choice(nodes)
d = rng.choice(nodes)
if s != d:
sd_pairs.append((s, d))
for (src, dst) in sd_pairs:
path, _ = dijkstra_static(constellation, src, dst, failed=failed)
if path is None:
continue
for a, b in zip(path[:-1], path[1:]):
k = link_key(a, b)
usage[k] = usage.get(k, 0.0) + 1.0
return usage
def load_aware_weight(constellation: WalkerConstellation,
a: Node,
b: Node,
usage_map: UsageMap,
lambda_weight: float = 1.0) -> float:
base = constellation.base_delay(a, b)
u = usage_map.get(link_key(a, b), 0.0)
return base + lambda_weight * u
def dijkstra_load_aware(constellation: WalkerConstellation,
src: Node,
dst: Node,
usage_map: UsageMap,
lambda_weight: float = 1.0,
failed: Optional[FailedSet] = None):
dist = {n: math.inf for n in constellation.all_nodes()}
prev: Dict[Node, Optional[Node]] = {n: None for n in constellation.all_nodes()}
dist[src] = 0.0
pq: List[Tuple[float, Node]] = [(0.0, src)]
while pq:
d, u = heapq.heappop(pq)
if u == dst:
break
if d > dist[u]:
continue
if failed and u in failed:
continue
for v in constellation.neighbors[u]:
if failed and v in failed:
continue
nd = d + load_aware_weight(constellation, u, v, usage_map, lambda_weight)
if nd < dist[v]:
dist[v] = nd
prev[v] = u
heapq.heappush(pq, (nd, v))
if dist[dst] == math.inf:
return None, math.inf
path: List[Node] = []
cur: Optional[Node] = dst
while cur is not None:
path.append(cur)
cur = prev[cur]
path.reverse()
return path, dist[dst]
# ============================================================
# 5. Multi-constraint cost(含 queue proxy + gateway)
# ============================================================
def est_queue_delay_ms(rho: float, config: RoutingConfig) -> float:
return queueing_delay(rho, service_rate_per_ms=config.service_rate_per_ms)
def est_contact_quality(constellation: WalkerConstellation, a: Node, b: Node) -> float:
return constellation.distance(a, b)
def est_gateway_distance(constellation: WalkerConstellation,
node: Node,
gateways: Optional[List[Node]],
node_to_gw_dist: Optional[Dict[Node, float]] = None) -> float:
if not gateways:
return 0.0
if node_to_gw_dist is not None:
return node_to_gw_dist[node]
return min(constellation.distance(node, g) for g in gateways)
def multi_constraint_cost(constellation: WalkerConstellation,
a: Node,
b: Node,
config: RoutingConfig,
util_map: Optional[UtilMap] = None,
usage_map: Optional[UsageMap] = None) -> float:
base = constellation.base_delay(a, b)
delay_norm = base / config.delay_norm_factor
# queue term(可用 util_map 或 usage_map 作 proxy)
rho = 0.0
if config.use_queue_proxy_in_multi:
if util_map is not None:
rho = util_map.get(link_key(a, b), 0.1)
elif usage_map is not None:
u = usage_map.get(link_key(a, b), 0.0)
rho = min(0.9, u / (config.usage_norm_factor * 2.0))
if rho > 0.0:
q_ms = est_queue_delay_ms(rho, config)
queue_norm = q_ms / config.queue_norm_factor
else:
queue_norm = 0.0
# usage term
if usage_map is not None:
u = usage_map.get(link_key(a, b), 0.0)
usage_norm = u / config.usage_norm_factor
else:
usage_norm = 0.0
# geometry term
d = est_contact_quality(constellation, a, b)
contact_norm = d / config.contact_norm_factor
# gateway term(只在 kuiper 用)
if config.gateways:
d_gw = est_gateway_distance(
constellation, b,
config.gateways,
node_to_gw_dist=config.node_to_gw_dist
)
gateway_norm = d_gw / config.contact_norm_factor
else:
gateway_norm = 0.0
cost = (config.w_delay * delay_norm +
config.w_queue * queue_norm +
config.w_usage * usage_norm +
config.w_contact * contact_norm +
config.w_gateway * gateway_norm)
return cost
def dijkstra_multi(constellation: WalkerConstellation,
src: Node,
dst: Node,
config: RoutingConfig,
util_map: Optional[UtilMap] = None,
usage_map: Optional[UsageMap] = None,
failed: Optional[FailedSet] = None):
dist = {n: math.inf for n in constellation.all_nodes()}
prev: Dict[Node, Optional[Node]] = {n: None for n in constellation.all_nodes()}
dist[src] = 0.0
pq: List[Tuple[float, Node]] = [(0.0, src)]
while pq:
d, u = heapq.heappop(pq)
if u == dst:
break
if d > dist[u]:
continue
if failed and u in failed:
continue
for v in constellation.neighbors[u]:
if failed and v in failed:
continue
nd = d + multi_constraint_cost(
constellation, u, v, config,
util_map=util_map,
usage_map=usage_map
)
if nd < dist[v]:
dist[v] = nd
prev[v] = u
heapq.heappush(pq, (nd, v))
if dist[dst] == math.inf:
return None, math.inf
path: List[Node] = []
cur: Optional[Node] = dst
while cur is not None:
path.append(cur)
cur = prev[cur]
path.reverse()
return path, dist[dst]
# ============================================================
# 6. Directed Flood
# ============================================================
def direction_cos(constellation: WalkerConstellation,
current: Node,
candidate: Node,
dst: Node) -> float:
cx, cy, cz = constellation.positions[current]
nx, ny, nz = constellation.positions[candidate]
dx, dy, dz = constellation.positions[dst]
v1 = (nx - cx, ny - cy, nz - cz)
v2 = (dx - cx, dy - cy, dz - cz)
n1 = math.sqrt(sum(c * c for c in v1))
n2 = math.sqrt(sum(c * c for c in v2))
if n1 == 0 or n2 == 0:
return 0.0
return sum(a * b for a, b in zip(v1, v2)) / (n1 * n2)
def directed_flood_multi(constellation: WalkerConstellation,
src: Node,
dst: Node,
util_map: UtilMap,
config: RoutingConfig,
cos_threshold: float = -0.2,
usage_map: Optional[UsageMap] = None,
failed: Optional[FailedSet] = None):
dist: Dict[Node, float] = {src: 0.0}
prev: Dict[Node, Optional[Node]] = {src: None}
pq: List[Tuple[float, Node]] = [(0.0, src)]
while pq:
d, u = heapq.heappop(pq)
if u == dst:
break
if d > dist.get(u, math.inf):
continue
if failed and u in failed:
continue
dist_u_dst = constellation.distance(u, dst)
for v in constellation.neighbors[u]:
if failed and v in failed:
continue
if v != dst:
dist_v_dst = constellation.distance(v, dst)
if dist_v_dst >= dist_u_dst:
if direction_cos(constellation, u, v, dst) < cos_threshold:
continue
nd = d + multi_constraint_cost(
constellation, u, v, config,
util_map=util_map,
usage_map=usage_map
)
if nd < dist.get(v, math.inf):
dist[v] = nd
prev[v] = u
heapq.heappush(pq, (nd, v))
if dst not in dist:
return None, math.inf
path: List[Node] = []
cur: Optional[Node] = dst
while cur is not None:
path.append(cur)
cur = prev[cur]
path.reverse()
return path, dist[dst]
def path_cost_on_map(constellation: WalkerConstellation,
path: Optional[List[Node]],
util_map: UtilMap,
config: RoutingConfig) -> float:
if path is None:
return math.inf
total = 0.0
for a, b in zip(path[:-1], path[1:]):
total += dynamic_weight(constellation, a, b, util_map, config)
return total
# ============================================================
# 7. Monte Carlo
# ============================================================
def monte_carlo(constellation: WalkerConstellation,
src: Node,
dst: Node,
config: RoutingConfig,
usage_map: UsageMap,
trials: int = 500,
seed: int = 42,
hotspot_ratio: float = 0.15,
hotspot_rho: float = 0.90,
cos_threshold: float = -0.2,
base_failed: Optional[FailedSet] = None):
rng = random.Random(seed)
static_path, static_predicted_cost = dijkstra_static(
constellation, src, dst, failed=base_failed
)
la_path, la_predicted_cost = dijkstra_load_aware(
constellation, src, dst, usage_map, lambda_weight=1.0,
failed=base_failed
)
mc_path, mc_agg_cost = dijkstra_multi(
constellation, src, dst,
config=config,
util_map=None,
usage_map=usage_map,
failed=base_failed,
)
flood_costs = []
static_actual_costs = []
la_actual_costs = []
mc_actual_costs = []
flood_success = 0
for _ in range(trials):
util = sample_utilization_map(
constellation, rng,
hotspot_ratio=hotspot_ratio,
hotspot_rho=hotspot_rho,
)
flood_path, flood_cost = directed_flood_multi(
constellation, src, dst,
util_map=util,
config=config,
cos_threshold=cos_threshold,
usage_map=usage_map,
failed=base_failed,
)
if flood_path is not None:
flood_success += 1
else:
# 保險起見,確保 cost 真的是 inf,方便辨識
flood_cost = math.inf
static_actual = path_cost_on_map(constellation, static_path, util, config)
la_actual = path_cost_on_map(constellation, la_path, util, config)
mc_actual = path_cost_on_map(constellation, mc_path, util, config)
flood_costs.append(flood_cost)
static_actual_costs.append(static_actual)
la_actual_costs.append(la_actual)
mc_actual_costs.append(mc_actual)
flood_arr = np.array(flood_costs)
static_arr = np.array(static_actual_costs)
la_arr = np.array(la_actual_costs)
mc_arr = np.array(mc_actual_costs)
flood_success_ratio = flood_success / trials if trials > 0 else 0.0
return {
"static_path": static_path,
"static_predicted_cost": static_predicted_cost,
"la_path": la_path,
"la_predicted_cost": la_predicted_cost,
"mc_path": mc_path,
"mc_agg_cost": mc_agg_cost,
"static_actual_arr": static_arr,
"la_actual_arr": la_arr,
"mc_actual_arr": mc_arr,
"flood_arr": flood_arr,
"flood_score_arr": flood_arr[np.isfinite(flood_arr)],
"flood_success_ratio": flood_success_ratio,
}
# ============================================================
# 8. CDF 視覺化
# ============================================================
def plot_four_cost_cdf(stats, mode: str, show=True, save_prefix=None):
static_arr = stats["static_actual_arr"]
la_arr = stats["la_actual_arr"]
mc_arr = stats["mc_actual_arr"]
flood_arr = stats["flood_arr"]
plt.figure(figsize=(7, 5))
def plot_cdf(arr, label, color):
arr_sorted = np.sort(arr)
cdf = np.linspace(0, 1, len(arr_sorted))
plt.plot(arr_sorted, cdf, label=label, color=color)
plot_cdf(static_arr, "Static", "tab:blue")
plot_cdf(la_arr, "Load-aware", "tab:green")
plot_cdf(mc_arr, "Multi-constraint", "tab:red")
plot_cdf(flood_arr, "Flood (MC cost)", "tab:orange")
plt.xlabel("End-to-end Latency (ms)")
plt.ylabel("CDF")
plt.title(f"Static / Load-aware / Multi-constraint / Flood ({mode})")
plt.legend()
plt.grid(True, alpha=0.3)
if save_prefix is not None:
plt.savefig(f"{save_prefix}_4cdf.png", dpi=150)
if show:
plt.show()
else:
plt.close()
# ============================================================
# 9. Throughput 模擬
# ============================================================
def build_link_index(constellation: WalkerConstellation):
link_to_idx: Dict[Tuple[Node, Node], int] = {}
idx_to_link: List[Tuple[Node, Node]] = []
idx = 0
for u in constellation.all_nodes():
for v in constellation.neighbors[u]:
link_to_idx[(u, v)] = idx
idx_to_link.append((u, v))
idx += 1
return link_to_idx, idx_to_link
def simulate_throughput_multiflow(constellation: WalkerConstellation,
paths: List[Optional[List[Node]]],
slots: int = 5000,
p_arrival: float = 0.05,
link_capacity: int = 1,
seed: int = 777) -> float:
rng = random.Random(seed)
link_to_idx, idx_to_link = build_link_index(constellation)
n_links = len(idx_to_link)
q = [0 for _ in range(n_links)]
MAX_Q = 1000
flows: List[List[int]] = []
for path in paths:
if path is None or len(path) < 2:
continue
hop_idx: List[int] = []
for u, v in zip(path[:-1], path[1:]):
hop_idx.append(link_to_idx[(u, v)])
if hop_idx:
flows.append(hop_idx)
if not flows:
return 0.0
delivered = 0
for _ in range(slots):
for hop_idx in flows:
if rng.random() < p_arrival:
first_link = hop_idx[0]
if q[first_link] < MAX_Q:
q[first_link] += 1
send_count = [0 for _ in range(n_links)]
recv_to_link: List[List[int]] = [[] for _ in range(n_links)]
for hop_idx in flows:
for i, link_id in enumerate(hop_idx):
can_send = min(q[link_id] - send_count[link_id], link_capacity)
if can_send <= 0:
continue
send_count[link_id] += can_send
if i < len(hop_idx) - 1:
next_link = hop_idx[i + 1]
recv_to_link[next_link].append(can_send)
else:
delivered += can_send
for link_id in range(n_links):
q[link_id] -= send_count[link_id]
if recv_to_link[link_id]:
q[link_id] += sum(recv_to_link[link_id])
if q[link_id] > MAX_Q:
q[link_id] = MAX_Q
return delivered / float(slots)
def throughput_experiment_multiflow(constellation: WalkerConstellation,
src_dst_pairs: List[Tuple[Node, Node]],
usage_map: UsageMap,
config: RoutingConfig,
p_arrival_list=(0.02, 0.05, 0.08, 0.10),
slots: int = 5000,
seed: int = 999,
base_failed: Optional[FailedSet] = None):
rng = random.Random(seed)
static_paths: List[Optional[List[Node]]] = []
la_paths: List[Optional[List[Node]]] = []
flood_paths: List[Optional[List[Node]]] = []
flood_success = 0
total_flows = len(src_dst_pairs)
for (src, dst) in src_dst_pairs:
sp, _ = dijkstra_static(constellation, src, dst, failed=base_failed)
static_paths.append(sp)
lap, _ = dijkstra_load_aware(constellation, src, dst, usage_map,
lambda_weight=1.0,
failed=base_failed)
la_paths.append(lap)
util = sample_utilization_map(constellation, rng,
hotspot_ratio=0.30,
hotspot_rho=0.95)
fp, _ = directed_flood_multi(
constellation, src, dst,
util_map=util,
config=config,
cos_threshold=-0.2,
usage_map=usage_map,
failed=base_failed,
)
if fp is not None and len(fp) >= 2:
flood_success += 1
else:
fp = None
flood_paths.append(fp)
results = {
"p_arrival": [],
"static": [],
"load_aware": [],
"flood": [],
"flood_success_rate": flood_success / total_flows if total_flows > 0 else 0.0,
}
for p in p_arrival_list:
thr_static = simulate_throughput_multiflow(
constellation, static_paths, slots=slots,
p_arrival=p, link_capacity=1, seed=rng.randint(0, 10**9)
)
thr_la = simulate_throughput_multiflow(
constellation, la_paths, slots=slots,
p_arrival=p, link_capacity=1, seed=rng.randint(0, 10**9)
)
thr_flood = simulate_throughput_multiflow(
constellation, flood_paths, slots=slots,
p_arrival=p, link_capacity=1, seed=rng.randint(0, 10**9)
)
results["p_arrival"].append(p)
results["static"].append(thr_static)
results["load_aware"].append(thr_la)
results["flood"].append(thr_flood)
return results
def plot_throughput(results, mode: str, show=True, save_prefix=None):
p = np.array(results["p_arrival"])
s = np.array(results["static"])
la = np.array(results["load_aware"])
f = np.array(results["flood"])
plt.figure(figsize=(6, 4))
plt.plot(p, s, "-o", label="Static", color="tab:blue")
plt.plot(p, la, "-o", label="Load-aware", color="tab:green")
plt.plot(p, f, "-o", label="Flood", color="tab:orange")
plt.xlabel("Arrival probability per slot (per-flow)")
plt.ylabel("Throughput (pkts/slot total)")
plt.title(f"Throughput vs Arrival Rate ({mode}, multi-flow)")
plt.grid(True, alpha=0.3)
plt.legend()
if save_prefix is not None:
plt.savefig(f"{save_prefix}_throughput.png", dpi=150)
if show:
plt.show()
else:
plt.close()
# ============================================================
# 10. Ground tracks & resilience(略,保持原 v3h 寫法)
# ============================================================
def eci_to_latlon(x: float, y: float, z: float) -> Tuple[float, float]:
r = math.sqrt(x*x + y*y + z*z)
lat = math.asin(z / r)
lon = math.atan2(y, x)
return math.degrees(lat), math.degrees(lon)
def simulate_satellite_tracks(constellation: WalkerConstellation,
nodes: List[Node],
t_start: float = 0.0,
t_end: float = 2 * 3600.0,
dt: float = 60.0):
times = np.arange(t_start, t_end + dt, dt)
tracks: Dict[Node, Dict[str, List[float]]] = {}
for node in nodes:
tracks[node] = {"t": [], "lat": [], "lon": []}
for t in times:
pos_t = constellation.positions_at_time(t)
for node in nodes:
x, y, z = pos_t[node]
lat, lon = eci_to_latlon(x, y, z)
tracks[node]["t"].append(t)
tracks[node]["lat"].append(lat)
tracks[node]["lon"].append(lon)
return tracks
def plot_satellite_tracks_2d(tracks: Dict[Node, Dict[str, List[float]]],
mode: str,
show=True,
save_prefix: Optional[str] = None):
plt.figure(figsize=(7, 4))
for node, data in tracks.items():
lats = data["lat"]
lons = data["lon"]
plt.plot(lons, lats, label=f"{node}")
plt.xlabel("Longitude (deg)")
plt.ylabel("Latitude (deg)")
plt.title(f"Sub-satellite Ground Tracks ({mode})")
plt.grid(True, alpha=0.3)
plt.legend(fontsize=8)
if save_prefix is not None:
Path(os.path.dirname(save_prefix)).mkdir(parents=True, exist_ok=True)
plt.savefig(f"{save_prefix}_tracks.png", dpi=150)
if show:
plt.show()
else:
plt.close()
def sample_failed_satellites(constellation: WalkerConstellation,
fail_ratio: float,
rng: random.Random,
exclude_nodes: Optional[List[Node]] = None,
base_failed: Optional[FailedSet] = None) -> FailedSet:
base = set(base_failed) if base_failed else set()
nodes = [n for n in constellation.all_nodes() if n not in base]
if exclude_nodes:
ex = set(exclude_nodes)
nodes = [n for n in nodes if n not in ex]
k = int(len(nodes) * fail_ratio)
if k <= 0:
return base
return base | set(rng.sample(nodes, k))
def resilience_single_pair(constellation: WalkerConstellation,
src: Node,
dst: Node,
config: RoutingConfig,
usage_map: UsageMap,
fail_ratio_list=(0.0, 0.05, 0.10, 0.20, 0.30),
trials_per_ratio: int = 100,
seed: int = 2026,
hotspot_ratio: float = 0.30,
hotspot_rho: float = 0.95,
# ① 放寬 cos_threshold:讓 Flood 的幾何過濾不那麼嚴苛
cos_threshold: float = -0.5,
base_failed: Optional[FailedSet] = None):
rng = random.Random(seed)
results = {
"fail_ratio": [],
"connect_prob": [],
"avg_latency": [],
"median_latency": [],
}