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

prepare for release v0.1.0

This commit is contained in:
Stefan Schroeder 2013-11-22 16:54:15 +01:00
parent 77d38de461
commit a85b0fc395
304 changed files with 4035 additions and 64795 deletions

View file

@ -0,0 +1,171 @@
/*******************************************************************************
* Copyright (C) 2013 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.analysis.toolbox;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import jsprit.core.algorithm.VehicleRoutingAlgorithm;
import jsprit.core.algorithm.listener.AlgorithmEndsListener;
import jsprit.core.algorithm.listener.AlgorithmStartsListener;
import jsprit.core.algorithm.listener.IterationEndsListener;
import jsprit.core.problem.VehicleRoutingProblem;
import jsprit.core.problem.solution.VehicleRoutingProblemSolution;
import org.apache.log4j.Logger;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.plot.XYPlot;
import org.jfree.data.Range;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;
/**
* VehicleRoutingAlgorithm-Listener to record the solution-search-progress.
*
* <p>Register this listener in VehicleRoutingAlgorithm.
*
* @author stefan schroeder
*
*/
public class AlgorithmSearchProgressChartListener implements IterationEndsListener, AlgorithmEndsListener, AlgorithmStartsListener {
private static Logger log = Logger.getLogger(AlgorithmSearchProgressChartListener.class);
private double[] bestResults;
private double[] worstResults;
private double[] avgResults;
private List<Double> bestResultList = new ArrayList<Double>();
private List<Double> worstResultList = new ArrayList<Double>();
private List<Double> avgResultList = new ArrayList<Double>();
private String filename;
/**
* Constructs chart listener with target png-file (filename plus path).
*
* @param pngFileName
*/
public AlgorithmSearchProgressChartListener(String pngFileName) {
super();
this.filename = pngFileName;
if(!this.filename.endsWith("png")){
this.filename += ".png";
}
}
@Override
public void informAlgorithmEnds(VehicleRoutingProblem problem, Collection<VehicleRoutingProblemSolution> solutions) {
log.info("create chart " + filename);
if(bestResultList.isEmpty()){
log.warn("cannot create chart since no results available.");
return;
}
bestResults = new double[bestResultList.size()];
worstResults = new double[worstResultList.size()];
avgResults = new double[avgResultList.size()];
double maxValue = 0.0;
double minValue = Double.MAX_VALUE;
double[] iteration = new double[bestResultList.size()];
for (int i = 0; i < bestResultList.size(); i++) {
if(bestResultList.get(i) < minValue) minValue = bestResultList.get(i);
if(worstResultList.get(i) < minValue) minValue = worstResultList.get(i);
if(avgResultList.get(i) < minValue) minValue = avgResultList.get(i);
if(bestResultList.get(i) > maxValue) maxValue = bestResultList.get(i);
if(worstResultList.get(i) > maxValue) maxValue = worstResultList.get(i);
if(avgResultList.get(i) > maxValue) maxValue = avgResultList.get(i);
bestResults[i] = bestResultList.get(i);
worstResults[i] = worstResultList.get(i);
avgResults[i] = avgResultList.get(i);
iteration[i] = i;
}
XYSeriesCollection coll = new XYSeriesCollection();
JFreeChart chart = ChartFactory.createXYLineChart("search-progress","iterations", "results",coll, PlotOrientation.VERTICAL,true,true,false);
addSeries("bestResults", iteration, bestResults, coll);
addSeries("worstResults", iteration, worstResults, coll);
addSeries("avgResults", iteration, avgResults, coll);
XYPlot plot = chart.getXYPlot();
NumberAxis yAxis = (NumberAxis) plot.getRangeAxis();
Range rangeBounds = coll.getRangeBounds(true);
double upper = Math.min(rangeBounds.getUpperBound(), rangeBounds.getLowerBound()*5);
if(upper == 0.0){ upper = 10000; }
yAxis.setRangeWithMargins(rangeBounds.getLowerBound(),upper);
try {
ChartUtilities.saveChartAsJPEG(new File(filename), chart, 1000, 600);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void addSeries(String string, double[] iteration, double[] results, XYSeriesCollection coll) {
XYSeries series = new XYSeries(string, true, true);
for(int i=0;i<iteration.length;i++){
series.add(iteration[i], results[i]);
}
coll.addSeries(series);
}
@Override
public void informIterationEnds(int i, VehicleRoutingProblem problem, Collection<VehicleRoutingProblemSolution> solutions) {
double worst = 0.0;
double best = Double.MAX_VALUE;
double sum = 0.0;
for(VehicleRoutingProblemSolution sol : solutions){
if(sol.getCost() > worst) worst = Math.min(sol.getCost(),Double.MAX_VALUE);
if(sol.getCost() < best) best = sol.getCost();
sum += Math.min(sol.getCost(),Double.MAX_VALUE);
}
bestResultList.add(best);
worstResultList.add(worst);
avgResultList.add(sum/(double)solutions.size());
}
@Override
public void informAlgorithmStarts(VehicleRoutingProblem problem,VehicleRoutingAlgorithm algorithm,Collection<VehicleRoutingProblemSolution> solutions) {
bestResults = null;
worstResults = null;
avgResults = null;
bestResultList.clear();
worstResultList.clear();
avgResultList.clear();
}
}

View file

@ -0,0 +1,226 @@
/*******************************************************************************
* Copyright (C) 2013 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.analysis.toolbox;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import jsprit.analysis.util.BenchmarkWriter;
import jsprit.core.algorithm.VehicleRoutingAlgorithm;
import jsprit.core.algorithm.VehicleRoutingAlgorithmFactory;
import jsprit.core.algorithm.io.VehicleRoutingAlgorithms;
import jsprit.core.algorithm.listener.VehicleRoutingAlgorithmListeners.Priority;
import jsprit.core.problem.VehicleRoutingProblem;
import jsprit.core.problem.solution.VehicleRoutingProblemSolution;
import jsprit.core.util.BenchmarkInstance;
import jsprit.core.util.BenchmarkResult;
import jsprit.core.util.Solutions;
import org.apache.commons.math.stat.descriptive.DescriptiveStatistics;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
public class ConcurrentBenchmarker {
public static interface Cost {
public double getCost(VehicleRoutingProblemSolution sol);
}
private String algorithmConfig = null;
private List<BenchmarkInstance> benchmarkInstances = new ArrayList<BenchmarkInstance>();
private int runs = 1;
private Collection<BenchmarkWriter> writers = new ArrayList<BenchmarkWriter>();
private Collection<BenchmarkResult> results = new ArrayList<BenchmarkResult>();
private Cost cost = new Cost(){
@Override
public double getCost(VehicleRoutingProblemSolution sol) {
return sol.getCost();
}
};
private VehicleRoutingAlgorithmFactory algorithmFactory;
public void setCost(Cost cost){ this.cost = cost; }
public ConcurrentBenchmarker(String algorithmConfig) {
super();
this.algorithmConfig = algorithmConfig;
Logger.getRootLogger().setLevel(Level.ERROR);
}
public ConcurrentBenchmarker(VehicleRoutingAlgorithmFactory algorithmFactory){
this.algorithmFactory = algorithmFactory;
}
public void addBenchmarkWriter(BenchmarkWriter writer){
writers.add(writer);
}
public void addInstance(String name, VehicleRoutingProblem problem){
benchmarkInstances.add(new BenchmarkInstance(name,problem,null,null));
}
public void addInstane(BenchmarkInstance instance){
benchmarkInstances.add(instance);
}
public void addAllInstances(Collection<BenchmarkInstance> instances){
benchmarkInstances.addAll(instances);
}
public void addInstance(String name, VehicleRoutingProblem problem, Double bestKnownResult, Double bestKnownVehicles){
benchmarkInstances.add(new BenchmarkInstance(name,problem,bestKnownResult,bestKnownVehicles));
}
/**
* Sets nuOfRuns with same algorithm on same instance.
* <p>Default is 1
*
* @param runs
*/
public void setNuOfRuns(int runs){
this.runs = runs;
}
public void run(){
System.out.println("start benchmarking [nuOfInstances=" + benchmarkInstances.size() + "][runsPerInstance=" + runs + "]");
double startTime = System.currentTimeMillis();
ExecutorService executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()+1);
List<Future<BenchmarkResult>> futures = new ArrayList<Future<BenchmarkResult>>();
for(final BenchmarkInstance p : benchmarkInstances){
Future<BenchmarkResult> futureResult = executor.submit(new Callable<BenchmarkResult>(){
@Override
public BenchmarkResult call() throws Exception {
return runAlgoAndGetResult(p);
}
});
futures.add(futureResult);
}
try {
int count = 1;
for(Future<BenchmarkResult> f : futures){
BenchmarkResult r = f.get();
print(r,count);
results.add(f.get());
count++;
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
executor.shutdown();
print(results);
System.out.println("done [time="+(System.currentTimeMillis()-startTime)/1000 + "sec]");
}
private BenchmarkResult runAlgoAndGetResult(BenchmarkInstance p) {
double[] vehicles = new double[runs];
double[] results = new double[runs];
double[] times = new double[runs];
for(int run=0;run<runs;run++){
VehicleRoutingAlgorithm vra = createAlgorithm(p);
StopWatch stopwatch = new StopWatch();
vra.getAlgorithmListeners().addListener(stopwatch,Priority.HIGH);
Collection<VehicleRoutingProblemSolution> solutions = vra.searchSolutions();
VehicleRoutingProblemSolution best = Solutions.bestOf(solutions);
vehicles[run] = best.getRoutes().size();
results[run] = cost.getCost(best);
times[run] = stopwatch.getCompTimeInSeconds();
}
return new BenchmarkResult(p, runs, results, times, vehicles);
}
private VehicleRoutingAlgorithm createAlgorithm(BenchmarkInstance p) {
if(algorithmConfig != null){
return VehicleRoutingAlgorithms.readAndCreateAlgorithm(p.vrp, algorithmConfig);
}
else{
return algorithmFactory.createAlgorithm(p.vrp);
}
}
private void print(Collection<BenchmarkResult> results) {
double sumTime=0.0;
double sumResult=0.0;
for(BenchmarkResult r : results){
sumTime+=r.getTimesStats().getMean();
sumResult+=r.getResultStats().getMean();
// print(r);
}
System.out.println("[avgTime="+round(sumTime/(double)results.size(),2)+"][avgResult="+round(sumResult/(double)results.size(),2)+"]");
for(BenchmarkWriter writer : writers){
writer.write(results);
}
}
private void print(BenchmarkResult r, int count) {
Double avgDelta = null;
Double bestDelta = null;
Double worstDelta = null;
if(r.instance.bestKnownResult != null){
avgDelta = (r.getResultStats().getMean() / r.instance.bestKnownResult - 1) * 100;
bestDelta = (r.getResultStats().getMin() / r.instance.bestKnownResult - 1) * 100;
worstDelta = (r.getResultStats().getMax() / r.instance.bestKnownResult - 1) * 100;
}
System.out.println("("+count+"/"+benchmarkInstances.size() +")"+ "\t[instance="+r.instance.name+
"][avgTime="+round(r.getTimesStats().getMean(),2)+"]" +
"[Result=" + getString(r.getResultStats()) + "]" +
"[Vehicles=" + getString(r.getVehicleStats()) + "]" +
"[Delta[%]=" + getString(bestDelta,avgDelta,worstDelta) + "]");
}
private String getString(Double bestDelta, Double avgDelta,Double worstDelta) {
return "[best="+round(bestDelta,2)+"][avg="+round(avgDelta,2)+"][worst="+round(worstDelta,2)+"]";
}
private String getString(DescriptiveStatistics stats){
return "[best="+round(stats.getMin(),2)+"][avg="+round(stats.getMean(),2)+"][worst="+round(stats.getMax(),2)+"][stdDev=" + round(stats.getStandardDeviation(),2)+"]";
}
private Double round(Double value, int i) {
if(value==null) return null;
long roundedVal = Math.round(value*Math.pow(10, i));
return (double)roundedVal/(double)(Math.pow(10, i));
}
}

View file

@ -0,0 +1,490 @@
/*******************************************************************************
* Copyright (C) 2013 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.analysis.toolbox;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.geom.Ellipse2D;
import java.io.File;
import java.io.IOException;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import jsprit.core.problem.VehicleRoutingProblem;
import jsprit.core.problem.job.Delivery;
import jsprit.core.problem.job.Job;
import jsprit.core.problem.job.Pickup;
import jsprit.core.problem.job.Service;
import jsprit.core.problem.job.Shipment;
import jsprit.core.problem.solution.VehicleRoutingProblemSolution;
import jsprit.core.problem.solution.route.VehicleRoute;
import jsprit.core.problem.solution.route.activity.TourActivity;
import jsprit.core.problem.vehicle.Vehicle;
import jsprit.core.util.Coordinate;
import jsprit.core.util.Locations;
import org.apache.log4j.Logger;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.LegendItemCollection;
import org.jfree.chart.LegendItemSource;
import org.jfree.chart.annotations.XYShapeAnnotation;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.labels.XYItemLabelGenerator;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.xy.XYItemRenderer;
import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer;
import org.jfree.chart.title.LegendTitle;
import org.jfree.data.xy.XYDataItem;
import org.jfree.data.xy.XYDataset;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;
import org.jfree.ui.RectangleEdge;
public class Plotter {
private static class NoLocationFoundException extends Exception{
/**
*
*/
private static final long serialVersionUID = 1L;
}
private static Logger log = Logger.getLogger(SolutionPlotter.class);
public static enum Label {
ID, SIZE, NO_LABEL
}
private boolean showFirstActivity = true;
private Label label = Label.SIZE;
private VehicleRoutingProblem vrp;
private boolean plotSolutionAsWell = false;
private boolean plotShipments = true;
private Collection<VehicleRoute> routes;
public void setShowFirstActivity(boolean show){
showFirstActivity = show;
}
public void setLabel(Label label){
this.label = label;
}
public Plotter(VehicleRoutingProblem vrp) {
super();
this.vrp = vrp;
}
public Plotter(VehicleRoutingProblem vrp, VehicleRoutingProblemSolution solution) {
super();
this.vrp = vrp;
this.routes = solution.getRoutes();
plotSolutionAsWell = true;
}
public Plotter(VehicleRoutingProblem vrp, Collection<VehicleRoute> routes) {
super();
this.vrp = vrp;
this.routes = routes;
plotSolutionAsWell = true;
}
public void plot(String pngFileName, String plotTitle){
String filename = pngFileName;
if(!pngFileName.endsWith(".png")) filename += ".png";
if(plotSolutionAsWell){
plotSolutionAsPNG(vrp, routes, filename, plotTitle);
}
else{
plotVrpAsPNG(vrp, filename, plotTitle);
}
}
private void plotVrpAsPNG(VehicleRoutingProblem vrp, String pngFile, String title){
log.info("plot routes to " + pngFile);
XYSeriesCollection problem;
final XYSeriesCollection shipments;
Map<XYDataItem,String> labels = new HashMap<XYDataItem, String>();
try {
problem = makeVrpSeries(vrp, labels);
shipments = makeShipmentSeries(vrp.getJobs().values(), null);
} catch (NoLocationFoundException e) {
log.warn("cannot plot vrp, since coord is missing");
return;
}
final XYPlot plot = createProblemPlot(problem, shipments, labels);
LegendItemSource lis = new LegendItemSource() {
@Override
public LegendItemCollection getLegendItems() {
LegendItemCollection lic = new LegendItemCollection();
lic.addAll(plot.getRenderer(0).getLegendItems());
if(!shipments.getSeries().isEmpty()){
lic.add(plot.getRenderer(1).getLegendItem(1, 0));
}
return lic;
}
};
JFreeChart chart = new JFreeChart(title, plot);
chart.removeLegend();
LegendTitle legend = new LegendTitle(lis);
legend.setPosition(RectangleEdge.BOTTOM);
chart.addLegend(legend);
save(chart,pngFile);
}
private void plotSolutionAsPNG(VehicleRoutingProblem vrp, Collection<VehicleRoute> routes, String pngFile, String title){
log.info("plot solution to " + pngFile);
XYSeriesCollection problem;
XYSeriesCollection solutionColl;
final XYSeriesCollection shipments;
Map<XYDataItem,String> labels = new HashMap<XYDataItem, String>();
try {
problem = makeVrpSeries(vrp, labels);
shipments = makeShipmentSeries(vrp.getJobs().values(), null);
solutionColl = makeSolutionSeries(vrp, routes);
} catch (NoLocationFoundException e) {
log.warn("cannot plot vrp, since coord is missing");
return;
}
final XYPlot plot = createProblemSolutionPlot(problem, shipments, solutionColl, labels);
JFreeChart chart = new JFreeChart(title, plot);
LegendItemSource lis = new LegendItemSource() {
@Override
public LegendItemCollection getLegendItems() {
LegendItemCollection lic = new LegendItemCollection();
lic.addAll(plot.getRenderer(0).getLegendItems());
lic.addAll(plot.getRenderer(2).getLegendItems());
if(!shipments.getSeries().isEmpty()){
lic.add(plot.getRenderer(1).getLegendItem(1, 0));
}
return lic;
}
};
chart.removeLegend();
LegendTitle legend = new LegendTitle(lis);
legend.setPosition(RectangleEdge.BOTTOM);
chart.addLegend(legend);
save(chart,pngFile);
}
private static XYPlot createProblemPlot(final XYSeriesCollection problem, XYSeriesCollection shipments, final Map<XYDataItem, String> labels) {
XYPlot plot = new XYPlot();
plot.setBackgroundPaint(Color.LIGHT_GRAY);
plot.setRangeGridlinePaint(Color.WHITE);
plot.setDomainGridlinePaint(Color.WHITE);
XYItemRenderer problemRenderer = new XYLineAndShapeRenderer(false, true); // Shapes only
problemRenderer.setBaseItemLabelGenerator(new XYItemLabelGenerator() {
@Override
public String generateLabel(XYDataset arg0, int arg1, int arg2) {
XYDataItem item = problem.getSeries(arg1).getDataItem(arg2);
return labels.get(item);
}
});
problemRenderer.setBaseItemLabelsVisible(true);
problemRenderer.setBaseItemLabelPaint(Color.BLACK);
NumberAxis xAxis = new NumberAxis();
xAxis.setRangeWithMargins(problem.getDomainBounds(true));
NumberAxis yAxis = new NumberAxis();
yAxis.setRangeWithMargins(problem.getRangeBounds(false));
plot.setDataset(0, problem);
plot.setRenderer(0, problemRenderer);
plot.setDomainAxis(0, xAxis);
plot.setRangeAxis(0, yAxis);
XYItemRenderer shipmentsRenderer = new XYLineAndShapeRenderer(true, false); // Shapes only
for(int i=0;i<shipments.getSeriesCount();i++){
shipmentsRenderer.setSeriesPaint(i, Color.BLUE);
shipmentsRenderer.setSeriesStroke(i, new BasicStroke(
1.0f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND,
1.0f, new float[] {6.0f, 6.0f}, 0.0f
));
}
// shipmentsRenderer.getLegendItems().
plot.setDataset(1, shipments);
plot.setRenderer(1, shipmentsRenderer);
// plot.setDomainAxis(1, xAxis);
// plot.setRangeAxis(1, yAxis);
// plot.addl
return plot;
}
private XYPlot createProblemSolutionPlot(final XYSeriesCollection problem, XYSeriesCollection shipments, XYSeriesCollection solutionColl, final Map<XYDataItem, String> labels) {
XYPlot plot = new XYPlot();
plot.setBackgroundPaint(Color.LIGHT_GRAY);
plot.setRangeGridlinePaint(Color.WHITE);
plot.setDomainGridlinePaint(Color.WHITE);
XYItemRenderer problemRenderer = new XYLineAndShapeRenderer(false, true); // Shapes only
problemRenderer.setBaseItemLabelGenerator(new XYItemLabelGenerator() {
@Override
public String generateLabel(XYDataset arg0, int arg1, int arg2) {
XYDataItem item = problem.getSeries(arg1).getDataItem(arg2);
return labels.get(item);
}
});
problemRenderer.setBaseItemLabelsVisible(true);
problemRenderer.setBaseItemLabelPaint(Color.BLACK);
NumberAxis xAxis = new NumberAxis();
xAxis.setRangeWithMargins(problem.getDomainBounds(true));
NumberAxis yAxis = new NumberAxis();
yAxis.setRangeWithMargins(problem.getRangeBounds(true));
plot.setDataset(0, problem);
plot.setRenderer(0, problemRenderer);
plot.setDomainAxis(0, xAxis);
plot.setRangeAxis(0, yAxis);
// plot.mapDatasetToDomainAxis(0, 0);
XYItemRenderer shipmentsRenderer = new XYLineAndShapeRenderer(true, false); // Shapes only
for(int i=0;i<shipments.getSeriesCount();i++){
shipmentsRenderer.setSeriesPaint(i, Color.BLUE);
shipmentsRenderer.setSeriesStroke(i, new BasicStroke(
1.0f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND,
1.0f, new float[] {6.0f, 6.0f}, 0.0f
));
}
plot.setDataset(1, shipments);
plot.setRenderer(1, shipmentsRenderer);
// plot.setDomainAxis(1, xAxis);
// plot.setRangeAxis(1, yAxis);
XYItemRenderer solutionRenderer = new XYLineAndShapeRenderer(true, false); // Lines only
if(showFirstActivity){
for(int i=0;i<solutionColl.getSeriesCount();i++){
XYSeries s = solutionColl.getSeries(i);
XYDataItem firstCustomer = s.getDataItem(1);
solutionRenderer.addAnnotation(new XYShapeAnnotation( new Ellipse2D.Double(firstCustomer.getXValue()-0.7, firstCustomer.getYValue()-0.7, 1.5, 1.5), new BasicStroke(1.0f), Color.RED));
}
}
plot.setDataset(2, solutionColl);
plot.setRenderer(2, solutionRenderer);
// plot.setDomainAxis(2, xAxis);
// plot.setRangeAxis(2, yAxis);
return plot;
}
private void save(JFreeChart chart, String pngFile) {
try {
ChartUtilities.saveChartAsPNG(new File(pngFile), chart, 1000, 600);
} catch (IOException e) {
log.error("cannot plot");
log.error(e);
e.printStackTrace();
}
}
private XYSeriesCollection makeSolutionSeries(VehicleRoutingProblem vrp, Collection<VehicleRoute> routes) throws NoLocationFoundException{
Locations locations = retrieveLocations(vrp);
XYSeriesCollection coll = new XYSeriesCollection();
int counter = 1;
for(VehicleRoute route : routes){
if(route.isEmpty()) continue;
XYSeries series = new XYSeries(counter, false, true);
Coordinate startCoord = locations.getCoord(route.getStart().getLocationId());
series.add(startCoord.getX(), startCoord.getY());
for(TourActivity act : route.getTourActivities().getActivities()){
Coordinate coord = locations.getCoord(act.getLocationId());
series.add(coord.getX(), coord.getY());
}
Coordinate endCoord = locations.getCoord(route.getEnd().getLocationId());
series.add(endCoord.getX(), endCoord.getY());
coll.addSeries(series);
counter++;
}
return coll;
}
private XYSeriesCollection makeShipmentSeries(Collection<Job> jobs, Map<XYDataItem, String> labels) throws NoLocationFoundException{
XYSeriesCollection coll = new XYSeriesCollection();
if(!plotShipments) return coll;
int sCounter = 1;
String ship = "shipment";
boolean first = true;
for(Job job : jobs){
if(!(job instanceof Shipment)){
continue;
}
Shipment shipment = (Shipment)job;
XYSeries shipmentSeries;
if(first){
first = false;
shipmentSeries = new XYSeries(ship, false, true);
}
else{
shipmentSeries = new XYSeries(sCounter, false, true);
sCounter++;
}
shipmentSeries.add(shipment.getPickupCoord().getX(), shipment.getPickupCoord().getY());
shipmentSeries.add(shipment.getDeliveryCoord().getX(), shipment.getDeliveryCoord().getY());
coll.addSeries(shipmentSeries);
}
return coll;
}
private XYSeriesCollection makeVrpSeries(Collection<Vehicle> vehicles, Collection<Job> jobs, Map<XYDataItem, String> labels) throws NoLocationFoundException{
XYSeriesCollection coll = new XYSeriesCollection();
XYSeries vehicleSeries = new XYSeries("depot", false, true);
for(Vehicle v : vehicles){
Coordinate coord = v.getCoord();
if(coord == null) throw new NoLocationFoundException();
vehicleSeries.add(coord.getX(),coord.getY());
}
coll.addSeries(vehicleSeries);
XYSeries serviceSeries = new XYSeries("service", false, true);
XYSeries pickupSeries = new XYSeries("pickup", false, true);
XYSeries deliverySeries = new XYSeries("delivery", false, true);
for(Job job : jobs){
if(job instanceof Shipment){
Shipment s = (Shipment)job;
XYDataItem dataItem = new XYDataItem(s.getPickupCoord().getX(), s.getPickupCoord().getY());
pickupSeries.add(dataItem);
addLabel(labels, s, dataItem);
XYDataItem dataItem2 = new XYDataItem(s.getDeliveryCoord().getX(), s.getDeliveryCoord().getY());
deliverySeries.add(dataItem2);
addLabel(labels, s, dataItem2);
}
else if(job instanceof Pickup){
Pickup service = (Pickup)job;
Coordinate coord = service.getCoord();
XYDataItem dataItem = new XYDataItem(coord.getX(), coord.getY());
pickupSeries.add(dataItem);
addLabel(labels, service, dataItem);
}
else if(job instanceof Delivery){
Delivery service = (Delivery)job;
Coordinate coord = service.getCoord();
XYDataItem dataItem = new XYDataItem(coord.getX(), coord.getY());
deliverySeries.add(dataItem);
addLabel(labels, service, dataItem);
}
else if(job instanceof Service){
Service service = (Service)job;
Coordinate coord = service.getCoord();
XYDataItem dataItem = new XYDataItem(coord.getX(), coord.getY());
serviceSeries.add(dataItem);
addLabel(labels, service, dataItem);
}
else{
throw new IllegalStateException("job instanceof " + job.getClass().toString() + ". this is not supported.");
}
}
if(!serviceSeries.isEmpty()) coll.addSeries(serviceSeries);
if(!pickupSeries.isEmpty()) coll.addSeries(pickupSeries);
if(!deliverySeries.isEmpty()) coll.addSeries(deliverySeries);
return coll;
}
private void addLabel(Map<XYDataItem, String> labels, Job job, XYDataItem dataItem) {
if(this.label.equals(Label.SIZE)){
labels.put(dataItem, String.valueOf(job.getCapacityDemand()));
}
else if(this.label.equals(Label.ID)){
labels.put(dataItem, String.valueOf(job.getId()));
}
}
private XYSeriesCollection makeVrpSeries(VehicleRoutingProblem vrp, Map<XYDataItem, String> labels) throws NoLocationFoundException{
return makeVrpSeries(vrp.getVehicles(), vrp.getJobs().values(), labels);
}
private Locations retrieveLocations(VehicleRoutingProblem vrp) throws NoLocationFoundException {
final Map<String, Coordinate> locs = new HashMap<String, Coordinate>();
for(Vehicle v : vrp.getVehicles()){
String locationId = v.getLocationId();
if(locationId == null) throw new NoLocationFoundException();
Coordinate coord = v.getCoord();
if(coord == null) throw new NoLocationFoundException();
locs.put(locationId, coord);
}
for(Job j : vrp.getJobs().values()){
if(j instanceof Service){
String locationId = ((Service) j).getLocationId();
if(locationId == null) throw new NoLocationFoundException();
Coordinate coord = ((Service) j).getCoord();
if(coord == null) throw new NoLocationFoundException();
locs.put(locationId, coord);
}
else if(j instanceof Shipment){
{
String locationId = ((Shipment) j).getPickupLocation();
if(locationId == null) throw new NoLocationFoundException();
Coordinate coord = ((Shipment) j).getPickupCoord();
if(coord == null) throw new NoLocationFoundException();
locs.put(locationId, coord);
}
{
String locationId = ((Shipment) j).getDeliveryLocation();
if(locationId == null) throw new NoLocationFoundException();
Coordinate coord = ((Shipment) j).getDeliveryCoord();
if(coord == null) throw new NoLocationFoundException();
locs.put(locationId, coord);
}
}
else{
throw new IllegalStateException("job is not a service. this is not supported yet.");
}
}
return new Locations() {
@Override
public Coordinate getCoord(String id) {
return locs.get(id);
}
};
}
public void plotShipments(boolean plotShipments) {
this.plotShipments = plotShipments;
}
}

View file

@ -0,0 +1,383 @@
/*******************************************************************************
* Copyright (C) 2013 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.analysis.toolbox;
import java.awt.Color;
import java.io.File;
import java.io.IOException;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import jsprit.core.problem.VehicleRoutingProblem;
import jsprit.core.problem.job.Delivery;
import jsprit.core.problem.job.Job;
import jsprit.core.problem.job.Pickup;
import jsprit.core.problem.job.Service;
import jsprit.core.problem.solution.VehicleRoutingProblemSolution;
import jsprit.core.problem.solution.route.VehicleRoute;
import jsprit.core.problem.solution.route.activity.TourActivity;
import jsprit.core.problem.vehicle.Vehicle;
import jsprit.core.util.Coordinate;
import jsprit.core.util.Locations;
import org.apache.log4j.Logger;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.xy.XYItemRenderer;
import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer;
import org.jfree.data.xy.XYDataItem;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;
/**
* A plotter to plot vehicle-routing-solution and routes respectively.
*
* @author stefan schroeder
*
*/
public class SolutionPlotter {
private static class NoLocationFoundException extends Exception{
/**
*
*/
private static final long serialVersionUID = 1L;
}
private static Logger log = Logger.getLogger(SolutionPlotter.class);
/**
* Plots the {@link VehicleRoutingProblem} to png-file.
* @param vrp
* @param pngFile target path with filename.
* @see VehicleRoutingProblem, VehicleRoutingProblemSolution
*/
public static void plotVrpAsPNG(VehicleRoutingProblem vrp, String pngFile, String title){
String filename = pngFile;
if(!pngFile.endsWith(".png")) filename += ".png";
log.info("plot routes to " + filename);
XYSeriesCollection problem;
Map<XYDataItem,String> labels = new HashMap<XYDataItem, String>();
try {
problem = makeVrpSeries(vrp, labels);
} catch (NoLocationFoundException e) {
log.warn("cannot plot vrp, since coord is missing");
return;
}
XYPlot plot = createPlot(problem, labels);
JFreeChart chart = new JFreeChart(title, plot);
save(chart,filename);
}
/**
* Retrieves the problem from routes, and plots it along with the routes to pngFile.
*
* @param routes
* @param locations indicating the locations for the tour-activities.
* @param pngFile target path with filename.
* @param plotTitle
* @see VehicleRoute
*/
public static void plotRoutesAsPNG(Collection<VehicleRoute> routes, Locations locations, String pngFile, String title) {
String filename = pngFile;
if(!pngFile.endsWith(".png")) filename += ".png";
log.info("plot routes to " + filename);
XYSeriesCollection problem;
Map<XYDataItem,String> labels = new HashMap<XYDataItem, String>();
try {
problem = makeVrpSeries(routes, labels);
} catch (NoLocationFoundException e) {
log.warn("cannot plot vrp, since coord is missing");
return;
}
XYSeriesCollection solutionColl = makeSolutionSeries(routes,locations);
XYPlot plot = createPlot(problem, solutionColl, labels);
JFreeChart chart = new JFreeChart(title, plot);
save(chart,filename);
}
/**
* Plots problem and solution to pngFile.
*
* <p>This can only plot if vehicles and jobs have locationIds and coordinates (@see Coordinate). Otherwise a warning message is logged
* and method returns but does not plot.
*
* @param vrp
* @param solution
* @param pngFile target path with filename.
* @see VehicleRoutingProblem, VehicleRoutingProblemSolution
*/
public static void plotSolutionAsPNG(VehicleRoutingProblem vrp, VehicleRoutingProblemSolution solution, String pngFile, String title){
String filename = pngFile;
if(!pngFile.endsWith(".png")) filename += ".png";
log.info("plot solution to " + filename);
XYSeriesCollection problem;
XYSeriesCollection solutionColl;
Map<XYDataItem,String> labels = new HashMap<XYDataItem, String>();
try {
problem = makeVrpSeries(vrp, labels);
solutionColl = makeSolutionSeries(vrp, solution);
} catch (NoLocationFoundException e) {
log.warn("cannot plot vrp, since coord is missing");
return;
}
XYPlot plot = createPlot(problem, solutionColl, labels);
JFreeChart chart = new JFreeChart(title, plot);
save(chart,filename);
}
private static XYPlot createPlot(final XYSeriesCollection problem, final Map<XYDataItem, String> labels) {
XYPlot plot = new XYPlot();
plot.setBackgroundPaint(Color.LIGHT_GRAY);
plot.setRangeGridlinePaint(Color.WHITE);
plot.setDomainGridlinePaint(Color.WHITE);
XYItemRenderer problemRenderer = new XYLineAndShapeRenderer(false, true); // Shapes only
// problemRenderer.setBaseItemLabelGenerator(new XYItemLabelGenerator() {
//
// @Override
// public String generateLabel(XYDataset arg0, int arg1, int arg2) {
// XYDataItem item = problem.getSeries(arg1).getDataItem(arg2);
// return labels.get(item);
// }
// });
problemRenderer.setBaseItemLabelsVisible(true);
problemRenderer.setBaseItemLabelPaint(Color.BLACK);
NumberAxis xAxis = new NumberAxis();
xAxis.setRangeWithMargins(problem.getDomainBounds(true));
NumberAxis yAxis = new NumberAxis();
yAxis.setRangeWithMargins(problem.getRangeBounds(false));
plot.setDataset(0, problem);
plot.setRenderer(0, problemRenderer);
plot.setDomainAxis(0, xAxis);
plot.setRangeAxis(0, yAxis);
return plot;
}
private static XYPlot createPlot(final XYSeriesCollection problem, XYSeriesCollection solutionColl, final Map<XYDataItem, String> labels) {
XYPlot plot = new XYPlot();
plot.setBackgroundPaint(Color.LIGHT_GRAY);
plot.setRangeGridlinePaint(Color.WHITE);
plot.setDomainGridlinePaint(Color.WHITE);
XYItemRenderer problemRenderer = new XYLineAndShapeRenderer(false, true); // Shapes only
// problemRenderer.setBaseItemLabelGenerator(new XYItemLabelGenerator() {
//
// @Override
// public String generateLabel(XYDataset arg0, int arg1, int arg2) {
// XYDataItem item = problem.getSeries(arg1).getDataItem(arg2);
// return labels.get(item);
// }
// });
problemRenderer.setBaseItemLabelsVisible(true);
problemRenderer.setBaseItemLabelPaint(Color.BLACK);
NumberAxis xAxis = new NumberAxis();
xAxis.setRangeWithMargins(problem.getDomainBounds(true));
NumberAxis yAxis = new NumberAxis();
yAxis.setRangeWithMargins(problem.getRangeBounds(true));
plot.setDataset(0, problem);
plot.setRenderer(0, problemRenderer);
plot.setDomainAxis(0, xAxis);
plot.setRangeAxis(0, yAxis);
XYItemRenderer solutionRenderer = new XYLineAndShapeRenderer(true, false); // Lines only
// for(int i=0;i<solutionColl.getSeriesCount();i++){
// XYSeries s = solutionColl.getSeries(i);
// XYDataItem firstCustomer = s.getDataItem(1);
// solutionRenderer.addAnnotation(new XYShapeAnnotation( new Ellipse2D.Double(firstCustomer.getXValue()-0.7, firstCustomer.getYValue()-0.7, 1.5, 1.5), new BasicStroke(1.0f), Color.RED));
// }
plot.setDataset(1, solutionColl);
plot.setRenderer(1, solutionRenderer);
plot.setDomainAxis(1, xAxis);
plot.setRangeAxis(1, yAxis);
return plot;
}
private static void save(JFreeChart chart, String pngFile) {
try {
ChartUtilities.saveChartAsPNG(new File(pngFile), chart, 1000, 600);
} catch (IOException e) {
log.error("cannot plot");
log.error(e);
e.printStackTrace();
}
}
private static XYSeriesCollection makeSolutionSeries(VehicleRoutingProblem vrp, VehicleRoutingProblemSolution solution) throws NoLocationFoundException{
Locations locations = retrieveLocations(vrp);
XYSeriesCollection coll = new XYSeriesCollection();
int counter = 1;
for(VehicleRoute route : solution.getRoutes()){
if(route.isEmpty()) continue;
XYSeries series = new XYSeries(counter, false, true);
Coordinate startCoord = locations.getCoord(route.getStart().getLocationId());
series.add(startCoord.getX(), startCoord.getY());
for(TourActivity act : route.getTourActivities().getActivities()){
Coordinate coord = locations.getCoord(act.getLocationId());
series.add(coord.getX(), coord.getY());
}
Coordinate endCoord = locations.getCoord(route.getEnd().getLocationId());
series.add(endCoord.getX(), endCoord.getY());
coll.addSeries(series);
counter++;
}
return coll;
}
private static XYSeriesCollection makeSolutionSeries(Collection<VehicleRoute> routes, Locations locations){
XYSeriesCollection coll = new XYSeriesCollection();
int counter = 1;
for(VehicleRoute route : routes){
if(route.isEmpty()) continue;
XYSeries series = new XYSeries(counter, false, true);
Coordinate startCoord = locations.getCoord(route.getStart().getLocationId());
series.add(startCoord.getX(), startCoord.getY());
for(TourActivity act : route.getTourActivities().getActivities()){
Coordinate coord = locations.getCoord(act.getLocationId());
series.add(coord.getX(), coord.getY());
}
Coordinate endCoord = locations.getCoord(route.getEnd().getLocationId());
series.add(endCoord.getX(), endCoord.getY());
coll.addSeries(series);
counter++;
}
return coll;
}
private static XYSeriesCollection makeVrpSeries(Collection<Vehicle> vehicles, Collection<Job> services, Map<XYDataItem, String> labels) throws NoLocationFoundException{
XYSeriesCollection coll = new XYSeriesCollection();
XYSeries vehicleSeries = new XYSeries("depot", false, true);
for(Vehicle v : vehicles){
Coordinate coord = v.getCoord();
if(coord == null) throw new NoLocationFoundException();
vehicleSeries.add(coord.getX(),coord.getY());
}
coll.addSeries(vehicleSeries);
XYSeries serviceSeries = new XYSeries("service", false, true);
XYSeries pickupSeries = new XYSeries("pickup", false, true);
XYSeries deliverySeries = new XYSeries("delivery", false, true);
for(Job job : services){
if(job instanceof Pickup){
Pickup service = (Pickup)job;
Coordinate coord = service.getCoord();
XYDataItem dataItem = new XYDataItem(coord.getX(), coord.getY());
pickupSeries.add(dataItem);
labels.put(dataItem, String.valueOf(service.getCapacityDemand()));
}
else if(job instanceof Delivery){
Delivery service = (Delivery)job;
Coordinate coord = service.getCoord();
XYDataItem dataItem = new XYDataItem(coord.getX(), coord.getY());
deliverySeries.add(dataItem);
labels.put(dataItem, String.valueOf(service.getCapacityDemand()));
}
else if(job instanceof Service){
Service service = (Service)job;
Coordinate coord = service.getCoord();
XYDataItem dataItem = new XYDataItem(coord.getX(), coord.getY());
serviceSeries.add(dataItem);
labels.put(dataItem, String.valueOf(service.getCapacityDemand()));
}
else{
throw new IllegalStateException("job instanceof " + job.getClass().toString() + ". this is not supported.");
}
}
if(!serviceSeries.isEmpty()) coll.addSeries(serviceSeries);
if(!pickupSeries.isEmpty()) coll.addSeries(pickupSeries);
if(!deliverySeries.isEmpty()) coll.addSeries(deliverySeries);
return coll;
}
private static XYSeriesCollection makeVrpSeries(Collection<VehicleRoute> routes, Map<XYDataItem, String> labels) throws NoLocationFoundException{
Set<Vehicle> vehicles = new HashSet<Vehicle>();
Set<Job> jobs = new HashSet<Job>();
for(VehicleRoute route : routes){
vehicles.add(route.getVehicle());
jobs.addAll(route.getTourActivities().getJobs());
}
return makeVrpSeries(vehicles, jobs, labels);
}
private static XYSeriesCollection makeVrpSeries(VehicleRoutingProblem vrp, Map<XYDataItem, String> labels) throws NoLocationFoundException{
return makeVrpSeries(vrp.getVehicles(), vrp.getJobs().values(), labels);
}
private static Locations retrieveLocations(VehicleRoutingProblem vrp) throws NoLocationFoundException {
final Map<String, Coordinate> locs = new HashMap<String, Coordinate>();
for(Vehicle v : vrp.getVehicles()){
String locationId = v.getLocationId();
if(locationId == null) throw new NoLocationFoundException();
Coordinate coord = v.getCoord();
if(coord == null) throw new NoLocationFoundException();
locs.put(locationId, coord);
}
for(Job j : vrp.getJobs().values()){
if(j instanceof Service){
String locationId = ((Service) j).getLocationId();
if(locationId == null) throw new NoLocationFoundException();
Coordinate coord = ((Service) j).getCoord();
if(coord == null) throw new NoLocationFoundException();
locs.put(locationId, coord);
}
else{
throw new IllegalStateException("job is not a service. this is not supported yet.");
}
}
return new Locations() {
@Override
public Coordinate getCoord(String id) {
return locs.get(id);
}
};
}
}

View file

@ -0,0 +1,88 @@
/*******************************************************************************
* Copyright (C) 2013 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.analysis.toolbox;
import jsprit.core.problem.solution.VehicleRoutingProblemSolution;
/**
* Printer to print the details of a vehicle-routing-problem solution.
*
* @author stefan schroeder
*
*/
public class SolutionPrinter {
/**
* Enum to indicate verbose-level.
*
* <p> Print.CONCISE and Print.VERBOSE are available.
*
* @author stefan schroeder
*
*/
public enum Print {
CONCISE,VERBOSE
}
/**
* Prints costs and #vehicles to stdout (System.out.println).
*
* @param solution
*/
public static void print(VehicleRoutingProblemSolution solution){
System.out.println("[costs="+solution.getCost() + "]");
System.out.println("[#vehicles="+solution.getRoutes().size() + "]");
}
// /**
// * Prints the details of the solution according to a print-level, i.e. Print.CONCISE or PRINT.VERBOSE.
// *
// * <p>CONCISE prints total-costs and #vehicles.
// * <p>VERBOSE prints the route-details additionally. If the DefaultVehicleRouteCostCalculator (which is the standard-calculator)
// * is used in VehicleRoute, then route-costs are differentiated further between transport, activity, vehicle, driver and other-costs.
// *
// * @param solution
// * @param level
// *
// * @deprecated is not going to work anymore
// */
// @Deprecated
// public static void print(VehicleRoutingProblemSolution solution, Print level){
// if(level.equals(Print.CONCISE)){
// print(solution);
// }
// else{
// print(solution);
// System.out.println("routes");
// int routeCount = 1;
// for(VehicleRoute route : solution.getRoutes()){
// System.out.println("[route="+routeCount+"][departureTime="+route.getStart().getEndTime()+"[total=" + route.getCost() + "]");
// if(route.getVehicleRouteCostCalculator() instanceof DefaultVehicleRouteCostCalculator){
// DefaultVehicleRouteCostCalculator defaultCalc = (DefaultVehicleRouteCostCalculator) route.getVehicleRouteCostCalculator();
// System.out.println("[transport=" + defaultCalc.getTpCosts() + "][activity=" + defaultCalc.getActCosts() +
// "][vehicle=" + defaultCalc.getVehicleCosts() + "][driver=" + defaultCalc.getDriverCosts() + "][other=" + defaultCalc.getOther() + "]");
// }
// routeCount++;
// }
// }
//
//
// }
}

View file

@ -0,0 +1,77 @@
/*******************************************************************************
* Copyright (C) 2013 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.analysis.toolbox;
import java.util.Collection;
import jsprit.core.algorithm.VehicleRoutingAlgorithm;
import jsprit.core.algorithm.listener.AlgorithmEndsListener;
import jsprit.core.algorithm.listener.AlgorithmStartsListener;
import jsprit.core.problem.VehicleRoutingProblem;
import jsprit.core.problem.solution.VehicleRoutingProblemSolution;
import org.apache.log4j.Logger;
public class StopWatch implements AlgorithmStartsListener, AlgorithmEndsListener{
private static Logger log = Logger.getLogger(StopWatch.class);
private double ran;
private double startTime;
@Override
public void informAlgorithmStarts(VehicleRoutingProblem problem, VehicleRoutingAlgorithm algorithm, Collection<VehicleRoutingProblemSolution> solutions) {
reset();
start();
}
public double getCompTimeInSeconds(){
return (ran)/1000.0;
}
@Override
public void informAlgorithmEnds(VehicleRoutingProblem problem, Collection<VehicleRoutingProblemSolution> solutions) {
stop();
log.info("computation time [in sec]: " + getCompTimeInSeconds());
}
public void stop(){
ran += System.currentTimeMillis() - startTime;
}
public void start(){
startTime = System.currentTimeMillis();
}
public void reset(){
startTime = 0;
ran = 0;
}
@Override
public String toString() {
return "stopWatch: " + getCompTimeInSeconds() + " sec";
}
public double getCurrTimeInSeconds() {
return (System.currentTimeMillis()-startTime)/1000.0;
}
}

View file

@ -0,0 +1,25 @@
/*******************************************************************************
* Copyright (C) 2013 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.analysis.util;
import java.util.Collection;
import jsprit.core.util.BenchmarkResult;
public interface BenchmarkWriter {
public void write(Collection<BenchmarkResult> results);
}

View file

@ -0,0 +1,261 @@
/*******************************************************************************
* Copyright (C) 2013 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.analysis.util;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Collection;
import jsprit.core.util.BenchmarkResult;
import org.jfree.chart.renderer.xy.DeviationRenderer;
public class HtmlBenchmarkTableWriter implements BenchmarkWriter{
private String filename;
public HtmlBenchmarkTableWriter(String filename) {
this.filename = filename;
}
@Override
public void write(Collection<BenchmarkResult> results) {
try {
BufferedWriter writer = new BufferedWriter(new FileWriter(new File(filename)));
writer.write(openTable() + newline());
//table head
writer.write(openRow() + newline());
writer.write(head("inst") + newline());
writer.write(head("runs") + newline());
writer.write(head("&Oslash; time [sec]") + newline());
writer.write(head("results",4));
writer.write(head("vehicles",4));
writer.write(head("res*") + newline());
writer.write(head("veh*") + newline());
writer.write(closeRow() + newline());
writer.write(openRow() + newline());
writer.write(head("") + newline());
writer.write(head("") + newline());
writer.write(head("") + newline());
writer.write(head("best") + newline());
writer.write(head("avg") + newline());
writer.write(head("worst") + newline());
writer.write(head("stdev") + newline());
writer.write(head("best") + newline());
writer.write(head("avg") + newline());
writer.write(head("worst") + newline());
writer.write(head("stdev") + newline());
writer.write(head("") + newline());
writer.write(head("") + newline());
writer.write(closeRow() + newline());
//data
double sum_avg_time = 0.0;
double sum_best_result = 0.0;
double sum_avg_result = 0.0;
double sum_worst_result = 0.0;
double sum_dev_result = 0.0;
double sum_best_veh = 0.0;
double sum_avg_veh = 0.0;
double sum_worst_veh = 0.0;
double sum_dev_veh = 0.0;
Integer runs = null;
Double sum_res_star=null;
Double sum_veh_star=null;
for(BenchmarkResult result : results){
if(runs==null) runs=result.runs;
writer.write(openRow() + newline());
writer.write(date(result.instance.name) + newline());
writer.write(date(Integer.valueOf(result.runs).toString()) + newline());
Double avg_time = round(result.getTimesStats().getMean(),2);
writer.write(date(Double.valueOf(avg_time).toString()) + newline());
//bestRes
Double best_result = round(result.getResultStats().getMin(),2);
writer.write(date(Double.valueOf(best_result).toString()) + newline());
//avgRes
Double avg_result = round(result.getResultStats().getMean(),2);
writer.write(date(Double.valueOf(avg_result).toString()) + newline());
//worstRes
Double worst_result = round(result.getResultStats().getMax(),2);
writer.write(date(Double.valueOf(worst_result).toString()) + newline());
//stdevRes
Double std_result = round(result.getResultStats().getStandardDeviation(),2);
writer.write(date(Double.valueOf(std_result).toString()) + newline());
//bestVeh
Double best_vehicle = round(result.getVehicleStats().getMin(),2);
writer.write(date(Double.valueOf(best_vehicle).toString()) + newline());
//avgVeh
Double avg_vehicle = round(result.getVehicleStats().getMean(),2);
writer.write(date(Double.valueOf(avg_vehicle).toString()) + newline());
//worstVeh
Double worst_vehicle = round(result.getVehicleStats().getMax(),2);
writer.write(date(Double.valueOf(worst_vehicle).toString()) + newline());
//stdevVeh
Double std_vehicle = round(result.getVehicleStats().getStandardDeviation(),2);
writer.write(date(Double.valueOf(std_vehicle).toString()) + newline());
//bestKnownRes
writer.write(date("" + result.instance.bestKnownResult + newline()));
//bestKnownVeh
writer.write(date("" + result.instance.bestKnownVehicles + newline()));
writer.write(closeRow() + newline());
sum_avg_time+=avg_time;
sum_best_result+=best_result;
sum_avg_result+=avg_result;
sum_worst_result+=worst_result;
sum_dev_result+=std_result;
sum_best_veh+=best_vehicle;
sum_avg_veh+=avg_vehicle;
sum_worst_veh+=worst_vehicle;
sum_dev_veh+=std_vehicle;
if(result.instance.bestKnownResult != null){
if(sum_res_star==null) sum_res_star=result.instance.bestKnownResult;
else sum_res_star+=result.instance.bestKnownResult;
}
if(result.instance.bestKnownVehicles != null){
if(sum_veh_star==null) sum_veh_star=result.instance.bestKnownVehicles;
else sum_veh_star+=result.instance.bestKnownVehicles;
}
}
writer.write(openRow() + newline());
writer.write(date("&Oslash;") + newline());
writer.write(date(""+runs) + newline());
Double average_time = round(sum_avg_time/(double)results.size(),2);
writer.write(date(Double.valueOf(average_time).toString()) + newline());
//bestRes
writer.write(date(Double.valueOf(round(sum_best_result/(double)results.size(),2)).toString()) + newline());
//avgRes
Double average_result = round(sum_avg_result/(double)results.size(),2);
writer.write(date(Double.valueOf(average_result).toString()) + newline());
//worstRes
writer.write(date(Double.valueOf(round(sum_worst_result/(double)results.size(),2)).toString()) + newline());
//stdevRes
writer.write(date(Double.valueOf(round(sum_dev_result/(double)results.size(),2)).toString()) + newline());
//bestVeh
writer.write(date(Double.valueOf(round(sum_best_veh/(double)results.size(),2)).toString()) + newline());
//avgVeh
Double average_vehicles = round(sum_avg_veh/(double)results.size(),2);
writer.write(date(Double.valueOf(average_vehicles).toString()) + newline());
//worstVeh
writer.write(date(Double.valueOf(round(sum_worst_veh/(double)results.size(),2)).toString()) + newline());
//stdevVeh
writer.write(date(Double.valueOf(round(sum_dev_veh/(double)results.size(),2)).toString()) + newline());
//bestKnownRes
Double delta_res = null;
if(sum_res_star != null){
writer.write(date(Double.valueOf(round(sum_res_star.doubleValue()/(double)results.size(),2)).toString()) + newline());
delta_res = (sum_avg_result/sum_res_star - 1)*100;
}
else writer.write(date("null") + newline());
//bestKnownVeh
Double delta_veh = null;
if(sum_veh_star != null){
writer.write(date(Double.valueOf(round(sum_veh_star.doubleValue()/(double)results.size(),2)).toString()) + newline());
delta_veh = (sum_avg_veh - sum_veh_star)/(double)results.size();
}
else writer.write(date("null") + newline());
writer.write(closeRow() + newline());
writer.write(closeTable() + newline());
writer.write("avg. percentage deviation to best-known result: " + round(delta_res,2) + newline() + newline());
writer.write("avg. absolute deviation to best-known vehicles: " + round(delta_veh,2) + newline());
writer.write(openTable() + newline());
writer.write(openRow() + newline());
writer.write(date("") + newline());
writer.write(date("") + newline());
writer.write(date("") + newline());
writer.write(date("") + newline());
writer.write(date(Double.valueOf(average_time).toString(),"align=\"right\"") + newline());
writer.write(date(Double.valueOf(average_result).toString(),"align=\"right\"") + newline());
writer.write(date(Double.valueOf(average_vehicles).toString(),"align=\"right\"") + newline());
if(delta_res != null){
writer.write(date(Double.valueOf(round(delta_res,2)).toString(),"align=\"right\"") + newline());
}else writer.write(date("n.a.") + newline());
if(delta_veh != null){
writer.write(date(Double.valueOf(round(delta_veh,2)).toString(),"align=\"right\"") + newline());
}else writer.write(date("n.a.") + newline());
writer.write(closeRow() + newline());
writer.write(closeTable() + newline());
writer.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private String head(String string, int i) {
return "<th colspan=\""+i+"\">"+string+"</th>";
}
private Double round(Double value, int i) {
if(value==null) return null;
long roundedVal = Math.round(value*Math.pow(10, i));
return (double)roundedVal/(double)(Math.pow(10, i));
}
private String head(String head) {
return "<th>"+head+"</th>";
}
private String closeTable() {
return "</table>";
}
private String openTable() {
return "<table>";
}
private String closeRow() {
return "</tr>";
}
private String date(String date) {
return "<td>"+date+"</td>";
}
private String date(String date, String metaData) {
return "<td " + metaData + ">"+date+"</td>";
}
private String newline() {
return "\n";
}
private String openRow() {
return "<tr>";
}
}