CsvMovement.java 9.6 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
26
27
28
29
30
31
32
33
/*
 * 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.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import de.tud.kom.p2psim.api.common.SimHost;
import de.tud.kom.p2psim.api.network.SimNetInterface;
34
import de.tud.kom.p2psim.api.topology.Topology;
35
import de.tud.kom.p2psim.api.topology.movement.MovementInformation;
36
import de.tud.kom.p2psim.api.topology.movement.SimLocationActuator;
37
38
import de.tud.kom.p2psim.impl.simengine.Simulator;
import de.tud.kom.p2psim.impl.topology.PositionVector;
39
40
import de.tud.kom.p2psim.impl.topology.movement.modularosm.ModularMovementModel;
import de.tud.kom.p2psim.impl.topology.movement.modularosm.transition.FixedAssignmentStrategy;
41
import de.tudarmstadt.maki.simonstrator.api.Binder;
42
import de.tudarmstadt.maki.simonstrator.api.Time;
43
import de.tudarmstadt.maki.simonstrator.api.component.sensor.location.AttractionPoint;
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import de.tudarmstadt.maki.simonstrator.api.util.XMLConfigurableConstructor;

/**
 * Movement of the {@link AttractionPoint}s in the {@link ModularMovementModel}.
 * {@link AttractionPoint}s follow path given via a .csv file.
 * 
 * @author Nils Richerzhagen
 * @version 1.0, 02.08.2014
 */
public class CsvMovement extends AbstractMovementModel {

	private FixedAssignmentStrategy transitionStrategy;

	private PositionVector worldDimensions;

	private final String SEP = ";";

	private final String INTERMEDIATE_SEP = ",";

	private String file;

	private LinkedList<LinkedList<CsvPathInfo>> readPathInfos;

67
	private Map<SimLocationActuator, LinkedList<CsvPathInfo>> componentsPathsInfos;
68

69
	private Map<SimLocationActuator, CsvMovementInfo> stateInfo;
70
71
72
73
74

	/**
	 * 
	 * @param movementPointsFile
	 */
Nils Richerzhagen's avatar
Nils Richerzhagen committed
75
76
	@XMLConfigurableConstructor({ "movementPointsFile" , "minMovementSpeed", "maxMovementSpeed" })
	public CsvMovement(String movementPointsFile, double minMovementSpeed, double maxMovementSpeed) {
77
		super();
78
79
		this.worldDimensions = Binder.getComponentOrNull(Topology.class)
				.getWorldDimensions();
80
81
		this.file = movementPointsFile;
		this.readPathInfos = new LinkedList<LinkedList<CsvPathInfo>>();
82
83
		this.stateInfo = new LinkedHashMap<SimLocationActuator, CsvMovementInfo>();
		this.componentsPathsInfos = new LinkedHashMap<SimLocationActuator, LinkedList<CsvPathInfo>>();
84

Nils Richerzhagen's avatar
Nils Richerzhagen committed
85
		readData(minMovementSpeed, maxMovementSpeed);
86
87
88
	}

	@Override
89
	public void addComponent(SimLocationActuator component) {
90
91
92
93
94
95
96
97
		super.addComponent(component);
		LinkedList<CsvPathInfo> first = readPathInfos.removeFirst();
		componentsPathsInfos.put(component, first);
		stateInfo.put(component, new CsvMovementInfo());
	}

	@Override
	public void move() {
98
99
		Set<SimLocationActuator> comps = getComponents();
		for (SimLocationActuator comp : comps) {
100
101
102
103
104
105
106
107
108
109

			PositionVector pos = comp.getRealPosition();
			CsvMovementInfo info = stateInfo.get(comp);

			if (info.getRemainingSteps() == 0 || info.getDelta() == null) {
				// assign next delta and next steps for next path point
				if (!assignNextMovementInfo(comp)) {
					return;
				}
			}
110
			updatePosition(comp, pos.plus(info.getDelta()));
111
112
113
114
			info.setRemainingSteps(info.getRemainingSteps() - 1);
		}
	}

115
	protected boolean assignNextMovementInfo(SimLocationActuator comp) {
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
		CsvMovementInfo info = stateInfo.get(comp);

		PositionVector actPos = comp.getRealPosition();
		PositionVector delta = null;
		int steps = 1;

		if (componentsPathsInfos.get(comp).isEmpty()) {
			return false;
		}

		// PositionVector targetPos =
		CsvPathInfo pathInfo = componentsPathsInfos.get(comp).removeFirst();
		PositionVector targetPos = pathInfo.getNextPostion();
		
		if(actPos.getX() == targetPos.getX() && actPos.getY() == targetPos.getY()){
			new Error("New position is exactly on the same place where old is. Do not do that!");
		}

		double distancePerMoveOperation = pathInfo.getSpeed()
				* getTimeBetweenMoveOperations() / Time.SECOND;
136
		double distance = actPos.distanceTo(targetPos);
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

		steps = (int) Math.round(distance / distancePerMoveOperation);

		double xDelta = (targetPos.getX() - actPos.getX()) / steps;
		double yDelta = (targetPos.getY() - actPos.getY()) / steps;

		String groupId = transitionStrategy
				.getGroupIdOfAttractionPoint((AttractionPoint) comp);

		if (!(groupId == null)) {

			// Go offline whenever intervals says to do so.
			if (!pathInfo.isOnline()) {
				List<SimHost> hosts = Simulator.getInstance().getScenario()
						.getHosts().get(groupId);

				for (SimHost simHost : hosts) {
					for (SimNetInterface net : simHost.getNetworkComponent()
							.getSimNetworkInterfaces()) {
						if (net.isOnline())
							net.goOffline();
					}
				}
			} else if (pathInfo.isOnline()) {
				List<SimHost> hosts = Simulator.getInstance().getScenario()
						.getHosts().get(groupId);

				for (SimHost simHost : hosts) {

					for (SimNetInterface net : simHost.getNetworkComponent()
							.getSimNetworkInterfaces()) {
						if (net.isOffline())
							net.goOnline();
					}
				}
			}
		}

		delta = new PositionVector(xDelta, yDelta);

		info.setDelta(delta);
		info.setRemainingSteps(steps);
		return true;
	}

