RealWorldStreetsMovement.java 11.1 KB
Newer Older
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
/*
 * 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.local;

import com.graphhopper.GHRequest;
import com.graphhopper.GHResponse;
import com.graphhopper.GraphHopper;
26
import com.graphhopper.routing.util.EdgeFilter;
27
import com.graphhopper.routing.util.EncodingManager;
28
29
import com.graphhopper.storage.index.LocationIndex;
import com.graphhopper.storage.index.QueryResult;
Clemens Krug's avatar
Clemens Krug committed
30
import com.graphhopper.util.DistanceCalc2D;
31
import com.graphhopper.util.EdgeIteratorState;
32
import com.graphhopper.util.PointList;
33
import com.graphhopper.util.shapes.GHPoint;
34
import com.graphhopper.util.shapes.GHPoint3D;
35
import de.tud.kom.p2psim.api.topology.Topology;
36
import de.tud.kom.p2psim.api.topology.movement.SimLocationActuator;
37
import de.tud.kom.p2psim.impl.topology.PositionVector;
38
import de.tud.kom.p2psim.impl.topology.movement.modularosm.GPSCalculation;
39
import de.tud.kom.p2psim.impl.topology.views.VisualizationTopologyView;
40
41
import de.tud.kom.p2psim.impl.util.Either;
import de.tud.kom.p2psim.impl.util.Left;
42
import de.tudarmstadt.maki.simonstrator.api.Binder;
43
import de.tudarmstadt.maki.simonstrator.api.Monitor;
44
import de.tudarmstadt.maki.simonstrator.api.Monitor.Level;
45

Clemens Krug's avatar
Clemens Krug committed
46
import java.util.*;
Clemens Krug's avatar
Clemens Krug committed
47

48
49
/**
 * This movement strategy uses the data from osm and navigates the nodes throught streets to the destination
Clemens Krug's avatar
Clemens Krug committed
50
 *
51
 * 13.03.2017 Clemens Krug: Fixed a bug. When the GraphHopper routing had errors the nodes would move to the
Clemens Krug's avatar
Clemens Krug committed
52
 * top right corner and not, as intended, straight to their destination.
53
54
55
56
57
58
 * 
 * @author Martin Hellwig
 * @version 1.0, 07.07.2015
 */
public class RealWorldStreetsMovement extends AbstractLocalMovementStrategy {
	
59
	private static PositionVector worldDimensions;
60
	private GraphHopper hopper;
61
	private LocationIndex index;
62
63
	private boolean init = false;
	
64
	private static HashMap<SimLocationActuator, RealWorldMovementPoints> movementPoints = new HashMap<>();
65
	
66
67
68
	private String osmFileLocation; //use pbf-format, because osm-format causes problems (xml-problems)
	private String graphFolderFiles;
	private String movementType; //car, bike or foot
Clemens Krug's avatar
Clemens Krug committed
69
	private String defaultMovement;
70
	private String navigationalType; //fastest,
71
72
73
74
	private static double latLower; //Values from -90 to 90; always smaller than latUpper
	private static double latUpper; //Values from -90 to 90
	private static double lonLeft; //Values from -180 to 180; Always smaller than lonRight
	private static double lonRight; //Values from -180 to 180
75
	private boolean uniqueFolders;
76

77
78
79
80
81
82
	/**
	 * Tolerance in meters (if the node reached a waypoint up to "tolerance"
	 * meters, it will select the next waypoint in the path.
	 */
	private double tolerance = 1;

83
	public RealWorldStreetsMovement() {
84
		worldDimensions = Binder.getComponentOrNull(Topology.class)
85
				.getWorldDimensions();
86
87
		latLower = GPSCalculation.getLatLower();
		latUpper = GPSCalculation.getLatUpper();
88
89
		lonLeft = GPSCalculation.getLonLeft();
		lonRight = GPSCalculation.getLonRight();
90
91
92
93
94
	}
	
