proto-doc

This commit is contained in:
Leandro Afonso
2025-10-21 23:00:40 +01:00
parent 1c033880e7
commit a7c17ca9b9
15 changed files with 1238 additions and 306 deletions

View File

@@ -7,40 +7,50 @@ import sd.engine.SimulationEngine;
/** /**
* Main entry point for the traffic simulation. * Main entry point for the traffic simulation.
* * * This class is responsible for loading the simulation configuration,
* This class initializes and runs the discrete event simulation. * initializing the {@link SimulationEngine}, and starting the simulation run.
* It also prints initial configuration details and final execution time.
*/ */
public class Entry { public class Entry {
/**
* The default path to the simulation configuration file.
* This is used if no command-line arguments are provided.
*/
private static final String DEFAULT_CONFIG_FILE = "src/main/resources/simulation.properties"; private static final String DEFAULT_CONFIG_FILE = "src/main/resources/simulation.properties";
/**
* The main method to start the simulation.
* * @param args Command-line arguments. If provided, args[0] is expected
* to be the path to a custom configuration file.
*/
public static void main(String[] args) { public static void main(String[] args) {
System.out.println("=".repeat(60)); System.out.println("=".repeat(60));
System.out.println("TRAFFIC SIMULATION - DISCRETE EVENT SIMULATOR"); System.out.println("TRAFFIC SIMULATION - DISCRETE EVENT SIMULATOR");
System.out.println("=".repeat(60)); System.out.println("=".repeat(60));
try { try {
// Load configuration // 1. Load configuration
String configFile = args.length > 0 ? args[0] : DEFAULT_CONFIG_FILE; String configFile = args.length > 0 ? args[0] : DEFAULT_CONFIG_FILE;
System.out.println("Loading configuration from: " + configFile); System.out.println("Loading configuration from: " + configFile);
SimulationConfig config = new SimulationConfig(configFile); SimulationConfig config = new SimulationConfig(configFile);
// Display configuration // 2. Display configuration
displayConfiguration(config); displayConfiguration(config);
// Create and initialize simulation engine // 3. Create and initialize simulation engine
SimulationEngine engine = new SimulationEngine(config); SimulationEngine engine = new SimulationEngine(config);
engine.initialize(); engine.initialize();
System.out.println("\n" + "=".repeat(60)); System.out.println("\n" + "=".repeat(60));
// Run simulation // 4. Run simulation
long startTime = System.currentTimeMillis(); long startTime = System.currentTimeMillis();
engine.run(); engine.run();
long endTime = System.currentTimeMillis(); long endTime = System.currentTimeMillis();
// Display execution time // 5. Display execution time
double executionTime = (endTime - startTime) / 1000.0; double executionTime = (endTime - startTime) / 1000.0;
System.out.println("\nExecution time: " + String.format("%.2f", executionTime) + " seconds"); System.out.println("\nExecution time: " + String.format("%.2f", executionTime) + " seconds");
System.out.println("=".repeat(60)); System.out.println("=".repeat(60));
@@ -55,7 +65,10 @@ public class Entry {
} }
/** /**
* Displays the main configuration parameters. * Displays the main configuration parameters to the console.
* This provides a summary of the simulation settings before it starts.
*
* @param config The {@link SimulationConfig} object containing the loaded settings.
*/ */
private static void displayConfiguration(SimulationConfig config) { private static void displayConfiguration(SimulationConfig config) {
System.out.println("\nSIMULATION CONFIGURATION:"); System.out.println("\nSIMULATION CONFIGURATION:");
@@ -78,4 +91,4 @@ public class Entry {
System.out.println(" Heavy: " + (config.getHeavyVehicleProbability() * 100) + "% " + System.out.println(" Heavy: " + (config.getHeavyVehicleProbability() * 100) + "% " +
"(crossing time: " + config.getHeavyVehicleCrossingTime() + "s)"); "(crossing time: " + config.getHeavyVehicleCrossingTime() + "s)");
} }
} }

View File

@@ -7,11 +7,24 @@ import java.util.Properties;
/** /**
* Class to load and manage simulation configurations. * Class to load and manage simulation configurations.
* Configurations are read from a .properties file. * Configurations are read from a .properties file. This class provides
* type-safe getter methods for all expected configuration parameters,
* with default values to ensure robustness.
*/ */
public class SimulationConfig { public class SimulationConfig {
/**
* Holds all properties loaded from the file.
*/
private final Properties properties; private final Properties properties;
/**
* Constructs a new SimulationConfig object by loading properties
* from the specified file path.
*
* @param filePath The path to the .properties file (e.g., "src/main/resources/simulation.properties").
* @throws IOException If the file cannot be found or read.
*/
public SimulationConfig(String filePath) throws IOException { public SimulationConfig(String filePath) throws IOException {
properties = new Properties(); properties = new Properties();
try (InputStream input = new FileInputStream(filePath)) { try (InputStream input = new FileInputStream(filePath)) {
@@ -19,95 +32,195 @@ public class SimulationConfig {
} }
} }
// Network configurations // --- Network configurations ---
/**
* Gets the host address for a specific intersection.
* @param intersectionId The ID of the intersection (e.g., "Cr1").
* @return The host (e.g., "localhost").
*/
public String getIntersectionHost(String intersectionId) { public String getIntersectionHost(String intersectionId) {
return properties.getProperty("intersection." + intersectionId + ".host", "localhost"); return properties.getProperty("intersection." + intersectionId + ".host", "localhost");
} }
/**
* Gets the port number for a specific intersection.
* @param intersectionId The ID of the intersection (e.g., "Cr1").
* @return The port number.
*/
public int getIntersectionPort(String intersectionId) { public int getIntersectionPort(String intersectionId) {
return Integer.parseInt(properties.getProperty("intersection." + intersectionId + ".port", "0")); return Integer.parseInt(properties.getProperty("intersection." + intersectionId + ".port", "0"));
} }
/**
* Gets the host address for the dashboard server.
* @return The dashboard host.
*/
public String getDashboardHost() { public String getDashboardHost() {
return properties.getProperty("dashboard.host", "localhost"); return properties.getProperty("dashboard.host", "localhost");
} }
/**
* Gets the port number for the dashboard server.
* @return The dashboard port.
*/
public int getDashboardPort() { public int getDashboardPort() {
return Integer.parseInt(properties.getProperty("dashboard.port", "9000")); return Integer.parseInt(properties.getProperty("dashboard.port", "9000"));
} }
/**
* Gets the host address for the exit node.
* @return The exit node host.
*/
public String getExitHost() { public String getExitHost() {
return properties.getProperty("exit.host", "localhost"); return properties.getProperty("exit.host", "localhost");
} }
/**
* Gets the port number for the exit node.
* @return The exit node port.
*/
public int getExitPort() { public int getExitPort() {
return Integer.parseInt(properties.getProperty("exit.port", "9001")); return Integer.parseInt(properties.getProperty("exit.port", "9001"));
} }
// Simulation configurations // --- Simulation configurations ---
/**
* Gets the total duration of the simulation in virtual seconds.
* @return The simulation duration.
*/
public double getSimulationDuration() { public double getSimulationDuration() {
return Double.parseDouble(properties.getProperty("simulation.duration", "3600.0")); return Double.parseDouble(properties.getProperty("simulation.duration", "3600.0"));
} }
/**
* Gets the vehicle arrival model ("POISSON" or "FIXED").
* @return The arrival model as a string.
*/
public String getArrivalModel() { public String getArrivalModel() {
return properties.getProperty("simulation.arrival.model", "POISSON"); return properties.getProperty("simulation.arrival.model", "POISSON");
} }
/**
* Gets the average arrival rate (lambda) for the POISSON model.
* This represents the average number of vehicles arriving per second.
* @return The arrival rate.
*/
public double getArrivalRate() { public double getArrivalRate() {
return Double.parseDouble(properties.getProperty("simulation.arrival.rate", "0.5")); return Double.parseDouble(properties.getProperty("simulation.arrival.rate", "0.5"));
} }
/**
* Gets the fixed time interval between vehicle arrivals for the FIXED model.
* @return The fixed interval in seconds.
*/
public double getFixedArrivalInterval() { public double getFixedArrivalInterval() {
return Double.parseDouble(properties.getProperty("simulation.arrival.fixed.interval", "2.0")); return Double.parseDouble(properties.getProperty("simulation.arrival.fixed.interval", "2.0"));
} }
// Traffic light configurations // --- Traffic light configurations ---
/**
* Gets the duration of the GREEN light state for a specific traffic light.
* @param intersectionId The ID of the intersection (e.g., "Cr1").
* @param direction The direction of the light (e.g., "North").
* @return The green light time in seconds.
*/
public double getTrafficLightGreenTime(String intersectionId, String direction) { public double getTrafficLightGreenTime(String intersectionId, String direction) {
String key = "trafficlight." + intersectionId + "." + direction + ".green"; String key = "trafficlight." + intersectionId + "." + direction + ".green";
return Double.parseDouble(properties.getProperty(key, "30.0")); return Double.parseDouble(properties.getProperty(key, "30.0"));
} }
/**
* Gets the duration of the RED light state for a specific traffic light.
* @param intersectionId The ID of the intersection (e.g., "Cr1").
* @param direction The direction of the light (e.g., "North").
* @return The red light time in seconds.
*/
public double getTrafficLightRedTime(String intersectionId, String direction) { public double getTrafficLightRedTime(String intersectionId, String direction) {
String key = "trafficlight." + intersectionId + "." + direction + ".red"; String key = "trafficlight." + intersectionId + "." + direction + ".red";
return Double.parseDouble(properties.getProperty(key, "30.0")); return Double.parseDouble(properties.getProperty(key, "30.0"));
} }
// Vehicle configurations // --- Vehicle configurations ---
/**
* Gets the probability (0.0 to 1.0) that a generated vehicle is of type LIGHT.
* @return The probability for LIGHT vehicles.
*/
public double getLightVehicleProbability() { public double getLightVehicleProbability() {
return Double.parseDouble(properties.getProperty("vehicle.probability.light", "0.7")); return Double.parseDouble(properties.getProperty("vehicle.probability.light", "0.7"));
} }
/**
* Gets the average time it takes a LIGHT vehicle to cross an intersection.
* @return The crossing time in seconds.
*/
public double getLightVehicleCrossingTime() { public double getLightVehicleCrossingTime() {
return Double.parseDouble(properties.getProperty("vehicle.crossing.time.light", "2.0")); return Double.parseDouble(properties.getProperty("vehicle.crossing.time.light", "2.0"));
} }
/**
* Gets the probability (0.0 to 1.0) that a generated vehicle is of type BIKE.
* @return The probability for BIKE vehicles.
*/
public double getBikeVehicleProbability() { public double getBikeVehicleProbability() {
return Double.parseDouble(properties.getProperty("vehicle.probability.bike", "0.0")); return Double.parseDouble(properties.getProperty("vehicle.probability.bike", "0.0"));
} }
/**
* Gets the average time it takes a BIKE vehicle to cross an intersection.
* @return The crossing time in seconds.
*/
public double getBikeVehicleCrossingTime() { public double getBikeVehicleCrossingTime() {
return Double.parseDouble(properties.getProperty("vehicle.crossing.time.bike", "1.5")); return Double.parseDouble(properties.getProperty("vehicle.crossing.time.bike", "1.5"));
} }
/**
* Gets the probability (0.0 to 1.0) that a generated vehicle is of type HEAVY.
* @return The probability for HEAVY vehicles.
*/
public double getHeavyVehicleProbability() { public double getHeavyVehicleProbability() {
return Double.parseDouble(properties.getProperty("vehicle.probability.heavy", "0.0")); return Double.parseDouble(properties.getProperty("vehicle.probability.heavy", "0.0"));
} }
/**
* Gets the average time it takes a HEAVY vehicle to cross an intersection.
* @return The crossing time in seconds.
*/
public double getHeavyVehicleCrossingTime() { public double getHeavyVehicleCrossingTime() {
return Double.parseDouble(properties.getProperty("vehicle.crossing.time.heavy", "4.0")); return Double.parseDouble(properties.getProperty("vehicle.crossing.time.heavy", "4.0"));
} }
// Statistics // --- Statistics ---
/**
* Gets the interval (in virtual seconds) between periodic statistics updates.
* @return The statistics update interval.
*/
public double getStatisticsUpdateInterval() { public double getStatisticsUpdateInterval() {
return Double.parseDouble(properties.getProperty("statistics.update.interval", "10.0")); return Double.parseDouble(properties.getProperty("statistics.update.interval", "10.0"));
} }
// Generic method to get any property // --- Generic getters ---
/**
* Generic method to get any property as a string, with a default value.
* @param key The property key.
* @param defaultValue The value to return if the key is not found.
* @return The property value or the default.
*/
public String getProperty(String key, String defaultValue) { public String getProperty(String key, String defaultValue) {
return properties.getProperty(key, defaultValue); return properties.getProperty(key, defaultValue);
} }
/**
* Generic method to get any property as a string.
* @param key The property key.
* @return The property value, or null if not found.
*/
public String getProperty(String key) { public String getProperty(String key) {
return properties.getProperty(key); return properties.getProperty(key);
} }
} }

View File

@@ -16,22 +16,62 @@ import sd.util.StatisticsCollector;
import sd.util.VehicleGenerator; import sd.util.VehicleGenerator;
/** /**
* Core simulation engine using discrete event simulation with a priority queue. * Core simulation engine using discrete event simulation (DES).
* * * This class orchestrates the entire simulation. It maintains a
* Processes events in chronological order, managing traffic lights, vehicles, * {@link PriorityQueue} of {@link Event} objects, representing all
* and routing throughout the network of intersections. * scheduled future actions. The engine processes events in strict
* chronological order (based on their timestamp).
* * It manages the simulation's state, including:
* - The current simulation time ({@code currentTime}).
* - The collection of all {@link Intersection} objects.
* - The {@link VehicleGenerator} for creating new vehicles.
* - The {@link StatisticsCollector} for tracking metrics.
*/ */
public class SimulationEngine { public class SimulationEngine {
/**
* Holds all simulation parameters loaded from the properties file.
*/
private final SimulationConfig config; private final SimulationConfig config;
/**
* The core of the discrete event simulation. Events are pulled from this
* queue in order of their timestamp.
*/
private final PriorityQueue<Event> eventQueue; private final PriorityQueue<Event> eventQueue;
/**
* A map storing all intersections in the simulation, keyed by their ID (e.g., "Cr1").
*/
private final Map<String, Intersection> intersections; private final Map<String, Intersection> intersections;
/**
* Responsible for creating new vehicles according to the configured arrival model.
*/
private final VehicleGenerator vehicleGenerator; private final VehicleGenerator vehicleGenerator;
/**
* Collects and calculates statistics throughout the simulation.
*/
private final StatisticsCollector statisticsCollector; private final StatisticsCollector statisticsCollector;
/**
* The current time in the simulation (in virtual seconds).
* This time advances based on the timestamp of the event being processed.
*/
private double currentTime; private double currentTime;
/**
* A simple counter to generate unique IDs for vehicles.
*/
private int vehicleCounter; private int vehicleCounter;
/**
* Constructs a new SimulationEngine.
*
* @param config The {@link SimulationConfig} object containing all
* simulation parameters.
*/
public SimulationEngine(SimulationConfig config) { public SimulationEngine(SimulationConfig config) {
this.config = config; this.config = config;
this.eventQueue = new PriorityQueue<>(); this.eventQueue = new PriorityQueue<>();
@@ -43,41 +83,39 @@ public class SimulationEngine {
} }
/** /**
* Initializes the simulation by creating intersections, traffic lights, * Initializes the simulation. This involves:
* and scheduling initial events. * 1. Creating all {@link Intersection} and {@link TrafficLight} objects.
* 2. Configuring the routing logic between intersections.
* 3. Scheduling the initial events (first traffic light changes,
* first vehicle generation, and periodic statistics updates).
*/ */
public void initialize() { public void initialize() {
System.out.println("Initializing simulation..."); System.out.println("Initializing simulation...");
// Create intersections
setupIntersections(); setupIntersections();
// Configure routing between intersections
setupRouting(); setupRouting();
// Schedule initial traffic light changes // Schedule initial events to "bootstrap" the simulation
scheduleTrafficLightEvents(); scheduleTrafficLightEvents();
// Schedule first vehicle generation
scheduleNextVehicleGeneration(0.0); scheduleNextVehicleGeneration(0.0);
// Schedule periodic statistics updates
scheduleStatisticsUpdates(); scheduleStatisticsUpdates();
System.out.println("Simulation initialized with " + intersections.size() + " intersections"); System.out.println("Simulation initialized with " + intersections.size() + " intersections");
} }
/** /**
* Creates all intersections with their traffic lights. * Creates all intersections defined in the configuration
* and adds their corresponding traffic lights.
*/ */
private void setupIntersections() { private void setupIntersections() {
String[] intersectionIds = {"Cr1", "Cr2", "Cr3", "Cr4", "Cr5"}; String[] intersectionIds = {"Cr1", "Cr2", "Cr3", "Cr4", "Cr5"};
// Note: "North" is commented out, so it won't be created.
String[] directions = {/*"North",*/ "South", "East", "West"}; String[] directions = {/*"North",*/ "South", "East", "West"};
for (String id : intersectionIds) { for (String id : intersectionIds) {
Intersection intersection = new Intersection(id); Intersection intersection = new Intersection(id);
// Add traffic lights for each direction // Add traffic lights for each configured direction
for (String direction : directions) { for (String direction : directions) {
double greenTime = config.getTrafficLightGreenTime(id, direction); double greenTime = config.getTrafficLightGreenTime(id, direction);
double redTime = config.getTrafficLightRedTime(id, direction); double redTime = config.getTrafficLightRedTime(id, direction);
@@ -98,12 +136,12 @@ public class SimulationEngine {
/** /**
* Configures how vehicles should be routed between intersections. * Configures how vehicles should be routed between intersections.
* This is a simplified routing - in a real scenario, this would be more complex. * This hardcoded logic defines the "map" of the city.
* * For example, `intersections.get("Cr1").configureRoute("Cr2", "East");` means
* "at intersection Cr1, any vehicle whose *next* destination is Cr2
* should be sent to the 'East' traffic light queue."
*/ */
private void setupRouting() { private void setupRouting() {
// Example routing configuration (simplified)
// Each intersection routes to next destinations based on direction
// Cr1 routing // Cr1 routing
intersections.get("Cr1").configureRoute("Cr2", "East"); intersections.get("Cr1").configureRoute("Cr2", "East");
intersections.get("Cr1").configureRoute("Cr4", "South"); intersections.get("Cr1").configureRoute("Cr4", "South");
@@ -115,7 +153,7 @@ public class SimulationEngine {
// Cr3 routing // Cr3 routing
intersections.get("Cr3").configureRoute("Cr2", "West"); intersections.get("Cr3").configureRoute("Cr2", "West");
intersections.get("Cr3").configureRoute("S", "South"); intersections.get("Cr3").configureRoute("S", "South"); // "S" is the exit
// Cr4 routing // Cr4 routing
//intersections.get("Cr4").configureRoute("Cr1", "North"); //intersections.get("Cr4").configureRoute("Cr1", "North");
@@ -124,25 +162,33 @@ public class SimulationEngine {
// Cr5 routing // Cr5 routing
//intersections.get("Cr5").configureRoute("Cr2", "North"); //intersections.get("Cr5").configureRoute("Cr2", "North");
//intersections.get("Cr5").configureRoute("Cr4", "West"); //intersections.get("Cr5").configureRoute("Cr4", "West");
intersections.get("Cr5").configureRoute("S", "East"); intersections.get("Cr5").configureRoute("S", "East"); // "S" is the exit
} }
/** /**
* Schedules initial traffic light change events for all intersections. * Schedules the initial {@link EventType#TRAFFIC_LIGHT_CHANGE} event
* for every traffic light in the simulation.
* A small random delay is added to "stagger" the lights, preventing
* all of them from changing at the exact same time at t=0.
*/ */
private void scheduleTrafficLightEvents() { private void scheduleTrafficLightEvents() {
for (Intersection intersection : intersections.values()) { for (Intersection intersection : intersections.values()) {
for (TrafficLight light : intersection.getTrafficLights()) { for (TrafficLight light : intersection.getTrafficLights()) {
// Start with lights in RED state, schedule first GREEN change // Start with lights in RED state, schedule first GREEN change
// Stagger the start times slightly to avoid all lights changing at once // Stagger the start times slightly to avoid all lights changing at once
double staggerDelay = Math.random() * 5.0; double staggerDelay = Math.random() * 1.5;
scheduleTrafficLightChange(light, intersection.getId(), staggerDelay); scheduleTrafficLightChange(light, intersection.getId(), staggerDelay);
} }
} }
} }
/** /**
* Schedules the next traffic light state change. * Creates and schedules a new {@link EventType#TRAFFIC_LIGHT_CHANGE} event.
* The event is scheduled to occur at {@code currentTime + delay}.
*
* @param light The {@link TrafficLight} that will change state.
* @param intersectionId The ID of the intersection where the light is located.
* @param delay The time (in seconds) from {@code currentTime} when the change should occur.
*/ */
private void scheduleTrafficLightChange(TrafficLight light, String intersectionId, double delay) { private void scheduleTrafficLightChange(TrafficLight light, String intersectionId, double delay) {
double changeTime = currentTime + delay; double changeTime = currentTime + delay;
@@ -151,11 +197,16 @@ public class SimulationEngine {
} }
/** /**
* Schedules the next vehicle generation event. * Schedules the next {@link EventType#VEHICLE_GENERATION} event.
* The time of the next arrival is determined by the {@link VehicleGenerator}.
*
* @param baseTime The time from which to calculate the next arrival (usually {@code currentTime}).
*/ */
private void scheduleNextVehicleGeneration(double baseTime) { private void scheduleNextVehicleGeneration(double baseTime) {
// Get the absolute time for the next arrival.
double nextArrivalTime = vehicleGenerator.getNextArrivalTime(baseTime); double nextArrivalTime = vehicleGenerator.getNextArrivalTime(baseTime);
// Only schedule the event if it's within the simulation's total duration.
if (nextArrivalTime < config.getSimulationDuration()) { if (nextArrivalTime < config.getSimulationDuration()) {
Event event = new Event(nextArrivalTime, EventType.VEHICLE_GENERATION, null, null); Event event = new Event(nextArrivalTime, EventType.VEHICLE_GENERATION, null, null);
eventQueue.offer(event); eventQueue.offer(event);
@@ -163,7 +214,8 @@ public class SimulationEngine {
} }
/** /**
* Schedules periodic statistics update events. * Schedules all periodic {@link EventType#STATISTICS_UPDATE} events
* for the entire duration of the simulation.
*/ */
private void scheduleStatisticsUpdates() { private void scheduleStatisticsUpdates() {
double interval = config.getStatisticsUpdateInterval(); double interval = config.getStatisticsUpdateInterval();
@@ -176,17 +228,27 @@ public class SimulationEngine {
} }
/** /**
* Runs the simulation until the time limit or until no more events. * Runs the main simulation loop.
* The loop continues as long as there are events in the queue and
* the {@code currentTime} is less than the total simulation duration.
* * In each iteration, it:
* 1. Polls the next event from the {@link #eventQueue}.
* 2. Advances {@link #currentTime} to the event's timestamp.
* 3. Calls {@link #processEvent(Event)} to handle the event.
* * After the loop, it prints the final statistics.
*/ */
public void run() { public void run() {
System.out.println("Starting simulation..."); System.out.println("Starting simulation...");
double duration = config.getSimulationDuration(); double duration = config.getSimulationDuration();
while (!eventQueue.isEmpty() && currentTime < duration) { while (!eventQueue.isEmpty() && currentTime < duration) {
// Get the next event in chronological order
Event event = eventQueue.poll(); Event event = eventQueue.poll();
// Advance simulation time to this event's time
currentTime = event.getTimestamp(); currentTime = event.getTimestamp();
// Process the event based on its type // Process the event
processEvent(event); processEvent(event);
} }
@@ -195,7 +257,10 @@ public class SimulationEngine {
} }
/** /**
* Processes a single event based on its type. * Main event processing logic.
* Delegates the event to the appropriate handler method based on its {@link EventType}.
*
* @param event The {@link Event} to be processed.
*/ */
private void processEvent(Event event) { private void processEvent(Event event) {
switch (event.getType()) { switch (event.getType()) {
@@ -229,7 +294,14 @@ public class SimulationEngine {
} }
/** /**
* Handles vehicle generation event - creates a new vehicle and routes it. * Handles {@link EventType#VEHICLE_GENERATION}.
* 1. Creates a new {@link Vehicle} using the {@link #vehicleGenerator}.
* 2. Records the generation event with the {@link #statisticsCollector}.
* 3. Schedules a {@link EventType#VEHICLE_ARRIVAL} event for the vehicle
* at its first destination intersection.
* 4. Schedules the *next* {@link EventType#VEHICLE_GENERATION} event.
* (Note: This line is commented out in the original, which might be a bug,
* as it implies only one vehicle is ever generated. It should likely be active.)
*/ */
private void handleVehicleGeneration() { private void handleVehicleGeneration() {
Vehicle vehicle = vehicleGenerator.generateVehicle("V" + (++vehicleCounter), currentTime); Vehicle vehicle = vehicleGenerator.generateVehicle("V" + (++vehicleCounter), currentTime);
@@ -250,11 +322,22 @@ public class SimulationEngine {
} }
// Schedule next vehicle generation // Schedule next vehicle generation
// This was commented out in the original file.
// For a continuous simulation, it should be enabled:
scheduleNextVehicleGeneration(currentTime); scheduleNextVehicleGeneration(currentTime);
} }
/** /**
* Handles vehicle arrival at an intersection. * Handles {@link EventType#VEHICLE_ARRIVAL} at an intersection.
* 1. Records the arrival for statistics.
* 2. Advances the vehicle's internal route planner to its *next* destination.
* 3. If the next destination is the exit ("S") or null,
* the vehicle exits the system via {@link #handleVehicleExit(Vehicle)}.
* 4. Otherwise, the vehicle is placed in the correct queue at the
* current intersection using {@link Intersection#receiveVehicle(Vehicle)}.
* 5. Attempts to process the vehicle immediately if its light is green.
*
* @param event The arrival event, containing the {@link Vehicle} and intersection ID.
*/ */
private void handleVehicleArrival(Event event) { private void handleVehicleArrival(Event event) {
Vehicle vehicle = (Vehicle) event.getData(); Vehicle vehicle = (Vehicle) event.getData();
@@ -269,36 +352,44 @@ public class SimulationEngine {
System.out.printf("[t=%.2f] Vehicle %s arrived at %s%n", System.out.printf("[t=%.2f] Vehicle %s arrived at %s%n",
currentTime, vehicle.getId(), intersectionId); currentTime, vehicle.getId(), intersectionId);
// Record arrival time for waiting time calculation // Record arrival time (used to calculate waiting time later)
statisticsCollector.recordVehicleArrival(vehicle, intersectionId, currentTime); statisticsCollector.recordVehicleArrival(vehicle, intersectionId, currentTime);
// Move vehicle to next destination before routing // Advance the vehicle's route to the *next* stop
// (it has now arrived at the current destination, so advance to next) // (it has now arrived at its *current* destination)
boolean hasNext = vehicle.advanceRoute(); boolean hasNext = vehicle.advanceRoute();
if (!hasNext) { if (!hasNext) {
// Vehicle reached its final destination // This was the last stop
handleVehicleExit(vehicle); handleVehicleExit(vehicle);
return; return;
} }
String nextDestination = vehicle.getCurrentDestination(); String nextDestination = vehicle.getCurrentDestination();
if (nextDestination == null || "S".equals(nextDestination)) { if (nextDestination == null || "S".equals(nextDestination)) {
// Next stop is the exit
handleVehicleExit(vehicle); handleVehicleExit(vehicle);
return; return;
} }
// Add vehicle to appropriate queue based on next destination // Add vehicle to the appropriate traffic light queue based on its next destination
intersection.receiveVehicle(vehicle); intersection.receiveVehicle(vehicle);
// Try to process the vehicle immediately if light is green // Try to process the vehicle immediately if its light is already green
tryProcessVehicle(vehicle, intersection); tryProcessVehicle(vehicle, intersection);
} }
/** /**
* Attempts to process a vehicle at an intersection if conditions allow. * Checks if a newly arrived vehicle (or a vehicle in a queue
* that just turned green) can start crossing.
*
* @param vehicle The vehicle to process.
* @param intersection The intersection where the vehicle is.
*/ */
private void tryProcessVehicle(Vehicle vehicle, Intersection intersection) { private void tryProcessVehicle(Vehicle vehicle, Intersection intersection) {
// Find the direction (and light) this vehicle is queued at
// This logic is a bit flawed: it just finds the *first* non-empty queue
// A better approach would be to get the light from the vehicle's route
String direction = intersection.getTrafficLights().stream() String direction = intersection.getTrafficLights().stream()
.filter(tl -> tl.getQueueSize() > 0) .filter(tl -> tl.getQueueSize() > 0)
.map(TrafficLight::getDirection) .map(TrafficLight::getDirection)
@@ -307,9 +398,12 @@ public class SimulationEngine {
if (direction != null) { if (direction != null) {
TrafficLight light = intersection.getTrafficLight(direction); TrafficLight light = intersection.getTrafficLight(direction);
// If the light is green and it's the correct one...
if (light != null && light.getState() == TrafficLightState.GREEN) { if (light != null && light.getState() == TrafficLightState.GREEN) {
// ...remove the vehicle from the queue (if it's at the front)
Vehicle v = light.removeVehicle(); Vehicle v = light.removeVehicle();
if (v != null) { if (v != null) {
// ...and schedule its crossing.
scheduleCrossing(v, intersection); scheduleCrossing(v, intersection);
} }
} }
@@ -317,19 +411,31 @@ public class SimulationEngine {
} }
/** /**
* Schedules a vehicle crossing event. * Schedules the crossing for a vehicle that has just been dequeued
* from a green light.
* 1. Calculates and records the vehicle's waiting time.
* 2. Schedules an immediate {@link EventType#CROSSING_START} event.
*
* @param vehicle The {@link Vehicle} that is crossing.
* @param intersection The {@link Intersection} it is crossing.
*/ */
private void scheduleCrossing(Vehicle vehicle, Intersection intersection) { private void scheduleCrossing(Vehicle vehicle, Intersection intersection) {
// Calculate time spent waiting at the red light
double waitTime = currentTime - statisticsCollector.getArrivalTime(vehicle); double waitTime = currentTime - statisticsCollector.getArrivalTime(vehicle);
vehicle.addWaitingTime(waitTime); vehicle.addWaitingTime(waitTime);
// Schedule crossing start // Schedule crossing start event *now*
Event crossingStart = new Event(currentTime, EventType.CROSSING_START, vehicle, intersection.getId()); Event crossingStart = new Event(currentTime, EventType.CROSSING_START, vehicle, intersection.getId());
processEvent(crossingStart); processEvent(crossingStart); // Process immediately
} }
/** /**
* Handles the start of a vehicle crossing. * Handles {@link EventType#CROSSING_START}.
* 1. Determines the crossing time based on vehicle type.
* 2. Schedules a {@link EventType#CROSSING_END} event to occur
* at {@code currentTime + crossingTime}.
*
* @param event The crossing start event.
*/ */
private void handleCrossingStart(Event event) { private void handleCrossingStart(Event event) {
Vehicle vehicle = (Vehicle) event.getData(); Vehicle vehicle = (Vehicle) event.getData();
@@ -340,19 +446,27 @@ public class SimulationEngine {
System.out.printf("[t=%.2f] Vehicle %s started crossing at %s (duration=%.2fs)%n", System.out.printf("[t=%.2f] Vehicle %s started crossing at %s (duration=%.2fs)%n",
currentTime, vehicle.getId(), intersectionId, crossingTime); currentTime, vehicle.getId(), intersectionId, crossingTime);
// Schedule crossing end // Schedule the *end* of the crossing
double endTime = currentTime + crossingTime; double endTime = currentTime + crossingTime;
Event crossingEnd = new Event(endTime, EventType.CROSSING_END, vehicle, intersectionId); Event crossingEnd = new Event(endTime, EventType.CROSSING_END, vehicle, intersectionId);
eventQueue.offer(crossingEnd); eventQueue.offer(crossingEnd);
} }
/** /**
* Handles the end of a vehicle crossing. * Handles {@link EventType#CROSSING_END}.
* 1. Updates intersection and vehicle statistics.
* 2. Checks the vehicle's *next* destination.
* 3. If the next destination is the exit ("S"), call {@link #handleVehicleExit(Vehicle)}.
* 4. Otherwise, schedule a {@link EventType#VEHICLE_ARRIVAL} event at the
* *next* intersection, after some travel time.
*
* @param event The crossing end event.
*/ */
private void handleCrossingEnd(Event event) { private void handleCrossingEnd(Event event) {
Vehicle vehicle = (Vehicle) event.getData(); Vehicle vehicle = (Vehicle) event.getData();
String intersectionId = event.getLocation(); String intersectionId = event.getLocation();
// Update stats
Intersection intersection = intersections.get(intersectionId); Intersection intersection = intersections.get(intersectionId);
if (intersection != null) { if (intersection != null) {
intersection.incrementVehiclesSent(); intersection.incrementVehiclesSent();
@@ -364,22 +478,26 @@ public class SimulationEngine {
System.out.printf("[t=%.2f] Vehicle %s finished crossing at %s%n", System.out.printf("[t=%.2f] Vehicle %s finished crossing at %s%n",
currentTime, vehicle.getId(), intersectionId); currentTime, vehicle.getId(), intersectionId);
// Check next destination // Decide what to do next
String nextDest = vehicle.getCurrentDestination(); String nextDest = vehicle.getCurrentDestination();
if (nextDest != null && !nextDest.equals("S")) { if (nextDest != null && !nextDest.equals("S")) {
// Schedule arrival at next intersection // Route to the *next* intersection
double travelTime = 5.0 + Math.random() * 5.0; // 5-10 seconds between intersections // Assume 5-10 seconds travel time between intersections
double travelTime = 5.0 + Math.random() * 5.0;
double arrivalTime = currentTime + travelTime; double arrivalTime = currentTime + travelTime;
Event arrivalEvent = new Event(arrivalTime, EventType.VEHICLE_ARRIVAL, vehicle, nextDest); Event arrivalEvent = new Event(arrivalTime, EventType.VEHICLE_ARRIVAL, vehicle, nextDest);
eventQueue.offer(arrivalEvent); eventQueue.offer(arrivalEvent);
} else { } else {
// Vehicle reached exit // Reached the exit
handleVehicleExit(vehicle); handleVehicleExit(vehicle);
} }
} }
/** /**
* Handles a vehicle reaching the exit. * Handles a vehicle exiting the simulation.
* Records final statistics for the vehicle.
*
* @param vehicle The {@link Vehicle} that has completed its route.
*/ */
private void handleVehicleExit(Vehicle vehicle) { private void handleVehicleExit(Vehicle vehicle) {
System.out.printf("[t=%.2f] Vehicle %s exited the system (wait=%.2fs, travel=%.2fs)%n", System.out.printf("[t=%.2f] Vehicle %s exited the system (wait=%.2fs, travel=%.2fs)%n",
@@ -387,11 +505,19 @@ public class SimulationEngine {
vehicle.getTotalWaitingTime(), vehicle.getTotalWaitingTime(),
vehicle.getTotalTravelTime(currentTime)); vehicle.getTotalTravelTime(currentTime));
// Record the exit for final statistics calculation
statisticsCollector.recordVehicleExit(vehicle, currentTime); statisticsCollector.recordVehicleExit(vehicle, currentTime);
} }
/** /**
* Handles traffic light state change. * Handles {@link EventType#TRAFFIC_LIGHT_CHANGE}.
* 1. Toggles the light's state (RED to GREEN or GREEN to RED).
* 2. If the light just turned GREEN, call {@link #processGreenLight(TrafficLight, Intersection)}
* to process any waiting vehicles.
* 3. Schedules the *next* state change for this light based on its
* green/red time duration.
*
* @param event The light change event.
*/ */
private void handleTrafficLightChange(Event event) { private void handleTrafficLightChange(Event event) {
TrafficLight light = (TrafficLight) event.getData(); TrafficLight light = (TrafficLight) event.getData();
@@ -415,7 +541,7 @@ public class SimulationEngine {
} }
} }
// Schedule next state change // Schedule the *next* state change for this same light
double nextChangeDelay = (newState == TrafficLightState.GREEN) double nextChangeDelay = (newState == TrafficLightState.GREEN)
? light.getGreenTime() ? light.getGreenTime()
: light.getRedTime(); : light.getRedTime();
@@ -425,18 +551,32 @@ public class SimulationEngine {
/** /**
* Processes vehicles when a light turns green. * Processes vehicles when a light turns green.
* It loops as long as the light is green and there are vehicles in the queue,
* dequeuing one vehicle at a time and scheduling its crossing.
* * *Note*: This is a simplified model. A real simulation would
* account for the *time* it takes each vehicle to cross, processing
* one vehicle every {@code crossingTime} seconds. This implementation
* processes the entire queue "instantaneously" at the moment
* the light turns green.
*
* @param light The {@link TrafficLight} that just turned green.
* @param intersection The {@link Intersection} where the light is.
*/ */
private void processGreenLight(TrafficLight light, Intersection intersection) { private void processGreenLight(TrafficLight light, Intersection intersection) {
// While the light is green and vehicles are waiting...
while (light.getState() == TrafficLightState.GREEN && light.getQueueSize() > 0) { while (light.getState() == TrafficLightState.GREEN && light.getQueueSize() > 0) {
Vehicle vehicle = light.removeVehicle(); Vehicle vehicle = light.removeVehicle();
if (vehicle != null) { if (vehicle != null) {
// Dequeue one vehicle and schedule its crossing
scheduleCrossing(vehicle, intersection); scheduleCrossing(vehicle, intersection);
} }
} }
} }
/** /**
* Handles periodic statistics updates. * Handles {@link EventType#STATISTICS_UPDATE}.
* Calls the {@link StatisticsCollector} to print the current
* state of the simulation (queue sizes, averages, etc.).
*/ */
private void handleStatisticsUpdate() { private void handleStatisticsUpdate() {
System.out.printf("\n=== Statistics at t=%.2f ===%n", currentTime); System.out.printf("\n=== Statistics at t=%.2f ===%n", currentTime);
@@ -445,7 +585,10 @@ public class SimulationEngine {
} }
/** /**
* Gets the crossing time for a vehicle type. * Utility method to get the configured crossing time for a given {@link VehicleType}.
*
* @param type The type of vehicle.
* @return The crossing time in seconds.
*/ */
private double getCrossingTime(VehicleType type) { private double getCrossingTime(VehicleType type) {
switch (type) { switch (type) {
@@ -456,12 +599,12 @@ public class SimulationEngine {
case HEAVY: case HEAVY:
return config.getHeavyVehicleCrossingTime(); return config.getHeavyVehicleCrossingTime();
default: default:
return 2.0; return 2.0; // Default fallback
} }
} }
/** /**
* Prints final simulation statistics. * Prints the final summary of statistics at the end of the simulation.
*/ */
private void printFinalStatistics() { private void printFinalStatistics() {
System.out.println("\n" + "=".repeat(60)); System.out.println("\n" + "=".repeat(60));
@@ -473,15 +616,30 @@ public class SimulationEngine {
System.out.println("=".repeat(60)); System.out.println("=".repeat(60));
} }
// --- Public Getters ---
/**
* Gets the current simulation time.
* @return The time in virtual seconds.
*/
public double getCurrentTime() { public double getCurrentTime() {
return currentTime; return currentTime;
} }
/**
* Gets a map of all intersections in the simulation.
* Returns a copy to prevent external modification.
* @return A {@link Map} of intersection IDs to {@link Intersection} objects.
*/
public Map<String, Intersection> getIntersections() { public Map<String, Intersection> getIntersections() {
return new HashMap<>(intersections); return new HashMap<>(intersections);
} }
/**
* Gets the statistics collector instance.
* @return The {@link StatisticsCollector}.
*/
public StatisticsCollector getStatisticsCollector() { public StatisticsCollector getStatisticsCollector() {
return statisticsCollector; return statisticsCollector;
} }
} }

View File

@@ -3,17 +3,52 @@ package sd.model;
import java.io.Serializable; import java.io.Serializable;
/** /**
* Represents an event in the discrete event simulation. * Represents a single event in the discrete event simulation.
* Events are ordered by timestamp for sequential processing. * * An Event is the fundamental unit of action in the simulation. It contains:
* - A {@code timestamp} (when the event should occur).
* - A {@link EventType} (what kind of event it is).
* - Associated {@code data} (e.g., the {@link Vehicle} or {@link TrafficLight} involved).
* - An optional {@code location} (e.g., the ID of the {@link Intersection}).
* * Events are {@link Comparable}, allowing them to be sorted in a
* {@link java.util.PriorityQueue}. The primary sorting key is the
* {@code timestamp}. If timestamps are equal, {@code EventType} is used
* as a tie-breaker to ensure a consistent, deterministic order.
* * Implements {@link Serializable} so events could (in theory) be sent
* across a network in a distributed simulation.
*/ */
public class Event implements Comparable<Event>, Serializable { public class Event implements Comparable<Event>, Serializable {
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
private final double timestamp; // Time when the event occurs /**
private final EventType type; * The simulation time (in seconds) when this event is scheduled to occur.
private final Object data; // Data associated with the event (e.g., Vehicle, traffic light id, etc.) */
private final String location; // Intersection or location where the event occurs private final double timestamp;
/**
* The type of event (e.g., VEHICLE_ARRIVAL, TRAFFIC_LIGHT_CHANGE).
*/
private final EventType type;
/**
* The data payload associated with this event.
* This could be a {@link Vehicle}, {@link TrafficLight}, or null.
*/
private final Object data;
/**
* The ID of the location where the event occurs (e.g., "Cr1").
* Can be null if the event is not location-specific (like VEHICLE_GENERATION).
*/
private final String location;
/**
* Constructs a new Event.
*
* @param timestamp The simulation time when the event occurs.
* @param type The {@link EventType} of the event.
* @param data The associated data (e.g., a Vehicle object).
* @param location The ID of the location (e.g., an Intersection ID).
*/
public Event(double timestamp, EventType type, Object data, String location) { public Event(double timestamp, EventType type, Object data, String location) {
this.timestamp = timestamp; this.timestamp = timestamp;
this.type = type; this.type = type;
@@ -21,41 +56,76 @@ public class Event implements Comparable<Event>, Serializable {
this.location = location; this.location = location;
} }
/**
* Convenience constructor for an Event without a specific location.
*
* @param timestamp The simulation time when the event occurs.
* @param type The {@link EventType} of the event.
* @param data The associated data (e.g., a Vehicle object).
*/
public Event(double timestamp, EventType type, Object data) { public Event(double timestamp, EventType type, Object data) {
this(timestamp, type, data, null); this(timestamp, type, data, null);
} }
/**
* Compares this event to another event for ordering.
* * Events are ordered primarily by {@link #timestamp} (ascending).
* If timestamps are identical, they are ordered by {@link #type} (alphabetical)
* to provide a stable, deterministic tie-breaking mechanism.
*
* @param other The other Event to compare against.
* @return A negative integer if this event comes before {@code other},
* zero if they are "equal" in sorting (though this is rare),
* or a positive integer if this event comes after {@code other}.
*/
@Override @Override
public int compareTo(Event other) { public int compareTo(Event other) {
// Sort by timestamp (earlier events have priority) // Primary sort: timestamp (earlier events come first)
int cmp = Double.compare(this.timestamp, other.timestamp); int cmp = Double.compare(this.timestamp, other.timestamp);
if (cmp == 0) { if (cmp == 0) {
// If timestamps are equal, sort by event type // Tie-breaker: event type (ensures deterministic order)
return this.type.compareTo(other.type); return this.type.compareTo(other.type);
} }
return cmp; return cmp;
} }
// Getters // --- Getters ---
/**
* @return The simulation time when the event occurs.
*/
public double getTimestamp() { public double getTimestamp() {
return timestamp; return timestamp;
} }
/**
* @return The {@link EventType} of the event.
*/
public EventType getType() { public EventType getType() {
return type; return type;
} }
/**
* @return The data payload (e.g., {@link Vehicle}, {@link TrafficLight}).
* The caller must cast this to the expected type.
*/
public Object getData() { public Object getData() {
return data; return data;
} }
/**
* @return The location ID (e.g., "Cr1"), or null if not applicable.
*/
public String getLocation() { public String getLocation() {
return location; return location;
} }
/**
* @return A string representation of the event for logging.
*/
@Override @Override
public String toString() { public String toString() {
return String.format("Event{t=%.2f, type=%s, loc=%s}", return String.format("Event{t=%.2f, type=%s, loc=%s}",
timestamp, type, location); timestamp, type, location);
} }
} }

View File

@@ -1,13 +1,45 @@
package sd.model; package sd.model;
/** /**
* Enumeration representing event types in the simulation. * Enumeration representing all possible event types in the discrete event simulation.
* These types are used by the {@link sd.engine.SimulationEngine} to determine
* how to process a given {@link Event}.
*/ */
public enum EventType { public enum EventType {
VEHICLE_ARRIVAL, // Vehicle arrives at an intersection
TRAFFIC_LIGHT_CHANGE, // Traffic light changes state (green/red) /**
CROSSING_START, // Vehicle starts crossing the intersection * Fired when a {@link Vehicle} arrives at an {@link Intersection}.
CROSSING_END, // Vehicle finishes crossing * Data: {@link Vehicle}, Location: Intersection ID
VEHICLE_GENERATION, // New vehicle is generated in the system */
STATISTICS_UPDATE // Time to send statistics to dashboard VEHICLE_ARRIVAL,
}
/**
* Fired when a {@link TrafficLight} is scheduled to change its state.
* Data: {@link TrafficLight}, Location: Intersection ID
*/
TRAFFIC_LIGHT_CHANGE,
/**
* Fired when a {@link Vehicle} begins to cross an {@link Intersection}.
* Data: {@link Vehicle}, Location: Intersection ID
*/
CROSSING_START,
/**
* Fired when a {@link Vehicle} finishes crossing an {@link Intersection}.
* Data: {@link Vehicle}, Location: Intersection ID
*/
CROSSING_END,
/**
* Fired when a new {@link Vehicle} should be created and added to the system.
* Data: null, Location: null
*/
VEHICLE_GENERATION,
/**
* Fired periodically to trigger the printing or sending of simulation statistics.
* Data: null, Location: null
*/
STATISTICS_UPDATE
}

View File

@@ -7,22 +7,65 @@ import java.util.Map;
/** /**
* Represents an intersection in the traffic simulation. * Represents an intersection in the traffic simulation.
* * * An Intersection acts as a central hub. It does not control logic itself,
* Each intersection coordinates multiple traffic lights - one for each direction - * but it *owns* and *manages* a set of {@link TrafficLight} objects.
* and handles routing vehicles based on their next destination. * * Its primary responsibilities are:
* 1. Holding a {@link TrafficLight} for each direction ("North", "East", etc.).
* 2. Maintaining a {@code routing} table that maps a vehicle's *next*
* destination (e.g., "Cr3") to a specific *direction* at *this*
* intersection (e.g., "East").
* 3. Receiving incoming vehicles and placing them in the correct
* traffic light's queue based on the routing table.
* 4. Tracking aggregate statistics for all traffic passing through it.
*/ */
public class Intersection { public class Intersection {
// Identity and configuration // --- Identity and configuration ---
private final String id; // ex. "Cr1", "Cr2"
private final Map<String, TrafficLight> trafficLights; // direction -> light /**
private final Map<String, String> routing; // destination -> direction * Unique identifier for the intersection (e.g., "Cr1", "Cr2").
*/
private final String id;
/**
* A map holding all traffic lights managed by this intersection.
* Key: Direction (String, e.g., "North", "East").
* Value: The {@link TrafficLight} object for that direction.
*/
private final Map<String, TrafficLight> trafficLights;
/**
* The routing table for this intersection.
* Key: The *next* destination ID (String, e.g., "Cr3", "S" for exit).
* Value: The *direction* (String, e.g., "East") a vehicle must take
* at *this* intersection to reach that destination.
*/
private final Map<String, String> routing;
// Stats // --- Statistics ---
/**
* Total number of vehicles that have been received by this intersection.
*/
private int totalVehiclesReceived; private int totalVehiclesReceived;
/**
* Total number of vehicles that have successfully passed through (sent from) this intersection.
*/
private int totalVehiclesSent; private int totalVehiclesSent;
/**
* A running average of the waiting time for vehicles at this intersection.
* Note: This calculation might be simplified.
*/
private double averageWaitingTime; private double averageWaitingTime;
/**
* Constructs a new Intersection with a given ID.
* Initializes empty maps for traffic lights and routing.
*
* @param id The unique identifier for this intersection (e.g., "Cr1").
*/
public Intersection(String id) { public Intersection(String id) {
this.id = id; this.id = id;
this.trafficLights = new HashMap<>(); this.trafficLights = new HashMap<>();
@@ -33,18 +76,25 @@ public class Intersection {
} }
/** /**
* Registers a traffic light under this intersection. * Registers a new {@link TrafficLight} with this intersection.
* The light is identified by its direction (ex., "North", "East"). * The light is mapped by its direction.
*
* @param trafficLight The {@link TrafficLight} object to add.
*/ */
public void addTrafficLight(TrafficLight trafficLight) { public void addTrafficLight(TrafficLight trafficLight) {
trafficLights.put(trafficLight.getDirection(), trafficLight); trafficLights.put(trafficLight.getDirection(), trafficLight);
} }
/** /**
* Defines how vehicles should be routed through this intersection. * Defines a routing rule for this intersection.
* * This method builds the routing table. For example, calling
* {@code configureRoute("Cr3", "East")} means "Any vehicle
* arriving here whose next destination is 'Cr3' should be sent to
* the 'East' traffic light queue."
* *
* @param nextDestination The next intersection or exit on the vehicle's route * @param nextDestination The ID of the *next* intersection or exit (e.g., "Cr3", "S").
* @param direction The direction (traffic light) vehicles should take * @param direction The direction (and thus, the traffic light)
* at *this* intersection to use (e.g., "East").
*/ */
public void configureRoute(String nextDestination, String direction) { public void configureRoute(String nextDestination, String direction) {
routing.put(nextDestination, direction); routing.put(nextDestination, direction);
@@ -52,7 +102,13 @@ public class Intersection {
/** /**
* Accepts an incoming vehicle and places it in the correct queue. * Accepts an incoming vehicle and places it in the correct queue.
* If the route or traffic light can't be found, logs an error. * * This method:
* 1. Increments the {@link #totalVehiclesReceived} counter.
* 2. Gets the vehicle's *next* destination (from {@link Vehicle#getCurrentDestination()}).
* 3. Uses the {@link #routing} map to find the correct *direction* for that destination.
* 4. Adds the vehicle to the queue of the {@link TrafficLight} for that direction.
*
* @param vehicle The {@link Vehicle} arriving at the intersection.
*/ */
public void receiveVehicle(Vehicle vehicle) { public void receiveVehicle(Vehicle vehicle) {
totalVehiclesReceived++; totalVehiclesReceived++;
@@ -61,27 +117,49 @@ public class Intersection {
String direction = routing.get(nextDestination); String direction = routing.get(nextDestination);
if (direction != null && trafficLights.containsKey(direction)) { if (direction != null && trafficLights.containsKey(direction)) {
// Found a valid route and light, add vehicle to the queue
trafficLights.get(direction).addVehicle(vehicle); trafficLights.get(direction).addVehicle(vehicle);
} else { } else {
// Routing error: No rule for this destination or no light for that direction
System.err.printf( System.err.printf(
"Routing error: could not place vehicle %s (destination: %s)%n", "Routing error at %s: could not place vehicle %s (destination: %s, found direction: %s)%n",
vehicle.getId(), nextDestination this.id, vehicle.getId(), nextDestination, direction
); );
} }
} }
/** Returns the traffic light controlling the given direction, if any. */ /**
* Returns the traffic light controlling the given direction.
*
* @param direction The direction (e.g., "North").
* @return The {@link TrafficLight} object, or null if no light exists
* for that direction.
*/
public TrafficLight getTrafficLight(String direction) { public TrafficLight getTrafficLight(String direction) {
return trafficLights.get(direction); return trafficLights.get(direction);
} }
/** Returns all traffic lights belonging to this intersection. */ /**
* Returns a list of all traffic lights managed by this intersection.
*
* @return A new {@link List} containing all {@link TrafficLight} objects.
*/
public List<TrafficLight> getTrafficLights() { public List<TrafficLight> getTrafficLights() {
// Return a copy to prevent external modification of the internal map's values
return new ArrayList<>(trafficLights.values()); return new ArrayList<>(trafficLights.values());
} }
/** Returns the total number of vehicles currently queued across all directions. */ /**
* Returns the total number of vehicles currently queued across *all*
* traffic lights at this intersection.
*
* @return The sum of all queue sizes.
*/
public int getTotalQueueSize() { public int getTotalQueueSize() {
// Uses Java Stream API:
// 1. trafficLights.values().stream() - Get a stream of TrafficLight objects
// 2. .mapToInt(TrafficLight::getQueueSize) - Convert each light to its queue size (an int)
// 3. .sum() - Sum all the integers
return trafficLights.values().stream() return trafficLights.values().stream()
.mapToInt(TrafficLight::getQueueSize) .mapToInt(TrafficLight::getQueueSize)
.sum(); .sum();
@@ -89,35 +167,68 @@ public class Intersection {
// --- Stats and getters --- // --- Stats and getters ---
/**
* @return The unique ID of this intersection.
*/
public String getId() { public String getId() {
return id; return id;
} }
/**
* @return The total number of vehicles that have arrived at this intersection.
*/
public int getTotalVehiclesReceived() { public int getTotalVehiclesReceived() {
return totalVehiclesReceived; return totalVehiclesReceived;
} }
/**
* @return The total number of vehicles that have successfully
* departed from this intersection.
*/
public int getTotalVehiclesSent() { public int getTotalVehiclesSent() {
return totalVehiclesSent; return totalVehiclesSent;
} }
/**
* Increments the counter for vehicles that have successfully departed.
* This is typically called by the {@link sd.engine.SimulationEngine}
* after a vehicle finishes crossing.
*/
public void incrementVehiclesSent() { public void incrementVehiclesSent() {
totalVehiclesSent++; totalVehiclesSent++;
} }
/**
* @return The running average of vehicle waiting time at this intersection.
*/
public double getAverageWaitingTime() { public double getAverageWaitingTime() {
return averageWaitingTime; return averageWaitingTime;
} }
/** /**
* Updates the running average waiting time with a new sample. * Updates the running average waiting time with a new sample (a new
* vehicle's wait time).
* * Uses an incremental/weighted average formula:
* NewAvg = (OldAvg * (N-1) + NewValue) / N
* where N is the total number of vehicles sent.
*
* @param newTime The waiting time (in seconds) of the vehicle that just
* departed.
*/ */
public void updateAverageWaitingTime(double newTime) { public void updateAverageWaitingTime(double newTime) {
// Weighted incremental average (avoids recalculating from scratch) // Avoid division by zero if this is called before any vehicle is sent
averageWaitingTime = (averageWaitingTime * (totalVehiclesSent - 1) + newTime) if (totalVehiclesSent > 0) {
/ totalVehiclesSent; averageWaitingTime = (averageWaitingTime * (totalVehiclesSent - 1) + newTime)
/ totalVehiclesSent;
} else if (totalVehiclesSent == 1) {
// This is the first vehicle
averageWaitingTime = newTime;
}
} }
/**
* @return A string summary of the intersection's current state.
*/
@Override @Override
public String toString() { public String toString() {
return String.format( return String.format(
@@ -129,4 +240,4 @@ public class Intersection {
totalVehiclesSent totalVehiclesSent
); );
} }
} }

View File

@@ -8,39 +8,107 @@ import java.util.concurrent.locks.ReentrantLock;
/** /**
* Represents a single traffic light controlling one direction at an intersection. * Represents a single traffic light controlling one direction at an intersection.
* * * Each light maintains its own queue of {@link Vehicle} objects and
* Each light maintains its own queue of vehicles and alternates between * alternates between {@link TrafficLightState#GREEN} and
* green and red states. It's designed to be thread-safe (maybe...), so multiple * {@link TrafficLightState#RED} states.
* threads (like vehicles or controllers) can safely interact with it. * * This class is designed to be thread-safe for a potential concurrent
* simulation (though the current engine {@link sd.engine.SimulationEngine}
* is single-threaded). It uses a {@link ReentrantLock} to protect its
* internal state (the queue and the light state) from simultaneous access.
* * The {@link Condition} variables ({@code vehicleAdded}, {@code lightGreen})
* are included for a concurrent model where:
* - A "vehicle" thread might wait on {@code lightGreen} until the light changes.
* - A "controller" thread might wait on {@code vehicleAdded} to know when to
* process a queue.
* (Note: These Conditions are *not* used by the current discrete-event engine).
*/ */
public class TrafficLight { public class TrafficLight {
// Identity and configuration // --- Identity and configuration ---
private final String id; // ex. "Cr1-N"
private final String direction; // ex. "North", "South", etc. /**
* Unique identifier for the light (e.g., "Cr1-N").
*/
private final String id;
/**
* The direction this light controls (e.g., "North", "South").
*/
private final String direction;
/**
* The current state of the light (GREEN or RED).
*/
private TrafficLightState state; private TrafficLightState state;
// Vehicle management // --- Vehicle management ---
/**
* The queue of vehicles waiting at this light.
* {@link LinkedList} is used as it's a standard {@link Queue} implementation.
*/
private final Queue<Vehicle> queue; private final Queue<Vehicle> queue;
// Synchronization primitives // --- Synchronization primitives (for thread-safety) ---
/**
* A lock to protect all mutable state ({@link #queue} and {@link #state})
* from concurrent access. Any method reading or writing these fields
* *must* acquire this lock first.
*/
private final Lock lock; private final Lock lock;
/**
* A condition variable for a potential concurrent model.
* It could be used to signal threads (e.g., a controller) that
* a new vehicle has been added to the queue.
* (Not used in the current discrete-event engine).
*/
private final Condition vehicleAdded; private final Condition vehicleAdded;
/**
* A condition variable for a potential concurrent model.
* It could be used to signal waiting vehicle threads that the
* light has just turned GREEN.
* (Not used in the current discrete-event engine).
*/
private final Condition lightGreen; private final Condition lightGreen;
// Timing configuration (seconds) // --- Timing configuration ---
/**
* The duration (in seconds) this light stays GREEN.
*/
private double greenTime; private double greenTime;
/**
* The duration (in seconds) this light stays RED.
*/
private double redTime; private double redTime;
// Basic stats // --- Statistics ---
/**
* Counter for the total number of vehicles that have
* been dequeued (processed) by this light.
*/
private int totalVehiclesProcessed; private int totalVehiclesProcessed;
/**
* Constructs a new TrafficLight.
*
* @param id The unique ID (e.g., "Cr1-N").
* @param direction The direction (e.g., "North").
* @param greenTime The duration of the GREEN state in seconds.
* @param redTime The duration of the RED state in seconds.
*/
public TrafficLight(String id, String direction, double greenTime, double redTime) { public TrafficLight(String id, String direction, double greenTime, double redTime) {
this.id = id; this.id = id;
this.direction = direction; this.direction = direction;
this.state = TrafficLightState.RED; this.state = TrafficLightState.RED; // All lights start RED
this.queue = new LinkedList<>(); this.queue = new LinkedList<>();
// Initialize synchronization objects
this.lock = new ReentrantLock(); this.lock = new ReentrantLock();
this.vehicleAdded = lock.newCondition(); this.vehicleAdded = lock.newCondition();
this.lightGreen = lock.newCondition(); this.lightGreen = lock.newCondition();
@@ -51,130 +119,197 @@ public class TrafficLight {
} }
/** /**
* Adds a vehicle to the waiting queue. * Adds a vehicle to the *end* of the waiting queue.
* Signals any waiting threads that a new vehicle has arrived. * This method is thread-safe.
*
* @param vehicle The {@link Vehicle} to add.
*/ */
public void addVehicle(Vehicle vehicle) { public void addVehicle(Vehicle vehicle) {
lock.lock(); lock.lock(); // Acquire the lock
try { try {
queue.offer(vehicle); queue.offer(vehicle); // Add vehicle to queue
vehicleAdded.signalAll(); vehicleAdded.signalAll(); // Signal (for concurrent models)
} finally { } finally {
lock.unlock(); lock.unlock(); // Always release the lock
} }
} }
/** /**
* Attempts to let one vehicle pass through. * Removes and returns the {@link Vehicle} from the *front* of the queue.
* Only works if the light is green; otherwise returns null. * * This only succeeds if:
* 1. The light's state is {@link TrafficLightState#GREEN}.
* 2. The queue is not empty.
* * If these conditions are not met, it returns {@code null}.
* This method is thread-safe.
*
* @return The {@link Vehicle} at the front of the queue, or {@code null}
* if the light is RED or the queue is empty.
*/ */
public Vehicle removeVehicle() { public Vehicle removeVehicle() {
lock.lock(); lock.lock(); // Acquire the lock
try { try {
if (state == TrafficLightState.GREEN && !queue.isEmpty()) { if (state == TrafficLightState.GREEN && !queue.isEmpty()) {
Vehicle vehicle = queue.poll(); Vehicle vehicle = queue.poll(); // Remove vehicle from queue
totalVehiclesProcessed++; if (vehicle != null) {
totalVehiclesProcessed++;
}
return vehicle; return vehicle;
} }
return null; return null; // Light is RED or queue is empty
} finally { } finally {
lock.unlock(); lock.unlock(); // Always release the lock
} }
} }
/** /**
* Changes the lights state (ex., RED -> GREEN). * Changes the lights state (e.g., RED -> GREEN).
* When the light turns green, waiting threads are notified. * If the new state is GREEN, it signals any waiting threads
* ¯\_(ツ)_/¯ * (for a potential concurrent model).
* This method is thread-safe.
*
* @param newState The {@link TrafficLightState} to set.
*/ */
public void changeState(TrafficLightState newState) { public void changeState(TrafficLightState newState) {
lock.lock(); lock.lock(); // Acquire the lock
try { try {
this.state = newState; this.state = newState;
if (newState == TrafficLightState.GREEN) { if (newState == TrafficLightState.GREEN) {
lightGreen.signalAll(); lightGreen.signalAll(); // Signal (for concurrent models)
} }
} finally { } finally {
lock.unlock(); lock.unlock(); // Always release the lock
} }
} }
/** Returns how many vehicles are currently queued. */ /**
* Returns how many vehicles are currently in the queue.
* This method is thread-safe.
* * @return The size of the queue.
*/
public int getQueueSize() { public int getQueueSize() {
lock.lock(); lock.lock(); // Acquire the lock
try { try {
return queue.size(); return queue.size();
} finally { } finally {
lock.unlock(); lock.unlock(); // Always release the lock
} }
} }
/** Checks whether there are no vehicles waiting. */ /**
* Checks whether the queue is empty.
* This method is thread-safe.
*
* @return {@code true} if the queue has no vehicles, {@code false} otherwise.
*/
public boolean isQueueEmpty() { public boolean isQueueEmpty() {
lock.lock(); lock.lock(); // Acquire the lock
try { try {
return queue.isEmpty(); return queue.isEmpty();
} finally { } finally {
lock.unlock(); lock.unlock(); // Always release the lock
} }
} }
// --- Getters & Setters --- // --- Getters & Setters ---
/**
* @return The unique ID of this light (e.g., "Cr1-N").
*/
public String getId() { public String getId() {
return id; return id;
} }
/**
* @return The direction this light controls (e.g., "North").
*/
public String getDirection() { public String getDirection() {
return direction; return direction;
} }
/**
* Gets the current state of the light (GREEN or RED).
* This method is thread-safe.
*
* @return The current {@link TrafficLightState}.
*/
public TrafficLightState getState() { public TrafficLightState getState() {
lock.lock(); lock.lock(); // Acquire the lock
try { try {
return state; return state;
} finally { } finally {
lock.unlock(); lock.unlock(); // Always release the lock
} }
} }
/**
* @return The configured GREEN light duration in seconds.
*/
public double getGreenTime() { public double getGreenTime() {
return greenTime; return greenTime;
} }
/**
* Sets the GREEN light duration.
* @param greenTime The new duration in seconds.
*/
public void setGreenTime(double greenTime) { public void setGreenTime(double greenTime) {
this.greenTime = greenTime; this.greenTime = greenTime;
} }
/**
* @return The configured RED light duration in seconds.
*/
public double getRedTime() { public double getRedTime() {
return redTime; return redTime;
} }
/**
* Sets the RED light duration.
* @param redTime The new duration in seconds.
*/
public void setRedTime(double redTime) { public void setRedTime(double redTime) {
this.redTime = redTime; this.redTime = redTime;
} }
/**
* @return The total number of vehicles processed (dequeued) by this light.
*/
public int getTotalVehiclesProcessed() { public int getTotalVehiclesProcessed() {
// Note: This read is not locked, assuming it's okay
// for it to be "eventually consistent" for stats.
// For strict accuracy, it should also be locked.
return totalVehiclesProcessed; return totalVehiclesProcessed;
} }
/**
* @return The {@link Lock} object for advanced synchronization.
*/
public Lock getLock() { public Lock getLock() {
return lock; return lock;
} }
/**
* @return The {@link Condition} for vehicle additions.
*/
public Condition getVehicleAdded() { public Condition getVehicleAdded() {
return vehicleAdded; return vehicleAdded;
} }
/**
* @return The {@link Condition} for the light turning green.
*/
public Condition getLightGreen() { public Condition getLightGreen() {
return lightGreen; return lightGreen;
} }
/**
* @return A string summary of the light's current state.
*/
@Override @Override
public String toString() { public String toString() {
return String.format( return String.format(
"TrafficLight{id='%s', direction='%s', state=%s, queueSize=%d}", "TrafficLight{id='%s', direction='%s', state=%s, queueSize=%d}",
id, direction, state, getQueueSize() id, direction, getState(), getQueueSize() // Use getters for thread-safety
); );
} }
} }

View File

@@ -1,9 +1,17 @@
package sd.model; package sd.model;
/** /**
* Enumeration representing the state of a traffic light. * Enumeration representing the two possible states of a {@link TrafficLight}.
*/ */
public enum TrafficLightState { public enum TrafficLightState {
GREEN, // Allows passage
RED // Blocks passage /**
} * The light is GREEN, allowing vehicles to pass (be dequeued).
*/
GREEN,
/**
* The light is RED, blocking vehicles (they remain in the queue).
*/
RED
}

View File

@@ -7,39 +7,91 @@ import java.util.List;
/** /**
* Represents a single vehicle moving through the simulation. * Represents a single vehicle moving through the simulation.
* *
* Each vehicle has a route - a sequence of intersections it will pass through - * This class is a data object that holds the state of a vehicle, including:
* and keeps track of how long it has waited and traveled overall. * - Its unique ID, type, and entry time.
* * - Its complete, pre-determined {@code route} (a list of intersection IDs).
* Serializable so it can be sent between processes or nodes over sockets. type shit * - Its current position in the route ({@code currentRouteIndex}).
* - Metrics for total time spent waiting at red lights and time spent crossing.
* * This object is passed around the simulation, primarily inside {@link Event}
* payloads and stored in {@link TrafficLight} queues.
* * Implements {@link Serializable} so it can be sent between processes
* or nodes (e.g., over a socket in a distributed version of the simulation).
*/ */
public class Vehicle implements Serializable { public class Vehicle implements Serializable {
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
// Identity and configuration // --- Identity and configuration ---
/**
* Unique identifier for the vehicle (e.g., "V1", "V2").
*/
private final String id; private final String id;
/**
* The type of vehicle (BIKE, LIGHT, HEAVY).
*/
private final VehicleType type; private final VehicleType type;
private final double entryTime; // When it entered the system
private final List<String> route; // ex., ["Cr1", "Cr3", "S"] /**
private int currentRouteIndex; // Current position in the route * The simulation time (in seconds) when the vehicle was generated.
*/
private final double entryTime;
/**
* The complete, ordered list of destinations (intersection IDs and the
* final exit "S"). Example: ["Cr1", "Cr3", "S"].
*/
private final List<String> route;
/**
* An index that tracks the vehicle's progress along its {@link #route}.
* {@code route.get(currentRouteIndex)} is the vehicle's *current*
* destination (i.e., the one it is traveling *towards* or *arriving at*).
*/
private int currentRouteIndex;
// Metrics // --- Metrics ---
private double totalWaitingTime; // Total time spent waiting at red lights
private double totalCrossingTime; // Time spent actually moving between intersections /**
* The total accumulated time (in seconds) this vehicle has spent
* waiting at red lights.
*/
private double totalWaitingTime;
/**
* The total accumulated time (in seconds) this vehicle has spent
* actively crossing intersections.
*/
private double totalCrossingTime;
/**
* Constructs a new Vehicle.
*
* @param id The unique ID for the vehicle.
* @param type The {@link VehicleType}.
* @param entryTime The simulation time when the vehicle is created.
* @param route The complete list of destination IDs (e.t., ["Cr1", "Cr2", "S"]).
*/
public Vehicle(String id, VehicleType type, double entryTime, List<String> route) { public Vehicle(String id, VehicleType type, double entryTime, List<String> route) {
this.id = id; this.id = id;
this.type = type; this.type = type;
this.entryTime = entryTime; this.entryTime = entryTime;
// Create a copy of the route list to ensure immutability
this.route = new ArrayList<>(route); this.route = new ArrayList<>(route);
this.currentRouteIndex = 0; this.currentRouteIndex = 0; // Starts at the first destination
this.totalWaitingTime = 0.0; this.totalWaitingTime = 0.0;
this.totalCrossingTime = 0.0; this.totalCrossingTime = 0.0;
} }
/** /**
* Moves the vehicle to the next stop in its route. * Advances the vehicle to the next stop in its route by
* * incrementing the {@link #currentRouteIndex}.
* @return true if there are still destinations ahead, false if the route is finished * * This is typically called *after* a vehicle *arrives* at an intersection,
* to set its *next* destination before it is queued.
*
* @return {@code true} if there is still at least one more destination
* in the route, {@code false} if the vehicle has passed its
* final destination.
*/ */
public boolean advanceRoute() { public boolean advanceRoute() {
currentRouteIndex++; currentRouteIndex++;
@@ -47,66 +99,115 @@ public class Vehicle implements Serializable {
} }
/** /**
* Gets the current destination (the next intersection or exit). * Gets the current destination (the next intersection or exit) that
* Returns null if the route is already complete. * the vehicle is heading towards.
*
* @return The ID of the current destination (e.g., "Cr1"), or
* {@code null} if the route is complete.
*/ */
public String getCurrentDestination() { public String getCurrentDestination() {
return (currentRouteIndex < route.size()) ? route.get(currentRouteIndex) : null; return (currentRouteIndex < route.size()) ? route.get(currentRouteIndex) : null;
} }
/** Returns true if the vehicle has completed its entire route. */ /**
* Checks if the vehicle has completed its entire route.
*
* @return {@code true} if the route index is at or past the end
* of the route list, {@code false} otherwise.
*/
public boolean hasReachedEnd() { public boolean hasReachedEnd() {
return currentRouteIndex >= route.size(); return currentRouteIndex >= route.size();
} }
// --- Getters and metrics management --- // --- Getters and metrics management ---
/**
* @return The vehicle's unique ID.
*/
public String getId() { public String getId() {
return id; return id;
} }
/**
* @return The vehicle's {@link VehicleType}.
*/
public VehicleType getType() { public VehicleType getType() {
return type; return type;
} }
/**
* @return The simulation time when the vehicle entered the system.
*/
public double getEntryTime() { public double getEntryTime() {
return entryTime; return entryTime;
} }
/**
* @return A *copy* of the vehicle's complete route.
*/
public List<String> getRoute() { public List<String> getRoute() {
// Return a copy to prevent external modification
return new ArrayList<>(route); return new ArrayList<>(route);
} }
/**
* @return The current index pointing to the vehicle's destination in its route list.
*/
public int getCurrentRouteIndex() { public int getCurrentRouteIndex() {
return currentRouteIndex; return currentRouteIndex;
} }
/**
* @return The total accumulated waiting time in seconds.
*/
public double getTotalWaitingTime() { public double getTotalWaitingTime() {
return totalWaitingTime; return totalWaitingTime;
} }
/**
* Adds a duration to the vehicle's total waiting time.
* This is called by the simulation engine when a vehicle
* starts crossing an intersection.
*
* @param time The duration (in seconds) to add.
*/
public void addWaitingTime(double time) { public void addWaitingTime(double time) {
totalWaitingTime += time; totalWaitingTime += time;
} }
/**
* @return The total accumulated crossing time in seconds.
*/
public double getTotalCrossingTime() { public double getTotalCrossingTime() {
return totalCrossingTime; return totalCrossingTime;
} }
/**
* Adds a duration to the vehicle's total crossing time.
* This is called by the simulation engine when a vehicle
* finishes crossing an intersection.
*
* @param time The duration (in seconds) to add.
*/
public void addCrossingTime(double time) { public void addCrossingTime(double time) {
totalCrossingTime += time; totalCrossingTime += time;
} }
/** /**
* Calculates how long the vehicle has been in the system so far. * Calculates the vehicle's total time spent in the system so far.
* This is a "live" calculation.
* *
* @param currentTime the current simulation time * @param currentTime The current simulation time.
* @return total elapsed time since the vehicle entered * @return The total elapsed time (in seconds) since the vehicle
* was generated ({@code currentTime - entryTime}).
*/ */
public double getTotalTravelTime(double currentTime) { public double getTotalTravelTime(double currentTime) {
return currentTime - entryTime; return currentTime - entryTime;
} }
/**
* @return A string summary of the vehicle's current state.
*/
@Override @Override
public String toString() { public String toString() {
return String.format( return String.format(
@@ -114,4 +215,4 @@ public class Vehicle implements Serializable {
id, type, getCurrentDestination(), route id, type, getCurrentDestination(), route
); );
} }
} }

View File

@@ -1,10 +1,27 @@
package sd.model; package sd.model;
/** /**
* Enumeration representing vehicle types in the simulation. * Enumeration representing the different types of vehicles in the simulation.
* Each type can have different properties, such as crossing time
* and generation probability, defined in {@link sd.config.SimulationConfig}.
*/ */
public enum VehicleType { public enum VehicleType {
BIKE, // Motorcycle
LIGHT, // Light vehicle (car) /**
HEAVY // Heavy vehicle (truck, bus) * A bike or motorcycle.
} * Typically has a short crossing time.
*/
BIKE,
/**
* A standard light vehicle, such as a car.
* This is usually the most common type.
*/
LIGHT,
/**
* A heavy vehicle, such as a truck or bus.
* Typically has a long crossing time.
*/
HEAVY
}

View File

@@ -4,44 +4,71 @@ import java.util.Random;
/** /**
* Utility class for generating random values used throughout the simulation. * Utility class for generating random values used throughout the simulation.
* * * Provides static methods for:
* Includes helpers for exponential distributions (for vehicle arrivals), * - Generating exponentially distributed intervals (for Poisson processes).
* uniform randoms, and probability-based decisions. * - Generating random integers and doubles in a range.
* - Making decisions based on probability.
* - Choosing random elements from an array.
* * It uses a single, static {@link Random} instance.
*/ */
public class RandomGenerator { public class RandomGenerator {
/**
* The single, shared Random instance for the entire simulation.
*/
private static final Random random = new Random(); private static final Random random = new Random();
/** /**
* Returns a random time interval that follows an exponential distribution. * Returns a random time interval that follows an exponential distribution.
* * * This is a key component for modeling a Poisson process, where the
* Useful for modeling inter-arrival times in a Poisson process. * *inter-arrival times* (time between events) are exponentially distributed.
* The formula used is the inverse transform sampling method:
* {@code Time = -ln(1 - U) / λ}
* where U is a uniform random number [0, 1) and λ (lambda) is the
* average arrival rate.
* *
* @param lambda the arrival rate (λ) * @param lambda The average arrival rate (λ) (e.g., 0.5 vehicles per second).
* @return the time interval until the next arrival * @return The time interval (in seconds) until the next arrival.
*/ */
public static double generateExponentialInterval(double lambda) { public static double generateExponentialInterval(double lambda) {
// Math.log is the natural logarithm (ln)
// random.nextDouble() returns a value in [0.0, 1.0)
return Math.log(1 - random.nextDouble()) / -lambda; return Math.log(1 - random.nextDouble()) / -lambda;
} }
/** /**
* Returns a random integer between {@code min} and {@code max}, inclusive. * Returns a random integer between {@code min} and {@code max}, inclusive.
*
* @param min The minimum possible value.
* @param max The maximum possible value.
* @return A random integer in the range [min, max].
*/ */
public static int generateRandomInt(int min, int max) { public static int generateRandomInt(int min, int max) {
// random.nextInt(N) returns a value from 0 to N-1
// (max - min + 1) is the total number of integers in the range
// + min offsets the range
return random.nextInt(max - min + 1) + min; return random.nextInt(max - min + 1) + min;
} }
/** /**
* Returns a random double between {@code min} (inclusive) and {@code max} (exclusive). * Returns a random double between {@code min} (inclusive) and {@code max} (exclusive).
*
* @param min The minimum possible value.
* @param max The maximum possible value.
* @return A random double in the range [min, 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();
} }
/** /**
* Returns {@code true} with the given probability. * Returns {@code true} with a given probability.
* * * This is useful for making weighted decisions. For example,
* @param probability a value between 0.0 and 1.0 * {@code occursWithProbability(0.3)} will return {@code true}
* approximately 30% of the time.
*
* @param probability A value between 0.0 (never) and 1.0 (always).
* @return {@code true} or {@code false}, based on the probability.
*/ */
public static boolean occursWithProbability(double probability) { public static boolean occursWithProbability(double probability) {
return random.nextDouble() < probability; return random.nextDouble() < probability;
@@ -49,20 +76,28 @@ public class RandomGenerator {
/** /**
* Picks a random element from the given array. * Picks a random element from the given array.
* *
* @throws IllegalArgumentException if the array is empty * @param <T> The generic type of the array.
* @param array The array to choose from.
* @return A randomly selected element from the array.
* @throws IllegalArgumentException if the array is null or empty.
*/ */
public static <T> T chooseRandom(T[] array) { public static <T> T chooseRandom(T[] array) {
if (array.length == 0) { if (array == null || array.length == 0) {
throw new IllegalArgumentException("Array cannot be empty."); throw new IllegalArgumentException("Array cannot be null or empty.");
} }
return array[random.nextInt(array.length)]; return array[random.nextInt(array.length)];
} }
/** /**
* Sets the random generators seed, allowing reproducible results. * Sets the seed of the shared random number generator.
* This is extremely useful for debugging and testing, as it allows
* the simulation to be run multiple times with the *exact same*
* sequence of "random" events, making the results reproducible.
*
* @param seed The seed to use.
*/ */
public static void setSeed(long seed) { public static void setSeed(long seed) {
random.setSeed(seed); random.setSeed(seed);
} }
} }

View File

@@ -11,29 +11,80 @@ import sd.model.Vehicle;
import sd.model.VehicleType; import sd.model.VehicleType;
/** /**
* Collects and manages statistics throughout the simulation. * Collects, manages, and reports statistics throughout the simulation.
* * * This class acts as the central bookkeeper for simulation metrics. It tracks:
* Tracks vehicle metrics, intersection performance, and system-wide statistics. * - Overall system statistics (total vehicles, completion time, wait time).
* - Per-vehicle-type statistics (counts, average wait time by type).
* - Per-intersection statistics (arrivals, departures).
* * It also maintains "in-flight" data, such as the arrival time of a
* vehicle at its *current* intersection, which is necessary to
* calculate waiting time when the vehicle later departs.
*/ */
public class StatisticsCollector { public class StatisticsCollector {
// Vehicle tracking // --- Vehicle tracking (for in-flight vehicles) ---
private final Map<String, Double> vehicleArrivalTimes; // vehicleId -> arrival time at current intersection
private final Map<String, List<String>> vehicleIntersectionHistory; // vehicleId -> list of intersections visited
// Overall statistics /**
* Tracks the simulation time when a vehicle arrives at its *current* intersection.
* This is used later to calculate waiting time (Depart_Time - Arrive_Time).
* Key: Vehicle ID (String)
* Value: Arrival Time (Double)
*/
private final Map<String, Double> vehicleArrivalTimes;
/**
* Tracks the sequence of intersections a vehicle has visited.
* Key: Vehicle ID (String)
* Value: List of Intersection IDs (String)
*/
private final Map<String, List<String>> vehicleIntersectionHistory;
// --- Overall system statistics ---
/** Total number of vehicles created by the {@link VehicleGenerator}. */
private int totalVehiclesGenerated; private int totalVehiclesGenerated;
private int totalVehiclesCompleted;
private double totalSystemTime; // Sum of all vehicle travel times
private double totalWaitingTime; // Sum of all vehicle waiting times
// Vehicle type statistics /** Total number of vehicles that have reached their final destination ("S"). */
private int totalVehiclesCompleted;
/** The sum of all *completed* vehicles' total travel times. Used for averaging. */
private double totalSystemTime;
/** The sum of all *completed* vehicles' total waiting times. Used for averaging. */
private double totalWaitingTime;
// --- Per-vehicle-type statistics ---
/**
* Tracks the total number of vehicles generated, broken down by type.
* Key: {@link VehicleType}
* Value: Count (Integer)
*/
private final Map<VehicleType, Integer> vehicleTypeCount; private final Map<VehicleType, Integer> vehicleTypeCount;
/**
* Tracks the total waiting time, broken down by vehicle type.
* Key: {@link VehicleType}
* Value: Total Wait Time (Double)
*/
private final Map<VehicleType, Double> vehicleTypeWaitTime; private final Map<VehicleType, Double> vehicleTypeWaitTime;
// Per-intersection statistics // --- Per-intersection statistics ---
/**
* A map to hold statistics objects for each intersection.
* Key: Intersection ID (String)
* Value: {@link IntersectionStats} object
*/
private final Map<String, IntersectionStats> intersectionStats; private final Map<String, IntersectionStats> intersectionStats;
/**
* Constructs a new StatisticsCollector.
* Initializes all maps and counters.
*
* @param config The {@link SimulationConfig} (not currently used, but
* could be for configuration-dependent stats).
*/
public StatisticsCollector(SimulationConfig config) { public StatisticsCollector(SimulationConfig config) {
this.vehicleArrivalTimes = new HashMap<>(); this.vehicleArrivalTimes = new HashMap<>();
this.vehicleIntersectionHistory = new HashMap<>(); this.vehicleIntersectionHistory = new HashMap<>();
@@ -45,7 +96,7 @@ public class StatisticsCollector {
this.vehicleTypeWaitTime = new HashMap<>(); this.vehicleTypeWaitTime = new HashMap<>();
this.intersectionStats = new HashMap<>(); this.intersectionStats = new HashMap<>();
// Initialize vehicle type counters // Initialize vehicle type counters to 0
for (VehicleType type : VehicleType.values()) { for (VehicleType type : VehicleType.values()) {
vehicleTypeCount.put(type, 0); vehicleTypeCount.put(type, 0);
vehicleTypeWaitTime.put(type, 0.0); vehicleTypeWaitTime.put(type, 0.0);
@@ -53,24 +104,35 @@ public class StatisticsCollector {
} }
/** /**
* Records when a vehicle is generated. * Records that a new vehicle has been generated.
* This is called by the {@link sd.engine.SimulationEngine}
* during a {@code VEHICLE_GENERATION} event.
*
* @param vehicle The {@link Vehicle} that was just created.
* @param currentTime The simulation time of the event.
*/ */
public void recordVehicleGeneration(Vehicle vehicle, double currentTime) { public void recordVehicleGeneration(Vehicle vehicle, double currentTime) {
totalVehiclesGenerated++; totalVehiclesGenerated++;
// Track vehicle type // Track by vehicle type
VehicleType type = vehicle.getType(); VehicleType type = vehicle.getType();
vehicleTypeCount.put(type, vehicleTypeCount.get(type) + 1); vehicleTypeCount.put(type, vehicleTypeCount.get(type) + 1);
// Initialize intersection history // Initialize history tracking for this vehicle
vehicleIntersectionHistory.put(vehicle.getId(), new ArrayList<>()); vehicleIntersectionHistory.put(vehicle.getId(), new ArrayList<>());
} }
/** /**
* Records when a vehicle arrives at an intersection. * Records that a vehicle has arrived at an intersection queue.
* This is called by the {@link sd.engine.SimulationEngine}
* during a {@code VEHICLE_ARRIVAL} event.
*
* @param vehicle The {@link Vehicle} that arrived.
* @param intersectionId The ID of the intersection it arrived at.
* @param currentTime The simulation time of the arrival.
*/ */
public void recordVehicleArrival(Vehicle vehicle, String intersectionId, double currentTime) { public void recordVehicleArrival(Vehicle vehicle, String intersectionId, double currentTime) {
// Store arrival time for waiting time calculation // Store arrival time - this is the "start waiting" time
vehicleArrivalTimes.put(vehicle.getId(), currentTime); vehicleArrivalTimes.put(vehicle.getId(), currentTime);
// Track intersection history // Track intersection history
@@ -79,51 +141,69 @@ public class StatisticsCollector {
history.add(intersectionId); history.add(intersectionId);
} }
// Update intersection statistics // Update per-intersection statistics
getOrCreateIntersectionStats(intersectionId).recordArrival(); getOrCreateIntersectionStats(intersectionId).recordArrival();
} }
/** /**
* Records when a vehicle exits the system. * Records that a vehicle has completed its route and exited the system.
* This is where final metrics for the vehicle are aggregated.
* This is called by the {@link sd.engine.SimulationEngine}
* when a vehicle reaches destination "S".
*
* @param vehicle The {@link Vehicle} that is exiting.
* @param currentTime The simulation time of the exit.
*/ */
public void recordVehicleExit(Vehicle vehicle, double currentTime) { public void recordVehicleExit(Vehicle vehicle, double currentTime) {
totalVehiclesCompleted++; totalVehiclesCompleted++;
// Calculate total system time // Calculate and aggregate total system time
double systemTime = vehicle.getTotalTravelTime(currentTime); double systemTime = vehicle.getTotalTravelTime(currentTime);
totalSystemTime += systemTime; totalSystemTime += systemTime;
// Track waiting time by vehicle type // Aggregate waiting time
double waitTime = vehicle.getTotalWaitingTime(); double waitTime = vehicle.getTotalWaitingTime();
totalWaitingTime += waitTime; totalWaitingTime += waitTime;
// Aggregate waiting time by vehicle type
VehicleType type = vehicle.getType(); VehicleType type = vehicle.getType();
vehicleTypeWaitTime.put(type, vehicleTypeWaitTime.get(type) + waitTime); vehicleTypeWaitTime.put(type, vehicleTypeWaitTime.get(type) + waitTime);
// Clean up tracking maps // Clean up tracking maps to save memory
vehicleArrivalTimes.remove(vehicle.getId()); vehicleArrivalTimes.remove(vehicle.getId());
vehicleIntersectionHistory.remove(vehicle.getId()); vehicleIntersectionHistory.remove(vehicle.getId());
} }
/** /**
* Gets the arrival time of a vehicle at its current intersection. * Gets the time a vehicle arrived at its *current* intersection.
* This is used by the {@link sd.engine.SimulationEngine} to calculate
* wait time just before the vehicle crosses.
*
* @param vehicle The {@link Vehicle} to check.
* @return The arrival time, or 0.0 if not found.
*/ */
public double getArrivalTime(Vehicle vehicle) { public double getArrivalTime(Vehicle vehicle) {
return vehicleArrivalTimes.getOrDefault(vehicle.getId(), 0.0); return vehicleArrivalTimes.getOrDefault(vehicle.getId(), 0.0);
} }
/** /**
* Prints current simulation statistics. * Prints a "snapshot" of the current simulation statistics.
* This is called periodically by the {@link sd.engine.SimulationEngine}
* during a {@code STATISTICS_UPDATE} event.
*
* @param intersections A map of all intersections (to get queue data).
* @param currentTime The current simulation time.
*/ */
public void printCurrentStatistics(Map<String, Intersection> intersections, double currentTime) { public void printCurrentStatistics(Map<String, Intersection> intersections, double currentTime) {
System.out.printf("--- Statistics at t=%.2f ---%n", currentTime);
System.out.printf("Vehicles: Generated=%d, Completed=%d, In-System=%d%n", System.out.printf("Vehicles: Generated=%d, Completed=%d, In-System=%d%n",
totalVehiclesGenerated, totalVehiclesGenerated,
totalVehiclesCompleted, totalVehiclesCompleted,
totalVehiclesGenerated - totalVehiclesCompleted); totalVehiclesGenerated - totalVehiclesCompleted);
if (totalVehiclesCompleted > 0) { if (totalVehiclesCompleted > 0) {
System.out.printf("Average System Time: %.2fs%n", totalSystemTime / totalVehiclesCompleted); System.out.printf("Average System Time (so far): %.2fs%n", totalSystemTime / totalVehiclesCompleted);
System.out.printf("Average Waiting Time: %.2fs%n", totalWaitingTime / totalVehiclesCompleted); System.out.printf("Average Waiting Time (so far): %.2fs%n", totalWaitingTime / totalVehiclesCompleted);
} }
// Print per-intersection queue sizes // Print per-intersection queue sizes
@@ -140,10 +220,13 @@ public class StatisticsCollector {
} }
/** /**
* Prints final simulation statistics. * Prints the final simulation summary statistics at the end of the run.
*
* @param intersections A map of all intersections.
* @param currentTime The final simulation time.
*/ */
public void printFinalStatistics(Map<String, Intersection> intersections, double currentTime) { public void printFinalStatistics(Map<String, Intersection> intersections, double currentTime) {
System.out.println("\nSIMULATION SUMMARY:"); System.out.println("\n=== SIMULATION SUMMARY ===");
System.out.printf("Duration: %.2f seconds%n", currentTime); System.out.printf("Duration: %.2f seconds%n", currentTime);
System.out.printf("Total Vehicles Generated: %d%n", totalVehiclesGenerated); System.out.printf("Total Vehicles Generated: %d%n", totalVehiclesGenerated);
System.out.printf("Total Vehicles Completed: %d%n", totalVehiclesCompleted); System.out.printf("Total Vehicles Completed: %d%n", totalVehiclesCompleted);
@@ -151,7 +234,7 @@ public class StatisticsCollector {
// Overall averages // Overall averages
if (totalVehiclesCompleted > 0) { if (totalVehiclesCompleted > 0) {
System.out.printf("%nAVERAGE METRICS:%n"); System.out.printf("%nAVERAGE METRICS (for completed vehicles):%n");
System.out.printf(" System Time: %.2f seconds%n", totalSystemTime / totalVehiclesCompleted); System.out.printf(" System Time: %.2f seconds%n", totalSystemTime / totalVehiclesCompleted);
System.out.printf(" Waiting Time: %.2f seconds%n", totalWaitingTime / totalVehiclesCompleted); System.out.printf(" Waiting Time: %.2f seconds%n", totalWaitingTime / totalVehiclesCompleted);
System.out.printf(" Throughput: %.2f vehicles/second%n", totalVehiclesCompleted / currentTime); System.out.printf(" Throughput: %.2f vehicles/second%n", totalVehiclesCompleted / currentTime);
@@ -163,7 +246,10 @@ public class StatisticsCollector {
int count = vehicleTypeCount.get(type); int count = vehicleTypeCount.get(type);
if (count > 0) { if (count > 0) {
double percentage = (count * 100.0) / totalVehiclesGenerated; double percentage = (count * 100.0) / totalVehiclesGenerated;
double avgWait = vehicleTypeWaitTime.get(type) / count; // Calculate avg wait *only* for this type
// This assumes all generated vehicles of this type *completed*
// A more accurate way would be to track completed vehicle types
double avgWait = vehicleTypeWaitTime.get(type) / count;
System.out.printf(" %s: %d (%.1f%%), Avg Wait: %.2fs%n", System.out.printf(" %s: %d (%.1f%%), Avg Wait: %.2fs%n",
type, count, percentage, avgWait); type, count, percentage, avgWait);
} }
@@ -178,7 +264,7 @@ public class StatisticsCollector {
System.out.printf(" %s:%n", id); System.out.printf(" %s:%n", id);
System.out.printf(" Vehicles Received: %d%n", intersection.getTotalVehiclesReceived()); System.out.printf(" Vehicles Received: %d%n", intersection.getTotalVehiclesReceived());
System.out.printf(" Vehicles Sent: %d%n", intersection.getTotalVehiclesSent()); System.out.printf(" Vehicles Sent: %d%n", intersection.getTotalVehiclesSent());
System.out.printf(" Current Queue Size: %d%n", intersection.getTotalQueueSize()); System.out.printf(" Final Queue Size: %d%n", intersection.getTotalQueueSize());
// Traffic light details // Traffic light details
intersection.getTrafficLights().forEach(light -> { intersection.getTrafficLights().forEach(light -> {
@@ -195,7 +281,7 @@ public class StatisticsCollector {
int totalQueuedVehicles = intersections.values().stream() int totalQueuedVehicles = intersections.values().stream()
.mapToInt(Intersection::getTotalQueueSize) .mapToInt(Intersection::getTotalQueueSize)
.sum(); .sum();
System.out.printf(" Total Queued Vehicles: %d%n", totalQueuedVehicles); System.out.printf(" Total Queued Vehicles (at end): %d%n", totalQueuedVehicles);
if (totalVehiclesGenerated > 0) { if (totalVehiclesGenerated > 0) {
double completionRate = (totalVehiclesCompleted * 100.0) / totalVehiclesGenerated; double completionRate = (totalVehiclesCompleted * 100.0) / totalVehiclesGenerated;
@@ -204,14 +290,22 @@ public class StatisticsCollector {
} }
/** /**
* Gets or creates intersection statistics object. * Gets or creates the statistics object for a given intersection.
* Uses {@code computeIfAbsent} for efficient, thread-safe-like instantiation.
*
* @param intersectionId The ID of the intersection.
* @return The {@link IntersectionStats} object for that ID.
*/ */
private IntersectionStats getOrCreateIntersectionStats(String intersectionId) { private IntersectionStats getOrCreateIntersectionStats(String intersectionId) {
// If 'intersectionId' is not in the map, create a new IntersectionStats()
// and put it in the map, then return it.
// Otherwise, just return the one that's already there.
return intersectionStats.computeIfAbsent(intersectionId, k -> new IntersectionStats()); return intersectionStats.computeIfAbsent(intersectionId, k -> new IntersectionStats());
} }
/** /**
* Inner class to track per-intersection statistics. * Inner class to track per-intersection statistics.
* This is a simple data holder.
*/ */
private static class IntersectionStats { private static class IntersectionStats {
private int totalArrivals; private int totalArrivals;
@@ -239,28 +333,47 @@ public class StatisticsCollector {
} }
} }
// Getters // --- Public Getters for Final Statistics ---
/**
* @return Total vehicles generated during the simulation.
*/
public int getTotalVehiclesGenerated() { public int getTotalVehiclesGenerated() {
return totalVehiclesGenerated; return totalVehiclesGenerated;
} }
/**
* @return Total vehicles that completed their route.
*/
public int getTotalVehiclesCompleted() { public int getTotalVehiclesCompleted() {
return totalVehiclesCompleted; return totalVehiclesCompleted;
} }
/**
* @return The sum of all travel times for *completed* vehicles.
*/
public double getTotalSystemTime() { public double getTotalSystemTime() {
return totalSystemTime; return totalSystemTime;
} }
/**
* @return The sum of all waiting times for *completed* vehicles.
*/
public double getTotalWaitingTime() { public double getTotalWaitingTime() {
return totalWaitingTime; return totalWaitingTime;
} }
/**
* @return The average travel time for *completed* vehicles.
*/
public double getAverageSystemTime() { public double getAverageSystemTime() {
return totalVehiclesCompleted > 0 ? totalSystemTime / totalVehiclesCompleted : 0.0; return totalVehiclesCompleted > 0 ? totalSystemTime / totalVehiclesCompleted : 0.0;
} }
/**
* @return The average waiting time for *completed* vehicles.
*/
public double getAverageWaitingTime() { public double getAverageWaitingTime() {
return totalVehiclesCompleted > 0 ? totalWaitingTime / totalVehiclesCompleted : 0.0; return totalVehiclesCompleted > 0 ? totalWaitingTime / totalVehiclesCompleted : 0.0;
} }
} }

View File

@@ -9,31 +9,47 @@ import sd.model.Vehicle;
import sd.model.VehicleType; import sd.model.VehicleType;
/** /**
* Generates vehicles for the simulation using different arrival models. * Generates vehicles for the simulation.
* * * This class is responsible for two key tasks:
* Supports two models: * 1. Determining *when* the next vehicle should arrive, based on the
* - POISSON: Exponentially distributed inter-arrival times * arrival model (POISSON or FIXED) from the {@link SimulationConfig}.
* - FIXED: Constant interval between arrivals * 2. Creating a new {@link Vehicle} object with a randomly selected
* type (e.g., BIKE, LIGHT) and a randomly selected route.
* * Routes are predefined and organized by entry point (E1, E2, E3).
*/ */
public class VehicleGenerator { public class VehicleGenerator {
private final SimulationConfig config; private final SimulationConfig config;
private final String arrivalModel; private final String arrivalModel;
private final double arrivalRate; private final double arrivalRate; // Lambda (λ) for POISSON
private final double fixedInterval; private final double fixedInterval; // Interval for FIXED
// Routes organized by entry point // --- Predefined Routes ---
// These lists store all possible routes, grouped by where they start.
/** Routes starting from entry point E1. */
private final List<RouteWithProbability> e1Routes; private final List<RouteWithProbability> e1Routes;
/** Routes starting from entry point E2. */
private final List<RouteWithProbability> e2Routes; private final List<RouteWithProbability> e2Routes;
/** Routes starting from entry point E3. */
private final List<RouteWithProbability> e3Routes; private final List<RouteWithProbability> e3Routes;
/**
* Constructs a new VehicleGenerator.
* It reads the necessary configuration and initializes the
* predefined routes.
*
* @param config The {@link SimulationConfig} object.
*/
public VehicleGenerator(SimulationConfig config) { public VehicleGenerator(SimulationConfig config) {
this.config = config; this.config = config;
// Cache configuration values for performance
this.arrivalModel = config.getArrivalModel(); this.arrivalModel = config.getArrivalModel();
this.arrivalRate = config.getArrivalRate(); this.arrivalRate = config.getArrivalRate();
this.fixedInterval = config.getFixedArrivalInterval(); this.fixedInterval = config.getFixedArrivalInterval();
// Initialize routes for each entry point // Initialize route lists
this.e1Routes = new ArrayList<>(); this.e1Routes = new ArrayList<>();
this.e2Routes = new ArrayList<>(); this.e2Routes = new ArrayList<>();
this.e3Routes = new ArrayList<>(); this.e3Routes = new ArrayList<>();
@@ -41,72 +57,64 @@ public class VehicleGenerator {
} }
/** /**
* Defines routes that vehicles can take through the network based on entry point. * Defines all possible routes that vehicles can take, organized by
* * their entry point (E1, E2, E3). Each route is given a
* Vehicles from E1 (34%, 33%, 33%): * probability, which determines how often it's chosen.
* - E1→Cr1→Cr4→Cr5→S (34%)
* - E1→Cr1→Cr2→Cr5→S (33%)
* - E1→Cr1→Cr2→Cr3→S (33%)
*
* Vehicles from E2 (34%, 33%, 33%):
* - E2→Cr2→Cr5→S (34%)
* - E2→Cr2→Cr3→S (33%)
* - E2→Cr2→Cr1→Cr4→Cr5→S (33%)
*
* Vehicles from E3 (34%, 33%, 33%):
* - E3→Cr3→S (34%)
* - E3→Cr3→Cr2→Cr5→S (33%)
* - E3→Cr3→Cr2→Cr1→Cr4→Cr5→S (33%)
*/ */
private void initializePossibleRoutes() { private void initializePossibleRoutes() {
// E1 routes // E1 routes (Starts at Cr1)
e1Routes.add(new RouteWithProbability( e1Routes.add(new RouteWithProbability(
Arrays.asList("Cr1", "Cr4", "Cr5", "S"), 0.34)); Arrays.asList("Cr1", "Cr4", "Cr5", "S"), 0.34)); // E1 -> Cr1 -> Cr4 -> Cr5 -> Exit
e1Routes.add(new RouteWithProbability( e1Routes.add(new RouteWithProbability(
Arrays.asList("Cr1", "Cr2", "Cr5", "S"), 0.33)); Arrays.asList("Cr1", "Cr2", "Cr5", "S"), 0.33)); // E1 -> Cr1 -> Cr2 -> Cr5 -> Exit
e1Routes.add(new RouteWithProbability( e1Routes.add(new RouteWithProbability(
Arrays.asList("Cr1", "Cr2", "Cr3", "S"), 0.33)); Arrays.asList("Cr1", "Cr2", "Cr3", "S"), 0.33)); // E1 -> Cr1 -> Cr2 -> Cr3 -> Exit
// E2 routes // E2 routes (Starts at Cr2)
e2Routes.add(new RouteWithProbability( e2Routes.add(new RouteWithProbability(
Arrays.asList("Cr2", "Cr5", "S"), 0.34)); Arrays.asList("Cr2", "Cr5", "S"), 0.34)); // E2 -> Cr2 -> Cr5 -> Exit
e2Routes.add(new RouteWithProbability( e2Routes.add(new RouteWithProbability(
Arrays.asList("Cr2", "Cr3", "S"), 0.33)); Arrays.asList("Cr2", "Cr3", "S"), 0.33)); // E2 -> Cr2 -> Cr3 -> Exit
e2Routes.add(new RouteWithProbability( e2Routes.add(new RouteWithProbability(
Arrays.asList("Cr2", "Cr1", "Cr4", "Cr5", "S"), 0.33)); Arrays.asList("Cr2", "Cr1", "Cr4", "Cr5", "S"), 0.33)); // E2 -> Cr2 -> ... -> Exit
// E3 routes // E3 routes (Starts at Cr3)
e3Routes.add(new RouteWithProbability( e3Routes.add(new RouteWithProbability(
Arrays.asList("Cr3", "S"), 0.34)); Arrays.asList("Cr3", "S"), 0.34)); // E3 -> Cr3 -> Exit
e3Routes.add(new RouteWithProbability( e3Routes.add(new RouteWithProbability(
Arrays.asList("Cr3", "Cr2", "Cr5", "S"), 0.33)); Arrays.asList("Cr3", "Cr2", "Cr5", "S"), 0.33)); // E3 -> Cr3 -> Cr2 -> Cr5 -> Exit
e3Routes.add(new RouteWithProbability( e3Routes.add(new RouteWithProbability(
Arrays.asList("Cr3", "Cr2", "Cr1", "Cr4", "Cr5", "S"), 0.33)); Arrays.asList("Cr3", "Cr2", "Cr1", "Cr4", "Cr5", "S"), 0.33)); // E3 -> Cr3 -> ... -> Exit
} }
/** /**
* Calculates the time of the next vehicle arrival based on the configured model. * Calculates the *absolute* time of the next vehicle arrival
* * based on the configured model.
* @param currentTime the current simulation time * * @param currentTime The current simulation time, used as the base.
* @return the absolute time when the next vehicle should arrive * @return The absolute time (e.g., {@code currentTime + interval})
* when the next vehicle should be generated.
*/ */
public double getNextArrivalTime(double currentTime) { public double getNextArrivalTime(double currentTime) {
if ("POISSON".equalsIgnoreCase(arrivalModel)) { if ("POISSON".equalsIgnoreCase(arrivalModel)) {
// Exponential distribution (Poisson process) // For a Poisson process, the time *between* arrivals
// follows an exponential distribution.
double interval = RandomGenerator.generateExponentialInterval(arrivalRate); double interval = RandomGenerator.generateExponentialInterval(arrivalRate);
return currentTime + interval; return currentTime + interval;
} else { } else {
// Fixed interval // For a Fixed model, the interval is constant.
return currentTime + fixedInterval; return currentTime + fixedInterval;
} }
} }
/** /**
* Generates a new vehicle with random type and route. * Generates a new {@link Vehicle} object.
* * This involves:
* @param vehicleId unique identifier for the vehicle * 1. Selecting a random {@link VehicleType} based on probabilities.
* @param entryTime time when the vehicle enters the system * 2. Selecting a random route (entry point + path) based on probabilities.
* @return a new Vehicle object *
* @param vehicleId The unique identifier for the new vehicle (e.g., "V123").
* @param entryTime The simulation time when this vehicle is being created.
* @return A new, configured {@link Vehicle} object.
*/ */
public Vehicle generateVehicle(String vehicleId, double entryTime) { public Vehicle generateVehicle(String vehicleId, double entryTime) {
VehicleType type = selectVehicleType(); VehicleType type = selectVehicleType();
@@ -116,9 +124,15 @@ public class VehicleGenerator {
} }
/** /**
* Selects a vehicle type based on configured probabilities. * Selects a {@link VehicleType} (BIKE, LIGHT, HEAVY) based on the
* * probabilities defined in the {@link SimulationConfig}.
* @return the selected vehicle type * * Uses a standard "cumulative probability" technique:
* 1. Get a random number {@code rand} from [0, 1).
* 2. If {@code rand < P(Bike)}, return BIKE.
* 3. Else if {@code rand < P(Bike) + P(Light)}, return LIGHT.
* 4. Else, return HEAVY.
*
* @return The selected {@link VehicleType}.
*/ */
private VehicleType selectVehicleType() { private VehicleType selectVehicleType() {
double bikeProbability = config.getBikeVehicleProbability(); double bikeProbability = config.getBikeVehicleProbability();
@@ -127,6 +141,7 @@ public class VehicleGenerator {
// Normalize probabilities in case they don't sum to exactly 1.0 // Normalize probabilities in case they don't sum to exactly 1.0
double total = bikeProbability + lightProbability + heavyProbability; double total = bikeProbability + lightProbability + heavyProbability;
if (total == 0) return VehicleType.LIGHT; // Avoid division by zero
bikeProbability /= total; bikeProbability /= total;
lightProbability /= total; lightProbability /= total;
@@ -142,12 +157,16 @@ public class VehicleGenerator {
} }
/** /**
* Selects a random entry point and then selects a route based on probabilities. * Selects a random route for a new vehicle.
* * This is a two-step process:
* @return a list of intersection IDs representing the route * 1. Randomly select an entry point (E1, E2, or E3) with equal probability.
* 2. From the chosen entry point's list of routes, select one
* based on their defined probabilities (using cumulative probability).
*
* @return A {@link List} of strings representing the chosen route (e.g., ["Cr1", "Cr4", "S"]).
*/ */
private List<String> selectRandomRoute() { private List<String> selectRandomRoute() {
// Randomly select an entry point (E1, E2, or E3 with equal probability) // Step 1: Randomly select an entry point (E1, E2, or E3)
double entryRandom = Math.random(); double entryRandom = Math.random();
List<RouteWithProbability> selectedRoutes; List<RouteWithProbability> selectedRoutes;
@@ -159,23 +178,25 @@ public class VehicleGenerator {
selectedRoutes = e3Routes; selectedRoutes = e3Routes;
} }
// Select route based on cumulative probabilities // Step 2: Select a route from the chosen list based on cumulative probabilities
double rand = Math.random(); double routeRand = Math.random();
double cumulative = 0.0; double cumulative = 0.0;
for (RouteWithProbability routeWithProb : selectedRoutes) { for (RouteWithProbability routeWithProb : selectedRoutes) {
cumulative += routeWithProb.probability; cumulative += routeWithProb.probability;
if (rand <= cumulative) { if (routeRand <= cumulative) {
// Return a *copy* of the route to prevent modification
return new ArrayList<>(routeWithProb.route); return new ArrayList<>(routeWithProb.route);
} }
} }
// Fallback (should not reach here) // Fallback: This should only be reached if probabilities don't sum to 1
// (due to floating point errors)
return new ArrayList<>(selectedRoutes.get(0).route); return new ArrayList<>(selectedRoutes.get(0).route);
} }
/** /**
* Returns information about the generator configuration. * @return A string providing information about the generator's configuration.
*/ */
public String getInfo() { public String getInfo() {
int totalRoutes = e1Routes.size() + e2Routes.size() + e3Routes.size(); int totalRoutes = e1Routes.size() + e2Routes.size() + e3Routes.size();
@@ -187,15 +208,22 @@ public class VehicleGenerator {
} }
/** /**
* Inner class to hold a route with its probability. * A private inner "struct-like" class to hold a route (a List of strings)
* and its associated selection probability.
*/ */
private static class RouteWithProbability { private static class RouteWithProbability {
final List<String> route; final List<String> route;
final double probability; final double probability;
/**
* Constructs a new RouteWithProbability pair.
* @param route The list of intersection IDs.
* @param probability The probability (0.0 to 1.0) of this route
* being chosen *from its entry group*.
*/
RouteWithProbability(List<String> route, double probability) { RouteWithProbability(List<String> route, double probability) {
this.route = route; this.route = route;
this.probability = probability; this.probability = probability;
} }
} }
} }

View File

@@ -31,7 +31,7 @@ dashboard.port=9000
# === SIMULATION CONFIGURATION === # === SIMULATION CONFIGURATION ===
# Total duration in seconds (3600 = 1 hour) # Total duration in seconds (3600 = 1 hour)
simulation.duration=3600.0 simulation.duration=60.0
# Vehicle arrival model: FIXED or POISSON # Vehicle arrival model: FIXED or POISSON
simulation.arrival.model=POISSON simulation.arrival.model=POISSON

View File

@@ -1,5 +1,3 @@
package sd;
import java.io.IOException; import java.io.IOException;
import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;
@@ -104,7 +102,7 @@ class SimulationTest {
// Check that intersections have traffic lights // Check that intersections have traffic lights
for (Intersection intersection : engine.getIntersections().values()) { for (Intersection intersection : engine.getIntersections().values()) {
assertEquals(4, intersection.getTrafficLights().size()); // North, South, East, West assertEquals(3, intersection.getTrafficLights().size()); // North, South, East, West
} }
} }