TraciSimulationController.java 16.7 KB
Newer Older
1
2
3
4
5
package de.tud.kom.p2psim.impl.topology.movement.vehicular.sumo.simulation.controller.traci;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
6
import java.util.LinkedList;
7
8
9
10
11
12
13
import java.util.List;
import java.util.Map;

import de.tud.kom.p2psim.impl.topology.movement.vehicular.information.LocationUtils;
import de.tud.kom.p2psim.impl.topology.movement.vehicular.information.Position;
import de.tud.kom.p2psim.impl.topology.movement.vehicular.sumo.simulation.controller.SimulationSetupExtractor;
import de.tud.kom.p2psim.impl.topology.movement.vehicular.sumo.simulation.controller.VehicleController;
14
15
16
17
18
19
20
import de.tudarmstadt.maki.simonstrator.api.component.vehicular.roadnetwork.RoadNetwork;
import de.tudarmstadt.maki.simonstrator.api.component.vehicular.roadnetwork.RoadNetworkEdge;
import de.tudarmstadt.maki.simonstrator.api.component.vehicular.roadnetwork.RoadNetworkRoute;
import de.tudarmstadt.maki.simonstrator.api.component.vehicular.roadnetwork.exception.NoAdditionalRouteAvailableException;
import de.tudarmstadt.maki.simonstrator.api.component.vehicular.roadnetwork.exception.NoExitAvailableException;
import de.tudarmstadt.maki.simonstrator.api.component.vehicular.roadnetwork.routing.BreathFirstSearchRoutingAlgorithm;
import de.tudarmstadt.maki.simonstrator.api.component.vehicular.roadnetwork.routing.RoutingAlgorithm;
21
import de.tudresden.sumo.cmd.Junction;
22
import de.tudresden.sumo.cmd.Lane;
23
24
25
import de.tudresden.sumo.cmd.Simulation;
import de.tudresden.sumo.cmd.Vehicle;
import de.tudresden.sumo.util.SumoCommand;
26
import de.tudresden.ws.container.SumoBoundingBox;
27
import de.tudresden.ws.container.SumoGeometry;
28
29
import de.tudresden.ws.container.SumoLink;
import de.tudresden.ws.container.SumoLinkList;
30
31
32
33
34
35
import de.tudresden.ws.container.SumoPosition2D;
import de.tudresden.ws.container.SumoStringList;
import it.polito.appeal.traci.SumoTraciConnection;

public class TraciSimulationController implements VehicleController, SimulationSetupExtractor {

36
	private static final Map<String, TraciSimulationController> CONTROLLER = new HashMap<>();
37

38
	private static final double CLUSTERING_DISTANCE = 50;
39

40
41
	private String _sumoExe;
	private String _configFile;
42

43
	private SumoTraciConnection _connection;
44

45
46
	private double _start = -1;
	private double _step = -1;
47

48
49
50
51
	private double _startX;
	private double _startY;
	private double _endX;
	private double _endY;
52

53
	private Map<Double, Map<String, Position>> _positonsByTimestamp = new HashMap<>();
54
	private int _futureInformation = 0;
55

56
	private boolean _initalized = false;
57

58
	private boolean _observedAreaSet;
59

60
	private Map<String, Double> _vehiclesOutOfRange = new HashMap<>();
61

62
63
64
65
	private RoadNetwork _roadNetwork;

