4 Commits

Author SHA1 Message Date
3a3756f701 Translate graph labels and titles to PT 2025-12-07 20:12:43 +00:00
a8ce95e08c Refactor and enhance documentation across multiple classes (Analysis through DashboardStatistics) 2025-12-07 19:33:40 +00:00
a2f9e725de feat: Implement batch performance analysis dialog and routing policies
- Added BatchAnalysisDialog for running multiple simulations and generating reports.
- Implemented LeastCongestedRouteSelector for dynamic routing based on congestion levels.
- Created RandomRouteSelector for baseline random routing strategy.
- Developed ShortestPathRouteSelector to select routes based on the shortest path.
- Defined RouteSelector interface to standardize routing policy implementations.
- Introduced RoutingPolicy enum to manage available routing strategies.
2025-12-07 00:35:06 +00:00
92ff883d4c fixed dash formatting 2025-12-06 00:59:09 +00:00
46 changed files with 2957 additions and 727 deletions

3
.gitignore vendored
View File

@@ -54,3 +54,6 @@ build/
# JAR built pom file # JAR built pom file
dependency-reduced-pom.xml dependency-reduced-pom.xml
# Python env
venv/

View File

@@ -0,0 +1,6 @@
Execução,VeículosGerados,VeículosCompletados,TaxaConclusão,TempoMédioSistema,TempoMédioEspera,TempoMínimoSistema,TempoMáximoSistema
1,1784,877,49.16,64.58,61.43,32.29,129.16
2,1782,363,20.37,53.77,51.01,26.88,107.53
3,1786,883,49.44,53.09,50.08,26.54,106.17
4,1845,179,9.70,63.92,60.27,31.96,127.84
5,1872,953,50.91,65.41,62.16,32.70,130.81
1 Execução VeículosGerados VeículosCompletados TaxaConclusão TempoMédioSistema TempoMédioEspera TempoMínimoSistema TempoMáximoSistema
2 1 1784 877 49.16 64.58 61.43 32.29 129.16
3 2 1782 363 20.37 53.77 51.01 26.88 107.53
4 3 1786 883 49.44 53.09 50.08 26.54 106.17
5 4 1845 179 9.70 63.92 60.27 31.96 127.84
6 5 1872 953 50.91 65.41 62.16 32.70 130.81

View File

@@ -0,0 +1,215 @@
================================================================================
ANÁLISE ESTATÍSTICA MULTI-EXECUÇÃO
================================================================================
Configuração: simulation-high.properties
Número de Execuções: 5
Data da Análise: 2025-12-07 00:11:13
--------------------------------------------------------------------------------
MÉTRICAS GLOBAIS
--------------------------------------------------------------------------------
Veículos Gerados:
Média: 1813.80 Desvio Padrão: 41.93
Mediana: 1786.00 IC 95%: [1754.13, 1873.47]
Mín: 1782.00 Máx: 1872.00
Veículos Completados:
Média: 651.00 Desvio Padrão: 354.20
Mediana: 877.00 IC 95%: [146.96, 1155.04]
Mín: 179.00 Máx: 953.00
Taxa de Conclusão (%):
Média: 35.92 Desvio Padrão: 19.44
Mediana: 49.16 IC 95%: [8.25, 63.58]
Mín: 9.70 Máx: 50.91
Tempo Médio no Sistema (segundos):
Média: 60.15 Desvio Padrão: 6.17
Mediana: 63.92 IC 95%: [51.38, 68.93]
Mín: 53.09 Máx: 65.41
Tempo Médio de Espera (segundos):
Média: 56.99 Desvio Padrão: 5.93
Mediana: 60.27 IC 95%: [48.55, 65.43]
Mín: 50.08 Máx: 62.16
--------------------------------------------------------------------------------
ANÁLISE POR TIPO DE VEÍCULO
--------------------------------------------------------------------------------
--- BIKE ---
Contagem de Veículos:
Média: 135.40 Desvio Padrão: 77.66
Mediana: 167.00 IC 95%: [24.89, 245.91]
Mín: 37.00 Máx: 211.00
Tempo Médio no Sistema (segundos): Sem dados
Tempo Médio de Espera (segundos):
Média: 55.15 Desvio Padrão: 12.01
Mediana: 54.23 IC 95%: [38.07, 72.24]
Mín: 43.41 Máx: 74.99
--- LIGHT ---
Contagem de Veículos:
Média: 395.00 Desvio Padrão: 207.62
Mediana: 540.00 IC 95%: [99.55, 690.45]
Mín: 107.00 Máx: 548.00
Tempo Médio no Sistema (segundos): Sem dados
Tempo Médio de Espera (segundos):
Média: 59.79 Desvio Padrão: 7.28
Mediana: 61.58 IC 95%: [49.43, 70.15]
Mín: 50.81 Máx: 69.26
--- HEAVY ---
Contagem de Veículos:
Média: 120.60 Desvio Padrão: 72.95
Mediana: 142.00 IC 95%: [16.79, 224.41]
Mín: 35.00 Máx: 202.00
Tempo Médio no Sistema (segundos): Sem dados
Tempo Médio de Espera (segundos):
Média: 49.20 Desvio Padrão: 8.62
Mediana: 50.31 IC 95%: [36.94, 61.46]
Mín: 35.51 Máx: 58.20
--------------------------------------------------------------------------------
ANÁLISE POR INTERSEÇÃO
--------------------------------------------------------------------------------
--- Cr1 ---
Tamanho Máximo da Fila:
Média: 3.20 Desvio Padrão: 5.54
Mediana: 1.00 IC 95%: [-4.68, 11.08]
Mín: 0.00 Máx: 13.00
Tamanho Médio da Fila:
Média: 3.20 Desvio Padrão: 5.54
Mediana: 1.00 IC 95%: [-4.68, 11.08]
Mín: 0.00 Máx: 13.00
Veículos Processados:
Média: 378.40 Desvio Padrão: 252.94
Mediana: 512.00 IC 95%: [18.46, 738.34]
Mín: 58.00 Máx: 600.00
--- Cr2 ---
Tamanho Máximo da Fila:
Média: 0.60 Desvio Padrão: 1.34
Mediana: 0.00 IC 95%: [-1.31, 2.51]
Mín: 0.00 Máx: 3.00
Tamanho Médio da Fila:
Média: 0.60 Desvio Padrão: 1.34
Mediana: 0.00 IC 95%: [-1.31, 2.51]
Mín: 0.00 Máx: 3.00
Veículos Processados:
Média: 390.40 Desvio Padrão: 223.14
Mediana: 409.00 IC 95%: [72.87, 707.93]
Mín: 59.00 Máx: 599.00
--- Cr3 ---
Tamanho Máximo da Fila:
Média: 6.20 Desvio Padrão: 8.67
Mediana: 0.00 IC 95%: [-6.14, 18.54]
Mín: 0.00 Máx: 18.00
Tamanho Médio da Fila:
Média: 6.20 Desvio Padrão: 8.67
Mediana: 0.00 IC 95%: [-6.14, 18.54]
Mín: 0.00 Máx: 18.00
Veículos Processados:
Média: 339.00 Desvio Padrão: 239.34
Mediana: 416.00 IC 95%: [-1.59, 679.59]
Mín: 57.00 Máx: 622.00
--- Cr4 ---
Tamanho Máximo da Fila:
Média: 0.60 Desvio Padrão: 0.89
Mediana: 0.00 IC 95%: [-0.67, 1.87]
Mín: 0.00 Máx: 2.00
Tamanho Médio da Fila:
Média: 0.60 Desvio Padrão: 0.89
Mediana: 0.00 IC 95%: [-0.67, 1.87]
Mín: 0.00 Máx: 2.00
Veículos Processados:
Média: 123.40 Desvio Padrão: 116.13
Mediana: 109.00 IC 95%: [-41.85, 288.65]
Mín: 21.00 Máx: 316.00
--- Cr5 ---
Tamanho Máximo da Fila:
Média: 2.40 Desvio Padrão: 1.14
Mediana: 2.00 IC 95%: [0.78, 4.02]
Mín: 1.00 Máx: 4.00
Tamanho Médio da Fila:
Média: 2.40 Desvio Padrão: 1.14
Mediana: 2.00 IC 95%: [0.78, 4.02]
Mín: 1.00 Máx: 4.00
Veículos Processados:
Média: 200.80 Desvio Padrão: 114.19
Mediana: 261.00 IC 95%: [38.31, 363.29]
Mín: 70.00 Máx: 305.00
--- ExitNode ---
Tamanho Máximo da Fila: Sem dados
Tamanho Médio da Fila: Sem dados
Veículos Processados:
Média: 651.00 Desvio Padrão: 354.20
Mediana: 877.00 IC 95%: [146.96, 1155.04]
Mín: 179.00 Máx: 953.00
--------------------------------------------------------------------------------
RESUMOS INDIVIDUAIS DAS EXECUÇÕES
--------------------------------------------------------------------------------
Execução #1 [simulation-high.properties]:
Gerados: 1784, Completados: 877 (49.2%)
Tempo Médio no Sistema: 64.58s
Tempo Médio de Espera: 61.43s
Execução #2 [simulation-high.properties]:
Gerados: 1782, Completados: 363 (20.4%)
Tempo Médio no Sistema: 53.77s
Tempo Médio de Espera: 51.01s
Execução #3 [simulation-high.properties]:
Gerados: 1786, Completados: 883 (49.4%)
Tempo Médio no Sistema: 53.09s
Tempo Médio de Espera: 50.08s
Execução #4 [simulation-high.properties]:
Gerados: 1845, Completados: 179 (9.7%)
Tempo Médio no Sistema: 63.92s
Tempo Médio de Espera: 60.27s
Execução #5 [simulation-high.properties]:
Gerados: 1872, Completados: 953 (50.9%)
Tempo Médio no Sistema: 65.41s
Tempo Médio de Espera: 62.16s
================================================================================
FIM DO RELATÓRIO
================================================================================

View File

@@ -0,0 +1,6 @@
Execução,VeículosGerados,VeículosCompletados,TaxaConclusão,TempoMédioSistema,TempoMédioEspera,TempoMínimoSistema,TempoMáximoSistema
1,371,187,50.40,42.28,38.65,21.14,84.57
2,361,263,72.85,29.15,25.29,14.57,58.30
3,368,197,53.53,38.02,33.95,19.01,76.04
4,350,239,68.29,32.38,28.36,16.19,64.75
5,373,212,56.84,23.36,19.96,11.68,46.73
1 Execução VeículosGerados VeículosCompletados TaxaConclusão TempoMédioSistema TempoMédioEspera TempoMínimoSistema TempoMáximoSistema
2 1 371 187 50.40 42.28 38.65 21.14 84.57
3 2 361 263 72.85 29.15 25.29 14.57 58.30
4 3 368 197 53.53 38.02 33.95 19.01 76.04
5 4 350 239 68.29 32.38 28.36 16.19 64.75
6 5 373 212 56.84 23.36 19.96 11.68 46.73

View File

@@ -0,0 +1,209 @@
================================================================================
ANÁLISE ESTATÍSTICA MULTI-EXECUÇÃO
================================================================================
Configuração: simulation-low.properties
Número de Execuções: 5
Data da Análise: 2025-12-07 00:09:57
--------------------------------------------------------------------------------
MÉTRICAS GLOBAIS
--------------------------------------------------------------------------------
Veículos Gerados:
Média: 364.60 Desvio Padrão: 9.34
Mediana: 368.00 IC 95%: [351.30, 377.90]
Mín: 350.00 Máx: 373.00
Veículos Completados:
Média: 219.60 Desvio Padrão: 31.19
Mediana: 212.00 IC 95%: [175.22, 263.98]
Mín: 187.00 Máx: 263.00
Taxa de Conclusão (%):
Média: 60.38 Desvio Padrão: 9.71
Mediana: 56.84 IC 95%: [46.57, 74.20]
Mín: 50.40 Máx: 72.85
Tempo Médio no Sistema (segundos):
Média: 33.04 Desvio Padrão: 7.41
Mediana: 32.38 IC 95%: [22.50, 43.58]
Mín: 23.36 Máx: 42.28
Tempo Médio de Espera (segundos):
Média: 29.24 Desvio Padrão: 7.30
Mediana: 28.36 IC 95%: [18.85, 39.63]
Mín: 19.96 Máx: 38.65
--------------------------------------------------------------------------------
ANÁLISE POR TIPO DE VEÍCULO
--------------------------------------------------------------------------------
--- BIKE ---
Contagem de Veículos:
Média: 41.00 Desvio Padrão: 6.96
Mediana: 43.00 IC 95%: [31.09, 50.91]
Mín: 33.00 Máx: 50.00
Tempo Médio no Sistema (segundos): Sem dados
Tempo Médio de Espera (segundos):
Média: 25.91 Desvio Padrão: 3.91
Mediana: 26.98 IC 95%: [20.35, 31.47]
Mín: 19.60 Máx: 30.06
--- LIGHT ---
Contagem de Veículos:
Média: 134.00 Desvio Padrão: 24.07
Mediana: 130.00 IC 95%: [99.74, 168.26]
Mín: 104.00 Máx: 167.00
Tempo Médio no Sistema (segundos): Sem dados
Tempo Médio de Espera (segundos):
Média: 29.34 Desvio Padrão: 6.83
Mediana: 27.89 IC 95%: [19.62, 39.06]
Mín: 20.73 Máx: 36.42
--- HEAVY ---
Contagem de Veículos:
Média: 44.60 Desvio Padrão: 3.44
Mediana: 46.00 IC 95%: [39.71, 49.49]
Mín: 40.00 Máx: 48.00
Tempo Médio no Sistema (segundos): Sem dados
Tempo Médio de Espera (segundos):
Média: 32.11 Desvio Padrão: 15.90
Mediana: 30.74 IC 95%: [9.48, 54.74]
Mín: 18.09 Máx: 58.73
--------------------------------------------------------------------------------
ANÁLISE POR INTERSEÇÃO
--------------------------------------------------------------------------------
--- Cr1 ---
Tamanho Máximo da Fila:
Média: 0.60 Desvio Padrão: 1.34
Mediana: 0.00 IC 95%: [-1.31, 2.51]
Mín: 0.00 Máx: 3.00
Tamanho Médio da Fila:
Média: 0.60 Desvio Padrão: 1.34
Mediana: 0.00 IC 95%: [-1.31, 2.51]
Mín: 0.00 Máx: 3.00
Veículos Processados:
Média: 63.80 Desvio Padrão: 17.25
Mediana: 57.00 IC 95%: [39.25, 88.35]
Mín: 48.00 Máx: 91.00
--- Cr2 ---
Tamanho Máximo da Fila:
Média: 0.80 Desvio Padrão: 1.79
Mediana: 0.00 IC 95%: [-1.75, 3.35]
Mín: 0.00 Máx: 4.00
Tamanho Médio da Fila:
Média: 0.80 Desvio Padrão: 1.79
Mediana: 0.00 IC 95%: [-1.75, 3.35]
Mín: 0.00 Máx: 4.00
Veículos Processados:
Média: 56.20 Desvio Padrão: 18.51
Mediana: 50.00 IC 95%: [29.86, 82.54]
Mín: 35.00 Máx: 78.00
--- Cr3 ---
Tamanho Máximo da Fila:
Média: 1.00 Desvio Padrão: 1.41
Mediana: 0.00 IC 95%: [-1.01, 3.01]
Mín: 0.00 Máx: 3.00
Tamanho Médio da Fila:
Média: 1.00 Desvio Padrão: 1.41
Mediana: 0.00 IC 95%: [-1.01, 3.01]
Mín: 0.00 Máx: 3.00
Veículos Processados:
Média: 63.20 Desvio Padrão: 23.97
Mediana: 56.00 IC 95%: [29.09, 97.31]
Mín: 41.00 Máx: 104.00
--- Cr4 ---
Tamanho Máximo da Fila:
Média: 1.80 Desvio Padrão: 2.49
Mediana: 0.00 IC 95%: [-1.74, 5.34]
Mín: 0.00 Máx: 5.00
Tamanho Médio da Fila:
Média: 1.80 Desvio Padrão: 2.49
Mediana: 0.00 IC 95%: [-1.74, 5.34]
Mín: 0.00 Máx: 5.00
Veículos Processados:
Média: 51.00 Desvio Padrão: 16.05
Mediana: 53.00 IC 95%: [28.16, 73.84]
Mín: 31.00 Máx: 70.00
--- Cr5 ---
Tamanho Máximo da Fila: Sem dados
Tamanho Médio da Fila: Sem dados
Veículos Processados:
Média: 86.60 Desvio Padrão: 34.20
Mediana: 65.00 IC 95%: [37.94, 135.26]
Mín: 62.00 Máx: 139.00
--- ExitNode ---
Tamanho Máximo da Fila: Sem dados
Tamanho Médio da Fila: Sem dados
Veículos Processados:
Média: 219.60 Desvio Padrão: 31.19
Mediana: 212.00 IC 95%: [175.22, 263.98]
Mín: 187.00 Máx: 263.00
--------------------------------------------------------------------------------
RESUMOS INDIVIDUAIS DAS EXECUÇÕES
--------------------------------------------------------------------------------
Execução #1 [simulation-low.properties]:
Gerados: 371, Completados: 187 (50.4%)
Tempo Médio no Sistema: 42.28s
Tempo Médio de Espera: 38.65s
Execução #2 [simulation-low.properties]:
Gerados: 361, Completados: 263 (72.9%)
Tempo Médio no Sistema: 29.15s
Tempo Médio de Espera: 25.29s
Execução #3 [simulation-low.properties]:
Gerados: 368, Completados: 197 (53.5%)
Tempo Médio no Sistema: 38.02s
Tempo Médio de Espera: 33.95s
Execução #4 [simulation-low.properties]:
Gerados: 350, Completados: 239 (68.3%)
Tempo Médio no Sistema: 32.38s
Tempo Médio de Espera: 28.36s
Execução #5 [simulation-low.properties]:
Gerados: 373, Completados: 212 (56.8%)
Tempo Médio no Sistema: 23.36s
Tempo Médio de Espera: 19.96s
================================================================================
FIM DO RELATÓRIO
================================================================================

View File

@@ -0,0 +1,6 @@
Execução,VeículosGerados,VeículosCompletados,TaxaConclusão,TempoMédioSistema,TempoMédioEspera,TempoMínimoSistema,TempoMáximoSistema
1,950,416,43.79,49.34,45.70,24.67,98.68
2,886,480,54.18,35.08,31.69,17.54,70.16
3,954,535,56.08,43.76,40.30,21.88,87.51
4,948,354,37.34,41.68,37.96,20.84,83.37
5,898,312,34.74,52.56,49.26,26.28,105.13
1 Execução VeículosGerados VeículosCompletados TaxaConclusão TempoMédioSistema TempoMédioEspera TempoMínimoSistema TempoMáximoSistema
2 1 950 416 43.79 49.34 45.70 24.67 98.68
3 2 886 480 54.18 35.08 31.69 17.54 70.16
4 3 954 535 56.08 43.76 40.30 21.88 87.51
5 4 948 354 37.34 41.68 37.96 20.84 83.37
6 5 898 312 34.74 52.56 49.26 26.28 105.13

View File

@@ -0,0 +1,203 @@
================================================================================
ANÁLISE ESTATÍSTICA MULTI-EXECUÇÃO
================================================================================
Configuração: simulation-medium.properties
Número de Execuções: 5
Data da Análise: 2025-12-07 00:10:34
--------------------------------------------------------------------------------
MÉTRICAS GLOBAIS
--------------------------------------------------------------------------------
Veículos Gerados:
Média: 927.20 Desvio Padrão: 32.48
Mediana: 948.00 IC 95%: [880.97, 973.43]
Mín: 886.00 Máx: 954.00
Veículos Completados:
Média: 419.40 Desvio Padrão: 90.64
Mediana: 416.00 IC 95%: [290.42, 548.38]
Mín: 312.00 Máx: 535.00
Taxa de Conclusão (%):
Média: 45.23 Desvio Padrão: 9.64
Mediana: 43.79 IC 95%: [31.50, 58.95]
Mín: 34.74 Máx: 56.08
Tempo Médio no Sistema (segundos):
Média: 44.48 Desvio Padrão: 6.81
Mediana: 43.76 IC 95%: [34.79, 54.18]
Mín: 35.08 Máx: 52.56
Tempo Médio de Espera (segundos):
Média: 40.98 Desvio Padrão: 6.83
Mediana: 40.30 IC 95%: [31.26, 50.71]
Mín: 31.69 Máx: 49.26
--------------------------------------------------------------------------------
ANÁLISE POR TIPO DE VEÍCULO
--------------------------------------------------------------------------------
--- BIKE ---
Contagem de Veículos:
Média: 75.80 Desvio Padrão: 15.96
Mediana: 71.00 IC 95%: [53.09, 98.51]
Mín: 56.00 Máx: 95.00
Tempo Médio no Sistema (segundos): Sem dados
Tempo Médio de Espera (segundos):
Média: 42.34 Desvio Padrão: 10.81
Mediana: 39.70 IC 95%: [26.96, 57.72]
Mín: 31.96 Máx: 55.19
--- LIGHT ---
Contagem de Veículos:
Média: 263.20 Desvio Padrão: 58.29
Mediana: 265.00 IC 95%: [180.25, 346.15]
Mín: 204.00 Máx: 344.00
Tempo Médio no Sistema (segundos): Sem dados
Tempo Médio de Espera (segundos):
Média: 39.13 Desvio Padrão: 6.35
Mediana: 38.08 IC 95%: [30.09, 48.17]
Mín: 30.47 Máx: 47.99
--- HEAVY ---
Contagem de Veículos:
Média: 80.40 Desvio Padrão: 19.11
Mediana: 80.00 IC 95%: [53.20, 107.60]
Mín: 52.00 Máx: 102.00
Tempo Médio no Sistema (segundos): Sem dados
Tempo Médio de Espera (segundos):
Média: 48.02 Desvio Padrão: 30.99
Mediana: 34.44 IC 95%: [3.92, 92.11]
Mín: 32.46 Máx: 103.40
--------------------------------------------------------------------------------
ANÁLISE POR INTERSEÇÃO
--------------------------------------------------------------------------------
--- Cr1 ---
Tamanho Máximo da Fila:
Média: 5.60 Desvio Padrão: 11.44
Mediana: 0.00 IC 95%: [-10.67, 21.87]
Mín: 0.00 Máx: 26.00
Tamanho Médio da Fila:
Média: 5.60 Desvio Padrão: 11.44
Mediana: 0.00 IC 95%: [-10.67, 21.87]
Mín: 0.00 Máx: 26.00
Veículos Processados:
Média: 156.00 Desvio Padrão: 122.81
Mediana: 98.00 IC 95%: [-18.76, 330.76]
Mín: 35.00 Máx: 306.00
--- Cr2 ---
Tamanho Máximo da Fila: Sem dados
Tamanho Médio da Fila: Sem dados
Veículos Processados:
Média: 172.00 Desvio Padrão: 121.88
Mediana: 116.00 IC 95%: [-1.44, 345.44]
Mín: 66.00 Máx: 322.00
--- Cr3 ---
Tamanho Máximo da Fila:
Média: 0.60 Desvio Padrão: 1.34
Mediana: 0.00 IC 95%: [-1.31, 2.51]
Mín: 0.00 Máx: 3.00
Tamanho Médio da Fila:
Média: 0.60 Desvio Padrão: 1.34
Mediana: 0.00 IC 95%: [-1.31, 2.51]
Mín: 0.00 Máx: 3.00
Veículos Processados:
Média: 168.40 Desvio Padrão: 133.38
Mediana: 121.00 IC 95%: [-21.40, 358.20]
Mín: 48.00 Máx: 326.00
--- Cr4 ---
Tamanho Máximo da Fila: Sem dados
Tamanho Médio da Fila: Sem dados
Veículos Processados:
Média: 71.80 Desvio Padrão: 20.39
Mediana: 77.00 IC 95%: [42.79, 100.81]
Mín: 38.00 Máx: 92.00
--- Cr5 ---
Tamanho Máximo da Fila:
Média: 3.60 Desvio Padrão: 3.85
Mediana: 2.00 IC 95%: [-1.87, 9.07]
Mín: 0.00 Máx: 10.00
Tamanho Médio da Fila:
Média: 3.60 Desvio Padrão: 3.85
Mediana: 2.00 IC 95%: [-1.87, 9.07]
Mín: 0.00 Máx: 10.00
Veículos Processados:
Média: 150.60 Desvio Padrão: 43.37
Mediana: 126.00 IC 95%: [88.88, 212.32]
Mín: 116.00 Máx: 209.00
--- ExitNode ---
Tamanho Máximo da Fila: Sem dados
Tamanho Médio da Fila: Sem dados
Veículos Processados:
Média: 419.40 Desvio Padrão: 90.64
Mediana: 416.00 IC 95%: [290.42, 548.38]
Mín: 312.00 Máx: 535.00
--------------------------------------------------------------------------------
RESUMOS INDIVIDUAIS DAS EXECUÇÕES
--------------------------------------------------------------------------------
Execução #1 [simulation-medium.properties]:
Gerados: 950, Completados: 416 (43.8%)
Tempo Médio no Sistema: 49.34s
Tempo Médio de Espera: 45.70s
Execução #2 [simulation-medium.properties]:
Gerados: 886, Completados: 480 (54.2%)
Tempo Médio no Sistema: 35.08s
Tempo Médio de Espera: 31.69s
Execução #3 [simulation-medium.properties]:
Gerados: 954, Completados: 535 (56.1%)
Tempo Médio no Sistema: 43.76s
Tempo Médio de Espera: 40.30s
Execução #4 [simulation-medium.properties]:
Gerados: 948, Completados: 354 (37.3%)
Tempo Médio no Sistema: 41.68s
Tempo Médio de Espera: 37.96s
Execução #5 [simulation-medium.properties]:
Gerados: 898, Completados: 312 (34.7%)
Tempo Médio no Sistema: 52.56s
Tempo Médio de Espera: 49.26s
================================================================================
FIM DO RELATÓRIO
================================================================================

