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

variable departure times and waiting time opt

This commit is contained in:
oblonski 2015-07-29 20:47:26 +02:00
parent 552729d7ee
commit f9c255cc08
24 changed files with 881 additions and 110 deletions

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;
@ -195,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);
@ -202,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)){
@ -219,6 +221,37 @@ public class VehicleRoutingAlgorithm {
return solutions; return solutions;
} }
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 addBestEver(Collection<VehicleRoutingProblemSolution> solutions) { private void addBestEver(Collection<VehicleRoutingProblemSolution> solutions) {
if(bestEver != null) solutions.add(bestEver); if(bestEver != null) solutions.add(bestEver);
} }

View file

@ -554,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

@ -28,13 +28,13 @@ public class ConfigureLocalActivityInsertionCalculator implements InsertionStart
public void informInsertionStarts(Collection<VehicleRoute> vehicleRoutes, Collection<Job> unassignedJobs) { public void informInsertionStarts(Collection<VehicleRoute> vehicleRoutes, Collection<Job> unassignedJobs) {
this.nuOfJobsToRecreate = unassignedJobs.size(); this.nuOfJobsToRecreate = unassignedJobs.size();
double completenessRatio = (1-((double)nuOfJobsToRecreate/(double)vrp.getJobs().values().size())); double completenessRatio = (1-((double)nuOfJobsToRecreate/(double)vrp.getJobs().values().size()));
localActivityInsertionCostsCalculator.setSolutionCompletenessRatio(completenessRatio); localActivityInsertionCostsCalculator.setSolutionCompletenessRatio(Math.max(0.5,completenessRatio));
} }
@Override @Override
public void informJobInserted(Job job2insert, VehicleRoute inRoute, double additionalCosts, double additionalTime) { public void informJobInserted(Job job2insert, VehicleRoute inRoute, double additionalCosts, double additionalTime) {
nuOfJobsToRecreate--; nuOfJobsToRecreate--;
double completenessRatio = (1-((double)nuOfJobsToRecreate/(double)vrp.getJobs().values().size())); double completenessRatio = (1-((double)nuOfJobsToRecreate/(double)vrp.getJobs().values().size()));
localActivityInsertionCostsCalculator.setSolutionCompletenessRatio(completenessRatio); localActivityInsertionCostsCalculator.setSolutionCompletenessRatio(Math.max(0.5,completenessRatio));
} }
} }

View file

