Repository navigation
Expand file tree
/
Copy pathsimulation.py
More file actions
355 lines (287 loc) · 13.9 KB
/
Copy pathsimulation.py
File metadata and controls
355 lines (287 loc) · 13.9 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
"""
Controle da simulação dos roteadores (play / próximo pacote / stop / voltar no tempo).
Refatoração da parte de simulação do MainFrame.java e do CheckpointController.java
do GraphicalDebugger original. A thread com sleep() do Java foi trocada por um
QTimer, que roda no laço de eventos do Qt e pode atualizar a interface com segurança.
"""
from PySide6.QtCore import QObject, QTimer, Signal
from MPSoCConfig import MPSoCConfig
# Velocidade (slider 0-100) acima da qual os roteadores não são redesenhados,
# para avançar o mais rápido possível
MAX_REPAINT_SPEED = 98
# Pacotes processados por passo do timer quando está sem redesenhar
FAST_BATCH_SIZE = 200
# No "voltar no tempo", só os últimos pacotes são desenhados
GO_REPAINT_LAST_PACKETS = 50
# Acompanhando um traffic_router.txt que ainda está sendo gravado: intervalo
# entre as tentativas de ler novas linhas quando o arquivo chega ao fim
FOLLOW_POLL_MS = 250
# Lado da malha de onde vem o pacote que entra por cada porta
_PORT_SIDES = {
MPSoCConfig.NORTH0: "N", MPSoCConfig.NORTH1: "N", MPSoCConfig.SOUTH0: "S", MPSoCConfig.SOUTH1: "S",
MPSoCConfig.EAST0: "E", MPSoCConfig.EAST1: "E", MPSoCConfig.WEST0: "W", MPSoCConfig.WEST1: "W",
}
class CheckpointController:
"""
Divide a simulação em janelas de tempo. Ao fim de cada janela a taxa de uso
dos enlaces é recalculada (checkpoint_reached).
"""
def __init__(self, clock_period_ns, checkpoint_reached, window_size_ms=0.5):
self.clock_period_ns = clock_period_ns
self.checkpoint_reached = checkpoint_reached
self.window_size_ms = window_size_ms
self.reset()
def reset(self):
self.window_init_ms = 0.0
self.current_time_ms = 0.0
def set_time(self, time_in_ticks):
self.current_time_ms = ticks_to_ms(time_in_ticks, self.clock_period_ns)
if self.current_time_ms - self.window_init_ms > self.window_size_ms:
self.window_init_ms = self.current_time_ms
self.checkpoint_reached()
def get_window_size_in_ns(self):
return self.window_size_ms * 1_000_000
def ticks_to_ms(ticks, clock_period_ns):
return ticks * clock_period_ns / 1_000_000
# Porta de entrada -> (seta no roteador atual, seta no vizinho de onde o pacote veio)
_INPUT_ARROWS = {
MPSoCConfig.EAST0: (MPSoCConfig.EAST_IN_HIGH, MPSoCConfig.WEST_OUT_HIGH),
MPSoCConfig.EAST1: (MPSoCConfig.EAST_IN_LOW, MPSoCConfig.WEST_OUT_LOW),
MPSoCConfig.NORTH0: (MPSoCConfig.NORTH_IN_HIGH, MPSoCConfig.SOUTH_OUT_HIGH),
MPSoCConfig.NORTH1: (MPSoCConfig.NORTH_IN_LOW, MPSoCConfig.SOUTH_OUT_LOW),
MPSoCConfig.WEST0: (MPSoCConfig.WEST_IN_HIGH, MPSoCConfig.EAST_OUT_HIGH),
MPSoCConfig.WEST1: (MPSoCConfig.WEST_IN_LOW, MPSoCConfig.EAST_OUT_LOW),
MPSoCConfig.SOUTH0: (MPSoCConfig.SOUTH_IN_HIGH, MPSoCConfig.NORTH_OUT_HIGH),
MPSoCConfig.SOUTH1: (MPSoCConfig.SOUTH_IN_LOW, MPSoCConfig.NORTH_OUT_LOW),
}
class SimulationController(QObject):
"""Reproduz os pacotes de traffic_router.txt sobre a matriz de roteadores."""
# Tempo (em ticks) do último pacote processado
time_changed = Signal(int)
# Último pacote processado (PacketInformation)
packet_changed = Signal(object)
# Play/stop mudou (True = rodando)
running_changed = Signal(bool)
# Fim do traffic_router.txt
finished = Signal()
# Pacote com serviço que não existe no services.cfg
unknown_service = Signal(object)
# Modo "follow": fim do arquivo alcançado, esperando novas linhas (True) ou voltaram a chegar (False)
waiting_for_data = Signal(bool)
def __init__(self, mpsoc_config, mpsoc_information, router_matrix, parent=None):
super().__init__(parent)
self.mpsoc_config = mpsoc_config
self.mpsoc_information = mpsoc_information
self.router_matrix = router_matrix
# Função (packet -> bool) usada pelo filtro de serviços/PEs; None = todos
self.packet_filter = None
self.speed = MAX_REPAINT_SPEED
self.running = False
# Roteadores de destino dos pacotes que saíram de um PE e ainda não
# chegaram; enquanto houver algum, as setas pintadas não são apagadas
self.unfinished_packets = []
# "Print Router Total Link Usage": roteador (-1 = desligado) e o que imprimir
self.link_usage_router = -1
self.print_link_usage = True
self.checkpoint = CheckpointController(mpsoc_config.clock_period_in_ns, self.checkpoint_reached)
self.timer = QTimer(self)
self.timer.timeout.connect(self._play_step)
# Acompanhar um traffic_router.txt que ainda está sendo gravado
self.follow = False
self.waiting = False
# ==========================================
# CONTROLES
# ==========================================
def set_speed(self, speed):
"""Velocidade de 0 (parado) a 100 (máxima, sem redesenhar as setas)."""
self.speed = speed
if self.running:
self.timer.setInterval(self._interval())
def _interval(self):
if self.waiting:
return FOLLOW_POLL_MS
return max(0, 400 - self.speed * 4)
def set_follow(self, follow):
"""Em vez de parar no fim do arquivo, espera o simulador gravar mais pacotes."""
self.follow = follow
self.mpsoc_information.read_traffic.follow = follow
if not follow:
self._set_waiting(False)
def _set_waiting(self, waiting):
if waiting == self.waiting:
return
self.waiting = waiting
if self.running:
self.timer.setInterval(self._interval())
self.waiting_for_data.emit(waiting)
def play(self):
if self.running:
return
self.running = True
self.timer.start(self._interval())
self.running_changed.emit(True)
def stop(self):
if not self.running:
return
self.running = False
self.timer.stop()
self.running_changed.emit(False)
def step(self):
"""Processa um único pacote, sempre redesenhando."""
return self.next_packet(repaint=True)
def _play_step(self):
if self.speed == 0:
return
if self.speed > MAX_REPAINT_SPEED:
# Modo rápido: vários pacotes por passo e sem desenhar as setas
self.unfinished_packets.clear()
for _ in range(FAST_BATCH_SIZE):
if self.next_packet(repaint=False) == -1 or not self.running:
return
else:
self.next_packet(repaint=True)
def go_to_time(self, desired_time):
"""
Volta (ou avança) a simulação até o tempo informado, em ticks.
Só é possível ir até o último pacote já lido. Gera ValueError se o
tempo for inválido.
"""
packet_counter = self.mpsoc_information.get_packet_counter_by_time(desired_time)
if packet_counter == -1:
raise ValueError(f"Invalid time: {desired_time}")
self.stop()
self.mpsoc_information.initialize_pe_information()
self.checkpoint.reset()
self.reset_graphical_path()
time = 0
while packet_counter > 0:
time = self.next_packet(packet_counter <= GO_REPAINT_LAST_PACKETS, desired_time)
if time == -1 or time > desired_time:
break
packet_counter -= 1
self.time_changed.emit(max(time, 0))
def reset_graphical_path(self):
self.unfinished_packets.clear()
self.router_matrix.reset_routers()
# ==========================================
# PROCESSAMENTO DOS PACOTES
# ==========================================
def next_packet(self, repaint=True, limit_time=0):
"""Processa o próximo pacote. Retorna o tempo dele ou -1 no fim do arquivo."""
packet = self.mpsoc_information.get_next_packet(self.packet_filter, limit_time)
if packet is None:
if self.follow:
# O simulador ainda pode gravar mais pacotes: continua rodando
self._set_waiting(True)
return -1
self.router_matrix.reset_routers()
self.stop()
self.finished.emit()
return -1
self._set_waiting(False)
if packet.service not in self.mpsoc_config.services_hash:
self.stop()
self.unknown_service.emit(packet)
self.checkpoint.set_time(packet.time)
if repaint:
self.repaint_router(packet)
self.packet_changed.emit(packet)
self.time_changed.emit(packet.time)
return packet.time
def repaint_router(self, packet):
"""Pinta o caminho do pacote: seta de entrada no roteador e de saída no vizinho."""
if packet.input_port in (MPSoCConfig.LOCAL0, MPSoCConfig.LOCAL1):
# Pacote novo saindo do PE: apaga o caminho anterior se nenhum
# outro pacote estiver em trânsito
if not self.unfinished_packets:
self.router_matrix.reset_routers()
# Destinos fora da malha (ex.: periféricos) nunca "chegam", então não são aguardados
if 0 <= packet.target_router < self.mpsoc_config.get_pe_number():
self.unfinished_packets.append(packet.target_router)
self.paint_hop(packet.router_address, packet.input_port, packet.target_router)
# Pacote chegou ao destino
if packet.router_address == packet.target_router and packet.router_address in self.unfinished_packets:
self.unfinished_packets.remove(packet.router_address)
def paint_hop(self, address, port, target):
"""Seta de entrada no roteador (e de saída no vizinho de onde o pacote veio)."""
router = self.router_matrix.get_router_by_address(address)
if router is None:
return
if port in _INPUT_ARROWS:
local_arrow, neighbor_arrow = _INPUT_ARROWS[port]
neighbors = self.mpsoc_information.neighbors
if port in (MPSoCConfig.NORTH0, MPSoCConfig.NORTH1):
neighbor_address = neighbors.get_vizinho_cima(address)
elif port in (MPSoCConfig.SOUTH0, MPSoCConfig.SOUTH1):
neighbor_address = neighbors.get_vizinho_baixo(address)
elif port in (MPSoCConfig.EAST0, MPSoCConfig.EAST1):
neighbor_address = neighbors.get_vizinho_direita(address)
else:
neighbor_address = neighbors.get_vizinho_esquerda(address)
neighbor = self.router_matrix.get_router_by_address(neighbor_address)
if neighbor is not None:
neighbor.paint_arrow(neighbor_arrow)
elif neighbor_address == -1 and port in _PORT_SIDES:
# Veio de fora da malha: marca o periférico, se o YAML não o declarou
side = _PORT_SIDES[port]
if side not in router.peripherals:
router.set_peripheral(side, "Peripheral")
elif port in (MPSoCConfig.LOCAL0, MPSoCConfig.LOCAL1):
local_arrow = MPSoCConfig.LOCAL_IN
else:
return
router.paint_arrow(local_arrow)
if address == target:
router.paint_arrow(MPSoCConfig.LOCAL_OUT)
def show_path(self, hops, target, highlight=None):
"""
Mostra na malha o caminho de um pacote já analisado: `hops` são
(roteador, porta de entrada) na ordem; `highlight` recebe a moldura.
Para a simulação para o desenho não ser apagado pelo próximo pacote.
"""
self.stop()
self.reset_graphical_path()
for address, port in hops:
self.paint_hop(address, port, target)
if highlight is not None:
router = self.router_matrix.get_router_by_address(highlight)
if router is not None:
router.set_highlight(True)
# ==========================================
# TAXA DE USO DOS ENLACES
# ==========================================
def checkpoint_reached(self):
"""Atualiza o percentual de uso dos enlaces de todos os roteadores."""
max_throughput_per_window = self.checkpoint.get_window_size_in_ns() / self.mpsoc_config.clock_period_in_ns
for address in range(self.mpsoc_config.get_pe_number()):
router_info = self.mpsoc_information.get_router_information(address)
self.update_router_throughput(address, router_info, max_throughput_per_window)
def update_router_throughput(self, address, router_info, max_throughput):
router = self.router_matrix.get_router_by_address(address)
if router is None or router_info is None:
return
neighbors = self.mpsoc_information.neighbors
percent = 100.0 / max_throughput
# Só as portas que possuem vizinho, mais as portas locais
ports = []
if neighbors.get_x_coordinate(address) != 0:
ports += [MPSoCConfig.WEST0, MPSoCConfig.WEST1]
if neighbors.get_x_coordinate(address) != self.mpsoc_config.mpsoc_x - 1:
ports += [MPSoCConfig.EAST0, MPSoCConfig.EAST1]
if neighbors.get_y_coordinate(address) != 0:
ports += [MPSoCConfig.SOUTH0, MPSoCConfig.SOUTH1]
if neighbors.get_y_coordinate(address) != self.mpsoc_config.mpsoc_y - 1:
ports += [MPSoCConfig.NORTH0, MPSoCConfig.NORTH1]
ports += [MPSoCConfig.LOCAL0, MPSoCConfig.LOCAL1]
total_link_usage = 0.0
for port in ports:
usage = router_info.get_port_bandwidth_throughput_in_cycles(port) * percent
router.update_throughput(port, usage)
if port not in (MPSoCConfig.LOCAL0, MPSoCConfig.LOCAL1):
total_link_usage += usage
if address == self.link_usage_router:
# Mesma saída do Java: um valor por checkpoint, com vírgula decimal
value = total_link_usage if self.print_link_usage else self.checkpoint.current_time_ms
print(f"{value:.6g}".replace(".", ","), flush=True)
router_info.reset_bandwidth_throughput()
router_info.reset_throughput()