1
0
Fork 0
mirror of https://github.com/graphhopper/jsprit.git synced 2020-01-24 07:45:05 +01:00
This commit is contained in:
oblonski 2015-10-06 12:44:16 +02:00
parent 5051b6960b
commit 966dc6e901
63 changed files with 1447 additions and 1466 deletions

View file

@ -59,7 +59,7 @@ public class AlgorithmSearchProgressChartListener implements IterationEndsListen
@Override @Override
public void informAlgorithmEnds(VehicleRoutingProblem problem, Collection<VehicleRoutingProblemSolution> solutions) { public void informAlgorithmEnds(VehicleRoutingProblem problem, Collection<VehicleRoutingProblemSolution> solutions) {
log.info("create chart " + filename); log.info("create chart {}", filename);
XYLineChartBuilder.saveChartAsPNG(chartBuilder.build(), filename); XYLineChartBuilder.saveChartAsPNG(chartBuilder.build(), filename);
} }

View file

@ -416,8 +416,7 @@ public class ComputationalLaboratory {
} }
}); });
} } catch (Exception e) {
catch (Exception e){
throw new RuntimeException(e); throw new RuntimeException(e);
} }
} }

View file

@ -283,7 +283,7 @@ public class Plotter {
} }
private void plot(VehicleRoutingProblem vrp, final Collection<VehicleRoute> routes, String pngFile, String title) { private void plot(VehicleRoutingProblem vrp, final Collection<VehicleRoute> routes, String pngFile, String title) {
log.info("plot to " + pngFile); log.info("plot to {}", pngFile);
XYSeriesCollection problem; XYSeriesCollection problem;
XYSeriesCollection solution = null; XYSeriesCollection solution = null;
final XYSeriesCollection shipments; final XYSeriesCollection shipments;

View file

@ -49,7 +49,7 @@ public class StopWatch implements AlgorithmStartsListener, AlgorithmEndsListener
@Override @Override
public void informAlgorithmEnds(VehicleRoutingProblem problem, Collection<VehicleRoutingProblemSolution> solutions) { public void informAlgorithmEnds(VehicleRoutingProblem problem, Collection<VehicleRoutingProblemSolution> solutions) {
stop(); stop();
log.info("computation time [in sec]: " + getCompTimeInSeconds()); log.info("computation time [in sec]: {}", getCompTimeInSeconds());
} }
public void stop() { public void stop() {

View file

@ -60,12 +60,12 @@ public final class InsertionInitialSolutionFactory implements InitialSolutionFac
return solution; return solution;
} }
private List<Job> getUnassignedJobs(VehicleRoutingProblem vrp) { private List<Job> getUnassignedJobs(VehicleRoutingProblem vrp) {
ArrayList<Job> jobs = new ArrayList<Job>(vrp.getJobs().values()); ArrayList<Job> jobs = new ArrayList<Job>(vrp.getJobs().values());
for(Vehicle v : vrp.getVehicles()){ for (Vehicle v : vrp.getVehicles()) {
if(v.getBreak() != null) jobs.add(v.getBreak()); if (v.getBreak() != null) jobs.add(v.getBreak());
} }
return jobs; return jobs;
} }
} }

View file