	private void init() {
		hopper = new GraphHopper().forServer();
		hopper.setOSMFile(osmFileLocation);
Clemens Krug's avatar
Clemens Krug committed
95

96
		// where to store graphhopper files?
97
98
99
100
101
102
103
104
105
106
		if (uniqueFolders) {
			Monitor.log(RealWorldStreetsMovement.class, Level.WARN,
					"Using per-simulation unique folders for GraphHopper temporary data in %s. Remember to delete them to prevent your disk from filling up.",
					graphFolderFiles);
			hopper.setGraphHopperLocation(graphFolderFiles + "/"
					+ UUID.randomUUID().toString());
		} else {
			hopper.setGraphHopperLocation(graphFolderFiles + "/"
					+ osmFileLocation.hashCode() + movementType);
		}
107
108
		hopper.setEncodingManager(new EncodingManager(movementType));
		hopper.importOrLoad();
109
		index = hopper.getLocationIndex();
Clemens Krug's avatar
Clemens Krug committed
110

111
112
113
		init = true;
	}

114
115
    public Either<PositionVector, Boolean> nextPosition(SimLocationActuator comp, PositionVector destination)
    {
Clemens Krug's avatar
Clemens Krug committed
116
        return nextPosition(comp, destination, defaultMovement);
117
118
    }

119
	public Either<PositionVector, Boolean> nextPosition(SimLocationActuator comp,
120
			PositionVector destination, String movementType) {
Clemens Krug's avatar
Clemens Krug committed
121
122
123
124

		if(movementType == null || movementType.equals("") || !this.movementType.contains(movementType))
			throw new AssertionError("Invalid movement type: " + movementType);

125
        if(!init) init();
126
		PositionVector newPosition = null;
Clemens Krug's avatar
Clemens Krug committed
127
128
        if (destination.distanceTo(comp.getRealPosition()) > getMovementSpeed(comp))
        {
129
			//if not set already for this node or new destination is different than last one
130
131
			RealWorldMovementPoints trajectory = movementPoints.get(comp);
			if(trajectory == null || destination.distanceTo(trajectory.getDestination()) > 1.0) {
132
133
134
135
136
137
138
				double[] startPosition = transformOwnWorldWindowToGPS(comp.getRealPosition().getX(), comp.getRealPosition().getY());
				double[] destinationPosition = transformOwnWorldWindowToGPS(destination.getX(), destination.getY());
				GHRequest req = new GHRequest(startPosition[0], startPosition[1], destinationPosition[0], destinationPosition[1]).
					    setWeighting(navigationalType).
					    setVehicle(movementType).
					    setLocale(Locale.GERMANY);
				GHResponse rsp = hopper.route(req);
139
140
				//If the requested point is not in the map data, simple return the destination as next point
				if(rsp.hasErrors()) {
141
					Monitor.log(this.getClass(), Monitor.Level.ERROR, "Routing request for Host %s with starting point (" +
Clemens Krug's avatar
Clemens Krug committed
142
143
							"%f,%f), destination (%f,%f) and type %s failed with error: %s.", comp.getHost().getId().valueAsString(),startPosition[0], startPosition[1],
							destinationPosition[0], destinationPosition[1], movementType, rsp.getErrors());
144
					
145
					PointList pointList = new PointList();
Clemens Krug's avatar
Clemens Krug committed
146
					pointList.add(new GHPoint(destinationPosition[0], destinationPosition[1]));
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
					trajectory = new RealWorldMovementPoints(comp.getRealPosition(), destination, pointList);
					movementPoints.put(comp, trajectory);
				} else {
					PointList pointList = rsp.getBest().getPoints();
					trajectory = new RealWorldMovementPoints(comp.getRealPosition(), destination, pointList);
					/*
					 * TODO obtain route IDs along the path.
					 */
//					for (GHPoint point : pointList) {
//						QueryResult qr = index.findClosest(point.getLat(), point.getLon(), EdgeFilter.ALL_EDGES);
//						EdgeIteratorState nearEdge = qr.getClosestEdge();
//						nearEdge.
//						int channelId = -1;
//						if (nearEdge != null) {
//							channelId = nearEdge.getEdge();
//						}
//						currentRoute.add(new PointIdTuple(point, channelId));
//					}
						
					movementPoints.put(comp, trajectory);
167
				}
168
			}
169
			newPosition = trajectory.updateCurrentLocation(comp, getMovementSpeed(comp), tolerance);
170
171
172
173
174
175
176
177
178
179
180
181
		}
		return new Left<PositionVector, Boolean>(newPosition);
	}
	