@ -261,7 +261,7 @@ public class JobInsertionCostsCalculatorBuilder {
ActivityInsertionCostsCalculator actInsertionCalc; ActivityInsertionCostsCalculator actInsertionCalc;
ConfigureLocalActivityInsertionCalculator configLocal = null; 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);
configLocal = new ConfigureLocalActivityInsertionCalculator(vrp, (LocalActivityInsertionCostsCalculator) actInsertionCalc); configLocal = new ConfigureLocalActivityInsertionCalculator(vrp, (LocalActivityInsertionCostsCalculator) actInsertionCalc);
} }
else if(activityInsertionCostCalculator == null && !addDefaultCostCalc){ else if(activityInsertionCostCalculator == null && !addDefaultCostCalc){

View file

@ -18,12 +18,15 @@
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.Start; import jsprit.core.problem.solution.route.activity.Start;
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;
/** /**
@ -46,56 +49,96 @@ class LocalActivityInsertionCostsCalculator implements ActivityInsertionCostsCal
private double solutionCompletenessRatio = 1.; private double solutionCompletenessRatio = 1.;
public LocalActivityInsertionCostsCalculator(VehicleRoutingTransportCosts routingCosts, VehicleRoutingActivityCosts actCosts) { private double variableStartTimeFactor = 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;
}
public void setVariableStartTimeFactor(double variableStartTimeFactor) {
this.variableStartTimeFactor = variableStartTimeFactor;
} }
@Override @Override
public double getCosts(JobInsertionContext iFacts, TourActivity prevAct, TourActivity nextAct, TourActivity newAct, double depTimeAtPrevAct) { public double getCosts(JobInsertionContext iFacts, TourActivity prevAct, TourActivity nextAct, TourActivity newAct, double depTimeAtPrevAct) {
// double waiting = 0;
// if(!isEnd(nextAct)){
// waiting = stateManager.getActivityState(nextAct, InternalStates.WAITING,Double.class);
// }
double tp_costs_prevAct_newAct = routingCosts.getTransportCost(prevAct.getLocation(), newAct.getLocation(), depTimeAtPrevAct, iFacts.getNewDriver(), iFacts.getNewVehicle()); double tp_costs_prevAct_newAct = routingCosts.getTransportCost(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 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());
if(prevAct instanceof Start) {
if(iFacts.getNewVehicle().hasVariableDepartureTime()){ double slack_time_new = 0;
act_costs_newAct = 0; double slack_time_prev = 0;
} if(isStart(prevAct) && hasVariableDeparture(iFacts.getNewVehicle())) act_costs_newAct = 0;
else if(hasVariableDeparture(iFacts.getNewVehicle())){
Double slack_time_prev_ = stateManager.getActivityState(prevAct,iFacts.getNewVehicle(),InternalStates.TIME_SLACK,Double.class);
if(slack_time_prev_ == null) slack_time_prev = 0.;
else slack_time_prev = slack_time_prev_;
act_costs_newAct = activityCosts.getActivityCost(newAct, newAct_arrTime + slack_time_prev, iFacts.getNewDriver(), iFacts.getNewVehicle());
slack_time_new = Math.min(newAct.getTheoreticalLatestOperationStartTime() - newAct.getTheoreticalEarliestOperationStartTime(), Math.max(newAct_arrTime + slack_time_prev - newAct.getTheoreticalEarliestOperationStartTime(), 0));
} }
//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 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());
if(hasVariableDeparture(iFacts.getNewVehicle())){
act_costs_nextAct = activityCosts.getActivityCost(nextAct, nextAct_arrTime + slack_time_new, iFacts.getNewDriver(), iFacts.getNewVehicle());
}
double totalCosts = tp_costs_prevAct_newAct + tp_costs_newAct_nextAct + solutionCompletenessRatio * activityCostsWeight * (act_costs_newAct + act_costs_nextAct); double totalCosts = tp_costs_prevAct_newAct + tp_costs_newAct_nextAct + solutionCompletenessRatio * activityCostsWeight * (act_costs_newAct + act_costs_nextAct);
double oldCosts; double oldCosts;
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 + solutionCompletenessRatio * activityCostsWeight * 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 = prevAct.getEndTime() + routingCosts.getTransportTime(prevAct.getLocation(), nextAct.getLocation(), prevAct.getEndTime(), iFacts.getRoute().getDriver(), iFacts.getRoute().getVehicle());
double actCost_nextAct = activityCosts.getActivityCost(nextAct, arrTime_nextAct, iFacts.getRoute().getDriver(), iFacts.getRoute().getVehicle()); double actCost_nextAct = activityCosts.getActivityCost(nextAct, arrTime_nextAct, iFacts.getRoute().getDriver(), iFacts.getRoute().getVehicle());
if(isStart(prevAct) && hasVariableDeparture(iFacts.getRoute().getVehicle())) {
actCost_nextAct = 0;
}
else if(hasVariableDeparture(iFacts.getRoute().getVehicle())){
actCost_nextAct = activityCosts.getActivityCost(nextAct, arrTime_nextAct + slack_time_prev, iFacts.getRoute().getDriver(), iFacts.getRoute().getVehicle());
}
oldCosts = tp_costs_prevAct_nextAct + solutionCompletenessRatio * activityCostsWeight * actCost_nextAct; 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;
}
private boolean hasVariableDeparture(Vehicle newVehicle) {
return newVehicle.hasVariableDepartureTime();
}
private boolean isStart(TourActivity prevAct) {
return prevAct instanceof Start;
}
public void setActivityCostWeight(double weight){ public void setActivityCostWeight(double weight){
this.activityCostsWeight = weight; this.activityCostsWeight = weight;
} }

View file

@ -109,9 +109,9 @@ final class VehicleTypeDependentJobInsertionCalculator implements JobInsertionCo
relevantVehicles.addAll(fleetManager.getAvailableVehicles()); relevantVehicles.addAll(fleetManager.getAvailableVehicles());
} }
for(Vehicle v : relevantVehicles){ for(Vehicle v : relevantVehicles){
double depTime; double depTime = v.getEarliestDeparture();
if(v == selectedVehicle) depTime = currentRoute.getDepartureTime(); // if(v == selectedVehicle) depTime = currentRoute.getDepartureTime();
else depTime = v.getEarliestDeparture(); // else depTime = v.getEarliestDeparture();
InsertionData iData = insertionCalculator.getInsertionData(currentRoute, jobToInsert, v, depTime, selectedDriver, bestKnownCost_); InsertionData iData = insertionCalculator.getInsertionData(currentRoute, jobToInsert, v, depTime, selectedDriver, bestKnownCost_);
if(iData instanceof NoInsertionFound) { if(iData instanceof NoInsertionFound) {
continue; continue;

View file

@ -42,4 +42,8 @@ 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);
} }

View file

@ -21,34 +21,86 @@ 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.TourActivity; import jsprit.core.problem.solution.route.activity.TourActivity;
public class UpdateDepartureTime implements StateUpdater, RouteVisitor{ import java.util.Iterator;
private VehicleRoutingTransportCosts routingCosts; /**
* Updates and memorizes latest operation start times at activities.
*
* @author schroeder
*
*/
public class UpdateDepartureTime implements RouteVisitor, StateUpdater{
public UpdateDepartureTime(VehicleRoutingTransportCosts routingCosts) {
this.routingCosts = routingCosts;
private VehicleRoute route;
private VehicleRoutingTransportCosts transportCosts;
private double arrTimeAtPrevActWithoutWaiting;
private TourActivity prevAct;
private boolean hasEarliest = false;
private boolean hasVariableDepartureTime;
public UpdateDepartureTime(VehicleRoutingTransportCosts tpCosts) {
super();
this.transportCosts = tpCosts;
}
public void begin(VehicleRoute route) {
this.route = route;
hasEarliest = false;
prevAct = route.getEnd();
hasVariableDepartureTime = route.getVehicle().hasVariableDepartureTime();
}
public void visit(TourActivity activity) {
if(!hasVariableDepartureTime) return;
if(hasEarliest){
double potentialArrivalTimeAtCurrAct = arrTimeAtPrevActWithoutWaiting - transportCosts.getBackwardTransportTime(activity.getLocation(), prevAct.getLocation(), arrTimeAtPrevActWithoutWaiting, route.getDriver(),route.getVehicle()) - activity.getOperationTime();
if(potentialArrivalTimeAtCurrAct < activity.getTheoreticalEarliestOperationStartTime()){
arrTimeAtPrevActWithoutWaiting = activity.getTheoreticalEarliestOperationStartTime();
}
else if(potentialArrivalTimeAtCurrAct >= activity.getTheoreticalEarliestOperationStartTime() && potentialArrivalTimeAtCurrAct <= activity.getTheoreticalLatestOperationStartTime()){
arrTimeAtPrevActWithoutWaiting = potentialArrivalTimeAtCurrAct;
}
else {
arrTimeAtPrevActWithoutWaiting = activity.getTheoreticalLatestOperationStartTime();
}
}
else{
if(activity.getTheoreticalEarliestOperationStartTime() > 0){
hasEarliest = true;
arrTimeAtPrevActWithoutWaiting = activity.getTheoreticalEarliestOperationStartTime();
}
}
prevAct = activity;
}
public void finish() {
if(!hasVariableDepartureTime) return;
if(hasEarliest){
double dep = arrTimeAtPrevActWithoutWaiting - transportCosts.getBackwardTransportTime(route.getStart().getLocation(), prevAct.getLocation(), arrTimeAtPrevActWithoutWaiting, route.getDriver(),route.getVehicle());
double newDepartureTime = Math.max(route.getVehicle().getEarliestDeparture(), dep);
route.setVehicleAndDepartureTime(route.getVehicle(),newDepartureTime);
}
else route.setVehicleAndDepartureTime(route.getVehicle(),route.getVehicle().getEarliestDeparture());
} }
@Override @Override
public void visit(VehicleRoute route) { public void visit(VehicleRoute route) {
if(route.getVehicle() != null){ begin(route);
if(route.getVehicle().hasVariableDepartureTime()) { Iterator<TourActivity> revIterator = route.getTourActivities().reverseActivityIterator();
if (!route.isEmpty()) { while(revIterator.hasNext()){
TourActivity first = route.getActivities().get(0); visit(revIterator.next());
double earliestStart = first.getTheoreticalEarliestOperationStartTime();
double backwardTravelTime = routingCosts.getBackwardTransportTime(first.getLocation(), route.getStart().getLocation(),
earliestStart, route.getDriver(), route.getVehicle());
double newDepartureTime = Math.max(route.getStart().getEndTime(), earliestStart - backwardTravelTime);
route.setVehicleAndDepartureTime(route.getVehicle(), newDepartureTime);
} }
finish();
} }
}
}
} }

View file

@ -0,0 +1,81 @@
/*******************************************************************************
* 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.ActivityVisitor;
import jsprit.core.problem.solution.route.activity.TourActivity;
/**
* Updates arrival and end times of activities.
*
* <p>Note that this modifies arrTime and endTime of each activity in a route.
*
* @author stefan
*
*/
public class UpdateTimeSlack implements ActivityVisitor, StateUpdater{
private VehicleRoute route;
private StateManager stateManager;
private VehicleRoutingTransportCosts costs;
private double prevTimeSlack;
private double prevActDeparture;
private TourActivity prevAct;
public UpdateTimeSlack(StateManager stateManager, VehicleRoutingTransportCosts costs) {
this.stateManager = stateManager;
this.costs = costs;
}
@Override
public void begin(VehicleRoute route) {
if(route.isEmpty()) return;
this.route = route;
prevActDeparture = route.getVehicle().getEarliestDeparture();
TourActivity first = route.getActivities().get(0);
double latestArr = stateManager.getActivityState(first,route.getVehicle(),InternalStates.LATEST_OPERATION_START_TIME,Double.class);
double latest = latestArr - costs.getBackwardTransportCost(first.getLocation(),route.getStart().getLocation(),latestArr,route.getDriver(),route.getVehicle());
prevTimeSlack = latest - prevActDeparture;
prevAct = route.getStart();
}
@Override
public void visit(TourActivity activity) {
double actArrTime = prevActDeparture + costs.getTransportTime(prevAct.getLocation(),activity.getLocation(),prevActDeparture,route.getDriver(),route.getVehicle());
double actEarliestStart = Math.max(actArrTime,activity.getTheoreticalEarliestOperationStartTime());
double actLatestStart = stateManager.getActivityState(activity,route.getVehicle(),InternalStates.LATEST_OPERATION_START_TIME,Double.class);
double latest_minus_earliest = actLatestStart - actEarliestStart;
double time_slack_ = Math.max(actArrTime + prevTimeSlack - activity.getTheoreticalEarliestOperationStartTime(),0);
double time_slack = Math.min(latest_minus_earliest,time_slack_);
stateManager.putInternalTypedActivityState(activity,route.getVehicle(), InternalStates.TIME_SLACK, time_slack);
prevTimeSlack = time_slack;
prevAct = activity;
prevActDeparture = actEarliestStart + activity.getOperationTime();
}
@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,7 +103,7 @@ 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;
@ -75,19 +75,7 @@ public class VehicleRoutingProblem {
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>();

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

@ -47,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);
} }
@ -83,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

