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

merge min-waiting-time branch

This commit is contained in:
oblonski 2015-09-12 13:37:03 +02:00
commit a9d1e03c56
27 changed files with 2898 additions and 1944 deletions

View file

@ -91,8 +91,8 @@ public class PrettyAlgorithmBuilder {
constraintManager.addSkillsConstraint(); constraintManager.addSkillsConstraint();
stateManager.updateLoadStates(); stateManager.updateLoadStates();
stateManager.updateTimeWindowStates(); stateManager.updateTimeWindowStates();
UpdateVehicleDependentPracticalTimeWindows tw_updater = new UpdateVehicleDependentPracticalTimeWindows(stateManager, vrp.getTransportCosts()); UpdateVehicleDependentPracticalTimeWindows twUpdater = new UpdateVehicleDependentPracticalTimeWindows(stateManager, vrp.getTransportCosts());
tw_updater.setVehiclesToUpdate(new UpdateVehicleDependentPracticalTimeWindows.VehiclesToUpdate() { twUpdater.setVehiclesToUpdate(new UpdateVehicleDependentPracticalTimeWindows.VehiclesToUpdate() {
Map<VehicleTypeKey, Vehicle> uniqueTypes = new HashMap<VehicleTypeKey, Vehicle>(); Map<VehicleTypeKey, Vehicle> uniqueTypes = new HashMap<VehicleTypeKey, Vehicle>();
@ -109,12 +109,14 @@ public class PrettyAlgorithmBuilder {
vehicles.addAll(uniqueTypes.values()); vehicles.addAll(uniqueTypes.values());
return vehicles; return vehicles;
} }
}); });
stateManager.addStateUpdater(tw_updater); stateManager.addStateUpdater(twUpdater);
stateManager.updateSkillStates(); stateManager.updateSkillStates();
stateManager.addStateUpdater(new UpdateEndLocationIfRouteIsOpen()); stateManager.addStateUpdater(new UpdateEndLocationIfRouteIsOpen());
stateManager.addStateUpdater(new UpdateActivityTimes(vrp.getTransportCosts(), ActivityTimeTracker.ActivityPolicy.AS_SOON_AS_TIME_WINDOW_OPENS)); stateManager.addStateUpdater(new UpdateActivityTimes(vrp.getTransportCosts(), ActivityTimeTracker.ActivityPolicy.AS_SOON_AS_TIME_WINDOW_OPENS));
stateManager.addStateUpdater(new UpdateVariableCosts(vrp.getActivityCosts(), vrp.getTransportCosts(), stateManager)); stateManager.addStateUpdater(new UpdateVariableCosts(vrp.getActivityCosts(), vrp.getTransportCosts(), stateManager));
stateManager.addStateUpdater(new UpdateFutureWaitingTimes(stateManager,vrp.getTransportCosts()));
} }
VehicleRoutingAlgorithm vra = new VehicleRoutingAlgorithm(vrp, searchStrategyManager); VehicleRoutingAlgorithm vra = new VehicleRoutingAlgorithm(vrp, searchStrategyManager);
vra.addListener(stateManager); vra.addListener(stateManager);

View file

