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

@ -60,12 +60,12 @@ public final class InsertionInitialSolutionFactory implements InitialSolutionFac
return solution;
}
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());
}
return jobs;
}
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());
}
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,140 +43,137 @@ 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);
private static final Logger logger = LogManager.getLogger(BreakInsertionCalculator.class);
private HardRouteConstraint hardRouteLevelConstraint;
private HardRouteConstraint hardRouteLevelConstraint;
private HardActivityConstraint hardActivityLevelConstraint;
private HardActivityConstraint hardActivityLevelConstraint;
private SoftRouteConstraint softRouteConstraint;
private SoftRouteConstraint softRouteConstraint;
private SoftActivityConstraint softActivityConstraint;
private SoftActivityConstraint softActivityConstraint;
private VehicleRoutingTransportCosts transportCosts;
private VehicleRoutingTransportCosts transportCosts;
private ActivityInsertionCostsCalculator additionalTransportCostsCalculator;
private ActivityInsertionCostsCalculator additionalTransportCostsCalculator;
private JobActivityFactory activityFactory;
private JobActivityFactory activityFactory;
private AdditionalAccessEgressCalculator additionalAccessEgressCalculator;
private AdditionalAccessEgressCalculator additionalAccessEgressCalculator;
public BreakInsertionCalculator(VehicleRoutingTransportCosts routingCosts, ActivityInsertionCostsCalculator additionalTransportCostsCalculator, ConstraintManager constraintManager) {
super();
this.transportCosts = routingCosts;
hardRouteLevelConstraint = constraintManager;
hardActivityLevelConstraint = constraintManager;
softActivityConstraint = constraintManager;
softRouteConstraint = constraintManager;
this.additionalTransportCostsCalculator = additionalTransportCostsCalculator;
additionalAccessEgressCalculator = new AdditionalAccessEgressCalculator(routingCosts);
logger.debug("initialise " + this);
}
public BreakInsertionCalculator(VehicleRoutingTransportCosts routingCosts, ActivityInsertionCostsCalculator additionalTransportCostsCalculator, ConstraintManager constraintManager) {
super();
this.transportCosts = routingCosts;
hardRouteLevelConstraint = constraintManager;
hardActivityLevelConstraint = constraintManager;
softActivityConstraint = constraintManager;
softRouteConstraint = constraintManager;
this.additionalTransportCostsCalculator = additionalTransportCostsCalculator;
additionalAccessEgressCalculator = new AdditionalAccessEgressCalculator(routingCosts);
logger.debug("initialise " + this);
}
public void setJobActivityFactory(JobActivityFactory jobActivityFactory){
public void setJobActivityFactory(JobActivityFactory jobActivityFactory) {
this.activityFactory = jobActivityFactory;
}
@Override
public String toString() {
return "[name=calculatesServiceInsertion]";
}
@Override
public String toString() {
return "[name=calculatesServiceInsertion]";
}
/**
* 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) {
/**
* 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) {
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;
BreakActivity breakAct2Insert = (BreakActivity) activityFactory.createActivities(breakToInsert).get(0);
BreakActivity breakAct2Insert = (BreakActivity) activityFactory.createActivities(breakToInsert).get(0);
insertionContext.getAssociatedActivities().add(breakAct2Insert);
/*
check hard constraints at route level
*/
if(!hardRouteLevelConstraint.fulfilled(insertionContext)){
return InsertionData.createEmptyInsertionData();
}
if (!hardRouteLevelConstraint.fulfilled(insertionContext)) {
return InsertionData.createEmptyInsertionData();
}
/*
check soft constraints at route level
*/
double additionalICostsAtRouteLevel = softRouteConstraint.getCosts(insertionContext);
double bestCost = bestKnownCosts;
double bestCost = bestKnownCosts;
additionalICostsAtRouteLevel += additionalAccessEgressCalculator.getCosts(insertionContext);
/*
generate new start and end for new vehicle
*/
Start start = new Start(newVehicle.getStartLocation(), newVehicle.getEarliestDeparture(), Double.MAX_VALUE);
start.setEndTime(newVehicleDepartureTime);
End end = new End(newVehicle.getEndLocation(), 0.0, newVehicle.getLatestArrival());
start.setEndTime(newVehicleDepartureTime);
End end = new End(newVehicle.getEndLocation(), 0.0, newVehicle.getLatestArrival());
Location bestLocation = null;
TourActivity prevAct = start;
double prevActStartTime = newVehicleDepartureTime;
int actIndex = 0;
Iterator<TourActivity> activityIterator = currentRoute.getActivities().iterator();
boolean tourEnd = false;
while(!tourEnd){
TourActivity nextAct;
if(activityIterator.hasNext()) nextAct = activityIterator.next();
else{
nextAct = end;
tourEnd = true;
}
boolean breakThis = true;
List<Location> locations = Arrays.asList( prevAct.getLocation(), nextAct.getLocation());
for(Location location : locations) {
breakAct2Insert.setLocation(location);
ConstraintsStatus status = hardActivityLevelConstraint.fulfilled(insertionContext, prevAct, breakAct2Insert, nextAct, prevActStartTime);
if (status.equals(ConstraintsStatus.FULFILLED)) {
//from job2insert induced costs at activity level
double additionalICostsAtActLevel = softActivityConstraint.getCosts(insertionContext, prevAct, breakAct2Insert, nextAct, prevActStartTime);
double additionalTransportationCosts = additionalTransportCostsCalculator.getCosts(insertionContext, prevAct, nextAct, breakAct2Insert, prevActStartTime);
if (additionalICostsAtRouteLevel + additionalICostsAtActLevel + additionalTransportationCosts < bestCost) {
bestCost = additionalICostsAtRouteLevel + additionalICostsAtActLevel + additionalTransportationCosts;
insertionIndex = actIndex;
bestLocation = location;
}
breakThis = false;
} else if (status.equals(ConstraintsStatus.NOT_FULFILLED)) {
breakThis = false;
}
}
double nextActArrTime = prevActStartTime + transportCosts.getTransportTime(prevAct.getLocation(), nextAct.getLocation(), prevActStartTime, newDriver, newVehicle);
prevActStartTime = CalculationUtils.getActivityEndTime(nextActArrTime, nextAct);
prevAct = nextAct;
actIndex++;
if(breakThis) break;
}
if(insertionIndex == InsertionData.NO_INDEX) {
return InsertionData.createEmptyInsertionData();
}
InsertionData insertionData = new InsertionData(bestCost, InsertionData.NO_INDEX, insertionIndex, newVehicle, newDriver);
breakAct2Insert.setLocation(bestLocation);
insertionData.getEvents().add(new InsertBreak(currentRoute,newVehicle,breakAct2Insert,insertionIndex));
insertionData.getEvents().add(new SwitchVehicle(currentRoute,newVehicle,newVehicleDepartureTime));
insertionData.setVehicleDepartureTime(newVehicleDepartureTime);
return insertionData;
}
Location bestLocation = null;
TourActivity prevAct = start;
double prevActStartTime = newVehicleDepartureTime;
int actIndex = 0;
Iterator<TourActivity> activityIterator = currentRoute.getActivities().iterator();
boolean tourEnd = false;
while (!tourEnd) {
TourActivity nextAct;
if (activityIterator.hasNext()) nextAct = activityIterator.next();
else {
nextAct = end;
tourEnd = true;
}
boolean breakThis = true;
List<Location> locations = Arrays.asList(prevAct.getLocation(), nextAct.getLocation());
for (Location location : locations) {
breakAct2Insert.setLocation(location);
ConstraintsStatus status = hardActivityLevelConstraint.fulfilled(insertionContext, prevAct, breakAct2Insert, nextAct, prevActStartTime);
if (status.equals(ConstraintsStatus.FULFILLED)) {
//from job2insert induced costs at activity level
double additionalICostsAtActLevel = softActivityConstraint.getCosts(insertionContext, prevAct, breakAct2Insert, nextAct, prevActStartTime);
double additionalTransportationCosts = additionalTransportCostsCalculator.getCosts(insertionContext, prevAct, nextAct, breakAct2Insert, prevActStartTime);
if (additionalICostsAtRouteLevel + additionalICostsAtActLevel + additionalTransportationCosts < bestCost) {
bestCost = additionalICostsAtRouteLevel + additionalICostsAtActLevel + additionalTransportationCosts;
insertionIndex = actIndex;
bestLocation = location;
}
breakThis = false;
} else if (status.equals(ConstraintsStatus.NOT_FULFILLED)) {
breakThis = false;
}
}
double nextActArrTime = prevActStartTime + transportCosts.getTransportTime(prevAct.getLocation(), nextAct.getLocation(), prevActStartTime, newDriver, newVehicle);
prevActStartTime = CalculationUtils.getActivityEndTime(nextActArrTime, nextAct);
prevAct = nextAct;
actIndex++;
if (breakThis) break;
}
if (insertionIndex == InsertionData.NO_INDEX) {
return InsertionData.createEmptyInsertionData();
}
InsertionData insertionData = new InsertionData(bestCost, InsertionData.NO_INDEX, insertionIndex, newVehicle, newDriver);
breakAct2Insert.setLocation(bestLocation);
insertionData.getEvents().add(new InsertBreak(currentRoute, newVehicle, breakAct2Insert, insertionIndex));
insertionData.getEvents().add(new SwitchVehicle(currentRoute, newVehicle, newVehicleDepartureTime));
insertionData.setVehicleDepartureTime(newVehicleDepartureTime);
return insertionData;
}
}

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,252 +32,251 @@ import java.util.ArrayList;
import java.util.List;
public class JobInsertionCostsCalculatorBuilder {
private static class CalculatorPlusListeners {
private static class CalculatorPlusListeners {
private JobInsertionCostsCalculator calculator;
private JobInsertionCostsCalculator calculator;
public JobInsertionCostsCalculator getCalculator() {
return calculator;
}
public JobInsertionCostsCalculator getCalculator() {
return calculator;
}
private List<PrioritizedVRAListener> algorithmListener = new ArrayList<PrioritizedVRAListener>();
private List<InsertionListener> insertionListener = new ArrayList<InsertionListener>();
private List<PrioritizedVRAListener> algorithmListener = new ArrayList<PrioritizedVRAListener>();
private List<InsertionListener> insertionListener = new ArrayList<InsertionListener>();
public CalculatorPlusListeners(JobInsertionCostsCalculator calculator) {
super();
this.calculator = calculator;
}
public CalculatorPlusListeners(JobInsertionCostsCalculator calculator) {
super();
this.calculator = calculator;
}
public List<PrioritizedVRAListener> getAlgorithmListener() {
return algorithmListener;
}
public List<PrioritizedVRAListener> getAlgorithmListener() {
return algorithmListener;
}
public List<InsertionListener> getInsertionListener() {
return insertionListener;
}
}
public List<InsertionListener> getInsertionListener() {
return insertionListener;
}
}
private List<InsertionListener> insertionListeners;
private List<InsertionListener> insertionListeners;
private List<PrioritizedVRAListener> algorithmListeners;
private List<PrioritizedVRAListener> algorithmListeners;
private VehicleRoutingProblem vrp;
private VehicleRoutingProblem vrp;
private RouteAndActivityStateGetter states;
private RouteAndActivityStateGetter states;
private boolean local = true;
private boolean local = true;
private int forwardLooking = 0;
private int forwardLooking = 0;
private int memory = 1;
private int memory = 1;
private boolean considerFixedCost = false;
private boolean considerFixedCost = false;
private double weightOfFixedCost = 0;
private double weightOfFixedCost = 0;
private VehicleFleetManager fleetManager;
private VehicleFleetManager fleetManager;
private boolean timeScheduling = false;
private boolean timeScheduling = false;
private double timeSlice;
private double timeSlice;
private int neighbors;
private int neighbors;
private ConstraintManager constraintManager;
private ConstraintManager constraintManager;
private ActivityInsertionCostsCalculator activityInsertionCostCalculator = null;
private ActivityInsertionCostsCalculator activityInsertionCostCalculator = null;
private boolean allowVehicleSwitch = true;
private boolean allowVehicleSwitch = true;
private boolean addDefaultCostCalc = true;
private boolean addDefaultCostCalc = true;
/**
* Constructs the builder.
*
* <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.
*
* @param insertionListeners
* @param algorithmListeners
*/
public JobInsertionCostsCalculatorBuilder(List<InsertionListener> insertionListeners, List<PrioritizedVRAListener> algorithmListeners) {
super();
this.insertionListeners = insertionListeners;
this.algorithmListeners = algorithmListeners;
}
/**
* 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.
*
* @param insertionListeners
* @param algorithmListeners
*/
public JobInsertionCostsCalculatorBuilder(List<InsertionListener> insertionListeners, List<PrioritizedVRAListener> algorithmListeners) {
super();
this.insertionListeners = insertionListeners;
this.algorithmListeners = algorithmListeners;
}
/**
* Sets activityStates. MUST be set.
* @param stateManager
*
* @return
*/
public JobInsertionCostsCalculatorBuilder setStateManager(RouteAndActivityStateGetter stateManager){
this.states = stateManager;
return this;
}
/**
* Sets routingProblem. MUST be set.
*
* @param vehicleRoutingProblem
* @return
*/
public JobInsertionCostsCalculatorBuilder setVehicleRoutingProblem(VehicleRoutingProblem vehicleRoutingProblem){
this.vrp = vehicleRoutingProblem;
return this;
}
/**
* Sets fleetManager. MUST be set.
*
* @param fleetManager
* @return
*/
public JobInsertionCostsCalculatorBuilder setVehicleFleetManager(VehicleFleetManager fleetManager){
this.fleetManager = fleetManager;
return this;
}
/**
* Sets a flag to build a calculator based on local calculations.
*
* <p>Insertion of a job and job-activity is evaluated based on the previous and next activity.
* @param addDefaultCostCalc
*/
public JobInsertionCostsCalculatorBuilder setLocalLevel(boolean addDefaultCostCalc){
local = true;
this.addDefaultCostCalc = addDefaultCostCalc;
/**
* Sets activityStates. MUST be set.
*
* @param stateManager
* @return
*/
public JobInsertionCostsCalculatorBuilder setStateManager(RouteAndActivityStateGetter stateManager) {
this.states = stateManager;
return this;
}
}
public JobInsertionCostsCalculatorBuilder setActivityInsertionCostsCalculator(ActivityInsertionCostsCalculator activityInsertionCostsCalculator){
this.activityInsertionCostCalculator = activityInsertionCostsCalculator;
/**
* Sets routingProblem. MUST be set.
*
* @param vehicleRoutingProblem
* @return
*/
public JobInsertionCostsCalculatorBuilder setVehicleRoutingProblem(VehicleRoutingProblem vehicleRoutingProblem) {
this.vrp = vehicleRoutingProblem;
return this;
}
}
/**
* Sets a flag to build a calculator that evaluates job insertion on route-level.
*
* @param forwardLooking
* @param memory
* @param addDefaultMarginalCostCalc
*/
public JobInsertionCostsCalculatorBuilder setRouteLevel(int forwardLooking, int memory, boolean addDefaultMarginalCostCalc){
local = false;
this.forwardLooking = forwardLooking;
this.memory = memory;
/**
* Sets fleetManager. MUST be set.
*
* @param fleetManager
* @return
*/
public JobInsertionCostsCalculatorBuilder setVehicleFleetManager(VehicleFleetManager fleetManager) {
this.fleetManager = fleetManager;
return this;
}
}
/**
* Sets a flag to consider also fixed-cost when evaluating the insertion of a job. The weight of the fixed-cost can be determined by setting
* weightofFixedCosts.
*
* @param weightOfFixedCosts
*/
public JobInsertionCostsCalculatorBuilder considerFixedCosts(double weightOfFixedCosts){
considerFixedCost = true;
this.weightOfFixedCost = weightOfFixedCosts;
/**
* 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) {
local = true;
this.addDefaultCostCalc = addDefaultCostCalc;
return this;
}
}
public JobInsertionCostsCalculatorBuilder experimentalTimeScheduler(double timeSlice, int neighbors){
timeScheduling = true;
this.timeSlice = timeSlice;
this.neighbors = neighbors;
public JobInsertionCostsCalculatorBuilder setActivityInsertionCostsCalculator(ActivityInsertionCostsCalculator activityInsertionCostsCalculator) {
this.activityInsertionCostCalculator = activityInsertionCostsCalculator;
return this;
}
}
/**
* Builds the jobInsertionCalculator.
*
* @return jobInsertionCalculator.
* @throws IllegalStateException if vrp == null or activityStates == null or fleetManager == null.
*/
public JobInsertionCostsCalculator build(){
if(vrp == null) throw new IllegalStateException("vehicle-routing-problem is null, but it must be set (this.setVehicleRoutingProblem(vrp))");
if(states == null) throw new IllegalStateException("states is null, but is must be set (this.setStateManager(states))");
if(fleetManager == null) throw new IllegalStateException("fleetManager is null, but it must be set (this.setVehicleFleetManager(fleetManager))");
JobInsertionCostsCalculator baseCalculator = null;
CalculatorPlusListeners standardLocal = null;
if(local){
standardLocal = createStandardLocal(vrp, states);
}
else{
checkServicesOnly();
standardLocal = createStandardRoute(vrp, states,forwardLooking,memory);
}
baseCalculator = standardLocal.getCalculator();
addAlgorithmListeners(standardLocal.getAlgorithmListener());
addInsertionListeners(standardLocal.getInsertionListener());
if(considerFixedCost){
CalculatorPlusListeners withFixed = createCalculatorConsideringFixedCosts(vrp, baseCalculator, states, weightOfFixedCost);
baseCalculator = withFixed.getCalculator();
addAlgorithmListeners(withFixed.getAlgorithmListener());
addInsertionListeners(withFixed.getInsertionListener());
}
if(timeScheduling){
/**
* Sets a flag to build a calculator that evaluates job insertion on route-level.
*
* @param forwardLooking
* @param memory
* @param addDefaultMarginalCostCalc
*/
public JobInsertionCostsCalculatorBuilder setRouteLevel(int forwardLooking, int memory, boolean addDefaultMarginalCostCalc) {
local = false;
this.forwardLooking = forwardLooking;
this.memory = memory;
return this;
}
/**
* Sets a flag to consider also fixed-cost when evaluating the insertion of a job. The weight of the fixed-cost can be determined by setting
* weightofFixedCosts.
*
* @param weightOfFixedCosts
*/
public JobInsertionCostsCalculatorBuilder considerFixedCosts(double weightOfFixedCosts) {
considerFixedCost = true;
this.weightOfFixedCost = weightOfFixedCosts;
return this;
}
public JobInsertionCostsCalculatorBuilder experimentalTimeScheduler(double timeSlice, int neighbors) {
timeScheduling = true;
this.timeSlice = timeSlice;
this.neighbors = neighbors;
return this;
}
/**
* Builds the jobInsertionCalculator.
*
* @return jobInsertionCalculator.
* @throws IllegalStateException if vrp == null or activityStates == null or fleetManager == null.
*/
public JobInsertionCostsCalculator build() {
if (vrp == null)
throw new IllegalStateException("vehicle-routing-problem is null, but it must be set (this.setVehicleRoutingProblem(vrp))");
if (states == null)
throw new IllegalStateException("states is null, but is must be set (this.setStateManager(states))");
if (fleetManager == null)
throw new IllegalStateException("fleetManager is null, but it must be set (this.setVehicleFleetManager(fleetManager))");
JobInsertionCostsCalculator baseCalculator = null;
CalculatorPlusListeners standardLocal = null;
if (local) {
standardLocal = createStandardLocal(vrp, states);
} else {
checkServicesOnly();
standardLocal = createStandardRoute(vrp, states, forwardLooking, memory);
}
baseCalculator = standardLocal.getCalculator();
addAlgorithmListeners(standardLocal.getAlgorithmListener());
addInsertionListeners(standardLocal.getInsertionListener());
if (considerFixedCost) {
CalculatorPlusListeners withFixed = createCalculatorConsideringFixedCosts(vrp, baseCalculator, states, weightOfFixedCost);
baseCalculator = withFixed.getCalculator();
addAlgorithmListeners(withFixed.getAlgorithmListener());
addInsertionListeners(withFixed.getInsertionListener());
}
if (timeScheduling) {
// baseCalculator = new CalculatesServiceInsertionWithTimeSchedulingInSlices(baseCalculator,timeSlice,neighbors);
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());
baseCalculator = calcPlusListeners.getCalculator();
}
return createFinalInsertion(fleetManager, baseCalculator, states);
}
}
return createFinalInsertion(fleetManager, baseCalculator, states);
}
private void checkServicesOnly() {
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");
}
}
private void checkServicesOnly() {
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");
}
}
}
}
private void addInsertionListeners(List<InsertionListener> list) {
for(InsertionListener iL : list){
insertionListeners.add(iL);
}
}
private void addInsertionListeners(List<InsertionListener> list) {
for (InsertionListener iL : list) {
insertionListeners.add(iL);
}
}
private void addAlgorithmListeners(List<PrioritizedVRAListener> list) {
for(PrioritizedVRAListener aL : list){
algorithmListeners.add(aL);
}
}
private void addAlgorithmListeners(List<PrioritizedVRAListener> 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){
actInsertionCalc = new LocalActivityInsertionCostsCalculator(vrp.getTransportCosts(), vrp.getActivityCosts(), statesManager);
configLocal = new ConfigureLocalActivityInsertionCalculator(vrp, (LocalActivityInsertionCostsCalculator) actInsertionCalc);
}
else if(activityInsertionCostCalculator == null && !addDefaultCostCalc){
actInsertionCalc = new ActivityInsertionCostsCalculator(){
ActivityInsertionCostsCalculator actInsertionCalc;
ConfigureLocalActivityInsertionCalculator configLocal = null;
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() {
@Override
public double getCosts(JobInsertionContext iContext, TourActivity prevAct, TourActivity nextAct, TourActivity newAct,
@Override
public double getCosts(JobInsertionContext iContext, TourActivity prevAct, TourActivity nextAct, TourActivity newAct,
double depTimeAtPrevAct) {
return 0.;
}
return 0.;
}
};
}
else{
actInsertionCalc = activityInsertionCostCalculator;
}
};
} else {
actInsertionCalc = activityInsertionCostCalculator;
}
JobActivityFactory activityFactory = new JobActivityFactory() {
@ -287,63 +286,61 @@ public class JobInsertionCostsCalculatorBuilder {
}
};
ShipmentInsertionCalculator shipmentInsertion = new ShipmentInsertionCalculator(vrp.getTransportCosts(), actInsertionCalc, constraintManager);
ShipmentInsertionCalculator shipmentInsertion = new ShipmentInsertionCalculator(vrp.getTransportCosts(), actInsertionCalc, constraintManager);
shipmentInsertion.setJobActivityFactory(activityFactory);
ServiceInsertionCalculator serviceInsertion = new ServiceInsertionCalculator(vrp.getTransportCosts(), actInsertionCalc, constraintManager);
ServiceInsertionCalculator serviceInsertion = new ServiceInsertionCalculator(vrp.getTransportCosts(), actInsertionCalc, constraintManager);
serviceInsertion.setJobActivityFactory(activityFactory);
BreakInsertionCalculator breakInsertionCalculator = new BreakInsertionCalculator(vrp.getTransportCosts(), actInsertionCalc, constraintManager);
breakInsertionCalculator.setJobActivityFactory(activityFactory);
BreakInsertionCalculator breakInsertionCalculator = new BreakInsertionCalculator(vrp.getTransportCosts(), actInsertionCalc, constraintManager);
breakInsertionCalculator.setJobActivityFactory(activityFactory);
JobCalculatorSwitcher switcher = new JobCalculatorSwitcher();
switcher.put(Shipment.class, shipmentInsertion);
switcher.put(Service.class, serviceInsertion);
switcher.put(Pickup.class, serviceInsertion);
switcher.put(Delivery.class, serviceInsertion);
switcher.put(Break.class, breakInsertionCalculator);
switcher.put(Shipment.class, shipmentInsertion);
switcher.put(Service.class, serviceInsertion);
switcher.put(Pickup.class, serviceInsertion);
switcher.put(Delivery.class, serviceInsertion);
switcher.put(Break.class, breakInsertionCalculator);
CalculatorPlusListeners calculatorPlusListeners = new CalculatorPlusListeners(switcher);
if(configLocal != null){
calculatorPlusListeners.insertionListener.add(configLocal);
}
return calculatorPlusListeners;
}
CalculatorPlusListeners calculatorPlusListeners = new CalculatorPlusListeners(switcher);
if (configLocal != null) {
calculatorPlusListeners.insertionListener.add(configLocal);
}
return calculatorPlusListeners;
}
private CalculatorPlusListeners createCalculatorConsideringFixedCosts(VehicleRoutingProblem vrp, JobInsertionCostsCalculator baseCalculator, RouteAndActivityStateGetter activityStates2, double weightOfFixedCosts){
final JobInsertionConsideringFixCostsCalculator withFixCost = new JobInsertionConsideringFixCostsCalculator(baseCalculator, activityStates2);
withFixCost.setWeightOfFixCost(weightOfFixedCosts);
CalculatorPlusListeners calcPlusListeners = new CalculatorPlusListeners(withFixCost);
calcPlusListeners.getInsertionListener().add(new ConfigureFixCostCalculator(vrp, withFixCost));
return calcPlusListeners;
}
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);
calcPlusListeners.getInsertionListener().add(new ConfigureFixCostCalculator(vrp, withFixCost));
return calcPlusListeners;
}
private CalculatorPlusListeners createStandardRoute(final VehicleRoutingProblem vrp, RouteAndActivityStateGetter activityStates2, int forwardLooking, int solutionMemory){
ActivityInsertionCostsCalculator routeLevelCostEstimator;
if(activityInsertionCostCalculator == null && addDefaultCostCalc){
private CalculatorPlusListeners createStandardRoute(final VehicleRoutingProblem vrp, RouteAndActivityStateGetter activityStates2, int forwardLooking, int solutionMemory) {
ActivityInsertionCostsCalculator routeLevelCostEstimator;
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,
@Override
public double getCosts(JobInsertionContext iContext, TourActivity prevAct, TourActivity nextAct, TourActivity newAct,
double depTimeAtPrevAct) {
return 0.;
}
return 0.;
}
};
}
else{
routeLevelCostEstimator = activityInsertionCostCalculator;
}
};
} else {
routeLevelCostEstimator = activityInsertionCostCalculator;
}
ServiceInsertionOnRouteLevelCalculator jobInsertionCalculator = new ServiceInsertionOnRouteLevelCalculator(vrp.getTransportCosts(), vrp.getActivityCosts(), routeLevelCostEstimator, constraintManager, constraintManager);
jobInsertionCalculator.setNuOfActsForwardLooking(forwardLooking);
jobInsertionCalculator.setMemorySize(solutionMemory);
jobInsertionCalculator.setStates(activityStates2);
jobInsertionCalculator.setNuOfActsForwardLooking(forwardLooking);
jobInsertionCalculator.setMemorySize(solutionMemory);
jobInsertionCalculator.setStates(activityStates2);
jobInsertionCalculator.setJobActivityFactory(new JobActivityFactory() {
@Override
public List<AbstractActivity> createActivities(Job job) {
@ -351,23 +348,23 @@ public class JobInsertionCostsCalculatorBuilder {
}
});
return new CalculatorPlusListeners(jobInsertionCalculator);
}
}
private JobInsertionCostsCalculator createFinalInsertion(VehicleFleetManager fleetManager, JobInsertionCostsCalculator baseCalc, RouteAndActivityStateGetter activityStates2){
VehicleTypeDependentJobInsertionCalculator vehicleTypeDependentJobInsertionCalculator = new VehicleTypeDependentJobInsertionCalculator(vrp, fleetManager, baseCalc);
vehicleTypeDependentJobInsertionCalculator.setVehicleSwitchAllowed(allowVehicleSwitch);
return vehicleTypeDependentJobInsertionCalculator;
}
private JobInsertionCostsCalculator createFinalInsertion(VehicleFleetManager fleetManager, JobInsertionCostsCalculator baseCalc, RouteAndActivityStateGetter activityStates2) {
VehicleTypeDependentJobInsertionCalculator vehicleTypeDependentJobInsertionCalculator = new VehicleTypeDependentJobInsertionCalculator(vrp, fleetManager, baseCalc);
vehicleTypeDependentJobInsertionCalculator.setVehicleSwitchAllowed(allowVehicleSwitch);
return vehicleTypeDependentJobInsertionCalculator;
}
public JobInsertionCostsCalculatorBuilder setConstraintManager(ConstraintManager constraintManager) {
this.constraintManager = constraintManager;
public JobInsertionCostsCalculatorBuilder setConstraintManager(ConstraintManager constraintManager) {
this.constraintManager = constraintManager;
return this;
}
}
public JobInsertionCostsCalculatorBuilder setAllowVehicleSwitch(boolean allowVehicleSwitch) {
public JobInsertionCostsCalculatorBuilder setAllowVehicleSwitch(boolean allowVehicleSwitch) {
this.allowVehicleSwitch = allowVehicleSwitch;
return this;
}
}
}