	private RoutingAlgorithm _algorithm = new BreathFirstSearchRoutingAlgorithm();

66
67
68
69
70
71
	public static synchronized TraciSimulationController createSimulationController(String pSumoExe, String pConfigFile) {
		if (!CONTROLLER.containsKey(pConfigFile)) {
			CONTROLLER.put(pConfigFile, new TraciSimulationController(pSumoExe, pConfigFile));
		}
		return CONTROLLER.get(pConfigFile);
	}
72

73
74
75
76
	private TraciSimulationController(String pSumoExe, String pConfigFile) {
		_sumoExe = pSumoExe;
		_configFile = pConfigFile;
	}
77

78
79
80
	public static VehicleController getSimulationController() {
		return CONTROLLER.values().iterator().next();
	}
81

82
83
84
85
	@Override
	public synchronized void init() {
		if (!_initalized) {
			_connection = new SumoTraciConnection(_sumoExe, _configFile);
86

87
88
			try {
				_connection.runServer();
89

90
91
92
93
94
95
96
97
				for (int i = 0; i < _futureInformation; i++) {
					nextStep();
				}
			} catch (RuntimeException e) {
				throw e;
			} catch (Exception e) {
				e.printStackTrace();
			}
98

99
			Runnable shutdownHook = new Runnable() {
100

101
102
103
104
105
				@Override
				public void run() {
					_connection.close();
				}
			};
106

107
			Runtime.getRuntime().addShutdownHook(new Thread(shutdownHook));
108

109
110
111
			_initalized = true;
		}
	}
112

113
114
115
116
	@Override
	public Position getVehiclePosition(String pVehicleID) {
		return getVehiclePosition(_step, pVehicleID);
	}
117

118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
	@Override
	public Position getVehiclePosition(double pStep, String pVehicleID) {
		Map<String, Position> map = _positonsByTimestamp.get(pStep);

		return map.get(pVehicleID);
	}

	@Override
	public List<Position> getAllIntersections(boolean pCluster) {
		List<Position> result = new ArrayList<>();

		SumoCommand intersectionCommand = Junction.getIDList();

		Object intersectionObject = requestObject(intersectionCommand);

		SumoStringList intersections = (SumoStringList) intersectionObject;

		for (String intersection : intersections) {
			SumoCommand positionCommand = Junction.getPosition(intersection);
			Object positionObject = requestObject(positionCommand);
			SumoPosition2D sumoPosition = (SumoPosition2D) positionObject;

			if (_observedAreaSet) {
				if (_startX <= sumoPosition.x && sumoPosition.x <= _endX && _startY <= sumoPosition.y && sumoPosition.y <= _endY) {
					result.add(new Position(sumoPosition.x - _startX, sumoPosition.y - _startY, 0, 0));
				}
			} else {
				result.add(new Position(sumoPosition.x, sumoPosition.y, 0, 0));
			}
		}

		if (pCluster) {
			List<Position> tempResult = new ArrayList<>();

			outer:for (int i = 0; i < result.size(); i++) {
				Position position = result.get(i);

				for (int j = 0; j < tempResult.size(); j++) {
					Position addedPosition = tempResult.get(j);
					if (position != addedPosition && LocationUtils.calculateDistance(position, addedPosition) < CLUSTERING_DISTANCE / 1000.0) {
						continue outer;
					}
				}

				tempResult.add(position);
			}

			result = tempResult;
		}

		return result;
	}