@ -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);
} }
@ -137,7 +137,7 @@ 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()){

View file

@ -298,7 +298,7 @@ public class VehicleImpl extends AbstractVehicle{
endLocation = builder.endLocation; endLocation = builder.endLocation;
startLocation = builder.startLocation; startLocation = builder.startLocation;
hasVariableDepartureTime = builder.hasVariableDepartureTime; hasVariableDepartureTime = builder.hasVariableDepartureTime;
setVehicleIdentifier(new VehicleTypeKey(type.getTypeId(),startLocation.getId(),endLocation.getId(),earliestDeparture,latestArrival,skills)); setVehicleIdentifier(new VehicleTypeKey(type.getTypeId(),startLocation.getId(),endLocation.getId(),earliestDeparture,latestArrival,skills, returnToDepot));
} }
/** /**

View file

@ -42,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+"]";
} }
} }
@ -66,6 +79,8 @@ public class VehicleTypeImpl implements VehicleType {
*/ */
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);
@ -80,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";
@ -143,13 +159,47 @@ public class VehicleTypeImpl implements VehicleType {
* @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.
* *
@ -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;
} }

View file

@ -37,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;
@ -46,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;
@ -77,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;
} }

View file

@ -13,16 +13,22 @@ import jsprit.core.problem.driver.Driver;
import jsprit.core.problem.job.Service; import jsprit.core.problem.job.Service;
import jsprit.core.problem.solution.SolutionCostCalculator; import jsprit.core.problem.solution.SolutionCostCalculator;
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.activity.TimeWindow; 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.VehicleImpl;
import jsprit.core.problem.vehicle.VehicleTypeImpl;
import jsprit.core.reporting.SolutionPrinter;
import jsprit.core.util.CostFactory; import jsprit.core.util.CostFactory;
import jsprit.core.util.RandomNumberGeneration;
import jsprit.core.util.Solutions; import jsprit.core.util.Solutions;
import junit.framework.Assert; import junit.framework.Assert;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import java.util.Random;
/** /**
* Created by schroeder on 22/07/15. * Created by schroeder on 22/07/15.
*/ */
@ -42,7 +48,7 @@ public class VariableDepartureAndWaitingTime_IT {
@Override @Override
public double getActivityCost(TourActivity tourAct, double arrivalTime, Driver driver, Vehicle vehicle) { public double getActivityCost(TourActivity tourAct, double arrivalTime, Driver driver, Vehicle vehicle) {
return Math.max(0,tourAct.getTheoreticalEarliestOperationStartTime() - arrivalTime); return vehicle.getType().getVehicleCostParams().perWaitingTimeUnit * Math.max(0,tourAct.getTheoreticalEarliestOperationStartTime() - arrivalTime);
} }
}; };
@ -138,6 +144,223 @@ public class VariableDepartureAndWaitingTime_IT {
Assert.assertEquals(40.,solution.getCost()); Assert.assertEquals(40.,solution.getCost());
} }
@Test
public void variableDepartureShouldWork3(){
VehicleImpl v = VehicleImpl.Builder.newInstance("v").setHasVariableDepartureTime(true).setStartLocation(Location.newInstance(0, 0)).build();
Service s1 = Service.Builder.newInstance("s1").setLocation(Location.newInstance(0,10)).setTimeWindow(TimeWindow.newInstance(10,10)).build();
Service s2 = Service.Builder.newInstance("s2").setLocation(Location.newInstance(5,15)).build();
Service s3 = Service.Builder.newInstance("s3").setLocation(Location.newInstance(10,10)).build();
final VehicleRoutingProblem vrp = VehicleRoutingProblem.Builder.newInstance()
.addJob(s1).addJob(s2).addJob(s3).addVehicle(v)
.setFleetSize(VehicleRoutingProblem.FleetSize.FINITE)
.setRoutingCost(CostFactory.createEuclideanCosts())
.setActivityCosts(activityCosts)
.build();
AlgorithmFactory algorithmFactory = new AlgorithmFactory() {
@Override
public VehicleRoutingAlgorithm createAlgorithm(final VehicleRoutingProblem vrp) {
StateManager stateManager = new StateManager(vrp);
stateManager.addStateUpdater(new UpdateDepartureTime(vrp.getTransportCosts()));
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();
}
};
VehicleRoutingAlgorithm vra = algorithmFactory.createAlgorithm(vrp);
vra.setMaxIterations(100);
VehicleRoutingProblemSolution solution = Solutions.bestOf(vra.searchSolutions());
System.out.println("c: " + solution.getCost());
Assert.assertEquals("s1", ((TourActivity.JobActivity) solution.getRoutes().iterator().next().getActivities().get(0)).getJob().getId());
Assert.assertEquals("s2",((TourActivity.JobActivity)solution.getRoutes().iterator().next().getActivities().get(1)).getJob().getId());
Assert.assertEquals("s3",((TourActivity.JobActivity)solution.getRoutes().iterator().next().getActivities().get(2)).getJob().getId());
}
@Test
public void variableDepartureShouldWork4(){
VehicleTypeImpl type = VehicleTypeImpl.Builder.newInstance("type").setCostPerDistance(1.0).setCostPerWaitingTime(1.).build();
VehicleImpl v = VehicleImpl.Builder.newInstance("v").setType(type).setHasVariableDepartureTime(false).setStartLocation(Location.newInstance(0, 0)).build();
Service s1 = Service.Builder.newInstance("s1").setLocation(Location.newInstance(0,10)).setTimeWindow(TimeWindow.newInstance(15,15)).build();
Service s2 = Service.Builder.newInstance("s2").setLocation(Location.newInstance(0,11)).setTimeWindow(TimeWindow.newInstance(100,100)).build();
Service s3 = Service.Builder.newInstance("s3").setLocation(Location.newInstance(10,10)).build();
final VehicleRoutingProblem vrp = VehicleRoutingProblem.Builder.newInstance()
.addJob(s1).addJob(s2).addJob(s3).addVehicle(v)
.setFleetSize(VehicleRoutingProblem.FleetSize.FINITE)
.setRoutingCost(CostFactory.createEuclideanCosts())
.build();
AlgorithmFactory algorithmFactory = new AlgorithmFactory() {
@Override
public VehicleRoutingAlgorithm createAlgorithm(final VehicleRoutingProblem vrp) {
StateManager stateManager = new StateManager(vrp);
stateManager.addStateUpdater(new UpdateDepartureTime(vrp.getTransportCosts()));
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) {
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() * 1000;
return costs;
}
})
.buildAlgorithm();
}
};
VehicleRoutingAlgorithm vra = algorithmFactory.createAlgorithm(vrp);
vra.setMaxIterations(100);
VehicleRoutingProblemSolution solution = Solutions.bestOf(vra.searchSolutions());
System.out.println("c: " + solution.getCost());
SolutionPrinter.print(vrp,solution, SolutionPrinter.Print.VERBOSE);
Assert.assertEquals("s1", ((TourActivity.JobActivity) solution.getRoutes().iterator().next().getActivities().get(0)).getJob().getId());
Assert.assertEquals("s3",((TourActivity.JobActivity)solution.getRoutes().iterator().next().getActivities().get(1)).getJob().getId());
Assert.assertEquals("s2",((TourActivity.JobActivity)solution.getRoutes().iterator().next().getActivities().get(2)).getJob().getId());
}
@Test
public void variableDepartureShouldWork5(){
VehicleTypeImpl type = VehicleTypeImpl.Builder.newInstance("type").setCostPerDistance(1.0).setCostPerWaitingTime(1.0).build();
VehicleImpl v = VehicleImpl.Builder.newInstance("v").setType(type).setHasVariableDepartureTime(true).setStartLocation(Location.newInstance(0, 0)).build();
VehicleImpl v2 = VehicleImpl.Builder.newInstance("v2").setType(type).setHasVariableDepartureTime(true).setStartLocation(Location.newInstance(0, 0)).build();
Service s1 = Service.Builder.newInstance("s1").setLocation(Location.newInstance(0,10)).setTimeWindow(TimeWindow.newInstance(15,15)).build();
Service s2 = Service.Builder.newInstance("s2").setLocation(Location.newInstance(0,11)).setTimeWindow(TimeWindow.newInstance(100,100)).build();
Service s3 = Service.Builder.newInstance("s3").setLocation(Location.newInstance(10,10)).build();
final VehicleRoutingProblem vrp = VehicleRoutingProblem.Builder.newInstance()
.addJob(s1).addJob(s2).addJob(s3).addVehicle(v).addVehicle(v2)
.setFleetSize(VehicleRoutingProblem.FleetSize.FINITE)
.setRoutingCost(CostFactory.createEuclideanCosts())
.build();
AlgorithmFactory algorithmFactory = new AlgorithmFactory() {
@Override
public VehicleRoutingAlgorithm createAlgorithm(final VehicleRoutingProblem vrp) {
StateManager stateManager = new StateManager(vrp);
stateManager.addStateUpdater(new UpdateDepartureTime(vrp.getTransportCosts()));
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) {
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() * 1000;
return costs;
}
})
.buildAlgorithm();
}
};
VehicleRoutingAlgorithm vra = algorithmFactory.createAlgorithm(vrp);
vra.setMaxIterations(100);
VehicleRoutingProblemSolution solution = Solutions.bestOf(vra.searchSolutions());
System.out.println("c: " + solution.getCost());
SolutionPrinter.print(vrp,solution, SolutionPrinter.Print.VERBOSE);
// Assert.assertEquals("s1", ((TourActivity.JobActivity) solution.getRoutes().iterator().next().getActivities().get(0)).getJob().getId());
// Assert.assertEquals("s3",((TourActivity.JobActivity)solution.getRoutes().iterator().next().getActivities().get(1)).getJob().getId());
// Assert.assertEquals("s2",((TourActivity.JobActivity)solution.getRoutes().iterator().next().getActivities().get(2)).getJob().getId());
}
@Test
public void variableDepartureShouldWork6(){
VehicleTypeImpl type = VehicleTypeImpl.Builder.newInstance("type").setCostPerDistance(1.0).setCostPerWaitingTime(1.0).build();
VehicleImpl v = VehicleImpl.Builder.newInstance("v").setType(type).setHasVariableDepartureTime(true).setStartLocation(Location.newInstance(0, 0)).build();
VehicleImpl v2 = VehicleImpl.Builder.newInstance("v2").setType(type).setHasVariableDepartureTime(true).setStartLocation(Location.newInstance(0, 0)).build();
VehicleRoutingProblem.Builder vrpBuilder = VehicleRoutingProblem.Builder.newInstance();
Random r = RandomNumberGeneration.newInstance();
for(int i=0;i<10;i++){
Service s = Service.Builder.newInstance("s"+i).setServiceTime(5).setLocation(Location.newInstance(0, 10 + r.nextInt(10))).build();
vrpBuilder.addJob(s);
}
Service s2 = Service.Builder.newInstance("s10").setLocation(Location.newInstance(10,21)).setTimeWindow(TimeWindow.newInstance(100,110)).build();
Service s3 = Service.Builder.newInstance("s11").setLocation(Location.newInstance(10,10)).setTimeWindow(TimeWindow.newInstance(300,310)).build();
vrpBuilder.addJob(s2).addJob(s3).addVehicle(v).addVehicle(v2);
vrpBuilder.setRoutingCost(CostFactory.createEuclideanCosts());
vrpBuilder.setFleetSize(VehicleRoutingProblem.FleetSize.FINITE);
final VehicleRoutingProblem vrp = vrpBuilder.build();
// final VehicleRoutingProblem vrp = VehicleRoutingProblem.Builder.newInstance()
// .addJob(s1).addJob(s2).addJob(s3).addVehicle(v).addVehicle(v2)
// .setFleetSize(VehicleRoutingProblem.FleetSize.FINITE)
// .setRoutingCost(CostFactory.createEuclideanCosts())
// .build();
AlgorithmFactory algorithmFactory = new AlgorithmFactory() {
@Override
public VehicleRoutingAlgorithm createAlgorithm(final VehicleRoutingProblem vrp) {
StateManager stateManager = new StateManager(vrp);
stateManager.addStateUpdater(new UpdateDepartureTime(vrp.getTransportCosts()));
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) {
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() * 1000;
return costs;
}
})
.buildAlgorithm();
}
};
VehicleRoutingAlgorithm vra = algorithmFactory.createAlgorithm(vrp);
vra.setMaxIterations(100);
VehicleRoutingProblemSolution solution = Solutions.bestOf(vra.searchSolutions());
System.out.println("c: " + solution.getCost());
SolutionPrinter.print(vrp,solution, SolutionPrinter.Print.VERBOSE);
// Assert.assertEquals("s1", ((TourActivity.JobActivity) solution.getRoutes().iterator().next().getActivities().get(0)).getJob().getId());
// Assert.assertEquals("s3",((TourActivity.JobActivity)solution.getRoutes().iterator().next().getActivities().get(1)).getJob().getId());
// Assert.assertEquals("s2",((TourActivity.JobActivity)solution.getRoutes().iterator().next().getActivities().get(2)).getJob().getId());
}
} }

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, null);
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, null);
createInsertionCalculator(hardRouteLevelConstraint); createInsertionCalculator(hardRouteLevelConstraint);
vehicleRoutingProblem = mock(VehicleRoutingProblem.class); vehicleRoutingProblem = mock(VehicleRoutingProblem.class);
} }