	/**
	 * Projects the world coordinates in the given gps window to the gps-coordinates
	 * @param x
	 * @param y
	 * @return The projected position in gps-coordinates (lat, long)
	 */
	private double[] transformOwnWorldWindowToGPS(double x, double y) {
		double[] gps_coordinates = new double[2];
182
		gps_coordinates[0] = latLower + (latUpper - latLower) * (worldDimensions.getY() - y)/worldDimensions.getY();
183
184
185
186
187
188
189
190
191
192
		gps_coordinates[1] = lonLeft + (lonRight - lonLeft) * x/worldDimensions.getX();
		return gps_coordinates;
	}
	
	/**
	 * Projects the gps coordinates in the given gps window to the world-coordinates given in world-dimensions
	 * @param lat
	 * @param lon
	 * @return The projected position in world-dimensions
	 */
193
	public static PositionVector transformGPSWindowToOwnWorld(double lat, double lon) {
194
		double x = worldDimensions.getX() * (lon - lonLeft)/(lonRight - lonLeft);
195
		double y = worldDimensions.getY() - worldDimensions.getY() * (lat - latLower)/(latUpper - latLower);
196
197
198
199
		x = Math.max(0, x);
		x = Math.min(worldDimensions.getX(), x);
		y = Math.max(0, y);
		y = Math.min(worldDimensions.getY(), y);
200
201
		return new PositionVector(x, y);
	}
Clemens Krug's avatar
Clemens Krug committed
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

	/**
	 * Returns a list of points representing the current route of the component. Points are
	 * in x / y values of the own world.
	 * @param ms the component
	 * @return list of movement points.
	 */
	public List<PositionVector> getMovementPoints(SimLocationActuator ms)
	{
		List<PositionVector> positions = new LinkedList<>();
		PointList pointList = movementPoints.get(ms).getPointList();

		pointList.forEach(p -> positions.add(new PositionVector(transformGPSWindowToOwnWorld(p.getLat(), p.getLon()))));

		return positions;
	}

	/**
	 * Calculates the length of a route in meters.
	 * @param start Starting position in own world coordinates (x / y)
	 * @param destination Destination on own world coordinates (x / y)
	 * @return the length of the route in meters.
	 */
	public double calculateRouteLength(PositionVector start, PositionVector destination)
	{
		PointList pointList;
			double[] startPosition = transformOwnWorldWindowToGPS(start.getX(), start.getY());
			double[] destinationPosition = transformOwnWorldWindowToGPS(destination.getX(), destination.getY());
			GHRequest req = new GHRequest(startPosition[0], startPosition[1], destinationPosition[0], destinationPosition[1]).
					setWeighting(navigationalType).
					setVehicle(movementType).
					setLocale(Locale.GERMANY);
			GHResponse rsp = hopper.route(req);

			//If the requested point is not in the map data, return -1
			if(rsp.hasErrors()) {
				return -1;
			}
			else {
				pointList = rsp.getBest().getPoints();
				return pointList.calcDistance(new DistanceCalc2D());
			}
	}

	/**
	 * Calculates the length of the current route of the SimLocationActuator.
	 * @param ms the component
	 * @return the length of the current route
	 */
	public double getCurrentRouteLength(SimLocationActuator ms)
	{
		return movementPoints.get(ms).getPointList().calcDistance(new DistanceCalc2D());
	}
255
256
257
258
259
260
261
262
263
264
265
	
	public void setOsmFileLocation(String osmFileLocation) {
		this.osmFileLocation = osmFileLocation;
	}

	public void setGraphFolderFiles(String graphFolderFiles) {
		this.graphFolderFiles = graphFolderFiles;
	}

	public void setMovementType(String movementType) {
		this.movementType = movementType;
Clemens Krug's avatar
Clemens Krug committed
266
		defaultMovement = movementType.split(",")[0];
267
268
269
270
271
	}

	public void setNavigationalType(String navigationalType) {
		this.navigationalType = navigationalType;
	}
272
	
273
274
	public void setWaypointTolerance(double tolerance) {
		this.tolerance = tolerance;
275
	}
276

277
278
279
280
281
	/**
	 * For large batch simulations, we need to prevent same-time access to
	 * garphhopper temp data. Therefore, this flag creates unique folders for
	 * each run (which, obviously, wastes a lot of space and comp-resources and
	 * should not be used in standalone, single-threaded demo mode...)
282
	 *
283
284
285
286
287
	 * @param uniqueFolders
	 */
	public void setCreateUniqueFolders(boolean uniqueFolders) {
		this.uniqueFolders = uniqueFolders;
	}
288
}