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
public void informAlgorithmEnds(VehicleRoutingProblem problem, Collection<VehicleRoutingProblemSolution> solutions) {
log.info("create chart " + filename);
log.info("create chart {}", 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);
}
}

View file

@ -283,7 +283,7 @@ public class Plotter {
}
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 solution = null;
final XYSeriesCollection shipments;

View file

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

View file

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

View file

@ -229,7 +229,7 @@ public class Jsprit {
return this;
}
public Builder setActivityInsertionCalculator(ActivityInsertionCostsCalculator activityInsertionCalculator){
public Builder setActivityInsertionCalculator(ActivityInsertionCostsCalculator activityInsertionCalculator) {
this.activityInsertionCalculator = activityInsertionCalculator;
return this;
}
@ -337,13 +337,12 @@ public class Jsprit {
final double maxCosts = jobNeighborhoods.getMaxDistance();
IterationStartsListener noiseConfigurator;
if(noThreads > 1) {
if (noThreads > 1) {
ConcurrentInsertionNoiseMaker noiseMaker = new ConcurrentInsertionNoiseMaker(vrp, maxCosts, noiseLevel, noiseProbability);
noiseMaker.setRandom(random);
constraintManager.addConstraint(noiseMaker);
noiseConfigurator = noiseMaker;
}
else {
} else {
InsertionNoiseMaker noiseMaker = new InsertionNoiseMaker(vrp, maxCosts, noiseLevel, noiseProbability);
noiseMaker.setRandom(random);
constraintManager.addConstraint(noiseMaker);
@ -583,19 +582,18 @@ public class Jsprit {
boolean hasBreak = false;
TourActivity prevAct = route.getStart();
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.getActivityCosts().getActivityCost(act, act.getArrTime(), route.getDriver(), route.getVehicle());
prevAct = act;
}
costs += vrp.getTransportCosts().getTransportCost(prevAct.getLocation(), route.getEnd().getLocation(), prevAct.getEndTime(), route.getDriver(), route.getVehicle());
if(route.getVehicle().getBreak() != null){
if(!hasBreak){
if (route.getVehicle().getBreak() != null) {
if (!hasBreak) {
//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;
}
else{
} else {
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}.
*
* @author schroeder
*
*/
final class BreakInsertionCalculator implements JobInsertionCostsCalculator{
final class BreakInsertionCalculator implements JobInsertionCostsCalculator {
private static final Logger logger = LogManager.getLogger(BreakInsertionCalculator.class);
@ -77,7 +76,7 @@ final class BreakInsertionCalculator implements JobInsertionCostsCalculator{
logger.debug("initialise " + this);
}
public void setJobActivityFactory(JobActivityFactory jobActivityFactory){
public void setJobActivityFactory(JobActivityFactory 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
* assumption that cost changes can entirely covered by only looking at the predecessor i-1 and its successor i+1.
*
*/
@Override
public InsertionData getInsertionData(final VehicleRoute currentRoute, final Job jobToInsert, final Vehicle newVehicle, double newVehicleDepartureTime, final Driver newDriver, final double bestKnownCosts) {
Break breakToInsert = (Break) jobToInsert;
if(newVehicle.getBreak() == null || newVehicle.getBreak() != breakToInsert) {
if (newVehicle.getBreak() == null || newVehicle.getBreak() != breakToInsert) {
return InsertionData.createEmptyInsertionData();
}
if(currentRoute.isEmpty()) return InsertionData.createEmptyInsertionData();
if (currentRoute.isEmpty()) return InsertionData.createEmptyInsertionData();
JobInsertionContext insertionContext = new JobInsertionContext(currentRoute, jobToInsert, newVehicle, newDriver, newVehicleDepartureTime);
int insertionIndex = InsertionData.NO_INDEX;
@ -108,7 +106,7 @@ final class BreakInsertionCalculator implements JobInsertionCostsCalculator{
/*
check hard constraints at route level
*/
if(!hardRouteLevelConstraint.fulfilled(insertionContext)){
if (!hardRouteLevelConstraint.fulfilled(insertionContext)) {
return InsertionData.createEmptyInsertionData();
}
@ -134,16 +132,16 @@ final class BreakInsertionCalculator implements JobInsertionCostsCalculator{
int actIndex = 0;
Iterator<TourActivity> activityIterator = currentRoute.getActivities().iterator();
boolean tourEnd = false;
while(!tourEnd){
while (!tourEnd) {
TourActivity nextAct;
if(activityIterator.hasNext()) nextAct = activityIterator.next();
else{
if (activityIterator.hasNext()) nextAct = activityIterator.next();
else {
nextAct = end;
tourEnd = true;
}
boolean breakThis = true;
List<Location> locations = Arrays.asList( prevAct.getLocation(), nextAct.getLocation());
for(Location location : locations) {
List<Location> locations = Arrays.asList(prevAct.getLocation(), nextAct.getLocation());
for (Location location : locations) {
breakAct2Insert.setLocation(location);
ConstraintsStatus status = hardActivityLevelConstraint.fulfilled(insertionContext, prevAct, breakAct2Insert, nextAct, prevActStartTime);
if (status.equals(ConstraintsStatus.FULFILLED)) {
@ -164,19 +162,18 @@ final class BreakInsertionCalculator implements JobInsertionCostsCalculator{
prevActStartTime = CalculationUtils.getActivityEndTime(nextActArrTime, nextAct);
prevAct = nextAct;
actIndex++;
if(breakThis) break;
if (breakThis) break;
}
if(insertionIndex == InsertionData.NO_INDEX) {
if (insertionIndex == InsertionData.NO_INDEX) {
return InsertionData.createEmptyInsertionData();
}
InsertionData insertionData = new InsertionData(bestCost, InsertionData.NO_INDEX, insertionIndex, newVehicle, newDriver);
breakAct2Insert.setLocation(bestLocation);
insertionData.getEvents().add(new InsertBreak(currentRoute,newVehicle,breakAct2Insert,insertionIndex));
insertionData.getEvents().add(new SwitchVehicle(currentRoute,newVehicle,newVehicleDepartureTime));
insertionData.getEvents().add(new InsertBreak(currentRoute, newVehicle, breakAct2Insert, insertionIndex));
insertionData.getEvents().add(new SwitchVehicle(currentRoute, newVehicle, newVehicleDepartureTime));
insertionData.setVehicleDepartureTime(newVehicleDepartureTime);
return insertionData;
}
}

View file

@ -13,24 +13,24 @@ class InsertBreakListener implements EventListener {
@Override
public void inform(Event event) {
if(event instanceof InsertBreak){
if (event instanceof InsertBreak) {
InsertBreak insertActivity = (InsertBreak) event;
if(!insertActivity.getNewVehicle().isReturnToDepot()){
if(insertActivity.getIndex()>=insertActivity.getVehicleRoute().getActivities().size()){
if (!insertActivity.getNewVehicle().isReturnToDepot()) {
if (insertActivity.getIndex() >= insertActivity.getVehicleRoute().getActivities().size()) {
insertActivity.getVehicleRoute().getEnd().setLocation(insertActivity.getActivity().getLocation());
}
}
VehicleRoute vehicleRoute = ((InsertBreak) event).getVehicleRoute();
if(!vehicleRoute.isEmpty()){
if(vehicleRoute.getVehicle() != ((InsertBreak) event).getNewVehicle()){
if(vehicleRoute.getVehicle().getBreak() != null){
if (!vehicleRoute.isEmpty()) {
if (vehicleRoute.getVehicle() != ((InsertBreak) event).getNewVehicle()) {
if (vehicleRoute.getVehicle().getBreak() != null) {
boolean removed = vehicleRoute.getTourActivities().removeJob(vehicleRoute.getVehicle().getBreak());
if(removed)
if (removed)
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;
public class JobInsertionCostsCalculatorBuilder {
private static class CalculatorPlusListeners {
@ -97,7 +95,7 @@ public class JobInsertionCostsCalculatorBuilder {
/**
* Constructs the builder.
*
* <p/>
* <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.
*
@ -112,11 +110,11 @@ public class JobInsertionCostsCalculatorBuilder {
/**
* Sets activityStates. MUST be set.
* @param stateManager
*
* @param stateManager
* @return
*/
public JobInsertionCostsCalculatorBuilder setStateManager(RouteAndActivityStateGetter stateManager){
public JobInsertionCostsCalculatorBuilder setStateManager(RouteAndActivityStateGetter stateManager) {
this.states = stateManager;
return this;
}
@ -127,7 +125,7 @@ public class JobInsertionCostsCalculatorBuilder {
* @param vehicleRoutingProblem
* @return
*/
public JobInsertionCostsCalculatorBuilder setVehicleRoutingProblem(VehicleRoutingProblem vehicleRoutingProblem){
public JobInsertionCostsCalculatorBuilder setVehicleRoutingProblem(VehicleRoutingProblem vehicleRoutingProblem) {
this.vrp = vehicleRoutingProblem;
return this;
}
@ -138,24 +136,25 @@ public class JobInsertionCostsCalculatorBuilder {
* @param fleetManager
* @return
*/
public JobInsertionCostsCalculatorBuilder setVehicleFleetManager(VehicleFleetManager fleetManager){
public JobInsertionCostsCalculatorBuilder setVehicleFleetManager(VehicleFleetManager fleetManager) {
this.fleetManager = fleetManager;
return this;
}
/**
* 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.
*
* @param addDefaultCostCalc
*/
public JobInsertionCostsCalculatorBuilder setLocalLevel(boolean addDefaultCostCalc){
public JobInsertionCostsCalculatorBuilder setLocalLevel(boolean addDefaultCostCalc) {
local = true;
this.addDefaultCostCalc = addDefaultCostCalc;
return this;
}
public JobInsertionCostsCalculatorBuilder setActivityInsertionCostsCalculator(ActivityInsertionCostsCalculator activityInsertionCostsCalculator){
public JobInsertionCostsCalculatorBuilder setActivityInsertionCostsCalculator(ActivityInsertionCostsCalculator activityInsertionCostsCalculator) {
this.activityInsertionCostCalculator = activityInsertionCostsCalculator;
return this;
}
@ -167,7 +166,7 @@ public class JobInsertionCostsCalculatorBuilder {
* @param memory
* @param addDefaultMarginalCostCalc
*/
public JobInsertionCostsCalculatorBuilder setRouteLevel(int forwardLooking, int memory, boolean addDefaultMarginalCostCalc){
public JobInsertionCostsCalculatorBuilder setRouteLevel(int forwardLooking, int memory, boolean addDefaultMarginalCostCalc) {
local = false;
this.forwardLooking = forwardLooking;
this.memory = memory;
@ -180,13 +179,13 @@ public class JobInsertionCostsCalculatorBuilder {
*
* @param weightOfFixedCosts
*/
public JobInsertionCostsCalculatorBuilder considerFixedCosts(double weightOfFixedCosts){
public JobInsertionCostsCalculatorBuilder considerFixedCosts(double weightOfFixedCosts) {
considerFixedCost = true;
this.weightOfFixedCost = weightOfFixedCosts;
return this;
}
public JobInsertionCostsCalculatorBuilder experimentalTimeScheduler(double timeSlice, int neighbors){
public JobInsertionCostsCalculatorBuilder experimentalTimeScheduler(double timeSlice, int neighbors) {
timeScheduling = true;
this.timeSlice = timeSlice;
this.neighbors = neighbors;
@ -199,31 +198,33 @@ public class JobInsertionCostsCalculatorBuilder {
* @return jobInsertionCalculator.
* @throws IllegalStateException if vrp == null or activityStates == null or fleetManager == null.
*/
public JobInsertionCostsCalculator build(){
if(vrp == null) throw new IllegalStateException("vehicle-routing-problem is null, but it must be set (this.setVehicleRoutingProblem(vrp))");
if(states == null) throw new IllegalStateException("states is null, but is must be set (this.setStateManager(states))");
if(fleetManager == null) throw new IllegalStateException("fleetManager is null, but it must be set (this.setVehicleFleetManager(fleetManager))");
public JobInsertionCostsCalculator build() {
if (vrp == null)
throw new IllegalStateException("vehicle-routing-problem is null, but it must be set (this.setVehicleRoutingProblem(vrp))");
if (states == null)
throw new IllegalStateException("states is null, but is must be set (this.setStateManager(states))");
if (fleetManager == null)
throw new IllegalStateException("fleetManager is null, but it must be set (this.setVehicleFleetManager(fleetManager))");
JobInsertionCostsCalculator baseCalculator = null;
CalculatorPlusListeners standardLocal = null;
if(local){
if (local) {
standardLocal = createStandardLocal(vrp, states);
}
else{
} else {
checkServicesOnly();
standardLocal = createStandardRoute(vrp, states,forwardLooking,memory);
standardLocal = createStandardRoute(vrp, states, forwardLooking, memory);
}
baseCalculator = standardLocal.getCalculator();
addAlgorithmListeners(standardLocal.getAlgorithmListener());
addInsertionListeners(standardLocal.getInsertionListener());
if(considerFixedCost){
if (considerFixedCost) {
CalculatorPlusListeners withFixed = createCalculatorConsideringFixedCosts(vrp, baseCalculator, states, weightOfFixedCost);
baseCalculator = withFixed.getCalculator();
addAlgorithmListeners(withFixed.getAlgorithmListener());
addInsertionListeners(withFixed.getInsertionListener());
}
if(timeScheduling){
if (timeScheduling) {
// 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);
calcPlusListeners.getInsertionListener().add(new CalculatesServiceInsertionWithTimeScheduling.KnowledgeInjection(wts));
addInsertionListeners(calcPlusListeners.getInsertionListener());
@ -233,8 +234,8 @@ public class JobInsertionCostsCalculatorBuilder {
}
private void checkServicesOnly() {
for(Job j : vrp.getJobs().values()){
if(j instanceof Shipment){
for (Job j : vrp.getJobs().values()) {
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" +
"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");
@ -244,28 +245,27 @@ public class JobInsertionCostsCalculatorBuilder {
}
private void addInsertionListeners(List<InsertionListener> list) {
for(InsertionListener iL : list){
for (InsertionListener iL : list) {
insertionListeners.add(iL);
}
}
private void addAlgorithmListeners(List<PrioritizedVRAListener> list) {
for(PrioritizedVRAListener aL : list){
for (PrioritizedVRAListener aL : list) {
algorithmListeners.add(aL);
}
}
private CalculatorPlusListeners createStandardLocal(final VehicleRoutingProblem vrp, RouteAndActivityStateGetter statesManager){
if(constraintManager == null) throw new IllegalStateException("constraint-manager is null");
private CalculatorPlusListeners createStandardLocal(final VehicleRoutingProblem vrp, RouteAndActivityStateGetter statesManager) {
if (constraintManager == null) throw new IllegalStateException("constraint-manager is null");
ActivityInsertionCostsCalculator actInsertionCalc;
ConfigureLocalActivityInsertionCalculator configLocal = null;
if(activityInsertionCostCalculator == null && addDefaultCostCalc){
if (activityInsertionCostCalculator == null && addDefaultCostCalc) {
actInsertionCalc = new LocalActivityInsertionCostsCalculator(vrp.getTransportCosts(), vrp.getActivityCosts(), statesManager);
configLocal = new ConfigureLocalActivityInsertionCalculator(vrp, (LocalActivityInsertionCostsCalculator) actInsertionCalc);
}
else if(activityInsertionCostCalculator == null && !addDefaultCostCalc){
actInsertionCalc = new ActivityInsertionCostsCalculator(){
} else if (activityInsertionCostCalculator == null && !addDefaultCostCalc) {
actInsertionCalc = new ActivityInsertionCostsCalculator() {
@Override
public double getCosts(JobInsertionContext iContext, TourActivity prevAct, TourActivity nextAct, TourActivity newAct,
@ -274,8 +274,7 @@ public class JobInsertionCostsCalculatorBuilder {
}
};
}
else{
} else {
actInsertionCalc = activityInsertionCostCalculator;
}
@ -303,13 +302,13 @@ public class JobInsertionCostsCalculatorBuilder {
switcher.put(Break.class, breakInsertionCalculator);
CalculatorPlusListeners calculatorPlusListeners = new CalculatorPlusListeners(switcher);
if(configLocal != null){
if (configLocal != null) {
calculatorPlusListeners.insertionListener.add(configLocal);
}
return calculatorPlusListeners;
}
private CalculatorPlusListeners createCalculatorConsideringFixedCosts(VehicleRoutingProblem vrp, JobInsertionCostsCalculator baseCalculator, RouteAndActivityStateGetter activityStates2, double weightOfFixedCosts){
private CalculatorPlusListeners createCalculatorConsideringFixedCosts(VehicleRoutingProblem vrp, JobInsertionCostsCalculator baseCalculator, RouteAndActivityStateGetter activityStates2, double weightOfFixedCosts) {
final JobInsertionConsideringFixCostsCalculator withFixCost = new JobInsertionConsideringFixCostsCalculator(baseCalculator, activityStates2);
withFixCost.setWeightOfFixCost(weightOfFixedCosts);
CalculatorPlusListeners calcPlusListeners = new CalculatorPlusListeners(withFixCost);
@ -317,17 +316,16 @@ public class JobInsertionCostsCalculatorBuilder {
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;
if(activityInsertionCostCalculator == null && addDefaultCostCalc){
if (activityInsertionCostCalculator == null && addDefaultCostCalc) {
RouteLevelActivityInsertionCostsEstimator routeLevelActivityInsertionCostsEstimator = new RouteLevelActivityInsertionCostsEstimator(vrp.getTransportCosts(), vrp.getActivityCosts(), activityStates2);
routeLevelActivityInsertionCostsEstimator.setForwardLooking(forwardLooking);
routeLevelCostEstimator = routeLevelActivityInsertionCostsEstimator;
}
else if(activityInsertionCostCalculator == null && !addDefaultCostCalc){
routeLevelCostEstimator = new ActivityInsertionCostsCalculator(){
} else if (activityInsertionCostCalculator == null && !addDefaultCostCalc) {
routeLevelCostEstimator = new ActivityInsertionCostsCalculator() {
final ActivityInsertionCosts noInsertionCosts = new ActivityInsertionCosts(0.,0.);
final ActivityInsertionCosts noInsertionCosts = new ActivityInsertionCosts(0., 0.);
@Override
public double getCosts(JobInsertionContext iContext, TourActivity prevAct, TourActivity nextAct, TourActivity newAct,
@ -336,8 +334,7 @@ public class JobInsertionCostsCalculatorBuilder {
}
};
}
else{
} else {
routeLevelCostEstimator = activityInsertionCostCalculator;
}
ServiceInsertionOnRouteLevelCalculator jobInsertionCalculator = new ServiceInsertionOnRouteLevelCalculator(vrp.getTransportCosts(), vrp.getActivityCosts(), routeLevelCostEstimator, constraintManager, constraintManager);
@ -353,7 +350,7 @@ public class JobInsertionCostsCalculatorBuilder {
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.setVehicleSwitchAllowed(allowVehicleSwitch);
return vehicleTypeDependentJobInsertionCalculator;

View file

@ -1,4 +1,3 @@
/*******************************************************************************
* 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
* activity i (prevAct) and j (nextAct).
* 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.
*
* @author stefan
*
*/
class LocalActivityInsertionCostsCalculator implements ActivityInsertionCostsCalculator{
class LocalActivityInsertionCostsCalculator implements ActivityInsertionCostsCalculator {
private VehicleRoutingTransportCosts routingCosts;
@ -67,7 +65,7 @@ class LocalActivityInsertionCostsCalculator implements ActivityInsertionCostsCal
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_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 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());
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 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 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;
/**
* Insertion based on regret approach.
*
* <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.
* 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.
*
* @author stefan schroeder
*
*/
* 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
* 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
* customer immediatedly. If difference is not that high, it might not impact solution if this customer is inserted later.
*
* @author stefan schroeder
*/
public class RegretInsertion extends AbstractInsertionStrategy {
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.
*
* @author schroeder
*
*/
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.
*
* <p/>
* <p>This is the default scorer, i.e.: score = (secondBest - firstBest) + this.TimeWindowScorer.score(job)
*
* @author schroeder
*
*/
public static class DefaultScorer implements ScoringFunction {
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) {
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
public double score(InsertionData best, Job job) {
double score;
if(job instanceof Service){
if (job instanceof Service) {
score = scoreService(best, job);
}
else if(job instanceof Shipment){
score = scoreShipment(best,job);
}
else throw new IllegalStateException("not supported");
} else if (job instanceof Shipment) {
score = scoreShipment(best, job);
} else throw new IllegalStateException("not supported");
return score;
}
private double scoreShipment(InsertionData best, Job job) {
Shipment shipment = (Shipment)job;
Shipment shipment = (Shipment) job;
double maxDepotDistance_1 = Math.max(
getDistance(best.getSelectedVehicle().getStartLocation(),shipment.getPickupLocation()),
getDistance(best.getSelectedVehicle().getStartLocation(),shipment.getDeliveryLocation())
getDistance(best.getSelectedVehicle().getStartLocation(), shipment.getPickupLocation()),
getDistance(best.getSelectedVehicle().getStartLocation(), shipment.getDeliveryLocation())
);
double maxDepotDistance_2 = Math.max(
getDistance(best.getSelectedVehicle().getEndLocation(),shipment.getPickupLocation()),
getDistance(best.getSelectedVehicle().getEndLocation(),shipment.getDeliveryLocation())
getDistance(best.getSelectedVehicle().getEndLocation(), shipment.getPickupLocation()),
getDistance(best.getSelectedVehicle().getEndLocation(), shipment.getDeliveryLocation())
);
double maxDepotDistance = Math.max(maxDepotDistance_1,maxDepotDistance_2);
double minTimeToOperate = Math.min(shipment.getPickupTimeWindow().getEnd()-shipment.getPickupTimeWindow().getStart(),
shipment.getDeliveryTimeWindow().getEnd()-shipment.getDeliveryTimeWindow().getStart());
return Math.max(tw_param * minTimeToOperate,minTimeWindowScore) + depotDistance_param * maxDepotDistance;
double maxDepotDistance = Math.max(maxDepotDistance_1, maxDepotDistance_2);
double minTimeToOperate = Math.min(shipment.getPickupTimeWindow().getEnd() - shipment.getPickupTimeWindow().getStart(),
shipment.getDeliveryTimeWindow().getEnd() - shipment.getDeliveryTimeWindow().getStart());
return Math.max(tw_param * minTimeToOperate, minTimeWindowScore) + depotDistance_param * maxDepotDistance;
}
private double scoreService(InsertionData best, Job job) {
Location location = ((Service) job).getLocation();
double maxDepotDistance = 0;
if(location != null) {
if (location != null) {
maxDepotDistance = Math.max(
getDistance(best.getSelectedVehicle().getStartLocation(), 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;
}
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
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.
*
* <p/>
* <p>By default, the this.TimeWindowScorer is used.
*
* @param scoringFunction to score
@ -212,15 +211,14 @@ public class RegretInsertion extends AbstractInsertionStrategy {
@Override
public String toString() {
return "[name=regretInsertion][additionalScorer="+scoringFunction+"]";
return "[name=regretInsertion][additionalScorer=" + scoringFunction + "]";
}
/**
* Runs insertion.
*
* <p/>
* <p>Before inserting a job, all unassigned jobs are scored according to its best- and secondBest-insertion plus additional scoring variables.
*
*/
@Override
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> badJobList = new ArrayList<Job>();
ScoredJob bestScoredJob = nextJob(routes, unassignedJobList, badJobList);
if(bestScoredJob != null){
if(bestScoredJob.isNewRoute()){
if (bestScoredJob != null) {
if (bestScoredJob.isNewRoute()) {
routes.add(bestScoredJob.getRoute());
}
insertJob(bestScoredJob.getJob(),bestScoredJob.getInsertionData(),bestScoredJob.getRoute());
insertJob(bestScoredJob.getJob(), bestScoredJob.getInsertionData(), bestScoredJob.getRoute());
jobs.remove(bestScoredJob.getJob());
}
for(Job bad : badJobList) {
for (Job bad : badJobList) {
jobs.remove(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) {
ScoredJob bestScoredJob = null;
for (Job unassignedJob : unassignedJobList) {
ScoredJob scoredJob = getScoredJob(routes,unassignedJob,insertionCostsCalculator,scoringFunction);
if(scoredJob instanceof BadJob){
ScoredJob scoredJob = getScoredJob(routes, unassignedJob, insertionCostsCalculator, scoringFunction);
if (scoredJob instanceof BadJob) {
badJobs.add(unassignedJob);
continue;
}
if(bestScoredJob == null) bestScoredJob = scoredJob;
else{
if(scoredJob.getScore() > bestScoredJob.getScore()){
if (bestScoredJob == null) bestScoredJob = scoredJob;
else {
if (scoredJob.getScore() > bestScoredJob.getScore()) {
bestScoredJob = scoredJob;
}
else if (scoredJob.getScore() == bestScoredJob.getScore()){
if(scoredJob.getJob().getId().compareTo(bestScoredJob.getJob().getId()) <= 0){
} else if (scoredJob.getScore() == bestScoredJob.getScore()) {
if (scoredJob.getJob().getId().compareTo(bestScoredJob.getJob().getId()) <= 0) {
bestScoredJob = scoredJob;
}
}
@ -307,31 +304,29 @@ public class RegretInsertion extends AbstractInsertionStrategy {
secondBest = iData;
}
}
if(best == null){
if (best == null) {
return new RegretInsertion.BadJob(unassignedJob);
}
double score = score(unassignedJob, best, secondBest, scoringFunction);
ScoredJob scoredJob;
if(bestRoute == emptyRoute){
if (bestRoute == emptyRoute) {
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;
}
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());
}
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 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);
}
else{
score = (secondBest.getInsertionCost()-best.getInsertionCost()) + scoringFunction.score(best, unassignedJob);
} else {
score = (secondBest.getInsertionCost() - best.getInsertionCost()) + scoringFunction.score(best, unassignedJob);
}
return score;
}

View file

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

View file

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

View file

@ -17,20 +17,22 @@ public class RuinBreaks implements RuinListener {
private final static Logger logger = LogManager.getLogger();
@Override
public void ruinStarts(Collection<VehicleRoute> routes) {}
public void ruinStarts(Collection<VehicleRoute> routes) {
}
@Override
public void ruinEnds(Collection<VehicleRoute> routes, Collection<Job> unassignedJobs) {
for(VehicleRoute r : routes){
for (VehicleRoute r : routes) {
Break aBreak = r.getVehicle().getBreak();
if(aBreak != null){
if (aBreak != null) {
r.getTourActivities().removeJob(aBreak);
logger.trace("ruin: {}",aBreak.getId());
logger.trace("ruin: {}", aBreak.getId());
unassignedJobs.add(aBreak);
}
}
}
@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.
*
* @author schroeder
*
*/
public class UpdateFutureWaitingTimes implements ReverseActivityVisitor, StateUpdater{
public class UpdateFutureWaitingTimes implements ReverseActivityVisitor, StateUpdater {
private StateManager states;
@ -51,12 +50,13 @@ public class UpdateFutureWaitingTimes implements ReverseActivityVisitor, StateUp
@Override
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)) {
futureWaiting += Math.max(activity.getTheoreticalEarliestOperationStartTime() - activity.getArrTime(), 0);
// }
}
@Override
public void finish() {}
public void finish() {
}
}

View file

@ -42,18 +42,15 @@ import java.util.*;
/**
* Contains and defines the vehicle routing problem.
*
* <p/>
* <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/>
* <p>By default, fleetSize is INFINITE, transport-costs are calculated as euclidean-distance (CrowFlyCosts),
* and activity-costs are set to zero.
*
*
*
* @author stefan schroeder
*
*/
public class VehicleRoutingProblem {
@ -61,26 +58,26 @@ public class VehicleRoutingProblem {
* Builder to build the routing-problem.
*
* @author stefan schroeder
*
*/
public static class Builder {
/**
* Returns a new instance of this builder.
*
* @return builder
*/
public static Builder newInstance(){ return new Builder(); }
public static Builder newInstance() {
return new Builder();
}
private VehicleRoutingTransportCosts transportCosts;
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>();
@ -101,10 +98,9 @@ public class VehicleRoutingProblem {
@Override
public List<AbstractActivity> createActivities(Job job) {
List<AbstractActivity> acts = new ArrayList<AbstractActivity>();
if(job instanceof Service){
if (job instanceof Service) {
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.createDelivery((Shipment) job));
}
@ -121,42 +117,43 @@ public class VehicleRoutingProblem {
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 DefaultTourActivityFactory serviceActivityFactory = new DefaultTourActivityFactory();
private void incJobIndexCounter(){
private void incJobIndexCounter() {
jobIndexCounter++;
}
private void incActivityIndexCounter(){
private void incActivityIndexCounter() {
activityIndexCounter++;
}
private void incVehicleTypeIdIndexCounter() { vehicleTypeIdIndexCounter++; }
private void incVehicleTypeIdIndexCounter() {
vehicleTypeIdIndexCounter++;
}
/**
* Returns the unmodifiable map of collected locations (mapped by their location-id).
*
* @return map with locations
*/
public Map<String,Coordinate> getLocationMap(){
public Map<String, Coordinate> getLocationMap() {
return Collections.unmodifiableMap(tentative_coordinates);
}
/**
* Returns the locations collected SO FAR by this builder.
*
* <p/>
* <p>Locations are cached when adding a shipment, service, depot, vehicle.
*
* @return locations
*
**/
public Locations getLocations(){
*/
public Locations getLocations() {
return new Locations() {
@Override
@ -174,7 +171,7 @@ public class VehicleRoutingProblem {
* @return builder
* @see VehicleRoutingTransportCosts
*/
public Builder setRoutingCost(VehicleRoutingTransportCosts costs){
public Builder setRoutingCost(VehicleRoutingTransportCosts costs) {
this.transportCosts = costs;
return this;
}
@ -182,20 +179,20 @@ public class VehicleRoutingProblem {
/**
* Sets the type of fleetSize.
*
* <p/>
* <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
* @return this builder
*/
public Builder setFleetSize(FleetSize fleetSize){
public Builder setFleetSize(FleetSize fleetSize) {
this.fleetSize = fleetSize;
return this;
}
/**
* Adds a job which is either a service or a shipment.
*
* <p/>
* <p>Note that job.getId() must be unique, i.e. no job (either it is a shipment or a service) is allowed to have an already allocated id.
*
* @param job job to be added
@ -205,13 +202,13 @@ public class VehicleRoutingProblem {
*/
@Deprecated
public Builder addJob(Job job) {
if(!(job instanceof AbstractJob)) throw new IllegalArgumentException("job must be of type AbstractJob");
return addJob((AbstractJob)job);
if (!(job instanceof AbstractJob)) throw new IllegalArgumentException("job must be of type AbstractJob");
return addJob((AbstractJob) job);
}
/**
* Adds a job which is either a service or a shipment.
*
* <p/>
* <p>Note that job.getId() must be unique, i.e. no job (either it is a shipment or a service) is allowed to have an already allocated id.
*
* @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.
*/
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(!(job instanceof Service || job instanceof Shipment)) throw new IllegalStateException("job must be either a service or a shipment");
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 (!(job instanceof Service || job instanceof Shipment))
throw new IllegalStateException("job must be either a service or a shipment");
job.setIndex(jobIndexCounter);
incJobIndexCounter();
tentativeJobs.put(job.getId(), job);
@ -229,42 +228,40 @@ public class VehicleRoutingProblem {
}
private void addLocationToTentativeLocations(Job job) {
if(job instanceof Service) {
tentative_coordinates.put(((Service)job).getLocation().getId(), ((Service)job).getLocation().getCoordinate());
}
else if(job instanceof Shipment){
Shipment shipment = (Shipment)job;
if (job instanceof Service) {
tentative_coordinates.put(((Service) job).getLocation().getId(), ((Service) job).getLocation().getCoordinate());
} else if (job instanceof Shipment) {
Shipment shipment = (Shipment) job;
tentative_coordinates.put(shipment.getPickupLocation().getId(), shipment.getPickupLocation().getCoordinate());
tentative_coordinates.put(shipment.getDeliveryLocation().getId(), shipment.getDeliveryLocation().getCoordinate());
}
}
private void addJobToFinalJobMapAndCreateActivities(Job job){
if(job instanceof Service) {
private void addJobToFinalJobMapAndCreateActivities(Job job) {
if (job instanceof Service) {
Service service = (Service) job;
addService(service);
}
else if(job instanceof Shipment){
Shipment shipment = (Shipment)job;
} else if (job instanceof Shipment) {
Shipment shipment = (Shipment) job;
addShipment(shipment);
}
List<AbstractActivity> jobActs = jobActivityFactory.createActivities(job);
for(AbstractActivity act : jobActs){
for (AbstractActivity act : jobActs) {
act.setIndex(activityIndexCounter);
incActivityIndexCounter();
}
activityMap.put(job, jobActs);
}
private boolean addBreaksToActivityMap(){
private boolean addBreaksToActivityMap() {
boolean hasBreaks = false;
for(Vehicle v : uniqueVehicles){
if(v.getBreak() != null){
for (Vehicle v : uniqueVehicles) {
if (v.getBreak() != null) {
hasBreaks = true;
AbstractActivity breakActivity = BreakActivity.newInstance(v.getBreak());
breakActivity.setIndex(activityIndexCounter);
incActivityIndexCounter();
activityMap.put(v.getBreak(),Arrays.asList(breakActivity));
activityMap.put(v.getBreak(), Arrays.asList(breakActivity));
}
}
return hasBreaks;
@ -276,13 +273,13 @@ public class VehicleRoutingProblem {
* @param route initial route
* @return the builder
*/
public Builder addInitialVehicleRoute(VehicleRoute route){
addVehicle((AbstractVehicle)route.getVehicle());
for(TourActivity act : route.getActivities()){
public Builder addInitialVehicleRoute(VehicleRoute route) {
addVehicle((AbstractVehicle) route.getVehicle());
for (TourActivity act : route.getActivities()) {
AbstractActivity abstractAct = (AbstractActivity) act;
abstractAct.setIndex(activityIndexCounter);
incActivityIndexCounter();
if(act instanceof TourActivity.JobActivity) {
if (act instanceof TourActivity.JobActivity) {
Job job = ((TourActivity.JobActivity) act).getJob();
jobsInInitialRoutes.add(job.getId());
registerLocation(job);
@ -294,7 +291,8 @@ public class VehicleRoutingProblem {
}
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) {
Shipment shipment = (Shipment) job;
tentative_coordinates.put(shipment.getPickupLocation().getId(), shipment.getPickupLocation().getCoordinate());
@ -303,11 +301,11 @@ public class VehicleRoutingProblem {
}
private void registerJobAndActivity(AbstractActivity abstractAct, Job job) {
if(activityMap.containsKey(job)) activityMap.get(job).add(abstractAct);
else{
if (activityMap.containsKey(job)) activityMap.get(job).add(abstractAct);
else {
List<AbstractActivity> actList = new ArrayList<AbstractActivity>();
actList.add(abstractAct);
activityMap.put(job,actList);
activityMap.put(job, actList);
}
}
@ -317,61 +315,61 @@ public class VehicleRoutingProblem {
* @param routes initial routes
* @return the builder
*/
public Builder addInitialVehicleRoutes(Collection<VehicleRoute> routes){
for(VehicleRoute r : routes){
public Builder addInitialVehicleRoutes(Collection<VehicleRoute> routes) {
for (VehicleRoute r : routes) {
addInitialVehicleRoute(r);
}
return this;
}
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.getDeliveryLocation().getId(), job.getDeliveryLocation().getCoordinate());
jobs.put(job.getId(),job);
jobs.put(job.getId(), job);
}
/**
* Adds a vehicle.
*
*
* @param vehicle vehicle to be added
* @return this builder
* @deprecated use addVehicle(AbstractVehicle vehicle) instead
*/
@Deprecated
public Builder addVehicle(Vehicle vehicle) {
if(!(vehicle instanceof AbstractVehicle)) throw new IllegalStateException("vehicle must be an AbstractVehicle");
return addVehicle((AbstractVehicle)vehicle);
if (!(vehicle instanceof AbstractVehicle))
throw new IllegalStateException("vehicle must be an AbstractVehicle");
return addVehicle((AbstractVehicle) vehicle);
}
/**
* Adds a vehicle.
*
*
* @param vehicle vehicle to be added
* @return this builder
*/
public Builder addVehicle(AbstractVehicle vehicle) {
if(!uniqueVehicles.contains(vehicle)){
if (!uniqueVehicles.contains(vehicle)) {
vehicle.setIndex(vehicleIndexCounter);
incVehicleIndexCounter();
}
if(typeKeyIndices.containsKey(vehicle.getVehicleTypeIdentifier())){
if (typeKeyIndices.containsKey(vehicle.getVehicleTypeIdentifier())) {
vehicle.getVehicleTypeIdentifier().setIndex(typeKeyIndices.get(vehicle.getVehicleTypeIdentifier()));
}
else {
} else {
vehicle.getVehicleTypeIdentifier().setIndex(vehicleTypeIdIndexCounter);
typeKeyIndices.put(vehicle.getVehicleTypeIdentifier(),vehicleTypeIdIndexCounter);
typeKeyIndices.put(vehicle.getVehicleTypeIdentifier(), vehicleTypeIdIndexCounter);
incVehicleTypeIdIndexCounter();
}
uniqueVehicles.add(vehicle);
if(!vehicleTypes.contains(vehicle.getType())){
if (!vehicleTypes.contains(vehicle.getType())) {
vehicleTypes.add(vehicle.getType());
}
String startLocationId = vehicle.getStartLocation().getId();
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());
}
return this;
@ -383,36 +381,37 @@ public class VehicleRoutingProblem {
/**
* Sets the activity-costs.
*
* <p/>
* <p>By default it is set to zero.
*
* @param activityCosts activity costs of the problem
* @return this builder
* @see VehicleRoutingActivityCosts
*/
public Builder setActivityCosts(VehicleRoutingActivityCosts activityCosts){
public Builder setActivityCosts(VehicleRoutingActivityCosts activityCosts) {
this.activityCosts = activityCosts;
return this;
}
/**
* Builds the {@link VehicleRoutingProblem}.
*
* <p/>
* <p>If {@link VehicleRoutingTransportCosts} are not set, {@link CrowFlyCosts} is used.
*
* @return {@link VehicleRoutingProblem}
*/
public VehicleRoutingProblem build() {
if(transportCosts == null){
if (transportCosts == null) {
transportCosts = new CrowFlyCosts(getLocations());
}
for(Job job : tentativeJobs.values()) {
for (Job job : tentativeJobs.values()) {
if (!jobsInInitialRoutes.contains(job.getId())) {
addJobToFinalJobMapAndCreateActivities(job);
}
}
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);
}
@ -430,7 +429,7 @@ public class VehicleRoutingProblem {
*/
@SuppressWarnings("deprecation")
public Builder addAllJobs(Collection<? extends Job> jobs) {
for(Job j : jobs){
for (Job j : jobs) {
addJob(j);
}
return this;
@ -444,7 +443,7 @@ public class VehicleRoutingProblem {
*/
@SuppressWarnings("deprecation")
public Builder addAllVehicles(Collection<? extends Vehicle> vehicles) {
for(Vehicle v : vehicles){
for (Vehicle v : vehicles) {
addVehicle(v);
}
return this;
@ -455,7 +454,7 @@ public class VehicleRoutingProblem {
*
* @return collection of vehicles
*/
public Collection<Vehicle> getAddedVehicles(){
public Collection<Vehicle> getAddedVehicles() {
return Collections.unmodifiableCollection(uniqueVehicles);
}
@ -464,7 +463,7 @@ public class VehicleRoutingProblem {
*
* @return collection of vehicle-types
*/
public Collection<VehicleType> getAddedVehicleTypes(){
public Collection<VehicleType> getAddedVehicleTypes() {
return Collections.unmodifiableCollection(vehicleTypes);
}
@ -473,25 +472,26 @@ public class VehicleRoutingProblem {
*
* @return collection of jobs
*/
public Collection<Job> getAddedJobs(){
public Collection<Job> getAddedJobs() {
return Collections.unmodifiableCollection(tentativeJobs.values());
}
private Builder addService(Service service){
private Builder addService(Service service) {
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."); }
jobs.put(service.getId(),service);
if (jobs.containsKey(service.getId())) {
logger.warn("service " + service + " already in job list. overrides existing job.");
}
jobs.put(service.getId(), service);
return this;
}
}
}
/**
* Enum that characterizes the fleet-size.
*
* @author sschroeder
*
*/
public static enum FleetSize {
FINITE, INFINITE
@ -537,7 +537,7 @@ public class VehicleRoutingProblem {
private final Locations locations;
private Map<Job,List<AbstractActivity>> activityMap;
private Map<Job, List<AbstractActivity>> activityMap;
private int nuActivities;
@ -553,7 +553,7 @@ public class VehicleRoutingProblem {
private VehicleRoutingProblem(Builder builder) {
this.jobs = builder.jobs;
this.fleetSize = builder.fleetSize;
this.vehicles=builder.uniqueVehicles;
this.vehicles = builder.uniqueVehicles;
this.vehicleTypes = builder.vehicleTypes;
this.initialVehicleRoutes = builder.initialRoutes;
this.transportCosts = builder.transportCosts;
@ -566,13 +566,13 @@ public class VehicleRoutingProblem {
@Override
public String toString() {
return "[fleetSize="+fleetSize+"][#jobs="+jobs.size()+"][#vehicles="+vehicles.size()+"][#vehicleTypes="+vehicleTypes.size()+"]["+
"transportCost="+transportCosts+"][activityCosts="+activityCosts+"]";
return "[fleetSize=" + fleetSize + "][#jobs=" + jobs.size() + "][#vehicles=" + vehicles.size() + "][#vehicleTypes=" + vehicleTypes.size() + "][" +
"transportCost=" + transportCosts + "][activityCosts=" + activityCosts + "]";
}
/**
* Returns type of fleetSize, either INFINITE or FINITE.
*
* <p/>
* <p>By default, it is INFINITE.
*
* @return either FleetSize.INFINITE or FleetSize.FINITE
@ -595,9 +595,9 @@ public class VehicleRoutingProblem {
*
* @return copied collection of initial vehicle routes
*/
public Collection<VehicleRoute> getInitialVehicleRoutes(){
public Collection<VehicleRoute> getInitialVehicleRoutes() {
Collection<VehicleRoute> copiedInitialRoutes = new ArrayList<VehicleRoute>();
for(VehicleRoute route : initialVehicleRoutes){
for (VehicleRoute route : initialVehicleRoutes) {
copiedInitialRoutes.add(VehicleRoute.copyOf(route));
}
return copiedInitialRoutes;
@ -609,7 +609,7 @@ public class VehicleRoutingProblem {
* @return unmodifiable collection of types
* @see VehicleTypeImpl
*/
public Collection<VehicleType> getTypes(){
public Collection<VehicleType> getTypes() {
return Collections.unmodifiableCollection(vehicleTypes);
}
@ -637,14 +637,14 @@ public class VehicleRoutingProblem {
/**
* Returns activityCosts.
*/
public VehicleRoutingActivityCosts getActivityCosts(){
public VehicleRoutingActivityCosts getActivityCosts() {
return activityCosts;
}
/**
* @return returns all location, i.e. from vehicles and jobs.
*/
public Locations getLocations(){
public Locations getLocations() {
return locations;
}
@ -652,19 +652,21 @@ public class VehicleRoutingProblem {
* @param job for which the corresponding activities needs to be returned
* @return associated activities
*/
public List<AbstractActivity> getActivities(Job job){
public List<AbstractActivity> getActivities(Job job) {
return Collections.unmodifiableList(activityMap.get(job));
}
/**
* @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
*/
public JobActivityFactory getJobActivityFactory(){
public JobActivityFactory getJobActivityFactory() {
return jobActivityFactory;
}
@ -672,9 +674,9 @@ public class VehicleRoutingProblem {
* @param job for which the corresponding activities needs to be returned
* @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>();
if(activityMap.containsKey(job)) {
if (activityMap.containsKey(job)) {
for (AbstractActivity act : activityMap.get(job)) acts.add((AbstractActivity) act.duplicate());
}
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.
*
* @author schroeder
*
*/
public class Break extends Service {
@ -36,7 +35,7 @@ public class Break extends Service {
* @param id the id of the pickup
* @return the builder
*/
public static Builder newInstance(String id){
public static Builder newInstance(String id) {
return new Builder(id);
}
@ -48,14 +47,14 @@ public class Break extends Service {
/**
* Builds Pickup.
*
*<p>Pickup type is "pickup"
* <p/>
* <p>Pickup type is "pickup"
*
* @return pickup
* @throws IllegalStateException if neither locationId nor coordinate has been set
*/
public Break build(){
if(location != null){
public Break build() {
if (location != null) {
variableLocation = false;
}
this.setType("break");
@ -73,7 +72,7 @@ public class Break extends Service {
this.variableLocation = builder.variableLocation;
}
public boolean hasVariableLocation(){
public boolean hasVariableLocation() {
return variableLocation;
}

View file

@ -127,13 +127,11 @@ public class VehicleRoute {
@Override
public List<AbstractActivity> createActivities(Job job) {
List<AbstractActivity> acts = new ArrayList<AbstractActivity>();
if(job instanceof Break){
acts.add(BreakActivity.newInstance((Break)job));
}
else if(job instanceof Service){
if (job instanceof Break) {
acts.add(BreakActivity.newInstance((Break) job));
} else if (job instanceof Service) {
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.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.solution.route.activity.TourActivity.JobActivity;
public class BreakActivity extends AbstractActivity implements JobActivity{
public class BreakActivity extends AbstractActivity implements JobActivity {
public static int counter = 0;
@ -61,11 +61,11 @@ public class BreakActivity extends AbstractActivity implements JobActivity{
this.endTime = endTime;
}
public static BreakActivity copyOf(BreakActivity breakActivity){
public static BreakActivity copyOf(BreakActivity breakActivity) {
return new BreakActivity(breakActivity);
}
public static BreakActivity newInstance(Break aBreak){
public static BreakActivity newInstance(Break aBreak) {
return new BreakActivity(aBreak);
}
@ -140,7 +140,7 @@ public class BreakActivity extends AbstractActivity implements JobActivity{
return location;
}
public void setLocation(Location breakLocation){
public void setLocation(Location breakLocation) {
this.location = breakLocation;
}
@ -152,7 +152,7 @@ public class BreakActivity extends AbstractActivity implements JobActivity{
@Override
public String toString() {
return "[type="+getName()+"][location=" + getLocation()
return "[type=" + getName() + "][location=" + getLocation()
+ "][size=" + getSize().toString()
+ "][twStart=" + Activities.round(getTheoreticalEarliestOperationStartTime())
+ "][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;
Iterator<TourActivity> iterator = tourActivities.iterator();
while(iterator.hasNext()){
while (iterator.hasNext()) {
TourActivity c = iterator.next();
if (c instanceof JobActivity) {
Job underlyingJob = ((JobActivity) c).getJob();
if (job.equals(underlyingJob)) {
iterator.remove();
activityRemoved = true;
if(underlyingJob instanceof Service){
if (underlyingJob instanceof Service) {
break;
}
}

View file

@ -24,7 +24,6 @@ import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
/**
* Implementation of {@link Vehicle}.
*
@ -91,19 +90,20 @@ public class VehicleImpl extends AbstractVehicle {
@Override
public Break getBreak() { return null; }
public Break getBreak() {
return null;
}
}
/**
* Builder that builds the vehicle.
*
* <p/>
* <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'
* and a capacity of 0.
*
* @author stefan
*
*/
public static class Builder {
@ -138,28 +138,28 @@ public class VehicleImpl extends AbstractVehicle {
* Sets the {@link VehicleType}.<br>
*
* @param type the type to be set
* @throws IllegalStateException if type is null
* @return this builder
* @throws IllegalStateException if type is null
*/
public Builder setType(VehicleType type){
if(type==null) throw new IllegalStateException("type cannot be null.");
public Builder setType(VehicleType type) {
if (type == null) throw new IllegalStateException("type cannot be null.");
this.type = type;
return this;
}
/**
* 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
* 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.
*
* <p/>
* <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
* @return this builder
*/
public Builder setReturnToDepot(boolean returnToDepot){
public Builder setReturnToDepot(boolean returnToDepot) {
this.returnToDepot = returnToDepot;
return this;
}
@ -187,7 +187,8 @@ public class VehicleImpl extends AbstractVehicle {
* @return this builder
*/
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;
return this;
}
@ -199,7 +200,8 @@ public class VehicleImpl extends AbstractVehicle {
* @return this builder
*/
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;
return this;
}
@ -226,7 +228,8 @@ public class VehicleImpl extends AbstractVehicle {
* or (endLocationId!=null AND returnToDepot=false)
*/
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.getId().equals(endLocation.getId()) && !returnToDepot)
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.
*
* <p/>
* <p>NoVehicle has id="noVehicle" and extends {@link VehicleImpl}
*
* @return emptyVehicle
*/
public static NoVehicle createNoVehicle(){
public static NoVehicle createNoVehicle() {
return new NoVehicle();
}
@ -292,7 +295,7 @@ public class VehicleImpl extends AbstractVehicle {
private final Break aBreak;
private VehicleImpl(Builder builder){
private VehicleImpl(Builder builder) {
id = builder.id;
type = builder.type;
earliestDeparture = builder.earliestStart;
@ -303,12 +306,12 @@ public class VehicleImpl extends AbstractVehicle {
startLocation = builder.startLocation;
aBreak = builder.aBreak;
// setVehicleIdentifier(new VehicleTypeKey(type.getTypeId(),startLocation.getId(),endLocation.getId(),earliestDeparture,latestArrival,skills));
setVehicleIdentifier(new VehicleTypeKey(type.getTypeId(),startLocation.getId(),endLocation.getId(),earliestDeparture,latestArrival,skills, returnToDepot));
setVehicleIdentifier(new VehicleTypeKey(type.getTypeId(), startLocation.getId(), endLocation.getId(), earliestDeparture, latestArrival, skills, returnToDepot));
}
/**
* Returns String with attributes of this vehicle
*
* <p/>
* <p>String has the following format [attr1=val1][attr2=val2]...[attrn=valn]
*/
@Override

View file

@ -36,7 +36,6 @@ public class VehicleTypeImpl implements VehicleType {
public static class VehicleCostParams {
public static VehicleTypeImpl.VehicleCostParams newInstance(double fix, double perTimeUnit, double 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();
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);
final List<String> firstRecord = new ArrayList<String>();
vra.addListener(new StrategySelectedListener() {
@ -210,7 +210,7 @@ public class JspritTest {
vra.searchSolutions();
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);
final List<String> secondRecord = new ArrayList<String>();
second.addListener(new StrategySelectedListener() {
@ -242,7 +242,7 @@ public class JspritTest {
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();
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.Parameter.THREADS, "2").buildAlgorithm();
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();
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.Parameter.THREADS, "4").buildAlgorithm();
vra.setMaxIterations(100);
@ -427,7 +427,7 @@ public class JspritTest {
vra.searchSolutions();
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.Parameter.THREADS, "5").buildAlgorithm();
second.setMaxIterations(100);
@ -460,11 +460,11 @@ public class JspritTest {
}
@Test
public void compare(){
public void compare() {
String s1 = "s2234";
String s2 = "s1";
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 {
@Test
public void itShouldRuinBreaks(){
public void itShouldRuinBreaks() {
Break aBreak = Break.Builder.newInstance("break").build();
VehicleImpl v = VehicleImpl.Builder.newInstance("v").setStartLocation(Location.newInstance("loc"))
.setBreak(aBreak).build();
@ -32,8 +32,8 @@ public class RuinBreakTest {
Assert.assertTrue(tourActivity instanceof BreakActivity);
RuinBreaks ruinBreaks = new RuinBreaks();
List<Job> unassigned = new ArrayList<Job>();
ruinBreaks.ruinEnds(Arrays.asList(route),unassigned);
Assert.assertEquals(1,unassigned.size());
Assert.assertEquals(aBreak,unassigned.get(0));
ruinBreaks.ruinEnds(Arrays.asList(route), unassigned);
Assert.assertEquals(1, unassigned.size());
Assert.assertEquals(aBreak, unassigned.get(0));
}
}

View file

@ -50,33 +50,33 @@ public class RuinClustersTest {
}
@Test
public void itShouldRuinTwoObviousClustersEvenThereAreBreaks(){
public void itShouldRuinTwoObviousClustersEvenThereAreBreaks() {
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 s2 = Service.Builder.newInstance("s2").setLocation(Location.newInstance(9,10)).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 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 s7 = Service.Builder.newInstance("s7").setLocation(Location.newInstance(9,30)).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 s4 = Service.Builder.newInstance("s4").setLocation(Location.newInstance(9, 16)).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 s7 = Service.Builder.newInstance("s7").setLocation(Location.newInstance(9, 30)).build();
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();
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();
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)
.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();
RuinClusters rc = new RuinClusters(vrp,5,n);
Collection<Job> ruined = rc.ruinRoutes(Arrays.asList(vr1,vr2));
Assert.assertEquals(5,ruined.size());
RuinClusters rc = new RuinClusters(vrp, 5, n);
Collection<Job> ruined = rc.ruinRoutes(Arrays.asList(vr1, vr2));
Assert.assertEquals(5, ruined.size());
}
}

View file

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

View file

@ -30,29 +30,27 @@ import static org.junit.Assert.*;
public class VehicleImplTest {
@Test(expected=IllegalStateException.class)
public void whenVehicleIsBuiltWithoutSettingNeitherLocationNorCoord_itThrowsAnIllegalStateException(){
@Test(expected = IllegalStateException.class)
public void whenVehicleIsBuiltWithoutSettingNeitherLocationNorCoord_itThrowsAnIllegalStateException() {
@SuppressWarnings("unused")
Vehicle v = VehicleImpl.Builder.newInstance("v").build();
}
@Test
public void whenAddingDriverBreak_itShouldBeAddedCorrectly(){
public void whenAddingDriverBreak_itShouldBeAddedCorrectly() {
VehicleTypeImpl type1 = VehicleTypeImpl.Builder.newInstance("type").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"))
.setType(type1).setEndLocation(Location.newInstance("start"))
.setBreak(aBreak).build();
assertNotNull(v.getBreak());
assertEquals(100.,v.getBreak().getTimeWindow().getStart(),0.1);
assertEquals(200.,v.getBreak().getTimeWindow().getEnd(),0.1);
assertEquals(30.,v.getBreak().getServiceDuration(),0.1);
assertEquals(100., v.getBreak().getTimeWindow().getStart(), 0.1);
assertEquals(200., v.getBreak().getTimeWindow().getEnd(), 0.1);
assertEquals(30., v.getBreak().getServiceDuration(), 0.1);
}
@Test
public void whenAddingSkills_theyShouldBeAddedCorrectly() {
VehicleTypeImpl type1 = VehicleTypeImpl.Builder.newInstance("type").build();

View file

@ -38,7 +38,6 @@ import java.util.Collection;
public class BreakExample {
public static void main(String[] args) {
@ -62,7 +61,7 @@ public class BreakExample {
VehicleImpl vehicle = vehicleBuilder.build();
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.
*/
@ -83,8 +82,8 @@ public class BreakExample {
* get the algorithm out-of-the-box.
*/
VehicleRoutingAlgorithm algorithm = Jsprit.Builder.newInstance(problem)
.setProperty(Jsprit.Strategy.CLUSTER_REGRET,"0.")
.setProperty(Jsprit.Strategy.CLUSTER_BEST,"0.").buildAlgorithm();
.setProperty(Jsprit.Strategy.CLUSTER_REGRET, "0.")
.setProperty(Jsprit.Strategy.CLUSTER_BEST, "0.").buildAlgorithm();
/*
* and search a solution
*/
@ -100,7 +99,7 @@ public class BreakExample {
/*
* plot
*/
new Plotter(problem,bestSolution).plot("output/plot","breaks");
new Plotter(problem, bestSolution).plot("output/plot", "breaks");
}