	/**
	 * Read the given csv file.
	 * 
	 * x, y, 'ONLINE'/'OFFLINE', min speed, max speed
	 * 
	 * if min speed == max speed = speed
	 */
Nils Richerzhagen's avatar
Nils Richerzhagen committed
189
	private void readData(double minMovementSpeed, double maxMovementSpeed) {
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
		readPathInfos.clear();
		boolean entrySuccessfullyRead = false;
		BufferedReader csv = null;
		try {
			csv = new BufferedReader(new FileReader(file));

			while (csv.ready()) {
				String line = csv.readLine();

				LinkedList<CsvPathInfo> currentPathInfos = new LinkedList<CsvPathInfo>();

				if (line.indexOf(SEP) > -1) {
					String[] parts = line.split(SEP);
					for (String actPart : parts) {
						String[] subParts = actPart.split(INTERMEDIATE_SEP);

						if (subParts.length == 5) {
							try {
								Double x = Double.parseDouble(subParts[0]);
								Double y = Double.parseDouble(subParts[1]);
								String online = subParts[2];
Nils Richerzhagen's avatar
Nils Richerzhagen committed
211
212
213
214
215
216
217
218
219
220
221
222
223
224
								online = online.replaceAll("\\s+","");
								Double minSpeed;
								Double maxSpeed;
								if(online.equals("OFFLINE")){
									minSpeed = Double
											.parseDouble(subParts[3]);
									maxSpeed = Double
											.parseDouble(subParts[4]);
								}
								else{
									minSpeed = minMovementSpeed;
									maxSpeed = maxMovementSpeed;
								}
//								log.error("Min speed: " + minSpeed + " max speed " + maxSpeed );
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
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349

								if (x > worldDimensions.getX()
										|| y > worldDimensions.getY() || x < 0
										|| y < 0) {
									System.err.println("Skipped entry " + x
											+ ";" + y);
									continue;
								}

								CsvPathInfo actPathInfo = new CsvPathInfo(
										new PositionVector(x, y), online,
										minSpeed, maxSpeed);
								currentPathInfos.add(actPathInfo);
								entrySuccessfullyRead = true;

							} catch (NumberFormatException e) {
								// Ignore leading comments
								if (entrySuccessfullyRead) {
									// System.err.println("CSV ParseError " +
									// line);
								}
							}
						} else {
							throw new AssertionError("To many columns in CSV.");
						}
					}
				}
				// Put MovementInfos of one line into the full vector.
				readPathInfos.add(currentPathInfos);
			}
		} catch (Exception e) {
			System.err.println(e.toString());
		} finally {
			if (csv != null) {
				try {
					csv.close();
				} catch (IOException e) {
					//
				}
			}
		}
	}

	/**
	 * 
	 * @param transStrategy
	 */
	public void addTransitionStrategy(FixedAssignmentStrategy transStrategy) {
		this.transitionStrategy = transStrategy;
	}

	/**
	 * 
	 * @author Nils Richerzhagen
	 * @version 1.0, 16.07.2014
	 */
	public class CsvMovementInfo implements MovementInformation {

		private PositionVector delta;

		private int remainingSteps = 0;

		public void setDelta(PositionVector delta) {
			this.delta = delta;
		}

		public void setRemainingSteps(int remainingSteps) {
			this.remainingSteps = remainingSteps;
		}

		public PositionVector getDelta() {
			return delta;
		}

		public int getRemainingSteps() {
			return remainingSteps;
		}
	}

	/**
	 * 
	 * @author Nils Richerzhagen
	 * @version 1.0, 02.08.2014
	 */
	public class CsvPathInfo {
		private PositionVector nextPostion;

		private boolean online;

		private double minSpeed;

		private double maxSpeed;

		public CsvPathInfo(PositionVector nextPosition, String online,
				double minSpeed, double maxSpeed) {
			this.nextPostion = nextPosition;
			this.minSpeed = minSpeed;
			this.maxSpeed = maxSpeed;

			if (online.equals("ONLINE"))
				this.online = true;
			else if (online.equals("OFFLINE"))
				this.online = false;
			else
				throw new Error(online + " no valid String in CsvMovement");
		}

		public PositionVector getNextPostion() {
			return nextPostion;
		}

		public double getSpeed() {
			if (minSpeed == maxSpeed)
				return minSpeed;

			return getRandomDouble(minSpeed, maxSpeed);
		}

		public boolean isOnline() {
			return online;
		}

	}

}