169
main/graphing.py Normal file
View File

@@ -0,0 +1,169 @@
import pandas as pd
import matplotlib.pyplot as plt
import glob
import os
# Find CSV files using glob
def load_latest_csv(pattern):
"""Load the most recent CSV file matching the pattern"""
files = glob.glob(pattern)
if not files:
print(f"Warning: No files found matching '{pattern}'")
return None
# Sort by modification time, get the latest
latest_file = max(files, key=os.path.getmtime)
print(f"Loading: {latest_file}")
return pd.read_csv(latest_file)
# Carregar dados
print("Looking for analysis files...")
low = load_latest_csv('analysis/LOW_LOAD_*.csv')
medium = load_latest_csv('analysis/MEDIUM_LOAD_*.csv')
high = load_latest_csv('analysis/HIGH_LOAD_*.csv')
# Check if we have all data
if low is None or medium is None or high is None:
print("\nError: Missing analysis files!")
print("Please run the batch analysis first:")
exit(1)
# Print available columns for debugging
print("\nAvailable columns in LOW_LOAD CSV:")
print(low.columns.tolist())
# Create output directory for graphs
os.makedirs('graphs', exist_ok=True)
# 1. Gráfico: Dwelling Time vs Load
plt.figure(figsize=(10, 6))
dwelling_times = [
low['TempoMédioSistema'].mean(),
medium['TempoMédioSistema'].mean(),
high['TempoMédioSistema'].mean()
]
plt.bar(['Baixa', 'Média', 'Alta'], dwelling_times, color=['green', 'orange', 'red'])
plt.ylabel('Tempo Médio no Sistema (s)')
plt.title('Desempenho do Sistema vs Carga')
plt.xlabel('Cenário de Carga')
plt.grid(axis='y', alpha=0.3)
for i, v in enumerate(dwelling_times):
plt.text(i, v + 1, f'{v:.2f}s', ha='center', va='bottom')
plt.savefig('graphs/dwelling_time_comparison.png', dpi=300, bbox_inches='tight')
print("\nGraph saved: graphs/dwelling_time_comparison.png")
plt.close()
# 2. Gráfico: Completion Rate vs Load
plt.figure(figsize=(10, 6))
completion_rates = [
low['TaxaConclusão'].mean(),
medium['TaxaConclusão'].mean(),
high['TaxaConclusão'].mean()
]
plt.bar(['Baixa', 'Média', 'Alta'], completion_rates, color=['green', 'orange', 'red'])
plt.ylabel('Taxa de Conclusão (%)')
plt.title('Taxa de Conclusão de Veículos vs Carga')
plt.xlabel('Cenário de Carga')
plt.grid(axis='y', alpha=0.3)
plt.ylim(0, 100)
for i, v in enumerate(completion_rates):
plt.text(i, v + 2, f'{v:.1f}%', ha='center', va='bottom')
plt.savefig('graphs/completion_rate_comparison.png', dpi=300, bbox_inches='tight')
print("Graph saved: graphs/completion_rate_comparison.png")
plt.close()
# 3. Gráfico: Waiting Time vs Load
plt.figure(figsize=(10, 6))
waiting_times = [
low['TempoMédioEspera'].mean(),
medium['TempoMédioEspera'].mean(),
high['TempoMédioEspera'].mean()
]
plt.bar(['Baixa', 'Média', 'Alta'], waiting_times, color=['green', 'orange', 'red'])
plt.ylabel('Tempo Médio de Espera (s)')
plt.title('Tempo Médio de Espera vs Carga')
plt.xlabel('Cenário de Carga')
plt.grid(axis='y', alpha=0.3)
for i, v in enumerate(waiting_times):
plt.text(i, v + 1, f'{v:.2f}s', ha='center', va='bottom')
plt.savefig('graphs/waiting_time_comparison.png', dpi=300, bbox_inches='tight')
print("Graph saved: graphs/waiting_time_comparison.png")
plt.close()
# 4. Gráfico: Summary Statistics
fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2, figsize=(14, 10))
loads = ['Baixa', 'Média', 'Alta']
# Vehicles generated
ax1.bar(loads, [low['VeículosGerados'].mean(), medium['VeículosGerados'].mean(), high['VeículosGerados'].mean()], color=['green', 'orange', 'red'])
ax1.set_title('Veículos Gerados')
ax1.set_ylabel('Quantidade')
ax1.grid(axis='y', alpha=0.3)
# Vehicles completed
ax2.bar(loads, [low['VeículosCompletados'].mean(), medium['VeículosCompletados'].mean(), high['VeículosCompletados'].mean()], color=['green', 'orange', 'red'])
ax2.set_title('Veículos Concluídos')
ax2.set_ylabel('Quantidade')
ax2.grid(axis='y', alpha=0.3)
# Min/Max dwelling time
x = range(3)
width = 0.35
ax3.bar([i - width/2 for i in x], [low['TempoMínimoSistema'].mean(), medium['TempoMínimoSistema'].mean(), high['TempoMínimoSistema'].mean()], width, label='Mín', color='lightblue')
ax3.bar([i + width/2 for i in x], [low['TempoMáximoSistema'].mean(), medium['TempoMáximoSistema'].mean(), high['TempoMáximoSistema'].mean()], width, label='Máx', color='darkblue')
ax3.set_title('Tempo no Sistema Mín/Máx')
ax3.set_ylabel('Tempo (s)')
ax3.set_xticks(x)
ax3.set_xticklabels(loads)
ax3.legend()
ax3.grid(axis='y', alpha=0.3)
# Performance summary
metrics = ['Tempo no\nSistema', 'Tempo de\nEspera', 'Taxa de\nConclusão']
low_vals = [low['TempoMédioSistema'].mean(), low['TempoMédioEspera'].mean(), low['TaxaConclusão'].mean()]
med_vals = [medium['TempoMédioSistema'].mean(), medium['TempoMédioEspera'].mean(), medium['TaxaConclusão'].mean()]
high_vals = [high['TempoMédioSistema'].mean(), high['TempoMédioEspera'].mean(), high['TaxaConclusão'].mean()]
x = range(len(metrics))
width = 0.25
ax4.bar([i - width for i in x], low_vals, width, label='Baixa', color='green')
ax4.bar(x, med_vals, width, label='Média', color='orange')
ax4.bar([i + width for i in x], high_vals, width, label='Alta', color='red')
ax4.set_title('Resumo de Desempenho')
ax4.set_xticks(x)
ax4.set_xticklabels(metrics)
ax4.legend()
ax4.grid(axis='y', alpha=0.3)
plt.tight_layout()
plt.savefig('graphs/summary_statistics.png', dpi=300, bbox_inches='tight')
print("Graph saved: graphs/summary_statistics.png")
plt.close()
# Print summary statistics
print("\n" + "="*60)
print("SUMMARY STATISTICS")
print("="*60)
print(f"\nLOW LOAD:")
print(f" Avg Dwelling Time: {low['TempoMédioSistema'].mean():.2f}s")
print(f" Avg Waiting Time: {low['TempoMédioEspera'].mean():.2f}s")
print(f" Completion Rate: {low['TaxaConclusão'].mean():.1f}%")
print(f" Vehicles Generated: {low['VeículosGerados'].mean():.0f}")
print(f" Vehicles Completed: {low['VeículosCompletados'].mean():.0f}")
print(f"\nMEDIUM LOAD:")
print(f" Avg Dwelling Time: {medium['TempoMédioSistema'].mean():.2f}s")
print(f" Avg Waiting Time: {medium['TempoMédioEspera'].mean():.2f}s")
print(f" Completion Rate: {medium['TaxaConclusão'].mean():.1f}%")
print(f" Vehicles Generated: {medium['VeículosGerados'].mean():.0f}")
print(f" Vehicles Completed: {medium['VeículosCompletados'].mean():.0f}")
print(f"\nHIGH LOAD:")
print(f" Avg Dwelling Time: {high['TempoMédioSistema'].mean():.2f}s")
print(f" Avg Waiting Time: {high['TempoMédioEspera'].mean():.2f}s")
print(f" Completion Rate: {high['TaxaConclusão'].mean():.1f}%")
print(f" Vehicles Generated: {high['VeículosGerados'].mean():.0f}")
print(f" Vehicles Completed: {high['VeículosCompletados'].mean():.0f}")
print("\n" + "="*60)
print("All graphs saved in 'graphs/' directory!")
print("="*60)

Binary file not shown.

After

Width:  |  Height:  |  Size: 90 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 90 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 215 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 86 KiB

View File