View file

@ -1,4 +1,3 @@
/*******************************************************************************
* Copyright (C) 2014 Stefan Schroeder
*
@ -32,82 +31,80 @@ import jsprit.core.util.CalculationUtils;
* Calculates activity insertion costs locally, i.e. by comparing the additional costs of insertion the new activity k between
* 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;
private VehicleRoutingTransportCosts routingCosts;
private VehicleRoutingActivityCosts activityCosts;
private VehicleRoutingActivityCosts activityCosts;
private double activityCostsWeight = 1.;
private double activityCostsWeight = 1.;
private double solutionCompletenessRatio = 1.;
private double solutionCompletenessRatio = 1.;
private RouteAndActivityStateGetter stateManager;
private RouteAndActivityStateGetter stateManager;
public LocalActivityInsertionCostsCalculator(VehicleRoutingTransportCosts routingCosts, VehicleRoutingActivityCosts actCosts, RouteAndActivityStateGetter stateManager) {
super();
this.routingCosts = routingCosts;
this.activityCosts = actCosts;
this.stateManager = stateManager;
}
public LocalActivityInsertionCostsCalculator(VehicleRoutingTransportCosts routingCosts, VehicleRoutingActivityCosts actCosts, RouteAndActivityStateGetter stateManager) {
super();
this.routingCosts = routingCosts;
this.activityCosts = actCosts;
this.stateManager = stateManager;
}
@Override
public double getCosts(JobInsertionContext iFacts, TourActivity prevAct, TourActivity nextAct, TourActivity newAct, double depTimeAtPrevAct) {
@Override
public double getCosts(JobInsertionContext iFacts, TourActivity prevAct, TourActivity nextAct, TourActivity newAct, double depTimeAtPrevAct) {
double tp_costs_prevAct_newAct = routingCosts.getTransportCost(prevAct.getLocation(), newAct.getLocation(), depTimeAtPrevAct, iFacts.getNewDriver(), iFacts.getNewVehicle());
double tp_time_prevAct_newAct = routingCosts.getTransportTime(prevAct.getLocation(), newAct.getLocation(), depTimeAtPrevAct, iFacts.getNewDriver(), iFacts.getNewVehicle());
double newAct_arrTime = depTimeAtPrevAct + tp_time_prevAct_newAct;
double newAct_endTime = CalculationUtils.getActivityEndTime(newAct_arrTime, newAct);
double tp_costs_prevAct_newAct = routingCosts.getTransportCost(prevAct.getLocation(), newAct.getLocation(), depTimeAtPrevAct, iFacts.getNewDriver(), iFacts.getNewVehicle());
double tp_time_prevAct_newAct = routingCosts.getTransportTime(prevAct.getLocation(), newAct.getLocation(), depTimeAtPrevAct, iFacts.getNewDriver(), iFacts.getNewVehicle());
double newAct_arrTime = depTimeAtPrevAct + tp_time_prevAct_newAct;
double newAct_endTime = CalculationUtils.getActivityEndTime(newAct_arrTime, newAct);
double act_costs_newAct = activityCosts.getActivityCost(newAct, newAct_arrTime, iFacts.getNewDriver(), iFacts.getNewVehicle());
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());
double nextAct_arrTime = newAct_endTime + tp_time_newAct_nextAct;
double endTime_nextAct_new = CalculationUtils.getActivityEndTime(nextAct_arrTime, nextAct);
double act_costs_nextAct = activityCosts.getActivityCost(nextAct, nextAct_arrTime, iFacts.getNewDriver(), iFacts.getNewVehicle());
double tp_costs_newAct_nextAct = routingCosts.getTransportCost(newAct.getLocation(), nextAct.getLocation(), newAct_endTime, iFacts.getNewDriver(), iFacts.getNewVehicle());
double tp_time_newAct_nextAct = routingCosts.getTransportTime(newAct.getLocation(), nextAct.getLocation(), newAct_endTime, iFacts.getNewDriver(), iFacts.getNewVehicle());
double nextAct_arrTime = newAct_endTime + tp_time_newAct_nextAct;
double endTime_nextAct_new = CalculationUtils.getActivityEndTime(nextAct_arrTime, nextAct);
double act_costs_nextAct = activityCosts.getActivityCost(nextAct, nextAct_arrTime, iFacts.getNewDriver(), iFacts.getNewVehicle());
double totalCosts = tp_costs_prevAct_newAct + tp_costs_newAct_nextAct + 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.;
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{
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 actCost_nextAct = activityCosts.getActivityCost(nextAct, arrTime_nextAct, iFacts.getRoute().getDriver(), iFacts.getRoute().getVehicle());
double oldCosts = 0.;
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 {
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 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 futureWaiting = stateManager.getActivityState(nextAct, iFacts.getRoute().getVehicle(), InternalStates.FUTURE_WAITING, Double.class);
if (futureWaiting == null) futureWaiting = 0.;
double waitingTime_savings_timeUnit = Math.min(futureWaiting, endTimeDelay_nextAct);
double waitingTime_savings = waitingTime_savings_timeUnit * iFacts.getRoute().getVehicle().getType().getVehicleCostParams().perWaitingTimeUnit;
oldCosts += solutionCompletenessRatio * activityCostsWeight * waitingTime_savings;
oldCosts += tp_costs_prevAct_nextAct + solutionCompletenessRatio * activityCostsWeight * actCost_nextAct;
}
return totalCosts - oldCosts;
}
double endTimeDelay_nextAct = Math.max(0, endTime_nextAct_new - endTime_nextAct_old);
Double futureWaiting = stateManager.getActivityState(nextAct, iFacts.getRoute().getVehicle(), InternalStates.FUTURE_WAITING, Double.class);
if (futureWaiting == null) futureWaiting = 0.;
double waitingTime_savings_timeUnit = Math.min(futureWaiting, endTimeDelay_nextAct);
double waitingTime_savings = waitingTime_savings_timeUnit * iFacts.getRoute().getVehicle().getType().getVehicleCostParams().perWaitingTimeUnit;
oldCosts += solutionCompletenessRatio * activityCostsWeight * waitingTime_savings;
oldCosts += tp_costs_prevAct_nextAct + solutionCompletenessRatio * activityCostsWeight * actCost_nextAct;
}
return totalCosts - oldCosts;
}
private boolean toDepot(Vehicle newVehicle) {
return newVehicle.isReturnToDepot();
}
private boolean toDepot(Vehicle newVehicle) {
return newVehicle.isReturnToDepot();
}
private boolean isEnd(TourActivity nextAct) {
return nextAct instanceof End;
}
private boolean isEnd(TourActivity nextAct) {
return nextAct instanceof End;
}
public void setSolutionCompletenessRatio(double solutionCompletenessRatio) {
this.solutionCompletenessRatio = solutionCompletenessRatio;
}
public void setSolutionCompletenessRatio(double solutionCompletenessRatio) {
this.solutionCompletenessRatio = solutionCompletenessRatio;
}
}

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 {
@ -92,138 +91,137 @@ public class RegretInsertion extends AbstractInsertionStrategy {
}
}
/**
* Scorer to include other impacts on score such as time-window length or distance to depot.
*
* @author schroeder
*
*/
static interface ScoringFunction {
/**
* Scorer to include other impacts on score such as time-window length or distance to depot.
*
* @author schroeder
*/
static interface ScoringFunction {
public double score(InsertionData best, Job job);
public double score(InsertionData best, Job job);
}
}
/**
* Scorer that includes the length of the time-window when scoring a job. The wider the time-window, the lower the score.
*
* <p>This is the default scorer, i.e.: score = (secondBest - firstBest) + this.TimeWindowScorer.score(job)
*
* @author schroeder
*
*/
public static class DefaultScorer implements ScoringFunction {
/**
* 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)
getDistance(best.getSelectedVehicle().getStartLocation(), location),
getDistance(best.getSelectedVehicle().getEndLocation(), location)
);
}
return Math.max(tw_param * (((Service)job).getTimeWindow().getEnd() - ((Service)job).getTimeWindow().getStart()),minTimeWindowScore) +
depotDistance_param * maxDepotDistance;
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 + "]";
}
@Override
public String toString() {
return "[name=defaultScorer][twParam=" + tw_param + "][depotDistanceParam=" + depotDistance_param + "]";
}
}
}
private static Logger logger = LogManager.getLogger(RegretInsertion.class);
private ScoringFunction scoringFunction;
private ScoringFunction scoringFunction;
private JobInsertionCostsCalculator insertionCostsCalculator;
/**
* Sets the scoring function.
*
* <p>By default, the this.TimeWindowScorer is used.
*
* @param scoringFunction to score
*/
public void setScoringFunction(ScoringFunction scoringFunction) {
this.scoringFunction = scoringFunction;
}
* Sets the scoring function.
* <p/>
* <p>By default, the this.TimeWindowScorer is used.
*
* @param scoringFunction to score
*/
public void setScoringFunction(ScoringFunction scoringFunction) {
this.scoringFunction = scoringFunction;
}
public RegretInsertion(JobInsertionCostsCalculator jobInsertionCalculator, VehicleRoutingProblem vehicleRoutingProblem) {
super(vehicleRoutingProblem);
public RegretInsertion(JobInsertionCostsCalculator jobInsertionCalculator, VehicleRoutingProblem vehicleRoutingProblem) {
super(vehicleRoutingProblem);
this.scoringFunction = new DefaultScorer(vehicleRoutingProblem);
this.insertionCostsCalculator = jobInsertionCalculator;
this.insertionCostsCalculator = jobInsertionCalculator;
this.vrp = vehicleRoutingProblem;
logger.debug("initialise {}", this);
}
@Override
public String toString() {
return "[name=regretInsertion][additionalScorer="+scoringFunction+"]";
}
@Override
public String toString() {
return "[name=regretInsertion][additionalScorer=" + scoringFunction + "]";
}
/**
* Runs insertion.
*
* <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) {
/**
* 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) {
List<Job> badJobs = new ArrayList<Job>(unassignedJobs.size());
List<Job> jobs = new ArrayList<Job>(unassignedJobs);
@ -231,14 +229,14 @@ public class RegretInsertion extends AbstractInsertionStrategy {
List<Job> unassignedJobList = new ArrayList<Job>(jobs);
List<Job> 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){
throw new IllegalStateException("cannot insert job " + unassignedJob.getId());
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;
0., null, r.getVehicle());
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,38 +25,38 @@ 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;
private StateManager states;
private VehicleRoute route;
private VehicleRoute route;
private VehicleRoutingTransportCosts transportCosts;
private VehicleRoutingTransportCosts transportCosts;
private double futureWaiting;
private double futureWaiting;
public UpdateFutureWaitingTimes(StateManager states, VehicleRoutingTransportCosts tpCosts) {
super();
this.states = states;
this.transportCosts = tpCosts;
}
public UpdateFutureWaitingTimes(StateManager states, VehicleRoutingTransportCosts tpCosts) {
super();
this.states = states;
this.transportCosts = tpCosts;
}
@Override
public void begin(VehicleRoute route) {
this.route = route;
this.futureWaiting = 0.;
}
@Override
public void begin(VehicleRoute route) {
this.route = route;
this.futureWaiting = 0.;
}
@Override
public void visit(TourActivity activity) {
states.putInternalTypedActivityState(activity,route.getVehicle(),InternalStates.FUTURE_WAITING,futureWaiting);
@Override
public void visit(TourActivity activity) {
states.putInternalTypedActivityState(activity, route.getVehicle(), InternalStates.FUTURE_WAITING, futureWaiting);
// if(!(activity instanceof BreakActivity)) {
futureWaiting += Math.max(activity.getTheoreticalEarliestOperationStartTime() - activity.getArrTime(), 0);
futureWaiting += Math.max(activity.getTheoreticalEarliestOperationStartTime() - activity.getArrTime(), 0);
// }
}
}
@Override
public void finish() {}
@Override
public void finish() {
}
}

View file

@ -42,73 +42,69 @@ 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 {
/**
* Builder to build the routing-problem.
*
* @author stefan schroeder
*
*/
public static class Builder {
/**
* 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(); }
* Returns a new instance of this builder.
*
* @return builder
*/
public static Builder newInstance() {
return new Builder();
}
private VehicleRoutingTransportCosts transportCosts;
private VehicleRoutingTransportCosts transportCosts;
private VehicleRoutingActivityCosts activityCosts = new WaitingTimeCosts();
private VehicleRoutingActivityCosts activityCosts = new WaitingTimeCosts();
private Map<String,Job> jobs = new LinkedHashMap<String, Job>();
private Map<String, Job> jobs = new LinkedHashMap<String, Job>();
private Map<String,Job> tentativeJobs = new LinkedHashMap<String,Job>();
private Map<String, Job> tentativeJobs = new LinkedHashMap<String, Job>();
private Set<String> jobsInInitialRoutes = new HashSet<String>();
private Set<String> jobsInInitialRoutes = new HashSet<String>();
private Map<String, Coordinate> tentative_coordinates = new HashMap<String, Coordinate>();
private Map<String, Coordinate> tentative_coordinates = new HashMap<String, Coordinate>();
private FleetSize fleetSize = FleetSize.INFINITE;
private FleetSize fleetSize = FleetSize.INFINITE;
private Collection<VehicleType> vehicleTypes = new ArrayList<VehicleType>();
private Collection<VehicleType> vehicleTypes = new ArrayList<VehicleType>();
private Collection<VehicleRoute> initialRoutes = new ArrayList<VehicleRoute>();
private Collection<VehicleRoute> initialRoutes = new ArrayList<VehicleRoute>();
private Set<Vehicle> uniqueVehicles = new HashSet<Vehicle>();
private Set<Vehicle> uniqueVehicles = new HashSet<Vehicle>();
private boolean hasBreaks = false;
private boolean hasBreaks = false;
private JobActivityFactory jobActivityFactory = new JobActivityFactory() {
private JobActivityFactory jobActivityFactory = new JobActivityFactory() {
@Override
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));
}
return acts;
return acts;
}
};
@ -121,97 +117,98 @@ 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(){
return Collections.unmodifiableMap(tentative_coordinates);
}
/**
* Returns the unmodifiable map of collected locations (mapped by their location-id).
*
* @return map with locations
*/
public Map<String, Coordinate> getLocationMap() {
return Collections.unmodifiableMap(tentative_coordinates);
}
/**
* Returns the locations collected SO FAR by this builder.
*
* <p>Locations are cached when adding a shipment, service, depot, vehicle.
*
* @return locations
*
**/
public Locations getLocations(){
return new Locations() {
/**
* 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() {
return new Locations() {
@Override
public Coordinate getCoord(String id) {
return tentative_coordinates.get(id);
}
@Override
public Coordinate getCoord(String id) {
return tentative_coordinates.get(id);
}
};
}
};
}
/**
* Sets routing costs.
*
* @param costs the routingCosts
* @return builder
* @see VehicleRoutingTransportCosts
*/
public Builder setRoutingCost(VehicleRoutingTransportCosts costs){
this.transportCosts = costs;
return this;
}
/**
* Sets routing costs.
*
* @param costs the routingCosts
* @return builder
* @see VehicleRoutingTransportCosts
*/
public Builder setRoutingCost(VehicleRoutingTransportCosts costs) {
this.transportCosts = costs;
return this;
}
/**
* Sets the type of fleetSize.
*
* <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){
this.fleetSize = fleetSize;
return this;
}
/**
* Adds a job which is either a service or a shipment.
*
* <p>Note that job.getId() must be unique, i.e. no job (either it is a shipment or a service) is allowed to have an already allocated id.
*
* @param job job to be added
* @return this builder
* @throws IllegalStateException if job is neither a shipment nor a service, or jobId has already been added.
* @deprecated use addJob(AbstractJob job) instead
*/
@Deprecated
public Builder addJob(Job job) {
if(!(job instanceof AbstractJob)) throw new IllegalArgumentException("job must be of type AbstractJob");
return addJob((AbstractJob)job);
}
/**
* 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) {
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
* @return this builder
* @throws IllegalStateException if job is neither a shipment nor a service, or jobId has already been added.
* @deprecated use addJob(AbstractJob job) instead
*/
@Deprecated
public Builder addJob(Job job) {
if (!(job instanceof AbstractJob)) throw new IllegalArgumentException("job must be of type AbstractJob");
return addJob((AbstractJob) job);
}
/**
* Adds a job which is either a service or a shipment.
* <p/>
* <p>Note that job.getId() must be unique, i.e. no job (either it is a shipment or a service) is allowed to have an already allocated id.
*
* @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);
@ -228,47 +227,45 @@ public class VehicleRoutingProblem {
return this;
}
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;
tentative_coordinates.put(shipment.getPickupLocation().getId(), shipment.getPickupLocation().getCoordinate());
tentative_coordinates.put(shipment.getDeliveryLocation().getId(), shipment.getDeliveryLocation().getCoordinate());
}
}
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;
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;
addService(service);
} 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(){
boolean hasBreaks = false;
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));
}
}
return hasBreaks;
}
private boolean addBreaksToActivityMap() {
boolean hasBreaks = false;
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));
}
}
return hasBreaks;
}
/**
* Adds an initial vehicle route.
@ -276,25 +273,26 @@ 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);
registerJobAndActivity(abstractAct, job);
}
}
initialRoutes.add(route);
return this;
}
initialRoutes.add(route);
return this;
}
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){
addInitialVehicleRoute(r);
}
return this;
}
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."); }
tentative_coordinates.put(job.getPickupLocation().getId(), job.getPickupLocation().getCoordinate());
tentative_coordinates.put(job.getDeliveryLocation().getId(), job.getDeliveryLocation().getCoordinate());
jobs.put(job.getId(),job);
}
/**
* Adds a vehicle.
*
*
* @param vehicle vehicle to be added
* @return this builder
* @deprecated use addVehicle(AbstractVehicle vehicle) instead
*/
@Deprecated
public Builder addVehicle(Vehicle vehicle) {
if(!(vehicle instanceof AbstractVehicle)) throw new IllegalStateException("vehicle must be an AbstractVehicle");
return addVehicle((AbstractVehicle)vehicle);
}
private void addShipment(Shipment 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);
}
/**
* Adds a vehicle.
*
* @param vehicle vehicle to be added
* @return this builder
* @deprecated use addVehicle(AbstractVehicle vehicle) instead
*/
@Deprecated
public Builder addVehicle(Vehicle vehicle) {
if (!(vehicle instanceof AbstractVehicle))
throw new IllegalStateException("vehicle must be an AbstractVehicle");
return addVehicle((AbstractVehicle) vehicle);
}
/**
* Adds a vehicle.
*
* @param vehicle vehicle to be added
* @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;
@ -382,162 +380,164 @@ public class VehicleRoutingProblem {
}
/**
* Sets the activity-costs.
*
* <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){
this.activityCosts = activityCosts;
return this;
}
* 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) {
this.activityCosts = activityCosts;
return this;
}
/**
* Builds the {@link VehicleRoutingProblem}.
*
* <p>If {@link VehicleRoutingTransportCosts} are not set, {@link CrowFlyCosts} is used.
*
* @return {@link VehicleRoutingProblem}
*/
public VehicleRoutingProblem build() {
if(transportCosts == null){
transportCosts = new CrowFlyCosts(getLocations());
}
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.");
return new VehicleRoutingProblem(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) {
transportCosts = new CrowFlyCosts(getLocations());
}
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.");
return new VehicleRoutingProblem(this);
}
@SuppressWarnings("UnusedDeclaration")
public Builder addLocation(String locationId, Coordinate coordinate) {
tentative_coordinates.put(locationId, coordinate);
return this;
}
tentative_coordinates.put(locationId, coordinate);
return this;
}
/**
* Adds a collection of jobs.
*
* @param jobs which is a collection of jobs that subclasses Job
* @return this builder
*/
@SuppressWarnings("deprecation")
/**
* Adds a collection of jobs.
*
* @param jobs which is a collection of jobs that subclasses Job
* @return this builder
*/
@SuppressWarnings("deprecation")
public Builder addAllJobs(Collection<? extends Job> jobs) {
for(Job j : jobs){
addJob(j);
}
return this;
}
for (Job j : jobs) {
addJob(j);
}
return this;
}
/**
* Adds a collection of vehicles.
*
* @param vehicles vehicles to be added
* @return this builder
*/
@SuppressWarnings("deprecation")
/**
* Adds a collection of vehicles.
*
* @param vehicles vehicles to be added
* @return this builder
*/
@SuppressWarnings("deprecation")
public Builder addAllVehicles(Collection<? extends Vehicle> vehicles) {
for(Vehicle v : vehicles){
addVehicle(v);
}
return this;
}
for (Vehicle v : vehicles) {
addVehicle(v);
}
return this;
}
/**
* Gets an unmodifiable collection of already added vehicles.
*
* @return collection of vehicles
*/
public Collection<Vehicle> getAddedVehicles(){
return Collections.unmodifiableCollection(uniqueVehicles);
}
/**
* Gets an unmodifiable collection of already added vehicles.
*
* @return collection of vehicles
*/
public Collection<Vehicle> getAddedVehicles() {
return Collections.unmodifiableCollection(uniqueVehicles);
}
/**
* Gets an unmodifiable collection of already added vehicle-types.
*
* @return collection of vehicle-types
*/
public Collection<VehicleType> getAddedVehicleTypes(){
return Collections.unmodifiableCollection(vehicleTypes);
}
/**
* Gets an unmodifiable collection of already added vehicle-types.
*
* @return collection of vehicle-types
*/
public Collection<VehicleType> getAddedVehicleTypes() {
return Collections.unmodifiableCollection(vehicleTypes);
}
/**
* Returns an unmodifiable collection of already added jobs.
*
* @return collection of jobs
*/
public Collection<Job> getAddedJobs(){
return Collections.unmodifiableCollection(tentativeJobs.values());
}
public Collection<Job> getAddedJobs() {
return Collections.unmodifiableCollection(tentativeJobs.values());
}
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);
return this;
}
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);
return this;
}
}
}
/**
* Enum that characterizes the fleet-size.
*
* @author sschroeder
*
*/
public static enum FleetSize {
FINITE, INFINITE
}
/**
* Enum that characterizes the fleet-size.
*
* @author sschroeder
*/
public static enum FleetSize {
FINITE, INFINITE
}
/**
* logger logging for this class
*/
private final static Logger logger = LogManager.getLogger(VehicleRoutingProblem.class);
/**
* logger logging for this class
*/
private final static Logger logger = LogManager.getLogger(VehicleRoutingProblem.class);
/**
* contains transportation costs, i.e. the costs traveling from location A to B
*/
private final VehicleRoutingTransportCosts transportCosts;
/**
* contains transportation costs, i.e. the costs traveling from location A to B
*/
private final VehicleRoutingTransportCosts transportCosts;
/**
* contains activity costs, i.e. the costs imposed by an activity
*/
private final VehicleRoutingActivityCosts activityCosts;
/**
* contains activity costs, i.e. the costs imposed by an activity
*/
private final VehicleRoutingActivityCosts activityCosts;
/**
* map of jobs, stored by jobId
*/
private final Map<String, Job> jobs;
/**
* map of jobs, stored by jobId
*/
private final Map<String, Job> jobs;
/**
* Collection that contains available vehicles.
*/
private final Collection<Vehicle> vehicles;
/**
* Collection that contains available vehicles.
*/
private final Collection<Vehicle> vehicles;
/**
* Collection that contains all available types.
*/
private final Collection<VehicleType> vehicleTypes;
/**
* Collection that contains all available types.
*/
private final Collection<VehicleType> vehicleTypes;
private final Collection<VehicleRoute> initialVehicleRoutes;
private final Collection<VehicleRoute> initialVehicleRoutes;
/**
* An enum that indicates type of fleetSize. By default, it is INFINTE
*/
private final FleetSize fleetSize;
/**
* An enum that indicates type of fleetSize. By default, it is INFINTE
*/
private final FleetSize fleetSize;
private final Locations locations;
private final Locations locations;
private Map<Job,List<AbstractActivity>> activityMap;
private Map<Job, List<AbstractActivity>> activityMap;
private int nuActivities;
@ -550,121 +550,123 @@ public class VehicleRoutingProblem {
};
private VehicleRoutingProblem(Builder builder) {
this.jobs = builder.jobs;
this.fleetSize = builder.fleetSize;
this.vehicles=builder.uniqueVehicles;
this.vehicleTypes = builder.vehicleTypes;
this.initialVehicleRoutes = builder.initialRoutes;
this.transportCosts = builder.transportCosts;
this.activityCosts = builder.activityCosts;
this.locations = builder.getLocations();
private VehicleRoutingProblem(Builder builder) {
this.jobs = builder.jobs;
this.fleetSize = builder.fleetSize;
this.vehicles = builder.uniqueVehicles;
this.vehicleTypes = builder.vehicleTypes;
this.initialVehicleRoutes = builder.initialRoutes;
this.transportCosts = builder.transportCosts;
this.activityCosts = builder.activityCosts;
this.locations = builder.getLocations();
this.activityMap = builder.activityMap;
this.nuActivities = builder.activityIndexCounter;
logger.info("setup problem: {}", this);
}
@Override
public String toString() {
return "[fleetSize="+fleetSize+"][#jobs="+jobs.size()+"][#vehicles="+vehicles.size()+"][#vehicleTypes="+vehicleTypes.size()+"]["+
"transportCost="+transportCosts+"][activityCosts="+activityCosts+"]";
}
public String toString() {
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>By default, it is INFINITE.
*
* @return either FleetSize.INFINITE or FleetSize.FINITE
*/
public FleetSize getFleetSize() {
return fleetSize;
}
/**
* Returns type of fleetSize, either INFINITE or FINITE.
* <p/>
* <p>By default, it is INFINITE.
*
* @return either FleetSize.INFINITE or FleetSize.FINITE
*/
public FleetSize getFleetSize() {
return fleetSize;
}
/**
* Returns the unmodifiable job map.
*
* @return unmodifiable jobMap
*/
public Map<String, Job> getJobs() {
return Collections.unmodifiableMap(jobs);
}
/**
* Returns the unmodifiable job map.
*
* @return unmodifiable jobMap
*/
public Map<String, Job> getJobs() {
return Collections.unmodifiableMap(jobs);
}
/**
* Returns a copy of initial vehicle routes.
*
* @return copied collection of initial vehicle routes
*/
public Collection<VehicleRoute> getInitialVehicleRoutes(){
Collection<VehicleRoute> copiedInitialRoutes = new ArrayList<VehicleRoute>();
for(VehicleRoute route : initialVehicleRoutes){
public Collection<VehicleRoute> getInitialVehicleRoutes() {
Collection<VehicleRoute> copiedInitialRoutes = new ArrayList<VehicleRoute>();
for (VehicleRoute route : initialVehicleRoutes) {
copiedInitialRoutes.add(VehicleRoute.copyOf(route));
}
return copiedInitialRoutes;
}
}
/**
* Returns the entire, unmodifiable collection of types.
*
* @return unmodifiable collection of types
* @see VehicleTypeImpl
*/
public Collection<VehicleType> getTypes(){
return Collections.unmodifiableCollection(vehicleTypes);
}
/**
* Returns the entire, unmodifiable collection of types.
*
* @return unmodifiable collection of types
* @see VehicleTypeImpl
*/
public Collection<VehicleType> getTypes() {
return Collections.unmodifiableCollection(vehicleTypes);
}
/**
* Returns the entire, unmodifiable collection of vehicles.
*
* @return unmodifiable collection of vehicles
* @see Vehicle
*/
public Collection<Vehicle> getVehicles() {
return Collections.unmodifiableCollection(vehicles);
}
/**
* Returns the entire, unmodifiable collection of vehicles.
*
* @return unmodifiable collection of vehicles
* @see Vehicle
*/
public Collection<Vehicle> getVehicles() {
return Collections.unmodifiableCollection(vehicles);
}
/**
* Returns routing costs.
*
* @return routingCosts
* @see VehicleRoutingTransportCosts
*/
public VehicleRoutingTransportCosts getTransportCosts() {
return transportCosts;
}
/**
* Returns routing costs.
*
* @return routingCosts
* @see VehicleRoutingTransportCosts
*/
public VehicleRoutingTransportCosts getTransportCosts() {
return transportCosts;
}
/**
* Returns activityCosts.
*/
public VehicleRoutingActivityCosts getActivityCosts(){
return activityCosts;
}
/**
* Returns activityCosts.
*/
public VehicleRoutingActivityCosts getActivityCosts() {
return activityCosts;
}
/**
* @return returns all location, i.e. from vehicles and jobs.
*/
public Locations getLocations(){
return locations;
}
public Locations getLocations() {
return locations;
}
/**
* @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

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

View file

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

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

View file

@ -129,14 +129,14 @@ public class TourActivities {
}
boolean activityRemoved = false;
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

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

View file

@ -24,7 +24,6 @@ import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
/**
* Implementation of {@link Vehicle}.
*
@ -46,8 +45,8 @@ public class VehicleImpl extends AbstractVehicle {
private VehicleType type = VehicleTypeImpl.Builder.newInstance("noType").build();
public NoVehicle() {
}
public NoVehicle() {
}
@Override
public double getEarliestDeparture() {
@ -90,22 +89,23 @@ public class VehicleImpl extends AbstractVehicle {
}
@Override
public Break getBreak() { return null; }
@Override
public Break getBreak() {
return null;
}
}
/**
* Builder that builds the vehicle.
*
* <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 {
/**
* 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 {
static final Logger log = LogManager.getLogger(Builder.class.getName());
@ -127,42 +127,42 @@ public class VehicleImpl extends AbstractVehicle {
private Location endLocation;
private Break aBreak;
private Break aBreak;
private Builder(String id) {
super();
this.id = id;
}
private Builder(String id) {
super();
this.id = id;
}
/**
* Sets the {@link VehicleType}.<br>
*
* @param type the type to be set
* @throws IllegalStateException if type is null
* @return this builder
*/
public Builder setType(VehicleType type){
if(type==null) throw new IllegalStateException("type cannot be null.");
this.type = type;
return this;
}
/**
* Sets the {@link VehicleType}.<br>
*
* @param type the type to be set
* @return this builder
* @throws IllegalStateException if type is 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>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>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){
this.returnToDepot = returnToDepot;
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) {
this.returnToDepot = returnToDepot;
return this;
}
/**
* Sets start location.
@ -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>" +
@ -257,22 +260,22 @@ public class VehicleImpl extends AbstractVehicle {
return this;
}
public Builder setBreak(Break aBreak) {
this.aBreak = aBreak;
return this;
}
}
public Builder setBreak(Break aBreak) {
this.aBreak = aBreak;
return this;
}
}
/**
* Returns empty/noVehicle which is a vehicle having no capacity, no type and no reasonable id.
*
* <p>NoVehicle has id="noVehicle" and extends {@link VehicleImpl}
*
* @return emptyVehicle
*/
public static NoVehicle createNoVehicle(){
return new NoVehicle();
}
/**
* 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() {
return new NoVehicle();
}
private final String id;
@ -290,29 +293,29 @@ public class VehicleImpl extends AbstractVehicle {
private final Location startLocation;
private final Break aBreak;
private final Break aBreak;
private VehicleImpl(Builder builder){
id = builder.id;
type = builder.type;
earliestDeparture = builder.earliestStart;
latestArrival = builder.latestArrival;
returnToDepot = builder.returnToDepot;
skills = builder.skills;
private VehicleImpl(Builder builder) {
id = builder.id;
type = builder.type;
earliestDeparture = builder.earliestStart;
latestArrival = builder.latestArrival;
returnToDepot = builder.returnToDepot;
skills = builder.skills;
endLocation = builder.endLocation;
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, returnToDepot));
}
setVehicleIdentifier(new VehicleTypeKey(type.getTypeId(), startLocation.getId(), endLocation.getId(), earliestDeparture, latestArrival, skills, returnToDepot));
}
/**
* Returns String with attributes of this vehicle
*
* <p>String has the following format [attr1=val1][attr2=val2]...[attrn=valn]
*/
@Override
public String toString() {
/**
* Returns String with attributes of this vehicle
* <p/>
* <p>String has the following format [attr1=val1][attr2=val2]...[attrn=valn]
*/
@Override
public String toString() {
return "[id=" + id + "]" +
"[type=" + type + "]" +
"[startLocation=" + startLocation + "]" +
@ -361,47 +364,47 @@ public class VehicleImpl extends AbstractVehicle {
return skills;
}
@Override
public Break getBreak() {
return aBreak;
}
@Override
public Break getBreak() {
return aBreak;
}
/* (non-Javadoc)
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
result = prime * result + ((type == null) ? 0 : type.hashCode());
return result;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
result = prime * result + ((type == null) ? 0 : type.hashCode());
return result;
}
/**
* Two vehicles are equal if they have the same id and if their types are equal.
*/
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
VehicleImpl other = (VehicleImpl) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
if (type == null) {
if (other.type != null)
return false;
} else if (!type.equals(other.type))
return false;
return true;
}
/**
* Two vehicles are equal if they have the same id and if their types are equal.
*/
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
VehicleImpl other = (VehicleImpl) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
if (type == null) {
if (other.type != null)
return false;
} else if (!type.equals(other.type))
return false;
return true;
}
}

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

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

View file

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

View file

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

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

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

View file

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

View file

@ -21,10 +21,10 @@ 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();
.setBreak(aBreak).build();
VehicleRoutingProblem vrp = VehicleRoutingProblem.Builder.newInstance().setFleetSize(VehicleRoutingProblem.FleetSize.FINITE).addVehicle(v).build();
VehicleRoute route = VehicleRoute.Builder.newInstance(v).setJobActivityFactory(vrp.getJobActivityFactory()).addService(aBreak).build();
TourActivity tourActivity = route.getActivities().get(0);
@ -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())
.setStartLocation(Location.newInstance(0, 0)).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();
.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();
.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

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

View file

@ -30,27 +30,25 @@ import static org.junit.Assert.*;
public class VehicleImplTest {
@Test(expected=IllegalStateException.class)
public void whenVehicleIsBuiltWithoutSettingNeitherLocationNorCoord_itThrowsAnIllegalStateException(){
@SuppressWarnings("unused")
Vehicle v = VehicleImpl.Builder.newInstance("v").build();
}
@Test(expected = IllegalStateException.class)
public void whenVehicleIsBuiltWithoutSettingNeitherLocationNorCoord_itThrowsAnIllegalStateException() {
@SuppressWarnings("unused")
Vehicle v = VehicleImpl.Builder.newInstance("v").build();
}
@Test
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);
}
@Test
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);
}
@Test

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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