View file

@ -132,7 +132,7 @@ public class TestCalculatesServiceInsertion {
VehicleRoutingActivityCosts actCosts = mock(VehicleRoutingActivityCosts.class); VehicleRoutingActivityCosts actCosts = mock(VehicleRoutingActivityCosts.class);
serviceInsertion = new ServiceInsertionCalculator(costs, new LocalActivityInsertionCostsCalculator(costs, actCosts), cManager); serviceInsertion = new ServiceInsertionCalculator(costs, new LocalActivityInsertionCostsCalculator(costs, actCosts, states), cManager);
serviceInsertion.setJobActivityFactory(new JobActivityFactory() { serviceInsertion.setJobActivityFactory(new JobActivityFactory() {
@Override @Override
public List<AbstractActivity> createActivities(Job job) { public List<AbstractActivity> createActivities(Job job) {

View file

@ -16,14 +16,20 @@
******************************************************************************/ ******************************************************************************/
package jsprit.core.algorithm.recreate; package jsprit.core.algorithm.recreate;
import jsprit.core.algorithm.state.StateManager;
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.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.*;
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;
@ -66,7 +72,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, null);
} }
private Location loc(String i) { private Location loc(String i) {
@ -130,4 +136,111 @@ public class TestLocalActivityInsertionCostsCalculator {
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,50)).build();
ServiceActivity prevAct = ServiceActivity.newInstance(prevS);
ServiceActivity newAct = ServiceActivity.newInstance(newS);
ServiceActivity nextAct = ServiceActivity.newInstance(nextS);
VehicleRoute route = VehicleRoute.Builder.newInstance(v).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.);
calc.setVariableStartTimeFactor(.8);
double c = calc.getCosts(context,prevAct,nextAct,newAct,0);
assertEquals(40.,c,0.01);
}
// @Test
// public void test_(){
// VehicleTypeImpl type = VehicleTypeImpl.Builder.newInstance("t").setCostPerWaitingTime(1.).build();
// VehicleImpl v = VehicleImpl.Builder.newInstance("v").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").setLocation(Location.newInstance(40, 0)).build();
// Service nextS = Service.Builder.newInstance("next").setLocation(Location.newInstance(30,0)).setTimeWindow(TimeWindow.newInstance(140,150)).build();
// ServiceActivity prevAct = ServiceActivity.newInstance(prevS);
// ServiceActivity newAct = ServiceActivity.newInstance(newS);
// ServiceActivity nextAct = ServiceActivity.newInstance(nextS);
// VehicleRoute route = VehicleRoute.Builder.newInstance(v).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.);
//// calc.setVariableStartTimeFactor(1.);
// double c = calc.getCosts(context,prevAct,nextAct,newAct,0);
// assertEquals(0.,c,0.01);
// }
@Test
public void test2(){
VehicleTypeImpl type = VehicleTypeImpl.Builder.newInstance("t").setCostPerWaitingTime(1.).build();
VehicleImpl v = VehicleImpl.Builder.newInstance("v").setHasVariableDepartureTime(false).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).setLocation(Location.newInstance(10, 0)).build();
Service nextS = Service.Builder.newInstance("next").setLocation(Location.newInstance(30,0))
.setTimeWindow(TimeWindow.newInstance(40,50)).build();
Start prevAct = new Start(Location.newInstance(0,0),0,100);
// ServiceActivity prevAct = ServiceActivity.newInstance(prevS);
ServiceActivity newAct = ServiceActivity.newInstance(newS);
ServiceActivity nextAct = ServiceActivity.newInstance(nextS);
VehicleRoute route = VehicleRoute.Builder.newInstance(v).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,0);
assertEquals(-10.,c,0.01);
}
@Test
public void test3(){
VehicleTypeImpl type = VehicleTypeImpl.Builder.newInstance("t").setCostPerWaitingTime(1.).build();
// VehicleImpl v = VehicleImpl.Builder.newInstance("v").setHasVariableDepartureTime(false).setType(type).setStartLocation(Location.newInstance(0,0)).build();
VehicleImpl v2 = VehicleImpl.Builder.newInstance("v2").setHasVariableDepartureTime(false).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();
Start prevAct = new Start(Location.newInstance(0,0),0,100);
// ServiceActivity prevAct = ServiceActivity.newInstance(prevS);
ServiceActivity newAct = ServiceActivity.newInstance(newS);
ServiceActivity nextAct = ServiceActivity.newInstance(nextS);
VehicleRoute route = VehicleRoute.Builder.newInstance(v2).addService(nextS).build();
JobInsertionContext context = new JobInsertionContext(route,newS,v2,null,0.);
LocalActivityInsertionCostsCalculator calc = new LocalActivityInsertionCostsCalculator(CostFactory.createEuclideanCosts(),new WaitingTimeCosts(), null);
calc.setSolutionCompletenessRatio(1.);
double c = calc.getCosts(context,prevAct,nextAct,newAct,0);
assertEquals(-10.,c,0.01);
}
@Test
public void test4(){
VehicleTypeImpl type = VehicleTypeImpl.Builder.newInstance("t").setCostPerWaitingTime(1.).build();
VehicleImpl v = VehicleImpl.Builder.newInstance("v").setHasVariableDepartureTime(false).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 newS = Service.Builder.newInstance("new").setServiceTime(10).setLocation(Location.newInstance(10, 0)).setTimeWindow(TimeWindow.newInstance(100,150)).build();
// Service nextS = Service.Builder.newInstance("next").setLocation(Location.newInstance(30,0)).setTimeWindow(TimeWindow.newInstance(40,50)).build();
Start prevAct = new Start(Location.newInstance(0,0),0,100);
// ServiceActivity prevAct = ServiceActivity.newInstance(prevS);
ServiceActivity newAct = ServiceActivity.newInstance(newS);
End nextAct = new End(Location.newInstance(0,0),0,100);
// ServiceActivity nextAct = ServiceActivity.newInstance(nextS);
// ServiceActivity nextAct = ServiceActivity.newInstance(nextS);
VehicleRoute route = VehicleRoute.Builder.newInstance(v).build();
JobInsertionContext context = new JobInsertionContext(route,newS,v,null,0.);
LocalActivityInsertionCostsCalculator calc = new LocalActivityInsertionCostsCalculator(CostFactory.createEuclideanCosts(),new WaitingTimeCosts(),null );
calc.setSolutionCompletenessRatio(1.);
double c = calc.getCosts(context,prevAct,nextAct,newAct,0);
assertEquals(110.,c,0.01);
}
} }

