VehicleMovementModel.java 13.9 KB
Newer Older
Tobias Meuser's avatar
Tobias Meuser committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
/*
 * Copyright (c) 2005-2010 KOM – Multimedia Communications Lab
 *
 * This file is part of PeerfactSim.KOM.
 *
 * PeerfactSim.KOM is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * any later version.
 *
 * PeerfactSim.KOM is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with PeerfactSim.KOM.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

package de.tud.kom.p2psim.impl.topology.movement;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Queue;
29
import java.util.Random;
Tobias Meuser's avatar
Tobias Meuser committed
30
31
32
33
34
35

import de.tud.kom.p2psim.api.network.SimNetInterface;
import de.tud.kom.p2psim.api.topology.movement.MovementModel;
import de.tud.kom.p2psim.api.topology.movement.SimLocationActuator;
import de.tud.kom.p2psim.impl.network.routed.RoutedNetLayer;
import de.tud.kom.p2psim.impl.topology.PositionVector;
36
37
import de.tud.kom.p2psim.impl.topology.movement.vehicular.sumo.simulation.controller.traci.TraciSimulationController;
import de.tud.kom.p2psim.impl.topology.movement.vehicular.sumo.simulation.controller.xml.XMLSimulationController;
38
import de.tud.kom.p2psim.impl.vehicular.DefaultVehicleInformationComponent;
Tobias Meuser's avatar
Tobias Meuser committed
39
40
41
import de.tudarmstadt.maki.simonstrator.api.Event;
import de.tudarmstadt.maki.simonstrator.api.EventHandler;
import de.tudarmstadt.maki.simonstrator.api.Host;
42
import de.tudarmstadt.maki.simonstrator.api.Randoms;
Tobias Meuser's avatar
Tobias Meuser committed
43
44
45
46
import de.tudarmstadt.maki.simonstrator.api.Time;
import de.tudarmstadt.maki.simonstrator.api.common.graph.INodeID;
import de.tudarmstadt.maki.simonstrator.api.component.ComponentNotAvailableException;
import de.tudarmstadt.maki.simonstrator.api.component.sensor.location.Location;
47
import de.tudarmstadt.maki.simonstrator.api.component.vehicular.VehicleInformationComponent;
48
49
import de.tudarmstadt.maki.simonstrator.api.component.vehicular.api.SimulationSetupExtractor;
import de.tudarmstadt.maki.simonstrator.api.component.vehicular.api.VehicleController;
50
import de.tudarmstadt.maki.simonstrator.api.component.vehicular.roadnetwork.RoadNetwork;
Tobias Meuser's avatar
Tobias Meuser committed
51
52
import de.tudarmstadt.maki.simonstrator.api.util.XMLConfigurableConstructor;

Tobias Meuser's avatar
Tobias Meuser committed
53
public class VehicleMovementModel implements MovementModel, EventHandler {
Tobias Meuser's avatar
Tobias Meuser committed
54

55
56
	private Random _knownRoutesRandom = Randoms.getRandom(getClass());

57
58
	private static final Location DEFAULT_LOCATION = new PositionVector(Double.NaN, Double.NaN);

59
60
	private boolean _reuseComponents = false;

Tobias Meuser's avatar
Tobias Meuser committed
61
62
	private static VehicleMovementModel MOVEMENT;

Tobias Meuser's avatar
Tobias Meuser committed
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
	private long timeBetweenMoveOperations;

	private final List<SimLocationActuator> components;

	private final Queue<SimLocationActuator> freeComponents;

	private final Map<String, SimLocationActuator> idComponentMatcher;

	private final Map<INodeID, String> hostVehicleIDMatching = new HashMap<>();

	private final int offsetX;
	private final int offsetY;
	private final int width;
	private final int height;

78
79
80
	private double scenarioWidth = 0;
	private double scenarioHeight = 0;

Tobias Meuser's avatar
Tobias Meuser committed
81
82
83
	private final String sumoExe;
	private final String sumoConfigFile;
	private final String sumoTrace;
84
	private String sumoIntersections;
Tobias Meuser's avatar
Tobias Meuser committed
85
86
87
88
89
90

	private final long timestepConversion = Time.SECOND;

	private boolean initialized = false;

	private VehicleController _controller;
91
	private SimulationSetupExtractor _extractor;
Tobias Meuser's avatar
Tobias Meuser committed
92

93
94
	private double _percentageOfKnownRoutes = 1;

Tobias Meuser's avatar
Tobias Meuser committed
95
96
97
98
99
100
101
102
103
104
105
106
	/**
	 * Constructor for the movement model using the sumo TraCI API
	 * @param timeBetweenMoveOperations The time between two movement operations.
	 * @param sumoExe The path to the executable of sumo
	 * @param sumoConfigFile The path to the configuration file of the scenario
	 * @param offsetX The offset that should be used. If no offset is required, offset 0 shall be used.
	 * @param offsetY The offset that should be used. If no offset is required, offset 0 shall be used.
	 * @param width The width of the scenario.
	 * @param height The height of the scenario.
	 */
	@XMLConfigurableConstructor({ "timeBetweenMoveOperations", "sumoExe", "sumoConfigFile", "offsetX", "offsetY", "width", "height" })
	public VehicleMovementModel(long timeBetweenMoveOperations, String sumoExe, String sumoConfigFile, String offsetX, String offsetY, String width, String height) {
Tobias Meuser's avatar
Tobias Meuser committed
107
108
		MOVEMENT = this;

Tobias Meuser's avatar
Tobias Meuser committed
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
		this.timeBetweenMoveOperations = timeBetweenMoveOperations;
		this.components = new LinkedList<>();
		this.freeComponents = new LinkedList<>();
		this.idComponentMatcher = new HashMap<>();
		this.sumoExe = sumoExe;
		this.sumoConfigFile = sumoConfigFile;
		this.sumoTrace = null;
		this.offsetX = Integer.parseInt(offsetX);
		this.offsetY = Integer.parseInt(offsetY);
		this.width = Integer.parseInt(width);
		this.height = Integer.parseInt(height);
	}

	/**
	 * Constructor for the movement model using the a generated sumo trace file
	 * @param timeBetweenMoveOperations The time between two movement operations.
	 * @param sumoTrace The path to the vehicle movement file (*.xml)
	 * @param sumoIntersections The path to the intersections file (*.csv)
	 * @param offsetX The offset that should be used. If no offset is required, offset 0 shall be used.
	 * @param offsetY The offset that should be used. If no offset is required, offset 0 shall be used.
	 * @param width The width of the scenario.
	 * @param height The height of the scenario.
	 */
	@XMLConfigurableConstructor({ "timeBetweenMoveOperations", "sumoTrace", "sumoIntersections", "offsetX", "offsetY", "width", "height" })
	public VehicleMovementModel(long timeBetweenMoveOperations, String sumoTrace, String sumoIntersections, int offsetX, int offsetY, int width, int height) {
Tobias Meuser's avatar
Tobias Meuser committed
134
135
		MOVEMENT = this;

Tobias Meuser's avatar
Tobias Meuser committed
136
137
138
139
140
141
142
143
144
145
146
147
148
149
		this.timeBetweenMoveOperations = timeBetweenMoveOperations;
		this.components = new LinkedList<>();
		this.freeComponents = new LinkedList<>();
		this.idComponentMatcher = new HashMap<>();
		this.sumoExe = null;
		this.sumoConfigFile = null;
		this.sumoTrace = sumoTrace;
		this.sumoIntersections = sumoIntersections;
		this.offsetX = offsetX;
		this.offsetY = offsetY;
		this.width = width;
		this.height = height;
	}

