1
0
Fork 0
mirror of https://github.com/graphhopper/jsprit.git synced 2020-01-24 07:45:05 +01:00

add editorconfig - #174

This commit is contained in:
oblonski 2015-09-11 12:45:48 +02:00
commit 2a95edf129
495 changed files with 73196 additions and 73383 deletions

13
.editorconfig Normal file
View file

@ -0,0 +1,13 @@
root = true
[*]
indent_style = space
indent_size = 4
insert_final_newline = true
charset = utf-8
end_of_line = lf
trim_trailing_whitespace = true
max_line_length = 120
[.travis.yml]
indent_size = 2

View file

@ -1,4 +1,5 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<groupId>jsprit</groupId>
<artifactId>jsprit</artifactId>

View file

@ -92,8 +92,7 @@ public class AlgorithmEventsRecorder implements RuinListener, IterationStartsLis
if (dgsFile.getName().endsWith("gz")) {
gzipOs = new GZIPOutputStream(fos);
fileSink.begin(gzipOs);
}
else{
} else {
fileSink.begin(fos);
}
graph.addSink(fileSink);
@ -151,8 +150,7 @@ public class AlgorithmEventsRecorder implements RuinListener, IterationStartsLis
Job job = ((TourActivity.JobActivity) act).getJob();
if (job instanceof Service) {
nodeId = job.getId();
}
else if(job instanceof Shipment){
} else if (job instanceof Shipment) {
if (act.getName().equals("pickupShipment")) nodeId = getFromNodeId((Shipment) job);
else nodeId = getToNodeId((Shipment) job);
}
@ -192,7 +190,8 @@ public class AlgorithmEventsRecorder implements RuinListener, IterationStartsLis
removeEdge(enteringFromNode.getId());
removeEdge(enteringToNode.getId());
if (graph.getNode(toNodeId).getLeavingEdgeSet().isEmpty()) {
if(fromRoute.getVehicle().isReturnToDepot()) throw new IllegalStateException("leaving edge is missing");
if (fromRoute.getVehicle().isReturnToDepot())
throw new IllegalStateException("leaving edge is missing");
return;
}
@ -203,8 +202,7 @@ public class AlgorithmEventsRecorder implements RuinListener, IterationStartsLis
if (!fromRoute.getActivities().isEmpty()) {
addEdge(makeEdgeId(from, to), from.getId(), to.getId());
}
}
else{
} else {
removeNodeAndBelongingEdges(fromNodeId, fromRoute);
removeNodeAndBelongingEdges(toNodeId, fromRoute);
}
@ -215,7 +213,9 @@ public class AlgorithmEventsRecorder implements RuinListener, IterationStartsLis
if (edges.size() == 1) return edges.iterator().next();
else {
for (Edge e : edges) {
if(e.getId().startsWith("shipment")){ continue; }
if (e.getId().startsWith("shipment")) {
continue;
}
return e;
}
}
@ -227,7 +227,9 @@ public class AlgorithmEventsRecorder implements RuinListener, IterationStartsLis
if (enteringEdges.size() == 1) return enteringEdges.iterator().next();
else {
for (Edge e : enteringEdges) {
if(e.getId().startsWith("shipment")){ continue; }
if (e.getId().startsWith("shipment")) {
continue;
}
return e;
}
}
@ -312,8 +314,7 @@ public class AlgorithmEventsRecorder implements RuinListener, IterationStartsLis
Service service = (Service) job;
addNode(service.getId(), service.getLocation().getCoordinate());
markService(service);
}
else if(job instanceof Shipment){
} else if (job instanceof Shipment) {
Shipment shipment = (Shipment) job;
String fromNodeId = getFromNodeId(shipment);
addNode(fromNodeId, shipment.getPickupLocation().getCoordinate());
@ -335,8 +336,7 @@ public class AlgorithmEventsRecorder implements RuinListener, IterationStartsLis
private void markService(Service service) {
if (service instanceof Delivery) {
markDelivery(service.getId());
}
else {
} else {
markPickup(service.getId());
}
}
@ -438,8 +438,7 @@ public class AlgorithmEventsRecorder implements RuinListener, IterationStartsLis
if (isFirst(insertionIndex)) {
node_i = makeStartId(data.getSelectedVehicle());
}
else {
} else {
TourActivity.JobActivity jobActivity = (TourActivity.JobActivity) route.getActivities().get(insertionIndex - 1);
node_i = getNodeId(jobActivity);
}
@ -447,8 +446,7 @@ public class AlgorithmEventsRecorder implements RuinListener, IterationStartsLis
String node_j;
if (isLast(insertionIndex, route)) {
node_j = makeEndId(data.getSelectedVehicle());
}
else {
} else {
TourActivity.JobActivity jobActivity = (TourActivity.JobActivity) route.getActivities().get(insertionIndex);
node_j = getNodeId(jobActivity);
}
@ -495,8 +493,7 @@ public class AlgorithmEventsRecorder implements RuinListener, IterationStartsLis
private void markInserted(Job job) {
if (job instanceof Service) {
markService((Service) job);
}
else{
} else {
markShipment((Shipment) job);
}
}

View file

@ -136,11 +136,9 @@ public class AlgorithmEventsViewer {
}
if (step == AlgorithmEventsRecorder.RUIN) {
delayContainer.delay = ruinDelay;
}
else if(step == AlgorithmEventsRecorder.CLEAR_SOLUTION){
} else if (step == AlgorithmEventsRecorder.CLEAR_SOLUTION) {
delayContainer.delay = delay;
}
else if(step == AlgorithmEventsRecorder.BEFORE_RUIN_RENDER_SOLUTION){
} else if (step == AlgorithmEventsRecorder.BEFORE_RUIN_RENDER_SOLUTION) {
delayContainer.delay = delay;
}
}

View file