	@Override
	public boolean nextStep() {
		try {
			_connection.do_timestep();

			try {
				int temp = (Integer) _connection.do_job_get(Simulation.getCurrentTime());

				_step = temp / 1000.0 - _futureInformation;

				if (_start == -1) {
					_start = _step + _futureInformation;
				}

				double newStep = _step + _futureInformation;
				if (!_positonsByTimestamp.containsKey(newStep)) {
					Map<String, Position> vehiclePositions = new HashMap<>();
					_positonsByTimestamp.put(newStep, vehiclePositions);

					List<String> allVehicles = requestAllVehicles();
					for (String vehicle : allVehicles) {
						Position vehiclePosition = requestVehiclePosition(vehicle);
						if (vehiclePosition != null) {
							vehiclePositions.put(vehicle, vehiclePosition);
						}
					}
				}

				if (_positonsByTimestamp.containsKey(_step - 1)) {
					_positonsByTimestamp.remove(_step - 1);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}

			return true;
		} catch (RuntimeException e) {
			throw e;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	private Position requestVehiclePosition(String pVehicleID) {
		if (_vehiclesOutOfRange.containsKey(pVehicleID)) {
			if (_vehiclesOutOfRange.get(pVehicleID) < _step) {
				return null;
			} else {
				_vehiclesOutOfRange.remove(pVehicleID);
			}
		}

		SumoCommand positionCommand = Vehicle.getPosition(pVehicleID);
		SumoCommand angleCommand = Vehicle.getAngle(pVehicleID);
		SumoCommand speedCommand = Vehicle.getSpeed(pVehicleID);

		Object positionObject = requestObject(positionCommand);
		Object angleObject = requestObject(angleCommand);
		Object speedObject = requestObject(speedCommand);

		SumoPosition2D sumoPosition = (SumoPosition2D) positionObject;
		double angle = (Double) angleObject;
		double speed = (Double) speedObject;

		if (_observedAreaSet) {
			if (_startX <= sumoPosition.x && sumoPosition.x <= _endX && _startY <= sumoPosition.y && sumoPosition.y <= _endY) {
				return new Position(sumoPosition.x - _startX, sumoPosition.y - _startY, 0, angle, speed);
			} else {
				double diffX = _startX - sumoPosition.x;
				if (diffX < 0 || sumoPosition.x - _endX < diffX) {
					diffX = sumoPosition.x - _endX;
				}
				if (diffX < 0) {
					diffX = 0;
				}
				double diffY = _startY - sumoPosition.y;
				if (diffY < 0 || sumoPosition.y - _endY < diffY) {
					diffY = sumoPosition.y - _endY;
				}
				if (diffY < 0) {
					diffY = 0;
				}
				double diff = Math.sqrt(Math.pow(diffX, 2) + Math.pow(diffY, 2));

				double timeTillNextJoin = diff / 50;

				//                _vehiclesOutOfRange.put(pVehicleID, _step + timeTillNextJoin);

				return null;
			}
		} else {
			return new Position(sumoPosition.x, sumoPosition.y, 0, angle);
		}
	}

	private List<String> requestAllVehicles() {
		SumoCommand idList = Vehicle.getIDList();
		Object object = requestObject(idList);
		SumoStringList list = (SumoStringList)object;

		List<String> result = new ArrayList<>();

		for (String vehicle : list) {
			result.add(vehicle);
		}

		return result;
	}

	@Override
	public List<String> getAllVehicles() {
		return getAllVehicles(_step);
	}

	@Override
	public List<String> getAllVehicles(double pStep) {
		Map<String, Position> map = _positonsByTimestamp.get(pStep);

		return new ArrayList<>(map.keySet());
	}

293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
	public RoadNetworkEdge getCurrentEdge(String pVehicleID) {
		obtainRoadNetwork();

		SumoCommand roadIDCommand = Vehicle.getRoadID(pVehicleID);
		String currentRoadID = (String) requestObject(roadIDCommand);

		RoadNetworkEdge edge = _roadNetwork.getEdge(currentRoadID);
		while (edge.isInternal()) {
			if (edge.getAccessibleEdges().size() == 1) {
				edge = edge.getAccessibleEdges().get(0);
			} else {
				break;
			}
		}

		return edge;
	}

311
312
	@Override
	public RoadNetworkRoute getCurrentRoute(String pVehicleID) {
313
314
		obtainRoadNetwork();

315
316
317
318
		SumoCommand routeCommand = Vehicle.getRoute(pVehicleID);
		Object object = requestObject(routeCommand);
		SumoStringList streetList = (SumoStringList) object;

319
		RoadNetworkEdge currentEdge = getCurrentEdge(pVehicleID);
320

321
322
323
		if (currentEdge == null) {
			return null;
		}
324
325

		List<RoadNetworkEdge> streets = new ArrayList<>();
326
		boolean add = false;
327
		for (String street : streetList) {
328
			if (street.equals(currentEdge.getEdgeID())) {
329
330
331
332
333
334
335
336
337
				add = true;
			}
			if (add) {
				streets.add(_roadNetwork.getEdge(street));
			}
		}


		if (streets.size() == 0) {
338
			return new RoadNetworkRoute(new ArrayList<>());
339
340
		}

341
		return new RoadNetworkRoute(streets);
342
343
344
345
346
347
348
349
350
351
352
353
354
355
	}

	public Object requestObject(SumoCommand routeCommand) {
		Object object = null;
		try {
			object = _connection.do_job_get(routeCommand);
		} catch (RuntimeException e) {
			throw e;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return object;
	}

356
357
358
359
360
361
362
363
364
365
	public void execute(SumoCommand routeCommand) {
		try {
			_connection.do_job_set(routeCommand);
		} catch (RuntimeException e) {
			throw e;
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
	@Override
	public double getStep() {
		return _step;
	}

	@Override
	public double getStart() {
		return _start;
	}

	@Override
	public double getMaximumAvailablePrediction() {
		double max = Collections.max(_positonsByTimestamp.keySet());

		return max;
	}

	@Override
	public void setObservedArea(double pStartX, double pStartY, double pEndX, double pEndY) {
		_startX = pStartX;
		_startY = pStartY;
		_endX = pEndX;
		_endY = pEndY;

		_observedAreaSet = true;
	}

	@Override
	public double getScenarioWidth() {
		SumoCommand netBoundaryCommand = Simulation.getNetBoundary();

		try {
			SumoBoundingBox netBoundary = (SumoBoundingBox) _connection.do_job_get(netBoundaryCommand);
399
			return Math.max(netBoundary.x_max - netBoundary.x_min, 10);
400
401
402
403
404
405
406
407
408
409
410
411
		} catch (Exception e) {
			//Nothing to do
		}
		return -1;
	}

	@Override
	public double getScenarioHeight() {
		SumoCommand netBoundaryCommand = Simulation.getNetBoundary();

		try {
			SumoBoundingBox netBoundary = (SumoBoundingBox) _connection.do_job_get(netBoundaryCommand);
412
			return Math.max(netBoundary.y_max - netBoundary.y_min, 10);
413
414
415
416
417
		} catch (Exception e) {
			//Nothing to do
		}
		return -1;
	}
418

419
420
421
422
423
	public boolean providesRoadInformation() {
		return true;
	}

	public RoadNetworkEdge getVehicleDestination(String pVehicleID) {
424
		RoadNetworkRoute roadNetworkRoute = getCurrentRoute(pVehicleID);
425
426
427
428

		return roadNetworkRoute.getDestination();
	}

429
	@Override
430
431
432
433
434
435
	public RoadNetwork getRoadNetwork() {
		obtainRoadNetwork();

		return _roadNetwork;
	}

436
	@Override
437
438
	public RoadNetworkRoute findNewRoute(String pVehicle) throws NoAdditionalRouteAvailableException {
		List<RoadNetworkRoute> routes = new ArrayList<>();
439
		RoadNetworkRoute route = getCurrentRoute(pVehicle);
440
441
442
443
444

		if (route.getRoute().isEmpty()) {
			return null;
		}

445
446
447
448
449
450
451
452
		routes.add(route);
		RoadNetworkRoute findRoute = _algorithm.findRoute(_roadNetwork, route.getStart(), route.getDestination(), routes);
		if (findRoute == null) {
			throw new NoAdditionalRouteAvailableException(route.getStart(), route.getDestination(), routes);
		}
		return findRoute;
	}

453
	@Override
454
455
456
	public RoadNetworkRoute findNewRoute(String pVehicle, List<RoadNetworkEdge> pEdgesToAvoid, boolean pKeepDestination) throws NoAdditionalRouteAvailableException, NoExitAvailableException {
		if (pKeepDestination) {
			List<RoadNetworkRoute> routes = new ArrayList<>();
457
			RoadNetworkRoute route = getCurrentRoute(pVehicle);
458
459
460
461
462

			if (route.getRoute().isEmpty()) {
				return null;
			}

463
464
465
466
467
468
469
470
			routes.add(route);

			RoadNetworkRoute findRoute = _algorithm.findRoute(_roadNetwork, route.getStart(), route.getDestination(), routes, pEdgesToAvoid);
			if (findRoute == null) {
				throw new NoAdditionalRouteAvailableException(route.getStart(), route.getDestination(), routes);
			}
			return findRoute;
		} else {
471
			RoadNetworkRoute route = getCurrentRoute(pVehicle);
472
473
474
475
476

			if (route.getRoute().isEmpty()) {
				return null;
			}

477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
			List<RoadNetworkEdge> routeList = route.getRoute();

			RoadNetworkEdge lastEdge = null;
			boolean search = false;
			outer:for (int i = routeList.size() - 1; i >= 0; i--) {
				if (search) {
					List<RoadNetworkEdge> accessibleEdges = routeList.get(i).getAccessibleEdges();
					if (accessibleEdges.size() > 1) {
						for (int j = 0; j < accessibleEdges.size(); j++) {
							if (!accessibleEdges.get(j).equals(lastEdge)) {
								List<RoadNetworkEdge> edges = new ArrayList<>();

								for (int k = 0; k <= i; k++) {
									edges.add(routeList.get(k));
								}
								edges.add(accessibleEdges.get(j));

								for (RoadNetworkEdge roadNetworkEdge : edges) {
									if (pEdgesToAvoid.contains(roadNetworkEdge)) {
										continue outer;
									}
								}

								return new RoadNetworkRoute(edges);
							}
						}
					}
				}
				search = true;
				lastEdge = routeList.get(i);
			}
			throw new NoExitAvailableException(route.getStart(), route.getDestination());
		}
	}

512
	@Override
513
514
515
516
517
518
519
520
	public void rerouteVehicle(String pVehicle, RoadNetworkRoute pRoute) {
		SumoStringList routeEdges = new SumoStringList();
		for (RoadNetworkEdge edge : pRoute.getRoute()) {
			routeEdges.add(edge.getEdgeID());
		}
		execute(Vehicle.setRoute(pVehicle, routeEdges));
	}

521
522
523
524
525
526
	@Override
	public void stopVehicle(String pVehicle) {
		SumoCommand stopCommand = Vehicle.setSpeed(pVehicle, 0);
		execute(stopCommand);
	}

527
528
529
530
531
532
533
	public void obtainRoadNetwork() {
		if (_roadNetwork == null) {
			SumoCommand laneIDCommand = Lane.getIDList();

			Map<String, RoadNetworkEdge> roadNetwork = new HashMap<>();

			SumoStringList laneIDStringList = (SumoStringList) requestObject(laneIDCommand);
534
535

			//Requesting all lanes from sumo.
536
537
538
539
540
			for (String laneID : laneIDStringList) {
				SumoCommand edgeIDCommand = Lane.getEdgeID(laneID);

				SumoLinkList linkStringList = (SumoLinkList) requestObject(Lane.getLinks(laneID));

541
542
543
544
				double angle = getLaneAngle(laneID);

				double maxSpeed = getMaxSpeed(laneID);

545
546
547
548
				if (linkStringList.size() > 0) {
					String edgeID = (String) requestObject(edgeIDCommand);

					if (!roadNetwork.containsKey(edgeID)) {
549
						roadNetwork.put(edgeID, new RoadNetworkEdge(edgeID, angle));
550
551
552
553
					}

					RoadNetworkEdge edge = roadNetwork.get(edgeID);

554
555
556
					edge.setMaxSpeed(maxSpeed);
					edge.increaseLaneAmount();

557
558
559
560
					for (SumoLink link : linkStringList) {
						String notInternalLane = link.notInternalLane;
						String connectedEdge = (String) requestObject(Lane.getEdgeID(notInternalLane));

561
562
						double linkAngle = getLaneAngle(laneID);

563
						if (!roadNetwork.containsKey(connectedEdge)) {
564
							roadNetwork.put(connectedEdge, new RoadNetworkEdge(connectedEdge, linkAngle));
565
566
567
568
569
570
571
572
573
574
575
576
						}

						edge.addConnectedEdge(roadNetwork.get(connectedEdge));
					}
				}


			}
			_roadNetwork = new RoadNetwork(roadNetwork);
		}
	}

577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
	public double getMaxSpeed(String laneID) {
		SumoCommand maxSpeedCommand = Lane.getMaxSpeed(laneID);
		double maxSpeed = (Double) requestObject(maxSpeedCommand);
		return maxSpeed;
	}

	public double getLaneAngle(String laneID) {
		SumoCommand shapeCommand = Lane.getShape(laneID);
		SumoGeometry geometry = (SumoGeometry) requestObject(shapeCommand);

		LinkedList<SumoPosition2D> coords = geometry.coords;
		SumoPosition2D start = coords.getFirst();
		SumoPosition2D end = coords.getLast();

		double sin = (end.y - start.y) / Math.sqrt(Math.pow(end.x - start.x, 2) + Math.pow(end.y - start.y, 2));

		double angle = Math.asin(sin) * 180 / Math.PI;
		if (end.x - start.x < 0) {
			angle += 180;
		}
		return angle;
	}

600
}