Compare commits
40 Commits
3a3756f701
...
linux-fix
| Author | SHA1 | Date | |
|---|---|---|---|
| 09e23f8f6a | |||
| 87f797987b | |||
| daaad57c08 | |||
| 1d748e0204 | |||
| 343d31ad68 | |||
| 92bd738266 | |||
| 9fa0586bc5 | |||
| a68862b98e | |||
|
|
a4b64e1d95 | ||
|
|
e171804ac6 | ||
| 6376e94c84 | |||
| a591dcfc52 | |||
| 903022719e | |||
| 4b90827c2a | |||
| 61277350d8 | |||
| 7af3fb558b | |||
| a360dc708e | |||
| 3250d5a433 | |||
| 65cb0b52f6 | |||
| 87a8a1bcb6 | |||
| bce15fe90f | |||
| 542ce9c8c0 | |||
| 926245986f | |||
| 83c3d65e38 | |||
|
|
b624cfe11e | ||
|
|
8fe4e564d3 | ||
|
|
e389c0711e | ||
| 1b6ad03057 | |||
|
|
24fe1c1d67 | ||
|
|
766eabbbe4 | ||
|
|
d7b1de1fe3 | ||
|
|
96b3a66b96 | ||
|
|
29848b04a6 | ||
| 043ba7d185 | |||
| 25f2876c34 | |||
| 7cbecc4fab | |||
| 72db59415f | |||
| 60b4f0c2b6 | |||
| 81f842e2bb | |||
|
|
108d2e544c |
4
.github/workflows/maven.yml
vendored
@@ -3,7 +3,7 @@ name: Java CI with Maven
|
|||||||
on:
|
on:
|
||||||
workflow_dispatch:
|
workflow_dispatch:
|
||||||
push:
|
push:
|
||||||
branches: [ "dev", "cleanup" ]
|
branches: [ "main", "dev", "cleanup" ]
|
||||||
tags:
|
tags:
|
||||||
- 'v*.*.*'
|
- 'v*.*.*'
|
||||||
pull_request:
|
pull_request:
|
||||||
@@ -77,7 +77,7 @@ jobs:
|
|||||||
publish-release:
|
publish-release:
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
needs: [build, build-windows]
|
needs: [build, build-windows]
|
||||||
if: startsWith(github.ref, 'refs/tags/') || github.event_name == 'workflow_dispatch'
|
if: startsWith(github.ref, 'refs/tags/') || github.event_name == 'workflow_dispatch' || github.ref == 'refs/heads/main'
|
||||||
permissions:
|
permissions:
|
||||||
contents: write
|
contents: write
|
||||||
steps:
|
steps:
|
||||||
|
|||||||
12
.gitignore
vendored
@@ -6,6 +6,11 @@
|
|||||||
*.trace
|
*.trace
|
||||||
logs
|
logs
|
||||||
*.md
|
*.md
|
||||||
|
*.tex
|
||||||
|
!README.md
|
||||||
|
report.aux
|
||||||
|
report.synctex.gz
|
||||||
|
!report.tex
|
||||||
|
|
||||||
# BlueJ files
|
# BlueJ files
|
||||||
*.ctxt
|
*.ctxt
|
||||||
@@ -51,9 +56,14 @@ build/
|
|||||||
# Other
|
# Other
|
||||||
*.swp
|
*.swp
|
||||||
*.pdf
|
*.pdf
|
||||||
|
!Desempenho_Linux.pdf
|
||||||
|
|
||||||
# JAR built pom file
|
# JAR built pom file
|
||||||
dependency-reduced-pom.xml
|
dependency-reduced-pom.xml
|
||||||
|
|
||||||
# Python env
|
# Python env
|
||||||
venv/
|
venv/
|
||||||
|
.$Diagrama de arquitetura - SD.drawio.bkp
|
||||||
|
|
||||||
|
#others
|
||||||
|
*.out
|
||||||
|
|||||||
BIN
Desempenho_Linux.pdf
Normal file
@@ -1,27 +0,0 @@
|
|||||||
<mxfile host="app.diagrams.net" agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.0.0 Safari/537.36 Edg/141.0.0.0" version="28.2.7">
|
|
||||||
<diagram name="Página-1" id="B1_hHcevBzWlEwI7FSV6">
|
|
||||||
<mxGraphModel dx="778" dy="476" grid="1" gridSize="10" guides="1" tooltips="1" connect="1" arrows="1" fold="1" page="1" pageScale="1" pageWidth="827" pageHeight="1169" math="0" shadow="0">
|
|
||||||
<root>
|
|
||||||
<mxCell id="0" />
|
|
||||||
<mxCell id="1" parent="0" />
|
|
||||||
<mxCell id="vcp7vux32DhQR4tKQhnF-8" value="Dashboard" style="sketch=0;pointerEvents=1;shadow=0;dashed=0;html=1;strokeColor=#C73500;labelPosition=center;verticalLabelPosition=bottom;verticalAlign=top;align=center;fillColor=#fa6800;shape=mxgraph.mscae.oms.dashboard;fontColor=#000000;" vertex="1" parent="1">
|
|
||||||
<mxGeometry x="389" y="230" width="50" height="41" as="geometry" />
|
|
||||||
</mxCell>
|
|
||||||
<mxCell id="vcp7vux32DhQR4tKQhnF-12" value="Semaforo.java" style="shape=image;html=1;verticalAlign=top;verticalLabelPosition=bottom;labelBackgroundColor=#ffffff;imageAspect=0;aspect=fixed;image=https://icons.diagrams.net/icon-cache1/Strabo-2829/traffic_light-1068.png" vertex="1" parent="1">
|
|
||||||
<mxGeometry x="230" y="350" width="53" height="53" as="geometry" />
|
|
||||||
</mxCell>
|
|
||||||
<mxCell id="vcp7vux32DhQR4tKQhnF-13" value="" style="endArrow=classic;startArrow=classic;html=1;rounded=0;movable=1;resizable=1;rotatable=1;deletable=1;editable=1;locked=0;connectable=1;" edge="1" parent="1">
|
|
||||||
<mxGeometry width="50" height="50" relative="1" as="geometry">
|
|
||||||
<mxPoint x="310" y="330" as="sourcePoint" />
|
|
||||||
<mxPoint x="360" y="280" as="targetPoint" />
|
|
||||||
</mxGeometry>
|
|
||||||
</mxCell>
|
|
||||||
<mxCell id="vcp7vux32DhQR4tKQhnF-14" value="CruzamentoServer.java" style="edgeLabel;html=1;align=center;verticalAlign=middle;resizable=1;points=[];movable=1;rotatable=1;deletable=1;editable=1;locked=0;connectable=1;" vertex="1" connectable="0" parent="vcp7vux32DhQR4tKQhnF-13">
|
|
||||||
<mxGeometry x="-0.3933" relative="1" as="geometry">
|
|
||||||
<mxPoint x="25" y="25" as="offset" />
|
|
||||||
</mxGeometry>
|
|
||||||
</mxCell>
|
|
||||||
</root>
|
|
||||||
</mxGraphModel>
|
|
||||||
</diagram>
|
|
||||||
</mxfile>
|
|
||||||
177
Diagrama de arquitetura.drawio
Normal file
@@ -0,0 +1,177 @@
|
|||||||
|
<mxfile host="app.diagrams.net" agent="Mozilla/5.0 (X11; Linux x86_64; rv:145.0) Gecko/20100101 Firefox/145.0" version="29.2.6">
|
||||||
|
<diagram name="Arquitetura SD" id="QKeTeUWuUs8JeLsq44d-">
|
||||||
|
<mxGraphModel dx="891" dy="484" grid="1" gridSize="10" guides="1" tooltips="1" connect="1" arrows="1" fold="1" page="1" pageScale="1" pageWidth="1169" pageHeight="827" math="0" shadow="0">
|
||||||
|
<root>
|
||||||
|
<mxCell id="0" />
|
||||||
|
<mxCell id="1" parent="0" />
|
||||||
|
<mxCell id="0K4eb2koB2xQ8duQ1-_a-27" parent="1" style="rounded=0;whiteSpace=wrap;html=1;align=left;verticalAlign=top;fillColor=#fff2cc;strokeColor=#d6b656;spacing=10;fontColor=#000000;" value="<b>MessageProtocol</b><hr>interface:<br>• getType()<br>• getPayload()<br>• getSourceNode()<br>• getDestinationNode()" vertex="1">
|
||||||
|
<mxGeometry height="120" width="180" x="30" y="30" as="geometry" />
|
||||||
|
</mxCell>
|
||||||
|
<mxCell id="0K4eb2koB2xQ8duQ1-_a-28" parent="1" style="rounded=0;whiteSpace=wrap;html=1;align=left;verticalAlign=top;fillColor=#fff2cc;strokeColor=#d6b656;spacing=10;fontColor=#000000;" value="<font style="color: rgb(0, 0, 0);"><b style="background-color: transparent;">Tipos de Mensagens</b><br></font><hr style="background-color: transparent;"><font style="color: rgb(0, 0, 0);"><span style="background-color: transparent;">• VEHICLE_TRANSFER</span><br><span style="background-color: transparent;">• VEHICLE_SPAWN</span><br><span style="background-color: transparent;">• STATS_UPDATE</span><br><span style="background-color: transparent;">•</span><span style="background-color: transparent;">&nbsp;</span><span style="background-color: transparent;">SIMULATION_START</span><br><span style="background-color: transparent;">•</span><span style="background-color: transparent;">&nbsp;</span><span style="background-color: transparent;">SHUTDOWN</span><br><span style="background-color: transparent;">•</span><span style="background-color: transparent;">&nbsp;</span><span style="background-color: transparent;">ROUTING_POLICY_CHANGE</span></font>" vertex="1">
|
||||||
|
<mxGeometry height="130" width="200" x="20" y="170" as="geometry" />
|
||||||
|
</mxCell>
|
||||||
|
<mxCell id="0K4eb2koB2xQ8duQ1-_a-26" parent="1" style="rounded=0;whiteSpace=wrap;html=1;align=left;verticalAlign=top;fillColor=#f5f5f5;strokeColor=#666666;fontColor=#333333;spacing=10;" value="<b>LEGENDA</b><hr>━━━► Comunicação síncrona<br>╌╌╌► Comunicação periódica<br><br><b>Cores:</b><br>🔵 Azul =&nbsp;<span style="background-color: transparent;">Criação do veículo</span><div>🟢 Verde = Transferência do veículo<br>🟠 Laranja = Chegada ao destino<br>🟣 Roxo =&nbsp;<span style="background-color: transparent;">Envio das estatísticas</span></div><div><br><b>Serialização:</b> JSON (Gson)<br><b>Protocolo:</b> TCP/IP</div>" vertex="1">
|
||||||
|
<mxGeometry height="220" width="220" x="10" y="320" as="geometry" />
|
||||||
|
</mxCell>
|
||||||
|
<mxCell id="L62mICw2ZrYi1D68OOFe-13" connectable="0" parent="1" style="group;strokeColor=light-dark(transparent,#CC6600);" value="" vertex="1">
|
||||||
|
<mxGeometry height="730" width="850" x="280" y="40" as="geometry" />
|
||||||
|
</mxCell>
|
||||||
|
<mxCell id="0K4eb2koB2xQ8duQ1-_a-20" edge="1" parent="L62mICw2ZrYi1D68OOFe-13" source="0K4eb2koB2xQ8duQ1-_a-2" style="edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;strokeColor=#9933FF;strokeWidth=2;dashed=1;exitX=0.616;exitY=-0.011;exitDx=0;exitDy=0;entryX=0.661;entryY=-0.002;entryDx=0;entryDy=0;entryPerimeter=0;exitPerimeter=0;" target="0K4eb2koB2xQ8duQ1-_a-8" value="">
|
||||||
|
<mxGeometry relative="1" as="geometry">
|
||||||
|
<Array as="points">
|
||||||
|
<mxPoint x="99" y="122" />
|
||||||
|
<mxPoint x="793" y="122" />
|
||||||
|
</Array>
|
||||||
|
<mxPoint x="794" y="530" as="targetPoint" />
|
||||||
|
</mxGeometry>
|
||||||
|
</mxCell>
|
||||||
|
<mxCell id="0K4eb2koB2xQ8duQ1-_a-1" parent="L62mICw2ZrYi1D68OOFe-13" style="rounded=1;whiteSpace=wrap;html=1;fillColor=#dae8fc;strokeColor=#6c8ebf;align=left;verticalAlign=top;spacing=10;fontColor=#000000;" value="<b>CoordinatorProcess</b><br>(Cliente Socket)<hr>• VehicleGenerator<br>• Modelo Poisson<br>• Liga a Cr1-Cr5" vertex="1">
|
||||||
|
<mxGeometry height="101.38888888888889" width="176.28318584070794" x="205.6637168141593" as="geometry" />
|
||||||
|
</mxCell>
|
||||||
|
<mxCell id="0K4eb2koB2xQ8duQ1-_a-2" parent="L62mICw2ZrYi1D68OOFe-13" style="rounded=1;whiteSpace=wrap;html=1;fillColor=#d5e8d4;strokeColor=#82b366;align=left;verticalAlign=top;spacing=10;fontColor=#000000;" value="<b>Cr1</b> (IntersectionProcess)<br><hr><div>• ServerSocket (8001)</div><div>• Eventos DES:&nbsp;</div><div>&nbsp; &nbsp;- Este</div><div>&nbsp; &nbsp;- Sul</div><div>• Fila Eventos (DES)</div><div>• ReentrantLock</div><div><div>• Objetos TrafficLight</div><div>• Pool Threads (I/O rede)</div></div><div><br></div>" vertex="1">
|
||||||
|
<mxGeometry height="162.22" width="160" y="162.22" as="geometry" />
|
||||||
|
</mxCell>
|
||||||
|
<mxCell id="0K4eb2koB2xQ8duQ1-_a-3" parent="L62mICw2ZrYi1D68OOFe-13" style="rounded=1;whiteSpace=wrap;html=1;fillColor=#d5e8d4;strokeColor=#82b366;align=left;verticalAlign=top;spacing=10;fontColor=#000000;" value="<b>Cr2</b> (IntersectionProcess)<br><hr>• ServerSocket (8002)<br><div>• Eventos DES:&nbsp;</div><div>&nbsp; &nbsp;- Oeste</div><div>&nbsp; &nbsp;- Este</div><div>&nbsp; &nbsp;- Sul</div><div>• Fila Eventos (DES)</div><div>• ReentrantLock</div><div><div>• Objetos TrafficLight</div></div><div>• Pool Threads (I/O rede)</div>" vertex="1">
|
||||||
|
<mxGeometry height="177.78" width="162.3" x="227.7" y="162.22" as="geometry" />
|
||||||
|
</mxCell>
|
||||||
|
<mxCell id="0K4eb2koB2xQ8duQ1-_a-5" parent="L62mICw2ZrYi1D68OOFe-13" style="rounded=1;whiteSpace=wrap;html=1;fillColor=#d5e8d4;strokeColor=#82b366;align=left;verticalAlign=top;spacing=10;fontColor=#000000;" value="<b>Cr4</b> (IntersectionProcess)<br><hr><div>• ServerSocket (8004)</div><div><div>• Eventos DES:&nbsp;</div><div>&nbsp; &nbsp;- Este</div><div>&nbsp; &nbsp;- Norte</div><div>• Fila Eventos (DES)<br>• ReentrantLock</div></div><div><div>• Objetos TrafficLight</div><div>• Pool Threads (I/O rede)</div></div>" vertex="1">
|
||||||
|
<mxGeometry height="163.33" width="160" y="486.67" as="geometry" />
|
||||||
|
</mxCell>
|
||||||
|
<mxCell id="0K4eb2koB2xQ8duQ1-_a-6" parent="L62mICw2ZrYi1D68OOFe-13" style="rounded=1;whiteSpace=wrap;html=1;fillColor=#d5e8d4;strokeColor=#82b366;align=left;verticalAlign=top;spacing=10;fontColor=#000000;" value="<b>Cr5</b> (IntersectionProcess)<br><hr>• ServerSocket (8005)<br><div><div><div>• Eventos DES:&nbsp;</div><div>&nbsp; &nbsp;- Norte</div><div>&nbsp; &nbsp;- Este</div><div>&nbsp; &nbsp;- Sul</div>• Fila Eventos (DES)<br>• ReentrantLock</div><div><div>• Objetos TrafficLight</div><div>• Pool Threads (I/O rede)</div></div></div>" vertex="1">
|
||||||
|
<mxGeometry height="173.33" width="169.65" x="220.35" y="486.67" as="geometry" />
|
||||||
|
</mxCell>
|
||||||
|
<mxCell id="0K4eb2koB2xQ8duQ1-_a-7" parent="L62mICw2ZrYi1D68OOFe-13" style="rounded=1;whiteSpace=wrap;html=1;fillColor=#ffe6cc;strokeColor=#d79b00;align=left;verticalAlign=top;spacing=10;fontColor=#000000;" value="<b>ExitNode (S)</b><div><hr><div>• Server Socket (9001)<br>• Recebe veículos finais<br>• Calcula estatísticas:<br> - Tempo no sistema<br> - Tempo de espera<br> - Métricas por tipo<br>• Envia para o Dashboard</div></div>" vertex="1">
|
||||||
|
<mxGeometry height="172.36" width="154.6" x="464.07" y="476.53" as="geometry" />
|
||||||
|
</mxCell>
|
||||||
|
<mxCell id="0K4eb2koB2xQ8duQ1-_a-8" parent="L62mICw2ZrYi1D68OOFe-13" style="rounded=1;whiteSpace=wrap;html=1;fillColor=#e1d5e7;strokeColor=#9673a6;align=left;verticalAlign=top;spacing=10;fontColor=#000000;" value="<b>DashboardServer</b><hr>• Server Socket (9000)<br><div>• Thread Pool (10 threads)<br>• ConcurrentHashMap<br>• Agrega estatísticas<br>• Display a cada segundo:<br> - Throughput<br> - Tempos médios<br> - Tamanhos de filas</div>" vertex="1">
|
||||||
|
<mxGeometry height="180" width="166.9" x="683.1" y="540" as="geometry" />
|
||||||
|
</mxCell>
|
||||||
|
<mxCell id="0K4eb2koB2xQ8duQ1-_a-9" edge="1" parent="L62mICw2ZrYi1D68OOFe-13" source="0K4eb2koB2xQ8duQ1-_a-1" style="edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;strokeColor=#0000FF;strokeWidth=2;" target="0K4eb2koB2xQ8duQ1-_a-2" value="">
|
||||||
|
<mxGeometry relative="1" x="-0.2105" as="geometry">
|
||||||
|
<mxPoint as="offset" />
|
||||||
|
</mxGeometry>
|
||||||
|
</mxCell>
|
||||||
|
<mxCell id="0K4eb2koB2xQ8duQ1-_a-10" edge="1" parent="L62mICw2ZrYi1D68OOFe-13" source="0K4eb2koB2xQ8duQ1-_a-1" style="edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;strokeColor=#0000FF;strokeWidth=2;" target="0K4eb2koB2xQ8duQ1-_a-3" value="">
|
||||||
|
<mxGeometry relative="1" as="geometry">
|
||||||
|
<Array as="points">
|
||||||
|
<mxPoint x="309" y="120" />
|
||||||
|
<mxPoint x="309" y="120" />
|
||||||
|
</Array>
|
||||||
|
</mxGeometry>
|
||||||
|
</mxCell>
|
||||||
|
<mxCell id="0K4eb2koB2xQ8duQ1-_a-11" edge="1" parent="L62mICw2ZrYi1D68OOFe-13" source="0K4eb2koB2xQ8duQ1-_a-1" style="edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;strokeColor=#0000FF;strokeWidth=2;" target="0K4eb2koB2xQ8duQ1-_a-4" value="">
|
||||||
|
<mxGeometry relative="1" as="geometry" />
|
||||||
|
</mxCell>
|
||||||
|
<mxCell id="0K4eb2koB2xQ8duQ1-_a-12" edge="1" parent="L62mICw2ZrYi1D68OOFe-13" source="0K4eb2koB2xQ8duQ1-_a-2" style="edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;strokeColor=#00AA00;strokeWidth=2;endArrow=classic;startArrow=classic;" target="0K4eb2koB2xQ8duQ1-_a-3" value="">
|
||||||
|
<mxGeometry relative="1" as="geometry">
|
||||||
|
<Array as="points">
|
||||||
|
<mxPoint x="210" y="243" />
|
||||||
|
<mxPoint x="210" y="243" />
|
||||||
|
</Array>
|
||||||
|
</mxGeometry>
|
||||||
|
</mxCell>
|
||||||
|
<mxCell id="0K4eb2koB2xQ8duQ1-_a-14" edge="1" parent="L62mICw2ZrYi1D68OOFe-13" source="0K4eb2koB2xQ8duQ1-_a-2" style="edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;strokeColor=#00AA00;strokeWidth=2;endArrow=classic;startArrow=none;startFill=0;" target="0K4eb2koB2xQ8duQ1-_a-5" value="">
|
||||||
|
<mxGeometry relative="1" x="0.125" y="100" as="geometry">
|
||||||
|
<mxPoint y="-1" as="offset" />
|
||||||
|
<Array as="points">
|
||||||
|
<mxPoint x="66.10619469026548" y="446.11111111111114" />
|
||||||
|
<mxPoint x="66.10619469026548" y="446.11111111111114" />
|
||||||
|
</Array>
|
||||||
|
</mxGeometry>
|
||||||
|
</mxCell>
|
||||||
|
<mxCell id="0K4eb2koB2xQ8duQ1-_a-16" edge="1" parent="L62mICw2ZrYi1D68OOFe-13" style="edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;strokeColor=#00AA00;strokeWidth=2;endArrow=classic;startArrow=none;startFill=0;align=center;" value="">
|
||||||
|
<mxGeometry relative="1" x="-0.0178" y="-49" as="geometry">
|
||||||
|
<mxPoint as="offset" />
|
||||||
|
<Array as="points">
|
||||||
|
<mxPoint x="220" y="571" />
|
||||||
|
</Array>
|
||||||
|
<mxPoint x="160" y="570" as="sourcePoint" />
|
||||||
|
<mxPoint x="220" y="571" as="targetPoint" />
|
||||||
|
</mxGeometry>
|
||||||
|
</mxCell>
|
||||||
|
<mxCell id="0K4eb2koB2xQ8duQ1-_a-19" edge="1" parent="L62mICw2ZrYi1D68OOFe-13" style="edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;strokeColor=#b46504;strokeWidth=2;fillColor=#fad7ac;" value="">
|
||||||
|
<mxGeometry relative="1" as="geometry">
|
||||||
|
<Array as="points" />
|
||||||
|
<mxPoint x="390" y="580" as="sourcePoint" />
|
||||||
|
<mxPoint x="462.74" y="580.22" as="targetPoint" />
|
||||||
|
</mxGeometry>
|
||||||
|
</mxCell>
|
||||||
|
<mxCell id="0K4eb2koB2xQ8duQ1-_a-22" edge="1" parent="L62mICw2ZrYi1D68OOFe-13" source="0K4eb2koB2xQ8duQ1-_a-4" style="edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;strokeColor=#9933FF;strokeWidth=2;dashed=1;exitX=0.981;exitY=0.08;exitDx=0;exitDy=0;exitPerimeter=0;" target="0K4eb2koB2xQ8duQ1-_a-8" value="">
|
||||||
|
<mxGeometry relative="1" x="0.1427" y="-60" as="geometry">
|
||||||
|
<mxPoint as="offset" />
|
||||||
|
<Array as="points">
|
||||||
|
<mxPoint x="593" y="175" />
|
||||||
|
<mxPoint x="593" y="140" />
|
||||||
|
<mxPoint x="764" y="140" />
|
||||||
|
</Array>
|
||||||
|
</mxGeometry>
|
||||||
|
</mxCell>
|
||||||
|
<mxCell id="0K4eb2koB2xQ8duQ1-_a-4" parent="L62mICw2ZrYi1D68OOFe-13" style="rounded=1;whiteSpace=wrap;html=1;fillColor=#d5e8d4;strokeColor=#82b366;align=left;verticalAlign=top;spacing=10;fontColor=#000000;" value="<b>Cr3</b> (IntersectionProcess)<div><hr></div><div>• ServerSocket (8003)<br><div>• Eventos DES:&nbsp;</div><div>&nbsp; &nbsp;- Oeste</div><div>&nbsp; &nbsp;- Sul</div><div>• Fila Eventos (DES)</div>• ReentrantLock</div><div><div>• Objetos TrafficLight</div></div><div>• Pool Threads (I/O rede)</div>" vertex="1">
|
||||||
|
<mxGeometry height="157.78" width="167.26" x="462.74" y="162.22" as="geometry" />
|
||||||
|
</mxCell>
|
||||||
|
<mxCell id="0K4eb2koB2xQ8duQ1-_a-30" edge="1" parent="L62mICw2ZrYi1D68OOFe-13" source="0K4eb2koB2xQ8duQ1-_a-5" style="edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;strokeColor=#9933FF;strokeWidth=2;dashed=1;entryX=0.186;entryY=0.998;entryDx=0;entryDy=0;entryPerimeter=0;exitX=0.638;exitY=1;exitDx=0;exitDy=0;exitPerimeter=0;" target="0K4eb2koB2xQ8duQ1-_a-8" value="">
|
||||||
|
<mxGeometry relative="1" as="geometry">
|
||||||
|
<Array as="points">
|
||||||
|
<mxPoint x="102" y="730" />
|
||||||
|
<mxPoint x="714" y="730" />
|
||||||
|
</Array>
|
||||||
|
<mxPoint x="103" y="660" as="sourcePoint" />
|
||||||
|
<mxPoint x="710" y="730" as="targetPoint" />
|
||||||
|
</mxGeometry>
|
||||||
|
</mxCell>
|
||||||
|
<mxCell id="L62mICw2ZrYi1D68OOFe-2" edge="1" parent="L62mICw2ZrYi1D68OOFe-13" style="edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;strokeColor=#00AA00;strokeWidth=2;endArrow=none;startArrow=classic;startFill=1;endFill=0;entryX=0.409;entryY=0.993;entryDx=0;entryDy=0;entryPerimeter=0;" target="0K4eb2koB2xQ8duQ1-_a-3" value="">
|
||||||
|
<mxGeometry relative="1" x="-0.2214" y="26" as="geometry">
|
||||||
|
<mxPoint x="-17" y="6" as="offset" />
|
||||||
|
<Array as="points" />
|
||||||
|
<mxPoint x="293.8053097345133" y="486.6666666666666" as="sourcePoint" />
|
||||||
|
<mxPoint x="293.8053097345133" y="324.44444444444446" as="targetPoint" />
|
||||||
|
</mxGeometry>
|
||||||
|
</mxCell>
|
||||||
|
<mxCell id="L62mICw2ZrYi1D68OOFe-10" edge="1" parent="L62mICw2ZrYi1D68OOFe-13" source="0K4eb2koB2xQ8duQ1-_a-3" style="edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;strokeColor=#9933FF;strokeWidth=2;dashed=1;exitX=0.621;exitY=-0.003;exitDx=0;exitDy=0;exitPerimeter=0;" value="">
|
||||||
|
<mxGeometry relative="1" x="0.1427" y="-60" as="geometry">
|
||||||
|
<mxPoint as="offset" />
|
||||||
|
<Array as="points">
|
||||||
|
<mxPoint x="329" y="130" />
|
||||||
|
<mxPoint x="780" y="130" />
|
||||||
|
</Array>
|
||||||
|
<mxPoint x="330.53097345132744" y="141.94444444444443" as="sourcePoint" />
|
||||||
|
<mxPoint x="780" y="540" as="targetPoint" />
|
||||||
|
</mxGeometry>
|
||||||
|
</mxCell>
|
||||||
|
<mxCell id="L62mICw2ZrYi1D68OOFe-11" edge="1" parent="L62mICw2ZrYi1D68OOFe-13" source="0K4eb2koB2xQ8duQ1-_a-6" style="edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;strokeColor=#9933FF;strokeWidth=2;dashed=1;exitX=0.627;exitY=1.014;exitDx=0;exitDy=0;exitPerimeter=0;" value="">
|
||||||
|
<mxGeometry relative="1" as="geometry">
|
||||||
|
<Array as="points">
|
||||||
|
<mxPoint x="327" y="700" />
|
||||||
|
</Array>
|
||||||
|
<mxPoint x="326" y="654" as="sourcePoint" />
|
||||||
|
<mxPoint x="683.1" y="700" as="targetPoint" />
|
||||||
|
</mxGeometry>
|
||||||
|
</mxCell>
|
||||||
|
<mxCell id="L62mICw2ZrYi1D68OOFe-12" edge="1" parent="L62mICw2ZrYi1D68OOFe-13" style="edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;strokeColor=#9933FF;strokeWidth=2;dashed=1;" value="">
|
||||||
|
<mxGeometry relative="1" as="geometry">
|
||||||
|
<Array as="points">
|
||||||
|
<mxPoint x="556" y="663" />
|
||||||
|
</Array>
|
||||||
|
<mxPoint x="556" y="650" as="sourcePoint" />
|
||||||
|
<mxPoint x="683.0973451327434" y="663.0833333333331" as="targetPoint" />
|
||||||
|
</mxGeometry>
|
||||||
|
</mxCell>
|
||||||
|
<mxCell id="J0awZyeCmWOCt0z9hVlQ-7" edge="1" parent="L62mICw2ZrYi1D68OOFe-13" source="0K4eb2koB2xQ8duQ1-_a-7" style="edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;strokeColor=light-dark(#00AA00,#C98531);strokeWidth=2;endArrow=none;startArrow=classic;startFill=1;endFill=0;exitX=0.5;exitY=0;exitDx=0;exitDy=0;" value="">
|
||||||
|
<mxGeometry relative="1" x="-0.2214" y="26" as="geometry">
|
||||||
|
<mxPoint x="-17" y="6" as="offset" />
|
||||||
|
<Array as="points" />
|
||||||
|
<mxPoint x="541" y="470" as="sourcePoint" />
|
||||||
|
<mxPoint x="541.17" y="320" as="targetPoint" />
|
||||||
|
</mxGeometry>
|
||||||
|
</mxCell>
|
||||||
|
<mxCell id="J0awZyeCmWOCt0z9hVlQ-33" edge="1" parent="L62mICw2ZrYi1D68OOFe-13" source="0K4eb2koB2xQ8duQ1-_a-3" style="edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;strokeColor=#00AA00;strokeWidth=2;endArrow=classic;startArrow=classic;entryX=-0.001;entryY=0.513;entryDx=0;entryDy=0;entryPerimeter=0;exitX=1;exitY=0.454;exitDx=0;exitDy=0;exitPerimeter=0;" target="0K4eb2koB2xQ8duQ1-_a-4" value="">
|
||||||
|
<mxGeometry relative="1" as="geometry">
|
||||||
|
<Array as="points" />
|
||||||
|
<mxPoint x="391" y="243.13" as="sourcePoint" />
|
||||||
|
<mxPoint x="460" y="243" as="targetPoint" />
|
||||||
|
</mxGeometry>
|
||||||
|
</mxCell>
|
||||||
|
</root>
|
||||||
|
</mxGraphModel>
|
||||||
|
</diagram>
|
||||||
|
</mxfile>
|
||||||
BIN
Diagrama de arquitetura.jpg
Normal file
|
After Width: | Height: | Size: 220 KiB |
BIN
Enunciado.pdf
Normal file
54
README.md
Normal file
@@ -0,0 +1,54 @@
|
|||||||
|
# DTSS - Distributed Traffic Simulation System
|
||||||
|
|
||||||
|
**Sistemas Distribuídos 2025/2026**
|
||||||
|
**Autores:** David Alves, Leandro Afonso, Gabriel Moreira
|
||||||
|
|
||||||
|
Simulador de tráfego distribuído (Malha 3x3) com comunicação TCP/IP e modelo de eventos discretos.
|
||||||
|
|
||||||
|
### 📋 Pré-requisitos
|
||||||
|
|
||||||
|
* **Java 17+**
|
||||||
|
* **Maven 3.6+**
|
||||||
|
|
||||||
|
-----
|
||||||
|
|
||||||
|
### Build
|
||||||
|
|
||||||
|
Compilar e gerar o JAR executável:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd main
|
||||||
|
mvn clean package
|
||||||
|
```
|
||||||
|
|
||||||
|
-----
|
||||||
|
|
||||||
|
### Execução
|
||||||
|
|
||||||
|
Inicia todos os processos (Dashboard, Coordenador, Nós, Saída) numa única instância.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd main
|
||||||
|
mvn javafx:run
|
||||||
|
```
|
||||||
|
|
||||||
|
-----
|
||||||
|
|
||||||
|
### Cenários de Carga
|
||||||
|
|
||||||
|
**Arquivos disponíveis em `src/main/resources/`:**
|
||||||
|
|
||||||
|
* `simulation-low.properties` ($\lambda=0.2$)
|
||||||
|
* `simulation-medium.properties` ($\lambda=0.5$)
|
||||||
|
* `simulation-high.properties` ($\lambda=1.0$)
|
||||||
|
|
||||||
|
-----
|
||||||
|
|
||||||
|
### Troubleshooting Rápido
|
||||||
|
|
||||||
|
**Port already in use / Limpeza de Processos:**
|
||||||
|
Se a simulação falhar ou portas ficarem presas, matar todos os processos Java associados:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
pkill -f "sd.IntersectionProcess|sd.dashboard.DashboardServer|sd.coordinator.CoordinatorProcess"
|
||||||
|
```
|
||||||
@@ -1,6 +0,0 @@
|
|||||||
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,215 +0,0 @@
|
|||||||
================================================================================
|
|
||||||
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
|
|
||||||
================================================================================
|
|
||||||
11
main/analysis/HIGH_LOAD_20251211-021618.csv
Normal file
@@ -0,0 +1,11 @@
|
|||||||
|
Execução,VeículosGerados,VeículosCompletados,TaxaConclusão,TempoMédioSistema,TempoMédioEspera,TempoMínimoSistema,TempoMáximoSistema
|
||||||
|
1,1801,1711,95.00,140.07,135.67,70.03,280.14
|
||||||
|
2,1796,1721,95.82,143.35,139.00,71.68,286.70
|
||||||
|
3,1834,1773,96.67,149.98,145.57,74.99,299.95
|
||||||
|
4,1799,1527,84.88,140.39,136.20,70.19,280.77
|
||||||
|
5,1830,1670,91.26,150.89,146.66,75.45,301.78
|
||||||
|
6,1833,1690,92.20,139.40,135.24,69.70,278.80
|
||||||
|
7,1822,1769,97.09,148.40,144.03,74.20,296.80
|
||||||
|
8,1756,1487,84.68,135.16,131.01,67.58,270.32
|
||||||
|
9,1829,1640,89.67,144.65,140.25,72.32,289.30
|
||||||
|
10,1784,1745,97.81,151.09,146.69,75.54,302.17
|
||||||
|
240
main/analysis/HIGH_LOAD_20251211-021618.txt
Normal file
@@ -0,0 +1,240 @@
|
|||||||
|
================================================================================
|
||||||
|
ANÁLISE ESTATÍSTICA MULTI-EXECUÇÃO
|
||||||
|
================================================================================
|
||||||
|
Configuração: simulation-high.properties
|
||||||
|
Número de Execuções: 10
|
||||||
|
Data da Análise: 2025-12-11 02:16:18
|
||||||
|
|
||||||
|
--------------------------------------------------------------------------------
|
||||||
|
MÉTRICAS GLOBAIS
|
||||||
|
--------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
Veículos Gerados:
|
||||||
|
Média: 1808.40 Desvio Padrão: 25.76
|
||||||
|
Mediana: 1811.50 IC 95%: [1787.45, 1829.35]
|
||||||
|
Mín: 1756.00 Máx: 1834.00
|
||||||
|
|
||||||
|
Veículos Completados:
|
||||||
|
Média: 1673.30 Desvio Padrão: 97.44
|
||||||
|
Mediana: 1700.50 IC 95%: [1594.08, 1752.52]
|
||||||
|
Mín: 1487.00 Máx: 1773.00
|
||||||
|
|
||||||
|
Taxa de Conclusão (%):
|
||||||
|
Média: 92.51 Desvio Padrão: 4.86
|
||||||
|
Mediana: 93.60 IC 95%: [88.55, 96.46]
|
||||||
|
Mín: 84.68 Máx: 97.81
|
||||||
|
|
||||||
|
Tempo Médio no Sistema (segundos):
|
||||||
|
Média: 144.34 Desvio Padrão: 5.58
|
||||||
|
Mediana: 144.00 IC 95%: [139.80, 148.87]
|
||||||
|
Mín: 135.16 Máx: 151.09
|
||||||
|
|
||||||
|
Tempo Médio de Espera (segundos):
|
||||||
|
Média: 140.03 Desvio Padrão: 5.52
|
||||||
|
Mediana: 139.62 IC 95%: [135.55, 144.52]
|
||||||
|
Mín: 131.01 Máx: 146.69
|
||||||
|
|
||||||
|
|
||||||
|
--------------------------------------------------------------------------------
|
||||||
|
ANÁLISE POR TIPO DE VEÍCULO
|
||||||
|
--------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
--- BIKE ---
|
||||||
|
Contagem de Veículos:
|
||||||
|
Média: 338.60 Desvio Padrão: 31.26
|
||||||
|
Mediana: 342.00 IC 95%: [313.19, 364.01]
|
||||||
|
Mín: 279.00 Máx: 377.00
|
||||||
|
|
||||||
|
Tempo Médio no Sistema (segundos): Sem dados
|
||||||
|
|
||||||
|
Tempo Médio de Espera (segundos):
|
||||||
|
Média: 140.36 Desvio Padrão: 11.64
|
||||||
|
Mediana: 138.38 IC 95%: [130.90, 149.82]
|
||||||
|
Mín: 121.77 Máx: 165.19
|
||||||
|
|
||||||
|
|
||||||
|
--- LIGHT ---
|
||||||
|
Contagem de Veículos:
|
||||||
|
Média: 991.30 Desvio Padrão: 49.19
|
||||||
|
Mediana: 1011.00 IC 95%: [951.31, 1031.29]
|
||||||
|
Mín: 893.00 Máx: 1035.00
|
||||||
|
|
||||||
|
Tempo Médio no Sistema (segundos): Sem dados
|
||||||
|
|
||||||
|
Tempo Médio de Espera (segundos):
|
||||||
|
Média: 141.44 Desvio Padrão: 7.85
|
||||||
|
Mediana: 143.16 IC 95%: [135.06, 147.83]
|
||||||
|
Mín: 130.22 Máx: 151.65
|
||||||
|
|
||||||
|
|
||||||
|
--- HEAVY ---
|
||||||
|
Contagem de Veículos:
|
||||||
|
Média: 343.40 Desvio Padrão: 29.42
|
||||||
|
Mediana: 343.00 IC 95%: [319.48, 367.32]
|
||||||
|
Mín: 288.00 Máx: 385.00
|
||||||
|
|
||||||
|
Tempo Médio no Sistema (segundos): Sem dados
|
||||||
|
|
||||||
|
Tempo Médio de Espera (segundos):
|
||||||
|
Média: 135.81 Desvio Padrão: 9.45
|
||||||
|
Mediana: 134.25 IC 95%: [128.13, 143.49]
|
||||||
|
Mín: 118.95 Máx: 149.71
|
||||||
|
|
||||||
|
|
||||||
|
--------------------------------------------------------------------------------
|
||||||
|
ANÁLISE POR INTERSEÇÃO
|
||||||
|
--------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
--- Cr1 ---
|
||||||
|
Tamanho Máximo da Fila:
|
||||||
|
Média: 0.70 Desvio Padrão: 1.25
|
||||||
|
Mediana: 0.00 IC 95%: [-0.32, 1.72]
|
||||||
|
Mín: 0.00 Máx: 3.00
|
||||||
|
|
||||||
|
Tamanho Médio da Fila:
|
||||||
|
Média: 0.70 Desvio Padrão: 1.25
|
||||||
|
Mediana: 0.00 IC 95%: [-0.32, 1.72]
|
||||||
|
Mín: 0.00 Máx: 3.00
|
||||||
|
|
||||||
|
Veículos Processados:
|
||||||
|
Média: 578.20 Desvio Padrão: 50.05
|
||||||
|
Mediana: 604.00 IC 95%: [537.51, 618.89]
|
||||||
|
Mín: 493.00 Máx: 626.00
|
||||||
|
|
||||||
|
|
||||||
|
--- Cr2 ---
|
||||||
|
Tamanho Máximo da Fila:
|
||||||
|
Média: 1.40 Desvio Padrão: 2.37
|
||||||
|
Mediana: 0.00 IC 95%: [-0.52, 3.32]
|
||||||
|
Mín: 0.00 Máx: 6.00
|
||||||
|
|
||||||
|
Tamanho Médio da Fila:
|
||||||
|
Média: 1.40 Desvio Padrão: 2.37
|
||||||
|
Mediana: 0.00 IC 95%: [-0.52, 3.32]
|
||||||
|
Mín: 0.00 Máx: 6.00
|
||||||
|
|
||||||
|
Veículos Processados:
|
||||||
|
Média: 550.30 Desvio Padrão: 50.21
|
||||||
|
Mediana: 540.00 IC 95%: [509.48, 591.12]
|
||||||
|
Mín: 459.00 Máx: 616.00
|
||||||
|
|
||||||
|
|
||||||
|
--- Cr3 ---
|
||||||
|
Tamanho Máximo da Fila:
|
||||||
|
Média: 0.40 Desvio Padrão: 1.26
|
||||||
|
Mediana: 0.00 IC 95%: [-0.63, 1.43]
|
||||||
|
Mín: 0.00 Máx: 4.00
|
||||||
|
|
||||||
|
Tamanho Médio da Fila:
|
||||||
|
Média: 0.40 Desvio Padrão: 1.26
|
||||||
|
Mediana: 0.00 IC 95%: [-0.63, 1.43]
|
||||||
|
Mín: 0.00 Máx: 4.00
|
||||||
|
|
||||||
|
Veículos Processados:
|
||||||
|
Média: 589.10 Desvio Padrão: 42.91
|
||||||
|
Mediana: 595.00 IC 95%: [554.21, 623.99]
|
||||||
|
Mín: 502.00 Máx: 671.00
|
||||||
|
|
||||||
|
|
||||||
|
--- Cr4 ---
|
||||||
|
Tamanho Máximo da Fila:
|
||||||
|
Média: 1.50 Desvio Padrão: 1.58
|
||||||
|
Mediana: 1.00 IC 95%: [0.21, 2.79]
|
||||||
|
Mín: 0.00 Máx: 5.00
|
||||||
|
|
||||||
|
Tamanho Médio da Fila:
|
||||||
|
Média: 1.50 Desvio Padrão: 1.58
|
||||||
|
Mediana: 1.00 IC 95%: [0.21, 2.79]
|
||||||
|
Mín: 0.00 Máx: 5.00
|
||||||
|
|
||||||
|
Veículos Processados:
|
||||||
|
Média: 540.10 Desvio Padrão: 52.20
|
||||||
|
Mediana: 549.50 IC 95%: [497.66, 582.54]
|
||||||
|
Mín: 442.00 Máx: 603.00
|
||||||
|
|
||||||
|
|
||||||
|
--- Cr5 ---
|
||||||
|
Tamanho Máximo da Fila:
|
||||||
|
Média: 1.50 Desvio Padrão: 1.51
|
||||||
|
Mediana: 1.00 IC 95%: [0.27, 2.73]
|
||||||
|
Mín: 0.00 Máx: 4.00
|
||||||
|
|
||||||
|
Tamanho Médio da Fila:
|
||||||
|
Média: 1.50 Desvio Padrão: 1.51
|
||||||
|
Mediana: 1.00 IC 95%: [0.27, 2.73]
|
||||||
|
Mín: 0.00 Máx: 4.00
|
||||||
|
|
||||||
|
Veículos Processados:
|
||||||
|
Média: 1075.10 Desvio Padrão: 78.71
|
||||||
|
Mediana: 1064.00 IC 95%: [1011.11, 1139.09]
|
||||||
|
Mín: 920.00 Máx: 1176.00
|
||||||
|
|
||||||
|
|
||||||
|
--- ExitNode ---
|
||||||
|
Tamanho Máximo da Fila: Sem dados
|
||||||
|
|
||||||
|
Tamanho Médio da Fila: Sem dados
|
||||||
|
|
||||||
|
Veículos Processados:
|
||||||
|
Média: 1673.30 Desvio Padrão: 97.44
|
||||||
|
Mediana: 1700.50 IC 95%: [1594.08, 1752.52]
|
||||||
|
Mín: 1487.00 Máx: 1773.00
|
||||||
|
|
||||||
|
|
||||||
|
--------------------------------------------------------------------------------
|
||||||
|
RESUMOS INDIVIDUAIS DAS EXECUÇÕES
|
||||||
|
--------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
Execução #1 [simulation-high.properties]:
|
||||||
|
Gerados: 1801, Completados: 1711 (95.0%)
|
||||||
|
Tempo Médio no Sistema: 140.07s
|
||||||
|
Tempo Médio de Espera: 135.67s
|
||||||
|
|
||||||
|
Execução #2 [simulation-high.properties]:
|
||||||
|
Gerados: 1796, Completados: 1721 (95.8%)
|
||||||
|
Tempo Médio no Sistema: 143.35s
|
||||||
|
Tempo Médio de Espera: 139.00s
|
||||||
|
|
||||||
|
Execução #3 [simulation-high.properties]:
|
||||||
|
Gerados: 1834, Completados: 1773 (96.7%)
|
||||||
|
Tempo Médio no Sistema: 149.98s
|
||||||
|
Tempo Médio de Espera: 145.57s
|
||||||
|
|
||||||
|
Execução #4 [simulation-high.properties]:
|
||||||
|
Gerados: 1799, Completados: 1527 (84.9%)
|
||||||
|
Tempo Médio no Sistema: 140.39s
|
||||||
|
Tempo Médio de Espera: 136.20s
|
||||||
|
|
||||||
|
Execução #5 [simulation-high.properties]:
|
||||||
|
Gerados: 1830, Completados: 1670 (91.3%)
|
||||||
|
Tempo Médio no Sistema: 150.89s
|
||||||
|
Tempo Médio de Espera: 146.66s
|
||||||
|
|
||||||
|
Execução #6 [simulation-high.properties]:
|
||||||
|
Gerados: 1833, Completados: 1690 (92.2%)
|
||||||
|
Tempo Médio no Sistema: 139.40s
|
||||||
|
Tempo Médio de Espera: 135.24s
|
||||||
|
|
||||||
|
Execução #7 [simulation-high.properties]:
|
||||||
|
Gerados: 1822, Completados: 1769 (97.1%)
|
||||||
|
Tempo Médio no Sistema: 148.40s
|
||||||
|
Tempo Médio de Espera: 144.03s
|
||||||
|
|
||||||
|
Execução #8 [simulation-high.properties]:
|
||||||
|
Gerados: 1756, Completados: 1487 (84.7%)
|
||||||
|
Tempo Médio no Sistema: 135.16s
|
||||||
|
Tempo Médio de Espera: 131.01s
|
||||||
|
|
||||||
|
Execução #9 [simulation-high.properties]:
|
||||||
|
Gerados: 1829, Completados: 1640 (89.7%)
|
||||||
|
Tempo Médio no Sistema: 144.65s
|
||||||
|
Tempo Médio de Espera: 140.25s
|
||||||
|
|
||||||
|
Execução #10 [simulation-high.properties]:
|
||||||
|
Gerados: 1784, Completados: 1745 (97.8%)
|
||||||
|
Tempo Médio no Sistema: 151.09s
|
||||||
|
Tempo Médio de Espera: 146.69s
|
||||||
|
|
||||||
|
================================================================================
|
||||||
|
FIM DO RELATÓRIO
|
||||||
|
================================================================================
|
||||||
@@ -1,6 +0,0 @@
|
|||||||
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,209 +0,0 @@
|
|||||||
================================================================================
|
|
||||||
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
|
|
||||||
================================================================================
|
|
||||||
11
main/analysis/LOW_LOAD_20251211-021249.csv
Normal file
@@ -0,0 +1,11 @@
|
|||||||
|
Execução,VeículosGerados,VeículosCompletados,TaxaConclusão,TempoMédioSistema,TempoMédioEspera,TempoMínimoSistema,TempoMáximoSistema
|
||||||
|
1,353,334,94.62,78.12,73.90,39.06,156.25
|
||||||
|
2,366,359,98.09,90.80,86.56,45.40,181.60
|
||||||
|
3,352,340,96.59,78.90,74.45,39.45,157.79
|
||||||
|
4,362,347,95.86,69.35,64.88,34.68,138.71
|
||||||
|
5,338,324,95.86,71.04,66.72,35.52,142.08
|
||||||
|
6,371,366,98.65,79.54,75.17,39.77,159.09
|
||||||
|
7,355,345,97.18,69.18,64.63,34.59,138.35
|
||||||
|
8,364,361,99.18,79.69,75.35,39.84,159.37
|
||||||
|
9,363,309,85.12,71.72,67.62,35.86,143.44
|
||||||
|
10,386,376,97.41,78.78,74.30,39.39,157.56
|
||||||
|
240
main/analysis/LOW_LOAD_20251211-021249.txt
Normal file
@@ -0,0 +1,240 @@
|
|||||||
|
================================================================================
|
||||||
|
ANÁLISE ESTATÍSTICA MULTI-EXECUÇÃO
|
||||||
|
================================================================================
|
||||||
|
Configuração: simulation-low.properties
|
||||||
|
Número de Execuções: 10
|
||||||
|
Data da Análise: 2025-12-11 02:12:49
|
||||||
|
|
||||||
|
--------------------------------------------------------------------------------
|
||||||
|
MÉTRICAS GLOBAIS
|
||||||
|
--------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
Veículos Gerados:
|
||||||
|
Média: 361.00 Desvio Padrão: 12.80
|
||||||
|
Mediana: 362.50 IC 95%: [350.60, 371.40]
|
||||||
|
Mín: 338.00 Máx: 386.00
|
||||||
|
|
||||||
|
Veículos Completados:
|
||||||
|
Média: 346.10 Desvio Padrão: 20.35
|
||||||
|
Mediana: 346.00 IC 95%: [329.55, 362.65]
|
||||||
|
Mín: 309.00 Máx: 376.00
|
||||||
|
|
||||||
|
Taxa de Conclusão (%):
|
||||||
|
Média: 95.86 Desvio Padrão: 4.02
|
||||||
|
Mediana: 96.89 IC 95%: [92.59, 99.12]
|
||||||
|
Mín: 85.12 Máx: 99.18
|
||||||
|
|
||||||
|
Tempo Médio no Sistema (segundos):
|
||||||
|
Média: 76.71 Desvio Padrão: 6.62
|
||||||
|
Mediana: 78.45 IC 95%: [71.33, 82.09]
|
||||||
|
Mín: 69.18 Máx: 90.80
|
||||||
|
|
||||||
|
Tempo Médio de Espera (segundos):
|
||||||
|
Média: 72.36 Desvio Padrão: 6.66
|
||||||
|
Mediana: 74.10 IC 95%: [66.95, 77.77]
|
||||||
|
Mín: 64.63 Máx: 86.56
|
||||||
|
|
||||||
|
|
||||||
|
--------------------------------------------------------------------------------
|
||||||
|
ANÁLISE POR TIPO DE VEÍCULO
|
||||||
|
--------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
--- BIKE ---
|
||||||
|
Contagem de Veículos:
|
||||||
|
Média: 69.60 Desvio Padrão: 6.69
|
||||||
|
Mediana: 71.00 IC 95%: [64.16, 75.04]
|
||||||
|
Mín: 58.00 Máx: 78.00
|
||||||
|
|
||||||
|
Tempo Médio no Sistema (segundos): Sem dados
|
||||||
|
|
||||||
|
Tempo Médio de Espera (segundos):
|
||||||
|
Média: 68.27 Desvio Padrão: 18.90
|
||||||
|
Mediana: 61.61 IC 95%: [52.90, 83.64]
|
||||||
|
Mín: 55.09 Máx: 119.43
|
||||||
|
|
||||||
|
|
||||||
|
--- LIGHT ---
|
||||||
|
Contagem de Veículos:
|
||||||
|
Média: 204.80 Desvio Padrão: 13.91
|
||||||
|
Mediana: 202.00 IC 95%: [193.49, 216.11]
|
||||||
|
Mín: 185.00 Máx: 231.00
|
||||||
|
|
||||||
|
Tempo Médio no Sistema (segundos): Sem dados
|
||||||
|
|
||||||
|
Tempo Médio de Espera (segundos):
|
||||||
|
Média: 72.78 Desvio Padrão: 7.41
|
||||||
|
Mediana: 72.59 IC 95%: [66.76, 78.80]
|
||||||
|
Mín: 63.84 Máx: 83.07
|
||||||
|
|
||||||
|
|
||||||
|
--- HEAVY ---
|
||||||
|
Contagem de Veículos:
|
||||||
|
Média: 71.70 Desvio Padrão: 8.33
|
||||||
|
Mediana: 70.00 IC 95%: [64.93, 78.47]
|
||||||
|
Mín: 60.00 Máx: 83.00
|
||||||
|
|
||||||
|
Tempo Médio no Sistema (segundos): Sem dados
|
||||||
|
|
||||||
|
Tempo Médio de Espera (segundos):
|
||||||
|
Média: 75.65 Desvio Padrão: 17.00
|
||||||
|
Mediana: 69.72 IC 95%: [61.83, 89.47]
|
||||||
|
Mín: 61.05 Máx: 116.12
|
||||||
|
|
||||||
|
|
||||||
|
--------------------------------------------------------------------------------
|
||||||
|
ANÁLISE POR INTERSEÇÃO
|
||||||
|
--------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
--- Cr1 ---
|
||||||
|
Tamanho Máximo da Fila:
|
||||||
|
Média: 1.50 Desvio Padrão: 2.68
|
||||||
|
Mediana: 0.00 IC 95%: [-0.68, 3.68]
|
||||||
|
Mín: 0.00 Máx: 7.00
|
||||||
|
|
||||||
|
Tamanho Médio da Fila:
|
||||||
|
Média: 1.50 Desvio Padrão: 2.68
|
||||||
|
Mediana: 0.00 IC 95%: [-0.68, 3.68]
|
||||||
|
Mín: 0.00 Máx: 7.00
|
||||||
|
|
||||||
|
Veículos Processados:
|
||||||
|
Média: 118.90 Desvio Padrão: 6.37
|
||||||
|
Mediana: 119.50 IC 95%: [113.72, 124.08]
|
||||||
|
Mín: 109.00 Máx: 127.00
|
||||||
|
|
||||||
|
|
||||||
|
--- Cr2 ---
|
||||||
|
Tamanho Máximo da Fila:
|
||||||
|
Média: 0.80 Desvio Padrão: 1.32
|
||||||
|
Mediana: 0.00 IC 95%: [-0.27, 1.87]
|
||||||
|
Mín: 0.00 Máx: 4.00
|
||||||
|
|
||||||
|
Tamanho Médio da Fila:
|
||||||
|
Média: 0.80 Desvio Padrão: 1.32
|
||||||
|
Mediana: 0.00 IC 95%: [-0.27, 1.87]
|
||||||
|
Mín: 0.00 Máx: 4.00
|
||||||
|
|
||||||
|
Veículos Processados:
|
||||||
|
Média: 118.30 Desvio Padrão: 8.82
|
||||||
|
Mediana: 121.00 IC 95%: [111.13, 125.47]
|
||||||
|
Mín: 104.00 Máx: 128.00
|
||||||
|
|
||||||
|
|
||||||
|
--- Cr3 ---
|
||||||
|
Tamanho Máximo da Fila:
|
||||||
|
Média: 0.30 Desvio Padrão: 0.48
|
||||||
|
Mediana: 0.00 IC 95%: [-0.09, 0.69]
|
||||||
|
Mín: 0.00 Máx: 1.00
|
||||||
|
|
||||||
|
Tamanho Médio da Fila:
|
||||||
|
Média: 0.30 Desvio Padrão: 0.48
|
||||||
|
Mediana: 0.00 IC 95%: [-0.09, 0.69]
|
||||||
|
Mín: 0.00 Máx: 1.00
|
||||||
|
|
||||||
|
Veículos Processados:
|
||||||
|
Média: 120.70 Desvio Padrão: 10.27
|
||||||
|
Mediana: 121.50 IC 95%: [112.35, 129.05]
|
||||||
|
Mín: 108.00 Máx: 132.00
|
||||||
|
|
||||||
|
|
||||||
|
--- Cr4 ---
|
||||||
|
Tamanho Máximo da Fila:
|
||||||
|
Média: 1.20 Desvio Padrão: 1.48
|
||||||
|
Mediana: 0.50 IC 95%: [0.00, 2.40]
|
||||||
|
Mín: 0.00 Máx: 4.00
|
||||||
|
|
||||||
|
Tamanho Médio da Fila:
|
||||||
|
Média: 1.20 Desvio Padrão: 1.48
|
||||||
|
Mediana: 0.50 IC 95%: [0.00, 2.40]
|
||||||
|
Mín: 0.00 Máx: 4.00
|
||||||
|
|
||||||
|
Veículos Processados:
|
||||||
|
Média: 111.50 Desvio Padrão: 13.71
|
||||||
|
Mediana: 115.00 IC 95%: [100.35, 122.65]
|
||||||
|
Mín: 79.00 Máx: 127.00
|
||||||
|
|
||||||
|
|
||||||
|
--- Cr5 ---
|
||||||
|
Tamanho Máximo da Fila:
|
||||||
|
Média: 1.60 Desvio Padrão: 1.35
|
||||||
|
Mediana: 1.00 IC 95%: [0.50, 2.70]
|
||||||
|
Mín: 0.00 Máx: 4.00
|
||||||
|
|
||||||
|
Tamanho Médio da Fila:
|
||||||
|
Média: 1.60 Desvio Padrão: 1.35
|
||||||
|
Mediana: 1.00 IC 95%: [0.50, 2.70]
|
||||||
|
Mín: 0.00 Máx: 4.00
|
||||||
|
|
||||||
|
Veículos Processados:
|
||||||
|
Média: 225.40 Desvio Padrão: 21.42
|
||||||
|
Mediana: 232.50 IC 95%: [207.99, 242.81]
|
||||||
|
Mín: 178.00 Máx: 251.00
|
||||||
|
|
||||||
|
|
||||||
|
--- ExitNode ---
|
||||||
|
Tamanho Máximo da Fila: Sem dados
|
||||||
|
|
||||||
|
Tamanho Médio da Fila: Sem dados
|
||||||
|
|
||||||
|
Veículos Processados:
|
||||||
|
Média: 346.10 Desvio Padrão: 20.35
|
||||||
|
Mediana: 346.00 IC 95%: [329.55, 362.65]
|
||||||
|
Mín: 309.00 Máx: 376.00
|
||||||
|
|
||||||
|
|
||||||
|
--------------------------------------------------------------------------------
|
||||||
|
RESUMOS INDIVIDUAIS DAS EXECUÇÕES
|
||||||
|
--------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
Execução #1 [simulation-low.properties]:
|
||||||
|
Gerados: 353, Completados: 334 (94.6%)
|
||||||
|
Tempo Médio no Sistema: 78.12s
|
||||||
|
Tempo Médio de Espera: 73.90s
|
||||||
|
|
||||||
|
Execução #2 [simulation-low.properties]:
|
||||||
|
Gerados: 366, Completados: 359 (98.1%)
|
||||||
|
Tempo Médio no Sistema: 90.80s
|
||||||
|
Tempo Médio de Espera: 86.56s
|
||||||
|
|
||||||
|
Execução #3 [simulation-low.properties]:
|
||||||
|
Gerados: 352, Completados: 340 (96.6%)
|
||||||
|
Tempo Médio no Sistema: 78.90s
|
||||||
|
Tempo Médio de Espera: 74.45s
|
||||||
|
|
||||||
|
Execução #4 [simulation-low.properties]:
|
||||||
|
Gerados: 362, Completados: 347 (95.9%)
|
||||||
|
Tempo Médio no Sistema: 69.35s
|
||||||
|
Tempo Médio de Espera: 64.88s
|
||||||
|
|
||||||
|
Execução #5 [simulation-low.properties]:
|
||||||
|
Gerados: 338, Completados: 324 (95.9%)
|
||||||
|
Tempo Médio no Sistema: 71.04s
|
||||||
|
Tempo Médio de Espera: 66.72s
|
||||||
|
|
||||||
|
Execução #6 [simulation-low.properties]:
|
||||||
|
Gerados: 371, Completados: 366 (98.7%)
|
||||||
|
Tempo Médio no Sistema: 79.54s
|
||||||
|
Tempo Médio de Espera: 75.17s
|
||||||
|
|
||||||
|
Execução #7 [simulation-low.properties]:
|
||||||
|
Gerados: 355, Completados: 345 (97.2%)
|
||||||
|
Tempo Médio no Sistema: 69.18s
|
||||||
|
Tempo Médio de Espera: 64.63s
|
||||||
|
|
||||||
|
Execução #8 [simulation-low.properties]:
|
||||||
|
Gerados: 364, Completados: 361 (99.2%)
|
||||||
|
Tempo Médio no Sistema: 79.69s
|
||||||
|
Tempo Médio de Espera: 75.35s
|
||||||
|
|
||||||
|
Execução #9 [simulation-low.properties]:
|
||||||
|
Gerados: 363, Completados: 309 (85.1%)
|
||||||
|
Tempo Médio no Sistema: 71.72s
|
||||||
|
Tempo Médio de Espera: 67.62s
|
||||||
|
|
||||||
|
Execução #10 [simulation-low.properties]:
|
||||||
|
Gerados: 386, Completados: 376 (97.4%)
|
||||||
|
Tempo Médio no Sistema: 78.78s
|
||||||
|
Tempo Médio de Espera: 74.30s
|
||||||
|
|
||||||
|
================================================================================
|
||||||
|
FIM DO RELATÓRIO
|
||||||
|
================================================================================
|
||||||
@@ -1,6 +0,0 @@
|
|||||||
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,203 +0,0 @@
|
|||||||
================================================================================
|
|
||||||
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
|
|
||||||
================================================================================
|
|
||||||
11
main/analysis/MEDIUM_LOAD_20251211-021429.csv
Normal file
@@ -0,0 +1,11 @@
|
|||||||
|
Execução,VeículosGerados,VeículosCompletados,TaxaConclusão,TempoMédioSistema,TempoMédioEspera,TempoMínimoSistema,TempoMáximoSistema
|
||||||
|
1,923,887,96.10,100.39,96.03,50.19,200.77
|
||||||
|
2,858,577,67.25,98.33,94.50,49.16,196.66
|
||||||
|
3,873,832,95.30,101.24,96.81,50.62,202.47
|
||||||
|
4,898,844,93.99,95.70,91.31,47.85,191.40
|
||||||
|
5,862,697,80.86,91.12,87.17,45.56,182.24
|
||||||
|
6,881,785,89.10,120.88,116.38,60.44,241.76
|
||||||
|
7,948,901,95.04,99.22,94.72,49.61,198.43
|
||||||
|
8,873,621,71.13,97.97,93.93,48.99,195.94
|
||||||
|
9,848,807,95.17,94.44,90.15,47.22,188.88
|
||||||
|
10,927,880,94.93,103.89,99.48,51.95,207.78
|
||||||
|
240
main/analysis/MEDIUM_LOAD_20251211-021429.txt
Normal file
@@ -0,0 +1,240 @@
|
|||||||
|
================================================================================
|
||||||
|
ANÁLISE ESTATÍSTICA MULTI-EXECUÇÃO
|
||||||
|
================================================================================
|
||||||
|
Configuração: simulation-medium.properties
|
||||||
|
Número de Execuções: 10
|
||||||
|
Data da Análise: 2025-12-11 02:14:29
|
||||||
|
|
||||||
|
--------------------------------------------------------------------------------
|
||||||
|
MÉTRICAS GLOBAIS
|
||||||
|
--------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
Veículos Gerados:
|
||||||
|
Média: 889.10 Desvio Padrão: 33.51
|
||||||
|
Mediana: 877.00 IC 95%: [861.85, 916.35]
|
||||||
|
Mín: 848.00 Máx: 948.00
|
||||||
|
|
||||||
|
Veículos Completados:
|
||||||
|
Média: 783.10 Desvio Padrão: 113.98
|
||||||
|
Mediana: 819.50 IC 95%: [690.43, 875.77]
|
||||||
|
Mín: 577.00 Máx: 901.00
|
||||||
|
|
||||||
|
Taxa de Conclusão (%):
|
||||||
|
Média: 87.89 Desvio Padrão: 10.91
|
||||||
|
Mediana: 94.46 IC 95%: [79.02, 96.76]
|
||||||
|
Mín: 67.25 Máx: 96.10
|
||||||
|
|
||||||
|
Tempo Médio no Sistema (segundos):
|
||||||
|
Média: 100.32 Desvio Padrão: 8.08
|
||||||
|
Mediana: 98.77 IC 95%: [93.75, 106.89]
|
||||||
|
Mín: 91.12 Máx: 120.88
|
||||||
|
|
||||||
|
Tempo Médio de Espera (segundos):
|
||||||
|
Média: 96.05 Desvio Padrão: 7.96
|
||||||
|
Mediana: 94.61 IC 95%: [89.58, 102.52]
|
||||||
|
Mín: 87.17 Máx: 116.38
|
||||||
|
|
||||||
|
|
||||||
|
--------------------------------------------------------------------------------
|
||||||
|
ANÁLISE POR TIPO DE VEÍCULO
|
||||||
|
--------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
--- BIKE ---
|
||||||
|
Contagem de Veículos:
|
||||||
|
Média: 157.20 Desvio Padrão: 23.74
|
||||||
|
Mediana: 163.50 IC 95%: [137.90, 176.50]
|
||||||
|
Mín: 113.00 Máx: 183.00
|
||||||
|
|
||||||
|
Tempo Médio no Sistema (segundos): Sem dados
|
||||||
|
|
||||||
|
Tempo Médio de Espera (segundos):
|
||||||
|
Média: 98.61 Desvio Padrão: 15.54
|
||||||
|
Mediana: 97.14 IC 95%: [85.98, 111.24]
|
||||||
|
Mín: 81.15 Máx: 135.92
|
||||||
|
|
||||||
|
|
||||||
|
--- LIGHT ---
|
||||||
|
Contagem de Veículos:
|
||||||
|
Média: 469.20 Desvio Padrão: 67.33
|
||||||
|
Mediana: 491.00 IC 95%: [414.46, 523.94]
|
||||||
|
Mín: 336.00 Máx: 539.00
|
||||||
|
|
||||||
|
Tempo Médio no Sistema (segundos): Sem dados
|
||||||
|
|
||||||
|
Tempo Médio de Espera (segundos):
|
||||||
|
Média: 94.53 Desvio Padrão: 11.74
|
||||||
|
Mediana: 93.58 IC 95%: [84.98, 104.08]
|
||||||
|
Mín: 78.21 Máx: 120.14
|
||||||
|
|
||||||
|
|
||||||
|
--- HEAVY ---
|
||||||
|
Contagem de Veículos:
|
||||||
|
Média: 156.70 Desvio Padrão: 27.98
|
||||||
|
Mediana: 167.50 IC 95%: [133.95, 179.45]
|
||||||
|
Mín: 117.00 Máx: 192.00
|
||||||
|
|
||||||
|
Tempo Médio no Sistema (segundos): Sem dados
|
||||||
|
|
||||||
|
Tempo Médio de Espera (segundos):
|
||||||
|
Média: 98.43 Desvio Padrão: 8.24
|
||||||
|
Mediana: 98.39 IC 95%: [91.73, 105.13]
|
||||||
|
Mín: 84.28 Máx: 111.64
|
||||||
|
|
||||||
|
|
||||||
|
--------------------------------------------------------------------------------
|
||||||
|
ANÁLISE POR INTERSEÇÃO
|
||||||
|
--------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
--- Cr1 ---
|
||||||
|
Tamanho Máximo da Fila:
|
||||||
|
Média: 0.50 Desvio Padrão: 1.08
|
||||||
|
Mediana: 0.00 IC 95%: [-0.38, 1.38]
|
||||||
|
Mín: 0.00 Máx: 3.00
|
||||||
|
|
||||||
|
Tamanho Médio da Fila:
|
||||||
|
Média: 0.50 Desvio Padrão: 1.08
|
||||||
|
Mediana: 0.00 IC 95%: [-0.38, 1.38]
|
||||||
|
Mín: 0.00 Máx: 3.00
|
||||||
|
|
||||||
|
Veículos Processados:
|
||||||
|
Média: 290.40 Desvio Padrão: 33.98
|
||||||
|
Mediana: 300.50 IC 95%: [262.77, 318.03]
|
||||||
|
Mín: 224.00 Máx: 337.00
|
||||||
|
|
||||||
|
|
||||||
|
--- Cr2 ---
|
||||||
|
Tamanho Máximo da Fila:
|
||||||
|
Média: 2.80 Desvio Padrão: 5.47
|
||||||
|
Mediana: 0.00 IC 95%: [-1.65, 7.25]
|
||||||
|
Mín: 0.00 Máx: 15.00
|
||||||
|
|
||||||
|
Tamanho Médio da Fila:
|
||||||
|
Média: 2.80 Desvio Padrão: 5.47
|
||||||
|
Mediana: 0.00 IC 95%: [-1.65, 7.25]
|
||||||
|
Mín: 0.00 Máx: 15.00
|
||||||
|
|
||||||
|
Veículos Processados:
|
||||||
|
Média: 281.70 Desvio Padrão: 23.73
|
||||||
|
Mediana: 284.50 IC 95%: [262.41, 300.99]
|
||||||
|
Mín: 245.00 Máx: 323.00
|
||||||
|
|
||||||
|
|
||||||
|
--- Cr3 ---
|
||||||
|
Tamanho Máximo da Fila:
|
||||||
|
Média: 0.30 Desvio Padrão: 0.48
|
||||||
|
Mediana: 0.00 IC 95%: [-0.09, 0.69]
|
||||||
|
Mín: 0.00 Máx: 1.00
|
||||||
|
|
||||||
|
Tamanho Médio da Fila:
|
||||||
|
Média: 0.30 Desvio Padrão: 0.48
|
||||||
|
Mediana: 0.00 IC 95%: [-0.09, 0.69]
|
||||||
|
Mín: 0.00 Máx: 1.00
|
||||||
|
|
||||||
|
Veículos Processados:
|
||||||
|
Média: 277.30 Desvio Padrão: 27.14
|
||||||
|
Mediana: 280.50 IC 95%: [255.24, 299.36]
|
||||||
|
Mín: 220.00 Máx: 314.00
|
||||||
|
|
||||||
|
|
||||||
|
--- Cr4 ---
|
||||||
|
Tamanho Máximo da Fila:
|
||||||
|
Média: 1.60 Desvio Padrão: 1.07
|
||||||
|
Mediana: 2.00 IC 95%: [0.73, 2.47]
|
||||||
|
Mín: 0.00 Máx: 3.00
|
||||||
|
|
||||||
|
Tamanho Médio da Fila:
|
||||||
|
Média: 1.60 Desvio Padrão: 1.07
|
||||||
|
Mediana: 2.00 IC 95%: [0.73, 2.47]
|
||||||
|
Mín: 0.00 Máx: 3.00
|
||||||
|
|
||||||
|
Veículos Processados:
|
||||||
|
Média: 272.80 Desvio Padrão: 31.86
|
||||||
|
Mediana: 274.50 IC 95%: [246.90, 298.70]
|
||||||
|
Mín: 204.00 Máx: 324.00
|
||||||
|
|
||||||
|
|
||||||
|
--- Cr5 ---
|
||||||
|
Tamanho Máximo da Fila:
|
||||||
|
Média: 2.70 Desvio Padrão: 2.45
|
||||||
|
Mediana: 2.00 IC 95%: [0.71, 4.69]
|
||||||
|
Mín: 0.00 Máx: 8.00
|
||||||
|
|
||||||
|
Tamanho Médio da Fila:
|
||||||
|
Média: 2.70 Desvio Padrão: 2.45
|
||||||
|
Mediana: 2.00 IC 95%: [0.71, 4.69]
|
||||||
|
Mín: 0.00 Máx: 8.00
|
||||||
|
|
||||||
|
Veículos Processados:
|
||||||
|
Média: 532.80 Desvio Padrão: 56.13
|
||||||
|
Mediana: 538.00 IC 95%: [487.17, 578.43]
|
||||||
|
Mín: 407.00 Máx: 615.00
|
||||||
|
|
||||||
|
|
||||||
|
--- ExitNode ---
|
||||||
|
Tamanho Máximo da Fila: Sem dados
|
||||||
|
|
||||||
|
Tamanho Médio da Fila: Sem dados
|
||||||
|
|
||||||
|
Veículos Processados:
|
||||||
|
Média: 783.10 Desvio Padrão: 113.98
|
||||||
|
Mediana: 819.50 IC 95%: [690.43, 875.77]
|
||||||
|
Mín: 577.00 Máx: 901.00
|
||||||
|
|
||||||
|
|
||||||
|
--------------------------------------------------------------------------------
|
||||||
|
RESUMOS INDIVIDUAIS DAS EXECUÇÕES
|
||||||
|
--------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
Execução #1 [simulation-medium.properties]:
|
||||||
|
Gerados: 923, Completados: 887 (96.1%)
|
||||||
|
Tempo Médio no Sistema: 100.39s
|
||||||
|
Tempo Médio de Espera: 96.03s
|
||||||
|
|
||||||
|
Execução #2 [simulation-medium.properties]:
|
||||||
|
Gerados: 858, Completados: 577 (67.2%)
|
||||||
|
Tempo Médio no Sistema: 98.33s
|
||||||
|
Tempo Médio de Espera: 94.50s
|
||||||
|
|
||||||
|
Execução #3 [simulation-medium.properties]:
|
||||||
|
Gerados: 873, Completados: 832 (95.3%)
|
||||||
|
Tempo Médio no Sistema: 101.24s
|
||||||
|
Tempo Médio de Espera: 96.81s
|
||||||
|
|
||||||
|
Execução #4 [simulation-medium.properties]:
|
||||||
|
Gerados: 898, Completados: 844 (94.0%)
|
||||||
|
Tempo Médio no Sistema: 95.70s
|
||||||
|
Tempo Médio de Espera: 91.31s
|
||||||
|
|
||||||
|
Execução #5 [simulation-medium.properties]:
|
||||||
|
Gerados: 862, Completados: 697 (80.9%)
|
||||||
|
Tempo Médio no Sistema: 91.12s
|
||||||
|
Tempo Médio de Espera: 87.17s
|
||||||
|
|
||||||
|
Execução #6 [simulation-medium.properties]:
|
||||||
|
Gerados: 881, Completados: 785 (89.1%)
|
||||||
|
Tempo Médio no Sistema: 120.88s
|
||||||
|
Tempo Médio de Espera: 116.38s
|
||||||
|
|
||||||
|
Execução #7 [simulation-medium.properties]:
|
||||||
|
Gerados: 948, Completados: 901 (95.0%)
|
||||||
|
Tempo Médio no Sistema: 99.22s
|
||||||
|
Tempo Médio de Espera: 94.72s
|
||||||
|
|
||||||
|
Execução #8 [simulation-medium.properties]:
|
||||||
|
Gerados: 873, Completados: 621 (71.1%)
|
||||||
|
Tempo Médio no Sistema: 97.97s
|
||||||
|
Tempo Médio de Espera: 93.93s
|
||||||
|
|
||||||
|
Execução #9 [simulation-medium.properties]:
|
||||||
|
Gerados: 848, Completados: 807 (95.2%)
|
||||||
|
Tempo Médio no Sistema: 94.44s
|
||||||
|
Tempo Médio de Espera: 90.15s
|
||||||
|
|
||||||
|
Execução #10 [simulation-medium.properties]:
|
||||||
|
Gerados: 927, Completados: 880 (94.9%)
|
||||||
|
Tempo Médio no Sistema: 103.89s
|
||||||
|
Tempo Médio de Espera: 99.48s
|
||||||
|
|
||||||
|
================================================================================
|
||||||
|
FIM DO RELATÓRIO
|
||||||
|
================================================================================
|
||||||
365
main/graphing_all.py
Normal file
@@ -0,0 +1,365 @@
|
|||||||
|
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"Aviso: Nenhum ficheiro encontrado com o padrão '{pattern}'")
|
||||||
|
return None
|
||||||
|
# Sort by modification time, get the latest
|
||||||
|
latest_file = max(files, key=os.path.getmtime)
|
||||||
|
print(f"A carregar: {latest_file}")
|
||||||
|
return pd.read_csv(latest_file)
|
||||||
|
|
||||||
|
print("="*60)
|
||||||
|
print("ANÁLISE COMPLETA DE SIMULAÇÃO")
|
||||||
|
print("="*60)
|
||||||
|
|
||||||
|
# Carregar todos os dados
|
||||||
|
print("\nA procurar ficheiros de análise...")
|
||||||
|
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("\nErro: Ficheiros de análise em falta!")
|
||||||
|
print("Por favor execute a análise batch primeiro.")
|
||||||
|
exit(1)
|
||||||
|
|
||||||
|
# Create output directory for graphs
|
||||||
|
os.makedirs('graphs', exist_ok=True)
|
||||||
|
|
||||||
|
# Determine the run column name (could be 'Run' or 'Execução')
|
||||||
|
run_col = 'Run' if 'Run' in low.columns else 'Execução'
|
||||||
|
|
||||||
|
print(f"\nColunas disponíveis: {low.columns.tolist()}")
|
||||||
|
|
||||||
|
# ==============================================================================
|
||||||
|
# GRÁFICOS COMPARATIVOS (entre cargas)
|
||||||
|
# ==============================================================================
|
||||||
|
|
||||||
|
print("\n" + "="*60)
|
||||||
|
print("A GERAR GRÁFICOS COMPARATIVOS")
|
||||||
|
print("="*60)
|
||||||
|
|
||||||
|
# 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("Gráfico guardado: 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("Gráfico guardado: 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("Gráfico guardado: graphs/waiting_time_comparison.png")
|
||||||
|
plt.close()
|
||||||
|
|
||||||
|
# 4. Gráfico: Summary Statistics (comparativo)
|
||||||
|
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("Gráfico guardado: graphs/summary_statistics.png")
|
||||||
|
plt.close()
|
||||||
|
|
||||||
|
# ==============================================================================
|
||||||
|
# GRÁFICOS INDIVIDUAIS POR CARGA
|
||||||
|
# ==============================================================================
|
||||||
|
|
||||||
|
def generate_individual_graphs(data, load_type, load_name, color):
|
||||||
|
"""Generate detailed graphs for a specific load type"""
|
||||||
|
|
||||||
|
print(f"\n{'='*60}")
|
||||||
|
print(f"A GERAR GRÁFICOS - CARGA {load_name.upper()}")
|
||||||
|
print("="*60)
|
||||||
|
|
||||||
|
# 1. Gráfico: Run-by-Run Dwelling Time
|
||||||
|
plt.figure(figsize=(12, 6))
|
||||||
|
plt.plot(data[run_col], data['TempoMédioSistema'], marker='o', color=color, linewidth=2, markersize=6)
|
||||||
|
plt.fill_between(data[run_col], data['TempoMínimoSistema'], data['TempoMáximoSistema'], alpha=0.2, color=color)
|
||||||
|
plt.ylabel('Tempo no Sistema (s)')
|
||||||
|
plt.xlabel('Número da Execução')
|
||||||
|
plt.title(f'Tempo no Sistema por Execução - Carga {load_name}')
|
||||||
|
plt.grid(alpha=0.3)
|
||||||
|
plt.legend(['Média', 'Intervalo Min-Max'])
|
||||||
|
plt.savefig(f'graphs/{load_type.lower()}_dwelling_time_runs.png', dpi=300, bbox_inches='tight')
|
||||||
|
print(f"Gráfico guardado: graphs/{load_type.lower()}_dwelling_time_runs.png")
|
||||||
|
plt.close()
|
||||||
|
|
||||||
|
# 2. Gráfico: Run-by-Run Completion Rate
|
||||||
|
plt.figure(figsize=(12, 6))
|
||||||
|
plt.plot(data[run_col], data['TaxaConclusão'], marker='o', color=color, linewidth=2, markersize=6)
|
||||||
|
plt.axhline(y=data['TaxaConclusão'].mean(), color='black', linestyle='--', label=f'Média: {data["TaxaConclusão"].mean():.1f}%')
|
||||||
|
plt.ylabel('Taxa de Conclusão (%)')
|
||||||
|
plt.xlabel('Número da Execução')
|
||||||
|
plt.title(f'Taxa de Conclusão por Execução - Carga {load_name}')
|
||||||
|
plt.ylim(0, 105)
|
||||||
|
plt.grid(alpha=0.3)
|
||||||
|
plt.legend()
|
||||||
|
plt.savefig(f'graphs/{load_type.lower()}_completion_rate_runs.png', dpi=300, bbox_inches='tight')
|
||||||
|
print(f"Gráfico guardado: graphs/{load_type.lower()}_completion_rate_runs.png")
|
||||||
|
plt.close()
|
||||||
|
|
||||||
|
# 3. Gráfico: Run-by-Run Waiting Time
|
||||||
|
plt.figure(figsize=(12, 6))
|
||||||
|
plt.plot(data[run_col], data['TempoMédioEspera'], marker='o', color=color, linewidth=2, markersize=6)
|
||||||
|
plt.ylabel('Tempo de Espera (s)')
|
||||||
|
plt.xlabel('Número da Execução')
|
||||||
|
plt.title(f'Tempo Médio de Espera por Execução - Carga {load_name}')
|
||||||
|
plt.grid(alpha=0.3)
|
||||||
|
plt.savefig(f'graphs/{load_type.lower()}_waiting_time_runs.png', dpi=300, bbox_inches='tight')
|
||||||
|
print(f"Gráfico guardado: graphs/{load_type.lower()}_waiting_time_runs.png")
|
||||||
|
plt.close()
|
||||||
|
|
||||||
|
# 4. Gráfico: Vehicles Generated vs Completed
|
||||||
|
plt.figure(figsize=(10, 6))
|
||||||
|
x = range(len(data))
|
||||||
|
width = 0.35
|
||||||
|
plt.bar([i - width/2 for i in x], data['VeículosGerados'], width, label='Gerados', color='lightblue', alpha=0.8)
|
||||||
|
plt.bar([i + width/2 for i in x], data['VeículosCompletados'], width, label='Concluídos', color=color, alpha=0.8)
|
||||||
|
plt.ylabel('Número de Veículos')
|
||||||
|
plt.xlabel('Número da Execução')
|
||||||
|
plt.title(f'Veículos Gerados vs Concluídos - Carga {load_name}')
|
||||||
|
plt.xticks(x, data[run_col])
|
||||||
|
plt.legend()
|
||||||
|
plt.grid(axis='y', alpha=0.3)
|
||||||
|
plt.savefig(f'graphs/{load_type.lower()}_vehicles_comparison.png', dpi=300, bbox_inches='tight')
|
||||||
|
print(f"Gráfico guardado: graphs/{load_type.lower()}_vehicles_comparison.png")
|
||||||
|
plt.close()
|
||||||
|
|
||||||
|
# 5. Gráfico: Summary Statistics (4-panel)
|
||||||
|
fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2, figsize=(14, 10))
|
||||||
|
|
||||||
|
# Panel 1: Dwelling Time Statistics
|
||||||
|
metrics = ['Média', 'Mínimo', 'Máximo', 'Desvio\nPadrão']
|
||||||
|
values = [
|
||||||
|
data['TempoMédioSistema'].mean(),
|
||||||
|
data['TempoMínimoSistema'].min(),
|
||||||
|
data['TempoMáximoSistema'].max(),
|
||||||
|
data['TempoMédioSistema'].std()
|
||||||
|
]
|
||||||
|
ax1.bar(metrics, values, color=[color, 'lightblue', 'darkblue', 'gray'])
|
||||||
|
ax1.set_title('Estatísticas de Tempo no Sistema')
|
||||||
|
ax1.set_ylabel('Tempo (s)')
|
||||||
|
ax1.grid(axis='y', alpha=0.3)
|
||||||
|
for i, v in enumerate(values):
|
||||||
|
ax1.text(i, v + 0.5, f'{v:.2f}s', ha='center', va='bottom')
|
||||||
|
|
||||||
|
# Panel 2: Waiting Time Statistics
|
||||||
|
values = [
|
||||||
|
data['TempoMédioEspera'].mean(),
|
||||||
|
data['TempoMédioEspera'].min(),
|
||||||
|
data['TempoMédioEspera'].max(),
|
||||||
|
data['TempoMédioEspera'].std()
|
||||||
|
]
|
||||||
|
ax2.bar(metrics, values, color=[color, 'lightblue', 'darkblue', 'gray'])
|
||||||
|
ax2.set_title('Estatísticas de Tempo de Espera')
|
||||||
|
ax2.set_ylabel('Tempo (s)')
|
||||||
|
ax2.grid(axis='y', alpha=0.3)
|
||||||
|
for i, v in enumerate(values):
|
||||||
|
ax2.text(i, v + 0.5, f'{v:.2f}s', ha='center', va='bottom')
|
||||||
|
|
||||||
|
# Panel 3: Completion Rate Distribution
|
||||||
|
ax3.hist(data['TaxaConclusão'], bins=10, color=color, alpha=0.7, edgecolor='black')
|
||||||
|
ax3.axvline(data['TaxaConclusão'].mean(), color='red', linestyle='--', linewidth=2, label='Média')
|
||||||
|
ax3.set_title('Distribuição da Taxa de Conclusão')
|
||||||
|
ax3.set_xlabel('Taxa de Conclusão (%)')
|
||||||
|
ax3.set_ylabel('Frequência')
|
||||||
|
ax3.legend()
|
||||||
|
ax3.grid(axis='y', alpha=0.3)
|
||||||
|
|
||||||
|
# Panel 4: Key Metrics Summary
|
||||||
|
summary_metrics = ['Veículos\nGerados', 'Veículos\nConcluídos', 'Taxa de\nConclusão (%)']
|
||||||
|
summary_values = [
|
||||||
|
data['VeículosGerados'].mean(),
|
||||||
|
data['VeículosCompletados'].mean(),
|
||||||
|
data['TaxaConclusão'].mean()
|
||||||
|
]
|
||||||
|
# Create bars individually with different alpha values
|
||||||
|
alphas = [0.5, 0.7, 0.9]
|
||||||
|
for i, (metric, value, alpha_val) in enumerate(zip(summary_metrics, summary_values, alphas)):
|
||||||
|
ax4.bar(i, value, color=color, alpha=alpha_val)
|
||||||
|
ax4.set_xticks(range(len(summary_metrics)))
|
||||||
|
ax4.set_xticklabels(summary_metrics)
|
||||||
|
ax4.set_title('Resumo de Métricas-Chave')
|
||||||
|
ax4.grid(axis='y', alpha=0.3)
|
||||||
|
for i, v in enumerate(summary_values):
|
||||||
|
ax4.text(i, v + max(summary_values)*0.02, f'{v:.1f}', ha='center', va='bottom', fontweight='bold')
|
||||||
|
|
||||||
|
plt.tight_layout()
|
||||||
|
plt.savefig(f'graphs/{load_type.lower()}_summary_statistics.png', dpi=300, bbox_inches='tight')
|
||||||
|
print(f"Gráfico guardado: graphs/{load_type.lower()}_summary_statistics.png")
|
||||||
|
plt.close()
|
||||||
|
|
||||||
|
# Print detailed summary statistics
|
||||||
|
print(f"\n{'='*60}")
|
||||||
|
print(f"CARGA {load_name.upper()} - ESTATÍSTICAS DETALHADAS")
|
||||||
|
print("="*60)
|
||||||
|
|
||||||
|
print(f"\nTEMPO NO SISTEMA:")
|
||||||
|
print(f" Média: {data['TempoMédioSistema'].mean():.2f}s")
|
||||||
|
print(f" Desvio Padrão: {data['TempoMédioSistema'].std():.2f}s")
|
||||||
|
print(f" Mínimo: {data['TempoMínimoSistema'].min():.2f}s")
|
||||||
|
print(f" Máximo: {data['TempoMáximoSistema'].max():.2f}s")
|
||||||
|
print(f" Mediana: {data['TempoMédioSistema'].median():.2f}s")
|
||||||
|
|
||||||
|
print(f"\nTEMPO DE ESPERA:")
|
||||||
|
print(f" Média: {data['TempoMédioEspera'].mean():.2f}s")
|
||||||
|
print(f" Desvio Padrão: {data['TempoMédioEspera'].std():.2f}s")
|
||||||
|
print(f" Mínimo: {data['TempoMédioEspera'].min():.2f}s")
|
||||||
|
print(f" Máximo: {data['TempoMédioEspera'].max():.2f}s")
|
||||||
|
print(f" Mediana: {data['TempoMédioEspera'].median():.2f}s")
|
||||||
|
|
||||||
|
print(f"\nTAXA DE CONCLUSÃO:")
|
||||||
|
print(f" Média: {data['TaxaConclusão'].mean():.2f}%")
|
||||||
|
print(f" Desvio Padrão: {data['TaxaConclusão'].std():.2f}%")
|
||||||
|
print(f" Mínimo: {data['TaxaConclusão'].min():.2f}%")
|
||||||
|
print(f" Máximo: {data['TaxaConclusão'].max():.2f}%")
|
||||||
|
print(f" Mediana: {data['TaxaConclusão'].median():.2f}%")
|
||||||
|
|
||||||
|
print(f"\nCONTAGEM DE VEÍCULOS:")
|
||||||
|
print(f" Média Gerados: {data['VeículosGerados'].mean():.0f}")
|
||||||
|
print(f" Média Concluídos: {data['VeículosCompletados'].mean():.0f}")
|
||||||
|
print(f" Média Perdidos: {data['VeículosGerados'].mean() - data['VeículosCompletados'].mean():.0f}")
|
||||||
|
|
||||||
|
print(f"\nEXECUÇÕES ANALISADAS: {len(data)}")
|
||||||
|
|
||||||
|
# Check for config file column - could be ArquivoConfig or ConfigFile
|
||||||
|
config_col = None
|
||||||
|
if 'ArquivoConfig' in data.columns:
|
||||||
|
config_col = 'ArquivoConfig'
|
||||||
|
elif 'ConfigFile' in data.columns:
|
||||||
|
config_col = 'ConfigFile'
|
||||||
|
|
||||||
|
if config_col:
|
||||||
|
print(f"FICHEIRO DE CONFIGURAÇÃO: {data[config_col].iloc[0]}")
|
||||||
|
|
||||||
|
# Generate individual graphs for each load
|
||||||
|
generate_individual_graphs(low, 'LOW', 'Baixa', 'green')
|
||||||
|
generate_individual_graphs(medium, 'MEDIUM', 'Média', 'orange')
|
||||||
|
generate_individual_graphs(high, 'HIGH', 'Alta', 'red')
|
||||||
|
|
||||||
|
# ==============================================================================
|
||||||
|
# SUMÁRIO FINAL
|
||||||
|
# ==============================================================================
|
||||||
|
|
||||||
|
print("\n" + "="*60)
|
||||||
|
print("SUMÁRIO COMPARATIVO FINAL")
|
||||||
|
print("="*60)
|
||||||
|
|
||||||
|
print(f"\nCARGA BAIXA:")
|
||||||
|
print(f" Tempo Médio no Sistema: {low['TempoMédioSistema'].mean():.2f}s")
|
||||||
|
print(f" Tempo Médio de Espera: {low['TempoMédioEspera'].mean():.2f}s")
|
||||||
|
print(f" Taxa de Conclusão: {low['TaxaConclusão'].mean():.1f}%")
|
||||||
|
print(f" Veículos Gerados: {low['VeículosGerados'].mean():.0f}")
|
||||||
|
print(f" Veículos Concluídos: {low['VeículosCompletados'].mean():.0f}")
|
||||||
|
|
||||||
|
print(f"\nCARGA MÉDIA:")
|
||||||
|
print(f" Tempo Médio no Sistema: {medium['TempoMédioSistema'].mean():.2f}s")
|
||||||
|
print(f" Tempo Médio de Espera: {medium['TempoMédioEspera'].mean():.2f}s")
|
||||||
|
print(f" Taxa de Conclusão: {medium['TaxaConclusão'].mean():.1f}%")
|
||||||
|
print(f" Veículos Gerados: {medium['VeículosGerados'].mean():.0f}")
|
||||||
|
print(f" Veículos Concluídos: {medium['VeículosCompletados'].mean():.0f}")
|
||||||
|
|
||||||
|
print(f"\nCARGA ALTA:")
|
||||||
|
print(f" Tempo Médio no Sistema: {high['TempoMédioSistema'].mean():.2f}s")
|
||||||
|
print(f" Tempo Médio de Espera: {high['TempoMédioEspera'].mean():.2f}s")
|
||||||
|
print(f" Taxa de Conclusão: {high['TaxaConclusão'].mean():.1f}%")
|
||||||
|
print(f" Veículos Gerados: {high['VeículosGerados'].mean():.0f}")
|
||||||
|
print(f" Veículos Concluídos: {high['VeículosCompletados'].mean():.0f}")
|
||||||
|
|
||||||
|
print("\n" + "="*60)
|
||||||
|
print("ANÁLISE COMPLETA!")
|
||||||
|
print(f"Total de gráficos gerados: 19")
|
||||||
|
print("Todos os gráficos foram guardados no diretório 'graphs/'")
|
||||||
|
print("="*60)
|
||||||
222
main/graphing_single.py
Normal file
@@ -0,0 +1,222 @@
|
|||||||
|
import pandas as pd
|
||||||
|
import matplotlib.pyplot as plt
|
||||||
|
import glob
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
|
||||||
|
# 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)
|
||||||
|
|
||||||
|
# Determine which load to analyze
|
||||||
|
if len(sys.argv) > 1:
|
||||||
|
load_type = sys.argv[1].upper()
|
||||||
|
else:
|
||||||
|
print("Usage: python graphing_single.py [LOW|MEDIUM|HIGH]")
|
||||||
|
print("Defaulting to LOW_LOAD...")
|
||||||
|
load_type = "LOW"
|
||||||
|
|
||||||
|
# Validate load type
|
||||||
|
if load_type not in ["LOW", "MEDIUM", "HIGH"]:
|
||||||
|
print(f"Error: Invalid load type '{load_type}'. Must be LOW, MEDIUM, or HIGH.")
|
||||||
|
exit(1)
|
||||||
|
|
||||||
|
# Load the specified data
|
||||||
|
print(f"Looking for {load_type}_LOAD analysis files...")
|
||||||
|
pattern = f'analysis/{load_type}_LOAD_*.csv'
|
||||||
|
data = load_latest_csv(pattern)
|
||||||
|
|
||||||
|
if data is None:
|
||||||
|
print(f"\nError: No {load_type}_LOAD analysis files found!")
|
||||||
|
print("Please run the batch analysis first.")
|
||||||
|
exit(1)
|
||||||
|
|
||||||
|
# Print available columns for debugging
|
||||||
|
print(f"\nAvailable columns in {load_type}_LOAD CSV:")
|
||||||
|
print(data.columns.tolist())
|
||||||
|
|
||||||
|
# Create output directory for graphs
|
||||||
|
os.makedirs('graphs', exist_ok=True)
|
||||||
|
|
||||||
|
# Determine the run column name (could be 'Run' or 'Execução')
|
||||||
|
run_col = 'Run' if 'Run' in data.columns else 'Execução'
|
||||||
|
|
||||||
|
# Load name for titles
|
||||||
|
load_name = load_type.capitalize()
|
||||||
|
colors = {'LOW': 'green', 'MEDIUM': 'orange', 'HIGH': 'red'}
|
||||||
|
color = colors[load_type]
|
||||||
|
|
||||||
|
# 1. Gráfico: Run-by-Run Dwelling Time
|
||||||
|
plt.figure(figsize=(12, 6))
|
||||||
|
plt.plot(data[run_col], data['TempoMédioSistema'], marker='o', color=color, linewidth=2, markersize=6)
|
||||||
|
plt.fill_between(data[run_col], data['TempoMínimoSistema'], data['TempoMáximoSistema'], alpha=0.2, color=color)
|
||||||
|
plt.ylabel('Tempo no Sistema (s)')
|
||||||
|
plt.xlabel('Run Number')
|
||||||
|
plt.title(f'Tempo no Sistema por Execução - Carga {load_name}')
|
||||||
|
plt.grid(alpha=0.3)
|
||||||
|
plt.legend(['Média', 'Min-Max Range'])
|
||||||
|
plt.savefig(f'graphs/{load_type.lower()}_dwelling_time_runs.png', dpi=300, bbox_inches='tight')
|
||||||
|
print(f"\nGraph saved: graphs/{load_type.lower()}_dwelling_time_runs.png")
|
||||||
|
plt.close()
|
||||||
|
|
||||||
|
# 2. Gráfico: Run-by-Run Completion Rate
|
||||||
|
plt.figure(figsize=(12, 6))
|
||||||
|
plt.plot(data[run_col], data['TaxaConclusão'], marker='o', color=color, linewidth=2, markersize=6)
|
||||||
|
plt.axhline(y=data['TaxaConclusão'].mean(), color='black', linestyle='--', label=f'Média: {data["TaxaConclusão"].mean():.1f}%')
|
||||||
|
plt.ylabel('Taxa de Conclusão (%)')
|
||||||
|
plt.xlabel('Run Number')
|
||||||
|
plt.title(f'Taxa de Conclusão por Execução - Carga {load_name}')
|
||||||
|
plt.ylim(0, 105)
|
||||||
|
plt.grid(alpha=0.3)
|
||||||
|
plt.legend()
|
||||||
|
plt.savefig(f'graphs/{load_type.lower()}_completion_rate_runs.png', dpi=300, bbox_inches='tight')
|
||||||
|
print(f"Graph saved: graphs/{load_type.lower()}_completion_rate_runs.png")
|
||||||
|
plt.close()
|
||||||
|
|
||||||
|
# 3. Gráfico: Run-by-Run Waiting Time
|
||||||
|
plt.figure(figsize=(12, 6))
|
||||||
|
plt.plot(data[run_col], data['TempoMédioEspera'], marker='o', color=color, linewidth=2, markersize=6)
|
||||||
|
plt.ylabel('Tempo de Espera (s)')
|
||||||
|
plt.xlabel('Run Number')
|
||||||
|
plt.title(f'Tempo Médio de Espera por Execução - Carga {load_name}')
|
||||||
|
plt.grid(alpha=0.3)
|
||||||
|
plt.savefig(f'graphs/{load_type.lower()}_waiting_time_runs.png', dpi=300, bbox_inches='tight')
|
||||||
|
print(f"Graph saved: graphs/{load_type.lower()}_waiting_time_runs.png")
|
||||||
|
plt.close()
|
||||||
|
|
||||||
|
# 4. Gráfico: Vehicles Generated vs Completed
|
||||||
|
plt.figure(figsize=(10, 6))
|
||||||
|
x = range(len(data))
|
||||||
|
width = 0.35
|
||||||
|
plt.bar([i - width/2 for i in x], data['VeículosGerados'], width, label='Gerados', color='lightblue', alpha=0.8)
|
||||||
|
plt.bar([i + width/2 for i in x], data['VeículosCompletados'], width, label='Concluídos', color=color, alpha=0.8)
|
||||||
|
plt.ylabel('Número de Veículos')
|
||||||
|
plt.xlabel('Run Number')
|
||||||
|
plt.title(f'Veículos Gerados vs Concluídos - Carga {load_name}')
|
||||||
|
plt.xticks(x, data[run_col])
|
||||||
|
plt.legend()
|
||||||
|
plt.grid(axis='y', alpha=0.3)
|
||||||
|
plt.savefig(f'graphs/{load_type.lower()}_vehicles_comparison.png', dpi=300, bbox_inches='tight')
|
||||||
|
print(f"Graph saved: graphs/{load_type.lower()}_vehicles_comparison.png")
|
||||||
|
plt.close()
|
||||||
|
|
||||||
|
# 5. Gráfico: Summary Statistics (4-panel)
|
||||||
|
fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2, figsize=(14, 10))
|
||||||
|
|
||||||
|
# Panel 1: Dwelling Time Statistics
|
||||||
|
metrics = ['Média', 'Mínimo', 'Máximo', 'Desvio\nPadrão']
|
||||||
|
values = [
|
||||||
|
data['TempoMédioSistema'].mean(),
|
||||||
|
data['TempoMínimoSistema'].min(),
|
||||||
|
data['TempoMáximoSistema'].max(),
|
||||||
|
data['TempoMédioSistema'].std()
|
||||||
|
]
|
||||||
|
ax1.bar(metrics, values, color=[color, 'lightblue', 'darkblue', 'gray'])
|
||||||
|
ax1.set_title('Estatísticas de Tempo no Sistema')
|
||||||
|
ax1.set_ylabel('Tempo (s)')
|
||||||
|
ax1.grid(axis='y', alpha=0.3)
|
||||||
|
for i, v in enumerate(values):
|
||||||
|
ax1.text(i, v + 0.5, f'{v:.2f}s', ha='center', va='bottom')
|
||||||
|
|
||||||
|
# Panel 2: Waiting Time Statistics
|
||||||
|
values = [
|
||||||
|
data['TempoMédioEspera'].mean(),
|
||||||
|
data['TempoMédioEspera'].min(),
|
||||||
|
data['TempoMédioEspera'].max(),
|
||||||
|
data['TempoMédioEspera'].std()
|
||||||
|
]
|
||||||
|
ax2.bar(metrics, values, color=[color, 'lightblue', 'darkblue', 'gray'])
|
||||||
|
ax2.set_title('Estatísticas de Tempo de Espera')
|
||||||
|
ax2.set_ylabel('Tempo (s)')
|
||||||
|
ax2.grid(axis='y', alpha=0.3)
|
||||||
|
for i, v in enumerate(values):
|
||||||
|
ax2.text(i, v + 0.5, f'{v:.2f}s', ha='center', va='bottom')
|
||||||
|
|
||||||
|
# Panel 3: Completion Rate Distribution
|
||||||
|
ax3.hist(data['TaxaConclusão'], bins=10, color=color, alpha=0.7, edgecolor='black')
|
||||||
|
ax3.axvline(data['TaxaConclusão'].mean(), color='red', linestyle='--', linewidth=2, label='Média')
|
||||||
|
ax3.set_title('Distribuição da Taxa de Conclusão')
|
||||||
|
ax3.set_xlabel('Taxa de Conclusão (%)')
|
||||||
|
ax3.set_ylabel('Frequência')
|
||||||
|
ax3.legend()
|
||||||
|
ax3.grid(axis='y', alpha=0.3)
|
||||||
|
|
||||||
|
# Panel 4: Key Metrics Summary
|
||||||
|
summary_metrics = ['Veículos\nGerados', 'Veículos\nConcluídos', 'Taxa de\nConclusão (%)']
|
||||||
|
summary_values = [
|
||||||
|
data['VeículosGerados'].mean(),
|
||||||
|
data['VeículosCompletados'].mean(),
|
||||||
|
data['TaxaConclusão'].mean()
|
||||||
|
]
|
||||||
|
# Create bars individually with different alpha values
|
||||||
|
alphas = [0.5, 0.7, 0.9]
|
||||||
|
for i, (metric, value, alpha_val) in enumerate(zip(summary_metrics, summary_values, alphas)):
|
||||||
|
ax4.bar(i, value, color=color, alpha=alpha_val)
|
||||||
|
ax4.set_xticks(range(len(summary_metrics)))
|
||||||
|
ax4.set_xticklabels(summary_metrics)
|
||||||
|
ax4.set_title('Resumo de Métricas-Chave')
|
||||||
|
ax4.grid(axis='y', alpha=0.3)
|
||||||
|
for i, v in enumerate(summary_values):
|
||||||
|
ax4.text(i, v + max(summary_values)*0.02, f'{v:.1f}', ha='center', va='bottom', fontweight='bold')
|
||||||
|
|
||||||
|
plt.tight_layout()
|
||||||
|
plt.savefig(f'graphs/{load_type.lower()}_summary_statistics.png', dpi=300, bbox_inches='tight')
|
||||||
|
print(f"Graph saved: graphs/{load_type.lower()}_summary_statistics.png")
|
||||||
|
plt.close()
|
||||||
|
|
||||||
|
# Print detailed summary statistics
|
||||||
|
print("\n" + "="*60)
|
||||||
|
print(f"{load_name.upper()} LOAD - DETAILED STATISTICS")
|
||||||
|
print("="*60)
|
||||||
|
|
||||||
|
print(f"\nTIME IN SYSTEM:")
|
||||||
|
print(f" Mean: {data['TempoMédioSistema'].mean():.2f}s")
|
||||||
|
print(f" Std Dev: {data['TempoMédioSistema'].std():.2f}s")
|
||||||
|
print(f" Min: {data['TempoMínimoSistema'].min():.2f}s")
|
||||||
|
print(f" Max: {data['TempoMáximoSistema'].max():.2f}s")
|
||||||
|
print(f" Median: {data['TempoMédioSistema'].median():.2f}s")
|
||||||
|
|
||||||
|
print(f"\nWAITING TIME:")
|
||||||
|
print(f" Mean: {data['TempoMédioEspera'].mean():.2f}s")
|
||||||
|
print(f" Std Dev: {data['TempoMédioEspera'].std():.2f}s")
|
||||||
|
print(f" Min: {data['TempoMédioEspera'].min():.2f}s")
|
||||||
|
print(f" Max: {data['TempoMédioEspera'].max():.2f}s")
|
||||||
|
print(f" Median: {data['TempoMédioEspera'].median():.2f}s")
|
||||||
|
|
||||||
|
print(f"\nCOMPLETION RATE:")
|
||||||
|
print(f" Mean: {data['TaxaConclusão'].mean():.2f}%")
|
||||||
|
print(f" Std Dev: {data['TaxaConclusão'].std():.2f}%")
|
||||||
|
print(f" Min: {data['TaxaConclusão'].min():.2f}%")
|
||||||
|
print(f" Max: {data['TaxaConclusão'].max():.2f}%")
|
||||||
|
print(f" Median: {data['TaxaConclusão'].median():.2f}%")
|
||||||
|
|
||||||
|
print(f"\nVEHICLE COUNTS:")
|
||||||
|
print(f" Mean Generated: {data['VeículosGerados'].mean():.0f}")
|
||||||
|
print(f" Mean Completed: {data['VeículosCompletados'].mean():.0f}")
|
||||||
|
print(f" Mean Lost: {data['VeículosGerados'].mean() - data['VeículosCompletados'].mean():.0f}")
|
||||||
|
|
||||||
|
print(f"\nRUNS ANALYZED: {len(data)}")
|
||||||
|
|
||||||
|
# Check for config file column - could be ArquivoConfig or ConfigFile
|
||||||
|
config_col = None
|
||||||
|
if 'ArquivoConfig' in data.columns:
|
||||||
|
config_col = 'ArquivoConfig'
|
||||||
|
elif 'ConfigFile' in data.columns:
|
||||||
|
config_col = 'ConfigFile'
|
||||||
|
|
||||||
|
if config_col:
|
||||||
|
print(f"CONFIGURATION FILE: {data[config_col].iloc[0]}")
|
||||||
|
else:
|
||||||
|
print(f"CONFIGURATION FILE: N/A")
|
||||||
|
|
||||||
|
print("\n" + "="*60)
|
||||||
|
print(f"All graphs saved in 'graphs/' directory with prefix '{load_type.lower()}_'")
|
||||||
|
print("="*60)
|
||||||
|
Before Width: | Height: | Size: 90 KiB After Width: | Height: | Size: 91 KiB |
|
Before Width: | Height: | Size: 90 KiB After Width: | Height: | Size: 92 KiB |
BIN
main/graphs/high_completion_rate_runs.png
Normal file
|
After Width: | Height: | Size: 116 KiB |
BIN
main/graphs/high_dwelling_time_runs.png
Normal file
|
After Width: | Height: | Size: 140 KiB |
BIN
main/graphs/high_summary_statistics.png
Normal file
|
After Width: | Height: | Size: 274 KiB |
BIN
main/graphs/high_vehicles_comparison.png
Normal file
|
After Width: | Height: | Size: 99 KiB |
BIN
main/graphs/high_waiting_time_runs.png
Normal file
|
After Width: | Height: | Size: 173 KiB |
BIN
main/graphs/low_completion_rate_runs.png
Normal file
|
After Width: | Height: | Size: 113 KiB |
BIN
main/graphs/low_dwelling_time_runs.png
Normal file
|
After Width: | Height: | Size: 188 KiB |
BIN
main/graphs/low_summary_statistics.png
Normal file
|
After Width: | Height: | Size: 265 KiB |
BIN
main/graphs/low_vehicles_comparison.png
Normal file
|
After Width: | Height: | Size: 100 KiB |
BIN
main/graphs/low_waiting_time_runs.png
Normal file
|
After Width: | Height: | Size: 168 KiB |
BIN
main/graphs/medium_completion_rate_runs.png
Normal file
|
After Width: | Height: | Size: 134 KiB |
BIN
main/graphs/medium_dwelling_time_runs.png
Normal file
|
After Width: | Height: | Size: 163 KiB |
BIN
main/graphs/medium_summary_statistics.png
Normal file
|
After Width: | Height: | Size: 254 KiB |
BIN
main/graphs/medium_vehicles_comparison.png
Normal file
|
After Width: | Height: | Size: 92 KiB |
BIN
main/graphs/medium_waiting_time_runs.png
Normal file
|
After Width: | Height: | Size: 142 KiB |
|
Before Width: | Height: | Size: 215 KiB After Width: | Height: | Size: 227 KiB |
|
Before Width: | Height: | Size: 86 KiB After Width: | Height: | Size: 92 KiB |
13
main/pom.xml
@@ -83,6 +83,19 @@
|
|||||||
</execution>
|
</execution>
|
||||||
</executions>
|
</executions>
|
||||||
</plugin>
|
</plugin>
|
||||||
|
<!-- Maven Javadoc Plugin -->
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
|
<artifactId>maven-javadoc-plugin</artifactId>
|
||||||
|
<version>3.12.0</version>
|
||||||
|
<configuration>
|
||||||
|
<source>17</source>
|
||||||
|
<encoding>UTF-8</encoding>
|
||||||
|
<doclint>none</doclint>
|
||||||
|
<failOnError>false</failOnError>
|
||||||
|
<failOnWarnings>false</failOnWarnings>
|
||||||
|
</configuration>
|
||||||
|
</plugin>
|
||||||
</plugins>
|
</plugins>
|
||||||
</build>
|
</build>
|
||||||
|
|
||||||
|
|||||||
@@ -27,22 +27,24 @@ import sd.protocol.MessageProtocol;
|
|||||||
import sd.protocol.SocketConnection;
|
import sd.protocol.SocketConnection;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Destino final de todos os veículos da simulação (nó de saída S).
|
* Ponto terminal da malha de simulação (Sink Node).
|
||||||
*
|
* <p>
|
||||||
* <p>Opera como sumidouro da rede:
|
* Este processo atua como o sumidouro da rede de filas. A sua função primária é
|
||||||
* <ol>
|
* a <b>coleta de telemetria final</b>. Diferente das interseções, não encaminha veículos;
|
||||||
* <li>Recebe veículos que completaram a viagem
|
* em vez disso, retira-os do sistema, calcula as métricas de latência "end-to-end"
|
||||||
* <li>Regista estatísticas finais (tempo total, espera, travessia)
|
* (tempo no sistema, tempo de espera acumulado) e reporta ao Dashboard.
|
||||||
* <li>Envia métricas ao dashboard em tempo real
|
* <p>
|
||||||
* </ol>
|
* <b>Arquitetura de Concorrência:</b>
|
||||||
*
|
* Utiliza um {@link ServerSocket} multithreaded para aceitar conexões simultâneas de
|
||||||
* <p>Participa no DES rastreando eventos, mas opera principalmente
|
* qualquer interseção de fronteira (Cr1, Cr5, etc.) que envie veículos para fora da malha.
|
||||||
* de forma reativa, aguardando chegadas via socket.
|
|
||||||
*/
|
*/
|
||||||
public class ExitNodeProcess {
|
public class ExitNodeProcess {
|
||||||
|
|
||||||
|
// --- Configuration and Networking ---
|
||||||
private final SimulationConfig config;
|
private final SimulationConfig config;
|
||||||
private ServerSocket serverSocket;
|
private ServerSocket serverSocket;
|
||||||
|
|
||||||
|
/** Pool de threads elástica para tratamento de conexões de entrada. */
|
||||||
private final ExecutorService connectionHandlerPool;
|
private final ExecutorService connectionHandlerPool;
|
||||||
|
|
||||||
// DES components
|
// DES components
|
||||||
@@ -51,37 +53,37 @@ public class ExitNodeProcess {
|
|||||||
private final EventLogger eventLogger;
|
private final EventLogger eventLogger;
|
||||||
private Thread eventProcessorThread;
|
private Thread eventProcessorThread;
|
||||||
|
|
||||||
/** Flag de controlo (volatile para visibilidade entre threads) */
|
/** Flag de controlo (volatile para visibilidade entre threads de I/O e lógica). */
|
||||||
private volatile boolean running;
|
private volatile boolean running;
|
||||||
|
|
||||||
/** Instante de início da simulação (milissegundos) */
|
/** Instante de início da simulação (milissegundos) sincronizado com o Coordenador. */
|
||||||
private long simulationStartMillis;
|
private long simulationStartMillis;
|
||||||
|
|
||||||
/** Contador de veículos que completaram a rota */
|
/** Contador atómico (via synchronized) de throughput total. */
|
||||||
private int totalVehiclesReceived;
|
private int totalVehiclesReceived;
|
||||||
|
|
||||||
/** Tempo acumulado no sistema de todos os veículos */
|
/** Tempo acumulado no sistema (System Time) de todos os veículos. */
|
||||||
private double totalSystemTime;
|
private double totalSystemTime;
|
||||||
|
|
||||||
/** Tempo acumulado em espera de todos os veículos */
|
/** Tempo acumulado em espera (Waiting Time) de todos os veículos. */
|
||||||
private double totalWaitingTime;
|
private double totalWaitingTime;
|
||||||
|
|
||||||
/** Tempo acumulado em travessia de todos os veículos */
|
/** Tempo acumulado em travessia (Service Time) de todos os veículos. */
|
||||||
private double totalCrossingTime;
|
private double totalCrossingTime;
|
||||||
|
|
||||||
/** Contagem de veículos por tipo */
|
/** Agregação por categoria de veículo. */
|
||||||
private final Map<VehicleType, Integer> vehicleTypeCount;
|
private final Map<VehicleType, Integer> vehicleTypeCount;
|
||||||
|
|
||||||
/** Tempo de espera acumulado por tipo de veículo */
|
/** Latência acumulada por categoria. */
|
||||||
private final Map<VehicleType, Double> vehicleTypeWaitTime;
|
private final Map<VehicleType, Double> vehicleTypeWaitTime;
|
||||||
|
|
||||||
/** Cliente socket para envio de estatísticas ao dashboard */
|
/** Cliente TCP persistente para push de métricas ao Dashboard. */
|
||||||
private SocketClient dashboardClient;
|
private SocketClient dashboardClient;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Ponto de entrada do processo.
|
* Bootstrap do processo ExitNode.
|
||||||
*
|
* Carrega configuração, inicializa subsistemas e entra no loop de serviço.
|
||||||
* @param args args[0] (opcional) = caminho do ficheiro de configuração
|
* * @param args Argumentos de CLI (caminho do config).
|
||||||
*/
|
*/
|
||||||
public static void main(String[] args) {
|
public static void main(String[] args) {
|
||||||
System.out.println("=".repeat(60));
|
System.out.println("=".repeat(60));
|
||||||
@@ -117,13 +119,9 @@ public class ExitNodeProcess {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Configura o Nó de Saída.
|
* Instancia o nó de saída.
|
||||||
*
|
* Prepara os acumuladores estatísticos e a infraestrutura de logging distribuído.
|
||||||
* Inicializamos os nossos contadores, preparamos a pool de threads para tratar
|
* * @param config A configuração global da simulação.
|
||||||
* das ligações de veículos recebidas,
|
|
||||||
* e configuramos os componentes DES para rastreio de eventos.
|
|
||||||
*
|
|
||||||
* @param config A configuração da simulação.
|
|
||||||
*/
|
*/
|
||||||
public ExitNodeProcess(SimulationConfig config) {
|
public ExitNodeProcess(SimulationConfig config) {
|
||||||
this.config = config;
|
this.config = config;
|
||||||
@@ -157,9 +155,8 @@ public class ExitNodeProcess {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Tenta estabelecer uma ligação ao dashboard.
|
* Estabelece o canal de controlo (Control Plane) com o Dashboard.
|
||||||
* Se for bem-sucedido, poderemos enviar estatísticas em tempo real. Se não,
|
* Essencial para a visualização em tempo real das métricas de saída.
|
||||||
* apenas registamos localmente.
|
|
||||||
*/
|
*/
|
||||||
public void initialize() {
|
public void initialize() {
|
||||||
System.out.println("Connecting to dashboard...");
|
System.out.println("Connecting to dashboard...");
|
||||||
@@ -179,10 +176,9 @@ public class ExitNodeProcess {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Starts the DES event processing thread.
|
* Inicia a thread de processamento de eventos DES.
|
||||||
* Currently, ExitNode is primarily reactive (receives vehicles via network),
|
* Embora o ExitNode seja primariamente reativo (Network-driven), o motor DES
|
||||||
* but maintains event queue for potential scheduled events and history
|
* é mantido para consistência de relógio e agendamento de fim de simulação.
|
||||||
* tracking.
|
|
||||||
*/
|
*/
|
||||||
private void startEventProcessor() {
|
private void startEventProcessor() {
|
||||||
eventProcessorThread = new Thread(() -> {
|
eventProcessorThread = new Thread(() -> {
|
||||||
@@ -218,8 +214,8 @@ public class ExitNodeProcess {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Processes a discrete event based on its type.
|
* Dispatcher de eventos discretos.
|
||||||
* Currently supports VEHICLE_EXIT and SIMULATION_END events.
|
* Trata eventos de fim de simulação. Chegadas de veículos são tratadas via Socket.
|
||||||
*/
|
*/
|
||||||
private void processEvent(SimulationEvent event) {
|
private void processEvent(SimulationEvent event) {
|
||||||
try {
|
try {
|
||||||
@@ -244,7 +240,7 @@ public class ExitNodeProcess {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Handles simulation end event.
|
* Executa a lógica de encerramento desencadeada pelo evento DES.
|
||||||
*/
|
*/
|
||||||
private void handleSimulationEndEvent(SimulationEvent event) {
|
private void handleSimulationEndEvent(SimulationEvent event) {
|
||||||
eventLogger.log(EventType.SIMULATION_STOPPED, "ExitNode",
|
eventLogger.log(EventType.SIMULATION_STOPPED, "ExitNode",
|
||||||
@@ -256,9 +252,8 @@ public class ExitNodeProcess {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Exports the complete event history for the exit node.
|
* Exporta o histórico completo de eventos para auditoria.
|
||||||
* This satisfies the spec requirement: "Deve ser possível verificar a lista
|
* Requisito funcional para verificação de trace.
|
||||||
* completa de eventos"
|
|
||||||
*/
|
*/
|
||||||
public void exportEventHistory(String outputPath) {
|
public void exportEventHistory(String outputPath) {
|
||||||
String history = eventQueue.exportEventHistory();
|
String history = eventQueue.exportEventHistory();
|
||||||
@@ -271,9 +266,8 @@ public class ExitNodeProcess {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Schedules a simulation end event at the specified time.
|
* Agenda o fim determinístico da simulação.
|
||||||
*
|
* * @param endTime Tempo virtual de paragem.
|
||||||
* @param endTime The simulation time when the simulation should end
|
|
||||||
*/
|
*/
|
||||||
public void scheduleSimulationEnd(double endTime) {
|
public void scheduleSimulationEnd(double endTime) {
|
||||||
SimulationEvent endEvent = new SimulationEvent(
|
SimulationEvent endEvent = new SimulationEvent(
|
||||||
@@ -285,22 +279,16 @@ public class ExitNodeProcess {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Abre o socket do servidor e começa a escutar por veículos.
|
* Inicia o servidor TCP em modo de bloqueio (Blocking I/O).
|
||||||
*
|
* @throws IOException Se ocorrer erro no bind da porta.
|
||||||
* Este é o loop principal. Aceitamos ligações das interseções (de onde vêm os
|
|
||||||
* veículos)
|
|
||||||
* e passamo-las para a nossa pool de threads para processamento.
|
|
||||||
*
|
|
||||||
* @throws IOException Se não conseguirmos fazer bind à porta.
|
|
||||||
*/
|
*/
|
||||||
public void start() throws IOException {
|
public void start() throws IOException {
|
||||||
start(true); // Default to DES mode
|
start(true); // Default to DES mode
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Starts the exit node process.
|
* Inicia o processo com opção de ativar o rastreio DES.
|
||||||
*
|
* * @param useDES Se verdadeiro, ativa a thread do processador de eventos.
|
||||||
* @param useDES If true, starts event processor for DES mode tracking
|
|
||||||
*/
|
*/
|
||||||
public void start(boolean useDES) throws IOException {
|
public void start(boolean useDES) throws IOException {
|
||||||
int port = config.getExitPort();
|
int port = config.getExitPort();
|
||||||
@@ -310,15 +298,15 @@ public class ExitNodeProcess {
|
|||||||
|
|
||||||
System.out.println("Exit node started on port " + port);
|
System.out.println("Exit node started on port " + port);
|
||||||
if (useDES) {
|
if (useDES) {
|
||||||
// Note: ExitNode is primarily reactive (network-driven), but maintains
|
|
||||||
// event queue for simulation end events and history tracking
|
|
||||||
System.out.println("Running in DES mode (event history tracking enabled)");
|
System.out.println("Running in DES mode (event history tracking enabled)");
|
||||||
}
|
}
|
||||||
System.out.println("Waiting for vehicles...\\n");
|
System.out.println("Waiting for vehicles...\\n");
|
||||||
|
|
||||||
|
// Loop de aceitação principal
|
||||||
while (running) {
|
while (running) {
|
||||||
try {
|
try {
|
||||||
Socket clientSocket = serverSocket.accept();
|
Socket clientSocket = serverSocket.accept();
|
||||||
|
// Delega o processamento da conexão para o Thread Pool
|
||||||
connectionHandlerPool.submit(() -> handleIncomingConnection(clientSocket));
|
connectionHandlerPool.submit(() -> handleIncomingConnection(clientSocket));
|
||||||
} catch (IOException e) {
|
} catch (IOException e) {
|
||||||
if (running) {
|
if (running) {
|
||||||
@@ -329,12 +317,11 @@ public class ExitNodeProcess {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Trata uma ligação de uma interseção.
|
* Worker method para tratar uma conexão persistente vinda de uma interseção.
|
||||||
*
|
* <p>
|
||||||
* Mantemos a ligação aberta e escutamos por mensagens `VEHICLE_TRANSFER`.
|
* Mantém o socket aberto e consome mensagens num loop até que a conexão seja fechada
|
||||||
* Cada mensagem contém um veículo que acabou de terminar a sua viagem.
|
* pelo remetente. Responsável pela desserialização polimórfica (JSON/Gson).
|
||||||
*
|
* * @param clientSocket O socket conectado.
|
||||||
* @param clientSocket O socket ligado à interseção.
|
|
||||||
*/
|
*/
|
||||||
private void handleIncomingConnection(Socket clientSocket) {
|
private void handleIncomingConnection(Socket clientSocket) {
|
||||||
String clientAddress = clientSocket.getInetAddress().getHostAddress();
|
String clientAddress = clientSocket.getInetAddress().getHostAddress();
|
||||||
@@ -350,14 +337,14 @@ public class ExitNodeProcess {
|
|||||||
" from " + message.getSourceNode());
|
" from " + message.getSourceNode());
|
||||||
|
|
||||||
if (message.getType() == MessageType.SIMULATION_START) {
|
if (message.getType() == MessageType.SIMULATION_START) {
|
||||||
// Coordinator sends start time - use it instead of our local start
|
// Sincronização de relógio com o Coordenador
|
||||||
simulationStartMillis = ((Number) message.getPayload()).longValue();
|
simulationStartMillis = ((Number) message.getPayload()).longValue();
|
||||||
System.out.println("[Exit] Simulation start time synchronized");
|
System.out.println("[Exit] Simulation start time synchronized");
|
||||||
} else if (message.getType() == MessageType.VEHICLE_TRANSFER) {
|
} else if (message.getType() == MessageType.VEHICLE_TRANSFER) {
|
||||||
Object payload = message.getPayload();
|
Object payload = message.getPayload();
|
||||||
System.out.println("[Exit] Payload type: " + payload.getClass().getName());
|
System.out.println("[Exit] Payload type: " + payload.getClass().getName());
|
||||||
|
|
||||||
// Handle Gson LinkedHashMap
|
// Tratamento de artefatos de desserialização do Gson (LinkedTreeMap -> POJO)
|
||||||
Vehicle vehicle;
|
Vehicle vehicle;
|
||||||
if (payload instanceof com.google.gson.internal.LinkedTreeMap ||
|
if (payload instanceof com.google.gson.internal.LinkedTreeMap ||
|
||||||
payload instanceof java.util.LinkedHashMap) {
|
payload instanceof java.util.LinkedHashMap) {
|
||||||
@@ -390,26 +377,21 @@ public class ExitNodeProcess {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Processa um veículo que acabou de sair do sistema.
|
* Processa atomicamente a saída de um veículo.
|
||||||
*
|
* <p>
|
||||||
* Calculamos quanto tempo demorou, atualizamos as nossas estatísticas globais e
|
* <b>Secção Crítica:</b> Método {@code synchronized} para garantir que a atualização
|
||||||
* notificamos o dashboard.
|
* das estatísticas globais (totalSystemTime, contadores) é atómica, prevenindo
|
||||||
* Este método é sincronizado porque múltiplos veículos podem chegar ao mesmo
|
* Race Conditions quando múltiplos veículos chegam simultaneamente de interseções diferentes.
|
||||||
* tempo.
|
* * @param vehicle O veículo que completou a rota.
|
||||||
*
|
|
||||||
* @param vehicle O veículo que completou a sua rota.
|
|
||||||
*/
|
*/
|
||||||
private synchronized void processExitingVehicle(Vehicle vehicle) {
|
private synchronized void processExitingVehicle(Vehicle vehicle) {
|
||||||
totalVehiclesReceived++;
|
totalVehiclesReceived++;
|
||||||
|
|
||||||
// Use simulation time instead of wall-clock time
|
// Cálculo de métricas finais baseadas no tempo virtual de simulação acumulado no veículo
|
||||||
// System time = total time vehicle spent in system (wait + crossing times)
|
|
||||||
// This represents the actual simulation time elapsed, not real-time
|
|
||||||
double waitTime = vehicle.getTotalWaitingTime();
|
double waitTime = vehicle.getTotalWaitingTime();
|
||||||
double crossingTime = vehicle.getTotalCrossingTime();
|
double crossingTime = vehicle.getTotalCrossingTime();
|
||||||
double systemTime = waitTime + crossingTime;
|
double systemTime = waitTime + crossingTime;
|
||||||
|
|
||||||
// Store times in seconds, will be converted to ms when sending to dashboard
|
|
||||||
totalSystemTime += systemTime;
|
totalSystemTime += systemTime;
|
||||||
totalWaitingTime += waitTime;
|
totalWaitingTime += waitTime;
|
||||||
totalCrossingTime += crossingTime;
|
totalCrossingTime += crossingTime;
|
||||||
@@ -421,23 +403,20 @@ public class ExitNodeProcess {
|
|||||||
System.out.printf("[Exit] Vehicle %s completed (type=%s, system_time=%.2fs, wait=%.2fs, crossing=%.2fs)%n",
|
System.out.printf("[Exit] Vehicle %s completed (type=%s, system_time=%.2fs, wait=%.2fs, crossing=%.2fs)%n",
|
||||||
vehicle.getId(), vehicle.getType(), systemTime, waitTime, crossingTime);
|
vehicle.getId(), vehicle.getType(), systemTime, waitTime, crossingTime);
|
||||||
|
|
||||||
// Log vehicle exit
|
// Logging estruturado
|
||||||
EventLogger.getInstance().logVehicle(EventType.VEHICLE_EXITED, "ExitNode", vehicle.getId(),
|
EventLogger.getInstance().logVehicle(EventType.VEHICLE_EXITED, "ExitNode", vehicle.getId(),
|
||||||
String.format("Completed - System: %.2fs, Wait: %.2fs, Crossing: %.2fs", systemTime, waitTime,
|
String.format("Completed - System: %.2fs, Wait: %.2fs, Crossing: %.2fs", systemTime, waitTime,
|
||||||
crossingTime));
|
crossingTime));
|
||||||
|
|
||||||
// Complete vehicle trace if tracking
|
// Finaliza o trace individual do veículo
|
||||||
VehicleTracer.getInstance().logExit(vehicle, systemTime);
|
VehicleTracer.getInstance().logExit(vehicle, systemTime);
|
||||||
|
|
||||||
// Send stats after every vehicle to ensure dashboard updates quickly
|
// Push imediato para o Dashboard para visualização em tempo real
|
||||||
sendStatsToDashboard();
|
sendStatsToDashboard();
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Envia as estatísticas mais recentes para o dashboard.
|
* Constrói e transmite o DTO de atualização de estatísticas.
|
||||||
*
|
|
||||||
* Empacotamos as contagens totais e os tempos médios num `StatsUpdatePayload`
|
|
||||||
* e enviamo-lo.
|
|
||||||
*/
|
*/
|
||||||
private void sendStatsToDashboard() {
|
private void sendStatsToDashboard() {
|
||||||
if (dashboardClient == null || !dashboardClient.isConnected()) {
|
if (dashboardClient == null || !dashboardClient.isConnected()) {
|
||||||
@@ -448,29 +427,28 @@ public class ExitNodeProcess {
|
|||||||
// Create stats payload
|
// Create stats payload
|
||||||
StatsUpdatePayload payload = new StatsUpdatePayload();
|
StatsUpdatePayload payload = new StatsUpdatePayload();
|
||||||
|
|
||||||
// Set global stats - convert seconds to milliseconds
|
// Set global stats - convert seconds to milliseconds for display consistency
|
||||||
payload.setTotalVehiclesCompleted(totalVehiclesReceived);
|
payload.setTotalVehiclesCompleted(totalVehiclesReceived);
|
||||||
payload.setTotalSystemTime((long) (totalSystemTime * 1000.0)); // s -> ms
|
payload.setTotalSystemTime((long) (totalSystemTime * 1000.0));
|
||||||
payload.setTotalWaitingTime((long) (totalWaitingTime * 1000.0)); // s -> ms
|
payload.setTotalWaitingTime((long) (totalWaitingTime * 1000.0));
|
||||||
|
|
||||||
// Set intersection-like stats so it shows up correctly in the dashboard table
|
// Hack: Usar campos de interseção para mostrar throughput no dashboard
|
||||||
payload.setIntersectionArrivals(totalVehiclesReceived);
|
payload.setIntersectionArrivals(totalVehiclesReceived);
|
||||||
payload.setIntersectionDepartures(totalVehiclesReceived);
|
payload.setIntersectionDepartures(totalVehiclesReceived);
|
||||||
payload.setIntersectionQueueSize(0);
|
payload.setIntersectionQueueSize(0);
|
||||||
|
|
||||||
// Set vehicle type stats
|
// Detailed breakdown
|
||||||
Map<VehicleType, Integer> typeCounts = new HashMap<>();
|
Map<VehicleType, Integer> typeCounts = new HashMap<>();
|
||||||
Map<VehicleType, Long> typeWaitTimes = new HashMap<>();
|
Map<VehicleType, Long> typeWaitTimes = new HashMap<>();
|
||||||
|
|
||||||
for (VehicleType type : VehicleType.values()) {
|
for (VehicleType type : VehicleType.values()) {
|
||||||
typeCounts.put(type, vehicleTypeCount.get(type));
|
typeCounts.put(type, vehicleTypeCount.get(type));
|
||||||
typeWaitTimes.put(type, (long) (vehicleTypeWaitTime.get(type) * 1000.0)); // s -> ms
|
typeWaitTimes.put(type, (long) (vehicleTypeWaitTime.get(type) * 1000.0));
|
||||||
}
|
}
|
||||||
|
|
||||||
payload.setVehicleTypeCounts(typeCounts);
|
payload.setVehicleTypeCounts(typeCounts);
|
||||||
payload.setVehicleTypeWaitTimes(typeWaitTimes);
|
payload.setVehicleTypeWaitTimes(typeWaitTimes);
|
||||||
|
|
||||||
// Send message
|
|
||||||
Message message = new Message(
|
Message message = new Message(
|
||||||
MessageType.STATS_UPDATE,
|
MessageType.STATS_UPDATE,
|
||||||
"ExitNode",
|
"ExitNode",
|
||||||
@@ -489,9 +467,8 @@ public class ExitNodeProcess {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Encerra graciosamente o processo.
|
* Encerramento gracioso do processo.
|
||||||
*
|
* Fecha sockets, termina a pool de threads e liberta recursos.
|
||||||
* Imprimimos as estatísticas finais, fechamos ligações e limpamos threads.
|
|
||||||
*/
|
*/
|
||||||
public void shutdown() {
|
public void shutdown() {
|
||||||
System.out.println("\n[Exit] Shutting down...");
|
System.out.println("\n[Exit] Shutting down...");
|
||||||
@@ -527,9 +504,7 @@ public class ExitNodeProcess {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Imprime um resumo dos resultados da simulação na consola.
|
* Imprime o relatório final no stdout.
|
||||||
* Isto dá-nos uma visão rápida de como a simulação correu (médias, contagens de
|
|
||||||
* veículos, etc.).
|
|
||||||
*/
|
*/
|
||||||
private void printFinalStatistics() {
|
private void printFinalStatistics() {
|
||||||
System.out.println("\n=== EXIT NODE STATISTICS ===");
|
System.out.println("\n=== EXIT NODE STATISTICS ===");
|
||||||
@@ -554,4 +529,4 @@ public class ExitNodeProcess {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
@@ -33,19 +33,22 @@ import sd.protocol.SocketConnection;
|
|||||||
import sd.serialization.SerializationException;
|
import sd.serialization.SerializationException;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Representa uma única interseção na nossa simulação de tráfego distribuída.
|
* Representa um nó de processamento autónomo na malha de simulação distribuída
|
||||||
*
|
* (Worker Node).
|
||||||
* Esta classe opera como um processo independente (uma aplicação Java autónoma)
|
* <p>
|
||||||
* e é responsável por:
|
* Esta classe implementa a lógica de uma interseção rodoviária utilizando uma
|
||||||
* 1. Gerir os semáforos e a sua temporização.
|
* arquitetura híbrida:
|
||||||
* 2. Processar as chegadas e partidas de veículos.
|
* <ol>
|
||||||
* 3. Comunicar com outras interseções e com o dashboard.
|
* <li><b>Reativa (Network I/O):</b> Threads dedicadas aceitam conexões TCP e
|
||||||
*
|
* injetam veículos nas filas de entrada assim que chegam.</li>
|
||||||
* Utiliza uma abordagem de Simulação de Eventos Discretos (DES), onde as
|
* <li><b>Proativa (DES Engine):</b> Uma thread de processamento de eventos gere
|
||||||
* mudanças de estado (como semáforos a mudar para verde)
|
* a lógica temporal (mudança de semáforos, tempos de travessia) baseada num
|
||||||
* são agendadas como eventos numa fila de prioridade, em vez de depender de
|
* relógio virtual monotónico.</li>
|
||||||
* loops contínuos ou threads em espera.
|
* </ol>
|
||||||
* Isto garante uma temporização precisa e uma execução eficiente.
|
* <p>
|
||||||
|
* A sincronização entre a chegada assíncrona de veículos (Rede) e o
|
||||||
|
* processamento determinístico (DES) é gerida através de estruturas de dados
|
||||||
|
* concorrentes e bloqueios justos (Fair Locks).
|
||||||
*/
|
*/
|
||||||
public class IntersectionProcess {
|
public class IntersectionProcess {
|
||||||
|
|
||||||
@@ -57,48 +60,56 @@ public class IntersectionProcess {
|
|||||||
|
|
||||||
private ServerSocket serverSocket;
|
private ServerSocket serverSocket;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Tabela de encaminhamento dinâmico para conexões de saída (Next-Hop Cache).
|
||||||
|
*/
|
||||||
private final Map<String, SocketConnection> outgoingConnections;
|
private final Map<String, SocketConnection> outgoingConnections;
|
||||||
|
|
||||||
|
/** Pool de threads para tratamento de I/O de rede (entrada de veículos). */
|
||||||
private final ExecutorService connectionHandlerPool;
|
private final ExecutorService connectionHandlerPool;
|
||||||
|
|
||||||
private ScheduledExecutorService statsExecutor;
|
private ScheduledExecutorService statsExecutor;
|
||||||
private ScheduledExecutorService departureExecutor;
|
private ScheduledExecutorService departureExecutor;
|
||||||
|
|
||||||
private volatile boolean running;
|
private volatile boolean running;
|
||||||
/** Escala temporal para visualização: tempo_real = tempo_simulado * escala */
|
/** Fator de dilatação temporal (0.0 = Velocidade Máxima, 1.0 = Tempo Real). */
|
||||||
private double timeScale;
|
private double timeScale;
|
||||||
|
|
||||||
/** Relógio central da simulação */
|
// --- Componentes DES (Simulação de Eventos Discretos) ---
|
||||||
|
/** Relógio central virtual da interseção. */
|
||||||
private final SimulationClock clock;
|
private final SimulationClock clock;
|
||||||
/** Fila de eventos discretos agendados */
|
/** Fila de prioridade (Min-Heap) para agendamento temporal de eventos. */
|
||||||
private final EventQueue eventQueue;
|
private final EventQueue eventQueue;
|
||||||
/** Sistema de registo de eventos */
|
|
||||||
private final EventLogger eventLogger;
|
private final EventLogger eventLogger;
|
||||||
/** Thread dedicada ao processamento sequencial de eventos DES */
|
/** Thread "Single-Writer" responsável pela mutação de estado da simulação. */
|
||||||
private Thread eventProcessorThread;
|
private Thread eventProcessorThread;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Lock para exclusão mútua entre semáforos.
|
* Mecanismo de exclusão mútua para controlo de fases semafóricas.
|
||||||
* Garante que apenas um semáforo pode estar verde de cada vez nesta interseção.
|
* Configurado com política de justiça (fairness=true) para evitar inanição
|
||||||
|
* (starvation) de direções com menos tráfego.
|
||||||
*/
|
*/
|
||||||
private final Lock trafficCoordinationLock;
|
private final Lock trafficCoordinationLock;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Regista qual direção tem atualmente o sinal verde.
|
* Estado volátil que indica a direção ativa. Apenas uma direção pode deter o
|
||||||
* {@code null} significa que todos os semáforos estão vermelhos.
|
* token 'Green' por vez.
|
||||||
*/
|
*/
|
||||||
private volatile String currentGreenDirection;
|
private volatile String currentGreenDirection;
|
||||||
|
|
||||||
private SocketClient dashboardClient;
|
private SocketClient dashboardClient;
|
||||||
|
|
||||||
|
// Métricas voláteis para acesso atómico sem bloqueio
|
||||||
private volatile int totalArrivals = 0;
|
private volatile int totalArrivals = 0;
|
||||||
private volatile int totalDepartures = 0;
|
private volatile int totalDepartures = 0;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Inicializa o processo da interseção.
|
* Inicializa o processo da interseção, carregando a topologia e preparando o
|
||||||
*
|
* motor DES.
|
||||||
* @param intersectionId O identificador único para esta interseção (ex: "Cr1").
|
*
|
||||||
* @param configFilePath O caminho para o ficheiro de configuração.
|
* @param intersectionId O identificador único na malha (ex: "Cr1").
|
||||||
* @throws IOException Se houver algum problema ao ler a configuração.
|
* @param configFilePath Caminho para o ficheiro de propriedades.
|
||||||
|
* @throws IOException Se falhar o bind da porta ou leitura de config.
|
||||||
*/
|
*/
|
||||||
public IntersectionProcess(String intersectionId, String configFilePath) throws IOException {
|
public IntersectionProcess(String intersectionId, String configFilePath) throws IOException {
|
||||||
this.intersectionId = intersectionId;
|
this.intersectionId = intersectionId;
|
||||||
@@ -127,13 +138,16 @@ public class IntersectionProcess {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Inicia o ciclo de processamento de eventos.
|
* Inicia o ciclo principal do motor de simulação (DES Engine Loop).
|
||||||
*
|
* <p>
|
||||||
* Esta thread é o coração do modelo DES para esta interseção. Retira eventos da
|
* Executa o ciclo "Fetch-Decode-Execute":
|
||||||
* fila
|
* <ol>
|
||||||
* e executa-os por ordem cronológica. Enquanto a thread principal trata das
|
* <li>Remove o evento com menor timestamp da fila (Fetch).</li>
|
||||||
* operações de I/O de rede (receção de veículos),
|
* <li>Avança o relógio virtual para o tempo do evento.</li>
|
||||||
* esta thread trata da lógica da simulação (semáforos, travessias de veículos).
|
* <li>Aplica atraso artificial se {@code timeScale > 0} (para visualização
|
||||||
|
* humana).</li>
|
||||||
|
* <li>Despacha o evento para o manipulador apropriado (Execute).</li>
|
||||||
|
* </ol>
|
||||||
*/
|
*/
|
||||||
private void startEventProcessor() {
|
private void startEventProcessor() {
|
||||||
eventProcessorThread = new Thread(() -> {
|
eventProcessorThread = new Thread(() -> {
|
||||||
@@ -145,9 +159,9 @@ public class IntersectionProcess {
|
|||||||
while (running) {
|
while (running) {
|
||||||
SimulationEvent event = eventQueue.poll();
|
SimulationEvent event = eventQueue.poll();
|
||||||
if (event == null) {
|
if (event == null) {
|
||||||
// No events currently, wait a bit before checking again
|
// Backoff exponencial ou sleep curto para evitar busy-waiting em idle
|
||||||
try {
|
try {
|
||||||
Thread.sleep(50); // Short sleep to avoid busy-waiting
|
Thread.sleep(50);
|
||||||
} catch (InterruptedException e) {
|
} catch (InterruptedException e) {
|
||||||
Thread.currentThread().interrupt();
|
Thread.currentThread().interrupt();
|
||||||
break;
|
break;
|
||||||
@@ -155,7 +169,7 @@ public class IntersectionProcess {
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Apply time scaling for visualization
|
// Aplicação de escala temporal (Throttle)
|
||||||
if (timeScale > 0) {
|
if (timeScale > 0) {
|
||||||
double simTimeDelta = event.getTimestamp() - lastTime;
|
double simTimeDelta = event.getTimestamp() - lastTime;
|
||||||
long realDelayMs = (long) (simTimeDelta * timeScale * 1000);
|
long realDelayMs = (long) (simTimeDelta * timeScale * 1000);
|
||||||
@@ -170,10 +184,10 @@ public class IntersectionProcess {
|
|||||||
lastTime = event.getTimestamp();
|
lastTime = event.getTimestamp();
|
||||||
}
|
}
|
||||||
|
|
||||||
// Advance clock to event time
|
// Atualização atómica do tempo de simulação
|
||||||
clock.advanceTo(event.getTimestamp());
|
clock.advanceTo(event.getTimestamp());
|
||||||
|
|
||||||
// Process the event
|
// Processamento polimórfico
|
||||||
processEvent(event);
|
processEvent(event);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -185,10 +199,12 @@ public class IntersectionProcess {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Processa um evento da fila de simulação.
|
* Despachante central de eventos.
|
||||||
* Cada tipo de evento é encaminhado para o seu tratador específico.
|
* <p>
|
||||||
*
|
* Encaminha o evento para a lógica de negócio específica baseada no tipo
|
||||||
* @param event o evento a processar
|
* {@link DESEventType}.
|
||||||
|
*
|
||||||
|
* @param event O evento de simulação a ser processado.
|
||||||
*/
|
*/
|
||||||
private void processEvent(SimulationEvent event) {
|
private void processEvent(SimulationEvent event) {
|
||||||
try {
|
try {
|
||||||
@@ -198,8 +214,8 @@ public class IntersectionProcess {
|
|||||||
break;
|
break;
|
||||||
|
|
||||||
case VEHICLE_ARRIVAL:
|
case VEHICLE_ARRIVAL:
|
||||||
// Vehicle arrivals are still handled via network messages
|
// Chegadas são tratadas reativamente via Socket, mas eventos podem ser usados
|
||||||
// This event type is for internal scheduling if needed
|
// para métricas
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case VEHICLE_CROSSING_START:
|
case VEHICLE_CROSSING_START:
|
||||||
@@ -225,12 +241,18 @@ public class IntersectionProcess {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Trata da mudança dos semáforos.
|
* Gere a máquina de estados dos semáforos.
|
||||||
*
|
* <p>
|
||||||
* Quando um semáforo muda de estado, registamos o evento, atualizamos o modelo
|
* O fluxo de execução é o seguinte:
|
||||||
* e, se tiver mudado para VERDE,
|
* <ol>
|
||||||
* verificamos imediatamente se há veículos à espera para atravessar.
|
* <li>Atualiza o estado do semáforo (Verde <-> Vermelho).</li>
|
||||||
* Também agendamos aqui o *próximo* evento de mudança, mantendo o ciclo ativo.
|
* <li>Se o novo estado for Verde: Calcula a capacidade de vazão e agenda
|
||||||
|
* travessias (Service Events).</li>
|
||||||
|
* <li>Agenda recursivamente a próxima mudança de estado para manter o ciclo
|
||||||
|
* infinito.</li>
|
||||||
|
* </ol>
|
||||||
|
*
|
||||||
|
* @param event O evento que desencadeou a mudança de estado.
|
||||||
*/
|
*/
|
||||||
private void handleTrafficLightChangeEvent(SimulationEvent event) {
|
private void handleTrafficLightChangeEvent(SimulationEvent event) {
|
||||||
TrafficLightEvent tlEvent = (TrafficLightEvent) event.getPayload();
|
TrafficLightEvent tlEvent = (TrafficLightEvent) event.getPayload();
|
||||||
@@ -252,12 +274,12 @@ public class IntersectionProcess {
|
|||||||
String.format("Direction %s changed to %s at time %.2f",
|
String.format("Direction %s changed to %s at time %.2f",
|
||||||
direction, newState, event.getTimestamp()));
|
direction, newState, event.getTimestamp()));
|
||||||
|
|
||||||
// If light turned GREEN, process queued vehicles
|
// Processamento de lote (Batch Processing) para a fase Verde
|
||||||
if (newState == TrafficLightState.GREEN) {
|
if (newState == TrafficLightState.GREEN) {
|
||||||
processQueuedVehiclesForLight(light, event.getTimestamp());
|
processQueuedVehiclesForLight(light, event.getTimestamp());
|
||||||
}
|
}
|
||||||
|
|
||||||
// Schedule next state change
|
// Agendamento do próximo ciclo (Feedback Loop)
|
||||||
double nextChangeTime = event.getTimestamp() +
|
double nextChangeTime = event.getTimestamp() +
|
||||||
(newState == TrafficLightState.GREEN ? light.getGreenTime() : light.getRedTime());
|
(newState == TrafficLightState.GREEN ? light.getGreenTime() : light.getRedTime());
|
||||||
|
|
||||||
@@ -269,23 +291,19 @@ public class IntersectionProcess {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Processa a fila de veículos quando um semáforo fica verde.
|
* Calcula a vazão da interseção durante uma fase verde.
|
||||||
*
|
|
||||||
* <p>
|
* <p>
|
||||||
* Para cada veículo na fila:
|
* Implementa uma lógica de previsão ("Look-ahead"):
|
||||||
* </p>
|
|
||||||
* <ol>
|
* <ol>
|
||||||
* <li>Calcula o tempo de travessia com base no tipo de veículo</li>
|
* <li>Itera sobre a fila de espera do semáforo.</li>
|
||||||
* <li>Verifica se cabe na duração restante do sinal verde</li>
|
* <li>Calcula o tempo de serviço acumulado (Service Time) baseado no tipo de
|
||||||
* <li>Agenda o evento de partida do veículo</li>
|
* veículo.</li>
|
||||||
|
* <li>Agenda a partida apenas se o veículo couber na janela temporal restante
|
||||||
|
* do sinal verde.</li>
|
||||||
* </ol>
|
* </ol>
|
||||||
*
|
*
|
||||||
* <p>
|
* @param light O semáforo ativo.
|
||||||
* Os veículos que não couberem no tempo verde ficam à espera do próximo ciclo.
|
* @param currentTime O instante de início da fase verde.
|
||||||
* </p>
|
|
||||||
*
|
|
||||||
* @param light o semáforo que acabou de ficar verde
|
|
||||||
* @param currentTime o tempo atual da simulação em segundos
|
|
||||||
*/
|
*/
|
||||||
private void processQueuedVehiclesForLight(TrafficLight light, double currentTime) {
|
private void processQueuedVehiclesForLight(TrafficLight light, double currentTime) {
|
||||||
double greenDuration = light.getGreenTime();
|
double greenDuration = light.getGreenTime();
|
||||||
@@ -295,30 +313,29 @@ public class IntersectionProcess {
|
|||||||
System.out.printf("[%s] Processing queue for %s (GREEN for %.2fs, queue size: %d, currentTime=%.2f)%n",
|
System.out.printf("[%s] Processing queue for %s (GREEN for %.2fs, queue size: %d, currentTime=%.2f)%n",
|
||||||
intersectionId, light.getId(), greenDuration, queueSize, currentTime);
|
intersectionId, light.getId(), greenDuration, queueSize, currentTime);
|
||||||
|
|
||||||
// Process vehicles while queue not empty and within green light duration
|
// Algoritmo de esvaziamento de fila baseado em Time Budget
|
||||||
while (light.getQueueSize() > 0) {
|
while (light.getQueueSize() > 0) {
|
||||||
// Calculate crossing time for next vehicle (peek at queue size to estimate)
|
// Estimativa inicial (optimista)
|
||||||
// We'll use LIGHT vehicle as default for estimation
|
|
||||||
double crossingTime = config.getLightVehicleCrossingTime();
|
double crossingTime = config.getLightVehicleCrossingTime();
|
||||||
|
|
||||||
// Check if another vehicle can fit in remaining green time
|
// Verificação de limite de tempo (Hard Deadline do sinal vermelho)
|
||||||
if (timeOffset + crossingTime > greenDuration) {
|
if (timeOffset + crossingTime > greenDuration) {
|
||||||
break; // No more vehicles can cross this green phase
|
break; // Veículo não cabe no ciclo atual
|
||||||
}
|
}
|
||||||
|
|
||||||
// Remove vehicle from queue with current simulation time
|
// Commit: Remove da fila
|
||||||
Vehicle vehicle = light.removeVehicle(currentTime + timeOffset);
|
Vehicle vehicle = light.removeVehicle(currentTime + timeOffset);
|
||||||
if (vehicle == null)
|
if (vehicle == null)
|
||||||
break;
|
break;
|
||||||
|
|
||||||
// Get actual crossing time for this vehicle
|
// Recálculo preciso baseado no tipo real do veículo
|
||||||
crossingTime = getCrossingTimeForVehicle(vehicle);
|
crossingTime = getCrossingTimeForVehicle(vehicle);
|
||||||
|
|
||||||
// Schedule crossing
|
// Agendamento do evento futuro de término de travessia
|
||||||
double crossingStartTime = currentTime + timeOffset;
|
double crossingStartTime = currentTime + timeOffset;
|
||||||
scheduleVehicleCrossing(vehicle, crossingStartTime, crossingTime);
|
scheduleVehicleCrossing(vehicle, crossingStartTime, crossingTime);
|
||||||
|
|
||||||
// Update offset for next vehicle
|
// Incrementa offset para serializar as travessias (Head-of-Line Blocking)
|
||||||
timeOffset += crossingTime;
|
timeOffset += crossingTime;
|
||||||
|
|
||||||
System.out.printf("[%s] Scheduled vehicle %s to cross at t=%.2f (duration=%.2fs)%n",
|
System.out.printf("[%s] Scheduled vehicle %s to cross at t=%.2f (duration=%.2fs)%n",
|
||||||
@@ -327,12 +344,11 @@ public class IntersectionProcess {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Agenda a travessia e partida de um veículo.
|
* Cria e agenda o evento de conclusão de travessia (Partida).
|
||||||
* Cria um evento de fim de travessia agendado para o tempo correto.
|
*
|
||||||
*
|
* @param vehicle O veículo que está a atravessar.
|
||||||
* @param vehicle o veículo que vai atravessar
|
* @param startTime Instante de início da travessia.
|
||||||
* @param startTime quando a travessia começa (segundos de simulação)
|
* @param crossingDuration Duração estimada da travessia.
|
||||||
* @param crossingDuration quanto tempo demora a atravessar (segundos)
|
|
||||||
*/
|
*/
|
||||||
private void scheduleVehicleCrossing(Vehicle vehicle, double startTime, double crossingDuration) {
|
private void scheduleVehicleCrossing(Vehicle vehicle, double startTime, double crossingDuration) {
|
||||||
// Schedule crossing end (when vehicle departs)
|
// Schedule crossing end (when vehicle departs)
|
||||||
@@ -351,11 +367,10 @@ public class IntersectionProcess {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Calcula o tempo de travessia com base no tipo de veículo.
|
* Determina o custo temporal da travessia baseado na física do veículo.
|
||||||
* Bicicletas são mais rápidas, veículos pesados mais lentos.
|
*
|
||||||
*
|
* @param vehicle O veículo em questão.
|
||||||
* @param vehicle o veículo para calcular o tempo
|
* @return O tempo em segundos necessário para atravessar a interseção.
|
||||||
* @return tempo de travessia em segundos
|
|
||||||
*/
|
*/
|
||||||
private double getCrossingTimeForVehicle(Vehicle vehicle) {
|
private double getCrossingTimeForVehicle(Vehicle vehicle) {
|
||||||
return switch (vehicle.getType()) {
|
return switch (vehicle.getType()) {
|
||||||
@@ -367,36 +382,45 @@ public class IntersectionProcess {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Trata o evento de início de travessia de um veículo.
|
* Manipula o evento de início de travessia de um veículo.
|
||||||
* (Implementação futura - atualmente apenas regista o evento)
|
* <p>
|
||||||
*
|
* Atualmente serve como placeholder para lógica futura de animação ou
|
||||||
* @param event o evento de início de travessia
|
* ocupação de zonas críticas na interseção.
|
||||||
|
*
|
||||||
|
* @param event O evento de início de travessia.
|
||||||
*/
|
*/
|
||||||
private void handleVehicleCrossingStartEvent(SimulationEvent event) {
|
private void handleVehicleCrossingStartEvent(SimulationEvent event) {
|
||||||
// Implementation will depend on how vehicle crossing is modeled
|
// Placeholder para lógica futura de animação ou ocupação de zona crítica
|
||||||
// For now, log the event
|
|
||||||
eventLogger.log(sd.logging.EventType.VEHICLE_DEPARTED, intersectionId,
|
eventLogger.log(sd.logging.EventType.VEHICLE_DEPARTED, intersectionId,
|
||||||
"Vehicle crossing started at time " + event.getTimestamp());
|
"Vehicle crossing started at time " + event.getTimestamp());
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Trata o fim da travessia de um veículo pela interseção.
|
* Finaliza a lógica de travessia e inicia a transferência (handover) para o
|
||||||
* Atualiza estatísticas, regista o tempo de travessia e envia o veículo
|
* próximo nó.
|
||||||
* para o próximo destino na sua rota.
|
* <p>
|
||||||
*
|
* Este método é invocado quando o tempo de travessia expira no relógio virtual.
|
||||||
* @param event evento contendo o veículo que terminou a travessia
|
* Executa as seguintes ações:
|
||||||
|
* <ol>
|
||||||
|
* <li>Atualiza as métricas de tempo de travessia do veículo.</li>
|
||||||
|
* <li>Incrementa contadores locais de veículos processados.</li>
|
||||||
|
* <li>Transfere a responsabilidade do veículo para a rede, enviando-o ao
|
||||||
|
* próximo destino.</li>
|
||||||
|
* </ol>
|
||||||
|
*
|
||||||
|
* @param event O evento de fim de travessia.
|
||||||
*/
|
*/
|
||||||
private void handleVehicleCrossingEndEvent(SimulationEvent event) {
|
private void handleVehicleCrossingEndEvent(SimulationEvent event) {
|
||||||
Vehicle vehicle = (Vehicle) event.getPayload();
|
Vehicle vehicle = (Vehicle) event.getPayload();
|
||||||
|
|
||||||
// Add crossing time to vehicle stats
|
// Atualiza métricas do veículo
|
||||||
double crossingTime = getCrossingTimeForVehicle(vehicle);
|
double crossingTime = getCrossingTimeForVehicle(vehicle);
|
||||||
vehicle.addCrossingTime(crossingTime);
|
vehicle.addCrossingTime(crossingTime);
|
||||||
|
|
||||||
// Update intersection statistics
|
// Atualiza métricas locais
|
||||||
intersection.incrementVehiclesSent();
|
intersection.incrementVehiclesSent();
|
||||||
|
|
||||||
// Send vehicle to next destination
|
// Handover: Transfere a responsabilidade do veículo para a rede
|
||||||
sendVehicleToNextDestination(vehicle);
|
sendVehicleToNextDestination(vehicle);
|
||||||
|
|
||||||
eventLogger.log(sd.logging.EventType.VEHICLE_DEPARTED, intersectionId,
|
eventLogger.log(sd.logging.EventType.VEHICLE_DEPARTED, intersectionId,
|
||||||
@@ -404,10 +428,9 @@ public class IntersectionProcess {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Trata o evento de fim da simulação.
|
* Finaliza a execução do processo de simulação.
|
||||||
* Define a flag de execução como falsa para terminar o processamento.
|
|
||||||
*
|
*
|
||||||
* @param event o evento de fim de simulação
|
* @param event O evento de fim de simulação.
|
||||||
*/
|
*/
|
||||||
private void handleSimulationEndEvent(SimulationEvent event) {
|
private void handleSimulationEndEvent(SimulationEvent event) {
|
||||||
eventLogger.log(sd.logging.EventType.SIMULATION_STOPPED, intersectionId,
|
eventLogger.log(sd.logging.EventType.SIMULATION_STOPPED, intersectionId,
|
||||||
@@ -416,10 +439,9 @@ public class IntersectionProcess {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Exporta o histórico completo de eventos para um ficheiro.
|
* Exporta o histórico completo de eventos para análise post-mortem.
|
||||||
* Útil para análise posterior e debugging da simulação.
|
*
|
||||||
*
|
* @param outputPath O caminho do ficheiro onde o histórico será guardado.
|
||||||
* @param outputPath caminho do ficheiro onde guardar o histórico
|
|
||||||
*/
|
*/
|
||||||
public void exportEventHistory(String outputPath) {
|
public void exportEventHistory(String outputPath) {
|
||||||
String history = eventQueue.exportEventHistory();
|
String history = eventQueue.exportEventHistory();
|
||||||
@@ -431,7 +453,12 @@ public class IntersectionProcess {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Main entry point for running an intersection process
|
/**
|
||||||
|
* Ponto de entrada principal da aplicação.
|
||||||
|
*
|
||||||
|
* @param args Argumentos da linha de comando (ID da interseção e ficheiro de
|
||||||
|
* configuração opcional).
|
||||||
|
*/
|
||||||
public static void main(String[] args) {
|
public static void main(String[] args) {
|
||||||
if (args.length < 1) {
|
if (args.length < 1) {
|
||||||
System.err.println("Usage: java IntersectionProcess <intersectionId> [configFile]");
|
System.err.println("Usage: java IntersectionProcess <intersectionId> [configFile]");
|
||||||
@@ -460,6 +487,12 @@ public class IntersectionProcess {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Realiza o bootstrap dos componentes lógicos e de rede da interseção.
|
||||||
|
* <p>
|
||||||
|
* Inclui a criação de semáforos, configuração de encaminhamento e conexão ao
|
||||||
|
* Dashboard.
|
||||||
|
*/
|
||||||
public void initialize() {
|
public void initialize() {
|
||||||
System.out.println("\n[" + intersectionId + "] Initializing intersection...");
|
System.out.println("\n[" + intersectionId + "] Initializing intersection...");
|
||||||
|
|
||||||
@@ -473,7 +506,7 @@ public class IntersectionProcess {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Estabelece ligação ao servidor do dashboard para reportar estatísticas.
|
* Estabelece a conexão com o Dashboard para envio de telemetria em tempo real.
|
||||||
*/
|
*/
|
||||||
private void connectToDashboard() {
|
private void connectToDashboard() {
|
||||||
try {
|
try {
|
||||||
@@ -497,9 +530,7 @@ public class IntersectionProcess {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Cria os semáforos para esta interseção com base nas suas ligações físicas.
|
* Inicializa os semáforos da interseção com base na configuração carregada.
|
||||||
* Cada interseção tem um número e direções de semáforos diferentes de acordo
|
|
||||||
* com a topologia da rede.
|
|
||||||
*/
|
*/
|
||||||
private void createTrafficLights() {
|
private void createTrafficLights() {
|
||||||
System.out.println("\n[" + intersectionId + "] Creating traffic lights...");
|
System.out.println("\n[" + intersectionId + "] Creating traffic lights...");
|
||||||
@@ -528,6 +559,13 @@ public class IntersectionProcess {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Obtém a configuração específica para esta interseção a partir da configuração
|
||||||
|
* global.
|
||||||
|
*
|
||||||
|
* @return O objeto de configuração da interseção.
|
||||||
|
* @throws RuntimeException Se a configuração estiver em falta.
|
||||||
|
*/
|
||||||
private SimulationConfig.IntersectionConfig getIntersectionConfig() {
|
private SimulationConfig.IntersectionConfig getIntersectionConfig() {
|
||||||
if (config.getNetworkConfig() == null || config.getNetworkConfig().getIntersections() == null) {
|
if (config.getNetworkConfig() == null || config.getNetworkConfig().getIntersections() == null) {
|
||||||
throw new RuntimeException("Network configuration not loaded or empty.");
|
throw new RuntimeException("Network configuration not loaded or empty.");
|
||||||
@@ -538,6 +576,11 @@ public class IntersectionProcess {
|
|||||||
.orElseThrow(() -> new RuntimeException("Intersection config not found for " + intersectionId));
|
.orElseThrow(() -> new RuntimeException("Intersection config not found for " + intersectionId));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Configura a tabela de encaminhamento (routing) da interseção.
|
||||||
|
* <p>
|
||||||
|
* Define para cada destino qual a direção de saída (semáforo) correspondente.
|
||||||
|
*/
|
||||||
private void configureRouting() {
|
private void configureRouting() {
|
||||||
System.out.println("\n[" + intersectionId + "] Configuring routing...");
|
System.out.println("\n[" + intersectionId + "] Configuring routing...");
|
||||||
|
|
||||||
@@ -559,11 +602,10 @@ public class IntersectionProcess {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Solicita permissão para um semáforo ficar verde.
|
* Primitiva de bloqueio: Solicita acesso exclusivo à zona crítica da
|
||||||
* Bloqueia até que a permissão seja concedida (nenhum outro semáforo está
|
* interseção.
|
||||||
* verde).
|
*
|
||||||
*
|
* @param direction A direção que solicita passagem.
|
||||||
* @param direction A direção que solicita o sinal verde
|
|
||||||
*/
|
*/
|
||||||
public void requestGreenLight(String direction) {
|
public void requestGreenLight(String direction) {
|
||||||
trafficCoordinationLock.lock();
|
trafficCoordinationLock.lock();
|
||||||
@@ -571,10 +613,9 @@ public class IntersectionProcess {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Liberta a permissão de sinal verde, permitindo que outro semáforo fique
|
* Primitiva de bloqueio: Liberta o acesso exclusivo à zona crítica.
|
||||||
* verde.
|
*
|
||||||
*
|
* @param direction A direção que está a libertar a passagem.
|
||||||
* @param direction A direção que liberta o sinal verde
|
|
||||||
*/
|
*/
|
||||||
public void releaseGreenLight(String direction) {
|
public void releaseGreenLight(String direction) {
|
||||||
if (direction.equals(currentGreenDirection)) {
|
if (direction.equals(currentGreenDirection)) {
|
||||||
@@ -584,8 +625,10 @@ public class IntersectionProcess {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Modo DES: Agenda os eventos iniciais de mudança de semáforo.
|
* Inicializa o estado dos semáforos no arranque da simulação (t=0).
|
||||||
* Isto substitui a antiga abordagem baseada em threads startTrafficLights().
|
* <p>
|
||||||
|
* Garante que apenas um semáforo começa em Verde e os restantes em Vermelho,
|
||||||
|
* agendando os eventos iniciais na fila do DES.
|
||||||
*/
|
*/
|
||||||
private void scheduleInitialTrafficLightEvents() {
|
private void scheduleInitialTrafficLightEvents() {
|
||||||
System.out.println("\n[" + intersectionId + "] Scheduling initial traffic light events (DES mode)...");
|
System.out.println("\n[" + intersectionId + "] Scheduling initial traffic light events (DES mode)...");
|
||||||
@@ -596,12 +639,12 @@ public class IntersectionProcess {
|
|||||||
for (TrafficLight light : intersection.getTrafficLights()) {
|
for (TrafficLight light : intersection.getTrafficLights()) {
|
||||||
String direction = light.getDirection();
|
String direction = light.getDirection();
|
||||||
|
|
||||||
// Set initial state (first light starts green, others red)
|
// Lógica de arranque: Primeiro da lista = Verde, outros = Vermelho
|
||||||
boolean isFirstLight = intersection.getTrafficLights().indexOf(light) == 0;
|
boolean isFirstLight = intersection.getTrafficLights().indexOf(light) == 0;
|
||||||
TrafficLightState initialState = isFirstLight ? TrafficLightState.GREEN : TrafficLightState.RED;
|
TrafficLightState initialState = isFirstLight ? TrafficLightState.GREEN : TrafficLightState.RED;
|
||||||
light.changeState(initialState);
|
light.changeState(initialState);
|
||||||
|
|
||||||
// Schedule first state change
|
// Agenda a primeira transição
|
||||||
double firstChangeTime = currentTime +
|
double firstChangeTime = currentTime +
|
||||||
(initialState == TrafficLightState.GREEN ? light.getGreenTime() : light.getRedTime());
|
(initialState == TrafficLightState.GREEN ? light.getGreenTime() : light.getRedTime());
|
||||||
|
|
||||||
@@ -624,14 +667,16 @@ public class IntersectionProcess {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Envia um veículo para o seu próximo destino via ligação socket.
|
* Encaminhamento de rede: Serializa e envia o objeto veículo para o próximo nó.
|
||||||
|
* <p>
|
||||||
|
* Calcula também o tempo de viagem virtual entre nós (Edge Weight).
|
||||||
*
|
*
|
||||||
* @param vehicle O veículo que atravessou esta interseção.
|
* @param vehicle O veículo a ser enviado.
|
||||||
*/
|
*/
|
||||||
public void sendVehicleToNextDestination(Vehicle vehicle) {
|
public void sendVehicleToNextDestination(Vehicle vehicle) {
|
||||||
String nextDestination = vehicle.getCurrentDestination();
|
String nextDestination = vehicle.getCurrentDestination();
|
||||||
|
|
||||||
// Calculate travel time
|
// Cálculo de latência de viagem (Edge Weight)
|
||||||
double baseTime = config.getBaseTravelTime();
|
double baseTime = config.getBaseTravelTime();
|
||||||
double multiplier = 1.0;
|
double multiplier = 1.0;
|
||||||
switch (vehicle.getType()) {
|
switch (vehicle.getType()) {
|
||||||
@@ -644,22 +689,25 @@ public class IntersectionProcess {
|
|||||||
System.out.printf("[%s] Vehicle %s departing to %s. Travel time: %.2fs%n",
|
System.out.printf("[%s] Vehicle %s departing to %s. Travel time: %.2fs%n",
|
||||||
intersectionId, vehicle.getId(), nextDestination, travelTime);
|
intersectionId, vehicle.getId(), nextDestination, travelTime);
|
||||||
|
|
||||||
// Record departure immediately as it leaves the intersection
|
|
||||||
recordVehicleDeparture();
|
recordVehicleDeparture();
|
||||||
|
|
||||||
// In DES mode, send immediately (no real-time delay)
|
// Envio imediato (o delay de viagem é implícito no tempo de chegada no próximo
|
||||||
|
// nó ou simulado aqui)
|
||||||
sendVehicleImmediately(vehicle, nextDestination);
|
sendVehicleImmediately(vehicle, nextDestination);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Envia imediatamente um veículo para o seu destino via rede.
|
* Envia o veículo imediatamente para o próximo nó via conexão TCP persistente.
|
||||||
|
*
|
||||||
|
* @param vehicle O veículo a ser enviado.
|
||||||
|
* @param nextDestination O identificador do próximo nó destino.
|
||||||
*/
|
*/
|
||||||
private void sendVehicleImmediately(Vehicle vehicle, String nextDestination) {
|
private void sendVehicleImmediately(Vehicle vehicle, String nextDestination) {
|
||||||
try {
|
try {
|
||||||
// Get or create connection to next destination
|
// Lazy loading da conexão
|
||||||
SocketConnection connection = getOrCreateConnection(nextDestination);
|
SocketConnection connection = getOrCreateConnection(nextDestination);
|
||||||
|
|
||||||
// Create and send message using Message class
|
// Encapsulamento da mensagem
|
||||||
MessageProtocol message = new Message(
|
MessageProtocol message = new Message(
|
||||||
MessageType.VEHICLE_TRANSFER,
|
MessageType.VEHICLE_TRANSFER,
|
||||||
intersectionId,
|
intersectionId,
|
||||||
@@ -672,8 +720,6 @@ public class IntersectionProcess {
|
|||||||
System.out.println("[" + intersectionId + "] Vehicle " + vehicle.getId() +
|
System.out.println("[" + intersectionId + "] Vehicle " + vehicle.getId() +
|
||||||
" arrived at " + nextDestination + " (msg sent)");
|
" arrived at " + nextDestination + " (msg sent)");
|
||||||
|
|
||||||
// Note: vehicle route is advanced when it arrives at the next intersection
|
|
||||||
|
|
||||||
} catch (IOException | InterruptedException e) {
|
} catch (IOException | InterruptedException e) {
|
||||||
System.err.println("[" + intersectionId + "] Failed to send vehicle " +
|
System.err.println("[" + intersectionId + "] Failed to send vehicle " +
|
||||||
vehicle.getId() + " to " + nextDestination + ": " + e.getMessage());
|
vehicle.getId() + " to " + nextDestination + ": " + e.getMessage());
|
||||||
@@ -681,12 +727,15 @@ public class IntersectionProcess {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Obtém uma ligação existente para um destino ou cria uma nova.
|
* Obtém ou cria uma conexão para o destino especificado (Singleton por
|
||||||
|
* destino).
|
||||||
|
* <p>
|
||||||
|
* Este método é thread-safe.
|
||||||
*
|
*
|
||||||
* @param destinationId O ID do nó de destino.
|
* @param destinationId O identificador do nó destino.
|
||||||
* @return A SocketConnection para esse destino.
|
* @return A conexão TCP estabelecida.
|
||||||
* @throws IOException Se a ligação não puder ser estabelecida.
|
* @throws IOException Se ocorrer um erro de I/O na criação da conexão.
|
||||||
* @throws InterruptedException Se a tentativa de ligação for interrompida.
|
* @throws InterruptedException Se a thread for interrompida durante a espera.
|
||||||
*/
|
*/
|
||||||
private synchronized SocketConnection getOrCreateConnection(String destinationId)
|
private synchronized SocketConnection getOrCreateConnection(String destinationId)
|
||||||
throws IOException, InterruptedException {
|
throws IOException, InterruptedException {
|
||||||
@@ -706,10 +755,10 @@ public class IntersectionProcess {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Obtém o endereço host para um nó de destino a partir da configuração.
|
* Resolve o hostname ou endereço IP para um determinado destino.
|
||||||
*
|
*
|
||||||
* @param destinationId O ID do nó de destino.
|
* @param destinationId O ID do destino.
|
||||||
* @return O endereço host.
|
* @return O endereço do host.
|
||||||
*/
|
*/
|
||||||
private String getHostForDestination(String destinationId) {
|
private String getHostForDestination(String destinationId) {
|
||||||
if (destinationId.equals("S")) {
|
if (destinationId.equals("S")) {
|
||||||
@@ -720,9 +769,9 @@ public class IntersectionProcess {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Obtém o número da porta para um nó de destino a partir da configuração.
|
* Resolve a porta TCP para um determinado destino.
|
||||||
*
|
*
|
||||||
* @param destinationId O ID do nó de destino.
|
* @param destinationId O ID do destino.
|
||||||
* @return O número da porta.
|
* @return O número da porta.
|
||||||
*/
|
*/
|
||||||
private int getPortForDestination(String destinationId) {
|
private int getPortForDestination(String destinationId) {
|
||||||
@@ -734,10 +783,11 @@ public class IntersectionProcess {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Inicia o socket do servidor e começa a aceitar ligações recebidas.
|
* Inicia o servidor e o loop de aceitação de conexões.
|
||||||
* Este é o loop principal de escuta do processo.
|
* <p>
|
||||||
|
* Este método bloqueia a thread chamadora durante a execução do servidor.
|
||||||
*
|
*
|
||||||
* @throws IOException Se o socket do servidor não puder ser criado.
|
* @throws IOException Se ocorrer um erro ao fazer bind da porta.
|
||||||
*/
|
*/
|
||||||
public void start() throws IOException {
|
public void start() throws IOException {
|
||||||
int port = config.getIntersectionPort(intersectionId);
|
int port = config.getIntersectionPort(intersectionId);
|
||||||
@@ -751,12 +801,12 @@ public class IntersectionProcess {
|
|||||||
startEventProcessor();
|
startEventProcessor();
|
||||||
System.out.println("[" + intersectionId + "] Running in DES mode");
|
System.out.println("[" + intersectionId + "] Running in DES mode");
|
||||||
|
|
||||||
// Start stats updater
|
// Background task para telemetria
|
||||||
statsExecutor.scheduleAtFixedRate(this::sendStatsToDashboard, 1, 1, TimeUnit.SECONDS);
|
statsExecutor.scheduleAtFixedRate(this::sendStatsToDashboard, 1, 1, TimeUnit.SECONDS);
|
||||||
|
|
||||||
System.out.println("[" + intersectionId + "] Waiting for incoming connections...\n");
|
System.out.println("[" + intersectionId + "] Waiting for incoming connections...\n");
|
||||||
|
|
||||||
// Main accept loop
|
// Loop principal de aceitação de conexões
|
||||||
while (running) {
|
while (running) {
|
||||||
try {
|
try {
|
||||||
Socket clientSocket = serverSocket.accept();
|
Socket clientSocket = serverSocket.accept();
|
||||||
@@ -764,13 +814,12 @@ public class IntersectionProcess {
|
|||||||
System.out.println("[" + intersectionId + "] New connection accepted from " +
|
System.out.println("[" + intersectionId + "] New connection accepted from " +
|
||||||
clientSocket.getInetAddress().getHostAddress());
|
clientSocket.getInetAddress().getHostAddress());
|
||||||
|
|
||||||
// Check running flag again before handling
|
|
||||||
if (!running) {
|
if (!running) {
|
||||||
clientSocket.close();
|
clientSocket.close();
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
// **Set timeout before submitting to handler**
|
// Configura timeout para evitar bloqueios infinitos em leitura
|
||||||
try {
|
try {
|
||||||
clientSocket.setSoTimeout(1000);
|
clientSocket.setSoTimeout(1000);
|
||||||
} catch (java.net.SocketException e) {
|
} catch (java.net.SocketException e) {
|
||||||
@@ -779,13 +828,12 @@ public class IntersectionProcess {
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Handle each connection in a separate thread
|
// Delega processamento para thread pool (NIO style)
|
||||||
connectionHandlerPool.submit(() -> handleIncomingConnection(clientSocket));
|
connectionHandlerPool.submit(() -> handleIncomingConnection(clientSocket));
|
||||||
|
|
||||||
} catch (IOException e) {
|
} catch (IOException e) {
|
||||||
// Expected when serverSocket.close() is called during shutdown
|
|
||||||
if (!running) {
|
if (!running) {
|
||||||
break; // Normal shutdown
|
break; // Shutdown normal
|
||||||
}
|
}
|
||||||
System.err.println("[" + intersectionId + "] Error accepting connection: " +
|
System.err.println("[" + intersectionId + "] Error accepting connection: " +
|
||||||
e.getMessage());
|
e.getMessage());
|
||||||
@@ -794,10 +842,13 @@ public class IntersectionProcess {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Trata uma ligação recebida de outro processo.
|
* Lógica de tratamento de conexões de entrada (Consumer).
|
||||||
* Escuta continuamente mensagens de transferência de veículos.
|
* <p>
|
||||||
|
* Lê continuamente do socket até que a conexão seja fechada, processando
|
||||||
|
* mensagens
|
||||||
|
* de chegada de veículos ou comandos de simulação.
|
||||||
*
|
*
|
||||||
* @param clientSocket A ligação socket aceite.
|
* @param clientSocket O socket do cliente conectado.
|
||||||
*/
|
*/
|
||||||
private void handleIncomingConnection(Socket clientSocket) {
|
private void handleIncomingConnection(Socket clientSocket) {
|
||||||
try {
|
try {
|
||||||
@@ -813,27 +864,24 @@ public class IntersectionProcess {
|
|||||||
System.out.println("[" + intersectionId + "] New connection accepted from " +
|
System.out.println("[" + intersectionId + "] New connection accepted from " +
|
||||||
clientSocket.getInetAddress().getHostAddress());
|
clientSocket.getInetAddress().getHostAddress());
|
||||||
|
|
||||||
// Continuously receive messages while connection is active
|
|
||||||
while (running && connection.isConnected()) {
|
while (running && connection.isConnected()) {
|
||||||
try {
|
try {
|
||||||
MessageProtocol message = connection.receiveMessage();
|
MessageProtocol message = connection.receiveMessage();
|
||||||
|
|
||||||
// Handle simulation start time synchronization
|
|
||||||
if (message.getType() == MessageType.SIMULATION_START) {
|
if (message.getType() == MessageType.SIMULATION_START) {
|
||||||
System.out.println("[" + intersectionId + "] Simulation start time synchronized");
|
System.out.println("[" + intersectionId + "] Simulation start time synchronized");
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Accept both VEHICLE_TRANSFER and VEHICLE_SPAWN (from coordinator)
|
|
||||||
if (message.getType() == MessageType.VEHICLE_TRANSFER ||
|
if (message.getType() == MessageType.VEHICLE_TRANSFER ||
|
||||||
message.getType() == MessageType.VEHICLE_SPAWN) {
|
message.getType() == MessageType.VEHICLE_SPAWN) {
|
||||||
// Cast payload to Vehicle - handle Gson deserialization
|
|
||||||
|
// Lógica de desserialização polimórfica (Vehicle ou Map)
|
||||||
Vehicle vehicle;
|
Vehicle vehicle;
|
||||||
Object payload = message.getPayload();
|
Object payload = message.getPayload();
|
||||||
if (payload instanceof Vehicle) {
|
if (payload instanceof Vehicle) {
|
||||||
vehicle = (Vehicle) payload;
|
vehicle = (Vehicle) payload;
|
||||||
} else if (payload instanceof java.util.Map) {
|
} else if (payload instanceof java.util.Map) {
|
||||||
// Gson deserialized as LinkedHashMap - re-serialize and deserialize as Vehicle
|
|
||||||
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);
|
||||||
vehicle = gson.fromJson(json, Vehicle.class);
|
vehicle = gson.fromJson(json, Vehicle.class);
|
||||||
@@ -845,43 +893,37 @@ public class IntersectionProcess {
|
|||||||
System.out.println("[" + intersectionId + "] Received vehicle: " +
|
System.out.println("[" + intersectionId + "] Received vehicle: " +
|
||||||
vehicle.getId() + " from " + message.getSourceNode());
|
vehicle.getId() + " from " + message.getSourceNode());
|
||||||
|
|
||||||
// Advance vehicle to next destination in its route
|
// Lógica de Roteamento Local
|
||||||
vehicle.advanceRoute();
|
vehicle.advanceRoute();
|
||||||
|
|
||||||
// Add vehicle to appropriate queue with current simulation time
|
|
||||||
intersection.receiveVehicle(vehicle, clock.getCurrentTime());
|
intersection.receiveVehicle(vehicle, clock.getCurrentTime());
|
||||||
|
|
||||||
// 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",
|
||||||
intersectionId, vehicle.getId(), intersection.getTotalQueueSize());
|
intersectionId, vehicle.getId(), intersection.getTotalQueueSize());
|
||||||
|
|
||||||
// Record arrival for statistics
|
|
||||||
recordVehicleArrival();
|
recordVehicleArrival();
|
||||||
|
|
||||||
} else if (message.getType() == MessageType.SHUTDOWN) {
|
} else if (message.getType() == MessageType.SHUTDOWN) {
|
||||||
System.out.println(
|
System.out.println(
|
||||||
"[" + intersectionId + "] Received SHUTDOWN command from " + message.getSourceNode());
|
"[" + intersectionId + "] Received SHUTDOWN command from " + message.getSourceNode());
|
||||||
running = false;
|
running = false;
|
||||||
// Close this specific connection
|
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
} catch (java.net.SocketTimeoutException e) {
|
} catch (java.net.SocketTimeoutException e) {
|
||||||
// Timeout - check running flag and continue
|
|
||||||
if (!running) {
|
if (!running) {
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
// Continue waiting for next message
|
|
||||||
} catch (ClassNotFoundException e) {
|
} catch (ClassNotFoundException e) {
|
||||||
System.err.println("[" + intersectionId + "] Unknown message type received: " +
|
System.err.println("[" + intersectionId + "] Unknown message type received: " +
|
||||||
e.getMessage());
|
e.getMessage());
|
||||||
break; // Invalid message, close connection
|
break;
|
||||||
} catch (IOException e) {
|
} catch (IOException e) {
|
||||||
if (running) {
|
if (running) {
|
||||||
System.err.println("[" + intersectionId + "] Failed to deserialize message: " +
|
System.err.println("[" + intersectionId + "] Failed to deserialize message: " +
|
||||||
e.getMessage());
|
e.getMessage());
|
||||||
e.printStackTrace(); // For debugging - maybe change//remove later
|
e.printStackTrace();
|
||||||
}
|
}
|
||||||
break; // Connection error, close connection
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -889,27 +931,29 @@ public class IntersectionProcess {
|
|||||||
if (running) {
|
if (running) {
|
||||||
System.err.println("[" + intersectionId + "] Connection error: " + e.getMessage());
|
System.err.println("[" + intersectionId + "] Connection error: " + e.getMessage());
|
||||||
}
|
}
|
||||||
// Expected during shutdown
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Stops the intersection process gracefully.
|
* Procedimento de Encerramento Gracioso (Graceful Shutdown).
|
||||||
* Shuts down all threads and closes all connections.
|
* <ol>
|
||||||
|
* <li>Para a aceitação de novas conexões.</li>
|
||||||
|
* <li>Envia últimas estatísticas.</li>
|
||||||
|
* <li>Encerra pools de threads.</li>
|
||||||
|
* <li>Fecha sockets ativos.</li>
|
||||||
|
* </ol>
|
||||||
*/
|
*/
|
||||||
public void shutdown() {
|
public void shutdown() {
|
||||||
// Check if already shutdown
|
|
||||||
if (!running) {
|
if (!running) {
|
||||||
return; // Already shutdown, do nothing
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
System.out.println("\n[" + intersectionId + "] Shutting down...");
|
System.out.println("\n[" + intersectionId + "] Shutting down...");
|
||||||
running = false;
|
running = false;
|
||||||
|
|
||||||
// Send final stats before closing connections
|
|
||||||
sendStatsToDashboard();
|
sendStatsToDashboard();
|
||||||
|
|
||||||
// 1. Close ServerSocket first
|
// 1. Close ServerSocket
|
||||||
if (serverSocket != null && !serverSocket.isClosed()) {
|
if (serverSocket != null && !serverSocket.isClosed()) {
|
||||||
try {
|
try {
|
||||||
serverSocket.close();
|
serverSocket.close();
|
||||||
@@ -918,8 +962,7 @@ public class IntersectionProcess {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 2. Shutdown thread pools with force
|
// 2. Shutdown thread pools
|
||||||
|
|
||||||
if (connectionHandlerPool != null && !connectionHandlerPool.isShutdown()) {
|
if (connectionHandlerPool != null && !connectionHandlerPool.isShutdown()) {
|
||||||
connectionHandlerPool.shutdownNow();
|
connectionHandlerPool.shutdownNow();
|
||||||
}
|
}
|
||||||
@@ -930,9 +973,8 @@ public class IntersectionProcess {
|
|||||||
departureExecutor.shutdownNow();
|
departureExecutor.shutdownNow();
|
||||||
}
|
}
|
||||||
|
|
||||||
// 3. Wait briefly for termination (don't block forever)
|
// 3. Wait briefly for termination
|
||||||
try {
|
try {
|
||||||
|
|
||||||
if (connectionHandlerPool != null) {
|
if (connectionHandlerPool != null) {
|
||||||
connectionHandlerPool.awaitTermination(1, TimeUnit.SECONDS);
|
connectionHandlerPool.awaitTermination(1, TimeUnit.SECONDS);
|
||||||
}
|
}
|
||||||
@@ -968,31 +1010,32 @@ public class IntersectionProcess {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Gets the Intersection object managed by this process.
|
* Obtém o modelo de dados da interseção.
|
||||||
* Useful for testing and monitoring.
|
*
|
||||||
*
|
* @return O objeto Intersection.
|
||||||
* @return The Intersection object.
|
|
||||||
*/
|
*/
|
||||||
public Intersection getIntersection() {
|
public Intersection getIntersection() {
|
||||||
return intersection;
|
return intersection;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Records that a vehicle has arrived at this intersection.
|
* Regista a chegada de um novo veículo para fins estatísticos.
|
||||||
*/
|
*/
|
||||||
public void recordVehicleArrival() {
|
public void recordVehicleArrival() {
|
||||||
totalArrivals++;
|
totalArrivals++;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Records that a vehicle has departed from this intersection.
|
* Regista a partida de um veículo para fins estatísticos.
|
||||||
*/
|
*/
|
||||||
public void recordVehicleDeparture() {
|
public void recordVehicleDeparture() {
|
||||||
totalDepartures++;
|
totalDepartures++;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Sends current statistics to the dashboard server.
|
* Envia um "snapshot" do estado atual para o Dashboard (Telemetria Push).
|
||||||
|
* <p>
|
||||||
|
* Inclui o número acumulado de chegadas, partidas e o tamanho atual das filas.
|
||||||
*/
|
*/
|
||||||
private void sendStatsToDashboard() {
|
private void sendStatsToDashboard() {
|
||||||
if (dashboardClient == null || !dashboardClient.isConnected()) {
|
if (dashboardClient == null || !dashboardClient.isConnected()) {
|
||||||
@@ -1000,7 +1043,6 @@ public class IntersectionProcess {
|
|||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// Calculate current queue size
|
|
||||||
int currentQueueSize = intersection.getTrafficLights().stream()
|
int currentQueueSize = intersection.getTrafficLights().stream()
|
||||||
.mapToInt(TrafficLight::getQueueSize)
|
.mapToInt(TrafficLight::getQueueSize)
|
||||||
.sum();
|
.sum();
|
||||||
@@ -1010,7 +1052,6 @@ public class IntersectionProcess {
|
|||||||
.setIntersectionDepartures(totalDepartures)
|
.setIntersectionDepartures(totalDepartures)
|
||||||
.setIntersectionQueueSize(currentQueueSize);
|
.setIntersectionQueueSize(currentQueueSize);
|
||||||
|
|
||||||
// Send StatsUpdatePayload directly as the message payload
|
|
||||||
sd.model.Message message = new sd.model.Message(
|
sd.model.Message message = new sd.model.Message(
|
||||||
MessageType.STATS_UPDATE,
|
MessageType.STATS_UPDATE,
|
||||||
intersectionId,
|
intersectionId,
|
||||||
@@ -1026,4 +1067,4 @@ public class IntersectionProcess {
|
|||||||
System.err.println("[" + intersectionId + "] Failed to send stats to dashboard: " + e.getMessage());
|
System.err.println("[" + intersectionId + "] Failed to send stats to dashboard: " + e.getMessage());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -3,6 +3,7 @@ package sd.coordinator;
|
|||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.util.HashMap;
|
import java.util.HashMap;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
import java.util.concurrent.locks.LockSupport;
|
||||||
|
|
||||||
import sd.config.SimulationConfig;
|
import sd.config.SimulationConfig;
|
||||||
import sd.dashboard.DashboardStatistics;
|
import sd.dashboard.DashboardStatistics;
|
||||||
@@ -375,6 +376,7 @@ public class CoordinatorProcess {
|
|||||||
|
|
||||||
String entryIntersection = vehicle.getRoute().get(0);
|
String entryIntersection = vehicle.getRoute().get(0);
|
||||||
sendVehicleToIntersection(vehicle, entryIntersection);
|
sendVehicleToIntersection(vehicle, entryIntersection);
|
||||||
|
LockSupport.parkNanos(100000); // 100us
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -50,10 +50,11 @@ public class ConfigurationDialog {
|
|||||||
// Criar painel de configuração
|
// Criar painel de configuração
|
||||||
VBox content = new VBox(15);
|
VBox content = new VBox(15);
|
||||||
content.setPadding(new Insets(20));
|
content.setPadding(new Insets(20));
|
||||||
|
content.setStyle("-fx-background-color: #2b2b2b;");
|
||||||
|
|
||||||
// Seção 1: Parâmetros de Chegada
|
// Seção 1: Parâmetros de Chegada
|
||||||
Label arrivalHeader = new Label("Parâmetros de Chegada de Veículos");
|
Label arrivalHeader = new Label("Parâmetros de Chegada de Veículos");
|
||||||
arrivalHeader.setStyle("-fx-font-weight: bold; -fx-font-size: 14px;");
|
arrivalHeader.setStyle("-fx-font-weight: bold; -fx-font-size: 14px; -fx-text-fill: white;");
|
||||||
|
|
||||||
GridPane arrivalGrid = new GridPane();
|
GridPane arrivalGrid = new GridPane();
|
||||||
arrivalGrid.setHgap(10);
|
arrivalGrid.setHgap(10);
|
||||||
@@ -62,6 +63,7 @@ public class ConfigurationDialog {
|
|||||||
|
|
||||||
// Modelo de chegada
|
// Modelo de chegada
|
||||||
Label modelLabel = new Label("Modelo de chegada:");
|
Label modelLabel = new Label("Modelo de chegada:");
|
||||||
|
modelLabel.setStyle("-fx-text-fill: white;");
|
||||||
ComboBox<String> modelCombo = new ComboBox<>();
|
ComboBox<String> modelCombo = new ComboBox<>();
|
||||||
modelCombo.getItems().addAll("POISSON", "FIXED");
|
modelCombo.getItems().addAll("POISSON", "FIXED");
|
||||||
modelCombo.setValue("POISSON");
|
modelCombo.setValue("POISSON");
|
||||||
@@ -70,6 +72,7 @@ public class ConfigurationDialog {
|
|||||||
|
|
||||||
// Taxa de chegada (λ)
|
// Taxa de chegada (λ)
|
||||||
Label rateLabel = new Label("Taxa de chegada (λ) [veículos/s]:");
|
Label rateLabel = new Label("Taxa de chegada (λ) [veículos/s]:");
|
||||||
|
rateLabel.setStyle("-fx-text-fill: white;");
|
||||||
Spinner<Double> rateSpinner = new Spinner<>(0.1, 2.0, 0.5, 0.1);
|
Spinner<Double> rateSpinner = new Spinner<>(0.1, 2.0, 0.5, 0.1);
|
||||||
rateSpinner.setEditable(true);
|
rateSpinner.setEditable(true);
|
||||||
rateSpinner.setPrefWidth(100);
|
rateSpinner.setPrefWidth(100);
|
||||||
@@ -78,6 +81,7 @@ public class ConfigurationDialog {
|
|||||||
|
|
||||||
// Intervalo fixo (se aplicável)
|
// Intervalo fixo (se aplicável)
|
||||||
Label intervalLabel = new Label("Intervalo fixo [s]:");
|
Label intervalLabel = new Label("Intervalo fixo [s]:");
|
||||||
|
intervalLabel.setStyle("-fx-text-fill: white;");
|
||||||
Spinner<Double> intervalSpinner = new Spinner<>(0.5, 10.0, 2.0, 0.5);
|
Spinner<Double> intervalSpinner = new Spinner<>(0.5, 10.0, 2.0, 0.5);
|
||||||
intervalSpinner.setEditable(true);
|
intervalSpinner.setEditable(true);
|
||||||
intervalSpinner.setPrefWidth(100);
|
intervalSpinner.setPrefWidth(100);
|
||||||
@@ -94,7 +98,7 @@ public class ConfigurationDialog {
|
|||||||
|
|
||||||
// Seção 2: Parâmetros de Tempo
|
// Seção 2: Parâmetros de Tempo
|
||||||
Label timeHeader = new Label("Parâmetros de Tempo");
|
Label timeHeader = new Label("Parâmetros de Tempo");
|
||||||
timeHeader.setStyle("-fx-font-weight: bold; -fx-font-size: 14px;");
|
timeHeader.setStyle("-fx-font-weight: bold; -fx-font-size: 14px; -fx-text-fill: white;");
|
||||||
|
|
||||||
GridPane timeGrid = new GridPane();
|
GridPane timeGrid = new GridPane();
|
||||||
timeGrid.setHgap(10);
|
timeGrid.setHgap(10);
|
||||||
@@ -103,6 +107,7 @@ public class ConfigurationDialog {
|
|||||||
|
|
||||||
// Duração da simulação
|
// Duração da simulação
|
||||||
Label durationLabel = new Label("Duração da simulação [s]:");
|
Label durationLabel = new Label("Duração da simulação [s]:");
|
||||||
|
durationLabel.setStyle("-fx-text-fill: white;");
|
||||||
Spinner<Integer> durationSpinner = new Spinner<>(60, 7200, 300, 60);
|
Spinner<Integer> durationSpinner = new Spinner<>(60, 7200, 300, 60);
|
||||||
durationSpinner.setEditable(true);
|
durationSpinner.setEditable(true);
|
||||||
durationSpinner.setPrefWidth(100);
|
durationSpinner.setPrefWidth(100);
|
||||||
@@ -111,6 +116,7 @@ public class ConfigurationDialog {
|
|||||||
|
|
||||||
// Escala temporal (para visualização)
|
// Escala temporal (para visualização)
|
||||||
Label scaleLabel = new Label("Escala temporal (0=instantâneo, 1=tempo real):");
|
Label scaleLabel = new Label("Escala temporal (0=instantâneo, 1=tempo real):");
|
||||||
|
scaleLabel.setStyle("-fx-text-fill: white;");
|
||||||
Spinner<Double> scaleSpinner = new Spinner<>(0.0, 1.0, 0.01, 0.01);
|
Spinner<Double> scaleSpinner = new Spinner<>(0.0, 1.0, 0.01, 0.01);
|
||||||
scaleSpinner.setEditable(true);
|
scaleSpinner.setEditable(true);
|
||||||
scaleSpinner.setPrefWidth(100);
|
scaleSpinner.setPrefWidth(100);
|
||||||
@@ -119,6 +125,7 @@ public class ConfigurationDialog {
|
|||||||
|
|
||||||
// Tempo de drenagem
|
// Tempo de drenagem
|
||||||
Label drainLabel = new Label("Tempo de drenagem [s]:");
|
Label drainLabel = new Label("Tempo de drenagem [s]:");
|
||||||
|
drainLabel.setStyle("-fx-text-fill: white;");
|
||||||
Spinner<Integer> drainSpinner = new Spinner<>(0, 300, 60, 10);
|
Spinner<Integer> drainSpinner = new Spinner<>(0, 300, 60, 10);
|
||||||
drainSpinner.setEditable(true);
|
drainSpinner.setEditable(true);
|
||||||
drainSpinner.setPrefWidth(100);
|
drainSpinner.setPrefWidth(100);
|
||||||
@@ -127,7 +134,7 @@ public class ConfigurationDialog {
|
|||||||
|
|
||||||
// Seção 3: Distribuição de Tipos de Veículos
|
// Seção 3: Distribuição de Tipos de Veículos
|
||||||
Label vehicleHeader = new Label("Distribuição de Tipos de Veículos");
|
Label vehicleHeader = new Label("Distribuição de Tipos de Veículos");
|
||||||
vehicleHeader.setStyle("-fx-font-weight: bold; -fx-font-size: 14px;");
|
vehicleHeader.setStyle("-fx-font-weight: bold; -fx-font-size: 14px; -fx-text-fill: white;");
|
||||||
|
|
||||||
GridPane vehicleGrid = new GridPane();
|
GridPane vehicleGrid = new GridPane();
|
||||||
vehicleGrid.setHgap(10);
|
vehicleGrid.setHgap(10);
|
||||||
@@ -135,6 +142,7 @@ public class ConfigurationDialog {
|
|||||||
vehicleGrid.setPadding(new Insets(10));
|
vehicleGrid.setPadding(new Insets(10));
|
||||||
|
|
||||||
Label bikeLabel = new Label("Bicicletas/Motos [%]:");
|
Label bikeLabel = new Label("Bicicletas/Motos [%]:");
|
||||||
|
bikeLabel.setStyle("-fx-text-fill: white;");
|
||||||
Spinner<Integer> bikeSpinner = new Spinner<>(0, 100, 10, 5);
|
Spinner<Integer> bikeSpinner = new Spinner<>(0, 100, 10, 5);
|
||||||
bikeSpinner.setEditable(true);
|
bikeSpinner.setEditable(true);
|
||||||
bikeSpinner.setPrefWidth(100);
|
bikeSpinner.setPrefWidth(100);
|
||||||
@@ -142,6 +150,7 @@ public class ConfigurationDialog {
|
|||||||
vehicleGrid.add(bikeSpinner, 1, 0);
|
vehicleGrid.add(bikeSpinner, 1, 0);
|
||||||
|
|
||||||
Label lightLabel = new Label("Veículos Ligeiros [%]:");
|
Label lightLabel = new Label("Veículos Ligeiros [%]:");
|
||||||
|
lightLabel.setStyle("-fx-text-fill: white;");
|
||||||
Spinner<Integer> lightSpinner = new Spinner<>(0, 100, 70, 5);
|
Spinner<Integer> lightSpinner = new Spinner<>(0, 100, 70, 5);
|
||||||
lightSpinner.setEditable(true);
|
lightSpinner.setEditable(true);
|
||||||
lightSpinner.setPrefWidth(100);
|
lightSpinner.setPrefWidth(100);
|
||||||
@@ -149,6 +158,7 @@ public class ConfigurationDialog {
|
|||||||
vehicleGrid.add(lightSpinner, 1, 1);
|
vehicleGrid.add(lightSpinner, 1, 1);
|
||||||
|
|
||||||
Label heavyLabel = new Label("Veículos Pesados [%]:");
|
Label heavyLabel = new Label("Veículos Pesados [%]:");
|
||||||
|
heavyLabel.setStyle("-fx-text-fill: white;");
|
||||||
Spinner<Integer> heavySpinner = new Spinner<>(0, 100, 20, 5);
|
Spinner<Integer> heavySpinner = new Spinner<>(0, 100, 20, 5);
|
||||||
heavySpinner.setEditable(true);
|
heavySpinner.setEditable(true);
|
||||||
heavySpinner.setPrefWidth(100);
|
heavySpinner.setPrefWidth(100);
|
||||||
@@ -159,7 +169,7 @@ public class ConfigurationDialog {
|
|||||||
Label noteLabel = new Label("Nota: Estes parâmetros sobrepõem os valores do ficheiro .properties selecionado.\n" +
|
Label noteLabel = new Label("Nota: Estes parâmetros sobrepõem os valores do ficheiro .properties selecionado.\n" +
|
||||||
"Para usar os valores padrão do ficheiro, deixe em branco ou cancele.");
|
"Para usar os valores padrão do ficheiro, deixe em branco ou cancele.");
|
||||||
noteLabel.setWrapText(true);
|
noteLabel.setWrapText(true);
|
||||||
noteLabel.setStyle("-fx-font-size: 11px; -fx-text-fill: #666666;");
|
noteLabel.setStyle("-fx-font-size: 11px; -fx-text-fill: #aaaaaa;");
|
||||||
|
|
||||||
// Adicionar tudo ao conteúdo
|
// Adicionar tudo ao conteúdo
|
||||||
content.getChildren().addAll(
|
content.getChildren().addAll(
|
||||||
|
|||||||
@@ -30,8 +30,22 @@ import sd.config.SimulationConfig;
|
|||||||
import sd.model.VehicleType;
|
import sd.model.VehicleType;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* JavaFX-based Dashboard UI for displaying real-time simulation statistics.
|
* Interface Gráfica (GUI) baseada em JavaFX para visualização de telemetria em tempo real.
|
||||||
* Provides a graphical interface with auto-updating statistics panels.
|
* <p>
|
||||||
|
* Esta classe atua como a camada de apresentação (View) do sistema. Implementa o padrão
|
||||||
|
* <i>Observer</i> (via polling) para refletir o estado do modelo {@link DashboardStatistics}
|
||||||
|
* nos componentes visuais.
|
||||||
|
* <p>
|
||||||
|
* <b>Aspetos Técnicos Relevantes:</b>
|
||||||
|
* <ul>
|
||||||
|
* <li><b>Concorrência de UI:</b> Utiliza um {@link ScheduledExecutorService} para buscar dados
|
||||||
|
* em background e {@link Platform#runLater(Runnable)} para injetar atualizações na
|
||||||
|
* <i>JavaFX Application Thread</i>, evitando exceções de "Not on FX application thread".</li>
|
||||||
|
* <li><b>Data Binding:</b> Utiliza {@link TableView} com classes internas (DTOs) para
|
||||||
|
* renderização tabular eficiente de tipos de veículos e interseções.</li>
|
||||||
|
* <li><b>Controlo de Processos:</b> Integra com {@link SimulationProcessManager} para orquestrar
|
||||||
|
* o ciclo de vida (spawn/kill) dos processos externos da simulação.</li>
|
||||||
|
* </ul>
|
||||||
*/
|
*/
|
||||||
public class DashboardUI extends Application {
|
public class DashboardUI extends Application {
|
||||||
|
|
||||||
@@ -52,7 +66,7 @@ public class DashboardUI extends Application {
|
|||||||
// Intersection Table
|
// Intersection Table
|
||||||
private TableView<IntersectionRow> intersectionTable;
|
private TableView<IntersectionRow> intersectionTable;
|
||||||
|
|
||||||
// Update scheduler
|
// Update scheduler (Background Thread)
|
||||||
private ScheduledExecutorService updateScheduler;
|
private ScheduledExecutorService updateScheduler;
|
||||||
|
|
||||||
// Configuration controls
|
// Configuration controls
|
||||||
@@ -60,6 +74,10 @@ public class DashboardUI extends Application {
|
|||||||
private String selectedConfigFile = "simulation.properties";
|
private String selectedConfigFile = "simulation.properties";
|
||||||
private Label configInfoLabel;
|
private Label configInfoLabel;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Ponto de entrada da aplicação JavaFX.
|
||||||
|
* Configura o Stage primário, inicializa o servidor de backend e constrói a árvore de cena (Scene Graph).
|
||||||
|
*/
|
||||||
@Override
|
@Override
|
||||||
public void start(Stage primaryStage) {
|
public void start(Stage primaryStage) {
|
||||||
try {
|
try {
|
||||||
@@ -72,29 +90,28 @@ public class DashboardUI extends Application {
|
|||||||
server = new DashboardServer(config);
|
server = new DashboardServer(config);
|
||||||
statistics = server.getStatistics();
|
statistics = server.getStatistics();
|
||||||
|
|
||||||
// Start the dashboard server
|
// Start the dashboard server (Backend listening port)
|
||||||
server.start();
|
server.start();
|
||||||
|
|
||||||
// Build UI
|
// Build UI Layout
|
||||||
BorderPane root = new BorderPane();
|
BorderPane root = new BorderPane();
|
||||||
root.getStyleClass().add("root");
|
root.getStyleClass().add("root");
|
||||||
|
root.setStyle("-fx-background-color: #2b2b2b;");
|
||||||
|
|
||||||
// Header
|
// Header (Top)
|
||||||
VBox header = createHeader();
|
VBox header = createHeader();
|
||||||
root.setTop(header);
|
root.setTop(header);
|
||||||
|
|
||||||
// Main content
|
// Main content (Center)
|
||||||
VBox mainContent = createMainContent();
|
VBox mainContent = createMainContent();
|
||||||
root.setCenter(mainContent);
|
root.setCenter(mainContent);
|
||||||
|
|
||||||
// Footer
|
// Footer (Bottom)
|
||||||
HBox footer = createFooter();
|
HBox footer = createFooter();
|
||||||
root.setBottom(footer);
|
root.setBottom(footer);
|
||||||
|
|
||||||
// Create scene
|
// Create scene & apply CSS
|
||||||
Scene scene = new Scene(root, 1200, 850);
|
Scene scene = new Scene(root, 1200, 850);
|
||||||
|
|
||||||
// Load CSS
|
|
||||||
String cssUrl = getClass().getResource("/dashboard.css").toExternalForm();
|
String cssUrl = getClass().getResource("/dashboard.css").toExternalForm();
|
||||||
scene.getStylesheets().add(cssUrl);
|
scene.getStylesheets().add(cssUrl);
|
||||||
|
|
||||||
@@ -102,10 +119,10 @@ public class DashboardUI extends Application {
|
|||||||
primaryStage.setScene(scene);
|
primaryStage.setScene(scene);
|
||||||
primaryStage.show();
|
primaryStage.show();
|
||||||
|
|
||||||
// Start periodic updates
|
// Start periodic updates loop
|
||||||
startPeriodicUpdates();
|
startPeriodicUpdates();
|
||||||
|
|
||||||
// Handle window close
|
// Handle window close (Graceful shutdown)
|
||||||
primaryStage.setOnCloseRequest(event -> {
|
primaryStage.setOnCloseRequest(event -> {
|
||||||
shutdown();
|
shutdown();
|
||||||
});
|
});
|
||||||
@@ -149,6 +166,8 @@ public class DashboardUI extends Application {
|
|||||||
// Passar o ficheiro de configuração selecionado
|
// Passar o ficheiro de configuração selecionado
|
||||||
processManager.setConfigFile(selectedConfigFile);
|
processManager.setConfigFile(selectedConfigFile);
|
||||||
processManager.startSimulation();
|
processManager.startSimulation();
|
||||||
|
|
||||||
|
// Toggle UI state
|
||||||
btnStart.setDisable(true);
|
btnStart.setDisable(true);
|
||||||
btnStop.setDisable(false);
|
btnStop.setDisable(false);
|
||||||
configFileSelector.setDisable(true); // Bloquear mudanças durante simulação
|
configFileSelector.setDisable(true); // Bloquear mudanças durante simulação
|
||||||
@@ -159,6 +178,8 @@ public class DashboardUI extends Application {
|
|||||||
|
|
||||||
btnStop.setOnAction(e -> {
|
btnStop.setOnAction(e -> {
|
||||||
processManager.stopSimulation();
|
processManager.stopSimulation();
|
||||||
|
|
||||||
|
// Toggle UI state
|
||||||
btnStart.setDisable(false);
|
btnStart.setDisable(false);
|
||||||
btnStop.setDisable(true);
|
btnStop.setDisable(true);
|
||||||
configFileSelector.setDisable(false); // Desbloquear para nova simulação
|
configFileSelector.setDisable(false); // Desbloquear para nova simulação
|
||||||
@@ -435,13 +456,23 @@ public class DashboardUI extends Application {
|
|||||||
grid.add(container, colGroup, row);
|
grid.add(container, colGroup, row);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Inicia o ciclo de polling em background.
|
||||||
|
* Atualiza a UI a cada 100ms.
|
||||||
|
*/
|
||||||
private void startPeriodicUpdates() {
|
private void startPeriodicUpdates() {
|
||||||
updateScheduler = Executors.newSingleThreadScheduledExecutor();
|
updateScheduler = Executors.newSingleThreadScheduledExecutor();
|
||||||
updateScheduler.scheduleAtFixedRate(() -> {
|
updateScheduler.scheduleAtFixedRate(() -> {
|
||||||
|
// Crucial: Encapsular atualização de UI em Platform.runLater
|
||||||
|
// para garantir execução na JavaFX Application Thread
|
||||||
Platform.runLater(this::updateUI);
|
Platform.runLater(this::updateUI);
|
||||||
}, 0, 100, TimeUnit.MILLISECONDS);
|
}, 0, 100, TimeUnit.MILLISECONDS);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sincroniza o estado atual do objeto Statistics com os controlos JavaFX.
|
||||||
|
* Chamado periodicamente pela thread de UI.
|
||||||
|
*/
|
||||||
private void updateUI() {
|
private void updateUI() {
|
||||||
// Update global statistics
|
// Update global statistics
|
||||||
lblVehiclesGenerated.setText(String.valueOf(statistics.getTotalVehiclesGenerated()));
|
lblVehiclesGenerated.setText(String.valueOf(statistics.getTotalVehiclesGenerated()));
|
||||||
@@ -548,7 +579,9 @@ public class DashboardUI extends Application {
|
|||||||
launch(args);
|
launch(args);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Inner classes for TableView data models
|
// --- DTOs para Data Binding nas Tabelas ---
|
||||||
|
|
||||||
|
/** DTO para linhas da tabela de Tipos de Veículo. */
|
||||||
public static class VehicleTypeRow {
|
public static class VehicleTypeRow {
|
||||||
private final String vehicleType;
|
private final String vehicleType;
|
||||||
private final int count;
|
private final int count;
|
||||||
@@ -560,19 +593,12 @@ public class DashboardUI extends Application {
|
|||||||
this.avgWaitTime = avgWaitTime;
|
this.avgWaitTime = avgWaitTime;
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getVehicleType() {
|
public String getVehicleType() { return vehicleType; }
|
||||||
return vehicleType;
|
public int getCount() { return count; }
|
||||||
}
|
public String getAvgWaitTime() { return avgWaitTime; }
|
||||||
|
|
||||||
public int getCount() {
|
|
||||||
return count;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getAvgWaitTime() {
|
|
||||||
return avgWaitTime;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** DTO para linhas da tabela de Interseções. */
|
||||||
public static class IntersectionRow {
|
public static class IntersectionRow {
|
||||||
private final String intersectionId;
|
private final String intersectionId;
|
||||||
private final int arrivals;
|
private final int arrivals;
|
||||||
@@ -586,20 +612,9 @@ public class DashboardUI extends Application {
|
|||||||
this.queueSize = queueSize;
|
this.queueSize = queueSize;
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getIntersectionId() {
|
public String getIntersectionId() { return intersectionId; }
|
||||||
return intersectionId;
|
public int getArrivals() { return arrivals; }
|
||||||
}
|
public int getDepartures() { return departures; }
|
||||||
|
public int getQueueSize() { return queueSize; }
|
||||||
public int getArrivals() {
|
|
||||||
return arrivals;
|
|
||||||
}
|
|
||||||
|
|
||||||
public int getDepartures() {
|
|
||||||
return departures;
|
|
||||||
}
|
|
||||||
|
|
||||||
public int getQueueSize() {
|
|
||||||
return queueSize;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -6,9 +6,17 @@ import java.util.ArrayList;
|
|||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Gere o ciclo de vida dos processos de simulação (Intersections, Exit Node,
|
* Orquestrador de processos para o ambiente de simulação distribuída.
|
||||||
* Coordinator).
|
* <p>
|
||||||
* Permite iniciar e parar a simulação distribuída dentro da aplicação Java.
|
* Esta classe atua como um supervisor (Process Manager), responsável pelo <i>bootstrapping</i>
|
||||||
|
* e <i>teardown</i> das múltiplas Java Virtual Machines (JVMs) que compõem o sistema.
|
||||||
|
* <p>
|
||||||
|
* Funcionalidades principais:
|
||||||
|
* <ul>
|
||||||
|
* <li><b>Isolamento:</b> Cada nó (Interseção, Coordinator, ExitNode) corre no seu próprio processo OS.</li>
|
||||||
|
* <li><b>Ordem de Arranque:</b> Garante que os servidores (Interseções) estão online antes dos clientes (Coordenador).</li>
|
||||||
|
* <li><b>Gestão de Logs:</b> Redireciona stdout/stderr de cada processo filho para ficheiros temporários para facilitar o debug.</li>
|
||||||
|
* </ul>
|
||||||
*/
|
*/
|
||||||
public class SimulationProcessManager {
|
public class SimulationProcessManager {
|
||||||
|
|
||||||
@@ -16,6 +24,10 @@ public class SimulationProcessManager {
|
|||||||
private final String classpath;
|
private final String classpath;
|
||||||
private String configFile;
|
private String configFile;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Inicializa o gestor capturando o classpath da JVM atual.
|
||||||
|
* Isto garante que os processos filhos herdam as mesmas dependências e configurações de ambiente.
|
||||||
|
*/
|
||||||
public SimulationProcessManager() {
|
public SimulationProcessManager() {
|
||||||
this.runningProcesses = new ArrayList<>();
|
this.runningProcesses = new ArrayList<>();
|
||||||
this.classpath = System.getProperty("java.class.path");
|
this.classpath = System.getProperty("java.class.path");
|
||||||
@@ -23,9 +35,9 @@ public class SimulationProcessManager {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Define o ficheiro de configuração a usar.
|
* Define o perfil de configuração a ser injetado nos processos filhos.
|
||||||
*
|
* Útil para alternar entre cenários (Low/Medium/High Load) dinamicamente.
|
||||||
* @param configFile nome do ficheiro (ex: "simulation-low.properties")
|
* * @param configFile Nome do ficheiro de propriedades (ex: "simulation-low.properties").
|
||||||
*/
|
*/
|
||||||
public void setConfigFile(String configFile) {
|
public void setConfigFile(String configFile) {
|
||||||
this.configFile = "src/main/resources/" + configFile;
|
this.configFile = "src/main/resources/" + configFile;
|
||||||
@@ -33,9 +45,16 @@ public class SimulationProcessManager {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Inicia a simulação completa: 5 Intersections, 1 Exit Node, e 1 Coordinator.
|
* Executa o procedimento de arranque (Bootstrap) da simulação distribuída.
|
||||||
*
|
* <p>
|
||||||
* @throws IOException se um processo falhar ao iniciar
|
* A ordem de inicialização é crítica para evitar <i>Race Conditions</i> na conexão TCP:
|
||||||
|
* <ol>
|
||||||
|
* <li><b>Workers (Interseções):</b> Iniciam os ServerSockets.</li>
|
||||||
|
* <li><b>Sink (Exit Node):</b> Prepara-se para receber métricas finais.</li>
|
||||||
|
* <li><b>Delay de Estabilização:</b> Pausa de 1s para garantir que os sockets estão em LISTENING.</li>
|
||||||
|
* <li><b>Source (Coordinator):</b> Inicia a geração de carga e conecta-se aos nós.</li>
|
||||||
|
* </ol>
|
||||||
|
* * @throws IOException Se falhar o fork de algum processo.
|
||||||
*/
|
*/
|
||||||
public void startSimulation() throws IOException {
|
public void startSimulation() throws IOException {
|
||||||
if (!runningProcesses.isEmpty()) {
|
if (!runningProcesses.isEmpty()) {
|
||||||
@@ -65,8 +84,11 @@ public class SimulationProcessManager {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Checks if the coordinator process (last process started) is still running.
|
* Verifica o estado de "liveness" da simulação monitorizando o processo Coordenador.
|
||||||
* When the coordinator finishes, the simulation is complete.
|
* <p>
|
||||||
|
* Como o Coordenador gere o relógio DES e a geração de eventos, a sua terminação
|
||||||
|
* (após o drain time) sinaliza o fim efetivo da simulação.
|
||||||
|
* * @return true se o Coordenador ainda estiver ativo (alive).
|
||||||
*/
|
*/
|
||||||
public boolean isSimulationRunning() {
|
public boolean isSimulationRunning() {
|
||||||
if (runningProcesses.isEmpty()) {
|
if (runningProcesses.isEmpty()) {
|
||||||
@@ -78,8 +100,10 @@ public class SimulationProcessManager {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Waits for the simulation to complete naturally.
|
* Bloqueia a thread atual até que a simulação termine naturalmente ou ocorra timeout.
|
||||||
* Returns true if completed, false if timeout.
|
* * @param timeoutSeconds Tempo máximo de espera.
|
||||||
|
* @return true se terminou, false se o timeout expirou.
|
||||||
|
* @throws InterruptedException Se a espera for interrompida.
|
||||||
*/
|
*/
|
||||||
public boolean waitForCompletion(long timeoutSeconds) throws InterruptedException {
|
public boolean waitForCompletion(long timeoutSeconds) throws InterruptedException {
|
||||||
if (runningProcesses.isEmpty()) {
|
if (runningProcesses.isEmpty()) {
|
||||||
@@ -91,7 +115,11 @@ public class SimulationProcessManager {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Stops all running simulation processes.
|
* Executa o procedimento de encerramento (Teardown) de todos os processos.
|
||||||
|
* <p>
|
||||||
|
* Tenta primeiro uma paragem graciosa (`SIGTERM`), aguarda meio segundo, e
|
||||||
|
* força a paragem (`SIGKILL`) para processos persistentes, garantindo que não
|
||||||
|
* ficam processos órfãos no SO.
|
||||||
*/
|
*/
|
||||||
public void stopSimulation() {
|
public void stopSimulation() {
|
||||||
System.out.println("Stopping simulation processes...");
|
System.out.println("Stopping simulation processes...");
|
||||||
@@ -120,7 +148,8 @@ public class SimulationProcessManager {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Helper para iniciar um único processo Java.
|
* Helper de baixo nível para construção e lançamento de processos Java.
|
||||||
|
* Configura o redirecionamento de I/O para ficheiros de log na diretoria temporária do SO.
|
||||||
*/
|
*/
|
||||||
private void startProcess(String className, String arg) throws IOException {
|
private void startProcess(String className, String arg) throws IOException {
|
||||||
String javaBin = System.getProperty("java.home") + File.separator + "bin" + File.separator + "java";
|
String javaBin = System.getProperty("java.home") + File.separator + "bin" + File.separator + "java";
|
||||||
@@ -152,4 +181,4 @@ public class SimulationProcessManager {
|
|||||||
// print where the logs are actually going
|
// print where the logs are actually going
|
||||||
System.out.println("Logs redirected to: " + logFile.getAbsolutePath());
|
System.out.println("Logs redirected to: " + logFile.getAbsolutePath());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -4,7 +4,14 @@ import sd.model.MessageType;
|
|||||||
import sd.protocol.MessageProtocol;
|
import sd.protocol.MessageProtocol;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Message wrapper for sending statistics to the dashboard.
|
* Implementação concreta do protocolo de mensagens destinada ao transporte de telemetria.
|
||||||
|
* <p>
|
||||||
|
* Esta classe atua como um envelope especializado para o envio de dados estatísticos
|
||||||
|
* (encapsulados em {@link StatsUpdatePayload}) dos nós operacionais (Interseções, Coordenador)
|
||||||
|
* para o servidor de Dashboard centralizado.
|
||||||
|
* <p>
|
||||||
|
* Diferencia-se das mensagens de controlo genéricas por ter o destino fixado no
|
||||||
|
* "DashboardServer" e um tipo de mensagem imutável ({@code STATS_UPDATE}).
|
||||||
*/
|
*/
|
||||||
public class StatsMessage implements MessageProtocol {
|
public class StatsMessage implements MessageProtocol {
|
||||||
|
|
||||||
@@ -14,27 +21,49 @@ public class StatsMessage implements MessageProtocol {
|
|||||||
private final String destinationNode;
|
private final String destinationNode;
|
||||||
private final StatsUpdatePayload payload;
|
private final StatsUpdatePayload payload;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Cria uma nova mensagem de estatística.
|
||||||
|
*
|
||||||
|
* @param sourceNode O ID do nó que gerou as estatísticas (ex: "Cr1", "ExitNode").
|
||||||
|
* @param payload O objeto DTO contendo os dados estatísticos brutos ou agregados.
|
||||||
|
*/
|
||||||
public StatsMessage(String sourceNode, StatsUpdatePayload payload) {
|
public StatsMessage(String sourceNode, StatsUpdatePayload payload) {
|
||||||
this.sourceNode = sourceNode;
|
this.sourceNode = sourceNode;
|
||||||
this.destinationNode = "DashboardServer";
|
this.destinationNode = "DashboardServer"; // Destino implícito e fixo
|
||||||
this.payload = payload;
|
this.payload = payload;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Retorna o tipo da mensagem, que identifica semanticamente o conteúdo para o recetor.
|
||||||
|
* @return Sempre {@link MessageType#STATS_UPDATE}.
|
||||||
|
*/
|
||||||
@Override
|
@Override
|
||||||
public MessageType getType() {
|
public MessageType getType() {
|
||||||
return MessageType.STATS_UPDATE;
|
return MessageType.STATS_UPDATE;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Obtém a carga útil da mensagem.
|
||||||
|
* @return O objeto {@link StatsUpdatePayload} associado.
|
||||||
|
*/
|
||||||
@Override
|
@Override
|
||||||
public Object getPayload() {
|
public Object getPayload() {
|
||||||
return payload;
|
return payload;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Identifica a origem da mensagem.
|
||||||
|
* @return O ID do nó remetente.
|
||||||
|
*/
|
||||||
@Override
|
@Override
|
||||||
public String getSourceNode() {
|
public String getSourceNode() {
|
||||||
return sourceNode;
|
return sourceNode;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Identifica o destino da mensagem.
|
||||||
|
* @return Sempre "DashboardServer".
|
||||||
|
*/
|
||||||
@Override
|
@Override
|
||||||
public String getDestinationNode() {
|
public String getDestinationNode() {
|
||||||
return destinationNode;
|
return destinationNode;
|
||||||
@@ -45,4 +74,4 @@ public class StatsMessage implements MessageProtocol {
|
|||||||
return String.format("StatsMessage[from=%s, to=%s, payload=%s]",
|
return String.format("StatsMessage[from=%s, to=%s, payload=%s]",
|
||||||
sourceNode, destinationNode, payload);
|
sourceNode, destinationNode, payload);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -7,25 +7,60 @@ import java.util.Map;
|
|||||||
import sd.model.VehicleType;
|
import sd.model.VehicleType;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* DTO para atualizações de estatísticas ao dashboard.
|
* Objeto de Transferência de Dados (DTO) otimizado para transporte de telemetria.
|
||||||
* Campos com valor -1 não são atualizados nesta mensagem.
|
* <p>
|
||||||
|
* Esta classe encapsula as métricas de desempenho enviadas pelos nós da simulação (Coordenador,
|
||||||
|
* Interseções, ExitNode) para o Dashboard. Foi desenhada para suportar <b>atualizações parciais</b>
|
||||||
|
* (Sparse Updates):
|
||||||
|
* <ul>
|
||||||
|
* <li>Campos globais inicializados com {@code -1} indicam "sem alteração" (no-op). O Dashboard
|
||||||
|
* deve ignorar estes campos e manter o valor acumulado anterior.</li>
|
||||||
|
* <li>Campos de interseção ({@code arrivals}, {@code departures}) representam deltas ou snapshots
|
||||||
|
* específicos do nó remetente.</li>
|
||||||
|
* </ul>
|
||||||
|
* Implementa {@link Serializable} para transmissão direta via Java Sockets.
|
||||||
|
*
|
||||||
|
|
||||||
|
[Image of data transfer object pattern]
|
||||||
|
|
||||||
*/
|
*/
|
||||||
public class StatsUpdatePayload implements Serializable {
|
public class StatsUpdatePayload implements Serializable {
|
||||||
|
|
||||||
private static final long serialVersionUID = 1L;
|
private static final long serialVersionUID = 1L;
|
||||||
|
|
||||||
|
// Global Metrics (Coordinator/ExitNode)
|
||||||
|
/** Total gerado. Valor -1 indica que este campo deve ser ignorado na atualização. */
|
||||||
private int totalVehiclesGenerated = -1;
|
private int totalVehiclesGenerated = -1;
|
||||||
|
|
||||||
|
/** Total completado. Valor -1 indica que este campo deve ser ignorado. */
|
||||||
private int totalVehiclesCompleted = -1;
|
private int totalVehiclesCompleted = -1;
|
||||||
|
|
||||||
|
/** Tempo total de sistema acumulado (ms). Valor -1 indica que deve ser ignorado. */
|
||||||
private long totalSystemTime = -1;
|
private long totalSystemTime = -1;
|
||||||
|
|
||||||
|
/** Tempo total de espera acumulado (ms). Valor -1 indica que deve ser ignorado. */
|
||||||
private long totalWaitingTime = -1;
|
private long totalWaitingTime = -1;
|
||||||
|
|
||||||
|
// Intersection Metrics (Worker Nodes)
|
||||||
|
/** Número de veículos que entraram na interseção desde o último reporte. */
|
||||||
private int intersectionArrivals = 0;
|
private int intersectionArrivals = 0;
|
||||||
|
|
||||||
|
/** Número de veículos que saíram da interseção desde o último reporte. */
|
||||||
private int intersectionDepartures = 0;
|
private int intersectionDepartures = 0;
|
||||||
|
|
||||||
|
/** Snapshot do tamanho atual da fila na interseção. */
|
||||||
private int intersectionQueueSize = 0;
|
private int intersectionQueueSize = 0;
|
||||||
|
|
||||||
|
// Detailed Breakdowns
|
||||||
|
/** Contagem acumulada por tipo de veículo. */
|
||||||
private Map<VehicleType, Integer> vehicleTypeCounts;
|
private Map<VehicleType, Integer> vehicleTypeCounts;
|
||||||
|
|
||||||
|
/** Tempos de espera acumulados por tipo de veículo. */
|
||||||
private Map<VehicleType, Long> vehicleTypeWaitTimes;
|
private Map<VehicleType, Long> vehicleTypeWaitTimes;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Inicializa o payload com os mapas vazios e contadores globais a -1 (estado neutro).
|
||||||
|
*/
|
||||||
public StatsUpdatePayload() {
|
public StatsUpdatePayload() {
|
||||||
this.vehicleTypeCounts = new HashMap<>();
|
this.vehicleTypeCounts = new HashMap<>();
|
||||||
this.vehicleTypeWaitTimes = new HashMap<>();
|
this.vehicleTypeWaitTimes = new HashMap<>();
|
||||||
@@ -67,6 +102,8 @@ public class StatsUpdatePayload implements Serializable {
|
|||||||
return vehicleTypeWaitTimes;
|
return vehicleTypeWaitTimes;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Setters implementam Fluent Interface para construção encadeada
|
||||||
|
|
||||||
public StatsUpdatePayload setTotalVehiclesGenerated(int totalVehiclesGenerated) {
|
public StatsUpdatePayload setTotalVehiclesGenerated(int totalVehiclesGenerated) {
|
||||||
this.totalVehiclesGenerated = totalVehiclesGenerated;
|
this.totalVehiclesGenerated = totalVehiclesGenerated;
|
||||||
return this;
|
return this;
|
||||||
@@ -118,4 +155,4 @@ public class StatsUpdatePayload implements Serializable {
|
|||||||
totalVehiclesGenerated, totalVehiclesCompleted, intersectionArrivals,
|
totalVehiclesGenerated, totalVehiclesCompleted, intersectionArrivals,
|
||||||
intersectionDepartures, intersectionQueueSize);
|
intersectionDepartures, intersectionQueueSize);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -3,31 +3,46 @@ package sd.des;
|
|||||||
import java.io.Serializable;
|
import java.io.Serializable;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Evento discreto da simulação.
|
* Representa um evento atómico e imutável no contexto da Simulação de Eventos Discretos (DES).
|
||||||
*
|
* <p>
|
||||||
* <p>Unidade fundamental de execução num sistema DES:
|
* Esta classe é a unidade fundamental de processamento. Numa arquitetura DES, o estado do sistema
|
||||||
|
* não muda continuamente, mas sim em instantes discretos definidos por estes eventos.
|
||||||
|
* <p>
|
||||||
|
* Características principais:
|
||||||
* <ul>
|
* <ul>
|
||||||
* <li>timestamp - quando ocorre
|
* <li><b>Ordenação Temporal:</b> Implementa {@link Comparable} para ser armazenado numa Fila de
|
||||||
* <li>type - o que acontece
|
* Eventos Futuros (FEL - Future Event List), garantindo execução cronológica.</li>
|
||||||
* <li>payload - dados associados
|
* <li><b>Distribuído:</b> Implementa {@link Serializable} para permitir que eventos gerados num nó
|
||||||
* <li>location - qual processo o trata
|
* (ex: Coordenador) sejam transmitidos e executados noutro (ex: Interseção).</li>
|
||||||
|
* <li><b>Polimórfico:</b> Transporta um {@code payload} genérico, permitindo associar qualquer
|
||||||
|
* entidade (Veículo, Sinal, etc.) ao evento.</li>
|
||||||
* </ul>
|
* </ul>
|
||||||
*/
|
*/
|
||||||
public class SimulationEvent implements Comparable<SimulationEvent>, Serializable {
|
public class SimulationEvent implements Comparable<SimulationEvent>, Serializable {
|
||||||
private static final long serialVersionUID = 1L;
|
private static final long serialVersionUID = 1L;
|
||||||
|
|
||||||
|
/** O instante virtual exato em que o evento deve ser processado. */
|
||||||
private final double timestamp;
|
private final double timestamp;
|
||||||
|
|
||||||
|
/** A categoria do evento (ex: VEHICLE_ARRIVAL, LIGHT_CHANGE). */
|
||||||
private final DESEventType type;
|
private final DESEventType type;
|
||||||
|
|
||||||
|
/** Dados contextuais associados (ex: o objeto Vehicle que chegou). */
|
||||||
private final Object payload;
|
private final Object payload;
|
||||||
private final String location; // Process ID (e.g., "Cr1", "Coordinator", "Exit")
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Cria um novo evento de simulação.
|
* O identificador do nó de destino onde o evento deve ser executado.
|
||||||
*
|
* (ex: "Cr1", "Coordinator", "ExitNode"). Se null, é um evento local.
|
||||||
* @param timestamp instante do evento (tempo de simulação em segundos)
|
*/
|
||||||
* @param type tipo de evento
|
private final String location;
|
||||||
* @param payload dados associados (ex: objeto Vehicle)
|
|
||||||
* @param location processo que trata o evento
|
/**
|
||||||
|
* Instancia um novo evento de simulação completo.
|
||||||
|
*
|
||||||
|
* @param timestamp Instante de execução (segundos virtuais).
|
||||||
|
* @param type Tipo enumerado do evento.
|
||||||
|
* @param payload Objeto de dados associado (pode ser null).
|
||||||
|
* @param location ID do processo alvo para execução distribuída.
|
||||||
*/
|
*/
|
||||||
public SimulationEvent(double timestamp, DESEventType type, Object payload, String location) {
|
public SimulationEvent(double timestamp, DESEventType type, Object payload, String location) {
|
||||||
this.timestamp = timestamp;
|
this.timestamp = timestamp;
|
||||||
@@ -36,7 +51,14 @@ public class SimulationEvent implements Comparable<SimulationEvent>, Serializabl
|
|||||||
this.location = location;
|
this.location = location;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Cria evento sem localização (para eventos locais) */
|
/**
|
||||||
|
* Construtor de conveniência para eventos locais (dentro do mesmo processo).
|
||||||
|
* Define {@code location} como null.
|
||||||
|
*
|
||||||
|
* @param timestamp Instante de execução.
|
||||||
|
* @param type Tipo do evento.
|
||||||
|
* @param payload Objeto de dados associado.
|
||||||
|
*/
|
||||||
public SimulationEvent(double timestamp, DESEventType type, Object payload) {
|
public SimulationEvent(double timestamp, DESEventType type, Object payload) {
|
||||||
this(timestamp, type, payload, null);
|
this(timestamp, type, payload, null);
|
||||||
}
|
}
|
||||||
@@ -58,8 +80,18 @@ public class SimulationEvent implements Comparable<SimulationEvent>, Serializabl
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Ordena eventos por timestamp (mais cedo primeiro).
|
* Define a ordem natural de processamento na Fila de Prioridade.
|
||||||
* Em caso de empate, ordena por tipo para determinismo.
|
* <p>
|
||||||
|
* <b>Lógica de Ordenação:</b>
|
||||||
|
* <ol>
|
||||||
|
* <li><b>Primária (Tempo):</b> Eventos com menor timestamp ocorrem primeiro.</li>
|
||||||
|
* <li><b>Secundária (Determinismo):</b> Em caso de empate temporal (simultaneidade),
|
||||||
|
* ordena alfabeticamente pelo nome do tipo. Isto garante que execuções repetidas
|
||||||
|
* da simulação produzam exatamente o mesmo resultado (determinismo estrito).</li>
|
||||||
|
* </ol>
|
||||||
|
*
|
||||||
|
* @param other O outro evento a comparar.
|
||||||
|
* @return Inteiro negativo, zero ou positivo conforme a ordem.
|
||||||
*/
|
*/
|
||||||
@Override
|
@Override
|
||||||
public int compareTo(SimulationEvent other) {
|
public int compareTo(SimulationEvent other) {
|
||||||
@@ -67,7 +99,7 @@ public class SimulationEvent implements Comparable<SimulationEvent>, Serializabl
|
|||||||
if (timeComparison != 0) {
|
if (timeComparison != 0) {
|
||||||
return timeComparison;
|
return timeComparison;
|
||||||
}
|
}
|
||||||
// Tie-breaker: order by event type name
|
// Tie-breaker: order by event type name to ensure reproducible runs
|
||||||
return this.type.name().compareTo(other.type.name());
|
return this.type.name().compareTo(other.type.name());
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -95,4 +127,4 @@ public class SimulationEvent implements Comparable<SimulationEvent>, Serializabl
|
|||||||
result = 31 * result + (location != null ? location.hashCode() : 0);
|
result = 31 * result + (location != null ? location.hashCode() : 0);
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -3,28 +3,47 @@ package sd.des;
|
|||||||
import sd.model.TrafficLight;
|
import sd.model.TrafficLight;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Payload for traffic light change events.
|
* Encapsula o contexto de dados para eventos de mudança de estado de semáforos.
|
||||||
* Contains the traffic light and its direction.
|
* <p>
|
||||||
|
* Este objeto atua como o <i>payload</i> transportado por um {@link SimulationEvent}
|
||||||
|
* quando o tipo de evento é relacionado com controlo de tráfego (ex: mudança Verde -> Amarelo).
|
||||||
|
* Permite que o motor DES identifique exatamente qual instância de {@link TrafficLight}
|
||||||
|
* deve ser atualizada numa determinada interseção e direção.
|
||||||
*/
|
*/
|
||||||
public class TrafficLightEvent {
|
public class TrafficLightEvent {
|
||||||
private final TrafficLight light;
|
private final TrafficLight light;
|
||||||
private final String direction;
|
private final String direction;
|
||||||
private final String intersectionId;
|
private final String intersectionId;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Cria um novo payload de evento de semáforo.
|
||||||
|
* @param light A instância do objeto semáforo a ser manipulado.
|
||||||
|
* @param direction A direção cardeal associada (ex: "North", "East").
|
||||||
|
* @param intersectionId O identificador da interseção onde o semáforo reside.
|
||||||
|
*/
|
||||||
public TrafficLightEvent(TrafficLight light, String direction, String intersectionId) {
|
public TrafficLightEvent(TrafficLight light, String direction, String intersectionId) {
|
||||||
this.light = light;
|
this.light = light;
|
||||||
this.direction = direction;
|
this.direction = direction;
|
||||||
this.intersectionId = intersectionId;
|
this.intersectionId = intersectionId;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return A referência direta para o objeto de domínio do semáforo.
|
||||||
|
*/
|
||||||
public TrafficLight getLight() {
|
public TrafficLight getLight() {
|
||||||
return light;
|
return light;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return A direção do fluxo controlado por este semáforo.
|
||||||
|
*/
|
||||||
public String getDirection() {
|
public String getDirection() {
|
||||||
return direction;
|
return direction;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return O ID da interseção pai.
|
||||||
|
*/
|
||||||
public String getIntersectionId() {
|
public String getIntersectionId() {
|
||||||
return intersectionId;
|
return intersectionId;
|
||||||
}
|
}
|
||||||
@@ -33,4 +52,4 @@ public class TrafficLightEvent {
|
|||||||
public String toString() {
|
public String toString() {
|
||||||
return String.format("TrafficLightEvent[%s-%s]", intersectionId, direction);
|
return String.format("TrafficLightEvent[%s-%s]", intersectionId, direction);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -11,10 +11,19 @@ import java.util.concurrent.LinkedBlockingQueue;
|
|||||||
import java.util.concurrent.atomic.AtomicBoolean;
|
import java.util.concurrent.atomic.AtomicBoolean;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Sistema de registo centralizado de eventos para a simulação distribuída.
|
* Motor de logging assíncrono e thread-safe para a simulação distribuída.
|
||||||
*
|
* <p>
|
||||||
* <p>Regista todos os eventos da simulação num ficheiro com timestamps e categorização.
|
* Implementa o padrão <i>Singleton</i> para garantir um ponto centralizado de registo.
|
||||||
* Thread-safe e não-bloqueante para impacto mínimo na performance.</p>
|
* Utiliza o padrão <i>Producer-Consumer</i> com uma {@link BlockingQueue} para desacoplar
|
||||||
|
* a geração de eventos (crítica para a performance da simulação) da persistência em disco
|
||||||
|
* (operação de I/O lenta).
|
||||||
|
* <p>
|
||||||
|
* <b>Garantias:</b>
|
||||||
|
* <ul>
|
||||||
|
* <li>Non-blocking writes (para a thread chamadora, na maioria dos casos).</li>
|
||||||
|
* <li>Ordering cronológico aproximado (FIFO na fila).</li>
|
||||||
|
* <li>Graceful Shutdown (flush de logs pendentes ao terminar).</li>
|
||||||
|
* </ul>
|
||||||
*/
|
*/
|
||||||
public class EventLogger {
|
public class EventLogger {
|
||||||
|
|
||||||
@@ -22,20 +31,33 @@ public class EventLogger {
|
|||||||
private static final Object instanceLock = new Object();
|
private static final Object instanceLock = new Object();
|
||||||
|
|
||||||
private final PrintWriter writer;
|
private final PrintWriter writer;
|
||||||
|
|
||||||
|
/** Buffer de memória para absorver picos de eventos (Burst traffic). */
|
||||||
private final BlockingQueue<LogEntry> logQueue;
|
private final BlockingQueue<LogEntry> logQueue;
|
||||||
|
|
||||||
|
/** Thread dedicada (Consumer) para escrita em ficheiro. */
|
||||||
private final Thread writerThread;
|
private final Thread writerThread;
|
||||||
|
|
||||||
private final AtomicBoolean running;
|
private final AtomicBoolean running;
|
||||||
private final SimpleDateFormat timestampFormat;
|
private final SimpleDateFormat timestampFormat;
|
||||||
private final long simulationStartMillis;
|
private final long simulationStartMillis;
|
||||||
|
|
||||||
/** Construtor privado para padrão singleton */
|
/**
|
||||||
|
* Inicializa o sistema de logs.
|
||||||
|
* Abre o ficheiro, escreve o cabeçalho e inicia a thread consumidora.
|
||||||
|
*
|
||||||
|
* @param logFilePath Caminho relativo ou absoluto do ficheiro de log.
|
||||||
|
* @throws IOException Se não for possível criar ou escrever no ficheiro.
|
||||||
|
*/
|
||||||
private EventLogger(String logFilePath) throws IOException {
|
private EventLogger(String logFilePath) throws IOException {
|
||||||
|
// Auto-flush ativado para garantir persistência, mas gerido pelo buffer do BufferedWriter
|
||||||
this.writer = new PrintWriter(new BufferedWriter(new FileWriter(logFilePath, false)), true);
|
this.writer = new PrintWriter(new BufferedWriter(new FileWriter(logFilePath, false)), true);
|
||||||
this.logQueue = new LinkedBlockingQueue<>(10000);
|
this.logQueue = new LinkedBlockingQueue<>(10000); // Backpressure: limita a 10k eventos pendentes
|
||||||
this.running = new AtomicBoolean(true);
|
this.running = new AtomicBoolean(true);
|
||||||
this.timestampFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
|
this.timestampFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
|
||||||
this.simulationStartMillis = System.currentTimeMillis();
|
this.simulationStartMillis = System.currentTimeMillis();
|
||||||
|
|
||||||
|
// Header inicial do log
|
||||||
writer.println("=".repeat(80));
|
writer.println("=".repeat(80));
|
||||||
writer.println("SIMULATION EVENT LOG");
|
writer.println("SIMULATION EVENT LOG");
|
||||||
writer.println("Started: " + timestampFormat.format(new Date()));
|
writer.println("Started: " + timestampFormat.format(new Date()));
|
||||||
@@ -47,11 +69,16 @@ public class EventLogger {
|
|||||||
writer.flush();
|
writer.flush();
|
||||||
|
|
||||||
this.writerThread = new Thread(this::processLogQueue, "EventLogger-Writer");
|
this.writerThread = new Thread(this::processLogQueue, "EventLogger-Writer");
|
||||||
this.writerThread.setDaemon(true);
|
this.writerThread.setDaemon(true); // Permite que a JVM termine se apenas esta thread sobrar
|
||||||
this.writerThread.start();
|
this.writerThread.start();
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Obtém ou cria a instância singleton */
|
/**
|
||||||
|
* Obtém a instância única do logger (Lazy Initialization).
|
||||||
|
* Se não existir, cria uma predefinida em "logs/simulation-events.log".
|
||||||
|
*
|
||||||
|
* @return A instância singleton.
|
||||||
|
*/
|
||||||
public static EventLogger getInstance() {
|
public static EventLogger getInstance() {
|
||||||
if (instance == null) {
|
if (instance == null) {
|
||||||
synchronized (instanceLock) {
|
synchronized (instanceLock) {
|
||||||
@@ -72,7 +99,8 @@ public class EventLogger {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Initialize with custom log file path.
|
* Reinicializa o logger com um ficheiro específico.
|
||||||
|
* Útil para testes ou configurações personalizadas.
|
||||||
*/
|
*/
|
||||||
public static void initialize(String logFilePath) throws IOException {
|
public static void initialize(String logFilePath) throws IOException {
|
||||||
synchronized (instanceLock) {
|
synchronized (instanceLock) {
|
||||||
@@ -84,7 +112,13 @@ public class EventLogger {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Logs an event (non-blocking).
|
* Regista um evento genérico.
|
||||||
|
* Esta operação é não-bloqueante (retorna imediatamente após colocar na fila),
|
||||||
|
* exceto se a fila estiver cheia (backpressure).
|
||||||
|
*
|
||||||
|
* @param eventType Categoria do evento.
|
||||||
|
* @param component Nome do componente (ex: "Coordinator", "IntersectionProcess").
|
||||||
|
* @param description Detalhes do evento.
|
||||||
*/
|
*/
|
||||||
public void log(EventType eventType, String component, String description) {
|
public void log(EventType eventType, String component, String description) {
|
||||||
if (!running.get()) return;
|
if (!running.get()) return;
|
||||||
@@ -96,7 +130,7 @@ public class EventLogger {
|
|||||||
description
|
description
|
||||||
);
|
);
|
||||||
|
|
||||||
// Non-blocking offer - if queue is full, drop oldest
|
// Non-blocking offer - if queue is full, drop oldest or warn
|
||||||
if (!logQueue.offer(entry)) {
|
if (!logQueue.offer(entry)) {
|
||||||
// Queue full - this shouldn't happen with 10k buffer, but handle gracefully
|
// Queue full - this shouldn't happen with 10k buffer, but handle gracefully
|
||||||
System.err.println("EventLogger queue full - dropping event: " + eventType);
|
System.err.println("EventLogger queue full - dropping event: " + eventType);
|
||||||
@@ -104,14 +138,14 @@ public class EventLogger {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Logs an event with vehicle context.
|
* Regista um evento associado a um veículo específico (Helper method).
|
||||||
*/
|
*/
|
||||||
public void logVehicle(EventType eventType, String component, String vehicleId, String description) {
|
public void logVehicle(EventType eventType, String component, String vehicleId, String description) {
|
||||||
log(eventType, component, "[" + vehicleId + "] " + description);
|
log(eventType, component, "[" + vehicleId + "] " + description);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Logs an error event.
|
* Regista um erro ou exceção com formatação apropriada.
|
||||||
*/
|
*/
|
||||||
public void logError(String component, String description, Exception e) {
|
public void logError(String component, String description, Exception e) {
|
||||||
String fullDescription = description + (e != null ? ": " + e.getMessage() : "");
|
String fullDescription = description + (e != null ? ": " + e.getMessage() : "");
|
||||||
@@ -119,11 +153,13 @@ public class EventLogger {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Background thread that writes log entries to file.
|
* Lógica da thread consumidora (Worker Thread).
|
||||||
|
* Retira eventos da fila e escreve no disco continuamente.
|
||||||
*/
|
*/
|
||||||
private void processLogQueue() {
|
private void processLogQueue() {
|
||||||
while (running.get() || !logQueue.isEmpty()) {
|
while (running.get() || !logQueue.isEmpty()) {
|
||||||
try {
|
try {
|
||||||
|
// Poll com timeout para permitir verificar a flag 'running' periodicamente
|
||||||
LogEntry entry = logQueue.poll(100, java.util.concurrent.TimeUnit.MILLISECONDS);
|
LogEntry entry = logQueue.poll(100, java.util.concurrent.TimeUnit.MILLISECONDS);
|
||||||
if (entry != null) {
|
if (entry != null) {
|
||||||
writeEntry(entry);
|
writeEntry(entry);
|
||||||
@@ -134,7 +170,7 @@ public class EventLogger {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Flush remaining entries
|
// Flush final: garantir que eventos restantes na fila são escritos antes de morrer
|
||||||
while (!logQueue.isEmpty()) {
|
while (!logQueue.isEmpty()) {
|
||||||
LogEntry entry = logQueue.poll();
|
LogEntry entry = logQueue.poll();
|
||||||
if (entry != null) {
|
if (entry != null) {
|
||||||
@@ -144,7 +180,7 @@ public class EventLogger {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Writes a single log entry to file.
|
* Formata e escreve uma entrada de log no PrintWriter.
|
||||||
*/
|
*/
|
||||||
private void writeEntry(LogEntry entry) {
|
private void writeEntry(LogEntry entry) {
|
||||||
String timestamp = timestampFormat.format(new Date(entry.timestampMillis));
|
String timestamp = timestampFormat.format(new Date(entry.timestampMillis));
|
||||||
@@ -158,7 +194,7 @@ public class EventLogger {
|
|||||||
entry.description
|
entry.description
|
||||||
);
|
);
|
||||||
|
|
||||||
// Flush periodically for real-time viewing
|
// Flush periódico inteligente: se a carga for baixa, garante que vemos logs em tempo real
|
||||||
if (logQueue.size() < 10) {
|
if (logQueue.size() < 10) {
|
||||||
writer.flush();
|
writer.flush();
|
||||||
}
|
}
|
||||||
@@ -170,15 +206,17 @@ public class EventLogger {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Shuts down the logger and flushes all pending entries.
|
* Encerra o logger de forma segura.
|
||||||
|
* Desativa a aceitação de novos eventos, aguarda que a fila esvazie (flush)
|
||||||
|
* e fecha o ficheiro.
|
||||||
*/
|
*/
|
||||||
public void shutdown() {
|
public void shutdown() {
|
||||||
if (!running.compareAndSet(true, false)) {
|
if (!running.compareAndSet(true, false)) {
|
||||||
return; // Already shut down
|
return; // Já encerrado
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// Wait for writer thread to finish
|
// Wait for writer thread to finish flushing
|
||||||
writerThread.join(5000); // Wait up to 5 seconds
|
writerThread.join(5000); // Wait up to 5 seconds
|
||||||
|
|
||||||
// Write footer
|
// Write footer
|
||||||
@@ -195,7 +233,7 @@ public class EventLogger {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Internal class to represent a log entry.
|
* DTO interno imutável para armazenar dados do evento na fila.
|
||||||
*/
|
*/
|
||||||
private static class LogEntry {
|
private static class LogEntry {
|
||||||
final long timestampMillis;
|
final long timestampMillis;
|
||||||
@@ -210,4 +248,4 @@ public class EventLogger {
|
|||||||
this.description = description;
|
this.description = description;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,34 +1,46 @@
|
|||||||
package sd.logging;
|
package sd.logging;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Tipos de eventos que podem ocorrer na simulação.
|
* Taxonomia oficial de eventos para o subsistema de logging centralizado.
|
||||||
* Usados para categorizar e filtrar logs.
|
* <p>
|
||||||
|
* Este enumerado padroniza a categorização de todas as ocorrências na simulação, permitindo:
|
||||||
|
* <ul>
|
||||||
|
* <li>Filtragem granular de logs (ex: ver apenas erros ou apenas tráfego de rede).</li>
|
||||||
|
* <li>Análise estatística post-mortem (parsear logs para calcular latências).</li>
|
||||||
|
* <li>Correlação de eventos distribuídos (seguir o rastro de um veículo através de vários nós).</li>
|
||||||
|
* </ul>
|
||||||
*/
|
*/
|
||||||
public enum EventType {
|
public enum EventType {
|
||||||
|
// --- Ciclo de Vida do Veículo ---
|
||||||
VEHICLE_GENERATED("Vehicle Generated"),
|
VEHICLE_GENERATED("Vehicle Generated"),
|
||||||
VEHICLE_ARRIVED("Vehicle Arrived"),
|
VEHICLE_ARRIVED("Vehicle Arrived"),
|
||||||
VEHICLE_QUEUED("Vehicle Queued"),
|
VEHICLE_QUEUED("Vehicle Queued"),
|
||||||
VEHICLE_DEPARTED("Vehicle Departed"),
|
VEHICLE_DEPARTED("Vehicle Departed"),
|
||||||
VEHICLE_EXITED("Vehicle Exited"),
|
VEHICLE_EXITED("Vehicle Exited"),
|
||||||
|
|
||||||
|
// --- Controlo de Semáforos e Exclusão Mútua ---
|
||||||
LIGHT_CHANGED_GREEN("Light Changed to Green"),
|
LIGHT_CHANGED_GREEN("Light Changed to Green"),
|
||||||
LIGHT_CHANGED_RED("Light Changed to Red"),
|
LIGHT_CHANGED_RED("Light Changed to Red"),
|
||||||
LIGHT_REQUEST_GREEN("Light Requested Green"),
|
LIGHT_REQUEST_GREEN("Light Requested Green"),
|
||||||
LIGHT_RELEASE_GREEN("Light Released Green"),
|
LIGHT_RELEASE_GREEN("Light Released Green"),
|
||||||
|
|
||||||
|
// --- Ciclo de Vida da Simulação/Processos ---
|
||||||
SIMULATION_STARTED("Simulation Started"),
|
SIMULATION_STARTED("Simulation Started"),
|
||||||
SIMULATION_STOPPED("Simulation Stopped"),
|
SIMULATION_STOPPED("Simulation Stopped"),
|
||||||
PROCESS_STARTED("Process Started"),
|
PROCESS_STARTED("Process Started"),
|
||||||
PROCESS_STOPPED("Process Stopped"),
|
PROCESS_STOPPED("Process Stopped"),
|
||||||
|
|
||||||
|
// --- Configuração e Telemetria ---
|
||||||
STATS_UPDATE("Statistics Update"),
|
STATS_UPDATE("Statistics Update"),
|
||||||
CONFIG_CHANGED("Configuration Changed"),
|
CONFIG_CHANGED("Configuration Changed"),
|
||||||
|
|
||||||
|
// --- Camada de Rede (TCP/Sockets) ---
|
||||||
CONNECTION_ESTABLISHED("Connection Established"),
|
CONNECTION_ESTABLISHED("Connection Established"),
|
||||||
CONNECTION_LOST("Connection Lost"),
|
CONNECTION_LOST("Connection Lost"),
|
||||||
MESSAGE_SENT("Message Sent"),
|
MESSAGE_SENT("Message Sent"),
|
||||||
MESSAGE_RECEIVED("Message Received"),
|
MESSAGE_RECEIVED("Message Received"),
|
||||||
|
|
||||||
|
// --- Tratamento de Exceções ---
|
||||||
ERROR("Error");
|
ERROR("Error");
|
||||||
|
|
||||||
private final String displayName;
|
private final String displayName;
|
||||||
@@ -45,4 +57,4 @@ public enum EventType {
|
|||||||
public String toString() {
|
public String toString() {
|
||||||
return displayName;
|
return displayName;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -12,16 +12,18 @@ import java.util.concurrent.ConcurrentHashMap;
|
|||||||
import sd.model.Vehicle;
|
import sd.model.Vehicle;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Rastreia e regista a viagem completa de veículos individuais.
|
* Subsistema de auditoria granular responsável pelo rastreio detalhado (Tracing) de veículos individuais.
|
||||||
*
|
|
||||||
* <p>
|
* <p>
|
||||||
* Cria ficheiros de trace detalhados com:
|
* Diferente do {@link EventLogger} (que regista eventos globais do sistema), esta classe foca-se
|
||||||
|
* na perspetiva do <b>agente</b>. Cria um ficheiro de rastro dedicado (`.trace`) para cada veículo
|
||||||
|
* monitorizado, registando cronologicamente cada interação com a infraestrutura (interseções,
|
||||||
|
* filas, semáforos).
|
||||||
|
* <p>
|
||||||
|
* <b>Funcionalidades:</b>
|
||||||
* <ul>
|
* <ul>
|
||||||
* <li>Timestamps de todos os eventos
|
* <li>Análise forense de percursos individuais.</li>
|
||||||
* <li>Localizações (interseções)
|
* <li>Validação de tempos de espera e travessia por nó.</li>
|
||||||
* <li>Tempos de espera em cada semáforo
|
* <li>Cálculo de eficiência de rota (tempo em movimento vs. tempo parado).</li>
|
||||||
* <li>Tempos de travessia
|
|
||||||
* <li>Tempo total no sistema
|
|
||||||
* </ul>
|
* </ul>
|
||||||
*/
|
*/
|
||||||
public class VehicleTracer {
|
public class VehicleTracer {
|
||||||
@@ -29,12 +31,18 @@ public class VehicleTracer {
|
|||||||
private static VehicleTracer instance;
|
private static VehicleTracer instance;
|
||||||
private static final Object instanceLock = new Object();
|
private static final Object instanceLock = new Object();
|
||||||
|
|
||||||
|
/** Mapa thread-safe de sessões de trace ativas (VehicleID -> TraceHandler). */
|
||||||
private final Map<String, VehicleTrace> trackedVehicles;
|
private final Map<String, VehicleTrace> trackedVehicles;
|
||||||
|
|
||||||
private final SimpleDateFormat timestampFormat;
|
private final SimpleDateFormat timestampFormat;
|
||||||
private final long simulationStartMillis;
|
private final long simulationStartMillis;
|
||||||
private final String traceDirectory;
|
private final String traceDirectory;
|
||||||
|
|
||||||
/** Construtor privado (singleton) */
|
/**
|
||||||
|
* Inicializa o tracer e prepara o diretório de saída.
|
||||||
|
*
|
||||||
|
* @param traceDirectory Caminho para armazenamento dos ficheiros .trace.
|
||||||
|
*/
|
||||||
private VehicleTracer(String traceDirectory) {
|
private VehicleTracer(String traceDirectory) {
|
||||||
this.trackedVehicles = new ConcurrentHashMap<>();
|
this.trackedVehicles = new ConcurrentHashMap<>();
|
||||||
this.timestampFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
|
this.timestampFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
|
||||||
@@ -48,7 +56,10 @@ public class VehicleTracer {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Obtém ou cria a instância singleton */
|
/**
|
||||||
|
* Obtém a instância única do tracer (Singleton).
|
||||||
|
* @return A instância global.
|
||||||
|
*/
|
||||||
public static VehicleTracer getInstance() {
|
public static VehicleTracer getInstance() {
|
||||||
if (instance == null) {
|
if (instance == null) {
|
||||||
synchronized (instanceLock) {
|
synchronized (instanceLock) {
|
||||||
@@ -60,7 +71,10 @@ public class VehicleTracer {
|
|||||||
return instance;
|
return instance;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Inicializa com diretório de trace customizado */
|
/**
|
||||||
|
* Reinicializa o tracer com um diretório personalizado.
|
||||||
|
* Útil para isolar logs de diferentes execuções em lote.
|
||||||
|
*/
|
||||||
public static void initialize(String traceDirectory) {
|
public static void initialize(String traceDirectory) {
|
||||||
synchronized (instanceLock) {
|
synchronized (instanceLock) {
|
||||||
if (instance != null) {
|
if (instance != null) {
|
||||||
@@ -71,12 +85,14 @@ public class VehicleTracer {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Começa a rastrear um veículo específico.
|
* Inicia a sessão de rastreio para um veículo específico.
|
||||||
* Cria ficheiro de trace para este veículo.
|
* Cria o ficheiro {@code logs/traces/vehicle-{id}.trace} e escreve o cabeçalho.
|
||||||
|
*
|
||||||
|
* @param vehicleId O identificador único do veículo.
|
||||||
*/
|
*/
|
||||||
public void startTracking(String vehicleId) {
|
public void startTracking(String vehicleId) {
|
||||||
if (trackedVehicles.containsKey(vehicleId)) {
|
if (trackedVehicles.containsKey(vehicleId)) {
|
||||||
return; // Already tracking
|
return; // Já está a ser rastreado
|
||||||
}
|
}
|
||||||
|
|
||||||
VehicleTrace trace = new VehicleTrace(vehicleId, traceDirectory);
|
VehicleTrace trace = new VehicleTrace(vehicleId, traceDirectory);
|
||||||
@@ -86,7 +102,7 @@ public class VehicleTracer {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Stops tracking a vehicle and closes its trace file.
|
* Encerra a sessão de rastreio, fecha o descritor de ficheiro e remove da memória.
|
||||||
*/
|
*/
|
||||||
public void stopTracking(String vehicleId) {
|
public void stopTracking(String vehicleId) {
|
||||||
VehicleTrace trace = trackedVehicles.remove(vehicleId);
|
VehicleTrace trace = trackedVehicles.remove(vehicleId);
|
||||||
@@ -97,14 +113,14 @@ public class VehicleTracer {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Checks if a vehicle is being tracked.
|
* Verifica se um veículo está atualmente sob auditoria.
|
||||||
*/
|
*/
|
||||||
public boolean isTracking(String vehicleId) {
|
public boolean isTracking(String vehicleId) {
|
||||||
return trackedVehicles.containsKey(vehicleId);
|
return trackedVehicles.containsKey(vehicleId);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Logs when a vehicle is generated.
|
* Regista o evento de instanciação do veículo pelo Coordenador.
|
||||||
*/
|
*/
|
||||||
public void logGenerated(Vehicle vehicle) {
|
public void logGenerated(Vehicle vehicle) {
|
||||||
if (!isTracking(vehicle.getId()))
|
if (!isTracking(vehicle.getId()))
|
||||||
@@ -119,7 +135,7 @@ public class VehicleTracer {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Logs when a vehicle arrives at an intersection.
|
* Regista a chegada física do veículo à zona de deteção de uma interseção.
|
||||||
*/
|
*/
|
||||||
public void logArrival(String vehicleId, String intersection, double simulationTime) {
|
public void logArrival(String vehicleId, String intersection, double simulationTime) {
|
||||||
if (!isTracking(vehicleId))
|
if (!isTracking(vehicleId))
|
||||||
@@ -133,7 +149,7 @@ public class VehicleTracer {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Logs when a vehicle is queued at a traffic light.
|
* Regista a entrada do veículo na estrutura de fila de um semáforo.
|
||||||
*/
|
*/
|
||||||
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))
|
if (!isTracking(vehicleId))
|
||||||
@@ -147,7 +163,7 @@ public class VehicleTracer {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Logs when a vehicle starts waiting at a red light.
|
* Regista o início da espera ativa (veículo parado no Vermelho).
|
||||||
*/
|
*/
|
||||||
public void logWaitingStart(String vehicleId, String intersection, String direction) {
|
public void logWaitingStart(String vehicleId, String intersection, String direction) {
|
||||||
if (!isTracking(vehicleId))
|
if (!isTracking(vehicleId))
|
||||||
@@ -161,7 +177,8 @@ public class VehicleTracer {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Logs when a vehicle finishes waiting (light turns green).
|
* Regista o fim da espera (Sinal Verde).
|
||||||
|
* @param waitTime Duração total da paragem nesta instância.
|
||||||
*/
|
*/
|
||||||
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))
|
if (!isTracking(vehicleId))
|
||||||
@@ -175,7 +192,7 @@ public class VehicleTracer {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Logs when a vehicle starts crossing an intersection.
|
* Regista o início da travessia da interseção (ocupação da zona crítica).
|
||||||
*/
|
*/
|
||||||
public void logCrossingStart(String vehicleId, String intersection, String direction) {
|
public void logCrossingStart(String vehicleId, String intersection, String direction) {
|
||||||
if (!isTracking(vehicleId))
|
if (!isTracking(vehicleId))
|
||||||
@@ -189,7 +206,7 @@ public class VehicleTracer {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Logs when a vehicle finishes crossing an intersection.
|
* Regista a libertação da zona crítica da interseção.
|
||||||
*/
|
*/
|
||||||
public void logCrossingEnd(String vehicleId, String intersection, double crossingTime) {
|
public void logCrossingEnd(String vehicleId, String intersection, double crossingTime) {
|
||||||
if (!isTracking(vehicleId))
|
if (!isTracking(vehicleId))
|
||||||
@@ -203,7 +220,7 @@ public class VehicleTracer {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Logs when a vehicle departs from an intersection.
|
* Regista a partida da interseção em direção ao próximo nó.
|
||||||
*/
|
*/
|
||||||
public void logDeparture(String vehicleId, String intersection, String nextDestination) {
|
public void logDeparture(String vehicleId, String intersection, String nextDestination) {
|
||||||
if (!isTracking(vehicleId))
|
if (!isTracking(vehicleId))
|
||||||
@@ -217,7 +234,10 @@ public class VehicleTracer {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Logs when a vehicle exits the system.
|
* Regista a saída do sistema (no Exit Node).
|
||||||
|
* <p>
|
||||||
|
* Este método também desencadeia a escrita do <b>Sumário de Viagem</b> no final do log
|
||||||
|
* e fecha o ficheiro automaticamente.
|
||||||
*/
|
*/
|
||||||
public void logExit(Vehicle vehicle, double systemTime) {
|
public void logExit(Vehicle vehicle, double systemTime) {
|
||||||
if (!isTracking(vehicle.getId()))
|
if (!isTracking(vehicle.getId()))
|
||||||
@@ -229,7 +249,7 @@ public class VehicleTracer {
|
|||||||
String.format("Exited system - Total time: %.2fs, Waiting: %.2fs, Crossing: %.2fs",
|
String.format("Exited system - Total time: %.2fs, Waiting: %.2fs, Crossing: %.2fs",
|
||||||
systemTime, vehicle.getTotalWaitingTime(), vehicle.getTotalCrossingTime()));
|
systemTime, vehicle.getTotalWaitingTime(), vehicle.getTotalCrossingTime()));
|
||||||
|
|
||||||
// Write summary
|
// Escreve estatísticas sumarizadas
|
||||||
trace.writeSummary(vehicle, systemTime);
|
trace.writeSummary(vehicle, systemTime);
|
||||||
|
|
||||||
// Stop tracking and close file
|
// Stop tracking and close file
|
||||||
@@ -238,7 +258,8 @@ public class VehicleTracer {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Shuts down the tracer and closes all trace files.
|
* Fecha forçosamente todos os traces abertos.
|
||||||
|
* Deve ser chamado no shutdown da simulação para evitar corrupção de logs.
|
||||||
*/
|
*/
|
||||||
public void shutdown() {
|
public void shutdown() {
|
||||||
for (VehicleTrace trace : trackedVehicles.values()) {
|
for (VehicleTrace trace : trackedVehicles.values()) {
|
||||||
@@ -248,7 +269,7 @@ public class VehicleTracer {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Internal class to handle tracing for a single vehicle.
|
* Classe interna auxiliar que gere o descritor de ficheiro e a formatação para um único veículo.
|
||||||
*/
|
*/
|
||||||
private class VehicleTrace {
|
private class VehicleTrace {
|
||||||
private final String vehicleId;
|
private final String vehicleId;
|
||||||
@@ -340,4 +361,4 @@ public class VehicleTracer {
|
|||||||
return str.length() <= maxLength ? str : str.substring(0, maxLength);
|
return str.length() <= maxLength ? str : str.substring(0, maxLength);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -94,9 +94,6 @@ public class Intersection {
|
|||||||
*/
|
*/
|
||||||
public void receiveVehicle(Vehicle vehicle, double simulationTime) {
|
public void receiveVehicle(Vehicle vehicle, double simulationTime) {
|
||||||
totalVehiclesReceived++;
|
totalVehiclesReceived++;
|
||||||
|
|
||||||
// Note: Route advancement is handled by SimulationEngine.handleVehicleArrival()
|
|
||||||
// before calling this method, so we don't advance here.
|
|
||||||
|
|
||||||
String nextDestination = vehicle.getCurrentDestination();
|
String nextDestination = vehicle.getCurrentDestination();
|
||||||
|
|
||||||
|
|||||||
@@ -5,41 +5,52 @@ import java.util.UUID;
|
|||||||
import sd.protocol.MessageProtocol;
|
import sd.protocol.MessageProtocol;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Representa uma mensagem trocada entre processos na simulação distribuída.
|
* Envelope fundamental do protocolo de comunicação entre processos distribuídos (IPC).
|
||||||
*
|
* <p>
|
||||||
* <p>Cada mensagem tem um ID único, tipo, remetente, destino e payload.
|
* Esta classe atua como a Unidade de Dados de Aplicação (ADU), encapsulando tanto
|
||||||
* Implementa {@link MessageProtocol} que estende Serializable para transmissão pela rede.</p>
|
* os metadados de roteamento (origem, destino, tipo) quanto a carga útil (payload)
|
||||||
|
* polimórfica. É agnóstica ao conteúdo, servindo como contentor genérico para
|
||||||
|
* transferência de estado (Veículos, Estatísticas) ou sinais de controlo (Semáforos).
|
||||||
|
* <p>
|
||||||
|
* A imutabilidade dos campos (exceto via serialização) garante a integridade da mensagem
|
||||||
|
* durante o trânsito na rede.
|
||||||
*/
|
*/
|
||||||
public class Message implements MessageProtocol {
|
public class Message implements MessageProtocol {
|
||||||
|
|
||||||
private static final long serialVersionUID = 1L;
|
private static final long serialVersionUID = 1L;
|
||||||
|
|
||||||
/** Identificador único desta mensagem */
|
/** * Identificador único universal (UUID).
|
||||||
|
* Essencial para rastreabilidade (tracing), logs de auditoria e mecanismos de deduplicação.
|
||||||
|
*/
|
||||||
private final String messageId;
|
private final String messageId;
|
||||||
|
|
||||||
/** Tipo desta mensagem (ex: VEHICLE_TRANSFER, STATS_UPDATE) */
|
/** Discriminador semântico que define como o recetor deve processar o payload. */
|
||||||
private final MessageType type;
|
private final MessageType type;
|
||||||
|
|
||||||
/** Identificador do processo que enviou esta mensagem */
|
/** Identificador lógico do nó emissor (ex: "Cr1", "Coordinator"). */
|
||||||
private final String senderId;
|
private final String senderId;
|
||||||
|
|
||||||
/** Identificador do processo de destino (pode ser null para broadcast) */
|
/** * Identificador lógico do nó recetor.
|
||||||
|
* Se {@code null}, a mensagem deve ser tratada como <b>Broadcast</b>.
|
||||||
|
*/
|
||||||
private final String destinationId;
|
private final String destinationId;
|
||||||
|
|
||||||
/** Dados a serem transmitidos (o tipo depende do tipo de mensagem) */
|
/** * Carga útil polimórfica.
|
||||||
|
* Deve implementar {@link java.io.Serializable} para garantir transmissão correta.
|
||||||
|
*/
|
||||||
private final Object payload;
|
private final Object payload;
|
||||||
|
|
||||||
/** Timestamp de criação da mensagem (tempo de simulação ou real) */
|
/** Marca temporal da criação da mensagem (Unix Timestamp), usada para cálculo de latência de rede. */
|
||||||
private final long timestamp;
|
private final long timestamp;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Cria uma nova mensagem com todos os parâmetros.
|
* Construtor completo para reconstrução de mensagens ou envio com timestamp manual.
|
||||||
*
|
*
|
||||||
* @param type tipo da mensagem
|
* @param type Classificação semântica da mensagem.
|
||||||
* @param senderId ID do processo remetente
|
* @param senderId ID do processo origem.
|
||||||
* @param destinationId ID do processo de destino (null para broadcast)
|
* @param destinationId ID do processo destino (ou null para broadcast).
|
||||||
* @param payload conteúdo da mensagem
|
* @param payload Objeto de domínio a ser transportado.
|
||||||
* @param timestamp timestamp de criação da mensagem
|
* @param timestamp Instante de criação (ms).
|
||||||
*/
|
*/
|
||||||
public Message(MessageType type, String senderId, String destinationId,
|
public Message(MessageType type, String senderId, String destinationId,
|
||||||
Object payload, long timestamp) {
|
Object payload, long timestamp) {
|
||||||
@@ -52,23 +63,24 @@ public class Message implements MessageProtocol {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Cria uma nova mensagem usando o tempo atual do sistema como timestamp.
|
* Construtor de conveniência que atribui automaticamente o timestamp atual do sistema.
|
||||||
*
|
*
|
||||||
* @param type tipo da mensagem
|
* @param type Classificação semântica.
|
||||||
* @param senderId ID do processo remetente
|
* @param senderId ID do processo origem.
|
||||||
* @param destinationId ID do processo de destino
|
* @param destinationId ID do processo destino.
|
||||||
* @param payload conteúdo da mensagem
|
* @param payload Objeto de domínio.
|
||||||
*/
|
*/
|
||||||
public Message(MessageType type, String senderId, String destinationId, Object payload) {
|
public Message(MessageType type, String senderId, String destinationId, Object payload) {
|
||||||
this(type, senderId, destinationId, payload, System.currentTimeMillis());
|
this(type, senderId, destinationId, payload, System.currentTimeMillis());
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Cria uma mensagem de broadcast (sem destino específico).
|
* Construtor de conveniência para mensagens de difusão (Broadcast).
|
||||||
|
* Define {@code destinationId} como null.
|
||||||
*
|
*
|
||||||
* @param type tipo da mensagem
|
* @param type Classificação semântica.
|
||||||
* @param senderId ID do processo remetente
|
* @param senderId ID do processo origem.
|
||||||
* @param payload conteúdo da mensagem
|
* @param payload Objeto de domínio.
|
||||||
*/
|
*/
|
||||||
public Message(MessageType type, String senderId, Object payload) {
|
public Message(MessageType type, String senderId, Object payload) {
|
||||||
this(type, senderId, null, payload, System.currentTimeMillis());
|
this(type, senderId, null, payload, System.currentTimeMillis());
|
||||||
@@ -101,21 +113,23 @@ public class Message implements MessageProtocol {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Checks if this is a broadcast message (no specific destination).
|
* Verifica se a mensagem se destina a todos os nós da rede.
|
||||||
*
|
*
|
||||||
* @return true if destinationId is null, false otherwise
|
* @return {@code true} se o destinationId for nulo.
|
||||||
*/
|
*/
|
||||||
public boolean isBroadcast() {
|
public boolean isBroadcast() {
|
||||||
return destinationId == null;
|
return destinationId == null;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Gets the payload cast to a specific type.
|
* Utilitário para casting seguro e fluente do payload.
|
||||||
* Use with caution and ensure type safety.
|
* <p>
|
||||||
|
* Evita a necessidade de casts explícitos e supressão de warnings no código cliente.
|
||||||
*
|
*
|
||||||
* @param <T> The expected payload type
|
* @param <T> O tipo esperado do payload.
|
||||||
* @return The payload cast to type T
|
* @param clazz A classe do tipo esperado para verificação em runtime (opcional no uso, mas boa prática).
|
||||||
* @throws ClassCastException if the payload is not of type T
|
* @return O payload convertido para o tipo T.
|
||||||
|
* @throws ClassCastException Se o payload não for compatível com o tipo solicitado.
|
||||||
*/
|
*/
|
||||||
@SuppressWarnings("unchecked")
|
@SuppressWarnings("unchecked")
|
||||||
public <T> T getPayloadAs(Class<T> clazz) {
|
public <T> T getPayloadAs(Class<T> clazz) {
|
||||||
@@ -140,4 +154,4 @@ public class Message implements MessageProtocol {
|
|||||||
destinationId != null ? destinationId : "BROADCAST",
|
destinationId != null ? destinationId : "BROADCAST",
|
||||||
timestamp);
|
timestamp);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -2,7 +2,7 @@ package sd.protocol;
|
|||||||
|
|
||||||
import java.io.Serializable;
|
import java.io.Serializable;
|
||||||
|
|
||||||
import sd.model.MessageType; // Assuming MessageType is in sd.model or sd.protocol
|
import sd.model.MessageType;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Contrato para todas as mensagens trocadas no simulador.
|
* Contrato para todas as mensagens trocadas no simulador.
|
||||||
|
|||||||
@@ -11,37 +11,70 @@ import java.net.Socket;
|
|||||||
import java.net.SocketTimeoutException;
|
import java.net.SocketTimeoutException;
|
||||||
import java.net.UnknownHostException;
|
import java.net.UnknownHostException;
|
||||||
import java.util.concurrent.TimeUnit;
|
import java.util.concurrent.TimeUnit;
|
||||||
|
import java.util.concurrent.locks.LockSupport;
|
||||||
|
|
||||||
import sd.serialization.MessageSerializer;
|
import sd.serialization.MessageSerializer;
|
||||||
import sd.serialization.SerializationException;
|
import sd.serialization.SerializationException;
|
||||||
import sd.serialization.SerializerFactory;
|
import sd.serialization.SerializerFactory;
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Simplifica comunicação via sockets.
|
* Wrapper de alto nível para gestão robusta de conexões TCP.
|
||||||
* Inclui lógica de retry para robustez.
|
* <p>
|
||||||
|
* Esta classe abstrai a complexidade da API nativa {@link java.net.Socket}, oferecendo:
|
||||||
|
* <ol>
|
||||||
|
* <li><b>Resiliência:</b> Lógica de reconexão automática (Retry Loop) no arranque, crucial para sistemas
|
||||||
|
* distribuídos onde a ordem de inicialização dos nós não é garantida.</li>
|
||||||
|
* <li><b>Framing:</b> Implementação transparente do protocolo "Length-Prefix" (4 bytes de tamanho + payload),
|
||||||
|
* resolvendo o problema de fragmentação de stream TCP.</li>
|
||||||
|
* <li><b>Serialização:</b> Integração direta com a camada de serialização JSON.</li>
|
||||||
|
* </ol>
|
||||||
*/
|
*/
|
||||||
public class SocketConnection implements Closeable {
|
public class SocketConnection implements Closeable {
|
||||||
|
|
||||||
|
// --- Network Resources ---
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The underlying TCP socket used for network communication.
|
||||||
|
*/
|
||||||
private final Socket socket;
|
private final Socket socket;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The raw output stream for writing bytes to the network.
|
||||||
|
* Wrapped by {@link DataOutputStream} during message sending.
|
||||||
|
*/
|
||||||
private final OutputStream outputStream;
|
private final OutputStream outputStream;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The raw input stream for reading bytes from the network.
|
||||||
|
* Wrapped by {@link DataInputStream} during message reception.
|
||||||
|
*/
|
||||||
private final InputStream inputStream;
|
private final InputStream inputStream;
|
||||||
|
|
||||||
|
// --- Serialization ---
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The serializer strategy used to convert objects to/from byte arrays (e.g., JSON).
|
||||||
|
*/
|
||||||
private final MessageSerializer serializer;
|
private final MessageSerializer serializer;
|
||||||
|
|
||||||
/** Número máximo de tentativas de ligação */
|
/** Número máximo de tentativas de ligação antes de desistir (Fail-fast). */
|
||||||
private static final int MAX_RETRIES = 5;
|
private static final int MAX_RETRIES = 5;
|
||||||
/** Atraso entre tentativas (milissegundos) */
|
|
||||||
|
/** Janela de espera (backoff) linear entre tentativas (em milissegundos). */
|
||||||
private static final long RETRY_DELAY_MS = 1000;
|
private static final long RETRY_DELAY_MS = 1000;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Construtor do cliente que inicia a ligação.
|
* Construtor para clientes (Active Open).
|
||||||
* Tenta ligar a um servidor já em escuta, com retry.
|
* Tenta estabelecer uma conexão TCP com um servidor, aplicando lógica de retry.
|
||||||
|
* <p>
|
||||||
|
* Este comportamento é vital quando o processo Coordenador inicia antes das Interseções estarem
|
||||||
|
* prontas para aceitar conexões ({@code accept()}).
|
||||||
*
|
*
|
||||||
* @param host endereço do host (ex: "localhost")
|
* @param host Endereço do nó de destino (ex: "localhost").
|
||||||
* @param port número da porta
|
* @param port Porta de serviço.
|
||||||
* @throws IOException se falhar após todas as tentativas
|
* @throws IOException Se a conexão falhar após todas as {@code MAX_RETRIES} tentativas.
|
||||||
* @throws UnknownHostException se o host não for encontrado
|
* @throws UnknownHostException Se o DNS não resolver o hostname.
|
||||||
* @throws InterruptedException se a thread for interrompida
|
* @throws InterruptedException Se a thread for interrompida durante o sleep de retry.
|
||||||
*/
|
*/
|
||||||
public SocketConnection(String host, int port) throws IOException, UnknownHostException, InterruptedException {
|
public SocketConnection(String host, int port) throws IOException, UnknownHostException, InterruptedException {
|
||||||
Socket tempSocket = null;
|
Socket tempSocket = null;
|
||||||
@@ -52,7 +85,7 @@ public class SocketConnection implements Closeable {
|
|||||||
// --- Retry Loop ---
|
// --- Retry Loop ---
|
||||||
for (int attempt = 1; attempt <= MAX_RETRIES; attempt++) {
|
for (int attempt = 1; attempt <= MAX_RETRIES; attempt++) {
|
||||||
try {
|
try {
|
||||||
// Try to establish the connection
|
// Try to establish the connection (SYN -> SYN-ACK -> ACK)
|
||||||
tempSocket = new Socket(host, port);
|
tempSocket = new Socket(host, port);
|
||||||
|
|
||||||
// If successful, break out of the retry loop
|
// If successful, break out of the retry loop
|
||||||
@@ -61,17 +94,17 @@ public class SocketConnection implements Closeable {
|
|||||||
break;
|
break;
|
||||||
|
|
||||||
} catch (ConnectException | SocketTimeoutException e) {
|
} catch (ConnectException | SocketTimeoutException e) {
|
||||||
// These are common errors indicating the server might not be ready.
|
// Common errors: "Connection refused" (server not up) or "Timeout" (firewall/network)
|
||||||
lastException = e;
|
lastException = e;
|
||||||
System.out.printf("[SocketConnection] Attempt %d/%d failed: %s. Retrying in %d ms...%n",
|
System.out.printf("[SocketConnection] Attempt %d/%d failed: %s. Retrying in %d ms...%n",
|
||||||
attempt, MAX_RETRIES, e.getMessage(), RETRY_DELAY_MS);
|
attempt, MAX_RETRIES, e.getMessage(), RETRY_DELAY_MS);
|
||||||
|
|
||||||
if (attempt < MAX_RETRIES) {
|
if (attempt < MAX_RETRIES) {
|
||||||
// Wait before the next attempt
|
// Blocking wait before next attempt
|
||||||
TimeUnit.MILLISECONDS.sleep(RETRY_DELAY_MS);
|
TimeUnit.MILLISECONDS.sleep(RETRY_DELAY_MS);
|
||||||
}
|
}
|
||||||
} catch (IOException e) {
|
} catch (IOException e) {
|
||||||
// Other IOExceptions might be more permanent, but we retry anyway.
|
// Other IO errors
|
||||||
lastException = e;
|
lastException = e;
|
||||||
System.out.printf("[SocketConnection] Attempt %d/%d failed with IOException: %s. Retrying in %d ms...%n",
|
System.out.printf("[SocketConnection] Attempt %d/%d failed with IOException: %s. Retrying in %d ms...%n",
|
||||||
attempt, MAX_RETRIES, e.getMessage(), RETRY_DELAY_MS);
|
attempt, MAX_RETRIES, e.getMessage(), RETRY_DELAY_MS);
|
||||||
@@ -81,51 +114,49 @@ public class SocketConnection implements Closeable {
|
|||||||
}
|
}
|
||||||
} // --- End of Retry Loop ---
|
} // --- End of Retry Loop ---
|
||||||
|
|
||||||
// If after all retries tempSocket is still null, it means connection failed permanently.
|
// Final validation
|
||||||
if (tempSocket == null) {
|
if (tempSocket == null) {
|
||||||
System.err.printf("[SocketConnection] Failed to connect to %s:%d after %d attempts.%n", host, port, MAX_RETRIES);
|
System.err.printf("[SocketConnection] Failed to connect to %s:%d after %d attempts.%n", host, port, MAX_RETRIES);
|
||||||
if (lastException != null) {
|
if (lastException != null) {
|
||||||
throw lastException; // Throw the last exception encountered
|
throw lastException; // Propagate the root cause
|
||||||
} else {
|
} else {
|
||||||
// Should not happen if loop ran, but as a fallback
|
|
||||||
throw new IOException("Failed to connect after " + MAX_RETRIES + " attempts, reason unknown.");
|
throw new IOException("Failed to connect after " + MAX_RETRIES + " attempts, reason unknown.");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// If connection was successful, assign to final variable and create streams
|
// Initialize streams
|
||||||
this.socket = tempSocket;
|
this.socket = tempSocket;
|
||||||
|
|
||||||
this.outputStream = socket.getOutputStream();
|
this.outputStream = socket.getOutputStream();
|
||||||
this.inputStream = socket.getInputStream();
|
this.inputStream = socket.getInputStream();
|
||||||
this.serializer = SerializerFactory.createDefault();
|
this.serializer = SerializerFactory.createDefault();
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Constructor for the "Server" (who accepts the connection).
|
* Construtor para servidores (Passive Open).
|
||||||
* Receives a Socket that has already been accepted by a ServerSocket.
|
* Envolve um socket já conectado (retornado por {@code serverSocket.accept()}).
|
||||||
* No retry logic needed here as the connection is already established.
|
* Não necessita de retry logic pois a conexão física já existe.
|
||||||
*
|
*
|
||||||
* @param acceptedSocket The Socket returned by serverSocket.accept().
|
* @param acceptedSocket O socket ativo retornado pelo SO.
|
||||||
* @throws IOException If stream creation fails.
|
* @throws IOException Se falhar a obtenção dos streams de I/O.
|
||||||
*/
|
*/
|
||||||
public SocketConnection(Socket acceptedSocket) throws IOException {
|
public SocketConnection(Socket acceptedSocket) throws IOException {
|
||||||
this.socket = acceptedSocket;
|
this.socket = acceptedSocket;
|
||||||
this.outputStream = socket.getOutputStream();
|
this.outputStream = socket.getOutputStream();
|
||||||
this.inputStream = socket.getInputStream();
|
this.inputStream = socket.getInputStream();
|
||||||
this.serializer = SerializerFactory.createDefault();
|
this.serializer = SerializerFactory.createDefault();
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Sends (serializes) a MessageProtocol object over the socket.
|
* Serializa e transmite uma mensagem através do canal.
|
||||||
|
* <p>
|
||||||
|
* Utiliza sincronização ({@code synchronized}) para garantir que escritas concorrentes
|
||||||
|
* na mesma conexão não corrompem a stream de bytes (thread-safety).
|
||||||
*
|
*
|
||||||
* @param message The "envelope" (which contains the Vehicle) to be sent.
|
* @param message O objeto de protocolo a enviar.
|
||||||
* @throws IOException If writing to the stream fails or socket is not connected.
|
* @throws IOException Se o socket estiver fechado ou ocorrer erro de escrita.
|
||||||
*/
|
*/
|
||||||
public synchronized void sendMessage(MessageProtocol message) throws IOException {
|
public synchronized void sendMessage(MessageProtocol message) throws IOException {
|
||||||
if (socket == null || !socket.isConnected()) {
|
if (socket == null || !socket.isConnected()) {
|
||||||
throw new IOException("Socket is not connected");
|
throw new IOException("Socket is not connected");
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -133,11 +164,12 @@ public class SocketConnection implements Closeable {
|
|||||||
// Serializa para bytes JSON
|
// Serializa para bytes JSON
|
||||||
byte[] data = serializer.serialize(message);
|
byte[] data = serializer.serialize(message);
|
||||||
|
|
||||||
// Write 4-byte length prefix
|
// Write 4-byte length prefix (Framing)
|
||||||
DataOutputStream dataOut = new DataOutputStream(outputStream);
|
DataOutputStream dataOut = new DataOutputStream(outputStream);
|
||||||
dataOut.writeInt(data.length);
|
dataOut.writeInt(data.length);
|
||||||
dataOut.write(data);
|
dataOut.write(data);
|
||||||
dataOut.flush();
|
dataOut.flush();
|
||||||
|
LockSupport.parkNanos(50000); // 50us
|
||||||
|
|
||||||
} catch (SerializationException e) {
|
} catch (SerializationException e) {
|
||||||
throw new IOException("Failed to serialize message", e);
|
throw new IOException("Failed to serialize message", e);
|
||||||
@@ -145,11 +177,14 @@ public class SocketConnection implements Closeable {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Tries to read (deserialize) a MessageProtocol object from the socket.
|
* Bloqueia à espera de uma mensagem completa do socket.
|
||||||
|
* <p>
|
||||||
|
* Lê primeiro o cabeçalho de tamanho (4 bytes) e depois o payload exato,
|
||||||
|
* garantindo que processa mensagens completas mesmo se chegarem fragmentadas em múltiplos pacotes TCP.
|
||||||
*
|
*
|
||||||
* @return The "envelope" (MessageProtocol) that was received.
|
* @return O objeto {@link MessageProtocol} reconstruído.
|
||||||
* @throws IOException If the connection is lost, the stream is corrupted, or socket is not connected.
|
* @throws IOException Se a conexão for perdida (EOF) ou o stream corrompido.
|
||||||
* @throws ClassNotFoundException If the received object is unknown.
|
* @throws ClassNotFoundException Se o tipo desserializado não for encontrado no classpath.
|
||||||
*/
|
*/
|
||||||
public MessageProtocol receiveMessage() throws IOException, ClassNotFoundException {
|
public MessageProtocol receiveMessage() throws IOException, ClassNotFoundException {
|
||||||
if (socket == null || !socket.isConnected()) {
|
if (socket == null || !socket.isConnected()) {
|
||||||
@@ -157,19 +192,21 @@ public class SocketConnection implements Closeable {
|
|||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// Lê um prefixo de 4 bytes - indicador de tamanho
|
|
||||||
DataInputStream dataIn = new DataInputStream(inputStream);
|
DataInputStream dataIn = new DataInputStream(inputStream);
|
||||||
int length = dataIn.readInt();
|
int length = dataIn.readInt();
|
||||||
|
|
||||||
if (length <= 0 || length > 10_000_000) { // Sanity check (10MB max)
|
// Sanity check para evitar OutOfMemory em caso de corrupção de stream
|
||||||
|
if (length <= 0 || length > 10_000_000) { // Max 10MB payload
|
||||||
throw new IOException("Invalid message length: " + length);
|
throw new IOException("Invalid message length: " + length);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Ler dados da mensagem
|
// Ler dados exatos da mensagem
|
||||||
byte[] data = new byte[length];
|
byte[] data = new byte[length];
|
||||||
dataIn.readFully(data);
|
dataIn.readFully(data);
|
||||||
|
LockSupport.parkNanos(50000); // 50us
|
||||||
|
|
||||||
// Deserialize do JSON - use concrete Message class, not interface
|
// Deserialize do JSON - força o tipo concreto Message
|
||||||
return serializer.deserialize(data, sd.model.Message.class);
|
return serializer.deserialize(data, sd.model.Message.class);
|
||||||
|
|
||||||
} catch (SerializationException e) {
|
} catch (SerializationException e) {
|
||||||
@@ -178,7 +215,8 @@ public class SocketConnection implements Closeable {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Closes the socket and all streams (Input and Output).
|
* Encerra a conexão e liberta os descritores de ficheiro.
|
||||||
|
* Operação idempotente.
|
||||||
*/
|
*/
|
||||||
@Override
|
@Override
|
||||||
public void close() throws IOException {
|
public void close() throws IOException {
|
||||||
@@ -188,7 +226,8 @@ public class SocketConnection implements Closeable {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @return true if the socket is still connected and not closed.
|
* Verifica o estado operacional da conexão.
|
||||||
|
* @return true se o socket está aberto e conectado.
|
||||||
*/
|
*/
|
||||||
public boolean isConnected() {
|
public boolean isConnected() {
|
||||||
return socket != null && socket.isConnected() && !socket.isClosed();
|
return socket != null && socket.isConnected() && !socket.isClosed();
|
||||||
|
|||||||
@@ -1,26 +1,25 @@
|
|||||||
package sd.serialization;
|
package sd.serialization;
|
||||||
|
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
|
||||||
import com.google.gson.Gson;
|
import com.google.gson.Gson;
|
||||||
import com.google.gson.GsonBuilder;
|
import com.google.gson.GsonBuilder;
|
||||||
import com.google.gson.JsonSyntaxException;
|
import com.google.gson.JsonSyntaxException;
|
||||||
|
|
||||||
import java.nio.charset.StandardCharsets;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* JSON-based implementation of {@link MessageSerializer} using Google's Gson library.
|
* Implementação baseada em JSON da estratégia {@link MessageSerializer}, utilizando a biblioteca Gson.
|
||||||
*
|
* <p>
|
||||||
* This serializer converts objects to JSON format for transmission, providing:
|
* Este serializador converte objetos Java para o formato de texto JSON antes da transmissão.
|
||||||
* - Human-readable message format (easy debugging)
|
* Oferece várias vantagens técnicas sobre a serialização nativa do Java:
|
||||||
* - Cross-platform compatibility
|
* <ul>
|
||||||
* - Smaller message sizes compared to Java native serialization
|
* <li><b>Legibilidade:</b> O formato de texto facilita a depuração (sniffing de rede) sem ferramentas especializadas.</li>
|
||||||
* - Better security (no code execution during deserialization)
|
* <li><b>Interoperabilidade:</b> Permite futura integração com componentes não-Java (ex: Dashboards web em JS).</li>
|
||||||
*
|
* <li><b>Segurança:</b> Reduz a superfície de ataque para execução remota de código (RCE), pois não desserializa classes arbitrárias, apenas dados.</li>
|
||||||
* The serializer is configured with pretty printing disabled by default for
|
* </ul>
|
||||||
* production use, but can be enabled for debugging purposes.
|
* <p>
|
||||||
*
|
* <b>Thread-Safety:</b> A instância interna do {@code Gson} é imutável e thread-safe, permitindo
|
||||||
* Thread-safety: This class is thread-safe as Gson instances are thread-safe.
|
* que este serializador seja partilhado entre múltiplas threads (ex: no pool do DashboardServer).
|
||||||
*
|
* * @see MessageSerializer
|
||||||
* @see MessageSerializer
|
|
||||||
*/
|
*/
|
||||||
public class JsonMessageSerializer implements MessageSerializer {
|
public class JsonMessageSerializer implements MessageSerializer {
|
||||||
|
|
||||||
@@ -28,16 +27,16 @@ public class JsonMessageSerializer implements MessageSerializer {
|
|||||||
private final boolean prettyPrint;
|
private final boolean prettyPrint;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Creates a new JSON serializer with default configuration (no pretty printing).
|
* Cria um novo serializador JSON com configuração otimizada para produção (compacto).
|
||||||
*/
|
*/
|
||||||
public JsonMessageSerializer() {
|
public JsonMessageSerializer() {
|
||||||
this(false);
|
this(false);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Creates a new JSON serializer with optional pretty printing.
|
* Cria um novo serializador JSON com formatação opcional.
|
||||||
*
|
* * @param prettyPrint Se {@code true}, o JSON gerado incluirá indentação e quebras de linha.
|
||||||
* @param prettyPrint If true, JSON output will be formatted with indentation
|
* Útil para debug, mas aumenta significativamente o tamanho do payload.
|
||||||
*/
|
*/
|
||||||
public JsonMessageSerializer(boolean prettyPrint) {
|
public JsonMessageSerializer(boolean prettyPrint) {
|
||||||
this.prettyPrint = prettyPrint;
|
this.prettyPrint = prettyPrint;
|
||||||
@@ -53,6 +52,13 @@ public class JsonMessageSerializer implements MessageSerializer {
|
|||||||
this.gson = builder.create();
|
this.gson = builder.create();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Converte um objeto em memória para um array de bytes JSON (UTF-8).
|
||||||
|
*
|
||||||
|
* @param object O objeto a ser serializado.
|
||||||
|
* @return O payload em bytes pronto para transmissão TCP.
|
||||||
|
* @throws SerializationException Se o objeto não for compatível com JSON ou ocorrer erro de encoding.
|
||||||
|
*/
|
||||||
@Override
|
@Override
|
||||||
public byte[] serialize(Object object) throws SerializationException {
|
public byte[] serialize(Object object) throws SerializationException {
|
||||||
if (object == null) {
|
if (object == null) {
|
||||||
@@ -68,6 +74,16 @@ public class JsonMessageSerializer implements MessageSerializer {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Reconstrói um objeto Java a partir de um array de bytes JSON.
|
||||||
|
* <p>
|
||||||
|
* Realiza a validação sintática do JSON e a validação de tipo baseada na classe alvo.
|
||||||
|
*
|
||||||
|
* @param data O array de bytes recebido da rede.
|
||||||
|
* @param clazz A classe do objeto esperado (Type Token).
|
||||||
|
* @return A instância do objeto reconstruído.
|
||||||
|
* @throws SerializationException Se o JSON for malformado ou incompatível com a classe alvo.
|
||||||
|
*/
|
||||||
@Override
|
@Override
|
||||||
public <T> T deserialize(byte[] data, Class<T> clazz) throws SerializationException {
|
public <T> T deserialize(byte[] data, Class<T> clazz) throws SerializationException {
|
||||||
if (data == null) {
|
if (data == null) {
|
||||||
@@ -95,20 +111,18 @@ public class JsonMessageSerializer implements MessageSerializer {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Returns the underlying Gson instance for advanced usage.
|
* Retorna a instância subjacente do Gson para configurações avançadas.
|
||||||
*
|
* * @return A instância Gson configurada.
|
||||||
* @return The Gson instance
|
|
||||||
*/
|
*/
|
||||||
public Gson getGson() {
|
public Gson getGson() {
|
||||||
return gson;
|
return gson;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Checks if pretty printing is enabled.
|
* Verifica se a formatação "pretty print" está ativa.
|
||||||
*
|
* * @return true se a indentação estiver habilitada.
|
||||||
* @return true if pretty printing is enabled
|
|
||||||
*/
|
*/
|
||||||
public boolean isPrettyPrint() {
|
public boolean isPrettyPrint() {
|
||||||
return prettyPrint;
|
return prettyPrint;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,48 +1,49 @@
|
|||||||
package sd.serialization;
|
package sd.serialization;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Interface for serializing and deserializing objects for network transmission.
|
* Interface que define o contrato para estratégias de serialização e desserialização de objetos.
|
||||||
*
|
* <p>
|
||||||
* This interface provides a common abstraction for different serialization strategies
|
* Esta abstração permite desacoplar a camada de transporte (Sockets TCP) da camada de
|
||||||
* allowing the system to switch between implementations without changing the communication layer.
|
* apresentação de dados. Ao implementar o padrão <b>Strategy</b>, o sistema ganha flexibilidade
|
||||||
*
|
* para alternar entre diferentes formatos de codificação (JSON, Binário Nativo, XML, Protobuf)
|
||||||
* Implementations must ensure:
|
* sem necessidade de refatorização da lógica de rede.
|
||||||
* - Thread-safety if used in concurrent contexts
|
* <p>
|
||||||
* - Proper exception handling with meaningful error messages
|
* <b>Requisitos para Implementações:</b>
|
||||||
* - Preservation of object state during round-trip serialization
|
* <ul>
|
||||||
*
|
* <li><b>Thread-Safety:</b> As implementações devem ser seguras para uso concorrente, dado que
|
||||||
* @see JsonMessageSerializer
|
* instâncias únicas podem ser partilhadas por múltiplos <i>ClientHandlers</i>.</li>
|
||||||
|
* <li><b>Robustez:</b> Falhas de parsing devem resultar em exceções tipificadas ({@link SerializationException}),
|
||||||
|
* nunca em falhas silenciosas ou estados inconsistentes.</li>
|
||||||
|
* </ul>
|
||||||
|
* * @see JsonMessageSerializer
|
||||||
*/
|
*/
|
||||||
public interface MessageSerializer {
|
public interface MessageSerializer {
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Serializes an object into a byte array for transmission.
|
* Converte (Marshals) um objeto em memória para uma sequência de bytes para transmissão.
|
||||||
*
|
* * @param object O objeto de domínio a ser serializado (não pode ser nulo).
|
||||||
* @param object The object to serialize (must not be null)
|
* @return Um array de bytes contendo a representação codificada do objeto.
|
||||||
* @return A byte array containing the serialized representation
|
* @throws SerializationException Se ocorrer um erro durante a codificação (ex: ciclo de referências).
|
||||||
* @throws SerializationException If serialization fails
|
* @throws IllegalArgumentException Se o objeto fornecido for nulo.
|
||||||
* @throws IllegalArgumentException If object is null
|
|
||||||
*/
|
*/
|
||||||
byte[] serialize(Object object) throws SerializationException;
|
byte[] serialize(Object object) throws SerializationException;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Deserializes a byte array back into an object of the specified type.
|
* Reconstrói (Unmarshals) um objeto a partir de uma sequência de bytes.
|
||||||
*
|
* * @param <T> O tipo genérico do objeto esperado.
|
||||||
* @param <T> The expected type of the deserialized object
|
* @param data O array de bytes contendo os dados serializados (não pode ser nulo).
|
||||||
* @param data The byte array containing serialized data (must not be null)
|
* @param clazz A classe do tipo esperado para verificação e instancialização.
|
||||||
* @param clazz The class of the expected object type (must not be null)
|
* @return A instância do objeto reconstruído com o seu estado restaurado.
|
||||||
* @return The deserialized object
|
* @throws SerializationException Se os dados estiverem corrompidos ou incompatíveis com a classe alvo.
|
||||||
* @throws SerializationException If deserialization fails
|
* @throws IllegalArgumentException Se os dados ou a classe forem nulos.
|
||||||
* @throws IllegalArgumentException If data or clazz is null
|
|
||||||
*/
|
*/
|
||||||
<T> T deserialize(byte[] data, Class<T> clazz) throws SerializationException;
|
<T> T deserialize(byte[] data, Class<T> clazz) throws SerializationException;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Gets the name of this serialization strategy (e.g., "JSON", "Java Native").
|
* Obtém o identificador legível desta estratégia de serialização (ex: "JSON (Gson)", "Native").
|
||||||
* Useful for logging and debugging.
|
* Utilizado primariamente para logging, auditoria e negociação de conteúdo.
|
||||||
*
|
* * @return O nome descritivo do serializador.
|
||||||
* @return The serializer name
|
|
||||||
*/
|
*/
|
||||||
String getName();
|
String getName();
|
||||||
|
|
||||||
}
|
}
|
||||||
@@ -1,41 +1,40 @@
|
|||||||
package sd.serialization;
|
package sd.serialization;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Exception thrown when serialization or deserialization operations fail.
|
* Exceção verificada (Checked Exception) que sinaliza falhas no processo de transformação de dados.
|
||||||
*
|
* <p>
|
||||||
* This exception wraps underlying errors (I/O exceptions, parsing errors, etc.)
|
* Esta classe atua como um wrapper unificador para erros ocorridos na camada de serialização,
|
||||||
* and provides context about what went wrong during the serialization process.
|
* abstraindo falhas de baixo nível (como erros de I/O, sintaxe JSON inválida ou incompatibilidade
|
||||||
|
* de tipos) numa única exceção de domínio. Permite que o código cliente trate falhas de
|
||||||
|
* protocolo de forma consistente, independentemente da implementação subjacente (Gson, Nativa, etc.).
|
||||||
*/
|
*/
|
||||||
public class SerializationException extends Exception {
|
public class SerializationException extends Exception {
|
||||||
|
|
||||||
private static final long serialVersionUID = 1L; // Long(64bits) instead of int(32bits)
|
private static final long serialVersionUID = 1L; // Long(64bits) instead of int(32bits)
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Constructs a new serialization exception with the specified detail message.
|
* Constrói uma nova exceção de serialização com uma mensagem descritiva.
|
||||||
*
|
* * @param message A mensagem detalhando o erro.
|
||||||
* @param message The detail message
|
|
||||||
*/
|
*/
|
||||||
public SerializationException(String message) {
|
public SerializationException(String message) {
|
||||||
super(message);
|
super(message);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Constructs a new serialization exception with the specified detail message
|
* Constrói uma nova exceção encapsulando a causa raiz do problema.
|
||||||
* and cause.
|
* Útil para preservar a stack trace original de erros de bibliotecas terceiras (ex: Gson).
|
||||||
*
|
* * @param message A mensagem detalhando o erro.
|
||||||
* @param message The detail message
|
* @param cause A exceção original que causou a falha.
|
||||||
* @param cause The cause of this exception
|
|
||||||
*/
|
*/
|
||||||
public SerializationException(String message, Throwable cause) {
|
public SerializationException(String message, Throwable cause) {
|
||||||
super(message, cause);
|
super(message, cause);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Constructs a new serialization exception with the specified cause.
|
* Constrói uma nova exceção baseada apenas na causa raiz.
|
||||||
*
|
* * @param cause A exceção original.
|
||||||
* @param cause The cause of this exception
|
|
||||||
*/
|
*/
|
||||||
public SerializationException(Throwable cause) {
|
public SerializationException(Throwable cause) {
|
||||||
super(cause);
|
super(cause);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,14 +1,14 @@
|
|||||||
package sd.serialization;
|
package sd.serialization;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Factory for creating {@link MessageSerializer} instances.
|
* Fábrica estática (Factory Pattern) para instanciação controlada de {@link MessageSerializer}.
|
||||||
*
|
* <p>
|
||||||
* This factory provides a centralized way to create and configure JSON serializers
|
* Esta classe centraliza a criação de estratégias de serialização, garantindo consistência
|
||||||
* using Gson, making it easy to configure serialization throughout the application.
|
* de configuração em todo o sistema distribuído. Permite a injeção de configurações via
|
||||||
*
|
* Propriedades de Sistema (System Properties), facilitando a alternância entre modos de
|
||||||
* The factory can be configured via system properties for easy deployment configuration.
|
* depuração (Pretty Print) e produção (Compacto) sem recompilação.
|
||||||
*
|
* <p>
|
||||||
* Example usage:
|
* <b>Exemplo de Uso:</b>
|
||||||
* <pre>
|
* <pre>
|
||||||
* MessageSerializer serializer = SerializerFactory.createDefault();
|
* MessageSerializer serializer = SerializerFactory.createDefault();
|
||||||
* byte[] data = serializer.serialize(myObject);
|
* byte[] data = serializer.serialize(myObject);
|
||||||
@@ -17,28 +17,27 @@ package sd.serialization;
|
|||||||
public class SerializerFactory {
|
public class SerializerFactory {
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* System property key for enabling pretty-print in JSON serialization.
|
* Chave da propriedade de sistema para ativar a formatação JSON legível (Pretty Print).
|
||||||
* Set to "true" for debugging, "false" for production.
|
* Defina {@code -Dsd.serialization.json.prettyPrint=true} na JVM para ativar.
|
||||||
*/
|
*/
|
||||||
public static final String JSON_PRETTY_PRINT_PROPERTY = "sd.serialization.json.prettyPrint";
|
public static final String JSON_PRETTY_PRINT_PROPERTY = "sd.serialization.json.prettyPrint";
|
||||||
|
|
||||||
// Default configuration
|
// Default configuration (Production-ready)
|
||||||
private static final boolean DEFAULT_JSON_PRETTY_PRINT = false;
|
private static final boolean DEFAULT_JSON_PRETTY_PRINT = false;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Private constructor to prevent instantiation.
|
* Construtor privado para prevenir instanciação acidental desta classe utilitária.
|
||||||
*/
|
*/
|
||||||
private SerializerFactory() {
|
private SerializerFactory() {
|
||||||
throw new UnsupportedOperationException("Factory class cannot be instantiated");
|
throw new UnsupportedOperationException("Factory class cannot be instantiated");
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Creates a JSON serializer based on system configuration.
|
* Cria um serializador JSON configurado dinamicamente pelo ambiente.
|
||||||
*
|
* <p>
|
||||||
* Pretty-print is determined by checking the system property
|
* Verifica a propriedade de sistema {@value #JSON_PRETTY_PRINT_PROPERTY}.
|
||||||
* {@value #JSON_PRETTY_PRINT_PROPERTY}. If not set, defaults to false.
|
* Se não definida, assume o padrão de produção (falso/compacto).
|
||||||
*
|
* * @return Uma instância configurada de {@link JsonMessageSerializer}.
|
||||||
* @return A configured JsonMessageSerializer instance
|
|
||||||
*/
|
*/
|
||||||
public static MessageSerializer createDefault() {
|
public static MessageSerializer createDefault() {
|
||||||
boolean prettyPrint = Boolean.getBoolean(JSON_PRETTY_PRINT_PROPERTY);
|
boolean prettyPrint = Boolean.getBoolean(JSON_PRETTY_PRINT_PROPERTY);
|
||||||
@@ -46,21 +45,20 @@ public class SerializerFactory {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Creates a JSON serializer with default configuration (no pretty printing).
|
* Cria um serializador JSON com configuração padrão otimizada (sem indentação).
|
||||||
*
|
* Ideal para ambientes de produção onde a largura de banda é prioritária.
|
||||||
* @return A JsonMessageSerializer instance
|
* * @return Uma instância compacta de {@link JsonMessageSerializer}.
|
||||||
*/
|
*/
|
||||||
public static MessageSerializer createSerializer() {
|
public static MessageSerializer createSerializer() {
|
||||||
return createSerializer(DEFAULT_JSON_PRETTY_PRINT);
|
return createSerializer(DEFAULT_JSON_PRETTY_PRINT);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Creates a JSON serializer with specified pretty-print setting.
|
* Cria um serializador JSON com configuração explícita de formatação.
|
||||||
*
|
* * @param prettyPrint {@code true} para ativar indentação (Debug), {@code false} para compacto.
|
||||||
* @param prettyPrint Whether to enable pretty printing
|
* @return Uma instância personalizada de {@link JsonMessageSerializer}.
|
||||||
* @return A JsonMessageSerializer instance
|
|
||||||
*/
|
*/
|
||||||
public static MessageSerializer createSerializer(boolean prettyPrint) {
|
public static MessageSerializer createSerializer(boolean prettyPrint) {
|
||||||
return new JsonMessageSerializer(prettyPrint);
|
return new JsonMessageSerializer(prettyPrint);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -3,82 +3,88 @@ package sd.util;
|
|||||||
import java.util.Random;
|
import java.util.Random;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Utilitário para gerar valores aleatórios usados na simulação.
|
* Utilitário central de geração estocástica para a simulação.
|
||||||
*
|
* <p>
|
||||||
* <p>Fornece métodos estáticos para:</p>
|
* Esta classe fornece primitivas para geração de números pseudo-aleatórios, abstraindo
|
||||||
|
* a complexidade de distribuições estatísticas.
|
||||||
|
* <p>
|
||||||
|
* <b>Funcionalidades Principais:</b>
|
||||||
* <ul>
|
* <ul>
|
||||||
* <li>Gerar intervalos exponencialmente distribuídos (processos de Poisson)</li>
|
* <li><b>Modelagem de Poisson:</b> Geração de tempos entre chegadas usando distribuição exponencial inversa.</li>
|
||||||
* <li>Gerar inteiros e doubles aleatórios num intervalo</li>
|
* <li><b>Amostragem Uniforme:</b> Geração de inteiros e doubles em intervalos fechados/abertos.</li>
|
||||||
* <li>Tomar decisões baseadas em probabilidade</li>
|
* <li><b>Decisão Probabilística:</b> Avaliação de eventos booleanos baseados em pesos (Bernoulli trials).</li>
|
||||||
* <li>Escolher elementos aleatórios de um array</li>
|
* <li><b>Determinismo:</b> Suporte a sementes (seeds) manuais para reprodutibilidade exata de cenários de teste.</li>
|
||||||
* </ul>
|
* </ul>
|
||||||
*
|
|
||||||
* <p>Usa uma única instância estática de {@link Random}.</p>
|
|
||||||
*/
|
*/
|
||||||
public class RandomGenerator {
|
public class RandomGenerator {
|
||||||
|
|
||||||
/** Instância partilhada de Random para toda a simulação */
|
/** * Instância singleton estática do gerador PRNG (Pseudo-Random Number Generator).
|
||||||
|
* Thread-safe (java.util.Random é sincronizado), embora possa haver contenção em alta concorrência.
|
||||||
|
*/
|
||||||
private static final Random random = new Random();
|
private static final Random random = new Random();
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Retorna um intervalo de tempo que segue uma distribuição exponencial.
|
* Gera um intervalo de tempo seguindo uma Distribuição Exponencial.
|
||||||
*
|
* <p>
|
||||||
* <p>Componente essencial para modelar processos de Poisson, onde os
|
* Este método implementa o algoritmo de <i>Inverse Transform Sampling</i> para simular
|
||||||
* tempos entre chegadas seguem uma distribuição exponencial.</p>
|
* um Processo de Poisson homogêneo. É fundamental para modelar a chegada natural de
|
||||||
*
|
* veículos, onde eventos independentes ocorrem a uma taxa média constante.
|
||||||
* <p>Fórmula: {@code Time = -ln(1 - U) / λ}<br>
|
* <p>
|
||||||
* onde U é um número aleatório uniforme [0, 1) e λ (lambda) é a taxa média de chegada.</p>
|
* <b>Fórmula Matemática:</b> {@code T = -ln(1 - U) / λ}
|
||||||
|
* <br>Onde:
|
||||||
|
* <ul>
|
||||||
|
* <li>{@code U}: Variável aleatória uniforme no intervalo [0, 1).</li>
|
||||||
|
* <li>{@code λ (lambda)}: Taxa média de eventos por unidade de tempo (ex: veículos/segundo).</li>
|
||||||
|
* </ul>
|
||||||
*
|
*
|
||||||
* @param lambda taxa média de chegada λ (ex: 0.5 veículos por segundo)
|
* @param lambda A taxa média de chegada (λ > 0).
|
||||||
* @return intervalo de tempo (segundos) até à próxima chegada
|
* @return O intervalo de tempo (delta t) até o próximo evento, em segundos.
|
||||||
*/
|
*/
|
||||||
public static double generateExponentialInterval(double lambda) {
|
public static double generateExponentialInterval(double lambda) {
|
||||||
return Math.log(1 - random.nextDouble()) / -lambda;
|
return Math.log(1 - random.nextDouble()) / -lambda;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Retorna um inteiro aleatório entre {@code min} e {@code max}, inclusive.
|
* Gera um número inteiro uniformemente distribuído no intervalo fechado {@code [min, max]}.
|
||||||
*
|
*
|
||||||
* @param min valor mínimo possível
|
* @param min Limite inferior (inclusivo).
|
||||||
* @param max valor máximo possível
|
* @param max Limite superior (inclusivo).
|
||||||
* @return inteiro aleatório no intervalo [min, max]
|
* @return Um inteiro aleatório I tal que {@code min <= I <= max}.
|
||||||
*/
|
*/
|
||||||
public static int generateRandomInt(int min, int max) {
|
public static int generateRandomInt(int min, int max) {
|
||||||
return random.nextInt(max - min + 1) + min;
|
return random.nextInt(max - min + 1) + min;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Retorna um double aleatório entre {@code min} (inclusive) e {@code max} (exclusivo).
|
* Gera um número de ponto flutuante uniformemente distribuído no intervalo semi-aberto {@code [min, max)}.
|
||||||
*
|
*
|
||||||
* @param min valor mínimo possível
|
* @param min Limite inferior (inclusivo).
|
||||||
* @param max valor máximo possível
|
* @param max Limite superior (exclusivo).
|
||||||
* @return double aleatório no intervalo [min, max)
|
* @return Um double aleatório D tal que {@code min <= D < max}.
|
||||||
*/
|
*/
|
||||||
public static double generateRandomDouble(double min, double max) {
|
public static double generateRandomDouble(double min, double max) {
|
||||||
return min + (max - min) * random.nextDouble();
|
return min + (max - min) * random.nextDouble();
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Retorna {@code true} com uma dada probabilidade.
|
* Realiza um teste de Bernoulli (Sim/Não) com uma probabilidade de sucesso especificada.
|
||||||
*
|
* <p>
|
||||||
* <p>Útil para tomar decisões ponderadas. Por exemplo,
|
* Utilizado para decisões de ramificação estocástica (ex: "Este veículo é um camião?").
|
||||||
* {@code occursWithProbability(0.3)} retorna {@code true}
|
|
||||||
* aproximadamente 30% das vezes.</p>
|
|
||||||
*
|
*
|
||||||
* @param probability valor entre 0.0 (nunca) e 1.0 (sempre)
|
* @param probability A probabilidade de retorno {@code true} (0.0 a 1.0).
|
||||||
* @return {@code true} ou {@code false}, baseado na probabilidade
|
* @return {@code true} se o evento ocorrer, {@code false} caso contrário.
|
||||||
*/
|
*/
|
||||||
public static boolean occursWithProbability(double probability) {
|
public static boolean occursWithProbability(double probability) {
|
||||||
return random.nextDouble() < probability;
|
return random.nextDouble() < probability;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Escolhe um elemento aleatório do array fornecido.
|
* Seleciona aleatoriamente um elemento de um array genérico (Amostragem Uniforme Discreta).
|
||||||
*
|
*
|
||||||
* @param <T> tipo genérico do array
|
* @param <T> O tipo dos elementos no array.
|
||||||
* @param array array de onde escolher
|
* @param array A população de onde escolher.
|
||||||
* @return elemento selecionado aleatoriamente
|
* @return O elemento selecionado.
|
||||||
* @throws IllegalArgumentException se o array for null ou vazio
|
* @throws IllegalArgumentException Se o array for nulo ou vazio.
|
||||||
*/
|
*/
|
||||||
public static <T> T chooseRandom(T[] array) {
|
public static <T> T chooseRandom(T[] array) {
|
||||||
if (array == null || array.length == 0) {
|
if (array == null || array.length == 0) {
|
||||||
@@ -88,13 +94,13 @@ public class RandomGenerator {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Define a seed do gerador de números aleatórios partilhado.
|
* Reinicializa a semente (seed) do gerador global.
|
||||||
*
|
* <p>
|
||||||
* <p>Extremamente útil para debugging e testes, pois permite executar
|
* <b>Importância Crítica:</b> Permite tornar a simulação determinística. Ao fixar a seed,
|
||||||
* a simulação múltiplas vezes com a mesma sequência de eventos "aleatórios",
|
* a sequência de números "aleatórios" gerada será idêntica em execuções subsequentes,
|
||||||
* tornando os resultados reproduzíveis.</p>
|
* facilitando a depuração de race conditions ou lógica complexa.
|
||||||
*
|
*
|
||||||
* @param seed seed a usar
|
* @param seed O valor da semente inicial (ex: timestamp ou constante).
|
||||||
*/
|
*/
|
||||||
public static void setSeed(long seed) {
|
public static void setSeed(long seed) {
|
||||||
random.setSeed(seed);
|
random.setSeed(seed);
|
||||||
|
|||||||
@@ -9,55 +9,58 @@ import sd.model.VehicleType;
|
|||||||
import sd.routing.RouteSelector;
|
import sd.routing.RouteSelector;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Gera veículos para a simulação.
|
* Motor de injeção de carga (Load Injector) para a simulação de tráfego.
|
||||||
*
|
* <p>
|
||||||
* <p>Esta classe é responsável por duas tarefas principais:</p>
|
* Esta classe atua como uma fábrica estocástica de veículos, sendo responsável por:
|
||||||
* <ol>
|
* <ol>
|
||||||
* <li>Determinar <em>quando</em> o próximo veículo deve chegar, baseado no
|
* <li><b>Modelagem Temporal:</b> Determinar os instantes de chegada (Inter-arrival times)
|
||||||
* modelo de chegada (POISSON ou FIXED) da {@link SimulationConfig}</li>
|
* usando processos de Poisson (estocástico) ou intervalos determinísticos.</li>
|
||||||
* <li>Criar um novo objeto {@link Vehicle} com tipo e rota selecionados pela
|
* <li><b>Caracterização da Entidade:</b> Atribuir tipos de veículo (Bike, Light, Heavy)
|
||||||
* política de roteamento configurada ({@link RouteSelector})</li>
|
* baseado numa Distribuição de Probabilidade Cumulativa (CDF).</li>
|
||||||
|
* <li><b>Inicialização Espacial:</b> Distribuir a carga uniformemente entre os pontos de entrada (E1-E3).</li>
|
||||||
|
* <li><b>Atribuição de Rota:</b> Delegar a escolha do percurso à estratégia {@link RouteSelector} ativa.</li>
|
||||||
* </ol>
|
* </ol>
|
||||||
*
|
|
||||||
* <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 {
|
||||||
|
|
||||||
private final SimulationConfig config;
|
private final SimulationConfig config;
|
||||||
private final String arrivalModel;
|
private final String arrivalModel;
|
||||||
/** Lambda (λ) para modelo POISSON */
|
|
||||||
|
/** Parâmetro Lambda (λ) para a distribuição de Poisson (taxa de chegada). */
|
||||||
private final double arrivalRate;
|
private final double arrivalRate;
|
||||||
/** Intervalo para modelo FIXED */
|
|
||||||
|
/** Intervalo determinístico para geração constante (modo debug/teste). */
|
||||||
private final double fixedInterval;
|
private final double fixedInterval;
|
||||||
|
|
||||||
/** Política de roteamento usada para selecionar rotas */
|
/** * Estratégia de roteamento atual.
|
||||||
|
* Não é final para permitir Hot-Swapping durante a execução.
|
||||||
|
*/
|
||||||
private RouteSelector routeSelector;
|
private RouteSelector routeSelector;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Cria um novo gerador de veículos com a política de roteamento especificada.
|
* Inicializa o gerador com as configurações de simulação e estratégia de roteamento.
|
||||||
* Lê a configuração necessária.
|
|
||||||
*
|
*
|
||||||
* @param config objeto de {@link SimulationConfig}
|
* @param config A configuração global contendo as taxas e probabilidades.
|
||||||
* @param routeSelector política de roteamento a usar para selecionar rotas
|
* @param routeSelector A estratégia inicial de seleção de rotas.
|
||||||
*/
|
*/
|
||||||
public VehicleGenerator(SimulationConfig config, RouteSelector routeSelector) {
|
public VehicleGenerator(SimulationConfig config, RouteSelector routeSelector) {
|
||||||
this.config = config;
|
this.config = config;
|
||||||
this.routeSelector = routeSelector;
|
this.routeSelector = routeSelector;
|
||||||
|
|
||||||
// Cache configuration values for performance
|
// Cache de valores de configuração para evitar lookups repetitivos em hot-path
|
||||||
this.arrivalModel = config.getArrivalModel();
|
this.arrivalModel = config.getArrivalModel();
|
||||||
this.arrivalRate = config.getArrivalRate();
|
this.arrivalRate = config.getArrivalRate();
|
||||||
this.fixedInterval = config.getFixedArrivalInterval();
|
this.fixedInterval = config.getFixedArrivalInterval();
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Calcula o tempo <em>absoluto</em> da próxima chegada de veículo
|
* Calcula o timestamp absoluto para a próxima injeção de veículo.
|
||||||
* baseado no modelo configurado.
|
* <p>
|
||||||
*
|
* Se o modelo for "POISSON", utiliza a técnica de <i>Inverse Transform Sampling</i>
|
||||||
* @param currentTime tempo atual da simulação, usado como base
|
* (via {@link RandomGenerator}) para gerar intervalos exponencialmente distribuídos,
|
||||||
* @return tempo absoluto (ex: {@code currentTime + intervalo})
|
* simulando a aleatoriedade natural do tráfego.
|
||||||
* em que o próximo veículo deve ser gerado
|
* * @param currentTime O tempo atual da simulação (base de cálculo).
|
||||||
|
* @return O instante futuro (t + delta) para agendamento do evento de geração.
|
||||||
*/
|
*/
|
||||||
public double getNextArrivalTime(double currentTime) {
|
public double getNextArrivalTime(double currentTime) {
|
||||||
if ("POISSON".equalsIgnoreCase(arrivalModel)) {
|
if ("POISSON".equalsIgnoreCase(arrivalModel)) {
|
||||||
@@ -69,19 +72,19 @@ public class VehicleGenerator {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Gera um novo objeto {@link Vehicle}.
|
* Instancia (Spawn) um novo veículo configurado e roteado.
|
||||||
*
|
* <p>
|
||||||
* <p>Passos executados:</p>
|
* O processo de criação segue um pipeline:
|
||||||
* <ol>
|
* <ol>
|
||||||
* <li>Seleciona um {@link VehicleType} aleatório baseado em probabilidades</li>
|
* <li>Seleção de Tipo (Roda da Fortuna / CDF).</li>
|
||||||
* <li>Seleciona um ponto de entrada aleatório (E1, E2, E3)</li>
|
* <li>Seleção de Entrada (Uniforme).</li>
|
||||||
* <li>Usa a política de roteamento para escolher a rota</li>
|
* <li>Cálculo de Rota (Delegado ao Strategy).</li>
|
||||||
* </ol>
|
* </ol>
|
||||||
*
|
*
|
||||||
* @param vehicleId identificador único do novo veículo (ex: "V123")
|
* @param vehicleId O identificador único sequencial (ex: "V104").
|
||||||
* @param entryTime tempo de simulação em que o veículo é criado
|
* @param entryTime O timestamp de criação.
|
||||||
* @param queueSizes mapa com tamanho das filas (opcional, pode ser null)
|
* @param queueSizes Snapshot atual das filas (usado apenas por estratégias dinâmicas como LEAST_CONGESTED).
|
||||||
* @return novo objeto {@link Vehicle} configurado
|
* @return A entidade {@link Vehicle} pronta para inserção na malha.
|
||||||
*/
|
*/
|
||||||
public Vehicle generateVehicle(String vehicleId, double entryTime, Map<String, Integer> queueSizes) {
|
public Vehicle generateVehicle(String vehicleId, double entryTime, Map<String, Integer> queueSizes) {
|
||||||
VehicleType type = selectVehicleType();
|
VehicleType type = selectVehicleType();
|
||||||
@@ -92,18 +95,12 @@ public class VehicleGenerator {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Seleciona um {@link VehicleType} (BIKE, LIGHT, HEAVY) baseado nas
|
* Seleciona o tipo de veículo usando Amostragem por Probabilidade Cumulativa.
|
||||||
* probabilidades definidas na {@link SimulationConfig}.
|
* <p>
|
||||||
*
|
* Normaliza as probabilidades configuradas e mapeia um número aleatório [0, 1)
|
||||||
* <p>Usa técnica de "probabilidade cumulativa":</p>
|
* para o intervalo correspondente ao tipo de veículo.
|
||||||
* <ol>
|
|
||||||
* <li>Obtém número aleatório {@code rand} de [0, 1)</li>
|
|
||||||
* <li>Se {@code rand < P(Bike)}, retorna BIKE</li>
|
|
||||||
* <li>Senão se {@code rand < P(Bike) + P(Light)}, retorna LIGHT</li>
|
|
||||||
* <li>Caso contrário, retorna HEAVY</li>
|
|
||||||
* </ol>
|
|
||||||
*
|
*
|
||||||
* @return tipo de veículo selecionado
|
* @return O tipo enumerado {@link VehicleType} selecionado.
|
||||||
*/
|
*/
|
||||||
private VehicleType selectVehicleType() {
|
private VehicleType selectVehicleType() {
|
||||||
double bikeProbability = config.getBikeVehicleProbability();
|
double bikeProbability = config.getBikeVehicleProbability();
|
||||||
@@ -111,7 +108,9 @@ public class VehicleGenerator {
|
|||||||
double heavyProbability = config.getHeavyVehicleProbability();
|
double heavyProbability = config.getHeavyVehicleProbability();
|
||||||
|
|
||||||
double total = bikeProbability + lightProbability + heavyProbability;
|
double total = bikeProbability + lightProbability + heavyProbability;
|
||||||
if (total == 0) return VehicleType.LIGHT; // Avoid division by zero
|
if (total == 0) return VehicleType.LIGHT; // Fallback de segurança
|
||||||
|
|
||||||
|
// Normalização
|
||||||
bikeProbability /= total;
|
bikeProbability /= total;
|
||||||
lightProbability /= total;
|
lightProbability /= total;
|
||||||
|
|
||||||
@@ -127,10 +126,10 @@ public class VehicleGenerator {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Seleciona aleatoriamente um ponto de entrada (E1, E2 ou E3).
|
* Seleciona um ponto de injeção na borda da rede (Edge Node).
|
||||||
* Cada ponto tem probabilidade igual (1/3).
|
* Distribuição Uniforme: ~33.3% para cada entrada (E1, E2, E3).
|
||||||
*
|
*
|
||||||
* @return ponto de entrada selecionado ("E1", "E2" ou "E3")
|
* @return O ID da interseção de entrada.
|
||||||
*/
|
*/
|
||||||
private String selectRandomEntryPoint() {
|
private String selectRandomEntryPoint() {
|
||||||
double rand = Math.random();
|
double rand = Math.random();
|
||||||
@@ -145,23 +144,19 @@ public class VehicleGenerator {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Altera dinamicamente o RouteSelector usado para gerar rotas.
|
* Atualiza a estratégia de roteamento em tempo de execução (Hot-Swap).
|
||||||
* Permite mudar a política de roteamento durante a simulação.
|
* <p>
|
||||||
*
|
* Permite que o Coordenador altere o comportamento da frota (ex: de RANDOM para SHORTEST_PATH)
|
||||||
* @param newRouteSelector novo seletor de rotas
|
* sem necessidade de reiniciar a simulação.
|
||||||
|
* * @param newRouteSelector A nova implementação de estratégia a utilizar.
|
||||||
*/
|
*/
|
||||||
public void setRouteSelector(RouteSelector newRouteSelector) {
|
public void setRouteSelector(RouteSelector newRouteSelector) {
|
||||||
// Note: In Java, we can't directly modify the 'final' field,
|
this.routeSelector = newRouteSelector;
|
||||||
// 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.
|
* Retorna uma representação textual do estado interno do gerador.
|
||||||
|
* Útil para logs de auditoria e debugging.
|
||||||
*/
|
*/
|
||||||
public String getInfo() {
|
public String getInfo() {
|
||||||
return String.format(
|
return String.format(
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
/* Global Styles */
|
/* Global Styles */
|
||||||
.root {
|
.root {
|
||||||
-fx-background-color: #f4f7f6;
|
-fx-background-color: #2b2b2b;
|
||||||
-fx-font-family: 'Segoe UI', sans-serif;
|
-fx-font-family: 'Segoe UI', sans-serif;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -63,24 +63,24 @@
|
|||||||
|
|
||||||
/* Cards / Panels */
|
/* Cards / Panels */
|
||||||
.card {
|
.card {
|
||||||
-fx-background-color: white;
|
-fx-background-color: #1e1e1e;
|
||||||
-fx-background-radius: 8;
|
-fx-background-radius: 8;
|
||||||
-fx-effect: dropshadow(three-pass-box, rgba(0,0,0,0.05), 10, 0, 0, 2);
|
-fx-effect: dropshadow(three-pass-box, rgba(0,0,0,0.3), 10, 0, 0, 2);
|
||||||
-fx-padding: 0;
|
-fx-padding: 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
.card-header {
|
.card-header {
|
||||||
-fx-background-color: #ecf0f1;
|
-fx-background-color: #3a3a3a;
|
||||||
-fx-background-radius: 8 8 0 0;
|
-fx-background-radius: 8 8 0 0;
|
||||||
-fx-padding: 10 15;
|
-fx-padding: 10 15;
|
||||||
-fx-border-color: #bdc3c7;
|
-fx-border-color: #555555;
|
||||||
-fx-border-width: 0 0 1 0;
|
-fx-border-width: 0 0 1 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
.card-title {
|
.card-title {
|
||||||
-fx-font-size: 16px;
|
-fx-font-size: 16px;
|
||||||
-fx-font-weight: bold;
|
-fx-font-weight: bold;
|
||||||
-fx-text-fill: #2c3e50;
|
-fx-text-fill: white;
|
||||||
}
|
}
|
||||||
|
|
||||||
.card-content {
|
.card-content {
|
||||||
@@ -90,43 +90,48 @@
|
|||||||
/* Statistics Grid */
|
/* Statistics Grid */
|
||||||
.stat-label {
|
.stat-label {
|
||||||
-fx-font-size: 14px;
|
-fx-font-size: 14px;
|
||||||
-fx-text-fill: #7f8c8d;
|
-fx-text-fill: #cccccc;
|
||||||
}
|
}
|
||||||
|
|
||||||
.stat-value {
|
.stat-value {
|
||||||
-fx-font-size: 20px;
|
-fx-font-size: 20px;
|
||||||
-fx-font-weight: bold;
|
-fx-font-weight: bold;
|
||||||
-fx-text-fill: #2980b9;
|
-fx-text-fill: #4ca1af;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Tables */
|
/* Tables */
|
||||||
.table-view {
|
.table-view {
|
||||||
-fx-background-color: transparent;
|
-fx-background-color: #1e1e1e;
|
||||||
-fx-border-color: transparent;
|
-fx-border-color: transparent;
|
||||||
}
|
}
|
||||||
|
|
||||||
.table-view .column-header-background {
|
.table-view .column-header-background {
|
||||||
-fx-background-color: #ecf0f1;
|
-fx-background-color: #3a3a3a;
|
||||||
-fx-border-color: #bdc3c7;
|
-fx-border-color: #555555;
|
||||||
-fx-border-width: 0 0 1 0;
|
-fx-border-width: 0 0 1 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
.table-view .column-header .label {
|
.table-view .column-header .label {
|
||||||
-fx-text-fill: #2c3e50;
|
-fx-text-fill: white;
|
||||||
-fx-font-weight: bold;
|
-fx-font-weight: bold;
|
||||||
}
|
}
|
||||||
|
|
||||||
.table-row-cell {
|
.table-row-cell {
|
||||||
-fx-background-color: white;
|
-fx-background-color: #1e1e1e;
|
||||||
-fx-border-color: transparent;
|
-fx-border-color: transparent;
|
||||||
|
-fx-text-fill: white;
|
||||||
}
|
}
|
||||||
|
|
||||||
.table-row-cell:odd {
|
.table-row-cell:odd {
|
||||||
-fx-background-color: #f9f9f9;
|
-fx-background-color: #252525;
|
||||||
}
|
}
|
||||||
|
|
||||||
.table-row-cell:selected {
|
.table-row-cell:selected {
|
||||||
-fx-background-color: #3498db;
|
-fx-background-color: #4ca1af;
|
||||||
|
-fx-text-fill: white;
|
||||||
|
}
|
||||||
|
|
||||||
|
.table-cell {
|
||||||
-fx-text-fill: white;
|
-fx-text-fill: white;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,13 +1,4 @@
|
|||||||
# =========================================================
|
# Configuração de rede
|
||||||
# Traffic Simulation Configuration - HIGH LOAD SCENARIO
|
|
||||||
# ---------------------------------------------------------
|
|
||||||
# High traffic scenario for testing system under heavy load.
|
|
||||||
# Expected: Significant congestion, large queues, system stress test
|
|
||||||
# =========================================================
|
|
||||||
|
|
||||||
# === NETWORK CONFIGURATION ===
|
|
||||||
|
|
||||||
# Intersections (each with its host and port)
|
|
||||||
intersection.Cr1.host=localhost
|
intersection.Cr1.host=localhost
|
||||||
intersection.Cr1.port=8001
|
intersection.Cr1.port=8001
|
||||||
intersection.Cr2.host=localhost
|
intersection.Cr2.host=localhost
|
||||||
@@ -19,67 +10,48 @@ intersection.Cr4.port=8004
|
|||||||
intersection.Cr5.host=localhost
|
intersection.Cr5.host=localhost
|
||||||
intersection.Cr5.port=8005
|
intersection.Cr5.port=8005
|
||||||
|
|
||||||
# Exit node
|
|
||||||
exit.host=localhost
|
exit.host=localhost
|
||||||
exit.port=9001
|
exit.port=9001
|
||||||
|
|
||||||
# Dashboard server
|
|
||||||
dashboard.host=localhost
|
dashboard.host=localhost
|
||||||
dashboard.port=9000
|
dashboard.port=9000
|
||||||
|
|
||||||
|
# Configuração da simulação
|
||||||
# === SIMULATION CONFIGURATION ===
|
# Cenário de carga alta - tráfego pesado, teste de stress do sistema
|
||||||
|
|
||||||
# Total duration in seconds (1800 = 30 minutes)
|
|
||||||
simulation.duration=1800
|
simulation.duration=1800
|
||||||
|
|
||||||
# Vehicle arrival model: FIXED or POISSON
|
|
||||||
simulation.arrival.model=POISSON
|
simulation.arrival.model=POISSON
|
||||||
|
|
||||||
# λ (lambda): HIGH LOAD = 1.0 vehicle per second (60 vehicles/minute, 3600 vehicles/hour)
|
|
||||||
# This is 2x medium load - tests system capacity limits
|
|
||||||
simulation.arrival.rate=1.0
|
simulation.arrival.rate=1.0
|
||||||
|
|
||||||
# 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
|
simulation.routing.policy=LEAST_CONGESTED
|
||||||
|
|
||||||
|
# Tempos dos semáforos (tempos realistas do mundo real, sem fase amarela)
|
||||||
|
# Cruzamento 1 - ponto de entrada, verde mais longo
|
||||||
|
trafficlight.Cr1.South.green=45.0
|
||||||
|
trafficlight.Cr1.South.red=45.0
|
||||||
|
trafficlight.Cr1.East.green=45.0
|
||||||
|
trafficlight.Cr1.East.red=45.0
|
||||||
|
|
||||||
# === TRAFFIC LIGHT TIMINGS ===
|
# Cruzamento 2 - hub principal, gargalo crítico, tempos máximos de verde
|
||||||
# Format: trafficlight.<intersection>.<direction>.<state>=<seconds>
|
trafficlight.Cr2.South.green=50.0
|
||||||
# Aggressive timings to maximize throughput under high load
|
trafficlight.Cr2.South.red=50.0
|
||||||
|
trafficlight.Cr2.East.green=60.0
|
||||||
|
trafficlight.Cr2.East.red=40.0
|
||||||
|
trafficlight.Cr2.West.green=50.0
|
||||||
|
trafficlight.Cr2.West.red=50.0
|
||||||
|
|
||||||
# Intersection 1 (Entry point - longer greens to prevent early backup)
|
# Cruzamento 3 - caminho para a saída
|
||||||
trafficlight.Cr1.South.green=60.0
|
trafficlight.Cr3.South.green=40.0
|
||||||
trafficlight.Cr1.South.red=3.0
|
trafficlight.Cr3.South.red=45.0
|
||||||
trafficlight.Cr1.East.green=60.0
|
trafficlight.Cr3.West.green=45.0
|
||||||
trafficlight.Cr1.East.red=3.0
|
trafficlight.Cr3.West.red=40.0
|
||||||
|
|
||||||
# Intersection 2 (Main hub - CRITICAL BOTTLENECK, maximum green times)
|
# Cruzamento 4
|
||||||
# This is the most critical intersection - all routes converge here
|
trafficlight.Cr4.East.green=45.0
|
||||||
trafficlight.Cr2.South.green=70.0
|
trafficlight.Cr4.East.red=45.0
|
||||||
trafficlight.Cr2.South.red=3.0
|
trafficlight.Cr4.North.green=45.0
|
||||||
trafficlight.Cr2.East.green=80.0
|
trafficlight.Cr4.North.red=45.0
|
||||||
trafficlight.Cr2.East.red=3.0
|
|
||||||
trafficlight.Cr2.West.green=70.0
|
|
||||||
trafficlight.Cr2.West.red=3.0
|
|
||||||
|
|
||||||
# Intersection 3 (Path to exit - maximize East throughput to exit)
|
# Cruzamento 5 - perto da saída, gargalo principal
|
||||||
trafficlight.Cr3.South.green=50.0
|
|
||||||
trafficlight.Cr3.South.red=3.0
|
|
||||||
trafficlight.Cr3.West.green=40.0
|
|
||||||
trafficlight.Cr3.West.red=3.0
|
|
||||||
|
|
||||||
# Intersection 4 (High throughput needed toward Cr5)
|
|
||||||
trafficlight.Cr4.East.green=70.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)
|
|
||||||
# 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.green=70.0
|
||||||
@@ -87,40 +59,17 @@ trafficlight.Cr5.West.red=3.0
|
|||||||
trafficlight.Cr5.North.green=70.0
|
trafficlight.Cr5.North.green=70.0
|
||||||
trafficlight.Cr5.North.red=3.0
|
trafficlight.Cr5.North.red=3.0
|
||||||
|
|
||||||
|
# Configuração de veículos
|
||||||
# === VEHICLE CONFIGURATION ===
|
|
||||||
# Probability distribution for vehicle types (must sum to 1.0)
|
|
||||||
vehicle.probability.bike=0.2
|
vehicle.probability.bike=0.2
|
||||||
vehicle.probability.light=0.6
|
vehicle.probability.light=0.6
|
||||||
vehicle.probability.heavy=0.2
|
vehicle.probability.heavy=0.2
|
||||||
|
|
||||||
# Average crossing times (in seconds)
|
|
||||||
vehicle.crossing.time.bike=1.0
|
vehicle.crossing.time.bike=1.0
|
||||||
vehicle.crossing.time.light=2.0
|
vehicle.crossing.time.light=2.0
|
||||||
vehicle.crossing.time.heavy=4.0
|
vehicle.crossing.time.heavy=4.0
|
||||||
|
|
||||||
# Travel times between intersections (in seconds)
|
|
||||||
# Base time for light vehicles (cars)
|
|
||||||
vehicle.travel.time.base=1.0
|
vehicle.travel.time.base=1.0
|
||||||
# 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
|
|
||||||
vehicle.travel.time.heavy.multiplier=4.0
|
vehicle.travel.time.heavy.multiplier=4.0
|
||||||
|
|
||||||
# === STATISTICS ===
|
|
||||||
|
|
||||||
# Interval between dashboard updates (seconds)
|
|
||||||
statistics.update.interval=10.0
|
statistics.update.interval=10.0
|
||||||
|
|
||||||
# === EXPECTED BEHAVIOR - HIGH LOAD ===
|
|
||||||
# - Average system time: 200-400+ seconds (3-7+ minutes)
|
|
||||||
# - Maximum queue sizes: 15-30+ vehicles at Cr2 and Cr5
|
|
||||||
# - Average queue sizes: 8-15+ vehicles
|
|
||||||
# - Severe congestion at Cr2 (main convergence point)
|
|
||||||
# - Severe congestion at Cr5 (pre-exit bottleneck)
|
|
||||||
# - System utilization: ~80-95%
|
|
||||||
# - Many vehicles will remain in system at simulation end
|
|
||||||
# - Queue growth may be unbounded if arrival rate exceeds service rate
|
|
||||||
# - Primary bottlenecks: Cr2 (3-way convergence) and Cr5 (final funnel)
|
|
||||||
# - This scenario tests maximum system capacity and traffic light optimization
|
|
||||||
# - Expected to demonstrate need for adaptive traffic light policies
|
|
||||||
|
|||||||
@@ -1,13 +1,4 @@
|
|||||||
# =========================================================
|
# Configuração de rede
|
||||||
# Traffic Simulation Configuration - LOW LOAD SCENARIO
|
|
||||||
# ---------------------------------------------------------
|
|
||||||
# Low traffic scenario for testing system under light load.
|
|
||||||
# Expected: No congestion, minimal queues, fast vehicle throughput
|
|
||||||
# =========================================================
|
|
||||||
|
|
||||||
# === NETWORK CONFIGURATION ===
|
|
||||||
|
|
||||||
# Intersections (each with its host and port)
|
|
||||||
intersection.Cr1.host=localhost
|
intersection.Cr1.host=localhost
|
||||||
intersection.Cr1.port=8001
|
intersection.Cr1.port=8001
|
||||||
intersection.Cr2.host=localhost
|
intersection.Cr2.host=localhost
|
||||||
@@ -19,65 +10,48 @@ intersection.Cr4.port=8004
|
|||||||
intersection.Cr5.host=localhost
|
intersection.Cr5.host=localhost
|
||||||
intersection.Cr5.port=8005
|
intersection.Cr5.port=8005
|
||||||
|
|
||||||
# Exit node
|
|
||||||
exit.host=localhost
|
exit.host=localhost
|
||||||
exit.port=9001
|
exit.port=9001
|
||||||
|
|
||||||
# Dashboard server
|
|
||||||
dashboard.host=localhost
|
dashboard.host=localhost
|
||||||
dashboard.port=9000
|
dashboard.port=9000
|
||||||
|
|
||||||
|
# Configuração da simulação
|
||||||
# === SIMULATION CONFIGURATION ===
|
# Cenário de carga baixa - tráfego leve para testar o sistema sem congestionamento
|
||||||
|
|
||||||
# Total duration in seconds (1800 = 30 minutes)
|
|
||||||
simulation.duration=1800
|
simulation.duration=1800
|
||||||
|
|
||||||
# Vehicle arrival model: FIXED or POISSON
|
|
||||||
simulation.arrival.model=POISSON
|
simulation.arrival.model=POISSON
|
||||||
|
|
||||||
# λ (lambda): LOW LOAD = 0.2 vehicles per second (12 vehicles/minute, 720 vehicles/hour)
|
|
||||||
# This is approximately 40% of medium load
|
|
||||||
simulation.arrival.rate=0.2
|
simulation.arrival.rate=0.2
|
||||||
|
|
||||||
# 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
|
simulation.routing.policy=LEAST_CONGESTED
|
||||||
|
|
||||||
|
# Tempos dos semáforos (tempos realistas do mundo real, sem fase amarela)
|
||||||
# === TRAFFIC LIGHT TIMINGS ===
|
# Cruzamento 1 - ponto de entrada, equilibrado
|
||||||
# Format: trafficlight.<intersection>.<direction>.<state>=<seconds>
|
|
||||||
# Standard timings - should be more than adequate for low load
|
|
||||||
|
|
||||||
# Intersection 1 (Entry point - balanced)
|
|
||||||
trafficlight.Cr1.South.green=30.0
|
trafficlight.Cr1.South.green=30.0
|
||||||
trafficlight.Cr1.South.red=5.0
|
trafficlight.Cr1.South.red=30.0
|
||||||
trafficlight.Cr1.East.green=30.0
|
trafficlight.Cr1.East.green=30.0
|
||||||
trafficlight.Cr1.East.red=5.0
|
trafficlight.Cr1.East.red=30.0
|
||||||
|
|
||||||
# Intersection 2 (Main hub - shorter cycles, favor East-West)
|
# Cruzamento 2 - hub principal
|
||||||
trafficlight.Cr2.South.green=30.0
|
trafficlight.Cr2.South.green=30.0
|
||||||
trafficlight.Cr2.South.red=5.0
|
trafficlight.Cr2.South.red=30.0
|
||||||
trafficlight.Cr2.East.green=30.0
|
trafficlight.Cr2.East.green=30.0
|
||||||
trafficlight.Cr2.East.red=5.0
|
trafficlight.Cr2.East.red=30.0
|
||||||
trafficlight.Cr2.West.green=30.0
|
trafficlight.Cr2.West.green=30.0
|
||||||
trafficlight.Cr2.West.red=5.0
|
trafficlight.Cr2.West.red=30.0
|
||||||
|
|
||||||
# Intersection 3 (Path to exit - favor East)
|
# Cruzamento 3 - caminho para a saída
|
||||||
trafficlight.Cr3.South.green=30.0
|
trafficlight.Cr3.South.green=30.0
|
||||||
trafficlight.Cr3.South.red=5.0
|
trafficlight.Cr3.South.red=30.0
|
||||||
trafficlight.Cr3.West.green=30.0
|
trafficlight.Cr3.West.green=30.0
|
||||||
trafficlight.Cr3.West.red=5.0
|
trafficlight.Cr3.West.red=30.0
|
||||||
|
|
||||||
# Intersection 4 (Favor East toward Cr5)
|
# Cruzamento 4
|
||||||
trafficlight.Cr4.East.green=30.0
|
trafficlight.Cr4.East.green=30.0
|
||||||
trafficlight.Cr4.East.red=5.0
|
trafficlight.Cr4.East.red=30.0
|
||||||
trafficlight.Cr4.North.green=30.0
|
trafficlight.Cr4.North.green=30.0
|
||||||
trafficlight.Cr4.North.red=5.0
|
trafficlight.Cr4.North.red=30.0
|
||||||
|
|
||||||
# Intersection 5 (Near exit - favor East)
|
# Cruzamento 5 - perto da saída
|
||||||
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.green=30.0
|
||||||
@@ -85,36 +59,17 @@ trafficlight.Cr5.West.red=5.0
|
|||||||
trafficlight.Cr5.North.green=30.0
|
trafficlight.Cr5.North.green=30.0
|
||||||
trafficlight.Cr5.North.red=5.0
|
trafficlight.Cr5.North.red=5.0
|
||||||
|
|
||||||
|
# Configuração de veículos
|
||||||
# === VEHICLE CONFIGURATION ===
|
|
||||||
# Probability distribution for vehicle types (must sum to 1.0)
|
|
||||||
vehicle.probability.bike=0.2
|
vehicle.probability.bike=0.2
|
||||||
vehicle.probability.light=0.6
|
vehicle.probability.light=0.6
|
||||||
vehicle.probability.heavy=0.2
|
vehicle.probability.heavy=0.2
|
||||||
|
|
||||||
# Average crossing times (in seconds)
|
|
||||||
vehicle.crossing.time.bike=1.0
|
vehicle.crossing.time.bike=1.0
|
||||||
vehicle.crossing.time.light=2.0
|
vehicle.crossing.time.light=2.0
|
||||||
vehicle.crossing.time.heavy=4.0
|
vehicle.crossing.time.heavy=4.0
|
||||||
|
|
||||||
# Travel times between intersections (in seconds)
|
|
||||||
# Base time for light vehicles (cars)
|
|
||||||
vehicle.travel.time.base=1.0
|
vehicle.travel.time.base=1.0
|
||||||
# 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
|
|
||||||
vehicle.travel.time.heavy.multiplier=4.0
|
vehicle.travel.time.heavy.multiplier=4.0
|
||||||
|
|
||||||
# === STATISTICS ===
|
|
||||||
|
|
||||||
# Interval between dashboard updates (seconds)
|
|
||||||
statistics.update.interval=10.0
|
statistics.update.interval=10.0
|
||||||
|
|
||||||
# === EXPECTED BEHAVIOR - LOW LOAD ===
|
|
||||||
# - Average system time: 40-80 seconds
|
|
||||||
# - Maximum queue sizes: 1-3 vehicles
|
|
||||||
# - Average queue sizes: < 1 vehicle
|
|
||||||
# - Vehicles should flow smoothly through the system
|
|
||||||
# - Minimal waiting at traffic lights (mostly travel time)
|
|
||||||
# - System utilization: ~20-30%
|
|
||||||
# - All vehicles should exit within simulation time
|
|
||||||
|
|||||||
@@ -1,13 +1,4 @@
|
|||||||
# =========================================================
|
# Configuração de rede
|
||||||
# Traffic Simulation Configuration - MEDIUM LOAD SCENARIO
|
|
||||||
# ---------------------------------------------------------
|
|
||||||
# Medium traffic scenario for testing system under normal load.
|
|
||||||
# Expected: Moderate queues, some congestion at peak intersections
|
|
||||||
# =========================================================
|
|
||||||
|
|
||||||
# === NETWORK CONFIGURATION ===
|
|
||||||
|
|
||||||
# Intersections (each with its host and port)
|
|
||||||
intersection.Cr1.host=localhost
|
intersection.Cr1.host=localhost
|
||||||
intersection.Cr1.port=8001
|
intersection.Cr1.port=8001
|
||||||
intersection.Cr2.host=localhost
|
intersection.Cr2.host=localhost
|
||||||
@@ -19,65 +10,48 @@ intersection.Cr4.port=8004
|
|||||||
intersection.Cr5.host=localhost
|
intersection.Cr5.host=localhost
|
||||||
intersection.Cr5.port=8005
|
intersection.Cr5.port=8005
|
||||||
|
|
||||||
# Exit node
|
|
||||||
exit.host=localhost
|
exit.host=localhost
|
||||||
exit.port=9001
|
exit.port=9001
|
||||||
|
|
||||||
# Dashboard server
|
|
||||||
dashboard.host=localhost
|
dashboard.host=localhost
|
||||||
dashboard.port=9000
|
dashboard.port=9000
|
||||||
|
|
||||||
|
# Configuração da simulação
|
||||||
# === SIMULATION CONFIGURATION ===
|
# Cenário de carga média - tráfego normal com algum congestionamento
|
||||||
|
|
||||||
# Total duration in seconds (1800 = 30 minutes)
|
|
||||||
simulation.duration=1800
|
simulation.duration=1800
|
||||||
|
|
||||||
# Vehicle arrival model: FIXED or POISSON
|
|
||||||
simulation.arrival.model=POISSON
|
simulation.arrival.model=POISSON
|
||||||
|
|
||||||
# λ (lambda): MEDIUM LOAD = 0.5 vehicles per second (30 vehicles/minute, 1800 vehicles/hour)
|
|
||||||
# This represents normal traffic conditions
|
|
||||||
simulation.arrival.rate=0.5
|
simulation.arrival.rate=0.5
|
||||||
|
|
||||||
# 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
|
simulation.routing.policy=LEAST_CONGESTED
|
||||||
|
|
||||||
|
# Tempos dos semáforos (tempos realistas do mundo real, sem fase amarela)
|
||||||
|
# Cruzamento 1 - ponto de entrada, equilibrado
|
||||||
|
trafficlight.Cr1.South.green=35.0
|
||||||
|
trafficlight.Cr1.South.red=35.0
|
||||||
|
trafficlight.Cr1.East.green=35.0
|
||||||
|
trafficlight.Cr1.East.red=35.0
|
||||||
|
|
||||||
# === TRAFFIC LIGHT TIMINGS ===
|
# Cruzamento 2 - hub principal, gargalo crítico
|
||||||
# Format: trafficlight.<intersection>.<direction>.<state>=<seconds>
|
trafficlight.Cr2.South.green=40.0
|
||||||
# Optimized timings for medium load
|
trafficlight.Cr2.South.red=40.0
|
||||||
|
trafficlight.Cr2.East.green=45.0
|
||||||
|
trafficlight.Cr2.East.red=35.0
|
||||||
|
trafficlight.Cr2.West.green=40.0
|
||||||
|
trafficlight.Cr2.West.red=40.0
|
||||||
|
|
||||||
# Intersection 1 (Entry point - balanced)
|
# Cruzamento 3 - caminho para a saída
|
||||||
trafficlight.Cr1.South.green=40.0
|
trafficlight.Cr3.South.green=35.0
|
||||||
trafficlight.Cr1.South.red=5.0
|
trafficlight.Cr3.South.red=40.0
|
||||||
trafficlight.Cr1.East.green=40.0
|
trafficlight.Cr3.West.green=40.0
|
||||||
trafficlight.Cr1.East.red=5.0
|
trafficlight.Cr3.West.red=35.0
|
||||||
|
|
||||||
# Intersection 2 (Main hub - CRITICAL BOTTLENECK, longer green times)
|
# Cruzamento 4
|
||||||
trafficlight.Cr2.South.green=45.0
|
trafficlight.Cr4.East.green=35.0
|
||||||
trafficlight.Cr2.South.red=5.0
|
trafficlight.Cr4.East.red=35.0
|
||||||
trafficlight.Cr2.East.green=50.0
|
trafficlight.Cr4.North.green=35.0
|
||||||
trafficlight.Cr2.East.red=5.0
|
trafficlight.Cr4.North.red=35.0
|
||||||
trafficlight.Cr2.West.green=45.0
|
|
||||||
trafficlight.Cr2.West.red=5.0
|
|
||||||
|
|
||||||
# Intersection 3 (Path to exit - favor East toward exit)
|
# Cruzamento 5 - perto da saída, possível gargalo
|
||||||
trafficlight.Cr3.South.green=40.0
|
|
||||||
trafficlight.Cr3.South.red=5.0
|
|
||||||
trafficlight.Cr3.West.green=35.0
|
|
||||||
trafficlight.Cr3.West.red=5.0
|
|
||||||
|
|
||||||
# Intersection 4 (Favor East toward Cr5)
|
|
||||||
trafficlight.Cr4.East.green=40.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)
|
|
||||||
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.green=45.0
|
||||||
@@ -85,37 +59,17 @@ trafficlight.Cr5.West.red=5.0
|
|||||||
trafficlight.Cr5.North.green=45.0
|
trafficlight.Cr5.North.green=45.0
|
||||||
trafficlight.Cr5.North.red=5.0
|
trafficlight.Cr5.North.red=5.0
|
||||||
|
|
||||||
|
# Configuração de veículos
|
||||||
# === VEHICLE CONFIGURATION ===
|
|
||||||
# Probability distribution for vehicle types (must sum to 1.0)
|
|
||||||
vehicle.probability.bike=0.2
|
vehicle.probability.bike=0.2
|
||||||
vehicle.probability.light=0.6
|
vehicle.probability.light=0.6
|
||||||
vehicle.probability.heavy=0.2
|
vehicle.probability.heavy=0.2
|
||||||
|
|
||||||
# Average crossing times (in seconds)
|
|
||||||
vehicle.crossing.time.bike=1.0
|
vehicle.crossing.time.bike=1.0
|
||||||
vehicle.crossing.time.light=2.0
|
vehicle.crossing.time.light=2.0
|
||||||
vehicle.crossing.time.heavy=4.0
|
vehicle.crossing.time.heavy=4.0
|
||||||
|
|
||||||
# Travel times between intersections (in seconds)
|
|
||||||
# Base time for light vehicles (cars)
|
|
||||||
vehicle.travel.time.base=1.0
|
vehicle.travel.time.base=1.0
|
||||||
# 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
|
|
||||||
vehicle.travel.time.heavy.multiplier=4.0
|
vehicle.travel.time.heavy.multiplier=4.0
|
||||||
|
|
||||||
# === STATISTICS ===
|
|
||||||
|
|
||||||
# Interval between dashboard updates (seconds)
|
|
||||||
statistics.update.interval=10.0
|
statistics.update.interval=10.0
|
||||||
|
|
||||||
# === EXPECTED BEHAVIOR - MEDIUM LOAD ===
|
|
||||||
# - Average system time: 80-150 seconds
|
|
||||||
# - Maximum queue sizes: 5-10 vehicles at Cr2 and Cr5
|
|
||||||
# - Average queue sizes: 2-5 vehicles
|
|
||||||
# - Moderate congestion at Cr2 (main hub) and Cr5 (pre-exit)
|
|
||||||
# - System utilization: ~50-60%
|
|
||||||
# - Most vehicles should exit, some may remain at simulation end
|
|
||||||
# - Cr2 is the primary bottleneck (3 directions converge)
|
|
||||||
# - Cr5 is secondary bottleneck (all routes pass through)
|
|
||||||
|
|||||||
@@ -1,13 +1,4 @@
|
|||||||
# =========================================================
|
# Configuração de rede
|
||||||
# Traffic Simulation Configuration
|
|
||||||
# ---------------------------------------------------------
|
|
||||||
# All parameters controlling network layout, timing,
|
|
||||||
# and simulation behavior.
|
|
||||||
# =========================================================
|
|
||||||
|
|
||||||
# === NETWORK CONFIGURATION ===
|
|
||||||
|
|
||||||
# Intersections (each with its host and port)
|
|
||||||
intersection.Cr1.host=localhost
|
intersection.Cr1.host=localhost
|
||||||
intersection.Cr1.port=8001
|
intersection.Cr1.port=8001
|
||||||
intersection.Cr2.host=localhost
|
intersection.Cr2.host=localhost
|
||||||
@@ -19,92 +10,60 @@ intersection.Cr4.port=8004
|
|||||||
intersection.Cr5.host=localhost
|
intersection.Cr5.host=localhost
|
||||||
intersection.Cr5.port=8005
|
intersection.Cr5.port=8005
|
||||||
|
|
||||||
# Exit node
|
|
||||||
exit.host=localhost
|
exit.host=localhost
|
||||||
exit.port=9001
|
exit.port=9001
|
||||||
|
|
||||||
# Dashboard server
|
|
||||||
dashboard.host=localhost
|
dashboard.host=localhost
|
||||||
dashboard.port=9000
|
dashboard.port=9000
|
||||||
|
|
||||||
|
# Configuração da simulação
|
||||||
# === SIMULATION CONFIGURATION ===
|
|
||||||
|
|
||||||
# Total duration in seconds (3600 = 1 hour)
|
|
||||||
simulation.duration=300
|
simulation.duration=300
|
||||||
|
|
||||||
# Time scaling factor for visualization (real_seconds = sim_seconds * scale)
|
|
||||||
# 0 = instant (pure DES), 0.01 = 100x speed, 0.1 = 10x speed, 1.0 = real-time
|
|
||||||
simulation.time.scale=0.01
|
simulation.time.scale=0.01
|
||||||
|
|
||||||
# Vehicle arrival model: FIXED or POISSON
|
|
||||||
simulation.arrival.model=POISSON
|
simulation.arrival.model=POISSON
|
||||||
|
|
||||||
# λ (lambda): average arrival rate (vehicles per second)
|
|
||||||
simulation.arrival.rate=0.5
|
simulation.arrival.rate=0.5
|
||||||
|
|
||||||
# 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
|
simulation.routing.policy=RANDOM
|
||||||
|
|
||||||
|
# Tempos dos semáforos (tempos realistas do mundo real, sem fase amarela)
|
||||||
|
# Cruzamento 1 - ponto de entrada, equilibrado
|
||||||
|
trafficlight.Cr1.South.green=35.0
|
||||||
|
trafficlight.Cr1.South.red=35.0
|
||||||
|
trafficlight.Cr1.East.green=35.0
|
||||||
|
trafficlight.Cr1.East.red=35.0
|
||||||
|
|
||||||
# === TRAFFIC LIGHT TIMINGS ===
|
# Cruzamento 2 - hub principal
|
||||||
# Format: trafficlight.<intersection>.<direction>.<state>=<seconds>
|
trafficlight.Cr2.South.green=40.0
|
||||||
|
trafficlight.Cr2.South.red=40.0
|
||||||
|
trafficlight.Cr2.East.green=40.0
|
||||||
|
trafficlight.Cr2.East.red=40.0
|
||||||
|
trafficlight.Cr2.West.green=40.0
|
||||||
|
trafficlight.Cr2.West.red=40.0
|
||||||
|
|
||||||
# Intersection 1 (Entry point - balanced)
|
# Cruzamento 3 - caminho para a saída
|
||||||
trafficlight.Cr1.South.green=60.0
|
trafficlight.Cr3.South.green=35.0
|
||||||
trafficlight.Cr1.South.red=5.0
|
trafficlight.Cr3.South.red=40.0
|
||||||
trafficlight.Cr1.East.green=60.0
|
trafficlight.Cr3.West.green=40.0
|
||||||
trafficlight.Cr1.East.red=5.0
|
trafficlight.Cr3.West.red=35.0
|
||||||
|
|
||||||
# Intersection 2 (Main hub - shorter cycles, favor East-West)
|
# Cruzamento 4
|
||||||
trafficlight.Cr2.South.green=60.0
|
trafficlight.Cr4.East.green=35.0
|
||||||
trafficlight.Cr2.South.red=5.0
|
trafficlight.Cr4.East.red=35.0
|
||||||
trafficlight.Cr2.East.green=60.0
|
|
||||||
trafficlight.Cr2.East.red=5.0
|
|
||||||
trafficlight.Cr2.West.green=60.0
|
|
||||||
trafficlight.Cr2.West.red=5.0
|
|
||||||
|
|
||||||
# Intersection 3 (Path to exit - favor East)
|
# Cruzamento 5 - perto da saída
|
||||||
trafficlight.Cr3.South.green=60.0
|
trafficlight.Cr5.East.green=35.0
|
||||||
trafficlight.Cr3.South.red=5.0
|
trafficlight.Cr5.East.red=35.0
|
||||||
trafficlight.Cr3.West.green=60.0
|
|
||||||
trafficlight.Cr3.West.red=5.0
|
|
||||||
|
|
||||||
# Intersection 4 (Favor East toward Cr5)
|
# Configuração de veículos
|
||||||
trafficlight.Cr4.East.green=60.0
|
|
||||||
trafficlight.Cr4.East.red=5.0
|
|
||||||
|
|
||||||
# Intersection 5 (Near exit - favor East)
|
|
||||||
trafficlight.Cr5.East.green=60.0
|
|
||||||
trafficlight.Cr5.East.red=5.0
|
|
||||||
|
|
||||||
|
|
||||||
# === VEHICLE CONFIGURATION ===
|
|
||||||
# Probability distribution for vehicle types (must sum to 1.0)
|
|
||||||
vehicle.probability.bike=0.2
|
vehicle.probability.bike=0.2
|
||||||
vehicle.probability.light=0.6
|
vehicle.probability.light=0.6
|
||||||
vehicle.probability.heavy=0.2
|
vehicle.probability.heavy=0.2
|
||||||
|
|
||||||
# Average crossing times (in seconds)
|
|
||||||
vehicle.crossing.time.bike=1.0
|
vehicle.crossing.time.bike=1.0
|
||||||
vehicle.crossing.time.light=2.0
|
vehicle.crossing.time.light=2.0
|
||||||
vehicle.crossing.time.heavy=4.0
|
vehicle.crossing.time.heavy=4.0
|
||||||
|
|
||||||
# Travel times between intersections (in seconds)
|
|
||||||
# Base time for light vehicles (cars)
|
|
||||||
vehicle.travel.time.base=1.0
|
vehicle.travel.time.base=1.0
|
||||||
# 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
|
|
||||||
vehicle.travel.time.heavy.multiplier=4.0
|
vehicle.travel.time.heavy.multiplier=4.0
|
||||||
|
|
||||||
# === STATISTICS ===
|
|
||||||
|
|
||||||
# Interval between dashboard updates (seconds)
|
|
||||||
statistics.update.interval=0.1
|
statistics.update.interval=0.1
|
||||||
|
|||||||
1055
main/testing.txt
186
report.tex
Normal file
@@ -0,0 +1,186 @@
|
|||||||
|
\documentclass[a4paper,11pt]{article}
|
||||||
|
|
||||||
|
% codificação
|
||||||
|
\usepackage[utf8]{inputenc}
|
||||||
|
\usepackage[T1]{fontenc}
|
||||||
|
|
||||||
|
% layout
|
||||||
|
\usepackage[top=2.5cm, bottom=2.5cm, left=2.5cm, right=2.5cm]{geometry}
|
||||||
|
\usepackage{parskip} % Espaçamento entre parágrafos sem indentação
|
||||||
|
\usepackage{titlesec} % Personalização de títulos
|
||||||
|
|
||||||
|
% cor/estilo
|
||||||
|
\usepackage{xcolor}
|
||||||
|
\definecolor{navyblue}{RGB}{0, 40, 85}
|
||||||
|
\definecolor{codegray}{rgb}{0.95,0.95,0.95}
|
||||||
|
\definecolor{accent}{RGB}{0, 100, 180}
|
||||||
|
|
||||||
|
\usepackage{hyperref}
|
||||||
|
|
||||||
|
\hypersetup{
|
||||||
|
pdftitle={Relatório de Correção de Regressão de Desempenho em Linux},
|
||||||
|
pdfauthor={Leandro Afonso},
|
||||||
|
pdfsubject={Análise Técnica},
|
||||||
|
pdfkeywords={Linux, Java, Latency, Syscall, Optimization},
|
||||||
|
pdfcreator={pdfLaTeX}
|
||||||
|
}
|
||||||
|
|
||||||
|
% data
|
||||||
|
\renewcommand{\today}{%
|
||||||
|
\number\day\ de %
|
||||||
|
\ifcase\month\or
|
||||||
|
Janeiro\or Fevereiro\or Março\or Abril\or Maio\or Junho\or
|
||||||
|
Julho\or Agosto\or Setembro\or Outubro\or Novembro\or Dezembro%
|
||||||
|
\fi
|
||||||
|
\ de \number\year%
|
||||||
|
}
|
||||||
|
|
||||||
|
% tabelas
|
||||||
|
\usepackage{booktabs}
|
||||||
|
\usepackage{array}
|
||||||
|
|
||||||
|
% conf
|
||||||
|
\usepackage{listings}
|
||||||
|
\lstset{
|
||||||
|
backgroundcolor=\color{codegray},
|
||||||
|
basicstyle=\ttfamily\small,
|
||||||
|
breakatwhitespace=false,
|
||||||
|
breaklines=true,
|
||||||
|
captionpos=b,
|
||||||
|
commentstyle=\color{green!50!black},
|
||||||
|
keywordstyle=\color{blue},
|
||||||
|
stringstyle=\color{red},
|
||||||
|
frame=single,
|
||||||
|
rulecolor=\color{black!20},
|
||||||
|
numbers=left,
|
||||||
|
numberstyle=\tiny\color{gray},
|
||||||
|
stepnumber=1,
|
||||||
|
tabsize=4,
|
||||||
|
showstringspaces=false
|
||||||
|
extendedchars=true,
|
||||||
|
literate={á}{{\'a}}1 {ã}{{\~a}}1 {é}{{\'e}}1 {ç}{{\c{c}}}1 {í}{{\'i}}1 {ó}{{\'o}}1 {õ}{{\~o}}1 {ú}{{\'u}}1 {µ}{{\ensuremath{\mu}}}1 {€}{{\euro}}1,
|
||||||
|
}
|
||||||
|
|
||||||
|
% seccões
|
||||||
|
\titleformat{\section}
|
||||||
|
{\color{navyblue}\normalfont\Large\bfseries}
|
||||||
|
{\thesection}{1em}{}
|
||||||
|
|
||||||
|
\titleformat{\subsection}
|
||||||
|
{\color{navyblue}\normalfont\large\bfseries}
|
||||||
|
{\thesubsection}{1em}{}
|
||||||
|
|
||||||
|
% metadados
|
||||||
|
\title{\textbf{\color{navyblue}Relatório de Correção de Regressão de Desempenho em Linux}}
|
||||||
|
\author{Leandro Afonso}
|
||||||
|
\date{\today}
|
||||||
|
|
||||||
|
\begin{document}
|
||||||
|
|
||||||
|
\maketitle
|
||||||
|
|
||||||
|
\section{Resumo do Problema}
|
||||||
|
A simulação distribuída de tráfego demonstrou uma regressão significativa de desempenho em ambiente Linux nativo quando comparada com a execução em Windows/Wine.
|
||||||
|
|
||||||
|
A tabela abaixo ilustra a discrepância nas taxas de conclusão de veículos dentro da janela de simulação fixa:
|
||||||
|
|
||||||
|
\begin{table}[h]
|
||||||
|
\centering
|
||||||
|
\begin{tabular}{@{}lc@{}}
|
||||||
|
\toprule
|
||||||
|
\textbf{Ambiente} & \textbf{Taxa de Conclusão} \\
|
||||||
|
\midrule
|
||||||
|
Windows / Wine & $\sim 95-100\%$ \\
|
||||||
|
Linux (OpenJDK Nativo) & $\sim 44\%$ \\
|
||||||
|
Linux (com \texttt{strace}) & $\sim 91\%$ \\
|
||||||
|
\bottomrule
|
||||||
|
\end{tabular}
|
||||||
|
\caption{Comparação de desempenho por ambiente.}
|
||||||
|
\end{table}
|
||||||
|
|
||||||
|
O \textit{insight} crucial surgiu ao descobrir que a execução sob \texttt{strace} recuperava a taxa de conclusão para 91\%. O \texttt{strace} introduz \textit{overhead} em cada \textit{syscall}, o que, paradoxalmente, estabilizou o sistema ao forçar um abrandamento natural (\textit{throttling}).
|
||||||
|
|
||||||
|
\section{Causa Raiz}
|
||||||
|
\textbf{O Linux executa demasiado rápido.}
|
||||||
|
|
||||||
|
O Coordenador gera veículos a uma velocidade superior à capacidade de processamento das interseções distribuídas e da pilha de rede. Em Windows/Wine, o \textit{overhead} inerente à emulação e ao agendador do SO limita naturalmente a taxa de transferência do sistema.
|
||||||
|
|
||||||
|
Em Linux nativo, a execução mais célere provoca uma condição de corrida sistémica:
|
||||||
|
\begin{itemize}
|
||||||
|
\item A geração de veículos excede a capacidade de processamento imediato dos nós.
|
||||||
|
\item As filas de eventos congestionam (\textit{back up}) rapidamente nas interseções.
|
||||||
|
\item Veículos gerados tardiamente não dispõem de tempo de CPU suficiente para concluir o percurso antes do fim da simulação.
|
||||||
|
\end{itemize}
|
||||||
|
|
||||||
|
\section{Solução Implementada}
|
||||||
|
A correção consistiu na introdução de micro-atrasos (\textit{micro-throttles}) utilizando \texttt{LockSupport.parkNanos()}. Esta abordagem simula o \textit{overhead} natural presente no ambiente Windows, permitindo o escoamento das filas de E/S.
|
||||||
|
|
||||||
|
\subsection{Alterações no Código}
|
||||||
|
|
||||||
|
\textbf{1. Ficheiro: \texttt{SocketConnection.java}} \\
|
||||||
|
Adicionado um atraso de 50$\mu$s após operações de E/S para permitir o processamento da pilha TCP.
|
||||||
|
|
||||||
|
\begin{lstlisting}[language=Java, title={SocketConnection.java (Excerto)}]
|
||||||
|
// Em sendMessage() após o flush:
|
||||||
|
dataOut.flush();
|
||||||
|
LockSupport.parkNanos(50000); // 50 us delay
|
||||||
|
|
||||||
|
// Em receiveMessage() após readFully:
|
||||||
|
dataIn.readFully(data);
|
||||||
|
LockSupport.parkNanos(50000); // 50 us delay
|
||||||
|
\end{lstlisting}
|
||||||
|
|
||||||
|
\textbf{2. Ficheiro: \texttt{CoordinatorProcess.java}} \\
|
||||||
|
Adicionado um atraso de 100$\mu$s na geração de veículos para limitar a taxa de produção.
|
||||||
|
|
||||||
|
\begin{lstlisting}[language=Java, title={CoordinatorProcess.java (Excerto)}]
|
||||||
|
// Em generateAndSendVehicle():
|
||||||
|
sendVehicleToIntersection(vehicle, entryIntersection);
|
||||||
|
LockSupport.parkNanos(100000); // 100 us delay
|
||||||
|
\end{lstlisting}
|
||||||
|
|
||||||
|
\textbf{Nota: \textnormal{Em ambos os ficheiros deve ser importado java.util.concurrent.locks.LockSupport.}}
|
||||||
|
|
||||||
|
\section{Resultados e Validação}
|
||||||
|
|
||||||
|
A aplicação dos atrasos sintéticos restaurou a paridade de desempenho entre os sistemas operativos.
|
||||||
|
|
||||||
|
\begin{table}[h]
|
||||||
|
\centering
|
||||||
|
\begin{tabular}{@{}lcc@{}}
|
||||||
|
\toprule
|
||||||
|
\textbf{Ambiente} & \textbf{Antes da Correção} & \textbf{Após Correção} \\
|
||||||
|
\midrule
|
||||||
|
Linux Nativo & $\sim 44\%$ & $\mathbf{\sim 92\%}$ \\
|
||||||
|
\bottomrule
|
||||||
|
\end{tabular}
|
||||||
|
\end{table}
|
||||||
|
|
||||||
|
\subsection{Por que funciona?}
|
||||||
|
\begin{itemize}
|
||||||
|
\item \textbf{Precisão:} \texttt{LockSupport.parkNanos()} oferece um atraso preciso e não bloqueante, com impacto mínimo no agendador do SO, ao contrário de \texttt{Thread.sleep()}.
|
||||||
|
\item \textbf{Ritmo de E/S (50$\mu$s):} Abranda a comunicação via \textit{socket} o suficiente para evitar a saturação dos \textit{buffers} de receção das interseções.
|
||||||
|
\item \textbf{Controlo de Fluxo (100$\mu$s):} Limita a produção do Coordenador, garantindo que o sistema a jusante consegue processar os eventos em tempo útil.
|
||||||
|
\end{itemize}
|
||||||
|
|
||||||
|
\subsection{Verificação}
|
||||||
|
Para validar a correção no ambiente de desenvolvimento:
|
||||||
|
|
||||||
|
\begin{lstlisting}[language=bash]
|
||||||
|
mvn clean compile
|
||||||
|
mvn javafx:run
|
||||||
|
\end{lstlisting}
|
||||||
|
|
||||||
|
\textbf{Resultado Esperado:} Taxa de conclusão superior a 90\%.
|
||||||
|
|
||||||
|
\section{Abordagens Alternativas (Falhadas)}
|
||||||
|
As seguintes tentativas foram realizadas antes da solução final, sem sucesso:
|
||||||
|
\begin{itemize}
|
||||||
|
\item \textbf{Thread.sleep(1):} Demasiado impreciso (granularidade mínima de $\sim$1ms em Linux), causando atrasos excessivos.
|
||||||
|
\item \textbf{Thread.yield():} Sem efeito prático no agendador CFS do Linux neste contexto.
|
||||||
|
\item \textbf{Garbage Collectors:} A alteração entre G1, Parallel e Shenandoah não surtiu efeito.
|
||||||
|
\item \textbf{Versão Java:} Testes com Java 17 e 25 mostraram o mesmo comportamento.
|
||||||
|
\item \textbf{Prioridade de Threads:} Ajustes de prioridade na JVM foram ignorados pelo SO.
|
||||||
|
\end{itemize}
|
||||||
|
|
||||||
|
\end{document}
|
||||||