@ -20,6 +20,7 @@ import jsprit.core.algorithm.SearchStrategy.DiscoveredSolution;
import jsprit.core.algorithm.listener.*; import jsprit.core.algorithm.listener.*;
import jsprit.core.algorithm.termination.PrematureAlgorithmTermination; import jsprit.core.algorithm.termination.PrematureAlgorithmTermination;
import jsprit.core.problem.VehicleRoutingProblem; import jsprit.core.problem.VehicleRoutingProblem;
import jsprit.core.problem.job.Job;
import jsprit.core.problem.solution.VehicleRoutingProblemSolution; import jsprit.core.problem.solution.VehicleRoutingProblemSolution;
import jsprit.core.problem.solution.route.VehicleRoute; import jsprit.core.problem.solution.route.VehicleRoute;
import jsprit.core.problem.solution.route.activity.TourActivity; import jsprit.core.problem.solution.route.activity.TourActivity;
@ -35,6 +36,7 @@ import java.util.Collection;
* Algorithm that solves a {@link VehicleRoutingProblem}. * Algorithm that solves a {@link VehicleRoutingProblem}.
* *
* @author stefan schroeder * @author stefan schroeder
*
*/ */
public class VehicleRoutingAlgorithm { public class VehicleRoutingAlgorithm {
@ -194,6 +196,7 @@ public class VehicleRoutingAlgorithm {
Collection<VehicleRoutingProblemSolution> solutions = new ArrayList<VehicleRoutingProblemSolution>(initialSolutions); Collection<VehicleRoutingProblemSolution> solutions = new ArrayList<VehicleRoutingProblemSolution>(initialSolutions);
algorithmStarts(problem, solutions); algorithmStarts(problem, solutions);
bestEver = Solutions.bestOf(solutions); bestEver = Solutions.bestOf(solutions);
if(logger.isTraceEnabled()) log(solutions);
logger.info("iterations start"); logger.info("iterations start");
for(int i=0;i< maxIterations;i++){ for(int i=0;i< maxIterations;i++){
iterationStarts(i+1,problem,solutions); iterationStarts(i+1,problem,solutions);
@ -201,7 +204,7 @@ public class VehicleRoutingAlgorithm {
counter.incCounter(); counter.incCounter();
SearchStrategy strategy = searchStrategyManager.getRandomStrategy(); SearchStrategy strategy = searchStrategyManager.getRandomStrategy();
DiscoveredSolution discoveredSolution = strategy.run(problem, solutions); DiscoveredSolution discoveredSolution = strategy.run(problem, solutions);
logger.trace("discovered solution: {}", discoveredSolution); if(logger.isTraceEnabled()) log(discoveredSolution);
memorizeIfBestEver(discoveredSolution); memorizeIfBestEver(discoveredSolution);
selectedStrategy(discoveredSolution, problem, solutions); selectedStrategy(discoveredSolution, problem, solutions);
if (terminationManager.isPrematureBreak(discoveredSolution)) { if (terminationManager.isPrematureBreak(discoveredSolution)) {
@ -222,6 +225,39 @@ public class VehicleRoutingAlgorithm {
if (bestEver != null) solutions.add(bestEver); if (bestEver != null) solutions.add(bestEver);
} }
private void log(Collection<VehicleRoutingProblemSolution> solutions) {
for(VehicleRoutingProblemSolution sol : solutions) log(sol);
}
private void log(VehicleRoutingProblemSolution solution){
logger.trace("solution costs: {}",solution.getCost());
for(VehicleRoute r : solution.getRoutes()){
StringBuilder b = new StringBuilder();
b.append(r.getVehicle().getId()).append(" : ").append("[ ");
for(TourActivity act : r.getActivities()){
if(act instanceof TourActivity.JobActivity){
b.append(((TourActivity.JobActivity) act).getJob().getId()).append(" ");
}
}
b.append("]");
logger.trace(b.toString());
}
StringBuilder b = new StringBuilder();
b.append("unassigned : [ ");
for(Job j : solution.getUnassignedJobs()){
b.append(j.getId()).append(" ");
}
b.append("]");
logger.trace(b.toString());
}
private void log(DiscoveredSolution discoveredSolution) {
logger.trace("discovered solution: {}",discoveredSolution);
log(discoveredSolution.getSolution());
}
private void memorizeIfBestEver(DiscoveredSolution discoveredSolution) { private void memorizeIfBestEver(DiscoveredSolution discoveredSolution) {
if (discoveredSolution == null) return; if (discoveredSolution == null) return;
if (bestEver == null) bestEver = discoveredSolution.getSolution(); if (bestEver == null) bestEver = discoveredSolution.getSolution();

View file

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

View file

@ -0,0 +1,40 @@
package jsprit.core.algorithm.recreate;
import jsprit.core.algorithm.recreate.listener.InsertionStartsListener;
import jsprit.core.algorithm.recreate.listener.JobInsertedListener;
import jsprit.core.problem.VehicleRoutingProblem;
import jsprit.core.problem.job.Job;
import jsprit.core.problem.solution.route.VehicleRoute;
import java.util.Collection;
/**
* Created by schroeder on 22/07/15.
*/
public class ConfigureLocalActivityInsertionCalculator implements InsertionStartsListener, JobInsertedListener {
private VehicleRoutingProblem vrp;
private LocalActivityInsertionCostsCalculator localActivityInsertionCostsCalculator;
private int nuOfJobsToRecreate;
public ConfigureLocalActivityInsertionCalculator(VehicleRoutingProblem vrp, LocalActivityInsertionCostsCalculator localActivityInsertionCostsCalculator) {
this.vrp = vrp;
this.localActivityInsertionCostsCalculator = localActivityInsertionCostsCalculator;
}
@Override
public void informInsertionStarts(Collection<VehicleRoute> vehicleRoutes, Collection<Job> unassignedJobs) {
this.nuOfJobsToRecreate = unassignedJobs.size();
double completenessRatio = (1-((double)nuOfJobsToRecreate/(double)vrp.getJobs().values().size()));
localActivityInsertionCostsCalculator.setSolutionCompletenessRatio(Math.max(0.5,completenessRatio));
}
@Override
public void informJobInserted(Job job2insert, VehicleRoute inRoute, double additionalCosts, double additionalTime) {
nuOfJobsToRecreate--;
double completenessRatio = (1-((double)nuOfJobsToRecreate/(double)vrp.getJobs().values().size()));
localActivityInsertionCostsCalculator.setSolutionCompletenessRatio(Math.max(0.5,completenessRatio));
}
}

View file

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

View file

@ -1,3 +1,4 @@
/******************************************************************************* /*******************************************************************************
* Copyright (C) 2014 Stefan Schroeder * Copyright (C) 2014 Stefan Schroeder
* *
@ -17,21 +18,25 @@
package jsprit.core.algorithm.recreate; package jsprit.core.algorithm.recreate;
import jsprit.core.algorithm.state.InternalStates;
import jsprit.core.problem.cost.VehicleRoutingActivityCosts; import jsprit.core.problem.cost.VehicleRoutingActivityCosts;
import jsprit.core.problem.cost.VehicleRoutingTransportCosts; import jsprit.core.problem.cost.VehicleRoutingTransportCosts;
import jsprit.core.problem.misc.JobInsertionContext; import jsprit.core.problem.misc.JobInsertionContext;
import jsprit.core.problem.solution.route.activity.End; import jsprit.core.problem.solution.route.activity.End;
import jsprit.core.problem.solution.route.activity.TourActivity; import jsprit.core.problem.solution.route.activity.TourActivity;
import jsprit.core.problem.solution.route.state.RouteAndActivityStateGetter;
import jsprit.core.problem.vehicle.Vehicle;
import jsprit.core.util.CalculationUtils; import jsprit.core.util.CalculationUtils;
/** /**
* Calculates activity insertion costs locally, i.e. by comparing the additional costs of insertion the new activity k between * 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). * activity i (prevAct) and j (nextAct).
* Additional costs are then basically calculated as delta c = c_ik + c_kj - c_ij. * 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. * <p>Note once time has an effect on costs this class requires activity endTimes.
* *
* @author stefan * @author stefan
*
*/ */
class LocalActivityInsertionCostsCalculator implements ActivityInsertionCostsCalculator{ class LocalActivityInsertionCostsCalculator implements ActivityInsertionCostsCalculator{
@ -39,11 +44,17 @@ class LocalActivityInsertionCostsCalculator implements ActivityInsertionCostsCal
private VehicleRoutingActivityCosts activityCosts; private VehicleRoutingActivityCosts activityCosts;
private double activityCostsWeight = 1.;
public LocalActivityInsertionCostsCalculator(VehicleRoutingTransportCosts routingCosts, VehicleRoutingActivityCosts actCosts) { private double solutionCompletenessRatio = 1.;
private RouteAndActivityStateGetter stateManager;
public LocalActivityInsertionCostsCalculator(VehicleRoutingTransportCosts routingCosts, VehicleRoutingActivityCosts actCosts, RouteAndActivityStateGetter stateManager) {
super(); super();
this.routingCosts = routingCosts; this.routingCosts = routingCosts;
this.activityCosts = actCosts; this.activityCosts = actCosts;
this.stateManager = stateManager;
} }
@Override @Override
@ -53,34 +64,50 @@ class LocalActivityInsertionCostsCalculator implements ActivityInsertionCostsCal
double tp_time_prevAct_newAct = routingCosts.getTransportTime(prevAct.getLocation(), newAct.getLocation(), depTimeAtPrevAct, iFacts.getNewDriver(), iFacts.getNewVehicle()); double tp_time_prevAct_newAct = routingCosts.getTransportTime(prevAct.getLocation(), newAct.getLocation(), depTimeAtPrevAct, iFacts.getNewDriver(), iFacts.getNewVehicle());
double newAct_arrTime = depTimeAtPrevAct + tp_time_prevAct_newAct; double newAct_arrTime = depTimeAtPrevAct + tp_time_prevAct_newAct;
double newAct_endTime = CalculationUtils.getActivityEndTime(newAct_arrTime, newAct); double newAct_endTime = CalculationUtils.getActivityEndTime(newAct_arrTime, newAct);
double act_costs_newAct = activityCosts.getActivityCost(newAct, newAct_arrTime, iFacts.getNewDriver(), iFacts.getNewVehicle()); double act_costs_newAct = activityCosts.getActivityCost(newAct, newAct_arrTime, iFacts.getNewDriver(), iFacts.getNewVehicle());
//open routes if(isEnd(nextAct) && !toDepot(iFacts.getNewVehicle())) return tp_costs_prevAct_newAct;
if (nextAct instanceof End) {
if (!iFacts.getNewVehicle().isReturnToDepot()) {
return tp_costs_prevAct_newAct;
}
}
double tp_costs_newAct_nextAct = routingCosts.getTransportCost(newAct.getLocation(), nextAct.getLocation(), newAct_endTime, iFacts.getNewDriver(), iFacts.getNewVehicle()); double tp_costs_newAct_nextAct = routingCosts.getTransportCost(newAct.getLocation(), nextAct.getLocation(), newAct_endTime, iFacts.getNewDriver(), iFacts.getNewVehicle());
double tp_time_newAct_nextAct = routingCosts.getTransportTime(newAct.getLocation(), nextAct.getLocation(), newAct_endTime, iFacts.getNewDriver(), iFacts.getNewVehicle()); double tp_time_newAct_nextAct = routingCosts.getTransportTime(newAct.getLocation(), nextAct.getLocation(), newAct_endTime, iFacts.getNewDriver(), iFacts.getNewVehicle());
double nextAct_arrTime = newAct_endTime + tp_time_newAct_nextAct; double nextAct_arrTime = newAct_endTime + tp_time_newAct_nextAct;
double endTime_nextAct_new = CalculationUtils.getActivityEndTime(nextAct_arrTime, nextAct);
double act_costs_nextAct = activityCosts.getActivityCost(nextAct, nextAct_arrTime, iFacts.getNewDriver(), iFacts.getNewVehicle()); double act_costs_nextAct = activityCosts.getActivityCost(nextAct, nextAct_arrTime, iFacts.getNewDriver(), iFacts.getNewVehicle());
double totalCosts = tp_costs_prevAct_newAct + tp_costs_newAct_nextAct + act_costs_newAct + act_costs_nextAct;
double oldCosts; double totalCosts = tp_costs_prevAct_newAct + tp_costs_newAct_nextAct + solutionCompletenessRatio * activityCostsWeight * (act_costs_newAct + act_costs_nextAct);
double oldCosts = 0.;
if(iFacts.getRoute().isEmpty()){ if(iFacts.getRoute().isEmpty()){
double tp_costs_prevAct_nextAct = routingCosts.getTransportCost(prevAct.getLocation(), nextAct.getLocation(), depTimeAtPrevAct, iFacts.getNewDriver(), iFacts.getNewVehicle()); double tp_costs_prevAct_nextAct = routingCosts.getTransportCost(prevAct.getLocation(), nextAct.getLocation(), depTimeAtPrevAct, iFacts.getNewDriver(), iFacts.getNewVehicle());
double arrTime_nextAct = routingCosts.getTransportTime(prevAct.getLocation(), nextAct.getLocation(), depTimeAtPrevAct, iFacts.getNewDriver(), iFacts.getNewVehicle()); oldCosts += tp_costs_prevAct_nextAct;
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 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 arrTime_nextAct = depTimeAtPrevAct + routingCosts.getTransportTime(prevAct.getLocation(), nextAct.getLocation(), prevAct.getEndTime(), iFacts.getRoute().getDriver(), iFacts.getRoute().getVehicle());
double endTime_nextAct_old = CalculationUtils.getActivityEndTime(arrTime_nextAct,nextAct);
double actCost_nextAct = activityCosts.getActivityCost(nextAct, arrTime_nextAct, iFacts.getRoute().getDriver(), iFacts.getRoute().getVehicle()); double actCost_nextAct = activityCosts.getActivityCost(nextAct, arrTime_nextAct, iFacts.getRoute().getDriver(), iFacts.getRoute().getVehicle());
oldCosts = tp_costs_prevAct_nextAct + actCost_nextAct;
double endTimeDelay_nextAct = Math.max(0, endTime_nextAct_new - endTime_nextAct_old);
Double futureWaiting = stateManager.getActivityState(nextAct, iFacts.getRoute().getVehicle(), InternalStates.FUTURE_WAITING, Double.class);
if (futureWaiting == null) futureWaiting = 0.;
double waitingTime_savings_timeUnit = Math.min(futureWaiting, endTimeDelay_nextAct);
double waitingTime_savings = waitingTime_savings_timeUnit * iFacts.getRoute().getVehicle().getType().getVehicleCostParams().perWaitingTimeUnit;
oldCosts += solutionCompletenessRatio * activityCostsWeight * waitingTime_savings;
oldCosts += tp_costs_prevAct_nextAct + solutionCompletenessRatio * activityCostsWeight * actCost_nextAct;
} }
return totalCosts - oldCosts; return totalCosts - oldCosts;
} }
private boolean toDepot(Vehicle newVehicle) {
return newVehicle.isReturnToDepot();
}
private boolean isEnd(TourActivity nextAct) {
return nextAct instanceof End;
}
public void setSolutionCompletenessRatio(double solutionCompletenessRatio) {
this.solutionCompletenessRatio = solutionCompletenessRatio;
}
} }

View file

@ -47,10 +47,11 @@ 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 * 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 * <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. * 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. * bigger vehicles can take over the route that was previously served by a small vehicle.
*
*/ */
private boolean vehicleSwitchAllowed = false; private boolean vehicleSwitchAllowed = false;
@ -59,7 +60,7 @@ final class VehicleTypeDependentJobInsertionCalculator implements JobInsertionCo
this.insertionCalculator = jobInsertionCalc; this.insertionCalculator = jobInsertionCalc;
this.vrp = vrp; this.vrp = vrp;
getInitialVehicleIds(); getInitialVehicleIds();
logger.debug("initialise {}", this); logger.debug("initialise " + this);
} }
private void getInitialVehicleIds() { private void getInitialVehicleIds() {
@ -88,7 +89,7 @@ final class VehicleTypeDependentJobInsertionCalculator implements JobInsertionCo
* @param vehicleSwitchAllowed the vehicleSwitchAllowed to set * @param vehicleSwitchAllowed the vehicleSwitchAllowed to set
*/ */
public void setVehicleSwitchAllowed(boolean vehicleSwitchAllowed) { public void setVehicleSwitchAllowed(boolean vehicleSwitchAllowed) {
logger.debug("set vehicleSwitchAllowed to {}", vehicleSwitchAllowed); logger.debug("set vehicleSwitchAllowed to " + vehicleSwitchAllowed);
this.vehicleSwitchAllowed = vehicleSwitchAllowed; this.vehicleSwitchAllowed = vehicleSwitchAllowed;
} }
@ -103,7 +104,8 @@ final class VehicleTypeDependentJobInsertionCalculator implements JobInsertionCo
if(vehicleSwitchAllowed && !isVehicleWithInitialRoute(selectedVehicle)){ if(vehicleSwitchAllowed && !isVehicleWithInitialRoute(selectedVehicle)){
relevantVehicles.addAll(fleetManager.getAvailableVehicles(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()); relevantVehicles.addAll(fleetManager.getAvailableVehicles());
} }
for(Vehicle v : relevantVehicles){ for(Vehicle v : relevantVehicles){

View file

@ -41,4 +41,12 @@ public class InternalStates {
public final static StateId PAST_MAXLOAD = new StateFactory.StateIdImpl("past_max_load", 9); public final static StateId PAST_MAXLOAD = new StateFactory.StateIdImpl("past_max_load", 9);
public static final StateId SKILLS = new StateFactory.StateIdImpl("skills", 10); public static final StateId SKILLS = new StateFactory.StateIdImpl("skills", 10);
public static final StateId WAITING = new StateFactory.StateIdImpl("waiting",11);
public static final StateId TIME_SLACK = new StateFactory.StateIdImpl("time_slack",12);
public static final StateId FUTURE_WAITING = new StateFactory.StateIdImpl("future_waiting",13);
public static final StateId EARLIEST_WITHOUT_WAITING = new StateFactory.StateIdImpl("earliest_without_waiting",14);
} }

View file

@ -0,0 +1,60 @@
/*******************************************************************************
* Copyright (C) 2014 Stefan Schroeder
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3.0 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library. If not, see <http://www.gnu.org/licenses/>.
******************************************************************************/
package jsprit.core.algorithm.state;
import jsprit.core.problem.cost.VehicleRoutingTransportCosts;
import jsprit.core.problem.solution.route.VehicleRoute;
import jsprit.core.problem.solution.route.activity.ReverseActivityVisitor;
import jsprit.core.problem.solution.route.activity.TourActivity;
/**
* Updates and memorizes latest operation start times at activities.
*
* @author schroeder
*
*/
public class UpdateFutureWaitingTimes implements ReverseActivityVisitor, StateUpdater{
private StateManager states;
private VehicleRoute route;
private VehicleRoutingTransportCosts transportCosts;
private double futureWaiting;
public UpdateFutureWaitingTimes(StateManager states, VehicleRoutingTransportCosts tpCosts) {
super();
this.states = states;
this.transportCosts = tpCosts;
}
@Override
public void begin(VehicleRoute route) {
this.route = route;
this.futureWaiting = 0.;
}
@Override
public void visit(TourActivity activity) {
states.putInternalTypedActivityState(activity,route.getVehicle(),InternalStates.FUTURE_WAITING,futureWaiting);
futureWaiting += Math.max(activity.getTheoreticalEarliestOperationStartTime() - activity.getArrTime(),0);
}
@Override
public void finish() {}
}

View file

@ -19,15 +19,26 @@ package jsprit.core.algorithm.state;
import jsprit.core.problem.Location; import jsprit.core.problem.Location;
import jsprit.core.problem.cost.VehicleRoutingTransportCosts; import jsprit.core.problem.cost.VehicleRoutingTransportCosts;
import jsprit.core.problem.solution.route.RouteVisitor;
import jsprit.core.problem.solution.route.VehicleRoute; import jsprit.core.problem.solution.route.VehicleRoute;
import jsprit.core.problem.solution.route.activity.ReverseActivityVisitor;
import jsprit.core.problem.solution.route.activity.TourActivity; import jsprit.core.problem.solution.route.activity.TourActivity;
import jsprit.core.problem.vehicle.Vehicle; import jsprit.core.problem.vehicle.Vehicle;
import java.util.Arrays; import java.util.Arrays;
import java.util.Collection; import java.util.Collection;
import java.util.Iterator;
public class UpdateVehicleDependentPracticalTimeWindows implements ReverseActivityVisitor, StateUpdater { public class UpdateVehicleDependentPracticalTimeWindows implements RouteVisitor, StateUpdater{
@Override
public void visit(VehicleRoute route) {
begin(route);
Iterator<TourActivity> revIterator = route.getTourActivities().reverseActivityIterator();
while(revIterator.hasNext()){
visit(revIterator.next());
}
finish();
}
public static interface VehiclesToUpdate { public static interface VehiclesToUpdate {
@ -68,7 +79,7 @@ public class UpdateVehicleDependentPracticalTimeWindows implements ReverseActivi
this.vehiclesToUpdate = vehiclesToUpdate; this.vehiclesToUpdate = vehiclesToUpdate;
} }
@Override
public void begin(VehicleRoute route) { public void begin(VehicleRoute route) {
this.route = route; this.route = route;
vehicles = vehiclesToUpdate.get(route); vehicles = vehiclesToUpdate.get(route);
@ -78,7 +89,7 @@ public class UpdateVehicleDependentPracticalTimeWindows implements ReverseActivi
} }
} }
@Override
public void visit(TourActivity activity) { public void visit(TourActivity activity) {
for(Vehicle vehicle : vehicles){ for(Vehicle vehicle : vehicles){
double latestArrTimeAtPrevAct = latest_arrTimes_at_prevAct[vehicle.getVehicleTypeIdentifier().getIndex()]; double latestArrTimeAtPrevAct = latest_arrTimes_at_prevAct[vehicle.getVehicleTypeIdentifier().getIndex()];
@ -92,9 +103,8 @@ public class UpdateVehicleDependentPracticalTimeWindows implements ReverseActivi
} }
} }
@Override
public void finish() { public void finish() {}
}
} }

View file

@ -18,7 +18,7 @@ package jsprit.core.problem;
import jsprit.core.problem.cost.VehicleRoutingActivityCosts; import jsprit.core.problem.cost.VehicleRoutingActivityCosts;
import jsprit.core.problem.cost.VehicleRoutingTransportCosts; import jsprit.core.problem.cost.VehicleRoutingTransportCosts;
import jsprit.core.problem.driver.Driver; import jsprit.core.problem.cost.WaitingTimeCosts;
import jsprit.core.problem.job.Job; import jsprit.core.problem.job.Job;
import jsprit.core.problem.job.Service; import jsprit.core.problem.job.Service;
import jsprit.core.problem.job.Shipment; import jsprit.core.problem.job.Shipment;
@ -41,15 +41,18 @@ import java.util.*;
/** /**
* Contains and defines the vehicle routing problem. * Contains and defines the vehicle routing problem.
* <p/> *
* <p>A routing problem is defined as jobs, vehicles, costs and constraints. * <p>A routing problem is defined as jobs, vehicles, costs and constraints.
* <p/> *
* <p> To construct the problem, use VehicleRoutingProblem.Builder. Get an instance of this by using the static method VehicleRoutingProblem.Builder.newInstance(). * <p> To construct the problem, use VehicleRoutingProblem.Builder. Get an instance of this by using the static method VehicleRoutingProblem.Builder.newInstance().
* <p/> *
* <p>By default, fleetSize is INFINITE, transport-costs are calculated as euclidean-distance (CrowFlyCosts), * <p>By default, fleetSize is INFINITE, transport-costs are calculated as euclidean-distance (CrowFlyCosts),
* and activity-costs are set to zero. * and activity-costs are set to zero.
* *
*
*
* @author stefan schroeder * @author stefan schroeder
*
*/ */
public class VehicleRoutingProblem { public class VehicleRoutingProblem {
@ -57,34 +60,22 @@ public class VehicleRoutingProblem {
* Builder to build the routing-problem. * Builder to build the routing-problem.
* *
* @author stefan schroeder * @author stefan schroeder
*
*/ */
public static class Builder { public static class Builder {
/** /**
* Returns a new instance of this builder. * Returns a new instance of this builder.
* *
* @return builder * @return builder
*/ */
public static Builder newInstance() { public static Builder newInstance(){ return new Builder(); }
return new Builder();
}
private VehicleRoutingTransportCosts transportCosts; private VehicleRoutingTransportCosts transportCosts;
private VehicleRoutingActivityCosts activityCosts = new VehicleRoutingActivityCosts() { private VehicleRoutingActivityCosts activityCosts = new WaitingTimeCosts();
@Override
public double getActivityCost(TourActivity tourAct, double arrivalTime, Driver driver, Vehicle vehicle) {
return 0;
}
@Override
public String toString() {
return "[name=defaultActivityCosts]";
}
};
private Map<String,Job> jobs = new LinkedHashMap<String, Job>(); private Map<String,Job> jobs = new LinkedHashMap<String, Job>();
@ -109,7 +100,8 @@ public class VehicleRoutingProblem {
List<AbstractActivity> acts = new ArrayList<AbstractActivity>(); List<AbstractActivity> acts = new ArrayList<AbstractActivity>();
if(job instanceof Service){ if(job instanceof Service){
acts.add(serviceActivityFactory.createActivity((Service) job)); acts.add(serviceActivityFactory.createActivity((Service) job));
} else if (job instanceof Shipment) { }
else if(job instanceof Shipment){
acts.add(shipmentActivityFactory.createPickup((Shipment) job)); acts.add(shipmentActivityFactory.createPickup((Shipment) job));
acts.add(shipmentActivityFactory.createDelivery((Shipment) job)); acts.add(shipmentActivityFactory.createDelivery((Shipment) job));
} }
@ -142,9 +134,7 @@ public class VehicleRoutingProblem {
activityIndexCounter++; activityIndexCounter++;
} }
private void incVehicleTypeIdIndexCounter() { private void incVehicleTypeIdIndexCounter() { vehicleTypeIdIndexCounter++; }
vehicleTypeIdIndexCounter++;
}
/** /**
* Returns the unmodifiable map of collected locations (mapped by their location-id). * Returns the unmodifiable map of collected locations (mapped by their location-id).
@ -157,11 +147,12 @@ public class VehicleRoutingProblem {
/** /**
* Returns the locations collected SO FAR by this builder. * Returns the locations collected SO FAR by this builder.
* <p/> *
* <p>Locations are cached when adding a shipment, service, depot, vehicle. * <p>Locations are cached when adding a shipment, service, depot, vehicle.
* *
* @return locations * @return locations
*/ *
**/
public Locations getLocations(){ public Locations getLocations(){
return new Locations() { return new Locations() {
@ -188,7 +179,7 @@ public class VehicleRoutingProblem {
/** /**
* Sets the type of fleetSize. * Sets the type of fleetSize.
* <p/> *
* <p>FleetSize is either FleetSize.INFINITE or FleetSize.FINITE. By default it is FleetSize.INFINITE. * <p>FleetSize is either FleetSize.INFINITE or FleetSize.FINITE. By default it is FleetSize.INFINITE.
* *
* @param fleetSize the fleet size used in this problem. it can either be FleetSize.INFINITE or FleetSize.FINITE * @param fleetSize the fleet size used in this problem. it can either be FleetSize.INFINITE or FleetSize.FINITE
@ -201,7 +192,7 @@ public class VehicleRoutingProblem {
/** /**
* Adds a job which is either a service or a shipment. * Adds a job which is either a service or a shipment.
* <p/> *
* <p>Note that job.getId() must be unique, i.e. no job (either it is a shipment or a service) is allowed to have an already allocated id. * <p>Note that job.getId() must be unique, i.e. no job (either it is a shipment or a service) is allowed to have an already allocated id.
* *
* @param job job to be added * @param job job to be added
@ -217,7 +208,7 @@ public class VehicleRoutingProblem {
/** /**
* Adds a job which is either a service or a shipment. * Adds a job which is either a service or a shipment.
* <p/> *
* <p>Note that job.getId() must be unique, i.e. no job (either it is a shipment or a service) is allowed to have an already allocated id. * <p>Note that job.getId() must be unique, i.e. no job (either it is a shipment or a service) is allowed to have an already allocated id.
* *
* @param job job to be added * @param job job to be added
@ -225,10 +216,8 @@ public class VehicleRoutingProblem {
* @throws IllegalStateException if job is neither a shipment nor a service, or jobId has already been added. * @throws IllegalStateException if job is neither a shipment nor a service, or jobId has already been added.
*/ */
public Builder addJob(AbstractJob job) { public Builder addJob(AbstractJob job) {
if (tentativeJobs.containsKey(job.getId())) if(tentativeJobs.containsKey(job.getId())) throw new IllegalStateException("jobList already contains a job with id " + job.getId() + ". make sure you use unique ids for your jobs (i.e. service and shipments)");
throw new IllegalStateException("jobList already contains a job with id " + job.getId() + ". make sure you use unique ids for your jobs (i.e. service and shipments)"); if(!(job instanceof Service || job instanceof Shipment)) throw new IllegalStateException("job must be either a service or a shipment");
if (!(job instanceof Service || job instanceof Shipment))
throw new IllegalStateException("job must be either a service or a shipment");
job.setIndex(jobIndexCounter); job.setIndex(jobIndexCounter);
incJobIndexCounter(); incJobIndexCounter();
tentativeJobs.put(job.getId(), job); tentativeJobs.put(job.getId(), job);
@ -239,7 +228,8 @@ public class VehicleRoutingProblem {
private void addLocationToTentativeLocations(Job job) { private void addLocationToTentativeLocations(Job job) {
if(job instanceof Service) { if(job instanceof Service) {
tentative_coordinates.put(((Service)job).getLocation().getId(), ((Service)job).getLocation().getCoordinate()); tentative_coordinates.put(((Service)job).getLocation().getId(), ((Service)job).getLocation().getCoordinate());
} else if (job instanceof Shipment) { }
else if(job instanceof Shipment){
Shipment shipment = (Shipment)job; Shipment shipment = (Shipment)job;
tentative_coordinates.put(shipment.getPickupLocation().getId(), shipment.getPickupLocation().getCoordinate()); tentative_coordinates.put(shipment.getPickupLocation().getId(), shipment.getPickupLocation().getCoordinate());
tentative_coordinates.put(shipment.getDeliveryLocation().getId(), shipment.getDeliveryLocation().getCoordinate()); tentative_coordinates.put(shipment.getDeliveryLocation().getId(), shipment.getDeliveryLocation().getCoordinate());
@ -250,7 +240,8 @@ public class VehicleRoutingProblem {
if(job instanceof Service) { if(job instanceof Service) {
Service service = (Service) job; Service service = (Service) job;
addService(service); addService(service);
} else if (job instanceof Shipment) { }
else if(job instanceof Shipment){
Shipment shipment = (Shipment)job; Shipment shipment = (Shipment)job;
addShipment(shipment); addShipment(shipment);
} }
@ -287,8 +278,7 @@ public class VehicleRoutingProblem {
} }
private void registerLocation(Job job) { private void registerLocation(Job job) {
if (job instanceof Service) if (job instanceof Service) tentative_coordinates.put(((Service) job).getLocation().getId(), ((Service) job).getLocation().getCoordinate());
tentative_coordinates.put(((Service) job).getLocation().getId(), ((Service) job).getLocation().getCoordinate());
if (job instanceof Shipment) { if (job instanceof Shipment) {
Shipment shipment = (Shipment) job; Shipment shipment = (Shipment) job;
tentative_coordinates.put(shipment.getPickupLocation().getId(), shipment.getPickupLocation().getCoordinate()); tentative_coordinates.put(shipment.getPickupLocation().getId(), shipment.getPickupLocation().getCoordinate());
@ -319,9 +309,7 @@ public class VehicleRoutingProblem {
} }
private void addShipment(Shipment job) { private void addShipment(Shipment job) {
if (jobs.containsKey(job.getId())) { if(jobs.containsKey(job.getId())){ logger.warn("job " + job + " already in job list. overrides existing job."); }
logger.warn("job {} already in job list. overrides existing job.", job);
}
tentative_coordinates.put(job.getPickupLocation().getId(), job.getPickupLocation().getCoordinate()); tentative_coordinates.put(job.getPickupLocation().getId(), job.getPickupLocation().getCoordinate());
tentative_coordinates.put(job.getDeliveryLocation().getId(), job.getDeliveryLocation().getCoordinate()); tentative_coordinates.put(job.getDeliveryLocation().getId(), job.getDeliveryLocation().getCoordinate());
jobs.put(job.getId(),job); jobs.put(job.getId(),job);
@ -330,20 +318,21 @@ public class VehicleRoutingProblem {
/** /**
* Adds a vehicle. * Adds a vehicle.
* *
*
* @param vehicle vehicle to be added * @param vehicle vehicle to be added
* @return this builder * @return this builder
* @deprecated use addVehicle(AbstractVehicle vehicle) instead * @deprecated use addVehicle(AbstractVehicle vehicle) instead
*/ */
@Deprecated @Deprecated
public Builder addVehicle(Vehicle vehicle) { public Builder addVehicle(Vehicle vehicle) {
if (!(vehicle instanceof AbstractVehicle)) if(!(vehicle instanceof AbstractVehicle)) throw new IllegalStateException("vehicle must be an AbstractVehicle");
throw new IllegalStateException("vehicle must be an AbstractVehicle");
return addVehicle((AbstractVehicle)vehicle); return addVehicle((AbstractVehicle)vehicle);
} }
/** /**
* Adds a vehicle. * Adds a vehicle.
* *
*
* @param vehicle vehicle to be added * @param vehicle vehicle to be added
* @return this builder * @return this builder
*/ */
@ -354,7 +343,8 @@ public class VehicleRoutingProblem {
} }
if(typeKeyIndices.containsKey(vehicle.getVehicleTypeIdentifier())){ if(typeKeyIndices.containsKey(vehicle.getVehicleTypeIdentifier())){
vehicle.getVehicleTypeIdentifier().setIndex(typeKeyIndices.get(vehicle.getVehicleTypeIdentifier())); vehicle.getVehicleTypeIdentifier().setIndex(typeKeyIndices.get(vehicle.getVehicleTypeIdentifier()));
} else { }
else {
vehicle.getVehicleTypeIdentifier().setIndex(vehicleTypeIdIndexCounter); vehicle.getVehicleTypeIdentifier().setIndex(vehicleTypeIdIndexCounter);
typeKeyIndices.put(vehicle.getVehicleTypeIdentifier(),vehicleTypeIdIndexCounter); typeKeyIndices.put(vehicle.getVehicleTypeIdentifier(),vehicleTypeIdIndexCounter);
incVehicleTypeIdIndexCounter(); incVehicleTypeIdIndexCounter();
@ -377,7 +367,7 @@ public class VehicleRoutingProblem {
/** /**
* Sets the activity-costs. * Sets the activity-costs.
* <p/> *
* <p>By default it is set to zero. * <p>By default it is set to zero.
* *
* @param activityCosts activity costs of the problem * @param activityCosts activity costs of the problem
@ -391,7 +381,7 @@ public class VehicleRoutingProblem {
/** /**
* Builds the {@link VehicleRoutingProblem}. * Builds the {@link VehicleRoutingProblem}.
* <p/> *
* <p>If {@link VehicleRoutingTransportCosts} are not set, {@link CrowFlyCosts} is used. * <p>If {@link VehicleRoutingTransportCosts} are not set, {@link CrowFlyCosts} is used.
* *
* @return {@link VehicleRoutingProblem} * @return {@link VehicleRoutingProblem}
@ -484,6 +474,7 @@ public class VehicleRoutingProblem {
* Enum that characterizes the fleet-size. * Enum that characterizes the fleet-size.
* *
* @author sschroeder * @author sschroeder
*
*/ */
public static enum FleetSize { public static enum FleetSize {
FINITE, INFINITE FINITE, INFINITE
@ -564,7 +555,7 @@ public class VehicleRoutingProblem {
/** /**
* Returns type of fleetSize, either INFINITE or FINITE. * Returns type of fleetSize, either INFINITE or FINITE.
* <p/> *
* <p>By default, it is INFINITE. * <p>By default, it is INFINITE.
* *
* @return either FleetSize.INFINITE or FleetSize.FINITE * @return either FleetSize.INFINITE or FleetSize.FINITE
@ -651,9 +642,7 @@ public class VehicleRoutingProblem {
/** /**
* @return total number of activities * @return total number of activities
*/ */
public int getNuActivities() { public int getNuActivities(){ return nuActivities; }
return nuActivities;
}
/** /**
* @return factory that creates the activities associated to a job * @return factory that creates the activities associated to a job

View file

@ -0,0 +1,20 @@
package jsprit.core.problem.cost;
import jsprit.core.problem.driver.Driver;
import jsprit.core.problem.solution.route.activity.TourActivity;
import jsprit.core.problem.vehicle.Vehicle;
/**
* Created by schroeder on 23/07/15.
*/
public class WaitingTimeCosts implements VehicleRoutingActivityCosts {
@Override
public double getActivityCost(TourActivity tourAct, double arrivalTime, Driver driver, Vehicle vehicle) {
if(vehicle != null){
return vehicle.getType().getVehicleCostParams().perWaitingTimeUnit * Math.max(0.,tourAct.getTheoreticalEarliestOperationStartTime()-arrivalTime);
}
return 0;
}
}

View file

@ -25,6 +25,8 @@ import java.util.HashMap;
import java.util.Map; import java.util.Map;
class InfiniteVehicles implements VehicleFleetManager{ class InfiniteVehicles implements VehicleFleetManager{
private static Logger logger = LogManager.getLogger(InfiniteVehicles.class); private static Logger logger = LogManager.getLogger(InfiniteVehicles.class);
@ -35,7 +37,7 @@ class InfiniteVehicles implements VehicleFleetManager {
public InfiniteVehicles(Collection<Vehicle> vehicles){ public InfiniteVehicles(Collection<Vehicle> vehicles){
extractTypes(vehicles); extractTypes(vehicles);
logger.debug("initialise {}", this); logger.debug("initialise " + this);
} }
@Override @Override
@ -45,7 +47,7 @@ class InfiniteVehicles implements VehicleFleetManager {
private void extractTypes(Collection<Vehicle> vehicles) { private void extractTypes(Collection<Vehicle> vehicles) {
for(Vehicle v : vehicles){ for(Vehicle v : vehicles){
VehicleTypeKey typeKey = new VehicleTypeKey(v.getType().getTypeId(), v.getStartLocation().getId(), v.getEndLocation().getId(), v.getEarliestDeparture(), v.getLatestArrival(), v.getSkills()); VehicleTypeKey typeKey = new VehicleTypeKey(v.getType().getTypeId(), v.getStartLocation().getId(),v.getEndLocation().getId(), v.getEarliestDeparture(), v.getLatestArrival(), v.getSkills(), v.isReturnToDepot());
types.put(typeKey,v); types.put(typeKey,v);
// sortedTypes.add(typeKey); // sortedTypes.add(typeKey);
} }
@ -81,7 +83,7 @@ class InfiniteVehicles implements VehicleFleetManager {
@Override @Override
public Collection<Vehicle> getAvailableVehicles(Vehicle withoutThisType) { public Collection<Vehicle> getAvailableVehicles(Vehicle withoutThisType) {
Collection<Vehicle> vehicles = new ArrayList<Vehicle>(); Collection<Vehicle> vehicles = new ArrayList<Vehicle>();
VehicleTypeKey thisKey = new VehicleTypeKey(withoutThisType.getType().getTypeId(), withoutThisType.getStartLocation().getId(), withoutThisType.getEndLocation().getId(), withoutThisType.getEarliestDeparture(), withoutThisType.getLatestArrival(), withoutThisType.getSkills()); VehicleTypeKey thisKey = new VehicleTypeKey(withoutThisType.getType().getTypeId(), withoutThisType.getStartLocation().getId(), withoutThisType.getEndLocation().getId(), withoutThisType.getEarliestDeparture(), withoutThisType.getLatestArrival(), withoutThisType.getSkills(), withoutThisType.isReturnToDepot());
for(VehicleTypeKey key : types.keySet()){ for(VehicleTypeKey key : types.keySet()){
if(!key.equals(thisKey)){ if(!key.equals(thisKey)){
vehicles.add(types.get(key)); vehicles.add(types.get(key));

View file

@ -70,4 +70,5 @@ public interface Vehicle extends HasId, HasIndex {
public abstract VehicleTypeKey getVehicleTypeIdentifier(); public abstract VehicleTypeKey getVehicleTypeIdentifier();
public abstract Skills getSkills(); public abstract Skills getSkills();
} }

View file

@ -76,7 +76,7 @@ class VehicleFleetManagerImpl implements VehicleFleetManager {
this.vehicles = vehicles; this.vehicles = vehicles;
this.lockedVehicles = new HashSet<Vehicle>(); this.lockedVehicles = new HashSet<Vehicle>();
makeMap(); makeMap();
logger.debug("initialise {}", this); logger.debug("initialise " + this);
} }
@Override @Override
@ -96,7 +96,7 @@ class VehicleFleetManagerImpl implements VehicleFleetManager {
if(v.getType() == null){ if(v.getType() == null){
throw new IllegalStateException("vehicle needs type"); throw new IllegalStateException("vehicle needs type");
} }
VehicleTypeKey typeKey = new VehicleTypeKey(v.getType().getTypeId(), v.getStartLocation().getId(), v.getEndLocation().getId(), v.getEarliestDeparture(), v.getLatestArrival(), v.getSkills()); VehicleTypeKey typeKey = new VehicleTypeKey(v.getType().getTypeId(), v.getStartLocation().getId(), v.getEndLocation().getId(), v.getEarliestDeparture(), v.getLatestArrival(), v.getSkills(),v.isReturnToDepot() );
if(!typeMapOfAvailableVehicles.containsKey(typeKey)){ if(!typeMapOfAvailableVehicles.containsKey(typeKey)){
typeMapOfAvailableVehicles.put(typeKey, new TypeContainer()); typeMapOfAvailableVehicles.put(typeKey, new TypeContainer());
} }
@ -105,7 +105,7 @@ class VehicleFleetManagerImpl implements VehicleFleetManager {
} }
private void removeVehicle(Vehicle v){ private void removeVehicle(Vehicle v){
VehicleTypeKey key = new VehicleTypeKey(v.getType().getTypeId(), v.getStartLocation().getId(), v.getEndLocation().getId(), v.getEarliestDeparture(), v.getLatestArrival(), v.getSkills()); VehicleTypeKey key = new VehicleTypeKey(v.getType().getTypeId(), v.getStartLocation().getId(), v.getEndLocation().getId(), v.getEarliestDeparture(), v.getLatestArrival(), v.getSkills(),v.isReturnToDepot() );
if(typeMapOfAvailableVehicles.containsKey(key)){ if(typeMapOfAvailableVehicles.containsKey(key)){
typeMapOfAvailableVehicles.get(key).remove(v); typeMapOfAvailableVehicles.get(key).remove(v);
} }
@ -114,7 +114,7 @@ class VehicleFleetManagerImpl implements VehicleFleetManager {
/** /**
* Returns a collection of available vehicles. * Returns a collection of available vehicles.
* <p/> *
*<p>If there is no vehicle with a certain type and location anymore, it looks up whether a penalty vehicle has been specified with *<p>If there is no vehicle with a certain type and location anymore, it looks up whether a penalty vehicle has been specified with
* this type and location. If so, it returns this penalty vehicle. If not, no vehicle with this type and location is returned. * this type and location. If so, it returns this penalty vehicle. If not, no vehicle with this type and location is returned.
*/ */
@ -124,7 +124,8 @@ class VehicleFleetManagerImpl implements VehicleFleetManager {
for(VehicleTypeKey key : typeMapOfAvailableVehicles.keySet()){ for(VehicleTypeKey key : typeMapOfAvailableVehicles.keySet()){
if(!typeMapOfAvailableVehicles.get(key).isEmpty()){ if(!typeMapOfAvailableVehicles.get(key).isEmpty()){
vehicles.add(typeMapOfAvailableVehicles.get(key).getVehicle()); vehicles.add(typeMapOfAvailableVehicles.get(key).getVehicle());
} else { }
else{
if(penaltyVehicles.containsKey(key)){ if(penaltyVehicles.containsKey(key)){
vehicles.add(penaltyVehicles.get(key)); vehicles.add(penaltyVehicles.get(key));
} }
@ -136,12 +137,13 @@ class VehicleFleetManagerImpl implements VehicleFleetManager {
@Override @Override
public Collection<Vehicle> getAvailableVehicles(Vehicle withoutThisType) { public Collection<Vehicle> getAvailableVehicles(Vehicle withoutThisType) {
List<Vehicle> vehicles = new ArrayList<Vehicle>(); List<Vehicle> vehicles = new ArrayList<Vehicle>();
VehicleTypeKey thisKey = new VehicleTypeKey(withoutThisType.getType().getTypeId(), withoutThisType.getStartLocation().getId(), withoutThisType.getEndLocation().getId(), withoutThisType.getEarliestDeparture(), withoutThisType.getLatestArrival(), withoutThisType.getSkills()); VehicleTypeKey thisKey = new VehicleTypeKey(withoutThisType.getType().getTypeId(), withoutThisType.getStartLocation().getId(), withoutThisType.getEndLocation().getId(), withoutThisType.getEarliestDeparture(), withoutThisType.getLatestArrival(), withoutThisType.getSkills(),withoutThisType.isReturnToDepot() );
for(VehicleTypeKey key : typeMapOfAvailableVehicles.keySet()){ for(VehicleTypeKey key : typeMapOfAvailableVehicles.keySet()){
if(key.equals(thisKey)) continue; if(key.equals(thisKey)) continue;
if(!typeMapOfAvailableVehicles.get(key).isEmpty()){ if(!typeMapOfAvailableVehicles.get(key).isEmpty()){
vehicles.add(typeMapOfAvailableVehicles.get(key).getVehicle()); vehicles.add(typeMapOfAvailableVehicles.get(key).getVehicle());
} else { }
else{
if(penaltyVehicles.containsKey(key)){ if(penaltyVehicles.containsKey(key)){
vehicles.add(penaltyVehicles.get(key)); vehicles.add(penaltyVehicles.get(key));
} }

View file

@ -23,20 +23,25 @@ import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
/** /**
* Implementation of {@link Vehicle}. * Implementation of {@link Vehicle}.
* *
* @author stefan schroeder * @author stefan schroeder
*
*/ */
public class VehicleImpl extends AbstractVehicle{ public class VehicleImpl extends AbstractVehicle{
/** /**
* Extension of {@link VehicleImpl} representing an unspecified vehicle with the id 'noVehicle' * Extension of {@link VehicleImpl} representing an unspecified vehicle with the id 'noVehicle'
* (to avoid null). * (to avoid null).
* *
* @author schroeder * @author schroeder
*
*/ */
public static class NoVehicle extends AbstractVehicle { public static class NoVehicle extends AbstractVehicle {
@ -90,12 +95,13 @@ public class VehicleImpl extends AbstractVehicle {
/** /**
* Builder that builds the vehicle. * Builder that builds the vehicle.
* <p/> *
* <p>By default, earliestDepartureTime is 0.0, latestDepartureTime is Double.MAX_VALUE, * <p>By default, earliestDepartureTime is 0.0, latestDepartureTime is Double.MAX_VALUE,
* it returns to the depot and its {@link VehicleType} is the DefaultType with typeId equal to 'default' * it returns to the depot and its {@link VehicleType} is the DefaultType with typeId equal to 'default'
* and a capacity of 0. * and a capacity of 0.
* *
* @author stefan * @author stefan
*
*/ */
public static class Builder { public static class Builder {
@ -128,8 +134,8 @@ public class VehicleImpl extends AbstractVehicle {
* Sets the {@link VehicleType}.<br> * Sets the {@link VehicleType}.<br>
* *
* @param type the type to be set * @param type the type to be set
* @return this builder
* @throws IllegalStateException if type is null * @throws IllegalStateException if type is null
* @return this builder
*/ */
public Builder setType(VehicleType type){ public Builder setType(VehicleType type){
if(type==null) throw new IllegalStateException("type cannot be null."); if(type==null) throw new IllegalStateException("type cannot be null.");
@ -139,11 +145,11 @@ public class VehicleImpl extends AbstractVehicle {
/** /**
* Sets the flag whether the vehicle must return to depot or not. * Sets the flag whether the vehicle must return to depot or not.
* <p/> *
* <p>If returnToDepot is true, the vehicle must return to specified end-location. If you * <p>If returnToDepot is true, the vehicle must return to specified end-location. If you
* omit specifying the end-location, vehicle returns to start-location (that must to be set). If * omit specifying the end-location, vehicle returns to start-location (that must to be set). If
* you specify it, it returns to specified end-location. * you specify it, it returns to specified end-location.
* <p/> *
* <p>If returnToDepot is false, the end-location of the vehicle is endogenous. * <p>If returnToDepot is false, the end-location of the vehicle is endogenous.
* *
* @param returnToDepot true if vehicle need to return to depot, otherwise false * @param returnToDepot true if vehicle need to return to depot, otherwise false
@ -156,7 +162,6 @@ public class VehicleImpl extends AbstractVehicle {
/** /**
* Sets start location. * Sets start location.
*
* @param startLocation start location * @param startLocation start location
* @return start location * @return start location
*/ */
@ -199,10 +204,10 @@ public class VehicleImpl extends AbstractVehicle {
/** /**
* Builds and returns the vehicle. * Builds and returns the vehicle.
* <p/> *
* <p>if {@link VehicleType} is not set, default vehicle-type is set with id="default" and * <p>if {@link VehicleType} is not set, default vehicle-type is set with id="default" and
* capacity=0 * capacity=0
* <p/> *
* <p>if startLocationId || locationId is null (=> startLocationCoordinate || locationCoordinate must be set) then startLocationId=startLocationCoordinate.toString() * <p>if startLocationId || locationId is null (=> startLocationCoordinate || locationCoordinate must be set) then startLocationId=startLocationCoordinate.toString()
* and locationId=locationCoordinate.toString() [coord.toString() --> [x=x_val][y=y_val]) * and locationId=locationCoordinate.toString() [coord.toString() --> [x=x_val][y=y_val])
* <p>if endLocationId is null and endLocationCoordinate is set then endLocationId=endLocationCoordinate.toString() * <p>if endLocationId is null and endLocationCoordinate is set then endLocationId=endLocationCoordinate.toString()
@ -215,8 +220,7 @@ public class VehicleImpl extends AbstractVehicle {
*/ */
public VehicleImpl build(){ public VehicleImpl build(){
if(startLocation != null && endLocation != null){ if(startLocation != null && endLocation != null){
if (!startLocation.getId().equals(endLocation.getId()) && !returnToDepot) if( !startLocation.getId().equals(endLocation.getId()) && !returnToDepot) throw new IllegalStateException("this must not be. you specified both endLocationId and open-routes. this is contradictory. <br>" +
throw new IllegalStateException("this must not be. you specified both endLocationId and open-routes. this is contradictory. <br>" +
"if you set endLocation, returnToDepot must be true. if returnToDepot is false, endLocationCoord must not be specified."); "if you set endLocation, returnToDepot must be true. if returnToDepot is false, endLocationCoord must not be specified.");
} }
if (startLocation != null && endLocation == null) { if (startLocation != null && endLocation == null) {
@ -235,9 +239,7 @@ public class VehicleImpl extends AbstractVehicle {
* @param vehicleId the id of the vehicle which must be a unique identifier among all vehicles * @param vehicleId the id of the vehicle which must be a unique identifier among all vehicles
* @return vehicle builder * @return vehicle builder
*/ */
public static Builder newInstance(String vehicleId) { public static Builder newInstance(String vehicleId){ return new Builder(vehicleId); }
return new Builder(vehicleId);
}
public Builder addSkills(Skills skills) { public Builder addSkills(Skills skills) {
this.skillBuilder.addAllSkills(skills.values()); this.skillBuilder.addAllSkills(skills.values());
@ -247,7 +249,7 @@ public class VehicleImpl extends AbstractVehicle {
/** /**
* Returns empty/noVehicle which is a vehicle having no capacity, no type and no reasonable id. * Returns empty/noVehicle which is a vehicle having no capacity, no type and no reasonable id.
* <p/> *
* <p>NoVehicle has id="noVehicle" and extends {@link VehicleImpl} * <p>NoVehicle has id="noVehicle" and extends {@link VehicleImpl}
* *
* @return emptyVehicle * @return emptyVehicle
@ -286,7 +288,7 @@ public class VehicleImpl extends AbstractVehicle {
/** /**
* Returns String with attributes of this vehicle * Returns String with attributes of this vehicle
* <p/> *
* <p>String has the following format [attr1=val1][attr2=val2]...[attrn=valn] * <p>String has the following format [attr1=val1][attr2=val2]...[attrn=valn]
*/ */
@Override @Override
@ -377,4 +379,6 @@ public class VehicleImpl extends AbstractVehicle {
} }
} }

View file

@ -21,10 +21,11 @@ import jsprit.core.problem.Capacity;
/** /**
* Implementation of {@link VehicleType}. * Implementation of {@link VehicleType}.
* <p/> *
* <p>Two vehicle-types are equal if they have the same typeId. * <p>Two vehicle-types are equal if they have the same typeId.
* *
* @author schroeder * @author schroeder
*
*/ */
public class VehicleTypeImpl implements VehicleType { public class VehicleTypeImpl implements VehicleType {
@ -32,6 +33,7 @@ public class VehicleTypeImpl implements VehicleType {
* CostParameter consisting of fixed cost parameter, time-based cost parameter and distance-based cost parameter. * CostParameter consisting of fixed cost parameter, time-based cost parameter and distance-based cost parameter.
* *
* @author schroeder * @author schroeder
*
*/ */
public static class VehicleCostParams { public static class VehicleCostParams {
@ -40,19 +42,32 @@ public class VehicleTypeImpl implements VehicleType {
} }
public final double fix; public final double fix;
@Deprecated
public final double perTimeUnit; public final double perTimeUnit;
public final double perTransportTimeUnit;
public final double perDistanceUnit; public final double perDistanceUnit;
public final double perWaitingTimeUnit;
private VehicleCostParams(double fix, double perTimeUnit,double perDistanceUnit) { private VehicleCostParams(double fix, double perTimeUnit,double perDistanceUnit) {
super(); super();
this.fix = fix; this.fix = fix;
this.perTimeUnit = perTimeUnit; this.perTimeUnit = perTimeUnit;
this.perTransportTimeUnit = perTimeUnit;
this.perDistanceUnit = perDistanceUnit; this.perDistanceUnit = perDistanceUnit;
this.perWaitingTimeUnit = 0.;
}
public VehicleCostParams(double fix, double perTimeUnit, double perDistanceUnit, double perWaitingTimeUnit) {
this.fix = fix;
this.perTimeUnit = perTimeUnit;
this.perTransportTimeUnit = perTimeUnit;
this.perDistanceUnit = perDistanceUnit;
this.perWaitingTimeUnit = perWaitingTimeUnit;
} }
@Override @Override
public String toString() { public String toString() {
return "[fixed=" + fix + "][perTime=" + perTimeUnit + "][perDistance=" + perDistanceUnit + "]"; return "[fixed="+fix+"][perTime="+perTransportTimeUnit+"][perDistance="+perDistanceUnit+"][perWaitingTimeUnit="+perWaitingTimeUnit+"]";
} }
} }
@ -60,9 +75,12 @@ public class VehicleTypeImpl implements VehicleType {
* Builder that builds the vehicle-type. * Builder that builds the vehicle-type.
* *
* @author schroeder * @author schroeder
*
*/ */
public static class Builder{ public static class Builder{
public static VehicleTypeImpl.Builder newInstance(String id) { public static VehicleTypeImpl.Builder newInstance(String id) {
if(id==null) throw new IllegalStateException(); if(id==null) throw new IllegalStateException();
return new Builder(id); return new Builder(id);
@ -77,6 +95,7 @@ public class VehicleTypeImpl implements VehicleType {
private double fixedCost = 0.0; private double fixedCost = 0.0;
private double perDistance = 1.0; private double perDistance = 1.0;
private double perTime = 0.0; private double perTime = 0.0;
private double perWaitingTime = 0.0;
private String profile = "car"; private String profile = "car";
@ -99,13 +118,12 @@ public class VehicleTypeImpl implements VehicleType {
*/ */
public VehicleTypeImpl.Builder setMaxVelocity(double inMeterPerSeconds){ public VehicleTypeImpl.Builder setMaxVelocity(double inMeterPerSeconds){
if(inMeterPerSeconds < 0.0) throw new IllegalStateException("velocity cannot be smaller than zero"); if(inMeterPerSeconds < 0.0) throw new IllegalStateException("velocity cannot be smaller than zero");
this.maxVelo = inMeterPerSeconds; this.maxVelo = inMeterPerSeconds; return this;
return this;
} }
/** /**
* Sets the fixed costs of the vehicle-type. * Sets the fixed costs of the vehicle-type.
* <p/> *
* <p>by default it is 0. * <p>by default it is 0.
* *
* @param fixedCost * @param fixedCost
@ -120,7 +138,7 @@ public class VehicleTypeImpl implements VehicleType {
/** /**
* Sets the cost per distance unit, for instance per meter. * Sets the cost per distance unit, for instance per meter.
* <p/> *
* <p>by default it is 1.0 * <p>by default it is 1.0
* *
* @param perDistance * @param perDistance
@ -135,19 +153,53 @@ public class VehicleTypeImpl implements VehicleType {
/** /**
* Sets cost per time unit, for instance per second. * Sets cost per time unit, for instance per second.
* <p/> *
* <p>by default it is 0.0 * <p>by default it is 0.0
* *
* @param perTime * @param perTime
* @return this builder * @return this builder
* @throws IllegalStateException if costPerTime is smaller than zero * @throws IllegalStateException if costPerTime is smaller than zero
* @deprecated use .setCostPerTransportTime(..) instead
*/ */
@Deprecated
public VehicleTypeImpl.Builder setCostPerTime(double perTime){ public VehicleTypeImpl.Builder setCostPerTime(double perTime){
if(perTime < 0.0) throw new IllegalStateException(); if(perTime < 0.0) throw new IllegalStateException();
this.perTime = perTime; this.perTime = perTime;
return this; return this;
} }
/**
* Sets cost per time unit, for instance per second.
*
* <p>by default it is 0.0
*
* @param perTime
* @return this builder
* @throws IllegalStateException if costPerTime is smaller than zero
*
*/
public VehicleTypeImpl.Builder setCostPerTransportTime(double perTime){
if(perTime < 0.0) throw new IllegalStateException();
this.perTime = perTime;
return this;
}
/**
* Sets cost per waiting time unit, for instance per second.
*
* <p>by default it is 0.0
*
* @param perWaitingTime
* @return this builder
* @throws IllegalStateException if costPerTime is smaller than zero
*
*/
public VehicleTypeImpl.Builder setCostPerWaitingTime(double perWaitingTime){
if(perWaitingTime < 0.0) throw new IllegalStateException();
this.perWaitingTime = perWaitingTime;
return this;
}
/** /**
* Builds the vehicle-type. * Builds the vehicle-type.
* *
@ -171,8 +223,7 @@ public class VehicleTypeImpl implements VehicleType {
*/ */
public Builder addCapacityDimension(int dimIndex, int dimVal) { public Builder addCapacityDimension(int dimIndex, int dimVal) {
if(dimVal<0) throw new IllegalArgumentException("capacity value cannot be negative"); if(dimVal<0) throw new IllegalArgumentException("capacity value cannot be negative");
if (capacityDimensions != null) if(capacityDimensions != null) throw new IllegalStateException("either build your dimension with build your dimensions with " +
throw new IllegalStateException("either build your dimension with build your dimensions with " +
"addCapacityDimension(int dimIndex, int dimVal) or set the already built dimensions with .setCapacityDimensions(Capacity capacity)." + "addCapacityDimension(int dimIndex, int dimVal) or set the already built dimensions with .setCapacityDimensions(Capacity capacity)." +
"You used both methods."); "You used both methods.");
dimensionAdded = true; dimensionAdded = true;
@ -182,7 +233,7 @@ public class VehicleTypeImpl implements VehicleType {
/** /**
* Sets capacity dimensions. * Sets capacity dimensions.
* <p/> *
* <p>Note if you use this you cannot use <code>addCapacityDimension(int dimIndex, int dimVal)</code> anymore. Thus either build * <p>Note if you use this you cannot use <code>addCapacityDimension(int dimIndex, int dimVal)</code> anymore. Thus either build
* your dimensions with <code>addCapacityDimension(int dimIndex, int dimVal)</code> or set the already built dimensions with * your dimensions with <code>addCapacityDimension(int dimIndex, int dimVal)</code> or set the already built dimensions with
* this method. * this method.
@ -192,8 +243,7 @@ public class VehicleTypeImpl implements VehicleType {
* @throws IllegalStateException if capacityDimension has already been added * @throws IllegalStateException if capacityDimension has already been added
*/ */
public Builder setCapacityDimensions(Capacity capacity){ public Builder setCapacityDimensions(Capacity capacity){
if (dimensionAdded) if(dimensionAdded) throw new IllegalStateException("either build your dimension with build your dimensions with " +
throw new IllegalStateException("either build your dimension with build your dimensions with " +
"addCapacityDimension(int dimIndex, int dimVal) or set the already built dimensions with .setCapacityDimensions(Capacity capacity)." + "addCapacityDimension(int dimIndex, int dimVal) or set the already built dimensions with .setCapacityDimensions(Capacity capacity)." +
"You used both methods."); "You used both methods.");
this.capacityDimensions = capacity; this.capacityDimensions = capacity;
@ -256,7 +306,7 @@ public class VehicleTypeImpl implements VehicleType {
typeId = builder.id; typeId = builder.id;
capacity = builder.capacity; capacity = builder.capacity;
maxVelocity = builder.maxVelo; maxVelocity = builder.maxVelo;
vehicleCostParams = new VehicleCostParams(builder.fixedCost, builder.perTime, builder.perDistance); vehicleCostParams = new VehicleCostParams(builder.fixedCost, builder.perTime, builder.perDistance, builder.perWaitingTime);
capacityDimensions = builder.capacityDimensions; capacityDimensions = builder.capacityDimensions;
profile = builder.profile; profile = builder.profile;
} }
@ -295,8 +345,6 @@ public class VehicleTypeImpl implements VehicleType {
} }
@Override @Override
public String getProfile() { public String getProfile(){ return profile; }
return profile;
}
} }

View file

@ -23,10 +23,11 @@ import jsprit.core.problem.Skills;
/** /**
* Key to identify similar vehicles * Key to identify similar vehicles
* <p/> *
* <p>Two vehicles are equal if they share the same type, the same start and end-location and the same earliestStart and latestStart. * <p>Two vehicles are equal if they share the same type, the same start and end-location and the same earliestStart and latestStart.
* *
* @author stefan * @author stefan
*
*/ */
public class VehicleTypeKey extends AbstractVehicle.AbstractTypeKey{ public class VehicleTypeKey extends AbstractVehicle.AbstractTypeKey{
@ -36,8 +37,9 @@ public class VehicleTypeKey extends AbstractVehicle.AbstractTypeKey {
public final double earliestStart; public final double earliestStart;
public final double latestEnd; public final double latestEnd;
public final Skills skills; public final Skills skills;
public final boolean returnToDepot;
public VehicleTypeKey(String typeId, String startLocationId, String endLocationId, double earliestStart, double latestEnd, Skills skills) { public VehicleTypeKey(String typeId, String startLocationId, String endLocationId, double earliestStart, double latestEnd, Skills skills, boolean returnToDepot) {
super(); super();
this.type = typeId; this.type = typeId;
this.startLocationId = startLocationId; this.startLocationId = startLocationId;
@ -45,17 +47,19 @@ public class VehicleTypeKey extends AbstractVehicle.AbstractTypeKey {
this.earliestStart = earliestStart; this.earliestStart = earliestStart;
this.latestEnd = latestEnd; this.latestEnd = latestEnd;
this.skills = skills; this.skills = skills;
this.returnToDepot=returnToDepot;
} }
@Override @Override
public boolean equals(Object o) { public boolean equals(Object o) {
if (this == o) return true; if (this == o) return true;
if (!(o instanceof VehicleTypeKey)) return false; if (o == null || getClass() != o.getClass()) return false;
VehicleTypeKey that = (VehicleTypeKey) o; VehicleTypeKey that = (VehicleTypeKey) o;
if (Double.compare(that.earliestStart, earliestStart) != 0) return false; if (Double.compare(that.earliestStart, earliestStart) != 0) return false;
if (Double.compare(that.latestEnd, latestEnd) != 0) return false; if (Double.compare(that.latestEnd, latestEnd) != 0) return false;
if (returnToDepot != that.returnToDepot) return false;
if (!endLocationId.equals(that.endLocationId)) return false; if (!endLocationId.equals(that.endLocationId)) return false;
if (!skills.equals(that.skills)) return false; if (!skills.equals(that.skills)) return false;
if (!startLocationId.equals(that.startLocationId)) return false; if (!startLocationId.equals(that.startLocationId)) return false;
@ -76,6 +80,7 @@ public class VehicleTypeKey extends AbstractVehicle.AbstractTypeKey {
temp = Double.doubleToLongBits(latestEnd); temp = Double.doubleToLongBits(latestEnd);
result = 31 * result + (int) (temp ^ (temp >>> 32)); result = 31 * result + (int) (temp ^ (temp >>> 32));
result = 31 * result + skills.hashCode(); result = 31 * result + skills.hashCode();
result = 31 * result + (returnToDepot ? 1 : 0);
return result; return result;
} }
@ -88,4 +93,5 @@ public class VehicleTypeKey extends AbstractVehicle.AbstractTypeKey {
} }
} }

View file

@ -0,0 +1,108 @@
package jsprit.core.algorithm;
import jsprit.core.algorithm.box.Jsprit;
import jsprit.core.algorithm.state.StateManager;
import jsprit.core.analysis.SolutionAnalyser;
import jsprit.core.problem.Location;
import jsprit.core.problem.VehicleRoutingProblem;
import jsprit.core.problem.constraint.ConstraintManager;
import jsprit.core.problem.cost.TransportDistance;
import jsprit.core.problem.cost.VehicleRoutingActivityCosts;
import jsprit.core.problem.driver.Driver;
import jsprit.core.problem.job.Service;
import jsprit.core.problem.solution.SolutionCostCalculator;
import jsprit.core.problem.solution.VehicleRoutingProblemSolution;
import jsprit.core.problem.solution.route.activity.TimeWindow;
import jsprit.core.problem.solution.route.activity.TourActivity;
import jsprit.core.problem.vehicle.Vehicle;
import jsprit.core.problem.vehicle.VehicleImpl;
import jsprit.core.util.CostFactory;
import jsprit.core.util.Solutions;
import junit.framework.Assert;
import org.junit.Before;
import org.junit.Test;
/**
* Created by schroeder on 22/07/15.
*/
public class VariableDepartureAndWaitingTime_IT {
static interface AlgorithmFactory {
VehicleRoutingAlgorithm createAlgorithm(VehicleRoutingProblem vrp);
}
VehicleRoutingActivityCosts activityCosts;
AlgorithmFactory algorithmFactory;
@Before
public void doBefore(){
activityCosts = new VehicleRoutingActivityCosts() {
@Override
public double getActivityCost(TourActivity tourAct, double arrivalTime, Driver driver, Vehicle vehicle) {
return vehicle.getType().getVehicleCostParams().perWaitingTimeUnit * Math.max(0,tourAct.getTheoreticalEarliestOperationStartTime() - arrivalTime);
}
};
algorithmFactory = new AlgorithmFactory() {
@Override
public VehicleRoutingAlgorithm createAlgorithm(final VehicleRoutingProblem vrp) {
StateManager stateManager = new StateManager(vrp);
ConstraintManager constraintManager = new ConstraintManager(vrp,stateManager);
return Jsprit.Builder.newInstance(vrp)
.addCoreStateAndConstraintStuff(true)
.setStateAndConstraintManager(stateManager,constraintManager)
.setObjectiveFunction(new SolutionCostCalculator() {
@Override
public double getCosts(VehicleRoutingProblemSolution solution) {
SolutionAnalyser sa = new SolutionAnalyser(vrp, solution, new TransportDistance() {
@Override
public double getDistance(Location from, Location to) {
return vrp.getTransportCosts().getTransportCost(from, to, 0., null, null);
}
});
return sa.getWaitingTime() + sa.getDistance();
}
})
.buildAlgorithm();
}
};
}
@Test
public void plainSetupShouldWork(){
VehicleImpl v = VehicleImpl.Builder.newInstance("v").setStartLocation(Location.newInstance(0,0)).build();
Service s1 = Service.Builder.newInstance("s1").setLocation(Location.newInstance(10,0)).build();
Service s2 = Service.Builder.newInstance("s2").setLocation(Location.newInstance(20,0)).build();
VehicleRoutingProblem vrp = VehicleRoutingProblem.Builder.newInstance()
.addJob(s1).addJob(s2).addVehicle(v)
.setFleetSize(VehicleRoutingProblem.FleetSize.FINITE)
.setRoutingCost(CostFactory.createManhattanCosts())
.setActivityCosts(activityCosts)
.build();
VehicleRoutingAlgorithm vra = algorithmFactory.createAlgorithm(vrp);
VehicleRoutingProblemSolution solution = Solutions.bestOf(vra.searchSolutions());
Assert.assertEquals(40.,solution.getCost());
}
@Test
public void withTimeWindowsShouldWork(){
VehicleImpl v = VehicleImpl.Builder.newInstance("v").setStartLocation(Location.newInstance(0,0)).build();
Service s1 = Service.Builder.newInstance("s1").setTimeWindow(TimeWindow.newInstance(1010,1100)).setLocation(Location.newInstance(10,0)).build();
Service s2 = Service.Builder.newInstance("s2").setTimeWindow(TimeWindow.newInstance(1020,1100)).setLocation(Location.newInstance(20,0)).build();
final VehicleRoutingProblem vrp = VehicleRoutingProblem.Builder.newInstance()
.addJob(s1).addJob(s2).addVehicle(v)
.setFleetSize(VehicleRoutingProblem.FleetSize.FINITE)
.setRoutingCost(CostFactory.createManhattanCosts())
.setActivityCosts(activityCosts)
.build();
VehicleRoutingAlgorithm vra = algorithmFactory.createAlgorithm(vrp);
VehicleRoutingProblemSolution solution = Solutions.bestOf(vra.searchSolutions());
Assert.assertEquals(40.+1000.,solution.getCost());
}
}

View file

@ -95,7 +95,7 @@ public class ServiceInsertionAndLoadConstraintsTest {
routingCosts = CostFactory.createManhattanCosts(); routingCosts = CostFactory.createManhattanCosts();
VehicleType type = VehicleTypeImpl.Builder.newInstance("t").addCapacityDimension(0, 2).setCostPerDistance(1).build(); VehicleType type = VehicleTypeImpl.Builder.newInstance("t").addCapacityDimension(0, 2).setCostPerDistance(1).build();
vehicle = VehicleImpl.Builder.newInstance("v").setStartLocation(Location.newInstance("0,0")).setType(type).build(); vehicle = VehicleImpl.Builder.newInstance("v").setStartLocation(Location.newInstance("0,0")).setType(type).build();
activityInsertionCostsCalculator = new LocalActivityInsertionCostsCalculator(routingCosts, activityCosts); activityInsertionCostsCalculator = new LocalActivityInsertionCostsCalculator(routingCosts, activityCosts, mock(StateManager.class));
createInsertionCalculator(hardRouteLevelConstraint); createInsertionCalculator(hardRouteLevelConstraint);
vehicleRoutingProblem = mock(VehicleRoutingProblem.class); vehicleRoutingProblem = mock(VehicleRoutingProblem.class);
} }

View file

@ -94,7 +94,7 @@ public class ShipmentInsertionCalculatorTest {
routingCosts = CostFactory.createManhattanCosts(); routingCosts = CostFactory.createManhattanCosts();
VehicleType type = VehicleTypeImpl.Builder.newInstance("t").addCapacityDimension(0, 2).setCostPerDistance(1).build(); VehicleType type = VehicleTypeImpl.Builder.newInstance("t").addCapacityDimension(0, 2).setCostPerDistance(1).build();
vehicle = VehicleImpl.Builder.newInstance("v").setStartLocation(Location.newInstance("0,0")).setType(type).build(); vehicle = VehicleImpl.Builder.newInstance("v").setStartLocation(Location.newInstance("0,0")).setType(type).build();
activityInsertionCostsCalculator = new LocalActivityInsertionCostsCalculator(routingCosts, activityCosts); activityInsertionCostsCalculator = new LocalActivityInsertionCostsCalculator(routingCosts, activityCosts, mock(StateManager.class));
createInsertionCalculator(hardRouteLevelConstraint); createInsertionCalculator(hardRouteLevelConstraint);
vehicleRoutingProblem = mock(VehicleRoutingProblem.class); vehicleRoutingProblem = mock(VehicleRoutingProblem.class);
} }

View file

@ -50,6 +50,8 @@ import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
public class TestCalculatesServiceInsertion { public class TestCalculatesServiceInsertion {
ServiceInsertionCalculator serviceInsertion; ServiceInsertionCalculator serviceInsertion;

View file

@ -16,17 +16,33 @@
******************************************************************************/ ******************************************************************************/
package jsprit.core.algorithm.recreate; package jsprit.core.algorithm.recreate;
import jsprit.core.algorithm.state.StateManager;
import jsprit.core.algorithm.state.UpdateActivityTimes;
import jsprit.core.algorithm.state.UpdateFutureWaitingTimes;
import jsprit.core.algorithm.state.UpdateVehicleDependentPracticalTimeWindows;
import jsprit.core.problem.Location; import jsprit.core.problem.Location;
import jsprit.core.problem.VehicleRoutingProblem;
import jsprit.core.problem.cost.VehicleRoutingActivityCosts; import jsprit.core.problem.cost.VehicleRoutingActivityCosts;
import jsprit.core.problem.cost.VehicleRoutingTransportCosts; import jsprit.core.problem.cost.VehicleRoutingTransportCosts;
import jsprit.core.problem.cost.WaitingTimeCosts;
import jsprit.core.problem.job.Job;
import jsprit.core.problem.job.Service;
import jsprit.core.problem.misc.JobInsertionContext; import jsprit.core.problem.misc.JobInsertionContext;
import jsprit.core.problem.solution.route.VehicleRoute; import jsprit.core.problem.solution.route.VehicleRoute;
import jsprit.core.problem.solution.route.activity.End; import jsprit.core.problem.solution.route.activity.End;
import jsprit.core.problem.solution.route.activity.Start;
import jsprit.core.problem.solution.route.activity.TimeWindow;
import jsprit.core.problem.solution.route.activity.TourActivity; import jsprit.core.problem.solution.route.activity.TourActivity;
import jsprit.core.problem.vehicle.Vehicle; import jsprit.core.problem.vehicle.Vehicle;
import jsprit.core.problem.vehicle.VehicleImpl;
import jsprit.core.problem.vehicle.VehicleTypeImpl;
import jsprit.core.util.CostFactory;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import java.util.ArrayList;
import java.util.Arrays;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
@ -56,6 +72,7 @@ public class TestLocalActivityInsertionCostsCalculator {
jic = mock(JobInsertionContext.class); jic = mock(JobInsertionContext.class);
when(jic.getRoute()).thenReturn(route); when(jic.getRoute()).thenReturn(route);
when(jic.getNewVehicle()).thenReturn(vehicle); when(jic.getNewVehicle()).thenReturn(vehicle);
when(vehicle.getType()).thenReturn(VehicleTypeImpl.Builder.newInstance("type").build());
tpCosts = mock(VehicleRoutingTransportCosts.class); tpCosts = mock(VehicleRoutingTransportCosts.class);
when(tpCosts.getTransportCost(loc("i"), loc("j"), 0.0, null, vehicle)).thenReturn(2.0); when(tpCosts.getTransportCost(loc("i"), loc("j"), 0.0, null, vehicle)).thenReturn(2.0);
@ -66,7 +83,7 @@ public class TestLocalActivityInsertionCostsCalculator {
when(tpCosts.getTransportTime(loc("k"), loc("j"), 0.0, null, vehicle)).thenReturn(0.0); when(tpCosts.getTransportTime(loc("k"), loc("j"), 0.0, null, vehicle)).thenReturn(0.0);
actCosts = mock(VehicleRoutingActivityCosts.class); actCosts = mock(VehicleRoutingActivityCosts.class);
calc = new LocalActivityInsertionCostsCalculator(tpCosts, actCosts); calc = new LocalActivityInsertionCostsCalculator(tpCosts, actCosts, mock(StateManager.class));
} }
private Location loc(String i) { private Location loc(String i) {
@ -77,10 +94,13 @@ public class TestLocalActivityInsertionCostsCalculator {
public void whenInsertingActBetweenTwoRouteActs_itCalcsMarginalTpCosts(){ public void whenInsertingActBetweenTwoRouteActs_itCalcsMarginalTpCosts(){
TourActivity prevAct = mock(TourActivity.class); TourActivity prevAct = mock(TourActivity.class);
when(prevAct.getLocation()).thenReturn(loc("i")); when(prevAct.getLocation()).thenReturn(loc("i"));
when(prevAct.getIndex()).thenReturn(1);
TourActivity nextAct = mock(TourActivity.class); TourActivity nextAct = mock(TourActivity.class);
when(nextAct.getLocation()).thenReturn(loc("j")); when(nextAct.getLocation()).thenReturn(loc("j"));
when(nextAct.getIndex()).thenReturn(1);
TourActivity newAct = mock(TourActivity.class); TourActivity newAct = mock(TourActivity.class);
when(newAct.getLocation()).thenReturn(loc("k")); when(newAct.getLocation()).thenReturn(loc("k"));
when(newAct.getIndex()).thenReturn(1);
when(vehicle.isReturnToDepot()).thenReturn(true); when(vehicle.isReturnToDepot()).thenReturn(true);
@ -92,9 +112,11 @@ public class TestLocalActivityInsertionCostsCalculator {
public void whenInsertingActBetweenLastActAndEnd_itCalcsMarginalTpCosts(){ public void whenInsertingActBetweenLastActAndEnd_itCalcsMarginalTpCosts(){
TourActivity prevAct = mock(TourActivity.class); TourActivity prevAct = mock(TourActivity.class);
when(prevAct.getLocation()).thenReturn(loc("i")); when(prevAct.getLocation()).thenReturn(loc("i"));
when(prevAct.getIndex()).thenReturn(1);
End nextAct = End.newInstance("j", 0.0, 0.0); End nextAct = End.newInstance("j", 0.0, 0.0);
TourActivity newAct = mock(TourActivity.class); TourActivity newAct = mock(TourActivity.class);
when(newAct.getLocation()).thenReturn(loc("k")); when(newAct.getLocation()).thenReturn(loc("k"));
when(newAct.getIndex()).thenReturn(1);
when(vehicle.isReturnToDepot()).thenReturn(true); when(vehicle.isReturnToDepot()).thenReturn(true);
@ -106,10 +128,13 @@ public class TestLocalActivityInsertionCostsCalculator {
public void whenInsertingActBetweenTwoRouteActsAndRouteIsOpen_itCalcsMarginalTpCosts(){ public void whenInsertingActBetweenTwoRouteActsAndRouteIsOpen_itCalcsMarginalTpCosts(){
TourActivity prevAct = mock(TourActivity.class); TourActivity prevAct = mock(TourActivity.class);
when(prevAct.getLocation()).thenReturn(loc("i")); when(prevAct.getLocation()).thenReturn(loc("i"));
when(prevAct.getIndex()).thenReturn(1);
TourActivity nextAct = mock(TourActivity.class); TourActivity nextAct = mock(TourActivity.class);
when(nextAct.getLocation()).thenReturn(loc("j")); when(nextAct.getLocation()).thenReturn(loc("j"));
when(nextAct.getIndex()).thenReturn(1);
TourActivity newAct = mock(TourActivity.class); TourActivity newAct = mock(TourActivity.class);
when(newAct.getLocation()).thenReturn(loc("k")); when(newAct.getLocation()).thenReturn(loc("k"));
when(newAct.getIndex()).thenReturn(1);
when(vehicle.isReturnToDepot()).thenReturn(false); when(vehicle.isReturnToDepot()).thenReturn(false);
@ -121,13 +146,368 @@ public class TestLocalActivityInsertionCostsCalculator {
public void whenInsertingActBetweenLastActAndEndAndRouteIsOpen_itCalculatesTpCostsFromPrevToNewAct(){ public void whenInsertingActBetweenLastActAndEndAndRouteIsOpen_itCalculatesTpCostsFromPrevToNewAct(){
TourActivity prevAct = mock(TourActivity.class); TourActivity prevAct = mock(TourActivity.class);
when(prevAct.getLocation()).thenReturn(loc("i")); when(prevAct.getLocation()).thenReturn(loc("i"));
when(prevAct.getIndex()).thenReturn(1);
End nextAct = End.newInstance("j", 0.0, 0.0); End nextAct = End.newInstance("j", 0.0, 0.0);
TourActivity newAct = mock(TourActivity.class); TourActivity newAct = mock(TourActivity.class);
when(newAct.getLocation()).thenReturn(loc("k")); when(newAct.getLocation()).thenReturn(loc("k"));
when(newAct.getIndex()).thenReturn(1);
when(vehicle.isReturnToDepot()).thenReturn(false); when(vehicle.isReturnToDepot()).thenReturn(false);
double costs = calc.getCosts(jic, prevAct, nextAct, newAct, 0.0); double costs = calc.getCosts(jic, prevAct, nextAct, newAct, 0.0);
assertEquals(3.0,costs,0.01); assertEquals(3.0,costs,0.01);
} }
@Test
public void test(){
VehicleTypeImpl type = VehicleTypeImpl.Builder.newInstance("t").setCostPerWaitingTime(1.).build();
VehicleImpl v = VehicleImpl.Builder.newInstance("v").setType(type).setStartLocation(Location.newInstance(0, 0)).build();
Service prevS = Service.Builder.newInstance("prev").setLocation(Location.newInstance(10,0)).build();
Service newS = Service.Builder.newInstance("new").setServiceTime(10).setLocation(Location.newInstance(60, 0)).build();
Service nextS = Service.Builder.newInstance("next").setLocation(Location.newInstance(30,0)).setTimeWindow(TimeWindow.newInstance(40,80)).build();
VehicleRoutingProblem vrp = VehicleRoutingProblem.Builder.newInstance().addJob(prevS).addJob(newS).addJob(nextS).addVehicle(v).build();
TourActivity prevAct = vrp.getActivities(prevS).get(0);
TourActivity newAct = vrp.getActivities(newS).get(0);
TourActivity nextAct = vrp.getActivities(nextS).get(0);
VehicleRoute route = VehicleRoute.Builder.newInstance(v).setJobActivityFactory(vrp.getJobActivityFactory()).addService(prevS).addService(nextS).build();
JobInsertionContext context = new JobInsertionContext(route,newS,v,null,0.);
LocalActivityInsertionCostsCalculator calc = new LocalActivityInsertionCostsCalculator(CostFactory.createEuclideanCosts(),new WaitingTimeCosts(), new StateManager(mock(VehicleRoutingProblem.class)));
calc.setSolutionCompletenessRatio(1.);
double c = calc.getCosts(context,prevAct,nextAct,newAct,10);
assertEquals(50.,c,0.01);
/*
new: dist = 90 & wait = 0
old: dist = 30 & wait = 10
c = new - old = 90 - 40 = 50
*/
}
@Test
public void whenAddingNewBetweenStartAndAct_itShouldCalcInsertionCostsCorrectly(){
VehicleTypeImpl type = VehicleTypeImpl.Builder.newInstance("t").setCostPerWaitingTime(1.).build();
VehicleImpl v = VehicleImpl.Builder.newInstance("v").setType(type).setStartLocation(Location.newInstance(0,0)).build();
Service newS = Service.Builder.newInstance("new").setServiceTime(10).setLocation(Location.newInstance(10, 0)).build();
Service nextS = Service.Builder.newInstance("next").setLocation(Location.newInstance(30, 0))
.setTimeWindow(TimeWindow.newInstance(40, 50)).build();
VehicleRoutingProblem vrp = VehicleRoutingProblem.Builder.newInstance().addJob(newS).addJob(nextS).addVehicle(v).build();
Start prevAct = new Start(Location.newInstance(0,0),0,100);
TourActivity newAct = vrp.getActivities(newS).get(0);
TourActivity nextAct = vrp.getActivities(nextS).get(0);
VehicleRoute route = VehicleRoute.Builder.newInstance(v).setJobActivityFactory(vrp.getJobActivityFactory()).addService(nextS).build();
JobInsertionContext context = new JobInsertionContext(route,newS,v,null,0.);
LocalActivityInsertionCostsCalculator calc = new LocalActivityInsertionCostsCalculator(CostFactory.createEuclideanCosts(),new WaitingTimeCosts(),new StateManager(vrp));
calc.setSolutionCompletenessRatio(1.);
double c = calc.getCosts(context,prevAct,nextAct,newAct,0);
assertEquals(-10.,c,0.01);
}
@Test
public void whenAddingNewBetweenStartAndAct2_itShouldCalcInsertionCostsCorrectly(){
VehicleTypeImpl type = VehicleTypeImpl.Builder.newInstance("t").setCostPerWaitingTime(1.).build();
VehicleImpl v2 = VehicleImpl.Builder.newInstance("v2").setType(type).setStartLocation(Location.newInstance(0,0)).build();
Service newS = Service.Builder.newInstance("new").setServiceTime(10).setLocation(Location.newInstance(10, 0)).build();
Service nextS = Service.Builder.newInstance("next").setLocation(Location.newInstance(30,0))
.setTimeWindow(TimeWindow.newInstance(140,150)).build();
VehicleRoutingProblem vrp = VehicleRoutingProblem.Builder.newInstance().addJob(newS).addJob(nextS).addVehicle(v2).build();
Start prevAct = new Start(Location.newInstance(0,0),0,100);
TourActivity newAct = vrp.getActivities(newS).get(0);
TourActivity nextAct = vrp.getActivities(nextS).get(0);
VehicleRoute route = VehicleRoute.Builder.newInstance(v2).setJobActivityFactory(vrp.getJobActivityFactory()).addService(nextS).build();
JobInsertionContext context = new JobInsertionContext(route,newS,v2,null,0.);
LocalActivityInsertionCostsCalculator calc = new LocalActivityInsertionCostsCalculator(CostFactory.createEuclideanCosts(),new WaitingTimeCosts(), new StateManager(vrp));
calc.setSolutionCompletenessRatio(1.);
double c = calc.getCosts(context,prevAct,nextAct,newAct,0);
assertEquals(-10.,c,0.01);
}
@Test
public void whenAddingNewInEmptyRoute_itShouldCalcInsertionCostsCorrectly(){
VehicleTypeImpl type = VehicleTypeImpl.Builder.newInstance("t").setCostPerWaitingTime(1.).build();
VehicleImpl v = VehicleImpl.Builder.newInstance("v").setType(type).setStartLocation(Location.newInstance(0,0)).build();
Service newS = Service.Builder.newInstance("new").setServiceTime(10).setLocation(Location.newInstance(10, 0)).setTimeWindow(TimeWindow.newInstance(100, 150)).build();
VehicleRoutingProblem vrp = VehicleRoutingProblem.Builder.newInstance().addJob(newS).addVehicle(v).build();
Start prevAct = new Start(Location.newInstance(0,0),0,100);
TourActivity newAct = vrp.getActivities(newS).get(0);
End nextAct = new End(Location.newInstance(0,0),0,100);
VehicleRoute route = VehicleRoute.Builder.newInstance(v).setJobActivityFactory(vrp.getJobActivityFactory()).build();
JobInsertionContext context = new JobInsertionContext(route,newS,v,null,0.);
LocalActivityInsertionCostsCalculator calc = new LocalActivityInsertionCostsCalculator(CostFactory.createEuclideanCosts(),new WaitingTimeCosts(),new StateManager(vrp) );
calc.setSolutionCompletenessRatio(1.);
double c = calc.getCosts(context,prevAct,nextAct,newAct,0);
assertEquals(110.,c,0.01);
}
@Test
public void whenAddingNewBetweenTwoActs_itShouldCalcInsertionCostsCorrectly(){
VehicleTypeImpl type = VehicleTypeImpl.Builder.newInstance("t").setCostPerWaitingTime(1.).build();
VehicleImpl v = VehicleImpl.Builder.newInstance("v").setType(type).setStartLocation(Location.newInstance(0,0)).build();
Service prevS = Service.Builder.newInstance("prev").setLocation(Location.newInstance(10, 0)).build();
Service newS = Service.Builder.newInstance("new").setServiceTime(10).setLocation(Location.newInstance(20, 0)).build();
Service nextS = Service.Builder.newInstance("next").setLocation(Location.newInstance(30,0)).setTimeWindow(TimeWindow.newInstance(40,50)).build();
VehicleRoutingProblem vrp = VehicleRoutingProblem.Builder.newInstance().addJob(prevS).addJob(newS).addJob(nextS).addVehicle(v).build();
TourActivity prevAct = vrp.getActivities(prevS).get(0);
TourActivity newAct = vrp.getActivities(newS).get(0);
TourActivity nextAct = vrp.getActivities(nextS).get(0);
VehicleRoute route = VehicleRoute.Builder.newInstance(v).setJobActivityFactory(vrp.getJobActivityFactory()).addService(prevS).addService(nextS).build();
JobInsertionContext context = new JobInsertionContext(route,newS,v,null,0.);
LocalActivityInsertionCostsCalculator calc = new LocalActivityInsertionCostsCalculator(CostFactory.createEuclideanCosts(),new WaitingTimeCosts(),new StateManager(vrp) );
calc.setSolutionCompletenessRatio(1.);
double c = calc.getCosts(context,prevAct,nextAct,newAct,10);
assertEquals(-10.,c,0.01);
}
@Test
public void whenAddingNewWithTWBetweenTwoActs_itShouldCalcInsertionCostsCorrectly(){
VehicleTypeImpl type = VehicleTypeImpl.Builder.newInstance("t").setCostPerWaitingTime(1.).build();
VehicleImpl v = VehicleImpl.Builder.newInstance("v").setType(type).setStartLocation(Location.newInstance(0,0)).build();
Service prevS = Service.Builder.newInstance("prev").setLocation(Location.newInstance(10,0)).build();
Service newS = Service.Builder.newInstance("new").setServiceTime(10).setTimeWindow(TimeWindow.newInstance(100, 120)).setLocation(Location.newInstance(20, 0)).build();
Service nextS = Service.Builder.newInstance("next").setLocation(Location.newInstance(30,0)).setTimeWindow(TimeWindow.newInstance(40,500)).build();
VehicleRoutingProblem vrp = VehicleRoutingProblem.Builder.newInstance().addJob(prevS).addJob(newS).addJob(nextS).addVehicle(v).build();
TourActivity prevAct = vrp.getActivities(prevS).get(0);
TourActivity newAct = vrp.getActivities(newS).get(0);
TourActivity nextAct = vrp.getActivities(nextS).get(0);
VehicleRoute route = VehicleRoute.Builder.newInstance(v).setJobActivityFactory(vrp.getJobActivityFactory()).addService(prevS).addService(nextS).build();
JobInsertionContext context = new JobInsertionContext(route,newS,v,null,0.);
LocalActivityInsertionCostsCalculator calc = new LocalActivityInsertionCostsCalculator(CostFactory.createEuclideanCosts(),new WaitingTimeCosts(),new StateManager(vrp) );
calc.setSolutionCompletenessRatio(0.5);
double c = calc.getCosts(context,prevAct,nextAct,newAct,10);
assertEquals(35.,c,0.01);
}
@Test
public void whenAddingNewWithTWBetweenTwoActs2_itShouldCalcInsertionCostsCorrectly(){
VehicleTypeImpl type = VehicleTypeImpl.Builder.newInstance("t").setCostPerWaitingTime(1.).build();
VehicleImpl v = VehicleImpl.Builder.newInstance("v").setType(type).setStartLocation(Location.newInstance(0,0)).build();
// VehicleImpl v2 = VehicleImpl.Builder.newInstance("v2").setHasVariableDepartureTime(true).setType(type).setStartLocation(Location.newInstance(0,0)).build();
Service prevS = Service.Builder.newInstance("prev").setLocation(Location.newInstance(10,0)).build();
Service newS = Service.Builder.newInstance("new").setServiceTime(10).setTimeWindow(TimeWindow.newInstance(100,120)).setLocation(Location.newInstance(20, 0)).build();
Service nextS = Service.Builder.newInstance("next").setLocation(Location.newInstance(30,0)).setTimeWindow(TimeWindow.newInstance(40,500)).build();
Service afterNextS = Service.Builder.newInstance("afterNext").setLocation(Location.newInstance(40,0)).setTimeWindow(TimeWindow.newInstance(400,500)).build();
VehicleRoutingProblem vrp = VehicleRoutingProblem.Builder.newInstance().addJob(afterNextS).addJob(prevS).addJob(newS).addJob(nextS).addVehicle(v).build();
TourActivity prevAct = vrp.getActivities(prevS).get(0);
TourActivity newAct = vrp.getActivities(newS).get(0);
TourActivity nextAct = vrp.getActivities(nextS).get(0);
VehicleRoute route = VehicleRoute.Builder.newInstance(v).setJobActivityFactory(vrp.getJobActivityFactory()).addService(prevS).addService(nextS).addService(afterNextS).build();
StateManager stateManager = getStateManager(vrp,route);
JobInsertionContext context = new JobInsertionContext(route,newS,v,null,0.);
LocalActivityInsertionCostsCalculator calc = new LocalActivityInsertionCostsCalculator(CostFactory.createEuclideanCosts(),new WaitingTimeCosts(),stateManager);
calc.setSolutionCompletenessRatio(1.);
double c = calc.getCosts(context,prevAct,nextAct,newAct,10);
assertEquals(-10.,c,0.01);
//
//old: dist: 0, waiting: 10 + 350 = 360
//new: dist: 0, waiting: 80 + 270 = 350
}
@Test
public void whenAddingNewWithTWBetweenTwoActs3_itShouldCalcInsertionCostsCorrectly(){
VehicleTypeImpl type = VehicleTypeImpl.Builder.newInstance("t").setCostPerWaitingTime(1.).build();
VehicleImpl v = VehicleImpl.Builder.newInstance("v").setType(type).setStartLocation(Location.newInstance(0,0)).build();
// VehicleImpl v2 = VehicleImpl.Builder.newInstance("v2").setHasVariableDepartureTime(true).setType(type).setStartLocation(Location.newInstance(0,0)).build();
Service prevS = Service.Builder.newInstance("prev").setLocation(Location.newInstance(10,0)).build();
Service newS = Service.Builder.newInstance("new").setServiceTime(10).setTimeWindow(TimeWindow.newInstance(100, 120)).setLocation(Location.newInstance(20, 0)).build();
Service nextS = Service.Builder.newInstance("next").setLocation(Location.newInstance(30, 0)).setTimeWindow(TimeWindow.newInstance(40, 500)).build();
Service afterNextS = Service.Builder.newInstance("afterNext").setLocation(Location.newInstance(40,0)).setTimeWindow(TimeWindow.newInstance(80, 500)).build();
Service afterAfterNextS = Service.Builder.newInstance("afterAfterNext").setLocation(Location.newInstance(40,0)).setTimeWindow(TimeWindow.newInstance(100, 500)).build();
VehicleRoutingProblem vrp = VehicleRoutingProblem.Builder.newInstance().addVehicle(v).addJob(prevS).addJob(newS).addJob(nextS)
.addJob(afterNextS).addJob(afterAfterNextS).build();
TourActivity prevAct = vrp.getActivities(prevS).get(0);
TourActivity newAct = vrp.getActivities(newS).get(0);
TourActivity nextAct = vrp.getActivities(nextS).get(0);
VehicleRoute route = VehicleRoute.Builder.newInstance(v).setJobActivityFactory(vrp.getJobActivityFactory()).addService(prevS).addService(nextS).addService(afterNextS).addService(afterAfterNextS).build();
StateManager stateManager = getStateManager(vrp, route);
JobInsertionContext context = new JobInsertionContext(route,newS,v,null,0.);
LocalActivityInsertionCostsCalculator calc = new LocalActivityInsertionCostsCalculator(CostFactory.createEuclideanCosts(),new WaitingTimeCosts(),stateManager);
calc.setSolutionCompletenessRatio(1.);
double c = calc.getCosts(context,prevAct,nextAct,newAct,10);
assertEquals(20.,c,0.01);
//start-delay = new - old = 120 - 40 = 80 > future waiting time savings = 30 + 20 + 10
//ref: 10 + 50 + 20 = 80
//new: 80 - 10 - 30 - 20 = 20
/*
w(new) + w(next) - w_old(next) - min{start_delay(next),future_waiting}
*/
}
@Test
public void whenAddingNewWithTWBetweenTwoActs4_itShouldCalcInsertionCostsCorrectly(){
VehicleTypeImpl type = VehicleTypeImpl.Builder.newInstance("t").setCostPerWaitingTime(1.).build();
VehicleImpl v = VehicleImpl.Builder.newInstance("v").setType(type).setStartLocation(Location.newInstance(0,0)).build();
// VehicleImpl v2 = VehicleImpl.Builder.newInstance("v2").setHasVariableDepartureTime(true).setType(type).setStartLocation(Location.newInstance(0,0)).build();
Service prevS = Service.Builder.newInstance("prev").setLocation(Location.newInstance(10,0)).build();
Service newS = Service.Builder.newInstance("new").setServiceTime(10).setTimeWindow(TimeWindow.newInstance(100,120)).setLocation(Location.newInstance(20, 0)).build();
Service nextS = Service.Builder.newInstance("next").setLocation(Location.newInstance(30,0)).setTimeWindow(TimeWindow.newInstance(40,500)).build();
Service afterNextS = Service.Builder.newInstance("afterNext").setLocation(Location.newInstance(40,0)).setTimeWindow(TimeWindow.newInstance(80,500)).build();
Service afterAfterNextS = Service.Builder.newInstance("afterAfterNext").setLocation(Location.newInstance(50,0)).setTimeWindow(TimeWindow.newInstance(100,500)).build();
VehicleRoutingProblem vrp = VehicleRoutingProblem.Builder.newInstance().addVehicle(v).addJob(prevS).addJob(newS).addJob(nextS)
.addJob(afterNextS).addJob(afterAfterNextS).build();
TourActivity prevAct = vrp.getActivities(prevS).get(0);
TourActivity newAct = vrp.getActivities(newS).get(0);
TourActivity nextAct = vrp.getActivities(nextS).get(0);
VehicleRoute route = VehicleRoute.Builder.newInstance(v).setJobActivityFactory(vrp.getJobActivityFactory()).addService(prevS).addService(nextS).addService(afterNextS).addService(afterAfterNextS).build();
JobInsertionContext context = new JobInsertionContext(route,newS,v,null,0.);
StateManager stateManager = getStateManager(vrp, route);
LocalActivityInsertionCostsCalculator calc = new LocalActivityInsertionCostsCalculator(CostFactory.createEuclideanCosts(),new WaitingTimeCosts(),stateManager);
calc.setSolutionCompletenessRatio(1.);
double c = calc.getCosts(context,prevAct,nextAct,newAct,10);
assertEquals(30.,c,0.01);
//ref: 10 + 30 + 10 = 50
//new: 50 - 50 = 0
/*
activity start time delay at next act = start-time-old - start-time-new is always bigger than subsequent waiting time savings
*/
/*
old = 10 + 30 + 10 = 50
new = 80 + 0 - 10 - min{80,40} = 30
*/
}
@Test
public void whenAddingNewWithTWBetweenTwoActs4WithVarStart_itShouldCalcInsertionCostsCorrectly(){
VehicleTypeImpl type = VehicleTypeImpl.Builder.newInstance("t").setCostPerWaitingTime(1.).build();
VehicleImpl v = VehicleImpl.Builder.newInstance("v").setType(type).setStartLocation(Location.newInstance(0,0)).build();
// VehicleImpl v2 = VehicleImpl.Builder.newInstance("v2").setHasVariableDepartureTime(true).setType(type).setStartLocation(Location.newInstance(0,0)).build();
Service prevS = Service.Builder.newInstance("prev").setLocation(Location.newInstance(10,0)).build();
Service newS = Service.Builder.newInstance("new").setServiceTime(10).setTimeWindow(TimeWindow.newInstance(100,120)).setLocation(Location.newInstance(20, 0)).build();
Service nextS = Service.Builder.newInstance("next").setLocation(Location.newInstance(30,0)).setTimeWindow(TimeWindow.newInstance(40,500)).build();
Service afterNextS = Service.Builder.newInstance("afterNext").setLocation(Location.newInstance(40,0)).setTimeWindow(TimeWindow.newInstance(80,500)).build();
Service afterAfterNextS = Service.Builder.newInstance("afterAfterNext").setLocation(Location.newInstance(50,0)).setTimeWindow(TimeWindow.newInstance(100,500)).build();
VehicleRoutingProblem vrp = VehicleRoutingProblem.Builder.newInstance().addVehicle(v).addJob(prevS).addJob(newS).addJob(nextS)
.addJob(afterNextS).addJob(afterAfterNextS).build();
TourActivity prevAct = vrp.getActivities(prevS).get(0);
TourActivity newAct = vrp.getActivities(newS).get(0);
TourActivity nextAct = vrp.getActivities(nextS).get(0);
VehicleRoute route = VehicleRoute.Builder.newInstance(v).setJobActivityFactory(vrp.getJobActivityFactory()).addService(prevS).addService(nextS).addService(afterNextS).addService(afterAfterNextS).build();
JobInsertionContext context = new JobInsertionContext(route,newS,v,null,0.);
StateManager stateManager = getStateManager(vrp, route);
LocalActivityInsertionCostsCalculator calc = new LocalActivityInsertionCostsCalculator(CostFactory.createEuclideanCosts(),new WaitingTimeCosts(),stateManager);
calc.setSolutionCompletenessRatio(1.);
double c = calc.getCosts(context,prevAct,nextAct,newAct,10);
assertEquals(30.,c,0.01);
/*
activity start time delay at next act = start-time-old - start-time-new is always bigger than subsequent waiting time savings
*/
/*
old = 10 + 30 + 10 = 50
new = 80
new - old = 80 - 40 = 40
*/
}
@Test
public void whenAddingNewWithTWBetweenTwoActs3WithVarStart_itShouldCalcInsertionCostsCorrectly(){
VehicleTypeImpl type = VehicleTypeImpl.Builder.newInstance("t").setCostPerWaitingTime(1.).build();
VehicleImpl v = VehicleImpl.Builder.newInstance("v").setType(type).setStartLocation(Location.newInstance(0,0)).build();
// VehicleImpl v2 = VehicleImpl.Builder.newInstance("v2").setHasVariableDepartureTime(true).setType(type).setStartLocation(Location.newInstance(0,0)).build();
Service prevS = Service.Builder.newInstance("prev").setLocation(Location.newInstance(10,0)).build();
Service newS = Service.Builder.newInstance("new").setServiceTime(10).setTimeWindow(TimeWindow.newInstance(50,70)).setLocation(Location.newInstance(20, 0)).build();
Service nextS = Service.Builder.newInstance("next").setLocation(Location.newInstance(30,0)).setTimeWindow(TimeWindow.newInstance(40,70)).build();
Service afterNextS = Service.Builder.newInstance("afterNext").setLocation(Location.newInstance(40,0)).setTimeWindow(TimeWindow.newInstance(50,100)).build();
Service afterAfterNextS = Service.Builder.newInstance("afterAfterNext").setLocation(Location.newInstance(50,0)).setTimeWindow(TimeWindow.newInstance(100,500)).build();
VehicleRoutingProblem vrp = VehicleRoutingProblem.Builder.newInstance().addVehicle(v).addJob(prevS).addJob(newS).addJob(nextS)
.addJob(afterNextS).addJob(afterAfterNextS).build();
TourActivity prevAct = vrp.getActivities(prevS).get(0);
TourActivity newAct = vrp.getActivities(newS).get(0);
TourActivity nextAct = vrp.getActivities(nextS).get(0);
VehicleRoute route = VehicleRoute.Builder.newInstance(v).setJobActivityFactory(vrp.getJobActivityFactory()).addService(prevS).addService(nextS).addService(afterNextS).addService(afterAfterNextS).build();
JobInsertionContext context = new JobInsertionContext(route,newS,v,null,0.);
StateManager stateManager = getStateManager(vrp, route);
LocalActivityInsertionCostsCalculator calc = new LocalActivityInsertionCostsCalculator(CostFactory.createEuclideanCosts(),new WaitingTimeCosts(),stateManager);
calc.setSolutionCompletenessRatio(1.);
double c = calc.getCosts(context,prevAct,nextAct,newAct,10);
assertEquals(-10.,c,0.01);
/*
activity start time delay at next act = start-time-old - start-time-new is always bigger than subsequent waiting time savings
*/
/*
old = 10 + 40 = 50
new = 30 + 10 = 40
*/
}
private StateManager getStateManager(VehicleRoutingProblem vrp, VehicleRoute route) {
StateManager stateManager = new StateManager(vrp);
stateManager.addStateUpdater(new UpdateActivityTimes(vrp.getTransportCosts()));
stateManager.addStateUpdater(new UpdateVehicleDependentPracticalTimeWindows(stateManager,vrp.getTransportCosts()));
stateManager.addStateUpdater(new UpdateFutureWaitingTimes(stateManager,vrp.getTransportCosts()));
stateManager.informInsertionStarts(Arrays.asList(route),new ArrayList<Job>());
return stateManager;
}
} }

View file

@ -34,6 +34,35 @@ public class VehicleImplTest {
Vehicle v = VehicleImpl.Builder.newInstance("v").build(); Vehicle v = VehicleImpl.Builder.newInstance("v").build();
} }
@Test
public void whenAddingSkills_theyShouldBeAddedCorrectly(){
VehicleTypeImpl type1 = VehicleTypeImpl.Builder.newInstance("type").build();
Vehicle v = VehicleImpl.Builder.newInstance("v").setStartLocation(Location.newInstance("start")).setType(type1).setEndLocation(Location.newInstance("start"))
.addSkill("drill").addSkill("screwdriver").build();
assertTrue(v.getSkills().containsSkill("drill"));
assertTrue(v.getSkills().containsSkill("drill"));
assertTrue(v.getSkills().containsSkill("screwdriver"));
}
@Test
public void whenAddingSkillsCaseSens_theyShouldBeAddedCorrectly(){
VehicleTypeImpl type1 = VehicleTypeImpl.Builder.newInstance("type").build();
Vehicle v = VehicleImpl.Builder.newInstance("v").setStartLocation(Location.newInstance("start")).setType(type1).setEndLocation(Location.newInstance("start"))
.addSkill("drill").addSkill("screwdriver").build();
assertTrue(v.getSkills().containsSkill("drill"));
assertTrue(v.getSkills().containsSkill("dRill"));
assertTrue(v.getSkills().containsSkill("ScrewDriver"));
}
@Test
public void whenAddingSkillsCaseSensV2_theyShouldBeAddedCorrectly(){
VehicleTypeImpl type1 = VehicleTypeImpl.Builder.newInstance("type").build();
Vehicle v = VehicleImpl.Builder.newInstance("v").setStartLocation(Location.newInstance("start")).setType(type1).setEndLocation(Location.newInstance("start"))
.addSkill("drill").build();
assertFalse(v.getSkills().containsSkill("ScrewDriver"));
}
@Test @Test
public void whenVehicleIsBuiltToReturnToDepot_itShouldReturnToDepot() { public void whenVehicleIsBuiltToReturnToDepot_itShouldReturnToDepot() {
Vehicle v = VehicleImpl.Builder.newInstance("v").setReturnToDepot(true).setStartLocation(Location.newInstance("loc")).build(); Vehicle v = VehicleImpl.Builder.newInstance("v").setReturnToDepot(true).setStartLocation(Location.newInstance("loc")).build();

View file

@ -18,7 +18,7 @@ package jsprit.examples;
import jsprit.analysis.toolbox.Plotter; import jsprit.analysis.toolbox.Plotter;
import jsprit.core.algorithm.VehicleRoutingAlgorithm; import jsprit.core.algorithm.VehicleRoutingAlgorithm;
import jsprit.core.algorithm.io.VehicleRoutingAlgorithms; import jsprit.core.algorithm.box.Jsprit;
import jsprit.core.problem.Location; import jsprit.core.problem.Location;
import jsprit.core.problem.VehicleRoutingProblem; import jsprit.core.problem.VehicleRoutingProblem;
import jsprit.core.problem.VehicleRoutingProblem.FleetSize; import jsprit.core.problem.VehicleRoutingProblem.FleetSize;
@ -40,6 +40,7 @@ import java.util.Collection;
* Illustrates how you can use jsprit with an already compiled distance and time matrix. * Illustrates how you can use jsprit with an already compiled distance and time matrix.
* *
* @author schroeder * @author schroeder
*
*/ */
public class CostMatrixExample { public class CostMatrixExample {
@ -97,7 +98,7 @@ public class CostMatrixExample {
VehicleRoutingProblem vrp = VehicleRoutingProblem.Builder.newInstance().setFleetSize(FleetSize.INFINITE).setRoutingCost(costMatrix) VehicleRoutingProblem vrp = VehicleRoutingProblem.Builder.newInstance().setFleetSize(FleetSize.INFINITE).setRoutingCost(costMatrix)
.addVehicle(vehicle).addJob(s1).addJob(s2).addJob(s3).build(); .addVehicle(vehicle).addJob(s1).addJob(s2).addJob(s3).build();
VehicleRoutingAlgorithm vra = VehicleRoutingAlgorithms.readAndCreateAlgorithm(vrp, "input/fastAlgo.xml"); VehicleRoutingAlgorithm vra = Jsprit.createAlgorithm(vrp);
Collection<VehicleRoutingProblemSolution> solutions = vra.searchSolutions(); Collection<VehicleRoutingProblemSolution> solutions = vra.searchSolutions();

View file

@ -0,0 +1,74 @@
package jsprit.examples;
import jsprit.analysis.toolbox.AlgorithmSearchProgressChartListener;
import jsprit.analysis.toolbox.Plotter;
import jsprit.core.algorithm.VehicleRoutingAlgorithm;
import jsprit.core.algorithm.box.Jsprit;
import jsprit.core.analysis.SolutionAnalyser;
import jsprit.core.problem.Location;
import jsprit.core.problem.VehicleRoutingProblem;
import jsprit.core.problem.cost.TransportDistance;
import jsprit.core.problem.job.Service;
import jsprit.core.problem.solution.VehicleRoutingProblemSolution;
import jsprit.core.problem.solution.route.activity.TimeWindow;
import jsprit.core.problem.vehicle.VehicleImpl;
import jsprit.core.problem.vehicle.VehicleTypeImpl;
import jsprit.core.reporting.SolutionPrinter;
import jsprit.core.util.RandomNumberGeneration;
import jsprit.core.util.Solutions;
import java.util.Random;
/**
* Created by schroeder on 23/07/15.
*/
public class WaitingTimeExample {
public static void main(String[] args) {
VehicleTypeImpl type = VehicleTypeImpl.Builder.newInstance("type").setCostPerDistance(4.).setCostPerWaitingTime(1.0).build();
VehicleTypeImpl type1 = VehicleTypeImpl.Builder.newInstance("type1").setCostPerDistance(4.).setCostPerWaitingTime(1.0).build();
VehicleImpl v2 = VehicleImpl.Builder.newInstance("v2").setType(type).setReturnToDepot(true)
.setStartLocation(Location.newInstance(0, 0))
.setEarliestStart(0).setLatestArrival(220)
.build();
VehicleImpl v3 = VehicleImpl.Builder.newInstance("v3").setType(type1).setReturnToDepot(true)
.setStartLocation(Location.newInstance(0, 10))
.setEarliestStart(200).setLatestArrival(450)
.build();
VehicleRoutingProblem.Builder vrpBuilder = VehicleRoutingProblem.Builder.newInstance();
Random r = RandomNumberGeneration.newInstance();
for(int i=0;i<40;i++){
Service s = Service.Builder.newInstance("s_"+i).setServiceTime(5)
.setLocation(Location.newInstance(1 - r.nextInt(5), 10 + r.nextInt(10))).build();
vrpBuilder.addJob(s);
}
Service s1 = Service.Builder.newInstance("s12").setLocation(Location.newInstance(-3, 15)).setTimeWindow(TimeWindow.newInstance(290, 600)).build();
Service s4 = Service.Builder.newInstance("s13").setLocation(Location.newInstance(0,20)).setTimeWindow(TimeWindow.newInstance(290, 340)).build();
Service s2 = Service.Builder.newInstance("s10").setLocation(Location.newInstance(-1, 15)).setTimeWindow(TimeWindow.newInstance(300, 350)).build();
Service s3 = Service.Builder.newInstance("s11").setLocation(Location.newInstance(10, 10)).setTimeWindow(TimeWindow.newInstance(400, 600)).build();
vrpBuilder.addJob(s1).addJob(s2).addJob(s3).addJob(s4).addVehicle(v2).addVehicle(v3);
vrpBuilder.setFleetSize(VehicleRoutingProblem.FleetSize.FINITE);
final VehicleRoutingProblem vrp = vrpBuilder.build();
VehicleRoutingAlgorithm vra = Jsprit.createAlgorithm(vrp);
vra.setMaxIterations(2000);
vra.addListener(new AlgorithmSearchProgressChartListener("output/search"));
VehicleRoutingProblemSolution solution = Solutions.bestOf(vra.searchSolutions());
System.out.println("c: " + solution.getCost());
SolutionPrinter.print(vrp, solution, SolutionPrinter.Print.VERBOSE);
SolutionAnalyser sa = new SolutionAnalyser(vrp, solution, new TransportDistance() {
@Override
public double getDistance(Location from, Location to) {
return vrp.getTransportCosts().getTransportTime(from,to,0.,null,null);
}
});
System.out.println("totalWaiting: " + sa.getWaitingTime());
System.out.println("brokenTWs: " + sa.getTimeWindowViolation());
new Plotter(vrp,solution).setLabel(Plotter.Label.ID).plot("output/plot","plot");
}
}

View file

@ -0,0 +1,90 @@
package jsprit.examples;
import jsprit.analysis.toolbox.AlgorithmSearchProgressChartListener;
import jsprit.analysis.toolbox.Plotter;
import jsprit.core.algorithm.VehicleRoutingAlgorithm;
import jsprit.core.algorithm.box.Jsprit;
import jsprit.core.problem.Location;
import jsprit.core.problem.VehicleRoutingProblem;
import jsprit.core.problem.job.Service;
import jsprit.core.problem.solution.VehicleRoutingProblemSolution;
import jsprit.core.problem.solution.route.activity.TimeWindow;
import jsprit.core.problem.vehicle.VehicleImpl;
import jsprit.core.problem.vehicle.VehicleTypeImpl;
import jsprit.core.reporting.SolutionPrinter;
import jsprit.core.util.Solutions;
/**
* Created by schroeder on 23/07/15.
*/
public class WaitingTimeExample2 {
static interface AlgorithmFactory {
VehicleRoutingAlgorithm createAlgorithm(VehicleRoutingProblem vrp);
}
public static void main(String[] args) {
VehicleTypeImpl type = VehicleTypeImpl.Builder.newInstance("type").setCostPerDistance(1.5).setCostPerWaitingTime(1.).build();
// VehicleTypeImpl type1 = VehicleTypeImpl.Builder.newInstance("type1").setCostPerDistance(1.5).setCostPerWaitingTime(.0).build();
VehicleImpl v2 = VehicleImpl.Builder.newInstance("v2").setType(type).setReturnToDepot(true)
.setStartLocation(Location.newInstance(0, 0)).build();
VehicleRoutingProblem.Builder vrpBuilder = VehicleRoutingProblem.Builder.newInstance();
Service s1 = Service.Builder.newInstance("s12").setLocation(Location.newInstance(-1, 5)).setTimeWindow(TimeWindow.newInstance(100, 110)).build();
Service s4 = Service.Builder.newInstance("s13").setLocation(Location.newInstance(0, 10)).build();
Service s2 = Service.Builder.newInstance("s10").setLocation(Location.newInstance(1, 12)).build();
Service s3 = Service.Builder.newInstance("s11").setLocation(Location.newInstance(4, 10)).build();
Service s5 = Service.Builder.newInstance("s14").setLocation(Location.newInstance(6, 5)).setTimeWindow(TimeWindow.newInstance(110,220)).build();
vrpBuilder.addJob(s1).addJob(s2).addJob(s3).addJob(s4).addJob(s5).addVehicle(v2);
vrpBuilder.setFleetSize(VehicleRoutingProblem.FleetSize.FINITE);
final VehicleRoutingProblem vrp = vrpBuilder.build();
// AlgorithmFactory algorithmFactory = new AlgorithmFactory() {
// @Override
// public VehicleRoutingAlgorithm createAlgorithm(final VehicleRoutingProblem vrp) {
// StateManager stateManager = new StateManager(vrp);
// stateManager.addStateUpdater(new UpdateFutureWaitingTimes(stateManager,vrp.getTransportCosts()));
// ConstraintManager constraintManager = new ConstraintManager(vrp,stateManager);
//
// return Jsprit.Builder.newInstance(vrp)
// .addCoreStateAndConstraintStuff(true)
// .setStateAndConstraintManager(stateManager, constraintManager)
//// .setProperty(Jsprit.Parameter.THRESHOLD_INI, "0.1")
//// .setProperty(Jsprit.Parameter.THRESHOLD_ALPHA, "0.3")
//// .setProperty(Parameter.)
//// .setProperty(Jsprit.Parameter.CONSTRUCTION, Jsprit.Construction.BEST_INSERTION.toString())
// .setObjectiveFunction(new SolutionCostCalculator() {
// @Override
// public double getCosts(VehicleRoutingProblemSolution solution) {
// double costs = 0.;
// for (VehicleRoute route : solution.getRoutes()) {
// costs += route.getVehicle().getType().getVehicleCostParams().fix;
// TourActivity prevAct = route.getStart();
// for (TourActivity act : route.getActivities()) {
// costs += vrp.getTransportCosts().getTransportCost(prevAct.getLocation(), act.getLocation(), prevAct.getEndTime(), route.getDriver(), route.getVehicle());
// costs += vrp.getActivityCosts().getActivityCost(act, act.getArrTime(), route.getDriver(), route.getVehicle());
// prevAct = act;
// }
// costs += vrp.getTransportCosts().getTransportCost(prevAct.getLocation(), route.getEnd().getLocation(), prevAct.getEndTime(), route.getDriver(), route.getVehicle());
// }
// costs += solution.getUnassignedJobs().size() * 200;
// return costs;
// }
// })
// .buildAlgorithm();
// }
// };
VehicleRoutingAlgorithm vra = Jsprit.createAlgorithm(vrp);
vra.setMaxIterations(1000);
vra.addListener(new AlgorithmSearchProgressChartListener("output/search"));
VehicleRoutingProblemSolution solution = Solutions.bestOf(vra.searchSolutions());
System.out.println("c: " + solution.getCost());
SolutionPrinter.print(vrp, solution, SolutionPrinter.Print.VERBOSE);
new Plotter(vrp,solution).setLabel(Plotter.Label.ID).plot("output/plot","plot");
}
}