View file

@ -1,13 +1,14 @@
package jsprit.core.algorithm.state; 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.job.Service; import jsprit.core.problem.job.Service;
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.TimeWindow; import jsprit.core.problem.solution.route.activity.TimeWindow;
import jsprit.core.problem.vehicle.VehicleImpl; import jsprit.core.problem.vehicle.VehicleImpl;
import jsprit.core.util.CostFactory; import jsprit.core.util.CostFactory;
import junit.framework.Assert; import junit.framework.Assert;
import org.junit.Before;
import org.junit.Test; import org.junit.Test;
/** /**
@ -15,83 +16,111 @@ import org.junit.Test;
*/ */
public class UpdateDepartureTimeTest { public class UpdateDepartureTimeTest {
RouteVisitor revVisitors;
@Before
public void doBefore(){
revVisitors = new UpdateDepartureTime(CostFactory.createManhattanCosts());
}
@Test @Test
public void whenNoTimeWindow_departureTimeShouldBeEarliestStartTime(){ public void whenNoTimeWindow_departureTimeShouldBeEarliestStartTime(){
VehicleRoutingTransportCosts routingCosts = CostFactory.createManhattanCosts();
VehicleImpl v = VehicleImpl.Builder.newInstance("v").setStartLocation(Location.newInstance(0,0)).build(); VehicleImpl v = VehicleImpl.Builder.newInstance("v").setStartLocation(Location.newInstance(0,0)).build();
Service s = Service.Builder.newInstance("s").setLocation(Location.newInstance(10,0)).build(); Service s = Service.Builder.newInstance("s").setLocation(Location.newInstance(10,0)).build();
VehicleRoute route = VehicleRoute.Builder.newInstance(v).addService(s).build(); VehicleRoute route = VehicleRoute.Builder.newInstance(v).addService(s).build();
revVisitors.visit(route);
UpdateDepartureTime udt = new UpdateDepartureTime(routingCosts);
udt.visit(route);
Assert.assertEquals(0.,route.getDepartureTime()); Assert.assertEquals(0.,route.getDepartureTime());
} }
@Test @Test
public void whenNoTimeWindow_departureTimeShouldBeEarliestStartTime2(){ public void whenNoTimeWindow_departureTimeShouldBeEarliestStartTime2(){
VehicleRoutingTransportCosts routingCosts = CostFactory.createManhattanCosts();
VehicleImpl v = VehicleImpl.Builder.newInstance("v").setEarliestStart(10).setStartLocation(Location.newInstance(0, 0)).build(); VehicleImpl v = VehicleImpl.Builder.newInstance("v").setEarliestStart(10).setStartLocation(Location.newInstance(0, 0)).build();
Service s = Service.Builder.newInstance("s").setLocation(Location.newInstance(10,0)).build(); Service s = Service.Builder.newInstance("s").setLocation(Location.newInstance(10,0)).build();
VehicleRoute route = VehicleRoute.Builder.newInstance(v).addService(s).build(); VehicleRoute route = VehicleRoute.Builder.newInstance(v).addService(s).build();
revVisitors.visit(route);
UpdateDepartureTime udt = new UpdateDepartureTime(routingCosts);
udt.visit(route);
Assert.assertEquals(10.,route.getDepartureTime()); Assert.assertEquals(10.,route.getDepartureTime());
} }
@Test @Test
public void whenTimeWindowAndNoWaitingTime_departureTimeShouldBeEarliestStartTime1(){ public void whenTimeWindowAndNoWaitingTime_departureTimeShouldBeEarliestStartTime1(){
VehicleRoutingTransportCosts routingCosts = CostFactory.createManhattanCosts();
VehicleImpl v = VehicleImpl.Builder.newInstance("v").setEarliestStart(0).setStartLocation(Location.newInstance(0,0)).build(); VehicleImpl v = VehicleImpl.Builder.newInstance("v").setEarliestStart(0).setStartLocation(Location.newInstance(0,0)).build();
Service s = Service.Builder.newInstance("s").setTimeWindow(TimeWindow.newInstance(5,20)).setLocation(Location.newInstance(10, 0)).build(); Service s = Service.Builder.newInstance("s").setTimeWindow(TimeWindow.newInstance(5,20)).setLocation(Location.newInstance(10, 0)).build();
VehicleRoute route = VehicleRoute.Builder.newInstance(v).addService(s).build(); VehicleRoute route = VehicleRoute.Builder.newInstance(v).addService(s).build();
revVisitors.visit(route);
UpdateDepartureTime udt = new UpdateDepartureTime(routingCosts);
udt.visit(route);
Assert.assertEquals(0.,route.getDepartureTime()); Assert.assertEquals(0.,route.getDepartureTime());
} }
@Test @Test
public void whenTimeWindowAndNoWaitingTime_departureTimeShouldBeEarliestStartTime2(){ public void whenTimeWindowAndNoWaitingTime_departureTimeShouldBeEarliestStartTime2(){
VehicleRoutingTransportCosts routingCosts = CostFactory.createManhattanCosts();
VehicleImpl v = VehicleImpl.Builder.newInstance("v").setEarliestStart(10).setStartLocation(Location.newInstance(0,0)).build(); VehicleImpl v = VehicleImpl.Builder.newInstance("v").setEarliestStart(10).setStartLocation(Location.newInstance(0,0)).build();
Service s = Service.Builder.newInstance("s").setTimeWindow(TimeWindow.newInstance(5,20)).setLocation(Location.newInstance(10, 0)).build(); Service s = Service.Builder.newInstance("s").setTimeWindow(TimeWindow.newInstance(5,20)).setLocation(Location.newInstance(10, 0)).build();
VehicleRoute route = VehicleRoute.Builder.newInstance(v).addService(s).build(); VehicleRoute route = VehicleRoute.Builder.newInstance(v).addService(s).build();
revVisitors.visit(route);
UpdateDepartureTime udt = new UpdateDepartureTime(routingCosts);
udt.visit(route);
Assert.assertEquals(10.,route.getDepartureTime()); Assert.assertEquals(10.,route.getDepartureTime());
} }
@Test @Test
public void whenTimeWindowAndWaitingTime_departureTimeShouldChange(){ public void whenTimeWindowAndWaitingTime_departureTimeShouldChange(){
VehicleRoutingTransportCosts routingCosts = CostFactory.createManhattanCosts();
VehicleImpl v = VehicleImpl.Builder.newInstance("v").setEarliestStart(0) VehicleImpl v = VehicleImpl.Builder.newInstance("v").setEarliestStart(0)
.setHasVariableDepartureTime(true) .setHasVariableDepartureTime(true)
.setStartLocation(Location.newInstance(0,0)).build(); .setStartLocation(Location.newInstance(0,0)).build();
Service s = Service.Builder.newInstance("s").setTimeWindow(TimeWindow.newInstance(15,20)).setLocation(Location.newInstance(10, 0)).build(); Service s = Service.Builder.newInstance("s").setTimeWindow(TimeWindow.newInstance(15,20)).setLocation(Location.newInstance(10, 0)).build();
VehicleRoute route = VehicleRoute.Builder.newInstance(v).addService(s).build(); VehicleRoute route = VehicleRoute.Builder.newInstance(v).addService(s).build();
revVisitors.visit(route);
UpdateDepartureTime udt = new UpdateDepartureTime(routingCosts);
udt.visit(route);
Assert.assertEquals(5.,route.getDepartureTime()); Assert.assertEquals(5.,route.getDepartureTime());
} }
@Test @Test
public void whenTimeWindowAndWaitingTime_departureTimeShouldChange2(){ public void whenTimeWindowAndWaitingTime_departureTimeShouldChange2(){
VehicleRoutingTransportCosts routingCosts = CostFactory.createManhattanCosts();
VehicleImpl v = VehicleImpl.Builder.newInstance("v").setHasVariableDepartureTime(true).setEarliestStart(5).setStartLocation(Location.newInstance(0,0)).build(); VehicleImpl v = VehicleImpl.Builder.newInstance("v").setHasVariableDepartureTime(true).setEarliestStart(5).setStartLocation(Location.newInstance(0,0)).build();
Service s = Service.Builder.newInstance("s").setTimeWindow(TimeWindow.newInstance(18,20)).setLocation(Location.newInstance(10, 0)).build(); Service s = Service.Builder.newInstance("s").setTimeWindow(TimeWindow.newInstance(18,20)).setLocation(Location.newInstance(10, 0)).build();
VehicleRoute route = VehicleRoute.Builder.newInstance(v).addService(s).build(); VehicleRoute route = VehicleRoute.Builder.newInstance(v).addService(s).build();
revVisitors.visit(route);
UpdateDepartureTime udt = new UpdateDepartureTime(routingCosts);
udt.visit(route);
Assert.assertEquals(8.,route.getDepartureTime()); Assert.assertEquals(8.,route.getDepartureTime());
} }
@Test
public void whenTimeWindowAndWaitingTime_departureTimeShouldChange3(){
VehicleImpl v = VehicleImpl.Builder.newInstance("v").setHasVariableDepartureTime(true).setEarliestStart(0).setStartLocation(Location.newInstance(0,0)).build();
Service s = Service.Builder.newInstance("s")
.setTimeWindow(TimeWindow.newInstance(15, 20)).setLocation(Location.newInstance(10, 0)).build();
Service s2 = Service.Builder.newInstance("s2")
.setTimeWindow(TimeWindow.newInstance(10,40)).setLocation(Location.newInstance(20, 0)).build();
VehicleRoute route = VehicleRoute.Builder.newInstance(v).addService(s).addService(s2).build();
revVisitors.visit(route);
Assert.assertEquals(5.,route.getDepartureTime());
}
@Test
public void whenTimeWindowAndWaitingTime_departureTimeShouldChange4(){
VehicleImpl v = VehicleImpl.Builder.newInstance("v").setHasVariableDepartureTime(true).setEarliestStart(0).setStartLocation(Location.newInstance(0,0)).build();
Service s = Service.Builder.newInstance("s")
.setTimeWindow(TimeWindow.newInstance(15, 20)).setLocation(Location.newInstance(10, 0)).build();
Service s2 = Service.Builder.newInstance("s2")
.setTimeWindow(TimeWindow.newInstance(29,40)).setLocation(Location.newInstance(20, 0)).build();
VehicleRoute route = VehicleRoute.Builder.newInstance(v).addService(s).addService(s2).build();
revVisitors.visit(route);
Assert.assertEquals(9.,route.getDepartureTime());
}
@Test
public void whenTimeWindowAndWaitingTime_departureTimeShouldChange5(){
VehicleImpl v = VehicleImpl.Builder.newInstance("v").setHasVariableDepartureTime(true).setEarliestStart(0).setStartLocation(Location.newInstance(0,0)).build();
Service s = Service.Builder.newInstance("s")
.setTimeWindow(TimeWindow.newInstance(15, 20)).setLocation(Location.newInstance(10, 0)).build();
Service s2 = Service.Builder.newInstance("s2")
.setTimeWindow(TimeWindow.newInstance(35,40)).setLocation(Location.newInstance(20, 0)).build();
VehicleRoute route = VehicleRoute.Builder.newInstance(v).addService(s).addService(s2).build();
revVisitors.visit(route);
Assert.assertEquals(10.,route.getDepartureTime());
}
} }