@ -30,11 +30,10 @@ import java.util.Collection;
/**
* VehicleRoutingAlgorithm-Listener to record the solution-search-progress.
*
* <p/>
* <p>Register this listener in VehicleRoutingAlgorithm.
*
* @author stefan schroeder
*
*/
public class AlgorithmSearchProgressChartListener implements IterationEndsListener, AlgorithmEndsListener, AlgorithmStartsListener {

View file

@ -39,12 +39,11 @@ public class ComputationalLaboratory {
/**
* Listener-interface to listen to calculation.
*
* <p/>
* <p>Note that calculations are run concurrently, i.e. a unique task that is distributed to an available thread is
* {algorithm, instance, run}.
*
* @author schroeder
*
*/
public static interface CalculationListener extends LabListener {
@ -65,7 +64,6 @@ public class ComputationalLaboratory {
* Collects whatever indicators you require by algorithmName, instanceName, run and indicator.
*
* @author schroeder
*
*/
public static class DataCollector {
@ -82,6 +80,7 @@ public class ComputationalLaboratory {
this.run = run;
this.indicatorName = indicatorName;
}
@Override
public int hashCode() {
final int prime = 31;
@ -100,6 +99,7 @@ public class ComputationalLaboratory {
result = prime * result + run;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
@ -128,15 +128,19 @@ public class ComputationalLaboratory {
return false;
return true;
}
public String getInstanceName() {
return instanceName;
}
public String getAlgorithmName() {
return algorithmName;
}
public int getRun() {
return run;
}
public String getIndicatorName() {
return indicatorName;
}
@ -153,6 +157,7 @@ public class ComputationalLaboratory {
private ConcurrentHashMap<Key, Double> data = new ConcurrentHashMap<ComputationalLaboratory.DataCollector.Key, Double>();
private ConcurrentHashMap<Key, VehicleRoutingProblemSolution> solutions = new ConcurrentHashMap<ComputationalLaboratory.DataCollector.Key, VehicleRoutingProblemSolution>();
/**
* Adds a single date by instanceName, algorithmName, run and indicatorName.
* <p>If there is already an entry for this instance, algorithm, run and indicatorName, it is overwritten.
@ -164,7 +169,8 @@ public class ComputationalLaboratory {
* @param value
*/
public void addDate(String instanceName, String algorithmName, int run, String indicatorName, double value) {
if(indicatorName.equals(SOLUTION_INDICATOR_NAME)) throw new IllegalArgumentException(indicatorName + " is already used internally. please choose another indicator-name.");
if (indicatorName.equals(SOLUTION_INDICATOR_NAME))
throw new IllegalArgumentException(indicatorName + " is already used internally. please choose another indicator-name.");
Key key = new Key(instanceName, algorithmName, run, indicatorName);
data.put(key, value);
}
@ -285,7 +291,8 @@ public class ComputationalLaboratory {
* @throws IllegalStateException if there is already an algorithmFactory with the same name
*/
public void addAlgorithmFactory(String name, VehicleRoutingAlgorithmFactory factory) {
if(algorithmNames.contains(name)) throw new IllegalStateException("there is already a algorithmFactory with the same name (algorithmName="+name+"). unique names are required.");
if (algorithmNames.contains(name))
throw new IllegalStateException("there is already a algorithmFactory with the same name (algorithmName=" + name + "). unique names are required.");
algorithms.add(new Algorithm(name, factory));
algorithmNames.add(name);
}
@ -306,7 +313,8 @@ public class ComputationalLaboratory {
* @throws IllegalStateException if there is already an instance with the same name.
*/
public void addInstance(String name, VehicleRoutingProblem problem) {
if(benchmarkInstances.contains(name)) throw new IllegalStateException("there is already an instance with the same name (instanceName="+name+"). unique names are required.");
if (benchmarkInstances.contains(name))
throw new IllegalStateException("there is already an instance with the same name (instanceName=" + name + "). unique names are required.");
benchmarkInstances.add(new BenchmarkInstance(name, problem, null, null));
instanceNames.add(name);
}
@ -318,7 +326,8 @@ public class ComputationalLaboratory {
* @throws IllegalStateException if there is already an instance with the same name.
*/
public void addInstance(BenchmarkInstance instance) {
if(benchmarkInstances.contains(instance.name)) throw new IllegalStateException("there is already an instance with the same name (instanceName="+instance.name+"). unique names are required.");
if (benchmarkInstances.contains(instance.name))
throw new IllegalStateException("there is already an instance with the same name (instanceName=" + instance.name + "). unique names are required.");
benchmarkInstances.add(instance);
instanceNames.add(instance.name);
}
@ -372,7 +381,7 @@ public class ComputationalLaboratory {
/**
* Runs experiments.
*
* <p/>
* <p>If nuThreads > 1 it runs them concurrently, i.e. individual runs are distributed to available threads. Therefore
* a unique task is defined by its algorithmName, instanceName and its runNumber.
* <p>If you have one algorithm called "myAlgorithm" and one instance called "myInstance", and you need to run "myAlgorithm" on "myInstance" three times
@ -380,8 +389,8 @@ public class ComputationalLaboratory {
* <p>You can register whatever analysisTool you require by implementing and registering CalculationListener. Then your tool is informed just
* before a calculation starts as well as just after a calculation has been finished.
*
* @see CalculationListener
* @throws IllegalStateException if either no algorithm or no instance has been specified
* @see CalculationListener
*/
public void run() {
if (algorithms.isEmpty()) {

View file

@ -41,7 +41,6 @@ public class ConcurrentBenchmarker {
}
private String algorithmConfig = null;
private List<BenchmarkInstance> benchmarkInstances = new ArrayList<BenchmarkInstance>();
@ -63,7 +62,9 @@ public class ConcurrentBenchmarker {
private VehicleRoutingAlgorithmFactory algorithmFactory;
public void setCost(Cost cost){ this.cost = cost; }
public void setCost(Cost cost) {
this.cost = cost;
}
public ConcurrentBenchmarker(String algorithmConfig) {
super();
@ -165,8 +166,7 @@ public class ConcurrentBenchmarker {
private VehicleRoutingAlgorithm createAlgorithm(BenchmarkInstance p) {
if (algorithmConfig != null) {
return VehicleRoutingAlgorithms.readAndCreateAlgorithm(p.vrp, algorithmConfig);
}
else{
} else {
return algorithmFactory.createAlgorithm(p.vrp);
}

View file

@ -113,7 +113,6 @@ public class GraphStreamViewer {
"}";
@SuppressWarnings("UnusedDeclaration")
public static String SIMPLE_WHITE =
"node {" +
@ -308,7 +307,7 @@ public class GraphStreamViewer {
/**
* Sets the camera-view. Center describes the center-focus of the camera and zoomFactor its
* zoomFactor.
*
* <p/>
* <p>a zoomFactor < 1 zooms in and > 1 out.
*
* @param centerX x coordinate of center
@ -392,8 +391,7 @@ public class GraphStreamViewer {
for (Job j : vrp.getJobs().values()) {
if (j instanceof Service) {
renderService(g, (Service) j, label);
}
else if(j instanceof Shipment){
} else if (j instanceof Shipment) {
renderShipment(g, (Shipment) j, label, renderShipments);
}
sleep(renderDelay_in_ms);
@ -583,22 +581,20 @@ public class GraphStreamViewer {
if (label.equals(Label.ACTIVITY)) {
Node actNode = g.getNode(currIdentifier);
actNode.addAttribute("ui.label", act.getName());
}
else if(label.equals(Label.JOB_NAME)){
} else if (label.equals(Label.JOB_NAME)) {
Node actNode = g.getNode(currIdentifier);
actNode.addAttribute("ui.label", job.getName());
}
else if(label.equals(Label.ARRIVAL_TIME)){
} else if (label.equals(Label.ARRIVAL_TIME)) {
Node actNode = g.getNode(currIdentifier);
actNode.addAttribute("ui.label", Time.parseSecondsToTime(act.getArrTime()));
}
else if(label.equals(Label.DEPARTURE_TIME)){
} else if (label.equals(Label.DEPARTURE_TIME)) {
Node actNode = g.getNode(currIdentifier);
actNode.addAttribute("ui.label", Time.parseSecondsToTime(act.getEndTime()));
}
g.addEdge(makeEdgeId(routeId, vehicle_edgeId), prevIdentifier, currIdentifier, true);
if (act instanceof PickupActivity) g.getNode(currIdentifier).addAttribute("ui.class", "pickupInRoute");
else if (act instanceof DeliveryActivity) g.getNode(currIdentifier).addAttribute("ui.class", "deliveryInRoute");
else if (act instanceof DeliveryActivity)
g.getNode(currIdentifier).addAttribute("ui.class", "deliveryInRoute");
prevIdentifier = currIdentifier;
vehicle_edgeId++;
sleep(renderDelay_in_ms);

View file

@ -53,7 +53,6 @@ import java.util.*;
* <p>Note that every item to be rendered need to have coordinates.
*
* @author schroeder
*
*/
public class Plotter {
@ -124,6 +123,7 @@ public class Plotter {
double minY;
double maxX;
double maxY;
public BoundingBox(double minX, double minY, double maxX, double maxY) {
super();
this.minX = minX;
@ -143,8 +143,8 @@ public class Plotter {
/**
* Label to label ID (=jobId), SIZE (=jobSize=jobCapacityDimensions)
* @author schroeder
*
* @author schroeder
*/
public static enum Label {
ID, SIZE, @SuppressWarnings("UnusedDeclaration")NO_LABEL
@ -224,6 +224,7 @@ public class Plotter {
/**
* Sets a label.
*
* @param label of jobs
* @return plotter
*/
@ -274,11 +275,9 @@ public class Plotter {
if (!pngFileName.endsWith(".png")) filename += ".png";
if (plotSolutionAsWell) {
plot(vrp, routes, filename, plotTitle);
}
else if(!(vrp.getInitialVehicleRoutes().isEmpty())){
} else if (!(vrp.getInitialVehicleRoutes().isEmpty())) {
plot(vrp, vrp.getInitialVehicleRoutes(), filename, plotTitle);
}
else{
} else {
plot(vrp, null, filename, plotTitle);
}
}
@ -428,8 +427,7 @@ public class Plotter {
if (boundingBox == null) {
xAxis.setRangeWithMargins(getDomainRange(problem));
yAxis.setRangeWithMargins(getRange(problem));
}
else{
} else {
xAxis.setRangeWithMargins(new Range(boundingBox.minX, boundingBox.maxX));
yAxis.setRangeWithMargins(new Range(boundingBox.minY, boundingBox.maxY));
}
@ -500,8 +498,7 @@ public class Plotter {
if (first) {
first = false;
shipmentSeries = new XYSeries(ship, false, true);
}
else{
} else {
shipmentSeries = new XYSeries(sCounter, false, true);
sCounter++;
}
@ -530,8 +527,7 @@ public class Plotter {
addLabel(s, dataItem2);
markItem(dataItem2, Activity.DELIVERY);
containsDeliveryAct = true;
}
else if(job instanceof Pickup){
} else if (job instanceof Pickup) {
Pickup service = (Pickup) job;
Coordinate coord = getCoordinate(service.getLocation().getCoordinate());
XYDataItem dataItem = new XYDataItem(coord.getX() * scalingFactor, coord.getY() * scalingFactor);
@ -539,8 +535,7 @@ public class Plotter {
addLabel(service, dataItem);
markItem(dataItem, Activity.PICKUP);
containsPickupAct = true;
}
else if(job instanceof Delivery){
} else if (job instanceof Delivery) {
Delivery service = (Delivery) job;
Coordinate coord = getCoordinate(service.getLocation().getCoordinate());
XYDataItem dataItem = new XYDataItem(coord.getX() * scalingFactor, coord.getY() * scalingFactor);
@ -548,8 +543,7 @@ public class Plotter {
addLabel(service, dataItem);
markItem(dataItem, Activity.DELIVERY);
containsDeliveryAct = true;
}
else if(job instanceof Service){
} else if (job instanceof Service) {
Service service = (Service) job;
Coordinate coord = getCoordinate(service.getLocation().getCoordinate());
XYDataItem dataItem = new XYDataItem(coord.getX() * scalingFactor, coord.getY() * scalingFactor);
@ -557,8 +551,7 @@ public class Plotter {
addLabel(service, dataItem);
markItem(dataItem, Activity.SERVICE);
containsServiceAct = true;
}
else{
} else {
throw new IllegalStateException("job instanceof " + job.getClass().toString() + ". this is not supported.");
}
}
@ -566,8 +559,7 @@ public class Plotter {
private void addLabel(Job job, XYDataItem dataItem) {
if (this.label.equals(Label.SIZE)) {
labelsByDataItem.put(dataItem, getSizeString(job));
}
else if(this.label.equals(Label.ID)){
} else if (this.label.equals(Label.ID)) {
labelsByDataItem.put(dataItem, String.valueOf(job.getId()));
}
}
@ -580,8 +572,7 @@ public class Plotter {
if (firstDim) {
builder.append(String.valueOf(job.getSize().get(i)));
firstDim = false;
}
else {
} else {
builder.append(",");
builder.append(String.valueOf(job.getSize().get(i)));
}

View file

@ -32,9 +32,7 @@ import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;
/**
*
* @author schroeder
*
*/
public class XYLineChartBuilder {
@ -58,7 +56,6 @@ public class XYLineChartBuilder {
* @param chartTitle appears on top of the XYLineChart
* @param xDomainName appears below the xAxis
* @param yDomainName appears beside the yAxis
*
* @return the builder
*/
public static XYLineChartBuilder newInstance(String chartTitle, String xDomainName, String yDomainName) {
@ -95,6 +92,7 @@ public class XYLineChartBuilder {
/**
* Builds and returns JFreeChart.
*
* @return
*/
public JFreeChart build() {

View file

@ -16,10 +16,10 @@
******************************************************************************/
package jsprit.analysis.util;
import java.util.Collection;
import jsprit.core.util.BenchmarkResult;
import java.util.Collection;
public interface BenchmarkWriter {
public void write(Collection<BenchmarkResult> results);
}

View file

@ -16,14 +16,14 @@
******************************************************************************/
package jsprit.analysis.util;
import jsprit.core.util.BenchmarkResult;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Collection;
import jsprit.core.util.BenchmarkResult;
public class HtmlBenchmarkTableWriter implements BenchmarkWriter {
private String filename;
@ -169,15 +169,13 @@ public class HtmlBenchmarkTableWriter implements BenchmarkWriter{
if (sum_res_star != null) {
writer.write(date(Double.valueOf(round(sum_res_star.doubleValue() / (double) results.size(), 2)).toString()) + newline());
delta_res = (sum_avg_result / sum_res_star - 1) * 100;
}
else writer.write(date("null") + newline());
} else writer.write(date("null") + newline());
//bestKnownVeh
Double delta_veh = null;
if (sum_veh_star != null) {
writer.write(date(Double.valueOf(round(sum_veh_star.doubleValue() / (double) results.size(), 2)).toString()) + newline());
delta_veh = (sum_avg_veh - sum_veh_star) / (double) results.size();
}
else writer.write(date("null") + newline());
} else writer.write(date("null") + newline());
writer.write(closeRow() + newline());
writer.write(closeTable() + newline());
@ -255,5 +253,4 @@ public class HtmlBenchmarkTableWriter implements BenchmarkWriter{
}
}

View file

@ -1,4 +1,3 @@
<!--~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~ Copyright (C) 2014 Stefan Schroeder
~
@ -16,7 +15,8 @@
~ License along with this library. If not, see <http://www.gnu.org/licenses />.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<groupId>jsprit</groupId>
<artifactId>jsprit</artifactId>

View file

@ -60,7 +60,9 @@ public class SearchStrategy {
return strategyId;
}
public String getStrategyId() { return strategyId; }
public String getStrategyId() {
return strategyId;
}
@Override
public String toString() {
@ -124,7 +126,7 @@ public class SearchStrategy {
/**
* Runs the search-strategy and its according modules, and returns DiscoveredSolution.
*
* <p/>
* <p>This involves three basic steps: 1) Selecting a solution from solutions (input parameter) according to {@link jsprit.core.algorithm.selector.SolutionSelector}, 2) running the modules
* ({@link jsprit.core.algorithm.SearchStrategyModule}) on the selectedSolution and 3) accepting the new solution according to {@link jsprit.core.algorithm.acceptor.SolutionAcceptor}.
* <p> Note that after 1) the selected solution is copied, thus the original solution is not modified.

View file

@ -55,6 +55,7 @@ public class SearchStrategyManager {
* Returns the probabilities.
* [schroeder (2014.11.21): Now they are actually no propabilities anymore but weights. The resulting probabilities
* are calculated here with the sum of weights]
*
* @return list of probabilities
*/
@Deprecated
@ -62,7 +63,9 @@ public class SearchStrategyManager {
return Collections.unmodifiableList(weights);
}
public List<Double> getWeights(){ return Collections.unmodifiableList(weights); }
public List<Double> getWeights() {
return Collections.unmodifiableList(weights);
}
public double getWeight(String strategyId) {
return weights.get(id2index.get(strategyId));
@ -70,6 +73,7 @@ public class SearchStrategyManager {
/**
* adds a new search strategy with a certain weight.
*
* @param strategy strategy to be added
* @param weight of corresponding strategy to be added
* @throws java.lang.IllegalStateException if strategy is null OR weight < 0
@ -112,7 +116,8 @@ public class SearchStrategyManager {
* @throws java.lang.IllegalStateException if randomNumberGenerator is null OR no search strategy can be found
*/
public SearchStrategy getRandomStrategy() {
if(random == null) throw new IllegalStateException("randomizer is null. make sure you set random object correctly");
if (random == null)
throw new IllegalStateException("randomizer is null. make sure you set random object correctly");
double randomFig = random.nextDouble();
double sumProbabilities = 0.0;
for (int i = 0; i < weights.size(); i++) {

View file

@ -31,7 +31,6 @@ import jsprit.core.problem.vehicle.Vehicle;
* this objective function.
*
* @author schroeder
*
*/
public class VariablePlusFixedSolutionCostCalculatorFactory {

View file

@ -35,7 +35,6 @@ import java.util.Collection;
* Algorithm that solves a {@link VehicleRoutingProblem}.
*
* @author stefan schroeder
*
*/
public class VehicleRoutingAlgorithm {
@ -179,7 +178,7 @@ public class VehicleRoutingAlgorithm {
/**
* Runs the vehicle routing algorithm and returns a number of generated solutions.
*
* <p/>
* <p>The algorithm runs as long as it is specified in nuOfIterations and prematureBreak. In each iteration it selects a searchStrategy according
* to searchStrategyManager and runs the strategy to improve solutions.
* <p>Note that clients are allowed to observe/listen the algorithm. See {@link VehicleRoutingAlgorithmListener} and its according listeners.
@ -226,7 +225,8 @@ public class VehicleRoutingAlgorithm {
private void memorizeIfBestEver(DiscoveredSolution discoveredSolution) {
if (discoveredSolution == null) return;
if (bestEver == null) bestEver = discoveredSolution.getSolution();
else if(discoveredSolution.getSolution().getCost() < bestEver.getCost()) bestEver = discoveredSolution.getSolution();
else if (discoveredSolution.getSolution().getCost() < bestEver.getCost())
bestEver = discoveredSolution.getSolution();
}
@ -244,8 +244,10 @@ public class VehicleRoutingAlgorithm {
public void addListener(VehicleRoutingAlgorithmListener l) {
algoListeners.addListener(l);
if(l instanceof SearchStrategyListener) searchStrategyManager.addSearchStrategyListener((SearchStrategyListener) l);
if(l instanceof SearchStrategyModuleListener) searchStrategyManager.addSearchStrategyModuleListener((SearchStrategyModuleListener) l);
if (l instanceof SearchStrategyListener)
searchStrategyManager.addSearchStrategyListener((SearchStrategyListener) l);
if (l instanceof SearchStrategyModuleListener)
searchStrategyManager.addSearchStrategyModuleListener((SearchStrategyModuleListener) l);
}
private void iterationEnds(int i, VehicleRoutingProblem problem, Collection<VehicleRoutingProblemSolution> solutions) {

View file

@ -29,7 +29,6 @@ import jsprit.core.problem.solution.SolutionCostCalculator;
* Builder that builds a {@link VehicleRoutingAlgorithm}.
*
* @author schroeder
*
*/
public class VehicleRoutingAlgorithmBuilder {
@ -77,7 +76,7 @@ public class VehicleRoutingAlgorithmBuilder {
/**
* Sets custom objective function.
*
* <p/>
* <p>If objective function is not set, a default function is applied (which basically minimizes
* fixed and variable transportation costs ({@link VariablePlusFixedSolutionCostCalculatorFactory}).
*
@ -100,10 +99,9 @@ public class VehicleRoutingAlgorithmBuilder {
/**
* Adds core constraints.
*
* <p/>
* <p>Thus, it adds vehicle-capacity, time-window and skills constraints and their
* required stateUpdater.
*
*/
public void addCoreConstraints() {
addCoreConstraints = true;
@ -115,7 +113,7 @@ public class VehicleRoutingAlgorithmBuilder {
* By default, marginal transportation costs are calculated. Thus when inserting
* act_k between act_i and act_j, marginal (additional) transportation costs
* are basically c(act_i,act_k)+c(act_k,act_j)-c(act_i,act_j).
*
* <p/>
* <p>Do not use this method, if you plan to control the insertion heuristic
* entirely via hard- and soft-constraints.
*/
@ -147,7 +145,7 @@ public class VehicleRoutingAlgorithmBuilder {
/**
* Builds and returns the algorithm.
*
* <p/>
* <p>If algorithmConfigFile is set, it reads the configuration.
*
* @return the algorithm

View file

@ -35,7 +35,7 @@ public class AcceptNewRemoveFirst implements SolutionAcceptor{
/**
* Accepts every solution if solution memory allows. If memory occupied, than accepts new solution only if better than the worst in memory.
* Consequently, the worst solution is removed from solutions, and the new solution added.
*
* <p/>
* <p>Note that this modifies Collection<VehicleRoutingProblemSolution> solutions.
*/
@Override
@ -53,6 +53,4 @@ public class AcceptNewRemoveFirst implements SolutionAcceptor{
}
}

View file

@ -61,7 +61,6 @@ public class ExperimentalSchrimpfAcceptance implements SolutionAcceptor, Iterati
}
@Override
public boolean acceptSolution(Collection<VehicleRoutingProblemSolution> solutions, VehicleRoutingProblemSolution newSolution) {
boolean solutionAccepted = false;
@ -79,8 +78,7 @@ public class ExperimentalSchrimpfAcceptance implements SolutionAcceptor, Iterati
solutions.remove(worst);
solutions.add(newSolution);
solutionAccepted = true;
}
else if(newSolution.getRoutes().size() == worst.getRoutes().size() && newSolution.getCost() < worst.getCost() + threshold){
} else if (newSolution.getRoutes().size() == worst.getRoutes().size() && newSolution.getCost() < worst.getCost() + threshold) {
solutions.remove(worst);
solutions.add(newSolution);
solutionAccepted = true;

View file

@ -23,7 +23,7 @@ import java.util.Collection;
/**
* Acceptor that accepts solutions to be memorized only better solutions.
*
* <p/>
* <p>If there is enough memory, every solution will be accepted. If there is no memory anymore and the solution
* to be evaluated is better than the worst, the worst will be replaced by the new solution.</p>
*/
@ -38,7 +38,7 @@ public class GreedyAcceptance implements SolutionAcceptor{
/**
* Accepts every solution if solution memory allows. If memory occupied, than accepts new solution only if better than the worst in memory.
* Consequently, the worst solution is removed from solutions, and the new solution added.
*
* <p/>
* <p>Note that this modifies Collection<VehicleRoutingProblemSolution> solutions.
*/
@Override
@ -68,6 +68,4 @@ public class GreedyAcceptance implements SolutionAcceptor{
}
}

View file

@ -33,7 +33,7 @@ public class GreedyAcceptance_minVehFirst implements SolutionAcceptor{
/**
* Accepts every solution if solution memory allows. If memory occupied, than accepts new solution only if better than the worst in memory.
* Consequently, the worst solution is removed from solutions, and the new solution added.
*
* <p/>
* <p>Note that this modifies Collection<VehicleRoutingProblemSolution> solutions.
*/
@Override
@ -52,8 +52,7 @@ public class GreedyAcceptance_minVehFirst implements SolutionAcceptor{
solutions.remove(worstSolution);
solutions.add(newSolution);
solutionAccepted = true;
}
else if(newSolution.getRoutes().size() == worstSolution.getRoutes().size() && newSolution.getCost() < worstSolution.getCost()){
} else if (newSolution.getRoutes().size() == worstSolution.getRoutes().size() && newSolution.getCost() < worstSolution.getCost()) {
solutions.remove(worstSolution);
solutions.add(newSolution);
solutionAccepted = true;
@ -68,6 +67,4 @@ public class GreedyAcceptance_minVehFirst implements SolutionAcceptor{
}
}

View file

@ -29,21 +29,21 @@ import java.util.Collection;
/**
* ThresholdAcceptance-Function defined by Schrimpf et al. (2000).
*
* <p/>
* <p>The <b>idea</b> can be described as follows: Most problems do not only have one unique minimum (maximum) but
* a number of local minima (maxima). To avoid to get stuck in a local minimum at the beginning of a search
* this threshold-acceptance function accepts also worse solution at the beginning (in contrary to a greedy
* approach which only accepts better solutions), and converges to a greedy approach at the end. <br>
* The difficulty is to define (i) an appropriate initial threshold and (ii) a corresponding function describing
* how the threshold converges to zero, i.e. the greedy threshold.
*
* <p/>
* <p>ad i) The initial threshold is determined by a random walk through the search space.
* The random walk currently runs with the following algorithm: src/main/resources/randomWalk.xml. It runs
* as long as it is specified in nuOfWarmupIterations. In the first iteration or walk respectively the algorithm generates a solution.
* This solution in turn is the basis of the next walk yielding to another solution value ... and so on.
* Each solution value is memorized since the initial threshold is essentially a function of the standard deviation of these solution values.
* To be more precise: initial threshold = stddev(solution values) / 2.
*
* <p/>
* <p>ad ii) The threshold of iteration i is determined as follows:
* threshold(i) = initialThreshold * Math.exp(-Math.log(2) * (i / nuOfTotalIterations) / alpha)
* To get a better understanding of the threshold-function go to Wolfram Alpha and plot the following line
@ -55,15 +55,13 @@ import java.util.Collection;
* alpha = 0.1<br>
* x corresponds to i iterations and<br>
* y to the threshold(i)
*
* <p/>
* <p>Gerhard Schrimpf, Johannes Schneider, Hermann Stamm- Wilbrandt, and Gunter Dueck (2000).
* Record breaking optimization results using the ruin and recreate principle.
* Journal of Computational Physics, 159(2):139 171, 2000. ISSN 0021-9991. doi: 10.1006/jcph.1999. 6413.
* URL http://www.sciencedirect.com/science/article/ pii/S0021999199964136
*
*
* @author schroeder
*
*/
public class SchrimpfAcceptance implements SolutionAcceptor, IterationStartsListener, AlgorithmStartsListener {
@ -102,8 +100,7 @@ public class SchrimpfAcceptance implements SolutionAcceptor, IterationStartsList
if (worst == null) {
solutions.add(newSolution);
solutionAccepted = true;
}
else if(newSolution.getCost() < worst.getCost() + threshold){
} else if (newSolution.getCost() < worst.getCost() + threshold) {
solutions.remove(worst);
solutions.add(newSolution);
solutionAccepted = true;

View file

@ -1,4 +1,3 @@
/*******************************************************************************
* Copyright (C) 2014 Stefan Schroeder
*
@ -26,15 +25,13 @@ import java.util.Collection;
/**
* Acceptor that decides whether the newSolution is accepted or not.
*
*
* @author stefan
*
*/
public interface SolutionAcceptor {
/**
* Accepts solution or not, and returns true if a new solution has been accepted.
*
* <p/>
* <p>If the solution is accepted, it is added to solutions, i.e. the solutions-collections is modified.
*
* @param solutions collection of existing solutions

View file

@ -26,25 +26,23 @@ import jsprit.core.util.Resource;
import java.net.URL;
/**
* Factory that creates the {@link VehicleRoutingAlgorithm} as proposed by Schrimpf et al., 2000 with the following parameters:
*
* <p>
* <p/>
* <p/>
* R&R_random (prob=0.5, F=0.5);
* R&R_radial (prob=0.5, F=0.3);
* threshold-accepting with exponentialDecayFunction (alpha=0.1, warmup-iterations=100);
* nuOfIterations=2000
*
* <p/>
* <p>Gerhard Schrimpf, Johannes Schneider, Hermann Stamm- Wilbrandt, and Gunter Dueck.
* Record breaking optimization results using the ruin and recreate principle.
* Journal of Computational Physics, 159(2):139 171, 2000. ISSN 0021-9991. doi: 10.1006/jcph.1999. 6413.
* URL http://www.sciencedirect.com/science/article/ pii/S0021999199964136
*
* <p/>
* <p>algorithm-xml-config is available at src/main/resources/schrimpf.xml.
*
* @author stefan schroeder
*
*/
public class GreedySchrimpfFactory {
@ -62,5 +60,4 @@ public class GreedySchrimpfFactory {
}
}

View file

@ -62,8 +62,7 @@ class InsertionNoiseMaker implements SoftActivityConstraint, IterationStartsList
List<Location> locs = new ArrayList<Location>();
if (j instanceof Service) {
locs.add(((Service) j).getLocation());
}
else if(j instanceof Shipment){
} else if (j instanceof Shipment) {
locs.add(((Shipment) j).getPickupLocation());
locs.add(((Shipment) j).getDeliveryLocation());
}
@ -74,8 +73,7 @@ class InsertionNoiseMaker implements SoftActivityConstraint, IterationStartsList
public void informIterationStarts(int i, VehicleRoutingProblem problem, Collection<VehicleRoutingProblemSolution> solutions) {
if (random.nextDouble() < noiseProbability) {
makeNoise = true;
}
else makeNoise = false;
} else makeNoise = false;
}
@Override

View file

@ -245,13 +245,15 @@ public class Jsprit {
}
public RuinShareFactoryImpl(int minShare, int maxShare) {
if(maxShare < minShare) throw new IllegalArgumentException("maxShare must be equal or greater than minShare");
if (maxShare < minShare)
throw new IllegalArgumentException("maxShare must be equal or greater than minShare");
this.minShare = minShare;
this.maxShare = maxShare;
}
public RuinShareFactoryImpl(int minShare, int maxShare, Random random) {
if(maxShare < minShare) throw new IllegalArgumentException("maxShare must be equal or greater than minShare");
if (maxShare < minShare)
throw new IllegalArgumentException("maxShare must be equal or greater than minShare");
this.minShare = minShare;
this.maxShare = maxShare;
this.random = random;
@ -297,8 +299,7 @@ public class Jsprit {
VehicleFleetManager fm;
if (vrp.getFleetSize().equals(VehicleRoutingProblem.FleetSize.INFINITE)) {
fm = new InfiniteFleetManagerFactory(vrp.getVehicles()).createFleetManager();
}
else fm = new FiniteFleetManagerFactory(vrp.getVehicles()).createFleetManager();
} else fm = new FiniteFleetManagerFactory(vrp.getVehicles()).createFleetManager();
if (stateManager == null) {
stateManager = new StateManager(vrp);
@ -356,8 +357,7 @@ public class Jsprit {
if (random.nextDouble() < toDouble(getProperty(Parameter.RUIN_WORST_NOISE_PROB.toString()))) {
return toDouble(getProperty(Parameter.RUIN_WORST_NOISE_LEVEL.toString()))
* noiseMaker.maxCosts * random.nextDouble();
}
else return 0.;
} else return 0.;
}
});
}
@ -392,8 +392,7 @@ public class Jsprit {
scorer = getRegretScorer(vrp);
regretInsertion.setScoringFunction(scorer);
regret = regretInsertion;
}
else {
} else {
RegretInsertion regretInsertion = (RegretInsertion) new InsertionBuilder(vrp, fm, stateManager, constraintManager)
.setInsertionStrategy(InsertionBuilder.Strategy.REGRET)
.setAllowVehicleSwitch(toBoolean(getProperty(Parameter.VEHICLE_SWITCH.toString())))
@ -413,8 +412,7 @@ public class Jsprit {
.setAllowVehicleSwitch(toBoolean(getProperty(Parameter.VEHICLE_SWITCH.toString())))
.build();
best = bestInsertion;
}
else{
} else {
BestInsertionConcurrent bestInsertion = (BestInsertionConcurrent) new InsertionBuilder(vrp, fm, stateManager, constraintManager)
.setInsertionStrategy(InsertionBuilder.Strategy.BEST)
.considerFixedCosts(Double.valueOf(properties.getProperty(Parameter.FIXED_COST_PARAM.toString())))
@ -477,8 +475,7 @@ public class Jsprit {
.withStrategy(clusters_best, toDouble(getProperty(Strategy.CLUSTER_BEST.toString())));
if (getProperty(Parameter.CONSTRUCTION.toString()).equals(Construction.BEST_INSERTION.toString())) {
prettyBuilder.constructInitialSolutionWith(best, objectiveFunction);
}
else{
} else {
prettyBuilder.constructInitialSolutionWith(regret, objectiveFunction);
}

View file

@ -26,25 +26,23 @@ import jsprit.core.util.Resource;
import java.net.URL;
/**
* Factory that creates the {@link VehicleRoutingAlgorithm} as proposed by Schrimpf et al., 2000 with the following parameters:
*
* <p>
* <p/>
* <p/>
* R&R_random (prob=0.5, F=0.5);
* R&R_radial (prob=0.5, F=0.3);
* threshold-accepting with exponentialDecayFunction (alpha=0.1, warmup-iterations=100);
* nuOfIterations=2000
*
* <p/>
* <p>Gerhard Schrimpf, Johannes Schneider, Hermann Stamm- Wilbrandt, and Gunter Dueck.
* Record breaking optimization results using the ruin and recreate principle.
* Journal of Computational Physics, 159(2):139 171, 2000. ISSN 0021-9991. doi: 10.1006/jcph.1999. 6413.
* URL http://www.sciencedirect.com/science/article/ pii/S0021999199964136
*
* <p/>
* <p>algorithm-xml-config is available at src/main/resources/schrimpf.xml.
*
* @author stefan schroeder
*
*/
public class SchrimpfFactory {
@ -62,5 +60,4 @@ public class SchrimpfFactory {
}
}

View file

@ -70,8 +70,7 @@ public class AlgorithmConfigXmlReader {
};
algorithmConfig.getXMLConfiguration().setEntityResolver(resolver);
algorithmConfig.getXMLConfiguration().setSchemaValidation(true);
}
else{
} else {
log.warn("cannot find schema-xsd file (algorithm_xml_schema.xsd). try to read xml without xml-file-validation.");
}
}

View file

@ -56,21 +56,20 @@ class InsertionFactory {
String level = config.getString("level");
if (level.equals("local")) {
iBuilder.setLocalLevel(addDefaultCostCalculators);
}
else if(level.equals("route")){
} else if (level.equals("route")) {
int forwardLooking = 0;
int memory = 1;
String forward = config.getString("level[@forwardLooking]");
String mem = config.getString("level[@memory]");
if (forward != null) forwardLooking = Integer.parseInt(forward);
else log.warn("parameter route[@forwardLooking] is missing. by default it is 0 which equals to local level");
else
log.warn("parameter route[@forwardLooking] is missing. by default it is 0 which equals to local level");
if (mem != null) memory = Integer.parseInt(mem);
else log.warn("parameter route[@memory] is missing. by default it is 1");
iBuilder.setRouteLevel(forwardLooking, memory, addDefaultCostCalculators);
}
else throw new IllegalStateException("level " + level + " is not known. currently it only knows \"local\" or \"route\"");
}
else iBuilder.setLocalLevel(addDefaultCostCalculators);
} else
throw new IllegalStateException("level " + level + " is not known. currently it only knows \"local\" or \"route\"");
} else iBuilder.setLocalLevel(addDefaultCostCalculators);
if (config.containsKey("considerFixedCosts") || config.containsKey("considerFixedCost")) {
if (addDefaultCostCalculators) {
@ -81,14 +80,14 @@ class InsertionFactory {
String weight = config.getString("considerFixedCosts[@weight]");
if (weight == null) weight = config.getString("considerFixedCost[@weight]");
if (weight != null) fixedCostWeight = Double.parseDouble(weight);
else throw new IllegalStateException("fixedCostsParameter 'weight' must be set, e.g. <considerFixedCosts weight=1.0>true</considerFixedCosts>.\n" +
else
throw new IllegalStateException("fixedCostsParameter 'weight' must be set, e.g. <considerFixedCosts weight=1.0>true</considerFixedCosts>.\n" +
"this has to be changed in algorithm-config-xml-file.");
iBuilder.considerFixedCosts(fixedCostWeight);
}
else if(val.equals("false")){
} else if (val.equals("false")) {
}
else throw new IllegalStateException("considerFixedCosts must either be true or false, i.e. <considerFixedCosts weight=1.0>true</considerFixedCosts> or \n<considerFixedCosts weight=1.0>false</considerFixedCosts>. " +
} else
throw new IllegalStateException("considerFixedCosts must either be true or false, i.e. <considerFixedCosts weight=1.0>true</considerFixedCosts> or \n<considerFixedCosts weight=1.0>false</considerFixedCosts>. " +
"if latter, you can also omit the tag. this has to be changed in algorithm-config-xml-file");
}
}
@ -106,8 +105,7 @@ class InsertionFactory {
iBuilder.setInsertionStrategy(InsertionBuilder.Strategy.REGRET);
}
return iBuilder.build();
}
else throw new IllegalStateException("cannot create insertionStrategy, since it has no name.");
} else throw new IllegalStateException("cannot create insertionStrategy, since it has no name.");
}

View file

@ -151,7 +151,6 @@ public class VehicleRoutingAlgorithms {
}
@Override
public Class<SolutionSelector> getType() {
return SolutionSelector.class;
@ -195,7 +194,6 @@ public class VehicleRoutingAlgorithms {
}
@Override
public Class<SearchStrategyModule> getType() {
return SearchStrategyModule.class;
@ -239,7 +237,6 @@ public class VehicleRoutingAlgorithms {
}
@Override
public Class<RuinStrategy> getType() {
return RuinStrategy.class;
@ -283,7 +280,6 @@ public class VehicleRoutingAlgorithms {
}
@Override
public Class<InsertionStrategy> getType() {
return InsertionStrategy.class;
@ -325,6 +321,7 @@ public class VehicleRoutingAlgorithms {
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
@ -351,7 +348,8 @@ public class VehicleRoutingAlgorithms {
private static Logger log = LogManager.getLogger(VehicleRoutingAlgorithms.class.getName());
private VehicleRoutingAlgorithms(){}
private VehicleRoutingAlgorithms() {
}
/**
* Creates a {@link jsprit.core.algorithm.VehicleRoutingAlgorithm} from a AlgorithConfig based on the input vrp.
@ -363,6 +361,7 @@ public class VehicleRoutingAlgorithms {
public static VehicleRoutingAlgorithm createAlgorithm(final VehicleRoutingProblem vrp, final AlgorithmConfig algorithmConfig) {
return createAlgo(vrp, algorithmConfig.getXMLConfiguration(), 0, null);
}
public static VehicleRoutingAlgorithm createAlgorithm(final VehicleRoutingProblem vrp, int nThreads, final AlgorithmConfig algorithmConfig) {
return createAlgo(vrp, algorithmConfig.getXMLConfiguration(), nThreads, null);
}
@ -380,6 +379,7 @@ public class VehicleRoutingAlgorithms {
xmlReader.read(configURL);
return createAlgo(vrp, algorithmConfig.getXMLConfiguration(), 0, null);
}
public static VehicleRoutingAlgorithm readAndCreateAlgorithm(final VehicleRoutingProblem vrp, int nThreads, final URL configURL) {
AlgorithmConfig algorithmConfig = new AlgorithmConfig();
AlgorithmConfigXmlReader xmlReader = new AlgorithmConfigXmlReader(algorithmConfig);
@ -459,8 +459,7 @@ public class VehicleRoutingAlgorithms {
final StateManager stateManager;
if (stateMan != null) {
stateManager = stateMan;
}
else{
} else {
stateManager = new StateManager(vrp);
}
stateManager.updateLoadStates();
@ -529,8 +528,7 @@ public class VehicleRoutingAlgorithms {
}
}
});
}
else executorService = null;
} else executorService = null;
//create fleetmanager
@ -540,8 +538,7 @@ public class VehicleRoutingAlgorithms {
final boolean switchAllowed;
if (switchString != null) {
switchAllowed = Boolean.parseBoolean(switchString);
}
else switchAllowed = true;
} else switchAllowed = true;
ActivityTimeTracker.ActivityPolicy activityPolicy;
if (stateManager.timeWindowUpdateIsActivated()) {
UpdateVehicleDependentPracticalTimeWindows timeWindowUpdater = new UpdateVehicleDependentPracticalTimeWindows(stateManager, vrp.getTransportCosts());
@ -564,8 +561,7 @@ public class VehicleRoutingAlgorithms {
});
stateManager.addStateUpdater(timeWindowUpdater);
activityPolicy = ActivityTimeTracker.ActivityPolicy.AS_SOON_AS_TIME_WINDOW_OPENS;
}
else{
} else {
activityPolicy = ActivityTimeTracker.ActivityPolicy.AS_SOON_AS_ARRIVED;
}
stateManager.addStateUpdater(new UpdateActivityTimes(vrp.getTransportCosts(), activityPolicy));
@ -578,7 +574,8 @@ public class VehicleRoutingAlgorithms {
PrettyAlgorithmBuilder prettyAlgorithmBuilder = PrettyAlgorithmBuilder.newInstance(vrp, vehicleFleetManager, stateManager, constraintManager);
//construct initial solution creator
final InsertionStrategy initialInsertionStrategy = createInitialSolution(config, vrp, vehicleFleetManager, stateManager, algorithmListeners, definedClasses, executorService, nuOfThreads, costCalculator, constraintManager, addDefaultCostCalculators);
if(initialInsertionStrategy != null) prettyAlgorithmBuilder.constructInitialSolutionWith(initialInsertionStrategy,costCalculator);
if (initialInsertionStrategy != null)
prettyAlgorithmBuilder.constructInitialSolutionWith(initialInsertionStrategy, costCalculator);
//construct algorithm, i.e. search-strategies and its modules
int solutionMemory = config.getInt("strategy.memory");
@ -605,7 +602,8 @@ public class VehicleRoutingAlgorithms {
//define prematureBreak
PrematureAlgorithmTermination prematureAlgorithmTermination = getPrematureTermination(config, algorithmListeners);
if(prematureAlgorithmTermination != null) metaAlgorithm.setPrematureAlgorithmTermination(prematureAlgorithmTermination);
if (prematureAlgorithmTermination != null)
metaAlgorithm.setPrematureAlgorithmTermination(prematureAlgorithmTermination);
else {
List<HierarchicalConfiguration> terminationCriteria = config.configurationsAt("terminationCriteria.termination");
for (HierarchicalConfiguration terminationConfig : terminationCriteria) {
@ -634,8 +632,7 @@ public class VehicleRoutingAlgorithms {
if (vrp.getFleetSize().equals(FleetSize.INFINITE)) {
return new InfiniteFleetManagerFactory(vrp.getVehicles()).createFleetManager();
}
else if(vrp.getFleetSize().equals(FleetSize.FINITE)){
} else if (vrp.getFleetSize().equals(FleetSize.FINITE)) {
return new FiniteFleetManagerFactory(vrp.getVehicles()).createFleetManager();
}
throw new IllegalStateException("fleet size can only be infinite or finite. " +
@ -716,7 +713,8 @@ public class VehicleRoutingAlgorithms {
throw new IllegalStateException("prematureBreak basedOn " + basedOn + " is not defined");
}
private static String getName(HierarchicalConfiguration strategyConfig) { if(strategyConfig.containsKey("[@name]")){
private static String getName(HierarchicalConfiguration strategyConfig) {
if (strategyConfig.containsKey("[@name]")) {
return strategyConfig.getString("[@name]");
}
return "";
@ -746,7 +744,8 @@ public class VehicleRoutingAlgorithms {
private static SolutionSelector getSelector(HierarchicalConfiguration strategyConfig, VehicleRoutingProblem vrp, Set<PrioritizedVRAListener> algorithmListeners, TypedMap definedSelectors) {
String selectorName = strategyConfig.getString("selector[@name]");
if(selectorName == null) throw new IllegalStateException("no solutionSelector defined. define either \"selectRandomly\" or \"selectBest\"");
if (selectorName == null)
throw new IllegalStateException("no solutionSelector defined. define either \"selectRandomly\" or \"selectBest\"");
String selectorId = strategyConfig.getString("selector[@id]");
if (selectorId == null) selectorId = "noId";
ModKey modKey = makeKey(selectorName, selectorId);
@ -807,8 +806,7 @@ public class VehicleRoutingAlgorithms {
if (nuWarmupIterations != null) {
SchrimpfInitialThresholdGenerator iniThresholdGenerator = new SchrimpfInitialThresholdGenerator(schrimpf, Integer.parseInt(nuWarmupIterations));
algorithmListeners.add(new PrioritizedVRAListener(Priority.LOW, iniThresholdGenerator));
}
else{
} else {
double threshold = strategyConfig.getDouble("acceptor.initialThreshold");
schrimpf.setInitialThreshold(threshold);
}
@ -823,8 +821,7 @@ public class VehicleRoutingAlgorithms {
algorithmListeners.add(new PrioritizedVRAListener(Priority.LOW, schrimpf));
typedMap.put(acceptorKey, schrimpf);
return schrimpf;
}
else{
} else {
throw new IllegalStateException("solution acceptor " + acceptorName + " is not known");
}
}
@ -852,15 +849,15 @@ public class VehicleRoutingAlgorithms {
ModKey ruinKey = makeKey(ruin_name, ruin_id);
if (ruin_name.equals("randomRuin")) {
ruin = getRandomRuin(vrp, routeStates, definedClasses, ruinKey, shareToRuin);
}
else if(ruin_name.equals("radialRuin")){
} else if (ruin_name.equals("radialRuin")) {
JobDistance jobDistance = new AvgServiceAndShipmentDistance(vrp.getTransportCosts());
ruin = getRadialRuin(vrp, routeStates, definedClasses, ruinKey, shareToRuin, jobDistance);
}
else throw new IllegalStateException("ruin[@name] " + ruin_name + " is not known. Use either randomRuin or radialRuin.");
} else
throw new IllegalStateException("ruin[@name] " + ruin_name + " is not known. Use either randomRuin or radialRuin.");
String insertionName = moduleConfig.getString("insertion[@name]");
if(insertionName == null) throw new IllegalStateException("module.insertion[@name] is missing. set it to \"regretInsertion\" or \"bestInsertion\"");
if (insertionName == null)
throw new IllegalStateException("module.insertion[@name] is missing. set it to \"regretInsertion\" or \"bestInsertion\"");
String insertionId = moduleConfig.getString("insertion[@id]");
if (insertionId == null) insertionId = "noId";
ModKey insertionKey = makeKey(insertionName, insertionId);
@ -911,6 +908,4 @@ public class VehicleRoutingAlgorithms {
}
}

View file

@ -22,8 +22,6 @@ import jsprit.core.problem.solution.VehicleRoutingProblemSolution;
import java.util.Collection;
public interface AlgorithmEndsListener extends VehicleRoutingAlgorithmListener {
void informAlgorithmEnds(VehicleRoutingProblem problem, Collection<VehicleRoutingProblemSolution> solutions);

View file

@ -23,8 +23,6 @@ import jsprit.core.problem.solution.VehicleRoutingProblemSolution;
import java.util.Collection;
public interface AlgorithmStartsListener extends VehicleRoutingAlgorithmListener {
void informAlgorithmStarts(VehicleRoutingProblem problem, VehicleRoutingAlgorithm algorithm, Collection<VehicleRoutingProblemSolution> solutions);

View file

@ -22,9 +22,6 @@ import jsprit.core.problem.solution.VehicleRoutingProblemSolution;
import java.util.Collection;
public interface IterationEndsListener extends VehicleRoutingAlgorithmListener {
public void informIterationEnds(int i, VehicleRoutingProblem problem, Collection<VehicleRoutingProblemSolution> solutions);

View file

@ -22,8 +22,6 @@ import jsprit.core.problem.solution.VehicleRoutingProblemSolution;
import java.util.Collection;
public interface IterationStartsListener extends VehicleRoutingAlgorithmListener {
public void informIterationStarts(int i, VehicleRoutingProblem problem, Collection<VehicleRoutingProblemSolution> solutions);

View file

@ -23,8 +23,6 @@ import jsprit.core.problem.solution.VehicleRoutingProblemSolution;
import java.util.Collection;
public interface StrategySelectedListener extends VehicleRoutingAlgorithmListener {
void informSelectedStrategy(SearchStrategy.DiscoveredSolution discoveredSolution, VehicleRoutingProblem vehicleRoutingProblem, Collection<VehicleRoutingProblemSolution> vehicleRoutingProblemSolutions);

View file

@ -24,22 +24,23 @@ import jsprit.core.problem.solution.VehicleRoutingProblemSolution;
import java.util.*;
public class VehicleRoutingAlgorithmListeners {
public static class PrioritizedVRAListener {
Priority priority;
VehicleRoutingAlgorithmListener l;
public PrioritizedVRAListener(Priority priority, VehicleRoutingAlgorithmListener l) {
super();
this.priority = priority;
this.l = l;
}
public Priority getPriority() {
return priority;
}
public VehicleRoutingAlgorithmListener getListener() {
return l;
}
@ -89,14 +90,11 @@ public class VehicleRoutingAlgorithmListeners {
if (o1 == o2) return 0;
if (o1.getPriority() == Priority.HIGH && o2.getPriority() != Priority.HIGH) {
return -1;
}
else if(o2.getPriority() == Priority.HIGH && o1.getPriority() != Priority.HIGH){
} else if (o2.getPriority() == Priority.HIGH && o1.getPriority() != Priority.HIGH) {
return 1;
}
else if(o1.getPriority() == Priority.MEDIUM && o2.getPriority() != Priority.MEDIUM){
} else if (o1.getPriority() == Priority.MEDIUM && o2.getPriority() != Priority.MEDIUM) {
return -1;
}
else if(o2.getPriority() == Priority.MEDIUM && o1.getPriority() != Priority.MEDIUM){
} else if (o2.getPriority() == Priority.MEDIUM && o1.getPriority() != Priority.MEDIUM) {
return 1;
}
return 1;
@ -114,7 +112,9 @@ public class VehicleRoutingAlgorithmListeners {
public void remove(PrioritizedVRAListener listener) {
boolean removed = algorithmListeners.remove(listener);
if(!removed){ throw new IllegalStateException("cannot remove listener"); }
if (!removed) {
throw new IllegalStateException("cannot remove listener");
}
}
public void addListener(VehicleRoutingAlgorithmListener listener, Priority priority) {
@ -143,7 +143,6 @@ public class VehicleRoutingAlgorithmListeners {
}
public void iterationStarts(int i, VehicleRoutingProblem problem, Collection<VehicleRoutingProblemSolution> solutions) {
for (PrioritizedVRAListener l : algorithmListeners) {
if (l.getListener() instanceof IterationStartsListener) {
@ -153,7 +152,6 @@ public class VehicleRoutingAlgorithmListeners {
}
public void algorithmStarts(VehicleRoutingProblem problem, VehicleRoutingAlgorithm algorithm, Collection<VehicleRoutingProblemSolution> solutions) {
for (PrioritizedVRAListener l : algorithmListeners) {
if (l.getListener() instanceof AlgorithmStartsListener) {

View file

@ -1,4 +1,3 @@
/*******************************************************************************
* Copyright (C) 2014 Stefan Schroeder
*
@ -27,17 +26,20 @@ public interface ActivityInsertionCostsCalculator {
private double additionalCosts;
private double additionalTime;
public ActivityInsertionCosts(double additionalCosts, double additionalTime) {
super();
this.additionalCosts = additionalCosts;
this.additionalTime = additionalTime;
}
/**
* @return the additionalCosts
*/
public double getAdditionalCosts() {
return additionalCosts;
}
/**
* @return the additionalTime
*/
@ -46,7 +48,6 @@ public interface ActivityInsertionCostsCalculator {
}
}
public double getCosts(JobInsertionContext iContext, TourActivity prevAct, TourActivity nextAct, TourActivity newAct, double depTimeAtPrevAct);

View file

@ -25,11 +25,10 @@ import jsprit.core.problem.vehicle.Vehicle;
/**
* Estimates additional access/egress costs when operating route with a new vehicle that has different start/end-location.
*
* <p/>
* <p>If two vehicles have the same start/end-location and departure-time .getCosts(...) must return zero.
*
* @author schroeder
*
*/
class AdditionalAccessEgressCalculator {
@ -37,11 +36,10 @@ class AdditionalAccessEgressCalculator {
/**
* Constructs the estimator that estimates additional access/egress costs when operating route with a new vehicle that has different start/end-location.
*
* <p/>
* <p>If two vehicles have the same start/end-location and departure-time .getCosts(...) must return zero.
*
* @author schroeder
*
*/
public AdditionalAccessEgressCalculator(VehicleRoutingTransportCosts routingCosts) {
this.routingCosts = routingCosts;

View file

@ -27,7 +27,6 @@ import java.util.Iterator;
import java.util.List;
final class AuxilliaryCostCalculator {
private final VehicleRoutingTransportCosts routingCosts;
@ -41,7 +40,6 @@ final class AuxilliaryCostCalculator {
}
/**
*
* @param path activity path to get the costs for
* @param depTime departure time at first activity in path
* @param driver driver of vehicle

View file

@ -30,13 +30,10 @@ import java.util.Collections;
import java.util.List;
/**
* Best insertion that insert the job where additional costs are minimal.
*
* @author stefan schroeder
*
*/
public final class BestInsertion extends AbstractInsertionStrategy {

View file

@ -77,7 +77,9 @@ public class BestInsertionBuilder {
this.forwaredLooking = forwardLooking;
this.memory = memory;
return this;
};
}
;
public BestInsertionBuilder setRouteLevel(int forwardLooking, int memory, boolean addDefaultMarginalCostCalculation) {
local = false;
@ -85,12 +87,16 @@ public class BestInsertionBuilder {
this.memory = memory;
this.addDefaultCostCalc = addDefaultMarginalCostCalculation;
return this;
};
}
;
public BestInsertionBuilder setLocalLevel() {
local = true;
return this;
};
}
;
/**
* If addDefaulMarginalCostCalculation is false, no calculator is set which implicitly assumes that marginal cost calculation
@ -114,7 +120,9 @@ public class BestInsertionBuilder {
public BestInsertionBuilder setActivityInsertionCostCalculator(ActivityInsertionCostsCalculator activityInsertionCostsCalculator) {
this.actInsertionCostsCalculator = activityInsertionCostsCalculator;
return this;
};
}
;
public BestInsertionBuilder setConcurrentMode(ExecutorService executor, int nuOfThreads) {
this.executor = executor;
@ -129,8 +137,7 @@ public class BestInsertionBuilder {
JobInsertionCostsCalculatorBuilder calcBuilder = new JobInsertionCostsCalculatorBuilder(iListeners, algorithmListeners);
if (local) {
calcBuilder.setLocalLevel(addDefaultCostCalc);
}
else {
} else {
calcBuilder.setRouteLevel(forwaredLooking, memory, addDefaultCostCalc);
}
calcBuilder.setConstraintManager(constraintManager);
@ -149,8 +156,7 @@ public class BestInsertionBuilder {
InsertionStrategy bestInsertion;
if (executor == null) {
bestInsertion = new BestInsertion(jobInsertions, vrp);
}
else{
} else {
bestInsertion = new BestInsertionConcurrent(jobInsertions, executor, nuOfThreads, vrp);
}
for (InsertionListener l : iListeners) bestInsertion.addListener(l);
@ -158,9 +164,9 @@ public class BestInsertionBuilder {
}
/**
* @deprecated this is experimental and can disappear.
* @param timeSlice the time slice
* @param nNeighbors number of neighbors
* @deprecated this is experimental and can disappear.
*/
@Deprecated
public void experimentalTimeScheduler(double timeSlice, int nNeighbors) {
@ -174,6 +180,4 @@ public class BestInsertionBuilder {
}
}

View file

@ -30,12 +30,8 @@ import java.util.*;
import java.util.concurrent.*;
/**
*
* @author stefan schroeder
*
*/
public final class BestInsertionConcurrent extends AbstractInsertionStrategy {
@ -133,8 +129,7 @@ public final class BestInsertionConcurrent extends AbstractInsertionStrategy{
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
catch (ExecutionException e) {
} catch (ExecutionException e) {
e.printStackTrace();
logger.error("Exception", e);
System.exit(1);
@ -180,8 +175,7 @@ public final class BestInsertionConcurrent extends AbstractInsertionStrategy{
for (int i = 0; i < nOfNewRoutes; i++) {
vehicleRoutes.add(VehicleRoute.emptyRoute());
}
}
else{
} else {
vehicleRoutes.add(VehicleRoute.emptyRoute());
}
/*

View file

@ -20,10 +20,12 @@ class CalculatesServiceInsertionWithTimeScheduling implements JobInsertionCostsC
public static class KnowledgeInjection implements InsertionStartsListener {
private CalculatesServiceInsertionWithTimeScheduling c;
public KnowledgeInjection(CalculatesServiceInsertionWithTimeScheduling c) {
super();
this.c = c;
}
@Override
public void informInsertionStarts(Collection<VehicleRoute> vehicleRoutes, Collection<Job> unassignedJobs) {
List<Double> knowledge = new ArrayList<Double>();
@ -70,8 +72,7 @@ class CalculatesServiceInsertionWithTimeScheduling implements JobInsertionCostsC
if (!departureTimeKnowledge.isEmpty()) {
departureTime = departureTimeKnowledge.get(random.nextInt(departureTimeKnowledge.size()));
}
}
else if(!currentRoute.getVehicle().getId().equals(newVehicle.getId())){
} else if (!currentRoute.getVehicle().getId().equals(newVehicle.getId())) {
departureTime = currentRoute.getDepartureTime();
}

View file

@ -57,8 +57,7 @@ class CalculatesServiceInsertionWithTimeSchedulingInSlices implements JobInserti
double currentStart;
if (currentRoute.getStart() == null) {
currentStart = newVehicleDepartureTime;
}
else currentStart = currentRoute.getStart().getEndTime();
} else currentStart = currentRoute.getStart().getEndTime();
vehicleDepartureTimes.add(currentStart);
// double earliestDeparture = newVehicle.getEarliestDeparture();

View file

@ -75,8 +75,7 @@ class Inserter {
}
TourActivity activity = vehicleRoutingProblem.copyAndGetActivities(job).get(0);
route.getTourActivities().addActivity(iData.getDeliveryInsertionIndex(), activity);
}
else delegator.handleJobInsertion(job, iData, route);
} else delegator.handleJobInsertion(job, iData, route);
}
private void setEndLocation(VehicleRoute route, Service service) {
@ -115,8 +114,7 @@ class Inserter {
}
route.getTourActivities().addActivity(iData.getDeliveryInsertionIndex(), deliverShipment);
route.getTourActivities().addActivity(iData.getPickupInsertionIndex(), pickupShipment);
}
else delegator.handleJobInsertion(job, iData, route);
} else delegator.handleJobInsertion(job, iData, route);
}
private void setEndLocation(VehicleRoute route, Shipment shipment) {
@ -145,7 +143,8 @@ class Inserter {
public void insertJob(Job job, InsertionData insertionData, VehicleRoute vehicleRoute) {
insertionListeners.informBeforeJobInsertion(job, insertionData, vehicleRoute);
if(insertionData == null || (insertionData instanceof NoInsertionFound)) throw new IllegalStateException("insertionData null. cannot insert job.");
if (insertionData == null || (insertionData instanceof NoInsertionFound))
throw new IllegalStateException("insertionData null. cannot insert job.");
if (job == null) throw new IllegalStateException("cannot insert null-job");
if (!(vehicleRoute.getVehicle().getId().equals(insertionData.getSelectedVehicle().getId()))) {
insertionListeners.informVehicleSwitched(vehicleRoute, vehicleRoute.getVehicle(), insertionData.getSelectedVehicle());

View file

@ -140,8 +140,7 @@ public class InsertionBuilder {
JobInsertionCostsCalculatorBuilder calcBuilder = new JobInsertionCostsCalculatorBuilder(iListeners, algorithmListeners);
if (local) {
calcBuilder.setLocalLevel(addDefaultCostCalc);
}
else {
} else {
calcBuilder.setRouteLevel(forwaredLooking, memory, addDefaultCostCalc);
}
calcBuilder.setConstraintManager(constraintManager);
@ -165,24 +164,21 @@ public class InsertionBuilder {
} else {
insertion = new BestInsertionConcurrent(costCalculator, executor, nuOfThreads, vrp);
}
}
else if(strategy.equals(Strategy.REGRET)){
} else if (strategy.equals(Strategy.REGRET)) {
if (executor == null) {
insertion = new RegretInsertion(costCalculator, vrp);
}
else {
} else {
insertion = new RegretInsertionConcurrent(costCalculator, vrp, executor);
}
}
else throw new IllegalStateException("you should never get here");
} else throw new IllegalStateException("you should never get here");
for (InsertionListener l : iListeners) insertion.addListener(l);
return insertion;
}
/**
* @deprecated this is experimental and can disappear.
* @param timeSlice the time slice
* @param nNeighbors number of neighbors
* @deprecated this is experimental and can disappear.
*/
@Deprecated
public void experimentalTimeScheduler(double timeSlice, int nNeighbors) {
@ -197,6 +193,4 @@ public class InsertionBuilder {
}
}

View file

@ -27,7 +27,6 @@ import java.util.List;
* and departureTime of vehicle at vehicle's start location (e.g. depot).
*
* @author stefan
*
*/
public class InsertionData {
@ -162,5 +161,4 @@ public class InsertionData {
}
}

View file

@ -23,18 +23,17 @@ import jsprit.core.problem.solution.route.VehicleRoute;
import java.util.Collection;
/**
* Basic interface for insertion strategies
*
* @author stefan schroeder
*
*/
public interface InsertionStrategy {
/**
* Inserts unassigned jobs into vehicle routes.
*
* @param vehicleRoutes existing vehicle routes
* @param unassignedJobs jobs to be inserted
*/

View file

@ -32,8 +32,6 @@ import java.util.ArrayList;
import java.util.List;
public class JobInsertionCostsCalculatorBuilder {
private static class CalculatorPlusListeners {
@ -97,7 +95,7 @@ public class JobInsertionCostsCalculatorBuilder {
/**
* Constructs the builder.
*
* <p/>
* <p>Some calculators require information from the overall algorithm or the higher-level insertion procedure. Thus listeners inform them.
* These listeners are cached in the according list and can thus be added when its time to add them.
*
@ -112,8 +110,8 @@ public class JobInsertionCostsCalculatorBuilder {
/**
* Sets activityStates. MUST be set.
* @param stateManager
*
* @param stateManager
* @return
*/
public JobInsertionCostsCalculatorBuilder setStateManager(RouteAndActivityStateGetter stateManager) {
@ -145,8 +143,9 @@ public class JobInsertionCostsCalculatorBuilder {
/**
* Sets a flag to build a calculator based on local calculations.
*
* <p/>
* <p>Insertion of a job and job-activity is evaluated based on the previous and next activity.
*
* @param addDefaultCostCalc
*/
public JobInsertionCostsCalculatorBuilder setLocalLevel(boolean addDefaultCostCalc) {
@ -200,15 +199,17 @@ public class JobInsertionCostsCalculatorBuilder {
* @throws IllegalStateException if vrp == null or activityStates == null or fleetManager == null.
*/
public JobInsertionCostsCalculator build() {
if(vrp == null) throw new IllegalStateException("vehicle-routing-problem is null, but it must be set (this.setVehicleRoutingProblem(vrp))");
if(states == null) throw new IllegalStateException("states is null, but is must be set (this.setStateManager(states))");
if(fleetManager == null) throw new IllegalStateException("fleetManager is null, but it must be set (this.setVehicleFleetManager(fleetManager))");
if (vrp == null)
throw new IllegalStateException("vehicle-routing-problem is null, but it must be set (this.setVehicleRoutingProblem(vrp))");
if (states == null)
throw new IllegalStateException("states is null, but is must be set (this.setStateManager(states))");
if (fleetManager == null)
throw new IllegalStateException("fleetManager is null, but it must be set (this.setVehicleFleetManager(fleetManager))");
JobInsertionCostsCalculator baseCalculator = null;
CalculatorPlusListeners standardLocal = null;
if (local) {
standardLocal = createStandardLocal(vrp, states);
}
else{
} else {
checkServicesOnly();
standardLocal = createStandardRoute(vrp, states, forwardLooking, memory);
}
@ -261,8 +262,7 @@ public class JobInsertionCostsCalculatorBuilder {
ActivityInsertionCostsCalculator actInsertionCalc;
if (activityInsertionCostCalculator == null && addDefaultCostCalc) {
actInsertionCalc = new LocalActivityInsertionCostsCalculator(vrp.getTransportCosts(), vrp.getActivityCosts());
}
else if(activityInsertionCostCalculator == null && !addDefaultCostCalc){
} else if (activityInsertionCostCalculator == null && !addDefaultCostCalc) {
actInsertionCalc = new ActivityInsertionCostsCalculator() {
@Override
@ -272,8 +272,7 @@ public class JobInsertionCostsCalculatorBuilder {
}
};
}
else{
} else {
actInsertionCalc = activityInsertionCostCalculator;
}
@ -313,8 +312,7 @@ public class JobInsertionCostsCalculatorBuilder {
RouteLevelActivityInsertionCostsEstimator routeLevelActivityInsertionCostsEstimator = new RouteLevelActivityInsertionCostsEstimator(vrp.getTransportCosts(), vrp.getActivityCosts(), activityStates2);
routeLevelActivityInsertionCostsEstimator.setForwardLooking(forwardLooking);
routeLevelCostEstimator = routeLevelActivityInsertionCostsEstimator;
}
else if(activityInsertionCostCalculator == null && !addDefaultCostCalc){
} else if (activityInsertionCostCalculator == null && !addDefaultCostCalc) {
routeLevelCostEstimator = new ActivityInsertionCostsCalculator() {
final ActivityInsertionCosts noInsertionCosts = new ActivityInsertionCosts(0., 0.);
@ -326,8 +324,7 @@ public class JobInsertionCostsCalculatorBuilder {
}
};
}
else{
} else {
routeLevelCostEstimator = activityInsertionCostCalculator;
}
ServiceInsertionOnRouteLevelCalculator jobInsertionCalculator = new ServiceInsertionOnRouteLevelCalculator(vrp.getTransportCosts(), vrp.getActivityCosts(), routeLevelCostEstimator, constraintManager, constraintManager);

View file

@ -1,4 +1,3 @@
/*******************************************************************************
* Copyright (C) 2014 Stefan Schroeder
*
@ -29,11 +28,10 @@ import jsprit.core.util.CalculationUtils;
* Calculates activity insertion costs locally, i.e. by comparing the additional costs of insertion the new activity k between
* activity i (prevAct) and j (nextAct).
* Additional costs are then basically calculated as delta c = c_ik + c_kj - c_ij.
*
* <p/>
* <p>Note once time has an effect on costs this class requires activity endTimes.
*
* @author stefan
*
*/
class LocalActivityInsertionCostsCalculator implements ActivityInsertionCostsCalculator {
@ -76,8 +74,7 @@ class LocalActivityInsertionCostsCalculator implements ActivityInsertionCostsCal
double arrTime_nextAct = routingCosts.getTransportTime(prevAct.getLocation(), nextAct.getLocation(), depTimeAtPrevAct, iFacts.getNewDriver(), iFacts.getNewVehicle());
double actCost_nextAct = activityCosts.getActivityCost(nextAct, arrTime_nextAct, iFacts.getNewDriver(), iFacts.getNewVehicle());
oldCosts = tp_costs_prevAct_nextAct + actCost_nextAct;
}
else{
} else {
double tp_costs_prevAct_nextAct = routingCosts.getTransportCost(prevAct.getLocation(), nextAct.getLocation(), prevAct.getEndTime(), iFacts.getRoute().getDriver(), iFacts.getRoute().getVehicle());
double arrTime_nextAct = routingCosts.getTransportTime(prevAct.getLocation(), nextAct.getLocation(), prevAct.getEndTime(), iFacts.getRoute().getDriver(), iFacts.getRoute().getVehicle());
double actCost_nextAct = activityCosts.getActivityCost(nextAct, arrTime_nextAct, iFacts.getRoute().getDriver(), iFacts.getRoute().getVehicle());

View file

@ -32,14 +32,13 @@ import java.util.List;
/**
* Insertion based on regret approach.
*
* <p/>
* <p>Basically calculates the insertion cost of the firstBest and the secondBest alternative. The score is then calculated as difference
* between secondBest and firstBest, plus additional scoring variables that can defined in this.ScoringFunction.
* The idea is that if the cost of the secondBest alternative is way higher than the first best, it seems to be important to insert this
* customer immediatedly. If difference is not that high, it might not impact solution if this customer is inserted later.
*
* @author stefan schroeder
*
*/
public class RegretInsertion extends AbstractInsertionStrategy {
@ -96,7 +95,6 @@ public class RegretInsertion extends AbstractInsertionStrategy {
* Scorer to include other impacts on score such as time-window length or distance to depot.
*
* @author schroeder
*
*/
static interface ScoringFunction {
@ -106,11 +104,10 @@ public class RegretInsertion extends AbstractInsertionStrategy {
/**
* Scorer that includes the length of the time-window when scoring a job. The wider the time-window, the lower the score.
*
* <p/>
* <p>This is the default scorer, i.e.: score = (secondBest - firstBest) + this.TimeWindowScorer.score(job)
*
* @author schroeder
*
*/
public static class DefaultScorer implements ScoringFunction {
@ -126,20 +123,22 @@ public class RegretInsertion extends AbstractInsertionStrategy {
this.vrp = vrp;
}
public void setTimeWindowParam(double tw_param){ this.tw_param = tw_param; }
public void setTimeWindowParam(double tw_param) {
this.tw_param = tw_param;
}
public void setDepotDistanceParam(double depotDistance_param){ this.depotDistance_param = depotDistance_param; }
public void setDepotDistanceParam(double depotDistance_param) {
this.depotDistance_param = depotDistance_param;
}
@Override
public double score(InsertionData best, Job job) {
double score;
if (job instanceof Service) {
score = scoreService(best, job);
}
else if(job instanceof Shipment){
} else if (job instanceof Shipment) {
score = scoreShipment(best, job);
}
else throw new IllegalStateException("not supported");
} else throw new IllegalStateException("not supported");
return score;
}
@ -189,7 +188,7 @@ public class RegretInsertion extends AbstractInsertionStrategy {
/**
* Sets the scoring function.
*
* <p/>
* <p>By default, the this.TimeWindowScorer is used.
*
* @param scoringFunction to score
@ -214,9 +213,8 @@ public class RegretInsertion extends AbstractInsertionStrategy {
/**
* Runs insertion.
*
* <p/>
* <p>Before inserting a job, all unassigned jobs are scored according to its best- and secondBest-insertion plus additional scoring variables.
*
*/
@Override
public Collection<Job> insertUnassignedJobs(Collection<VehicleRoute> routes, Collection<Job> unassignedJobs) {
@ -305,8 +303,7 @@ public class RegretInsertion extends AbstractInsertionStrategy {
ScoredJob scoredJob;
if (bestRoute == emptyRoute) {
scoredJob = new ScoredJob(unassignedJob, score, best, bestRoute, true);
}
else scoredJob = new ScoredJob(unassignedJob, score, best, bestRoute, false);
} else scoredJob = new ScoredJob(unassignedJob, score, best, bestRoute, false);
return scoredJob;
}
@ -320,8 +317,7 @@ public class RegretInsertion extends AbstractInsertionStrategy {
//if only one vehicle, I want the job to be inserted with min iCosts
//if there are more vehicles, I want this job to be prioritized since there are no alternatives
score = Integer.MAX_VALUE - best.getInsertionCost() + scoringFunction.score(best, unassignedJob);
}
else{
} else {
score = (secondBest.getInsertionCost() - best.getInsertionCost()) + scoringFunction.score(best, unassignedJob);
}
return score;

View file

@ -1,4 +1,3 @@
/*******************************************************************************
* Copyright (C) 2014 Stefan Schroeder
*
@ -52,11 +51,15 @@ class RouteLevelActivityInsertionCostsEstimator implements ActivityInsertionCost
@Override
public double getCosts(JobInsertionContext iFacts, TourActivity prevAct, TourActivity nextAct, TourActivity newAct, double depTimeAtPrevAct) {
List<TourActivity> path = new ArrayList<TourActivity>();
path.add(prevAct); path.add(newAct); path.add(nextAct);
path.add(prevAct);
path.add(newAct);
path.add(nextAct);
int actIndex;
if (prevAct instanceof Start) actIndex = 0;
else actIndex = iFacts.getRoute().getTourActivities().getActivities().indexOf(nextAct);
if(nuOfActivities2LookForward > 0 && !(nextAct instanceof End)){ path.addAll(getForwardLookingPath(iFacts.getRoute(),actIndex)); }
if (nuOfActivities2LookForward > 0 && !(nextAct instanceof End)) {
path.addAll(getForwardLookingPath(iFacts.getRoute(), actIndex));
}
/*
* calculates the path costs with new vehicle, c(forwardPath,newVehicle).
@ -69,8 +72,7 @@ class RouteLevelActivityInsertionCostsEstimator implements ActivityInsertionCost
Double cost_at_act;
if (act instanceof End) {
cost_at_act = stateManager.getRouteState(vehicleRoute, InternalStates.COSTS, Double.class);
}
else{
} else {
cost_at_act = stateManager.getActivityState(act, InternalStates.COSTS, Double.class);
}
if (cost_at_act == null) cost_at_act = 0.;

View file

@ -39,7 +39,6 @@ import java.util.Iterator;
* Calculator that calculates the best insertion position for a {@link Service}.
*
* @author schroeder
*
*/
final class ServiceInsertionCalculator implements JobInsertionCostsCalculator {
@ -85,7 +84,6 @@ final class ServiceInsertionCalculator implements JobInsertionCostsCalculator{
/**
* Calculates the marginal cost of inserting job i locally. This is based on the
* assumption that cost changes can entirely covered by only looking at the predecessor i-1 and its successor i+1.
*
*/
@Override
public InsertionData getInsertionData(final VehicleRoute currentRoute, final Job jobToInsert, final Vehicle newVehicle, double newVehicleDepartureTime, final Driver newDriver, final double bestKnownCosts) {
@ -139,8 +137,7 @@ final class ServiceInsertionCalculator implements JobInsertionCostsCalculator{
bestCost = additionalICostsAtRouteLevel + additionalICostsAtActLevel + additionalTransportationCosts;
insertionIndex = actIndex;
}
}
else if(status.equals(ConstraintsStatus.NOT_FULFILLED_BREAK)){
} else if (status.equals(ConstraintsStatus.NOT_FULFILLED_BREAK)) {
break;
}
double nextActArrTime = prevActStartTime + transportCosts.getTransportTime(prevAct.getLocation(), nextAct.getLocation(), prevActStartTime, newDriver, newVehicle);

View file

@ -45,8 +45,6 @@ import java.util.List;
import java.util.PriorityQueue;
final class ServiceInsertionOnRouteLevelCalculator implements JobInsertionCostsCalculator {
private static final Logger logger = LogManager.getLogger(ServiceInsertionOnRouteLevelCalculator.class);
@ -115,13 +113,13 @@ final class ServiceInsertionOnRouteLevelCalculator implements JobInsertionCostsC
* have local effects but affects the entire route).
* Calculation is conducted by two steps. In the first step, promising insertion positions are identified by appromiximating their
* marginal insertion cost. In the second step, marginal cost of the best M positions are calculated exactly.
*
*
*/
@Override
public InsertionData getInsertionData(final VehicleRoute currentRoute, final Job jobToInsert, final Vehicle newVehicle, double newVehicleDepartureTime, final Driver newDriver, final double best_known_insertion_costs) {
if(jobToInsert == null) throw new IllegalStateException("job is null. cannot calculate the insertion of a null-job.");
if(newVehicle == null || newVehicle instanceof NoVehicle) throw new IllegalStateException("no vehicle given. set para vehicle!");
if (jobToInsert == null)
throw new IllegalStateException("job is null. cannot calculate the insertion of a null-job.");
if (newVehicle == null || newVehicle instanceof NoVehicle)
throw new IllegalStateException("no vehicle given. set para vehicle!");
JobInsertionContext insertionContext = new JobInsertionContext(currentRoute, jobToInsert, newVehicle, newDriver, newVehicleDepartureTime);
if (!hardRouteLevelConstraint.fulfilled(insertionContext)) {
@ -182,8 +180,7 @@ final class ServiceInsertionOnRouteLevelCalculator implements JobInsertionCostsC
if (insertion_cost_approximation < best_known_insertion_costs) {
bestInsertionsQueue.add(new InsertionData(insertion_cost_approximation, InsertionData.NO_INDEX, actIndex, newVehicle, newDriver));
}
}
else if(hardActivityConstraintsStatus.equals(ConstraintsStatus.NOT_FULFILLED_BREAK)){
} else if (hardActivityConstraintsStatus.equals(ConstraintsStatus.NOT_FULFILLED_BREAK)) {
loopBroken = true;
break;
}
@ -250,8 +247,7 @@ final class ServiceInsertionOnRouteLevelCalculator implements JobInsertionCostsC
best_insertion_index = insertion.getDeliveryInsertionIndex();
best_insertion_costs = insertion.getInsertionCost();
}
}
else{
} else {
for (int i = 0; i < memorySize; i++) {
InsertionData data = bestInsertionsQueue.poll();
@ -293,8 +289,7 @@ final class ServiceInsertionOnRouteLevelCalculator implements JobInsertionCostsC
if (start == null) {
start = new Start(newVehicle.getStartLocation(), newVehicle.getEarliestDeparture(), Double.MAX_VALUE);
start.setEndTime(newVehicleDepartureTime);
}
else{
} else {
start.setLocation(Location.newInstance(newVehicle.getStartLocation().getId()));
start.setTheoreticalEarliestOperationStartTime(newVehicle.getEarliestDeparture());
start.setTheoreticalLatestOperationStartTime(Double.MAX_VALUE);
@ -303,8 +298,7 @@ final class ServiceInsertionOnRouteLevelCalculator implements JobInsertionCostsC
if (end == null) {
end = new End(newVehicle.getEndLocation(), 0.0, newVehicle.getLatestArrival());
}
else{
} else {
end.setLocation(Location.newInstance(newVehicle.getEndLocation().getId()));
end.setTheoreticalEarliestOperationStartTime(0.0);
end.setTheoreticalLatestOperationStartTime(newVehicle.getLatestArrival());
@ -315,8 +309,7 @@ final class ServiceInsertionOnRouteLevelCalculator implements JobInsertionCostsC
Double prevCost;
if (act instanceof End) {
prevCost = stateManager.getRouteState(vehicleRoute, InternalStates.COSTS, Double.class);
}
else prevCost = stateManager.getActivityState(act, InternalStates.COSTS,Double.class);
} else prevCost = stateManager.getActivityState(act, InternalStates.COSTS, Double.class);
if (prevCost == null) prevCost = 0.;
return prevCost;
}
@ -328,8 +321,7 @@ final class ServiceInsertionOnRouteLevelCalculator implements JobInsertionCostsC
public int compare(InsertionData o1, InsertionData o2) {
if (o1.getInsertionCost() < o2.getInsertionCost()) {
return -1;
}
else {
} else {
return 1;
}

View file

@ -37,8 +37,6 @@ import org.apache.logging.log4j.Logger;
import java.util.List;
final class ShipmentInsertionCalculator implements JobInsertionCostsCalculator {
private static final Logger logger = LogManager.getLogger(ShipmentInsertionCalculator.class);
@ -83,7 +81,6 @@ final class ShipmentInsertionCalculator implements JobInsertionCostsCalculator{
/**
* Calculates the marginal cost of inserting job i locally. This is based on the
* assumption that cost changes can entirely covered by only looking at the predecessor i-1 and its successor i+1.
*
*/
@Override
public InsertionData getInsertionData(final VehicleRoute currentRoute, final Job jobToInsert, final Vehicle newVehicle, double newVehicleDepartureTime, final Driver newDriver, final double bestKnownCosts) {
@ -131,8 +128,7 @@ final class ShipmentInsertionCalculator implements JobInsertionCostsCalculator{
TourActivity nextAct;
if (i < activities.size()) {
nextAct = activities.get(i);
}
else{
} else {
nextAct = end;
tourEnd = true;
}
@ -144,8 +140,7 @@ final class ShipmentInsertionCalculator implements JobInsertionCostsCalculator{
prevAct = nextAct;
i++;
continue;
}
else if(pickupShipmentConstraintStatus.equals(ConstraintsStatus.NOT_FULFILLED_BREAK)){
} else if (pickupShipmentConstraintStatus.equals(ConstraintsStatus.NOT_FULFILLED_BREAK)) {
break;
}
double additionalPickupICosts = softActivityConstraint.getCosts(insertionContext, prevAct, pickupShipment, nextAct, prevActEndTime);
@ -174,8 +169,7 @@ final class ShipmentInsertionCalculator implements JobInsertionCostsCalculator{
TourActivity nextAct_deliveryLoop;
if (j < activities.size()) {
nextAct_deliveryLoop = activities.get(j);
}
else{
} else {
nextAct_deliveryLoop = end;
tourEnd_deliveryLoop = true;
}
@ -191,8 +185,7 @@ final class ShipmentInsertionCalculator implements JobInsertionCostsCalculator{
pickupInsertionIndex = i;
deliveryInsertionIndex = j;
}
}
else if(deliverShipmentConstraintStatus.equals(ConstraintsStatus.NOT_FULFILLED_BREAK)){
} else if (deliverShipmentConstraintStatus.equals(ConstraintsStatus.NOT_FULFILLED_BREAK)) {
break;
}
//update prevAct and endTime

View file

@ -54,8 +54,7 @@ public class VariableTransportCostCalculator implements SoftActivityConstraint{
if (iFacts.getRoute().isEmpty()) {
double tp_costs_prevAct_nextAct = routingCosts.getTransportCost(prevAct.getLocation(), nextAct.getLocation(), depTimeAtPrevAct, iFacts.getNewDriver(), iFacts.getNewVehicle());
oldCosts = tp_costs_prevAct_nextAct;
}
else{
} else {
double tp_costs_prevAct_nextAct = routingCosts.getTransportCost(prevAct.getLocation(), nextAct.getLocation(), prevAct.getEndTime(), iFacts.getRoute().getDriver(), iFacts.getRoute().getVehicle());
oldCosts = tp_costs_prevAct_nextAct;
}

View file

@ -47,11 +47,10 @@ final class VehicleTypeDependentJobInsertionCalculator implements JobInsertionCo
/**
* true if a vehicle(-type) is allowed to take over the whole route that was previously served by another vehicle
*
* <p/>
* <p>vehicleSwitch allowed makes sense if fleet consists of vehicles with different capacities such that one
* can start with a small vehicle, but as the number of customers grows bigger vehicles can be operated, i.e.
* bigger vehicles can take over the route that was previously served by a small vehicle.
*
*/
private boolean vehicleSwitchAllowed = false;
@ -104,8 +103,7 @@ final class VehicleTypeDependentJobInsertionCalculator implements JobInsertionCo
if (vehicleSwitchAllowed && !isVehicleWithInitialRoute(selectedVehicle)) {
relevantVehicles.addAll(fleetManager.getAvailableVehicles(selectedVehicle));
}
}
else{ //if no vehicle has been assigned, i.e. it is an empty route
} else { //if no vehicle has been assigned, i.e. it is an empty route
relevantVehicles.addAll(fleetManager.getAvailableVehicles());
}
for (Vehicle v : relevantVehicles) {

View file

@ -21,7 +21,6 @@ import jsprit.core.problem.solution.route.VehicleRoute;
import java.util.Collection;
public interface InsertionEndsListener extends InsertionListener {
public void informInsertionEnds(Collection<VehicleRoute> vehicleRoutes);

View file

@ -19,11 +19,7 @@ package jsprit.core.algorithm.recreate.listener;
import jsprit.core.algorithm.listener.SearchStrategyModuleListener;
public interface InsertionListener extends SearchStrategyModuleListener {
}

View file

@ -22,7 +22,6 @@ import jsprit.core.problem.solution.route.VehicleRoute;
import java.util.Collection;
public interface InsertionStartsListener extends InsertionListener {
public void informInsertionStarts(Collection<VehicleRoute> vehicleRoutes, Collection<Job> unassignedJobs);

View file

@ -20,10 +20,6 @@ import jsprit.core.problem.job.Job;
import jsprit.core.problem.solution.route.VehicleRoute;
public interface JobInsertedListener extends InsertionListener {
public void informJobInserted(Job job2insert, VehicleRoute inRoute, double additionalCosts, double additionalTime);

View file

@ -41,8 +41,7 @@ public class DBSCANClusterer {
List<Location> locs = new ArrayList<Location>();
if (job instanceof Service) {
locs.add(((Service) job).getLocation());
}
else if(job instanceof Shipment){
} else if (job instanceof Shipment) {
locs.add(((Shipment) job).getPickupLocation());
locs.add(((Shipment) job).getDeliveryLocation());
}

View file

@ -89,8 +89,7 @@ class JobNeighborhoodsImplWithCapRestriction implements JobNeighborhoods {
if (treeSet.size() < capacity) {
treeSet.add(refNode);
nuOfDistancesStored++;
}
else{
} else {
if (treeSet.last().getDistance() > distance) {
treeSet.pollLast();
treeSet.add(refNode);

View file

@ -29,7 +29,8 @@ class NearestNeighborhoodIterator implements Iterator<Job> {
public boolean hasNext() {
if (jobCount < nJobs) {
boolean hasNext = jobIter.hasNext();
if(!hasNext) log.warn("more jobs are requested then iterator can iterate over. probably the number of neighbors memorized in JobNeighborhoods is too small");
if (!hasNext)
log.warn("more jobs are requested then iterator can iterate over. probably the number of neighbors memorized in JobNeighborhoods is too small");
return hasNext;
}
return false;

View file

@ -28,13 +28,11 @@ import java.util.*;
/**
*
* RuinStrategy that ruins the neighborhood of a randomly selected job. The size and the structure of the neighborhood is defined by
* the share of jobs to be removed and the distance between jobs (where distance not necessarily mean Euclidean distance but an arbitrary
* measure).
*
* @author stefan
*
*/
public final class RuinRadial extends AbstractRuinStrategy {
@ -130,6 +128,7 @@ public final class RuinRadial extends AbstractRuinStrategy {
/**
* Removes targetJob and its neighborhood and returns the removed jobs.
*
* @deprecated will be private
*/
@Deprecated

View file

@ -27,13 +27,11 @@ import java.util.*;
/**
*
* RuinStrategy that ruins the neighborhood of a randomly selected job. The size and the structure of the neighborhood is defined by
* the share of jobs to be removed and the distance between jobs (where distance not necessarily mean Euclidean distance but an arbitrary
* measure).
*
* @author stefan
*
*/
public final class RuinRadialMultipleCenters extends AbstractRuinStrategy {
@ -100,6 +98,7 @@ public final class RuinRadialMultipleCenters extends AbstractRuinStrategy {
/**
* Removes targetJob and its neighborhood and returns the removed jobs.
*
* @deprecated will be private
*/
@Deprecated
@ -129,8 +128,7 @@ public final class RuinRadialMultipleCenters extends AbstractRuinStrategy {
for (Job j : available) {
if (i >= randomIndex) {
return j;
}
else i++;
} else i++;
}
return null;
}

View file

@ -33,7 +33,6 @@ import java.util.List;
* customer are removed randomly from current solution.
*
* @author stefan schroeder
*
*/
public final class RuinRandom extends AbstractRuinStrategy {
@ -65,7 +64,7 @@ public final class RuinRandom extends AbstractRuinStrategy {
/**
* Removes a fraction of jobs from vehicleRoutes.
*
* <p/>
* <p>The number of jobs is calculated as follows: Math.ceil(vrp.getJobs().values().size() * fractionOfAllNodes2beRuined).
*/
@Override

View file

@ -23,13 +23,8 @@ import jsprit.core.problem.solution.route.VehicleRoute;
import java.util.Collection;
/**
*
* @author stefan schroeder
*
*/
public interface RuinStrategy {

View file

@ -34,7 +34,6 @@ import java.util.*;
* customer are removed randomly from current solution.
*
* @author stefan schroeder
*
*/
public final class RuinWorst extends AbstractRuinStrategy {
@ -69,7 +68,7 @@ public final class RuinWorst extends AbstractRuinStrategy {
/**
* Removes a fraction of jobs from vehicleRoutes.
*
* <p/>
* <p>The number of jobs is calculated as follows: Math.ceil(vrp.getJobs().values().size() * fractionOfAllNodes2beRuined).
*/
@Override
@ -120,8 +119,7 @@ public final class RuinWorst extends AbstractRuinStrategy {
Job job = ((TourActivity.JobActivity) actToEval).getJob();
if (!savingsMap.containsKey(job)) {
savingsMap.put(job, savings);
}
else {
} else {
double s = savingsMap.get(job);
savingsMap.put(job, s + savings);
}
@ -132,8 +130,7 @@ public final class RuinWorst extends AbstractRuinStrategy {
Job job = ((TourActivity.JobActivity) actToEval).getJob();
if (!savingsMap.containsKey(job)) {
savingsMap.put(job, savings);
}
else {
} else {
double s = savingsMap.get(job);
savingsMap.put(job, s + savings);
}

View file

@ -24,14 +24,12 @@ import jsprit.core.problem.job.Shipment;
import jsprit.core.util.EuclideanDistanceCalculator;
/**
* Calculator that calculates average distance between two jobs based on the input-transport costs.
*
* <p/>
* <p>If the distance between two jobs cannot be calculated with input-transport costs, it tries the euclidean distance between these jobs.
*
* @author stefan schroeder
*
*/
public class AvgServiceAndShipmentDistance implements JobDistance {
@ -45,7 +43,7 @@ public class AvgServiceAndShipmentDistance implements JobDistance {
/**
* Calculates and returns the average distance between two jobs based on the input-transport costs.
*
* <p/>
* <p>If the distance between two jobs cannot be calculated with input-transport costs, it tries the euclidean distance between these jobs.
*/
@Override
@ -54,17 +52,13 @@ public class AvgServiceAndShipmentDistance implements JobDistance {
if (i instanceof Service && j instanceof Service) {
return calcDist((Service) i, (Service) j);
}
else if(i instanceof Service && j instanceof Shipment){
} else if (i instanceof Service && j instanceof Shipment) {
return calcDist((Service) i, (Shipment) j);
}
else if(i instanceof Shipment && j instanceof Service){
} else if (i instanceof Shipment && j instanceof Service) {
return calcDist((Service) j, (Shipment) i);
}
else if(i instanceof Shipment && j instanceof Shipment){
} else if (i instanceof Shipment && j instanceof Shipment) {
return calcDist((Shipment) i, (Shipment) j);
}
else{
} else {
throw new IllegalStateException("this supports only shipments or services");
}
}
@ -90,8 +84,7 @@ public class AvgServiceAndShipmentDistance implements JobDistance {
private double calcDist(Location location_i, Location location_j) {
try {
return costs.getTransportCost(location_i, location_j, 0.0, null, null);
}
catch(IllegalStateException e){
} catch (IllegalStateException e) {
// now try the euclidean distance between these two services
}
return EuclideanDistanceCalculator.calculateDistance(location_i.getCoordinate(), location_j.getCoordinate());

View file

@ -21,14 +21,12 @@ import jsprit.core.problem.job.Job;
import jsprit.core.problem.job.Service;
/**
* Calculator that calculates average distance between two jobs based on the input-transport costs.
*
* <p/>
* <p>If the distance between two jobs cannot be calculated with input-transport costs, it tries the euclidean distance between these jobs.
*
* @author stefan schroeder
*
*/
public class AvgServiceDistance implements JobDistance {
@ -42,7 +40,7 @@ public class AvgServiceDistance implements JobDistance {
/**
* Calculates and returns the average distance between two jobs based on the input-transport costs.
*
* <p/>
* <p>If the distance between two jobs cannot be calculated with input-transport costs, it tries the euclidean distance between these jobs.
*/
@Override
@ -68,8 +66,7 @@ public class AvgServiceDistance implements JobDistance {
try {
distance = costs.getTransportCost(s_i.getLocation(), s_j.getLocation(), 0.0, null, null);
return distance;
}
catch(IllegalStateException e){
} catch (IllegalStateException e) {
// now try the euclidean distance between these two services
}
EuclideanServiceDistance euclidean = new EuclideanServiceDistance();

View file

@ -35,7 +35,8 @@ public class EuclideanServiceDistance implements JobDistance {
} else {
Service s_i = (Service) i;
Service s_j = (Service) j;
if(s_i.getLocation().getCoordinate() == null || s_j.getLocation().getCoordinate() == null) throw new IllegalStateException("cannot calculate euclidean distance. since service coords are missing");
if (s_i.getLocation().getCoordinate() == null || s_j.getLocation().getCoordinate() == null)
throw new IllegalStateException("cannot calculate euclidean distance. since service coords are missing");
avgCost = EuclideanDistanceCalculator.calculateDistance(s_i.getLocation().getCoordinate(), s_j.getLocation().getCoordinate());
}
} else {

View file

@ -19,7 +19,6 @@ package jsprit.core.algorithm.ruin.distance;
import jsprit.core.problem.job.Job;
public interface JobDistance {
public double getDistance(Job i, Job j);

View file

@ -29,7 +29,6 @@ import java.util.Collection;
* Listener that listens to the ruin-process. It informs whoever is interested about start, end and about a removal of a job.
*
* @author schroeder
*
*/
public interface RuinListener extends SearchStrategyModuleListener {

View file

@ -1,4 +1,3 @@
/*******************************************************************************
* Copyright (C) 2014 Stefan Schroeder
*

View file

@ -21,9 +21,6 @@ import jsprit.core.problem.solution.VehicleRoutingProblemSolution;
import java.util.Collection;
public class SelectBest implements SolutionSelector {
private static SelectBest selector = null;
@ -44,8 +41,7 @@ public class SelectBest implements SolutionSelector{
if (bestSolution == null) {
bestSolution = sol;
minCost = sol.getCost();
}
else if(sol.getCost() < minCost){
} else if (sol.getCost() < minCost) {
bestSolution = sol;
minCost = sol.getCost();
}

View file

@ -25,8 +25,6 @@ import java.util.List;
import java.util.Random;
public class SelectRandomly implements SolutionSelector {
private static SelectRandomly selector = null;

View file

@ -21,7 +21,6 @@ import jsprit.core.problem.solution.VehicleRoutingProblemSolution;
import java.util.Collection;
public interface SolutionSelector {
public VehicleRoutingProblemSolution selectSolution(Collection<VehicleRoutingProblemSolution> solutions);

View file

@ -1,4 +1,3 @@
/*******************************************************************************
* Copyright (C) 2014 Stefan Schroeder
*

View file

@ -13,7 +13,9 @@ class StateFactory {
static StateId createId(String name) {
if(reservedIds.contains(name)){ throwReservedIdException(name); }
if (reservedIds.contains(name)) {
throwReservedIdException(name);
}
return new StateIdImpl(name, -1);
}
@ -41,7 +43,9 @@ class StateFactory {
private int index;
public int getIndex(){ return index; }
public int getIndex() {
return index;
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()

View file

@ -37,12 +37,11 @@ import java.util.*;
/**
* Manages states.
*
* <p/>
* <p>Some condition, rules or constraints are stateful. This StateManager manages these states, i.e. it offers
* methods to add, store and retrieve states based on the problem, vehicle-routes and tour-activities.
*
* @author schroeder
*
*/
public class StateManager implements RouteAndActivityStateGetter, IterationStartsListener, RuinListener, InsertionStartsListener, JobInsertedListener, InsertionEndsListener {
@ -109,13 +108,16 @@ public class StateManager implements RouteAndActivityStateGetter, IterationStart
private VehicleRoutingProblem vrp;
int getMaxIndexOfVehicleTypeIdentifiers(){ return nuVehicleTypeKeys; }
int getMaxIndexOfVehicleTypeIdentifiers() {
return nuVehicleTypeKeys;
}
/**
* Create and returns a stateId with the specified state-name.
*
* <p/>
* <p>If a stateId with the specified name has already been created, it returns the created stateId.</p>
* <p>If the specified is equal to a name that is already used internally, it throws an IllegalStateException</p>
*
* @param name the specified name of the state
* @return the stateId with which a state can be identified, no matter if it is a problem, route or activity state.
* @throws java.lang.IllegalStateException if name of state is already used internally
@ -194,7 +196,6 @@ public class StateManager implements RouteAndActivityStateGetter, IterationStart
/**
* Clears all states, i.e. set all value to null.
*
*/
public void clear() {
fill_twoDimArr(activity_states, null);
@ -239,8 +240,7 @@ public class StateManager implements RouteAndActivityStateGetter, IterationStart
T state;
try {
state = type.cast(activity_states[act.getIndex()][stateId.getIndex()]);
}
catch (ClassCastException e){
} catch (ClassCastException e) {
throw getClassCastException(e, stateId, type.toString(), activity_states[act.getIndex()][stateId.getIndex()].getClass().toString());
}
return state;
@ -264,6 +264,7 @@ public class StateManager implements RouteAndActivityStateGetter, IterationStart
* Returns the associated state value to the specified activity, vehicle and stateId, or null if no state value is
* associated.
* <p>If type class is not equal to the associated type class of the requested state value, it throws a ClassCastException.</p>
*
* @param act the activity for which a state value is associated to
* @param vehicle the vehicle for which a state value is associated to
* @param stateId the stateId which is the associated key to the problem state
@ -280,8 +281,7 @@ public class StateManager implements RouteAndActivityStateGetter, IterationStart
T state;
try {
state = type.cast(vehicle_dependent_activity_states[act.getIndex()][vehicle.getVehicleTypeIdentifier().getIndex()][stateId.getIndex()]);
}
catch(ClassCastException e){
} catch (ClassCastException e) {
Object state_class = vehicle_dependent_activity_states[act.getIndex()][vehicle.getVehicleTypeIdentifier().getIndex()][stateId.getIndex()];
throw getClassCastException(e, stateId, type.toString(), state_class.getClass().toString());
}
@ -316,8 +316,7 @@ public class StateManager implements RouteAndActivityStateGetter, IterationStart
state = type.cast(route_state_map.get(route)[stateId.getIndex()]);
}
// state = type.cast(route_states[index_of_first_act][stateId.getIndex()]);
}
catch (ClassCastException e){
} catch (ClassCastException e) {
throw getClassCastException(e, stateId, type.toString(), route_state_map.get(route)[stateId.getIndex()].getClass().toString());
// throw getClassCastException(e,stateId,type.toString(),route_states[index_of_first_act][stateId.getIndex()].getClass().toString());
}
@ -342,6 +341,7 @@ public class StateManager implements RouteAndActivityStateGetter, IterationStart
/**
* Returns the route state that is assigned to the specified route, vehicle and stateId.
* <p>Returns null if no state can be found</p>
*
* @param route the route for which the state is requested
* @param vehicle the vehicle for which the state is requested
* @param stateId the stateId(entifier) for the state that is requested
@ -361,8 +361,7 @@ public class StateManager implements RouteAndActivityStateGetter, IterationStart
state = type.cast(vehicle_dependent_route_state_map.get(route)[vehicle.getVehicleTypeIdentifier().getIndex()][stateId.getIndex()]);
}
// state = type.cast(vehicle_dependent_route_states[index_of_first_act][vehicle.getVehicleTypeIdentifier().getIndex()][stateId.getIndex()]);
}
catch( ClassCastException e){
} catch (ClassCastException e) {
throw getClassCastException(e, stateId, type.toString(), vehicle_dependent_route_state_map.get(route)[vehicle.getVehicleTypeIdentifier().getIndex()][stateId.getIndex()].getClass().toString());
}
return state;
@ -378,11 +377,11 @@ public class StateManager implements RouteAndActivityStateGetter, IterationStart
* @param <T> the type of the state
* @throws java.lang.IllegalStateException if <code>act.getIndex() == 0</code>
* || stateId.getIndex < noInternalStates
*
*/
public <T> void putActivityState(TourActivity act, StateId stateId, T state) {
if (act.getIndex() == 0) throw new IllegalStateException("activity index is 0. this should not be.");
if(stateId.getIndex() < initialNoStates) throw new IllegalStateException("either you use a reserved stateId that is applied\n" +
if (stateId.getIndex() < initialNoStates)
throw new IllegalStateException("either you use a reserved stateId that is applied\n" +
"internally or your stateId has been created without index, e.g. StateFactory.createId(stateName)\n" +
" does not assign indeces thus do not use it anymore, but use\n " +
"stateManager.createStateId(name)\n" +
@ -404,7 +403,8 @@ public class StateManager implements RouteAndActivityStateGetter, IterationStart
*/
public <T> void putActivityState(TourActivity act, Vehicle vehicle, StateId stateId, T state) {
if (act.getIndex() == 0) throw new IllegalStateException("activity index is 0. this should not be.");
if(stateId.getIndex() < initialNoStates) throw new IllegalStateException("either you use a reserved stateId that is applied\n" +
if (stateId.getIndex() < initialNoStates)
throw new IllegalStateException("either you use a reserved stateId that is applied\n" +
"internally or your stateId has been created without index, e.g. StateFactory.createId(stateName)\n" +
" does not assign indeces thus do not use it anymore, but use\n " +
"stateManager.createStateId(name)\n" +
@ -472,11 +472,11 @@ public class StateManager implements RouteAndActivityStateGetter, IterationStart
/**
* Adds state updater.
*
* <p/>
* <p>Note that a state update occurs if route and/or activity states have changed, i.e. if jobs are removed
* or inserted into a route. Thus here, it is assumed that a state updater is either of type InsertionListener,
* RuinListener, ActivityVisitor, ReverseActivityVisitor, RouteVisitor, ReverseRouteVisitor.
*
* <p/>
* <p>The following rule pertain for activity/route visitors:These visitors visits all activities/route in a route subsequently in two cases. First, if insertionStart (after ruinStrategies have removed activities from routes)
* and, second, if a job has been inserted and thus if a route has changed.
*
@ -543,7 +543,9 @@ public class StateManager implements RouteAndActivityStateGetter, IterationStart
public void informJobInserted(Job job2insert, VehicleRoute inRoute, double additionalCosts, double additionalTime) {
// log.debug("insert " + job2insert + " in " + inRoute);
insertionListeners.informJobInserted(job2insert, inRoute, additionalCosts, additionalTime);
for(RouteVisitor v : routeVisitors){ v.visit(inRoute); }
for (RouteVisitor v : routeVisitors) {
v.visit(inRoute);
}
routeActivityVisitor.visit(inRoute);
revRouteActivityVisitor.visit(inRoute);
}
@ -552,7 +554,9 @@ public class StateManager implements RouteAndActivityStateGetter, IterationStart
public void informInsertionStarts(Collection<VehicleRoute> vehicleRoutes, Collection<Job> unassignedJobs) {
insertionListeners.informInsertionStarts(vehicleRoutes, unassignedJobs);
for (VehicleRoute route : vehicleRoutes) {
for(RouteVisitor v : routeVisitors){ v.visit(route); }
for (RouteVisitor v : routeVisitors) {
v.visit(route);
}
routeActivityVisitor.visit(route);
revRouteActivityVisitor.visit(route);
}

View file

@ -25,11 +25,10 @@ import jsprit.core.util.ActivityTimeTracker;
/**
* Updates arrival and end times of activities.
*
* <p/>
* <p>Note that this modifies arrTime and endTime of each activity in a route.
*
* @author stefan
*
*/
public class UpdateActivityTimes implements ActivityVisitor, StateUpdater {
@ -39,15 +38,12 @@ public class UpdateActivityTimes implements ActivityVisitor, StateUpdater{
/**
* Updates arrival and end times of activities.
*
* <p/>
* <p>Note that this modifies arrTime and endTime of each activity in a route.
*
* <p/>
* <p>ArrTimes and EndTimes can be retrieved by <br>
* <code>activity.getArrTime()</code> and
* <code>activity.getEndTime()</code>
*
*
*
*/
public UpdateActivityTimes(ForwardTransportTime transportTime) {
super();

View file

@ -39,7 +39,4 @@ public class UpdateEndLocationIfRouteIsOpen implements StateUpdater, RouteVisito
}
}

View file

@ -33,13 +33,12 @@ import java.util.Collection;
/**
* Updates load at start and end of route as well as at each activity. And update is triggered when either
* activityVisitor has been started, the insertion process has been started or a job has been inserted.
*
* <p/>
* <p>Note that this only works properly if you register this class as ActivityVisitor AND InsertionStartsListener AND JobInsertedListener.
* The reason behind is that activity states are dependent on route-level states and vice versa. If this is properly registered,
* this dependency is solved automatically.
*
* @author stefan
*
*/
class UpdateLoads implements ActivityVisitor, StateUpdater, InsertionStartsListener, JobInsertedListener {
@ -86,8 +85,7 @@ class UpdateLoads implements ActivityVisitor, StateUpdater, InsertionStartsListe
for (Job j : route.getTourActivities().getJobs()) {
if (j instanceof Delivery) {
loadAtDepot = Capacity.addup(loadAtDepot, j.getSize());
}
else if(j instanceof Pickup || j instanceof Service){
} else if (j instanceof Pickup || j instanceof Service) {
loadAtEnd = Capacity.addup(loadAtEnd, j.getSize());
}
}
@ -97,7 +95,9 @@ class UpdateLoads implements ActivityVisitor, StateUpdater, InsertionStartsListe
@Override
public void informInsertionStarts(Collection<VehicleRoute> vehicleRoutes, Collection<Job> unassignedJobs) {
for(VehicleRoute route : vehicleRoutes){ insertionStarts(route); }
for (VehicleRoute route : vehicleRoutes) {
insertionStarts(route);
}
}
@Override
@ -106,8 +106,7 @@ class UpdateLoads implements ActivityVisitor, StateUpdater, InsertionStartsListe
Capacity loadAtDepot = stateManager.getRouteState(inRoute, InternalStates.LOAD_AT_BEGINNING, Capacity.class);
if (loadAtDepot == null) loadAtDepot = defaultValue;
stateManager.putTypedInternalRouteState(inRoute, InternalStates.LOAD_AT_BEGINNING, Capacity.addup(loadAtDepot, job2insert.getSize()));
}
else if(job2insert instanceof Pickup || job2insert instanceof Service){
} else if (job2insert instanceof Pickup || job2insert instanceof Service) {
Capacity loadAtEnd = stateManager.getRouteState(inRoute, InternalStates.LOAD_AT_END, Capacity.class);
if (loadAtEnd == null) loadAtEnd = defaultValue;
stateManager.putTypedInternalRouteState(inRoute, InternalStates.LOAD_AT_END, Capacity.addup(loadAtEnd, job2insert.getSize()));

View file

@ -26,7 +26,6 @@ import jsprit.core.problem.solution.route.activity.TourActivity;
* i.e. the maximum capacity utilization at previous activities.
*
* @author schroeder
*
*/
class UpdateMaxCapacityUtilisationAtActivitiesByLookingBackwardInRoute implements ActivityVisitor, StateUpdater {
@ -59,5 +58,6 @@ class UpdateMaxCapacityUtilisationAtActivitiesByLookingBackwardInRoute implement
}
@Override
public void finish() {}
public void finish() {
}
}

View file

@ -24,7 +24,7 @@ import jsprit.core.problem.solution.route.activity.TourActivity;
/**
* A {@link ReverseActivityVisitor} that looks forward in the vehicle route and determines
* the maximum capacity utilization (in terms of loads) at subsequent activities.
*
* <p/>
* <p>Assume a vehicle route with the following activity sequence {start,pickup(1,4),delivery(2,3),pickup(3,2),end} where
* pickup(1,2) = pickup(id,cap-demand).<br>
* Future maxLoad for each activity are calculated as follows:<br>
@ -36,9 +36,7 @@ import jsprit.core.problem.solution.route.activity.TourActivity;
* activity (apart from start and end), the maximum capacity is determined when forward looking into the route.
* That is at each activity we know how much capacity is available whithout breaking future capacity constraints.
*
*
* @author schroeder
*
*/
class UpdateMaxCapacityUtilisationAtActivitiesByLookingForwardInRoute implements ReverseActivityVisitor, StateUpdater {
@ -72,5 +70,6 @@ class UpdateMaxCapacityUtilisationAtActivitiesByLookingForwardInRoute implements
}
@Override
public void finish() {}
public void finish() {
}
}

View file

@ -25,14 +25,13 @@ import jsprit.core.problem.solution.route.activity.TourActivity;
/**
* Updates load at activity level.
*
* <p/>
* <p>Note that this assumes that StateTypes.LOAD_AT_DEPOT is already updated, i.e. it starts by setting loadAtDepot to StateTypes.LOAD_AT_DEPOT.
* If StateTypes.LOAD_AT_DEPOT is not set, it starts with 0 load at depot.
*
* <p/>
* <p>Thus it DEPENDS on StateTypes.LOAD_AT_DEPOT
*
* @author stefan
*
*/
class UpdateMaxCapacityUtilisationAtRoute implements ActivityVisitor, StateUpdater {

View file

@ -25,7 +25,6 @@ import jsprit.core.problem.solution.route.activity.TourActivity;
* Updates and memorizes latest operation start times at activities.
*
* @author schroeder
*
*/
class UpdatePracticalTimeWindows implements ReverseActivityVisitor, StateUpdater {
@ -64,5 +63,6 @@ class UpdatePracticalTimeWindows implements ReverseActivityVisitor, StateUpdater
}
@Override
public void finish() {}
public void finish() {
}
}

View file

@ -27,10 +27,9 @@ import jsprit.core.util.ActivityTimeTracker;
/**
* Updates total costs (i.e. transport and activity costs) at route and activity level.
*
* <p/>
* <p>Thus it modifies <code>stateManager.getRouteState(route, StateTypes.COSTS)</code> and <br>
* <code>stateManager.getActivityState(activity, StateTypes.COSTS)</code>
*
*/
public class UpdateVariableCosts implements ActivityVisitor, StateUpdater {
@ -52,11 +51,10 @@ public class UpdateVariableCosts implements ActivityVisitor,StateUpdater{
/**
* Updates total costs (i.e. transport and activity costs) at route and activity level.
*
* <p/>
* <p>Thus it modifies <code>stateManager.getRouteState(route, StateTypes.COSTS)</code> and <br>
* <code>stateManager.getActivityState(activity, StateTypes.COSTS)</code>
*
*
* @param activityCost
* @param transportCost
* @param states

View file

@ -93,7 +93,8 @@ public class UpdateVehicleDependentPracticalTimeWindows implements ReverseActivi
}
@Override
public void finish() {}
public void finish() {
}
}

View file

@ -22,13 +22,12 @@ import org.apache.logging.log4j.Logger;
/**
* Terminates algorithm prematurely based on iterations without any improvement (i.e. new solution acceptance).
*
* <p/>
* <p>Termination will be activated by:<br>
*
* <p/>
* <code>algorithm.setPrematureAlgorithmTermination(this);</code><br>
*
* @author stefan schroeder
*
*/
public class IterationWithoutImprovementTermination implements PrematureAlgorithmTermination {

View file

@ -20,7 +20,6 @@ import jsprit.core.algorithm.SearchStrategy.DiscoveredSolution;
/**
* Basic interface for prematureTermination.
*
*/
public interface PrematureAlgorithmTermination {

View file

@ -29,15 +29,14 @@ import java.util.Collection;
/**
* Terminates algorithm prematurely based on specified time.
*
* <p/>
* <p>Note, TimeTermination must be registered as AlgorithmListener <br>
* TimeTermination will be activated by:<br>
*
* <p/>
* <code>algorithm.setPrematureAlgorithmTermination(this);</code><br>
* <code>algorithm.addListener(this);</code>
*
* @author stefan schroeder
*
*/
public class TimeTermination implements PrematureAlgorithmTermination, AlgorithmStartsListener {

View file

@ -34,16 +34,14 @@ import java.util.Collection;
/**
* Terminates algorithm prematurely based on variationCoefficient (http://en.wikipedia.org/wiki/Coefficient_of_variation).
*
* <p/>
* <p>Note, that this must be registered as AlgorithmListener <br>
* It will be activated by:<br>
*
* <p/>
* <code>algorithm.setPrematureAlgorithmTermination(this);</code><br>
* <code>algorithm.addListener(this);</code>
*
*
* @author stefan schroeder
*
*/
public class VariationCoefficientTermination implements PrematureAlgorithmTermination, IterationStartsListener, AlgorithmStartsListener, IterationEndsListener {
@ -86,12 +84,10 @@ public class VariationCoefficientTermination implements PrematureAlgorithmTermin
if (discoveredSolution.isAccepted()) {
lastAccepted = discoveredSolution.getSolution();
solutionValues[currentIteration] = discoveredSolution.getSolution().getCost();
}
else{
} else {
if (lastAccepted != null) {
solutionValues[currentIteration] = lastAccepted.getCost();
}
else solutionValues[currentIteration] = Integer.MAX_VALUE;
} else solutionValues[currentIteration] = Integer.MAX_VALUE;
}
if (currentIteration == (noIterations - 1)) {
double mean = StatUtils.mean(solutionValues);
@ -117,8 +113,7 @@ public class VariationCoefficientTermination implements PrematureAlgorithmTermin
public void informIterationEnds(int i, VehicleRoutingProblem problem, Collection<VehicleRoutingProblemSolution> solutions) {
if (currentIteration == (noIterations - 1)) {
reset();
}
else{
} else {
currentIteration++;
}
}

View file

@ -122,8 +122,7 @@ public class SolutionAnalyser {
if (activity instanceof PickupService) {
deliverAtEndCounter++;
}
}
else if(activity instanceof DeliveryActivity){
} else if (activity instanceof DeliveryActivity) {
deliveryCounter++;
delivered = Capacity.addup(delivered, ((DeliveryActivity) activity).getJob().getSize());
if (activity instanceof DeliverService) {
@ -181,33 +180,28 @@ public class SolutionAnalyser {
//shipment
if (activity instanceof PickupShipment) {
openShipments.put(((PickupShipment) activity).getJob().getId(), (PickupShipment) activity);
}
else if(activity instanceof DeliverShipment){
} else if (activity instanceof DeliverShipment) {
String jobId = ((DeliverShipment) activity).getJob().getId();
if (!openShipments.containsKey(jobId)) {
//deliverShipment without pickupShipment
stateManager.putActivityState(activity, shipment_id, true);
shipmentConstraintOnRouteViolated = true;
}
else {
} else {
PickupShipment removed = openShipments.remove(jobId);
stateManager.putActivityState(removed, shipment_id, false);
stateManager.putActivityState(activity, shipment_id, false);
}
}
else stateManager.putActivityState(activity,shipment_id,false);
} else stateManager.putActivityState(activity, shipment_id, false);
//backhaul
if (activity instanceof DeliverService && pickupOccured) {
stateManager.putActivityState(activity, backhaul_id, true);
backhaulConstraintOnRouteViolated = true;
}
else{
} else {
if (activity instanceof PickupService || activity instanceof ServiceActivity || activity instanceof PickupShipment) {
pickupOccured = true;
stateManager.putActivityState(activity, backhaul_id, false);
}
else stateManager.putActivityState(activity,backhaul_id,false);
} else stateManager.putActivityState(activity, backhaul_id, false);
}
}
@ -509,7 +503,6 @@ public class SolutionAnalyser {
private VehicleRoutingProblemSolution solution;
/**
*
* @param vrp
* @param solution
* @param distanceCalculator
@ -672,7 +665,6 @@ public class SolutionAnalyser {
}
/**
*
* @param activity to get the load from (after activity)
* @return load right after the specified activity. If act is Start, it returns the load atBeginning of the specified
* route. If act is End, it returns the load atEnd of specified route.
@ -707,8 +699,7 @@ public class SolutionAnalyser {
Capacity afterAct = stateManager.getActivityState(activity, InternalStates.LOAD, Capacity.class);
if (afterAct != null && activity.getSize() != null) {
return Capacity.subtract(afterAct, activity.getSize());
}
else if(afterAct != null) return afterAct;
} else if (afterAct != null) return afterAct;
else return null;
}
@ -904,7 +895,6 @@ public class SolutionAnalyser {
}
/**
* @param route to get the total operation time from
* @return operation time of this route, i.e. endTime - startTime of specified route
@ -979,7 +969,6 @@ public class SolutionAnalyser {
}
/**
*
* @param activity to get the transport time from
* @param route where the activity should be part of
* @return transport time at the activity, i.e. the total time spent driving since the start of the route to the specified activity.
@ -994,7 +983,6 @@ public class SolutionAnalyser {
}
/**
*
* @param activity to get the last transport time from
* @param route where the activity should be part of
* @return The transport time from the previous activity to this one.
@ -1004,7 +992,6 @@ public class SolutionAnalyser {
}
/**
*
* @param activity to get the last transport distance from
* @param route where the activity should be part of
* @return The transport distance from the previous activity to this one.
@ -1014,7 +1001,6 @@ public class SolutionAnalyser {
}
/**
*
* @param activity to get the last transport cost from
* @param route where the activity should be part of
* @return The transport cost from the previous activity to this one.
@ -1145,7 +1131,6 @@ public class SolutionAnalyser {
}
/**
* @return total distance for specified solution
*/
@ -1238,10 +1223,5 @@ public class SolutionAnalyser {
}
}

View file

@ -9,7 +9,11 @@ public abstract class AbstractActivity implements TourActivity {
private int index;
public int getIndex(){ return index; }
protected void setIndex(int index){ this.index = index; }
public int getIndex() {
return index;
}
protected void setIndex(int index) {
this.index = index;
}
}

View file

@ -9,8 +9,12 @@ public abstract class AbstractJob implements Job {
private int index;
public int getIndex(){ return index; }
public int getIndex() {
return index;
}
protected void setIndex(int index){ this.index = index; }
protected void setIndex(int index) {
this.index = index;
}
}

View file

@ -12,9 +12,13 @@ public abstract class AbstractVehicle implements Vehicle {
private int index;
public int getIndex(){ return index; }
public int getIndex() {
return index;
}
public void setIndex(int index) { this.index = index; }
public void setIndex(int index) {
this.index = index;
}
}
@ -22,9 +26,13 @@ public abstract class AbstractVehicle implements Vehicle {
private VehicleTypeKey vehicleIdentifier;
public int getIndex(){ return index; }
public int getIndex() {
return index;
}
protected void setIndex(int index){ this.index = index; }
protected void setIndex(int index) {
this.index = index;
}
public VehicleTypeKey getVehicleTypeIdentifier() {
return vehicleIdentifier;

View file

@ -18,24 +18,22 @@ package jsprit.core.problem;
/**
* Capacity with an arbitrary number of capacity-dimension.
*
* <p/>
* <p>Note that this assumes the the values of each capacity dimension can be added up and subtracted
*
* @author schroeder
*
*/
public class Capacity {
/**
* Adds up two capacities, i.e. sums up each and every capacity dimension, and returns the resulting Capacity.
*
* <p/>
* <p>Note that this assumes that capacity dimension can be added up.
*
* @param cap1 capacity to be added up
* @param cap2 capacity to be added up
* @return new capacity
* @throws NullPointerException if one of the args is null
*/
public static Capacity addup(Capacity cap1, Capacity cap2) {
if (cap1 == null || cap2 == null) throw new NullPointerException("arguments must not be null");
@ -54,7 +52,6 @@ public class Capacity {
* @return new capacity
* @throws NullPointerException if one of the args is null
* @throws IllegalStateException if number of capacityDimensions of cap1 and cap2 are different (i.e. <code>cap1.getNuOfDimension() != cap2.getNuOfDimension()</code>).
*
*/
public static Capacity subtract(Capacity cap, Capacity cap2subtract) {
if (cap == null || cap2subtract == null) throw new NullPointerException("arguments must not be null");
@ -86,9 +83,10 @@ public class Capacity {
/**
* Divides every dimension of numerator capacity by the corresponding dimension of denominator capacity,
* , and averages each quotient.
*
* <p/>
* <p>If both nominator.get(i) and denominator.get(i) equal to 0, dimension i is ignored.
* <p>If both capacities are have only dimensions with dimensionVal=0, it returns 0.0
*
* @param numerator the numerator
* @param denominator the denominator
* @return quotient
@ -100,11 +98,9 @@ public class Capacity {
for (int index = 0; index < Math.max(numerator.getNuOfDimensions(), denominator.getNuOfDimensions()); index++) {
if (numerator.get(index) != 0 && denominator.get(index) == 0) {
throw new IllegalStateException("numerator > 0 and denominator = 0. cannot divide by 0");
}
else if(numerator.get(index) == 0 && denominator.get(index) == 0){
} else if (numerator.get(index) == 0 && denominator.get(index) == 0) {
continue;
}
else{
} else {
nuOfDimensions++;
sumQuotients += (double) numerator.get(index) / (double) denominator.get(index);
}
@ -128,7 +124,6 @@ public class Capacity {
* Builder that builds Capacity
*
* @author schroeder
*
*/
public static class Builder {
@ -146,11 +141,12 @@ public class Capacity {
return new Builder();
}
Builder(){}
Builder() {
}
/**
* add capacity dimension
*
* <p/>
* <p>Note that it automatically resizes dimensions according to index, i.e. if index=7 there are 8 dimensions.
* New dimensions then are initialized with 0
*
@ -161,8 +157,7 @@ public class Capacity {
public Builder addDimension(int index, int dimValue) {
if (index < dimensions.length) {
dimensions[index] = dimValue;
}
else{
} else {
int requiredSize = index + 1;
int[] newDimensions = new int[requiredSize];
copy(dimensions, newDimensions);
@ -218,10 +213,9 @@ public class Capacity {
}
/**
* Returns value of capacity-dimension with specified index.
*
* <p/>
* <p>If capacity dimension does not exist, it returns 0 (rather than IndexOutOfBoundsException).
*
* @param index dimension index of the capacity value to be retrieved
@ -253,7 +247,6 @@ public class Capacity {
* @param toCompare the capacity to compare
* @return true if this capacity is greater or equal than toCompare
* @throws NullPointerException if one of the args is null
*/
public boolean isGreaterOrEqual(Capacity toCompare) {
if (toCompare == null) throw new NullPointerException();

Some files were not shown because too many files have changed in this diff Show more