150
151
152
153
154
155
156
	/**
	 * @param pPercentageOfKnownRoutes the percentageOfKnownRoutes to set
	 */
	public void setPercentageOfKnownRoutes(double pPercentageOfKnownRoutes) {
		_percentageOfKnownRoutes = pPercentageOfKnownRoutes;
	}

157
158
159
160
161
162
163
164
	public void setReuseComponents(boolean pReuseComponents) {
		_reuseComponents = pReuseComponents;

		if (_reuseComponents) {
			System.err.println("WARNING: Enabling the reuse of components might cause strange behaviors of your simulation!");
		}
	}

Tobias Meuser's avatar
Tobias Meuser committed
165
166
167
168
169
170
171
172
	/**
	 * Adding an additional component to be moved by this movement model
	 * @param comp The component to be added.
	 */
	@Override
	public final void addComponent(SimLocationActuator comp) {
		components.add(comp);
		freeComponents.add(comp);
173

174
		comp.updateCurrentLocation(DEFAULT_LOCATION);
Tobias Meuser's avatar
Tobias Meuser committed
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
	}

	/**
	 * Returns the time between movement operations
	 * @return time between movement operations
	 */
	public long getTimeBetweenMoveOperations() {
		return timeBetweenMoveOperations;
	}

	/**
	 * Set the time between movement operations
	 * @param time the time between movement operations
	 */
	@Override
	public void setTimeBetweenMoveOperations(long time) {
		this.timeBetweenMoveOperations = time;
	}

	/**
	 * Place a component at the correct location
	 * @param actuator The component to be placed.
	 */
	@Override
	public void placeComponent(SimLocationActuator actuator) {
		if (!initialized) {
			initializeModel();
202
203
204

			VehicleMovementModel.getRoadNetwork();

Tobias Meuser's avatar
Tobias Meuser committed
205
206
207
			initialized = true;
		}
		// Initial placement
208
		actuator.updateCurrentLocation(DEFAULT_LOCATION);
Tobias Meuser's avatar
Tobias Meuser committed
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
	}

	/**
	 * Initializes the movement model by executing BonnMotion and parsing the
	 * resulting movement trace.
	 */
	protected void initializeModel() {
		// Schedule first step
		if (!initialized) {
			Event.scheduleWithDelay(timeBetweenMoveOperations, this, null, 0);

			if (sumoExe != null) {
				TraciSimulationController simulationController = TraciSimulationController.createSimulationController(sumoExe, sumoConfigFile);
				_controller = simulationController;
				_controller.setObservedArea(offsetX, offsetY, offsetX + width, offsetY + height);
224
				_controller.init();
Tobias Meuser's avatar
Tobias Meuser committed
225
226
				_controller.nextStep();

227
				_extractor = simulationController;
Tobias Meuser's avatar
Tobias Meuser committed
228
229
230
231
232
233
234
235
236
237
238
239
240
			} else {
				XMLSimulationController simulationController;
				if (sumoIntersections == null || sumoIntersections.equals("")) {
					simulationController = new XMLSimulationController(sumoTrace);
				} else {
					simulationController = new XMLSimulationController(sumoTrace, sumoIntersections);
				}

				_controller = simulationController;
				_controller.setObservedArea(offsetX, offsetY, offsetX + width, offsetY + height);
				_controller.init();
				_controller.nextStep();

241
				_extractor = simulationController;
Tobias Meuser's avatar
Tobias Meuser committed
242
			}
243

244
245
			scenarioWidth = _extractor.getScenarioWidth();
			scenarioHeight = _extractor.getScenarioHeight();
Tobias Meuser's avatar
Tobias Meuser committed
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265

			System.out.println("Initialization: done.");
		}
	}

	/**
	 * Used for the periodical updates of the vehicle positions
	 * @param content not used in this case, should be null
	 * @param type not used in this case, should be 0
	 */
	@Override
	public void eventOccurred(Object content, int type) {
		/*
		 * One event for all nodes (synchronized movement), as this boosts
		 * simulation performance due to less recalculations in the network
		 * models.
		 */
		long currentTime = Time.getCurrentTime() / timestepConversion;

		while (_controller.getStep() - _controller.getStart() < currentTime) {
266
267
268
			if (!_controller.nextStep()) {
				return;
			}
Tobias Meuser's avatar
Tobias Meuser committed
269
270
271
272
273
274
275
		}

		List<String> allVehicles = _controller.getAllVehicles();

		for (int i = 0; i < allVehicles.size(); i++) {
			String vehicle = allVehicles.get(i);

Tobias Meuser's avatar
Tobias Meuser committed
276
			Location position = _controller.getVehiclePosition(vehicle);
Tobias Meuser's avatar
Tobias Meuser committed
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294

			if (position == null) {
				allVehicles.remove(i--);
				continue;
			}

			SimLocationActuator component = requestSimActuator(vehicle);

			try {
				RoutedNetLayer routedNetLayer = component.getHost().getComponent(RoutedNetLayer.class);
				for (SimNetInterface netInterface : routedNetLayer.getSimNetworkInterfaces()) {
					if (netInterface.isOffline()) {
						netInterface.goOnline();
					}
				}
			} catch (ComponentNotAvailableException e) {
				e.printStackTrace();
			}
295

296
			component.updateCurrentLocation(new PositionVector(position.getLongitudeOrX(), position.getLatitudeOrY()));
297
298
299

			component.setMovementSpeed(_controller.getVehicleSpeed(vehicle));

Tobias Meuser's avatar
Tobias Meuser committed
300
301
302
303
304
305
306
307
308
309
310
311
		}

		if (allVehicles.size() != idComponentMatcher.size()) {
			ArrayList<String> registeredVehicles = new ArrayList<>(idComponentMatcher.keySet());
			for (int i = 0; i < registeredVehicles.size(); i++) {
				String vehicle = registeredVehicles.get(i);
				if (!allVehicles.contains(vehicle)) {
					addFreeHost(vehicle);
				}
			}
		}

312
313
314
315
316
317
		if (Time.getCurrentTime() < 5 * Time.SECOND) {
			for (SimLocationActuator simLocationActuator : freeComponents) {
				simLocationActuator.updateCurrentLocation(DEFAULT_LOCATION);
			}
		}

Tobias Meuser's avatar
Tobias Meuser committed
318
319
320
321
322
323
324
325
326
327
328
329
		// Reschedule next step
		Event.scheduleWithDelay(timeBetweenMoveOperations, this, null, 0);
	}

	/**
	 * Remove a vehicle from the set of moved components as the vehicle has stopped driving
	 * @param vehicleID The stopped vehicle
	 */
	private void addFreeHost(String vehicleID) {
		if (idComponentMatcher.containsKey(vehicleID)) {
			SimLocationActuator simLocationActuator = idComponentMatcher.remove(vehicleID);
			if (simLocationActuator != null) {
330
331
332
333
334
335
336
				try {
					VehicleInformationComponent vehicularHostComponent = simLocationActuator.getHost().getComponent(VehicleInformationComponent.class);
					vehicularHostComponent.resetVehicleID();
				} catch (ComponentNotAvailableException e) {
					// Nothing to do here
				}

Tobias Meuser's avatar
Tobias Meuser committed
337
				hostVehicleIDMatching.remove(simLocationActuator.getHost().getId());
338
339
340
341
342
343
344
345
346
347
348

				try {
					RoutedNetLayer routedNetLayer = simLocationActuator.getHost().getComponent(RoutedNetLayer.class);
					for (SimNetInterface netInterface : routedNetLayer.getSimNetworkInterfaces()) {
						if (netInterface.isOnline()) {
							netInterface.goOffline();
						}
					}
				} catch (ComponentNotAvailableException e) {
					e.printStackTrace();
				}
349
				simLocationActuator.updateCurrentLocation(DEFAULT_LOCATION);
350
351
352
353

				if (_reuseComponents) {
					freeComponents.add(simLocationActuator);
				}
Tobias Meuser's avatar
Tobias Meuser committed
354
355
356
357
358
359
360
361
362
363
364
365
366
			}
		}
	}

	/**
	 * Request a component for a vehicle. If no component has been assigned to the vehicle yet, a new component is assigned.
	 * @param vehicle The vehicle for which a component is requested.
	 * @throws RuntimeException If no component can be assigned.
	 * @return The component for the vehicle.
	 */
	private SimLocationActuator requestSimActuator(String vehicle) {
		if (!idComponentMatcher.containsKey(vehicle)) {
			SimLocationActuator simLocationActuator = freeComponents.poll();
367

Tobias Meuser's avatar
Tobias Meuser committed
368
			if (simLocationActuator != null) {
369
370
371
372
373
				VehicleInformationComponent vehicularHostComponent;
				try {
					vehicularHostComponent = simLocationActuator.getHost().getComponent(VehicleInformationComponent.class);
				} catch (ComponentNotAvailableException e) {
					Host host = simLocationActuator.getHost();
374
375
376
377
378
379
380
					boolean routeKnown;
					if (_knownRoutesRandom.nextDouble() < _percentageOfKnownRoutes) {
						routeKnown = true;
					} else {
						routeKnown = false;
					}
					vehicularHostComponent = new DefaultVehicleInformationComponent(host, _controller, _extractor, routeKnown);
381
382
383
384
					host.registerComponent(vehicularHostComponent);
				}
				vehicularHostComponent.setVehicleID(vehicle);

Tobias Meuser's avatar
Tobias Meuser committed
385
386
387
				idComponentMatcher.put(vehicle, simLocationActuator);
				hostVehicleIDMatching.put(simLocationActuator.getHost().getId(), vehicle);
			} else {
388
				throw new RuntimeException("Unable to assign new components. Please increase node amount" + (_reuseComponents?".":" or enable the reuse of components."));
Tobias Meuser's avatar
Tobias Meuser committed
389
390
391
392
393
			}
		}
		return idComponentMatcher.get(vehicle);
	}

Tobias Meuser's avatar
Tobias Meuser committed
394
395
	public static RoadNetwork getRoadNetwork() {
		return MOVEMENT._extractor.getRoadNetwork();
396
	}
Tobias Meuser's avatar
Tobias Meuser committed
397
}