View file

@ -0,0 +1,119 @@
package jsprit.core.algorithm.state;
import jsprit.core.problem.Location;
import jsprit.core.problem.VehicleRoutingProblem;
import jsprit.core.problem.job.Service;
import jsprit.core.problem.solution.route.VehicleRoute;
import jsprit.core.problem.solution.route.activity.TimeWindow;
import jsprit.core.problem.vehicle.VehicleImpl;
import jsprit.core.problem.vehicle.VehicleType;
import jsprit.core.problem.vehicle.VehicleTypeImpl;
import jsprit.core.util.CostFactory;
import junit.framework.Assert;
import org.junit.Test;
import java.util.Arrays;
/**
* Created by schroeder on 29/07/15.
*/
public class UpdateTimeSlackTest {
@Test
public void test_withoutTW(){
VehicleType type = VehicleTypeImpl.Builder.newInstance("t").build();
VehicleImpl vehicle = VehicleImpl.Builder.newInstance("v").setLatestArrival(200).setStartLocation(Location.newInstance("0,0")).setType(type).build();
Service service = Service.Builder.newInstance("s").setLocation(Location.newInstance("0,10")).build();
Service service2 = Service.Builder.newInstance("s2").setLocation(Location.newInstance("10,10")).build();
Service service3 = Service.Builder.newInstance("s3").setLocation(Location.newInstance("10,0")).build();
VehicleRoutingProblem vrp = VehicleRoutingProblem.Builder.newInstance().addVehicle(vehicle).addJob(service)
.addJob(service2).addJob(service3).setRoutingCost(CostFactory.createManhattanCosts()).build();
VehicleRoute route = VehicleRoute.Builder.newInstance(vehicle).setJobActivityFactory(vrp.getJobActivityFactory()).addService(service).addService(service2).addService(service3).build();
StateManager stateManager = new StateManager(vrp);
stateManager.addStateUpdater(new UpdateVehicleDependentPracticalTimeWindows(stateManager,CostFactory.createManhattanCosts()));
stateManager.addStateUpdater(new UpdateTimeSlack(stateManager,CostFactory.createManhattanCosts()));
stateManager.informInsertionStarts(Arrays.asList(route), null);
double timeSlack_act1 = stateManager.getActivityState(route.getActivities().get(0),route.getVehicle(),InternalStates.TIME_SLACK,Double.class);
double timeSlack_act2 = stateManager.getActivityState(route.getActivities().get(1),route.getVehicle(),InternalStates.TIME_SLACK,Double.class);
double timeSlack_act3 = stateManager.getActivityState(route.getActivities().get(2),route.getVehicle(),InternalStates.TIME_SLACK,Double.class);
Assert.assertEquals(160.,timeSlack_act1);
Assert.assertEquals(160.,timeSlack_act2);
Assert.assertEquals(160.,timeSlack_act3);
}
@Test
public void test_TW(){
VehicleType type = VehicleTypeImpl.Builder.newInstance("t").build();
VehicleImpl vehicle = VehicleImpl.Builder.newInstance("v").setLatestArrival(200).setStartLocation(Location.newInstance("0,0")).setType(type).build();
Service service = Service.Builder.newInstance("s").setTimeWindow(TimeWindow.newInstance(10,40)).setLocation(Location.newInstance("0,10")).build();
Service service2 = Service.Builder.newInstance("s2").setTimeWindow(TimeWindow.newInstance(0, 40)).setLocation(Location.newInstance("10,10")).build();
Service service3 = Service.Builder.newInstance("s3").setTimeWindow(TimeWindow.newInstance(80, 120)).setLocation(Location.newInstance("10,0")).build();
VehicleRoutingProblem vrp = VehicleRoutingProblem.Builder.newInstance().addVehicle(vehicle).addJob(service)
.addJob(service2).addJob(service3).setRoutingCost(CostFactory.createManhattanCosts()).build();
VehicleRoute route = VehicleRoute.Builder.newInstance(vehicle).setJobActivityFactory(vrp.getJobActivityFactory()).addService(service).addService(service2).addService(service3).build();
StateManager stateManager = new StateManager(vrp);
stateManager.addStateUpdater(new UpdateVehicleDependentPracticalTimeWindows(stateManager,CostFactory.createManhattanCosts()));
stateManager.addStateUpdater(new UpdateTimeSlack(stateManager,CostFactory.createManhattanCosts()));
stateManager.informInsertionStarts(Arrays.asList(route), null);
double timeSlack_act1 = stateManager.getActivityState(route.getActivities().get(0),route.getVehicle(),InternalStates.TIME_SLACK,Double.class);
double timeSlack_act2 = stateManager.getActivityState(route.getActivities().get(1),route.getVehicle(),InternalStates.TIME_SLACK,Double.class);
double timeSlack_act3 = stateManager.getActivityState(route.getActivities().get(2),route.getVehicle(),InternalStates.TIME_SLACK,Double.class);
Assert.assertEquals(20.,timeSlack_act1);
Assert.assertEquals(20.,timeSlack_act2);
Assert.assertEquals(0.,timeSlack_act3);
}
@Test
public void test_TW2(){
VehicleType type = VehicleTypeImpl.Builder.newInstance("t").build();
VehicleImpl vehicle = VehicleImpl.Builder.newInstance("v").setLatestArrival(200).setStartLocation(Location.newInstance("0,0")).setType(type).build();
Service service = Service.Builder.newInstance("s").setTimeWindow(TimeWindow.newInstance(10,40)).setLocation(Location.newInstance("0,10")).build();
Service service2 = Service.Builder.newInstance("s2").setTimeWindow(TimeWindow.newInstance(0,40)).setLocation(Location.newInstance("10,10")).build();
Service service3 = Service.Builder.newInstance("s3").setTimeWindow(TimeWindow.newInstance(40,120)).setLocation(Location.newInstance("10,0")).build();
VehicleRoutingProblem vrp = VehicleRoutingProblem.Builder.newInstance().addVehicle(vehicle).addJob(service)
.addJob(service2).addJob(service3).setRoutingCost(CostFactory.createManhattanCosts()).build();
VehicleRoute route = VehicleRoute.Builder.newInstance(vehicle).setJobActivityFactory(vrp.getJobActivityFactory()).addService(service).addService(service2).addService(service3).build();
StateManager stateManager = new StateManager(vrp);
stateManager.addStateUpdater(new UpdateVehicleDependentPracticalTimeWindows(stateManager,CostFactory.createManhattanCosts()));
stateManager.addStateUpdater(new UpdateTimeSlack(stateManager,CostFactory.createManhattanCosts()));
stateManager.informInsertionStarts(Arrays.asList(route), null);
double timeSlack_act1 = stateManager.getActivityState(route.getActivities().get(0),route.getVehicle(),InternalStates.TIME_SLACK,Double.class);
double timeSlack_act2 = stateManager.getActivityState(route.getActivities().get(1),route.getVehicle(),InternalStates.TIME_SLACK,Double.class);
double timeSlack_act3 = stateManager.getActivityState(route.getActivities().get(2),route.getVehicle(),InternalStates.TIME_SLACK,Double.class);
Assert.assertEquals(20.,timeSlack_act1);
Assert.assertEquals(20.,timeSlack_act2);
Assert.assertEquals(10.,timeSlack_act3);
}
@Test
public void test_TW3(){
VehicleType type = VehicleTypeImpl.Builder.newInstance("t").build();
VehicleImpl vehicle = VehicleImpl.Builder.newInstance("v").setLatestArrival(200).setStartLocation(Location.newInstance("0,0")).setType(type).build();
Service service = Service.Builder.newInstance("s").setTimeWindow(TimeWindow.newInstance(10,40)).setLocation(Location.newInstance("0,10")).build();
Service service2 = Service.Builder.newInstance("s2").setTimeWindow(TimeWindow.newInstance(30,60)).setLocation(Location.newInstance("10,10")).build();
Service service3 = Service.Builder.newInstance("s3").setTimeWindow(TimeWindow.newInstance(40,120)).setLocation(Location.newInstance("10,0")).build();
VehicleRoutingProblem vrp = VehicleRoutingProblem.Builder.newInstance().addVehicle(vehicle).addJob(service)
.addJob(service2).addJob(service3).setRoutingCost(CostFactory.createManhattanCosts()).build();
VehicleRoute route = VehicleRoute.Builder.newInstance(vehicle).setJobActivityFactory(vrp.getJobActivityFactory()).addService(service).addService(service2).addService(service3).build();
StateManager stateManager = new StateManager(vrp);
stateManager.addStateUpdater(new UpdateVehicleDependentPracticalTimeWindows(stateManager,CostFactory.createManhattanCosts()));
stateManager.addStateUpdater(new UpdateTimeSlack(stateManager,CostFactory.createManhattanCosts()));
stateManager.informInsertionStarts(Arrays.asList(route), null);
double timeSlack_act1 = stateManager.getActivityState(route.getActivities().get(0),route.getVehicle(),InternalStates.TIME_SLACK,Double.class);
double timeSlack_act2 = stateManager.getActivityState(route.getActivities().get(1),route.getVehicle(),InternalStates.TIME_SLACK,Double.class);
double timeSlack_act3 = stateManager.getActivityState(route.getActivities().get(2),route.getVehicle(),InternalStates.TIME_SLACK,Double.class);
Assert.assertEquals(30.,timeSlack_act1);
Assert.assertEquals(20.,timeSlack_act2);
Assert.assertEquals(20.,timeSlack_act3);
}
}