1
0
Fork 0
mirror of https://github.com/graphhopper/jsprit.git synced 2020-01-24 07:45:05 +01:00

comply with .editorconfig

This commit is contained in:
oblonski 2015-08-29 12:46:52 +02:00
parent 58afc3590d
commit 33075b479f
416 changed files with 29653 additions and 29979 deletions

View file

@ -1,4 +1,3 @@
/*******************************************************************************
* Copyright (C) 2014 Stefan Schroeder
*
@ -52,7 +51,7 @@ public class AdditionalDistanceConstraintExample {
private final VehicleRoutingTransportCostsMatrix costMatrix;
// private final StateFactory.StateId distanceStateId; //v1.3.1
// private final StateFactory.StateId distanceStateId; //v1.3.1
private final StateId distanceStateId; //head of development - upcoming release
private VehicleRoute vehicleRoute;
@ -61,8 +60,8 @@ public class AdditionalDistanceConstraintExample {
private TourActivity prevAct;
// public DistanceUpdater(StateFactory.StateId distanceStateId, StateManager stateManager, VehicleRoutingTransportCostsMatrix costMatrix) { //v1.3.1
public DistanceUpdater(StateId distanceStateId, StateManager stateManager, VehicleRoutingTransportCostsMatrix transportCosts) { //head of development - upcoming release (v1.4)
// public DistanceUpdater(StateFactory.StateId distanceStateId, StateManager stateManager, VehicleRoutingTransportCostsMatrix costMatrix) { //v1.3.1
public DistanceUpdater(StateId distanceStateId, StateManager stateManager, VehicleRoutingTransportCostsMatrix transportCosts) { //head of development - upcoming release (v1.4)
this.costMatrix = transportCosts;
this.stateManager = stateManager;
this.distanceStateId = distanceStateId;
@ -77,18 +76,18 @@ public class AdditionalDistanceConstraintExample {
@Override
public void visit(TourActivity tourActivity) {
distance += getDistance(prevAct,tourActivity);
distance += getDistance(prevAct, tourActivity);
prevAct = tourActivity;
}
@Override
public void finish() {
distance += getDistance(prevAct,vehicleRoute.getEnd());
distance += getDistance(prevAct, vehicleRoute.getEnd());
// stateManager.putTypedRouteState(vehicleRoute,distanceStateId,Double.class,distance); //v1.3.1
stateManager.putRouteState(vehicleRoute, distanceStateId, distance); //head of development - upcoming release (v1.4)
}
double getDistance(TourActivity from, TourActivity to){
double getDistance(TourActivity from, TourActivity to) {
return costMatrix.getDistance(from.getLocation().getId(), to.getLocation().getId());
}
}
@ -101,10 +100,10 @@ public class AdditionalDistanceConstraintExample {
private final double maxDistance;
// private final StateFactory.StateId distanceStateId; //v1.3.1
// private final StateFactory.StateId distanceStateId; //v1.3.1
private final StateId distanceStateId; //head of development - upcoming release (v1.4)
// DistanceConstraint(double maxDistance, StateFactory.StateId distanceStateId, StateManager stateManager, VehicleRoutingTransportCostsMatrix costsMatrix) { //v1.3.1
// DistanceConstraint(double maxDistance, StateFactory.StateId distanceStateId, StateManager stateManager, VehicleRoutingTransportCostsMatrix costsMatrix) { //v1.3.1
DistanceConstraint(double maxDistance, StateId distanceStateId, StateManager stateManager, VehicleRoutingTransportCostsMatrix transportCosts) { //head of development - upcoming release (v1.4)
this.costsMatrix = transportCosts;
this.maxDistance = maxDistance;
@ -114,21 +113,21 @@ public class AdditionalDistanceConstraintExample {
@Override
public ConstraintsStatus fulfilled(JobInsertionContext context, TourActivity prevAct, TourActivity newAct, TourActivity nextAct, double v) {
double additionalDistance = getDistance(prevAct,newAct) + getDistance(newAct,nextAct) - getDistance(prevAct,nextAct);
double additionalDistance = getDistance(prevAct, newAct) + getDistance(newAct, nextAct) - getDistance(prevAct, nextAct);
Double routeDistance = stateManager.getRouteState(context.getRoute(), distanceStateId, Double.class);
if(routeDistance == null) routeDistance = 0.;
if (routeDistance == null) routeDistance = 0.;
double newRouteDistance = routeDistance + additionalDistance;
if(newRouteDistance > maxDistance) {
if (newRouteDistance > maxDistance) {
return ConstraintsStatus.NOT_FULFILLED;
}
else return ConstraintsStatus.FULFILLED;
} else return ConstraintsStatus.FULFILLED;
}
double getDistance(TourActivity from, TourActivity to){
double getDistance(TourActivity from, TourActivity to) {
return costsMatrix.getDistance(from.getLocation().getId(), to.getLocation().getId());
}
}
public static void main(String[] args) {
//route length 618
@ -139,7 +138,7 @@ public class AdditionalDistanceConstraintExample {
vrpBuilder.setRoutingCost(costMatrix);
VehicleRoutingProblem vrp = vrpBuilder.build();
VehicleRoutingAlgorithmBuilder vraBuilder = new VehicleRoutingAlgorithmBuilder(vrp,"input/algorithmConfig_solomon.xml");
VehicleRoutingAlgorithmBuilder vraBuilder = new VehicleRoutingAlgorithmBuilder(vrp, "input/algorithmConfig_solomon.xml");
// StateManager stateManager = new StateManager(vrp.getTransportCosts()); //v1.3.1
StateManager stateManager = new StateManager(vrp); //head of development - upcoming release (v1.4)
@ -149,13 +148,13 @@ public class AdditionalDistanceConstraintExample {
stateManager.addStateUpdater(new DistanceUpdater(distanceStateId, stateManager, costMatrix));
// stateManager.updateLoadStates();
ConstraintManager constraintManager = new ConstraintManager(vrp,stateManager);
constraintManager.addConstraint(new DistanceConstraint(120.,distanceStateId,stateManager,costMatrix), ConstraintManager.Priority.CRITICAL);
ConstraintManager constraintManager = new ConstraintManager(vrp, stateManager);
constraintManager.addConstraint(new DistanceConstraint(120., distanceStateId, stateManager, costMatrix), ConstraintManager.Priority.CRITICAL);
// constraintManager.addLoadConstraint();
// vraBuilder.addCoreConstraints();
vraBuilder.addDefaultCostCalculators();
vraBuilder.setStateAndConstraintManager(stateManager,constraintManager);
vraBuilder.setStateAndConstraintManager(stateManager, constraintManager);
VehicleRoutingAlgorithm vra = vraBuilder.build();
// vra.setMaxIterations(250); //v1.3.1
@ -165,18 +164,18 @@ public class AdditionalDistanceConstraintExample {
SolutionPrinter.print(vrp, Solutions.bestOf(solutions), SolutionPrinter.Print.VERBOSE);
new Plotter(vrp, Solutions.bestOf(solutions)).plot("output/plot","plot");
new Plotter(vrp, Solutions.bestOf(solutions)).plot("output/plot", "plot");
}
private static VehicleRoutingTransportCostsMatrix createMatrix(VehicleRoutingProblem.Builder vrpBuilder) {
VehicleRoutingTransportCostsMatrix.Builder matrixBuilder = VehicleRoutingTransportCostsMatrix.Builder.newInstance(true);
for(String from : vrpBuilder.getLocationMap().keySet()){
for(String to : vrpBuilder.getLocationMap().keySet()){
for (String from : vrpBuilder.getLocationMap().keySet()) {
for (String to : vrpBuilder.getLocationMap().keySet()) {
Coordinate fromCoord = vrpBuilder.getLocationMap().get(from);
Coordinate toCoord = vrpBuilder.getLocationMap().get(to);
double distance = EuclideanDistanceCalculator.calculateDistance(fromCoord, toCoord);
matrixBuilder.addTransportDistance(from,to,distance);
matrixBuilder.addTransportTime(from,to,(distance / 2.));
matrixBuilder.addTransportDistance(from, to, distance);
matrixBuilder.addTransportTime(from, to, (distance / 2.));
}
}
return matrixBuilder.build();

View file

@ -64,186 +64,184 @@ import java.util.Map;
/**
* This class provides the/a solution to the following problem:
*
* <p/>
* Statement of the problem (see Stackoverflow: http://stackoverflow.com/questions/19080537/bicycle-messenger-tsppd-with-optaplanner/20412598#20412598):
*
* Optimize the routes for a bicycle messenger service!
* <p/>
* Optimize the routes for a bicycle messenger service!
* Assume 5 messengers that have to pick up 30 envelopes distributed through the city. These 5 messengers are distributed through the city as well. Thus
* there is no single depot and they do not need to go back to their original starting location.
*
* <p/>
* Additional hard constraints:
* 1) Every messenger can carry up to fifteen envelopes
* 2) The way an evelopes travels should be less than three times the direct route (so delivery does not take too long)
*
* <p/>
* Thus this problem is basically a Capacitated VRP with Pickups and Deliveries, Multiple Depots, Open Routes and Time Windows/Restrictions.
*
* @author stefan schroeder
*
* @author stefan schroeder
*/
public class BicycleMessenger {
/**
* Hard constraint: delivery of envelope must not take longer than 3*bestDirect (i.e. fastest messenger on direct delivery)
*
* @author stefan
*
*/
static class ThreeTimesLessThanBestDirectRouteConstraint implements HardActivityConstraint {
/**
* Hard constraint: delivery of envelope must not take longer than 3*bestDirect (i.e. fastest messenger on direct delivery)
*
* @author stefan
*/
static class ThreeTimesLessThanBestDirectRouteConstraint implements HardActivityConstraint {
private final VehicleRoutingTransportCosts routingCosts;
private final RouteAndActivityStateGetter stateManager;
//jobId map direct-distance by nearestMessenger
private final Map<String,Double> bestMessengers;
private final VehicleRoutingTransportCosts routingCosts;
private final RouteAndActivityStateGetter stateManager;
//jobId map direct-distance by nearestMessenger
private final Map<String, Double> bestMessengers;
private final StateId latest_act_arrival_time_stateId;
public ThreeTimesLessThanBestDirectRouteConstraint(StateId latest_act_arrival_time, Map<String, Double> nearestMessengers, VehicleRoutingTransportCosts routingCosts, RouteAndActivityStateGetter stateManager) {
this.bestMessengers = nearestMessengers;
this.routingCosts = routingCosts;
this.stateManager = stateManager;
public ThreeTimesLessThanBestDirectRouteConstraint(StateId latest_act_arrival_time, Map<String, Double> nearestMessengers, VehicleRoutingTransportCosts routingCosts, RouteAndActivityStateGetter stateManager) {
this.bestMessengers = nearestMessengers;
this.routingCosts = routingCosts;
this.stateManager = stateManager;
this.latest_act_arrival_time_stateId = latest_act_arrival_time;
}
}
@Override
public ConstraintsStatus fulfilled(JobInsertionContext iFacts,TourActivity prevAct, TourActivity newAct, TourActivity nextAct, double prevActDepTime) {
//make sure vehicle can manage direct path
double arrTime_at_nextAct_onDirectRoute = prevActDepTime + routingCosts.getTransportTime(prevAct.getLocation(), nextAct.getLocation(), prevActDepTime, iFacts.getNewDriver(), iFacts.getNewVehicle());
@Override
public ConstraintsStatus fulfilled(JobInsertionContext iFacts, TourActivity prevAct, TourActivity newAct, TourActivity nextAct, double prevActDepTime) {
//make sure vehicle can manage direct path
double arrTime_at_nextAct_onDirectRoute = prevActDepTime + routingCosts.getTransportTime(prevAct.getLocation(), nextAct.getLocation(), prevActDepTime, iFacts.getNewDriver(), iFacts.getNewVehicle());
Double latest_arrTime_at_nextAct = stateManager.getActivityState(nextAct, latest_act_arrival_time_stateId, Double.class);
if(latest_arrTime_at_nextAct == null) latest_arrTime_at_nextAct = nextAct.getTheoreticalLatestOperationStartTime();
if(arrTime_at_nextAct_onDirectRoute > latest_arrTime_at_nextAct){
if (latest_arrTime_at_nextAct == null)
latest_arrTime_at_nextAct = nextAct.getTheoreticalLatestOperationStartTime();
if (arrTime_at_nextAct_onDirectRoute > latest_arrTime_at_nextAct) {
//constraint can never be fulfilled anymore, thus .NOT_FULFILLED_BREAK
return ConstraintsStatus.NOT_FULFILLED_BREAK;
}
double arrTime_at_newAct = prevActDepTime + routingCosts.getTransportTime(prevAct.getLocation(), newAct.getLocation(), prevActDepTime, iFacts.getNewDriver(), iFacts.getNewVehicle());
//local impact
//no matter whether it is a pickupShipment or deliverShipment activities. both arrivalTimes must be < 3*best.
double directTimeOfNearestMessenger = bestMessengers.get(((JobActivity) newAct).getJob().getId());
if(arrTime_at_newAct > 3 * directTimeOfNearestMessenger){
//not fulfilled AND it can never be fulfilled anymore by going forward in route, thus NOT_FULFILLED_BREAK
return ConstraintsStatus.NOT_FULFILLED_BREAK;
}
return ConstraintsStatus.NOT_FULFILLED_BREAK;
}
//impact on whole route, since insertion of newAct shifts all subsequent activities forward in time
double departureTime_at_newAct = arrTime_at_newAct + newAct.getOperationTime();
double latest_arrTime_at_newAct = latest_arrTime_at_nextAct - routingCosts.getTransportTime(newAct.getLocation(),nextAct.getLocation(),departureTime_at_newAct,iFacts.getNewDriver(),iFacts.getNewVehicle());
if(arrTime_at_newAct > latest_arrTime_at_newAct){
double arrTime_at_newAct = prevActDepTime + routingCosts.getTransportTime(prevAct.getLocation(), newAct.getLocation(), prevActDepTime, iFacts.getNewDriver(), iFacts.getNewVehicle());
//local impact
//no matter whether it is a pickupShipment or deliverShipment activities. both arrivalTimes must be < 3*best.
double directTimeOfNearestMessenger = bestMessengers.get(((JobActivity) newAct).getJob().getId());
if (arrTime_at_newAct > 3 * directTimeOfNearestMessenger) {
//not fulfilled AND it can never be fulfilled anymore by going forward in route, thus NOT_FULFILLED_BREAK
return ConstraintsStatus.NOT_FULFILLED_BREAK;
}
//impact on whole route, since insertion of newAct shifts all subsequent activities forward in time
double departureTime_at_newAct = arrTime_at_newAct + newAct.getOperationTime();
double latest_arrTime_at_newAct = latest_arrTime_at_nextAct - routingCosts.getTransportTime(newAct.getLocation(), nextAct.getLocation(), departureTime_at_newAct, iFacts.getNewDriver(), iFacts.getNewVehicle());
if (arrTime_at_newAct > latest_arrTime_at_newAct) {
return ConstraintsStatus.NOT_FULFILLED;
}
double arrTime_at_nextAct = departureTime_at_newAct + routingCosts.getTransportTime(newAct.getLocation(), nextAct.getLocation(), departureTime_at_newAct, iFacts.getNewDriver(), iFacts.getNewVehicle());
//here you need an activity state
if(arrTime_at_nextAct > latest_arrTime_at_nextAct){
return ConstraintsStatus.NOT_FULFILLED;
}
return ConstraintsStatus.FULFILLED;
}
}
/**
* When inserting the activities of an envelope which are pickup and deliver envelope, this constraint makes insertion procedure to ignore messengers that are too far away to meet the 3*directTime-Constraint.
*
* <p>one does not need this constraint. but it is faster. the earlier the solution-space can be constraint the better/faster.
* @author schroeder
*
*/
static class IgnoreMessengerThatCanNeverMeetTimeRequirements implements HardRouteConstraint {
//here you need an activity state
if (arrTime_at_nextAct > latest_arrTime_at_nextAct) {
return ConstraintsStatus.NOT_FULFILLED;
}
return ConstraintsStatus.FULFILLED;
}
private final Map<String,Double> bestMessengers;
private final VehicleRoutingTransportCosts routingCosts;
public IgnoreMessengerThatCanNeverMeetTimeRequirements(Map<String, Double> bestMessengers, VehicleRoutingTransportCosts routingCosts) {
super();
this.bestMessengers = bestMessengers;
this.routingCosts = routingCosts;
}
}
@Override
public boolean fulfilled(JobInsertionContext insertionContext) {
double timeOfDirectRoute = getTimeOfDirectRoute(insertionContext.getJob(), insertionContext.getNewVehicle(), routingCosts);
double timeOfNearestMessenger = bestMessengers.get(insertionContext.getJob().getId());
return !(timeOfDirectRoute > 3 * timeOfNearestMessenger);
}
}
/**
* updates the state "latest-activity-start-time" (required above) once route/activity states changed, i.e. when removing or inserting an envelope-activity
*
* <p>thus once either the insertion-procedure starts or an envelope has been inserted, this visitor runs through the route in reverse order (i.e. starting with the end of the route) and
* calculates the latest-activity-start-time (or latest-activity-arrival-time) which is the time to just meet the constraints of subsequent activities.
*
* @author schroeder
*
*/
static class UpdateLatestActivityStartTimes implements StateUpdater, ReverseActivityVisitor {
/**
* When inserting the activities of an envelope which are pickup and deliver envelope, this constraint makes insertion procedure to ignore messengers that are too far away to meet the 3*directTime-Constraint.
* <p/>
* <p>one does not need this constraint. but it is faster. the earlier the solution-space can be constraint the better/faster.
*
* @author schroeder
*/
static class IgnoreMessengerThatCanNeverMeetTimeRequirements implements HardRouteConstraint {
private final StateManager stateManager;
private final VehicleRoutingTransportCosts routingCosts;
private final Map<String,Double> bestMessengers;
private VehicleRoute route;
private TourActivity prevAct;
private double latest_arrTime_at_prevAct;
private final Map<String, Double> bestMessengers;
private final VehicleRoutingTransportCosts routingCosts;
public IgnoreMessengerThatCanNeverMeetTimeRequirements(Map<String, Double> bestMessengers, VehicleRoutingTransportCosts routingCosts) {
super();
this.bestMessengers = bestMessengers;
this.routingCosts = routingCosts;
}
@Override
public boolean fulfilled(JobInsertionContext insertionContext) {
double timeOfDirectRoute = getTimeOfDirectRoute(insertionContext.getJob(), insertionContext.getNewVehicle(), routingCosts);
double timeOfNearestMessenger = bestMessengers.get(insertionContext.getJob().getId());
return !(timeOfDirectRoute > 3 * timeOfNearestMessenger);
}
}
/**
* updates the state "latest-activity-start-time" (required above) once route/activity states changed, i.e. when removing or inserting an envelope-activity
* <p/>
* <p>thus once either the insertion-procedure starts or an envelope has been inserted, this visitor runs through the route in reverse order (i.e. starting with the end of the route) and
* calculates the latest-activity-start-time (or latest-activity-arrival-time) which is the time to just meet the constraints of subsequent activities.
*
* @author schroeder
*/
static class UpdateLatestActivityStartTimes implements StateUpdater, ReverseActivityVisitor {
private final StateManager stateManager;
private final VehicleRoutingTransportCosts routingCosts;
private final Map<String, Double> bestMessengers;
private VehicleRoute route;
private TourActivity prevAct;
private double latest_arrTime_at_prevAct;
private final StateId latest_act_arrival_time_stateId;
public UpdateLatestActivityStartTimes(StateId latest_act_arrival_time, StateManager stateManager, VehicleRoutingTransportCosts routingCosts, Map<String, Double> bestMessengers) {
super();
this.stateManager = stateManager;
this.routingCosts = routingCosts;
this.bestMessengers = bestMessengers;
public UpdateLatestActivityStartTimes(StateId latest_act_arrival_time, StateManager stateManager, VehicleRoutingTransportCosts routingCosts, Map<String, Double> bestMessengers) {
super();
this.stateManager = stateManager;
this.routingCosts = routingCosts;
this.bestMessengers = bestMessengers;
this.latest_act_arrival_time_stateId = latest_act_arrival_time;
}
}
@Override
public void begin(VehicleRoute route) {
this.route = route;
latest_arrTime_at_prevAct = route.getEnd().getTheoreticalLatestOperationStartTime();
prevAct = route.getEnd();
}
@Override
public void begin(VehicleRoute route) {
this.route = route;
latest_arrTime_at_prevAct = route.getEnd().getTheoreticalLatestOperationStartTime();
prevAct = route.getEnd();
}
@Override
public void visit(TourActivity currAct) {
double timeOfNearestMessenger = bestMessengers.get(((JobActivity)currAct).getJob().getId());
double potential_latest_arrTime_at_currAct =
latest_arrTime_at_prevAct - routingCosts.getBackwardTransportTime(currAct.getLocation(), prevAct.getLocation(), latest_arrTime_at_prevAct, route.getDriver(),route.getVehicle()) - currAct.getOperationTime();
double latest_arrTime_at_currAct = Math.min(3*timeOfNearestMessenger, potential_latest_arrTime_at_currAct);
stateManager.putActivityState(currAct, latest_act_arrival_time_stateId, latest_arrTime_at_currAct);
assert currAct.getArrTime() <= latest_arrTime_at_currAct : "this must not be since it breaks condition; actArrTime: " + currAct.getArrTime() + " latestArrTime: " + latest_arrTime_at_currAct + " vehicle: " + route.getVehicle().getId();
latest_arrTime_at_prevAct = latest_arrTime_at_currAct;
prevAct = currAct;
}
@Override
public void visit(TourActivity currAct) {
double timeOfNearestMessenger = bestMessengers.get(((JobActivity) currAct).getJob().getId());
double potential_latest_arrTime_at_currAct =
latest_arrTime_at_prevAct - routingCosts.getBackwardTransportTime(currAct.getLocation(), prevAct.getLocation(), latest_arrTime_at_prevAct, route.getDriver(), route.getVehicle()) - currAct.getOperationTime();
double latest_arrTime_at_currAct = Math.min(3 * timeOfNearestMessenger, potential_latest_arrTime_at_currAct);
stateManager.putActivityState(currAct, latest_act_arrival_time_stateId, latest_arrTime_at_currAct);
assert currAct.getArrTime() <= latest_arrTime_at_currAct : "this must not be since it breaks condition; actArrTime: " + currAct.getArrTime() + " latestArrTime: " + latest_arrTime_at_currAct + " vehicle: " + route.getVehicle().getId();
latest_arrTime_at_prevAct = latest_arrTime_at_currAct;
prevAct = currAct;
}
@Override
public void finish() {
}
}
/**
* @throws IOException
*/
public static void main(String[] args) throws IOException {
Examples.createOutputFolder();
@Override
public void finish() {}
}
/**
*
* @throws IOException
*/
public static void main(String[] args) throws IOException {
Examples.createOutputFolder();
/*
build the problem
*/
VehicleRoutingProblem.Builder problemBuilder = VehicleRoutingProblem.Builder.newInstance();
problemBuilder.setFleetSize(FleetSize.FINITE);
readEnvelopes(problemBuilder);
readMessengers(problemBuilder);
//add constraints to problem
VehicleRoutingTransportCosts routingCosts = new CrowFlyCosts(problemBuilder.getLocations()); //which is the default VehicleRoutingTransportCosts in builder above
VehicleRoutingProblem.Builder problemBuilder = VehicleRoutingProblem.Builder.newInstance();
problemBuilder.setFleetSize(FleetSize.FINITE);
readEnvelopes(problemBuilder);
readMessengers(problemBuilder);
//add constraints to problem
VehicleRoutingTransportCosts routingCosts = new CrowFlyCosts(problemBuilder.getLocations()); //which is the default VehicleRoutingTransportCosts in builder above
problemBuilder.setRoutingCost(routingCosts);
//finally build the problem
// problemBuilder.addPenaltyVehicles(20.0,50000);
@ -253,7 +251,7 @@ public class BicycleMessenger {
define states and constraints
*/
//map mapping nearest messengers, i.e. for each envelope the direct-delivery-time with the fastest messenger is stored here
Map<String,Double> nearestMessengers = getNearestMessengers(routingCosts, problemBuilder.getAddedJobs(), problemBuilder.getAddedVehicles());
Map<String, Double> nearestMessengers = getNearestMessengers(routingCosts, problemBuilder.getAddedJobs(), problemBuilder.getAddedVehicles());
//define stateManager to update the required activity-state: "latest-activity-start-time"
StateManager stateManager = new StateManager(bicycleMessengerProblem);
@ -263,13 +261,13 @@ public class BicycleMessenger {
stateManager.addStateUpdater(new UpdateLatestActivityStartTimes(latest_act_arrival_time_stateId, stateManager, routingCosts, nearestMessengers));
stateManager.updateLoadStates();
ConstraintManager constraintManager = new ConstraintManager(bicycleMessengerProblem,stateManager);
ConstraintManager constraintManager = new ConstraintManager(bicycleMessengerProblem, stateManager);
constraintManager.addLoadConstraint();
constraintManager.addConstraint(new ThreeTimesLessThanBestDirectRouteConstraint(latest_act_arrival_time_stateId,nearestMessengers,routingCosts,stateManager), ConstraintManager.Priority.CRITICAL);
constraintManager.addConstraint(new ThreeTimesLessThanBestDirectRouteConstraint(latest_act_arrival_time_stateId, nearestMessengers, routingCosts, stateManager), ConstraintManager.Priority.CRITICAL);
constraintManager.addConstraint(new IgnoreMessengerThatCanNeverMeetTimeRequirements(nearestMessengers, routingCosts));
//create your algorithm
VehicleRoutingAlgorithmBuilder vraBuilder = new VehicleRoutingAlgorithmBuilder(bicycleMessengerProblem,"input/algorithmConfig.xml");
VehicleRoutingAlgorithmBuilder vraBuilder = new VehicleRoutingAlgorithmBuilder(bicycleMessengerProblem, "input/algorithmConfig.xml");
// vraBuilder.setNuOfThreads(2);
vraBuilder.addDefaultCostCalculators();
vraBuilder.setStateAndConstraintManager(stateManager, constraintManager);
@ -294,110 +292,115 @@ public class BicycleMessenger {
// VariationCoefficientTermination prematureAlgorithmTermination = new VariationCoefficientTermination(200, 0.001);
// algorithm.setPrematureAlgorithmTermination(prematureAlgorithmTermination);
// algorithm.addListener(prematureAlgorithmTermination);
algorithm.addListener(new AlgorithmSearchProgressChartListener("output/progress.png"));
algorithm.addListener(new AlgorithmSearchProgressChartListener("output/progress.png"));
//search
Collection<VehicleRoutingProblemSolution> solutions = algorithm.searchSolutions();
//this is just to ensure that solution meet the above constraints
validateSolution(Solutions.bestOf(solutions), bicycleMessengerProblem, nearestMessengers);
Collection<VehicleRoutingProblemSolution> solutions = algorithm.searchSolutions();
//this is just to ensure that solution meet the above constraints
validateSolution(Solutions.bestOf(solutions), bicycleMessengerProblem, nearestMessengers);
SolutionPrinter.print(bicycleMessengerProblem, Solutions.bestOf(solutions), SolutionPrinter.Print.VERBOSE);
//you may want to plot the problem
Plotter plotter = new Plotter(bicycleMessengerProblem);
//you may want to plot the problem
Plotter plotter = new Plotter(bicycleMessengerProblem);
// plotter.setBoundingBox(10000, 47500, 20000, 67500);
plotter.plotShipments(true);
plotter.plot("output/bicycleMessengerProblem.png", "bicycleMessenger");
//and the problem as well as the solution
Plotter plotter1 = new Plotter(bicycleMessengerProblem, Solutions.bestOf(solutions));
plotter1.setLabel(Plotter.Label.ID);
plotter.plotShipments(true);
plotter.plot("output/bicycleMessengerProblem.png", "bicycleMessenger");
//and the problem as well as the solution
Plotter plotter1 = new Plotter(bicycleMessengerProblem, Solutions.bestOf(solutions));
plotter1.setLabel(Plotter.Label.ID);
plotter1.plotShipments(false);
// plotter1.setBoundingBox(5000, 45500, 25000, 66500);
plotter1.plot("output/bicycleMessengerSolution.png", "bicycleMessenger");
//and write out your solution in xml
plotter1.plot("output/bicycleMessengerSolution.png", "bicycleMessenger");
//and write out your solution in xml
// new VrpXMLWriter(bicycleMessengerProblem, solutions).write("output/bicycleMessenger.xml");
new GraphStreamViewer(bicycleMessengerProblem).labelWith(Label.ID).setRenderShipments(true).setRenderDelay(150).display();
//
new GraphStreamViewer(bicycleMessengerProblem, Solutions.bestOf(solutions)).setGraphStreamFrameScalingFactor(1.5).setCameraView(12500, 55000, 0.25).labelWith(Label.ACTIVITY).setRenderShipments(true).setRenderDelay(150).display();
}
new GraphStreamViewer(bicycleMessengerProblem).labelWith(Label.ID).setRenderShipments(true).setRenderDelay(150).display();
//
new GraphStreamViewer(bicycleMessengerProblem, Solutions.bestOf(solutions)).setGraphStreamFrameScalingFactor(1.5).setCameraView(12500, 55000, 0.25).labelWith(Label.ACTIVITY).setRenderShipments(true).setRenderDelay(150).display();
//if you wanne run this enable assertion by putting an '-ea' in your vmargument list - Run As --> Run Configurations --> (x)=Arguments --> VM arguments: -ea
private static void validateSolution(VehicleRoutingProblemSolution bestOf, VehicleRoutingProblem bicycleMessengerProblem, Map<String, Double> nearestMessengers) {
for(VehicleRoute route : bestOf.getRoutes()){
for(TourActivity act : route.getActivities()){
if(act.getArrTime() > 3*nearestMessengers.get(((JobActivity)act).getJob().getId())){
SolutionPrinter.print(bicycleMessengerProblem, bestOf, SolutionPrinter.Print.VERBOSE);
throw new IllegalStateException("three times less than ... constraint broken. this must not be. act.getArrTime(): " + act.getArrTime() + " allowed: " + 3*nearestMessengers.get(((JobActivity)act).getJob().getId()));
}
}
}
}
}
static Map<String,Double> getNearestMessengers(VehicleRoutingTransportCosts routingCosts, Collection<Job> envelopes, Collection<Vehicle> messengers) {
Map<String,Double> nearestMessengers = new HashMap<String, Double>();
for(Job envelope : envelopes){
double minDirect = Double.MAX_VALUE;
for(Vehicle m : messengers){
double direct = getTimeOfDirectRoute(envelope, m, routingCosts);
if(direct < minDirect){
minDirect = direct;
}
}
nearestMessengers.put(envelope.getId(), minDirect);
}
return nearestMessengers;
}
static double getTimeOfDirectRoute(Job job, Vehicle v, VehicleRoutingTransportCosts routingCosts) {
Shipment envelope = (Shipment) job;
return routingCosts.getTransportTime(v.getStartLocation(), envelope.getPickupLocation(), 0.0, DriverImpl.noDriver(), v) +
routingCosts.getTransportTime(envelope.getPickupLocation(), envelope.getDeliveryLocation(), 0.0, DriverImpl.noDriver(), v);
}
//if you wanne run this enable assertion by putting an '-ea' in your vmargument list - Run As --> Run Configurations --> (x)=Arguments --> VM arguments: -ea
private static void validateSolution(VehicleRoutingProblemSolution bestOf, VehicleRoutingProblem bicycleMessengerProblem, Map<String, Double> nearestMessengers) {
for (VehicleRoute route : bestOf.getRoutes()) {
for (TourActivity act : route.getActivities()) {
if (act.getArrTime() > 3 * nearestMessengers.get(((JobActivity) act).getJob().getId())) {
SolutionPrinter.print(bicycleMessengerProblem, bestOf, SolutionPrinter.Print.VERBOSE);
throw new IllegalStateException("three times less than ... constraint broken. this must not be. act.getArrTime(): " + act.getArrTime() + " allowed: " + 3 * nearestMessengers.get(((JobActivity) act).getJob().getId()));
}
}
}
}
private static void readEnvelopes(Builder problemBuilder) throws IOException {
BufferedReader reader = new BufferedReader(new FileReader(new File("input/bicycle_messenger_demand.txt")));
String line;
boolean firstLine = true;
while((line = reader.readLine()) != null){
if(firstLine) { firstLine = false; continue; }
String[] tokens = line.split("\\s+");
//define your envelope which is basically a shipment from A to B
Shipment envelope = Shipment.Builder.newInstance(tokens[1]).addSizeDimension(0, 1)
.setPickupLocation(Location.Builder.newInstance().setCoordinate(Coordinate.newInstance(Double.parseDouble(tokens[2]), Double.parseDouble(tokens[3]))).build())
.setDeliveryLocation(Location.Builder.newInstance().setCoordinate(Coordinate.newInstance(Double.parseDouble(tokens[4]), Double.parseDouble(tokens[5]))).build()).build();
problemBuilder.addJob(envelope);
}
reader.close();
}
static Map<String, Double> getNearestMessengers(VehicleRoutingTransportCosts routingCosts, Collection<Job> envelopes, Collection<Vehicle> messengers) {
Map<String, Double> nearestMessengers = new HashMap<String, Double>();
for (Job envelope : envelopes) {
double minDirect = Double.MAX_VALUE;
for (Vehicle m : messengers) {
double direct = getTimeOfDirectRoute(envelope, m, routingCosts);
if (direct < minDirect) {
minDirect = direct;
}
}
nearestMessengers.put(envelope.getId(), minDirect);
}
return nearestMessengers;
}
private static void readMessengers(Builder problemBuilder) throws IOException {
BufferedReader reader = new BufferedReader(new FileReader(new File("input/bicycle_messenger_supply.txt")));
String line;
boolean firstLine = true;
VehicleType messengerType = VehicleTypeImpl.Builder.newInstance("messengerType").addCapacityDimension(0, 15).setCostPerDistance(1).build();
static double getTimeOfDirectRoute(Job job, Vehicle v, VehicleRoutingTransportCosts routingCosts) {
Shipment envelope = (Shipment) job;
return routingCosts.getTransportTime(v.getStartLocation(), envelope.getPickupLocation(), 0.0, DriverImpl.noDriver(), v) +
routingCosts.getTransportTime(envelope.getPickupLocation(), envelope.getDeliveryLocation(), 0.0, DriverImpl.noDriver(), v);
}
private static void readEnvelopes(Builder problemBuilder) throws IOException {
BufferedReader reader = new BufferedReader(new FileReader(new File("input/bicycle_messenger_demand.txt")));
String line;
boolean firstLine = true;
while ((line = reader.readLine()) != null) {
if (firstLine) {
firstLine = false;
continue;
}
String[] tokens = line.split("\\s+");
//define your envelope which is basically a shipment from A to B
Shipment envelope = Shipment.Builder.newInstance(tokens[1]).addSizeDimension(0, 1)
.setPickupLocation(Location.Builder.newInstance().setCoordinate(Coordinate.newInstance(Double.parseDouble(tokens[2]), Double.parseDouble(tokens[3]))).build())
.setDeliveryLocation(Location.Builder.newInstance().setCoordinate(Coordinate.newInstance(Double.parseDouble(tokens[4]), Double.parseDouble(tokens[5]))).build()).build();
problemBuilder.addJob(envelope);
}
reader.close();
}
private static void readMessengers(Builder problemBuilder) throws IOException {
BufferedReader reader = new BufferedReader(new FileReader(new File("input/bicycle_messenger_supply.txt")));
String line;
boolean firstLine = true;
VehicleType messengerType = VehicleTypeImpl.Builder.newInstance("messengerType").addCapacityDimension(0, 15).setCostPerDistance(1).build();
/*
* the algo requires some time and space to search for a valid solution. if you ommit a penalty-type, it probably throws an Exception once it cannot insert an envelope anymore
* thus, give it space by defining a penalty/shadow vehicle with higher variable and fixed costs to up the pressure to find solutions without penalty type
*
*
* it is important to give it the same typeId as the type you want to shadow
*/
while((line = reader.readLine()) != null){
if(firstLine) { firstLine = false; continue; }
String[] tokens = line.split("\\s+");
//build your vehicle
VehicleImpl vehicle = VehicleImpl.Builder.newInstance(tokens[1])
.setStartLocation(Location.Builder.newInstance().setCoordinate(Coordinate.newInstance(Double.parseDouble(tokens[2]), Double.parseDouble(tokens[3]))).build())
.setReturnToDepot(false).setType(messengerType).build();
problemBuilder.addVehicle(vehicle);
}
reader.close();
}
while ((line = reader.readLine()) != null) {
if (firstLine) {
firstLine = false;
continue;
}
String[] tokens = line.split("\\s+");
//build your vehicle
VehicleImpl vehicle = VehicleImpl.Builder.newInstance(tokens[1])
.setStartLocation(Location.Builder.newInstance().setCoordinate(Coordinate.newInstance(Double.parseDouble(tokens[2]), Double.parseDouble(tokens[3]))).build())
.setReturnToDepot(false).setType(messengerType).build();
problemBuilder.addVehicle(vehicle);
}
reader.close();
}
}

View file

@ -72,15 +72,15 @@ public class BuildAlgorithmFromScratch {
List<Job> unassigned = new ArrayList<Job>(unassignedJobs);
Collections.shuffle(unassigned, random);
for(Job j : unassigned){
for (Job j : unassigned) {
InsertionData bestInsertionData = InsertionData.createEmptyInsertionData();
VehicleRoute bestRoute = null;
//look for inserting unassigned job into existing route
for(VehicleRoute r : vehicleRoutes){
InsertionData insertionData = insertionCalculator.getInsertionData(j,r,bestInsertionData.getInsertionCost());
if(insertionData instanceof InsertionData.NoInsertionFound) continue;
if(insertionData.getInsertionCost() < bestInsertionData.getInsertionCost()){
for (VehicleRoute r : vehicleRoutes) {
InsertionData insertionData = insertionCalculator.getInsertionData(j, r, bestInsertionData.getInsertionCost());
if (insertionData instanceof InsertionData.NoInsertionFound) continue;
if (insertionData.getInsertionCost() < bestInsertionData.getInsertionCost()) {
bestInsertionData = insertionData;
bestRoute = r;
}
@ -88,14 +88,13 @@ public class BuildAlgorithmFromScratch {
//try whole new route
VehicleRoute empty = VehicleRoute.emptyRoute();
InsertionData insertionData = insertionCalculator.getInsertionData(j, empty, bestInsertionData.getInsertionCost());
if(!(insertionData instanceof InsertionData.NoInsertionFound)) {
if (!(insertionData instanceof InsertionData.NoInsertionFound)) {
if (insertionData.getInsertionCost() < bestInsertionData.getInsertionCost()) {
vehicleRoutes.add(empty);
insertJob(j, insertionData, empty);
}
}
else {
if(bestRoute != null) insertJob(j,bestInsertionData,bestRoute);
} else {
if (bestRoute != null) insertJob(j, bestInsertionData, bestRoute);
else badJobs.add(j);
}
}
@ -115,8 +114,8 @@ public class BuildAlgorithmFromScratch {
VehicleRoutingAlgorithm vra = createAlgorithm(vrp);
vra.setMaxIterations(100);
AlgorithmEventsRecorder eventsRecorder = new AlgorithmEventsRecorder(vrp,"output/events.dgs.gz");
eventsRecorder.setRecordingRange(90,100);
AlgorithmEventsRecorder eventsRecorder = new AlgorithmEventsRecorder(vrp, "output/events.dgs.gz");
eventsRecorder.setRecordingRange(90, 100);
vra.addListener(eventsRecorder);
VehicleRoutingProblemSolution solution = Solutions.bestOf(vra.searchSolutions());
@ -129,17 +128,17 @@ public class BuildAlgorithmFromScratch {
}
public static VehicleRoutingAlgorithm createAlgorithm(final VehicleRoutingProblem vrp){
public static VehicleRoutingAlgorithm createAlgorithm(final VehicleRoutingProblem vrp) {
VehicleFleetManager fleetManager = new FiniteFleetManagerFactory(vrp.getVehicles()).createFleetManager();
StateManager stateManager = new StateManager(vrp);
ConstraintManager constraintManager = new ConstraintManager(vrp,stateManager);
ConstraintManager constraintManager = new ConstraintManager(vrp, stateManager);
/*
* insertion strategies
*/
//my custom best insertion
MyBestStrategy best = new MyBestStrategy(vrp,fleetManager,stateManager,constraintManager);
MyBestStrategy best = new MyBestStrategy(vrp, fleetManager, stateManager, constraintManager);
//regret insertion
InsertionBuilder iBuilder = new InsertionBuilder(vrp, fleetManager, stateManager, constraintManager);
@ -151,7 +150,7 @@ public class BuildAlgorithmFromScratch {
regret.setScoringFunction(scoringFunction);
/*
* ruin strategies
* ruin strategies
*/
RuinStrategy randomRuin = new RandomRuinStrategyFactory(0.5).createStrategy(vrp);
RuinStrategy radialRuin = new RadialRuinStrategyFactory(0.3, new AvgServiceAndShipmentDistance(vrp.getTransportCosts())).createStrategy(vrp);
@ -170,12 +169,12 @@ public class BuildAlgorithmFromScratch {
SearchStrategy thirdStrategy = new SearchStrategy("thirdStrategy", new SelectBest(), new GreedyAcceptance(1), objectiveFunction);
secondStrategy.addModule(new RuinAndRecreateModule("radRuinBestIns", regret, radialRuin));
PrettyAlgorithmBuilder prettyAlgorithmBuilder = PrettyAlgorithmBuilder.newInstance(vrp,fleetManager,stateManager,constraintManager);
PrettyAlgorithmBuilder prettyAlgorithmBuilder = PrettyAlgorithmBuilder.newInstance(vrp, fleetManager, stateManager, constraintManager);
final VehicleRoutingAlgorithm vra = prettyAlgorithmBuilder
.withStrategy(firstStrategy, 0.5).withStrategy(secondStrategy, 0.5).withStrategy(thirdStrategy, 0.2)
.addCoreStateAndConstraintStuff()
.constructInitialSolutionWith(regret, objectiveFunction)
.build();
.withStrategy(firstStrategy, 0.5).withStrategy(secondStrategy, 0.5).withStrategy(thirdStrategy, 0.2)
.addCoreStateAndConstraintStuff()
.constructInitialSolutionWith(regret, objectiveFunction)
.build();
//if you want to switch on/off strategies or adapt their weight within the search, you can do the following
//e.g. from iteration 50 on, switch off first strategy
@ -183,12 +182,12 @@ public class BuildAlgorithmFromScratch {
IterationStartsListener strategyAdaptor = new IterationStartsListener() {
@Override
public void informIterationStarts(int i, VehicleRoutingProblem problem, Collection<VehicleRoutingProblemSolution> solutions) {
if(i == 50){
vra.getSearchStrategyManager().informStrategyWeightChanged("firstStrategy",0.0);
if (i == 50) {
vra.getSearchStrategyManager().informStrategyWeightChanged("firstStrategy", 0.0);
System.out.println("switched off firstStrategy");
}
if(i == 90){
vra.getSearchStrategyManager().informStrategyWeightChanged("firstStrategy",0.7);
if (i == 90) {
vra.getSearchStrategyManager().informStrategyWeightChanged("firstStrategy", 0.7);
System.out.println("switched on firstStrategy again with higher weight");
}
}
@ -204,10 +203,10 @@ public class BuildAlgorithmFromScratch {
@Override
public double getCosts(VehicleRoutingProblemSolution solution) {
SolutionAnalyser analyser = new SolutionAnalyser(vrp,solution,new SolutionAnalyser.DistanceCalculator() {
SolutionAnalyser analyser = new SolutionAnalyser(vrp, solution, new SolutionAnalyser.DistanceCalculator() {
@Override
public double getDistance(Location from, Location to) {
return vrp.getTransportCosts().getTransportCost(from, to,0.,null,null);
return vrp.getTransportCosts().getTransportCost(from, to, 0., null, null);
}
});
return analyser.getVariableTransportCosts() + solution.getUnassignedJobs().size() * 500.;

View file

@ -40,12 +40,12 @@ import java.util.Collection;
*/
public class CircleExample {
public static Collection<Coordinate> createCoordinates(double center_x, double center_y, double radius, double step){
public static Collection<Coordinate> createCoordinates(double center_x, double center_y, double radius, double step) {
Collection<Coordinate> coords = new ArrayList<Coordinate>();
for(double theta = 0; theta < 2*Math.PI; theta += step){
double x = center_x + radius*Math.cos(theta);
double y = center_y - radius*Math.sin(theta);
coords.add(Coordinate.newInstance(x,y));
for (double theta = 0; theta < 2 * Math.PI; theta += step) {
double x = center_x + radius * Math.cos(theta);
double y = center_y - radius * Math.sin(theta);
coords.add(Coordinate.newInstance(x, y));
}
return coords;
}
@ -53,21 +53,21 @@ public class CircleExample {
public static void main(String[] args) {
File dir = new File("output");
// if the directory does not exist, create it
if (!dir.exists()){
if (!dir.exists()) {
System.out.println("creating directory ./output");
boolean result = dir.mkdir();
if(result) System.out.println("./output created");
if (result) System.out.println("./output created");
}
VehicleRoutingProblem.Builder vrpBuilder = VehicleRoutingProblem.Builder.newInstance();
VehicleImpl v = VehicleImpl.Builder.newInstance("v")
.setStartLocation(Location.Builder.newInstance().setCoordinate(Coordinate.newInstance(0, 0)).build()).build();
.setStartLocation(Location.Builder.newInstance().setCoordinate(Coordinate.newInstance(0, 0)).build()).build();
vrpBuilder.addVehicle(v);
double step = 2*Math.PI/50.;
Collection<Coordinate> circle = createCoordinates(0,0,20,step);
double step = 2 * Math.PI / 50.;
Collection<Coordinate> circle = createCoordinates(0, 0, 20, step);
int id = 1;
for(Coordinate c : circle){
for (Coordinate c : circle) {
Service s = Service.Builder.newInstance(Integer.toString(id)).setLocation(Location.Builder.newInstance().setCoordinate(c).build()).build();
vrpBuilder.addJob(s);
id++;
@ -75,8 +75,8 @@ public class CircleExample {
VehicleRoutingProblem vrp = vrpBuilder.build();
//only works with latest snapshot: 1.4.3
AlgorithmEventsRecorder eventsRecorder = new AlgorithmEventsRecorder(vrp,"output/events.dgs.gz");
eventsRecorder.setRecordingRange(0,50);
AlgorithmEventsRecorder eventsRecorder = new AlgorithmEventsRecorder(vrp, "output/events.dgs.gz");
eventsRecorder.setRecordingRange(0, 50);
VehicleRoutingAlgorithm vra = new GreedySchrimpfFactory().createAlgorithm(vrp);
vra.setMaxIterations(50);
@ -86,8 +86,8 @@ public class CircleExample {
VehicleRoutingProblemSolution solution = Solutions.bestOf(vra.searchSolutions());
new Plotter(vrp,solution).plot("output/circle.png","circleProblem");
new GraphStreamViewer(vrp,solution).display();
new Plotter(vrp, solution).plot("output/circle.png", "circleProblem");
new GraphStreamViewer(vrp, solution).display();
//only works with latest snapshot: 1.4.3
AlgorithmEventsViewer viewer = new AlgorithmEventsViewer();

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.examples;
@ -38,97 +38,97 @@ import java.util.Collection;
public class ConfigureAlgorithmInCodeInsteadOfPerXml {
public static void main(String[] args) {
/*
public static void main(String[] args) {
/*
* some preparation - create output folder
*/
Examples.createOutputFolder();
Examples.createOutputFolder();
/*
* get a vehicle type-builder and build a type with the typeId "vehicleType" and a capacity of 2
*/
VehicleTypeImpl.Builder vehicleTypeBuilder = VehicleTypeImpl.Builder.newInstance("vehicleType").addCapacityDimension(0, 2);
VehicleType vehicleType = vehicleTypeBuilder.build();
VehicleTypeImpl.Builder vehicleTypeBuilder = VehicleTypeImpl.Builder.newInstance("vehicleType").addCapacityDimension(0, 2);
VehicleType vehicleType = vehicleTypeBuilder.build();
/*
* get a vehicle-builder and build a vehicle located at (10,10) with type "vehicleType"
*/
Builder vehicleBuilder = VehicleImpl.Builder.newInstance("vehicle");
vehicleBuilder.setStartLocation(Location.newInstance(10, 10));
vehicleBuilder.setType(vehicleType);
VehicleImpl vehicle = vehicleBuilder.build();
Builder vehicleBuilder = VehicleImpl.Builder.newInstance("vehicle");
vehicleBuilder.setStartLocation(Location.newInstance(10, 10));
vehicleBuilder.setType(vehicleType);
VehicleImpl vehicle = vehicleBuilder.build();
/*
* build services at the required locations, each with a capacity-demand of 1.
*/
Service service1 = Service.Builder.newInstance("1").addSizeDimension(0, 1).setLocation(Location.newInstance(5, 7)).build();
Service service2 = Service.Builder.newInstance("2").addSizeDimension(0, 1).setLocation(Location.newInstance(5, 13)).build();
Service service3 = Service.Builder.newInstance("3").addSizeDimension(0, 1).setLocation(Location.newInstance(15, 7)).build();
Service service4 = Service.Builder.newInstance("4").addSizeDimension(0, 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);
VehicleRoutingProblem problem = vrpBuilder.build();
Service service1 = Service.Builder.newInstance("1").addSizeDimension(0, 1).setLocation(Location.newInstance(5, 7)).build();
Service service2 = Service.Builder.newInstance("2").addSizeDimension(0, 1).setLocation(Location.newInstance(5, 13)).build();
Service service3 = Service.Builder.newInstance("3").addSizeDimension(0, 1).setLocation(Location.newInstance(15, 7)).build();
Service service4 = Service.Builder.newInstance("4").addSizeDimension(0, 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);
VehicleRoutingProblem problem = vrpBuilder.build();
/*
* get the algorithm out-of-the-box.
* get the algorithm out-of-the-box.
*/
AlgorithmConfig algorithmConfig = getAlgorithmConfig();
VehicleRoutingAlgorithm algorithm = VehicleRoutingAlgorithms.createAlgorithm(problem,algorithmConfig);
AlgorithmConfig algorithmConfig = getAlgorithmConfig();
VehicleRoutingAlgorithm algorithm = VehicleRoutingAlgorithms.createAlgorithm(problem, algorithmConfig);
/*
* and search a solution
*/
Collection<VehicleRoutingProblemSolution> solutions = algorithm.searchSolutions();
Collection<VehicleRoutingProblemSolution> solutions = algorithm.searchSolutions();
/*
* get the best
* get the best
*/
VehicleRoutingProblemSolution bestSolution = Solutions.bestOf(solutions);
new VrpXMLWriter(problem, solutions).write("output/problem-with-solution.xml");
SolutionPrinter.print(bestSolution);
VehicleRoutingProblemSolution bestSolution = Solutions.bestOf(solutions);
new VrpXMLWriter(problem, solutions).write("output/problem-with-solution.xml");
SolutionPrinter.print(bestSolution);
/*
* plot
*/
new Plotter(problem,bestSolution).plot("output/solution.png", "solution");
}
new Plotter(problem, bestSolution).plot("output/solution.png", "solution");
}
private static AlgorithmConfig getAlgorithmConfig() {
AlgorithmConfig config = new AlgorithmConfig();
XMLConfiguration xmlConfig = config.getXMLConfiguration();
xmlConfig.setProperty("iterations", "2000");
xmlConfig.setProperty("construction.insertion[@name]","bestInsertion");
xmlConfig.setProperty("strategy.memory", 1);
String searchStrategy = "strategy.searchStrategies.searchStrategy";
private static AlgorithmConfig getAlgorithmConfig() {
AlgorithmConfig config = new AlgorithmConfig();
XMLConfiguration xmlConfig = config.getXMLConfiguration();
xmlConfig.setProperty("iterations", "2000");
xmlConfig.setProperty("construction.insertion[@name]", "bestInsertion");
xmlConfig.setProperty(searchStrategy + "(0)[@name]","random_best");
xmlConfig.setProperty(searchStrategy + "(0).selector[@name]","selectBest");
xmlConfig.setProperty(searchStrategy + "(0).acceptor[@name]","acceptNewRemoveWorst");
xmlConfig.setProperty(searchStrategy + "(0).modules.module(0)[@name]","ruin_and_recreate");
xmlConfig.setProperty(searchStrategy + "(0).modules.module(0).ruin[@name]","randomRuin");
xmlConfig.setProperty(searchStrategy + "(0).modules.module(0).ruin.share","0.3");
xmlConfig.setProperty(searchStrategy + "(0).modules.module(0).insertion[@name]","bestInsertion");
xmlConfig.setProperty(searchStrategy + "(0).probability","0.5");
xmlConfig.setProperty("strategy.memory", 1);
String searchStrategy = "strategy.searchStrategies.searchStrategy";
xmlConfig.setProperty(searchStrategy + "(1)[@name]","radial_best");
xmlConfig.setProperty(searchStrategy + "(1).selector[@name]","selectBest");
xmlConfig.setProperty(searchStrategy + "(1).acceptor[@name]","acceptNewRemoveWorst");
xmlConfig.setProperty(searchStrategy + "(1).modules.module(0)[@name]","ruin_and_recreate");
xmlConfig.setProperty(searchStrategy + "(1).modules.module(0).ruin[@name]","radialRuin");
xmlConfig.setProperty(searchStrategy + "(1).modules.module(0).ruin.share","0.15");
xmlConfig.setProperty(searchStrategy + "(1).modules.module(0).insertion[@name]","bestInsertion");
xmlConfig.setProperty(searchStrategy + "(1).probability","0.5");
return config;
}
xmlConfig.setProperty(searchStrategy + "(0)[@name]", "random_best");
xmlConfig.setProperty(searchStrategy + "(0).selector[@name]", "selectBest");
xmlConfig.setProperty(searchStrategy + "(0).acceptor[@name]", "acceptNewRemoveWorst");
xmlConfig.setProperty(searchStrategy + "(0).modules.module(0)[@name]", "ruin_and_recreate");
xmlConfig.setProperty(searchStrategy + "(0).modules.module(0).ruin[@name]", "randomRuin");
xmlConfig.setProperty(searchStrategy + "(0).modules.module(0).ruin.share", "0.3");
xmlConfig.setProperty(searchStrategy + "(0).modules.module(0).insertion[@name]", "bestInsertion");
xmlConfig.setProperty(searchStrategy + "(0).probability", "0.5");
xmlConfig.setProperty(searchStrategy + "(1)[@name]", "radial_best");
xmlConfig.setProperty(searchStrategy + "(1).selector[@name]", "selectBest");
xmlConfig.setProperty(searchStrategy + "(1).acceptor[@name]", "acceptNewRemoveWorst");
xmlConfig.setProperty(searchStrategy + "(1).modules.module(0)[@name]", "ruin_and_recreate");
xmlConfig.setProperty(searchStrategy + "(1).modules.module(0).ruin[@name]", "radialRuin");
xmlConfig.setProperty(searchStrategy + "(1).modules.module(0).ruin.share", "0.15");
xmlConfig.setProperty(searchStrategy + "(1).modules.module(0).insertion[@name]", "bestInsertion");
xmlConfig.setProperty(searchStrategy + "(1).probability", "0.5");
return config;
}
}

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.examples;
@ -38,27 +38,26 @@ import java.util.Collection;
/**
* Illustrates how you can use jsprit with an already compiled distance and time matrix.
*
* @author schroeder
*
* @author schroeder
*/
public class CostMatrixExample {
public static void main(String[] args) {
/*
public static void main(String[] args) {
/*
* some preparation - create output folder
*/
Examples.createOutputFolder();
VehicleType type = VehicleTypeImpl.Builder.newInstance("type").addCapacityDimension(0, 2).setCostPerDistance(1).setCostPerTime(2).build();
VehicleImpl vehicle = VehicleImpl.Builder.newInstance("vehicle")
.setStartLocation(Location.newInstance("0")).setType(type).build();
Service s1 = Service.Builder.newInstance("1").addSizeDimension(0, 1).setLocation(Location.newInstance("1")).build();
Service s2 = Service.Builder.newInstance("2").addSizeDimension(0, 1).setLocation(Location.newInstance("2")).build();
Service s3 = Service.Builder.newInstance("3").addSizeDimension(0, 1).setLocation(Location.newInstance("3")).build();
Examples.createOutputFolder();
VehicleType type = VehicleTypeImpl.Builder.newInstance("type").addCapacityDimension(0, 2).setCostPerDistance(1).setCostPerTime(2).build();
VehicleImpl vehicle = VehicleImpl.Builder.newInstance("vehicle")
.setStartLocation(Location.newInstance("0")).setType(type).build();
Service s1 = Service.Builder.newInstance("1").addSizeDimension(0, 1).setLocation(Location.newInstance("1")).build();
Service s2 = Service.Builder.newInstance("2").addSizeDimension(0, 1).setLocation(Location.newInstance("2")).build();
Service s3 = Service.Builder.newInstance("3").addSizeDimension(0, 1).setLocation(Location.newInstance("3")).build();
/*
* Assume the following symmetric distance-matrix
* from,to,distance
@ -68,7 +67,7 @@ public class CostMatrixExample {
* 1,2,4.0
* 1,3,1.0
* 2,3,2.0
*
*
* and this time-matrix
* 0,1,5.0
* 0,2,10.0
@ -77,35 +76,35 @@ public class CostMatrixExample {
* 1,3,0.5
* 2,3,1.0
*/
//define a matrix-builder building a symmetric matrix
VehicleRoutingTransportCostsMatrix.Builder costMatrixBuilder = VehicleRoutingTransportCostsMatrix.Builder.newInstance(true);
costMatrixBuilder.addTransportDistance("0", "1", 10.0);
costMatrixBuilder.addTransportDistance("0", "2", 20.0);
costMatrixBuilder.addTransportDistance("0", "3", 5.0);
costMatrixBuilder.addTransportDistance("1", "2", 4.0);
costMatrixBuilder.addTransportDistance("1", "3", 1.0);
costMatrixBuilder.addTransportDistance("2", "3", 2.0);
costMatrixBuilder.addTransportTime("0", "1", 10.0);
costMatrixBuilder.addTransportTime("0", "2", 20.0);
costMatrixBuilder.addTransportTime("0", "3", 5.0);
costMatrixBuilder.addTransportTime("1", "2", 4.0);
costMatrixBuilder.addTransportTime("1", "3", 1.0);
costMatrixBuilder.addTransportTime("2", "3", 2.0);
VehicleRoutingTransportCosts costMatrix = costMatrixBuilder.build();
VehicleRoutingProblem vrp = VehicleRoutingProblem.Builder.newInstance().setFleetSize(FleetSize.INFINITE).setRoutingCost(costMatrix)
.addVehicle(vehicle).addJob(s1).addJob(s2).addJob(s3).build();
VehicleRoutingAlgorithm vra = VehicleRoutingAlgorithms.readAndCreateAlgorithm(vrp, "input/fastAlgo.xml");
Collection<VehicleRoutingProblemSolution> solutions = vra.searchSolutions();
SolutionPrinter.print(Solutions.bestOf(solutions));
new Plotter(vrp, Solutions.bestOf(solutions)).plot("output/yo.png", "po");
}
//define a matrix-builder building a symmetric matrix
VehicleRoutingTransportCostsMatrix.Builder costMatrixBuilder = VehicleRoutingTransportCostsMatrix.Builder.newInstance(true);
costMatrixBuilder.addTransportDistance("0", "1", 10.0);
costMatrixBuilder.addTransportDistance("0", "2", 20.0);
costMatrixBuilder.addTransportDistance("0", "3", 5.0);
costMatrixBuilder.addTransportDistance("1", "2", 4.0);
costMatrixBuilder.addTransportDistance("1", "3", 1.0);
costMatrixBuilder.addTransportDistance("2", "3", 2.0);
costMatrixBuilder.addTransportTime("0", "1", 10.0);
costMatrixBuilder.addTransportTime("0", "2", 20.0);
costMatrixBuilder.addTransportTime("0", "3", 5.0);
costMatrixBuilder.addTransportTime("1", "2", 4.0);
costMatrixBuilder.addTransportTime("1", "3", 1.0);
costMatrixBuilder.addTransportTime("2", "3", 2.0);
VehicleRoutingTransportCosts costMatrix = costMatrixBuilder.build();
VehicleRoutingProblem vrp = VehicleRoutingProblem.Builder.newInstance().setFleetSize(FleetSize.INFINITE).setRoutingCost(costMatrix)
.addVehicle(vehicle).addJob(s1).addJob(s2).addJob(s3).build();
VehicleRoutingAlgorithm vra = VehicleRoutingAlgorithms.readAndCreateAlgorithm(vrp, "input/fastAlgo.xml");
Collection<VehicleRoutingProblemSolution> solutions = vra.searchSolutions();
SolutionPrinter.print(Solutions.bestOf(solutions));
new Plotter(vrp, Solutions.bestOf(solutions)).plot("output/yo.png", "po");
}
}

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.examples;
@ -41,131 +41,131 @@ import java.util.Collection;
public class EnRoutePickupAndDeliveryWithMultipleDepotsAndOpenRoutesExample {
public static void main(String[] args) {
/*
public static void main(String[] args) {
/*
* some preparation - create output folder
*/
Examples.createOutputFolder();
Examples.createOutputFolder();
/*
* get a vehicle type-builder and build a type with the typeId "vehicleType" and a capacity of 2
*/
VehicleTypeImpl.Builder vehicleTypeBuilder = VehicleTypeImpl.Builder.newInstance("vehicleType").addCapacityDimension(0, 2);
vehicleTypeBuilder.setCostPerDistance(1.0);
VehicleType vehicleType = vehicleTypeBuilder.build();
VehicleTypeImpl.Builder vehicleTypeBuilder = VehicleTypeImpl.Builder.newInstance("vehicleType").addCapacityDimension(0, 2);
vehicleTypeBuilder.setCostPerDistance(1.0);
VehicleType vehicleType = vehicleTypeBuilder.build();
/*
* define two vehicles and their start-locations
*
* define two vehicles and their start-locations
*
* the first two do need to return to depot
*/
Builder vehicleBuilder1 = VehicleImpl.Builder.newInstance("vehicles@[10,10]");
vehicleBuilder1.setStartLocation(loc(Coordinate.newInstance(10, 10))).setReturnToDepot(false);
vehicleBuilder1.setType(vehicleType);
VehicleImpl vehicle1 = vehicleBuilder1.build();
Builder vehicleBuilder2 = VehicleImpl.Builder.newInstance("vehicles@[30,30]");
vehicleBuilder2.setStartLocation(loc(Coordinate.newInstance(30, 30))).setReturnToDepot(false);
vehicleBuilder2.setType(vehicleType);
VehicleImpl vehicle2 = vehicleBuilder2.build();
Builder vehicleBuilder3 = VehicleImpl.Builder.newInstance("vehicles@[10,30]");
vehicleBuilder3.setStartLocation(loc(Coordinate.newInstance(10, 30)));
vehicleBuilder3.setType(vehicleType);
VehicleImpl vehicle3 = vehicleBuilder3.build();
Builder vehicleBuilder4 = VehicleImpl.Builder.newInstance("vehicles@[30,10]");
vehicleBuilder4.setStartLocation(loc(Coordinate.newInstance(30, 10)));
vehicleBuilder4.setType(vehicleType);
VehicleImpl vehicle4 = vehicleBuilder4.build();
Builder vehicleBuilder1 = VehicleImpl.Builder.newInstance("vehicles@[10,10]");
vehicleBuilder1.setStartLocation(loc(Coordinate.newInstance(10, 10))).setReturnToDepot(false);
vehicleBuilder1.setType(vehicleType);
VehicleImpl vehicle1 = vehicleBuilder1.build();
Builder vehicleBuilder2 = VehicleImpl.Builder.newInstance("vehicles@[30,30]");
vehicleBuilder2.setStartLocation(loc(Coordinate.newInstance(30, 30))).setReturnToDepot(false);
vehicleBuilder2.setType(vehicleType);
VehicleImpl vehicle2 = vehicleBuilder2.build();
Builder vehicleBuilder3 = VehicleImpl.Builder.newInstance("vehicles@[10,30]");
vehicleBuilder3.setStartLocation(loc(Coordinate.newInstance(10, 30)));
vehicleBuilder3.setType(vehicleType);
VehicleImpl vehicle3 = vehicleBuilder3.build();
Builder vehicleBuilder4 = VehicleImpl.Builder.newInstance("vehicles@[30,10]");
vehicleBuilder4.setStartLocation(loc(Coordinate.newInstance(30, 10)));
vehicleBuilder4.setType(vehicleType);
VehicleImpl vehicle4 = vehicleBuilder4.build();
/*
* build shipments at the required locations, each with a capacity-demand of 1.
*/
Shipment shipment1 = Shipment.Builder.newInstance("1").addSizeDimension(0, 1).setPickupLocation(loc(Coordinate.newInstance(5, 7))).setDeliveryLocation(loc(Coordinate.newInstance(6, 9))).build();
Shipment shipment2 = Shipment.Builder.newInstance("2").addSizeDimension(0, 1).setPickupLocation(loc(Coordinate.newInstance(5, 13))).setDeliveryLocation(loc(Coordinate.newInstance(6, 11))).build();
Shipment shipment3 = Shipment.Builder.newInstance("3").addSizeDimension(0, 1).setPickupLocation(loc(Coordinate.newInstance(15, 7))).setDeliveryLocation(loc(Coordinate.newInstance(14, 9))).build();
Shipment shipment4 = Shipment.Builder.newInstance("4").addSizeDimension(0, 1).setPickupLocation(loc(Coordinate.newInstance(15, 13))).setDeliveryLocation(loc(Coordinate.newInstance(14, 11))).build();
Shipment shipment5 = Shipment.Builder.newInstance("5").addSizeDimension(0, 1).setPickupLocation(loc(Coordinate.newInstance(25, 27))).setDeliveryLocation(loc(Coordinate.newInstance(26, 29))).build();
Shipment shipment6 = Shipment.Builder.newInstance("6").addSizeDimension(0, 1).setPickupLocation(loc(Coordinate.newInstance(25, 33))).setDeliveryLocation(loc(Coordinate.newInstance(26, 31))).build();
Shipment shipment7 = Shipment.Builder.newInstance("7").addSizeDimension(0, 1).setPickupLocation(loc(Coordinate.newInstance(35, 27))).setDeliveryLocation(loc(Coordinate.newInstance(34, 29))).build();
Shipment shipment8 = Shipment.Builder.newInstance("8").addSizeDimension(0, 1).setPickupLocation(loc(Coordinate.newInstance(35, 33))).setDeliveryLocation(loc(Coordinate.newInstance(34, 31))).build();
Shipment shipment9 = Shipment.Builder.newInstance("9").addSizeDimension(0, 1).setPickupLocation(loc(Coordinate.newInstance(5, 27))).setDeliveryLocation(loc(Coordinate.newInstance(6, 29))).build();
Shipment shipment10 = Shipment.Builder.newInstance("10").addSizeDimension(0, 1).setPickupLocation(loc(Coordinate.newInstance(5, 33))).setDeliveryLocation(loc(Coordinate.newInstance(6, 31))).build();
Shipment shipment11 = Shipment.Builder.newInstance("11").addSizeDimension(0, 1).setPickupLocation(loc(Coordinate.newInstance(15, 27))).setDeliveryLocation(loc(Coordinate.newInstance(14, 29))).build();
Shipment shipment12 = Shipment.Builder.newInstance("12").addSizeDimension(0, 1).setPickupLocation(loc(Coordinate.newInstance(15, 33))).setDeliveryLocation(loc(Coordinate.newInstance(14, 31))).build();
Shipment shipment13 = Shipment.Builder.newInstance("13").addSizeDimension(0, 1).setPickupLocation(loc(Coordinate.newInstance(25, 7))).setDeliveryLocation(loc(Coordinate.newInstance(26, 9))).build();
Shipment shipment14 = Shipment.Builder.newInstance("14").addSizeDimension(0, 1).setPickupLocation(loc(Coordinate.newInstance(25, 13))).setDeliveryLocation(loc(Coordinate.newInstance(26, 11))).build();
Shipment shipment15 = Shipment.Builder.newInstance("15").addSizeDimension(0, 1).setPickupLocation(loc(Coordinate.newInstance(35, 7))).setDeliveryLocation(loc(Coordinate.newInstance(34, 9))).build();
Shipment shipment16 = Shipment.Builder.newInstance("16").addSizeDimension(0, 1).setPickupLocation(loc(Coordinate.newInstance(35, 13))).setDeliveryLocation(loc(Coordinate.newInstance(34, 11))).build();
VehicleRoutingProblem.Builder vrpBuilder = VehicleRoutingProblem.Builder.newInstance();
vrpBuilder.addVehicle(vehicle1).addVehicle(vehicle2).addVehicle(vehicle3).addVehicle(vehicle4);
vrpBuilder.addJob(shipment1).addJob(shipment2).addJob(shipment3).addJob(shipment4);
vrpBuilder.addJob(shipment5).addJob(shipment6).addJob(shipment7).addJob(shipment8);
vrpBuilder.addJob(shipment9).addJob(shipment10).addJob(shipment11).addJob(shipment12);
vrpBuilder.addJob(shipment13).addJob(shipment14).addJob(shipment15).addJob(shipment16);
vrpBuilder.setFleetSize(FleetSize.FINITE);
VehicleRoutingProblem problem = vrpBuilder.build();
Shipment shipment1 = Shipment.Builder.newInstance("1").addSizeDimension(0, 1).setPickupLocation(loc(Coordinate.newInstance(5, 7))).setDeliveryLocation(loc(Coordinate.newInstance(6, 9))).build();
Shipment shipment2 = Shipment.Builder.newInstance("2").addSizeDimension(0, 1).setPickupLocation(loc(Coordinate.newInstance(5, 13))).setDeliveryLocation(loc(Coordinate.newInstance(6, 11))).build();
Shipment shipment3 = Shipment.Builder.newInstance("3").addSizeDimension(0, 1).setPickupLocation(loc(Coordinate.newInstance(15, 7))).setDeliveryLocation(loc(Coordinate.newInstance(14, 9))).build();
Shipment shipment4 = Shipment.Builder.newInstance("4").addSizeDimension(0, 1).setPickupLocation(loc(Coordinate.newInstance(15, 13))).setDeliveryLocation(loc(Coordinate.newInstance(14, 11))).build();
Shipment shipment5 = Shipment.Builder.newInstance("5").addSizeDimension(0, 1).setPickupLocation(loc(Coordinate.newInstance(25, 27))).setDeliveryLocation(loc(Coordinate.newInstance(26, 29))).build();
Shipment shipment6 = Shipment.Builder.newInstance("6").addSizeDimension(0, 1).setPickupLocation(loc(Coordinate.newInstance(25, 33))).setDeliveryLocation(loc(Coordinate.newInstance(26, 31))).build();
Shipment shipment7 = Shipment.Builder.newInstance("7").addSizeDimension(0, 1).setPickupLocation(loc(Coordinate.newInstance(35, 27))).setDeliveryLocation(loc(Coordinate.newInstance(34, 29))).build();
Shipment shipment8 = Shipment.Builder.newInstance("8").addSizeDimension(0, 1).setPickupLocation(loc(Coordinate.newInstance(35, 33))).setDeliveryLocation(loc(Coordinate.newInstance(34, 31))).build();
Shipment shipment9 = Shipment.Builder.newInstance("9").addSizeDimension(0, 1).setPickupLocation(loc(Coordinate.newInstance(5, 27))).setDeliveryLocation(loc(Coordinate.newInstance(6, 29))).build();
Shipment shipment10 = Shipment.Builder.newInstance("10").addSizeDimension(0, 1).setPickupLocation(loc(Coordinate.newInstance(5, 33))).setDeliveryLocation(loc(Coordinate.newInstance(6, 31))).build();
Shipment shipment11 = Shipment.Builder.newInstance("11").addSizeDimension(0, 1).setPickupLocation(loc(Coordinate.newInstance(15, 27))).setDeliveryLocation(loc(Coordinate.newInstance(14, 29))).build();
Shipment shipment12 = Shipment.Builder.newInstance("12").addSizeDimension(0, 1).setPickupLocation(loc(Coordinate.newInstance(15, 33))).setDeliveryLocation(loc(Coordinate.newInstance(14, 31))).build();
Shipment shipment13 = Shipment.Builder.newInstance("13").addSizeDimension(0, 1).setPickupLocation(loc(Coordinate.newInstance(25, 7))).setDeliveryLocation(loc(Coordinate.newInstance(26, 9))).build();
Shipment shipment14 = Shipment.Builder.newInstance("14").addSizeDimension(0, 1).setPickupLocation(loc(Coordinate.newInstance(25, 13))).setDeliveryLocation(loc(Coordinate.newInstance(26, 11))).build();
Shipment shipment15 = Shipment.Builder.newInstance("15").addSizeDimension(0, 1).setPickupLocation(loc(Coordinate.newInstance(35, 7))).setDeliveryLocation(loc(Coordinate.newInstance(34, 9))).build();
Shipment shipment16 = Shipment.Builder.newInstance("16").addSizeDimension(0, 1).setPickupLocation(loc(Coordinate.newInstance(35, 13))).setDeliveryLocation(loc(Coordinate.newInstance(34, 11))).build();
VehicleRoutingProblem.Builder vrpBuilder = VehicleRoutingProblem.Builder.newInstance();
vrpBuilder.addVehicle(vehicle1).addVehicle(vehicle2).addVehicle(vehicle3).addVehicle(vehicle4);
vrpBuilder.addJob(shipment1).addJob(shipment2).addJob(shipment3).addJob(shipment4);
vrpBuilder.addJob(shipment5).addJob(shipment6).addJob(shipment7).addJob(shipment8);
vrpBuilder.addJob(shipment9).addJob(shipment10).addJob(shipment11).addJob(shipment12);
vrpBuilder.addJob(shipment13).addJob(shipment14).addJob(shipment15).addJob(shipment16);
vrpBuilder.setFleetSize(FleetSize.FINITE);
VehicleRoutingProblem problem = vrpBuilder.build();
/*
* get the algorithm out-of-the-box.
* get the algorithm out-of-the-box.
*/
VehicleRoutingAlgorithm algorithm = VehicleRoutingAlgorithms.readAndCreateAlgorithm(problem, "input/algorithmConfig.xml");
VehicleRoutingAlgorithm algorithm = VehicleRoutingAlgorithms.readAndCreateAlgorithm(problem, "input/algorithmConfig.xml");
// algorithm.setMaxIterations(30000);
/*
* and search a solution
*/
Collection<VehicleRoutingProblemSolution> solutions = algorithm.searchSolutions();
Collection<VehicleRoutingProblemSolution> solutions = algorithm.searchSolutions();
/*
* get the best
* get the best
*/
VehicleRoutingProblemSolution bestSolution = Solutions.bestOf(solutions);
VehicleRoutingProblemSolution bestSolution = Solutions.bestOf(solutions);
/*
* write out problem and solution to xml-file
*/
new VrpXMLWriter(problem, solutions).write("output/shipment-problem-with-solution.xml");
new VrpXMLWriter(problem, solutions).write("output/shipment-problem-with-solution.xml");
/*
* print nRoutes and totalCosts of bestSolution
*/
SolutionPrinter.print(bestSolution);
SolutionPrinter.print(bestSolution);
/*
* plot problem without solution
*/
Plotter problemPlotter = new Plotter(problem);
problemPlotter.plotShipments(true);
problemPlotter.plot("output/enRoutePickupAndDeliveryWithMultipleLocationsExample_problem.png", "en-route pickup and delivery");
Plotter problemPlotter = new Plotter(problem);
problemPlotter.plotShipments(true);
problemPlotter.plot("output/enRoutePickupAndDeliveryWithMultipleLocationsExample_problem.png", "en-route pickup and delivery");
/*
* plot problem with solution
*/
Plotter solutionPlotter = new Plotter(problem,Arrays.asList(Solutions.bestOf(solutions).getRoutes().iterator().next()));
solutionPlotter.plotShipments(true);
solutionPlotter.plot("output/enRoutePickupAndDeliveryWithMultipleLocationsExample_solution.png", "en-route pickup and delivery");
new GraphStreamViewer(problem,Solutions.bestOf(solutions)).labelWith(Label.ACTIVITY).setRenderDelay(100).setRenderShipments(true).display();
}
Plotter solutionPlotter = new Plotter(problem, Arrays.asList(Solutions.bestOf(solutions).getRoutes().iterator().next()));
solutionPlotter.plotShipments(true);
solutionPlotter.plot("output/enRoutePickupAndDeliveryWithMultipleLocationsExample_solution.png", "en-route pickup and delivery");
private static Location loc(Coordinate coordinate){
return Location.Builder.newInstance().setCoordinate(coordinate).build();
}
new GraphStreamViewer(problem, Solutions.bestOf(solutions)).labelWith(Label.ACTIVITY).setRenderDelay(100).setRenderShipments(true).display();
}
private static Location loc(Coordinate coordinate) {
return Location.Builder.newInstance().setCoordinate(coordinate).build();
}
}

View file

@ -34,99 +34,98 @@ import java.util.Collection;
/**
* customers (id,x,y,demand)
* 1 22 22 18
* 2 36 26 26
* 3 21 45 11
* 4 45 35 30
* 5 55 20 21
* 6 33 34 19
* 7 50 50 15
* 8 55 45 16
* 9 26 59 29
* 1 22 22 18
* 2 36 26 26
* 3 21 45 11
* 4 45 35 30
* 5 55 20 21
* 6 33 34 19
* 7 50 50 15
* 8 55 45 16
* 9 26 59 29
* 10 40 66 26
* 11 55 65 37
* 12 35 51 16
* 13 62 35 12
* 14 62 57 31
* 15 62 24 8
* 16 21 36 19
* 17 33 44 20
* 18 9 56 13
* 19 62 48 15
* 11 55 65 37
* 12 35 51 16
* 13 62 35 12
* 14 62 57 31
* 15 62 24 8
* 16 21 36 19
* 17 33 44 20
* 18 9 56 13
* 19 62 48 15
* 20 66 14 22
*
* <p/>
* vehicles (id,cap,fixed costs, perDistance, #vehicles) at location (40,40)
* 1 120 1000 1.0 2
* 2 160 1500 1.1 1
* 3 300 3500 1.4 1
*
* @author schroeder
*
* @author schroeder
*/
public class HVRPExample {
public static void main(String[] args) {
VehicleRoutingProblem.Builder vrpBuilder = VehicleRoutingProblem.Builder.newInstance();
//add customers
vrpBuilder.addJob(Service.Builder.newInstance("1").addSizeDimension(0, 18).setLocation(Location.newInstance(22, 22)).build());
vrpBuilder.addJob(Service.Builder.newInstance("2").addSizeDimension(0, 26).setLocation(Location.newInstance(36, 26)).build());
vrpBuilder.addJob(Service.Builder.newInstance("3").addSizeDimension(0, 11).setLocation(Location.newInstance(21, 45)).build());
vrpBuilder.addJob(Service.Builder.newInstance("4").addSizeDimension(0, 30).setLocation(Location.newInstance(45, 35)).build());
vrpBuilder.addJob(Service.Builder.newInstance("5").addSizeDimension(0, 21).setLocation(Location.newInstance(55, 20)).build());
vrpBuilder.addJob(Service.Builder.newInstance("6").addSizeDimension(0, 19).setLocation(Location.newInstance(33, 34)).build());
vrpBuilder.addJob(Service.Builder.newInstance("7").addSizeDimension(0, 15).setLocation(Location.newInstance(50, 50)).build());
vrpBuilder.addJob(Service.Builder.newInstance("8").addSizeDimension(0, 16).setLocation(Location.newInstance(55, 45)).build());
vrpBuilder.addJob(Service.Builder.newInstance("9").addSizeDimension(0, 29).setLocation(Location.newInstance(26, 59)).build());
vrpBuilder.addJob(Service.Builder.newInstance("10").addSizeDimension(0, 26).setLocation(Location.newInstance(40, 66)).build());
vrpBuilder.addJob(Service.Builder.newInstance("11").addSizeDimension(0, 37).setLocation(Location.newInstance(55, 56)).build());
vrpBuilder.addJob(Service.Builder.newInstance("12").addSizeDimension(0, 16).setLocation(Location.newInstance(35, 51)).build());
vrpBuilder.addJob(Service.Builder.newInstance("13").addSizeDimension(0, 12).setLocation(Location.newInstance(62, 35)).build());
vrpBuilder.addJob(Service.Builder.newInstance("14").addSizeDimension(0, 31).setLocation(Location.newInstance(62, 57)).build());
vrpBuilder.addJob(Service.Builder.newInstance("15").addSizeDimension(0, 8).setLocation(Location.newInstance(62, 24)).build());
vrpBuilder.addJob(Service.Builder.newInstance("16").addSizeDimension(0, 19).setLocation(Location.newInstance(21, 36)).build());
vrpBuilder.addJob(Service.Builder.newInstance("17").addSizeDimension(0, 20).setLocation(Location.newInstance(33, 44)).build());
vrpBuilder.addJob(Service.Builder.newInstance("18").addSizeDimension(0, 13).setLocation(Location.newInstance(9, 56)).build());
vrpBuilder.addJob(Service.Builder.newInstance("19").addSizeDimension(0, 15).setLocation(Location.newInstance(62, 48)).build());
vrpBuilder.addJob(Service.Builder.newInstance("20").addSizeDimension(0, 22).setLocation(Location.newInstance(66, 14)).build());
//add vehicle - finite fleet
//2xtype1
VehicleType type1 = VehicleTypeImpl.Builder.newInstance("type_1").addCapacityDimension(0, 120).setCostPerDistance(1.0).build();
VehicleImpl vehicle1_1 = VehicleImpl.Builder.newInstance("1_1").setStartLocation(Location.newInstance(40, 40)).setType(type1).build();
vrpBuilder.addVehicle(vehicle1_1);
VehicleImpl vehicle1_2 = VehicleImpl.Builder.newInstance("1_2").setStartLocation(Location.newInstance(40, 40)).setType(type1).build();
vrpBuilder.addVehicle(vehicle1_2);
//1xtype2
VehicleType type2 = VehicleTypeImpl.Builder.newInstance("type_2").addCapacityDimension(0, 160).setCostPerDistance(1.1).build();
VehicleImpl vehicle2_1 = VehicleImpl.Builder.newInstance("2_1").setStartLocation(Location.newInstance(40, 40)).setType(type2).build();
vrpBuilder.addVehicle(vehicle2_1);
//1xtype3
VehicleType type3 = VehicleTypeImpl.Builder.newInstance("type_3").addCapacityDimension(0, 300).setCostPerDistance(1.3).build();
VehicleImpl vehicle3_1 = VehicleImpl.Builder.newInstance("3_1").setStartLocation(Location.newInstance(40, 40)).setType(type3).build();
vrpBuilder.addVehicle(vehicle3_1);
//add penaltyVehicles to allow invalid solutions temporarily
public static void main(String[] args) {
VehicleRoutingProblem.Builder vrpBuilder = VehicleRoutingProblem.Builder.newInstance();
//add customers
vrpBuilder.addJob(Service.Builder.newInstance("1").addSizeDimension(0, 18).setLocation(Location.newInstance(22, 22)).build());
vrpBuilder.addJob(Service.Builder.newInstance("2").addSizeDimension(0, 26).setLocation(Location.newInstance(36, 26)).build());
vrpBuilder.addJob(Service.Builder.newInstance("3").addSizeDimension(0, 11).setLocation(Location.newInstance(21, 45)).build());
vrpBuilder.addJob(Service.Builder.newInstance("4").addSizeDimension(0, 30).setLocation(Location.newInstance(45, 35)).build());
vrpBuilder.addJob(Service.Builder.newInstance("5").addSizeDimension(0, 21).setLocation(Location.newInstance(55, 20)).build());
vrpBuilder.addJob(Service.Builder.newInstance("6").addSizeDimension(0, 19).setLocation(Location.newInstance(33, 34)).build());
vrpBuilder.addJob(Service.Builder.newInstance("7").addSizeDimension(0, 15).setLocation(Location.newInstance(50, 50)).build());
vrpBuilder.addJob(Service.Builder.newInstance("8").addSizeDimension(0, 16).setLocation(Location.newInstance(55, 45)).build());
vrpBuilder.addJob(Service.Builder.newInstance("9").addSizeDimension(0, 29).setLocation(Location.newInstance(26, 59)).build());
vrpBuilder.addJob(Service.Builder.newInstance("10").addSizeDimension(0, 26).setLocation(Location.newInstance(40, 66)).build());
vrpBuilder.addJob(Service.Builder.newInstance("11").addSizeDimension(0, 37).setLocation(Location.newInstance(55, 56)).build());
vrpBuilder.addJob(Service.Builder.newInstance("12").addSizeDimension(0, 16).setLocation(Location.newInstance(35, 51)).build());
vrpBuilder.addJob(Service.Builder.newInstance("13").addSizeDimension(0, 12).setLocation(Location.newInstance(62, 35)).build());
vrpBuilder.addJob(Service.Builder.newInstance("14").addSizeDimension(0, 31).setLocation(Location.newInstance(62, 57)).build());
vrpBuilder.addJob(Service.Builder.newInstance("15").addSizeDimension(0, 8).setLocation(Location.newInstance(62, 24)).build());
vrpBuilder.addJob(Service.Builder.newInstance("16").addSizeDimension(0, 19).setLocation(Location.newInstance(21, 36)).build());
vrpBuilder.addJob(Service.Builder.newInstance("17").addSizeDimension(0, 20).setLocation(Location.newInstance(33, 44)).build());
vrpBuilder.addJob(Service.Builder.newInstance("18").addSizeDimension(0, 13).setLocation(Location.newInstance(9, 56)).build());
vrpBuilder.addJob(Service.Builder.newInstance("19").addSizeDimension(0, 15).setLocation(Location.newInstance(62, 48)).build());
vrpBuilder.addJob(Service.Builder.newInstance("20").addSizeDimension(0, 22).setLocation(Location.newInstance(66, 14)).build());
//add vehicle - finite fleet
//2xtype1
VehicleType type1 = VehicleTypeImpl.Builder.newInstance("type_1").addCapacityDimension(0, 120).setCostPerDistance(1.0).build();
VehicleImpl vehicle1_1 = VehicleImpl.Builder.newInstance("1_1").setStartLocation(Location.newInstance(40, 40)).setType(type1).build();
vrpBuilder.addVehicle(vehicle1_1);
VehicleImpl vehicle1_2 = VehicleImpl.Builder.newInstance("1_2").setStartLocation(Location.newInstance(40, 40)).setType(type1).build();
vrpBuilder.addVehicle(vehicle1_2);
//1xtype2
VehicleType type2 = VehicleTypeImpl.Builder.newInstance("type_2").addCapacityDimension(0, 160).setCostPerDistance(1.1).build();
VehicleImpl vehicle2_1 = VehicleImpl.Builder.newInstance("2_1").setStartLocation(Location.newInstance(40, 40)).setType(type2).build();
vrpBuilder.addVehicle(vehicle2_1);
//1xtype3
VehicleType type3 = VehicleTypeImpl.Builder.newInstance("type_3").addCapacityDimension(0, 300).setCostPerDistance(1.3).build();
VehicleImpl vehicle3_1 = VehicleImpl.Builder.newInstance("3_1").setStartLocation(Location.newInstance(40, 40)).setType(type3).build();
vrpBuilder.addVehicle(vehicle3_1);
//add penaltyVehicles to allow invalid solutions temporarily
// vrpBuilder.addPenaltyVehicles(5, 1000);
//set fleetsize finite
vrpBuilder.setFleetSize(FleetSize.FINITE);
//build problem
VehicleRoutingProblem vrp = vrpBuilder.build();
VehicleRoutingAlgorithm vra = VehicleRoutingAlgorithms.readAndCreateAlgorithm(vrp, "input/algorithmConfigWithSchrimpfAcceptance.xml");
Collection<VehicleRoutingProblemSolution> solutions = vra.searchSolutions();
VehicleRoutingProblemSolution best = Solutions.bestOf(solutions);
SolutionPrinter.print(vrp, best, SolutionPrinter.Print.VERBOSE);
new GraphStreamViewer(vrp, best).setRenderDelay(100).display();
}
//set fleetsize finite
vrpBuilder.setFleetSize(FleetSize.FINITE);
//build problem
VehicleRoutingProblem vrp = vrpBuilder.build();
VehicleRoutingAlgorithm vra = VehicleRoutingAlgorithms.readAndCreateAlgorithm(vrp, "input/algorithmConfigWithSchrimpfAcceptance.xml");
Collection<VehicleRoutingProblemSolution> solutions = vra.searchSolutions();
VehicleRoutingProblemSolution best = Solutions.bestOf(solutions);
SolutionPrinter.print(vrp, best, SolutionPrinter.Print.VERBOSE);
new GraphStreamViewer(vrp, best).setRenderDelay(100).display();
}
}

View file

@ -43,11 +43,10 @@ import java.util.Collection;
/**
* Illustrates dependencies between jobs.
*
* <p/>
* The hard requirement here is that three jobs with name "get key", "use key" and "deliver key" need to
* be not only in loose sequence in one particular route but also one after another (without any other activities
* between them).
*
*/
public class JobAndActivityDependenciesExample {
@ -78,19 +77,18 @@ public class JobAndActivityDependenciesExample {
@Override
public void visit(TourActivity activity) {
if(((TourActivity.JobActivity)activity).getJob().getName().equals("use key")) {
if (((TourActivity.JobActivity) activity).getJob().getName().equals("use key")) {
stateManager.putProblemState(keyUsedStateId, VehicleRoute.class, route);
}
else if(((TourActivity.JobActivity)activity).getJob().getName().equals("get key")) {
} else if (((TourActivity.JobActivity) activity).getJob().getName().equals("get key")) {
stateManager.putProblemState(keyPickedStateId, VehicleRoute.class, route);
}
else if(((TourActivity.JobActivity)activity).getJob().getName().equals("deliver key")) {
} else if (((TourActivity.JobActivity) activity).getJob().getName().equals("deliver key")) {
stateManager.putProblemState(keyDeliveredStateId, VehicleRoute.class, route);
}
}
@Override
public void finish() {}
public void finish() {
}
}
static class GetUseAndDeliverHardRouteContraint implements HardRouteConstraint {
@ -112,20 +110,20 @@ public class JobAndActivityDependenciesExample {
@Override
public boolean fulfilled(JobInsertionContext iFacts) {
if(iFacts.getJob().getName().equals("get key") || iFacts.getJob().getName().equals("use key")
|| iFacts.getJob().getName().equals("deliver key")){
if (iFacts.getJob().getName().equals("get key") || iFacts.getJob().getName().equals("use key")
|| iFacts.getJob().getName().equals("deliver key")) {
VehicleRoute routeOfPickupKey = stateManager.getProblemState(keyPickedStateId, VehicleRoute.class);
VehicleRoute routeOfUseKey = stateManager.getProblemState(keyUsedStateId, VehicleRoute.class);
VehicleRoute routeOfDeliverKey = stateManager.getProblemState(keyDeliveredStateId, VehicleRoute.class);
if( routeOfPickupKey != null ){
if( routeOfPickupKey != iFacts.getRoute() ) return false;
if (routeOfPickupKey != null) {
if (routeOfPickupKey != iFacts.getRoute()) return false;
}
if( routeOfUseKey != null ){
if( routeOfUseKey != iFacts.getRoute() ) return false;
if (routeOfUseKey != null) {
if (routeOfUseKey != iFacts.getRoute()) return false;
}
if( routeOfDeliverKey != null ) {
if( routeOfDeliverKey != iFacts.getRoute() ) return false;
if (routeOfDeliverKey != null) {
if (routeOfDeliverKey != iFacts.getRoute()) return false;
}
}
return true;
@ -157,50 +155,50 @@ public class JobAndActivityDependenciesExample {
VehicleRoute routeOfUseKey = stateManager.getProblemState(keyUsedStateId, VehicleRoute.class);
VehicleRoute routeOfDeliverKey = stateManager.getProblemState(keyDeliveredStateId, VehicleRoute.class);
if( !isPickupKey(newAct) && !isUseKey(newAct) && !isDeliverKey(newAct) ){
if(isPickupKey(prevAct) && isUseKey(nextAct)) return ConstraintsStatus.NOT_FULFILLED;
if(isPickupKey(prevAct) && isDeliverKey(nextAct)) return ConstraintsStatus.NOT_FULFILLED;
if(isUseKey(prevAct) && isDeliverKey(nextAct)) return ConstraintsStatus.NOT_FULFILLED;
if (!isPickupKey(newAct) && !isUseKey(newAct) && !isDeliverKey(newAct)) {
if (isPickupKey(prevAct) && isUseKey(nextAct)) return ConstraintsStatus.NOT_FULFILLED;
if (isPickupKey(prevAct) && isDeliverKey(nextAct)) return ConstraintsStatus.NOT_FULFILLED;
if (isUseKey(prevAct) && isDeliverKey(nextAct)) return ConstraintsStatus.NOT_FULFILLED;
}
if( isPickupKey(newAct) ) {
if ( routeOfUseKey != null){
if ( !isUseKey(nextAct) ) return ConstraintsStatus.NOT_FULFILLED;
if (isPickupKey(newAct)) {
if (routeOfUseKey != null) {
if (!isUseKey(nextAct)) return ConstraintsStatus.NOT_FULFILLED;
}
if ( routeOfDeliverKey != null ){
if ( !isDeliverKey( nextAct )) return ConstraintsStatus.NOT_FULFILLED;
if (routeOfDeliverKey != null) {
if (!isDeliverKey(nextAct)) return ConstraintsStatus.NOT_FULFILLED;
}
return ConstraintsStatus.FULFILLED;
}
if( isUseKey(newAct) ) {
if ( routeOfPickupKey != null ) {
if ( !isPickupKey(prevAct) ) return ConstraintsStatus.NOT_FULFILLED;
if (isUseKey(newAct)) {
if (routeOfPickupKey != null) {
if (!isPickupKey(prevAct)) return ConstraintsStatus.NOT_FULFILLED;
}
if ( routeOfDeliverKey != null ) {
if ( !isDeliverKey(nextAct) ) return ConstraintsStatus.NOT_FULFILLED;
if (routeOfDeliverKey != null) {
if (!isDeliverKey(nextAct)) return ConstraintsStatus.NOT_FULFILLED;
}
return ConstraintsStatus.FULFILLED;
}
if( isDeliverKey(newAct) ){
if( routeOfUseKey != null ) {
if ( !isUseKey(prevAct) ) return ConstraintsStatus.NOT_FULFILLED;
if (isDeliverKey(newAct)) {
if (routeOfUseKey != null) {
if (!isUseKey(prevAct)) return ConstraintsStatus.NOT_FULFILLED;
}
}
return ConstraintsStatus.FULFILLED;
}
private boolean isPickupKey(TourActivity act) {
if(!(act instanceof TourActivity.JobActivity)) return false;
return ((TourActivity.JobActivity)act).getJob().getName().equals("get key");
if (!(act instanceof TourActivity.JobActivity)) return false;
return ((TourActivity.JobActivity) act).getJob().getName().equals("get key");
}
private boolean isUseKey(TourActivity act) {
if(!(act instanceof TourActivity.JobActivity)) return false;
return ((TourActivity.JobActivity)act).getJob().getName().equals("use key");
if (!(act instanceof TourActivity.JobActivity)) return false;
return ((TourActivity.JobActivity) act).getJob().getName().equals("use key");
}
private boolean isDeliverKey(TourActivity act) {
if(!(act instanceof TourActivity.JobActivity)) return false;
return ((TourActivity.JobActivity)act).getJob().getName().equals("deliver key");
if (!(act instanceof TourActivity.JobActivity)) return false;
return ((TourActivity.JobActivity) act).getJob().getName().equals("deliver key");
}
@ -209,54 +207,54 @@ public class JobAndActivityDependenciesExample {
public static void main(String[] args) {
VehicleImpl driver1 = VehicleImpl.Builder.newInstance("driver1")
.addSkill("driver1")
.setStartLocation(Location.newInstance(0, 0)).setReturnToDepot(false).build();
.addSkill("driver1")
.setStartLocation(Location.newInstance(0, 0)).setReturnToDepot(false).build();
VehicleImpl driver3 = VehicleImpl.Builder.newInstance("driver3")
.addSkill("driver3")
.setStartLocation(Location.newInstance(-3, 5)).setReturnToDepot(true).build();
.addSkill("driver3")
.setStartLocation(Location.newInstance(-3, 5)).setReturnToDepot(true).build();
Service s1 = Service.Builder.newInstance("s1")
.addRequiredSkill("driver1")
.setName("install new device")
.setLocation(Location.newInstance(2, 2)).build();
.addRequiredSkill("driver1")
.setName("install new device")
.setLocation(Location.newInstance(2, 2)).build();
Service s2 = Service.Builder.newInstance("s2")
.addRequiredSkill("driver3")
.setName("deliver key")
.setLocation(Location.newInstance(2, 4)).build();
.addRequiredSkill("driver3")
.setName("deliver key")
.setLocation(Location.newInstance(2, 4)).build();
Service s3 = Service.Builder.newInstance("s3")
.addRequiredSkill("driver1")
.setName("repair heater")
.setLocation(Location.newInstance(-2, 2)).build();
.addRequiredSkill("driver1")
.setName("repair heater")
.setLocation(Location.newInstance(-2, 2)).build();
Service s4 = Service.Builder.newInstance("s4")
.addRequiredSkill("driver3")
.setName("get key")
.setLocation(Location.newInstance(-2.3, 4)).build();
.addRequiredSkill("driver3")
.setName("get key")
.setLocation(Location.newInstance(-2.3, 4)).build();
Service s5 = Service.Builder.newInstance("s5")
.addRequiredSkill("driver1")
.setName("cleaning")
.setLocation(Location.newInstance(1, 5)).build();
.addRequiredSkill("driver1")
.setName("cleaning")
.setLocation(Location.newInstance(1, 5)).build();
Service s6 = Service.Builder.newInstance("s6")
.addRequiredSkill("driver3")
.setName("use key")
.setLocation(Location.newInstance(-2, 3)).build();
.addRequiredSkill("driver3")
.setName("use key")
.setLocation(Location.newInstance(-2, 3)).build();
Service s7 = Service.Builder.newInstance("s7")
.addRequiredSkill("driver3")
.setName("maintenance")
.setLocation(Location.newInstance(-1.7, 3.5)).build();
.addRequiredSkill("driver3")
.setName("maintenance")
.setLocation(Location.newInstance(-1.7, 3.5)).build();
VehicleRoutingProblem.Builder vrpBuilder = VehicleRoutingProblem.Builder.newInstance().setFleetSize(VehicleRoutingProblem.FleetSize.FINITE)
.addJob(s1).addJob(s2).addJob(s3).addJob(s4).addJob(s5).addJob(s6).addJob(s7)
.addVehicle(driver1).addVehicle(driver3);
.addJob(s1).addJob(s2).addJob(s3).addJob(s4).addJob(s5).addJob(s6).addJob(s7)
.addVehicle(driver1).addVehicle(driver3);
VehicleRoutingProblem vrp = vrpBuilder.build();
VehicleRoutingAlgorithmBuilder vraBuilder = new VehicleRoutingAlgorithmBuilder(vrp,"input/algorithmConfig.xml");
VehicleRoutingAlgorithmBuilder vraBuilder = new VehicleRoutingAlgorithmBuilder(vrp, "input/algorithmConfig.xml");
vraBuilder.addDefaultCostCalculators();
vraBuilder.addCoreConstraints();
@ -264,13 +262,13 @@ public class JobAndActivityDependenciesExample {
StateId keyPicked = stateManager.createStateId("key-picked");
StateId keyUsed = stateManager.createStateId("key-used");
StateId keyDelivered = stateManager.createStateId("key-delivered");
stateManager.addStateUpdater(new KeyStatusUpdater(stateManager,keyPicked,keyUsed,keyDelivered));
stateManager.addStateUpdater(new KeyStatusUpdater(stateManager, keyPicked, keyUsed, keyDelivered));
ConstraintManager constraintManager = new ConstraintManager(vrp,stateManager);
constraintManager.addConstraint(new GetUseAndDeliverKeySimpleHardActivityConstraint(stateManager,keyPicked,keyUsed,keyDelivered), ConstraintManager.Priority.CRITICAL);
constraintManager.addConstraint(new GetUseAndDeliverHardRouteContraint(stateManager,keyPicked,keyUsed,keyDelivered));
ConstraintManager constraintManager = new ConstraintManager(vrp, stateManager);
constraintManager.addConstraint(new GetUseAndDeliverKeySimpleHardActivityConstraint(stateManager, keyPicked, keyUsed, keyDelivered), ConstraintManager.Priority.CRITICAL);
constraintManager.addConstraint(new GetUseAndDeliverHardRouteContraint(stateManager, keyPicked, keyUsed, keyDelivered));
vraBuilder.setStateAndConstraintManager(stateManager,constraintManager);
vraBuilder.setStateAndConstraintManager(stateManager, constraintManager);
VehicleRoutingAlgorithm vra = vraBuilder.build();
vra.setMaxIterations(100);

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.examples;
@ -41,18 +41,18 @@ import java.util.Collection;
public class MultipleDepotExample {
public static void main(String[] args) {
/*
public static void main(String[] args) {
/*
* some preparation - create output folder
*/
Examples.createOutputFolder();
VehicleRoutingProblem.Builder vrpBuilder = VehicleRoutingProblem.Builder.newInstance();
Examples.createOutputFolder();
VehicleRoutingProblem.Builder vrpBuilder = VehicleRoutingProblem.Builder.newInstance();
/*
* Read cordeau-instance p01, BUT only its services without any vehicles
* Read cordeau-instance p01, BUT only its services without any vehicles
*/
new VrpXMLReader(vrpBuilder).read("input/vrp_cordeau_01.xml");
new VrpXMLReader(vrpBuilder).read("input/vrp_cordeau_01.xml");
/*
* add vehicles with its depots
* 4 depots:
@ -60,36 +60,36 @@ public class MultipleDepotExample {
* (30,40)
* (50,30)
* (60,50)
*
*
* each with 4 vehicles each with a capacity of 80
*/
int nuOfVehicles = 4;
int capacity = 80;
Coordinate firstDepotCoord = Coordinate.newInstance(20, 20);
Coordinate second = Coordinate.newInstance(30, 40);
Coordinate third = Coordinate.newInstance(50, 30);
Coordinate fourth = Coordinate.newInstance(60, 50);
int depotCounter = 1;
for(Coordinate depotCoord : Arrays.asList(firstDepotCoord,second,third,fourth)){
for(int i=0;i<nuOfVehicles;i++){
VehicleTypeImpl vehicleType = VehicleTypeImpl.Builder.newInstance(depotCounter + "_type").addCapacityDimension(0, capacity).setCostPerDistance(1.0).build();
VehicleImpl vehicle = VehicleImpl.Builder.newInstance(depotCounter + "_" + (i + 1) + "_vehicle").setStartLocation(Location.newInstance(depotCoord.getX(), depotCoord.getY())).setType(vehicleType).build();
vrpBuilder.addVehicle(vehicle);
}
depotCounter++;
}
int nuOfVehicles = 4;
int capacity = 80;
Coordinate firstDepotCoord = Coordinate.newInstance(20, 20);
Coordinate second = Coordinate.newInstance(30, 40);
Coordinate third = Coordinate.newInstance(50, 30);
Coordinate fourth = Coordinate.newInstance(60, 50);
int depotCounter = 1;
for (Coordinate depotCoord : Arrays.asList(firstDepotCoord, second, third, fourth)) {
for (int i = 0; i < nuOfVehicles; i++) {
VehicleTypeImpl vehicleType = VehicleTypeImpl.Builder.newInstance(depotCounter + "_type").addCapacityDimension(0, capacity).setCostPerDistance(1.0).build();
VehicleImpl vehicle = VehicleImpl.Builder.newInstance(depotCounter + "_" + (i + 1) + "_vehicle").setStartLocation(Location.newInstance(depotCoord.getX(), depotCoord.getY())).setType(vehicleType).build();
vrpBuilder.addVehicle(vehicle);
}
depotCounter++;
}
/*
* define problem with finite fleet
*/
vrpBuilder.setFleetSize(FleetSize.FINITE);
vrpBuilder.setFleetSize(FleetSize.FINITE);
/*
* build the problem
*/
VehicleRoutingProblem vrp = vrpBuilder.build();
VehicleRoutingProblem vrp = vrpBuilder.build();
/*
* plot to see how the problem looks like
*/
@ -98,17 +98,17 @@ public class MultipleDepotExample {
/*
* solve the problem
*/
VehicleRoutingAlgorithm vra = Jsprit.Builder.newInstance(vrp).setProperty(Jsprit.Parameter.THREADS,"5").buildAlgorithm();
vra.getAlgorithmListeners().addListener(new StopWatch(),Priority.HIGH);
vra.getAlgorithmListeners().addListener(new AlgorithmSearchProgressChartListener("output/progress.png"));
Collection<VehicleRoutingProblemSolution> solutions = vra.searchSolutions();
SolutionPrinter.print(Solutions.bestOf(solutions));
new Plotter(vrp, Solutions.bestOf(solutions)).plot("output/p01_solution.png", "p01");
new GraphStreamViewer(vrp, Solutions.bestOf(solutions)).setRenderDelay(100).display();
}
VehicleRoutingAlgorithm vra = Jsprit.Builder.newInstance(vrp).setProperty(Jsprit.Parameter.THREADS, "5").buildAlgorithm();
vra.getAlgorithmListeners().addListener(new StopWatch(), Priority.HIGH);
vra.getAlgorithmListeners().addListener(new AlgorithmSearchProgressChartListener("output/progress.png"));
Collection<VehicleRoutingProblemSolution> solutions = vra.searchSolutions();
SolutionPrinter.print(Solutions.bestOf(solutions));
new Plotter(vrp, Solutions.bestOf(solutions)).plot("output/p01_solution.png", "p01");
new GraphStreamViewer(vrp, Solutions.bestOf(solutions)).setRenderDelay(100).display();
}
}

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.examples;
@ -43,59 +43,59 @@ import java.util.Collection;
public class MultipleDepotExample2 {
public static void main(String[] args) {
/*
public static void main(String[] args) {
/*
* some preparation - create output folder
*/
Examples.createOutputFolder();
VehicleRoutingProblem.Builder vrpBuilder = VehicleRoutingProblem.Builder.newInstance();
Examples.createOutputFolder();
VehicleRoutingProblem.Builder vrpBuilder = VehicleRoutingProblem.Builder.newInstance();
/*
* Read cordeau-instance p01, BUT only its services without any vehicles
* Read cordeau-instance p01, BUT only its services without any vehicles
*/
new CordeauReader(vrpBuilder).read("input/p08");
new CordeauReader(vrpBuilder).read("input/p08");
/*
* add vehicles with its depots
* 2 depots:
* (-33,33)
* (33,-33)
*
*
* each with 14 vehicles each with a capacity of 500 and a maximum duration of 310
*/
int nuOfVehicles = 13;
int capacity = 500;
double maxDuration = 310;
Coordinate firstDepotCoord = Coordinate.newInstance(-33, 33);
Coordinate second = Coordinate.newInstance(33, -33);
int depotCounter = 1;
for(Coordinate depotCoord : Arrays.asList(firstDepotCoord,second)){
for(int i=0;i<nuOfVehicles;i++){
VehicleType vehicleType = VehicleTypeImpl.Builder.newInstance(depotCounter + "_type")
.addCapacityDimension(0, capacity).setCostPerDistance(1.0).build();
String vehicleId = depotCounter + "_" + (i+1) + "_vehicle";
VehicleImpl.Builder vehicleBuilder = VehicleImpl.Builder.newInstance(vehicleId);
vehicleBuilder.setStartLocation(Location.newInstance(depotCoord.getX(),depotCoord.getY()));
vehicleBuilder.setType(vehicleType);
vehicleBuilder.setLatestArrival(maxDuration);
VehicleImpl vehicle = vehicleBuilder.build();
vrpBuilder.addVehicle(vehicle);
}
depotCounter++;
}
int nuOfVehicles = 13;
int capacity = 500;
double maxDuration = 310;
Coordinate firstDepotCoord = Coordinate.newInstance(-33, 33);
Coordinate second = Coordinate.newInstance(33, -33);
int depotCounter = 1;
for (Coordinate depotCoord : Arrays.asList(firstDepotCoord, second)) {
for (int i = 0; i < nuOfVehicles; i++) {
VehicleType vehicleType = VehicleTypeImpl.Builder.newInstance(depotCounter + "_type")
.addCapacityDimension(0, capacity).setCostPerDistance(1.0).build();
String vehicleId = depotCounter + "_" + (i + 1) + "_vehicle";
VehicleImpl.Builder vehicleBuilder = VehicleImpl.Builder.newInstance(vehicleId);
vehicleBuilder.setStartLocation(Location.newInstance(depotCoord.getX(), depotCoord.getY()));
vehicleBuilder.setType(vehicleType);
vehicleBuilder.setLatestArrival(maxDuration);
VehicleImpl vehicle = vehicleBuilder.build();
vrpBuilder.addVehicle(vehicle);
}
depotCounter++;
}
/*
* define problem with finite fleet
*/
vrpBuilder.setFleetSize(FleetSize.FINITE);
vrpBuilder.setFleetSize(FleetSize.FINITE);
/*
* build the problem
*/
VehicleRoutingProblem vrp = vrpBuilder.build();
VehicleRoutingProblem vrp = vrpBuilder.build();
/*
* plot to see how the problem looks like
*/
@ -104,17 +104,17 @@ public class MultipleDepotExample2 {
/*
* solve the problem
*/
VehicleRoutingAlgorithm vra = Jsprit.Builder.newInstance(vrp).setProperty(Jsprit.Parameter.THREADS,"5").buildAlgorithm();
vra.setMaxIterations(2000);
vra.getAlgorithmListeners().addListener(new StopWatch(),Priority.HIGH);
vra.getAlgorithmListeners().addListener(new AlgorithmSearchProgressChartListener("output/progress.png"));
Collection<VehicleRoutingProblemSolution> solutions = vra.searchSolutions();
SolutionPrinter.print(vrp, Solutions.bestOf(solutions), jsprit.core.reporting.SolutionPrinter.Print.VERBOSE);
VehicleRoutingAlgorithm vra = Jsprit.Builder.newInstance(vrp).setProperty(Jsprit.Parameter.THREADS, "5").buildAlgorithm();
vra.setMaxIterations(2000);
vra.getAlgorithmListeners().addListener(new StopWatch(), Priority.HIGH);
vra.getAlgorithmListeners().addListener(new AlgorithmSearchProgressChartListener("output/progress.png"));
Collection<VehicleRoutingProblemSolution> solutions = vra.searchSolutions();
new Plotter(vrp, Solutions.bestOf(solutions)).plot("output/p08_solution.png", "p08");
new GraphStreamViewer(vrp,Solutions.bestOf(solutions)).setRenderDelay(50).display();
}
SolutionPrinter.print(vrp, Solutions.bestOf(solutions), jsprit.core.reporting.SolutionPrinter.Print.VERBOSE);
new Plotter(vrp, Solutions.bestOf(solutions)).plot("output/p08_solution.png", "p08");
new GraphStreamViewer(vrp, Solutions.bestOf(solutions)).setRenderDelay(50).display();
}
}

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.examples;
@ -38,40 +38,40 @@ import java.util.Collection;
public class MultipleDepotWithInitialRoutesExample {
public static void main(String[] args) {
/*
public static void main(String[] args) {
/*
* some preparation - create output folder
*/
Examples.createOutputFolder();
VehicleRoutingProblem.Builder vrpBuilder = VehicleRoutingProblem.Builder.newInstance();
Examples.createOutputFolder();
VehicleRoutingProblem.Builder vrpBuilder = VehicleRoutingProblem.Builder.newInstance();
/*
* Read cordeau-instance p01
*/
new VrpXMLReader(vrpBuilder).read("input/cordeau01.xml");
new VrpXMLReader(vrpBuilder).read("input/cordeau01.xml");
/*
* Add initial route with 1_4_vehicle and services 44, 26
*/
VehicleRoute initialRoute = VehicleRoute.Builder.newInstance(getVehicle("1_4_vehicle",vrpBuilder)).addService(getService("44",vrpBuilder))
.addService(getService("26",vrpBuilder)).build();
vrpBuilder.addInitialVehicleRoute(initialRoute);
VehicleRoute initialRoute = VehicleRoute.Builder.newInstance(getVehicle("1_4_vehicle", vrpBuilder)).addService(getService("44", vrpBuilder))
.addService(getService("26", vrpBuilder)).build();
vrpBuilder.addInitialVehicleRoute(initialRoute);
/*
* build the problem
*/
VehicleRoutingProblem vrp = vrpBuilder.build();
VehicleRoutingProblem vrp = vrpBuilder.build();
/*
* since job (service) 26 and 44 are already planned in initial route and thus static AND sequence is fixed they
* should not be in jobMap anymore (only variable jobs are in jobMap)
*/
assert !vrp.getJobs().containsKey("26") : "strange. service 26 should not be part of the problem";
assert !vrp.getJobs().containsKey("44") : "strange. service 44 should not be part of the problem";
assert !vrp.getJobs().containsKey("26") : "strange. service 26 should not be part of the problem";
assert !vrp.getJobs().containsKey("44") : "strange. service 44 should not be part of the problem";
/*
* plot to see how the problem looks like
*/
new Plotter(vrp).setLabel(Label.ID).plot("output/cordeau01_problem_withInitialRoute.png", "c");
new Plotter(vrp).setLabel(Label.ID).plot("output/cordeau01_problem_withInitialRoute.png", "c");
/*
* solve the problem
@ -79,30 +79,30 @@ public class MultipleDepotWithInitialRoutesExample {
// VehicleRoutingAlgorithm vra = Jsprit.Builder.newInstance(vrp)
// .setProperty(Jsprit.Parameter.ITERATIONS,"10000").buildAlgorithm();
VehicleRoutingAlgorithm vra = VehicleRoutingAlgorithms.readAndCreateAlgorithm(vrp, "input/algorithmConfig_noVehicleSwitch.xml");
Collection<VehicleRoutingProblemSolution> solutions = vra.searchSolutions();
SolutionPrinter.print(Solutions.bestOf(solutions));
new Plotter(vrp, Solutions.bestOf(solutions)).setLabel(Label.ID).plot("output/cordeau01_solution_withInitialRoute.png", "p01");
}
VehicleRoutingAlgorithm vra = VehicleRoutingAlgorithms.readAndCreateAlgorithm(vrp, "input/algorithmConfig_noVehicleSwitch.xml");
Collection<VehicleRoutingProblemSolution> solutions = vra.searchSolutions();
private static Service getService(String serviceId, Builder vrpBuilder) {
for(Job j : vrpBuilder.getAddedJobs()){
if(j.getId().equals(serviceId)){
return (Service)j;
}
}
return null;
}
SolutionPrinter.print(Solutions.bestOf(solutions));
private static Vehicle getVehicle(String vehicleId, Builder vrpBuilder) {
for(Vehicle v : vrpBuilder.getAddedVehicles()){
if(v.getId().equals(vehicleId)) return v;
}
return null;
}
new Plotter(vrp, Solutions.bestOf(solutions)).setLabel(Label.ID).plot("output/cordeau01_solution_withInitialRoute.png", "p01");
}
private static Service getService(String serviceId, Builder vrpBuilder) {
for (Job j : vrpBuilder.getAddedJobs()) {
if (j.getId().equals(serviceId)) {
return (Service) j;
}
}
return null;
}
private static Vehicle getVehicle(String vehicleId, Builder vrpBuilder) {
for (Vehicle v : vrpBuilder.getAddedVehicles()) {
if (v.getId().equals(vehicleId)) return v;
}
return null;
}
}

View file

@ -47,12 +47,12 @@ import java.util.Collection;
/**
* Illustrates a VRP with multiple products.
*
* <p/>
* It has the hard requirements that no two different products can be transported in the same vehicle at the same time.
* This might be important if products require different temperatures. For example, if a vehicle transports
* apples then no bananas can be loaded (and the other way around). Once all apples have been unloaded, bananas can
* be loaded.
*
* <p/>
* See also the discussion here: https://groups.google.com/forum/#!topic/jsprit-mailing-list/2JQqY4loC0U
*/
public class MultipleProductsWithLoadConstraintExample {
@ -61,21 +61,22 @@ public class MultipleProductsWithLoadConstraintExample {
static final int APPLES_DIMENSION_INDEX = 1;
// static class BananasFirst implements HardActivityStateLevelConstraint { //v1.3.1
// static class BananasFirst implements HardActivityStateLevelConstraint { //v1.3.1
static class BananasFirst implements HardActivityConstraint {
@Override
public ConstraintsStatus fulfilled(JobInsertionContext jobInsertionContext, TourActivity prevActivity, TourActivity newActivity, TourActivity nextActivity, double departureTimeAtPrevActivity) {
if(isBananaPickup(newActivity) && isApplePickup(prevActivity)) return ConstraintsStatus.NOT_FULFILLED_BREAK;
if(isBananaPickup(nextActivity) && isApplePickup(newActivity)) return ConstraintsStatus.NOT_FULFILLED;
if (isBananaPickup(newActivity) && isApplePickup(prevActivity))
return ConstraintsStatus.NOT_FULFILLED_BREAK;
if (isBananaPickup(nextActivity) && isApplePickup(newActivity)) return ConstraintsStatus.NOT_FULFILLED;
return ConstraintsStatus.FULFILLED;
}
private boolean isApplePickup(TourActivity act){
private boolean isApplePickup(TourActivity act) {
return act.getSize().get(APPLES_DIMENSION_INDEX) > 0;
}
private boolean isBananaPickup(TourActivity act){
private boolean isBananaPickup(TourActivity act) {
return act.getSize().get(BANANAS_DIMENSION_INDEX) > 0;
}
}
@ -93,21 +94,21 @@ public class MultipleProductsWithLoadConstraintExample {
public ConstraintsStatus fulfilled(JobInsertionContext jobInsertionContext, TourActivity prevAct, TourActivity newAct, TourActivity nextAct, double departureTimeAtPrevAct) {
Capacity loadAtPrevAct = getLoadAtPreviousAct(prevAct);
if( isPickup(newAct) ){
if( ( isApplePickup(newAct) && hasBananasInVehicle(loadAtPrevAct) ) ||
( isBananaPickup(newAct) && hasApplesInVehicle(loadAtPrevAct) ) ){
if (isPickup(newAct)) {
if ((isApplePickup(newAct) && hasBananasInVehicle(loadAtPrevAct)) ||
(isBananaPickup(newAct) && hasApplesInVehicle(loadAtPrevAct))) {
return ConstraintsStatus.NOT_FULFILLED;
}
if( ( isApplePickup(newAct) && isBananaPickup(nextAct) ) ||
( isBananaPickup(newAct) && isApplePickup(nextAct) ) ){
if ((isApplePickup(newAct) && isBananaPickup(nextAct)) ||
(isBananaPickup(newAct) && isApplePickup(nextAct))) {
return ConstraintsStatus.NOT_FULFILLED;
}
return ConstraintsStatus.FULFILLED;
}
if( isDelivery(newAct) ){
if( ( isAppleDelivery(newAct) && hasBananasInVehicle(loadAtPrevAct) ) ||
( isBananaDelivery(newAct) && hasApplesInVehicle(loadAtPrevAct) ) ){
if (isDelivery(newAct)) {
if ((isAppleDelivery(newAct) && hasBananasInVehicle(loadAtPrevAct)) ||
(isBananaDelivery(newAct) && hasApplesInVehicle(loadAtPrevAct))) {
return ConstraintsStatus.NOT_FULFILLED_BREAK; // if so constraint is broken forever -> break here
}
return ConstraintsStatus.FULFILLED;
@ -119,23 +120,23 @@ public class MultipleProductsWithLoadConstraintExample {
return loadAtPrevAct.get(APPLES_DIMENSION_INDEX) > 0;
}
private boolean hasBananasInVehicle(Capacity loadAtPrevAct){
private boolean hasBananasInVehicle(Capacity loadAtPrevAct) {
return loadAtPrevAct.get(BANANAS_DIMENSION_INDEX) > 0;
}
private boolean isBananaPickup(TourActivity act){
private boolean isBananaPickup(TourActivity act) {
return act.getSize().get(BANANAS_DIMENSION_INDEX) > 0;
}
private boolean isBananaDelivery(TourActivity act){
private boolean isBananaDelivery(TourActivity act) {
return act.getSize().get(BANANAS_DIMENSION_INDEX) < 0;
}
private boolean isApplePickup(TourActivity act){
private boolean isApplePickup(TourActivity act) {
return act.getSize().get(APPLES_DIMENSION_INDEX) > 0;
}
private boolean isAppleDelivery(TourActivity act){
private boolean isAppleDelivery(TourActivity act) {
return act.getSize().get(APPLES_DIMENSION_INDEX) < 0;
}
@ -150,47 +151,46 @@ public class MultipleProductsWithLoadConstraintExample {
private Capacity getLoadAtPreviousAct(TourActivity prevAct) {
// Capacity prevLoad = stateManager.getActivityState(prevAct, StateFactory.LOAD, Capacity.class); //v1.3.1
Capacity prevLoad = stateManager.getActivityState(prevAct, InternalStates.LOAD, Capacity.class); //1.3.2-SNAPSHOT & upcoming release v1.4
if(prevLoad != null) return prevLoad;
if (prevLoad != null) return prevLoad;
else return Capacity.Builder.newInstance().build();
}
}
public static void main(String[] args) {
VehicleType type = VehicleTypeImpl.Builder.newInstance("type").addCapacityDimension(BANANAS_DIMENSION_INDEX,10)
.addCapacityDimension(APPLES_DIMENSION_INDEX, 20).build();
VehicleType type = VehicleTypeImpl.Builder.newInstance("type").addCapacityDimension(BANANAS_DIMENSION_INDEX, 10)
.addCapacityDimension(APPLES_DIMENSION_INDEX, 20).build();
VehicleImpl vehicle = VehicleImpl.Builder.newInstance("vehicle").setStartLocation(loc(Coordinate.newInstance(0, 0)))
.setType(type).build();
.setType(type).build();
Shipment bananas = Shipment.Builder.newInstance("bananas_1").addSizeDimension(BANANAS_DIMENSION_INDEX,1)
.setPickupLocation(loc(Coordinate.newInstance(1, 8))).setDeliveryLocation(loc(Coordinate.newInstance(10, 8))).build();
Shipment bananas = Shipment.Builder.newInstance("bananas_1").addSizeDimension(BANANAS_DIMENSION_INDEX, 1)
.setPickupLocation(loc(Coordinate.newInstance(1, 8))).setDeliveryLocation(loc(Coordinate.newInstance(10, 8))).build();
Shipment bananas_2 = Shipment.Builder.newInstance("bananas_2").addSizeDimension(BANANAS_DIMENSION_INDEX,1)
.setPickupLocation(loc(Coordinate.newInstance(2, 8))).setDeliveryLocation(loc(Coordinate.newInstance(11, 8))).build();
Shipment bananas_2 = Shipment.Builder.newInstance("bananas_2").addSizeDimension(BANANAS_DIMENSION_INDEX, 1)
.setPickupLocation(loc(Coordinate.newInstance(2, 8))).setDeliveryLocation(loc(Coordinate.newInstance(11, 8))).build();
Shipment bananas_3 = Shipment.Builder.newInstance("bananas_3").addSizeDimension(BANANAS_DIMENSION_INDEX,1)
.setPickupLocation(loc(Coordinate.newInstance(3, 8))).setDeliveryLocation(loc(Coordinate.newInstance(12, 8))).build();
Shipment bananas_3 = Shipment.Builder.newInstance("bananas_3").addSizeDimension(BANANAS_DIMENSION_INDEX, 1)
.setPickupLocation(loc(Coordinate.newInstance(3, 8))).setDeliveryLocation(loc(Coordinate.newInstance(12, 8))).build();
Shipment apples = Shipment.Builder.newInstance("apples_1").addSizeDimension(APPLES_DIMENSION_INDEX,1)
.setPickupLocation(loc(Coordinate.newInstance(1, 6))).setDeliveryLocation(loc(Coordinate.newInstance(10, 12))).build();
Shipment apples = Shipment.Builder.newInstance("apples_1").addSizeDimension(APPLES_DIMENSION_INDEX, 1)
.setPickupLocation(loc(Coordinate.newInstance(1, 6))).setDeliveryLocation(loc(Coordinate.newInstance(10, 12))).build();
Shipment apples_2 = Shipment.Builder.newInstance("apples_2").addSizeDimension(APPLES_DIMENSION_INDEX,1)
.setPickupLocation(loc(Coordinate.newInstance(1, 5))).setDeliveryLocation(loc(Coordinate.newInstance(10, 11))).build();
Shipment apples_2 = Shipment.Builder.newInstance("apples_2").addSizeDimension(APPLES_DIMENSION_INDEX, 1)
.setPickupLocation(loc(Coordinate.newInstance(1, 5))).setDeliveryLocation(loc(Coordinate.newInstance(10, 11))).build();
VehicleRoutingProblem vrp = VehicleRoutingProblem.Builder.newInstance().setFleetSize(VehicleRoutingProblem.FleetSize.INFINITE)
.addVehicle(vehicle)
.addJob(bananas).addJob(apples).addJob(bananas_2).addJob(bananas_3).addJob(apples_2).build();
.addVehicle(vehicle)
.addJob(bananas).addJob(apples).addJob(bananas_2).addJob(bananas_3).addJob(apples_2).build();
StateManager stateManager = new StateManager(vrp);
ConstraintManager constraintManager = new ConstraintManager(vrp,stateManager);
ConstraintManager constraintManager = new ConstraintManager(vrp, stateManager);
constraintManager.addConstraint(new NoBananasANDApplesConstraint(stateManager), ConstraintManager.Priority.CRITICAL);
// constraintManager.addConstraint(new BananasFirst(),ConstraintManager.Priority.CRITICAL);
VehicleRoutingAlgorithm vra = Jsprit.Builder.newInstance(vrp).setStateAndConstraintManager(stateManager,constraintManager)
.buildAlgorithm();
VehicleRoutingAlgorithm vra = Jsprit.Builder.newInstance(vrp).setStateAndConstraintManager(stateManager, constraintManager)
.buildAlgorithm();
Collection<VehicleRoutingProblemSolution> solutions = vra.searchSolutions();

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.examples;
@ -34,74 +34,74 @@ import java.util.Collection;
public class PickupAndDeliveryExample {
public static void main(String[] args) {
public static void main(String[] args) {
/*
* some preparation - create output folder
*/
Examples.createOutputFolder();
Examples.createOutputFolder();
/*
* Build the problem.
*
*
* But define a problem-builder first.
*/
VehicleRoutingProblem.Builder vrpBuilder = VehicleRoutingProblem.Builder.newInstance();
VehicleRoutingProblem.Builder vrpBuilder = VehicleRoutingProblem.Builder.newInstance();
/*
* A solomonReader reads solomon-instance files, and stores the required information in the builder.
*/
new VrpXMLReader(vrpBuilder).read("input/pickups_and_deliveries_solomon_r101_withoutTWs.xml");
new VrpXMLReader(vrpBuilder).read("input/pickups_and_deliveries_solomon_r101_withoutTWs.xml");
/*
* Finally, the problem can be built. By default, transportCosts are crowFlyDistances (as usually used for vrp-instances).
*/
final VehicleRoutingProblem vrp = vrpBuilder.build();
new Plotter(vrp).plot("output/pd_solomon_r101.png", "pd_r101");
final VehicleRoutingProblem vrp = vrpBuilder.build();
new Plotter(vrp).plot("output/pd_solomon_r101.png", "pd_r101");
/*
* Define the required vehicle-routing algorithms to solve the above problem.
*
*
* The algorithm can be defined and configured in an xml-file.
*/
// VehicleRoutingAlgorithm vra = new SchrimpfFactory().createAlgorithm(vrp);
VehicleRoutingAlgorithm vra = VehicleRoutingAlgorithms.readAndCreateAlgorithm(vrp, "input/algorithmConfig_solomon.xml");
vra.getAlgorithmListeners().addListener(new AlgorithmSearchProgressChartListener("output/sol_progress.png"));
VehicleRoutingAlgorithm vra = VehicleRoutingAlgorithms.readAndCreateAlgorithm(vrp, "input/algorithmConfig_solomon.xml");
vra.getAlgorithmListeners().addListener(new AlgorithmSearchProgressChartListener("output/sol_progress.png"));
/*
* Solve the problem.
*
*
*
*/
Collection<VehicleRoutingProblemSolution> solutions = vra.searchSolutions();
Collection<VehicleRoutingProblemSolution> solutions = vra.searchSolutions();
/*
* Retrieve best solution.
*/
VehicleRoutingProblemSolution solution = new SelectBest().selectSolution(solutions);
VehicleRoutingProblemSolution solution = new SelectBest().selectSolution(solutions);
/*
* print solution
*/
SolutionPrinter.print(solution);
SolutionPrinter.print(solution);
/*
* Plot solution.
* Plot solution.
*/
// SolutionPlotter.plotSolutionAsPNG(vrp, solution, "output/pd_solomon_r101_solution.png","pd_r101");
Plotter plotter = new Plotter(vrp, solution);
plotter.setLabel(Label.SIZE);
plotter.plot("output/pd_solomon_r101_solution.png","pd_r101");
Plotter plotter = new Plotter(vrp, solution);
plotter.setLabel(Label.SIZE);
plotter.plot("output/pd_solomon_r101_solution.png", "pd_r101");
//some stats
SolutionAnalyser analyser = new SolutionAnalyser(vrp,solution,new SolutionAnalyser.DistanceCalculator() {
SolutionAnalyser analyser = new SolutionAnalyser(vrp, solution, new SolutionAnalyser.DistanceCalculator() {
@Override
public double getDistance(Location from, Location to) {
return vrp.getTransportCosts().getTransportCost(from, to,0.,null,null);
return vrp.getTransportCosts().getTransportCost(from, to, 0., null, null);
}
});

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.examples;
@ -33,71 +33,71 @@ import java.util.Collection;
public class PickupAndDeliveryExample2 {
public static void main(String[] args) {
public static void main(String[] args) {
/*
* some preparation - create output folder
* some preparation - create output folder
*/
Examples.createOutputFolder();
Examples.createOutputFolder();
/*
* Build the problem.
*
*
* But define a problem-builder first.
*/
VehicleRoutingProblem.Builder vrpBuilder = VehicleRoutingProblem.Builder.newInstance();
VehicleRoutingProblem.Builder vrpBuilder = VehicleRoutingProblem.Builder.newInstance();
/*
* A solomonReader reads solomon-instance files, and stores the required information in the builder.
*/
new VrpXMLReader(vrpBuilder).read("input/pd_christophides_vrpnc1_vcap50.xml");
new VrpXMLReader(vrpBuilder).read("input/pd_christophides_vrpnc1_vcap50.xml");
/*
* Finally, the problem can be built. By default, transportCosts are crowFlyDistances (as usually used for vrp-instances).
*/
VehicleRoutingProblem vrp = vrpBuilder.build();
new Plotter(vrp).plot("output/pd_christophides_vrpnc1.png", "pd_vrpnc1");
VehicleRoutingProblem vrp = vrpBuilder.build();
new Plotter(vrp).plot("output/pd_christophides_vrpnc1.png", "pd_vrpnc1");
/*
* Define the required vehicle-routing algorithms to solve the above problem.
*
*
* The algorithm can be defined and configured in an xml-file.
*/
// VehicleRoutingAlgorithm vra = new SchrimpfFactory().createAlgorithm(vrp);
VehicleRoutingAlgorithm vra = VehicleRoutingAlgorithms.readAndCreateAlgorithm(vrp, "input/algorithmConfig_solomon.xml");
vra.getAlgorithmListeners().addListener(new AlgorithmSearchProgressChartListener("output/sol_progress.png"));
VehicleRoutingAlgorithm vra = VehicleRoutingAlgorithms.readAndCreateAlgorithm(vrp, "input/algorithmConfig_solomon.xml");
vra.getAlgorithmListeners().addListener(new AlgorithmSearchProgressChartListener("output/sol_progress.png"));
/*
* Solve the problem.
*
*
*
*/
Collection<VehicleRoutingProblemSolution> solutions = vra.searchSolutions();
Collection<VehicleRoutingProblemSolution> solutions = vra.searchSolutions();
/*
* Retrieve best solution.
*/
VehicleRoutingProblemSolution solution = new SelectBest().selectSolution(solutions);
VehicleRoutingProblemSolution solution = new SelectBest().selectSolution(solutions);
/*
* print solution
*/
SolutionPrinter.print(solution);
SolutionPrinter.print(solution);
/*
* Plot solution.
* Plot solution.
*/
// SolutionPlotter.plotSolutionAsPNG(vrp, solution, "output/pd_solomon_r101_solution.png","pd_r101");
Plotter plotter = new Plotter(vrp, solution);
plotter.setLabel(Label.SIZE);
plotter.plot("output/pd_christophides_vrpnc1_solution.png","pd_vrpnc1");
new GraphStreamViewer(vrp, solution).setRenderDelay(200).display();
}
Plotter plotter = new Plotter(vrp, solution);
plotter.setLabel(Label.SIZE);
plotter.plot("output/pd_christophides_vrpnc1_solution.png", "pd_vrpnc1");
new GraphStreamViewer(vrp, solution).setRenderDelay(200).display();
}
}

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.examples;
@ -32,69 +32,68 @@ import java.util.Collection;
public class PickupAndDeliveryOpenExample {
public static void main(String[] args) {
public static void main(String[] args) {
/*
* some preparation - create output folder
*/
Examples.createOutputFolder();
Examples.createOutputFolder();
/*
* Build the problem.
*
*
* But define a problem-builder first.
*/
VehicleRoutingProblem.Builder vrpBuilder = VehicleRoutingProblem.Builder.newInstance();
VehicleRoutingProblem.Builder vrpBuilder = VehicleRoutingProblem.Builder.newInstance();
/*
* A solomonReader reads solomon-instance files, and stores the required information in the builder.
*/
new VrpXMLReader(vrpBuilder).read("input/pickups_and_deliveries_solomon_r101_withoutTWs_open.xml");
new VrpXMLReader(vrpBuilder).read("input/pickups_and_deliveries_solomon_r101_withoutTWs_open.xml");
/*
* Finally, the problem can be built. By default, transportCosts are crowFlyDistances (as usually used for vrp-instances).
*/
VehicleRoutingProblem vrp = vrpBuilder.build();
VehicleRoutingProblem vrp = vrpBuilder.build();
// SolutionPlotter.plotVrpAsPNG(vrp, "output/pd_solomon_r101_o.png", "pd_r101");
/*
* Define the required vehicle-routing algorithms to solve the above problem.
*
*
* The algorithm can be defined and configured in an xml-file.
*/
// VehicleRoutingAlgorithm vra = new SchrimpfFactory().createAlgorithm(vrp);
VehicleRoutingAlgorithm vra = VehicleRoutingAlgorithms.readAndCreateAlgorithm(vrp, "input/algorithmConfig_open.xml");
vra.getAlgorithmListeners().addListener(new AlgorithmSearchProgressChartListener("output/sol_progress.png"));
VehicleRoutingAlgorithm vra = VehicleRoutingAlgorithms.readAndCreateAlgorithm(vrp, "input/algorithmConfig_open.xml");
vra.getAlgorithmListeners().addListener(new AlgorithmSearchProgressChartListener("output/sol_progress.png"));
/*
* Solve the problem.
*
*
*
*/
Collection<VehicleRoutingProblemSolution> solutions = vra.searchSolutions();
Collection<VehicleRoutingProblemSolution> solutions = vra.searchSolutions();
/*
* Retrieve best solution.
*/
VehicleRoutingProblemSolution solution = new SelectBest().selectSolution(solutions);
VehicleRoutingProblemSolution solution = new SelectBest().selectSolution(solutions);
/*
* print solution
*/
SolutionPrinter.print(solution);
SolutionPrinter.print(solution);
/*
* Plot solution.
* Plot solution.
*/
// SolutionPlotter.plotSolutionAsPNG(vrp, solution, "output/pd_solomon_r101_solution.png","pd_r101");
Plotter plotter = new Plotter(vrp, solution);
plotter.setLabel(Label.SIZE);
plotter.plot("output/pd_solomon_r101_solution_open.png","pd_r101");
}
Plotter plotter = new Plotter(vrp, solution);
plotter.setLabel(Label.SIZE);
plotter.plot("output/pd_solomon_r101_solution_open.png", "pd_r101");
}
}

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.examples;
@ -40,104 +40,102 @@ import java.io.IOException;
import java.util.Collection;
/**
* This example is base on
* http://web.mit.edu/urban_or_book/www/book/chapter6/6.4.12.html
*
* @author stefan schroeder
*
* @author stefan schroeder
*/
public class RefuseCollectionExample {
public static void main(String[] args) throws IOException {
/*
public static void main(String[] args) throws IOException {
/*
* some preparation - create output folder
*/
Examples.createOutputFolder();
Examples.createOutputFolder();
/*
* create vehicle-type and vehicle
*/
VehicleTypeImpl.Builder typeBuilder = VehicleTypeImpl.Builder.newInstance("vehicle-type").addCapacityDimension(0, 23);
typeBuilder.setCostPerDistance(1.0);
VehicleTypeImpl bigType = typeBuilder.build();
VehicleImpl.Builder vehicleBuilder = VehicleImpl.Builder.newInstance("vehicle");
vehicleBuilder.setStartLocation(Location.newInstance("1"));
vehicleBuilder.setType(bigType);
VehicleImpl bigVehicle = vehicleBuilder.build();
VehicleTypeImpl.Builder typeBuilder = VehicleTypeImpl.Builder.newInstance("vehicle-type").addCapacityDimension(0, 23);
typeBuilder.setCostPerDistance(1.0);
VehicleTypeImpl bigType = typeBuilder.build();
VehicleImpl.Builder vehicleBuilder = VehicleImpl.Builder.newInstance("vehicle");
vehicleBuilder.setStartLocation(Location.newInstance("1"));
vehicleBuilder.setType(bigType);
VehicleImpl bigVehicle = vehicleBuilder.build();
/*
* start building the problem
*/
VehicleRoutingProblem.Builder vrpBuilder = VehicleRoutingProblem.Builder.newInstance();
vrpBuilder.setFleetSize(FleetSize.INFINITE);
vrpBuilder.addVehicle(bigVehicle);
VehicleRoutingProblem.Builder vrpBuilder = VehicleRoutingProblem.Builder.newInstance();
vrpBuilder.setFleetSize(FleetSize.INFINITE);
vrpBuilder.addVehicle(bigVehicle);
/*
* read demand quantities
*/
readDemandQuantities(vrpBuilder);
readDemandQuantities(vrpBuilder);
/*
* create cost-matrix
*/
VehicleRoutingTransportCostsMatrix.Builder matrixBuilder = VehicleRoutingTransportCostsMatrix.Builder.newInstance(true);
readDistances(matrixBuilder);
VehicleRoutingTransportCostsMatrix.Builder matrixBuilder = VehicleRoutingTransportCostsMatrix.Builder.newInstance(true);
readDistances(matrixBuilder);
vrpBuilder.setRoutingCost(matrixBuilder.build());
VehicleRoutingProblem vrp = vrpBuilder.build();
VehicleRoutingAlgorithm vra = new GreedySchrimpfFactory().createAlgorithm(vrp);
vra.setPrematureAlgorithmTermination(new IterationWithoutImprovementTermination(100));
Collection<VehicleRoutingProblemSolution> solutions = vra.searchSolutions();
SolutionPrinter.print(Solutions.bestOf(solutions));
new VrpXMLWriter(vrp, solutions).write("output/refuseCollectionExampleSolution.xml");
}
vrpBuilder.setRoutingCost(matrixBuilder.build());
VehicleRoutingProblem vrp = vrpBuilder.build();
VehicleRoutingAlgorithm vra = new GreedySchrimpfFactory().createAlgorithm(vrp);
vra.setPrematureAlgorithmTermination(new IterationWithoutImprovementTermination(100));
Collection<VehicleRoutingProblemSolution> solutions = vra.searchSolutions();
SolutionPrinter.print(Solutions.bestOf(solutions));
new VrpXMLWriter(vrp, solutions).write("output/refuseCollectionExampleSolution.xml");
}
private static void readDemandQuantities(VehicleRoutingProblem.Builder vrpBuilder) throws IOException {
BufferedReader reader = new BufferedReader(new FileReader(new File("input/RefuseCollectionExample_Quantities")));
String line;
boolean firstLine = true;
while((line = reader.readLine()) != null){
if(firstLine) {
firstLine = false;
continue;
}
String[] lineTokens = line.split(",");
private static void readDemandQuantities(VehicleRoutingProblem.Builder vrpBuilder) throws IOException {
BufferedReader reader = new BufferedReader(new FileReader(new File("input/RefuseCollectionExample_Quantities")));
String line;
boolean firstLine = true;
while ((line = reader.readLine()) != null) {
if (firstLine) {
firstLine = false;
continue;
}
String[] lineTokens = line.split(",");
/*
* build service
*/
Service service = Service.Builder.newInstance(lineTokens[0]).addSizeDimension(0, Integer.parseInt(lineTokens[1])).setLocation(Location.newInstance(lineTokens[0])).build();
Service service = Service.Builder.newInstance(lineTokens[0]).addSizeDimension(0, Integer.parseInt(lineTokens[1])).setLocation(Location.newInstance(lineTokens[0])).build();
/*
* and add it to problem
*/
vrpBuilder.addJob(service);
}
reader.close();
}
vrpBuilder.addJob(service);
}
reader.close();
}
private static void readDistances(Builder matrixBuilder) throws IOException {
BufferedReader reader = new BufferedReader(new FileReader(new File("input/RefuseCollectionExample_Distances")));
String line;
boolean firstLine = true;
while((line = reader.readLine()) != null){
if(firstLine) {
firstLine = false;
continue;
}
String[] lineTokens = line.split(",");
matrixBuilder.addTransportDistance(lineTokens[0],lineTokens[1], Integer.parseInt(lineTokens[2]));
}
reader.close();
}
private static void readDistances(Builder matrixBuilder) throws IOException {
BufferedReader reader = new BufferedReader(new FileReader(new File("input/RefuseCollectionExample_Distances")));
String line;
boolean firstLine = true;
while ((line = reader.readLine()) != null) {
if (firstLine) {
firstLine = false;
continue;
}
String[] lineTokens = line.split(",");
matrixBuilder.addTransportDistance(lineTokens[0], lineTokens[1], Integer.parseInt(lineTokens[2]));
}
reader.close();
}
}

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.examples;
@ -42,103 +42,102 @@ import java.util.Collection;
/**
* This example is base on
* http://web.mit.edu/urban_or_book/www/book/chapter6/6.4.12.html
*
* @author stefan schroeder
*
* @author stefan schroeder
*/
public class RefuseCollectionWithFastMatrixExample {
public static void main(String[] args) throws IOException {
/*
public static void main(String[] args) throws IOException {
/*
* some preparation - create output folder
*/
Examples.createOutputFolder();
Examples.createOutputFolder();
/*
* create vehicle-type and vehicle
*/
VehicleTypeImpl.Builder typeBuilder = VehicleTypeImpl.Builder.newInstance("vehicle-type").addCapacityDimension(0, 23);
typeBuilder.setCostPerDistance(1.0);
VehicleTypeImpl bigType = typeBuilder.build();
VehicleTypeImpl.Builder typeBuilder = VehicleTypeImpl.Builder.newInstance("vehicle-type").addCapacityDimension(0, 23);
typeBuilder.setCostPerDistance(1.0);
VehicleTypeImpl bigType = typeBuilder.build();
VehicleImpl.Builder vehicleBuilder = VehicleImpl.Builder.newInstance("vehicle");
vehicleBuilder.setStartLocation(Location.Builder.newInstance().setIndex(1).build());
vehicleBuilder.setType(bigType);
VehicleImpl bigVehicle = vehicleBuilder.build();
VehicleImpl.Builder vehicleBuilder = VehicleImpl.Builder.newInstance("vehicle");
vehicleBuilder.setStartLocation(Location.Builder.newInstance().setIndex(1).build());
vehicleBuilder.setType(bigType);
VehicleImpl bigVehicle = vehicleBuilder.build();
/*
* start building the problem
*/
VehicleRoutingProblem.Builder vrpBuilder = VehicleRoutingProblem.Builder.newInstance();
vrpBuilder.setFleetSize(FleetSize.INFINITE);
vrpBuilder.addVehicle(bigVehicle);
VehicleRoutingProblem.Builder vrpBuilder = VehicleRoutingProblem.Builder.newInstance();
vrpBuilder.setFleetSize(FleetSize.INFINITE);
vrpBuilder.addVehicle(bigVehicle);
/*
* read demand quantities
*/
readDemandQuantities(vrpBuilder);
readDemandQuantities(vrpBuilder);
/*
* create cost-matrix
*/
FastVehicleRoutingTransportCostsMatrix.Builder matrixBuilder = FastVehicleRoutingTransportCostsMatrix.Builder.newInstance(11,true);
readDistances(matrixBuilder);
FastVehicleRoutingTransportCostsMatrix.Builder matrixBuilder = FastVehicleRoutingTransportCostsMatrix.Builder.newInstance(11, true);
readDistances(matrixBuilder);
vrpBuilder.setRoutingCost(matrixBuilder.build());
VehicleRoutingProblem vrp = vrpBuilder.build();
VehicleRoutingAlgorithm vra = new GreedySchrimpfFactory().createAlgorithm(vrp);
vra.setPrematureAlgorithmTermination(new IterationWithoutImprovementTermination(100));
Collection<VehicleRoutingProblemSolution> solutions = vra.searchSolutions();
SolutionPrinter.print(Solutions.bestOf(solutions));
new VrpXMLWriter(vrp, solutions).write("output/refuseCollectionExampleSolution.xml");
}
vrpBuilder.setRoutingCost(matrixBuilder.build());
VehicleRoutingProblem vrp = vrpBuilder.build();
VehicleRoutingAlgorithm vra = new GreedySchrimpfFactory().createAlgorithm(vrp);
vra.setPrematureAlgorithmTermination(new IterationWithoutImprovementTermination(100));
Collection<VehicleRoutingProblemSolution> solutions = vra.searchSolutions();
SolutionPrinter.print(Solutions.bestOf(solutions));
new VrpXMLWriter(vrp, solutions).write("output/refuseCollectionExampleSolution.xml");
}
private static void readDemandQuantities(VehicleRoutingProblem.Builder vrpBuilder) throws IOException {
BufferedReader reader = new BufferedReader(new FileReader(new File("input/RefuseCollectionExample_Quantities")));
String line;
boolean firstLine = true;
while((line = reader.readLine()) != null){
if(firstLine) {
firstLine = false;
continue;
}
String[] lineTokens = line.split(",");
private static void readDemandQuantities(VehicleRoutingProblem.Builder vrpBuilder) throws IOException {
BufferedReader reader = new BufferedReader(new FileReader(new File("input/RefuseCollectionExample_Quantities")));
String line;
boolean firstLine = true;
while ((line = reader.readLine()) != null) {
if (firstLine) {
firstLine = false;
continue;
}
String[] lineTokens = line.split(",");
/*
* build service
*/
Service service = Service.Builder.newInstance(lineTokens[0])
.addSizeDimension(0, Integer.parseInt(lineTokens[1]))
.setLocation(Location.Builder.newInstance().setIndex(Integer.parseInt(lineTokens[0])).build())
.build();
Service service = Service.Builder.newInstance(lineTokens[0])
.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);
}
reader.close();
}
vrpBuilder.addJob(service);
}
reader.close();
}
private static void readDistances(FastVehicleRoutingTransportCostsMatrix.Builder matrixBuilder) throws IOException {
BufferedReader reader = new BufferedReader(new FileReader(new File("input/RefuseCollectionExample_Distances")));
String line;
boolean firstLine = true;
while((line = reader.readLine()) != null){
if(firstLine) {
firstLine = false;
continue;
}
String[] lineTokens = line.split(",");
matrixBuilder.addTransportDistance(Integer.parseInt(lineTokens[0]),Integer.parseInt(lineTokens[1]), Integer.parseInt(lineTokens[2]));
}
reader.close();
}
private static void readDistances(FastVehicleRoutingTransportCostsMatrix.Builder matrixBuilder) throws IOException {
BufferedReader reader = new BufferedReader(new FileReader(new File("input/RefuseCollectionExample_Distances")));
String line;
boolean firstLine = true;
while ((line = reader.readLine()) != null) {
if (firstLine) {
firstLine = false;
continue;
}
String[] lineTokens = line.split(",");
matrixBuilder.addTransportDistance(Integer.parseInt(lineTokens[0]), Integer.parseInt(lineTokens[1]), Integer.parseInt(lineTokens[2]));
}
reader.close();
}
}

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.examples;
@ -39,34 +39,34 @@ import java.util.Collection;
public class ServicePickupsWithMultipleDepotsExample {
public static void main(String[] args) {
/*
public static void main(String[] args) {
/*
* some preparation - create output folder
*/
Examples.createOutputFolder();
Examples.createOutputFolder();
/*
* get a vehicle type-builder and build a type with the typeId "vehicleType" and a capacity of 2
*/
VehicleTypeImpl.Builder vehicleTypeBuilder = VehicleTypeImpl.Builder.newInstance("vehicleType").addCapacityDimension(0, 8);
vehicleTypeBuilder.setCostPerDistance(1.0);
VehicleType vehicleType = vehicleTypeBuilder.build();
VehicleTypeImpl.Builder vehicleTypeBuilder = VehicleTypeImpl.Builder.newInstance("vehicleType").addCapacityDimension(0, 8);
vehicleTypeBuilder.setCostPerDistance(1.0);
VehicleType vehicleType = vehicleTypeBuilder.build();
/*
* define two depots, i.e. two vehicle locations ([10,10],[50,50]) and equip them with an infinite number of vehicles of type 'vehicleType'
* define two depots, i.e. two vehicle locations ([10,10],[50,50]) and equip them with an infinite number of vehicles of type 'vehicleType'
*/
Builder vehicleBuilder1 = VehicleImpl.Builder.newInstance("vehicles@[10,10]");
vehicleBuilder1.setStartLocation(Location.newInstance(10, 10));
vehicleBuilder1.setType(vehicleType);
VehicleImpl vehicle1 = vehicleBuilder1.build();
Builder vehicleBuilder2 = VehicleImpl.Builder.newInstance("vehicles@[50,50]");
vehicleBuilder2.setStartLocation(Location.newInstance(50, 50));
vehicleBuilder2.setType(vehicleType);
VehicleImpl vehicle2 = vehicleBuilder2.build();
Builder vehicleBuilder1 = VehicleImpl.Builder.newInstance("vehicles@[10,10]");
vehicleBuilder1.setStartLocation(Location.newInstance(10, 10));
vehicleBuilder1.setType(vehicleType);
VehicleImpl vehicle1 = vehicleBuilder1.build();
Builder vehicleBuilder2 = VehicleImpl.Builder.newInstance("vehicles@[50,50]");
vehicleBuilder2.setStartLocation(Location.newInstance(50, 50));
vehicleBuilder2.setType(vehicleType);
VehicleImpl vehicle2 = vehicleBuilder2.build();
/*
* build shipments at the required locations, each with a capacity-demand of 1.
* 4 shipments
@ -75,70 +75,70 @@ public class ServicePickupsWithMultipleDepotsExample {
* 3: (15,7)->(14,9)
* 4: (15,13)->(14,11)
*/
Service shipment1 = Service.Builder.newInstance("1").addSizeDimension(0, 1).setLocation(Location.newInstance(5, 7)).build();
Service shipment2 = Service.Builder.newInstance("2").addSizeDimension(0, 1).setLocation(Location.newInstance(5, 13)).build();
Service shipment3 = Service.Builder.newInstance("3").addSizeDimension(0, 1).setLocation(Location.newInstance(15, 7)).build();
Service shipment4 = Service.Builder.newInstance("4").addSizeDimension(0, 1).setLocation(Location.newInstance(15, 13)).build();
Service shipment5 = Service.Builder.newInstance("5").addSizeDimension(0, 1).setLocation(Location.newInstance(55, 57)).build();
Service shipment6 = Service.Builder.newInstance("6").addSizeDimension(0, 1).setLocation(Location.newInstance(55, 63)).build();
Service shipment7 = Service.Builder.newInstance("7").addSizeDimension(0, 1).setLocation(Location.newInstance(65, 57)).build();
Service shipment8 = Service.Builder.newInstance("8").addSizeDimension(0, 1).setLocation(Location.newInstance(65, 63)).build();
VehicleRoutingProblem.Builder vrpBuilder = VehicleRoutingProblem.Builder.newInstance();
vrpBuilder.addVehicle(vehicle1).addVehicle(vehicle2);
vrpBuilder.addJob(shipment1).addJob(shipment2).addJob(shipment3).addJob(shipment4);
vrpBuilder.addJob(shipment5).addJob(shipment6).addJob(shipment7).addJob(shipment8);
Service shipment1 = Service.Builder.newInstance("1").addSizeDimension(0, 1).setLocation(Location.newInstance(5, 7)).build();
Service shipment2 = Service.Builder.newInstance("2").addSizeDimension(0, 1).setLocation(Location.newInstance(5, 13)).build();
Service shipment3 = Service.Builder.newInstance("3").addSizeDimension(0, 1).setLocation(Location.newInstance(15, 7)).build();
Service shipment4 = Service.Builder.newInstance("4").addSizeDimension(0, 1).setLocation(Location.newInstance(15, 13)).build();
Service shipment5 = Service.Builder.newInstance("5").addSizeDimension(0, 1).setLocation(Location.newInstance(55, 57)).build();
Service shipment6 = Service.Builder.newInstance("6").addSizeDimension(0, 1).setLocation(Location.newInstance(55, 63)).build();
Service shipment7 = Service.Builder.newInstance("7").addSizeDimension(0, 1).setLocation(Location.newInstance(65, 57)).build();
Service shipment8 = Service.Builder.newInstance("8").addSizeDimension(0, 1).setLocation(Location.newInstance(65, 63)).build();
VehicleRoutingProblem.Builder vrpBuilder = VehicleRoutingProblem.Builder.newInstance();
vrpBuilder.addVehicle(vehicle1).addVehicle(vehicle2);
vrpBuilder.addJob(shipment1).addJob(shipment2).addJob(shipment3).addJob(shipment4);
vrpBuilder.addJob(shipment5).addJob(shipment6).addJob(shipment7).addJob(shipment8);
// vrpBuilder.setFleetSize(FleetSize.FINITE);
VehicleRoutingProblem problem = vrpBuilder.build();
VehicleRoutingProblem problem = vrpBuilder.build();
/*
* get the algorithm out-of-the-box.
* get the algorithm out-of-the-box.
*/
VehicleRoutingAlgorithm algorithm = VehicleRoutingAlgorithms.readAndCreateAlgorithm(problem, "input/algorithmConfig.xml");
algorithm.setMaxIterations(10);
VehicleRoutingAlgorithm algorithm = VehicleRoutingAlgorithms.readAndCreateAlgorithm(problem, "input/algorithmConfig.xml");
algorithm.setMaxIterations(10);
/*
* and search a solution
*/
Collection<VehicleRoutingProblemSolution> solutions = algorithm.searchSolutions();
Collection<VehicleRoutingProblemSolution> solutions = algorithm.searchSolutions();
/*
* get the best
* get the best
*/
VehicleRoutingProblemSolution bestSolution = Solutions.bestOf(solutions);
VehicleRoutingProblemSolution bestSolution = Solutions.bestOf(solutions);
/*
* write out problem and solution to xml-file
*/
new VrpXMLWriter(problem, solutions).write("output/shipment-problem-with-solution.xml");
new VrpXMLWriter(problem, solutions).write("output/shipment-problem-with-solution.xml");
/*
* print nRoutes and totalCosts of bestSolution
*/
SolutionPrinter.print(bestSolution);
SolutionPrinter.print(bestSolution);
/*
* plot problem without solution
*/
Plotter problemPlotter = new Plotter(problem);
problemPlotter.plotShipments(true);
problemPlotter.plot("output/enRoutePickupAndDeliveryWithMultipleLocationsExample_problem.png", "en-route pickup and delivery");
Plotter problemPlotter = new Plotter(problem);
problemPlotter.plotShipments(true);
problemPlotter.plot("output/enRoutePickupAndDeliveryWithMultipleLocationsExample_problem.png", "en-route pickup and delivery");
/*
* plot problem with solution
*/
Plotter solutionPlotter = new Plotter(problem,Arrays.asList(Solutions.bestOf(solutions).getRoutes().iterator().next()));
solutionPlotter.plotShipments(true);
solutionPlotter.plot("output/enRoutePickupAndDeliveryWithMultipleLocationsExample_solution.png", "en-route pickup and delivery");
new GraphStreamViewer(problem,Solutions.bestOf(solutions)).labelWith(Label.ACTIVITY).setRenderDelay(100).setRenderShipments(true).display();
}
Plotter solutionPlotter = new Plotter(problem, Arrays.asList(Solutions.bestOf(solutions).getRoutes().iterator().next()));
solutionPlotter.plotShipments(true);
solutionPlotter.plot("output/enRoutePickupAndDeliveryWithMultipleLocationsExample_solution.png", "en-route pickup and delivery");
new GraphStreamViewer(problem, Solutions.bestOf(solutions)).labelWith(Label.ACTIVITY).setRenderDelay(100).setRenderShipments(true).display();
}
}

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.examples;
@ -38,70 +38,70 @@ import java.util.Collection;
public class SimpleDepotBoundedPickupAndDeliveryExample {
public static void main(String[] args) {
/*
public static void main(String[] args) {
/*
* some preparation - create output folder
*/
Examples.createOutputFolder();
Examples.createOutputFolder();
/*
* get a vehicle type-builder and build a type with the typeId "vehicleType" and a capacity of 2
*/
VehicleTypeImpl.Builder vehicleTypeBuilder = VehicleTypeImpl.Builder.newInstance("vehicleType").addCapacityDimension(0, 2);
VehicleType vehicleType = vehicleTypeBuilder.build();
VehicleTypeImpl.Builder vehicleTypeBuilder = VehicleTypeImpl.Builder.newInstance("vehicleType").addCapacityDimension(0, 2);
VehicleType vehicleType = vehicleTypeBuilder.build();
/*
* get a vehicle-builder and build a vehicle located at (10,10) with type "vehicleType"
*/
Builder vehicleBuilder = VehicleImpl.Builder.newInstance("vehicle");
vehicleBuilder.setStartLocation(Location.newInstance(10, 10));
vehicleBuilder.setType(vehicleType);
VehicleImpl vehicle = vehicleBuilder.build();
Builder vehicleBuilder = VehicleImpl.Builder.newInstance("vehicle");
vehicleBuilder.setStartLocation(Location.newInstance(10, 10));
vehicleBuilder.setType(vehicleType);
VehicleImpl vehicle = vehicleBuilder.build();
/*
* build pickups and deliveries at the required locations, each with a capacity-demand of 1.
*/
Pickup pickup1 = (Pickup) Pickup.Builder.newInstance("1").addSizeDimension(0, 1).setLocation(Location.newInstance(5, 7)).build();
Delivery delivery1 = (Delivery) Delivery.Builder.newInstance("2").addSizeDimension(0, 1).setLocation(Location.newInstance(5, 13)).build();
Pickup pickup2 = (Pickup) Pickup.Builder.newInstance("3").addSizeDimension(0, 1).setLocation(Location.newInstance(15, 7)).build();
Delivery delivery2 = (Delivery) Delivery.Builder.newInstance("4").addSizeDimension(0, 1).setLocation(Location.newInstance(15, 13)).build();
VehicleRoutingProblem.Builder vrpBuilder = VehicleRoutingProblem.Builder.newInstance();
vrpBuilder.addVehicle(vehicle);
vrpBuilder.addJob(pickup1).addJob(pickup2).addJob(delivery1).addJob(delivery2);
VehicleRoutingProblem problem = vrpBuilder.build();
Pickup pickup1 = (Pickup) Pickup.Builder.newInstance("1").addSizeDimension(0, 1).setLocation(Location.newInstance(5, 7)).build();
Delivery delivery1 = (Delivery) Delivery.Builder.newInstance("2").addSizeDimension(0, 1).setLocation(Location.newInstance(5, 13)).build();
Pickup pickup2 = (Pickup) Pickup.Builder.newInstance("3").addSizeDimension(0, 1).setLocation(Location.newInstance(15, 7)).build();
Delivery delivery2 = (Delivery) Delivery.Builder.newInstance("4").addSizeDimension(0, 1).setLocation(Location.newInstance(15, 13)).build();
VehicleRoutingProblem.Builder vrpBuilder = VehicleRoutingProblem.Builder.newInstance();
vrpBuilder.addVehicle(vehicle);
vrpBuilder.addJob(pickup1).addJob(pickup2).addJob(delivery1).addJob(delivery2);
VehicleRoutingProblem problem = vrpBuilder.build();
/*
* get the algorithm out-of-the-box.
* get the algorithm out-of-the-box.
*/
VehicleRoutingAlgorithm algorithm = new SchrimpfFactory().createAlgorithm(problem);
VehicleRoutingAlgorithm algorithm = new SchrimpfFactory().createAlgorithm(problem);
/*
* and search a solution
*/
Collection<VehicleRoutingProblemSolution> solutions = algorithm.searchSolutions();
Collection<VehicleRoutingProblemSolution> solutions = algorithm.searchSolutions();
/*
* get the best
* get the best
*/
VehicleRoutingProblemSolution bestSolution = Solutions.bestOf(solutions);
new VrpXMLWriter(problem, solutions).write("output/problem-with-solution.xml");
SolutionPrinter.print(bestSolution);
VehicleRoutingProblemSolution bestSolution = Solutions.bestOf(solutions);
new VrpXMLWriter(problem, solutions).write("output/problem-with-solution.xml");
SolutionPrinter.print(bestSolution);
/*
* plot
*/
Plotter plotter = new Plotter(problem,bestSolution);
plotter.setLabel(Label.SIZE);
plotter.plot("output/solution.png", "solution");
Plotter plotter = new Plotter(problem, bestSolution);
plotter.setLabel(Label.SIZE);
plotter.plot("output/solution.png", "solution");
}
}
}

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.examples;
@ -39,27 +39,27 @@ import java.util.Collection;
public class SimpleEnRoutePickupAndDeliveryExample {
public static void main(String[] args) {
/*
public static void main(String[] args) {
/*
* some preparation - create output folder
*/
Examples.createOutputFolder();
Examples.createOutputFolder();
/*
* get a vehicle type-builder and build a type with the typeId "vehicleType" and a capacity of 2
*/
VehicleTypeImpl.Builder vehicleTypeBuilder = VehicleTypeImpl.Builder.newInstance("vehicleType").addCapacityDimension(0, 2);
VehicleType vehicleType = vehicleTypeBuilder.build();
VehicleTypeImpl.Builder vehicleTypeBuilder = VehicleTypeImpl.Builder.newInstance("vehicleType").addCapacityDimension(0, 2);
VehicleType vehicleType = vehicleTypeBuilder.build();
/*
* get a vehicle-builder and build a vehicle located at (10,10) with type "vehicleType"
*/
Builder vehicleBuilder = VehicleImpl.Builder.newInstance("vehicle");
vehicleBuilder.setStartLocation(loc(Coordinate.newInstance(10, 10)));
vehicleBuilder.setType(vehicleType);
VehicleImpl vehicle = vehicleBuilder.build();
Builder vehicleBuilder = VehicleImpl.Builder.newInstance("vehicle");
vehicleBuilder.setStartLocation(loc(Coordinate.newInstance(10, 10)));
vehicleBuilder.setType(vehicleType);
VehicleImpl vehicle = vehicleBuilder.build();
/*
* build shipments at the required locations, each with a capacity-demand of 1.
* 4 shipments
@ -68,65 +68,65 @@ public class SimpleEnRoutePickupAndDeliveryExample {
* 3: (15,7)->(14,9)
* 4: (15,13)->(14,11)
*/
Shipment shipment1 = Shipment.Builder.newInstance("1").addSizeDimension(0, 1).setPickupLocation(loc(Coordinate.newInstance(5, 7))).setDeliveryLocation(loc(Coordinate.newInstance(6, 9))).build();
Shipment shipment2 = Shipment.Builder.newInstance("2").addSizeDimension(0, 1).setPickupLocation(loc(Coordinate.newInstance(5, 13))).setDeliveryLocation(loc(Coordinate.newInstance(6, 11))).build();
Shipment shipment3 = Shipment.Builder.newInstance("3").addSizeDimension(0, 1).setPickupLocation(loc(Coordinate.newInstance(15, 7))).setDeliveryLocation(loc(Coordinate.newInstance(14, 9))).build();
Shipment shipment4 = Shipment.Builder.newInstance("4").addSizeDimension(0, 1).setPickupLocation(loc(Coordinate.newInstance(15, 13))).setDeliveryLocation(loc(Coordinate.newInstance(14, 11))).build();
VehicleRoutingProblem.Builder vrpBuilder = VehicleRoutingProblem.Builder.newInstance();
vrpBuilder.addVehicle(vehicle);
vrpBuilder.addJob(shipment1).addJob(shipment2).addJob(shipment3).addJob(shipment4);
VehicleRoutingProblem problem = vrpBuilder.build();
Shipment shipment1 = Shipment.Builder.newInstance("1").addSizeDimension(0, 1).setPickupLocation(loc(Coordinate.newInstance(5, 7))).setDeliveryLocation(loc(Coordinate.newInstance(6, 9))).build();
Shipment shipment2 = Shipment.Builder.newInstance("2").addSizeDimension(0, 1).setPickupLocation(loc(Coordinate.newInstance(5, 13))).setDeliveryLocation(loc(Coordinate.newInstance(6, 11))).build();
Shipment shipment3 = Shipment.Builder.newInstance("3").addSizeDimension(0, 1).setPickupLocation(loc(Coordinate.newInstance(15, 7))).setDeliveryLocation(loc(Coordinate.newInstance(14, 9))).build();
Shipment shipment4 = Shipment.Builder.newInstance("4").addSizeDimension(0, 1).setPickupLocation(loc(Coordinate.newInstance(15, 13))).setDeliveryLocation(loc(Coordinate.newInstance(14, 11))).build();
VehicleRoutingProblem.Builder vrpBuilder = VehicleRoutingProblem.Builder.newInstance();
vrpBuilder.addVehicle(vehicle);
vrpBuilder.addJob(shipment1).addJob(shipment2).addJob(shipment3).addJob(shipment4);
VehicleRoutingProblem problem = vrpBuilder.build();
/*
* get the algorithm out-of-the-box.
* get the algorithm out-of-the-box.
*/
VehicleRoutingAlgorithm algorithm = new SchrimpfFactory().createAlgorithm(problem);
VehicleRoutingAlgorithm algorithm = new SchrimpfFactory().createAlgorithm(problem);
/*
* and search a solution
*/
Collection<VehicleRoutingProblemSolution> solutions = algorithm.searchSolutions();
Collection<VehicleRoutingProblemSolution> solutions = algorithm.searchSolutions();
/*
* get the best
* get the best
*/
VehicleRoutingProblemSolution bestSolution = Solutions.bestOf(solutions);
VehicleRoutingProblemSolution bestSolution = Solutions.bestOf(solutions);
/*
* write out problem and solution to xml-file
*/
new VrpXMLWriter(problem, solutions).write("output/shipment-problem-with-solution.xml");
new VrpXMLWriter(problem, solutions).write("output/shipment-problem-with-solution.xml");
/*
* print nRoutes and totalCosts of bestSolution
*/
SolutionPrinter.print(bestSolution);
SolutionPrinter.print(bestSolution);
/*
* plot problem without solution
*/
Plotter problemPlotter = new Plotter(problem);
problemPlotter.plotShipments(true);
problemPlotter.plot("output/simpleEnRoutePickupAndDeliveryExample_problem.png", "en-route pickup and delivery");
Plotter problemPlotter = new Plotter(problem);
problemPlotter.plotShipments(true);
problemPlotter.plot("output/simpleEnRoutePickupAndDeliveryExample_problem.png", "en-route pickup and delivery");
/*
* plot problem with solution
*/
Plotter solutionPlotter = new Plotter(problem,Arrays.asList(Solutions.bestOf(solutions).getRoutes().iterator().next()));
solutionPlotter.plotShipments(true);
solutionPlotter.plot("output/simpleEnRoutePickupAndDeliveryExample_solution.png", "en-route pickup and delivery");
new GraphStreamViewer(problem).setRenderShipments(true).display();
}
Plotter solutionPlotter = new Plotter(problem, Arrays.asList(Solutions.bestOf(solutions).getRoutes().iterator().next()));
solutionPlotter.plotShipments(true);
solutionPlotter.plot("output/simpleEnRoutePickupAndDeliveryExample_solution.png", "en-route pickup and delivery");
private static Location loc(Coordinate coordinate) {
return Location.Builder.newInstance().setCoordinate(coordinate).build();
}
new GraphStreamViewer(problem).setRenderShipments(true).display();
}
private static Location loc(Coordinate coordinate) {
return Location.Builder.newInstance().setCoordinate(coordinate).build();
}
}

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.examples;
@ -38,28 +38,28 @@ import java.util.Collection;
public class SimpleEnRoutePickupAndDeliveryOpenRoutesExample {
public static void main(String[] args) {
/*
public static void main(String[] args) {
/*
* some preparation - create output folder
*/
Examples.createOutputFolder();
Examples.createOutputFolder();
/*
* get a vehicle type-builder and build a type with the typeId "vehicleType" and a capacity of 2
*/
VehicleTypeImpl.Builder vehicleTypeBuilder = VehicleTypeImpl.Builder.newInstance("vehicleType").addCapacityDimension(0, 2);
VehicleType vehicleType = vehicleTypeBuilder.build();
VehicleTypeImpl.Builder vehicleTypeBuilder = VehicleTypeImpl.Builder.newInstance("vehicleType").addCapacityDimension(0, 2);
VehicleType vehicleType = vehicleTypeBuilder.build();
/*
* get a vehicle-builder and build a vehicle located at (10,10) with type "vehicleType"
*/
Builder vehicleBuilder = VehicleImpl.Builder.newInstance("vehicle");
vehicleBuilder.setStartLocation(loc(Coordinate.newInstance(10, 10)));
vehicleBuilder.setType(vehicleType);
vehicleBuilder.setReturnToDepot(false);
VehicleImpl vehicle = vehicleBuilder.build();
Builder vehicleBuilder = VehicleImpl.Builder.newInstance("vehicle");
vehicleBuilder.setStartLocation(loc(Coordinate.newInstance(10, 10)));
vehicleBuilder.setType(vehicleType);
vehicleBuilder.setReturnToDepot(false);
VehicleImpl vehicle = vehicleBuilder.build();
/*
* build shipments at the required locations, each with a capacity-demand of 1.
* 4 shipments
@ -68,64 +68,64 @@ public class SimpleEnRoutePickupAndDeliveryOpenRoutesExample {
* 3: (15,7)->(14,9)
* 4: (15,13)->(14,11)
*/
Shipment shipment1 = Shipment.Builder.newInstance("1").addSizeDimension(0, 1).setPickupLocation(loc(Coordinate.newInstance(5, 7))).setDeliveryLocation(loc(Coordinate.newInstance(6, 9))).build();
Shipment shipment2 = Shipment.Builder.newInstance("2").addSizeDimension(0, 1).setPickupLocation(loc(Coordinate.newInstance(5, 13))).setDeliveryLocation(loc(Coordinate.newInstance(6, 11))).build();
Shipment shipment3 = Shipment.Builder.newInstance("3").addSizeDimension(0, 1).setPickupLocation(loc(Coordinate.newInstance(15, 7))).setDeliveryLocation(loc(Coordinate.newInstance(14, 9))).build();
Shipment shipment4 = Shipment.Builder.newInstance("4").addSizeDimension(0, 1).setPickupLocation(loc(Coordinate.newInstance(15, 13))).setDeliveryLocation(loc(Coordinate.newInstance(14, 11))).build();
VehicleRoutingProblem.Builder vrpBuilder = VehicleRoutingProblem.Builder.newInstance();
vrpBuilder.addVehicle(vehicle);
vrpBuilder.addJob(shipment1).addJob(shipment2).addJob(shipment3).addJob(shipment4);
VehicleRoutingProblem problem = vrpBuilder.build();
Shipment shipment1 = Shipment.Builder.newInstance("1").addSizeDimension(0, 1).setPickupLocation(loc(Coordinate.newInstance(5, 7))).setDeliveryLocation(loc(Coordinate.newInstance(6, 9))).build();
Shipment shipment2 = Shipment.Builder.newInstance("2").addSizeDimension(0, 1).setPickupLocation(loc(Coordinate.newInstance(5, 13))).setDeliveryLocation(loc(Coordinate.newInstance(6, 11))).build();
Shipment shipment3 = Shipment.Builder.newInstance("3").addSizeDimension(0, 1).setPickupLocation(loc(Coordinate.newInstance(15, 7))).setDeliveryLocation(loc(Coordinate.newInstance(14, 9))).build();
Shipment shipment4 = Shipment.Builder.newInstance("4").addSizeDimension(0, 1).setPickupLocation(loc(Coordinate.newInstance(15, 13))).setDeliveryLocation(loc(Coordinate.newInstance(14, 11))).build();
VehicleRoutingProblem.Builder vrpBuilder = VehicleRoutingProblem.Builder.newInstance();
vrpBuilder.addVehicle(vehicle);
vrpBuilder.addJob(shipment1).addJob(shipment2).addJob(shipment3).addJob(shipment4);
VehicleRoutingProblem problem = vrpBuilder.build();
/*
* get the algorithm out-of-the-box.
* get the algorithm out-of-the-box.
*/
VehicleRoutingAlgorithm algorithm = new SchrimpfFactory().createAlgorithm(problem);
VehicleRoutingAlgorithm algorithm = new SchrimpfFactory().createAlgorithm(problem);
/*
* and search a solution
*/
Collection<VehicleRoutingProblemSolution> solutions = algorithm.searchSolutions();
Collection<VehicleRoutingProblemSolution> solutions = algorithm.searchSolutions();
/*
* get the best
* get the best
*/
VehicleRoutingProblemSolution bestSolution = Solutions.bestOf(solutions);
VehicleRoutingProblemSolution bestSolution = Solutions.bestOf(solutions);
/*
* write out problem and solution to xml-file
*/
new VrpXMLWriter(problem, solutions).write("output/shipment-problem-with-solution.xml");
new VrpXMLWriter(problem, solutions).write("output/shipment-problem-with-solution.xml");
/*
* print nRoutes and totalCosts of bestSolution
*/
SolutionPrinter.print(problem, bestSolution, SolutionPrinter.Print.VERBOSE);
SolutionPrinter.print(problem, bestSolution, SolutionPrinter.Print.VERBOSE);
/*
* plot problem without solution
*/
Plotter problemPlotter = new Plotter(problem);
problemPlotter.plotShipments(true);
problemPlotter.plot("output/simpleEnRoutePickupAndDeliveryExample_problem.png", "en-route pickup and delivery");
Plotter problemPlotter = new Plotter(problem);
problemPlotter.plotShipments(true);
problemPlotter.plot("output/simpleEnRoutePickupAndDeliveryExample_problem.png", "en-route pickup and delivery");
/*
* plot problem with solution
*/
Plotter solutionPlotter = new Plotter(problem,Solutions.bestOf(solutions).getRoutes());
solutionPlotter.plotShipments(true);
solutionPlotter.plot("output/simpleEnRoutePickupAndDeliveryExample_solution.png", "en-route pickup and delivery");
new GraphStreamViewer(problem, bestSolution).setRenderShipments(true).setRenderDelay(100).display();
}
Plotter solutionPlotter = new Plotter(problem, Solutions.bestOf(solutions).getRoutes());
solutionPlotter.plotShipments(true);
solutionPlotter.plot("output/simpleEnRoutePickupAndDeliveryExample_solution.png", "en-route pickup and delivery");
private static Location loc(Coordinate coordinate) {
return Location.Builder.newInstance().setCoordinate(coordinate).build();
}
new GraphStreamViewer(problem, bestSolution).setRenderShipments(true).setRenderDelay(100).display();
}
private static Location loc(Coordinate coordinate) {
return Location.Builder.newInstance().setCoordinate(coordinate).build();
}
}

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.examples;
@ -41,27 +41,27 @@ import java.util.Collection;
public class SimpleEnRoutePickupAndDeliveryWithDepotBoundedDeliveriesExample {
public static void main(String[] args) {
/*
public static void main(String[] args) {
/*
* some preparation - create output folder
*/
Examples.createOutputFolder();
Examples.createOutputFolder();
/*
* get a vehicle type-builder and build a type with the typeId "vehicleType" and a capacity of 2
*/
VehicleTypeImpl.Builder vehicleTypeBuilder = VehicleTypeImpl.Builder.newInstance("vehicleType").addCapacityDimension(0, 2);
VehicleType vehicleType = vehicleTypeBuilder.build();
VehicleTypeImpl.Builder vehicleTypeBuilder = VehicleTypeImpl.Builder.newInstance("vehicleType").addCapacityDimension(0, 2);
VehicleType vehicleType = vehicleTypeBuilder.build();
/*
* get a vehicle-builder and build a vehicle located at (10,10) with type "vehicleType"
*/
Builder vehicleBuilder = VehicleImpl.Builder.newInstance("vehicle");
vehicleBuilder.setStartLocation(loc(Coordinate.newInstance(10, 10)));
vehicleBuilder.setType(vehicleType);
VehicleImpl vehicle = vehicleBuilder.build();
Builder vehicleBuilder = VehicleImpl.Builder.newInstance("vehicle");
vehicleBuilder.setStartLocation(loc(Coordinate.newInstance(10, 10)));
vehicleBuilder.setType(vehicleType);
VehicleImpl vehicle = vehicleBuilder.build();
/*
* build shipments at the required locations, each with a capacity-demand of 1.
* 4 shipments
@ -70,13 +70,13 @@ public class SimpleEnRoutePickupAndDeliveryWithDepotBoundedDeliveriesExample {
* 3: (15,7)->(14,9)
* 4: (15,13)->(14,11)
*/
Shipment shipment1 = Shipment.Builder.newInstance("1").addSizeDimension(0, 1).setPickupLocation(loc(Coordinate.newInstance(5, 7))).setDeliveryLocation(loc(Coordinate.newInstance(6, 9))).build();
Shipment shipment2 = Shipment.Builder.newInstance("2").addSizeDimension(0, 1).setPickupLocation(loc(Coordinate.newInstance(5, 13))).setDeliveryLocation(loc(Coordinate.newInstance(6, 11))).build();
Shipment shipment3 = Shipment.Builder.newInstance("3").addSizeDimension(0, 1).setPickupLocation(loc(Coordinate.newInstance(15, 7))).setDeliveryLocation(loc(Coordinate.newInstance(14, 9))).build();
Shipment shipment4 = Shipment.Builder.newInstance("4").addSizeDimension(0, 1).setPickupLocation(loc(Coordinate.newInstance(15, 13))).setDeliveryLocation(loc(Coordinate.newInstance(14, 11))).build();
//
Shipment shipment1 = Shipment.Builder.newInstance("1").addSizeDimension(0, 1).setPickupLocation(loc(Coordinate.newInstance(5, 7))).setDeliveryLocation(loc(Coordinate.newInstance(6, 9))).build();
Shipment shipment2 = Shipment.Builder.newInstance("2").addSizeDimension(0, 1).setPickupLocation(loc(Coordinate.newInstance(5, 13))).setDeliveryLocation(loc(Coordinate.newInstance(6, 11))).build();
Shipment shipment3 = Shipment.Builder.newInstance("3").addSizeDimension(0, 1).setPickupLocation(loc(Coordinate.newInstance(15, 7))).setDeliveryLocation(loc(Coordinate.newInstance(14, 9))).build();
Shipment shipment4 = Shipment.Builder.newInstance("4").addSizeDimension(0, 1).setPickupLocation(loc(Coordinate.newInstance(15, 13))).setDeliveryLocation(loc(Coordinate.newInstance(14, 11))).build();
//
/*
* build deliveries, (implicitly picked up in the depot)
* 1: (4,8)
@ -84,59 +84,59 @@ public class SimpleEnRoutePickupAndDeliveryWithDepotBoundedDeliveriesExample {
* 3: (16,8)
* 4: (16,12)
*/
Delivery delivery1 = (Delivery) Delivery.Builder.newInstance("5").addSizeDimension(0, 1).setLocation(loc(Coordinate.newInstance(4, 8))).build();
Delivery delivery2 = (Delivery) Delivery.Builder.newInstance("6").addSizeDimension(0, 1).setLocation(loc(Coordinate.newInstance(4, 12))).build();
Delivery delivery3 = (Delivery) Delivery.Builder.newInstance("7").addSizeDimension(0, 1).setLocation(loc(Coordinate.newInstance(16, 8))).build();
Delivery delivery4 = (Delivery) Delivery.Builder.newInstance("8").addSizeDimension(0, 1).setLocation(loc(Coordinate.newInstance(16, 12))).build();
VehicleRoutingProblem.Builder vrpBuilder = VehicleRoutingProblem.Builder.newInstance();
vrpBuilder.addVehicle(vehicle);
vrpBuilder.addJob(shipment1).addJob(shipment2).addJob(shipment3).addJob(shipment4)
.addJob(delivery1).addJob(delivery2).addJob(delivery3).addJob(delivery4).build();
Delivery delivery1 = (Delivery) Delivery.Builder.newInstance("5").addSizeDimension(0, 1).setLocation(loc(Coordinate.newInstance(4, 8))).build();
Delivery delivery2 = (Delivery) Delivery.Builder.newInstance("6").addSizeDimension(0, 1).setLocation(loc(Coordinate.newInstance(4, 12))).build();
Delivery delivery3 = (Delivery) Delivery.Builder.newInstance("7").addSizeDimension(0, 1).setLocation(loc(Coordinate.newInstance(16, 8))).build();
Delivery delivery4 = (Delivery) Delivery.Builder.newInstance("8").addSizeDimension(0, 1).setLocation(loc(Coordinate.newInstance(16, 12))).build();
VehicleRoutingProblem.Builder vrpBuilder = VehicleRoutingProblem.Builder.newInstance();
vrpBuilder.addVehicle(vehicle);
vrpBuilder.addJob(shipment1).addJob(shipment2).addJob(shipment3).addJob(shipment4)
.addJob(delivery1).addJob(delivery2).addJob(delivery3).addJob(delivery4).build();
VehicleRoutingProblem problem = vrpBuilder.build();
VehicleRoutingProblem problem = vrpBuilder.build();
/*
* build the algorithm
*/
VehicleRoutingAlgorithmBuilder vraBuilder = new VehicleRoutingAlgorithmBuilder(problem,"input/algorithmConfig.xml");
VehicleRoutingAlgorithmBuilder vraBuilder = new VehicleRoutingAlgorithmBuilder(problem, "input/algorithmConfig.xml");
vraBuilder.addCoreConstraints();
vraBuilder.addDefaultCostCalculators();
StateManager stateManager = new StateManager(problem);
ConstraintManager constraintManager = new ConstraintManager(problem,stateManager);
ConstraintManager constraintManager = new ConstraintManager(problem, stateManager);
constraintManager.addConstraint(new ServiceDeliveriesFirstConstraint(), ConstraintManager.Priority.CRITICAL);
vraBuilder.setStateAndConstraintManager(stateManager,constraintManager);
vraBuilder.setStateAndConstraintManager(stateManager, constraintManager);
VehicleRoutingAlgorithm algorithm = vraBuilder.build();
/*
* and search a solution
*/
Collection<VehicleRoutingProblemSolution> solutions = algorithm.searchSolutions();
Collection<VehicleRoutingProblemSolution> solutions = algorithm.searchSolutions();
/*
* get the best
* get the best
*/
VehicleRoutingProblemSolution bestSolution = Solutions.bestOf(solutions);
new VrpXMLWriter(problem, solutions).write("output/mixed-shipments-services-problem-with-solution.xml");
SolutionPrinter.print(bestSolution);
VehicleRoutingProblemSolution bestSolution = Solutions.bestOf(solutions);
new VrpXMLWriter(problem, solutions).write("output/mixed-shipments-services-problem-with-solution.xml");
SolutionPrinter.print(bestSolution);
/*
* plot
*/
Plotter problemPlotter = new Plotter(problem);
problemPlotter.plotShipments(true);
problemPlotter.plot("output/simpleMixedEnRoutePickupAndDeliveryExample_problem.png", "en-route pd and depot bounded deliveries");
Plotter solutionPlotter = new Plotter(problem,Solutions.bestOf(solutions));
solutionPlotter.plotShipments(true);
solutionPlotter.plot("output/simpleMixedEnRoutePickupAndDeliveryExample_solution.png", "en-route pd and depot bounded deliveries");
}
Plotter problemPlotter = new Plotter(problem);
problemPlotter.plotShipments(true);
problemPlotter.plot("output/simpleMixedEnRoutePickupAndDeliveryExample_problem.png", "en-route pd and depot bounded deliveries");
private static Location loc(Coordinate coordinate) {
return Location.Builder.newInstance().setCoordinate(coordinate).build();
}
Plotter solutionPlotter = new Plotter(problem, Solutions.bestOf(solutions));
solutionPlotter.plotShipments(true);
solutionPlotter.plot("output/simpleMixedEnRoutePickupAndDeliveryExample_solution.png", "en-route pd and depot bounded deliveries");
}
private static Location loc(Coordinate coordinate) {
return Location.Builder.newInstance().setCoordinate(coordinate).build();
}
}

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.examples;
@ -37,77 +37,76 @@ import java.util.Collection;
public class SimpleExample {
public static void main(String[] args) {
/*
public static void main(String[] args) {
/*
* some preparation - create output folder
*/
File dir = new File("output");
// if the directory does not exist, create it
if (!dir.exists()){
System.out.println("creating directory ./output");
boolean result = dir.mkdir();
if(result) System.out.println("./output created");
}
File dir = new File("output");
// if the directory does not exist, create it
if (!dir.exists()) {
System.out.println("creating directory ./output");
boolean result = dir.mkdir();
if (result) System.out.println("./output created");
}
/*
* 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);
VehicleType vehicleType = vehicleTypeBuilder.build();
final int WEIGHT_INDEX = 0;
VehicleTypeImpl.Builder vehicleTypeBuilder = VehicleTypeImpl.Builder.newInstance("vehicleType").addCapacityDimension(WEIGHT_INDEX, 2);
VehicleType vehicleType = vehicleTypeBuilder.build();
/*
* get a vehicle-builder and build a vehicle located at (10,10) with type "vehicleType"
*/
Builder vehicleBuilder = VehicleImpl.Builder.newInstance("vehicle");
vehicleBuilder.setStartLocation(Location.newInstance(10, 10));
vehicleBuilder.setType(vehicleType);
VehicleImpl vehicle = vehicleBuilder.build();
Builder vehicleBuilder = VehicleImpl.Builder.newInstance("vehicle");
vehicleBuilder.setStartLocation(Location.newInstance(10, 10));
vehicleBuilder.setType(vehicleType);
VehicleImpl vehicle = vehicleBuilder.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 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);
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();
VehicleRoutingProblem.Builder vrpBuilder = VehicleRoutingProblem.Builder.newInstance();
vrpBuilder.addVehicle(vehicle);
vrpBuilder.addJob(service1).addJob(service2).addJob(service3).addJob(service4);
VehicleRoutingProblem problem = vrpBuilder.build();
VehicleRoutingProblem problem = vrpBuilder.build();
/*
* get the algorithm out-of-the-box.
* get the algorithm out-of-the-box.
*/
VehicleRoutingAlgorithm algorithm = new SchrimpfFactory().createAlgorithm(problem);
VehicleRoutingAlgorithm algorithm = new SchrimpfFactory().createAlgorithm(problem);
/*
* and search a solution
*/
Collection<VehicleRoutingProblemSolution> solutions = algorithm.searchSolutions();
Collection<VehicleRoutingProblemSolution> solutions = algorithm.searchSolutions();
/*
* get the best
* get the best
*/
VehicleRoutingProblemSolution bestSolution = Solutions.bestOf(solutions);
new VrpXMLWriter(problem, solutions).write("output/problem-with-solution.xml");
SolutionPrinter.print(problem, bestSolution, SolutionPrinter.Print.VERBOSE);
VehicleRoutingProblemSolution bestSolution = Solutions.bestOf(solutions);
new VrpXMLWriter(problem, solutions).write("output/problem-with-solution.xml");
SolutionPrinter.print(problem, bestSolution, SolutionPrinter.Print.VERBOSE);
/*
* plot
*/
// SolutionPlotter.plotSolutionAsPNG(problem, bestSolution, "output/solution.png", "solution");
new GraphStreamViewer(problem, bestSolution).labelWith(Label.ID).setRenderDelay(200).display();
}
new GraphStreamViewer(problem, bestSolution).labelWith(Label.ID).setRenderDelay(200).display();
}
}

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.examples;
@ -36,71 +36,71 @@ import java.util.Collection;
public class SimpleExampleOpenRoutes {
public static void main(String[] args) {
/*
public static void main(String[] args) {
/*
* some preparation - create output folder
*/
Examples.createOutputFolder();
Examples.createOutputFolder();
/*
* get a vehicle type-builder and build a type with the typeId "vehicleType" and a capacity of 2
*/
VehicleTypeImpl.Builder vehicleTypeBuilder = VehicleTypeImpl.Builder.newInstance("vehicleType").addCapacityDimension(0, 2);
vehicleTypeBuilder.setFixedCost(100);
VehicleType vehicleType = vehicleTypeBuilder.build();
VehicleTypeImpl.Builder vehicleTypeBuilder = VehicleTypeImpl.Builder.newInstance("vehicleType").addCapacityDimension(0, 2);
vehicleTypeBuilder.setFixedCost(100);
VehicleType vehicleType = vehicleTypeBuilder.build();
/*
* get a vehicle-builder and build a vehicle located at (10,10) with type "vehicleType"
*/
Builder vehicleBuilder = VehicleImpl.Builder.newInstance("vehicle");
vehicleBuilder.setStartLocation(Location.newInstance(10, 10));
vehicleBuilder.setType(vehicleType);
vehicleBuilder.setReturnToDepot(false);
VehicleImpl vehicle = vehicleBuilder.build();
Builder vehicleBuilder = VehicleImpl.Builder.newInstance("vehicle");
vehicleBuilder.setStartLocation(Location.newInstance(10, 10));
vehicleBuilder.setType(vehicleType);
vehicleBuilder.setReturnToDepot(false);
VehicleImpl vehicle = vehicleBuilder.build();
/*
* build services at the required locations, each with a capacity-demand of 1.
*/
Service service1 = Service.Builder.newInstance("1").addSizeDimension(0, 1).setLocation(Location.newInstance(5, 7)).build();
Service service2 = Service.Builder.newInstance("2").addSizeDimension(0, 1).setLocation(Location.newInstance(5, 13)).build();
Service service3 = Service.Builder.newInstance("3").addSizeDimension(0, 1).setLocation(Location.newInstance(15, 7)).build();
Service service4 = Service.Builder.newInstance("4").addSizeDimension(0, 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);
VehicleRoutingProblem problem = vrpBuilder.build();
Service service1 = Service.Builder.newInstance("1").addSizeDimension(0, 1).setLocation(Location.newInstance(5, 7)).build();
Service service2 = Service.Builder.newInstance("2").addSizeDimension(0, 1).setLocation(Location.newInstance(5, 13)).build();
Service service3 = Service.Builder.newInstance("3").addSizeDimension(0, 1).setLocation(Location.newInstance(15, 7)).build();
Service service4 = Service.Builder.newInstance("4").addSizeDimension(0, 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);
VehicleRoutingProblem problem = vrpBuilder.build();
/*
* get the algorithm out-of-the-box.
* get the algorithm out-of-the-box.
*/
VehicleRoutingAlgorithm algorithm = VehicleRoutingAlgorithms.readAndCreateAlgorithm(problem, "input/algorithmConfig_fix.xml");
VehicleRoutingAlgorithm algorithm = VehicleRoutingAlgorithms.readAndCreateAlgorithm(problem, "input/algorithmConfig_fix.xml");
/*
* and search a solution
*/
Collection<VehicleRoutingProblemSolution> solutions = algorithm.searchSolutions();
Collection<VehicleRoutingProblemSolution> solutions = algorithm.searchSolutions();
/*
* get the best
* get the best
*/
VehicleRoutingProblemSolution bestSolution = Solutions.bestOf(solutions);
new VrpXMLWriter(problem, solutions).write("output/problem-with-solution.xml");
SolutionPrinter.print(bestSolution);
VehicleRoutingProblemSolution bestSolution = Solutions.bestOf(solutions);
new VrpXMLWriter(problem, solutions).write("output/problem-with-solution.xml");
SolutionPrinter.print(bestSolution);
/*
* plot
*/
new Plotter(problem, bestSolution).plot("output/solution.png", "solution");
}
new Plotter(problem, bestSolution).plot("output/solution.png", "solution");
}
}

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.examples;
@ -41,61 +41,60 @@ import java.util.Collection;
public class SimpleExampleWithSkills {
public static void main(String[] args) {
/*
public static void main(String[] args) {
/*
* some preparation - create output folder
*/
File dir = new File("output");
// if the directory does not exist, create it
if (!dir.exists()){
System.out.println("creating directory ./output");
boolean result = dir.mkdir();
if(result) System.out.println("./output created");
}
File dir = new File("output");
// if the directory does not exist, create it
if (!dir.exists()) {
System.out.println("creating directory ./output");
boolean result = dir.mkdir();
if (result) System.out.println("./output created");
}
/*
* 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);
VehicleType vehicleType = vehicleTypeBuilder.build();
final int WEIGHT_INDEX = 0;
VehicleTypeImpl.Builder vehicleTypeBuilder = VehicleTypeImpl.Builder.newInstance("vehicleType").addCapacityDimension(WEIGHT_INDEX, 2);
VehicleType vehicleType = vehicleTypeBuilder.build();
/*
* get a vehicle-builder and build a vehicle located at (10,10) with type "vehicleType"
*/
Builder vehicleBuilder = Builder.newInstance("vehicle");
vehicleBuilder.setStartLocation(Location.newInstance(10, 10));
vehicleBuilder.setType(vehicleType);
VehicleImpl vehicle = vehicleBuilder.build();
Builder vehicleBuilder = Builder.newInstance("vehicle");
vehicleBuilder.setStartLocation(Location.newInstance(10, 10));
vehicleBuilder.setType(vehicleType);
VehicleImpl vehicle = vehicleBuilder.build();
Builder vehicle2Builder = Builder.newInstance("vehicle2");
vehicle2Builder.setStartLocation(Location.newInstance(1, 1));
vehicle2Builder.setType(vehicleType);
vehicle2Builder.addSkill("drill");
VehicleImpl vehicle2 = vehicle2Builder.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 service3 = Service.Builder.newInstance("3").addSizeDimension(WEIGHT_INDEX, 1).setLocation(Location.newInstance(15, 7)).build();
Service service1 = Service.Builder.newInstance("1").addSizeDimension(WEIGHT_INDEX, 1).setLocation(Location.newInstance(5, 7)).build();
Service service2 = Service.Builder.newInstance("2").addSizeDimension(WEIGHT_INDEX, 1).setLocation(Location.newInstance(5, 13)).build();
Service 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).addRequiredSkill("drill").setLocation(Location.newInstance(15, 13)).build();
VehicleRoutingProblem.Builder vrpBuilder = VehicleRoutingProblem.Builder.newInstance();
vrpBuilder.addVehicle(vehicle).addVehicle(vehicle2);
vrpBuilder.addJob(service1).addJob(service2).addJob(service3).addJob(service4);
VehicleRoutingProblem problem = vrpBuilder.build();
Service service4 = Service.Builder.newInstance("4").addSizeDimension(WEIGHT_INDEX, 1).addRequiredSkill("drill").setLocation(Location.newInstance(15, 13)).build();
VehicleRoutingProblem.Builder vrpBuilder = VehicleRoutingProblem.Builder.newInstance();
vrpBuilder.addVehicle(vehicle).addVehicle(vehicle2);
vrpBuilder.addJob(service1).addJob(service2).addJob(service3).addJob(service4);
VehicleRoutingProblem problem = vrpBuilder.build();
/*
* get the algorithm out-of-the-box.
* get the algorithm out-of-the-box.
*/
VehicleRoutingAlgorithmBuilder vraBuilder = new VehicleRoutingAlgorithmBuilder(problem,"input/algorithmConfig.xml");
VehicleRoutingAlgorithmBuilder vraBuilder = new VehicleRoutingAlgorithmBuilder(problem, "input/algorithmConfig.xml");
vraBuilder.addCoreConstraints();
vraBuilder.addDefaultCostCalculators();
@ -103,33 +102,33 @@ public class SimpleExampleWithSkills {
StateManager stateManager = new StateManager(problem);
stateManager.updateSkillStates();
ConstraintManager constraintManager = new ConstraintManager(problem,stateManager);
ConstraintManager constraintManager = new ConstraintManager(problem, stateManager);
constraintManager.addSkillsConstraint();
vraBuilder.setStateAndConstraintManager(stateManager,constraintManager);
vraBuilder.setStateAndConstraintManager(stateManager, constraintManager);
VehicleRoutingAlgorithm algorithm = vraBuilder.build();
VehicleRoutingAlgorithm algorithm = vraBuilder.build();
/*
* and search a solution
*/
Collection<VehicleRoutingProblemSolution> solutions = algorithm.searchSolutions();
Collection<VehicleRoutingProblemSolution> solutions = algorithm.searchSolutions();
/*
* get the best
* get the best
*/
VehicleRoutingProblemSolution bestSolution = Solutions.bestOf(solutions);
new VrpXMLWriter(problem, solutions).write("output/problem-with-solution.xml");
SolutionPrinter.print(problem, bestSolution, SolutionPrinter.Print.VERBOSE);
VehicleRoutingProblemSolution bestSolution = Solutions.bestOf(solutions);
new VrpXMLWriter(problem, solutions).write("output/problem-with-solution.xml");
SolutionPrinter.print(problem, bestSolution, SolutionPrinter.Print.VERBOSE);
/*
* plot
*/
// SolutionPlotter.plotSolutionAsPNG(problem, bestSolution, "output/solution.png", "solution");
new GraphStreamViewer(problem, bestSolution).labelWith(Label.ID).setRenderDelay(200).display();
}
new GraphStreamViewer(problem, bestSolution).labelWith(Label.ID).setRenderDelay(200).display();
}
}

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.examples;
@ -41,74 +41,74 @@ import java.util.Collection;
public class SimpleVRPWithBackhaulsExample {
public static void main(String[] args) {
/*
public static void main(String[] args) {
/*
* some preparation - create output folder
*/
Examples.createOutputFolder();
Examples.createOutputFolder();
/*
* get a vehicle type-builder and build a type with the typeId "vehicleType" and a capacity of 2
*/
VehicleTypeImpl.Builder vehicleTypeBuilder = VehicleTypeImpl.Builder.newInstance("vehicleType").addCapacityDimension(0, 2);
VehicleType vehicleType = vehicleTypeBuilder.build();
VehicleTypeImpl.Builder vehicleTypeBuilder = VehicleTypeImpl.Builder.newInstance("vehicleType").addCapacityDimension(0, 2);
VehicleType vehicleType = vehicleTypeBuilder.build();
/*
* get a vehicle-builder and build a vehicle located at (10,10) with type "vehicleType"
*/
Builder vehicleBuilder = VehicleImpl.Builder.newInstance("vehicle");
vehicleBuilder.setStartLocation(Location.newInstance(10, 10));
vehicleBuilder.setType(vehicleType);
VehicleImpl vehicle = vehicleBuilder.build();
Builder vehicleBuilder = VehicleImpl.Builder.newInstance("vehicle");
vehicleBuilder.setStartLocation(Location.newInstance(10, 10));
vehicleBuilder.setType(vehicleType);
VehicleImpl vehicle = vehicleBuilder.build();
/*
* build pickups and deliveries at the required locations, each with a capacity-demand of 1.
*/
Pickup pickup1 = (Pickup) Pickup.Builder.newInstance("1").addSizeDimension(0, 1).setLocation(Location.newInstance(5, 7)).build();
Delivery delivery1 = (Delivery) Delivery.Builder.newInstance("2").addSizeDimension(0, 1).setLocation(Location.newInstance(5, 13)).build();
Pickup pickup2 = (Pickup) Pickup.Builder.newInstance("3").addSizeDimension(0, 1).setLocation(Location.newInstance(15, 7)).build();
Delivery delivery2 = (Delivery) Delivery.Builder.newInstance("4").addSizeDimension(0, 1).setLocation(Location.newInstance(15, 13)).build();
VehicleRoutingProblem.Builder vrpBuilder = VehicleRoutingProblem.Builder.newInstance();
vrpBuilder.addVehicle(vehicle);
vrpBuilder.addJob(pickup1).addJob(pickup2).addJob(delivery1).addJob(delivery2);
Pickup pickup1 = (Pickup) Pickup.Builder.newInstance("1").addSizeDimension(0, 1).setLocation(Location.newInstance(5, 7)).build();
Delivery delivery1 = (Delivery) Delivery.Builder.newInstance("2").addSizeDimension(0, 1).setLocation(Location.newInstance(5, 13)).build();
VehicleRoutingProblem problem = vrpBuilder.build();
Pickup pickup2 = (Pickup) Pickup.Builder.newInstance("3").addSizeDimension(0, 1).setLocation(Location.newInstance(15, 7)).build();
Delivery delivery2 = (Delivery) Delivery.Builder.newInstance("4").addSizeDimension(0, 1).setLocation(Location.newInstance(15, 13)).build();
VehicleRoutingAlgorithmBuilder vraBuilder = new VehicleRoutingAlgorithmBuilder(problem,"input/algorithmConfig.xml");
VehicleRoutingProblem.Builder vrpBuilder = VehicleRoutingProblem.Builder.newInstance();
vrpBuilder.addVehicle(vehicle);
vrpBuilder.addJob(pickup1).addJob(pickup2).addJob(delivery1).addJob(delivery2);
VehicleRoutingProblem problem = vrpBuilder.build();
VehicleRoutingAlgorithmBuilder vraBuilder = new VehicleRoutingAlgorithmBuilder(problem, "input/algorithmConfig.xml");
vraBuilder.addCoreConstraints();
vraBuilder.addDefaultCostCalculators();
StateManager stateManager = new StateManager(problem);
ConstraintManager constraintManager = new ConstraintManager(problem,stateManager);
ConstraintManager constraintManager = new ConstraintManager(problem, stateManager);
constraintManager.addConstraint(new ServiceDeliveriesFirstConstraint(), ConstraintManager.Priority.CRITICAL);
vraBuilder.setStateAndConstraintManager(stateManager,constraintManager);
vraBuilder.setStateAndConstraintManager(stateManager, constraintManager);
VehicleRoutingAlgorithm algorithm = vraBuilder.build();
/*
* and search a solution
*/
Collection<VehicleRoutingProblemSolution> solutions = algorithm.searchSolutions();
Collection<VehicleRoutingProblemSolution> solutions = algorithm.searchSolutions();
/*
* get the best
* get the best
*/
VehicleRoutingProblemSolution bestSolution = Solutions.bestOf(solutions);
new VrpXMLWriter(problem, solutions).write("output/problem-with-solution.xml");
SolutionPrinter.print(bestSolution);
VehicleRoutingProblemSolution bestSolution = Solutions.bestOf(solutions);
new VrpXMLWriter(problem, solutions).write("output/problem-with-solution.xml");
SolutionPrinter.print(bestSolution);
/*
* plot
*/
Plotter plotter = new Plotter(problem,bestSolution);
plotter.setLabel(Label.SIZE);
plotter.plot("output/solution.png", "solution");
Plotter plotter = new Plotter(problem, bestSolution);
plotter.setLabel(Label.SIZE);
plotter.plot("output/solution.png", "solution");
}
}
}

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.examples;
@ -32,67 +32,67 @@ import java.util.Collection;
public class SolomonExample {
public static void main(String[] args) {
/*
public static void main(String[] args) {
/*
* some preparation - create output folder
*/
Examples.createOutputFolder();
Examples.createOutputFolder();
/*
* Build the problem.
*
*
* But define a problem-builder first.
*/
VehicleRoutingProblem.Builder vrpBuilder = VehicleRoutingProblem.Builder.newInstance();
VehicleRoutingProblem.Builder vrpBuilder = VehicleRoutingProblem.Builder.newInstance();
/*
* A solomonReader reads solomon-instance files, and stores the required information in the builder.
*/
new SolomonReader(vrpBuilder).read("input/C101_solomon.txt");
new SolomonReader(vrpBuilder).read("input/C101_solomon.txt");
/*
* Finally, the problem can be built. By default, transportCosts are crowFlyDistances (as usually used for vrp-instances).
*/
VehicleRoutingProblem vrp = vrpBuilder.build();
VehicleRoutingProblem vrp = vrpBuilder.build();
new Plotter(vrp).plot("output/solomon_C101.png", "C101");
new Plotter(vrp).plot("output/solomon_C101.png", "C101");
/*
* Define the required vehicle-routing algorithms to solve the above problem.
*
*
* The algorithm can be defined and configured in an xml-file.
*/
VehicleRoutingAlgorithm vra = new SchrimpfFactory().createAlgorithm(vrp);
VehicleRoutingAlgorithm vra = new SchrimpfFactory().createAlgorithm(vrp);
/*
* Solve the problem.
*
*
*
*/
Collection<VehicleRoutingProblemSolution> solutions = vra.searchSolutions();
Collection<VehicleRoutingProblemSolution> solutions = vra.searchSolutions();
/*
* Retrieve best solution.
*/
VehicleRoutingProblemSolution solution = new SelectBest().selectSolution(solutions);
VehicleRoutingProblemSolution solution = new SelectBest().selectSolution(solutions);
/*
* print solution
*/
SolutionPrinter.print(vrp, solution, SolutionPrinter.Print.VERBOSE);
/*
* Plot solution.
*/
Plotter plotter = new Plotter(vrp,solution);
// plotter.setBoundingBox(30, 0, 50, 20);
plotter.plot("output/solomon_C101_solution.png", "C101");
SolutionPrinter.print(vrp, solution, SolutionPrinter.Print.VERBOSE);
new GraphStreamViewer(vrp,solution).setCameraView(30, 30, 0.25).labelWith(Label.ID).setRenderDelay(100).display();
}
/*
* Plot solution.
*/
Plotter plotter = new Plotter(vrp, solution);
// plotter.setBoundingBox(30, 0, 50, 20);
plotter.plot("output/solomon_C101_solution.png", "C101");
new GraphStreamViewer(vrp, solution).setCameraView(30, 30, 0.25).labelWith(Label.ID).setRenderDelay(100).display();
}
}

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.examples;
@ -33,77 +33,77 @@ import java.util.Collection;
public class SolomonExampleWithSpecifiedVehicleEndLocations {
public static void main(String[] args) {
/*
public static void main(String[] args) {
/*
* some preparation - create output folder
*/
File dir = new File("output");
// if the directory does not exist, create it
if (!dir.exists()){
System.out.println("creating directory ./output");
boolean result = dir.mkdir();
if(result) System.out.println("./output created");
}
File dir = new File("output");
// if the directory does not exist, create it
if (!dir.exists()) {
System.out.println("creating directory ./output");
boolean result = dir.mkdir();
if (result) System.out.println("./output created");
}
/*
* Build the problem.
*
*
* But define a problem-builder first.
*/
VehicleRoutingProblem.Builder vrpBuilder = VehicleRoutingProblem.Builder.newInstance();
VehicleRoutingProblem.Builder vrpBuilder = VehicleRoutingProblem.Builder.newInstance();
/*
* A solomonReader reads solomon-instance files, and stores the required information in the builder.
*/
new VrpXMLReader(vrpBuilder).read("input/deliveries_solomon_specifiedVehicleEndLocations_c101.xml");
new VrpXMLReader(vrpBuilder).read("input/deliveries_solomon_specifiedVehicleEndLocations_c101.xml");
/*
* Finally, the problem can be built. By default, transportCosts are crowFlyDistances (as usually used for vrp-instances).
*/
VehicleRoutingProblem vrp = vrpBuilder.build();
Plotter pblmPlotter = new Plotter(vrp);
pblmPlotter.plot("output/solomon_C101_specifiedVehicleEndLocations.png","C101");
VehicleRoutingProblem vrp = vrpBuilder.build();
Plotter pblmPlotter = new Plotter(vrp);
pblmPlotter.plot("output/solomon_C101_specifiedVehicleEndLocations.png", "C101");
/*
* Define the required vehicle-routing algorithms to solve the above problem.
*
*
* The algorithm can be defined and configured in an xml-file.
*/
// VehicleRoutingAlgorithm vra = new SchrimpfFactory().createAlgorithm(vrp);
VehicleRoutingAlgorithm vra = VehicleRoutingAlgorithms.readAndCreateAlgorithm(vrp, "input/algorithmConfig_fix.xml");
vra.setMaxIterations(20000);
VehicleRoutingAlgorithm vra = VehicleRoutingAlgorithms.readAndCreateAlgorithm(vrp, "input/algorithmConfig_fix.xml");
vra.setMaxIterations(20000);
// vra.setPrematureBreak(100);
vra.getAlgorithmListeners().addListener(new AlgorithmSearchProgressChartListener("output/sol_progress.png"));
vra.getAlgorithmListeners().addListener(new AlgorithmSearchProgressChartListener("output/sol_progress.png"));
/*
* Solve the problem.
*
*
*
*/
Collection<VehicleRoutingProblemSolution> solutions = vra.searchSolutions();
Collection<VehicleRoutingProblemSolution> solutions = vra.searchSolutions();
/*
* Retrieve best solution.
*/
VehicleRoutingProblemSolution solution = new SelectBest().selectSolution(solutions);
VehicleRoutingProblemSolution solution = new SelectBest().selectSolution(solutions);
/*
* print solution
*/
SolutionPrinter.print(solution);
SolutionPrinter.print(solution);
/*
* Plot solution.
* Plot solution.
*/
// SolutionPlotter.plotSolutionAsPNG(vrp, solution, "output/solomon_C101_specifiedVehicleEndLocations_solution.png","C101");
Plotter solPlotter = new Plotter(vrp, solution);
solPlotter.plot("output/solomon_C101_specifiedVehicleEndLocations_solution.png","C101");
new GraphStreamViewer(vrp, solution).setRenderDelay(50).labelWith(Label.ID).setEnableAutoLayout(true).display();
}
Plotter solPlotter = new Plotter(vrp, solution);
solPlotter.plot("output/solomon_C101_specifiedVehicleEndLocations_solution.png", "C101");
new GraphStreamViewer(vrp, solution).setRenderDelay(50).labelWith(Label.ID).setEnableAutoLayout(true).display();
}
}

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.examples;
@ -32,78 +32,78 @@ import java.util.Collection;
public class SolomonExampleWithSpecifiedVehicleEndLocationsWithoutTWs {
public static void main(String[] args) {
/*
public static void main(String[] args) {
/*
* some preparation - create output folder
*/
File dir = new File("output");
// if the directory does not exist, create it
if (!dir.exists()){
System.out.println("creating directory ./output");
boolean result = dir.mkdir();
if(result) System.out.println("./output created");
}
File dir = new File("output");
// if the directory does not exist, create it
if (!dir.exists()) {
System.out.println("creating directory ./output");
boolean result = dir.mkdir();
if (result) System.out.println("./output created");
}
/*
* Build the problem.
*
*
* But define a problem-builder first.
*/
VehicleRoutingProblem.Builder vrpBuilder = VehicleRoutingProblem.Builder.newInstance();
VehicleRoutingProblem.Builder vrpBuilder = VehicleRoutingProblem.Builder.newInstance();
/*
* A solomonReader reads solomon-instance files, and stores the required information in the builder.
*/
new VrpXMLReader(vrpBuilder).read("input/pickups_and_deliveries_solomon_c101_withoutTWs_and_specifiedVehicleEndLocations.xml");
new VrpXMLReader(vrpBuilder).read("input/pickups_and_deliveries_solomon_c101_withoutTWs_and_specifiedVehicleEndLocations.xml");
/*
* Finally, the problem can be built. By default, transportCosts are crowFlyDistances (as usually used for vrp-instances).
*/
// vrpBuilder.addProblemConstraint(Constraint.DELIVERIES_FIRST);
VehicleRoutingProblem vrp = vrpBuilder.build();
Plotter pblmPlotter = new Plotter(vrp);
pblmPlotter.plot("output/solomon_C101_specifiedVehicleEndLocations_withoutTWs.png","C101");
VehicleRoutingProblem vrp = vrpBuilder.build();
Plotter pblmPlotter = new Plotter(vrp);
pblmPlotter.plot("output/solomon_C101_specifiedVehicleEndLocations_withoutTWs.png", "C101");
/*
* Define the required vehicle-routing algorithms to solve the above problem.
*
*
* The algorithm can be defined and configured in an xml-file.
*/
// VehicleRoutingAlgorithm vra = new SchrimpfFactory().createAlgorithm(vrp);
VehicleRoutingAlgorithm vra = VehicleRoutingAlgorithms.readAndCreateAlgorithm(vrp, "input/algorithmConfigWithSchrimpfAcceptance.xml");
vra.setMaxIterations(20000);
VehicleRoutingAlgorithm vra = VehicleRoutingAlgorithms.readAndCreateAlgorithm(vrp, "input/algorithmConfigWithSchrimpfAcceptance.xml");
vra.setMaxIterations(20000);
// vra.setPrematureBreak(100);
// vra.getAlgorithmListeners().addListener(new AlgorithmSearchProgressChartListener("output/sol_progress.png"));
/*
* Solve the problem.
*
*
*
*/
Collection<VehicleRoutingProblemSolution> solutions = vra.searchSolutions();
Collection<VehicleRoutingProblemSolution> solutions = vra.searchSolutions();
/*
* Retrieve best solution.
*/
VehicleRoutingProblemSolution solution = new SelectBest().selectSolution(solutions);
VehicleRoutingProblemSolution solution = new SelectBest().selectSolution(solutions);
/*
* print solution
*/
SolutionPrinter.print(solution);
SolutionPrinter.print(solution);
/*
* Plot solution.
* Plot solution.
*/
// SolutionPlotter.plotSolutionAsPNG(vrp, solution, "output/solomon_C101_specifiedVehicleEndLocations_solution.png","C101");
Plotter solPlotter = new Plotter(vrp, solution);
solPlotter.plot("output/solomon_C101_specifiedVehicleEndLocations_withoutTWs_solution.png","C101");
new GraphStreamViewer(vrp, solution).setRenderDelay(50).labelWith(Label.ID).setEnableAutoLayout(true).display();
}
Plotter solPlotter = new Plotter(vrp, solution);
solPlotter.plot("output/solomon_C101_specifiedVehicleEndLocations_withoutTWs_solution.png", "C101");
new GraphStreamViewer(vrp, solution).setRenderDelay(50).labelWith(Label.ID).setEnableAutoLayout(true).display();
}
}

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.examples;
@ -32,68 +32,68 @@ import java.util.Collection;
public class SolomonOpenExample {
public static void main(String[] args) {
/*
public static void main(String[] args) {
/*
* some preparation - create output folder
*/
Examples.createOutputFolder();
Examples.createOutputFolder();
/*
* Build the problem.
*
*
* But define a problem-builder first.
*/
VehicleRoutingProblem.Builder vrpBuilder = VehicleRoutingProblem.Builder.newInstance();
VehicleRoutingProblem.Builder vrpBuilder = VehicleRoutingProblem.Builder.newInstance();
/*
* A solomonReader reads solomon-instance files, and stores the required information in the builder.
*/
new VrpXMLReader(vrpBuilder).read("input/deliveries_solomon_open_c101.xml");
new VrpXMLReader(vrpBuilder).read("input/deliveries_solomon_open_c101.xml");
/*
* Finally, the problem can be built. By default, transportCosts are crowFlyDistances (as usually used for vrp-instances).
*/
VehicleRoutingProblem vrp = vrpBuilder.build();
new Plotter(vrp).plot("output/solomon_C101_open.png", "C101");
VehicleRoutingProblem vrp = vrpBuilder.build();
new Plotter(vrp).plot("output/solomon_C101_open.png", "C101");
/*
* Define the required vehicle-routing algorithms to solve the above problem.
*
*
* The algorithm can be defined and configured in an xml-file.
*/
// VehicleRoutingAlgorithm vra = new SchrimpfFactory().createAlgorithm(vrp);
// VehicleRoutingAlgorithm vra = VehicleRoutingAlgorithms.readAndCreateAlgorithm(vrp, "input/algorithmConfig_fix.xml");
VehicleRoutingAlgorithm vra = Jsprit.createAlgorithm(vrp);
VehicleRoutingAlgorithm vra = Jsprit.createAlgorithm(vrp);
// vra.setPrematureBreak(100);
// vra.getAlgorithmListeners().addListener(new AlgorithmSearchProgressChartListener("output/sol_progress.png"));
/*
* Solve the problem.
*
*
*
*/
Collection<VehicleRoutingProblemSolution> solutions = vra.searchSolutions();
Collection<VehicleRoutingProblemSolution> solutions = vra.searchSolutions();
/*
* Retrieve best solution.
*/
VehicleRoutingProblemSolution solution = new SelectBest().selectSolution(solutions);
VehicleRoutingProblemSolution solution = new SelectBest().selectSolution(solutions);
/*
* print solution
*/
SolutionPrinter.print(solution);
SolutionPrinter.print(solution);
/*
* Plot solution.
* Plot solution.
*/
// SolutionPlotter.plotSolutionAsPNG(vrp, solution, "output/solomon_C101_open_solution.png","C101");
new GraphStreamViewer(vrp, solution).setRenderDelay(150).labelWith(Label.ID).setEnableAutoLayout(true).display();
}
new GraphStreamViewer(vrp, solution).setRenderDelay(150).labelWith(Label.ID).setEnableAutoLayout(true).display();
}
}

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.examples;
@ -32,28 +32,28 @@ import java.util.Collection;
public class SolomonR101Example {
public static void main(String[] args) {
/*
public static void main(String[] args) {
/*
* some preparation - create output folder
*/
Examples.createOutputFolder();
Examples.createOutputFolder();
/*
* Build the problem.
*
* But define a problem-builder first.
*/
VehicleRoutingProblem.Builder vrpBuilder = VehicleRoutingProblem.Builder.newInstance();
VehicleRoutingProblem.Builder vrpBuilder = VehicleRoutingProblem.Builder.newInstance();
/*
* A solomonReader reads solomon-instance files, and stores the required information in the builder.
*/
// new SolomonReader(vrpBuilder).read("/Users/schroeder/IdeaProjects/jsprit/jsprit-instances/instances/solomon/R211.txt");
new VrpXMLReader(vrpBuilder).read("output/R211.xml");
new VrpXMLReader(vrpBuilder).read("output/R211.xml");
/*
* Finally, the problem can be built. By default, transportCosts are crowFlyDistances (as usually used for vrp-instances).
*/
VehicleRoutingProblem vrp = vrpBuilder.build();
VehicleRoutingProblem vrp = vrpBuilder.build();
// new VrpXMLWriter(vrp).write("output/R211.xml");
// new Plotter(vrp).plot("output/solomon_R101.png", "R101");
@ -64,33 +64,33 @@ public class SolomonR101Example {
* The algorithm can be defined and configured in an xml-file.
*/
// VehicleRoutingAlgorithm vra = new SchrimpfFactory().createAlgorithm(vrp);
VehicleRoutingAlgorithm vra = VehicleRoutingAlgorithms.readAndCreateAlgorithm(vrp, "input/algorithmConfig.xml");
VehicleRoutingAlgorithm vra = VehicleRoutingAlgorithms.readAndCreateAlgorithm(vrp, "input/algorithmConfig.xml");
vra.setMaxIterations(20000);
// vra.setPrematureBreak(100);
vra.getAlgorithmListeners().addListener(new AlgorithmSearchProgressChartListener("output/sol_progress.png"));
vra.getAlgorithmListeners().addListener(new AlgorithmSearchProgressChartListener("output/sol_progress.png"));
/*
* Solve the problem.
*
*
*/
Collection<VehicleRoutingProblemSolution> solutions = vra.searchSolutions();
Collection<VehicleRoutingProblemSolution> solutions = vra.searchSolutions();
/*
* Retrieve best solution.
*/
VehicleRoutingProblemSolution solution = new SelectBest().selectSolution(solutions);
VehicleRoutingProblemSolution solution = new SelectBest().selectSolution(solutions);
/*
* print solution
*/
SolutionPrinter.print(vrp,solution, SolutionPrinter.Print.VERBOSE);
SolutionPrinter.print(vrp, solution, SolutionPrinter.Print.VERBOSE);
new GraphStreamViewer(vrp,solution).display();
new GraphStreamViewer(vrp, solution).display();
/*
* Plot solution.
*/
// new Plotter(vrp,solution).plot( "output/solomon_R101_solution.png","R101");
}
}
}

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.examples;
@ -34,77 +34,77 @@ import java.util.Collection;
public class SolomonWithRegretInsertionExample {
public static void main(String[] args) {
/*
public static void main(String[] args) {
/*
* some preparation - create output folder
*/
Examples.createOutputFolder();
Examples.createOutputFolder();
/*
* Build the problem.
*
*
* But define a problem-builder first.
*/
VehicleRoutingProblem.Builder vrpBuilder = VehicleRoutingProblem.Builder.newInstance();
VehicleRoutingProblem.Builder vrpBuilder = VehicleRoutingProblem.Builder.newInstance();
/*
* A solomonReader reads solomon-instance files, and stores the required information in the builder.
*/
new SolomonReader(vrpBuilder).read("input/C101_solomon.txt");
new SolomonReader(vrpBuilder).read("input/C101_solomon.txt");
/*
* Finally, the problem can be built. By default, transportCosts are crowFlyDistances (as usually used for vrp-instances).
*/
VehicleRoutingProblem vrp = vrpBuilder.build();
VehicleRoutingProblem vrp = vrpBuilder.build();
new Plotter(vrp).plot("output/solomon_C101.png", "C101");
new Plotter(vrp).plot("output/solomon_C101.png", "C101");
/*
* Define the required vehicle-routing algorithms to solve the above problem.
*
*
* The algorithm can be defined and configured in an xml-file.
*/
VehicleRoutingAlgorithm vra = VehicleRoutingAlgorithms.readAndCreateAlgorithm(vrp, "input/algorithmConfig_greedyWithRegret.xml");
VehicleRoutingAlgorithm vra = VehicleRoutingAlgorithms.readAndCreateAlgorithm(vrp, "input/algorithmConfig_greedyWithRegret.xml");
vra.setMaxIterations(2);
AlgorithmEventsRecorder eventsRecorder = new AlgorithmEventsRecorder(vrp,"output/events.dgs.gz");
eventsRecorder.setRecordingRange(0,50);
AlgorithmEventsRecorder eventsRecorder = new AlgorithmEventsRecorder(vrp, "output/events.dgs.gz");
eventsRecorder.setRecordingRange(0, 50);
vra.addListener(eventsRecorder);
/*
* Solve the problem.
*
*
*
*/
Collection<VehicleRoutingProblemSolution> solutions = vra.searchSolutions();
Collection<VehicleRoutingProblemSolution> solutions = vra.searchSolutions();
/*
* Retrieve best solution.
*/
VehicleRoutingProblemSolution solution = new SelectBest().selectSolution(solutions);
VehicleRoutingProblemSolution solution = new SelectBest().selectSolution(solutions);
/*
* print solution
*/
SolutionPrinter.print(vrp, solution, SolutionPrinter.Print.VERBOSE);
/*
* Plot solution.
*/
Plotter plotter = new Plotter(vrp,solution);
// plotter.setBoundingBox(30, 0, 50, 20);
plotter.plot("output/solomon_C101_solution.png", "C101");
SolutionPrinter.print(vrp, solution, SolutionPrinter.Print.VERBOSE);
new GraphStreamViewer(vrp,solution).labelWith(Label.ID).setRenderDelay(100).display();
/*
* Plot solution.
*/
Plotter plotter = new Plotter(vrp, solution);
// plotter.setBoundingBox(30, 0, 50, 20);
plotter.plot("output/solomon_C101_solution.png", "C101");
new GraphStreamViewer(vrp, solution).labelWith(Label.ID).setRenderDelay(100).display();
AlgorithmEventsViewer viewer = new AlgorithmEventsViewer();
viewer.setRuinDelay(16);
viewer.setRecreationDelay(8);
viewer.display("output/events.dgs.gz");
}
}
}

View file

@ -51,35 +51,34 @@ public class SolomonWithSkillsExample {
Vehicle solomonVehicle = vrp.getVehicles().iterator().next();
VehicleType newType = solomonVehicle.getType();
VehicleRoutingProblem.Builder skillProblemBuilder = VehicleRoutingProblem.Builder.newInstance();
for(int i=0;i<5;i++) {
for (int i = 0; i < 5; i++) {
VehicleImpl skill1Vehicle = VehicleImpl.Builder.newInstance("skill1_vehicle_" + i).addSkill("skill1")
.setStartLocation(Location.Builder.newInstance().setId(solomonVehicle.getStartLocation().getId()).setCoordinate(solomonVehicle.getStartLocation().getCoordinate()).build())
.setEarliestStart(solomonVehicle.getEarliestDeparture())
.setType(newType).build();
.setStartLocation(Location.Builder.newInstance().setId(solomonVehicle.getStartLocation().getId()).setCoordinate(solomonVehicle.getStartLocation().getCoordinate()).build())
.setEarliestStart(solomonVehicle.getEarliestDeparture())
.setType(newType).build();
VehicleImpl skill2Vehicle = VehicleImpl.Builder.newInstance("skill2_vehicle_" + i).addSkill("skill2")
.setStartLocation(Location.Builder.newInstance().setId(solomonVehicle.getStartLocation().getId())
.setCoordinate(solomonVehicle.getStartLocation().getCoordinate()).build())
.setEarliestStart(solomonVehicle.getEarliestDeparture())
.setType(newType).build();
.setStartLocation(Location.Builder.newInstance().setId(solomonVehicle.getStartLocation().getId())
.setCoordinate(solomonVehicle.getStartLocation().getCoordinate()).build())
.setEarliestStart(solomonVehicle.getEarliestDeparture())
.setType(newType).build();
skillProblemBuilder.addVehicle(skill1Vehicle).addVehicle(skill2Vehicle);
}
for(Job job : vrp.getJobs().values()){
for (Job job : vrp.getJobs().values()) {
Service service = (Service) job;
Service.Builder skillServiceBuilder;
if(service.getLocation().getCoordinate().getY()<50.){
if (service.getLocation().getCoordinate().getY() < 50.) {
skillServiceBuilder = Service.Builder.newInstance(service.getId() + "_skill2").setServiceTime(service.getServiceDuration())
.setLocation(Location.Builder.newInstance().setId(service.getLocation().getId())
.setCoordinate(service.getLocation().getCoordinate()).build()).setTimeWindow(service.getTimeWindow())
.addSizeDimension(0, service.getSize().get(0));
.setLocation(Location.Builder.newInstance().setId(service.getLocation().getId())
.setCoordinate(service.getLocation().getCoordinate()).build()).setTimeWindow(service.getTimeWindow())
.addSizeDimension(0, service.getSize().get(0));
skillServiceBuilder.addRequiredSkill("skill2");
}
else {
skillServiceBuilder = Service.Builder.newInstance(service.getId()+"_skill1").setServiceTime(service.getServiceDuration())
.setLocation(
Location.Builder.newInstance().setId(service.getLocation().getId())
.setCoordinate(service.getLocation().getCoordinate()).build()
).setTimeWindow(service.getTimeWindow())
.addSizeDimension(0,service.getSize().get(0));
} else {
skillServiceBuilder = Service.Builder.newInstance(service.getId() + "_skill1").setServiceTime(service.getServiceDuration())
.setLocation(
Location.Builder.newInstance().setId(service.getLocation().getId())
.setCoordinate(service.getLocation().getCoordinate()).build()
).setTimeWindow(service.getTimeWindow())
.addSizeDimension(0, service.getSize().get(0));
skillServiceBuilder.addRequiredSkill("skill1");
}
skillProblemBuilder.addJob(skillServiceBuilder.build());
@ -87,25 +86,25 @@ public class SolomonWithSkillsExample {
skillProblemBuilder.setFleetSize(VehicleRoutingProblem.FleetSize.FINITE);
VehicleRoutingProblem skillProblem = skillProblemBuilder.build();
VehicleRoutingAlgorithmBuilder vraBuilder = new VehicleRoutingAlgorithmBuilder(skillProblem,"input/algorithmConfig_solomon.xml");
VehicleRoutingAlgorithmBuilder vraBuilder = new VehicleRoutingAlgorithmBuilder(skillProblem, "input/algorithmConfig_solomon.xml");
vraBuilder.addCoreConstraints();
vraBuilder.addDefaultCostCalculators();
StateManager stateManager = new StateManager(skillProblem);
stateManager.updateSkillStates();
ConstraintManager constraintManager = new ConstraintManager(skillProblem,stateManager);
ConstraintManager constraintManager = new ConstraintManager(skillProblem, stateManager);
constraintManager.addSkillsConstraint();
VehicleRoutingAlgorithm vra = Jsprit.Builder.newInstance(skillProblem).setStateAndConstraintManager(stateManager,constraintManager).buildAlgorithm();
VehicleRoutingAlgorithm vra = Jsprit.Builder.newInstance(skillProblem).setStateAndConstraintManager(stateManager, constraintManager).buildAlgorithm();
Collection<VehicleRoutingProblemSolution> solutions = vra.searchSolutions();
VehicleRoutingProblemSolution solution = Solutions.bestOf(solutions);
SolutionPrinter.print(skillProblem, solution, SolutionPrinter.Print.VERBOSE);
new Plotter(skillProblem,solution).plot("output/skill_solution","solomon_with_skills");
new Plotter(skillProblem, solution).plot("output/skill_solution", "solomon_with_skills");
new VrpXMLWriter(skillProblem,solutions).write("output/solomon_with_skills");
new VrpXMLWriter(skillProblem, solutions).write("output/solomon_with_skills");
}
}

View file

@ -43,189 +43,189 @@ import jsprit.util.Examples;
import java.util.Collection;
public class TransportOfDisabledPeople {
static int WHEELCHAIRSPACE_INDEX = 0;
static int PASSENGERSEATS_INDEX = 1;
public static void main(String[] args) {
/*
static int WHEELCHAIRSPACE_INDEX = 0;
static int PASSENGERSEATS_INDEX = 1;
public static void main(String[] args) {
/*
* some preparation - create output folder
*/
Examples.createOutputFolder();
Examples.createOutputFolder();
/*
* get a vehicle type-builder and build a type with the typeId "vehicleType" and a capacity of 2
*/
VehicleTypeImpl.Builder wheelChairTypeBuilder = VehicleTypeImpl.Builder.newInstance("wheelChairBusType")
.addCapacityDimension(WHEELCHAIRSPACE_INDEX, 2) //can transport two people with wheelchair
.addCapacityDimension(PASSENGERSEATS_INDEX, 4); //and 4 without
VehicleType vehicleType_wheelchair = wheelChairTypeBuilder.build();
VehicleTypeImpl.Builder soleyPassengerTypeBuilder = VehicleTypeImpl.Builder.newInstance("passengerBusType")
.addCapacityDimension(PASSENGERSEATS_INDEX, 6); //and 4 without
VehicleType vehicleType_solelypassenger = soleyPassengerTypeBuilder.build();
VehicleTypeImpl.Builder wheelChairTypeBuilder = VehicleTypeImpl.Builder.newInstance("wheelChairBusType")
.addCapacityDimension(WHEELCHAIRSPACE_INDEX, 2) //can transport two people with wheelchair
.addCapacityDimension(PASSENGERSEATS_INDEX, 4); //and 4 without
VehicleType vehicleType_wheelchair = wheelChairTypeBuilder.build();
VehicleTypeImpl.Builder soleyPassengerTypeBuilder = VehicleTypeImpl.Builder.newInstance("passengerBusType")
.addCapacityDimension(PASSENGERSEATS_INDEX, 6); //and 4 without
VehicleType vehicleType_solelypassenger = soleyPassengerTypeBuilder.build();
/*
* define two vehicles and their locations.
*
*
* this example employs two vehicles. one that has to return to its start-location (vehicle1) and one that has a different
* end-location.
*
*
* play with these location to see which impact they have on customer-sequences.
*/
Builder vehicleBuilder1 = VehicleImpl.Builder.newInstance("wheelchair_bus");
vehicleBuilder1.setStartLocation(loc(Coordinate.newInstance(10, 10)));
vehicleBuilder1.setType(vehicleType_wheelchair);
VehicleImpl vehicle1 = vehicleBuilder1.build();
Builder vehicleBuilder1_2 = VehicleImpl.Builder.newInstance("wheelchair_bus_2");
vehicleBuilder1_2.setStartLocation(loc(Coordinate.newInstance(10, 10)));
vehicleBuilder1_2.setType(vehicleType_wheelchair);
VehicleImpl vehicle1_2 = vehicleBuilder1_2.build();
Builder vehicleBuilder2 = VehicleImpl.Builder.newInstance("passenger_bus");
vehicleBuilder2.setStartLocation(loc(Coordinate.newInstance(30, 30))).setEndLocation(loc(Coordinate.newInstance(30, 19)));
vehicleBuilder2.setType(vehicleType_solelypassenger);
VehicleImpl vehicle2 = vehicleBuilder2.build();
Builder vehicleBuilder2_2 = VehicleImpl.Builder.newInstance("passenger_bus_2");
vehicleBuilder2_2.setStartLocation(loc(Coordinate.newInstance(30, 30))).setEndLocation(loc(Coordinate.newInstance(30, 19)));
vehicleBuilder2_2.setType(vehicleType_solelypassenger);
VehicleImpl vehicle2_2 = vehicleBuilder2_2.build();
Builder vehicleBuilder1 = VehicleImpl.Builder.newInstance("wheelchair_bus");
vehicleBuilder1.setStartLocation(loc(Coordinate.newInstance(10, 10)));
vehicleBuilder1.setType(vehicleType_wheelchair);
VehicleImpl vehicle1 = vehicleBuilder1.build();
Builder vehicleBuilder1_2 = VehicleImpl.Builder.newInstance("wheelchair_bus_2");
vehicleBuilder1_2.setStartLocation(loc(Coordinate.newInstance(10, 10)));
vehicleBuilder1_2.setType(vehicleType_wheelchair);
VehicleImpl vehicle1_2 = vehicleBuilder1_2.build();
Builder vehicleBuilder2 = VehicleImpl.Builder.newInstance("passenger_bus");
vehicleBuilder2.setStartLocation(loc(Coordinate.newInstance(30, 30))).setEndLocation(loc(Coordinate.newInstance(30, 19)));
vehicleBuilder2.setType(vehicleType_solelypassenger);
VehicleImpl vehicle2 = vehicleBuilder2.build();
Builder vehicleBuilder2_2 = VehicleImpl.Builder.newInstance("passenger_bus_2");
vehicleBuilder2_2.setStartLocation(loc(Coordinate.newInstance(30, 30))).setEndLocation(loc(Coordinate.newInstance(30, 19)));
vehicleBuilder2_2.setType(vehicleType_solelypassenger);
VehicleImpl vehicle2_2 = vehicleBuilder2_2.build();
/*
* build shipments at the required locations, each with a capacity-demand of 1.
*
*
*/
Shipment shipment1 = Shipment.Builder.newInstance("wheelchair_1").addSizeDimension(WHEELCHAIRSPACE_INDEX, 1).setPickupLocation(loc(Coordinate.newInstance(5, 7))).setDeliveryLocation(loc(Coordinate.newInstance(6, 9))).build();
Shipment shipment2 = Shipment.Builder.newInstance("2").addSizeDimension(PASSENGERSEATS_INDEX, 1).setPickupLocation(loc(Coordinate.newInstance(5, 13))).setDeliveryLocation(loc(Coordinate.newInstance(6, 11))).build();
Shipment shipment3 = Shipment.Builder.newInstance("wheelchair_2").addSizeDimension(WHEELCHAIRSPACE_INDEX, 1).setPickupLocation(loc(Coordinate.newInstance(15, 7))).setDeliveryLocation(loc(Coordinate.newInstance(14, 9))).build();
Shipment shipment4 = Shipment.Builder.newInstance("4").addSizeDimension(PASSENGERSEATS_INDEX, 1).setPickupLocation(loc(Coordinate.newInstance(15, 13))).setDeliveryLocation(loc(Coordinate.newInstance(14, 11))).build();
Shipment shipment5 = Shipment.Builder.newInstance("wheelchair_3").addSizeDimension(WHEELCHAIRSPACE_INDEX, 1).setPickupLocation(loc(Coordinate.newInstance(25, 27))).setDeliveryLocation(loc(Coordinate.newInstance(26, 29))).build();
Shipment shipment6 = Shipment.Builder.newInstance("6").addSizeDimension(PASSENGERSEATS_INDEX, 1).setPickupLocation(loc(Coordinate.newInstance(25, 33))).setDeliveryLocation(loc(Coordinate.newInstance(26, 31))).build();
Shipment shipment7 = Shipment.Builder.newInstance("7").addSizeDimension(PASSENGERSEATS_INDEX, 1).setPickupLocation(loc(Coordinate.newInstance(35, 27))).setDeliveryLocation(loc(Coordinate.newInstance(34, 29))).build();
Shipment shipment8 = Shipment.Builder.newInstance("wheelchair_4").addSizeDimension(WHEELCHAIRSPACE_INDEX, 1).setPickupLocation(loc(Coordinate.newInstance(35, 33))).setDeliveryLocation(loc(Coordinate.newInstance(34, 31))).build();
Shipment shipment9 = Shipment.Builder.newInstance("9").addSizeDimension(PASSENGERSEATS_INDEX, 1).setPickupLocation(loc(Coordinate.newInstance(5, 27))).setDeliveryLocation(loc(Coordinate.newInstance(6, 29))).build();
Shipment shipment10 = Shipment.Builder.newInstance("wheelchair_5").addSizeDimension(WHEELCHAIRSPACE_INDEX, 1).setPickupLocation(loc(Coordinate.newInstance(5, 33))).setDeliveryLocation(loc(Coordinate.newInstance(6, 31))).build();
Shipment shipment11 = Shipment.Builder.newInstance("11").addSizeDimension(PASSENGERSEATS_INDEX, 1).setPickupLocation(loc(Coordinate.newInstance(15, 27))).setDeliveryLocation(loc(Coordinate.newInstance(14, 29))).build();
Shipment shipment12 = Shipment.Builder.newInstance("wheelchair_6").addSizeDimension(WHEELCHAIRSPACE_INDEX, 1).setPickupLocation(loc(Coordinate.newInstance(15, 33))).setDeliveryLocation(loc(Coordinate.newInstance(14, 31))).build();
Shipment shipment13 = Shipment.Builder.newInstance("13").addSizeDimension(PASSENGERSEATS_INDEX, 1).setPickupLocation(loc(Coordinate.newInstance(25, 7))).setDeliveryLocation(loc(Coordinate.newInstance(26, 9))).build();
Shipment shipment14 = Shipment.Builder.newInstance("wheelchair_7").addSizeDimension(WHEELCHAIRSPACE_INDEX, 1).setPickupLocation(loc(Coordinate.newInstance(25, 13))).setDeliveryLocation(loc(Coordinate.newInstance(26, 11))).build();
Shipment shipment15 = Shipment.Builder.newInstance("15").addSizeDimension(PASSENGERSEATS_INDEX, 1).setPickupLocation(loc(Coordinate.newInstance(35, 7))).setDeliveryLocation(loc(Coordinate.newInstance(34, 9))).build();
Shipment shipment16 = Shipment.Builder.newInstance("wheelchair_8").addSizeDimension(WHEELCHAIRSPACE_INDEX, 1).setPickupLocation(loc(Coordinate.newInstance(35, 13))).setDeliveryLocation(loc(Coordinate.newInstance(34, 11))).build();
Shipment shipment17 = Shipment.Builder.newInstance("17").addSizeDimension(PASSENGERSEATS_INDEX, 1).setPickupLocation(loc(Coordinate.newInstance(5, 14))).setDeliveryLocation(loc(Coordinate.newInstance(6, 16))).build();
Shipment shipment18 = Shipment.Builder.newInstance("wheelchair_9").addSizeDimension(WHEELCHAIRSPACE_INDEX, 1).setPickupLocation(loc(Coordinate.newInstance(5, 20))).setDeliveryLocation(loc(Coordinate.newInstance(6, 18))).build();
Shipment shipment19 = Shipment.Builder.newInstance("19").addSizeDimension(PASSENGERSEATS_INDEX, 1).setPickupLocation(loc(Coordinate.newInstance(15, 14))).setDeliveryLocation(loc(Coordinate.newInstance(14, 16))).build();
Shipment shipment20 = Shipment.Builder.newInstance("wheelchair_10").addSizeDimension(WHEELCHAIRSPACE_INDEX, 1).setPickupLocation(loc(Coordinate.newInstance(15, 20))).setDeliveryLocation(loc(Coordinate.newInstance(14, 18))).build();
VehicleRoutingProblem.Builder vrpBuilder = VehicleRoutingProblem.Builder.newInstance();
vrpBuilder.addVehicle(vehicle1).addVehicle(vehicle2).addVehicle(vehicle1_2).addVehicle(vehicle2_2);
vrpBuilder.addJob(shipment1).addJob(shipment2).addJob(shipment3).addJob(shipment4);
vrpBuilder.addJob(shipment5).addJob(shipment6).addJob(shipment7).addJob(shipment8);
vrpBuilder.addJob(shipment9).addJob(shipment10).addJob(shipment11).addJob(shipment12);
vrpBuilder.addJob(shipment13).addJob(shipment14).addJob(shipment15).addJob(shipment16);
vrpBuilder.addJob(shipment17).addJob(shipment18).addJob(shipment19).addJob(shipment20);
//you only have two vehicles
vrpBuilder.setFleetSize(FleetSize.FINITE);
Shipment shipment1 = Shipment.Builder.newInstance("wheelchair_1").addSizeDimension(WHEELCHAIRSPACE_INDEX, 1).setPickupLocation(loc(Coordinate.newInstance(5, 7))).setDeliveryLocation(loc(Coordinate.newInstance(6, 9))).build();
Shipment shipment2 = Shipment.Builder.newInstance("2").addSizeDimension(PASSENGERSEATS_INDEX, 1).setPickupLocation(loc(Coordinate.newInstance(5, 13))).setDeliveryLocation(loc(Coordinate.newInstance(6, 11))).build();
Shipment shipment3 = Shipment.Builder.newInstance("wheelchair_2").addSizeDimension(WHEELCHAIRSPACE_INDEX, 1).setPickupLocation(loc(Coordinate.newInstance(15, 7))).setDeliveryLocation(loc(Coordinate.newInstance(14, 9))).build();
Shipment shipment4 = Shipment.Builder.newInstance("4").addSizeDimension(PASSENGERSEATS_INDEX, 1).setPickupLocation(loc(Coordinate.newInstance(15, 13))).setDeliveryLocation(loc(Coordinate.newInstance(14, 11))).build();
Shipment shipment5 = Shipment.Builder.newInstance("wheelchair_3").addSizeDimension(WHEELCHAIRSPACE_INDEX, 1).setPickupLocation(loc(Coordinate.newInstance(25, 27))).setDeliveryLocation(loc(Coordinate.newInstance(26, 29))).build();
Shipment shipment6 = Shipment.Builder.newInstance("6").addSizeDimension(PASSENGERSEATS_INDEX, 1).setPickupLocation(loc(Coordinate.newInstance(25, 33))).setDeliveryLocation(loc(Coordinate.newInstance(26, 31))).build();
Shipment shipment7 = Shipment.Builder.newInstance("7").addSizeDimension(PASSENGERSEATS_INDEX, 1).setPickupLocation(loc(Coordinate.newInstance(35, 27))).setDeliveryLocation(loc(Coordinate.newInstance(34, 29))).build();
Shipment shipment8 = Shipment.Builder.newInstance("wheelchair_4").addSizeDimension(WHEELCHAIRSPACE_INDEX, 1).setPickupLocation(loc(Coordinate.newInstance(35, 33))).setDeliveryLocation(loc(Coordinate.newInstance(34, 31))).build();
Shipment shipment9 = Shipment.Builder.newInstance("9").addSizeDimension(PASSENGERSEATS_INDEX, 1).setPickupLocation(loc(Coordinate.newInstance(5, 27))).setDeliveryLocation(loc(Coordinate.newInstance(6, 29))).build();
Shipment shipment10 = Shipment.Builder.newInstance("wheelchair_5").addSizeDimension(WHEELCHAIRSPACE_INDEX, 1).setPickupLocation(loc(Coordinate.newInstance(5, 33))).setDeliveryLocation(loc(Coordinate.newInstance(6, 31))).build();
Shipment shipment11 = Shipment.Builder.newInstance("11").addSizeDimension(PASSENGERSEATS_INDEX, 1).setPickupLocation(loc(Coordinate.newInstance(15, 27))).setDeliveryLocation(loc(Coordinate.newInstance(14, 29))).build();
Shipment shipment12 = Shipment.Builder.newInstance("wheelchair_6").addSizeDimension(WHEELCHAIRSPACE_INDEX, 1).setPickupLocation(loc(Coordinate.newInstance(15, 33))).setDeliveryLocation(loc(Coordinate.newInstance(14, 31))).build();
Shipment shipment13 = Shipment.Builder.newInstance("13").addSizeDimension(PASSENGERSEATS_INDEX, 1).setPickupLocation(loc(Coordinate.newInstance(25, 7))).setDeliveryLocation(loc(Coordinate.newInstance(26, 9))).build();
Shipment shipment14 = Shipment.Builder.newInstance("wheelchair_7").addSizeDimension(WHEELCHAIRSPACE_INDEX, 1).setPickupLocation(loc(Coordinate.newInstance(25, 13))).setDeliveryLocation(loc(Coordinate.newInstance(26, 11))).build();
Shipment shipment15 = Shipment.Builder.newInstance("15").addSizeDimension(PASSENGERSEATS_INDEX, 1).setPickupLocation(loc(Coordinate.newInstance(35, 7))).setDeliveryLocation(loc(Coordinate.newInstance(34, 9))).build();
Shipment shipment16 = Shipment.Builder.newInstance("wheelchair_8").addSizeDimension(WHEELCHAIRSPACE_INDEX, 1).setPickupLocation(loc(Coordinate.newInstance(35, 13))).setDeliveryLocation(loc(Coordinate.newInstance(34, 11))).build();
Shipment shipment17 = Shipment.Builder.newInstance("17").addSizeDimension(PASSENGERSEATS_INDEX, 1).setPickupLocation(loc(Coordinate.newInstance(5, 14))).setDeliveryLocation(loc(Coordinate.newInstance(6, 16))).build();
Shipment shipment18 = Shipment.Builder.newInstance("wheelchair_9").addSizeDimension(WHEELCHAIRSPACE_INDEX, 1).setPickupLocation(loc(Coordinate.newInstance(5, 20))).setDeliveryLocation(loc(Coordinate.newInstance(6, 18))).build();
Shipment shipment19 = Shipment.Builder.newInstance("19").addSizeDimension(PASSENGERSEATS_INDEX, 1).setPickupLocation(loc(Coordinate.newInstance(15, 14))).setDeliveryLocation(loc(Coordinate.newInstance(14, 16))).build();
Shipment shipment20 = Shipment.Builder.newInstance("wheelchair_10").addSizeDimension(WHEELCHAIRSPACE_INDEX, 1).setPickupLocation(loc(Coordinate.newInstance(15, 20))).setDeliveryLocation(loc(Coordinate.newInstance(14, 18))).build();
VehicleRoutingProblem.Builder vrpBuilder = VehicleRoutingProblem.Builder.newInstance();
vrpBuilder.addVehicle(vehicle1).addVehicle(vehicle2).addVehicle(vehicle1_2).addVehicle(vehicle2_2);
vrpBuilder.addJob(shipment1).addJob(shipment2).addJob(shipment3).addJob(shipment4);
vrpBuilder.addJob(shipment5).addJob(shipment6).addJob(shipment7).addJob(shipment8);
vrpBuilder.addJob(shipment9).addJob(shipment10).addJob(shipment11).addJob(shipment12);
vrpBuilder.addJob(shipment13).addJob(shipment14).addJob(shipment15).addJob(shipment16);
vrpBuilder.addJob(shipment17).addJob(shipment18).addJob(shipment19).addJob(shipment20);
//you only have two vehicles
vrpBuilder.setFleetSize(FleetSize.FINITE);
/*
*
*
* wheelchair-bus can only pickup passenger where x<15
*/
HardRouteConstraint wheelchair_bus_passenger_pickup_constraint = new HardRouteConstraint() {
@Override
public boolean fulfilled(JobInsertionContext insertionContext) {
Shipment shipment2insert = ((Shipment)insertionContext.getJob());
if(insertionContext.getNewVehicle().getId().equals("wheelchair_bus")){
if(shipment2insert.getSize().get(PASSENGERSEATS_INDEX)>0){
if(shipment2insert.getPickupLocation().getCoordinate().getX() > 15. || shipment2insert.getDeliveryLocation().getCoordinate().getX() > 15.){
return false;
}
}
}
return true;
}
};
HardRouteConstraint wheelchair_bus_passenger_pickup_constraint = new HardRouteConstraint() {
//build the problem
VehicleRoutingProblem problem = vrpBuilder.build();
@Override
public boolean fulfilled(JobInsertionContext insertionContext) {
Shipment shipment2insert = ((Shipment) insertionContext.getJob());
if (insertionContext.getNewVehicle().getId().equals("wheelchair_bus")) {
if (shipment2insert.getSize().get(PASSENGERSEATS_INDEX) > 0) {
if (shipment2insert.getPickupLocation().getCoordinate().getX() > 15. || shipment2insert.getDeliveryLocation().getCoordinate().getX() > 15.) {
return false;
}
}
}
return true;
}
};
//build the problem
VehicleRoutingProblem problem = vrpBuilder.build();
StateManager stateManager = new StateManager(problem);
ConstraintManager constraintManager = new ConstraintManager(problem, stateManager);
constraintManager.addConstraint(wheelchair_bus_passenger_pickup_constraint);
StateManager stateManager = new StateManager(problem);
ConstraintManager constraintManager = new ConstraintManager(problem, stateManager);
constraintManager.addConstraint(wheelchair_bus_passenger_pickup_constraint);
/*
* get a sample algorithm.
*
* get a sample algorithm.
*
* Note that you need to make sure to prohibit vehicle-switching by adding the insertion-tag <vehicleSwitchAllowed>false</vehicleSwitchAllowed>.
* This way you make sure that no vehicle can take over a route that is employed by another. Allowing this might make sense when dealing with
* a heterogeneous fleet and you want to employ a bigger vehicle on a still existing route. However, allowing it makes constraint-checking
* a heterogeneous fleet and you want to employ a bigger vehicle on a still existing route. However, allowing it makes constraint-checking
* bit more complicated and you cannot just add the above hard-constraint. Latter will be covered in another example.
*
*
*/
VehicleRoutingAlgorithmBuilder algorithmBuilder = new VehicleRoutingAlgorithmBuilder(problem, "input/algorithmConfig_noVehicleSwitch.xml");
algorithmBuilder.setStateAndConstraintManager(stateManager, constraintManager);
algorithmBuilder.addCoreConstraints();
algorithmBuilder.addDefaultCostCalculators();
VehicleRoutingAlgorithm algorithm = algorithmBuilder.build();
algorithm.setPrematureAlgorithmTermination(new IterationWithoutImprovementTermination(100));
VehicleRoutingAlgorithmBuilder algorithmBuilder = new VehicleRoutingAlgorithmBuilder(problem, "input/algorithmConfig_noVehicleSwitch.xml");
algorithmBuilder.setStateAndConstraintManager(stateManager, constraintManager);
algorithmBuilder.addCoreConstraints();
algorithmBuilder.addDefaultCostCalculators();
VehicleRoutingAlgorithm algorithm = algorithmBuilder.build();
algorithm.setPrematureAlgorithmTermination(new IterationWithoutImprovementTermination(100));
/*
* and search a solution
*/
Collection<VehicleRoutingProblemSolution> solutions = algorithm.searchSolutions();
Collection<VehicleRoutingProblemSolution> solutions = algorithm.searchSolutions();
/*
* get the best
* get the best
*/
VehicleRoutingProblemSolution bestSolution = Solutions.bestOf(solutions);
VehicleRoutingProblemSolution bestSolution = Solutions.bestOf(solutions);
/*
* write out problem and solution to xml-file
*/
// new VrpXMLWriter(problem, solutions).write("output/shipment-problem-with-solution.xml");
/*
* print nRoutes and totalCosts of bestSolution
*/
SolutionPrinter.print(problem, bestSolution, SolutionPrinter.Print.VERBOSE);
SolutionPrinter.print(problem, bestSolution, SolutionPrinter.Print.VERBOSE);
/*
* plot problem without solution
*/
Plotter problemPlotter = new Plotter(problem);
problemPlotter.plotShipments(true);
problemPlotter.setLabel(jsprit.analysis.toolbox.Plotter.Label.SIZE);
problemPlotter.plot("output/transportOfDisabledPeopleExample_problem.png", "disabled people tp");
Plotter problemPlotter = new Plotter(problem);
problemPlotter.plotShipments(true);
problemPlotter.setLabel(jsprit.analysis.toolbox.Plotter.Label.SIZE);
problemPlotter.plot("output/transportOfDisabledPeopleExample_problem.png", "disabled people tp");
Plotter solutionPlotter = new Plotter(problem,Solutions.bestOf(solutions));
Plotter solutionPlotter = new Plotter(problem, Solutions.bestOf(solutions));
solutionPlotter.plotShipments(true);
solutionPlotter.setLabel(jsprit.analysis.toolbox.Plotter.Label.SIZE);
solutionPlotter.plot("output/transportOfDisabledPeopleExample_solution.png", "disabled people tp");
new GraphStreamViewer(problem).labelWith(Label.ID).setRenderDelay(100).setRenderShipments(true).display();
new GraphStreamViewer(problem,Solutions.bestOf(solutions)).labelWith(Label.ACTIVITY).setRenderDelay(100).setRenderShipments(true).display();
}
new GraphStreamViewer(problem).labelWith(Label.ID).setRenderDelay(100).setRenderShipments(true).display();
private static Location loc(Coordinate coordinate) {
return Location.Builder.newInstance().setCoordinate(coordinate).build();
}
new GraphStreamViewer(problem, Solutions.bestOf(solutions)).labelWith(Label.ACTIVITY).setRenderDelay(100).setRenderShipments(true).display();
}
private static Location loc(Coordinate coordinate) {
return Location.Builder.newInstance().setCoordinate(coordinate).build();
}
}

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.examples;
@ -34,75 +34,75 @@ import java.util.Collection;
public class VRPWithBackhaulsExample {
public static void main(String[] args) {
public static void main(String[] args) {
/*
* some preparation - create output folder
*/
Examples.createOutputFolder();
Examples.createOutputFolder();
/*
* Build the problem.
*
*
* But define a problem-builder first.
*/
VehicleRoutingProblem.Builder vrpBuilder = VehicleRoutingProblem.Builder.newInstance();
VehicleRoutingProblem.Builder vrpBuilder = VehicleRoutingProblem.Builder.newInstance();
/*
* A solomonReader reads solomon-instance files, and stores the required information in the builder.
*/
new VrpXMLReader(vrpBuilder).read("input/pickups_and_deliveries_solomon_r101.xml");
new VrpXMLReader(vrpBuilder).read("input/pickups_and_deliveries_solomon_r101.xml");
/*
* Finally, the problem can be built. By default, transportCosts are crowFlyDistances (as usually used for vrp-instances).
*/
//
VehicleRoutingProblem vrp = vrpBuilder.build();
VehicleRoutingProblem vrp = vrpBuilder.build();
// SolutionPlotter.plotVrpAsPNG(vrp, "output/vrpwbh_solomon_r101.png", "pd_r101");
/*
* Define the required vehicle-routing algorithms to solve the above problem.
*
*
* The algorithm can be defined and configured in an xml-file.
*/
VehicleRoutingAlgorithmBuilder vraBuilder = new VehicleRoutingAlgorithmBuilder(vrp,"input/algorithmConfig_solomon.xml");
VehicleRoutingAlgorithmBuilder vraBuilder = new VehicleRoutingAlgorithmBuilder(vrp, "input/algorithmConfig_solomon.xml");
vraBuilder.addCoreConstraints();
vraBuilder.addDefaultCostCalculators();
StateManager stateManager = new StateManager(vrp);
ConstraintManager constraintManager = new ConstraintManager(vrp,stateManager);
ConstraintManager constraintManager = new ConstraintManager(vrp, stateManager);
constraintManager.addConstraint(new ServiceDeliveriesFirstConstraint(), ConstraintManager.Priority.CRITICAL);
vraBuilder.setStateAndConstraintManager(stateManager,constraintManager);
vraBuilder.setStateAndConstraintManager(stateManager, constraintManager);
VehicleRoutingAlgorithm vra = vraBuilder.build();
vra.getAlgorithmListeners().addListener(new AlgorithmSearchProgressChartListener("output/sol_progress.png"));
/*
* Solve the problem.
*
*
*
*/
Collection<VehicleRoutingProblemSolution> solutions = vra.searchSolutions();
Collection<VehicleRoutingProblemSolution> solutions = vra.searchSolutions();
/*
* Retrieve best solution.
*/
VehicleRoutingProblemSolution solution = new SelectBest().selectSolution(solutions);
VehicleRoutingProblemSolution solution = new SelectBest().selectSolution(solutions);
/*
* print solution
*/
SolutionPrinter.print(vrp, solution, SolutionPrinter.Print.VERBOSE);
SolutionPrinter.print(vrp, solution, SolutionPrinter.Print.VERBOSE);
/*
* Plot solution.
* Plot solution.
*/
// Plotter plotter = new Plotter(vrp, solution);
// plotter.setLabel(Label.SIZE);
// plotter.setShowFirstActivity(true);
// plotter.plot("output/vrpwbh_solomon_r101_solution.png","vrpwbh_r101");
new GraphStreamViewer(vrp, solution).setRenderDelay(100).setEnableAutoLayout(false).display();
}
new GraphStreamViewer(vrp, solution).setRenderDelay(100).setEnableAutoLayout(false).display();
}
}

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.examples;
@ -39,38 +39,38 @@ import java.util.Collection;
public class VRPWithBackhaulsExample2 {
public static void main(String[] args) {
public static void main(String[] args) {
/*
* some preparation - create output folder
*/
Examples.createOutputFolder();
Examples.createOutputFolder();
/*
* Build the problem.
*
*
* But define a problem-builder first.
*/
VehicleRoutingProblem.Builder vrpBuilder = VehicleRoutingProblem.Builder.newInstance();
VehicleRoutingProblem.Builder vrpBuilder = VehicleRoutingProblem.Builder.newInstance();
/*
* A solomonReader reads solomon-instance files, and stores the required information in the builder.
*/
new VrpXMLReader(vrpBuilder).read("input/pd_christophides_vrpnc1_vcap50.xml");
new VrpXMLReader(vrpBuilder).read("input/pd_christophides_vrpnc1_vcap50.xml");
/*
* Finally, the problem can be built. By default, transportCosts are crowFlyDistances (as usually used for vrp-instances).
*/
final VehicleRoutingProblem vrp = vrpBuilder.build();
final VehicleRoutingProblem vrp = vrpBuilder.build();
// new Plotter(vrp).plot("output/vrpwbh_christophides_vrpnc1.png", "pd_vrpnc1");
/*
* Define the required vehicle-routing algorithms to solve the above problem.
*
*
* The algorithm can be defined and configured in an xml-file.
*/
// VehicleRoutingAlgorithm vra = VehicleRoutingAlgorithms.readAndCreateAlgorithm(vrp, "input/algorithmConfig_solomon.xml");
@ -80,7 +80,7 @@ public class VRPWithBackhaulsExample2 {
// vraBuilder.addCoreConstraints();
StateManager stateManager = new StateManager(vrp);
ConstraintManager constraintManager = new ConstraintManager(vrp,stateManager);
ConstraintManager constraintManager = new ConstraintManager(vrp, stateManager);
constraintManager.addConstraint(new ServiceDeliveriesFirstConstraint(), ConstraintManager.Priority.CRITICAL);
// vraBuilder.setStateAndConstraintManager(stateManager,constraintManager);
@ -89,9 +89,9 @@ public class VRPWithBackhaulsExample2 {
VehicleRoutingAlgorithm vra = Jsprit.Builder.newInstance(vrp)
.setStateAndConstraintManager(stateManager, constraintManager)
.setProperty(Jsprit.Parameter.FIXED_COST_PARAM.toString(),"0.")
.buildAlgorithm();
.setStateAndConstraintManager(stateManager, constraintManager)
.setProperty(Jsprit.Parameter.FIXED_COST_PARAM.toString(), "0.")
.buildAlgorithm();
vra.setMaxIterations(2000);
vra.addListener(new AlgorithmSearchProgressChartListener("output/search"));
@ -99,39 +99,39 @@ public class VRPWithBackhaulsExample2 {
/*
* Solve the problem.
*
*
*
*/
Collection<VehicleRoutingProblemSolution> solutions = vra.searchSolutions();
Collection<VehicleRoutingProblemSolution> solutions = vra.searchSolutions();
/*
* Retrieve best solution.
*/
VehicleRoutingProblemSolution solution = new SelectBest().selectSolution(solutions);
VehicleRoutingProblemSolution solution = new SelectBest().selectSolution(solutions);
/*
* print solution
*/
SolutionPrinter.print(solution);
SolutionPrinter.print(solution);
/*
* Plot solution.
* Plot solution.
*/
// SolutionPlotter.plotSolutionAsPNG(vrp, solution, "output/pd_solomon_r101_solution.png","pd_r101");
Plotter plotter = new Plotter(vrp, solution);
Plotter plotter = new Plotter(vrp, solution);
// plotter.setLabel(Plotter.Label.SIZE);
plotter.plot("output/vrpwbh_christophides_vrpnc1_solution.png","vrpwbh_vrpnc1");
plotter.plot("output/vrpwbh_christophides_vrpnc1_solution.png", "vrpwbh_vrpnc1");
SolutionAnalyser analyser = new SolutionAnalyser(vrp, solution, new SolutionAnalyser.DistanceCalculator() {
@Override
public double getDistance(Location from, Location to) {
return vrp.getTransportCosts().getTransportCost(from, to,0.,null,null);
return vrp.getTransportCosts().getTransportCost(from, to, 0., null, null);
}
});
for(VehicleRoute route : solution.getRoutes()){
for (VehicleRoute route : solution.getRoutes()) {
System.out.println("------");
System.out.println("vehicleId: " + route.getVehicle().getId());
System.out.println("vehicleCapacity: " + route.getVehicle().getType().getCapacityDimensions() + " maxLoad: " + analyser.getMaxLoad(route));
@ -150,27 +150,27 @@ public class VRPWithBackhaulsExample2 {
System.out.println("timeWindowViolationOnRoute: " + analyser.getTimeWindowViolation(route));
System.out.println("skillConstraintViolatedOnRoute: " + analyser.hasSkillConstraintViolation(route));
System.out.println("dist@" + route.getStart().getLocation().getId() + ": " + analyser.getDistanceAtActivity(route.getStart(),route));
System.out.println("timeWindowViolation@" + route.getStart().getLocation().getId() + ": " + analyser.getTimeWindowViolationAtActivity(route.getStart(), route));
for(TourActivity act : route.getActivities()){
System.out.println("dist@" + route.getStart().getLocation().getId() + ": " + analyser.getDistanceAtActivity(route.getStart(), route));
System.out.println("timeWindowViolation@" + route.getStart().getLocation().getId() + ": " + analyser.getTimeWindowViolationAtActivity(route.getStart(), route));
for (TourActivity act : route.getActivities()) {
System.out.println("--");
System.out.println("actType: " + act.getName() + " demand: " + act.getSize());
System.out.println("dist@" + act.getLocation().getId() + ": " + analyser.getDistanceAtActivity(act,route));
System.out.println("load(before)@" + act.getLocation().getId() + ": " + analyser.getLoadJustBeforeActivity(act,route));
System.out.println("dist@" + act.getLocation().getId() + ": " + analyser.getDistanceAtActivity(act, route));
System.out.println("load(before)@" + act.getLocation().getId() + ": " + analyser.getLoadJustBeforeActivity(act, route));
System.out.println("load(after)@" + act.getLocation().getId() + ": " + analyser.getLoadRightAfterActivity(act, route));
System.out.println("transportCosts@" + act.getLocation().getId() + ": " + analyser.getVariableTransportCostsAtActivity(act,route));
System.out.println("capViolation(after)@" + act.getLocation().getId() + ": " + analyser.getCapacityViolationAfterActivity(act,route));
System.out.println("timeWindowViolation@" + act.getLocation().getId() + ": " + analyser.getTimeWindowViolationAtActivity(act,route));
System.out.println("transportCosts@" + act.getLocation().getId() + ": " + analyser.getVariableTransportCostsAtActivity(act, route));
System.out.println("capViolation(after)@" + act.getLocation().getId() + ": " + analyser.getCapacityViolationAfterActivity(act, route));
System.out.println("timeWindowViolation@" + act.getLocation().getId() + ": " + analyser.getTimeWindowViolationAtActivity(act, route));
System.out.println("skillConstraintViolated@" + act.getLocation().getId() + ": " + analyser.hasSkillConstraintViolationAtActivity(act, route));
}
System.out.println("--");
System.out.println("dist@" + route.getEnd().getLocation().getId() + ": " + analyser.getDistanceAtActivity(route.getEnd(),route));
System.out.println("timeWindowViolation@" + route.getEnd().getLocation().getId() + ": " + analyser.getTimeWindowViolationAtActivity(route.getEnd(),route));
System.out.println("dist@" + route.getEnd().getLocation().getId() + ": " + analyser.getDistanceAtActivity(route.getEnd(), route));
System.out.println("timeWindowViolation@" + route.getEnd().getLocation().getId() + ": " + analyser.getTimeWindowViolationAtActivity(route.getEnd(), route));
}
System.out.println("-----");
System.out.println("aggreate solution stats");
System.out.println("total freight moved: " + Capacity.addup(analyser.getLoadAtBeginning(),analyser.getLoadPickedUp()));
System.out.println("total freight moved: " + Capacity.addup(analyser.getLoadAtBeginning(), analyser.getLoadPickedUp()));
System.out.println("total no. picks at beginning: " + analyser.getNumberOfPickupsAtBeginning());
System.out.println("total no. picks on routes: " + analyser.getNumberOfPickups());
System.out.println("total picked load at beginnnig: " + analyser.getLoadAtBeginning());

View file

@ -1,18 +1,18 @@
/*******************************************************************************
* Copyright (c) 2014 Stefan Schroeder.
*
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* License as published by the Free Software Foundation; either
* version 3.0 of the License, or (at your option) any later version.
*
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
*
* 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/>.
*
*
* Contributors:
* Stefan Schroeder - initial API and implementation
******************************************************************************/
@ -21,15 +21,15 @@ package jsprit.util;
import java.io.File;
public class Examples {
public static void createOutputFolder(){
File dir = new File("output");
// if the directory does not exist, create it
if (!dir.exists()){
System.out.println("creating directory ./output");
boolean result = dir.mkdir();
if(result) System.out.println("./output created");
}
}
public static void createOutputFolder() {
File dir = new File("output");
// if the directory does not exist, create it
if (!dir.exists()) {
System.out.println("creating directory ./output");
boolean result = dir.mkdir();
if (result) System.out.println("./output created");
}
}
}