-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsimulation.py
More file actions
177 lines (149 loc) · 6.59 KB
/
simulation.py
File metadata and controls
177 lines (149 loc) · 6.59 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
import numpy as np
import matplotlib.pyplot as plt
from collections import deque
import random
import imageio.v2 as imageio
import os
# --- Simulation Configuration ---
NUM_TERMINALS = 50
SIM_AREA_SIZE = 100
JAMMER_CENTER = (SIM_AREA_SIZE / 2, SIM_AREA_SIZE / 2)
JAMMER_RADIUS = 25
MAX_MESH_RANGE = 20
# Styling
SATELLITE_LINK_GOOD_COLOR = 'green'
SATELLITE_LINK_JAMMED_COLOR = 'gray'
MESH_LINK_COLOR = 'blue'
TERMINAL_COLOR_GOOD = 'green'
TERMINAL_COLOR_JAMMED = 'red'
TERMINAL_COLOR_RELAY = 'purple'
DATA_PATH_COLOR = 'cyan'
DATA_PATH_WIDTH = 2
SAT_LINK_WIDTH = 0.5
MESH_LINK_WIDTH = 0.3
GIF_FILENAME = "vkp8_simulation.gif"
FPS = 5
class Terminal:
def __init__(self, id, x, y):
self.id = id
self.pos = np.array([x, y])
self.is_jammed = False
self.is_gateway = False # Can communicate directly with satellite
self.neighbors = [] # Neighbors for Mesh communication
def distance_to(self, other_terminal):
return np.linalg.norm(self.pos - other_terminal.pos)
def setup_terminals(num_terminals, area_size):
terminals = []
for i in range(num_terminals):
x = random.uniform(0, area_size)
y = random.uniform(0, area_size)
terminals.append(Terminal(i, x, y))
return terminals
def apply_jammer(terminals, jammer_center, jammer_radius):
for t in terminals:
dist_to_jammer = np.linalg.norm(t.pos - np.array(jammer_center))
if dist_to_jammer <= jammer_radius:
t.is_jammed = True
t.is_gateway = False
else:
t.is_jammed = False
t.is_gateway = True
def establish_mesh_links(terminals, max_mesh_range):
for i, t1 in enumerate(terminals):
t1.neighbors.clear()
for j, t2 in enumerate(terminals):
if i != j and t1.distance_to(t2) <= max_mesh_range:
t1.neighbors.append(t2)
def find_mesh_path(start_terminal, terminals):
"""
Finds the shortest path in the Mesh network using BFS.
Target: The first available gateway (un-jammed node).
"""
if start_terminal.is_gateway:
return [start_terminal]
queue = deque([(start_terminal, [start_terminal])])
visited = {start_terminal.id}
while queue:
current_terminal, path = queue.popleft()
if current_terminal.is_gateway:
return path
for neighbor in current_terminal.neighbors:
if neighbor.id not in visited:
visited.add(neighbor.id)
queue.append((neighbor, path + [neighbor]))
return None
def visualize_network_frame(ax, terminals, jammer_center, jammer_radius, data_path=None, frame_title=""):
ax.clear()
# Jammer Visualization
jammer_circle = plt.Circle(jammer_center, jammer_radius, color='red', alpha=0.1, label='Jamming Zone (EW)')
ax.add_artist(jammer_circle)
# Mesh Link Visualization
for t1 in terminals:
for t2 in t1.neighbors:
if t1.id < t2.id:
ax.plot([t1.pos[0], t2.pos[0]], [t1.pos[1], t2.pos[1]],
color=MESH_LINK_COLOR, linewidth=MESH_LINK_WIDTH, alpha=0.4)
# Terminal & Sat-Link Visualization
for t in terminals:
color = TERMINAL_COLOR_GOOD if t.is_gateway else TERMINAL_COLOR_JAMMED
ax.plot(t.pos[0], t.pos[1], 'o', color=color, markersize=7, zorder=5)
sat_link_color = SATELLITE_LINK_GOOD_COLOR if t.is_gateway else SATELLITE_LINK_JAMMED_COLOR
ax.plot([t.pos[0], t.pos[0]], [t.pos[1], t.pos[1] + 4],
color=sat_link_color, linestyle='--', linewidth=SAT_LINK_WIDTH, zorder=1)
# Data Path Visualization
if data_path:
for i in range(len(data_path) - 1):
t1 = data_path[i]
t2 = data_path[i+1]
ax.plot([t1.pos[0], t2.pos[0]], [t1.pos[1], t2.pos[1]],
color=DATA_PATH_COLOR, linewidth=DATA_PATH_WIDTH, zorder=10)
ax.plot(t1.pos[0], t1.pos[1], 'o', color=TERMINAL_COLOR_RELAY, markersize=9, markeredgecolor='black', zorder=11)
ax.plot(data_path[-1].pos[0], data_path[-1].pos[1], 'o', color=SATELLITE_LINK_GOOD_COLOR, markersize=9, markeredgecolor='black', zorder=11, label='Active Gateway')
ax.plot(data_path[0].pos[0], data_path[0].pos[1], 'o', color='gold', markersize=9, markeredgecolor='black', zorder=11, label='Jammed Source')
ax.set_title(frame_title, fontsize=12)
ax.set_xlabel('X Coordinate (Relative)')
ax.set_ylabel('Y Coordinate (Relative)')
ax.set_xlim(0, SIM_AREA_SIZE)
ax.set_ylim(0, SIM_AREA_SIZE + 5)
ax.set_aspect('equal')
ax.legend(loc='upper right', fontsize='small')
ax.grid(True, linestyle=':', alpha=0.5)
if __name__ == "__main__":
fig, ax = plt.subplots(figsize=(10, 10))
frames = []
print("Initializing VKP-8 Simulation...")
terminals = setup_terminals(NUM_TERMINALS, SIM_AREA_SIZE)
apply_jammer(terminals, JAMMER_CENTER, JAMMER_RADIUS)
establish_mesh_links(terminals, MAX_MESH_RANGE)
# Generate initial state frame
visualize_network_frame(ax, terminals, JAMMER_CENTER, JAMMER_RADIUS,
frame_title="VKP-8: Jammer Active / Vertical Links Blocked")
plt.tight_layout()
fig.canvas.draw()
image = np.frombuffer(fig.canvas.tostring_rgb(), dtype='uint8')
image = image.reshape(fig.canvas.get_width_height()[::-1] + (3,))
for _ in range(5): frames.append(image) # Hold initial frame
jammed_terminals = [t for t in terminals if t.is_jammed]
if jammed_terminals:
start_node = random.choice(jammed_terminals)
path_to_gateway = find_mesh_path(start_node, terminals)
if path_to_gateway:
print(f"Path found from Terminal {start_node.id} to Gateway {path_to_gateway[-1].id}")
# Animating path discovery
for i in range(1, len(path_to_gateway) + 1):
visualize_network_frame(ax, terminals, JAMMER_CENTER, JAMMER_RADIUS,
data_path=path_to_gateway[:i],
frame_title=f"VKP-8: Routing through Mesh (Step {i})")
plt.tight_layout()
fig.canvas.draw()
image = np.frombuffer(fig.canvas.tostring_rgb(), dtype='uint8')
image = image.reshape(fig.canvas.get_width_height()[::-1] + (3,))
frames.append(image)
# Hold final path
for _ in range(10): frames.append(image)
else:
print("Critical Failure: No path to Gateway found.")
print(f"Exporting GIF to {GIF_FILENAME}...")
imageio.mimsave(GIF_FILENAME, frames, fps=FPS)
print("Export Complete.")
plt.close(fig)