@ -229,7 +229,7 @@ public class Jsprit {
return this; return this;
} }
public Builder setActivityInsertionCalculator(ActivityInsertionCostsCalculator activityInsertionCalculator){ public Builder setActivityInsertionCalculator(ActivityInsertionCostsCalculator activityInsertionCalculator) {
this.activityInsertionCalculator = activityInsertionCalculator; this.activityInsertionCalculator = activityInsertionCalculator;
return this; return this;
} }
@ -337,13 +337,12 @@ public class Jsprit {
final double maxCosts = jobNeighborhoods.getMaxDistance(); final double maxCosts = jobNeighborhoods.getMaxDistance();
IterationStartsListener noiseConfigurator; IterationStartsListener noiseConfigurator;
if(noThreads > 1) { if (noThreads > 1) {
ConcurrentInsertionNoiseMaker noiseMaker = new ConcurrentInsertionNoiseMaker(vrp, maxCosts, noiseLevel, noiseProbability); ConcurrentInsertionNoiseMaker noiseMaker = new ConcurrentInsertionNoiseMaker(vrp, maxCosts, noiseLevel, noiseProbability);
noiseMaker.setRandom(random); noiseMaker.setRandom(random);
constraintManager.addConstraint(noiseMaker); constraintManager.addConstraint(noiseMaker);
noiseConfigurator = noiseMaker; noiseConfigurator = noiseMaker;
} } else {
else {
InsertionNoiseMaker noiseMaker = new InsertionNoiseMaker(vrp, maxCosts, noiseLevel, noiseProbability); InsertionNoiseMaker noiseMaker = new InsertionNoiseMaker(vrp, maxCosts, noiseLevel, noiseProbability);
noiseMaker.setRandom(random); noiseMaker.setRandom(random);
constraintManager.addConstraint(noiseMaker); constraintManager.addConstraint(noiseMaker);
@ -583,19 +582,18 @@ public class Jsprit {
boolean hasBreak = false; boolean hasBreak = false;
TourActivity prevAct = route.getStart(); TourActivity prevAct = route.getStart();
for (TourActivity act : route.getActivities()) { for (TourActivity act : route.getActivities()) {
if(act instanceof BreakActivity) hasBreak = true; if (act instanceof BreakActivity) hasBreak = true;
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()); 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());
if(route.getVehicle().getBreak() != null){ if (route.getVehicle().getBreak() != null) {
if(!hasBreak){ if (!hasBreak) {
//break defined and required but not assigned penalty //break defined and required but not assigned penalty
if(route.getEnd().getArrTime() > route.getVehicle().getBreak().getTimeWindow().getEnd()){ if (route.getEnd().getArrTime() > route.getVehicle().getBreak().getTimeWindow().getEnd()) {
costs += maxCosts * 2 + route.getVehicle().getBreak().getServiceDuration() * route.getVehicle().getType().getVehicleCostParams().perServiceTimeUnit; costs += maxCosts * 2 + route.getVehicle().getBreak().getServiceDuration() * route.getVehicle().getType().getVehicleCostParams().perServiceTimeUnit;
} } else {
else{
costs -= maxCosts * 2; costs -= maxCosts * 2;
} }
} }

View file

@ -43,140 +43,137 @@ import java.util.List;
* Calculator that calculates the best insertion position for a {@link jsprit.core.problem.job.Service}. * Calculator that calculates the best insertion position for a {@link jsprit.core.problem.job.Service}.
* *
* @author schroeder * @author schroeder
*
*/ */
final class BreakInsertionCalculator implements JobInsertionCostsCalculator{ final class BreakInsertionCalculator implements JobInsertionCostsCalculator {
private static final Logger logger = LogManager.getLogger(BreakInsertionCalculator.class); private static final Logger logger = LogManager.getLogger(BreakInsertionCalculator.class);
private HardRouteConstraint hardRouteLevelConstraint; private HardRouteConstraint hardRouteLevelConstraint;
private HardActivityConstraint hardActivityLevelConstraint; private HardActivityConstraint hardActivityLevelConstraint;
private SoftRouteConstraint softRouteConstraint; private SoftRouteConstraint softRouteConstraint;
private SoftActivityConstraint softActivityConstraint; private SoftActivityConstraint softActivityConstraint;
private VehicleRoutingTransportCosts transportCosts; private VehicleRoutingTransportCosts transportCosts;
private ActivityInsertionCostsCalculator additionalTransportCostsCalculator; private ActivityInsertionCostsCalculator additionalTransportCostsCalculator;
private JobActivityFactory activityFactory; private JobActivityFactory activityFactory;
private AdditionalAccessEgressCalculator additionalAccessEgressCalculator; private AdditionalAccessEgressCalculator additionalAccessEgressCalculator;
public BreakInsertionCalculator(VehicleRoutingTransportCosts routingCosts, ActivityInsertionCostsCalculator additionalTransportCostsCalculator, ConstraintManager constraintManager) { public BreakInsertionCalculator(VehicleRoutingTransportCosts routingCosts, ActivityInsertionCostsCalculator additionalTransportCostsCalculator, ConstraintManager constraintManager) {
super(); super();
this.transportCosts = routingCosts; this.transportCosts = routingCosts;
hardRouteLevelConstraint = constraintManager; hardRouteLevelConstraint = constraintManager;
hardActivityLevelConstraint = constraintManager; hardActivityLevelConstraint = constraintManager;
softActivityConstraint = constraintManager; softActivityConstraint = constraintManager;
softRouteConstraint = constraintManager; softRouteConstraint = constraintManager;
this.additionalTransportCostsCalculator = additionalTransportCostsCalculator; this.additionalTransportCostsCalculator = additionalTransportCostsCalculator;
additionalAccessEgressCalculator = new AdditionalAccessEgressCalculator(routingCosts); additionalAccessEgressCalculator = new AdditionalAccessEgressCalculator(routingCosts);
logger.debug("initialise " + this); logger.debug("initialise " + this);
} }
public void setJobActivityFactory(JobActivityFactory jobActivityFactory){ public void setJobActivityFactory(JobActivityFactory jobActivityFactory) {
this.activityFactory = jobActivityFactory; this.activityFactory = jobActivityFactory;
} }
@Override @Override
public String toString() { public String toString() {
return "[name=calculatesServiceInsertion]"; return "[name=calculatesServiceInsertion]";
} }
/** /**
* Calculates the marginal cost of inserting job i locally. This is based on the * Calculates the marginal cost of inserting job i locally. This is based on the
* assumption that cost changes can entirely covered by only looking at the predecessor i-1 and its successor i+1. * assumption that cost changes can entirely covered by only looking at the predecessor i-1 and its successor i+1.
* */
*/ @Override
@Override public InsertionData getInsertionData(final VehicleRoute currentRoute, final Job jobToInsert, final Vehicle newVehicle, double newVehicleDepartureTime, final Driver newDriver, final double bestKnownCosts) {
public InsertionData getInsertionData(final VehicleRoute currentRoute, final Job jobToInsert, final Vehicle newVehicle, double newVehicleDepartureTime, final Driver newDriver, final double bestKnownCosts) { Break breakToInsert = (Break) jobToInsert;
Break breakToInsert = (Break) jobToInsert; if (newVehicle.getBreak() == null || newVehicle.getBreak() != breakToInsert) {
if(newVehicle.getBreak() == null || newVehicle.getBreak() != breakToInsert) {
return InsertionData.createEmptyInsertionData(); return InsertionData.createEmptyInsertionData();
} }
if(currentRoute.isEmpty()) return InsertionData.createEmptyInsertionData(); if (currentRoute.isEmpty()) return InsertionData.createEmptyInsertionData();
JobInsertionContext insertionContext = new JobInsertionContext(currentRoute, jobToInsert, newVehicle, newDriver, newVehicleDepartureTime); JobInsertionContext insertionContext = new JobInsertionContext(currentRoute, jobToInsert, newVehicle, newDriver, newVehicleDepartureTime);
int insertionIndex = InsertionData.NO_INDEX; int insertionIndex = InsertionData.NO_INDEX;
BreakActivity breakAct2Insert = (BreakActivity) activityFactory.createActivities(breakToInsert).get(0); BreakActivity breakAct2Insert = (BreakActivity) activityFactory.createActivities(breakToInsert).get(0);
insertionContext.getAssociatedActivities().add(breakAct2Insert); insertionContext.getAssociatedActivities().add(breakAct2Insert);
/* /*
check hard constraints at route level check hard constraints at route level
*/ */
if(!hardRouteLevelConstraint.fulfilled(insertionContext)){ if (!hardRouteLevelConstraint.fulfilled(insertionContext)) {
return InsertionData.createEmptyInsertionData(); return InsertionData.createEmptyInsertionData();
} }
/* /*
check soft constraints at route level check soft constraints at route level
*/ */
double additionalICostsAtRouteLevel = softRouteConstraint.getCosts(insertionContext); double additionalICostsAtRouteLevel = softRouteConstraint.getCosts(insertionContext);
double bestCost = bestKnownCosts; double bestCost = bestKnownCosts;
additionalICostsAtRouteLevel += additionalAccessEgressCalculator.getCosts(insertionContext); additionalICostsAtRouteLevel += additionalAccessEgressCalculator.getCosts(insertionContext);
/* /*
generate new start and end for new vehicle generate new start and end for new vehicle
*/ */
Start start = new Start(newVehicle.getStartLocation(), newVehicle.getEarliestDeparture(), Double.MAX_VALUE); Start start = new Start(newVehicle.getStartLocation(), newVehicle.getEarliestDeparture(), Double.MAX_VALUE);
start.setEndTime(newVehicleDepartureTime); start.setEndTime(newVehicleDepartureTime);
End end = new End(newVehicle.getEndLocation(), 0.0, newVehicle.getLatestArrival()); End end = new End(newVehicle.getEndLocation(), 0.0, newVehicle.getLatestArrival());
Location bestLocation = null; Location bestLocation = null;
TourActivity prevAct = start;
double prevActStartTime = newVehicleDepartureTime;
int actIndex = 0;
Iterator<TourActivity> activityIterator = currentRoute.getActivities().iterator();
boolean tourEnd = false;
while(!tourEnd){
TourActivity nextAct;
if(activityIterator.hasNext()) nextAct = activityIterator.next();
else{
nextAct = end;
tourEnd = true;
}
boolean breakThis = true;
List<Location> locations = Arrays.asList( prevAct.getLocation(), nextAct.getLocation());
for(Location location : locations) {
breakAct2Insert.setLocation(location);
ConstraintsStatus status = hardActivityLevelConstraint.fulfilled(insertionContext, prevAct, breakAct2Insert, nextAct, prevActStartTime);
if (status.equals(ConstraintsStatus.FULFILLED)) {
//from job2insert induced costs at activity level
double additionalICostsAtActLevel = softActivityConstraint.getCosts(insertionContext, prevAct, breakAct2Insert, nextAct, prevActStartTime);
double additionalTransportationCosts = additionalTransportCostsCalculator.getCosts(insertionContext, prevAct, nextAct, breakAct2Insert, prevActStartTime);
if (additionalICostsAtRouteLevel + additionalICostsAtActLevel + additionalTransportationCosts < bestCost) {
bestCost = additionalICostsAtRouteLevel + additionalICostsAtActLevel + additionalTransportationCosts;
insertionIndex = actIndex;
bestLocation = location;
}
breakThis = false;
} else if (status.equals(ConstraintsStatus.NOT_FULFILLED)) {
breakThis = false;
}
}
double nextActArrTime = prevActStartTime + transportCosts.getTransportTime(prevAct.getLocation(), nextAct.getLocation(), prevActStartTime, newDriver, newVehicle);
prevActStartTime = CalculationUtils.getActivityEndTime(nextActArrTime, nextAct);
prevAct = nextAct;
actIndex++;
if(breakThis) break;
}
if(insertionIndex == InsertionData.NO_INDEX) {
return InsertionData.createEmptyInsertionData();
}
InsertionData insertionData = new InsertionData(bestCost, InsertionData.NO_INDEX, insertionIndex, newVehicle, newDriver);
breakAct2Insert.setLocation(bestLocation);
insertionData.getEvents().add(new InsertBreak(currentRoute,newVehicle,breakAct2Insert,insertionIndex));
insertionData.getEvents().add(new SwitchVehicle(currentRoute,newVehicle,newVehicleDepartureTime));
insertionData.setVehicleDepartureTime(newVehicleDepartureTime);
return insertionData;
}
TourActivity prevAct = start;
double prevActStartTime = newVehicleDepartureTime;
int actIndex = 0;
Iterator<TourActivity> activityIterator = currentRoute.getActivities().iterator();
boolean tourEnd = false;
while (!tourEnd) {
TourActivity nextAct;
if (activityIterator.hasNext()) nextAct = activityIterator.next();
else {
nextAct = end;
tourEnd = true;
}
boolean breakThis = true;
List<Location> locations = Arrays.asList(prevAct.getLocation(), nextAct.getLocation());
for (Location location : locations) {
breakAct2Insert.setLocation(location);
ConstraintsStatus status = hardActivityLevelConstraint.fulfilled(insertionContext, prevAct, breakAct2Insert, nextAct, prevActStartTime);
if (status.equals(ConstraintsStatus.FULFILLED)) {
//from job2insert induced costs at activity level
double additionalICostsAtActLevel = softActivityConstraint.getCosts(insertionContext, prevAct, breakAct2Insert, nextAct, prevActStartTime);
double additionalTransportationCosts = additionalTransportCostsCalculator.getCosts(insertionContext, prevAct, nextAct, breakAct2Insert, prevActStartTime);
if (additionalICostsAtRouteLevel + additionalICostsAtActLevel + additionalTransportationCosts < bestCost) {
bestCost = additionalICostsAtRouteLevel + additionalICostsAtActLevel + additionalTransportationCosts;
insertionIndex = actIndex;
bestLocation = location;
}
breakThis = false;
} else if (status.equals(ConstraintsStatus.NOT_FULFILLED)) {
breakThis = false;
}
}
double nextActArrTime = prevActStartTime + transportCosts.getTransportTime(prevAct.getLocation(), nextAct.getLocation(), prevActStartTime, newDriver, newVehicle);
prevActStartTime = CalculationUtils.getActivityEndTime(nextActArrTime, nextAct);
prevAct = nextAct;
actIndex++;
if (breakThis) break;
}
if (insertionIndex == InsertionData.NO_INDEX) {
return InsertionData.createEmptyInsertionData();
}
InsertionData insertionData = new InsertionData(bestCost, InsertionData.NO_INDEX, insertionIndex, newVehicle, newDriver);
breakAct2Insert.setLocation(bestLocation);
insertionData.getEvents().add(new InsertBreak(currentRoute, newVehicle, breakAct2Insert, insertionIndex));
insertionData.getEvents().add(new SwitchVehicle(currentRoute, newVehicle, newVehicleDepartureTime));
insertionData.setVehicleDepartureTime(newVehicleDepartureTime);
return insertionData;
}
} }

View file

@ -13,24 +13,24 @@ class InsertBreakListener implements EventListener {
@Override @Override
public void inform(Event event) { public void inform(Event event) {
if(event instanceof InsertBreak){ if (event instanceof InsertBreak) {
InsertBreak insertActivity = (InsertBreak) event; InsertBreak insertActivity = (InsertBreak) event;
if(!insertActivity.getNewVehicle().isReturnToDepot()){ if (!insertActivity.getNewVehicle().isReturnToDepot()) {
if(insertActivity.getIndex()>=insertActivity.getVehicleRoute().getActivities().size()){ if (insertActivity.getIndex() >= insertActivity.getVehicleRoute().getActivities().size()) {
insertActivity.getVehicleRoute().getEnd().setLocation(insertActivity.getActivity().getLocation()); insertActivity.getVehicleRoute().getEnd().setLocation(insertActivity.getActivity().getLocation());
} }
} }
VehicleRoute vehicleRoute = ((InsertBreak) event).getVehicleRoute(); VehicleRoute vehicleRoute = ((InsertBreak) event).getVehicleRoute();
if(!vehicleRoute.isEmpty()){ if (!vehicleRoute.isEmpty()) {
if(vehicleRoute.getVehicle() != ((InsertBreak) event).getNewVehicle()){ if (vehicleRoute.getVehicle() != ((InsertBreak) event).getNewVehicle()) {
if(vehicleRoute.getVehicle().getBreak() != null){ if (vehicleRoute.getVehicle().getBreak() != null) {
boolean removed = vehicleRoute.getTourActivities().removeJob(vehicleRoute.getVehicle().getBreak()); boolean removed = vehicleRoute.getTourActivities().removeJob(vehicleRoute.getVehicle().getBreak());
if(removed) if (removed)
logger.trace("remove old break " + vehicleRoute.getVehicle().getBreak()); logger.trace("remove old break " + vehicleRoute.getVehicle().getBreak());
} }
} }
} }
insertActivity.getVehicleRoute().getTourActivities().addActivity(insertActivity.getIndex(),((InsertBreak) event).getActivity()); insertActivity.getVehicleRoute().getTourActivities().addActivity(insertActivity.getIndex(), ((InsertBreak) event).getActivity());
} }
} }

View file

@ -32,252 +32,251 @@ import java.util.ArrayList;
import java.util.List; import java.util.List;
public class JobInsertionCostsCalculatorBuilder { public class JobInsertionCostsCalculatorBuilder {
private static class CalculatorPlusListeners { private static class CalculatorPlusListeners {
private JobInsertionCostsCalculator calculator; private JobInsertionCostsCalculator calculator;
public JobInsertionCostsCalculator getCalculator() { public JobInsertionCostsCalculator getCalculator() {
return calculator; return calculator;
} }
private List<PrioritizedVRAListener> algorithmListener = new ArrayList<PrioritizedVRAListener>(); private List<PrioritizedVRAListener> algorithmListener = new ArrayList<PrioritizedVRAListener>();
private List<InsertionListener> insertionListener = new ArrayList<InsertionListener>(); private List<InsertionListener> insertionListener = new ArrayList<InsertionListener>();
public CalculatorPlusListeners(JobInsertionCostsCalculator calculator) { public CalculatorPlusListeners(JobInsertionCostsCalculator calculator) {
super(); super();
this.calculator = calculator; this.calculator = calculator;
} }
public List<PrioritizedVRAListener> getAlgorithmListener() { public List<PrioritizedVRAListener> getAlgorithmListener() {
return algorithmListener; return algorithmListener;
} }
public List<InsertionListener> getInsertionListener() { public List<InsertionListener> getInsertionListener() {
return insertionListener; return insertionListener;
} }
} }
private List<InsertionListener> insertionListeners; private List<InsertionListener> insertionListeners;
private List<PrioritizedVRAListener> algorithmListeners; private List<PrioritizedVRAListener> algorithmListeners;
private VehicleRoutingProblem vrp; private VehicleRoutingProblem vrp;
private RouteAndActivityStateGetter states; private RouteAndActivityStateGetter states;
private boolean local = true; private boolean local = true;
private int forwardLooking = 0; private int forwardLooking = 0;
private int memory = 1; private int memory = 1;
private boolean considerFixedCost = false; private boolean considerFixedCost = false;
private double weightOfFixedCost = 0; private double weightOfFixedCost = 0;
private VehicleFleetManager fleetManager; private VehicleFleetManager fleetManager;
private boolean timeScheduling = false; private boolean timeScheduling = false;
private double timeSlice; private double timeSlice;
private int neighbors; private int neighbors;
private ConstraintManager constraintManager; private ConstraintManager constraintManager;
private ActivityInsertionCostsCalculator activityInsertionCostCalculator = null; private ActivityInsertionCostsCalculator activityInsertionCostCalculator = null;
private boolean allowVehicleSwitch = true; private boolean allowVehicleSwitch = true;
private boolean addDefaultCostCalc = true; private boolean addDefaultCostCalc = true;
/** /**
* Constructs the builder. * Constructs the builder.
* * <p/>
* <p>Some calculators require information from the overall algorithm or the higher-level insertion procedure. Thus listeners inform them. * <p>Some calculators require information from the overall algorithm or the higher-level insertion procedure. Thus listeners inform them.
* These listeners are cached in the according list and can thus be added when its time to add them. * These listeners are cached in the according list and can thus be added when its time to add them.
* *
* @param insertionListeners * @param insertionListeners
* @param algorithmListeners * @param algorithmListeners
*/ */
public JobInsertionCostsCalculatorBuilder(List<InsertionListener> insertionListeners, List<PrioritizedVRAListener> algorithmListeners) { public JobInsertionCostsCalculatorBuilder(List<InsertionListener> insertionListeners, List<PrioritizedVRAListener> algorithmListeners) {
super(); super();
this.insertionListeners = insertionListeners; this.insertionListeners = insertionListeners;
this.algorithmListeners = algorithmListeners; this.algorithmListeners = algorithmListeners;
} }
/** /**
* Sets activityStates. MUST be set. * Sets activityStates. MUST be set.
* @param stateManager *
* * @param stateManager
* @return * @return
*/ */
public JobInsertionCostsCalculatorBuilder setStateManager(RouteAndActivityStateGetter stateManager){ public JobInsertionCostsCalculatorBuilder setStateManager(RouteAndActivityStateGetter stateManager) {
this.states = stateManager; this.states = stateManager;
return this;
}
/**
* Sets routingProblem. MUST be set.
*
* @param vehicleRoutingProblem
* @return
*/
public JobInsertionCostsCalculatorBuilder setVehicleRoutingProblem(VehicleRoutingProblem vehicleRoutingProblem){
this.vrp = vehicleRoutingProblem;
return this;
}
/**
* Sets fleetManager. MUST be set.
*
* @param fleetManager
* @return
*/
public JobInsertionCostsCalculatorBuilder setVehicleFleetManager(VehicleFleetManager fleetManager){
this.fleetManager = fleetManager;
return this;
}
/**
* Sets a flag to build a calculator based on local calculations.
*
* <p>Insertion of a job and job-activity is evaluated based on the previous and next activity.
* @param addDefaultCostCalc
*/
public JobInsertionCostsCalculatorBuilder setLocalLevel(boolean addDefaultCostCalc){
local = true;
this.addDefaultCostCalc = addDefaultCostCalc;
return this; return this;
} }
public JobInsertionCostsCalculatorBuilder setActivityInsertionCostsCalculator(ActivityInsertionCostsCalculator activityInsertionCostsCalculator){ /**
this.activityInsertionCostCalculator = activityInsertionCostsCalculator; * Sets routingProblem. MUST be set.
*
* @param vehicleRoutingProblem
* @return
*/
public JobInsertionCostsCalculatorBuilder setVehicleRoutingProblem(VehicleRoutingProblem vehicleRoutingProblem) {
this.vrp = vehicleRoutingProblem;
return this; return this;
} }
/** /**
* Sets a flag to build a calculator that evaluates job insertion on route-level. * Sets fleetManager. MUST be set.
* *
* @param forwardLooking * @param fleetManager
* @param memory * @return
* @param addDefaultMarginalCostCalc */
*/ public JobInsertionCostsCalculatorBuilder setVehicleFleetManager(VehicleFleetManager fleetManager) {
public JobInsertionCostsCalculatorBuilder setRouteLevel(int forwardLooking, int memory, boolean addDefaultMarginalCostCalc){ this.fleetManager = fleetManager;
local = false;
this.forwardLooking = forwardLooking;
this.memory = memory;
return this; return this;
} }
/** /**
* Sets a flag to consider also fixed-cost when evaluating the insertion of a job. The weight of the fixed-cost can be determined by setting * Sets a flag to build a calculator based on local calculations.
* weightofFixedCosts. * <p/>
* * <p>Insertion of a job and job-activity is evaluated based on the previous and next activity.
* @param weightOfFixedCosts *
*/ * @param addDefaultCostCalc
public JobInsertionCostsCalculatorBuilder considerFixedCosts(double weightOfFixedCosts){ */
considerFixedCost = true; public JobInsertionCostsCalculatorBuilder setLocalLevel(boolean addDefaultCostCalc) {
this.weightOfFixedCost = weightOfFixedCosts; local = true;
this.addDefaultCostCalc = addDefaultCostCalc;
return this; return this;
} }
public JobInsertionCostsCalculatorBuilder experimentalTimeScheduler(double timeSlice, int neighbors){ public JobInsertionCostsCalculatorBuilder setActivityInsertionCostsCalculator(ActivityInsertionCostsCalculator activityInsertionCostsCalculator) {
timeScheduling = true; this.activityInsertionCostCalculator = activityInsertionCostsCalculator;
this.timeSlice = timeSlice;
this.neighbors = neighbors;
return this; return this;
} }
/** /**
* Builds the jobInsertionCalculator. * Sets a flag to build a calculator that evaluates job insertion on route-level.
* *
* @return jobInsertionCalculator. * @param forwardLooking
* @throws IllegalStateException if vrp == null or activityStates == null or fleetManager == null. * @param memory
*/ * @param addDefaultMarginalCostCalc
public JobInsertionCostsCalculator build(){ */
if(vrp == null) throw new IllegalStateException("vehicle-routing-problem is null, but it must be set (this.setVehicleRoutingProblem(vrp))"); public JobInsertionCostsCalculatorBuilder setRouteLevel(int forwardLooking, int memory, boolean addDefaultMarginalCostCalc) {
if(states == null) throw new IllegalStateException("states is null, but is must be set (this.setStateManager(states))"); local = false;
if(fleetManager == null) throw new IllegalStateException("fleetManager is null, but it must be set (this.setVehicleFleetManager(fleetManager))"); this.forwardLooking = forwardLooking;
JobInsertionCostsCalculator baseCalculator = null; this.memory = memory;
CalculatorPlusListeners standardLocal = null; return this;
if(local){ }
standardLocal = createStandardLocal(vrp, states);
} /**
else{ * Sets a flag to consider also fixed-cost when evaluating the insertion of a job. The weight of the fixed-cost can be determined by setting
checkServicesOnly(); * weightofFixedCosts.
standardLocal = createStandardRoute(vrp, states,forwardLooking,memory); *
} * @param weightOfFixedCosts
baseCalculator = standardLocal.getCalculator(); */
addAlgorithmListeners(standardLocal.getAlgorithmListener()); public JobInsertionCostsCalculatorBuilder considerFixedCosts(double weightOfFixedCosts) {
addInsertionListeners(standardLocal.getInsertionListener()); considerFixedCost = true;
if(considerFixedCost){ this.weightOfFixedCost = weightOfFixedCosts;
CalculatorPlusListeners withFixed = createCalculatorConsideringFixedCosts(vrp, baseCalculator, states, weightOfFixedCost); return this;
baseCalculator = withFixed.getCalculator(); }
addAlgorithmListeners(withFixed.getAlgorithmListener());
addInsertionListeners(withFixed.getInsertionListener()); public JobInsertionCostsCalculatorBuilder experimentalTimeScheduler(double timeSlice, int neighbors) {
} timeScheduling = true;
if(timeScheduling){ this.timeSlice = timeSlice;
this.neighbors = neighbors;
return this;
}
/**
* Builds the jobInsertionCalculator.
*
* @return jobInsertionCalculator.
* @throws IllegalStateException if vrp == null or activityStates == null or fleetManager == null.
*/
public JobInsertionCostsCalculator build() {
if (vrp == null)
throw new IllegalStateException("vehicle-routing-problem is null, but it must be set (this.setVehicleRoutingProblem(vrp))");
if (states == null)
throw new IllegalStateException("states is null, but is must be set (this.setStateManager(states))");
if (fleetManager == null)
throw new IllegalStateException("fleetManager is null, but it must be set (this.setVehicleFleetManager(fleetManager))");
JobInsertionCostsCalculator baseCalculator = null;
CalculatorPlusListeners standardLocal = null;
if (local) {
standardLocal = createStandardLocal(vrp, states);
} else {
checkServicesOnly();
standardLocal = createStandardRoute(vrp, states, forwardLooking, memory);
}
baseCalculator = standardLocal.getCalculator();
addAlgorithmListeners(standardLocal.getAlgorithmListener());
addInsertionListeners(standardLocal.getInsertionListener());
if (considerFixedCost) {
CalculatorPlusListeners withFixed = createCalculatorConsideringFixedCosts(vrp, baseCalculator, states, weightOfFixedCost);
baseCalculator = withFixed.getCalculator();
addAlgorithmListeners(withFixed.getAlgorithmListener());
addInsertionListeners(withFixed.getInsertionListener());
}
if (timeScheduling) {
// baseCalculator = new CalculatesServiceInsertionWithTimeSchedulingInSlices(baseCalculator,timeSlice,neighbors); // baseCalculator = new CalculatesServiceInsertionWithTimeSchedulingInSlices(baseCalculator,timeSlice,neighbors);
CalculatesServiceInsertionWithTimeScheduling wts = new CalculatesServiceInsertionWithTimeScheduling(baseCalculator,timeSlice,neighbors); CalculatesServiceInsertionWithTimeScheduling wts = new CalculatesServiceInsertionWithTimeScheduling(baseCalculator, timeSlice, neighbors);
CalculatorPlusListeners calcPlusListeners = new CalculatorPlusListeners(wts); CalculatorPlusListeners calcPlusListeners = new CalculatorPlusListeners(wts);
calcPlusListeners.getInsertionListener().add(new CalculatesServiceInsertionWithTimeScheduling.KnowledgeInjection(wts)); calcPlusListeners.getInsertionListener().add(new CalculatesServiceInsertionWithTimeScheduling.KnowledgeInjection(wts));
addInsertionListeners(calcPlusListeners.getInsertionListener()); addInsertionListeners(calcPlusListeners.getInsertionListener());
baseCalculator = calcPlusListeners.getCalculator(); baseCalculator = calcPlusListeners.getCalculator();
} }
return createFinalInsertion(fleetManager, baseCalculator, states); return createFinalInsertion(fleetManager, baseCalculator, states);
} }
private void checkServicesOnly() { private void checkServicesOnly() {
for(Job j : vrp.getJobs().values()){ for (Job j : vrp.getJobs().values()) {
if(j instanceof Shipment){ if (j instanceof Shipment) {
throw new UnsupportedOperationException("currently the 'insert-on-route-level' option is only available for services (i.e. service, pickup, delivery), \n" + throw new UnsupportedOperationException("currently the 'insert-on-route-level' option is only available for services (i.e. service, pickup, delivery), \n" +
"if you want to deal with shipments switch to option 'local-level' by either setting bestInsertionBuilder.setLocalLevel() or \n" "if you want to deal with shipments switch to option 'local-level' by either setting bestInsertionBuilder.setLocalLevel() or \n"
+ "by omitting the xml-tag '<level forwardLooking=2 memory=1>route</level>' when defining your insertionStrategy in algo-config.xml file"); + "by omitting the xml-tag '<level forwardLooking=2 memory=1>route</level>' when defining your insertionStrategy in algo-config.xml file");
} }
} }
} }
private void addInsertionListeners(List<InsertionListener> list) { private void addInsertionListeners(List<InsertionListener> list) {
for(InsertionListener iL : list){ for (InsertionListener iL : list) {
insertionListeners.add(iL); insertionListeners.add(iL);
} }
} }
private void addAlgorithmListeners(List<PrioritizedVRAListener> list) { private void addAlgorithmListeners(List<PrioritizedVRAListener> list) {
for(PrioritizedVRAListener aL : list){ for (PrioritizedVRAListener aL : list) {
algorithmListeners.add(aL); algorithmListeners.add(aL);
} }
} }
private CalculatorPlusListeners createStandardLocal(final VehicleRoutingProblem vrp, RouteAndActivityStateGetter statesManager){ private CalculatorPlusListeners createStandardLocal(final VehicleRoutingProblem vrp, RouteAndActivityStateGetter statesManager) {
if(constraintManager == null) throw new IllegalStateException("constraint-manager is null"); if (constraintManager == null) throw new IllegalStateException("constraint-manager is null");
ActivityInsertionCostsCalculator actInsertionCalc; ActivityInsertionCostsCalculator actInsertionCalc;
ConfigureLocalActivityInsertionCalculator configLocal = null; ConfigureLocalActivityInsertionCalculator configLocal = null;
if(activityInsertionCostCalculator == null && addDefaultCostCalc){ if (activityInsertionCostCalculator == null && addDefaultCostCalc) {
actInsertionCalc = new LocalActivityInsertionCostsCalculator(vrp.getTransportCosts(), vrp.getActivityCosts(), statesManager); 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){ actInsertionCalc = new ActivityInsertionCostsCalculator() {
actInsertionCalc = new ActivityInsertionCostsCalculator(){
@Override @Override
public double getCosts(JobInsertionContext iContext, TourActivity prevAct, TourActivity nextAct, TourActivity newAct, public double getCosts(JobInsertionContext iContext, TourActivity prevAct, TourActivity nextAct, TourActivity newAct,
double depTimeAtPrevAct) { double depTimeAtPrevAct) {
return 0.; return 0.;
} }
}; };
} } else {
else{ actInsertionCalc = activityInsertionCostCalculator;
actInsertionCalc = activityInsertionCostCalculator; }
}
JobActivityFactory activityFactory = new JobActivityFactory() { JobActivityFactory activityFactory = new JobActivityFactory() {
@ -287,63 +286,61 @@ public class JobInsertionCostsCalculatorBuilder {
} }
}; };
ShipmentInsertionCalculator shipmentInsertion = new ShipmentInsertionCalculator(vrp.getTransportCosts(), actInsertionCalc, constraintManager); ShipmentInsertionCalculator shipmentInsertion = new ShipmentInsertionCalculator(vrp.getTransportCosts(), actInsertionCalc, constraintManager);
shipmentInsertion.setJobActivityFactory(activityFactory); shipmentInsertion.setJobActivityFactory(activityFactory);
ServiceInsertionCalculator serviceInsertion = new ServiceInsertionCalculator(vrp.getTransportCosts(), actInsertionCalc, constraintManager); ServiceInsertionCalculator serviceInsertion = new ServiceInsertionCalculator(vrp.getTransportCosts(), actInsertionCalc, constraintManager);
serviceInsertion.setJobActivityFactory(activityFactory); serviceInsertion.setJobActivityFactory(activityFactory);
BreakInsertionCalculator breakInsertionCalculator = new BreakInsertionCalculator(vrp.getTransportCosts(), actInsertionCalc, constraintManager); BreakInsertionCalculator breakInsertionCalculator = new BreakInsertionCalculator(vrp.getTransportCosts(), actInsertionCalc, constraintManager);
breakInsertionCalculator.setJobActivityFactory(activityFactory); breakInsertionCalculator.setJobActivityFactory(activityFactory);
JobCalculatorSwitcher switcher = new JobCalculatorSwitcher(); JobCalculatorSwitcher switcher = new JobCalculatorSwitcher();
switcher.put(Shipment.class, shipmentInsertion); switcher.put(Shipment.class, shipmentInsertion);
switcher.put(Service.class, serviceInsertion); switcher.put(Service.class, serviceInsertion);
switcher.put(Pickup.class, serviceInsertion); switcher.put(Pickup.class, serviceInsertion);
switcher.put(Delivery.class, serviceInsertion); switcher.put(Delivery.class, serviceInsertion);
switcher.put(Break.class, breakInsertionCalculator); switcher.put(Break.class, breakInsertionCalculator);
CalculatorPlusListeners calculatorPlusListeners = new CalculatorPlusListeners(switcher); CalculatorPlusListeners calculatorPlusListeners = new CalculatorPlusListeners(switcher);
if(configLocal != null){ if (configLocal != null) {
calculatorPlusListeners.insertionListener.add(configLocal); calculatorPlusListeners.insertionListener.add(configLocal);
} }
return calculatorPlusListeners; return calculatorPlusListeners;
} }
private CalculatorPlusListeners createCalculatorConsideringFixedCosts(VehicleRoutingProblem vrp, JobInsertionCostsCalculator baseCalculator, RouteAndActivityStateGetter activityStates2, double weightOfFixedCosts){ private CalculatorPlusListeners createCalculatorConsideringFixedCosts(VehicleRoutingProblem vrp, JobInsertionCostsCalculator baseCalculator, RouteAndActivityStateGetter activityStates2, double weightOfFixedCosts) {
final JobInsertionConsideringFixCostsCalculator withFixCost = new JobInsertionConsideringFixCostsCalculator(baseCalculator, activityStates2); final JobInsertionConsideringFixCostsCalculator withFixCost = new JobInsertionConsideringFixCostsCalculator(baseCalculator, activityStates2);
withFixCost.setWeightOfFixCost(weightOfFixedCosts); withFixCost.setWeightOfFixCost(weightOfFixedCosts);
CalculatorPlusListeners calcPlusListeners = new CalculatorPlusListeners(withFixCost); CalculatorPlusListeners calcPlusListeners = new CalculatorPlusListeners(withFixCost);
calcPlusListeners.getInsertionListener().add(new ConfigureFixCostCalculator(vrp, withFixCost)); calcPlusListeners.getInsertionListener().add(new ConfigureFixCostCalculator(vrp, withFixCost));
return calcPlusListeners; return calcPlusListeners;
} }
private CalculatorPlusListeners createStandardRoute(final VehicleRoutingProblem vrp, RouteAndActivityStateGetter activityStates2, int forwardLooking, int solutionMemory){ private CalculatorPlusListeners createStandardRoute(final VehicleRoutingProblem vrp, RouteAndActivityStateGetter activityStates2, int forwardLooking, int solutionMemory) {
ActivityInsertionCostsCalculator routeLevelCostEstimator; ActivityInsertionCostsCalculator routeLevelCostEstimator;
if(activityInsertionCostCalculator == null && addDefaultCostCalc){ if (activityInsertionCostCalculator == null && addDefaultCostCalc) {
RouteLevelActivityInsertionCostsEstimator routeLevelActivityInsertionCostsEstimator = new RouteLevelActivityInsertionCostsEstimator(vrp.getTransportCosts(), vrp.getActivityCosts(), activityStates2); RouteLevelActivityInsertionCostsEstimator routeLevelActivityInsertionCostsEstimator = new RouteLevelActivityInsertionCostsEstimator(vrp.getTransportCosts(), vrp.getActivityCosts(), activityStates2);
routeLevelActivityInsertionCostsEstimator.setForwardLooking(forwardLooking); routeLevelActivityInsertionCostsEstimator.setForwardLooking(forwardLooking);
routeLevelCostEstimator = routeLevelActivityInsertionCostsEstimator; routeLevelCostEstimator = routeLevelActivityInsertionCostsEstimator;
} } else if (activityInsertionCostCalculator == null && !addDefaultCostCalc) {
else if(activityInsertionCostCalculator == null && !addDefaultCostCalc){ routeLevelCostEstimator = new ActivityInsertionCostsCalculator() {
routeLevelCostEstimator = new ActivityInsertionCostsCalculator(){
final ActivityInsertionCosts noInsertionCosts = new ActivityInsertionCosts(0.,0.); final ActivityInsertionCosts noInsertionCosts = new ActivityInsertionCosts(0., 0.);
@Override @Override
public double getCosts(JobInsertionContext iContext, TourActivity prevAct, TourActivity nextAct, TourActivity newAct, public double getCosts(JobInsertionContext iContext, TourActivity prevAct, TourActivity nextAct, TourActivity newAct,
double depTimeAtPrevAct) { double depTimeAtPrevAct) {
return 0.; return 0.;
} }
}; };
} } else {
else{ routeLevelCostEstimator = activityInsertionCostCalculator;
routeLevelCostEstimator = activityInsertionCostCalculator; }
}
ServiceInsertionOnRouteLevelCalculator jobInsertionCalculator = new ServiceInsertionOnRouteLevelCalculator(vrp.getTransportCosts(), vrp.getActivityCosts(), routeLevelCostEstimator, constraintManager, constraintManager); ServiceInsertionOnRouteLevelCalculator jobInsertionCalculator = new ServiceInsertionOnRouteLevelCalculator(vrp.getTransportCosts(), vrp.getActivityCosts(), routeLevelCostEstimator, constraintManager, constraintManager);
jobInsertionCalculator.setNuOfActsForwardLooking(forwardLooking); jobInsertionCalculator.setNuOfActsForwardLooking(forwardLooking);
jobInsertionCalculator.setMemorySize(solutionMemory); jobInsertionCalculator.setMemorySize(solutionMemory);
jobInsertionCalculator.setStates(activityStates2); jobInsertionCalculator.setStates(activityStates2);
jobInsertionCalculator.setJobActivityFactory(new JobActivityFactory() { jobInsertionCalculator.setJobActivityFactory(new JobActivityFactory() {
@Override @Override
public List<AbstractActivity> createActivities(Job job) { public List<AbstractActivity> createActivities(Job job) {
@ -351,23 +348,23 @@ public class JobInsertionCostsCalculatorBuilder {
} }
}); });
return new CalculatorPlusListeners(jobInsertionCalculator); return new CalculatorPlusListeners(jobInsertionCalculator);
} }
private JobInsertionCostsCalculator createFinalInsertion(VehicleFleetManager fleetManager, JobInsertionCostsCalculator baseCalc, RouteAndActivityStateGetter activityStates2){ private JobInsertionCostsCalculator createFinalInsertion(VehicleFleetManager fleetManager, JobInsertionCostsCalculator baseCalc, RouteAndActivityStateGetter activityStates2) {
VehicleTypeDependentJobInsertionCalculator vehicleTypeDependentJobInsertionCalculator = new VehicleTypeDependentJobInsertionCalculator(vrp, fleetManager, baseCalc); VehicleTypeDependentJobInsertionCalculator vehicleTypeDependentJobInsertionCalculator = new VehicleTypeDependentJobInsertionCalculator(vrp, fleetManager, baseCalc);
vehicleTypeDependentJobInsertionCalculator.setVehicleSwitchAllowed(allowVehicleSwitch); vehicleTypeDependentJobInsertionCalculator.setVehicleSwitchAllowed(allowVehicleSwitch);
return vehicleTypeDependentJobInsertionCalculator; return vehicleTypeDependentJobInsertionCalculator;
} }
public JobInsertionCostsCalculatorBuilder setConstraintManager(ConstraintManager constraintManager) { public JobInsertionCostsCalculatorBuilder setConstraintManager(ConstraintManager constraintManager) {
this.constraintManager = constraintManager; this.constraintManager = constraintManager;
return this; return this;
} }
public JobInsertionCostsCalculatorBuilder setAllowVehicleSwitch(boolean allowVehicleSwitch) { public JobInsertionCostsCalculatorBuilder setAllowVehicleSwitch(boolean allowVehicleSwitch) {
this.allowVehicleSwitch = allowVehicleSwitch; this.allowVehicleSwitch = allowVehicleSwitch;
return this; return this;
} }
} }

View file

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

View file

@ -31,16 +31,15 @@ import java.util.Collection;
import java.util.List; import java.util.List;
/** /**
* Insertion based on regret approach. * Insertion based on regret approach.
* * <p/>
* <p>Basically calculates the insertion cost of the firstBest and the secondBest alternative. The score is then calculated as difference * <p>Basically calculates the insertion cost of the firstBest and the secondBest alternative. The score is then calculated as difference
* between secondBest and firstBest, plus additional scoring variables that can defined in this.ScoringFunction. * between secondBest and firstBest, plus additional scoring variables that can defined in this.ScoringFunction.
* The idea is that if the cost of the secondBest alternative is way higher than the first best, it seems to be important to insert this * The idea is that if the cost of the secondBest alternative is way higher than the first best, it seems to be important to insert this
* customer immediatedly. If difference is not that high, it might not impact solution if this customer is inserted later. * customer immediatedly. If difference is not that high, it might not impact solution if this customer is inserted later.
* *
* @author stefan schroeder * @author stefan schroeder
* */
*/
public class RegretInsertion extends AbstractInsertionStrategy { public class RegretInsertion extends AbstractInsertionStrategy {
static class ScoredJob { static class ScoredJob {
@ -92,138 +91,137 @@ public class RegretInsertion extends AbstractInsertionStrategy {
} }
} }
/** /**
* Scorer to include other impacts on score such as time-window length or distance to depot. * Scorer to include other impacts on score such as time-window length or distance to depot.
* *
* @author schroeder * @author schroeder
* */
*/ static interface ScoringFunction {
static interface ScoringFunction {
public double score(InsertionData best, Job job); public double score(InsertionData best, Job job);
} }
/** /**
* Scorer that includes the length of the time-window when scoring a job. The wider the time-window, the lower the score. * Scorer that includes the length of the time-window when scoring a job. The wider the time-window, the lower the score.
* * <p/>
* <p>This is the default scorer, i.e.: score = (secondBest - firstBest) + this.TimeWindowScorer.score(job) * <p>This is the default scorer, i.e.: score = (secondBest - firstBest) + this.TimeWindowScorer.score(job)
* *
* @author schroeder * @author schroeder
* */
*/ public static class DefaultScorer implements ScoringFunction {
public static class DefaultScorer implements ScoringFunction {
private VehicleRoutingProblem vrp; private VehicleRoutingProblem vrp;
private double tw_param = - 0.5; private double tw_param = -0.5;
private double depotDistance_param = + 0.1; private double depotDistance_param = +0.1;
private double minTimeWindowScore = - 100000; private double minTimeWindowScore = -100000;
public DefaultScorer(VehicleRoutingProblem vrp) { public DefaultScorer(VehicleRoutingProblem vrp) {
this.vrp = vrp; this.vrp = vrp;
} }
public void setTimeWindowParam(double tw_param){ this.tw_param = tw_param; } public void setTimeWindowParam(double tw_param) {
this.tw_param = tw_param;
}
public void setDepotDistanceParam(double depotDistance_param){ this.depotDistance_param = depotDistance_param; } public void setDepotDistanceParam(double depotDistance_param) {
this.depotDistance_param = depotDistance_param;
}
@Override @Override
public double score(InsertionData best, Job job) { public double score(InsertionData best, Job job) {
double score; double score;
if(job instanceof Service){ if (job instanceof Service) {
score = scoreService(best, job); score = scoreService(best, job);
} } else if (job instanceof Shipment) {
else if(job instanceof Shipment){ score = scoreShipment(best, job);
score = scoreShipment(best,job); } else throw new IllegalStateException("not supported");
}
else throw new IllegalStateException("not supported");
return score; return score;
} }
private double scoreShipment(InsertionData best, Job job) { private double scoreShipment(InsertionData best, Job job) {
Shipment shipment = (Shipment)job; Shipment shipment = (Shipment) job;
double maxDepotDistance_1 = Math.max( double maxDepotDistance_1 = Math.max(
getDistance(best.getSelectedVehicle().getStartLocation(),shipment.getPickupLocation()), getDistance(best.getSelectedVehicle().getStartLocation(), shipment.getPickupLocation()),
getDistance(best.getSelectedVehicle().getStartLocation(),shipment.getDeliveryLocation()) getDistance(best.getSelectedVehicle().getStartLocation(), shipment.getDeliveryLocation())
); );
double maxDepotDistance_2 = Math.max( double maxDepotDistance_2 = Math.max(
getDistance(best.getSelectedVehicle().getEndLocation(),shipment.getPickupLocation()), getDistance(best.getSelectedVehicle().getEndLocation(), shipment.getPickupLocation()),
getDistance(best.getSelectedVehicle().getEndLocation(),shipment.getDeliveryLocation()) getDistance(best.getSelectedVehicle().getEndLocation(), shipment.getDeliveryLocation())
); );
double maxDepotDistance = Math.max(maxDepotDistance_1,maxDepotDistance_2); double maxDepotDistance = Math.max(maxDepotDistance_1, maxDepotDistance_2);
double minTimeToOperate = Math.min(shipment.getPickupTimeWindow().getEnd()-shipment.getPickupTimeWindow().getStart(), double minTimeToOperate = Math.min(shipment.getPickupTimeWindow().getEnd() - shipment.getPickupTimeWindow().getStart(),
shipment.getDeliveryTimeWindow().getEnd()-shipment.getDeliveryTimeWindow().getStart()); shipment.getDeliveryTimeWindow().getEnd() - shipment.getDeliveryTimeWindow().getStart());
return Math.max(tw_param * minTimeToOperate,minTimeWindowScore) + depotDistance_param * maxDepotDistance; return Math.max(tw_param * minTimeToOperate, minTimeWindowScore) + depotDistance_param * maxDepotDistance;
} }
private double scoreService(InsertionData best, Job job) { private double scoreService(InsertionData best, Job job) {
Location location = ((Service) job).getLocation(); Location location = ((Service) job).getLocation();
double maxDepotDistance = 0; double maxDepotDistance = 0;
if(location != null) { if (location != null) {
maxDepotDistance = Math.max( maxDepotDistance = Math.max(
getDistance(best.getSelectedVehicle().getStartLocation(), location), getDistance(best.getSelectedVehicle().getStartLocation(), location),
getDistance(best.getSelectedVehicle().getEndLocation(), location) getDistance(best.getSelectedVehicle().getEndLocation(), location)
); );
} }
return Math.max(tw_param * (((Service)job).getTimeWindow().getEnd() - ((Service)job).getTimeWindow().getStart()),minTimeWindowScore) + return Math.max(tw_param * (((Service) job).getTimeWindow().getEnd() - ((Service) job).getTimeWindow().getStart()), minTimeWindowScore) +
depotDistance_param * maxDepotDistance; depotDistance_param * maxDepotDistance;
} }
private double getDistance(Location loc1, Location loc2) { private double getDistance(Location loc1, Location loc2) {
return vrp.getTransportCosts().getTransportCost(loc1,loc2,0.,null,null); return vrp.getTransportCosts().getTransportCost(loc1, loc2, 0., null, null);
} }
@Override @Override
public String toString() { public String toString() {
return "[name=defaultScorer][twParam="+tw_param+"][depotDistanceParam=" + depotDistance_param + "]"; return "[name=defaultScorer][twParam=" + tw_param + "][depotDistanceParam=" + depotDistance_param + "]";
} }
} }
private static Logger logger = LogManager.getLogger(RegretInsertion.class); private static Logger logger = LogManager.getLogger(RegretInsertion.class);
private ScoringFunction scoringFunction; private ScoringFunction scoringFunction;
private JobInsertionCostsCalculator insertionCostsCalculator; private JobInsertionCostsCalculator insertionCostsCalculator;
/** /**
* Sets the scoring function. * Sets the scoring function.
* * <p/>
* <p>By default, the this.TimeWindowScorer is used. * <p>By default, the this.TimeWindowScorer is used.
* *
* @param scoringFunction to score * @param scoringFunction to score
*/ */
public void setScoringFunction(ScoringFunction scoringFunction) { public void setScoringFunction(ScoringFunction scoringFunction) {
this.scoringFunction = scoringFunction; this.scoringFunction = scoringFunction;
} }
public RegretInsertion(JobInsertionCostsCalculator jobInsertionCalculator, VehicleRoutingProblem vehicleRoutingProblem) { public RegretInsertion(JobInsertionCostsCalculator jobInsertionCalculator, VehicleRoutingProblem vehicleRoutingProblem) {
super(vehicleRoutingProblem); super(vehicleRoutingProblem);
this.scoringFunction = new DefaultScorer(vehicleRoutingProblem); this.scoringFunction = new DefaultScorer(vehicleRoutingProblem);
this.insertionCostsCalculator = jobInsertionCalculator; this.insertionCostsCalculator = jobInsertionCalculator;
this.vrp = vehicleRoutingProblem; this.vrp = vehicleRoutingProblem;
logger.debug("initialise {}", this); logger.debug("initialise {}", this);
} }
@Override @Override
public String toString() { public String toString() {
return "[name=regretInsertion][additionalScorer="+scoringFunction+"]"; return "[name=regretInsertion][additionalScorer=" + scoringFunction + "]";
} }
/** /**
* Runs insertion. * Runs insertion.
* * <p/>
* <p>Before inserting a job, all unassigned jobs are scored according to its best- and secondBest-insertion plus additional scoring variables. * <p>Before inserting a job, all unassigned jobs are scored according to its best- and secondBest-insertion plus additional scoring variables.
* */
*/ @Override
@Override public Collection<Job> insertUnassignedJobs(Collection<VehicleRoute> routes, Collection<Job> unassignedJobs) {
public Collection<Job> insertUnassignedJobs(Collection<VehicleRoute> routes, Collection<Job> unassignedJobs) {
List<Job> badJobs = new ArrayList<Job>(unassignedJobs.size()); List<Job> badJobs = new ArrayList<Job>(unassignedJobs.size());
List<Job> jobs = new ArrayList<Job>(unassignedJobs); List<Job> jobs = new ArrayList<Job>(unassignedJobs);
@ -231,14 +229,14 @@ public class RegretInsertion extends AbstractInsertionStrategy {
List<Job> unassignedJobList = new ArrayList<Job>(jobs); List<Job> unassignedJobList = new ArrayList<Job>(jobs);
List<Job> badJobList = new ArrayList<Job>(); List<Job> badJobList = new ArrayList<Job>();
ScoredJob bestScoredJob = nextJob(routes, unassignedJobList, badJobList); ScoredJob bestScoredJob = nextJob(routes, unassignedJobList, badJobList);
if(bestScoredJob != null){ if (bestScoredJob != null) {
if(bestScoredJob.isNewRoute()){ if (bestScoredJob.isNewRoute()) {
routes.add(bestScoredJob.getRoute()); routes.add(bestScoredJob.getRoute());
} }
insertJob(bestScoredJob.getJob(),bestScoredJob.getInsertionData(),bestScoredJob.getRoute()); insertJob(bestScoredJob.getJob(), bestScoredJob.getInsertionData(), bestScoredJob.getRoute());
jobs.remove(bestScoredJob.getJob()); jobs.remove(bestScoredJob.getJob());
} }
for(Job bad : badJobList) { for (Job bad : badJobList) {
jobs.remove(bad); jobs.remove(bad);
badJobs.add(bad); badJobs.add(bad);
} }
@ -249,18 +247,17 @@ public class RegretInsertion extends AbstractInsertionStrategy {
private ScoredJob nextJob(Collection<VehicleRoute> routes, List<Job> unassignedJobList, List<Job> badJobs) { private ScoredJob nextJob(Collection<VehicleRoute> routes, List<Job> unassignedJobList, List<Job> badJobs) {
ScoredJob bestScoredJob = null; ScoredJob bestScoredJob = null;
for (Job unassignedJob : unassignedJobList) { for (Job unassignedJob : unassignedJobList) {
ScoredJob scoredJob = getScoredJob(routes,unassignedJob,insertionCostsCalculator,scoringFunction); ScoredJob scoredJob = getScoredJob(routes, unassignedJob, insertionCostsCalculator, scoringFunction);
if(scoredJob instanceof BadJob){ if (scoredJob instanceof BadJob) {
badJobs.add(unassignedJob); badJobs.add(unassignedJob);
continue; continue;
} }
if(bestScoredJob == null) bestScoredJob = scoredJob; if (bestScoredJob == null) bestScoredJob = scoredJob;
else{ else {
if(scoredJob.getScore() > bestScoredJob.getScore()){ if (scoredJob.getScore() > bestScoredJob.getScore()) {
bestScoredJob = scoredJob; bestScoredJob = scoredJob;
} } else if (scoredJob.getScore() == bestScoredJob.getScore()) {
else if (scoredJob.getScore() == bestScoredJob.getScore()){ if (scoredJob.getJob().getId().compareTo(bestScoredJob.getJob().getId()) <= 0) {
if(scoredJob.getJob().getId().compareTo(bestScoredJob.getJob().getId()) <= 0){
bestScoredJob = scoredJob; bestScoredJob = scoredJob;
} }
} }
@ -307,31 +304,29 @@ public class RegretInsertion extends AbstractInsertionStrategy {
secondBest = iData; secondBest = iData;
} }
} }
if(best == null){ if (best == null) {
return new RegretInsertion.BadJob(unassignedJob); return new RegretInsertion.BadJob(unassignedJob);
} }
double score = score(unassignedJob, best, secondBest, scoringFunction); double score = score(unassignedJob, best, secondBest, scoringFunction);
ScoredJob scoredJob; ScoredJob scoredJob;
if(bestRoute == emptyRoute){ if (bestRoute == emptyRoute) {
scoredJob = new ScoredJob(unassignedJob, score, best, bestRoute, true); scoredJob = new ScoredJob(unassignedJob, score, best, bestRoute, true);
} } else scoredJob = new ScoredJob(unassignedJob, score, best, bestRoute, false);
else scoredJob = new ScoredJob(unassignedJob, score, best, bestRoute, false);
return scoredJob; return scoredJob;
} }
static double score(Job unassignedJob, InsertionData best, InsertionData secondBest, ScoringFunction scoringFunction) { static double score(Job unassignedJob, InsertionData best, InsertionData secondBest, ScoringFunction scoringFunction) {
if(best == null){ if (best == null) {
throw new IllegalStateException("cannot insert job " + unassignedJob.getId()); throw new IllegalStateException("cannot insert job " + unassignedJob.getId());
} }
double score; double score;
if(secondBest == null){ //either there is only one vehicle or there are more vehicles, but they cannot load unassignedJob if (secondBest == null) { //either there is only one vehicle or there are more vehicles, but they cannot load unassignedJob
//if only one vehicle, I want the job to be inserted with min iCosts //if only one vehicle, I want the job to be inserted with min iCosts
//if there are more vehicles, I want this job to be prioritized since there are no alternatives //if there are more vehicles, I want this job to be prioritized since there are no alternatives
score = Integer.MAX_VALUE - best.getInsertionCost() + scoringFunction.score(best, unassignedJob); score = Integer.MAX_VALUE - best.getInsertionCost() + scoringFunction.score(best, unassignedJob);
} } else {
else{ score = (secondBest.getInsertionCost() - best.getInsertionCost()) + scoringFunction.score(best, unassignedJob);
score = (secondBest.getInsertionCost()-best.getInsertionCost()) + scoringFunction.score(best, unassignedJob);
} }
return score; return score;
} }

View file

@ -135,9 +135,8 @@ public class RegretInsertionConcurrent extends AbstractInsertionStrategy {
bestScoredJob = sJob; bestScoredJob = sJob;
} else if (sJob.getScore() > bestScoredJob.getScore()) { } else if (sJob.getScore() > bestScoredJob.getScore()) {
bestScoredJob = sJob; bestScoredJob = sJob;
} } else if (sJob.getScore() == bestScoredJob.getScore()) {
else if (sJob.getScore() == bestScoredJob.getScore()){ if (sJob.getJob().getId().compareTo(bestScoredJob.getJob().getId()) <= 0) {
if(sJob.getJob().getId().compareTo(bestScoredJob.getJob().getId()) <= 0){
bestScoredJob = sJob; bestScoredJob = sJob;
} }
} }

View file

@ -15,7 +15,7 @@ class SwitchVehicleListener implements EventListener {
public void inform(Event event) { public void inform(Event event) {
if (event instanceof SwitchVehicle) { if (event instanceof SwitchVehicle) {
SwitchVehicle switchVehicle = (SwitchVehicle) event; SwitchVehicle switchVehicle = (SwitchVehicle) event;
if(vehiclesDifferent((SwitchVehicle) event)) { if (vehiclesDifferent((SwitchVehicle) event)) {
logger.trace("switch vehicle (" + ((SwitchVehicle) event).getRoute().getVehicle().getId() + " to " + ((SwitchVehicle) event).getVehicle().getId() + ")"); logger.trace("switch vehicle (" + ((SwitchVehicle) event).getRoute().getVehicle().getId() + " to " + ((SwitchVehicle) event).getVehicle().getId() + ")");
Break aBreak = ((SwitchVehicle) event).getRoute().getVehicle().getBreak(); Break aBreak = ((SwitchVehicle) event).getRoute().getVehicle().getBreak();
if (aBreak != null) { if (aBreak != null) {
@ -23,7 +23,7 @@ class SwitchVehicleListener implements EventListener {
if (removed) logger.trace("remove " + aBreak.getId()); if (removed) logger.trace("remove " + aBreak.getId());
} }
} }
switchVehicle.getRoute().setVehicleAndDepartureTime(switchVehicle.getVehicle(),((SwitchVehicle) event).getDepartureTime()); switchVehicle.getRoute().setVehicleAndDepartureTime(switchVehicle.getVehicle(), ((SwitchVehicle) event).getDepartureTime());
} }
} }

View file

@ -14,8 +14,8 @@ import org.apache.commons.math3.ml.distance.DistanceMeasure;
import java.util.*; import java.util.*;
/** /**
* Created by schroeder on 04/02/15. * Created by schroeder on 04/02/15.
*/ */
public class DBSCANClusterer { public class DBSCANClusterer {
private static class LocationWrapper implements Clusterable { private static class LocationWrapper implements Clusterable {
@ -53,7 +53,7 @@ public class DBSCANClusterer {
@Override @Override
public double[] getPoint() { public double[] getPoint() {
return new double[]{ id }; return new double[]{id};
} }
public Job getJob() { public Job getJob() {
@ -63,31 +63,31 @@ public class DBSCANClusterer {
private static class MyDistance implements DistanceMeasure { private static class MyDistance implements DistanceMeasure {
private Map<Integer,LocationWrapper> locations; private Map<Integer, LocationWrapper> locations;
private VehicleRoutingTransportCosts costs; private VehicleRoutingTransportCosts costs;
public MyDistance(List<LocationWrapper> locations, VehicleRoutingTransportCosts costs) { public MyDistance(List<LocationWrapper> locations, VehicleRoutingTransportCosts costs) {
this.locations = new HashMap<Integer, LocationWrapper>(); this.locations = new HashMap<Integer, LocationWrapper>();
for(LocationWrapper lw : locations){ for (LocationWrapper lw : locations) {
this.locations.put((int)lw.getPoint()[0],lw); this.locations.put((int) lw.getPoint()[0], lw);
} }
this.costs = costs; this.costs = costs;
} }
@Override @Override
public double compute(double[] doubles, double[] doubles1) { public double compute(double[] doubles, double[] doubles1) {
LocationWrapper l1 = locations.get((int)doubles[0]); LocationWrapper l1 = locations.get((int) doubles[0]);
LocationWrapper l2 = locations.get((int)doubles1[0]); LocationWrapper l2 = locations.get((int) doubles1[0]);
int count = 0; int count = 0;
double sum = 0; double sum = 0;
for(Location loc_1 : l1.getLocations()){ for (Location loc_1 : l1.getLocations()) {
for(Location loc_2 : l2.getLocations()){ for (Location loc_2 : l2.getLocations()) {
sum += costs.getTransportCost(loc_1,loc_2,0,null,null); sum += costs.getTransportCost(loc_1, loc_2, 0, null, null);
count++; count++;
} }
} }
return sum / (double)count; return sum / (double) count;
} }
} }
@ -111,19 +111,19 @@ public class DBSCANClusterer {
this.costs = costs; this.costs = costs;
} }
public void setMinPts(int pts){ public void setMinPts(int pts) {
this.minNoOfJobsInCluster = pts; this.minNoOfJobsInCluster = pts;
} }
public void setEpsFactor(double epsFactor){ public void setEpsFactor(double epsFactor) {
this.epsFactor = epsFactor; this.epsFactor = epsFactor;
} }
public void setEpsDistance(double epsDistance){ public void setEpsDistance(double epsDistance) {
this.epsDistance = epsDistance; this.epsDistance = epsDistance;
} }
public List<List<Job>> getClusters(VehicleRoute route){ public List<List<Job>> getClusters(VehicleRoute route) {
List<LocationWrapper> locations = getLocationWrappers(route); List<LocationWrapper> locations = getLocationWrappers(route);
List<Cluster<LocationWrapper>> clusterResults = getClusters(route, locations); List<Cluster<LocationWrapper>> clusterResults = getClusters(route, locations);
return makeList(clusterResults); return makeList(clusterResults);
@ -131,33 +131,33 @@ public class DBSCANClusterer {
private List<LocationWrapper> getLocationWrappers(VehicleRoute route) { private List<LocationWrapper> getLocationWrappers(VehicleRoute route) {
List<LocationWrapper> locations = new ArrayList<LocationWrapper>(route.getTourActivities().getJobs().size()); List<LocationWrapper> locations = new ArrayList<LocationWrapper>(route.getTourActivities().getJobs().size());
Map<Job,List<Location>> jobs2locations = new HashMap<Job, List<Location>>(); Map<Job, List<Location>> jobs2locations = new HashMap<Job, List<Location>>();
for(TourActivity act : route.getActivities()){ for (TourActivity act : route.getActivities()) {
if(act instanceof TourActivity.JobActivity){ if (act instanceof TourActivity.JobActivity) {
Job job = ((TourActivity.JobActivity) act).getJob(); Job job = ((TourActivity.JobActivity) act).getJob();
if(!jobs2locations.containsKey(job)){ if (!jobs2locations.containsKey(job)) {
jobs2locations.put(job,new ArrayList<Location>()); jobs2locations.put(job, new ArrayList<Location>());
} }
jobs2locations.get(job).add(act.getLocation()); jobs2locations.get(job).add(act.getLocation());
} }
} }
for(Job j : jobs2locations.keySet()){ for (Job j : jobs2locations.keySet()) {
locations.add(new LocationWrapper(j,jobs2locations.get(j))); locations.add(new LocationWrapper(j, jobs2locations.get(j)));
} }
return locations; return locations;
} }
private List<Cluster<LocationWrapper>> getClusters(VehicleRoute route, List<LocationWrapper> locations) { private List<Cluster<LocationWrapper>> getClusters(VehicleRoute route, List<LocationWrapper> locations) {
double sampledDistance; double sampledDistance;
if(epsDistance != null) sampledDistance = epsDistance; if (epsDistance != null) sampledDistance = epsDistance;
else sampledDistance = Math.max(0, sample(costs, route)); else sampledDistance = Math.max(0, sample(costs, route));
org.apache.commons.math3.ml.clustering.DBSCANClusterer<LocationWrapper> clusterer = new org.apache.commons.math3.ml.clustering.DBSCANClusterer<LocationWrapper>(sampledDistance, minNoOfJobsInCluster, new MyDistance(locations,costs)); org.apache.commons.math3.ml.clustering.DBSCANClusterer<LocationWrapper> clusterer = new org.apache.commons.math3.ml.clustering.DBSCANClusterer<LocationWrapper>(sampledDistance, minNoOfJobsInCluster, new MyDistance(locations, costs));
return clusterer.cluster(locations); return clusterer.cluster(locations);
} }
private List<List<Job>> makeList(List<Cluster<LocationWrapper>> clusterResults) { private List<List<Job>> makeList(List<Cluster<LocationWrapper>> clusterResults) {
List<List<Job>> l = new ArrayList<List<Job>>(); List<List<Job>> l = new ArrayList<List<Job>>();
for(Cluster<LocationWrapper> c : clusterResults){ for (Cluster<LocationWrapper> c : clusterResults) {
List<Job> l_ = getJobList(c); List<Job> l_ = getJobList(c);
l.add(l_); l.add(l_);
} }
@ -166,18 +166,18 @@ public class DBSCANClusterer {
private List<Job> getJobList(Cluster<LocationWrapper> c) { private List<Job> getJobList(Cluster<LocationWrapper> c) {
List<Job> l_ = new ArrayList<Job>(); List<Job> l_ = new ArrayList<Job>();
if(c == null) return l_; if (c == null) return l_;
for(LocationWrapper lw : c.getPoints()){ for (LocationWrapper lw : c.getPoints()) {
l_.add(lw.getJob()); l_.add(lw.getJob());
} }
return l_; return l_;
} }
public List<Job> getRandomCluster(VehicleRoute route){ public List<Job> getRandomCluster(VehicleRoute route) {
if(route.isEmpty()) return Collections.emptyList(); if (route.isEmpty()) return Collections.emptyList();
List<LocationWrapper> locations = getLocationWrappers(route); List<LocationWrapper> locations = getLocationWrappers(route);
List<Cluster<LocationWrapper>> clusterResults = getClusters(route,locations); List<Cluster<LocationWrapper>> clusterResults = getClusters(route, locations);
if(clusterResults.isEmpty()) return Collections.emptyList(); if (clusterResults.isEmpty()) return Collections.emptyList();
Cluster<LocationWrapper> randomCluster = RandomUtils.nextItem(clusterResults, random); Cluster<LocationWrapper> randomCluster = RandomUtils.nextItem(clusterResults, random);
return getJobList(randomCluster); return getJobList(randomCluster);
} }
@ -185,15 +185,15 @@ public class DBSCANClusterer {
private double sample(VehicleRoutingTransportCosts costs, VehicleRoute r) { private double sample(VehicleRoutingTransportCosts costs, VehicleRoute r) {
double min = Double.MAX_VALUE; double min = Double.MAX_VALUE;
double sum = 0; double sum = 0;
for(int i=0;i<noDistanceSamples;i++){ for (int i = 0; i < noDistanceSamples; i++) {
TourActivity act1 = RandomUtils.nextItem(r.getActivities(), random); TourActivity act1 = RandomUtils.nextItem(r.getActivities(), random);
TourActivity act2 = RandomUtils.nextItem(r.getActivities(), random); TourActivity act2 = RandomUtils.nextItem(r.getActivities(), random);
double dist = costs.getTransportCost(act1.getLocation(), act2.getLocation(), double dist = costs.getTransportCost(act1.getLocation(), act2.getLocation(),
0., null, r.getVehicle()); 0., null, r.getVehicle());
if(dist < min) min = dist; if (dist < min) min = dist;
sum += dist; sum += dist;
} }
double avg = sum / ((double)noDistanceSamples); double avg = sum / ((double) noDistanceSamples);
return (avg - min) * epsFactor; return (avg - min) * epsFactor;
} }

View file

@ -17,20 +17,22 @@ public class RuinBreaks implements RuinListener {
private final static Logger logger = LogManager.getLogger(); private final static Logger logger = LogManager.getLogger();
@Override @Override
public void ruinStarts(Collection<VehicleRoute> routes) {} public void ruinStarts(Collection<VehicleRoute> routes) {
}
@Override @Override
public void ruinEnds(Collection<VehicleRoute> routes, Collection<Job> unassignedJobs) { public void ruinEnds(Collection<VehicleRoute> routes, Collection<Job> unassignedJobs) {
for(VehicleRoute r : routes){ for (VehicleRoute r : routes) {
Break aBreak = r.getVehicle().getBreak(); Break aBreak = r.getVehicle().getBreak();
if(aBreak != null){ if (aBreak != null) {
r.getTourActivities().removeJob(aBreak); r.getTourActivities().removeJob(aBreak);
logger.trace("ruin: {}",aBreak.getId()); logger.trace("ruin: {}", aBreak.getId());
unassignedJobs.add(aBreak); unassignedJobs.add(aBreak);
} }
} }
} }
@Override @Override
public void removed(Job job, VehicleRoute fromRoute) {} public void removed(Job job, VehicleRoute fromRoute) {
}
} }

View file

@ -25,38 +25,38 @@ import jsprit.core.problem.solution.route.activity.TourActivity;
* Updates and memorizes latest operation start times at activities. * Updates and memorizes latest operation start times at activities.
* *
* @author schroeder * @author schroeder
*
*/ */
public class UpdateFutureWaitingTimes implements ReverseActivityVisitor, StateUpdater{ public class UpdateFutureWaitingTimes implements ReverseActivityVisitor, StateUpdater {
private StateManager states; private StateManager states;
private VehicleRoute route; private VehicleRoute route;
private VehicleRoutingTransportCosts transportCosts; private VehicleRoutingTransportCosts transportCosts;
private double futureWaiting; private double futureWaiting;
public UpdateFutureWaitingTimes(StateManager states, VehicleRoutingTransportCosts tpCosts) { public UpdateFutureWaitingTimes(StateManager states, VehicleRoutingTransportCosts tpCosts) {
super(); super();
this.states = states; this.states = states;
this.transportCosts = tpCosts; this.transportCosts = tpCosts;
} }
@Override @Override
public void begin(VehicleRoute route) { public void begin(VehicleRoute route) {
this.route = route; this.route = route;
this.futureWaiting = 0.; this.futureWaiting = 0.;
} }
@Override @Override
public void visit(TourActivity activity) { public void visit(TourActivity activity) {
states.putInternalTypedActivityState(activity,route.getVehicle(),InternalStates.FUTURE_WAITING,futureWaiting); states.putInternalTypedActivityState(activity, route.getVehicle(), InternalStates.FUTURE_WAITING, futureWaiting);
// if(!(activity instanceof BreakActivity)) { // if(!(activity instanceof BreakActivity)) {
futureWaiting += Math.max(activity.getTheoreticalEarliestOperationStartTime() - activity.getArrTime(), 0); futureWaiting += Math.max(activity.getTheoreticalEarliestOperationStartTime() - activity.getArrTime(), 0);
// } // }
} }
@Override @Override
public void finish() {} public void finish() {
}
} }

View file

@ -42,73 +42,69 @@ import java.util.*;
/** /**
* Contains and defines the vehicle routing problem. * Contains and defines the vehicle routing problem.
* * <p/>
* <p>A routing problem is defined as jobs, vehicles, costs and constraints. * <p>A routing problem is defined as jobs, vehicles, costs and constraints.
* * <p/>
* <p> To construct the problem, use VehicleRoutingProblem.Builder. Get an instance of this by using the static method VehicleRoutingProblem.Builder.newInstance(). * <p> To construct the problem, use VehicleRoutingProblem.Builder. Get an instance of this by using the static method VehicleRoutingProblem.Builder.newInstance().
* * <p/>
* <p>By default, fleetSize is INFINITE, transport-costs are calculated as euclidean-distance (CrowFlyCosts), * <p>By default, fleetSize is INFINITE, transport-costs are calculated as euclidean-distance (CrowFlyCosts),
* and activity-costs are set to zero. * and activity-costs are set to zero.
* *
*
*
* @author stefan schroeder * @author stefan schroeder
*
*/ */
public class VehicleRoutingProblem { public class VehicleRoutingProblem {
/** /**
* Builder to build the routing-problem. * Builder to build the routing-problem.
* *
* @author stefan schroeder * @author stefan schroeder
* */
*/ public static class Builder {
public static class Builder {
/** /**
* Returns a new instance of this builder. * Returns a new instance of this builder.
* *
* @return builder * @return builder
*/ */
public static Builder newInstance(){ return new Builder(); } public static Builder newInstance() {
return new Builder();
}
private VehicleRoutingTransportCosts transportCosts; private VehicleRoutingTransportCosts transportCosts;
private VehicleRoutingActivityCosts activityCosts = new WaitingTimeCosts(); private VehicleRoutingActivityCosts activityCosts = new WaitingTimeCosts();
private Map<String,Job> jobs = new LinkedHashMap<String, Job>(); private Map<String, Job> jobs = new LinkedHashMap<String, Job>();
private Map<String,Job> tentativeJobs = new LinkedHashMap<String,Job>(); private Map<String, Job> tentativeJobs = new LinkedHashMap<String, Job>();
private Set<String> jobsInInitialRoutes = new HashSet<String>(); private Set<String> jobsInInitialRoutes = new HashSet<String>();
private Map<String, Coordinate> tentative_coordinates = new HashMap<String, Coordinate>(); private Map<String, Coordinate> tentative_coordinates = new HashMap<String, Coordinate>();
private FleetSize fleetSize = FleetSize.INFINITE; private FleetSize fleetSize = FleetSize.INFINITE;
private Collection<VehicleType> vehicleTypes = new ArrayList<VehicleType>(); private Collection<VehicleType> vehicleTypes = new ArrayList<VehicleType>();
private Collection<VehicleRoute> initialRoutes = new ArrayList<VehicleRoute>(); private Collection<VehicleRoute> initialRoutes = new ArrayList<VehicleRoute>();
private Set<Vehicle> uniqueVehicles = new HashSet<Vehicle>(); private Set<Vehicle> uniqueVehicles = new HashSet<Vehicle>();
private boolean hasBreaks = false; private boolean hasBreaks = false;
private JobActivityFactory jobActivityFactory = new JobActivityFactory() { private JobActivityFactory jobActivityFactory = new JobActivityFactory() {
@Override @Override
public List<AbstractActivity> createActivities(Job job) { public List<AbstractActivity> createActivities(Job job) {
List<AbstractActivity> acts = new ArrayList<AbstractActivity>(); List<AbstractActivity> acts = new ArrayList<AbstractActivity>();
if(job instanceof Service){ if (job instanceof Service) {
acts.add(serviceActivityFactory.createActivity((Service) job)); acts.add(serviceActivityFactory.createActivity((Service) job));
} } else if (job instanceof Shipment) {
else if(job instanceof Shipment){
acts.add(shipmentActivityFactory.createPickup((Shipment) job)); acts.add(shipmentActivityFactory.createPickup((Shipment) job));
acts.add(shipmentActivityFactory.createDelivery((Shipment) job)); acts.add(shipmentActivityFactory.createDelivery((Shipment) job));
} }
return acts; return acts;
} }
}; };
@ -121,97 +117,98 @@ public class VehicleRoutingProblem {
private int vehicleTypeIdIndexCounter = 1; private int vehicleTypeIdIndexCounter = 1;
private Map<VehicleTypeKey,Integer> typeKeyIndices = new HashMap<VehicleTypeKey, Integer>(); private Map<VehicleTypeKey, Integer> typeKeyIndices = new HashMap<VehicleTypeKey, Integer>();
private Map<Job,List<AbstractActivity>> activityMap = new HashMap<Job, List<AbstractActivity>>(); private Map<Job, List<AbstractActivity>> activityMap = new HashMap<Job, List<AbstractActivity>>();
private final DefaultShipmentActivityFactory shipmentActivityFactory = new DefaultShipmentActivityFactory(); private final DefaultShipmentActivityFactory shipmentActivityFactory = new DefaultShipmentActivityFactory();
private final DefaultTourActivityFactory serviceActivityFactory = new DefaultTourActivityFactory(); private final DefaultTourActivityFactory serviceActivityFactory = new DefaultTourActivityFactory();
private void incJobIndexCounter(){ private void incJobIndexCounter() {
jobIndexCounter++; jobIndexCounter++;
} }
private void incActivityIndexCounter(){ private void incActivityIndexCounter() {
activityIndexCounter++; activityIndexCounter++;
} }
private void incVehicleTypeIdIndexCounter() { vehicleTypeIdIndexCounter++; } private void incVehicleTypeIdIndexCounter() {
vehicleTypeIdIndexCounter++;
}
/** /**
* Returns the unmodifiable map of collected locations (mapped by their location-id). * Returns the unmodifiable map of collected locations (mapped by their location-id).
* *
* @return map with locations * @return map with locations
*/ */
public Map<String,Coordinate> getLocationMap(){ public Map<String, Coordinate> getLocationMap() {
return Collections.unmodifiableMap(tentative_coordinates); return Collections.unmodifiableMap(tentative_coordinates);
} }
/** /**
* Returns the locations collected SO FAR by this builder. * Returns the locations collected SO FAR by this builder.
* * <p/>
* <p>Locations are cached when adding a shipment, service, depot, vehicle. * <p>Locations are cached when adding a shipment, service, depot, vehicle.
* *
* @return locations * @return locations
* */
**/ public Locations getLocations() {
public Locations getLocations(){ return new Locations() {
return new Locations() {
@Override @Override
public Coordinate getCoord(String id) { public Coordinate getCoord(String id) {
return tentative_coordinates.get(id); return tentative_coordinates.get(id);
} }
}; };
} }
/** /**
* Sets routing costs. * Sets routing costs.
* *
* @param costs the routingCosts * @param costs the routingCosts
* @return builder * @return builder
* @see VehicleRoutingTransportCosts * @see VehicleRoutingTransportCosts
*/ */
public Builder setRoutingCost(VehicleRoutingTransportCosts costs){ public Builder setRoutingCost(VehicleRoutingTransportCosts costs) {
this.transportCosts = costs; this.transportCosts = costs;
return this; return this;
} }
/** /**
* Sets the type of fleetSize. * Sets the type of fleetSize.
* * <p/>
* <p>FleetSize is either FleetSize.INFINITE or FleetSize.FINITE. By default it is FleetSize.INFINITE. * <p>FleetSize is either FleetSize.INFINITE or FleetSize.FINITE. By default it is FleetSize.INFINITE.
* *
* @param fleetSize the fleet size used in this problem. it can either be FleetSize.INFINITE or FleetSize.FINITE * @param fleetSize the fleet size used in this problem. it can either be FleetSize.INFINITE or FleetSize.FINITE
* @return this builder * @return this builder
*/ */
public Builder setFleetSize(FleetSize fleetSize){ public Builder setFleetSize(FleetSize fleetSize) {
this.fleetSize = fleetSize; this.fleetSize = fleetSize;
return this; return this;
} }
/**
* Adds a job which is either a service or a shipment.
*
* <p>Note that job.getId() must be unique, i.e. no job (either it is a shipment or a service) is allowed to have an already allocated id.
*
* @param job job to be added
* @return this builder
* @throws IllegalStateException if job is neither a shipment nor a service, or jobId has already been added.
* @deprecated use addJob(AbstractJob job) instead
*/
@Deprecated
public Builder addJob(Job job) {
if(!(job instanceof AbstractJob)) throw new IllegalArgumentException("job must be of type AbstractJob");
return addJob((AbstractJob)job);
}
/** /**
* Adds a job which is either a service or a shipment. * Adds a job which is either a service or a shipment.
* <p/>
* <p>Note that job.getId() must be unique, i.e. no job (either it is a shipment or a service) is allowed to have an already allocated id.
* *
* @param job job to be added
* @return this builder
* @throws IllegalStateException if job is neither a shipment nor a service, or jobId has already been added.
* @deprecated use addJob(AbstractJob job) instead
*/
@Deprecated
public Builder addJob(Job job) {
if (!(job instanceof AbstractJob)) throw new IllegalArgumentException("job must be of type AbstractJob");
return addJob((AbstractJob) job);
}
/**
* Adds a job which is either a service or a shipment.
* <p/>
* <p>Note that job.getId() must be unique, i.e. no job (either it is a shipment or a service) is allowed to have an already allocated id. * <p>Note that job.getId() must be unique, i.e. no job (either it is a shipment or a service) is allowed to have an already allocated id.
* *
* @param job job to be added * @param job job to be added
@ -219,8 +216,10 @@ public class VehicleRoutingProblem {
* @throws IllegalStateException if job is neither a shipment nor a service, or jobId has already been added. * @throws IllegalStateException if job is neither a shipment nor a service, or jobId has already been added.
*/ */
public Builder addJob(AbstractJob job) { public Builder addJob(AbstractJob job) {
if(tentativeJobs.containsKey(job.getId())) throw new IllegalStateException("jobList already contains a job with id " + job.getId() + ". make sure you use unique ids for your jobs (i.e. service and shipments)"); if (tentativeJobs.containsKey(job.getId()))
if(!(job instanceof Service || job instanceof Shipment)) throw new IllegalStateException("job must be either a service or a shipment"); throw new IllegalStateException("jobList already contains a job with id " + job.getId() + ". make sure you use unique ids for your jobs (i.e. service and shipments)");
if (!(job instanceof Service || job instanceof Shipment))
throw new IllegalStateException("job must be either a service or a shipment");
job.setIndex(jobIndexCounter); job.setIndex(jobIndexCounter);
incJobIndexCounter(); incJobIndexCounter();
tentativeJobs.put(job.getId(), job); tentativeJobs.put(job.getId(), job);
@ -228,47 +227,45 @@ public class VehicleRoutingProblem {
return this; return this;
} }
private void addLocationToTentativeLocations(Job job) { private void addLocationToTentativeLocations(Job job) {
if(job instanceof Service) { if (job instanceof Service) {
tentative_coordinates.put(((Service)job).getLocation().getId(), ((Service)job).getLocation().getCoordinate()); tentative_coordinates.put(((Service) job).getLocation().getId(), ((Service) job).getLocation().getCoordinate());
} } else if (job instanceof Shipment) {
else if(job instanceof Shipment){ Shipment shipment = (Shipment) job;
Shipment shipment = (Shipment)job; tentative_coordinates.put(shipment.getPickupLocation().getId(), shipment.getPickupLocation().getCoordinate());
tentative_coordinates.put(shipment.getPickupLocation().getId(), shipment.getPickupLocation().getCoordinate()); tentative_coordinates.put(shipment.getDeliveryLocation().getId(), shipment.getDeliveryLocation().getCoordinate());
tentative_coordinates.put(shipment.getDeliveryLocation().getId(), shipment.getDeliveryLocation().getCoordinate()); }
} }
}
private void addJobToFinalJobMapAndCreateActivities(Job job){ private void addJobToFinalJobMapAndCreateActivities(Job job) {
if(job instanceof Service) { if (job instanceof Service) {
Service service = (Service) job; Service service = (Service) job;
addService(service); addService(service);
} } else if (job instanceof Shipment) {
else if(job instanceof Shipment){ Shipment shipment = (Shipment) job;
Shipment shipment = (Shipment)job;
addShipment(shipment); addShipment(shipment);
} }
List<AbstractActivity> jobActs = jobActivityFactory.createActivities(job); List<AbstractActivity> jobActs = jobActivityFactory.createActivities(job);
for(AbstractActivity act : jobActs){ for (AbstractActivity act : jobActs) {
act.setIndex(activityIndexCounter); act.setIndex(activityIndexCounter);
incActivityIndexCounter(); incActivityIndexCounter();
} }
activityMap.put(job, jobActs); activityMap.put(job, jobActs);
} }
private boolean addBreaksToActivityMap(){ private boolean addBreaksToActivityMap() {
boolean hasBreaks = false; boolean hasBreaks = false;
for(Vehicle v : uniqueVehicles){ for (Vehicle v : uniqueVehicles) {
if(v.getBreak() != null){ if (v.getBreak() != null) {
hasBreaks = true; hasBreaks = true;
AbstractActivity breakActivity = BreakActivity.newInstance(v.getBreak()); AbstractActivity breakActivity = BreakActivity.newInstance(v.getBreak());
breakActivity.setIndex(activityIndexCounter); breakActivity.setIndex(activityIndexCounter);
incActivityIndexCounter(); incActivityIndexCounter();
activityMap.put(v.getBreak(),Arrays.asList(breakActivity)); activityMap.put(v.getBreak(), Arrays.asList(breakActivity));
} }
} }
return hasBreaks; return hasBreaks;
} }
/** /**
* Adds an initial vehicle route. * Adds an initial vehicle route.
@ -276,25 +273,26 @@ public class VehicleRoutingProblem {
* @param route initial route * @param route initial route
* @return the builder * @return the builder
*/ */
public Builder addInitialVehicleRoute(VehicleRoute route){ public Builder addInitialVehicleRoute(VehicleRoute route) {
addVehicle((AbstractVehicle)route.getVehicle()); addVehicle((AbstractVehicle) route.getVehicle());
for(TourActivity act : route.getActivities()){ for (TourActivity act : route.getActivities()) {
AbstractActivity abstractAct = (AbstractActivity) act; AbstractActivity abstractAct = (AbstractActivity) act;
abstractAct.setIndex(activityIndexCounter); abstractAct.setIndex(activityIndexCounter);
incActivityIndexCounter(); incActivityIndexCounter();
if(act instanceof TourActivity.JobActivity) { if (act instanceof TourActivity.JobActivity) {
Job job = ((TourActivity.JobActivity) act).getJob(); Job job = ((TourActivity.JobActivity) act).getJob();
jobsInInitialRoutes.add(job.getId()); jobsInInitialRoutes.add(job.getId());
registerLocation(job); registerLocation(job);
registerJobAndActivity(abstractAct, job); registerJobAndActivity(abstractAct, job);
} }
} }
initialRoutes.add(route); initialRoutes.add(route);
return this; return this;
} }
private void registerLocation(Job job) { private void registerLocation(Job job) {
if (job instanceof Service) tentative_coordinates.put(((Service) job).getLocation().getId(), ((Service) job).getLocation().getCoordinate()); if (job instanceof Service)
tentative_coordinates.put(((Service) job).getLocation().getId(), ((Service) job).getLocation().getCoordinate());
if (job instanceof Shipment) { if (job instanceof Shipment) {
Shipment shipment = (Shipment) job; Shipment shipment = (Shipment) job;
tentative_coordinates.put(shipment.getPickupLocation().getId(), shipment.getPickupLocation().getCoordinate()); tentative_coordinates.put(shipment.getPickupLocation().getId(), shipment.getPickupLocation().getCoordinate());
@ -303,11 +301,11 @@ public class VehicleRoutingProblem {
} }
private void registerJobAndActivity(AbstractActivity abstractAct, Job job) { private void registerJobAndActivity(AbstractActivity abstractAct, Job job) {
if(activityMap.containsKey(job)) activityMap.get(job).add(abstractAct); if (activityMap.containsKey(job)) activityMap.get(job).add(abstractAct);
else{ else {
List<AbstractActivity> actList = new ArrayList<AbstractActivity>(); List<AbstractActivity> actList = new ArrayList<AbstractActivity>();
actList.add(abstractAct); actList.add(abstractAct);
activityMap.put(job,actList); activityMap.put(job, actList);
} }
} }
@ -317,61 +315,61 @@ public class VehicleRoutingProblem {
* @param routes initial routes * @param routes initial routes
* @return the builder * @return the builder
*/ */
public Builder addInitialVehicleRoutes(Collection<VehicleRoute> routes){ public Builder addInitialVehicleRoutes(Collection<VehicleRoute> routes) {
for(VehicleRoute r : routes){ for (VehicleRoute r : routes) {
addInitialVehicleRoute(r); addInitialVehicleRoute(r);
} }
return this; return this;
} }
private void addShipment(Shipment job) { private void addShipment(Shipment job) {
if(jobs.containsKey(job.getId())){ logger.warn("job " + job + " already in job list. overrides existing job."); } if (jobs.containsKey(job.getId())) {
tentative_coordinates.put(job.getPickupLocation().getId(), job.getPickupLocation().getCoordinate()); logger.warn("job " + job + " already in job list. overrides existing job.");
tentative_coordinates.put(job.getDeliveryLocation().getId(), job.getDeliveryLocation().getCoordinate()); }
jobs.put(job.getId(),job); tentative_coordinates.put(job.getPickupLocation().getId(), job.getPickupLocation().getCoordinate());
} tentative_coordinates.put(job.getDeliveryLocation().getId(), job.getDeliveryLocation().getCoordinate());
jobs.put(job.getId(), job);
/** }
* Adds a vehicle.
*
*
* @param vehicle vehicle to be added
* @return this builder
* @deprecated use addVehicle(AbstractVehicle vehicle) instead
*/
@Deprecated
public Builder addVehicle(Vehicle vehicle) {
if(!(vehicle instanceof AbstractVehicle)) throw new IllegalStateException("vehicle must be an AbstractVehicle");
return addVehicle((AbstractVehicle)vehicle);
}
/** /**
* Adds a vehicle. * Adds a vehicle.
* *
* @param vehicle vehicle to be added
* @return this builder
* @deprecated use addVehicle(AbstractVehicle vehicle) instead
*/
@Deprecated
public Builder addVehicle(Vehicle vehicle) {
if (!(vehicle instanceof AbstractVehicle))
throw new IllegalStateException("vehicle must be an AbstractVehicle");
return addVehicle((AbstractVehicle) vehicle);
}
/**
* Adds a vehicle.
* *
* @param vehicle vehicle to be added * @param vehicle vehicle to be added
* @return this builder * @return this builder
*/ */
public Builder addVehicle(AbstractVehicle vehicle) { public Builder addVehicle(AbstractVehicle vehicle) {
if(!uniqueVehicles.contains(vehicle)){ if (!uniqueVehicles.contains(vehicle)) {
vehicle.setIndex(vehicleIndexCounter); vehicle.setIndex(vehicleIndexCounter);
incVehicleIndexCounter(); incVehicleIndexCounter();
} }
if(typeKeyIndices.containsKey(vehicle.getVehicleTypeIdentifier())){ if (typeKeyIndices.containsKey(vehicle.getVehicleTypeIdentifier())) {
vehicle.getVehicleTypeIdentifier().setIndex(typeKeyIndices.get(vehicle.getVehicleTypeIdentifier())); vehicle.getVehicleTypeIdentifier().setIndex(typeKeyIndices.get(vehicle.getVehicleTypeIdentifier()));
} } else {
else {
vehicle.getVehicleTypeIdentifier().setIndex(vehicleTypeIdIndexCounter); vehicle.getVehicleTypeIdentifier().setIndex(vehicleTypeIdIndexCounter);
typeKeyIndices.put(vehicle.getVehicleTypeIdentifier(),vehicleTypeIdIndexCounter); typeKeyIndices.put(vehicle.getVehicleTypeIdentifier(), vehicleTypeIdIndexCounter);
incVehicleTypeIdIndexCounter(); incVehicleTypeIdIndexCounter();
} }
uniqueVehicles.add(vehicle); uniqueVehicles.add(vehicle);
if(!vehicleTypes.contains(vehicle.getType())){ if (!vehicleTypes.contains(vehicle.getType())) {
vehicleTypes.add(vehicle.getType()); vehicleTypes.add(vehicle.getType());
} }
String startLocationId = vehicle.getStartLocation().getId(); String startLocationId = vehicle.getStartLocation().getId();
tentative_coordinates.put(startLocationId, vehicle.getStartLocation().getCoordinate()); tentative_coordinates.put(startLocationId, vehicle.getStartLocation().getCoordinate());
if(!vehicle.getEndLocation().getId().equals(startLocationId)){ if (!vehicle.getEndLocation().getId().equals(startLocationId)) {
tentative_coordinates.put(vehicle.getEndLocation().getId(), vehicle.getEndLocation().getCoordinate()); tentative_coordinates.put(vehicle.getEndLocation().getId(), vehicle.getEndLocation().getCoordinate());
} }
return this; return this;
@ -382,162 +380,164 @@ public class VehicleRoutingProblem {
} }
/** /**
* Sets the activity-costs. * Sets the activity-costs.
* * <p/>
* <p>By default it is set to zero. * <p>By default it is set to zero.
* *
* @param activityCosts activity costs of the problem * @param activityCosts activity costs of the problem
* @return this builder * @return this builder
* @see VehicleRoutingActivityCosts * @see VehicleRoutingActivityCosts
*/ */
public Builder setActivityCosts(VehicleRoutingActivityCosts activityCosts){ public Builder setActivityCosts(VehicleRoutingActivityCosts activityCosts) {
this.activityCosts = activityCosts; this.activityCosts = activityCosts;
return this; return this;
} }
/** /**
* Builds the {@link VehicleRoutingProblem}. * Builds the {@link VehicleRoutingProblem}.
* * <p/>
* <p>If {@link VehicleRoutingTransportCosts} are not set, {@link CrowFlyCosts} is used. * <p>If {@link VehicleRoutingTransportCosts} are not set, {@link CrowFlyCosts} is used.
* *
* @return {@link VehicleRoutingProblem} * @return {@link VehicleRoutingProblem}
*/ */
public VehicleRoutingProblem build() { public VehicleRoutingProblem build() {
if(transportCosts == null){ if (transportCosts == null) {
transportCosts = new CrowFlyCosts(getLocations()); transportCosts = new CrowFlyCosts(getLocations());
} }
for(Job job : tentativeJobs.values()) { for (Job job : tentativeJobs.values()) {
if (!jobsInInitialRoutes.contains(job.getId())) { if (!jobsInInitialRoutes.contains(job.getId())) {
addJobToFinalJobMapAndCreateActivities(job); addJobToFinalJobMapAndCreateActivities(job);
} }
} }
boolean hasBreaks = addBreaksToActivityMap(); boolean hasBreaks = addBreaksToActivityMap();
if(hasBreaks && fleetSize.equals(FleetSize.INFINITE)) throw new UnsupportedOperationException("breaks are not yet supported when dealing with infinite fleet. either set it to finite or omit breaks."); if (hasBreaks && fleetSize.equals(FleetSize.INFINITE))
return new VehicleRoutingProblem(this); throw new UnsupportedOperationException("breaks are not yet supported when dealing with infinite fleet. either set it to finite or omit breaks.");
} return new VehicleRoutingProblem(this);
}
@SuppressWarnings("UnusedDeclaration") @SuppressWarnings("UnusedDeclaration")
public Builder addLocation(String locationId, Coordinate coordinate) { public Builder addLocation(String locationId, Coordinate coordinate) {
tentative_coordinates.put(locationId, coordinate); tentative_coordinates.put(locationId, coordinate);
return this; return this;
} }
/** /**
* Adds a collection of jobs. * Adds a collection of jobs.
* *
* @param jobs which is a collection of jobs that subclasses Job * @param jobs which is a collection of jobs that subclasses Job
* @return this builder * @return this builder
*/ */
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public Builder addAllJobs(Collection<? extends Job> jobs) { public Builder addAllJobs(Collection<? extends Job> jobs) {
for(Job j : jobs){ for (Job j : jobs) {
addJob(j); addJob(j);
} }
return this; return this;
} }
/** /**
* Adds a collection of vehicles. * Adds a collection of vehicles.
* *
* @param vehicles vehicles to be added * @param vehicles vehicles to be added
* @return this builder * @return this builder
*/ */
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public Builder addAllVehicles(Collection<? extends Vehicle> vehicles) { public Builder addAllVehicles(Collection<? extends Vehicle> vehicles) {
for(Vehicle v : vehicles){ for (Vehicle v : vehicles) {
addVehicle(v); addVehicle(v);
} }
return this; return this;
} }
/** /**
* Gets an unmodifiable collection of already added vehicles. * Gets an unmodifiable collection of already added vehicles.
* *
* @return collection of vehicles * @return collection of vehicles
*/ */
public Collection<Vehicle> getAddedVehicles(){ public Collection<Vehicle> getAddedVehicles() {
return Collections.unmodifiableCollection(uniqueVehicles); return Collections.unmodifiableCollection(uniqueVehicles);
} }
/** /**
* Gets an unmodifiable collection of already added vehicle-types. * Gets an unmodifiable collection of already added vehicle-types.
* *
* @return collection of vehicle-types * @return collection of vehicle-types
*/ */
public Collection<VehicleType> getAddedVehicleTypes(){ public Collection<VehicleType> getAddedVehicleTypes() {
return Collections.unmodifiableCollection(vehicleTypes); return Collections.unmodifiableCollection(vehicleTypes);
} }
/** /**
* Returns an unmodifiable collection of already added jobs. * Returns an unmodifiable collection of already added jobs.
* *
* @return collection of jobs * @return collection of jobs
*/ */
public Collection<Job> getAddedJobs(){ public Collection<Job> getAddedJobs() {
return Collections.unmodifiableCollection(tentativeJobs.values()); return Collections.unmodifiableCollection(tentativeJobs.values());
} }
private Builder addService(Service service){ private Builder addService(Service service) {
tentative_coordinates.put(service.getLocation().getId(), service.getLocation().getCoordinate()); tentative_coordinates.put(service.getLocation().getId(), service.getLocation().getCoordinate());
if(jobs.containsKey(service.getId())){ logger.warn("service " + service + " already in job list. overrides existing job."); } if (jobs.containsKey(service.getId())) {
jobs.put(service.getId(),service); logger.warn("service " + service + " already in job list. overrides existing job.");
return this; }
} jobs.put(service.getId(), service);
return this;
}
} }
/** /**
* Enum that characterizes the fleet-size. * Enum that characterizes the fleet-size.
* *
* @author sschroeder * @author sschroeder
* */
*/ public static enum FleetSize {
public static enum FleetSize { FINITE, INFINITE
FINITE, INFINITE }
}
/** /**
* logger logging for this class * logger logging for this class
*/ */
private final static Logger logger = LogManager.getLogger(VehicleRoutingProblem.class); private final static Logger logger = LogManager.getLogger(VehicleRoutingProblem.class);
/** /**
* contains transportation costs, i.e. the costs traveling from location A to B * contains transportation costs, i.e. the costs traveling from location A to B
*/ */
private final VehicleRoutingTransportCosts transportCosts; private final VehicleRoutingTransportCosts transportCosts;
/** /**
* contains activity costs, i.e. the costs imposed by an activity * contains activity costs, i.e. the costs imposed by an activity
*/ */
private final VehicleRoutingActivityCosts activityCosts; private final VehicleRoutingActivityCosts activityCosts;
/** /**
* map of jobs, stored by jobId * map of jobs, stored by jobId
*/ */
private final Map<String, Job> jobs; private final Map<String, Job> jobs;
/** /**
* Collection that contains available vehicles. * Collection that contains available vehicles.
*/ */
private final Collection<Vehicle> vehicles; private final Collection<Vehicle> vehicles;
/** /**
* Collection that contains all available types. * Collection that contains all available types.
*/ */
private final Collection<VehicleType> vehicleTypes; private final Collection<VehicleType> vehicleTypes;
private final Collection<VehicleRoute> initialVehicleRoutes; private final Collection<VehicleRoute> initialVehicleRoutes;
/** /**
* An enum that indicates type of fleetSize. By default, it is INFINTE * An enum that indicates type of fleetSize. By default, it is INFINTE
*/ */
private final FleetSize fleetSize; private final FleetSize fleetSize;
private final Locations locations; private final Locations locations;
private Map<Job,List<AbstractActivity>> activityMap; private Map<Job, List<AbstractActivity>> activityMap;
private int nuActivities; private int nuActivities;
@ -550,121 +550,123 @@ public class VehicleRoutingProblem {
}; };
private VehicleRoutingProblem(Builder builder) { private VehicleRoutingProblem(Builder builder) {
this.jobs = builder.jobs; this.jobs = builder.jobs;
this.fleetSize = builder.fleetSize; this.fleetSize = builder.fleetSize;
this.vehicles=builder.uniqueVehicles; this.vehicles = builder.uniqueVehicles;
this.vehicleTypes = builder.vehicleTypes; this.vehicleTypes = builder.vehicleTypes;
this.initialVehicleRoutes = builder.initialRoutes; this.initialVehicleRoutes = builder.initialRoutes;
this.transportCosts = builder.transportCosts; this.transportCosts = builder.transportCosts;
this.activityCosts = builder.activityCosts; this.activityCosts = builder.activityCosts;
this.locations = builder.getLocations(); this.locations = builder.getLocations();
this.activityMap = builder.activityMap; this.activityMap = builder.activityMap;
this.nuActivities = builder.activityIndexCounter; this.nuActivities = builder.activityIndexCounter;
logger.info("setup problem: {}", this); logger.info("setup problem: {}", this);
} }
@Override @Override
public String toString() { public String toString() {
return "[fleetSize="+fleetSize+"][#jobs="+jobs.size()+"][#vehicles="+vehicles.size()+"][#vehicleTypes="+vehicleTypes.size()+"]["+ return "[fleetSize=" + fleetSize + "][#jobs=" + jobs.size() + "][#vehicles=" + vehicles.size() + "][#vehicleTypes=" + vehicleTypes.size() + "][" +
"transportCost="+transportCosts+"][activityCosts="+activityCosts+"]"; "transportCost=" + transportCosts + "][activityCosts=" + activityCosts + "]";
} }
/** /**
* Returns type of fleetSize, either INFINITE or FINITE. * Returns type of fleetSize, either INFINITE or FINITE.
* * <p/>
* <p>By default, it is INFINITE. * <p>By default, it is INFINITE.
* *
* @return either FleetSize.INFINITE or FleetSize.FINITE * @return either FleetSize.INFINITE or FleetSize.FINITE
*/ */
public FleetSize getFleetSize() { public FleetSize getFleetSize() {
return fleetSize; return fleetSize;
} }
/** /**
* Returns the unmodifiable job map. * Returns the unmodifiable job map.
* *
* @return unmodifiable jobMap * @return unmodifiable jobMap
*/ */
public Map<String, Job> getJobs() { public Map<String, Job> getJobs() {
return Collections.unmodifiableMap(jobs); return Collections.unmodifiableMap(jobs);
} }
/** /**
* Returns a copy of initial vehicle routes. * Returns a copy of initial vehicle routes.
* *
* @return copied collection of initial vehicle routes * @return copied collection of initial vehicle routes
*/ */
public Collection<VehicleRoute> getInitialVehicleRoutes(){ public Collection<VehicleRoute> getInitialVehicleRoutes() {
Collection<VehicleRoute> copiedInitialRoutes = new ArrayList<VehicleRoute>(); Collection<VehicleRoute> copiedInitialRoutes = new ArrayList<VehicleRoute>();
for(VehicleRoute route : initialVehicleRoutes){ for (VehicleRoute route : initialVehicleRoutes) {
copiedInitialRoutes.add(VehicleRoute.copyOf(route)); copiedInitialRoutes.add(VehicleRoute.copyOf(route));
} }
return copiedInitialRoutes; return copiedInitialRoutes;
} }
/** /**
* Returns the entire, unmodifiable collection of types. * Returns the entire, unmodifiable collection of types.
* *
* @return unmodifiable collection of types * @return unmodifiable collection of types
* @see VehicleTypeImpl * @see VehicleTypeImpl
*/ */
public Collection<VehicleType> getTypes(){ public Collection<VehicleType> getTypes() {
return Collections.unmodifiableCollection(vehicleTypes); return Collections.unmodifiableCollection(vehicleTypes);
} }
/** /**
* Returns the entire, unmodifiable collection of vehicles. * Returns the entire, unmodifiable collection of vehicles.
* *
* @return unmodifiable collection of vehicles * @return unmodifiable collection of vehicles
* @see Vehicle * @see Vehicle
*/ */
public Collection<Vehicle> getVehicles() { public Collection<Vehicle> getVehicles() {
return Collections.unmodifiableCollection(vehicles); return Collections.unmodifiableCollection(vehicles);
} }
/** /**
* Returns routing costs. * Returns routing costs.
* *
* @return routingCosts * @return routingCosts
* @see VehicleRoutingTransportCosts * @see VehicleRoutingTransportCosts
*/ */
public VehicleRoutingTransportCosts getTransportCosts() { public VehicleRoutingTransportCosts getTransportCosts() {
return transportCosts; return transportCosts;
} }
/** /**
* Returns activityCosts. * Returns activityCosts.
*/ */
public VehicleRoutingActivityCosts getActivityCosts(){ public VehicleRoutingActivityCosts getActivityCosts() {
return activityCosts; return activityCosts;
} }
/** /**
* @return returns all location, i.e. from vehicles and jobs. * @return returns all location, i.e. from vehicles and jobs.
*/ */
public Locations getLocations(){ public Locations getLocations() {
return locations; return locations;
} }
/** /**
* @param job for which the corresponding activities needs to be returned * @param job for which the corresponding activities needs to be returned
* @return associated activities * @return associated activities
*/ */
public List<AbstractActivity> getActivities(Job job){ public List<AbstractActivity> getActivities(Job job) {
return Collections.unmodifiableList(activityMap.get(job)); return Collections.unmodifiableList(activityMap.get(job));
} }
/** /**
* @return total number of activities * @return total number of activities
*/ */
public int getNuActivities(){ return nuActivities; } public int getNuActivities() {
return nuActivities;
}
/** /**
* @return factory that creates the activities associated to a job * @return factory that creates the activities associated to a job
*/ */
public JobActivityFactory getJobActivityFactory(){ public JobActivityFactory getJobActivityFactory() {
return jobActivityFactory; return jobActivityFactory;
} }
@ -672,9 +674,9 @@ public class VehicleRoutingProblem {
* @param job for which the corresponding activities needs to be returned * @param job for which the corresponding activities needs to be returned
* @return a copy of the activities that are associated to the specified job * @return a copy of the activities that are associated to the specified job
*/ */
public List<AbstractActivity> copyAndGetActivities(Job job){ public List<AbstractActivity> copyAndGetActivities(Job job) {
List<AbstractActivity> acts = new ArrayList<AbstractActivity>(); List<AbstractActivity> acts = new ArrayList<AbstractActivity>();
if(activityMap.containsKey(job)) { if (activityMap.containsKey(job)) {
for (AbstractActivity act : activityMap.get(job)) acts.add((AbstractActivity) act.duplicate()); for (AbstractActivity act : activityMap.get(job)) acts.add((AbstractActivity) act.duplicate());
} }
return acts; return acts;

View file

@ -125,7 +125,7 @@ class TimeWindowConstraint implements HardActivityConstraint {
double arrTimeAtNextAct = endTimeAtNewAct + routingCosts.getTransportTime(newAct.getLocation(), nextAct.getLocation(), endTimeAtNewAct, iFacts.getNewDriver(), iFacts.getNewVehicle()); double arrTimeAtNextAct = endTimeAtNewAct + routingCosts.getTransportTime(newAct.getLocation(), nextAct.getLocation(), endTimeAtNewAct, iFacts.getNewDriver(), iFacts.getNewVehicle());
/* /*
* |--- newAct ---| * |--- newAct ---|
* |--- vehicle's arrival @nextAct * |--- vehicle's arrival @nextAct
* latest arrival of vehicle @nextAct ---| * latest arrival of vehicle @nextAct ---|
*/ */

View file

@ -24,57 +24,56 @@ import jsprit.core.problem.Skills;
* Pickup extends Service and is intended to model a Service where smth is LOADED (i.e. picked up) to a transport unit. * Pickup extends Service and is intended to model a Service where smth is LOADED (i.e. picked up) to a transport unit.
* *
* @author schroeder * @author schroeder
*
*/ */
public class Break extends Service { public class Break extends Service {
public static class Builder extends Service.Builder<Break> { public static class Builder extends Service.Builder<Break> {
/** /**
* Returns a new instance of builder that builds a pickup. * Returns a new instance of builder that builds a pickup.
* *
* @param id the id of the pickup * @param id the id of the pickup
* @return the builder * @return the builder
*/ */
public static Builder newInstance(String id){ public static Builder newInstance(String id) {
return new Builder(id); return new Builder(id);
} }
private boolean variableLocation = true; private boolean variableLocation = true;
Builder(String id) { Builder(String id) {
super(id); super(id);
} }
/** /**
* Builds Pickup. * Builds Pickup.
* * <p/>
*<p>Pickup type is "pickup" * <p>Pickup type is "pickup"
* *
* @return pickup * @return pickup
* @throws IllegalStateException if neither locationId nor coordinate has been set * @throws IllegalStateException if neither locationId nor coordinate has been set
*/ */
public Break build(){ public Break build() {
if(location != null){ if (location != null) {
variableLocation = false; variableLocation = false;
} }
this.setType("break"); this.setType("break");
super.capacity = Capacity.Builder.newInstance().build(); super.capacity = Capacity.Builder.newInstance().build();
super.skills = Skills.Builder.newInstance().build(); super.skills = Skills.Builder.newInstance().build();
return new Break(this); return new Break(this);
} }
} }
private boolean variableLocation = true; private boolean variableLocation = true;
Break(Builder builder) { Break(Builder builder) {
super(builder); super(builder);
this.variableLocation = builder.variableLocation; this.variableLocation = builder.variableLocation;
} }
public boolean hasVariableLocation(){ public boolean hasVariableLocation() {
return variableLocation; return variableLocation;
} }
} }

View file

@ -127,13 +127,11 @@ public class VehicleRoute {
@Override @Override
public List<AbstractActivity> createActivities(Job job) { public List<AbstractActivity> createActivities(Job job) {
List<AbstractActivity> acts = new ArrayList<AbstractActivity>(); List<AbstractActivity> acts = new ArrayList<AbstractActivity>();
if(job instanceof Break){ if (job instanceof Break) {
acts.add(BreakActivity.newInstance((Break)job)); acts.add(BreakActivity.newInstance((Break) job));
} } else if (job instanceof Service) {
else if(job instanceof Service){
acts.add(serviceActivityFactory.createActivity((Service) job)); acts.add(serviceActivityFactory.createActivity((Service) job));
} } else if (job instanceof Shipment) {
else if(job instanceof Shipment){
acts.add(shipmentActivityFactory.createPickup((Shipment) job)); acts.add(shipmentActivityFactory.createPickup((Shipment) job));
acts.add(shipmentActivityFactory.createDelivery((Shipment) job)); acts.add(shipmentActivityFactory.createDelivery((Shipment) job));
} }

View file

@ -11,7 +11,7 @@
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details. * Lesser General Public License for more details.
* *
* You should have received a copy of the GNU Lesser General Public * 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/>. * License along with this library. If not, see <http://www.gnu.org/licenses/>.
******************************************************************************/ ******************************************************************************/
package jsprit.core.problem.solution.route.activity; package jsprit.core.problem.solution.route.activity;
@ -23,156 +23,155 @@ import jsprit.core.problem.job.Break;
import jsprit.core.problem.job.Service; import jsprit.core.problem.job.Service;
import jsprit.core.problem.solution.route.activity.TourActivity.JobActivity; import jsprit.core.problem.solution.route.activity.TourActivity.JobActivity;
public class BreakActivity extends AbstractActivity implements JobActivity{ public class BreakActivity extends AbstractActivity implements JobActivity {
public static int counter = 0; public static int counter = 0;
public double arrTime; public double arrTime;
public double endTime; public double endTime;
private Location location; private Location location;
/** /**
* @return the arrTime * @return the arrTime
*/ */
public double getArrTime() { public double getArrTime() {
return arrTime; return arrTime;
} }
/** /**
* @param arrTime the arrTime to set * @param arrTime the arrTime to set
*/ */
public void setArrTime(double arrTime) { public void setArrTime(double arrTime) {
this.arrTime = arrTime; this.arrTime = arrTime;
} }
/** /**
* @return the endTime * @return the endTime
*/ */
public double getEndTime() { public double getEndTime() {
return endTime; return endTime;
} }
/** /**
* @param endTime the endTime to set * @param endTime the endTime to set
*/ */
public void setEndTime(double endTime) { public void setEndTime(double endTime) {
this.endTime = endTime; this.endTime = endTime;
} }
public static BreakActivity copyOf(BreakActivity breakActivity){ public static BreakActivity copyOf(BreakActivity breakActivity) {
return new BreakActivity(breakActivity); return new BreakActivity(breakActivity);
} }
public static BreakActivity newInstance(Break aBreak){ public static BreakActivity newInstance(Break aBreak) {
return new BreakActivity(aBreak); return new BreakActivity(aBreak);
} }
private final Break aBreak; private final Break aBreak;
protected BreakActivity(Break aBreak) { protected BreakActivity(Break aBreak) {
counter++; counter++;
this.aBreak = aBreak; this.aBreak = aBreak;
} }
protected BreakActivity(BreakActivity breakActivity) { protected BreakActivity(BreakActivity breakActivity) {
counter++; counter++;
this.aBreak = (Break) breakActivity.getJob(); this.aBreak = (Break) breakActivity.getJob();
this.arrTime = breakActivity.getArrTime(); this.arrTime = breakActivity.getArrTime();
this.endTime = breakActivity.getEndTime(); this.endTime = breakActivity.getEndTime();
this.location = breakActivity.getLocation(); this.location = breakActivity.getLocation();
setIndex(breakActivity.getIndex()); setIndex(breakActivity.getIndex());
} }
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((aBreak == null) ? 0 : aBreak.hashCode());
return result;
}
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
BreakActivity other = (BreakActivity) obj;
if (aBreak == null) {
if (other.aBreak != null)
return false;
} else if (!aBreak.equals(other.aBreak))
return false;
return true;
}
public double getTheoreticalEarliestOperationStartTime() { /* (non-Javadoc)
return aBreak.getTimeWindow().getStart(); * @see java.lang.Object#hashCode()
} */
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((aBreak == null) ? 0 : aBreak.hashCode());
return result;
}
public double getTheoreticalLatestOperationStartTime() { /* (non-Javadoc)
return aBreak.getTimeWindow().getEnd(); * @see java.lang.Object#equals(java.lang.Object)
} */
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
BreakActivity other = (BreakActivity) obj;
if (aBreak == null) {
if (other.aBreak != null)
return false;
} else if (!aBreak.equals(other.aBreak))
return false;
return true;
}
@Override public double getTheoreticalEarliestOperationStartTime() {
public double getOperationTime() { return aBreak.getTimeWindow().getStart();
return aBreak.getServiceDuration(); }
}
@Override public double getTheoreticalLatestOperationStartTime() {
public String getLocationId() { return aBreak.getTimeWindow().getEnd();
return aBreak.getLocation().getId(); }
}
@Override
public double getOperationTime() {
return aBreak.getServiceDuration();
}
@Override
public String getLocationId() {
return aBreak.getLocation().getId();
}
@Override @Override
public Location getLocation() { public Location getLocation() {
return location; return location;
} }
public void setLocation(Location breakLocation){ public void setLocation(Location breakLocation) {
this.location = breakLocation; this.location = breakLocation;
} }
@Override @Override
public Service getJob() { public Service getJob() {
return aBreak; return aBreak;
} }
@Override
public String toString() {
return "[type="+getName()+"][location=" + getLocation()
+ "][size=" + getSize().toString()
+ "][twStart=" + Activities.round(getTheoreticalEarliestOperationStartTime())
+ "][twEnd=" + Activities.round(getTheoreticalLatestOperationStartTime()) + "]";
}
@Override
public String getName() {
return aBreak.getType();
}
@Override @Override
public TourActivity duplicate() { public String toString() {
return new BreakActivity(this); return "[type=" + getName() + "][location=" + getLocation()
} + "][size=" + getSize().toString()
+ "][twStart=" + Activities.round(getTheoreticalEarliestOperationStartTime())
+ "][twEnd=" + Activities.round(getTheoreticalLatestOperationStartTime()) + "]";
}
@Override
public String getName() {
return aBreak.getType();
}
@Override
public TourActivity duplicate() {
return new BreakActivity(this);
}
@Override
public Capacity getSize() {
return aBreak.getSize();
}
@Override
public Capacity getSize() {
return aBreak.getSize();
}
} }

View file

@ -129,14 +129,14 @@ public class TourActivities {
} }
boolean activityRemoved = false; boolean activityRemoved = false;
Iterator<TourActivity> iterator = tourActivities.iterator(); Iterator<TourActivity> iterator = tourActivities.iterator();
while(iterator.hasNext()){ while (iterator.hasNext()) {
TourActivity c = iterator.next(); TourActivity c = iterator.next();
if (c instanceof JobActivity) { if (c instanceof JobActivity) {
Job underlyingJob = ((JobActivity) c).getJob(); Job underlyingJob = ((JobActivity) c).getJob();
if (job.equals(underlyingJob)) { if (job.equals(underlyingJob)) {
iterator.remove(); iterator.remove();
activityRemoved = true; activityRemoved = true;
if(underlyingJob instanceof Service){ if (underlyingJob instanceof Service) {
break; break;
} }
} }

View file

@ -72,5 +72,5 @@ public interface Vehicle extends HasId, HasIndex {
public abstract Skills getSkills(); public abstract Skills getSkills();
public abstract Break getBreak(); public abstract Break getBreak();
} }

View file

@ -24,7 +24,6 @@ import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
/** /**
* Implementation of {@link Vehicle}. * Implementation of {@link Vehicle}.
* *
@ -46,8 +45,8 @@ public class VehicleImpl extends AbstractVehicle {
private VehicleType type = VehicleTypeImpl.Builder.newInstance("noType").build(); private VehicleType type = VehicleTypeImpl.Builder.newInstance("noType").build();
public NoVehicle() { public NoVehicle() {
} }
@Override @Override
public double getEarliestDeparture() { public double getEarliestDeparture() {
@ -90,22 +89,23 @@ public class VehicleImpl extends AbstractVehicle {
} }
@Override @Override
public Break getBreak() { return null; } public Break getBreak() {
return null;
}
} }
/** /**
* Builder that builds the vehicle. * Builder that builds the vehicle.
* * <p/>
* <p>By default, earliestDepartureTime is 0.0, latestDepartureTime is Double.MAX_VALUE, * <p>By default, earliestDepartureTime is 0.0, latestDepartureTime is Double.MAX_VALUE,
* it returns to the depot and its {@link VehicleType} is the DefaultType with typeId equal to 'default' * it returns to the depot and its {@link VehicleType} is the DefaultType with typeId equal to 'default'
* and a capacity of 0. * and a capacity of 0.
* *
* @author stefan * @author stefan
* */
*/ public static class Builder {
public static class Builder {
static final Logger log = LogManager.getLogger(Builder.class.getName()); static final Logger log = LogManager.getLogger(Builder.class.getName());
@ -127,42 +127,42 @@ public class VehicleImpl extends AbstractVehicle {
private Location endLocation; private Location endLocation;
private Break aBreak; private Break aBreak;
private Builder(String id) { private Builder(String id) {
super(); super();
this.id = id; this.id = id;
} }
/** /**
* Sets the {@link VehicleType}.<br> * Sets the {@link VehicleType}.<br>
* *
* @param type the type to be set * @param type the type to be set
* @throws IllegalStateException if type is null * @return this builder
* @return this builder * @throws IllegalStateException if type is null
*/ */
public Builder setType(VehicleType type){ public Builder setType(VehicleType type) {
if(type==null) throw new IllegalStateException("type cannot be null."); if (type == null) throw new IllegalStateException("type cannot be null.");
this.type = type; this.type = type;
return this; return this;
} }
/** /**
* Sets the flag whether the vehicle must return to depot or not. * Sets the flag whether the vehicle must return to depot or not.
* * <p/>
* <p>If returnToDepot is true, the vehicle must return to specified end-location. If you * <p>If returnToDepot is true, the vehicle must return to specified end-location. If you
* omit specifying the end-location, vehicle returns to start-location (that must to be set). If * omit specifying the end-location, vehicle returns to start-location (that must to be set). If
* you specify it, it returns to specified end-location. * you specify it, it returns to specified end-location.
* * <p/>
* <p>If returnToDepot is false, the end-location of the vehicle is endogenous. * <p>If returnToDepot is false, the end-location of the vehicle is endogenous.
* *
* @param returnToDepot true if vehicle need to return to depot, otherwise false * @param returnToDepot true if vehicle need to return to depot, otherwise false
* @return this builder * @return this builder
*/ */
public Builder setReturnToDepot(boolean returnToDepot){ public Builder setReturnToDepot(boolean returnToDepot) {
this.returnToDepot = returnToDepot; this.returnToDepot = returnToDepot;
return this; return this;
} }
/** /**
* Sets start location. * Sets start location.
@ -187,7 +187,8 @@ public class VehicleImpl extends AbstractVehicle {
* @return this builder * @return this builder
*/ */
public Builder setEarliestStart(double earliest_startTime) { public Builder setEarliestStart(double earliest_startTime) {
if(earliest_startTime < 0) throw new IllegalArgumentException("earliest start of vehicle " + id + " must not be negative"); if (earliest_startTime < 0)
throw new IllegalArgumentException("earliest start of vehicle " + id + " must not be negative");
this.earliestStart = earliest_startTime; this.earliestStart = earliest_startTime;
return this; return this;
} }
@ -199,7 +200,8 @@ public class VehicleImpl extends AbstractVehicle {
* @return this builder * @return this builder
*/ */
public Builder setLatestArrival(double latest_arrTime) { public Builder setLatestArrival(double latest_arrTime) {
if(latest_arrTime < 0) throw new IllegalArgumentException("latest arrival time of vehicle " + id + " must not be negative"); if (latest_arrTime < 0)
throw new IllegalArgumentException("latest arrival time of vehicle " + id + " must not be negative");
this.latestArrival = latest_arrTime; this.latestArrival = latest_arrTime;
return this; return this;
} }
@ -226,7 +228,8 @@ public class VehicleImpl extends AbstractVehicle {
* or (endLocationId!=null AND returnToDepot=false) * or (endLocationId!=null AND returnToDepot=false)
*/ */
public VehicleImpl build() { public VehicleImpl build() {
if(latestArrival < earliestStart) throw new IllegalStateException("latest arrival of vehicle " + id + " must not be smaller than its start time"); if (latestArrival < earliestStart)
throw new IllegalStateException("latest arrival of vehicle " + id + " must not be smaller than its start time");
if (startLocation != null && endLocation != null) { if (startLocation != null && endLocation != null) {
if (!startLocation.getId().equals(endLocation.getId()) && !returnToDepot) if (!startLocation.getId().equals(endLocation.getId()) && !returnToDepot)
throw new IllegalStateException("this must not be. you specified both endLocationId and open-routes. this is contradictory. <br>" + throw new IllegalStateException("this must not be. you specified both endLocationId and open-routes. this is contradictory. <br>" +
@ -257,22 +260,22 @@ public class VehicleImpl extends AbstractVehicle {
return this; return this;
} }
public Builder setBreak(Break aBreak) { public Builder setBreak(Break aBreak) {
this.aBreak = aBreak; this.aBreak = aBreak;
return this; return this;
} }
} }
/** /**
* Returns empty/noVehicle which is a vehicle having no capacity, no type and no reasonable id. * Returns empty/noVehicle which is a vehicle having no capacity, no type and no reasonable id.
* * <p/>
* <p>NoVehicle has id="noVehicle" and extends {@link VehicleImpl} * <p>NoVehicle has id="noVehicle" and extends {@link VehicleImpl}
* *
* @return emptyVehicle * @return emptyVehicle
*/ */
public static NoVehicle createNoVehicle(){ public static NoVehicle createNoVehicle() {
return new NoVehicle(); return new NoVehicle();
} }
private final String id; private final String id;
@ -290,29 +293,29 @@ public class VehicleImpl extends AbstractVehicle {
private final Location startLocation; private final Location startLocation;
private final Break aBreak; private final Break aBreak;
private VehicleImpl(Builder builder){ private VehicleImpl(Builder builder) {
id = builder.id; id = builder.id;
type = builder.type; type = builder.type;
earliestDeparture = builder.earliestStart; earliestDeparture = builder.earliestStart;
latestArrival = builder.latestArrival; latestArrival = builder.latestArrival;
returnToDepot = builder.returnToDepot; returnToDepot = builder.returnToDepot;
skills = builder.skills; skills = builder.skills;
endLocation = builder.endLocation; endLocation = builder.endLocation;
startLocation = builder.startLocation; startLocation = builder.startLocation;
aBreak = builder.aBreak; 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)); setVehicleIdentifier(new VehicleTypeKey(type.getTypeId(), startLocation.getId(), endLocation.getId(), earliestDeparture, latestArrival, skills, returnToDepot));
} }
/** /**
* Returns String with attributes of this vehicle * Returns String with attributes of this vehicle
* * <p/>
* <p>String has the following format [attr1=val1][attr2=val2]...[attrn=valn] * <p>String has the following format [attr1=val1][attr2=val2]...[attrn=valn]
*/ */
@Override @Override
public String toString() { public String toString() {
return "[id=" + id + "]" + return "[id=" + id + "]" +
"[type=" + type + "]" + "[type=" + type + "]" +
"[startLocation=" + startLocation + "]" + "[startLocation=" + startLocation + "]" +
@ -361,47 +364,47 @@ public class VehicleImpl extends AbstractVehicle {
return skills; return skills;
} }
@Override @Override
public Break getBreak() { public Break getBreak() {
return aBreak; return aBreak;
} }
/* (non-Javadoc) /* (non-Javadoc)
* @see java.lang.Object#hashCode() * @see java.lang.Object#hashCode()
*/ */
@Override @Override
public int hashCode() { public int hashCode() {
final int prime = 31; final int prime = 31;
int result = 1; int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode()); result = prime * result + ((id == null) ? 0 : id.hashCode());
result = prime * result + ((type == null) ? 0 : type.hashCode()); result = prime * result + ((type == null) ? 0 : type.hashCode());
return result; return result;
} }
/** /**
* Two vehicles are equal if they have the same id and if their types are equal. * Two vehicles are equal if they have the same id and if their types are equal.
*/ */
@Override @Override
public boolean equals(Object obj) { public boolean equals(Object obj) {
if (this == obj) if (this == obj)
return true; return true;
if (obj == null) if (obj == null)
return false; return false;
if (getClass() != obj.getClass()) if (getClass() != obj.getClass())
return false; return false;
VehicleImpl other = (VehicleImpl) obj; VehicleImpl other = (VehicleImpl) obj;
if (id == null) { if (id == null) {
if (other.id != null) if (other.id != null)
return false; return false;
} else if (!id.equals(other.id)) } else if (!id.equals(other.id))
return false; return false;
if (type == null) { if (type == null) {
if (other.type != null) if (other.type != null)
return false; return false;
} else if (!type.equals(other.type)) } else if (!type.equals(other.type))
return false; return false;
return true; return true;
} }
} }

View file

@ -36,7 +36,6 @@ public class VehicleTypeImpl implements VehicleType {
public static class VehicleCostParams { public static class VehicleCostParams {
public static VehicleTypeImpl.VehicleCostParams newInstance(double fix, double perTimeUnit, double perDistanceUnit) { public static VehicleTypeImpl.VehicleCostParams newInstance(double fix, double perTimeUnit, double perDistanceUnit) {
return new VehicleCostParams(fix, perTimeUnit, perDistanceUnit); return new VehicleCostParams(fix, perTimeUnit, perDistanceUnit);
} }

View file

@ -171,7 +171,7 @@ public class RefuseCollectionWithCostsHigherThanTimesAndFiniteFleet_IT {
*/ */
Service service = Service.Builder.newInstance(lineTokens[0]).addSizeDimension(0, Integer.parseInt(lineTokens[1])) Service service = Service.Builder.newInstance(lineTokens[0]).addSizeDimension(0, Integer.parseInt(lineTokens[1]))
.setLocation(Location.newInstance(lineTokens[0])).build(); .setLocation(Location.newInstance(lineTokens[0])).build();
/* /*
* and add it to problem * and add it to problem
*/ */
vrpBuilder.addJob(service); vrpBuilder.addJob(service);

View file

@ -171,7 +171,7 @@ public class RefuseCollectionWithCostsHigherThanTimesAndFiniteFleet_withTimeAndD
*/ */
Service service = Service.Builder.newInstance(lineTokens[0]).addSizeDimension(0, Integer.parseInt(lineTokens[1])) Service service = Service.Builder.newInstance(lineTokens[0]).addSizeDimension(0, Integer.parseInt(lineTokens[1]))
.setLocation(Location.newInstance(lineTokens[0])).build(); .setLocation(Location.newInstance(lineTokens[0])).build();
/* /*
* and add it to problem * and add it to problem
*/ */
vrpBuilder.addJob(service); vrpBuilder.addJob(service);

View file

@ -118,7 +118,7 @@ public class RefuseCollection_IT {
* create cost-matrix * create cost-matrix
*/ */
VehicleRoutingTransportCostsMatrix.Builder matrixBuilder = VehicleRoutingTransportCostsMatrix.Builder.newInstance(true); VehicleRoutingTransportCostsMatrix.Builder matrixBuilder = VehicleRoutingTransportCostsMatrix.Builder.newInstance(true);
/* /*
* read demand quantities * read demand quantities
*/ */
readDemandQuantitiesAsServices(vrpBuilder); readDemandQuantitiesAsServices(vrpBuilder);

View file

@ -196,7 +196,7 @@ public class JspritTest {
VehicleImpl v = VehicleImpl.Builder.newInstance("v").setStartLocation(Location.newInstance(0, 0)).build(); VehicleImpl v = VehicleImpl.Builder.newInstance("v").setStartLocation(Location.newInstance(0, 0)).build();
VehicleRoutingProblem vrp = VehicleRoutingProblem.Builder.newInstance().addJob(s4).addJob(s3).addVehicle(v).addJob(s2).addJob(s).build(); VehicleRoutingProblem vrp = VehicleRoutingProblem.Builder.newInstance().addJob(s4).addJob(s3).addVehicle(v).addJob(s2).addJob(s).build();
VehicleRoutingAlgorithm vra = Jsprit.Builder.newInstance(vrp).setProperty(Jsprit.Parameter.THREADS,"4").buildAlgorithm(); VehicleRoutingAlgorithm vra = Jsprit.Builder.newInstance(vrp).setProperty(Jsprit.Parameter.THREADS, "4").buildAlgorithm();
vra.setMaxIterations(100); vra.setMaxIterations(100);
final List<String> firstRecord = new ArrayList<String>(); final List<String> firstRecord = new ArrayList<String>();
vra.addListener(new StrategySelectedListener() { vra.addListener(new StrategySelectedListener() {
@ -210,7 +210,7 @@ public class JspritTest {
vra.searchSolutions(); vra.searchSolutions();
RandomNumberGeneration.reset(); RandomNumberGeneration.reset();
VehicleRoutingAlgorithm second = Jsprit.Builder.newInstance(vrp).setProperty(Jsprit.Parameter.THREADS,"2").buildAlgorithm(); VehicleRoutingAlgorithm second = Jsprit.Builder.newInstance(vrp).setProperty(Jsprit.Parameter.THREADS, "2").buildAlgorithm();
second.setMaxIterations(100); second.setMaxIterations(100);
final List<String> secondRecord = new ArrayList<String>(); final List<String> secondRecord = new ArrayList<String>();
second.addListener(new StrategySelectedListener() { second.addListener(new StrategySelectedListener() {
@ -242,7 +242,7 @@ public class JspritTest {
VehicleImpl v = VehicleImpl.Builder.newInstance("v").setStartLocation(Location.newInstance(0, 0)).build(); VehicleImpl v = VehicleImpl.Builder.newInstance("v").setStartLocation(Location.newInstance(0, 0)).build();
VehicleRoutingProblem vrp = VehicleRoutingProblem.Builder.newInstance().addJob(s4).addJob(s3).addVehicle(v).addJob(s2).addJob(s).build(); VehicleRoutingProblem vrp = VehicleRoutingProblem.Builder.newInstance().addJob(s4).addJob(s3).addVehicle(v).addJob(s2).addJob(s).build();
VehicleRoutingAlgorithm vra = Jsprit.Builder.newInstance(vrp) VehicleRoutingAlgorithm vra = Jsprit.Builder.newInstance(vrp)
.setProperty(Jsprit.Strategy.WORST_REGRET,"0.") .setProperty(Jsprit.Strategy.WORST_REGRET, "0.")
.setProperty(Jsprit.Strategy.WORST_BEST, "0.") .setProperty(Jsprit.Strategy.WORST_BEST, "0.")
.setProperty(Jsprit.Parameter.THREADS, "2").buildAlgorithm(); .setProperty(Jsprit.Parameter.THREADS, "2").buildAlgorithm();
vra.setMaxIterations(100); vra.setMaxIterations(100);
@ -410,7 +410,7 @@ public class JspritTest {
VehicleRoutingProblem vrp = VehicleRoutingProblem.Builder.newInstance().setFleetSize(VehicleRoutingProblem.FleetSize.FINITE).addJob(s4).addJob(s3).addVehicle(v).addJob(s2).addJob(s).build(); VehicleRoutingProblem vrp = VehicleRoutingProblem.Builder.newInstance().setFleetSize(VehicleRoutingProblem.FleetSize.FINITE).addJob(s4).addJob(s3).addVehicle(v).addJob(s2).addJob(s).build();
VehicleRoutingAlgorithm vra = Jsprit.Builder.newInstance(vrp) VehicleRoutingAlgorithm vra = Jsprit.Builder.newInstance(vrp)
.setProperty(Jsprit.Strategy.WORST_REGRET,"0.") .setProperty(Jsprit.Strategy.WORST_REGRET, "0.")
.setProperty(Jsprit.Strategy.WORST_BEST, "0.") .setProperty(Jsprit.Strategy.WORST_BEST, "0.")
.setProperty(Jsprit.Parameter.THREADS, "4").buildAlgorithm(); .setProperty(Jsprit.Parameter.THREADS, "4").buildAlgorithm();
vra.setMaxIterations(100); vra.setMaxIterations(100);
@ -427,7 +427,7 @@ public class JspritTest {
vra.searchSolutions(); vra.searchSolutions();
VehicleRoutingAlgorithm second = Jsprit.Builder.newInstance(vrp) VehicleRoutingAlgorithm second = Jsprit.Builder.newInstance(vrp)
.setProperty(Jsprit.Strategy.WORST_REGRET,"0.") .setProperty(Jsprit.Strategy.WORST_REGRET, "0.")
.setProperty(Jsprit.Strategy.WORST_BEST, "0.") .setProperty(Jsprit.Strategy.WORST_BEST, "0.")
.setProperty(Jsprit.Parameter.THREADS, "5").buildAlgorithm(); .setProperty(Jsprit.Parameter.THREADS, "5").buildAlgorithm();
second.setMaxIterations(100); second.setMaxIterations(100);
@ -460,11 +460,11 @@ public class JspritTest {
} }
@Test @Test
public void compare(){ public void compare() {
String s1 = "s2234"; String s1 = "s2234";
String s2 = "s1"; String s2 = "s1";
int c = s1.compareTo(s2); int c = s1.compareTo(s2);
Assert.assertEquals(1,c); Assert.assertEquals(1, c);
} }

View file

@ -411,7 +411,7 @@ public class TestLocalActivityInsertionCostsCalculator {
/* /*
activity start time delay at next act = start-time-old - start-time-new is always bigger than subsequent waiting time savings 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 old = 10 + 30 + 10 = 50
new = 80 + 0 - 10 - min{80,40} = 30 new = 80 + 0 - 10 - min{80,40} = 30
*/ */

View file

@ -118,7 +118,7 @@ public class TestMixedServiceAndShipmentsProblemOnRouteLevel {
/* /*
* build deliveries, (implicitly picked up in the depot) * build deliveries, (implicitly picked up in the depot)
* 1: (4,8) * 1: (4,8)
* 2: (4,12) * 2: (4,12)
* 3: (16,8) * 3: (16,8)

View file

@ -21,10 +21,10 @@ import java.util.List;
public class RuinBreakTest { public class RuinBreakTest {
@Test @Test
public void itShouldRuinBreaks(){ public void itShouldRuinBreaks() {
Break aBreak = Break.Builder.newInstance("break").build(); Break aBreak = Break.Builder.newInstance("break").build();
VehicleImpl v = VehicleImpl.Builder.newInstance("v").setStartLocation(Location.newInstance("loc")) VehicleImpl v = VehicleImpl.Builder.newInstance("v").setStartLocation(Location.newInstance("loc"))
.setBreak(aBreak).build(); .setBreak(aBreak).build();
VehicleRoutingProblem vrp = VehicleRoutingProblem.Builder.newInstance().setFleetSize(VehicleRoutingProblem.FleetSize.FINITE).addVehicle(v).build(); VehicleRoutingProblem vrp = VehicleRoutingProblem.Builder.newInstance().setFleetSize(VehicleRoutingProblem.FleetSize.FINITE).addVehicle(v).build();
VehicleRoute route = VehicleRoute.Builder.newInstance(v).setJobActivityFactory(vrp.getJobActivityFactory()).addService(aBreak).build(); VehicleRoute route = VehicleRoute.Builder.newInstance(v).setJobActivityFactory(vrp.getJobActivityFactory()).addService(aBreak).build();
TourActivity tourActivity = route.getActivities().get(0); TourActivity tourActivity = route.getActivities().get(0);
@ -32,8 +32,8 @@ public class RuinBreakTest {
Assert.assertTrue(tourActivity instanceof BreakActivity); Assert.assertTrue(tourActivity instanceof BreakActivity);
RuinBreaks ruinBreaks = new RuinBreaks(); RuinBreaks ruinBreaks = new RuinBreaks();
List<Job> unassigned = new ArrayList<Job>(); List<Job> unassigned = new ArrayList<Job>();
ruinBreaks.ruinEnds(Arrays.asList(route),unassigned); ruinBreaks.ruinEnds(Arrays.asList(route), unassigned);
Assert.assertEquals(1,unassigned.size()); Assert.assertEquals(1, unassigned.size());
Assert.assertEquals(aBreak,unassigned.get(0)); Assert.assertEquals(aBreak, unassigned.get(0));
} }
} }

View file

@ -50,33 +50,33 @@ public class RuinClustersTest {
} }
@Test @Test
public void itShouldRuinTwoObviousClustersEvenThereAreBreaks(){ public void itShouldRuinTwoObviousClustersEvenThereAreBreaks() {
Service s0 = Service.Builder.newInstance("s0").setLocation(Location.newInstance(9, 0)).build(); Service s0 = Service.Builder.newInstance("s0").setLocation(Location.newInstance(9, 0)).build();
Service s1 = Service.Builder.newInstance("s1").setLocation(Location.newInstance(9, 1)).build(); Service s1 = Service.Builder.newInstance("s1").setLocation(Location.newInstance(9, 1)).build();
Service s2 = Service.Builder.newInstance("s2").setLocation(Location.newInstance(9,10)).build(); Service s2 = Service.Builder.newInstance("s2").setLocation(Location.newInstance(9, 10)).build();
Service s3 = Service.Builder.newInstance("s3").setLocation(Location.newInstance(9,9)).build(); Service s3 = Service.Builder.newInstance("s3").setLocation(Location.newInstance(9, 9)).build();
Service s4 = Service.Builder.newInstance("s4").setLocation(Location.newInstance(9,16)).build(); Service s4 = Service.Builder.newInstance("s4").setLocation(Location.newInstance(9, 16)).build();
Service s5 = Service.Builder.newInstance("s5").setLocation(Location.newInstance(9,17)).build(); Service s5 = Service.Builder.newInstance("s5").setLocation(Location.newInstance(9, 17)).build();
Service s6 = Service.Builder.newInstance("s6").setLocation(Location.newInstance(9,15.5)).build(); Service s6 = Service.Builder.newInstance("s6").setLocation(Location.newInstance(9, 15.5)).build();
Service s7 = Service.Builder.newInstance("s7").setLocation(Location.newInstance(9,30)).build(); Service s7 = Service.Builder.newInstance("s7").setLocation(Location.newInstance(9, 30)).build();
VehicleImpl v = VehicleImpl.Builder.newInstance("v") VehicleImpl v = VehicleImpl.Builder.newInstance("v")
.setBreak((Break) Break.Builder.newInstance("break").setServiceTime(10).setTimeWindow(TimeWindow.newInstance(20,30)).build()) .setBreak((Break) Break.Builder.newInstance("break").setServiceTime(10).setTimeWindow(TimeWindow.newInstance(20, 30)).build())
.setStartLocation(Location.newInstance(0, 0)).build(); .setStartLocation(Location.newInstance(0, 0)).build();
VehicleRoutingProblem vrp = VehicleRoutingProblem.Builder.newInstance().addJob(s1).addJob(s2).setFleetSize(VehicleRoutingProblem.FleetSize.FINITE) VehicleRoutingProblem vrp = VehicleRoutingProblem.Builder.newInstance().addJob(s1).addJob(s2).setFleetSize(VehicleRoutingProblem.FleetSize.FINITE)
.addJob(s6).addJob(s7).addJob(s0).addJob(s3).addJob(s4).addJob(s5).addVehicle(v).build(); .addJob(s6).addJob(s7).addJob(s0).addJob(s3).addJob(s4).addJob(s5).addVehicle(v).build();
VehicleRoute vr1 = VehicleRoute.Builder.newInstance(v).addService(s0).addService(v.getBreak()).addService(s1).addService(s2).addService(s3).setJobActivityFactory(vrp.getJobActivityFactory()).build(); VehicleRoute vr1 = VehicleRoute.Builder.newInstance(v).addService(s0).addService(v.getBreak()).addService(s1).addService(s2).addService(s3).setJobActivityFactory(vrp.getJobActivityFactory()).build();
((BreakActivity)vr1.getActivities().get(1)).setLocation(Location.newInstance(9,1)); ((BreakActivity) vr1.getActivities().get(1)).setLocation(Location.newInstance(9, 1));
VehicleRoute vr2 = VehicleRoute.Builder.newInstance(v) VehicleRoute vr2 = VehicleRoute.Builder.newInstance(v)
.addService(s6).addService(s7).addService(s4).addService(s5).setJobActivityFactory(vrp.getJobActivityFactory()).build(); .addService(s6).addService(s7).addService(s4).addService(s5).setJobActivityFactory(vrp.getJobActivityFactory()).build();
JobNeighborhoods n = new JobNeighborhoodsFactory().createNeighborhoods(vrp,new AvgServiceAndShipmentDistance(vrp.getTransportCosts())); JobNeighborhoods n = new JobNeighborhoodsFactory().createNeighborhoods(vrp, new AvgServiceAndShipmentDistance(vrp.getTransportCosts()));
n.initialise(); n.initialise();
RuinClusters rc = new RuinClusters(vrp,5,n); RuinClusters rc = new RuinClusters(vrp, 5, n);
Collection<Job> ruined = rc.ruinRoutes(Arrays.asList(vr1,vr2)); Collection<Job> ruined = rc.ruinRoutes(Arrays.asList(vr1, vr2));
Assert.assertEquals(5,ruined.size()); Assert.assertEquals(5, ruined.size());
} }
} }

View file

@ -11,7 +11,7 @@
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details. * Lesser General Public License for more details.
* *
* You should have received a copy of the GNU Lesser General Public * 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/>. * License along with this library. If not, see <http://www.gnu.org/licenses/>.
******************************************************************************/ ******************************************************************************/
package jsprit.core.problem.solution.route.activity; package jsprit.core.problem.solution.route.activity;
@ -26,81 +26,81 @@ import static org.junit.Assert.*;
public class BreakActivityTest { public class BreakActivityTest {
private Break service;
private BreakActivity serviceActivity;
@Before
public void doBefore(){
service = (Break) Break.Builder.newInstance("service")
.setTimeWindow(TimeWindow.newInstance(1., 2.)).setServiceTime(3).build();
serviceActivity = BreakActivity.newInstance(service);
}
@Test
public void whenCallingCapacity_itShouldReturnCorrectCapacity(){
assertEquals(0,serviceActivity.getSize().get(0));
}
@Test private Break service;
public void hasVariableLocationShouldBeTrue(){
Break aBreak = (Break) serviceActivity.getJob();
assertTrue(aBreak.hasVariableLocation());
}
private BreakActivity serviceActivity;
@Test
public void whenStartIsIniWithEarliestStart_itShouldBeSetCorrectly(){
assertEquals(1.,serviceActivity.getTheoreticalEarliestOperationStartTime(),0.01);
}
@Test
public void whenStartIsIniWithLatestStart_itShouldBeSetCorrectly(){
assertEquals(2.,serviceActivity.getTheoreticalLatestOperationStartTime(),0.01);
}
@Test
public void whenSettingArrTime_itShouldBeSetCorrectly(){
serviceActivity.setArrTime(4.0);
assertEquals(4.,serviceActivity.getArrTime(),0.01);
}
@Test
public void whenSettingEndTime_itShouldBeSetCorrectly(){
serviceActivity.setEndTime(5.0);
assertEquals(5.,serviceActivity.getEndTime(),0.01);
}
@Test @Before
public void whenCopyingStart_itShouldBeDoneCorrectly(){ public void doBefore() {
BreakActivity copy = (BreakActivity) serviceActivity.duplicate(); service = (Break) Break.Builder.newInstance("service")
assertEquals(1.,copy.getTheoreticalEarliestOperationStartTime(),0.01); .setTimeWindow(TimeWindow.newInstance(1., 2.)).setServiceTime(3).build();
assertEquals(2.,copy.getTheoreticalLatestOperationStartTime(),0.01); serviceActivity = BreakActivity.newInstance(service);
assertTrue(copy!=serviceActivity); }
}
@Test
@Test public void whenCallingCapacity_itShouldReturnCorrectCapacity() {
public void whenTwoDeliveriesHaveTheSameUnderlyingJob_theyAreEqual(){ assertEquals(0, serviceActivity.getSize().get(0));
Service s1 = Service.Builder.newInstance("s").setLocation(Location.newInstance("loc")).build(); }
Service s2 = Service.Builder.newInstance("s").setLocation(Location.newInstance("loc")).build();
@Test
ServiceActivity d1 = ServiceActivity.newInstance(s1); public void hasVariableLocationShouldBeTrue() {
ServiceActivity d2 = ServiceActivity.newInstance(s2); Break aBreak = (Break) serviceActivity.getJob();
assertTrue(aBreak.hasVariableLocation());
assertTrue(d1.equals(d2)); }
}
@Test @Test
public void whenTwoDeliveriesHaveTheDifferentUnderlyingJob_theyAreNotEqual(){ public void whenStartIsIniWithEarliestStart_itShouldBeSetCorrectly() {
Service s1 = Service.Builder.newInstance("s").setLocation(Location.newInstance("loc")).build(); assertEquals(1., serviceActivity.getTheoreticalEarliestOperationStartTime(), 0.01);
Service s2 = Service.Builder.newInstance("s1").setLocation(Location.newInstance("loc")).build(); }
ServiceActivity d1 = ServiceActivity.newInstance(s1); @Test
ServiceActivity d2 = ServiceActivity.newInstance(s2); public void whenStartIsIniWithLatestStart_itShouldBeSetCorrectly() {
assertEquals(2., serviceActivity.getTheoreticalLatestOperationStartTime(), 0.01);
assertFalse(d1.equals(d2)); }
}
@Test
public void whenSettingArrTime_itShouldBeSetCorrectly() {
serviceActivity.setArrTime(4.0);
assertEquals(4., serviceActivity.getArrTime(), 0.01);
}
@Test
public void whenSettingEndTime_itShouldBeSetCorrectly() {
serviceActivity.setEndTime(5.0);
assertEquals(5., serviceActivity.getEndTime(), 0.01);
}
@Test
public void whenCopyingStart_itShouldBeDoneCorrectly() {
BreakActivity copy = (BreakActivity) serviceActivity.duplicate();
assertEquals(1., copy.getTheoreticalEarliestOperationStartTime(), 0.01);
assertEquals(2., copy.getTheoreticalLatestOperationStartTime(), 0.01);
assertTrue(copy != serviceActivity);
}
@Test
public void whenTwoDeliveriesHaveTheSameUnderlyingJob_theyAreEqual() {
Service s1 = Service.Builder.newInstance("s").setLocation(Location.newInstance("loc")).build();
Service s2 = Service.Builder.newInstance("s").setLocation(Location.newInstance("loc")).build();
ServiceActivity d1 = ServiceActivity.newInstance(s1);
ServiceActivity d2 = ServiceActivity.newInstance(s2);
assertTrue(d1.equals(d2));
}
@Test
public void whenTwoDeliveriesHaveTheDifferentUnderlyingJob_theyAreNotEqual() {
Service s1 = Service.Builder.newInstance("s").setLocation(Location.newInstance("loc")).build();
Service s2 = Service.Builder.newInstance("s1").setLocation(Location.newInstance("loc")).build();
ServiceActivity d1 = ServiceActivity.newInstance(s1);
ServiceActivity d2 = ServiceActivity.newInstance(s2);
assertFalse(d1.equals(d2));
}
} }

View file

@ -30,27 +30,25 @@ import static org.junit.Assert.*;
public class VehicleImplTest { public class VehicleImplTest {
@Test(expected = IllegalStateException.class)
@Test(expected=IllegalStateException.class) public void whenVehicleIsBuiltWithoutSettingNeitherLocationNorCoord_itThrowsAnIllegalStateException() {
public void whenVehicleIsBuiltWithoutSettingNeitherLocationNorCoord_itThrowsAnIllegalStateException(){ @SuppressWarnings("unused")
@SuppressWarnings("unused") Vehicle v = VehicleImpl.Builder.newInstance("v").build();
Vehicle v = VehicleImpl.Builder.newInstance("v").build(); }
}
@Test @Test
public void whenAddingDriverBreak_itShouldBeAddedCorrectly(){ public void whenAddingDriverBreak_itShouldBeAddedCorrectly() {
VehicleTypeImpl type1 = VehicleTypeImpl.Builder.newInstance("type").build(); VehicleTypeImpl type1 = VehicleTypeImpl.Builder.newInstance("type").build();
Break aBreak = (Break) Break.Builder.newInstance("break").setTimeWindow(TimeWindow.newInstance(100, 200)).setServiceTime(30).build(); Break aBreak = (Break) Break.Builder.newInstance("break").setTimeWindow(TimeWindow.newInstance(100, 200)).setServiceTime(30).build();
Vehicle v = VehicleImpl.Builder.newInstance("v").setStartLocation(Location.newInstance("start")) Vehicle v = VehicleImpl.Builder.newInstance("v").setStartLocation(Location.newInstance("start"))
.setType(type1).setEndLocation(Location.newInstance("start")) .setType(type1).setEndLocation(Location.newInstance("start"))
.setBreak(aBreak).build(); .setBreak(aBreak).build();
assertNotNull(v.getBreak()); assertNotNull(v.getBreak());
assertEquals(100.,v.getBreak().getTimeWindow().getStart(),0.1); assertEquals(100., v.getBreak().getTimeWindow().getStart(), 0.1);
assertEquals(200.,v.getBreak().getTimeWindow().getEnd(),0.1); assertEquals(200., v.getBreak().getTimeWindow().getEnd(), 0.1);
assertEquals(30.,v.getBreak().getServiceDuration(),0.1); assertEquals(30., v.getBreak().getServiceDuration(), 0.1);
} }
@Test @Test

View file

@ -38,71 +38,70 @@ import java.util.Collection;
public class BreakExample { public class BreakExample {
public static void main(String[] args) {
public static void main(String[] args) {
/* /*
* get a vehicle type-builder and build a type with the typeId "vehicleType" and one capacity dimension, i.e. weight, and capacity dimension value of 2 * get a vehicle type-builder and build a type with the typeId "vehicleType" and one capacity dimension, i.e. weight, and capacity dimension value of 2
*/ */
final int WEIGHT_INDEX = 0; final int WEIGHT_INDEX = 0;
VehicleTypeImpl.Builder vehicleTypeBuilder = VehicleTypeImpl.Builder.newInstance("vehicleType") VehicleTypeImpl.Builder vehicleTypeBuilder = VehicleTypeImpl.Builder.newInstance("vehicleType")
.addCapacityDimension(WEIGHT_INDEX, 2).setCostPerWaitingTime(1.0); .addCapacityDimension(WEIGHT_INDEX, 2).setCostPerWaitingTime(1.0);
VehicleType vehicleType = vehicleTypeBuilder.build(); VehicleType vehicleType = vehicleTypeBuilder.build();
/* /*
* get a vehicle-builder and build a vehicle located at (10,10) with type "vehicleType" * get a vehicle-builder and build a vehicle located at (10,10) with type "vehicleType"
*/ */
Builder vehicleBuilder = Builder.newInstance("v1"); Builder vehicleBuilder = Builder.newInstance("v1");
vehicleBuilder.setStartLocation(Location.newInstance(10, 10)); vehicleBuilder.setStartLocation(Location.newInstance(10, 10));
Break myFirstBreak = Break.Builder.newInstance("myFirstBreak") Break myFirstBreak = Break.Builder.newInstance("myFirstBreak")
.setTimeWindow(TimeWindow.newInstance(10, 15)).setServiceTime(100).build(); .setTimeWindow(TimeWindow.newInstance(10, 15)).setServiceTime(100).build();
vehicleBuilder.setBreak(myFirstBreak); vehicleBuilder.setBreak(myFirstBreak);
vehicleBuilder.setType(vehicleType); vehicleBuilder.setType(vehicleType);
VehicleImpl vehicle = vehicleBuilder.build(); VehicleImpl vehicle = vehicleBuilder.build();
VehicleImpl v2 = VehicleImpl.Builder.newInstance("v2").setStartLocation(Location.newInstance(0, 10)).setType(vehicleType) VehicleImpl v2 = VehicleImpl.Builder.newInstance("v2").setStartLocation(Location.newInstance(0, 10)).setType(vehicleType)
.setBreak((Break) Break.Builder.newInstance("mySecondBreak").setTimeWindow(TimeWindow.newInstance(5,10)).setServiceTime(10).build()).build(); .setBreak((Break) Break.Builder.newInstance("mySecondBreak").setTimeWindow(TimeWindow.newInstance(5, 10)).setServiceTime(10).build()).build();
/* /*
* build services at the required locations, each with a capacity-demand of 1. * build services at the required locations, each with a capacity-demand of 1.
*/ */
Service service1 = Service.Builder.newInstance("1").addSizeDimension(WEIGHT_INDEX, 1).setLocation(Location.newInstance(5, 7)).build(); Service service1 = Service.Builder.newInstance("1").addSizeDimension(WEIGHT_INDEX, 1).setLocation(Location.newInstance(5, 7)).build();
Service service2 = Service.Builder.newInstance("2").addSizeDimension(WEIGHT_INDEX, 1).setLocation(Location.newInstance(5, 13)).build(); Service service2 = Service.Builder.newInstance("2").addSizeDimension(WEIGHT_INDEX, 1).setLocation(Location.newInstance(5, 13)).build();
Service service3 = Service.Builder.newInstance("3").addSizeDimension(WEIGHT_INDEX, 1).setLocation(Location.newInstance(15, 7)).build(); Service service3 = Service.Builder.newInstance("3").addSizeDimension(WEIGHT_INDEX, 1).setLocation(Location.newInstance(15, 7)).build();
Service service4 = Service.Builder.newInstance("4").addSizeDimension(WEIGHT_INDEX, 1).setLocation(Location.newInstance(15, 13)).build(); Service service4 = Service.Builder.newInstance("4").addSizeDimension(WEIGHT_INDEX, 1).setLocation(Location.newInstance(15, 13)).build();
VehicleRoutingProblem.Builder vrpBuilder = VehicleRoutingProblem.Builder.newInstance(); VehicleRoutingProblem.Builder vrpBuilder = VehicleRoutingProblem.Builder.newInstance();
vrpBuilder.addVehicle(vehicle); vrpBuilder.addVehicle(vehicle);
vrpBuilder.addJob(service1).addJob(service2).addJob(service3).addJob(service4).addVehicle(v2); vrpBuilder.addJob(service1).addJob(service2).addJob(service3).addJob(service4).addVehicle(v2);
vrpBuilder.setFleetSize(VehicleRoutingProblem.FleetSize.FINITE); vrpBuilder.setFleetSize(VehicleRoutingProblem.FleetSize.FINITE);
VehicleRoutingProblem problem = vrpBuilder.build(); VehicleRoutingProblem problem = vrpBuilder.build();
/* /*
* get the algorithm out-of-the-box. * get the algorithm out-of-the-box.
*/ */
VehicleRoutingAlgorithm algorithm = Jsprit.Builder.newInstance(problem) VehicleRoutingAlgorithm algorithm = Jsprit.Builder.newInstance(problem)
.setProperty(Jsprit.Strategy.CLUSTER_REGRET,"0.") .setProperty(Jsprit.Strategy.CLUSTER_REGRET, "0.")
.setProperty(Jsprit.Strategy.CLUSTER_BEST,"0.").buildAlgorithm(); .setProperty(Jsprit.Strategy.CLUSTER_BEST, "0.").buildAlgorithm();
/* /*
* and search a solution * and search a solution
*/ */
Collection<VehicleRoutingProblemSolution> solutions = algorithm.searchSolutions(); Collection<VehicleRoutingProblemSolution> solutions = algorithm.searchSolutions();
/* /*
* get the best * get the best
*/ */
VehicleRoutingProblemSolution bestSolution = Solutions.bestOf(solutions); VehicleRoutingProblemSolution bestSolution = Solutions.bestOf(solutions);
SolutionPrinter.print(problem, bestSolution, SolutionPrinter.Print.VERBOSE); SolutionPrinter.print(problem, bestSolution, SolutionPrinter.Print.VERBOSE);
/* /*
* plot * plot
*/ */
new Plotter(problem,bestSolution).plot("output/plot","breaks"); new Plotter(problem, bestSolution).plot("output/plot", "breaks");
} }
} }

View file

@ -96,7 +96,7 @@ public class ConfigureAlgorithmInCodeInsteadOfPerXml {
SolutionPrinter.print(bestSolution); SolutionPrinter.print(bestSolution);
/* /*
* plot * plot
*/ */
new Plotter(problem, bestSolution).plot("output/solution.png", "solution"); new Plotter(problem, bestSolution).plot("output/solution.png", "solution");
} }

View file

@ -131,7 +131,7 @@ public class EnRoutePickupAndDeliveryWithMultipleDepotsAndOpenRoutesExample {
Collection<VehicleRoutingProblemSolution> solutions = algorithm.searchSolutions(); Collection<VehicleRoutingProblemSolution> solutions = algorithm.searchSolutions();
/* /*
* get the best * get the best
*/ */
VehicleRoutingProblemSolution bestSolution = Solutions.bestOf(solutions); VehicleRoutingProblemSolution bestSolution = Solutions.bestOf(solutions);

View file

@ -96,7 +96,7 @@ public class MultipleDepotExample {
// SolutionPlotter.plotVrpAsPNG(vrp, "output/problem01.png", "p01"); // SolutionPlotter.plotVrpAsPNG(vrp, "output/problem01.png", "p01");
/* /*
* solve the problem * solve the problem
*/ */
VehicleRoutingAlgorithm vra = Jsprit.Builder.newInstance(vrp).setProperty(Jsprit.Parameter.THREADS, "5").buildAlgorithm(); VehicleRoutingAlgorithm vra = Jsprit.Builder.newInstance(vrp).setProperty(Jsprit.Parameter.THREADS, "5").buildAlgorithm();
vra.getAlgorithmListeners().addListener(new StopWatch(), Priority.HIGH); vra.getAlgorithmListeners().addListener(new StopWatch(), Priority.HIGH);

View file

@ -102,7 +102,7 @@ public class MultipleDepotExample2 {
// SolutionPlotter.plotVrpAsPNG(vrp, "output/problem08.png", "p08"); // SolutionPlotter.plotVrpAsPNG(vrp, "output/problem08.png", "p08");
/* /*
* solve the problem * solve the problem
*/ */
VehicleRoutingAlgorithm vra = Jsprit.Builder.newInstance(vrp).setProperty(Jsprit.Parameter.THREADS, "5").buildAlgorithm(); VehicleRoutingAlgorithm vra = Jsprit.Builder.newInstance(vrp).setProperty(Jsprit.Parameter.THREADS, "5").buildAlgorithm();
vra.setMaxIterations(2000); vra.setMaxIterations(2000);

View file

@ -69,7 +69,7 @@ public class MultipleDepotWithInitialRoutesExample {
assert !vrp.getJobs().containsKey("44") : "strange. service 44 should not be part of the problem"; assert !vrp.getJobs().containsKey("44") : "strange. service 44 should not be part of the problem";
/* /*
* plot to see how the problem looks like * plot to see how the problem looks like
*/ */
new Plotter(vrp).setLabel(Label.ID).plot("output/cordeau01_problem_withInitialRoute.png", "c"); new Plotter(vrp).setLabel(Label.ID).plot("output/cordeau01_problem_withInitialRoute.png", "c");

View file

@ -79,7 +79,7 @@ public class PickupAndDeliveryExample {
Collection<VehicleRoutingProblemSolution> solutions = vra.searchSolutions(); Collection<VehicleRoutingProblemSolution> solutions = vra.searchSolutions();
/* /*
* Retrieve best solution. * Retrieve best solution.
*/ */
VehicleRoutingProblemSolution solution = new SelectBest().selectSolution(solutions); VehicleRoutingProblemSolution solution = new SelectBest().selectSolution(solutions);

View file

@ -83,7 +83,7 @@ public class PickupAndDeliveryExample2 {
VehicleRoutingProblemSolution solution = new SelectBest().selectSolution(solutions); VehicleRoutingProblemSolution solution = new SelectBest().selectSolution(solutions);
/* /*
* print solution * print solution
*/ */
SolutionPrinter.print(solution); SolutionPrinter.print(solution);

View file

@ -76,7 +76,7 @@ public class PickupAndDeliveryOpenExample {
Collection<VehicleRoutingProblemSolution> solutions = vra.searchSolutions(); Collection<VehicleRoutingProblemSolution> solutions = vra.searchSolutions();
/* /*
* Retrieve best solution. * Retrieve best solution.
*/ */
VehicleRoutingProblemSolution solution = new SelectBest().selectSolution(solutions); VehicleRoutingProblemSolution solution = new SelectBest().selectSolution(solutions);

View file

@ -113,7 +113,7 @@ public class RefuseCollectionExample {
* build service * build service
*/ */
Service service = Service.Builder.newInstance(lineTokens[0]).addSizeDimension(0, Integer.parseInt(lineTokens[1])).setLocation(Location.newInstance(lineTokens[0])).build(); Service service = Service.Builder.newInstance(lineTokens[0]).addSizeDimension(0, Integer.parseInt(lineTokens[1])).setLocation(Location.newInstance(lineTokens[0])).build();
/* /*
* and add it to problem * and add it to problem
*/ */
vrpBuilder.addJob(service); vrpBuilder.addJob(service);

View file

@ -115,7 +115,7 @@ public class RefuseCollectionWithFastMatrixExample {
.addSizeDimension(0, Integer.parseInt(lineTokens[1])) .addSizeDimension(0, Integer.parseInt(lineTokens[1]))
.setLocation(Location.Builder.newInstance().setIndex(Integer.parseInt(lineTokens[0])).build()) .setLocation(Location.Builder.newInstance().setIndex(Integer.parseInt(lineTokens[0])).build())
.build(); .build();
/* /*
* and add it to problem * and add it to problem
*/ */
vrpBuilder.addJob(service); vrpBuilder.addJob(service);

View file

@ -114,7 +114,7 @@ public class ServicePickupsWithMultipleDepotsExample {
VehicleRoutingProblemSolution bestSolution = Solutions.bestOf(solutions); VehicleRoutingProblemSolution bestSolution = Solutions.bestOf(solutions);
/* /*
* write out problem and solution to xml-file * write out problem and solution to xml-file
*/ */
new VrpXMLWriter(problem, solutions).write("output/shipment-problem-with-solution.xml"); new VrpXMLWriter(problem, solutions).write("output/shipment-problem-with-solution.xml");

View file

@ -97,7 +97,7 @@ public class SimpleDepotBoundedPickupAndDeliveryExample {
SolutionPrinter.print(bestSolution); SolutionPrinter.print(bestSolution);
/* /*
* plot * plot
*/ */
Plotter plotter = new Plotter(problem, bestSolution); Plotter plotter = new Plotter(problem, bestSolution);
plotter.setLabel(Label.SIZE); plotter.setLabel(Label.SIZE);

View file

@ -98,7 +98,7 @@ public class SimpleEnRoutePickupAndDeliveryExample {
VehicleRoutingProblemSolution bestSolution = Solutions.bestOf(solutions); VehicleRoutingProblemSolution bestSolution = Solutions.bestOf(solutions);
/* /*
* write out problem and solution to xml-file * write out problem and solution to xml-file
*/ */
new VrpXMLWriter(problem, solutions).write("output/shipment-problem-with-solution.xml"); new VrpXMLWriter(problem, solutions).write("output/shipment-problem-with-solution.xml");

View file

@ -98,7 +98,7 @@ public class SimpleEnRoutePickupAndDeliveryOpenRoutesExample {
VehicleRoutingProblemSolution bestSolution = Solutions.bestOf(solutions); VehicleRoutingProblemSolution bestSolution = Solutions.bestOf(solutions);
/* /*
* write out problem and solution to xml-file * write out problem and solution to xml-file
*/ */
new VrpXMLWriter(problem, solutions).write("output/shipment-problem-with-solution.xml"); new VrpXMLWriter(problem, solutions).write("output/shipment-problem-with-solution.xml");

View file

@ -109,7 +109,7 @@ public class SimpleEnRoutePickupAndDeliveryWithDepotBoundedDeliveriesExample {
VehicleRoutingAlgorithm algorithm = vraBuilder.build(); VehicleRoutingAlgorithm algorithm = vraBuilder.build();
/* /*
* and search a solution * and search a solution
*/ */
Collection<VehicleRoutingProblemSolution> solutions = algorithm.searchSolutions(); Collection<VehicleRoutingProblemSolution> solutions = algorithm.searchSolutions();

View file

@ -102,7 +102,7 @@ public class SimpleExample {
SolutionPrinter.print(problem, bestSolution, SolutionPrinter.Print.VERBOSE); SolutionPrinter.print(problem, bestSolution, SolutionPrinter.Print.VERBOSE);
/* /*
* plot * plot
*/ */
// SolutionPlotter.plotSolutionAsPNG(problem, bestSolution, "output/solution.png", "solution"); // SolutionPlotter.plotSolutionAsPNG(problem, bestSolution, "output/solution.png", "solution");

View file

@ -96,7 +96,7 @@ public class SimpleExampleOpenRoutes {
SolutionPrinter.print(bestSolution); SolutionPrinter.print(bestSolution);
/* /*
* plot * plot
*/ */
new Plotter(problem, bestSolution).plot("output/solution.png", "solution"); new Plotter(problem, bestSolution).plot("output/solution.png", "solution");

View file

@ -124,7 +124,7 @@ public class SimpleExampleWithSkills {
SolutionPrinter.print(problem, bestSolution, SolutionPrinter.Print.VERBOSE); SolutionPrinter.print(problem, bestSolution, SolutionPrinter.Print.VERBOSE);
/* /*
* plot * plot
*/ */
// SolutionPlotter.plotSolutionAsPNG(problem, bestSolution, "output/solution.png", "solution"); // SolutionPlotter.plotSolutionAsPNG(problem, bestSolution, "output/solution.png", "solution");

View file

@ -80,7 +80,7 @@ public class SolomonExample {
/* /*
* print solution * print solution
*/ */
SolutionPrinter.print(vrp, solution, SolutionPrinter.Print.VERBOSE); SolutionPrinter.print(vrp, solution, SolutionPrinter.Print.VERBOSE);

View file

@ -84,7 +84,7 @@ public class SolomonExampleWithSpecifiedVehicleEndLocations {
Collection<VehicleRoutingProblemSolution> solutions = vra.searchSolutions(); Collection<VehicleRoutingProblemSolution> solutions = vra.searchSolutions();
/* /*
* Retrieve best solution. * Retrieve best solution.
*/ */
VehicleRoutingProblemSolution solution = new SelectBest().selectSolution(solutions); VehicleRoutingProblemSolution solution = new SelectBest().selectSolution(solutions);

View file

@ -84,7 +84,7 @@ public class SolomonExampleWithSpecifiedVehicleEndLocationsWithoutTWs {
Collection<VehicleRoutingProblemSolution> solutions = vra.searchSolutions(); Collection<VehicleRoutingProblemSolution> solutions = vra.searchSolutions();
/* /*
* Retrieve best solution. * Retrieve best solution.
*/ */
VehicleRoutingProblemSolution solution = new SelectBest().selectSolution(solutions); VehicleRoutingProblemSolution solution = new SelectBest().selectSolution(solutions);

View file

@ -76,7 +76,7 @@ public class SolomonOpenExample {
Collection<VehicleRoutingProblemSolution> solutions = vra.searchSolutions(); Collection<VehicleRoutingProblemSolution> solutions = vra.searchSolutions();
/* /*
* Retrieve best solution. * Retrieve best solution.
*/ */
VehicleRoutingProblemSolution solution = new SelectBest().selectSolution(solutions); VehicleRoutingProblemSolution solution = new SelectBest().selectSolution(solutions);

View file

@ -69,7 +69,7 @@ public class SolomonR101Example {
// vra.setPrematureBreak(100); // vra.setPrematureBreak(100);
vra.getAlgorithmListeners().addListener(new AlgorithmSearchProgressChartListener("output/sol_progress.png")); vra.getAlgorithmListeners().addListener(new AlgorithmSearchProgressChartListener("output/sol_progress.png"));
/* /*
* Solve the problem. * Solve the problem.
* *
* *
*/ */

View file

@ -87,7 +87,7 @@ public class SolomonWithRegretInsertionExample {
/* /*
* print solution * print solution
*/ */
SolutionPrinter.print(vrp, solution, SolutionPrinter.Print.VERBOSE); SolutionPrinter.print(vrp, solution, SolutionPrinter.Print.VERBOSE);

View file

@ -191,7 +191,7 @@ public class TransportOfDisabledPeople {
Collection<VehicleRoutingProblemSolution> solutions = algorithm.searchSolutions(); Collection<VehicleRoutingProblemSolution> solutions = algorithm.searchSolutions();
/* /*
* get the best * get the best
*/ */
VehicleRoutingProblemSolution bestSolution = Solutions.bestOf(solutions); VehicleRoutingProblemSolution bestSolution = Solutions.bestOf(solutions);

View file

@ -84,7 +84,7 @@ public class VRPWithBackhaulsExample {
Collection<VehicleRoutingProblemSolution> solutions = vra.searchSolutions(); Collection<VehicleRoutingProblemSolution> solutions = vra.searchSolutions();
/* /*
* Retrieve best solution. * Retrieve best solution.
*/ */
VehicleRoutingProblemSolution solution = new SelectBest().selectSolution(solutions); VehicleRoutingProblemSolution solution = new SelectBest().selectSolution(solutions);

View file

@ -110,7 +110,7 @@ public class VRPWithBackhaulsExample2 {
VehicleRoutingProblemSolution solution = new SelectBest().selectSolution(solutions); VehicleRoutingProblemSolution solution = new SelectBest().selectSolution(solutions);
/* /*
* print solution * print solution
*/ */
SolutionPrinter.print(solution); SolutionPrinter.print(solution);