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

@ -62,8 +62,8 @@ public final class InsertionInitialSolutionFactory implements InitialSolutionFac
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,9 +43,8 @@ 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);
@ -77,7 +76,7 @@ final class BreakInsertionCalculator implements JobInsertionCostsCalculator{
logger.debug("initialise " + this); logger.debug("initialise " + this);
} }
public void setJobActivityFactory(JobActivityFactory jobActivityFactory){ public void setJobActivityFactory(JobActivityFactory jobActivityFactory) {
this.activityFactory = jobActivityFactory; this.activityFactory = jobActivityFactory;
} }
@ -89,15 +88,14 @@ final class BreakInsertionCalculator implements JobInsertionCostsCalculator{
/** /**
* 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;
@ -108,7 +106,7 @@ final class BreakInsertionCalculator implements JobInsertionCostsCalculator{
/* /*
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();
} }
@ -134,16 +132,16 @@ final class BreakInsertionCalculator implements JobInsertionCostsCalculator{
int actIndex = 0; int actIndex = 0;
Iterator<TourActivity> activityIterator = currentRoute.getActivities().iterator(); Iterator<TourActivity> activityIterator = currentRoute.getActivities().iterator();
boolean tourEnd = false; boolean tourEnd = false;
while(!tourEnd){ while (!tourEnd) {
TourActivity nextAct; TourActivity nextAct;
if(activityIterator.hasNext()) nextAct = activityIterator.next(); if (activityIterator.hasNext()) nextAct = activityIterator.next();
else{ else {
nextAct = end; nextAct = end;
tourEnd = true; tourEnd = true;
} }
boolean breakThis = true; boolean breakThis = true;
List<Location> locations = Arrays.asList( prevAct.getLocation(), nextAct.getLocation()); List<Location> locations = Arrays.asList(prevAct.getLocation(), nextAct.getLocation());
for(Location location : locations) { for (Location location : locations) {
breakAct2Insert.setLocation(location); breakAct2Insert.setLocation(location);
ConstraintsStatus status = hardActivityLevelConstraint.fulfilled(insertionContext, prevAct, breakAct2Insert, nextAct, prevActStartTime); ConstraintsStatus status = hardActivityLevelConstraint.fulfilled(insertionContext, prevAct, breakAct2Insert, nextAct, prevActStartTime);
if (status.equals(ConstraintsStatus.FULFILLED)) { if (status.equals(ConstraintsStatus.FULFILLED)) {
@ -164,19 +162,18 @@ final class BreakInsertionCalculator implements JobInsertionCostsCalculator{
prevActStartTime = CalculationUtils.getActivityEndTime(nextActArrTime, nextAct); prevActStartTime = CalculationUtils.getActivityEndTime(nextActArrTime, nextAct);
prevAct = nextAct; prevAct = nextAct;
actIndex++; actIndex++;
if(breakThis) break; if (breakThis) break;
} }
if(insertionIndex == InsertionData.NO_INDEX) { if (insertionIndex == InsertionData.NO_INDEX) {
return InsertionData.createEmptyInsertionData(); return InsertionData.createEmptyInsertionData();
} }
InsertionData insertionData = new InsertionData(bestCost, InsertionData.NO_INDEX, insertionIndex, newVehicle, newDriver); InsertionData insertionData = new InsertionData(bestCost, InsertionData.NO_INDEX, insertionIndex, newVehicle, newDriver);
breakAct2Insert.setLocation(bestLocation); breakAct2Insert.setLocation(bestLocation);
insertionData.getEvents().add(new InsertBreak(currentRoute,newVehicle,breakAct2Insert,insertionIndex)); insertionData.getEvents().add(new InsertBreak(currentRoute, newVehicle, breakAct2Insert, insertionIndex));
insertionData.getEvents().add(new SwitchVehicle(currentRoute,newVehicle,newVehicleDepartureTime)); insertionData.getEvents().add(new SwitchVehicle(currentRoute, newVehicle, newVehicleDepartureTime));
insertionData.setVehicleDepartureTime(newVehicleDepartureTime); insertionData.setVehicleDepartureTime(newVehicleDepartureTime);
return insertionData; 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,8 +32,6 @@ 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 {
@ -97,7 +95,7 @@ public class JobInsertionCostsCalculatorBuilder {
/** /**
* Constructs the builder. * Constructs the builder.
* * <p/>
* <p>Some calculators require information from the overall algorithm or the higher-level insertion procedure. Thus listeners inform them. * <p>Some calculators require information from the overall algorithm or the higher-level insertion procedure. Thus listeners inform them.
* These listeners are cached in the according list and can thus be added when its time to add them. * These listeners are cached in the according list and can thus be added when its time to add them.
* *
@ -112,11 +110,11 @@ public class JobInsertionCostsCalculatorBuilder {
/** /**
* Sets activityStates. MUST be set. * Sets activityStates. MUST be set.
* @param stateManager
* *
* @param stateManager
* @return * @return
*/ */
public JobInsertionCostsCalculatorBuilder setStateManager(RouteAndActivityStateGetter stateManager){ public JobInsertionCostsCalculatorBuilder setStateManager(RouteAndActivityStateGetter stateManager) {
this.states = stateManager; this.states = stateManager;
return this; return this;
} }
@ -127,7 +125,7 @@ public class JobInsertionCostsCalculatorBuilder {
* @param vehicleRoutingProblem * @param vehicleRoutingProblem
* @return * @return
*/ */
public JobInsertionCostsCalculatorBuilder setVehicleRoutingProblem(VehicleRoutingProblem vehicleRoutingProblem){ public JobInsertionCostsCalculatorBuilder setVehicleRoutingProblem(VehicleRoutingProblem vehicleRoutingProblem) {
this.vrp = vehicleRoutingProblem; this.vrp = vehicleRoutingProblem;
return this; return this;
} }
@ -138,24 +136,25 @@ public class JobInsertionCostsCalculatorBuilder {
* @param fleetManager * @param fleetManager
* @return * @return
*/ */
public JobInsertionCostsCalculatorBuilder setVehicleFleetManager(VehicleFleetManager fleetManager){ public JobInsertionCostsCalculatorBuilder setVehicleFleetManager(VehicleFleetManager fleetManager) {
this.fleetManager = fleetManager; this.fleetManager = fleetManager;
return this; return this;
} }
/** /**
* Sets a flag to build a calculator based on local calculations. * Sets a flag to build a calculator based on local calculations.
* * <p/>
* <p>Insertion of a job and job-activity is evaluated based on the previous and next activity. * <p>Insertion of a job and job-activity is evaluated based on the previous and next activity.
*
* @param addDefaultCostCalc * @param addDefaultCostCalc
*/ */
public JobInsertionCostsCalculatorBuilder setLocalLevel(boolean addDefaultCostCalc){ public JobInsertionCostsCalculatorBuilder setLocalLevel(boolean addDefaultCostCalc) {
local = true; local = true;
this.addDefaultCostCalc = addDefaultCostCalc; this.addDefaultCostCalc = addDefaultCostCalc;
return this; return this;
} }
public JobInsertionCostsCalculatorBuilder setActivityInsertionCostsCalculator(ActivityInsertionCostsCalculator activityInsertionCostsCalculator){ public JobInsertionCostsCalculatorBuilder setActivityInsertionCostsCalculator(ActivityInsertionCostsCalculator activityInsertionCostsCalculator) {
this.activityInsertionCostCalculator = activityInsertionCostsCalculator; this.activityInsertionCostCalculator = activityInsertionCostsCalculator;
return this; return this;
} }
@ -167,7 +166,7 @@ public class JobInsertionCostsCalculatorBuilder {
* @param memory * @param memory
* @param addDefaultMarginalCostCalc * @param addDefaultMarginalCostCalc
*/ */
public JobInsertionCostsCalculatorBuilder setRouteLevel(int forwardLooking, int memory, boolean addDefaultMarginalCostCalc){ public JobInsertionCostsCalculatorBuilder setRouteLevel(int forwardLooking, int memory, boolean addDefaultMarginalCostCalc) {
local = false; local = false;
this.forwardLooking = forwardLooking; this.forwardLooking = forwardLooking;
this.memory = memory; this.memory = memory;
@ -180,13 +179,13 @@ public class JobInsertionCostsCalculatorBuilder {
* *
* @param weightOfFixedCosts * @param weightOfFixedCosts
*/ */
public JobInsertionCostsCalculatorBuilder considerFixedCosts(double weightOfFixedCosts){ public JobInsertionCostsCalculatorBuilder considerFixedCosts(double weightOfFixedCosts) {
considerFixedCost = true; considerFixedCost = true;
this.weightOfFixedCost = weightOfFixedCosts; this.weightOfFixedCost = weightOfFixedCosts;
return this; return this;
} }
public JobInsertionCostsCalculatorBuilder experimentalTimeScheduler(double timeSlice, int neighbors){ public JobInsertionCostsCalculatorBuilder experimentalTimeScheduler(double timeSlice, int neighbors) {
timeScheduling = true; timeScheduling = true;
this.timeSlice = timeSlice; this.timeSlice = timeSlice;
this.neighbors = neighbors; this.neighbors = neighbors;
@ -199,31 +198,33 @@ public class JobInsertionCostsCalculatorBuilder {
* @return jobInsertionCalculator. * @return jobInsertionCalculator.
* @throws IllegalStateException if vrp == null or activityStates == null or fleetManager == null. * @throws IllegalStateException if vrp == null or activityStates == null or fleetManager == null.
*/ */
public JobInsertionCostsCalculator build(){ public JobInsertionCostsCalculator build() {
if(vrp == null) throw new IllegalStateException("vehicle-routing-problem is null, but it must be set (this.setVehicleRoutingProblem(vrp))"); if (vrp == null)
if(states == null) throw new IllegalStateException("states is null, but is must be set (this.setStateManager(states))"); throw new IllegalStateException("vehicle-routing-problem is null, but it must be set (this.setVehicleRoutingProblem(vrp))");
if(fleetManager == null) throw new IllegalStateException("fleetManager is null, but it must be set (this.setVehicleFleetManager(fleetManager))"); 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; JobInsertionCostsCalculator baseCalculator = null;
CalculatorPlusListeners standardLocal = null; CalculatorPlusListeners standardLocal = null;
if(local){ if (local) {
standardLocal = createStandardLocal(vrp, states); standardLocal = createStandardLocal(vrp, states);
} } else {
else{
checkServicesOnly(); checkServicesOnly();
standardLocal = createStandardRoute(vrp, states,forwardLooking,memory); standardLocal = createStandardRoute(vrp, states, forwardLooking, memory);
} }
baseCalculator = standardLocal.getCalculator(); baseCalculator = standardLocal.getCalculator();
addAlgorithmListeners(standardLocal.getAlgorithmListener()); addAlgorithmListeners(standardLocal.getAlgorithmListener());
addInsertionListeners(standardLocal.getInsertionListener()); addInsertionListeners(standardLocal.getInsertionListener());
if(considerFixedCost){ if (considerFixedCost) {
CalculatorPlusListeners withFixed = createCalculatorConsideringFixedCosts(vrp, baseCalculator, states, weightOfFixedCost); CalculatorPlusListeners withFixed = createCalculatorConsideringFixedCosts(vrp, baseCalculator, states, weightOfFixedCost);
baseCalculator = withFixed.getCalculator(); baseCalculator = withFixed.getCalculator();
addAlgorithmListeners(withFixed.getAlgorithmListener()); addAlgorithmListeners(withFixed.getAlgorithmListener());
addInsertionListeners(withFixed.getInsertionListener()); addInsertionListeners(withFixed.getInsertionListener());
} }
if(timeScheduling){ 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());
@ -233,8 +234,8 @@ public class JobInsertionCostsCalculatorBuilder {
} }
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");
@ -244,28 +245,27 @@ public class JobInsertionCostsCalculatorBuilder {
} }
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,
@ -274,8 +274,7 @@ public class JobInsertionCostsCalculatorBuilder {
} }
}; };
} } else {
else{
actInsertionCalc = activityInsertionCostCalculator; actInsertionCalc = activityInsertionCostCalculator;
} }
@ -303,13 +302,13 @@ public class JobInsertionCostsCalculatorBuilder {
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);
@ -317,17 +316,16 @@ public class JobInsertionCostsCalculatorBuilder {
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,
@ -336,8 +334,7 @@ public class JobInsertionCostsCalculatorBuilder {
} }
}; };
} } else {
else{
routeLevelCostEstimator = activityInsertionCostCalculator; routeLevelCostEstimator = activityInsertionCostCalculator;
} }
ServiceInsertionOnRouteLevelCalculator jobInsertionCalculator = new ServiceInsertionOnRouteLevelCalculator(vrp.getTransportCosts(), vrp.getActivityCosts(), routeLevelCostEstimator, constraintManager, constraintManager); ServiceInsertionOnRouteLevelCalculator jobInsertionCalculator = new ServiceInsertionOnRouteLevelCalculator(vrp.getTransportCosts(), vrp.getActivityCosts(), routeLevelCostEstimator, constraintManager, constraintManager);
@ -353,7 +350,7 @@ 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;

View file

@ -1,4 +1,3 @@
/******************************************************************************* /*******************************************************************************
* Copyright (C) 2014 Stefan Schroeder * Copyright (C) 2014 Stefan Schroeder
* *
@ -32,13 +31,12 @@ 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;
@ -67,7 +65,7 @@ class LocalActivityInsertionCostsCalculator implements ActivityInsertionCostsCal
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());
@ -78,14 +76,13 @@ class LocalActivityInsertionCostsCalculator implements ActivityInsertionCostsCal
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);

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 {
@ -96,7 +95,6 @@ public class RegretInsertion extends AbstractInsertionStrategy {
* Scorer to include other impacts on score such as time-window length or distance to depot. * 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 {
@ -106,80 +104,81 @@ public class RegretInsertion extends AbstractInsertionStrategy {
/** /**
* Scorer that includes the length of the time-window when scoring a job. The wider the time-window, the lower the score. * 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 + "]";
} }
} }
@ -193,7 +192,7 @@ public class RegretInsertion extends AbstractInsertionStrategy {
/** /**
* 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
@ -212,15 +211,14 @@ public class RegretInsertion extends AbstractInsertionStrategy {
@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) {
@ -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,9 +25,8 @@ 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;
@ -51,12 +50,13 @@ public class UpdateFutureWaitingTimes implements ReverseActivityVisitor, StateUp
@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,18 +42,15 @@ 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 {
@ -61,26 +58,26 @@ 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>();
@ -101,10 +98,9 @@ public class VehicleRoutingProblem {
@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));
} }
@ -121,42 +117,43 @@ 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
@ -174,7 +171,7 @@ public class VehicleRoutingProblem {
* @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;
} }
@ -182,20 +179,20 @@ public class VehicleRoutingProblem {
/** /**
* Sets the type of fleetSize. * Sets the type of fleetSize.
* * <p/>
* <p>FleetSize is either FleetSize.INFINITE or FleetSize.FINITE. By default it is FleetSize.INFINITE. * <p>FleetSize is either FleetSize.INFINITE or FleetSize.FINITE. By default it is FleetSize.INFINITE.
* *
* @param fleetSize the fleet size used in this problem. it can either be FleetSize.INFINITE or FleetSize.FINITE * @param fleetSize the fleet size used in this problem. it can either be FleetSize.INFINITE or FleetSize.FINITE
* @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. * 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
@ -205,13 +202,13 @@ public class VehicleRoutingProblem {
*/ */
@Deprecated @Deprecated
public Builder addJob(Job job) { public Builder addJob(Job job) {
if(!(job instanceof AbstractJob)) throw new IllegalArgumentException("job must be of type AbstractJob"); if (!(job instanceof AbstractJob)) throw new IllegalArgumentException("job must be of type AbstractJob");
return addJob((AbstractJob)job); 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. * <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);
@ -229,42 +228,40 @@ public class VehicleRoutingProblem {
} }
private void addLocationToTentativeLocations(Job job) { private void addLocationToTentativeLocations(Job job) {
if(job instanceof Service) { if (job instanceof Service) {
tentative_coordinates.put(((Service)job).getLocation().getId(), ((Service)job).getLocation().getCoordinate()); tentative_coordinates.put(((Service) job).getLocation().getId(), ((Service) job).getLocation().getCoordinate());
} } else if (job instanceof Shipment) {
else if(job instanceof Shipment){ Shipment shipment = (Shipment) job;
Shipment shipment = (Shipment)job;
tentative_coordinates.put(shipment.getPickupLocation().getId(), shipment.getPickupLocation().getCoordinate()); tentative_coordinates.put(shipment.getPickupLocation().getId(), shipment.getPickupLocation().getCoordinate());
tentative_coordinates.put(shipment.getDeliveryLocation().getId(), shipment.getDeliveryLocation().getCoordinate()); tentative_coordinates.put(shipment.getDeliveryLocation().getId(), shipment.getDeliveryLocation().getCoordinate());
} }
} }
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;
@ -276,13 +273,13 @@ 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);
@ -294,7 +291,8 @@ public class VehicleRoutingProblem {
} }
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())) {
logger.warn("job " + job + " already in job list. overrides existing job.");
}
tentative_coordinates.put(job.getPickupLocation().getId(), job.getPickupLocation().getCoordinate()); tentative_coordinates.put(job.getPickupLocation().getId(), job.getPickupLocation().getCoordinate());
tentative_coordinates.put(job.getDeliveryLocation().getId(), job.getDeliveryLocation().getCoordinate()); tentative_coordinates.put(job.getDeliveryLocation().getId(), job.getDeliveryLocation().getCoordinate());
jobs.put(job.getId(),job); jobs.put(job.getId(), job);
} }
/** /**
* Adds a vehicle. * Adds a vehicle.
* *
*
* @param vehicle vehicle to be added * @param vehicle vehicle to be added
* @return this builder * @return this builder
* @deprecated use addVehicle(AbstractVehicle vehicle) instead * @deprecated use addVehicle(AbstractVehicle vehicle) instead
*/ */
@Deprecated @Deprecated
public Builder addVehicle(Vehicle vehicle) { public Builder addVehicle(Vehicle vehicle) {
if(!(vehicle instanceof AbstractVehicle)) throw new IllegalStateException("vehicle must be an AbstractVehicle"); if (!(vehicle instanceof AbstractVehicle))
return addVehicle((AbstractVehicle)vehicle); throw new IllegalStateException("vehicle must be an AbstractVehicle");
return addVehicle((AbstractVehicle) vehicle);
} }
/** /**
* Adds a vehicle. * Adds a vehicle.
* *
*
* @param vehicle vehicle to be added * @param vehicle vehicle to be added
* @return this builder * @return this builder
*/ */
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;
@ -383,36 +381,37 @@ 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))
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); return new VehicleRoutingProblem(this);
} }
@ -430,7 +429,7 @@ public class VehicleRoutingProblem {
*/ */
@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;
@ -444,7 +443,7 @@ public class VehicleRoutingProblem {
*/ */
@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;
@ -455,7 +454,7 @@ public class VehicleRoutingProblem {
* *
* @return collection of vehicles * @return collection of vehicles
*/ */
public Collection<Vehicle> getAddedVehicles(){ public Collection<Vehicle> getAddedVehicles() {
return Collections.unmodifiableCollection(uniqueVehicles); return Collections.unmodifiableCollection(uniqueVehicles);
} }
@ -464,7 +463,7 @@ public class VehicleRoutingProblem {
* *
* @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);
} }
@ -473,25 +472,26 @@ public class VehicleRoutingProblem {
* *
* @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.");
}
jobs.put(service.getId(), service);
return this; 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
@ -537,7 +537,7 @@ public class VehicleRoutingProblem {
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;
@ -553,7 +553,7 @@ 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;
@ -566,13 +566,13 @@ public class VehicleRoutingProblem {
@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
@ -595,9 +595,9 @@ public class VehicleRoutingProblem {
* *
* @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;
@ -609,7 +609,7 @@ public class VehicleRoutingProblem {
* @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);
} }
@ -637,14 +637,14 @@ public class VehicleRoutingProblem {
/** /**
* 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;
} }
@ -652,19 +652,21 @@ 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 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

@ -24,7 +24,6 @@ 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 {
@ -36,7 +35,7 @@ public class Break extends Service {
* @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);
} }
@ -48,14 +47,14 @@ public class Break extends Service {
/** /**
* 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");
@ -73,7 +72,7 @@ public class Break extends Service {
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

@ -23,7 +23,7 @@ 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;
@ -61,11 +61,11 @@ public class BreakActivity extends AbstractActivity implements JobActivity{
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);
} }
@ -140,7 +140,7 @@ public class BreakActivity extends AbstractActivity implements JobActivity{
return location; return location;
} }
public void setLocation(Location breakLocation){ public void setLocation(Location breakLocation) {
this.location = breakLocation; this.location = breakLocation;
} }
@ -152,7 +152,7 @@ public class BreakActivity extends AbstractActivity implements JobActivity{
@Override @Override
public String toString() { public String toString() {
return "[type="+getName()+"][location=" + getLocation() return "[type=" + getName() + "][location=" + getLocation()
+ "][size=" + getSize().toString() + "][size=" + getSize().toString()
+ "][twStart=" + Activities.round(getTheoreticalEarliestOperationStartTime()) + "][twStart=" + Activities.round(getTheoreticalEarliestOperationStartTime())
+ "][twEnd=" + Activities.round(getTheoreticalLatestOperationStartTime()) + "]"; + "][twEnd=" + Activities.round(getTheoreticalLatestOperationStartTime()) + "]";
@ -174,5 +174,4 @@ public class BreakActivity extends AbstractActivity implements JobActivity{
} }
} }

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

@ -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}.
* *
@ -91,19 +90,20 @@ 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 {
@ -138,28 +138,28 @@ public class VehicleImpl extends AbstractVehicle {
* Sets the {@link VehicleType}.<br> * Sets the {@link VehicleType}.<br>
* *
* @param type the type to be set * @param type the type to be set
* @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;
} }
@ -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>" +
@ -265,12 +268,12 @@ public class VehicleImpl extends AbstractVehicle {
/** /**
* Returns empty/noVehicle which is a vehicle having no capacity, no type and no reasonable id. * Returns empty/noVehicle which is a vehicle having no capacity, no type and no reasonable id.
* * <p/>
* <p>NoVehicle has id="noVehicle" and extends {@link VehicleImpl} * <p>NoVehicle has id="noVehicle" and extends {@link VehicleImpl}
* *
* @return emptyVehicle * @return emptyVehicle
*/ */
public static NoVehicle createNoVehicle(){ public static NoVehicle createNoVehicle() {
return new NoVehicle(); return new NoVehicle();
} }
@ -292,7 +295,7 @@ public class VehicleImpl extends AbstractVehicle {
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;
@ -303,12 +306,12 @@ public class VehicleImpl extends AbstractVehicle {
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

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

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

@ -21,7 +21,7 @@ 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();
@ -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

@ -32,58 +32,58 @@ public class BreakActivityTest {
private BreakActivity serviceActivity; private BreakActivity serviceActivity;
@Before @Before
public void doBefore(){ public void doBefore() {
service = (Break) Break.Builder.newInstance("service") service = (Break) Break.Builder.newInstance("service")
.setTimeWindow(TimeWindow.newInstance(1., 2.)).setServiceTime(3).build(); .setTimeWindow(TimeWindow.newInstance(1., 2.)).setServiceTime(3).build();
serviceActivity = BreakActivity.newInstance(service); serviceActivity = BreakActivity.newInstance(service);
} }
@Test @Test
public void whenCallingCapacity_itShouldReturnCorrectCapacity(){ public void whenCallingCapacity_itShouldReturnCorrectCapacity() {
assertEquals(0,serviceActivity.getSize().get(0)); assertEquals(0, serviceActivity.getSize().get(0));
} }
@Test @Test
public void hasVariableLocationShouldBeTrue(){ public void hasVariableLocationShouldBeTrue() {
Break aBreak = (Break) serviceActivity.getJob(); Break aBreak = (Break) serviceActivity.getJob();
assertTrue(aBreak.hasVariableLocation()); assertTrue(aBreak.hasVariableLocation());
} }
@Test @Test
public void whenStartIsIniWithEarliestStart_itShouldBeSetCorrectly(){ public void whenStartIsIniWithEarliestStart_itShouldBeSetCorrectly() {
assertEquals(1.,serviceActivity.getTheoreticalEarliestOperationStartTime(),0.01); assertEquals(1., serviceActivity.getTheoreticalEarliestOperationStartTime(), 0.01);
} }
@Test @Test
public void whenStartIsIniWithLatestStart_itShouldBeSetCorrectly(){ public void whenStartIsIniWithLatestStart_itShouldBeSetCorrectly() {
assertEquals(2.,serviceActivity.getTheoreticalLatestOperationStartTime(),0.01); assertEquals(2., serviceActivity.getTheoreticalLatestOperationStartTime(), 0.01);
} }
@Test @Test
public void whenSettingArrTime_itShouldBeSetCorrectly(){ public void whenSettingArrTime_itShouldBeSetCorrectly() {
serviceActivity.setArrTime(4.0); serviceActivity.setArrTime(4.0);
assertEquals(4.,serviceActivity.getArrTime(),0.01); assertEquals(4., serviceActivity.getArrTime(), 0.01);
} }
@Test @Test
public void whenSettingEndTime_itShouldBeSetCorrectly(){ public void whenSettingEndTime_itShouldBeSetCorrectly() {
serviceActivity.setEndTime(5.0); serviceActivity.setEndTime(5.0);
assertEquals(5.,serviceActivity.getEndTime(),0.01); assertEquals(5., serviceActivity.getEndTime(), 0.01);
} }
@Test @Test
public void whenCopyingStart_itShouldBeDoneCorrectly(){ public void whenCopyingStart_itShouldBeDoneCorrectly() {
BreakActivity copy = (BreakActivity) serviceActivity.duplicate(); BreakActivity copy = (BreakActivity) serviceActivity.duplicate();
assertEquals(1.,copy.getTheoreticalEarliestOperationStartTime(),0.01); assertEquals(1., copy.getTheoreticalEarliestOperationStartTime(), 0.01);
assertEquals(2.,copy.getTheoreticalLatestOperationStartTime(),0.01); assertEquals(2., copy.getTheoreticalLatestOperationStartTime(), 0.01);
assertTrue(copy!=serviceActivity); assertTrue(copy != serviceActivity);
} }
@Test @Test
public void whenTwoDeliveriesHaveTheSameUnderlyingJob_theyAreEqual(){ public void whenTwoDeliveriesHaveTheSameUnderlyingJob_theyAreEqual() {
Service s1 = Service.Builder.newInstance("s").setLocation(Location.newInstance("loc")).build(); Service s1 = Service.Builder.newInstance("s").setLocation(Location.newInstance("loc")).build();
Service s2 = Service.Builder.newInstance("s").setLocation(Location.newInstance("loc")).build(); Service s2 = Service.Builder.newInstance("s").setLocation(Location.newInstance("loc")).build();
@ -94,7 +94,7 @@ public class BreakActivityTest {
} }
@Test @Test
public void whenTwoDeliveriesHaveTheDifferentUnderlyingJob_theyAreNotEqual(){ public void whenTwoDeliveriesHaveTheDifferentUnderlyingJob_theyAreNotEqual() {
Service s1 = Service.Builder.newInstance("s").setLocation(Location.newInstance("loc")).build(); Service s1 = Service.Builder.newInstance("s").setLocation(Location.newInstance("loc")).build();
Service s2 = Service.Builder.newInstance("s1").setLocation(Location.newInstance("loc")).build(); Service s2 = Service.Builder.newInstance("s1").setLocation(Location.newInstance("loc")).build();

View file

@ -30,29 +30,27 @@ 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
public void whenAddingSkills_theyShouldBeAddedCorrectly() { public void whenAddingSkills_theyShouldBeAddedCorrectly() {
VehicleTypeImpl type1 = VehicleTypeImpl.Builder.newInstance("type").build(); VehicleTypeImpl type1 = VehicleTypeImpl.Builder.newInstance("type").build();

View file

@ -38,7 +38,6 @@ import java.util.Collection;
public class BreakExample { public class BreakExample {
public static void main(String[] args) { public static void main(String[] args) {
@ -62,7 +61,7 @@ public class BreakExample {
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.
*/ */
@ -83,8 +82,8 @@ public class BreakExample {
* 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
*/ */
@ -100,7 +99,7 @@ public class BreakExample {
/* /*
* plot * plot
*/ */
new Plotter(problem,bestSolution).plot("output/plot","breaks"); new Plotter(problem, bestSolution).plot("output/plot", "breaks");
} }