Commit 1e657922 authored by Tobias Meuser's avatar Tobias Meuser
Browse files

Merged tm/vehicular-services into master-integration

parents 2a24c1a4 2c04ab95
...@@ -25,6 +25,10 @@ import java.util.LinkedHashMap; ...@@ -25,6 +25,10 @@ import java.util.LinkedHashMap;
import java.util.LinkedList; import java.util.LinkedList;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Map.Entry;
import org.hibernate.Criteria;
import org.hibernate.criterion.Restrictions;
import de.tud.kom.p2psim.impl.simengine.Simulator; import de.tud.kom.p2psim.impl.simengine.Simulator;
import de.tud.kom.p2psim.impl.util.db.dao.DAO; import de.tud.kom.p2psim.impl.util.db.dao.DAO;
...@@ -85,6 +89,22 @@ public class ExperimentDAO extends DAO { ...@@ -85,6 +89,22 @@ public class ExperimentDAO extends DAO {
return experiment; return experiment;
} }
public static Experiment retrieveExperiment(long pSeed, Map<String, String> pVariables) {
begin();
Criteria criteria = getSession().createCriteria(Experiment.class);
criteria = criteria.add(Restrictions.eq("seed", pSeed));
for (Entry<String, String> entry : pVariables.entrySet()) {
criteria = criteria.add(Restrictions.like("workload", "%" + entry.getKey() + "=" + entry.getValue() + "%"));
}
List<Experiment> experiments = criteria.list();
commit();
if (experiments.size() > 0) {
return experiments.get(experiments.size() - 1);
}
return null;
}
/** Called by the {@link Time} when the simulation is shut down. */ /** Called by the {@link Time} when the simulation is shut down. */
public static void simulationFinished() { public static void simulationFinished() {
// If there is no experiment object, no measurements have been made, // If there is no experiment object, no measurements have been made,
......
...@@ -104,31 +104,47 @@ public class MeasurementDAO extends DAO { ...@@ -104,31 +104,47 @@ public class MeasurementDAO extends DAO {
hostMetric); hostMetric);
addToPersistQueue(measurement); addToPersistQueue(measurement);
} }
/**
* Store a single measurement for a host, tied to a specific location.
*
* @param metricDesc
* @param hostId
* @param time
* @param value
* @param locationX
* @param locationY
*/
public static void storeSpatialMeasurement(MetricDescription metricDesc,
long hostId, long time, double value, int locationX,
int locationY) {
if (inactive) {
return;
}
Metric metric = MetricDAO.lookupSpatialMetric(metricDesc); /**
HostMetric hostMetric = HostMetricDAO.lookupHostMetric(metric, hostId); * Store a single measurement for a host, tied to a specific location.
*
* @param metricDesc
* @param hostId
* @param time
* @param value
* @param locationX
* @param locationY
*/
public static void storeSpatialMeasurement(MetricDescription metricDesc,
long hostId, long time, double value, int locationX,
int locationY) {
if (inactive) {
return;
}
Metric metric = MetricDAO.lookupSpatialMetric(metricDesc);
HostMetric hostMetric = HostMetricDAO.lookupHostMetric(metric, hostId);
MeasurementSpatial measurement = new MeasurementSpatial(time, value,
hostMetric, locationX, locationY);
addToPersistQueue(measurement);
}
/**
* Store a global single measurement for a host, tied to a specific location.
*
* @param metricDesc
* @param hostId
* @param time
* @param value
* @param locationX
* @param locationY
*/
public static void storeGlobalSpatialMeasurement(MetricDescription metricDesc,
long time, double value, int locationX, int locationY) {
storeSpatialMeasurement(metricDesc, GLOBAL_HOST_ID, time, value, locationX, locationY);
}
MeasurementSpatial measurement = new MeasurementSpatial(time, value,
hostMetric, locationX, locationY);
addToPersistQueue(measurement);
}
/** /**
* Stores for a series of measurements the given values for a host. The * Stores for a series of measurements the given values for a host. The
...@@ -196,7 +212,7 @@ public class MeasurementDAO extends DAO { ...@@ -196,7 +212,7 @@ public class MeasurementDAO extends DAO {
groupMetric, observationDuration, describesWholeSimulation); groupMetric, observationDuration, describesWholeSimulation);
addToPersistQueue(measurement); addToPersistQueue(measurement);
} }
/** /**
* Stores a statistical description of a series of values for group of * Stores a statistical description of a series of values for group of
* hosts and a given spatial coordinate. * hosts and a given spatial coordinate.
...@@ -305,7 +321,7 @@ public class MeasurementDAO extends DAO { ...@@ -305,7 +321,7 @@ public class MeasurementDAO extends DAO {
/** /**
* Store a list-based measurement with a key (i.e., as a * Store a list-based measurement with a key (i.e., as a
* {@link MeasurementPairList}). * {@link MeasurementPairList}).
* *
* @param metricDesc * @param metricDesc
* @param hostId * @param hostId
* @param time * @param time
...@@ -328,7 +344,7 @@ public class MeasurementDAO extends DAO { ...@@ -328,7 +344,7 @@ public class MeasurementDAO extends DAO {
/** /**
* Shortcut for {@link MeasurementPairList} metrics based on a single list. * Shortcut for {@link MeasurementPairList} metrics based on a single list.
* *
* @param metric * @param metric
* @param hostId * @param hostId
* @param time * @param time
......
package de.tud.kom.p2psim.impl.util.db.dao.metric; package de.tud.kom.p2psim.impl.util.db.dao.metric;
import java.util.HashMap; import java.util.HashMap;
import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Map.Entry;
import org.hibernate.Criteria;
import org.hibernate.criterion.Restrictions;
import de.tud.kom.p2psim.impl.util.Tuple; import de.tud.kom.p2psim.impl.util.Tuple;
import de.tud.kom.p2psim.impl.util.db.dao.DAO; import de.tud.kom.p2psim.impl.util.db.dao.DAO;
import de.tud.kom.p2psim.impl.util.db.metric.Experiment;
import de.tud.kom.p2psim.impl.util.db.metric.Metric; import de.tud.kom.p2psim.impl.util.db.metric.Metric;
import de.tud.kom.p2psim.impl.util.db.metric.MetricDescription; import de.tud.kom.p2psim.impl.util.db.metric.MetricDescription;
...@@ -53,6 +59,21 @@ public class MetricDAO extends DAO { ...@@ -53,6 +59,21 @@ public class MetricDAO extends DAO {
} }
} }
public static List<Metric> getMetricsForExperiment(int pExperimentID) {
begin();
Criteria criteria = getSession().createCriteria(Experiment.class);
if (pExperimentID != -1) {
criteria = criteria.add(Restrictions.eq("experimentID", pExperimentID));
}
List<Metric> metrics = criteria.list();
commit();
return metrics;
}
public List<Metric> getMetrics() {
return getMetricsForExperiment(-1);
}
/** Retrieve a {@link Metric} object for the given MetricDescription /** Retrieve a {@link Metric} object for the given MetricDescription
* for single value metrics. * for single value metrics.
* *
...@@ -62,7 +83,7 @@ public class MetricDAO extends DAO { ...@@ -62,7 +83,7 @@ public class MetricDAO extends DAO {
public static Metric lookupSingleMetric(MetricDescription metricDesc) { public static Metric lookupSingleMetric(MetricDescription metricDesc) {
return lookupMetric(metricDesc, MetricType.SINGLE); return lookupMetric(metricDesc, MetricType.SINGLE);
} }
/** Retrieve a {@link Metric} object for the given MetricDescription /** Retrieve a {@link Metric} object for the given MetricDescription
* for spatial value metrics. * for spatial value metrics.
* *
...@@ -86,7 +107,7 @@ public class MetricDAO extends DAO { ...@@ -86,7 +107,7 @@ public class MetricDAO extends DAO {
/** /**
* Retrieve a {@link Metric} object for the given MetricDescription for pair * Retrieve a {@link Metric} object for the given MetricDescription for pair
* list metrics. * list metrics.
* *
* If there is no matching Metric object, it is created, persisted, and * If there is no matching Metric object, it is created, persisted, and
* cached automatically. * cached automatically.
*/ */
......
...@@ -152,6 +152,14 @@ public class Metric { ...@@ -152,6 +152,14 @@ public class Metric {
return true; return true;
} }
public String getName() {
return name;
}
public String getComment() {
return comment;
}
@Override @Override
public String toString() { public String toString() {
return "Metric{" + return "Metric{" +
......
...@@ -2,17 +2,17 @@ ...@@ -2,17 +2,17 @@
* Copyright (c) 2005-2011 KOM - Multimedia Communications Lab * Copyright (c) 2005-2011 KOM - Multimedia Communications Lab
* *
* This file is part of PeerfactSim.KOM. * This file is part of PeerfactSim.KOM.
* *
* PeerfactSim.KOM is free software: you can redistribute it and/or modify * 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 * it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or * the Free Software Foundation, either version 3 of the License, or
* any later version. * any later version.
* *
* PeerfactSim.KOM is distributed in the hope that it will be useful, * PeerfactSim.KOM is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details. * GNU General Public License for more details.
* *
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with PeerfactSim.KOM. If not, see <http://www.gnu.org/licenses/>. * along with PeerfactSim.KOM. If not, see <http://www.gnu.org/licenses/>.
* *
...@@ -32,9 +32,9 @@ import de.tud.kom.p2psim.impl.util.guirunner.GUIRunner; ...@@ -32,9 +32,9 @@ import de.tud.kom.p2psim.impl.util.guirunner.GUIRunner;
import de.tud.kom.p2psim.impl.util.guirunner.seed.SeedDetermination; import de.tud.kom.p2psim.impl.util.guirunner.seed.SeedDetermination;
/** /**
* *
* Runs the simulator or invokes operations on the view. * Runs the simulator or invokes operations on the view.
* *
* @author Leo Nobach * @author Leo Nobach
* @version 3.0, 25.11.2008 * @version 3.0, 25.11.2008
* *
...@@ -45,11 +45,11 @@ public class RunnerController implements ActionListener { ...@@ -45,11 +45,11 @@ public class RunnerController implements ActionListener {
ConfigFile selectedFile = null; ConfigFile selectedFile = null;
JButton launchButton = null; JButton launchButton = null;
private GUIRunner runner; private GUIRunner runner;
private List<IRunnerCtrlListener> listeners = new LinkedList<IRunnerCtrlListener>(); private List<IRunnerCtrlListener> listeners = new LinkedList<IRunnerCtrlListener>();
SeedDetermination det = new SeedDetermination(); SeedDetermination det = new SeedDetermination();
/** /**
* Runs the simulator with the specified config file string. * Runs the simulator with the specified config file string.
* @param configFile * @param configFile
...@@ -57,9 +57,9 @@ public class RunnerController implements ActionListener { ...@@ -57,9 +57,9 @@ public class RunnerController implements ActionListener {
private void runSimulator() { private void runSimulator() {
SimulationThread simulationThread = new SimulationThread(selectedFile, det.getChosenSeed()); SimulationThread simulationThread = new SimulationThread(selectedFile, det.getChosenSeed());
simulationThread.start(); simulationThread.start();
Thread thread = new Thread(new Runnable() { Thread thread = new Thread(new Runnable() {
@Override @Override
public void run() { public void run() {
while (true) { while (true) {
...@@ -78,30 +78,30 @@ public class RunnerController implements ActionListener { ...@@ -78,30 +78,30 @@ public class RunnerController implements ActionListener {
}); });
// thread.start(); // thread.start();
} }
public void setLastOpened(LastOpened lastOpened) { public void setLastOpened(LastOpened lastOpened) {
this.lastOpened = lastOpened; this.lastOpened = lastOpened;
} }
public SeedDetermination getDetermination() { public SeedDetermination getDetermination() {
return det; return det;
} }
/** /**
* Called when the user wants to start the simulation. * Called when the user wants to start the simulation.
*/ */
public void invokeRunSimulator() { public void invokeRunSimulator() {
if (selectedFile == null) return; //No file is selected! if (selectedFile == null) return; //No file is selected!
if (lastOpened != null) lastOpened.append(selectedFile); if (lastOpened != null) lastOpened.append(selectedFile);
lastOpened.saveToFile(); lastOpened.saveToFile();
System.out.println("GUIRunner: Starting simulator with " + selectedFile.getFile().getAbsolutePath()); System.out.println("GUIRunner: Starting simulator with " + selectedFile.getFile().getAbsolutePath());
runner.disposeRunner(); runner.disposeRunner();
det.saveSettings(); det.saveSettings();
runSimulator(); runSimulator();
} }
...@@ -111,11 +111,11 @@ public class RunnerController implements ActionListener { ...@@ -111,11 +111,11 @@ public class RunnerController implements ActionListener {
*/ */
public void selectFile(final ConfigFile file) { public void selectFile(final ConfigFile file) {
selectedFile = file; selectedFile = file;
if (selectedFile == null) { if (selectedFile == null) {
return; return;
} }
selectedFile.loadConfiguration(new ConfigLoadedCallback() { selectedFile.loadConfiguration(new ConfigLoadedCallback() {
@Override @Override
public void loadingFinished() { public void loadingFinished() {
...@@ -123,11 +123,11 @@ public class RunnerController implements ActionListener { ...@@ -123,11 +123,11 @@ public class RunnerController implements ActionListener {
launchButton.setEnabled(selectedFile != null); launchButton.setEnabled(selectedFile != null);
} }
if (file != null) det.loadFile(selectedFile); if (file != null) det.loadFile(selectedFile);
newFileSelected(file); newFileSelected(file);
} }
}); });
} }
/** /**
* Sets the launch button that invokes the launch of the * Sets the launch button that invokes the launch of the
* simulation * simulation
...@@ -144,15 +144,15 @@ public class RunnerController implements ActionListener { ...@@ -144,15 +144,15 @@ public class RunnerController implements ActionListener {
invokeRunSimulator(); invokeRunSimulator();
} }
} }
public void addListener(IRunnerCtrlListener l) { public void addListener(IRunnerCtrlListener l) {
listeners.add(l); listeners.add(l);
} }
public void removeListener(IRunnerCtrlListener l) { public void removeListener(IRunnerCtrlListener l) {
listeners.remove(l); listeners.remove(l);
} }
void newFileSelected(ConfigFile f) { void newFileSelected(ConfigFile f) {
for (IRunnerCtrlListener l : listeners) l.newFileSelected(f); for (IRunnerCtrlListener l : listeners) l.newFileSelected(f);
} }
...@@ -164,16 +164,16 @@ public class RunnerController implements ActionListener { ...@@ -164,16 +164,16 @@ public class RunnerController implements ActionListener {
public void setMainWindow(GUIRunner runner) { public void setMainWindow(GUIRunner runner) {
this.runner=runner; this.runner=runner;
} }
public static interface IRunnerCtrlListener { public static interface IRunnerCtrlListener {
public void newFileSelected(ConfigFile f); public void newFileSelected(ConfigFile f);
} }
public ConfigFile getSelectedFile() { public ConfigFile getSelectedFile() {
return selectedFile; return selectedFile;
} }
} }
...@@ -2,17 +2,17 @@ ...@@ -2,17 +2,17 @@
* Copyright (c) 2005-2011 KOM - Multimedia Communications Lab * Copyright (c) 2005-2011 KOM - Multimedia Communications Lab
* *
* This file is part of PeerfactSim.KOM. * This file is part of PeerfactSim.KOM.
* *
* PeerfactSim.KOM is free software: you can redistribute it and/or modify * 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 * it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or * the Free Software Foundation, either version 3 of the License, or
* any later version. * any later version.
* *
* PeerfactSim.KOM is distributed in the hope that it will be useful, * PeerfactSim.KOM is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details. * GNU General Public License for more details.
* *
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with PeerfactSim.KOM. If not, see <http://www.gnu.org/licenses/>. * along with PeerfactSim.KOM. If not, see <http://www.gnu.org/licenses/>.
* *
...@@ -47,12 +47,12 @@ import de.tudarmstadt.maki.simonstrator.api.component.topology.TopologyProvider; ...@@ -47,12 +47,12 @@ import de.tudarmstadt.maki.simonstrator.api.component.topology.TopologyProvider;
/** /**
* This class gives access to the hosts of the scenario. To work, it has to be * This class gives access to the hosts of the scenario. To work, it has to be
* referenced in the configuration file after the host builder. * referenced in the configuration file after the host builder.
* *
* The purpose of this class is to enable a global knowledge for analyzing. It * The purpose of this class is to enable a global knowledge for analyzing. It
* is not meant to be used within any functional parts of simulated systems. * is not meant to be used within any functional parts of simulated systems.
* *
* @author Julius Rueckert * @author Julius Rueckert
* *
*/ */
public class GlobalOracle implements OracleComponent { public class GlobalOracle implements OracleComponent {
...@@ -90,7 +90,7 @@ public class GlobalOracle implements OracleComponent { ...@@ -90,7 +90,7 @@ public class GlobalOracle implements OracleComponent {
/** /**
* Initial population with hosts. * Initial population with hosts.
* *
* @param hostBuilder * @param hostBuilder
*/ */
public static void populate(List<SimHost> allHosts) { public static void populate(List<SimHost> allHosts) {
...@@ -120,7 +120,7 @@ public class GlobalOracle implements OracleComponent { ...@@ -120,7 +120,7 @@ public class GlobalOracle implements OracleComponent {
/** /**
* Sets the bootstrap hosts. To be called by netLayer. * Sets the bootstrap hosts. To be called by netLayer.
* *
* @param bootstrapList * @param bootstrapList
* the new bootstrap hosts * the new bootstrap hosts
*/ */
...@@ -130,7 +130,7 @@ public class GlobalOracle implements OracleComponent { ...@@ -130,7 +130,7 @@ public class GlobalOracle implements OracleComponent {
/** /**
* Gets the bootstrap hosts. * Gets the bootstrap hosts.
* *
* @return the bootstrap hosts * @return the bootstrap hosts
*/ */
public static List<NetID> getBootstrapHosts() { public static List<NetID> getBootstrapHosts() {
...@@ -139,7 +139,7 @@ public class GlobalOracle implements OracleComponent { ...@@ -139,7 +139,7 @@ public class GlobalOracle implements OracleComponent {
/** /**
* Gets the random host. * Gets the random host.
* *
* @return the random host * @return the random host
*/ */
public static NetID getRandomHost() { public static NetID getRandomHost() {
...@@ -149,7 +149,7 @@ public class GlobalOracle implements OracleComponent { ...@@ -149,7 +149,7 @@ public class GlobalOracle implements OracleComponent {
/** /**
* Gets the first host. * Gets the first host.
* *
* @return the first host * @return the first host
*/ */
public static NetID getFirstHost() { public static NetID getFirstHost() {
...@@ -216,17 +216,22 @@ public class GlobalOracle implements OracleComponent { ...@@ -216,17 +216,22 @@ public class GlobalOracle implements OracleComponent {
return new ArrayList<Host>(hosts); return new ArrayList<Host>(hosts);
} }
@Override
public Host getHostByID(long pValue) {
return hostIDtoHosts.get(pValue);
}
@Override @Override
public boolean isSimulation() { public boolean isSimulation() {
return true; return true;
} }
/** /**
* Returns a global view of the topology for the specified mechanism. The * Returns a global view of the topology for the specified mechanism. The
* mechanism must be a HostComponent that is registered at the local host. * mechanism must be a HostComponent that is registered at the local host.
* Otherwise, this method will not be able to find the local mechanism * Otherwise, this method will not be able to find the local mechanism
* objects. * objects.
* *
* @param component * @param component
* @param identifier * @param identifier
* @return * @return
...@@ -275,17 +280,17 @@ public class GlobalOracle implements OracleComponent { ...@@ -275,17 +280,17 @@ public class GlobalOracle implements OracleComponent {
IEdge copy = graph.createEdge(edge.fromId(), edge.toId()); IEdge copy = graph.createEdge(edge.fromId(), edge.toId());
copy.addPropertiesFrom(edge); copy.addPropertiesFrom(edge);
} }
return graph; return graph;
} }
/** /**
* Returns available topology identifiers for the given component. Throws an * Returns available topology identifiers for the given component. Throws an
* {@link ComponentNotAvailableException} if the component is not available * {@link ComponentNotAvailableException} if the component is not available
* on any node in the network. Assumes that all instances of a given * on any node in the network. Assumes that all instances of a given
* component class provide the same topology identifiers. * component class provide the same topology identifiers.
* *
* @throws ComponentNotAvailableException * @throws ComponentNotAvailableException
*/ */
public static <T extends TopologyProvider> Iterable<TopologyID> getTopologyIdentifiers( public static <T extends TopologyProvider> Iterable<TopologyID> getTopologyIdentifiers(
Class<T> component) throws ComponentNotAvailableException { Class<T> component) throws ComponentNotAvailableException {
...@@ -305,16 +310,16 @@ public class GlobalOracle implements OracleComponent { ...@@ -305,16 +310,16 @@ public class GlobalOracle implements OracleComponent {
// in various scenarios // in various scenarios
} }
} }
throw new ComponentNotAvailableException(); throw new ComponentNotAvailableException();
} }
/** /**
* Checks whether the host with the given NetID is online using a global * Checks whether the host with the given NetID is online using a global
* list of all hosts in the current scenario. * list of all hosts in the current scenario.
* *
* @param receiver * @param receiver
* @return true if online * @return true if online
*/ */
......
...@@ -24,8 +24,15 @@ import java.util.List; ...@@ -24,8 +24,15 @@ import java.util.List;
import java.util.Set; import java.util.Set;
import de.tudarmstadt.maki.simonstrator.api.Host; import de.tudarmstadt.maki.simonstrator.api.Host;
import de.tudarmstadt.maki.simonstrator.api.Time;
import de.tudarmstadt.maki.simonstrator.api.common.graph.INodeID; import de.tudarmstadt.maki.simonstrator.api.common.graph.INodeID;
import de.tudarmstadt.maki.simonstrator.api.component.ComponentNotAvailableException; import de.tudarmstadt.maki.simonstrator.api.component.ComponentNotAvailableException;
import de.tudarmstadt.maki.simonstrator.api.component.privacy.PrivacyComponent;
import de.tudarmstadt.maki.simonstrator.api.component.privacy.PrivacyLevel;
import de.tudarmstadt.maki.simonstrator.api.component.sensor.environment.data.properties.VehicleProperty;
import de.tudarmstadt.maki.simonstrator.api.component.sensor.location.Location;
import de.tudarmstadt.maki.simonstrator.api.component.sensor.location.LocationListener;
import de.tudarmstadt.maki.simonstrator.api.component.sensor.location.LocationRequest;
import de.tudarmstadt.maki.simonstrator.api.component.sensor.route.Route; import de.tudarmstadt.maki.simonstrator.api.component.sensor.route.Route;
import de.tudarmstadt.maki.simonstrator.api.component.sis.SiSComponent; import de.tudarmstadt.maki.simonstrator.api.component.sis.SiSComponent;
import de.tudarmstadt.maki.simonstrator.api.component.sis.SiSDataCallback; import de.tudarmstadt.maki.simonstrator.api.component.sis.SiSDataCallback;
...@@ -50,6 +57,8 @@ public class DefaultVehicleInformationComponent implements VehicleInformationCom ...@@ -50,6 +57,8 @@ public class DefaultVehicleInformationComponent implements VehicleInformationCom
private String vehicleID; private String vehicleID;
private long _startingTime = -1;
public DefaultVehicleInformationComponent(Host host, VehicleController controller, SimulationSetupExtractor extractor, boolean pRouteKnown) { public DefaultVehicleInformationComponent(Host host, VehicleController controller, SimulationSetupExtractor extractor, boolean pRouteKnown) {
this.host = host; this.host = host;
...@@ -87,31 +96,57 @@ public class DefaultVehicleInformationComponent implements VehicleInformationCom ...@@ -87,31 +96,57 @@ public class DefaultVehicleInformationComponent implements VehicleInformationCom
}); });
siSComponent.provide().nodeState(SiSTypes.HEADING, new SiSDataCallback<Double>() { siSComponent.provide().nodeState(SiSTypes.HEADING, new SiSDataCallback<Double>() {
@Override @Override
public Double getValue(INodeID pNodeID, public Double getValue(INodeID pNodeID,
SiSProviderHandle pProviderHandle) SiSProviderHandle pProviderHandle)
throws InformationNotAvailableException { throws InformationNotAvailableException {
if (pNodeID == getHost().getId()) { if (pNodeID == getHost().getId()) {
if (isValid()) { if (isValid()) {
return controller.getVehicleHeading(vehicleID); return controller.getVehicleHeading(vehicleID);
} }
} }
return null; return null;
} }
@Override @Override
public Set<INodeID> getObservedNodes() { public Set<INodeID> getObservedNodes() {
return INodeID.getSingleIDSet(getHost().getId()); return INodeID.getSingleIDSet(getHost().getId());
} }
@Override @Override
public SiSInfoProperties getInfoProperties() { public SiSInfoProperties getInfoProperties() {
return new SiSInfoProperties(); return new SiSInfoProperties();
} }
}); });
siSComponent.provide().nodeState(SiSTypes.VEHICLE_LENGTH, new SiSDataCallback<Double>() {
@Override
public Double getValue(INodeID pNodeID,
SiSProviderHandle pProviderHandle)
throws InformationNotAvailableException {
if (pNodeID == getHost().getId()) {
if (isValid()) {
return controller.getVehicleLength(vehicleID);
}
}
return null;
}
@Override
public Set<INodeID> getObservedNodes() {
return INodeID.getSingleIDSet(getHost().getId());
}
@Override
public SiSInfoProperties getInfoProperties() {
return new SiSInfoProperties();
}
});
if (pRouteKnown) { if (pRouteKnown) {
siSComponent.provide().nodeState(SiSTypes.ROUTE, new SiSDataCallback<RoadNetworkRoute>() { siSComponent.provide().nodeState(SiSTypes.ROUTE, new SiSDataCallback<RoadNetworkRoute>() {
...@@ -145,11 +180,32 @@ public class DefaultVehicleInformationComponent implements VehicleInformationCom ...@@ -145,11 +180,32 @@ public class DefaultVehicleInformationComponent implements VehicleInformationCom
} }
} }
@Override
public VehicleProperty getVehicleProperty() {
PrivacyLevel privacyLevel = PrivacyLevel.NO_PRIVACY;
try {
PrivacyComponent privacyComponent = getHost().getComponent(PrivacyComponent.class);
privacyLevel = privacyComponent.getPrivacyLevel();
} catch (ComponentNotAvailableException e) {
// Nothing to be done
}
return new VehicleProperty(host.getId().value(), getLastLocation(),
getCurrentRoute().getStart(), getCurrentSpeed(), getLength(), privacyLevel);
}
@Override @Override
public void setVehicleID(String pVehicleID) { public void setVehicleID(String pVehicleID) {
vehicleID = pVehicleID; vehicleID = pVehicleID;
_startingTime = Time.getCurrentTime();
} }
@Override
public long getStartingTime() {
return _startingTime;
}
@Override @Override
public void resetVehicleID() { public void resetVehicleID() {
vehicleID = null; vehicleID = null;
...@@ -183,6 +239,10 @@ public class DefaultVehicleInformationComponent implements VehicleInformationCom ...@@ -183,6 +239,10 @@ public class DefaultVehicleInformationComponent implements VehicleInformationCom
return true; return true;
} }
public double getLength() {
return controller.getVehicleLength(vehicleID);
}
@Override @Override
public RoadNetworkRoute findNewRoute() { public RoadNetworkRoute findNewRoute() {
try { try {
...@@ -243,4 +303,24 @@ public class DefaultVehicleInformationComponent implements VehicleInformationCom ...@@ -243,4 +303,24 @@ public class DefaultVehicleInformationComponent implements VehicleInformationCom
throw new UnsupportedOperationException(); throw new UnsupportedOperationException();
} }
@Override
public Location getLastLocation() {
return controller.getVehiclePosition(vehicleID);
}
@Override
public void requestLocationUpdates(LocationRequest pRequest, LocationListener pListener) {
throw new UnsupportedOperationException();
}
@Override
public void removeLocationUpdates(LocationListener pListener) {
throw new UnsupportedOperationException();
}
@Override
public LocationRequest getLocationRequest() {
throw new UnsupportedOperationException();
}
} }
...@@ -24,18 +24,24 @@ import java.util.ArrayList; ...@@ -24,18 +24,24 @@ import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import de.tudarmstadt.maki.simonstrator.api.Host; import de.tudarmstadt.maki.simonstrator.api.Host;
import de.tudarmstadt.maki.simonstrator.api.common.graph.INodeID;
import de.tudarmstadt.maki.simonstrator.api.component.ComponentNotAvailableException; import de.tudarmstadt.maki.simonstrator.api.component.ComponentNotAvailableException;
import de.tudarmstadt.maki.simonstrator.api.component.network.NetInterface; import de.tudarmstadt.maki.simonstrator.api.component.network.NetInterface;
import de.tudarmstadt.maki.simonstrator.api.component.network.NetworkComponent.NetInterfaceName; import de.tudarmstadt.maki.simonstrator.api.component.network.NetworkComponent.NetInterfaceName;
import de.tudarmstadt.maki.simonstrator.api.component.sensor.environment.data.VectoralProperty; import de.tudarmstadt.maki.simonstrator.api.component.transition.TransitionEngine;
import de.tudarmstadt.maki.simonstrator.api.component.transport.ConnectivityListener; import de.tudarmstadt.maki.simonstrator.api.component.transport.ConnectivityListener;
import de.tudarmstadt.maki.simonstrator.api.component.vehicular.VehicleInformationComponent; import de.tudarmstadt.maki.simonstrator.api.component.vehicular.VehicleInformationComponent;
import de.tudarmstadt.maki.simonstrator.api.component.vehicular.caching.CacheStateListener;
import de.tudarmstadt.maki.simonstrator.api.component.vehicular.caching.CachingComponent; import de.tudarmstadt.maki.simonstrator.api.component.vehicular.caching.CachingComponent;
import de.tudarmstadt.maki.simonstrator.api.component.vehicular.caching.decision.CacheDecisionStrategy; import de.tudarmstadt.maki.simonstrator.api.component.vehicular.caching.decision.CacheDecisionStrategy;
import de.tudarmstadt.maki.simonstrator.api.component.vehicular.caching.decision.CacheSizeAwareCacheDecisionStrategy;
import de.tudarmstadt.maki.simonstrator.api.component.vehicular.caching.invalidation.CacheInvalidationStrategy; import de.tudarmstadt.maki.simonstrator.api.component.vehicular.caching.invalidation.CacheInvalidationStrategy;
import de.tudarmstadt.maki.simonstrator.api.component.vehicular.caching.replacement.CacheReplacementStrategy; import de.tudarmstadt.maki.simonstrator.api.component.vehicular.caching.replacement.CacheReplacementStrategy;
import de.tudarmstadt.maki.simonstrator.api.component.vehicular.information.AggregatedInformation;
import de.tudarmstadt.maki.simonstrator.api.component.vehicular.information.AvailableInformationAttributes; import de.tudarmstadt.maki.simonstrator.api.component.vehicular.information.AvailableInformationAttributes;
import de.tudarmstadt.maki.simonstrator.api.component.vehicular.information.JamInformation; import de.tudarmstadt.maki.simonstrator.api.component.vehicular.information.JamInformation;
import de.tudarmstadt.maki.simonstrator.api.component.vehicular.information.PointInformation; import de.tudarmstadt.maki.simonstrator.api.component.vehicular.information.PointInformation;
...@@ -44,8 +50,8 @@ import de.tudarmstadt.maki.simonstrator.api.component.vehicular.roadnetwork.Road ...@@ -44,8 +50,8 @@ import de.tudarmstadt.maki.simonstrator.api.component.vehicular.roadnetwork.Road
import de.tudarmstadt.maki.simonstrator.api.component.vehicular.roadnetwork.RoadNetworkEdge; 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.RoadNetworkRoute;
public class DefaultCachingComponent public class DefaultCachingComponent implements CachingComponent, ConnectivityListener {
implements CachingComponent, ConnectivityListener {
private Map<Class<? extends Object>, List<PointInformation>> _cache = new HashMap<>(); private Map<Class<? extends Object>, List<PointInformation>> _cache = new HashMap<>();
private Map<Integer, Integer> _lastColorValues = new HashMap<>(); private Map<Integer, Integer> _lastColorValues = new HashMap<>();
...@@ -56,10 +62,17 @@ implements CachingComponent, ConnectivityListener { ...@@ -56,10 +62,17 @@ implements CachingComponent, ConnectivityListener {
private CacheReplacementStrategy _replacementStrategy; private CacheReplacementStrategy _replacementStrategy;
private CacheDecisionStrategy _decisionStrategy; private CacheDecisionStrategy _defaultDecisionStrategy;
private Map<Class<? extends Object>, CacheDecisionStrategy> _decisionStrategies = new HashMap<>();
private int _minObservations = 0;
private int _maxCacheSize = Integer.MAX_VALUE;
private double[] informationRatios = new double[] {1, 0.75, 0.5, 0.25, 0}; private double[] informationRatios = new double[] {1, 0.75, 0.5, 0.25, 0};
private List<CacheStateListener> _cacheStateListeners = new ArrayList<>();
public DefaultCachingComponent(Host pHost, public DefaultCachingComponent(Host pHost,
CacheInvalidationStrategy pInvalidationStrategy, CacheInvalidationStrategy pInvalidationStrategy,
CacheReplacementStrategy pReplacementStrategy, CacheReplacementStrategy pReplacementStrategy,
...@@ -67,46 +80,149 @@ implements CachingComponent, ConnectivityListener { ...@@ -67,46 +80,149 @@ implements CachingComponent, ConnectivityListener {
_host = pHost; _host = pHost;
if (_host != null) { if (_host != null) {
_host.getNetworkComponent().getByName(NetInterfaceName.WIFI) NetInterface cellular = _host.getNetworkComponent().getByName(NetInterfaceName.MOBILE);
.addConnectivityListener(this); cellular.addConnectivityListener(this);
} }
_invalidationStrategy = pInvalidationStrategy; _invalidationStrategy = pInvalidationStrategy;
_replacementStrategy = pReplacementStrategy; _replacementStrategy = pReplacementStrategy;
_decisionStrategy = pDecisionStrategy; _defaultDecisionStrategy = pDecisionStrategy;
}
private TransitionEngine getTransitionEngine() throws AssertionError {
try {
return getHost().getComponent(TransitionEngine.class);
} catch (ComponentNotAvailableException e) {
throw new AssertionError("Unable to get transition engine!");
}
}
@Override
public void registerCacheStateListener(CacheStateListener pListener) {
_cacheStateListeners.add(pListener);
} }
@Override @Override
public <T extends PointInformation> List<T> getDecidedCacheEntries( public <T extends PointInformation> List<T> getDecidedCacheEntries(
Class<T> pCacheEntryClass) { Class<T> pCacheEntryClass) {
CacheDecisionStrategy decisionStrategy = getCacheDecisionStrategy(pCacheEntryClass);
Set<RoadNetworkEdge> allEverActiveEdges = RoadNetwork.CURRENT_ROAD_NETWORK.getAllEverActiveEdges();
List<T> cacheEntries = getCacheEntries(pCacheEntryClass); List<T> cacheEntries = getCacheEntries(pCacheEntryClass);
if (cacheEntries == null) { if (cacheEntries == null) {
return null; return null;
} }
Map<Object, List<PointInformation>> similarCacheEntries = new HashMap<>(); Map<Object, Map<Class<? extends Object>, List<PointInformation>>> similarCacheEntries = new HashMap<>();
for (T t : cacheEntries) { for (T t : cacheEntries) {
Object position = getEdgeOrPosition(t); Object position = getEdgeOrPosition(t);
if (!similarCacheEntries.containsKey(position)) { if (!(position instanceof RoadNetworkEdge) || allEverActiveEdges.contains((position))) {
similarCacheEntries.put(position, new ArrayList<>()); if (!similarCacheEntries.containsKey(position)) {
similarCacheEntries.put(position, new HashMap<>());
}
if (!similarCacheEntries.get(position).containsKey(t.getValue().getClass())) {
similarCacheEntries.get(position).put(t.getValue().getClass(), new ArrayList<PointInformation>());
}
similarCacheEntries.get(position).get(t.getValue().getClass()).add(t);
} }
similarCacheEntries.get(position).add(t);
} }
List<T> decidedInformation = new ArrayList<>(); List<T> decidedInformation = new ArrayList<>();
for (List<PointInformation> similarEntries : similarCacheEntries for (Map<Class<? extends Object>, List<PointInformation>> similarEdges : similarCacheEntries
.values()) { .values()) {
PointInformation correctInformation = _decisionStrategy for (List<PointInformation> similarInformation : similarEdges.values()) {
.decideOnCorrectInformation(similarEntries); if (similarInformation.size() >= _minObservations) {
decidedInformation.add((T) correctInformation); PointInformation correctInformation = decisionStrategy
.decideOnCorrectInformation(similarInformation);
decidedInformation.add((T) correctInformation);
}
}
} }
return decidedInformation; return decidedInformation;
} }
@Override
public <T extends PointInformation> List<T> getDecidedCacheEntries(
Class<T> pCacheEntryClass, RoadNetworkEdge pEdge) {
return getDecidedCacheEntries(pCacheEntryClass, null, pEdge);
}
@Override
public <T extends PointInformation> List<T> getDecidedCacheEntries(
Class<T> pCacheEntryClass, Class<?> pCacheValueClass, RoadNetworkEdge pEdge) {
return getDecidedCacheEntries(pCacheEntryClass, pCacheValueClass, pEdge, null);
}
@Override
public <T extends PointInformation> List<T> getDecidedCacheEntries(Class<T> pCacheEntryClass, Class<?> pCacheValueClass,
RoadNetworkEdge pEdge, INodeID pWithoutID) {
CacheDecisionStrategy decisionStrategy = getCacheDecisionStrategy(pCacheEntryClass);
Set<RoadNetworkEdge> allEverActiveEdges = RoadNetwork.CURRENT_ROAD_NETWORK.getAllEverActiveEdges();
if (!allEverActiveEdges.contains(pEdge)) {
return null;
}
List<T> cacheEntries = getCacheEntries(pCacheEntryClass);
if (cacheEntries == null) {
return null;
}
Map<Class<? extends Object>, List<PointInformation>> similarCacheEntries = new HashMap<>();
for (T t : cacheEntries) {
if (pWithoutID == null || !t.getAttribute(AvailableInformationAttributes.OWNER).equals(pWithoutID)) {
Object position = getEdgeOrPosition(t);
if (position.equals(pEdge) && (pCacheValueClass == null || t.getValue().getClass().equals(pCacheValueClass))) {
if (!similarCacheEntries.containsKey(t.getValue().getClass())) {
similarCacheEntries.put(t.getValue().getClass(), new ArrayList<PointInformation>());
}
similarCacheEntries.get(t.getValue().getClass()).add(t);
}
}
}
List<T> decidedInformation = new ArrayList<>();
for (List<PointInformation> similarInformation : similarCacheEntries.values()) {
if (similarInformation.size() >= _minObservations) {
PointInformation correctInformation = decisionStrategy
.decideOnCorrectInformation(similarInformation);
decidedInformation.add((T) correctInformation);
}
}
return decidedInformation;
}
private <T extends PointInformation> CacheDecisionStrategy getCacheDecisionStrategy(Class<T> pCacheEntryClass)
throws AssertionError {
if (!_decisionStrategies.containsKey(pCacheEntryClass)) {
CacheDecisionStrategy clone = _defaultDecisionStrategy.clone();
TransitionEngine tEngine = getTransitionEngine();
clone = tEngine.createMechanismProxy(CacheDecisionStrategy.class, clone, DECISION_STRATEGY + pCacheEntryClass.getSimpleName());
_decisionStrategies.put(pCacheEntryClass, clone);
}
CacheDecisionStrategy decisionStrategy = _decisionStrategies.get(pCacheEntryClass);
return decisionStrategy;
}
public void setMinObservations(int pMinObservations) {
this._minObservations = pMinObservations;
}
@Override @Override
public <T extends PointInformation> List<T> getCacheEntries( public <T extends PointInformation> List<T> getCacheEntries(
Class<T> pCacheEntryClass) { Class<T> pCacheEntryClass) {
...@@ -131,8 +247,8 @@ implements CachingComponent, ConnectivityListener { ...@@ -131,8 +247,8 @@ implements CachingComponent, ConnectivityListener {
@Override @Override
public <T extends PointInformation> boolean containsEntry(T pCacheEntry) { public <T extends PointInformation> boolean containsEntry(T pCacheEntry) {
if (_cache.containsKey(pCacheEntry)) { if (_cache.containsKey(pCacheEntry.getClass())) {
List<? extends Object> cacheEntries = _cache.get(pCacheEntry); List<? extends Object> cacheEntries = _cache.get(pCacheEntry.getClass());
return cacheEntries.contains(pCacheEntry); return cacheEntries.contains(pCacheEntry);
} }
return false; return false;
...@@ -145,7 +261,81 @@ implements CachingComponent, ConnectivityListener { ...@@ -145,7 +261,81 @@ implements CachingComponent, ConnectivityListener {
} }
List<PointInformation> entries = _cache.get(pCacheEntry.getClass()); List<PointInformation> entries = _cache.get(pCacheEntry.getClass());
if (pCacheEntry instanceof AggregatedInformation && ((AggregatedInformation) pCacheEntry).isAggregated()) {
List<PointInformation> toBeRemoved = new ArrayList<>();
for (PointInformation pointInformation : entries) {
if (_replacementStrategy.replaceInformation(pointInformation, pCacheEntry)) {
toBeRemoved.add(pointInformation);
}
}
for (PointInformation pointInformation : toBeRemoved) {
entries.remove(pointInformation);
}
}
shrinkCache(_maxCacheSize);
entries.add(pCacheEntry); entries.add(pCacheEntry);
for (CacheStateListener cacheStateListener : _cacheStateListeners) {
cacheStateListener.entryStored(pCacheEntry);
}
}
private void shrinkCache(int maxSize) {
while (getTotalCacheSize() > maxSize) {
int maxSizeValue = 0;
List<PointInformation> removedValues = null;
List<PointInformation> removedList = null;
for (List<PointInformation> informationList : _cache.values()) {
Map<Object, List<PointInformation>> perPosition = new HashMap<>();
for (PointInformation pointInformation : informationList) {
Object position = getEdgeOrPosition(pointInformation);
if (!perPosition.containsKey(position)) {
perPosition.put(position, new ArrayList<>());
}
perPosition.get(position).add(pointInformation);
}
for (Entry<Object, List<PointInformation>> entry : perPosition.entrySet()) {
if (!((RoadNetworkEdge) entry.getKey()).isActive()) {
removedValues = entry.getValue();
removedList = informationList;
break;
}
if (maxSizeValue < entry.getValue().size()) {
maxSizeValue = entry.getValue().size();
removedValues = entry.getValue();
removedList = informationList;
}
}
}
removedList.removeAll(removedValues);
CacheDecisionStrategy decisionStrategy = getCacheDecisionStrategy(removedValues.get(0).getClass());
PointInformation correctInformation = decisionStrategy
.decideOnCorrectInformation(removedValues);
for (CacheStateListener cacheStateListener : _cacheStateListeners) {
cacheStateListener.entriesRemoved(removedValues, correctInformation);
}
}
}
private int getTotalCacheSize() {
int sum = 0;
for (List<PointInformation> informationList : _cache.values()) {
sum += informationList.size();
}
return sum;
} }
@Override @Override
...@@ -172,11 +362,47 @@ implements CachingComponent, ConnectivityListener { ...@@ -172,11 +362,47 @@ implements CachingComponent, ConnectivityListener {
} }
@Override
public void performDecisionTransition(Class<? extends Object> pInformationClass, Class<? extends CacheDecisionStrategy> pCacheDecisionStrategy) {
getTransitionEngine().executeAtomicTransition(DECISION_STRATEGY + pInformationClass.getSimpleName(), pCacheDecisionStrategy);
}
@Override
public void setMaxSize(int pMaxCacheSize) {
_maxCacheSize = pMaxCacheSize;
shrinkCache(_maxCacheSize);
}
@Override
public void adjustCacheSizePerEntry(Class<? extends Object> pInformationClass, int pMaxCacheSizePerEntry) {
getTransitionEngine().alterLocalState(DECISION_STRATEGY + pInformationClass.getSimpleName(), CacheSizeAwareCacheDecisionStrategy.class, "CacheSize", pMaxCacheSizePerEntry);
}
@Override @Override
public void clear() { public void clear() {
_cache.clear(); _cache.clear();
} }
@Override
public <T extends PointInformation> void partialClear(Class<T> pCacheEntryClass, Class<?> pCacheValueClass, RoadNetworkEdge pEdge) {
List<PointInformation> cacheEntries = _cache.get(pCacheEntryClass);
if (cacheEntries == null) {
return;
}
List<PointInformation> toBeRemoved = new ArrayList<>();
for (PointInformation entry : cacheEntries) {
if ((pEdge == null || getEdgeOrPosition(entry).equals(pEdge))
&& (pCacheEntryClass == null || entry.getValue().getClass().equals(pCacheValueClass))) {
toBeRemoved.add(entry);
}
}
cacheEntries.removeAll(toBeRemoved);
}
public Object getEdgeOrPosition(PointInformation information) { public Object getEdgeOrPosition(PointInformation information) {
if (information.hasAttribute(AvailableInformationAttributes.EDGE)) { if (information.hasAttribute(AvailableInformationAttributes.EDGE)) {
return information return information
...@@ -188,13 +414,12 @@ implements CachingComponent, ConnectivityListener { ...@@ -188,13 +414,12 @@ implements CachingComponent, ConnectivityListener {
} }
} }
public CacheDecisionStrategy getDecisionStrategy() {
return _decisionStrategy;
}
@Override @Override
public String getNodeDescription() { public String getNodeDescription() {
return " " + getHost().getId(); if (getHost().getId().value() > 47) {
return " " + getHost().getId();
}
return "";
} }
@Override @Override
......
...@@ -21,14 +21,25 @@ ...@@ -21,14 +21,25 @@
package de.tud.kom.p2psim.impl.vehicular.caching.decision; package de.tud.kom.p2psim.impl.vehicular.caching.decision;
import java.util.List; import java.util.List;
import java.util.Map;
import de.tudarmstadt.maki.simonstrator.api.component.sensor.environment.data.NumericVectoralProperty; import de.tudarmstadt.maki.simonstrator.api.component.sensor.environment.data.properties.vectoral.NumericVectoralProperty;
import de.tudarmstadt.maki.simonstrator.api.component.sensor.environment.data.jam.VectoralJamProperty; import de.tudarmstadt.maki.simonstrator.api.component.sensor.environment.data.properties.vectoral.VectoralJamProperty;
import de.tudarmstadt.maki.simonstrator.api.component.transition.TransferState;
import de.tudarmstadt.maki.simonstrator.api.component.vehicular.caching.decision.AbstractCacheDecisionStrategy;
import de.tudarmstadt.maki.simonstrator.api.component.vehicular.caching.decision.CacheDecisionStrategy; import de.tudarmstadt.maki.simonstrator.api.component.vehicular.caching.decision.CacheDecisionStrategy;
import de.tudarmstadt.maki.simonstrator.api.component.vehicular.caching.decision.CacheDecisionStrategyParameters;
import de.tudarmstadt.maki.simonstrator.api.component.vehicular.information.PointInformation; import de.tudarmstadt.maki.simonstrator.api.component.vehicular.information.PointInformation;
import de.tudarmstadt.maki.simonstrator.api.component.vehicular.information.RoadInformation; import de.tudarmstadt.maki.simonstrator.api.component.vehicular.information.RoadInformation;
public class AveragingCacheDecisionStrategy implements CacheDecisionStrategy { public class AveragingCacheDecisionStrategy extends AbstractCacheDecisionStrategy implements CacheDecisionStrategy {
private Map<CacheDecisionStrategyParameters, String> _params;
@TransferState(value = { "Params" })
public AveragingCacheDecisionStrategy(Map<CacheDecisionStrategyParameters, String> pParams) {
_params = pParams;
}
@Override @Override
public <T extends PointInformation> T decideOnCorrectInformation( public <T extends PointInformation> T decideOnCorrectInformation(
...@@ -39,33 +50,43 @@ public class AveragingCacheDecisionStrategy implements CacheDecisionStrategy { ...@@ -39,33 +50,43 @@ public class AveragingCacheDecisionStrategy implements CacheDecisionStrategy {
} else if (pSimilarPointInformation.size() == 0) { } else if (pSimilarPointInformation.size() == 0) {
return null; return null;
} }
double sum = 0; double sum = 0;
double count = 0; double count = 0;
NumericVectoralProperty cloned = null; NumericVectoralProperty cloned = null;
for (T t : pSimilarPointInformation) { for (T t : pSimilarPointInformation) {
RoadInformation roadInformation = ((RoadInformation) t); RoadInformation roadInformation = ((RoadInformation) t);
NumericVectoralProperty property = (NumericVectoralProperty) roadInformation.getValue(); NumericVectoralProperty property = (NumericVectoralProperty) roadInformation.getValue();
if (cloned == null) { if (cloned == null) {
cloned = property.clone(); cloned = property.clone();
} }
sum += property.getMostProbableValue(); sum += property.getMostProbableValue();
count++; count++;
} }
double value = sum / count; double value = sum / count;
if (cloned instanceof VectoralJamProperty) { if (cloned instanceof VectoralJamProperty) {
((VectoralJamProperty) cloned).setSpeed(((int)(value / VectoralJamProperty.SCALING)) * VectoralJamProperty.SCALING); ((VectoralJamProperty) cloned).setSpeed(((int)(value / VectoralJamProperty.SCALING)) * VectoralJamProperty.SCALING);
} else { } else {
throw new AssertionError("Unknown data type " + cloned.getClass().getSimpleName()); throw new AssertionError("Unknown data type " + cloned.getClass().getSimpleName());
} }
return (T) new RoadInformation(cloned); RoadInformation aggregate = new RoadInformation(cloned);
addAggregationInformation(pSimilarPointInformation, aggregate);
return (T) aggregate;
}
public Map<CacheDecisionStrategyParameters, String> getParams() {
return _params;
} }
@Override
public AveragingCacheDecisionStrategy clone() {
return new AveragingCacheDecisionStrategy(_params);
}
} }
...@@ -26,12 +26,13 @@ import java.util.HashMap; ...@@ -26,12 +26,13 @@ import java.util.HashMap;
import java.util.Map; import java.util.Map;
import de.tudarmstadt.maki.simonstrator.api.component.vehicular.caching.decision.CacheDecisionStrategy; import de.tudarmstadt.maki.simonstrator.api.component.vehicular.caching.decision.CacheDecisionStrategy;
import de.tudarmstadt.maki.simonstrator.api.component.vehicular.caching.decision.CacheDecisionStrategyParameters;
public enum CacheDecisionStrategyType { public enum CacheDecisionStrategyType {
DEFAULT(NewestCacheDecisionStrategy.class), NEWEST(NewestCacheDecisionStrategy.class), MAJORITY(MajorityVotingCacheDecisionStrategy.class), AVERAGING(AveragingCacheDecisionStrategy.class), TTL(TTLbasedCacheDecisionStrategy.class), OPTIMAL(OptimalCacheDecisionStrategy.class), RANDOM(RandomCacheDecisionStrategy.class), TTL_VECTOR(TTLbasedVectoralCacheDecisionStrategy.class), MAJORITY_VECTOR(MajorityVotingVectoralCacheDecisionStrategy.class); DEFAULT(NewestCacheDecisionStrategy.class), NEWEST(NewestCacheDecisionStrategy.class), MAJORITY(MajorityVotingCacheDecisionStrategy.class), AVERAGING(AveragingCacheDecisionStrategy.class), TTL(TTLbasedCacheDecisionStrategy.class), OPTIMAL(OptimalCacheDecisionStrategy.class), RANDOM(RandomCacheDecisionStrategy.class), TTL_VECTOR(TTLbasedVectoralCacheDecisionStrategy.class), MAJORITY_VECTOR(MajorityVotingVectoralCacheDecisionStrategy.class);
private final Class<? extends CacheDecisionStrategy> decisionStrategy; private final Class<? extends CacheDecisionStrategy> decisionStrategy;
private final Map<String, String> params = new HashMap<>(); private final Map<CacheDecisionStrategyParameters, String> params = new HashMap<>();
private CacheDecisionStrategyType(final Class<? extends CacheDecisionStrategy> decisionStrategy) { private CacheDecisionStrategyType(final Class<? extends CacheDecisionStrategy> decisionStrategy) {
this.decisionStrategy = decisionStrategy; this.decisionStrategy = decisionStrategy;
...@@ -50,7 +51,7 @@ public enum CacheDecisionStrategyType { ...@@ -50,7 +51,7 @@ public enum CacheDecisionStrategyType {
} }
} }
public void addAttribute(String pKey, String pValue) { public void addAttribute(CacheDecisionStrategyParameters pParam, String pValue) {
params.put(pKey, pValue); params.put(pParam, pValue);
} }
} }
...@@ -25,21 +25,37 @@ import java.util.List; ...@@ -25,21 +25,37 @@ import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Map.Entry; import java.util.Map.Entry;
import de.tudarmstadt.maki.simonstrator.api.component.sensor.environment.data.properties.vectoral.VectoralProperty;
import de.tudarmstadt.maki.simonstrator.api.component.transition.TransferState;
import de.tudarmstadt.maki.simonstrator.api.component.vehicular.caching.decision.AbstractCacheDecisionStrategy;
import de.tudarmstadt.maki.simonstrator.api.component.vehicular.caching.decision.CacheDecisionStrategy; import de.tudarmstadt.maki.simonstrator.api.component.vehicular.caching.decision.CacheDecisionStrategy;
import de.tudarmstadt.maki.simonstrator.api.component.vehicular.caching.decision.CacheDecisionStrategyParameters;
import de.tudarmstadt.maki.simonstrator.api.component.vehicular.information.PointInformation; import de.tudarmstadt.maki.simonstrator.api.component.vehicular.information.PointInformation;
import de.tudarmstadt.maki.simonstrator.api.component.vehicular.information.RoadInformation;
public class MajorityVotingCacheDecisionStrategy implements CacheDecisionStrategy { public class MajorityVotingCacheDecisionStrategy extends AbstractCacheDecisionStrategy implements CacheDecisionStrategy {
private Map<CacheDecisionStrategyParameters, String> _params;
@TransferState(value = { "Params" })
public MajorityVotingCacheDecisionStrategy(Map<CacheDecisionStrategyParameters, String> pParams) {
_params = pParams;
}
@Override @Override
public <T extends PointInformation> T decideOnCorrectInformation( public <T extends PointInformation> T decideOnCorrectInformation(
List<T> pSimilarPointInformation) { List<T> pSimilarPointInformation) {
Map<Object, Integer> voting = new HashMap<>(); Map<Object, Integer> voting = new HashMap<>();
for (T t : pSimilarPointInformation) { for (T t : pSimilarPointInformation) {
if (!voting.containsKey(t.getValue())) { Object value = t.getValue();
voting.put(t.getValue(), 0); if (value instanceof VectoralProperty) {
value = ((VectoralProperty) value).getMostProbableValue();
}
if (!voting.containsKey(value)) {
voting.put(value, 0);
} }
voting.put(t.getValue(), voting.get(t.getValue()) + 1); voting.put(value, voting.get(value) + 1);
} }
Entry<Object, Integer> maxEntry = null; Entry<Object, Integer> maxEntry = null;
...@@ -58,13 +74,23 @@ public class MajorityVotingCacheDecisionStrategy implements CacheDecisionStrateg ...@@ -58,13 +74,23 @@ public class MajorityVotingCacheDecisionStrategy implements CacheDecisionStrateg
for (T t : pSimilarPointInformation) { for (T t : pSimilarPointInformation) {
long timestamp = t.getDetectionDate(); long timestamp = t.getDetectionDate();
if (t.getValue().equals(maxEntry.getKey()) && timestamp > maxTimestamp) { if ((t.getValue().equals(maxEntry.getKey()) || t.getValue() instanceof VectoralProperty && ((VectoralProperty)t.getValue()).getMostProbableValue().equals(maxEntry.getKey())) && timestamp > maxTimestamp) {
maxTimestamp = timestamp; maxTimestamp = timestamp;
maxFitting = t; maxFitting = t;
} }
} }
addAggregationInformation(pSimilarPointInformation, maxFitting);
return maxFitting; return maxFitting;
} }
public Map<CacheDecisionStrategyParameters, String> getParams() {
return _params;
}
@Override
public MajorityVotingCacheDecisionStrategy clone() {
return new MajorityVotingCacheDecisionStrategy(_params);
}
} }
...@@ -21,23 +21,34 @@ ...@@ -21,23 +21,34 @@
package de.tud.kom.p2psim.impl.vehicular.caching.decision; package de.tud.kom.p2psim.impl.vehicular.caching.decision;
import java.util.List; import java.util.List;
import java.util.Map;
import de.tudarmstadt.maki.simonstrator.api.Time; import de.tudarmstadt.maki.simonstrator.api.Time;
import de.tudarmstadt.maki.simonstrator.api.component.sensor.environment.data.TemporalDependencyMatrix; import de.tudarmstadt.maki.simonstrator.api.component.sensor.environment.data.TemporalDependencyMatrix;
import de.tudarmstadt.maki.simonstrator.api.component.sensor.environment.data.VectoralProperty; import de.tudarmstadt.maki.simonstrator.api.component.sensor.environment.data.properties.vectoral.VectoralProperty;
import de.tudarmstadt.maki.simonstrator.api.component.transition.TransferState;
import de.tudarmstadt.maki.simonstrator.api.component.vehicular.caching.decision.AbstractCacheDecisionStrategy;
import de.tudarmstadt.maki.simonstrator.api.component.vehicular.caching.decision.CacheDecisionStrategy; import de.tudarmstadt.maki.simonstrator.api.component.vehicular.caching.decision.CacheDecisionStrategy;
import de.tudarmstadt.maki.simonstrator.api.component.vehicular.caching.decision.CacheDecisionStrategyParameters;
import de.tudarmstadt.maki.simonstrator.api.component.vehicular.information.AvailableInformationAttributes; import de.tudarmstadt.maki.simonstrator.api.component.vehicular.information.AvailableInformationAttributes;
import de.tudarmstadt.maki.simonstrator.api.component.vehicular.information.PointInformation; import de.tudarmstadt.maki.simonstrator.api.component.vehicular.information.PointInformation;
import de.tudarmstadt.maki.simonstrator.api.component.vehicular.information.RoadInformation; import de.tudarmstadt.maki.simonstrator.api.component.vehicular.information.RoadInformation;
public class MajorityVotingVectoralCacheDecisionStrategy implements CacheDecisionStrategy { public class MajorityVotingVectoralCacheDecisionStrategy extends AbstractCacheDecisionStrategy implements CacheDecisionStrategy {
private static final long SCALING = Time.SECOND; private static final long SCALING = Time.SECOND;
private Map<CacheDecisionStrategyParameters, String> _params;
@TransferState(value = { "Params" })
public MajorityVotingVectoralCacheDecisionStrategy(Map<CacheDecisionStrategyParameters, String> pParams) {
_params = pParams;
}
@Override @Override
public <T extends PointInformation> T decideOnCorrectInformation( public <T extends PointInformation> T decideOnCorrectInformation(
List<T> pSimilarPointInformation) { List<T> pSimilarPointInformation) {
VectoralProperty currentProperty = null; VectoralProperty currentProperty = null;
long minTimestamp = Long.MAX_VALUE; long minTimestamp = Long.MAX_VALUE;
long maxTimestamp = 0; long maxTimestamp = 0;
for (T t : pSimilarPointInformation) { for (T t : pSimilarPointInformation) {
...@@ -50,14 +61,14 @@ public class MajorityVotingVectoralCacheDecisionStrategy implements CacheDecisio ...@@ -50,14 +61,14 @@ public class MajorityVotingVectoralCacheDecisionStrategy implements CacheDecisio
maxTimestamp = timestamp; maxTimestamp = timestamp;
} }
} }
for (T t : pSimilarPointInformation) { for (T t : pSimilarPointInformation) {
RoadInformation roadInformation = ((RoadInformation) t); RoadInformation roadInformation = ((RoadInformation) t);
VectoralProperty property = (VectoralProperty) roadInformation.getValue(); VectoralProperty property = (VectoralProperty) roadInformation.getValue();
TemporalDependencyMatrix dependencyMatrix = property.getDependencyMatrix(); TemporalDependencyMatrix dependencyMatrix = property.getDependencyMatrix();
VectoralProperty agedProperty = property.age((maxTimestamp - property.getDetectionDate()) / SCALING, dependencyMatrix); VectoralProperty agedProperty = property.age((maxTimestamp - property.getDetectionDate()) / SCALING, dependencyMatrix);
if (currentProperty != null) { if (currentProperty != null) {
currentProperty = currentProperty.combine(agedProperty); currentProperty = currentProperty.combine(agedProperty);
...@@ -65,15 +76,16 @@ public class MajorityVotingVectoralCacheDecisionStrategy implements CacheDecisio ...@@ -65,15 +76,16 @@ public class MajorityVotingVectoralCacheDecisionStrategy implements CacheDecisio
currentProperty = agedProperty; currentProperty = agedProperty;
} }
} }
TemporalDependencyMatrix dependencyMatrix = currentProperty.getDependencyMatrix(); // TemporalDependencyMatrix dependencyMatrix = currentProperty.getDependencyMatrix();
//
VectoralProperty agedProperty = currentProperty.age((Time.getCurrentTime() - maxTimestamp) / SCALING, dependencyMatrix); // VectoralProperty agedProperty = currentProperty.age((Time.getCurrentTime() - maxTimestamp) / SCALING, dependencyMatrix);
RoadInformation roadInformation = new RoadInformation(agedProperty); RoadInformation roadInformation = new RoadInformation(currentProperty);
copyAttributes((RoadInformation) pSimilarPointInformation.get(0), roadInformation); copyAttributes((RoadInformation) pSimilarPointInformation.get(0), roadInformation);
addAggregationInformation(pSimilarPointInformation, roadInformation);
return (T) roadInformation; return (T) roadInformation;
} }
...@@ -87,4 +99,13 @@ public class MajorityVotingVectoralCacheDecisionStrategy implements CacheDecisio ...@@ -87,4 +99,13 @@ public class MajorityVotingVectoralCacheDecisionStrategy implements CacheDecisio
} }
} }
public Map<CacheDecisionStrategyParameters, String> getParams() {
return _params;
}
@Override
public MajorityVotingVectoralCacheDecisionStrategy clone() {
return new MajorityVotingVectoralCacheDecisionStrategy(_params);
}
} }
...@@ -21,11 +21,22 @@ ...@@ -21,11 +21,22 @@
package de.tud.kom.p2psim.impl.vehicular.caching.decision; package de.tud.kom.p2psim.impl.vehicular.caching.decision;
import java.util.List; import java.util.List;
import java.util.Map;
import de.tudarmstadt.maki.simonstrator.api.component.transition.TransferState;
import de.tudarmstadt.maki.simonstrator.api.component.vehicular.caching.decision.AbstractCacheDecisionStrategy;
import de.tudarmstadt.maki.simonstrator.api.component.vehicular.caching.decision.CacheDecisionStrategy; import de.tudarmstadt.maki.simonstrator.api.component.vehicular.caching.decision.CacheDecisionStrategy;
import de.tudarmstadt.maki.simonstrator.api.component.vehicular.caching.decision.CacheDecisionStrategyParameters;
import de.tudarmstadt.maki.simonstrator.api.component.vehicular.information.PointInformation; import de.tudarmstadt.maki.simonstrator.api.component.vehicular.information.PointInformation;
public class NewestCacheDecisionStrategy implements CacheDecisionStrategy { public class NewestCacheDecisionStrategy extends AbstractCacheDecisionStrategy implements CacheDecisionStrategy {
private Map<CacheDecisionStrategyParameters, String> _params;
@TransferState(value = { "Params" })
public NewestCacheDecisionStrategy(Map<CacheDecisionStrategyParameters, String> pParams) {
_params = pParams;
}
@Override @Override
public <T extends PointInformation> T decideOnCorrectInformation( public <T extends PointInformation> T decideOnCorrectInformation(
...@@ -41,4 +52,13 @@ public class NewestCacheDecisionStrategy implements CacheDecisionStrategy { ...@@ -41,4 +52,13 @@ public class NewestCacheDecisionStrategy implements CacheDecisionStrategy {
return chosenInformation; return chosenInformation;
} }
public Map<CacheDecisionStrategyParameters, String> getParams() {
return _params;
}
@Override
public NewestCacheDecisionStrategy clone() {
return new NewestCacheDecisionStrategy(_params);
}
} }
...@@ -21,17 +21,26 @@ ...@@ -21,17 +21,26 @@
package de.tud.kom.p2psim.impl.vehicular.caching.decision; package de.tud.kom.p2psim.impl.vehicular.caching.decision;
import java.util.List; import java.util.List;
import java.util.Map;
import de.tudarmstadt.maki.simonstrator.api.Time; import de.tudarmstadt.maki.simonstrator.api.Time;
import de.tudarmstadt.maki.simonstrator.api.component.sensor.environment.data.VectoralProperty; import de.tudarmstadt.maki.simonstrator.api.component.sensor.environment.data.properties.JamProperty;
import de.tudarmstadt.maki.simonstrator.api.component.sensor.environment.data.jam.JamProperty; import de.tudarmstadt.maki.simonstrator.api.component.sensor.environment.data.properties.vectoral.VectoralProperty;
import de.tudarmstadt.maki.simonstrator.api.component.transition.TransferState;
import de.tudarmstadt.maki.simonstrator.api.component.vehicular.caching.decision.AbstractCacheDecisionStrategy;
import de.tudarmstadt.maki.simonstrator.api.component.vehicular.caching.decision.CacheDecisionStrategy; import de.tudarmstadt.maki.simonstrator.api.component.vehicular.caching.decision.CacheDecisionStrategy;
import de.tudarmstadt.maki.simonstrator.api.component.vehicular.caching.decision.CacheDecisionStrategyParameters;
import de.tudarmstadt.maki.simonstrator.api.component.vehicular.information.AvailableInformationAttributes; import de.tudarmstadt.maki.simonstrator.api.component.vehicular.information.AvailableInformationAttributes;
import de.tudarmstadt.maki.simonstrator.api.component.vehicular.information.PointInformation; import de.tudarmstadt.maki.simonstrator.api.component.vehicular.information.PointInformation;
import de.tudarmstadt.maki.simonstrator.api.component.vehicular.roadnetwork.RoadNetworkEdge; import de.tudarmstadt.maki.simonstrator.api.component.vehicular.roadnetwork.RoadNetworkEdge;
public class OptimalCacheDecisionStrategy implements CacheDecisionStrategy { public class OptimalCacheDecisionStrategy extends AbstractCacheDecisionStrategy implements CacheDecisionStrategy {
public OptimalCacheDecisionStrategy() {
private Map<CacheDecisionStrategyParameters, String> _params;
@TransferState(value = { "Params" })
public OptimalCacheDecisionStrategy(Map<CacheDecisionStrategyParameters, String> pParams) {
_params = pParams;
} }
@Override @Override
...@@ -43,11 +52,11 @@ public class OptimalCacheDecisionStrategy implements CacheDecisionStrategy { ...@@ -43,11 +52,11 @@ public class OptimalCacheDecisionStrategy implements CacheDecisionStrategy {
} else if (pSimilarPointInformation.size() == 0) { } else if (pSimilarPointInformation.size() == 0) {
return null; return null;
} }
RoadNetworkEdge edge = (RoadNetworkEdge) pSimilarPointInformation.get(0).getAttribute(AvailableInformationAttributes.EDGE); RoadNetworkEdge edge = (RoadNetworkEdge) pSimilarPointInformation.get(0).getAttribute(AvailableInformationAttributes.EDGE);
double actualSpeed = edge.getCurrentSpeed(); double actualSpeed = edge.getCurrentSpeed();
JamProperty jamProperty = edge.getJamProperty(); JamProperty jamProperty = edge.getJamProperty();
long maxTimestamp; long maxTimestamp;
...@@ -66,7 +75,7 @@ public class OptimalCacheDecisionStrategy implements CacheDecisionStrategy { ...@@ -66,7 +75,7 @@ public class OptimalCacheDecisionStrategy implements CacheDecisionStrategy {
if (currentValue instanceof VectoralProperty) { if (currentValue instanceof VectoralProperty) {
currentValue = ((VectoralProperty) currentValue).getMostProbableValue(); currentValue = ((VectoralProperty) currentValue).getMostProbableValue();
} }
if (timestamp >= maxTimestamp) { if (timestamp >= maxTimestamp) {
if (currentValue.equals(actualSpeed)) { if (currentValue.equals(actualSpeed)) {
maxFitting = t; maxFitting = t;
...@@ -93,4 +102,14 @@ public class OptimalCacheDecisionStrategy implements CacheDecisionStrategy { ...@@ -93,4 +102,14 @@ public class OptimalCacheDecisionStrategy implements CacheDecisionStrategy {
return maxFitting; return maxFitting;
} }
public Map<CacheDecisionStrategyParameters, String> getParams() {
return _params;
}
@Override
public OptimalCacheDecisionStrategy clone() {
return new OptimalCacheDecisionStrategy(_params);
}
} }
...@@ -21,16 +21,24 @@ ...@@ -21,16 +21,24 @@
package de.tud.kom.p2psim.impl.vehicular.caching.decision; package de.tud.kom.p2psim.impl.vehicular.caching.decision;
import java.util.List; import java.util.List;
import java.util.Map;
import java.util.Random; import java.util.Random;
import de.tudarmstadt.maki.simonstrator.api.Randoms; import de.tudarmstadt.maki.simonstrator.api.Randoms;
import de.tudarmstadt.maki.simonstrator.api.component.transition.TransferState;
import de.tudarmstadt.maki.simonstrator.api.component.vehicular.caching.decision.AbstractCacheDecisionStrategy;
import de.tudarmstadt.maki.simonstrator.api.component.vehicular.caching.decision.CacheDecisionStrategy; import de.tudarmstadt.maki.simonstrator.api.component.vehicular.caching.decision.CacheDecisionStrategy;
import de.tudarmstadt.maki.simonstrator.api.component.vehicular.caching.decision.CacheDecisionStrategyParameters;
import de.tudarmstadt.maki.simonstrator.api.component.vehicular.information.PointInformation; import de.tudarmstadt.maki.simonstrator.api.component.vehicular.information.PointInformation;
public class RandomCacheDecisionStrategy implements CacheDecisionStrategy { public class RandomCacheDecisionStrategy extends AbstractCacheDecisionStrategy implements CacheDecisionStrategy {
private Random _random = Randoms.getRandom(getClass()); private Random _random = Randoms.getRandom(getClass());
public RandomCacheDecisionStrategy() { private Map<CacheDecisionStrategyParameters, String> _params;
@TransferState(value = { "Params" })
public RandomCacheDecisionStrategy(Map<CacheDecisionStrategyParameters, String> pParams) {
_params = pParams;
} }
@Override @Override
...@@ -45,4 +53,14 @@ public class RandomCacheDecisionStrategy implements CacheDecisionStrategy { ...@@ -45,4 +53,14 @@ public class RandomCacheDecisionStrategy implements CacheDecisionStrategy {
return pSimilarPointInformation.get(_random.nextInt(pSimilarPointInformation.size())); return pSimilarPointInformation.get(_random.nextInt(pSimilarPointInformation.size()));
} }
public Map<CacheDecisionStrategyParameters, String> getParams() {
return _params;
}
@Override
public RandomCacheDecisionStrategy clone() {
return new RandomCacheDecisionStrategy(_params);
}
} }
...@@ -29,19 +29,26 @@ import java.util.Map; ...@@ -29,19 +29,26 @@ import java.util.Map;
import java.util.Map.Entry; import java.util.Map.Entry;
import de.tudarmstadt.maki.simonstrator.api.Time; import de.tudarmstadt.maki.simonstrator.api.Time;
import de.tudarmstadt.maki.simonstrator.api.component.sensor.environment.data.RoadProperty; import de.tudarmstadt.maki.simonstrator.api.component.relevance.vehicular.impl.SimpleQoIBasedImpactFunction;
import de.tudarmstadt.maki.simonstrator.api.component.sensor.environment.data.VectoralProperty; import de.tudarmstadt.maki.simonstrator.api.component.sensor.environment.data.properties.RoadProperty;
import de.tudarmstadt.maki.simonstrator.api.component.sensor.environment.data.jam.VectoralJamProperty; import de.tudarmstadt.maki.simonstrator.api.component.sensor.environment.data.properties.vectoral.VectoralJamProperty;
import de.tudarmstadt.maki.simonstrator.api.component.sensor.environment.data.properties.vectoral.VectoralProperty;
import de.tudarmstadt.maki.simonstrator.api.component.transition.TransferState;
import de.tudarmstadt.maki.simonstrator.api.component.vehicular.caching.decision.AbstractCacheDecisionStrategy;
import de.tudarmstadt.maki.simonstrator.api.component.vehicular.caching.decision.CacheDecisionStrategy; import de.tudarmstadt.maki.simonstrator.api.component.vehicular.caching.decision.CacheDecisionStrategy;
import de.tudarmstadt.maki.simonstrator.api.component.vehicular.caching.decision.CacheDecisionStrategyParameters;
import de.tudarmstadt.maki.simonstrator.api.component.vehicular.caching.decision.CacheSizeAwareCacheDecisionStrategy;
import de.tudarmstadt.maki.simonstrator.api.component.vehicular.information.AvailableInformationAttributes; import de.tudarmstadt.maki.simonstrator.api.component.vehicular.information.AvailableInformationAttributes;
import de.tudarmstadt.maki.simonstrator.api.component.vehicular.information.PointInformation; import de.tudarmstadt.maki.simonstrator.api.component.vehicular.information.PointInformation;
import de.tudarmstadt.maki.simonstrator.api.component.vehicular.information.RoadInformation; import de.tudarmstadt.maki.simonstrator.api.component.vehicular.information.RoadInformation;
public class TTLbasedCacheDecisionStrategy implements CacheDecisionStrategy { public class TTLbasedCacheDecisionStrategy extends AbstractCacheDecisionStrategy implements CacheSizeAwareCacheDecisionStrategy {
private static final long SCALING = Time.SECOND; private static final long SCALING = Time.SECOND;
private static final double ACCURACY_FACTOR = 100000; private static final double ACCURACY_FACTOR = 100000;
private final Map<CacheDecisionStrategyParameters, String> _params;
private long ttl = 300 * Time.SECOND / SCALING; private long ttl = 300 * Time.SECOND / SCALING;
private double accuracy = 1; private double accuracy = 1;
...@@ -50,13 +57,17 @@ public class TTLbasedCacheDecisionStrategy implements CacheDecisionStrategy { ...@@ -50,13 +57,17 @@ public class TTLbasedCacheDecisionStrategy implements CacheDecisionStrategy {
private Object _lastDecision = false; private Object _lastDecision = false;
public TTLbasedCacheDecisionStrategy(Map<String, String> pParams) { private int _maxCacheSize = Integer.MAX_VALUE;
for (Entry<String, String> param : pParams.entrySet()) {
@TransferState(value = { "Params" })
public TTLbasedCacheDecisionStrategy(Map<CacheDecisionStrategyParameters, String> pParams) {
_params = pParams;
for (Entry<CacheDecisionStrategyParameters, String> param : pParams.entrySet()) {
switch (param.getKey()) { switch (param.getKey()) {
case "ACCURACY": case ACCURACY:
accuracy = Double.valueOf(param.getValue()); accuracy = Double.valueOf(param.getValue());
break; break;
case "COST_RATIO": case COST_RATIO:
double ratio = Double.valueOf(param.getValue()); double ratio = Double.valueOf(param.getValue());
costWrongChange = 2 / (ratio + 1); costWrongChange = 2 / (ratio + 1);
costWrongKeep = 2 - costWrongChange; costWrongKeep = 2 - costWrongChange;
...@@ -80,283 +91,118 @@ public class TTLbasedCacheDecisionStrategy implements CacheDecisionStrategy { ...@@ -80,283 +91,118 @@ public class TTLbasedCacheDecisionStrategy implements CacheDecisionStrategy {
List<T> pSimilarPointInformation) { List<T> pSimilarPointInformation) {
if (pSimilarPointInformation.size() == 1) { if (pSimilarPointInformation.size() == 1) {
T decision = pSimilarPointInformation.get(0); T decision = pSimilarPointInformation.get(0);
addAggregationInformation(pSimilarPointInformation, decision);
_lastDecision = decision.getValue(); _lastDecision = decision.getValue();
return decision; return decision;
} else if (pSimilarPointInformation.size() == 0) { } else if (pSimilarPointInformation.size() == 0) {
return null; return null;
} }
Collections.sort(pSimilarPointInformation, new Comparator<T>() { Collections.sort(pSimilarPointInformation, new Comparator<T>() {
@Override @Override
public int compare(T pArg0, T pArg1) { public int compare(T pArg0, T pArg1) {
return Long.compare(pArg0.getDetectionDate(), pArg1.getDetectionDate()); return Long.compare(pArg0.getDetectionDate(), pArg1.getDetectionDate());
} }
}); });
long minTimestamp = Long.MAX_VALUE;
long maxTimestamp = 0;
Object value = pSimilarPointInformation.get(0).getValue(); Object value = pSimilarPointInformation.get(0).getValue();
boolean differentValue = false; boolean differentValue = false;
for (T t : pSimilarPointInformation) { for (T t : pSimilarPointInformation) {
if (!t.hasAttribute(AvailableInformationAttributes.TTL)) {
throw new AssertionError("Unable to perform TTL-based majority voting witout TTL");
}
long timestamp = t.getDetectionDate();
if (timestamp < minTimestamp) {
minTimestamp = timestamp;
}
if (timestamp > maxTimestamp) {
maxTimestamp = timestamp;
}
if (!value.equals(t.getValue())) { if (!value.equals(t.getValue())) {
differentValue = true; differentValue = true;
} }
} }
if (differentValue) { SimpleQoIBasedImpactFunction<T> impactFunction = new SimpleQoIBasedImpactFunction<>(pSimilarPointInformation, accuracy, _maxCacheSize);
long difference = maxTimestamp - minTimestamp;
if (difference == 0) {
return pSimilarPointInformation.get(pSimilarPointInformation.size() - 1);
}
double rate = difference / ((double) (pSimilarPointInformation.size() - 1) * SCALING);
long ttl = (long)pSimilarPointInformation.get(0).getAttribute(AvailableInformationAttributes.TTL) / SCALING; Map<Object, Double> weight = new HashMap<>();
rate = Math.min(rate, ttl / 10.0);
double b; for (T t : pSimilarPointInformation) {
if (Boolean.FALSE.equals(_lastDecision)) { double impact = impactFunction.calculateImpact(t);
b = determineB(rate, 1 - accuracy, ttl, costWrongKeep, costWrongChange);
} else {
b = determineB(rate, 1 - accuracy, ttl, costWrongChange, costWrongKeep);
}
Map<Object, Double> weight = new HashMap<>();
for (T t : pSimilarPointInformation) {
double impact = calculateImpact(1 - accuracy, ttl, t.getDetectionDate() / SCALING, b, maxTimestamp / SCALING);
double sumImpact = 0;
Object currentValue = t.getValue();
if (currentValue instanceof VectoralJamProperty) {
currentValue = ((VectoralJamProperty) currentValue).getMostProbableValue();
}
if (weight.containsKey(currentValue)) {
sumImpact = weight.get(currentValue);
}
sumImpact += impact;
weight.put(currentValue, sumImpact); double sumImpact = 0;
}
double maxWeight = -1; Object currentValue = t.getValue();
Object maxValue = null;
for (Object key : weight.keySet()) { if (currentValue instanceof VectoralJamProperty) {
if (weight.get(key) > maxWeight) { currentValue = ((VectoralJamProperty) currentValue).getMostProbableValue();
maxWeight = weight.get(key);
maxValue = key;
}
} }
maxTimestamp = -1; if (weight.containsKey(currentValue)) {
T maxFitting = null; sumImpact = weight.get(currentValue);
for (T t : pSimilarPointInformation) {
long timestamp = t.getDetectionDate();
Object currentValue = t.getValue();
if (currentValue instanceof VectoralProperty) {
currentValue = ((VectoralProperty)currentValue).getMostProbableValue();
}
if (currentValue.equals(maxValue) && timestamp > maxTimestamp) {
maxTimestamp = timestamp;
maxFitting = t;
}
}
if (maxFitting.getValue() instanceof VectoralProperty) {
VectoralProperty vectoralProperty = ((VectoralProperty)maxFitting.getValue()).clone();
double[] valueProbabilities = vectoralProperty.getValueProbabilities();
Arrays.fill(valueProbabilities, 0);
double sum = 0;
for (Object key : weight.keySet()) {
valueProbabilities[vectoralProperty.getIndexForValue(key)] = weight.get(key);
sum += weight.get(key);
}
for (int i = 0; i < valueProbabilities.length; i++) {
valueProbabilities[i] /= sum;
}
RoadInformation roadInformation = new RoadInformation(vectoralProperty);
roadInformation.copyAttributes((RoadInformation)maxFitting);
maxFitting = (T) roadInformation;
} }
sumImpact += impact;
_lastDecision = maxFitting.getValue(); weight.put(currentValue, sumImpact);
}
return maxFitting; double maxWeight = -1;
} else { Object maxValue = null;
maxTimestamp = -1;
T maxFitting = null;
for (T t : pSimilarPointInformation) {
long timestamp = (long) t.getAttribute(AvailableInformationAttributes.TTL);
if (timestamp > maxTimestamp) { for (Object key : weight.keySet()) {
maxTimestamp = timestamp; if (weight.get(key) > maxWeight) {
maxFitting = t; maxWeight = weight.get(key);
} maxValue = key;
} }
_lastDecision = maxFitting.getValue();
return maxFitting;
} }
}
public double calculateImpact(double errorProbability, long ttl, long time, double b, long maxTimestamp) {
long age = maxTimestamp - time;
if (errorProbability == 0) {
if (time == maxTimestamp) {
return 1;
} else {
return 0;
}
} else if (errorProbability == 1) {
return 1;
} else if (errorProbability == 0.5) {
return (errorProbability - 1) / ttl * age + errorProbability;
} else if (b == Double.NEGATIVE_INFINITY) {
if (time == maxTimestamp) {
return 1;
} else {
return 0;
}
}
return (1 - errorProbability) * (Math.exp(b * age) - Math.exp(b * ttl)) / (1 - Math.exp(b * ttl));
}
public double getChangeProbability(long ttl) { long maxTimestamp = -1;
return 1 - Math.pow(0.5, 1 / (double) ttl); T maxFitting = null;
} for (T t : pSimilarPointInformation) {
long timestamp = t.getDetectionDate();
public int getOptimalMessageAmountForSwitch(double changeProbability, double errorProbability, double costSlow, double costFast) {
return (int) Math.round(Math.log(-changeProbability / Math.log(errorProbability) * costSlow / costFast) / Math.log(errorProbability));
}
public double determineB(double rate, double errorProbability, long ttl, double costSlow, double costFast) { Object currentValue = t.getValue();
return determineB(rate, errorProbability, ttl, costSlow, costFast, 1); if (currentValue instanceof VectoralProperty) {
} currentValue = ((VectoralProperty)currentValue).getMostProbableValue();
}
public double determineB(double rate, double errorProbability, long ttl, double costSlow, double costFast, int reversed) { if (currentValue.equals(maxValue) && timestamp > maxTimestamp) {
if (errorProbability == 0 || errorProbability == 1 || errorProbability == 0.5) { maxTimestamp = timestamp;
return Double.NaN; maxFitting = t;
}
} }
double b; if (maxFitting.getValue() instanceof VectoralProperty) {
double p_c = getChangeProbability((long) (ttl / rate)); VectoralProperty vectoralProperty = ((VectoralProperty)maxFitting.getValue()).clone();
double[] valueProbabilities = vectoralProperty.getValueProbabilities();
int optimalAmount = getOptimalMessageAmountForSwitch(p_c, errorProbability, costSlow, costFast); Arrays.fill(valueProbabilities, 0);
if (optimalAmount == 1) { double sum = 0;
return Double.NEGATIVE_INFINITY; for (Object key : weight.keySet()) {
} valueProbabilities[vectoralProperty.getIndexForValue(key)] = weight.get(key);
sum += weight.get(key);
boolean first = true; }
double leftSide;
double rightSide;
double step = 5; for (int i = 0; i < valueProbabilities.length; i++) {
valueProbabilities[i] /= sum;
}
if (errorProbability < 0.5) { RoadInformation roadInformation = new RoadInformation(vectoralProperty);
b = -2 * step * reversed; roadInformation.copyAttributes((RoadInformation)maxFitting);
} else { maxFitting = (T) roadInformation;
b = 2 * step * reversed;
} }
int similar = 0; _lastDecision = maxFitting.getValue();
double lastDifference = -1;
do {
leftSide = calculateWeightingForOldState(optimalAmount, rate, errorProbability, ttl, b);
rightSide = calculateWeightingForNewState(optimalAmount, rate, errorProbability, ttl, b);
if (Math.abs(Math.round((rightSide - leftSide) * ACCURACY_FACTOR)) == lastDifference) {
similar++;
} else {
lastDifference = Math.abs(Math.round((rightSide - leftSide) * ACCURACY_FACTOR));
similar = 0;
}
if (Double.isNaN(leftSide) || Double.isNaN(rightSide) || similar > 100) { addAggregationInformation(pSimilarPointInformation, maxFitting);
if (reversed != -1) {
double determineB = determineB(rate, errorProbability, ttl, costSlow, costFast, -1);
if (!Double.isNaN(determineB)) {
return determineB;
} else {
return b;
}
} else {
return Double.NaN;
}
}
leftSide = Math.round(leftSide * ACCURACY_FACTOR); return maxFitting;
rightSide = Math.round(rightSide * ACCURACY_FACTOR); }
if (leftSide > rightSide) {
if (b < 0) {
b -= step;
if (!first) {
step *= 0.5;
}
} else {
b -= step;
step *= 0.5;
first = false;
}
} else if (leftSide < rightSide) {
if (b > 0) {
b += step;
if (!first) {
step *= 0.5;
}
} else {
b += step;
step *= 0.5;
first = false;
}
} else {
break;
}
} while (true);
return b; public Map<CacheDecisionStrategyParameters, String> getParams() {
return _params;
} }
public double calculateWeightingForOldState(int optimalMessageAmount, double rate, double errorProbability, long ttl, double b) { @Override
double impact = 0; public void setCacheSize(int pCacheSize) {
for (int a = optimalMessageAmount; a < Math.max(Math.floor(ttl / rate), optimalMessageAmount + 2); a++) { _maxCacheSize = pCacheSize;
impact += calculateImpact(errorProbability, ttl, Time.getCurrentTime() / SCALING - (long)Math.floor(a * rate), b, Time.getCurrentTime() / SCALING);
}
return impact;
} }
public double calculateWeightingForNewState(int optimalMessageAmount, double rate, double errorProbability, long ttl, double b) { @Override
double impact = 0; public TTLbasedCacheDecisionStrategy clone() {
for (int a = 0; a < optimalMessageAmount; a++) { return new TTLbasedCacheDecisionStrategy(_params);
impact += calculateImpact(errorProbability, ttl, Time.getCurrentTime() / SCALING - (long)Math.floor(a * rate), b, Time.getCurrentTime() / SCALING);
}
return impact;
} }
} }
...@@ -21,9 +21,10 @@ ...@@ -21,9 +21,10 @@
package de.tud.kom.p2psim.impl.vehicular.caching.replacement; package de.tud.kom.p2psim.impl.vehicular.caching.replacement;
import de.tudarmstadt.maki.simonstrator.api.component.vehicular.caching.replacement.CacheReplacementStrategy; import de.tudarmstadt.maki.simonstrator.api.component.vehicular.caching.replacement.CacheReplacementStrategy;
import de.tudarmstadt.maki.simonstrator.api.component.vehicular.caching.replacement.SimilarInformationReplacementStrategy;
public enum CacheReplacementStrategyType { public enum CacheReplacementStrategyType {
DEFAULT(NoCacheReplacementStrategy.class), NONE(NoCacheReplacementStrategy.class), IMMEDIATE(ImmediateCacheReplacementStrategy.class), TTL(TTLbasedCacheReplacementStrategy.class); DEFAULT(NoCacheReplacementStrategy.class), NONE(NoCacheReplacementStrategy.class), IMMEDIATE(ImmediateCacheReplacementStrategy.class), TTL(TTLbasedCacheReplacementStrategy.class), SIMILAR(SimilarInformationReplacementStrategy.class);
private final Class<? extends CacheReplacementStrategy> replacementStrategy; private final Class<? extends CacheReplacementStrategy> replacementStrategy;
......
/*
* Copyright (c) 2005-2010 KOM – Multimedia Communications Lab
*
* This file is part of Simonstrator.KOM.
*
* Simonstrator.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.vehicular.decision;
import de.tud.kom.p2psim.impl.topology.movement.VehicleMovementModel;
import de.tudarmstadt.maki.simonstrator.api.Event;
import de.tudarmstadt.maki.simonstrator.api.EventHandler;
import de.tudarmstadt.maki.simonstrator.api.Host;
import de.tudarmstadt.maki.simonstrator.api.Monitor;
import de.tudarmstadt.maki.simonstrator.api.Time;
import de.tudarmstadt.maki.simonstrator.api.component.ComponentNotAvailableException;
import de.tudarmstadt.maki.simonstrator.api.component.core.MonitorComponent.AnalyzerNotAvailableException;
import de.tudarmstadt.maki.simonstrator.api.component.sensor.environment.EnvironmentSensor;
import de.tudarmstadt.maki.simonstrator.api.component.vehicular.VehicleDecisionComponent;
import de.tudarmstadt.maki.simonstrator.api.component.vehicular.VehicleInformationComponent;
import de.tudarmstadt.maki.simonstrator.api.component.vehicular.caching.CachingComponent;
import de.tudarmstadt.maki.simonstrator.api.component.vehicular.information.RoadInformation;
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.VehicleRouteAnalyzer;
public abstract class AbstractVehicleDecisionComponent implements VehicleDecisionComponent, EventHandler {
private static final int EVENT_DECISION_MAKING_CYCLE = 0;
private static final long EVENT_DECISION_MAKING_FREQUENCY = Time.SECOND * VehicleMovementModel.TIMESTEP_RATIO;
private VehicleInformationComponent _vehicleInformation;
private Host _host;
private CachingComponent _cache;
private boolean _routeAnalyzerInit = false;
private VehicleRouteAnalyzer _routeAnalyzer = null;
private EnvironmentSensor _sensors;
public AbstractVehicleDecisionComponent(Host pHost) {
_host = pHost;
}
@Override
public void initialize() {
try {
_cache = getHost().getComponent(CachingComponent.class);
_sensors = getHost().getComponent(EnvironmentSensor.class);
} catch (ComponentNotAvailableException e) {
throw new AssertionError(e);
}
}
@Override
public void shutdown() {
// Nothing to do
}
public VehicleInformationComponent getVehicleInformation() {
if (_vehicleInformation == null) {
try {
_vehicleInformation = getHost().getComponent(VehicleInformationComponent.class);
} catch (ComponentNotAvailableException e) {
throw new AssertionError(e);
}
}
return _vehicleInformation;
}
@Override
public Host getHost() {
return _host;
}
@Override
public void startDecisionMaking() {
Event.scheduleWithDelay(EVENT_DECISION_MAKING_FREQUENCY / 3 * 2, this, null, EVENT_DECISION_MAKING_CYCLE);
}
@Override
public final void eventOccurred(Object pContent, int pType) {
switch (pType) {
case EVENT_DECISION_MAKING_CYCLE:
RoadNetworkRoute currentRoute = getVehicleInformation().getCurrentRoute();
if (currentRoute != null) {
boolean changed = false;
if (currentRoute.getRoute().size() > 2) {
BenefitBasedRoute optimalRouteWithBenefit = getOptimalRoute(currentRoute,
_cache.getDecidedCacheEntries(RoadInformation.class), _sensors.getEnvironment());
if (optimalRouteWithBenefit != null && optimalRouteWithBenefit.getBenefit() > 0) {
RoadNetworkRoute optimalRoute = optimalRouteWithBenefit.getRoute();
if (optimalRouteWithBenefit.getRoute().getRoute().size() > 1) {
if (hasRouteAnalyzer()) {
getRouteAnalyzer().routeChanged(getHost().getId(), currentRoute, optimalRoute);
}
changed = true;
getVehicleInformation().changeCurrentRoute(optimalRouteWithBenefit.getRoute());
}
}
}
if (!changed && hasRouteAnalyzer()) {
getRouteAnalyzer().routeUnchanged(getHost().getId(), currentRoute);
}
}
Event.scheduleWithDelay(EVENT_DECISION_MAKING_FREQUENCY, this, null, EVENT_DECISION_MAKING_CYCLE);
break;
default:
break;
}
}
public boolean hasRouteAnalyzer() {
if (!_routeAnalyzerInit) {
_routeAnalyzerInit = true;
try {
_routeAnalyzer = Monitor.get(VehicleRouteAnalyzer.class);
} catch (AnalyzerNotAvailableException e) {
}
}
return _routeAnalyzer != null;
}
public VehicleRouteAnalyzer getRouteAnalyzer() {
return _routeAnalyzer;
}
}
\ No newline at end of file
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment