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

prepare release 1.5

This commit is contained in:
oblonski 2014-12-12 10:55:56 +01:00
parent 9938a6a123
commit 1458b03be7
13 changed files with 253 additions and 1502 deletions

View file

@ -14,196 +14,206 @@
* 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;
import jsprit.core.algorithm.*;
import jsprit.analysis.toolbox.AlgorithmEventsRecorder;
import jsprit.analysis.toolbox.AlgorithmEventsViewer;
import jsprit.core.algorithm.PrettyAlgorithmBuilder;
import jsprit.core.algorithm.SearchStrategy;
import jsprit.core.algorithm.VehicleRoutingAlgorithm;
import jsprit.core.algorithm.acceptor.GreedyAcceptance;
import jsprit.core.algorithm.listener.IterationStartsListener;
import jsprit.core.algorithm.module.RuinAndRecreateModule;
import jsprit.core.algorithm.recreate.BestInsertionBuilder;
import jsprit.core.algorithm.recreate.InsertionStrategy;
import jsprit.core.algorithm.recreate.*;
import jsprit.core.algorithm.ruin.RadialRuinStrategyFactory;
import jsprit.core.algorithm.ruin.RandomRuinStrategyFactory;
import jsprit.core.algorithm.ruin.RuinStrategy;
import jsprit.core.algorithm.ruin.distance.AvgServiceAndShipmentDistance;
import jsprit.core.algorithm.selector.SelectBest;
import jsprit.core.algorithm.state.StateManager;
import jsprit.core.algorithm.state.UpdateVariableCosts;
import jsprit.core.algorithm.termination.IterationWithoutImprovementTermination;
import jsprit.core.analysis.SolutionAnalyser;
import jsprit.core.problem.VehicleRoutingProblem;
import jsprit.core.problem.constraint.ConstraintManager;
import jsprit.core.problem.job.Job;
import jsprit.core.problem.solution.SolutionCostCalculator;
import jsprit.core.problem.solution.VehicleRoutingProblemSolution;
import jsprit.core.problem.vehicle.InfiniteFleetManagerFactory;
import jsprit.core.problem.solution.route.VehicleRoute;
import jsprit.core.problem.vehicle.FiniteFleetManagerFactory;
import jsprit.core.problem.vehicle.VehicleFleetManager;
import jsprit.core.reporting.SolutionPrinter;
import jsprit.core.util.Solutions;
import jsprit.instance.reader.SolomonReader;
import jsprit.instance.reader.CordeauReader;
import jsprit.util.Examples;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
public class BuildAlgorithmFromScratch {
public static void main(String[] args) {
/*
* some preparation - create output folder
*/
Examples.createOutputFolder();
/*
* Build the problem.
*
* But define a problem-builder first.
*/
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");
/*
* Finally, the problem can be built. By default, transportCosts are crowFlyDistances (as usually used for vrp-instances).
*/
VehicleRoutingProblem vrp = vrpBuilder.build();
/*
* Build algorithm
*/
VehicleRoutingAlgorithm vra = buildAlgorithmFromScratch(vrp);
/*
* search solution
*/
Collection<VehicleRoutingProblemSolution> solutions = vra.searchSolutions();
/*
* print result
*/
SolutionPrinter.print(Solutions.bestOf(solutions));
public static class MyBestStrategy extends AbstractInsertionStrategy {
}
private JobInsertionCostsCalculatorLight insertionCalculator;
public MyBestStrategy(VehicleRoutingProblem vrp, VehicleFleetManager fleetManager, StateManager stateManager, ConstraintManager constraintManager) {
super(vrp);
insertionCalculator = JobInsertionCostsCalculatorLightFactory.createStandardCalculator(vrp, fleetManager, stateManager, constraintManager);
}
@Override
public Collection<Job> insertUnassignedJobs(Collection<VehicleRoute> vehicleRoutes, Collection<Job> unassignedJobs) {
List<Job> badJobs = new ArrayList<Job>();
List<Job> unassigned = new ArrayList<Job>(unassignedJobs);
Collections.shuffle(unassigned, random);
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()){
bestInsertionData = insertionData;
bestRoute = r;
}
}
//try whole new route
VehicleRoute empty = VehicleRoute.emptyRoute();
InsertionData insertionData = insertionCalculator.getInsertionData(j, empty, bestInsertionData.getInsertionCost());
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 badJobs.add(j);
}
}
return badJobs;
}
}
public static void main(String[] args) {
Examples.createOutputFolder();
VehicleRoutingProblem.Builder vrpBuilder = VehicleRoutingProblem.Builder.newInstance();
new CordeauReader(vrpBuilder).read("input/p08");
final VehicleRoutingProblem vrp = vrpBuilder.build();
VehicleRoutingAlgorithm vra = createAlgorithm(vrp);
vra.setMaxIterations(100);
AlgorithmEventsRecorder eventsRecorder = new AlgorithmEventsRecorder(vrp,"output/events.dgs.gz");
eventsRecorder.setRecordingRange(90,100);
vra.addListener(eventsRecorder);
VehicleRoutingProblemSolution solution = Solutions.bestOf(vra.searchSolutions());
SolutionPrinter.print(vrp, solution, SolutionPrinter.Print.VERBOSE);
AlgorithmEventsViewer viewer = new AlgorithmEventsViewer();
viewer.setRuinDelay(3);
viewer.setRecreationDelay(1);
viewer.display("output/events.dgs.gz");
}
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);
/*
* insertion strategies
*/
//my custom best insertion
MyBestStrategy best = new MyBestStrategy(vrp,fleetManager,stateManager,constraintManager);
//regret insertion
InsertionBuilder iBuilder = new InsertionBuilder(vrp, fleetManager, stateManager, constraintManager);
iBuilder.setInsertionStrategy(InsertionBuilder.Strategy.REGRET);
RegretInsertion regret = (RegretInsertion) iBuilder.build();
RegretInsertion.DefaultScorer scoringFunction = new RegretInsertion.DefaultScorer(vrp);
scoringFunction.setDepotDistanceParam(0.2);
scoringFunction.setTimeWindowParam(-.2);
regret.setScoringFunction(scoringFunction);
private static VehicleRoutingAlgorithm buildAlgorithmFromScratch(VehicleRoutingProblem vrp) {
/*
* manages route and activity states.
* ruin strategies
*/
StateManager stateManager = new StateManager(vrp);
RuinStrategy randomRuin = new RandomRuinStrategyFactory(0.5).createStrategy(vrp);
RuinStrategy radialRuin = new RadialRuinStrategyFactory(0.3, new AvgServiceAndShipmentDistance(vrp.getTransportCosts())).createStrategy(vrp);
/*
* tells stateManager to update load states
* objective function
*/
stateManager.updateLoadStates();
/*
* tells stateManager to update time-window states
*/
stateManager.updateTimeWindowStates();
/*
* stateManager.addStateUpdater(updater);
* lets you register your own stateUpdater
*/
/*
* updates variable costs once a vehicleRoute has changed (by removing or adding a customer)
*/
stateManager.addStateUpdater(new UpdateVariableCosts(vrp.getActivityCosts(), vrp.getTransportCosts(), stateManager));
/*
* constructs a constraintManager that manages the various hardConstraints (and soon also softConstraints)
*/
ConstraintManager constraintManager = new ConstraintManager(vrp,stateManager);
/*
* tells constraintManager to add timeWindowConstraints
*/
constraintManager.addTimeWindowConstraint();
/*
* tells constraintManager to add loadConstraints
*/
constraintManager.addLoadConstraint();
/*
* add an arbitrary number of hardConstraints by
* constraintManager.addConstraint(...)
*/
/*
* define a fleetManager, here infinite vehicles can be used
*/
VehicleFleetManager fleetManager = new InfiniteFleetManagerFactory(vrp.getVehicles()).createFleetManager();
/*
* define ruin-and-recreate strategies
*
*/
/*
* first, define an insertion-strategy, i.e. bestInsertion
*/
BestInsertionBuilder iBuilder = new BestInsertionBuilder(vrp, fleetManager, stateManager, constraintManager);
/*
* no need to set further options
*/
InsertionStrategy iStrategy = iBuilder.build();
/*
* second, define random-ruin that ruins 50-percent of the selected solution
*/
RuinStrategy randomRuin = new RandomRuinStrategyFactory(0.5).createStrategy(vrp);
/*
* third, define radial-ruin that ruins 30-percent of the selected solution
* the second para defines the distance between two jobs.
*/
RuinStrategy radialRuin = new RadialRuinStrategyFactory(0.3, new AvgServiceAndShipmentDistance(vrp.getTransportCosts())).createStrategy(vrp);
/*
* now define a strategy
*/
/*
* but before define how a generated solution is evaluated
* here: the VariablePlusFixed.... comes out of the box and it does what its name suggests
*/
SolutionCostCalculator solutionCostCalculator = new VariablePlusFixedSolutionCostCalculatorFactory(stateManager).createCalculator();
SearchStrategy firstStrategy = new SearchStrategy("random",new SelectBest(), new GreedyAcceptance(1), solutionCostCalculator);
firstStrategy.addModule(new RuinAndRecreateModule("randomRuinAndBestInsertion", iStrategy, randomRuin));
SearchStrategy secondStrategy = new SearchStrategy("radial",new SelectBest(), new GreedyAcceptance(1), solutionCostCalculator);
secondStrategy.addModule(new RuinAndRecreateModule("radialRuinAndBestInsertion", iStrategy, radialRuin));
/*
* put both strategies together, each with the prob of 0.5 to be selected
*/
SearchStrategyManager searchStrategyManager = new SearchStrategyManager();
searchStrategyManager.addStrategy(firstStrategy, 0.5);
searchStrategyManager.addStrategy(secondStrategy, 0.5);
/*
* construct the algorithm
*/
VehicleRoutingAlgorithm vra = new VehicleRoutingAlgorithm(vrp, searchStrategyManager);
//do not forgett to add the stateManager listening to the algorithm-stages
vra.addListener(stateManager);
//remove empty vehicles after insertion has finished
vra.addListener(new RemoveEmptyVehicles(fleetManager));
/*
* Do not forget to add an initial solution by vra.addInitialSolution(solution);
* or
*/
vra.addInitialSolution(new InsertionInitialSolutionFactory(iStrategy, solutionCostCalculator).createSolution(vrp));
/*
* define the nIterations (by default nIteration=100)
*/
vra.setMaxIterations(1000);
/*
* optionally define a premature termination criterion (by default: not criterion is set)
*/
vra.setPrematureAlgorithmTermination(new IterationWithoutImprovementTermination(100));
return vra;
}
SolutionCostCalculator objectiveFunction = getObjectiveFunction(vrp);
SearchStrategy firstStrategy = new SearchStrategy("firstStrategy", new SelectBest(), new GreedyAcceptance(1), objectiveFunction);
firstStrategy.addModule(new RuinAndRecreateModule("randRuinRegretIns", regret, randomRuin));
SearchStrategy secondStrategy = new SearchStrategy("secondStrategy", new SelectBest(), new GreedyAcceptance(1), objectiveFunction);
secondStrategy.addModule(new RuinAndRecreateModule("radRuinRegretIns", regret, radialRuin));
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);
final VehicleRoutingAlgorithm vra = prettyAlgorithmBuilder
.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
//switch on again at iteration 90 with slightly higher weight
IterationStartsListener strategyAdaptor = new IterationStartsListener() {
@Override
public void informIterationStarts(int i, VehicleRoutingProblem problem, Collection<VehicleRoutingProblemSolution> solutions) {
if(i == 50){
vra.getSearchStrategyManager().informStrategyWeightChanged("firstStrategy",0.0);
System.out.println("switched off firstStrategy");
}
if(i == 90){
vra.getSearchStrategyManager().informStrategyWeightChanged("firstStrategy",0.7);
System.out.println("switched on firstStrategy again with higher weight");
}
}
};
vra.addListener(strategyAdaptor);
return vra;
}
private static SolutionCostCalculator getObjectiveFunction(final VehicleRoutingProblem vrp) {
return new SolutionCostCalculator() {
@Override
public double getCosts(VehicleRoutingProblemSolution solution) {
SolutionAnalyser analyser = new SolutionAnalyser(vrp,solution,new SolutionAnalyser.DistanceCalculator() {
@Override
public double getDistance(String fromLocationId, String toLocationId) {
return vrp.getTransportCosts().getTransportCost(fromLocationId,toLocationId,0.,null,null);
}
});
return analyser.getVariableTransportCosts() + solution.getUnassignedJobs().size() * 500.;
}
};
}
}

View file

@ -1,208 +0,0 @@
/*******************************************************************************
* 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
* 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
* License along with this library. If not, see <http://www.gnu.org/licenses/>.
******************************************************************************/
package jsprit.examples;
import jsprit.core.algorithm.*;
import jsprit.core.algorithm.acceptor.GreedyAcceptance;
import jsprit.core.algorithm.module.RuinAndRecreateModule;
import jsprit.core.algorithm.recreate.BestInsertionBuilder;
import jsprit.core.algorithm.recreate.InsertionStrategy;
import jsprit.core.algorithm.ruin.RadialRuinStrategyFactory;
import jsprit.core.algorithm.ruin.RandomRuinStrategyFactory;
import jsprit.core.algorithm.ruin.RuinStrategy;
import jsprit.core.algorithm.ruin.distance.AvgServiceAndShipmentDistance;
import jsprit.core.algorithm.selector.SelectBest;
import jsprit.core.algorithm.state.StateManager;
import jsprit.core.algorithm.state.UpdateVariableCosts;
import jsprit.core.algorithm.termination.IterationWithoutImprovementTermination;
import jsprit.core.problem.VehicleRoutingProblem;
import jsprit.core.problem.constraint.ConstraintManager;
import jsprit.core.problem.solution.SolutionCostCalculator;
import jsprit.core.problem.solution.VehicleRoutingProblemSolution;
import jsprit.core.problem.vehicle.InfiniteFleetManagerFactory;
import jsprit.core.problem.vehicle.VehicleFleetManager;
import jsprit.core.reporting.SolutionPrinter;
import jsprit.core.util.Solutions;
import jsprit.instance.reader.SolomonReader;
import jsprit.util.Examples;
import java.util.Collection;
public class BuildAlgorithmFromScratchWithHardAndSoftConstraints {
public static void main(String[] args) {
/*
* some preparation - create output folder
*/
Examples.createOutputFolder();
/*
* Build the problem.
*
* But define a problem-builder first.
*/
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");
/*
* Finally, the problem can be built. By default, transportCosts are crowFlyDistances (as usually used for vrp-instances).
*/
VehicleRoutingProblem vrp = vrpBuilder.build();
/*
* Build algorithm
*/
VehicleRoutingAlgorithm vra = buildAlgorithmFromScratch(vrp);
/*
* search solution
*/
Collection<VehicleRoutingProblemSolution> solutions = vra.searchSolutions();
/*
* print result
*/
SolutionPrinter.print(Solutions.bestOf(solutions));
}
private static VehicleRoutingAlgorithm buildAlgorithmFromScratch(VehicleRoutingProblem vrp) {
/*
* manages route and activity states.
*/
StateManager stateManager = new StateManager(vrp);
/*
* tells stateManager to update load states
*/
stateManager.updateLoadStates();
/*
* tells stateManager to update time-window states
*/
stateManager.updateTimeWindowStates();
/*
* stateManager.addStateUpdater(updater);
* lets you register your own stateUpdater
*/
/*
* updates variable costs once a vehicleRoute has changed (by removing or adding a customer)
*/
stateManager.addStateUpdater(new UpdateVariableCosts(vrp.getActivityCosts(), vrp.getTransportCosts(), stateManager));
/*
* constructs a constraintManager that manages the various hardConstraints (and soon also softConstraints)
*/
ConstraintManager constraintManager = new ConstraintManager(vrp,stateManager);
/*
* tells constraintManager to add timeWindowConstraints
*/
constraintManager.addTimeWindowConstraint();
/*
* tells constraintManager to add loadConstraints
*/
constraintManager.addLoadConstraint();
/*
* add an arbitrary number of hardConstraints by
* constraintManager.addConstraint(...)
*/
/*
* define a fleetManager, here infinite vehicles can be used
*/
VehicleFleetManager fleetManager = new InfiniteFleetManagerFactory(vrp.getVehicles()).createFleetManager();
/*
* define ruin-and-recreate strategies
*
*/
/*
* first, define an insertion-strategy, i.e. bestInsertion
*/
BestInsertionBuilder iBuilder = new BestInsertionBuilder(vrp, fleetManager, stateManager, constraintManager);
/*
* no need to set further options
*/
InsertionStrategy iStrategy = iBuilder.build();
/*
* second, define random-ruin that ruins 50-percent of the selected solution
*/
RuinStrategy randomRuin = new RandomRuinStrategyFactory(0.5).createStrategy(vrp);
/*
* third, define radial-ruin that ruins 30-percent of the selected solution
* the second para defines the distance between two jobs.
*/
RuinStrategy radialRuin = new RadialRuinStrategyFactory(0.3, new AvgServiceAndShipmentDistance(vrp.getTransportCosts())).createStrategy(vrp);
/*
* now define a strategy
*/
/*
* but before define how a generated solution is evaluated
* here: the VariablePlusFixed.... comes out of the box and it does what its name suggests
*/
SolutionCostCalculator solutionCostCalculator = new VariablePlusFixedSolutionCostCalculatorFactory(stateManager).createCalculator();
SearchStrategy firstStrategy = new SearchStrategy("random",new SelectBest(), new GreedyAcceptance(1), solutionCostCalculator);
firstStrategy.addModule(new RuinAndRecreateModule("randomRuinAndBestInsertion", iStrategy, randomRuin));
SearchStrategy secondStrategy = new SearchStrategy("radial",new SelectBest(), new GreedyAcceptance(1), solutionCostCalculator);
secondStrategy.addModule(new RuinAndRecreateModule("radialRuinAndBestInsertion", iStrategy, radialRuin));
/*
* put both strategies together, each with the prob of 0.5 to be selected
*/
SearchStrategyManager searchStrategyManager = new SearchStrategyManager();
searchStrategyManager.addStrategy(firstStrategy, 0.5);
searchStrategyManager.addStrategy(secondStrategy, 0.5);
/*
* construct the algorithm
*/
VehicleRoutingAlgorithm vra = new VehicleRoutingAlgorithm(vrp, searchStrategyManager);
//do not forgett to add the stateManager listening to the algorithm-stages
vra.addListener(stateManager);
//remove empty vehicles after insertion has finished
vra.addListener(new RemoveEmptyVehicles(fleetManager));
/*
* Do not forget to add an initial solution by vra.addInitialSolution(solution);
* or
*/
vra.addInitialSolution(new InsertionInitialSolutionFactory(iStrategy, solutionCostCalculator).createSolution(vrp));
/*
* define the nIterations (by default nIteration=100)
*/
vra.setMaxIterations(1000);
/*
* optionally define a premature termination criterion (by default: not criterion is set)
*/
vra.setPrematureAlgorithmTermination(new IterationWithoutImprovementTermination(100));
return vra;
}
}

View file

@ -73,7 +73,7 @@ public class CircleExample {
VehicleRoutingProblem vrp = vrpBuilder.build();
//only works with latest snapshot: 1.4.3
AlgorithmEventsRecorder eventsRecorder = new AlgorithmEventsRecorder(vrp,new File("output/events.dgs.gz"));
AlgorithmEventsRecorder eventsRecorder = new AlgorithmEventsRecorder(vrp,"output/events.dgs.gz");
eventsRecorder.setRecordingRange(0,50);
VehicleRoutingAlgorithm vra = new GreedySchrimpfFactory().createAlgorithm(vrp);

View file

@ -30,7 +30,6 @@ import jsprit.core.reporting.SolutionPrinter;
import jsprit.instance.reader.SolomonReader;
import jsprit.util.Examples;
import java.io.File;
import java.util.Collection;
@ -70,7 +69,7 @@ public class SolomonWithRegretInsertionExample {
VehicleRoutingAlgorithm vra = VehicleRoutingAlgorithms.readAndCreateAlgorithm(vrp, "input/algorithmConfig_greedyWithRegret.xml");
vra.setMaxIterations(2);
AlgorithmEventsRecorder eventsRecorder = new AlgorithmEventsRecorder(vrp,new File("output/events.dgs.gz"));
AlgorithmEventsRecorder eventsRecorder = new AlgorithmEventsRecorder(vrp,"output/events.dgs.gz");
eventsRecorder.setRecordingRange(0,50);
vra.addListener(eventsRecorder);