diff --git a/jsprit-core/src/main/java/jsprit/core/algorithm/VehicleRoutingAlgorithm.java b/jsprit-core/src/main/java/jsprit/core/algorithm/VehicleRoutingAlgorithm.java index df46b466..35891e16 100644 --- a/jsprit-core/src/main/java/jsprit/core/algorithm/VehicleRoutingAlgorithm.java +++ b/jsprit-core/src/main/java/jsprit/core/algorithm/VehicleRoutingAlgorithm.java @@ -20,6 +20,7 @@ import jsprit.core.algorithm.SearchStrategy.DiscoveredSolution; import jsprit.core.algorithm.listener.*; import jsprit.core.algorithm.termination.PrematureAlgorithmTermination; import jsprit.core.problem.VehicleRoutingProblem; +import jsprit.core.problem.job.Job; import jsprit.core.problem.solution.VehicleRoutingProblemSolution; import jsprit.core.problem.solution.route.VehicleRoute; import jsprit.core.problem.solution.route.activity.TourActivity; @@ -195,6 +196,7 @@ public class VehicleRoutingAlgorithm { Collection solutions = new ArrayList(initialSolutions); algorithmStarts(problem,solutions); bestEver = Solutions.bestOf(solutions); + if(logger.isTraceEnabled()) log(solutions); logger.info("iterations start"); for(int i=0;i< maxIterations;i++){ iterationStarts(i+1,problem,solutions); @@ -202,7 +204,7 @@ public class VehicleRoutingAlgorithm { counter.incCounter(); SearchStrategy strategy = searchStrategyManager.getRandomStrategy(); DiscoveredSolution discoveredSolution = strategy.run(problem, solutions); - logger.trace("discovered solution: " + discoveredSolution); + if(logger.isTraceEnabled()) log(discoveredSolution); memorizeIfBestEver(discoveredSolution); selectedStrategy(discoveredSolution,problem,solutions); if(terminationManager.isPrematureBreak(discoveredSolution)){ @@ -219,7 +221,38 @@ public class VehicleRoutingAlgorithm { return solutions; } - private void addBestEver(Collection solutions) { + private void log(Collection 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 solutions) { if(bestEver != null) solutions.add(bestEver); } diff --git a/jsprit-core/src/main/java/jsprit/core/algorithm/box/Jsprit.java b/jsprit-core/src/main/java/jsprit/core/algorithm/box/Jsprit.java index add86df7..3bbfeb86 100644 --- a/jsprit-core/src/main/java/jsprit/core/algorithm/box/Jsprit.java +++ b/jsprit-core/src/main/java/jsprit/core/algorithm/box/Jsprit.java @@ -554,6 +554,7 @@ public class Jsprit { 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()); diff --git a/jsprit-core/src/main/java/jsprit/core/algorithm/recreate/ConfigureLocalActivityInsertionCalculator.java b/jsprit-core/src/main/java/jsprit/core/algorithm/recreate/ConfigureLocalActivityInsertionCalculator.java new file mode 100644 index 00000000..1c2850df --- /dev/null +++ b/jsprit-core/src/main/java/jsprit/core/algorithm/recreate/ConfigureLocalActivityInsertionCalculator.java @@ -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 vehicleRoutes, Collection 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)); + } +} diff --git a/jsprit-core/src/main/java/jsprit/core/algorithm/recreate/JobInsertionCostsCalculatorBuilder.java b/jsprit-core/src/main/java/jsprit/core/algorithm/recreate/JobInsertionCostsCalculatorBuilder.java index aa661a2a..a96eccda 100644 --- a/jsprit-core/src/main/java/jsprit/core/algorithm/recreate/JobInsertionCostsCalculatorBuilder.java +++ b/jsprit-core/src/main/java/jsprit/core/algorithm/recreate/JobInsertionCostsCalculatorBuilder.java @@ -259,8 +259,10 @@ public class JobInsertionCostsCalculatorBuilder { if(constraintManager == null) throw new IllegalStateException("constraint-manager is null"); ActivityInsertionCostsCalculator actInsertionCalc; + ConfigureLocalActivityInsertionCalculator configLocal = null; 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); } else if(activityInsertionCostCalculator == null && !addDefaultCostCalc){ actInsertionCalc = new ActivityInsertionCostsCalculator(){ @@ -300,7 +302,11 @@ public class JobInsertionCostsCalculatorBuilder { switcher.put(Delivery.class, serviceInsertion); switcher.put(Break.class, breakInsertionCalculator); - 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){ diff --git a/jsprit-core/src/main/java/jsprit/core/algorithm/recreate/LocalActivityInsertionCostsCalculator.java b/jsprit-core/src/main/java/jsprit/core/algorithm/recreate/LocalActivityInsertionCostsCalculator.java index 0a8e61c0..02209716 100644 --- a/jsprit-core/src/main/java/jsprit/core/algorithm/recreate/LocalActivityInsertionCostsCalculator.java +++ b/jsprit-core/src/main/java/jsprit/core/algorithm/recreate/LocalActivityInsertionCostsCalculator.java @@ -18,11 +18,14 @@ package jsprit.core.algorithm.recreate; +import jsprit.core.algorithm.state.InternalStates; import jsprit.core.problem.cost.VehicleRoutingActivityCosts; import jsprit.core.problem.cost.VehicleRoutingTransportCosts; import jsprit.core.problem.misc.JobInsertionContext; import jsprit.core.problem.solution.route.activity.End; 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; /** @@ -40,50 +43,71 @@ class LocalActivityInsertionCostsCalculator implements ActivityInsertionCostsCal private VehicleRoutingTransportCosts routingCosts; private VehicleRoutingActivityCosts activityCosts; - - - public LocalActivityInsertionCostsCalculator(VehicleRoutingTransportCosts routingCosts, VehicleRoutingActivityCosts actCosts) { + + private double activityCostsWeight = 1.; + + private double solutionCompletenessRatio = 1.; + + private RouteAndActivityStateGetter stateManager; + + public LocalActivityInsertionCostsCalculator(VehicleRoutingTransportCosts routingCosts, VehicleRoutingActivityCosts actCosts, RouteAndActivityStateGetter stateManager) { super(); this.routingCosts = routingCosts; this.activityCosts = actCosts; + this.stateManager = stateManager; } @Override public double getCosts(JobInsertionContext iFacts, TourActivity prevAct, TourActivity nextAct, TourActivity newAct, double depTimeAtPrevAct) { - + 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 newAct_arrTime = depTimeAtPrevAct + tp_time_prevAct_newAct; double newAct_endTime = CalculationUtils.getActivityEndTime(newAct_arrTime, newAct); + double act_costs_newAct = activityCosts.getActivityCost(newAct, newAct_arrTime, iFacts.getNewDriver(), iFacts.getNewVehicle()); - - //open routes - if(nextAct instanceof End){ - if(!iFacts.getNewVehicle().isReturnToDepot()){ - return tp_costs_prevAct_newAct; - } - } - + + if(isEnd(nextAct) && !toDepot(iFacts.getNewVehicle())) return tp_costs_prevAct_newAct; + 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 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 totalCosts = tp_costs_prevAct_newAct + tp_costs_newAct_nextAct + 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 = 0.; if(iFacts.getRoute().isEmpty()){ 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()); - double actCost_nextAct = activityCosts.getActivityCost(nextAct, arrTime_nextAct, iFacts.getNewDriver(), iFacts.getNewVehicle()); - oldCosts = tp_costs_prevAct_nextAct + actCost_nextAct; + oldCosts += tp_costs_prevAct_nextAct; } else{ double tp_costs_prevAct_nextAct = routingCosts.getTransportCost(prevAct.getLocation(), nextAct.getLocation(), prevAct.getEndTime(), iFacts.getRoute().getDriver(), iFacts.getRoute().getVehicle()); - double arrTime_nextAct = routingCosts.getTransportTime(prevAct.getLocation(), nextAct.getLocation(), prevAct.getEndTime(), iFacts.getRoute().getDriver(), iFacts.getRoute().getVehicle()); + double 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()); - 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; } + 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; + } } diff --git a/jsprit-core/src/main/java/jsprit/core/algorithm/recreate/VehicleTypeDependentJobInsertionCalculator.java b/jsprit-core/src/main/java/jsprit/core/algorithm/recreate/VehicleTypeDependentJobInsertionCalculator.java index 4b630eea..0eedc539 100644 --- a/jsprit-core/src/main/java/jsprit/core/algorithm/recreate/VehicleTypeDependentJobInsertionCalculator.java +++ b/jsprit-core/src/main/java/jsprit/core/algorithm/recreate/VehicleTypeDependentJobInsertionCalculator.java @@ -109,9 +109,9 @@ final class VehicleTypeDependentJobInsertionCalculator implements JobInsertionCo relevantVehicles.addAll(fleetManager.getAvailableVehicles()); } for(Vehicle v : relevantVehicles){ - double depTime; - if(v == selectedVehicle) depTime = currentRoute.getDepartureTime(); - else depTime = v.getEarliestDeparture(); + double depTime = v.getEarliestDeparture(); +// if(v == selectedVehicle) depTime = currentRoute.getDepartureTime(); +// else depTime = v.getEarliestDeparture(); InsertionData iData = insertionCalculator.getInsertionData(currentRoute, jobToInsert, v, depTime, selectedDriver, bestKnownCost_); if(iData instanceof NoInsertionFound) { continue; diff --git a/jsprit-core/src/main/java/jsprit/core/algorithm/state/InternalStates.java b/jsprit-core/src/main/java/jsprit/core/algorithm/state/InternalStates.java index ae8336d0..5f85e2c1 100644 --- a/jsprit-core/src/main/java/jsprit/core/algorithm/state/InternalStates.java +++ b/jsprit-core/src/main/java/jsprit/core/algorithm/state/InternalStates.java @@ -42,4 +42,12 @@ public class InternalStates { 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 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); } diff --git a/jsprit-core/src/main/java/jsprit/core/algorithm/state/UpdateFutureWaitingTimes.java b/jsprit-core/src/main/java/jsprit/core/algorithm/state/UpdateFutureWaitingTimes.java new file mode 100644 index 00000000..61b99284 --- /dev/null +++ b/jsprit-core/src/main/java/jsprit/core/algorithm/state/UpdateFutureWaitingTimes.java @@ -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 . + ******************************************************************************/ +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() {} +} diff --git a/jsprit-core/src/main/java/jsprit/core/algorithm/state/UpdateVehicleDependentPracticalTimeWindows.java b/jsprit-core/src/main/java/jsprit/core/algorithm/state/UpdateVehicleDependentPracticalTimeWindows.java index 7f0afa73..43b7186a 100644 --- a/jsprit-core/src/main/java/jsprit/core/algorithm/state/UpdateVehicleDependentPracticalTimeWindows.java +++ b/jsprit-core/src/main/java/jsprit/core/algorithm/state/UpdateVehicleDependentPracticalTimeWindows.java @@ -19,15 +19,26 @@ package jsprit.core.algorithm.state; import jsprit.core.problem.Location; 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.activity.ReverseActivityVisitor; import jsprit.core.problem.solution.route.activity.TourActivity; import jsprit.core.problem.vehicle.Vehicle; import java.util.Arrays; 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 revIterator = route.getTourActivities().reverseActivityIterator(); + while(revIterator.hasNext()){ + visit(revIterator.next()); + } + finish(); + } public static interface VehiclesToUpdate { @@ -68,7 +79,7 @@ public class UpdateVehicleDependentPracticalTimeWindows implements ReverseActivi this.vehiclesToUpdate = vehiclesToUpdate; } - @Override + public void begin(VehicleRoute route) { this.route = route; vehicles = vehiclesToUpdate.get(route); @@ -78,7 +89,7 @@ public class UpdateVehicleDependentPracticalTimeWindows implements ReverseActivi } } - @Override + public void visit(TourActivity activity) { for(Vehicle vehicle : vehicles){ double latestArrTimeAtPrevAct = latest_arrTimes_at_prevAct[vehicle.getVehicleTypeIdentifier().getIndex()]; @@ -92,7 +103,7 @@ public class UpdateVehicleDependentPracticalTimeWindows implements ReverseActivi } } - @Override + public void finish() {} } diff --git a/jsprit-core/src/main/java/jsprit/core/problem/VehicleRoutingProblem.java b/jsprit-core/src/main/java/jsprit/core/problem/VehicleRoutingProblem.java index e4f63dae..9f6db14c 100644 --- a/jsprit-core/src/main/java/jsprit/core/problem/VehicleRoutingProblem.java +++ b/jsprit-core/src/main/java/jsprit/core/problem/VehicleRoutingProblem.java @@ -18,7 +18,7 @@ package jsprit.core.problem; import jsprit.core.problem.cost.VehicleRoutingActivityCosts; 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.Service; import jsprit.core.problem.job.Shipment; @@ -76,19 +76,7 @@ public class VehicleRoutingProblem { private VehicleRoutingTransportCosts transportCosts; - private VehicleRoutingActivityCosts activityCosts = new VehicleRoutingActivityCosts() { - - @Override - public double getActivityCost(TourActivity tourAct, double arrivalTime, Driver driver, Vehicle vehicle) { - return 0; - } - - @Override - public String toString() { - return "[name=defaultActivityCosts]"; - } - - }; + private VehicleRoutingActivityCosts activityCosts = new WaitingTimeCosts(); private Map jobs = new LinkedHashMap(); diff --git a/jsprit-core/src/main/java/jsprit/core/problem/cost/WaitingTimeCosts.java b/jsprit-core/src/main/java/jsprit/core/problem/cost/WaitingTimeCosts.java new file mode 100644 index 00000000..91103616 --- /dev/null +++ b/jsprit-core/src/main/java/jsprit/core/problem/cost/WaitingTimeCosts.java @@ -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; + } + +} diff --git a/jsprit-core/src/main/java/jsprit/core/problem/vehicle/InfiniteVehicles.java b/jsprit-core/src/main/java/jsprit/core/problem/vehicle/InfiniteVehicles.java index 800751e0..7212e2d1 100644 --- a/jsprit-core/src/main/java/jsprit/core/problem/vehicle/InfiniteVehicles.java +++ b/jsprit-core/src/main/java/jsprit/core/problem/vehicle/InfiniteVehicles.java @@ -47,7 +47,7 @@ class InfiniteVehicles implements VehicleFleetManager{ private void extractTypes(Collection 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); // sortedTypes.add(typeKey); } @@ -83,7 +83,7 @@ class InfiniteVehicles implements VehicleFleetManager{ @Override public Collection getAvailableVehicles(Vehicle withoutThisType) { Collection vehicles = new ArrayList(); - 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()){ if(!key.equals(thisKey)){ vehicles.add(types.get(key)); diff --git a/jsprit-core/src/main/java/jsprit/core/problem/vehicle/VehicleFleetManagerImpl.java b/jsprit-core/src/main/java/jsprit/core/problem/vehicle/VehicleFleetManagerImpl.java index e5786b66..9defc0d3 100644 --- a/jsprit-core/src/main/java/jsprit/core/problem/vehicle/VehicleFleetManagerImpl.java +++ b/jsprit-core/src/main/java/jsprit/core/problem/vehicle/VehicleFleetManagerImpl.java @@ -96,7 +96,7 @@ class VehicleFleetManagerImpl implements VehicleFleetManager { if(v.getType() == null){ 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)){ typeMapOfAvailableVehicles.put(typeKey, new TypeContainer()); } @@ -105,7 +105,7 @@ class VehicleFleetManagerImpl implements VehicleFleetManager { } 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)){ typeMapOfAvailableVehicles.get(key).remove(v); } @@ -137,7 +137,7 @@ class VehicleFleetManagerImpl implements VehicleFleetManager { @Override public Collection getAvailableVehicles(Vehicle withoutThisType) { List vehicles = new ArrayList(); - 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()){ if(key.equals(thisKey)) continue; if(!typeMapOfAvailableVehicles.get(key).isEmpty()){ diff --git a/jsprit-core/src/main/java/jsprit/core/problem/vehicle/VehicleImpl.java b/jsprit-core/src/main/java/jsprit/core/problem/vehicle/VehicleImpl.java index bd78254d..2644830e 100644 --- a/jsprit-core/src/main/java/jsprit/core/problem/vehicle/VehicleImpl.java +++ b/jsprit-core/src/main/java/jsprit/core/problem/vehicle/VehicleImpl.java @@ -297,7 +297,8 @@ public class VehicleImpl extends AbstractVehicle{ endLocation = builder.endLocation; startLocation = builder.startLocation; aBreak = builder.aBreak; - setVehicleIdentifier(new VehicleTypeKey(type.getTypeId(),startLocation.getId(),endLocation.getId(),earliestDeparture,latestArrival,skills)); +// 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)); } /** diff --git a/jsprit-core/src/main/java/jsprit/core/problem/vehicle/VehicleTypeImpl.java b/jsprit-core/src/main/java/jsprit/core/problem/vehicle/VehicleTypeImpl.java index fe1d5d34..8ebb56e5 100644 --- a/jsprit-core/src/main/java/jsprit/core/problem/vehicle/VehicleTypeImpl.java +++ b/jsprit-core/src/main/java/jsprit/core/problem/vehicle/VehicleTypeImpl.java @@ -42,19 +42,32 @@ public class VehicleTypeImpl implements VehicleType { } public final double fix; + @Deprecated public final double perTimeUnit; + public final double perTransportTimeUnit; public final double perDistanceUnit; + public final double perWaitingTimeUnit; private VehicleCostParams(double fix, double perTimeUnit,double perDistanceUnit) { super(); this.fix = fix; this.perTimeUnit = perTimeUnit; + this.perTransportTimeUnit = perTimeUnit; 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 public String toString() { - return "[fixed="+fix+"][perTime="+perTimeUnit+"][perDistance="+perDistanceUnit+"]"; + return "[fixed="+fix+"][perTime="+perTransportTimeUnit+"][perDistance="+perDistanceUnit+"][perWaitingTimeUnit="+perWaitingTimeUnit+"]"; } } @@ -65,7 +78,9 @@ public class VehicleTypeImpl implements VehicleType { * */ public static class Builder{ - + + + public static VehicleTypeImpl.Builder newInstance(String id) { if(id==null) throw new IllegalStateException(); return new Builder(id); @@ -80,6 +95,7 @@ public class VehicleTypeImpl implements VehicleType { private double fixedCost = 0.0; private double perDistance = 1.0; private double perTime = 0.0; + private double perWaitingTime = 0.0; private String profile = "car"; @@ -143,12 +159,46 @@ public class VehicleTypeImpl implements VehicleType { * @param perTime * @return this builder * @throws IllegalStateException if costPerTime is smaller than zero + * @deprecated use .setCostPerTransportTime(..) instead */ + @Deprecated public VehicleTypeImpl.Builder setCostPerTime(double perTime){ if(perTime < 0.0) throw new IllegalStateException(); this.perTime = perTime; return this; } + + /** + * Sets cost per time unit, for instance € per second. + * + *

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. + * + *

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. @@ -256,7 +306,7 @@ public class VehicleTypeImpl implements VehicleType { typeId = builder.id; capacity = builder.capacity; 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; profile = builder.profile; } diff --git a/jsprit-core/src/main/java/jsprit/core/problem/vehicle/VehicleTypeKey.java b/jsprit-core/src/main/java/jsprit/core/problem/vehicle/VehicleTypeKey.java index ce050058..4a9c2c67 100644 --- a/jsprit-core/src/main/java/jsprit/core/problem/vehicle/VehicleTypeKey.java +++ b/jsprit-core/src/main/java/jsprit/core/problem/vehicle/VehicleTypeKey.java @@ -37,8 +37,9 @@ public class VehicleTypeKey extends AbstractVehicle.AbstractTypeKey{ public final double earliestStart; public final double latestEnd; 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(); this.type = typeId; this.startLocationId = startLocationId; @@ -46,17 +47,19 @@ public class VehicleTypeKey extends AbstractVehicle.AbstractTypeKey{ this.earliestStart = earliestStart; this.latestEnd = latestEnd; this.skills = skills; + this.returnToDepot=returnToDepot; } @Override public boolean equals(Object o) { if (this == o) return true; - if (!(o instanceof VehicleTypeKey)) return false; + if (o == null || getClass() != o.getClass()) return false; VehicleTypeKey that = (VehicleTypeKey) o; if (Double.compare(that.earliestStart, earliestStart) != 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 (!skills.equals(that.skills)) return false; if (!startLocationId.equals(that.startLocationId)) return false; @@ -77,6 +80,7 @@ public class VehicleTypeKey extends AbstractVehicle.AbstractTypeKey{ temp = Double.doubleToLongBits(latestEnd); result = 31 * result + (int) (temp ^ (temp >>> 32)); result = 31 * result + skills.hashCode(); + result = 31 * result + (returnToDepot ? 1 : 0); return result; } diff --git a/jsprit-core/src/test/java/jsprit/core/algorithm/VariableDepartureAndWaitingTime_IT.java b/jsprit-core/src/test/java/jsprit/core/algorithm/VariableDepartureAndWaitingTime_IT.java new file mode 100644 index 00000000..baf2d17d --- /dev/null +++ b/jsprit-core/src/test/java/jsprit/core/algorithm/VariableDepartureAndWaitingTime_IT.java @@ -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()); + } + + + +} diff --git a/jsprit-core/src/test/java/jsprit/core/algorithm/recreate/ServiceInsertionAndLoadConstraintsTest.java b/jsprit-core/src/test/java/jsprit/core/algorithm/recreate/ServiceInsertionAndLoadConstraintsTest.java index 3d9bfaad..0c2c4340 100644 --- a/jsprit-core/src/test/java/jsprit/core/algorithm/recreate/ServiceInsertionAndLoadConstraintsTest.java +++ b/jsprit-core/src/test/java/jsprit/core/algorithm/recreate/ServiceInsertionAndLoadConstraintsTest.java @@ -95,7 +95,7 @@ public class ServiceInsertionAndLoadConstraintsTest { routingCosts = CostFactory.createManhattanCosts(); 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(); - activityInsertionCostsCalculator = new LocalActivityInsertionCostsCalculator(routingCosts, activityCosts); + activityInsertionCostsCalculator = new LocalActivityInsertionCostsCalculator(routingCosts, activityCosts, mock(StateManager.class)); createInsertionCalculator(hardRouteLevelConstraint); vehicleRoutingProblem = mock(VehicleRoutingProblem.class); } diff --git a/jsprit-core/src/test/java/jsprit/core/algorithm/recreate/ShipmentInsertionCalculatorTest.java b/jsprit-core/src/test/java/jsprit/core/algorithm/recreate/ShipmentInsertionCalculatorTest.java index 94dea056..6b3bc144 100644 --- a/jsprit-core/src/test/java/jsprit/core/algorithm/recreate/ShipmentInsertionCalculatorTest.java +++ b/jsprit-core/src/test/java/jsprit/core/algorithm/recreate/ShipmentInsertionCalculatorTest.java @@ -94,7 +94,7 @@ public class ShipmentInsertionCalculatorTest { routingCosts = CostFactory.createManhattanCosts(); 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(); - activityInsertionCostsCalculator = new LocalActivityInsertionCostsCalculator(routingCosts, activityCosts); + activityInsertionCostsCalculator = new LocalActivityInsertionCostsCalculator(routingCosts, activityCosts, mock(StateManager.class)); createInsertionCalculator(hardRouteLevelConstraint); vehicleRoutingProblem = mock(VehicleRoutingProblem.class); } diff --git a/jsprit-core/src/test/java/jsprit/core/algorithm/recreate/TestCalculatesServiceInsertion.java b/jsprit-core/src/test/java/jsprit/core/algorithm/recreate/TestCalculatesServiceInsertion.java index 3527e5bc..6fdb1962 100644 --- a/jsprit-core/src/test/java/jsprit/core/algorithm/recreate/TestCalculatesServiceInsertion.java +++ b/jsprit-core/src/test/java/jsprit/core/algorithm/recreate/TestCalculatesServiceInsertion.java @@ -132,7 +132,7 @@ public class TestCalculatesServiceInsertion { 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() { @Override public List createActivities(Job job) { diff --git a/jsprit-core/src/test/java/jsprit/core/algorithm/recreate/TestLocalActivityInsertionCostsCalculator.java b/jsprit-core/src/test/java/jsprit/core/algorithm/recreate/TestLocalActivityInsertionCostsCalculator.java index 92b02a7d..c0f42345 100644 --- a/jsprit-core/src/test/java/jsprit/core/algorithm/recreate/TestLocalActivityInsertionCostsCalculator.java +++ b/jsprit-core/src/test/java/jsprit/core/algorithm/recreate/TestLocalActivityInsertionCostsCalculator.java @@ -16,17 +16,33 @@ ******************************************************************************/ 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.VehicleRoutingProblem; import jsprit.core.problem.cost.VehicleRoutingActivityCosts; 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.solution.route.VehicleRoute; 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.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.Test; +import java.util.ArrayList; +import java.util.Arrays; + import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -56,6 +72,7 @@ public class TestLocalActivityInsertionCostsCalculator { jic = mock(JobInsertionContext.class); when(jic.getRoute()).thenReturn(route); when(jic.getNewVehicle()).thenReturn(vehicle); + when(vehicle.getType()).thenReturn(VehicleTypeImpl.Builder.newInstance("type").build()); tpCosts = mock(VehicleRoutingTransportCosts.class); 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); actCosts = mock(VehicleRoutingActivityCosts.class); - calc = new LocalActivityInsertionCostsCalculator(tpCosts, actCosts); + calc = new LocalActivityInsertionCostsCalculator(tpCosts, actCosts, mock(StateManager.class)); } private Location loc(String i) { @@ -77,11 +94,14 @@ public class TestLocalActivityInsertionCostsCalculator { public void whenInsertingActBetweenTwoRouteActs_itCalcsMarginalTpCosts(){ TourActivity prevAct = mock(TourActivity.class); when(prevAct.getLocation()).thenReturn(loc("i")); + when(prevAct.getIndex()).thenReturn(1); TourActivity nextAct = mock(TourActivity.class); when(nextAct.getLocation()).thenReturn(loc("j")); + when(nextAct.getIndex()).thenReturn(1); TourActivity newAct = mock(TourActivity.class); when(newAct.getLocation()).thenReturn(loc("k")); - + when(newAct.getIndex()).thenReturn(1); + when(vehicle.isReturnToDepot()).thenReturn(true); double costs = calc.getCosts(jic, prevAct, nextAct, newAct, 0.0); @@ -92,9 +112,11 @@ public class TestLocalActivityInsertionCostsCalculator { public void whenInsertingActBetweenLastActAndEnd_itCalcsMarginalTpCosts(){ TourActivity prevAct = mock(TourActivity.class); when(prevAct.getLocation()).thenReturn(loc("i")); + when(prevAct.getIndex()).thenReturn(1); End nextAct = End.newInstance("j", 0.0, 0.0); TourActivity newAct = mock(TourActivity.class); when(newAct.getLocation()).thenReturn(loc("k")); + when(newAct.getIndex()).thenReturn(1); when(vehicle.isReturnToDepot()).thenReturn(true); @@ -106,10 +128,13 @@ public class TestLocalActivityInsertionCostsCalculator { public void whenInsertingActBetweenTwoRouteActsAndRouteIsOpen_itCalcsMarginalTpCosts(){ TourActivity prevAct = mock(TourActivity.class); when(prevAct.getLocation()).thenReturn(loc("i")); + when(prevAct.getIndex()).thenReturn(1); TourActivity nextAct = mock(TourActivity.class); when(nextAct.getLocation()).thenReturn(loc("j")); + when(nextAct.getIndex()).thenReturn(1); TourActivity newAct = mock(TourActivity.class); when(newAct.getLocation()).thenReturn(loc("k")); + when(newAct.getIndex()).thenReturn(1); when(vehicle.isReturnToDepot()).thenReturn(false); @@ -121,13 +146,369 @@ public class TestLocalActivityInsertionCostsCalculator { public void whenInsertingActBetweenLastActAndEndAndRouteIsOpen_itCalculatesTpCostsFromPrevToNewAct(){ TourActivity prevAct = mock(TourActivity.class); when(prevAct.getLocation()).thenReturn(loc("i")); + when(prevAct.getIndex()).thenReturn(1); End nextAct = End.newInstance("j", 0.0, 0.0); TourActivity newAct = mock(TourActivity.class); when(newAct.getLocation()).thenReturn(loc("k")); + when(newAct.getIndex()).thenReturn(1); when(vehicle.isReturnToDepot()).thenReturn(false); double costs = calc.getCosts(jic, prevAct, nextAct, newAct, 0.0); 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()); + return stateManager; + } } + diff --git a/jsprit-core/src/test/java/jsprit/core/problem/vehicle/VehicleImplTest.java b/jsprit-core/src/test/java/jsprit/core/problem/vehicle/VehicleImplTest.java index e3e1500b..61ee6f5e 100644 --- a/jsprit-core/src/test/java/jsprit/core/problem/vehicle/VehicleImplTest.java +++ b/jsprit-core/src/test/java/jsprit/core/problem/vehicle/VehicleImplTest.java @@ -238,5 +238,5 @@ public class VehicleImplTest { - + } diff --git a/jsprit-examples/src/main/java/jsprit/examples/CostMatrixExample.java b/jsprit-examples/src/main/java/jsprit/examples/CostMatrixExample.java index 17bc0d74..d7bea962 100644 --- a/jsprit-examples/src/main/java/jsprit/examples/CostMatrixExample.java +++ b/jsprit-examples/src/main/java/jsprit/examples/CostMatrixExample.java @@ -18,7 +18,7 @@ package jsprit.examples; import jsprit.analysis.toolbox.Plotter; 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.VehicleRoutingProblem; import jsprit.core.problem.VehicleRoutingProblem.FleetSize; @@ -58,7 +58,7 @@ public class CostMatrixExample { Service s2 = Service.Builder.newInstance("2").addSizeDimension(0, 1).setLocation(Location.newInstance("2")).build(); Service s3 = Service.Builder.newInstance("3").addSizeDimension(0, 1).setLocation(Location.newInstance("3")).build(); - + /* * Assume the following symmetric distance-matrix * from,to,distance @@ -98,7 +98,7 @@ public class CostMatrixExample { VehicleRoutingProblem vrp = VehicleRoutingProblem.Builder.newInstance().setFleetSize(FleetSize.INFINITE).setRoutingCost(costMatrix) .addVehicle(vehicle).addJob(s1).addJob(s2).addJob(s3).build(); - VehicleRoutingAlgorithm vra = VehicleRoutingAlgorithms.readAndCreateAlgorithm(vrp, "input/fastAlgo.xml"); + VehicleRoutingAlgorithm vra = Jsprit.createAlgorithm(vrp); Collection solutions = vra.searchSolutions(); diff --git a/jsprit-examples/src/main/java/jsprit/examples/VariableStartAndWaitingTimeExample.java b/jsprit-examples/src/main/java/jsprit/examples/VariableStartAndWaitingTimeExample.java new file mode 100644 index 00000000..7e9c80ae --- /dev/null +++ b/jsprit-examples/src/main/java/jsprit/examples/VariableStartAndWaitingTimeExample.java @@ -0,0 +1,123 @@ +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.algorithm.state.StateManager; +import jsprit.core.algorithm.state.UpdateFutureWaitingTimes; +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.job.Service; +import jsprit.core.problem.solution.SolutionCostCalculator; +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.TourActivity; +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 VariableStartAndWaitingTimeExample { + + static interface AlgorithmFactory { + VehicleRoutingAlgorithm createAlgorithm(VehicleRoutingProblem vrp); + } + + public static void main(String[] args) { + + VehicleTypeImpl type = VehicleTypeImpl.Builder.newInstance("type").setCostPerDistance(4.).setCostPerWaitingTime(2.0).build(); + VehicleTypeImpl type1 = VehicleTypeImpl.Builder.newInstance("type1").setCostPerDistance(4.).setCostPerWaitingTime(2.0).build(); +// VehicleTypeImpl type2 = VehicleTypeImpl.Builder.newInstance("type2").setCostPerDistance(4.).setCostPerWaitingTime(2.0).build(); + + VehicleImpl v2 = VehicleImpl.Builder.newInstance("v2").setType(type).setReturnToDepot(false) + .setStartLocation(Location.newInstance(0, 0)) + .setEarliestStart(0).setLatestArrival(220) + .build(); + VehicleImpl v3 = VehicleImpl.Builder.newInstance("v3").setType(type1).setReturnToDepot(false) + .setStartLocation(Location.newInstance(0, 10)) + .setEarliestStart(200).setLatestArrival(450) + .build(); +// VehicleImpl v4 = VehicleImpl.Builder.newInstance("v4").setType(type2).setReturnToDepot(true) +// .setStartLocation(Location.newInstance(0, 0)).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) +// .setTimeWindow(TimeWindow.newInstance(0,100*(1+r.nextInt(3)))) + .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(300, 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(); + + 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 = algorithmFactory.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"); + } +} diff --git a/jsprit-examples/src/main/java/jsprit/examples/VariableStartAndWaitingTimeExample2.java b/jsprit-examples/src/main/java/jsprit/examples/VariableStartAndWaitingTimeExample2.java new file mode 100644 index 00000000..fe29c99f --- /dev/null +++ b/jsprit-examples/src/main/java/jsprit/examples/VariableStartAndWaitingTimeExample2.java @@ -0,0 +1,96 @@ +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.algorithm.state.StateManager; +import jsprit.core.algorithm.state.UpdateFutureWaitingTimes; +import jsprit.core.problem.Location; +import jsprit.core.problem.VehicleRoutingProblem; +import jsprit.core.problem.constraint.ConstraintManager; +import jsprit.core.problem.job.Service; +import jsprit.core.problem.solution.SolutionCostCalculator; +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.TourActivity; +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 VariableStartAndWaitingTimeExample2 { + + 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 = algorithmFactory.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"); + } +}