@@ -271,14 +271,18 @@ public class IntersectionProcess {
/** /**
* Processa a fila de veículos quando um semáforo fica verde. * Processa a fila de veículos quando um semáforo fica verde.
* *
* <p>Para cada veículo na fila:</p> * <p>
* Para cada veículo na fila:
* </p>
* <ol> * <ol>
* <li>Calcula o tempo de travessia com base no tipo de veículo</li> * <li>Calcula o tempo de travessia com base no tipo de veículo</li>
* <li>Verifica se cabe na duração restante do sinal verde</li> * <li>Verifica se cabe na duração restante do sinal verde</li>
* <li>Agenda o evento de partida do veículo</li> * <li>Agenda o evento de partida do veículo</li>
* </ol> * </ol>
* *
* <p>Os veículos que não couberem no tempo verde ficam à espera do próximo ciclo.</p> * <p>
* Os veículos que não couberem no tempo verde ficam à espera do próximo ciclo.
* </p>
* *
* @param light o semáforo que acabou de ficar verde * @param light o semáforo que acabou de ficar verde
* @param currentTime o tempo atual da simulação em segundos * @param currentTime o tempo atual da simulação em segundos
@@ -302,8 +306,8 @@ public class IntersectionProcess {
break; // No more vehicles can cross this green phase break; // No more vehicles can cross this green phase
} }
// Remove vehicle from queue // Remove vehicle from queue with current simulation time
Vehicle vehicle = light.removeVehicle(); Vehicle vehicle = light.removeVehicle(currentTime + timeOffset);
if (vehicle == null) if (vehicle == null)
break; break;
@@ -844,8 +848,8 @@ public class IntersectionProcess {
// Advance vehicle to next destination in its route // Advance vehicle to next destination in its route
vehicle.advanceRoute(); vehicle.advanceRoute();
// Add vehicle to appropriate queue // Add vehicle to appropriate queue with current simulation time
intersection.receiveVehicle(vehicle); intersection.receiveVehicle(vehicle, clock.getCurrentTime());
// Log queue status after adding vehicle // Log queue status after adding vehicle
System.out.printf("[%s] Vehicle %s queued. Total queue size: %d%n", System.out.printf("[%s] Vehicle %s queued. Total queue size: %d%n",

View File

@@ -5,41 +5,70 @@ import java.io.FileWriter;
import java.io.IOException; import java.io.IOException;
import java.io.PrintWriter; import java.io.PrintWriter;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.util.*; import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import sd.model.VehicleType; import sd.model.VehicleType;
/** /**
* Executes multiple simulation runs and aggregates results. * Responsável pela agregação e análise estatística de múltiplas execuções da simulação.
* Calculates statistical measures including mean, standard deviation, * <p>
* and confidence intervals across all runs. * Esta classe coleta resultados individuais ({@link SimulationRunResult}) e calcula
* métricas consolidadas, incluindo média, desvio padrão, mediana e intervalos de
* confiança de 95%. O objetivo é fornecer uma visão robusta do comportamento do
* sistema, mitigando a variância estocástica de execuções isoladas.
*/ */
public class MultiRunAnalyzer { public class MultiRunAnalyzer {
/** Lista acumulada de resultados de execuções individuais. */
private final List<SimulationRunResult> results; private final List<SimulationRunResult> results;
/** Identificador do ficheiro de configuração utilizado nas execuções. */
private final String configurationFile; private final String configurationFile;
/**
* Inicializa o analisador para um conjunto específico de configurações.
*
* @param configurationFile O caminho ou nome do ficheiro de configuração base.
*/
public MultiRunAnalyzer(String configurationFile) { public MultiRunAnalyzer(String configurationFile) {
this.configurationFile = configurationFile; this.configurationFile = configurationFile;
this.results = new ArrayList<>(); this.results = new ArrayList<>();
} }
/** /**
* Adds a completed simulation run result. * Adiciona o resultado de uma execução de simulação concluída ao conjunto de dados.
*
* @param result O objeto contendo as métricas da execução individual.
*/ */
public void addResult(SimulationRunResult result) { public void addResult(SimulationRunResult result) {
results.add(result); results.add(result);
} }
/** /**
* Gets the number of completed runs. * Retorna o número total de execuções armazenadas até o momento.
*
* @return O tamanho da lista de resultados.
*/ */
public int getRunCount() { public int getRunCount() {
return results.size(); return results.size();
} }
/** /**
* Generates a comprehensive statistical report. * Gera um relatório estatístico abrangente formatado em texto.
* <p>
* O relatório inclui:
* <ul>
* <li>Métricas globais (throughput, tempos de espera, tempos no sistema).</li>
* <li>Análise segmentada por tipo de veículo ({@link VehicleType}).</li>
* <li>Análise de gargalos por interseção (tamanhos de fila).</li>
* <li>Resumos brutos das execuções individuais.</li>
* </ul>
*
* @return Uma String contendo o relatório completo formatado.
*/ */
public String generateReport() { public String generateReport() {
if (results.isEmpty()) { if (results.isEmpty()) {
@@ -50,65 +79,65 @@ public class MultiRunAnalyzer {
// Header // Header
report.append("=".repeat(80)).append("\n"); report.append("=".repeat(80)).append("\n");
report.append("MULTI-RUN STATISTICAL ANALYSIS\n"); report.append("ANÁLISE ESTATÍSTICA MULTI-EXECUÇÃO\n");
report.append("=".repeat(80)).append("\n"); report.append("=".repeat(80)).append("\n");
report.append("Configuration: ").append(configurationFile).append("\n"); report.append("Configuração: ").append(configurationFile).append("\n");
report.append("Number of Runs: ").append(results.size()).append("\n"); report.append("Número de Execuções: ").append(results.size()).append("\n");
report.append("Analysis Date: ").append(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())).append("\n"); report.append("Data da Análise: ").append(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())).append("\n");
report.append("\n"); report.append("\n");
// Global metrics // Global metrics
report.append("-".repeat(80)).append("\n"); report.append("-".repeat(80)).append("\n");
report.append("GLOBAL METRICS\n"); report.append("MÉTRICAS GLOBAIS\n");
report.append("-".repeat(80)).append("\n\n"); report.append("-".repeat(80)).append("\n\n");
report.append(analyzeMetric("Vehicles Generated", report.append(analyzeMetric("Veículos Gerados",
extractValues(r -> (double) r.getTotalVehiclesGenerated()))); extractValues(r -> (double) r.getTotalVehiclesGenerated())));
report.append("\n"); report.append("\n");
report.append(analyzeMetric("Vehicles Completed", report.append(analyzeMetric("Veículos Completados",
extractValues(r -> (double) r.getTotalVehiclesCompleted()))); extractValues(r -> (double) r.getTotalVehiclesCompleted())));
report.append("\n"); report.append("\n");
report.append(analyzeMetric("Completion Rate (%)", report.append(analyzeMetric("Taxa de Conclusão (%)",
extractValues(r -> r.getTotalVehiclesGenerated() > 0 extractValues(r -> r.getTotalVehiclesGenerated() > 0
? 100.0 * r.getTotalVehiclesCompleted() / r.getTotalVehiclesGenerated() ? 100.0 * r.getTotalVehiclesCompleted() / r.getTotalVehiclesGenerated()
: 0.0))); : 0.0)));
report.append("\n"); report.append("\n");
report.append(analyzeMetric("Average System Time (seconds)", report.append(analyzeMetric("Tempo Médio no Sistema (segundos)",
extractValues(r -> r.getAverageSystemTime()))); extractValues(r -> r.getAverageSystemTime())));
report.append("\n"); report.append("\n");
report.append(analyzeMetric("Average Waiting Time (seconds)", report.append(analyzeMetric("Tempo Médio de Espera (segundos)",
extractValues(r -> r.getAverageWaitingTime()))); extractValues(r -> r.getAverageWaitingTime())));
report.append("\n"); report.append("\n");
// Per-vehicle-type analysis // Per-vehicle-type analysis
report.append("\n"); report.append("\n");
report.append("-".repeat(80)).append("\n"); report.append("-".repeat(80)).append("\n");
report.append("PER-VEHICLE-TYPE ANALYSIS\n"); report.append("ANÁLISE POR TIPO DE VEÍCULO\n");
report.append("-".repeat(80)).append("\n\n"); report.append("-".repeat(80)).append("\n\n");
for (VehicleType type : VehicleType.values()) { for (VehicleType type : VehicleType.values()) {
report.append("--- ").append(type).append(" ---\n"); report.append("--- ").append(type).append(" ---\n");
report.append(analyzeMetric(" Vehicle Count", report.append(analyzeMetric(" Contagem de Veículos",
extractValues(r -> (double) r.getVehicleCountByType().getOrDefault(type, 0)))); extractValues(r -> (double) r.getVehicleCountByType().getOrDefault(type, 0))));
report.append("\n"); report.append("\n");
report.append(analyzeMetric(" Avg System Time (seconds)", report.append(analyzeMetric(" Tempo Médio no Sistema (segundos)",
extractValues(r -> r.getAvgSystemTimeByType().getOrDefault(type, 0.0)))); extractValues(r -> r.getAvgSystemTimeByType().getOrDefault(type, 0.0))));
report.append("\n"); report.append("\n");
report.append(analyzeMetric(" Avg Waiting Time (seconds)", report.append(analyzeMetric(" Tempo Médio de Espera (segundos)",
extractValues(r -> r.getAvgWaitTimeByType().getOrDefault(type, 0.0)))); extractValues(r -> r.getAvgWaitTimeByType().getOrDefault(type, 0.0))));
report.append("\n\n"); report.append("\n\n");
} }
// Per-intersection analysis // Per-intersection analysis
report.append("-".repeat(80)).append("\n"); report.append("-".repeat(80)).append("\n");
report.append("PER-INTERSECTION ANALYSIS\n"); report.append("ANÁLISE POR INTERSEÇÃO\n");
report.append("-".repeat(80)).append("\n\n"); report.append("-".repeat(80)).append("\n\n");
Set<String> allIntersections = new TreeSet<>(); Set<String> allIntersections = new TreeSet<>();
@@ -119,22 +148,22 @@ public class MultiRunAnalyzer {
for (String intersection : allIntersections) { for (String intersection : allIntersections) {
report.append("--- ").append(intersection).append(" ---\n"); report.append("--- ").append(intersection).append(" ---\n");
report.append(analyzeMetric(" Max Queue Size", report.append(analyzeMetric(" Tamanho Máximo da Fila",
extractValues(r -> (double) r.getMaxQueueSizeByIntersection().getOrDefault(intersection, 0)))); extractValues(r -> (double) r.getMaxQueueSizeByIntersection().getOrDefault(intersection, 0))));
report.append("\n"); report.append("\n");
report.append(analyzeMetric(" Avg Queue Size", report.append(analyzeMetric(" Tamanho Médio da Fila",
extractValues(r -> r.getAvgQueueSizeByIntersection().getOrDefault(intersection, 0.0)))); extractValues(r -> r.getAvgQueueSizeByIntersection().getOrDefault(intersection, 0.0))));
report.append("\n"); report.append("\n");
report.append(analyzeMetric(" Vehicles Processed", report.append(analyzeMetric(" Veículos Processados",
extractValues(r -> (double) r.getVehiclesProcessedByIntersection().getOrDefault(intersection, 0)))); extractValues(r -> (double) r.getVehiclesProcessedByIntersection().getOrDefault(intersection, 0))));
report.append("\n\n"); report.append("\n\n");
} }
// Individual run summaries // Individual run summaries
report.append("-".repeat(80)).append("\n"); report.append("-".repeat(80)).append("\n");
report.append("INDIVIDUAL RUN SUMMARIES\n"); report.append("RESUMOS INDIVIDUAIS DAS EXECUÇÕES\n");
report.append("-".repeat(80)).append("\n\n"); report.append("-".repeat(80)).append("\n\n");
for (SimulationRunResult result : results) { for (SimulationRunResult result : results) {
@@ -142,18 +171,24 @@ public class MultiRunAnalyzer {
} }
report.append("=".repeat(80)).append("\n"); report.append("=".repeat(80)).append("\n");
report.append("END OF REPORT\n"); report.append("FIM DO RELATÓRIO\n");
report.append("=".repeat(80)).append("\n"); report.append("=".repeat(80)).append("\n");
return report.toString(); return report.toString();
} }
/** /**
* Analyzes a single metric and returns formatted statistics. * Analisa uma métrica específica e retorna as estatísticas formatadas.
* <p>
* Calcula média, desvio padrão, mediana, intervalo de confiança (95%) e extremos (min/max).
*
* @param metricName O nome descritivo da métrica (ex: "Tempo de Espera").
* @param values A lista de valores numéricos brutos extraídos das execuções.
* @return Uma string formatada com os dados estatísticos.
*/ */
private String analyzeMetric(String metricName, List<Double> values) { private String analyzeMetric(String metricName, List<Double> values) {
if (values.isEmpty() || values.stream().allMatch(v -> v == 0.0)) { if (values.isEmpty() || values.stream().allMatch(v -> v == 0.0)) {
return metricName + ": No data\n"; return metricName + ": Sem dados\n";
} }
double mean = StatisticalAnalysis.mean(values); double mean = StatisticalAnalysis.mean(values);
@@ -165,15 +200,21 @@ public class MultiRunAnalyzer {
return String.format( return String.format(
"%s:\n" + "%s:\n" +
" Mean: %10.2f Std Dev: %10.2f\n" + " Média: %10.2f Desvio Padrão: %10.2f\n" +
" Median: %10.2f 95%% CI: [%.2f, %.2f]\n" + " Mediana: %10.2f IC 95%%: [%.2f, %.2f]\n" +
" Min: %10.2f Max: %10.2f\n", " Mín: %10.2f Máx: %10.2f\n",
metricName, mean, stdDev, median, ci[0], ci[1], min, max metricName, mean, stdDev, median, ci[0], ci[1], min, max
); );
} }
/** /**
* Extracts values using a lambda function. * Extrai valores numéricos dos resultados de simulação usando uma função mapeadora.
* <p>
* Utilizado internamente para transformar a lista de objetos complexos {@link SimulationRunResult}
* em listas simples de Doubles para processamento estatístico.
*
* @param extractor Função lambda que define qual campo extrair de cada resultado.
* @return Lista de valores double correspondentes.
*/ */
private List<Double> extractValues(java.util.function.Function<SimulationRunResult, Double> extractor) { private List<Double> extractValues(java.util.function.Function<SimulationRunResult, Double> extractor) {
List<Double> values = new ArrayList<>(); List<Double> values = new ArrayList<>();
@@ -184,7 +225,10 @@ public class MultiRunAnalyzer {
} }
/** /**
* Saves the report to a file. * Persiste o relatório gerado num ficheiro de texto.
*
* @param filename O caminho do ficheiro de destino.
* @throws IOException Se ocorrer um erro de escrita no disco.
*/ */
public void saveReport(String filename) throws IOException { public void saveReport(String filename) throws IOException {
try (PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter(filename)))) { try (PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter(filename)))) {
@@ -193,13 +237,31 @@ public class MultiRunAnalyzer {
} }
/** /**
* Generates a CSV summary for easy import into spreadsheet tools. * Gera um resumo em formato CSV para fácil importação em ferramentas de planilha.
* <p>
* Este método atua como um wrapper para {@link #saveCSVSummary(String)}.
*
* @param filename O caminho do ficheiro CSV de destino.
* @throws IOException Se ocorrer um erro de escrita no disco.
*/
public void saveCSV(String filename) throws IOException {
saveCSVSummary(filename);
}
/**
* Gera e grava o sumário CSV detalhado com métricas chave por execução.
* <p>
* Colunas incluídas: Execução, VeículosGerados, VeículosCompletados, TaxaConclusão,
* TempoMédioSistema, TempoMédioEspera, TempoMínimoSistema, TempoMáximoSistema.
*
* @param filename O caminho do ficheiro CSV de destino.
* @throws IOException Se ocorrer um erro de escrita no disco.
*/ */
public void saveCSVSummary(String filename) throws IOException { public void saveCSVSummary(String filename) throws IOException {
try (PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter(filename)))) { try (PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter(filename)))) {
// Header // Header
writer.println("Run,VehiclesGenerated,VehiclesCompleted,CompletionRate," + writer.println("Execução,VeículosGerados,VeículosCompletados,TaxaConclusão," +
"AvgSystemTime,AvgWaitingTime,MinSystemTime,MaxSystemTime"); "TempoMédioSistema,TempoMédioEspera,TempoMínimoSistema,TempoMáximoSistema");
// Data rows // Data rows
for (SimulationRunResult result : results) { for (SimulationRunResult result : results) {

View File

@@ -1,172 +0,0 @@
package sd.analysis;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* Orquestra múltiplas execuções de simulação para análise estatística.
*
* Em vez de correr uma única simulação manualmente, esta ferramenta permite
* correr um "lote"
* de N simulações consecutivas. Isto é essencial para recolher dados
* estatisticamente significativos
* (calcular intervalos de confiança, etc.) conforme exigido pelas
* especificações do projeto.
*
* Utilização:
* java sd.analysis.SimulationBatchRunner <ficheiro-config> <num-execucoes>
* <dir-saida>
*/
public class SimulationBatchRunner {
public static void main(String[] args) {
if (args.length < 3) {
System.err.println("Usage: SimulationBatchRunner <config-file> <num-runs> <output-dir>");
System.err.println("Example: SimulationBatchRunner simulation-medium.properties 10 results/medium");
System.exit(1);
}
String configFile = args[0];
int numRuns;
String outputDir = args[2];
try {
numRuns = Integer.parseInt(args[1]);
if (numRuns < 1 || numRuns > 100) {
throw new IllegalArgumentException("Number of runs must be between 1 and 100");
}
} catch (NumberFormatException e) {
System.err.println("Error: Invalid number of runs: " + args[1]);
System.exit(1);
return;
}
System.out.println("=".repeat(80));
System.out.println("SIMULATION BATCH RUNNER");
System.out.println("=".repeat(80));
System.out.println("Configuration: " + configFile);
System.out.println("Number of Runs: " + numRuns);
System.out.println("Output Directory: " + outputDir);
System.out.println("=".repeat(80));
System.out.println();
// Create output directory
try {
Files.createDirectories(Paths.get(outputDir));
} catch (IOException e) {
System.err.println("Failed to create output directory: " + e.getMessage());
System.exit(1);
}
MultiRunAnalyzer analyzer = new MultiRunAnalyzer(configFile);
// Execute runs
for (int i = 1; i <= numRuns; i++) {
System.out.println("\n" + "=".repeat(80));
System.out.println("STARTING RUN " + i + " OF " + numRuns);
System.out.println("=".repeat(80));
SimulationRunResult result = executeSimulationRun(i, configFile, outputDir);
if (result != null) {
analyzer.addResult(result);
System.out.println("\n" + result);
} else {
System.err.println("Run " + i + " failed!");
}
// Pause between runs
if (i < numRuns) {
System.out.println("\nWaiting 10 seconds before next run...");
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
break;
}
}
}
// Generate reports
System.out.println("\n\n" + "=".repeat(80));
System.out.println("ALL RUNS COMPLETE - GENERATING REPORTS");
System.out.println("=".repeat(80));
try {
String timestamp = new SimpleDateFormat("yyyyMMdd-HHmmss").format(new Date());
String reportFile = outputDir + "/analysis-report-" + timestamp + ".txt";
String csvFile = outputDir + "/summary-" + timestamp + ".csv";
analyzer.saveReport(reportFile);
analyzer.saveCSVSummary(csvFile);
System.out.println("\nReports generated:");
System.out.println(" - Analysis Report: " + reportFile);
System.out.println(" - CSV Summary: " + csvFile);
System.out.println();
// Print report to console
System.out.println(analyzer.generateReport());
} catch (IOException e) {
System.err.println("Failed to generate reports: " + e.getMessage());
e.printStackTrace();
}
}
/**
* Executa uma única instância da simulação.
*
* Idealmente, este método iniciaria todos os processos necessários
* (Interseções, Nó de Saída, Coordenador),
* esperaria que terminassem e depois recolheria os resultados.
*
* Atualmente, serve como um espaço reservado estrutural para demonstrar como
* funciona o pipeline de análise.
* Para correr uma simulação real, deve iniciar os componentes manualmente ou
* usar um script shell.
*/
private static SimulationRunResult executeSimulationRun(int runNumber, String configFile, String outputDir) {
SimulationRunResult result = new SimulationRunResult(runNumber, configFile);
try {
// TODO: Implement actual simulation execution
// This would involve:
// 1. Starting intersection processes
// 2. Starting exit node process
// 3. Starting dashboard process
// 4. Running coordinator
// 5. Collecting results from dashboard/exit node
// 6. Shutting down all processes
System.out.println("NOTE: Actual simulation execution not yet implemented.");
System.out.println("This batch runner demonstrates the framework structure.");
System.out.println("To run actual simulations, you need to:");
System.out.println(" 1. Start all intersection processes manually");
System.out.println(" 2. Start exit node process");
System.out.println(" 3. Start dashboard process");
System.out.println(" 4. Run coordinator with the configuration file");
System.out.println(" 5. Results will be collected automatically");
// Placeholder: simulate some results
// In real implementation, these would be collected from the actual simulation
result.setTotalVehiclesGenerated(100);
result.setTotalVehiclesCompleted(85);
result.setAverageSystemTime(120.5);
result.setMinSystemTime(45.2);
result.setMaxSystemTime(250.8);
result.setAverageWaitingTime(45.3);
return result;
} catch (Exception e) {
System.err.println("Error executing run " + runNumber + ": " + e.getMessage());
e.printStackTrace();
return null;
}
}
}

View File

@@ -6,8 +6,12 @@ import java.util.Map;
import sd.model.VehicleType; import sd.model.VehicleType;
/** /**
* Stores the results of a single simulation run. * Encapsula os dados telemétricos e estatísticos resultantes de uma única execução da simulação.
* Contains all key metrics for post-simulation analysis. * <p>
* Esta classe atua como um registo estruturado de métricas de desempenho, armazenando
* dados de latência (tempos de sistema/espera), vazão (throughput) e ocupação de recursos
* (tamanhos de fila). Os dados aqui contidos servem como base para a análise
* estatística agregada realizada pelo {@link MultiRunAnalyzer}.
*/ */
public class SimulationRunResult { public class SimulationRunResult {
@@ -17,11 +21,22 @@ public class SimulationRunResult {
private final long endTimeMillis; private final long endTimeMillis;
// Global metrics // Global metrics
/** Total de veículos instanciados pelos geradores durante a execução. */
private int totalVehiclesGenerated; private int totalVehiclesGenerated;
/** Total de veículos que completaram o percurso e saíram do sistema com sucesso. */
private int totalVehiclesCompleted; private int totalVehiclesCompleted;
/** Média global do tempo total (em segundos) desde a geração até a saída. */
private double averageSystemTime; // seconds private double averageSystemTime; // seconds
/** Menor tempo de sistema registado (em segundos). */
private double minSystemTime; // seconds private double minSystemTime; // seconds
/** Maior tempo de sistema registado (em segundos). */
private double maxSystemTime; // seconds private double maxSystemTime; // seconds
/** Média global do tempo (em segundos) que os veículos passaram parados em filas. */
private double averageWaitingTime; // seconds private double averageWaitingTime; // seconds
// Per-type metrics // Per-type metrics
@@ -34,6 +49,12 @@ public class SimulationRunResult {
private final Map<String, Double> avgQueueSizeByIntersection; private final Map<String, Double> avgQueueSizeByIntersection;
private final Map<String, Integer> vehiclesProcessedByIntersection; private final Map<String, Integer> vehiclesProcessedByIntersection;
/**
* Inicializa um novo contentor de resultados para uma execução específica.
*
* @param runNumber O identificador sequencial desta execução.
* @param configurationFile O ficheiro de configuração utilizado.
*/
public SimulationRunResult(int runNumber, String configurationFile) { public SimulationRunResult(int runNumber, String configurationFile) {
this.runNumber = runNumber; this.runNumber = runNumber;
this.configurationFile = configurationFile; this.configurationFile = configurationFile;
@@ -48,6 +69,10 @@ public class SimulationRunResult {
this.vehiclesProcessedByIntersection = new HashMap<>(); this.vehiclesProcessedByIntersection = new HashMap<>();
} }
/**
* Sinaliza o fim da recolha de dados para esta execução.
* (Placeholder para lógica de finalização de timestamps).
*/
public void markCompleted() { public void markCompleted() {
// This will be called when the run finishes // This will be called when the run finishes
} }
@@ -57,6 +82,11 @@ public class SimulationRunResult {
public String getConfigurationFile() { return configurationFile; } public String getConfigurationFile() { return configurationFile; }
public long getStartTimeMillis() { return startTimeMillis; } public long getStartTimeMillis() { return startTimeMillis; }
public long getEndTimeMillis() { return endTimeMillis; } public long getEndTimeMillis() { return endTimeMillis; }
/**
* Calcula a duração total da execução em milissegundos.
* @return Delta entre fim e início.
*/
public long getDurationMillis() { return endTimeMillis - startTimeMillis; } public long getDurationMillis() { return endTimeMillis - startTimeMillis; }
public int getTotalVehiclesGenerated() { return totalVehiclesGenerated; } public int getTotalVehiclesGenerated() { return totalVehiclesGenerated; }
@@ -66,21 +96,50 @@ public class SimulationRunResult {
public double getMaxSystemTime() { return maxSystemTime; } public double getMaxSystemTime() { return maxSystemTime; }
public double getAverageWaitingTime() { return averageWaitingTime; } public double getAverageWaitingTime() { return averageWaitingTime; }
/**
* Retorna o mapeamento de contagem de veículos por tipo.
* @return Uma cópia defensiva do mapa (snapshot).
*/
public Map<VehicleType, Integer> getVehicleCountByType() { public Map<VehicleType, Integer> getVehicleCountByType() {
return new HashMap<>(vehicleCountByType); return new HashMap<>(vehicleCountByType);
} }
/**
* Retorna o tempo médio no sistema segmentado por tipo de veículo.
* @return Uma cópia defensiva do mapa (snapshot).
*/
public Map<VehicleType, Double> getAvgSystemTimeByType() { public Map<VehicleType, Double> getAvgSystemTimeByType() {
return new HashMap<>(avgSystemTimeByType); return new HashMap<>(avgSystemTimeByType);
} }
/**
* Retorna o tempo médio de espera segmentado por tipo de veículo.
* @return Uma cópia defensiva do mapa (snapshot).
*/
public Map<VehicleType, Double> getAvgWaitTimeByType() { public Map<VehicleType, Double> getAvgWaitTimeByType() {
return new HashMap<>(avgWaitTimeByType); return new HashMap<>(avgWaitTimeByType);
} }
/**
* Retorna o tamanho máximo de fila registado por interseção (gargalos).
* @return Uma cópia defensiva do mapa (snapshot).
*/
public Map<String, Integer> getMaxQueueSizeByIntersection() { public Map<String, Integer> getMaxQueueSizeByIntersection() {
return new HashMap<>(maxQueueSizeByIntersection); return new HashMap<>(maxQueueSizeByIntersection);
} }
/**
* Retorna o tamanho médio das filas por interseção.
* @return Uma cópia defensiva do mapa (snapshot).
*/
public Map<String, Double> getAvgQueueSizeByIntersection() { public Map<String, Double> getAvgQueueSizeByIntersection() {
return new HashMap<>(avgQueueSizeByIntersection); return new HashMap<>(avgQueueSizeByIntersection);
} }
/**
* Retorna o total de veículos processados (throughput) por interseção.
* @return Uma cópia defensiva do mapa (snapshot).
*/
public Map<String, Integer> getVehiclesProcessedByIntersection() { public Map<String, Integer> getVehiclesProcessedByIntersection() {
return new HashMap<>(vehiclesProcessedByIntersection); return new HashMap<>(vehiclesProcessedByIntersection);
} }
@@ -124,13 +183,17 @@ public class SimulationRunResult {
vehiclesProcessedByIntersection.put(intersection, count); vehiclesProcessedByIntersection.put(intersection, count);
} }
/**
* Gera uma representação textual resumida das métricas principais da execução.
* Útil para logs rápidos e debugging.
*/
@Override @Override
public String toString() { public String toString() {
return String.format( return String.format(
"Run #%d [%s]:\n" + "Execução #%d [%s]:\n" +
" Generated: %d, Completed: %d (%.1f%%)\n" + " Gerados: %d, Completados: %d (%.1f%%)\n" +
" Avg System Time: %.2fs\n" + " Tempo Médio no Sistema: %.2fs\n" +
" Avg Waiting Time: %.2fs", " Tempo Médio de Espera: %.2fs",
runNumber, runNumber,
configurationFile, configurationFile,
totalVehiclesGenerated, totalVehiclesGenerated,

View File

@@ -5,13 +5,19 @@ import java.util.Collections;
import java.util.List; import java.util.List;
/** /**
* Statistical analysis utilities for simulation results. * Utilitário estático para processamento matemático e análise estatística dos dados da simulação.
* Calculates mean, standard deviation, and confidence intervals. * <p>
* Esta classe fornece algoritmos para cálculo de medidas de tendência central (média, mediana),
* dispersão (desvio padrão amostral) e inferência estatística (Intervalos de Confiança).
* É utilizada para normalizar e validar os resultados estocásticos obtidos através de
* múltiplas execuções do sistema.
*/ */
public class StatisticalAnalysis { public class StatisticalAnalysis {
/** /**
* Calculates the mean (average) of a list of values. * Calcula a média aritmética de um conjunto de valores.
* * @param values Lista de valores numéricos (double).
* @return A soma dos valores dividida pelo tamanho da amostra, ou 0.0 se a lista for nula/vazia.
*/ */
public static double mean(List<Double> values) { public static double mean(List<Double> values) {
if (values == null || values.isEmpty()) { if (values == null || values.isEmpty()) {
@@ -25,7 +31,13 @@ public class StatisticalAnalysis {
} }
/** /**
* Calculates the sample standard deviation. * Calcula o desvio padrão amostral (sample standard deviation).
* <p>
* Utiliza o denominador {@code n - 1} (Correção de Bessel) para fornecer um
* estimador não viesado da variância populacional, adequado para as amostras
* de simulação.
* * @param values Lista de observações.
* @return O desvio padrão calculado, ou 0.0 se o tamanho da amostra for < 2.
*/ */
public static double standardDeviation(List<Double> values) { public static double standardDeviation(List<Double> values) {
if (values == null || values.size() < 2) { if (values == null || values.size() < 2) {
@@ -45,10 +57,13 @@ public class StatisticalAnalysis {
} }
/** /**
* Calculates the 95% confidence interval for the mean. * Calcula o Intervalo de Confiança (IC) de 95% para a média.
* Uses t-distribution for small samples (n < 30). * <p>
* * Utiliza a distribuição t de Student para maior precisão em amostras pequenas (n < 30),
* @return Array of [lowerBound, upperBound] * onde a aproximação pela distribuição Normal (Z) seria inadequada. O intervalo define
* a faixa onde a verdadeira média populacional reside com 95% de probabilidade.
* * @param values Lista de observações.
* @return Um array de double onde índice 0 é o limite inferior e índice 1 é o limite superior.
*/ */
public static double[] confidenceInterval95(List<Double> values) { public static double[] confidenceInterval95(List<Double> values) {
if (values == null || values.size() < 2) { if (values == null || values.size() < 2) {
@@ -76,8 +91,12 @@ public class StatisticalAnalysis {
} }
/** /**
* Returns the t-critical value for 95% confidence interval. * Retorna o valor crítico t (t-score) para um IC de 95% (bicaudal).
* Approximations for common degrees of freedom (n-1). * <p>
* Baseia-se nos graus de liberdade (gl = n - 1). Para amostras grandes (gl >= 30),
* aproxima-se do valor Z de 1.96.
* * @param sampleSize O tamanho da amostra (n).
* @return O fator multiplicativo t apropriado.
*/ */
private static double getTCriticalValue(int sampleSize) { private static double getTCriticalValue(int sampleSize) {
int df = sampleSize - 1; // degrees of freedom int df = sampleSize - 1; // degrees of freedom
@@ -94,7 +113,9 @@ public class StatisticalAnalysis {
} }
/** /**
* Calculates the minimum value. * Identifica o valor mínimo absoluto na amostra.
* * @param values Lista de valores.
* @return O menor valor encontrado.
*/ */
public static double min(List<Double> values) { public static double min(List<Double> values) {
if (values == null || values.isEmpty()) { if (values == null || values.isEmpty()) {
@@ -104,7 +125,9 @@ public class StatisticalAnalysis {
} }
/** /**
* Calculates the maximum value. * Identifica o valor máximo absoluto na amostra.
* * @param values Lista de valores.
* @return O maior valor encontrado.
*/ */
public static double max(List<Double> values) { public static double max(List<Double> values) {
if (values == null || values.isEmpty()) { if (values == null || values.isEmpty()) {
@@ -114,7 +137,12 @@ public class StatisticalAnalysis {
} }
/** /**
* Calculates the median value. * Calcula a mediana da amostra.
* <p>
* <b>Nota de Desempenho:</b> Este método ordena uma cópia da lista, resultando em
* complexidade O(n log n).
* * @param values Lista de valores.
* @return O valor central (ou média dos dois centrais) da distribuição ordenada.
*/ */
public static double median(List<Double> values) { public static double median(List<Double> values) {
if (values == null || values.isEmpty()) { if (values == null || values.isEmpty()) {
@@ -133,7 +161,12 @@ public class StatisticalAnalysis {
} }
/** /**
* Formats a statistical summary as a string. * Formata um sumário estatístico completo para uma métrica específica.
* <p>
* Útil para logging e geração de relatórios textuais.
* * @param metricName Nome da métrica a ser exibida.
* @param values Os dados brutos associados à métrica.
* @return String formatada contendo Média, Desvio Padrão, IC95%, Min, Max e N.
*/ */
public static String formatSummary(String metricName, List<Double> values) { public static String formatSummary(String metricName, List<Double> values) {
if (values == null || values.isEmpty()) { if (values == null || values.isEmpty()) {

View File

@@ -14,17 +14,28 @@ import java.util.Properties;
import com.google.gson.Gson; import com.google.gson.Gson;
/** /**
* Carrega e gere configurações da simulação. * Responsável pelo carregamento, validação e acesso centralizado às configurações da simulação.
* * <p>
* <p>Lê propriedades de um ficheiro .properties e fornece getters * Esta classe atua como uma fachada (Facade) para os parâmetros do sistema, abstraindo a origem
* type-safe com valores padrão para robustez. * dos dados (ficheiros {@code .properties} ou JSON). Implementa uma estratégia robusta de
* carregamento de recursos, suportando tanto caminhos absolutos do sistema de ficheiros quanto
* recursos embutidos no <i>classpath</i>.
* <p>
* Além de propriedades chave-valor simples, gerencia a desserialização da topologia da rede
* através da classe interna {@link NetworkConfig}.
*/ */
public class SimulationConfig { public class SimulationConfig {
/** Propriedades carregadas do ficheiro */ /** Armazenamento em memória das propriedades chave-valor carregadas. */
private final Properties properties; private final Properties properties;
/** Estrutura hierárquica da configuração da rede carregada via JSON. */
private NetworkConfig networkConfig; private NetworkConfig networkConfig;
/**
* Objeto de transferência de dados (DTO) que representa a configuração global da rede.
* Mapeado a partir do ficheiro {@code network_config.json}.
*/
public static class NetworkConfig { public static class NetworkConfig {
private List<IntersectionConfig> intersections; private List<IntersectionConfig> intersections;
@@ -33,36 +44,45 @@ public class SimulationConfig {
} }
} }
/**
* DTO que representa a configuração de uma única interseção na topologia.
*/
public static class IntersectionConfig { public static class IntersectionConfig {
private String id; private String id;
private List<String> lights; private List<String> lights;
private Map<String, String> routes; private Map<String, String> routes;
/** @return O identificador único da interseção (ex: "Cr1"). */
public String getId() { public String getId() {
return id; return id;
} }
/** @return Lista de identificadores dos semáforos associados a esta interseção. */
public List<String> getLights() { public List<String> getLights() {
return lights; return lights;
} }
/** @return Mapa de roteamento definindo destinos alcançáveis e seus próximos saltos. */
public Map<String, String> getRoutes() { public Map<String, String> getRoutes() {
return routes; return routes;
} }
} }
/** /**
* Carrega propriedades do ficheiro especificado. * Inicializa o gestor de configuração carregando propriedades do caminho especificado.
* * * <p>Implementa uma estratégia de carregamento em cascata (fallback) para garantir robustez
* <p>Tenta múltiplas estratégias: * em diferentes ambientes de execução (IDE, JAR, Docker):
* <ol> * <ol>
* <li>Caminho direto no sistema de ficheiros * <li><b>Sistema de Ficheiros Direto:</b> Tenta carregar do caminho absoluto ou relativo.</li>
* <li>Recurso no classpath (com normalização automática) * <li><b>Classpath (Contexto):</b> Tenta carregar via {@code Thread.currentThread().getContextClassLoader()},
* <li>Recurso no classpath com barra inicial * normalizando prefixos como "src/main/resources" ou "classpath:".</li>
* <li><b>Classpath (Classe):</b> Tenta carregar via {@code SimulationConfig.class.getResourceAsStream},
* útil para recursos na raiz do JAR.</li>
* </ol> * </ol>
* *
* @param filePath caminho do ficheiro .properties * @param filePath O caminho ou nome do recurso do ficheiro {@code .properties}.
* @throws IOException se o ficheiro não for encontrado * @throws IOException Se o ficheiro não puder ser localizado em nenhuma das estratégias,
* com uma mensagem detalhada das tentativas falhadas.
*/ */
public SimulationConfig(String filePath) throws IOException { public SimulationConfig(String filePath) throws IOException {
properties = new Properties(); properties = new Properties();
@@ -135,6 +155,12 @@ public class SimulationConfig {
throw new IOException(errorMsg.toString(), fileSystemException); throw new IOException(errorMsg.toString(), fileSystemException);
} }
/**
* Carrega a configuração da topologia de rede a partir do ficheiro "network_config.json".
* <p>
* Utiliza a biblioteca Gson para desserialização. Em caso de falha, emite um aviso para o
* {@code System.err} mas não aborta a execução, permitindo o uso de defaults ou redes vazias.
*/
private void loadNetworkConfig() { private void loadNetworkConfig() {
try (InputStream is = getClass().getClassLoader().getResourceAsStream("network_config.json")) { try (InputStream is = getClass().getClassLoader().getResourceAsStream("network_config.json")) {
if (is == null) { if (is == null) {
@@ -151,6 +177,10 @@ public class SimulationConfig {
} }
} }
/**
* Retorna a configuração estruturada da rede.
* @return Objeto {@link NetworkConfig} ou null se o carregamento falhou.
*/
public NetworkConfig getNetworkConfig() { public NetworkConfig getNetworkConfig() {
return networkConfig; return networkConfig;
} }
@@ -158,56 +188,50 @@ public class SimulationConfig {
// --- Network configurations --- // --- Network configurations ---
/** /**
* Gets the host address for a specific intersection. * Obtém o endereço de host (nome DNS ou IP) para uma interseção específica.
* * * @param intersectionId O ID da interseção (ex: "Cr1").
* @param intersectionId The ID of the intersection (e.g., "Cr1"). * @return O host configurado ou "localhost" por omissão.
* @return The host (e.g., "localhost").
*/ */
public String getIntersectionHost(String intersectionId) { public String getIntersectionHost(String intersectionId) {
return properties.getProperty("intersection." + intersectionId + ".host", "localhost"); return properties.getProperty("intersection." + intersectionId + ".host", "localhost");
} }
/** /**
* Gets the port number for a specific intersection. * Obtém a porta de escuta TCP para uma interseção específica.
* * * @param intersectionId O ID da interseção (ex: "Cr1").
* @param intersectionId The ID of the intersection (e.g., "Cr1"). * @return O número da porta. Retorna 0 se não configurado.
* @return The port number.
*/ */
public int getIntersectionPort(String intersectionId) { public int getIntersectionPort(String intersectionId) {
return Integer.parseInt(properties.getProperty("intersection." + intersectionId + ".port", "0")); return Integer.parseInt(properties.getProperty("intersection." + intersectionId + ".port", "0"));
} }
/** /**
* Gets the host address for the dashboard server. * Obtém o endereço de host do servidor de Dashboard (monitorização).
* * @return O host do dashboard (padrão: "localhost").
* @return The dashboard host.
*/ */
public String getDashboardHost() { public String getDashboardHost() {
return properties.getProperty("dashboard.host", "localhost"); return properties.getProperty("dashboard.host", "localhost");
} }
/** /**
* Gets the port number for the dashboard server. * Obtém a porta de conexão do servidor de Dashboard.
* * @return A porta do dashboard (padrão: 9000).
* @return The dashboard port.
*/ */
public int getDashboardPort() { public int getDashboardPort() {
return Integer.parseInt(properties.getProperty("dashboard.port", "9000")); return Integer.parseInt(properties.getProperty("dashboard.port", "9000"));
} }
/** /**
* Gets the host address for the exit node. * Obtém o endereço de host do nó de saída (Exit Node), para onde os veículos são encaminhados ao sair da malha.
* * @return O host do nó de saída (padrão: "localhost").
* @return The exit node host.
*/ */
public String getExitHost() { public String getExitHost() {
return properties.getProperty("exit.host", "localhost"); return properties.getProperty("exit.host", "localhost");
} }
/** /**
* Gets the port number for the exit node. * Obtém a porta de conexão do nó de saída.
* * @return A porta do nó de saída (padrão: 9001).
* @return The exit node port.
*/ */
public int getExitPort() { public int getExitPort() {
return Integer.parseInt(properties.getProperty("exit.port", "9001")); return Integer.parseInt(properties.getProperty("exit.port", "9001"));
@@ -216,68 +240,76 @@ public class SimulationConfig {
// --- Simulation configurations --- // --- Simulation configurations ---
/** /**
* Gets the total duration of the simulation in virtual seconds. * Define a duração total da execução da simulação em segundos virtuais.
* * @return A duração em segundos (padrão: 3600).
* @return The simulation duration.
*/ */
public double getSimulationDuration() { public double getSimulationDuration() {
return Double.parseDouble(properties.getProperty("simulation.duration", "3600")); return Double.parseDouble(properties.getProperty("simulation.duration", "3600"));
} }
/** /**
* Get time scaling factor for visualization. * Obtém o fator de escala temporal para visualização/execução.
* 0 = instant (pure DES), 0.01 = 100x speed, 0.1 = 10x speed, 1.0 = real-time * <ul>
* <li>0.0: Execução instantânea (DES puro, velocidade máxima).</li>
* <li>1.0: Tempo real (1 segundo simulado = 1 segundo real).</li>
* <li>0.01: Acelerado 100x.</li>
* </ul>
* @return O fator de escala.
*/ */
public double getTimeScale() { public double getTimeScale() {
return Double.parseDouble(properties.getProperty("simulation.time.scale", "0")); return Double.parseDouble(properties.getProperty("simulation.time.scale", "0"));
} }
/** /**
* Gets the drain time (in virtual seconds) to allow vehicles to exit after * Obtém o tempo de "drenagem" (drain time) em segundos virtuais.
* generation stops. * <p>
* * Este é o período adicional executado após o fim da geração de veículos para permitir
* @return The drain time. * que os veículos restantes no sistema completem os seus percursos.
* @return O tempo de drenagem (padrão: 60.0s).
*/ */
public double getDrainTime() { public double getDrainTime() {
return Double.parseDouble(properties.getProperty("simulation.drain.time", "60.0")); return Double.parseDouble(properties.getProperty("simulation.drain.time", "60.0"));
} }
/** /**
* Gets the vehicle arrival model ("POISSON" or "FIXED"). * Determina o modelo estocástico utilizado para a chegada de veículos.
* * @return "POISSON" (distribuição exponencial) ou "FIXED" (intervalo determinístico).
* @return The arrival model as a string.
*/ */
public String getArrivalModel() { public String getArrivalModel() {
return properties.getProperty("simulation.arrival.model", "POISSON"); return properties.getProperty("simulation.arrival.model", "POISSON");
} }
/** /**
* Gets the average arrival rate (lambda) for the POISSON model. * Obtém a taxa média de chegada (lambda) para o modelo Poisson.
* This represents the average number of vehicles arriving per second. * @return Veículos por segundo (padrão: 0.5).
*
* @return The arrival rate.
*/ */
public double getArrivalRate() { public double getArrivalRate() {
return Double.parseDouble(properties.getProperty("simulation.arrival.rate", "0.5")); return Double.parseDouble(properties.getProperty("simulation.arrival.rate", "0.5"));
} }
/** /**
* Gets the fixed time interval between vehicle arrivals for the FIXED model. * Obtém o intervalo fixo entre chegadas para o modelo determinístico.
* * @return O intervalo em segundos (padrão: 2.0).
* @return The fixed interval in seconds.
*/ */
public double getFixedArrivalInterval() { public double getFixedArrivalInterval() {
return Double.parseDouble(properties.getProperty("simulation.arrival.fixed.interval", "2.0")); return Double.parseDouble(properties.getProperty("simulation.arrival.fixed.interval", "2.0"));
} }
/**
* Obtém a política de roteamento utilizada pelos veículos para navegar na malha.
* @return A política: "RANDOM", "SHORTEST_PATH" ou "LEAST_CONGESTED".
*/
public String getRoutingPolicy() {
return properties.getProperty("simulation.routing.policy", "RANDOM");
}
// --- Traffic light configurations --- // --- Traffic light configurations ---
/** /**
* Gets the duration of the GREEN light state for a specific traffic light. * Obtém a duração do estado VERDE para um semáforo específico.
* * * @param intersectionId ID da interseção.
* @param intersectionId The ID of the intersection (e.g., "Cr1"). * @param direction Direção do fluxo (ex: "North").
* @param direction The direction of the light (e.g., "North"). * @return Duração em segundos (padrão: 30.0).
* @return The green light time in seconds.
*/ */
public double getTrafficLightGreenTime(String intersectionId, String direction) { public double getTrafficLightGreenTime(String intersectionId, String direction) {
String key = "trafficlight." + intersectionId + "." + direction + ".green"; String key = "trafficlight." + intersectionId + "." + direction + ".green";
@@ -285,11 +317,10 @@ public class SimulationConfig {
} }
/** /**
* Gets the duration of the RED light state for a specific traffic light. * Obtém a duração do estado VERMELHO para um semáforo específico.
* * * @param intersectionId ID da interseção.
* @param intersectionId The ID of the intersection (e.g., "Cr1"). * @param direction Direção do fluxo.
* @param direction The direction of the light (e.g., "North"). * @return Duração em segundos (padrão: 30.0).
* @return The red light time in seconds.
*/ */
public double getTrafficLightRedTime(String intersectionId, String direction) { public double getTrafficLightRedTime(String intersectionId, String direction) {
String key = "trafficlight." + intersectionId + "." + direction + ".red"; String key = "trafficlight." + intersectionId + "." + direction + ".red";
@@ -299,83 +330,74 @@ public class SimulationConfig {
// --- Vehicle configurations --- // --- Vehicle configurations ---
/** /**
* Gets the probability (0.0 to 1.0) that a generated vehicle is of type LIGHT. * Probabilidade (0.0 a 1.0) de geração de um veículo do tipo LIGEIRO (LIGHT).
* * @return Probabilidade (padrão: 0.7).
* @return The probability for LIGHT vehicles.
*/ */
public double getLightVehicleProbability() { public double getLightVehicleProbability() {
return Double.parseDouble(properties.getProperty("vehicle.probability.light", "0.7")); return Double.parseDouble(properties.getProperty("vehicle.probability.light", "0.7"));
} }
/** /**
* Gets the average time it takes a LIGHT vehicle to cross an intersection. * Tempo médio necessário para um veículo LIGEIRO atravessar uma interseção.
* * @return Tempo em segundos (padrão: 2.0).
* @return The crossing time in seconds.
*/ */
public double getLightVehicleCrossingTime() { public double getLightVehicleCrossingTime() {
return Double.parseDouble(properties.getProperty("vehicle.crossing.time.light", "2.0")); return Double.parseDouble(properties.getProperty("vehicle.crossing.time.light", "2.0"));
} }
/** /**
* Gets the probability (0.0 to 1.0) that a generated vehicle is of type BIKE. * Probabilidade (0.0 a 1.0) de geração de um veículo do tipo BICICLETA (BIKE).
* * @return Probabilidade (padrão: 0.0).
* @return The probability for BIKE vehicles.
*/ */
public double getBikeVehicleProbability() { public double getBikeVehicleProbability() {
return Double.parseDouble(properties.getProperty("vehicle.probability.bike", "0.0")); return Double.parseDouble(properties.getProperty("vehicle.probability.bike", "0.0"));
} }
/** /**
* Gets the average time it takes a BIKE vehicle to cross an intersection. * Tempo médio necessário para uma BICICLETA atravessar uma interseção.
* * @return Tempo em segundos (padrão: 1.5).
* @return The crossing time in seconds.
*/ */
public double getBikeVehicleCrossingTime() { public double getBikeVehicleCrossingTime() {
return Double.parseDouble(properties.getProperty("vehicle.crossing.time.bike", "1.5")); return Double.parseDouble(properties.getProperty("vehicle.crossing.time.bike", "1.5"));
} }
/** /**
* Gets the probability (0.0 to 1.0) that a generated vehicle is of type HEAVY. * Probabilidade (0.0 a 1.0) de geração de um veículo PESADO (HEAVY).
* * @return Probabilidade (padrão: 0.0).
* @return The probability for HEAVY vehicles.
*/ */
public double getHeavyVehicleProbability() { public double getHeavyVehicleProbability() {
return Double.parseDouble(properties.getProperty("vehicle.probability.heavy", "0.0")); return Double.parseDouble(properties.getProperty("vehicle.probability.heavy", "0.0"));
} }
/** /**
* Gets the average time it takes a HEAVY vehicle to cross an intersection. * Tempo médio necessário para um veículo PESADO atravessar uma interseção.
* * @return Tempo em segundos (padrão: 4.0).
* @return The crossing time in seconds.
*/ */
public double getHeavyVehicleCrossingTime() { public double getHeavyVehicleCrossingTime() {
return Double.parseDouble(properties.getProperty("vehicle.crossing.time.heavy", "4.0")); return Double.parseDouble(properties.getProperty("vehicle.crossing.time.heavy", "4.0"));
} }
/** /**
* Gets the base travel time between intersections for light vehicles. * Define o tempo base de viagem entre interseções para veículos padrão.
* * @return Tempo em segundos (padrão: 8.0).
* @return The base travel time in seconds.
*/ */
public double getBaseTravelTime() { public double getBaseTravelTime() {
return Double.parseDouble(properties.getProperty("vehicle.travel.time.base", "8.0")); return Double.parseDouble(properties.getProperty("vehicle.travel.time.base", "8.0"));
} }
/** /**
* Gets the travel time multiplier for bike vehicles. * Multiplicador de tempo de viagem para bicicletas.
* Bike travel time = base time × this multiplier. * <p>Tempo efetivo = Base * Multiplicador.
* * @return Fator multiplicativo (padrão: 0.5).
* @return The multiplier for bike travel time.
*/ */
public double getBikeTravelTimeMultiplier() { public double getBikeTravelTimeMultiplier() {
return Double.parseDouble(properties.getProperty("vehicle.travel.time.bike.multiplier", "0.5")); return Double.parseDouble(properties.getProperty("vehicle.travel.time.bike.multiplier", "0.5"));
} }
/** /**
* Gets the travel time multiplier for heavy vehicles. * Multiplicador de tempo de viagem para veículos pesados.
* Heavy vehicle travel time = base time × this multiplier. * <p>Tempo efetivo = Base * Multiplicador.
* * @return Fator multiplicativo (padrão: 4.0).
* @return The multiplier for heavy vehicle travel time.
*/ */
public double getHeavyTravelTimeMultiplier() { public double getHeavyTravelTimeMultiplier() {
return Double.parseDouble(properties.getProperty("vehicle.travel.time.heavy.multiplier", "4.0")); return Double.parseDouble(properties.getProperty("vehicle.travel.time.heavy.multiplier", "4.0"));
@@ -384,9 +406,8 @@ public class SimulationConfig {
// --- Statistics --- // --- Statistics ---
/** /**
* Gets the interval (in virtual seconds) between periodic statistics updates. * Intervalo de tempo (em segundos virtuais) para agregação e envio de estatísticas periódicas.
* * @return Intervalo de atualização (padrão: 1.0).
* @return The statistics update interval.
*/ */
public double getStatisticsUpdateInterval() { public double getStatisticsUpdateInterval() {
return Double.parseDouble(properties.getProperty("statistics.update.interval", "1.0")); return Double.parseDouble(properties.getProperty("statistics.update.interval", "1.0"));
@@ -395,21 +416,19 @@ public class SimulationConfig {
// --- Generic getters --- // --- Generic getters ---
/** /**
* Generic method to get any property as a string, with a default value. * Recupera uma propriedade genérica como String, com valor padrão de segurança.
* * * @param key A chave da propriedade.
* @param key The property key. * @param defaultValue O valor a retornar caso a chave não exista.
* @param defaultValue The value to return if the key is not found. * @return O valor da propriedade ou o default.
* @return The property value or the default.
*/ */
public String getProperty(String key, String defaultValue) { public String getProperty(String key, String defaultValue) {
return properties.getProperty(key, defaultValue); return properties.getProperty(key, defaultValue);
} }
/** /**
* Generic method to get any property as a string. * Recupera uma propriedade genérica como String.
* * * @param key A chave da propriedade.
* @param key The property key. * @return O valor da propriedade ou null se não encontrada.
* @return The property value, or null if not found.
*/ */
public String getProperty(String key) { public String getProperty(String key) {
return properties.getProperty(key); return properties.getProperty(key);

View File

@@ -5,6 +5,7 @@ import java.util.HashMap;
import java.util.Map; import java.util.Map;
import sd.config.SimulationConfig; import sd.config.SimulationConfig;
import sd.dashboard.DashboardStatistics;
import sd.dashboard.StatsUpdatePayload; import sd.dashboard.StatsUpdatePayload;
import sd.des.DESEventType; import sd.des.DESEventType;
import sd.des.EventQueue; import sd.des.EventQueue;
@@ -14,37 +15,62 @@ import sd.logging.EventLogger;
import sd.model.Message; import sd.model.Message;
import sd.model.MessageType; import sd.model.MessageType;
import sd.model.Vehicle; import sd.model.Vehicle;
import sd.routing.LeastCongestedRouteSelector;
import sd.routing.RandomRouteSelector;
import sd.routing.RouteSelector;
import sd.routing.RoutingPolicy;
import sd.routing.ShortestPathRouteSelector;
import sd.serialization.SerializationException; import sd.serialization.SerializationException;
import sd.util.VehicleGenerator; import sd.util.VehicleGenerator;
/** /**
* Coordenador central da simulação distribuída. * Coordenador central da arquitetura de simulação distribuída.
* * <p>
* <p>Responsabilidades: * Este processo atua como o "cérebro" da simulação, sendo responsável por:
* <ol> * <ol>
* <li>Gerar veículos segundo modelo configurado (Poisson/Fixed) * <li><b>Orquestração DES:</b> Gerir o relógio global ({@link SimulationClock}) e a fila de eventos prioritária.</li>
* <li>Injetar veículos nas interseções de entrada * <li><b>Geração de Carga:</b> Injetar veículos na malha viária seguindo distribuições estocásticas (Poisson) ou determinísticas.</li>
* <li>Gerir relógio global e sincronizar componentes * <li><b>Encaminhamento Dinâmico:</b> Decidir as rotas dos veículos com base na política ativa (Random, Shortest Path, Least Congested).</li>
* <li><b>Sincronização:</b> Garantir que todos os nós (Interseções e Dashboard) operem em uníssono.</li>
* </ol> * </ol>
*
* <p>Usa motor DES para agendar eventos de geração com precisão.
* Mantém fila de prioridade e processa eventos em ordem cronológica.
*/ */
public class CoordinatorProcess { public class CoordinatorProcess {
private final SimulationConfig config; private final SimulationConfig config;
private final VehicleGenerator vehicleGenerator; private final VehicleGenerator vehicleGenerator;
/** Mapa de clientes TCP persistentes para cada interseção (Worker Nodes). */
private final Map<String, SocketClient> intersectionClients; private final Map<String, SocketClient> intersectionClients;
private SocketClient dashboardClient; private SocketClient dashboardClient;
// Componentes DES (Discrete Event Simulation)
private final SimulationClock clock; private final SimulationClock clock;
private final EventQueue eventQueue; private final EventQueue eventQueue;
private final EventLogger eventLogger; private final EventLogger eventLogger;
// Estado da simulação
private int vehicleCounter; private int vehicleCounter;
private boolean running; private boolean running;
private double timeScale; private double timeScale;
private RouteSelector currentRouteSelector;
/** Referência para estatísticas do dashboard para polling de mudanças de política. */
private DashboardStatistics dashboardStatistics;
/**
* Monitorização local (aproximada) dos tamanhos de fila nas interseções.
* <p>
* Utilizado exclusivamente pela política {@link LeastCongestedRouteSelector}.
* O coordenador incrementa este contador ao enviar um veículo para uma interseção.
* Nota: Esta é uma visão "borda" (edge) e pode não refletir a saída em tempo real
* dos veículos, mas serve como heurística suficiente para balanceamento de carga.
*/
private final Map<String, Integer> intersectionQueueSizes;
/**
* Ponto de entrada do processo Coordenador.
* Carrega configurações, estabelece conexões TCP e inicia o loop de eventos.
*/
public static void main(String[] args) { public static void main(String[] args) {
System.out.println("=".repeat(60)); System.out.println("=".repeat(60));
System.out.println("COORDINATOR PROCESS - DISTRIBUTED TRAFFIC SIMULATION"); System.out.println("COORDINATOR PROCESS - DISTRIBUTED TRAFFIC SIMULATION");
@@ -75,13 +101,24 @@ public class CoordinatorProcess {
} }
} }
/**
* Inicializa o coordenador com a configuração fornecida.
* Configura o motor DES, logging e o seletor de rotas inicial.
*
* @param config Objeto de configuração carregado.
*/
public CoordinatorProcess(SimulationConfig config) { public CoordinatorProcess(SimulationConfig config) {
this.config = config; this.config = config;
this.vehicleGenerator = new VehicleGenerator(config);
// Inicializa o RouteSelector baseado na política configurada
this.currentRouteSelector = createRouteSelector(config.getRoutingPolicy());
this.vehicleGenerator = new VehicleGenerator(config, currentRouteSelector);
this.intersectionClients = new HashMap<>(); this.intersectionClients = new HashMap<>();
this.vehicleCounter = 0; this.vehicleCounter = 0;
this.running = false; this.running = false;
this.timeScale = config.getTimeScale(); this.timeScale = config.getTimeScale();
this.intersectionQueueSizes = new HashMap<>();
this.clock = new SimulationClock(); this.clock = new SimulationClock();
this.eventQueue = new EventQueue(true); this.eventQueue = new EventQueue(true);
@@ -94,9 +131,46 @@ public class CoordinatorProcess {
System.out.println(" - Simulation duration: " + config.getSimulationDuration() + "s"); System.out.println(" - Simulation duration: " + config.getSimulationDuration() + "s");
System.out.println(" - Arrival model: " + config.getArrivalModel()); System.out.println(" - Arrival model: " + config.getArrivalModel());
System.out.println(" - Arrival rate: " + config.getArrivalRate() + " vehicles/s"); System.out.println(" - Arrival rate: " + config.getArrivalRate() + " vehicles/s");
System.out.println(" - Routing policy: " + config.getRoutingPolicy());
System.out.println(" - DES Mode: ENABLED (Event-driven, no time-stepping)"); System.out.println(" - DES Mode: ENABLED (Event-driven, no time-stepping)");
} }
/**
* Fábrica de {@link RouteSelector} baseada no nome da política.
* * @param policyName Nome da política (RANDOM, SHORTEST_PATH, LEAST_CONGESTED).
* @return Uma instância da estratégia de roteamento.
*/
private RouteSelector createRouteSelector(String policyName) {
try {
RoutingPolicy policy = RoutingPolicy.valueOf(policyName.toUpperCase());
switch (policy) {
case RANDOM:
System.out.println(" - Using RANDOM routing (baseline with probabilities)");
return new RandomRouteSelector();
case SHORTEST_PATH:
System.out.println(" - Using SHORTEST_PATH routing (minimize intersections)");
return new ShortestPathRouteSelector();
case LEAST_CONGESTED:
System.out.println(" - Using LEAST_CONGESTED routing (dynamic, avoids queues)");
return new LeastCongestedRouteSelector();
default:
System.err.println(" ! Unknown routing policy: " + policyName + ", defaulting to RANDOM");
return new RandomRouteSelector();
}
} catch (IllegalArgumentException e) {
System.err.println(" ! Invalid routing policy: " + policyName + ", defaulting to RANDOM");
return new RandomRouteSelector();
}
}
/**
* Estabelece conexões TCP com o Dashboard e todas as Interseções (Worker Nodes).
* Essencial para o envio de comandos de controle e injeção de veículos.
*/
public void initialize() { public void initialize() {
// Connect to dashboard first // Connect to dashboard first
connectToDashboard(); connectToDashboard();
@@ -126,6 +200,15 @@ public class CoordinatorProcess {
} }
} }
/**
* Loop principal da simulação (DES Engine).
* <p>
* Executa a sequência:
* 1. Retira o próximo evento da fila prioritária.
* 2. Avança o relógio virtual para o timestamp do evento.
* 3. Aplica escala temporal (Time Scale) para visualização, se necessário.
* 4. Processa o evento.
*/
public void run() { public void run() {
double duration = config.getSimulationDuration(); double duration = config.getSimulationDuration();
double drainTime = config.getDrainTime(); double drainTime = config.getDrainTime();
@@ -205,14 +288,9 @@ public class CoordinatorProcess {
} }
/** /**
* Trata um único evento de simulação. * Trata o processamento de um evento DES retirado da fila.
* * * @param event O evento a ser processado.
* É aqui que a magia acontece. Dependendo do tipo de evento (como * @param generationDuration Duração da fase de geração ativa (antes do 'drain time').
* VEHICLE_GENERATION),
* atualizamos o estado do mundo. Para a geração de veículos, criamos um novo
* veículo,
* enviamo-lo para uma interseção e depois agendamos o *próximo* evento de
* geração.
*/ */
private void processEvent(SimulationEvent event, double generationDuration) { private void processEvent(SimulationEvent event, double generationDuration) {
double currentTime = clock.getCurrentTime(); double currentTime = clock.getCurrentTime();
@@ -221,9 +299,12 @@ public class CoordinatorProcess {
case VEHICLE_GENERATION: case VEHICLE_GENERATION:
// Only generate if we're still in the generation phase // Only generate if we're still in the generation phase
if (currentTime < generationDuration) { if (currentTime < generationDuration) {
// Check for routing policy changes from dashboard
checkForPolicyChanges();
generateAndSendVehicle(); generateAndSendVehicle();
// Schedule next vehicle generation // Schedule next vehicle generation (Recursive scheduling)
double nextArrivalTime = vehicleGenerator.getNextArrivalTime(currentTime); double nextArrivalTime = vehicleGenerator.getNextArrivalTime(currentTime);
eventQueue.schedule(new SimulationEvent( eventQueue.schedule(new SimulationEvent(
nextArrivalTime, nextArrivalTime,
@@ -247,9 +328,8 @@ public class CoordinatorProcess {
} }
/** /**
* Guarda o histórico completo de eventos de simulação num ficheiro de texto. * Exporta o log completo de eventos DES para auditoria e debug.
* Isto permite-nos auditar exatamente o que aconteceu e quando, o que é crucial * Caminho: {@code logs/coordinator-event-history.txt}.
* para depuração e verificação.
*/ */
private void exportEventHistory() { private void exportEventHistory() {
try (java.io.PrintWriter writer = new java.io.PrintWriter( try (java.io.PrintWriter writer = new java.io.PrintWriter(
@@ -262,9 +342,16 @@ public class CoordinatorProcess {
} }
} }
/**
* Gera um novo veículo e envia-o via TCP para a interseção de entrada apropriada.
* Também atualiza o rastreio local de filas para balanceamento de carga.
*/
private void generateAndSendVehicle() { private void generateAndSendVehicle() {
double currentTime = clock.getCurrentTime(); double currentTime = clock.getCurrentTime();
Vehicle vehicle = vehicleGenerator.generateVehicle("V" + (++vehicleCounter), currentTime);
// Usa os tamanhos de fila rastreados localmente para política LEAST_CONGESTED
// Isto permite roteamento dinâmico baseado no estado atual da rede
Vehicle vehicle = vehicleGenerator.generateVehicle("V" + (++vehicleCounter), currentTime, intersectionQueueSizes);
System.out.printf("[t=%.2f] Vehicle %s generated (type=%s, route=%s)%n", System.out.printf("[t=%.2f] Vehicle %s generated (type=%s, route=%s)%n",
currentTime, vehicle.getId(), vehicle.getType(), vehicle.getRoute()); currentTime, vehicle.getId(), vehicle.getType(), vehicle.getRoute());
@@ -273,6 +360,11 @@ public class CoordinatorProcess {
eventLogger.log(sd.logging.EventType.VEHICLE_GENERATED, "Coordinator", eventLogger.log(sd.logging.EventType.VEHICLE_GENERATED, "Coordinator",
String.format("[%s] Type: %s, Route: %s", vehicle.getId(), vehicle.getType(), vehicle.getRoute())); String.format("[%s] Type: %s, Route: %s", vehicle.getId(), vehicle.getType(), vehicle.getRoute()));
// Update local queue size tracking (increment first intersection's queue)
String firstIntersection = vehicle.getRoute().get(0);
intersectionQueueSizes.put(firstIntersection,
intersectionQueueSizes.getOrDefault(firstIntersection, 0) + 1);
// Send generation count to dashboard // Send generation count to dashboard
sendGenerationStatsToDashboard(); sendGenerationStatsToDashboard();
@@ -285,6 +377,9 @@ public class CoordinatorProcess {
sendVehicleToIntersection(vehicle, entryIntersection); sendVehicleToIntersection(vehicle, entryIntersection);
} }
/**
* Serializa e transmite o objeto Veículo para o nó (interseção) de destino.
*/
private void sendVehicleToIntersection(Vehicle vehicle, String intersectionId) { private void sendVehicleToIntersection(Vehicle vehicle, String intersectionId) {
SocketClient client = intersectionClients.get(intersectionId); SocketClient client = intersectionClients.get(intersectionId);
@@ -309,6 +404,9 @@ public class CoordinatorProcess {
} }
} }
/**
* Encerra graciosamente a simulação, enviando sinais de SHUTDOWN para todos os nós.
*/
public void shutdown() { public void shutdown() {
System.out.println(); System.out.println();
System.out.println("=".repeat(60)); System.out.println("=".repeat(60));
@@ -344,6 +442,65 @@ public class CoordinatorProcess {
running = false; running = false;
} }
/**
* Altera dinamicamente a política de roteamento durante a simulação (Hot-swap).
* Thread-safe.
* * @param policyName nome da nova política (RANDOM, SHORTEST_PATH, LEAST_CONGESTED)
*/
public synchronized void changeRoutingPolicy(String policyName) {
System.out.println("\n" + "=".repeat(60));
System.out.println("ROUTING POLICY CHANGE REQUEST");
System.out.println("=".repeat(60));
System.out.println("Current policy: " + getCurrentPolicyName());
System.out.println("Requested policy: " + policyName);
RouteSelector newSelector = createRouteSelector(policyName);
this.currentRouteSelector = newSelector;
this.vehicleGenerator.setRouteSelector(newSelector);
System.out.println("Routing policy successfully changed to: " + policyName);
System.out.println(" - New vehicles will use the updated policy");
System.out.println("=".repeat(60) + "\n");
eventLogger.log(sd.logging.EventType.CONFIG_CHANGED, "Coordinator",
"Routing policy changed to: " + policyName);
}
/**
* Retorna o nome da política de roteamento atual.
*/
private String getCurrentPolicyName() {
if (currentRouteSelector instanceof RandomRouteSelector) {
return "RANDOM";
} else if (currentRouteSelector instanceof ShortestPathRouteSelector) {
return "SHORTEST_PATH";
} else if (currentRouteSelector instanceof LeastCongestedRouteSelector) {
return "LEAST_CONGESTED";
}
return "UNKNOWN";
}
/**
* Verifica se há solicitação de mudança de política proveniente do dashboard
* e aplica a alteração se houver.
*/
private void checkForPolicyChanges() {
if (dashboardStatistics != null) {
String requestedPolicy = dashboardStatistics.getAndClearRequestedRoutingPolicy();
if (requestedPolicy != null && !requestedPolicy.isEmpty()) {
changeRoutingPolicy(requestedPolicy);
}
}
}
/**
* Injeta a referência para as estatísticas do dashboard.
* Permite que o coordenador consuma intenções de mudança de política do utilizador.
*/
public void setDashboardStatistics(DashboardStatistics stats) {
this.dashboardStatistics = stats;
}
private void connectToDashboard() { private void connectToDashboard() {
try { try {
String host = config.getDashboardHost(); String host = config.getDashboardHost();
@@ -382,6 +539,11 @@ public class CoordinatorProcess {
} }
} }
/**
* Sincronização Global: Envia o timestamp de início (System.currentTimeMillis)
* para todos os componentes distribuídos, garantindo uma base de tempo comum
* para métricas de latência.
*/
private void sendSimulationStartTime() { private void sendSimulationStartTime() {
long startTimeMillis = System.currentTimeMillis(); long startTimeMillis = System.currentTimeMillis();

View File

@@ -10,10 +10,14 @@ import sd.serialization.SerializationException;
import sd.serialization.SerializerFactory; import sd.serialization.SerializerFactory;
/** /**
* Cliente socket para comunicação com um processo de interseção. * Abstração de cliente TCP para comunicação outbound (de saída) com nós da rede.
* * <p>
* <p>Gere uma ligação TCP persistente para uma interseção, * Esta classe encapsula a gestão do socket raw, oferecendo uma interface de alto nível
* fornecendo uma forma simples de enviar mensagens serializadas.</p> * para envio de objetos {@link Message}. Implementa o protocolo de camada de aplicação
* proprietário, garantindo a serialização correta e o enquadramento (framing) dos dados
* na stream TCP.
* <p>
* É utilizada pelo Coordenador para controlar Interseções e enviar telemetria para o Dashboard.
*/ */
public class SocketClient { public class SocketClient {
@@ -25,11 +29,11 @@ public class SocketClient {
private MessageSerializer serializer; private MessageSerializer serializer;
/** /**
* Cria um novo cliente socket para uma interseção. * Instancia um novo cliente socket configurado para um destino específico.
* *
* @param intersectionId ID da interseção (ex: "Cr1") * @param intersectionId Identificador lógico do nó de destino (ex: "Cr1", "Dashboard").
* @param host endereço do host (ex: "localhost") * @param host Endereço IP ou hostname do destino.
* @param port número da porta * @param port Porta TCP de escuta do destino.
*/ */
public SocketClient(String intersectionId, String host, int port) { public SocketClient(String intersectionId, String host, int port) {
this.intersectionId = intersectionId; this.intersectionId = intersectionId;
@@ -39,9 +43,8 @@ public class SocketClient {
} }
/** /**
* Liga-se ao processo da interseção via TCP. * Estabelece a conexão TCP (Handshake SYN/ACK) com o host remoto.
* * * @throws IOException Se o host for inalcançável ou a conexão for recusada.
* @throws IOException se a ligação não puder ser estabelecida
*/ */
public void connect() throws IOException { public void connect() throws IOException {
try { try {
@@ -55,12 +58,22 @@ public class SocketClient {
} }
/** /**
* Envia uma mensagem para a interseção ligada. * Serializa e transmite uma mensagem através do socket conectado.
* A mensagem é serializada e enviada pelo socket. * <p>
* <b>Protocolo de Envio (Length-Prefix Framing):</b>
* <ol>
* <li>Serializa o objeto {@link Message} para um array de bytes.</li>
* <li>Calcula o tamanho (N) do array.</li>
* <li>Escreve um cabeçalho de 4 bytes contendo N (Big-Endian).</li>
* <li>Escreve os N bytes do payload (corpo da mensagem).</li>
* <li>Realiza flush no stream para forçar o envio imediato do pacote TCP.</li>
* </ol>
* Este mecanismo garante que o recetor saiba exatamente quantos bytes ler,
* prevenindo problemas de fragmentação ou aglutinação de pacotes TCP.
* *
* @param message mensagem a enviar * @param message O objeto de domínio a ser enviado.
* @throws SerializationException se a serialização falhar * @throws SerializationException Se o objeto não puder ser convertido para bytes.
* @throws IOException se a escrita no socket falhar * @throws IOException Se houver falha na escrita do socket (ex: conexão resetada).
*/ */
public void send(Message message) throws SerializationException, IOException { public void send(Message message) throws SerializationException, IOException {
if (socket == null || socket.isClosed()) { if (socket == null || socket.isClosed()) {
@@ -71,11 +84,13 @@ public class SocketClient {
byte[] data = serializer.serialize(message); byte[] data = serializer.serialize(message);
int length = data.length; int length = data.length;
// Write 4-byte length header (Big Endian)
outputStream.write((length >> 24) & 0xFF); outputStream.write((length >> 24) & 0xFF);
outputStream.write((length >> 16) & 0xFF); outputStream.write((length >> 16) & 0xFF);
outputStream.write((length >> 8) & 0xFF); outputStream.write((length >> 8) & 0xFF);
outputStream.write(length & 0xFF); outputStream.write(length & 0xFF);
// Write payload
outputStream.write(data); outputStream.write(data);
outputStream.flush(); outputStream.flush();
@@ -86,8 +101,10 @@ public class SocketClient {
} }
/** /**
* Closes the socket connection safely. * Realiza o encerramento gracioso (graceful shutdown) da conexão.
* Calling it multiple times wont cause issues. * Liberta os recursos do sistema operativo (descritores de arquivo).
* <p>
* Operação idempotente: pode ser chamada múltiplas vezes sem erro.
*/ */
public void close() { public void close() {
try { try {
@@ -104,7 +121,8 @@ public class SocketClient {
} }
/** /**
* @return true if connected and socket is open, false otherwise * Verifica o estado atual da conexão.
* * @return true se o socket estiver instanciado, conectado e aberto; false caso contrário.
*/ */
public boolean isConnected() { public boolean isConnected() {
return socket != null && socket.isConnected() && !socket.isClosed(); return socket != null && socket.isConnected() && !socket.isClosed();

View File

@@ -0,0 +1,576 @@
package sd.dashboard;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import javafx.application.Platform;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.CheckBox;
import javafx.scene.control.Label;
import javafx.scene.control.ProgressBar;
import javafx.scene.control.Spinner;
import javafx.scene.control.TextArea;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.VBox;
import javafx.stage.Modality;
import javafx.stage.Stage;
import sd.analysis.MultiRunAnalyzer;
import sd.analysis.SimulationRunResult;
import sd.model.VehicleType;
/**
* Diálogo para configuração e execução de análise de desempenho em lote (Batch Processing).
* <p>
* Esta classe fornece uma interface gráfica para automatizar múltiplas execuções da simulação
* sob diferentes cenários de carga. É responsável por:
* <ol>
* <li>Orquestrar o ciclo de vida dos processos de simulação (start/stop/wait).</li>
* <li>Coletar métricas estatísticas de cada execução.</li>
* <li>Agregar resultados usando o {@link MultiRunAnalyzer}.</li>
* <li>Gerar relatórios consolidados para análise de variância e intervalos de confiança.</li>
* </ol>
* A execução ocorre numa thread separada (background) para manter a responsividade da UI.
*/
public class BatchAnalysisDialog {
private Stage dialog;
private ProgressBar progressBar;
private Label statusLabel;
private Label progressLabel;
private TextArea logArea;
private Button startButton;
private Button closeButton;
// Flags de controlo de concorrência
private volatile boolean isRunning = false;
private volatile boolean shouldStop = false;
/** Referência partilhada para capturar estatísticas em tempo real do Dashboard. */
private DashboardStatistics sharedStatistics;
/**
* Exibe o diálogo de análise em lote.
* * @param owner A janela pai (Stage) para modalidade.
* @param statistics Objeto partilhado de estatísticas para coleta de dados.
*/
public static void show(Stage owner, DashboardStatistics statistics) {
BatchAnalysisDialog dialog = new BatchAnalysisDialog();
dialog.sharedStatistics = statistics;
dialog.createAndShow(owner);
}
/**
* Constrói e inicializa a interface gráfica do diálogo.
*/
private void createAndShow(Stage owner) {
dialog = new Stage();
dialog.initOwner(owner);
dialog.initModality(Modality.APPLICATION_MODAL);
dialog.setTitle("Batch Performance Analysis");
VBox root = new VBox(20);
root.setPadding(new Insets(20));
root.setAlignment(Pos.TOP_CENTER);
// Estilo Dark Mode conforme guidelines visuais
root.setStyle("-fx-background-color: #2b2b2b;");
// Header
Label title = new Label("Batch Performance Evaluation");
title.setStyle("-fx-font-size: 18px; -fx-font-weight: bold; -fx-text-fill: white;");
Label subtitle = new Label("Executar múltiplas simulações para gerar análise estatística consolidada");
subtitle.setStyle("-fx-font-size: 12px; -fx-text-fill: #cccccc;");
subtitle.setWrapText(true);
// Painéis de Componentes
VBox configPanel = createConfigPanel();
VBox progressPanel = createProgressPanel();
VBox logPanel = createLogPanel();
HBox buttonBox = createButtonBox();
root.getChildren().addAll(title, subtitle, configPanel, progressPanel, logPanel, buttonBox);
Scene scene = new Scene(root, 700, 600);
dialog.setScene(scene);
// Tratamento de fecho da janela: interromper thread de worker se ativa
dialog.setOnCloseRequest(e -> {
if (isRunning) {
e.consume(); // Previne fecho imediato
shouldStop = true;
log("A parar após conclusão da execução atual...");
}
});
dialog.show();
}
private VBox createConfigPanel() {
VBox panel = new VBox(15);
panel.setPadding(new Insets(15));
panel.setStyle("-fx-background-color: rgba(255, 255, 255, 0.05); -fx-background-radius: 5;");
Label header = new Label("Configuração");
header.setStyle("-fx-font-size: 14px; -fx-font-weight: bold; -fx-text-fill: white;");
// Runs per scenario
HBox runsBox = new HBox(10);
runsBox.setAlignment(Pos.CENTER_LEFT);
Label runsLabel = new Label("Execuções por cenário:");
runsLabel.setStyle("-fx-text-fill: white; -fx-min-width: 150px;");
Spinner<Integer> runsSpinner = new Spinner<>(1, 20, 5, 1);
runsSpinner.setEditable(true);
runsSpinner.setPrefWidth(80);
runsSpinner.setId("runsSpinner");
runsBox.getChildren().addAll(runsLabel, runsSpinner);
// Scenario selection
Label scenarioHeader = new Label("Selecionar Cenários:");
scenarioHeader.setStyle("-fx-text-fill: white; -fx-font-size: 12px; -fx-font-weight: bold;");
CheckBox lowCheck = new CheckBox("Carga Baixa (λ=0.2 v/s)");
lowCheck.setSelected(true);
lowCheck.setId("lowCheck");
lowCheck.setStyle("-fx-text-fill: white;");
CheckBox mediumCheck = new CheckBox("Carga Média (λ=0.5 v/s)");
mediumCheck.setSelected(true);
mediumCheck.setId("mediumCheck");
mediumCheck.setStyle("-fx-text-fill: white;");
CheckBox highCheck = new CheckBox("Carga Alta (λ=1.0 v/s)");
highCheck.setSelected(true);
highCheck.setId("highCheck");
highCheck.setStyle("-fx-text-fill: white;");
// Run duration
HBox durationBox = new HBox(10);
durationBox.setAlignment(Pos.CENTER_LEFT);
Label durationLabel = new Label("Duração (segundos):");
durationLabel.setStyle("-fx-text-fill: white; -fx-min-width: 150px;");
Spinner<Integer> durationSpinner = new Spinner<>(30, 3600, 120, 30);
durationSpinner.setEditable(true);
durationSpinner.setPrefWidth(80);
durationSpinner.setId("durationSpinner");
Label durationInfo = new Label("(tempo simulado - duração real depende do time.scale)");
durationInfo.setStyle("-fx-text-fill: #999999; -fx-font-size: 10px;");
durationBox.getChildren().addAll(durationLabel, durationSpinner, durationInfo);
panel.getChildren().addAll(header, runsBox, scenarioHeader, lowCheck, mediumCheck, highCheck, durationBox);
return panel;
}
private VBox createProgressPanel() {
VBox panel = new VBox(10);
panel.setPadding(new Insets(15));
panel.setStyle("-fx-background-color: rgba(255, 255, 255, 0.05); -fx-background-radius: 5;");
statusLabel = new Label("Pronto para iniciar");
statusLabel.setStyle("-fx-text-fill: white; -fx-font-weight: bold;");
progressBar = new ProgressBar(0);
progressBar.setPrefWidth(Double.MAX_VALUE);
progressBar.setPrefHeight(25);
progressLabel = new Label("0 / 0 execuções concluídas");
progressLabel.setStyle("-fx-text-fill: #cccccc; -fx-font-size: 11px;");
panel.getChildren().addAll(statusLabel, progressBar, progressLabel);
return panel;
}
private VBox createLogPanel() {
VBox panel = new VBox(5);
Label logHeader = new Label("Log de Atividade:");
logHeader.setStyle("-fx-text-fill: white; -fx-font-size: 12px; -fx-font-weight: bold;");
logArea = new TextArea();
logArea.setEditable(false);
logArea.setPrefRowCount(10);
logArea.setWrapText(true);
// Estilo de terminal para o log
logArea.setStyle("-fx-control-inner-background: #1e1e1e; -fx-text-fill: #00ff00; -fx-font-family: 'Courier New';");
VBox.setVgrow(logArea, Priority.ALWAYS);
panel.getChildren().addAll(logHeader, logArea);
return panel;
}
private HBox createButtonBox() {
HBox box = new HBox(15);
box.setAlignment(Pos.CENTER);
box.setPadding(new Insets(10, 0, 0, 0));
startButton = new Button("INICIAR BATCH");
startButton.setStyle("-fx-background-color: #28a745; -fx-text-fill: white; -fx-font-weight: bold; -fx-padding: 10 20;");
startButton.setOnAction(e -> startBatchAnalysis());
Button stopButton = new Button("PARAR");
stopButton.setStyle("-fx-background-color: #dc3545; -fx-text-fill: white; -fx-font-weight: bold; -fx-padding: 10 20;");
stopButton.setOnAction(e -> {
shouldStop = true;
log("Paragem solicitada...");
});
closeButton = new Button("FECHAR");
closeButton.setStyle("-fx-background-color: #6c757d; -fx-text-fill: white; -fx-font-weight: bold; -fx-padding: 10 20;");
closeButton.setOnAction(e -> dialog.close());
box.getChildren().addAll(startButton, stopButton, closeButton);
return box;
}
/**
* Valida configurações e inicia a thread de execução em batch.
*/
private void startBatchAnalysis() {
if (isRunning) return;
// Get configuration
Spinner<Integer> runsSpinner = (Spinner<Integer>) dialog.getScene().lookup("#runsSpinner");
Spinner<Integer> durationSpinner = (Spinner<Integer>) dialog.getScene().lookup("#durationSpinner");
CheckBox lowCheck = (CheckBox) dialog.getScene().lookup("#lowCheck");
CheckBox mediumCheck = (CheckBox) dialog.getScene().lookup("#mediumCheck");
CheckBox highCheck = (CheckBox) dialog.getScene().lookup("#highCheck");
int runsPerScenario = runsSpinner.getValue();
int duration = durationSpinner.getValue();
// Validate selection
if (!lowCheck.isSelected() && !mediumCheck.isSelected() && !highCheck.isSelected()) {
log("ERRO: Selecione pelo menos um cenário!");
return;
}
// Disable controls para evitar alterações durante execução
startButton.setDisable(true);
runsSpinner.setDisable(true);
durationSpinner.setDisable(true);
lowCheck.setDisable(true);
mediumCheck.setDisable(true);
highCheck.setDisable(true);
isRunning = true;
shouldStop = false;
// Executar em thread daemon para não bloquear a UI JavaFX
Thread analysisThread = new Thread(() -> {
try {
runBatchAnalysis(lowCheck.isSelected(), mediumCheck.isSelected(),
highCheck.isSelected(), runsPerScenario, duration);
} finally {
// Restaurar estado da UI no final
Platform.runLater(() -> {
startButton.setDisable(false);
runsSpinner.setDisable(false);
durationSpinner.setDisable(false);
lowCheck.setDisable(false);
mediumCheck.setDisable(false);
highCheck.setDisable(false);
isRunning = false;
});
}
});
analysisThread.setDaemon(true);
analysisThread.start();
}
/**
* Lógica principal de orquestração do batch.
* Itera sobre cenários e execuções, chamando a simulação e o analisador.
*/
private void runBatchAnalysis(boolean low, boolean medium, boolean high, int runsPerScenario, int durationSeconds) {
log("===========================================================");
log("INICIANDO ANÁLISE DE DESEMPENHO EM LOTE");
log("===========================================================");
log("Configuração:");
log(" • Execuções por cenário: " + runsPerScenario);
log(" • Duração por execução: " + durationSeconds + " segundos");
log(" • Cenários: " + (low ? "LOW " : "") + (medium ? "MEDIUM " : "") + (high ? "HIGH" : ""));
log("");
String[] scenarios = new String[]{
low ? "simulation-low.properties" : null,
medium ? "simulation-medium.properties" : null,
high ? "simulation-high.properties" : null
};
String[] scenarioNames = {"LOW LOAD", "MEDIUM LOAD", "HIGH LOAD"};
int totalRuns = 0;
for (String scenario : scenarios) {
if (scenario != null) totalRuns += runsPerScenario;
}
int currentRun = 0;
for (int i = 0; i < scenarios.length; i++) {
if (scenarios[i] == null) continue;
if (shouldStop) {
log("Batch analysis interrompida pelo utilizador");
updateStatus("Parado", currentRun, totalRuns);
return;
}
String configFile = scenarios[i];
String scenarioName = scenarioNames[i];
log("");
log("---------------------------------------------------------");
log("CENÁRIO: " + scenarioName + " (" + configFile + ")");
log("---------------------------------------------------------");
MultiRunAnalyzer analyzer = new MultiRunAnalyzer(configFile);
for (int run = 1; run <= runsPerScenario; run++) {
if (shouldStop) {
log("Batch analysis interrompida pelo utilizador");
updateStatus("Parado", currentRun, totalRuns);
savePartialReport(analyzer, scenarioName);
return;
}
currentRun++;
log("");
log("Execução " + run + "/" + runsPerScenario + " a iniciar...");
updateStatus("A correr " + scenarioName + " - Execução " + run + "/" + runsPerScenario,
currentRun - 1, totalRuns);
// Executa uma simulação completa e bloqueia até terminar
SimulationRunResult result = runSingleSimulation(configFile, run, durationSeconds);
if (result != null) {
analyzer.addResult(result);
log("Execução " + run + " completa - Gerados: " + result.getTotalVehiclesGenerated() +
" | Completados: " + result.getTotalVehiclesCompleted() +
" | Tempo Médio: " + String.format("%.2f", result.getAverageSystemTime()) + "s");
} else {
log("Execução " + run + " falhou!");
}
updateProgress(currentRun, totalRuns);
}
// Gera e guarda o relatório final deste cenário
saveScenarioReport(analyzer, scenarioName);
}
log("");
log("============================================================");
log("BATCH ANALYSIS COMPLETA!");
log("===========================================================");
log("Relatórios guardados em: analysis/");
log("");
updateStatus("Concluído!", totalRuns, totalRuns);
updateProgress(1.0);
}
/**
* Instancia os processos de simulação, monitoriza o estado e recolhe resultados.
*/
private SimulationRunResult runSingleSimulation(String configFile, int runNumber, int durationSeconds) {
SimulationProcessManager processManager = new SimulationProcessManager();
SimulationRunResult result = new SimulationRunResult(runNumber, configFile);
try {
// Start simulation
processManager.setConfigFile(configFile);
processManager.startSimulation();
// Tempo para processos arrancarem e estabelecerem conexões TCP
Thread.sleep(3000);
log(" Simulação em curso (duração config: " + durationSeconds + "s tempo simulado)...");
log(" A aguardar processo Coordenador completar...");
// Loop de polling para verificar se o Coordenador terminou
// Isso lida automaticamente com diferentes time scales (DES)
int checkInterval = 2; // Check every 2 seconds
int elapsed = 0;
int maxWaitSeconds = durationSeconds + 120; // Timeout de segurança
while (elapsed < maxWaitSeconds) {
if (shouldStop) {
processManager.stopSimulation();
return null;
}
// Check if simulation completed
if (!processManager.isSimulationRunning()) {
log(" Simulação terminou após " + elapsed + "s");
break;
}
Thread.sleep(checkInterval * 1000L);
elapsed += checkInterval;
// Atualização periódica do log
if (elapsed % 10 == 0 && elapsed < 60) {
log(" " + elapsed + "s decorridos...");
}
}
if (elapsed >= maxWaitSeconds) {
log(" Timeout atingido, forçando paragem...");
}
// Stop and collect results
log(" A terminar processos...");
processManager.stopSimulation();
Thread.sleep(2000); // Tempo para flushing de buffers
// Recolha de estatísticas (Prioridade: Dados reais do socket)
if (sharedStatistics != null) {
collectRealStatistics(result, sharedStatistics);
} else {
collectSimulatedStatistics(result, configFile, durationSeconds);
}
return result;
} catch (InterruptedException e) {
log("Interrompido: " + e.getMessage());
Thread.currentThread().interrupt();
stopSimulation(processManager);
return null;
} catch (IOException e) {
log("Erro IO: " + e.getMessage());
stopSimulation(processManager);
return null;
} catch (RuntimeException e) {
log("Erro Runtime: " + e.getMessage());
stopSimulation(processManager);
return null;
}
}
private void stopSimulation(SimulationProcessManager processManager) {
try {
processManager.stopSimulation();
} catch (Exception ex) {
// Ignora erros de cleanup
}
}
/**
* Popula o objeto de resultado com dados reais capturados pelo Dashboard.
*/
private void collectRealStatistics(SimulationRunResult result, DashboardStatistics stats) {
result.setTotalVehiclesGenerated(stats.getTotalVehiclesGenerated());
result.setTotalVehiclesCompleted(stats.getTotalVehiclesCompleted());
result.setAverageSystemTime(stats.getAverageSystemTime() / 1000.0); // Converte ms para segundos
result.setAverageWaitingTime(stats.getAverageWaitingTime() / 1000.0);
// Estimação de extremos (o DashboardStatistics deve ser expandido para guardar exatos se necessário)
result.setMinSystemTime(stats.getAverageSystemTime() / 1000.0 * 0.5);
result.setMaxSystemTime(stats.getAverageSystemTime() / 1000.0 * 2.0);
// Estatísticas por tipo
for (VehicleType type : VehicleType.values()) {
int count = stats.getVehicleTypeCount(type);
double waitTime = stats.getAverageWaitingTimeByType(type) / 1000.0;
result.setVehicleCountByType(type, count);
result.setAvgWaitTimeByType(type, waitTime);
}
// Estatísticas por interseção
for (var entry : stats.getAllIntersectionStats().entrySet()) {
String intersectionId = entry.getKey();
DashboardStatistics.IntersectionStats iStats = entry.getValue();
result.setVehiclesProcessed(intersectionId, iStats.getTotalDepartures());
result.setMaxQueueSize(intersectionId, iStats.getCurrentQueueSize());
result.setAvgQueueSize(intersectionId, (double) iStats.getCurrentQueueSize());
}
}
/**
* Gera dados simulados (mock) caso o dashboard não esteja conectado.
* Útil para testes de interface.
*/
private void collectSimulatedStatistics(SimulationRunResult result, String configFile, int durationSeconds) {
// Mock data based on load profile
int baseGenerated = durationSeconds / 3;
double loadFactor = configFile.contains("low") ? 0.2 :
configFile.contains("medium") ? 0.5 : 1.0;
int generated = (int)(baseGenerated * loadFactor * 3);
int completed = (int)(generated * (0.85 + Math.random() * 0.1)); // 85-95% completion rate
double baseSystemTime = 40.0;
double congestionFactor = configFile.contains("low") ? 1.0 :
configFile.contains("medium") ? 1.5 : 2.5;
result.setTotalVehiclesGenerated(generated);
result.setTotalVehiclesCompleted(completed);
result.setAverageSystemTime(baseSystemTime * congestionFactor + Math.random() * 10);
result.setMinSystemTime(20.0 + Math.random() * 5);
result.setMaxSystemTime(baseSystemTime * congestionFactor * 2 + Math.random() * 20);
result.setAverageWaitingTime(10.0 * congestionFactor + Math.random() * 5);
log(" Nota: A usar estatísticas simuladas (conexão real necessária)");
}
private void saveScenarioReport(MultiRunAnalyzer analyzer, String scenarioName) {
try {
File analysisDir = new File("analysis");
if (!analysisDir.exists()) {
analysisDir.mkdirs();
}
String timestamp = new SimpleDateFormat("yyyyMMdd-HHmmss").format(new Date());
String reportFile = "analysis/" + scenarioName.replace(" ", "_") + "_" + timestamp + ".txt";
String csvFile = "analysis/" + scenarioName.replace(" ", "_") + "_" + timestamp + ".csv";
analyzer.saveReport(reportFile);
analyzer.saveCSV(csvFile);
log("Relatório guardado: " + reportFile);
log("CSV guardado: " + csvFile);
} catch (IOException e) {
log("Falha ao guardar relatório: " + e.getMessage());
}
}
private void savePartialReport(MultiRunAnalyzer analyzer, String scenarioName) {
if (analyzer.getRunCount() > 0) {
log("A guardar resultados parciais...");
saveScenarioReport(analyzer, scenarioName + "_PARTIAL");
}
}
// --- Helpers de UI Thread-Safe ---
private void log(String message) {
Platform.runLater(() -> {
logArea.appendText(message + "\n");
logArea.setScrollTop(Double.MAX_VALUE);
});
}
private void updateStatus(String status, int current, int total) {
Platform.runLater(() -> {
statusLabel.setText(status);
progressLabel.setText(current + " / " + total + " execuções completas");
});
}
private void updateProgress(int current, int total) {
Platform.runLater(() -> {
progressBar.setProgress((double) current / total);
});
}
private void updateProgress(double progress) {
Platform.runLater(() -> {
progressBar.setProgress(progress);
});
}
}

View File

@@ -13,16 +13,32 @@ import javafx.stage.Modality;
import javafx.stage.Stage; import javafx.stage.Stage;
/** /**
* Diálogo para configuração avançada de parâmetros da simulação. * Componente de interface gráfica (GUI) responsável pela parametrização "fine-tuning" da simulação.
* Permite ajustar parâmetros em runtime antes de iniciar a simulação. * <p>
* Esta classe apresenta um diálogo modal que permite ao operador sobrepor (override)
* as configurações estáticas carregadas do ficheiro {@code .properties} imediatamente
* antes da execução. Oferece controlo granular sobre:
* <ul>
* <li><b>Geração de Carga:</b> Alternância entre modelos estocásticos (Poisson) e determinísticos.</li>
* <li><b>Temporização:</b> Ajuste da escala de tempo (Time Scale) para visualização vs. performance pura.</li>
* <li><b>Mix de Veículos:</b> Definição das probabilidades de geração por tipo de agente.</li>
* </ul>
*/ */
public class ConfigurationDialog { public class ConfigurationDialog {
/** /**
* Mostra um diálogo com opções avançadas de configuração. * Exibe o diálogo de configuração avançada e captura as intenções do utilizador.
* <p>
* A interface é construída dinamicamente usando layouts JavaFX ({@link GridPane}, {@link VBox}).
* Inclui lógica de validação reativa (ex: desabilitar campos de intervalo fixo quando
* o modelo Poisson está selecionado).
* *
[Image of Poisson distribution graph]
* *
* @param owner janela pai * @param owner A janela pai (Stage) para bloquear a interação até o fecho do diálogo (Modalidade).
* @return true se o utilizador confirmar, false se cancelar * @return {@code true} se o utilizador confirmou as alterações (OK), {@code false} se cancelou.
*/ */
public static boolean showAdvancedConfig(Stage owner) { public static boolean showAdvancedConfig(Stage owner) {
Dialog<ButtonType> dialog = new Dialog<>(); Dialog<ButtonType> dialog = new Dialog<>();

View File

@@ -9,19 +9,42 @@ import sd.protocol.MessageProtocol;
import sd.protocol.SocketConnection; import sd.protocol.SocketConnection;
/** /**
* Processes statistics messages from a single client connection. * Worker responsável pelo processamento dedicado de uma conexão de cliente TCP no Dashboard.
* Runs in a separate thread per client. * <p>
* Esta classe implementa o padrão <i>Thread-per-Client</i>. Cada instância executa numa
* thread separada, garantindo que a latência de rede ou o processamento de mensagens
* de um nó (Interseção/Coordenador) não bloqueie a receção de telemetria dos outros.
* <p>
* As suas principais funções são:
* <ol>
* <li>Manter a conexão persistente com o nó remoto.</li>
* <li>Desserializar mensagens de protocolo recebidas.</li>
* <li>Normalizar payloads JSON (resolvendo ambiguidades de tipagem do Gson).</li>
* <li>Atualizar o objeto partilhado {@link DashboardStatistics} de forma thread-safe.</li>
* </ol>
*/ */
public class DashboardClientHandler implements Runnable { public class DashboardClientHandler implements Runnable {
private final Socket clientSocket; private final Socket clientSocket;
private final DashboardStatistics statistics; private final DashboardStatistics statistics;
/**
* Inicializa o handler com o socket ativo e a referência para o agregador de estatísticas.
*
* @param clientSocket O socket TCP conectado ao nó remoto.
* @param statistics O objeto singleton partilhado onde as métricas serão agregadas.
*/
public DashboardClientHandler(Socket clientSocket, DashboardStatistics statistics) { public DashboardClientHandler(Socket clientSocket, DashboardStatistics statistics) {
this.clientSocket = clientSocket; this.clientSocket = clientSocket;
this.statistics = statistics; this.statistics = statistics;
} }
/**
* Ciclo de vida da conexão.
* <p>
* Estabelece o wrapper {@link SocketConnection}, entra num loop de leitura bloqueante
* e gere exceções de I/O. Garante o fecho limpo do socket em caso de desconexão ou erro.
*/
@Override @Override
public void run() { public void run() {
String clientInfo = clientSocket.getInetAddress().getHostAddress() + ":" + clientSocket.getPort(); String clientInfo = clientSocket.getInetAddress().getHostAddress() + ":" + clientSocket.getPort();
@@ -61,6 +84,16 @@ public class DashboardClientHandler implements Runnable {
} }
} }
/**
* Valida e extrai os dados estatísticos da mensagem.
* <p>
* Implementa uma lógica de correção de tipagem para payloads desserializados via Gson.
* Frequentemente, objetos genéricos são desserializados como {@code LinkedHashMap} em vez
* da classe alvo {@link StatsUpdatePayload}. Este método deteta essa situação e realiza
* uma conversão "round-trip" (Map -> JSON -> Object) para garantir a integridade dos dados.
*
* @param message A mensagem recebida da rede.
*/
private void processMessage(MessageProtocol message) { private void processMessage(MessageProtocol message) {
if (message.getType() != MessageType.STATS_UPDATE) { if (message.getType() != MessageType.STATS_UPDATE) {
System.out.println("[Handler] Ignoring non-statistics message type: " + message.getType()); System.out.println("[Handler] Ignoring non-statistics message type: " + message.getType());
@@ -78,6 +111,7 @@ public class DashboardClientHandler implements Runnable {
stats = (StatsUpdatePayload) payload; stats = (StatsUpdatePayload) payload;
} else if (payload instanceof java.util.Map) { } else if (payload instanceof java.util.Map) {
// Gson deserialized as LinkedHashMap - re-serialize and deserialize properly // Gson deserialized as LinkedHashMap - re-serialize and deserialize properly
// This acts as a type-safety bridge for generic JSON payloads
com.google.gson.Gson gson = new com.google.gson.Gson(); com.google.gson.Gson gson = new com.google.gson.Gson();
String json = gson.toJson(payload); String json = gson.toJson(payload);
stats = gson.fromJson(json, StatsUpdatePayload.class); stats = gson.fromJson(json, StatsUpdatePayload.class);
@@ -90,6 +124,15 @@ public class DashboardClientHandler implements Runnable {
updateStatistics(senderId, stats); updateStatistics(senderId, stats);
} }
/**
* Aplica os dados recebidos ao modelo global de estatísticas.
* <p>
* Distingue entre atualizações incrementais (ex: contagem de veículos) e
* substituições de estado (ex: tempo total de sistema reportado pelo nó de saída).
*
* @param senderId Identificador do nó que enviou a atualização (ex: "Cr1", "ExitNode").
* @param stats O objeto DTO contendo as métricas normalizadas.
*/
private void updateStatistics(String senderId, StatsUpdatePayload stats) { private void updateStatistics(String senderId, StatsUpdatePayload stats) {
if (stats.getTotalVehiclesGenerated() >= 0) { if (stats.getTotalVehiclesGenerated() >= 0) {
statistics.updateVehiclesGenerated(stats.getTotalVehiclesGenerated()); statistics.updateVehiclesGenerated(stats.getTotalVehiclesGenerated());

View File

@@ -10,17 +10,43 @@ import java.util.concurrent.atomic.AtomicBoolean;
import sd.config.SimulationConfig; import sd.config.SimulationConfig;
/** /**
* Agrega e apresenta estatísticas em tempo real de todos os processos da simulação. * Servidor central de agregação de telemetria e estatísticas.
* Usa um thread pool para gerir ligações concorrentes de clientes. * <p>
* Este componente atua como o nó de monitorização do sistema distribuído.
* Implementa uma arquitetura de servidor concorrente utilizando um {@link ExecutorService}
* (Thread Pool) para gerir múltiplas conexões de entrada simultâneas provenientes
* das Interseções, Coordenador e Nó de Saída.
* <p>
* Suporta dois modos de operação:
* <ul>
* <li><b>Headless (CLI):</b> Renderização periódica de métricas no terminal (stdout).</li>
* <li><b>GUI (JavaFX):</b> Delegação do controlo para a interface gráfica {@link DashboardUI}.</li>
* </ul>
*/ */
public class DashboardServer { public class DashboardServer {
private final int port; private final int port;
/** Armazenamento em memória (Thread-safe) do estado global do sistema. */
private final DashboardStatistics statistics; private final DashboardStatistics statistics;
/** Pool de threads para isolamento de falhas e gestão de recursos de I/O. */
private final ExecutorService clientHandlerPool; private final ExecutorService clientHandlerPool;
/** Flag atómica para controlo seguro do ciclo de vida do servidor. */
private final AtomicBoolean running; private final AtomicBoolean running;
private ServerSocket serverSocket; private ServerSocket serverSocket;
/**
* Ponto de entrada (Bootstrap) da aplicação de monitorização.
* <p>
* Analisa os argumentos de linha de comando para determinar o modo de execução.
* Se a flag {@code --gui} ou {@code -g} estiver presente, inicia o subsistema JavaFX.
* Caso contrário, inicia o modo servidor de terminal padrão.
*
* @param args Argumentos de CLI (ex: caminho do config, flags de modo).
*/
public static void main(String[] args) { public static void main(String[] args) {
// Check if GUI mode is requested // Check if GUI mode is requested
boolean useGUI = false; boolean useGUI = false;
@@ -70,13 +96,24 @@ public class DashboardServer {
} }
} }
/**
* Inicializa a infraestrutura do servidor.
*
* @param config A configuração carregada contendo a porta de escuta.
*/
public DashboardServer(SimulationConfig config) { public DashboardServer(SimulationConfig config) {
this.port = config.getDashboardPort(); this.port = config.getDashboardPort();
this.statistics = new DashboardStatistics(); this.statistics = new DashboardStatistics();
// Fixed pool limita o consumo de recursos, prevenindo exaustão sob carga alta
this.clientHandlerPool = Executors.newFixedThreadPool(10); this.clientHandlerPool = Executors.newFixedThreadPool(10);
this.running = new AtomicBoolean(false); this.running = new AtomicBoolean(false);
} }
/**
* Inicia a escuta por conexões (Bind & Listen) e a thread de despacho.
*
* @throws IOException Se a porta já estiver em uso ou ocorrer erro de bind.
*/
public void start() throws IOException { public void start() throws IOException {
if (running.get()) { if (running.get()) {
System.out.println("Dashboard Server is already running."); System.out.println("Dashboard Server is already running.");
@@ -95,6 +132,13 @@ public class DashboardServer {
acceptThread.start(); acceptThread.start();
} }
/**
* Loop principal de aceitação de conexões (Dispatcher).
* <p>
* Bloqueia em {@code accept()} até que uma nova conexão chegue, delegando
* imediatamente o processamento para um {@link DashboardClientHandler} gerido
* pelo Thread Pool.
*/
private void acceptConnections() { private void acceptConnections() {
while (running.get()) { while (running.get()) {
try { try {
@@ -112,6 +156,10 @@ public class DashboardServer {
} }
} }
/**
* Ciclo de renderização de métricas para o modo CLI (Headless).
* Atualiza o ecrã a cada 5 segundos.
*/
@SuppressWarnings("BusyWait") @SuppressWarnings("BusyWait")
private void displayLoop() { private void displayLoop() {
final long DISPLAY_INTERVAL_MS = 5000; final long DISPLAY_INTERVAL_MS = 5000;
@@ -127,6 +175,9 @@ public class DashboardServer {
} }
} }
/**
* Renderiza o snapshot atual das estatísticas no stdout.
*/
public void displayStatistics() { public void displayStatistics() {
System.out.println("\n" + "=".repeat(60)); System.out.println("\n" + "=".repeat(60));
System.out.println("REAL-TIME SIMULATION STATISTICS"); System.out.println("REAL-TIME SIMULATION STATISTICS");
@@ -135,6 +186,13 @@ public class DashboardServer {
System.out.println("=".repeat(60)); System.out.println("=".repeat(60));
} }
/**
* Procedimento de encerramento gracioso (Graceful Shutdown).
* <p>
* 1. Altera flag de execução.
* 2. Fecha o socket do servidor para desbloquear a thread de aceitação.
* 3. Força o encerramento do pool de threads de clientes.
*/
public void stop() { public void stop() {
if (!running.get()) { if (!running.get()) {
return; return;

View File

@@ -9,8 +9,13 @@ import java.util.concurrent.atomic.AtomicLong;
import sd.model.VehicleType; import sd.model.VehicleType;
/** /**
* Armazenamento thread-safe de estatísticas agregadas da simulação. * Repositório central de estado da simulação, desenhado para acesso concorrente de alta frequência.
* Usa tipos atómicos e coleções concorrentes para atualizações sem locks. * <p>
* Esta classe atua como a "Single Source of Truth" para o Dashboard. Utiliza primitivas
* de concorrência do pacote {@code java.util.concurrent} (como {@link AtomicInteger} e
* {@link ConcurrentHashMap}) para permitir leituras e escritas simultâneas sem a necessidade
* de bloqueios explícitos (Lock-Free), minimizando a latência de processamento das mensagens
* recebidas dos múltiplos nós da rede.
*/ */
public class DashboardStatistics { public class DashboardStatistics {
@@ -19,12 +24,21 @@ public class DashboardStatistics {
private final AtomicLong totalSystemTime; private final AtomicLong totalSystemTime;
private final AtomicLong totalWaitingTime; private final AtomicLong totalWaitingTime;
/** Mapa thread-safe para armazenar métricas granulares por interseção. */
private final Map<String, IntersectionStats> intersectionStats; private final Map<String, IntersectionStats> intersectionStats;
private final Map<VehicleType, AtomicInteger> vehicleTypeCount; private final Map<VehicleType, AtomicInteger> vehicleTypeCount;
private final Map<VehicleType, AtomicLong> vehicleTypeWaitTime; private final Map<VehicleType, AtomicLong> vehicleTypeWaitTime;
/** Timestamp da última atualização de escrita, com garantia de visibilidade de memória (volatile). */
private volatile long lastUpdateTime; private volatile long lastUpdateTime;
/** Buffer para sinalização assíncrona de mudança de política (Dashboard -> Coordenador). */
private volatile String requestedRoutingPolicy;
/**
* Inicializa os contadores atómicos e as estruturas de dados concorrentes.
*/
public DashboardStatistics() { public DashboardStatistics() {
this.totalVehiclesGenerated = new AtomicInteger(0); this.totalVehiclesGenerated = new AtomicInteger(0);
this.totalVehiclesCompleted = new AtomicInteger(0); this.totalVehiclesCompleted = new AtomicInteger(0);
@@ -94,6 +108,17 @@ public class DashboardStatistics {
updateTimestamp(); updateTimestamp();
} }
/**
* Atualiza ou inicializa atomicamente as estatísticas de uma interseção específica.
* <p>
* Utiliza {@link Map#compute} para garantir que a criação do objeto {@link IntersectionStats}
* seja thread-safe sem necessidade de blocos synchronized externos.
*
* @param intersectionId ID da interseção.
* @param arrivals Total acumulado de chegadas.
* @param departures Total acumulado de partidas.
* @param currentQueueSize Tamanho instantâneo da fila.
*/
public void updateIntersectionStats(String intersectionId, int arrivals, public void updateIntersectionStats(String intersectionId, int arrivals,
int departures, int currentQueueSize) { int departures, int currentQueueSize) {
intersectionStats.compute(intersectionId, (id, stats) -> { intersectionStats.compute(intersectionId, (id, stats) -> {
@@ -110,6 +135,8 @@ public class DashboardStatistics {
lastUpdateTime = System.currentTimeMillis(); lastUpdateTime = System.currentTimeMillis();
} }
// --- Getters e Métricas Calculadas ---
public int getTotalVehiclesGenerated() { public int getTotalVehiclesGenerated() {
return totalVehiclesGenerated.get(); return totalVehiclesGenerated.get();
} }
@@ -118,12 +145,20 @@ public class DashboardStatistics {
return totalVehiclesCompleted.get(); return totalVehiclesCompleted.get();
} }
/**
* Calcula o tempo médio no sistema em tempo real.
* @return Média em milissegundos (0.0 se nenhum veículo completou).
*/
public double getAverageSystemTime() { public double getAverageSystemTime() {
int completed = totalVehiclesCompleted.get(); int completed = totalVehiclesCompleted.get();
if (completed == 0) return 0.0; if (completed == 0) return 0.0;
return (double) totalSystemTime.get() / completed; return (double) totalSystemTime.get() / completed;
} }
/**
* Calcula o tempo médio de espera em tempo real.
* @return Média em milissegundos (0.0 se nenhum veículo completou).
*/
public double getAverageWaitingTime() { public double getAverageWaitingTime() {
int completed = totalVehiclesCompleted.get(); int completed = totalVehiclesCompleted.get();
if (completed == 0) return 0.0; if (completed == 0) return 0.0;
@@ -152,6 +187,44 @@ public class DashboardStatistics {
return lastUpdateTime; return lastUpdateTime;
} }
/**
* Obtém um snapshot dos tamanhos atuais das filas de todas as interseções.
* <p>
* Utilizado primariamente pelo algoritmo de roteamento dinâmico (LEAST_CONGESTED)
* para tomar decisões de encaminhamento baseadas na carga atual da rede.
* * @return Mapa contendo {@code intersectionId -> queueSize}.
*/
public Map<String, Integer> getCurrentQueueSizes() {
Map<String, Integer> queueSizes = new HashMap<>();
for (Map.Entry<String, IntersectionStats> entry : intersectionStats.entrySet()) {
queueSizes.put(entry.getKey(), entry.getValue().getCurrentQueueSize());
}
return queueSizes;
}
/**
* Regista uma intenção de mudança de política de roteamento solicitada pela UI.
* O Coordenador fará polling deste valor periodicamente.
*/
public void setRequestedRoutingPolicy(String policy) {
this.requestedRoutingPolicy = policy;
}
/**
* Obtém e limpa atomicamente a política de roteamento solicitada.
* Implementa a semântica de consumo único (one-time consumption).
* * @return A política solicitada ou null se não houver mudança pendente.
*/
public synchronized String getAndClearRequestedRoutingPolicy() {
String policy = this.requestedRoutingPolicy;
this.requestedRoutingPolicy = null;
return policy;
}
/**
* Imprime um resumo formatado das estatísticas no stdout.
* Útil para o modo CLI (Headless).
*/
public void display() { public void display() {
System.out.println("\n--- GLOBAL STATISTICS ---"); System.out.println("\n--- GLOBAL STATISTICS ---");
System.out.printf("Total Vehicles Generated: %d%n", getTotalVehiclesGenerated()); System.out.printf("Total Vehicles Generated: %d%n", getTotalVehiclesGenerated());
@@ -181,6 +254,10 @@ public class DashboardStatistics {
System.out.printf("%nLast Update: %tT%n", lastUpdateTime); System.out.printf("%nLast Update: %tT%n", lastUpdateTime);
} }
/**
* Agregado de métricas específico para um nó de interseção.
* Mantém contadores atómicos para garantir consistência em atualizações concorrentes.
*/
public static class IntersectionStats { public static class IntersectionStats {
private final String intersectionId; private final String intersectionId;
private final AtomicInteger totalArrivals; private final AtomicInteger totalArrivals;

View File

@@ -188,7 +188,7 @@ public class DashboardUI extends Application {
// Scenario selector // Scenario selector
VBox scenarioBox = new VBox(5); VBox scenarioBox = new VBox(5);
scenarioBox.setAlignment(Pos.CENTER); scenarioBox.setAlignment(Pos.CENTER_LEFT);
Label scenarioLabel = new Label("Cenário:"); Label scenarioLabel = new Label("Cenário:");
scenarioLabel.setStyle("-fx-font-size: 12px;"); scenarioLabel.setStyle("-fx-font-size: 12px;");
@@ -209,13 +209,48 @@ public class DashboardUI extends Application {
scenarioBox.getChildren().addAll(scenarioLabel, configFileSelector); scenarioBox.getChildren().addAll(scenarioLabel, configFileSelector);
configControls.getChildren().add(scenarioBox); configControls.getChildren().add(scenarioBox);
// Routing policy selector
VBox routingBox = new VBox(5);
routingBox.setAlignment(Pos.CENTER_LEFT);
Label routingLabel = new Label("Política de Roteamento:");
routingLabel.setStyle("-fx-font-size: 12px;");
ComboBox<String> routingPolicySelector = new ComboBox<>();
routingPolicySelector.getItems().addAll(
"RANDOM",
"SHORTEST_PATH",
"LEAST_CONGESTED"
);
routingPolicySelector.setValue("RANDOM");
routingPolicySelector.setOnAction(e -> {
String selectedPolicy = routingPolicySelector.getValue();
System.out.println("Política de roteamento selecionada: " + selectedPolicy);
sendRoutingPolicyChange(selectedPolicy);
});
routingBox.getChildren().addAll(routingLabel, routingPolicySelector);
configControls.getChildren().add(routingBox);
// Advanced configuration button // Advanced configuration button
VBox buttonBox = new VBox(5);
buttonBox.setAlignment(Pos.CENTER_LEFT);
Label spacerLabel = new Label(" ");
spacerLabel.setStyle("-fx-font-size: 12px;");
Button btnAdvancedConfig = new Button("Configuração Avançada..."); Button btnAdvancedConfig = new Button("Configuração Avançada...");
btnAdvancedConfig.setStyle("-fx-font-size: 11px;"); btnAdvancedConfig.setStyle("-fx-font-size: 11px;");
btnAdvancedConfig.setOnAction(e -> { btnAdvancedConfig.setOnAction(e -> {
ConfigurationDialog.showAdvancedConfig((Stage) configBox.getScene().getWindow()); ConfigurationDialog.showAdvancedConfig((Stage) configBox.getScene().getWindow());
}); });
configControls.getChildren().add(btnAdvancedConfig);
Button btnBatchAnalysis = new Button("Análise em Lote...");
btnBatchAnalysis.setStyle("-fx-font-size: 11px;");
btnBatchAnalysis.setOnAction(e -> {
BatchAnalysisDialog.show((Stage) configBox.getScene().getWindow(), statistics);
});
buttonBox.getChildren().addAll(spacerLabel, btnAdvancedConfig, btnBatchAnalysis);
configControls.getChildren().add(buttonBox);
// Configuration info display // Configuration info display
configInfoLabel = new Label(); configInfoLabel = new Label();
@@ -445,13 +480,13 @@ public class DashboardUI extends Application {
String info = ""; String info = "";
switch (selectedConfigFile) { switch (selectedConfigFile) {
case "simulation-low.properties": case "simulation-low.properties":
info = "🟢 CARGA BAIXA: 0.2 veículos/s (~720/hora) | Sem congestionamento esperado"; info = "CARGA BAIXA: 0.2 veículos/s (~720/hora) | Sem congestionamento esperado";
break; break;
case "simulation-medium.properties": case "simulation-medium.properties":
info = "🟡 CARGA MÉDIA: 0.5 veículos/s (~1800/hora) | Algum congestionamento esperado"; info = "CARGA MÉDIA: 0.5 veículos/s (~1800/hora) | Algum congestionamento esperado";
break; break;
case "simulation-high.properties": case "simulation-high.properties":
info = "🔴 CARGA ALTA: 1.0 veículo/s (~3600/hora) | Congestionamento significativo esperado"; info = "CARGA ALTA: 1.0 veículo/s (~3600/hora) | Congestionamento significativo esperado";
break; break;
default: default:
info = "⚙️ CONFIGURAÇÃO PADRÃO: Verificar ficheiro para parâmetros"; info = "⚙️ CONFIGURAÇÃO PADRÃO: Verificar ficheiro para parâmetros";
@@ -482,6 +517,33 @@ public class DashboardUI extends Application {
alert.showAndWait(); alert.showAndWait();
} }
/**
* Envia mensagem para o servidor do dashboard que notificará o coordenador.
* Usa uma abordagem indireta: salva a política desejada e o coordenador lerá na próxima geração.
*/
private void sendRoutingPolicyChange(String newPolicy) {
// Store the policy change request in statistics
// The coordinator will check this periodically
if (server != null && statistics != null) {
statistics.setRequestedRoutingPolicy(newPolicy);
System.out.println("Política de roteamento solicitada: " + newPolicy);
System.out.println(" - A mudança será aplicada pelo coordenador na próxima atualização");
// Mostrar confirmação visual
Platform.runLater(() -> {
Alert alert = new Alert(Alert.AlertType.INFORMATION);
alert.setTitle("Política Solicitada");
alert.setHeaderText(null);
alert.setContentText("Política de roteamento solicitada: " + newPolicy + "\nSerá aplicada em breve.");
alert.show();
});
} else {
Platform.runLater(() -> {
showErrorAlert("Erro", "Dashboard não está conectado. Inicie a simulação primeiro.");
});
}
}
public static void main(String[] args) { public static void main(String[] args) {
launch(args); launch(args);
} }

View File

@@ -64,6 +64,32 @@ public class SimulationProcessManager {
System.out.println("All simulation processes started."); System.out.println("All simulation processes started.");
} }
/**
* Checks if the coordinator process (last process started) is still running.
* When the coordinator finishes, the simulation is complete.
*/
public boolean isSimulationRunning() {
if (runningProcesses.isEmpty()) {
return false;
}
// Coordinator is the last process in the list
Process coordinator = runningProcesses.get(runningProcesses.size() - 1);
return coordinator.isAlive();
}
/**
* Waits for the simulation to complete naturally.
* Returns true if completed, false if timeout.
*/
public boolean waitForCompletion(long timeoutSeconds) throws InterruptedException {
if (runningProcesses.isEmpty()) {
return true;
}
Process coordinator = runningProcesses.get(runningProcesses.size() - 1);
return coordinator.waitFor(timeoutSeconds, java.util.concurrent.TimeUnit.SECONDS);
}
/** /**
* Stops all running simulation processes. * Stops all running simulation processes.
*/ */

View File

@@ -3,11 +3,15 @@ package sd.des;
/** /**
* Gere o tempo de simulação para Simulação de Eventos Discretos. * Gere o tempo de simulação para Simulação de Eventos Discretos.
* *
* <p>No DES, o tempo avança em saltos discretos de evento para evento, * <p>
* não de forma contínua como o tempo real.</p> * No DES, o tempo avança em saltos discretos de evento para evento,
* não de forma contínua como o tempo real.
* </p>
* *
* <p>Esta classe garante que todos os processos no sistema distribuído * <p>
* mantêm uma visão sincronizada do tempo de simulação.</p> * Esta classe garante que todos os processos no sistema distribuído
* mantêm uma visão sincronizada do tempo de simulação.
* </p>
*/ */
public class SimulationClock { public class SimulationClock {
private double currentTime; private double currentTime;

View File

@@ -22,6 +22,7 @@ public enum EventType {
PROCESS_STOPPED("Process Stopped"), PROCESS_STOPPED("Process Stopped"),
STATS_UPDATE("Statistics Update"), STATS_UPDATE("Statistics Update"),
CONFIG_CHANGED("Configuration Changed"),
CONNECTION_ESTABLISHED("Connection Established"), CONNECTION_ESTABLISHED("Connection Established"),
CONNECTION_LOST("Connection Lost"), CONNECTION_LOST("Connection Lost"),

View File

@@ -14,7 +14,8 @@ import sd.model.Vehicle;
/** /**
* Rastreia e regista a viagem completa de veículos individuais. * Rastreia e regista a viagem completa de veículos individuais.
* *
* <p>Cria ficheiros de trace detalhados com: * <p>
* Cria ficheiros de trace detalhados com:
* <ul> * <ul>
* <li>Timestamps de todos os eventos * <li>Timestamps de todos os eventos
* <li>Localizações (interseções) * <li>Localizações (interseções)
@@ -106,7 +107,8 @@ public class VehicleTracer {
* Logs when a vehicle is generated. * Logs when a vehicle is generated.
*/ */
public void logGenerated(Vehicle vehicle) { public void logGenerated(Vehicle vehicle) {
if (!isTracking(vehicle.getId())) return; if (!isTracking(vehicle.getId()))
return;
VehicleTrace trace = trackedVehicles.get(vehicle.getId()); VehicleTrace trace = trackedVehicles.get(vehicle.getId());
if (trace != null) { if (trace != null) {
@@ -120,7 +122,8 @@ public class VehicleTracer {
* Logs when a vehicle arrives at an intersection. * Logs when a vehicle arrives at an intersection.
*/ */
public void logArrival(String vehicleId, String intersection, double simulationTime) { public void logArrival(String vehicleId, String intersection, double simulationTime) {
if (!isTracking(vehicleId)) return; if (!isTracking(vehicleId))
return;
VehicleTrace trace = trackedVehicles.get(vehicleId); VehicleTrace trace = trackedVehicles.get(vehicleId);
if (trace != null) { if (trace != null) {
@@ -133,7 +136,8 @@ public class VehicleTracer {
* Logs when a vehicle is queued at a traffic light. * Logs when a vehicle is queued at a traffic light.
*/ */
public void logQueued(String vehicleId, String intersection, String direction, int queuePosition) { public void logQueued(String vehicleId, String intersection, String direction, int queuePosition) {
if (!isTracking(vehicleId)) return; if (!isTracking(vehicleId))
return;
VehicleTrace trace = trackedVehicles.get(vehicleId); VehicleTrace trace = trackedVehicles.get(vehicleId);
if (trace != null) { if (trace != null) {
@@ -146,7 +150,8 @@ public class VehicleTracer {
* Logs when a vehicle starts waiting at a red light. * Logs when a vehicle starts waiting at a red light.
*/ */
public void logWaitingStart(String vehicleId, String intersection, String direction) { public void logWaitingStart(String vehicleId, String intersection, String direction) {
if (!isTracking(vehicleId)) return; if (!isTracking(vehicleId))
return;
VehicleTrace trace = trackedVehicles.get(vehicleId); VehicleTrace trace = trackedVehicles.get(vehicleId);
if (trace != null) { if (trace != null) {
@@ -159,7 +164,8 @@ public class VehicleTracer {
* Logs when a vehicle finishes waiting (light turns green). * Logs when a vehicle finishes waiting (light turns green).
*/ */
public void logWaitingEnd(String vehicleId, String intersection, String direction, double waitTime) { public void logWaitingEnd(String vehicleId, String intersection, String direction, double waitTime) {
if (!isTracking(vehicleId)) return; if (!isTracking(vehicleId))
return;
VehicleTrace trace = trackedVehicles.get(vehicleId); VehicleTrace trace = trackedVehicles.get(vehicleId);
if (trace != null) { if (trace != null) {
@@ -172,7 +178,8 @@ public class VehicleTracer {
* Logs when a vehicle starts crossing an intersection. * Logs when a vehicle starts crossing an intersection.
*/ */
public void logCrossingStart(String vehicleId, String intersection, String direction) { public void logCrossingStart(String vehicleId, String intersection, String direction) {
if (!isTracking(vehicleId)) return; if (!isTracking(vehicleId))
return;
VehicleTrace trace = trackedVehicles.get(vehicleId); VehicleTrace trace = trackedVehicles.get(vehicleId);
if (trace != null) { if (trace != null) {
@@ -185,7 +192,8 @@ public class VehicleTracer {
* Logs when a vehicle finishes crossing an intersection. * Logs when a vehicle finishes crossing an intersection.
*/ */
public void logCrossingEnd(String vehicleId, String intersection, double crossingTime) { public void logCrossingEnd(String vehicleId, String intersection, double crossingTime) {
if (!isTracking(vehicleId)) return; if (!isTracking(vehicleId))
return;
VehicleTrace trace = trackedVehicles.get(vehicleId); VehicleTrace trace = trackedVehicles.get(vehicleId);
if (trace != null) { if (trace != null) {
@@ -198,7 +206,8 @@ public class VehicleTracer {
* Logs when a vehicle departs from an intersection. * Logs when a vehicle departs from an intersection.
*/ */
public void logDeparture(String vehicleId, String intersection, String nextDestination) { public void logDeparture(String vehicleId, String intersection, String nextDestination) {
if (!isTracking(vehicleId)) return; if (!isTracking(vehicleId))
return;
VehicleTrace trace = trackedVehicles.get(vehicleId); VehicleTrace trace = trackedVehicles.get(vehicleId);
if (trace != null) { if (trace != null) {
@@ -211,7 +220,8 @@ public class VehicleTracer {
* Logs when a vehicle exits the system. * Logs when a vehicle exits the system.
*/ */
public void logExit(Vehicle vehicle, double systemTime) { public void logExit(Vehicle vehicle, double systemTime) {
if (!isTracking(vehicle.getId())) return; if (!isTracking(vehicle.getId()))
return;
VehicleTrace trace = trackedVehicles.get(vehicle.getId()); VehicleTrace trace = trackedVehicles.get(vehicle.getId());
if (trace != null) { if (trace != null) {
@@ -272,7 +282,8 @@ public class VehicleTracer {
} }
void logEvent(String eventType, String location, String description) { void logEvent(String eventType, String location, String description) {
if (writer == null) return; if (writer == null)
return;
long now = System.currentTimeMillis(); long now = System.currentTimeMillis();
String timestamp = timestampFormat.format(new Date(now)); String timestamp = timestampFormat.format(new Date(now));
@@ -283,13 +294,13 @@ public class VehicleTracer {
relativeTime, relativeTime,
truncate(eventType, 15), truncate(eventType, 15),
truncate(location, 15), truncate(location, 15),
description description);
);
writer.flush(); writer.flush();
} }
void writeSummary(Vehicle vehicle, double systemTime) { void writeSummary(Vehicle vehicle, double systemTime) {
if (writer == null) return; if (writer == null)
return;
writer.println(); writer.println();
writer.println("=".repeat(80)); writer.println("=".repeat(80));
@@ -324,7 +335,8 @@ public class VehicleTracer {
} }
private String truncate(String str, int maxLength) { private String truncate(String str, int maxLength) {
if (str == null) return ""; if (str == null)
return "";
return str.length() <= maxLength ? str : str.substring(0, maxLength); return str.length() <= maxLength ? str : str.substring(0, maxLength);
} }
} }

View File

@@ -86,19 +86,13 @@ public class Intersection {
} }
/** /**
* Recebe um veículo e coloca-o na fila correta. * Recebe um novo veículo e coloca-o na fila do semáforo apropriado.
* A direção é escolhida com base na tabela de encaminhamento.
* *
* <p>Passos executados:</p> * @param vehicle o veículo que está a chegar a esta interseção
* <ol> * @param simulationTime o tempo de simulação atual (em segundos)
* <li>Incrementa o contador de veículos recebidos</li>
* <li>Obtém o próximo destino do veículo</li>
* <li>Consulta a tabela de encaminhamento para encontrar a direção</li>
* <li>Adiciona o veículo à fila do semáforo apropriado</li>
* </ol>
*
* @param vehicle o veículo que chega à interseção
*/ */
public void receiveVehicle(Vehicle vehicle) { public void receiveVehicle(Vehicle vehicle, double simulationTime) {
totalVehiclesReceived++; totalVehiclesReceived++;
// Note: Route advancement is handled by SimulationEngine.handleVehicleArrival() // Note: Route advancement is handled by SimulationEngine.handleVehicleArrival()
@@ -117,7 +111,7 @@ public class Intersection {
if (direction != null && trafficLights.containsKey(direction)) { if (direction != null && trafficLights.containsKey(direction)) {
// Found a valid route and light, add vehicle to the queue // Found a valid route and light, add vehicle to the queue
trafficLights.get(direction).addVehicle(vehicle); trafficLights.get(direction).addVehicle(vehicle, simulationTime);
} else { } else {
// Routing error: No rule for this destination or no light for that direction // Routing error: No rule for this destination or no light for that direction
System.err.printf( System.err.printf(
@@ -125,9 +119,7 @@ public class Intersection {
this.id, vehicle.getId(), nextDestination, direction this.id, vehicle.getId(), nextDestination, direction
); );
} }
} } /**
/**
* Retorna a direção que um veículo deve tomar para alcançar um destino. * Retorna a direção que um veículo deve tomar para alcançar um destino.
* *
* @param destination o próximo destino (ex: "Cr3", "S") * @param destination o próximo destino (ex: "Cr3", "S")

View File

@@ -40,4 +40,10 @@ public enum MessageType {
*/ */
SHUTDOWN, SHUTDOWN,
/**
* Mensagem para alterar a política de roteamento durante a simulação.
* Payload: String com o nome da nova política (RANDOM, SHORTEST_PATH, LEAST_CONGESTED)
*/
ROUTING_POLICY_CHANGE,
} }

View File

@@ -54,9 +54,9 @@ public class TrafficLight {
/** /**
* Regista quando os veículos chegam ao semáforo para cálculo do tempo de espera. * Regista quando os veículos chegam ao semáforo para cálculo do tempo de espera.
* Mapeia ID do veículo para timestamp de chegada (milissegundos). * Mapeia ID do veículo para tempo de simulação de chegada (segundos).
*/ */
private final Map<String, Long> vehicleArrivalTimes; private final Map<String, Double> vehicleArrivalTimes;
/** /**
* Cria um novo semáforo. * Cria um novo semáforo.
@@ -89,12 +89,13 @@ public class TrafficLight {
* veículo esperou. * veículo esperou.
* *
* @param vehicle O veículo que chega ao semáforo. * @param vehicle O veículo que chega ao semáforo.
* @param simulationTime O tempo de simulação atual (em segundos).
*/ */
public void addVehicle(Vehicle vehicle) { public void addVehicle(Vehicle vehicle, double simulationTime) {
lock.lock(); lock.lock();
try { try {
queue.offer(vehicle); queue.offer(vehicle);
vehicleArrivalTimes.put(vehicle.getId(), System.currentTimeMillis()); vehicleArrivalTimes.put(vehicle.getId(), simulationTime);
vehicleAdded.signalAll(); vehicleAdded.signalAll();
} finally { } finally {
lock.unlock(); lock.unlock();
@@ -112,9 +113,10 @@ public class TrafficLight {
* *
* <p>Atualiza automaticamente as estatísticas de tempo de espera do veículo.</p> * <p>Atualiza automaticamente as estatísticas de tempo de espera do veículo.</p>
* *
* @param simulationTime O tempo de simulação atual (em segundos).
* @return o veículo que vai atravessar, ou null se não for possível * @return o veículo que vai atravessar, ou null se não for possível
*/ */
public Vehicle removeVehicle() { public Vehicle removeVehicle(double simulationTime) {
lock.lock(); lock.lock();
try { try {
if (state == TrafficLightState.GREEN && !queue.isEmpty()) { if (state == TrafficLightState.GREEN && !queue.isEmpty()) {
@@ -122,9 +124,9 @@ public class TrafficLight {
if (vehicle != null) { if (vehicle != null) {
totalVehiclesProcessed++; totalVehiclesProcessed++;
Long arrivalTime = vehicleArrivalTimes.remove(vehicle.getId()); Double arrivalTime = vehicleArrivalTimes.remove(vehicle.getId());
if (arrivalTime != null) { if (arrivalTime != null) {
double waitTimeSeconds = (System.currentTimeMillis() - arrivalTime) / 1000.0; double waitTimeSeconds = simulationTime - arrivalTime;
vehicle.addWaitingTime(waitTimeSeconds); vehicle.addWaitingTime(waitTimeSeconds);
} }
} }

View File

@@ -7,16 +7,20 @@ import java.util.List;
/** /**
* Representa um veículo que se move pela rede de interseções. * Representa um veículo que se move pela rede de interseções.
* *
* <p>Esta classe é o "gémeo digital" de um carro, mota ou camião. * <p>
* Mantém toda a informação necessária:</p> * Esta classe é o "gémeo digital" de um carro, mota ou camião.
* Mantém toda a informação necessária:
* </p>
* <ul> * <ul>
* <li>Identificação e tipo do veículo</li> * <li>Identificação e tipo do veículo</li>
* <li>Rota completa a percorrer</li> * <li>Rota completa a percorrer</li>
* <li>Métricas de tempo (espera, travessia, total)</li> * <li>Métricas de tempo (espera, travessia, total)</li>
* </ul> * </ul>
* *
* <p>O objeto é serializado e enviado pela rede à medida que o veículo * <p>
* se move entre processos distribuídos.</p> * O objeto é serializado e enviado pela rede à medida que o veículo
* se move entre processos distribuídos.
* </p>
*/ */
public class Vehicle implements Serializable { public class Vehicle implements Serializable {
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
@@ -42,10 +46,16 @@ public class Vehicle implements Serializable {
*/ */
private int currentRouteIndex; private int currentRouteIndex;
/** Tempo total acumulado (segundos) que o veículo passou à espera em semáforos vermelhos */ /**
* Tempo total acumulado (segundos) que o veículo passou à espera em semáforos
* vermelhos
*/
private double totalWaitingTime; private double totalWaitingTime;
/** Tempo total acumulado (segundos) que o veículo passou a atravessar interseções */ /**
* Tempo total acumulado (segundos) que o veículo passou a atravessar
* interseções
*/
private double totalCrossingTime; private double totalCrossingTime;
/** /**
@@ -80,7 +90,8 @@ public class Vehicle implements Serializable {
} }
/** /**
* Obtém o destino atual (próxima interseção ou saída) para onde o veículo se dirige. * Obtém o destino atual (próxima interseção ou saída) para onde o veículo se
* dirige.
* *
* @return ID do destino atual (ex: "Cr1"), ou {@code null} se a rota terminou * @return ID do destino atual (ex: "Cr1"), ou {@code null} se a rota terminou
*/ */

View File

@@ -0,0 +1,151 @@
package sd.routing;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
/**
* Implementação da política de roteamento por menor congestionamento.
*
* <p>Esta política escolhe dinamicamente a rota que passa pelos cruzamentos
* menos congestionados, com base no tamanho atual das filas em cada interseção.
* É uma política dinâmica que adapta as decisões ao estado da rede.</p>
*
* <p>Objetivo: Distribuir o tráfego pela rede, evitando bottlenecks e
* minimizando o tempo de espera total.</p>
*
* <p><strong>Algoritmo:</strong></p>
* <ol>
* <li>Para cada rota possível, calcula a carga total (soma das filas)</li>
* <li>Escolhe a rota com menor carga total</li>
* <li>Em caso de empate ou falta de informação, usa a rota mais curta</li>
* </ol>
*/
public class LeastCongestedRouteSelector implements RouteSelector {
/** Rotas possíveis a partir do ponto de entrada E1 */
private final List<List<String>> e1Routes;
/** Rotas possíveis a partir do ponto de entrada E2 */
private final List<List<String>> e2Routes;
/** Rotas possíveis a partir do ponto de entrada E3 */
private final List<List<String>> e3Routes;
/**
* Cria um novo seletor de rotas baseado em menor congestionamento.
*/
public LeastCongestedRouteSelector() {
this.e1Routes = new ArrayList<>();
this.e2Routes = new ArrayList<>();
this.e3Routes = new ArrayList<>();
initializeRoutes();
}
/**
* Inicializa as rotas possíveis para cada ponto de entrada.
*/
private void initializeRoutes() {
// Rotas de E1 (entrada Norte)
e1Routes.add(Arrays.asList("Cr1", "Cr4", "Cr5", "S"));
e1Routes.add(Arrays.asList("Cr1", "Cr2", "Cr5", "S"));
e1Routes.add(Arrays.asList("Cr1", "Cr2", "Cr3", "S"));
// Rotas de E2 (entrada Oeste)
e2Routes.add(Arrays.asList("Cr2", "Cr5", "S"));
e2Routes.add(Arrays.asList("Cr2", "Cr3", "S"));
e2Routes.add(Arrays.asList("Cr2", "Cr1", "Cr4", "Cr5", "S"));
// Rotas de E3 (entrada Sul)
e3Routes.add(Arrays.asList("Cr3", "S"));
e3Routes.add(Arrays.asList("Cr3", "Cr2", "Cr5", "S"));
e3Routes.add(Arrays.asList("Cr3", "Cr2", "Cr1", "Cr4", "Cr5", "S"));
}
@Override
public List<String> selectRoute(String entryPoint, Map<String, Integer> queueSizes) {
List<List<String>> availableRoutes = getRoutesForEntryPoint(entryPoint);
// Se não temos informação sobre filas, usa a rota mais curta como fallback
if (queueSizes == null || queueSizes.isEmpty()) {
return selectShortestRoute(availableRoutes);
}
// Calcula a carga de cada rota e escolhe a menos congestionada
List<String> bestRoute = null;
int minLoad = Integer.MAX_VALUE;
for (List<String> route : availableRoutes) {
int routeLoad = calculateRouteLoad(route, queueSizes);
if (routeLoad < minLoad) {
minLoad = routeLoad;
bestRoute = route;
}
}
// Fallback: se não conseguimos calcular carga, usa a primeira rota
if (bestRoute == null) {
bestRoute = availableRoutes.get(0);
}
return new ArrayList<>(bestRoute);
}
/**
* Calcula a carga total de uma rota (soma do tamanho das filas em todos os cruzamentos).
*
* @param route rota a avaliar
* @param queueSizes mapa com tamanho das filas por interseção
* @return carga total da rota (soma das filas)
*/
private int calculateRouteLoad(List<String> route, Map<String, Integer> queueSizes) {
int totalLoad = 0;
for (String intersection : route) {
// Ignora "S" (saída) e apenas conta cruzamentos reais
if (!intersection.equals("S") && queueSizes.containsKey(intersection)) {
totalLoad += queueSizes.get(intersection);
}
}
return totalLoad;
}
/**
* Seleciona a rota mais curta (menor número de nós) como fallback.
*
* @param routes lista de rotas disponíveis
* @return a rota mais curta
*/
private List<String> selectShortestRoute(List<List<String>> routes) {
List<String> shortest = routes.get(0);
for (List<String> route : routes) {
if (route.size() < shortest.size()) {
shortest = route;
}
}
return new ArrayList<>(shortest);
}
/**
* Obtém as rotas disponíveis para um ponto de entrada.
*
* @param entryPoint ponto de entrada (E1, E2 ou E3)
* @return lista de rotas disponíveis
*/
private List<List<String>> getRoutesForEntryPoint(String entryPoint) {
switch (entryPoint.toUpperCase()) {
case "E1":
return e1Routes;
case "E2":
return e2Routes;
case "E3":
return e3Routes;
default:
System.err.printf("Unknown entry point: %s, defaulting to E1%n", entryPoint);
return e1Routes;
}
}
}

View File

@@ -0,0 +1,122 @@
package sd.routing;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
/**
* Implementação da política de roteamento aleatória (baseline).
*
* <p>Esta política seleciona rotas com base em probabilidades predefinidas,
* sem considerar o estado atual da rede. É a implementação de referência
* para comparação com outras políticas.</p>
*
* <p>As rotas são organizadas por ponto de entrada (E1, E2, E3) e cada rota
* tem uma probabilidade de seleção associada.</p>
*/
public class RandomRouteSelector implements RouteSelector {
/** Rotas possíveis a partir do ponto de entrada E1 */
private final List<RouteWithProbability> e1Routes;
/** Rotas possíveis a partir do ponto de entrada E2 */
private final List<RouteWithProbability> e2Routes;
/** Rotas possíveis a partir do ponto de entrada E3 */
private final List<RouteWithProbability> e3Routes;
/**
* Cria um novo seletor de rotas aleatórias com rotas predefinidas.
*/
public RandomRouteSelector() {
this.e1Routes = new ArrayList<>();
this.e2Routes = new ArrayList<>();
this.e3Routes = new ArrayList<>();
initializePossibleRoutes();
}
/**
* Define todas as rotas possíveis que os veículos podem tomar.
* As rotas são organizadas por ponto de entrada (E1, E2, E3).
* Cada rota tem uma probabilidade que determina a frequência com que é escolhida.
*/
private void initializePossibleRoutes() {
// Rotas de E1 (entrada Norte)
e1Routes.add(new RouteWithProbability(
Arrays.asList("Cr1", "Cr4", "Cr5", "S"), 0.34));
e1Routes.add(new RouteWithProbability(
Arrays.asList("Cr1", "Cr2", "Cr5", "S"), 0.33));
e1Routes.add(new RouteWithProbability(
Arrays.asList("Cr1", "Cr2", "Cr3", "S"), 0.33));
// Rotas de E2 (entrada Oeste)
e2Routes.add(new RouteWithProbability(
Arrays.asList("Cr2", "Cr5", "S"), 0.34));
e2Routes.add(new RouteWithProbability(
Arrays.asList("Cr2", "Cr3", "S"), 0.33));
e2Routes.add(new RouteWithProbability(
Arrays.asList("Cr2", "Cr1", "Cr4", "Cr5", "S"), 0.33));
// Rotas de E3 (entrada Sul)
e3Routes.add(new RouteWithProbability(
Arrays.asList("Cr3", "S"), 0.34));
e3Routes.add(new RouteWithProbability(
Arrays.asList("Cr3", "Cr2", "Cr5", "S"), 0.33));
e3Routes.add(new RouteWithProbability(
Arrays.asList("Cr3", "Cr2", "Cr1", "Cr4", "Cr5", "S"), 0.33));
}
@Override
public List<String> selectRoute(String entryPoint, Map<String, Integer> queueSizes) {
// Ignora queueSizes - seleção aleatória não depende do estado da rede
List<RouteWithProbability> selectedRoutes = getRoutesForEntryPoint(entryPoint);
// Seleciona uma rota baseada em probabilidades cumulativas
double rand = Math.random();
double cumulative = 0.0;
for (RouteWithProbability routeWithProb : selectedRoutes) {
cumulative += routeWithProb.probability;
if (rand <= cumulative) {
// Retorna uma cópia da rota para prevenir modificações
return new ArrayList<>(routeWithProb.route);
}
}
// Fallback: retorna a primeira rota
return new ArrayList<>(selectedRoutes.get(0).route);
}
/**
* Obtém as rotas disponíveis para um ponto de entrada.
*
* @param entryPoint ponto de entrada (E1, E2 ou E3)
* @return lista de rotas com probabilidades
*/
private List<RouteWithProbability> getRoutesForEntryPoint(String entryPoint) {
switch (entryPoint.toUpperCase()) {
case "E1":
return e1Routes;
case "E2":
return e2Routes;
case "E3":
return e3Routes;
default:
System.err.printf("Unknown entry point: %s, defaulting to E1%n", entryPoint);
return e1Routes;
}
}
/**
* Classe interna para associar uma rota com sua probabilidade de seleção.
*/
private static class RouteWithProbability {
final List<String> route;
final double probability;
RouteWithProbability(List<String> route, double probability) {
this.route = route;
this.probability = probability;
}
}
}

View File

@@ -0,0 +1,25 @@
package sd.routing;
import java.util.List;
import java.util.Map;
/**
* Interface para implementação de políticas de seleção de rotas.
*
* <p>Define o contrato que todas as políticas de roteamento devem seguir.
* Permite a implementação de diferentes estratégias de roteamento
* (aleatória, caminho mais curto, menor congestionamento, etc.).</p>
*/
public interface RouteSelector {
/**
* Seleciona uma rota para um veículo a partir de um ponto de entrada.
*
* @param entryPoint ponto de entrada (E1, E2 ou E3)
* @param queueSizes mapa com o tamanho das filas em cada interseção (opcional, pode ser null).
* Chave: ID da interseção (ex: "Cr1", "Cr2")
* Valor: número total de veículos em espera nessa interseção
* @return lista de IDs representando a rota escolhida (ex: ["Cr1", "Cr2", "Cr5", "S"])
*/
List<String> selectRoute(String entryPoint, Map<String, Integer> queueSizes);
}

View File

@@ -0,0 +1,36 @@
package sd.routing;
/**
* Enumeração que define as políticas de roteamento disponíveis para a simulação.
*
* <p>As políticas de roteamento determinam como os veículos escolhem o caminho
* a seguir desde o ponto de entrada até à saída da rede de interseções.</p>
*
* <ul>
* <li><strong>RANDOM:</strong> Seleção aleatória de rotas baseada em probabilidades predefinidas</li>
* <li><strong>SHORTEST_PATH:</strong> Escolhe sempre a rota com o menor número de cruzamentos</li>
* <li><strong>LEAST_CONGESTED:</strong> Escolhe a rota evitando cruzamentos mais congestionados</li>
* </ul>
*/
public enum RoutingPolicy {
/**
* Política aleatória (baseline).
* Seleciona rotas com base em probabilidades predefinidas, sem considerar
* o estado atual da rede.
*/
RANDOM,
/**
* Política do caminho mais curto.
* Sempre escolhe a rota com o menor número de cruzamentos entre o ponto
* de entrada e a saída, minimizando a distância teórica.
*/
SHORTEST_PATH,
/**
* Política das menores filas (roteamento dinâmico).
* Escolhe a rota que passa pelos cruzamentos menos congestionados,
* com base no tamanho atual das filas em cada interseção.
*/
LEAST_CONGESTED
}

View File

@@ -0,0 +1,89 @@
package sd.routing;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
/**
* Implementação da política de roteamento por caminho mais curto.
*
* <p>Esta política sempre escolhe a rota com o menor número de cruzamentos
* entre o ponto de entrada e a saída. É uma política determinística que
* não considera o estado da rede (tamanho das filas).</p>
*
* <p>Objetivo: Minimizar a distância teórica percorrida pelos veículos.</p>
*/
public class ShortestPathRouteSelector implements RouteSelector {
/** Rotas possíveis a partir do ponto de entrada E1, ordenadas por comprimento */
private final List<List<String>> e1Routes;
/** Rotas possíveis a partir do ponto de entrada E2, ordenadas por comprimento */
private final List<List<String>> e2Routes;
/** Rotas possíveis a partir do ponto de entrada E3, ordenadas por comprimento */
private final List<List<String>> e3Routes;
/**
* Cria um novo seletor de rotas por caminho mais curto.
* As rotas são ordenadas por comprimento (número de cruzamentos).
*/
public ShortestPathRouteSelector() {
this.e1Routes = new ArrayList<>();
this.e2Routes = new ArrayList<>();
this.e3Routes = new ArrayList<>();
initializeRoutes();
}
/**
* Inicializa as rotas possíveis para cada ponto de entrada.
* As rotas são organizadas da mais curta para a mais longa.
*/
private void initializeRoutes() {
// Rotas de E1 (entrada Norte) - ordenadas por comprimento
e1Routes.add(Arrays.asList("Cr1", "Cr2", "Cr3", "S")); // 4 nós
e1Routes.add(Arrays.asList("Cr1", "Cr2", "Cr5", "S")); // 4 nós
e1Routes.add(Arrays.asList("Cr1", "Cr4", "Cr5", "S")); // 4 nós
// Rotas de E2 (entrada Oeste) - ordenadas por comprimento
e2Routes.add(Arrays.asList("Cr2", "Cr3", "S")); // 3 nós (mais curta!)
e2Routes.add(Arrays.asList("Cr2", "Cr5", "S")); // 3 nós
e2Routes.add(Arrays.asList("Cr2", "Cr1", "Cr4", "Cr5", "S")); // 5 nós
// Rotas de E3 (entrada Sul) - ordenadas por comprimento
e3Routes.add(Arrays.asList("Cr3", "S")); // 2 nós (mais curta!)
e3Routes.add(Arrays.asList("Cr3", "Cr2", "Cr5", "S")); // 4 nós
e3Routes.add(Arrays.asList("Cr3", "Cr2", "Cr1", "Cr4", "Cr5", "S")); // 6 nós
}
@Override
public List<String> selectRoute(String entryPoint, Map<String, Integer> queueSizes) {
// Ignora queueSizes - política baseada apenas no comprimento do caminho
List<List<String>> availableRoutes = getRoutesForEntryPoint(entryPoint);
// Retorna a rota mais curta (primeira da lista)
List<String> shortestRoute = availableRoutes.get(0);
return new ArrayList<>(shortestRoute);
}
/**
* Obtém as rotas disponíveis para um ponto de entrada.
*
* @param entryPoint ponto de entrada (E1, E2 ou E3)
* @return lista de rotas ordenadas por comprimento
*/
private List<List<String>> getRoutesForEntryPoint(String entryPoint) {
switch (entryPoint.toUpperCase()) {
case "E1":
return e1Routes;
case "E2":
return e2Routes;
case "E3":
return e3Routes;
default:
System.err.printf("Unknown entry point: %s, defaulting to E1%n", entryPoint);
return e1Routes;
}
}
}

View File

@@ -1,12 +1,12 @@
package sd.util; package sd.util;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List; import java.util.List;
import java.util.Map;
import sd.config.SimulationConfig; import sd.config.SimulationConfig;
import sd.model.Vehicle; import sd.model.Vehicle;
import sd.model.VehicleType; import sd.model.VehicleType;
import sd.routing.RouteSelector;
/** /**
* Gera veículos para a simulação. * Gera veículos para a simulação.
@@ -15,10 +15,12 @@ import sd.model.VehicleType;
* <ol> * <ol>
* <li>Determinar <em>quando</em> o próximo veículo deve chegar, baseado no * <li>Determinar <em>quando</em> o próximo veículo deve chegar, baseado no
* modelo de chegada (POISSON ou FIXED) da {@link SimulationConfig}</li> * modelo de chegada (POISSON ou FIXED) da {@link SimulationConfig}</li>
* <li>Criar um novo objeto {@link Vehicle} com tipo e rota selecionados aleatoriamente</li> * <li>Criar um novo objeto {@link Vehicle} com tipo e rota selecionados pela
* política de roteamento configurada ({@link RouteSelector})</li>
* </ol> * </ol>
* *
* <p>As rotas são predefinidas e organizadas por ponto de entrada (E1, E2, E3).</p> * <p>As rotas são selecionadas usando uma política de roteamento que pode ser:
* aleatória, caminho mais curto, menor congestionamento, etc.</p>
*/ */
public class VehicleGenerator { public class VehicleGenerator {
@@ -29,60 +31,24 @@ public class VehicleGenerator {
/** Intervalo para modelo FIXED */ /** Intervalo para modelo FIXED */
private final double fixedInterval; private final double fixedInterval;
/** Rotas possíveis a partir do ponto de entrada E1 */ /** Política de roteamento usada para selecionar rotas */
private final List<RouteWithProbability> e1Routes; private RouteSelector routeSelector;
/** Rotas possíveis a partir do ponto de entrada E2 */
private final List<RouteWithProbability> e2Routes;
/** Rotas possíveis a partir do ponto de entrada E3 */
private final List<RouteWithProbability> e3Routes;
/** /**
* Cria um novo gerador de veículos. * Cria um novo gerador de veículos com a política de roteamento especificada.
* Lê a configuração necessária e inicializa as rotas predefinidas. * Lê a configuração necessária.
* *
* @param config objeto de {@link SimulationConfig} * @param config objeto de {@link SimulationConfig}
* @param routeSelector política de roteamento a usar para selecionar rotas
*/ */
public VehicleGenerator(SimulationConfig config) { public VehicleGenerator(SimulationConfig config, RouteSelector routeSelector) {
this.config = config; this.config = config;
this.routeSelector = routeSelector;
// Cache configuration values for performance // Cache configuration values for performance
this.arrivalModel = config.getArrivalModel(); this.arrivalModel = config.getArrivalModel();
this.arrivalRate = config.getArrivalRate(); this.arrivalRate = config.getArrivalRate();
this.fixedInterval = config.getFixedArrivalInterval(); this.fixedInterval = config.getFixedArrivalInterval();
// Initialize route lists
this.e1Routes = new ArrayList<>();
this.e2Routes = new ArrayList<>();
this.e3Routes = new ArrayList<>();
initializePossibleRoutes();
}
/**
* Define todas as rotas possíveis que os veículos podem tomar.
* As rotas são organizadas por ponto de entrada (E1, E2, E3).
* Cada rota tem uma probabilidade que determina a frequência com que é escolhida.
*/
private void initializePossibleRoutes() {
e1Routes.add(new RouteWithProbability(
Arrays.asList("Cr1", "Cr4", "Cr5", "S"), 0.34));
e1Routes.add(new RouteWithProbability(
Arrays.asList("Cr1", "Cr2", "Cr5", "S"), 0.33));
e1Routes.add(new RouteWithProbability(
Arrays.asList("Cr1", "Cr2", "Cr3", "S"), 0.33));
e2Routes.add(new RouteWithProbability(
Arrays.asList("Cr2", "Cr5", "S"), 0.34));
e2Routes.add(new RouteWithProbability(
Arrays.asList("Cr2", "Cr3", "S"), 0.33));
e2Routes.add(new RouteWithProbability(
Arrays.asList("Cr2", "Cr1", "Cr4", "Cr5", "S"), 0.33));
e3Routes.add(new RouteWithProbability(
Arrays.asList("Cr3", "S"), 0.34));
e3Routes.add(new RouteWithProbability(
Arrays.asList("Cr3", "Cr2", "Cr5", "S"), 0.33));
e3Routes.add(new RouteWithProbability(
Arrays.asList("Cr3", "Cr2", "Cr1", "Cr4", "Cr5", "S"), 0.33));
} }
/** /**
@@ -108,16 +74,19 @@ public class VehicleGenerator {
* <p>Passos executados:</p> * <p>Passos executados:</p>
* <ol> * <ol>
* <li>Seleciona um {@link VehicleType} aleatório baseado em probabilidades</li> * <li>Seleciona um {@link VehicleType} aleatório baseado em probabilidades</li>
* <li>Seleciona uma rota aleatória (ponto de entrada + caminho)</li> * <li>Seleciona um ponto de entrada aleatório (E1, E2, E3)</li>
* <li>Usa a política de roteamento para escolher a rota</li>
* </ol> * </ol>
* *
* @param vehicleId identificador único do novo veículo (ex: "V123") * @param vehicleId identificador único do novo veículo (ex: "V123")
* @param entryTime tempo de simulação em que o veículo é criado * @param entryTime tempo de simulação em que o veículo é criado
* @param queueSizes mapa com tamanho das filas (opcional, pode ser null)
* @return novo objeto {@link Vehicle} configurado * @return novo objeto {@link Vehicle} configurado
*/ */
public Vehicle generateVehicle(String vehicleId, double entryTime) { public Vehicle generateVehicle(String vehicleId, double entryTime, Map<String, Integer> queueSizes) {
VehicleType type = selectVehicleType(); VehicleType type = selectVehicleType();
List<String> route = selectRandomRoute(); String entryPoint = selectRandomEntryPoint();
List<String> route = routeSelector.selectRoute(entryPoint, queueSizes);
return new Vehicle(vehicleId, type, entryTime, route); return new Vehicle(vehicleId, type, entryTime, route);
} }
@@ -158,73 +127,46 @@ public class VehicleGenerator {
} }
/** /**
* Selects a random route for a new vehicle. * Seleciona aleatoriamente um ponto de entrada (E1, E2 ou E3).
* This is a two-step process: * Cada ponto tem probabilidade igual (1/3).
* 1. Randomly select an entry point (E1, E2, or E3) with equal probability.
* 2. From the chosen entry point's list of routes, select one
* based on their defined probabilities (using cumulative probability).
* *
* @return A {@link List} of strings representing the chosen route (e.g., ["Cr1", "Cr4", "S"]). * @return ponto de entrada selecionado ("E1", "E2" ou "E3")
*/ */
private List<String> selectRandomRoute() { private String selectRandomEntryPoint() {
// Step 1: Randomly select an entry point (E1, E2, or E3) double rand = Math.random();
double entryRandom = Math.random();
List<RouteWithProbability> selectedRoutes;
if (entryRandom < 0.333) { if (rand < 0.333) {
selectedRoutes = e1Routes; return "E1";
} else if (entryRandom < 0.666) { } else if (rand < 0.666) {
selectedRoutes = e2Routes; return "E2";
} else { } else {
selectedRoutes = e3Routes; return "E3";
}
// Step 2: Select a route from the chosen list based on cumulative probabilities
double routeRand = Math.random();
double cumulative = 0.0;
for (RouteWithProbability routeWithProb : selectedRoutes) {
cumulative += routeWithProb.probability;
if (routeRand <= cumulative) {
// Return a *copy* of the route to prevent modification
return new ArrayList<>(routeWithProb.route);
} }
} }
// Fallback: This should only be reached if probabilities don't sum to 1 /**
// (due to floating point errors) * Altera dinamicamente o RouteSelector usado para gerar rotas.
return new ArrayList<>(selectedRoutes.get(0).route); * Permite mudar a política de roteamento durante a simulação.
*
* @param newRouteSelector novo seletor de rotas
*/
public void setRouteSelector(RouteSelector newRouteSelector) {
// Note: In Java, we can't directly modify the 'final' field,
// but we can create a new VehicleGenerator with the new selector.
// For this implementation, we'll need to remove 'final' from routeSelector.
// This is acceptable since we want dynamic policy changes.
throw new UnsupportedOperationException(
"VehicleGenerator is immutable. Use CoordinatorProcess.changeRoutingPolicy() instead."
);
} }
/** /**
* @return A string providing information about the generator's configuration. * @return A string providing information about the generator's configuration.
*/ */
public String getInfo() { public String getInfo() {
int totalRoutes = e1Routes.size() + e2Routes.size() + e3Routes.size();
return String.format( return String.format(
"VehicleGenerator{model=%s, rate=%.2f, interval=%.2f, routes=%d (E1:%d, E2:%d, E3:%d)}", "VehicleGenerator{model=%s, rate=%.2f, interval=%.2f, routeSelector=%s}",
arrivalModel, arrivalRate, fixedInterval, totalRoutes, arrivalModel, arrivalRate, fixedInterval, routeSelector.getClass().getSimpleName()
e1Routes.size(), e2Routes.size(), e3Routes.size()
); );
} }
/**
* A private inner "struct-like" class to hold a route (a List of strings)
* and its associated selection probability.
*/
private static class RouteWithProbability {
final List<String> route;
final double probability;
/**
* Constructs a new RouteWithProbability pair.
* @param route The list of intersection IDs.
* @param probability The probability (0.0 to 1.0) of this route
* being chosen *from its entry group*.
*/
RouteWithProbability(List<String> route, double probability) {
this.route = route;
this.probability = probability;
}
}
} }

View File

@@ -27,7 +27,7 @@
}, },
{ {
"id": "Cr4", "id": "Cr4",
"lights": ["East", "West"], "lights": ["East", "North"],
"routes": { "routes": {
"Cr1": "North", "Cr1": "North",
"Cr5": "East" "Cr5": "East"

View File

@@ -41,7 +41,10 @@ simulation.arrival.model=POISSON
simulation.arrival.rate=1.0 simulation.arrival.rate=1.0
# Fixed interval between arrivals (only used if model=FIXED) # Fixed interval between arrivals (only used if model=FIXED)
simulation.arrival.fixed.interval=1.0 simulation.arrival.fixed.interval=2.0
# Routing policy: RANDOM, SHORTEST_PATH, LEAST_CONGESTED
simulation.routing.policy=LEAST_CONGESTED
# === TRAFFIC LIGHT TIMINGS === # === TRAFFIC LIGHT TIMINGS ===
@@ -72,11 +75,17 @@ trafficlight.Cr3.West.red=3.0
# Intersection 4 (High throughput needed toward Cr5) # Intersection 4 (High throughput needed toward Cr5)
trafficlight.Cr4.East.green=70.0 trafficlight.Cr4.East.green=70.0
trafficlight.Cr4.East.red=3.0 trafficlight.Cr4.East.red=3.0
trafficlight.Cr4.North.green=70.0
trafficlight.Cr4.North.red=3.0
# Intersection 5 (Near exit - MAJOR BOTTLENECK, longest green time) # Intersection 5 (Near exit - MAJOR BOTTLENECK, longest green time)
# All routes funnel through here before exit # All routes funnel through here before exit
trafficlight.Cr5.East.green=90.0 trafficlight.Cr5.East.green=90.0
trafficlight.Cr5.East.red=3.0 trafficlight.Cr5.East.red=3.0
trafficlight.Cr5.West.green=70.0
trafficlight.Cr5.West.red=3.0
trafficlight.Cr5.North.green=70.0
trafficlight.Cr5.North.red=3.0
# === VEHICLE CONFIGURATION === # === VEHICLE CONFIGURATION ===
@@ -93,7 +102,7 @@ vehicle.crossing.time.heavy=4.0
# Travel times between intersections (in seconds) # Travel times between intersections (in seconds)
# Base time for light vehicles (cars) # Base time for light vehicles (cars)
vehicle.travel.time.base=1.0 vehicle.travel.time.base=1.0
# Bike travel time = 0.5 × car travel time # Bike travel time = 0.5 x car travel time
vehicle.travel.time.bike.multiplier=0.5 vehicle.travel.time.bike.multiplier=0.5
# Heavy vehicle travel time = 4.0 x base travel time # Heavy vehicle travel time = 4.0 x base travel time
vehicle.travel.time.heavy.multiplier=4.0 vehicle.travel.time.heavy.multiplier=4.0

View File

@@ -41,7 +41,10 @@ simulation.arrival.model=POISSON
simulation.arrival.rate=0.2 simulation.arrival.rate=0.2
# Fixed interval between arrivals (only used if model=FIXED) # Fixed interval between arrivals (only used if model=FIXED)
simulation.arrival.fixed.interval=5.0 simulation.arrival.fixed.interval=2.0
# Routing policy: RANDOM, SHORTEST_PATH, LEAST_CONGESTED
simulation.routing.policy=LEAST_CONGESTED
# === TRAFFIC LIGHT TIMINGS === # === TRAFFIC LIGHT TIMINGS ===
@@ -71,10 +74,16 @@ trafficlight.Cr3.West.red=5.0
# Intersection 4 (Favor East toward Cr5) # Intersection 4 (Favor East toward Cr5)
trafficlight.Cr4.East.green=30.0 trafficlight.Cr4.East.green=30.0
trafficlight.Cr4.East.red=5.0 trafficlight.Cr4.East.red=5.0
trafficlight.Cr4.North.green=30.0
trafficlight.Cr4.North.red=5.0
# Intersection 5 (Near exit - favor East) # Intersection 5 (Near exit - favor East)
trafficlight.Cr5.East.green=30.0 trafficlight.Cr5.East.green=30.0
trafficlight.Cr5.East.red=5.0 trafficlight.Cr5.East.red=5.0
trafficlight.Cr5.West.green=30.0
trafficlight.Cr5.West.red=5.0
trafficlight.Cr5.North.green=30.0
trafficlight.Cr5.North.red=5.0
# === VEHICLE CONFIGURATION === # === VEHICLE CONFIGURATION ===
@@ -91,7 +100,7 @@ vehicle.crossing.time.heavy=4.0
# Travel times between intersections (in seconds) # Travel times between intersections (in seconds)
# Base time for light vehicles (cars) # Base time for light vehicles (cars)
vehicle.travel.time.base=1.0 vehicle.travel.time.base=1.0
# Bike travel time = 0.5 × car travel time # Bike travel time = 0.5 x car travel time
vehicle.travel.time.bike.multiplier=0.5 vehicle.travel.time.bike.multiplier=0.5
# Heavy vehicle travel time = 4.0 x base travel time # Heavy vehicle travel time = 4.0 x base travel time
vehicle.travel.time.heavy.multiplier=4.0 vehicle.travel.time.heavy.multiplier=4.0

View File

@@ -43,6 +43,9 @@ simulation.arrival.rate=0.5
# Fixed interval between arrivals (only used if model=FIXED) # Fixed interval between arrivals (only used if model=FIXED)
simulation.arrival.fixed.interval=2.0 simulation.arrival.fixed.interval=2.0
# Routing policy: RANDOM, SHORTEST_PATH, LEAST_CONGESTED
simulation.routing.policy=LEAST_CONGESTED
# === TRAFFIC LIGHT TIMINGS === # === TRAFFIC LIGHT TIMINGS ===
# Format: trafficlight.<intersection>.<direction>.<state>=<seconds> # Format: trafficlight.<intersection>.<direction>.<state>=<seconds>
@@ -71,10 +74,16 @@ trafficlight.Cr3.West.red=5.0
# Intersection 4 (Favor East toward Cr5) # Intersection 4 (Favor East toward Cr5)
trafficlight.Cr4.East.green=40.0 trafficlight.Cr4.East.green=40.0
trafficlight.Cr4.East.red=5.0 trafficlight.Cr4.East.red=5.0
trafficlight.Cr4.North.green=40.0
trafficlight.Cr4.North.red=5.0
# Intersection 5 (Near exit - POTENTIAL BOTTLENECK, longer green) # Intersection 5 (Near exit - POTENTIAL BOTTLENECK, longer green)
trafficlight.Cr5.East.green=50.0 trafficlight.Cr5.East.green=50.0
trafficlight.Cr5.East.red=5.0 trafficlight.Cr5.East.red=5.0
trafficlight.Cr5.West.green=45.0
trafficlight.Cr5.West.red=5.0
trafficlight.Cr5.North.green=45.0
trafficlight.Cr5.North.red=5.0
# === VEHICLE CONFIGURATION === # === VEHICLE CONFIGURATION ===
@@ -91,7 +100,7 @@ vehicle.crossing.time.heavy=4.0
# Travel times between intersections (in seconds) # Travel times between intersections (in seconds)
# Base time for light vehicles (cars) # Base time for light vehicles (cars)
vehicle.travel.time.base=1.0 vehicle.travel.time.base=1.0
# Bike travel time = 0.5 × car travel time # Bike travel time = 0.5 x car travel time
vehicle.travel.time.bike.multiplier=0.5 vehicle.travel.time.bike.multiplier=0.5
# Heavy vehicle travel time = 4.0 x base travel time # Heavy vehicle travel time = 4.0 x base travel time
vehicle.travel.time.heavy.multiplier=4.0 vehicle.travel.time.heavy.multiplier=4.0

View File

@@ -46,6 +46,12 @@ simulation.arrival.rate=0.5
# Fixed interval between arrivals (only used if model=FIXED) # Fixed interval between arrivals (only used if model=FIXED)
simulation.arrival.fixed.interval=2.0 simulation.arrival.fixed.interval=2.0
# Routing policy: RANDOM, SHORTEST_PATH, LEAST_CONGESTED
# RANDOM: selects routes with predefined probabilities (baseline)
# SHORTEST_PATH: always chooses the route with fewest intersections
# LEAST_CONGESTED: dynamically chooses routes to avoid congested areas
simulation.routing.policy=RANDOM
# === TRAFFIC LIGHT TIMINGS === # === TRAFFIC LIGHT TIMINGS ===
# Format: trafficlight.<intersection>.<direction>.<state>=<seconds> # Format: trafficlight.<intersection>.<direction>.<state>=<seconds>
@@ -93,7 +99,7 @@ vehicle.crossing.time.heavy=4.0
# Travel times between intersections (in seconds) # Travel times between intersections (in seconds)
# Base time for light vehicles (cars) # Base time for light vehicles (cars)
vehicle.travel.time.base=1.0 vehicle.travel.time.base=1.0
# Bike travel time = 0.5 × car travel time # Bike travel time = 0.5 x car travel time
vehicle.travel.time.bike.multiplier=0.5 vehicle.travel.time.bike.multiplier=0.5
# Heavy vehicle travel time = 4.0 x base travel time # Heavy vehicle travel time = 4.0 x base travel time
vehicle.travel.time.heavy.multiplier=4.0 vehicle.travel.time.heavy.multiplier=4.0

View File

@@ -1,60 +0,0 @@
#!/bin/bash
# Distributed Traffic Simulation Startup Script
# kill java
echo "-> Cleaning up existing processes..."
pkill -9 java 2>/dev/null
sleep 2
# build
echo "-> Building project..."
cd "$(dirname "$0")"
mvn package -DskipTests -q
if [ $? -ne 0 ]; then
echo "XXX Build failed! XXX"
exit 1
fi
echo "-> Build complete"
echo ""
# start gui
echo "-> Starting JavaFX Dashboard..."
mvn javafx:run &
DASHBOARD_PID=$!
sleep 3
# acho que é assim idk
echo "-> Starting 5 Intersection processes..."
for id in Cr1 Cr2 Cr3 Cr4 Cr5; do
java -cp target/classes:target/main-1.0-SNAPSHOT.jar sd.IntersectionProcess $id > /tmp/$(echo $id | tr '[:upper:]' '[:lower:]').log 2>&1 &
echo "[SUCCESS] Started $id"
done
sleep 2
# exit
echo "-> Starting Exit Node..."
java -cp target/classes:target/main-1.0-SNAPSHOT.jar sd.ExitNodeProcess > /tmp/exit.log 2>&1 &
sleep 1
# coordinator
echo "-> Starting Coordinator..."
java -cp target/classes:target/main-1.0-SNAPSHOT.jar sd.coordinator.CoordinatorProcess > /tmp/coordinator.log 2>&1 &
sleep 1
echo ""
echo "-> All processes started!"
echo ""
echo "-> System Status:"
ps aux | grep "java.*sd\." | grep -v grep | wc -l | xargs -I {} echo " {} Java processes running"
echo ""
echo " IMPORTANT: Keep the JavaFX Dashboard window OPEN for 60+ seconds"
echo " to see live updates! The simulation runs for 60 seconds."
echo ""
echo "-> Logs available at:"
echo " Dashboard: Check JavaFX window (live updates)"
echo " Intersections: /tmp/cr*.log"
echo " Exit Node: /tmp/exit.log"
echo " Coordinator: /tmp/coordinator.log"
echo ""
echo "-> To stop all processes: pkill -9 java"
echo ""